我到处找遍了,找不到解决办法。我是ANTLR的新手,对于一个赋值,当我的解析器遇到一个带有行号和标记的未知令牌时,我需要打印一个错误消息(使用下面类似的语法)。antlr4文档表示,行是令牌对象的属性,它提供“令牌发生的行号,从1计数;转换为对getLine的调用。例如:$ID.line”。
我试图在以下代码块中实现这一点:
not_valid : not_digit { System.out.println("Line " + $not_digit.line + " Contains Unrecognized Token " $not_digit.text)};
not_digit : ~( DIGIT );但我一直搞错了
unknown attribute line for rule not_digit in $not_digit.line
我的第一个想法是,我要将lexer令牌的属性应用到解析器规则中,因为文档将令牌和规则属性拆分为两个不同的表。因此,我将代码更改为:
not_valid : NOT_DIGIT { System.out.println("Line " + $NOT_DIGIT.line + " Contains Unrecognized Token " $NOT_DIGIT.text)};
NOT_DIGIT : ~ ( DIGIT ) ;而且还
not_valid : NOT_DIGIT { System.out.println("Line " + $NOT_DIGIT.line + " Contains Unrecognized Token " $NOT_DIGIT.text)};
NOT_DIGIT : ~DIGIT ;就像文档中的例子,但是两次我都得到了错误
rule reference DIGIT is not currently supported in a set
我不知道我错过了什么。我所有的搜索都显示了如何在解析器之外的Java中实现这一点,但我需要在解析器中处理操作代码(我认为这就是它的名称)。
发布于 2020-09-24 18:47:39
像{ ... }这样的块称为动作。在其中嵌入特定的目标代码。因此,如果您正在使用Java,那么您需要在{和}之间编写Java
一个简单的演示:
grammar T;
parse
: not_valid EOF
;
not_valid
: r=not_digit
{
System.out.printf("line=%s, charPositionInLine=%s, text=%s\n",
$r.start.getLine(),
$r.start.getCharPositionInLine(),
$r.start.getText()
);
}
;
not_digit
: ~DIGIT
;
DIGIT
: [0-9]
;
OTHER
: ~[0-9]
;用代码测试它:
String source = "a";
TLexer lexer = new TLexer(CharStreams.fromString(source));
TParser parser = new TParser(new CommonTokenStream(lexer));
parser.parse();它将打印:
line=1, charPositionInLine=0, text=ahttps://stackoverflow.com/questions/64049896
复制相似问题