Is there any Way to skip the parsing of specific block while using Listener in ANTLR4 using enter or exit method. I have read link here but unable to make it work. Thank You!
1 Answers
By the time you're using the Listener pattern with your own Listener class, the input is already correctly lexed and parsed. Therefore, the answer to your question is no. When you're using the listener you're typically just walking the tree post-parse.
Does that mean all is lost though? Of course not. All you have to do is simply not code the Enter
or Exit
events for those constructs you want to "ignore." It's that easy.
As to if-else statements, I've always implemented them using the visitor pattern like this:
As to how to program an if
statement, I'll give you a peek at they way I implement them:
public override MuValue VisitIfstmt(LISBASICParser.IfstmtContext context)
{
LISBASICParser.Condition_blockContext[] conditions = context.condition_block();
bool evaluatedBlock = false;
foreach (LISBASICParser.Condition_blockContext condition in conditions)
{
MuValue evaluated = Visit(condition.expr());
if (evaluated.AsBoolean())
{
evaluatedBlock = true;
Visit(condition.stmt_block());
break;
}
}
if (!evaluatedBlock && context.stmt_block() != null)
{
Visit(context.stmt_block());
}
return MuValue.Void;
}
Granted, this probably doesn't make much sense out of context, but rest assured it works. To see this in its full context, please visit Bart Kiers for an excellent example of grammar and implementation .

- 7,248
- 5
- 30
- 47
-
can we implement if-else statements by using JUST listeners? – Breathe Hacker Aug 21 '17 at 03:36
-
@BreatheHacker Please see my update answer regarding if-else. Once I learned this pattern, I never looked back to see if it could be done using only listener. – TomServo Aug 21 '17 at 11:52
-
I wanna some explanation about `ctx.expr()`. How this is working. i.e evaluating the expression and saving of value in HashMap? – Breathe Hacker Aug 21 '17 at 13:59
-
No, not hashMap. Each Visit() call eventually is resolved into a MuValue object. This is the difference between Visitor and Listener. Visitor can return a value of any type, in this case a MuValue object. In Listener, you have to construct your own mechanism to store values as you traverse the tree. That's why I chose visitor; for anything that requires something more complicated than a Stack, I use visitor. Listener works great with Stack as the storage mechanism. – TomServo Aug 21 '17 at 14:10
-
What I have learned so far is that hashMap is only used to store the ID atom and Value associated with that ID atom. Now as we have (*) on stat so while logging out the value each time when stat block is called for parsing then first of all value of n is returned then the string is printed on screen.(but what about + sign there?).Correct me if i'm wrong – Breathe Hacker Aug 21 '17 at 14:29