Standard library

Short stdlib/ reference — builtins on methods; modules below.

نظرة عامة

الاستيراد الكسول: تُدمج الوحدات التي تستخدمها فقط. للدوال مثل print و.split راجع الدوال المدمجة.

fn main() {
    print("stdlib ready")
}

Output

stdlib ready

أسلوب قصير شائع

كل اسم له مثال + Output في المعرض أسفل الصفحة (وفي فهرس methods): jparse/jstr · sb() · slurp/spit · now/ms · env · cmd · uuid · b64 · vec()/strs() · qb() · form/params. شبكة: fetch/req.

fn main() {
    let o = jparse("{\"n\":1}")
    print(jnum(o, "n"))
    print(sb().push("hi").build())
}

Output

1
hi

حالة التنفيذ

معظم الوحدات الأساسية مستقرة. الجداول التفصيلية وأمثلة الـ builtins أسفل الصفحة؛ المصدر: stdlib/README.md.

import "stdlib/fs.ny"

fn main() {
    spit("hi.txt", "ok")
    print(slurp("hi.txt"))
}

Output

ok

Collections

ImportTypes / API
stdlib/vec.nyvec() / VecI32push, filter, map, find, contains, reduce
stdlib/vec_str.nystrs() / StrVecjoined, filter, map, find, contains, argv()
stdlib/map.nyHashMap_str_i32, HashMap_str_strinsert/remove return self (refcounted; safe store = store.insert(...) and TtlCache_put chains)
stdlib/parser/SourceLoc, ParseCursor, Comb_take_while, Comb_or_literal, Comb_many, AstRow — parser building blocks
stdlib/collections/vec_pod.nyVec<T> POD vectors — synthesized Vec_{Struct}_* for Copy structs
stdlib/collections/vec_pod.ny + reloc expandVec<MoveStruct> — parallel columns for string + scalar (+ nested) fields
stdlib/collections/nested_vec.nyVec<Vec<i32>> — synthesized Vec_Vec_i32_* (2D dynamic grid MVP)
stdlib/map.nyHashMap<K,V> generic syntax aliases HashMap_str_i32 / HashMap_str_str
stdlib/strings/split.nyString_split_safe, String_split_quoted
stdlib/collections/kv_vec.nyKvVec — parallel key/value vectors for object rows
stdlib/unicode/iter.nyutf8_codepoint_at, utf8_codepoint_count
stdlib/collections/set.nyHashSet_str
stdlib/collections/stack.nyStack_i32
stdlib/collections/queue.nyQueue_i32front, advance
stdlib/collections/list.nyLinkedList_i32 (Vec-backed MVP)
stdlib/collections/advanced.nyBTreeMap_str_i32, BTreeSet_str, Deque_i32, PriorityQueue_i32
stdlib/gui/TextBuffer, ScrollState, FilePicker, Syntax_line_kind — raylib UI helpers
stdlib/games/Grid2D_i32, EcsWorld, VoxelChunk_i32, Gfx3D_orbit_position, GameAudioSession — game grids, ECS, voxels, 3D math, audio paths; optional raylib_audio / raylib_gfx
stdlib/strings/builder.nysb(), .push/.build, cat/cat3/cat4, StringBuilder_*
fn is_even(x: i32) -> i32 {
    if x % 2 == 0 { return 1 }
    return 0
}

fn main() {
    let xs = vec().push(1).push(2).push(3).push(4)
    let evens = xs.filter(is_even)
    print(evens.len(), xs.contains(3))

    let names = strs().push("ada").push("nyra")
    print(names.joined(","), names.includes("nyra"))

    let map = dict().insert("age", "20")
    print(map.get("age"))
}

Strings & regex

ImportFunctions
stdlib/strings.nystrlen, strcat, strcmp, char_from_code, …
stdlib/strings/ops.nystr_len, str_contains, str_trim, str_to_upper, str_replace
stdlib/strings/regex.nyRegex_new, regex_matches, regex_replace
import "stdlib/strings/regex.ny"

fn main() {
    let re = Regex_new(".+@.+")
    if regex_matches(re, "user@example.com") != 0 {
        print("valid email pattern")
    }
}

FS & path

ImportAPI
stdlib/fs.ny / stdlib/fs/mod.nyslurp/spit/mkdir/rm/ls, read_file, write_file, exists
stdlib/path.nyPath_new, join, extension, file_name, parent
stdlib/url/mod.nyUrl_parse, url_host, url_path

Time & date

ImportAPI
stdlib/time/instant.nyInstant_now, elapsed_ms, sleep(ms)
stdlib/time/date.nyCalendarDate, DateTime, date_add_days, date_format (import)
builtinsdate() — local clock fields (no import); time_start / time_end, mem_start / mem_end

Net, HTTP, WebSocket

ImportAPI
stdlib/net/http/mod.nyPrimary. fetch(url)HttpResponse; req().header(…).json(…).post(url); get body-only; headers, FormData, cookies, abort, redirects, Router
stdlib/net/tcp.nyTcpListener, TcpStream, tcp_connect, tcp_connect_timeout, tcp_accept_wait
stdlib/net/dns.nydns_lookupStrVec of IP addresses
stdlib/net/icmp.nyping_tcp, ping_icmp, ping_icmp_system, ping_icmp_capable, ping_auto, ping_auto_verbose (ICMP → system ping → TCP)
stdlib/net/poll.nypoll_wait, tcp_relay_poll
stdlib/net/ftp.nyFtp_login, Ftp_list, Ftp_retr, Ftp_stor
stdlib/net/http/router.nyHttpRouter — slots/tags; parametric /users/:id; HttpRouter_match / RequestContext_param
stdlib/net/http/handler.nyHttp_dispatch_slot, serve_handlers
stdlib/net/http/pool.nyHttpPool, HttpPool_get — HTTP/HTTPS keep-alive reuse
stdlib/net/cache.nyTtlCache — TTL eviction + optional disk tier
stdlib/net/hub.nyTcpHub (Send) — broadcast to connected TCP fds
stdlib/sync/channel.nyChannel_i32, Channel_str
stdlib/net/udp.nyUdpSocket_bind, send, recv, close
stdlib/net/websocket.nyWebSocket_connect, ws_listen_on, ws_listen_tls_on, ws_listen_dev_on, ws_listen_prod_on, ws_accept/ws_accept_tls, send/send_server, recv
stdlib/net/smtp.nySmtp_send, Smtp_send_tls, Smtp_send_starttls
stdlib/net/mail.nyMail_send, Mail_message
stdlib/net/rpc.nyrpc_encode, JSON-RPC 2.0 helpers
stdlib/net.nyRe-exports TCP + net/http
stdlib/http/mod.nyLegacy re-export of net/http + HttpServer
stdlib/tls.nytls_connect, tls_connect_verify, tls_connect_ca, tls_upgrade_fd (STARTTLS), tls_listen, tls_validate_pem, tls_last_error, tls_require — client backends via tls in nyra.mod: rustls (default), native (Secure Transport / SChannel), openssl
stdlib/net/tls_dev.nytls_dev_ensure, tls_listen_dev — local self-signed cert/key (tls openssl)
stdlib/net/tls_prod.nytls_listen_prod, tls_connect_prod, tls_upgrade_prod — production cert paths via NYRA_TLS_CERT / NYRA_TLS_KEY
stdlib/mime/mod.nymime_write_multipart, mime_content_type_multipart
stdlib/text/templatetemplate_execute{{key}} substitution
stdlib/html/templatehtml_template_execute — HTML-escaped templates

Full reference: net/http

JSON & serialization

ImportAPI
stdlib/json/mod.nyparse_json/stringify_json (document validate+compact), jparse/jstr/jnum/obj/dict, JSON_parse_object, encode_field
stdlib/serialize/mod.nyencode_object, toml_encode_object, yaml_encode_object; serialize/deserialize by SerializeFormat
stdlib/serde/mod.nySerialize/Deserialize traits + compiler schema encode/decode

Examples: examples/json/decode_i32.ny · examples/serialize/toml.ny · examples/serde_json_pkg.ny (document JSON via stdlib). For full TOML beyond the serialize MVP, see nyrapkg (ny-toml).

Crypto, random & encoding

ImportAPI
stdlib/crypto/mod.nyrandom_bytes, sha256, sha512, hmac_sha256, aes_encrypt/aes_decrypt — portable, no external deps
stdlib/crypto/rsa.nyrsa_encrypt_pem, rsa_sign_sha256_pem (OpenSSL when linked)
stdlib/crypto/x509.nyx509_subject, x509_valid_now (OpenSSL)
stdlib/random.nyrandom, random(min, max), random_f64, shuffle_pick — ChaCha20 CSPRNG
stdlib/uuid/mod.nyUUID_v4() (MVP formatting)
stdlib/encoding/mod.nyhex_encode, hex_encode_upper, hex_decode, hex_encode_byte, url_encode
stdlib/encoding/base64.nybase64_encode, base64_decode — pure Nyra
stdlib/encoding/csv.nycsv_parse_line, csv_format_row (quoted fields)
stdlib/encoding/xml.nyxml_element, xml_decode_tag_text
stdlib/unicode/utf8.nyutf8_valid
stdlib/compress/mod.nygzip_compress/gzip_decompress (zlib), rle_*, zip_*
stdlib/compress/flate.nyflate_compress, flate_decompress
stdlib/archive/zip.nyzip_pack, zip_unpack (store method)
stdlib/archive/tar.nytar archive helpers
stdlib/embed/mod.nyEmbedFs, embed_from_manifest — runtime embed FS
stdlib/slog/mod.nyslog_info_kv, slog_error_kv — JSON log lines

Examples: examples/crypto/sha256.ny · examples/compress/gzip_roundtrip.ny · examples/stdlib_medium_smoke.ny · examples/builtins/stdlib/random.ny

Random (ChaCha20, hardware-seeded)

random(), random(min, max), random_f64(), and random_f64(min, max) are compiler builtins (ChaCha20, hardware-seeded). Integer random is generic — return type follows the bounds (Rust gen_range style): i32, i64, u64, etc. No-arg random() defaults to i32; use random<i64>() for other widths. import "stdlib/random.ny" for shuffle_pick.

CallDescription
random()Random i32 — full 32-bit stream
random(min, max)Inclusive integer range; type inferred from bounds (rejection sampling, no modulo bias)
random<T>() / random<T>(min, max)Explicit integer type (i64, u64, …)
random_f64()Random f64 in [0, 1) — 53-bit precision
random_f64(min, max)Random f64 in [min, max)
shuffle_pick(vec)Random element from an i32 vector handle (import required)

Math_random() from stdlib/builtins_math.ny delegates to the same rand_f64() backend. For raw OS TRNG bytes (tokens, keys), use hw_random_bytes or stdlib/crypto/random.nyrandom_bytes.

import "stdlib/random.ny"

fn main() {
    let dice = random(1, 6)
    let unit = random_f64()
    print(random())
    print(dice)
    print(unit)
    print(random_f64(0.0, 1.0))
}

Example: examples/builtins/stdlib/random.ny · tests: tests/nyra/random_test.ny

Env & config

ImportAPI
stdlib/env/mod.nyenv/env_or, env_get, env_has, env_set
stdlib/os/env.nyos_getenv (low-level)
stdlib/config/mod.nyconfig_load, config_get_env_or_file

CLI parsing

Build command-line tools with argv parsing, flags, and line scanners. Used by apps under Apps/ and examples/zero_types_cli.ny.

ImportAPI
stdlib/strconv/mod.nyatoi, itoa, parse_i32, parse_int, parse_i64, parse_u64, parse_f64, parse_bool, format_i32, format_pad, format_hex, format_bin, format_oct, format_f64, format_quote, format_radix, format_u64
stdlib/flag/mod.nyFlagSet_new, FlagSet_parse, Flag_has-v/--verbose, -h/--help, subcommands
stdlib/bufio/mod.nyScanner_new, Scanner_scan, Scanner_token — line/token scanner over strings
stdlib/vec_str.nyStrVec_from_argv(1) — CLI args after program name
import "stdlib/flag/mod.ny"

fn main() {
    let set = FlagSet_new("mytool", "Usage: mytool [flags] args…")
    let parsed = FlagSet_parse(set)
    if parsed.help_requested != 0 {
        Flag_print_usage(parsed)
        return
    }
    let paths = parsed.positional
    print(paths.len())
}

Database

SQLite is native when you add link sqlite3 in nyra.mod. Postgres and MySQL expose stable import paths with stub drivers today.

ImportAPI
stdlib/db/sqlite.nySqlite_open, .exec, .query_rows, .find(q), .prepare — requires link sqlite3
stdlib/db/query.nyPreferred. qb().select().from().where().include().lookup().unwind().order().limit().to_sql(); run with db.find(q)
stdlib/db/resp.nyResp_decode_array, Resp_encode_bulk, Resp_cmd_name
stdlib/db/sstable.nySsTable_write_sorted, SsTable_get, sstable_merge_files, SsTable_fsync
stdlib/db/lsm.nyLsmTree_put, LsmTree_lookup, LsmTree_get, LsmTree_delete, LsmTree_recover — WAL + leveled compaction
stdlib/db/sql_parse.nySqlParse_parse, SqlParse_format — subset SELECT/INSERT/UPDATE/DELETE
stdlib/collections/btree_map.nyBTreeMap_str_str_* sorted key map
stdlib/collections/btree_pages.nyBTreePaged_* — internal descent, BTreePaged_range, BTreePaged_keys
stdlib/db/sql.nySql_open, .query_rows, .find(q) — unified entry (sqlite, postgres, mysql)
stdlib/db/postgres.nyStub — native driver in progress
stdlib/db/mysql.nyStub — native driver in progress
fn main() {
    // Build SQL without a live DB
    print(qb()
        .select("u.name, p.title")
        .from("users u")
        .include("posts p", "p.user_id = u.id")
        .where("u.active", "=", "1")
        .limit(10)
        .to_sql())

    // With SQLite (add `link sqlite3` in nyra.mod):
    // let db = Sqlite_open("app.db")
    // let rows = db.find(qb_from("kv").select("*").where("k", "=", "hello"))
}

NyraPkg bindings: examples/packages/ny-sqlite/ · nyrapkg

Terminal & console

Preferred: use built-in print(msg, color: red) and input("prompt") — see I/O built-ins.

ImportAPI
stdlib/terminal/mod.nystdout_write, stderr_write, stdin_read (line-based)
stdlib/terminal/console.nyconsole_red, console_green, … (ANSI via \033[…m)
stdlib/terminal/pty.nyPtySession_spawn, PtySession_write, PtySession_read — interactive shell; see Subprocess
stdlib/log.nylog_info, log_warn, log_error
stdlib/color.nyRgba, rgba(r,g,b,a) — color values for UI/graphics

Helpers: color_ansi(spec), ansi_reset().

Subprocess & commands

Run external programs from Nyra — similar to Rust’s std::process::Command. Symbols from stdlib/process.ny resolve via auto-prelude (no import required) or explicit import "stdlib/process.ny".

The child inherits stdin/stdout/stderr from the parent — output appears on your terminal. .run() blocks until the child exits and returns its exit code (i32). Returns -1 on failure (including Windows today).

APIDescription
Command_new(program)Builder — program path or name on PATH
cmd.arg(value)Append one argument (returns new Command)
cmd.run()Spawn, wait, return exit code
cmd.output()Capture stdout/stderr into ExecResult
exec(program, args)Top-level capture — { code, stdout, stderr }
run_command(program)Shorthand — program with no extra args
command_run_args(program, args)Run with a StrVec of arguments
stdlib/compiler.nycheck(path), diag_json(path) — run nyra from NYRA_HOME or PATH
fn main() {
    // Exit code only — stdout goes to the terminal
    let code = Command_new("true").run()
    print(code)

    let ls = Command_new("ls").arg("-la").arg("/tmp").run()
    print(ls)

    // Shell one-liner (pipes, globs) — not a built-in shell parser
    let sh = Command_new("/bin/sh").arg("-c").arg("echo hello from sh").run()
    print(sh)
}

أي API تستخدم؟

Command.run لكود الخروج مع الـ I/O · exec / Command.output() لالتقاط stdout · check/diag_json للتحقق · bridge_exec لعمال JSON · pty.ny لتيرمنال تفاعلي. حد أقصى 30 وسيطًا.

nyra run examples/process_command.ny
nyra run examples/process_exec.ny

Sync, context & async channels

ImportAPI
stdlib/sync/mod.nyChannel_i32, Mutex, RwLock, WaitGroup, Atomic_i32
stdlib/sync/async_channel.nyAsyncChannel_i32 (Extended + channel)
stdlib/context/mod.nyContext_background, Context_with_timeout, context_done, context_cancel, context_sleep_or_done
stdlib/async.nyPromise/async helpers (Extended) — see Async
spawn { }Language keyword — Concurrency

Context uses monotonic deadlines from time/instant.ny — poll with context_done in loops or before blocking I/O. See Concurrency.

Iterators (Vec_i32 MVP)

import "stdlib/iter/mod.ny" — chain via separate calls (no closures yet):

import "stdlib/iter/mod.ny"
import "stdlib/vec.ny"

fn main() {
    let mut nums = Vec_i32_new()
    nums = nums.push(1)
    nums = nums.push(5)
    nums = nums.push(3)
    let big = vec_filter_gt(nums, 2)
    print(vec_reduce_sum(big))
}

vec_map_add, vec_take, vec_skip, vec_find

Reflect, result & memory utils

ImportAPI
stdlib/reflect/mod.nytypeof_i32, type_name_i32, type_name_string — no runtime RTTI
stdlib/result.nyoption_is_some, result_is_ok
compiler intrinsicsize_of<T>(), align_of<T>() — type layout in bytes (no import)
stdlib/mem/layout.nysize_of_i32, size_of_ptr, align_of_i32, align_of_ptr — wrappers over the intrinsics
stdlib/mem/util.nyMVP scalars (size_of_i32, align_of_ptr, swap_i32) — prefer layout.ny / intrinsics
stdlib/arc.nyArc_i32, Arc_from_i32, Arc_from_string — refcounted shared ownership; see Memory
stdlib/option.nyOption helpers — see Match
stdlib/box.nyHeap box — see Memory
stdlib/math.nyabs_i32, pow_i32, sqrt_i32, sin, cos, floor, gcd_i32, saturating_add, leading_zeros, is_finite, …
stdlib/random.nyshuffle_pick; builtins random, random_f64
stdlib/terminal/raw.nyterminal_raw_on, terminal_read_key
stdlib/time/fixed_step.nyFixedStep_new, FixedStep_tick
stdlib/testing.nyassert_eq, assert_ne, assert_true, assert, assert_bool — see testing
stdlib/process.nyCommand_new, .run — see Subprocess & commands
stdlib/bridge/mod.nybridge_exec, bridge_result — see examples/bridge/

size_of / align_of

Ask the compiler for a type’s layout size and alignment in bytes. Multiply by 8 for bits (i32 → 4 bytes → 32 bits). Works on scalars, repr(C) structs, and unions — no import required for the intrinsics.

struct Packet repr(C) align(8) {
    kind: i32
    port: i32
}

fn main() {
    print(size_of<i32>())        // 4 bytes
    print(size_of<i32>() * 8)    // 32 bits
    print(size_of<i64>())        // 8 bytes
    print(align_of<i64>())       // 8
    print(size_of<Packet>())     // 8
    print(align_of<Packet>())    // 8
}

Output

4
32
8
8
8
8

Named helpers (same values) via import "stdlib/mem/layout.ny":

import "stdlib/mem/layout.ny"

fn main() {
    print(size_of_i32())
    print(align_of_ptr())
}

Output (64-bit target)

4
8

Also see Memory → Type layout and Learn → Data types → Type sizes.

Reflect — type names

Compile-time helpers only — Nyra has no runtime RTTI. Useful for tests and debug labels. typeof_i32(x) returns TypeKind.I32 (and siblings for bool / string).

import "stdlib/reflect/mod.ny"

fn main() {
    print(type_name_i32())
    print(type_name_string())
    print(type_name_bool())
}

Output

i32
string
bool

Fixed-step clock

Game-loop helper: accumulate frame time and return how many fixed simulation steps to run.

import "stdlib/time/fixed_step.ny"

fn main() {
    let mut clock = FixedStep_new(60)   // 60 Hz → ~16.67 ms/step
    let steps = FixedStep_tick(clock, 33.0)
    print(steps)                        // 1 (33 ms covers one step)
    print(FixedStep_hz(clock))
}

Output

1
60

Terminal raw mode

Disable line buffering to read single key codes (TUI / games). Always restore cooked mode afterward.

import "stdlib/terminal/raw.ny"

fn main() {
    terminal_raw_on()
    let key = terminal_read_key()   // blocks until a key is pressed
    terminal_raw_off()
    print(key)
}

Testing helpers

Import for nyra test and the CONF-LANG suite (tests/conformance/pass/). Full CLI walkthrough (COMPILE → LINK → PASS, --filter, --list-json): Toolchain → nyra test.

ImportAPI
stdlib/testing.nyassert_eq, assert_ne, assert_true, assert_bool
stdlib/testing/fstest.nyassert_file_contains, assert_file_exists
stdlib/testing/quick.nyquick_check_range_i32 — property-style checks
import "stdlib/testing.ny"

test fn adds() {
    assert_eq(2 + 3, 5)
    assert_bool(true)
}
nyra test .                 # run all test fn in the project
nyra test . --filter adds   # only matching names
nyra test . --list-json     # IDE discovery
FunctionJob
assert_eq(actual, expected)i32 equality — exits 1 on mismatch
assert_ne(actual, expected)i32 inequality
assert_true(cond) / assert(cond)Non-zero i32 condition
assert_bool(cond)bool must be true

Run conformance: bash scripts/conformance-tests.sh · Toolchain → CONF-LANG

Benchmark & profile

ImportAPI
stdlib/bench/mod.nybench_loop(label, iterations), bench_once(label); uses blackbox_i32. For block timing use the benchmark { } statement (no import).
stdlib/profile/mod.nyprofile_start, ProfileSession.stop

Built-in functions & methods (no import)

الأنواع اختيارية: المترجم يستنتجها. المعرض أدناه: تبويب بدون أنواع (افتراضي) ومع أنواع. الأمثلة في examples/builtins/.

I/O

CallSignatureDescriptionExample
print(expr)1 arg → voidStdout + newline (string, i32, bool, char, f64).examples/builtins/io/print.ny
print(expr, color: spec)value + named color → voidColored stdout + newline. spec: name (red), "#RGB" / "#RRGGBB", "rgb(r,g,b)", or string expr. Resets style after each line.
write(expr)1 arg → voidBuffered stdout (no newline).examples/builtins/io/write.ny
println(expr)1 arg → voidBuffered stdout + newline.examples/builtins/io/println.ny
flush()none → voidFlush stdout buffer.examples/builtins/io/flush.ny
input()none → stringRead one line from stdin.examples/builtins/io/input.ny
input(prompt)stringstringPrint prompt, then read line.examples/builtins/io/input.ny

Math intrinsics

Compiler builtins — call like normal functions; the backend lowers them to LLVM intrinsics (no function-call overhead). Available with or without stdlib prelude (--no-prelude / embedded builds).

CallLLVMExample
abs_i32(x) / abs(x) on i32@llvm.abs.i32examples/builtins/math_intrinsics.ny
abs_f64(x) / abs(x) on f64@llvm.fabs.f64
min_i32(a, b) / max_i32(a, b)@llvm.smin.i32 / @llvm.smax.i32examples/builtins/math_intrinsics.ny
min_f64(a, b) / max_f64(a, b)@llvm.minnum.f64 / @llvm.maxnum.f64
clamp_i32(x, lo, hi)smax + sminexamples/builtins/math_intrinsics.ny
sin(x), cos(x), atan2(y, x), tan(x) on f64via stdlib/math.nyexamples/games/trig_raycast.ny

stdlib/math.ny keeps reference stubs for type discovery via auto-prelude; pow_i32 and sqrt_i32 remain ordinary Nyra code (no libm). Trig calls are compiler intrinsics (direct @sin_f64 etc.) so Nyra’s sin wrapper does not collide with libc sin at link time.

date() — local date & time

Returns a Date struct (fields, not methods). Month is 1–12 (calendar month).

Field / aliasTypeRangeExample
yeari32e.g. 2026examples/builtins/date/date.ny
monthi321–12
dayi321–31
hour, minute, secondi32clock time
week / weekdayi320=Sun … 6=Sat
millisecondi320–999
minutesalias → minute
secondsalias → second

Call: date()date_now (local timezone).

String methods

Method syntax on string — borrows the receiver (does not move). Copy with the clone keyword: let c = clone s (not .clone()).

MethodArgsReturnsDescriptionExample
.length()nonei32Byte lengthexamples/builtins/strings/length.ny
.len()nonei32Alias of .length()examples/builtins/strings/len.ny
.split(sep)stringsplit listSplit on separatorexamples/builtins/strings/split.ny
.trim()nonestringStrip whitespaceexamples/builtins/strings/trim.ny
.contains(needle)stringi321 / 0examples/builtins/strings/contains.ny
.starts_with(prefix)stringi32Prefix testexamples/builtins/strings/starts_with.ny
.ends_with(suffix)stringi32Suffix testexamples/builtins/strings/ends_with.ny
.replace(from, to)2 × stringstringFirst occurrence onlyexamples/builtins/strings/replace.ny
.to_upper()nonestringASCII upper-caseexamples/builtins/strings/to_upper.ny
.to_lower()nonestringASCII lower-caseexamples/builtins/strings/to_lower.ny
clone sstringHeap copy (keyword)examples/builtins/strings/clone.ny

Fixed arrays & for … in

Syntax / methodOnReturnsExample
for i in 0..nrangeexamples/builtins/for_in/range.ny
for x in arrfixed arrayexamples/builtins/arrays/for_in.ny
for c in strstringchar per byteexamples/builtins/for_in/string_chars.ny
.length() / .len()fixed arrayi32examples/builtins/arrays/length.ny
.sort()i32 / f64 arraynew sorted array (numeric; original unchanged)examples/builtins/arrays/sort.ny
.sort_by(cmp)fn(T, T) -> i32new sorted array (comparator; original unchanged)examples/syntax/array_sort_by.ny

Split lists (.split result)

Method / syntaxReturnsExample
.length() / .len()i32 part countexamples/builtins/split_list/length.ny
for s in partseach string partexamples/builtins/split_list/for_in.ny

Timing & memory

CallLowers toExample
time_start(label) / time_end(label)time_start / time_endexamples/builtins/timing/time.ny
mem_start(label) / mem_end(label)mem_start / mem_endexamples/builtins/timing/mem.ny

Terminal output uses colored timing / RSS deltas (platform-dependent).

spawn { ... }

Runs a block on a new thread. Captures must be Send; active borrows are rejected.

RuntimeExample
spawn_captureexamples/builtins/spawn/spawn.ny

Channels: examples/syntax/spawn_channel.ny · Rules: Concurrency

Stdlib JS-style helpers (import)

Ergonomic wrappers in stdlib/builtins_*.ny — import when you need dynamic Vec helpers or naming familiar from JavaScript.

stdlib/builtins_array.ny

FunctionDescriptionExample
Array_push(v, x)Append i32examples/builtins/stdlib/array_push.ny
Array_pop(v)Pop last i32examples/builtins/stdlib/array_pop.ny
Array_map(v, f)Map with fn(i32) -> i32examples/builtins/stdlib/array_map.ny
Array_filter(v, pred)Filter (pred returns 1/0)examples/builtins/stdlib/array_filter.ny
Array_reduce(v, init, f)Fold leftexamples/builtins/stdlib/array_reduce.ny
Array_find(v, pred, fallback)First match or fallbackexamples/builtins/stdlib/array_find.ny

Combined: examples/builtins/array/main.ny

stdlib/builtins_string.ny

FunctionDescriptionExample
String_toUpperCase(s)Upper-caseexamples/builtins/stdlib/string_to_upper.ny
String_toLowerCase(s)Lower-caseexamples/builtins/stdlib/string_to_lower.ny
String_includes(s, needle)Substring testexamples/builtins/stdlib/string_includes.ny
String_split(s, sep)Split to string vector (ptr)examples/builtins/stdlib/string_split.ny
String_replace(s, from, to)Replace all matchesexamples/builtins/stdlib/string_replace.ny
String_replacen(s, from, to, count)Replace at most count matchesexamples/syntax/string_replace.ny
trim(s)Trim whitespaceexamples/builtins/stdlib/trim.ny

Combined: examples/builtins/string/main.ny

stdlib/builtins_math.ny

FunctionDescriptionExample
Math_max(a, b)Maximumexamples/builtins/stdlib/math_max.ny
Math_min(a, b)Minimumexamples/builtins/stdlib/math_min.ny
Math_round(x)Round (MVP: identity on i32)examples/builtins/stdlib/math_round.ny
Math_floor(x)Floor (MVP)examples/builtins/stdlib/math_floor.ny
Math_ceil(x)Ceil (MVP)examples/builtins/stdlib/math_ceil.ny
Math_random()Random f64 in [0, 1) — ChaCha20 via rand_f64()examples/builtins/stdlib/math_random.ny

Combined: examples/builtins/math/main.ny

stdlib/random.ny

FunctionDescriptionExample
random() / random(min, max)Generic integer random (ChaCha20, HW-seeded)examples/builtins/stdlib/random.ny
random_f64() / random_f64(min, max)Unit or range f64examples/builtins/stdlib/random.ny
shuffle_pick(vec)Random i32 from vector (import required)

See also Random (ChaCha20) · Hardware TRNG

stdlib/builtins_json.ny

FunctionDescriptionExample
JSON_stringify(key, value)Single-field JSON objectexamples/builtins/stdlib/json_stringify.ny
JSON_parse(json, key)Read string fieldexamples/builtins/stdlib/json_parse.ny

Combined: examples/builtins/json/main.ny

core/mem, alloc & os

import "stdlib/alloc.ny"free (FFI only; normal code auto-drops).

import "stdlib/core/mem.ny"malloc, memcpy, volatile MMIO for unsafe / no_std. See Memory → unsafe.

import "stdlib/os.ny" — platform, battery, os_getenv, syscalls, asm. See OS module table below and the OS, files & hardware guide.

alloc.ny

import "stdlib/alloc.ny"

FunctionSignatureNotes
free(p: string) -> voidFFI / advanced only. Normal Nyra code auto-drops owned strings. Compiler warns if you call this on a live owned binding.

fs.ny — files (extended)

import "stdlib/fs.ny" or declare extern in your file. Tutorial: OS, files & hardware → Filesystem.

FunctionSignatureOwnershipDescription
read_file(path: string) -> stringMoveRead entire file
write_file(path, content) -> i32BorrowsWrite file
read_file / wrappersvia stdlib/fs/mod.nyAlso append_file, exists, create_dir, remove_file, copy_file, list_dir, list_dir_entries, read_file_limit, is_dir
read_file_limit(path, max_bytes: i32) -> stringMoveRead at most max_bytes (editors / previews)
list_dir_entries(path: string) -> StrVecMoveDirectory listing without manual line split
os_arg_count() -> i32CLI argc (set at program entry; see Apps/cat)
os_arg_at(index: i32) -> stringMoveArgv entry (0 = program name)
StrVec_from_argv(skip: i32) -> StrVecMoveCLI args from index (use 1 to skip program name)
argv()() -> StrVecMoveShorthand for StrVec_from_argv(1)
exit(code: i32) -> voidTerminate process with status code
bytes_read_filevia stdlib/fs/bytes.nyBinary-safe file read (ptr handle + bytes_len)
stdin_read_bytes(max: i32) -> ptrMoveRead stdin (0 = up to 64 MiB)
basename_strstdlib/path.nyBorrowsLast path segment
Regex_newstdlib/strings/regex.nyPOSIX extended regex (use -E in Apps/grep)
tar_pack / tar_unpackstdlib/archive/tar.nyPOSIX ustar archives
gzip_compress_filestdlib/compress/gzip.nyzlib gzip (requires -lz at link)
import "stdlib/fs.ny"

fn main() {
    let msg = "hello\n"
    write_file("/tmp/out.txt", msg)
    let content = read_file("/tmp/out.txt")
    print(content)
}

strings.ny — low-level C API

import "stdlib/strings.ny"

FunctionSignatureOwnershipDescription
strlen(s: string) -> i32Borrows sByte length (C string, excludes NUL).
strcat(a: string, b: string) -> stringMove — new owned heap stringConcatenate; result auto-dropped.
strcmp(a: string, b: string) -> i32Borrows bothC-style strcmp (0 if equal).
i32_to_string(n: i32) -> stringMove — new owned heap stringFormat signed 32-bit integer.
i64_to_string(n: i64) -> stringMove — new owned heap stringFormat signed 64-bit integer (timestamps, offsets).

time.ny — timing (extern aliases)

Optional import when you want explicit extern names in scope:

import "stdlib/time.ny"

fn main() {
    time_start("bench")
    // ...
    time_end("bench")
}

Equivalent to builtins time_start / time_end without import.

mem.ny — memory stats (extern aliases)

import "stdlib/mem.ny"

fn main() {
    mem_start("phase")
    // ...
    mem_end("phase")
}

Equivalent to builtins mem_start / mem_end without import.

core/mem.ny — unsafe primitives

import "stdlib/core/mem.ny" — for no_std, embedded, or unsafe code. Link with libc or provide your own symbols when using --freestanding.

FunctionSignatureRole
malloc(size: i64) -> ptrHeap allocation
free(p: ptr) -> voidHeap free
memcpy(dst: ptr, src: ptr, nbytes: i64) -> ptrBulk copy
memset(dst: ptr, byte: i32, nbytes: i64) -> ptrBulk fill
volatile_load_i32(addr: ptr) -> i32MMIO register read
volatile_store_i32(addr: ptr, value: i32) -> voidMMIO register write
volatile_load_u32(addr: ptr) -> u32MMIO (unsigned)
volatile_store_u32(addr: ptr, value: u32) -> voidMMIO (unsigned)

Volatile symbols are experimental in the ABI manifest. See Memory → unsafe and FFI & ABI.

os.ny — OS APIs

import "stdlib/os.ny" — ready OS, hardware, and syscall wrappers (macOS, Linux, Windows).

import "stdlib/os.ny"

fn main() {
    print(platform_name())
    print(battery_percent())
    print(os_getenv("HOME"))
    print(os_getpid())
    unsafe { asm "nop" }
}
ModuleFunctionsNotes
platform.nyplatform_name(), is_linux(), page_size()Platform detection
env.nyos_getenv(name)Use os_getenv — not getenv (libc collision)
battery.nybattery_percent()0–100 or -1
unistd.nyos_read, os_write, os_syscall6, …POSIX-style + raw syscalls
syscall_linux.ny / syscall_darwin.nySYS_* constantsFor os_syscall6
syscall_windows.nyWIN_NT_*, WIN_PAGE_*, VirtualAlloc flagsWindows constants (Win32 preferred over raw syscall)
cpu.nycpu_brand(), cpu_*_cores(), cpu_has_avx2(), …CPU info
memory.nymem_map_anonymous, mem_unmap, dma_available()mmap / VirtualAlloc
storage.nydisk_total_bytes, disk_free_bytes, disk_fs_typePath mount point
netif.nynet_interface_*MAC, name, link up (not TCP — see stdlib/net)
display.nydisplay_width, display_refresh_hz, …CoreGraphics / Win32 / Linux env fallback
power.nypower_on_ac(), power_cpu_temp_centi_c()Extends battery.ny
affinity.nyaffinity_set_thread_cpu, affinity_get_thread_cpuThread affinity
clocks.nyclock_rdtsc, clock_monotonic_nsi64 timestamps
usb.ny / serial.nyUSB VID/PID, serial open/read/writeLinux sysfs + termios/COM
signals.ny / mqueue.nysignal_install, mqueue_*Poll-based signals; mqueue: Linux POSIX, macOS in-memory, Windows mailslots
hw_crypto.ny / permissions.nyhw_random_bytes, perm_chrootTRNG + priv drop
asm.nycpu_nop(), cpu_pause()Plus Nyra asm "..." in unsafe

Channels (runtime C API)

Thread-safe channels built on the Nyra runtime. Declare extern in your code or wrap in a project module.

SymbolRole
channel_new()Create channel; returns handle (i32 in MVP)
channel_send(ch, value)Send i32 value
channel_recv(ch)Blocking receive
channel_free(ch)Release channel memory

Spawn: spawn_capture (with captures) and spawn (empty). Async stubs: await, async_run (evolving).

Built-in enums

Registered in the typechecker — no import required:

TypeVariants
option / OptionNone, Some
result / ResultOk, Err
let x = Option.Some(42)
let r = Result.Ok("ok")

Where stdlib lives

أمثلة stdlib

شغّل العروض الجاهزة:

NYRA_HOME= nyra run examples/stdlib/demo/main.ny
NYRA_HOME= nyra run examples/stdlib/extended/main.ny