Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need help reviewing this code and making sure it reads from a file C programming language and it processes it through a lexical, sintaxis

I need help reviewing this code and making sure it reads from a file C programming language and it processes it through a lexical, sintaxis, semantic analyzer and then it outputs an object file .o with code transformed to assembly code. import pandas as pd
LEXER_TABLE = pd.DataFrame(columns =['TOKEN','IDENTITY'], index = range(1))
def lexer(code):
SYMBOLS =['(',')',';',',',':',"'"]
SYMBOLS_1=['(',')',';',',',':',"'",'+','=','>']
SYMBOLS_1_DUP =[
['Open bracket', '('],
['close bracket', ')'],
['semicolon',';'],
['comma',','],
['colon',':'],
['single quote', "'"],
['plus','+'],
['equal','='],
['greater than', '>']
]
keywords =['integers', 'main', 'while', 'begin', 'end', 'expr', 'procedure', 'If', 'elseif', 'else', 'then', 'printf', 'and', 'or']
KEYWORDS = SYMBOLS_1+ keywords
white_space =''
lexeme =''
tokens =[]
code = code.replace('\t','')
for i, char in enumerate(code):
if char != white_space:
lexeme += char
if (i+1< len(code)):
if code[i+1]== white_space or code[i +1] in KEYWORDS or lexeme in KEYWORDS:
if lexeme !='':
tokens.append(lexeme.replace('',''))
lexeme =''
j =0
for i in tokens:
for k in SYMBOLS_1_DUP:
if i == k[1]:
LEXER_TABLE.at[j, 'TOKEN']= i
LEXER_TABLE.at[j, 'IDENTITY']= k[0]
j +=1
break
if i in keywords:
LEXER_TABLE.at[j, 'TOKEN']= i
LEXER_TABLE.at[j, 'IDENTITY']= 'keyword'
j +=1
continue
if i.isdigit():
LEXER_TABLE.at[j, 'TOKEN']= i
LEXER_TABLE.at[j, 'IDENTITY']= 'Digit'
j +=1
continue
elif i not in KEYWORDS:
LEXER_TABLE.at[j, 'TOKEN']= i
LEXER_TABLE.at[j, 'IDENTITY']= 'Identifier'
j +=1
continue
print(f"Lexer Tokens: {tokens}")
return tokens
if __name__=="__main__":
code ="3+5*(10-20)"
tokens = lexer(code)
print("tokens:", tokens)
class Node:
def __init__(self, type, value = None):
self.type = type
self.value = value
self.children =[]
def add_child(self,node):
self.children.append(node)
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.current_token_index =0
def parse(self):
return self.expr()
def expr(self):
node = self.term()
while self.current_token() in ['+','-']:
token = self.current_token()
self.eat(token)
node = Node(type = token, value = token)
node.add_child(self.term())
return node
def term(self):
node = self.factor()
while self.current_token() in ['*','/']:
token = self.current.token()
self.eat(token)
node = Node(type = token, value = token)
node.add_child(self.factor())
return node
def factor(self):
token = self.current_token()
if token.isdigit():
self.eat(token)
return Node(type = 'NUMBER', value = int(token))
elif token =='(':
self.eat('(')
node = self.expr()
self.eat(')')
return node
def current_token(self):
return self.tokens[self.current_token_index]
def eat(self,token_type):
if self.current_token()== token_type:
self.current_token_index +=1
else:
raise Exception(f"Unexpected token: {self.current_token()}")
if __name__=="__main__":
code ="3+5*(10-20)"
tokens = lexer(code)
parser = Parser(tokens)
try:
ast = parser.parse()
print("Parsed AST sucessfully")
except Exception as e:
print(f"parsing error: {e}")
class CodeGenerator:
def __init__(self, ast):
self.ast = ast
self.code =[]
self.temp_count =0
def generate_code(self):
self.visit(self.ast)
return self.code
def visit(self, node):
if node.type == 'NUMBER':
self.code.append(f"LOAD {node.value}")
elif node.type in ['+','-','*','/']:
left = node.children[0]
self.visit(left)
right = node.children[1]
self.visit(right)
self.code.append(f"{node.type} TEMP{self.temp_count}")
self.temp_count +=1
if __name__=="__main__":
code ="3+5*(10-20)"
tokens = lexer(code)
parser = Parser(tokens)
try:
ast = parser.parse()
codegen = CodeGenerator(ast)
object_code = codegen.generate__code()
print("Generated object code: ")
for line in object_code:
print(line)
except Exception as e:
print(f"parsing error: {e}")

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Jeffrey A. Hoffer Fred R. McFadden

9th Edition

B01JXPZ7AK, 9780805360479

More Books

Students also viewed these Databases questions