Professional Documents
Culture Documents
Lab 8
Lab 8
Enrolment: 02-134192-0540
Lab 8
Exercise 1
Write a program to implement recursive decent parser for arithmetic expressions
ETE’
E’+TE’ ׀ε
TFT’
T’*FT’ ׀ε
Fid
Input:
inbuffer=input('Enter your input ,separated by space : ')
t=[]
t=inbuffer.split(' ')
t.append('$')
print(t)
global i
i=-1
def R():
E()
def E():
T()
A()
def A():
if( id == '+'):
matcht('+')
T()
A()
def T():
F()
G()
def G():
if( id == '*'):
matcht('*')
F()
G()
def F():
if( id == 'id'):
matcht('id')
def nexttoken():
global i
Name: Muhammad Mukarrum
Enrolment: 02-134192-0540
i=i+1
nt=t[i]
return nt
def matcht(t):
print(t)
global id
if (id == t):
id=nexttoken()
else:
print('error')
def main():
global id
id=nexttoken()
R()
if(id=='$'):
print('Accept')
else:
print("Reject")
main()
output:
Exercise 2
Write a program to implement recursive decent parser for conditional statements
(if-else and switch case)
Input:
import re
inbuffer=input('Enter your input ,separated by space : ')
Name: Muhammad Mukarrum
Enrolment: 02-134192-0540
t=[]
t=inbuffer.split(' ')
t.append('$')
print(t)
global i
i=-1
def R():
iff()
def iff():
if(id == 'if'):
matcht('if')
matcht('(')
iden()
con()
exp()
matcht(')')
statement()
if(id == 'elseif'):
statement()
if( id == 'else'):
matcht('else')
statement()
else:
print('error')
def statement():
if(id == '{'):
matcht('{')
if(id == 'if'):
iff()
Name: Muhammad Mukarrum
Enrolment: 02-134192-0540
matcht('}')
matcht(';')
elif re.match('^[a-zA-Z]+$',id):
iden()
matcht('}')
matcht(';')
else:
if(id == 'elseif'):
matcht('elseif')
matcht('(')
iden()
con()
exp()
matcht(')')
statement()
else:
print('error')
def exp():
if (re.match("^[a-zA-Z]+$",id)):
iden()
elif(re.match("^[0-9]+$",id)):
digits()
else:
print('error')
def con():
if(id=="<"):
matcht('<')
elif(id==">"):
matcht('>')
elif(id=="<="):
Name: Muhammad Mukarrum
Enrolment: 02-134192-0540
matcht('<=')
elif(id==">="):
matcht('>=')
elif(id=="=="):
matcht('==')
else:
print('error')
def iden():
if re.match('^[a-zA-Z]+$',id):
matcht(id)
else:
print('error')
def digits():
if re.match('^[0-9]+$',id):
matcht(id)
else:
print('error')
def nexttoken():
global i
i=i+1
nt=t[i]
return nt
def matcht(t):
print(t)
global id
if (id == t):
id=nexttoken()
else:
print('error')
Name: Muhammad Mukarrum
Enrolment: 02-134192-0540
def main():
global id
id=nexttoken()
R()
if(id=='$'):
print('Accept')
else:
print("Reject")
main()
Output: