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 ti.get().type_tag.as_ref() == "java.util.Date"
353 && method == "getTime"
354 && args.is_empty()
355 {
356 let key = Value::keyword(cljrs_value::Keyword::simple("millis"));
357 return Ok(ti.get().fields.get(&key).unwrap_or(Value::Nil));
358 }
359 if let Some(field) = method.strip_prefix('-') {
363 let key = Value::keyword(cljrs_value::Keyword::simple(field));
364 let inst = ti.get();
365 if let Some(atom) = &inst.mutable
368 && let Value::Map(m) = atom.get().deref()
369 && let Some(v) = m.get(&key)
370 {
371 return Ok(v);
372 }
373 Ok(inst.fields.get(&key).unwrap_or(Value::Nil))
374 } else {
375 Err(EvalError::Runtime(format!(
376 ".{method} not supported on {} (only .-field access is)",
377 target.type_name()
378 )))
379 }
380 }
381 _ => Err(EvalError::Runtime(format!(
382 ".{method} not supported on type {}",
383 target.type_name()
384 ))),
385 }
386}
387
388fn dispatch_string_method(method: &str, s: &str, args: &[Value]) -> EvalResult {
389 match method {
390 "indexOf" => {
391 let needle = match args.first() {
392 Some(Value::Str(s)) => s.get().to_string(),
393 Some(Value::Char(c)) => c.to_string(),
394 Some(v) => {
395 return Err(EvalError::Runtime(format!(
396 ".indexOf expects string or char argument, got {}",
397 v.type_name()
398 )));
399 }
400 None => return Err(EvalError::Runtime(".indexOf requires an argument".into())),
401 };
402 match s.find(&needle) {
403 Some(pos) => Ok(Value::Long(pos as i64)),
404 None => Ok(Value::Long(-1)),
405 }
406 }
407 "lastIndexOf" => {
408 let needle = match args.first() {
409 Some(Value::Str(s)) => s.get().to_string(),
410 Some(Value::Char(c)) => c.to_string(),
411 _ => {
412 return Err(EvalError::Runtime(
413 ".lastIndexOf requires a string or char argument".into(),
414 ));
415 }
416 };
417 match s.rfind(&needle) {
418 Some(pos) => Ok(Value::Long(pos as i64)),
419 None => Ok(Value::Long(-1)),
420 }
421 }
422 "startsWith" => {
423 let prefix = require_str_arg(args, ".startsWith")?;
424 Ok(Value::Bool(s.starts_with(&prefix)))
425 }
426 "endsWith" => {
427 let suffix = require_str_arg(args, ".endsWith")?;
428 Ok(Value::Bool(s.ends_with(&suffix)))
429 }
430 "contains" => {
431 let sub = require_str_arg(args, ".contains")?;
432 Ok(Value::Bool(s.contains(&sub)))
433 }
434 "length" => Ok(Value::Long(s.len() as i64)),
435 "isEmpty" => Ok(Value::Bool(s.is_empty())),
436 "charAt" => {
437 let idx = require_long_arg(args, ".charAt")? as usize;
438 s.chars()
439 .nth(idx)
440 .map(Value::Char)
441 .ok_or_else(|| EvalError::Runtime(format!(".charAt index {idx} out of bounds")))
442 }
443 "substring" => {
444 let start = require_long_arg(args, ".substring")? as usize;
445 let end = args
446 .get(1)
447 .map(|v| match v {
448 Value::Long(n) => Ok(*n as usize),
449 _ => Err(EvalError::Runtime(
450 ".substring end must be an integer".into(),
451 )),
452 })
453 .transpose()?;
454 let result = match end {
455 Some(e) => &s[start..e.min(s.len())],
456 None => &s[start..],
457 };
458 Ok(Value::Str(GcPtr::new(result.to_string())))
459 }
460 "toUpperCase" => Ok(Value::Str(GcPtr::new(s.to_uppercase()))),
461 "toLowerCase" => Ok(Value::Str(GcPtr::new(s.to_lowercase()))),
462 "trim" => Ok(Value::Str(GcPtr::new(s.trim().to_string()))),
463 "replace" => {
464 let from = require_str_arg(args, ".replace")?;
465 let to = match args.get(1) {
466 Some(Value::Str(s)) => s.get().to_string(),
467 Some(Value::Char(c)) => c.to_string(),
468 _ => {
469 return Err(EvalError::Runtime(
470 ".replace requires two string arguments".into(),
471 ));
472 }
473 };
474 Ok(Value::Str(GcPtr::new(s.replace(&from, &to))))
475 }
476 "split" => {
477 let sep = require_str_arg(args, ".split")?;
478 let parts: Vec<Value> = s
479 .split(&sep)
480 .map(|p| Value::Str(GcPtr::new(p.to_string())))
481 .collect();
482 Ok(Value::Vector(GcPtr::new(
483 cljrs_value::PersistentVector::from_iter(parts),
484 )))
485 }
486 _ => Err(EvalError::Runtime(format!(
487 ".{method} not supported on String"
488 ))),
489 }
490}
491
492fn dispatch_vector_method(
493 method: &str,
494 v: &GcPtr<cljrs_value::PersistentVector>,
495 args: &[Value],
496) -> EvalResult {
497 match method {
498 "indexOf" => {
499 let needle = args
500 .first()
501 .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
502 for (i, item) in v.get().iter().enumerate() {
503 if item == needle {
504 return Ok(Value::Long(i as i64));
505 }
506 }
507 Ok(Value::Long(-1))
508 }
509 "size" | "count" => Ok(Value::Long(v.get().count() as i64)),
510 _ => Err(EvalError::Runtime(format!(
511 ".{method} not supported on Vector"
512 ))),
513 }
514}
515
516fn dispatch_seq_method(method: &str, target: &Value, args: &[Value]) -> EvalResult {
517 match method {
518 "indexOf" => {
519 let needle = args
520 .first()
521 .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
522 let items = crate::interp::destructure::value_to_seq_vec(target);
523 for (i, item) in items.iter().enumerate() {
524 if item == needle {
525 return Ok(Value::Long(i as i64));
526 }
527 }
528 Ok(Value::Long(-1))
529 }
530 _ => Err(EvalError::Runtime(format!(
531 ".{method} not supported on {}",
532 target.type_name()
533 ))),
534 }
535}
536
537fn require_str_arg(args: &[Value], method: &str) -> Result<String, EvalError> {
538 match args.first() {
539 Some(Value::Str(s)) => Ok(s.get().to_string()),
540 Some(Value::Char(c)) => Ok(c.to_string()),
541 _ => Err(EvalError::Runtime(format!(
542 "{method} requires a string argument"
543 ))),
544 }
545}
546
547fn require_long_arg(args: &[Value], method: &str) -> Result<i64, EvalError> {
548 match args.first() {
549 Some(Value::Long(n)) => Ok(*n),
550 _ => Err(EvalError::Runtime(format!(
551 "{method} requires an integer argument"
552 ))),
553 }
554}
555
556pub fn resolve_type_tag(sym: &str) -> Arc<str> {
559 Arc::from(sym)
560}
561
562pub fn call_cljrs_fn(f: &CljxFn, args: &[Value], caller_env: &mut Env) -> EvalResult {
564 let arity = select_arity(f, args.len())?;
565
566 let _caller_root = crate::env::gc_roots::push_env_root(caller_env);
569
570 let mut env = Env::with_closure(caller_env.globals.clone(), &f.defining_ns, f);
573
574 let mut current_args = Vec::from(args);
575 loop {
576 let _args_root = crate::env::gc_roots::root_values(¤t_args);
579
580 crate::env::gc_roots::gc_safepoint(&env);
582
583 env.push_frame();
584
585 #[cfg(not(feature = "no-gc"))]
595 let _call_frame = cljrs_gc::push_alloc_frame();
596
597 if let Some(ref name) = f.name {
606 let self_val = if let Some(ref p) = f.self_ptr {
607 Value::Fn(p.clone())
608 } else {
609 Value::Fn(GcPtr::new(f.clone()))
610 };
611 env.bind(name.clone(), self_val);
612 }
613
614 bind_fn_params(arity, ¤t_args, &mut env)?;
616
617 #[cfg(not(feature = "no-gc"))]
622 let result = eval_body_recur_fn(&arity.body, &mut env);
623 #[cfg(feature = "no-gc")]
624 let result = {
625 let mut scratch = cljrs_gc::alloc_ctx::ScratchGuard::new();
626 eval_body_with_scratch(&arity.body, &mut scratch, &mut env)
628 };
629 env.pop_frame();
630 match result {
634 Ok(v) => return Ok(v),
635 Err(EvalError::Recur(new_args)) => {
636 if arity.rest_param.is_some() {
641 let n = arity.params.len();
642 if new_args.len() == n + 1 {
643 let mut flat = new_args[..n].to_vec();
644 let rest_val = &new_args[n];
646 match rest_val {
647 Value::Nil => {} _ => {
649 let rest_items = value_to_seq_vec(rest_val);
650 flat.extend(rest_items);
651 }
652 }
653 current_args = flat;
654 } else {
655 current_args = new_args;
656 }
657 } else {
658 current_args = new_args;
659 }
660 }
661 Err(e) => return Err(e),
662 }
663 }
664}
665
666pub fn bind_fn_params(arity: &CljxFnArity, args: &[Value], env: &mut Env) -> EvalResult<()> {
669 bind_fn_params_impl(arity, args, env, true)
670}
671
672pub fn bind_fn_params_positional(
683 arity: &CljxFnArity,
684 args: &[Value],
685 env: &mut Env,
686) -> EvalResult<()> {
687 bind_fn_params_impl(arity, args, env, false)
688}
689
690fn bind_fn_params_impl(
691 arity: &CljxFnArity,
692 args: &[Value],
693 env: &mut Env,
694 destructure: bool,
695) -> EvalResult<()> {
696 let n = arity.params.len();
697 for (i, name) in arity.params.iter().enumerate() {
699 let val = args.get(i).cloned().unwrap_or(Value::Nil);
700 env.bind(name.clone(), val);
701 }
702 if let Some(ref rest) = arity.rest_param {
704 let rest_items = args[n..].to_vec();
705 let rest_val = if rest_items.is_empty() {
706 Value::Nil
707 } else {
708 Value::List(GcPtr::new(PersistentList::from_iter(rest_items)))
709 };
710 env.bind(rest.clone(), rest_val.clone());
711 if destructure && let Some(ref pattern) = arity.destructure_rest {
713 let destructure_val = if pattern.is_kwargs_rest_pattern() {
717 let items = value_to_seq_vec(&rest_val);
718 Value::from_kwargs_rest(items).map_err(value_error_to_eval_error)?
719 } else {
720 rest_val
721 };
722 crate::interp::destructure::bind_pattern(pattern, destructure_val, env)?;
723 }
724 }
725 if destructure {
727 for (idx, pattern) in &arity.destructure_params {
728 let val = args.get(*idx).cloned().unwrap_or(Value::Nil);
729 crate::interp::destructure::bind_pattern(pattern, val, env)?;
730 }
731 }
732 Ok(())
733}
734
735#[cfg(not(feature = "no-gc"))]
737fn eval_body_recur_fn(body: &[cljrs_reader::Form], env: &mut Env) -> EvalResult {
738 let mut result = Value::Nil;
739 for form in body {
740 result = eval(form, env)?;
741 }
742 Ok(result)
743}
744
745#[cfg(feature = "no-gc")]
749fn eval_body_with_scratch(
750 body: &[cljrs_reader::Form],
751 scratch: &mut cljrs_gc::alloc_ctx::ScratchGuard,
752 env: &mut Env,
753) -> EvalResult {
754 if body.is_empty() {
755 scratch.pop_for_return();
756 return Ok(Value::Nil);
757 }
758 for form in &body[..body.len() - 1] {
760 eval(form, env)?;
761 }
762 scratch.pop_for_return();
764 eval(&body[body.len() - 1], env)
765}
766
767pub fn select_arity(f: &CljxFn, argc: usize) -> EvalResult<&CljxFnArity> {
769 let name = f.name.as_deref().unwrap_or("fn");
770 for arity in &f.arities {
772 if arity.rest_param.is_none() && arity.params.len() == argc {
773 return Ok(arity);
774 }
775 }
776 for arity in &f.arities {
778 if arity.rest_param.is_some() && argc >= arity.params.len() {
779 return Ok(arity);
780 }
781 }
782 let implicit = if f.is_macro { IMPLICIT_MACRO_ARGS } else { 0 };
787 let expected: Vec<String> = f
788 .arities
789 .iter()
790 .map(|a| {
791 let fixed = a.params.len().saturating_sub(implicit);
792 if a.rest_param.is_some() {
793 format!("{fixed}+")
794 } else {
795 fixed.to_string()
796 }
797 })
798 .collect();
799 Err(EvalError::Arity {
800 name: name.to_string(),
801 expected: expected.join(" or "),
802 got: argc.saturating_sub(implicit),
803 })
804}
805
806const IMPLICIT_MACRO_ARGS: usize = 2;
808
809fn macro_apply(
816 mfn: &CljxFn,
817 func_form: &Form,
818 arg_forms: &[Form],
819 env: &mut Env,
820) -> EvalResult<Form> {
821 let resolved_args: Vec<Form> = arg_forms
826 .iter()
827 .map(|f| crate::builtins::form::resolve_auto_forms(f, env))
828 .collect::<EvalResult<Vec<Form>>>()?;
829
830 let form_val = {
832 let mut items = vec![form_to_value(func_form)?];
833 for f in &resolved_args {
834 items.push(form_to_value(f)?);
835 }
836 Value::List(GcPtr::new(PersistentList::from_iter(items)))
837 };
838
839 let env_val = {
841 let (names, vals) = env.all_local_bindings();
842 let mut m = MapValue::empty();
843 for (name, val) in names.iter().zip(vals.iter()) {
844 m = m.assoc(Value::symbol(Symbol::simple(name.as_ref())), val.clone());
845 }
846 Value::Map(m)
847 };
848
849 let mut args = vec![form_val, env_val];
851 for f in &resolved_args {
852 args.push(form_to_value(f)?);
853 }
854
855 let expanded_val = call_cljrs_fn(mfn, args.as_ref(), env)?;
856 let dummy_span = cljrs_types::span::Span::new(Arc::new("<macro>".to_string()), 0, 0, 1, 1);
857 crate::interp::macros::value_to_form(&expanded_val, dummy_span)
858}
859
860fn handle_apply_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
862 let mut evaled: Vec<Value> = Vec::with_capacity(arg_forms.len());
863 for f in arg_forms {
864 let _root = crate::env::gc_roots::root_values(&evaled);
865 evaled.push(eval(f, env)?);
866 }
867
868 if evaled.len() < 2 {
869 return Err(EvalError::Arity {
870 name: "apply".into(),
871 expected: "2+".into(),
872 got: evaled.len(),
873 });
874 }
875
876 let f = evaled.remove(0);
877 let last = evaled.pop().unwrap();
878 let _f_root = crate::env::gc_roots::root_value(&f);
880 let _last_root = crate::env::gc_roots::root_value(&last);
881 let _evaled_root = crate::env::gc_roots::root_values(&evaled);
882 let spread =
884 crate::builtins::builtins::value_to_seq(&last).map_err(value_error_to_eval_error)?;
885 evaled.extend(spread);
886 crate::env::apply::apply_value(&f, evaled, env)
887}
888
889pub fn handle_make_lazy_seq(arg_forms: &[Form], env: &mut Env) -> EvalResult {
891 if arg_forms.len() != 1 {
892 return Err(EvalError::Arity {
893 name: "make-lazy-seq".into(),
894 expected: "1".into(),
895 got: arg_forms.len(),
896 });
897 }
898 let f_val = eval(&arg_forms[0], env)?;
899 let f = match f_val {
900 Value::Fn(f) => f.get().clone(),
901 other => {
902 return Err(EvalError::Runtime(format!(
903 "make-lazy-seq requires a fn, got {}",
904 other.type_name()
905 )));
906 }
907 };
908 let thunk = ClosureThunk {
909 f,
910 globals: env.globals.clone(),
911 ns: env.current_ns.clone(),
912 };
913 Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))))
914}
915
916fn handle_make_delay(arg_forms: &[Form], env: &mut Env) -> EvalResult {
918 if arg_forms.len() != 1 {
919 return Err(EvalError::Arity {
920 name: "make-delay".into(),
921 expected: "1".into(),
922 got: arg_forms.len(),
923 });
924 }
925 let f_val = eval(&arg_forms[0], env)?;
926 let f = match f_val {
927 Value::Fn(f) => f.get().clone(),
928 other => {
929 return Err(EvalError::Runtime(format!(
930 "make-delay requires a fn, got {}",
931 other.type_name()
932 )));
933 }
934 };
935 let thunk = ClosureThunk {
936 f,
937 globals: env.globals.clone(),
938 ns: env.current_ns.clone(),
939 };
940 Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
941}
942
943fn handle_vswap(arg_forms: &[Form], env: &mut Env) -> EvalResult {
945 if arg_forms.len() < 2 {
946 return Err(EvalError::Arity {
947 name: "vswap!".into(),
948 expected: "2+".into(),
949 got: arg_forms.len(),
950 });
951 }
952 let vol_val = eval(&arg_forms[0], env)?;
953 let f = eval(&arg_forms[1], env)?;
954 let extra: Vec<Value> = arg_forms[2..]
955 .iter()
956 .map(|a| eval(a, env))
957 .collect::<EvalResult<_>>()?;
958
959 match vol_val {
960 Value::Volatile(v) => {
961 let cur = v.get().deref();
962 let mut call_args = vec![cur];
963 call_args.extend(extra);
964 #[cfg(feature = "no-gc")]
967 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
968 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
969 v.get().reset(new_val.clone());
970 Ok(new_val)
971 }
972 other => Err(EvalError::Runtime(format!(
973 "vswap!: expected volatile, got {}",
974 other.type_name()
975 ))),
976 }
977}
978
979fn handle_volatile(arg_forms: &[Form], env: &mut Env) -> EvalResult {
983 if arg_forms.is_empty() {
984 return Err(EvalError::Arity {
985 name: "volatile!".into(),
986 expected: "1".into(),
987 got: 0,
988 });
989 }
990 #[cfg(feature = "no-gc")]
993 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
994 let initial = eval(&arg_forms[0], env)?;
995 Ok(Value::Volatile(GcPtr::new(Volatile::new(initial))))
996}
997
998fn handle_vreset(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1002 if arg_forms.len() < 2 {
1003 return Err(EvalError::Arity {
1004 name: "vreset!".into(),
1005 expected: "2".into(),
1006 got: arg_forms.len(),
1007 });
1008 }
1009 let vol_val = eval(&arg_forms[0], env)?;
1010 #[cfg(feature = "no-gc")]
1013 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1014 let new_val = eval(&arg_forms[1], env)?;
1015 match &vol_val {
1016 Value::Volatile(v) => {
1017 v.get().reset(new_val.clone());
1018 Ok(new_val)
1019 }
1020 other => Err(EvalError::Runtime(format!(
1021 "vreset!: expected volatile, got {}",
1022 other.type_name()
1023 ))),
1024 }
1025}
1026
1027fn handle_agent_call(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1031 Err(EvalError::Runtime("agent is not yet implemented".into()))
1032}
1033
1034fn handle_send(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1036 Err(EvalError::Runtime(
1037 "send/send-off: agents are not yet implemented".into(),
1038 ))
1039}
1040
1041fn handle_atom_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1045 if arg_forms.is_empty() {
1046 return Err(EvalError::Arity {
1047 name: "atom".into(),
1048 expected: "1+".into(),
1049 got: 0,
1050 });
1051 }
1052 #[cfg(feature = "no-gc")]
1055 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1056 let initial = eval(&arg_forms[0], env)?;
1057
1058 let options: Vec<Value> = arg_forms[1..]
1060 .iter()
1061 .map(|f| eval(f, env))
1062 .collect::<EvalResult<_>>()?;
1063
1064 let mut meta_opt: Option<Value> = None;
1065 let mut validator_opt: Option<Value> = None;
1066 let mut i = 0;
1067 while i + 1 < options.len() {
1068 match &options[i] {
1069 Value::Keyword(k) if k.get().name.as_ref() == "meta" => {
1070 meta_opt = Some(options[i + 1].clone());
1071 i += 2;
1072 }
1073 Value::Keyword(k) if k.get().name.as_ref() == "validator" => {
1074 let vf = options[i + 1].clone();
1075 validator_opt = if vf == Value::Nil { None } else { Some(vf) };
1076 i += 2;
1077 }
1078 _ => {
1079 i += 2;
1080 }
1081 }
1082 }
1083
1084 if let Some(ref m) = meta_opt
1086 && !matches!(m, Value::Nil | Value::Map(_))
1087 {
1088 return Err(EvalError::Thrown(Value::string(
1089 "Atom metadata must be a map or nil".to_string(),
1090 )));
1091 }
1092
1093 if let Some(ref vf) = validator_opt {
1095 let result = crate::env::apply::apply_value(vf, vec![initial.clone()], env)?;
1096 if result == Value::Nil || result == Value::Bool(false) {
1097 return Err(EvalError::Thrown(Value::string(
1098 "Invalid initial value for atom".to_string(),
1099 )));
1100 }
1101 }
1102
1103 let atom = GcPtr::new(Atom::new(initial));
1104 if let Some(m) = meta_opt {
1105 atom.get()
1106 .set_meta(if m == Value::Nil { None } else { Some(m) });
1107 }
1108 if let Some(vf) = validator_opt {
1109 atom.get().set_validator(Some(vf));
1110 }
1111 Ok(Value::Atom(atom))
1112}
1113
1114fn shared_atom_reset(sa: &Arc<cljrs_value::SharedAtom>, new_val: Value) -> EvalResult {
1126 let promoted = cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1127 sa.reset(promoted);
1128 Ok(new_val)
1129}
1130
1131fn shared_atom_swap(
1136 sa: &Arc<cljrs_value::SharedAtom>,
1137 f: &Value,
1138 extra: Vec<Value>,
1139 env: &mut Env,
1140) -> EvalResult {
1141 loop {
1142 let cur = sa.deref_val();
1143 let old_val = cljrs_value::demote(&cur);
1144 let mut call_args = Vec::with_capacity(1 + extra.len());
1145 call_args.push(old_val);
1146 call_args.extend(extra.iter().cloned());
1147 let new_val = crate::env::apply::apply_value(f, call_args, env)?;
1148 let promoted =
1149 cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1150 if sa.compare_and_set(&cur, promoted) {
1151 return Ok(new_val);
1152 }
1153 }
1155}
1156
1157fn handle_reset_bang(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1160 if arg_forms.len() < 2 {
1161 return Err(EvalError::Arity {
1162 name: "reset!".into(),
1163 expected: "2".into(),
1164 got: arg_forms.len(),
1165 });
1166 }
1167 let atom_val = eval(&arg_forms[0], env)?;
1168 #[cfg(feature = "no-gc")]
1171 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1172 let new_val = eval(&arg_forms[1], env)?;
1173
1174 let atom = match &atom_val {
1175 Value::Atom(a) => a.clone(),
1176 Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1177 v => {
1178 return Err(EvalError::Runtime(format!(
1179 "reset! requires an atom, got {}",
1180 v.type_name()
1181 )));
1182 }
1183 };
1184
1185 validate_atom_value(&atom, &new_val, env)?;
1186 let old_val = atom.get().deref();
1187 atom.get().reset(new_val.clone());
1188 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1189 check_watch_error()?;
1190 Ok(new_val)
1191}
1192
1193fn validate_atom_value(atom: &GcPtr<Atom>, new_val: &Value, env: &mut Env) -> EvalResult<()> {
1195 if let Some(vf) = atom.get().get_validator() {
1196 let result = crate::env::apply::apply_value(&vf, vec![new_val.clone()], env)?;
1197 if result == Value::Nil || result == Value::Bool(false) {
1198 return Err(EvalError::Thrown(Value::string(
1199 "Invalid value for atom".to_string(),
1200 )));
1201 }
1202 }
1203 Ok(())
1204}
1205
1206fn handle_swap_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1209 let mut evaled: Vec<Value> = arg_forms
1210 .iter()
1211 .map(|f| eval(f, env))
1212 .collect::<EvalResult<_>>()?;
1213
1214 if evaled.len() < 2 {
1215 return Err(EvalError::Arity {
1216 name: "swap!".into(),
1217 expected: "2+".into(),
1218 got: evaled.len(),
1219 });
1220 }
1221
1222 let atom_val = evaled.remove(0);
1223 let f = evaled.remove(0);
1224
1225 let atom = match &atom_val {
1226 Value::Atom(a) => a.clone(),
1227 Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, evaled, env),
1228 v => {
1229 return Err(EvalError::Runtime(format!(
1230 "swap! requires an atom, got {}",
1231 v.type_name()
1232 )));
1233 }
1234 };
1235
1236 let old_val = atom.get().deref();
1237 let mut args = vec![old_val.clone()];
1238 args.extend(evaled);
1239 #[cfg(feature = "no-gc")]
1242 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1243 let new_val = crate::env::apply::apply_value(&f, args, env)?;
1244 validate_atom_value(&atom, &new_val, env)?;
1245 atom.get().reset(new_val.clone());
1246 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1247 check_watch_error()?;
1248 Ok(new_val)
1249}
1250
1251fn handle_with_bindings(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1256 if arg_forms.len() < 2 {
1257 return Err(EvalError::Arity {
1258 name: "with-bindings*".into(),
1259 expected: "2".into(),
1260 got: arg_forms.len(),
1261 });
1262 }
1263 let map_val = eval(&arg_forms[0], env)?;
1264 let func_val = eval(&arg_forms[1], env)?;
1265
1266 let mut frame: HashMap<usize, Value> = HashMap::new();
1267 if let Value::Map(m) = &map_val {
1268 m.for_each(|k, v| {
1269 if let Value::Var(vp) = k {
1270 frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1271 }
1272 });
1274 } else {
1275 return Err(EvalError::Runtime(
1276 "with-bindings*: first arg must be a map".into(),
1277 ));
1278 }
1279
1280 let _guard = crate::env::dynamics::push_frame(frame);
1281 crate::env::apply::apply_value(&func_val, vec![], env)
1282}
1283
1284fn handle_alter_var_root(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1288 if arg_forms.len() < 2 {
1289 return Err(EvalError::Arity {
1290 name: "alter-var-root".into(),
1291 expected: "2+".into(),
1292 got: arg_forms.len(),
1293 });
1294 }
1295 let var_val = eval(&arg_forms[0], env)?;
1296 let f = eval(&arg_forms[1], env)?;
1297 let extra: Vec<Value> = arg_forms[2..]
1298 .iter()
1299 .map(|form| eval(form, env))
1300 .collect::<EvalResult<_>>()?;
1301
1302 let vp = match &var_val {
1303 Value::Var(vp) => vp.clone(),
1304 v => {
1305 return Err(EvalError::Runtime(format!(
1306 "alter-var-root: expected var, got {}",
1307 v.type_name()
1308 )));
1309 }
1310 };
1311 let old_val = vp.get().deref().unwrap_or(Value::Nil);
1312 let mut call_args = vec![old_val.clone()];
1313 call_args.extend(extra);
1314 #[cfg(feature = "no-gc")]
1317 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1318 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1319 vp.get().bind(new_val.clone());
1320 fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1321 check_watch_error()?;
1322 Ok(new_val)
1323}
1324
1325fn handle_vary_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1329 if arg_forms.len() < 2 {
1330 return Err(EvalError::Arity {
1331 name: "vary-meta".into(),
1332 expected: "2+".into(),
1333 got: arg_forms.len(),
1334 });
1335 }
1336 let obj = eval(&arg_forms[0], env)?;
1337 let f = eval(&arg_forms[1], env)?;
1338 let extra: Vec<Value> = arg_forms[2..]
1339 .iter()
1340 .map(|form| eval(form, env))
1341 .collect::<EvalResult<_>>()?;
1342
1343 let current_meta = match &obj {
1344 Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1345 _ => Value::Nil,
1346 };
1347 let mut call_args = vec![current_meta];
1348 call_args.extend(extra);
1349 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1350 if let Value::Var(vp) = &obj {
1351 vp.get().set_meta(new_meta);
1352 }
1353 Ok(obj)
1354}
1355
1356fn handle_eval(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1360 let [arg] = arg_forms else {
1361 return Err(EvalError::Arity {
1362 name: "eval".into(),
1363 expected: "1".into(),
1364 got: arg_forms.len(),
1365 });
1366 };
1367 let value = eval(arg, env)?;
1368 eval_eval(vec![value], env)
1369}
1370
1371pub fn eval_eval(args: Vec<Value>, env: &mut Env) -> EvalResult {
1376 let [value] = args.as_slice() else {
1377 return Err(EvalError::Arity {
1378 name: "eval".into(),
1379 expected: "1".into(),
1380 got: args.len(),
1381 });
1382 };
1383 if matches!(
1386 value.unwrap_meta(),
1387 Value::NativeFunction(_) | Value::Fn(_) | Value::Macro(_) | Value::BoundFn(_)
1388 ) {
1389 return Ok(value.clone());
1390 }
1391 let span = cljrs_types::span::Span::new(Arc::new("<eval>".to_string()), 0, 0, 1, 1);
1392 let form = crate::interp::macros::value_to_form(value, span)?;
1393 let mut top = Env::new(env.globals.clone(), &env.current_ns);
1394 eval(&form, &mut top)
1395}
1396
1397pub fn eval_reset_bang(args: Vec<Value>, env: &mut Env) -> EvalResult {
1405 if args.len() < 2 {
1406 return Err(EvalError::Arity {
1407 name: "reset!".into(),
1408 expected: "2".into(),
1409 got: args.len(),
1410 });
1411 }
1412 let atom_val = args[0].clone();
1413 let new_val = args[1].clone();
1414 let atom = match &atom_val {
1415 Value::Atom(a) => a.clone(),
1416 Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1417 v => {
1418 return Err(EvalError::Runtime(format!(
1419 "reset! requires an atom, got {}",
1420 v.type_name()
1421 )));
1422 }
1423 };
1424 #[cfg(feature = "no-gc")]
1425 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1426 validate_atom_value(&atom, &new_val, env)?;
1427 let old_val = atom.get().deref();
1428 atom.get().reset(new_val.clone());
1429 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1430 check_watch_error()?;
1431 Ok(new_val)
1432}
1433
1434pub fn eval_swap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1436 if args.len() < 2 {
1437 return Err(EvalError::Arity {
1438 name: "swap!".into(),
1439 expected: "2+".into(),
1440 got: args.len(),
1441 });
1442 }
1443 let atom_val = args.remove(0);
1444 let f = args.remove(0);
1445 let atom = match &atom_val {
1446 Value::Atom(a) => a.clone(),
1447 Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, args, env),
1448 v => {
1449 return Err(EvalError::Runtime(format!(
1450 "swap! requires an atom, got {}",
1451 v.type_name()
1452 )));
1453 }
1454 };
1455 let old_val = atom.get().deref();
1456 let mut call_args = vec![old_val.clone()];
1457 call_args.extend(args);
1458 #[cfg(feature = "no-gc")]
1459 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1460 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1461 validate_atom_value(&atom, &new_val, env)?;
1462 atom.get().reset(new_val.clone());
1463 fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1464 check_watch_error()?;
1465 Ok(new_val)
1466}
1467
1468pub fn eval_volatile(args: Vec<Value>) -> EvalResult {
1470 if args.is_empty() {
1471 return Err(EvalError::Arity {
1472 name: "volatile!".into(),
1473 expected: "1".into(),
1474 got: 0,
1475 });
1476 }
1477 #[cfg(feature = "no-gc")]
1478 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1479 Ok(Value::Volatile(GcPtr::new(Volatile::new(
1480 args.into_iter().next().unwrap(),
1481 ))))
1482}
1483
1484pub fn eval_vreset_bang(args: Vec<Value>) -> EvalResult {
1486 if args.len() < 2 {
1487 return Err(EvalError::Arity {
1488 name: "vreset!".into(),
1489 expected: "2".into(),
1490 got: args.len(),
1491 });
1492 }
1493 #[cfg(feature = "no-gc")]
1494 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1495 let new_val = args[1].clone();
1496 match &args[0] {
1497 Value::Volatile(v) => {
1498 v.get().reset(new_val.clone());
1499 Ok(new_val)
1500 }
1501 other => Err(EvalError::Runtime(format!(
1502 "vreset!: expected volatile, got {}",
1503 other.type_name()
1504 ))),
1505 }
1506}
1507
1508pub fn eval_vswap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1510 if args.len() < 2 {
1511 return Err(EvalError::Arity {
1512 name: "vswap!".into(),
1513 expected: "2+".into(),
1514 got: args.len(),
1515 });
1516 }
1517 let vol_val = args.remove(0);
1518 let f = args.remove(0);
1519 match vol_val {
1520 Value::Volatile(v) => {
1521 let cur = v.get().deref();
1522 let mut call_args = vec![cur];
1523 call_args.extend(args);
1524 #[cfg(feature = "no-gc")]
1525 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1526 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1527 v.get().reset(new_val.clone());
1528 Ok(new_val)
1529 }
1530 other => Err(EvalError::Runtime(format!(
1531 "vswap!: expected volatile, got {}",
1532 other.type_name()
1533 ))),
1534 }
1535}
1536
1537pub fn make_delay_from_fn(
1542 f_val: &Value,
1543 globals: std::sync::Arc<crate::env::env::GlobalEnv>,
1544 ns: std::sync::Arc<str>,
1545) -> EvalResult {
1546 let f = match f_val {
1547 Value::Fn(f) => f.get().clone(),
1548 other => {
1549 return Err(EvalError::Runtime(format!(
1550 "make-delay requires a fn, got {}",
1551 other.type_name()
1552 )));
1553 }
1554 };
1555 let thunk = ClosureThunk { f, globals, ns };
1556 Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
1557}
1558
1559pub fn eval_alter_var_root(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1561 if args.len() < 2 {
1562 return Err(EvalError::Arity {
1563 name: "alter-var-root".into(),
1564 expected: "2+".into(),
1565 got: args.len(),
1566 });
1567 }
1568 let var_val = args.remove(0);
1569 let f = args.remove(0);
1570 let vp = match &var_val {
1571 Value::Var(vp) => vp.clone(),
1572 v => {
1573 return Err(EvalError::Runtime(format!(
1574 "alter-var-root: expected var, got {}",
1575 v.type_name()
1576 )));
1577 }
1578 };
1579 let old_val = vp.get().deref().unwrap_or(Value::Nil);
1580 let mut call_args = vec![old_val.clone()];
1581 call_args.extend(args);
1582 #[cfg(feature = "no-gc")]
1583 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1584 let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1585 vp.get().bind(new_val.clone());
1586 fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1587 check_watch_error()?;
1588 Ok(new_val)
1589}
1590
1591pub fn eval_vary_meta(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1593 if args.len() < 2 {
1594 return Err(EvalError::Arity {
1595 name: "vary-meta".into(),
1596 expected: "2+".into(),
1597 got: args.len(),
1598 });
1599 }
1600 let obj = args.remove(0);
1601 let f = args.remove(0);
1602 let current_meta = match &obj {
1603 Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1604 _ => Value::Nil,
1605 };
1606 let mut call_args = vec![current_meta];
1607 call_args.extend(args);
1608 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1609 if let Value::Var(vp) = &obj {
1610 vp.get().set_meta(new_meta);
1611 }
1612 Ok(obj)
1613}
1614
1615pub fn eval_with_bindings_star(args: Vec<Value>, env: &mut Env) -> EvalResult {
1617 if args.len() < 2 {
1618 return Err(EvalError::Arity {
1619 name: "with-bindings*".into(),
1620 expected: "2".into(),
1621 got: args.len(),
1622 });
1623 }
1624 let mut frame: HashMap<usize, Value> = HashMap::new();
1625 if let Value::Map(m) = &args[0] {
1626 m.for_each(|k, v| {
1627 if let Value::Var(vp) = k {
1628 frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1629 }
1630 });
1631 } else {
1632 return Err(EvalError::Runtime(
1633 "with-bindings*: first arg must be a map".into(),
1634 ));
1635 }
1636 let _guard = crate::env::dynamics::push_frame(frame);
1637 crate::env::apply::apply_value(&args[1], vec![], env)
1638}
1639
1640pub fn eval_send_to_agent(_args: Vec<Value>, _env: &mut Env) -> EvalResult {
1642 Err(EvalError::Runtime(
1643 "send/send-off: agents are not yet implemented".into(),
1644 ))
1645}
1646
1647fn ns_name_from_val(v: &Value) -> Result<String, EvalError> {
1650 match v {
1651 Value::Symbol(s) => Ok(s.get().name.as_ref().to_string()),
1652 Value::Str(s) => Ok(s.get().clone()),
1653 Value::Namespace(ns) => Ok(ns.get().name.as_ref().to_string()),
1654 Value::Keyword(k) => Ok(k.get().name.as_ref().to_string()),
1655 other => Err(EvalError::Runtime(format!(
1656 "expected symbol, string, or namespace, got {}",
1657 other.type_name()
1658 ))),
1659 }
1660}
1661
1662fn the_ns(v: &Value, env: &Env) -> Result<GcPtr<cljrs_value::Namespace>, EvalError> {
1667 if let Value::Namespace(ns) = v {
1668 return Ok(ns.clone());
1669 }
1670 let name = ns_name_from_val(v)?;
1671 let map = env.globals.namespaces.read().unwrap();
1672 match map.get(name.as_str()) {
1673 Some(ns) => Ok(ns.clone()),
1674 None => Err(EvalError::Runtime(format!("No namespace: {name} found"))),
1675 }
1676}
1677
1678fn handle_ns_interns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1681 if arg_forms.is_empty() {
1682 return Err(EvalError::Arity {
1683 name: "ns-interns".into(),
1684 expected: "1".into(),
1685 got: 0,
1686 });
1687 }
1688 let arg = eval(&arg_forms[0], env)?;
1689 let ns = the_ns(&arg, env)?;
1690 crate::builtins::builtins::builtin_ns_interns(&[Value::Namespace(ns)])
1691 .map_err(crate::env::error::value_error_to_eval_error)
1692}
1693
1694fn handle_ns_refers(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1696 if arg_forms.is_empty() {
1697 return Err(EvalError::Arity {
1698 name: "ns-refers".into(),
1699 expected: "1".into(),
1700 got: 0,
1701 });
1702 }
1703 let arg = eval(&arg_forms[0], env)?;
1704 let ns = the_ns(&arg, env)?;
1705 crate::builtins::builtins::builtin_ns_refers(&[Value::Namespace(ns)])
1706 .map_err(crate::env::error::value_error_to_eval_error)
1707}
1708
1709fn handle_ns_map(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1711 if arg_forms.is_empty() {
1712 return Err(EvalError::Arity {
1713 name: "ns-map".into(),
1714 expected: "1".into(),
1715 got: 0,
1716 });
1717 }
1718 let arg = eval(&arg_forms[0], env)?;
1719 let ns = the_ns(&arg, env)?;
1720 crate::builtins::builtins::builtin_ns_map(&[Value::Namespace(ns)])
1721 .map_err(crate::env::error::value_error_to_eval_error)
1722}
1723
1724fn handle_find_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1726 if arg_forms.is_empty() {
1727 return Err(EvalError::Arity {
1728 name: "find-ns".into(),
1729 expected: "1".into(),
1730 got: 0,
1731 });
1732 }
1733 let arg = eval(&arg_forms[0], env)?;
1734 let name = ns_name_from_val(&arg)?;
1735 let map = env.globals.namespaces.read().unwrap();
1736 match map.get(name.as_str()) {
1737 Some(ns) => Ok(Value::Namespace(ns.clone())),
1738 None => Ok(Value::Nil),
1739 }
1740}
1741
1742fn handle_all_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1744 if !arg_forms.is_empty() {
1745 let _ = eval(&arg_forms[0], env)?; }
1747 let map = env.globals.namespaces.read().unwrap();
1748 let items: Vec<Value> = map
1749 .values()
1750 .map(|ns| Value::Namespace(ns.clone()))
1751 .collect();
1752 drop(map);
1753 Ok(Value::List(cljrs_gc::GcPtr::new(
1754 cljrs_value::PersistentList::from_iter(items),
1755 )))
1756}
1757
1758fn handle_create_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1760 if arg_forms.is_empty() {
1761 return Err(EvalError::Arity {
1762 name: "create-ns".into(),
1763 expected: "1".into(),
1764 got: 0,
1765 });
1766 }
1767 let arg = eval(&arg_forms[0], env)?;
1768 let name = ns_name_from_val(&arg)?;
1769 let ns = env.globals.get_or_create_ns(&name);
1770 Ok(Value::Namespace(ns))
1771}
1772
1773fn handle_ns_aliases(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1775 if arg_forms.is_empty() {
1776 return Err(EvalError::Arity {
1777 name: "ns-aliases".into(),
1778 expected: "1".into(),
1779 got: 0,
1780 });
1781 }
1782 let ns_val = eval(&arg_forms[0], env)?;
1783 let ns_name = ns_name_from_val(&ns_val)?;
1784 let map = env.globals.namespaces.read().unwrap();
1785 let ns = match map.get(ns_name.as_str()) {
1786 Some(ns) => ns.clone(),
1787 None => return Ok(Value::Map(cljrs_value::MapValue::empty())),
1788 };
1789 let aliases = ns.get().aliases.lock().unwrap().clone();
1790 drop(map);
1791 let mut m = cljrs_value::MapValue::empty();
1792 for (alias, full_ns_name) in &aliases {
1793 let sym = Value::symbol(cljrs_value::Symbol::simple(alias.clone()));
1794 let nsmap = env.globals.namespaces.read().unwrap();
1795 if let Some(target_ns) = nsmap.get(full_ns_name.as_ref()) {
1796 m = m.assoc(sym, Value::Namespace(target_ns.clone()));
1797 }
1798 }
1799 Ok(Value::Map(m))
1800}
1801
1802fn handle_remove_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1804 if arg_forms.is_empty() {
1805 return Err(EvalError::Arity {
1806 name: "remove-ns".into(),
1807 expected: "1".into(),
1808 got: 0,
1809 });
1810 }
1811 let arg = eval(&arg_forms[0], env)?;
1812 let name = ns_name_from_val(&arg)?;
1813 env.globals
1814 .namespaces
1815 .write()
1816 .unwrap()
1817 .remove(name.as_str());
1818 Ok(Value::Nil)
1819}
1820
1821fn handle_alter_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1823 if arg_forms.len() < 2 {
1824 return Err(EvalError::Arity {
1825 name: "alter-meta!".into(),
1826 expected: "2+".into(),
1827 got: arg_forms.len(),
1828 });
1829 }
1830 let obj = eval(&arg_forms[0], env)?;
1831 let f = eval(&arg_forms[1], env)?;
1832 let extra: Vec<Value> = arg_forms[2..]
1833 .iter()
1834 .map(|form| eval(form, env))
1835 .collect::<EvalResult<_>>()?;
1836
1837 let current_meta = match &obj {
1838 Value::Var(vp) => vp
1839 .get()
1840 .get_meta()
1841 .unwrap_or(Value::Map(cljrs_value::MapValue::empty())),
1842 _ => Value::Map(cljrs_value::MapValue::empty()),
1843 };
1844 let mut call_args = vec![current_meta];
1845 call_args.extend(extra);
1846 let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1847 if let Value::Var(vp) = &obj {
1848 vp.get().set_meta(new_meta.clone());
1849 }
1850 Ok(new_meta)
1851}
1852
1853fn handle_ns_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1855 if arg_forms.len() < 2 {
1856 return Err(EvalError::Arity {
1857 name: "ns-resolve".into(),
1858 expected: "2".into(),
1859 got: arg_forms.len(),
1860 });
1861 }
1862 let ns_arg = eval(&arg_forms[0], env)?;
1863 let sym_arg = eval(&arg_forms[1], env)?;
1864 let ns_name = ns_name_from_val(&ns_arg)?;
1865 let sym_name = match &sym_arg {
1866 Value::Symbol(s) => s.get().name.as_ref().to_string(),
1867 Value::Str(s) => s.get().clone(),
1868 other => {
1869 return Err(EvalError::Runtime(format!(
1870 "ns-resolve: second arg must be symbol or string, got {}",
1871 other.type_name()
1872 )));
1873 }
1874 };
1875 match env.globals.lookup_var(&ns_name, &sym_name) {
1876 Some(var_ptr) => Ok(Value::Var(var_ptr)),
1877 None => Ok(Value::Nil),
1878 }
1879}
1880
1881fn resolve_current_ns(env: &Env) -> Arc<str> {
1885 if let Some(var) = env.globals.lookup_var("clojure.core", "*ns*") {
1886 let val = crate::env::dynamics::deref_var(&var);
1887 if let Some(Value::Namespace(ns_ptr)) = val {
1888 return ns_ptr.get().name.clone();
1889 }
1890 }
1891 env.current_ns.clone()
1892}
1893
1894fn handle_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1896 if arg_forms.len() != 1 {
1897 return Err(EvalError::Arity {
1898 name: "resolve".into(),
1899 expected: "1".into(),
1900 got: arg_forms.len(),
1901 });
1902 }
1903 let resolve_ns = resolve_current_ns(env);
1904 let sym_arg = eval(&arg_forms[0], env)?;
1905 let sym_name = match &sym_arg {
1906 Value::Symbol(s) => {
1907 let sym = s.get();
1908 if let Some(ns) = &sym.namespace {
1910 let full_ns = env.globals.resolve_ns_part_in(&resolve_ns, ns.as_ref());
1913 return Ok(
1914 match env.globals.lookup_var_in_ns(&full_ns, sym.name.as_ref()) {
1915 Some(var_ptr) => Value::Var(var_ptr),
1916 None => Value::Nil,
1917 },
1918 );
1919 }
1920 sym.name.as_ref().to_string()
1921 }
1922 Value::Str(s) => s.get().clone(),
1923 other => {
1924 return Err(EvalError::Runtime(format!(
1925 "resolve: arg must be symbol or string, got {}",
1926 other.type_name()
1927 )));
1928 }
1929 };
1930 Ok(match env.globals.lookup_var_in_ns(&resolve_ns, &sym_name) {
1931 Some(var_ptr) => Value::Var(var_ptr),
1932 None => Value::Nil,
1933 })
1934}
1935
1936fn handle_intern(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1937 if arg_forms.len() < 2 || arg_forms.len() > 3 {
1938 return Err(EvalError::Runtime("intern expects 2 or 3 arguments".into()));
1939 }
1940 let ns_val = eval(&arg_forms[0], env)?;
1941 let ns_name: Arc<str> = match &ns_val {
1942 Value::Symbol(s) => s.get().name.clone(),
1943 Value::Namespace(ns) => ns.get().name.clone(),
1944 other => {
1945 return Err(EvalError::Runtime(format!(
1946 "intern: first arg must be namespace or symbol, got {}",
1947 other.type_name()
1948 )));
1949 }
1950 };
1951 let var_name: Arc<str> = match eval(&arg_forms[1], env)? {
1952 Value::Symbol(s) => s.get().name.clone(),
1953 other => {
1954 return Err(EvalError::Runtime(format!(
1955 "intern: second arg must be symbol, got {}",
1956 other.type_name()
1957 )));
1958 }
1959 };
1960 let ns = {
1962 let map = env.globals.namespaces.read().unwrap();
1963 map.get(ns_name.as_ref()).cloned()
1964 };
1965 let ns = ns.ok_or_else(|| EvalError::Runtime(format!("No namespace: {ns_name} found")))?;
1966 let var = if arg_forms.len() == 3 {
1967 #[cfg(feature = "no-gc")]
1970 let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1971 let val = eval(&arg_forms[2], env)?;
1972 let mut interns = ns.get().interns.lock().unwrap();
1973 if let Some(var) = interns.get(&var_name) {
1974 var.get().bind(val);
1975 var.clone()
1976 } else {
1977 let var =
1978 cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1979 var.get().bind(val);
1980 interns.insert(var_name, var.clone());
1981 var
1982 }
1983 } else {
1984 let mut interns = ns.get().interns.lock().unwrap();
1985 if let Some(var) = interns.get(&var_name) {
1986 var.clone()
1987 } else {
1988 let var =
1989 cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1990 interns.insert(var_name, var.clone());
1991 var
1992 }
1993 };
1994 Ok(Value::Var(var))
1995}
1996
1997fn handle_bound_fn_star(arg_forms: &[Form], env: &mut Env) -> EvalResult {
2002 if arg_forms.len() != 1 {
2003 return Err(EvalError::Arity {
2004 name: "bound-fn*".into(),
2005 expected: "1".into(),
2006 got: arg_forms.len(),
2007 });
2008 }
2009 let f = eval(&arg_forms[0], env)?;
2010 let frames = crate::env::dynamics::capture_current();
2012 let mut merged = std::collections::HashMap::new();
2013 for frame in &frames {
2014 merged.extend(frame.iter().map(|(k, v)| (*k, v.clone())));
2015 }
2016 Ok(Value::BoundFn(cljrs_gc::GcPtr::new(cljrs_value::BoundFn {
2017 wrapped: f,
2018 captured_bindings: merged,
2019 })))
2020}