| 1 |
The grammar specification file for the tt(mfcalc) calculator shows several new |
| 2 |
features. Here is the b() directive section for the tt(mfcalc) multi-function |
| 3 |
calculator (line numbers were added for referential purposes, they are not |
| 4 |
part of the declaraction section as used in the actual grammar file): |
| 5 |
verb( |
| 6 |
1 %union |
| 7 |
2 { |
| 8 |
3 double u_val; |
| 9 |
4 double *u_symbol; |
| 10 |
5 double (*u_fun)(double); |
| 11 |
6 } |
| 12 |
7 |
| 13 |
8 %token <u_val> NUM // Simple double precision number |
| 14 |
9 %token <u_symbol> VAR // Variable |
| 15 |
10 %token <u_fun> FNCT // Function |
| 16 |
11 %type <u_val> exp |
| 17 |
12 |
| 18 |
13 %right '=' |
| 19 |
14 %left '-' '+' |
| 20 |
15 %left '*' '/' |
| 21 |
16 %left NEG // negation--unary minus |
| 22 |
17 %right '^' // exponentiation |
| 23 |
) |
| 24 |
The above specifications show two new features of b()'s grammar |
| 25 |
specification language, allowing semantic values to have different data types. |
| 26 |
itemization( |
| 27 |
it() The tt(%union) directive (given in lines 1 through 6) allows semantic |
| 28 |
values to have various data types (see section ref(UNION)). It is used |
| 29 |
instead of tt(%stype), and defines tt(Parser::STYPE_) as a the union type: |
| 30 |
all semantic values now have this type. Now semantic values can have any of |
| 31 |
the types that are defined as the union's fields. |
| 32 |
it() The tt(%type) directive is used to associate (non)terminal tokens with |
| 33 |
the types of the fields of the union: |
| 34 |
itemization( |
| 35 |
itt(double) (for tt(exp) and tt(NUM)); |
| 36 |
it() a em(pointer) to a tt(double), being a pointer to entries in |
| 37 |
tt(mfcalc)'s symbol table, used with tt(VAR) tokens. |
| 38 |
it() a em(pointer to a function) expecting a tt(double) argument and |
| 39 |
returning a tt(double) value, used with tt(FNCT) tokens. |
| 40 |
) |
| 41 |
Since semantic values no longer are of one single type, each grammar |
| 42 |
symbol whose semantic value is used must explicitly be associated with one of |
| 43 |
the types of the fields of the union. This holds true for the symbols tt(NUM, |
| 44 |
VAR, FNCT), and tt(exp). The tt(%type) directive first specifies (between |
| 45 |
angle brackets) one of the union's field types, followed by a list of (blank |
| 46 |
or comma separated) nonterminal or terminal symbols which are associated with |
| 47 |
the specified union field type. |
| 48 |
) |
| 49 |
Finally note the em(right associative) operator `tt(=)', defined in line |
| 50 |
13: by making the assignment operator right-associative we can allow |
| 51 |
em(sequential assignments) of the form tt(a = b = c = expression). |
| 52 |
|
| 53 |
|
| 54 |
|