Skip to main content

elly_core/
value.rs

1//! Runtime [`Value`] and payload types: [`ObjectData`] and [`HostFn`].
2//! Includes value equality, hashing, and human-readable rendering. Split from the
3//! evaluator, which drives these via `apply1`/`apply_n` and owns the
4//! environment types ([`EnvNode`], [`Raised`]); the realm is [`Ctx`].
5
6use alloc::boxed::Box;
7use alloc::rc::Rc;
8use alloc::string::{String, ToString};
9use alloc::vec::Vec;
10use core::hash::{Hash, Hasher};
11
12use num_bigint::BigInt;
13use rpds::{HashTrieMap, Vector};
14
15use crate::code::{json_str, push_sym, Text};
16use crate::code::{ChunkId, LambdaId};
17use crate::sym::Sym;
18
19use super::{Builtin, Ctx, Env, EnvNode, EnvRef, Raised};
20use crate::eval::iter::Iter;
21
22/// An object: a payload and the prototype that defines its type.
23/// A [`Value::Object`] is an `Rc` pointer to `ObjectData`.
24///
25/// `proto` is the [`Module`](EnvNode::Module) terminal that is the instance; methods
26/// dispatched on the object run in this environment. This is also the handle
27/// used by [`Value::Iota`]'s `home`.
28///
29/// `data` is a single-slot payload. Records with named fields are not yet implemented;
30/// maps are the current idiom. Only the module's own code can access this via
31/// [`__value`](crate::HomeLeaf::Value).
32#[derive(Debug)]
33pub struct ObjectData {
34    pub(crate) proto: EnvRef,
35    pub(crate) data: Value,
36}
37
38impl ObjectData {
39    /// The object's prototype, as the module value it is.
40    pub fn proto(&self) -> Value {
41        Value::Module(self.proto.clone())
42    }
43
44    /// The object's payload. Public to Rust because a debugger and an embedding
45    /// host sit outside the language's module scope; no *builtin* hands it out,
46    /// so Elly code cannot reach it except through its own module's `__value`.
47    pub fn data(&self) -> &Value {
48        &self.data
49    }
50}
51
52/// A runtime value.
53///
54/// On 64-bit targets `Value` is aligned to 16 bytes: it is already 32 bytes
55/// wide, so this costs it nothing, and its 16-byte halves never straddle a
56/// cache line. The `EnvNode` cons cell grows from 40 to 48 bytes (its `Rc`
57/// allocation from 56 to 64, which the system allocator rounds 56 up to
58/// anyway), for 3–7% on the environment-heavy benches. On wasm32 `Value` is 24
59/// bytes, and the alignment would pad it to 32 and cost 5–16%, so it is left off.
60#[derive(Debug, Clone)]
61#[cfg_attr(target_pointer_width = "64", repr(align(16)))]
62pub enum Value {
63    /// Machine-word integer: the canonical representation for any integer fitting
64    /// in `i64`. Stored inline to avoid allocation on common arithmetic paths.
65    /// The invariant "an integer is [`Value::BigInt`] iff it does not fit `i64`"
66    /// ensures well-defined equality and hashing.
67    I64(i64),
68    /// Arbitrary-precision integer for magnitudes outside `i64`. Stored behind
69    /// an `Rc` to keep `Value` width small and make cloning a refcount bump.
70    /// Always `|n| > i64::MAX` per the canonical invariant.
71    BigInt(Rc<BigInt>),
72    /// A symbol (its text stored without the leading dot), interned in the
73    /// realm as a [`Sym`]. Rendered with a leading dot.
74    Symbol(Sym),
75    /// An owned, immutable UTF-8 string ([`Text`]). Equality and order follow
76    /// Rust's `&str` (lexicographic byte order). Rendered quoted and re-escaped.
77    Str(Text),
78    /// The unit value `()`. A nullary variant that does not widen `Value`.
79    /// Distinct from the empty list.
80    Unit,
81    /// A runtime list backed by an immutable `rpds::Vector` (O(log n) access,
82    /// cheap structural-sharing clone/append). The empty list is a `List` of
83    /// arity zero, not `Unit`.
84    List(Vector<Value>),
85    /// A closure capturing its environment over the code of `lambda` in
86    /// `chunk`. `id` is a per-runtime unique identity minted at creation;
87    /// closures compare by identity rather than structure. `applied` tracks
88    /// bound parameters of the lambda's `arity`, so the remaining ones are the
89    /// head's from `applied` on. Partial application extends `env` and
90    /// increments `applied`; the code is not touched.
91    ///
92    /// `arity` copies the head's length, so that [`remaining_arity`] needs no
93    /// [`Ctx`] to read the code.
94    ///
95    /// [`remaining_arity`]: Value::remaining_arity
96    Closure {
97        id: u64,
98        chunk: ChunkId,
99        lambda: LambdaId,
100        applied: u8,
101        arity: u8,
102        env: Env,
103    },
104    /// An immutable, persistent, unordered map from keys to values, backed by
105    /// `rpds::HashTrieMap`. Keys are identified by structural value equality.
106    /// See `docs/elly-spec.md` § maps.
107    Map(HashTrieMap<Value, Value>),
108    /// A partially-applied builtin: a native `__…` operation and its
109    /// gathered arguments. Invoked when `args.len()` reaches the op's arity.
110    Builtin { op: Builtin, args: Vec<Value> },
111    /// A partially-applied host function: a callback provided by the embedder
112    /// ([`HostFn`]) and its gathered arguments. This is the primary FFI boundary
113    /// in the calling direction.
114    ///
115    /// It is a `Value` rather than a node of code so it retains meaning regardless of
116    /// the context it is handed. Identity is the `Rc` pointer plus applied
117    /// arguments.
118    ///
119    /// Applied arguments use `Box<[Value]>` instead of `Vec` to keep `Value`
120    /// width at four words, as pinned by `tests/sizes.rs`. Both are one
121    /// allocation per curried step.
122    HostFn {
123        code: Rc<HostFn>,
124        args: Box<[Value]>,
125    },
126    /// A module instance: the module's [`Module`](EnvNode::Module) terminal.
127    /// The value is the terminal itself, ensuring the module's code and its
128    /// instantiation environment are linked. Applying a symbol materializes
129    /// the item. Identity is the `Rc` pointer.
130    Module(EnvRef),
131    /// An iota: an atomic identity declared with `const`. Equal only to itself.
132    /// Identity is the pair (instance, position), where `home` is the instance's
133    /// [`Module`](EnvNode::Module) terminal and `index` is the position in
134    /// the module's iotas. Derived upon reference; two references to the
135    /// same iota of one instance are equal.
136    Iota { home: EnvRef, index: u32 },
137    /// An object: a payload plus the prototype module defining its type
138    /// (see [`ObjectData`]). Built by the [`__new`](crate::HomeLeaf::New) leaf
139    /// of the owning module. Applying a symbol dispatches the name by materializing
140    /// it from the prototype and applying it to the object. Compared by payload
141    /// contents and prototype identity.
142    Object(Rc<ObjectData>),
143    /// An iterator: an immutable cursor over a source (see [`Iter`]). One
144    /// pointer, like [`Object`](Value::Object). Compared by identity: comparing
145    /// what two iterators hold is a loop, and loops are explicit (`Iter.eq`).
146    Iter(Rc<Iter>),
147}
148
149/// Structural value equality used by `__eq`. Data compares structurally
150/// (integers mathematically, symbols/strings by text, lists elementwise, maps by
151/// content); callables compare by identity (builtins by operation and arguments,
152/// closures by unique id). Different variants are never equal. Total order is not
153/// defined; `<` / `>` only compare `Int` / `Str`.
154impl PartialEq for Value {
155    fn eq(&self, other: &Self) -> bool {
156        match (self, other) {
157            (Value::I64(a), Value::I64(b)) => a == b,
158            (Value::BigInt(a), Value::BigInt(b)) => a == b,
159            // An `I64` and a `BigInt` never compare equal: by the canonical
160            // invariant they partition the integers (a `BigInt` never fits `i64`),
161            // so they cannot denote the same number.
162            (Value::Symbol(a), Value::Symbol(b)) => a == b,
163            (Value::Str(a), Value::Str(b)) => a == b,
164            // Unit is a singleton — one value, so any two are equal.
165            (Value::Unit, Value::Unit) => true,
166            (Value::List(a), Value::List(b)) => a == b,
167            // `HashTrieMap`'s own `PartialEq` is content-based (order-independent).
168            (Value::Map(a), Value::Map(b)) => a == b,
169            // Same operation and equal applied arguments.
170            (Value::Builtin { op: o1, args: a1 }, Value::Builtin { op: o2, args: a2 }) => {
171                o1 == o2 && a1 == a2
172            }
173            // The same reading for a host callback, with the allocation standing
174            // in for the operation: a `HostFn` has no structure to compare, so
175            // two of one name are two functions.
176            (
177                Value::HostFn {
178                    code: c1, args: a1, ..
179                },
180                Value::HostFn {
181                    code: c2, args: a2, ..
182                },
183            ) => Rc::ptr_eq(c1, c2) && a1 == a2,
184            (Value::Closure { id: i1, .. }, Value::Closure { id: i2, .. }) => i1 == i2,
185            // A module value is its instance's identity: the terminal's `Rc`
186            // pointer, not the item contents (mirrors the closure "compare by
187            // identity" precedent).
188            (Value::Module(a), Value::Module(b)) => EnvRef::ptr_eq(a, b),
189            // An iota is the instance it was declared by plus its position, so
190            // two iotas of one instance differ and one iota of two instantiations
191            // does too.
192            (
193                Value::Iota {
194                    home: a, index: i, ..
195                },
196                Value::Iota {
197                    home: b, index: j, ..
198                },
199            ) => i == j && EnvRef::ptr_eq(a, b),
200            // An object is its prototype by *identity* and its payload by
201            // *contents* — the nominal/structural mix objects are for. The payload
202            // half is what makes two accesses of one data item compare equal, and
203            // what lets an object be a map key.
204            (Value::Object(a), Value::Object(b)) => {
205                EnvRef::ptr_eq(&a.proto, &b.proto) && a.data == b.data
206            }
207            (Value::Iter(a), Value::Iter(b)) => Rc::ptr_eq(a, b),
208            _ => false,
209        }
210    }
211}
212
213impl Eq for Value {}
214
215/// A `Hash` consistent with structural `PartialEq`. A per-variant discriminant
216/// prevents collisions between different types (e.g. symbol `.0` and integer `0`).
217/// `Map` keys hash order-independently by summing the hash of entries.
218impl Hash for Value {
219    fn hash<H: Hasher>(&self, state: &mut H) {
220        core::mem::discriminant(self).hash(state);
221        match self {
222            Value::I64(n) => n.hash(state),
223            Value::BigInt(n) => n.hash(state),
224            Value::Symbol(s) => s.hash(state),
225            Value::Str(s) => s.hash(state),
226            // Unit carries no payload; the discriminant above is its whole hash.
227            Value::Unit => {}
228            Value::List(vs) => {
229                for v in vs.iter() {
230                    v.hash(state);
231                }
232            }
233            Value::Map(m) => {
234                let mut acc: u64 = 0;
235                for (k, v) in m.iter() {
236                    let mut h = FnvHasher::new();
237                    k.hash(&mut h);
238                    v.hash(&mut h);
239                    acc = acc.wrapping_add(h.finish());
240                }
241                acc.hash(state);
242            }
243            Value::Builtin { op, args } => {
244                op.hash(state);
245                for a in args {
246                    a.hash(state);
247                }
248            }
249            Value::HostFn { code, args } => {
250                (Rc::as_ptr(code) as usize).hash(state);
251                for a in args {
252                    a.hash(state);
253                }
254            }
255            Value::Closure { id, .. } => id.hash(state),
256            // Hash by the same identity used for equality: the terminal's pointer.
257            Value::Module(home) => (EnvRef::as_ptr(home) as usize).hash(state),
258            Value::Iota { home, index } => {
259                (EnvRef::as_ptr(home) as usize).hash(state);
260                index.hash(state);
261            }
262            // Mirrors the equality above: the prototype's pointer, the payload's
263            // contents.
264            Value::Object(obj) => {
265                (EnvRef::as_ptr(&obj.proto) as usize).hash(state);
266                obj.data.hash(state);
267            }
268            // The same identity as equality: the iterator's pointer.
269            Value::Iter(it) => (Rc::as_ptr(it) as usize).hash(state),
270        }
271    }
272}
273
274/// A deterministic no_std FNV-1a `Hasher` used for order-independent map
275/// hashing (see `impl Hash for Value`) and by the symbol store's index. Not the
276/// hasher used by `HashTrieMap`.
277struct FnvHasher(u64);
278
279/// The FNV-1a hash of `bytes`.
280pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
281    let mut h = FnvHasher::new();
282    h.write(bytes);
283    h.finish()
284}
285
286impl FnvHasher {
287    fn new() -> Self {
288        FnvHasher(0xcbf2_9ce4_8422_2325)
289    }
290}
291
292impl Hasher for FnvHasher {
293    fn finish(&self) -> u64 {
294        self.0
295    }
296    fn write(&mut self, bytes: &[u8]) {
297        for &b in bytes {
298            self.0 ^= u64::from(b);
299            self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
300        }
301    }
302}
303
304/// A host function: a native callback provided by the embedder, behind the `Rc`
305/// a [`Value::HostFn`] carries.
306///
307/// It includes a name, arity, and code. The evaluator gathers arguments according
308/// to `arity` before calling the function, making it strict and curried.
309///
310/// `Ctx` is passed to allow the callback to call Elly functions ([`apply_with`](crate::apply_with))
311/// using the same ID source, preventing identity collisions for minted closures.
312///
313/// Arity must be at least 1; zero-argument constants are supplied as values.
314pub struct HostFn {
315    pub(crate) name: Text,
316    pub(crate) arity: usize,
317    pub(crate) f: Box<HostCall>,
318}
319
320/// The contract a host callback signs: a whole call's arguments — exactly
321/// [`arity`](HostFn::arity) of them, since the evaluator gathers before it fires
322/// — plus the [`Ctx`], answering a value or a [`Raised`].
323pub type HostCall = dyn Fn(&[Value], &Ctx) -> Result<Value, Raised>;
324
325impl HostFn {
326    /// A host function taking `arity` arguments.
327    ///
328    /// Name is for diagnostics; identity is the allocation. Panics on `arity == 0`.
329    pub fn new(
330        name: impl Into<Text>,
331        arity: usize,
332        f: impl Fn(&[Value], &Ctx) -> Result<Value, Raised> + 'static,
333    ) -> HostFn {
334        assert!(arity > 0, "a host function takes at least one argument");
335        HostFn {
336            name: name.into(),
337            arity,
338            f: Box::new(f),
339        }
340    }
341
342    /// The name the function renders under.
343    pub fn name(&self) -> &Text {
344        &self.name
345    }
346
347    /// How many arguments it is called with.
348    pub fn arity(&self) -> usize {
349        self.arity
350    }
351}
352
353/// The callback is not `Debug`, so the derive cannot apply; the shape a
354/// `Value::HostFn` shows is its name and arity, which is what identifies it in a
355/// dump anyway.
356impl core::fmt::Debug for HostFn {
357    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
358        f.debug_struct("HostFn")
359            .field("name", &self.name)
360            .field("arity", &self.arity)
361            .finish_non_exhaustive()
362    }
363}
364
365impl Value {
366    /// Builds an integer value from a `BigInt`, demoting to [`Value::I64`] if it
367    /// fits. This maintains the canonical invariant that a `BigInt` is used only
368    /// when the value does not fit `i64`, ensuring consistent equality and hashing.
369    pub fn from_bigint(n: BigInt) -> Value {
370        match i64::try_from(&n) {
371            Ok(i) => Value::I64(i),
372            Err(_) => Value::BigInt(Rc::new(n)),
373        }
374    }
375
376    /// [`from_bigint`](Value::from_bigint) for a `BigInt` reference. Demotion
377    /// to `i64` is decided before cloning to avoid unnecessary allocations
378    /// for literals fitting in `i64`.
379    pub fn from_bigint_ref(n: &BigInt) -> Value {
380        match i64::try_from(n) {
381            Ok(i) => Value::I64(i),
382            Err(_) => Value::BigInt(Rc::new(n.clone())),
383        }
384    }
385
386    /// An unsigned count as an integer, wide if it does not fit `i64`.
387    pub(crate) fn from_u64(n: u64) -> Value {
388        match i64::try_from(n) {
389            Ok(n) => Value::I64(n),
390            Err(_) => Value::from_bigint(BigInt::from(n)),
391        }
392    }
393
394    /// The two-element list `[a, b]`: a map entry, or an index and an element.
395    pub(crate) fn pair(a: Value, b: Value) -> Value {
396        Value::List(Vector::new().push_back(a).push_back(b))
397    }
398
399    /// Compares two integers mathematically, or `None` if either is not one.
400    pub(crate) fn int_cmp(&self, other: &Value) -> Option<core::cmp::Ordering> {
401        match (self, other) {
402            (Value::I64(a), Value::I64(b)) => Some(a.cmp(b)),
403            _ => Some(self.to_bigint()?.cmp(&other.to_bigint()?)),
404        }
405    }
406
407    /// The integer one above this one, or `None` if this is not an integer.
408    pub(crate) fn int_succ(&self) -> Option<Value> {
409        match self {
410            Value::I64(n) => Some(match n.checked_add(1) {
411                Some(m) => Value::I64(m),
412                None => Value::from_bigint(BigInt::from(*n) + 1),
413            }),
414            _ => Some(Value::from_bigint(self.to_bigint()? + 1)),
415        }
416    }
417
418    /// `self - other` over two integers, or `None` if either is not one.
419    pub(crate) fn int_sub(&self, other: &Value) -> Option<Value> {
420        if let (Value::I64(a), Value::I64(b)) = (self, other) {
421            if let Some(d) = a.checked_sub(*b) {
422                return Some(Value::I64(d));
423            }
424        }
425        Some(Value::from_bigint(self.to_bigint()? - other.to_bigint()?))
426    }
427
428    /// An integer as the character with that codepoint: `.not_an_int` for a
429    /// non-integer, `.bad_codepoint` for one that is not a Unicode scalar.
430    pub(crate) fn to_codepoint(&self) -> Result<char, Raised> {
431        let code = match self {
432            Value::I64(x) => u32::try_from(*x).ok(),
433            Value::BigInt(n) => u32::try_from(&**n).ok(),
434            _ => return Err(Raised::symbol(Sym::NOT_AN_INT)),
435        };
436        code.and_then(char::from_u32)
437            .ok_or_else(|| Raised::symbol(Sym::BAD_CODEPOINT))
438    }
439
440    /// An integer as a `BigInt`, or `None` if this is not an integer.
441    fn to_bigint(&self) -> Option<BigInt> {
442        match self {
443            Value::I64(n) => Some(BigInt::from(*n)),
444            Value::BigInt(n) => Some((**n).clone()),
445            _ => None,
446        }
447    }
448
449    /// Creates a `Value::HostFn` from a callback. Unapplied, so the first
450    /// argument begins the currying process. Panics on `arity == 0`.
451    pub fn host_fn(
452        name: impl Into<Text>,
453        arity: usize,
454        f: impl Fn(&[Value], &Ctx) -> Result<Value, Raised> + 'static,
455    ) -> Value {
456        Value::HostFn {
457            code: Rc::new(HostFn::new(name, arity, f)),
458            args: Box::new([]),
459        }
460    }
461
462    /// Creates a list value from its elements. Hides the backing `rpds::Vector`
463    /// to avoid version/feature mismatches between the core and the host.
464    pub fn list(elems: impl IntoIterator<Item = Value>) -> Value {
465        Value::List(elems.into_iter().collect())
466    }
467
468    /// Creates a map value from its entries; later entries overwrite equal keys.
469    /// Hides `rpds` implementation details.
470    pub fn map(entries: impl IntoIterator<Item = (Value, Value)>) -> Value {
471        let mut m = HashTrieMap::new();
472        for (k, v) in entries {
473            m.insert_mut(k, v);
474        }
475        Value::Map(m)
476    }
477
478    /// Returns the elements of a list value, or `None` otherwise. Hides
479    /// `rpds` implementation details.
480    pub fn list_items(&self) -> Option<impl ExactSizeIterator<Item = &Value>> {
481        match self {
482            Value::List(elems) => Some(elems.iter()),
483            _ => None,
484        }
485    }
486
487    /// Returns the number of arguments a function-shaped value needs before it
488    /// runs. `None` for non-functions, including applicable values like lists
489    /// or modules (which use projection, not calls).
490    ///
491    /// Runners use this to detect under-application (see `docs/done/2026-08-14_elly-run.md`).
492    pub fn remaining_arity(&self) -> Option<usize> {
493        match self {
494            Value::Closure { applied, arity, .. } => Some(usize::from(arity - applied)),
495            Value::Builtin { op, args } => Some(op.arity() - args.len()),
496            Value::HostFn { code, args } => Some(code.arity - args.len()),
497            _ => None,
498        }
499    }
500
501    /// The item names of a [`Value::Module`], sorted by `Sym`, or `None` for
502    /// any other value. Locals and iotas are not items.
503    pub fn item_names(&self, ctx: &Ctx) -> Option<Vec<Sym>> {
504        match self {
505            Value::Module(home) => match **home {
506                EnvNode::Module { chunk, module, .. } => {
507                    Some(ctx.chunk(chunk).item_names(module).collect())
508                }
509                _ => unreachable!("a module value always holds a module terminal"),
510            },
511            _ => None,
512        }
513    }
514
515    /// Returns the [`ObjectData`] of a [`Value::Object`], or `None`. Provides
516    /// access to the payload and prototype.
517    pub fn object_data(&self) -> Option<&Rc<ObjectData>> {
518        match self {
519            Value::Object(obj) => Some(obj),
520            _ => None,
521        }
522    }
523
524    /// Returns a human-readable rendering for golden tests.
525    pub fn to_display(&self, ctx: &Ctx) -> String {
526        let mut out = String::new();
527        self.write_display(&mut out, ctx);
528        out
529    }
530
531    fn write_display(&self, out: &mut String, ctx: &Ctx) {
532        match self {
533            Value::I64(n) => out.push_str(&n.to_string()),
534            Value::BigInt(n) => out.push_str(&n.to_string()),
535            Value::Symbol(s) => {
536                out.push('.');
537                push_sym(*s, out, ctx);
538            }
539            // A string renders as a quoted, re-escaped literal (`"foo"`),
540            // distinguishing it from symbols and names.
541            Value::Str(s) => json_str(s, out),
542            // Unit renders `()`, distinct from the empty list `[]`.
543            Value::Unit => out.push_str("()"),
544            // Lists render with brackets (`[]`, `[.a]`, `[.a, .b]`).
545            Value::List(vs) => {
546                out.push('[');
547                for (i, v) in vs.iter().enumerate() {
548                    if i > 0 {
549                        out.push_str(", ");
550                    }
551                    v.write_display(out, ctx);
552                }
553                out.push(']');
554            }
555            // Maps render sorted by rendered key text (ties broken by value)
556            // for stable dumps: `{}` or `{ .a: 1, .b: 2 }`.
557            Value::Map(m) => {
558                if m.is_empty() {
559                    out.push_str("{}");
560                } else {
561                    let mut entries: Vec<(String, String)> = m
562                        .iter()
563                        .map(|(k, v)| {
564                            let mut ks = String::new();
565                            k.write_display(&mut ks, ctx);
566                            let mut vs = String::new();
567                            v.write_display(&mut vs, ctx);
568                            (ks, vs)
569                        })
570                        .collect();
571                    entries.sort();
572                    out.push('{');
573                    for (i, (ks, vs)) in entries.iter().enumerate() {
574                        out.push_str(if i > 0 { ", " } else { " " });
575                        out.push_str(ks);
576                        out.push_str(": ");
577                        out.push_str(vs);
578                    }
579                    out.push_str(" }");
580                }
581            }
582            Value::Closure { .. } => out.push_str("<closure>"),
583            Value::Builtin { op, .. } => {
584                out.push_str("<builtin ");
585                out.push_str(op.name());
586                out.push('>');
587            }
588            // Host functions render by name and arity.
589            Value::HostFn { code, .. } => {
590                out.push_str("<hostfn ");
591                out.push_str(code.name.as_str());
592                out.push('>');
593            }
594            Value::Module(_) => out.push_str("<module>"),
595            // Iotas render as `<const .name>`. The module instance is not
596            // named to avoid dependence on host-defined resolver paths.
597            Value::Iota { home, index } => {
598                out.push_str("<const .");
599                if let EnvNode::Module { chunk, module, .. } = **home {
600                    let name = ctx.chunk(chunk).iota(module, *index);
601                    if let Some(name) = name {
602                        push_sym(name, out, ctx);
603                    }
604                }
605                out.push('>');
606            }
607            // Objects render as `<object payload>`. The prototype is not
608            // named for the same reason as modules. The payload is shown to support
609            // debugging by hosts.
610            Value::Object(obj) => {
611                out.push_str("<object ");
612                obj.data.write_display(out, ctx);
613                out.push('>');
614            }
615            // An iterator renders opaquely: showing its elements would read
616            // them, and reading a loop runs it.
617            Value::Iter(_) => out.push_str("<iter>"),
618        }
619    }
620}