Skip to main content

fic/xta_backend/xta/
expr.rs

1//! Expressions (`Expression`, parser.y:1087): the operators, assignment as an
2//! expression, `++`/`--` and the comma list.
3
4use std::fmt;
5
6use super::joined;
7
8keywords! {
9    /// Unary operators of the printed subset.
10    pub enum UnOp { Not => "!", Neg => "-", Plus => "+" }
11}
12
13keywords! {
14    /// Binary operators (`BinaryOp` in UTAP's grammar).
15    pub enum BinOp {
16        Add => "+", Sub => "-", Mul => "*", Div => "/", Mod => "%",
17        Eq => "==", Ne => "!=", Lt => "<", Le => "<=", Gt => ">", Ge => ">=",
18        And => "&&", Or => "||",
19        BitAnd => "&", BitOr => "|", BitXor => "^", Shl => "<<", Shr => ">>",
20        Min => "<?", Max => ">?", Imply => "imply",
21    }
22}
23
24keywords! {
25    /// The operator of an assignment expression (`AssignOp`).
26    pub enum AssignOp {
27        Assign => "=", Add => "+=", Sub => "-=", Mul => "*=", Div => "/=", Mod => "%=",
28        BitAnd => "&=", BitOr => "|=", BitXor => "^=", Shl => "<<=", Shr => ">>=",
29    }
30}
31
32keywords! {
33    /// `++` or `--`.
34    pub enum Step { Inc => "++", Dec => "--" }
35}
36
37/// An expression: what a declaration, a function body or a transition label
38/// is built from.
39///
40/// Compound forms print fully parenthesised. UPPAAL's precedence table is not
41/// C's — `T_MIN`/`T_MAX` and the bit operators sit in places a reader does not
42/// expect — so the printer never relies on it.
43#[derive(Debug, Clone, PartialEq)]
44pub enum Expr {
45    /// An integer literal.
46    Int(i128),
47    /// A floating-point literal.
48    Double(f64),
49    /// `true` / `false`.
50    Bool(bool),
51    /// A bare identifier.
52    Ident(String),
53    /// `op operand`.
54    Unary {
55        /// The operator.
56        op: UnOp,
57        /// The operand.
58        operand: Box<Expr>,
59    },
60    /// `lhs op rhs`.
61    Binary {
62        /// The operator.
63        op: BinOp,
64        /// Left operand.
65        lhs: Box<Expr>,
66        /// Right operand.
67        rhs: Box<Expr>,
68    },
69    /// `cond ? then : els`.
70    Ternary {
71        /// The condition.
72        cond: Box<Expr>,
73        /// Value when the condition holds.
74        then: Box<Expr>,
75        /// Value otherwise.
76        els: Box<Expr>,
77    },
78    /// `f(a, b)`.
79    Call {
80        /// The function name.
81        name: String,
82        /// The arguments, in order.
83        args: Vec<Expr>,
84    },
85    /// `base[index]`.
86    Index {
87        /// The indexed expression.
88        base: Box<Expr>,
89        /// The index.
90        index: Box<Expr>,
91    },
92    /// `base.name`.
93    Field {
94        /// The struct-valued expression.
95        base: Box<Expr>,
96        /// The field name.
97        name: String,
98    },
99    /// `lhs op rhs`: an assignment is an expression in UTAP, as in C.
100    Assign {
101        /// The assigned location.
102        lhs: Box<Expr>,
103        /// The operator.
104        op: AssignOp,
105        /// The assigned value.
106        rhs: Box<Expr>,
107    },
108    /// `++x`, `x++`, `--x` or `x--`.
109    Step {
110        /// Increment or decrement.
111        step: Step,
112        /// `++x` rather than `x++`.
113        prefix: bool,
114        /// The stepped location.
115        operand: Box<Expr>,
116    },
117    /// `a, b, c`: the comma list (`ExprList`), as an update label is.
118    Comma(Vec<Expr>),
119    /// Pre-rendered UPPAAL text, spliced in as written.
120    ///
121    /// The escape hatch for what the enum cannot hold: one of the
122    /// placeholder comments the transpiler emits where a foreign call has no
123    /// usable contract (`/* io.f() */ 0`). Everything that *can* be
124    /// structured should be.
125    Verbatim(String),
126}
127
128impl Expr {
129    /// An identifier expression.
130    pub fn ident(name: impl Into<String>) -> Self {
131        Expr::Ident(name.into())
132    }
133
134    /// `lhs op rhs`.
135    pub fn binary(op: BinOp, lhs: Expr, rhs: Expr) -> Self {
136        Expr::Binary {
137            op,
138            lhs: Box::new(lhs),
139            rhs: Box::new(rhs),
140        }
141    }
142
143    /// `op operand`.
144    pub fn unary(op: UnOp, operand: Expr) -> Self {
145        Expr::Unary {
146            op,
147            operand: Box::new(operand),
148        }
149    }
150
151    /// `lhs op rhs`, an assignment.
152    pub fn assign(lhs: Expr, op: AssignOp, rhs: Expr) -> Self {
153        Expr::Assign {
154            lhs: Box::new(lhs),
155            op,
156            rhs: Box::new(rhs),
157        }
158    }
159}
160
161impl fmt::Display for Expr {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Expr::Int(n) => write!(f, "{n}"),
165            Expr::Double(x) => write!(f, "{x}"),
166            Expr::Bool(b) => write!(f, "{b}"),
167            Expr::Ident(name) => f.write_str(name),
168            Expr::Unary { op, operand } => write!(f, "{op}({operand})"),
169            Expr::Binary { op, lhs, rhs } => write!(f, "({lhs}) {op} ({rhs})"),
170            Expr::Ternary { cond, then, els } => write!(f, "({cond}) ? ({then}) : ({els})"),
171            Expr::Call { name, args } => {
172                write!(f, "{name}(")?;
173                for (i, arg) in args.iter().enumerate() {
174                    if i > 0 {
175                        f.write_str(", ")?;
176                    }
177                    // A comma list as one argument, not several.
178                    match arg {
179                        Expr::Comma(_) => write!(f, "({arg})")?,
180                        _ => write!(f, "{arg}")?,
181                    }
182                }
183                f.write_str(")")
184            }
185            Expr::Index { base, index } => write!(f, "{base}[{index}]"),
186            Expr::Field { base, name } => write!(f, "({base}).{name}"),
187            Expr::Assign { lhs, op, rhs } => write!(f, "{lhs} {op} {rhs}"),
188            Expr::Step {
189                step,
190                prefix: true,
191                operand,
192            } => write!(f, "{step}{operand}"),
193            Expr::Step {
194                step,
195                prefix: false,
196                operand,
197            } => write!(f, "{operand}{step}"),
198            Expr::Comma(items) => joined(f, items, ", "),
199            Expr::Verbatim(text) => f.write_str(text),
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use crate::xta_backend::xta::*;
207
208    fn x() -> Expr {
209        Expr::ident("x")
210    }
211
212    #[test]
213    fn bitwise_min_max_and_imply_print_as_utap_spells_them() {
214        let cases = [
215            (BinOp::BitAnd, "(x) & (1)"),
216            (BinOp::BitOr, "(x) | (1)"),
217            (BinOp::BitXor, "(x) ^ (1)"),
218            (BinOp::Shl, "(x) << (1)"),
219            (BinOp::Shr, "(x) >> (1)"),
220            (BinOp::Min, "(x) <? (1)"),
221            (BinOp::Max, "(x) >? (1)"),
222            (BinOp::Imply, "(x) imply (1)"),
223        ];
224        for (op, text) in cases {
225            assert_eq!(Expr::binary(op, x(), Expr::Int(1)).to_string(), text);
226        }
227        assert_eq!(Expr::unary(UnOp::Plus, x()).to_string(), "+(x)");
228    }
229
230    #[test]
231    fn assignment_is_an_expression() {
232        let e = Expr::assign(x(), AssignOp::Shl, Expr::Int(2));
233        assert_eq!(e.to_string(), "x <<= 2");
234        assert_eq!(
235            Stmt::Expr(Expr::assign(x(), AssignOp::Assign, Expr::Int(1))).to_string(),
236            "x = 1;"
237        );
238        // Nested, it is parenthesised like every other compound form.
239        let nested = Expr::binary(
240            BinOp::Add,
241            Expr::assign(x(), AssignOp::Add, Expr::Int(1)),
242            Expr::Int(2),
243        );
244        assert_eq!(nested.to_string(), "(x += 1) + (2)");
245    }
246
247    #[test]
248    fn increments_prefix_and_postfix() {
249        let step = |step, prefix| Expr::Step {
250            step,
251            prefix,
252            operand: Box::new(x()),
253        };
254        assert_eq!(step(Step::Inc, true).to_string(), "++x");
255        assert_eq!(step(Step::Inc, false).to_string(), "x++");
256        assert_eq!(step(Step::Dec, true).to_string(), "--x");
257        assert_eq!(step(Step::Dec, false).to_string(), "x--");
258    }
259
260    #[test]
261    fn a_comma_list_is_one_argument() {
262        let list = Expr::Comma(vec![
263            Expr::assign(x(), AssignOp::Assign, Expr::Int(0)),
264            Expr::ident("y"),
265        ]);
266        assert_eq!(list.to_string(), "x = 0, y");
267        let call = Expr::Call {
268            name: "f".to_string(),
269            args: vec![list, Expr::Int(3)],
270        };
271        assert_eq!(call.to_string(), "f((x = 0, y), 3)");
272    }
273
274    #[test]
275    fn expressions_parenthesise_conservatively() {
276        let e = Expr::Ternary {
277            cond: Box::new(Expr::binary(BinOp::Lt, Expr::ident("r"), Expr::ident("N"))),
278            then: Box::new(Expr::Int(1)),
279            els: Box::new(Expr::Int(0)),
280        };
281        assert_eq!(e.to_string(), "((r) < (N)) ? (1) : (0)");
282        assert_eq!(Expr::unary(UnOp::Not, Expr::ident("p")).to_string(), "!(p)");
283        assert_eq!(
284            Expr::Field {
285                base: Box::new(Expr::ident("pkt")),
286                name: "len".into(),
287            }
288            .to_string(),
289            "(pkt).len"
290        );
291        assert_eq!(Expr::Verbatim("0x1f".into()).to_string(), "0x1f");
292        assert_eq!(
293            Expr::Call {
294                name: "io_f".into(),
295                args: vec![Expr::ident("x"), Expr::Int(2)],
296            }
297            .to_string(),
298            "io_f(x, 2)"
299        );
300    }
301}