Skip to main content

harn_vm/value/
core.rs

1use std::collections::{BTreeMap, HashMap};
2use std::rc::Rc;
3use std::sync::atomic::Ordering;
4use std::{cell::RefCell, future::Future, pin::Pin};
5
6use crate::mcp::VmMcpClientHandle;
7use crate::BuiltinId;
8
9use super::{
10    VmAtomicHandle, VmChannelHandle, VmClosure, VmError, VmGenerator, VmRange, VmRngHandle,
11    VmSyncPermitHandle,
12};
13
14/// An async builtin function for the VM.
15pub type VmAsyncBuiltinFn =
16    Rc<dyn Fn(Vec<VmValue>) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>>>>>;
17
18/// Indexed runtime layout for a Harn struct instance.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct StructLayout {
21    struct_name: String,
22    field_names: Vec<String>,
23    field_indexes: HashMap<String, usize>,
24}
25
26impl StructLayout {
27    pub fn new(struct_name: impl Into<String>, field_names: Vec<String>) -> Self {
28        let mut deduped = Vec::with_capacity(field_names.len());
29        let mut field_indexes = HashMap::with_capacity(field_names.len());
30        for field_name in field_names {
31            if field_indexes.contains_key(&field_name) {
32                continue;
33            }
34            let index = deduped.len();
35            field_indexes.insert(field_name.clone(), index);
36            deduped.push(field_name);
37        }
38
39        Self {
40            struct_name: struct_name.into(),
41            field_names: deduped,
42            field_indexes,
43        }
44    }
45
46    pub fn from_map(struct_name: impl Into<String>, fields: &BTreeMap<String, VmValue>) -> Self {
47        Self::new(struct_name, fields.keys().cloned().collect())
48    }
49
50    pub fn struct_name(&self) -> &str {
51        &self.struct_name
52    }
53
54    pub fn field_names(&self) -> &[String] {
55        &self.field_names
56    }
57
58    pub fn field_index(&self, field_name: &str) -> Option<usize> {
59        if self.field_names.len() <= 8 {
60            return self
61                .field_names
62                .iter()
63                .position(|candidate| candidate == field_name);
64        }
65        self.field_indexes.get(field_name).copied()
66    }
67
68    pub fn with_appended_field(&self, field_name: String) -> Self {
69        if self.field_indexes.contains_key(&field_name) {
70            return self.clone();
71        }
72        let mut field_names = self.field_names.clone();
73        field_names.push(field_name);
74        Self::new(self.struct_name.clone(), field_names)
75    }
76}
77
78/// VM runtime value.
79///
80/// Rare compound payloads use shared pointers so cloning or moving common
81/// values does not pay for the largest enum alternatives. Unsafe layouts such
82/// as NaN boxing or tagged pointers are deliberately deferred until Harn has a
83/// stronger object/heap story.
84#[derive(Debug, Clone)]
85pub enum VmValue {
86    Int(i64),
87    Float(f64),
88    String(Rc<str>),
89    Bytes(Rc<Vec<u8>>),
90    Bool(bool),
91    Nil,
92    List(Rc<Vec<VmValue>>),
93    Dict(Rc<BTreeMap<String, VmValue>>),
94    Closure(Rc<VmClosure>),
95    /// Reference to a registered builtin function, used when a builtin name is
96    /// referenced as a value (e.g. `snake_dict.rekey(snake_to_camel)`). The
97    /// contained string is the builtin's registered name.
98    BuiltinRef(Rc<str>),
99    /// Compact builtin reference for callback positions. Carries the name for
100    /// policy, diagnostics, and fallback if the ID cannot be used.
101    BuiltinRefId {
102        id: BuiltinId,
103        name: Rc<str>,
104    },
105    Duration(i64),
106    EnumVariant {
107        enum_name: Rc<str>,
108        variant: Rc<str>,
109        fields: Rc<Vec<VmValue>>,
110    },
111    StructInstance {
112        layout: Rc<StructLayout>,
113        fields: Rc<Vec<Option<VmValue>>>,
114    },
115    TaskHandle(String),
116    Channel(VmChannelHandle),
117    Atomic(VmAtomicHandle),
118    Rng(VmRngHandle),
119    SyncPermit(VmSyncPermitHandle),
120    McpClient(VmMcpClientHandle),
121    Set(Rc<Vec<VmValue>>),
122    Generator(VmGenerator),
123    Range(VmRange),
124    /// Lazy iterator handle. Single-pass, fused. See `crate::vm::iter::VmIter`.
125    Iter(Rc<RefCell<crate::vm::iter::VmIter>>),
126    /// Two-element pair value. Produced by `pair(a, b)`, yielded by the
127    /// Dict iterator source, and (later) by `zip` / `enumerate` combinators.
128    /// Accessed via `.first` / `.second`, and destructurable in
129    /// `for (a, b) in ...` loops.
130    Pair(Rc<(VmValue, VmValue)>),
131}
132
133impl VmValue {
134    pub fn enum_variant(
135        enum_name: impl Into<Rc<str>>,
136        variant: impl Into<Rc<str>>,
137        fields: Vec<VmValue>,
138    ) -> Self {
139        VmValue::EnumVariant {
140            enum_name: enum_name.into(),
141            variant: variant.into(),
142            fields: Rc::new(fields),
143        }
144    }
145
146    pub fn struct_instance(
147        struct_name: impl Into<Rc<str>>,
148        fields: BTreeMap<String, VmValue>,
149    ) -> Self {
150        Self::struct_instance_from_map(struct_name.into().to_string(), fields)
151    }
152
153    pub fn is_truthy(&self) -> bool {
154        match self {
155            VmValue::Bool(b) => *b,
156            VmValue::Nil => false,
157            VmValue::Int(n) => *n != 0,
158            VmValue::Float(n) => *n != 0.0,
159            VmValue::String(s) => !s.is_empty(),
160            VmValue::Bytes(bytes) => !bytes.is_empty(),
161            VmValue::List(l) => !l.is_empty(),
162            VmValue::Dict(d) => !d.is_empty(),
163            VmValue::Closure(_) => true,
164            VmValue::BuiltinRef(_) => true,
165            VmValue::BuiltinRefId { .. } => true,
166            VmValue::Duration(ms) => *ms != 0,
167            VmValue::EnumVariant { .. } => true,
168            VmValue::StructInstance { .. } => true,
169            VmValue::TaskHandle(_) => true,
170            VmValue::Channel(_) => true,
171            VmValue::Atomic(_) => true,
172            VmValue::Rng(_) => true,
173            VmValue::SyncPermit(_) => true,
174            VmValue::McpClient(_) => true,
175            VmValue::Set(s) => !s.is_empty(),
176            VmValue::Generator(_) => true,
177            // Match Python semantics: range objects are always truthy,
178            // even the empty range (analogous to generators / iterators).
179            VmValue::Range(_) => true,
180            VmValue::Iter(_) => true,
181            VmValue::Pair(_) => true,
182        }
183    }
184
185    pub fn type_name(&self) -> &'static str {
186        match self {
187            VmValue::String(_) => "string",
188            VmValue::Bytes(_) => "bytes",
189            VmValue::Int(_) => "int",
190            VmValue::Float(_) => "float",
191            VmValue::Bool(_) => "bool",
192            VmValue::Nil => "nil",
193            VmValue::List(_) => "list",
194            VmValue::Dict(_) => "dict",
195            VmValue::Closure(_) => "closure",
196            VmValue::BuiltinRef(_) => "builtin",
197            VmValue::BuiltinRefId { .. } => "builtin",
198            VmValue::Duration(_) => "duration",
199            VmValue::EnumVariant { .. } => "enum",
200            VmValue::StructInstance { .. } => "struct",
201            VmValue::TaskHandle(_) => "task_handle",
202            VmValue::Channel(_) => "channel",
203            VmValue::Atomic(_) => "atomic",
204            VmValue::Rng(_) => "rng",
205            VmValue::SyncPermit(_) => "sync_permit",
206            VmValue::McpClient(_) => "mcp_client",
207            VmValue::Set(_) => "set",
208            VmValue::Generator(_) => "generator",
209            VmValue::Range(_) => "range",
210            VmValue::Iter(_) => "iter",
211            VmValue::Pair(_) => "pair",
212        }
213    }
214
215    pub fn struct_name(&self) -> Option<&str> {
216        match self {
217            VmValue::StructInstance { layout, .. } => Some(layout.struct_name()),
218            _ => None,
219        }
220    }
221
222    pub fn struct_field(&self, field_name: &str) -> Option<&VmValue> {
223        match self {
224            VmValue::StructInstance { layout, fields } => layout
225                .field_index(field_name)
226                .and_then(|index| fields.get(index))
227                .and_then(Option::as_ref),
228            _ => None,
229        }
230    }
231
232    pub fn struct_fields_map(&self) -> Option<BTreeMap<String, VmValue>> {
233        match self {
234            VmValue::StructInstance { layout, fields } => {
235                Some(struct_fields_to_map(layout, fields))
236            }
237            _ => None,
238        }
239    }
240
241    pub fn struct_instance_from_map(
242        struct_name: impl Into<String>,
243        fields: BTreeMap<String, VmValue>,
244    ) -> Self {
245        let layout = Rc::new(StructLayout::from_map(struct_name, &fields));
246        let slots = layout
247            .field_names()
248            .iter()
249            .map(|name| fields.get(name).cloned())
250            .collect();
251        VmValue::StructInstance {
252            layout,
253            fields: Rc::new(slots),
254        }
255    }
256
257    pub fn struct_instance_with_layout(
258        struct_name: impl Into<String>,
259        field_names: Vec<String>,
260        field_values: BTreeMap<String, VmValue>,
261    ) -> Self {
262        let layout = Rc::new(StructLayout::new(struct_name, field_names));
263        let fields = layout
264            .field_names()
265            .iter()
266            .map(|name| field_values.get(name).cloned())
267            .collect();
268        VmValue::StructInstance {
269            layout,
270            fields: Rc::new(fields),
271        }
272    }
273
274    pub fn struct_instance_with_property(
275        &self,
276        field_name: String,
277        value: VmValue,
278    ) -> Option<Self> {
279        let VmValue::StructInstance { layout, fields } = self else {
280            return None;
281        };
282
283        let mut new_fields = fields.as_ref().clone();
284        let layout = match layout.field_index(&field_name) {
285            Some(index) => {
286                if index >= new_fields.len() {
287                    new_fields.resize(index + 1, None);
288                }
289                new_fields[index] = Some(value);
290                Rc::clone(layout)
291            }
292            None => {
293                let new_layout = Rc::new(layout.with_appended_field(field_name));
294                new_fields.push(Some(value));
295                new_layout
296            }
297        };
298
299        Some(VmValue::StructInstance {
300            layout,
301            fields: Rc::new(new_fields),
302        })
303    }
304
305    pub fn display(&self) -> String {
306        let mut out = String::new();
307        self.write_display(&mut out);
308        out
309    }
310
311    /// Writes the display representation directly into `out`,
312    /// avoiding intermediate Vec<String> allocations for collections.
313    pub fn write_display(&self, out: &mut String) {
314        use std::fmt::Write;
315
316        match self {
317            VmValue::Int(n) => {
318                let _ = write!(out, "{n}");
319            }
320            VmValue::Float(n) => {
321                if *n == (*n as i64) as f64 && n.abs() < 1e15 {
322                    let _ = write!(out, "{n:.1}");
323                } else {
324                    let _ = write!(out, "{n}");
325                }
326            }
327            VmValue::String(s) => out.push_str(s),
328            VmValue::Bytes(bytes) => {
329                const MAX_PREVIEW_BYTES: usize = 32;
330
331                out.push_str("b\"");
332                for byte in bytes.iter().take(MAX_PREVIEW_BYTES) {
333                    let _ = write!(out, "{byte:02x}");
334                }
335                if bytes.len() > MAX_PREVIEW_BYTES {
336                    let _ = write!(out, "...+{}", bytes.len() - MAX_PREVIEW_BYTES);
337                }
338                out.push('"');
339            }
340            VmValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
341            VmValue::Nil => out.push_str("nil"),
342            VmValue::List(items) => {
343                out.push('[');
344                for (i, item) in items.iter().enumerate() {
345                    if i > 0 {
346                        out.push_str(", ");
347                    }
348                    item.write_display(out);
349                }
350                out.push(']');
351            }
352            VmValue::Dict(map) => {
353                out.push('{');
354                for (i, (k, v)) in map.iter().enumerate() {
355                    if i > 0 {
356                        out.push_str(", ");
357                    }
358                    out.push_str(k);
359                    out.push_str(": ");
360                    v.write_display(out);
361                }
362                out.push('}');
363            }
364            VmValue::Closure(c) => {
365                let _ = write!(out, "<fn({})>", c.func.params.join(", "));
366            }
367            VmValue::BuiltinRef(name) => {
368                let _ = write!(out, "<builtin {name}>");
369            }
370            VmValue::BuiltinRefId { name, .. } => {
371                let _ = write!(out, "<builtin {name}>");
372            }
373            VmValue::Duration(ms) => {
374                let sign = if *ms < 0 { "-" } else { "" };
375                let abs_ms = ms.unsigned_abs();
376                if abs_ms >= 3_600_000 && abs_ms % 3_600_000 == 0 {
377                    let _ = write!(out, "{}{}h", sign, abs_ms / 3_600_000);
378                } else if abs_ms >= 60_000 && abs_ms % 60_000 == 0 {
379                    let _ = write!(out, "{}{}m", sign, abs_ms / 60_000);
380                } else if abs_ms >= 1000 && abs_ms % 1000 == 0 {
381                    let _ = write!(out, "{}{}s", sign, abs_ms / 1000);
382                } else {
383                    let _ = write!(out, "{}{}ms", sign, abs_ms);
384                }
385            }
386            VmValue::EnumVariant {
387                enum_name,
388                variant,
389                fields,
390            } => {
391                if fields.is_empty() {
392                    let _ = write!(out, "{enum_name}.{variant}");
393                } else {
394                    let _ = write!(out, "{enum_name}.{variant}(");
395                    for (i, v) in fields.iter().enumerate() {
396                        if i > 0 {
397                            out.push_str(", ");
398                        }
399                        v.write_display(out);
400                    }
401                    out.push(')');
402                }
403            }
404            VmValue::StructInstance { layout, fields } => {
405                let _ = write!(out, "{} {{", layout.struct_name());
406                for (i, (k, v)) in struct_fields_to_map(layout, fields).iter().enumerate() {
407                    if i > 0 {
408                        out.push_str(", ");
409                    }
410                    out.push_str(k);
411                    out.push_str(": ");
412                    v.write_display(out);
413                }
414                out.push('}');
415            }
416            VmValue::TaskHandle(id) => {
417                let _ = write!(out, "<task:{id}>");
418            }
419            VmValue::Channel(ch) => {
420                let _ = write!(out, "<channel:{}>", ch.name);
421            }
422            VmValue::Atomic(a) => {
423                let _ = write!(out, "<atomic:{}>", a.value.load(Ordering::SeqCst));
424            }
425            VmValue::Rng(_) => {
426                out.push_str("<rng>");
427            }
428            VmValue::SyncPermit(p) => {
429                let _ = write!(out, "<sync_permit:{}:{}>", p.kind(), p.key());
430            }
431            VmValue::McpClient(c) => {
432                let _ = write!(out, "<mcp_client:{}>", c.name);
433            }
434            VmValue::Set(items) => {
435                out.push_str("set(");
436                for (i, item) in items.iter().enumerate() {
437                    if i > 0 {
438                        out.push_str(", ");
439                    }
440                    item.write_display(out);
441                }
442                out.push(')');
443            }
444            VmValue::Generator(g) => {
445                if g.done.get() {
446                    out.push_str("<generator (done)>");
447                } else {
448                    out.push_str("<generator>");
449                }
450            }
451            // Print form mirrors source syntax: `1 to 5` / `0 to 3 exclusive`.
452            // `.to_list()` is the explicit path to materialize for display.
453            VmValue::Range(r) => {
454                let _ = write!(out, "{} to {}", r.start, r.end);
455                if !r.inclusive {
456                    out.push_str(" exclusive");
457                }
458            }
459            VmValue::Iter(h) => {
460                if matches!(&*h.borrow(), crate::vm::iter::VmIter::Exhausted) {
461                    out.push_str("<iter (exhausted)>");
462                } else {
463                    out.push_str("<iter>");
464                }
465            }
466            VmValue::Pair(p) => {
467                out.push('(');
468                p.0.write_display(out);
469                out.push_str(", ");
470                p.1.write_display(out);
471                out.push(')');
472            }
473        }
474    }
475
476    /// Get the value as a BTreeMap reference, if it's a Dict.
477    pub fn as_dict(&self) -> Option<&BTreeMap<String, VmValue>> {
478        if let VmValue::Dict(d) = self {
479            Some(d)
480        } else {
481            None
482        }
483    }
484
485    pub fn as_int(&self) -> Option<i64> {
486        if let VmValue::Int(n) = self {
487            Some(*n)
488        } else {
489            None
490        }
491    }
492
493    pub fn as_bytes(&self) -> Option<&[u8]> {
494        if let VmValue::Bytes(bytes) = self {
495            Some(bytes.as_slice())
496        } else {
497            None
498        }
499    }
500}
501
502pub fn struct_fields_to_map(
503    layout: &StructLayout,
504    fields: &[Option<VmValue>],
505) -> BTreeMap<String, VmValue> {
506    layout
507        .field_names()
508        .iter()
509        .enumerate()
510        .filter_map(|(index, name)| {
511            fields
512                .get(index)
513                .and_then(Option::as_ref)
514                .map(|value| (name.clone(), value.clone()))
515        })
516        .collect()
517}
518
519/// Sync builtin function for the VM.
520pub type VmBuiltinFn = Rc<dyn Fn(&[VmValue], &mut String) -> Result<VmValue, VmError>>;