Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cheatsheet - all builtins at a glance

Alphabetical index of every standard-library function and constant. Use it when you know the name and want to know which library and how to call it; use each library’s own page when you want to read about a topic. Each row’s library prefix links to the per-library doc.

The table covers what ships with the interpreter. New entries land here at the same time as the per-library doc - it’s a flat lookup view, not authoritative.

Functions

CallWhat it does
archive.pack(entries, fmt)Bundle a list of archive.Entry into bytes; fmt "tar"/"zip"/"tar.gz".
archive.unpack(b, fmt)Read a bundle back into a list of archive.Entry.
compress.finalize(stream)Close a streaming compressor; returns all compressed bytes.
compress.pack(b, algo [, level])Compress bytes; algo "gzip"/"zlib"/"deflate", optional level "fast"/"default"/"best".
compress.stream(algo [, level])Start a streaming compressor -> compress.Stream.
compress.unpack(b, algo)Decompress bytes with algo.
compress.update(stream, b)Feed one chunk into a streaming compressor.
convert.fromCodepoint(n)One-rune string for Unicode code point n (whole range, 1-4 UTF-8 bytes); errors on out-of-range / surrogate.
convert.toBool(v)Canonical conversion to bool (0/1, 0.0/1.0, "true"/"false").
convert.toCodepoint(char)Unicode code point (int) of a one-rune string; errors unless exactly one code point (not a grapheme cluster).
convert.toFloat(v)Convert to float (int→float, float identity, string parses, bool→1.0/0.0).
convert.toInt(v)Convert to int (float truncates toward zero, string parses, bool→1/0).
convert.toString(v)Convert to string (always succeeds; uses the value’s display form).
convert.typeOf(v)Runtime kind as string ("int", "float", "string", "bool", "null", "list", "map", "object").
convert.objectType(v)Specific registered name of an opaque object (e.g. "json.Value"); errors on a non-object.
crc.compute(b, algo)One-shot checksum. algo is "crc32" or "crc64". Returns big-endian bytes (4 or 8).
crc.finalize($s)Final checksum as big-endian bytes; consumes the handle.
crc.stream(algo)Allocate a crc.Stream for algo; feed chunks via crc.update then close with crc.finalize.
crc.update($s, $bytes)Feed one chunk into a crc.Stream (mutates by side effect).
encoding.codecs()Canonical character-codec names in registration order.
encoding.decode(b, codec)Decode bytes from a character codec to a Jennifer string.
encoding.encode(s, codec)Encode a Jennifer string into a character codec’s bytes.
encoding.fromText(s, format)Decode a binary-to-text format. format: "hex", "base32", "base32-hex", "base64", "base64-url", "ascii85", "z85", "quoted-printable".
encoding.isAscii(b)True iff every byte in b is < 0x80.
encoding.lenBytes(s)UTF-8 byte length of s (pair with len(s) for rune count).
encoding.lenRunes(b)Rune count of valid UTF-8 bytes; errors on invalid UTF-8.
encoding.toText(b, format)Encode bytes as printable text. format: "hex", "base32", "base32-hex", "base64", "base64-url", "ascii85", "z85", "quoted-printable".
fs.appendBytes(path, content)Append bytes to path; creates the file if missing.
fs.appendString(path, content)Append UTF-8 string to path; creates the file if missing.
fs.close($f)Close an fs.File handle; removes it from the registry.
fs.eof($f)True iff the next read on $f would error or return partial. Sticky.
fs.exists(path)True if path resolves; permission errors still surface.
fs.isDir(path)True iff path exists and is a directory.
fs.isFile(path)True iff path exists and is a regular file.
fs.list(path)Sorted entry names in path. Non-recursive; returns list of string.
fs.mkdir(path)Create a single directory; errors if any parent is missing.
fs.mkdirAll(path)Create path and every missing parent (like mkdir -p).
fs.open(path, mode)Open path and return an fs.File. mode: "read", "write", "append".
fs.readBytes(path) / .readBytes($f, n)Whole-file read (1 arg) or up to n bytes from handle (2 args). Partial + sticky-EOF on short handle reads.
fs.readChars($f, n)Up to n runes from handle, UTF-8 decoded. Partial + sticky-EOF on short reads.
fs.readLine($f)One line from handle, \r\n / \n stripped. Errors on EOF - check fs.eof first.
fs.readString(path)Whole file as UTF-8; invalid UTF-8 is a positioned runtime error.
fs.remove(path)Delete one file or empty directory. Non-empty dir errors.
fs.removeAll(path)Recursive delete. Explicit second verb (no-footguns stance).
fs.rename(old, new)Same-filesystem rename; cross-fs is a boundary error.
fs.stat(path)Returns fs.Stat (path, size, isDir, mtimeNanos, mode). Missing path errors.
fs.walk(path)Depth-first, sorted, includes path. Returns list of fs.Stat. Skips symlinks.
fs.writeBytes(path, content) / .writeBytes($f, b)Whole-file overwrite (path form) or write via handle (fs.File form).
fs.writeString(path, content) / .writeString($f, s)Whole-file overwrite (path form) or write via handle (fs.File form).
hash.compute(b, algo)One-shot digest. algo is "md5", "sha1", "sha256", or "sha512". Returns raw bytes.
hash.hmac(key, message, algo)Keyed-hash MAC (RFC 2104) over the same algorithms; raw bytes out. For JWT / TOTP / SigV4 / webhook signatures.
hash.finalize($s)Final digest as bytes; consumes the handle (later calls error).
hash.stream(algo)Allocate a hash.Stream for algo; feed chunks via hash.update then close with hash.finalize.
hash.update($s, $bytes)Feed one chunk into a hash.Stream (mutates by side effect).
httpd.listen(addr) / .listenTLS(addr, cert, key)Start an HTTP / HTTPS server -> httpd.Server (":0" = ephemeral port). Default binary only.
httpd.address($srv) / .shutdown($srv)Bound address of a server / graceful drain (unblocks parked accept).
httpd.accept($srv)Block for the next request -> httpd.Request (the pull loop). Errors once the server is shut down.
httpd.method($req) / .path($req) / .query($req, name) / .header($req, name) / .body($req) / .remoteAddr($req)Read the accepted request (query / header -> "" if absent; body -> bytes).
httpd.setHeader($req, name, value) / .respond($req, status, body)Set a response header / send the response once (body is string or bytes).
httpd.serveFile($req, path) / .serveDir($req, root)Answer with a file / the file under root for the request path (.. cannot escape root).
io.eof()True if and only if the next io.readLine() would error. Pair with while (not io.eof()) {...}.
io.printf(format, args...)Format-string write to stdout. Verbs: %d %f %s %t %v %%; per-verb |key=value modifiers (pad, prec, base, null=*, …).
io.printf(value)Write a value’s display form to stdout.
io.eprintf(format, args...)Like printf, but writes to stderr (diagnostics / logs that must not mix into stdout).
io.readLine()Read one line from stdin (trailing newline stripped). Errors at EOF - check io.eof() first.
io.readLine(prompt)Same as io.readLine() but writes prompt to stdout first.
io.sprintf(format, args...)Format-string version of sprintf. Same verbs and |key=value modifiers as printf.
io.sprintf(value)Display-form of a value, returned as a string (doesn’t write).
len(v) (language built-in)Structural length: rune count (string), element count (list), entry count (map), byte count (bytes).
json.decode(s)Parse JSON text into an opaque json.Value handle (walk it with the accessors below).
json.encode(v)Compact JSON string for an encodable value (struct/map -> object, bytes -> base64, json.Value round-trips; task / non-string keys error).
json.encodePretty(v)Like encode, 2-space indented.
json.typeOf(v[, ptr])JSON type at an optional JSON Pointer: null bool int float string list map.
json.get(v[, ptr])Sub-node at a JSON Pointer, as a json.Value (walk stays opaque; no pointer = the node itself).
json.has(v, ptr)Whether the JSON Pointer resolves to an existing node.
json.keys(v[, ptr])list of string keys of the addressed map, in document order.
json.length(v[, ptr])Element count of a list / entry count of a map at the pointer.
json.asInt(v[, ptr]) / asFloat / asString / asBoolExtract the addressed leaf as a typed value (strict; asFloat promotes an integral number).
json.isNull(v[, ptr])Whether the addressed node is JSON null.
json.map() / .list()A fresh empty JSON map / list json.Value - the explicit start of a document (writes never auto-vivify).
json.set(v, ptr, val)Non-mutating: upsert a map key or replace an in-range list index; returns a new json.Value. Strict (no missing intermediates).
json.insert(v, ptr, val)Insert into a list before index ptr (or - = at end); returns a new handle.
json.append(v, ptr, val)Push onto the list addressed by ptr (sugar for insert at /.../-).
json.remove(v, ptr)Drop the map key or list element at ptr; returns a new handle.
json.move(v, from, to)Relocate the subtree at from to to (read, remove, then set).
lists.concat(a, b)New list with a’s elements followed by b’s.
lists.contains(xs, item)True if item appears in xs (haystack, needle).
lists.first(xs)Element at index 0. Empty input errors.
lists.head(xs, n)New list of the first n elements.
lists.last(xs)Element at the last index. Empty input errors.
lists.pop(xs)New list without the last element. Empty input errors.
lists.push(xs, item)New list with item appended.
lists.range(start, end[, step])Half-open list of consecutive ints; end excluded; step must match direction.
lists.reverse(xs)New list with elements reversed.
lists.shuffle(xs)Fisher-Yates; respects math.randSeed. Non-mutating.
lists.slice(xs, start[, end])New sublist [start, end); end defaults to len(xs).
lists.sort(xs)New ascending-sorted list. Numeric / string / bool elements; mixed errors.
lists.tail(xs, n)New list of the last n elements.
maps.delete(m, key)New map without key. Missing key errors (strict at boundaries).
maps.has(m, key)True if map m contains key. The non-erroring companion to $m[key].
maps.keys(m)List of keys in insertion order.
maps.merge(a, b)New map; b’s entries layered on top of a.
maps.values(m)List of values in insertion order.
math.abs(x)Absolute value of x (int→int, float→float).
net.accept($listener)Block until a client connects to $listener; return the new net.Conn.
net.address($h)Polymorphic. Conn -> peer address; Listener / UDPSocket -> local bound address.
net.close($h)Polymorphic. Closes a net.Conn, net.Listener, or net.UDPSocket.
net.connect(address)TCP client: dial "host:port" and return a net.Conn.
net.connectTLS(address)TLS client: dial "host:port" + handshake, verifying the cert against the host. net.TLSOptions for caCert / skipVerify.
net.startTLS($conn)Upgrade an open plaintext net.Conn to TLS in place (STARTTLS); host reused from connect; same handle.
net.eof($conn)True iff the next read on $conn would return partial or fail. Sticky.
net.listen(address)Bind TCP "host:port" (use ":0" for ephemeral). Returns a net.Listener.
net.listenUDP(address)Bind a UDP socket. Returns a net.UDPSocket; usable as both client and server.
net.lookup(host)DNS: resolve host to a list of string IPs.
net.readBytes($conn, n)Read up to n bytes; blocks for at least one byte. Sticky-EOF on close.
net.recvFrom($sock, n)Block for one UDP datagram, up to n bytes. Returns net.Datagram{data, peer}.
net.reverseLookup(ip)Reverse DNS: IP address to a list of string of hostnames.
net.sendTo($sock, peer, bytes)Send one UDP datagram to peer ("host:port").
net.setDeadline($conn, ms)Arm a read/write deadline ms ms out (0 clears). A read past it fails with a catchable read timed out.
net.writeBytes($conn, bytes)Blocking write of every byte to a net.Conn.
regex.escape(s)Escape RE2 metacharacters so s matches literally when used as a pattern.
regex.find(pattern, s)First match as regex.Match; sentinel with start=-1 if no match.
regex.findAll(pattern, s)Every non-overlapping match; returns list of regex.Match.
regex.matches(pattern, s)True iff pattern matches somewhere in s.
regex.replace(pattern, s, replacement)Replace every match. $1, ${name} expand to captured groups; $$ is a literal $.
regex.split(pattern, s)Split s at every match; returns list of string.
math.ceil(x)Smallest int ≥ x. Accepts int (identity) or float.
math.floor(x)Largest int ≤ x. Accepts int (identity) or float.
math.max(a, b)Larger of two numbers; mixed int/float promotes to float.
math.min(a, b)Smaller of two numbers; mixed int/float promotes to float.
math.pow(x, y)x raised to y; always float. Errors on NaN/Inf-producing inputs.
math.round(x)Round to nearest int (half away from zero).
math.sqrt(x)Square root; always float. Errors on negative input.
os.flag(name)Value following name in os.ARGS, or "" if absent / at end. Exact-match (no --foo=bar parsing).
os.getEnv(name)Read environment variable name. Unset → empty string, no error.
os.setEnv(name, value)Set environment variable name for this process (and children it spawns). Invalid name errors.
os.hasFlag(name)True if name appears as an exact element of os.ARGS.
os.isTerminal(stream)Is stream ("stdout"/"stderr"/"stdin") an interactive terminal? Pipe/file -> false.
os.cwd()Absolute path of the current working directory.
os.homeDir()Current user’s home directory ($HOME / %USERPROFILE%).
os.tempDir()Temp-file directory ($TMPDIR//tmp; %TMP% on Windows). Never errors.
os.kill(p)Send SIGTERM to spawned process $p.
os.poll(p)True if spawned process $p has exited (a following os.wait returns immediately).
os.run(argv)Blocking: run argv to completion, return os.Result{exitCode, stdout, stderr}.
os.spawn(argv)Non-blocking: start argv, return os.Process{pid} handle.
os.wait(p)Block until spawned process $p exits; return os.Result. Idempotent.
strings.chars(s)Split s into a list of string, one entry per Unicode code point.
testing.assertContains(hay, needle)Throw Error{kind:"assertion"} unless hay contains needle: substring / list element / map key.
testing.assertEqual(actual, expected)Throw unless deeply equal (lists / maps / structs compare by value).
testing.assertFalse(cond)Throw unless cond (a bool) is false.
testing.assertNotEqual(actual, expected)Throw unless not deeply equal.
testing.assertThrows(name, kind)Throw unless the named zero-arg method throws an Error of that kind.
testing.assertTrue(cond)Throw unless cond (a bool) is true.
testing.report(results, format)Render results to "text", "tap", or "junit" (returns string).
testing.reset()Clear the process-wide result accumulator.
testing.results()Snapshot of the accumulator as list of testing.Result.
testing.run(name)Invoke a zero-arg user method by name; catch every failure mode into a testing.Result.
testing.runWith(name, args)Like run, binding the args list to the method’s parameters (arity + type checked).
strings.contains(s, sub)True if s contains the substring sub.
strings.endsWith(s, suffix)True if s ends with suffix.
strings.indexOf(s, sub)Rune index of first sub in s, or -1 if absent.
strings.join(parts, sep)Concatenate list of string parts separated by sep. Inverse of strings.split.
strings.lower(s)Lowercase s (Unicode-aware).
strings.repeat(s, n)n non-negative copies of s concatenated.
strings.replace(s, old, new)Replace all occurrences of old in s with new.
strings.split(s, sep)Split s on non-empty sep; returns list of string.
strings.startsWith(s, prefix)True if s starts with prefix.
strings.substring(s, start)Rune-indexed slice of s from start to end.
strings.substring(s, start, end)Rune-indexed slice; exclusive end.
strings.trim(s)Strip leading and trailing Unicode whitespace.
strings.trimLeft(s)Strip leading whitespace.
strings.trimRight(s)Strip trailing whitespace.
strings.upper(s)Uppercase s (Unicode-aware).
task.discard($t)Mark a task of T fire-and-forget; suppresses exit-time loud-fail. Returns null.
task.poll($t)True if $t has finished (non-blocking).
task.wait($t)Block until $t finishes; return its value or re-raise its error.
task.waitAll($ts)Block for all tasks in $ts; results in list order; re-raises the first error if any.
task.waitAny($ts)Block until any task in $ts is done; return its index.
time.add($t, $d)time.Time shifted by duration $d.
time.after($a, $b)True if $a is strictly later than $b.
time.before($a, $b)True if $a is strictly earlier than $b.
time.day($t)Day of month, 1-31.
time.equal($a, $b)True if $a and $b are the same UTC instant.
time.format($t, layout)Strftime-style format. Codes: %Y %m %d %H %M %S %z %a %A %b %B %j %u %%.
time.fromHours(n)time.Duration of n hours.
time.fromIso(s)Parse RFC 3339; accepts Z or +HH:MM; optional fractional seconds.
time.fromMilliseconds(n)time.Duration of n milliseconds.
time.fromMinutes(n)time.Duration of n minutes.
time.fromSeconds(n)time.Duration of n seconds.
time.fromUnix(seconds)time.Time at the given Unix second.
time.fromUnixMillis(ms)time.Time at the given Unix millisecond.
time.fromUnixNanos(ns)time.Time at the given Unix nanosecond.
time.hour($t)Hour 0-23.
time.hours($d)Span as whole hours (int).
time.inZone($t, $z)Re-render $t in $z’s wall-clock; UTC instant is preserved.
time.iso($t)RFC 3339 string: Z for UTC, +HH:MM otherwise; fractional seconds when non-zero.
time.local()Host’s current time.Zone (name + offset).
time.milliseconds($d)Span as whole milliseconds (int).
time.minute($t)Minute 0-59.
time.minutes($d)Span as whole minutes (int).
time.month($t)Calendar month, January = 1.
time.nanosecond($t)Fractional second, 0-999_999_999.
time.now()Current instant in the host’s local zone (time.Time).
time.parse(s, layout)Strict strftime-style parse. Same code set as format (%j / %u are format-only).
time.second($t)Second 0-59.
time.seconds($d)Span as whole seconds (int).
time.sleep($d)Block the running task for $d. Negative / zero returns immediately. Returns null.
time.sub($a, $b)Signed time.Duration between two time.Time values.
time.unix($t)Unix-second instant of $t (int).
time.unixMillis($t)Unix-millisecond instant of $t (int).
time.unixNanos($t)Unix-nanosecond instant of $t (int).
time.utc()Current instant in UTC (time.Time).
time.weekday($t)ISO 8601 weekday: Monday = 1 … Sunday = 7.
time.year($t)Calendar year (int).
time.zone(offset, name)Build a time.Zone from an integer offset (seconds east of UTC) and a display name.
toml.decode(s)Parse TOML text into an opaque toml.Value handle (walk it with the accessors below).
toml.encode(v) / .encodePretty(v)TOML string for a toml.Value (or native map / list / scalar); encodePretty blank-lines sections. Null value / non-table root errors.
toml.typeOf(v[, ptr])Node type at an optional JSON Pointer: null bool int float string list map datetime.
toml.get(v[, ptr])Sub-node at a JSON Pointer, as a toml.Value (walk stays opaque; no pointer = the node itself).
toml.has(v, ptr)Whether the JSON Pointer resolves to an existing node.
toml.keys(v[, ptr]) / .length(v[, ptr])list of string table keys in document order / element count of a list or table.
toml.asInt(v[, ptr]) / asFloat / asString / asBoolExtract the addressed leaf as a typed value (strict; asFloat promotes an int).
toml.asDatetime(v[, ptr]) / .isDatetime(v[, ptr])A date-time node as a time.Time (needs use time;) / whether the node is a date-time.
toml.map() / .list()A fresh empty table / array toml.Value - the explicit start of a document (writes never auto-vivify).
toml.set(v, ptr, val) / .insert / .append / .remove / .moveNon-mutating edits by JSON Pointer; each returns a new toml.Value (strict / no missing intermediates).
uuid.generate(v)New UUID string; v is "v4" (random) or "v7" (time-ordered).
uuid.isValid(s)Whether s is a well-formed UUID string.
uuid.parse(s)The 16 bytes of a UUID string; errors on malformed input.
uuid.version(s)Version digit (4, 7, …; 0 for NIL); errors on malformed input.

Constants

NameTypeValue
math.EfloatEuler’s number, 2.718281828459045.
math.PIfloatπ, 3.141592653589793.
meta.BUILDstringWhich Go toolchain compiled the interpreter: "go" / "tinygo".
meta.VERSIONstringThe interpreter’s build version (e.g. "0.14.0").
meta.SYSMODDIRstringResolved system module directory (--sysmoddir > JENNIFER_SYSMODDIR > compile default).
meta.call(name, args...)valueInvoke a top-level method by runtime name (arity + types checked); errors / exit propagate.
meta.defined(name)boolWhether a top-level method name exists.
meta.callMain(name, args...) / .definedMain(name)value / boolLike call / defined but against the entry program’s methods (a module reaching its host’s handlers).
os.ARCHstringCPU architecture: "amd64", "arm64", "wasm", …
os.ARGSlist of stringArgv. Index 0 is the script path, the rest are user args.
os.DIRSEPstringPath-component separator: "/" Unix, "\\" Windows.
os.EOLstringPlatform line ending. "\n" Unix-likes, "\r\n" Windows.
os.NCPUintLogical CPUs usable by the process (runtime.NumCPU). 1 on jennifer-tiny (single-thread scheduler).
os.PATHSEPstringPATH-list separator: ":" Unix, ";" Windows.
os.PLATFORMstringOS tag: "linux", "darwin", "windows", …
time.PROGRAM_STARTtime.TimeCaptured the moment the time library installed; “since program launched” anchor.
time.UTCtime.ZoneCanonical UTC: Zone{offset: 0, name: "UTC"}.
uuid.NILstringThe all-zero UUID 00000000-0000-0000-0000-000000000000.

Type-conversion calls

int, float, string, bool are also type keywords (used in def x as int). The parser allows them in expression position only when immediately followed by (, so def x as int init convert.toInt("42"); works but def x as int init int; errors. See convert.md for the parser detail.

See also