Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %{
- #include <stdio.h>
- void yyerror(char *);
- int yylex(void);
- int sym[26];
- %}
- %token INTEGER VARIABLE
- %token EXIT
- %left '+' '-'
- %left '*' '/'
- %left '^'
- %left '>' '<' GE LE EQ NE
- %left COS SIN TAN SQRT EXP CTAN POW LOG
- %%
- program:
- program statement '\n'
- | /* NULL */
- ;
- statement:
- expression { printf("%d\n", $1); }
- | VARIABLE '=' expression { sym[$1] = $3; }
- ;
- expression:
- INTEGER
- | VARIABLE { $$ = sym[$1]; }
- | expression '+' expression { $$ = $1 + $3; }
- | expression '-' expression { $$ = $1 - $3; }
- | expression '*' expression { $$ = $1 * $3; }
- | expression '/' expression { $$ = $1 / $3; }
- | '(' expression ')' { $$ = $2; }
- | COS expression { $$ = printf("%.2f", cos($2)); }
- | SIN expression { $$ = printf("%.2f", sin($2)); }
- | TAN expression { printf("%.2f",tan($2)); }
- | CTAN expression { printf("%.2f", 1/tan($2)); }
- | expression POW expression { $$ = pow($1,$3);}
- | SQRT expression { $$ = sqrt($2);}
- | LOG expression { printf("%f", log($2));}
- | expression '<' expression { ($1 < $3) ? printf("True\n"):printf("False\n"); }
- | expression '>' expression { ($1 > $3) ? printf("True\n"):printf("False\n");}
- | expression GE expression { ($1 >= $3) ? printf("True\n"):printf("False\n"); }
- | expression LE expression { ($1 <= $3) ? printf("True\n"):printf("False\n"); }
- | expression EQ expression { ($1 <= $3) ? printf("True\n"):printf("False\n"); }
- | expression NE expression { ($1 != $3) ? printf("True\n"):printf("False\n"); }
- | EXIT {exit(0);}
- ;
- %%
- void yyerror(char *s) {
- fprintf(stderr, "%s\n", s);
- }
- int main(void) {
- yyparse();
- }
- //================================================================================
- //LEX
- /* calculator #1 */
- %{
- #include "y.tab.h"
- #include <stdlib.h>
- #include <math.h>
- void yyerror(char *);
- %}
- %%
- "cos" return COS;
- "sin" return SIN;
- "tan" return TAN;
- "ctan" return CTAN;
- "pow" return POW;
- "sqrt" return SQRT;
- "log" return LOG;
- ">=" return GE;
- "<=" return LE;
- "==" return EQ;
- "!=" return NE;
- "exit" return EXIT;
- [a-z]* {
- yylval = *yytext - 'a';
- return VARIABLE;
- }
- [1-9][0-9]* {
- yylval = atoi(yytext);
- return INTEGER;
- }
- [-+()=/*\n<>] { return *yytext; }
- [ \t\n] ; /* skip whitespace */
- . yyerror("Unknown character");
- %%
- int yywrap(void) {
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement