Struct rust_lisp::model::Env

source ·
pub struct Env { /* private fields */ }
Expand description

An environment of symbol bindings. Used for the base environment, for closures, for let statements, for function arguments, etc.

Implementations§

Create a new, empty environment

Examples found in repository?
src/default_environment.rs (line 19)
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
pub fn default_env() -> Env {
    let mut env = Env::new();

    env.define(
        Symbol::from("print"),
        Value::NativeFunc(|_env, args| {
            let expr = require_arg("print", &args, 0)?;

            println!("{}", &expr);
            Ok(expr.clone())
        }),
    );

    env.define(
        Symbol::from("is_null"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_null", &args, 0)?;

            Ok(Value::from(*val == Value::NIL))
        }),
    );

    env.define(
        Symbol::from("is_number"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_number", &args, 0)?;

            Ok(match val {
                Value::Int(_) => Value::True,
                Value::Float(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_symbol"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_symbol", &args, 0)?;

            Ok(match val {
                Value::Symbol(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_boolean"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_boolean", &args, 0)?;

            Ok(match val {
                Value::True => Value::True,
                Value::False => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_procedure"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_procedure", &args, 0)?;

            Ok(match val {
                Value::Lambda(_) => Value::True,
                Value::NativeFunc(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_pair"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_pair", &args, 0)?;

            Ok(match val {
                Value::List(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("car"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("car", &args, 0)?;

            list.car()
        }),
    );

    env.define(
        Symbol::from("cdr"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("cdr", &args, 0)?;

            Ok(Value::List(list.cdr()))
        }),
    );

    env.define(
        Symbol::from("cons"),
        Value::NativeFunc(|_env, args| {
            let car = require_arg("cons", &args, 0)?;
            let cdr = require_typed_arg::<&List>("cons", &args, 1)?;

            Ok(Value::List(cdr.cons(car.clone())))
        }),
    );

    env.define(
        Symbol::from("list"),
        Value::NativeFunc(|_env, args| Ok(Value::List(args.iter().collect::<List>()))),
    );

    env.define(
        Symbol::from("nth"),
        Value::NativeFunc(|_env, args| {
            let index = require_typed_arg::<IntType>("nth", &args, 0)?;
            let list = require_typed_arg::<&List>("nth", &args, 1)?;

            let index = TryInto::<usize>::try_into(index).map_err(|_| RuntimeError {
                msg: "Failed converting to `usize`".to_owned(),
            })?;

            Ok(list.into_iter().nth(index).unwrap_or(Value::NIL))
        }),
    );

    env.define(
        Symbol::from("sort"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("sort", &args, 0)?;

            let mut v: Vec<Value> = list.into_iter().collect();

            v.sort();

            Ok(Value::List(v.into_iter().collect()))
        }),
    );

    env.define(
        Symbol::from("reverse"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("reverse", &args, 0)?;

            let mut v: Vec<Value> = list.into_iter().collect();

            v.reverse();

            Ok(Value::List(v.into_iter().collect()))
        }),
    );

    env.define(
        Symbol::from("map"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("map", &args, 0)?;
            let list = require_typed_arg::<&List>("map", &args, 1)?;

            list.into_iter()
                .map(|val| {
                    let expr = lisp! { ({func.clone()} (quote {val})) };

                    eval(env.clone(), &expr)
                })
                .collect::<Result<List, RuntimeError>>()
                .map(Value::List)
        }),
    );

    // 🦀 Oh the poor `filter`, you must feel really sad being unused.
    env.define(
        Symbol::from("filter"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("filter", &args, 0)?;
            let list = require_typed_arg::<&List>("filter", &args, 1)?;

            list.into_iter()
                .filter_map(|val: Value| -> Option<Result<Value, RuntimeError>> {
                    let expr = lisp! { ({func.clone()} (quote {val.clone()})) };

                    match eval(env.clone(), &expr) {
                        Ok(matches) => {
                            if matches.into() {
                                Some(Ok(val))
                            } else {
                                None
                            }
                        }
                        Err(e) => Some(Err(e)),
                    }
                })
                .collect::<Result<List, RuntimeError>>()
                .map(Value::List)
        }),
    );

    env.define(
        Symbol::from("length"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("length", &args, 0)?;

            cfg_if! {
                if #[cfg(feature = "bigint")] {
                    Ok(Value::Int(list.into_iter().len().into()))
                } else {
                    Ok(Value::Int(list.into_iter().len() as IntType))
                }
            }
        }),
    );

    env.define(
        Symbol::from("range"),
        Value::NativeFunc(|_env, args| {
            let start = require_typed_arg::<IntType>("range", &args, 0)?;
            let end = require_typed_arg::<IntType>("range", &args, 1)?;

            let mut current = start;

            Ok(Value::List(
                std::iter::from_fn(move || {
                    if current == end {
                        None
                    } else {
                        let res = Some(current.clone());

                        current += 1;

                        res
                    }
                })
                .map(Value::from)
                .collect(),
            ))
        }),
    );

    env.define(
        Symbol::from("hash"),
        Value::NativeFunc(|_env, args| {
            let chunks = args.chunks(2);

            let mut hash = HashMap::new();

            for pair in chunks {
                let key = pair.get(0).unwrap();
                let value = pair.get(1);

                if let Some(value) = value {
                    hash.insert(key.clone(), value.clone());
                } else {
                    return Err(RuntimeError {
                        msg: format!("Must pass an even number of arguments to 'hash', because they're used as key/value pairs; found extra argument {}", key)
                    });
                }
            }

            Ok(Value::HashMap(Rc::new(RefCell::new(hash))))
        }),
    );

    env.define(
        Symbol::from("hash_get"),
        Value::NativeFunc(|_env, args| {
            let hash = require_typed_arg::<&HashMapRc>("hash_get", &args, 0)?;
            let key = require_arg("hash_get", &args, 1)?;

            Ok(hash
                .borrow()
                .get(key)
                .map(|v| v.clone())
                .unwrap_or(Value::NIL))
        }),
    );

    env.define(
        Symbol::from("hash_set"),
        Value::NativeFunc(|_env, args| {
            let hash = require_typed_arg::<&HashMapRc>("hash_set", &args, 0)?;
            let key = require_arg("hash_set", &args, 1)?;
            let value = require_arg("hash_set", &args, 2)?;

            hash.borrow_mut().insert(key.clone(), value.clone());

            Ok(Value::HashMap(hash.clone()))
        }),
    );

    env.define(
        Symbol::from("+"),
        Value::NativeFunc(|_env, args| {
            let first_arg = require_arg("+", &args, 1)?;

            let mut total = match first_arg {
                Value::Int(_) => Ok(Value::Int(0.into())),
                Value::Float(_) => Ok(Value::Float(0.0)),
                Value::String(_) => Ok(Value::String("".into())),
                _ => Err(RuntimeError {
                    msg: format!(
                        "Function \"+\" requires arguments to be numbers or strings; found {}",
                        first_arg
                    ),
                }),
            }?;

            for arg in args {
                total = (&total + &arg).map_err(|_| RuntimeError {
                    msg: format!(
                        "Function \"+\" requires arguments to be numbers or strings; found {}",
                        arg
                    ),
                })?;
            }

            Ok(total)
        }),
    );

    env.define(
        Symbol::from("-"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("-", &args, 0)?;
            let b = require_arg("-", &args, 1)?;

            (a - b).map_err(|_| RuntimeError {
                msg: String::from("Function \"-\" requires arguments to be numbers"),
            })
        }),
    );

    env.define(
        Symbol::from("*"),
        Value::NativeFunc(|_env, args| {
            let mut product = Value::Int(1.into());

            for arg in args {
                product = (&product * &arg).map_err(|_| RuntimeError {
                    msg: format!(
                        "Function \"*\" requires arguments to be numbers; found {}",
                        arg
                    ),
                })?;
            }

            Ok(product)
        }),
    );

    env.define(
        Symbol::from("/"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("/", &args, 0)?;
            let b = require_arg("/", &args, 1)?;

            (a / b).map_err(|_| RuntimeError {
                msg: String::from("Function \"/\" requires arguments to be numbers"),
            })
        }),
    );

    env.define(
        Symbol::from("truncate"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("truncate", &args, 0)?;
            let b = require_arg("truncate", &args, 1)?;

            if let (Ok(a), Ok(b)) = (
                TryInto::<IntType>::try_into(a),
                TryInto::<IntType>::try_into(b),
            ) {
                return Ok(Value::Int(a / b));
            }

            Err(RuntimeError {
                msg: String::from("Function \"truncate\" requires arguments to be integers"),
            })
        }),
    );

    env.define(
        Symbol::from("not"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("not", &args, 0)?;
            let a: bool = a.into();

            Ok(Value::from(!a))
        }),
    );

    env.define(
        Symbol::from("=="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("==", &args, 0)?;
            let b = require_arg("==", &args, 1)?;

            Ok(Value::from(a == b))
        }),
    );

    env.define(
        Symbol::from("!="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("!=", &args, 0)?;
            let b = require_arg("!=", &args, 1)?;

            Ok(Value::from(a != b))
        }),
    );

    env.define(
        Symbol::from("<"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("<", &args, 0)?;
            let b = require_arg("<", &args, 1)?;

            Ok(Value::from(a < b))
        }),
    );

    env.define(
        Symbol::from("<="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("<=", &args, 0)?;
            let b = require_arg("<=", &args, 1)?;

            Ok(Value::from(a <= b))
        }),
    );

    env.define(
        Symbol::from(">"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg(">", &args, 0)?;
            let b = require_arg(">", &args, 1)?;

            Ok(Value::from(a > b))
        }),
    );

    env.define(
        Symbol::from(">="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg(">=", &args, 0)?;
            let b = require_arg(">=", &args, 1)?;

            Ok(Value::from(a >= b))
        }),
    );

    env.define(
        Symbol::from("eval"),
        Value::NativeFunc(|env, args| {
            let expr = require_arg("eval", &args, 0)?;

            eval(env, expr)
        }),
    );

    env.define(
        Symbol::from("apply"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("apply", &args, 0)?;
            let params = require_typed_arg::<&List>("apply", &args, 1)?;

            eval(env, &Value::List(params.cons(func.clone())))
        }),
    );

    env
}

Create a new environment extending the given environment

Examples found in repository?
src/interpreter.rs (line 168)
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
fn eval_inner(
    env: Rc<RefCell<Env>>,
    expression: &Value,
    context: Context,
) -> Result<Value, RuntimeError> {
    if context.quoting {
        match expression {
            Value::List(list) if *list != List::NIL => match &list.car()? {
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    // do nothing, handle it down below
                }
                _ => {
                    return list
                        .into_iter()
                        .map(|el| eval_inner(env.clone(), &el, context))
                        .collect::<Result<List, RuntimeError>>()
                        .map(Value::List);
                }
            },
            _ => return Ok(expression.clone()),
        }
    }

    match expression {
        // look up symbol
        Value::Symbol(symbol) => env.borrow().get(symbol).ok_or_else(|| RuntimeError {
            msg: format!("\"{}\" is not defined", symbol),
        }),

        // s-expression
        Value::List(list) if *list != List::NIL => {
            match &list.car()? {
                // special forms
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(false))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "quote" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(true))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "define" || keyword == "set" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let value_expr = require_arg(keyword, args, 1)?;

                    let value = eval_inner(env.clone(), value_expr, context.found_tail(true))?;

                    if keyword == "define" {
                        env.borrow_mut().define(symbol.clone(), value.clone());
                    } else {
                        env.borrow_mut().set(symbol.clone(), value.clone())?;
                    }

                    Ok(value)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defmacro" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Macro(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defun" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Lambda(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "lambda" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let argnames_list = require_typed_arg::<&List>(keyword, args, 0)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr()));

                    Ok(Value::Lambda(Lambda {
                        closure: env,
                        argnames,
                        body,
                    }))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "let" => {
                    let let_env = Rc::new(RefCell::new(Env::extend(env)));

                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let declarations = require_typed_arg::<&List>(keyword, args, 0)?;

                    for decl in declarations.into_iter() {
                        let decl = &decl;

                        let decl_cons: &List = decl.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected declaration clause, found {}", decl),
                        })?;
                        let symbol = &decl_cons.car()?;
                        let symbol: &Symbol = symbol.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected symbol for let declaration, found {}", symbol),
                        })?;
                        let expr = &decl_cons.cdr().car()?;

                        let result = eval_inner(let_env.clone(), expr, context.found_tail(true))?;
                        let_env.borrow_mut().define(symbol.clone(), result);
                    }

                    let body = &Value::List(list.cdr().cdr());
                    let body: &List = body.try_into().map_err(|_| RuntimeError {
                        msg: format!(
                            "Expected expression(s) after let-declarations, found {}",
                            body
                        ),
                    })?;

                    eval_block_inner(let_env, body.into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "begin" => {
                    eval_block_inner(env, list.cdr().into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "cond" => {
                    let clauses = list.cdr();

                    for clause in clauses.into_iter() {
                        let clause = &clause;

                        let clause: &List = clause.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected conditional clause, found {}", clause),
                        })?;

                        let condition = &clause.car()?;
                        let then = &clause.cdr().car()?;

                        if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                            return eval_inner(env, then, context);
                        }
                    }

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "if" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let condition = require_arg(keyword, args, 0)?;
                    let then_expr = require_arg(keyword, args, 1)?;
                    let else_expr = require_arg(keyword, args, 2).ok();

                    if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                        eval_inner(env, then_expr, context)
                    } else {
                        else_expr
                            .map(|expr| eval_inner(env, &expr, context))
                            .unwrap_or(Ok(Value::NIL))
                    }
                }

                Value::Symbol(Symbol(keyword)) if keyword == "and" || keyword == "or" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();
                    let is_or = keyword.as_str() == "or";

                    let mut last_result: Option<Value> = None;
                    for arg in args {
                        let result = eval_inner(env.clone(), arg, context.found_tail(true))?;
                        let truthy: bool = (&result).into();

                        if is_or == truthy {
                            return Ok(result);
                        }

                        last_result = Some(result);
                    }

                    Ok(if let Some(last_result) = last_result {
                        last_result
                    } else {
                        // there were zero arguments
                        (!is_or).into()
                    })
                }

                // function call or macro expand
                _ => {
                    let mut func_or_macro =
                        eval_inner(env.clone(), &list.car()?, context.found_tail(true))?;

                    if matches!(func_or_macro, Value::Macro(_)) {
                        let args = list.into_iter().skip(1).collect::<Vec<Value>>();

                        let expanded =
                            call_function_or_macro(env.clone(), &mut func_or_macro, args)?;

                        eval_inner(env.clone(), &expanded, Context::new())
                    } else {
                        let args = list
                            .into_iter()
                            .skip(1)
                            .map(|car| eval_inner(env.clone(), &car, context.found_tail(true)))
                            .collect::<Result<Vec<Value>, RuntimeError>>()?;

                        if !context.found_tail && context.in_func {
                            Ok(Value::TailCall {
                                func: Rc::new(func_or_macro),
                                args,
                            })
                        } else {
                            let mut res =
                                call_function_or_macro(env.clone(), &mut func_or_macro, args);

                            while let Ok(Value::TailCall { func, args }) = res {
                                res = call_function_or_macro(env.clone(), func.as_ref(), args);
                            }

                            res
                        }
                    }
                }
            }
        }

        // plain value
        _ => Ok(expression.clone()),
    }
}
// 🦀 Boo! Did I scare ya? Haha!

fn value_to_argnames(argnames: List) -> Result<Vec<Symbol>, RuntimeError> {
    argnames
        .into_iter()
        .enumerate()
        .map(|(index, arg)| match arg {
            Value::Symbol(s) => Ok(s),
            _ => Err(RuntimeError {
                msg: format!(
                    "Expected list of arg names, but arg {} is a {}",
                    index,
                    arg.type_name()
                ),
            }),
        })
        .collect()
}

/// Calling a function is separated from the main `eval_inner()` function
/// so that tail calls can be evaluated without just returning themselves
/// as-is as a tail-call.
fn call_function_or_macro(
    env: Rc<RefCell<Env>>,
    func: &Value,
    args: Vec<Value>,
) -> Result<Value, RuntimeError> {
    if let Value::NativeFunc(func) = func {
        func(env, args)
    } else if let Value::NativeClosure(closure) = func {
        closure.borrow_mut()(env, args)
    } else {
        let lambda = match func {
            Value::Lambda(lamb) => Some(lamb),
            Value::Macro(lamb) => Some(lamb),
            _ => None,
        };

        if let Some(lambda) = lambda {
            // bind args
            let mut arg_env = Env::extend(lambda.closure.clone());
            for (index, arg_name) in lambda.argnames.iter().enumerate() {
                if arg_name.0 == "..." {
                    // rest parameters
                    arg_env.define(
                        Symbol::from("..."),
                        Value::List(args.into_iter().skip(index).collect()),
                    );
                    break;
                } else {
                    arg_env.define(arg_name.clone(), args[index].clone());
                }
            }

            // evaluate each line of body
            let clauses: &List = lambda.body.as_ref().try_into()?;
            eval_block_inner(
                Rc::new(RefCell::new(arg_env)),
                clauses.into_iter(),
                Context {
                    found_tail: false,
                    in_func: true,
                    quoting: false,
                },
            )
        } else {
            Err(RuntimeError {
                msg: format!("{} is not callable", func),
            })
        }
    }
}

Walks up the environment hierarchy until it finds the symbol’s value or runs out of environments.

Examples found in repository?
src/model/env.rs (line 38)
34
35
36
37
38
39
40
41
42
    pub fn get(&self, key: &Symbol) -> Option<Value> {
        if let Some(val) = self.entries.get(&key) {
            Some(val.clone()) // clone the Rc
        } else if let Some(parent) = &self.parent {
            parent.borrow().get(key)
        } else {
            None
        }
    }
More examples
Hide additional examples
src/interpreter.rs (line 82)
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
fn eval_inner(
    env: Rc<RefCell<Env>>,
    expression: &Value,
    context: Context,
) -> Result<Value, RuntimeError> {
    if context.quoting {
        match expression {
            Value::List(list) if *list != List::NIL => match &list.car()? {
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    // do nothing, handle it down below
                }
                _ => {
                    return list
                        .into_iter()
                        .map(|el| eval_inner(env.clone(), &el, context))
                        .collect::<Result<List, RuntimeError>>()
                        .map(Value::List);
                }
            },
            _ => return Ok(expression.clone()),
        }
    }

    match expression {
        // look up symbol
        Value::Symbol(symbol) => env.borrow().get(symbol).ok_or_else(|| RuntimeError {
            msg: format!("\"{}\" is not defined", symbol),
        }),

        // s-expression
        Value::List(list) if *list != List::NIL => {
            match &list.car()? {
                // special forms
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(false))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "quote" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(true))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "define" || keyword == "set" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let value_expr = require_arg(keyword, args, 1)?;

                    let value = eval_inner(env.clone(), value_expr, context.found_tail(true))?;

                    if keyword == "define" {
                        env.borrow_mut().define(symbol.clone(), value.clone());
                    } else {
                        env.borrow_mut().set(symbol.clone(), value.clone())?;
                    }

                    Ok(value)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defmacro" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Macro(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defun" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Lambda(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "lambda" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let argnames_list = require_typed_arg::<&List>(keyword, args, 0)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr()));

                    Ok(Value::Lambda(Lambda {
                        closure: env,
                        argnames,
                        body,
                    }))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "let" => {
                    let let_env = Rc::new(RefCell::new(Env::extend(env)));

                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let declarations = require_typed_arg::<&List>(keyword, args, 0)?;

                    for decl in declarations.into_iter() {
                        let decl = &decl;

                        let decl_cons: &List = decl.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected declaration clause, found {}", decl),
                        })?;
                        let symbol = &decl_cons.car()?;
                        let symbol: &Symbol = symbol.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected symbol for let declaration, found {}", symbol),
                        })?;
                        let expr = &decl_cons.cdr().car()?;

                        let result = eval_inner(let_env.clone(), expr, context.found_tail(true))?;
                        let_env.borrow_mut().define(symbol.clone(), result);
                    }

                    let body = &Value::List(list.cdr().cdr());
                    let body: &List = body.try_into().map_err(|_| RuntimeError {
                        msg: format!(
                            "Expected expression(s) after let-declarations, found {}",
                            body
                        ),
                    })?;

                    eval_block_inner(let_env, body.into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "begin" => {
                    eval_block_inner(env, list.cdr().into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "cond" => {
                    let clauses = list.cdr();

                    for clause in clauses.into_iter() {
                        let clause = &clause;

                        let clause: &List = clause.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected conditional clause, found {}", clause),
                        })?;

                        let condition = &clause.car()?;
                        let then = &clause.cdr().car()?;

                        if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                            return eval_inner(env, then, context);
                        }
                    }

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "if" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let condition = require_arg(keyword, args, 0)?;
                    let then_expr = require_arg(keyword, args, 1)?;
                    let else_expr = require_arg(keyword, args, 2).ok();

                    if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                        eval_inner(env, then_expr, context)
                    } else {
                        else_expr
                            .map(|expr| eval_inner(env, &expr, context))
                            .unwrap_or(Ok(Value::NIL))
                    }
                }

                Value::Symbol(Symbol(keyword)) if keyword == "and" || keyword == "or" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();
                    let is_or = keyword.as_str() == "or";

                    let mut last_result: Option<Value> = None;
                    for arg in args {
                        let result = eval_inner(env.clone(), arg, context.found_tail(true))?;
                        let truthy: bool = (&result).into();

                        if is_or == truthy {
                            return Ok(result);
                        }

                        last_result = Some(result);
                    }

                    Ok(if let Some(last_result) = last_result {
                        last_result
                    } else {
                        // there were zero arguments
                        (!is_or).into()
                    })
                }

                // function call or macro expand
                _ => {
                    let mut func_or_macro =
                        eval_inner(env.clone(), &list.car()?, context.found_tail(true))?;

                    if matches!(func_or_macro, Value::Macro(_)) {
                        let args = list.into_iter().skip(1).collect::<Vec<Value>>();

                        let expanded =
                            call_function_or_macro(env.clone(), &mut func_or_macro, args)?;

                        eval_inner(env.clone(), &expanded, Context::new())
                    } else {
                        let args = list
                            .into_iter()
                            .skip(1)
                            .map(|car| eval_inner(env.clone(), &car, context.found_tail(true)))
                            .collect::<Result<Vec<Value>, RuntimeError>>()?;

                        if !context.found_tail && context.in_func {
                            Ok(Value::TailCall {
                                func: Rc::new(func_or_macro),
                                args,
                            })
                        } else {
                            let mut res =
                                call_function_or_macro(env.clone(), &mut func_or_macro, args);

                            while let Ok(Value::TailCall { func, args }) = res {
                                res = call_function_or_macro(env.clone(), func.as_ref(), args);
                            }

                            res
                        }
                    }
                }
            }
        }

        // plain value
        _ => Ok(expression.clone()),
    }
}

Define a new key in the current environment

Examples found in repository?
src/interpreter.rs (line 107)
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
fn eval_inner(
    env: Rc<RefCell<Env>>,
    expression: &Value,
    context: Context,
) -> Result<Value, RuntimeError> {
    if context.quoting {
        match expression {
            Value::List(list) if *list != List::NIL => match &list.car()? {
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    // do nothing, handle it down below
                }
                _ => {
                    return list
                        .into_iter()
                        .map(|el| eval_inner(env.clone(), &el, context))
                        .collect::<Result<List, RuntimeError>>()
                        .map(Value::List);
                }
            },
            _ => return Ok(expression.clone()),
        }
    }

    match expression {
        // look up symbol
        Value::Symbol(symbol) => env.borrow().get(symbol).ok_or_else(|| RuntimeError {
            msg: format!("\"{}\" is not defined", symbol),
        }),

        // s-expression
        Value::List(list) if *list != List::NIL => {
            match &list.car()? {
                // special forms
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(false))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "quote" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(true))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "define" || keyword == "set" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let value_expr = require_arg(keyword, args, 1)?;

                    let value = eval_inner(env.clone(), value_expr, context.found_tail(true))?;

                    if keyword == "define" {
                        env.borrow_mut().define(symbol.clone(), value.clone());
                    } else {
                        env.borrow_mut().set(symbol.clone(), value.clone())?;
                    }

                    Ok(value)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defmacro" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Macro(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defun" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Lambda(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "lambda" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let argnames_list = require_typed_arg::<&List>(keyword, args, 0)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr()));

                    Ok(Value::Lambda(Lambda {
                        closure: env,
                        argnames,
                        body,
                    }))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "let" => {
                    let let_env = Rc::new(RefCell::new(Env::extend(env)));

                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let declarations = require_typed_arg::<&List>(keyword, args, 0)?;

                    for decl in declarations.into_iter() {
                        let decl = &decl;

                        let decl_cons: &List = decl.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected declaration clause, found {}", decl),
                        })?;
                        let symbol = &decl_cons.car()?;
                        let symbol: &Symbol = symbol.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected symbol for let declaration, found {}", symbol),
                        })?;
                        let expr = &decl_cons.cdr().car()?;

                        let result = eval_inner(let_env.clone(), expr, context.found_tail(true))?;
                        let_env.borrow_mut().define(symbol.clone(), result);
                    }

                    let body = &Value::List(list.cdr().cdr());
                    let body: &List = body.try_into().map_err(|_| RuntimeError {
                        msg: format!(
                            "Expected expression(s) after let-declarations, found {}",
                            body
                        ),
                    })?;

                    eval_block_inner(let_env, body.into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "begin" => {
                    eval_block_inner(env, list.cdr().into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "cond" => {
                    let clauses = list.cdr();

                    for clause in clauses.into_iter() {
                        let clause = &clause;

                        let clause: &List = clause.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected conditional clause, found {}", clause),
                        })?;

                        let condition = &clause.car()?;
                        let then = &clause.cdr().car()?;

                        if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                            return eval_inner(env, then, context);
                        }
                    }

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "if" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let condition = require_arg(keyword, args, 0)?;
                    let then_expr = require_arg(keyword, args, 1)?;
                    let else_expr = require_arg(keyword, args, 2).ok();

                    if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                        eval_inner(env, then_expr, context)
                    } else {
                        else_expr
                            .map(|expr| eval_inner(env, &expr, context))
                            .unwrap_or(Ok(Value::NIL))
                    }
                }

                Value::Symbol(Symbol(keyword)) if keyword == "and" || keyword == "or" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();
                    let is_or = keyword.as_str() == "or";

                    let mut last_result: Option<Value> = None;
                    for arg in args {
                        let result = eval_inner(env.clone(), arg, context.found_tail(true))?;
                        let truthy: bool = (&result).into();

                        if is_or == truthy {
                            return Ok(result);
                        }

                        last_result = Some(result);
                    }

                    Ok(if let Some(last_result) = last_result {
                        last_result
                    } else {
                        // there were zero arguments
                        (!is_or).into()
                    })
                }

                // function call or macro expand
                _ => {
                    let mut func_or_macro =
                        eval_inner(env.clone(), &list.car()?, context.found_tail(true))?;

                    if matches!(func_or_macro, Value::Macro(_)) {
                        let args = list.into_iter().skip(1).collect::<Vec<Value>>();

                        let expanded =
                            call_function_or_macro(env.clone(), &mut func_or_macro, args)?;

                        eval_inner(env.clone(), &expanded, Context::new())
                    } else {
                        let args = list
                            .into_iter()
                            .skip(1)
                            .map(|car| eval_inner(env.clone(), &car, context.found_tail(true)))
                            .collect::<Result<Vec<Value>, RuntimeError>>()?;

                        if !context.found_tail && context.in_func {
                            Ok(Value::TailCall {
                                func: Rc::new(func_or_macro),
                                args,
                            })
                        } else {
                            let mut res =
                                call_function_or_macro(env.clone(), &mut func_or_macro, args);

                            while let Ok(Value::TailCall { func, args }) = res {
                                res = call_function_or_macro(env.clone(), func.as_ref(), args);
                            }

                            res
                        }
                    }
                }
            }
        }

        // plain value
        _ => Ok(expression.clone()),
    }
}
// 🦀 Boo! Did I scare ya? Haha!

fn value_to_argnames(argnames: List) -> Result<Vec<Symbol>, RuntimeError> {
    argnames
        .into_iter()
        .enumerate()
        .map(|(index, arg)| match arg {
            Value::Symbol(s) => Ok(s),
            _ => Err(RuntimeError {
                msg: format!(
                    "Expected list of arg names, but arg {} is a {}",
                    index,
                    arg.type_name()
                ),
            }),
        })
        .collect()
}

/// Calling a function is separated from the main `eval_inner()` function
/// so that tail calls can be evaluated without just returning themselves
/// as-is as a tail-call.
fn call_function_or_macro(
    env: Rc<RefCell<Env>>,
    func: &Value,
    args: Vec<Value>,
) -> Result<Value, RuntimeError> {
    if let Value::NativeFunc(func) = func {
        func(env, args)
    } else if let Value::NativeClosure(closure) = func {
        closure.borrow_mut()(env, args)
    } else {
        let lambda = match func {
            Value::Lambda(lamb) => Some(lamb),
            Value::Macro(lamb) => Some(lamb),
            _ => None,
        };

        if let Some(lambda) = lambda {
            // bind args
            let mut arg_env = Env::extend(lambda.closure.clone());
            for (index, arg_name) in lambda.argnames.iter().enumerate() {
                if arg_name.0 == "..." {
                    // rest parameters
                    arg_env.define(
                        Symbol::from("..."),
                        Value::List(args.into_iter().skip(index).collect()),
                    );
                    break;
                } else {
                    arg_env.define(arg_name.clone(), args[index].clone());
                }
            }

            // evaluate each line of body
            let clauses: &List = lambda.body.as_ref().try_into()?;
            eval_block_inner(
                Rc::new(RefCell::new(arg_env)),
                clauses.into_iter(),
                Context {
                    found_tail: false,
                    in_func: true,
                    quoting: false,
                },
            )
        } else {
            Err(RuntimeError {
                msg: format!("{} is not callable", func),
            })
        }
    }
}
More examples
Hide additional examples
src/default_environment.rs (lines 21-29)
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
pub fn default_env() -> Env {
    let mut env = Env::new();

    env.define(
        Symbol::from("print"),
        Value::NativeFunc(|_env, args| {
            let expr = require_arg("print", &args, 0)?;

            println!("{}", &expr);
            Ok(expr.clone())
        }),
    );

    env.define(
        Symbol::from("is_null"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_null", &args, 0)?;

            Ok(Value::from(*val == Value::NIL))
        }),
    );

    env.define(
        Symbol::from("is_number"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_number", &args, 0)?;

            Ok(match val {
                Value::Int(_) => Value::True,
                Value::Float(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_symbol"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_symbol", &args, 0)?;

            Ok(match val {
                Value::Symbol(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_boolean"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_boolean", &args, 0)?;

            Ok(match val {
                Value::True => Value::True,
                Value::False => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_procedure"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_procedure", &args, 0)?;

            Ok(match val {
                Value::Lambda(_) => Value::True,
                Value::NativeFunc(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("is_pair"),
        Value::NativeFunc(|_env, args| {
            let val = require_arg("is_pair", &args, 0)?;

            Ok(match val {
                Value::List(_) => Value::True,
                _ => Value::NIL,
            })
        }),
    );

    env.define(
        Symbol::from("car"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("car", &args, 0)?;

            list.car()
        }),
    );

    env.define(
        Symbol::from("cdr"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("cdr", &args, 0)?;

            Ok(Value::List(list.cdr()))
        }),
    );

    env.define(
        Symbol::from("cons"),
        Value::NativeFunc(|_env, args| {
            let car = require_arg("cons", &args, 0)?;
            let cdr = require_typed_arg::<&List>("cons", &args, 1)?;

            Ok(Value::List(cdr.cons(car.clone())))
        }),
    );

    env.define(
        Symbol::from("list"),
        Value::NativeFunc(|_env, args| Ok(Value::List(args.iter().collect::<List>()))),
    );

    env.define(
        Symbol::from("nth"),
        Value::NativeFunc(|_env, args| {
            let index = require_typed_arg::<IntType>("nth", &args, 0)?;
            let list = require_typed_arg::<&List>("nth", &args, 1)?;

            let index = TryInto::<usize>::try_into(index).map_err(|_| RuntimeError {
                msg: "Failed converting to `usize`".to_owned(),
            })?;

            Ok(list.into_iter().nth(index).unwrap_or(Value::NIL))
        }),
    );

    env.define(
        Symbol::from("sort"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("sort", &args, 0)?;

            let mut v: Vec<Value> = list.into_iter().collect();

            v.sort();

            Ok(Value::List(v.into_iter().collect()))
        }),
    );

    env.define(
        Symbol::from("reverse"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("reverse", &args, 0)?;

            let mut v: Vec<Value> = list.into_iter().collect();

            v.reverse();

            Ok(Value::List(v.into_iter().collect()))
        }),
    );

    env.define(
        Symbol::from("map"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("map", &args, 0)?;
            let list = require_typed_arg::<&List>("map", &args, 1)?;

            list.into_iter()
                .map(|val| {
                    let expr = lisp! { ({func.clone()} (quote {val})) };

                    eval(env.clone(), &expr)
                })
                .collect::<Result<List, RuntimeError>>()
                .map(Value::List)
        }),
    );

    // 🦀 Oh the poor `filter`, you must feel really sad being unused.
    env.define(
        Symbol::from("filter"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("filter", &args, 0)?;
            let list = require_typed_arg::<&List>("filter", &args, 1)?;

            list.into_iter()
                .filter_map(|val: Value| -> Option<Result<Value, RuntimeError>> {
                    let expr = lisp! { ({func.clone()} (quote {val.clone()})) };

                    match eval(env.clone(), &expr) {
                        Ok(matches) => {
                            if matches.into() {
                                Some(Ok(val))
                            } else {
                                None
                            }
                        }
                        Err(e) => Some(Err(e)),
                    }
                })
                .collect::<Result<List, RuntimeError>>()
                .map(Value::List)
        }),
    );

    env.define(
        Symbol::from("length"),
        Value::NativeFunc(|_env, args| {
            let list = require_typed_arg::<&List>("length", &args, 0)?;

            cfg_if! {
                if #[cfg(feature = "bigint")] {
                    Ok(Value::Int(list.into_iter().len().into()))
                } else {
                    Ok(Value::Int(list.into_iter().len() as IntType))
                }
            }
        }),
    );

    env.define(
        Symbol::from("range"),
        Value::NativeFunc(|_env, args| {
            let start = require_typed_arg::<IntType>("range", &args, 0)?;
            let end = require_typed_arg::<IntType>("range", &args, 1)?;

            let mut current = start;

            Ok(Value::List(
                std::iter::from_fn(move || {
                    if current == end {
                        None
                    } else {
                        let res = Some(current.clone());

                        current += 1;

                        res
                    }
                })
                .map(Value::from)
                .collect(),
            ))
        }),
    );

    env.define(
        Symbol::from("hash"),
        Value::NativeFunc(|_env, args| {
            let chunks = args.chunks(2);

            let mut hash = HashMap::new();

            for pair in chunks {
                let key = pair.get(0).unwrap();
                let value = pair.get(1);

                if let Some(value) = value {
                    hash.insert(key.clone(), value.clone());
                } else {
                    return Err(RuntimeError {
                        msg: format!("Must pass an even number of arguments to 'hash', because they're used as key/value pairs; found extra argument {}", key)
                    });
                }
            }

            Ok(Value::HashMap(Rc::new(RefCell::new(hash))))
        }),
    );

    env.define(
        Symbol::from("hash_get"),
        Value::NativeFunc(|_env, args| {
            let hash = require_typed_arg::<&HashMapRc>("hash_get", &args, 0)?;
            let key = require_arg("hash_get", &args, 1)?;

            Ok(hash
                .borrow()
                .get(key)
                .map(|v| v.clone())
                .unwrap_or(Value::NIL))
        }),
    );

    env.define(
        Symbol::from("hash_set"),
        Value::NativeFunc(|_env, args| {
            let hash = require_typed_arg::<&HashMapRc>("hash_set", &args, 0)?;
            let key = require_arg("hash_set", &args, 1)?;
            let value = require_arg("hash_set", &args, 2)?;

            hash.borrow_mut().insert(key.clone(), value.clone());

            Ok(Value::HashMap(hash.clone()))
        }),
    );

    env.define(
        Symbol::from("+"),
        Value::NativeFunc(|_env, args| {
            let first_arg = require_arg("+", &args, 1)?;

            let mut total = match first_arg {
                Value::Int(_) => Ok(Value::Int(0.into())),
                Value::Float(_) => Ok(Value::Float(0.0)),
                Value::String(_) => Ok(Value::String("".into())),
                _ => Err(RuntimeError {
                    msg: format!(
                        "Function \"+\" requires arguments to be numbers or strings; found {}",
                        first_arg
                    ),
                }),
            }?;

            for arg in args {
                total = (&total + &arg).map_err(|_| RuntimeError {
                    msg: format!(
                        "Function \"+\" requires arguments to be numbers or strings; found {}",
                        arg
                    ),
                })?;
            }

            Ok(total)
        }),
    );

    env.define(
        Symbol::from("-"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("-", &args, 0)?;
            let b = require_arg("-", &args, 1)?;

            (a - b).map_err(|_| RuntimeError {
                msg: String::from("Function \"-\" requires arguments to be numbers"),
            })
        }),
    );

    env.define(
        Symbol::from("*"),
        Value::NativeFunc(|_env, args| {
            let mut product = Value::Int(1.into());

            for arg in args {
                product = (&product * &arg).map_err(|_| RuntimeError {
                    msg: format!(
                        "Function \"*\" requires arguments to be numbers; found {}",
                        arg
                    ),
                })?;
            }

            Ok(product)
        }),
    );

    env.define(
        Symbol::from("/"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("/", &args, 0)?;
            let b = require_arg("/", &args, 1)?;

            (a / b).map_err(|_| RuntimeError {
                msg: String::from("Function \"/\" requires arguments to be numbers"),
            })
        }),
    );

    env.define(
        Symbol::from("truncate"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("truncate", &args, 0)?;
            let b = require_arg("truncate", &args, 1)?;

            if let (Ok(a), Ok(b)) = (
                TryInto::<IntType>::try_into(a),
                TryInto::<IntType>::try_into(b),
            ) {
                return Ok(Value::Int(a / b));
            }

            Err(RuntimeError {
                msg: String::from("Function \"truncate\" requires arguments to be integers"),
            })
        }),
    );

    env.define(
        Symbol::from("not"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("not", &args, 0)?;
            let a: bool = a.into();

            Ok(Value::from(!a))
        }),
    );

    env.define(
        Symbol::from("=="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("==", &args, 0)?;
            let b = require_arg("==", &args, 1)?;

            Ok(Value::from(a == b))
        }),
    );

    env.define(
        Symbol::from("!="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("!=", &args, 0)?;
            let b = require_arg("!=", &args, 1)?;

            Ok(Value::from(a != b))
        }),
    );

    env.define(
        Symbol::from("<"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("<", &args, 0)?;
            let b = require_arg("<", &args, 1)?;

            Ok(Value::from(a < b))
        }),
    );

    env.define(
        Symbol::from("<="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg("<=", &args, 0)?;
            let b = require_arg("<=", &args, 1)?;

            Ok(Value::from(a <= b))
        }),
    );

    env.define(
        Symbol::from(">"),
        Value::NativeFunc(|_env, args| {
            let a = require_arg(">", &args, 0)?;
            let b = require_arg(">", &args, 1)?;

            Ok(Value::from(a > b))
        }),
    );

    env.define(
        Symbol::from(">="),
        Value::NativeFunc(|_env, args| {
            let a = require_arg(">=", &args, 0)?;
            let b = require_arg(">=", &args, 1)?;

            Ok(Value::from(a >= b))
        }),
    );

    env.define(
        Symbol::from("eval"),
        Value::NativeFunc(|env, args| {
            let expr = require_arg("eval", &args, 0)?;

            eval(env, expr)
        }),
    );

    env.define(
        Symbol::from("apply"),
        Value::NativeFunc(|env, args| {
            let func = require_arg("apply", &args, 0)?;
            let params = require_typed_arg::<&List>("apply", &args, 1)?;

            eval(env, &Value::List(params.cons(func.clone())))
        }),
    );

    env
}

Find the environment where this key is defined, and update its value. Returns an Err if the symbol has not been defined anywhere in the hierarchy.

Examples found in repository?
src/model/env.rs (line 56)
51
52
53
54
55
56
57
58
59
60
61
62
    pub fn set(&mut self, key: Symbol, value: Value) -> Result<(), RuntimeError> {
        if self.entries.contains_key(&key) {
            self.entries.insert(key, value);
            Ok(())
        } else if let Some(parent) = &self.parent {
            parent.borrow_mut().set(key, value)
        } else {
            Err(RuntimeError {
                msg: format!("Tried to set value of undefined symbol \"{}\"", key),
            })
        }
    }
More examples
Hide additional examples
src/interpreter.rs (line 109)
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
fn eval_inner(
    env: Rc<RefCell<Env>>,
    expression: &Value,
    context: Context,
) -> Result<Value, RuntimeError> {
    if context.quoting {
        match expression {
            Value::List(list) if *list != List::NIL => match &list.car()? {
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    // do nothing, handle it down below
                }
                _ => {
                    return list
                        .into_iter()
                        .map(|el| eval_inner(env.clone(), &el, context))
                        .collect::<Result<List, RuntimeError>>()
                        .map(Value::List);
                }
            },
            _ => return Ok(expression.clone()),
        }
    }

    match expression {
        // look up symbol
        Value::Symbol(symbol) => env.borrow().get(symbol).ok_or_else(|| RuntimeError {
            msg: format!("\"{}\" is not defined", symbol),
        }),

        // s-expression
        Value::List(list) if *list != List::NIL => {
            match &list.car()? {
                // special forms
                Value::Symbol(Symbol(keyword)) if keyword == "comma" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(false))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "quote" => {
                    eval_inner(env, &list.cdr().car()?, context.quoting(true))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "define" || keyword == "set" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let value_expr = require_arg(keyword, args, 1)?;

                    let value = eval_inner(env.clone(), value_expr, context.found_tail(true))?;

                    if keyword == "define" {
                        env.borrow_mut().define(symbol.clone(), value.clone());
                    } else {
                        env.borrow_mut().set(symbol.clone(), value.clone())?;
                    }

                    Ok(value)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defmacro" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Macro(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "defun" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let symbol = require_typed_arg::<&Symbol>(keyword, args, 0)?;
                    let argnames_list = require_typed_arg::<&List>(keyword, args, 1)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr().cdr()));

                    let lambda = Value::Lambda(Lambda {
                        closure: env.clone(),
                        argnames,
                        body,
                    });

                    env.borrow_mut().define(symbol.clone(), lambda);

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "lambda" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let argnames_list = require_typed_arg::<&List>(keyword, args, 0)?;
                    let argnames = value_to_argnames(argnames_list.clone())?;
                    let body = Rc::new(Value::List(list.cdr().cdr()));

                    Ok(Value::Lambda(Lambda {
                        closure: env,
                        argnames,
                        body,
                    }))
                }

                Value::Symbol(Symbol(keyword)) if keyword == "let" => {
                    let let_env = Rc::new(RefCell::new(Env::extend(env)));

                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let declarations = require_typed_arg::<&List>(keyword, args, 0)?;

                    for decl in declarations.into_iter() {
                        let decl = &decl;

                        let decl_cons: &List = decl.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected declaration clause, found {}", decl),
                        })?;
                        let symbol = &decl_cons.car()?;
                        let symbol: &Symbol = symbol.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected symbol for let declaration, found {}", symbol),
                        })?;
                        let expr = &decl_cons.cdr().car()?;

                        let result = eval_inner(let_env.clone(), expr, context.found_tail(true))?;
                        let_env.borrow_mut().define(symbol.clone(), result);
                    }

                    let body = &Value::List(list.cdr().cdr());
                    let body: &List = body.try_into().map_err(|_| RuntimeError {
                        msg: format!(
                            "Expected expression(s) after let-declarations, found {}",
                            body
                        ),
                    })?;

                    eval_block_inner(let_env, body.into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "begin" => {
                    eval_block_inner(env, list.cdr().into_iter(), context)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "cond" => {
                    let clauses = list.cdr();

                    for clause in clauses.into_iter() {
                        let clause = &clause;

                        let clause: &List = clause.try_into().map_err(|_| RuntimeError {
                            msg: format!("Expected conditional clause, found {}", clause),
                        })?;

                        let condition = &clause.car()?;
                        let then = &clause.cdr().car()?;

                        if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                            return eval_inner(env, then, context);
                        }
                    }

                    Ok(Value::NIL)
                }

                Value::Symbol(Symbol(keyword)) if keyword == "if" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();

                    let condition = require_arg(keyword, args, 0)?;
                    let then_expr = require_arg(keyword, args, 1)?;
                    let else_expr = require_arg(keyword, args, 2).ok();

                    if eval_inner(env.clone(), condition, context.found_tail(true))?.into() {
                        eval_inner(env, then_expr, context)
                    } else {
                        else_expr
                            .map(|expr| eval_inner(env, &expr, context))
                            .unwrap_or(Ok(Value::NIL))
                    }
                }

                Value::Symbol(Symbol(keyword)) if keyword == "and" || keyword == "or" => {
                    let args = &list.cdr().into_iter().collect::<Vec<Value>>();
                    let is_or = keyword.as_str() == "or";

                    let mut last_result: Option<Value> = None;
                    for arg in args {
                        let result = eval_inner(env.clone(), arg, context.found_tail(true))?;
                        let truthy: bool = (&result).into();

                        if is_or == truthy {
                            return Ok(result);
                        }

                        last_result = Some(result);
                    }

                    Ok(if let Some(last_result) = last_result {
                        last_result
                    } else {
                        // there were zero arguments
                        (!is_or).into()
                    })
                }

                // function call or macro expand
                _ => {
                    let mut func_or_macro =
                        eval_inner(env.clone(), &list.car()?, context.found_tail(true))?;

                    if matches!(func_or_macro, Value::Macro(_)) {
                        let args = list.into_iter().skip(1).collect::<Vec<Value>>();

                        let expanded =
                            call_function_or_macro(env.clone(), &mut func_or_macro, args)?;

                        eval_inner(env.clone(), &expanded, Context::new())
                    } else {
                        let args = list
                            .into_iter()
                            .skip(1)
                            .map(|car| eval_inner(env.clone(), &car, context.found_tail(true)))
                            .collect::<Result<Vec<Value>, RuntimeError>>()?;

                        if !context.found_tail && context.in_func {
                            Ok(Value::TailCall {
                                func: Rc::new(func_or_macro),
                                args,
                            })
                        } else {
                            let mut res =
                                call_function_or_macro(env.clone(), &mut func_or_macro, args);

                            while let Ok(Value::TailCall { func, args }) = res {
                                res = call_function_or_macro(env.clone(), func.as_ref(), args);
                            }

                            res
                        }
                    }
                }
            }
        }

        // plain value
        _ => Ok(expression.clone()),
    }
}

Delete the nearest (going upwards) definition of this key

Examples found in repository?
src/model/env.rs (line 69)
65
66
67
68
69
70
71
    pub fn undefine(&mut self, key: &Symbol) {
        if self.entries.contains_key(key) {
            self.entries.remove(key);
        } else if let Some(parent) = &self.parent {
            parent.borrow_mut().undefine(key);
        }
    }

Trait Implementations§

Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.