0
votes

I'm new to ANTLR and using ANTLR4 (4.7.2 Jar file). I'm currently working on Oracle Parser.

Is there a way to add a node (with some text) directly to the AST from the Parser or Lexer? I'm hiding comments in my Lexer and would like to add that directly to the tree.

Is it possible? I believe Less4j allows something similar.

1
As Bart mentions below, there is nothing to decorate the parse tree with hidden channel tokens directly in the Antlr4 runtime. He is correct. But you can--and I would add that you do so post-parsing as to not use target-specific code into your grammar--with the primitives that the runtime provides (see ParserRuleContext and TerminalNodeImpl).kaby76
@kaby76 Thanks for the reply. Is there anything which I can refer? As stated im a newbie and would need some help in doing the aboveSandy
Follow this link to some code that does what you want. It's in C#, so you'll have to translate and change accordingly, e.g., recursive implementation to stack implementation, change streams to the type you use, etc. But, it should get you started.kaby76
@kaby76 : Could you please tell me what does "tree is ParserRuleContext internal_node" do (mentioned in Program.cs)? What is internal_node? How do I translate this to java? Thanks.Sandy
@kaby76 Thanks a lot. I was finally able to add the comments to the ast based on the sample you had given.Sandy

1 Answers

1
votes

Is there a way to add a node (with some text) directly to the AST from the Parser or Lexer?

Not from the lexer: at that phase there is no parse tree yet.

From the parser you could, but there's no ANTLR API to do that. ANTLR gives you the parse tree just as it parses your input. It does not allow you to mutate it. You'll have to create your own parse tree while you traverse the ANTLR parse tree and do the mutations yourself (including reading of the hidden channel) during that stage.