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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Expression and equation parser for mathematical notation.
//!
//! This module provides a complete parser for mathematical expressions and equations,
//! converting string input into Abstract Syntax Tree (AST) structures for evaluation
//! and manipulation.
//!
//! # Supported Syntax
//!
//! The parser supports a comprehensive set of mathematical constructs:
//!
//! | Category | Syntax | Example |
//! |----------|--------|---------|
//! | **Numbers** | Integer | `42`, `-17` |
//! | | Float | `3.14`, `-2.5` |
//! | | Scientific notation | `1.5e10`, `2.3e-5` |
//! | **Variables** | Identifiers | `x`, `theta`, `my_var_2` |
//! | **Binary Operators** | Addition | `a + b` |
//! | | Subtraction | `a - b` |
//! | | Multiplication | `a * b` |
//! | | Division | `a / b` |
//! | | Modulo | `a % b` |
//! | | Power | `a ^ b` |
//! | **Unary Operators** | Negation | `-x` |
//! | **Functions** | Trigonometric | `sin(x)`, `cos(x)`, `tan(x)` |
//! | | Inverse trig | `asin(x)`, `acos(x)`, `atan(x)`, `atan2(y, x)` |
//! | | Hyperbolic | `sinh(x)`, `cosh(x)`, `tanh(x)` |
//! | | Exponential | `exp(x)`, `pow(base, exp)` |
//! | | Logarithmic | `ln(x)`, `log(value, base)`, `log2(x)`, `log10(x)` |
//! | | Root | `sqrt(x)`, `cbrt(x)` |
//! | | Rounding | `floor(x)`, `ceil(x)`, `round(x)` |
//! | | Other | `abs(x)`, `sign(x)`, `min(a, b)`, `max(a, b)` |
//! | **Grouping** | Parentheses | `(a + b) * c` |
//! | **Equations** | Equality | `x + 2 = 5` |
//!
//! # Operator Precedence
//!
//! Operators are evaluated in the following order (highest to lowest precedence):
//!
//! 1. **Function calls**: `sin(x)`, `sqrt(y)` - highest precedence
//! 2. **Unary negation**: `-x` - right-associative
//! 3. **Power**: `a ^ b` - right-associative (e.g., `2 ^ 3 ^ 4` = `2 ^ (3 ^ 4)`)
//! 4. **Multiplication/Division/Modulo**: `a * b`, `a / b`, `a % b` - left-associative
//! 5. **Addition/Subtraction**: `a + b`, `a - b` - left-associative
//!
//! Use parentheses to override precedence: `(a + b) * c` evaluates addition before multiplication.
//!
//! # Examples
//!
//! ## Simple Expression
//!
//! ```
//! use thales::parser::parse_expression;
//! use thales::ast::{Expression, BinaryOp};
//!
//! let expr = parse_expression("2 + 3").unwrap();
//! match expr {
//! Expression::Binary(BinaryOp::Add, _, _) => println!("Parsed addition"),
//! _ => panic!("Expected addition"),
//! }
//! ```
//!
//! ## Complex Expression with Functions
//!
//! ```
//! use thales::parser::parse_expression;
//!
//! let expr = parse_expression("sin(x) + cos(y) * 2").unwrap();
//! // Parses as: (sin(x)) + ((cos(y)) * 2)
//! ```
//!
//! ## Power Expression (Right-Associative)
//!
//! ```
//! use thales::parser::parse_expression;
//! use thales::ast::Expression;
//!
//! let expr = parse_expression("2 ^ 3 ^ 4").unwrap();
//! // Parses as: 2 ^ (3 ^ 4) = 2 ^ 81, not (2 ^ 3) ^ 4
//! ```
//!
//! ## Equation Parsing
//!
//! ```
//! use thales::parser::parse_equation;
//!
//! let eq = parse_equation("x + 2 = 5").unwrap();
//! println!("Left side: {:?}", eq.left);
//! println!("Right side: {:?}", eq.right);
//! ```
//!
//! ## Error Handling
//!
//! ```
//! use thales::parser::{parse_expression, ParseError};
//!
//! match parse_expression("2 + + 3") {
//! Ok(expr) => println!("Parsed: {:?}", expr),
//! Err(errors) => {
//! for err in errors {
//! eprintln!("Parse error: {}", err);
//! }
//! }
//! }
//! ```
//!
//! # Performance
//!
//! The parser runs in O(n) time complexity where n is the length of the input string.
//! Memory complexity is O(d) where d is the maximum nesting depth of the expression.
//!
//! # Implicit Multiplication
//!
//! The parser supports implicit multiplication in several forms:
//!
//! | Pattern | Interpretation | Example |
//! |---------|----------------|---------|
//! | Number-Variable | Coefficient | `2x` → `2 * x` |
//! | Number-Parenthesis | Coefficient | `2(x+1)` → `2 * (x+1)` |
//! | Parenthesis-Parenthesis | Product | `(a)(b)` → `a * b` |
//! | Variable Variable (spaced) | Product | `x y` → `x * y` |
//!
//! Note: Multi-character identifiers like `xy` or `theta` are NOT split into
//! separate variables. Use spaces to separate variables: `x y` not `xy`.
//!
//! # Symbolic Constants
//!
//! The parser recognizes the following symbolic constants:
//!
//! | Constant | Keyword | Value |
//! |----------|---------|-------|
//! | π (pi) | `pi` | 3.14159... |
//! | e (Euler's number) | `e` | 2.71828... |
//! | i (imaginary unit) | `i` | √(-1) |
//!
//! # Note
//!
//! Parsing is delegated to the [mathlex](https://crates.io/crates/mathlex) library.
//! For LaTeX input, see the [`latex`](crate::latex) module.
use crate;
use cratemathlex_bridge;
/// Parse error type with detailed position information.
///
/// All error variants include a `pos` field indicating the character position
/// where the error was detected (0-based index).
///
/// # Error Variants
///
/// - **UnexpectedCharacter**: Found a character that doesn't fit the grammar at this position
/// - **UnexpectedEndOfInput**: Input ended when more tokens were expected
/// - **InvalidNumber**: Number format is incorrect (e.g., "1.2.3", "1e")
/// - **UnknownFunction**: Function name not recognized
/// - **MismatchedParentheses**: Opening/closing parentheses don't match
/// - **InvalidExpression**: Generic parse error with custom message
///
/// # Examples
///
/// ```
/// use thales::parser::{parse_expression, ParseError};
///
/// // Unexpected character
/// match parse_expression("2 @ 3") {
/// Err(errors) => {
/// assert!(errors.iter().any(|e| matches!(
/// e,
/// ParseError::UnexpectedCharacter { pos: 2, found: '@' }
/// )));
/// }
/// Ok(_) => panic!("Expected parse error"),
/// }
///
/// // With implicit multiplication, `foo(x)` parses as `foo * x`.
/// // To trigger an actual parse error, use truly invalid syntax:
/// match parse_expression("2 +* 3") {
/// Err(errors) => {
/// assert!(!errors.is_empty());
/// }
/// Ok(_) => panic!("Expected parse error"),
/// }
/// ```
/// Convert a mathlex ParseError into a thales ParseError.
/// Parses a mathematical expression from string input into an AST.
///
/// This function converts a textual mathematical expression into an Abstract Syntax Tree
/// (AST) represented by the `Expression` enum. The parser supports all operators, functions,
/// and syntax described in the module-level documentation.
///
/// # Arguments
///
/// * `input` - String slice containing the mathematical expression
///
/// # Returns
///
/// * `Ok(Expression)` - Successfully parsed expression as AST
/// * `Err(Vec<ParseError>)` - One or more parse errors with position information
///
/// # Performance
///
/// Runs in O(n) time where n is the input length. Maximum recursion depth is proportional
/// to expression nesting depth.
///
/// # Examples
///
/// ## Simple Arithmetic
///
/// ```
/// use thales::parser::parse_expression;
/// use thales::ast::{Expression, BinaryOp};
///
/// let expr = parse_expression("2 + 3").unwrap();
/// match expr {
/// Expression::Binary(BinaryOp::Add, _, _) => println!("Addition expression"),
/// _ => panic!("Expected addition"),
/// }
/// ```
///
/// ## Scientific Notation
///
/// ```
/// use thales::parser::parse_expression;
/// use thales::ast::Expression;
///
/// let expr = parse_expression("1.5e-10").unwrap();
/// match expr {
/// Expression::Float(val) => assert!((val - 1.5e-10).abs() < 1e-20),
/// _ => panic!("Expected float"),
/// }
/// ```
///
/// ## Nested Functions
///
/// ```
/// use thales::parser::parse_expression;
///
/// let expr = parse_expression("sqrt(abs(-16))").unwrap();
/// // Parses as: sqrt(abs(-16)) = sqrt(16) = 4
/// ```
///
/// ## Operator Precedence
///
/// ```
/// use thales::parser::parse_expression;
///
/// // Multiplication before addition
/// let expr = parse_expression("2 + 3 * 4").unwrap();
/// // Parses as: 2 + (3 * 4) = 14, not (2 + 3) * 4 = 20
///
/// // Power is right-associative
/// let expr = parse_expression("2 ^ 3 ^ 2").unwrap();
/// // Parses as: 2 ^ (3 ^ 2) = 2 ^ 9 = 512, not (2 ^ 3) ^ 2 = 8 ^ 2 = 64
/// ```
///
/// ## Multiple Variables
///
/// ```
/// use thales::parser::parse_expression;
///
/// let expr = parse_expression("x * y + z").unwrap();
/// // Expression with three variables
/// ```
///
/// ## Complex Expression
///
/// ```
/// use thales::parser::parse_expression;
///
/// let expr = parse_expression("sin(x) ^ 2 + cos(x) ^ 2").unwrap();
/// // Trigonometric identity expression
/// ```
///
/// ## Error Handling
///
/// ```
/// use thales::parser::{parse_expression, ParseError};
///
/// // Incomplete expression
/// match parse_expression("2 * ") {
/// Ok(_) => panic!("Should fail"),
/// Err(errors) => {
/// assert!(!errors.is_empty());
/// }
/// }
///
/// // Unary plus is valid: "2 + + 3" parses as 2 + (+3)
/// assert!(parse_expression("2 + + 3").is_ok());
///
/// // Unknown function names are parsed as generic function calls
/// assert!(parse_expression("foo(x)").is_ok());
/// ```
/// Parses a complete equation from string input into an AST.
///
/// An equation consists of two expressions separated by an equals sign (`=`).
/// The parsed equation has an empty ID by default (can be set later using
/// `Equation::with_id()`).
///
/// # Arguments
///
/// * `input` - String slice containing the equation (format: `expression = expression`)
///
/// # Returns
///
/// * `Ok(Equation)` - Successfully parsed equation with left and right sides
/// * `Err(Vec<ParseError>)` - One or more parse errors with position information
///
/// # Performance
///
/// Runs in O(n) time where n is the input length. Equivalent to parsing two expressions
/// plus the equals sign.
///
/// # Examples
///
/// ## Simple Linear Equation
///
/// ```
/// use thales::parser::parse_equation;
///
/// let eq = parse_equation("x + 2 = 5").unwrap();
/// assert_eq!(eq.id, "");
/// // eq.left: x + 2
/// // eq.right: 5
/// ```
///
/// ## Quadratic Equation
///
/// ```
/// use thales::parser::parse_equation;
///
/// let eq = parse_equation("x^2 + 3*x - 4 = 0").unwrap();
/// // Standard form quadratic equation
/// ```
///
/// ## Equation with Functions
///
/// ```
/// use thales::parser::parse_equation;
///
/// let eq = parse_equation("sin(x) = 0.5").unwrap();
/// // Trigonometric equation
/// ```
///
/// ## Complex Equation
///
/// ```
/// use thales::parser::parse_equation;
///
/// let eq = parse_equation("sqrt(x^2 + y^2) = r").unwrap();
/// // Distance formula equation
/// ```
///
/// ## Setting an ID
///
/// ```
/// use thales::parser::parse_equation;
///
/// let mut eq = parse_equation("F = m * a").unwrap();
/// eq.id = "newton_second_law".to_string();
/// assert_eq!(eq.id, "newton_second_law");
/// ```
///
/// ## Error Handling
///
/// ```
/// use thales::parser::parse_equation;
///
/// // Missing equals sign
/// assert!(parse_equation("x + 2").is_err());
///
/// // Multiple equals signs (not supported)
/// assert!(parse_equation("x = y = 5").is_err());
///
/// // Unary plus is valid, so "2 + + 3 = 5" parses successfully
/// assert!(parse_equation("2 + + 3 = 5").is_ok());
///
/// // Invalid expression on either side
/// assert!(parse_equation("x = 2 * * 3").is_err());
/// ```
///
/// # Limitations
///
/// - Only single equations supported (no equation systems)
/// - Exactly one equals sign required
/// - Both sides must be valid expressions
/// Parse a semicolon-separated list of equations into a vector of [`Equation`] values.
///
/// Each segment between semicolons is trimmed and parsed as a single equation using
/// [`parse_equation`]. Empty segments (e.g. trailing semicolons) are silently skipped.
/// If any segment fails to parse, the errors from **all** failing segments are
/// collected and returned together.
///
/// # Arguments
///
/// * `input` - A string containing one or more equations separated by `';'`.
///
/// # Returns
///
/// - `Ok(Vec<Equation>)` — all segments parsed successfully (empty input returns an
/// empty vector).
/// - `Err(Vec<ParseError>)` — one or more segments failed; every error from every
/// failing segment is included.
///
/// # Examples
///
/// ## Two-equation linear system
///
/// ```
/// use thales::parser::parse_equation_system;
///
/// let eqs = parse_equation_system("x + y = 5; 2*x - y = 1").unwrap();
/// assert_eq!(eqs.len(), 2);
/// ```
///
/// ## Trailing semicolon is ignored
///
/// ```
/// use thales::parser::parse_equation_system;
///
/// let eqs = parse_equation_system("x = 1;").unwrap();
/// assert_eq!(eqs.len(), 1);
/// ```
///
/// ## Empty input returns empty vector
///
/// ```
/// use thales::parser::parse_equation_system;
///
/// let eqs = parse_equation_system("").unwrap();
/// assert!(eqs.is_empty());
/// ```
///
/// ## Parse error propagation
///
/// ```
/// use thales::parser::parse_equation_system;
///
/// assert!(parse_equation_system("x + y = 5; not_an_equation").is_err());
/// ```