简体   繁体   English

算术表达式语法

[英]Grammar for Arithmetic Expressions

I was assigned a task for creating a parser for Arithmetic Expressions (with parenthesis and unary operators). 我被分配了一个为算术表达式创建解析器的任务(带括号和一元运算符)。 So I just wanna know if this grammar correct or not and is it in LL(1) form and having real problems constructing the parse table for this 所以我只想知道这个语法是否正确,是否为LL(1)形式,并为此构造解析表时遇到实际问题

 S  -> TS'
 S' -> +TS' | -TS' | epsilon
 T  -> UT'
 T' -> *UT' | /UT' | epsilon
 U  -> VX
 X  -> ^U | epsilon
 V  -> (W) | -W | W | epsilon
 W  -> S | number

Precedence (high to low) 优先级(从高到低)

 (), unary –
 ^
 *, /
 +, -

Associativity for binary operators 二进制运算符的关联性

 ^ = right
 +, -, *, / = left

Is it in LL(1) form? 它是LL(1)形式吗?

To tell if the grammar is LL(1) or not, you need to expand the production rules out. 要判断语法是否为LL(1),您需要扩展生产规则。 If you can generate any sequence of productions which results in the left-hand-side appearing as the first thing on the right-hand-side, the grammar is not LL(1). 如果您可以生成任何产生式序列,从而导致左侧在第一手出现在右侧,则语法不是LL(1)。

For example, consider this rule: 例如,考虑以下规则:

X --> X | x | epsilon

This clearly can't be part of an LL(1) grammar, since it's left-recursive if you apply the leftmost production. 显然,这不是LL(1)语法的一部分,因为如果应用最左边的产生式,则它是左递归的。 But what about this? 但是呢?

X --> Y | x
Y --> X + X

This isn't an LL(1) grammar either, but it's more subtle: first you have to apply X --> Y, then apply Y --> X + X to see that you now have X --> X + X, which is left-recursive. 这也不是LL(1)语法,但是更微妙:首先您必须应用X-> Y,然后应用Y-> X + X才能看到现在有了X-> X + X ,这是左递归的。

You seem to be missing anything for unary plus operator. 对于一元加号运算符,您似乎缺少任何内容。 Try this instead... 试试这个...

V -> (W) | V->(W)| -W | -W | +W | + W | epsilon ε

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

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