Module std::builtins

Built-in functions available in every Hew program.

These functions are always in scope — no import is needed. They cover I/O, assertions, math, string operations, and program control flow.

Contents

Functions

Function println

pub fn println(value: dyn Display)

Print a value followed by a newline.

Accepts any type that implements Display.

Examples

println(42);
println("hello");
println(true);

Function print

pub fn print(value: dyn Display)

Print a value without a trailing newline.

Examples

print("Enter name: ");

Function assert

pub fn assert(condition: bool)

Assert that a condition is true. Panics if condition is false.

Examples

assert(x > 0);

Function assert_eq

pub fn assert_eq(left: dyn Display, right: dyn Display)

Assert that two values are equal. Panics with a diff if they differ.

Both arguments must be the same type.

Examples

assert_eq(add(1, 2), 3);

Function assert_ne

pub fn assert_ne(left: dyn Display, right: dyn Display)

Assert that two values are not equal. Panics if they are the same.

Both arguments must be the same type.

Examples

assert_ne(a, b);

Function abs

pub fn abs(x: i32) -> i32

Returns the absolute value of an integer.

Examples

let x = abs(-5);  // 5

Function sqrt

pub fn sqrt(x: f64) -> f64

Returns the square root of a floating-point number.

Examples

let r = sqrt(9.0);  // 3.0

Function min

pub fn min(a: i32, b: i32) -> i32

Returns the smaller of two integers.

Function max

pub fn max(a: i32, b: i32) -> i32

Returns the larger of two integers.

Function to_float

pub fn to_float(x: i32) -> f64

Convert an integer to a floating-point number.

Examples

let f = to_float(42);  // 42.0

Function string_concat

pub fn string_concat(a: string, b: string) -> string

Concatenate two strings, returning a new string.

Examples

let full = string_concat("hello ", "world");

Function string_length

pub fn string_length(s: string) -> i32

Returns the byte length of a string.

Function to_string

pub fn to_string(value: dyn Display) -> string

Convert any value to its string representation.

Accepts any type that implements Display — this includes all numeric primitives, bool, char, string, and user types with a Display impl.

Examples

let s = to_string(42);     // "42"
let t = to_string(true);   // "true"
let u = to_string('x');    // "x"

Function len

pub fn len(value: dyn Display) -> i32

Returns the length of a collection or string.

Function string_char_at

pub fn string_char_at(s: string, index: i32) -> char

Returns the character (as a char) at the given byte index.

Function string_equals

pub fn string_equals(a: string, b: string) -> bool

Test whether two strings are equal.

Function string_from_int

pub fn string_from_int(n: i64) -> string

Convert an integer to a string.

Examples

let s = string_from_int(42);  // "42"

Function string_contains

pub fn string_contains(haystack: string, needle: string) -> bool

Test whether haystack contains needle.

Function string_starts_with

pub fn string_starts_with(s: string, prefix: string) -> bool

Test whether a string starts with the given prefix.

Function substring

pub fn substring(s: string, start: i32, end: i32) -> string

Extract a substring by byte indices [start, end).

Examples

let s = substring("hello", 0, 3);  // "hel"

Function string_trim

pub fn string_trim(s: string) -> string

Strip leading and trailing whitespace.

Function string_to_int

pub fn string_to_int(s: string) -> i64

Parse a string as an integer. Returns 0 on failure.

Function string_find

pub fn string_find(haystack: string, needle: string) -> i32

Find the first occurrence of needle in haystack.

Returns the byte offset, or -1 if not found.

Function read_file

pub fn read_file(path: string) -> string

Read the entire contents of a file as a string.

Function write_file

pub fn write_file(path: string, content: string)

Write a string to a file, creating or overwriting it.

Function sleep_ms

pub fn sleep_ms(ms: i32)

Pause execution for the given number of milliseconds.

Function sleep

pub fn sleep(seconds: i32)

Pause execution for the given number of seconds.

Function stop

pub fn stop(target: dyn Display)

Stop an actor gracefully.

Function exit

pub fn exit(code: i32)

Terminate the program with the given exit code.

This function never returns.

Function panic

pub fn panic(message: string)

Terminate the program with an error message.

This function never returns.

Examples

panic("something went wrong");

Types

Struct LocalPid

A process-local actor pid returned by spawn.

LocalPid<T> is accepted by all built-in actor functions (close, link, monitor, etc.) and by any function that takes dyn Pid<Msg = M>.

Coercion to a remote pid is explicit:

let remote = pid.to_remote_via(node_handle);

Struct RemotePid

An actor pid on a remote node.

Produced by peer-discovery or explicit construction via RemotePid::from_raw. Does NOT coerce implicitly to LocalPid<T> — remote actors are a distinct class.

.tell is a fail-closed stub until S4 wires up hew_actor_send_remote.

SHIM

RemotePid::from_raw is scaffolding for S1 tests. .tell fails closed with SendError::NodeRoutingNotWired until hew_actor_send_remote lands.

Enum SendError

Error returned when a pid send cannot be completed.

Variants

Full

The destination mailbox is full.

Closed

The destination is closed or no longer alive.

NodeRoutingNotWired

Cross-node routing has not been wired for this runtime path yet.

Enum LookupError

Error returned when Node::lookup<T>(name) cannot resolve name.

Returned as Err(LookupError::NotFound) when no actor is registered under name on the current node (or any peer with a gossiped name). Future variants (e.g. transport-level failures, schema mismatches) are deferred to follow-on polish; today the runtime collapses every failure into NotFound since the underlying registry surface is fail-closed per set_last_error for the diagnostic detail.

Variants

NotFound

No actor is registered under the requested name.

Enum AskError

Error returned when a remote actor ask cannot complete.

Variant order matches the native runtime ask ABI so codegen can project the runtime error discriminant directly into this public enum.

Variants

NoError

Internal no-error sentinel; should not be returned as Err.

NodeNotRunning

The local node is not running.

RoutingFailed

The destination node or actor could not be routed.

EncodeFailed

The request payload could not be encoded.

SendFailed

The request could not be sent.

Timeout

The caller-supplied timeout elapsed before a reply arrived.

ConnectionDropped

The remote connection closed before the reply arrived.

PayloadSizeMismatch

The reply payload did not match the expected reply size.

WorkerAtCapacity

The remote ask worker is at capacity.

ActorStopped

The destination actor is stopped.

MailboxFull

The destination actor mailbox is full.

OrphanedAsk

A reply arrived after its waiter was gone.

NoRunnableWork

The runtime had no runnable work while waiting for the reply.

Enum TimeoutError

Error arm of await rx.recv() | after d and await stream.recv() | after d.

Returned as Err(TimeoutError::Timeout) when the deadline fires before an item arrives. Distinguishes a timeout from a closed channel (Ok(None)).

match await rx.recv() | after 50ms {
    Ok(Some(v)) => v,       // item received before deadline
    Ok(None)    => -1,      // channel closed (no deadline race)
    Err(_)      => -2,      // deadline fired
}

Variants

Timeout

The deadline fired before the recv completed.

Struct VecIter

Cursor iterator over a Vec<T> produced by vec.into_iter().

VecIter<T> is the concrete IntoIterator::IntoIter for Vec<T> — it pairs the owned vector with the current idx cursor so that for x in v { ... } (for-loop desugar) and the lazy combinators in std/iter can drive iteration through the trait surface rather than the per-type *_int / *_str / *_f64 table.

next takes a mutable receiver: each call reads the current element and then bumps self.idx in place via a field-store. idx advances once per call until it reaches the vector's length, after which every subsequent next returns None. The receiver remains Live after exhaustion and drops at scope exit — see the Iterator trait doc-comment.

Vec is a refcounted heap handle, so the cursor carries the underlying vector storage by handle (no per-step copy).

Lives in std/builtins.hew rather than std/vec.hew so it registers alongside the Vec Index impl through register_builtins_hew_impls (the per-stdlib-module receiver-impl harness only handles a fixed set of receivers; auto-registration on builtin nominals belongs in builtins).

Fields

vec: Vec<T>
idx: i64

Struct Instant

Monotonic timestamp captured by the runtime.

Fields

nanos: i64

Traits

Trait ActorMsg

Message contract for actor types used behind LocalPid<A> / RemotePid<A>.

Named actors opt into the erased Pid surface by implementing this trait and binding Msg to the envelope type accepted by .tell / .ask, plus Reply to the response type returned by .ask.

Trait Pid

Trait satisfied by both LocalPid<A> and RemotePid<A>.

Future surface target for accepting either local or remote pids. A640: generic P: Pid sends are fail-closed unless P::Msg is concretely proven Serializable; local-only dispatch through LocalPid<T> keeps the value model below.

fn ping<P: Pid>(p: P, msg: P::Msg) -> Result<(), SendError> {
    p.tell(msg)
}

Methods

fn tell(pid: Self, msg: Self::Msg) -> Result<(), SendError>

Trait Iterator

Produce a sequence of values one item at a time.

User-defined iterators implement this trait directly; for loops accept values whose type implements IntoIterator and walk the resulting Iterator to bind each yielded Item.

next takes its receiver mutably (var self): iterator implementations step their internal state in place (cursor advance, decrement remaining, flush a buffer) and surface successive items through the Option<Self::Item> return. Callers must hold the iterator in a var binding so that the mutated receiver remains observable between calls; binding the iterator with let is rejected by the checker with a "receiver requires mutable binding" diagnostic.

Iterator methods with mutable receivers keep the iterator Live past exhaustion; drop fires at scope exit, not at the None return. This is a deliberate shift from a hypothetical by-move shape: exhaustion is a Some → None boundary, not a lifetime boundary. Iterator implementations that own non-shared resources (heap-owning buffers, channel readers) inherit the "exhaustion ≠ drop" invariant — see the lifecycle-symmetry invariant in LESSONS.md.

Methods

fn next(self: Self) -> Option<Self::Item>

Trait IntoIterator

Convert a value into an Iterator.

for x in expr { ... } desugars to let mut it = expr.into_iter(); loop { match it.next() { Some(x) => ..., None => break } } — the iterable on the right of in must implement IntoIterator, and the loop binding is typed as <Self::IntoIter as Iterator>::Item.

IntoIter carries the Iterator<Item = Self::Item> bound so that callers projecting <T as IntoIterator>::IntoIter::Item always agree with <T as IntoIterator>::Item. Concrete IntoIterator impls live next to each collection (Vec, HashSet, HashMap); this trait declaration reserves the surface only.

Methods

fn into_iter(self: Self) -> Self::IntoIter

Trait Index

Bracket indexing surface for values that define an element lookup.

obj[k] type-checks through this trait for user-defined receivers. Vec keeps its compiler-backed bounds-check/runtime path, with this impl providing the same trait surface for bounds and associated-type projection.

Methods

fn at(self: Self, key: i32) -> Self::Output

Trait Display

Convert a value of type Self into a human-readable string.

Implementing Display for a type lets it flow through print, println, assert_eq, assert_ne, to_string, len, and stop. The trait method must return a string derived from the receiver without invoking print itself (otherwise the output path becomes recursive).

Blanket impls below cover the primitive numeric kinds, bool, char, and string; user types add their own impls per receiver.

Methods

fn fmt(val: Self) -> string