0% found this document useful (0 votes)
30 views29 pages

5IT4 22 - Compiler Lab Manual Student

hh

Uploaded by

harshit31jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
30 views29 pages

5IT4 22 - Compiler Lab Manual Student

hh

Uploaded by

harshit31jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
EXPERIMENT: AIM: Introduction: Objective, scope and outcome ofthe course. OBJECTIVE: The laboratory course is intended to make experiments on the basic techniques of compiler construction and tools that can be used to perform syntax-directed translation of a high-level programming language into an executable code. Students will design and implement language processors in C by using tools to automate parts of the implementation process. This will provide deeper insights into the more advanced semantics aspects of Programming languages, code generation, machine independent optimizations, dynamic memory allocation, and object orientation. SCOPE: ‘The scope of this course is to explore the principle, algorithm and data structure involved in the design and ‘construction of compiler. ourcomes: ‘Upon the completion of Compiler Design practical course, the student willbe able to: 1. Understand the working of lex and yace compiler for debugging of programs. 2, Understand and define the ole of lexical analyzer, use of regular expression and transition diagrams. 3. Understand and use Context free grammar, and parse tre construction. 4, Lear & use the new tools and technologies used for designing a compiler. 5. Develop program for solving parser problems. 6. Leam how to write programs that execute faster. Introduction of Compiler Design Compiler is a software which converts a program written in high level language (Source Language) to low level language (Object/Farget/Machine Language). , Low Level Compiler aanpanteerd t Compilation Error High Level Language . Cross Compiler that runs on a machine ‘A' and produces a code for another machine “B’. It is capable of creating code for a platform other than the one on which the compi Phases of a Compiler — ‘There ate two major phases of compilation, which in turn have many parts. Each of them take input from the output of the previous level and work in a coordinated way. hem High Level Language: ere Snes moe eT az Generator Smarty anne aoe Assembly Code Analysis Phase — An semantic tree representation is created from the 1. Lexical Analyzer 2. Syntax Analyzer 3. Semantic Analyzer Lexical analyzer divides the program into “tokens” program using syntax of language and Semant construct. ‘Syntax analyzer recognizes “sentences” in the analyzer checks static semantics of each ‘Synthesis Phase - It has three parts : 4, Intermediate Code Generator 5. Code Optimizer 6. Code Generator Intermediate Code Generator generates “abstract” code, Code Optimizer optimizes the abstract code, and final Code Generator translates abstract intermediate code into specific machine instructions, 3h .XPERI} 2 AIM: Program to find whether given string is keyword or not, PROGRAM: #include #include Hinclude void main() char a[5](10}=("printf","scanf”,"if","else","break"); char str{10]; int flag; clrser(); puts("Enter the string ; gett st) for(i=0;i Hinclude #include #include Static int count=0; int isKeyword(char buffert])( char keywordsf32][10] = snum","extern","f1 7 igned","sizeof", "static", "struct", "swite ","volatile", "while" ‘union", "unsigned", "voi fori = 0; 1 < 32; ++i)( if(stremp(keywordsfi), buffer) flag = 1; count+ break; 1 } return flag; } int mainO char ch, bufferf15] ; FILE “fp; int ij=0; fp = fopen("KESHAV3.C',"""); if({p == NULL) . printf("error while opening the file\n"); exit(0); } while((ch = fgetc(fp)) != EOF){ if(isalnum(ch)){ buffer(j++] = ch; ) else if((ch = 1) && (j= OD 0; if(isKeyword(buffer) == 1) print{("%s is keyword\n", buffer); } e@ printf("'no of keywords= %d", count); fclose(fp); return 0; EXPERIMENT-4 AIM: Count total no of operators ina file, [Taking file from user] Hinclude PROGRAM: #include #include Hinclude static int cout int main()( char ch, buffer{15], operatorst print((“error while opening the file\n"); exit(0); printf("%6c is operator\n", ch); countt+; ) } ) print{(’no of operators= 9d", count); felose( fp); return 0; 38 E [ENT- AIM: Count total occurrence of each character in a given PROGRAM: finclude include #include int main { FILE * fp; char string{100}; int = 0, count(26] = (0 }, x; fp = fopen ("deepa.xt", "r"); eo clser(); while Fscant (fp, "96s", string) != EOF) (c=0; ‘while (stringfc] != No) { [Taking file from user] /** Considering rif (stringle] { aracters from 'a' to '2' only and ignoring others. &&e stringle] <="2') x= stringle] count{x]++; } cH } } for (c= 0; ¢<26; c++) printf ("%c occurs %d times in the string.\n", ¢ + 'a', count{c]); e return 0; 38 EXPERIMENT-6 AIM: ‘Write a C program to inser, delete and display the entries in Symbol Table. PROGRAM: ‘tmplementation of symbol table #include #includesctype.h> #include #includesstring h> #include void main() { int i=0,j=0.x=0,n void *p,*addlS]; char chstch,b{15}dL151.¢; print{(" Expression terminated by $:"); While((c=getchar())!='S') { itt; } neil; print{("Given Expression 0; while(i<=n) { printf("%c" bil); itty ) print{("\n Symbol Table\n"); printf ("Symbol \t addr \t type’ while(j<=n) { =bij) iffisalpha(toascii(©))) p=malloc(c); addlx]=p; lx} printf("\n%c \t 96d \t identifier\n",c,p); xt; 4 p=malloc(ch); add{x} als} hi printf("\n %c \t %d \Coperator\n’,ch,p); RH; jes mn EXP! NT-7 AIM: ‘Write a LEX program to identify following: L. Valid mobile number 2. Valid url 3. Valid identifier 4, Valid date (ddimm/yyyy) S. Valid time (hh:mm:ss) PROGRAM: 1.Valid mobile number 6 /* Definition section */ %) P Rule Section */ 4% [1-9][0-9]{9} {printf(’\nMobile Number Valid\n”);} + {printf("\wMobile Number Invalid\n");} 56% I1 driver code int main() { printf(\nEnter Mobile Number :"); yylex(); printf("\n"); return 0; } int yywrap() { } 2. Valid url 4% (Coup ittpys23Wvia-28-20-91(2,\fo-2}(2) ula2A-Z0-9+=2") (prnf(URL Vaido")) ‘> (printf((WURL Invalid\n");} %% void main() ( 42 printf(’\wnEnter URL : "); yylex(); printf("\n" ) int yywrap() ( } 3. Valid identifier ‘fa>zA-Z_lla-2A-Z0-9_}* print{("Valid Identifier"); 11 regex for invalid identifiers ‘(a -z A -Z_) printf("Invalid Identifier"); 6% void main() { printf(’\nEnter Identifier: "); yylex(); printi(’\n"); int yywrapQ) { 2 4. Valid date (dd/mmiyyyy) 6% ({0-2}{0-9}}{31(0-1])v((0(113}5)7/8))|(10]12))v(C1-2]{0-9}{0-9]f-0-9]) {valid=1;} ({O-2]{0-9]30)((0(4)6|9))|11)V(L1-2]10-9]{0-9][0-9}) {valid=1;) ({0-1}{0-9}}2{0-8)vo2v((1-2]{0-9}{0-9]{0-9}) {valid=1;} 29VO2V((1-2]{0-9][0-9][0-9]) { while(yytextfi)!=/)i++; i++;while(yytext(i]! Oryr}#(yytextli++]-0); i(yr%4==O}\ yr i %% void main() { yyin=fopen("new", yylex(); #3 {H(valid==1) printf(*H is a valid date else printf ("It is not a valid date\n"); ) int yywrap() ( return 1; ! id time(hh ht ide int i=0,yr=0,vall %) %% ({0-2}{0-9]:[0-6][0-9)\:{0-6][0-9]) {print{("%s It is a valid time\ 4% void main() { yyin=fopen(“new yylex } int yywrap() ( retum 1; ) 44 Al Write a lex program to count blank spaces,words,lines in a given file. PR 9% EXPERIMENT-8 IM: OGRAM: finclude int Tines=0, words %6) 4% \n (lines ++; words +#3) [ie '"] wordst +; [A-2] c_letters +5 [a-z] s lewers++; {0-9} num++; splchart +; 4% void main(void) ( FILE “fp; char {(50); print{(“enterfile name \n"); scant("%s" yyin= fopen(| yylexOs ‘otal=s_letters*c_letters#num#spl_char; printi(" This File contains ."); print{(% ‘nd lines", lines); printf" words", words); printf("int%d small letters", sewers); printf("w9%d capital lewters"¢_letters); print{("ni%6d digits", 7 print{("\nt%d special characters" spl_char); printf("\nithn total 9d characters.\n" total}; } int yywrap) { return(1); } 45 ,c_letters=0, num=0, spl_char=0,total AIM: Wate a tex program to count the no, of vowels and consonants in a C file. PROGRAM: ot Hincludesstaio.h> {nt veount=0,ccount=0; %) Lalifeloae|AMO]UT (veount’ +3) [az A-Z, Cailefoluf|A MOL) 1 {ecomne++ int main) { FILE stp: hae 15 print(Centertite name Wn"); seant(” yyin= fopen(fy yylex0s print{("No, of Vowels :%d\n®,veount); print((°No, of Consonants :26d\n",ccount); ret 0; ) int yywrap) { ) AIM: EXP! NT-10 ‘Write a YACC program to recognize strings aaab,abbb using a”nb’n, where b>=0. PROGRAM: Gm %( #include "y.tab.h" %} return A;} (return B;} 0) G) \n return 05} - {return yytext{0};) int yywrap() {return 1; } Gmy 96 Hinclude 9%) S6token A B stmt: S; S:ASB | 6% void main) ( print{(“enter \n"); exit(0); } void yyerror() { printf ("invalid"); exit(0); } EXPERIMENT-11 AIM: Write a YAC PROGRAM: Expr %t include "y.tab.h" extern int yylval; %) %% [0-9}+ {yylval=atoi(yytext); return number; } 0G) Dun} {retum 03) » {return yytext{0};) %% int yywrap() { return J; } Expry Mf #include int res=0; 96} S6token number olefe + ‘left '* %% ‘stmt:expr {res=$$;} expriexpr'" expr (SS=$1+83;) lexpr's expr {$$=81-83;) lexpr'™ expr {S$=$1"83;} Jexpr'7 expr else $$=$1/S3;} program to evaluate an arithmetic expression involving operators +, and /. Jnumber 6% void main() 56d" res); exit(O); y void yyerror() { print{("invalid\n"); exit(O); 1 44 PERI AIM: Write a YACC program to check validity of a strings abcd, aabbed using grammar a*nbancdmdam, where n , m>0 PROGRAM: Grammer.y %E Hinclude iclude yerror(char*); int yylex; %) token A BC D NEWLINE %Y% stmt: NEWLINE { primt("validin"); return 1; 36% extern FILE *yyin; void main() { printf(“enter \n"); do { yyparseQ } while(!feof(yyin)); int yyerror(char* str) { 5o printf("invalid "); return 1; } Grammer. 9% #include'y.tab.h” %) 6% al A {retum A;) cl € {return 3) b] B (return B;} al D {retum D;) tw) "vn (retum NEWLINI {return yytext{O};} int yywrap() t return 1; ) IMENT-13 AIM: Write a C program to find first of any grammar, PROGRAM: #include Hinclude void FIRST(char int count,n=0; har prodn{10]{10}, first(10}; void main() { int ichoice; char ¢,ch;, Printf("How many productions ? scanf("%6q",&ccount); print{(’Enter 9%d productions epsilon: for(i=Osi

You might also like