Skip to content

ii. Builtins

Xansidev edited this page Nov 8, 2026 · 6 revisions

Builtins

This part is extremely underspec'd and is mostly just a list of functions. This will be improved in the future.

src/builtins.c

_write(fd, string) -> i32
_exit(code)
_traceback() -> string
_clock() -> f64
_rand() -> i32
_len(v) -> u32
_get(v, i)
_set(a, i, v)
_trunc(a, n)
_cast(v, "type")
_read(fd, n) -> string
_open(path, mode) -> fd
_close(fd)
_run(cmd) -> i32
_seed(n)
_pipe() -> [rfd, wfd]
_spawn(cmd, in, out, err) -> pid
_wait(pid) -> i32

_open(path, "mode")                // r, w, rw, standard stuff
_read(fd, chunk_size)
_write(fd, "string") -> stdout     // flushed per write, fd 2 -> stderr

_run(cmd) -> exit_code             // returns the exit code (128+signal if killed) and flushes first so child output stays ordered

_get(v, i)
_set(i, len, v) 

_mmap(size) -> int                 // address, or null on failure
_munmap(addr, size)
_peek(addr) -> int                 // one byte, 0-255
_poke(addr, byte)
_memcpy(dst, src, n)

_mmap(size) anonymous read/write memory straight from the OS; returns its address as an int

_munmap(addr, size) gives a region from _mmap back to the OS

_peek(addr) / _poke(addr, byte) read/write a single byte at an address

_memcpy(dst, src, n) copies n bytes (memmove, so overlapping regions are safe)

These are raw and unchecked. A bad address segfaults the interpreter instead of raising a vivi error. Addresses are plain ints. Memory builtins are POSIX only (Linux/macOS).

_get/_set are positional over every entry (t[i] matches an int key first). _get on a string returns the byte as an int. _set past the end pads with null.

_trunc only shrinks and args aren't copied. _set/_trunc mutate the caller's array and each builtin checks its own args.

bad type / out of range -> builtin_contract wrong count -> builtin_arity

builtins are :: names, redeclaring one in any scope -> reserved callable, not usable as values, a bare _write is undefined.

Wrap them in a function to pass it around and make it visible everywhere, including namespaced imports. They aren't exported through a module's namespace.

_base.vivi

This file is auto included in every program and needs no #import

malloc(size) -> int              // returns the address of a block of at least size bytes
free(ptr)                        // currently a no-op, memory is not reused yet
memcpy(dst, src, n)              // wrapper around _memcpy

exit(code)
panic(str)
timestamp()
traceback()
rand()
seed(n)
hash(str)

bool(v)
i8(v)
i16(v)
i32(v)
i64(v)
u8(v)
u16(v)
u32(v)
u64(v)
f32(v)
f64(v)
rune(v)
string(v)
cast(*v, type)

#method len()
#method char_at(i)
#method push(v)
#method pop()
#method empty()
#method add(i, v)
#method take(i)
#method sort()

Io

// CLI draw functions
rgb := (r, g, b, text)            // 24-bit color converter
clear_screen()
clear_line()
cursor_to()
cursor_hide()
cursor_show()
    
input(prompt)
read_line() -> string

// These go through the regular stdout
print(...)                       // No newline
println(...)                     // Provides a free newline
printf(...)                      // %x (int)
                                 // %d (double)
                                 // %s (string)
                                 // %c (rune)

// These go through stderr
eprint(...)                      // No newline
eprintln(...)                    // Provides a free newline
eprintf(...)                     // %x (int)
                                 // %d (double)
                                 // %s (string)
                                 // %c (rune)
    
// File handling
file_exists(path) -> bool
file_lines(path) -> array
file_read(path) -> text
file_write(path, text)
file_append(path, text)

Sys

run(cmd)                         // Run cmd with the script's own stdin/stdout/stderr; returns the exit code
capture(cmd)                     // Run cmd and return [exit code, stdout as a string]
feed(cmd, text)                  // Run cmd with text as its stdin; returns the exit code
pipe(left, right)                // left | right; returns right's exit code
redirect(cmd, path)              // cmd > path

Json

#import "Json"                   // lib/core/json.vivi

json_parse(text) -> value        // returns null on bad input, see json_error()
json_parse_strict(text) -> value // same, but panic()s on bad input (can't be caught)
json_error() -> string           // message from the last json_parse, null if it succeeded
json_stringify(v) -> string      // compact JSON
json_pretty(v, indent) -> string // indented JSON, indent is a number of spaces (default 2) or a string

Mapping

object       -> array with string keys      doc["name"]
array        -> array                       doc[0]
string       -> string
number       -> int, or f64 if it has a fraction or exponent
true / false -> bool
null         -> null

doc := json_parse("{\"name\": \"vivi\", \"tags\": [\"a\", \"b\"]}")
println(doc["name"])             // vivi
println(doc["tags"][1])          // b

Going the other way, an array is written as an object when any of its keys isn't just its position, otherwise as an array. nan and inf are written as null.

Errors

panic() can't be caught, so json_parse simply doesn't use it. It returns null and sets the message json_error() gives back:

json: unterminated array (line 1, column 6)

The message is reset on every json_parse call. Check json_error(), not the result: a JSON null and a failed parse both return null, and an empty array also compares equal to null.

    doc := json_parse(text)
    if json_error() != null {
        eprintln(json_error())
        exit(1)
    }

Use json_parse_strict if you'd rather the script stop on bad input which was built in to use personally and now for testing.

Limits and quirks right now.

{} and [] both parse to an empty array, so {} is written back as []. Single-character string literals are runes in vivi, so a hand-written ["x": 1] has rune keys and is written as an array. Use keys of two or more characters. Keys from json_parse are always strings, so parsed data round-trips fine. json_parse("7") works, a single character is converted to a string first. Strings are bytes. \uXXXX escapes (including surrogate pairs) are encoded as UTF-8, and raw UTF-8 passes through untouched. Numbers keep 18 significant digits, longer integers become floats. Nesting is limited to 512 levels.

I (Xansidev) am Not strict about: leading zeros (01 parses as 1) raw control characters inside strings a BOM at the start of the text

Internals

Parser state is module-level (json_text, json_pos, json_err) because arrays are passed to functions by value. That means json_parse isn't reentrant. Every other json_ name in the file (json_at, json_fail, json_skip, json_hex4, json_utf8, json_string, json_number, json_literal, json_array, json_object, json_value, json_encode, json_quote, json_repeat) is an internal helper, and they're all visible globally once the lib is imported.

Math

abs(x)
min(a, b)
max(a, b)
clamp(x, low, high)
lerp(a, b, t)
sign(x)
copysign(x, y)
trunc(x)
ceil(x)
round(x)
fmod(x, y)
modf(x)
sqrt(x)
exp(x)
log(x)
log10(x)
expm1(x)
cbrt(x)
hypot(a, b)
pow(base, exponent)
sin(x)
cos(x)
atan(x)
atan2(y, x)
asin(x)
acos(x)
sinh(x)
cosh(x)
tanh(x)
acosh(x)
deg_to_rad(d)
rad_to_deg(r)
gcd(a, b)
lcm(a, b)
factorial(n)
gamma(x)
erf(x)
erfc(x)

Time

now()
dt(time)
dateTime(time, base_offset)
getTime(time, base_offset, zulu)
getDay(day, month, year)                // Uses the Tomohiko Sakamoto algorithm
getMonth(month)
getYear(year)
formatDate(day, month, year)

Strings

index_of(str, substr, from)
is_digit(c)
has_prefix(str, prefix)
has_suffix(str, suffix)
contains(str, substr)
substring(str, start, end)
split(str, delimiter)
join(str1, str2)
replace(str, target, replacement)
trim(str)
to_upper(str)
to_lower(str)
reverse(str)
to_pascal_case(str)
to_camel_case(str)
to_snake_case(str)

Clone this wiki locally