Question
Given This Code of a Lexical Analyzer in Python: import ply.lex as lex t_ID=r'[a-zA-Z0-9]' t_NUM=r'[0-9]' t_LPAREN = r'(' t_RPAREN= r')' t_LBRACE=r'{' t_RBRACE=r'}' t_NE=r'!=' t_EQ=r'==' t_ARROW=r'=>'
Given This Code of a Lexical Analyzer in Python:
import ply.lex as lex
t_ID=r'[a-zA-Z0-9]'
t_NUM=r'[0-9]'
t_LPAREN = r'\('
t_RPAREN= r'\)'
t_LBRACE=r'{'
t_RBRACE=r'}'
t_NE=r'!='
t_EQ=r'=='
t_ARROW=r'=>'
t_LE=r'
t_GE=r'>='
t_BECOMES=r'='
t_LT=r'
t_GT=r'>'
t_PLUS=r'\+'
t_MINUS=r'-'
t_STAR=r'\*'
t_SLASH=r'/'
t_PCT=r'%'
t_COMMA=r','
t_SEMI=r';'
t_COLON=r':'
t_ignore = ' \t'
keywords = {
'def':'DEF',
'var':'VAR',
'Int':'INT',
'if':'IF',
'else':'ELSE',
}
tokens = ["ID", "DEF", "VAR", "INT", "IF", "ELSE", "NUM", "LPAREN",
"RPAREN", "LBRACE", "RBRACE", "BECOMES", "EQ", "NE", "LT", "GT",
"LE", "GE", "PLUS", "MINUS", "STAR", "SLASH", "PCT", "COMMA", "SEMI", "COLON", "ARROW"]
def t_DEF(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'DEF')
return t
def t_VAR(t):
r'[a-zA-Z][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'VAR')
return t
def t_INT(t):
r'[a-zA-Z][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'INT')
return t
def t_IF(t):
r'[a-zA-Z][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'IF')
return t
def t_ELSE(t):
r'[a-zA-Z][a-zA-Z_0-9]*'
t.type = keywords.get(t.value, 'ELSE')
return t
t_ignore_COMMENT = r'\#.'
def t_newline(t):
r' +'
t.lexer.lineno += len(t.value)
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
lexer = lex.lex()
file = open("test_file.txt", 'r')
for line in file:
lexer.input(line)
while True:
tok = lexer.token()
if not tok:
break
print(tok)
file.close()
Add the parsing code using PLY to recognize the following grammar rules:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started