Debian Codegraph @

examples/prism-bison.html

raw symbols SCIP
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 &lt;stdio.h>
9 #include &lt;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 &lt;int_val> INTEGER_LITERAL
56 %type &lt;int_val> exp
57 %left PLUS
58 %left MULT
59
60 %%
61
62 input: /* empty */
63 | exp { cout &lt;&lt; "Result: " &lt;&lt; $1 &lt;&lt; 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 &lt;&lt; "ERROR: " &lt;&lt; s &lt;&lt; " at symbol \"" &lt;&lt; yytext;
79 cerr &lt;&lt; "\" on line " &lt;&lt; yylineno &lt;&lt; endl;
80 exit(1);
81 }
82
83 int yyerror(char *s)
84 {
85 return yyerror(string(s));
86 }</code></pre>