summaryrefslogtreecommitdiff
path: root/src/syntax/expr.rs
blob: cb09041ce50f686ddc80cf11a18d8c02fcb994d3 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use super::*;
use crate::color::RgbaColor;
use crate::geom::{AngularUnit, LengthUnit};

/// An expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// The none literal: `none`.
    None,
    /// A identifier literal: `left`.
    Ident(Ident),
    /// A boolean literal: `true`, `false`.
    Bool(bool),
    /// An integer literal: `120`.
    Int(i64),
    /// A floating-point literal: `1.2`, `10e-4`.
    Float(f64),
    /// A length literal: `12pt`, `3cm`.
    Length(f64, LengthUnit),
    /// An angle literal:  `1.5rad`, `90deg`.
    Angle(f64, AngularUnit),
    /// A percent literal: `50%`.
    ///
    /// _Note_: `50%` is stored as `50.0` here, but as `0.5` in the
    /// corresponding [value](crate::geom::Relative).
    Percent(f64),
    /// A color literal: `#ffccee`.
    Color(RgbaColor),
    /// A string literal: `"hello!"`.
    Str(String),
    /// An invocation of a function: `[foo ...]`, `foo(...)`.
    Call(ExprCall),
    /// A unary operation: `-x`.
    Unary(ExprUnary),
    /// A binary operation: `a + b`, `a / b`.
    Binary(ExprBinary),
    /// An array expression: `(1, "hi", 12cm)`.
    Array(ExprArray),
    /// A dictionary expression: `(color: #f79143, pattern: dashed)`.
    Dict(ExprDict),
    /// A template expression: `[*Hi* there!]`.
    Template(ExprTemplate),
}

impl Pretty for Expr {
    fn pretty(&self, p: &mut Printer) {
        match self {
            Self::None => p.push_str("none"),
            Self::Ident(v) => p.push_str(&v),
            Self::Bool(v) => write!(p, "{}", v).unwrap(),
            Self::Int(v) => write!(p, "{}", v).unwrap(),
            Self::Float(v) => write!(p, "{}", v).unwrap(),
            Self::Length(v, u) => write!(p, "{}{}", v, u).unwrap(),
            Self::Angle(v, u) => write!(p, "{}{}", v, u).unwrap(),
            Self::Percent(v) => write!(p, "{}%", v).unwrap(),
            Self::Color(v) => write!(p, "{}", v).unwrap(),
            Self::Str(s) => write!(p, "{:?}", &s).unwrap(),
            Self::Call(call) => call.pretty(p),
            Self::Unary(unary) => unary.pretty(p),
            Self::Binary(binary) => binary.pretty(p),
            Self::Array(array) => array.pretty(p),
            Self::Dict(dict) => dict.pretty(p),
            Self::Template(template) => pretty_template_expr(template, p),
        }
    }
}

/// Pretty print a template in an expression context.
pub fn pretty_template_expr(tree: &Tree, p: &mut Printer) {
    p.push_str("[");
    tree.pretty(p);
    p.push_str("]");
}

/// An invocation of a function: `[foo ...]`, `foo(...)`.
#[derive(Debug, Clone, PartialEq)]
pub struct ExprCall {
    /// The name of the function.
    pub name: Spanned<Ident>,
    /// The arguments to the function.
    pub args: Spanned<ExprArgs>,
}

impl Pretty for ExprCall {
    fn pretty(&self, p: &mut Printer) {
        p.push_str(&self.name.v);
        p.push_str("(");
        self.args.v.pretty(p);
        p.push_str(")");
    }
}

/// Pretty print a bracketed function call, with body or chaining when possible.
pub fn pretty_bracket_call(call: &ExprCall, p: &mut Printer, chained: bool) {
    if chained {
        p.push_str(" | ");
    } else {
        p.push_str("[");
    }

    // Function name.
    p.push_str(&call.name.v);

    // Find out whether this can be written with a body or as a chain.
    //
    // Example: Transforms "[v [Hi]]" => "[v][Hi]".
    if let [head @ .., Argument::Pos(Spanned { v: Expr::Template(template), .. })] =
        call.args.v.as_slice()
    {
        // Previous arguments.
        if !head.is_empty() {
            p.push_str(" ");
            p.join(head, ", ", |item, p| item.pretty(p));
        }

        // Find out whether this can written as a chain.
        //
        // Example: Transforms "[v][[f]]" => "[v | f]".
        if let [Spanned { v: Node::Expr(Expr::Call(call)), .. }] = template.as_slice() {
            return pretty_bracket_call(call, p, true);
        } else {
            p.push_str("][");
            template.pretty(p);
        }
    } else if !call.args.v.is_empty() {
        p.push_str(" ");
        call.args.v.pretty(p);
    }

    // Either end of header or end of body.
    p.push_str("]");
}

/// The arguments to a function: `12, draw: false`.
///
/// In case of a bracketed invocation with a body, the body is _not_
/// included in the span for the sake of clearer error messages.
pub type ExprArgs = Vec<Argument>;

impl Pretty for Vec<Argument> {
    fn pretty(&self, p: &mut Printer) {
        p.join(self, ", ", |item, p| item.pretty(p));
    }
}

/// An argument to a function call: `12` or `draw: false`.
#[derive(Debug, Clone, PartialEq)]
pub enum Argument {
    /// A positional arguments.
    Pos(Spanned<Expr>),
    /// A named argument.
    Named(Named),
}

impl Pretty for Argument {
    fn pretty(&self, p: &mut Printer) {
        match self {
            Self::Pos(expr) => expr.v.pretty(p),
            Self::Named(named) => named.pretty(p),
        }
    }
}

/// A pair of a name and an expression: `pattern: dashed`.
#[derive(Debug, Clone, PartialEq)]
pub struct Named {
    /// The name: `pattern`.
    pub name: Spanned<Ident>,
    /// The right-hand side of the pair: `dashed`.
    pub expr: Spanned<Expr>,
}

impl Pretty for Named {
    fn pretty(&self, p: &mut Printer) {
        p.push_str(&self.name.v);
        p.push_str(": ");
        self.expr.v.pretty(p);
    }
}

/// A unary operation: `-x`.
#[derive(Debug, Clone, PartialEq)]
pub struct ExprUnary {
    /// The operator: `-`.
    pub op: Spanned<UnOp>,
    /// The expression to operator on: `x`.
    pub expr: Box<Spanned<Expr>>,
}

impl Pretty for ExprUnary {
    fn pretty(&self, p: &mut Printer) {
        self.op.v.pretty(p);
        self.expr.v.pretty(p);
    }
}

/// A unary operator.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum UnOp {
    /// The negation operator: `-`.
    Neg,
}

impl Pretty for UnOp {
    fn pretty(&self, p: &mut Printer) {
        p.push_str(match self {
            Self::Neg => "-",
        });
    }
}

/// A binary operation: `a + b`, `a / b`.
#[derive(Debug, Clone, PartialEq)]
pub struct ExprBinary {
    /// The left-hand side of the operation: `a`.
    pub lhs: Box<Spanned<Expr>>,
    /// The operator: `+`.
    pub op: Spanned<BinOp>,
    /// The right-hand side of the operation: `b`.
    pub rhs: Box<Spanned<Expr>>,
}

impl Pretty for ExprBinary {
    fn pretty(&self, p: &mut Printer) {
        self.lhs.v.pretty(p);
        p.push_str(" ");
        self.op.v.pretty(p);
        p.push_str(" ");
        self.rhs.v.pretty(p);
    }
}

/// A binary operator.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BinOp {
    /// The addition operator: `+`.
    Add,
    /// The subtraction operator: `-`.
    Sub,
    /// The multiplication operator: `*`.
    Mul,
    /// The division operator: `/`.
    Div,
}

impl Pretty for BinOp {
    fn pretty(&self, p: &mut Printer) {
        p.push_str(match self {
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
        });
    }
}

/// An array expression: `(1, "hi", 12cm)`.
pub type ExprArray = SpanVec<Expr>;

impl Pretty for ExprArray {
    fn pretty(&self, p: &mut Printer) {
        p.push_str("(");
        p.join(self, ", ", |item, p| item.v.pretty(p));
        if self.len() == 1 {
            p.push_str(",");
        }
        p.push_str(")");
    }
}

/// A dictionary expression: `(color: #f79143, pattern: dashed)`.
pub type ExprDict = Vec<Named>;

impl Pretty for ExprDict {
    fn pretty(&self, p: &mut Printer) {
        p.push_str("(");
        if self.is_empty() {
            p.push_str(":");
        } else {
            p.join(self, ", ", |named, p| named.pretty(p));
        }
        p.push_str(")");
    }
}

/// A template expression: `[*Hi* there!]`.
pub type ExprTemplate = Tree;

#[cfg(test)]
mod tests {
    use super::super::tests::test_pretty;

    #[test]
    fn test_pretty_print_chaining() {
        // All equivalent.
        test_pretty("[v [[f]]]", "[v | f]");
        test_pretty("[v][[f]]", "[v | f]");
        test_pretty("[v | f]", "[v | f]");
    }

    #[test]
    fn test_pretty_print_expressions() {
        // Unary and binary operations.
        test_pretty("{1 +}", "{1}");
        test_pretty("{1 + func(-2)}", "{1 + func(-2)}");

        // Array.
        test_pretty("(-5,)", "(-5,)");
        test_pretty("(1, 2, 3)", "(1, 2, 3)");

        // Dictionary.
        test_pretty("{(:)}", "{(:)}");
        test_pretty("{(percent: 5%)}", "{(percent: 5%)}");

        // Content expression.
        test_pretty("[v [[f]], 1]", "[v [[f]], 1]");
    }

    #[test]
    fn test_pretty_print_literals() {
        test_pretty("{none}", "{none}");
        test_pretty("{true}", "{true}");
        test_pretty("{25}", "{25}");
        test_pretty("{2.50}", "{2.5}");
        test_pretty("{1e2}", "{100}");
        test_pretty("{12pt}", "{12pt}");
        test_pretty("{90.0deg}", "{90deg}");
        test_pretty("{50%}", "{50%}");
        test_pretty("{#fff}", "{#ffffff}");
        test_pretty(r#"{"hi\n"}"#, r#"{"hi\n"}"#);
    }
}