Built-ins¶
These names live in stdlib/builtins.kod and are available in every Kod program without an explicit import.
A call without a module name, f(args), goes to the first of these that
exists:
- a struct named
fthat the module sees (Pt(x: 1)constructs); - the innermost binding of
fin force, when it holds a function value; - a function the module declares or lists in an
import; - the builtin of that name.
A binding that holds anything else doesn't hide a function, so
let len = len(xs) and a later len(ys) both call the builtin. It does
hide any outer binding of its name: after let g = double, a call
g(1) in a block that binds let g = 5 goes to the module's or the
builtin g. With neither, it is an error:
`g` is a local of type `int64`, not a function.
A function value declared in a block hides an outer one only inside that
block; after the block, f(args) calls the outer one again. With no
binding of f in force and no function of that name, the call is an
error: `f` is called before its `let` or
`f` is declared in a block that has ended; declare it outside the block to call it here.
The same holds for len, str, hash and panic: a module can
declare its own func hash(anon p: Point) -> int64, and
its hash(...) calls use it, while another module's dep.hash(x) names
that one. An f-string always converts its values with the builtin str.
Only the builtin panic counts as a call that never returns; a
module's own or imported panic, or a local function value of that
name, is an ordinary call. A local named panic that holds anything
else doesn't hide the builtin, so panic(msg) after
let panic = 5 never returns.
Output¶
| Function | Signature | Description |
|---|---|---|
print |
(x) -> none |
Print x, followed by a newline. Takes whatever f"{x}" does (see Strings). |
print_int |
(int64) -> none |
Print an integer followed by a newline. Equivalent to print(n.to_str()). |
kod_puts |
(str) -> int64 |
Write a string and a newline to stdout. What print calls; embedded NULs are written as-is. |
putchar |
(int64) -> int64 |
C putchar: write a single byte to stdout. Shares libc's stdout buffer with print. |
Length¶
| Function | Signature | Description |
|---|---|---|
len |
(str) -> int64 |
String length in bytes. |
len |
([T]) -> int64 |
Number of elements in an array. |
len |
(SomeStruct) -> int64 |
Dispatches to the struct's func len(self) -> int64 method if one exists (e.g. Map.len); a len method of any other shape is an error. |
As a value, len is its string form: let n: func(str) -> int64 = len.
Bytes¶
| Function | Signature | Description |
|---|---|---|
kod_str_to_bytes |
(str) -> bytes |
The same bytes, typed bytes; nothing is copied. |
kod_bytes_to_str |
(bytes) -> str |
The same bytes, typed str; nothing is copied. |
kod_bytes_from_array |
([int64]) -> bytes |
One byte per element, from its low 8 bits. |
kod_bytes_le64 |
(bytes, int64) -> int64 |
The 8 bytes from at as one int64, the first byte lowest (little-endian). An at below 0, or fewer than 8 bytes left, panics with the index of the first missing byte. |
kod_bytes_le64(b, at) is what reading the 8 bytes one at a time and
shifting them together gives, in one load: a decoder reading many bits at a
time uses it to fill its bit buffer.
String conversion¶
There is no int_to_str builtin — primitives carry their own to_str methods:
let s: str = 42.to_str() // "42"
let t: str = true.to_str() // "true"
let u: str = "hi".to_str() // identity
F-strings interpolate non-str values by calling to_str automatically:
Hashing¶
int64.hash is the identity function; str.hash is djb2; bool.hash is 0/1.
Used internally by Map[K, V].
The hash(x) builtin takes a hashable value: an int64, str, bytes or
bool, a value of an enum whose variants have no payloads, which hashes
by variant, or a value of a union whose members are all hashable, such as
int64 | str. Hashing anything else, such as a struct, an array, an optional
or an enum with payload variants, is an error
(cannot hash a value of type `[int64]`), as is hashing a union with a
member that can't be hashed, which the error names
(cannot hash a value of type `[int64] | int64`; its member `[int64]` can't be hashed).
It gives what the methods above give, a bytes value hashes like the str
with the same bytes, an enum value hashes to its variant's position, counting
from 1, and a union value hashes the member it holds, mixed with which member
that is, so the int64 0 and the bool false don't collide.
Map[K, V]¶
A built-in generic. Open-addressing hash map (PEP 468 dense + sparse).
A map is a value, like an array: let n = m gives n the map as it is, and
m.set(...) afterwards changes only m. So set, remove and m[k] = v
need a map that may be changed, a mut binding, a field, or a mut
parameter, and a function that fills a caller's map takes it as a
mut parameter. Nothing is copied until a
map another holder still has is changed. Set[T] (in sets) is a value the
same way.
mut m: Map[str, int64] = Map[str, int64]()
m.set("a", 1)
m.set("b", 2)
match m.get("a") {
Some(v) -> print(v.to_str())
none -> print("miss")
}
print(len(m).to_str()) // 2
| Method | Description |
|---|---|
set(k, v) |
Add k with value v, or replace the value k has. m[k] = v is the same. |
get(k) -> V? |
k's value, or none when k isn't in the map. m[k] is the same. |
m[k, default: d] |
k's value, or d when k isn't in the map; m[k, default: d] += v changes it in place (see Indexing a struct). |
get_or_set(k, v) -> V |
k's value; when k isn't in the map, v, which becomes k's value. One search either way, as for numbering names: ids.get_or_set(name, len(ids)). |
contains(k) -> bool |
Whether k is in the map. |
remove(k) -> V? |
Take k out of the map, giving the value it had, or none when it wasn't there. |
keys() -> [K] / values() -> [V] |
The keys, or the values, in the order the keys were first set, as a new array. |
len(m) |
How many keys the map holds. |
f"{m}", str(m), print(m) |
The entries in order as text, {a: 1, b: 2}, each key and value as an f-string shows it; {} when empty. The key and value types must have a text of their own. |
The entries keep the order their keys were first set in: setting a key again
changes its value but not its place, and a key that is removed and set again goes
last. for k in m and for k, v in m go over them in that order (see
for / in). set, get, contains and
remove take constant time on average.
A lookup finds the entry whose key is == to the one it's given, so key
equality depends on the key type: str and bytes keys match by
content, int64 and bool keys by value, enum keys by variant, and union
keys when they hold the same member and those are equal, so in a
Map[int64 | str, V] the keys 1 and "1" are two keys.
The key type must be hashable, as for hash(x): int64, str, bytes,
bool, an enum without payload variants, or a union of those. Any other key type, such as
Map[[int64], int64], Map[int64?, str] or a struct, is an error at the
type argument that names it, in whichever module it's written
(`[int64]` can't be a `Map` key), reported once per key type. A key
that comes from another generic type's parameter is reported at the
argument of that type that is or holds the key: with
type Index[V, K] = struct { m: Map[K, V] }, a parameter of type
Index[int64, Pt] is an error at Pt
(`Pt` can't be a `Map` key in `Index[int64, Pt]`). A Map[T, V] in
a generic type's method names the instance whose T is the bad key
(`Pt` can't be a `Map` key in `Box[Pt]`); any other bad key in a
method, such as a Map[Pt, int64] written out in Box[Pt], ends with the
instance it's compiled for, as other errors there do
((in `Box[Pt]`)). The same holds for the element type of a
Set[T] from the sets module, which shows as its elements in braces,
{a, b}, in the order they were first added.
Indexing a struct¶
m[k] calls the struct's op_index and m[k] = v its op_index_set,
which is how Map supports both (m[k] is a V?, like m.get(k)).
op_index must take one key besides self, and op_index_set a key and
a value:
func op_index(self, anon key: K) -> V? { ... }
func op_index_set(mut self, anon key: K, anon value: V) -> none { ... }
The key and value must have those parameters' types, like a method's
arguments. m[k] = v evaluates m, then k, then v before the call.
m[k, default: d] is k's value, or d when there is none, through the
struct's op_index_or; for a Map it is a V, not a V?:
mut counts = Map[str, int64]()
mut groups = Map[int64, [str]]()
for word in words {
counts[word, default: 0] += 1
groups[len(word), default: []] += [word]
}
A change to an entry, such as m[k] += v, m[k][i] = v, m[k].x = v or
the same with default:, changes the value where the struct keeps it: m,
k and v are evaluated first (in that order), then op_index_take (or
op_index_take_or with the default) takes the value out, the change is
made to it, and op_index_set puts it back. Since nothing else holds the
value meanwhile, appending to an array in a map doesn't copy it. Without
default: the key must be there; a Map panics when it isn't
(key not in map). A struct that declares neither take method gets
m[k] += v as op_index and then op_index_set, each with the same m
and k:
func op_index_or(self, anon key: K, default: V) -> V { ... }
func op_index_take(mut self, anon key: K) -> V { ... }
func op_index_take_or(mut self, anon key: K, default: V) -> V { ... }
Error handling¶
| Name | Description |
|---|---|
Error (interface) |
Marker for types that can be thrown. Requires to_str(self) -> str. |
ExitCode (interface) |
exit_code(self) -> int64, declared but not consulted yet: an Err that main returns exits with status 1 whatever it implements. |
panic |
Print panic: <msg>\n to stderr and exit(1). Used by must and by assert outside a test. |
kod_eprint (extern) |
Write to stderr without exiting. |
Testing¶
| Name | Description |
|---|---|
fail(msg) |
Mark the current test "..." {} as failed; outside a test, no-op. |
assert <expr> |
Statement form. Inside a test, flag on false; outside, panic. Source text is captured at parse time. See Testing. |
I/O¶
The io module wraps the filesystem primitives. Both calls require
import "io" — touching the filesystem is explicit at the import line.
import "io"
// Read the whole file. Pipes and FIFOs (e.g. "/dev/stdin") are read
// until EOF. Returns "" if the file can't be opened or read.
let contents: str = io.read_file("data.txt")
// Write a file, replacing it if it exists. Returns 0 on success,
// -1 on failure. The parent directory must already exist.
let rc: int64 = io.write_file("out.txt", "hello\n")
For subprocess support, see stdlib/process.kod:
import "process"
let r: process.ProcessResult = process.run(["echo", "hello"])
assert r.status == 0
assert r.stdout == "hello\n"
process.output(argv) runs argv[0], looked up on PATH, to the end and
returns what it wrote, as a process.Output or an Error:
import "process"
func branch() -> str or Error {
let out = try process.output(["git", "branch", "--show-current"], dir: "/src/kod")
if out.status != 0 {
throw process.ProcessError(message: f"git: {out.stderr}")
}
return out.stdout.trim()
}
out.statusis the exit code, andout.stdoutandout.stderrare what the program wrote to each, read together, so a program that writes a lot to both can't stall.input:is written to the program's stdin while its output is read, then stdin is closed. Without it, stdin is empty. A program that exits without reading all of its input is not an error.dir:,env:andadd_env:work as forstart, below.- It fails as
startdoes when the program can't be run, and with aprocess.ProcessErrorwhen a signal ends it.
process.start(argv) starts argv[0], looked up on PATH, without
waiting for it, and returns a process.Child or an Error:
import "process"
func shout(anon text: str) -> str or Error {
let child = try process.start(["tr", "a-z", "A-Z"], stdin: .Pipe, stdout: .Pipe)
try child.stdin.write_str(text)
try child.stdin.close() // the child sees the end of its input
let out = try child.stdout.read_all()
try child.stdout.close()
let status = try child.wait() // the exit code
if status != 0 {
throw process.ProcessError(message: f"tr exited with {status}")
}
return str(out)
}
stdin:,stdout:andstderr:each take aprocess.Stdio:.Inherit(the default) shares this process's stream,.Nullgives the child/dev/null, and.Pipeconnects it to this process. A piped stream is aposix.Fdfield of the same name on theChild, for this process to write to (stdin) or read from (stdout,stderr) and to close. A stream that isn't piped has theFd-1, which fails on every call.dir:starts the child in that directory instead of the current one.env:replaces the child's environment with a list ofNAME=valuestrings; without it, the child gets this process's environment.argv[0]is looked up on this process'sPATHeither way.add_env:sets variables on top of that, asNAME=valuestrings: each replaces a variable of the same name or adds one, soadd_env: ["DEBUG=1"]runs the child with this process's environment plusDEBUG. An entry without a=, or with nothing before it, is aprocess.ProcessError.startfails with anIoErrorwhen the program can't be run, as for a missing program (.NotFound) or directory.child.wait()closeschild.stdinif it is a pipe, waits for the child to end, and returns its exit code. A child ended by a signal is aprocess.ProcessErrorthat names it, as intr was killed by SIGTERM. A child can be waited for once.child.try_wait()iswaitwithout the waiting. It returns the exit code (int64?) if the child has ended, which counts as its one wait, ornoneif it is still running. It doesn't closestdin.child.kill()sends itSIGTERMand returns without waiting;waitthen collects it.kill(signal: .Kill)sends anotherprocess.Signal:.Hup,.Int,.Quit,.Kill,.Term,.Usr1or.Usr2.child.pidis its process id.
A child that is never waited for stays a zombie until this process exits.
process.run, process.spawn and process.kill are shorthands for common cases:
process.run(argv) captures stdout and stderr; unlike output, it can't
fail: a program that can't be run, or that a signal ends, has the status -1. process.spawn(argv) starts argv[0] (looked up on PATH) without waiting for it, with stdin, stdout and stderr on /dev/null, and returns its process id, or -1 when it could not be started. process.kill(pid) ends a child that spawn started, with SIGTERM, waits for it, and returns whether it was signalled; a child that is never killed stays a zombie until the parent exits. process.exec(argv) instead replaces the calling process with argv[0], looked up on PATH: the new program has the same terminal, stdin and process id. Stdout is flushed first. If stdin is a pipe, input the program has already read into its buffer (as io.read_stdin_line does, beyond the line it asked for) is not handed on; a file or a terminal loses nothing. exec returns, with -1, only if argv[0] could not be run.
import "process"
func main() -> int64 {
process.exec(["echo", "hello"])
return 127 // not reached unless `echo` could not be run
}
Environment variables¶
stdlib/env.kod reads and changes the process's environment. A program's
arguments come from main(argv: [str]) (see Functions).
import "env"
func main() -> int64 {
let token = env.get("API_TOKEN")
print(token? or "no token")
must env.set("MODE", "test")
env.unset("API_TOKEN")
return 0
}
| Function | Meaning |
|---|---|
get(name) -> str? |
the value, or none if the variable isn't set; a variable set to the empty string is "", not none |
set(name, value) -> none or Error |
set or replace it; the change is seen by programs started afterwards with process.run and process.exec; an empty name, one containing = or a NUL byte, and a value with a NUL byte are InvalidInput errors |
unset(name) -> none |
remove it; unsetting a variable that isn't set does nothing |
Extern (C runtime)¶
Available for re-declaration in any module if needed:
| Symbol | Description |
|---|---|
_strlen |
C strlen. |
_rc_alloc |
Allocates an object with a reference count of 1; see Memory layout. |
_kod_str_concat, _kod_str_slice |
String operations the runtime exposes to codegen. |
_kod_sb_new, _kod_sb_append, _kod_sb_append_byte, _kod_sb_append_int, _kod_sb_len, _kod_sb_clear, _kod_sb_to_str |
The growable buffer behind StrBuilder and the str methods join, repeat, replace, lower and upper; a handle is typed as a str so that it is counted, but isn't one. |
_kod_array_concat, _kod_array_concat_new |
Array append in place (+=) and concatenation into a new array (+). |
_kod_test_fail, _kod_test_summary |
Test runner internals. |
Direct use is rarely needed — the language-level operators cover most cases.