1

I want to know how can I define, in a grammar file, that a Node of an AST has "two parents". 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).

    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.

user2144555
  • 1,315
  • 11
  • 34
  • 55

1 Answers1

1

AFAIK, there is no convenient API for that. You will have to manually copy the AST, and then insert it in your rewrite rule:

@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)})
 ;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288