lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Numeric primitives integration with the R7RS-large numeric library
//!
//! Provides primitive functions that integrate the advanced numeric system
//! with the Lambdust runtime environment.

use crate::diagnostics::{Result, Error, Span};
use crate::eval::Value;
use crate::ast::Literal;
use super::{NumericValue, tower, functions, constants};

/// Converts a Value to NumericValue if possible
pub fn value_to_numeric(value: &Value) -> Result<NumericValue> {
    match value {
        Value::Literal(literal) => {
            NumericValue::from_literal(literal)
                .ok_or_else(|| Box::new(Error::type_error("Expected numeric value", Span::default())))
        }
        _ => Err(Box::new(Error::type_error("Expected numeric value", Span::default()))),
    }
}

/// Converts NumericValue back to Value
pub fn numeric_to_value(numeric: &NumericValue) -> Value {
    Value::Literal(numeric.to_literal())
}

/// Helper to extract numeric values from argument list
pub fn extract_numeric_args(args: &[Value]) -> Result<Vec<NumericValue>> {
    args.iter()
        .map(value_to_numeric)
        .collect()
}

/// Helper to extract exactly N numeric arguments
pub fn extract_n_numeric_args<const N: usize>(args: &[Value]) -> Result<[NumericValue; N]> {
    if args.len() != N {
        return Err(Box::new(Error::arity_error("extract_n_numeric_args", N, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    numeric_args.try_into()
        .map_err(|_| Box::new(Error::internal_error("Failed to convert to fixed-size array")))
}

// ============= BASIC ARITHMETIC PRIMITIVES =============

/// Addition with automatic type promotion
pub fn primitive_add(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Ok(numeric_to_value(&NumericValue::integer(0)));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    let result = numeric_args.iter()
        .skip(1)
        .fold(numeric_args[0].clone(), |acc, arg| tower::add(&acc, arg));
    
    Ok(numeric_to_value(&result))
}

/// Subtraction with automatic type promotion
pub fn primitive_subtract(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(Error::arity_error("subtract", 1, 0)));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let result = if args.len() == 1 {
        // Unary minus
        tower::negate(&numeric_args[0])
    } else {
        // Binary subtraction
        numeric_args.iter()
            .skip(1)
            .fold(numeric_args[0].clone(), |acc, arg| tower::subtract(&acc, arg))
    };
    
    Ok(numeric_to_value(&result))
}

/// Multiplication with automatic type promotion
pub fn primitive_multiply(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Ok(numeric_to_value(&NumericValue::integer(1)));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    let result = numeric_args.iter()
        .skip(1)
        .fold(numeric_args[0].clone(), |acc, arg| tower::multiply(&acc, arg));
    
    Ok(numeric_to_value(&result))
}

/// Division with automatic type promotion
pub fn primitive_divide(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(Error::arity_error("divide", 1, 0)));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let result = if args.len() == 1 {
        // Reciprocal
        tower::divide(&NumericValue::integer(1), &numeric_args[0])
            .map_err(|msg| Error::runtime_error(&msg, Some(Span::default())))?
    } else {
        // Binary division
        let mut result = numeric_args[0].clone();
        for arg in &numeric_args[1..] {
            result = tower::divide(&result, arg)
                .map_err(|msg| Error::runtime_error(&msg, Some(Span::default())))?;
        }
        result
    };
    
    Ok(numeric_to_value(&result))
}

// ============= COMPARISON PRIMITIVES =============

/// Numeric equality
pub fn primitive_numeric_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::arity_error("numeric-function", 2, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    let first = &numeric_args[0];
    
    let all_equal = numeric_args.iter().skip(1).all(|arg| {
        matches!(tower::compare(first, arg), Some(std::cmp::Ordering::Equal))
    });
    
    Ok(Value::boolean(all_equal))
}

/// Numeric less than
pub fn primitive_less_than(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::arity_error("numeric-function", 2, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let monotonic = numeric_args.windows(2).all(|pair| {
        matches!(tower::compare(&pair[0], &pair[1]), Some(std::cmp::Ordering::Less))
    });
    
    Ok(Value::boolean(monotonic))
}

/// Numeric greater than
pub fn primitive_greater_than(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::arity_error("numeric-function", 2, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let monotonic = numeric_args.windows(2).all(|pair| {
        matches!(tower::compare(&pair[0], &pair[1]), Some(std::cmp::Ordering::Greater))
    });
    
    Ok(Value::boolean(monotonic))
}

/// Numeric less than or equal
pub fn primitive_less_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::arity_error("numeric-function", 2, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let monotonic = numeric_args.windows(2).all(|pair| {
        matches!(tower::compare(&pair[0], &pair[1]), 
               Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal))
    });
    
    Ok(Value::boolean(monotonic))
}

/// Numeric greater than or equal
pub fn primitive_greater_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::arity_error("numeric-function", 2, args.len())));
    }
    
    let numeric_args = extract_numeric_args(args)?;
    
    let monotonic = numeric_args.windows(2).all(|pair| {
        matches!(tower::compare(&pair[0], &pair[1]), 
               Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal))
    });
    
    Ok(Value::boolean(monotonic))
}

// ============= ADVANCED MATHEMATICAL FUNCTIONS =============

/// Exponential function
pub fn primitive_exp(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(r.exp()),
        NumericValue::Complex(c) => NumericValue::complex(c.exp().real, c.exp().imaginary),
        _ => {
            // Promote to real/complex and compute
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(r.exp())
            } else {
                return Err(Box::new(Error::type_error("Cannot compute exp of this type", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Natural logarithm
pub fn primitive_log(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) if r > 0.0 => NumericValue::real(r.ln()),
        NumericValue::Complex(c) => {
            let log_c = c.ln();
            NumericValue::complex(log_c.real, log_c.imaginary)
        }
        _ => {
            // For negative reals or other types, promote to complex
            let promoted = tower::promote_to_complex(&arg);
            if let NumericValue::Complex(c) = promoted {
                let log_c = c.ln();
                NumericValue::complex(log_c.real, log_c.imaginary)
            } else {
                return Err(Box::new(Error::type_error("Cannot compute log of this type", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Square root
pub fn primitive_sqrt(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    let result = tower::sqrt(&arg);
    Ok(numeric_to_value(&result))
}

/// Power function
pub fn primitive_expt(args: &[Value]) -> Result<Value> {
    let [base, exponent] = extract_n_numeric_args(args)?;
    let result = tower::power(&base, &exponent);
    Ok(numeric_to_value(&result))
}

/// Sine function
pub fn primitive_sin(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(r.sin()),
        NumericValue::Complex(c) => {
            let sin_c = c.sin();
            NumericValue::complex(sin_c.real, sin_c.imaginary)
        }
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(r.sin())
            } else {
                return Err(Box::new(Error::type_error("Cannot compute sin of this type", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Cosine function
pub fn primitive_cos(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(r.cos()),
        NumericValue::Complex(c) => {
            let cos_c = c.cos();
            NumericValue::complex(cos_c.real, cos_c.imaginary)
        }
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(r.cos())
            } else {
                return Err(Box::new(Error::type_error("Cannot compute cos of this type", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Tangent function
pub fn primitive_tan(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(r.tan()),
        NumericValue::Complex(c) => {
            let tan_c = c.tan();
            NumericValue::complex(tan_c.real, tan_c.imaginary)
        }
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(r.tan())
            } else {
                return Err(Box::new(Error::type_error("Cannot compute tan of this type", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

// ============= SPECIAL FUNCTIONS =============

/// Gamma function
pub fn primitive_gamma(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(functions::gamma(r)),
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(functions::gamma(r))
            } else {
                return Err(Box::new(Error::type_error("Gamma function requires real argument", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Error function
pub fn primitive_erf(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(functions::erf(r)),
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(functions::erf(r))
            } else {
                return Err(Box::new(Error::type_error("Error function requires real argument", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

/// Bessel function J0
pub fn primitive_bessel_j0(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    
    let result = match arg {
        NumericValue::Real(r) => NumericValue::real(functions::bessel_j0(r)),
        _ => {
            let promoted = tower::promote_to_real(&arg);
            if let NumericValue::Real(r) = promoted {
                NumericValue::real(functions::bessel_j0(r))
            } else {
                return Err(Box::new(Error::type_error("Bessel function requires real argument", Span::default())));
            }
        }
    };
    
    Ok(numeric_to_value(&result))
}

// ============= TYPE PREDICATES =============

/// Check if value is a number
pub fn primitive_number_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_number = matches!(&args[0], Value::Literal(lit) if lit.is_number());
    Ok(Value::boolean(is_number))
}

/// Check if value is exact
pub fn primitive_exact_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_exact = match value_to_numeric(&args[0]) {
        Ok(num) => num.is_exact(),
        Err(_) => false,
    };
    
    Ok(Value::boolean(is_exact))
}

/// Check if value is inexact
pub fn primitive_inexact_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_inexact = match value_to_numeric(&args[0]) {
        Ok(num) => num.is_inexact(),
        Err(_) => false,
    };
    
    Ok(Value::boolean(is_inexact))
}

/// Check if value is integer
pub fn primitive_integer_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_integer = match value_to_numeric(&args[0]) {
        Ok(num) => num.is_integer(),
        Err(_) => false,
    };
    
    Ok(Value::boolean(is_integer))
}

/// Check if value is real
pub fn primitive_real_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_real = match value_to_numeric(&args[0]) {
        Ok(num) => num.is_real(),
        Err(_) => false,
    };
    
    Ok(Value::boolean(is_real))
}

/// Check if value is complex
pub fn primitive_complex_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let is_complex = value_to_numeric(&args[0]).is_ok();
    Ok(Value::boolean(is_complex))
}

// ============= EXACTNESS CONVERSION =============

/// Convert to exact representation
pub fn primitive_exact(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    let result = tower::make_exact(&arg);
    Ok(numeric_to_value(&result))
}

/// Convert to inexact representation
pub fn primitive_inexact(args: &[Value]) -> Result<Value> {
    let [arg] = extract_n_numeric_args(args)?;
    let result = tower::make_inexact(&arg);
    Ok(numeric_to_value(&result))
}

// ============= CONSTANTS =============

/// Get mathematical or physical constant
pub fn primitive_constant(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::arity_error("numeric-function", 1, args.len())));
    }
    
    let name = match &args[0] {
        Value::Literal(Literal::String(s)) => s.clone(),
        Value::Symbol(id) => {
            // Convert symbol to string for lookup
            if let Some(name) = crate::utils::symbol_name(*id) {
                name
            } else {
                return Err(Box::new(Error::type_error("Unknown symbol", Span::default())));
            }
        }
        _ => return Err(Box::new(Error::type_error("Expected string or symbol", Span::default()))),
    };
    
    if let Some(constant) = constants::get_constant(&name) {
        Ok(numeric_to_value(&constant))
    } else {
        Err(Box::new(Error::runtime_error(format!("Unknown constant: {name}"), Some(Span::default()))))
    }
}

/// List available constants
pub fn primitive_list_constants(args: &[Value]) -> Result<Value> {
    if !args.is_empty() {
        return Err(Box::new(Error::arity_error("numeric-function", 0, args.len())));
    }
    
    let constant_names = constants::list_constants();
    let values: Vec<Value> = constant_names.into_iter()
        .map(Value::string)
        .collect();
    
    Ok(Value::list(values))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_arithmetic_primitives() {
        let args = vec![
            Value::Literal(Literal::Number(3.0)),
            Value::Literal(Literal::Number(4.0)),
        ];
        
        let result = primitive_add(&args).unwrap();
        assert_eq!(result.as_number().unwrap(), 7.0);
        
        let result = primitive_multiply(&args).unwrap();
        assert_eq!(result.as_number().unwrap(), 12.0);
    }

    #[test]
    fn test_comparison_primitives() {
        let args = vec![
            Value::Literal(Literal::Number(3.0)),
            Value::Literal(Literal::Number(4.0)),
            Value::Literal(Literal::Number(5.0)),
        ];
        
        let result = primitive_less_than(&args).unwrap();
        assert_eq!(result, Value::boolean(true));
        
        let result = primitive_greater_than(&args).unwrap();
        assert_eq!(result, Value::boolean(false));
    }

    #[test]
    fn test_type_predicates() {
        let number_val = Value::Literal(Literal::Number(std::f64::consts::PI));
        let string_val = Value::Literal(Literal::String("hello".to_string()));
        
        let result = primitive_number_p(&[number_val.clone()]).unwrap();
        assert_eq!(result, Value::boolean(true));
        
        let result = primitive_number_p(&[string_val]).unwrap();
        assert_eq!(result, Value::boolean(false));
        
        let result = primitive_inexact_p(&[number_val]).unwrap();
        assert_eq!(result, Value::boolean(true));
    }

    #[test]
    fn test_mathematical_functions() {
        let arg = Value::Literal(Literal::Number(1.0));
        
        let result = primitive_sin(&[arg.clone()]).unwrap();
        let sin_1 = result.as_number().unwrap();
        assert!((sin_1 - 1.0_f64.sin()).abs() < 1e-10);
        
        let result = primitive_exp(&[arg]).unwrap();
        let exp_1 = result.as_number().unwrap();
        assert!((exp_1 - std::f64::consts::E).abs() < 1e-10);
    }

    #[test]
    fn test_constant_lookup() {
        let pi_arg = Value::string("pi");
        let result = primitive_constant(&[pi_arg]).unwrap();
        let pi_val = result.as_number().unwrap();
        assert!((pi_val - std::f64::consts::PI).abs() < 1e-10);
        
        let list_result = primitive_list_constants(&[]).unwrap();
        assert!(list_result.is_list());
    }
}