README

#value package

The Starlark value system. Import connect0459/starlark/value for the Value enum, every concrete value type (StarlarkList, StarlarkDict, StarlarkSet, …), the host-side StringDict, embedder-extension helpers, and the embedder protocol traits.

#Key types

TypeDescription
ValueUnion of all Starlark values (None, Bool, Int, Float, String, Bytes, List, Tuple, Dict, Set, Range, Function, Builtin, ExtVal, …)
StarlarkStringImmutable UTF-8 string
StarlarkListMutable, freezable sequence
StarlarkDictInsertion-ordered mutable mapping
StarlarkSetInsertion-ordered mutable hash set
StarlarkRangeLazy integer range
StringDictHost-side Map[String, Value] wrapper (used as eval_expr env)
CustomValueEmbedder-defined custom type for Value::ExtVal

#Quick start

Constructing and inspecting values:

///|
test {
let n = @value.Value::new_int(42L)
let s = @value.Value::new_string("hello")
let lst = @value.Value::new_list([@value.Value::Bool(true), n])
assert_eq(n.type_name(), "int")
assert_eq(s.type_name(), "string")
assert_eq(lst.type_name(), "list")
assert_eq(n.truth(), true)
assert_eq(@value.Value::None.truth(), false)
}

Working with StarlarkList:

///|
test {
let lst = @value.StarlarkList::new([@value.Value::new_int(1L)])
let _ = lst.push(@value.Value::new_int(2L))
assert_eq(lst.length(), 2)
assert_true(lst.get(0) is Some(@value.Value::Int(_)))
lst.freeze()
assert_true(lst.is_frozen())
}

Using StringDict as an eval environment:

///|
test {
let env = @value.StringDict::new()
env.set("x", @value.Value::new_int(10L))
assert_true(env.get("x") is Some(@value.Value::Int(_)))
assert_eq(env.has("y"), false)
}

Defining a host built-in callable:

///|
test {
let add = @value.Value::new_builtin("add", fn(_ctx, args, _kw) {
match (args[0], args[1]) {
(@value.Value::Int(a), @value.Value::Int(b)) =>
Ok(@value.Value::Int(a + b))
_ => Err("expected two ints")
}
})
assert_eq(add.type_name(), "builtin_function_or_method")
}

#API reference

#Value enum

///|
pub enum Value {
None
Bool(Bool)
Int(BigInt) // arbitrary-precision integer; use `N` suffix in patterns: `42N`
Float(Double)
String(StarlarkString)
Bytes(Bytes)
List(StarlarkList)
Tuple(Array[Value])
Dict(StarlarkDict)
Set(StarlarkSet)
Range(StarlarkRange)
Function(StarlarkFunction)
Builtin(StarlarkBuiltinFunc)
BoundMethod(StarlarkBoundMethod)
Module(StarlarkModule)
StringElems(StarlarkStringElems) // str.elems()
StringCodepoints(StarlarkStringCodepoints) // str.codepoints()
BytesElems(StarlarkBytesElems) // bytes.elems()
ExtVal(CustomValue) // embedder-defined custom type
}

#Value constructors and methods

MethodSignatureDescription
Value::new_int(Int64)-> ValueConstruct an Int value
Value::new_float(Double)-> ValueConstruct a Float value
Value::new_string(String)-> ValueConstruct a String value
Value::new_list(Array[Value])-> ValueConstruct a List value
Value::new_dict()-> ValueConstruct an empty Dict value
Value::new_set()-> ValueConstruct an empty Set value
Value::new_builtin(String, (BuiltinCallCtx, Array[Value], Array[(String, Value)]) -> Result[Value, String])-> ValueConstruct a host-provided callable built-in
repr()-> Stringrepr() form (the Starlark literal)
to_str()-> Stringstr() form (unquoted for strings)
type_name()-> Stringtype() name
truth()-> BoolTruthiness for if/while/and/or
starlark_equals(Value)-> BoolStructural equality
hash()-> Result[UInt, String]Hash; Err for unhashable values
freeze()-> UnitFreeze this value (and, transitively, its contents); aborts on depth overflow
freeze_checked()-> Result[Unit, String]Like freeze but returns Err on depth overflow

Value also implements Eq.

#Value-inspection helpers

Mirrors of starlark-go's package-level helpers; errors are plain String (value-level operations carry no source position).

FunctionSignatureDescription
equal(Value, Value) -> Result[Bool, String]Structural equality (depth-capped)
len_of(Value) -> Int64Sequence length; returns -1 for non-sequences
length_of(Value) -> Result[Int64, String]Sequence length; Err for non-sequences
iterate(Value) -> Result[StarlarkIterator, String]Obtain an iterator over a Starlark iterable
number_to_int(Value) -> Int64?Convert Int or Float to Int64
as_float(Value) -> (Double, Bool)Extract Float or convert Int; second is true on success
as_string(Value) -> (String, Bool)Extract raw string from String value; second is true on success

#Depth-limited comparison

These guard against infinite recursion on cyclic data structures.

SymbolSignatureDescription
compare_limitIntDefault recursion depth for comparison (value: 10)
freeze_limitIntDefault recursion depth for Value::freeze / freeze_checked (value: 200)
hash_limitIntDefault recursion depth for Value::hash (value: 200)
equal_depth(Value, Value, Int) -> Result[Bool, String]Equality with explicit depth limit
compare_depth(String, Value, Value, Int) -> Result[Bool, String]Comparison operator ("==", "<", …) with explicit depth limit
hash_value_depth(Value, Int) -> Result[UInt, String]Hash with explicit depth limit; use inside CustomValue::with_hash_depth callbacks
compare_values(Value, Value, op? : String) -> Result[Int, String]Internal / eval-engine only — embedders should use compare_depth instead
compare_values_depth(Value, Value, Int, op? : String) -> Result[Int, String]Internal / eval-engine only — embedders should use compare_depth instead

#Depth-limited repr / str

Value::repr and Value::repr_checked cap recursive nesting at repr_limit (200) to prevent a native stack overflow on deeply-nested acyclic values. Exceeding the limit in repr_checked returns an Err; repr aborts (it is intended for contexts where the depth is already known to be safe).

repr_at_depth lets callers pass an explicit remaining-depth budget — useful for CustomValue implementations that call repr on nested values and want to share the parent's depth budget.

SymbolSignatureDescription
repr_limitIntDefault nesting budget for repr / repr_checked (value: 200)
Value::repr(Value) -> StringStarlark repr() string; aborts on depth overflow
Value::repr_checked(Value) -> Result[String, String]Like repr but returns Err on depth overflow
Value::repr_at_depth(Value, Int) -> Result[String, String]repr_checked with an explicit depth budget


#StarlarkString

MethodSignatureDescription
StarlarkString::new(String)-> StarlarkStringConstruct from a MoonBit string
StarlarkString::from_bytes(Bytes)-> StarlarkStringConstruct from raw UTF-8 bytes
raw()-> StringThe underlying MoonBit string
to_bytes()-> BytesUTF-8 byte representation
byte_len()-> IntLength in bytes
byte_at(Int)-> ByteThe i-th byte
equals(StarlarkString)-> BoolByte-wise equality


#StarlarkList

MethodDescription
StarlarkList::new(Array[Value])Construct from an array
length() -> IntNumber of elements
is_empty() -> BoolWhether the list has no elements
get(Int) -> Value?Element at index; None if out of range
at(Int) -> ValueElement at index (panics if out of range; backs list[i] syntax)
set(Int, Value) -> Result[Unit, String]Replace the element at index
push(Value) -> Result[Unit, String]Append (Err if frozen)
insert(Int, Value) -> Result[Unit, String]Insert at index
pop() -> Result[Value?, String]Remove and return the last element
pop_at(Int, String) -> Result[Value, String]Remove and return the element at index
clear() -> Result[Unit, String]Remove all elements
reverse() -> Result[Unit, String]Reverse in place
sort_by((Value, Value) -> Int) -> Result[Unit, String]Sort in place with a comparator
each((Value) -> Unit)Iterate elements
eachi((Int, Value) -> Unit)Iterate elements with index
iter() -> Iter[Value]Lazy iterator
is_frozen() -> BoolWhether the list is frozen
freeze() -> UnitFreeze the list (and transitively its values)
check_mutable(String) -> Result[Unit, String]Err if frozen or being iterated; verb names the operation


#StarlarkDict

Insertion-ordered mutable mapping; keys are any hashable Value.

MethodDescription
StarlarkDict::new()Empty dict
set(Value, Value) -> Result[Unit, String]Insert or replace
get(Value) -> Result[Value?, String]Look up by key (Err if unhashable)
contains(Value) -> Result[Bool, String]Membership test (Err if unhashable)
delete(Value) -> Result[Bool, String]Remove; returns whether present
clear() -> Result[Unit, String]Remove all entries
length() -> IntNumber of entries
keys() -> Array[Value]Keys in insertion order
each((Value, Value) -> Unit)Iterate all key–value pairs
iter() -> Iter[Value]Iterator over a snapshot of keys in insertion order
entries() -> Iter[(Value, Value)]Iterator over key–value pairs in insertion order
pop_entry(Value) -> Result[Value?, String]Remove and return the value for a key; None if absent
popitem() -> Result[(Value, Value)?, String]Remove and return the first inserted pair
is_frozen() -> BoolWhether the dict is frozen
freeze() -> UnitFreeze the dict and its contents


#StarlarkSet

Insertion-ordered mutable hash set; members are any hashable Value.

MethodDescription
StarlarkSet::new()Empty set
add(Value) -> Result[Unit, String]Add a member
contains(Value) -> Result[Bool, String]Membership test (Err if unhashable)
remove(Value) -> Result[Bool, String]Remove; returns whether present
pop_first() -> Result[Value?, String]Remove and return the first inserted member
clear() -> Result[Unit, String]Remove all members
length() -> IntNumber of members
each((Value) -> Unit)Iterate members in insertion order
iter() -> Iter[Value]Lazy iterator
is_frozen() -> BoolWhether the set is frozen
freeze() -> UnitFreeze the set and its members


#StarlarkRange

The lazy integer sequence returned by range(); not a list.

MethodSignatureDescription
StarlarkRange::new(Int64, Int64, Int64)-> StarlarkRangeConstruct from start, stop, step
start() / stop() / step()-> Int64The three range parameters
length()-> Int64Number of elements
index_at(Int64)-> Int64The value at the i-th position
contains(Int64)-> BoolMembership test


#StringDict

A Map[String, Value] wrapper for host-side string-keyed environments; the type accepted by eval_expr and exec_repl_chunk.

MethodDescription
StringDict::new()Empty map
StringDict::from_map(Map[String, Value])Wrap an existing map
set(String, Value)Add or replace a binding
get(String) -> Value?Look up by key
has(String) -> BoolTest for key presence
delete(String) -> BoolRemove; returns whether present
keys() -> Array[String]Sorted list of keys
values() -> Array[Value]All contained values
each((String, Value) -> Unit)Iterate all key-value pairs
freeze()Transitively freeze all contained values


#StarlarkFunction

A user-defined (Starlark-source) function. Obtain via Value::Function(f) pattern matching.

MethodReturnsDescription
name()StringFunction name; "<lambda>" for lambdas
position()@errors.PositionSource position of the def keyword
doc()StringDocstring (first string literal in body); "" if absent
num_params()IntTotal parameter count
num_kwonly_params()IntNumber of keyword-only parameters (after *args)
has_varargs()BoolWhether the function has a *args parameter
has_kwargs()BoolWhether the function has a **kwargs parameter
param(Int)(String, @errors.Position)Name and position of the i-th parameter
param_default(Int)Value?Default value of the i-th parameter; None if required
num_free_vars()IntNumber of captured (closure) variables
free_var(Int)(String, Value)?Name and current value of the i-th free variable
defining_module()StarlarkModule?Module that defined this function

///|
test {
let thread = @eval.Thread::new("main")
match
@eval.exec_file(
thread,
"lib.star",
"CONST = 99\ndef greet(name):\n \"\"\"Say hello.\"\"\"\n return 'hi ' + name",
@eval.Options::default(),
) {
Ok(m) =>
match m.get("greet") {
Some(@value.Value::Function(f)) => {
assert_eq(f.name(), "greet")
assert_eq(f.num_params(), 1)
assert_eq(f.doc(), "Say hello.")
match f.defining_module() {
Some(mod_ref) => assert_true(mod_ref.get("CONST") is Some(_))
None => fail("expected module")
}
}
_ => fail("expected function")
}
Err(e) => fail(e.to_string())
}
}


#String and bytes iterables

The lazy iterables returned by str.elems(), str.codepoints(), and bytes.elems(). Each appears as a dedicated Value variant and reports its own type() string.

TypeConstructorAccessorsDescription
StarlarkStringElemsnew(StarlarkString, Bool)source_string(), is_ords()str.elems(); is_ords=true yields integer ordinals, false yields one-char substrings
StarlarkStringCodepointsnew(StarlarkString, Bool)source_string(), is_ords()str.codepoints(); is_ords=true yields codepoint integers, false yields substrings
StarlarkBytesElemsnew(Bytes)raw_bytes()bytes.elems(); yields integer byte values


#StarlarkModule, StarlarkIterator, StarlarkBuiltinFunc, StarlarkBoundMethod

TypeKey methodsDescription
StarlarkModuleStarlarkModule::new(String, Map[String, Value]), name(), get(String), attr_names()Loaded module value (e.g. from load or StarlarkFunction::defining_module)
StarlarkIteratornext() -> Value?, done(), collect() -> Array[Value]Iterator returned by @value.iterate; must call done() even on early exit
StarlarkBuiltinFuncname(), receiver() -> Value?, bind_receiver(Value)Host-provided callable; build with Value::new_builtin
StarlarkBoundMethodStarlarkBoundMethod::new(Value, String), recv(), method_name()Method bound to a receiver, e.g. "abc".upper


#CustomValue and BuiltinCallCtx

CustomValue is an embedder-defined custom type that participates in the Starlark value system as Value::ExtVal(cv). Construct with CustomValue::new(repr_fn, truth_fn,type_name_fn) and attach optional protocol implementations via fluent .with_* methods: with_attrs, with_call, with_binary, with_unary, with_compare, with_contains, with_equals, with_hash, with_hash_depth, with_iterate, with_length, with_items, with_freeze, with_get_index, with_set_index, with_set_key, with_set_field, with_slice. Use with_hash_depth instead of with_hash when the value contains nested Value fields — pass the received depth to hash_value_depth so the budget is not reset. The hash callback passed to with_hash/with_hash_depth must be deterministic (same logical value produces the same hash on every call); some call paths probe a key's hash more than once without caching it, so a non-deterministic hash can produce duplicate logical entries.

BuiltinCallCtx is passed to a built-in's body so it can call back into the evaluator:

MethodSignatureDescription
BuiltinCallCtx::new((Value, Array[Value], Array[(String, Value)]) -> Result[Value, String], get_local? : (String) -> Value?)-> BuiltinCallCtxConstruct a call context with an invoke body and optional thread-local reader
invoke(Value, Array[Value], Array[(String, Value)])-> Result[Value, String]Call a Starlark callable from within the built-in
get_local(String)-> Value?Read thread-local state set on the active Thread


#Embedder protocol traits

Implement these on a host type to make it interoperate with the evaluator.

TraitMethod(s)Purpose
Containerhas(Value) -> Result[Bool, String]x in c membership
HasAttrsget_attr(String), attr_names()Attribute read (x.attr, dir(x))
HasSetFieldset_field(String, Value)Attribute write (x.attr = v)
Indexableindexable_get(Int), indexable_len()Index read (x[i])
HasSetIndex : Indexableset_index(Int, Value)Index write (x[i] = v)
Sliceable : Indexableslice(Int, Int, Int)Slicing (x[a:b:c])
Mappingmapping_get(Value), mapping_keys(), mapping_len()Dict-like key access
IterableMapping : Mappingitems()Key–value enumeration
HasBinarybinary_op(String, Value, Bool)Custom binary operators
HasUnaryunary_op(String)Custom unary operators
StarlarkComparablecompare_same_type(Value)Same-type ordering for sorted/min/max
TotallyOrderedcmp(Value)Total ordering across comparisons
Unpacker (open)unpack(Value)Per-argument coercion for @unpack.unpack_args_with

#
Container

pub trait Container {
fn has(Self, Value) -> Result[Bool, String]
}

Container protocol for the in operator. Embedders implement has on custom types to define membership semantics.

#
HasAttrs

pub trait HasAttrs {
fn get_attr(Self, String) -> Result[Value?, String]
fn attr_names(Self) -> Array[String]
}

Attribute-access protocol for custom Starlark value types. Implement this trait to support getattr, hasattr, and dir on a custom type registered as a Value::ExtVal.

#
HasBinary

pub trait HasBinary {
fn binary_op(Self, op : String, other : Value, is_left : Bool) -> Result[Value, String]?
}

HasBinary protocol for custom types that define binary operators (+, -, *, /, //, %, &, |, ^, <>, in, not in). Return Some(Ok(v)) to provide a result, Some(Err(msg)) to signal an error, or None to decline (let the evaluator try the other operand or raise a TypeError).

#
HasSetField

pub trait HasSetField {
fn set_field(Self, String, Value) -> Result[Unit, String]
}

Field-assignment protocol for custom Starlark value types. Implement this trait to support x.name = v field assignment on a custom type registered as a Value::ExtVal.

#
HasSetIndex

pub trait HasSetIndex : Indexable {
fn set_index(Self, Int, Value) -> Result[Unit, String]
}

HasSetIndex protocol for indexed sequence types that support element update (a[i] = v). The index i is already bounds-checked and adjusted for negative values before this method is called.

#
HasUnary

pub trait HasUnary {
fn unary_op(Self, op : String) -> Result[Value, String]?
}

HasUnary protocol for custom types that define unary operators (+, -, ~). Return Some(Ok(v)) to provide a result, Some(Err(msg)) to signal an error, or None to decline.

#
Indexable

pub trait Indexable {
fn indexable_get(Self, Int) -> Result[Value, String]
fn indexable_len(Self) -> Int
}

Indexable protocol for sequence types that support a[i] subscript. Allows embedders to expose custom sequences that participate in the evaluator's subscript and slice paths.

#
IterableMapping

pub trait IterableMapping : Mapping {
fn items(Self) -> Result[Array[(Value, Value)], String]
}

IterableMapping protocol for mapping types that support key enumeration and bulk key/value retrieval. Combines Mapping with an items() method that returns all key/value pairs.

#
Mapping

pub trait Mapping {
fn mapping_get(Self, Value) -> Result[Value?, String]
fn mapping_keys(Self) -> Result[Array[Value], String]
fn mapping_len(Self) -> Int
}

Mapping protocol for Dict-like types. Allows embedders to expose custom key-value stores that participate in subscript read, in membership, and iteration via the standard evaluator paths.

#
Sliceable

pub trait Sliceable : Indexable {
fn slice(Self, Int, Int, Int) -> Result[Value, String]
}

Sliceable protocol for sequence types that support the slice operator (a[start:end:step]). start, end, and step are already normalised by the evaluator (non-zero step, adjusted for sequence length).

#
StarlarkComparable

pub trait StarlarkComparable {
fn compare_same_type(Self, Value) -> Result[Int, String]
}

Total-order comparison protocol for custom Starlark value types. Implement this trait to define <, <=, >, >= on a custom type registered as a Value::ExtVal. By convention, compare_same_type is intended to be called only when both operands have the same Starlark type name, though this is not yet enforced by the evaluator. Return a negative int, zero, or positive int to indicate ordering.

#
TotallyOrdered

pub trait TotallyOrdered {
fn cmp(Self, Value) -> Int?
}

TotallyOrdered protocol for types that define a complete ordering. cmp returns a negative Int if self < other, zero if equal, or a positive Int if self > other. Return None if the two values are not comparable (e.g., different types).

#
Unpacker

pub(open) trait Unpacker {
fn unpack(Self, Value) -> Result[Unit, String]
}

Custom argument-unpacking protocol. A type implementing Unpacker defines how a single Starlark Value is validated and absorbed into the target, mirroring starlark-go's Unpacker interface. Pass implementors to unpack_args_with (in the unpack package) to give built-in functions custom per-argument coercion beyond the plain value extraction performed by unpack_args.

#
BuiltinCallCtx

pub struct BuiltinCallCtx {
// private fields
}

Context object passed to every builtin function call. Provides two capabilities: a dispatcher for invoking arbitrary Starlark callables (needed when a builtin must call back into the interpreter), and a thread-local key lookup for embedder-supplied per-call overrides (e.g. a test-injected clock).

#
BuiltinCallCtx::get_local

fn BuiltinCallCtx::get_local(self : BuiltinCallCtx, key : String) -> Value?

Reads the active thread's thread-local value for key. Used by extension builtins (e.g. time.now) that honor an embedder-provided per-thread override.

Parameters:

  • self : The call context.
  • key : The key to look up in the per-thread override store.

Returns Some(v) if the embedder has set a value for key, or None.

#
BuiltinCallCtx::invoke

fn BuiltinCallCtx::invoke(self : BuiltinCallCtx, callee : Value, args : Array[Value], kwargs : Array[(String, Value)]) -> Result[Value, String]

Invokes a Starlark callable through this context's call dispatcher.

Parameters:

  • self : The call context.
  • callee : The Starlark value to call.
  • args : Positional arguments.
  • kwargs : Keyword arguments as (name, value) pairs.

Returns Ok(result) on success, or Err with an error message.

#
BuiltinCallCtx::new

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn BuiltinCallCtx::new(call : (Value, Array[Value], Array[(String, Value)]) -> Result[Value, String], get_local? : (String) -> Value?) -> BuiltinCallCtx

Creates a BuiltinCallCtx with the given call dispatcher and optional thread-local lookup function.

Parameters:

  • call : The function used to invoke a Starlark callable; receives the callee, positional args, and keyword args.
  • get_local : An optional function to read per-thread overrides by key (defaults to always returning None).

Returns a new BuiltinCallCtx.

#
Cell

#internal(unsafe, "closure machinery; not part of the public embedding API")
pub struct Cell {
// private fields
}

A mutable box shared between a closure and the function that defines the captured variable.

A local variable captured by a nested function is promoted to a Cell: the defining frame and every capturing closure hold the same instance, so assignments are visible across all of them. None means the variable has not been assigned yet.

#
Cell::get

#internal(unsafe, "closure machinery; not part of the public embedding API")
fn Cell::get(self : Cell) -> Value?

Returns the cell's current value, or None if it has not been assigned.

#
Cell::new

#internal(unsafe, "closure machinery; not part of the public embedding API")
fn Cell::new() -> Cell

Creates an empty (unassigned) cell.

#
Cell::set

#internal(unsafe, "closure machinery; not part of the public embedding API")
fn Cell::set(self : Cell, value : Value) -> Unit

Stores value into the cell.

#
CustomValue

pub struct CustomValue {
// private fields
}

Vtable-based wrapper for embedding custom Starlark value types. Construct with CustomValue::new, then call with_* builder methods to add optional protocol support. Wrap in Value::ExtVal(cv) to produce a Value.

#
CustomValue::do_call

fn CustomValue::do_call(self : CustomValue, pos_args : Array[Value], kw_args : Array[(String, Value)]) -> Result[Value, String]?

Invokes the call callback with pos_args and kw_args, or returns None if no callback was registered (value is not callable).

Parameters:

  • self : The custom value to call.
  • pos_args : Positional arguments passed to the call.
  • kw_args : Keyword arguments passed to the call, as name-value pairs.

Returns Some(Ok(v)) with the call result, Some(Err(msg)) if the callback signals an error, or None if no call callback was registered.

#
CustomValue::do_freeze

fn CustomValue::do_freeze(self : CustomValue) -> Unit

Invokes the freeze callback if one was registered, otherwise is a no-op.

#
CustomValue::do_set_index

fn CustomValue::do_set_index(self : CustomValue, i : Int, v : Value) -> Result[Unit, String]?

Invokes the integer-index write callback for x[i] = v, or returns None if no callback was registered.

Parameters:

  • self : The custom value to write an index on.
  • i : The integer index to assign.
  • v : The value to assign at that index.

Returns Some(Ok(())) on success, Some(Err(msg)) if the callback signals an error, or None if no callback was registered.

#
CustomValue::do_set_key

fn CustomValue::do_set_key(self : CustomValue, k : Value, v : Value) -> Result[Unit, String]?

Invokes the mapping-key write callback for x[k] = v, or returns None if no callback was registered.

Parameters:

  • self : The custom value to write a key on.
  • k : The key to assign.
  • v : The value to assign at that key.

Returns Some(Ok(())) on success, Some(Err(msg)) if the callback signals an error, or None if no callback was registered.

#
CustomValue::do_slice

fn CustomValue::do_slice(self : CustomValue, start : Int, stop : Int, step : Int) -> Result[Value, String]?

Invokes the slice callback for x[start:stop:step], or returns None if no callback was registered.

Parameters:

  • self : The custom value to slice.
  • start : The normalised start index of the slice.
  • stop : The normalised stop index of the slice.
  • step : The normalised step of the slice (non-zero).

Returns Some(Ok(v)) with the sliced value, Some(Err(msg)) if the callback signals an error, or None if no callback was registered.

#
CustomValue::get_attr

fn CustomValue::get_attr(self : CustomValue, name : String) -> Result[Value?, String]

Invokes the attribute callback for name, or returns Ok(None) if no callback was registered.

Parameters:

  • self : The custom value to look up an attribute on.
  • name : The attribute name to look up.

Returns Ok(Some(v)) if the attribute exists, Ok(None) if not found or no callback was registered, or Err if the callback signals an error.

#
CustomValue::get_attr_names

fn CustomValue::get_attr_names(self : CustomValue) -> Array[String]?

Invokes the attribute-listing callback, or returns None if no callback was registered. The result is used by dir().

Returns Some(names) if an attribute-listing callback was registered, or None otherwise.

#
CustomValue::get_binary

fn CustomValue::get_binary(self : CustomValue, op : String, rhs : Value, is_left : Bool) -> Result[Value, String]?

Invokes the binary operator callback, or returns None if no callback was registered.

Parameters:

  • self : The custom value on which the operator is applied.
  • op : The operator string (e.g. "+", "-", "*", "in").
  • rhs : The right-hand operand.
  • is_left : true if this value is the left operand; false if right.

Returns Some(Ok(v)) if the callback produces a result, Some(Err(msg)) if it signals an error, or None if no callback was registered or the callback declines.

#
CustomValue::get_compare

fn CustomValue::get_compare(self : CustomValue, other : Value) -> Int?

Invokes the comparison callback against other, or returns None if no callback was registered.

Parameters:

  • self : The custom value to compare.
  • other : The value to compare against.

Returns Some(n) where n is negative, zero, or positive to indicate ordering, or None if no callback was registered or the values are not comparable.

#
CustomValue::get_contains

fn CustomValue::get_contains(self : CustomValue, v : Value) -> Result[Bool, String]?

Invokes the membership-test callback for v, or returns None if no callback was registered.

Parameters:

  • self : The custom value to test membership on.
  • v : The value to test for membership.

Returns Some(Ok(true)) if v is a member, Some(Ok(false)) if not, Some(Err(...)) if the callback signals an error, or None if no callback was registered.

#
CustomValue::get_equals

fn CustomValue::get_equals(self : CustomValue, other : Value, depth : Int) -> Result[Bool, String]

Invokes the equality callback against other with the given recursion budget, or returns Ok(false) if no callback was registered.

Parameters:

  • self : The custom value to test equality for.
  • other : The value to compare against.
  • depth : Remaining recursion budget, threaded from the caller's starlark_equals_depth invocation. Pass this value unchanged to any nested starlark_equals_depth calls inside the callback.

Returns Ok(true) if equal, Ok(false) if not equal or no callback is registered, or Err(msg) if the callback reports a comparison error.

#
CustomValue::get_hash

fn CustomValue::get_hash(self : CustomValue) -> Result[UInt, String]

Invokes the hash callback, or returns Err("unhashable type: T") if no hash callback was registered.

Returns Ok(hash) if a hash callback was registered, or Err("unhashable type: T") otherwise.

#
CustomValue::get_hash_depth

fn CustomValue::get_hash_depth(self : CustomValue, depth : Int) -> Result[UInt, String]

Invokes the depth-aware hash callback if registered, or falls back to the plain hash callback. Returns Err when the recursion budget (depth) is exhausted and no depth-aware callback is registered, to prevent the fallback from calling Value::hash (which restarts at hash_limit) inside a deeply nested traversal.

Parameters:

  • depth : Remaining recursion depth passed down from the caller.

#
CustomValue::get_index

fn CustomValue::get_index(self : CustomValue, i : Int) -> Result[Value, String]

Invokes the integer-index read callback for i, or returns Err if no callback was registered.

Parameters:

  • self : The custom value to index into.
  • i : The integer index to read.

Returns Ok(v) if the callback returns a value, or Err if no callback was registered or the callback signals an error.

#
CustomValue::get_internal_attr

fn CustomValue::get_internal_attr(self : CustomValue, name : String) -> Result[Value?, String]

Invokes the internal attribute accessor registered by with_internal_get_attr, or falls back to get_attr if none was registered. Intended for cross-value protocols that need to read implementation-private fields hidden from user-facing get_attr.

Parameters:

  • self : The custom value to look up an internal attribute on.
  • name : The attribute name to look up.

Returns Ok(Some(v)) if found, Ok(None) if absent, or Err on error.

#
CustomValue::get_items

fn CustomValue::get_items(self : CustomValue) -> Result[Array[(Value, Value)], String]?

Invokes the items callback, returning (key, value) pairs, or None if no callback was registered.

Returns Some(Ok(pairs)) with all key-value pairs, Some(Err(msg)) if the callback signals an error, or None if no callback was registered.

#
CustomValue::get_iterate

fn CustomValue::get_iterate(self : CustomValue) -> Result[StarlarkIterator, String]

Invokes the iteration callback, or returns Err("'T' object is not iterable") if no callback was registered.

Returns Ok(iterator) if an iteration callback was registered, or Err("'T' object is not iterable") otherwise.

#
CustomValue::get_length

fn CustomValue::get_length(self : CustomValue) -> Result[Int, String]

Invokes the length callback, or returns Err("len: value of type T has no len") if no callback was registered.

Returns Ok(n) if a length callback was registered, or Err("len: value of type T has no len") otherwise.

#
CustomValue::get_repr

fn CustomValue::get_repr(self : CustomValue) -> String

Invokes the repr callback, returning the repr() string of this value.

Returns the string representation of this value, as provided by repr_fn.

#
CustomValue::get_repr_depth

fn CustomValue::get_repr_depth(self : CustomValue, depth : Int) -> Result[String, String]

Invokes the depth-aware repr callback with depth, propagating the remaining recursion budget. Falls back to repr_fn() when no depth-aware callback was registered, but still returns Err when depth is exhausted to prevent the fallback from calling Value::repr() (which restarts at repr_limit) inside a deeply nested traversal.

Parameters:

  • depth : Remaining recursion depth passed down from the caller.

#
CustomValue::get_set_field

fn CustomValue::get_set_field(self : CustomValue, name : String, v : Value) -> Result[Unit, String]?

Invokes the field-assignment callback for name = v, or returns None if no callback was registered.

Parameters:

  • self : The custom value to assign a field on.
  • name : The name of the field to assign.
  • v : The value to assign.

Returns Some(Ok(())) on success, Some(Err(...)) if the callback signals an error, or None if no field-assignment callback was registered.

#
CustomValue::get_truth

fn CustomValue::get_truth(self : CustomValue) -> Bool

Invokes the truth callback, returning the Starlark truthiness of this value.

Returns the boolean truthiness of this value, as provided by truth_fn.

#
CustomValue::get_type_name

fn CustomValue::get_type_name(self : CustomValue) -> String

Invokes the type-name callback, returning the Starlark type name string.

Returns the Starlark type name of this value, as provided by type_name_fn.

#
CustomValue::get_unary

fn CustomValue::get_unary(self : CustomValue, op : String) -> Result[Value, String]?

Invokes the unary operator callback, or returns None if no callback was registered.

Parameters:

  • self : The custom value on which the operator is applied.
  • op : The operator string (e.g. "-", "+", "~", "not").

Returns Some(Ok(v)) if the callback produces a result, Some(Err(msg)) if it signals an error, or None if no callback was registered or the callback declines.

#
CustomValue::new

fn CustomValue::new(type_name_fn : () -> String, truth_fn : () -> Bool, repr_fn : () -> String) -> CustomValue

Creates a CustomValue with type-name, truthiness, and repr callbacks. All optional protocols (hash, equals, attrs, iterate, …) default to absent and can be added via with_* builder methods.

Parameters:

  • type_name_fn : Callback that returns the Starlark type name string.
  • truth_fn : Callback that returns the boolean truthiness of the value.
  • repr_fn : Callback that returns the repr() string of the value.

Returns a new CustomValue with all optional protocol slots set to absent.

#
CustomValue::with_attrs

fn CustomValue::with_attrs(self : CustomValue, get_attr_fn : (String) -> Result[Value?, String], attr_names_fn : () -> Array[String]) -> CustomValue

Attaches attribute-access and attribute-listing callbacks, enabling getattr, hasattr, and dir on this value.

Parameters:

  • self : The CustomValue to extend.
  • get_attr_fn : Callback that looks up an attribute by name.
  • attr_names_fn : Callback that returns all attribute names.

Returns a new CustomValue with both attribute callbacks registered.

#
CustomValue::with_binary

fn CustomValue::with_binary(self : CustomValue, binary_fn : (String, Value, Bool) -> Result[Value, String]?) -> CustomValue

Attaches a binary operator callback for x op y. The callback receives the operator string, the right-hand operand, and is_left (whether x is on the left). Return None to fall back to the default type-error.

Parameters:

  • self : The CustomValue to extend.
  • binary_fn : Callback invoked with the operator string, the other operand, and a flag indicating whether this value is the left operand.

Returns a new CustomValue with the binary operator callback registered.

#
CustomValue::with_call

fn CustomValue::with_call(self : CustomValue, call_fn : (Array[Value], Array[(String, Value)]) -> Result[Value, String]) -> CustomValue

Attaches a call callback, making this value callable from Starlark.

Parameters:

  • self : The CustomValue to extend.
  • call_fn : Callback invoked with positional arguments and keyword arguments when the value is called.

Returns a new CustomValue with the call callback registered.

#
CustomValue::with_compare

fn CustomValue::with_compare(self : CustomValue, compare_fn : (Value) -> Int?) -> CustomValue

Attaches a total-order comparison callback for <, <=, >, >=. The callback returns a negative int, 0, or positive int (like compare). Return None to fall back to the default type-error.

Parameters:

  • self : The CustomValue to extend.
  • compare_fn : Callback that compares this value against another, returning a negative int, zero, or positive int, or None if not comparable.

Returns a new CustomValue with the comparison callback registered.

#
CustomValue::with_contains

fn CustomValue::with_contains(self : CustomValue, contains_fn : (Value) -> Result[Bool, String]) -> CustomValue

Attaches a membership-test callback, enabling v in x on this value.

Parameters:

  • self : The CustomValue to extend.
  • contains_fn : Callback that tests whether a value is a member.

Returns a new CustomValue with the membership-test callback registered.

#
CustomValue::with_equals

fn CustomValue::with_equals(self : CustomValue, equals_fn : (Value, Int) -> Result[Bool, String]) -> CustomValue

Attaches a custom equality function. Invoked by starlark_equals and starlark_equals_depth for Value::ExtVal. Without this, two ExtVals compare unequal by default.

Parameters:

  • self : The CustomValue to extend.
  • equals_fn : Callback that tests equality against another Value and the remaining recursion budget. Returns Ok(true) if equal, Ok(false) if not, or Err(msg) if the comparison fails (e.g., recursion depth exceeded). Errors are propagated by starlark_equals_depth and squashed to false by starlark_equals. Pass the received depth to any nested starlark_equals_depth calls to compose the depth guard correctly.

Returns a new CustomValue with the equality callback registered.

#
CustomValue::with_freeze

fn CustomValue::with_freeze(self : CustomValue, freeze_fn : () -> Unit) -> CustomValue

Attaches a freeze callback invoked when this value is frozen transitively (e.g. when a containing module or dict is frozen).

Parameters:

  • self : The CustomValue to extend.
  • freeze_fn : Callback invoked when the value is transitively frozen.

Returns a new CustomValue with the freeze callback registered.

#
CustomValue::with_get_index

fn CustomValue::with_get_index(self : CustomValue, get_index_fn : (Int) -> Result[Value, String]) -> CustomValue

Attaches an integer-index read callback, enabling x[i] where i is an integer. For arbitrary-key indexing, use with_set_key.

Parameters:

  • self : The CustomValue to extend.
  • get_index_fn : Callback that returns the element at a given integer index.

Returns a new CustomValue with the integer-index read callback registered.

#
CustomValue::with_hash

fn CustomValue::with_hash(self : CustomValue, hash_fn : () -> Result[UInt, String]) -> CustomValue

Attaches a custom hash function. Invoked by starlark_hash for Value::ExtVal. Without this, the value is considered unhashable.

hash_fn must be deterministic: repeated calls for the same logical value must return the same hash for the lifetime of that value. Some call paths probe a key's hash more than once without caching it — for example, rejecting a duplicate key while building a dict literal — so a non-deterministic hash_fn can land those probes in different hash slots, silently producing a duplicate logical entry in a dict or set.

Parameters:

  • self : The CustomValue to extend.
  • hash_fn : Callback that computes and returns a hash code, or Err if the value is unhashable at runtime.

Returns a new CustomValue with the hash callback registered.

#
CustomValue::with_hash_depth

fn CustomValue::with_hash_depth(self : CustomValue, hash_depth_fn : (Int) -> Result[UInt, String]) -> CustomValue

Attaches a depth-aware hash callback. When registered, Value::hash_depth calls this instead of hash_fn, passing the remaining depth budget so field values can be hashed without restarting the counter. Use hash_value_depth (from the value package's public API) to hash nested Values while propagating depth correctly.

hash_depth_fn must be deterministic for a given depth: repeated calls with the same depth for the same logical value must return the same hash, for the same reason documented on CustomValue::with_hash.

Parameters:

  • self : The CustomValue to extend.
  • hash_depth_fn : Callback (depth: Int) -> Result[UInt, String] that hashes the value with depth remaining levels.

Returns a new CustomValue with the depth-aware hash registered.

#
CustomValue::with_internal_get_attr

fn CustomValue::with_internal_get_attr(self : CustomValue, internal_get_attr_fn : (String) -> Result[Value?, String]) -> CustomValue

Attaches an internal-only attribute accessor that bypasses user-facing access restrictions. Use this for cross-value protocols (e.g., struct equality or merge) that need to read implementation-private fields without exposing them to Starlark programs.

Parameters:

  • self : The CustomValue to extend.
  • internal_get_attr_fn : Callback that looks up an attribute by name, including implementation-private names hidden from user code.

Returns a new CustomValue with the internal attribute callback registered.

#
CustomValue::with_items

fn CustomValue::with_items(self : CustomValue, items_fn : () -> Result[Array[(Value, Value)], String]) -> CustomValue

Attaches an items callback that yields (key, value) pairs, enabling dict-like iteration over this mapping value.

Parameters:

  • self : The CustomValue to extend.
  • items_fn : Callback that returns all key-value pairs as an array.

Returns a new CustomValue with the items callback registered.

#
CustomValue::with_iterate

fn CustomValue::with_iterate(self : CustomValue, iterate_fn : () -> Result[StarlarkIterator, String]) -> CustomValue

Attaches an iteration callback, enabling for v in x and related built-ins (list, tuple, set, sorted, …) on this value.

Parameters:

  • self : The CustomValue to extend.
  • iterate_fn : Callback that creates and returns a StarlarkIterator.

Returns a new CustomValue with the iteration callback registered.

#
CustomValue::with_length

fn CustomValue::with_length(self : CustomValue, length_fn : () -> Int) -> CustomValue

Attaches a length callback, enabling len(x) on this value.

Parameters:

  • self : The CustomValue to extend.
  • length_fn : Callback that returns the number of elements.

Returns a new CustomValue with the length callback registered.

#
CustomValue::with_repr_depth

fn CustomValue::with_repr_depth(self : CustomValue, repr_depth_fn : (Int) -> Result[String, String]) -> CustomValue

Attaches a depth-aware repr callback. When registered, repr_inner calls this instead of repr_fn, passing the remaining depth budget so field values can be repr'd without restarting the counter.

Parameters:

  • self : The CustomValue to extend.
  • repr_depth_fn : Callback (depth: Int) -> Result[String, String] that renders the value with depth remaining levels.

Returns a new CustomValue with the depth-aware repr registered.

#
CustomValue::with_set_field

fn CustomValue::with_set_field(self : CustomValue, set_field_fn : (String, Value) -> Result[Unit, String]) -> CustomValue

Attaches a field-assignment callback, enabling x.name = v on this value.

Parameters:

  • self : The CustomValue to extend.
  • set_field_fn : Callback that assigns a value to a named field.

Returns a new CustomValue with the field-assignment callback registered.

#
CustomValue::with_set_index

fn CustomValue::with_set_index(self : CustomValue, set_index_fn : (Int, Value) -> Result[Unit, String]) -> CustomValue

Attaches an integer-index write callback, enabling x[i] = v where i is an integer.

Parameters:

  • self : The CustomValue to extend.
  • set_index_fn : Callback that assigns a value at a given integer index.

Returns a new CustomValue with the integer-index write callback registered.

#
CustomValue::with_set_key

fn CustomValue::with_set_key(self : CustomValue, set_key_fn : (Value, Value) -> Result[Unit, String]) -> CustomValue

Attaches a mapping-key write callback for x[k] = v, where k is any hashable Starlark value (not restricted to an integer index).

Parameters:

  • self : The CustomValue to extend.
  • set_key_fn : Callback that assigns a value at an arbitrary hashable key.

Returns a new CustomValue with the mapping-key write callback registered.

#
CustomValue::with_slice

fn CustomValue::with_slice(self : CustomValue, slice_fn : (Int, Int, Int) -> Result[Value, String]) -> CustomValue

Attaches a slice callback, enabling x[start:stop:step] on this value.

Parameters:

  • self : The CustomValue to extend.
  • slice_fn : Callback that computes a slice given start, stop, and step indices.

Returns a new CustomValue with the slice callback registered.

#
CustomValue::with_unary

fn CustomValue::with_unary(self : CustomValue, unary_fn : (String) -> Result[Value, String]?) -> CustomValue

Attaches a unary operator callback for op x. The callback receives the operator string ("-", "+", "~", "not"). Return None to fall back to the default type-error.

Parameters:

  • self : The CustomValue to extend.
  • unary_fn : Callback invoked with the operator string.

Returns a new CustomValue with the unary operator callback registered.

#
StarlarkBoundMethod

pub struct StarlarkBoundMethod {
// private fields
}

A built-in method bound to a specific receiver. Each value is assigned a unique id at construction time so that identity comparison and hashing treat two separately created bound methods as distinct, even when they wrap the same receiver and method name.

#
StarlarkBoundMethod::method_name

fn StarlarkBoundMethod::method_name(self : StarlarkBoundMethod) -> String

Returns the name of the method this object is bound to.

Returns the method name string.

#
StarlarkBoundMethod::new

fn StarlarkBoundMethod::new(recv : Value, method_name : String) -> StarlarkBoundMethod

Creates a new StarlarkBoundMethod binding method_name to recv, assigning a globally unique identity id.

Parameters:

  • recv : The receiver value that the method is bound to.
  • method_name : The name of the method.

Returns a new StarlarkBoundMethod with a unique id.

#
StarlarkBoundMethod::recv

Returns the receiver value this method is bound to.

Returns the Value that was passed as recv when this bound method was created.

#
StarlarkBuiltinFunc

pub struct StarlarkBuiltinFunc {
// private fields
}

A built-in function value. Carries a name for display, an optional inline body closure (absent for dispatch-only builtins resolved by name at call time), and an optional recv for bound-method builtins.

#
StarlarkBuiltinFunc::bind_receiver

Returns a copy of this builtin with recv bound as its receiver.

Parameters:

  • self : The builtin function to bind.
  • recv : The receiver value to bind (typically the owning object).

Returns a new StarlarkBuiltinFunc with recv set.

#
StarlarkBuiltinFunc::call_body

fn StarlarkBuiltinFunc::call_body(self : StarlarkBuiltinFunc, ctx : BuiltinCallCtx, pos_args : Array[Value], kw_args : Array[(String, Value)]) -> Result[Value, String]?

Calls the inline body of this builtin, if one was provided.

Parameters:

  • self : The builtin function to call.
  • ctx : The call context providing the call dispatcher and thread-local lookup.
  • pos_args : Positional arguments.
  • kw_args : Keyword arguments as (name, value) pairs.

Returns Some(Ok(v)) or Some(Err(msg)) when a body is present, or None for dispatch-only builtins.

#
StarlarkBuiltinFunc::dispatch

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkBuiltinFunc::dispatch(name : String) -> StarlarkBuiltinFunc

Creates a dispatch-only StarlarkBuiltinFunc with the given name and no inline body. Calls are handled externally by pattern-matching on the name.

Parameters:

  • name : The name to associate with this builtin function.

Returns a StarlarkBuiltinFunc with body set to None.

#
StarlarkBuiltinFunc::name

fn StarlarkBuiltinFunc::name(self : StarlarkBuiltinFunc) -> String

Returns the name of the builtin function.

Returns the function's name string.

#
StarlarkBuiltinFunc::receiver

Returns the bound receiver of this builtin, or None if unbound.

Returns Some(recv) when the builtin was created via bind_receiver, or None for a free function.

#
StarlarkBytesElems

pub struct StarlarkBytesElems {
// private fields
}

A lazy byte-element iterator over a Bytes value. Returned by bytes.elems(). Each iteration step yields the integer value of the next byte. This mirrors starlark-go's bytesIterable type.

#
StarlarkBytesElems::new

Creates a StarlarkBytesElems view over a raw byte sequence.

Parameters:

  • b : The raw bytes to iterate over.

Returns a new StarlarkBytesElems wrapping b.

#
StarlarkBytesElems::raw_bytes

fn StarlarkBytesElems::raw_bytes(self : StarlarkBytesElems) -> Bytes

Returns the raw bytes backing this view.

Returns the underlying Bytes array.

#
StarlarkDict

pub struct StarlarkDict {
// private fields
}

An insertion-ordered mapping from Starlark hashable keys to values. Wraps Hashtable[Value, Value]; mutation is rejected when frozen or under active iteration.

#
StarlarkDict::check_mutable

fn StarlarkDict::check_mutable(self : StarlarkDict, verb : String) -> Result[Unit, String]

Checks that the dict is mutable, returning Err if it is frozen or under active iteration.

Parameters:

  • verb : A short description of the attempted operation, included in the error message (e.g. "dict.pop").

Returns Ok(()) if the dict can be mutated, or Err with a message describing why mutation is disallowed.

#
StarlarkDict::clear

fn StarlarkDict::clear(self : StarlarkDict) -> Result[Unit, String]

Removes all entries. Returns Err if the dict is frozen or under active iteration.

Returns Ok(()) on success, or Err with an error message if the dict is frozen or under active iteration.

#
StarlarkDict::contains

fn StarlarkDict::contains(self : StarlarkDict, key : Value) -> Result[Bool, String]

Returns Ok(true) if key is present, Ok(false) if absent, or Err if the key is unhashable.

#
StarlarkDict::delete

fn StarlarkDict::delete(self : StarlarkDict, key : Value) -> Result[Bool, String]

Removes the entry for key. Returns true if the key was present, false if absent. Returns Err if frozen, under active iteration, or if key is unhashable.

Parameters:

  • self : The dict to remove from.
  • key : The key to remove; must be hashable.

Returns Ok(true) if the key was present and removed, Ok(false) if the key was absent, or Err if the dict is frozen, under active iteration, or the key is unhashable.

#
StarlarkDict::each

fn StarlarkDict::each(self : StarlarkDict, f : (Value, Value) -> Unit) -> Unit

Iterates over all key-value pairs in insertion order, calling f for each.

Parameters:

  • self : The dict to iterate over.
  • f : The callback invoked with each key-value pair.

#
StarlarkDict::entries

fn StarlarkDict::entries(self : StarlarkDict) -> Iter[(Value, Value)]

Returns an iterator over a snapshot of all key-value pairs in insertion order.

The snapshot is taken eagerly at call time (one allocation), so mutations to the dict after calling entries do not affect the returned iterator.

#
StarlarkDict::freeze

fn StarlarkDict::freeze(self : StarlarkDict) -> Unit

Freezes the dict, making it immutable. Subsequent mutations raise an error.

#
StarlarkDict::get

fn StarlarkDict::get(self : StarlarkDict, key : Value) -> Result[Value?, String]

Returns the value for key, or None if absent. Returns Err if key is unhashable.

Parameters:

  • self : The dict to look up in.
  • key : The key to search for; must be hashable.

Returns Ok(Some(v)) if the key is present, Ok(None) if absent, or Err if the key is unhashable.

#
StarlarkDict::is_frozen

fn StarlarkDict::is_frozen(self : StarlarkDict) -> Bool

Returns true if the dict has been frozen and can no longer be mutated.

Returns true when the dict is frozen, false otherwise.

#
StarlarkDict::iter

fn StarlarkDict::iter(self : StarlarkDict) -> Iter[Value]

Returns an iterator over a snapshot of the dict keys in insertion order.

The snapshot is taken eagerly at call time (one allocation), so mutations to the dict after calling iter do not affect the returned iterator. Mirrors StarlarkList::iter and StarlarkSet::iter; iterating a dict yields its keys (as Starlark's for k in dict does). Use entries for (key, value) pairs.

#
StarlarkDict::keys

fn StarlarkDict::keys(self : StarlarkDict) -> Array[Value]

Returns a snapshot of all keys in insertion order.

Returns an array containing every key in the dict, in insertion order.

#
StarlarkDict::length

fn StarlarkDict::length(self : StarlarkDict) -> Int

Returns the number of key-value entries.

Returns the count of entries currently stored in the dict.

#
StarlarkDict::new

Creates an empty StarlarkDict.

Returns a new, unfrozen, empty dict with no entries.

#
StarlarkDict::pop_entry

fn StarlarkDict::pop_entry(self : StarlarkDict, key : Value) -> Result[Value?, String]

Removes key and returns its associated value, or None if absent. Returns Err if frozen, under active iteration, or the key is unhashable. An empty dict returns Ok(None) without attempting to hash the key.

#
StarlarkDict::popitem

fn StarlarkDict::popitem(self : StarlarkDict) -> Result[(Value, Value)?, String]

Removes and returns the first inserted key-value pair, or None if empty. Returns Err if frozen or under active iteration.

Returns Ok(Some((key, value))) if an entry was removed, Ok(None) if the dict is empty, or Err if the dict is frozen or under active iteration.

#
StarlarkDict::set

fn StarlarkDict::set(self : StarlarkDict, key : Value, value : Value) -> Result[Unit, String]

Inserts or updates the entry for key. Returns Err if the dict is frozen, has active iterators, or if key is unhashable.

Parameters:

  • self : The dict to update.
  • key : The key to insert or update; must be hashable.
  • value : The value to associate with key.

Returns Ok(()) on success, or Err with an error message on failure.

#
StarlarkFunction

pub struct StarlarkFunction {
// private fields
}

A Starlark user-defined function, carrying its name, source position, default values, and — for compiled functions — the bytecode Funcode, captured free variable cells, and a reference to the module it was defined in.

#
StarlarkFunction::compiled_freevars

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::compiled_freevars(self : StarlarkFunction) -> Array[Cell]

Returns the captured cells of a compiled closure (one per funcode.freevars entry). Empty for AST functions. Used by the VM to set up a call frame.

#
StarlarkFunction::compiled_funcode

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::compiled_funcode(self : StarlarkFunction) ->
Funcode
?

Returns the compiled code backing this function, or None if it is an AST-interpreted function. Used by the VM to run a called function.

#
StarlarkFunction::compiled_module_prog

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::compiled_module_prog(self : StarlarkFunction) ->
CompiledProgram
?

Returns the compiled program (module) this function belongs to, or None for an AST function. The VM runs the function's funcode against this program so constants, globals, and nested functions resolve correctly across modules.

#
StarlarkFunction::compiled_module_slots

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::compiled_module_slots(self : StarlarkFunction) -> Array[Value?]

Returns the function's module-global slots (shared with its defining module).

#
StarlarkFunction::defaults

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::defaults(self : StarlarkFunction) -> Array[Value?]

Returns the default value array aligned to the parameter list.

Returns an array of Value?, where None indicates no default for that parameter position.

#
StarlarkFunction::defining_module

fn StarlarkFunction::defining_module(self : StarlarkFunction) -> StarlarkModule?

Returns the module that defined this function, if module globals are bound.

Returns Some(module) when module globals have been associated via with_module_globals, or None otherwise.

#
StarlarkFunction::doc

fn StarlarkFunction::doc(self : StarlarkFunction) -> String

Returns the docstring of the function, or an empty string if absent.

Returns the string literal from the first statement of the body when it is a bare string expression; otherwise "".

#
StarlarkFunction::free_var

fn StarlarkFunction::free_var(self : StarlarkFunction, i : Int) -> (String, Value)?

Returns the i-th captured free variable as a (name, value) pair.

Parameters:

  • self : The function to query.
  • i : The zero-based index across all captured-scope layers.

Returns Some((name, value)) if index i exists, or None if out of range.

#
StarlarkFunction::from_compiled

#internal(unsafe, "bytecode VM only; not part of the public embedding API")
fn StarlarkFunction::from_compiled(name : String, funcode :
Funcode
, prog :
CompiledProgram
, slots : Array[Value?], defaults : Array[Value?], freevars : Array[Cell]) -> StarlarkFunction

Creates a StarlarkFunction backed by compiled bytecode. This is how every executable function value is built: the VM runs funcode against the module the function carries.

Parameters:

  • name : The function's declared name.
  • funcode : The compiled code for this function.
  • prog : The compiled program (module) this function belongs to.
  • slots : The module's live global slots, shared so the function resolves its module globals (and forward references) against its own module.
  • defaults : Default values aligned to the optional parameters.
  • freevars : Captured cells, one per funcode.freevars entry.

#
StarlarkFunction::globals

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkFunction::globals(self : StarlarkFunction) -> Map[String, Value]

Returns the module-level globals map, or an empty map if none is bound.

Returns the associated Map[String, Value], or {} when no module globals have been set.

#
StarlarkFunction::has_kwargs

fn StarlarkFunction::has_kwargs(self : StarlarkFunction) -> Bool

Returns true if the function accepts a variadic keyword parameter (**kwargs).

Returns true when any parameter is ParamKwIdent.

#
StarlarkFunction::has_varargs

fn StarlarkFunction::has_varargs(self : StarlarkFunction) -> Bool

Returns true if the function accepts a variadic positional parameter (*args).

Returns true when any parameter is ParamStarIdent.

#
StarlarkFunction::name

fn StarlarkFunction::name(self : StarlarkFunction) -> String

Returns the declared name of the function.

Returns the function's name string.

#
StarlarkFunction::new

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkFunction::new(name : String, pos :
Position
) -> StarlarkFunction

Creates a minimal, non-runnable StarlarkFunction carrying only a name and position (no compiled code). Functions produced by executing Starlark are built by from_compiled; this exists for tests and reflection-only uses that need a function value but never call it.

Parameters:

  • name : The function's declared name.
  • pos : Source position to report for the function.

#
StarlarkFunction::num_free_vars

fn StarlarkFunction::num_free_vars(self : StarlarkFunction) -> Int

Returns the total number of captured free variables across all closure scopes.

Returns the sum of binding counts across all captured-scope layers.

#
StarlarkFunction::num_kwonly_params

fn StarlarkFunction::num_kwonly_params(self : StarlarkFunction) -> Int

Returns the number of keyword-only parameters (those appearing after *).

Returns the count of ParamIdent and ParamDefault parameters that follow a ParamStarBare or ParamStarIdent separator.

#
StarlarkFunction::num_params

fn StarlarkFunction::num_params(self : StarlarkFunction) -> Int

Returns the number of named parameters (excludes bare * separators).

Returns the count of parameters that bind to a name (positional, default, *args, and **kwargs), excluding bare ParamStarBare separators.

#
StarlarkFunction::param

Returns the name and source position of the i-th named parameter.

Parameters:

  • self : The function to query.
  • i : The zero-based index among named parameters (same count as num_params).

Returns a (name, position) tuple. Aborts if i is out of range.

#
StarlarkFunction::param_default

fn StarlarkFunction::param_default(self : StarlarkFunction, i : Int) -> Value?

Returns the default value for parameter at position i, or None.

Parameters:

  • self : The function to query.
  • i : The zero-based parameter index into the defaults array.

Returns Some(v) if a default exists at position i, or None if i is out of range or the parameter has no default.

#
StarlarkFunction::position

Returns the source position of the function's def statement.

Returns the @errors.Position where this function was defined.

#
StarlarkIterator

pub struct StarlarkIterator {
// private fields
}

A forward-only cursor over a Starlark sequence or mapping. Call next() to advance; call done() when iteration is finished, even on early exit, to release any frozen-state hold on the container.

#
StarlarkIterator::collect

Drains the iterator into a fresh array, calling done() once exhausted.

Returns every remaining element in iteration order.

#
StarlarkIterator::done

fn StarlarkIterator::done(self : StarlarkIterator) -> Unit

Signals that iteration is complete, releasing any frozen-state hold on the container. Must be called even on early exit (e.g. break).

#
StarlarkIterator::next

Advances the iterator and returns the next value, or None when exhausted.

Returns Some(v) with the next element, or None when iteration is complete.

#
StarlarkList

pub struct StarlarkList {
// private fields
}

A mutable, ordered sequence of Starlark values. Mutation is rejected when the list is frozen or has active iterators.

#
StarlarkList::at

#alias("_[_]")
fn StarlarkList::at(self : StarlarkList, i : Int) -> Value

Returns the Value at index i, aborting if i is out of bounds. Mirrors Array's indexed access; use get for a bounds-checked option.

#
StarlarkList::check_mutable

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkList::check_mutable(self : StarlarkList, verb : String) -> Result[Unit, String]

Returns Ok(()) if the list can be mutated, otherwise Err with a descriptive message using verb (e.g. "append to", "clear").

Parameters:

  • self : The list to check.
  • verb : A short phrase describing the attempted operation, used in the error message (e.g. "append to", "clear").

Returns Ok(()) if mutation is allowed, or Err with a descriptive message if the list is frozen or has active iterators.

#
StarlarkList::clear

fn StarlarkList::clear(self : StarlarkList) -> Result[Unit, String]

Removes all elements. Fails if the list is frozen or being iterated.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkList::copy_items

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkList::copy_items(self : StarlarkList) -> Array[Value]

Returns a copy of the underlying items array.

Returns a shallow copy of the internal Array[Value].

#
StarlarkList::each

fn StarlarkList::each(self : StarlarkList, f : (Value) -> Unit) -> Unit

Calls f(value) for each element in order.

Parameters:

  • self : The list to iterate over.
  • f : A callback receiving each element value.

#
StarlarkList::eachi

fn StarlarkList::eachi(self : StarlarkList, f : (Int, Value) -> Unit) -> Unit

Calls f(index, value) for each element.

Parameters:

  • self : The list to iterate over.
  • f : A callback receiving the zero-based index and the element value.

#
StarlarkList::freeze

fn StarlarkList::freeze(self : StarlarkList) -> Unit

Marks the list as frozen; subsequent mutation attempts raise an error.

#
StarlarkList::get

fn StarlarkList::get(self : StarlarkList, i : Int) -> Value?

Returns the element at index i (unchecked).

Parameters:

  • self : The list to index into.
  • i : The zero-based index of the element to retrieve.

Returns Some(value) at index i, or None if i is out of bounds. Mirrors Array::get; use list[i] for direct (aborting) indexed access.

#
StarlarkList::insert

fn StarlarkList::insert(self : StarlarkList, i : Int, v : Value) -> Result[Unit, String]

Inserts v at index i, shifting subsequent elements right. Fails if the list is frozen or being iterated.

Parameters:

  • self : The list to insert into.
  • i : The zero-based index at which to insert.
  • v : The value to insert.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkList::is_empty

fn StarlarkList::is_empty(self : StarlarkList) -> Bool

Returns true if the list contains no elements.

Returns true when the list has zero elements.

#
StarlarkList::is_frozen

fn StarlarkList::is_frozen(self : StarlarkList) -> Bool

Returns true if the list has been frozen.

Returns true when the list is immutable; false otherwise.

#
StarlarkList::iter

fn StarlarkList::iter(self : StarlarkList) -> Iter[Value]

Returns a lazy iterator over the list elements.

Returns an Iter[Value] that yields each element in order.

#
StarlarkList::length

fn StarlarkList::length(self : StarlarkList) -> Int

Returns the number of elements in the list.

Returns the element count.

#
StarlarkList::new

fn StarlarkList::new(items : Array[Value]) -> StarlarkList

Creates a new, unfrozen StarlarkList wrapping items.

Parameters:

  • items : The initial array of Value elements.

Returns a new mutable StarlarkList containing items.

#
StarlarkList::pop

fn StarlarkList::pop(self : StarlarkList) -> Result[Value?, String]

Removes and returns the last element, or None if the list is empty. Fails if the list is frozen or being iterated.

Returns Ok(Some(v)) with the removed element, Ok(None) if the list was empty, or Err if the list is frozen or being iterated.

#
StarlarkList::pop_at

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn StarlarkList::pop_at(self : StarlarkList, i : Int, verb : String) -> Result[Value, String]

Removes and returns the element at index i. Fails if the list is frozen or being iterated.

Parameters:

  • self : The list to remove from.
  • i : The zero-based index of the element to remove.
  • verb : Verb used in the error message (e.g. "pop from", "remove from").

Returns Ok(v) with the removed element, or Err if the list is frozen or being iterated.

#
StarlarkList::push

fn StarlarkList::push(self : StarlarkList, v : Value) -> Result[Unit, String]

Appends v to the end of the list. Fails if the list is frozen or being iterated.

Parameters:

  • self : The list to append to.
  • v : The value to append.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkList::reverse

fn StarlarkList::reverse(self : StarlarkList) -> Result[Unit, String]

Reverses the list in place. Fails if the list is frozen or being iterated.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkList::set

fn StarlarkList::set(self : StarlarkList, i : Int, v : Value) -> Result[Unit, String]

Replaces the element at index i with v. Fails if the list is frozen or being iterated.

Parameters:

  • self : The list to update.
  • i : The zero-based index of the element to replace.
  • v : The new value to store at index i.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkList::sort_by

fn StarlarkList::sort_by(self : StarlarkList, cmp : (Value, Value) -> Int) -> Result[Unit, String]

Sorts the list in place using cmp. Fails if the list is frozen or being iterated.

Parameters:

  • self : The list to sort.
  • cmp : A comparator returning a negative int, zero, or positive int.

Returns Ok(()) on success, or Err if the list is frozen or being iterated.

#
StarlarkModule

pub struct StarlarkModule {
// private fields
}

A Starlark module value produced by executing a .star file. Carries the module's name (typically its filename or import path) and the map of module-level bindings that are visible to importers.

#
StarlarkModule::attr_names

fn StarlarkModule::attr_names(self : StarlarkModule) -> Array[String]

Returns the list of all attribute names exported by the module.

Returns an array of attribute name strings.

#
StarlarkModule::get

fn StarlarkModule::get(self : StarlarkModule, key : String) -> Value?

Looks up an attribute by name in the module.

Parameters:

  • self : The module to query.
  • key : The attribute name to look up.

Returns Some(v) if the attribute exists, or None.

#
StarlarkModule::name

fn StarlarkModule::name(self : StarlarkModule) -> String

Returns the name of the module.

Returns the module's name string.

#
StarlarkModule::new

fn StarlarkModule::new(name : String, attrs : Map[String, Value]) -> StarlarkModule

Creates a new StarlarkModule with the given name and attribute map.

Parameters:

  • name : The module's name (typically its filename or import path).
  • attrs : The module-level exported bindings.

Returns a new StarlarkModule.

#
StarlarkRange

pub struct StarlarkRange {
// private fields
}

A lazy, immutable arithmetic sequence returned by range(). Not a list; supports membership testing and indexing without materialising all elements.

#
StarlarkRange::contains

fn StarlarkRange::contains(self : StarlarkRange, n : Int64) -> Bool

Returns true if n is a member of the range.

Parameters:

  • self : The range to test membership against.
  • n : The integer value to look up.

Returns true if n lies within the range bounds and aligns to the step.

#
StarlarkRange::index_at

fn StarlarkRange::index_at(self : StarlarkRange, i : Int64) -> Int64

Returns the value at position i within the range.

Parameters:

  • self : The range to index into.
  • i : The zero-based position within the range.

Returns the arithmetic value at position i (i.e. start + step * i).

#
StarlarkRange::length

fn StarlarkRange::length(self : StarlarkRange) -> Int64

Returns the number of elements in the range.

Returns the count of integers produced by iterating the range.

#
StarlarkRange::new

fn StarlarkRange::new(start : Int64, stop : Int64, step : Int64) -> StarlarkRange

Creates a StarlarkRange with the given start, stop, and step.

Parameters:

  • start : The first value of the range (inclusive).
  • stop : The exclusive upper (or lower) bound of the range.
  • step : The increment between consecutive values; must not be zero.

Returns a new StarlarkRange representing the arithmetic sequence.

#
StarlarkRange::start

fn StarlarkRange::start(self : StarlarkRange) -> Int64

Returns the start of the range.

Returns the inclusive start value of the range.

#
StarlarkRange::step

fn StarlarkRange::step(self : StarlarkRange) -> Int64

Returns the step of the range.

Returns the increment between consecutive elements.

#
StarlarkRange::stop

fn StarlarkRange::stop(self : StarlarkRange) -> Int64

Returns the stop (exclusive end) of the range.

Returns the exclusive stop value of the range.

#
StarlarkSet

pub struct StarlarkSet {
// private fields
}

An insertion-ordered set of Starlark hashable values. Wraps Hashtable[Value, Value] (values are None); mutation is rejected when frozen or under active iteration.

#
StarlarkSet::add

fn StarlarkSet::add(self : StarlarkSet, key : Value) -> Result[Unit, String]

Inserts key into the set. Returns Err if the set is frozen, under active iteration, or if key is unhashable.

Parameters:

  • self : The set to insert into.
  • key : The value to add; must be hashable.

Returns Ok(()) on success, or Err with an error message on failure.

#
StarlarkSet::clear

fn StarlarkSet::clear(self : StarlarkSet) -> Result[Unit, String]

Removes all elements. Returns Err if the set is frozen or under active iteration.

Returns Ok(()) on success, or Err with an error message if the set is frozen or under active iteration.

#
StarlarkSet::contains

fn StarlarkSet::contains(self : StarlarkSet, key : Value) -> Result[Bool, String]

Returns true if key is in the set. Returns Err if key is unhashable.

Parameters:

  • self : The set to search.
  • key : The value to look for; must be hashable.

Returns Ok(true) if the value is present, Ok(false) if absent, or Err if the key is unhashable.

#
StarlarkSet::each

fn StarlarkSet::each(self : StarlarkSet, f : (Value) -> Unit) -> Unit

Iterates over all keys in insertion order, calling f for each.

Parameters:

  • self : The set to iterate over.
  • f : The callback invoked with each element.

#
StarlarkSet::freeze

fn StarlarkSet::freeze(self : StarlarkSet) -> Unit

Freezes the set, making it immutable. Subsequent mutations raise an error.

#
StarlarkSet::is_frozen

fn StarlarkSet::is_frozen(self : StarlarkSet) -> Bool

Returns true if the set has been frozen and can no longer be mutated.

Returns true when the set is frozen, false otherwise.

#
StarlarkSet::iter

fn StarlarkSet::iter(self : StarlarkSet) -> Iter[Value]

Returns an Iter over all keys in insertion order.

Returns a lazy iterator over elements in insertion order.

#
StarlarkSet::length

fn StarlarkSet::length(self : StarlarkSet) -> Int

Returns the number of elements.

Returns the count of elements currently stored in the set.

#
StarlarkSet::new

Creates an empty StarlarkSet.

Returns a new, unfrozen, empty set with no elements.

#
StarlarkSet::pop_first

fn StarlarkSet::pop_first(self : StarlarkSet) -> Result[Value?, String]

Removes and returns the first inserted key, or None if empty. Returns Err if the set is frozen or under active iteration.

Returns Ok(Some(v)) if an element was removed, Ok(None) if the set is empty, or Err if the set is frozen or under active iteration.

#
StarlarkSet::remove

fn StarlarkSet::remove(self : StarlarkSet, key : Value) -> Result[Bool, String]

Removes key from the set. Returns true if the key was present, false if absent. Returns Err if frozen, under active iteration, or if key is unhashable.

Parameters:

  • self : The set to remove from.
  • key : The value to remove; must be hashable.

Returns Ok(true) if the value was present and removed, Ok(false) if absent, or Err if the set is frozen, under active iteration, or the key is unhashable.

#
StarlarkString

pub struct StarlarkString {
// private fields
}

An immutable Starlark string backed by a pre-computed UTF-8 Bytes array. All length, indexing, and hashing operations use the byte array so that s[i] returns the i-th byte, matching starlark-go semantics.

The dual raw/bytes representation (Option A) is deliberate: raw is a MoonBit String used for display and MoonBit-level operations; bytes is the authoritative byte sequence used for all Starlark-observable output (print, repr, write). Output sinks must read bytes, not raw, so that invalid-UTF-8 strings round-trip faithfully instead of being replaced with U+FFFD. See also StarlarkString::from_bytes.

#
StarlarkString::byte_at

fn StarlarkString::byte_at(self : StarlarkString, i : Int) -> Byte

Returns the byte at UTF-8 offset i.

Parameters:

  • self : The string to index into.
  • i : The zero-based UTF-8 byte offset.

Returns the byte value at offset i.

#
StarlarkString::byte_len

fn StarlarkString::byte_len(self : StarlarkString) -> Int

Returns the number of UTF-8 bytes in the string (the Starlark len()).

Returns the byte length of the underlying UTF-8 encoding.

#
StarlarkString::equals

fn StarlarkString::equals(self : StarlarkString, other : StarlarkString) -> Bool

Returns true if self and other contain the same bytes.

Parameters:

  • self : The first string to compare.
  • other : The second string to compare.

Returns true if both strings have identical UTF-8 byte content.

#
StarlarkString::from_bytes

fn StarlarkString::from_bytes(bytes : Bytes) -> StarlarkString

Creates a StarlarkString from a raw UTF-8 byte sequence. Invalid bytes are replaced with U+FFFD.

Parameters:

  • bytes : The raw UTF-8 byte sequence to wrap.

Returns a new StarlarkString decoded from bytes, replacing any invalid sequences with U+FFFD.

#
StarlarkString::new

fn StarlarkString::new(raw : String) -> StarlarkString

Creates a StarlarkString from a MoonBit String, encoding it to UTF-8.

Parameters:

  • raw : The MoonBit String to encode.

Returns a new StarlarkString backed by the UTF-8 encoding of raw.

#
StarlarkString::raw

fn StarlarkString::raw(self : StarlarkString) -> String

Returns the MoonBit String (UTF-16 internally) that was used to create this StarlarkString.

Returns the original MoonBit String value.

#
StarlarkString::to_bytes

fn StarlarkString::to_bytes(self : StarlarkString) -> Bytes

Returns the underlying UTF-8 Bytes array.

Returns the pre-computed UTF-8 Bytes backing this string.

#
StarlarkStringCodepoints

pub struct StarlarkStringCodepoints {
// private fields
}

A lazy Unicode-codepoint iterator over a StarlarkString. Returned by string.codepoints() and string.codepoint_ords(). When ords is true the iterator yields integer codepoint values; when false it yields single-codepoint StarlarkString values. This mirrors starlark-go's stringCodepoints type.

#
StarlarkStringCodepoints::is_ords

Returns true if this view yields integer codepoint ordinals rather than single-codepoint strings.

Returns the ords flag set at construction time.

#
StarlarkStringCodepoints::new

Creates a StarlarkStringCodepoints view over a string.

Parameters:

  • s : The source string to iterate over.
  • ords : When true, the iterator yields integer codepoint values; when false, it yields single-codepoint StarlarkString values.

Returns a new StarlarkStringCodepoints.

#
StarlarkStringCodepoints::source_string

Returns the source string this codepoints view was created from.

Returns the underlying StarlarkString.

#
StarlarkStringElems

pub struct StarlarkStringElems {
// private fields
}

A lazy byte-element iterator over a StarlarkString. Returned by string.elems() and string.elem_ords(). When ords is true the iterator yields integer byte values; when false it yields single-byte StarlarkString values. This mirrors starlark-go's stringElems type.

#
StarlarkStringElems::is_ords

fn StarlarkStringElems::is_ords(self : StarlarkStringElems) -> Bool

Returns true if this view yields integer byte ordinals rather than single-byte strings.

Returns the ords flag set at construction time.

#
StarlarkStringElems::new

Creates a StarlarkStringElems view over a string.

Parameters:

  • s : The source string to iterate over.
  • ords : When true, the iterator yields integer byte values; when false, it yields single-byte StarlarkString values.

Returns a new StarlarkStringElems.

#
StarlarkStringElems::source_string

Returns the source string this view was created from.

Returns the underlying StarlarkString.

#
StringDict

pub struct StringDict {
// private fields
}

A string-keyed dict of Values; used by the embedding API to pass named globals to eval_expr and to inspect module exports.

#
StringDict::delete

fn StringDict::delete(self : StringDict, key : String) -> Bool

Removes the binding for key.

Parameters:

  • self : The dict to modify.
  • key : The string key to remove.

Returns true if key was present (and removed), false if absent.

#
StringDict::each

fn StringDict::each(self : StringDict, f : (String, Value) -> Unit) -> Unit

Calls f(key, value) for every entry in the dict.

Parameters:

  • self : The dict to iterate.
  • f : Callback receiving each key-value pair.

#
StringDict::freeze

fn StringDict::freeze(self : StringDict) -> Unit

Recursively deep-freezes all values in the dict.

Parameters:

  • self : The dict whose values to freeze.

#
StringDict::from_map

fn StringDict::from_map(m : Map[String, Value]) -> StringDict

Creates a StringDict wrapping an existing Map[String, Value].

Parameters:

  • m : The map to wrap; ownership is transferred.

Returns a StringDict backed by m.

#
StringDict::get

fn StringDict::get(self : StringDict, key : String) -> Value?

Returns the value bound to key, or None.

Parameters:

  • self : The dict to look up in.
  • key : The string key to retrieve.

Returns Some(value) if key is present, None otherwise.

#
StringDict::has

fn StringDict::has(self : StringDict, key : String) -> Bool

Returns true if key is present.

Parameters:

  • self : The dict to query.
  • key : The string key to test for presence.

Returns true if key exists in the dict.

#
StringDict::keys

fn StringDict::keys(self : StringDict) -> Array[String]

Returns the keys in lexicographic order.

Parameters:

  • self : The dict whose keys to retrieve.

Returns an array of all keys sorted lexicographically.

#
StringDict::new

fn StringDict::new() -> StringDict

Creates an empty StringDict.

Returns a new StringDict with no bindings.

#
StringDict::set

fn StringDict::set(self : StringDict, key : String, v : Value) -> Unit

Inserts or updates the binding for key.

Parameters:

  • self : The dict to modify.
  • key : The string key to bind.
  • v : The value to associate with key.

#
StringDict::values

fn StringDict::values(self : StringDict) -> Array[Value]

Returns all values in the dict.

Parameters:

  • self : The dict whose values to retrieve.

Returns an array of all values.

#
Value

pub(all) enum Value {
None
Bool(Bool)
Int(
BigInt
)
Float(Double)
String(StarlarkString)
Bytes(Bytes)
List(StarlarkList)
Tuple(Array[Value])
Dict(StarlarkDict)
Set(StarlarkSet)
Range(StarlarkRange)
Function(StarlarkFunction)
Builtin(StarlarkBuiltinFunc)
BoundMethod(StarlarkBoundMethod)
Module(StarlarkModule)
StringElems(StarlarkStringElems)
StringCodepoints(StarlarkStringCodepoints)
BytesElems(StarlarkBytesElems)
ExtVal(CustomValue)
}

The Starlark value sum type. Covers all built-in types plus embedder extensions via ExtVal.
impl Eq for Value

#
Value::freeze

fn Value::freeze(self : Value) -> Unit

Recursively deep-freezes self and all values reachable from it (list items, dict keys/values, set elements, function defaults and closures). Aborts if the nesting depth exceeds freeze_limit.

Parameters:

  • self : The root value to freeze.

#
Value::freeze_checked

fn Value::freeze_checked(self : Value) -> Result[Unit, String]

Like Value::freeze but returns Err instead of aborting when the nesting depth limit is exceeded.

On Err, the value is in an indeterminate partially-frozen state and must be discarded. The exec-file entry points do this automatically; embedders calling freeze_checked directly must not use the value after an Err return.

#
Value::hash

fn Value::hash(self : Value) -> Result[UInt, String]

Computes the Starlark hash of self. Returns Err for unhashable types (list, dict, set, range, module). Guarantees hash(x) == hash(y) whenever x == y under Starlark semantics, including cross-type Int/Float.

Parameters:

  • self : The value to hash.

Returns Ok(hash) for hashable values, or Err with a message like "unhashable type: list" for unhashable types.

#
Value::new_builtin

fn Value::new_builtin(name : String, body : (BuiltinCallCtx, Array[Value], Array[(String, Value)]) -> Result[Value, String]) -> Value

Creates a Value::Builtin with the given name and callable body.

Parameters:

  • name : The name of the builtin function.
  • body : The implementation closure receiving the call context, positional args, and keyword args.

Returns a Value::Builtin that dispatches through body.

#
Value::new_dict

fn Value::new_dict() -> Value

Creates an empty Value::Dict.

Returns a new empty Value::Dict.

test {
let v = Value::new_dict()
inspect(v.repr(), content="{}")
}

#
Value::new_float

fn Value::new_float(f : Double) -> Value

Creates a Value::Float from a Double.

Parameters:

  • f : The double-precision float to wrap.

Returns a Value::Float containing f.

test {
let v = Value::new_float(1.5)
inspect(v.repr(), content="1.5")
}

#
Value::new_int

fn Value::new_int(n : Int64) -> Value

Creates a Value::Int from an Int64.

Parameters:

  • n : The 64-bit signed integer to wrap.

Returns a Value::Int containing n as an arbitrary-precision integer.

test {
let v = Value::new_int(42L)
inspect(v.repr(), content="42")
}

#
Value::new_list

fn Value::new_list(items : Array[Value]) -> Value

Creates a Value::List wrapping a new StarlarkList.

Parameters:

  • items : The initial array of Value elements.

Returns a Value::List containing items.

test {
let v = Value::new_list([Value::Int(1N), Value::Int(2N), Value::Int(3N)])
inspect(v.repr(), content="[1, 2, 3]")
}

#
Value::new_set

fn Value::new_set() -> Value

Creates an empty Value::Set.

Returns a new empty Value::Set.

test {
let v = Value::new_set()
inspect(v.repr(), content="set([])")
}

#
Value::new_string

fn Value::new_string(s : String) -> Value

Creates a Value::String from a MoonBit String.

Parameters:

  • s : The MoonBit String to wrap.

Returns a Value::String backed by a new StarlarkString.

test {
let v = Value::new_string("hello")
inspect(v.repr(), content="\"hello\"")
}

#
Value::repr

fn Value::repr(v : Value) -> String

Returns the Starlark repr(v) string. Detects cyclic list/dict references and replaces them with [...] / {...}.

Parameters:

  • v : The value to represent.

Returns the Starlark repr() string for v.

test {
inspect(Value::None.repr(), content="None")
inspect(Value::Bool(true).repr(), content="True")
inspect(Value::Int(42N).repr(), content="42")
inspect(Value::new_string("hi").repr(), content="\"hi\"")
// Cyclic list is shown with a placeholder rather than crashing.
let l = StarlarkList::new([Value::Int(0N)])
l.push(Value::List(l)) |> ignore
inspect(Value::List(l).repr().contains("[...]"), content="true")
}

#
Value::repr_at_depth

fn Value::repr_at_depth(v : Value, depth : Int) -> Result[String, String]

Like Value::repr_checked but starts with an explicit depth budget instead of repr_limit. Intended for use by CustomValue implementations (e.g. structs) that repr field values and need to propagate the caller's remaining depth rather than restarting it.

Parameters:

  • depth : Remaining recursion depth to allow.

#
Value::repr_checked

fn Value::repr_checked(v : Value) -> Result[String, String]

Like Value::repr but returns Err instead of aborting when the nesting depth limit is exceeded. For use in the eval engine where the error should surface as a Starlark runtime error.

test {
inspect(Value::Int(99N).repr_checked().unwrap(), content="99")
// Exceeding the depth limit yields an Err rather than aborting.
let mut v : Value = Value::Int(0N)
for _ in 0..<(repr_limit + 1) {
v = Value::new_list([v])
}
inspect(v.repr_checked() is Err(_), content="true")
}

#
Value::starlark_equals

fn Value::starlark_equals(a : Value, b : Value) -> Bool

Returns true if a == b under Starlark semantics, including cross-type Int/Float equality and NaN inequality.

Parameters:

  • a : The left-hand side value.
  • b : The right-hand side value.

Returns true when the two values are equal under Starlark semantics.

#
Value::to_str

fn Value::to_str(v : Value) -> String

Returns the Starlark str(v) string representation of v. Unlike repr, string values are returned without quotes.

Parameters:

  • v : The value to convert to a string.

Returns the Starlark str() representation of v.

#
Value::to_str_checked

fn Value::to_str_checked(v : Value) -> Result[String, String]

Like Value::to_str but returns Err instead of aborting when the nesting depth limit is exceeded. For use in the eval engine where the error should surface as a Starlark runtime error.

#
Value::truth

fn Value::truth(v : Value) -> Bool

Returns the Starlark truth value of v (equivalent to bool(v)).

Parameters:

  • v : The value to evaluate.

Returns false for None, False, zero numbers, empty strings/bytes/ collections, and zero-length ranges; true for everything else.

test {
inspect(Value::None.truth(), content="false")
inspect(Value::Int(0N).truth(), content="false")
inspect(Value::new_string("").truth(), content="false")
inspect(Value::Int(1N).truth(), content="true")
inspect(Value::Bool(true).truth(), content="true")
}

#
Value::type_name

fn Value::type_name(v : Value) -> String

Returns the Starlark type() string for v (e.g. "int", "list").

Parameters:

  • v : The value whose type name to retrieve.

Returns the Starlark type name string.

test {
inspect(Value::None.type_name(), content="NoneType")
inspect(Value::Int(1N).type_name(), content="int")
inspect(Value::Bool(true).type_name(), content="bool")
inspect(Value::new_string("").type_name(), content="string")
}

#
as_float

fn as_float(v : Value) -> (Double, Bool)

Extracts a Double from an Int or Float value.

Parameters:

  • v : The value to extract a float from.

Returns (value, true) on success, or (0.0, false) if v is neither a numeric type.

#
as_string

fn as_string(v : Value) -> (String, Bool)

Extracts the raw String from a Starlark String value.

Parameters:

  • v : The value to extract a string from.

Returns (string, true) on success, or ("", false) if v is not a string.

#
compare_depth

fn compare_depth(op : String, a : Value, b : Value, depth : Int) -> Result[Bool, String]

Applies a comparison operator ("==", "!=", "<", "<=", ">", ">=") to a and b with an explicit recursion-depth cap.

Parameters:

  • op : The comparison operator string.
  • a : The left-hand value.
  • b : The right-hand value.
  • depth : Remaining recursion budget; use compare_limit as the initial value.

Returns Ok(result) on success, or Err on type mismatch, depth exhaustion, or unknown operator.

#
compare_limit

let compare_limit : Int

Depth cap for recursive comparison and equality operations. Matches starlark-go's CompareLimit (10). Every function that recurses over nested Values must accept a depth : Int parameter, decrement it before each recursive call, and return Err when depth < 1. The named limit constants here are the shared roots; never recurse without one.

#
compare_values

#internal(unsafe, "eval engine only; embedders use compare_depth")
fn compare_values(a : Value, b : Value, op? : String) -> Result[Int, String]

Compares a and b using Starlark's total ordering, returning a negative int, zero, or positive int. Returns Err for incompatible types. op is the operator string used in the error message.

Parameters:

  • a : The left-hand side value.
  • b : The right-hand side value.
  • op : The comparison operator string used in error messages (default "<").

Returns Ok(n) where n < 0, n == 0, or n > 0, or Err when the types cannot be compared.

#
compare_values_depth

#internal(unsafe, "eval engine only; embedders use compare_depth")
fn compare_values_depth(a : Value, b : Value, depth : Int, op? : String) -> Result[Int, String]

Like compare_values but with an explicit recursion-depth cap to guard against cycles in nested structures.

Parameters:

  • a : The left-hand side value.
  • b : The right-hand side value.
  • depth : Maximum remaining recursion depth; returns Err when it reaches zero.
  • op : The comparison operator string used in error messages (default "<").

Returns Ok(n) where n < 0, n == 0, or n > 0, or Err when types are incompatible or the depth limit is exceeded.

#
dict_key_hash_limit

let dict_key_hash_limit : Int

Depth cap for hashing StarlarkDict and StarlarkSet keys.

Set to compare_limit - 1 so that any key that hashes successfully can also be compared for equality. starlark_equals_depth checks depth < 1 before dispatching — including for leaf types — so equality with budget compare_limit accepts nesting only up to compare_limit - 1. Using this constant for the hash function keeps both limits in lock-step: a key that hashes at depth D can always be equality-compared at the same depth.

#
equal

fn equal(a : Value, b : Value) -> Result[Bool, String]

Structural equality with the default recursion-depth cap (compare_limit) to guard against cycles.

Parameters:

  • a : The left-hand value.
  • b : The right-hand value.

Returns Ok(true) if a == b, Ok(false) if not, or Err when the recursion-depth cap is exceeded (cyclic structure).

#
equal_depth

fn equal_depth(a : Value, b : Value, depth : Int) -> Result[Bool, String]

Structural equality with an explicit recursion-depth cap.

Parameters:

  • a : The left-hand value.
  • b : The right-hand value.
  • depth : Remaining recursion budget; use compare_limit as the initial value.

Returns Ok(true) if a == b, Ok(false) if not, or Err when depth is exhausted (cyclic structure).

#
freeze_limit

let freeze_limit : Int

Depth cap for freeze traversal. Set to 200 — a safe ceiling on all four MoonBit backends. See compare_limit for the depth-guard convention.

#
hash_limit

let hash_limit : Int

Depth cap for hash traversal. Set to 200 — a safe ceiling on all four MoonBit backends. See compare_limit for the depth-guard convention.

StarlarkDict and StarlarkSet use dict_key_hash_limit (not this constant) for their internal hash function. Use hash_limit only for standalone hash calls outside of a hash-table context.

#
hash_value_depth

fn hash_value_depth(v : Value, depth : Int) -> Result[UInt, String]

Hashes v with an explicit recursion-depth cap. Pass the received depth to hash_value_depth inside a CustomValue::with_hash_depth callback so nested Value fields are hashed without restarting the counter.

Parameters:

  • v : The value to hash.
  • depth : Remaining recursion budget; use hash_limit as the initial value.

Returns Ok(hash) on success, or Err for unhashable types or when depth is exhausted.

#
iterate

fn iterate(v : Value) -> Result[StarlarkIterator, String]

Returns a StarlarkIterator over v. Returns Err if v is not iterable. Supported types: List, Tuple, Dict (keys), Set (keys), Range, string elems/codepoints, bytes elems, and ExtVal with an iterate callback.

Parameters:

  • v : The Starlark value to iterate over.

Returns Ok(iterator) for iterable values, or Err with a message like "int value is not iterable" for non-iterable types.

#
len_of

fn len_of(v : Value) -> Int64

Returns the sequence length of v (list, tuple, string, bytes, range), or -1 if v has no length.

Parameters:

  • v : The value whose length to retrieve.

Returns the non-negative length, or -1 if v does not support len.

#
length_of

#internal(unsafe, "eval engine only; embedders use len_of")
fn length_of(v : Value) -> Result[Int64, String]

Returns the number of elements in v for types that have a length (String, Bytes, List, Tuple, Dict, Set, Range, StringElems, ExtVal with a length callback). Returns Err for all other types.

Parameters:

  • v : The Starlark value to measure.

Returns Ok(n) with the element count, or Err with a message like "len: value of type int has no len" for types without a length.

#
number_to_int

fn number_to_int(v : Value) -> Int64?

Converts an Int or Float value to Int64.

Parameters:

  • v : The numeric value to convert.

Returns Some(n) on success, or None if v is not numeric, is NaN or infinite, or is outside the signed 64-bit range.

#
repr_limit

let repr_limit : Int

Depth cap for repr / str traversal. Set to 200 — a safe ceiling on all four MoonBit backends (see #175). See compare_limit in value/traits.mbt for the depth-guard convention that all recursive traversal paths follow.

#
starlark_equals_depth

#internal(unsafe, "eval engine only; not part of the public embedding API")
fn starlark_equals_depth(a : Value, b : Value, depth : Int) -> Result[Bool, String]

Like starlark_equals but with an explicit recursion-depth cap.

Parameters:

  • a : The left-hand side value.
  • b : The right-hand side value.
  • depth : Maximum remaining recursion depth; returns Err when it reaches zero.

Returns Ok(true) when equal, Ok(false) when not, or Err when the depth limit is exceeded.