消除左递归后的文法如下: E -> TE' E' -> '+'TE' | '-'TE' | ε T -> FT' T' -> '*'FT' | '/'FT' | ε F -> 'i' | '(' E ')'按消去左递归的文法,使用你熟悉的语言,写出对应的递归下降语法分析器
时间: 2023-08-18 19:09:28 浏览: 121
以下是使用 Python 实现的递归下降语法分析器:
```python
class Parser:
def __init__(self, text):
self.text = text
self.pos = 0
def parse(self):
return self.parse_expression()
def parse_expression(self):
left = self.parse_term()
while self.pos < len(self.text) and self.text[self.pos] in ('+', '-'):
op = self.text[self.pos]
self.pos += 1
right = self.parse_term()
if op == '+':
left += right
else:
left -= right
return left
def parse_term(self):
left = self.parse_factor()
while self.pos < len(self.text) and self.text[self.pos] in ('*', '/'):
op = self.text[self.pos]
self.pos += 1
right = self.parse_factor()
if op == '*':
left *= right
else:
left /= right
return left
def parse_factor(self):
if self.text[self.pos] == '(':
self.pos += 1
result = self.parse_expression()
if self.text[self.pos] != ')':
raise Exception('Expected )')
self.pos += 1
return result
elif self.text[self.pos].isdigit():
start = self.pos
while self.pos < len(self.text) and self.text[self.pos].isdigit():
self.pos += 1
return int(self.text[start:self.pos])
else:
raise Exception('Expected digit or (')
```
例如,假设输入表达式为 "2+3*4-5",则可以通过以下方式调用上述递归下降语法分析器:
```python
parser = Parser("2+3*4-5")
result = parser.parse()
print(result) # 输出: 9
```
阅读全文