| 1 | <h2>Comments</h2> |
| 2 | <pre><code>// Single-line comment |
| 3 | /* Multi-line |
| 4 | comment */</code></pre> |
| 5 | |
| 6 | <h2>C prologue and Bison declarations</h2> |
| 7 | <pre><code>%{ |
| 8 | #include <stdio.h> |
| 9 | #include <math.h> |
| 10 | int yylex (void); |
| 11 | void yyerror (char const *); |
| 12 | %} |
| 13 | |
| 14 | %define api.value.type {double} |
| 15 | %token NUM |
| 16 | %union { char *string; } |
| 17 | %% |
| 18 | %%</code></pre> |
| 19 | |
| 20 | <h2>Grammar rules</h2> |
| 21 | <pre><code>%% |
| 22 | exp: |
| 23 | NUM { $$ = $1; } |
| 24 | | exp exp '+' { $$ = $1 + $2; } |
| 25 | | exp exp '-' { $$ = $1 - $2; } |
| 26 | | exp exp '*' { $$ = $1 * $2; } |
| 27 | | exp exp '/' { $$ = $1 / $2; } |
| 28 | | exp exp '^' { $$ = pow($1, $2); } /* Exponentiation */ |
| 29 | | exp 'n' { $$ = -$1; } /* Unary minus */ |
| 30 | ; |
| 31 | |
| 32 | $@1: %empty { a(); }; |
| 33 | $@2: %empty { c(); }; |
| 34 | $@3: %empty { d(); }; |
| 35 | exp: $@1 "b" $@2 $@3 "e" { f(); }; |
| 36 | %%</code></pre> |
| 37 | |
| 38 | <h2>Full example</h2> |
| 39 | <pre><code>/* Mini Calculator */ |
| 40 | /* calc.y */ |
| 41 | |
| 42 | %{ |
| 43 | #include "heading.h" |
| 44 | int yyerror(char *s); |
| 45 | int yylex(void); |
| 46 | %} |
| 47 | |
| 48 | %union{ |
| 49 | int int_val; |
| 50 | string* op_val; |
| 51 | } |
| 52 | |
| 53 | %start input |
| 54 | |
| 55 | %token <int_val> INTEGER_LITERAL |
| 56 | %type <int_val> exp |
| 57 | %left PLUS |
| 58 | %left MULT |
| 59 | |
| 60 | %% |
| 61 | |
| 62 | input: /* empty */ |
| 63 | | exp { cout << "Result: " << $1 << endl; } |
| 64 | ; |
| 65 | |
| 66 | exp: INTEGER_LITERAL { $$ = $1; } |
| 67 | | exp PLUS exp { $$ = $1 + $3; } |
| 68 | | exp MULT exp { $$ = $1 * $3; } |
| 69 | ; |
| 70 | |
| 71 | %% |
| 72 | |
| 73 | int yyerror(string s) |
| 74 | { |
| 75 | extern int yylineno; // defined and maintained in lex.c |
| 76 | extern char *yytext; // defined and maintained in lex.c |
| 77 | |
| 78 | cerr << "ERROR: " << s << " at symbol \"" << yytext; |
| 79 | cerr << "\" on line " << yylineno << endl; |
| 80 | exit(1); |
| 81 | } |
| 82 | |
| 83 | int yyerror(char *s) |
| 84 | { |
| 85 | return yyerror(string(s)); |
| 86 | }</code></pre> |