【问题标题】:complex AST rewrite rule in ANTLRANTLR 中复杂的 AST 重写规则
【发布时间】:2012-12-20 16:43:36
【问题描述】:

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   :     ',';

现在,输入:“noun1 and noun2, noun3 in noun4, noun5”,我得到了以下意想不到的 AST:

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

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

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

感谢您的帮助!

【问题讨论】:

    标签: antlr antlrworks


    【解决方案1】:

    如果打破start 规则,最容易获得所需的分离。这是一个示例(没有将COMMAs 写入 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 规则查找以逗号分隔的 prepphrases。

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


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

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

    【讨论】:

    • 非常感谢!这真的很治愈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多