Reputation: 184
I have a grammar for parsing diverse SQL code.
Problem :
- sometimes, I want it to handle nested comments (ex: Microsoft SQL):
COMMENT: '/*' (COMMENT|.)*? ('*/' | EOF) -> channel(HIDDEN);
- sometimes, I want it to not handle them (ex: Oracle):
COMMENT: '/*' .*? '*/' -> channel(HIDDEN);
I don't want to :
make two different grammars
compile my grammar twice to get two different lexers and two different parsers.
Best solution would be to have an argument, passed to the lexer/parser, to choose which "COMMENT implementation" to use.
Can I do this ? If yes, how, if not, is there a satisfying solution to my problem ?
Thanks !
Upvotes: 0
Views: 60
Reputation: 1408
You can achieve this using a semantic predicate in your lexer. You will need to (1) split the lexer and parser from each other. (2) Create a base class for the lexer with a boolean field, property, or method that you can set true if you want the lexer to allow nested comments, or false to disallow. For sake of below code, assume you add "bool nested = false;" to the lexer base class. (3) Within your lexer grammar, create one COMMENT rule as shown below. (4) After creating you lexer, assign the "nested" field to true if you want nested comments to be recognized.
COMMENT
: (
{nested}? '/*' (COMMENT|.)*? ('*/' | EOF)
| '/*' .*? '*/') -> channel(HIDDEN)
;
Upvotes: 2