caret prefix instead of postfix in antlr

前端 未结 1 798
说谎
说谎 2021-01-13 01:53

I know what the caret postfix means in antlr(ie. make root) but what about when the caret is the prefix as in the following grammar I have been reading(this grammar is brand

相关标签:
1条回答
  • 2021-01-13 02:34

    The ^ is used as an inline tree operator, indicating a certain token should become the root of the tree.

    For example, the rule:

    p : A B^ C;
    

    creates the following AST:

      B
     / \
    A   C
    

    There's another way to create an AST which is using a rewrite rule. A rewrite rule is placed after (or at the right of) an alternative of a parser rule. You start a rewrite rule with an "arrow", ->, followed by the rules/tokens you want to be in the AST.

    Take the previous rule:

    p : A B C;
    

    and you want to reverse the tokens, but keep the ASST "flat" (no root node). THis can be done using the following rewrite rule:

    p : A B C -> C B A;
    

    And if you want to create an AST similar to p : A B^ C;, you start your rewrite rule with ^( ... ) where the first token/rule inside the parenthesis will become the root node. So the rule:

    p : A B C -> ^(B A C);
    

    produces the same AST as p : A B^ C;.


    Related:

    • Tree construction
    • How to output the AST built using ANTLR?
    0 讨论(0)
提交回复
热议问题