0
votes

I'm using ANTLR 4 to parse an SQL subset and currently, I'm faced with a problem. I need a rule for predicate with the following structure:

predicate
    :
    expr relation expr
    | between_clause
    | predicate OR predicate
    | predicate AND predicate
    | '(' predicate ')'
    ;

The issue here is an expr rule. There are different types of predicates where expr should be different, but the whole aforementioned structure is preserved.

I would like to parametrize the predicate rule in some way to automatically instantiate several rules for different predicate types (the rule above where specific expr types are substituted).

Is it possible in ANTLR 4?

P.S. I see two alternative options:

  • Copy-paste predicate rule and substitute different expr rules manually
  • Have all possible alternatives in the expr rule and verify that only one type of them is used for a specific predicate in the target language code

But both of them are looking bad enough. The first case leads to a combinatorial explosion, and the second one leads to accepting a lot of incorrect predicates on the grammar level.

1

1 Answers

1
votes

Is it possible in ANTLR 4?

No, ANTLR does not have such a feature.

Your two alternatives are exactly how these things are commonly done in practice. Which one is preferable depends on how exactly the different replacements for expr differ.

the second one leads to accepting a lot of incorrect predicates on the grammar level.

There'll always types of errors that you can't prevent in the grammar and that'll have to be handled in a separate phase. Type errors or undeclared variable errors for example. So having the grammar accept incorrect programs isn't unusual at all.