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