第四次上机—语法分析
目的:熟练掌握自上而下的语法分析方法,并能用程序实现。
要求:
- 使用的文法如下:
E ->TE ’
E ’ -> + TE’ | ε
T -> FT ’
T’ -> * FT ’ | ε
F -> (E) | id - 对于任意给定的输入串(词法记号流)进行语法分析,递归下降方法和非递归预测分析方法可以任选其一来实现。
- 要有一定的错误处理功能。即对错误能提示,并且能在一定程度上忽略尽量少的记号来进行接下来的分析。可以参考书上介绍的同步记号集合来处理。
可能的出错情况:ididid, id**id, (id+id, +id+id …… - 输入串以#结尾,输出推导过程中使用到的产生式。例如:
输入:id+idid#
输出:
E -> TE ’
T-> FT ’
F -> id
E’ -> + TE ’
T -> FT ’
……
如果输入串有错误,则在输出中要体现是跳过输入串的某些记号了,还是弹栈,弹出某个非终结符或者是终结符了,同时给出相应的出错提示信息。比如:
ididid对应的出错信息是:“输入串跳过记号id,用户多输入了一个id”;
id**id对应的出错信息是:“弹栈,弹出非终结符F,用户少输入了一个id”
(id+id对应的出错信息是:“弹栈,弹出终结符 ) ,用户少输入了一个右括号(或者说,括号不匹配)”
代码写的很乱:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
dict={'Eid':'E->TA','E+':'error','E*':'error','E(':'E->TA','E)':'synch','E#':'synch',
'Aid':'error','A+':'A->+TA','A*':'error','A(':'error','A)':'A->ε','A#':'A->ε',
'Tid':'T->FB','T+':'synch','T*':'error','T(':'T->FB','T)':'synch','T#':'synch',
'Bid':'error','B+':'B->ε','B*':'B->*FB','B(':'error','B)':'B->ε','B#':'B->ε',
'Fid':'F->id','F+':'synch','F*':'synch','F(':'F->(E)','F)':'F->synch','F#':'synch'}
flag=0
def abc(s1):
if (len(st) == 1 and st[0] == "#"):
if(s1!="#"):
return "error3"
return "end"
if(len(st)==0):
return "end"
a=st[-1]
if(st[-1]=='d' and st[-2]=='i'):
a='id'
if(a==s1):
st.pop(-1)
return "one"
finding=a.__add__(s1)
b=dict.get(finding)
if(b is None):
return "error2"
if(b=='error'):
return 'error'
elif(b=='synch'):
return 'synch'
else:
print(b)
temp1=b.split('->')
return temp1[1]
#s=input("输入内容,以#结束")
s="id+id)#"
print(s)
i=0
st=[]
st.append('#')
st.append('E')
s1=s[i:i+1]
while(s1!="#" or st!='#'):
if(s1=='i' and s[i+1:i+2]=='d'):
s1=s[i:i+2]
i+=2
temp2 = abc(s1)
if (temp2 == "end"):
break;
while (st[len(st) - 2:len(st)] != 'id'):
if (temp2 == 'error'):
print("出错,跳过",s1,'用户多输入了一个id')
break
elif (temp2 == "error2"):
mn = st.pop(-1)
print('出错,终结符',mn,'弹栈', '用户少输入了{0}'.format(mn))
temp2 = abc(s1)
elif(temp2=="error3"):
print("出错,书写多了",s1)
flag=-1
break
elif(temp2=="one"):
break
elif (temp2 == 'synch'):
st.pop(-1)
st.pop(-1)
print('出错,非终结符id弹栈,用户少输入了一个id')
temp2 = abc(s1)
elif(temp2=='ε'):
st.pop(-1)
temp2=abc(s1)
elif (temp2 == s1):
st.pop(-1)
st.append(s1)
break
else:
st.pop(-1)
for x in range(len(temp2)):
st.append(temp2[-x - 1])
temp2=abc(s1)
if (temp2 == s1):
st.pop(-1)
st.append(s1)
break
if (st[-1] == 'id'):
st.pop(-1)
else:
i+=1
temp2 = abc(s1)
if(temp2=="end"):
break
while (st[-1]!=s1):
if (temp2 == 'error'):
print("出错,跳过", s1, '用户多输入了一个',s1)
break
elif(temp2=="error2"):
mn = st.pop(-1)
print('出错,终结符', mn, '弹栈', '用户少输入了{0}'.format(mn))
temp2 = abc(s1)
elif (temp2 == "one"):
break
elif (temp2 == 'synch'):
mn=st.pop(-1)
print('出错,非终结符',mn,'弹栈')
temp2=abc(s1)
elif (temp2 == 'ε'):
st.pop(-1)
temp2=abc(s1)
elif(temp2==s1):
st.pop(-1)
st.append(s1)
elif (temp2 == "error3"):
print("出错,书写多了", s1,"及其后面的内容")
flag=-1
break
else:
st.pop(-1)
for x in range(len(temp2)):
st.append(temp2[-x - 1])
temp2 = abc(s1)
if(st[-1]==s1):
st.pop(-1)
if(flag!=-1):
s1 = s[i:i + 1]
else:
break