我现在正在使用基于 this grammar file 的 Antlr 3 编写 C# 语法.
但是,我发现了一些我无法理解的定义。
NUMBER:
Decimal_digits INTEGER_TYPE_SUFFIX? ;
// For the rare case where 0.ToString() etc is used.
GooBall
@after
{
CommonToken int_literal = new CommonToken(NUMBER, $dil.text);
CommonToken dot = new CommonToken(DOT, ".");
CommonToken iden = new CommonToken(IDENTIFIER, $s.text);
Emit(int_literal);
Emit(dot);
Emit(iden);
Console.Error.WriteLine("\tFound GooBall {0}", $text);
}
:
dil = Decimal_integer_literal d = '.' s=GooBallIdentifier
;
fragment GooBallIdentifier
: IdentifierStart IdentifierPart* ;
以上片段包含“GooBall”的定义。 我对这个定义有一些疑问。
为什么需要 GooBall? 为什么此语法定义词法分析器规则来解析“0.ToString()”而不是解析器规则?
最佳答案
这是因为这是一个不被任何其他规则处理的有效表达式 - 我猜你会称它为匿名对象之类的东西,因为没有更好的术语。类似于“hello world”.ToUpper()。通常,方法调用仅对变量标识符或返回值 ala GetThing().Method() 有效,否则为空。
关于使用 ANTLR 3 的 C# 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833487/