0% found this document useful (0 votes)
170 views25 pages

Lex, Yacc Pgms

The document contains code snippets for Lex and Yacc programs that perform various tasks related to parsing and validating syntax. Some examples include counting characters, words and lines in a file; validating arithmetic expressions; checking for valid variable names; and defining context-free grammars to recognize specific language patterns. The code shows the Lex and Yacc specifications, with rules to tokenize input and define a grammar, as well as C code for driver functions and semantic actions.

Uploaded by

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

Lex, Yacc Pgms

The document contains code snippets for Lex and Yacc programs that perform various tasks related to parsing and validating syntax. Some examples include counting characters, words and lines in a file; validating arithmetic expressions; checking for valid variable names; and defining context-free grammars to recognize specific language patterns. The code shows the Lex and Yacc specifications, with rules to tokenize input and define a grammar, as well as C code for driver functions and semantic actions.

Uploaded by

revamrocks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 25

Part A(LEX and YACC)

http://programsvtu.weebly.com/ss-and-cd-lab.html

a.l file ->


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

4a.y file
%{
#include<stdio.h>
%}
%token ID NUMBER
%left '+' '-'
%left '*' '/'
%%
stmt:expr
;
expr: expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| '(' expr ')'
| NUMBER
| ID
;
%%
void main()
{
printf("enter expr : \n");
yyparse();
printf("valid exp");
exit(0);
}
void yyerror()
{
printf("invalid exp");
exit(0);
}

1a.Count characters, lines and words

%{
int s=0,w=0,l=1,c=0;
%}
%%
[\n]* { l+=yyleng;}
[ \t]* { s+=yyleng;}
[^ \n\t]*[\t] { w++;c+=yyleng-1;s++;}
[^ \n\t]*[ ] { w++;c+=yyleng-1;s++;}
[^ \n\t]*[\n] { w++;c+=yyleng-1;l++;}
[^ \n\t]* { w++;c+=yyleng;}
%%
main(int argc,char **argv)
{
if(argc!=2)
{
printf("\nIncorrect usage!!\n");
return 1;
}
yyin=fopen(*(argv+1),"r");
if(!yyin)
{
printf("\nCannot open the file!\n");
return 1;
}
yylex();
printf("\nChar=%d\nSpaces=%d\nWords=%d\nLines=%d\n",c,s,w,l);
}

1b.Comment Lines

%{
int com=0;
%}
%%
\/\*[^*]*\*(\*|([^*/][^*]*\*))*\/ com++;
\/\/[^\n]*[\n] com++;
% fprintf(yyout,"%%");
.|[\n] fprintf(yyout,yytext);
%%
main(int argc,char **argv)
{
if(argc!=3)
{
printf("\nArguments passed in wrong manner\n");
return 1;
}
yyin=fopen(*(argv+1),"r");
yyout=fopen(*(argv+2),"w");
if(!(yyin&&yyout))
{
printf("\nSpecified file cannot be opened!");
return 1;
}
yylex();
printf("\nTotla number of comment lines=%d\n",com);
}

2a.Valid arithmetic expression

%{
#include<string.h>
int valid,i,j,k,temp,temp1,top=1,num[40];
char arr[40][10],st[80],op[40];
%}
%%
[a-zA-Z][a-zA-Z0-9]* {
strcpy(arr[j++],yytext);
if(st[top-1]=='i')
valid=1;
else if(st[top-1]=='o')
st[top-1]='i';
else
st[top++]='i';
}
[0-9]+ {
num[k++]=atoi(yytext);
if(st[top-1]=='i')
valid=1;
else if(st[top-1]=='o')
st[top-1]='i';
else
st[top++]='i';
}
[\-+/*%^&|] {
op[temp++]=yytext[0];
if(st[top-1]=='i')
st[top-1]='o';
else
valid=1;
}
"(" {
if(st[top-1]=='('||st[top-1]=='$'||st[top-1]=='o')
st[top++]='(';
else
valid=1;
}
")" {
if(st[top-1]=='(')
top--;
else if(st[top-1]=='i'&&st[top-2]=='(')
{
top-=2;
if(st[top-1]=='o')
st[top-1]='i';
else if(st[top-1]=='i')
valid=1;
else
st[top++]='i';
}
else
valid=1;
}
. valid=1;
\n return ;
%%
check()
{
if(!(temp|k|j))
return 0;
if(valid)
return 0;
if(top==2&&st[top-1]=='i')
top--;
if(top==1&&st[top-1]=='$')
top--;
if(top==0)
return 1;
return 0;
}
main()
{
st[top-1]='$';
printf("\nEnter the expression\n");
yylex();
if(check())
{
printf("\nValid expression!\n");
if(j>0)
printf("\nIdentifiers present are ");
for(i=0;i<j;i++)
printf("\n%s",arr[i]);
if(k>0)
printf("\nNumbers used are ");
for(i=0;i<k;i++)
printf("\n%d",num[i]);
if(temp>0)
printf("\nOperators present are ");
for(i=0;i<temp;i++)
printf("\n%c",op[i]);
}
else
printf("\nInvalid expression!\n");
}
2b.Simple or complex statement

%{
int valid;
%}
%%
[a-zA-Z][ ](and|but|if|then|else|nevertheless)[ ][a-zA-Z] { valid=1; }
.|[\n] ;
%%
main()
{
printf("\nEnter the text ");
yylex();
if(valid)
{
printf("\nStatement is compound!\n");
}
else
{
printf("\nStatement is simple!\n");
}
}

3.Identifiers(method1)

%{
char ch;
int id;
%}
%%
^[ \t]*(int|float|double|char) {
ch=input();
while(1)
{
if(ch==',')
id++;
else if(ch==';')
{
id++;
break;
}
ch=input();
}
}
.|[\n] ;
%%
int main(int argc,char **argv)
{
if(argc!=2)
{
printf("\nImproper usage!\n");
return 1;
}
yyin=fopen(*(argv+1),"r");
if(!yyin)
{
printf("\nSpecified file cannot be opened!\n");
return 1;
}
yylex();
printf("\nTotal identifiers is %d\n",id);
}

3.Identifiers(method2)
%{
#include<ctype.h>
char ch,arr[20];
int id,i,j;
int test(char *);
%}
%%
^[ \t]*("int "|"float "|"double "|"char ")[ \t]* {
ch=input();
while(1)
{
if(ch=='\n'||ch==0)
break;
if(ch==','||ch==';')
{
arr[i]=0;
i=0;
j=test(arr);
if(j!=-1)
{
id+=j;
printf("\n%s is a %s",arr,j?"identifier":"nonidentifier");
}
if(ch==';')
break;
ch=input();
continue;
}
arr[i++]=ch;
ch=input();
}
}
.|[\n] ;
%%
yywrap()
{
return 1;
}
int rno(char *a,int state)
{
if(*a=='='&&state==0&&!(*a=0))
return 1;
if(isdigit(*a)&&state==1)
state=1;
if(*a==']'&&state==1)
state=0;
if(*a==0&&state==0)
return 1;
if(*a=='['&&state==0)
state=1;
a++;
return rno(a,state);
}
int test(char *a)
{
char *b=a;
int i;
while(*b==' ')
b++;
if(!isalpha(*b))
return 0;
while(*b!=0)
{
if(*b=='='&&!(*b=0))
return 1;
if(*b=='[')
{
i=rno(b++,1);
b--;
if(i==1)
*b=0;
return i;
}
if(!isalnum(*b))
return 0;
b++;
}
return 1;
}
int main(int argc,char **argv)
{
if(argc!=2)
{
printf("\nImproper usage!\n");
return 1;
}
yyin=fopen(*(argv+1),"r");
if(!yyin)
{
printf("\nSpecified file cannot be opened!\n");
return 1;
}
yylex();
printf("\nTotal identifiers is %d\n",id);
}

4a.Valid arithmetic expression(method 1)

LEX part

%{
#include "y.tab.h"
%}
%%
[a-zA-Z_][a-zA-Z_0-9]* return id;
[0-9]+(\.[0-9]*)? return num;
[+/*] return op;
. return yytext[0];
\n return 0;
%%

YACC part

%{
#include<stdio.h>
int valid=1;
%}
%token num id op
%%
start : id '=' s ';'
s: id x
| num x
| '-' num x
| '(' s ')' x
;
x: op s
| '-' s
|
;
%%
int yyerror()
{
valid=0;
printf("\nInvalid expression!\n");
return 0;
}
int main()
{
printf("\nEnter the expression:\n");
yyparse();
if(valid)
{
printf("\nValid expression!\n");
}
}
4a.Valid arithmetic expression(method 2)

LEX part

%{
#include "y.tab.h"
%}
%%
[a-zA-Z_][a-zA-Z_0-9]* return id;
[0-9]+(\.[0-9]*)? return num;
[+/*] return op;
. return yytext[0];
\n return 0;
%%

YACC part

%{
#include<stdio.h>
int valid=1;
%}
%token num id op
%left '-' op
%%
start : id y '=' s ';'
y : op
| '-'
|
;
s : x op x
| x '-' x
| '(' s ')'
|x
;
x : id
| '-' num
| num
;
%%
int yyerror()
{
valid=0;
printf("\nInvalid expression!\n");
return 0;
}
int main()
{
printf("\nEnter the expression:\n");
yyparse();
if(valid)
{
printf("\nValid expression!\n");
}
}
4b.Valid variable

LEX part

%{
#include "y.tab.h"
%}
%%
[a-zA-Z] return letter;
[0-9] return digit;
. return yytext[0];
\n return 0;
%%

YACC part

%{
#include<stdio.h>
int valid=1;
%}
%token digit letter
%%
start : letter s
s: letter s
| digit s
|
;
%%
int yyerror()
{
printf("\nIts not a identifier!\n");
valid=0;
return 0;
}
int main()
{
printf("\nEnter a name to tested for identifier ");
yyparse();
if(valid)
{
printf("\nIt is a identifier!\n");
}
}

5a.Evaluate valid arithmetic expression

LEX part

%{
#include "y.tab.h"
int extern yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return num; }
. return yytext[0];
\n return 0;
%%

YACC part

%
#include<stdio.h>
int valid=0,temp;
%}
%token num
%left '+''-'
%left '*''/'
%nonassoc UMINUS
%%
expr1 : expr { temp=$1; }
expr: expr '+' expr { $$=$1+$3; }
| expr '-' expr { $$=$1-$3; }
| expr '*' expr { $$=$1*$3; }
| expr '/' expr { if($3==0) { valid=1; $$=0; } else { $$=$1/$3; } }
| '(' expr ')' { $$=$2; }
| '-' expr { $$=-1*$2; }
| num { $$=yylval; }
;
%%
int yyerror()
{
printf("\nInvalid expression!\n");
valid=2;
return 0;
}
int main()
{
printf("\nEnter the expression to be evaluated\n");
yyparse();
if(valid==1)
{
printf("\nDivision by 0!\n");
}
if(valid==0)
{
printf("\nValid expression!\n");
printf("The value evaluated is %d\n",temp);
}
}

5b.Language a^nb^n(n>=0)

LEX part

%{
#include "y.tab.h"
%}
%%
a return A;
b return B;
.|[\n] return 0;
%%

YACC part

%{
#include<stdio.h>
int valid=1;
%}
%token A B
%%
start : A start B
|
;
%%
int yyerror()
{
valid=0;
printf("\nPattern not matched!\n");
return 0;
}
int main()
{
printf("\nEnter the pattern ");
yyparse();
if(valid)
{
printf("\nValid pattern!\n");
}
}

6.Language of type a^nb(n>=10)

LEX part

%{
#include "y.tab.h"
%}
%%
a return A;
b return B;
.|[\n] return 0;
%%

YACC part

%{
#include<stdio.h>
int valid=1;
%}
%token A B
%%
start : A A A A A A A A A A s B
s: As
|
;
%%
int yyerror()
{
valid=0;
printf("\nPattern not matched!\n");
return 0;
}
int main()
{
printf("\nEnter the pattern ");
yyparse();
if(valid)
{
printf("\nValid pattern!\n");
}
}

YACC PART:

CODE: (gram.y)

%{
#include<stdio.h>
#include<stdlib.h>
%}

%token A B NL

%%
stmt: S NL {printf("valid string\n");
exit(0);}
;
S: A S B |
;
%%

int yyerror(char *msg)


{
printf("invalid string\n");
exit(0);
}

main()
{
printf("enter the string\n");
yyparse();
}

LEX PART:

CODE: (gram.l)
%{
#include "y.tab.h"
%}

%%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
. {return yytext[0];}
%%

OUTPUT :

yacc -d gram.y
lex gram.l
cc y.tab.c lex.yy.c -ly -ll
./a.out
enter the string
ab
valid string

./a.out
enter the string
aaabb
invalid string

./a.out
enter the string
aabb
valid string

./a.out
enter the string
a
invalid string

NOV

lex and yacc programs

Y- 1
Yacc program to recognize a valid arithmetic expression for
operators (+,-,*, / ).

%{ #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
%}
%token num let
%left '+' '-'
%left '*' '/'
%%
Stmt : Stmt \n { printf (\n.. Valid Expression..
\n); exit(0); }
| expr
|
| error \n { printf (\n..Invalid
..\n); exit(0); }
;
expr : num
| let
| expr + expr
| expr - expr
| expr * expr
| expr / expr
| '(' expr ')'
;
%%
main ( )
{
printf (Enter an expression to validate : );
yyparse ( );
}

yylex()
{
int ch;
while ( ( ch = getchar() ) == ' ' );
if ( isdigit(ch) )
return num; // return token num
if ( isalpha(ch) )
return let; // return token let
return ch;
}

yyerror (char *s)


{
printf ( %s, s );
}
COMPILATION OUTPUT FILE PRODUCED
$ yacc -d prog.y y.tab.c , y.tab.h
$ cc y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
4+t Accepted
(5*d+5) Accepted
a+*5 Rejected

Y5.y
Yacc program to Evaluate an arithmetic expression for operators
(+,-,*, / ).

%{ /* Evaluate simple arithmetic expression */


#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define YYSTYPE double
%}
%token num
%left '+' '-'
%left '*' '/'
%%
Stmt : Stmt '\n' { printf ( "Value is %f \n", $1); exit(0); }
| Expr
|
| error '\n' { printf ("INVALID"); exit(0);
}
;
Expr : num { $$ = $1;
}
| Expr '+' Expr { $$ = $1 + $3;
}
| Expr '-' Expr { $$ = $1 - $3;
}
| Expr '*' Expr { $$ = $1 * $3;
}
| Expr '/' Expr {
if ( $3 ==
0)
{ printf ( "division by zero \n");
exit (0);
}
else
$$ = $1 / $3;
}
| '(' Expr ')' { $$ = $2;
}
;
%%

main ( )
{
printf ( "ENTER AN EXPRESSION TO EVALUATE : \n" );
yyparse ( );
}

yyerror (char *s)


{
printf ( "%s", s );
}

yylex ( )
{
char ch;
while ( (ch = getchar() ) == ' ' ) ;
if ( isdigit(ch) | ch == '.' )
{
ungetc ( ch, stdin );
scanf ( "%lf", &yylval );
return num;
}
return ch;
}

COMPILATION OUTPUT FILE PRODUCED


$ yacc -d Y5.y y.tab.c , y.tab.h
$ cc y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
4+8 Value is 12.000000
3*9 Value is 27.000000
5- Syntax error

Y2.y
Program to recognize nested IF control statements and display the
number of levels of nesting.

Yacc Program (without curly braces { } )

%{ #include <stdio.h>
int depth = 0, nesting = 0;
%}
%token IF ROP ST NUM ENTER
%%
Strt : IF_STAT ENTER { printf ( \n Total Nested if = %d\n,
count); exit(0); }
;
IF_STAT: IF '(' COND ')' ENTER STAT { count++; }
;
STAT : ST ;
| IF_STAT
;
COND: ST ROP ST
| ST
;
%%
main()
{
printf ( \n ENTER if statement : \n );
yyparse ();
}
yyerror (char *s)
{
printf ( "\n %s \n", s );
}
Lex program : Y2.l

%{
#include "y.tab.h"
%}
%%
if { return IF; }
[\(\)\{\}] { return *yytext; }
[<>] { return *yytext; }
{;}
. { return *yytext; }
%%
Yacc Program (without curly braces { } )

%{ #include <stdio.h>
int depth = 0, nesting = 0;
%}
%token IF ROP ST NUM ENTER
%%
StartP : IF_STAT ENTER { printf ( \n Total Nested if = %d\n,
count); exit(0); }
;
IF_STAT: IF '(' COND ')' ENTER STAT { count++; }
;
STAT : { ENTER ST ; ENTER }
| { ENTER IF_STAT ENTER }
| IF_STAT
| ST
;
COND: ST ROP ST
| ST
;
%%

COMPILATION OUTPUT FILE PRODUCED


$ yacc -d Y2.y y.tab.c , y.tab.h
$ lex Y2.l
$ cc lex.yy.c y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
If ( a > b )
{ Total NESTED IF = 1
a+b;
}

Y4.y
/* Yacc program to recognize a valid variable, which starts with a
letter followed by any number of digits and letters. */

%{ #include <stdio.h>
#include <ctype.h>
%}
%token let dig
%%
TERM : XTERM \n { printf
( \nAccepted\n ); exit(0); }
| error { yyerror ( Rejected\n ); }
;
XTERM : XTERM let
| XTERM dig
| let
;
%%
yylex()
{
char ch;
while ( ( ch = getchar ( ) ) == ) ;
if ( isalpha (ch) )
return let;
if ( isdigit (ch) )
return dig;
return ch;
}
main()
{
printf (Enter a variable : );
yyparse ();
}

yyerror(char *s)
{
printf (%s, s);
}

COMPILATION OUTPUT FILE PRODUCED


$ yacc -d Y4.y y.tab.c , y.tab.h
$ cc y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
Enter a variable : asd12 Accepted
Enter a variable : 12adr Rejected

Y6.y
Yacc program to recognize strings aaab, abbb,ab and a using
the grammar (anbn , n>0).

%{
#include<stdio.h>
%}
%token a b

%%
Stmt : TERM '\n' { printf ( "\n string belongs to grammar..\n" );
exit(0); }

| error '\n' { yyerror ( "\n String does not belong to


grammar..\n" ); }
;
TERM: a TERM b
|
;
%%

main ( )
{
printf ( "ENTER String for GRAMMER a^nb^n : \n"
);
yyparse ( );
}

yylex ( )
{
char ch;
while ( ( ch = getchar() ) == ' ' );
if ( ch == 'a' )
return a;
if ( ch == 'b' )
return b;
return ch;
}

yyerror (char *s)


{
printf ( "%s", s);
}

COMPILATION OUTPUT FILE PRODUCED


$ yacc -d Y6.y y.tab.c , y.tab.h
$ cc y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
ENTER String : aaabbb String belongs to grammar
ENTER String: aabbb Rejected
Y7.y
Yacc program to recognize strings for grammar (a nb, n>=10).

%{
#include<stdio.h>
int n = 0 ;
%}
%token A B
%%
Stmt : TERM B '\n' { if ( n>=10 ) printf ( "\n String belongs
to grammar.." );
else printf ("\n Rejected .. ");
}
| error '\n' { printf ( "\n ..Rejected..\n" ); }
;
TERM: TERM A { n++ ; }
|
;
%%

main ( )
{
printf ( "ENTER String for GRAMMER a^nb^n : \n" )
;
yyparse ( );
}

yyerror (char *s)


{
printf ( " Syntax Error " );
}

yylex ( )
{
char ch;
while ( ( ch = getchar() ) == ' ' );
if ( ch == 'a' )
return A;
if ( ch == 'b' )
return B;
return ch;
}

COMPILATION OUTPUT FILE PRODUCED


$ yacc -d Y7.y y.tab.c , y.tab.h
$ cc y.tab.c -ll a.out (PARSER)
./a.out Running parser

Input OUTPUT
ENTER String : aaab Rejected
ENTER String: aaaaaaaaaaaab String belong to the grammar

Lex program : Y2.l

%{
#include "y.tab.h"
%}

%%
if(.*) { return IF; }
else { return ELSE; }
.* { return SIMPLE; }
{.*} { return SIMPLE; }
{;}
%%

Yacc program : Y2.l

%{
#include <stdio.h>
%}

%token SIMPLE IF ELSE


%nonassoc REDUCE
%nonassoc ELSE

%%
Strt : stmnt '\n' {printf(\n..Valid..\n);}
;
stmnt : SIMPLE
| if_stmnt
;
if_stmnt : IF stmnt %prec REDUCE { printf("simple if");}
| IF stmnt ELSE stmnt { printf("if_then_else");}
;
%%

main ()
{
yyin = fopen(iffile.c, r);
yyparse();
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy