Quartz v5.25

Quartz Intrinsics

Intrinsics are Quartz’s semantic primitives. Everything else is sugar that desugars to these.

Total: 28 intrinsics

Design Principles

  1. If it can be a library function, it’s NOT an intrinsic
  2. Intrinsics are the compiler’s syscalls—stable ABI
  3. Adding an intrinsic requires discussion
  4. Removing an intrinsic requires migration path

Tier 0: Control Flow

IntrinsicSignatureLLVM
@ret(val: i64) -> !ret i64
@br(cond: i64, then: Label, else: Label) -> !br i1, label, label
@jmp(target: Label) -> !br label
@unreachable() -> !unreachable

Tier 1: Memory

IntrinsicSignatureDescription
@alloc(words: i64) -> i64Heap allocate N words
@load(ptr: i64, offset: i64) -> i64Load word at ptr[offset]
@store(ptr: i64, offset: i64, val: i64) -> ()Store word at ptr[offset]

Tier 2: Arithmetic

IntrinsicSignatureDescription
@add(a: i64, b: i64) -> i64Integer addition
@sub(a: i64, b: i64) -> i64Integer subtraction
@mul(a: i64, b: i64) -> i64Integer multiplication
@div(a: i64, b: i64) -> i64Integer division (signed)
@mod(a: i64, b: i64) -> i64Integer modulo
@neg(a: i64) -> i64Integer negation

Tier 3: Comparison

IntrinsicSignatureDescription
@eq(a: i64, b: i64) -> i64Equal (returns 0 or 1)
@ne(a: i64, b: i64) -> i64Not equal
@lt(a: i64, b: i64) -> i64Less than (signed)
@le(a: i64, b: i64) -> i64Less or equal
@gt(a: i64, b: i64) -> i64Greater than
@ge(a: i64, b: i64) -> i64Greater or equal

Tier 4: Values & Tagging

IntrinsicSignatureDescription
@truthy(val: i64) -> i64Ruby truthiness (only nil/false are falsy)
@tag(val: i64) -> i64Get type tag from value
@box_int(n: i64) -> i64Tag raw int as Quartz integer
@unbox_int(val: i64) -> i64Extract raw int from tagged value

Tier 5: Strings

IntrinsicSignatureDescription
@str_size(s: i64) -> i64String length in codepoints
@str_concat(a: i64, b: i64) -> i64Concatenate two strings
@str_eq(a: i64, b: i64) -> i64String equality

Tier 6: Calls

IntrinsicSignatureDescription
@call(fn: i64, args: i64, argc: i64) -> i64Indirect function call

Builtins (Not Intrinsics)

Builtins are compiler-provided functions that aren’t semantic primitives. They’re implemented in codegen but could eventually move to a standard library.

Total: ~250+ builtins (registered in self-hosted/middle/typecheck_builtins.qz)

I/O

BuiltinSignatureDescription
puts(s: String, newline?: Bool) -> VoidPrint string with trailing newline
print(s: String) -> VoidPrint string without trailing newline
eputs(s: String, newline?: Bool) -> VoidPrint to stderr, auto-appends trailing newline (do not pass "msg\n" — you will get msg\n\n)
eprint(s: String) -> VoidPrint to stderr without trailing newline
print_int(n: Int) -> VoidPrint integer with trailing newline
eprint_int(n: Int) -> VoidPrint integer to stderr with trailing newline
read_file(path: String) -> StringRead entire file contents
write_file(path: String, content: String) -> IntWrite string to file
read_line() -> StringRead line from stdin

String Functions — Codepoint Level (default)

Strings in Quartz are UTF-8 encoded. The default string API operates at codepoint level: .size returns codepoint count, s[i] returns the codepoint at codepoint index i, .slice(a, b) extracts by codepoint range. Codepoint indexing is O(n) per access.

BuiltinSignatureDescription
str_size(s: String) -> IntString length in codepoints
str_char_at(s: String, i: Int) -> IntCodepoint value at codepoint index
str_slice(s: String, start: Int, end: Int) -> StringSubstring by codepoint range [start, end)
str_find(s: String, needle: String) -> Option<Int>Find substring, returns codepoint offset
str_codepoint_at(s: String, i: Int) -> IntAlias for str_char_at (deprecated)
str_len_utf8(s: String) -> IntAlias for str_size (deprecated)
str_from_codepoint(cp: Int) -> StringCodepoint to string
str_concat(a: String, b: String) -> StringConcatenate two strings
str_contains(s: String, needle: String) -> BoolCheck substring existence
str_split(s: String, delim: String) -> Vec<String>Split into vector
str_from_int(n: Int) -> StringInteger to string
str_from_char(code: Int) -> StringChar code to single-char string
str_eq(a: String, b: String) -> BoolString equality
str_cmp(a: String, b: String) -> IntString comparison (-1/0/1)
str_hash(s: String) -> IntString hash
str_to_int(s: String) -> IntParse string to integer
str_to_f64(s: String) -> F64Parse string to float
f64_to_str(f: F64) -> StringFloat to string
str_starts_with(s: String, prefix: String) -> BoolCheck prefix
str_ends_with(s: String, suffix: String) -> BoolCheck suffix
str_downcase(s: String) -> StringLowercase
str_upcase(s: String) -> StringUppercase
str_trim(s: String) -> StringTrim whitespace
str_trim_left(s: String) -> StringTrim left whitespace
str_trim_right(s: String) -> StringTrim right whitespace
str_replace(s: String, old: String, new: String) -> StringReplace occurrences
str_reverse(s: String) -> StringReverse string
str_repeat(s: String, n: Int) -> StringRepeat N times
str_count(s: String, sub: String) -> IntCount occurrences
str_join(v: Vec<String>, sep: String) -> StringJoin vector with separator
str_is_empty(s: String) -> BoolCheck if empty
str_substr(s: String, start: Int, len: Int) -> StringSubstring by offset+length
str_pad_left(s: String, width: Int, pad: String) -> StringLeft pad
str_pad_right(s: String, width: Int, pad: String) -> StringRight pad
str_chars(s: String) -> Vec<Int>String to codepoint vector

String Functions — Byte Level

Byte-level intrinsics provide O(1) indexed access to the raw UTF-8 bytes. Use these for performance-critical code, ASCII protocol parsing, or when you need byte-exact control. Available as both free functions and UFCS methods (e.g., s.byte_len()).

BuiltinSignatureDescription
str_byte_len(s: String) -> IntString length in bytes, O(1)
str_byte_at(s: String, i: Int) -> IntByte value at byte index, O(1)
str_byte_slice(s: String, start: Int, end: Int) -> StringSubstring by byte range [start, end), O(1)
str_byte_find(s: String, needle: String) -> Option<Int>Find substring, returns byte offset
str_bytes(s: String) -> Vec<Int>String to byte value vector
str_is_valid_utf8(s: String) -> BoolValidate UTF-8 encoding

Character Classification

BuiltinSignatureDescription
is_digit(ch: Int) -> BoolIs 0-9
is_alpha(ch: Int) -> BoolIs a-z, A-Z
is_alnum(ch: Int) -> BoolIs alphanumeric
is_whitespace(ch: Int) -> BoolIs space/tab/newline
is_upper(ch: Int) -> BoolIs uppercase
is_lower(ch: Int) -> BoolIs lowercase

Control Flow

BuiltinSignatureDescription
exit(code: Int) -> !Exit process
assert(cond: Int) -> VoidAbort if false
panic(msg: String) -> !Panic with message
unreachable() -> !Mark unreachable code
expect(cond: Int) -> IntAssert with return

Vector Operations

All Vec builtins support UFCS. Prefer v.push(x) over vec_push(v, x).

BuiltinUFCSDescription
vec_new<T>Create new dynamic array
vec_new_filledCreate filled vector
vec_push<T>v.push(val)Append to end
vec_pop<T>v.pop()Remove last — Option (v5.26)
vec_get<T>v.get(idx) or v[idx]Get value at index
vec_set<T>v.set(idx, val) or v[idx] = valSet value at index
vec_get_unchecked<T>Get without bounds check
vec_set_unchecked<T>Set without bounds check
vec_size<T>v.sizeGet length
vec_free<T>v.free()Free memory
vec_clearv.clear()Remove all elements
vec_containsv.contains(val)Check if contains value
vec_index_ofv.index_of(val)Find index — Option (v5.26)
vec_insertv.insert(idx, val)Insert at index
vec_deletev.delete(idx)Delete at index
vec_joinv.join(sep)Join strings
vec_reversev.reverse()Reverse copy
vec_clonev.clone()Deep copy
vec_sortv.sort()In-place sort ascending
vec_sort_byv.sort_by(cmp)Sort with comparator

Binary Vec I/O

BuiltinSignatureDescription
vec_save(v: Vec<Int>, path: String) -> IntSave Vec to file
vec_load(path: String) -> Vec<Int>Load Vec from file
strvec_save(v: Vec<String>, path: String) -> IntSave string Vec to file
strvec_load(path: String) -> Vec<String>Load string Vec from file

Map Operations

Quartz has a unified Map<K,V> type. The compiler dispatches to string-key or integer-key implementations based on the key type. All Map builtins support UFCS. Prefer m.get(k) over map_get(m, k).

BuiltinUFCSDescription
map_new<K,V>Create new map
map_get<K,V>m.get(key)Get value — Option
map_set<K,V>m.set(key, val)Set key-value
map_has<K,V>m.has(key)Check key exists
map_delete<K,V>m.delete(key)Delete key
map_free<K,V>m.free()Free memory
map_clearm.clear()Remove all entries
map_sizem.size()Number of entries
map_keysm.keys()All keys
map_valuesm.values()All values

Set Operations

All Set builtins support UFCS. Prefer s.add(x) over set_add(s, x).

BuiltinUFCSDescription
set_newCreate new set
set_adds.add(val)Add element
set_hass.has(val)Check membership
set_deletes.delete(val)Remove element
set_sizes.size()Number of elements
set_memberss.members()All members
set_clears.clear()Remove all
set_frees.free()Free memory
set_unions.union(other)Union
set_intersections.intersection(other)Intersection
set_differences.difference(other)Difference
set_is_subsets.is_subset(other)Subset check

StringBuilder

All StringBuilder builtins support UFCS. Prefer sb.append(s) over sb_append(sb, s).

BuiltinUFCSDescription
sb_newCreate builder
sb_appendsb.append(s)Append string
sb_append_intsb.append_int(n)Append integer
sb_append_charsb.append_char(c)Append char code
sb_to_stringsb.to_string()Build string
sb_lensb.size()Current length
sb_clearsb.clear()Reset builder
sb_freesb.free()Free memory

Option/Result

All Option/Result builtins support UFCS. Prefer opt.unwrap_or(0) over unwrap_or(opt, 0). Also use the is keyword for variant checks: opt is Some, result is Err.

BuiltinUFCSDescription
unwrapopt.unwrap()Unwrap or panic
unwrap_oropt.unwrap_or(fallback)Unwrap with default
option_is_someopt.is_some() or opt is SomeCheck if Some
option_is_noneopt.is_none() or opt is NoneCheck if None
option_mapopt.map(fn)Transform inner value
option_getopt.get()Extract value
option_freeopt.free()Free option
option_someConstruct Some
option_noneConstruct None

Arena Operations (v5.1+)

BuiltinSignatureDescription
arena_new() -> ArenaCreate new arena (4KB default)
arena_alloc(arena: Arena, size: Int) -> IntAllocate bytes
arena_alloc<T>(arena: Arena) -> Ptr<T>Typed allocation
arena_reset(arena: Arena) -> VoidReset (preserves chain)
arena_destroy(arena: Arena) -> VoidFree all blocks
arena_bytes_used(arena: Arena) -> IntTotal allocated bytes
arena_capacity(arena: Arena) -> IntTotal capacity
arena_alloc_count(arena: Arena) -> IntNumber of allocations
arena_block_count(arena: Arena) -> IntNumber of blocks

Bump Allocator

BuiltinSignatureDescription
bump_new(capacity: Int) -> IntCreate bump allocator
bump_alloc(bump: Int, size: Int) -> IntAllocate (branchless)
bump_reset(bump: Int) -> VoidReset to start
bump_free(bump: Int) -> VoidFree allocator

Pool Allocator

BuiltinSignatureDescription
pool_new(elem_size: Int, count: Int) -> PoolCreate pool
pool_alloc(pool: Pool) -> IntAllocate slot
pool_free(pool: Pool, ptr: Int) -> VoidFree slot
pool_destroy(pool: Pool) -> VoidDestroy pool
pool_capacity(pool: Pool) -> IntTotal slots
pool_alloc_count(pool: Pool) -> IntActive allocations
pool_free_count(pool: Pool) -> IntFree slots

Arena Pools (v5.2+)

BuiltinSignatureDescription
arena_pool_new(arena_size: Int, count: Int) -> ArenaPoolCreate pool of arenas
arena_pool_acquire(pool: ArenaPool) -> ArenaGet available arena
arena_pool_release(pool: ArenaPool, arena: Arena) -> VoidReturn arena (auto-reset)
arena_pool_destroy(pool: ArenaPool) -> VoidFree pool and all arenas
arena_pool_available(pool: ArenaPool) -> IntAvailable arenas
arena_pool_capacity(pool: ArenaPool) -> IntTotal arenas

Type-safe Pointers (v5.2+)

BuiltinSignatureDescription
ptr_read<T>(ptr: Int) -> TRead typed value
ptr_write<T>(ptr: Int, value: T) -> VoidWrite typed value
ptr_alloc(n: Int) -> IntAllocate n * 8 bytes
ptr_add(ptr: Int, offset: Int) -> IntPointer arithmetic
ptr_is_null(ptr: CPtr) -> BoolNull check
addr_of(var: T) -> IntAddress of variable

FFI / C Interop

BuiltinSignatureDescription
string_to_cstr(s: String) -> CPtrString to C string (strdup)
cstr_to_string(p: CPtr) -> StringC string to Quartz string
cptr_to_string_with_len(p: CPtr, len: Int) -> StringBuffer with length to String
cptr_to_int(p: CPtr) -> IntPointer to integer
int_to_cptr(i: Int) -> CPtrInteger to pointer
ptr_read_byte(p: CPtr) -> IntRead byte
ptr_write_byte(p: CPtr, val: Int) -> VoidWrite byte
qz_malloc(size: Int) -> CPtrAllocate memory
qz_free(p: CPtr) -> VoidFree memory
field_offset<T>(field: String) -> IntByte offset of field

Type Conversion

BuiltinSignatureDescription
to_int(f: F64) -> IntFloat to integer (truncates)
to_f64(n: Int) -> F64Integer to double
to_f32(n: Int) -> F32Integer to float
to_i8(n: Int) -> I8Truncate to signed 8-bit
to_i16(n: Int) -> I16Truncate to signed 16-bit
to_i32(n: Int) -> I32Truncate to signed 32-bit
to_u8(n: Int) -> U8Truncate to unsigned 8-bit
to_u16(n: Int) -> U16Truncate to unsigned 16-bit
to_u32(n: Int) -> U32Truncate to unsigned 32-bit
to_u64(n: Int) -> IntIdentity (U64 = Int width)
as_string(val: Int) -> StringCoerce to string
as_int(val: String) -> IntCoerce to int
as_int_generic(val: T) -> IntType erasure (identity)
as_type<T>(val: Int) -> TType recovery (identity)

Bitwise Operations

BuiltinSignatureDescription
bor(a: Int, b: Int) -> IntBitwise OR
band(a: Int, b: Int) -> IntBitwise AND
bxor(a: Int, b: Int) -> IntBitwise XOR
bnot(a: Int) -> IntBitwise NOT
shl(a: Int, b: Int) -> IntShift left
shr(a: Int, b: Int) -> IntShift right
popcount(n: Int) -> IntCount set bits
clz(n: Int) -> IntCount leading zeros
ctz(n: Int) -> IntCount trailing zeros
bswap(n: Int) -> IntByte swap
rotl(n: Int, k: Int) -> IntRotate left
rotr(n: Int, k: Int) -> IntRotate right

Concurrency (v5.5+)

BuiltinSignatureDescription
channel_new(capacity: Int) -> IntCreate buffered channel
send(ch: Int, val: Int) -> VoidSend (blocks if full)
recv(ch: Int) -> IntReceive (blocks if empty)
recv_timeout(ch: Int, ms: Int) -> IntReceive with timeout
try_send(ch: Int, val: Int) -> BoolNon-blocking send
try_recv(ch: Int) -> BoolNon-blocking receive
channel_close(ch: Int) -> VoidClose channel
channel_closed(ch: Int) -> BoolCheck if closed
channel_len(ch: Int) -> IntBuffered items
mutex_new(init: Int) -> IntCreate mutex
mutex_lock(m: Int) -> IntLock (returns value)
mutex_unlock(m: Int, val: Int) -> VoidUnlock (stores value)
mutex_try_lock(m: Int) -> BoolNon-blocking lock
channel_free(ch: Int) -> VoidFree channel resources
mutex_free(m: Int) -> VoidFree mutex resources
pool_shutdown() -> VoidShut down thread pool

RWLock (v5.13+)

BuiltinSignatureDescription
rwlock_new(init: Int) -> IntCreate read-write lock with initial value
rwlock_read(rw: Int) -> IntAcquire read lock, return value
rwlock_read_unlock(rw: Int) -> VoidRelease read lock
rwlock_write(rw: Int) -> IntAcquire write lock, return value
rwlock_write_unlock(rw: Int, val: Int) -> VoidStore new value, release write lock
rwlock_free(rw: Int) -> VoidDestroy and free rwlock

WaitGroup (v5.13+)

BuiltinSignatureDescription
waitgroup_new(count: Int) -> IntCreate waitgroup with initial count
waitgroup_done(wg: Int) -> VoidDecrement count; signal when zero
waitgroup_wait(wg: Int) -> VoidBlock until count reaches zero
waitgroup_free(wg: Int) -> VoidFree waitgroup resources

OnceCell (v5.13+)

BuiltinSignatureDescription
oncecell_new() -> IntCreate empty once-cell
oncecell_get_or_init(cell: Int, init: Fn(): Int) -> IntInitialize or return cached value
oncecell_get(cell: Int) -> IntGet value (aborts if uninitialized)
oncecell_free(cell: Int) -> VoidFree once-cell resources

Atomics (v5.5+)

BuiltinSignatureDescription
atomic_new(val: Int) -> AtomicIntCreate atomic integer
atomic_load(a: AtomicInt, ord?: Int) -> IntAtomic load
atomic_store(a: AtomicInt, val: Int, ord?: Int) -> VoidAtomic store
atomic_add(a: AtomicInt, val: Int, ord?: Int) -> IntAtomic add (returns old)
atomic_sub(a: AtomicInt, val: Int, ord?: Int) -> IntAtomic subtract (returns old)
atomic_exchange(a: AtomicInt, val: Int, ord?: Int) -> IntExchange (returns old)
atomic_cas(a: AtomicInt, exp: Int, new: Int, ord?: Int) -> BoolCompare-and-swap
fence(ordering: Int) -> VoidFull memory barrier
compiler_fence(ordering: Int) -> VoidCompiler-only fence

F64 Math

BuiltinSignatureDescription
f64_sqrt(f: F64) -> F64Square root
f64_sin/cos/tan(f: F64) -> F64Trigonometric
f64_asin/acos/atan(f: F64) -> F64Inverse trig
f64_atan2(y: F64, x: F64) -> F64Two-argument arctangent
f64_floor/ceil/round(f: F64) -> F64Rounding
f64_abs(f: F64) -> F64Absolute value
f64_log/log2/log10(f: F64) -> F64Logarithms
f64_exp(f: F64) -> F64Exponential
f64_pow(base: F64, exp: F64) -> F64Power
f64_min/f64_max(a: F64, b: F64) -> F64Min/max

Regex

BuiltinSignatureDescription
regex_replace(s: String, pat: String, rep: String) -> StringFirst match replace
regex_replace_all(s: String, pat: String, rep: String) -> StringAll matches replace
regex_split(s: String, pat: String) -> Vec<String>Split by pattern
regex_count(s: String, pat: String) -> IntCount matches
regex_matches(s: String, pat: String) -> Vec<String>All match strings
regex_match_start(s: String, pat: String) -> Option<Int>Match start index
regex_match_end(s: String, pat: String) -> Option<Int>Match end index
regex_capture_named(s: String, pat: String, name: String) -> StringNamed capture

File System

BuiltinSignatureDescription
file_exists(path: String) -> BoolCheck file existence
file_size(path: String) -> IntFile size in bytes
file_delete(path: String) -> IntDelete file
file_bytes(path: String) -> Vec<Int>Read as byte array
file_chars(path: String) -> Vec<Int>Read as char array
file_lines(path: String) -> Vec<String>Read as line array
open_file(path: String, mode: Int) -> IntOpen file descriptor
close_file(fd: Int) -> IntClose file descriptor
fwrite(fd: Int, data: String) -> IntWrite to file descriptor
fread(fd: Int, len: Int) -> StringRead from file descriptor
mkdir(path: String) -> IntCreate directory
rmdir(path: String) -> IntRemove directory
readdir(path: String) -> Vec<String>List directory entries
rename(old: String, new: String) -> IntRename file/directory

Path Operations

BuiltinSignatureDescription
path_join(a: String, b: String) -> StringJoin paths
path_ext(path: String) -> StringFile extension
path_dir(path: String) -> StringDirectory component
path_basename(path: String) -> StringBase name

Environment

BuiltinSignatureDescription
getenv(name: String) -> StringGet environment variable
setenv(name: String, value: String) -> IntSet environment variable
argc() -> IntNumber of CLI arguments
argv(n: Int) -> StringGet CLI argument N
system(cmd: String) -> IntExecute shell command
getcwd() -> StringCurrent working directory
chdir(path: String) -> IntChange directory

Random Numbers

BuiltinSignatureDescription
rand_seed(seed: Int) -> VoidSeed the RNG
rand_int() -> IntRandom integer
rand_range(min: Int, max: Int) -> IntRandom in range
rand_float() -> F64Random float [0, 1)

System & Timing

BuiltinSignatureDescription
time_mono_ns() -> IntMonotonic clock (nanoseconds)
sleep_ms(ms: Int) -> VoidSleep for milliseconds
mem_peak_rss() -> IntPeak resident set size (bytes, via getrusage)
mem_forget(val: T) -> VoidPrevent destructor from running

Enumerable Functions

All enumerable functions support UFCS. Prefer arr.map() { it * 2 } over map(arr, x -> x * 2). Use implicit it in short trailing blocks: arr.filter() { it > 0 }.

BuiltinUFCS + implicit itDescription
eacharr.each() { puts("#{it}") }Iterate with side effects
maparr.map() { it * 2 }Transform elements
filterarr.filter() { it > 0 }Filter by predicate
reducearr.reduce(0) do acc, x -> acc + x endAccumulate
any?/all?arr.any?() { it < 0 }Quantifier predicates (return Bool, so ? suffix)
findarr.find() { it == 42 }First matching element
first/lastarr.first()First/last element
take/droparr.take(3)Slice operations
countarr.count() { it > 0 }Count matches
sum/productarr.sum()Aggregation
min/maxarr.min()Extrema
sortsorted(arr)Sorted copy
reversereversed(arr)Reversed copy
uniqueunique(arr)Deduplicated copy
zipzip(a, b)Zip two arrays
enumerateenumerate(arr)Index-value pairs
flattenflatten(nested)Flatten nested arrays
group_bygroup_by(arr, fn)Group by function
partitionpartition(arr, fn)Split by predicate
parallel_map/parallel_for/parallel_reduceParallel variants

SIMD Intrinsics

See typecheck_builtins.qz for the full list (~60 builtins). Grouped by vector type:

  • F32x4 (128-bit, 4×float): simd_f32x4_splat, _add, _sub, _mul, _div, _load, _store, _extract, _sum, _fma, _min, _max, _abs, _shuffle, _gather, _scatter
  • F64x2 (128-bit, 2×double): simd_f64x2_splat, _add, _sub, _mul, _div, _extract, _sum, _fma, _min, _max, _abs, _shuffle, _gather, _scatter
  • I32x4 (128-bit, 4×i32): simd_i32x4_splat, _add, _sub, _mul, _extract, _sum, _fma, _min, _max, _abs, _shuffle, _gather, _scatter
  • F32x8 (256-bit, 8×float): simd_f32x8_splat, _add, _sub, _mul, _div, _load, _store, _extract, _sum, _fma, _min, _max, _abs, _sqrt, _gather, _scatter
  • Conversion: simd_convert_f32x4_to_i32x4, simd_convert_i32x4_to_f32x4, etc.

Structured Concurrency

BuiltinSignatureDescription
task_pool_get() -> IntGet thread pool
task_group_new(pool: Int) -> IntCreate task group
task_group_await_all(tg: Int) -> VoidWait for all tasks
task_group_destroy(tg: Int) -> VoidDestroy task group
taskgroup_spawn(tg: Int, fn: Fn) -> VoidSpawn task
taskgroup_collect(tg: Int) -> Vec<Int>Collect results
taskgroup_cancel(tg: Int) -> VoidCancel group
cancel_token_new() -> IntCreate token
cancel_token_cancel(tok: Int) -> VoidSignal cancel
cancel_token_is_cancelled(tok: Int) -> BoolCheck cancelled
cancel_token_with_deadline(timeout_ms: Int) -> IntCreate token that auto-cancels after timeout
cancel_token_free(tok: Int) -> VoidFree cancel token
is_cancelled() -> BoolCheck current thread

M:N Scheduler (v5.26+)

BuiltinSignatureDescription
sched_init(num_workers: Int) -> VoidInitialize scheduler with N worker threads (0 = auto-detect)
sched_spawn(task: Int) -> VoidEnqueue async task frame onto scheduler
sched_shutdown() -> VoidWait for all tasks to complete, then shut down
sched_yield() -> VoidCooperative yield (re-enqueue current task)
sched_register_io(fd: Int, task: Int) -> VoidRegister fd for I/O wakeup (internal)

The go keyword desugars to async func(args) + sched_spawn(frame):

sched_init(4)
go my_func(arg1, arg2)   # spawns lightweight task
sched_shutdown()          # waits for all tasks, then cleans up

When a task calls io_suspend(fd), the scheduler registers the fd with kqueue (macOS) or epoll (Linux). When the fd becomes ready, the task is automatically re-enqueued and resumed.

Output Capture (Testing)

BuiltinSignatureDescription
capture_output_start() -> IntStart stdout capture
capture_output_end(handle: Int) -> StringEnd capture, get output

UFCS Method Aliases

All built-in types have UFCS method aliases registered as Type$method. These allow calling builtins with dot syntax. UFCS style is preferred over free-function calls:

# Preferred UFCS style
v.push(x)                        # → vec_push(v, x)
v.pop()                          # → vec_pop(v)
v.size                           # → vec_size(v)
s.find("x")                      # → str_find(s, x)
m.get(k)                         # → map_get(m, k)
m.set(k, v)                      # → map_set(m, k, v)
m.has(k)                         # → map_has(m, k)
a.load()                         # → atomic_load(a)
ch.send(v)                       # → send(ch, v)

# Option/Result UFCS
opt.unwrap_or(0)                 # → unwrap_or(opt, 0)
opt.is_some()                    # → option_is_some(opt)
opt.is_none()                    # boolean check
opt.map(x -> x * 2)             # transform inner value
res.is_ok()                      # boolean check
res.is_err()                     # boolean check

Types with UFCS aliases: Vec, Map, Set, StringBuilder, String, Int, F64, Channel, Mutex, AtomicInt, TaskGroup, Option, Result.

Future Intrinsics (When Needed)

Reserved for future implementation:

IntrinsicPurpose
@gc_safepointGC integration

Versioning

Intrinsic ABI is versioned with the language:

  • v0.x: Intrinsics may change
  • v1.0+: Intrinsics are stable ABI

To change an intrinsic after v1.0:

  1. Add new intrinsic with new name
  2. Deprecate old intrinsic
  3. Remove old intrinsic after 2 major versions