You are on page 1of 7

BCSE307P

Compiler Design
Lab- 5

Reg No: 21BAI139 Date: 22/02/2024


Name: P YASWANTHA RAO

Q1. To write a Yacc program to program to recognize a valid arithmetic


expression that uses operator +, -, * and /.

Code:
Lex Program: (sample.l)

%{

#include<stdio.h>

#include "y.tab.h"

%}

%%

[a-zA-Z]+ return VARIABLE;

[0-9]+ return NUMBER;

[\t] ;

[\n] return 0;

. return yytext[0];

%%

int yywrap()

{
return 1;

Yacc program: (sample.y)

%{

#include<stdio.h>

%}

%token NUMBER

%token VARIABLE

%left '+' '-'

%left '*' '/' '%'

%left '(' ')'

%%

S: VARIABLE'='E {

printf("\nEntered arithmetic expression is Valid\n\n");

return 0;

E:E'+'E

|E'-'E

|E'*'E

|E'/'E

|E'%'E

|'('E')'

| NUMBER

| VARIABLE

;
%%

void main()

printf("\nEnter Any Arithmetic Expression which can have operations


Addition, Subtraction, Multiplication, Divison, Modulus and Round brackets:\
n");

yyparse();

void yyerror()

printf("\nEntered arithmetic expression is Invalid\n\n");

}
OUTPUT:

Q2. To write a YAAC program to recognize a valid variable which


starts with a letter followed by any number of letters or digits.

Code:
Yacc program :

%token DIGIT LETTER NL UND


%%
stmt : variable NL { printf(“Valid Identifiers\n”); exit(0);}
;

variable : LETTER alphanumeric


;
alphanumeric: LETTER alphanumeric
| DIGIT alphanumeric
| UND alphanumeric
| LETTER
| DIGIT
| UND
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expression\n”);
exit(0);
}
main ()
{
printf(“Enter the variable name\n”);
yyparse();
}

Lex program :

%{
#include “y.tab.h”
%}
%%
[a-zA-Z] { return LETTER ;}
[0-9] { return DIGIT ; }
[\n] { return NL ;}
[_] { return UND; }
. { return yytext[0]; }
%%

Output:
Q3. To write a YAAC program to recognize a valid control structures
syntax of c language

Code:
Yacc program :

%token IF RELOP S NUMBER ID


%{
int count=0;
%}
%%
stmt : if_stmt { printf(“No of nested if statements=%d\n”,count); exit(0);}
;
if_stmt : IF ‘(‘ cond ‘)’ if_stmt {count++;}
| S;
;
cond : x RELOP x
;
x : ID
| NUMBER
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expression\n”);
exit(0);
}
main ()
{
printf(“Enter the statement”);
yyparse();
}
Lex program :

%{
#include “y.tab.h”
%}
%%
“if” { return IF; }
[sS][0-9]* {return S;}
“<”|”>”|”==”|”!=”|”<=”|”>=” { return RELOP; }
[0-9]+ { return NUMBER; }
[a-zA-Z][a-zA-Z0-9_]* { return ID; }
\n { ; }
. { return yytext[0]; }
%%

Output:

You might also like