Design and Implement a Calculator using ‘YACC’ and ‘LEX

khanCalc.y
%{
#include <stdlib.h>
#include <stdio.h>
int yylex(void);
#include "y.tab.h"
%}
%token INTEGER
%%s
program:
line program
| line
line:
expr '\n' { printf("%d\n",$1); }
| 'n'
expr:
expr '+' mulex { $$ = $1 + $3; }
| expr '-' mulex { $$ = $1 - $3; }
| mulex { $$ = $1; }
mulex:
mulex '*' term { $$ = $1 * $3; }
| mulex '/' term { $$ = $1 / $3; }
| term { $$ = $1; }
term:
'(' expr ')' { $$ = $2; }
| INTEGER { $$ = $1; }
%%
void yyerror(char *s)
{
fprintf(stderr,"%s\n",s);
return;
}
yywrap()
{
return(1);
}
int main(void)
{
/*yydebug=1;*/
yyparse();
return 0;
}
Lexx.l
%{
#include <stdlib.h>
#include <stdio.h>
#include "y.tab.h"
void yyerror(char*);
extern int yylval;
%}
%%
[ \t]+ ;
[0-9]+ {yylval = atoi(yytext);
return INTEGER;}
[-+*/] {return *yytext;}
"(" {return *yytext;}
")" {return *yytext;}
\n {return *yytext;}
. {char msg[25];
sprintf(msg,"%s <%s>","invalid character",yytext);
yyerror(msg);}
Output :-
[Sajid@localhost Desktop]$ flex lexx.l
[Sajid@localhost Desktop]$ yacc -d calc.y
[Sajid@localhost Desktop]$ gcc y.tab.c lex.yy.c
[Sajid@localhost Desktop]$ ./a.out
5+6
11
8+9-7
10
6++9
syntax error

Program execution time calculation in c

#include <stdio.h>

#include <time.h>

// A function that terminates when enter key is pressed

voidfun()

{

printf("fun() starts \n");

printf("Press enter to stop fun \n");

while(1)

{

if(getchar())

break;

}

printf("fun() ends \n");

}

// The main program calls fun() and measures time taken by fun()

intmain()

{

// Calculate the time taken by fun()

clock_tt;

t = clock();

fun();

t = clock() - t;

doubletime_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("fun() took %f seconds to execute \n", time_taken);

return0;

}

LEX Program to count number of blank spaces, characters, lines, words from given input by file…

%{ #include<stdio.h> int ch=0,bl=0,ln=0,wr=0;%}

%%

[\n] {ln++;wr++;}

[\t] {bl++;wr++;}

[" "] {bl++;wr++;}

[^\n\t] {ch++;}

%%

int main()

{

FILE *fp;

char file[10];

printf("Enter the filename: ");

scanf("%s", file);

yyin=fp;

yylex();

printf("Character=%d\nBlank=%d\nLines=%d\nWords=%d", ch, bl, ln, wr);

return 0;

}

Output ->

$cat >inputsajidk and sidhart

$lex p1a.l

$cc lex.yy.c –ll

$./a.out

Enter the filename:inputCharacter=16Blank=2Lines=1Word=3

Write a Lex program to count the number of vowels and consonants in a givenstring.

%{
#include<stdio.h>
int vowels=0;
int cons=0;
%}
%%
[aeiouAEIOU] {vowels++;}
[a-zA-Z] {cons++;}
%%
int yywrap()
{
return 1;
}
main()
{
printf(“Enter the string.. at end press ^d\n”);
yylex();
printf(“No of vowels=%d\nNo of consonants=%d\n”, vowels,cons);
}

How to Compile:
Save the file with .l extention. E.g. vowels.l
lex vowels.l
gcc –o sajlex.yy.c
./saj Or ./a.out

Write lex to define Identifier Number and Keyword.

%{

#include<stdio.h>

%}

%%

If|else|switch|for|char|int

{

Printf(“keyword”);

}

[a-z]([a-z][0-9])*

{

Printf(“Identifier”);

}

[0-9]*

{

Printf(“Number”);

}

.*{

Printf(“Invalid”);

}

%%

Main()

{

yylex();

return 0;

}

Intyywrap(); }} //sample output:- if you enter –int then output is it’s keyword

Wap for String Acceptance:-

YACC programe:-

%{
#include<stdio.h>
%}
%token DIGIT LETTER
%%
stmt:A
;
A: LETTER B;
B: LETTER B
| DIGIT B
| LETTER
| DIGIT
;
%%
voidmain(){
printf("enter string \n");
yyparse();
printf("valid");
exit(0);
}
voidyyerror()
{
printf("invalid");
exit(0);
}

//LEX Programe:-

%{
#include "y.tab.h"
%}
%%
[0-9]+ {return DIGIT;}
[a-zA-Z]+ {return LETTER;}
[ \t] {;}
\n { return 0;}
. {return yytext[0];}
%%

Compiling this Program

lex sajidlex.l

yacc -d sajidyacc.y

gcc lex.yy.c y.tab.c -ll -ly

./a.out

Valid Arithmetic Expression Yacc Programe

%{
#include<stdio.h>
#include<ctype.h>
%}
%token LETTER DIGIT
%left '+' '-'
%left '*' '/'
%%
st:st expr '\n' {
printf("\n valid expression \n");
}
| st '\n'
|
;
expr:expr '+' expr
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'(' expr ')'
| NUM
| LETTER
;
NUM: DIGIT
|NUM DIGIT
;
%%
intyylex()
{
char c;
while((c=getchar())==' ');
if(isalpha(c)) return LETTER;
if(isdigit(c)) return DIGIT;
return(c);
}
int main()
{
printf("\n enter an expression\n");
yyparse();
}
int yyerror()
{
printf("invalid\n");
return 0;
}

Write a programe to implement first of any grammer Production

#include<stdio.h>

#include<ctype.h>

void first(char[], char);

void addtoresultset(char[], char);

int n;

char productionset[10][10];

main(){

int i;

char c;

char choice;

char result[20];

printf("How many no. of productions?:");

scanf("%d", &n);

for(i=0; i<n; i++){

printf("Enter Production number %d:", i+1);

scanf("%s", productionset[i]);

}

do{

printf("\nFind the first of:");

scanf(" %c", &c);

first(result, c);

printf("\nFirst(%c) = {",c);

for(i=0; result[i]!='\0'; i++){

printf(" %c", result[i]);

}

printf("}\n");

printf("Press y to continue:");

scanf(" %c", &choice);

}while(choice == 'y' || choice == 'Y');

}

void first(char* result, char c){

int i, j, k;

char subresult[20];

int epsilon;

subresult[0] = '\0';

result[0] = '\0';

if(!(isupper(c))){

addtoresultset(result, c);

return;

}

for(i=0; i<n; i++){

if(productionset[i][0] == c){

if(productionset[i][2] == '$'){

addtoresultset(result, '$');

}

else{

j = 2;

while(productionset[i][j]!='\0'){

epsilon = 0;

first(subresult, productionset[i][j]);

for(k=0; subresult[k]!='\0'; k++){

addtoresultset(result, subresult[k]);

}

for(k=0; subresult[k]!='0'; k++){

if(subresult[k] == '$'){

epsilon = 1;

break;

}

}

if(!(epsilon)){

break;

}

j++;

}

}

}

}

return;

}

void addtoresultset(char result[], char val){

int k;

for(k=0; result[k]!='\0'; k++)

if(result[k] == val)

return;

result[k] = val;

result[k+1] = '\0';

}

Compiling this Program

gcc sajid.cpp

./a.out

Write a programe for SYMBOL TABLE (LINKED LIST)

#include<stdio.h>

#include<conio.h>

#include<malloc.h>

#include<string.h>

#include<stdlib.h>

#define NULL 0

int size=0;

void Insert();

void Display();

void Delete();

int Search(char lab[]);

void Modify();

struct SymbTab

{

char label[10],symbol[10];

int addr;

struct SymbTab *next;};

struct SymbTab *first,*last;

int main()

{

int op,y;

char la[10];

//clrscr();

do

{

printf("\n\tSYMBOL TABLE IMPLEMENTATION\n");

printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.DELETE\n\t4.SEARCH\n\t5.MODIFY\n\t6.END\n");

printf("\n\tEnter your option : ");

scanf("%d",&op);

switch(op)

{

case 1:

Insert();

break;

case 2:

Display();

break;

case 3:

Delete();

break;

case 4:

printf("\n\tEnter the label to be searched : ");

scanf("%s",la);

y=Search(la);

printf("\n\tSearch Result:");

if(y==1)

printf("\n\tThe label is present in the symbol table\n");

else

printf("\n\tThe label is not present in the symbol table\n");

break;

case 5:

Modify();

break;

case 6:

exit(0);

}

}while(op<6);

getch();

}

void Insert()

{

int n;

char l[10];

printf("\n\tEnter the label : ");

scanf("%s",l);

n=Search(l);

if(n==1)

printf("\n\tThe label exists already in the symbol table\n\tDuplicate can't be inserted");

else

{

struct SymbTab *p;

p=(SymbTab *)malloc(sizeof(struct SymbTab));

strcpy(p->label,l);

printf("\n\tEnter the symbol : ");

scanf("%s",p->symbol);

printf("\n\tEnter the address : ");

scanf("%d",&p->addr);

p->next=NULL;

if(size==0)

{

first=p;

last=p;

}

else

{

last->next=p;

last=p;

}

size++;

}

printf("\n\tLabel inserted\n");

}

void Display()

{

int i;

struct SymbTab *p;

p=first;

printf("\n\tLABEL\t\tSYMBOL\t\tADDRESS\n");

for(i=0;i<size;i++)

{

printf("\t%s\t\t%s\t\t%d\n",p->label,p->symbol,p->addr);

p=p->next;

}

}

int Search(char lab[])

{

int i,flag=0;

struct SymbTab *p;

p=first;

for(i=0;i<size;i++)

{

if(strcmp(p->label,lab)==0)

flag=1;

p=p->next;

}

return flag;

}

void Modify()

{

char l[10],nl[10];

int add,choice,i,s;

struct SymbTab *p;

p=first;

printf("\n\tWhat do you want to modify?\n");

printf("\n\t1.Only the label\n\t2.Only the address\n\t3.Both the label and address\n");

printf("\tEnter your choice : ");

scanf("%d",&choice);

switch(choice)

{

case 1:

printf("\n\tEnter the old label : ");

scanf("%s",l);

s=Search(l);

if(s==0)

printf("\n\tLabel not found\n");

else

{

printf("\n\tEnter the new label : ");

scanf("%s",nl);

for(i=0;i<size;i++)

{

if(strcmp(p->label,l)==0)

strcpy(p->label,nl);

p=p->next;

}

printf("\n\tAfter Modification:\n");

Display();

}

break;

case 2:

printf("\n\tEnter the label where the address is to be modified : ");

scanf("%s",l);

s=Search(l);

if(s==0)

printf("\n\tLabel not found\n");

else

{

printf("\n\tEnter the new address : ");

scanf("%d",&add);

for(i=0;i<size;i++)

{

if(strcmp(p->label,l)==0)

p->addr=add;

p=p->next;

}

printf("\n\tAfter Modification:\n");

Display();

}

break;

case 3:

printf("\n\tEnter the old label : ");

scanf("%s",l);

s=Search(l);

if(s==0)

printf("\n\tLabel not found\n");

else

{

printf("\n\tEnter the new label : ");

scanf("%s",nl);

printf("\n\tEnter the new address : ");

scanf("%d",&add);

for(i=0;i<size;i++)

{

if(strcmp(p->label,l)==0)

{

strcpy(p->label,nl);

p->addr=add;

}

p=p->next;

}

printf("\n\tAfter Modification:\n");

Display();

}

break;

}

}

void Delete()

{

int a;

char l[10];

struct SymbTab *p,*q;

p=first;

printf("\n\tEnter the label to be deleted : ");

scanf("%s",l);

a=Search(l);

if(a==0)

printf("\n\tLabel not found\n");

else

{

if(strcmp(first->label,l)==0)

first=first->next;

else if(strcmp(last->label,l)==0)

{

q=p->next;

while(strcmp(q->label,l)!=0)

{

p=p->next;

q=q->next;

}

p->next=NULL;

last=p;

}

else

{

q=p->next;

while(strcmp(q->label,l)!=0)

{

p=p->next;

q=q->next;

}

p->next=q->next;

}

size--;

printf("\n\tAfter Deletion:\n");

Display();

}

}

Write a programe for Symbol table by using Array

#include<stdio.h>

#include<string.h>

int main(){

char arr[3][3];

int i, j, b, n;

char s, c;

for(i=0; i<3; i++){

printf("Enter the label no.:");

scanf(" %d", &n);

s = n + '0';

arr[n-1][0] = s;

printf("\nEnter the symbol:");

scanf(" %c", &arr[n-1][1]);

printf("\nEnter the address:");

scanf(" %d", &b);

c = b + '0';

arr[n-1][2] = c;

}

for(i=0; i<3; i++){

for(j=0; j<3; j++){

printf(" %c\t", arr[i][j]);

}

printf("\n");

}

}

Write a programe to show valid email by lex…

%{

#include<stdio.h>

#include<stdlib.h>

int flag=0;

%}

%%

[a-z ].[0-9]+@[a-z]+".com"|".in" { flag=1; }

%%

int main()

{

yylex();

if(flag==1)

printf("Accepted");

else

printf("Not Accepted");

}

Write a programe for this grammer by using lex and yacc

E->E+T/T

T->T*F/F

F->(E)/NUMBER

%{

#include”y.tab.h”

#include<stdio.h>

Extream int yylval;

%}

%%

[0-9]+

{

Yylval=atoi(yytext);

Return NUMBER;

}

{

Return yytext[0];

}

%%