Built-in Functions
All built-in functions available in Osprey.
Channel
Signature: Channel(capacity: int) -> Channel<t0>
Creates a buffered channel with a positive capacity.
List
Signature: List() -> List<t0>
Creates a new empty list.
Map
Signature: Map() -> Map<string, t0>
Creates a new empty string-keyed map.
__jsonDecodeClose
Signature: __jsonDecodeClose(document: int) -> Result<int, Error>
Internal primitive of jsonDecode: frees a document the walk has finished with. Call jsonDecode instead.
__jsonDecodeOpen
Signature: __jsonDecodeOpen(text: string) -> Result<int, Error>
Internal primitive of jsonDecode: parses a document into slots for the typed walk. Call jsonDecode instead.
__jsonDecodePythonOpen
Signature: __jsonDecodePythonOpen(text: string) -> Result<int, Error>
Internal primitive of jsonDecodePython: Python last-wins keys, non-finite numbers, and escaped NUL. Native integer and nesting limits apply.
__jsonNodeEnd
Signature: __jsonNodeEnd(document: int, node: int) -> int
Internal primitive of jsonDecode: the slot after a container's last child. Call jsonDecode instead.
__jsonNodeFirst
Signature: __jsonNodeFirst(document: int, node: int) -> int
Internal primitive of jsonDecode: the first slot of a container's children. Call jsonDecode instead.
__jsonNodeFloat
Signature: __jsonNodeFloat(document: int, node: int) -> float
Internal primitive of jsonDecode: a float's value. Call jsonDecode instead.
__jsonNodeInt
Signature: __jsonNodeInt(document: int, node: int) -> int
Internal primitive of jsonDecode: an integer's value. Call jsonDecode instead.
__jsonNodeKey
Signature: __jsonNodeKey(document: int, node: int) -> string
Internal primitive of jsonDecode: the member name of an object's child. Call jsonDecode instead.
__jsonNodeKind
Signature: __jsonNodeKind(document: int, node: int) -> int
Internal primitive of jsonDecode: the kind code of one value. Call jsonDecode instead.
__jsonNodeText
Signature: __jsonNodeText(document: int, node: int) -> string
Internal primitive of jsonDecode: a string's value. Call jsonDecode instead.
__jsonWriteFloat
Signature: __jsonWriteFloat(writer: int, number: float) -> Unit
Internal primitive of jsonEncode: appends one finite float. Call jsonEncode instead.
__jsonWriteInt
Signature: __jsonWriteInt(writer: int, number: int) -> Unit
Internal primitive of jsonEncode: appends one integer. Call jsonEncode instead.
__jsonWriteRaw
Signature: __jsonWriteRaw(writer: int, token: string) -> Unit
Internal primitive of jsonEncode: appends a structural token. Call jsonEncode instead.
__jsonWriteString
Signature: __jsonWriteString(writer: int, text: string) -> Unit
Internal primitive of jsonEncode: appends one quoted, escaped string. Call jsonEncode instead.
__jsonWriterClose
Signature: __jsonWriterClose(writer: int) -> Result<string, Error>
Internal primitive of jsonEncode: closes a writer and returns its document, or the first refusal. Call jsonEncode instead.
__jsonWriterOpen
Signature: __jsonWriterOpen() -> Result<int, Error>
Internal primitive of jsonEncode: opens a single-buffer writer. Call jsonEncode instead.
abs
Signature: abs(value: t0) -> t0
Returns the absolute value with the same numeric type as its input, at any integer or float width. A signed integer minimum performs Arith.overflow; the enclosing policy supplies the result. Float absolute value is total: negative zero becomes positive zero, infinities become positive infinity, and NaN remains NaN.
acos
Signature: acos(x: t0) -> t0
The arc cosine in radians. Total: an argument outside [-1, 1] yields NaN.
acosh
Signature: acosh(x: t0) -> t0
The inverse hyperbolic cosine. Total: an argument below 1.0 yields NaN.
asin
Signature: asin(x: t0) -> t0
The arc sine in radians. Total: an argument outside [-1, 1] yields NaN.
asinh
Signature: asinh(x: t0) -> t0
The inverse hyperbolic sine. Total.
atan
Signature: atan(x: t0) -> t0
The arc tangent in radians, in (-pi/2, pi/2). Total.
atan2
Signature: atan2(y: t0, x: t0) -> t0
Returns the quadrant-aware angle of (x, y) in radians. Signed zeros select the quadrant: atan2(0.0, 0.0) is 0.0; atan2(0.0, -0.0) is pi.
atanh
Signature: atanh(x: t0) -> t0
The inverse hyperbolic tangent. Total: |x| > 1 yields NaN, and exactly 1 yields infinity.
await
Signature: await(fiber: Fiber<t0>) -> t0
Waits for a fiber to finish and returns its result, suspending the current fiber until then.
awaitProcess
Signature: awaitProcess(handle: int) -> int
Waits for a spawned process to complete and returns its exit code. Blocks until the process finishes.
bitAnd
Signature: bitAnd(a: t0, b: t0) -> t0
Bitwise and of two ints. Total; performs no Arith operation.
bitNot
Signature: bitNot(a: t0) -> t0
One's complement of an int. Total; performs no Arith operation.
bitOr
Signature: bitOr(a: t0, b: t0) -> t0
Bitwise or of two ints. Total; performs no Arith operation.
bitXor
Signature: bitXor(a: t0, b: t0) -> t0
Bitwise exclusive or of two ints. Total; performs no Arith operation.
byteAt
Signature: byteAt(text: string, index: int) -> Result<int, Error>
Returns the byte at the given index (0-255), or an error if the index is out of range.
byteLength
Signature: byteLength(text: string) -> int
Returns the number of bytes in the string's UTF-8 encoding.
ceil
Signature: ceil(x: t0) -> t0
The least integer >= x, as a float. Total: ceil of an infinity or NaN is itself.
check
Signature: check(label: string, expected: any, actual: any) -> Unit
Asserts expected equals actual and includes label in a mismatch diagnostic. Execution continues after a mismatch.
checkAll
Signature: checkAll(label: string, conditions: List<bool>) -> Unit
Runs every boolean in a list literal as an independent labeled soft assertion. All conditions run even when an earlier one fails.
checkFalse
Signature: checkFalse(label: string, actual: bool) -> Unit
Labeled assertion that a boolean expression is false.
checkTrue
Signature: checkTrue(label: string, actual: bool) -> Unit
Labeled assertion that a boolean expression is true.
checkedAdd
Signature: checkedAdd(a: t0, b: t0) -> Result<t0, Error>
Named overflow-checked integer addition, returning Result<int, Error>.
checkedMul
Signature: checkedMul(a: t0, b: t0) -> Result<t0, Error>
Named overflow-checked integer multiplication, returning Result<int, Error>.
checkedSub
Signature: checkedSub(a: t0, b: t0) -> Result<t0, Error>
Named overflow-checked integer subtraction, returning Result<int, Error>.
cleanupProcess
Signature: cleanupProcess(handle: int) -> Unit
Cleans up resources associated with a completed process. Should be called after awaitProcess.
codePointAt
Signature: codePointAt(text: string, index: int) -> Result<int, Error>
Returns the Unicode code point that begins at the given byte index. Fails on an invalid index or malformed UTF-8.
codePointWidth
Signature: codePointWidth(codePoint: int) -> Result<int, Error>
Returns how many bytes the given Unicode code point occupies in UTF-8 (1-4).
contains
Signature: contains(s: string, needle: string) -> bool
True if needle appears anywhere in s. Empty needle returns true.
copysign
Signature: copysign(x: t0, y: t0) -> t0
x's magnitude with y's sign. Total; a NaN keeps its payload and takes y's sign bit.
cos
Signature: cos(x: t0) -> t0
The cosine of a float in radians. Total over IEEE doubles; pure, so a kernel may call it or name it.
cosh
Signature: cosh(x: t0) -> t0
The hyperbolic cosine, >= 1.0. Total: a large argument yields infinity.
drop
Signature: drop(s: string, n: int) -> string
Returns s without its first n bytes, including the whole of any character n falls inside. Clamps; never fails.
endsWith
Signature: endsWith(s: string, suffix: string) -> bool
True if s ends with suffix.
erf
Signature: erf(x: t0) -> t0
The error function, the Gaussian CDF up to scaling. Total; erf(+inf) is 1.0 and erf(-inf) is -1.0.
erfc
Signature: erfc(x: t0) -> t0
1 - erf(x), computed without cancellation so the tail keeps its relative precision. Total.
exp
Signature: exp(x: t0) -> t0
e raised to a float. Total: a large argument yields infinity, never an Arith operation. Pure, so softmax kernels name it directly.
expect
Signature: expect(actual: any, expected: any) -> Unit
Asserts two values are equal by canonical rendering. Success payloads compare by value; Errors remain visible as Error(message). On mismatch, marks the enclosing test failed and prints a diagnostic; execution continues.
expectAll
Signature: expectAll(conditions: List<bool>) -> Unit
Runs every boolean in a list literal as an independent soft assertion. All conditions run even when an earlier one fails.
expectFalse
Signature: expectFalse(actual: bool) -> Unit
Asserts that a boolean expression is false.
expectTrue
Signature: expectTrue(actual: bool) -> Unit
Asserts that a boolean expression is true.
expm1
Signature: expm1(x: t0) -> t0
Computes e^x - 1 directly, avoiding loss of small results when subtracting 1 from exp(x). Large positive inputs yield infinity.
fiberDone
Signature: fiberDone(fiber: Fiber<t0>) -> int
Returns 1 if the given fiber has finished, 0 otherwise.
fiber_yield
Signature: fiber_yield(value: int) -> int
Yields control to the fiber scheduler and returns its integer value.
fileSize
Signature: fileSize(path: string) -> Result<int, Error>
The byte length of a regular file, as stat reports it. A missing path or a path that is not a regular file is an Error naming the reason.
filter
Signature: filter(iterator: Iterator<t0>, predicate: (t0) -> bool) -> Iterator<t0>
Filters elements in an iterator based on a predicate function.
filterList
Signature: filterList(list: List<t0>, predicate: (t0) -> bool) -> List<t0>
Returns a new list keeping the elements that satisfy a predicate, in index order.
float16Bits
Signature: float16Bits(x: float16) -> int16
The binary16 pattern of x as an int16, preserving every bit including NaN payloads and signed zero.
float16FromBits
Signature: float16FromBits(bits: int16) -> float16
The float16 the binary16 pattern bits holds. The exact inverse of float16Bits.
float32Bits
Signature: float32Bits(x: float32) -> int32
The binary32 pattern of x as an int32: a bitcast preserving NaN payloads, signed zeros, infinities and subnormals.
float32FromBits
Signature: float32FromBits(bits: int32) -> float32
The float32 the binary32 pattern bits holds. The exact inverse of float32Bits.
floatBits
Signature: floatBits(x: float) -> int
The binary64 word of x as an int: a bitcast, preserving NaN payloads, signed zeros and infinities.
floatFromBits
Signature: floatFromBits(bits: int) -> float
The float the binary64 word bits holds. The exact inverse of floatBits.
floatToInt
Signature: floatToInt(x: t0) -> Result<int, Error>
Checked truncation toward zero: Success(n) when x is finite and inside the int range, Error for NaN, infinities and out-of-range magnitudes.
floor
Signature: floor(x: t0) -> t0
The greatest integer <= x, as a float. Total: floor of an infinity or NaN is itself.
fmod
Signature: fmod(x: t0, y: t0) -> t0
The C fmod: the remainder of x/y with x's sign, truncating toward zero. Total: a zero divisor yields NaN, unlike the % operator's Arith policy.
fold
Signature: fold(iterator: Iterator<t0>, initial: t1, fn: (t1, t0) -> t1) -> t1
Reduces an iterator to a single value by repeatedly applying a function.
foldList
Signature: foldList(list: List<t0>, initial: t1, function: (t1, t0) -> t1) -> t1
Reduces a list to a single value by repeatedly applying a function.
forEach
Signature: forEach(iterator: Iterator<t0>, function: (t0) -> Unit) -> Unit
Applies a function to each element in an iterator.
forEachList
Signature: forEachList(list: List<t0>, function: (t0) -> Unit) -> Unit
Applies function to every list element in index order.
fromCodePoint
Signature: fromCodePoint(codePoint: int) -> Result<string, Error>
Returns the single-character string for a nonzero Unicode scalar, or an error for U+0000 and non-scalars.
fromGpu
Signature: fromGpu(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>) -> Result<List<t0>, Error>
Returns a host list in Success, keeping its element type; a failed device download returns Error with its reason. A valid empty buffer succeeds with an empty list.
gpuDeltaRule
Signature: gpuDeltaRule(state: GpuBuffer<float32>, queries: GpuBuffer<float32>, keys: GpuBuffer<float32>, values: GpuBuffer<float32>, beta: GpuBuffer<float32>, decay: GpuBuffer<float32>, heads: int, dim: int) -> Result<GpuBuffer<float32>, Error>
One token of the recurrent gated delta rule [LLM-DELTA-RULE], fused into one library kernel: each value element decays its state column, recalls through the keys, writes the updated column and reads it out through the queries, in one fixed order on every backend. The result holds heads x dim x dim state cells, then heads x dim outputs, and feeds the next step as its state.
gpuDevice
Signature: gpuDevice() -> string
Returns the name of the backend GPU kernels and products run on: "host", or the adapter OSPREY_GPU selected, such as "metal:0 (Apple M4 Max)" or "opencl:0 (Apple M4 Max)".
gpuFilter
Signature: gpuFilter(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, predicate: (t0) -> bool) -> Result<GpuBuffer<t0>, Error>
Stream compaction: keeps the elements a pure predicate accepts, preserving order. Allocation, dispatch or synchronization failure returns Error with its reason.
gpuFold
Signature: gpuFold(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, initial: t1, combine: (t1, t0) -> t1) -> Result<t1, Error>
Reduces a buffer to one scalar with a pure combine function, applied left to right on every backend. A device runs the fold on one thread, so fold a large buffer by rows and then fold the rows. Allocation, dispatch or synchronization failure returns Error with its reason.
gpuGet
Signature: gpuGet(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, index: int) -> Result<t0, Error>
Bounds-checked read of one element at the buffer's element type. Out of bounds returns Error.
gpuIota
Signature: gpuIota(n: int) -> Result<GpuBuffer<int>, Error>
Returns the index buffer [0, n), or Error for a negative count, byte-size overflow or allocation failure. Zero succeeds with an empty buffer.
gpuLength
Signature: gpuLength(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>) -> int
Returns a GpuBuffer's element count. O(1).
gpuLoad
Signature: gpuLoad(path: string, offset: int, count: int) -> Result<GpuBuffer<float32>, Error>
Reads count little-endian IEEE-754 binary32 values starting at a byte offset of a file into a GpuBuffer<float32>, preserving the binary32 words. A missing file or a short read is an Error carrying the operating system's reason.
gpuLoadTensor
Signature: gpuLoadTensor(path: string, name: string) -> Result<GpuBuffer<t0>, Error>
Reads one named tensor out of a safetensors file into the requested float buffer type: F64 requires float, F32 and BF16 require float32, and F16 requires float16. An unknown name, mismatched request, unsupported dtype or truncated file returns Error.
gpuMap
Signature: gpuMap(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, kernel: (t0) -> t1) -> Result<GpuBuffer<t1>, Error>
Applies a pure kernel to every buffer element independently, one thread per element when OSPREY_GPU selects Metal or OpenCL. The compiler rejects a kernel that performs any effect a handler must discharge at runtime; an effect a static handler has already erased is gone before the check. Allocation, dispatch or synchronization failure returns Error with its reason.
gpuMapFile
Signature: gpuMapFile(path: string, offset: int, count: int) -> Result<GpuBuffer<t0>, Error>
Maps count elements of a file, starting at a byte offset, as a read-only GpuBuffer of the requested numeric type. Nothing is copied: on unified memory the GPU reads the file's own pages.
gpuMatMul
Signature: gpuMatMul(left: GpuBuffer<float> | GpuBuffer<float32>, right: GpuBuffer<t0>, rows: int, inner: int, cols: int) -> Result<GpuBuffer<t0>, Error>
The dense row-major product of a rows x inner float buffer and an inner x cols one, as a rows x cols buffer. Both operands have the same float or float32 element type. Every element accumulates in k order from 0.0 at that width, without fused multiply-add; a length that disagrees with the stated shape is an Error naming the operand.
gpuMatMulQuant
Signature: gpuMatMulQuant(x: GpuBuffer<float32>, weights: GpuBuffer<uint8>, type: string, rows: int, inner: int, cols: int) -> Result<GpuBuffer<float32>, Error>
The product of a rows x inner float32 matrix and cols rows of quantized weights in the named GGUF block format (Q4_K, Q8_0, Q6_K, Q5_K, Q3_K, IQ4_NL, IQ4_XS or IQ3_S), as a rows x cols float32 buffer. Each weight is dequantized, multiplied and added in ggml's block order with every step rounded, in block-range parts added in order (one part above 2^20 outputs, four above 2^16, sixteen otherwise), identically on the host and every device. A length, element type or inner dimension the shape disagrees with returns Error.
gpuScan
Signature: gpuScan(buffer: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, initial: t0, combine: (t0, t0) -> t0) -> Result<GpuBuffer<t0>, Error>
Inclusive prefix scan: element i is combine folded left to right through element i. Allocation, dispatch or synchronization failure returns Error with its reason.
gpuSigmoid
Signature: gpuSigmoid(x: GpuBuffer<float32>) -> Result<GpuBuffer<float32>, Error>
The logistic function 1 / (1 + exp(-x)) of every element [LLM-SIGMOID], as a library kernel on the target's native binary32 exp. Device results agree with the host's within exp's ulps, not bit for bit.
gpuZipWith
Signature: gpuZipWith(a: GpuBuffer<int8> | GpuBuffer<int16> | GpuBuffer<int32> | GpuBuffer<int> | GpuBuffer<uint8> | GpuBuffer<uint16> | GpuBuffer<uint32> | GpuBuffer<float16> | GpuBuffer<float32> | GpuBuffer<float> | GpuBuffer<bool>, b: GpuBuffer<t1>, kernel: (t0, t1) -> t2) -> Result<GpuBuffer<t2>, Error>
Combines two buffers elementwise with a pure binary kernel. The result takes the shorter operand's length. Allocation, dispatch or synchronization failure returns Error with its reason.
httpCloseClient
Signature: httpCloseClient(clientID: int) -> Result<int, Error>
Closes the HTTP client and answers 0, or an Error.
httpCreateClient
Signature: httpCreateClient(base_url: string, timeout: int) -> Result<int, Error>
Creates an HTTP client and answers its handle, or an Error.
httpCreateServer
Signature: httpCreateServer(port: int, address: string) -> Result<int, Error>
Creates an HTTP server bound to the specified port and address, and answers its handle or an Error.
httpDelete
Signature: httpDelete(clientID: int, path: string, headers: string) -> Result<int, Error>
Makes an HTTP DELETE request and answers its status code, or an Error on transport failure.
httpGet
Signature: httpGet(clientID: int, path: string, headers: string) -> Result<int, Error>
Makes an HTTP GET request and answers its status code, or an Error on transport failure.
httpGetResponse
Signature: httpGetResponse(clientID: int, path: string, headers: string) -> Result<int, Error>
Sends an HTTP GET request and returns a response handle for inspecting the status, headers, and body.
httpListen
Signature: httpListen(serverID: int, handler: (string, string, string, string) -> HttpResponse) -> Result<int, Error>
Starts the HTTP server with a request handler and answers 0, or an Error when it cannot bind.
httpPost
Signature: httpPost(clientID: int, path: string, body: string, headers: string) -> Result<int, Error>
Makes an HTTP POST request and answers its status code, or an Error on transport failure.
httpPostResponse
Signature: httpPostResponse(clientID: int, path: string, body: string, headers: string) -> Result<int, Error>
Sends an HTTP POST request and returns a response handle as Result<int, Error>; inspect and free it like a GET response.
httpPut
Signature: httpPut(clientID: int, path: string, body: string, headers: string) -> Result<int, Error>
Makes an HTTP PUT request and answers its status code, or an Error on transport failure.
httpResponseBody
Signature: httpResponseBody(responseID: int) -> Result<string, Error>
Returns a copy of the response body as Result<string, Error>. An invalid or released handle returns Error; the copied body survives httpResponseFree.
httpResponseFree
Signature: httpResponseFree(responseID: int) -> Result<int, Error>
Releases a response handle; an invalid handle or double free returns Error.
httpResponseHeader
Signature: httpResponseHeader(responseID: int, name: string) -> Result<string, Error>
Returns the named header as Result<string, Error>, matching its name without case sensitivity. A missing header or invalid handle returns Error.
httpResponseStatus
Signature: httpResponseStatus(responseID: int) -> int
Returns the HTTP status code, or -1 for an invalid or released response handle.
httpStopServer
Signature: httpStopServer(serverID: int) -> Result<int, Error>
Stops the HTTP server and answers 0, or an Error.
hypot
Signature: hypot(x: t0, y: t0) -> t0
sqrt(xx + yy) without intermediate overflow or underflow. Total.
indexOf
Signature: indexOf(s: string, needle: string) -> Result<int, Error>
Returns the byte index of needle's first occurrence, or Error with 'indexOf: substring not found'.
input
Signature: input() -> string
Reads a string from the user's input.
intDiv
Signature: intDiv(a: t0, b: t0) -> t0
Truncating integer division returning a plain int. A zero divisor performs Arith.remainderByZero and INT64_MIN / -1 performs Arith.overflow; a literal divisor other than 0 and -1 is total.
isEmpty
Signature: isEmpty(s: string | List<T> | Map<string, V>) -> bool
True if a string has zero bytes or a List/Map has zero elements.
join
Signature: join(parts: List<string>, separator: string) -> string
Concatenates parts with separator between each pair.
jsonFree
Signature: jsonFree(document: int) -> Result<int, Error>
Releases a parsed JSON document handle obtained from jsonParse.
jsonGet
Signature: jsonGet(document: int, path: string) -> Result<string, Error>
Returns a JSON scalar at the given path as a string. Arrays, objects, invalid paths, and invalid handles return Error.
jsonLength
Signature: jsonLength(document: int, path: string) -> int
Returns an array length or object member count at the given path, or -1 for an invalid path, handle, or scalar.
jsonParse
Signature: jsonParse(text: string) -> Result<int, Error>
Parses a JSON string and returns an opaque document handle for querying, or an error on malformed input.
kindOf
Signature: kindOf(path: string) -> Result<string, Error>
Classifies one path as "dir", "file" or "other" as stat reports it. A path that cannot be stated is an Error naming the reason.
length
Signature: length(s: string | List<T> | Map<string, V>) -> int
Returns a string's byte length or a List/Map element count.
lines
Signature: lines(s: string) -> List<string>
Splits on '\n'. A trailing newline does not produce an empty entry.
listAppend
Signature: listAppend(list: List<t0>, value: t0) -> List<t0>
Returns a new list with value at the end. Amortized O(1).
listConcat
Signature: listConcat(left: List<t0>, right: List<t0>) -> List<t0>
Returns left ++ right. Same as left + right.
listContains
Signature: listContains(list: List<t0>, value: t0) -> bool
Linear search. Strings compare by content, scalars by value, and managed handles by identity.
listDir
Signature: listDir(path: string) -> Result<List<string>, Error>
Lists one directory's entries as full child paths; directories carry a trailing /, and . and .. never appear. Returns Result<List<string>, Error>.
listGet
Signature: listGet(list: List<t0>, index: int) -> Result<t0, Error>
Returns the element at the given index, or an error if the index is out of range.
listLength
Signature: listLength(list: List<t0>) -> int
Returns the number of elements in a list. O(1).
listPrepend
Signature: listPrepend(list: List<t0>, value: t0) -> List<t0>
Returns a new list with value at the front. O(n).
listReverse
Signature: listReverse(list: List<t0>) -> List<t0>
Returns a new list in reverse order.
listSort
Signature: listSort(list: List<int> | List<string>) -> List<t0>
Returns a new list sorted in ascending order by the elements' natural order: integers by value, strings by byte content. The sort is stable. Only List<int> and List<string> are supported; any other element type is a compile-time error.
listSortBy
Signature: listSortBy(list: List<t0>, compare: (t0, t0) -> int) -> List<t0>
Returns a new list sorted by a comparator, for any element type. The comparator returns a negative int when its first argument comes first, a positive int when it comes second and zero to keep the two in their original order: the sort is stable.
ln
Signature: ln(x: t0) -> t0
The natural logarithm of a float. Total: zero yields negative infinity and a negative argument NaN. Named ln so programs keep the name log for their loggers.
loadTensor
Signature: loadTensor(path: string, name: string) -> Result<List<float>, Error>
Reads one named F64, F32, F16 or BF16 tensor out of a safetensors file as a List<float>, every element widened exactly. Nothing touches the GPU surface.
log10
Signature: log10(x: t0) -> t0
The base-10 logarithm. Total: zero yields negative infinity, a negative argument NaN.
log1p
Signature: log1p(x: t0) -> t0
Computes ln(1 + x) without first rounding 1 + x, preserving small inputs. x = -1 yields negative infinity; x < -1 yields NaN.
log2
Signature: log2(x: t0) -> t0
The base-2 logarithm. Total: zero yields negative infinity, a negative argument NaN.
makeDir
Signature: makeDir(path: string) -> Result<int, Error>
Creates one directory, idempotently: an existing directory is success. Returns Result<int, Error>.
map
Signature: map(iterator: Iterator<t0>, fn: (t0) -> t1) -> Iterator<t1>
Transforms each element in an iterator using a function, returning a new iterator.
mapContains
Signature: mapContains(map: Map<string, t0>, key: string) -> bool
True iff key is present in map.
mapGet
Signature: mapGet(map: Map<string, t0>, key: string) -> Result<t0, Error>
Returns the value associated with the key, or an error if the key is absent.
mapKeys
Signature: mapKeys(map: Map<string, t0>) -> List<string>
All keys of the map as a list. Order unspecified.
mapLength
Signature: mapLength(map: Map<string, t0>) -> int
Returns the number of entries in a map. O(1).
mapList
Signature: mapList(list: List<t0>, function: (t0) -> t1) -> List<t1>
Returns a new list by applying a function to every element, in index order.
mapMerge
Signature: mapMerge(left: Map<string, t0>, right: Map<string, t0>) -> Map<string, t0>
Right-biased union. Same as left + right.
mapRemove
Signature: mapRemove(map: Map<string, t0>, key: string) -> Map<string, t0>
Returns a new map without key. No-op if key is absent.
mapSet
Signature: mapSet(map: Map<string, t0>, key: string, value: t0) -> Map<string, t0>
Returns a new map with key bound to value (replaces prior binding).
mapValues
Signature: mapValues(map: Map<string, t0>) -> List<t0>
All values of the map as a list. Order matches mapKeys.
padEnd
Signature: padEnd(s: string, targetLength: int, fill: string) -> Result<string, Error>
Pads s on the right with copies of fill to reach targetLength bytes.
padStart
Signature: padStart(s: string, targetLength: int, fill: string) -> Result<string, Error>
Pads s on the left with copies of fill to reach targetLength bytes.
parseFloat
Signature: parseFloat(s: string) -> Result<float, Error>
Strict finite base-10 floating-point parser. Rejects surrounding whitespace, NaN/infinity spellings, and hexadecimal floats.
parseInt
Signature: parseInt(s: string) -> Result<int, Error>
Strict base-10 signed-int parser. No whitespace tolerance.
pow
Signature: pow(x: t0, y: t0) -> t0
x raised to y, C pow semantics: pow(0.0, 0.0) is 1.0, a negative base needs an integer exponent, and an overflow yields infinity — never a fault.
Signature: print(value: int8 | int16 | int32 | int | uint8 | uint16 | uint32 | float16 | float32 | float | bool | string | Unit | any | Result<printable, printable>) -> Unit
Writes a supported scalar or Result representation followed by a newline. Unit renders as 0.
random
Signature: random() -> int
A cryptographically-secure uniform random non-negative integer (0 .. 2^63-1), drawn fresh from the OS entropy source. Unseeded and unpredictable.
randomBelow
Signature: randomBelow(n: int) -> Result<int, Error>
A cryptographically-secure uniform random integer in [0, n), unbiased by rejection sampling. Returns Result<int, Error> when n is positive and Error otherwise.
range
Signature: range(start: int, end: int) -> Iterator<int>
Creates an iterator that generates numbers from start to end (exclusive).
readFile
Signature: readFile(filename: string) -> Result<string, Error>
Reads a text file into a Result<string, Error>. The NUL-terminated string ABI is not a binary-buffer interface.
readFileBytes
Signature: readFileBytes(path: string, offset: int, count: int) -> Result<List<int>, Error>
Reads at most count bytes from byte offset of a binary file as a List<int> of 0 to 255; NUL is an ordinary byte. The list is shorter only when the file ends first.
recv
Signature: recv(channel: Channel<t0>) -> t0
Blocks while the channel is empty, then receives its oldest value.
repeat
Signature: repeat(s: string, n: int) -> Result<string, Error>
Concatenates s with itself n times. A negative n returns Error.
replace
Signature: replace(s: string, needle: string, replacement: string) -> Result<string, Error>
Replaces every occurrence of needle. An empty needle returns Error.
reverse
Signature: reverse(s: string) -> string
Reverses byte order.
round
Signature: round(x: t0) -> t0
The nearest integer to x, as a float, with halfway cases rounded to even — Python's round and numpy's rounding, not C's half-away-from-zero. Total.
satAdd
Signature: satAdd(a: t0, b: t0) -> t0
Total saturating addition: overflow clamps to the int range and performs no Arith operation.
satMul
Signature: satMul(a: t0, b: t0) -> t0
Total saturating multiplication: overflow clamps to the int range and performs no Arith operation.
satSub
Signature: satSub(a: t0, b: t0) -> t0
Total saturating subtraction: overflow clamps to the int range and performs no Arith operation.
send
Signature: send(channel: Channel<t0>, value: t0) -> Unit
Blocks while the channel is full, then sends a value and returns Unit.
shiftLeft
Signature: shiftLeft(a: t0, n: t0) -> t0
a << n, total: a count outside 0..63 yields 0, the limit of repeated shifting. Performs no Arith operation.
shiftRight
Signature: shiftRight(a: t0, n: t0) -> t0
Arithmetic right shift a >> n, total: a count outside 0..63 yields 0 for a >= 0 and -1 for a < 0. Performs no Arith operation.
shiftRightLogical
Signature: shiftRightLogical(a: t0, n: t0) -> t0
Logical right shift of a's bits, total: a count outside 0..63 yields 0. Performs no Arith operation.
signalDependencies
Signature: signalDependencies(work: () -> t0) -> List<string>
Returns the checked static signal operations a callback may read, without invoking it. An unresolved remainder is <unknown>.
signalRefresh
Signature: signalRefresh(cached: { dependencies: List<string>, revision: int, value: t0 }, changed: List<string>, work: () -> t0) -> { dependencies: List<string>, revision: int, value: t0 }
Rebuilds an immutable snapshot when a dependency changes, its callback dependency set changes or dependencies remain unknown. Otherwise returns the cached snapshot.
signalSnapshot
Signature: signalSnapshot(work: () -> t0) -> { dependencies: List<string>, revision: int, value: t0 }
Runs a computation once and returns its value, compiler-derived signal dependencies and revision 1.
sin
Signature: sin(x: t0) -> t0
The sine of a float in radians. Total over IEEE doubles; pure, so a kernel may call it or name it.
sinh
Signature: sinh(x: t0) -> t0
The hyperbolic sine. Total: a large argument yields infinity.
sleep
Signature: sleep(milliseconds: int) -> Unit
Pauses execution for the specified number of milliseconds.
spawnProcess
Signature: spawnProcess(command: string, callback: (int, int, string) -> Unit) -> Result<int, Error>
Spawns a process and reports stdout, stderr and exit events through the required callback. Returns a handle for the running process.
split
Signature: split(s: string, separator: string) -> Result<List<string>, Error>
Splits s on separator. An empty separator returns Error.
sqrt
Signature: sqrt(x: t0) -> t0
The square root of a float. Total over IEEE doubles: a negative argument yields NaN. Pure, so a kernel may call it or name it.
startsWith
Signature: startsWith(s: string, prefix: string) -> bool
True if s begins with prefix.
structuralEquals
Signature: structuralEquals(a: t0, b: t0) -> bool
Compares two values by their contents, walking both completely, so its cost grows with their size; == deliberately does not do this. Both operands must be one type whose every part has a decided equality — a function, a runtime handle, any or Result anywhere inside is a compile error. NaN stays unequal to itself, including inside a record, list, map or union.
substring
Signature: substring(s: string, start: int, end: int) -> Result<string, Error>
Extracts the byte interval s[start, end), even inside a UTF-8 character. Invalid or inverted bounds return Error.
take
Signature: take(s: string, n: int) -> string
Returns the first n bytes of s, including the whole of any character n falls inside. Clamps; never fails.
tan
Signature: tan(x: t0) -> t0
The tangent of a float in radians. Total: an argument at a pole yields the large finite neighbour, never a fault.
tanh
Signature: tanh(x: t0) -> t0
Returns the hyperbolic tangent in [-1, 1] for non-NaN inputs. Large magnitudes round to -1.0 or 1.0; NaN remains NaN.
termClear
Signature: termClear() -> int
Clears the terminal screen.
termCols
Signature: termCols() -> int
Returns the terminal width in columns, or -1 when unavailable.
termHideCursor
Signature: termHideCursor() -> int
Hides the terminal cursor.
termMoveCursor
Signature: termMoveCursor(row: int, col: int) -> int
Moves the terminal cursor to the given row and column.
termRawMode
Signature: termRawMode(enabled: int) -> Unit
Enables (1) or disables (0) raw terminal input mode, so keypresses arrive unbuffered.
termReadKey
Signature: termReadKey() -> Result<string, Error>
Reads a single keypress from the terminal and returns it as a string.
termRows
Signature: termRows() -> int
Returns the terminal height in rows, or -1 when unavailable.
termShowCursor
Signature: termShowCursor() -> int
Shows the terminal cursor.
test
Signature: test(name: string, body: () -> t0) -> Unit
Runs body as one named test case and prints a TAP result line. A case fails when any assertion inside it fails; the program exits non-zero if any case failed.
toFloat
Signature: toFloat(value: t0) -> float
Converts any numeric type to float, rounding to nearest even. Exact for integer magnitudes up to 2^53 and for wider float sources only when representable. Total, so it returns a bare float rather than a Result.
toFloat16
Signature: toFloat16(value: t0) -> float16
Converts any numeric type to float16, rounding to nearest even. Overflow becomes signed infinity; 65520.0 is the first finite double that rounds to infinity. Total and pure.
toFloat32
Signature: toFloat32(value: t0) -> float32
Converts any numeric type to float32, rounding to nearest even. Overflow becomes signed infinity; widening from float16 is exact. Total and pure.
toGpu
Signature: toGpu(source: List<int8> | List<int16> | List<int32> | List<int> | List<uint8> | List<uint16> | List<uint32> | List<float16> | List<float32> | List<float> | List<bool> | Iterator<int8> | Iterator<int16> | Iterator<int32> | Iterator<int> | Iterator<uint8> | Iterator<uint16> | Iterator<uint32> | Iterator<float16> | Iterator<float32> | Iterator<float> | Iterator<bool>) -> Result<GpuBuffer<t0>, Error>
Returns a dense GpuBuffer in Success, or Error with the allocation reason, for a list of numeric scalars at any width or bools. Also consumes an iterator pipeline, replaying its map/filter stages into the buffer with no list in between.
toInt
Signature: toInt(value: t0) -> int
Converts any integer type to int. Exact and total: every integer type fits.
toInt16
Signature: toInt16(value: t0) -> int16
Converts any integer type to int16. A value outside -32768..32767 performs Arith.overflow with the source as its operand.
toInt32
Signature: toInt32(value: t0) -> int32
Converts any integer type to int32. A value outside the 32-bit signed range performs Arith.overflow with the source as its operand.
toInt8
Signature: toInt8(value: t0) -> int8
Converts any integer type to int8. A value outside -128..127 performs Arith.overflow with the source as its operand.
toList
Signature: toList(iterator: Iterator<t0>) -> List<t0>
Runs an iterator pipeline once and collects every element it yields into a list, in order.
toLowerCase
Signature: toLowerCase(s: string) -> string
ASCII-aware lowercase.
toString
Signature: toString(value: int8 | int16 | int32 | int | uint8 | uint16 | uint32 | float16 | float32 | float | bool | string | Unit | any | Result<printable, printable>) -> string
Formats the same scalar and Result values accepted by print without writing output. Unit renders as 0.
toUint16
Signature: toUint16(value: t0) -> uint16
Converts any integer type to uint16. A value outside 0..65535 performs Arith.overflow with the source as its operand.
toUint32
Signature: toUint32(value: t0) -> uint32
Converts any integer type to uint32. A value outside the 32-bit unsigned range performs Arith.overflow with the source as its operand.
toUint8
Signature: toUint8(value: t0) -> uint8
Converts any integer type to uint8. A value outside 0..255 performs Arith.overflow with the source as its operand.
toUpperCase
Signature: toUpperCase(s: string) -> string
Converts ASCII letters to uppercase; other bytes are unchanged.
trim
Signature: trim(s: string) -> string
Removes leading and trailing ASCII whitespace.
trimEnd
Signature: trimEnd(s: string) -> string
Removes trailing ASCII whitespace.
trimStart
Signature: trimStart(s: string) -> string
Removes leading ASCII whitespace.
trunc
Signature: trunc(x: t0) -> t0
The integer part of x toward zero, as a float. Total.
websocketClose
Signature: websocketClose(wsID: int) -> int
Closes the WebSocket connection and returns the runtime status.
websocketConnect
Signature: websocketConnect(url: string) -> int
Connects to a ws:// URL and returns a connection handle, or a negative error. wss:// is rejected; incoming frames have no receive callback.
websocketCreateServer
Signature: websocketCreateServer(port: int, address: string, path: string) -> int
Creates a WebSocket server and returns its handle, or a negative runtime error.
websocketKeepAlive
Signature: websocketKeepAlive() -> Unit
Blocks until SIGINT or SIGTERM so server threads remain alive.
websocketSend
Signature: websocketSend(wsID: int, message: string) -> int
Sends one text frame and returns 0 or a negative runtime error.
websocketServerBroadcast
Signature: websocketServerBroadcast(serverID: int, message: string) -> int
Broadcasts one text frame and returns the number of connections written, or a negative error.
websocketServerListen
Signature: websocketServerListen(serverID: int) -> int
Starts the WebSocket server and returns 0 or a negative runtime error.
words
Signature: words(s: string) -> List<string>
Splits on runs of ASCII whitespace; empty results are dropped.
wrapAdd
Signature: wrapAdd(a: t0, b: t0) -> t0
Total two's-complement addition: overflow wraps and performs no Arith operation.
wrapMul
Signature: wrapMul(a: t0, b: t0) -> t0
Total two's-complement multiplication: overflow wraps and performs no Arith operation.
wrapSub
Signature: wrapSub(a: t0, b: t0) -> t0
Total two's-complement subtraction: overflow wraps and performs no Arith operation.
writeFile
Signature: writeFile(filename: string, content: string) -> Result<int, Error>
Writes text, creating the file if needed. Returns Result<int, Error> containing the number of bytes written.
yield
Signature: yield() -> Unit
Yields control from the current fiber, letting other ready fibers run.