180501002 PAGE NUMBER: CS18611 COMPILER DESIGN LABORATORY EXNO:1 IMPLEMENTATION OF SYMBOL TABLE DATE: AIM: To implement symbol table in C. ALGORITHM: Step 1: Start Step 2: Read the contents of the text file Step 3: Run a loop with the steps 4,5,6 until all the characters in the file is read Step 4: Read the characters in each line Step 5: Increment the value of i Step 6: Run a loop with the steps 7 to 12 till the condition j < i-1 remains true Step 7: Initialize the type pointer as a token using strtok( ) Step 8: Check for '{' in the type string using strcmp( ) to increment the depth value Step 9: Check for '}' in the type string using strcmp( ) to decrement the depth value Step 10: Classify the type string as “int” or “float” or “char” or “double” Step 11: Check for the identifiers using the strtok( ) Step 12: Print the type of identifiers,identifiers and address of identifiers along with the depth value Step 13:End PROGRAM: #include<stdio.h> #include<string.h> #include<stdlib.h> main() { FILE *fp; char line[100][100]; char *type,*var; int i=0,j,depth=0; fp=fopen("symbolfile.c","r"); while(!feof(fp)) { fgets(line[i],200,fp); i++; } printf("TYPE\tIDENTIFIER\tADDRESS\tDEPTH\n"); for(j=0;j<i-1;j++) { type=strtok(line[j]," "); 180501002 PAGE NUMBER: if(strncmp(type,"{",1)==0) { depth++; } else if(strncmp(type,"}",1)==0) { depth--; } if(strcmp(type,"int")==0||strcmp(type,"float")==0||strcmp(type,"double")==0|| strcmp(type,"char")==0) { while((var=strtok(NULL,",;\n"))!=NULL) { printf("%s\t%s\t%p\t%d\n",type,var,var,depth); } } } } symbolfile.c #include<stdio.h> main() { int a,b; { float c,d; double e,f; } char g,h; } SAMPLE OUTPUT: TYPE IDENTIFIER ADDRESS DEPTH int a 0x7fffccf41222 1 int b 0x7fffccf41224 1 float c 0x7fffccf412ee 2 float d 0x7fffccf412f0 2 double e 0x7fffccf41353 2 double f 0x7fffccf41355 2 char g 0x7fffccf41417 1 char h 0x7fffccf41419 1 RESULT: 180501002 PAGE NUMBER: Thus the C program for implementation of symbol table had been executed successfully. CS18611 COMPILER DESIGN LABORATORY EXNO:2 IMPLEMENTATION OF LEXICAL ANALYSER DATE: AIM: To implement lexical analyser in C. ALGORITHM: Step 1:Start Step 2:Read the contents of the text file Step 3:Run a loop with the steps 4,5,6 until all the characters in the file is read Step 4:Read the characters in each line Step 5:Increment the value of i Step 6:Run a loop with the steps 7 to 11 till the condition j < i-1 remains true Step 7:Initialize the type pointer as a token using strtok( ) Step 8:Check for '#' in the type string and if it is true then print it as a preprocessor Step 9: Check for '(' in the type string and if it is true then print it as a function Ste p 10:Classify the type string as “int” or “float” or “char” or “double” Step 11:Check for the identifiers using the strtok( ) and if it is true then print it as an identifier Step 12:End PROGRAM: #include<stdio.h> #include<string.h> #include<stdlib.h> main() { FILE *fp; char line[100][100]; char *type,*var,*check,*check_p,*check_f; char pre[10]; int i=0,j; fp=fopen("symbolfile.c","r"); while(!feof(fp)) { fgets(line[i],200,fp); i++; } printf("LINE NUMBER\tPREPROCESSORS\tFUNCTIONS\tKEYWORDS \tIDENTIFIERS\n"); for(j=0;j<i-1;j++) 180501002 PAGE NUMBER: { type=strtok(line[j]," "); check_p=strchr(type,'#'); if(check_p!=NULL) printf("%d\t\t%s\n",j+1,type); check_f=strchr(type,'('); if(check_f!=NULL) printf("%d\t\t\t\t%s",j+1,type); if(strcmp(type,"int")==0||strcmp(type,"float")==0||strcmp(type,"double")==0|| strcmp(type,"char")==0) { while((var=strtok(NULL,";\n"))!=NULL) { printf("%d\t\t\t\t\t\t%s\t\t%s\n",j+1,type,var,var); } } } } symbol.file.c: #include<stdio.h> main() { int a,b; { float c,d; double e,f; } char g,h; printf("%d",a); } SAMPLE OUTPUT: LINE NUMBER PREPROCESSORS FUNCTIONS KEYWORDS IDENTIFIERS 1 #include<stdio.h> 2 main() 4 int a,b 6 float c,d 7 double e,f 9 char g,h 10 printf("%d",a); RESULT: 180501002 PAGE NUMBER: Thus the C program for implementation of lexical analyser had been executed successfully. CS18611 COMPILER DESIGN LABORATORY EXNO:3 IMPLEMENTATION OF SIMPLE PROGRAMS USING LEX DATE: A)TO FIND WHETHER THE GIVEN NUMBER IS POSITIVE OR NEGATIVE: AIM: To find whether the given number is positive or negative using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> %} %% [+]+[0-9]* { printf("POSITIVE NUMBER");} [-]+[0-9]* { printf("NEGATIVE NUMBER");} \n {return 0;} %% main() { printf("ENTER A NUMBER: "); yylex(); } SAMPLE OUTPUT: ENTER A NUMBER:+10 POSITIVE NUMBER RESULT: 180501002 PAGE NUMBER: Thus the program to find whether the given number is positive or negative using lex had been executed successfully. B)TO FIND WHETHER THE GIVEN NUMBER IS ODD OR EVEN: AIM: To find whether the given number is odd or even using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> %} %% [0-9]*[02468] { printf("ODD NUMBER");} [0-9]*[13579] { printf("EVEN NUMBER");} \n {return 0;} %% main() { printf("ENTER A NUMBER: "); yylex(); } SAMPLE OUTPUT: ENTER A NUMBER:20 EVEN NUMBER RESULT: 180501002 PAGE NUMBER: Thus the program to find whether the given number is odd or even using lex had been executed successfully. C)TO FIND THE NUMBER OF VOWELS AND CONSONANTS IN A GIVEN STRING : AIM: To find the number of vowels and consonants in a given string using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> int c=0,v=0; %} %% [aeiouAEIOU] { v++;} [a-z] { c++;} \n {return 0;} %% main() { printf("ENTER A STRING: "); yylex(); printf("CONSONANTS: %d \n VOWELS: %d\n",c,v); } SAMPLE OUTPUT: ENTER A STRING: KOUSHIK CONSONANTS: 4 VOWELS: 3 RESULT: 180501002 PAGE NUMBER: Thus the program to print the number of vowels and consonants in a given string using lex had been executed successfully. D)TO FIND WHETHER THE GIVEN IDENTIFIER IS VALID OR NOT: AIM: To find whether the given identifier is valid or not using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> %} %% [a-zA-Z]+[_0-9a-zA-Z]* {printf("VALID IDENTIFIER\n ");} .* { printf(" INVALID ");} \n {return 0;} %% main() { printf("ENTER AN IDENTIFIER :"); yylex(); } SAMPLE OUTPUT: ENTER AN IDENTIFIER :A_123BC VALID IDENTIFIER RESULT: 180501002 PAGE NUMBER: Thus the program to find whether the given identifier is valid or not using lex had been executed successfully. E)TO FIND THE NUMBER OF VOWELS,CONSONANTS,LINES AND SYMBOLS IN A GIVEN FILE : AIM: To find the number of vowels,consonants,lines and symbols in a given file using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> int v=0,c=0,s=0,l=0,n=0; %} %% [aeiouAEIOU] {v++;} [a-zA-Z] {c++;} [0-9] {n++;} \n {l++;} [!@#$%^&*] {s++;} . {return 0;} %% main() { yyin=fopen("file.txt","r"); yylex(); printf("VOWELS:%d\nCONSONANTS:%d\nNUMBERS:%d\nLINES:%d\nSYMBOLS:%d",v, c,n,l,s); } file.txt KOUSHIK$ DHANUSH1010 RAM@ VIKASH23 SAMPLE OUTPUT: VOWELS:8 CONSONANTS:15 NUMBERS:6 LINES:4 SYMBOLS:2 180501002 PAGE NUMBER: RESULT: Thus the program to print the number of vowels,consonants lines and symbols in a given file using lex had been executed successfully. F)TO FIND THE NUMBER OF WORDS STARTING WITH VOWELS, INTEGERS AND FLOATING POINT IN A GIVEN FILE USING LEX: AIM: To find the number of words starting with vowels, integers and floating point in a given file using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> int w=0,i=0,f=0; %} %% [aeiouAEIOU][a-zA-Z]* {w++;} [a-zA-Z]+ ; [0-9]+ {i++;} [0-9]*[.][0-9]* {f++;} . {return 0;} %% main() { yyin=fopen("file.txt","r"); yylex(); printf("WORDS STARTING WITH VOWELS:%d\nINTEGERS:%d\nFLOATING POINTS:%d\n",w,i,f); } file.txt ABINAND 8 9.8 SAMPLE OUTPUT: WORDS STARTING WITH VOWELS:1 INTEGERS:1 FLOATING POINTS:1 RESULT: 180501002 PAGE NUMBER: Thus the program to print the number of words starting with vowels, integers and floating point in a given file using lex had been executed successfully. CS18611 COMPILER DESIGN LABORATORY EXNO:4 IMPLEMENTATION OF LEXICAL ANALYSER USING LEX DATE: AIM: To implement lexical analyser using lex. PROGRAM: %option noyywrap %{ #include<stdio.h> int l=1; %} %% \n {l++;} [#][a-zA- Z<>.]+ {printf(“preprocessor:%s line:%d \ n”,yytext,l);} [A-Za- z]+[()]+ {printf(“function:%s line:%d \ n”,yytext,l); “int”|”float”|”double”|”char”|”if”|”else” {printf(“keyword:%s line:%d \ n”,yytext,l);} [a-zA-Z_]+[A-Za-z0-9]* { printf(“identifier:%s line:%d \ n”,yytext,l);} %% main() { yyin=fopen(“file.txt”,”r”); yylex(); } file.txt: #include<stdio.h> main() { int a; } SAMPLE OUTPUT: Preprocessor:#include<stdio.h> line:1 Function:main() line:2 Keyword:int line:3 Identifier:a line:3 180501002 PAGE NUMBER: RESULT: Thus the implementation of lexical analyser using lex had been executed successfully. CS18611 COMPILER DESIGN LABORATORY EXNO:5 IMPLEMENTATION OF SIMPLE PROGRAMS USING LEX AND YACC DATE: A) TO FIND WHETHER THE GIVEN IDENTIFIER IS VALID OR NOT: AIM: To find whether the given identifier is valid or not using lex and yacc. ALGORITHM: LEX: Step 1:Start Step 2:Include the y.tab.h file Step 3:Give the definition for the identifiers such that the identifier starts with either an alphabet or _ and followed by alphabets and numbers. Step 4:End YACC: Step 1:Start Step 2:Read the data from the user Step 3:Check for the definitions for the variable given in lex Step 4:If it satisfies the definition of identifier , then print that it is a variable Step 5:End PROGRAM: LEX: %option noyywrap %{ #include "y.tab.h" %} %% [_]+[a-zA-Z0-9]+ {return var;} [a-zA-Z]+[0-9]* {return var;} . {return nvar;} 180501002 PAGE NUMBER: %% YACC: %{ #include <stdio.h> #include <stdlib.h> int yylex(); void yyerror(const char*); %} %token var,nvar %% V:var {printf("IT'S A VARIABLE\n");exit(0);} |nvar {printf("IT'S NOT A VARIABLE\n");exit(0);} %% int main() { printf("ENTER ANYTHING: "); yyparse(); } void yyerror(const char* s) { fprintf(stderr,"\n%s\n",s); } SAMPLE OUTPUT: ENTER ANYTHING:_abcgd5 IT'S A VARIABLE 180501002 PAGE NUMBER: RESULT: Thus the program to find whether the given identifier is valid or not using lex and yacc had been executed successfully. B) TO VALIDATE THE GIVEN EXPRESSION: AIM: To validate the given expression using lex and yacc. ALGORITHM: LEX: Step 1:Start Step 2:Include the y.tab.h file Step 3:Give the definition for a number and return it Step 4:End YACC: Step 1:Start Step 2:Read the expression from the user Step 3:Define the associativity for the operators to be evaluated Step 4:Define the syntax for the expression to be evaluated Step 5:Check for any exceptions or errors Step 6:Print the result of evaluated expression Step 7:End PROGRAM: LEX: %option noyywrap %{ #include "y.tab.h" extern int yylval; %} %% [0-9]+ {yylval=atoi(yytext); return num;} [\n] {return 0;} . {return yytext[0];} %% 180501002 PAGE NUMBER: YACC: %{ #include <stdio.h> #include <stdlib.h> int yylex(); void yyerror(const char*); %} %token num,var,nvar %left '+' '-' %left '*' '/' '%' %nonassoc UMINUS %% stmt: E {printf("ANSWER = %d\n",$$);} E:E '+' E {$$=$1+$3;} |E '-' E {$$=$1-$3;} |E '/' E {if($3==0) {printf("Divide by zero\n"); exit(0);} $$=$1/$3;} |E '*' E {$$=$1*$3;} |E '%' E {$$=$1%$3;} |'('E')' {$$=$2;} |'-'E %prec UMINUS {$$=-$2;} |num {$$=$1;} ; %% int main() { printf("ENTER AN EXPRESSION: "); yyparse(); } void yyerror(const char* s) { fprintf(stderr,"\n%s\n",s); } SAMPLE OUTPUT: ENTER AN EXPRESSION:5+5 ANSWER =10 180501002 PAGE NUMBER: RESULT: Thus the program to validate the given expression using lex and yacc had been executed successfully. CS18611 COMPILER DESIGN LABORATORY EXNO:6 IMPLEMENTATION OF CALCULATOR USING LEX AND YACC DATE: AIM: To implement calculator using lex and yacc. ALGORITHM: LEX: Step 1:Start Step 2:Include the y.tab.h file Step 3:Give the definition for the identifiers,operators,numbers and print,exit statements Step 4:End YACC: Step 1:Start Step 2:Read the expression from the user Step 3:Define the tokens,associativity for the operators and syntax for the expressions Step 4:Check for the token in the symbol table Step 5:If token is present then return it else update the symbol table Step 6:The index of the token in the symbol table is returned after searching for the token Step 7:End PROGRAM: LEX: %option noyywrap %{ #include "y.tab.h" #include <stdlib.h> #include <string.h> void yyerror(const char *); %} %% "print" {return print;} 180501002 PAGE NUMBER: "exit" {return kill;} [a-zA-Z]+[0-9]* {yylval.id=strdup(yytext); return iden;} [0-9]+ {yylval.nu=atoi(yytext); return num;} [ \t] ; [-+=/*%\n] {return yytext[0];} . {ECHO; yyerror("NOT A VALID CHARACTER\n"); exit(0);} %% YACC: %{ #include <stdio.h> #include <stdlib.h> #define YYERROR_VERBOSE char sym[100][100]; int symval[100]; int yylex(); void yyerror(const char*); int search(char *sym); int check(char *sym); int n=0,err=0; void update(char *sym, int val); %} %union {int nu; char *id;} %start line %token print %token kill %token <nu> num %token <id> iden %type <nu> line exp term %type <id> assign %left '+' '-' %left '*' '/' '%' %nonassoc UMINUS %% line : assign '\n' {;} | kill '\n' {exit(0);} | print exp '\n' {if(err)err=0; else printf("%d\n",$2);} | line assign '\n' {;} | line kill '\n' {exit(0);} | line print exp '\n' {if(err)err=0; else printf("%d\n",$3);}; ; assign : iden '=' exp {if(err); else update($1,$3);} ; exp : term {if(err) ; else $$=$1;} 180501002 PAGE NUMBER: |exp '+' exp {$$=$1+$3;} |exp '-' exp {$$=$1-$3;} |exp '/' exp {if($3==0) {yyerror("Divide by zero\n"); exit(0);} else {$$=$1/$3;}} |exp '*' exp {$$=$1*$3;} |exp '%' exp {if($3==0) {yyerror("Divide by zero\n"); exit(0);} else {$$=$1%$3;}} |'-'exp %prec UMINUS {$$=-$2;} |'('exp')' {$$=$2;} ; term :num {$$=$1;} |iden {int idx; if((idx = search($1))!=-1) {$$=idx;} else {printf("UNDEFINED SYMBOL %s\n",$1);err=1;}} ; %% int main(void) { printf("CALCULATOR IS ACTIVE\n"); printf("\nENTER EXPRESSION:\n"); yyparse(); } void yyerror(const char* s) { fprintf(stderr,"\n%s\n",s); } int check(char *syma) { int i; for(i=0;i<=n;i++) if(strcmp(syma,sym[i])==0) return i; return -1; } int search(char *syma) { int index = check(syma); if(index==-1) return index; else return symval[index]; } void update(char *syma, int val) { int index = check(syma); if(index!=-1) symval[index]=val; else { 180501002 PAGE NUMBER: strcpy(sym[n],syma); symval[n] = val; n++; } } SAMPLE INPUT/OUTPUT: INPUT : CALCULATOR IS ACTIVE ENTER EXPRESSION: a=5 b=5 c=a+b print c exit OUTPUT: 10 RESULT: Thus, the program for the implementation of calculator using lex and yacc had been executed successfully. 180501002 PAGE NUMBER: CS18611 COMPILER DESIGN LABORATORY EXNO:7 IMPLEMENTATION OF ABSTRACT SYNTAX TREE DATE: USING LEX AND YACC AIM: To implement abstract syntax tree using lex and yacc. ALGORITHM: LEX: Step 1:Start Step 2:Include the y.tab.h file Step 3:Give the definition for the identifiers and numbers Step 4:End YACC: Step 1:Start Step 2:Read the expression from the user Step 3:Define the tokens,associativity for the operators and syntax for the expressions Step 4:In addnode ( ) ,create and allocate memory to a temporary node and initialize the left and right data pointers with parameters l and r respectively Step 5: In makenode ( ) ,create and allocate memory to a temporary node and initialize the left and right data pointers as NULL Step 6:In printasttree ( ) ,print the preorder(root-left-right) traversal of the given expression using recursive call Step 7:End PROGRAM: LEX: %option noyywrap