3
1
SystemsProgrammingAndOperat.../Codes/Python version/Assignment-A2 (Macro)/Code-A2.py

110 lines
2.6 KiB
Python
Raw Permalink Normal View History

try:
source = open('source1.txt', 'r')
print("File is read successfully.")
source.seek(0)
except FileNotFoundError:
print('\n\n\nsource2.txt file not found. Create it first!\n\n\n')
except IOError:
print('The source file has an IO error')
MDT = [] # Macro Definition Table
MNT = [] # Macro Name Table
LIT = [] # Literal Table
LPT = [] # Literal Pool Table
def macroman(line):
name = line.split()[1]
entry = []
entry.append(line.strip())
while True:
line = source.readline().upper()
if not line:
print('No MEND found for: ', name)
return
if 'MACRO' in line:
macroman(line)
elif 'MEND' in line:
global MDT, MNT
entry.append(line.strip())
MNT.append([len(MNT) + 1, name, len(MDT) + 1])
MDT.extend(entry)
return
else:
entry.append(line.strip())
# Check for literals and add to the literal table
for word in line.split():
if word.startswith('='): # Assuming literals start with '='
if word not in LIT:
LIT.append(word)
def pass1():
global MDT, MNT, LIT
while True:
line = source.readline().upper()
if not line: break
if 'MACRO' in line:
macroman(line)
print('\nMNT:')
for a in MNT:
print(a)
print('\nMDT:')
for i, a in enumerate(MDT, start=1):
print(i, ' ', a)
print('\nLIT:')
for i, lit in enumerate(LIT, start=1):
print(i, ' ', lit)
pass1()
def inserter(sline, name):
global MDT, MNT
sline = ''
for a in MNT:
if a[1] == name:
add = a[2]
break
while True:
if 'MEND' in MDT[add]:
break
sline += MDT[add] + '\n'
add += 1
return sline
def pass2():
source.seek(0)
output = open('output.txt', 'w')
output.close()
output = open('output.txt', 'a+')
while True:
sline = source.readline().upper()
if not sline: break
for a in MNT:
if a[1] in sline and 'MACRO' not in sline:
sline = inserter(sline, a[1])
d = sline.strip()
# Check for literals in the output line
for word in d.split():
if word.startswith('='):
if word not in LPT: # If not already in the literal pool table
LPT.append(word)
if d not in MDT:
output.write(sline)
print('done.')
print('\nLPT:')
for i, lpt in enumerate(LPT, start=1):
print(i, ' ', lpt)
pass2()