Principles of Compiler Construction Lab File NSUT
Principles of Compiler Construction Lab File NSUT
Principles of Compiler Construction Lab File NSUT
right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
printf("%s\n", subStr);
left = right;
}
}
return;
}
int main()
{
char str[100] = "while(1){int a = 4};";
parse(str);
return (0);
}
Output:
Experiment 2
AIM: Write a program to implement lexical analysis phase
of a compiler.
Implementation:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
right++;
left = right;
if (isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr);
left = right;
}
}
return;
}
int main()
{
char str[100] = "while(1){int a = 4.6};";
parse(str);
return (0);
}
Output:
Experiment 3
Desk calculator
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
while (!iss.eof()) {
std::string token;
iss >> token;
while (!operatorStack.empty()) {
double b = operandStack.top();
operandStack.pop();
double a = operandStack.top();
operandStack.pop();
char op = operatorStack.top();
operatorStack.pop();
return operandStack.top();
}
int main() {
std::string expression;
std::cout << "Enter an arithmetic expression: ";
std::getline(std::cin, expression);
return 0;
}
2. ASSEMBLER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
3
SymbolTableEntry symbolTable[MAX_SYMBOLS];
int symbolCount = 0;
// Functions
int searchSymbolTable(char label[10]) {
for (int i = 0; i < symbolCount; i++) {
if (strcmp(symbolTable[i].label, label) == 0) {
return symbolTable[i].address;
}
}
return -1;
}
int main() {
char line[MAX_LINE_LENGTH];
char mnemonic[10];
char label[10];
char operand[10];
int address = 0;
int machineCode = 0;
if (!inputFile) {
printf("Error: Unable to open input file.\n");
return 1;
}
if (!outputFile) {
printf("Error: Unable to open output file.\n");
return 1;
}
4
machineCode = 0xF000;
} else {
printf("Error: Invalid mnemonic '%s'.\n", mnemonic);
return 1;
}
if (operand[0] != '\0') {
int operandValue = searchSymbolTable(operand);
if (operandValue == -1) {
printf("Error: Undefined label '%s'.\n", operand);
return 1;
}
machineCode += operandValue;
}
fclose(inputFile);
fclose(outputFile);
printf("Assembly completed successfully.\n");
return 0;
}
RESULTS
Output:
a. Desk Calculator
5
ASSEMBLER O/P:
6
Experiment 4
1. Data Types:
• Integer (int): Represents whole numbers.
• Float (float): Represents numbers with decimal points.
• String (str): Represents text.
2. Variables:
• Variables are defined with the var keyword.
• Variables are dynamically typed (no need to specify data types explicitly).
3. Operators:
• Arithmetic operators: +, -, *, /, % (modulo)
• Comparison operators: ==, !=, <, >, <=, >=
• Logical operators: and, or, not
4. Control Flow:
• Conditional statements: if, else if, else
• Looping: for and while loops
5. Functions:
• Functions are defined with the func keyword.
• Support for parameters and return values.
6. Comments:
• Single-line comments using #
7
Source Code:
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <cstdlib>
while (!operators.empty()) {
char op = operators.top();
operators.pop();
8
int right = values.top();
values.pop();
int left = values.top();
values.pop();
if (op == '+') {
values.push(left + right);
} else if (op == '-') {
values.push(left - right);
} else if (op == '*') {
values.push(left * right);
} else if (op == '/') {
values.push(left / right);
}
}
return values.top();
}
int main() {
string input;
while (true) {
cout << "Enter an arithmetic expression (or 'quit' to exit): ";
getline(cin, input);
if (input == "quit") {
break;
}
return 0;
}
EXAMPLE
9
Output:
10
Experiment 5
AIM
Develop a lexical analyzer and a syntax analyzer for the same using the LEX and
YACC tools. Also implement the bookkeeper module.
Implementation
1. Lexical Analyzer(lex):
11
2 Syntax Analyzer(Yacc/bison)
%{
#include <stdio.h>
int yylex(void);
%}
%token NUMBER
%%
if ($3 != 0) {
$$ = $1 / $3;
} else {
$$ = 0;
%%
int main() {
yyparse();
return 0;
}
12
Bookkeeper Module
You can create a file named bookkeeper.c with the following content:
#include <stdio.h>
void bookkeeper_module() {
Results
Compile
Input
Output
13
Experiment 6
AIM
Develop a simple calculator using LEX and YACC tools.
Implementation
RESULTS
15
Experiment 7
AIM
Implementation
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 11
char l[10];
struct symb
{
int add;
char label[10];
}sy[11];
void search();
void main()
{
int a[MAX],num,key,i,ch;
char ans;
int create(int);
void lprob(int [],int,int);
void display(int []);
system("cls");
for(i=0;i<MAX;i++)
a[i]=0;
do
{
printf("\nEnter your choice:");
printf("\n1 - Create entry in the symbol table\n2 - Search in the symbol table\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
do
{
printf("\nEnter the address:");
scanf("%d",&num);
key=create(num);
printf("Enter the label:");
scanf("%s",l);
lprob(a,key,num);
16
printf("\nContinue?\n0 for no\n1 for yes\n");
scanf("%s",ans);
}
while(ans==1);
display(a);
break;
case 2:
search();
break;
}
}while(ch<=2);
getch();
}
void search()
{
FILE *fp1;
char la[10];
int set=0,s;
int j,i;
printf("Enter the label: ");
scanf("%s",la);
fp1=fopen("symbol.txt","r");
for(i=0;i<MAX;i++)
{
fscanf(fp1,"%d%d",&j,&sy[i].add);
if(sy[i].add!=0)
fscanf(fp1,"%s",sy[i].label);
}
for(i=0;i<MAX;i++)
{
if(sy[i].add!=0)
{
18
if(strcmp(sy[i].label,la)==0)
{
set=1;
s=sy[i].add;
}
}
}
if(set==1)
printf("\nThe label '%s' is present in the symbol table at address:%d\n",la,s);
else
printf("\nThe label is not present in the symbol table\n");
}
RESULTS
19
20
21
EXPERIMENT-8
AIM
Implement a bottom-up parser using YACC tool.
Implementation
LEX file:
%{
#include<stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.dval=atof(yytext);
return DIGIT;
}
\n|. return yytext[0];
%%
YACC file:
%{
/*This YACC specification file generates the LALR parser for the program
considered in experiment 4.*/
#include<stdio.h>
%}
%union
{
double dval;
}
%token <dval> DIGIT
%type <dval> expr
%type <dval> term
%type <dval> factor
%%
line: expr '\n' {
printf("%g\n",$1);
}
;
expr: expr '+' term {$$=$1 + $3 ;}
| term
;
term: term '*' factor {$$=$1 * $3 ;}
| factor
22
;
factor: '(' expr ')' {$$=$2 ;}
| DIGIT
;
%%
int main()
{
yyparse();
}
yyerror(char *s)
{
printf("%s",s);
}
RESULT:
$lex parser.l
$yacc –d parser.y
$cc lex.yy.c y.tab.c –ll –lm
$./a.out
9+4
15.0000
23
EXPERIMENT-9
AIM
Represent ‘C’ language using Context Free Grammar
IMPLEMENTATION
program -> declaration-list
var -> ID
simple-expression -> additive-expression relop additive-expression
| additive-expression
addop -> + | -
24
term -> term mulop factor
| factor
mulop -> * | /
factor -> ( expression )
| var
| call
| NUM
25
EXPERIMENT-10
AIM
Add assignment statement, If then else statement and while loop to the calculator and generate the three address code for
the same
IMPLEMENTATION
import ply.yacc as yacc
# Tokens
tokens = (
'NUMBER',
'ID',
'ASSIGN',
'IF',
'THEN',
'ELSE',
'WHILE',
'PLUS',
'MINUS',
'TIMES',
'DIVIDE',
'LPAREN',
'RPAREN',
'SEMICOLON',
)
# Grammar
def p_program(p):
'''
program : statements
'''
p[0] = p[1]
def p_statements_empty(p):
'''
statements :
'''
p[0] = []
def p_statements_statement(p):
'''
statements : statements statement SEMICOLON
'''
p[0] = p[1] + [p[2]]
def p_statement_assign(p):
'''
statement : ID ASSIGN expression
'''
p[0] = ("=", p[1], p[3])
def p_statement_if(p):
'''
statement : IF expression THEN statements ELSE statements
'''
p[0] = ("if-else", p[2], p[4], p[6])
def p_statement_while(p):
'''
statement : WHILE expression statements
'''
p[0] = ("while", p[2], p[3])
26