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

//! # mathlex
//!
//! A mathematical expression parser for LaTeX and plain text notation,
//! producing a language-agnostic Abstract Syntax Tree (AST).
//!
//! ## Overview
//!
//! mathlex is a pure parsing library that converts mathematical expressions
//! in LaTeX or plain text format into a well-defined AST. The library does
//! NOT perform any evaluation or mathematical operations - interpretation
//! of the AST is entirely the responsibility of consuming libraries.
//!
//! ## Features
//!
//! - **LaTeX Parsing**: Parse mathematical LaTeX notation
//! - **Plain Text Parsing**: Parse standard mathematical expressions
//! - **Rich AST**: Comprehensive AST for algebra, calculus, linear algebra, set theory, logic
//! - **Vector Calculus**: Gradient, divergence, curl, Laplacian operators
//! - **Multiple Integrals**: Double, triple, and closed path integrals
//! - **Set Theory**: Union, intersection, quantifiers, logical connectives
//! - **Quaternions**: Support for quaternion algebra with basis vectors i, j, k
//! - **Vector Notation**: Multiple styles (bold, arrow, hat) with context awareness
//! - **Utilities**: Variable extraction, substitution, string conversion
//!
//! ## Quick Start
//!
//! ### Basic Parsing
//!
//! ```
//! use mathlex::{parse, parse_latex, Expression, ExprKind, BinaryOp};
//!
//! // Parse plain text
//! let expr = parse("2*x + sin(y)").unwrap();
//!
//! // Parse LaTeX
//! let expr = parse_latex(r"\frac{1}{2}").unwrap();
//!
//! // Verify the parsed structure
//! if let ExprKind::Binary { op: BinaryOp::Div, .. } = expr.kind {
//!     println!("Parsed as division");
//! }
//! ```
//!
//! ### Vector Calculus
//!
//! ```
//! use mathlex::{parse_latex, Expression, ExprKind};
//!
//! // Gradient operator
//! let grad = parse_latex(r"\nabla f").unwrap();
//! assert!(matches!(grad.kind, ExprKind::Gradient { .. }));
//!
//! // Divergence of a vector field
//! let div = parse_latex(r"\nabla \cdot \mathbf{F}").unwrap();
//! assert!(matches!(div.kind, ExprKind::Divergence { .. }));
//!
//! // Curl (cross product with nabla)
//! let curl = parse_latex(r"\nabla \times \mathbf{F}").unwrap();
//! assert!(matches!(curl.kind, ExprKind::Curl { .. }));
//!
//! // Laplacian
//! let laplacian = parse_latex(r"\nabla^2 f").unwrap();
//! assert!(matches!(laplacian.kind, ExprKind::Laplacian { .. }));
//! ```
//!
//! ### Vector Notation Styles
//!
//! ```
//! use mathlex::{parse_latex, Expression, ExprKind, VectorNotation};
//!
//! // Bold vectors
//! let bold = parse_latex(r"\mathbf{v}").unwrap();
//! if let ExprKind::MarkedVector { notation, .. } = bold.kind {
//!     assert_eq!(notation, VectorNotation::Bold);
//! }
//!
//! // Arrow vectors
//! let arrow = parse_latex(r"\vec{a}").unwrap();
//! if let ExprKind::MarkedVector { notation, .. } = arrow.kind {
//!     assert_eq!(notation, VectorNotation::Arrow);
//! }
//!
//! // Hat notation (unit vectors)
//! let hat = parse_latex(r"\hat{n}").unwrap();
//! if let ExprKind::MarkedVector { notation, .. } = hat.kind {
//!     assert_eq!(notation, VectorNotation::Hat);
//! }
//! ```
//!
//! ### Set Theory
//!
//! ```
//! use mathlex::{parse_latex, Expression, ExprKind};
//!
//! // Set union
//! let union = parse_latex(r"A \cup B").unwrap();
//! assert!(matches!(union.kind, ExprKind::SetOperation { .. }));
//!
//! // Set membership
//! let membership = parse_latex(r"x \in A").unwrap();
//! assert!(matches!(membership.kind, ExprKind::SetRelationExpr { .. }));
//!
//! // Universal quantifier
//! let forall = parse_latex(r"\forall x P").unwrap();
//! assert!(matches!(forall.kind, ExprKind::ForAll { .. }));
//!
//! // Logical connectives
//! let and = parse_latex(r"P \land Q").unwrap();
//! assert!(matches!(and.kind, ExprKind::Logical { .. }));
//! ```
//!
//! ### Multiple Integrals
//!
//! ```
//! use mathlex::{parse_latex, Expression, ExprKind};
//!
//! // Double integral
//! let double = parse_latex(r"\iint_R f dA").unwrap();
//! if let ExprKind::MultipleIntegral { dimension, .. } = double.kind {
//!     assert_eq!(dimension, 2);
//! }
//!
//! // Triple integral
//! let triple = parse_latex(r"\iiint_V f dV").unwrap();
//! if let ExprKind::MultipleIntegral { dimension, .. } = triple.kind {
//!     assert_eq!(dimension, 3);
//! }
//!
//! // Closed path integral
//! let closed = parse_latex(r"\oint_C F dr").unwrap();
//! assert!(matches!(closed.kind, ExprKind::ClosedIntegral { .. }));
//! ```
//!
//! ### Quaternions
//!
//! ```
//! use mathlex::{Expression, ExprKind, MathConstant};
//!
//! // Quaternion basis vectors are available as constants
//! let i = Expression::constant(MathConstant::I);
//! let j = Expression::constant(MathConstant::J);
//! let k = Expression::constant(MathConstant::K);
//!
//! // Create quaternion expression programmatically
//! // 1 + 2i + 3j + 4k
//! let quat = ExprKind::Quaternion {
//!     real: Box::new(Expression::integer(1)),
//!     i: Box::new(Expression::integer(2)),
//!     j: Box::new(Expression::integer(3)),
//!     k: Box::new(Expression::integer(4)),
//! };
//! ```
//!
//! ## Configuration
//!
//! For advanced parsing options, use [`ParserConfig`]:
//!
//! ```
//! use mathlex::{parse_with_config, ParserConfig, NumberSystem};
//! use std::collections::HashSet;
//!
//! let config = ParserConfig {
//!     implicit_multiplication: true,
//!     number_system: NumberSystem::Complex,
//!     ..Default::default()
//! };
//!
//! // Parse with custom configuration
//! let expr = parse_with_config("2*x + 3", &config).unwrap();
//! ```
//!
//! ### Context-Aware Parsing
//!
//! The parser uses context awareness for certain symbols:
//!
//! - **`e`**: Parsed as Euler's constant unless it appears in an exponent
//!   (where it's treated as a variable for scientific notation)
//! - **`i`, `j`, `k`**: Interpreted based on [`NumberSystem`] setting:
//!   - In `Real`: treated as variables
//!   - In `Complex`: `i` is the imaginary unit, `j` and `k` are variables
//!   - In `Quaternion`: `i`, `j`, `k` are quaternion basis vectors
//!
//! ```
//! use mathlex::{parse_latex, Expression, MathConstant};
//!
//! // 'e' as Euler's constant
//! let euler = parse_latex(r"e").unwrap();
//! assert_eq!(euler, Expression::constant(MathConstant::E));
//!
//! // 'i' as imaginary unit (when explicitly marked)
//! let imag = parse_latex(r"\mathrm{i}").unwrap();
//! assert_eq!(imag, Expression::constant(MathConstant::I));
//! ```
//!
//! ## Parser Features
//!
//! ### Expression Subscripts
//!
//! The LaTeX parser supports complex expression subscripts that are flattened into
//! variable names:
//!
//! ```
//! use mathlex::{parse_latex, Expression};
//!
//! // Simple subscript: x_i
//! let simple = parse_latex(r"x_i").unwrap();
//! assert_eq!(simple, Expression::variable("x_i".to_string()));
//!
//! // Expression subscript: x_{i+1}
//! let expr_sub = parse_latex(r"x_{i+1}").unwrap();
//! assert_eq!(expr_sub, Expression::variable("x_iplus1".to_string()));
//!
//! // Complex subscript: a_{n-1}
//! let complex = parse_latex(r"a_{n-1}").unwrap();
//! assert_eq!(complex, Expression::variable("a_nminus1".to_string()));
//! ```
//!
//! Supported subscript operators: `+` (plus), `-` (minus), `*` (times), `/` (div), `^` (pow)
//!
//! ### Derivative Notation
//!
//! Both explicit and standard derivative notations are supported:
//!
//! ```
//! use mathlex::{parse_latex, Expression, ExprKind};
//!
//! // Standard notation: d/dx followed by expression
//! let standard = parse_latex(r"\frac{d}{dx}f").unwrap();
//! assert!(matches!(standard.kind, ExprKind::Derivative { .. }));
//!
//! // Explicit multiplication marker: d/d*x (when variable needs explicit marker)
//! let explicit = parse_latex(r"\frac{d}{d*x}f").unwrap();
//! assert!(matches!(explicit.kind, ExprKind::Derivative { .. }));
//!
//! // Partial derivatives: ∂/∂x followed by expression
//! let partial = parse_latex(r"\frac{\partial}{\partial x}f").unwrap();
//! assert!(matches!(partial.kind, ExprKind::PartialDerivative { .. }));
//!
//! // Higher order: d²/dx² followed by expression
//! let second = parse_latex(r"\frac{d^2}{dx^2}f").unwrap();
//! if let ExprKind::Derivative { order, .. } = second.kind {
//!     assert_eq!(order, 2);
//! }
//! ```
//!
//! ## Design Philosophy
//!
//! mathlex follows the principle of single responsibility:
//!
//! - **Parse** text into AST
//! - **Convert** AST back to text (plain or LaTeX)
//! - **Query** AST (find variables, functions)
//! - **Transform** AST (substitution)
//!
//! What mathlex does NOT do:
//!
//! - Evaluate expressions
//! - Simplify expressions
//! - Solve equations
//! - Perform any mathematical computation
//!
//! This design allows mathlex to serve as a shared foundation for both
//! symbolic computation systems (like thales) and numerical libraries
//! (like NumericSwift) without creating dependencies between them.

#![warn(missing_docs)]
#![warn(clippy::all)]

use std::collections::HashSet;

// Modules will be added as development progresses
pub mod ast;
pub mod context;
pub mod display;
pub mod error;
pub mod latex;
pub mod metadata;
pub mod parser;
pub mod util;

#[cfg(feature = "ffi")]
pub mod ffi;

// Re-export key types at crate root for convenience
pub use ast::{
    AnnotationSet, BinaryOp, Direction, ExprKind, Expression, IndexType, InequalityOp,
    IntegralBounds, LogicalOp, MathConstant, MathFloat, MultipleBounds, NumberSet, RelationOp,
    SetOp, SetRelation, TensorIndex, UnaryOp, VectorNotation,
};
pub use context::{parse_system, ExpressionContext, InputFormat};
pub use error::{ParseError, ParseErrorKind, ParseOutput, ParseResult, Position, Span};
pub use latex::ToLatex;
pub use metadata::{ContextSource, ExpressionMetadata, MathType};

// Re-export parser functions
pub use parser::{
    parse, parse_equation_system, parse_latex, parse_latex_equation_system, parse_latex_lenient,
    parse_lenient, parse_lenient_with_config,
};

/// Number system context for parsing.
///
/// Indicates the assumed number system for parsing expressions.
/// This can help disambiguate notation in context-dependent scenarios.
///
/// # Examples
///
/// ```
/// use mathlex::NumberSystem;
///
/// let real = NumberSystem::Real;
/// let complex = NumberSystem::Complex;
/// let quaternion = NumberSystem::Quaternion;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NumberSystem {
    /// Real number system (default)
    #[default]
    Real,
    /// Complex number system
    Complex,
    /// Quaternion number system
    Quaternion,
}

/// Index convention for tensor notation.
///
/// Specifies how repeated indices should be interpreted in expressions.
///
/// # Examples
///
/// ```
/// use mathlex::IndexConvention;
///
/// let standard = IndexConvention::Standard;
/// let einstein = IndexConvention::EinsteinSummation;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexConvention {
    /// Standard index notation (default)
    #[default]
    Standard,
    /// Einstein summation convention (implied summation over repeated indices)
    EinsteinSummation,
}

/// Configuration options for the mathematical expression parser.
///
/// This struct controls various parsing behaviors including implicit
/// multiplication, number system context, and symbol declarations.
///
/// # Examples
///
/// ```
/// use mathlex::{ParserConfig, NumberSystem, IndexConvention};
/// use std::collections::HashSet;
///
/// // Use default configuration
/// let config = ParserConfig::default();
/// assert_eq!(config.implicit_multiplication, true);
///
/// // Create custom configuration with context hints
/// let mut declared_vectors = HashSet::new();
/// declared_vectors.insert("v".to_string());
/// declared_vectors.insert("u".to_string());
///
/// let config = ParserConfig {
///     implicit_multiplication: false,
///     number_system: NumberSystem::Complex,
///     index_convention: IndexConvention::EinsteinSummation,
///     declared_vectors,
///     declared_matrices: HashSet::new(),
///     declared_scalars: HashSet::new(),
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParserConfig {
    /// Enable implicit multiplication (e.g., `2x` means `2*x`).
    ///
    /// When `true`, expressions like `2x` or `(a)(b)` are interpreted
    /// as multiplication. When `false`, such expressions may result in
    /// parse errors.
    ///
    /// Default: `true`
    pub implicit_multiplication: bool,

    /// Number system context for parsing.
    ///
    /// Indicates the assumed number system which can help disambiguate
    /// notation in context-dependent scenarios.
    ///
    /// Default: `NumberSystem::Real`
    pub number_system: NumberSystem,

    /// Index convention for tensor notation.
    ///
    /// Specifies how repeated indices should be interpreted in expressions,
    /// particularly for Einstein summation convention.
    ///
    /// Default: `IndexConvention::Standard`
    pub index_convention: IndexConvention,

    /// Declared vector symbols.
    ///
    /// A set of symbol names that should be treated as vectors during parsing.
    /// This helps the parser disambiguate between scalar and vector quantities.
    ///
    /// Default: empty set
    pub declared_vectors: HashSet<String>,

    /// Declared matrix symbols.
    ///
    /// A set of symbol names that should be treated as matrices during parsing.
    /// This helps the parser disambiguate between scalar and matrix quantities.
    ///
    /// Default: empty set
    pub declared_matrices: HashSet<String>,

    /// Declared scalar symbols.
    ///
    /// A set of symbol names that should be explicitly treated as scalars.
    /// Useful when certain symbols might otherwise be ambiguous.
    ///
    /// Default: empty set
    pub declared_scalars: HashSet<String>,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            implicit_multiplication: true,
            number_system: NumberSystem::default(),
            index_convention: IndexConvention::default(),
            declared_vectors: HashSet::new(),
            declared_matrices: HashSet::new(),
            declared_scalars: HashSet::new(),
        }
    }
}

/// Parses a plain text mathematical expression with custom configuration.
///
/// This function allows parsing with custom configuration options.
///
/// # Arguments
///
/// * `input` - The mathematical expression string to parse
/// * `config` - Parser configuration options
///
/// # Returns
///
/// A `ParseResult<Expression>` containing the parsed AST or an error.
///
/// # Examples
///
/// ```
/// use mathlex::{parse_with_config, ParserConfig};
///
/// let config = ParserConfig::default();
/// let expr = parse_with_config("sin(x) + 2", &config).unwrap();
/// ```
///
/// ```
/// use mathlex::{parse_with_config, ParserConfig, Expression, ExprKind, BinaryOp};
///
/// let config = ParserConfig {
///     implicit_multiplication: true,
///     ..Default::default()
/// };
///
/// // Parse expression with implicit multiplication
/// let expr = parse_with_config("2x", &config).unwrap();
/// match &expr.kind {
///     ExprKind::Binary { op: BinaryOp::Mul, .. } => println!("Parsed as multiplication"),
///     _ => panic!("Unexpected expression type"),
/// }
/// ```
pub fn parse_with_config(input: &str, config: &ParserConfig) -> ParseResult<Expression> {
    parser::parse_with_config(input, config)
}

/// Placeholder for library version
pub const VERSION: &str = env!("CARGO_PKG_VERSION");