harn-vm 0.8.113

Async bytecode virtual machine for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::{future::Future, pin::Pin};

use crate::harness::VmHarness;
use crate::mcp::VmMcpClientHandle;
use crate::BuiltinId;

use super::{
    VmAtomicHandle, VmChannelHandle, VmClosure, VmError, VmGenerator, VmRange, VmRngHandle,
    VmStream, VmSyncPermitHandle,
};

/// An async builtin function for the VM.
///
/// Receives an explicit [`crate::vm::AsyncBuiltinCtx`] handle (threaded by the
/// dispatch loop + the `#[harn_builtin]` macro) so handlers mint child VMs and
/// forward output through the ctx they were given instead of relying on hidden
/// task state.
pub type VmAsyncBuiltinFn = Arc<
    dyn Fn(
            crate::vm::AsyncBuiltinCtx,
            Vec<VmValue>,
        ) -> Pin<Box<dyn Future<Output = Result<VmValue, VmError>> + Send>>
        + Send
        + Sync,
>;

type Shared<T> = Arc<T>;

/// Backing store for [`VmValue::Dict`]: a persistent, ordered, structurally
/// shared map.
///
/// Replacing the former `BTreeMap` with `imbl::OrdMap` turns the copy-on-write
/// `Arc::make_mut` clone — performed on every dict mutation whenever the value
/// is aliased (on the stack, in another local, captured by a closure) — from an
/// O(n) deep copy of every key and entry into an O(log n) path copy. Ordering
/// and the read API (`get` / `iter` / `keys` / `values` / `contains_key` /
/// `range` / `len`) match `BTreeMap`, so dict reads are unchanged. The `Arc`
/// wrapper is retained so reference identity (`Arc::ptr_eq`) — used by the `===`
/// operator and `value_identity_key` — keeps its current semantics.
pub type DictMap = imbl::OrdMap<String, VmValue>;

/// Character count with a byte-length fast path for ASCII text.
///
/// Harn exposes string lengths as Unicode scalar counts. ASCII is one byte per
/// scalar, so cached string `count` / `len` paths can avoid a full iterator
/// scan without changing behavior for non-ASCII text.
pub fn string_char_count(text: &str) -> usize {
    if text.is_ascii() {
        text.len()
    } else {
        text.chars().count()
    }
}

/// Indexed runtime layout for a Harn struct instance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructLayout {
    struct_name: String,
    field_names: Vec<String>,
    field_indexes: HashMap<String, usize>,
}

impl StructLayout {
    pub fn new(struct_name: impl Into<String>, field_names: Vec<String>) -> Self {
        let mut deduped = Vec::with_capacity(field_names.len());
        let mut field_indexes = HashMap::with_capacity(field_names.len());
        for field_name in field_names {
            if field_indexes.contains_key(&field_name) {
                continue;
            }
            let index = deduped.len();
            field_indexes.insert(field_name.clone(), index);
            deduped.push(field_name);
        }

        Self {
            struct_name: struct_name.into(),
            field_names: deduped,
            field_indexes,
        }
    }

    pub fn from_map(struct_name: impl Into<String>, fields: &crate::value::DictMap) -> Self {
        Self::new(struct_name, fields.keys().cloned().collect())
    }

    pub fn struct_name(&self) -> &str {
        &self.struct_name
    }

    pub fn field_names(&self) -> &[String] {
        &self.field_names
    }

    pub fn field_index(&self, field_name: &str) -> Option<usize> {
        if self.field_names.len() <= 8 {
            return self
                .field_names
                .iter()
                .position(|candidate| candidate == field_name);
        }
        self.field_indexes.get(field_name).copied()
    }

    pub fn with_appended_field(&self, field_name: String) -> Self {
        if self.field_indexes.contains_key(&field_name) {
            return self.clone();
        }
        let mut field_names = self.field_names.clone();
        field_names.push(field_name);
        Self::new(self.struct_name.clone(), field_names)
    }
}

/// Runtime payload for a Harn enum variant.
#[derive(Debug, Clone)]
pub struct VmEnumVariant {
    pub enum_name: Shared<str>,
    pub variant: Shared<str>,
    pub fields: Shared<Vec<VmValue>>,
}

impl VmEnumVariant {
    pub fn has_enum_name(&self, enum_name: &str) -> bool {
        self.enum_name.as_ref() == enum_name
    }

    pub fn is_variant(&self, enum_name: &str, variant: &str) -> bool {
        self.has_enum_name(enum_name) && self.variant.as_ref() == variant
    }
}

/// Boxed payload for [`VmValue::BuiltinRefId`].
///
/// Pairs the compact [`BuiltinId`] used for direct dispatch with the builtin's
/// registered name (kept for policy checks, diagnostics, and name-keyed
/// fallback). Stored behind a `Shared` pointer in the value so the `{ id, name
/// }` pair does not widen every `VmValue` to its 24-byte footprint.
#[derive(Debug, Clone)]
pub struct VmBuiltinRefId {
    pub id: BuiltinId,
    pub name: Shared<str>,
}

/// VM runtime value.
///
/// Rare compound payloads use shared pointers so stack/local-slot traffic is
/// bounded by the common scalar and pointer-sized value shapes. The two
/// oversized inline payloads — `Range` (a 24-byte `start/end/inclusive`
/// triple) and `BuiltinRefId` (an id + `Arc<str>` name) — are boxed behind a
/// `Shared` pointer so no variant exceeds a fat pointer. That keeps `VmValue`
/// at 24 bytes (down from 32) without inflating the common `Int` / `Float` /
/// `List` / `Dict` / `String` shapes the interpreter moves on every push,
/// pop, clone, and local-slot write. Unsafe layouts such as NaN boxing or
/// tagged pointers are deliberately deferred until Harn has a stronger
/// object/heap story.
#[derive(Debug, Clone)]
pub enum VmValue {
    Int(i64),
    Float(f64),
    /// Exact base-10 decimal (96-bit mantissa, up to 28–29 significant digits)
    /// for money and other values where binary float rounding is unacceptable.
    /// Inline (`rust_decimal::Decimal` is `Copy` and 16 bytes, the same width as
    /// the existing widest variants). Constructed via the `decimal(value)`
    /// builtin; it is a distinct type from `Int`/`Float` for
    /// equality/ordering/hashing (a clean island) but promotes `Int` operands
    /// exactly in arithmetic. See `docs/src/decimal.md`.
    Decimal(rust_decimal::Decimal),
    String(Shared<str>),
    Bytes(Shared<Vec<u8>>),
    Bool(bool),
    Nil,
    List(Shared<Vec<VmValue>>),
    Dict(Shared<DictMap>),
    Closure(Shared<VmClosure>),
    /// Reference to a registered builtin function, used when a builtin name is
    /// referenced as a value (e.g. `snake_dict.rekey(snake_to_camel)`). The
    /// contained string is the builtin's registered name.
    BuiltinRef(Shared<str>),
    /// Compact builtin reference for callback positions. The boxed
    /// [`VmBuiltinRefId`] carries the id plus the name for policy,
    /// diagnostics, and fallback if the ID cannot be used. Boxed so the
    /// `{ id, name }` pair does not widen every `VmValue`.
    BuiltinRefId(Shared<VmBuiltinRefId>),
    Duration(i64),
    EnumVariant(Shared<VmEnumVariant>),
    StructInstance {
        layout: Shared<StructLayout>,
        fields: Shared<Vec<Option<VmValue>>>,
    },
    TaskHandle(Shared<str>),
    Channel(Shared<VmChannelHandle>),
    Atomic(Shared<VmAtomicHandle>),
    Rng(Shared<VmRngHandle>),
    SyncPermit(Shared<VmSyncPermitHandle>),
    McpClient(Shared<VmMcpClientHandle>),
    Set(Shared<Vec<VmValue>>),
    Generator(Shared<VmGenerator>),
    Stream(Shared<VmStream>),
    /// Lazy numeric range. Boxed behind a `Shared` pointer so its 24-byte
    /// `start/end/inclusive` payload does not set the whole-enum size; cloning
    /// a range value is then a refcount bump.
    Range(Shared<VmRange>),
    /// Lazy iterator handle. Single-pass, fused. See `crate::vm::iter::VmIter`.
    Iter(crate::vm::iter::VmIterHandle),
    /// Two-element pair value. Produced by `pair(a, b)`, yielded by the
    /// Dict iterator source, and (later) by `zip` / `enumerate` combinators.
    /// Accessed via `.first` / `.second`, and destructurable in
    /// `for (a, b) in ...` loops.
    Pair(Shared<(VmValue, VmValue)>),
    /// Capability handle threaded into `main(harness: Harness)`. The same
    /// variant carries the root handle and each typed sub-handle (`stdio`,
    /// `clock`, `fs`, `env`, `random`, `net`) so they share one value shape
    /// but stay distinguishable via `VmHarness::kind`.
    Harness(Shared<VmHarness>),
}

/// Process-wide interned `Arc<str>` for every single-byte ASCII character.
///
/// Materializing source text into per-character string values — the supported
/// idiom for cursor-style scanners (`chars`, `char_at`, `s[i]`) — would
/// otherwise heap-allocate once per character. Source files are overwhelmingly
/// ASCII, so interning the 128 single-char strings lets those paths clone a
/// cheap `Arc` (a refcount bump) instead of allocating, keeping a full-file
/// scan linear with a low constant factor.
static ASCII_CHAR_STRINGS: std::sync::LazyLock<[Arc<str>; 128]> = std::sync::LazyLock::new(|| {
    std::array::from_fn(|byte| {
        let mut buffer = [0u8; 4];
        Arc::from((byte as u8 as char).encode_utf8(&mut buffer))
    })
});

impl VmValue {
    /// Canonical `VmValue::String` constructor from anything string-like.
    ///
    /// Collapses the ubiquitous `VmValue::String(std::sync::Arc::from(..))`
    /// spelling to a single call and performs exactly one allocation via
    /// `Arc::<str>::from(&str)` regardless of whether the input is a `&str`,
    /// `String`, `&String`, or `Cow<str>`. Prefer this over hand-writing the
    /// `Arc::from` at call sites.
    pub fn string(value: impl AsRef<str>) -> Self {
        VmValue::String(Arc::from(value.as_ref()))
    }

    /// Builds a `VmValue::String` holding a single character, reusing the
    /// interned ASCII table (see [`ASCII_CHAR_STRINGS`]) so the common ASCII
    /// path does not allocate.
    pub fn char_value(ch: char) -> Self {
        if ch.is_ascii() {
            return VmValue::String(Arc::clone(&ASCII_CHAR_STRINGS[ch as usize]));
        }
        let mut buffer = [0u8; 4];
        VmValue::String(Arc::from(ch.encode_utf8(&mut buffer)))
    }

    /// Materializes a string into a `VmValue::List` of single-character string
    /// values in one linear pass. Backs both the `chars` builtin and the
    /// `.chars()` method, and is the cursor-scanner-friendly counterpart to the
    /// O(n)-per-call `substring` / slice / `s[i]` operations on a `string`.
    pub fn chars_list(text: &str) -> Self {
        VmValue::List(Shared::new(text.chars().map(VmValue::char_value).collect()))
    }

    pub fn enum_variant(
        enum_name: impl Into<Shared<str>>,
        variant: impl Into<Shared<str>>,
        fields: Vec<VmValue>,
    ) -> Self {
        VmValue::EnumVariant(Shared::new(VmEnumVariant {
            enum_name: enum_name.into(),
            variant: variant.into(),
            fields: Shared::new(fields),
        }))
    }

    pub fn task_handle(id: impl Into<Shared<str>>) -> Self {
        VmValue::TaskHandle(id.into())
    }

    /// Construct a boxed [`VmValue::Range`] from a [`VmRange`].
    pub fn range(range: VmRange) -> Self {
        VmValue::Range(Shared::new(range))
    }

    /// Construct a boxed [`VmValue::BuiltinRefId`] from its id and name.
    pub fn builtin_ref_id(id: BuiltinId, name: impl Into<Shared<str>>) -> Self {
        VmValue::BuiltinRefId(Shared::new(VmBuiltinRefId {
            id,
            name: name.into(),
        }))
    }

    /// Construct a [`VmValue::Dict`] from any iterator of `(key, value)`
    /// entries. Accepts the `BTreeMap` that most builders still assemble (it is
    /// `IntoIterator<Item = (String, VmValue)>`) and collects it into the
    /// persistent [`DictMap`], so callers keep their familiar map-building code
    /// while the stored value gains structural sharing.
    pub fn dict(entries: impl IntoIterator<Item = (String, VmValue)>) -> Self {
        VmValue::Dict(Shared::new(entries.into_iter().collect::<DictMap>()))
    }

    /// Construct a [`VmValue::Dict`] from an already-built [`DictMap`].
    pub fn dict_map(map: DictMap) -> Self {
        VmValue::Dict(Shared::new(map))
    }

    pub fn channel(handle: VmChannelHandle) -> Self {
        VmValue::Channel(Shared::new(handle))
    }

    pub fn atomic(handle: VmAtomicHandle) -> Self {
        VmValue::Atomic(Shared::new(handle))
    }

    pub fn rng(handle: VmRngHandle) -> Self {
        VmValue::Rng(Shared::new(handle))
    }

    pub fn sync_permit(handle: VmSyncPermitHandle) -> Self {
        VmValue::SyncPermit(Shared::new(handle))
    }

    pub fn mcp_client(handle: VmMcpClientHandle) -> Self {
        VmValue::McpClient(Shared::new(handle))
    }

    pub fn generator(generator: VmGenerator) -> Self {
        VmValue::Generator(Shared::new(generator))
    }

    pub fn stream(stream: VmStream) -> Self {
        VmValue::Stream(Shared::new(stream))
    }

    pub fn harness(handle: VmHarness) -> Self {
        VmValue::Harness(Shared::new(handle))
    }

    pub fn struct_instance(
        struct_name: impl Into<Shared<str>>,
        fields: crate::value::DictMap,
    ) -> Self {
        Self::struct_instance_from_map(struct_name.into().to_string(), fields)
    }

    pub fn is_truthy(&self) -> bool {
        match self {
            VmValue::Bool(b) => *b,
            VmValue::Nil => false,
            VmValue::Int(n) => *n != 0,
            VmValue::Float(n) => *n != 0.0,
            VmValue::Decimal(d) => *d != rust_decimal::Decimal::ZERO,
            VmValue::String(s) => !s.is_empty(),
            VmValue::Bytes(bytes) => !bytes.is_empty(),
            VmValue::List(l) => !l.is_empty(),
            VmValue::Dict(d) => !d.is_empty(),
            VmValue::Closure(_) => true,
            VmValue::BuiltinRef(_) => true,
            VmValue::BuiltinRefId(_) => true,
            VmValue::Duration(ms) => *ms != 0,
            VmValue::EnumVariant(_) => true,
            VmValue::StructInstance { .. } => true,
            VmValue::TaskHandle(_) => true,
            VmValue::Channel(_) => true,
            VmValue::Atomic(_) => true,
            VmValue::Rng(_) => true,
            VmValue::SyncPermit(_) => true,
            VmValue::McpClient(_) => true,
            VmValue::Set(s) => !s.is_empty(),
            VmValue::Generator(_) => true,
            VmValue::Stream(_) => true,
            // Match Python semantics: range objects are always truthy,
            // even the empty range (analogous to generators / iterators).
            VmValue::Range(_) => true,
            VmValue::Iter(_) => true,
            VmValue::Pair(_) => true,
            VmValue::Harness(_) => true,
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self {
            VmValue::String(_) => "string",
            VmValue::Bytes(_) => "bytes",
            VmValue::Int(_) => "int",
            VmValue::Float(_) => "float",
            VmValue::Decimal(_) => "decimal",
            VmValue::Bool(_) => "bool",
            VmValue::Nil => "nil",
            VmValue::List(_) => "list",
            VmValue::Dict(_) => "dict",
            VmValue::Closure(_) => "closure",
            VmValue::BuiltinRef(_) => "builtin",
            VmValue::BuiltinRefId(_) => "builtin",
            VmValue::Duration(_) => "duration",
            VmValue::EnumVariant(_) => "enum",
            VmValue::StructInstance { .. } => "struct",
            VmValue::TaskHandle(_) => "task_handle",
            VmValue::Channel(_) => "channel",
            VmValue::Atomic(_) => "atomic",
            VmValue::Rng(_) => "rng",
            VmValue::SyncPermit(_) => "sync_permit",
            VmValue::McpClient(_) => "mcp_client",
            VmValue::Set(_) => "set",
            VmValue::Generator(_) => "generator",
            VmValue::Stream(_) => "stream",
            VmValue::Range(_) => "range",
            VmValue::Iter(_) => "iter",
            VmValue::Pair(_) => "pair",
            VmValue::Harness(h) => h.type_name(),
        }
    }

    /// Borrows the string contents without allocating when the value is
    /// already a string. Non-string values are rendered with `display()`,
    /// matching the coercion callers apply at string boundaries. Hot string
    /// builtins (regex, split, contains) use this to avoid cloning the
    /// subject text on every call.
    pub fn as_str_cow(&self) -> std::borrow::Cow<'_, str> {
        match self {
            VmValue::String(s) => std::borrow::Cow::Borrowed(s),
            other => std::borrow::Cow::Owned(other.display()),
        }
    }

    pub fn struct_name(&self) -> Option<&str> {
        match self {
            VmValue::StructInstance { layout, .. } => Some(layout.struct_name()),
            _ => None,
        }
    }

    pub fn struct_field(&self, field_name: &str) -> Option<&VmValue> {
        match self {
            VmValue::StructInstance { layout, fields } => layout
                .field_index(field_name)
                .and_then(|index| fields.get(index))
                .and_then(Option::as_ref),
            _ => None,
        }
    }

    pub fn struct_fields_map(&self) -> Option<crate::value::DictMap> {
        match self {
            VmValue::StructInstance { layout, fields } => {
                Some(struct_fields_to_map(layout, fields))
            }
            _ => None,
        }
    }

    pub fn struct_instance_from_map(
        struct_name: impl Into<String>,
        fields: crate::value::DictMap,
    ) -> Self {
        let layout = Shared::new(StructLayout::from_map(struct_name, &fields));
        let slots = layout
            .field_names()
            .iter()
            .map(|name| fields.get(name).cloned())
            .collect();
        VmValue::StructInstance {
            layout,
            fields: Shared::new(slots),
        }
    }

    pub fn struct_instance_with_layout(
        struct_name: impl Into<String>,
        field_names: Vec<String>,
        field_values: crate::value::DictMap,
    ) -> Self {
        let layout = Shared::new(StructLayout::new(struct_name, field_names));
        let fields = layout
            .field_names()
            .iter()
            .map(|name| field_values.get(name).cloned())
            .collect();
        VmValue::StructInstance {
            layout,
            fields: Shared::new(fields),
        }
    }

    pub fn struct_instance_with_property(&self, field_name: &str, value: VmValue) -> Option<Self> {
        let VmValue::StructInstance { layout, fields } = self else {
            return None;
        };

        let mut new_fields = fields.as_ref().clone();
        let layout = match layout.field_index(field_name) {
            Some(index) => {
                if index >= new_fields.len() {
                    new_fields.resize(index + 1, None);
                }
                new_fields[index] = Some(value);
                Shared::clone(layout)
            }
            None => {
                let new_layout = Shared::new(layout.with_appended_field(field_name.to_string()));
                new_fields.push(Some(value));
                new_layout
            }
        };

        Some(VmValue::StructInstance {
            layout,
            fields: Shared::new(new_fields),
        })
    }

    pub fn display(&self) -> String {
        let mut out = String::new();
        self.write_display(&mut out);
        out
    }

    /// Writes the display representation directly into `out`,
    /// avoiding intermediate Vec<String> allocations for collections.
    pub fn write_display(&self, out: &mut String) {
        use std::fmt::Write;

        match self {
            VmValue::Int(n) => {
                let _ = write!(out, "{n}");
            }
            VmValue::Float(n) => {
                if *n == (*n as i64) as f64 && n.abs() < 1e15 {
                    let _ = write!(out, "{n:.1}");
                } else {
                    let _ = write!(out, "{n}");
                }
            }
            // Render the decimal at its stored scale (e.g. `1.50` stays `1.50`),
            // which is what money formatting expects. Equality normalizes scale,
            // so `1.5` and `1.50` are still equal even though they display
            // differently.
            VmValue::Decimal(d) => {
                let _ = write!(out, "{d}");
            }
            VmValue::String(s) => out.push_str(s),
            VmValue::Bytes(bytes) => {
                const MAX_PREVIEW_BYTES: usize = 32;

                out.push_str("b\"");
                for byte in bytes.iter().take(MAX_PREVIEW_BYTES) {
                    let _ = write!(out, "{byte:02x}");
                }
                if bytes.len() > MAX_PREVIEW_BYTES {
                    let _ = write!(out, "...+{}", bytes.len() - MAX_PREVIEW_BYTES);
                }
                out.push('"');
            }
            VmValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
            VmValue::Nil => out.push_str("nil"),
            VmValue::List(items) => {
                out.push('[');
                crate::value::recursion::guard_recursion(|| {
                    for (i, item) in items.iter().enumerate() {
                        if i > 0 {
                            out.push_str(", ");
                        }
                        item.write_display(out);
                    }
                });
                out.push(']');
            }
            VmValue::Dict(map) => {
                out.push('{');
                crate::value::recursion::guard_recursion(|| {
                    for (i, (k, v)) in map.iter().enumerate() {
                        if i > 0 {
                            out.push_str(", ");
                        }
                        out.push_str(k);
                        out.push_str(": ");
                        v.write_display(out);
                    }
                });
                out.push('}');
            }
            VmValue::Closure(c) => {
                let names: Vec<&str> = c.func.param_names().collect();
                let _ = write!(out, "<fn({})>", names.join(", "));
            }
            VmValue::BuiltinRef(name) => {
                let _ = write!(out, "<builtin {name}>");
            }
            VmValue::BuiltinRefId(r) => {
                let _ = write!(out, "<builtin {}>", r.name);
            }
            VmValue::Duration(ms) => {
                let sign = if *ms < 0 { "-" } else { "" };
                let abs_ms = ms.unsigned_abs();
                if abs_ms >= 604_800_000 && abs_ms % 604_800_000 == 0 {
                    let _ = write!(out, "{}{}w", sign, abs_ms / 604_800_000);
                } else if abs_ms >= 86_400_000 && abs_ms % 86_400_000 == 0 {
                    let _ = write!(out, "{}{}d", sign, abs_ms / 86_400_000);
                } else if abs_ms >= 3_600_000 && abs_ms % 3_600_000 == 0 {
                    let _ = write!(out, "{}{}h", sign, abs_ms / 3_600_000);
                } else if abs_ms >= 60_000 && abs_ms % 60_000 == 0 {
                    let _ = write!(out, "{}{}m", sign, abs_ms / 60_000);
                } else if abs_ms >= 1000 && abs_ms % 1000 == 0 {
                    let _ = write!(out, "{}{}s", sign, abs_ms / 1000);
                } else {
                    let _ = write!(out, "{sign}{abs_ms}ms");
                }
            }
            VmValue::EnumVariant(enum_variant) => {
                if enum_variant.fields.is_empty() {
                    let _ = write!(out, "{}.{}", enum_variant.enum_name, enum_variant.variant);
                } else {
                    let _ = write!(out, "{}.{}(", enum_variant.enum_name, enum_variant.variant);
                    crate::value::recursion::guard_recursion(|| {
                        for (i, v) in enum_variant.fields.iter().enumerate() {
                            if i > 0 {
                                out.push_str(", ");
                            }
                            v.write_display(out);
                        }
                    });
                    out.push(')');
                }
            }
            VmValue::StructInstance { layout, fields } => {
                let _ = write!(out, "{} {{", layout.struct_name());
                crate::value::recursion::guard_recursion(|| {
                    for (i, (k, v)) in struct_fields_to_map(layout, fields).iter().enumerate() {
                        if i > 0 {
                            out.push_str(", ");
                        }
                        out.push_str(k);
                        out.push_str(": ");
                        v.write_display(out);
                    }
                });
                out.push('}');
            }
            VmValue::TaskHandle(id) => {
                let _ = write!(out, "<task:{id}>");
            }
            VmValue::Channel(ch) => {
                let _ = write!(out, "<channel:{}>", ch.name);
            }
            VmValue::Atomic(a) => {
                let _ = write!(out, "<atomic:{}>", a.value.load(Ordering::SeqCst));
            }
            VmValue::Rng(_) => {
                out.push_str("<rng>");
            }
            VmValue::SyncPermit(p) => {
                let _ = write!(out, "<sync_permit:{}:{}>", p.kind(), p.key());
            }
            VmValue::McpClient(c) => {
                let _ = write!(out, "<mcp_client:{}>", c.name);
            }
            VmValue::Set(items) => {
                out.push_str("set(");
                crate::value::recursion::guard_recursion(|| {
                    for (i, item) in items.iter().enumerate() {
                        if i > 0 {
                            out.push_str(", ");
                        }
                        item.write_display(out);
                    }
                });
                out.push(')');
            }
            VmValue::Generator(g) => {
                if g.is_done() {
                    out.push_str("<generator (done)>");
                } else {
                    out.push_str("<generator>");
                }
            }
            VmValue::Stream(s) => {
                if s.is_done() {
                    out.push_str("<stream (done)>");
                } else {
                    out.push_str("<stream>");
                }
            }
            // Print form mirrors source syntax: `1 to 5` / `0 to 3 exclusive`.
            // `.to_list()` is the explicit path to materialize for display.
            VmValue::Range(r) => {
                let _ = write!(out, "{} to {}", r.start, r.end);
                if !r.inclusive {
                    out.push_str(" exclusive");
                }
            }
            VmValue::Iter(h) => {
                if matches!(&*h.lock(), crate::vm::iter::VmIter::Exhausted) {
                    out.push_str("<iter (exhausted)>");
                } else {
                    out.push_str("<iter>");
                }
            }
            VmValue::Harness(h) => {
                let _ = write!(out, "<{}>", h.type_name());
            }
            VmValue::Pair(p) => {
                out.push('(');
                crate::value::recursion::guard_recursion(|| {
                    p.0.write_display(out);
                    out.push_str(", ");
                    p.1.write_display(out);
                });
                out.push(')');
            }
        }
    }

    /// Get the value as a [`DictMap`] reference, if it's a Dict.
    pub fn as_dict(&self) -> Option<&DictMap> {
        if let VmValue::Dict(d) = self {
            Some(d)
        } else {
            None
        }
    }

    pub fn as_int(&self) -> Option<i64> {
        if let VmValue::Int(n) = self {
            Some(*n)
        } else {
            None
        }
    }

    pub fn as_bytes(&self) -> Option<&[u8]> {
        if let VmValue::Bytes(bytes) = self {
            Some(bytes.as_slice())
        } else {
            None
        }
    }
}

pub fn struct_fields_to_map(
    layout: &StructLayout,
    fields: &[Option<VmValue>],
) -> crate::value::DictMap {
    layout
        .field_names()
        .iter()
        .enumerate()
        .filter_map(|(index, name)| {
            fields
                .get(index)
                .and_then(Option::as_ref)
                .map(|value| (name.clone(), value.clone()))
        })
        .collect()
}

/// Sync builtin function for the VM.
pub type VmBuiltinFn =
    Arc<dyn Fn(&[VmValue], &mut String) -> Result<VmValue, VmError> + Send + Sync>;