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
// Allow large error variants - boxing would be a breaking API change
#![allow(clippy::result_large_err)]
use super::*;
impl LatexParser {
/// Parses additive expressions (+, -, \pm, \mp) and set union/difference.
pub(super) fn parse_additive(&mut self) -> ParseResult<Expression> {
let mut left = self.parse_multiplicative()?;
while let Some((token, _)) = self.peek() {
// Check for set operations first (union, difference)
match token {
LatexToken::Cup => {
self.next(); // consume \cup
let right = self.parse_multiplicative()?;
left = ExprKind::SetOperation {
op: SetOp::Union,
left: Box::new(left),
right: Box::new(right),
}
.into();
continue;
}
LatexToken::Setminus => {
self.next(); // consume \setminus
let right = self.parse_multiplicative()?;
left = ExprKind::SetOperation {
op: SetOp::Difference,
left: Box::new(left),
right: Box::new(right),
}
.into();
continue;
}
_ => {}
}
// Standard arithmetic operators
let op = match token {
LatexToken::Plus => BinaryOp::Add,
LatexToken::Minus => BinaryOp::Sub,
LatexToken::Command(cmd) if cmd == "pm" => BinaryOp::PlusMinus,
LatexToken::Command(cmd) if cmd == "mp" => BinaryOp::MinusPlus,
_ => break,
};
self.next(); // consume operator
let right = self.parse_multiplicative()?;
left = ExprKind::Binary {
op,
left: Box::new(left),
right: Box::new(right),
}
.into();
}
Ok(left)
}
/// Tries to parse a named product operator (\circ, \bullet, \otimes, \wedge, \times).
/// Returns `Ok(new_left)` if a product operator was consumed, `Err(left)` otherwise.
pub(super) fn try_parse_named_product(
&mut self,
token: &LatexToken,
left: Expression,
) -> ParseResult<Result<Expression, Expression>> {
match token {
LatexToken::Circ => {
self.next();
let right = self.parse_power()?;
Ok(Ok(ExprKind::Composition {
outer: Box::new(left),
inner: Box::new(right),
}
.into()))
}
LatexToken::Bullet => {
self.next();
let right = self.parse_power()?;
Ok(Ok(ExprKind::DotProduct {
left: Box::new(left),
right: Box::new(right),
}
.into()))
}
LatexToken::Otimes => {
self.next();
let right = self.parse_power()?;
Ok(Ok(ExprKind::OuterProduct {
left: Box::new(left),
right: Box::new(right),
}
.into()))
}
LatexToken::Wedge => {
self.next();
let right = self.parse_power()?;
Ok(Ok(ExprKind::WedgeProduct {
left: Box::new(left),
right: Box::new(right),
}
.into()))
}
LatexToken::Cross => {
self.next();
let right = self.parse_power()?;
Ok(Ok(ExprKind::CrossProduct {
left: Box::new(left),
right: Box::new(right),
}
.into()))
}
_ => Ok(Err(left)),
}
}
/// Parses multiplicative expressions (*, /) and set intersection.
pub(super) fn parse_multiplicative(&mut self) -> ParseResult<Expression> {
let mut left = self.parse_power()?;
while let Some((t, _)) = self.peek() {
// Clone the token so we drop the immutable borrow before any `&mut self` call.
let token = t.clone();
// Set intersection
if matches!(token, LatexToken::Cap) {
self.next();
let right = self.parse_power()?;
left = ExprKind::SetOperation {
op: SetOp::Intersection,
left: Box::new(left),
right: Box::new(right),
}
.into();
continue;
}
// Named product operators (\circ, \bullet, \otimes, \wedge, \times)
match self.try_parse_named_product(&token, left)? {
Ok(new_left) => {
left = new_left;
continue;
}
Err(returned) => {
left = returned;
}
}
// Regular scalar multiplication (token was already cloned above)
let op = match &token {
LatexToken::Star | LatexToken::Cdot => BinaryOp::Mul,
LatexToken::Slash => BinaryOp::Div,
_ => {
if self.should_insert_implicit_mult(&left) {
BinaryOp::Mul
} else {
break;
}
}
};
// Consume the explicit operator (not for implicit multiplication)
if matches!(
token,
LatexToken::Star | LatexToken::Cdot | LatexToken::Slash
) {
self.next();
}
let right = self.parse_power()?;
left = ExprKind::Binary {
op,
left: Box::new(left),
right: Box::new(right),
}
.into();
}
Ok(left)
}
/// Determines if implicit multiplication should be inserted in LaTeX.
/// This is used for patterns like 2x, xy, 2\pi, i\pi, etc.
pub(super) fn should_insert_implicit_mult(&self, left: &Expression) -> bool {
// Only insert implicit mult when left is a simple variable, number, constant, or differential
let is_valid_left = matches!(
left.kind,
ExprKind::Variable(_)
| ExprKind::Integer(_)
| ExprKind::Float(_)
| ExprKind::Constant(_)
| ExprKind::Differential { .. }
);
if !is_valid_left {
return false;
}
// Check if next token is something that could start a multiplicand
match self.peek() {
Some((LatexToken::Letter(ch), _)) => {
// In integral context, don't trigger implicit mult for 'd' followed by a letter
// This allows the integral parser to handle 'dx' properly
if self.in_integral_context && *ch == 'd' {
if let Some((LatexToken::Letter(_), _)) = self.peek_ahead(1) {
return false;
}
}
true
}
Some((LatexToken::Command(cmd), _)) => {
// Exclude relation commands and right delimiters - they should not trigger implicit mult
!matches!(
cmd.as_str(),
"lt" | "gt"
| "leq"
| "le"
| "geq"
| "ge"
| "neq"
| "ne"
| "pm"
| "mp"
| "cdot"
| "times"
| "div"
| "rfloor"
| "rceil"
)
}
Some((LatexToken::LParen, _)) => true,
Some((LatexToken::LBrace, _)) => true,
_ => false,
}
}
/// Returns true when the token stream after `^` indicates a transpose:
/// - bare `T` letter: `^T`
/// - braced `{T}`: `^{T}`
/// - `\top` command: `^\top`
fn is_transpose_exponent(&self) -> bool {
match self.peek() {
Some((LatexToken::Letter('T'), _)) => true,
Some((LatexToken::Command(cmd), _)) if cmd == "top" => true,
Some((LatexToken::LBrace, _)) => {
// peek inside: {T}
matches!(self.peek_ahead(1), Some((LatexToken::Letter('T'), _)))
&& matches!(self.peek_ahead(2), Some((LatexToken::RBrace, _)))
}
_ => false,
}
}
/// Consumes the transpose exponent token(s) after `^` has been consumed.
fn consume_transpose_exponent(&mut self) {
match self.peek() {
Some((LatexToken::Letter('T'), _)) | Some((LatexToken::Command(_), _)) => {
self.next();
}
Some((LatexToken::LBrace, _)) => {
self.next(); // {
self.next(); // T
self.next(); // }
}
_ => {}
}
}
/// Parses power expressions (^) and subscripts (_).
///
/// Note: When the base is Euler's number `e` (Constant(E)), the expression
/// `e^x` is normalized to `exp(x)` for consistency with `\exp{x}`.
/// When the exponent is `T` or `\top`, the expression is parsed as a transpose.
pub(super) fn parse_power(&mut self) -> ParseResult<Expression> {
let mut base = self.parse_postfix()?;
// Handle superscript (power)
if self.check(&LatexToken::Caret) {
self.next(); // consume ^
// Check for transpose before consuming the exponent
if self.is_transpose_exponent() {
self.consume_transpose_exponent();
return Ok(ExprKind::Unary {
op: crate::ast::UnaryOp::Transpose,
operand: Box::new(base),
}
.into());
}
let exponent = self.parse_braced_or_atom()?;
// Normalize e^{...} to exp(...)
if matches!(base.kind, ExprKind::Constant(MathConstant::E)) {
return Ok(ExprKind::Function {
name: "exp".to_string(),
args: vec![exponent],
}
.into());
}
base = ExprKind::Binary {
op: BinaryOp::Pow,
left: Box::new(base),
right: Box::new(exponent),
}
.into();
}
// Handle subscript (append to variable name if base is a variable)
if self.check(&LatexToken::Underscore) {
self.next(); // consume _
let subscript = self.parse_braced_or_atom()?;
// Convert base to variable with subscript
base = match &base.kind {
ExprKind::Variable(name) => {
// Format: var_subscript
let subscript_str = self.expression_to_subscript_string(&subscript)?;
ExprKind::Variable(format!("{}_{}", name, subscript_str)).into()
}
_ => {
return Err(ParseError::invalid_subscript(
"subscript can only be applied to variables",
Some(self.current_span()),
));
}
};
}
Ok(base)
}
/// Parses postfix expressions (currently just primary, extensible for factorial, etc.).
pub(super) fn parse_postfix(&mut self) -> ParseResult<Expression> {
self.parse_primary()
}
}