1use crate::builtins::form::form_to_value;
4use cljrs_gc::GcPtr;
5use cljrs_reader::{Form, FormKind};
6use cljrs_value::{
7 Atom, CljxFn, CljxFnArity, Delay, LazySeq, MapValue, PersistentList, Symbol, Thunk, Value,
8 Volatile,
9};
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use crate::env::env::Env;
14use crate::env::error::{EvalError, EvalResult, value_error_to_eval_error};
15use crate::interp::destructure::value_to_seq_vec;
16use crate::interp::eval::eval;
17
18#[allow(dead_code)]
21fn eval_error_to_value(e: EvalError) -> Value {
22 match e {
23 EvalError::Thrown(v) => v,
24 other => Value::string(format!("{other}")),
25 }
26}
27
28fn fire_watches(
34 watches: &std::sync::Mutex<Vec<(Value, Value)>>,
35 reference: &Value,
36 old: &Value,
37 new: &Value,
38 env: &mut Env,
39) {
40 let ws: Vec<(Value, Value)> = watches.lock().unwrap().clone();
41 for (key, f) in &ws {
42 let args = vec![key.clone(), reference.clone(), old.clone(), new.clone()];
43 if let Err(e) = crate::env::apply::apply_value(f, args, env) {
44 WATCH_ERROR.with(|cell| {
51 cell.borrow_mut().replace(e);
52 });
53 return;
54 }
55 }
56}
57
58thread_local! {
59 static WATCH_ERROR: std::cell::RefCell<Option<EvalError>> = const { std::cell::RefCell::new(None) };
60}
61
62fn check_watch_error() -> EvalResult<()> {
64 WATCH_ERROR.with(|cell| {
65 if let Some(e) = cell.borrow_mut().take() {
66 Err(e)
67 } else {
68 Ok(())
69 }
70 })
71}
72
73#[derive(Debug)]
77pub struct ClosureThunk {
78 pub f: CljxFn,
79 pub globals: std::sync::Arc<crate::env::env::GlobalEnv>,
80 pub ns: std::sync::Arc<str>,
81}
82
83struct CallableValueThunk {
89 callee: Value,
90 globals: std::sync::Arc<crate::env::env::GlobalEnv>,
91 ns: std::sync::Arc<str>,
92}
93
94impl std::fmt::Debug for CallableValueThunk {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 f.debug_struct("CallableValueThunk")
97 .field("callee", &self.callee.type_name())
98 .field("ns", &self.ns)
99 .finish()
100 }
101}
102
103impl cljrs_gc::Trace for CallableValueThunk {
104 fn trace(&self, visitor: &mut cljrs_gc::MarkVisitor) {
105 self.callee.trace(visitor);
106 }
107}
108
109impl Thunk for CallableValueThunk {
110 fn force(&self) -> Result<Value, String> {
111 let mut env = Env::new(self.globals.clone(), &self.ns);
112 crate::env::apply::apply_value(&self.callee, Vec::new(), &mut env)
113 .map_err(|e| format!("{e}"))
114 }
115}
116
117pub fn make_lazy_seq_from_fn(
130 f_val: &Value,
131 globals: std::sync::Arc<crate::env::env::GlobalEnv>,
132 ns: std::sync::Arc<str>,
133) -> EvalResult {
134 let unwrapped = f_val.unwrap_meta();
135 if let Value::Fn(g) = unwrapped {
136 let thunk = ClosureThunk {
137 f: g.get().clone(),
138 globals,
139 ns,
140 };
141 return Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))));
142 }
143 if unwrapped.type_name() != "fn" {
146 return Err(EvalError::Runtime(format!(
147 "make-lazy-seq requires a fn, got {}",
148 unwrapped.type_name(),
149 )));
150 }
151 let thunk = CallableValueThunk {
152 callee: unwrapped.clone(),
153 globals,
154 ns,
155 };
156 Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))))
157}
158
159impl cljrs_gc::Trace for ClosureThunk {
160 fn trace(&self, visitor: &mut cljrs_gc::MarkVisitor) {
161 self.f.trace(visitor);
162 }
163}
164
165impl Thunk for ClosureThunk {
166 fn force(&self) -> Result<Value, String> {
167 let _closed_root = crate::env::gc_roots::root_values(&self.f.closed_over_vals);
171 let mut env = Env::with_closure(self.globals.clone(), &self.ns, &self.f);
172 call_cljrs_fn(&self.f, &[], &mut env).map_err(|e| format!("{e}"))
173 }
174}
175
176pub fn is_form_intercepted(name: &str) -> bool {
183 matches!(
184 name,
185 "apply"
186 | "atom"
187 | "reset!"
188 | "swap!"
189 | "volatile!"
190 | "vreset!"
191 | "agent"
192 | "make-lazy-seq"
193 | "make-delay"
194 | "vswap!"
195 | "send"
196 | "send-off"
197 | "with-bindings*"
198 | "alter-var-root"
199 | "vary-meta"
200 | "eval"
201 | "find-ns"
202 | "the-ns"
203 | "ns-interns"
204 | "ns-publics"
205 | "ns-refers"
206 | "ns-map"
207 | "all-ns"
208 | "create-ns"
209 | "ns-aliases"
210 | "remove-ns"
211 | "alter-meta!"
212 | "ns-resolve"
213 | "resolve"
214 | "intern"
215 | "bound-fn*"
216 )
217}
218
219pub fn eval_call(func_form: &Form, arg_forms: &[Form], env: &mut Env) -> EvalResult {
227 if let FormKind::Symbol(s) = &func_form.kind
229 && is_method_sugar(s)
230 {
231 return eval_method_call(&s[1..], arg_forms, env);
232 }
233
234 let callee = eval(func_form, env)?;
236
237 let _callee_root = crate::env::gc_roots::root_value(&callee);
239
240 if let Value::Macro(mfn) = &callee {
242 let expanded = macro_apply(mfn.get(), func_form, arg_forms, env)?;
243 return eval(&expanded, env);
244 }
245
246 if let Value::NativeFunction(nf) = &callee {
248 crate::env::policy::check_native(&nf.get().name)?;
249 match nf.get().name.as_ref() {
250 "apply" => return handle_apply_call(arg_forms, env),
251 "atom" => return handle_atom_call(arg_forms, env),
252 "reset!" => return handle_reset_bang(arg_forms, env),
253 "swap!" => return handle_swap_call(arg_forms, env),
254 "volatile!" => return handle_volatile(arg_forms, env),
255 "vreset!" => return handle_vreset(arg_forms, env),
256 "agent" => return handle_agent_call(arg_forms, env),
257 "make-lazy-seq" => return handle_make_lazy_seq(arg_forms, env),
258 "make-delay" => return handle_make_delay(arg_forms, env),
259 "vswap!" => return handle_vswap(arg_forms, env),
260 "send" | "send-off" => return handle_send(arg_forms, env),
261 "with-bindings*" => return handle_with_bindings(arg_forms, env),
262 "alter-var-root" => return handle_alter_var_root(arg_forms, env),
263 "vary-meta" => return handle_vary_meta(arg_forms, env),
264 "eval" => return handle_eval(arg_forms, env),
265 "find-ns" | "the-ns" => return handle_find_ns(arg_forms, env),
266 "ns-interns" | "ns-publics" => return handle_ns_interns(arg_forms, env),
267 "ns-refers" => return handle_ns_refers(arg_forms, env),
268 "ns-map" => return handle_ns_map(arg_forms, env),
269 "all-ns" => return handle_all_ns(arg_forms, env),
270 "create-ns" => return handle_create_ns(arg_forms, env),
271 "ns-aliases" => return handle_ns_aliases(arg_forms, env),
272 "remove-ns" => return handle_remove_ns(arg_forms, env),
273 "alter-meta!" => return handle_alter_meta(arg_forms, env),
274 "ns-resolve" => return handle_ns_resolve(arg_forms, env),
275 "resolve" => return handle_resolve(arg_forms, env),
276 "intern" => return handle_intern(arg_forms, env),
277 "bound-fn*" => return handle_bound_fn_star(arg_forms, env),
278 _ => {}
279 }
280 }
281
282 let mut args: Vec<Value> = Vec::with_capacity(arg_forms.len());
285 for f in arg_forms {
286 let _args_root = crate::env::gc_roots::root_values(&args);
288 args.push(eval(f, env)?);
289 }
290
291 if let Value::Fn(f) = &callee {
296 if let Some(fut) = crate::env::apply::dispatch_if_async(&callee, &args, env) {
299 return Ok(fut);
300 }
301 let _args_root = crate::env::gc_roots::root_values(&args);
302 crate::env::gc_roots::gc_safepoint(env);
303 return env.call_cljrs_fn(f.get(), &args);
304 }
305
306 crate::env::apply::apply_value(&callee, args, env)
307}
308
309fn eval_method_call(method: &str, arg_forms: &[Form], env: &mut Env) -> EvalResult {
319 if arg_forms.is_empty() {
320 return Err(EvalError::Runtime(format!(
321 ".{method} requires a target object"
322 )));
323 }
324 let target = eval(&arg_forms[0], env)?;
325 let args: Vec<Value> = arg_forms[1..]
326 .iter()
327 .map(|f| eval(f, env))
328 .collect::<EvalResult<_>>()?;
329
330 dispatch_method(method, &target, &args)
331}
332
333pub use cljrs_ir::lower::is_method_sugar;
338
339pub fn dispatch_method(method: &str, target: &Value, args: &[Value]) -> EvalResult {
345 match target {
346 Value::Str(s) => dispatch_string_method(method, s.get(), args),
347 Value::Vector(v) => dispatch_vector_method(method, v, args),
348 Value::List(_) | Value::Cons(_) | Value::LazySeq(_) => {
349 dispatch_seq_method(method, target, args)
350 }
351 Value::TypeInstance(ti) => {
352 if let Some(field) = method.strip_prefix('-') {
356 let key = Value::keyword(cljrs_value::Keyword::simple(field));
357 let inst = ti.get();
358 if let Some(atom) = &inst.mutable
361 && let Value::Map(m) = atom.get().deref()
362 && let Some(v) = m.get(&key)
363 {
364 return Ok(v);
365 }
366 Ok(inst.fields.get(&key).unwrap_or(Value::Nil))
367 } else {
368 Err(EvalError::Runtime(format!(
369 ".{method} not supported on {} (only .-field access is)",
370 target.type_name()
371 )))
372 }
373 }
374 _ => Err(EvalError::Runtime(format!(
375 ".{method} not supported on type {}",
376 target.type_name()
377 ))),
378 }
379}
380
381fn dispatch_string_method(method: &str, s: &str, args: &[Value]) -> EvalResult {
382 match method {
383 "indexOf" => {
384 let needle = match args.first() {
385 Some(Value::Str(s)) => s.get().to_string(),
386 Some(Value::Char(c)) => c.to_string(),
387 Some(v) => {
388 return Err(EvalError::Runtime(format!(
389 ".indexOf expects string or char argument, got {}",
390 v.type_name()
391 )));
392 }
393 None => return Err(EvalError::Runtime(".indexOf requires an argument".into())),
394 };
395 match s.find(&needle) {
396 Some(pos) => Ok(Value::Long(pos as i64)),
397 None => Ok(Value::Long(-1)),
398 }
399 }
400 "lastIndexOf" => {
401 let needle = match args.first() {
402 Some(Value::Str(s)) => s.get().to_string(),
403 Some(Value::Char(c)) => c.to_string(),
404 _ => {
405 return Err(EvalError::Runtime(
406 ".lastIndexOf requires a string or char argument".into(),
407 ));
408 }
409 };
410 match s.rfind(&needle) {
411 Some(pos) => Ok(Value::Long(pos as i64)),
412 None => Ok(Value::Long(-1)),
413 }
414 }
415 "startsWith" => {
416 let prefix = require_str_arg(args, ".startsWith")?;
417 Ok(Value::Bool(s.starts_with(&prefix)))
418 }
419 "endsWith" => {
420 let suffix = require_str_arg(args, ".endsWith")?;
421 Ok(Value::Bool(s.ends_with(&suffix)))
422 }
423 "contains" => {
424 let sub = require_str_arg(args, ".contains")?;
425 Ok(Value::Bool(s.contains(&sub)))
426 }
427 "length" => Ok(Value::Long(s.len() as i64)),
428 "isEmpty" => Ok(Value::Bool(s.is_empty())),
429 "charAt" => {
430 let idx = require_long_arg(args, ".charAt")? as usize;
431 s.chars()
432 .nth(idx)
433 .map(Value::Char)
434 .ok_or_else(|| EvalError::Runtime(format!(".charAt index {idx} out of bounds")))
435 }
436 "substring" => {
437 let start = require_long_arg(args, ".substring")? as usize;
438 let end = args
439 .get(1)
440 .map(|v| match v {
441 Value::Long(n) => Ok(*n as usize),
442 _ => Err(EvalError::Runtime(
443 ".substring end must be an integer".into(),
444 )),
445 })
446 .transpose()?;
447 let result = match end {
448 Some(e) => &s[start..e.min(s.len())],
449 None => &s[start..],
450 };
451 Ok(Value::Str(GcPtr::new(result.to_string())))
452 }
453 "toUpperCase" => Ok(Value::Str(GcPtr::new(s.to_uppercase()))),
454 "toLowerCase" => Ok(Value::Str(GcPtr::new(s.to_lowercase()))),
455 "trim" => Ok(Value::Str(GcPtr::new(s.trim().to_string()))),
456 "replace" => {
457 let from = require_str_arg(args, ".replace")?;
458 let to = match args.get(1) {
459 Some(Value::Str(s)) => s.get().to_string(),
460 Some(Value::Char(c)) => c.to_string(),
461 _ => {
462 return Err(EvalError::Runtime(
463 ".replace requires two string arguments".into(),
464 ));
465 }
466 };
467 Ok(Value::Str(GcPtr::new(s.replace(&from, &to))))
468 }
469 "split" => {
470 let sep = require_str_arg(args, ".split")?;
471 let parts: Vec<Value> = s
472 .split(&sep)
473 .map(|p| Value::Str(GcPtr::new(p.to_string())))
474 .collect();
475 Ok(Value::Vector(GcPtr::new(
476 cljrs_value::PersistentVector::from_iter(parts),
477 )))
478 }
479 _ => Err(EvalError::Runtime(format!(
480 ".{method} not supported on String"
481 ))),
482 }
483}
484
485fn dispatch_vector_method(
486 method: &str,
487 v: &GcPtr<cljrs_value::PersistentVector>,
488 args: &[Value],
489) -> EvalResult {
490 match method {
491 "indexOf" => {
492 let needle = args
493 .first()
494 .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
495 for (i, item) in v.get().iter().enumerate() {
496 if item == needle {
497 return Ok(Value::Long(i as i64));
498 }
499 }
500 Ok(Value::Long(-1))
501 }
502 "size" | "count" => Ok(Value::Long(v.get().count() as i64)),
503 _ => Err(EvalError::Runtime(format!(
504 ".{method} not supported on Vector"
505 ))),
506 }
507}
508
509fn dispatch_seq_method(method: &str, target: &Value, args: &[Value]) -> EvalResult {
510 match method {
511 "indexOf" => {
512 let needle = args
513 .first()
514 .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
515 let items = crate::interp::destructure::value_to_seq_vec(target);
516 for (i, item) in items.iter().enumerate() {
517 if item == needle {
518 return Ok(Value::Long(i as i64));
519 }
520 }
521 Ok(Value::Long(-1))
522 }
523 _ => Err(EvalError::Runtime(format!(
524 ".{method} not supported on {}",
525 target.type_name()
526 ))),
527 }
528}
529
530fn require_str_arg(args: &[Value], method: &str) -> Result<String, EvalError> {
531 match args.first() {
532 Some(Value::Str(s)) => Ok(s.get().to_string()),
533 Some(Value::Char(c)) => Ok(c.to_string()),
534 _ => Err(EvalError::Runtime(format!(
535 "{method} requires a string argument"
536 ))),
537 }
538}
539
540fn require_long_arg(args: &[Value], method: &str) -> Result<i64, EvalError> {
541 match args.first() {
542 Some(Value::Long(n)) => Ok(*n),
543 _ => Err(EvalError::Runtime(format!(
544 "{method} requires an integer argument"
545 ))),
546 }
547}
548
549pub fn resolve_type_tag(sym: &str) -> Arc<str> {
552 Arc::from(sym)
553}
554
555pub fn call_cljrs_fn(f: &CljxFn, args: &[Value], caller_env: &mut Env) -> EvalResult {
557 let arity = select_arity(f, args.len())?;
558
559 let _caller_root = crate::env::gc_roots::push_env_root(caller_env);
562
563 let mut env = Env::with_closure(caller_env.globals.clone(), &f.defining_ns, f);
566
567 let mut current_args = Vec::from(args);
568 loop {
569 let _args_root = crate::env::gc_roots::root_values(¤t_args);
572
573 crate::env::gc_roots::gc_safepoint(&env);
575
576 env.push_frame();
577
578 #[cfg(not(feature = "no-gc"))]
588 let _call_frame = cljrs_gc::push_alloc_frame();
589
590 if let Some(ref name) = f.name {
599 let self_val = if let Some(ref p) = f.self_ptr {
600 Value::Fn(p.clone())
601 } else {
602 Value::Fn(GcPtr::new(f.clone()))
603 };
604 env.bind(name.clone(), self_val);
605 }
606
607 bind_fn_params(arity, ¤t_args, &mut env)?;
609
610 #[cfg(not(feature = "no-gc"))]
615 let result = eval_body_recur_fn(&arity.body, &mut env);
616 #[cfg(feature = "no-gc")]
617 let result = {
618 let mut scratch = cljrs_gc::alloc_ctx::ScratchGuard::new();
619 eval_body_with_scratch(&arity.body, &mut scratch, &mut env)
621 };
622 env.pop_frame();
623 match result {
627 Ok(v) => return Ok(v),
628 Err(EvalError::Recur(new_args)) => {
629 if arity.rest_param.is_some() {
634 let n = arity.params.len();
635 if new_args.len() == n + 1 {
636 let mut flat = new_args[..n].to_vec();
637 let rest_val = &new_args[n];
639 match rest_val {
640 Value::Nil => {} _ => {
642 let rest_items = value_to_seq_vec(rest_val);
643 flat.extend(rest_items);
644 }
645 }
646 current_args = flat;
647 } else {
648 current_args = new_args;
649 }
650 } else {
651 current_args = new_args;
652 }
653 }
654 Err(e) => return Err(e),
655 }
656 }
657}
658
659pub fn bind_fn_params(arity: &CljxFnArity, args: &[Value], env: &mut Env) -> EvalResult<()> {
662 bind_fn_params_impl(arity, args, env, true)
663}
664
665pub fn bind_fn_params_positional(
676 arity: &CljxFnArity,
677 args: &[Value],
678 env: &mut Env,
679) -> EvalResult<()> {
680 bind_fn_params_impl(arity, args, env, false)
681}
682
683fn bind_fn_params_impl(
684 arity: &CljxFnArity,
685 args: &[Value],
686 env: &mut Env,
687 destructure: bool,
688) -> EvalResult<()> {
689 let n = arity.params.len();
690 for (i, name) in arity.params.iter().enumerate() {
692 let val = args.get(i).cloned().unwrap_or(Value::Nil);
693 env.bind(name.clone(), val);
694 }
695 if let Some(ref rest) = arity.rest_param {
697 let rest_items = args[n..].to_vec();
698 let rest_val = if rest_items.is_empty() {
699 Value::Nil
700 } else {
701 Value::List(GcPtr::new(PersistentList::from_iter(rest_items)))
702 };
703 env.bind(rest.clone(), rest_val.clone());
704 if destructure && let Some(ref pattern) = arity.destructure_rest {
706 let destructure_val = if pattern.is_kwargs_rest_pattern() {
710 let items = value_to_seq_vec(&rest_val);
711 Value::from_kwargs_rest(items).map_err(value_error_to_eval_error)?
712 } else {
713 rest_val
714 };
715 crate::interp::destructure::bind_pattern(pattern, destructure_val, env)?;
716 }
717 }
718 if destructure {
720 for (idx, pattern) in &arity.destructure_params {
721 let val = args.get(*idx).cloned().unwrap_or(Value::Nil);
722 crate::interp::destructure::bind_pattern(pattern, val, env)?;
723 }
724 }
725 Ok(())
726}
727
728#[cfg(not(feature = "no-gc"))]
730fn eval_body_recur_fn(body: &[cljrs_reader::Form], env: &mut Env) -> EvalResult {
731 let mut result = Value::Nil;
732 for form in body {
733 result = eval(form, env)?;
734 }
735 Ok(result)
736}
737
738#[cfg(feature = "no-gc")]
742fn eval_body_with_scratch(
743 body: &[cljrs_reader::Form],
744 scratch: &mut cljrs_gc::alloc_ctx::ScratchGuard,
745 env: &mut Env,
746) -> EvalResult {
747 if body.is_empty() {
748 scratch.pop_for_return();
749 return Ok(Value::Nil);
750 }
751 for form in &body[..body.len() - 1] {
753 eval(form, env)?;
754 }
755 scratch.pop_for_return();
757 eval(&body[body.len() - 1], env)
758}
759
760pub fn select_arity(f: &CljxFn, argc: usize) -> EvalResult<&CljxFnArity> {
762 let name = f.name.as_deref().unwrap_or("fn");
763 for arity in &f.arities {
765 if arity.rest_param.is_none() && arity.params.len() == argc {
766 return Ok(arity);
767 }
768 }
769 for arity in &f.arities {
771 if arity.rest_param.is_some() && argc >= arity.params.len() {
772 return Ok(arity);
773 }
774 }
775 let expected: Vec<String> = f
777 .arities
778 .iter()
779 .map(|a| {
780 if a.rest_param.is_some() {
781 format!("{}+", a.params.len())
782 } else {
783 a.params.len().to_string()
784 }
785 })
786 .collect();
787 Err(EvalError::Arity {
788 name: name.to_string(),
789 expected: expected.join(" or "),
790 got: argc,
791 })
792}
793
794fn macro_apply(
801 mfn: &CljxFn,
802 func_form: &Form,
803 arg_forms: &[Form],
804 env: &mut Env,
805) -> EvalResult<Form> {
806 let resolved_args: Vec<Form> = arg_forms
811 .iter()
812 .map(|f| crate::builtins::form::resolve_auto_forms(f, env))
813 .collect::<EvalResult<Vec<Form>>>()?;
814
815 let form_val = {
817 let mut items = vec![form_to_value(func_form)?];
818 for f in &resolved_args {
819 items.push(form_to_value(f)?);
820 }
821 Value::List(GcPtr::new(PersistentList::from_iter(items)))
822 };
823
824 let env_val = {
826 let (names, vals) = env.all_local_bindings();
827 let mut m = MapValue::empty();
828 for (name, val) in names.iter().zip(vals.iter()) {
829 m = m.assoc(Value::symbol(Symbol::simple(name.as_ref())), val.clone());
830 }
831 Value::Map(m)
832 };
833
834 let mut args = vec![form_val, env_val];
836 for f in &resolved_args {
837 args.push(form_to_value(f)?);
838 }
839
840 let expanded_val = call_cljrs_fn(mfn, args.as_ref(), env)?;
841 let dummy_span = cljrs_types::span::Span::new(Arc::new("<macro>".to_string()), 0, 0, 1, 1);
842 crate::interp::macros::value_to_form(&expanded_val, dummy_span)
843}
844
845fn handle_apply_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
847 let mut evaled: Vec<Value> = Vec::with_capacity(arg_forms.len());
848 for f in arg_forms {
849 let _root = crate::env::gc_roots::root_values(&evaled);
850 evaled.push(eval(f, env)?);
851 }
852
853 if evaled.len() < 2 {
854 return Err(EvalError::Arity {
855 name: "apply".into(),
856 expected: "2+".into(),
857 got: evaled.len(),
858 });
859 }
860
861 let f = evaled.remove(0);
862 let last = evaled.pop().unwrap();
863 let _f_root = crate::env::gc_roots::root_value(&f);
865 let _last_root = crate::env::gc_roots::root_value(&last);
866 let _evaled_root = crate::env::gc_roots::root_values(&evaled);
867 let spread = value_to_seq_vec(&last);
869 evaled.extend(spread);
870 crate::env::apply::apply_value(&f, evaled, env)
871}
872
873pub fn handle_make_lazy_seq(arg_forms: &[Form], env: &mut Env) -> EvalResult {
875 if arg_forms.len() != 1 {
876 return Err(EvalError::Arity {
877 name: "make-lazy-seq".into(),
878 expected: "1".into(),
879 got: arg_forms.len(),
880 });
881 }
882 let f_val = eval(&arg_forms[0], env)?;
883 let f = match f_val {
884 Value::Fn(f) => f.get().clone(),
885 other => {
886 return Err(EvalError::Runtime(format!(
887 "make-lazy-seq requires a fn, got {}",
888 other.type_name()
889 )));
890 }
891 };
892 let thunk = ClosureThunk {
893 f,
894 globals: env.globals.clone(),
895 ns: env.current_ns.clone(),
896 };
897 Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))))
898}
899
900fn handle_make_delay(arg_forms: &[Form], env: &mut Env) -> EvalResult {
902 if arg_forms.len() != 1 {
903 return Err(EvalError::Arity {
904 name: "make-delay".into(),
905 expected: "1".into(),
906 got: arg_forms.len(),
907 });
908 }
909 let f_val = eval(&arg_forms[0], env)?;
910 let f = match f_val {
911 Value::Fn(f) => f.get().clone(),
912 other => {
913 return Err(EvalError::Runtime(format!(
914 "make-delay requires a fn, got {}",
915 other.type_name()
916 )));
917 }
918 };
919 let thunk = ClosureThunk {
920 f,
921 globals: env.globals.clone(),
922 ns: env.current_ns.clone(),
923 };
924 Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
925}
926
927fn handle_vswap(arg_forms: &[Form], env: &mut Env) -> EvalResult {
929 if arg_forms.len() < 2 {
930 return Err(EvalError::Arity {
931 name: "vswap!".into(),
932 expected: "2+".into(),
933 got: arg_forms.len(),
934 });
935 }
936 let vol_val = eval(&arg_forms[0], env)?;
937 let f = eval(&arg_forms[1], env)?;
938 let extra: Vec<Value> = arg_forms[2..]
939 .iter()
940 .map(|a| eval(a, env))
941 .collect::<EvalResult<_>>()?;
942
943 match vol_val {
944 Value::Volatile(v) => {
945 let cur = v.get().deref();
946 let mut call_args = vec![cur];
947 call_args.extend(extra);
948 #[cfg(feature = "no-gc")]
951 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
952 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
953 v.get().reset(new_val.clone());
954 Ok(new_val)
955 }
956 other => Err(EvalError::Runtime(format!(
957 "vswap!: expected volatile, got {}",
958 other.type_name()
959 ))),
960 }
961}
962
963fn handle_volatile(arg_forms: &[Form], env: &mut Env) -> EvalResult {
967 if arg_forms.is_empty() {
968 return Err(EvalError::Arity {
969 name: "volatile!".into(),
970 expected: "1".into(),
971 got: 0,
972 });
973 }
974 #[cfg(feature = "no-gc")]
977 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
978 let initial = eval(&arg_forms[0], env)?;
979 Ok(Value::Volatile(GcPtr::new(Volatile::new(initial))))
980}
981
982fn handle_vreset(arg_forms: &[Form], env: &mut Env) -> EvalResult {
986 if arg_forms.len() < 2 {
987 return Err(EvalError::Arity {
988 name: "vreset!".into(),
989 expected: "2".into(),
990 got: arg_forms.len(),
991 });
992 }
993 let vol_val = eval(&arg_forms[0], env)?;
994 #[cfg(feature = "no-gc")]
997 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
998 let new_val = eval(&arg_forms[1], env)?;
999 match &vol_val {
1000 Value::Volatile(v) => {
1001 v.get().reset(new_val.clone());
1002 Ok(new_val)
1003 }
1004 other => Err(EvalError::Runtime(format!(
1005 "vreset!: expected volatile, got {}",
1006 other.type_name()
1007 ))),
1008 }
1009}
1010
1011fn handle_agent_call(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1015 Err(EvalError::Runtime("agent is not yet implemented".into()))
1016}
1017
1018fn handle_send(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1020 Err(EvalError::Runtime(
1021 "send/send-off: agents are not yet implemented".into(),
1022 ))
1023}
1024
1025fn handle_atom_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1029 if arg_forms.is_empty() {
1030 return Err(EvalError::Arity {
1031 name: "atom".into(),
1032 expected: "1+".into(),
1033 got: 0,
1034 });
1035 }
1036 #[cfg(feature = "no-gc")]
1039 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1040 let initial = eval(&arg_forms[0], env)?;
1041
1042 let options: Vec<Value> = arg_forms[1..]
1044 .iter()
1045 .map(|f| eval(f, env))
1046 .collect::<EvalResult<_>>()?;
1047
1048 let mut meta_opt: Option<Value> = None;
1049 let mut validator_opt: Option<Value> = None;
1050 let mut i = 0;
1051 while i + 1 < options.len() {
1052 match &options[i] {
1053 Value::Keyword(k) if k.get().name.as_ref() == "meta" => {
1054 meta_opt = Some(options[i + 1].clone());
1055 i += 2;
1056 }
1057 Value::Keyword(k) if k.get().name.as_ref() == "validator" => {
1058 let vf = options[i + 1].clone();
1059 validator_opt = if vf == Value::Nil { None } else { Some(vf) };
1060 i += 2;
1061 }
1062 _ => {
1063 i += 2;
1064 }
1065 }
1066 }
1067
1068 if let Some(ref m) = meta_opt
1070 && !matches!(m, Value::Nil | Value::Map(_))
1071 {
1072 return Err(EvalError::Thrown(Value::string(
1073 "Atom metadata must be a map or nil".to_string(),
1074 )));
1075 }
1076
1077 if let Some(ref vf) = validator_opt {
1079 let result = crate::env::apply::apply_value(vf, vec![initial.clone()], env)?;
1080 if result == Value::Nil || result == Value::Bool(false) {
1081 return Err(EvalError::Thrown(Value::string(
1082 "Invalid initial value for atom".to_string(),
1083 )));
1084 }
1085 }
1086
1087 let atom = GcPtr::new(Atom::new(initial));
1088 if let Some(m) = meta_opt {
1089 atom.get()
1090 .set_meta(if m == Value::Nil { None } else { Some(m) });
1091 }
1092 if let Some(vf) = validator_opt {
1093 atom.get().set_validator(Some(vf));
1094 }
1095 Ok(Value::Atom(atom))
1096}
1097
1098fn shared_atom_reset(sa: &Arc<cljrs_value::SharedAtom>, new_val: Value) -> EvalResult {
1110 let promoted = cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1111 sa.reset(promoted);
1112 Ok(new_val)
1113}
1114
1115fn shared_atom_swap(
1120 sa: &Arc<cljrs_value::SharedAtom>,
1121 f: &Value,
1122 extra: Vec<Value>,
1123 env: &mut Env,
1124) -> EvalResult {
1125 loop {
1126 let cur = sa.deref_val();
1127 let old_val = cljrs_value::demote(&cur);
1128 let mut call_args = Vec::with_capacity(1 + extra.len());
1129 call_args.push(old_val);
1130 call_args.extend(extra.iter().cloned());
1131 let new_val = crate::env::apply::apply_value(f, call_args, env)?;
1132 let promoted =
1133 cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1134 if sa.compare_and_set(&cur, promoted) {
1135 return Ok(new_val);
1136 }
1137 }
1139}
1140
1141fn handle_reset_bang(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1144 if arg_forms.len() < 2 {
1145 return Err(EvalError::Arity {
1146 name: "reset!".into(),
1147 expected: "2".into(),
1148 got: arg_forms.len(),
1149 });
1150 }
1151 let atom_val = eval(&arg_forms[0], env)?;
1152 #[cfg(feature = "no-gc")]
1155 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1156 let new_val = eval(&arg_forms[1], env)?;
1157
1158 let atom = match &atom_val {
1159 Value::Atom(a) => a.clone(),
1160 Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1161 v => {
1162 return Err(EvalError::Runtime(format!(
1163 "reset! requires an atom, got {}",
1164 v.type_name()
1165 )));
1166 }
1167 };
1168
1169 validate_atom_value(&atom, &new_val, env)?;
1170 let old_val = atom.get().deref();
1171 atom.get().reset(new_val.clone());
1172 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1173 check_watch_error()?;
1174 Ok(new_val)
1175}
1176
1177fn validate_atom_value(atom: &GcPtr<Atom>, new_val: &Value, env: &mut Env) -> EvalResult<()> {
1179 if let Some(vf) = atom.get().get_validator() {
1180 let result = crate::env::apply::apply_value(&vf, vec![new_val.clone()], env)?;
1181 if result == Value::Nil || result == Value::Bool(false) {
1182 return Err(EvalError::Thrown(Value::string(
1183 "Invalid value for atom".to_string(),
1184 )));
1185 }
1186 }
1187 Ok(())
1188}
1189
1190fn handle_swap_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1193 let mut evaled: Vec<Value> = arg_forms
1194 .iter()
1195 .map(|f| eval(f, env))
1196 .collect::<EvalResult<_>>()?;
1197
1198 if evaled.len() < 2 {
1199 return Err(EvalError::Arity {
1200 name: "swap!".into(),
1201 expected: "2+".into(),
1202 got: evaled.len(),
1203 });
1204 }
1205
1206 let atom_val = evaled.remove(0);
1207 let f = evaled.remove(0);
1208
1209 let atom = match &atom_val {
1210 Value::Atom(a) => a.clone(),
1211 Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, evaled, env),
1212 v => {
1213 return Err(EvalError::Runtime(format!(
1214 "swap! requires an atom, got {}",
1215 v.type_name()
1216 )));
1217 }
1218 };
1219
1220 let old_val = atom.get().deref();
1221 let mut args = vec![old_val.clone()];
1222 args.extend(evaled);
1223 #[cfg(feature = "no-gc")]
1226 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1227 let new_val = crate::env::apply::apply_value(&f, args, env)?;
1228 validate_atom_value(&atom, &new_val, env)?;
1229 atom.get().reset(new_val.clone());
1230 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1231 check_watch_error()?;
1232 Ok(new_val)
1233}
1234
1235fn handle_with_bindings(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1240 if arg_forms.len() < 2 {
1241 return Err(EvalError::Arity {
1242 name: "with-bindings*".into(),
1243 expected: "2".into(),
1244 got: arg_forms.len(),
1245 });
1246 }
1247 let map_val = eval(&arg_forms[0], env)?;
1248 let func_val = eval(&arg_forms[1], env)?;
1249
1250 let mut frame: HashMap<usize, Value> = HashMap::new();
1251 if let Value::Map(m) = &map_val {
1252 m.for_each(|k, v| {
1253 if let Value::Var(vp) = k {
1254 frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1255 }
1256 });
1258 } else {
1259 return Err(EvalError::Runtime(
1260 "with-bindings*: first arg must be a map".into(),
1261 ));
1262 }
1263
1264 let _guard = crate::env::dynamics::push_frame(frame);
1265 crate::env::apply::apply_value(&func_val, vec![], env)
1266}
1267
1268fn handle_alter_var_root(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1272 if arg_forms.len() < 2 {
1273 return Err(EvalError::Arity {
1274 name: "alter-var-root".into(),
1275 expected: "2+".into(),
1276 got: arg_forms.len(),
1277 });
1278 }
1279 let var_val = eval(&arg_forms[0], env)?;
1280 let f = eval(&arg_forms[1], env)?;
1281 let extra: Vec<Value> = arg_forms[2..]
1282 .iter()
1283 .map(|form| eval(form, env))
1284 .collect::<EvalResult<_>>()?;
1285
1286 let vp = match &var_val {
1287 Value::Var(vp) => vp.clone(),
1288 v => {
1289 return Err(EvalError::Runtime(format!(
1290 "alter-var-root: expected var, got {}",
1291 v.type_name()
1292 )));
1293 }
1294 };
1295 let old_val = vp.get().deref().unwrap_or(Value::Nil);
1296 let mut call_args = vec![old_val.clone()];
1297 call_args.extend(extra);
1298 #[cfg(feature = "no-gc")]
1301 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1302 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1303 vp.get().bind(new_val.clone());
1304 fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1305 check_watch_error()?;
1306 Ok(new_val)
1307}
1308
1309fn handle_vary_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1313 if arg_forms.len() < 2 {
1314 return Err(EvalError::Arity {
1315 name: "vary-meta".into(),
1316 expected: "2+".into(),
1317 got: arg_forms.len(),
1318 });
1319 }
1320 let obj = eval(&arg_forms[0], env)?;
1321 let f = eval(&arg_forms[1], env)?;
1322 let extra: Vec<Value> = arg_forms[2..]
1323 .iter()
1324 .map(|form| eval(form, env))
1325 .collect::<EvalResult<_>>()?;
1326
1327 let current_meta = match &obj {
1328 Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1329 _ => Value::Nil,
1330 };
1331 let mut call_args = vec![current_meta];
1332 call_args.extend(extra);
1333 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1334 if let Value::Var(vp) = &obj {
1335 vp.get().set_meta(new_meta);
1336 }
1337 Ok(obj)
1338}
1339
1340fn handle_eval(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1344 let [arg] = arg_forms else {
1345 return Err(EvalError::Arity {
1346 name: "eval".into(),
1347 expected: "1".into(),
1348 got: arg_forms.len(),
1349 });
1350 };
1351 let value = eval(arg, env)?;
1352 eval_eval(vec![value], env)
1353}
1354
1355pub fn eval_eval(args: Vec<Value>, env: &mut Env) -> EvalResult {
1360 let [value] = args.as_slice() else {
1361 return Err(EvalError::Arity {
1362 name: "eval".into(),
1363 expected: "1".into(),
1364 got: args.len(),
1365 });
1366 };
1367 let span = cljrs_types::span::Span::new(Arc::new("<eval>".to_string()), 0, 0, 1, 1);
1368 let form = crate::interp::macros::value_to_form(value, span)?;
1369 let mut top = Env::new(env.globals.clone(), &env.current_ns);
1370 eval(&form, &mut top)
1371}
1372
1373pub fn eval_reset_bang(args: Vec<Value>, env: &mut Env) -> EvalResult {
1381 if args.len() < 2 {
1382 return Err(EvalError::Arity {
1383 name: "reset!".into(),
1384 expected: "2".into(),
1385 got: args.len(),
1386 });
1387 }
1388 let atom_val = args[0].clone();
1389 let new_val = args[1].clone();
1390 let atom = match &atom_val {
1391 Value::Atom(a) => a.clone(),
1392 Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1393 v => {
1394 return Err(EvalError::Runtime(format!(
1395 "reset! requires an atom, got {}",
1396 v.type_name()
1397 )));
1398 }
1399 };
1400 #[cfg(feature = "no-gc")]
1401 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1402 validate_atom_value(&atom, &new_val, env)?;
1403 let old_val = atom.get().deref();
1404 atom.get().reset(new_val.clone());
1405 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1406 check_watch_error()?;
1407 Ok(new_val)
1408}
1409
1410pub fn eval_swap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1412 if args.len() < 2 {
1413 return Err(EvalError::Arity {
1414 name: "swap!".into(),
1415 expected: "2+".into(),
1416 got: args.len(),
1417 });
1418 }
1419 let atom_val = args.remove(0);
1420 let f = args.remove(0);
1421 let atom = match &atom_val {
1422 Value::Atom(a) => a.clone(),
1423 Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, args, env),
1424 v => {
1425 return Err(EvalError::Runtime(format!(
1426 "swap! requires an atom, got {}",
1427 v.type_name()
1428 )));
1429 }
1430 };
1431 let old_val = atom.get().deref();
1432 let mut call_args = vec![old_val.clone()];
1433 call_args.extend(args);
1434 #[cfg(feature = "no-gc")]
1435 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1436 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1437 validate_atom_value(&atom, &new_val, env)?;
1438 atom.get().reset(new_val.clone());
1439 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1440 check_watch_error()?;
1441 Ok(new_val)
1442}
1443
1444pub fn eval_volatile(args: Vec<Value>) -> EvalResult {
1446 if args.is_empty() {
1447 return Err(EvalError::Arity {
1448 name: "volatile!".into(),
1449 expected: "1".into(),
1450 got: 0,
1451 });
1452 }
1453 #[cfg(feature = "no-gc")]
1454 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1455 Ok(Value::Volatile(GcPtr::new(Volatile::new(
1456 args.into_iter().next().unwrap(),
1457 ))))
1458}
1459
1460pub fn eval_vreset_bang(args: Vec<Value>) -> EvalResult {
1462 if args.len() < 2 {
1463 return Err(EvalError::Arity {
1464 name: "vreset!".into(),
1465 expected: "2".into(),
1466 got: args.len(),
1467 });
1468 }
1469 #[cfg(feature = "no-gc")]
1470 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1471 let new_val = args[1].clone();
1472 match &args[0] {
1473 Value::Volatile(v) => {
1474 v.get().reset(new_val.clone());
1475 Ok(new_val)
1476 }
1477 other => Err(EvalError::Runtime(format!(
1478 "vreset!: expected volatile, got {}",
1479 other.type_name()
1480 ))),
1481 }
1482}
1483
1484pub fn eval_vswap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1486 if args.len() < 2 {
1487 return Err(EvalError::Arity {
1488 name: "vswap!".into(),
1489 expected: "2+".into(),
1490 got: args.len(),
1491 });
1492 }
1493 let vol_val = args.remove(0);
1494 let f = args.remove(0);
1495 match vol_val {
1496 Value::Volatile(v) => {
1497 let cur = v.get().deref();
1498 let mut call_args = vec![cur];
1499 call_args.extend(args);
1500 #[cfg(feature = "no-gc")]
1501 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1502 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1503 v.get().reset(new_val.clone());
1504 Ok(new_val)
1505 }
1506 other => Err(EvalError::Runtime(format!(
1507 "vswap!: expected volatile, got {}",
1508 other.type_name()
1509 ))),
1510 }
1511}
1512
1513pub fn make_delay_from_fn(
1518 f_val: &Value,
1519 globals: std::sync::Arc<crate::env::env::GlobalEnv>,
1520 ns: std::sync::Arc<str>,
1521) -> EvalResult {
1522 let f = match f_val {
1523 Value::Fn(f) => f.get().clone(),
1524 other => {
1525 return Err(EvalError::Runtime(format!(
1526 "make-delay requires a fn, got {}",
1527 other.type_name()
1528 )));
1529 }
1530 };
1531 let thunk = ClosureThunk { f, globals, ns };
1532 Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
1533}
1534
1535pub fn eval_alter_var_root(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1537 if args.len() < 2 {
1538 return Err(EvalError::Arity {
1539 name: "alter-var-root".into(),
1540 expected: "2+".into(),
1541 got: args.len(),
1542 });
1543 }
1544 let var_val = args.remove(0);
1545 let f = args.remove(0);
1546 let vp = match &var_val {
1547 Value::Var(vp) => vp.clone(),
1548 v => {
1549 return Err(EvalError::Runtime(format!(
1550 "alter-var-root: expected var, got {}",
1551 v.type_name()
1552 )));
1553 }
1554 };
1555 let old_val = vp.get().deref().unwrap_or(Value::Nil);
1556 let mut call_args = vec![old_val.clone()];
1557 call_args.extend(args);
1558 #[cfg(feature = "no-gc")]
1559 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1560 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1561 vp.get().bind(new_val.clone());
1562 fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1563 check_watch_error()?;
1564 Ok(new_val)
1565}
1566
1567pub fn eval_vary_meta(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1569 if args.len() < 2 {
1570 return Err(EvalError::Arity {
1571 name: "vary-meta".into(),
1572 expected: "2+".into(),
1573 got: args.len(),
1574 });
1575 }
1576 let obj = args.remove(0);
1577 let f = args.remove(0);
1578 let current_meta = match &obj {
1579 Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1580 _ => Value::Nil,
1581 };
1582 let mut call_args = vec![current_meta];
1583 call_args.extend(args);
1584 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1585 if let Value::Var(vp) = &obj {
1586 vp.get().set_meta(new_meta);
1587 }
1588 Ok(obj)
1589}
1590
1591pub fn eval_with_bindings_star(args: Vec<Value>, env: &mut Env) -> EvalResult {
1593 if args.len() < 2 {
1594 return Err(EvalError::Arity {
1595 name: "with-bindings*".into(),
1596 expected: "2".into(),
1597 got: args.len(),
1598 });
1599 }
1600 let mut frame: HashMap<usize, Value> = HashMap::new();
1601 if let Value::Map(m) = &args[0] {
1602 m.for_each(|k, v| {
1603 if let Value::Var(vp) = k {
1604 frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1605 }
1606 });
1607 } else {
1608 return Err(EvalError::Runtime(
1609 "with-bindings*: first arg must be a map".into(),
1610 ));
1611 }
1612 let _guard = crate::env::dynamics::push_frame(frame);
1613 crate::env::apply::apply_value(&args[1], vec![], env)
1614}
1615
1616pub fn eval_send_to_agent(_args: Vec<Value>, _env: &mut Env) -> EvalResult {
1618 Err(EvalError::Runtime(
1619 "send/send-off: agents are not yet implemented".into(),
1620 ))
1621}
1622
1623fn ns_name_from_val(v: &Value) -> Result<String, EvalError> {
1626 match v {
1627 Value::Symbol(s) => Ok(s.get().name.as_ref().to_string()),
1628 Value::Str(s) => Ok(s.get().clone()),
1629 Value::Namespace(ns) => Ok(ns.get().name.as_ref().to_string()),
1630 Value::Keyword(k) => Ok(k.get().name.as_ref().to_string()),
1631 other => Err(EvalError::Runtime(format!(
1632 "expected symbol, string, or namespace, got {}",
1633 other.type_name()
1634 ))),
1635 }
1636}
1637
1638fn the_ns(v: &Value, env: &Env) -> Result<GcPtr<cljrs_value::Namespace>, EvalError> {
1643 if let Value::Namespace(ns) = v {
1644 return Ok(ns.clone());
1645 }
1646 let name = ns_name_from_val(v)?;
1647 let map = env.globals.namespaces.read().unwrap();
1648 match map.get(name.as_str()) {
1649 Some(ns) => Ok(ns.clone()),
1650 None => Err(EvalError::Runtime(format!("No namespace: {name} found"))),
1651 }
1652}
1653
1654fn handle_ns_interns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1657 if arg_forms.is_empty() {
1658 return Err(EvalError::Arity {
1659 name: "ns-interns".into(),
1660 expected: "1".into(),
1661 got: 0,
1662 });
1663 }
1664 let arg = eval(&arg_forms[0], env)?;
1665 let ns = the_ns(&arg, env)?;
1666 crate::builtins::builtins::builtin_ns_interns(&[Value::Namespace(ns)])
1667 .map_err(crate::env::error::value_error_to_eval_error)
1668}
1669
1670fn handle_ns_refers(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1672 if arg_forms.is_empty() {
1673 return Err(EvalError::Arity {
1674 name: "ns-refers".into(),
1675 expected: "1".into(),
1676 got: 0,
1677 });
1678 }
1679 let arg = eval(&arg_forms[0], env)?;
1680 let ns = the_ns(&arg, env)?;
1681 crate::builtins::builtins::builtin_ns_refers(&[Value::Namespace(ns)])
1682 .map_err(crate::env::error::value_error_to_eval_error)
1683}
1684
1685fn handle_ns_map(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1687 if arg_forms.is_empty() {
1688 return Err(EvalError::Arity {
1689 name: "ns-map".into(),
1690 expected: "1".into(),
1691 got: 0,
1692 });
1693 }
1694 let arg = eval(&arg_forms[0], env)?;
1695 let ns = the_ns(&arg, env)?;
1696 crate::builtins::builtins::builtin_ns_map(&[Value::Namespace(ns)])
1697 .map_err(crate::env::error::value_error_to_eval_error)
1698}
1699
1700fn handle_find_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1702 if arg_forms.is_empty() {
1703 return Err(EvalError::Arity {
1704 name: "find-ns".into(),
1705 expected: "1".into(),
1706 got: 0,
1707 });
1708 }
1709 let arg = eval(&arg_forms[0], env)?;
1710 let name = ns_name_from_val(&arg)?;
1711 let map = env.globals.namespaces.read().unwrap();
1712 match map.get(name.as_str()) {
1713 Some(ns) => Ok(Value::Namespace(ns.clone())),
1714 None => Ok(Value::Nil),
1715 }
1716}
1717
1718fn handle_all_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1720 if !arg_forms.is_empty() {
1721 let _ = eval(&arg_forms[0], env)?; }
1723 let map = env.globals.namespaces.read().unwrap();
1724 let items: Vec<Value> = map
1725 .values()
1726 .map(|ns| Value::Namespace(ns.clone()))
1727 .collect();
1728 drop(map);
1729 Ok(Value::List(cljrs_gc::GcPtr::new(
1730 cljrs_value::PersistentList::from_iter(items),
1731 )))
1732}
1733
1734fn handle_create_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1736 if arg_forms.is_empty() {
1737 return Err(EvalError::Arity {
1738 name: "create-ns".into(),
1739 expected: "1".into(),
1740 got: 0,
1741 });
1742 }
1743 let arg = eval(&arg_forms[0], env)?;
1744 let name = ns_name_from_val(&arg)?;
1745 let ns = env.globals.get_or_create_ns(&name);
1746 Ok(Value::Namespace(ns))
1747}
1748
1749fn handle_ns_aliases(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1751 if arg_forms.is_empty() {
1752 return Err(EvalError::Arity {
1753 name: "ns-aliases".into(),
1754 expected: "1".into(),
1755 got: 0,
1756 });
1757 }
1758 let ns_val = eval(&arg_forms[0], env)?;
1759 let ns_name = ns_name_from_val(&ns_val)?;
1760 let map = env.globals.namespaces.read().unwrap();
1761 let ns = match map.get(ns_name.as_str()) {
1762 Some(ns) => ns.clone(),
1763 None => return Ok(Value::Map(cljrs_value::MapValue::empty())),
1764 };
1765 let aliases = ns.get().aliases.lock().unwrap().clone();
1766 drop(map);
1767 let mut m = cljrs_value::MapValue::empty();
1768 for (alias, full_ns_name) in &aliases {
1769 let sym = Value::symbol(cljrs_value::Symbol::simple(alias.clone()));
1770 let nsmap = env.globals.namespaces.read().unwrap();
1771 if let Some(target_ns) = nsmap.get(full_ns_name.as_ref()) {
1772 m = m.assoc(sym, Value::Namespace(target_ns.clone()));
1773 }
1774 }
1775 Ok(Value::Map(m))
1776}
1777
1778fn handle_remove_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1780 if arg_forms.is_empty() {
1781 return Err(EvalError::Arity {
1782 name: "remove-ns".into(),
1783 expected: "1".into(),
1784 got: 0,
1785 });
1786 }
1787 let arg = eval(&arg_forms[0], env)?;
1788 let name = ns_name_from_val(&arg)?;
1789 env.globals
1790 .namespaces
1791 .write()
1792 .unwrap()
1793 .remove(name.as_str());
1794 Ok(Value::Nil)
1795}
1796
1797fn handle_alter_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1799 if arg_forms.len() < 2 {
1800 return Err(EvalError::Arity {
1801 name: "alter-meta!".into(),
1802 expected: "2+".into(),
1803 got: arg_forms.len(),
1804 });
1805 }
1806 let obj = eval(&arg_forms[0], env)?;
1807 let f = eval(&arg_forms[1], env)?;
1808 let extra: Vec<Value> = arg_forms[2..]
1809 .iter()
1810 .map(|form| eval(form, env))
1811 .collect::<EvalResult<_>>()?;
1812
1813 let current_meta = match &obj {
1814 Value::Var(vp) => vp
1815 .get()
1816 .get_meta()
1817 .unwrap_or(Value::Map(cljrs_value::MapValue::empty())),
1818 _ => Value::Map(cljrs_value::MapValue::empty()),
1819 };
1820 let mut call_args = vec![current_meta];
1821 call_args.extend(extra);
1822 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1823 if let Value::Var(vp) = &obj {
1824 vp.get().set_meta(new_meta.clone());
1825 }
1826 Ok(new_meta)
1827}
1828
1829fn handle_ns_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1831 if arg_forms.len() < 2 {
1832 return Err(EvalError::Arity {
1833 name: "ns-resolve".into(),
1834 expected: "2".into(),
1835 got: arg_forms.len(),
1836 });
1837 }
1838 let ns_arg = eval(&arg_forms[0], env)?;
1839 let sym_arg = eval(&arg_forms[1], env)?;
1840 let ns_name = ns_name_from_val(&ns_arg)?;
1841 let sym_name = match &sym_arg {
1842 Value::Symbol(s) => s.get().name.as_ref().to_string(),
1843 Value::Str(s) => s.get().clone(),
1844 other => {
1845 return Err(EvalError::Runtime(format!(
1846 "ns-resolve: second arg must be symbol or string, got {}",
1847 other.type_name()
1848 )));
1849 }
1850 };
1851 match env.globals.lookup_var(&ns_name, &sym_name) {
1852 Some(var_ptr) => Ok(Value::Var(var_ptr)),
1853 None => Ok(Value::Nil),
1854 }
1855}
1856
1857fn resolve_current_ns(env: &Env) -> Arc<str> {
1861 if let Some(var) = env.globals.lookup_var("clojure.core", "*ns*") {
1862 let val = crate::env::dynamics::deref_var(&var);
1863 if let Some(Value::Namespace(ns_ptr)) = val {
1864 return ns_ptr.get().name.clone();
1865 }
1866 }
1867 env.current_ns.clone()
1868}
1869
1870fn handle_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1872 if arg_forms.len() != 1 {
1873 return Err(EvalError::Arity {
1874 name: "resolve".into(),
1875 expected: "1".into(),
1876 got: arg_forms.len(),
1877 });
1878 }
1879 let resolve_ns = resolve_current_ns(env);
1880 let sym_arg = eval(&arg_forms[0], env)?;
1881 let sym_name = match &sym_arg {
1882 Value::Symbol(s) => {
1883 let sym = s.get();
1884 if let Some(ns) = &sym.namespace {
1886 let full_ns = env.globals.resolve_ns_part_in(&resolve_ns, ns.as_ref());
1889 return Ok(
1890 match env.globals.lookup_var_in_ns(&full_ns, sym.name.as_ref()) {
1891 Some(var_ptr) => Value::Var(var_ptr),
1892 None => Value::Nil,
1893 },
1894 );
1895 }
1896 sym.name.as_ref().to_string()
1897 }
1898 Value::Str(s) => s.get().clone(),
1899 other => {
1900 return Err(EvalError::Runtime(format!(
1901 "resolve: arg must be symbol or string, got {}",
1902 other.type_name()
1903 )));
1904 }
1905 };
1906 Ok(match env.globals.lookup_var_in_ns(&resolve_ns, &sym_name) {
1907 Some(var_ptr) => Value::Var(var_ptr),
1908 None => Value::Nil,
1909 })
1910}
1911
1912fn handle_intern(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1913 if arg_forms.len() < 2 || arg_forms.len() > 3 {
1914 return Err(EvalError::Runtime("intern expects 2 or 3 arguments".into()));
1915 }
1916 let ns_val = eval(&arg_forms[0], env)?;
1917 let ns_name: Arc<str> = match &ns_val {
1918 Value::Symbol(s) => s.get().name.clone(),
1919 Value::Namespace(ns) => ns.get().name.clone(),
1920 other => {
1921 return Err(EvalError::Runtime(format!(
1922 "intern: first arg must be namespace or symbol, got {}",
1923 other.type_name()
1924 )));
1925 }
1926 };
1927 let var_name: Arc<str> = match eval(&arg_forms[1], env)? {
1928 Value::Symbol(s) => s.get().name.clone(),
1929 other => {
1930 return Err(EvalError::Runtime(format!(
1931 "intern: second arg must be symbol, got {}",
1932 other.type_name()
1933 )));
1934 }
1935 };
1936 let ns = {
1938 let map = env.globals.namespaces.read().unwrap();
1939 map.get(ns_name.as_ref()).cloned()
1940 };
1941 let ns = ns.ok_or_else(|| EvalError::Runtime(format!("No namespace: {ns_name} found")))?;
1942 let var = if arg_forms.len() == 3 {
1943 #[cfg(feature = "no-gc")]
1946 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1947 let val = eval(&arg_forms[2], env)?;
1948 let mut interns = ns.get().interns.lock().unwrap();
1949 if let Some(var) = interns.get(&var_name) {
1950 var.get().bind(val);
1951 var.clone()
1952 } else {
1953 let var =
1954 cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1955 var.get().bind(val);
1956 interns.insert(var_name, var.clone());
1957 var
1958 }
1959 } else {
1960 let mut interns = ns.get().interns.lock().unwrap();
1961 if let Some(var) = interns.get(&var_name) {
1962 var.clone()
1963 } else {
1964 let var =
1965 cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1966 interns.insert(var_name, var.clone());
1967 var
1968 }
1969 };
1970 Ok(Value::Var(var))
1971}
1972
1973fn handle_bound_fn_star(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1978 if arg_forms.len() != 1 {
1979 return Err(EvalError::Arity {
1980 name: "bound-fn*".into(),
1981 expected: "1".into(),
1982 got: arg_forms.len(),
1983 });
1984 }
1985 let f = eval(&arg_forms[0], env)?;
1986 let frames = crate::env::dynamics::capture_current();
1988 let mut merged = std::collections::HashMap::new();
1989 for frame in &frames {
1990 merged.extend(frame.iter().map(|(k, v)| (*k, v.clone())));
1991 }
1992 Ok(Value::BoundFn(cljrs_gc::GcPtr::new(cljrs_value::BoundFn {
1993 wrapped: f,
1994 captured_bindings: merged,
1995 })))
1996}