简体   繁体   English

ANTLR-链接AST的节点

[英]ANTLR - Linking nodes of an AST

I want to know how can I define, in a grammar file, that a Node of an AST has "two parents ". 我想知道如何在语法文件中定义AST的节点具有“两个父对象 ”。 If for example, the node 'D' of the first tree is also child of the node 'A', what syntax should I use so that node 'D' not appear repeated (I want something like the second tree). 例如,如果第一棵树的节点“ D”也是节点“ A”的子节点,则应使用哪种语法,以使节点“ D”不会重复出现(我想要第二棵树之类的东西)。

    A
    |
    |
|-------|
B       C
        |
        D

       A
      / \
     /   |
 |----|  |
 B     C |
       \ |
        D

If I use something like: 如果我使用类似:

A B C D -> ^(A B ^(C D) D)

Node 'D' will appear repeated. 节点“ D”将重复出现。

AFAIK, there is no convenient API for that. AFAIK,没有方便的API。 You will have to manually copy the AST, and then insert it in your rewrite rule: 您将必须手动复制AST,然后将其插入重写规则中:

@parser::members {
  CommonTree copy(CommonTree original) {
    // http://stackoverflow.com/questions/6781019/antlr-duplicate-a-tree
    return copyOfOriginal;
  }
}

rule
 : a b c d -> ^(a b ^(c d) {copy($d.tree)})
 ;

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

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