Built-in system modules

TON618 ships with twelve built-in system modules. They aren't files on disk — they live inside the interpreter — but you still IMPORT://ton.<name> them before using them, exactly like a user module:

IMPORT://ton.sys
IMPORT://ton.os
IMPORT://ton.requests
IMPORT://ton.random
IMPORT://ton.time
IMPORT://ton.json
IMPORT://ton.mathutils
IMPORT://ton.strings
IMPORT://ton.encoding
IMPORT://ton.regex
IMPORT://ton.path
IMPORT://ton.tensor

Calling any of the functions below without first importing its module fails with an "undefined function" error — this is intentional: a script only pays for (and only exposes) the built-ins it actually asked for. Every module follows the naming convention recommended for user modules above: every function is prefixed with the module's own name.

#ton.sys — runtime & process information

FunctionDescription
sys_args()Array of extra command-line arguments passed after the script path (ton618 script.ton foo bar → ["foo", "bar"])
sys_platform()"windows", "termux", "macos", or "linux" — auto-detected (Termux is told apart from plain Linux via its $PREFIX environment variable)
sys_arch()"x64", "arm64", "arm", "x86", or "unknown"
sys_version()The interpreter's own version string (e.g. "beta-1.0.1"), same as ton618 --version
sys_exit(code)Stops the whole program immediately with the given exit code
sys_sleep(ms)Pauses execution for the given number of milliseconds

#ton.os — environment variables & filesystem

FunctionDescription
os_name()"nt" on Windows, "posix" elsewhere
os_getenv(name)An environment variable's value, or nil if unset
os_setenv(name, value)Sets an environment variable for this process; returns whether it succeeded
os_cwd()The current working directory
os_exists(path)Whether a file or directory exists
os_isfile(path) / os_isdir(path)Whether path exists and is that kind of entry
os_mkdir(path)Creates a directory (and any missing parent directories)
os_remove(path)Removes a file or an empty directory
os_rename(src, dst)Renames/moves a file or directory
os_copy(src, dst)Copies a file, overwriting dst if it already exists
os_listdir(path)Array of entry names directly inside a directory (not recursive)
os_readlines(path)Array of the file's lines (no trailing newlines)
os_appendfile(path, content)Appends text to a file, creating it if needed
os_tempdir()The system's temporary-files directory

#ton.requests — a minimal HTTP client

A small, dependency-free HTTP client (raw sockets, same spirit as the built-in server). Limitation: http:// only, no TLS/https:// — there is no bundled SSL library, so it can talk to local services, other TON618 servers, or any plain-HTTP endpoint, but not to an HTTPS-only API.

FunctionDescription
requests_get(url)Performs a GET request
requests_post(url, [body])Performs a POST request with an optional string body
requests_request(method, url, [body])Performs a request with any HTTP method

All three return a ton.dict with the same shape:

{
    ok: true,      // whether a response was received at all
    status: 200,     // the HTTP status code (0 if the request failed outright)
    body: "...",       // the raw response body
    error: ""            // a human-readable reason when ok is false
}
IMPORT://ton.requests

ton.dict res = requests_get("http://localhost:8081/api/users")
if res["ok"] {
    print("Status: " + str(res["status"]))
    print(res["body"])
} else {
    print("Request failed: " + res["error"])
}

#ton.random — extra randomness helpers

Complements the always-available random() with a few common patterns:

FunctionDescription
random_int(min, max)An integer in [min, max], inclusive on both ends
random_float()A float in [0, 1)
random_choice(arr)A uniformly random element from a non-empty array
random_shuffle(arr)Shuffles an array in place (Fisher-Yates) and returns it
random_seed(n)Reseeds the random generator deterministically — useful for reproducible tests

#ton.time — clocks & timestamps

FunctionDescription
time_now()Seconds since the Unix epoch
time_millis()Milliseconds since the Unix epoch — handy for measuring elapsed time
time_string([timestamp])A human-readable local time string; defaults to now
time_sleep(ms)Pauses execution for the given number of milliseconds (same as sys_sleep)

#ton.json — JSON parsing & pretty-printing

The always-available json(x) native already turns a value into compact JSON. IMPORT://ton.json adds the other direction, plus a multi-line format:

FunctionDescription
json_parse(text)Parses a JSON string into a ton.dict/ton.array/scalar
json_stringify(value)Same as json(value), provided under a matching name for scripts that import this module
json_pretty(value)Same as json_stringify, indented across multiple lines for human-readable output
IMPORT://ton.json
IMPORT://ton.requests

ton.dict res = requests_get("http://localhost:8081/api/users")
ton.array users = json_parse(res["body"])
print(len(users))

#ton.mathutils — trig, logs & stats helpers

Complements the always-available sqrt/pow/abs/floor/ceil/round/min/max with trigonometry, logarithms, and small statistics/number-theory helpers:

FunctionDescription
mathutils_pi() / mathutils_e()The constants π and e
mathutils_sin/cos/tan(x), mathutils_asin/acos/atan(x), mathutils_atan2(y, x)Trigonometry, in radians
mathutils_log(x) / mathutils_log2(x) / mathutils_log10(x) / mathutils_exp(x)Natural, base-2, base-10 logarithms, and e^x
mathutils_hypot(x, y)sqrt(x*x + y*y), computed without overflow
mathutils_degrees(rad) / mathutils_radians(deg)Angle unit conversion
mathutils_clamp(x, lo, hi)Restricts x to [lo, hi]
mathutils_lerp(a, b, t)Linear interpolation between a and b at t (0..1)
mathutils_sign(x)-1, 0, or 1
mathutils_gcd(a, b) / mathutils_lcm(a, b)Greatest common divisor / least common multiple of two integers
mathutils_factorial(n)n! for a non-negative integer n
mathutils_is_prime(n)true if n is prime
mathutils_sum(arr) / mathutils_mean(arr) / mathutils_median(arr) / mathutils_stddev(arr)Sum, mean, median, and population standard deviation of a numeric array
mathutils_min_of(arr) / mathutils_max_of(arr)Smallest/largest number in an array (unlike min()/max(), which take separate arguments)
IMPORT://ton.mathutils

print(mathutils_gcd(48, 18))          // 6
print(mathutils_mean([1, 2, 3, 4]))   // 2.5
print(mathutils_clamp(15, 0, 10))     // 10

#ton.strings — extra string helpers

Complements the always-available upper/lower/trim/split/replace/contains/substring:

FunctionDescription
strings_starts_with(s, prefix) / strings_ends_with(s, suffix)Prefix/suffix tests
strings_repeat(s, n)Repeats s n times
strings_reverse(s)Reverses a string (the always-available reverse() only works on arrays)
strings_capitalize(s)Uppercases the first letter, lowercases the rest
strings_pad_left(s, width, [ch]) / strings_pad_right(s, width, [ch])Pads s up to width with ch (default " ")
strings_center(s, width, [ch])Centers s within width, padding both sides with ch
strings_count(s, sub)Number of non-overlapping occurrences of sub in s
strings_trim_start(s) / strings_trim_end(s)Strip whitespace from only the start/end of s (trim() strips both)
strings_words(s)Array of whitespace-separated words (unlike split(), which needs an exact separator)
strings_replace_first(s, search, repl)Replaces only the first occurrence of search
strings_snake_case(s)"Hello World" → "hello_world"
strings_camel_case(s)"hello_world" → "helloWorld"
IMPORT://ton.strings

print(strings_capitalize("hello world"))  // "Hello world"
print(strings_pad_left("7", 3, "0"))      // "007"

#ton.encoding — base64, hex, and URL percent-encoding

Dependency-free encoders/decoders for the formats scripts most often need when talking to web APIs:

FunctionDescription
base64_encode(s) / base64_decode(s)Standard base64
hex_encode(s) / hex_decode(s)Lowercase hexadecimal
url_encode(s) / url_decode(s)Percent-encoding (also used internally to parse a local server request's query string)
IMPORT://ton.encoding

print(base64_encode("hello world"))  // aGVsbG8gd29ybGQ=
print(url_encode("a b/c"))            // a%20b%2Fc

#ton.regex — pattern matching

Backed by C++'s standard <regex> library (ECMAScript syntax) — no external dependency, and the same regex flavor used by JavaScript.

FunctionDescription
regex_test(s, pattern)Whether pattern matches anywhere in s
regex_match(s, pattern)[fullMatch, group1, group2, ...] for the first match, or nil
regex_find_all(s, pattern)Array of every full match found in s
regex_replace(s, pattern, repl)s with every match replaced; repl can use $1, $2... for capture groups
regex_split(s, pattern)Array of substrings, splitting s on every match
IMPORT://ton.regex

print(regex_test("hello123", "[0-9]+"))                          // true
print(regex_replace("2024-01-15", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1"))  // 15/01/2024

#ton.path — filesystem path manipulation

Pure string/path manipulation — no disk access (see ton.os for that).

FunctionDescription
path_join(a, b, ...)Joins any number of path segments with the platform separator
path_basename(p)The filename with its extension
path_dirname(p)The parent directory
path_extension(p)The extension including the dot, or "" if none
path_stem(p)The filename without its extension
path_absolute(p)An absolute path (resolved against the current working directory)
IMPORT://ton.path

print(path_join("a", "b", "c.txt"))     // a/b/c.txt
print(path_extension("/foo/bar.txt"))    // .txt

#ton.tensor — small 1D/2D numeric arrays for basic ML work

A tensor is a ton.dict with two fields — {shape: [...], data: [...]} (data is flat, row-major) — so it prints, str()s, and json()s like any other dict. The functions below implement element-wise/matmul/reduction ops as real C++ loops (bypassing the AST), a genuine speed-up over the same loop hand-written in TON618 — but see honest limits below before reaching for this to do anything ambitious. This same {shape, data} convention is what the community atome module (a plain .ton file, not part of the interpreter — see ton618 install atome) builds its autograd/training layer on top of.

FunctionDescription
tensor_zeros(shape) / tensor_ones(shape) / tensor_full(shape, value)A new tensor of the given shape (1 or 2 dimensions), filled
tensor_random(shape, [lo=0, hi=1])A new tensor filled with values uniformly random in [lo, hi) (uses the same RNG as random()/ton.random — seed it with random_seed() for reproducible runs)
tensor_from_array(arr)Builds a tensor from a flat array (1D) or an array of same-length arrays (2D)
tensor_to_array(t)The reverse: a plain ton.array (nested for 2D)
tensor_shape(t) / tensor_size(t)The shape array / total element count
tensor_clone(t)A deep copy — t and its dict/array fields are otherwise shared references like any dict, so mutating one alias mutates all of them
tensor_reshape(t, newShape)A new tensor viewing the same data with a different shape (element count must match)
tensor_get(t, indices) / tensor_set(t, indices, value)Read/write one element — indices is [i] for 1D, [row, col] for 2D
tensor_add(a, b) / tensor_sub(a, b) / tensor_mul(a, b) / tensor_div(a, b)Element-wise; either side may be a plain number (scalar broadcast), but two tensors must have the same shape — there is no NumPy-style broadcasting between differently-shaped tensors
tensor_add_bias(mat, bias)Adds a 1D bias to every row of a 2D matrix — the one deliberate exception to "no broadcasting," exactly what a dense/linear layer needs
tensor_matmul(a, b)2D matrix multiply (a is m×k, b is k×n, result is m×n)
tensor_transpose(t)2D transpose
tensor_sum(t) / tensor_mean(t) / tensor_max(t) / tensor_min(t)Reduce every element to one number (no per-axis reduction)
tensor_relu(t) / tensor_sigmoid(t) / tensor_tanh(t) / tensor_exp(t) / tensor_log(t)Element-wise activation/math functions
tensor_softmax(t)Softmax over the whole vector (1D) or row-wise (2D)
tensor_relu_grad(input) / tensor_sigmoid_grad(output) / tensor_tanh_grad(output)Element-wise derivatives for hand-rolled backprop — note sigmoid_grad/tanh_grad take that function's output (cheaper to express that way), while relu_grad takes its input
tensor_map(t, fn)Applies a ton.function/function-expression to every element — slower than the natives above (one interpreter call per element) but works for any custom scalar function
tensor_argmax(t)The index of the largest element (1D), or one index per row (2D) — the "which class did this predict" op
tensor_conv1d(signal, kernel, [stride=1])1D "valid" convolution (cross-correlation) on single-channel 1D tensors: out[i] = sum_j signal[i*stride+j] * kernel[j] — see the community atome module for how multi-channel Conv1D layers (and their gradient) are built from this primitive
tensor_to_bytes(t)Packs the tensor's flat data as raw IEEE-754 float64 bytes (native endianness), returned as a ton.string — combined with writefile (which writes a string's exact bytes), this is what lets a module write real binary files instead of JSON text. Not portable between machines of different endianness
tensor_from_bytes(bytes, shape)The inverse of tensor_to_bytes — unpacks a raw bytes string (e.g. from readfile + substring) back into a tensor of the given shape; errors if the byte length doesn't match shape's element count × 8
IMPORT://ton.tensor

ton.dict a = tensor_from_array([[1, 2], [3, 4]])
ton.dict b = tensor_from_array([[5, 6], [7, 8]])
print(tensor_to_array(tensor_matmul(a, b)))   // [[19, 22], [43, 50]]
print(tensor_to_array(tensor_relu(tensor_from_array([-1, 0, 2]))))  // [0, 0, 2]

Honest limits — read this before building anything ambitious on top of ton.tensor:

  • CPU only. There is no GPU compute backend (no CUDA/OpenCL bindings) anywhere in this interpreter, and none is planned — "GPU support" isn't something a .ton module can add on its own.
  • 1D and 2D shapes only — no 3D+ tensors (so no image batches, no attention-head-shaped tensors, etc. without flattening/reshaping tricks yourself).
  • Only scalar broadcasting (plus the one explicit tensor_add_bias exception above) — tensor + differently-shaped-tensor (general NumPy-style broadcasting) does not work.
  • No autograd built in. ton.tensor gives you the forward ops and the matching _grad helpers to build backpropagation by hand — there's no automatic computation-graph tracking. See the community atome module (ton618 install atome) for a from-scratch autograd/training layer built on top of this.
  • Not remotely competitive with a real numeric library. These are still C++ loops over a dynamically-typed Value array — real work for a small language, but nowhere near BLAS/cuDNN performance. Fine for learning, toy models, and small experiments; not for training anything at real scale.

Edit this page on GitHub