Search code examples
antlr4antlr4cs

How to modify or insert a ParserRuleContext as I am walking it with a BaseListener


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.


Solution

  • 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.