compiler practical file (1)
compiler practical file (1)
Submitted By:
Name Roll No.
Sumit 2022UIT3121
Code:
#include <iostream>
#include <string>
#include <unordered_set>
#include <cctype>
bool isConsonant(char c) {
string vowels = "aeiouAEIOU";
return isalpha(c) && vowels.find(c) == string::npos;
}
unordered_set<string> keywords = {
"auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed",
"sizeof", "static", "struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while"
};
if (state == "start") {
if (ch == '/') {
buffer += ch;
state = "maybe_comment";
index++;
} else if (isalpha(ch) || ch == '_') {
buffer += ch;
state = "identifier";
index++;
} else {
index++;
}
} else if (state == "maybe_comment") {
if (ch == '*') {
buffer.clear();
state = "in_comment_block";
index++;
} else if (ch == '/') {
buffer.clear();
state = "in_comment_line";
index++;
} else {
buffer.clear();
state = "start";
}
} else if (state == "in_comment_block") {
if (ch == '*') {
state = "maybe_end_block";
}
buffer += ch;
index++;
} else if (state == "maybe_end_block") {
if (ch == '/') {
buffer.pop_back(); // Remove the last '*'
cout << "Comment: " << buffer << endl;
buffer.clear();
state = "start";
} else {
state = "in_comment_block";
buffer += ch;
}
index++;
} else if (state == "in_comment_line") {
if (ch == '\n') {
cout << "Comment: " << buffer << endl;
buffer.clear();
state = "start";
} else {
buffer += ch;
}
index++;
} else if (state == "identifier") {
if (isalnum(ch) || ch == '_') {
buffer += ch;
index++;
} else {
if (keywords.find(buffer) != keywords.end()) {
cout << "Keyword: " << buffer << endl;
} else {
bool hasLetters = false;
bool allConsonant = true;
int main() {
string input = R"(
int main() {
// This is a comment
int xyz = 123;
char consonant_test = 'a';
/* Another comment */
if (xyz) {
return 0;
}
}
)";
analyze(input);
return 0;
}
OUTPUT:
Practical – 2
Aim: Write a program for predictive parsing, in C language.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int i=0,top=0;
char stack[20],ip[20];
void pop(void){
if(top<0){
printf("Stack underflow\n");
exit(1);
}else{
top--;
}
}
void error(void){
printf("\n\nSyntax Error!!!! String is invalid\n");
exit(0);
}
int main(){
int n;
printf("The given grammar is:\n\n");
printf("E -> TE'\n");
printf("E' -> +TE' | epsilon\n");
printf("T -> FT'\n");
printf("T' -> *FT' | epsilon\n");
printf("F -> (E) | d\n\n");
push('$');
push('E');
while(ip[i]!='\0'){
if(ip[i]=='$' && stack[top-1]=='$'){
printf("\n\nSuccessful parsing of string\n");
return 1;
}
else if(ip[i]==stack[top-1]){
printf("\nMatch of %c\n",ip[i]);
i++;
pop();
}
else{
if(stack[top-1]=='E' && (ip[i]=='d' || ip[i]=='(')){
printf("\nE -> TE'\n");
pop();
push('\'');
push('T');
}
else if(stack[top-1]=='\'' && ip[i]=='+'){
printf("\nE' -> +TE'\n");
pop();
push('\'');
push('T');
push('+');
}
else if(stack[top-1]=='\'' && (ip[i]==')' || ip[i]=='$')){
printf("\nE' -> epsilon\n");
pop();
}
else if(stack[top-1]=='T' && (ip[i]=='d' || ip[i]=='(')){
printf("\nT -> FT'\n");
pop();
push('\'');
push('F');
}
else if(stack[top-1]=='\'' && ip[i]=='*'){
printf("\nT' -> *FT'\n");
pop();
push('\'');
push('F');
push('*');
}
else if(stack[top-1]=='\'' && (ip[i]=='+' || ip[i]==')' || ip[i]=='$')){
printf("\nT' -> epsilon\n");
pop();
}
else if(stack[top-1]=='F' && ip[i]=='d'){
printf("\nF -> d\n");
pop();
push('d');
}
else if(stack[top-1]=='F' && ip[i]=='('){
printf("\nF -> (E)\n");
pop();
push(')');
push('E');
push('(');
}
else{
error();
}
}
}
return 0;
}
Output:
Practical – 3
Aim: Write a program to convert infix to postfix using Lex and Yacc .
Code:
infix_to_postfix.y -
%{
#include<stdio.h>
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right NEGATIVE
%%
S: E {printf("\n");}
;
E: E '+' E {printf("+");}
| E '*' E {printf("*");}
| E '-' E {printf("-");}
| E '/' E {printf("/");}
| '(' E ')'
| '-' E %prec NEGATIVE {printf("-");}
| NUM {printf("%d", yylval);}
;
%%
int main(){
yyparse();
}
int yyerror (char *msg) {
return printf ("error YACC: %s\n", msg);
}
infix_to_postfix.l -
%{
#include"infix_to_postfix.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUM;}
\n return 0;
. return *yytext;
%%
int yywrap(){
return 1;
}
Practical – 4
Aim: Write a program to implement symbol table.
Code:
unordered_map<string, string> m;
void display() {
if (m.empty()) {
return;
cout << ite.first << " is present at " << ite.second << endl;
int main() {
int n;
do {
cin >> n;
switch (n) {
case 1: { // Insert
string x, y;
if (m.find(x) != m.end()) {
} else {
m[x] = y;
break;
case 2: { // Display
display();
break;
case 3: { // Delete
string x;
cin >> x;
if (m.find(x) == m.end()) {
} else {
m.erase(x);
break;
case 4: { // Search
string x;
cin >> x;
if (m.find(x) != m.end()) {
cout << "The label is already in the symbol table at address: " << m[x]
<< endl;
} else {
break;
case 5: { // Modify
string x, newAddr;
cin >> x;
if (m.find(x) == m.end()) {
else {
m[x] = newAddr;
break;
case 6: { // Exit
break;
default:
} while (n != 6);
return 0;
}
Output:
Practical – 5
Aim: Write a program to implement a simple calculator using Lex and Yacc.
Code:
calc.y -
%{
#include <stdio.h>
#include <stdlib.h>
%union {
int ival;
float fval;
}
%token<ival> T_INT
%token<fval> T_FLOAT
%token T_PLUS T_MINUS T_MULTIPLY T_DIVIDE T_LEFT T_RIGHT
%token T_NEWLINE T_QUIT
%left T_PLUS T_MINUS
%left T_MULTIPLY T_DIVIDE
%type<ival> expression
%type<fval> mixed_expression
%start calculation
%%
calculation:
| calculation line
;
line: T_NEWLINE
| mixed_expression T_NEWLINE { printf("\tResult: %f\n", $1);}
| expression T_NEWLINE { printf("\tResult: %i\n", $1); }
| T_QUIT T_NEWLINE { printf("bye!\n"); exit(0); }
;
mixed_expression: T_FLOAT { $$ = $1; }
| mixed_expression T_PLUS mixed_expression { $$ = $1 + $3; }
| mixed_expression T_MINUS mixed_expression { $$ = $1 - $3; }
| mixed_expression T_MULTIPLY mixed_expression { $$ = $1 * $3; }
| mixed_expression T_DIVIDE mixed_expression { $$ = $1 / $3; }
| T_LEFT mixed_expression T_RIGHT { $$ = $2; }
| expression T_PLUS mixed_expression { $$ = $1 + $3; }
| expression T_MINUS mixed_expression { $$ = $1 - $3; }
| expression T_MULTIPLY mixed_expression { $$ = $1 * $3; }
| expression T_DIVIDE mixed_expression { $$ = $1 / $3; }
| mixed_expression T_PLUS expression { $$ = $1 + $3; }
| mixed_expression T_MINUS expression { $$ = $1 - $3; }
| mixed_expression T_MULTIPLY expression { $$ = $1 * $3; }
| mixed_expression T_DIVIDE expression { $$ = $1 / $3; }
| expression T_DIVIDE expression { $$ = $1 / (float)$3; }
;
%%
int main() {
yyin = stdin;
do {
yyparse();
} while(!feof(yyin));
return 0;
}
calc.l -
%option noyywrap
%{
#include <stdio.h>
#define YY_DECL int yylex()
#include "calc.tab.h"
%}
%%
%%
Practical 6
Code:
c_lex_analyser.l -
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.*\n {printf("%sThis is a PREPROCESSOR DIRECTIVE\n",yytext);}
auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|go
to|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|uns
igned|void|volatile|while {printf("\n%s is a KEYWORD",yytext);}
"/*" {COMMENT = 1;}
"*/" {COMMENT = 0;}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION: \n%s",yytext);}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n%s is an IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n%s is a NUMBER ",yytext);}
\{ {if(!COMMENT) printf("\nBLOCK BEGINS");}
\} {if(!COMMENT) printf("\nBLOCK ENDS");}
\) {if(!COMMENT);printf("\n)");}
= {if(!COMMENT) printf("\n%s is an ASSIGNMENT OPERATOR",yytext);}
\<= | \>= | \< | \== | \!= | \> {if(!COMMENT) printf("\n%s is a RELATIONAL
OPERATOR",yytext);}
\, | \; {if(!COMMENT) printf("\n%s is a SEPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("input.c","r");
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{ return(1);
}
Output:-
input.c -
#include <stdio.h>
#define PI 3.14
struct inp
{
int a;
};
int check(int a, int b)
{
return (a > b);
}
int main()
{
struct inp ab;
int r = 5;
printf("abc");
return 0;
}
Practical 7
Aim: Write a program to implement parser for C language.
Code:
YACC CODE
%{
#include <stdio.h>
#include <stdlib.h>
%}
%union {
int number;
char* str;
}
%%
program:
declarations
;
declarations:
declaration
| declarations declaration
;
declaration:
type_specifier IDENTIFIER SEMICOLON
| type_specifier IDENTIFIER ASSIGN expression
SEMICOLON ;
type_specifier:
INT
| FLOAT
| VOID
;
expression:
NUMBER
| IDENTIFIER
| expression PLUS expression
| expression MINUS expression
| expression STAR expression
| expression SLASH expression
;
%%
int main(void) {
printf("Enter the C code:\n");
yyparse();
return 0;
}
OUTPUT:
I
Practical 8
Code:
three_address.l
%{
#include"three_address.tab.h" extern
char yyval;
%}
%%
%%
three_address.y
%{
#include"three_address.tab.h"
#include<stdio.h>
char addtotable(char,char,char);
struct expr{
%}
%union{ char
symbol;
}
%%
yyerror(char *s){
printf("Errror %s",s);
}
void threeAdd(){
int i=0;
char temp='A'; while(i<index1){
printf("%c:=\t",arr[i].result);
printf("%c\t",arr[i].operand1);
printf("%c\t",arr[i].operator);
printf("%c\t",arr[i].operand2);
i++;
temp++; printf("\n");
}
}
int yywrap(){
return 1;
}
int main(){
printf("Enter the expression: ");
yyparse();
printf("\n");
threeAdd();
printf("\n"); return
0;
}
Output:-