我正在学习编程语言和编程语言的概念。 我怎么翻译呢?
问题:
<S> → (+ | -)[<C>]{<A>}
起初,我翻译成这样:
<S> -> epsilon
| +<S>
| -<S>
| <C><S>
| <A><S>
然而,它有一个问题,它可以重现C!
答案 0 :(得分:2)
您的BNF版本不仅可以生成多个<C>
,还可以生成多个+
和-
s(或者零,这也与原始语法不同)。< / p>
要解决这些问题,您需要引入其他非终端。具体来说,您可以使用仅匹配{<A>}
的匹配和匹配[<C>]
的匹配。您对<S>
的定义可能是:
<S> -> + <OptionalC> <RepeatedA>
| - <OptionalC> <RepeatedA>
答案 1 :(得分:0)
Your EBNF original is not recursive in <S>
, but your trial BNF is. If you want the BNF to generate the same language, you shouldn't do that. Also, your EBNF can't generate epsilon
, so you shouldn't add that to your <S>
-production, either.
As the other answer says, you need to introduce additional non-terminals:
<S> -> <plusminus> <optionalC> <repeatedA>
<plusminus> -> + | -
<optionalC> -> <C> | epsilon
<repeatedA> -> <A> <repeatedA> | epsilon
This is a straightforward translation of the EBNF elements in your original grammar. Even if you have additional requirements (such as epsilon-elimination), you should start with this kind of step.
Note that the <S>
rule is not recursive. Also, although epsilon
is used for some additional nonterminals, it is not part of the <S>
or <plusminus>
rules, so that, as in the EBNF original, <S>
cannot produce it.