Professional Documents
Culture Documents
ex5pcd kavi
ex5pcd kavi
Aim:
Algorithm:
Parser (Calc.y):
Exno:5 Page 1
Kaviraj N(2112064) 19CS62C-PRINCIPLES OF COMPILER DESIGN LAB1
o %left '('')': Declares that parentheses ((, )) have the same precedence and
associativity (usually left-to-right), allowing for grouping of expressions
o Calculation: E { printf("\nResult=%d\n", $$); return 0; }:
▪ Defines a non-terminal symbol Calculation that matches an expression
(E).
▪ Inside the action block ({...}):
▪ Prints the calculated result using printf().
▪ Returns 0 to indicate successful parsing.
o E: E '+' E { $$ = $1 + $3; }: Matches an expression followed by a plus sign and
another expression, assigning the sum to $$ (result).
o Other rules are similar, performing subtraction, multiplication, division, modulo,
and handling parentheses and numbers.
o The yyerror() function is likely called by the parser generator (Bison) when a
syntax error is encountered. It prints an error message and sets the flag f to 1 to
indicate an invalid expression.
Main Function:
Code:
Calc.l
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval = atoi(yytext);return number;}
[\t ] ;
\n {return 0;}
. return yytext[0];
%%
int yywrap()
Exno:5 Page 2
Kaviraj N(2112064) 19CS62C-PRINCIPLES OF COMPILER DESIGN LAB1
{
return 1;
}
Calc.y
%{
#include<stdio.h>
int f = 0;
%}
%token number
%left '+''-'
%left '*''/''%'
%left '('')'
%%
Calculation: 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;}
;
%%
void main(){
Exno:5 Page 3
Kaviraj N(2112064) 19CS62C-PRINCIPLES OF COMPILER DESIGN LAB1
Exno:5 Page 4
Kaviraj N(2112064) 19CS62C-PRINCIPLES OF COMPILER DESIGN LAB1
Problem Program
Understanding and Implementation
Algorithm Record Total
(30)
(10) (10) (50)
Result:
Hence The lexical analyzer successfully generates tokens from the source file using Lex
tools and the output was verified.
Exno:5 Page 5