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
use super::{FormattingContext, FormattingError};
use crate::core::expression::smart_display::SmartDisplayFormatter;
use crate::core::expression::{CalculusData, RelationType};
use crate::core::{Expression, Number};
use crate::functions::intelligence::get_universal_registry;
const MAX_RECURSION_DEPTH: usize = 1000;
const MAX_TERMS_PER_OPERATION: usize = 10000;
/// Wolfram formatting context
#[derive(Debug, Default, Clone)]
pub struct WolframContext {
pub needs_parentheses: bool,
}
impl FormattingContext for WolframContext {}
/// Format the expression to Wolfram Language
pub trait WolframFormatter {
/// Format an Expression as Wolfram Language notation
///
/// Converts mathematical expressions into Wolfram Language format suitable for
/// use in Mathematica and other Wolfram products.
///
/// # Arguments
/// * `context` - Wolfram formatting configuration
///
/// # Context Options
/// * `needs_parentheses` - Whether to wrap the entire expression in parentheses
///
/// # Examples
/// ```
/// use mathhook_core::{Expression, expr};
/// use mathhook_core::formatter::wolfram::{WolframFormatter, WolframContext};
///
/// let expression = expr!(x ^ 2);
/// let context = WolframContext::default();
/// let result = expression.to_wolfram(&context).unwrap();
/// assert!(result.contains("Power"));
/// assert!(result.contains("x"));
/// ```
///
/// # Error Handling
/// Returns error messages for expressions that exceed safety limits:
/// - Maximum recursion depth (1000 levels)
/// - Maximum terms per operation (10000 terms)
fn to_wolfram(&self, context: &WolframContext) -> Result<String, FormattingError> {
self.to_wolfram_with_depth(context, 0)
}
/// Format with explicit recursion depth tracking
///
/// Internal method that provides stack overflow protection by tracking
/// recursion depth. This method returns a Result to allow proper error
/// propagation during recursive formatting.
///
/// # Arguments
/// * `context` - Wolfram formatting configuration
/// * `depth` - Current recursion depth (starts at 0)
///
/// # Returns
/// * `Ok(String)` - Successfully formatted Wolfram expression
/// * `Err(String)` - Error message if limits exceeded
///
/// # Safety Limits
/// * Maximum recursion depth: 1000 levels
/// * Maximum terms per operation: 10000 terms/factors/arguments
fn to_wolfram_with_depth(
&self,
context: &WolframContext,
depth: usize,
) -> Result<String, FormattingError>;
/// Convert function to Wolfram Language with depth tracking
fn format_function_with_depth(
&self,
name: &str,
args: &[Expression],
context: &WolframContext,
depth: usize,
) -> Result<String, FormattingError>;
}
impl WolframFormatter for Expression {
fn to_wolfram_with_depth(
&self,
context: &WolframContext,
depth: usize,
) -> Result<String, FormattingError> {
if depth > MAX_RECURSION_DEPTH {
return Err(FormattingError::RecursionLimitExceeded {
depth,
limit: MAX_RECURSION_DEPTH,
});
}
match self {
Expression::Number(Number::Integer(n)) => Ok(n.to_string()),
Expression::Number(Number::BigInteger(n)) => Ok(n.to_string()),
Expression::Number(Number::Rational(r)) => {
if r.denom() == &num_bigint::BigInt::from(1) {
Ok(r.numer().to_string())
} else {
// Use Power[denominator, -1] for proper Wolfram syntax
Ok(format!("Times[{}, Power[{}, -1]]", r.numer(), r.denom()))
}
}
Expression::Number(Number::Float(f)) => Ok(f.to_string()),
Expression::Symbol(s) => Ok(s.name().to_owned()),
Expression::Add(terms) => {
if terms.len() > MAX_TERMS_PER_OPERATION {
return Err(FormattingError::TooManyTerms {
count: terms.len(),
limit: MAX_TERMS_PER_OPERATION,
});
}
if terms.len() == 1 {
terms[0].to_wolfram_with_depth(context, depth + 1)
} else if terms.len() == 2
&& SmartDisplayFormatter::is_negated_expression(&terms[1])
{
// Smart subtraction detection: x + (-1 * y) → Subtract[x, y]
if let Some(positive_part) =
SmartDisplayFormatter::extract_negated_expression(&terms[1])
{
Ok(format!(
"Subtract[{}, {}]",
terms[0].to_wolfram_with_depth(context, depth + 1)?,
positive_part.to_wolfram_with_depth(context, depth + 1)?
))
} else {
let mut term_strs = Vec::with_capacity(terms.len());
for term in terms.iter() {
term_strs.push(term.to_wolfram_with_depth(context, depth + 1)?);
}
Ok(format!("Plus[{}]", term_strs.join(", ")))
}
} else {
let mut term_strs = Vec::with_capacity(terms.len());
for term in terms.iter() {
term_strs.push(term.to_wolfram_with_depth(context, depth + 1)?);
}
Ok(format!("Plus[{}]", term_strs.join(", ")))
}
}
Expression::Mul(factors) => {
if factors.len() > MAX_TERMS_PER_OPERATION {
return Err(FormattingError::TooManyTerms {
count: factors.len(),
limit: MAX_TERMS_PER_OPERATION,
});
}
if factors.len() == 1 {
factors[0].to_wolfram_with_depth(context, depth + 1)
} else if let Some((dividend, divisor)) =
SmartDisplayFormatter::extract_division_parts(factors)
{
// Smart division detection: x * y^(-1) → Divide[x, y]
Ok(format!(
"Divide[{}, {}]",
dividend.to_wolfram_with_depth(context, depth + 1)?,
divisor.to_wolfram_with_depth(context, depth + 1)?
))
} else {
let mut factor_strs = Vec::with_capacity(factors.len());
for factor in factors.iter() {
factor_strs.push(factor.to_wolfram_with_depth(context, depth + 1)?);
}
Ok(format!("Times[{}]", factor_strs.join(", ")))
}
}
Expression::Pow(base, exp) => Ok(format!(
"Power[{}, {}]",
base.to_wolfram_with_depth(context, depth + 1)?,
exp.to_wolfram_with_depth(context, depth + 1)?
)),
Expression::Function { name, args } => {
self.format_function_with_depth(name, args, context, depth + 1)
}
Expression::Complex(complex_data) => Ok(format!(
"Complex[{}, {}]",
complex_data
.real
.to_wolfram_with_depth(context, depth + 1)?,
complex_data
.imag
.to_wolfram_with_depth(context, depth + 1)?
)),
Expression::Matrix(_) => Ok("matrix".to_owned()),
Expression::Constant(c) => Ok(format!("{:?}", c)),
Expression::Relation(relation_data) => {
let left_wolfram = relation_data
.left
.to_wolfram_with_depth(context, depth + 1)?;
let right_wolfram = relation_data
.right
.to_wolfram_with_depth(context, depth + 1)?;
let operator = match relation_data.relation_type {
RelationType::Equal => "Equal",
RelationType::NotEqual => "Unequal",
RelationType::Less => "Less",
RelationType::LessEqual => "LessEqual",
RelationType::Greater => "Greater",
RelationType::GreaterEqual => "GreaterEqual",
RelationType::Approximate => "TildeEqual",
RelationType::Similar => "Tilde",
RelationType::Proportional => "Proportional",
RelationType::Congruent => "Congruent",
};
Ok(format!("{}[{}, {}]", operator, left_wolfram, right_wolfram))
}
Expression::Piecewise(piecewise_data) => {
let mut conditions = Vec::new();
let mut values = Vec::new();
for (condition, value) in &piecewise_data.pieces {
conditions.push(condition.to_wolfram_with_depth(context, depth + 1)?);
values.push(value.to_wolfram_with_depth(context, depth + 1)?);
}
if let Some(default_value) = &piecewise_data.default {
conditions.push("True".to_owned());
values.push(default_value.to_wolfram_with_depth(context, depth + 1)?);
}
let conditions_list = format!("{{{}}}", conditions.join(", "));
let values_list = format!("{{{}}}", values.join(", "));
Ok(format!("Piecewise[{}, {}]", values_list, conditions_list))
}
Expression::Set(elements) => {
if elements.len() > MAX_TERMS_PER_OPERATION {
return Err(FormattingError::TooManyTerms {
count: elements.len(),
limit: MAX_TERMS_PER_OPERATION,
});
}
if elements.is_empty() {
Ok("{}".to_owned())
} else {
let mut element_strs = Vec::with_capacity(elements.len());
for elem in elements.iter() {
element_strs.push(elem.to_wolfram_with_depth(context, depth + 1)?);
}
Ok(format!("{{{}}}", element_strs.join(", ")))
}
}
Expression::Interval(_) => Ok("interval".to_owned()),
Expression::Calculus(calculus_data) => {
Ok(match calculus_data.as_ref() {
CalculusData::Derivative {
expression,
variable,
order,
} => {
if *order == 1 {
format!(
"D[{}, {}]",
expression.to_wolfram_with_depth(context, depth + 1)?,
variable.name()
)
} else {
format!(
"D[{}, {{{}, {}}}]",
expression.to_wolfram_with_depth(context, depth + 1)?,
variable.name(),
order
)
}
}
CalculusData::Integral {
integrand,
variable,
bounds,
} => match bounds {
None => format!(
"Integrate[{}, {}]",
integrand.to_wolfram_with_depth(context, depth + 1)?,
variable.name()
),
Some((start, end)) => format!(
"Integrate[{}, {{{}, {}, {}}}]",
integrand.to_wolfram_with_depth(context, depth + 1)?,
variable.name(),
start.to_wolfram_with_depth(context, depth + 1)?,
end.to_wolfram_with_depth(context, depth + 1)?
),
},
CalculusData::Limit {
expression,
variable,
point,
direction: _,
} => {
// Simplified Wolfram limit format for roundtrip consistency
format!(
"Limit[{}, {} -> {}]",
expression.to_wolfram_with_depth(context, depth + 1)?,
variable.name(),
point.to_wolfram_with_depth(context, depth + 1)?
)
}
CalculusData::Sum {
expression,
variable,
start,
end,
} => {
format!(
"Sum[{}, {{{}, {}, {}}}]",
expression.to_wolfram_with_depth(context, depth + 1)?,
variable.name(),
start.to_wolfram_with_depth(context, depth + 1)?,
end.to_wolfram_with_depth(context, depth + 1)?
)
}
CalculusData::Product {
expression,
variable,
start,
end,
} => {
format!(
"Product[{}, {{{}, {}, {}}}]",
expression.to_wolfram_with_depth(context, depth + 1)?,
variable.name(),
start.to_wolfram_with_depth(context, depth + 1)?,
end.to_wolfram_with_depth(context, depth + 1)?
)
}
})
}
Expression::MethodCall(method_data) => {
let object_str = method_data
.object
.to_wolfram_with_depth(context, depth + 1)?;
let args_str = method_data
.args
.iter()
.map(|arg| arg.to_wolfram_with_depth(context, depth + 1))
.collect::<Result<Vec<_>, _>>()?
.join(", ");
Ok(format!(
"{}.{}[{}]",
object_str, method_data.method_name, args_str
))
}
}
}
/// Convert function to Wolfram Language with depth tracking
fn format_function_with_depth(
&self,
name: &str,
args: &[Expression],
context: &WolframContext,
depth: usize,
) -> Result<String, FormattingError> {
if args.len() > MAX_TERMS_PER_OPERATION {
return Err(FormattingError::TooManyTerms {
count: args.len(),
limit: MAX_TERMS_PER_OPERATION,
});
}
let registry = get_universal_registry();
let wolfram_name = registry
.get_properties(name)
.and_then(|props| match props {
crate::functions::properties::FunctionProperties::Elementary(elem_props) => {
elem_props.wolfram_name
}
crate::functions::properties::FunctionProperties::Special(spec_props) => {
spec_props.wolfram_name
}
_ => None,
})
.unwrap_or(name);
if args.is_empty() {
Ok(wolfram_name.to_owned())
} else {
let mut arg_strs = Vec::with_capacity(args.len());
for arg in args.iter() {
arg_strs.push(arg.to_wolfram_with_depth(context, depth + 1)?);
}
Ok(format!("{}[{}]", wolfram_name, arg_strs.join(", ")))
}
}
}