You are on page 1of 33

Expt.

No: 3 IMPLEMENT A LEXICAL ANALYZER USING LEX TOOL


Date:

AIM

To implement a Lexical Analyzer using Lex Tool.

ALGORITHM

Step 1: Lex program contains three sections: definitions, rules, and user subroutines.
Each section must be separated from the others by a line containing only the delimiter,
%%. The format is as follows: definitions %% rules %% user subroutines
Step 2: In definition section, the variables make up the left column, and their
definitions make up the right column. Any C statements should be enclosed in %{..}
%. Identifier is defined such that the first letter of an identifier is alphabet and
remaining letters are alphanumeric.
Step 3: In rules section, the left column contains the pattern to be recognized in an
input file to yylex(). The right column contains the C program fragment executed
when that pattern is recognized. The various patterns are keywords, operators, new
line character, number, string, identifier, beginning and end of block, comment
statements, preprocessor directive statements etc.
Step 4: Each pattern may have a corresponding action, that is, a fragment of C source
code to execute when the pattern is matched.
Step 5: When yylex() matches a string in the input stream, it copies the matched text
to an external character array, yytext, before it executes any actions in the rules
section. Step 6: In user subroutine section, main routine calls yylex(). yywrap() is
used to get more
input.
Step 7: The lex command uses the rules and actions contained in file to generate a
program, lex.yy.c, which can be compiled with the cc command. That program can
then receive input, break the input into the logical pieces defined by the rules in file,
and run program fragments contained in the actions in file.

Jothish B 714020205017
PROGRAM
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
for |
struct |
typedef |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n\t%s is a keyword",yytext);}
"/*" {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT)printf("\n BLOCK BEGINS");}
\} {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n\t %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER
",yytext);}
\)(\:)? {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("var.c","r");
Jothish B 714020205017
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}

INPUT
//var.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=1;
b=2;
c=a+b; printf("Sum:
%d",c);
}

Jothish B 714020205017
OUTPUT

Class Performance

Record
Viva
Total

RESULT
Hence the program to implement a Lexical Analyzer using Lex Tool is executed and
the output is verified.

Jothish B 714020205017
Expt.No: 4 IMPLEMENT AN ARITHMETIC CALCULATOR
Date: USING LEX AND YACC

AIM

To implement an Arithmetic Calculator using LEX and YACC.

ALGORITHM

Step 1: Declarations %% translation rules %% supporting C routines

Step 2: Declarations Section: This section contains entries that:

i. Include standard I/O header file.

ii. Define global variables.

iii. Define the list rule as the place to start processing.

iv. Define the tokens used by the parser. v. Define the operators and their precedence.

Step 3: Rules Section: The rules section defines the rules that parse the input stream.
Each rule of a grammar production and the associated semantic action.

Step 4: Programs Section: The programs section contains the following subroutines.
Because these subroutines are included in this file, it is not necessary to use the yacc
library when processing this file.

Step 5: Main- The required main program that calls the yyparse subroutine to start the
program.

Step 6: yyerror(s) -This error-handling subroutine only prints a syntax error message.

Step 7: yywrap -The wrap-up subroutine that returns a value of 1 when the end of
input occurs. The calc.lex file contains include statements for standard input and
output, as programmar file information if we use the -d flag with the yacc command.
The y.tab.h file contains definitions for the tokens that the parser program uses.

Step 8: calc.lex contains the rules to generate these tokens from the input stream.

Jothish B 714020205017
PROGRAM
LEX PROGRAM
%{
/* Definition section
*/ #include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
/* Rule Section */
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}

YACC PROGRAM
%{
/* Definition section
*/ #include<stdio.h>
int flag=0;
%}
%token NUMBER
%left '+' '-'

Jothish B 714020205017
%left '*' '/' '%'
%left '(' ')'
/* Rule Section */
%%
ArithmeticExpression: E{
printf("\nResult=%d\n", $$);
return 0;
};
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%%
//driver code
void main()
{
printf("\nEnter Any Arithmetic Expression which can have operations Addition,
Subtraction, Multiplication, Division, Modulus and Round brackets:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
}

Jothish B 714020205017
OUTPUT

Class Performance

Record
Viva
Total

RESULT
Hence the program to implement an Arithmetic Calculator using LEX and YACC is
executed and the output is verified.

Jothish B 714020205017
Expt.No: 5 GENERATE THREE ADDRESS CODE FOR A SIMPLE
Date: PROGRAM USING LEX AND YACC

AIM
To generate three address code for a simple program using LEX and YACC.

ALGORITHM
Step 1 : Start the Program.
Step 2 : Read the input from the user.
Step 3 : Break the given code into several separate three address codes.
Step 4 : Three address code instruction has atmost three operands.It is a combination of
assignment and a binary operator.
Step 5 : Print the generated instructions.
Step 6 : Stop the program.

Jothish B 714020205017
LEX PROGRAM
%{
#include
#include
#include “y.tab.h”
%}
%%
[0-9]+ {yylval.dval=atoi(yytext);return NUM;}
[t];
n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf(“n Invalid Character…”);
}
int main()
{
printf(“Enter Expression x => “);
yyparse();
return(0);
}

YACC PROGRAM
%{
#include
int yylex(void);
char p=’A’-1;
%}
%union
{
char dval;
}
%token NUM

Jothish B 714020205017
%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%nonassoc UMINUS
%type S
%type E
%%
S : E {printf(” x = %cn”,$$);}
;
E : NUM {}
| E ‘+’ E {p++;printf(“n %c = %c + %c “,p,$1,$3);$$=p;}
| E ‘-‘ E {p++;printf(“n %c = %c – %c “,p,$1,$3);$$=p;}
| E ‘*’ E {p++;printf(“n %c = %c * %c “,p,$1,$3);$$=p;}
| E ‘/’ E {p++;printf(“n %c = %c / %c “,p,$1,$3);$$=p;}
| ‘(‘E’)’ {$$=p;}
| ‘-‘ E %prec UMINUS {p++;printf(“n %c = -%c “,p,$2);$$=p;}
;
%%

Jothish B 714020205017
OUTPUT

Class Performance

Record

Viva

Total

RESULT
Hence the program generate three address code for a simple program using LEX and
YACC . and the output is verified.

Jothish B 714020205017
Expt.No: 6 IMPLEMENT SIMPLE CODE OPTIMIZATION TECHNIQUES
Date:

AIM
To implement simple code optimization techniques (Constant folding,
Strength reduction and Algebraic transformation).

ALGORITHM
Step 1: Generate the program for factorial program using for and do-while loop to specify
optimization technique.

Step 2: In for loop variable initialization is activated first and the condition is checked next.
If the condition is true the corresponding statements are executed and specified increment /
decrement operation is performed.

Step 3: The for loop operation is activated till the condition failure.

Step 4: In do-while loop the variable is initialized and the statements are executed then the
condition checking and increment / decrement operation is performed.

Step 5: When comparing both for and do-while loop for optimization dowhile is best
because first the statement execution is done then only the condition is checked. So, during
the statement execution itself we can find the inconvenience of the result and no need to wait
for the specified condition result.

Step 6: Finally when considering Code Optimization in loop do-while is best with respect
to performance

Jothish B 714020205017
PROGRAM
#include<stdio.h>
#include<string.h>
struct op {
char l;
char r[20];
}
op[10],pr[10];
void main() {
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;
printf("Enter the Number of Values:");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("left: ");
scanf(" %c",&op[i].l);
printf("right: ");
scanf(" %s",op[i].r);
}
printf("Intermediate Code\n") ;
for(i=0;i<n;i++) {
printf("%c=",op[i].l);
printf("%s\n",op[i].r);
}
for(i=0;i<n-1;i++) {
temp=op[i].l;
for(j=0;j<n;j++) {
p=strchr(op[j].r,temp);
if(p) {

Jothish B 714020205017
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i]. r);
z++;
}
}
}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");
for(k=0;k<z;k++) {
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++) {
tem=pr[m].r;
for(j=m+1;j<z;j++) {
p=strstr(tem,pr[j].r);
if(p) {
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++) {
l=strchr(pr[i].r,t) ;
if(l) {
a=l-pr[i].r;
printf("pos: %d\n",a);
pr[i].r[a]=pr[m].l;
}
}
}
}
}

Jothish B 714020205017
printf("Eliminate Common Expression\n");
for(i=0;i<z;i++) {
printf("%c\t=",pr[i].l);
printf("%s\n",pr[i].r);
}
for(i=0;i<z;i++) {
for(j=i+1;j<z;j++) {
q=strcmp(pr[i].r,pr[j].r);
if((pr[i].l==pr[j].l)&&!q) {
pr[i].l='\0';
}
}
}
printf("Optimized Code\n");
for(i=0;i<z;i++) { if(pr[i].l!
='\0') {
printf("%c=",pr[i].l);
printf("%s\n",pr[i].r);
}
}
}

Jothish B 714020205017
OUTPUT

Class Performance

Record

Viva

Total

RESULT
Hence the program to implement simple code optimization techniques is executed and
the output is verified.

Jothish B 714020205017
Expt.No: 7 IMPLEMENT BACK-END OF THE COMPILER
Date:

AIM

Implement back-end of the compiler for which the three address code is given as input
and the 8086 assembly language code is produced as output

ALGORITHM

Step 1: Start the program

Step 2: Open the source file and store the contents as quadruples.

Step 3: Check for operators, in quadruples, if it is an arithmetic operator generator it


or if assignment operator generates it, else perform unary minus on register C.

Step 4: Write the generated code into output definition of the file in outp.c

Step 5: Print the output.

Step 6: Stop the program.

Jothish B 714020205017
PROGRAM
#include<stdio.h>
#include<stdio.h>
//#include<conio.h>
#include<string.h>
void main()
{
char icode[10][30],str[20],opr[10];
int i=0;
//clrscr();
printf("\n Enter the set of intermediate code (terminated by
exit):\n");
do
{
scanf("%s",icode[i]);
} while(strcmp(icode[i++],"exit")!=0);
printf("\n target code generation");
printf("\n**********");
i=0;
do
{
strcpy(str,icode[i]);
switch(str[3])
{
case '+':
strcpy(opr,"ADD");
break;
case '-':
strcpy(opr,"SUB");
break;
case '*':

Jothish B 714020205017
strcpy(opr,"MUL");
break;
case '/':
strcpy(opr,"DIV");
break;
}
printf("\n\tMov %c,R%d",str[2],i);
printf("\n\t%s%c,R%d",opr,str[4],i);
printf("\n\tMov R%d,%c",i,str[0]);
}while(strcmp(icode[++i],"exit")!=0);
//getch();
}

Jothish B 714020205017
OUTPUT

Class Performance

Record
Viva
Total

RESULT
Hence the program to implement back-end of the compiler is executed and the output
is verified.

Jothish B 714020205017
Expt.No: 8 LEX PROGRAM TO COUNT THE NUMBER OF
Date: VOWELS AND CONSONANTS IN A STRING

AIM

To write a LEX Program to count the number of vowels and consonants in a string

ALGORITHM

Step 1: Start the program

Step 2: Read the input string

Step 3: Initialize the vowel count and consonant count as zero

Step 4: If the characters in the string include aeiou the increment the vowel count
otherwise increment the consonant count

Step 5: Print the vowel count and consonant count

Step 6: End

Jothish B 714020205017
PROGRAM

%{
int vow_count=0;
int const_count =0;
%}

%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%
int yywrap(){}
int main()
{
printf("Enter the string of vowels and consonants:");
yylex();
printf("Number of vowels are: %d\n", vow_count);
printf("Number of consonants are: %d\n", const_count);
return 0;
}

Jothish B 714020205017
OUTPUT
Enter the string of vowels and consonents: compilerdesign
Number of vowels are: 5
Number of consonants are: 9

Class Performance

Record
Viva
Total

RESULT
Hence the program to write a LEX Program to count the number of vowels and
consonants in a string is executed and the output is verified.

Jothish B 714020205017
Expt.No: 9 LEX PROGRAM TO COUNT THE IDENTIFIERS

Date:

AIM:

To write a LEX program to count the identifiers in given string.

ALGORITHM:

Step-1 : Start the program.

Step-2 : By using lex tool get the input from the user.

Step-3 : Compare the input with symbol table and

keywords. Step-4 : Count the string that does not match.

Step-5 : Display the count.

Step-6 : Stop the program.

Jothish B 714020205017
PROGRAM:

%{#include<iostream.h>

int count=0;

char ch=0;

%}

digit[0-9]

letter[a-zA-Z_]

%%

{letter}({letter}|{digit})* {

count++;

%%

int main()

yylex();

printf("count: %d",count);

return 0;

Jothish B 714020205017
OUTPUT:

Class Performance

Viva

Record
Total

RESULT:

Hence the program is implemented and the output is verified.

Jothish B 714020205017
Expt.No: 10 LEX PROGRAM TO CALCULATE SUM AND AVERAGE

Date:

AIM:

To write a LEX program to calculate sum and average of given numbers.

ALGORITHM:

Step-1 : Start the program.

Step-2 : Perform the calculation using lex tool.

Step-3 : In lex tool, first the input is read and the calculation is done for addition and average.

Step-4 : Display the sum and average.

Step-5 : Stop the program.

Jothish B 714020205017
PROGRAM:

%{

//Average of given numbers.

#include<stdio.h>

#include<math.h>

%}

digit[0-9]+

%%

{digit} return atoi(yytext);

%%

int main(){

float sum=0, num, n=0;

while((num=yylex())>0){

sum = sum+num;

n = n+1;

printf("The sum of given numbers is %f\n",sum);

printf("Average of given numbers is %f\n",sum/n);

yylex();

return 0;

Jothish B 714020205017
OUTPUT:

Class Performance

Viva

Record
Total

RESULT:

Hence the program is implemented and the output is verified.

Jothish B 714020205017
Expt.No: 11 LEX PROGRAM TO RECOGNIZE SIMPLE AND COMPUND

Date: SENTENCE

AIM:

To write a LEX program to recognize whether the given sentence is simple or compound.

ALGORITHM:

Step-1: Start the program.

Step-2 : Using lex tool get the string from the user.

Step-3 : Compare the string with given string and classify them as simple or compound sentence.

Step-4 : Display the output.

Step-5 : Stop the program.

Jothish B 714020205017
PROGRAM:

%{

#include<stdio.h>

int flag=0;

%}

%%

and |

or |

but |

because |

if |

then |

nevertheless { flag=1; }

.;

\n { return 0; }

%%

int main()

printf("Enter the sentence:\n");

yylex();

if(flag==0)

printf("Simple sentence\n");

else

printf("compound sentence\n");
}

int yywrap( )

return 1;

Jothish B 714020205017
OUTPUT:

Enter the sentence: My name is Mahesh Huddar and I am from India

Compound sentence

Class Performance

Viva

Record
Total

RESULT:

Hence the program is implemented and the output is verified.

Jothish B 714020205017

You might also like