Allow AST optimization based on external Scope.

This commit is contained in:
Stephen Chung
2020-03-14 14:30:44 +08:00
parent 9844ae8665
commit b3a22d942a
6 changed files with 222 additions and 55 deletions

View File

@@ -1,5 +1,6 @@
use crate::engine::KEYWORD_DUMP_AST;
use crate::parser::{Expr, Stmt};
use crate::scope::{Scope, ScopeEntry, VariableType};
struct State {
changed: bool,
@@ -330,13 +331,27 @@ fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
}
}
pub(crate) fn optimize(statements: Vec<Stmt>) -> Vec<Stmt> {
pub(crate) fn optimize(statements: Vec<Stmt>, scope: &Scope) -> Vec<Stmt> {
let mut result = statements;
loop {
let mut state = State::new();
let num_statements = result.len();
scope
.iter()
.filter(|ScopeEntry { var_type, expr, .. }| {
// Get all the constants with definite constant expressions
*var_type == VariableType::Constant
&& expr.as_ref().map(|e| e.is_constant()).unwrap_or(false)
})
.for_each(|ScopeEntry { name, expr, .. }| {
state.push_constant(
name.as_ref(),
expr.as_ref().expect("should be Some(expr)").clone(),
)
});
result = result
.into_iter()
.enumerate()