所以,我有一个语法,即:
termo : PESQ termo termo PDIR
| PESQ LAMBDA listav PONTO termo PDIR
| VAR
listav : VAR listav
| VAR
其中termo = term,PESQ =(,PDIR =),LAMBDA =!,PONTO =。,VAR = [a-z],listav =变量列表。
问题是,当我尝试生成我输入的某些表达式的抽象语法树时,例如!x.x,它给了我一个错误:yacc:第1行的语法错误,token = LAMBDA。
我认为这里的问题是我定义语法的方式(并将非终结符插入堆栈数组。我将代码留在底部。也许是关于stack.append(p [x ])?我不确定应该将哪些非终结符附加到数组,因为我有多个生成。
import sys
from tree import *
stack = []
tokens = [
'LAMBDA',
'PONTO',
'VAR',
'PDIR',
'PESQ'
]
t_LAMBDA = r'\!'
t_PONTO = r'\.'
t_VAR = r'[a-z]'
t_PDIR = r'\)'
t_PESQ = r'\('
t_ignore = r' '
def t_error(t):
print("Illegal Character!")
t.lexer.skip(1)
import ply.lex as lex
lexer = lex.lex()
def p_termo(p):
'''
termo : PESQ termo termo PDIR
| PESQ LAMBDA listav PONTO termo PDIR
| VAR
'''
if len(p) == 7:
stack.append(p[2])
stack.append(p[3])
stack.append(p[4])
elif len(p) == 2:
stack.append(p[1])
def p_listav(p):
'''
listav : VAR listav
| VAR
'''
if len(p) == 3:
stack.append(p[1])
elif len(p) == 2:
stack.append(p[1])
import ply.yacc as yacc
parser = yacc.yacc()
while True:
try:
print('')
print('Input: ')
inp = input('')
except EOFError:
break
stack = []
p = parser.parse(inp)
z = 0
while z < len(stack):
if z == 0:
if len(stack) == 1:
a = Tree(stack[z])
z += 1
elif stack[z+1] != '!':
auxL = Tree(stack[z + 1])
auxR = Tree(stack[z])
a = Tree('@', auxL, auxR)
z += 2
else:
a = Tree(stack[z])
z += 1
else:
if stack[z] == '!' and stack[z-2] == '.' and z > 1:
auxR = Tree(stack[z + 1])
b = Tree('!', m, auxR)
a = Tree('@', a, b)
z += 3
elif stack[z] == '!':
auxL = Tree(stack[z+1])
a = Tree('!', auxL, a)
z += 3
elif stack[z] != '!' and stack[z-1] == '.' and z != len(stack) - 1:
if stack[z+1] == '!':
m = Tree(stack[z])
z += 1
else:
auxR = Tree(stack[z])
a = Tree('@', a, auxR)
z += 1
else:
auxR = Tree(stack[z])
a = Tree('@', a, auxR)
z += 1
arv = Tree.print_tree(a)
print('###########################')
print('Arvore: ')
print(arv)
print('###########################')