Cymbol.g4来自“权威的ANTLR 4参考”。我编译并用文件t.cymbol对其进行测试。我认为应该在第2行中报告意外字符's'的错误。但是结果是该行之后的所有内容都将被忽略,而不会出现任何错误消息。 谢谢!
grun Cymbol file -trace t.cymbol
enter file, LT(1)=int
enter varDecl, LT(1)=int
enter type, LT(1)=int
consume [@0,14:16='int',<4>,2:0] rule type
exit type, LT(1)=g
consume [@1,18:18='g',<23>,2:4] rule varDecl
consume [@2,19:19='=',<1>,2:5] rule varDecl
enter expr, LT(1)=9
consume [@3,20:20='9',<24>,2:6] rule expr
exit expr, LT(1)=;
consume [@4,21:21=';',<2>,2:7] rule varDecl
exit varDecl, LT(1)=s
exit file, LT(1)=s
解析器在包含“ s”时退出。解析器为什么不使用此令牌并重新同步?
Cymbol.g4
grammar Cymbol;
file: (functionDecl | varDecl)+ ;
varDecl: type ID ('=' expr)? ';' ;
type: 'float' | 'int' | 'void' ;
functionDecl: type ID '(' formalParameters? ')' block;
formalParameters: formalParameter (',' formalParameter)*;
formalParameter: type ID;
block: '{' stat* '}';
stat: block
| varDecl
| 'if' expr 'then' stat ('else' stat)?
| 'return' expr? ';'
| expr '=' expr ';'
| expr ';'
;
expr: ID '(' exprList? ')' #Call
| expr '[' expr ']' #Index
| '-' expr #Negate
| '!' expr #Not
| expr ('*'|'/') expr #MultDiv
| expr ('+'|'-') expr #AddSub
| expr '==' expr #Equal
| ID #Var
| INT #Int
| FLOAT #Float
| '(' expr ')' #Parens
;
exprList: expr (',' expr)* ;
ID: (LETTER|'_') (LETTER|DIGITAL|'_')* ;
fragment LETTER: [a-zA-Z];
fragment DIGITAL: [0-9];
INT: DIGITAL+;
FLOAT: DIGITAL+ '.' DIGITAL*
| '.' DIGITAL+ ;
WS: [ \t\r\n]+ ->skip;
LINE_COMMENT: '//' .*? '\n' -> skip;
COMMENT: '/*' .*? '*/' ->skip;
t.cymbol
//Cymbol test
int g=9; s
float h=1.2;
int fact(int x)
{
int z=4;
if x==0 then return 1;
return x * factor(x-1);
}