Built-in methods

Quick lookup for builtins and method syntax — full examples in the gallery below.

كيف تقرأ الصفحة

كل صف: الاسم، الأنواع، ومثال قصير. ابحث بـ Ctrl+K. الوحدات الكاملة في stdlib.

fn main() {
    print("hi".len())
    print(abs(-3))
}

Output

2
3

فهرس الـ sugar

كل اسم أدناه له مثال + Output في المعرض. انقر للانتقال:

I/O no import

CallArgsReturnsNotesExample
print(expr)valuevoidStdout + newlineprint(42) · print("hi")
write(expr)valuevoidBuffered stdout, no newlinewrite("> ")
println(expr)valuevoidBuffered stdout + newlineprintln("done")
flush()voidFlush stdout bufferwrite("…"); flush()
input()stringRead one stdin linelet line = input()
input(prompt)stringstringPrint prompt, then read linelet name = input("Name? ")

Examples: print · input

String methods no import

Method syntax on string — borrows the receiver (does not move). Heap copy: clone s keyword.

MethodArgsReturnsDescriptionExample
.length() / .len()i32Byte length"hello".len()
.split(sep)stringsplit listSplit on separator"a,b,c".split(",")
.trim()stringStrip whitespace" hi ".trim()
.contains(needle)stringi321 if found"abc".contains("b")
.starts_with(prefix)stringi32Prefix test"hello".starts_with("he")
.ends_with(suffix)stringi32Suffix test"hello".ends_with("lo")
.replace(from, to)2 × stringstringReplace all"a-b".replace("-", "_")
.replacen(from, to, count)2 × string, i32stringReplace at most count"aaa".replacen("a", "b", 2)
.to_upper()stringASCII upper-case"hi".to_upper()
.to_lower()stringASCII lower-case"HI".to_lower()
clone sstringHeap copy (keyword)let copy = clone s
.strip_prefix(prefix)stringstringRemove prefix if present"pre_hi".strip_prefix("pre_")
.strip_suffix(suffix)stringstringRemove suffix if present"hi.txt".strip_suffix(".txt")
.index(needle)stringi32First byte index or -1"hello".index("ell")
.last_index(needle)stringi32Last occurrence index"aba".last_index("a")
.is_empty()i321 if length 0"".is_empty()
.count(needle)stringi32Non-overlapping matches"hello".count("l")
.repeat(n)i32stringRepeat n times"ab".repeat(3)
.trim_start() / .trim_end()stringStrip leading / trailing whitespace" hi".trim_start()
.splitn(sep, n)string, i32VecStrSplit into at most n parts"a,b,c".splitn(",", 2)
.split_once(sep)stringstringPart before first separator"a:b:c".split_once(":")
.fields()VecStrWhitespace-split words"a b c".fields()
.pad_start(w, pad) / .pad_end(w, pad)i32, stringstringPad to width"hi".pad_start(5, "0")
.to_snake_case().to_pascal_case()stringCase conversion helpers"Hello World".to_snake_case()
.compare(other) / .equal_fold(other)stringi32Lexicographic / case-insensitive compare"abc".compare("abd")
.index_byte(b) / .last_index_byte(b)i32i32Byte search; -1 if missing"abc".index_byte(97)
.substring(start, len)2 × i32stringSlice by byte offset + length"hello".substring(1, 3)
.push_char(ch) / .pop()i32 / —stringAppend byte / remove last byte"ab".push_char(99)
.after_sep(sep) / .before_sep(sep)stringstringPart after / before first separator"a:b".after_sep(":")
.strip_ansi()stringRemove ANSI escape codess.strip_ansi()
.is_ascii()i321 if all bytes ≤ 127"hello".is_ascii()
.collapse_ws()stringCollapse runs of whitespace to single space" a b ".collapse_ws()
.reverse()stringReverse byte order (new string)"abc".reverse()
.is_digit() / .is_alpha() / .is_alnum()i32ASCII digit / letter / alphanumeric tests"123".is_digit()
.common_prefix_len(other)stringi32Shared prefix length in bytes"abc".common_prefix_len("abx")
.pad_center(w, pad)i32, stringstringCenter-pad to width"hi".pad_center(6, " ")
.escape_json() / .truncate(n) / .split_after(sep)variesstringJSON escape / byte cap / split after separator"a\\"b".escape_json()

Examples: .split() · .trim() · .strip_prefix() · .fields() · for c in string

Number & math no import

Compiler math intrinsics — lowered to LLVM, no call overhead. Type overload on abs.

CallArgsReturnsNotesExample
abs(x)i32 or f64same as argAbsolute valueabs(-5)
abs_i32(x) / abs_f64(x)1 numerici32 / f64Explicit typed variantsabs_i32(-42)
min_i32(a, b) / max_i32(a, b)2 × i32i32Min / maxmax_i32(3, 7)
min_f64(a, b) / max_f64(a, b)2 × f64f64Min / maxmin_f64(1.0, 2.0)
clamp_i32(x, lo, hi)3 × i32i32Clamp to rangeclamp_i32(15, 0, 10)
cpu_count()i32Logical CPU countcpu_count()
size_of<T>() / align_of<T>()type parami32Layout size / alignment in bytes (×8 for bits)size_of<i32>()

Example: abs / min / max · See also stdlib/math.ny f64 helpers · legacy Math_* · size_of / align_of

import "stdlib/math.ny"f64 math stdlib

Runtime libm-backed helpers with short aliases (floor(x)floor_f64). Examples in the gallery below.

CallArgsReturnsNotesExample
floor(x) / ceil(x) / round(x)f64f64Roundingfloor(3.7)
sqrt(x) / pow(b, e)1–2 × f64f64Root / powersqrt(16.0)
log(x) / log10(x) / log2(x)f64f64Natural / base-10 / base-2 loglog(2.718)
exp(x)f64f64e^xexp(1.0)
clamp(x, lo, hi)3 × f64f64Clamp to rangeclamp(1.5, 0.0, 1.0)
trunc(x)f64f64Truncate toward zerotrunc(1.9)
hypot(x, y)2 × f64f64sqrt(x²+y²)hypot(3.0, 4.0)
asin(x) / acos(x) / atan(x)f64f64Inverse trigasin(0.0)
signum(x) / fract(x) / fmod(x, y)f64f64Sign / fractional part / remaindersignum(-2.0)
deg_to_rad(deg) / rad_to_deg(rad)f64f64Degree ↔ radiandeg_to_rad(180.0)
is_nan(x) / is_finite(x) / is_infinite(x)f64i32Float classificationis_finite(1.0)
floor_i32(x) / ceil_i32(x) / round_i32(x) / trunc_i32(x)i32i32Integer rounding helpersround_i32(5)
gcd_i32(a, b) / lcm_i32(a, b) / mod_i32(a, b)2–3 × i32i32GCD / LCM / Euclidean modgcd_i32(12, 8)
saturating_add(a, b) / saturating_sub(a, b) / wrapping_add(a, b)2 × i32i32Saturating / wrapping integer opssaturating_add(2147483647, 1)
leading_zeros(n) / count_ones(n) / trailing_zeros(n)i32i32Bit population / leading / trailing zeroscount_ones(5)
rotate_left(n, s) / rotate_right(n, s) / rem_euclid(a, b)i32i32Bit rotate / Euclidean remainderrotate_left(1, 1)
lerp(a, b, t) / copysign(x, y)f64f64Linear interpolate / copy signlerp(0.0, 10.0, 0.5)

Booleans no import

Booleans have no methods — use operators and print:

SyntaxResultExample
a && b / a || bboolLogical and / or
!aboolLogical not
a == b, a != bboolEquality
print(flag)voidPrints true / false

Lesson: Nyra Booleans

Fixed arrays no import

Syntax [T; N] — size known at compile time.

Syntax / methodOnReturnsNotesExample
arr[i]fixed arrayTZero-based indexlet x = nums[0]
.length() / .len()fixed arrayi32Element countnums.len()
.sort()[i32; N] or [f64; N]new sorted arrayOriginal unchanged[3, 1, 2].sort()
.sort_by(cmp)fixed arraynew sorted arrayComparator fnitems.sort_by(cmp)
for x in arrfixed arrayIterate elementsfor x in nums { print(x) }
for i in 0..nrangeHalf-open integer rangefor i in 0..10 { … }

Examples: sort · for i in 0..n

Vectors & dynamic lists

vec() / VecI32 — preferred (auto-prelude)

Growable i32 vector with method chaining and HOFs. Low-level Vec_i32_* ptr API remains for FFI.

Method / ctorArgsReturnsNotesExample
vec()VecI32Empty vectorlet v = vec()
.push(x)i32VecI32Append (chains)v.push(42)
.get(i) / .set(i, v)index, valuei32 / selfIndexed accessv.get(0)
.len() / .pop()i32Length / pop lastv.len()
.contains(x) / .includes(x)i32i321 / 0v.contains(42)
.find(pred, fb) / .find_eq(x, fb)pred / valuei32Search with fallbackv.find_eq(10, -1)
.filter(pred) / .map(f) / .reduce(init, f)fnVecI32 / valueHOFsv.filter(is_even)
vec_range(start, end)2 × i32VecI32Half-open rangevec_range(0, 10)
.insert(i, x)i32, i32VecI32Insert at indexv.insert(0, 9)
.remove(i)i32VecI32Remove at index (chains)v.remove(0)
.clear()VecI32Remove all elementsv.clear()
.reverse()VecI32Reverse in placev.reverse()
.sort()VecI32Sort ascending in placev.sort()
.swap(i, j) / .extend(other) / .append(x)indices / VecI32 / i32VecI32Swap elements / merge vectorsv.extend(other)
.capacity() / .reserve(n) / .fill(x)i32i32 / selfCapacity / preallocate / fill in placev.reserve(64)
.swap_remove(i) / .is_empty()i32 / —i32 / i32O(1) remove (unordered) / empty testv.swap_remove(1)
.slice(start, end) / .window(start, size) / .retain(pred)i32 / fnVecI32Sub-range copy / in-place filterv.window(0, 3)

Example: vec(). Legacy: Vec_i32_new / Vec_i32_push.

strs() / StrVec — auto-prelude

String vector with method syntax + HOFs.

Method / functionArgsReturnsNotesExample
strs() / StrVec_new()StrVecEmpty string liststrs()
.push(value)stringStrVecAppend stringv.push("line")
.get(index)i32stringIndexed accessv.get(0)
.len() / .joined(sep)i32 / stringCount / joinv.joined(",")
.filter / .map / .find / .containsfn / valueself / valueHOFsv.contains("a")
lines(text) / StrVec_from_linesstringStrVecSplit on newlineslines(text)
argv()StrVecCLI argsargv()
.pop() / .clear() / .reverse()string / selfMutate in placev.pop()
.insert(i, s) / .remove_at(i) / .set(i, s)i32, stringself / stringIndexed editv.insert(0, "x")
.swap(i, j) / .extend(other) / .is_empty()indices / StrVecself / i32Reorder / merge / empty testv.extend(other)

Example: StrVec

Maps (key-value objects) — import "stdlib/map.ny"

String-keyed hash maps with method syntax.

MethodArgsReturnsOn typeExample
.insert(key, value)string, valuesame map typeHashMap_str_i32m = m.insert("k", 1)
.get(key)stringi32 / stringLookup valuem.get("score")
.get_or(key, default)string, defaultvalue typeFallback when key missingm.get_or("x", 0)
.contains(key)stringi321 / 0m.contains("score")
.len()i32Entry countm.len()
.values()VecI32 / StrVecAll values as vectorm.values()
.clear()same map typeRemove all entriesm.clear()
.or_insert(key, val) / .get_or_insert(key, val)key, valuevalue typeInsert if missing; return valuem.or_insert("k", 1)
.is_empty() / .remove(key) / .update(key, f)key / fni32 / selfEmpty test / remove / in-place updatem.is_empty()
HashMap_i32_i32i32 key & valueInteger-keyed mapHashMap_i32_i32_new()

Constructors: HashMap_str_i32_new(), HashMap_str_str_new(), HashMap_i32_i32_new(). Example: HashMap insert / get · .len() / .values() / .clear()

import "stdlib/sync/atomic.ny" — atomics stdlib

CallArgsReturnsNotesExample
atomic_load_i32(p) / atomic_store_i32(p, v)ptr, i32i32 / voidSeq-cst load / storeatomic_load_i32(cell)
atomic_add_i32(p, d) / atomic_sub_i32(p, d) / atomic_xor_i32(p, m)ptr, i32i32Fetch-add / sub / xoratomic_add_i32(cell, 1)
atomic_and_i32(p, m) / atomic_or_i32(p, m)ptr, i32i32Fetch-and / oratomic_and_i32(cell, 3)
atomic_cas_i32(p, exp, des)ptr, 2 × i32i32Compare-and-swapAtomic_i32_new(0)

Encoding, strconv & FS stdlib

CallModuleReturnsNotesExample
hex_decode(s)stdlib/encoding/mod.nystringDecode hex bytes to stringhex_decode("4869")
hex_encode(s) / hex_encode_upper(s)stdlib/encoding/mod.nystringEncode bytes to hex (lower / upper)hex_encode("Hi")
parse_bool(s) / str_to_bool(s)stdlib/strconv/mod.nyi321/0 for true/false/yes/noparse_bool("true")
parse_int(s, base) / parse_i64(s, base) / parse_u64(s)string, i32i32 / i64Parse integers with radixparse_int("ff", 16)
format_pad(n, w) / format_hex(n) / format_bin(n) / format_oct(n)i32, widthstringPadded decimal / hex / bin / octformat_pad(7, 3)
format_f64(n, prec) / format_f64_pad(n, w, prec)f64, i32stringFloat with precision / widthformat_f64(3.14, 2)
quote(s) / format_quote(s)stringstringGo-style quoted string literalquote("hi")
format_radix(n, base) / format_u64(n) / format_bin_i64(n)i32 / i64stringRadix formattingformat_radix(255, 16)
file_mtime(path) / path_is_file(path) / file_is_symlink(path)stringi64 / i32Metadata helpers (import "stdlib/fs/mod.ny")file_mtime("Cargo.toml")
rename_file(src, dst)2 × stringi32Rename / move filerename_file("a.txt", "b.txt")

Split lists no import

Result of string.split(sep) — iterable string parts.

Syntax / methodReturnsNotesExample
.length() / .len()i32Part countparts.len()
for s in partseach stringIterate partsfor p in parts { print(p) }

Example: for s in split_list

Timing & memory no import

CallDescriptionExample
time_start(label) / time_end(label)Wall-clock timingtime_start("work"); …; time_end("work")
mem_start(label) / mem_end(label)RSS deltamem_start("alloc"); …; mem_end("alloc")
benchmark { ... }Time + memory + CPU% for a blockbenchmark { heavy_work() }

Examples: time_start / time_end · mem_start / mem_end · benchmark { }

Other builtins no import

CallReturns / effectNotesExample
random() / random(min, max)generic integerChaCha20 CSPRNG; return type follows bounds (i32, i64, u64, …). No-arg defaults to i32.random(1, 6) · random<i64>(50, 100)
random_f64() / random_f64(min, max)f64Unit interval [0, 1) or range [min, max)random_f64(0.0, 1.0)
date()Date structLocal clock fieldslet d = date(); print(d.year)
spawn { ... } / spawn:task { ... }JoinHandle (expr) / none (stmt)Lightweight task pool; needs allow_extended; not on wasm32spawn { print(1) }
spawn:thread { ... }JoinHandle (expr)Dedicated OS thread (~MB stack)spawn:thread { heavy() }
h.join()voidOn JoinHandle; blocks until spawn completes; consumes handlelet h = spawn { … }; h.join()
parallel for i in 0..n { ... } / parallel:taskparallel loopTask pool (default); max = N, cpu = N%parallel for · parallel:task(max = 4) · cpu = N% · mode = …
parallel:thread(...) for ...parallel loopOS thread fork-join per chunkparallel:thread(max = 4)
progress for x in items { ... }loop + progress barOptional labelprogress for
defer exprscope-exit call (LIFO)Extended — prefer impl Dropdefer · LIFO
async fn … { … }promise / future handleBody on task pool (spawn:task); not on wasm32async fn
await handleblocks until completeInside async fn or at call siteawait

Examples: allow_extended · JoinHandle · random · date() · spawn · .join() · parallel for · progress · benchmark · defer · async/await

File directive: allow_extended

spawn, parallel for, async/await, defer, and related APIs live in Nyra’s Stable Extended tier. Put this line at the top of the file (before fn main or imports) when the unit intentionally uses those features:

allow_extended
What it doesWhy use it
Marks the file as an Extended-tier programDocuments intent for readers and reviewers
Suppresses warning[W001]Extended-feature warnings are silenced in this file (useful when CI runs with stricter flags)
One line per fileNot per-function — applies to the whole compilation unit

You do not need allow_extended for Core-only code (plain print, structs, loops, etc.). All spawn and parallel examples below include it. See also Concurrency → spawn and Roadmap (Core vs Extended).

Name: allow_extended (first line of file)
Explanation: Declares that this compilation unit intentionally uses Stable Extended APIs. Does not enable features by itself — it documents intent and integrates with stability warnings.
Example:

allow_extended
fn main() {
    parallel for i in 0..3 {
        print(i)
    }
}

Output: Same as parallel for (iteration order non-deterministic). Without this line, Extended syntax still compiles in default builds; the directive is recommended in files that use spawn, parallel for, etc.

Platform: spawn is unavailable on wasm32-wasi (compile error). Native Linux, macOS, and Windows only.

JoinHandle and .join()

When spawn appears as an expression (let h = spawn { … }), the type of h is JoinHandle — an opaque handle to a background task or thread. It is not a numeric ID; you cannot print it or compare it. You either wait on it or drop it.

MethodSignatureEffect
.join()h.join() -> voidBlocks the current thread until the spawned work finishes. Consumes the handle (move) — you cannot call .join() twice on the same variable.
FormSyntaxWait for completion?
Statementspawn { … }No — fire-and-forget; runtime detaches immediately
Expression + joinlet h = spawn { … }; h.join()Yes — main waits at h.join()
Drop without joinlet h = spawn { … } then scope endsNo — handle dropped → detach (same as statement form)

.join() takes no arguments. Works the same for spawn, spawn:task, and spawn:thread; the compiler calls the correct runtime (spawn_task_join vs spawn_join) based on how the handle was created. See example.

Spawn & parallel examples

Runnable gallery (name · explanation · example · output): spawn · parallel · progress · benchmark · defer · async/await. Source: examples/builtins/{spawn,parallel,benchmark,defer,async}/.

JS-style helpers import required

Ergonomic wrappers with familiar names — import when you want function-style APIs over ptr handles.

Array helpers — import "stdlib/builtins_array.ny"

FunctionDescriptionExample
Array_push(v, x)Append i32Array_push(v, 42)
Array_pop(v)Pop last i32Array_pop(v)
Array_map(v, f)Map with fnArray_map(v, double)
Array_filter(v, pred)Filter (pred → 1/0)Array_filter(v, is_even)
Array_reduce(v, init, f)Fold leftArray_reduce(v, 0, sum)
Array_find(v, pred, fallback)First match or fallbackArray_find(v, is_even, -1)

Example: Array_push / map / filter

String helpers — import "stdlib/builtins_string.ny"

FunctionDescriptionExample
String_toUpperCase(s)Upper-caseString_toUpperCase("hi")
String_toLowerCase(s)Lower-caseString_toLowerCase("HI")
String_includes(s, needle)Substring testString_includes(s, "ab")
String_split(s, sep)Split to string vectorString_split("a,b", ",")
String_replace(s, from, to)Replace all matchesString_replace(s, "-", "_")
String_replacen(s, from, to, count)Replace at most countString_replacen(s, "a", "b", 2)
trim(s)Trim whitespacetrim(" x ")
strip_prefix(s, p) / strip_suffix(s, sfx)Prefix / suffix removalstrip_prefix("pre_x", "pre_")
index(s, needle) / last_indexSearch indicesindex("aba", "a")
pad_start / pad_end (method syntax)Pad to width"hi".pad_start(5, "0")

Example: String_split

stdlib/random.ny import for shuffle only

random(), random(min, max), and random_f64() are compiler builtins — no import. Import this module for shuffle_pick.

FunctionDescriptionExample
random() / random(min, max)Generic integer random (ChaCha20, HW-seeded) — type from boundsrandom(1, 6)
random_f64() / random_f64(min, max)Random f64 — unit or rangerandom_f64(0.0, 1.0)
shuffle_pick(vec)Random i32 from vector handleshuffle_pick(v)

Example: random · shuffle_pick

Math helpers — import "stdlib/builtins_math.ny"

FunctionDescriptionExample
Math_max(a, b) / Math_min(a, b)Min / max (i32)Math_max(3, 7)
Math_round(x) / Math_floor(x) / Math_ceil(x)Rounding (MVP on i32)Math_round(42)
Math_random()Random f64 in [0, 1)Math_random()

Example: Math_random

JSON helpers — import "stdlib/builtins_json.ny"

FunctionDescriptionExample
JSON_stringify(key, value)Single-field JSON objectJSON_stringify("name", "Ada")
JSON_parse(json, key)Read string fieldJSON_parse(json, "name")

Example: JSON_stringify / JSON_parse

Module reference: Standard library · Concurrency: Concurrency