ANTLR语法错误意外令牌:加 [英] ANTLR syntax error unexpected token: plus
问题描述
我的ANTLR树语法有一个小问题.我正在使用ANTLRWorks 1.4.在解析器语法中,我有如下规则:
Hi I have a small problem in my ANTLR tree grammar. I am using ANTLRWorks 1.4. In parser grammar I have the rule like this:
declaration
: 'variable' IDENTIFIER ( ',' IDENTIFIER)* ':' TYPE ';'
-> ^('variable' IDENTIFIER TYPE)+
所以我希望每个IDENTIFIER都有一棵树.
So I wanted one tree per each IDENTIFIER.
在树语法中,我只保留了重写规则:
And in the tree grammar I left only rewrite rules:
declaration
: ^('variable' IDENTIFIER TYPE)+
但是当我检查语法时,出现语法错误意外的标记+.它是树语法中声明规则末尾的+号.那我做错了吗?
But when I check grammar I got syntax error unexpected token +. And it is this + sign at the end of the declaration rule in the tree grammar. So what I am doing wrong?
解析器语法可以正常工作,并且可以按预期构建AST树.我为C#生成了词法分析器和解析器,并对其进行了一些输入测试.
Parser grammar works fine and builds AST tree as expected. I generated lexer and parser for C# and test it for some input.
推荐答案
解析源代码时:
variable a, b, c : int;
您正在尝试构建如下所示的AST:
you're trying to construct an AST that looks like:
variable variable variable
/ | \
a b c
/ | \
int int int
但是,由于'variable'
和TYPE
始终是相同的标记,因此我认为无需创建所有这些重复的节点.为什么不这样做:
But since 'variable'
and TYPE
are always the same token, I see no need to create all those duplicate nodes. Why not just do:
declaration
: 'variable' IDENTIFIER ( ',' IDENTIFIER)* ':' TYPE ';'
-> ^('variable' TYPE IDENTIFIER+)
;
这将创建类似AST的
variable
/ | | \
int a b c
?
这篇关于ANTLR语法错误意外令牌:加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!