问题
I'm building a tree walker for an homogeneus AST (all nodes have same class), what's the correct way to evaluate an if statement?
My AST for if are like this:
I would something that when parses an IF
block, evaluates sequentially his CONDBLOCK
children and if one of them is true, the tree walker doesn't evaluate the remaining.
More clearly, my tree walker is something like:
ifStat : ^(IF { jump=false; } condition* defcond?)
condition : { if (jump) return retval; } ^(CONDBLOCK exp block) { jump=$exp.value; }
defcond : ^(DEFAULT block)
My question is, if in the example $op=+
so the first CONDBLOCK
must be executed, I don't want evaluate anything else, I want execute the first CODEBLOCK
and go up in my AST tree to evaluate the block after if
.
Now I've implemented that with a flag and a check in condition
rule that returns if the flag was true (that means another block is already been executed).
But return retval;
completely stops the execution, I want just go up without evaluate remaining conditions. How can I do that?
回答1:
Any kind of runtime evaluation from an AST that involves branching or jumps is probably going to get ugly. You may want to consider converting the AST into a series of more conventional operations and execute them in sequence. It's an extra step, but it will get you out of jams like this one and I think it's easier to verify and to debug than an AST evaluator.
With that out of the way, here is a way to skip evaluating subsequent condition
and defcond
rules. I'm sticking with the structure that you have, which means that evaluations have two distinct phases: a matching phase (exp
) and an execution phase (block
). This is only worth noting because the phases are handled in different parts of a subgraph and there is no natural means of jumping around, so they need to be tracked across the whole if
statement.
Here's a simple class to manage tracking a single if
evaluation:
class Evaluation {
boolean matched = false;
boolean done = false;
}
When matched
is true and done
is false, the next block
gets executed. After execution, done
is set to true. When matched
and done
are both true, no more block
s get executed for the remainder of the if
statement.
Here are the tree parser rules to handle this:
ifStat
@init { Evaluation eval = new Evaluation(); }
: ^(IF condition[eval]* defcond[eval]?)
;
condition [Evaluation eval]
: ^(CONDBLOCK exp {if ($exp.value) eval.matched = true;} evalblock[eval])
;
defcond [Evaluation eval]
: ^(DEFAULT {eval.matched = true;} evalblock[eval]) //force a match
;
evalblock [Evaluation eval]
: {eval.matched && !eval.done}? //Only do this when a condition is matched but not yet executed
block //call the execution code
{eval.done = true;} //evaluation is complete.
| ^(CODEBLOCK .*) //read the code subgraph (nothing gets executed)
;
Here are the grammars and the code I used to test this:
TreeEvaluator.g (combined grammar to produce an AST)
grammar TreeEvaluator;
options {
output = AST;
}
tokens {
CONDBLOCK;
CODEBLOCK;
DEFAULT;
}
compilationUnit : condition+ EOF;
condition : cif elif* celse? -> ^(IF cif elif* celse?);
cif : IF expr block -> ^(CONDBLOCK expr block);
elif : ELIF expr block -> ^(CONDBLOCK expr block);
celse : ELSE block -> ^(DEFAULT block);
expr : ID EQ^ ID;
block : LCUR ID RCUR -> ^(CODEBLOCK ID);
IF : 'if';
ELIF: 'elif';
ELSE: 'else';
LCUR: '{';
RCUR: '}';
EQ : '==';
ID : ('a'..'z'|'A'..'Z')+;
WS : (' '|'\t'|'\f'|'\r'|'\n')+ {skip();};
AstTreeEvaluatorParser.g (tree parser)
tree grammar AstTreeEvaluatorParser;
options {
output = AST;
tokenVocab = TreeEvaluator;
ASTLabelType = CommonTree;
}
@members {
private static final class Evaluation {
boolean matched = false;
boolean done = false;
}
private java.util.HashMap<String, Integer> vars = new java.util.HashMap<String, Integer>();
public void addVar(String name, int value){
vars.put(name, value);
}
}
compilationUnit : ifStat+;
ifStat
@init { Evaluation eval = new Evaluation(); }
: ^(IF condition[eval]* defcond[eval]?)
;
condition [Evaluation eval]
: ^(CONDBLOCK exp {if ($exp.value) eval.matched = true;} evalblock[eval])
;
defcond [Evaluation eval]
: ^(DEFAULT {eval.matched = true;} evalblock[eval]) //force a match
;
evalblock [Evaluation eval]
: {eval.matched && !eval.done}? //Only do this when a condition is matched but not finished
block //call the execution code
{eval.done = true;} //evaluation is complete.
| ^(CODEBLOCK .*) //read the code node and continue without executing
;
block : ^(CODEBLOCK ID) {System.out.println("Executed " + $ID.getText());};
exp returns [boolean value]
: ^(EQ lhs=ID rhs=ID)
{$value = vars.get($lhs.getText()) == vars.get($rhs.getText());}
;
TreeEvaluatorTest.java (test code)
public class TreeEvaluatorTest {
public static void main(String[] args) throws Exception {
CharStream input = new ANTLRStringStream("if a == b {b} elif a == c {c} elif a == d {d} else {e}");
TreeEvaluatorLexer lexer = new TreeEvaluatorLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
TreeEvaluatorParser parser = new TreeEvaluatorParser(tokens);
TreeEvaluatorParser.compilationUnit_return result = parser.compilationUnit();
if (lexer.getNumberOfSyntaxErrors() > 0 || parser.getNumberOfSyntaxErrors() > 0){
throw new Exception("Syntax Errors encountered!");
}
AstTreeEvaluatorParser tparser = new AstTreeEvaluatorParser(new CommonTreeNodeStream(result.getTree()));
tparser.addVar("a", 0);
tparser.addVar("b", 2);
tparser.addVar("c", 3);
tparser.addVar("d", 4);
AstTreeEvaluatorParser.compilationUnit_return tresult = tparser.compilationUnit();
}
}
The test code evaluates if a == b {b} elif a == c {c} elif a == d {d} else {e}
. The id between the {}
s is printed if it is evaluated. So if a == b
is true, then "Executed b"
will be printed.
Variable values are assigned by calling tparser.addVar(...)
. In this case, a
doesn't equal any other variable, so block {e}
is evaluated.
来源:https://stackoverflow.com/questions/14282143/evaluate-if-subtree-in-homogeneus-ast