1 /* -----------------------------------------------------
2
3 basic notes:
4
5 bison is a parser generator.
6
7 similar syntax to flex.
8
9 ----------------------
10 %{
11 c declarations
12 %}
13 bison declarations
14 %%
15 grammar rules
16 %%
17 user routines
18 ----------------------
19
20 precedence rules (e.g. %left, %right) are given
21 more priority further down the list
22 ( unary minus > multiplication > addition).
23
24 define tokens in this file -- flex will find them
25 in the bison header file you explicitly #include.
26
27 bison
28 -d Generate bison header file including
29 macros, tokens.
30 -v Write out a *verbose* file describing
31 all parser states. Very useful for
32 debugging shift/reduce conflicts.
33
34 compile
35
36 bison -d (-v) parser.y
37 flex scanner.l
38 gcc lex.yy.c parser.tab.c -lfl -o ti89
39
40
41 use yyerrok to tell parser that "syntax error
42 recovery is done, proceed as normal."
43
44 --------------------------------------------------- */
45
46 %{
47 #include <stdio.h>
48 %}
49
50 %start calculator
51
52 %token NUMBER
53
54 %left '+' '-'
55 %left '*' '/' '%'
56 %right UMINUS
57
58 %%
59
60 calculator: /* empty */
61 | calculator expr '\n' { printf("> %d\n\n", $2); }
62 | calculator error '\n' { yyerrok; }
63 ;
64
65
66 expr: '(' expr ')' { $$ = $2; }
67 | expr '*' expr { $$ = $1 * $3; }
68 | expr '/' expr { $$ = $1 / $3; }
69 | expr '%' expr { $$ = $1 % $3; }
70 | expr '+' expr { $$ = $1 + $3; }
71 | expr '-' expr { $$ = $1 - $3; }
72 | '-' expr %prec UMINUS { $$ = -$2; }
73 | NUMBER { $$ = $1; }
74 ;
75
76 %%
77
78 int main( void )
79 {
80 return yyparse();
81 }
82
83 int yyerror( char *s)
84 {
85 fprintf(stderr, "%s\n",s);
86 }