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
// Allow large error variants - boxing would be a breaking API change
#![allow(clippy::result_large_err)]

use super::*;

impl LatexParser {
    /// Parses an integral: \int f(x) dx or \int_a^b f(x) dx
    pub(super) fn parse_integral(&mut self) -> ParseResult<Expression> {
        // Check for subscript (lower bound)
        let bounds = if self.check(&LatexToken::Underscore) {
            self.next(); // consume _
            let lower = self.parse_braced_or_atom()?;

            // Must have superscript (upper bound) if we have subscript
            if !self.check(&LatexToken::Caret) {
                return Err(ParseError::custom(
                    "integral with lower bound must also have upper bound".to_string(),
                    Some(self.current_span()),
                ));
            }
            self.next(); // consume ^
            let upper = self.parse_braced_or_atom()?;

            Some(IntegralBounds {
                lower: Box::new(lower),
                upper: Box::new(upper),
            })
        } else if self.check(&LatexToken::Caret) {
            // Upper bound without lower bound is an error
            return Err(ParseError::custom(
                "integral with upper bound must also have lower bound".to_string(),
                Some(self.current_span()),
            ));
        } else {
            None
        };

        // Parse integrand - use multiplicative level so x + 1 parses as (int x) + 1
        // Set integral context to prevent 'dx' from being parsed as a Differential
        self.in_integral_context = true;
        let integrand = self.parse_multiplicative()?;
        self.in_integral_context = false;

        // Expect 'd' followed by variable name
        if let Some((LatexToken::Letter('d'), _)) = self.peek() {
            self.next(); // consume 'd'

            // Next should be the variable
            if let Some((LatexToken::Letter(var_ch), _)) = self.peek() {
                let var = var_ch.to_string();
                self.next(); // consume variable

                Ok(ExprKind::Integral {
                    integrand: Box::new(integrand),
                    var,
                    bounds,
                }
                .into())
            } else {
                Err(ParseError::custom(
                    "expected variable name after 'd' in integral".to_string(),
                    Some(self.current_span()),
                ))
            }
        } else {
            Err(ParseError::custom(
                "expected 'd' followed by variable in integral".to_string(),
                Some(self.current_span()),
            ))
        }
    }

    /// Parses a multiple integral: \iint, \iiint, \iiiint
    /// Format: \iint f(x,y) dy dx or \iint_{bounds} f(x,y) dy dx
    pub(super) fn parse_multiple_integral(&mut self, dimension: u8) -> ParseResult<Expression> {
        // Check for optional bounds subscript
        let bounds = if self.check(&LatexToken::Underscore) {
            self.next(); // consume _
            let _region = self.parse_braced_or_atom()?;
            // For simplicity, we don't track the region expression
            None
        } else {
            None
        };

        // Parse integrand with integral context set
        self.in_integral_context = true;
        let integrand = self.parse_multiplicative()?;
        self.in_integral_context = false;

        // Parse the differential variables (dy dx, dz dy dx, etc.)
        let mut vars = Vec::new();
        while let Some((LatexToken::Letter('d'), _)) = self.peek() {
            self.next(); // consume 'd'
            if let Some((LatexToken::Letter(var_ch), _)) = self.peek() {
                vars.push(var_ch.to_string());
                self.next(); // consume variable
            } else {
                return Err(ParseError::custom(
                    "expected variable name after 'd' in multiple integral".to_string(),
                    Some(self.current_span()),
                ));
            }
        }

        if vars.is_empty() {
            return Err(ParseError::custom(
                format!(
                    "expected {} differential variables for {}-dimensional integral",
                    dimension,
                    match dimension {
                        2 => "double",
                        3 => "triple",
                        4 => "quadruple",
                        _ => "multiple",
                    }
                ),
                Some(self.current_span()),
            ));
        }

        Ok(ExprKind::MultipleIntegral {
            dimension,
            integrand: Box::new(integrand),
            bounds,
            vars,
        }
        .into())
    }

    /// Parses a closed/contour integral: \oint, \oiint, \oiiint
    /// Format: \oint_C f(x) dx or \oiint_S f(x,y) dA
    pub(super) fn parse_closed_integral(&mut self, dimension: u8) -> ParseResult<Expression> {
        // Check for optional surface/curve subscript
        let surface = if self.check(&LatexToken::Underscore) {
            self.next(); // consume _
            let surface_expr = self.parse_braced_or_atom()?;
            // Extract name if it's a variable
            match &surface_expr.kind {
                ExprKind::Variable(name) => Some(name.clone()),
                _ => None,
            }
        } else {
            None
        };

        // Parse integrand with integral context set
        self.in_integral_context = true;
        let integrand = self.parse_multiplicative()?;
        self.in_integral_context = false;

        // Parse the differential variable
        let var = if let Some((LatexToken::Letter('d'), _)) = self.peek() {
            self.next(); // consume 'd'
            if let Some((LatexToken::Letter(var_ch), _)) = self.peek() {
                let v = var_ch.to_string();
                self.next(); // consume variable
                v
            } else {
                // Could be dA, dS, etc. - check for uppercase
                if let Some((LatexToken::Letter(var_ch), _)) = self.peek() {
                    let v = var_ch.to_string();
                    self.next();
                    v
                } else {
                    "".to_string() // Will error below
                }
            }
        } else {
            "".to_string()
        };

        if var.is_empty() {
            return Err(ParseError::custom(
                "expected differential variable in closed integral".to_string(),
                Some(self.current_span()),
            ));
        }

        Ok(ExprKind::ClosedIntegral {
            dimension,
            integrand: Box::new(integrand),
            surface,
            var,
        }
        .into())
    }

    // ============================================================
    // Quantifier Parsing
    // ============================================================

    /// Parses a universal quantifier: \forall x P(x) or \forall x \in S P(x)
    pub(super) fn parse_forall(&mut self) -> ParseResult<Expression> {
        // Expect variable
        let variable = match self.peek() {
            Some((LatexToken::Letter(ch), _)) => {
                let v = ch.to_string();
                self.next();
                v
            }
            Some((LatexToken::Command(cmd), _)) => {
                // Greek letter variable
                let v = cmd.clone();
                self.next();
                v
            }
            _ => {
                return Err(ParseError::custom(
                    "expected variable after \\forall".to_string(),
                    Some(self.current_span()),
                ));
            }
        };

        // Check for optional domain: \in S
        let domain = if let Some((LatexToken::In, _)) = self.peek() {
            self.next(); // consume \in
            let set = self.parse_power()?;
            Some(Box::new(set))
        } else {
            None
        };

        // Parse the body expression
        let body = self.parse_expression()?;

        Ok(ExprKind::ForAll {
            variable,
            domain,
            body: Box::new(body),
        }
        .into())
    }

    /// Parses an existential quantifier: \exists x P(x) or \exists! x P(x)
    pub(super) fn parse_exists(&mut self) -> ParseResult<Expression> {
        // Check for unique existence: \exists!
        let unique = if let Some((LatexToken::Command(cmd), _)) = self.peek() {
            if cmd == "!" {
                self.next(); // consume !
                true
            } else {
                false
            }
        } else {
            false
        };

        // Expect variable
        let variable = match self.peek() {
            Some((LatexToken::Letter(ch), _)) => {
                let v = ch.to_string();
                self.next();
                v
            }
            Some((LatexToken::Command(cmd), _)) => {
                // Greek letter variable
                let v = cmd.clone();
                self.next();
                v
            }
            _ => {
                return Err(ParseError::custom(
                    "expected variable after \\exists".to_string(),
                    Some(self.current_span()),
                ));
            }
        };

        // Check for optional domain: \in S
        let domain = if let Some((LatexToken::In, _)) = self.peek() {
            self.next(); // consume \in
            let set = self.parse_power()?;
            Some(Box::new(set))
        } else {
            None
        };

        // Parse the body expression
        let body = self.parse_expression()?;

        Ok(ExprKind::Exists {
            variable,
            domain,
            body: Box::new(body),
            unique,
        }
        .into())
    }

    /// Parses a limit: \lim_{x \to a} or \lim_{x \to a^+}
    pub(super) fn parse_limit(&mut self) -> ParseResult<Expression> {
        // Expect subscript with pattern: var \to value
        if !self.check(&LatexToken::Underscore) {
            return Err(ParseError::custom(
                "limit must have subscript with approach pattern".to_string(),
                Some(self.current_span()),
            ));
        }
        self.next(); // consume _

        // Parse the subscript content
        self.consume(LatexToken::LBrace)?;

        // Expect variable
        let var = if let Some((LatexToken::Letter(ch), _)) = self.peek() {
            let v = ch.to_string();
            self.next(); // consume variable
            v
        } else {
            return Err(ParseError::custom(
                "expected variable in limit subscript".to_string(),
                Some(self.current_span()),
            ));
        };

        // Expect \to
        if let Some((LatexToken::To, _)) = self.peek() {
            self.next(); // consume \to
        } else {
            return Err(ParseError::custom(
                "expected \\to in limit subscript".to_string(),
                Some(self.current_span()),
            ));
        }

        // Parse approach value
        let to = self.parse_primary()?;

        // Check for direction (^+ or ^-) before the closing brace
        let direction = if self.check(&LatexToken::Caret) {
            self.next(); // consume ^

            match self.peek() {
                Some((LatexToken::Plus, _)) => {
                    self.next();
                    Direction::Right
                }
                Some((LatexToken::Minus, _)) => {
                    self.next();
                    Direction::Left
                }
                _ => {
                    return Err(ParseError::custom(
                        "expected + or - after ^ in limit direction".to_string(),
                        Some(self.current_span()),
                    ));
                }
            }
        } else {
            Direction::Both
        };

        self.consume(LatexToken::RBrace)?;

        // Parse the expression - use parse_multiplicative to capture full expressions
        let expr = self.parse_multiplicative()?;

        Ok(ExprKind::Limit {
            expr: Box::new(expr),
            var,
            to: Box::new(to),
            direction,
        }
        .into())
    }

    /// Parses a sum: \sum_{i=1}^{n} expr
    pub(super) fn parse_sum(&mut self) -> ParseResult<Expression> {
        let (index, lower, upper) = self.parse_iterator_bounds()?;
        // Bind the index variable in scope while parsing the body
        self.push_scope(std::iter::once(index.clone()));
        let body = self.parse_multiplicative()?;
        self.pop_scope();

        Ok(ExprKind::Sum {
            index,
            lower: Box::new(lower),
            upper: Box::new(upper),
            body: Box::new(body),
        }
        .into())
    }

    /// Parses a product: \prod_{i=1}^{n} expr
    pub(super) fn parse_product(&mut self) -> ParseResult<Expression> {
        let (index, lower, upper) = self.parse_iterator_bounds()?;
        // Bind the index variable in scope while parsing the body
        self.push_scope(std::iter::once(index.clone()));
        let body = self.parse_multiplicative()?;
        self.pop_scope();

        Ok(ExprKind::Product {
            index,
            lower: Box::new(lower),
            upper: Box::new(upper),
            body: Box::new(body),
        }
        .into())
    }

    /// Helper to parse iterator bounds: _{var=lower}^{upper}
    pub(super) fn parse_iterator_bounds(
        &mut self,
    ) -> ParseResult<(String, Expression, Expression)> {
        // Expect subscript with pattern: var = value
        if !self.check(&LatexToken::Underscore) {
            return Err(ParseError::custom(
                "iterator must have subscript with index=lower pattern".to_string(),
                Some(self.current_span()),
            ));
        }
        self.next(); // consume _

        // Parse the subscript content
        self.consume(LatexToken::LBrace)?;

        // Expect variable
        let index = if let Some((LatexToken::Letter(ch), _)) = self.peek() {
            let v = ch.to_string();
            self.next(); // consume variable
            v
        } else {
            return Err(ParseError::custom(
                "expected index variable in iterator subscript".to_string(),
                Some(self.current_span()),
            ));
        };

        // Expect =
        if let Some((LatexToken::Equals, _)) = self.peek() {
            self.next(); // consume =
        } else {
            return Err(ParseError::custom(
                "expected = in iterator subscript".to_string(),
                Some(self.current_span()),
            ));
        }

        // Parse lower bound
        let lower = self.parse_additive()?;

        self.consume(LatexToken::RBrace)?;

        // Expect superscript with upper bound
        if !self.check(&LatexToken::Caret) {
            return Err(ParseError::custom(
                "iterator must have superscript with upper bound".to_string(),
                Some(self.current_span()),
            ));
        }
        self.next(); // consume ^

        let upper = self.parse_braced_or_atom()?;

        Ok((index, lower, upper))
    }
}