0% found this document useful (0 votes)
15 views16 pages

SPCC Adheesh

Uploaded by

bihod71717
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views16 pages

SPCC Adheesh

Uploaded by

bihod71717
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

EXP NO 2

Program: -
def extract_macros(source_code):
macros = []
lines = source_code.split('\n')
index = 0
for line in lines:
if line.strip().startswith("MACRO"):
macro_name = lines[index+1].strip().split()[0]
macros.append((macro_name, index+1))
index += 1
return macros

def display_macro_name_table(macros):
print("Macro Name Table:")
print("Index\tMacro Name\tMDT Index")
for i, (macro_name, index) in enumerate(macros, start=1):
print(f"{i}\t{macro_name}\t\t{index}")

# Step 1: Open and read the source code file


with open('prog.txt', 'r') as file:
source_code = file.read()

# Step 2: Display the content of the source code


print("Source Code:")
print(source_code)

# Step 3: Extract macro name table


macros = extract_macros(source_code)

# Step 4: Display macro name table


display_macro_name_table(macros)

prog.txt
MACRO
INCR1 &ARG1,&ARG2
A 1,&ARG1
L 2,&ARG2
MEND
MACRO
INCR2 &ARG1,&ARG2
M 1,&ARG1
S 2,&ARG2
MEND
MACRO
COMPLEX &X
INCR1 &X,DATA1
INCR2 &X,DATA2
MEND

OUTPUT: -
Source Code:
MACRO
INCR1 &ARG1,&ARG2
A 1,&ARG1
L 2,&ARG2
MEND
MACRO
INCR2 &ARG1,&ARG2
M 1,&ARG1
S 2,&ARG2
MEND
MACRO
COMPLEX &X
INCR1 &X,DATA1
INCR2 &X,DATA2
MEND

Macro Name Table:


Index Macro Name MDT Index
1 INCR1 1
2 INCR2 6
3 COMPLEX 11
EXP NO 3
Program: -
# Define functions to identify tokens
def is_keyword(word):
keywords = ['if', 'else', 'while', 'for', 'int', 'float', 'char', 'return']
return word in keywords
def is_identifier(word):
return word.isidentifier() and not is_keyword(word)
def is_integer_literal(word):
try:
int(word)
return True
except ValueError:
return False
def is_float_literal(word):
try:
float(word)
return True
except ValueError:
return False
def is_operator(word):
operators = ['+', '-', '*', '/', '=', '==', '!=', '<', '>', '<=', '>=']
return word in operators
def is_delimiter(word):
delimiters = ['(', ')', '{', '}', '[', ']', ',', ';']
return word in delimiters
# Define function for lexical analysis
def lexical_analyzer(code):
tokens = []
lines = code.split('\n')
for line in lines:
words = line.split()
for word in words:
if is_keyword(word):
tokens.append((word, 'Keyword'))
elif is_identifier(word):
tokens.append((word, 'Identifier'))
elif is_integer_literal(word):
tokens.append((word, 'Integer Literal'))
elif is_float_literal(word):
tokens.append((word, 'Float Literal'))
elif is_operator(word):
tokens.append((word, 'Operator'))
elif is_delimiter(word):
tokens.append((word, 'Delimiter'))
else:
tokens.append((word, 'Unknown'))
return tokens
# Main program
if __name__ == "__main__":
code = """int main() {
int x = 10 ;
float y = 3.14 ;
if ( x == 10 ) {
printf ( " Hello , World ! " ) ;
}
}"""

print("Input Code:")
print(code)
print("\nLexical Analysis:")
tokens = lexical_analyzer(code)
for token in tokens:
print(token[0], "-", token[1])

OUTPUT: -
Input Code:
int main() {
int x = 10 ;
float y = 3.14 ;
if ( x == 10 ) {
printf ( " Hello , World ! " ) ;
}
}
Lexical Analysis:
int - Keyword
main() - Unknown
{ - Delimiter
int - Keyword
x - Identifier
= - Operator
10 - Integer Literal
; - Delimiter
float - Keyword
y - Identifier
= - Operator
3.14 - Float Literal
; - Delimiter
if - Keyword
( - Delimiter
x - Identifier
== - Operator
10 - Integer Literal
) - Delimiter
{ - Delimiter
printf - Identifier
( - Delimiter
" - Unknown
Hello - Identifier
, - Delimiter
World - Identifier
! - Unknown
" - Unknown
) - Delimiter
; - Delimiter
} - Delimiter
} – Delimiter
EXP NO 4
Program: -
def eliminate_left_recursion(grammar):
non_terminals = list(grammar.keys())

for A in non_terminals:
productions_A = grammar[A]

# Split productions into left-recursive and non-left-recursive


left_recursive_productions = [prod for prod in productions_A if prod.startswith(A)]
non_left_recursive_productions = [prod for prod in productions_A if not prod.startswith(A)]

if not left_recursive_productions:
continue

# Create a new non-terminal A' for the non-left-recursive productions


A_prime = A + "'"
grammar[A_prime] = [prod[len(A):] + A_prime for prod in left_recursive_productions] + ["ε"]

# Update original non-terminal A with non-left-recursive productions followed by A'


grammar[A] = [prod + A_prime for prod in non_left_recursive_productions]

return grammar

# Function to parse user input for grammar


def parse_grammar():
grammar = {}
while True:
production = input("Enter production (or type 'done' to finish): ").strip()
if production.lower() == 'done':
break
non_terminal, rhs = production.split('->')
non_terminal = non_terminal.strip()
rhs = [symbol.strip() for symbol in rhs.split('|')]
grammar[non_terminal] = rhs
return grammar

# Main program
if __name__ == "__main__":
print("Enter the grammar productions:")
user_grammar = parse_grammar()

# Eliminate left recursion


eliminated_grammar = eliminate_left_recursion(user_grammar)

# Print the modified grammar


print("\nModified Grammar after eliminating left recursion:")
for non_terminal, productions in eliminated_grammar.items():
print(f"{non_terminal} -> {' | '.join(productions)}")

OUTPUT: -
Enter the grammar productions:
Enter production (or type 'done' to finish): E -> E + T | T
Enter production (or type 'done' to finish): T -> T * F | F
Enter production (or type 'done' to finish): F -> (E)|id
Enter production (or type 'done' to finish): done

Modified Grammar after eliminating left recursion:


E -> TE'
T -> FT'
F -> (E) | id
E' -> + TE' | ε
T' -> * FT' | ε
EXP NO 5
Program: -
gram = {
"E":["2E2","3E3","4"]
}
starting_terminal = "E"
inp="2324232$"
stack = "$"
print(f'{"Stack": <15}'+"/"+f'{"Input Buffer": <15}'+"|"+f'Parsing Action')
print(f'{"-":-<50}')
while True:
action = True
i=0
while i<len(gram[starting_terminal]):
if gram[starting_terminal][i] in stack:
stack = stack.replace(gram[starting_terminal][i],starting_terminal)
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Reduce S->{gram[starting_terminal][i]}')
i=-1
action = False
i+=1
if len(inp)>1:
stack+=inp[0]
inp=inp[1:]
print(f'{stack: <15}'+"/"+f'{inp: <15}'+"|"+f'Shift')
action = False
if inp == "$" and stack ==("$"+starting_terminal):
print(f'{stack: <15}'+"/"+f'{inp: <15}'+"/"+f'Accepted')
break
if action:
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Rejected')
break
OUTPUT: -
Stack /Input Buffer |Parsing Action
--------------------------------------------------
$2 /324232$ |Shift
$23 /24232$ |Shift
$232 /4232$ |Shift
$2324 /232$ |Shift
$232E |232$ |Reduce S->4
$232E2 /32$ |Shift
$23E |32$ |Reduce S->2E2
$23E3 /2$ |Shift
$2E |2$ |Reduce S->3E3
$2E2 /$ |Shift
$E |$ |Reduce S->2E2
$E /$ /Accepted
EXP NO 6
Program: -
OPERATORS = set(['+', '-', '*', '/', '(', ')'])
PRI = {'+':1, '-':1, '*':2, '/':2}

### INFIX ===> POSTFIX ###


def infix_to_postfix(formula):
stack = [] # only pop when the coming op has priority
output = ''
for ch in formula:
if ch not in OPERATORS:
output += ch
elif ch == '(':
stack.append('(')
elif ch == ')':
while stack and stack[-1] != '(':
output += stack.pop()
stack.pop() # pop '('
else:
while stack and stack[-1] != '(' and PRI[ch] <= PRI[stack[-1]]:
output += stack.pop()
stack.append(ch)
# leftover
while stack:
output += stack.pop()
print(f'POSTFIX: {output}')
return output

### INFIX ===> PREFIX ###


def infix_to_prefix(formula):
op_stack = []
exp_stack = []
for ch in formula:
if not ch in OPERATORS:
exp_stack.append(ch)
elif ch == '(':
op_stack.append(ch)
elif ch == ')':
while op_stack[-1] != '(':
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+b+a )
op_stack.pop() # pop '('
else:
while op_stack and op_stack[-1] != '(' and PRI[ch] <= PRI[op_stack[-1]]:
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+b+a )
op_stack.append(ch)
# leftover
while op_stack:
op = op_stack.pop()
a = exp_stack.pop()
b = exp_stack.pop()
exp_stack.append( op+b+a )
print(f'PREFIX: {exp_stack[-1]}')
return exp_stack[-1]

### THREE ADDRESS CODE GENERATION ###


def generate3AC(pos):
print("### THREE ADDRESS CODE GENERATION ###")
exp_stack = []
t=1

for i in pos:
if i not in OPERATORS:
exp_stack.append(i)
else:
print(f't{t} := {exp_stack[-2]} {i} {exp_stack[-1]}')
exp_stack=exp_stack[:-2]
exp_stack.append(f't{t}')
t+=1

expres = input("INPUT THE EXPRESSION: ")


pre = infix_to_prefix(expres)
pos = infix_to_postfix(expres)
generate3AC(pos)

OUTPUT: -
INPUT THE EXPRESSION: a+b*9-d+c
PREFIX: +-+a*b9dc
POSTFIX: ab9*+d-c+
### THREE ADDRESS CODE GENERATION ###
t1 := b * 9
t2 := a + t1
t3 := t2 - d
t4 := t3 + c
EXP NO 7
Program: -
import re
expr_buffer = []
optm_code = []
with open(r"sample_code_unopt.txt") as source:
code = source.readlines()
source.close()
print("\nInput Expressions: \n")
for line in code:
print(line)
for line in code:
spline = line.replace(" ", "")
if "=" in spline:
expr = (re.findall(r"(\w)+=\S*", spline))
for y in expr_buffer:
for x in y:
if expr[0] == x:
expr_buffer.remove(y)
if "/" in spline:
expr = (re.findall(r"[a-zA-Z]+[\d]*/[a-zA-Z]+[\d]*", spline))
for x in expr:
if x not in expr_buffer:
expr_buffer.append(x)
s = "t"+ str(expr_buffer.index(x))
optm_code.append(s + " = " + x + "\n")
spline = spline.replace(x, s)
else:
s = "t" + str(expr_buffer.index(x))
spline = spline.replace(x, s)
if "*" in spline:
expr = (re.findall(r"[a-zA-Z]+[\d]*\*[a-zA-Z]+[\d]*", spline))
for x in expr:
if x not in expr_buffer:
expr_buffer.append(x)
s = "t"+ str(expr_buffer.index(x))
optm_code.append(s + " = " + x + "\n")
spline = spline.replace(x, s)
else:
s = "t" + str(expr_buffer.index(x))
spline = spline.replace(x, s)
if "+" in spline:
expr = (re.findall(r"[a-zA-Z]+[\d]*\+[a-zA-Z]+[\d]*", spline))
for x in expr:
if x not in expr_buffer:
expr_buffer.append(x)
s = "t"+ str(expr_buffer.index(x))
optm_code.append(s + " = " + x + "\n")
spline = spline.replace(x, s)
else:
s = "t" + str(expr_buffer.index(x))
spline = spline.replace(x, s)
if "-" in spline:
expr = (re.findall(r"[a-zA-Z]+[\d]*-[a-zA-Z]+[\d]*", spline))
for x in expr:
if x not in expr_buffer:
expr_buffer.append(x)
s = "t"+ str(expr_buffer.index(x))
optm_code.append(s + " = " + x + "\n")
spline = spline.replace(x, s)
else:
s = "t" + str(expr_buffer.index(x))
spline = spline.replace(x, s)
optm_code.append(spline)
print("\nOptimized Expressions with computed compiler variable assignments: \n")
for line in optm_code:
print(line)

OUTPUT: -
Input Expressions:
c = a/b * d
a=c*d
f = a/b * c/d + e
g = f * a/b - c/d
Optimized Expressions with computed compiler variable assignments:
t0 = a/b
t1 = t0*d
c=t1
t1 = c*d
a=t1
t2 = a/b
t3 = c/d
t4 = t2*t3
t5 = t4+e
f=t5
t6 = f*t2
t7 = t6-t3
g=t7
EXP NO 8
Program: -
import re

f = open("IntermediateCode.txt", 'r')
lines = f.readlines()
f.close()

fifo_return_reg = 'R0'
reg = [0] * 13
var = {}
store_seq = []
fifo_reg = 0
operator_list = {'+': 'ADD', '-': 'SUB', '*': 'MUL', '/': 'DIV', '=': 'MOV', '==': 'NE', '>': 'G', '>=': 'GE', '<': 'L',
'<=': 'LE', 'and': 'AND', 'or': 'OR'}

def fifo():
global fifo_reg
global fifo_return_reg
for k, v in var.copy().items():
if v == 'R' + str(fifo_reg):
fifo_return_reg = v
var.pop(k)
if k in store_seq:
store_seq.remove(k)
print("ST", k, ',', v, sep='')
fifo_reg = int(fifo_return_reg[1:]) + 1
return fifo_return_reg

def getreg():
for i in range(0, 13):
if reg[i] == 0:
reg[i] = 1
return 'R' + str(i)
register = fifo()
return register

for line in lines:


line = line.strip()
if not line:
continue

line = line.split()
length = len(line)

if length == 0:
continue
if length == 1:
print(line[0])
continue

if re.match(r'^t[0-9]+$', line[0]):
continue

if length == 3:
lhs = line[0]
operand = line[2]
if operand not in var:
var[operand] = getreg()
if operand.isalpha():
print("LD", var[operand], ', ', operand, sep="")
else:
print("MOV", var[operand], ', #', operand, sep="")
if lhs in store_seq:
old_reg = var[lhs]
store_seq.remove(lhs)
print("ST", lhs, ',', old_reg, sep='')
var[lhs] = var[operand]
store_seq.append(lhs)

elif 'goto' in line:


if 'if' in line:
operand = line[1]
label = line[3]
if operand not in var:
var[operand] = getreg()
if operand.isalpha():
print("LD", var[operand], ', ', operand, sep="")
else:
print("MOV", var[operand], ', #', operand, sep="")
print("BNEZ", var[operand], ',', label)
else:
print("BR", line[1])

else:
if len(line) >= 5:
oper = line[3]
operand1 = line[2]
operand2 = line[4]
lhs = line[0]
if operand1 not in var:
var[operand1] = getreg()
if operand1.isalpha():
print("LD", var[operand1], ', ', operand1, sep="")
else:
print("MOV", var[operand1], ', #', operand1, sep="")
if operand2 not in var:
var[operand2] = getreg()
if operand2.isalpha():
print("LD", var[operand2], ', ', operand2, sep="")
else:
print("MOV", var[operand2], ', #', operand2, sep="")
operator_print = operator_list.get(oper)
if operator_print:
if lhs in store_seq:
old_reg = var[lhs]
store_seq.remove(lhs)
print("ST", lhs, ',', old_reg, sep='')
var[lhs] = getreg()
store_seq.append(lhs)
print(operator_print, var[lhs], ',', var[operand1], ',', var[operand2], sep=' ')

else:
operand = line[3]
lhs = line[0]
if operand not in var:
var[operand] = getreg()
if operand.isalpha():
print("LD", var[operand], ', ', operand, sep="")
else:
print("MOV", var[operand], ', #', operand, sep="")
if lhs in store_seq:
old_reg = var[lhs]
store_seq.remove(lhs)
print("ST", lhs, ',', old_reg, sep='')
var[lhs] = getreg()
store_seq.append(lhs)
print("NOT", var[lhs], ',', var[operand], sep='')

for i in store_seq:
print("ST", i, ',', var[i], sep='')

IntermediateCode.txt
a = 10
b=9
t0= 10 + 9
tl = 19 + 100
c = 119
e = 10
f=8
t2 = 10 * 8
d = 80
|0:
t3 = 10 >= 9
t4 = not 1
if 0 goto |1
a = 19
15 = 80 * 100
g = 8000
|1:
u = 10
j = 99

OUTPUT: -

MOVR0, #10
MOVR1, #9
NOTR2,R1
MOVR3, #19
MOVR4, #100
ADD R5 , R3 , R4
MOVR6, #119
MOVR7, #8
MOVR8, #80
|0:
MOVR9, #0
BNEZ R9 , |1
STa,R0
MUL R10 , R8 , R4
MOVR11, #8000
|1:
MOVR12, #99
STb,R1
STt0=,R2
STtl,R5
STc,R6
STe,R0
STf,R7
STd,R8
STa,R3
ST15,R10
STg,R11
STu,R0
STj,R12

You might also like