用符号表示如下: E→T|E+T|E-T T→F|T*F|T/F F→i|(E) 2、消去上面文法的左递归 E→TE1 E1 →+TE1|-TE1|ε T→FT1 T1→*FT1|/FT1|ε F →i|(E) 3. 按消去左递归的文法,使用Python语言,写出对应的递归下降语法分析器。
时间: 2023-09-04 09:12:16 浏览: 106
递归下降==语法分析器
3星 · 编辑精心推荐
以下是Python代码:
```
def match_terminal(expected_token, tokens, index):
if tokens[index] == expected_token:
return index + 1
else:
return -1
def parse_E(tokens, index):
index = parse_T(tokens, index)
if index == -1:
return -1
else:
return parse_E1(tokens, index)
def parse_E1(tokens, index):
next_index = match_terminal('+', tokens, index)
if next_index != -1:
next_index = parse_T(tokens, next_index)
if next_index == -1:
return -1
else:
return parse_E1(tokens, next_index)
else:
next_index = match_terminal('-', tokens, index)
if next_index != -1:
next_index = parse_T(tokens, next_index)
if next_index == -1:
return -1
else:
return parse_E1(tokens, next_index)
else:
return index
def parse_T(tokens, index):
index = parse_F(tokens, index)
if index == -1:
return -1
else:
return parse_T1(tokens, index)
def parse_T1(tokens, index):
next_index = match_terminal('*', tokens, index)
if next_index != -1:
next_index = parse_F(tokens, next_index)
if next_index == -1:
return -1
else:
return parse_T1(tokens, next_index)
else:
next_index = match_terminal('/', tokens, index)
if next_index != -1:
next_index = parse_F(tokens, next_index)
if next_index == -1:
return -1
else:
return parse_T1(tokens, next_index)
else:
return index
def parse_F(tokens, index):
next_index = match_terminal('i', tokens, index)
if next_index != -1:
return next_index
else:
next_index = match_terminal('(', tokens, index)
if next_index != -1:
next_index = parse_E(tokens, next_index)
if next_index == -1:
return -1
else:
return match_terminal(')', tokens, next_index)
else:
return -1
def parse(tokens):
index = parse_E(tokens, 0)
if index != -1 and index == len(tokens):
print("RIGHT, AGAIN! 语法分析完毕!")
else:
print("WRONG! 退出语法分析!")
tokens = ['i', '+', 'i', '*', 'i', '#']
parse(tokens)
```
阅读全文