Search code examples
antlr4option-typevisitor-pattern

How to handle Optional Grammar Blocks with a ANTLR-Visitor?


It is possible that this question has been asked before but i cannot find it. So if you guys find something similar, please let me know.

According to the following Rule:

fix_body : ident  binders (annotation)? (':' term)? ':=' fix_body_term;

I have an optional annotation and an optional Term. The corresponding visitorRule looks like this :

public FixBody visitFix_body(coqParser.Fix_bodyContext ctx)

My Question is how do i find out, if there was a term or not?

There is a method for reaching the term by using ctx.term(), but when there is no term given, does this method return null? Or is there a completly different way to approach this? As i am working with a large grammer it will take me a while to test this, otherwise I would have done that.


Solution

  • There is no trap there ...

    If the term is optional, you just have to test it before calling the accept(visitor) method

    In your case

    if(ctx.term() != null) ctx.term().accept(new TermVisitor())
    

    Example: