Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Kaviraj N(2112064) 19CS62C-PRINCIPLES OF COMPILER DESIGN LAB1

Exercise 5: YACC- Implementation of Arithmetic Calculator using LEX and YACC

Aim:

To implement a simple arithmetic calculator to define an arithmetic grammar rules using


YACC specification, subroutine for action and use lex code specification to generate token from
the given input source and provide it to parser for evaluation.

Algorithm:

Lexical Analyzer (Calc.l):

o #include <stdio.h>: Includes the standard input/output library for functions


like printf().
o #include "y.tab.h": Includes a user-defined header file (likely generated by a
parser generator like Bison) that might contain token type declarations for the
parser.
o extern int yylval;: Declares an external variable yylval accessible from other files
(probably Calc.y). This variable is likely used by the lexical analyzer to store the
attribute value (e.g., numeric value) associated with a token.
o [0-9]+: Matches one or more digits, capturing the matched sequence in
the yytext string. The captured value is converted to an integer using atoi() and
stored in yylval. The token type returned is number.
o [\t ]: Matches whitespace characters (tabs and spaces), discarding them (no return
value).
o \n: Matches a newline character, returning 0 to signal the end of an input line.
o .: Matches any other single character, returning the character itself. This is a
catch-all rule to handle unexpected characters, which might be considered an error
depending on the language's syntax.
o Declared as int yywrap(). This function is typically called by the lexer (generated
by a tool like Flex) when the end of the input file is reached. By returning 1, it
signals that there's no more input to be read.

Parser (Calc.y):

o #include <stdio.h>: Includes the standard input/output library for functions


like printf().
o int f = 0;: Declares a global integer variable f, initialized to 0, which is likely used
as a flag to indicate parsing errors.
o %token number: Declares a token type named number that might represent
numeric values in the grammar.
o %left '+' '-': Declares that addition (+) and subtraction (-) have equal left-
associativity (meaning expressions are evaluated from left to right).
o %left '*' '/' '%': Similarly, declares that multiplication (*), division (/), and modulo
(%) have equal left-associativity.

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:

1. Prompts the user to enter an arithmetic expression.


2. Calls yyparse(), which initiates the parsing process.
3. If f remains 0 (no errors), it prints a success message

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

printf("\nEnter Arithmetic Expression:\n");


yyparse();
if(f==0)
printf("\n Entered arithmetic Expression is Valid\n\n");
}
void yyerror(){
printf("\n Entered arithmetic Expression is Invalid\n\n");
f=1;
}
Output:

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

You might also like