%{ #include <stdio.h> #include <ctype.h> %} %token NUMBER %% command : exp {prin
ID: 3567491 • Letter: #
Question
%{
#include <stdio.h>
#include <ctype.h>
%}
%token NUMBER
%%
command : exp {printf("%d ", $1);}
; /* allows printing of the result */
exp : exp '+' term {$$ = $1 + $3;}
| exp '-' term {$$ = $1 - $3;}
| term {$$ = $1;}
;
term : term '*' factor {$$ = $1 * $3;}
| factor {$$ = $1;}
;
factor : NUMBER {$$ = $1;}
| '(' exp ')' {$$ = $2;}
;
%%
main()
{
return yyparse();
}
int yylex(void)
{
int c;
while((c = getchar()) == ' ');
/* eliminates blanks */
if (isdigit(c)){
ungetc(c, stdin);
scanf("%d", &yylval);
return (NUMBER);
}
if ( c == ' ') return 0;
/* makes the parse stop */
return (c);
}
int yyerror(char * s){
fprintf(stderr, "%s ", s);
return 0;
} /* allows for printing of an error message */
?
5.27) Rewrite the Yacc specification of the above the program to use the following grammer rules (instead of scanf) to calculate the value of a number (and, hence, do away with the NUMBER token):
number ? number digit | digit
digit ? 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
5.28) Add the following to the Yacc integer calculator specification for the above program(make sure they have the correct associativity and precedence):
Integer division with the symbol /.
Integer mod with the symbol %.
Integer exponentiation with the symbol ^. (Warning: This operator has higher precedence than multiplication and is right associative.)
Unary minus with the symbol
5.29) Redo the Yacc calculator specification of the above program so that the calculator will accept floating point numbers ( and perform floating point calculations).
5.30) Rewrite the Yacc calculator specification for the above figure so that it distinguishes between floating point and integer values, rather than simply computing everything as integers or floating point numbers. ( Hint: A
Explanation / Answer
5.27) We have to make another file having flec specification.
It would be like:
%{
#include<stdio.h>
#include "y.tab.h"
%}
digit [0-9]
number [0-9]{digit}*
%%
{number} {yylval.int_val=atoi(yytext);return NUMBER;}
%%
in yacc file no changes in needed then.
5.28)
exp: exp: + term;
exp: exp - term
exp:term
term:term * factor
term: term / factor
term: term % factor
Factor: -expression
Factor: NUMBER
5.30) in flex we make the follwing changes:
%{
#include<stdio.h>
#include "y.tab.h"
%}
digit [0-9]
number [0-9]{digit}*
f_const (([1-9][0-9]*.?[0-9]*)|(.[0-9]+))([Ee][+-]?[0-9]+)?
%%
{number} {yylval.int_val=atoi(yytext);return NUMBER;}
{f_const} { yylval.f_val=atof(yytext);return F_CONSTANT;}
%%
in yacc write :
%union {
int int_val;
float f_val;
};
%token NUMBER F_CONSTANT
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.