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
599
600
601
602
603
604
605
606
607
//! Environment and variable binding implementation.
//!
//! This module provides the environment system for Lambdust, which handles
//! lexical scoping, variable binding, and proper closure semantics.

use super::{Generation, Value};
use crate::diagnostics::{Error, Result};
use std::sync::Arc;
use std::rc::Rc;

/// A lexical environment that maintains variable bindings.
///
/// Environments form a chain through parent pointers, implementing
/// proper lexical scoping. Each environment has a generation number
/// for garbage collection optimization.
pub type Environment = super::value::Environment;

/// Builder for creating environments with standard bindings.
pub struct EnvironmentBuilder {
    environment: Rc<Environment>,
    #[allow(dead_code)]
    generation: Generation,
}

impl EnvironmentBuilder {
    /// Creates a new environment builder.
    pub fn new(generation: Generation) -> Self {
        let env = Rc::new(Environment::new(None, generation));
        Self {
            environment: env,
            generation,
        }
    }

    /// Creates a new environment builder with a parent.
    pub fn with_parent(parent: Rc<Environment>, generation: Generation) -> Self {
        let env = Rc::new(Environment::new(Some(parent), generation));
        Self {
            environment: env,
            generation,
        }
    }

    /// Adds a binding to the environment.
    pub fn bind(self, name: impl Into<String>, value: Value) -> Self {
        self.environment.define(name.into(), value);
        self
    }

    /// Adds a primitive procedure binding.
    pub fn bind_primitive(
        self, 
        name: impl Into<String>, 
        proc: super::value::PrimitiveProcedure
    ) -> Self {
        let value = Value::Primitive(Arc::new(proc));
        self.bind(name, value)
    }

    /// Builds the final environment.
    pub fn build(self) -> Rc<Environment> {
        self.environment
    }
}

/// Gets or creates the global environment.
/// Each thread gets its own copy since Rc<Environment> is not thread-safe.
pub fn global_environment() -> Rc<Environment> {
    thread_local! {
        static GLOBAL_ENV: std::cell::OnceCell<Rc<Environment>> = const { std::cell::OnceCell::new() };
    }
    
    GLOBAL_ENV.with(|cell| {
        cell.get_or_init(create_global_environment).clone()
    })
}

/// Creates the global environment with standard bindings.
fn create_global_environment() -> Rc<Environment> {
    // Start with an empty environment
    let env = Rc::new(Environment::new(None, 0));
    
    // Add basic values first - these are essential and should never fail
    env.define("true".to_owned(), Value::t());
    env.define("false".to_owned(), Value::f());
    env.define("null".to_owned(), Value::Nil);
    
    // Add R7RS-small special forms as identifiers for macro expansion
    // These are needed for macro templates to reference basic syntax
    bind_special_forms_as_identifiers(&env);
    
    // Convert to ThreadSafeEnvironment to use StandardLibrary
    let thread_safe_env = env.to_thread_safe();
    
    // Populate with complete standard library (same as multithreaded runtime)
    // This ensures both single-threaded and multi-threaded paths have identical environments
    let stdlib = crate::stdlib::StandardLibrary::new();
    stdlib.populate_environment(&thread_safe_env);
    
    // Convert back to legacy Environment for single-threaded use
    thread_safe_env.to_legacy()
}

/// Binds R7RS-small special forms as identifiers in the environment.
/// This allows macros to reference basic syntax elements like 'lambda', 'if', etc.
/// These are not callable procedures but syntactic identifiers for macro expansion.
fn bind_special_forms_as_identifiers(env: &Rc<Environment>) {
    use crate::utils::intern_symbol;
    
    // Core special forms required for macro expansion
    let special_forms = [
        "lambda", "if", "define", "set!", "quote", "quasiquote", "unquote", "unquote-splicing",
        "begin", "let", "let*", "letrec", "cond", "case", "and", "or",
        "when", "unless", "do", "delay", "force", "case-lambda",
        "make-promise", "promise-force", // for delay/force implementation
    ];
    
    for &form_name in &special_forms {
        // Create a special syntax value that indicates this is a special form identifier
        let symbol_id = intern_symbol(form_name.to_owned());
        let syntax_value = Value::Symbol(symbol_id);
        env.define(form_name.to_owned(), syntax_value);
    }
    
    // Also bind some essential procedures that macros might need to reference
    // These will be overwritten by actual implementations later if they exist
    env.define("apply".to_owned(), Value::Symbol(intern_symbol("apply".to_owned())));
    env.define("list".to_owned(), Value::Symbol(intern_symbol("list".to_owned())));
    env.define("cons".to_owned(), Value::Symbol(intern_symbol("cons".to_owned())));
    env.define("car".to_owned(), Value::Symbol(intern_symbol("car".to_owned())));
    env.define("cdr".to_owned(), Value::Symbol(intern_symbol("cdr".to_owned())));
    env.define("null?".to_owned(), Value::Symbol(intern_symbol("null?".to_owned())));
    env.define("length".to_owned(), Value::Symbol(intern_symbol("length".to_owned())));
    env.define("error".to_owned(), Value::Symbol(intern_symbol("error".to_owned())));
    env.define("not".to_owned(), Value::Symbol(intern_symbol("not".to_owned())));
    env.define("memv".to_owned(), Value::Symbol(intern_symbol("memv".to_owned())));
}


// ============= PRIMITIVE IMPLEMENTATIONS =============

/// Addition primitive (+).
pub fn primitive_add(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Ok(Value::integer(0));
    }

    let mut result = 0.0;
    for arg in args {
        match arg.as_number() {
            Some(n) => result += n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {arg}"),
                None,
            ))),
        }
    }

    Ok(Value::number(result))
}

/// Subtraction primitive (-).
#[allow(dead_code)]
fn primitive_subtract(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(Error::runtime_error(
            "- requires at least one argument",
            None,
        )));
    }

    if args.len() == 1 {
        // Unary minus
        match args[0].as_number() {
            Some(n) => Ok(Value::number(-n)),
            None => Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", args[0]),
                None,
            ))),
        }
    } else {
        // Binary and n-ary minus
        let mut result = match args[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", args[0]),
                None,
            ))),
        };

        for arg in &args[1..] {
            match arg.as_number() {
                Some(n) => result -= n,
                None => return Err(Box::new(Error::runtime_error(
                    format!("Expected number, got {arg}"),
                    None,
                ))),
            }
        }

        Ok(Value::number(result))
    }
}

/// Multiplication primitive (*).
#[allow(dead_code)]
fn primitive_multiply(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Ok(Value::integer(1));
    }

    let mut result = 1.0;
    for arg in args {
        match arg.as_number() {
            Some(n) => result *= n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {arg}"),
                None,
            ))),
        }
    }

    Ok(Value::number(result))
}

/// Division primitive (/).
#[allow(dead_code)]
fn primitive_divide(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(Error::runtime_error(
            "/ requires at least one argument",
            None,
        )));
    }

    if args.len() == 1 {
        // Reciprocal
        match args[0].as_number() {
            Some(n) => {
                if n == 0.0 {
                    Err(Box::new(Error::runtime_error("Division by zero", None)))
                } else {
                    Ok(Value::number(1.0 / n))
                }
            }
            None => Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", args[0]),
                None,
            ))),
        }
    } else {
        // Binary and n-ary division
        let mut result = match args[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", args[0]),
                None,
            ))),
        };

        for arg in &args[1..] {
            match arg.as_number() {
                Some(n) => {
                    if n == 0.0 {
                        return Err(Box::new(Error::runtime_error("Division by zero", None)));
                    }
                    result /= n;
                }
                None => return Err(Box::new(Error::runtime_error(
                    format!("Expected number, got {arg}"),
                    None,
                ))),
            }
        }

        Ok(Value::number(result))
    }
}

/// Numeric equality primitive (=).
#[allow(dead_code)]
fn primitive_numeric_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::runtime_error(
            "= requires at least two arguments",
            None,
        )));
    }

    let first = match args[0].as_number() {
        Some(n) => n,
        None => return Err(Box::new(Error::runtime_error(
            format!("Expected number, got {}", args[0]),
            None,
        ))),
    };

    for arg in &args[1..] {
        match arg.as_number() {
            Some(n) => {
                if (first - n).abs() > f64::EPSILON {
                    return Ok(Value::f());
                }
            }
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {arg}"),
                None,
            ))),
        }
    }

    Ok(Value::t())
}

/// Less than primitive (<).
#[allow(dead_code)]
fn primitive_less_than(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::runtime_error(
            "< requires at least two arguments",
            None,
        )));
    }

    for window in args.windows(2) {
        let a = match window[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[0]),
                None,
            ))),
        };

        let b = match window[1].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[1]),
                None,
            ))),
        };

        if a >= b {
            return Ok(Value::f());
        }
    }

    Ok(Value::t())
}

/// Greater than primitive (>).
#[allow(dead_code)]
fn primitive_greater_than(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::runtime_error(
            "> requires at least two arguments",
            None,
        )));
    }

    for window in args.windows(2) {
        let a = match window[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[0]),
                None,
            ))),
        };

        let b = match window[1].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[1]),
                None,
            ))),
        };

        if a <= b {
            return Ok(Value::f());
        }
    }

    Ok(Value::t())
}

/// Cons primitive (cons).
#[allow(dead_code)]
fn primitive_cons(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(Error::runtime_error(
            format!("cons expects 2 arguments, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::pair(args[0].clone(), args[1].clone()))
}

/// Car primitive (car).
#[allow(dead_code)]
fn primitive_car(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("car expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    match &args[0] {
        Value::Pair(car, _) => Ok((**car).clone()),
        _ => Err(Box::new(Error::runtime_error(
            format!("car expects a pair, got {}", args[0]),
            None,
        ))),
    }
}

/// Cdr primitive (cdr).
#[allow(dead_code)]
fn primitive_cdr(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("cdr expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    match &args[0] {
        Value::Pair(_, cdr) => Ok((**cdr).clone()),
        _ => Err(Box::new(Error::runtime_error(
            format!("cdr expects a pair, got {}", args[0]),
            None,
        ))),
    }
}

// Type predicate primitives

#[allow(dead_code)]
fn primitive_number_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("number? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_number()))
}

#[allow(dead_code)]
fn primitive_string_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("string? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_string()))
}

#[allow(dead_code)]
fn primitive_symbol_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("symbol? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_symbol()))
}

#[allow(dead_code)]
fn primitive_pair_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("pair? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_pair()))
}

#[allow(dead_code)]
fn primitive_null_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("null? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_nil()))
}

#[allow(dead_code)]
fn primitive_procedure_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("procedure? expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    Ok(Value::boolean(args[0].is_procedure()))
}

// I/O primitives

#[allow(dead_code)]
fn primitive_display(args: &[Value]) -> Result<Value> {
    if args.is_empty() || args.len() > 2 {
        return Err(Box::new(Error::runtime_error(
            format!("display expects 1 or 2 arguments, got {}", args.len()),
            None,
        )));
    }

    let value = &args[0];
    
    // For now, just print to stdout
    // TODO: Handle optional port argument
    print!("{value}");
    
    Ok(Value::Unspecified)
}

#[allow(dead_code)]
fn primitive_newline(args: &[Value]) -> Result<Value> {
    if args.len() > 1 {
        return Err(Box::new(Error::runtime_error(
            format!("newline expects 0 or 1 arguments, got {}", args.len()),
            None,
        )));
    }

    // For now, just print to stdout
    // TODO: Handle optional port argument
    println!();
    
    Ok(Value::Unspecified)
}

// Additional comparison primitives

#[allow(dead_code)]
fn primitive_less_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::runtime_error(
            "<= requires at least two arguments",
            None,
        )));
    }
    for window in args.windows(2) {
        let a = match window[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[0]),
                None,
            ))),
        };
        let b = match window[1].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[1]),
                None,
            ))),
        };
        if a > b {
            return Ok(Value::boolean(false));
        }
    }
    Ok(Value::boolean(true))
}

#[allow(dead_code)]
fn primitive_greater_equal(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(Error::runtime_error(
            ">= requires at least two arguments",
            None,
        )));
    }
    for window in args.windows(2) {
        let a = match window[0].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[0]),
                None,
            ))),
        };
        let b = match window[1].as_number() {
            Some(n) => n,
            None => return Err(Box::new(Error::runtime_error(
                format!("Expected number, got {}", window[1]),
                None,
            ))),
        };
        if a < b {
            return Ok(Value::boolean(false));
        }
    }
    Ok(Value::boolean(true))
}