title: Collapsing some AST subtrees in Antlr using rewrite rules
body: <p>I have the following grammar (i'm showing only the important sectons)</p>
  
  <pre><code>packageDeclaration
      :   PACKAGE qualifiedIdentifier SEMI -&gt; ^(PACKAGE qualifiedIdentifier+) 
      ;
  
  qualifiedIdentifier
      :   (   IDENT               -&gt;  IDENT
          )
          (   DOT ident=IDENT     -&gt;  ^(DOT $qualifiedIdentifier $ident)
          )*
      ;
  </code></pre>
  
  <p>and let's say i have a package decleration of "package a.b.c" (Java parser btw)</p>
  
  <p>What i get now is something of the form
  (package (. (. a b) c))</p>
  
  <p>what i want is to inline the package so that i get
  (package a.b.c)</p>
  
  <p>I would prefer not to change the rewriting for the qualifiedIdentifier, but only for the packageDeclaration.</p>
  
  <p>How can i do this.</p>
  
  <p>I understand what you mean by alias and + now.  But i'm still unclear about the difference between qualifiedIdentifier and $qualifiedIdentifier in the rewrite rule.</p>
  
  <p>As for my second question, what i mean is that i removed the rewrite rule for qualifiedIdentifier and for the package i have the following:</p>
  
  <pre><code>packageDeclaration
      :   PACKAGE ident=qualifiedIdentifier SEMI -&gt; ^(PACKAGE $ident+) 
      ;
  </code></pre>
  
  <p>What i get as a result of this is nested tokens as in:</p>
  
  <pre><code> (package
      (a) [end:a]
  
      (.) [end:.]
  
      (b) [end:b]
  
      (.) [end:.]
  
      (c) [end:c]
    ) [end:package]
  
  Each token is represented as "(&lt;token's text property&gt;) [end: &lt;token's text property&gt;]"
  </code></pre>
  
  <p>I hope it's clear in the output above but i have one parent token (package) with 5 children.  Now they are in the correct order and all that.  What i would like is the same parent with only one child as in:</p>
  
  <pre><code> (package
      (a.b.c) [end:a.b.c]
    ) [end:package]
  </code></pre>