Debian Codegraph @

documentation/manual/demos/calc.yo

raw
1 We now modify tt(rpn) to handle infix operators instead of postfix. Infix
2 notation requires us to define operator precedence and to extend the grammar
3 with nested expressions. Here is b()'s grammar specification for tt(calc), an
4 infix calculator:
5 verbinclude(calc/parser/grammar)
6 The functions tt(lex), tt(error) and tt(main) are identical to the ones
7 used with tt(rpn).
8
9 This example illustrates several important new features:
10 itemization(
11 it() In the first section (b() directives), tt(%left) declares token types
12 stating that the mentioned operators are left-associative. The directives
13 tt(%left) and tt(%right) (right associativity) are used instead of tt(%token),
14 which is merely used to declare a token identifier. The tokens mentioned with
15 tt(%left) and tt(%right) are single-character tokens, which ordinarily don't
16 need to be declared. We declare them here to specify their priority and
17 associativity.
18 it() Operator precedence is determined by the ordering of the directives;
19 the earlier tt(%left) and tt(%right) are specified, the lower the priority of
20 the operators that are following these keywords. So addition/subtraction have
21 the lowest precedence, multiplication and division are next, then unary minus
22 (tt(NEG)), and exponentiation has the highest precedence. See section
23 ref(PRECEDENCE).
24 it() Another important new feature is the tt(%prec) directive encountered
25 in the grammar section at the definition of the unary minus operator
26 production rule. The tt(%prec) directive indicates that the minus operator in
27 the production rule `tt('-' exp)' has tt(NEG's), rather than the minus
28 (tt('-')) operator's precedence. See section ref(CONDEP).
29 )
30
31 Here is a sample run of tt(calc):
32 verb(
33 % calc
34 4 + 4.5 - (34/(8*3+-3))
35 6.88095
36 -56 + 2
37 -54
38 3 ^ 2
39 9
40 )