Valentin Grigorev
Valentin Grigorev

Reputation: 31

ANTLR templated rules

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:

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.

Upvotes: 0

Views: 47

Answers (1)

sepp2k
sepp2k

Reputation: 370172

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.

Upvotes: 1

Related Questions