IlluLang Logo

IlluLang

IlluLang Standard Library Reference

This is the reference for builtins and their behavior contracts. For language syntax (types, control flow, intents), see SYNTAX. Native runtime modules (import "<name>") are listed in INTERNALS/README.

I/O

  • display(expr, ...) -> value
  • Prints arguments space-separated.
  • Returns first argument, or 0 when empty.
  • input([prompt], [type]) -> string|int|float|bool
  • Reads a line of input from stdin, returns as string.
  • Optional prompt string is printed before reading.
  • Optional type parameter converts the input: input(">> ", int), input(">> ", float), input(">> ", bool).
  • Type can be a bare identifier (int) or a string ("int").
  • read_file(path: string) -> string
  • write_file(path: string, contents: string) -> bool
  • append_file(path: string, contents: string) -> bool
  • exists(path: string) -> bool
  • list_dir([path: string]) -> array[string] -- defaults to "." if omitted
  • read_lines(path: string) -> array[string] -- reads file and splits into lines
  • file_delete(path: string) -> bool
  • file_copy(src: string, dst: string) -> bool
  • file_move(src: string, dst: string) -> bool
  • is_dir(path: string) -> bool -- checks if path is a directory
  • is_file(path: string) -> bool -- checks if path is a regular file

Types / Introspection

  • type(value) -> string
  • Returns a detailed type string:
    • Scalars: "int", "float", "bool", "string", "function", "none", "unknown"
    • Arrays: "array[int]", "array[int, float]" (union of element types)
    • Dicts: "dict[string, int]" (union of value types)
    • Matrices: "matrix[int]"
    • Custom types: returns the custom type name (e.g., "score" for let s: score = 42)
  • is_int(value) -> bool
  • is_float(value) -> bool
  • is_bool(value) -> bool
  • is_string(value) -> bool
  • is_array(value) -> bool
  • is_dict(value) -> bool
  • is_function(value) -> bool
  • is_matrix(value) -> bool
  • is_none(value) -> bool
  • is_empty(value) -> bool -- works on strings, arrays, dicts, and matrices
  • is_strict(value_or_var) -> bool

Conversion

  • to_int(value) -> int
  • to_float(value) -> float
  • to_string(value) -> string
  • to_bool(value) -> bool -- converts using truthiness rules (0/empty/none = false, everything else = true)
  • char(code: int) -> string -- converts a Unicode code point (0..1114111) to a one-character UTF-8 string
  • ord(str: string) -> int -- returns Unicode code point of the first character (0 for empty strings)

Note: values 128..159 are Unicode C1 control code points and are usually non-printable in terminals.

Math

  • abs(x) -> int|float
  • sqrt(x) -> float
  • pow(base, exp) -> float
  • floor(x) -> float
  • ceil(x) -> float
  • round(x, [decimals]) -> float -- rounds to decimals decimal places (default 0)
  • random() -> float -- automatically seeded on first call
  • random_int(min, max) -> int -- random integer in [min, max] inclusive; automatically seeded on first call
  • log(x) -> float -- natural logarithm
  • log10(x) -> float -- base-10 logarithm
  • exp(x) -> float -- e raised to the power x

Trigonometry

  • sin(x) -> float
  • cos(x) -> float
  • tan(x) -> float
  • asin(x) -> float
  • acos(x) -> float
  • atan(x) -> float
  • atan2(y, x) -> float

Operators

Operator Description Example
+ - * Standard arithmetic 2 + 35
/ Division (int when evenly divisible, float otherwise) 10 / 25, 10 / 33.333...
^ Power / exponentiation 2 ^ 101024
// Euclidean (floor) division 17 // 35
% Modulo (remainder) 17 % 32
and Logical (bool) or bitwise (int/float) AND true and falsefalse, 0xF and 0x33
or Logical (bool) or bitwise (int/float) OR 0xF0 or 0x0F255
xor Logical (bool) or bitwise (int/float) XOR 0xFF xor 0xFF0
not Logical (bool) or bitwise (int) NOT not truefalse, not 0-1

Compound Assignment

  • +=, -=, *=, /=, ^=, //=, %=
  • Works on variables and indexed targets: arr[i] += 1, d["key"] -= 5, m[r][c] *= 2

Array Arithmetic

Expression Result Description
[5] + 2 [5, 0, 0] Extend with N zeros
[5, 8] - 1 [5] Shrink by N elements
[7] * 2 [7, 7] Repeat array N times
[5, 6] ^ 2 [[5,6]:[5,6]] Convert to squared matrix (var only)
[1, 2] + [3, 4] [1, 2, 3, 4] Concatenate two arrays
[1, 2, 3] - [2] [1, 3] Remove last occurrence of each right-hand element

Number Bases

Prefix Base Example
0b Binary 0b101010
0o Octal 0o1715
0x Hexadecimal 0xFF255
0d Explicit decimal 0d4242

Arithmetic between same-base values preserves the base in the result. Use base() to convert or query:

  • base(value, target) -> int -- convert value to target base (2, 8, 10, 16). Returns the same integer with the display base set.
  • base(value) -> int -- query the current display base of a value (returns 2, 8, 10, or 16).
display(base(255, 16))  ## 0xff
display(base(255, 2))   ## 0b11111111
display(0xFF + 0x01)    ## 0x100 (base preserved)
display(base(0xFF))     ## 16

Scientific Notation

Float literals support e/E notation: 1e9, 2.5e-3, 6.022e23.

Strings

  • len(string|array|dict|matrix) -> int
  • upper(s) -> string
  • lower(s) -> string
  • substr(s, start, [len]) -> string
  • trim(s) -> string
  • trim_left(s) -> string -- trims leading whitespace (alias: ltrim)
  • trim_right(s) -> string -- trims trailing whitespace (alias: rtrim)
  • split(s, [delim]) -> array[string] -- splits by delimiter (default " ")
  • join(arr, [sep]) -> string -- joins with separator (default "")
  • replace(s, from, to) -> string
  • starts_with(s, prefix) -> bool
  • ends_with(s, suffix) -> bool
  • index_of(s, needle) -> int
  • find(s, needle) -> int -- alias for index_of
  • repeat(s, count) -> string
  • char_at(s, index) -> string
  • String indexing: s[i] returns the character at index i (negative indices count from end)

Arrays

  • slice(arr, start, [end]) -> array
  • push(arr, value) -> array (statement-form mutates target var)
  • pop(arr) -> array (statement-form mutates target var)
  • insert(arr, index, value) -> array -- inserts value at index (negative indices supported)
  • remove_at(arr, index) -> array -- removes element at index (negative indices supported)
  • find(arr, fn) -> value|none -- returns first element where fn returns truthy, or none
  • find_index(arr, fn) -> int -- returns index of first matching element, or -1
  • any(arr, [fn]) -> bool -- true if any element satisfies fn (without fn, checks truthiness)
  • all(arr, [fn]) -> bool -- true if all elements satisfy fn (without fn, checks truthiness)
  • max(arr) -> number -- also: max(a, b, ...) for scalar max
  • min(arr) -> number -- also: min(a, b, ...) for scalar min
  • contains(arr, value) -> bool
  • includes(arr, value) -> bool -- alias for contains
  • reverse(arr) -> array (statement-form mutates target var)
  • sort(arr, [fn]) -> array -- O(n log n) merge sort; optional comparator fn(a, b) returns negative/zero/positive (statement-form mutates target var)
  • unique(arr) -> array (statement-form mutates target var)
  • flatten(arr) -> array (statement-form mutates target var)
  • range(end) -> array[int] (equivalent to range(0, end))
  • range(start, end, [step]) -> array[int] (exclusive end)

Range operator notes (start->end[:step]): - End is exclusive. - Positive step follows natural direction (ascending when start < end, descending when start > end). - Negative step returns the reverse of the corresponding positive-step range.

Dictionaries

  • dict() -> dict
  • dict_get(d, key: string) -> value|0
  • dict_set(d, key: string, value) -> dict (statement-form mutates target var)
  • dict_has(d, key: string) -> bool
  • dict_remove(d, key: string) -> dict (statement-form mutates target var)
  • dict_keys(d) -> array[string]
  • dict_values(d) -> array
  • keys(d) -> array[string] -- alias for dict_keys
  • values(d) -> array -- alias for dict_values
  • dict_merge(d1, d2) -> dict -- merges two dicts (d2 keys override d1) (alias: merge)
  • dict_items(d) -> array[array] -- returns [[key, value], ...] pairs (aliases: entries, items)
  • Access: d["key"] returns value for key
  • Assignment: d["key"] = value sets value for key
  • Compound assignment: d["key"] += 1 -- all compound operators supported
  • Value arithmetic: d["key"] + 1 works because indexing returns the stored value type

Matrices

Matrices are strict 2D grids declared with let and a required element type annotation.

  • is_matrix(v) -> bool
  • mat_rows(m) -> int -- number of rows
  • mat_cols(m) -> int -- number of columns
  • mat_get(m, row, col) -> value -- get element at (row, col)
  • mat_set(m, row, col, value) -- set element at (row, col), mutates in place
  • mat_transpose(m) -> matrix -- returns a new transposed matrix
  • mat_flatten(m) -> array -- returns all elements as a flat array
  • Row access: m[row] -- returns a row as an array
  • Element access: m[row][col] -- returns element at (row, col)
  • Element assignment: m[row][col] = value -- sets element at (row, col)
  • Compound assignment: m[row][col] += value -- all compound operators supported

Matrix Declaration

let m: matrix[int] = 2*3                     ## 2×3, zero-initialized
let m: matrix[int] = [[1, 2]:[3, 4]]         ## 2×2 literal

Functional

  • map(arr, fn) -> array -- applies fn to each element
  • filter(arr, fn) -> array -- keeps elements where fn returns truthy
  • reduce(arr, fn, [initial]) -> value -- accumulates via fn(acc, elem); if initial omitted, uses first element
  • foreach(arr, fn) -> 0 -- calls fn(elem) for each element, returns 0
  • enumerate(arr) -> array[array] -- returns [[0, elem0], [1, elem1], ...]
  • zip(arr1, arr2) -> array[array] -- pairs elements: [[a0, b0], [a1, b1], ...]
  • sum(arr) -> int|float -- sums numeric elements

String Formatting

  • format(fmt, ...) -> string -- printf-style formatting (alias: sprintf)
  • %s string, %d/%i integer, %f float, %e scientific, %g general
  • %x/%X hex, %o octal, %b binary, %c character
  • Width: %10d, zero-pad: %05d, left-align: %-10s, precision: %.2f
  • %% for literal percent

Error Handling

  • throw(message) -- raises a user-defined error[throw] error (works as both statement and expression)
  • Statement form: throw "something went wrong"
  • Expression form: throw("error message")
  • Caught by try { ... } instead { ... } blocks, exposed as error variable
  • Non-string arguments are automatically converted to strings
  • References Enum.Errors.ThrowError in error output
  • assert(condition, [message]) -- verifies condition is truthy
  • On failure, raises error[assert] with optional message as hint
  • References Enum.Errors.AssertionError in error output
  • Example: assert(x > 0, "x must be positive")

Enum.Errors

Built-in error constant namespace. Each constant evaluates to its fully-qualified string name:

  • Enum.Errors.SyntaxError -- parser/syntax errors
  • Enum.Errors.TypeError -- type mismatch errors
  • Enum.Errors.DivisionByZero -- division by zero
  • Enum.Errors.IndexOutOfRange -- array/string index out of range
  • Enum.Errors.RuntimeError -- undefined variable/function reference
  • Enum.Errors.ThrowError -- user-thrown errors via throw
  • Enum.Errors.AssertionError -- assertion failures via assert
  • Enum.Errors.KeyboardInterrupt -- interrupt/signal errors

Custom Enums (makenum)

Define custom enum categories with makenum Category[type] { Key: value, ... }:

  • makenum HttpStatus[int] { OK: 200, NotFound: 404 } -- creates an integer enum
  • makenum Color[string] { Red: "red", Green: "green" } -- creates a string enum
  • Access via Enum.Category.Member (e.g., Enum.HttpStatus.OK -> 200)
  • Re-declaring an existing category appends only missing members; existing keys are unchanged
  • Built-in categories (for example Errors) can be extended only one member at a time

Deletion (del)

Use del to remove user-defined names or indexed entries:

  • del name -- deletes a user-defined variable, custom type, or custom enum category
  • del name.member -- deletes a dictionary member using dot path syntax
  • del Enum.Category -- deletes a user-defined enum category by namespace path
  • del Enum.Category.Member -- deletes a user-defined enum member by namespace path
  • del name[index] -- deletes an array element or dictionary key

Examples:

  • del cache -- remove variable cache
  • del nums[2] -- remove third array element
  • del cfg["host"] -- remove dict key

Named import internals are protected. del lib["x"] is blocked, while del lib is allowed. Built-in enum categories are protected. del Enum.Errors is blocked. Built-in enum members are protected. del Enum.Errors.SyntaxError is blocked. Named import internals are also protected from assignment/mutation (lib["x"] = ..., lib.x = ..., lib["x"] += ..., lib.x += ...).

JSON

  • json_parse(str: string) -> value -- parses a JSON string into an IlluLang value (objects become dicts, arrays become arrays). Supports all standard escapes including \b, \f, and \uXXXX Unicode escapes with proper UTF-8 encoding.
  • json_stringify(value) -> string -- converts an IlluLang value to a JSON string

System

  • clock() -> float -- current time in seconds (since epoch)
  • exit([code]) -> void -- exits the process
  • env_get(name: string) -> string -- get environment variable
  • env_set(name: string, value: string) -> bool -- set environment variable
  • env_list() -> dict -- returns all environment variables as a dict
  • getcwd() -> string -- current working directory
  • chdir(path: string) -> bool -- change working directory
  • system_exec(cmd: string) -> string -- execute shell command, returns output
  • input([prompt], [type]) -> string|int|float|bool -- read a line from stdin; optional type converts result
  • get_args([index]) -> array[string] | string | none -- script CLI args (excluding script path). With index, returns one arg or none.

Path

  • path_join(parts...) -> string -- joins path components
  • path_dir(path: string) -> string -- directory portion of path
  • path_base(path: string) -> string -- filename portion of path
  • path_ext(path: string) -> string -- file extension (including dot)

Internal Libraries

Internal libraries are imported with an angle-bracket module ID inside a string literal:

  • import "<time>"

Detailed internal-library docs are maintained in:

  • INTERNALS/TIME.html
  • INTERNALS/WINDOWS.html

Intent-Oriented

  • achieve("name", ...args) -> value|0 -- dispatches intent, returns handler result
  • achieve_async("name", ...args) -> int -- schedules intent dispatch as a deferred task, returns task ID. Use await(task_id) or await_all(...) to execute.
  • intents() -> array[string] -- list all registered intent names
  • handlers(name: string) -> array[dict] -- list handlers for intent

Intent handlers support yield - yielded values are collected and returned as an array.

String Builder

  • sb_new() -> int -- creates a new string builder, returns a builder ID
  • sb_append(sb: int, value) -> void -- appends value (converted to string) to the builder
  • sb_to_string(sb: int) -> string -- returns the built string
  • sb_len(sb: int) -> int -- current total length in characters
  • sb_count(sb: int) -> int -- number of sb_append calls performed
  • sb_clear(sb: int) -> void -- resets the builder (clears contents and counter)

Reference Cells

  • ref(value) -> int -- creates a reference cell holding value, returns a cell ID
  • deref(cell_id: int) -> value -- reads the current value of the cell
  • ref_set(cell_id: int, value) -> void -- updates the cell's value

Reference cells enable shared mutable state across closures. The cell ID is an integer that can be captured by lambdas.

Typed Array Constructors

  • int_array(size: int, default: int) -> array[int] -- pre-allocates an array of size ints
  • float_array(size: int, default: float) -> array[float] -- pre-allocates an array of size floats
  • bool_array(size: int, default: bool) -> array[bool] -- pre-allocates an array of size bools
  • string_array(size: int, default: string) -> array[string] -- pre-allocates an array of size strings

Async / Await

  • async(fn: function) -> int -- schedules a zero-argument function for execution, returns a task ID
  • achieve_async("name", ...args) -> int -- schedules an intent dispatch as a deferred task, returns a task ID
  • await(task_id: int) -> value -- executes the task (if still pending) and returns its result. Works for both async() and achieve_async() tasks.
  • await_all(t1: int, t2: int, ...) -> array -- executes all tasks and returns an array of results

Note: Tasks are currently executed eagerly when await or await_all is called (cooperative scheduling, not parallel threading).

Notes

  • Division (/) returns int when evenly divisible, float otherwise; use // for euclidean (floor) division.
  • and, or, xor, not are dual-purpose: logical on booleans, bitwise on integers/floats.