0% found this document useful (0 votes)
15 views

Experiment No4

The document outlines an experiment for students at Don Bosco Institute of Technology to design and implement Pass 1 of a macro processor, focusing on identifying macros in a program and displaying relevant tables. It includes objectives, theoretical background on macros, an algorithm for processing macros, and a sample program code for implementation. The experiment aims to enhance students' understanding of macro definitions, their usage, and the automation benefits they provide in programming.

Uploaded by

amishav2004
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 views

Experiment No4

The document outlines an experiment for students at Don Bosco Institute of Technology to design and implement Pass 1 of a macro processor, focusing on identifying macros in a program and displaying relevant tables. It includes objectives, theoretical background on macros, an algorithm for processing macros, and a sample program code for implementation. The experiment aims to enhance students' understanding of macro definitions, their usage, and the automation benefits they provide in programming.

Uploaded by

amishav2004
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/ 5

Don Bosco Institute of Technology, Kulra(W)

Department of Computer Engineering


CSL601: System Programming and Compiler Construction Lab 2024-25

Experiment No. 04

Experiment Title Design and Implement Pass 1 of a Macro processor

Task: Write a program to read a given text file which can


identify the macros in the program and display MNT, MDT
and Argument List Array.

Student Name Amisha Verma

Roll No. 66

Objectives: 1) Students will be able to learn and identify macro definition

And macro name in a given program.

2) Students will be able to understand the use of Macros in a

program.

Theory /Algorithm: What is a Macro?


A macro is a set of instructions or a sequence of commands that can be
recorded, stored, and executed automatically to perform repetitive
tasks efficiently. Macros are commonly used in programming, word
processing, and spreadsheets to automate workflows and save time.

Types of Macros
1. Keyboard Macros – Automate sequences of keystrokes or mouse
actions.
2. Programming Macros – Shortcuts in languages like C, C++,
Python, and Assembly to expand complex code.
3. Excel & Word Macros – Used in Microsoft Office (VBA) to
automate document editing or data processing.

Examples of Macros
1. C Programming Macro (Preprocessor Directive)
#include <stdio.h>
#define PI 3.14159 // Macro definition

int main() {
printf("The value of PI is %f\n", PI);
return 0;
}
Advantage: PI is replaced at compile time, improving performance.

2. Excel VBA Macro


Sub AutoFillData()
Range("A1:A10").Value = "Hello, Macro!"
End Sub
Advantage: Automates filling cells in Excel.

Advantages of Macros
Automation – Reduces repetitive work.
Faster Execution – Macros expand at compile time in programming.
Reduces Errors – Minimizes human mistakes.
Disadvantages of Macros
Hard to Debug – Errors in macros can be difficult to track.
Security Risks – Malicious macros (e.g., in VBA) can execute
harmful code.
Not Flexible – Limited compared to full-fledged functions in some
cases.

Where Are Macros Used?


• Software Development – Code simplification in C, C++, and
Assembly.
• Office Applications – Automating tasks in Excel, Word, and
PowerPoint.
• Game Development – Automating player actions (e.g., scripting in
Unity).
• Cybersecurity – Both for automation and potential threats (e.g.,
macro viruses).
Algorithm for Pass 1 of Macro Processor
Input: Assembly program with macro definitions.
Output: Macro Name Table (MNT), Macro Definition Table (MDT),
and Argument List Array (ALA).
1. Initialize tables:
o Create Macro Name Table (MNT) to store macro names
and their positions in MDT.
o Create Macro Definition Table (MDT) to store macro
instructions.
o Create Argument List Array (ALA) to handle macro
parameters.
2. Read next line from source code.
o If MACRO is encountered:
▪ Read the macro name and store it in MNT with an
index to MDT.
▪ Store macro parameters in ALA (assign argument
indices like &ARG1, &ARG2).
▪ Continue reading lines until MEND is found.
3. Store macro definition in MDT:
o Replace parameters with positional indices (#1, #2, etc.)
using ALA.
o Continue storing macro body in MDT until MEND is
found.
o Mark MEND in MDT.
4. If a normal instruction (not a macro definition), write it to the
output (pass it through).
5. Repeat until the end of the source file.

Program Code: import re

def process_macros(file_path, output_file):


macro_name_table = {}
macro_definition_table = {}
argument_list_array = {}
expanded_code = []

with open(file_path, 'r') as file:


lines = file.readlines()
macro_flag = False
macro_name = ''
argument_list = []
macro_definition = []

for line in lines:


line = line.strip()

if line.startswith('MACRO'):
parts = re.findall(r'\w+', line)

# Ensure MACRO line has at least a name


if len(parts) < 2:
print("Error: Invalid MACRO definition (missing name)")
return

macro_flag = True
macro_name = parts[1]
argument_list = parts[2:] # Extract arguments if any
argument_list_array[macro_name] = argument_list
macro_name_table[macro_name] =
len(macro_definition_table) # Store MDT index
macro_definition = []

elif line.startswith('MEND'):
if not macro_flag:
print("Error: Found MEND without a MACRO definition")
return

macro_flag = False
macro_definition_table[macro_name] = macro_definition

elif macro_flag:
macro_definition.append(line)

else:
# Check if the line contains a macro invocation
for macro, arguments in argument_list_array.items():
if macro in line:
parts = line.split()
macro_index = parts.index(macro)
arguments_values = parts[macro_index + 1:] # Get
arguments passed

# Ensure correct number of arguments


if len(arguments_values) != len(arguments):
print(f"Error: Argument count mismatch for macro
{macro}")
return

# Replace macro definition placeholders with actual values


expanded_lines = []
for macro_line in macro_definition_table[macro]:
for i, arg in enumerate(arguments):
macro_line = macro_line.replace(arg,
arguments_values[i])
expanded_lines.append(macro_line)

expanded_code.extend(expanded_lines)
break
else:
expanded_code.append(line)

# Save output to file


with open(output_file, 'w') as out_file:
out_file.write("Expanded Assembly Code:\n")
out_file.writelines('\n'.join(expanded_code) + '\n')

out_file.write("\nMacro Name Table (MNT):\n")


out_file.write(str(macro_name_table) + '\n')

out_file.write("\nMacro Definition Table (MDT):\n")


out_file.write(str(macro_definition_table) + '\n')

out_file.write("\nArgument List Array:\n")


out_file.write(str(argument_list_array) + '\n')

print(f"Macro processing completed. Output saved in '{output_file}'.")

# Example usage
file_path = 'assembly_code.txt'
output_file = 'output.txt'
process_macros(file_path, output_file)

Input to the MACRO MULTIPLY &X &Y &RESULT


Program: MOVER A, &X
MUL &Y
MOVEM A, &RESULT
MEND

MACRO SQUARE &NUM &RES


MULTIPLY &NUM &NUM &RES
MEND

MULTIPLY 5 10 RESULT1
SQUARE 4 RESULT2
END
Output of the
program:
Outcome of the
Experiment:
References:

You might also like