mathlex 0.4.1

Mathematical expression parser for LaTeX and plain text notation, producing a language-agnostic AST
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Constant tests for LaTeX parser
// Tests for context-aware parsing of e (Euler's number) and i (imaginary unit)
use super::*;

// =============================================================================
// Explicit markers
// =============================================================================

#[test]
fn test_explicit_mathrm_e() {
    // \mathrm{e} should always parse as Constant(E)
    let expr = parse_latex(r"\mathrm{e}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::E));
}

#[test]
fn test_explicit_mathrm_i() {
    // \mathrm{i} should always parse as Constant(I)
    let expr = parse_latex(r"\mathrm{i}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::I));
}

#[test]
fn test_imath() {
    // \imath should parse as Constant(I)
    let expr = parse_latex(r"\imath").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::I));
}

#[test]
fn test_jmath() {
    // \jmath should parse as Constant(I) (engineering notation)
    let expr = parse_latex(r"\jmath").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::I));
}

// =============================================================================
// Default behavior (unbound e and i are constants)
// =============================================================================

#[test]
fn test_bare_e_is_constant() {
    // Unbound e defaults to Euler's number
    let expr = parse_latex("e").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::E));
}

#[test]
fn test_bare_i_is_constant() {
    // Unbound i defaults to imaginary unit
    let expr = parse_latex("i").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::I));
}

#[test]
fn test_e_in_expression() {
    // e + 1 should have Constant(E) on left
    let expr = parse_latex("e + 1").unwrap();
    match &expr.kind {
        ExprKind::Binary { op, left, right } => {
            assert_eq!(*op, BinaryOp::Add);
            assert_eq!(**left, Expression::constant(MathConstant::E));
            assert_eq!(**right, Expression::integer(1));
        }
        _ => panic!("Expected binary expression"),
    }
}

#[test]
fn test_i_in_expression() {
    // 2 * i should have Constant(I) on right
    let expr = parse_latex("2 * i").unwrap();
    match &expr.kind {
        ExprKind::Binary { op, left, right } => {
            assert_eq!(*op, BinaryOp::Mul);
            assert_eq!(**left, Expression::integer(2));
            assert_eq!(**right, Expression::constant(MathConstant::I));
        }
        _ => panic!("Expected binary expression"),
    }
}

// =============================================================================
// Scope tracking (bound variables in sum/product)
// =============================================================================

#[test]
fn test_sum_bound_i() {
    // \sum_{i=1}^n i -> i in body is Variable, not Constant
    let expr = parse_latex(r"\sum_{i=1}^{n} i").unwrap();
    match &expr.kind {
        ExprKind::Sum {
            index,
            lower,
            upper,
            body,
        } => {
            assert_eq!(index, "i");
            assert_eq!(**lower, Expression::integer(1));
            assert_eq!(**upper, Expression::variable("n".to_string()));
            // The body i should be a Variable, not Constant(I)
            assert_eq!(**body, Expression::variable("i".to_string()));
        }
        _ => panic!("Expected Sum variant"),
    }
}

#[test]
fn test_prod_bound_e() {
    // \prod_{e=1}^n e -> e in body is Variable, not Constant
    let expr = parse_latex(r"\prod_{e=1}^{n} e").unwrap();
    match &expr.kind {
        ExprKind::Product {
            index,
            lower,
            upper,
            body,
        } => {
            assert_eq!(index, "e");
            assert_eq!(**lower, Expression::integer(1));
            assert_eq!(**upper, Expression::variable("n".to_string()));
            // The body e should be a Variable, not Constant(E)
            assert_eq!(**body, Expression::variable("e".to_string()));
        }
        _ => panic!("Expected Product variant"),
    }
}

#[test]
fn test_sum_with_e_and_i() {
    // \sum_{i=1}^n e -> i is bound (Variable), e is unbound (Constant)
    let expr = parse_latex(r"\sum_{i=1}^{n} e").unwrap();
    match &expr.kind {
        ExprKind::Sum { index, body, .. } => {
            assert_eq!(index, "i");
            // e is NOT the index, so it should remain Constant(E)
            assert_eq!(**body, Expression::constant(MathConstant::E));
        }
        _ => panic!("Expected Sum variant"),
    }
}

#[test]
fn test_sum_bound_i_in_multiplication() {
    // \sum_{i=1}^n 2*i -> i in body is Variable
    let expr = parse_latex(r"\sum_{i=1}^{n} 2 * i").unwrap();
    match &expr.kind {
        ExprKind::Sum { body, .. } => {
            match &body.kind {
                ExprKind::Binary { op, left, right } => {
                    assert_eq!(*op, BinaryOp::Mul);
                    assert_eq!(**left, Expression::integer(2));
                    // i should be Variable, not Constant
                    assert_eq!(**right, Expression::variable("i".to_string()));
                }
                _ => panic!("Expected multiplication in body"),
            }
        }
        _ => panic!("Expected Sum variant"),
    }
}

// =============================================================================
// Exponential normalization (e^x -> exp(x))
// =============================================================================

#[test]
fn test_e_power_is_exp() {
    // e^x should normalize to Function("exp", [x])
    let expr = parse_latex("e^x").unwrap();
    match &expr.kind {
        ExprKind::Function { name, args } => {
            assert_eq!(name, "exp");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Expression::variable("x".to_string()));
        }
        _ => panic!("Expected Function variant"),
    }
}

#[test]
fn test_e_power_braced() {
    // e^{x+1} should normalize to Function("exp", [x+1])
    let expr = parse_latex("e^{x+1}").unwrap();
    match &expr.kind {
        ExprKind::Function { name, args } => {
            assert_eq!(name, "exp");
            assert_eq!(args.len(), 1);
            match &args[0].kind {
                ExprKind::Binary { op, .. } => {
                    assert_eq!(*op, BinaryOp::Add);
                }
                _ => panic!("Expected binary expression in exp argument"),
            }
        }
        _ => panic!("Expected Function variant"),
    }
}

#[test]
fn test_exp_and_e_power_equal() {
    // \exp{x} and e^x should produce the same AST
    let expr1 = parse_latex(r"\exp{x}").unwrap();
    let expr2 = parse_latex("e^x").unwrap();
    assert_eq!(expr1, expr2);
}

#[test]
fn test_explicit_mathrm_e_power() {
    // \mathrm{e}^x should also normalize to exp(x)
    let expr = parse_latex(r"\mathrm{e}^x").unwrap();
    match &expr.kind {
        ExprKind::Function { name, args } => {
            assert_eq!(name, "exp");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], Expression::variable("x".to_string()));
        }
        _ => panic!("Expected Function variant"),
    }
}

#[test]
fn test_euler_formula() {
    // e^{i\pi} should produce exp(Constant(I) * Constant(Pi))
    let expr = parse_latex(r"e^{i \pi}").unwrap();
    match &expr.kind {
        ExprKind::Function { name, args } => {
            assert_eq!(name, "exp");
            assert_eq!(args.len(), 1);
            match &args[0].kind {
                ExprKind::Binary { op, left, right } => {
                    assert_eq!(*op, BinaryOp::Mul);
                    assert_eq!(**left, Expression::constant(MathConstant::I));
                    assert_eq!(**right, Expression::constant(MathConstant::Pi));
                }
                _ => panic!("Expected multiplication in exp argument"),
            }
        }
        _ => panic!("Expected Function variant"),
    }
}

#[test]
fn test_e_without_power() {
    // e + 1 should keep e as Constant(E), no normalization
    let expr = parse_latex("e + 1").unwrap();
    match &expr.kind {
        ExprKind::Binary { op, left, right } => {
            assert_eq!(*op, BinaryOp::Add);
            assert_eq!(**left, Expression::constant(MathConstant::E));
            assert_eq!(**right, Expression::integer(1));
        }
        _ => panic!("Expected binary expression"),
    }
}

// =============================================================================
// Edge cases
// =============================================================================

#[test]
fn test_subscript_e_is_variable() {
    // x_e should produce Variable("x_e"), the subscript 'e' is just a label
    let expr = parse_latex("x_e").unwrap();
    assert_eq!(expr, Expression::variable("x_e".to_string()));
}

#[test]
fn test_subscript_i_is_variable() {
    // x_i should produce Variable("x_i"), the subscript 'i' is just a label
    let expr = parse_latex("x_i").unwrap();
    assert_eq!(expr, Expression::variable("x_i".to_string()));
}

#[test]
fn test_other_letters_are_variables() {
    // a, b, c, x, y, z should all be variables
    assert_eq!(
        parse_latex("a").unwrap(),
        Expression::variable("a".to_string())
    );
    assert_eq!(
        parse_latex("b").unwrap(),
        Expression::variable("b".to_string())
    );
    assert_eq!(
        parse_latex("x").unwrap(),
        Expression::variable("x".to_string())
    );
    assert_eq!(
        parse_latex("y").unwrap(),
        Expression::variable("y".to_string())
    );
}

#[test]
fn test_complex_number_pattern() {
    // a + bi - both i's should be Constant(I)
    let expr = parse_latex("a + b * i").unwrap();
    match &expr.kind {
        ExprKind::Binary {
            op: BinaryOp::Add,
            left,
            right,
        } => {
            assert_eq!(**left, Expression::variable("a".to_string()));
            match &right.kind {
                ExprKind::Binary {
                    op: BinaryOp::Mul,
                    left: ref b,
                    right: ref i,
                } => {
                    assert_eq!(**b, Expression::variable("b".to_string()));
                    assert_eq!(**i, Expression::constant(MathConstant::I));
                }
                _ => panic!("Expected multiplication"),
            }
        }
        _ => panic!("Expected addition"),
    }
}

#[test]
fn test_nested_sum_scope() {
    // \sum_{i=1}^n \sum_{j=1}^m i*j
    // Both i and j should be Variables in the body
    let expr = parse_latex(r"\sum_{i=1}^{n} \sum_{j=1}^{m} i * j").unwrap();
    match &expr.kind {
        ExprKind::Sum {
            body: outer_body, ..
        } => {
            // outer_body is the inner sum
            match &outer_body.kind {
                ExprKind::Sum {
                    body: inner_body, ..
                } => {
                    // inner_body should be i * j with both as Variables
                    match &inner_body.kind {
                        ExprKind::Binary { op, left, right } => {
                            assert_eq!(*op, BinaryOp::Mul);
                            assert_eq!(**left, Expression::variable("i".to_string()));
                            assert_eq!(**right, Expression::variable("j".to_string()));
                        }
                        _ => panic!("Expected binary multiplication"),
                    }
                }
                _ => panic!("Expected inner Sum"),
            }
        }
        _ => panic!("Expected outer Sum"),
    }
}

#[test]
fn test_mathrm_other_letter() {
    // \mathrm{a} should produce a Command-like result, not ExplicitConstant
    // Since 'a' is not e or i, it should be treated as a command
    let result = parse_latex(r"\mathrm{a}");
    // This should either error or produce something different
    assert!(result.is_err() || matches!(result, Ok(_)));
}

// =============================================================================
// NegInfinity folding
// =============================================================================

#[test]
fn test_neg_infty_is_neg_infinity() {
    // -\infty should fold to Constant(NegInfinity)
    let expr = parse_latex(r"-\infty").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::NegInfinity));
}

#[test]
fn test_neg_infty_in_limit() {
    // \lim_{x \to -\infty} f(x) should have NegInfinity as the limit target
    let expr = parse_latex(r"\lim_{x \to -\infty} f(x)").unwrap();
    match &expr.kind {
        ExprKind::Limit { to, .. } => {
            assert_eq!(**to, Expression::constant(MathConstant::NegInfinity));
        }
        _ => panic!("Expected Limit variant"),
    }
}

#[test]
fn test_neg_infty_in_integral_bound() {
    // \int_{-\infty}^{\infty} should have NegInfinity as lower bound
    let expr = parse_latex(r"\int_{-\infty}^{\infty} x dx").unwrap();
    match &expr.kind {
        ExprKind::Integral { bounds, .. } => {
            let bounds = bounds.as_ref().expect("Expected definite integral bounds");
            assert_eq!(
                *bounds.lower,
                Expression::constant(MathConstant::NegInfinity)
            );
            assert_eq!(*bounds.upper, Expression::constant(MathConstant::Infinity));
        }
        _ => panic!("Expected Integral variant"),
    }
}

#[test]
fn test_positive_infty_unchanged() {
    // \infty should remain Constant(Infinity), not NegInfinity
    let expr = parse_latex(r"\infty").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::Infinity));
}

// =============================================================================
// Tokenizer tests for ExplicitConstant
// =============================================================================

#[test]
fn test_tokenize_mathrm_e() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\mathrm{e}").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::ExplicitConstant('e')));
}

#[test]
fn test_tokenize_mathrm_i() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\mathrm{i}").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::ExplicitConstant('i')));
}

#[test]
fn test_tokenize_imath() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\imath").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::ExplicitConstant('i')));
}

#[test]
fn test_tokenize_jmath() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\jmath").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::ExplicitConstant('i')));
}

// =============================================================================
// NaN constant
// =============================================================================

#[test]
fn test_text_nan_uppercase() {
    // \text{NaN} should parse as Constant(NaN)
    let expr = parse_latex(r"\text{NaN}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::NaN));
}

#[test]
fn test_text_nan_lowercase() {
    // \text{nan} should parse as Constant(NaN)
    let expr = parse_latex(r"\text{nan}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::NaN));
}

#[test]
fn test_mathrm_nan_uppercase() {
    // \mathrm{NaN} should parse as Constant(NaN)
    let expr = parse_latex(r"\mathrm{NaN}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::NaN));
}

#[test]
fn test_mathrm_nan_lowercase() {
    // \mathrm{nan} should parse as Constant(NaN)
    let expr = parse_latex(r"\mathrm{nan}").unwrap();
    assert_eq!(expr, Expression::constant(MathConstant::NaN));
}

#[test]
fn test_nan_in_expression() {
    // x + \text{NaN} should produce a binary with NaN on the right
    let expr = parse_latex(r"x + \text{NaN}").unwrap();
    match &expr.kind {
        ExprKind::Binary { op, left, right } => {
            assert_eq!(*op, BinaryOp::Add);
            assert_eq!(**left, Expression::variable("x".to_string()));
            assert_eq!(**right, Expression::constant(MathConstant::NaN));
        }
        _ => panic!("Expected binary expression"),
    }
}

#[test]
fn test_tokenize_text_nan() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\text{NaN}").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::NaNConstant));
}

#[test]
fn test_tokenize_text_nan_lowercase() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\text{nan}").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::NaNConstant));
}

#[test]
fn test_tokenize_mathrm_nan() {
    use crate::parser::latex_tokenizer::{tokenize_latex, LatexToken};
    let tokens = tokenize_latex(r"\mathrm{NaN}").unwrap();
    assert!(matches!(tokens[0].0, LatexToken::NaNConstant));
}

#[test]
fn test_nan_to_latex_roundtrip() {
    use crate::latex::ToLatex;
    let expr = Expression::constant(MathConstant::NaN);
    let latex = expr.to_latex();
    assert_eq!(latex, r"\text{NaN}");
    // Re-parse the LaTeX output — must round-trip.
    let reparsed = parse_latex(&latex).unwrap();
    assert_eq!(reparsed, expr);
}

#[test]
fn test_nan_display() {
    let expr = Expression::constant(MathConstant::NaN);
    assert_eq!(format!("{}", expr), "NaN");
}

#[test]
fn test_nan_ne_infinity() {
    assert_ne!(MathConstant::NaN, MathConstant::Infinity);
    assert_ne!(MathConstant::NaN, MathConstant::NegInfinity);
}