dslcompile 0.0.1

High-performance symbolic mathematics with final tagless design, egglog optimization, and Rust hot-loading compilation
Documentation
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
//! JIT Compilation Demo
//!
//! This example demonstrates the JIT compilation capabilities of `DSLCompile` using the final tagless approach.
//! It shows how to define mathematical expressions and compile them to native code for high performance.

use dslcompile::backends::cranelift::CraneliftCompiler;
use dslcompile::final_tagless::VariableRegistry;
#[cfg(feature = "cranelift")]
use dslcompile::{ASTEval, ASTMathExpr, Result};

#[cfg(not(feature = "cranelift"))]
use dslcompile::{ASTEval, Result, RustCodeGenerator, RustCompiler};

#[cfg(feature = "cranelift")]
fn main() -> Result<()> {
    println!("🚀 DSLCompile - JIT Compilation Demo (Cranelift)");
    println!("==================================================\n");

    // Demo 1: Simple linear expression
    demo_linear_expression()?;

    // Demo 2: Quadratic polynomial
    demo_quadratic_polynomial()?;

    // Demo 3: Complex mathematical expression
    demo_complex_expression()?;

    // Demo 4: Performance comparison
    demo_performance_comparison()?;

    // Demo 5: Two-variable JIT compilation
    demo_two_variables()?;

    // Demo 6: Multi-variable JIT compilation
    demo_multi_variables()?;

    // Demo 7: Maximum variables (6 variables)
    demo_max_variables()?;

    Ok(())
}

#[cfg(not(feature = "cranelift"))]
fn main() -> Result<()> {
    println!("🚀 DSLCompile - JIT Compilation Demo (Rust Backend)");
    println!("====================================================\n");

    // Demo 1: Simple linear expression
    demo_linear_expression_rust()?;

    // Demo 2: Quadratic polynomial
    demo_quadratic_polynomial_rust()?;

    // Demo 3: Complex mathematical expression
    demo_complex_expression_rust()?;

    println!("✅ Rust backend demos completed!");
    println!("Note: Additional demos require the cranelift feature.");

    Ok(())
}

/// Demo 1: Simple linear expression (2x + 3)
#[cfg(feature = "cranelift")]
fn demo_linear_expression() -> Result<()> {
    println!("📊 Demo 1: Linear Expression (2x + 3)");
    println!("--------------------------------------");

    // Define the expression using index-based variables
    let expr = ASTEval::add(
        ASTEval::mul(ASTEval::constant(2.0), ASTEval::var(0)),
        ASTEval::constant(3.0),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_values = [0.0, 1.0, 2.0, 5.0, -1.0];
    println!("Testing compiled function:");
    for x in test_values {
        let result = jit_func.call(&[x])?;
        let expected = 2.0 * x + 3.0;
        println!("f({x}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 1: Simple linear expression (2x + 3) - Rust backend
#[cfg(not(feature = "cranelift"))]
fn demo_linear_expression_rust() -> Result<()> {
    println!("📊 Demo 1: Linear Expression (2x + 3)");
    println!("--------------------------------------");

    // Define the expression using index-based variables
    let expr = ASTEval::add(
        ASTEval::mul(ASTEval::constant(2.0), ASTEval::var(0)),
        ASTEval::constant(3.0),
    );

    // Generate and compile Rust code
    let codegen = RustCodeGenerator::new();
    let rust_code = codegen.generate_function(&expr, "linear_func")?;

    let compiler = RustCompiler::new();
    let compiled_func = compiler.compile_and_load(&rust_code, "linear_func")?;

    // Test the compiled function
    let test_values = [0.0, 1.0, 2.0, 5.0, -1.0];
    println!("Testing compiled function:");
    for x in test_values {
        let result = compiled_func.call(x)?;
        let expected = 2.0 * x + 3.0;
        println!("f({x}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!(
        "Code size: {} bytes",
        compiled_func.metadata().code_size_bytes
    );
    println!(
        "Compilation time: {} μs",
        compiled_func.metadata().compile_time_us
    );

    Ok(())
}

/// Demo 2: Quadratic polynomial (x² + 2x + 1)
#[cfg(feature = "cranelift")]
fn demo_quadratic_polynomial() -> Result<()> {
    println!("📊 Demo 2: Quadratic Polynomial (x² + 2x + 1)");
    println!("----------------------------------------------");

    // Define the quadratic expression using index-based variables
    let x = ASTEval::var(0);
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::pow(x.clone(), ASTEval::constant(2.0)),
            ASTEval::mul(ASTEval::constant(2.0), x),
        ),
        ASTEval::constant(1.0),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_values = [0.0, 1.0, 2.0, -1.0, 3.0];
    println!("Testing compiled quadratic function:");
    for x in test_values {
        let result = jit_func.call(&[x])?;
        let expected = x * x + 2.0 * x + 1.0;
        println!("f({x}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 2: Quadratic polynomial (x² + 2x + 1) - Rust backend
#[cfg(not(feature = "cranelift"))]
fn demo_quadratic_polynomial_rust() -> Result<()> {
    println!("📊 Demo 2: Quadratic Polynomial (x² + 2x + 1)");
    println!("----------------------------------------------");

    // Define the quadratic expression using index-based variables
    let x = ASTEval::var(0);
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::pow(x.clone(), ASTEval::constant(2.0)),
            ASTEval::mul(ASTEval::constant(2.0), x),
        ),
        ASTEval::constant(1.0),
    );

    // Generate and compile Rust code
    let codegen = RustCodeGenerator::new();
    let rust_code = codegen.generate_function(&expr, "quadratic_func")?;

    let compiler = RustCompiler::new();
    let compiled_func = compiler.compile_and_load(&rust_code, "quadratic_func")?;

    // Test the compiled function
    let test_values = [0.0, 1.0, 2.0, -1.0, 3.0];
    println!("Testing compiled quadratic function:");
    for x in test_values {
        let result = compiled_func.call(x)?;
        let expected = x * x + 2.0 * x + 1.0;
        println!("f({x}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!(
        "Code size: {} bytes",
        compiled_func.metadata().code_size_bytes
    );
    println!(
        "Compilation time: {} μs",
        compiled_func.metadata().compile_time_us
    );

    Ok(())
}

/// Demo 3: Complex mathematical expression with transcendental functions
#[cfg(feature = "cranelift")]
fn demo_complex_expression() -> Result<()> {
    println!("📊 Demo 3: Complex Expression (x² + sin(x) + sqrt(x))");
    println!("----------------------------------------------------");

    // Define a complex expression: x² + sin(x) + sqrt(x)
    let x = ASTEval::var(0);
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::pow(x.clone(), ASTEval::constant(2.0)),
            ASTEval::sin(x.clone()),
        ),
        ASTEval::sqrt(x),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_values = [1.0, 2.0, 4.0, 9.0];
    println!("Testing compiled complex function:");
    for x in test_values {
        let result = jit_func.call(&[x])?;
        let expected: f64 = x * x + x.sin() + x.sqrt();
        println!("f({x}) = {result}, expected = {expected}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 3: Complex mathematical expression with transcendental functions - Rust backend
#[cfg(not(feature = "cranelift"))]
fn demo_complex_expression_rust() -> Result<()> {
    println!("📊 Demo 3: Complex Expression (x² + sin(x) + sqrt(x))");
    println!("----------------------------------------------------");

    // Define a complex expression: x² + sin(x) + sqrt(x)
    let x = ASTEval::var(0);
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::pow(x.clone(), ASTEval::constant(2.0)),
            ASTEval::sin(x.clone()),
        ),
        ASTEval::sqrt(x),
    );

    // Generate and compile Rust code
    let codegen = RustCodeGenerator::new();
    let rust_code = codegen.generate_function(&expr, "complex_func")?;

    let compiler = RustCompiler::new();
    let compiled_func = compiler.compile_and_load(&rust_code, "complex_func")?;

    // Test the compiled function
    let test_values = [1.0, 2.0, 4.0, 9.0];
    println!("Testing compiled complex function:");
    for x in test_values {
        let result = compiled_func.call(x)?;
        let expected: f64 = x * x + x.sin() + x.sqrt();
        println!("f({x}) = {result}, expected = {expected}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!(
        "Code size: {} bytes",
        compiled_func.metadata().code_size_bytes
    );
    println!(
        "Compilation time: {} μs",
        compiled_func.metadata().compile_time_us
    );

    Ok(())
}

/// Demo 4: Performance comparison between direct evaluation and JIT
#[cfg(feature = "cranelift")]
fn demo_performance_comparison() -> Result<()> {
    println!("📊 Demo 4: Performance Comparison");
    println!("----------------------------------");

    // Define a moderately complex polynomial: 3x³ - 2x² + x - 5
    let x = ASTEval::var(0);
    let expr = ASTEval::sub(
        ASTEval::add(
            ASTEval::sub(
                ASTEval::mul(
                    ASTEval::constant(3.0),
                    ASTEval::pow(x.clone(), ASTEval::constant(3.0)),
                ),
                ASTEval::mul(
                    ASTEval::constant(2.0),
                    ASTEval::pow(x.clone(), ASTEval::constant(2.0)),
                ),
            ),
            x,
        ),
        ASTEval::constant(5.0),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Performance test parameters
    let test_value = 2.5;
    let iterations = 1_000_000;

    // Test JIT performance
    let start = std::time::Instant::now();
    let mut jit_result = 0.0;
    for _ in 0..iterations {
        jit_result = jit_func.call(&[test_value])?;
    }
    let jit_time = start.elapsed();

    // Test native Rust performance (for comparison)
    let start = std::time::Instant::now();
    let mut native_result = 0.0;
    for _ in 0..iterations {
        let x = test_value;
        native_result = 3.0 * x * x * x - 2.0 * x * x + x - 5.0;
    }
    let native_time = start.elapsed();

    println!("Performance comparison ({iterations} iterations):");
    println!(
        "  JIT compiled:  {:.2?} ({:.1} ns/call)",
        jit_time,
        jit_time.as_nanos() as f64 / f64::from(iterations)
    );
    println!(
        "  Native Rust:   {:.2?} ({:.1} ns/call)",
        native_time,
        native_time.as_nanos() as f64 / f64::from(iterations)
    );

    let speedup = native_time.as_nanos() as f64 / jit_time.as_nanos() as f64;
    if speedup > 1.0 {
        println!("  🚀 JIT is {speedup:.1}x faster than native!");
    } else {
        println!("  ⚠️  Native is {:.1}x faster than JIT", 1.0 / speedup);
    }

    // Verify results are consistent
    assert!((jit_result - native_result).abs() < 1e-10);
    println!("✅ Results are consistent between JIT and native\n");

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 5: Two-variable JIT compilation
#[cfg(feature = "cranelift")]
fn demo_two_variables() -> Result<()> {
    println!("📊 Demo 5: Two-Variable Expression (x² + y²)");
    println!("--------------------------------------------");

    // Define a two-variable expression: x² + y²
    let x = ASTEval::var(0);
    let y = ASTEval::var(1);
    let expr = ASTEval::add(
        ASTEval::pow(x, ASTEval::constant(2.0)),
        ASTEval::pow(y, ASTEval::constant(2.0)),
    );

    // Compile for two variables
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_cases = [(1.0, 1.0), (2.0, 3.0), (-1.0, 2.0), (0.0, 5.0)];
    println!("Testing compiled two-variable function:");
    for (x, y) in test_cases {
        let result = jit_func.call(&[x, y])?;
        let expected = x * x + y * y;
        println!("f({x}, {y}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 6: Multi-variable JIT compilation
#[cfg(feature = "cranelift")]
fn demo_multi_variables() -> Result<()> {
    println!("📊 Demo 6: Multiple Variables (x*y + y*z + z*x)");
    println!("-----------------------------------------------");

    // Define a three-variable expression: x*y + y*z + z*x
    let x = ASTEval::var(0);
    let y = ASTEval::var(1);
    let z = ASTEval::var(2);
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::mul(x.clone(), y.clone()),
            ASTEval::mul(y, z.clone()),
        ),
        ASTEval::mul(z, x),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_triples = [
        (1.0, 2.0, 3.0),
        (2.0, 3.0, 4.0),
        (0.5, 1.0, 1.5),
        (-1.0, 2.0, -3.0),
    ];
    println!("Testing compiled multi-variable function:");
    for (x, y, z) in test_triples {
        let result = jit_func.call(&[x, y, z])?;
        let expected = x * y + y * z + z * x;
        println!("f({x}, {y}, {z}) = {result}");
        assert!((result - expected).abs() < 1e-10);
    }

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );

    Ok(())
}

/// Demo 7: Maximum variables (6 variables)
#[cfg(feature = "cranelift")]
fn demo_max_variables() -> Result<()> {
    println!("📊 Demo 7: Maximum Variables (x₁ + x₂ + x₃ + x₄ + x₅ + x₆)");
    println!("----------------------------------------------------------");

    // Define a six-variable expression: sum of all variables
    let expr = ASTEval::add(
        ASTEval::add(
            ASTEval::add(
                ASTEval::add(
                    ASTEval::add(ASTEval::var(0), ASTEval::var(1)),
                    ASTEval::var(2),
                ),
                ASTEval::var(3),
            ),
            ASTEval::var(4),
        ),
        ASTEval::var(5),
    );

    // Compile to native code
    let mut compiler = CraneliftCompiler::new_default()?;
    let registry = VariableRegistry::new();
    let jit_func = compiler.compile_expression(&expr, &registry)?;

    // Test the compiled function
    let test_values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
    let result = jit_func.call(&test_values)?;
    println!("f({test_values:?}) = {result}");

    // Verify correctness
    let jit_result = jit_func.call(&test_values)?;
    let native_result = test_values.iter().sum::<f64>();
    assert!((jit_result - native_result).abs() < 1e-10);

    println!("\n📊 Compilation Statistics:");
    println!("Expression complexity: {} operations", jit_func.metadata().expression_complexity);
    println!(
        "Compilation time: {:.2}ms",
        jit_func.metadata().compilation_time_ms
    );
    println!("🏁 Maximum variable demo completed!\n");

    Ok(())
}