简体   繁体   中英

Detect wrong grammar (error alternatives) for quick fixes

In my ANTLR grammar I would like to detect wrong keywords or wrong typed constants, eg 'null' instead of 'NULL'. I added error alternatives in the grammar, eg:

|   extra='null' #error1

If the wrong constant is detected in my custom editor I can fix it by replacing it with the correct constant.

But I don't know if this is the correct way to address and detect wrong keywords or constants in a grammar.

In addition I tried to detect missing closing in the grammar (see ANTLR book chapter 9.4):

.......
|   'if' '(' expr  expr #error2
|   '{'  exprlist #error3
|   'while' '(' expr  expr #error4
........

But this massively slows down the parsing process and so I think that it is wrong to do so.

My questions are:

Is it correct to detect wrong keywords, constants, etc. in that way as described above?

Is it somehow possible to catch missing closing in the grammar without the massive speed decrease?

Any help is appreciated.

I found out that I can extract the second Token from the rule (to add a brace at that position):

|   'if' '(' expr  expr #error2

with:

Token myToken = tokens.get(ctx.getChild(2).getSourceInterval().b);
parser.notifyErrorListeners(........

However it massively decreases the speed of the parser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM