【发布时间】:2012-11-22 22:39:49
【问题描述】:
问题
Entry
: temp += (Expression | Declaration | UserType)*
;
Declaration
: Type '*' name=ID ';'
;
Expression
: temp1 = Primary ('*' temp2 += Primary)* ';'
;
Primary
: temp1 = INT
| temp2 = [Declaration]
;
Type
: temp1 = SimpleType
| temp2 = [UserType]
;
SimpleType
: 'int' | 'long'
;
UserType
: 'typedef' name=ID ';'
;
规则 Declaration 和 Expression 不明确,因为这两个规则共享完全相同的语法,并且出现问题是因为交叉引用 [Declaration] 和 [UserType] 都基于终端规则 ID .
因此为上述语法生成代码将引发 ANTLR 警告:
Decision can match input such as "RULE_ID '*' RULE_ID ';'"
using multiple alternatives: 1, 2
目标
我希望选择能够首先解决交叉引用的规则。
假设如下:
typedef x;
int* x;
int* b;
AST 的
x*b
应该看起来像:
x = Entry -> Expression -> Primary (temp1) -> [Declaration] -> Stop!
* = Entry -> Expression -> Primary '*' -> Stop!
b = Entry -> Expression -> Primary (temp2) -> [Declaration] -> Stop!
因此
Entry -> Declaration
永远不应该考虑,因为
Entry -> Expression -> [Declaration]
已经可以验证交叉引用[Declaration]。
问题
因为我们在 Xtext 中没有语义谓词(或者我错了吗?),有没有办法验证交叉引用并根据该验证明确选择该规则?
PS:有些人可能已经知道,这个问题源于我试图用 Xtext 实现的 C 语言。
【问题讨论】:
标签: c grammar semantics predicate xtext