Syntactic errors on optional rules in Antlr 4 doesn't work as expected

心已入冬 提交于 2019-12-02 08:02:39

Normally it is not a syntax error if an input stream contains more input than what is required by the rule you invoke. The additional input is simply left in the stream. This allows you to invoke rules in a loop for example.

So if you invoke your prog rule on the input if (2==2){ let a = 4; } else { let b = 5;, the if (2==2){ let a = 4; } part will be parsed as an if-statement without else and else { let b = 5; will remain in the input buffer.

Since that's not what you want, you should add EOF at the end of your prog rule:

prog       : stat+ EOF;

The EOF tells ANTLR that a program is only syntactically valid if there's nothing left in the input after parsing it. This will give you the syntax error you want for your input.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!