从这个语法开始:
https://stackoverflow.com/a/14287002/1082002我会实现一个接受和评估简单语言的简单语法,如下所示:
{
if a==c {
a
if a==b {
b
} else {
c
}
}
}
所以,如果a == c,它执行a并计算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());}
;
问题是为预测规则evalblock而生成的DFA,此DFA有一个方法SpecialStateTransition(),它引用参数eval(在规则中指定),但在生成的Java类中,该参数不可见.
我不明白为什么,如果有办法避免这个问题.
最佳答案 你有一个语义谓词(syntax {…}?),它包含对一个由一个动作改变的值的引用(syntax {…}).在您的情况下,值是Evaluation.matched和Evaluation.done字段.
你应该完全避免这种情况 – 永远不要包含依赖于执行动作的谓词.相反,通过将操作代码包装在if(eval.matched&&!eval.done)中来检查操作中的这些值{…}
¹有些人用这种方式编写语法,但我严格避免使用它,因为你可能会遇到问题,而其他问题甚至更糟.