简体   繁体   中英

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. 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 . 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.

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). A surprise is the c:FOO part. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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