Skip to main content

sim_codec_algol/pratt/
table.rs

1//! Operator table for the Algol codec: builds the default `PrattTable` of infix
2//! and other operators with their fixities and binding powers, and reports
3//! whether Pratt parsing is supported.
4
5use sim_kernel::{Fixity, PrattOperator, PrattResult, PrattTable, Symbol};
6
7/// Reports whether this codec offers Pratt parsing. Always `true` for the Algol
8/// surface.
9pub fn supports_pratt() -> bool {
10    true
11}
12
13/// Builds the default Algol operator table.
14///
15/// Registers the arithmetic operators with their fixities and binding powers:
16/// left-associative `+` and `-` (binding power 50/51), `*` and `/` (60/61),
17/// right-associative `^` (80), prefix negation `-` (90), and postfix `!` (100).
18/// Higher binding power binds more tightly, so `1 + 2 * 3` groups as
19/// `1 + (2 * 3)`.
20pub fn default_pratt_table() -> PrattTable {
21    let mut table = PrattTable::new();
22    table.register(PrattOperator {
23        symbol: Symbol::new("+"),
24        fixity: Fixity::InfixLeft,
25        left_bp: 50,
26        right_bp: 51,
27        result: PrattResult::ExprInfix,
28    });
29    table.register(PrattOperator {
30        symbol: Symbol::new("-"),
31        fixity: Fixity::InfixLeft,
32        left_bp: 50,
33        right_bp: 51,
34        result: PrattResult::ExprInfix,
35    });
36    table.register(PrattOperator {
37        symbol: Symbol::new("*"),
38        fixity: Fixity::InfixLeft,
39        left_bp: 60,
40        right_bp: 61,
41        result: PrattResult::ExprInfix,
42    });
43    table.register(PrattOperator {
44        symbol: Symbol::new("/"),
45        fixity: Fixity::InfixLeft,
46        left_bp: 60,
47        right_bp: 61,
48        result: PrattResult::ExprInfix,
49    });
50    table.register(PrattOperator {
51        symbol: Symbol::new("^"),
52        fixity: Fixity::InfixRight,
53        left_bp: 80,
54        right_bp: 80,
55        result: PrattResult::ExprInfix,
56    });
57    table.register(PrattOperator {
58        symbol: Symbol::new("-"),
59        fixity: Fixity::Prefix,
60        left_bp: 0,
61        right_bp: 90,
62        result: PrattResult::ExprPrefix,
63    });
64    table.register(PrattOperator {
65        symbol: Symbol::new("!"),
66        fixity: Fixity::Postfix,
67        left_bp: 100,
68        right_bp: 0,
69        result: PrattResult::ExprPostfix,
70    });
71    table
72}