ANTLR4:无关输入错误 [英] ANTLR4: Extraneous Input error
问题描述
我正在关注权威 ANTLR4 参考"一书,并决定在他们的计算器语法中添加几个关键字以帮助清理记忆.构建语法并编译生成的 Java 代码工作正常,但是当我执行访问者代码时,我收到错误:"line 6:0 extraneous input '$rem' expecting {<EOF>, '(',ID, INT, NEWLINE}"
和第 8:0 行的 '$clearmem'
相同.
I'm following the "Definitive ANTLR4 Reference" book, and decided to add a couple of keywords to their calculator grammar to help clear memory. Building the grammar and compiling the resulting java code works fine, but when I execute the visitor code, I get the error: "line 6:0 extraneous input '$rem' expecting {<EOF>, '(', ID, INT, NEWLINE}"
and the same for '$clearmem'
on line 8:0.
这是我的语法文件:
grammar LabeledExpr;
//Parser rules=================================
prog: kword+
| stat+
;
stat: expr endl # printExpr
| ID '=' expr endl # assign
| NEWLINE # blank
;
expr: expr op=('*'|'/') expr # MulDiv
| expr op=('+'|'-') expr # AddSub
| INT # int
| ID # id
| '(' expr ')' # parens
;
kword: '$clearmem' endl #clearMem
| '$rem' ID endl #remVar
;
endl: NEWLINE
| EOF
;
//Lexer rules==================================
ID: [a-zA-Z]+ ;
INT: [0-9]+ ;
NEWLINE: '\r'? '\n' ;
WS: [ \t]+ -> skip;
MUL: '*' ;
DIV: '/' ;
ADD: '+' ;
SUB: '-' ;
以及带有要解析代码的 .expr 文件:
And the .expr file with the code to parse:
193
a = 5
b = 6
a
b
$rem a
a
$clearmem
我昨晚刚开始使用 ANTLR4,所以我真的不知道在错误方面要查找什么,但是从我可以看出的两个文件都没有问题.
I just started on ANTLR4 last night so I really don't know much of what to look for error-wise, but from what I can tell nothing is wrong with either file.
我确定我遗漏了一些非常简单的东西,但我可以找到它,所以我很感激任何更熟悉 ANTLR4 的人的帮助.
I'm sure that I am missing something pretty simple, but I can find it, so I would appreciate help from anyone who is more familiar with ANTLR4.
谢谢.
推荐答案
问题在于你的 prog
规则:
The problem is your prog
rule:
prog: kword+
| stat+
;
此规则声明程序由一个或多个kword
规则或一个或多个stat
规则组成.没有程序同时包含 kword
和 stat
.您可能打算编写以下内容,它允许任何 kword
或 stat
规则序列.请注意,我将 +
更改为 *
以允许空程序.即使您的编译器不应该允许程序为空,也最好将此错误留给访问者或侦听器进行验证.
This rule states that the program consists of one or more kword
rules or one or more stat
rules. There is no program that includes both a kword
and stat
. What you probably meant to write is the following, which allows any sequence of kword
or stat
rules. Note that I changed +
to *
to allow an empty program. Even if your compiler shouldn't allow the program to be empty, this error is better left for validation in a visitor or listener.
prog
: ( kword
| stat
)*
;
这篇关于ANTLR4:无关输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!