从这个语法开始:https ://stackoverflow.com/a/14287002/1082002我会实现一个简单的语法,它接受和评估这样的简单语言:
{
if a==c {
a
if a==b {
b
} else {
c
}
}
}
所以,如果a==c
,它执行a
并评估if a==b
,如果它是真的,它执行b
否则c
。真的很简单。
解析器语法和树语法是这些:
TreeEvaluator.g(组合语法生成 AST)
grammar TreeEvaluator;
options {
output = AST;
}
tokens {
CONDBLOCK;
CODEBLOCK;
DEFAULT;
}
compilationUnit : block EOF -> block;
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 instruction* RCUR -> ^(CODEBLOCK instruction*);
instruction : ID | condition;
IF : 'if';
ELIF: 'elif';
ELSE: 'else';
LCUR: '{';
RCUR: '}';
EQ : '==';
ID : ('a'..'z'|'A'..'Z')+;
WS : (' '|'\t'|'\f'|'\r'|'\n')+ {skip();};
AstTreeEvaluatorParser.g(树解析器)
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 : block+;
block : ^(CODEBLOCK instruction*);
instruction : ifStat | ID;
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
;
exp returns [boolean value]
: ^(EQ lhs=ID rhs=ID)
{$value = vars.get($lhs.getText()) == vars.get($rhs.getText());}
;
问题是为预测规则而生成的 DFA evalblock
,该 DFA 有一个SpecialStateTransition()
引用参数的方法eval
(如规则中指定的那样),但在生成的 Java 类中,该参数不可见。
我不明白为什么,以及是否有办法避免这个问题。