Number (0-9) + %% (/ Skip Blanks /) (Number) (Sscanf (Yytext,"%lf",&yylval) Return INTEGER ) - (Return Yytext (0) ) /N (Return Yytext (0) )

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Submitted by 04CS3009,Puneet Jain

Assignment No 03:
We want to construct a simple pocket-calculator program using yacc and lex
which can parse strings such as 1+(10-5-3)*5+2 and print the result, 13 in this
case. Outline the overall structure of your program components. Give full
details of the input to yacc and lex. (Precise syntactic details are not important,
but your answer should reflect basic principles involved)

Make following assumption :


- Only three binary operator are allowed i.e. plus, minus and multiply
- Only integer data type is allowed
- Parentheses are used to override precedence.

Compile the program using following commands

$lex calculator.l
$yacc calculator.y
$cc y.tab.c –ly -ll

****************Lexical Analyzer**************************

number [0-9]+
%%
[ ] { /*skip blanks*/}

{number} {
sscanf(yytext,"%lf",&yylval);
return INTEGER;
}

. {return yytext[0];
}
\n {return yytext[0];
}

*****************Yacc Pharser ************************


%{
#include <ctype.h>
#include <stdio.h>
#define YYSTYPE double
%}

%token INTEGER
%left '+' '-'
%left '*'
%right UMINUS

%%
lines : lines expr '\n' {printf("%g\n",$2);}
| lines '\n'
|
| error '\n' {yyerror("reenter last line :");
yyerrok;}
;

expr : | expr '+' expr {$$=$1+$3;}


| expr '-' expr {$$=$1-$3;}
| expr '*' expr {$$=$1*$3;}
| '(' expr ')'{$$=$2;}
| '-' expr %prec UMINUS {$$=-$2;}
| INTEGER
;

%%
#include "lex.yy.c"

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