CompilerConsLab Pranjal
CompilerConsLab Pranjal
Sol:-
#include<stdio.h>
#include<ctype.h>
int i = 0;
if (isalpha(code[i])) {
} else if (isdigit(code[i])) {
} else {
i++;
int main() {
lexicalAnalysis(code)
return 0;
}
Lexical Analysis Output:
Identifier: a
Operator: =
Number: 5
Operator: +
Number: 9
2.Write a program to identify macro definitions in an assembly language program. Extend the
above program to implement simple and recursive macro expansion.
Sol:-
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
// Sample assembly language program with macro definitions
vector<string> program = {
"MACRO INCR",
"ADD 1",
"MEND",
"MACRO DOUBLE",
"INCR",
"INCR",
"MEND",
"START",
"INCR",
"DOUBLE",
"END"
};
identifyMacroDefinitions(program);
return 0;
}
Macro Definition Found: INCR
Macro Body:
ADD 1
End of Macro: INCR
Macro Definition Found: DOUBLE
Macro Body:
INCR
INCR
End of Macro: DOUBLE
3.Write a program to process 'include' and 'define' macros in C language. Write a program to parse
source code strings of C-language and identify tokens in terms of Keywords and identifiers.
Sol:-
#include <iostream>
#include <string>
#include <map>
#include <vector>
if (line.find("#include") != string::npos) {
cout << "Processing include file: " << headerFile << endl;
defineTable[macroName] = macroValue;
cout << "Macro defined: " << macroName << " -> " << macroValue << endl;
}
int main() {
vector<string> sourceCode = {
"#include <stdio.h>",
"#define PI 3.14",
};
// Process macros
processMacros(sourceCode);
return 0;
}
Processing include file: <stdio.h>
Macro defined: PI -> 3.14
Macro defined: MAX -> 100
4. Write a program to process 'include' and 'define' macros in C language. Write a program to parse source
code strings of C-language and identify tokens in terms of Keywords and identifiers.
Sol:-
#include <iostream>
#include <string>
#include <stack>
struct Node {
string value;
Node* left;
Node* right;
};
// Function to print the parse tree in an inorder traversal (for visualizing the structure)
printInOrder(root->left);
printInOrder(root->right);
if (isalnum(ch)) {
operands.push(createNode(string(1, ch)));
char op = operators.top();
operators.pop();
// Create a new node with the operator and the two operands
operatorNode->left = left;
operatorNode->right = right;
operands.push(operatorNode);
operators.push(ch);
while (!operators.empty()) {
char op = operators.top();
operators.pop();
Node* right = operands.top(); operands.pop();
operatorNode->left = left;
operatorNode->right = right;
operands.push(operatorNode);
return operands.top();
int main() {
printInOrder(root);
return 0;
}
Parse Tree (In-Order Traversal):
/\
a +
/\
b *
/\
c d