S —> do { A } while ( B );
A —> A1 A2
A1 —> c | s
A2 —> A | ε
B —> D 条件符 D
C —> 标识符 = D;
D —> ED1
D1 —> 加减符 ED1 | ε
E —> FE1
E1 —> 乘除符 FE1 | ε
F —> 加减符 G | G
G —> 标识符 | 数字 | (D)
属性文法就不写了
do{
a = -a + ( b * (-c + (-d) - 3.14 - 1)/e);
do{
a = - a + (-b) - 2.71;
}
while(a + b<-100);
}
while(a *(b + c)< -(c - d)/b); #
1.条件语句不支持逻辑运算(如:|| &&),设计文法时忘记了,懒得改,有需要自己加。修改这条文法就行:B —> D 条件符 D
2.没有做语义分析,具体看自己实验需求增加,改的难度应该不高。
keyword = ["do", "while"]
operator1 = ["+", "-", "*", "/", "=", "<", ">"]
operator2 = ["!=", ">=", "<=", "=="]
boundary = [";", "(", ")", "{", "}"]
word = [] # 词法分析单词表
index = 0 # 当前分析单词位置
out_code = [] # 四元式
l_depth = list(range(1000)) # 分配标签
result1 = True
result2 = False
def label(x):
return 'T' + str(x)
def isfloatnum(str):
s = str.split('.')
if len(s) > 2:
return False
else:
for si in s:
if not si.isdigit():
return False
return True
def lexical_analysis():
global result1
file = open('code.txt')
code = file.read()
code = code.replace('\n', ' ')
i = 0
while i < len(code): # 忽略结束符
if code[i] == ' ':
i += 1
continue
elif code[i] == '#':
word.append(['结束符', code[i]])
break
elif code[i].isalpha():
s = ''
for j in range(i, len(code)):
if code[j].isalpha() or code[j].isdigit() or code[j] == '_':
s = s + code[j]
else:
break
if s in keyword:
word.append(['keyword', s])
else:
word.append(['identifier', s])
i += len(s)
elif code[i].isdigit():
s = ''
j = i
while j < len(code) and (code[j].isdigit() or code[j].isalpha() or code[j] == '.'):
s = s + code[j]
j += 1
if isfloatnum(s):
word.append(['digit', s])
i += len(s)
else:
word.append(['error', s])
result1 = False
i += len(s)
elif code[i:i + 2] in operator2:
word.append(['operator', code[i:i + 2]])
i += 2
elif code[i] in operator1:
word.append(['operator', code[i]])
i += 1
elif code[i] in boundary:
word.append(['boundary', code[i]])
i += 1
else:
word.append(['error', code[i]])
result1 = False
i += 1
def S_analysis():
global index, out_code
if word[index][1] == 'do':
index += 1
else:
print('error:缺少do')
return False
if word[index][1] == '{':
index += 1
else:
print('error:缺少{')
return False
flag = l_depth[0] # 跳转标记
A = A_analysis() # 主体语句
if not A:
print('error:语句错误')
return False
if word[index][1] == '}':
index += 1
else:
print('error:缺少}')
return False
if word[index][1] == 'while':
index += 1
else:
print('error:缺少while')
return False
if word[index][1] == '(':
index += 1
else:
print('error:缺少(')
return False
B = B_analysis() # 条件语句
if not B:
print('error:条件语句错误')
return False
if word[index][1] == ')':
index += 1
else:
print('error:缺少)')
return False
if word[index][1] == ';':
index += 1
else:
print('error:缺少;')
return False
num = l_depth.pop(0)
out_code.append([num, 'JNZ', B, ' ', flag])
return True
def A_analysis():
global index, out_code
if not A1_analysis():
return False
if not A2_analysis():
return False
return True
def A1_analysis():
global index, out_code
if word[index][1] == 'do': # 循环语句
if S_analysis():
return True
else:
return False
if word[index][0] == 'identifier': # 赋值语句
if C_analysis():
return True
else:
return False
return False
def A2_analysis():
global index, out_code
if word[index][1] == '}': # A2——>e SELECT集
return True
if A_analysis(): # 下一条语句
return True
return False
def B_analysis(): # 条件语句
global index, out_code
x1 = D_analysis() # 左表达式
if not x1:
return False
if word[index][1] in ["<", ">", "!=", ">=", "<=", "=="]:
oper = word[index][1]
index += 1
else:
print('error: 条件符错误:' + word[index][1])
return False
x2 = D_analysis() # 右表达式
if not x2:
return False
num = l_depth.pop(0)
lable = label(num)
out_code.append([num, oper, x1, x2, lable])
return lable
def C_analysis(): # 赋值语句
global index, out_code
if word[index][0] == 'identifier':
x1 = word[index][1]
index += 1
else:
return False
if word[index][1] == '=':
index += 1
else:
print('error: 缺少 =')
return False
D = D_analysis() # 表达式
if not D:
return False
if word[index][1] == ';':
index += 1
else:
print('error: 缺少 ;')
return False
num = l_depth.pop(0)
lable = label(num)
out_code.append([num, '=', ' ', D, x1])
return lable
def D_analysis(): # 加减法
global index, out_code
E = E_analysis() # 左项
if not E:
return False
D1 = D1_analysis(E) # +右项
if not D1:
return False
if D1 == ' ':
return E # 项后为空,没有加法,返回项标签
else:
return D1 # 返回加法结果标签
def D1_analysis(E1):
global index, out_code
if word[index][1] in '+-':
if word[index][1] in '+-':
oper = word[index][1]
index += 1
else:
print('error: 缺少运算符 +-')
return False
E2 = E_analysis() # 右项
if not E2:
return False
num = l_depth.pop(0)
lable = label(num)
out_code.append([num, oper, E1, E2, lable])
D1 = D1_analysis(lable) # 下一个加减法
if not D1:
return False
if D1 == ' ':
return lable # 右参数后续为空,返回当前加法结果标签
else:
return D1 # 右参数后续还有加法,返回当前加法结果,进行后续加法产生的新结果
if word[index][1] in [";", "=<", "=>", '==', '!=', '<', '>', ')']: # D1——>e SELECT集
return ' ' # 加法左参数后续为空
return False
def E_analysis(): # 乘除法
global index, out_code
F = F_analysis() # 左因子
if not F:
return False
E1 = E1_analysis(F) # */右因子
if not E1:
return False
if E1 == ' ':
return F # 左因子后为空,没有乘法,返回左因子标签
else:
return E1 # 返回乘法结果标签
def E1_analysis(F1):
global index, out_code
if word[index][1] in '*/':
if word[index][1] in '*/':
oper = word[index][1]
index += 1
else:
print('error: 缺少运算符 */')
return False
F2 = F_analysis() # 右因子
if not F2:
return False
num = l_depth.pop(0)
lable = label(num)
out_code.append([num, oper, F1, F2, lable])
E1 = E1_analysis(lable) # 下一个乘除法
if not E1:
return False
if E1 == ' ':
return lable # 右参数后续为空,返回当前乘法结果标签
else:
return E1 # 右参数后续还有乘法,返回当前乘法结果,进行后续乘法产生的新结果
if word[index][1] in ["+", "-", ";", "=<", "=>", '==', '!=', '<', ">", ')']: # E1——>e SELECT集
return ' ' # 乘法左参数后续为空
return False
def F_analysis(): # 有符因子
global index, out_code
if word[index][1] in '+-':
oper = word[index][1]
index += 1
G = G_analysis()
if not G:
return False
num = l_depth.pop(0)
lable = label(num)
out_code.append([num, oper, G, ' ', lable])
return lable
else:
G = G_analysis()
if G:
return G # 无符因子
else:
return False
def G_analysis(): # 无符因子
global index, out_code
if word[index][0] == 'identifier':
index += 1
return word[index - 1][1]
elif word[index][0] == 'digit':
index += 1
return word[index - 1][1]
elif word[index][1] == '(':
if word[index][1] == '(':
index += 1
else:
print('error: 缺少左括号')
return False
D = D_analysis() # 表达式
if not D:
return False
if word[index][1] == ')':
index += 1
else:
print('error: 缺少右括号')
return False
return D # 返回表达式结果标签
else:
print('缺少因子')
return False
lexical_analysis()
for i in word:
print(i)
print('词法分析: ' + str(result1))
if S_analysis() and index+1 == len(word) and word[index][1] == '#':
result2 = True
else:
print('缺少结束符#')
result2 = False
print('语法分析: ' + str(result2))
#out_code.sort(key=lambda x: x[0])
if (result2):
for i in out_code:
print(i[0],end=' ')
j = tuple(i[1:5]) #元组
print(j)
if i[1] in ['=', 'JNZ']:
print()