rustleaf 0.1.0

A simple programming language interpreter written in Rust
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
use crate::core::Value;
use crate::core::{Args, RustValue};

use anyhow::{anyhow, Result};
use std::cell::RefCell;

// Thread-local capture for print output and assertion counting during testing
thread_local! {
    static PRINT_CAPTURE: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
    static ASSERTION_COUNT: RefCell<Option<u32>> = const { RefCell::new(None) };
}

#[derive(Clone)]
pub struct RustFunction {
    name: &'static str,
    func: fn(Args) -> Result<Value>,
}

impl RustFunction {
    pub fn new(name: &'static str, func: fn(Args) -> Result<Value>) -> Self {
        Self { name, func }
    }
}

impl std::fmt::Debug for RustFunction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RustFunction")
            .field("name", &self.name)
            .finish()
    }
}

#[crate::rust_value_any]
impl RustValue for RustFunction {
    fn dyn_clone(&self) -> Box<dyn RustValue> {
        Box::new(self.clone())
    }

    fn call(&self, args: Args) -> Result<Value> {
        (self.func)(args)
    }
}

// Internal helper to write to print capture or stdout
fn write_output(output: &str) {
    PRINT_CAPTURE.with(|capture| {
        if let Some(ref mut captured) = *capture.borrow_mut() {
            captured.push(output.to_string());
        } else {
            // Normal behavior: print to stdout
            println!("{output}");
        }
    });
}

pub fn print(mut args: Args) -> Result<Value> {
    args.set_function_name("print");
    let arg = args.expect("arg")?;
    args.complete()?;

    // Use str() conversion for consistent string representation
    let str_result = str(Args::new(vec![arg], Default::default()))?;
    let output = match str_result {
        Value::String(s) => s,
        _ => unreachable!("str() should always return a string"),
    };

    write_output(&output);
    Ok(Value::Unit)
}

pub fn assert(mut args: Args) -> Result<Value> {
    args.set_function_name("assert");
    let condition = args.expect("condition")?;
    let message = args.optional("message", Value::String("Assertion failed".to_string()));
    args.complete()?;

    // Increment assertion count if capture is enabled
    ASSERTION_COUNT.with(|count| {
        if let Some(ref mut counter) = *count.borrow_mut() {
            *counter += 1;
        }
    });

    if !condition.is_truthy() {
        let message_str = match message {
            Value::String(s) => s,
            other => format!("{other:?}"),
        };
        return Err(anyhow!("Assertion failed: {}", message_str));
    }

    Ok(Value::Unit)
}

// Helper functions for test capture
pub fn start_print_capture() {
    PRINT_CAPTURE.with(|capture| {
        *capture.borrow_mut() = Some(Vec::new());
    });
}

pub fn get_captured_prints() -> Vec<String> {
    PRINT_CAPTURE.with(|capture| capture.borrow_mut().take().unwrap_or_default())
}

pub fn stop_print_capture() {
    PRINT_CAPTURE.with(|capture| {
        *capture.borrow_mut() = None;
    });
}

// Helper functions for assertion counting
pub fn start_assertion_count() {
    ASSERTION_COUNT.with(|count| {
        *count.borrow_mut() = Some(0);
    });
}

pub fn get_assertion_count() -> u32 {
    ASSERTION_COUNT.with(|count| count.borrow_mut().take().unwrap_or(0))
}

pub fn stop_assertion_count() {
    ASSERTION_COUNT.with(|count| {
        *count.borrow_mut() = None;
    });
}

// Public function to write directly to PRINT_CAPTURE
// Used by the parser tracing module
pub fn write_to_print_capture(msg: String) {
    write_output(&msg);
}

pub fn is_unit(mut args: Args) -> Result<Value> {
    args.set_function_name("is_unit");
    let value = args.expect("value")?;
    args.complete()?;

    let result = matches!(value, Value::Unit);
    Ok(Value::Bool(result))
}

pub fn str(mut args: Args) -> Result<Value> {
    args.set_function_name("str");
    let value = args.expect("value")?;
    args.complete()?;

    Ok(Value::String(value.str()))
}

pub fn raise(mut args: Args) -> Result<Value> {
    args.set_function_name("raise");
    let error_value = args.expect("error")?;
    args.complete()?;

    // Return a special Error value that the evaluator will detect
    Ok(Value::Raised(Box::new(error_value)))
}

pub fn parse_builtin(mut args: Args) -> Result<Value> {
    args.set_function_name("parse");
    let template_result = args.expect("template")?;
    args.complete()?;

    let code_string = match template_result {
        Value::String(s) => s,
        _ => return Err(anyhow!("parse() expects a string")),
    };

    // Use existing lexer/parser/compiler infrastructure
    let tokens = crate::lexer::Lexer::tokenize(&code_string)
        .map_err(|e| anyhow!("Failed to tokenize: {}:\n{}", e, code_string))?;
    let ast = crate::parser::Parser::parse(tokens)
        .map_err(|e| anyhow!("Failed to parse: {}:\n{}", e, code_string))?;
    let eval_ir = crate::eval::Compiler::compile(ast)
        .map_err(|e| anyhow!("Failed to compile: {}:\n{}", e, code_string))?;

    // Return the Eval directly
    Ok(eval_ir)
}

pub fn macro_identity_builtin(mut args: Args) -> Result<Value> {
    args.set_function_name("macro");
    let eval_node = args.expect("eval_node")?;
    args.complete()?;

    // Identity macro: just return the input node unchanged
    Ok(eval_node)
}

pub fn join_builtin(mut args: Args) -> Result<Value> {
    args.set_function_name("join");
    let list = args.expect("list")?;
    let separator = args.expect("separator")?;
    args.complete()?;

    let sep_str = match separator {
        Value::String(s) => s,
        _ => return Err(anyhow!("join() separator must be a string")),
    };

    match list {
        Value::List(list_ref) => {
            let list_data = list_ref.borrow();
            let string_parts: Vec<String> = list_data
                .iter()
                .map(|item| match item {
                    Value::String(s) => s.clone(),
                    other => format!("{other:?}"), // Convert other types to string representation
                })
                .collect();
            Ok(Value::String(string_parts.join(&sep_str)))
        }
        _ => Err(anyhow!("join() expects a list as first argument")),
    }
}

pub fn int(mut args: Args) -> Result<Value> {
    args.set_function_name("int");
    let value = args.expect("value")?;
    args.complete()?;

    match value {
        Value::Int(i) => Ok(Value::Int(i)),
        Value::Float(f) => Ok(Value::Int(f.trunc() as i64)),
        _ => Err(anyhow!("Cannot convert {:?} to int", value.type_name())),
    }
}

pub fn float(mut args: Args) -> Result<Value> {
    args.set_function_name("float");
    let value = args.expect("value")?;
    args.complete()?;

    match value {
        Value::Float(f) => Ok(Value::Float(f)),
        Value::Int(i) => Ok(Value::Float(i as f64)),
        _ => Err(anyhow!("Cannot convert {:?} to float", value.type_name())),
    }
}

pub fn range(mut args: Args) -> Result<Value> {
    args.set_function_name("range");

    // Handle different argument patterns:
    // range(start, end, step=1) → list
    // range(start) → list (shorthand for range(0, start))

    let first_arg = args.expect("start")?;
    let start_val = first_arg.expect_i64("range", "start")?;

    // Check if we have a second argument (end)
    let (start, end, step) = if let Ok(second_arg) = args.expect("end") {
        // Two or three argument form: range(start, end) or range(start, end, step)
        let end_val = second_arg.expect_i64("range", "end")?;
        let step_val = if let Ok(third_arg) = args.expect("step") {
            third_arg.expect_i64("range", "step")?
        } else {
            1i64
        };
        args.complete()?;
        (start_val, end_val, step_val)
    } else {
        // Single argument form: range(start) is shorthand for range(0, start)
        args.complete()?;
        (0i64, start_val, 1i64)
    };

    // Validate step != 0
    if step == 0 {
        return Err(anyhow!("range() step argument must not be zero"));
    }

    // Generate the range
    let mut values = Vec::new();

    if step > 0 {
        // Positive step: start < end
        let mut current = start;
        while current < end {
            values.push(Value::Int(current));
            current += step;
        }
    } else {
        // Negative step: start > end
        let mut current = start;
        while current > end {
            values.push(Value::Int(current));
            current += step;
        }
    }

    Ok(Value::new_list_with_values(values))
}

pub fn sum(mut args: Args) -> Result<Value> {
    args.set_function_name("sum");
    let iterable = args.expect("iterable")?;
    args.complete()?;

    match iterable {
        Value::List(list_ref) => {
            let list = list_ref.borrow();

            if list.is_empty() {
                return Ok(Value::Int(0));
            }

            let mut sum = list[0].clone();

            for item in list.iter().skip(1) {
                // Use the helper method for cleaner code
                sum = sum.op_add(item.clone())?;
            }

            Ok(sum)
        }
        _ => Err(anyhow!("sum() expects a list or iterable")),
    }
}

pub fn filter(mut args: Args) -> Result<Value> {
    args.set_function_name("filter");
    let mut iterable = args.expect("iterable")?;
    let predicate = args.expect("predicate")?;
    args.complete()?;

    match &iterable {
        Value::List(list_ref) => {
            // Handle lists directly for efficiency
            let list = list_ref.borrow();
            let mut filtered = Vec::new();

            for item in list.iter() {
                // Call the predicate function with the item
                let predicate_args = crate::core::Args::positional(vec![item.clone()]);
                let result = predicate.call(predicate_args)?;

                // Check if result is truthy
                if result.is_truthy() {
                    filtered.push(item.clone());
                }
            }

            Ok(Value::new_list_with_values(filtered))
        }
        _ => {
            // Handle any iterator using the op_next helper
            let mut filtered = Vec::new();

            loop {
                // Try to get the next value from the iterator
                match iterable.op_next() {
                    Ok(Some(item)) => {
                        // Call the predicate function with the item
                        let predicate_args = crate::core::Args::positional(vec![item.clone()]);
                        let result = predicate.call(predicate_args)?;

                        // Check if result is truthy
                        if result.is_truthy() {
                            filtered.push(item);
                        }
                    }
                    Ok(None) => break, // Iterator exhausted
                    Err(_) => {
                        // Not an iterator, return error
                        return Err(anyhow!("filter() expects a list or iterable"));
                    }
                }
            }

            Ok(Value::new_list_with_values(filtered))
        }
    }
}

pub fn take_while(mut args: Args) -> Result<Value> {
    args.set_function_name("take_while");
    let mut iterable = args.expect("iterable")?;
    let predicate = args.expect("predicate")?;
    args.complete()?;

    match &iterable {
        Value::List(list_ref) => {
            // Handle lists directly for efficiency
            let list = list_ref.borrow();
            let mut taken = Vec::new();

            for item in list.iter() {
                // Call the predicate function with the item
                let predicate_args = crate::core::Args::positional(vec![item.clone()]);
                let result = predicate.call(predicate_args)?;

                // Check if result is truthy
                if result.is_truthy() {
                    taken.push(item.clone());
                } else {
                    break; // Stop taking once predicate is false
                }
            }

            Ok(Value::new_list_with_values(taken))
        }
        _ => {
            // Handle any iterator using the op_next helper
            let mut taken = Vec::new();

            loop {
                // Try to get the next value from the iterator
                match iterable.op_next() {
                    Ok(Some(item)) => {
                        // Call the predicate function with the item
                        let predicate_args = crate::core::Args::positional(vec![item.clone()]);
                        let result = predicate.call(predicate_args)?;

                        // Check if result is truthy
                        if result.is_truthy() {
                            taken.push(item);
                        } else {
                            break; // Stop taking once predicate is false
                        }
                    }
                    Ok(None) => break, // Iterator exhausted
                    Err(_) => {
                        // Not an iterator, return error
                        return Err(anyhow!("take_while() expects a list or iterable"));
                    }
                }
            }

            Ok(Value::new_list_with_values(taken))
        }
    }
}