formualizer-parse 4.1.0

High-performance Excel/OpenFormula tokenizer + parser with a stable AST surface
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use crate::parser::{ASTNode, ASTNodeType, ParserError, parse};
use crate::tokenizer::Associativity;

/// Pretty-prints an AST node according to canonical formatting rules.
///
/// Rules:
/// - All functions upper-case, no spaces before '('
/// - Commas followed by single space; no space before ','
/// - Binary operators surrounded by single spaces
/// - No superfluous parentheses (keeps semantics)
/// - References printed via .normalise()
/// - Array literals: {1, 2; 3, 4}
///
/// # Depth
///
/// Recursive in the tree height. Trees within the default
/// [`ParserLimits::ast_height`](crate::ParserLimits::ast_height) limit (256)
/// are supported, which includes every tree the parser returns under default
/// limits. A taller tree, hand-built or parsed under a raised limit, needs the
/// caller to provide the stack (see
/// [`ParserLimits::with_ast_height`](crate::ParserLimits::with_ast_height)).
pub fn pretty_print(ast: &ASTNode) -> String {
    pretty_print_node(ast)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
    Left,
    Right,
}

fn infix_info(op: &str) -> (u8, Associativity) {
    match op {
        ":" => (10, Associativity::Left),
        " " => (9, Associativity::Left),
        "," => (8, Associativity::Left),
        "^" => (5, Associativity::Left),
        "*" | "/" => (4, Associativity::Left),
        "+" | "-" => (3, Associativity::Left),
        "&" => (2, Associativity::Left),
        "=" | "<" | ">" | "<=" | ">=" | "<>" => (1, Associativity::Left),
        _ => (0, Associativity::Left),
    }
}

fn unary_precedence(op: &str) -> u8 {
    match op {
        "#" => 11,
        "%" => 7,
        _ => 6,
    }
}

fn node_precedence(ast: &ASTNode) -> u8 {
    match &ast.node_type {
        ASTNodeType::BinaryOp { op, .. } => infix_info(op.as_str()).0,
        ASTNodeType::UnaryOp { op, .. } => unary_precedence(op.as_str()),
        // Treat everything else as an atom.
        _ => 10,
    }
}

fn child_needs_parens(
    child: &ASTNode,
    parent_op: &str,
    parent_prec: u8,
    parent_assoc: Associativity,
    side: Side,
) -> bool {
    let child_prec = node_precedence(child);
    if child_prec < parent_prec {
        return true;
    }
    if child_prec > parent_prec {
        return false;
    }

    // Same precedence: associativity and mixed operators matter.
    match side {
        Side::Left => {
            if parent_assoc == Associativity::Right {
                // Right-assoc ops (e.g. '^'): parenthesize left child if it could re-associate.
                matches!(child.node_type, ASTNodeType::BinaryOp { .. })
            } else {
                false
            }
        }
        Side::Right => {
            if parent_assoc == Associativity::Left {
                // A same-precedence right operand of a left-associative
                // operator only exists because the source grouped it, so the
                // brackets are part of the tree: `A1*(B1*C1)` is not
                // `(A1*B1)*C1`, and `1=(2=3)` is not `1=2=3`.
                matches!(child.node_type, ASTNodeType::BinaryOp { .. })
            } else {
                // Right-assoc ops: parenthesize if mixing ops at same precedence.
                if let ASTNodeType::BinaryOp { op: child_op, .. } = &child.node_type {
                    return child_op.as_str() != parent_op;
                }
                false
            }
        }
    }
}

fn unary_operand_needs_parens(unary_op: &str, operand: &ASTNode) -> bool {
    match unary_op {
        "%" | "#" => matches!(operand.node_type, ASTNodeType::BinaryOp { .. }),
        _ => {
            let operand_prec = node_precedence(operand);
            operand_prec < unary_precedence(unary_op)
                && matches!(operand.node_type, ASTNodeType::BinaryOp { .. })
        }
    }
}

fn pretty_child(
    child: &ASTNode,
    parent_op: &str,
    parent_prec: u8,
    parent_assoc: Associativity,
    side: Side,
    comma_delimited: bool,
) -> String {
    if child_needs_parens(child, parent_op, parent_prec, parent_assoc, side) {
        // Explicit grouping shields any union below this child from the
        // surrounding argument/array separator grammar.
        format!("({})", pretty_print_node(child))
    } else {
        pretty_print_node_in_context(child, comma_delimited)
    }
}

fn pretty_print_arguments(args: &[ASTNode]) -> String {
    let mut rendered = String::new();
    for (index, arg) in args.iter().enumerate() {
        if index > 0 {
            rendered.push(',');
            if !matches!(arg.node_type, ASTNodeType::Omitted) {
                rendered.push(' ');
            }
        }
        // Union operators need grouping anywhere in the unparenthesized
        // argument expression, not only at its root: SUM((A1,B1)+1).
        rendered.push_str(&pretty_print_node_in_context(arg, true));
    }
    rendered
}

fn pretty_print_node(ast: &ASTNode) -> String {
    pretty_print_node_in_context(ast, false)
}

fn pretty_print_node_in_context(ast: &ASTNode, comma_delimited: bool) -> String {
    if comma_delimited
        && matches!(&ast.node_type, ASTNodeType::BinaryOp { op, .. } if op.as_str() == ",")
    {
        return format!("({})", pretty_print_node(ast));
    }
    match &ast.node_type {
        ASTNodeType::Literal(value) => match value {
            // Quote and escape text literals to preserve Excel semantics
            crate::LiteralValue::Text(s) => {
                let escaped = s.replace('"', "\"\"");
                format!("\"{escaped}\"")
            }
            _ => format!("{value}"),
        },
        ASTNodeType::Omitted => String::new(),
        ASTNodeType::Reference { reference, .. } => reference.normalise(),
        ASTNodeType::UnaryOp { op, expr } => {
            let inner = if unary_operand_needs_parens(op.as_str(), expr) {
                format!("({})", pretty_print_node(expr))
            } else {
                pretty_print_node_in_context(expr, comma_delimited)
            };

            if op.as_str() == "%" || op.as_str() == "#" {
                format!("{inner}{op}")
            } else {
                format!("{op}{inner}")
            }
        }
        ASTNodeType::BinaryOp { op, left, right } => {
            let (prec, assoc) = infix_info(op.as_str());
            let left_s = pretty_child(left, op.as_str(), prec, assoc, Side::Left, comma_delimited);
            let right_s = pretty_child(
                right,
                op.as_str(),
                prec,
                assoc,
                Side::Right,
                comma_delimited,
            );

            match op.as_str() {
                // Reference range operator prints tight; intersection is a
                // single space rather than the generic three-space infix form.
                ":" => format!("{left_s}:{right_s}"),
                " " => format!("{left_s} {right_s}"),
                "," => format!("{left_s}, {right_s}"),
                _ => format!("{left_s} {op} {right_s}"),
            }
        }
        ASTNodeType::Function { name, args } => {
            let args_str = pretty_print_arguments(args);
            format!("{}({})", name.to_uppercase(), args_str)
        }
        ASTNodeType::Call { callee, args } => {
            let callee_str = pretty_print_node(callee);
            // Wrap the callee in parentheses if it isn't already a callable-looking
            // primary (function call or another call expression). This keeps things
            // like `(1 + 2)(3)` unambiguous when round-tripping unusual ASTs.
            let callee_rendered = match &callee.node_type {
                ASTNodeType::Function { .. } | ASTNodeType::Call { .. } => callee_str,
                _ => format!("({callee_str})"),
            };
            let args_str = pretty_print_arguments(args);
            format!("{callee_rendered}({args_str})")
        }
        ASTNodeType::Array(rows) => {
            let rows_str = rows
                .iter()
                .map(|row| {
                    row.iter()
                        .map(|cell| pretty_print_node_in_context(cell, true))
                        .collect::<Vec<String>>()
                        .join(", ")
                })
                .collect::<Vec<String>>()
                .join("; ");

            format!("{{{rows_str}}}")
        }
    }
}

/// Produce a canonical Excel formula string for an AST, prefixed with '='.
///
/// This is the single entry-point that UI layers should use when displaying
/// a formula reconstructed from an AST.
///
/// # Depth
///
/// Recursive in the tree height. Trees within the default
/// [`ParserLimits::ast_height`](crate::ParserLimits::ast_height) limit (256)
/// are supported, which includes every tree the parser returns under default
/// limits. A taller tree, hand-built or parsed under a raised limit, needs the
/// caller to provide the stack (see
/// [`ParserLimits::with_ast_height`](crate::ParserLimits::with_ast_height)).
pub fn canonical_formula(ast: &ASTNode) -> String {
    format!("={}", pretty_print(ast))
}

/// Tokenizes and parses a formula, then pretty-prints it.
///
/// Returns a Result with the pretty-printed formula or a parser error.
pub fn pretty_parse_render(formula: &str) -> Result<String, ParserError> {
    // Handle empty formula case
    if formula.is_empty() {
        return Ok(String::new());
    }

    // If formula doesn't start with '=', add it before parsing and remove it after
    let needs_equals = !formula.starts_with('=');
    let formula_to_parse = if needs_equals {
        format!("={formula}")
    } else {
        formula.to_string()
    };

    // Parse and pretty-print
    let ast = parse(&formula_to_parse)?;

    // Format the result with '=' prefix
    let pretty_printed = pretty_print(&ast);

    // Return the result with appropriate '=' prefix
    if needs_equals {
        Ok(pretty_printed)
    } else {
        Ok(format!("={pretty_printed}"))
    }
}

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

    #[test]
    fn test_pretty_print_validation() {
        let original = "= sum(  a1 ,2 ) ";
        let pretty = pretty_parse_render(original).unwrap();
        assert_eq!(pretty, "=SUM(A1, 2)");

        let round = pretty_parse_render(&pretty).unwrap();
        assert_eq!(pretty, round); // idempotent
    }

    #[test]
    fn test_ast_canonicalization() {
        // Test that our pretty printer produces canonical form
        let formula = "=sum(  a1, b2  )";
        let pretty = pretty_parse_render(formula).unwrap();

        // Check that the pretty printed version is canonicalized
        assert_eq!(pretty, "=SUM(A1, B2)");

        // Test round-trip consistency
        let repretty = pretty_parse_render(&pretty).unwrap();
        assert_eq!(pretty, repretty);
    }

    #[test]
    fn test_pretty_print_operators() {
        let formula = "=a1+b2*3";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=A1 + B2 * 3");

        let formula = "=a1 + b2 *     3";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=A1 + B2 * 3");
    }

    #[test]
    fn test_pretty_print_inserts_parentheses_when_needed() {
        let formula = "=(a1+b2)*c3";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=(A1 + B2) * C3");
    }

    #[test]
    fn test_pretty_print_keeps_same_precedence_right_grouping() {
        for (formula, expected) in [
            ("=A1*(B1*C1)", "=A1 * (B1 * C1)"),
            ("=A1+(B1+C1)", "=A1 + (B1 + C1)"),
            ("=1=(2=3)", "=1 = (2 = 3)"),
            ("=\"a\"&(\"b\"&\"c\")", "=\"a\" & (\"b\" & \"c\")"),
            ("=A1-(B1+C1)", "=A1 - (B1 + C1)"),
            // Left grouping is the default and needs no brackets.
            ("=(A1*B1)*C1", "=A1 * B1 * C1"),
            ("=(1=2)=3", "=1 = 2 = 3"),
        ] {
            let pretty = pretty_parse_render(formula).unwrap();
            assert_eq!(pretty, expected, "{formula}");
            assert_eq!(
                parse(&pretty).unwrap().fingerprint(),
                parse(formula).unwrap().fingerprint(),
                "{formula} must re-parse to the same tree"
            );
        }
    }

    #[test]
    fn test_pretty_print_keeps_union_argument_brackets() {
        for (formula, expected) in [
            ("=RANK(A1,(B1,B5))", "=RANK(A1, (B1, B5))"),
            ("=SUM((A1,B1),C1)", "=SUM((A1, B1), C1)"),
            ("=SUM((A1,B1,C1))", "=SUM((A1, B1, C1))"),
        ] {
            let pretty = pretty_parse_render(formula).unwrap();
            assert_eq!(pretty, expected, "{formula}");
            assert_eq!(
                parse(&pretty).unwrap().fingerprint(),
                parse(formula).unwrap().fingerprint(),
                "{formula} must re-parse to the same tree"
            );
        }
    }

    #[test]
    fn test_pretty_print_function_nesting() {
        let formula = "=if(a1>0, sum(b1:b10), average(c1:c10))";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=IF(A1 > 0, SUM(B1:B10), AVERAGE(C1:C10))");
    }

    #[test]
    fn test_pretty_print_arrays() {
        let formula = "={1,2;3,4}";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "={1, 2; 3, 4}");

        let formula = "={1, 2; 3, 4}";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "={1, 2; 3, 4}");
    }

    #[test]
    fn test_pretty_print_references() {
        let formula = "=Sheet1!$a$1:$b$2";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=Sheet1!$A$1:$B$2");

        let formula = "='My Sheet'!a1";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "='My Sheet'!A1");
    }

    #[test]
    fn test_pretty_print_text_literals_in_functions() {
        // Should preserve quotes around text literals
        let formula = "=SUMIFS(A:A, B:B, \"*Parking*\")";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=SUMIFS(A:A, B:B, \"*Parking*\")");
    }

    #[test]
    fn test_pretty_print_text_concatenation_and_escaping() {
        // Operators as text must stay quoted, and spacing around '&' is canonical
        let formula = "=\">=\"&DATE(2024,1,1)";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=\">=\" & DATE(2024, 1, 1)");

        // Embedded quotes should be doubled
        let formula = "=\"He said \"\"Hi\"\"\"";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "=\"He said \"\"Hi\"\"\"");
    }

    #[test]
    fn test_pretty_print_text_in_arrays() {
        let formula = "={\"A\", \"B\"; \"C\", \"D\"}";
        let pretty = pretty_parse_render(formula).unwrap();
        assert_eq!(pretty, "={\"A\", \"B\"; \"C\", \"D\"}");
    }
}