简体   繁体   English

在EBNF或GNU Bison语法中使用括号/括号

[英]Using brackets/parentheses in EBNF or GNU Bison grammar

I am defining my own grammar for a parser generator that outputs C/C++ code. 我正在为输出C / C ++代码的解析器生成器定义自己的语法。 I chose Bison for this, but have run into a problemm. 我为此选择了Bison,但遇到了问题。 I would like to use brackets ("(", ")") within rules, but Bison doesn't accept themFor example, to declare a character I use (the three dots are instead of all other possible ASCII characters): 我想在规则中使用方括号(“(”,“)”),但Bison不接受它们。例如,声明一个我使用的字符(三个点代替所有其他可能的ASCII字符):

character: "'" ("\0" | "\t" | "\n" | " " | "!" | ... | "}" | "~") "'";

As you can see, I use brackets to say that a character must have a quotation mark, any character and then another quotation mark. 如您所见,我使用方括号来表示一个字符必须带有引号,任何字符都必须带有引号。

I do something similar for an integer: 我对整数做了类似的事情:

integer: (["-"] digits) | "0";

Is there any way of achieving something similar in Bison? 有什么办法可以在野牛中实现类似的目的吗? Alternatively, is there a parser generator that accepts EBNF, or even just brackets and that outputs c++ code? 另外,是否有一个解析器生成器可以接受EBNF,甚至可以接受方括号并输出c ++代码?

Bison does not support EBNF, only BNF, so if you want optional or grouped things, you'll have to write the rule yourself: Bison仅支持EBNF,因此不支持EBNF,因此,如果需要可选或分组的内容,则必须自己编写规则:

character: '\'' character_char '\''
character_char: '\0' | '\t' | ...

integer: opt_negate digits | '0'
opt_negate: | '-'

Also, note that " characters in bison don't denote literals, so won't do what you want (and are generally useless, as you can't refer to them easily in the lexer). Always use ' -- single quotes -- for literal. 另外,请注意,野牛字符"并不表示文字,因此不会做您想要的事情(并且通常是无用的,因为您在词法分析器中无法轻松引用它们)。请始终使用' -单引号- -字面意思。

In addition, anything that can be recognized by a regular expression (like these examples), should probably be recognized in the lexer and returned to the bison parser as a single token -- it's much simpler, clearer, and more efficient. 此外,正则表达式可以识别的任何内容(如这些示例),都应该在词法分析器中识别,并作为单个标记返回给bison解析器,这更加简单,清晰和高效。

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

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