1use std::fmt;
5
6use super::joined;
7
8keywords! {
9 pub enum UnOp { Not => "!", Neg => "-", Plus => "+" }
11}
12
13keywords! {
14 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 pub enum AssignOp {
27 Assign => "=", Add => "+=", Sub => "-=", Mul => "*=", Div => "/=", Mod => "%=",
28 BitAnd => "&=", BitOr => "|=", BitXor => "^=", Shl => "<<=", Shr => ">>=",
29 }
30}
31
32keywords! {
33 pub enum Step { Inc => "++", Dec => "--" }
35}
36
37#[derive(Debug, Clone, PartialEq)]
44pub enum Expr {
45 Int(i128),
47 Double(f64),
49 Bool(bool),
51 Ident(String),
53 Unary {
55 op: UnOp,
57 operand: Box<Expr>,
59 },
60 Binary {
62 op: BinOp,
64 lhs: Box<Expr>,
66 rhs: Box<Expr>,
68 },
69 Ternary {
71 cond: Box<Expr>,
73 then: Box<Expr>,
75 els: Box<Expr>,
77 },
78 Call {
80 name: String,
82 args: Vec<Expr>,
84 },
85 Index {
87 base: Box<Expr>,
89 index: Box<Expr>,
91 },
92 Field {
94 base: Box<Expr>,
96 name: String,
98 },
99 Assign {
101 lhs: Box<Expr>,
103 op: AssignOp,
105 rhs: Box<Expr>,
107 },
108 Step {
110 step: Step,
112 prefix: bool,
114 operand: Box<Expr>,
116 },
117 Comma(Vec<Expr>),
119 Verbatim(String),
126}
127
128impl Expr {
129 pub fn ident(name: impl Into<String>) -> Self {
131 Expr::Ident(name.into())
132 }
133
134 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 pub fn unary(op: UnOp, operand: Expr) -> Self {
145 Expr::Unary {
146 op,
147 operand: Box::new(operand),
148 }
149 }
150
151 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 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 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}