# Product Requirements Document: Symbolic CAS Expansion
## mathsolver-core v0.2.0 - v1.0.0

**Document ID:** 20251231-1423_project_0.2.0_PRD_symbolic-cas-expansion
**Created:** 2025-12-31
**Author:** Claude Code (Opus 4.5)
**Status:** Draft for Review

---

## 1. Executive Summary

This PRD defines the expansion of mathsolver-core from a basic equation solver to a comprehensive Computer Algebra System (CAS) capable of symbolic mathematics at the level required for physics, engineering, and advanced mathematics education. The target is a clean-room, MIT-licensed Rust implementation that can be linked to iOS/macOS applications via FFI.

### Vision
Create a high-performance, memory-safe symbolic mathematics engine that:
- Parses LaTeX mathematical notation
- Solves equations symbolically for any variable
- Performs symbolic differentiation and integration
- Handles limits, differential equations, and linear algebra
- Generates step-by-step solution explanations
- Evaluates expressions numerically with configurable precision

### Scope
This PRD covers versions 0.2.0 through 1.0.0, building incrementally on the existing v0.1.0 foundation.

---

## 2. Background and Context

### 2.1 Current State (v0.1.0)

mathsolver-core already implements:

**Completed:**
- Core AST definitions (Expression, Equation, Variable, BinaryOp, UnaryOp, Function)
- Coordinate transformations (2D/3D: Cartesian, Polar, Spherical, Cylindrical)
- Complex number operations (De Moivre's theorem, polar form, conjugate, modulus)
- Linear equation solver (ax + b = c)
- Quadratic equation solver (ax^2 + bx + c = 0)
- Smart solver with method dispatch
- iOS cross-compilation (arm64, simulator)
- FFI bindings via swift-bridge
- Resolution path tracking infrastructure

**In Progress:**
- Expression parser using chumsky
- Polynomial solver (degree > 2)
- Numerical methods (Newton-Raphson, bisection, Brent's)
- Unit and dimension system

**Key Files (by size, indicating complexity):**
- ast.rs (105KB) - Expression and equation AST
- solver.rs (127KB) - Symbolic solving engine
- transforms.rs (55KB) - Coordinate transformations
- numerical.rs (44KB) - Numerical methods
- resolution_path.rs (35KB) - Step-by-step tracking
- dimensions.rs (34KB) - Unit system
- parser.rs (25KB) - Expression parser
- ffi.rs (24KB) - Swift bindings

### 2.2 Target Capabilities

The expanded CAS must handle:

1. **Basic Operations:** Arithmetic, exponents, logarithms, roots
2. **Trigonometry:** sin, cos, tan, cot, sec, csc with inverses
3. **Hyperbolic Functions:** sinh, cosh, tanh with inverses
4. **Complex Numbers:** Full complex arithmetic, Euler's formula, roots of unity
5. **Differentiation:** Simple, chain rule, product/quotient rule, partial derivatives
6. **Limits:** Including L'Hopital's rule for indeterminate forms
7. **Integration:** Definite and indefinite, basic techniques (substitution, parts)
8. **Differential Equations:** First-order ODEs, separable, linear
9. **Systems of Equations:** Linear and nonlinear systems
10. **Linear Algebra:** Matrix operations, determinants, eigenvalues/eigenvectors

### 2.3 Existing Rust CAS Landscape

Research identified these libraries:

| Library | License | Status | Relevance |
|---------|---------|--------|-----------|
| **mathcore** | MIT | Active (2025) | **Best candidate** - has differentiation, integration, equation solving |
| **Symbolica** | Commercial | Active | Not usable - proprietary license |
| **rusymbols** | MIT/Apache-2.0 | Stale (2020) | Unmaintained, unstable |
| **cas-rs** | Unknown | Early | Incomplete, focused on Discord bot |
| **Numerica** | MIT | Active | Symbolica spin-off - numeric types only |

**Recommendation:** Study mathcore's MIT-licensed implementation as a reference for clean-room development. Do not copy code directly; use the mathematical algorithms and patterns as inspiration.

### 2.4 Design Philosophy

Inspired by GiNaC (physics-focused CAS from CERN):
- Expressions as first-class objects
- Symbolic manipulation before numerical evaluation
- Extensible function system
- Pattern matching for transformations
- Memory-safe, zero-cost abstractions (Rust idioms)

---

## 3. Functional Requirements

### 3.1 LaTeX Input/Output

**Priority:** P0 (Critical)

#### 3.1.1 LaTeX Parser
- Parse standard LaTeX mathematical notation
- Support common macros: \frac, \sqrt, \sum, \int, \lim, \partial
- Handle Greek letters: \alpha, \beta, \gamma, \theta, \pi, etc.
- Parse superscripts/subscripts for exponents and indices
- Support matrices: \begin{matrix}, \begin{pmatrix}, \begin{bmatrix}

**Input Examples:**
```latex
\frac{d}{dx}(x^2 + 3x)
\int_0^{\pi} \sin(x) dx
\lim_{x \to 0} \frac{\sin(x)}{x}
\begin{pmatrix} a & b \\ c & d \end{pmatrix}
```

#### 3.1.2 LaTeX Output
- Render expressions back to valid LaTeX
- Configurable formatting (inline vs display mode)
- Proper fraction, root, and operator rendering

### 3.2 Symbolic Expression Engine

**Priority:** P0 (Critical)

#### 3.2.1 Expression Representation
Extend existing AST to support:
- Rational numbers (exact arithmetic)
- Symbolic constants (pi, e, i)
- Undefined symbols (variables)
- Composite expressions (sums, products)
- Special functions (Gamma, Bessel, etc. - future)

#### 3.2.2 Expression Simplification
- Combine like terms
- Reduce fractions to lowest terms
- Apply trigonometric identities
- Constant folding
- Common subexpression elimination

#### 3.2.3 Pattern Matching
- Match expression patterns for transformations
- Support wildcards in patterns
- Enable rule-based simplification

### 3.3 Symbolic Differentiation

**Priority:** P0 (Critical)

#### 3.3.1 Basic Differentiation
- Power rule: d/dx(x^n) = n*x^(n-1)
- Sum rule: d/dx(f + g) = f' + g'
- Constant rule: d/dx(c) = 0
- Product rule: d/dx(f*g) = f'*g + f*g'
- Quotient rule: d/dx(f/g) = (f'*g - f*g')/g^2

#### 3.3.2 Chain Rule
- d/dx(f(g(x))) = f'(g(x)) * g'(x)
- Recursive application for nested functions

#### 3.3.3 Transcendental Functions
- d/dx(sin(x)) = cos(x)
- d/dx(cos(x)) = -sin(x)
- d/dx(tan(x)) = sec^2(x)
- d/dx(e^x) = e^x
- d/dx(ln(x)) = 1/x
- d/dx(a^x) = a^x * ln(a)

#### 3.3.4 Partial Derivatives
- Specify variable of differentiation
- Hold other variables constant
- Support d/dx, d/dy, d/dz notation

#### 3.3.5 Higher-Order Derivatives
- d^n/dx^n for arbitrary n
- Mixed partial derivatives: d^2/(dx dy)

### 3.4 Limits

**Priority:** P1 (High)

#### 3.4.1 Basic Limits
- lim_{x -> a} f(x) by substitution
- One-sided limits (x -> a+ and x -> a-)
- Limits at infinity

#### 3.4.2 Indeterminate Forms
- Detect 0/0, infinity/infinity, 0*infinity, infinity - infinity
- Apply L'Hopital's rule automatically
- Track application count to prevent infinite loops

#### 3.4.3 Common Limits
- lim_{x -> 0} sin(x)/x = 1
- lim_{x -> infinity} (1 + 1/x)^x = e
- Pre-computed standard limits table

### 3.5 Symbolic Integration

**Priority:** P1 (High)

#### 3.5.1 Basic Integration
- Power rule: integral(x^n) = x^(n+1)/(n+1) + C
- Sum rule
- Constant multiple rule

#### 3.5.2 Standard Integrals
- Trigonometric: sin, cos, tan, sec, csc, cot
- Exponential: e^x, a^x
- Logarithmic: ln(x), log_a(x)
- Inverse trigonometric

#### 3.5.3 Integration Techniques
- Substitution (u-substitution)
- Integration by parts
- Partial fractions (for rational functions)
- Trigonometric substitution (basic cases)

#### 3.5.4 Definite Integrals
- Apply limits of integration
- Handle improper integrals (basic cases)
- Numerical fallback when symbolic fails

### 3.6 Equation Solving

**Priority:** P0 (Critical)

#### 3.6.1 Single Variable Equations
- Linear: ax + b = c
- Quadratic: ax^2 + bx + c = 0 (discriminant handling)
- Polynomial: degree 3+ (Cardano's formula, numerical fallback)
- Transcendental: sin(x) = 0.5, e^x = 10

#### 3.6.2 Solve for Any Variable
- Algebraic manipulation to isolate variable
- Handle implicit functions
- Multiple solutions (real and complex)

#### 3.6.3 Inequality Solving
- Linear inequalities
- Quadratic inequalities
- System of inequalities

### 3.7 Differential Equations

**Priority:** P2 (Medium)

#### 3.7.1 First-Order ODEs
- Separable equations: dy/dx = f(x)*g(y)
- Linear first-order: dy/dx + P(x)*y = Q(x)
- Exact equations
- Integrating factors

#### 3.7.2 Second-Order ODEs
- Constant coefficient: y'' + ay' + by = 0
- Non-homogeneous with method of undetermined coefficients
- Reduction of order

#### 3.7.3 Initial Value Problems
- Apply initial conditions
- Find particular solutions

### 3.8 Systems of Equations

**Priority:** P1 (High)

#### 3.8.1 Linear Systems
- Gaussian elimination
- LU decomposition
- Cramer's rule for small systems
- Handle over/under-determined systems

#### 3.8.2 Nonlinear Systems
- Newton-Raphson for systems (Jacobian)
- Fixed-point iteration
- Numerical methods with symbolic derivatives

### 3.9 Linear Algebra

**Priority:** P2 (Medium)

#### 3.9.1 Matrix Operations
- Addition, subtraction, multiplication
- Transpose, trace
- Scalar multiplication

#### 3.9.2 Matrix Properties
- Determinant (symbolic)
- Rank
- Inverse (when exists)

#### 3.9.3 Eigenvalue Problems
- Characteristic polynomial
- Eigenvalues (symbolic for small matrices)
- Eigenvectors
- Diagonalization

#### 3.9.4 Special Matrices
- Identity, zero, diagonal
- Symmetric, antisymmetric
- Orthogonal, unitary

### 3.10 Step-by-Step Solutions

**Priority:** P0 (Critical)

#### 3.10.1 Resolution Path
- Every operation recorded as a step
- Human-readable description for each step
- Mathematical justification (rule applied)

#### 3.10.2 Output Formats
- Plain text
- LaTeX
- Structured data (JSON for UI rendering)

#### 3.10.3 Verbosity Levels
- Minimal: just key transformations
- Standard: all major steps
- Detailed: every algebraic manipulation

### 3.11 Numerical Evaluation

**Priority:** P1 (High)

#### 3.11.1 Precision Control
- Fixed decimal places
- Significant figures
- Arbitrary precision (via num-bigint)

#### 3.11.2 Evaluation Modes
- Symbolic-first: simplify, then evaluate
- Numeric-first: evaluate early for performance
- Mixed: symbolic until variable substitution

#### 3.11.3 Special Values
- Handle infinity, NaN appropriately
- Complex results from real inputs

---

## 4. Non-Functional Requirements

### 4.1 Performance

| Metric | Target |
|--------|--------|
| Expression parsing | < 1ms for typical expressions |
| Symbolic differentiation | < 10ms for degree-10 polynomials |
| Integration (basic) | < 100ms |
| Matrix operations (4x4) | < 1ms |
| Eigenvalues (4x4) | < 10ms |

### 4.2 Memory

- Zero-copy where possible
- Expression trees use arena allocation for cache locality
- No memory leaks (Rust guarantees)

### 4.3 Portability

- Pure Rust core (no C dependencies except Lua if integrated)
- iOS: arm64, arm64-simulator, x86_64-simulator
- macOS: arm64, x86_64
- Linux: x86_64, arm64
- WebAssembly: future target

### 4.4 API Stability

- Semantic versioning
- Deprecation warnings before removal
- Breaking changes only in major versions

### 4.5 Error Handling

- All errors are typed (no panics in library code)
- Rich error messages with context
- Source location tracking for parse errors

---

## 5. Technical Architecture

### 5.1 Module Structure

```
src/
├── lib.rs                 # Public API and re-exports
├── ast/                   # Expression AST (expand existing)
│   ├── mod.rs
│   ├── expression.rs      # Core expression types
│   ├── equation.rs        # Equation representation
│   ├── matrix.rs          # Matrix expressions
│   └── pattern.rs         # Pattern matching
├── parser/                # LaTeX and text parsing
│   ├── mod.rs
│   ├── latex.rs           # LaTeX parser
│   ├── text.rs            # Plain text parser
│   └── tokenizer.rs       # Common tokenization
├── simplify/              # Expression simplification
│   ├── mod.rs
│   ├── algebraic.rs       # Algebraic simplification
│   ├── trigonometric.rs   # Trig identities
│   └── rules.rs           # Rule-based rewriting
├── calculus/              # Differentiation and integration
│   ├── mod.rs
│   ├── derivative.rs      # Symbolic differentiation
│   ├── integral.rs        # Symbolic integration
│   ├── limit.rs           # Limits and L'Hopital
│   └── ode.rs             # Differential equations
├── solver/                # Equation solving (extend existing)
│   ├── mod.rs
│   ├── algebraic.rs       # Algebraic equations
│   ├── transcendental.rs  # Trig/exp/log equations
│   ├── polynomial.rs      # Polynomial solving
│   └── systems.rs         # System of equations
├── linalg/                # Linear algebra
│   ├── mod.rs
│   ├── matrix.rs          # Matrix operations
│   ├── decomposition.rs   # LU, QR, etc.
│   └── eigen.rs           # Eigenvalue problems
├── numerical/             # Numerical methods (extend existing)
│   ├── mod.rs
│   ├── roots.rs           # Root finding
│   ├── integration.rs     # Numerical integration
│   └── optimization.rs    # Optimization algorithms
├── resolution_path/       # Step-by-step solutions (extend existing)
│   ├── mod.rs
│   ├── step.rs            # Individual steps
│   └── formatter.rs       # Output formatting
├── transforms/            # Coordinate transforms (existing)
├── dimensions/            # Units and dimensions (existing)
└── ffi/                   # Swift bindings (extend existing)
```

### 5.2 Key Abstractions

#### Expression Trait
```rust
pub trait Expression: Clone + Debug + Display {
    fn simplify(&self) -> Self;
    fn substitute(&self, var: &Variable, value: &Self) -> Self;
    fn contains_variable(&self, name: &str) -> bool;
    fn variables(&self) -> HashSet<Variable>;
    fn evaluate(&self, context: &EvalContext) -> Result<Value, EvalError>;
    fn to_latex(&self) -> String;
}
```

#### Differentiable Trait
```rust
pub trait Differentiable: Expression {
    fn derivative(&self, var: &Variable) -> Self;
    fn partial_derivative(&self, var: &Variable) -> Self;
    fn gradient(&self) -> Vec<Self>;
}
```

#### Integrable Trait
```rust
pub trait Integrable: Expression {
    fn indefinite_integral(&self, var: &Variable) -> Option<Self>;
    fn definite_integral(&self, var: &Variable, lower: &Self, upper: &Self)
        -> Option<Self>;
}
```

### 5.3 Dependencies

Existing (keep):
- chumsky: Parser combinators
- num-*: Numeric types
- nalgebra: Matrix operations
- argmin: Optimization
- swift-bridge: FFI

New (add):
- lalrpop or pest: For LaTeX grammar (evaluate vs chumsky)
- regex: Pattern matching support
- unicode-segmentation: LaTeX Unicode handling

### 5.4 Testing Strategy

- Unit tests for every function
- Property-based tests (proptest) for mathematical properties
- Round-trip tests: parse -> render -> parse
- Numerical accuracy tests against known values
- Benchmark suite for performance regression

---

## 6. Implementation Phases

### Phase 1: Parser and Simplification (v0.2.0)
**Duration:** 4-6 weeks

- Complete expression parser (text and basic LaTeX)
- Basic simplification (combine terms, constant folding)
- Extended AST for new expression types
- Unit tests for parser and simplifier

### Phase 2: Symbolic Differentiation (v0.3.0)
**Duration:** 3-4 weeks

- Implement all differentiation rules
- Chain rule and partial derivatives
- Step-by-step solution tracking
- Higher-order derivatives

### Phase 3: Limits and Basic Integration (v0.4.0)
**Duration:** 4-6 weeks

- Limit evaluation with L'Hopital's rule
- Basic integration (power rule, standard functions)
- U-substitution
- Integration by parts

### Phase 4: Advanced Integration and ODEs (v0.5.0)
**Duration:** 4-6 weeks

- Partial fractions
- Trigonometric substitution
- First-order ODEs (separable, linear)
- Initial value problems

### Phase 5: Systems and Linear Algebra (v0.6.0)
**Duration:** 4-6 weeks

- System of linear equations
- Matrix operations
- Determinants and inverses
- Basic eigenvalue computation

### Phase 6: Advanced Features (v0.7.0-0.9.0)
**Duration:** 6-8 weeks

- Complete LaTeX parser
- Advanced equation solving
- Second-order ODEs
- Nonlinear systems
- Performance optimization

### Phase 7: Stabilization (v1.0.0)
**Duration:** 4 weeks

- API stabilization
- Documentation polish
- Performance benchmarks
- Edge case handling

---

## 7. Integration Points

### 7.1 LuaSwift Integration

mathsolver-core will be linked into LuaSwift for use in iOS apps:

```
LuaSwift (Swift Package)
    └── Links to: mathsolver_core (static library)
        └── Exposed via: Swift-Bridge FFI
```

Lua scripts can call Swift functions that invoke mathsolver-core:

```lua
-- Example Lua usage via LuaSwift
local result = Math.differentiate("x^2 + 3*x", "x")
print(result.latex)  -- "2x + 3"
print(result.steps[1])  -- "Apply power rule..."
```

### 7.2 FFI Expansion

New Swift-accessible functions:
- `parse_latex(input: String) -> Expression`
- `differentiate(expr: Expression, var: String) -> DiffResult`
- `integrate(expr: Expression, var: String) -> IntResult`
- `solve_equation(eq: Equation, var: String) -> Solutions`
- `evaluate(expr: Expression, vars: Dictionary) -> Value`

### 7.3 Future Integrations

- Python bindings via PyO3
- WebAssembly for browser use
- C API for general FFI

---

## 8. Open Questions

1. **LaTeX Parser Approach:** Should we use chumsky (consistent with current parser), lalrpop (more formal), or pest (PEG-based)?

2. **Arbitrary Precision:** When should arbitrary precision arithmetic be default vs opt-in?

3. **Special Functions:** Which special functions (Gamma, Bessel, etc.) are needed for target use cases?

4. **Symbolic vs Numeric Boundary:** At what complexity should we switch from symbolic to numerical methods?

5. **Step Verbosity:** What is the right default verbosity for educational applications?

---

## 9. Success Criteria

### 9.1 Functional
- [ ] Parse standard LaTeX mathematical expressions
- [ ] Differentiate polynomial, trigonometric, exponential expressions
- [ ] Integrate basic functions with standard techniques
- [ ] Solve linear and quadratic equations symbolically
- [ ] Compute limits including L'Hopital cases
- [ ] Solve first-order separable ODEs
- [ ] Perform matrix operations and find eigenvalues
- [ ] Generate step-by-step solutions

### 9.2 Performance
- [ ] Parse typical expressions in < 1ms
- [ ] Differentiate degree-10 polynomials in < 10ms
- [ ] Integrate basic functions in < 100ms

### 9.3 Quality
- [ ] Zero memory leaks
- [ ] No panics in library code
- [ ] 80%+ test coverage
- [ ] All clippy lints pass

---

## 10. References

### Mathematical References
- [GiNaC - C++ CAS by physicists](https://www.ginac.de/) - Design inspiration (GPL, cannot use code)
- [mathcore - Rust CAS](https://github.com/Nonanti/mathcore) - MIT reference implementation
- [Wolfram MathWorld](https://mathworld.wolfram.com/) - Mathematical definitions
- [DLMF - Digital Library of Mathematical Functions](https://dlmf.nist.gov/) - Special functions

### Rust Libraries
- [chumsky](https://github.com/zesterer/chumsky) - Parser combinators
- [nalgebra](https://nalgebra.org/) - Linear algebra
- [num crates](https://docs.rs/num/) - Numeric types
- [argmin](https://argmin-rs.org/) - Optimization

### Integration
- [swift-bridge](https://github.com/chinedufn/swift-bridge) - Swift FFI
- [LuaSwift](https://github.com/ChrisGVE/LuaSwift) - Target integration

---

## Appendix A: Sample Expressions

### Differentiation
```
Input: d/dx(x^3 + 2x^2 - 5x + 1)
Output: 3x^2 + 4x - 5

Input: d/dx(sin(x^2))
Output: 2x*cos(x^2)

Input: partial/partial_x(x^2*y + y^3)
Output: 2xy
```

### Integration
```
Input: integral(x^2 dx)
Output: x^3/3 + C

Input: integral_0^pi(sin(x) dx)
Output: 2

Input: integral(x*e^x dx)
Output: (x-1)*e^x + C
```

### Limits
```
Input: lim_{x->0}(sin(x)/x)
Output: 1

Input: lim_{x->0}((e^x - 1)/x)
Output: 1 [L'Hopital applied]
```

### Equation Solving
```
Input: solve(2x^2 - 5x + 2 = 0, x)
Output: x = 2, x = 1/2

Input: solve(e^x = 10, x)
Output: x = ln(10)
```

---

**Document End**
