0

I need to transform text from following structure:

{ A1 A2 { B1 B2 { C1 C2 } } }

to the following developed/flattened structure:

{ A1 }
{ A2 B1 }
{ A2 B2 C1 }
{ A2 B2 C2 }

I use the following Antlr grammar to parse the file:

grammar tree;
node : '{' (STRING | node)* '}';
STRING : ('A' .. 'Z' | '0' .. '9')+;
WS : ( ' ' | '\t' | '\n' | '\r') -> channel(HIDDEN);

Is it possible to perform the Ast transformation by only using inline Antlr rewrite rules (using ->)?

jeromerg
  • 2,997
  • 2
  • 26
  • 36

1 Answers1

1

By looking at channel(HIDDEN), it seems you're using ANTLR4, which does not have the rewrite functionality anymore: ANTLR 4 tree inject/rewrite operator. Besides, if you'd be using ANTLR3, I doubt you'd be able to rewrite the AST is such a way.

You should see this as two operations: 1) parse the input, and 2) walk/visit the parse tree and [by using plain programming] rewrite the parsed tree into something else. This last step is done by yourself in tree listener- or visitor of which ANTLR generates base classes for.

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Thanks. The grammar is not exactly the one I use, it was just an example to give an idea of the composite model. I have indeed already implemented the transformation in the same way as you described: with a visitor implemented in C#. I'm curious to see whether it is possible to "develop" the tree with a smart rewrite rule... and without visitor... Any other suggestion? – jeromerg Apr 01 '14 at 19:59
  • @jrg, as I said: ANTLR4 does not have any way to rewrite its (parse) tree, only ANTLR3 does. And with ANTLR3, I highly doubt it would be possible: rewrite rules are more meant to remove, or make small alterations to nodes in the tree, not to radically change it as you describe. – Bart Kiers Apr 01 '14 at 20:02