我有以下语法:
grammar lab02;
@header{
package laboratorios.lab02;
}
word : [a-z]+ ;
op_plus : '+' ;
op_min : '-' ;
op_mul : '*' ;
op_div : '/' ;
WS : [ \t\r\n]+ -> skip ;
digit : ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9') ;
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误说: error(50): lab02.g4:7:10: syntax error: 'a-z' came as a complete surprise to me while matching alternative.
我从一个例子中复制了它,但它在我的电脑上不起作用。看看数字规则:digit : ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9') ;它是这样的,因为这是它不会报告错误的唯一方法。如果我使用 [0-9]+ 我得到:
error(50): lab02.g4:7:10: syntax error: '0-9' came as a complete surprise to me while matching alternative
Run Code Online (Sandbox Code Playgroud)
你知道为什么这不起作用吗?
在 ANTLR 中,以小写字母开头的规则是解析器规则,而以大写字母开头的规则是词法分析器规则。
您试图在此处定义词法分析器规则,因此您必须以大写字母开头。
WORD : [a-z]+ ;
OP_plus : '+' ;
OP_min : '-' ;
OP_mul : '*' ;
OP_div : '/' ;
WS : [ \t\r\n]+ -> skip ;
DIGIT : [0-9] ;
Run Code Online (Sandbox Code Playgroud)
您的规则digit: ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9');实际上对解析器规则有效,这就是它编译的原因,但它会隐式地为每个数字创建一种令牌类型,这并不好。
| 归档时间: |
|
| 查看次数: |
1896 次 |
| 最近记录: |