简体   繁体   English

为什么这样解析

[英]Why is that parsable

I have the following grammar: 我有以下语法:

grammar Demo;

program: command
         IDENTIFIER
         ;

command:
       | 'add'
       | 'remove'
       ;

IDENTIFIER: [a-zA-Z][a-zA-Z0-9]* ;

WHITESPACE: [ \t\n\r]+ -> skip;

Now I can entered something like "add foo" and I get the right result. 现在,我可以输入“ add foo”之类的东西,并且得到正确的结果。 But he also accept "foo" only. 但是他也只接受“ foo”。 I thought that the parser will throw an exception, because the value have to start with one of the commands? 我以为解析器会抛出异常,因为值必须以命令之一开头? Is there an option to fix the problem? 有解决此问题的选项吗? Or have I a fallacy? 还是我有谬误?

As indicated in the comments by Seelenvirtuose, the problem is that your rule for command allows an empty command, it should be: 如Seelenvirtuose的注释中所述,问题是您的command规则允许使用空命令,它应该是:

command:
         'add'
       | 'remove'
       ;

The pipe symbol ( | ) is a separator between alternatives, in your original code it separated an empty production from 'add' . 管道符号( | )是备选项之间的分隔符,在您的原始代码中,它用'add'分隔了空的生产。

However, as is, the grammar would still allow to only match foo which is because you don't have an explicit EOF token in your program rule (similar to the $ option in a regular expression). 但是,语法仍然只允许匹配foo ,这是因为您的program规则中没有显式的EOF标记(类似于正则表达式中的$选项)。 Without the EOF token the parser happily matches what it can and ignores the rest. 如果没有EOF令牌,则解析器会愉快地匹配它可以执行的操作,而忽略其余操作。 So, if that is no the desired behavior always end your main rule with EOF: 因此,如果这不是所需的行为,请始终以EOF结束您的主要规则:

program: command IDENTIFIER EOF;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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