1use std::any::Any;
2use std::cell::{Cell, RefCell};
3use std::collections::BTreeMap;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6use std::rc::Rc;
7
8use hashbrown::HashMap as SpurMap;
9use lasso::{Rodeo, Spur};
10
11use crate::error::SemaError;
12use crate::EvalContext;
13
14#[cfg(not(any(target_pointer_width = "64", target_arch = "wasm32")))]
18compile_error!("sema-core NaN-boxed Value requires a 64-bit platform (or wasm32)");
19
20thread_local! {
23 static INTERNER: RefCell<Rodeo> = RefCell::new(Rodeo::default());
24}
25
26pub fn intern(s: &str) -> Spur {
28 INTERNER.with(|r| r.borrow_mut().get_or_intern(s))
29}
30
31pub fn resolve(spur: Spur) -> String {
33 INTERNER.with(|r| r.borrow().resolve(&spur).to_string())
34}
35
36pub fn with_resolved<F, R>(spur: Spur, f: F) -> R
38where
39 F: FnOnce(&str) -> R,
40{
41 INTERNER.with(|r| {
42 let interner = r.borrow();
43 f(interner.resolve(&spur))
44 })
45}
46
47pub fn interner_stats() -> (usize, usize) {
49 INTERNER.with(|r| {
50 let interner = r.borrow();
51 let count = interner.len();
52 let bytes = count * 16; (count, bytes)
54 })
55}
56
57thread_local! {
60 static GENSYM_COUNTER: Cell<u64> = const { Cell::new(0) };
61}
62
63pub fn next_gensym(prefix: &str) -> String {
67 GENSYM_COUNTER.with(|c| {
68 let val = c.get();
69 c.set(val.wrapping_add(1));
70 format!("{prefix}__{val}")
71 })
72}
73
74pub fn compare_spurs(a: Spur, b: Spur) -> std::cmp::Ordering {
76 if a == b {
77 return std::cmp::Ordering::Equal;
78 }
79 INTERNER.with(|r| {
80 let interner = r.borrow();
81 interner.resolve(&a).cmp(interner.resolve(&b))
82 })
83}
84
85pub type NativeFnInner = dyn Fn(&EvalContext, &[Value]) -> Result<Value, SemaError>;
89
90pub struct NativeFn {
91 pub name: String,
92 pub func: Box<NativeFnInner>,
93 pub payload: Option<Rc<dyn Any>>,
94 pub is_closure: bool,
100}
101
102impl NativeFn {
103 pub fn simple(
104 name: impl Into<String>,
105 f: impl Fn(&[Value]) -> Result<Value, SemaError> + 'static,
106 ) -> Self {
107 Self {
108 name: name.into(),
109 func: Box::new(move |_ctx, args| f(args)),
110 payload: None,
111 is_closure: false,
112 }
113 }
114
115 pub fn with_ctx(
116 name: impl Into<String>,
117 f: impl Fn(&EvalContext, &[Value]) -> Result<Value, SemaError> + 'static,
118 ) -> Self {
119 Self {
120 name: name.into(),
121 func: Box::new(f),
122 payload: None,
123 is_closure: false,
124 }
125 }
126
127 pub fn with_payload(
128 name: impl Into<String>,
129 payload: Rc<dyn Any>,
130 f: impl Fn(&EvalContext, &[Value]) -> Result<Value, SemaError> + 'static,
131 ) -> Self {
132 Self {
133 name: name.into(),
134 func: Box::new(f),
135 payload: Some(payload),
136 is_closure: false,
137 }
138 }
139}
140
141impl fmt::Debug for NativeFn {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 write!(f, "<native-fn {}>", self.name)
144 }
145}
146
147#[derive(Debug, Clone)]
149pub struct Lambda {
150 pub params: Vec<Spur>,
151 pub rest_param: Option<Spur>,
152 pub body: Vec<Value>,
153 pub env: Env,
154 pub name: Option<Spur>,
155}
156
157#[derive(Debug, Clone)]
159pub struct Macro {
160 pub params: Vec<Spur>,
161 pub rest_param: Option<Spur>,
162 pub body: Vec<Value>,
163 pub name: Spur,
164}
165
166pub struct Thunk {
168 pub body: Value,
169 pub forced: RefCell<Option<Value>>,
170}
171
172impl fmt::Debug for Thunk {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 if self.forced.borrow().is_some() {
175 write!(f, "<promise (forced)>")
176 } else {
177 write!(f, "<promise>")
178 }
179 }
180}
181
182impl Clone for Thunk {
183 fn clone(&self) -> Self {
184 Thunk {
185 body: self.body.clone(),
186 forced: RefCell::new(self.forced.borrow().clone()),
187 }
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
199pub enum PromiseState {
200 Pending,
201 Resolved(Value),
202 Rejected(String),
203 Cancelled,
204}
205
206pub struct AsyncPromise {
208 pub state: RefCell<PromiseState>,
209 pub task_id: Cell<u64>,
210}
211
212impl fmt::Debug for AsyncPromise {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 match &*self.state.borrow() {
215 PromiseState::Pending => write!(f, "<async-promise pending>"),
216 PromiseState::Resolved(_) => write!(f, "<async-promise resolved>"),
217 PromiseState::Rejected(e) => write!(f, "<async-promise rejected: {e}>"),
218 PromiseState::Cancelled => write!(f, "<async-promise cancelled>"),
219 }
220 }
221}
222
223impl Clone for AsyncPromise {
224 fn clone(&self) -> Self {
225 AsyncPromise {
226 state: RefCell::new(self.state.borrow().clone()),
227 task_id: Cell::new(self.task_id.get()),
228 }
229 }
230}
231
232pub struct Channel {
234 pub buffer: RefCell<std::collections::VecDeque<Value>>,
235 pub capacity: usize,
236 pub closed: Cell<bool>,
237}
238
239impl fmt::Debug for Channel {
240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241 let len = self.buffer.borrow().len();
242 write!(f, "<channel {len}/{}>", self.capacity)
243 }
244}
245
246impl Clone for Channel {
247 fn clone(&self) -> Self {
248 Channel {
249 buffer: RefCell::new(self.buffer.borrow().clone()),
250 capacity: self.capacity,
251 closed: Cell::new(self.closed.get()),
252 }
253 }
254}
255
256#[derive(Debug, Clone)]
258pub struct Record {
259 pub type_tag: Spur,
260 pub field_names: Vec<Spur>,
261 pub fields: Vec<Value>,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq)]
266pub enum Role {
267 System,
268 User,
269 Assistant,
270 Tool,
271}
272
273impl fmt::Display for Role {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 match self {
276 Role::System => write!(f, "system"),
277 Role::User => write!(f, "user"),
278 Role::Assistant => write!(f, "assistant"),
279 Role::Tool => write!(f, "tool"),
280 }
281 }
282}
283
284#[derive(Debug, Clone)]
286pub struct ImageAttachment {
287 pub data: String,
288 pub media_type: String,
289}
290
291#[derive(Debug, Clone)]
293pub struct Message {
294 pub role: Role,
295 pub content: String,
296 pub images: Vec<ImageAttachment>,
298}
299
300#[derive(Debug, Clone)]
302pub struct Prompt {
303 pub messages: Vec<Message>,
304}
305
306#[derive(Debug, Clone)]
308pub struct Conversation {
309 pub messages: Vec<Message>,
310 pub model: String,
311 pub metadata: BTreeMap<String, String>,
312}
313
314#[derive(Debug, Clone)]
316pub struct ToolDefinition {
317 pub name: String,
318 pub description: String,
319 pub parameters: Value,
320 pub handler: Value,
321}
322
323#[derive(Debug, Clone)]
325pub struct Agent {
326 pub name: String,
327 pub system: String,
328 pub tools: Vec<Value>,
329 pub max_turns: usize,
330 pub model: String,
331}
332
333pub struct MultiMethod {
336 pub name: Spur,
337 pub dispatch_fn: Value,
338 pub methods: RefCell<BTreeMap<Value, Value>>,
339 pub default: RefCell<Option<Value>>,
340}
341
342impl fmt::Debug for MultiMethod {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 write!(f, "<multimethod {}>", resolve(self.name))
345 }
346}
347
348pub trait SemaStream: fmt::Debug {
351 fn read(&self, buf: &mut [u8]) -> Result<usize, SemaError>;
352 fn write(&self, data: &[u8]) -> Result<usize, SemaError>;
353 fn available(&self) -> Result<bool, SemaError> {
354 Ok(false)
355 }
356 fn flush(&self) -> Result<(), SemaError> {
357 Ok(())
358 }
359 fn close(&self) -> Result<(), SemaError> {
360 Ok(())
361 }
362 fn is_readable(&self) -> bool {
363 true
364 }
365 fn is_writable(&self) -> bool {
366 true
367 }
368 fn stream_type(&self) -> &'static str;
369 fn as_any(&self) -> &dyn std::any::Any;
370}
371
372pub struct StreamBox {
375 inner: RefCell<Box<dyn SemaStream>>,
376 closed: Cell<bool>,
377}
378
379impl StreamBox {
380 pub fn new(s: impl SemaStream + 'static) -> Self {
381 StreamBox {
382 inner: RefCell::new(Box::new(s)),
383 closed: Cell::new(false),
384 }
385 }
386
387 pub fn read(&self, buf: &mut [u8]) -> Result<usize, SemaError> {
388 if self.closed.get() {
389 return Err(SemaError::eval("stream/read: stream is closed"));
390 }
391 self.inner.borrow().read(buf)
392 }
393
394 pub fn write(&self, data: &[u8]) -> Result<usize, SemaError> {
395 if self.closed.get() {
396 return Err(SemaError::eval("stream/write: stream is closed"));
397 }
398 self.inner.borrow().write(data)
399 }
400
401 pub fn flush(&self) -> Result<(), SemaError> {
402 if self.closed.get() {
403 return Err(SemaError::eval("stream/flush: stream is closed"));
404 }
405 self.inner.borrow().flush()
406 }
407
408 pub fn close(&self) -> Result<(), SemaError> {
409 if self.closed.get() {
410 return Ok(()); }
412 self.inner.borrow().close()?;
413 self.closed.set(true);
414 Ok(())
415 }
416
417 pub fn is_closed(&self) -> bool {
418 self.closed.get()
419 }
420
421 pub fn is_readable(&self) -> bool {
422 !self.closed.get() && self.inner.borrow().is_readable()
423 }
424
425 pub fn is_writable(&self) -> bool {
426 !self.closed.get() && self.inner.borrow().is_writable()
427 }
428
429 pub fn available(&self) -> Result<bool, SemaError> {
430 if self.closed.get() {
431 return Ok(false);
432 }
433 self.inner.borrow().available()
434 }
435
436 pub fn stream_type(&self) -> &'static str {
437 self.inner.borrow().stream_type()
438 }
439
440 pub fn borrow_inner(&self) -> std::cell::Ref<'_, Box<dyn SemaStream>> {
441 self.inner.borrow()
442 }
443}
444
445impl fmt::Debug for StreamBox {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 write!(f, "<stream:{}>", self.stream_type())
448 }
449}
450
451impl Clone for MultiMethod {
452 fn clone(&self) -> Self {
453 MultiMethod {
454 name: self.name,
455 dispatch_fn: self.dispatch_fn.clone(),
456 methods: RefCell::new(self.methods.borrow().clone()),
457 default: RefCell::new(self.default.borrow().clone()),
458 }
459 }
460}
461
462const BOX_MASK: u64 = 0xFFF8_0000_0000_0000;
474
475const PAYLOAD_MASK: u64 = (1u64 << 45) - 1; const INT_SIGN_BIT: u64 = 1u64 << 44;
480
481const TAG_MASK_6BIT: u64 = 0x3F;
483
484const CANONICAL_NAN: u64 = 0x7FF8_0000_0000_0000;
486
487const TAG_NIL: u64 = 0;
489const TAG_FALSE: u64 = 1;
490const TAG_TRUE: u64 = 2;
491const TAG_INT_SMALL: u64 = 3;
492const TAG_CHAR: u64 = 4;
493const TAG_SYMBOL: u64 = 5;
494const TAG_KEYWORD: u64 = 6;
495const TAG_INT_BIG: u64 = 7;
496const TAG_STRING: u64 = 8;
497const TAG_LIST: u64 = 9;
498const TAG_VECTOR: u64 = 10;
499const TAG_MAP: u64 = 11;
500const TAG_HASHMAP: u64 = 12;
501const TAG_LAMBDA: u64 = 13;
502const TAG_MACRO: u64 = 14;
503pub const TAG_NATIVE_FN: u64 = 15;
504const TAG_PROMPT: u64 = 16;
505const TAG_MESSAGE: u64 = 17;
506const TAG_CONVERSATION: u64 = 18;
507const TAG_TOOL_DEF: u64 = 19;
508const TAG_AGENT: u64 = 20;
509const TAG_THUNK: u64 = 21;
510const TAG_RECORD: u64 = 22;
511const TAG_BYTEVECTOR: u64 = 23;
512const TAG_MULTIMETHOD: u64 = 24;
513const TAG_STREAM: u64 = 25;
514const TAG_F64_ARRAY: u64 = 26;
515const TAG_I64_ARRAY: u64 = 27;
516const TAG_ASYNC_PROMISE: u64 = 28;
517const TAG_CHANNEL: u64 = 29;
518
519const SMALL_INT_MIN: i64 = -(1i64 << 44);
521const SMALL_INT_MAX: i64 = (1i64 << 44) - 1;
522
523pub const NAN_TAG_MASK: u64 = BOX_MASK | (TAG_MASK_6BIT << 45); pub const NAN_INT_SMALL_PATTERN: u64 = BOX_MASK | (TAG_INT_SMALL << 45);
530
531pub const NAN_PAYLOAD_MASK: u64 = PAYLOAD_MASK;
533
534pub const NAN_INT_SIGN_BIT: u64 = INT_SIGN_BIT;
536
537pub const NAN_PAYLOAD_BITS: u32 = 45;
539
540#[inline(always)]
543fn make_boxed(tag: u64, payload: u64) -> u64 {
544 BOX_MASK | (tag << 45) | (payload & PAYLOAD_MASK)
545}
546
547#[inline(always)]
548fn is_boxed(bits: u64) -> bool {
549 (bits & BOX_MASK) == BOX_MASK
550}
551
552#[inline(always)]
553fn get_tag(bits: u64) -> u64 {
554 (bits >> 45) & TAG_MASK_6BIT
555}
556
557#[inline(always)]
558fn get_payload(bits: u64) -> u64 {
559 bits & PAYLOAD_MASK
560}
561
562#[inline(always)]
563fn ptr_to_payload(ptr: *const u8) -> u64 {
564 let raw = ptr as u64;
565 debug_assert!(raw & 0x7 == 0, "pointer not 8-byte aligned: 0x{:x}", raw);
566 debug_assert!(
567 raw >> 48 == 0,
568 "pointer exceeds 48-bit VA space: 0x{:x}",
569 raw
570 );
571 raw >> 3
572}
573
574#[inline(always)]
575fn payload_to_ptr(payload: u64) -> *const u8 {
576 (payload << 3) as *const u8
577}
578
579pub enum ValueView {
584 Nil,
585 Bool(bool),
586 Int(i64),
587 Float(f64),
588 String(Rc<String>),
589 Symbol(Spur),
590 Keyword(Spur),
591 Char(char),
592 List(Rc<Vec<Value>>),
593 Vector(Rc<Vec<Value>>),
594 Map(Rc<BTreeMap<Value, Value>>),
595 HashMap(Rc<hashbrown::HashMap<Value, Value>>),
596 Lambda(Rc<Lambda>),
597 Macro(Rc<Macro>),
598 NativeFn(Rc<NativeFn>),
599 Prompt(Rc<Prompt>),
600 Message(Rc<Message>),
601 Conversation(Rc<Conversation>),
602 ToolDef(Rc<ToolDefinition>),
603 Agent(Rc<Agent>),
604 Thunk(Rc<Thunk>),
605 Record(Rc<Record>),
606 Bytevector(Rc<Vec<u8>>),
607 MultiMethod(Rc<MultiMethod>),
608 Stream(Rc<StreamBox>),
609 F64Array(Rc<Vec<f64>>),
610 I64Array(Rc<Vec<i64>>),
611 AsyncPromise(Rc<AsyncPromise>),
612 Channel(Rc<Channel>),
613}
614
615#[repr(transparent)]
621pub struct Value(u64);
622
623impl Value {
626 pub const NIL: Value = Value(make_boxed_const(TAG_NIL, 0));
629 pub const TRUE: Value = Value(make_boxed_const(TAG_TRUE, 0));
630 pub const FALSE: Value = Value(make_boxed_const(TAG_FALSE, 0));
631
632 #[inline(always)]
633 pub fn nil() -> Value {
634 Value::NIL
635 }
636
637 #[inline(always)]
638 pub fn bool(b: bool) -> Value {
639 if b {
640 Value::TRUE
641 } else {
642 Value::FALSE
643 }
644 }
645
646 #[inline(always)]
647 pub fn int(n: i64) -> Value {
648 if (SMALL_INT_MIN..=SMALL_INT_MAX).contains(&n) {
649 let payload = (n as u64) & PAYLOAD_MASK;
651 Value(make_boxed(TAG_INT_SMALL, payload))
652 } else {
653 let rc = Rc::new(n);
655 let ptr = Rc::into_raw(rc) as *const u8;
656 Value(make_boxed(TAG_INT_BIG, ptr_to_payload(ptr)))
657 }
658 }
659
660 #[inline(always)]
661 pub fn float(f: f64) -> Value {
662 let bits = f.to_bits();
663 if f.is_nan() {
664 Value(CANONICAL_NAN)
666 } else {
667 debug_assert!(
674 !is_boxed(bits),
675 "non-NaN float collides with boxed pattern: {:?} = 0x{:016x}",
676 f,
677 bits
678 );
679 Value(bits)
680 }
681 }
682
683 #[inline(always)]
684 pub fn char(c: char) -> Value {
685 Value(make_boxed(TAG_CHAR, c as u64))
686 }
687
688 #[inline(always)]
689 pub fn symbol_from_spur(spur: Spur) -> Value {
690 let bits: u32 = unsafe { std::mem::transmute(spur) };
692 Value(make_boxed(TAG_SYMBOL, bits as u64))
693 }
694
695 pub fn symbol(s: &str) -> Value {
696 Value::symbol_from_spur(intern(s))
697 }
698
699 #[inline(always)]
700 pub fn keyword_from_spur(spur: Spur) -> Value {
701 let bits: u32 = unsafe { std::mem::transmute(spur) };
703 Value(make_boxed(TAG_KEYWORD, bits as u64))
704 }
705
706 pub fn keyword(s: &str) -> Value {
707 Value::keyword_from_spur(intern(s))
708 }
709
710 fn from_rc_ptr<T>(tag: u64, rc: Rc<T>) -> Value {
713 let ptr = Rc::into_raw(rc) as *const u8;
714 Value(make_boxed(tag, ptr_to_payload(ptr)))
715 }
716
717 pub fn string(s: &str) -> Value {
718 Value::from_rc_ptr(TAG_STRING, Rc::new(s.to_string()))
719 }
720
721 pub fn string_from_rc(rc: Rc<String>) -> Value {
722 Value::from_rc_ptr(TAG_STRING, rc)
723 }
724
725 pub fn list(v: Vec<Value>) -> Value {
726 Value::from_rc_ptr(TAG_LIST, Rc::new(v))
727 }
728
729 pub fn list_from_rc(rc: Rc<Vec<Value>>) -> Value {
730 Value::from_rc_ptr(TAG_LIST, rc)
731 }
732
733 pub fn vector(v: Vec<Value>) -> Value {
734 Value::from_rc_ptr(TAG_VECTOR, Rc::new(v))
735 }
736
737 pub fn vector_from_rc(rc: Rc<Vec<Value>>) -> Value {
738 Value::from_rc_ptr(TAG_VECTOR, rc)
739 }
740
741 pub fn map(m: BTreeMap<Value, Value>) -> Value {
742 Value::from_rc_ptr(TAG_MAP, Rc::new(m))
743 }
744
745 pub fn map_from_rc(rc: Rc<BTreeMap<Value, Value>>) -> Value {
746 Value::from_rc_ptr(TAG_MAP, rc)
747 }
748
749 pub fn hashmap(entries: Vec<(Value, Value)>) -> Value {
750 let map: hashbrown::HashMap<Value, Value> = entries.into_iter().collect();
751 Value::from_rc_ptr(TAG_HASHMAP, Rc::new(map))
752 }
753
754 pub fn hashmap_from_rc(rc: Rc<hashbrown::HashMap<Value, Value>>) -> Value {
755 Value::from_rc_ptr(TAG_HASHMAP, rc)
756 }
757
758 pub fn lambda(l: Lambda) -> Value {
759 Value::from_rc_ptr(TAG_LAMBDA, Rc::new(l))
760 }
761
762 pub fn lambda_from_rc(rc: Rc<Lambda>) -> Value {
763 Value::from_rc_ptr(TAG_LAMBDA, rc)
764 }
765
766 pub fn macro_val(m: Macro) -> Value {
767 Value::from_rc_ptr(TAG_MACRO, Rc::new(m))
768 }
769
770 pub fn macro_from_rc(rc: Rc<Macro>) -> Value {
771 Value::from_rc_ptr(TAG_MACRO, rc)
772 }
773
774 pub fn native_fn(f: NativeFn) -> Value {
775 Value::from_rc_ptr(TAG_NATIVE_FN, Rc::new(f))
776 }
777
778 pub fn native_fn_from_rc(rc: Rc<NativeFn>) -> Value {
779 Value::from_rc_ptr(TAG_NATIVE_FN, rc)
780 }
781
782 pub fn prompt(p: Prompt) -> Value {
783 Value::from_rc_ptr(TAG_PROMPT, Rc::new(p))
784 }
785
786 pub fn prompt_from_rc(rc: Rc<Prompt>) -> Value {
787 Value::from_rc_ptr(TAG_PROMPT, rc)
788 }
789
790 pub fn message(m: Message) -> Value {
791 Value::from_rc_ptr(TAG_MESSAGE, Rc::new(m))
792 }
793
794 pub fn message_from_rc(rc: Rc<Message>) -> Value {
795 Value::from_rc_ptr(TAG_MESSAGE, rc)
796 }
797
798 pub fn conversation(c: Conversation) -> Value {
799 Value::from_rc_ptr(TAG_CONVERSATION, Rc::new(c))
800 }
801
802 pub fn conversation_from_rc(rc: Rc<Conversation>) -> Value {
803 Value::from_rc_ptr(TAG_CONVERSATION, rc)
804 }
805
806 pub fn tool_def(t: ToolDefinition) -> Value {
807 Value::from_rc_ptr(TAG_TOOL_DEF, Rc::new(t))
808 }
809
810 pub fn tool_def_from_rc(rc: Rc<ToolDefinition>) -> Value {
811 Value::from_rc_ptr(TAG_TOOL_DEF, rc)
812 }
813
814 pub fn agent(a: Agent) -> Value {
815 Value::from_rc_ptr(TAG_AGENT, Rc::new(a))
816 }
817
818 pub fn agent_from_rc(rc: Rc<Agent>) -> Value {
819 Value::from_rc_ptr(TAG_AGENT, rc)
820 }
821
822 pub fn thunk(t: Thunk) -> Value {
823 Value::from_rc_ptr(TAG_THUNK, Rc::new(t))
824 }
825
826 pub fn thunk_from_rc(rc: Rc<Thunk>) -> Value {
827 Value::from_rc_ptr(TAG_THUNK, rc)
828 }
829
830 pub fn record(r: Record) -> Value {
831 Value::from_rc_ptr(TAG_RECORD, Rc::new(r))
832 }
833
834 pub fn record_from_rc(rc: Rc<Record>) -> Value {
835 Value::from_rc_ptr(TAG_RECORD, rc)
836 }
837
838 pub fn bytevector(bytes: Vec<u8>) -> Value {
839 Value::from_rc_ptr(TAG_BYTEVECTOR, Rc::new(bytes))
840 }
841
842 pub fn bytevector_from_rc(rc: Rc<Vec<u8>>) -> Value {
843 Value::from_rc_ptr(TAG_BYTEVECTOR, rc)
844 }
845
846 pub fn f64_array(data: Vec<f64>) -> Value {
847 Value::from_rc_ptr(TAG_F64_ARRAY, Rc::new(data))
848 }
849
850 pub fn f64_array_from_rc(rc: Rc<Vec<f64>>) -> Value {
851 Value::from_rc_ptr(TAG_F64_ARRAY, rc)
852 }
853
854 pub fn i64_array(data: Vec<i64>) -> Value {
855 Value::from_rc_ptr(TAG_I64_ARRAY, Rc::new(data))
856 }
857
858 pub fn i64_array_from_rc(rc: Rc<Vec<i64>>) -> Value {
859 Value::from_rc_ptr(TAG_I64_ARRAY, rc)
860 }
861
862 pub fn multimethod(m: MultiMethod) -> Value {
863 Value::from_rc_ptr(TAG_MULTIMETHOD, Rc::new(m))
864 }
865
866 pub fn multimethod_from_rc(rc: Rc<MultiMethod>) -> Value {
867 Value::from_rc_ptr(TAG_MULTIMETHOD, rc)
868 }
869
870 pub fn stream(s: impl SemaStream + 'static) -> Value {
871 Value::from_rc_ptr(TAG_STREAM, Rc::new(StreamBox::new(s)))
872 }
873
874 pub fn stream_from_rc(rc: Rc<StreamBox>) -> Value {
875 Value::from_rc_ptr(TAG_STREAM, rc)
876 }
877
878 pub fn async_promise(promise: AsyncPromise) -> Value {
879 Value::from_rc_ptr(TAG_ASYNC_PROMISE, Rc::new(promise))
880 }
881 pub fn async_promise_from_rc(rc: Rc<AsyncPromise>) -> Value {
882 Value::from_rc_ptr(TAG_ASYNC_PROMISE, rc)
883 }
884 pub fn channel(ch: Channel) -> Value {
885 Value::from_rc_ptr(TAG_CHANNEL, Rc::new(ch))
886 }
887 pub fn channel_from_rc(rc: Rc<Channel>) -> Value {
888 Value::from_rc_ptr(TAG_CHANNEL, rc)
889 }
890}
891
892const fn make_boxed_const(tag: u64, payload: u64) -> u64 {
894 BOX_MASK | (tag << 45) | (payload & PAYLOAD_MASK)
895}
896
897impl Value {
900 #[inline(always)]
902 pub fn raw_bits(&self) -> u64 {
903 self.0
904 }
905
906 #[inline(always)]
915 pub unsafe fn from_raw_bits(bits: u64) -> Value {
916 Value(bits)
917 }
918
919 #[inline(always)]
922 pub fn raw_tag(&self) -> Option<u64> {
923 if is_boxed(self.0) {
924 Some(get_tag(self.0))
925 } else {
926 None
927 }
928 }
929
930 #[inline(always)]
933 pub fn as_native_fn_ref(&self) -> Option<&NativeFn> {
934 if is_boxed(self.0) && get_tag(self.0) == TAG_NATIVE_FN {
935 Some(unsafe { self.borrow_ref::<NativeFn>() })
936 } else {
937 None
938 }
939 }
940
941 #[inline(always)]
943 pub fn is_float(&self) -> bool {
944 !is_boxed(self.0)
945 }
946
947 #[inline(always)]
950 unsafe fn get_rc<T>(&self) -> Rc<T> {
951 let payload = get_payload(self.0);
952 let ptr = payload_to_ptr(payload) as *const T;
953 Rc::increment_strong_count(ptr);
954 Rc::from_raw(ptr)
955 }
956
957 #[inline(always)]
960 unsafe fn borrow_ref<T>(&self) -> &T {
961 let payload = get_payload(self.0);
962 let ptr = payload_to_ptr(payload) as *const T;
963 &*ptr
964 }
965
966 pub fn view(&self) -> ValueView {
969 if !is_boxed(self.0) {
970 return ValueView::Float(f64::from_bits(self.0));
971 }
972 let tag = get_tag(self.0);
973 match tag {
974 TAG_NIL => ValueView::Nil,
975 TAG_FALSE => ValueView::Bool(false),
976 TAG_TRUE => ValueView::Bool(true),
977 TAG_INT_SMALL => {
978 let payload = get_payload(self.0);
979 let val = if payload & INT_SIGN_BIT != 0 {
980 (payload | !PAYLOAD_MASK) as i64
981 } else {
982 payload as i64
983 };
984 ValueView::Int(val)
985 }
986 TAG_CHAR => {
987 let payload = get_payload(self.0);
988 ValueView::Char(unsafe { char::from_u32_unchecked(payload as u32) })
989 }
990 TAG_SYMBOL => {
991 let payload = get_payload(self.0);
992 let spur: Spur = unsafe { std::mem::transmute(payload as u32) };
996 ValueView::Symbol(spur)
997 }
998 TAG_KEYWORD => {
999 let payload = get_payload(self.0);
1000 let spur: Spur = unsafe { std::mem::transmute(payload as u32) };
1004 ValueView::Keyword(spur)
1005 }
1006 TAG_INT_BIG => {
1007 let val = unsafe { *self.borrow_ref::<i64>() };
1008 ValueView::Int(val)
1009 }
1010 TAG_STRING => ValueView::String(unsafe { self.get_rc::<String>() }),
1016 TAG_LIST => ValueView::List(unsafe { self.get_rc::<Vec<Value>>() }),
1017 TAG_VECTOR => ValueView::Vector(unsafe { self.get_rc::<Vec<Value>>() }),
1018 TAG_MAP => ValueView::Map(unsafe { self.get_rc::<BTreeMap<Value, Value>>() }),
1019 TAG_HASHMAP => {
1020 ValueView::HashMap(unsafe { self.get_rc::<hashbrown::HashMap<Value, Value>>() })
1021 }
1022 TAG_LAMBDA => ValueView::Lambda(unsafe { self.get_rc::<Lambda>() }),
1023 TAG_MACRO => ValueView::Macro(unsafe { self.get_rc::<Macro>() }),
1024 TAG_NATIVE_FN => ValueView::NativeFn(unsafe { self.get_rc::<NativeFn>() }),
1025 TAG_PROMPT => ValueView::Prompt(unsafe { self.get_rc::<Prompt>() }),
1026 TAG_MESSAGE => ValueView::Message(unsafe { self.get_rc::<Message>() }),
1027 TAG_CONVERSATION => ValueView::Conversation(unsafe { self.get_rc::<Conversation>() }),
1028 TAG_TOOL_DEF => ValueView::ToolDef(unsafe { self.get_rc::<ToolDefinition>() }),
1029 TAG_AGENT => ValueView::Agent(unsafe { self.get_rc::<Agent>() }),
1030 TAG_THUNK => ValueView::Thunk(unsafe { self.get_rc::<Thunk>() }),
1031 TAG_RECORD => ValueView::Record(unsafe { self.get_rc::<Record>() }),
1032 TAG_BYTEVECTOR => ValueView::Bytevector(unsafe { self.get_rc::<Vec<u8>>() }),
1033 TAG_MULTIMETHOD => ValueView::MultiMethod(unsafe { self.get_rc::<MultiMethod>() }),
1034 TAG_STREAM => ValueView::Stream(unsafe { self.get_rc::<StreamBox>() }),
1035 TAG_F64_ARRAY => ValueView::F64Array(unsafe { self.get_rc::<Vec<f64>>() }),
1036 TAG_I64_ARRAY => ValueView::I64Array(unsafe { self.get_rc::<Vec<i64>>() }),
1037 TAG_ASYNC_PROMISE => ValueView::AsyncPromise(unsafe { self.get_rc::<AsyncPromise>() }),
1038 TAG_CHANNEL => ValueView::Channel(unsafe { self.get_rc::<Channel>() }),
1039 _ => unreachable!("invalid NaN-boxed tag: {}", tag),
1040 }
1041 }
1042
1043 pub fn type_name(&self) -> &'static str {
1046 if !is_boxed(self.0) {
1047 return "float";
1048 }
1049 match get_tag(self.0) {
1050 TAG_NIL => "nil",
1051 TAG_FALSE | TAG_TRUE => "bool",
1052 TAG_INT_SMALL | TAG_INT_BIG => "int",
1053 TAG_CHAR => "char",
1054 TAG_SYMBOL => "symbol",
1055 TAG_KEYWORD => "keyword",
1056 TAG_STRING => "string",
1057 TAG_LIST => "list",
1058 TAG_VECTOR => "vector",
1059 TAG_MAP => "map",
1060 TAG_HASHMAP => "hashmap",
1061 TAG_LAMBDA => "lambda",
1062 TAG_MACRO => "macro",
1063 TAG_NATIVE_FN => "native-fn",
1064 TAG_PROMPT => "prompt",
1065 TAG_MESSAGE => "message",
1066 TAG_CONVERSATION => "conversation",
1067 TAG_TOOL_DEF => "tool",
1068 TAG_AGENT => "agent",
1069 TAG_THUNK => "promise",
1070 TAG_RECORD => "record",
1071 TAG_BYTEVECTOR => "bytevector",
1072 TAG_MULTIMETHOD => "multimethod",
1073 TAG_STREAM => "stream",
1074 TAG_F64_ARRAY => "f64-array",
1075 TAG_I64_ARRAY => "i64-array",
1076 TAG_ASYNC_PROMISE => "async-promise",
1077 TAG_CHANNEL => "channel",
1078 _ => "unknown",
1079 }
1080 }
1081
1082 #[inline(always)]
1083 pub fn is_nil(&self) -> bool {
1084 self.0 == Value::NIL.0
1085 }
1086
1087 #[inline(always)]
1088 pub fn is_truthy(&self) -> bool {
1089 self.0 != Value::NIL.0 && self.0 != Value::FALSE.0
1090 }
1091
1092 #[inline(always)]
1093 pub fn is_falsy(&self) -> bool {
1094 !self.is_truthy()
1095 }
1096
1097 #[inline(always)]
1098 pub fn is_bool(&self) -> bool {
1099 self.0 == Value::TRUE.0 || self.0 == Value::FALSE.0
1100 }
1101
1102 #[inline(always)]
1103 pub fn is_int(&self) -> bool {
1104 is_boxed(self.0) && matches!(get_tag(self.0), TAG_INT_SMALL | TAG_INT_BIG)
1105 }
1106
1107 #[inline(always)]
1108 pub fn is_symbol(&self) -> bool {
1109 is_boxed(self.0) && get_tag(self.0) == TAG_SYMBOL
1110 }
1111
1112 #[inline(always)]
1113 pub fn is_keyword(&self) -> bool {
1114 is_boxed(self.0) && get_tag(self.0) == TAG_KEYWORD
1115 }
1116
1117 #[inline(always)]
1118 pub fn is_string(&self) -> bool {
1119 is_boxed(self.0) && get_tag(self.0) == TAG_STRING
1120 }
1121
1122 #[inline(always)]
1123 pub fn is_list(&self) -> bool {
1124 is_boxed(self.0) && get_tag(self.0) == TAG_LIST
1125 }
1126
1127 #[inline(always)]
1128 pub fn is_pair(&self) -> bool {
1129 if let Some(items) = self.as_list() {
1130 !items.is_empty()
1131 } else {
1132 false
1133 }
1134 }
1135
1136 #[inline(always)]
1137 pub fn is_vector(&self) -> bool {
1138 is_boxed(self.0) && get_tag(self.0) == TAG_VECTOR
1139 }
1140
1141 #[inline(always)]
1142 pub fn is_map(&self) -> bool {
1143 is_boxed(self.0) && matches!(get_tag(self.0), TAG_MAP | TAG_HASHMAP)
1144 }
1145
1146 #[inline(always)]
1147 pub fn is_lambda(&self) -> bool {
1148 is_boxed(self.0) && get_tag(self.0) == TAG_LAMBDA
1149 }
1150
1151 #[inline(always)]
1152 pub fn is_native_fn(&self) -> bool {
1153 is_boxed(self.0) && get_tag(self.0) == TAG_NATIVE_FN
1154 }
1155
1156 #[inline(always)]
1157 pub fn is_thunk(&self) -> bool {
1158 is_boxed(self.0) && get_tag(self.0) == TAG_THUNK
1159 }
1160
1161 #[inline(always)]
1162 pub fn is_async_promise(&self) -> bool {
1163 is_boxed(self.0) && get_tag(self.0) == TAG_ASYNC_PROMISE
1164 }
1165 #[inline(always)]
1166 pub fn is_channel(&self) -> bool {
1167 is_boxed(self.0) && get_tag(self.0) == TAG_CHANNEL
1168 }
1169
1170 #[inline(always)]
1171 pub fn is_record(&self) -> bool {
1172 is_boxed(self.0) && get_tag(self.0) == TAG_RECORD
1173 }
1174
1175 #[inline(always)]
1176 pub fn as_int(&self) -> Option<i64> {
1177 if !is_boxed(self.0) {
1178 return None;
1179 }
1180 match get_tag(self.0) {
1181 TAG_INT_SMALL => {
1182 let payload = get_payload(self.0);
1183 let val = if payload & INT_SIGN_BIT != 0 {
1184 (payload | !PAYLOAD_MASK) as i64
1185 } else {
1186 payload as i64
1187 };
1188 Some(val)
1189 }
1190 TAG_INT_BIG => Some(unsafe { *self.borrow_ref::<i64>() }),
1191 _ => None,
1192 }
1193 }
1194
1195 pub fn as_index(&self, name: &str) -> Result<usize, SemaError> {
1201 let n = self.as_int().ok_or_else(|| {
1202 SemaError::type_error("int", self.type_name())
1203 .with_hint(format!("{name}: argument must be an integer"))
1204 })?;
1205 if n < 0 {
1206 return Err(SemaError::eval(format!(
1207 "{name}: expected a non-negative integer, got {n}"
1208 ))
1209 .with_hint("pass 0 or a positive integer"));
1210 }
1211 Ok(n as usize)
1212 }
1213
1214 #[inline(always)]
1215 pub fn as_float(&self) -> Option<f64> {
1216 if !is_boxed(self.0) {
1217 return Some(f64::from_bits(self.0));
1218 }
1219 match get_tag(self.0) {
1220 TAG_INT_SMALL => {
1221 let payload = get_payload(self.0);
1222 let val = if payload & INT_SIGN_BIT != 0 {
1223 (payload | !PAYLOAD_MASK) as i64
1224 } else {
1225 payload as i64
1226 };
1227 Some(val as f64)
1228 }
1229 TAG_INT_BIG => Some(unsafe { *self.borrow_ref::<i64>() } as f64),
1230 _ => None,
1231 }
1232 }
1233
1234 #[inline(always)]
1235 pub fn as_bool(&self) -> Option<bool> {
1236 if self.0 == Value::TRUE.0 {
1237 Some(true)
1238 } else if self.0 == Value::FALSE.0 {
1239 Some(false)
1240 } else {
1241 None
1242 }
1243 }
1244
1245 pub fn as_str(&self) -> Option<&str> {
1246 if is_boxed(self.0) && get_tag(self.0) == TAG_STRING {
1247 Some(unsafe { self.borrow_ref::<String>() })
1248 } else {
1249 None
1250 }
1251 }
1252
1253 pub fn as_string_rc(&self) -> Option<Rc<String>> {
1254 if is_boxed(self.0) && get_tag(self.0) == TAG_STRING {
1255 Some(unsafe { self.get_rc::<String>() })
1256 } else {
1257 None
1258 }
1259 }
1260
1261 pub fn as_symbol(&self) -> Option<String> {
1262 self.as_symbol_spur().map(resolve)
1263 }
1264
1265 pub fn as_symbol_spur(&self) -> Option<Spur> {
1266 if is_boxed(self.0) && get_tag(self.0) == TAG_SYMBOL {
1267 let payload = get_payload(self.0);
1268 Some(unsafe { std::mem::transmute::<u32, Spur>(payload as u32) })
1273 } else {
1274 None
1275 }
1276 }
1277
1278 pub fn as_keyword(&self) -> Option<String> {
1279 self.as_keyword_spur().map(resolve)
1280 }
1281
1282 pub fn as_keyword_spur(&self) -> Option<Spur> {
1283 if is_boxed(self.0) && get_tag(self.0) == TAG_KEYWORD {
1284 let payload = get_payload(self.0);
1285 Some(unsafe { std::mem::transmute::<u32, Spur>(payload as u32) })
1290 } else {
1291 None
1292 }
1293 }
1294
1295 pub fn as_char(&self) -> Option<char> {
1296 if is_boxed(self.0) && get_tag(self.0) == TAG_CHAR {
1297 let payload = get_payload(self.0);
1298 char::from_u32(payload as u32)
1299 } else {
1300 None
1301 }
1302 }
1303
1304 pub fn as_list(&self) -> Option<&[Value]> {
1305 if is_boxed(self.0) && get_tag(self.0) == TAG_LIST {
1306 Some(unsafe { self.borrow_ref::<Vec<Value>>() })
1307 } else {
1308 None
1309 }
1310 }
1311
1312 pub fn as_list_rc(&self) -> Option<Rc<Vec<Value>>> {
1313 if is_boxed(self.0) && get_tag(self.0) == TAG_LIST {
1314 Some(unsafe { self.get_rc::<Vec<Value>>() })
1315 } else {
1316 None
1317 }
1318 }
1319
1320 pub fn as_seq(&self) -> Option<&[Value]> {
1322 self.as_list().or_else(|| self.as_vector())
1323 }
1324
1325 pub fn as_vector(&self) -> Option<&[Value]> {
1326 if is_boxed(self.0) && get_tag(self.0) == TAG_VECTOR {
1327 Some(unsafe { self.borrow_ref::<Vec<Value>>() })
1328 } else {
1329 None
1330 }
1331 }
1332
1333 pub fn as_vector_rc(&self) -> Option<Rc<Vec<Value>>> {
1334 if is_boxed(self.0) && get_tag(self.0) == TAG_VECTOR {
1335 Some(unsafe { self.get_rc::<Vec<Value>>() })
1336 } else {
1337 None
1338 }
1339 }
1340
1341 pub fn as_map_rc(&self) -> Option<Rc<BTreeMap<Value, Value>>> {
1342 if is_boxed(self.0) && get_tag(self.0) == TAG_MAP {
1343 Some(unsafe { self.get_rc::<BTreeMap<Value, Value>>() })
1344 } else {
1345 None
1346 }
1347 }
1348
1349 pub fn as_hashmap_rc(&self) -> Option<Rc<hashbrown::HashMap<Value, Value>>> {
1350 if is_boxed(self.0) && get_tag(self.0) == TAG_HASHMAP {
1351 Some(unsafe { self.get_rc::<hashbrown::HashMap<Value, Value>>() })
1352 } else {
1353 None
1354 }
1355 }
1356
1357 #[inline(always)]
1359 pub fn as_hashmap_ref(&self) -> Option<&hashbrown::HashMap<Value, Value>> {
1360 if is_boxed(self.0) && get_tag(self.0) == TAG_HASHMAP {
1361 Some(unsafe { self.borrow_ref::<hashbrown::HashMap<Value, Value>>() })
1362 } else {
1363 None
1364 }
1365 }
1366
1367 #[inline(always)]
1369 pub fn as_map_ref(&self) -> Option<&BTreeMap<Value, Value>> {
1370 if is_boxed(self.0) && get_tag(self.0) == TAG_MAP {
1371 Some(unsafe { self.borrow_ref::<BTreeMap<Value, Value>>() })
1372 } else {
1373 None
1374 }
1375 }
1376
1377 #[inline(always)]
1381 pub fn with_hashmap_mut_if_unique<R>(
1382 &self,
1383 f: impl FnOnce(&mut hashbrown::HashMap<Value, Value>) -> R,
1384 ) -> Option<R> {
1385 if !is_boxed(self.0) || get_tag(self.0) != TAG_HASHMAP {
1386 return None;
1387 }
1388 let payload = get_payload(self.0);
1389 let ptr = payload_to_ptr(payload) as *const hashbrown::HashMap<Value, Value>;
1390 let rc = std::mem::ManuallyDrop::new(unsafe { Rc::from_raw(ptr) });
1391 if Rc::strong_count(&rc) != 1 {
1392 return None;
1393 }
1394 let ptr_mut = ptr as *mut hashbrown::HashMap<Value, Value>;
1396 Some(f(unsafe { &mut *ptr_mut }))
1397 }
1398
1399 #[inline(always)]
1402 pub fn with_map_mut_if_unique<R>(
1403 &self,
1404 f: impl FnOnce(&mut BTreeMap<Value, Value>) -> R,
1405 ) -> Option<R> {
1406 if !is_boxed(self.0) || get_tag(self.0) != TAG_MAP {
1407 return None;
1408 }
1409 let payload = get_payload(self.0);
1410 let ptr = payload_to_ptr(payload) as *const BTreeMap<Value, Value>;
1411 let rc = std::mem::ManuallyDrop::new(unsafe { Rc::from_raw(ptr) });
1412 if Rc::strong_count(&rc) != 1 {
1413 return None;
1414 }
1415 let ptr_mut = ptr as *mut BTreeMap<Value, Value>;
1416 Some(f(unsafe { &mut *ptr_mut }))
1417 }
1418
1419 pub fn into_hashmap_rc(self) -> Result<Rc<hashbrown::HashMap<Value, Value>>, Value> {
1422 if is_boxed(self.0) && get_tag(self.0) == TAG_HASHMAP {
1423 let payload = get_payload(self.0);
1424 let ptr = payload_to_ptr(payload) as *const hashbrown::HashMap<Value, Value>;
1425 std::mem::forget(self);
1427 Ok(unsafe { Rc::from_raw(ptr) })
1428 } else {
1429 Err(self)
1430 }
1431 }
1432
1433 pub fn into_map_rc(self) -> Result<Rc<BTreeMap<Value, Value>>, Value> {
1436 if is_boxed(self.0) && get_tag(self.0) == TAG_MAP {
1437 let payload = get_payload(self.0);
1438 let ptr = payload_to_ptr(payload) as *const BTreeMap<Value, Value>;
1439 std::mem::forget(self);
1440 Ok(unsafe { Rc::from_raw(ptr) })
1441 } else {
1442 Err(self)
1443 }
1444 }
1445
1446 pub fn as_lambda_rc(&self) -> Option<Rc<Lambda>> {
1447 if is_boxed(self.0) && get_tag(self.0) == TAG_LAMBDA {
1448 Some(unsafe { self.get_rc::<Lambda>() })
1449 } else {
1450 None
1451 }
1452 }
1453
1454 pub fn as_macro_rc(&self) -> Option<Rc<Macro>> {
1455 if is_boxed(self.0) && get_tag(self.0) == TAG_MACRO {
1456 Some(unsafe { self.get_rc::<Macro>() })
1457 } else {
1458 None
1459 }
1460 }
1461
1462 pub fn as_native_fn_rc(&self) -> Option<Rc<NativeFn>> {
1463 if is_boxed(self.0) && get_tag(self.0) == TAG_NATIVE_FN {
1464 Some(unsafe { self.get_rc::<NativeFn>() })
1465 } else {
1466 None
1467 }
1468 }
1469
1470 pub fn as_thunk_rc(&self) -> Option<Rc<Thunk>> {
1471 if is_boxed(self.0) && get_tag(self.0) == TAG_THUNK {
1472 Some(unsafe { self.get_rc::<Thunk>() })
1473 } else {
1474 None
1475 }
1476 }
1477
1478 pub fn as_record(&self) -> Option<&Record> {
1479 if is_boxed(self.0) && get_tag(self.0) == TAG_RECORD {
1480 Some(unsafe { self.borrow_ref::<Record>() })
1481 } else {
1482 None
1483 }
1484 }
1485
1486 pub fn as_record_rc(&self) -> Option<Rc<Record>> {
1487 if is_boxed(self.0) && get_tag(self.0) == TAG_RECORD {
1488 Some(unsafe { self.get_rc::<Record>() })
1489 } else {
1490 None
1491 }
1492 }
1493
1494 pub fn as_bytevector(&self) -> Option<&[u8]> {
1495 if is_boxed(self.0) && get_tag(self.0) == TAG_BYTEVECTOR {
1496 Some(unsafe { self.borrow_ref::<Vec<u8>>() })
1497 } else {
1498 None
1499 }
1500 }
1501
1502 pub fn as_bytevector_rc(&self) -> Option<Rc<Vec<u8>>> {
1503 if is_boxed(self.0) && get_tag(self.0) == TAG_BYTEVECTOR {
1504 Some(unsafe { self.get_rc::<Vec<u8>>() })
1505 } else {
1506 None
1507 }
1508 }
1509
1510 pub fn as_f64_array(&self) -> Option<&[f64]> {
1511 if is_boxed(self.0) && get_tag(self.0) == TAG_F64_ARRAY {
1512 Some(unsafe { self.borrow_ref::<Vec<f64>>() })
1513 } else {
1514 None
1515 }
1516 }
1517
1518 pub fn as_f64_array_rc(&self) -> Option<Rc<Vec<f64>>> {
1519 if is_boxed(self.0) && get_tag(self.0) == TAG_F64_ARRAY {
1520 Some(unsafe { self.get_rc::<Vec<f64>>() })
1521 } else {
1522 None
1523 }
1524 }
1525
1526 pub fn as_i64_array(&self) -> Option<&[i64]> {
1527 if is_boxed(self.0) && get_tag(self.0) == TAG_I64_ARRAY {
1528 Some(unsafe { self.borrow_ref::<Vec<i64>>() })
1529 } else {
1530 None
1531 }
1532 }
1533
1534 pub fn as_i64_array_rc(&self) -> Option<Rc<Vec<i64>>> {
1535 if is_boxed(self.0) && get_tag(self.0) == TAG_I64_ARRAY {
1536 Some(unsafe { self.get_rc::<Vec<i64>>() })
1537 } else {
1538 None
1539 }
1540 }
1541
1542 pub fn as_stream(&self) -> Option<&StreamBox> {
1543 if is_boxed(self.0) && get_tag(self.0) == TAG_STREAM {
1544 Some(unsafe { self.borrow_ref::<StreamBox>() })
1545 } else {
1546 None
1547 }
1548 }
1549
1550 pub fn as_stream_rc(&self) -> Option<Rc<StreamBox>> {
1551 if is_boxed(self.0) && get_tag(self.0) == TAG_STREAM {
1552 Some(unsafe { self.get_rc::<StreamBox>() })
1553 } else {
1554 None
1555 }
1556 }
1557
1558 pub fn as_prompt_rc(&self) -> Option<Rc<Prompt>> {
1559 if is_boxed(self.0) && get_tag(self.0) == TAG_PROMPT {
1560 Some(unsafe { self.get_rc::<Prompt>() })
1561 } else {
1562 None
1563 }
1564 }
1565
1566 pub fn as_message_rc(&self) -> Option<Rc<Message>> {
1567 if is_boxed(self.0) && get_tag(self.0) == TAG_MESSAGE {
1568 Some(unsafe { self.get_rc::<Message>() })
1569 } else {
1570 None
1571 }
1572 }
1573
1574 pub fn as_conversation_rc(&self) -> Option<Rc<Conversation>> {
1575 if is_boxed(self.0) && get_tag(self.0) == TAG_CONVERSATION {
1576 Some(unsafe { self.get_rc::<Conversation>() })
1577 } else {
1578 None
1579 }
1580 }
1581
1582 pub fn as_tool_def_rc(&self) -> Option<Rc<ToolDefinition>> {
1583 if is_boxed(self.0) && get_tag(self.0) == TAG_TOOL_DEF {
1584 Some(unsafe { self.get_rc::<ToolDefinition>() })
1585 } else {
1586 None
1587 }
1588 }
1589
1590 pub fn as_agent_rc(&self) -> Option<Rc<Agent>> {
1591 if is_boxed(self.0) && get_tag(self.0) == TAG_AGENT {
1592 Some(unsafe { self.get_rc::<Agent>() })
1593 } else {
1594 None
1595 }
1596 }
1597
1598 pub fn as_multimethod_rc(&self) -> Option<Rc<MultiMethod>> {
1599 if is_boxed(self.0) && get_tag(self.0) == TAG_MULTIMETHOD {
1600 Some(unsafe { self.get_rc::<MultiMethod>() })
1601 } else {
1602 None
1603 }
1604 }
1605}
1606
1607impl Clone for Value {
1610 #[inline(always)]
1611 fn clone(&self) -> Self {
1612 if !is_boxed(self.0) {
1613 return Value(self.0);
1615 }
1616 let tag = get_tag(self.0);
1617 match tag {
1618 TAG_NIL | TAG_FALSE | TAG_TRUE | TAG_INT_SMALL | TAG_CHAR | TAG_SYMBOL
1620 | TAG_KEYWORD => Value(self.0),
1621 _ => {
1623 let payload = get_payload(self.0);
1624 let ptr = payload_to_ptr(payload);
1625 unsafe {
1627 match tag {
1628 TAG_INT_BIG => Rc::increment_strong_count(ptr as *const i64),
1629 TAG_STRING => Rc::increment_strong_count(ptr as *const String),
1630 TAG_LIST | TAG_VECTOR => {
1631 Rc::increment_strong_count(ptr as *const Vec<Value>)
1632 }
1633 TAG_MAP => Rc::increment_strong_count(ptr as *const BTreeMap<Value, Value>),
1634 TAG_HASHMAP => Rc::increment_strong_count(
1635 ptr as *const hashbrown::HashMap<Value, Value>,
1636 ),
1637 TAG_LAMBDA => Rc::increment_strong_count(ptr as *const Lambda),
1638 TAG_MACRO => Rc::increment_strong_count(ptr as *const Macro),
1639 TAG_NATIVE_FN => Rc::increment_strong_count(ptr as *const NativeFn),
1640 TAG_PROMPT => Rc::increment_strong_count(ptr as *const Prompt),
1641 TAG_MESSAGE => Rc::increment_strong_count(ptr as *const Message),
1642 TAG_CONVERSATION => Rc::increment_strong_count(ptr as *const Conversation),
1643 TAG_TOOL_DEF => Rc::increment_strong_count(ptr as *const ToolDefinition),
1644 TAG_AGENT => Rc::increment_strong_count(ptr as *const Agent),
1645 TAG_THUNK => Rc::increment_strong_count(ptr as *const Thunk),
1646 TAG_RECORD => Rc::increment_strong_count(ptr as *const Record),
1647 TAG_BYTEVECTOR => Rc::increment_strong_count(ptr as *const Vec<u8>),
1648 TAG_MULTIMETHOD => Rc::increment_strong_count(ptr as *const MultiMethod),
1649 TAG_STREAM => Rc::increment_strong_count(ptr as *const StreamBox),
1650 TAG_F64_ARRAY => Rc::increment_strong_count(ptr as *const Vec<f64>),
1651 TAG_I64_ARRAY => Rc::increment_strong_count(ptr as *const Vec<i64>),
1652 TAG_ASYNC_PROMISE => Rc::increment_strong_count(ptr as *const AsyncPromise),
1653 TAG_CHANNEL => Rc::increment_strong_count(ptr as *const Channel),
1654 _ => unreachable!("invalid heap tag in clone: {}", tag),
1655 }
1656 }
1657 Value(self.0)
1658 }
1659 }
1660 }
1661}
1662
1663impl Drop for Value {
1666 #[inline(always)]
1667 fn drop(&mut self) {
1668 if !is_boxed(self.0) {
1669 return; }
1671 let tag = get_tag(self.0);
1672 match tag {
1673 TAG_NIL | TAG_FALSE | TAG_TRUE | TAG_INT_SMALL | TAG_CHAR | TAG_SYMBOL
1675 | TAG_KEYWORD => {}
1676 _ => {
1678 let payload = get_payload(self.0);
1679 let ptr = payload_to_ptr(payload);
1680 unsafe {
1681 match tag {
1682 TAG_INT_BIG => drop(Rc::from_raw(ptr as *const i64)),
1683 TAG_STRING => drop(Rc::from_raw(ptr as *const String)),
1684 TAG_LIST | TAG_VECTOR => drop(Rc::from_raw(ptr as *const Vec<Value>)),
1685 TAG_MAP => drop(Rc::from_raw(ptr as *const BTreeMap<Value, Value>)),
1686 TAG_HASHMAP => {
1687 drop(Rc::from_raw(ptr as *const hashbrown::HashMap<Value, Value>))
1688 }
1689 TAG_LAMBDA => drop(Rc::from_raw(ptr as *const Lambda)),
1690 TAG_MACRO => drop(Rc::from_raw(ptr as *const Macro)),
1691 TAG_NATIVE_FN => drop(Rc::from_raw(ptr as *const NativeFn)),
1692 TAG_PROMPT => drop(Rc::from_raw(ptr as *const Prompt)),
1693 TAG_MESSAGE => drop(Rc::from_raw(ptr as *const Message)),
1694 TAG_CONVERSATION => drop(Rc::from_raw(ptr as *const Conversation)),
1695 TAG_TOOL_DEF => drop(Rc::from_raw(ptr as *const ToolDefinition)),
1696 TAG_AGENT => drop(Rc::from_raw(ptr as *const Agent)),
1697 TAG_THUNK => drop(Rc::from_raw(ptr as *const Thunk)),
1698 TAG_RECORD => drop(Rc::from_raw(ptr as *const Record)),
1699 TAG_BYTEVECTOR => drop(Rc::from_raw(ptr as *const Vec<u8>)),
1700 TAG_MULTIMETHOD => drop(Rc::from_raw(ptr as *const MultiMethod)),
1701 TAG_STREAM => drop(Rc::from_raw(ptr as *const StreamBox)),
1702 TAG_F64_ARRAY => drop(Rc::from_raw(ptr as *const Vec<f64>)),
1703 TAG_I64_ARRAY => drop(Rc::from_raw(ptr as *const Vec<i64>)),
1704 TAG_ASYNC_PROMISE => drop(Rc::from_raw(ptr as *const AsyncPromise)),
1705 TAG_CHANNEL => drop(Rc::from_raw(ptr as *const Channel)),
1706 _ => {} }
1708 }
1709 }
1710 }
1711 }
1712}
1713
1714impl PartialEq for Value {
1717 fn eq(&self, other: &Self) -> bool {
1718 if self.0 == other.0 {
1720 if !is_boxed(self.0) {
1724 let f = f64::from_bits(self.0);
1725 if f.is_nan() {
1727 return false;
1728 }
1729 return true;
1730 }
1731 return true;
1732 }
1733 match (self.view(), other.view()) {
1735 (ValueView::Nil, ValueView::Nil) => true,
1736 (ValueView::Bool(a), ValueView::Bool(b)) => a == b,
1737 (ValueView::Int(a), ValueView::Int(b)) => a == b,
1738 (ValueView::Float(a), ValueView::Float(b)) => a == b,
1739 (ValueView::String(a), ValueView::String(b)) => a == b,
1740 (ValueView::Symbol(a), ValueView::Symbol(b)) => a == b,
1741 (ValueView::Keyword(a), ValueView::Keyword(b)) => a == b,
1742 (ValueView::Char(a), ValueView::Char(b)) => a == b,
1743 (ValueView::List(a), ValueView::List(b)) => a == b,
1744 (ValueView::Vector(a), ValueView::Vector(b)) => a == b,
1745 (ValueView::Map(a), ValueView::Map(b)) => a == b,
1746 (ValueView::HashMap(a), ValueView::HashMap(b)) => a == b,
1747 (ValueView::Record(a), ValueView::Record(b)) => {
1748 a.type_tag == b.type_tag && a.fields == b.fields
1749 }
1750 (ValueView::Bytevector(a), ValueView::Bytevector(b)) => a == b,
1751 (ValueView::F64Array(a), ValueView::F64Array(b)) => {
1752 a.len() == b.len()
1753 && a.iter()
1754 .zip(b.iter())
1755 .all(|(x, y)| x.to_bits() == y.to_bits())
1756 }
1757 (ValueView::I64Array(a), ValueView::I64Array(b)) => a == b,
1758 (ValueView::Stream(a), ValueView::Stream(b)) => Rc::ptr_eq(&a, &b),
1759 (ValueView::AsyncPromise(a), ValueView::AsyncPromise(b)) => Rc::ptr_eq(&a, &b),
1760 (ValueView::Channel(a), ValueView::Channel(b)) => Rc::ptr_eq(&a, &b),
1761 _ => false,
1762 }
1763 }
1764}
1765
1766impl Eq for Value {}
1767
1768impl Hash for Value {
1771 fn hash<H: Hasher>(&self, state: &mut H) {
1772 match self.view() {
1773 ValueView::Nil => 0u8.hash(state),
1774 ValueView::Bool(b) => {
1775 1u8.hash(state);
1776 b.hash(state);
1777 }
1778 ValueView::Int(n) => {
1779 2u8.hash(state);
1780 n.hash(state);
1781 }
1782 ValueView::Float(f) => {
1783 3u8.hash(state);
1784 let bits = if f == 0.0 { 0u64 } else { f.to_bits() };
1786 bits.hash(state);
1787 }
1788 ValueView::String(s) => {
1789 4u8.hash(state);
1790 s.hash(state);
1791 }
1792 ValueView::Symbol(s) => {
1793 5u8.hash(state);
1794 s.hash(state);
1795 }
1796 ValueView::Keyword(s) => {
1797 6u8.hash(state);
1798 s.hash(state);
1799 }
1800 ValueView::Char(c) => {
1801 7u8.hash(state);
1802 c.hash(state);
1803 }
1804 ValueView::List(l) => {
1805 8u8.hash(state);
1806 l.hash(state);
1807 }
1808 ValueView::Vector(v) => {
1809 9u8.hash(state);
1810 v.hash(state);
1811 }
1812 ValueView::Record(r) => {
1813 10u8.hash(state);
1814 r.type_tag.hash(state);
1815 r.fields.hash(state);
1816 }
1817 ValueView::Bytevector(bv) => {
1818 11u8.hash(state);
1819 bv.hash(state);
1820 }
1821 ValueView::F64Array(arr) => {
1822 26u8.hash(state);
1823 for v in arr.iter() {
1824 v.to_bits().hash(state);
1825 }
1826 }
1827 ValueView::I64Array(arr) => {
1828 27u8.hash(state);
1829 arr.hash(state);
1830 }
1831 ValueView::Stream(s) => {
1832 25u8.hash(state);
1833 (Rc::as_ptr(&s) as usize).hash(state);
1834 }
1835 ValueView::AsyncPromise(p) => {
1836 28u8.hash(state);
1837 (Rc::as_ptr(&p) as usize).hash(state);
1838 }
1839 ValueView::Channel(c) => {
1840 29u8.hash(state);
1841 (Rc::as_ptr(&c) as usize).hash(state);
1842 }
1843 _ => {}
1844 }
1845 }
1846}
1847
1848impl PartialOrd for Value {
1851 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1852 Some(self.cmp(other))
1853 }
1854}
1855
1856impl Ord for Value {
1857 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1858 use std::cmp::Ordering;
1859 fn type_order(v: &Value) -> u8 {
1860 match v.view() {
1861 ValueView::Nil => 0,
1862 ValueView::Bool(_) => 1,
1863 ValueView::Int(_) => 2,
1864 ValueView::Float(_) => 3,
1865 ValueView::Char(_) => 4,
1866 ValueView::String(_) => 5,
1867 ValueView::Symbol(_) => 6,
1868 ValueView::Keyword(_) => 7,
1869 ValueView::List(_) => 8,
1870 ValueView::Vector(_) => 9,
1871 ValueView::Map(_) => 10,
1872 ValueView::HashMap(_) => 11,
1873 ValueView::Record(_) => 12,
1874 ValueView::Bytevector(_) => 13,
1875 ValueView::F64Array(_) => 14,
1876 ValueView::I64Array(_) => 15,
1877 ValueView::Stream(_) => 16,
1878 _ => 17,
1879 }
1880 }
1881 match (self.view(), other.view()) {
1882 (ValueView::Nil, ValueView::Nil) => Ordering::Equal,
1883 (ValueView::Bool(a), ValueView::Bool(b)) => a.cmp(&b),
1884 (ValueView::Int(a), ValueView::Int(b)) => a.cmp(&b),
1885 (ValueView::Float(a), ValueView::Float(b)) => a.total_cmp(&b),
1886 (ValueView::String(a), ValueView::String(b)) => a.cmp(&b),
1887 (ValueView::Symbol(a), ValueView::Symbol(b)) => compare_spurs(a, b),
1888 (ValueView::Keyword(a), ValueView::Keyword(b)) => compare_spurs(a, b),
1889 (ValueView::Char(a), ValueView::Char(b)) => a.cmp(&b),
1890 (ValueView::List(a), ValueView::List(b)) => a.cmp(&b),
1891 (ValueView::Vector(a), ValueView::Vector(b)) => a.cmp(&b),
1892 (ValueView::Record(a), ValueView::Record(b)) => {
1893 compare_spurs(a.type_tag, b.type_tag).then_with(|| a.fields.cmp(&b.fields))
1894 }
1895 (ValueView::Bytevector(a), ValueView::Bytevector(b)) => a.cmp(&b),
1896 (ValueView::I64Array(a), ValueView::I64Array(b)) => a.cmp(&b),
1897 (ValueView::F64Array(a), ValueView::F64Array(b)) => a
1898 .iter()
1899 .zip(b.iter())
1900 .map(|(x, y)| x.total_cmp(y))
1901 .find(|o| *o != std::cmp::Ordering::Equal)
1902 .unwrap_or_else(|| a.len().cmp(&b.len())),
1903 _ => type_order(self).cmp(&type_order(other)),
1904 }
1905 }
1906}
1907
1908fn truncate(s: &str, max: usize) -> String {
1911 let mut iter = s.chars();
1912 let prefix: String = iter.by_ref().take(max).collect();
1913 if iter.next().is_none() {
1914 prefix
1915 } else {
1916 format!("{prefix}...")
1917 }
1918}
1919
1920impl fmt::Display for Value {
1921 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1922 match self.view() {
1923 ValueView::Nil => write!(f, "nil"),
1924 ValueView::Bool(true) => write!(f, "#t"),
1925 ValueView::Bool(false) => write!(f, "#f"),
1926 ValueView::Int(n) => write!(f, "{n}"),
1927 ValueView::Float(n) => {
1928 if n.fract() == 0.0 {
1929 write!(f, "{n:.1}")
1930 } else {
1931 write!(f, "{n}")
1932 }
1933 }
1934 ValueView::String(s) => write!(f, "\"{s}\""),
1935 ValueView::Symbol(s) => with_resolved(s, |name| write!(f, "{name}")),
1936 ValueView::Keyword(s) => with_resolved(s, |name| write!(f, ":{name}")),
1937 ValueView::Char(c) => match c {
1938 ' ' => write!(f, "#\\space"),
1939 '\n' => write!(f, "#\\newline"),
1940 '\t' => write!(f, "#\\tab"),
1941 '\r' => write!(f, "#\\return"),
1942 '\0' => write!(f, "#\\nul"),
1943 _ => write!(f, "#\\{c}"),
1944 },
1945 ValueView::List(items) => {
1946 write!(f, "(")?;
1947 for (i, item) in items.iter().enumerate() {
1948 if i > 0 {
1949 write!(f, " ")?;
1950 }
1951 write!(f, "{item}")?;
1952 }
1953 write!(f, ")")
1954 }
1955 ValueView::Vector(items) => {
1956 write!(f, "[")?;
1957 for (i, item) in items.iter().enumerate() {
1958 if i > 0 {
1959 write!(f, " ")?;
1960 }
1961 write!(f, "{item}")?;
1962 }
1963 write!(f, "]")
1964 }
1965 ValueView::Map(map) => {
1966 write!(f, "{{")?;
1967 for (i, (k, v)) in map.iter().enumerate() {
1968 if i > 0 {
1969 write!(f, " ")?;
1970 }
1971 write!(f, "{k} {v}")?;
1972 }
1973 write!(f, "}}")
1974 }
1975 ValueView::HashMap(map) => {
1976 let mut entries: Vec<_> = map.iter().collect();
1977 entries.sort_by_key(|(k1, _)| *k1);
1978 write!(f, "{{")?;
1979 for (i, (k, v)) in entries.iter().enumerate() {
1980 if i > 0 {
1981 write!(f, " ")?;
1982 }
1983 write!(f, "{k} {v}")?;
1984 }
1985 write!(f, "}}")
1986 }
1987 ValueView::Lambda(l) => {
1988 if let Some(name) = &l.name {
1989 with_resolved(*name, |n| write!(f, "<lambda {n}>"))
1990 } else {
1991 write!(f, "<lambda>")
1992 }
1993 }
1994 ValueView::Macro(m) => with_resolved(m.name, |n| write!(f, "<macro {n}>")),
1995 ValueView::NativeFn(n) => write!(f, "<native-fn {}>", n.name),
1996 ValueView::Prompt(p) => write!(f, "<prompt {} messages>", p.messages.len()),
1997 ValueView::Message(m) => {
1998 write!(f, "<message {} \"{}\">", m.role, truncate(&m.content, 40))
1999 }
2000 ValueView::Conversation(c) => {
2001 write!(f, "<conversation {} messages>", c.messages.len())
2002 }
2003 ValueView::ToolDef(t) => write!(f, "<tool {}>", t.name),
2004 ValueView::Agent(a) => write!(f, "<agent {}>", a.name),
2005 ValueView::Thunk(t) => {
2006 if t.forced.borrow().is_some() {
2007 write!(f, "<promise (forced)>")
2008 } else {
2009 write!(f, "<promise>")
2010 }
2011 }
2012 ValueView::Record(r) => {
2013 with_resolved(r.type_tag, |tag| write!(f, "#<record {tag}"))?;
2014 for field in &r.fields {
2015 write!(f, " {field}")?;
2016 }
2017 write!(f, ">")
2018 }
2019 ValueView::Bytevector(bv) => {
2020 write!(f, "#u8(")?;
2021 for (i, byte) in bv.iter().enumerate() {
2022 if i > 0 {
2023 write!(f, " ")?;
2024 }
2025 write!(f, "{byte}")?;
2026 }
2027 write!(f, ")")
2028 }
2029 ValueView::F64Array(arr) => {
2030 write!(f, "#f64(")?;
2031 for (i, v) in arr.iter().enumerate() {
2032 if i > 0 {
2033 write!(f, " ")?;
2034 }
2035 write!(f, "{v}")?;
2036 }
2037 write!(f, ")")
2038 }
2039 ValueView::I64Array(arr) => {
2040 write!(f, "#i64(")?;
2041 for (i, v) in arr.iter().enumerate() {
2042 if i > 0 {
2043 write!(f, " ")?;
2044 }
2045 write!(f, "{v}")?;
2046 }
2047 write!(f, ")")
2048 }
2049 ValueView::MultiMethod(m) => with_resolved(m.name, |n| write!(f, "<multimethod {n}>")),
2050 ValueView::Stream(s) => write!(f, "<stream:{}>", s.stream_type()),
2051 ValueView::AsyncPromise(p) => match &*p.state.borrow() {
2052 PromiseState::Pending => write!(f, "<async-promise pending>"),
2053 PromiseState::Resolved(v) => write!(f, "<async-promise resolved: {v}>"),
2054 PromiseState::Rejected(e) => write!(f, "<async-promise rejected: {e}>"),
2055 PromiseState::Cancelled => write!(f, "<async-promise cancelled>"),
2056 },
2057 ValueView::Channel(c) => {
2058 let len = c.buffer.borrow().len();
2059 if c.closed.get() {
2060 write!(f, "<channel {len}/{} closed>", c.capacity)
2061 } else {
2062 write!(f, "<channel {len}/{}>", c.capacity)
2063 }
2064 }
2065 }
2066 }
2067}
2068
2069pub fn pretty_print(value: &Value, max_width: usize) -> String {
2075 let compact = format!("{value}");
2076 if compact.len() <= max_width {
2077 return compact;
2078 }
2079 let mut buf = String::new();
2080 pp_value(value, 0, max_width, &mut buf);
2081 buf
2082}
2083
2084fn pp_value(value: &Value, indent: usize, max_width: usize, buf: &mut String) {
2088 let compact = format!("{value}");
2089 let remaining = max_width.saturating_sub(indent);
2090 if compact.len() <= remaining {
2091 buf.push_str(&compact);
2092 return;
2093 }
2094
2095 match value.view() {
2096 ValueView::List(items) => {
2097 pp_seq(items.iter(), '(', ')', indent, max_width, buf);
2098 }
2099 ValueView::Vector(items) => {
2100 pp_seq(items.iter(), '[', ']', indent, max_width, buf);
2101 }
2102 ValueView::Map(map) => {
2103 pp_map(
2104 map.iter().map(|(k, v)| (k.clone(), v.clone())),
2105 indent,
2106 max_width,
2107 buf,
2108 );
2109 }
2110 ValueView::HashMap(map) => {
2111 let mut entries: Vec<_> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
2112 entries.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
2113 pp_map(entries.into_iter(), indent, max_width, buf);
2114 }
2115 _ => buf.push_str(&compact),
2116 }
2117}
2118
2119fn pp_seq<'a>(
2121 items: impl Iterator<Item = &'a Value>,
2122 open: char,
2123 close: char,
2124 indent: usize,
2125 max_width: usize,
2126 buf: &mut String,
2127) {
2128 buf.push(open);
2129 let child_indent = indent + 1;
2130 let pad = " ".repeat(child_indent);
2131 for (i, item) in items.enumerate() {
2132 if i > 0 {
2133 buf.push('\n');
2134 buf.push_str(&pad);
2135 }
2136 pp_value(item, child_indent, max_width, buf);
2137 }
2138 buf.push(close);
2139}
2140
2141fn pp_map(
2143 entries: impl Iterator<Item = (Value, Value)>,
2144 indent: usize,
2145 max_width: usize,
2146 buf: &mut String,
2147) {
2148 buf.push('{');
2149 let child_indent = indent + 1;
2150 let pad = " ".repeat(child_indent);
2151 for (i, (k, v)) in entries.enumerate() {
2152 if i > 0 {
2153 buf.push('\n');
2154 buf.push_str(&pad);
2155 }
2156 let key_str = format!("{k}");
2158 buf.push_str(&key_str);
2159
2160 let inline_indent = child_indent + key_str.len() + 1;
2162 let compact_val = format!("{v}");
2163 let remaining = max_width.saturating_sub(inline_indent);
2164
2165 if compact_val.len() <= remaining {
2166 buf.push(' ');
2168 buf.push_str(&compact_val);
2169 } else if is_compound(&v) {
2170 let nested_indent = child_indent + 2;
2172 let nested_pad = " ".repeat(nested_indent);
2173 buf.push('\n');
2174 buf.push_str(&nested_pad);
2175 pp_value(&v, nested_indent, max_width, buf);
2176 } else {
2177 buf.push(' ');
2179 buf.push_str(&compact_val);
2180 }
2181 }
2182 buf.push('}');
2183}
2184
2185fn is_compound(value: &Value) -> bool {
2187 matches!(
2188 value.view(),
2189 ValueView::List(_) | ValueView::Vector(_) | ValueView::Map(_) | ValueView::HashMap(_)
2190 )
2191}
2192
2193impl fmt::Debug for Value {
2196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2197 match self.view() {
2198 ValueView::Nil => write!(f, "Nil"),
2199 ValueView::Bool(b) => write!(f, "Bool({b})"),
2200 ValueView::Int(n) => write!(f, "Int({n})"),
2201 ValueView::Float(n) => write!(f, "Float({n})"),
2202 ValueView::String(s) => write!(f, "String({:?})", &**s),
2203 ValueView::Symbol(s) => write!(f, "Symbol({})", resolve(s)),
2204 ValueView::Keyword(s) => write!(f, "Keyword({})", resolve(s)),
2205 ValueView::Char(c) => write!(f, "Char({c:?})"),
2206 ValueView::List(items) => write!(f, "List({items:?})"),
2207 ValueView::Vector(items) => write!(f, "Vector({items:?})"),
2208 ValueView::Map(map) => write!(f, "Map({map:?})"),
2209 ValueView::HashMap(map) => write!(f, "HashMap({map:?})"),
2210 ValueView::Lambda(l) => write!(f, "{l:?}"),
2211 ValueView::Macro(m) => write!(f, "{m:?}"),
2212 ValueView::NativeFn(n) => write!(f, "{n:?}"),
2213 ValueView::Prompt(p) => write!(f, "{p:?}"),
2214 ValueView::Message(m) => write!(f, "{m:?}"),
2215 ValueView::Conversation(c) => write!(f, "{c:?}"),
2216 ValueView::ToolDef(t) => write!(f, "{t:?}"),
2217 ValueView::Agent(a) => write!(f, "{a:?}"),
2218 ValueView::Thunk(t) => write!(f, "{t:?}"),
2219 ValueView::Record(r) => write!(f, "{r:?}"),
2220 ValueView::Bytevector(bv) => write!(f, "Bytevector({bv:?})"),
2221 ValueView::F64Array(arr) => write!(f, "F64Array({arr:?})"),
2222 ValueView::I64Array(arr) => write!(f, "I64Array({arr:?})"),
2223 ValueView::MultiMethod(m) => write!(f, "{m:?}"),
2224 ValueView::Stream(s) => write!(f, "Stream({:?})", s.stream_type()),
2225 ValueView::AsyncPromise(p) => write!(f, "{p:?}"),
2226 ValueView::Channel(c) => write!(f, "{c:?}"),
2227 }
2228 }
2229}
2230
2231#[derive(Debug, Clone)]
2235pub struct Env {
2236 pub bindings: Rc<RefCell<SpurMap<Spur, Value>>>,
2237 pub parent: Option<Rc<Env>>,
2238 pub version: Cell<u64>,
2239}
2240
2241impl Env {
2242 pub fn new() -> Self {
2243 Env {
2244 bindings: Rc::new(RefCell::new(SpurMap::new())),
2245 parent: None,
2246 version: Cell::new(0),
2247 }
2248 }
2249
2250 pub fn with_parent(parent: Rc<Env>) -> Self {
2251 Env {
2252 bindings: Rc::new(RefCell::new(SpurMap::new())),
2253 parent: Some(parent),
2254 version: Cell::new(0),
2255 }
2256 }
2257
2258 pub fn bump_version(&self) {
2264 self.version.set(self.version.get().wrapping_add(1));
2265 }
2266
2267 pub fn get(&self, name: Spur) -> Option<Value> {
2268 if let Some(val) = self.bindings.borrow().get(&name) {
2269 Some(val.clone())
2270 } else if let Some(parent) = &self.parent {
2271 parent.get(name)
2272 } else {
2273 None
2274 }
2275 }
2276
2277 pub fn get_str(&self, name: &str) -> Option<Value> {
2278 self.get(intern(name))
2279 }
2280
2281 pub fn set(&self, name: Spur, val: Value) {
2282 self.bindings.borrow_mut().insert(name, val);
2283 self.bump_version();
2284 }
2285
2286 pub fn set_str(&self, name: &str, val: Value) {
2287 self.set(intern(name), val);
2288 }
2289
2290 pub fn update(&self, name: Spur, val: Value) {
2292 let mut bindings = self.bindings.borrow_mut();
2293 if let Some(entry) = bindings.get_mut(&name) {
2294 *entry = val;
2295 } else {
2296 bindings.insert(name, val);
2297 }
2298 drop(bindings);
2299 self.bump_version();
2300 }
2301
2302 pub fn take(&self, name: Spur) -> Option<Value> {
2304 let result = self.bindings.borrow_mut().remove(&name);
2305 if result.is_some() {
2306 self.bump_version();
2307 }
2308 result
2309 }
2310
2311 pub fn take_anywhere(&self, name: Spur) -> Option<Value> {
2313 if let Some(val) = self.bindings.borrow_mut().remove(&name) {
2314 self.bump_version();
2315 Some(val)
2316 } else if let Some(parent) = &self.parent {
2317 parent.take_anywhere(name)
2318 } else {
2319 None
2320 }
2321 }
2322
2323 pub fn set_existing(&self, name: Spur, val: Value) -> bool {
2325 let mut bindings = self.bindings.borrow_mut();
2326 if let Some(entry) = bindings.get_mut(&name) {
2327 *entry = val;
2328 drop(bindings);
2329 self.bump_version();
2330 true
2331 } else {
2332 drop(bindings);
2333 if let Some(parent) = &self.parent {
2334 parent.set_existing(name, val)
2335 } else {
2336 false
2337 }
2338 }
2339 }
2340
2341 pub fn all_names(&self) -> Vec<Spur> {
2343 let mut names: Vec<Spur> = self.bindings.borrow().keys().copied().collect();
2344 if let Some(parent) = &self.parent {
2345 names.extend(parent.all_names());
2346 }
2347 names.sort_unstable();
2348 names.dedup();
2349 names
2350 }
2351
2352 pub fn iter_bindings(&self, mut f: impl FnMut(Spur, &Value)) {
2354 let bindings = self.bindings.borrow();
2355 for (&spur, value) in bindings.iter() {
2356 f(spur, value);
2357 }
2358 }
2359
2360 pub fn get_local(&self, name: Spur) -> Option<Value> {
2362 self.bindings.borrow().get(&name).cloned()
2363 }
2364
2365 pub fn replace_bindings(&self, new_bindings: impl IntoIterator<Item = (Spur, Value)>) {
2368 let mut bindings = self.bindings.borrow_mut();
2369 bindings.clear();
2370 for (spur, value) in new_bindings {
2371 bindings.insert(spur, value);
2372 }
2373 drop(bindings);
2374 self.bump_version();
2375 }
2376}
2377
2378impl Default for Env {
2379 fn default() -> Self {
2380 Self::new()
2381 }
2382}
2383
2384#[cfg(test)]
2387#[allow(clippy::approx_constant)]
2388mod tests {
2389 use super::*;
2390
2391 #[test]
2392 fn test_size_of_value() {
2393 assert_eq!(std::mem::size_of::<Value>(), 8);
2394 }
2395
2396 #[test]
2397 fn as_index_rejects_negative() {
2398 let e = Value::int(-1).as_index("test").unwrap_err();
2399 assert!(
2400 matches!(e.inner(), SemaError::Eval(_)),
2401 "expected Eval error, got {e:?}"
2402 );
2403 assert!(e.to_string().contains("test"));
2404 }
2405
2406 #[test]
2407 fn as_index_accepts_non_negative() {
2408 assert_eq!(Value::int(0).as_index("test").unwrap(), 0);
2409 assert_eq!(Value::int(5).as_index("test").unwrap(), 5);
2410 }
2411
2412 #[test]
2413 fn as_index_rejects_non_int() {
2414 assert!(Value::string("x").as_index("test").is_err());
2415 }
2416
2417 #[test]
2418 fn test_nil() {
2419 let v = Value::nil();
2420 assert!(v.is_nil());
2421 assert!(!v.is_truthy());
2422 assert_eq!(v.type_name(), "nil");
2423 assert_eq!(format!("{v}"), "nil");
2424 }
2425
2426 #[test]
2427 fn test_bool() {
2428 let t = Value::bool(true);
2429 let f = Value::bool(false);
2430 assert!(t.is_truthy());
2431 assert!(!f.is_truthy());
2432 assert_eq!(t.as_bool(), Some(true));
2433 assert_eq!(f.as_bool(), Some(false));
2434 assert_eq!(format!("{t}"), "#t");
2435 assert_eq!(format!("{f}"), "#f");
2436 }
2437
2438 #[test]
2439 fn test_small_int() {
2440 let v = Value::int(42);
2441 assert_eq!(v.as_int(), Some(42));
2442 assert_eq!(v.type_name(), "int");
2443 assert_eq!(format!("{v}"), "42");
2444
2445 let neg = Value::int(-100);
2446 assert_eq!(neg.as_int(), Some(-100));
2447 assert_eq!(format!("{neg}"), "-100");
2448
2449 let zero = Value::int(0);
2450 assert_eq!(zero.as_int(), Some(0));
2451 }
2452
2453 #[test]
2454 fn test_small_int_boundaries() {
2455 let max = Value::int(SMALL_INT_MAX);
2456 assert_eq!(max.as_int(), Some(SMALL_INT_MAX));
2457
2458 let min = Value::int(SMALL_INT_MIN);
2459 assert_eq!(min.as_int(), Some(SMALL_INT_MIN));
2460 }
2461
2462 #[test]
2463 fn test_big_int() {
2464 let big = Value::int(i64::MAX);
2465 assert_eq!(big.as_int(), Some(i64::MAX));
2466 assert_eq!(big.type_name(), "int");
2467
2468 let big_neg = Value::int(i64::MIN);
2469 assert_eq!(big_neg.as_int(), Some(i64::MIN));
2470
2471 let just_over = Value::int(SMALL_INT_MAX + 1);
2473 assert_eq!(just_over.as_int(), Some(SMALL_INT_MAX + 1));
2474 }
2475
2476 #[test]
2477 fn test_float() {
2478 let v = Value::float(3.14);
2479 assert_eq!(v.as_float(), Some(3.14));
2480 assert_eq!(v.type_name(), "float");
2481
2482 let neg = Value::float(-0.5);
2483 assert_eq!(neg.as_float(), Some(-0.5));
2484
2485 let inf = Value::float(f64::INFINITY);
2486 assert_eq!(inf.as_float(), Some(f64::INFINITY));
2487
2488 let neg_inf = Value::float(f64::NEG_INFINITY);
2489 assert_eq!(neg_inf.as_float(), Some(f64::NEG_INFINITY));
2490 }
2491
2492 #[test]
2493 fn test_float_nan() {
2494 let nan = Value::float(f64::NAN);
2495 let f = nan.as_float().unwrap();
2496 assert!(f.is_nan());
2497 }
2498
2499 #[test]
2500 fn test_string() {
2501 let v = Value::string("hello");
2502 assert_eq!(v.as_str(), Some("hello"));
2503 assert_eq!(v.type_name(), "string");
2504 assert_eq!(format!("{v}"), "\"hello\"");
2505 }
2506
2507 #[test]
2508 fn test_symbol() {
2509 let v = Value::symbol("foo");
2510 assert!(v.as_symbol_spur().is_some());
2511 assert_eq!(v.as_symbol(), Some("foo".to_string()));
2512 assert_eq!(v.type_name(), "symbol");
2513 assert_eq!(format!("{v}"), "foo");
2514 }
2515
2516 #[test]
2517 fn test_keyword() {
2518 let v = Value::keyword("bar");
2519 assert!(v.as_keyword_spur().is_some());
2520 assert_eq!(v.as_keyword(), Some("bar".to_string()));
2521 assert_eq!(v.type_name(), "keyword");
2522 assert_eq!(format!("{v}"), ":bar");
2523 }
2524
2525 #[test]
2526 fn test_char() {
2527 let v = Value::char('λ');
2528 assert_eq!(v.as_char(), Some('λ'));
2529 assert_eq!(v.type_name(), "char");
2530 }
2531
2532 #[test]
2533 fn test_list() {
2534 let v = Value::list(vec![Value::int(1), Value::int(2), Value::int(3)]);
2535 assert_eq!(v.as_list().unwrap().len(), 3);
2536 assert_eq!(v.type_name(), "list");
2537 assert_eq!(format!("{v}"), "(1 2 3)");
2538 }
2539
2540 #[test]
2541 fn test_clone_immediate() {
2542 let v = Value::int(42);
2543 let v2 = v.clone();
2544 assert_eq!(v.as_int(), v2.as_int());
2545 }
2546
2547 #[test]
2548 fn test_clone_heap() {
2549 let v = Value::string("hello");
2550 let v2 = v.clone();
2551 assert_eq!(v.as_str(), v2.as_str());
2552 assert_eq!(format!("{v}"), format!("{v2}"));
2554 }
2555
2556 #[test]
2557 fn test_equality() {
2558 assert_eq!(Value::int(42), Value::int(42));
2559 assert_ne!(Value::int(42), Value::int(43));
2560 assert_eq!(Value::nil(), Value::nil());
2561 assert_eq!(Value::bool(true), Value::bool(true));
2562 assert_ne!(Value::bool(true), Value::bool(false));
2563 assert_eq!(Value::string("a"), Value::string("a"));
2564 assert_ne!(Value::string("a"), Value::string("b"));
2565 assert_eq!(Value::symbol("x"), Value::symbol("x"));
2566 }
2567
2568 #[test]
2569 fn record_field_names_do_not_affect_language_semantics() {
2570 use std::collections::hash_map::DefaultHasher;
2571 use std::hash::{Hash, Hasher};
2572
2573 let a = Value::record(Record {
2574 type_tag: intern("point"),
2575 field_names: vec![intern("x"), intern("y")],
2576 fields: vec![Value::int(1), Value::int(2)],
2577 });
2578 let b = Value::record(Record {
2579 type_tag: intern("point"),
2580 field_names: vec![intern("left"), intern("top")],
2581 fields: vec![Value::int(1), Value::int(2)],
2582 });
2583
2584 assert_eq!(a, b);
2585 assert_eq!(a.cmp(&b), std::cmp::Ordering::Equal);
2586 assert_eq!(format!("{a}"), "#<record point 1 2>");
2587 assert_eq!(format!("{a}"), format!("{b}"));
2588
2589 let mut a_hasher = DefaultHasher::new();
2590 a.hash(&mut a_hasher);
2591 let mut b_hasher = DefaultHasher::new();
2592 b.hash(&mut b_hasher);
2593 assert_eq!(a_hasher.finish(), b_hasher.finish());
2594 }
2595
2596 #[test]
2597 fn test_big_int_equality() {
2598 assert_eq!(Value::int(i64::MAX), Value::int(i64::MAX));
2599 assert_ne!(Value::int(i64::MAX), Value::int(i64::MIN));
2600 }
2601
2602 #[test]
2603 fn test_view_pattern_matching() {
2604 let v = Value::int(42);
2605 match v.view() {
2606 ValueView::Int(n) => assert_eq!(n, 42),
2607 _ => panic!("expected int"),
2608 }
2609
2610 let v = Value::string("hello");
2611 match v.view() {
2612 ValueView::String(s) => assert_eq!(&**s, "hello"),
2613 _ => panic!("expected string"),
2614 }
2615 }
2616
2617 #[test]
2618 fn test_env() {
2619 let env = Env::new();
2620 env.set_str("x", Value::int(42));
2621 assert_eq!(env.get_str("x"), Some(Value::int(42)));
2622 }
2623
2624 #[test]
2625 fn test_native_fn_simple() {
2626 let f = NativeFn::simple("add1", |args| Ok(args[0].clone()));
2627 let ctx = EvalContext::new();
2628 assert!((f.func)(&ctx, &[Value::int(42)]).is_ok());
2629 }
2630
2631 #[test]
2632 fn test_native_fn_with_ctx() {
2633 let f = NativeFn::with_ctx("get-depth", |ctx, _args| {
2634 Ok(Value::int(ctx.eval_depth.get() as i64))
2635 });
2636 let ctx = EvalContext::new();
2637 assert_eq!((f.func)(&ctx, &[]).unwrap(), Value::int(0));
2638 }
2639
2640 #[test]
2641 fn test_drop_doesnt_leak() {
2642 for _ in 0..10000 {
2644 let _ = Value::string("test");
2645 let _ = Value::list(vec![Value::int(1), Value::int(2)]);
2646 let _ = Value::int(i64::MAX); }
2648 }
2649
2650 #[test]
2651 fn test_is_truthy() {
2652 assert!(!Value::nil().is_truthy());
2653 assert!(!Value::bool(false).is_truthy());
2654 assert!(Value::bool(true).is_truthy());
2655 assert!(Value::int(0).is_truthy());
2656 assert!(Value::int(1).is_truthy());
2657 assert!(Value::string("").is_truthy());
2658 assert!(Value::list(vec![]).is_truthy());
2659 }
2660
2661 #[test]
2662 fn test_as_float_from_int() {
2663 assert_eq!(Value::int(42).as_float(), Some(42.0));
2664 assert_eq!(Value::float(3.14).as_float(), Some(3.14));
2665 }
2666
2667 #[test]
2668 fn test_next_gensym_unique() {
2669 let a = next_gensym("x");
2670 let b = next_gensym("x");
2671 let c = next_gensym("y");
2672 assert_ne!(a, b);
2673 assert_ne!(a, c);
2674 assert_ne!(b, c);
2675 assert!(a.starts_with("x__"));
2676 assert!(b.starts_with("x__"));
2677 assert!(c.starts_with("y__"));
2678 }
2679
2680 #[test]
2681 fn test_next_gensym_counter_does_not_panic_near_max() {
2682 GENSYM_COUNTER.with(|c| c.set(u64::MAX - 1));
2684 let a = next_gensym("z");
2685 assert!(a.contains(&(u64::MAX - 1).to_string()));
2686 let b = next_gensym("z");
2688 assert!(b.contains(&u64::MAX.to_string()));
2689 let c = next_gensym("z");
2691 assert!(c.contains("__0"));
2692 }
2693
2694 #[derive(Debug)]
2697 struct TestStream {
2698 data: RefCell<Vec<u8>>,
2699 readable: bool,
2700 writable: bool,
2701 }
2702
2703 impl TestStream {
2704 fn new(readable: bool, writable: bool) -> Self {
2705 TestStream {
2706 data: RefCell::new(Vec::new()),
2707 readable,
2708 writable,
2709 }
2710 }
2711 }
2712
2713 impl SemaStream for TestStream {
2714 fn read(&self, buf: &mut [u8]) -> Result<usize, SemaError> {
2715 let mut data = self.data.borrow_mut();
2716 let n = buf.len().min(data.len());
2717 buf[..n].copy_from_slice(&data[..n]);
2718 data.drain(..n);
2719 Ok(n)
2720 }
2721
2722 fn write(&self, data: &[u8]) -> Result<usize, SemaError> {
2723 self.data.borrow_mut().extend_from_slice(data);
2724 Ok(data.len())
2725 }
2726
2727 fn flush(&self) -> Result<(), SemaError> {
2728 Ok(())
2729 }
2730
2731 fn close(&self) -> Result<(), SemaError> {
2732 Ok(())
2733 }
2734
2735 fn available(&self) -> Result<bool, SemaError> {
2736 Ok(!self.data.borrow().is_empty())
2737 }
2738
2739 fn is_readable(&self) -> bool {
2740 self.readable
2741 }
2742
2743 fn is_writable(&self) -> bool {
2744 self.writable
2745 }
2746
2747 fn stream_type(&self) -> &'static str {
2748 "test"
2749 }
2750
2751 fn as_any(&self) -> &dyn std::any::Any {
2752 self
2753 }
2754 }
2755
2756 #[test]
2757 fn streambox_read_writes_data() {
2758 let sb = StreamBox::new(TestStream::new(true, true));
2759 sb.write(b"hello").unwrap();
2760 let mut buf = [0u8; 5];
2761 let n = sb.read(&mut buf).unwrap();
2762 assert_eq!(n, 5);
2763 assert_eq!(&buf, b"hello");
2764 }
2765
2766 #[test]
2767 fn streambox_close_prevents_read() {
2768 let sb = StreamBox::new(TestStream::new(true, true));
2769 sb.close().unwrap();
2770 let mut buf = [0u8; 5];
2771 let err = sb.read(&mut buf).unwrap_err();
2772 assert!(err.to_string().contains("closed"));
2773 }
2774
2775 #[test]
2776 fn streambox_close_prevents_write() {
2777 let sb = StreamBox::new(TestStream::new(true, true));
2778 sb.close().unwrap();
2779 let err = sb.write(b"data").unwrap_err();
2780 assert!(err.to_string().contains("closed"));
2781 }
2782
2783 #[test]
2784 fn streambox_close_prevents_flush() {
2785 let sb = StreamBox::new(TestStream::new(true, true));
2786 sb.close().unwrap();
2787 let err = sb.flush().unwrap_err();
2788 assert!(err.to_string().contains("closed"));
2789 }
2790
2791 #[test]
2792 fn streambox_double_close_is_noop() {
2793 let sb = StreamBox::new(TestStream::new(true, true));
2794 sb.close().unwrap();
2795 sb.close().unwrap(); }
2797
2798 #[test]
2799 fn streambox_is_closed() {
2800 let sb = StreamBox::new(TestStream::new(true, true));
2801 assert!(!sb.is_closed());
2802 sb.close().unwrap();
2803 assert!(sb.is_closed());
2804 }
2805
2806 #[test]
2807 fn streambox_is_readable() {
2808 let sb = StreamBox::new(TestStream::new(true, false));
2809 assert!(sb.is_readable());
2810 sb.close().unwrap();
2811 assert!(!sb.is_readable());
2812 }
2813
2814 #[test]
2815 fn streambox_is_writable() {
2816 let sb = StreamBox::new(TestStream::new(false, true));
2817 assert!(sb.is_writable());
2818 sb.close().unwrap();
2819 assert!(!sb.is_writable());
2820 }
2821
2822 #[test]
2823 fn streambox_available_when_closed() {
2824 let sb = StreamBox::new(TestStream::new(true, true));
2825 sb.close().unwrap();
2826 assert!(!sb.available().unwrap());
2827 }
2828
2829 #[test]
2830 fn streambox_stream_type() {
2831 let sb = StreamBox::new(TestStream::new(true, true));
2832 assert_eq!(sb.stream_type(), "test");
2833 }
2834}