Repository navigation
Expand file tree
/
Copy patheval.rs
More file actions
4038 lines (3845 loc) · 155 KB
/
Copy patheval.rs
File metadata and controls
4038 lines (3845 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The evaluator. This is the heart of the interpreter.
//!
//! ## What you'll learn here
//!
//! - **Tree-walking evaluation**: how to turn parsed source (which in
//! nscheme is a [`Value`]) into a result by recursive descent over
//! the syntax tree.
//! - **The "step loop" trick**: instead of writing a recursive
//! `fn eval(expr, env) -> Value`, we run a *loop* over a small
//! `Step` state machine with an explicit `Vec<Frame>` stack of
//! pending work. That shape pays for itself many times over:
//! - **Tail-call optimization** (R7RS §3.5) becomes free: a tail
//! position transitions `Step::Eval(tail_expr, env)` *without*
//! pushing a frame.
//! - **First-class continuations** (`call/cc`) become two dozen
//! lines: a continuation is a `frames.clone()`, and invoking
//! it is `frames = saved`. See [ADR
//! 0004](../../docs/0004-continuations.md).
//! - **Exception handling**, `dynamic-wind`, and parameter
//! restoration all use the same `Frame` enum. See [ADR
//! 0005](../../docs/0005-exception-handling.md).
//! - **R7RS special forms**: how `quote` / `if` / `lambda` / `define`
//! / `set!` / `begin` / the derived forms (`let`, `cond`, `do`, …)
//! are dispatched and what each one's evaluation rule actually is.
//!
//! ## Read in this order
//!
//! 1. The [`Step`] and [`Frame`] enums below — they define the
//! state machine. Don't skim. The rest of the file is a catalog
//! of how to transition between these states.
//! 2. The [`eval`] function — five match arms, one per `Step`. The
//! whole architecture is visible in those forty lines.
//! 3. `step_eval` — the syntax dispatcher; one arm per special
//! form.
//! 4. `step_apply` — the procedure dispatcher; one arm per
//! [`Procedure`](crate::value::Procedure) variant.
//! 5. `resume` — the frame dispatcher; one arm per [`Frame`].
//!
//! Each `step_*_form` helper handles one special form in isolation
//! and is short enough to read on its own. The big bodies are
//! `step_eval` and `resume`; both are dispatch tables.
//!
//! ## Tail positions (the discipline this module enforces)
//!
//! R7RS §3.5 specifies which expression positions must be in tail
//! position. The rule we enforce here: a sub-evaluation is in tail
//! position if and only if no frame is pushed for it.
//!
//! - The chosen branch of `if` is in tail position.
//! - The last expression of `begin` (and of a `lambda` body) is in
//! tail position; earlier expressions are not.
//! - The body expression of a procedure call is in tail position
//! with respect to its caller.
//!
//! Argument evaluation is *not* in tail position. `(f (g x))`
//! evaluates `(g x)` under a frame so the value can be collected as
//! an argument to `f`.
//!
//! See also: [ADR 0001](../../docs/0001-tree-walking-interpreter.md)
//! for the long-form architectural rationale.
// Several internal helpers take `Value`/`EnvRef` by value so they can
// consume and decompose them without forcing the caller to clone. The
// alternative — taking `&Value` — would push the clones into the
// special-form code where they aren't any cheaper. Allow the lint at
// module scope rather than spraying `#[allow]` on each helper.
#![allow(clippy::needless_pass_by_value)]
// step_eval is a single dispatch table per the architecture in
// docs/0001; splitting it further to satisfy clippy's line-count cap
// would obscure the dispatch.
#![allow(clippy::too_many_lines)]
use std::collections::HashMap;
use std::rc::Rc;
use thiserror::Error;
use crate::env::{Env, EnvRef};
use crate::parse::{ParseError, parse_program};
use crate::value::{ErrorKind, ErrorObject, Pair, Procedure, RuntimeError, Symbol, Value};
/// Convert a [`RuntimeError`] (raised by a primitive) into a Scheme
/// error-object Value, so it can flow through the R7RS exception
/// mechanism (with-exception-handler / guard). The error kind is
/// preserved so `file-error?` and `read-error?` work on the
/// resulting value.
fn runtime_error_to_value(e: RuntimeError) -> Value {
let kind = match &e {
RuntimeError::FileError(_) => ErrorKind::File,
RuntimeError::ReadError(_) => ErrorKind::Read,
_ => ErrorKind::User,
};
Value::ErrorObject(Rc::new(ErrorObject {
message: format!("{e}"),
irritants: Vec::new(),
kind,
}))
}
/// Errors raised during evaluation. Wraps [`RuntimeError`] (primitive /
/// lookup failures) and [`ParseError`] for convenience APIs that go
/// straight from source to result.
#[derive(Clone, Debug, Error)]
pub enum EvalError {
#[error("{0}")]
Runtime(#[from] RuntimeError),
#[error("{0}")]
Parse(#[from] ParseError),
#[error("malformed special form `{form}`: {message}")]
MalformedForm { form: &'static str, message: String },
/// An uncaught `raise` — bubbled out past the outermost handler.
/// The payload is whatever value was passed to `raise`.
#[error("unhandled raise: {0}")]
Raised(Value),
}
impl EvalError {
fn malformed(form: &'static str, message: impl Into<String>) -> Self {
Self::MalformedForm {
form,
message: message.into(),
}
}
}
// ---------------------------------------------------------------------
// Step + Frame state
// ---------------------------------------------------------------------
//
// The evaluator is a state machine. The `Step` enum names the four
// transitions the machine can make on any given iteration; the
// `Frame` enum names the *pending work* that's waiting on a
// sub-evaluation to complete. The eval loop in `eval()` is the
// dispatch:
//
// loop {
// Step::Eval(expr, env) -> step_eval(...) (one form -> next Step)
// Step::Apply(proc, args) -> step_apply(...) (one call -> next Step)
// Step::Return(value) -> resume(top_frame, v) (next Step from pending work)
// Step::InvokeContinuation -> restore saved frames
// Step::Raise(exc, cont?) -> walk frames for handler
// }
//
// If `Step::Return` pops an empty frame stack, evaluation is done
// and the result is returned. Every other transition picks back up
// inside the loop.
//
// The `Frame` enum is bigger because every sub-evaluation needs to
// remember what to do with its result. There's one variant per
// flavor of pending work: "the test of an `if` is evaluating",
// "argument 3 of a call is evaluating", "an exception handler is
// installed", and so on. Each variant carries an `env` so the
// resume happens in the right lexical scope.
/// One transition of the evaluator loop.
enum Step {
/// Evaluate this expression in this environment.
Eval(Value, EnvRef),
/// Apply this procedure to these argument values.
Apply(Value, Vec<Value>),
/// A sub-evaluation produced this value; resume the next frame.
Return(Value),
/// Replace the evaluator's frame stack with the captured one and
/// resume by returning `value`. Used to invoke a continuation
/// captured by `call/cc`.
InvokeContinuation(Vec<Frame>, Value),
/// Propagate an exception up the frame stack until an
/// [`Frame::ExceptionHandler`] catches it. If none catches, the
/// `eval()` function returns an `EvalError::Raised(value)`. The
/// boolean is `true` for `raise-continuable`: when set, a handler
/// that returns normally substitutes its result for the raise
/// expression. Otherwise the handler's result is re-raised.
Raise(Value, bool),
}
/// Pending work that resumes when a sub-evaluation returns.
///
/// Every variant carries an `env` so it can resume in the correct
/// lexical scope.
#[derive(Clone)]
pub enum Frame {
/// `(if test conseq alt)` — `test` is currently evaluating.
IfBranch {
conseq: Value,
alt: Option<Value>,
env: EnvRef,
},
/// `(begin e1 e2 … en)` — `e_i` is currently evaluating, and the
/// remaining (non-empty) tail expressions are `rest`. The last
/// expression is reached by *not* pushing this frame for it.
BeginRest { rest: Vec<Value>, env: EnvRef },
/// `(define name <expr>)` — `<expr>` is currently evaluating.
DefineBind { name: Symbol, env: EnvRef },
/// `(set! name <expr>)` — `<expr>` is currently evaluating.
SetBind { name: Symbol, env: EnvRef },
/// `(op a1 a2 …)` — the operator `op` is currently evaluating;
/// `args` holds the unevaluated argument expressions.
CallOp { args: Vec<Value>, env: EnvRef },
/// `(op a1 a2 …)` — the operator is `proc`, we've already
/// evaluated `evaluated`, and `remaining[0]` is currently
/// evaluating; the rest of `remaining` is queued.
CallArg {
proc: Value,
evaluated: Vec<Value>,
remaining: Vec<Value>,
env: EnvRef,
},
/// `(cond (t b…) … )` — currently evaluating the test of `clause`;
/// `remaining_clauses` holds the as-yet-unexamined clauses.
CondClause {
clause: Value,
remaining_clauses: Vec<Value>,
env: EnvRef,
},
/// `((test => proc-expr))` — the test was truthy and produced
/// `test_value`; `proc-expr` is currently evaluating.
CondArrow { test_value: Value, env: EnvRef },
/// `(and e1 … en)` — short-circuit AND. The currently-evaluating
/// expression is non-last (we never push this frame for the tail
/// expression).
AndNext { remaining: Vec<Value>, env: EnvRef },
/// `(or e1 … en)` — short-circuit OR. The currently-evaluating
/// expression is non-last.
OrNext { remaining: Vec<Value>, env: EnvRef },
/// An exception handler installed by `with-exception-handler`.
/// When a `Step::Raise(v, _)` propagates up, the handler is
/// invoked with `v`. Whether the handler's return value is
/// substituted (for `raise-continuable`) or re-raised (for plain
/// `raise`) is decided by the `continuable` flag carried by the
/// raise itself, not the handler.
ExceptionHandler { handler: Value, env: EnvRef },
/// Helper frame: when a non-continuable handler returns, re-raise
/// the value to the next outer handler.
ReRaise,
/// Pending raise. When the operand of `raise` /
/// `raise-continuable` finishes evaluating, this frame fires
/// `Step::Raise(value, continuable)`.
RaiseAfter { continuable: bool },
/// Helper for `with-exception-handler`: when the handler
/// expression has finished evaluating, install it as an
/// `ExceptionHandler` frame and call the thunk.
InstallHandler { thunk_expr: Value, env: EnvRef },
/// Restore parameter values when a `parameterize` form's body
/// completes (or unwinds via raise — see `Step::Raise` handling).
ParameterRestore {
saved: Vec<(Rc<crate::value::ParameterCell>, Value)>,
},
/// `dynamic-wind` extent marker. The `before` and `after` thunks
/// are kept so a `call/cc` jump that crosses this frame can
/// re-enter (`before`) or leave (`after`) the wind correctly.
/// `id` distinguishes nested winds across continuation
/// invocations.
DynamicWind {
id: u64,
before: Value,
after: Value,
},
/// `dynamic-wind` helper: after the user thunk returns, fire
/// the `after` thunk. We save the thunk's result first (the
/// frame transitions to `DynamicWindFinish` once `after` runs).
DynamicWindAfter { after: Value },
/// `dynamic-wind` helper: `after` has finished; return the
/// previously-saved thunk result.
DynamicWindFinish { thunk_result: Value },
/// `dynamic-wind` helper: after the `before` thunk returns,
/// install the `DynamicWind` marker and apply the body thunk.
DynamicWindCallThunk {
id: u64,
thunk: Value,
before: Value,
after: Value,
},
/// Helper frame for continuation invocation across dynamic-wind
/// boundaries (R7RS §6.10). Each step pops the next `after` (or
/// `before` when afters are empty) and applies it; once both
/// queues drain, the saved frames + value get reinstalled.
WindJump {
afters: Vec<Value>,
befores: Vec<Value>,
target_frames: Vec<Frame>,
target_value: Value,
},
}
// ---------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------
thread_local! {
/// Call-chain backtrace captured at the most recent error exit of
/// [`eval`] (bead nscheme-tn3). Innermost call first. The CLI reads
/// it via [`take_backtrace`] to annotate an error with "called from"
/// context. It's the pending non-tail call chain — tail calls leave
/// no `CallArg` frame, so deep tail recursion correctly yields a
/// short trace.
static BACKTRACE: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Take (and clear) the backtrace recorded by the last failed `eval`.
/// Empty if the last evaluation succeeded or failed before any call.
#[must_use]
pub fn take_backtrace() -> Vec<String> {
BACKTRACE.with(|b| std::mem::take(&mut *b.borrow_mut()))
}
/// Render a procedure value for a backtrace line.
fn describe_callee(v: &Value) -> String {
match v {
Value::Procedure(p) => p.name().to_string(),
other => format!("{other}"),
}
}
/// Record the pending call chain (innermost first) from `frames` into
/// the thread-local backtrace. Reads `CallArg` frames, whose `proc` is
/// the procedure whose argument evaluation was in progress.
fn capture_backtrace(frames: &[Frame]) {
let trace: Vec<String> = frames
.iter()
.rev()
.filter_map(|f| {
if let Frame::CallArg { proc, .. } = f {
Some(describe_callee(proc))
} else {
None
}
})
.collect();
BACKTRACE.with(|b| *b.borrow_mut() = trace);
}
/// Evaluate one expression in `env`. The expression is a runtime
/// [`Value`] produced by [`crate::parse::parse_one`] or constructed
/// programmatically.
///
/// This is the entire evaluator in forty lines. Everything else in
/// the file is a helper that produces or consumes a [`Step`].
pub fn eval(expr: Value, env: EnvRef) -> Result<Value, EvalError> {
// Two pieces of state: the next transition to make, and the
// continuation stack. `frames` IS the call stack — a call/cc
// can snapshot it (`frames.clone()`) and a continuation
// invocation can replace it (`frames = saved`).
let mut state = Step::Eval(expr, env);
let mut frames: Vec<Frame> = Vec::new();
// On any error exit, snapshot the pending call chain for a backtrace
// (nscheme-tn3) before unwinding loses it.
macro_rules! try_step {
($e:expr) => {
match $e {
Ok(step) => step,
Err(err) => {
capture_backtrace(&frames);
return Err(err);
}
}
};
}
loop {
state = match state {
// Evaluate the expression. Returns the next Step —
// possibly `Eval` again (we recursed into a sub-expr),
// `Apply` (the expression was a call), `Return` (the
// expression was self-evaluating), or `Raise`.
Step::Eval(expr, env) => try_step!(step_eval(expr, env, &mut frames)),
// Apply a procedure to args. Returns the next Step the
// procedure produced.
Step::Apply(proc, args) => try_step!(step_apply(proc, args, &mut frames)),
// A sub-evaluation finished. Pop the top frame to
// decide what's next. If there isn't one, the whole
// evaluation is done and `value` is the result.
Step::Return(value) => match frames.pop() {
Some(frame) => try_step!(resume(frame, value, &mut frames)),
None => return Ok(value),
},
// A captured continuation is being invoked. Per ADR
// 0004, that's a frame-stack replacement — but it's
// not quite a one-liner because `dynamic-wind`
// demands we fire `before`/`after` thunks on the way
// out of the current extents and into the target
// extents.
Step::InvokeContinuation(saved, value) => {
// R7RS §6.10: before/after thunks of any
// dynamic-wind extents that we leave/enter must
// fire. Diff current and target wind chains, then
// schedule the dance via Frame::WindJump.
let cur_winds = wind_chain(&frames);
let tgt_winds = wind_chain(&saved);
let lca = wind_lca(&cur_winds, &tgt_winds);
// afters: from current[lca..] innermost first
let afters: Vec<Value> =
cur_winds[lca..].iter().rev().map(|w| w.2.clone()).collect();
// befores: from target[lca..] outermost first
let befores: Vec<Value> = tgt_winds[lca..].iter().map(|w| w.1.clone()).collect();
if afters.is_empty() && befores.is_empty() {
frames = saved;
Step::Return(value)
} else {
// Start the dance from the current frame stack
// — the WindJump frame runs each thunk in turn,
// then installs `saved` and returns `value`.
frames.push(Frame::WindJump {
afters,
befores,
target_frames: saved,
target_value: value,
});
Step::Return(Value::Unspecified)
}
}
// An exception is propagating. See ADR 0005 for the
// architecture. The short version: walk back through
// the frame stack until we find a handler (installed
// by `with-exception-handler` / `guard`), unwind the
// frames we passed, and apply the handler.
Step::Raise(value, continuable) => {
// Walk the frame stack looking for an ExceptionHandler.
// For raise-continuable we preserve the frames between
// the raise and the handler so the handler's return
// value substitutes for the raise expression. For plain
// raise we discard them and push ReRaise so the
// handler's return is re-raised. ParameterRestore
// frames fire as we unwind so parameterize's old
// values survive uncaught raises.
let mut popped: Vec<Frame> = Vec::new();
let mut handler_found = None;
while let Some(frame) = frames.pop() {
if let Frame::ExceptionHandler { handler, env: _ } = frame {
handler_found = Some(handler);
break;
}
if let Frame::ParameterRestore { saved } = &frame {
for (cell, old) in saved {
*cell.value.borrow_mut() = old.clone();
}
}
popped.push(frame);
}
let Some(handler) = handler_found else {
// No handler: this raise escapes. Snapshot the call
// chain for a backtrace, then surface it.
capture_backtrace(&popped);
return Err(EvalError::Raised(value));
};
if continuable {
// Restore the frames between handler and raise so the
// handler's result resumes at the raise expression's
// position.
for f in popped.into_iter().rev() {
frames.push(f);
}
} else {
frames.push(Frame::ReRaise);
}
Step::Apply(handler, vec![value])
}
};
}
}
/// Convenience: lex, parse, and evaluate every top-level datum in
/// `source` in `env`. Returns the value of the last expression (or
/// [`Value::Unspecified`] if `source` is empty).
///
/// All top-level datums share a single evaluator loop (wrapped in an
/// implicit `begin`) so that continuations captured by `call/cc` can
/// span across top-level forms — invoking a saved continuation jumps
/// back to whatever was about to happen at capture time, even if a
/// later top-level form has since started evaluating.
pub fn eval_source(source: &str, env: EnvRef) -> Result<Value, EvalError> {
// Track this source so runtime errors can report a `line:col`
// location (nscheme-tn3); parsing populates the per-pair span map.
crate::diagnostic::begin_source(source);
let datums = parse_program(source)?;
if datums.is_empty() {
return Ok(Value::Unspecified);
}
let mut begin_items = vec![Value::Symbol(Symbol::intern("begin"))];
begin_items.extend(datums);
eval(Value::list_from(begin_items), env)
}
// ---------------------------------------------------------------------
// step_eval
// ---------------------------------------------------------------------
//
// The syntax dispatcher. Given a [`Value`] that represents one
// Scheme expression, decide what to do next. Self-evaluating atoms
// return immediately; symbol references look up the env; pair-headed
// forms dispatch on the head identifier — first checking whether
// the head is a [`Value::SyntaxRef`] (a macro-introduced
// identifier — see `macros.rs`), then checking the special-form
// table, then trying the env for a procedure or macro.
//
// Reading note: this is one of the three big match tables in the
// file (the others are `step_apply` for procedure dispatch and
// `resume` for frame dispatch). Each arm in the special-form match
// hands off to a `step_X_form` helper. The helpers are in the
// Special forms / Derived forms sections below.
fn step_eval(expr: Value, env: EnvRef, frames: &mut Vec<Frame>) -> Result<Step, EvalError> {
// Note the form we're entering so an error can report its location
// (nscheme-tn3). Pairs without a recorded span (macro output) leave
// the current location at the nearest enclosing recorded form.
if let Value::Pair(p) = &expr {
crate::diagnostic::note_current(Rc::as_ptr(p) as usize);
}
// Self-evaluating values.
match &expr {
Value::Bool(_)
| Value::Char(_)
| Value::Int(_)
| Value::BigInt(_)
| Value::Rational(_)
| Value::Float(_)
| Value::Complex(_)
| Value::String(_)
| Value::Vector(_)
| Value::Bytevector(_)
| Value::Eof
| Value::Unspecified
| Value::Procedure(_)
| Value::Port(_)
| Value::Macro(_)
| Value::ErrorObject(_)
| Value::Promise(_)
| Value::Values(_)
| Value::Record { .. } => return Ok(Step::Return(expr)),
Value::Symbol(sym) => {
let v = env.lookup(sym).ok_or_else(|| {
EvalError::Runtime(RuntimeError::Undefined(sym.name().to_string()))
})?;
return Ok(Step::Return(v));
}
Value::SyntaxRef {
name,
scope,
env: def_env,
} => {
// Macro-introduced reference. R7RS hygiene §4.3.2:
// 1. The expansion's own hygienic name first: if this
// identifier was bound by *this* expansion (a `let`/
// `lambda`/named-`let` binder the template introduced),
// it lives under `name\u{1}scope` and shadows all else.
// 2. The macro's definition-site env, so a free reference
// resolves where the macro was written, not where it
// was called (user shadowing at the call site is
// invisible).
// 3. The call-site env by bare name, the last-ditch case
// for identifiers a surrounding `let-syntax` bound.
let v = env
.lookup(&hygienic_name(name, *scope))
.or_else(|| def_env.lookup(name))
.or_else(|| env.lookup(name))
.ok_or_else(|| {
EvalError::Runtime(RuntimeError::Undefined(name.name().to_string()))
})?;
return Ok(Step::Return(v));
}
Value::Null => {
// `()` is not a valid expression in R7RS; evaluating it
// is an error.
return Err(EvalError::malformed(
"application",
"() is not a procedure call",
));
}
Value::Pair(_) => { /* fall through */ }
}
// Compound expression: a pair. Inspect the head.
let (head, tail) = expr.as_pair().expect("must be a pair");
// A macro-introduced free identifier carries its definition-site
// environment. R7RS hygiene §4.3.2: head dispatch checks
// (1) the def-site env (handles user shadowing at the call
// site — shadowed bindings don't affect us),
// (2) the special-form name table (so `(SR:if …)` stays the
// `if` keyword even when the call-site env shadowed it),
// (3) the call-site env (so a binding the macro itself
// introduced via the template — e.g. through `let-syntax`
// — remains visible to template references).
if let Value::SyntaxRef {
name,
scope,
env: def_env,
} = &head
{
// (0) A binding this expansion introduced (its hygienic name):
// e.g. the named-`let` loop variable a template brought in.
// It must be checked first, since such a binding shadows.
if let Some(value) = env.lookup(&hygienic_name(name, *scope)) {
if let Value::Macro(rules) = value {
let args = collect_list(&tail)
.map_err(|()| EvalError::malformed("macro", "argument list must be proper"))?;
let call_form = Value::cons(Value::Symbol(name.clone()), Value::list_from(args));
let expanded = crate::macros::expand(&rules, &call_form)?;
return Ok(Step::Eval(expanded, env));
}
return step_call(value, tail, env, frames);
}
if let Some(value) = def_env.lookup(name) {
if let Value::Macro(rules) = value {
let args = collect_list(&tail)
.map_err(|()| EvalError::malformed("macro", "argument list must be proper"))?;
let call_form = Value::cons(Value::Symbol(name.clone()), Value::list_from(args));
let expanded = crate::macros::expand(&rules, &call_form)?;
return Ok(Step::Eval(expanded, env));
}
return step_call(value, tail, env, frames);
}
if is_special_form_name(name.name()) {
return dispatch_special_form(name, tail, env, frames);
}
if let Some(value) = env.lookup(name) {
if let Value::Macro(rules) = value {
let args = collect_list(&tail)
.map_err(|()| EvalError::malformed("macro", "argument list must be proper"))?;
let call_form = Value::cons(Value::Symbol(name.clone()), Value::list_from(args));
let expanded = crate::macros::expand(&rules, &call_form)?;
return Ok(Step::Eval(expanded, env));
}
return step_call(value, tail, env, frames);
}
return Err(EvalError::Runtime(RuntimeError::Undefined(
name.name().to_string(),
)));
}
if let Value::Symbol(sym) = &head {
// R7RS-style shadowing: a binding in the lexical env always
// wins over the same-named special form. So `(let ((let -))
// (let 5))` does *not* invoke the `let` keyword — it calls
// `-`. Only fall through to special-form dispatch when the
// identifier is unbound (or bound to a Macro, which we
// dispatch separately below).
if let Some(value) = env.lookup(sym) {
if let Value::Macro(rules) = value {
let args = collect_list(&tail)
.map_err(|()| EvalError::malformed("macro", "argument list must be proper"))?;
let call_form = Value::cons(Value::Symbol(sym.clone()), Value::list_from(args));
let expanded = crate::macros::expand(&rules, &call_form)?;
return Ok(Step::Eval(expanded, env));
}
return step_call(value, tail, env, frames);
}
return dispatch_special_form(sym, tail, env, frames);
}
step_call(head, tail, env, frames)
}
/// True if `name` is one of the evaluator's syntactic keywords.
/// Used by `SyntaxRef` head dispatch to decide whether to treat
/// an unbound macro-introduced identifier as a keyword (e.g. `let`,
/// `if`) before falling back to call-site env lookup.
fn is_special_form_name(name: &str) -> bool {
matches!(
name,
"quote"
| "if"
| "lambda"
| "define"
| "set!"
| "begin"
| "let"
| "let*"
| "letrec"
| "letrec*"
| "cond"
| "case"
| "and"
| "or"
| "when"
| "unless"
| "do"
| "quasiquote"
| "define-syntax"
| "let-syntax"
| "letrec-syntax"
| "define-library"
| "import"
| "cond-expand"
| "call/cc"
| "call-with-current-continuation"
| "delay"
| "delay-force"
| "lazy"
| "case-lambda"
| "define-values"
| "define-record-type"
| "let-values"
| "let*-values"
| "parameterize"
| "raise"
| "raise-continuable"
| "with-exception-handler"
| "guard"
| "dynamic-wind"
)
}
/// Dispatch a symbol-headed form as a special form. Used when the
/// head is a bare Symbol with no env binding *and* when a macro-
/// introduced `SyntaxRef` resolves to no binding in its def-site
/// env (the usual case for R7RS keywords like `let`, `if`, `lambda`,
/// …, which aren't real bindings).
fn dispatch_special_form(
sym: &Symbol,
tail: Value,
env: EnvRef,
frames: &mut Vec<Frame>,
) -> Result<Step, EvalError> {
match sym.name() {
"quote" => step_quote(&tail),
"if" => step_if(tail, env, frames),
"lambda" => step_lambda(tail, env, None),
"define" => step_define(tail, env, frames),
"set!" => step_set(tail, env, frames),
"begin" => step_begin(tail, env, frames),
"let" => step_let(tail, env, frames),
"let*" => step_let_star(tail, env, frames),
"letrec" | "letrec*" => step_letrec(tail, env, frames),
"cond" => step_cond(tail, env, frames),
"case" => step_case(tail, env, frames),
"and" => step_and(tail, env, frames),
"or" => step_or(tail, env, frames),
"when" => step_when(tail, env, frames),
"unless" => step_unless(tail, env, frames),
"do" => step_do(tail, env, frames),
"quasiquote" => step_quasiquote(&tail, env),
"define-syntax" => step_define_syntax(tail, env),
"let-syntax" | "letrec-syntax" => step_let_syntax(tail, env, frames),
"define-library" => step_define_library(tail, env),
"import" => step_import(tail, env),
"cond-expand" => step_cond_expand(tail, env, frames),
"call/cc" | "call-with-current-continuation" => step_call_cc(tail, env, frames),
"delay" | "delay-force" | "lazy" => step_delay(tail, env),
"case-lambda" => step_case_lambda(tail, env),
"define-values" => step_define_values(tail, env),
"define-record-type" => step_define_record_type(tail, env),
"let-values" => step_let_values(tail, env, frames, false),
"let*-values" => step_let_values(tail, env, frames, true),
"parameterize" => step_parameterize(tail, env, frames),
"raise" => step_raise_with_frames(tail, env, false, frames),
"raise-continuable" => step_raise_with_frames(tail, env, true, frames),
"with-exception-handler" => step_with_exception_handler_real(tail, env, frames),
"guard" => step_guard_real(tail, env, frames),
"dynamic-wind" => step_dynamic_wind(tail, env, frames),
_ => Err(EvalError::Runtime(RuntimeError::Undefined(
sym.name().to_string(),
))),
}
}
/// `(define-syntax name (syntax-rules ...))` — install a macro.
fn step_define_syntax(tail: Value, env: EnvRef) -> Result<Step, EvalError> {
let (name_val, rest) = tail
.as_pair()
.ok_or_else(|| EvalError::malformed("define-syntax", "expected name and rules"))?;
let name = name_val
.as_identifier()
.ok_or_else(|| EvalError::malformed("define-syntax", "name must be a symbol"))?
.clone();
let mut iter = ListIter::new(rest);
let rules_form = iter
.next()
.ok_or_else(|| EvalError::malformed("define-syntax", "expected a syntax-rules form"))??;
let mut rules = crate::macros::parse_syntax_rules(&rules_form)?;
rules.def_env = Some(env.clone());
env.define(name, Value::Macro(Rc::new(rules)));
Ok(Step::Return(Value::Unspecified))
}
/// `(let-syntax ((name (syntax-rules ...)) ...) body...)`. Binds the
/// macros in a fresh child env and evaluates the body.
/// `letrec-syntax` is treated the same — `syntax-rules` can't reference
/// other macros being defined in the same form anyway.
fn step_let_syntax(tail: Value, env: EnvRef, frames: &mut Vec<Frame>) -> Result<Step, EvalError> {
let (bindings_form, body_tail) = tail
.as_pair()
.ok_or_else(|| EvalError::malformed("let-syntax", "expected bindings and body"))?;
let bindings = collect_list(&bindings_form)
.map_err(|()| EvalError::malformed("let-syntax", "bindings must be a proper list"))?;
let body = collect_list(&body_tail)
.map_err(|()| EvalError::malformed("let-syntax", "body must be a proper list"))?;
if body.is_empty() {
return Err(EvalError::malformed("let-syntax", "body must not be empty"));
}
let scope = Env::extend(env);
for b in bindings {
let parts = collect_list(&b)
.map_err(|()| EvalError::malformed("let-syntax", "each binding must be a list"))?;
if parts.len() != 2 {
return Err(EvalError::malformed(
"let-syntax",
"binding must be (name (syntax-rules ...))",
));
}
let name = parts[0]
.as_identifier()
.ok_or_else(|| EvalError::malformed("let-syntax", "binding name must be a symbol"))?
.clone();
let mut rules = crate::macros::parse_syntax_rules(&parts[1])?;
// For letrec-syntax we'd want the def_env to include
// sibling macros, but R7RS forbids forward-referencing
// siblings in syntax-rules anyway, and our parser doesn't
// distinguish let-syntax from letrec-syntax. Use the inner
// scope so a referenced binding *introduced inside the
// let-syntax body* (rare) at least resolves; for the
// common case, the parent env is what matters.
rules.def_env = Some(scope.clone());
scope.define(name, Value::Macro(Rc::new(rules)));
}
Ok(eval_sequence(body, scope, frames))
}
/// `(define-library (name) decl...)`. Each `decl` is one of:
/// `(export …)`, `(import …)`, `(begin …)`, `(include "file")`,
/// `(cond-expand …)`.
fn step_define_library(tail: Value, env: EnvRef) -> Result<Step, EvalError> {
let (name_form, decls_tail) = tail
.as_pair()
.ok_or_else(|| EvalError::malformed("define-library", "expected name and decls"))?;
let lib_name = crate::library::parse_library_name(&name_form)?;
let decls = collect_list(&decls_tail)
.map_err(|()| EvalError::malformed("define-library", "decls must be a proper list"))?;
let lib_env = crate::env::Env::extend(env.clone());
// Each export is (external-name, internal-name); they differ only
// for `(rename internal external)` specs.
let mut exports: Vec<(Symbol, Symbol)> = Vec::new();
process_library_decls(&decls, &lib_env, &mut exports)?;
// Collect exported bindings into a registry entry. We store the
// *cells*, not their current values, so importers share the
// library's mutable bindings rather than copying them (bead
// nscheme-q1c).
let mut bindings: HashMap<Symbol, crate::env::Cell> = HashMap::new();
for (external, internal) in exports {
let cell = lib_env.cell(&internal).ok_or_else(|| {
EvalError::malformed("define-library", "exported name was not defined")
})?;
bindings.insert(external, cell);
}
crate::library::register_library(lib_name, bindings);
Ok(Step::Return(Value::Unspecified))
}
fn process_library_decls(
decls: &[Value],
lib_env: &EnvRef,
exports: &mut Vec<(Symbol, Symbol)>,
) -> Result<(), EvalError> {
for decl in decls {
let parts = collect_list(decl)
.map_err(|()| EvalError::malformed("define-library", "decl must be a list"))?;
if parts.is_empty() {
continue;
}
let Value::Symbol(head) = &parts[0] else {
return Err(EvalError::malformed(
"define-library",
"decl must start with an identifier",
));
};
match head.name() {
"export" => {
for e in &parts[1..] {
match e {
// Bare identifier: external name == internal name.
Value::Symbol(s) => exports.push((s.clone(), s.clone())),
// R7RS §5.6.1 (rename <internal> <external>): export
// the binding named <internal> under the name <external>.
Value::Pair(_) => {
let spec = collect_list(e).map_err(|()| {
EvalError::malformed("export", "malformed export spec")
})?;
match spec.as_slice() {
[
Value::Symbol(kw),
Value::Symbol(internal),
Value::Symbol(external),
] if kw.name() == "rename" => {
exports.push((external.clone(), internal.clone()));
}
_ => {
return Err(EvalError::malformed(
"export",
"expected identifier or (rename internal external)",
));
}
}
}
_ => {
return Err(EvalError::malformed("export", "expected identifier"));
}
}
}
}
"import" => {
for lib_form in &parts[1..] {
import_one(lib_form, lib_env)?;
}
}
"begin" => {
for body in &parts[1..] {
eval(body.clone(), lib_env.clone())?;
}
}
"include" => {
for path_val in &parts[1..] {
let Value::String(p) = path_val else {
return Err(EvalError::malformed("include", "argument must be a string"));
};
// Resolve relative to the including file's directory.
let resolved = crate::library::resolve_include(&p.borrow());
let source = std::fs::read_to_string(&resolved).map_err(|e| {
EvalError::malformed("include", format!("read {}: {e}", resolved.display()))
})?;
eval_source(&source, lib_env.clone())?;
}
}
"cond-expand" => {
let chosen = pick_cond_expand_branch(&parts[1..])?;
if let Some(branch_decls) = chosen {
process_library_decls(&branch_decls, lib_env, exports)?;
}
}
other => {
return Err(EvalError::malformed(
"define-library",
format!("unknown library declaration: {other}"),
));
}
}
}
Ok(())
}
fn step_import(tail: Value, env: EnvRef) -> Result<Step, EvalError> {
let libs = collect_list(&tail)
.map_err(|()| EvalError::malformed("import", "import list must be proper"))?;
for lib_form in libs {
import_one(&lib_form, &env)?;
}
Ok(Step::Return(Value::Unspecified))
}
fn import_one(lib_form: &Value, target: &EnvRef) -> Result<(), EvalError> {
// Fast path: a *plain* built-in library name needs no work — its
// bindings are already global. Qualified forms like
// `(only (scheme base) car)` are not valid library names, so they
// fail `parse_library_name` and fall through to the resolver.
if let Ok(name) = crate::library::parse_library_name(lib_form)
&& crate::library::is_builtin_library(&name)
{
return Ok(());
}
for (name, cell) in resolve_import_set(lib_form)? {
target.bind_cell(name, cell);
}
Ok(())
}
/// Resolve an import-set (R7RS §5.6.1) to the `name -> cell` bindings it
/// contributes, applying any `only` / `except` / `rename` / `prefix`
/// qualifier. Qualifiers nest: the second element of each form is itself
/// an import-set, so `(prefix (only (lib) a b) p:)` works.
fn resolve_import_set(form: &Value) -> Result<HashMap<Symbol, crate::env::Cell>, EvalError> {
if let Some((Value::Symbol(kw), _)) = form.as_pair() {
match kw.name() {
"only" => {
let (inner, ids) = import_qualifier_parts(form, "only")?;
let mut base = resolve_import_set(&inner)?;
let mut out = HashMap::new();
for id in &ids {
let n = import_identifier(id, "only")?;
let cell = base.remove(&n).ok_or_else(|| {
EvalError::malformed("only", format!("not exported: {}", n.name()))
})?;
out.insert(n, cell);
}
return Ok(out);
}
"except" => {
let (inner, ids) = import_qualifier_parts(form, "except")?;
let mut base = resolve_import_set(&inner)?;
for id in &ids {
let n = import_identifier(id, "except")?;
if base.remove(&n).is_none() {
return Err(EvalError::malformed(
"except",
format!("not exported: {}", n.name()),
));
}
}
return Ok(base);
}
"prefix" => {
let (inner, args) = import_qualifier_parts(form, "prefix")?;
let [prefix] = args.as_slice() else {