-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharithmetic.l
More file actions
65 lines (51 loc) · 936 Bytes
/
Copy patharithmetic.l
File metadata and controls
65 lines (51 loc) · 936 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// lex file
%{
/* Definition section*/
#include "y.tab.h"
extern yylval;
%}
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
[a-zA-Z]+ { return ID; }
[ \t]+ ; /*For skipping whitespaces*/
\n { return 0; }
. { return yytext[0]; }
%%
// yacc file
%{
/* Definition section */
#include <stdio.h>
%}
%token NUMBER ID
// setting the precedence
// and associativity of operators
%left '+' '-'
%left '*' '/'
/* Rule Section */
%%
E : T {
printf("Result = %d\n", $$);
return 0;
}
T :
T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
% %
int main() {
printf("Enter the expression\n");
yyparse();
}
/* For printing error messages */
int yyerror(char* s) {
printf("\nExpression is invalid\n");
}