ANTLR4:无关输入错误 [英] ANTLR4: Extraneous Input error

查看:110
本文介绍了ANTLR4:无关输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《权威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规则:

prog: kword+
  | stat+ 
  ;

此规则声明该程序由一个或多个kword规则一个或多个stat规则组成.没有同时包含kwordstat的程序.您可能想写的是以下内容,它允许kwordstat规则的任何序列.请注意,我将+更改为*以允许使用空程序.即使您的编译器不应允许该程序为空,该错误也最好留给访问者或听众进行验证.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆