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
use crate::TulispObject;
use crate::TulispValue;
use crate::context::TulispContext;
use crate::destruct_bind;
use crate::error::Error;
use crate::eval::DummyEval;
use crate::eval::Eval;
use crate::eval::EvalInto;
use crate::eval::substitute_lexical;
use crate::object::wrappers::generic::{Shared, SharedMut};
use crate::value::{DefunParams, LexAllocator};
use std::convert::TryInto;
// `mark_tail_calls` lives in `crate::parse` (single canonical
// implementation, used by both this TW defspecial and the VM
// `compile_fn_defun`). The VM version's extra `is_known_vm_defun`
// check is a no-op for the TW path — it widens the "is it a tail
// call I can `Bounce`?" predicate to include known VM-compiled
// defuns; in TW we only ever produced `Lambda` values, so the new
// check returns false and the existing `Lambda` arm wins as
// before.
pub(crate) fn add(ctx: &mut TulispContext) {
ctx.defun("load", |ctx: &mut TulispContext, filename: String| {
let full_path = if let Some(ref load_path) = ctx.load_path {
load_path.join(&filename)
} else {
std::path::PathBuf::from(&filename)
};
let Some(full_path) = full_path.to_str() else {
return Err(Error::invalid_argument(format!(
"load: Invalid path: {}",
full_path.to_string_lossy()
)));
};
ctx.eval_file(full_path)
});
ctx.defun(
"intern",
|ctx: &mut TulispContext, name: String| -> TulispObject { ctx.intern(&name) },
);
ctx.defun(
"symbol-value",
|sym: TulispObject| -> Result<TulispObject, Error> {
if !sym.symbolp() {
return Err(Error::type_mismatch(format!(
"symbol-value: expected a symbol, got {sym}"
)));
}
sym.get()
},
);
fn make_symbol(name: String) -> TulispObject {
let constant = name.starts_with(":");
TulispObject::symbol(name, constant)
}
ctx.defun("make-symbol", make_symbol);
ctx.defun(
"gensym",
|ctx: &mut TulispContext, prefix: Option<String>| -> Result<TulispObject, Error> {
let prefix = prefix.unwrap_or_else(|| "g".to_string());
let counter = ctx.intern("gensym-counter");
let count = if counter.boundp() {
let value = counter.get()?;
if value.integerp() {
value.as_int().unwrap()
} else {
0
}
} else {
0
};
counter.set(TulispObject::from(count + 1))?;
Ok(make_symbol(format!("{prefix}{count}")))
},
);
ctx.defun(
"concat",
|rest: crate::Rest<TulispObject>| -> Result<String, Error> {
let mut ret = String::new();
for ele in rest {
match ele.as_string() {
Ok(ref s) => ret.push_str(s),
_ => {
return Err(Error::type_mismatch(format!("Not a string: {}", ele)));
}
}
}
Ok(ret)
},
);
ctx.defun(
"format",
|in_string: String, rest: crate::Rest<TulispObject>| -> Result<String, Error> {
let rest: Vec<TulispObject> = rest.into_iter().collect();
let mut args = rest.iter();
let mut output = String::new();
let mut in_chars = in_string.chars().peekable();
// Supports `%[-][0]WIDTH[.PRECISION]TYPE` where TYPE is one of
// `s S d f`, plus `%%` for a literal percent. The `-` flag
// left-aligns and the `0` flag pads numerics with zeros.
// PRECISION applies to `%f` (digits after the decimal point).
// See the Emacs manual for the full format-spec grammar:
// https://www.gnu.org/software/emacs/manual/html_node/elisp/Formatting-Strings.html
while let Some(ch) = in_chars.next() {
if ch != '%' {
output.push(ch);
continue;
}
let mut left_align = false;
let mut zero_pad = false;
let mut width: usize = 0;
loop {
match in_chars.peek() {
Some('-') => {
left_align = true;
in_chars.next();
}
Some('0') if width == 0 => {
zero_pad = true;
in_chars.next();
}
Some(c) if c.is_ascii_digit() => {
width = width * 10 + (*c as usize - '0' as usize);
in_chars.next();
}
_ => break,
}
}
let mut precision: Option<usize> = None;
if in_chars.peek() == Some(&'.') {
in_chars.next();
let mut p: usize = 0;
while let Some(c) = in_chars.peek() {
if !c.is_ascii_digit() {
break;
}
p = p * 10 + (*c as usize - '0' as usize);
in_chars.next();
}
precision = Some(p);
}
let type_char = match in_chars.next() {
Some(c) => c,
None => {
return Err(Error::syntax_error(
"format: unterminated % spec".to_string(),
));
}
};
if type_char == '%' {
output.push('%');
continue;
}
let Some(next_arg) = args.next() else {
return Err(Error::missing_argument(
"format has missing args".to_string(),
));
};
let formatted = match type_char {
's' => next_arg.fmt_string(),
'S' => next_arg.to_string(),
'd' => next_arg.try_int()?.to_string(),
'f' => {
let v = next_arg.try_float()?;
match precision {
Some(p) => format!("{v:.*}", p),
None => v.to_string(),
}
}
_ => {
return Err(Error::syntax_error(format!(
"Invalid format operation: %{}",
type_char
)));
}
};
let len = formatted.chars().count();
if width > len {
let pad_char = if zero_pad && !left_align && matches!(type_char, 'd' | 'f') {
'0'
} else {
' '
};
let pad = pad_char.to_string().repeat(width - len);
if left_align {
output.push_str(&formatted);
output.push_str(&pad);
} else {
output.push_str(&pad);
output.push_str(&formatted);
}
} else {
output.push_str(&formatted);
}
}
Ok(output)
},
);
ctx.defun("print", |val: TulispObject| -> TulispObject {
println!("{}", val.fmt_string());
val
});
ctx.defun("prin1-to-string", |arg: TulispObject| -> String {
arg.fmt_string()
});
ctx.defun("princ", |val: TulispObject| -> TulispObject {
println!("{}", val.fmt_string());
val
});
ctx.defspecial("while", |ctx, args| {
destruct_bind!((condition &rest rest) = args);
let mut result = TulispObject::nil();
while condition.eval_into(ctx)? {
result = ctx.eval_progn(&rest)?;
}
Ok(result)
});
ctx.defspecial("setq", |ctx, args| {
args.car_and_then(crate::builtin::check_settable_target)?;
let value = args.cdr_and_then(|args| {
if args.null() {
return Err(Error::type_mismatch(
"setq requires exactly 2 arguments".to_string(),
));
}
args.cdr_and_then(|x| {
if !x.null() {
return Err(Error::type_mismatch(
"setq requires exactly 2 arguments".to_string(),
));
}
args.car_and_then(|arg| ctx.eval(arg))
})
})?;
args.car_and_then(|name| name.set(value.clone()))?;
Ok(value)
});
ctx.defun(
"set",
|name: TulispObject, value: TulispObject| -> Result<TulispObject, Error> {
name.set(value.clone())?;
Ok(value)
},
);
/// RAII guard that unwinds dynamic (`defvar`-declared) let bindings
/// on scope exit — including the error path when the body returns
/// `?` partway through. Lexical (non-special) let vars don't need a
/// guard: they own their slot directly via
/// `lexical_binding_captured`, so the slot drops with the binding.
struct DynamicScopeGuard {
names: Vec<TulispObject>,
}
impl Drop for DynamicScopeGuard {
fn drop(&mut self) {
for name in self.names.drain(..).rev() {
let _ = name.unset();
}
}
}
fn impl_let(ctx: &mut TulispContext, args: &TulispObject) -> Result<TulispObject, Error> {
destruct_bind!((varlist &rest body) = args);
// `body` may be nil — `(let ((x 5)))` is well-formed and
// evaluates to nil per Emacs. `eval_progn` returns nil for
// an empty form list, so no explicit check is needed.
// For non-special vars, create a fresh LexicalBinding per
// evaluation that directly owns its slot (via
// `lexical_binding_captured`) and rewrite the body to reference
// it. The slot drops when the binding drops — no thread-local
// stack involvement, no per-call id→stack growth.
// For `defvar`-declared (special/dynamic) vars, push onto the
// symbol's own stack instead — matching Emacs' behavior under
// `lexical-binding: t` for declared variables. The dynamic guard
// unwinds those pushes on scope exit.
// Initializers are evaluated in the scope of previously-bound
// let vars (same as `let*` — tulisp has always had `let` behave
// this way).
let mut mappings: Vec<(TulispObject, TulispObject)> = Vec::new();
let mut dynamic_guard = DynamicScopeGuard { names: Vec::new() };
for varitem in varlist.base_iter() {
let (name, initial) = if varitem.symbolp() {
(varitem, TulispObject::nil())
} else if varitem.consp() {
destruct_bind!((&optional name value &rest rest) = varitem);
if name.null() {
return Err(Error::syntax_error("let varitem requires name".to_string()));
}
if !name.symbolp() {
return Err(Error::type_mismatch(format!(
"Expected Symbol: Can't assign to {name}"
)));
}
if !rest.null() {
return Err(Error::syntax_error(
"let varitem has too many values".to_string(),
));
}
let value_expr = substitute_lexical(value, &mappings)?;
let initial = ctx.eval(&value_expr)?;
(name, initial)
} else {
return Err(Error::syntax_error(format!(
"varitems inside a let-varlist should be a var or a binding: {}",
varitem
)));
};
if name.is_special() {
name.set_scope(initial)?;
dynamic_guard.names.push(name);
} else {
let slot = SharedMut::new(initial);
let lex = TulispObject::lexical_binding_captured(
ctx.lex_allocator.clone(),
name.clone(),
slot,
);
mappings.push((name, lex));
}
}
let rewritten = substitute_lexical(body, &mappings)?;
ctx.eval_progn(&rewritten)
}
ctx.defspecial("let", impl_let);
ctx.defspecial("let*", impl_let);
ctx.defspecial("progn", |ctx, args| ctx.eval_progn(args));
ctx.defspecial("defun", |ctx, args| {
destruct_bind!((name params &rest rest) = args);
{
let body = if rest.car()?.as_string().is_ok() {
rest.cdr()?
} else {
rest
};
let body = crate::parse::mark_tail_calls(ctx, name.clone(), body)?;
// Pre-rewrite the body so each param reference points at a
// shared `LexicalBinding` allocated once here. Call-time
// evaluation then only push/pops values onto the binding's
// thread-local stack, avoiding per-call AST clones (fib was
// 10.6× slower without this).
let raw_params: DefunParams = params.try_into()?;
let (params, mappings) = raw_params.bind_as_lexical(&ctx.lex_allocator);
let body = substitute_lexical(body, &mappings)?;
name.set_global(TulispValue::Lambda { params, body }.into_ref(None))?;
Ok(TulispObject::nil())
}
});
fn lambda(ctx: &mut TulispContext, args: &TulispObject) -> Result<TulispObject, Error> {
destruct_bind!((params &rest rest) = args);
let body = if rest.car()?.as_string().is_ok() {
rest.cdr()?
} else {
rest
};
let params: DefunParams = params.try_into()?;
let param_names: Vec<_> = params.iter().map(|x| x.param.clone()).collect();
fn slice_contains(vec: &[TulispObject], item: &TulispObject) -> bool {
for i in vec {
if i.eq(item) {
return true;
}
}
false
}
fn capture_symbol(
allocator: &Shared<LexAllocator>,
captured_vars: &mut Vec<(TulispObject, TulispObject)>,
exclude: &[TulispObject],
symbol: TulispObject,
) -> Result<TulispObject, Error> {
if !symbol.is_lexically_bound() {
return Ok(symbol);
}
if !slice_contains(exclude, &symbol) {
for (from, to) in captured_vars.iter() {
if symbol.eq(from) {
return Ok(to.clone().with_span(symbol.span()));
}
}
// Share the enclosing scope's slot with the closure
// so `setq` on either side is visible to both —
// matching Emacs' `lexical-binding: t` semantics.
let slot_opt = {
let inner = symbol.inner_ref();
match &inner.0 {
crate::value::TulispValue::LexicalBinding { binding } => {
Some((binding.current_slot(), binding.name().to_string()))
}
_ => None,
}
};
let slot = match slot_opt {
Some((Some(slot), _)) => slot,
Some((None, name)) => {
return Err(Error::uninitialized(format!(
"Variable definition is void: {}",
name
)));
}
None => return Ok(symbol),
};
let new_var =
TulispObject::lexical_binding_captured(allocator.clone(), symbol.clone(), slot);
captured_vars.push((symbol, new_var.clone()));
return Ok(new_var);
}
Ok(symbol)
}
fn capture_variables(
allocator: &Shared<LexAllocator>,
captured_vars: &mut Vec<(TulispObject, TulispObject)>,
exclude: &[TulispObject],
body: TulispObject,
) -> Result<TulispObject, Error> {
capture_variables_inner(allocator, captured_vars, exclude, body, 0)
}
// `quote_depth` tracks quasi-quote nesting: 0 = code context
// (substitute/capture vars); >0 = inside a backquote (data
// context — literal symbols are not var references). Unquote /
// splice decrement it (back to code), backquote increments.
fn capture_variables_inner(
allocator: &Shared<LexAllocator>,
captured_vars: &mut Vec<(TulispObject, TulispObject)>,
exclude: &[TulispObject],
mut body: TulispObject,
quote_depth: u32,
) -> Result<TulispObject, Error> {
if !body.consp() {
let inner_ref = body.inner_ref();
return match &inner_ref.0 {
TulispValue::Symbol { .. } | TulispValue::LexicalBinding { .. } => {
drop(inner_ref);
if quote_depth > 0 {
Ok(body)
} else {
capture_symbol(allocator, captured_vars, exclude, body)
}
}
TulispValue::Backquote { value } => Ok(TulispValue::Backquote {
value: capture_variables_inner(
allocator,
captured_vars,
exclude,
value.clone(),
quote_depth + 1,
)?,
}
.into_ref(body.span())),
TulispValue::Unquote { value } => Ok(TulispValue::Unquote {
value: capture_variables_inner(
allocator,
captured_vars,
exclude,
value.clone(),
quote_depth.saturating_sub(1),
)?,
}
.into_ref(body.span())),
TulispValue::Splice { value } => Ok(TulispValue::Splice {
value: capture_variables_inner(
allocator,
captured_vars,
exclude,
value.clone(),
quote_depth.saturating_sub(1),
)?,
}
.into_ref(body.span())),
TulispValue::Sharpquote { value } if quote_depth == 0 => {
Ok(TulispValue::Sharpquote {
value: capture_variables_inner(
allocator,
captured_vars,
exclude,
value.clone(),
quote_depth,
)?,
}
.into_ref(body.span()))
}
// `Quote` is always data — don't descend.
_ => {
drop(inner_ref);
Ok(body)
}
};
}
// At code level, `(quote X)` written as a list form is
// data-only — don't descend into X.
if quote_depth == 0
&& let Ok(car) = body.car()
&& let Ok(name) = car.as_symbol()
&& name == "quote"
{
return Ok(body);
}
let span = body.span();
let mut builder = crate::cons::ListBuilder::new();
loop {
let car = body.car()?;
builder.push(capture_variables_inner(
allocator,
captured_vars,
exclude,
car,
quote_depth,
)?);
let cdr = body.cdr()?;
if cdr.null() {
break;
}
if !cdr.consp() {
builder.append(capture_variables_inner(
allocator,
captured_vars,
exclude,
cdr,
quote_depth,
)?)?;
break;
}
body = cdr;
}
Ok(builder.build().with_span(span))
}
let body = capture_variables(&ctx.lex_allocator, &mut vec![], ¶m_names, body)?;
// After capture_variables, free vars in body point at captured
// LexicalBindings from the enclosing scope; param references
// are still raw symbols. Pre-rewrite them to the new
// per-param LexicalBindings so calls are push/pop only.
let (params, mappings) = params.bind_as_lexical(&ctx.lex_allocator);
let body = substitute_lexical(body, &mappings)?;
Ok(TulispValue::Lambda { params, body }.into_ref(None))
}
ctx.defspecial("lambda", lambda);
ctx.defspecial("defmacro", |ctx, args| {
destruct_bind!((name params &rest rest) = args);
let body = if rest.car()?.as_string().is_ok() {
rest.cdr()?
} else {
rest
};
let raw_params: DefunParams = params.try_into()?;
let (params, mappings) = raw_params.bind_as_lexical(&ctx.lex_allocator);
let body = substitute_lexical(body, &mappings)?;
name.set_scope(TulispValue::Defmacro { params, body }.into_ref(None))?;
Ok(TulispObject::nil())
});
ctx.defun("null", |arg: TulispObject| -> bool { arg.null() });
ctx.defun(
"eval",
|ctx: &mut TulispContext, arg: TulispObject| -> Result<TulispObject, Error> {
ctx.eval(&arg)
},
);
ctx.defspecial("apply", |ctx, args| {
// (apply FUNCTION &rest ARGUMENTS) — calls FUNCTION with its
// intermediate ARGUMENTS plus the elements of the final list
// (which must itself evaluate to a list). E.g.
// (apply '+ 1 2 '(3 4)) => 10
if args.null() {
return Err(Error::missing_argument(
"apply requires at least 2 arguments".to_string(),
));
}
destruct_bind!((name &rest rest) = args);
let name = ctx.eval(&name)?;
let name = ctx.eval(&name)?;
let mut evaluated: Vec<TulispObject> = Vec::new();
let mut cur = rest;
while cur.consp() {
evaluated.push(ctx.eval(&cur.car()?)?);
cur = cur.cdr()?;
}
let Some(final_list) = evaluated.pop() else {
return Err(Error::missing_argument(
"apply requires at least 2 arguments".to_string(),
));
};
if !final_list.listp() {
return Err(Error::type_mismatch(format!(
"apply: last argument must be a list, got: {final_list}"
)));
}
// Splice with Floyd's tortoise / hare so a circular final
// list errors instead of hanging the splice loop.
let mut slow = final_list.clone();
let mut fast = final_list.clone();
loop {
for _ in 0..2 {
if !fast.consp() {
break;
}
evaluated.push(fast.car()?);
fast = fast.cdr()?;
}
if !fast.consp() {
if !fast.null() {
return Err(Error::type_mismatch(format!(
"apply: last argument must be a proper list, got non-nil tail: {fast}"
)));
}
break;
}
slow = slow.cdr()?;
if slow.eq_ptr(&fast) {
return Err(Error::out_of_range(
"apply: last argument is a circular list".to_string(),
));
}
}
// Hand the spliced, already-evaluated args to `funcall` via a
// quoted arg list — same trick the VM's `funcall_inline` uses
// for Lambda/Func: wrap each value in `quote` so the inner
// `Eval` pass treats it as a no-op.
let call_args = TulispObject::nil();
for arg in evaluated {
call_args.push(TulispValue::Quote { value: arg }.into_ref(None))?;
}
if matches!(
&name.inner_ref().0,
TulispValue::Lambda { .. }
| TulispValue::Defun { .. }
| TulispValue::CompiledDefun { .. }
) {
crate::eval::funcall::<Eval>(ctx, &name, &call_args)
} else {
crate::eval::funcall::<DummyEval>(ctx, &name, &call_args)
}
});
ctx.defspecial("funcall", |ctx, args| {
destruct_bind!((name &rest rest) = args);
let name = ctx.eval(&name)?;
let name = ctx.eval(&name)?;
// Lambda / Defun / CompiledDefun all expect their args to be
// already-evaluated values. Pass through `Eval` so the rest
// list is evaluated before dispatch. Func-style defspecials
// are the only callers that want the raw, unevaluated arg
// list — those keep the `DummyEval` path.
if matches!(
&name.inner_ref().0,
TulispValue::Lambda { .. }
| TulispValue::Defun { .. }
| TulispValue::CompiledDefun { .. }
) {
crate::eval::funcall::<Eval>(ctx, &name, &rest)
} else {
crate::eval::funcall::<DummyEval>(ctx, &name, &rest)
}
});
ctx.defun(
"macroexpand",
|ctx: &mut TulispContext, name: TulispObject| -> Result<TulispObject, Error> {
crate::eval::macroexpand(ctx, name)
},
);
// List functions
ctx.defun(
"cons",
|car: TulispObject, cdr: TulispObject| -> TulispObject { TulispObject::cons(car, cdr) },
);
ctx.defun(
"append",
|rest: crate::Rest<TulispObject>| -> Result<TulispObject, Error> {
// Emacs `append`: copy every list except the last; share
// the last argument's cells with the result. The last
// argument may be any value (it becomes the dotted tail
// when non-list, non-nil).
let mut args: Vec<TulispObject> = rest.into_iter().collect();
let Some(last) = args.pop() else {
return Ok(TulispObject::nil());
};
let mut builder = crate::cons::ListBuilder::new();
for arg in args {
if !arg.listp() {
return Err(Error::type_mismatch(format!(
"append: expected list, got: {arg}"
)));
}
for elem in arg.base_iter() {
builder.push(elem);
}
}
Ok(builder.build_with_tail(last))
},
);
ctx.defspecial("dolist", |ctx, args| {
destruct_bind!((spec &rest body) = args);
destruct_bind!((var list &optional result) = spec);
// Under Emacs' `lexical-binding: t`, dolist freshly binds the
// loop variable at each iteration — equivalent to `(while tail
// (let ((var (car tail))) body))`. So closures captured in
// different iterations get distinct slots. `result` is
// evaluated in the *outer* scope and does not see `var`.
let lex = TulispObject::lexical_binding(ctx.lex_allocator.clone(), var.clone());
let mappings = vec![(var, lex.clone())];
let body = substitute_lexical(body, &mappings)?;
let mut list = ctx.eval(&list)?;
while list.is_truthy() {
lex.set_scope(list.car()?)?;
let res = ctx.eval_progn(&body);
lex.unset()?;
res?;
list = list.cdr()?;
}
ctx.eval(&result)
});
ctx.defspecial("dotimes", |ctx, args| {
destruct_bind!((spec &rest body) = args);
destruct_bind!((var count &optional result) = spec);
let lex = TulispObject::lexical_binding(ctx.lex_allocator.clone(), var.clone());
let mappings = vec![(var, lex.clone())];
let body = substitute_lexical(body, &mappings)?;
for counter in 0..count.as_int()? {
lex.set_scope(TulispObject::from(counter))?;
let res = ctx.eval_progn(&body);
lex.unset()?;
res?;
}
ctx.eval(&result)
});
ctx.defun("list", |args: crate::Rest<TulispObject>| -> TulispObject {
args.into_iter().collect()
});
ctx.defun(
"assoc",
|ctx: &mut TulispContext,
key: TulispObject,
alist: TulispObject,
testfn: Option<TulispObject>|
-> Result<TulispObject, Error> { crate::alist::assoc(ctx, &key, &alist, testfn) },
);
ctx.defun(
"alist-get",
|ctx: &mut TulispContext,
key: TulispObject,
alist: TulispObject,
default_value: Option<TulispObject>,
remove: Option<TulispObject>,
testfn: Option<TulispObject>|
-> Result<TulispObject, Error> {
// TODO: implement remove after `setf`.
crate::alist::alist_get(ctx, &key, &alist, default_value, remove, testfn)
},
);
ctx.defun(
"plist-get",
|plist: TulispObject, property: TulispObject| -> Result<TulispObject, Error> {
crate::plist::plist_get(&plist, &property)
},
);
// predicates begin
macro_rules! predicate_function {
($name: ident) => {
ctx.defun(stringify!($name), |arg: TulispObject| -> bool {
arg.$name()
});
};
}
predicate_function!(consp);
predicate_function!(listp);
predicate_function!(floatp);
predicate_function!(integerp);
predicate_function!(numberp);
predicate_function!(stringp);
predicate_function!(symbolp);
predicate_function!(boundp);
predicate_function!(keywordp);
// predicates end
ctx.defspecial("declare", |_ctx, _args| {
// no-op
Ok(TulispObject::nil())
});
ctx.defspecial("defvar", |ctx, args| {
destruct_bind!((name &optional initval _docstring) = args);
if !name.symbolp() {
return Err(Error::type_mismatch(
"defvar: first argument must be a symbol".to_string(),
));
}
// Flip the symbol's `special` flag so subsequent let/let* and
// reference-rewrite paths treat it as dynamic (Emacs' behavior
// under `lexical-binding: t`). Done before any initval eval so
// the flag is set even if initval errors.
name.set_special()?;
if !name.boundp() {
let val = ctx.eval(&initval)?;
name.set(val)?;
}
Ok(name)
});
}