2

I have the following code which extends ProcessBaseListener:

var myProcessListener = new MyProcessListener();
walker = new ParseTreeWalker();
walker.Walk(myProcessListener , tree);

I've overridden one method:

public override void ExitLineNumberOrLabel(ProcessParser.LineNumberOrLabelContext context)
{
    var lineNumberOrLabel = context.GetText().ToUpper();
}

How do I manipulate that context or it's parent context? All the methods are read only.

For example, I may want to modify the lineNumberOrLabel or remove it from its parent context. I may even want to insert a new context of a different type before or after it.

I've tried using TokenStreamRewriter but that doesn't modify the stream. I have to invoke ToString() to see the changes and then possible parse it all over again??? Why can't I just modify the ParserRuleContexts? I used to essentially do this is SableCC.

tmakaro
  • 33
  • 5

1 Answers1

2

In idiomatic usage, the parse-tree is immutable, once generated. Record what is otherwise intended by parse-tree/context node changes as properties attached to each relevant node. See the embedded JavaDoc for usage.

As for why, Antlr offers its own approach to handling the analysis phase/tree walking as discussed in the last few paragraphs of this answer.

Community
  • 1
  • 1
GRosenberg
  • 5,843
  • 2
  • 19
  • 23
  • Thanks. I think that will work fine and I am already doing that in some places. I just have to follow it through. – tmakaro Jun 17 '15 at 22:14