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

**Document ID:** 20251231-1546_project_0.2.0_PRD_symbolic-cas-expansion-v2
**Created:** 2025-12-31
**Revised:** 2025-12-31 (v2 - incorporates scope corrections)
**Author:** Claude Code (Opus 4.5)
**Status:** Ready 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 (linear, quadratic, arbitrary, transcendental, systems)
- Performs symbolic differentiation and integration
- Handles limits, series expansions, differential equations, and linear algebra
- Generates detailed step-by-step solution explanations optimized for manual computation
- Evaluates expressions numerically with configurable precision and error tracking

### Primary Use Case
**Educational application teaching manual computation techniques.** The library generates computation steps that may be executed by hand or on limited-precision tools, requiring:
- Minimization of additive operations (error-prone when done manually)
- Optimization of multiplicative chains
- Use of approximations and scaled forms where appropriate
- Full derivation of special function values (not just lookup tables)

### 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 (square, cube, nth)
2. **Trigonometry:** sin, cos, tan, cot, sec, csc with inverses (degrees supported)
3. **Hyperbolic Functions:** sinh, cosh, tanh with inverses
4. **Complex Numbers:** Full complex arithmetic, Euler's formula, roots of unity
5. **Differentiation:** All rules, partial derivatives, higher-order
6. **Limits:** Including L'Hopital's rule for indeterminate forms
7. **Integration:** Definite and indefinite, all standard techniques
8. **Series Expansions:** Taylor, Maclaurin, Laurent, Fourier, asymptotic
9. **Equation Solving:** Linear, quadratic, arbitrary, transcendental, implicit
10. **Systems of Equations:** Linear and nonlinear systems
11. **Differential Equations:** First and second-order ODEs
12. **Linear Algebra:** Matrix operations, determinants, eigenvalues/eigenvectors
13. **Special Functions:** Gamma, Bessel, etc. with derivation steps

### 2.3 Library Development Strategy

**Approach: Hybrid Reference Implementation**

| Source | License | Usage |
|--------|---------|-------|
| **mathcore** | MIT | Study Rust idioms, AST patterns, basic algorithms |
| **GiNaC** | GPL | Study algorithms and documentation only (no code reuse) |
| **Academic literature** | N/A | Mathematical foundations and numerical methods |

**Reference document:** `.taskmaster/docs/20251231-1546_CAS_algorithm_reference.md`

### 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)

**Additional principle:** Optimize step generation for manual computation by minimizing additive operations and maximizing chainable multiplicative operations.

---

## 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}

**Parser Choice:** Continue with **chumsky** (already integrated, excellent error messages, active maintenance)

**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.)
- Series representations

#### 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 Series Expansions

**Priority:** P0 (Critical) - Essential for numerical evaluation

#### 3.3.1 Taylor/Maclaurin Series
- Compute series expansion to arbitrary order
- Center at any point (Taylor) or at 0 (Maclaurin)
- Track remainder/error terms

#### 3.3.2 Laurent Series
- Handle functions with poles
- Include negative power terms
- Identify singularities

#### 3.3.3 Fourier Series
- Periodic function decomposition
- Compute coefficients symbolically
- Truncation to finite terms

#### 3.3.4 Asymptotic Expansions
- Behavior as variable approaches infinity
- Big-O notation support

#### 3.3.5 Series Arithmetic
- Addition, multiplication of series
- Series inversion (1/S)
- Series composition

### 3.4 Symbolic Differentiation

**Priority:** P0 (Critical)

#### 3.4.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.4.2 Chain Rule
- d/dx(f(g(x))) = f'(g(x)) * g'(x)
- Recursive application for nested functions

#### 3.4.3 Transcendental Functions
- All trigonometric derivatives
- Exponential and logarithmic derivatives
- Inverse trigonometric derivatives
- Hyperbolic function derivatives

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

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

### 3.5 Limits

**Priority:** P1 (High)

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

#### 3.5.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.5.3 Common Limits
- lim_{x -> 0} sin(x)/x = 1
- lim_{x -> infinity} (1 + 1/x)^x = e
- Pre-computed standard limits table

### 3.6 Symbolic Integration

**Priority:** P1 (High)

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

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

#### 3.6.3 Integration Techniques
- Substitution (u-substitution)
- Integration by parts (LIATE heuristic)
- Partial fractions (for rational functions)
- Trigonometric substitution

#### 3.6.4 Definite Integrals
- Apply limits of integration
- Handle improper integrals
- Numerical fallback when symbolic fails

### 3.7 Equation Solving

**Priority:** P0 (Critical)

#### 3.7.1 Single Variable Equations
- Linear: ax + b = c
- Quadratic: ax^2 + bx + c = 0 (discriminant handling)
- Cubic: Cardano's formula with casus irreducibilis handling
- Quartic: Ferrari's method
- Higher degree: rational root theorem, numerical fallback
- Transcendental: sin(x) = c, e^x = c, etc.
- Arbitrary equations: general algebraic manipulation

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

#### 3.7.3 Inequality Solving
- Linear inequalities
- Quadratic inequalities
- System of inequalities
- Interval notation output

### 3.8 Differential Equations

**Priority:** P2 (Medium)

#### 3.8.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.8.2 Second-Order ODEs
- Constant coefficient: y'' + ay' + by = 0
- Non-homogeneous with method of undetermined coefficients
- Reduction of order

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

### 3.9 Systems of Equations

**Priority:** P1 (High)

#### 3.9.1 Linear Systems
- Gaussian elimination with partial pivoting
- LU decomposition
- Cramer's rule for small systems
- Handle over/under-determined systems
- Parameterized solutions

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

### 3.10 Linear Algebra

**Priority:** P2 (Medium)

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

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

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

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

### 3.11 Special Functions

**Priority:** P1 (High) - Must include derivation steps

#### 3.11.1 Gamma Function
- Definition via integral or series
- Step-by-step computation for specific values
- Reflection formula, duplication formula

#### 3.11.2 Bessel Functions
- Series expansion derivation
- Recurrence relations
- Asymptotic forms

#### 3.11.3 Other Special Functions (as needed)
- Error function (erf)
- Beta function
- Legendre polynomials

**Key Requirement:** All special function values must be derivable step-by-step, not just looked up from tables.

### 3.12 Step-by-Step Solutions

**Priority:** P0 (Critical)

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

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

#### 3.12.3 Verbosity
- **Default: ALL DETAILS** - Every algebraic manipulation recorded
- Steps will be post-processed by external module for presentation
- No filtering at library level

### 3.13 Numerical Evaluation

**Priority:** P0 (Critical)

#### 3.13.1 Precision Modes
1. **System Standard:** Use native f64 precision
2. **Target Precision:** User-specified significant digits (e.g., 4 mantissa digits)
   - Target precision always <= system precision
   - Error accumulates through operation chains
   - Optimal ordering minimizes precision loss

#### 3.13.2 Evaluation Strategy
- Symbolic-first: always attempt symbolic solution
- If symbolic impossible: indicate applicable numerical method(s)
- Numerical evaluation on demand to specified precision

#### 3.13.3 Output Requirements (Minimal Set)
1. Resolved symbolic equation, OR indication of numerical approach with methodology
2. Numerical result
3. Steps to obtain numerical result to target precision

#### 3.13.4 Output Requirements (Optional, Highly Desirable)
4. Optimal order of operations for step list (minimize steps, maximize precision)
5. Error evaluation/propagation tracking

### 3.14 Operation Ordering Optimization

**Priority:** P1 (High)

#### 3.14.1 Supported Operations (Finite Set)
| Category | Operations |
|----------|------------|
| **Multiplicative** | multiplication, division, inverse |
| **Powers** | square, cube, square root, cubic root |
| **Trigonometric** | sin, cos, tan (degrees), small angle approximations |
| **Logarithmic** | log, ln |
| **Exponential** | exp, scaled variants (e^-x, e^(-0.1x), e^(-0.01x)) |
| **Pythagorean** | sqrt(1-x^2), sqrt(1-(kx)^2) |
| **Additive** | addition, subtraction (minimize - must be numerical) |

#### 3.14.2 Optimization Goals
1. **Minimize additive operations** - Must be performed manually
2. **Maximize multiplicative chains** - Can be accumulated
3. **Use scaled forms** - Better precision in target ranges
4. **Apply approximations** - When within valid error bounds

#### 3.14.3 Configuration
```rust
struct OperationConfig {
    target_precision: u32,  // mantissa significant digits
    use_small_angle_approx: bool,
    small_angle_threshold: f64,  // radians (default ~0.1)

    // Preference weights for optimizer (configurable)
    prefer_multiplication: f64,
    avoid_addition: f64,

    // Scaling preferences for exponentials
    exp_scaling_levels: Vec<f64>,  // e.g., [1.0, 0.1, 0.01]
}
```

#### 3.14.4 Defaults with Override
- Built-in heuristics that "just work" for common cases
- User can supply custom configuration/ruleset
- Configuration not stored in source code (external)

---

## 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 |
| Series expansion (10 terms) | < 50ms |

### 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)
- 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
│   ├── series.rs          # Series representations
│   └── pattern.rs         # Pattern matching
├── parser/                # LaTeX and text parsing (chumsky)
│   ├── 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
│   ├── series.rs          # Series expansions
│   └── 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
│   ├── arbitrary.rs       # Arbitrary equation solving
│   └── systems.rs         # System of equations
├── linalg/                # Linear algebra
│   ├── mod.rs
│   ├── matrix.rs          # Matrix operations
│   ├── decomposition.rs   # LU, QR, etc.
│   └── eigen.rs           # Eigenvalue problems
├── special/               # Special functions
│   ├── mod.rs
│   ├── gamma.rs           # Gamma function
│   ├── bessel.rs          # Bessel functions
│   └── error.rs           # Error function
├── numerical/             # Numerical methods (extend existing)
│   ├── mod.rs
│   ├── roots.rs           # Root finding
│   ├── integration.rs     # Numerical integration
│   ├── precision.rs       # Precision control
│   └── optimization.rs    # Operation ordering optimizer
├── 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>;
}
```

#### SeriesExpansion Trait
```rust
pub trait SeriesExpansion: Expression {
    fn taylor(&self, var: &Variable, center: &Self, order: u32) -> Series;
    fn laurent(&self, var: &Variable, center: &Self, order: u32) -> Series;
    fn asymptotic(&self, var: &Variable, order: u32) -> Series;
}
```

### 5.3 Dependencies

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

New (add):
- proptest: Property-based testing
- regex: Pattern matching support
- unicode-segmentation: LaTeX Unicode handling

**Decision:** Use chumsky for LaTeX parsing (consistency, excellent error messages).

### 5.4 Testing Strategy (TDD Throughout)

**Test-Driven Development is mandatory.** Tests are written concurrently with code, not as a final phase.

For each feature:
1. Write unit test immediately after each logical unit of code
2. Cover edge cases and validation errors (multiple tests per unit)
3. Run tests after atomic changes
4. Amend tests only after first run identifies failures

**Test Categories:**
- Unit tests for every function
- Property-based tests (proptest) for mathematical invariants
  - d/dx(integral(f)) = f
  - Linearity of differentiation
  - Series convergence properties
- Round-trip tests: parse -> render -> parse
- Numerical accuracy tests against known values
- Benchmark suite for performance regression

---

## 6. Implementation Phases

**Note:** Each phase includes comprehensive testing. Tests are not a separate phase.

### Phase 1: Series and Core Infrastructure (v0.2.0)
- Complete expression parser (text and basic LaTeX)
- Series representations (Taylor, Maclaurin, Laurent)
- Series arithmetic (add, multiply, invert)
- Basic simplification (combine terms, constant folding)
- Extended AST for new expression types
- Concurrent unit tests for all features

### Phase 2: Symbolic Differentiation (v0.3.0)
- Implement all differentiation rules
- Chain rule and partial derivatives
- Higher-order derivatives
- Step-by-step solution tracking
- Concurrent unit tests

### Phase 3: Limits and Basic Integration (v0.4.0)
- Limit evaluation with L'Hopital's rule
- Basic integration (power rule, standard functions)
- U-substitution
- Integration by parts
- Concurrent unit tests

### Phase 4: Advanced Integration, Series, ODEs (v0.5.0)
- Partial fractions
- Fourier series
- Asymptotic expansions
- First-order ODEs (separable, linear)
- Initial value problems
- Concurrent unit tests

### Phase 5: Equation Solving and Systems (v0.6.0)
- Cubic and quartic equations
- Arbitrary equation solving
- System of linear equations
- Nonlinear systems
- Concurrent unit tests

### Phase 6: Linear Algebra and Special Functions (v0.7.0-0.8.0)
- Matrix operations
- Determinants and inverses
- Eigenvalue computation
- Gamma function with derivation
- Bessel functions with derivation
- Concurrent unit tests

### Phase 7: Operation Optimization and Precision (v0.9.0)
- Operation ordering optimizer
- Precision tracking and error propagation
- Small angle approximations
- Scaled exponential forms
- Configuration system
- Concurrent unit tests

### Phase 8: Stabilization (v1.0.0)
- API stabilization
- Documentation polish
- Performance benchmarks
- Integration testing
- 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, precision: u32) -> Value`
- `expand_series(expr: Expression, var: String, center: f64, order: u32) -> Series`
- `get_steps(result: ResultHandle) -> Vec<Step>`

### 7.3 Future Integrations

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

---

## 8. Resolved Decisions

| Question | Decision | Rationale |
|----------|----------|-----------|
| LaTeX Parser | chumsky | Already integrated, excellent error messages |
| Precision | System + Target | f64 standard, configurable target (always lower) |
| Special Functions | All with derivation | Educational use case requires showing work |
| Verbosity | All details | External module handles presentation |
| Library Strategy | Hybrid A+B | mathcore (Rust patterns) + GiNaC (algorithms) |

---

## 9. Success Criteria

### 9.1 Functional
- [ ] Parse standard LaTeX mathematical expressions
- [ ] Differentiate polynomial, trigonometric, exponential expressions
- [ ] Integrate basic functions with standard techniques
- [ ] Expand functions into Taylor, Maclaurin, Laurent series
- [ ] Solve linear, quadratic, and arbitrary equations symbolically
- [ ] Solve systems of linear equations
- [ ] Compute limits including L'Hopital cases
- [ ] Solve first-order separable ODEs
- [ ] Perform matrix operations and find eigenvalues
- [ ] Compute special function values with derivation steps
- [ ] Generate detailed step-by-step solutions
- [ ] Optimize operation ordering for precision

### 9.2 Performance
- [ ] Parse typical expressions in < 1ms
- [ ] Differentiate degree-10 polynomials in < 10ms
- [ ] Integrate basic functions in < 100ms
- [ ] Expand series (10 terms) in < 50ms

### 9.3 Quality
- [ ] Zero memory leaks
- [ ] No panics in library code
- [ ] 80%+ test coverage
- [ ] All clippy lints pass
- [ ] TDD practiced throughout (tests concurrent with code)

---

## 10. References

### Algorithm Reference
- `.taskmaster/docs/20251231-1546_CAS_algorithm_reference.md` - Extracted algorithms from mathcore and GiNaC

### Mathematical References
- [GiNaC - C++ CAS by physicists](https://www.ginac.de/) - Design inspiration (GPL, algorithms only)
- [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
- [proptest](https://github.com/proptest-rs/proptest) - Property-based testing

### 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)

Input: solve(x^3 - 1 = 0, x)
Output: x = 1, x = (-1 + i*sqrt(3))/2, x = (-1 - i*sqrt(3))/2
```

### Series Expansion
```
Input: taylor(sin(x), x, 0, 5)
Output: x - x^3/6 + x^5/120 + O(x^6)

Input: taylor(e^x, x, 0, 4)
Output: 1 + x + x^2/2 + x^3/6 + x^4/24 + O(x^5)
```

---

**Document End**
