antlr - ANTLR 中复杂的 AST 重写规则

标签 antlr antlrworks

AST rewrite rule with " * +" in antlr 出现关于使用 devide group 技术的 AST 重写规则的问题之后。

我在 ANTLR 中生成 AST 时再次遇到问题:)。这是我的 antlr 代码:

start   :   noun1+=n (prep noun2+=n (COMMA noun3+=n)*)*
        ->  ^(NOUN $noun1) (^(PREP prep) ^(NOUN $noun2) ^(NOUN $noun3)*)*
    ;
n       :    'noun1'|'noun2'|'noun3'|'noun4'|'noun5';
prep    :    'and'|'in';
COMMA   :     ',';

现在,输入:“名词1和名词2,名词3在名词4,名词5中”,我得到了以下意想不到的AST:

enter image description here

与 ANLRwork 中的“解析树”比较:

enter image description here

我认为 $noun3 变量保存了“COMMA noun3+=n”中所有“n”的列表。因此,AST 解析器 ^(NOUN $noun3)* 将绘制所有“n”,而不分离哪个“n”实际上属于“prep”。

有什么方法可以在“(^(PREP prep) ^(NOUN $noun2) ^(NOUN $noun3))中进行分离>。我想要做的就是 AST 必须在 ANTLRwork 中使用“解析树”准确绘制,无需标记逗号。

感谢您的帮助!

最佳答案

如果打破 start 规则,获得您想要的分离是最容易的。下面是一个示例(未将 COMMA 写入 AST):

start   :   prepphrase             //one prepphrase is required.
            (COMMA! prepphrase)*   //"COMMA!" means "match a COMMA but don't write it to the AST"
        ;

prepphrase: noun1=n                //You can use "noun1=n" instead of "noun1+=n" when you're only using it to store one value
            (prep noun2=n)? 
            -> ^(NOUN $noun1) ^(PREP prep)? ^(NOUN $noun2)?
        ;

prepphrase 是一个名词,后面可以跟另一个名词的介词。 start 规则查找以逗号分隔的 prepphrase

输出看起来像解析 TreeMap 像,但没有逗号。


如果您更喜欢使用 -> 显式写出 AST,或者如果您不喜欢 COMMA! 这样的语法,您可以编写 start 改为这样规则。这两种不同的形式在功能上是等效的。

start   :   prepphrase             //one prepphrase is required.
            (COMMA prepphrase)*
            -> prepphrase+         //write each prepphrase, which doesn't include commas
        ;

关于antlr - ANTLR 中复杂的 AST 重写规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13976717/

相关文章:

antlr - 将小写字母与 ANTLR 匹配

ANTLRWorks 1.4.3 不显示某些字符,例如竖线和左括号

java - (CommonTree)parser.javaSource() 行中的 antlr 错误

parsing - 类香料语言识别器的语法

ant - ANTLR 项目的 build.xml 示例?

debugging - ANTLRWorks调试——不同颜色的含义?

antlr - 如何解决 Antlr3 中的解析歧义

parsing - ANTLR 解析树修改

ANTLR - 允许不完整的语法

python - 找不到 antlr-python-runtime 的匹配分布