简体   繁体   English

将AST动作翻译重写为ANTLR4

[英]rewriting AST Action Translation to ANTLR4

I have a grammar file written in antlr2 syntax and need help understanding how to rewrite some of the parser rules in antlr4 syntax. 我有一个用antlr2语法编写的语法文件,需要帮助来了解如何用antlr4语法重写一些解析器规则。 I know antlr4 eliminated the need for building AST so I'm not sure what to do with the rules that are AST action translations . 我知道antlr4消除了构建AST的需要,因此我不确定该如何处理AST操作转换的规则。 ANTLR Tree Construction explains some of the syntax and how to use the # construct but I'm still unsure how to read this rules and re-write them. ANTLR树构造解释了一些语法以及如何使用#构造,但是我仍然不确定如何阅读此规则并重新编写它们。

temp_root :   
    temp { #temp_root = #([ROOT, "root"], #temp_root); } EOF;

temp :
    c:temp_content 
        { #temp = #(#([FUNCTION_CALL, "template"], #template), c);
          reparent((MyAST)#temp, MyAST)#c); };

temp_content :
    (foo | bar);

foo :     
     {
         StringBuilder result = new StringBuilder("");
     }
    :   (c:FOO! { result.append(c.getText()); } )+
    { #foo = #([TEMPLATE_STRING_LITERAL, result.toString()], #foo); };

bar :
    BEGIN_BAR! expr END_BAR!
    exception 
        catch [Exception x] {
            bar_AST = handleException(x);
        };

You cannot manipulate the produced parse tree (at least not with grammar code), so simply remove all tree rewriting stuff (you may have to adjust consumer code, if that relies on a specific tree structure). 您无法操作产生的解析树(至少不能使用语法代码),因此只需删除所有树重写内容(如果依赖特定的树结构,则可能需要调整使用者代码)。 Also remove the exclamation marks (which denote a token that should not appear in the AST). 同时删除感叹号(表示不应该出现在AST中的令牌)。 A surprise is the c:FOO part. 令人惊讶的是c:FOO部分。 Can't remember having ever seen this. 不记得曾经见过这个。 but judging from the following action code I guess it's a var assignment and should be rewritten as c = FOO . 但是从下面的动作代码来看,我猜这是一个var赋值,应该重写为c = FOO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM