第二章 一个简单语法制导编译器
根据语法制导定义,使用python实现了一个简单的语法制导翻译器,供大家参考。
m1.py:简单的词法分析模块
import re
def parse(str):
tokens = re.findall(r'for|if|\(|\)|other|expr|;',str)
print(tokens)
return tokens
if __name__ == '__main__':
str='''for ( ;expr; expr)
other
'''
parse(str)
m2.py:语法制导模块
import m2
str='''for ( ;expr; expr)
other
'''
lookahead = None
tokens = m2.parse(str)
nextTerminal = iter(tokens)
lookahead = next(nextTerminal)
def stmt():
global lookahead
if(lookahead == 'expr'):
match('expr')
match(';')
elif(lookahead == 'if'):
match('if')
match('(')
optexpr()
match(')')
stmt()
elif(lookahead == 'for'):
match('for')
match('(')
optexpr()
match(';')
optexpr()
match(';')
optexpr()
match(')')
stmt()
elif(lookahead == 'other'):
match('other')
elif(lookahead == None):
return
else:
print('syntax error')
def match(t):
global lookahead
global nextTerminal
if(lookahead == t):
try:
print(lookahead + ' matched')
lookahead = next(nextTerminal)
except StopIteration as e:
lookahead = None
def optexpr():
global lookahead
if(lookahead == 'expr'):
match('expr')
else:
print('skip expr')
if __name__ == '__main__':
stmt()