Globals

Ambient declarations for the Nish global surface.

Every Nish program is legal TypeScript syntax — the compiler parses it with the official TypeScript parser and nothing else. This file is what makes it legal TypeScript semantics too: reference it from a tsconfig.json (or with /// <reference path="..." />) and tsc --noEmit, your editor and your language server all accept Result<T, E>, Ok(...), i32 and the rest without a red squiggle.

{ "include": ["src/**/*.ts", "node_modules/nish/runtime/nish.d.ts"] }
`nish` is still the authority

TypeScript's structural checker is weaker than this compiler's in the places where Nish is deliberately stricter, and it cannot see the flow rules at all:

  • the integer and float widths are aliases of number here, so tsc lets an i32 and an f64 mix where nish refuses;
  • tsc does not know that a Result may not be dropped, that orReturn() returns early, or that the enclosing function has to return a Result of its own for it to be legal at all;
  • everything Phase 0 forbids (any, throw, try, prototypes, arrow functions, ...) is ordinary TypeScript and passes tsc happily.

So a program that tsc accepts may still be rejected by nish; the reverse should never happen, and a case where it does is a bug in this file. docs/LANGUAGE.md is the normative description; the doc comments here are the reference for each builtin, and the doc of each callable builtin ends with the capability a call needs (docs/LANGUAGE.md -> Capabilities), none for a call that needs none.

Map, Set, Math, Array, ReadonlyArray and String are lib.es2022's, which a program is checked against: a second declaration would clash with it, so the interfaces at the foot of this file merge into lib's, adding Nish's documentation and no signature narrower than lib's. nish's surface is lib's less what it defers — no entries, no for...of over a Map itself — with keys() and values() admitted only as the iterable of a for...of, and get's V | undefined only as a const's initialiser, the left of ?? or an operand of === undefined, none of which tsc can know (docs/LANGUAGE.md -> Map and Set).

nish/map's reserve and getOrInsert are not declared here: they are ordinary source, std/map.ts, which tsconfig.json maps nish/* to.

Functions

Err

The failure value, likewise: its Result type comes from the context. Capability: none.

const Err: <T, E>(error: E) => Result<T, E>
errorErequired

the error payload.

returnsResult<T, E>

a Result on its failure arm.

Ok

The success value. Its Result type comes from the context, as null's does; Ok() with no argument is a Result<void, E>. In f64 mode a numeric literal payload takes no type from the context, so Ok(3) for a Result<i32, string> needs toI32(3). Capability: none.

const Ok: <T, E>(value: T) => Result<T, E>
valueTrequired

the payload.

returnsResult<T, E>

a Result on its success arm.

The success of a Result<void, E>, with no payload. Capability: none.

const Ok: <E>() => Result<void, E>
returnsResult<void, E>

a Result<void, E> on its success arm.

appendFileSync

data added at the end of the file, created at 0644 when missing; statement position. A symbolic link as the last component is refused, as for writeFileSync. Capability: fs.write.

const appendFileSync: (path: string, data: string) => void
pathstringrequired

the file to extend.

datastringrequired

the text appended.

arena

using a = arena() (docs/LANGUAGE.md -> Arena): everything the block allocates after this declaration is released when the block ends, on every exit (its end, a return after the returned value is computed, a break or continue that leaves it, and an orReturn()), and the compiler refuses the block if anything allocated in it could outlive it. Only a using initialiser, and the binding is never read; under Node there is no arena and the disposal does nothing.

arena() anywhere but the initialiser of a using is NL2416, and reading the binding is NL2417. A number, a boolean or an enum leaves the block freely, as does a value older than it.

These routes are refused for anything else allocated inside:

  • assigning it to a local declared outside the block (NL2418),
  • storing it into a field (NL2419) or an element (NL2420),
  • storing it any other way (NL2421),
  • a push onto an array the block does not bind to a fresh array (NL2422),
  • a return or orReturn() (NL2423),
  • a call to a function that stores an allocation (NL2424)
  • and a spawn on a scope declared outside the block (NL2427), on a scope the same using declares ahead of arena() (using s = scope(), a = arena(), NL2427, since s joins after the release) or on one ahead of the statement's last arena() (using a = arena(), s = scope(), b = arena(), NL2427, since b releases before s joins).

The rule is the escape analysis's, so it is conservative. A parallel body or a task may not open one (NL2351). A map that answers numbers or strings may run inside one, and a task filed on a scope the block declares may read what it allocated. It nests with scope() and lock() on the same stack, innermost first. A return g(n) whose arguments are all numbers is a tail call with the release moved ahead of it, unless g reads the arena. A panic ends the process. Capability: none.

const arena: () => Disposable
returnsDisposable

the scope the using declaration disposes.

availableParallelism

How many CPUs the program may use, with or without --threads: the smallest of the CPUs online, the ones its thread may run on (an affinity mask, a container's cpuset), a cgroup v2 CPU quota rounded up, and NISH_NUM_THREADS when that is a positive number — which can lower the count and never raise it. A program asks it to decide how many workers to start; it reads the count again on each call. Under Node it is os.availableParallelism() lowered by NISH_NUM_THREADS, and since Node reads no cgroup quota, inside a container with one the two can differ. A wasm32 build refuses it (NL2404). It writes nothing and may be called in a task. Also exported by nish:process. Capability: none.

const availableParallelism: () => i32
returnsi32

at least 1.

bitsToF64

The inverse of f64ToBits: bitsToF64(f64ToBits(x)) === x for every x except NaN, which is not === to itself. An argument that is not an i64 is refused. Capability: none.

const bitsToF64: (bits: i64) => f64
bitsi64required

the 64 bits to read as a float.

returnsf64

the f64 those bits are.

cErrno

cErrno(), from nish:unsafe (WP27 S5): the errno the most recent declare function call on this thread left, or 0 before any. Naming it anywhere in a program makes every foreign call zero errno just before it and save it just after, before the result is copied or anything allocated, so the runtime's own work after the call cannot change it. Meaningful only where the C function documents that it sets errno. Per thread; refused on a freestanding wasm32 build, which has no libc. Capability: unsafe.

const cErrno: () => i32
returnsi32

the saved errno, an i32.

connectResult

How the connection of a tcpConnect went, asked once fd is writable. The kernel clears the failure as it is read, so a second call answers 0; the descriptor is closed with netClose either way. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const connectResult: (fd: i32) => i32
fdi32required

the connecting socket.

returnsi32

0 when the connection is made, else its failure from SO_ERROR: -111 for a port nobody listens on, -110 for one that never answered.

createFileExclusiveSync

data in a new file of exactly mode (set as for writeFileSyncMode), created only if nothing is at path (O_CREAT | O_EXCL): -17 EEXIST when any name is, a dangling symbolic link included, which is never followed. Of several processes racing for one path exactly one succeeds, so it takes a lock: create it, and unlinkSync it to release. A write that fails after the create removes the file, so a failed create never leaves a half-written lock behind. Never an exit and never a panic. A wasm32 build refuses it, and a WASI build answers -ENOSYS. Capability: fs.write.

const createFileExclusiveSync: (
  path: string,
  data: string,
  mode: i32,
) => i32
pathstringrequired

the file to create.

datastringrequired

its contents.

modei32required

the file's mode, 0..0o777.

returnsi32

the byte count, or a negative errno as for writeFileSyncMode, -17 when something is already at path.

ctEq

All-ones of the operands' type when a === b, zero otherwise, without a branch; the answer is only ever one of the two, and is the mask ctSelect takes, so ctSelect(ctEq(a, b), x, y) never shows the optimiser a boolean. Both operands are one type, u32 or u64; any other type, a boolean and a ranged integer included, is refused with NL2399, and operands of two types with NL2400, as for ctSelect.

A bare numeric literal takes its type from the other operand, so ctEq(0, x) works, while ctEq(1, 2), with no width to take, is an i32 and refused. The call takes exactly two arguments, and like every function it is not a value. The no-branch promise and its limits are ctSelect's, and so are the wasm32 and Node readings. Capability: none.

const ctEq: <T extends u32 | u64>(a: T, b: T) => T
aTrequired

one operand.

bTrequired

the other, of the same type.

returnsT

a mask for ctSelect.

ctSelect

(a & mask) | (b & ~mask) with the mask hidden from the optimiser, so it is never turned into a branch: a for an all-ones mask, b for zero. Every operand is one type, u32 or u64. Both are number here, so one generic declaration stands for the two. Any other type is refused, as `ctEq` takes u32 or u64 operands (convert with toU32 or toU64), got i64 (NL2399): i32, i64, u8, u16, a ranged integer, f32, f64 and boolean included, and a boolean mask in particular.

Operands of two types are `ctSelect` needs every operand of one type, got u32 and u64 (NL2400). A bare numeric literal takes its type from the first operand that is not one, wherever it stands. The call takes exactly three arguments, and like every function it is not a value. The all-ones-or-zero convention for the mask is not checked, because the check would be a branch; any other mask is a defined bitwise blend, so ctSelect(0xf0f0f0f0, a, b) takes the high nibble of each byte from a.

The promise is no branch and no secret-indexed load in the primitive itself and nothing about the caller's own code, which branches on a secret if it writes if (ctEq(a, b) !== 0). On wasm32 the same barrier is emitted, but the engine compiles the module again, so nothing is promised there. Under Node the runtime shim computes the same answer as a pure function (over u32, put back in range with >>> 0; over u64, on BigInts), and only the timing is not claimed. Capability: none.

const ctSelect: <T extends u32 | u64>(
  mask: T,
  a: T,
  b: T,
) => T
maskTrequired

all ones to choose a, zero to choose b.

aTrequired

the value an all-ones mask selects.

bTrequired

the value a zero mask selects.

returnsT

a or b, chosen without a branch.

f32ToBits

Reinterpret the 32 bits of an f32, never convert the value, signed as an i32: f32ToBits(1.5) is 0x3FC00000, and f32ToBits(-0) is -2147483648. An f64 argument is refused, as `f32ToBits` expects an argument of type f32, got f64. Under Node the runtime shim supplies it from a DataView. Capability: none.

const f32ToBits: (x: f32) => i32
xf32required

the float whose bits are read.

returnsi32

the same 32 bits as an i32.

f64ToBits

Reinterpret the 64 bits of an f64, never convert the value: toI64(1.5) is 1, f64ToBits(1.5) is 0x3FF8000000000000. A function that only reinterprets bits has no side effect. An argument that is not an f64 is refused, as is a call with other than one argument. Capability: none.

const f64ToBits: (x: f64) => i64
xf64required

the float whose bits are read.

returnsi64

the same 64 bits as an i64.

fileClose

Close a descriptor fileOpen gave. A second close answers -9, unless the number has been handed out again since, so close once. Capability: fs.read.

const fileClose: (fd: i32) => i32
fdi32required

a descriptor from fileOpen.

returnsi32

0, or a negative errno (-9 EBADF).

fileOpen

Open a regular file to read a window at a time (WP44): read-only, close-on-exec and non-blocking, so a FIFO or a device never waits. A directory is refused with -21 and any other kind that is not a regular file with -22, the descriptor closed again first. Pair it with fileClose in a try/finally. A freestanding wasm32 build refuses the call (NL2718); --profile wasi reads through WASI. Capability: fs.read.

const fileOpen: (path: string) => i32
pathstringrequired

the file to open; a NUL in it is refused as a missing path is.

returnsi32

a descriptor (>= 0), or the negated Linux errno: -2 ENOENT, -13 EACCES, -20 ENOTDIR, -21 EISDIR, -22 EINVAL for a FIFO or device, -6 ENXIO for a socket, -23 ENFILE, -24 EMFILE, -36 ENAMETOOLONG, -40 ELOOP; anything else is -5 EIO.

fileReadAt

Read up to len bytes from byte pos of the file into buf[off .. off + len), without moving any shared offset (pread). The window is checked as buf.slice checks it and panics the same way when it falls outside buf. The array is never grown: memory follows the window. Capability: fs.read.

const fileReadAt: (
  fd: i32,
  buf: u8[],
  off: i32,
  len: i32,
  pos: i64,
) => i32
fdi32required

a descriptor from fileOpen.

bufu8[]required

the array the bytes land in; its length is unchanged.

offi32required

where in buf the first byte lands.

leni32required

the most bytes to read.

posi64required

the file offset to read from, an i64.

returnsi32

the bytes read, 0 at end of file (and for a len of 0, even on a closed or negative descriptor), or a negative errno: -22 EINVAL for a negative pos or one where pos + len overflows, -9 EBADF for a closed or negative descriptor, -21 EISDIR, -29 ESPIPE; anything else is -5 EIO.

fileSize

The file's size in bytes now, from fstat: a file may grow or shrink between this and a read, which then answers what is there. Capability: fs.read.

const fileSize: (fd: i32) => i64
fdi32required

a descriptor from fileOpen.

returnsi64

the size, an i64 past 2^31 when the file is, or a negative errno (-9 EBADF for a closed descriptor).

getenv

One environment variable, as the call runs. The value is what getenv(3) answers, so it is bytes: a variable holding something that is not valid UTF-8 comes back as those bytes, as readFileSync does, and every offset into it is a byte offset. The bytes are copied into the arena, so the result is an ordinary string that outlives any later change to the environment, and it is narrowed with if (cc !== null) like any other nullable.

It is a call and not process.env.CC, because a member access on a key chosen at runtime is forbidden. Two reads of one variable are two calls: a setenv from linked C may change the answer between them. Also exported by nish:process. Capability: env.

const getenv: (name: string) => string | null
namestringrequired

the variable's name.

returnsstring | null

its value, or null when it is unset (an empty value, as CC=, is a set variable and answers a zero-length string).

geteuid

The effective user id, the one to compare an owner from lstatOwnerModeSync with; compare it with (om >> 32) & 0xffffffff. The answer is an i64 in both number modes. It takes no argument, and a wasm32 build is refused, as there is no user there. Under Node the runtime shim supplies process.geteuid(). It is a global, not a nish: export. Capability: env.

const geteuid: () => i64
returnsi64

the process's effective uid.

isDirectorySync

Whether a directory is at path right now. One stat, and never an exit. The answer is a fact about the file system as the call runs and can be stale by the time the caller acts on it: mkdirSync is still the call that decides whether a directory was made, and readFileSyncOrNull is still the way to read a file without racing a check against it. Capability: fs.read.

const isDirectorySync: (path: string) => boolean
pathstringrequired

the path to ask about.

returnsboolean

true for a directory; false for everything else — a missing path, a plain file, a device node, a parent that cannot be searched.

isExecutableSync

Whether the real user may run path: access(path, X_OK), the shell's question. It is false for a path that does not resolve or holds a NUL, for a file with no execute bit (root included), and a merely readable file is not executable. It takes a string path and exactly one argument, and a wasm32 build is refused, as there is no file system there. Under Node the runtime shim supplies fs.accessSync with X_OK. It is a global, not a nish: export. Capability: fs.read.

const isExecutableSync: (path: string) => boolean
pathstringrequired

the file to ask about.

returnsboolean

whether it is executable by the real user.

isTerminal

Whether descriptor fd is a terminal (isatty). false for a pipe or a file and under --profile wasi; under Node it is tty.isatty, in a browser false; refused at compile time on a freestanding wasm32 target. Capability: tty.

const isTerminal: (fd: i32) => boolean
fdi32required

the descriptor asked about.

returnsboolean

whether it is a terminal.

kill

Send sig to pid. Only 0, 2 (SIGINT), 9 (SIGKILL) and 15 (SIGTERM) are accepted, whose numbers are the same on Linux and Darwin, so a number means the same signal on every host. A positive pid may be any process of this user, not only a child. A wasm32 build refuses it (NL2404), and a scope's task or a parallel body that calls it is refused as any shared write is. Under Node it checks the signal and the pid as the native one does and turns Node's error code back into its errno. Also exported by nish:process. Capability: process.spawn.

const kill: (pid: i32, sig: i32) => i32
pidi32required

the process signalled; 0 or below is -22, because kill(2) reads those as a process group or every process.

sigi32required

0, 2, 9 or 15; anything else is -22.

returnsi32

0, or a negative errno: -3 (ESRCH) when no process has the pid, a child already reaped included, -1 (EPERM) when it is another user's, -22 for a refused sig or pid.

lstatOwnerModeSync

One lstat of path, so a symbolic link answers for itself and not for what it names: the owner's uid in the high 32 bits and st_mode (the file type and the permission bits) in the low 32, or -1 when the path does not resolve or holds a NUL (#386). Both come out of one lstat, so they describe the same file however the path changes in between.

Take them apart with (om >> 32) & 0xffffffff (the owner) and om & 0xfff (the permission bits) or om & 0xf000 (the type: 0x8000 a regular file, 0x4000 a directory, 0xa000 a symbolic link). The mask on the owner is not optional: a uid of 2^31 or more fills bit 63, which >> on an i64 copies down, so om >> 32 alone answers a negative owner that never equals geteuid().

The answer is an i64 in both number modes, and an i32 variable is refused rather than truncated (Cannot initialize i32 variable `om` with i64). It takes a string path and exactly one argument. A wasm32 build is refused, with `lstatOwnerModeSync` reaches the operating system, and a wasm32 build has none to reach. Under Node the runtime shim packs fs.lstatSync's uid and mode the same way as a BigInt. It is a global, not a nish: export. Capability: fs.read.

const lstatOwnerModeSync: (path: string) => i64
pathstringrequired

the path to stat, not followed through a final link.

returnsi64

(uid << 32) | st_mode, or -1.

mkdirSync

One directory, not recursive, mode 0777 & ~umask, exactly like Node's fs.mkdirSync(p) with no options, so a missing parent is a failure and not a reason to create it. Answers a value where it could have exited, so a program can turn the failure into its own diagnostic. isDirectorySync is the stat half of it. Capability: fs.write.

const mkdirSync: (path: string) => boolean
pathstringrequired

the directory to make.

returnsboolean

true when a directory exists at path once the call returns, whether this call created it or it was already there; false for every other outcome, a plain file at path included.

mkdirSyncMode

mkdir(2) of one level, made with mode less the umask (0o700 is exact under any umask that leaves the owner's bits, as every usual one does; a wider mode may come out narrower). A path already there is -17 EEXIST and its mode is left as it was, never changed. Never a panic. A wasm32 build refuses it, and a WASI build answers -ENOSYS. Capability: fs.write.

const mkdirSyncMode: (path: string, mode: i32) => i32
pathstringrequired

the directory to make.

modei32required

its mode before the umask, 0..0o777.

returnsi32

0, or a negative errno: -2 ENOENT for a missing parent; -22 for a mode outside 0..0o777 (the sticky, setuid and setgid bits included) or a NUL in path.

monotonicNanos

CLOCK_MONOTONIC in nanoseconds, for timing a region of a program. The origin is arbitrary, so only the difference between two reads means anything: it is not comparable between two processes or two machines, and it is not a date. It is an i64 in both number modes. Two reads with work between them do not fold into one. Not refused on wasm32. Also exported by nish:process. Capability: clock.

const monotonicNanos: () => i64
returnsi64

nanoseconds since an arbitrary origin.

netAddress

Write the address form of a numeric host and port into out. No nish:net call looks a name up; nish/net/dns resolves one first. An address is 18 bytes: the 16 bytes of an IPv6 address (IPv4 as the mapped ::ffff:a.b.c.d), then the port, big-endian, so 127.0.0.1:8080 is ten zeros, 255 255, 127 0 0 1, 31 144. An array longer than 18 bytes is fine; the rest is not touched. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404); under Node it throws. A call that writes out is refused in a scope's region on an array a task may read, as fill is. Capability: net.

const netAddress: (
  out: u8[],
  host: string,
  port: i32,
) => i32
outu8[]required

at least 18 bytes, receiving the address; it must not be readonly, and is left as it was when the answer is -22.

hoststringrequired

a numeric IPv4 dotted quad or IPv6 literal.

porti32required

the port, 0 to 65535.

returnsi32

0, or -22 for a name, a string with a NUL inside it, a port outside 0..65535 or an out shorter than 18 bytes.

netClose

Close the descriptor. The descriptor is gone whatever the answer, as close(2) promises on Linux. Not willreturn, because a socket the program inherited with a linger time can wait. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netClose: (fd: i32) => i32
fdi32required

the descriptor closed.

returnsi32

0, or the failure.

netLocalPort

The port the socket fd is bound to, which is how a program that listened on port 0 learns the one the kernel chose. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netLocalPort: (fd: i32) => i32
fdi32required

a bound socket.

returnsi32

the port, or a negative errno.

netMss

A connected TCP socket's send MSS, the payload bytes one segment carries: Linux's TCP_INFO tcpi_snd_mss, or TCP_MAXSEG where that is not above 0 and on Darwin. The answer moves as the path does, so read it when it is needed rather than once. It never panics. Not callable in a scope() task or a parallel body. It compiles on wasm32 and the WASI profile, where it is the constant -1 with its descriptor still evaluated; under Node it throws rather than answer -1. Capability: net.

import { netMss } from "nish:net";

// A batch of whole segments, or the caller's own size where there is no MSS.
export const batch = (conn: i32, fallback: i32): i32 => {
  const mss = netMss(conn);
  return mss > 0 ? mss * 8 : fallback;
};
const netMss: (fd: i32) => i32
fdi32required

the socket.

returnsi32

the MSS; -1, never an errno, for anything else (a descriptor that is not open, a socket with no peer such as a listener or one never connected, though the kernel answers its default 536 for those, a socket that is not TCP, a connection a NET_LISTEN_RING listener accepted, whose ring cannot ask for it), and always on wasm.

netRead

Up to len bytes into buf[off, off + len). The range is checked in the compiled code before the call: one outside 0 <= off <= off + len <= buf.length, or a negative off or len, panics with slice out of range: [4, 9) of length 8 (the numbers are the range and length), exit 1. A buf that is not a writable u8[] is refused at compile time (NL2402). Not callable in a scope() task or a parallel body. A call that writes buf is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netRead: (
  fd: i32,
  buf: u8[],
  off: i32,
  len: i32,
) => i32
fdi32required

the socket to read.

bufu8[]required

the buffer filled.

offi32required

the first byte of buf written.

leni32required

the most bytes read; a len of 0 answers 0 too, so ask for at least one byte.

returnsi32

the count, 0 at end of stream, or -11 when nothing is waiting.

netRingState

Whether listeners opened with NET_LISTEN_RING accept into rings: 1 when they do, 0 until a listener has found rings or a refusal, or the negative errno the kernel refused rings with (-1 when a seccomp filter refuses io_uring_setup, -38 for a kernel without it), in which case they serve descriptors. Decided once per process, by the first listener that finds rings or a refusal; one that finds descriptors or memory short serves descriptors itself and leaves the state at 0, and a later listener asks again. -95 on Darwin. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netRingState: () => i32
returnsi32

1, 0 or the negative errno.

netSetOption

Set one socket option from a whitelist: there is no raw level and option number, so a program cannot pass a level, a name and a length through to the kernel. The ids are the runtime's own numbers, the same on Linux and Darwin. Refused at compile time on wasm32 and the WASI profile (NL2404); under Node it throws rather than set one. Not callable in a scope() task or a parallel body. Capability: net.

import { NET_TCP_QUICKACK, netSetOption } from "nish:net";

// After each response: Linux may have left quick-ACK mode.
export const answered = (conn: i32): i32 => netSetOption(conn, NET_TCP_QUICKACK, 1);
const netSetOption: (
  fd: i32,
  option: i32,
  value: i32,
) => i32
fdi32required

the socket.

optioni32required

one of the NET_* ids below; any other is -22.

valuei32required

the option's value: 0 or 1 for the switches, a byte count for the buffer sizes.

returnsi32

0, or a negative errno (-9 a closed descriptor, -88 not a socket, -95 for NET_TCP_QUICKACK off Linux).

netShutdown

Shut one or both directions of a connection. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

On a connection a NET_LISTEN_RING listener accepted, the shutdown goes behind the bytes already written, so the peer reads them and then the end of the stream; a later netWrite answers -32 once the write side is shut, and netRead answers what is queued and then 0 once the read side is.

const netShutdown: (fd: i32, how: i32) => i32
fdi32required

the socket.

howi32required

the read side (0), the write side (1) or both (2).

returnsi32

0, or a negative errno; -22 for any other how, -9 for a closed ring connection.

netWrite

Up to len bytes of buf[off, off + len). A gone peer is -32, never SIGPIPE, so a closed connection cannot end the process. The range is checked as netRead's is, with the same panic. buf may be readonly; anything but a u8[] is refused at compile time (NL2405). Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netWrite: (
  fd: i32,
  buf: readonly u8[],
  off: i32,
  len: i32,
) => i32
fdi32required

the socket to write.

bufreadonly u8[]required

the bytes sent.

offi32required

the first byte sent.

leni32required

the most bytes sent.

returnsi32

the count, which may be fewer than len, or a negative errno: -11 when the send buffer is full, -32 for a gone peer.

netWrite2

netWrite of a's range then b's, in one system call (sendmsg with two buffers), so a header and a body leave together with no copy into one buffer. The count may be fewer than aLen + bLen and may end inside a; the program sends the rest, as after a short netWrite. A gone peer is -32, never SIGPIPE. Both ranges are checked as netRead's is, a's first, and either may be empty. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const netWrite2: (
  fd: i32,
  a: readonly u8[],
  aOff: i32,
  aLen: i32,
  b: readonly u8[],
  bOff: i32,
  bLen: i32,
) => i32
fdi32required

the socket to write.

areadonly u8[]required

the first buffer.

aOffi32required

the first byte of a sent.

aLeni32required

how many bytes of a.

breadonly u8[]required

the second buffer.

bOffi32required

the first byte of b sent.

bLeni32required

how many bytes of b.

returnsi32

the count of both, at most aLen + bLen, or a negative errno: -11 when the send buffer is full, -32 for a gone peer.

panic

message and a newline to stderr, then exit 1: it ends the program, with the same ending an out-of-range index has. It is how a program ends on an unmet invariant. Statement position, and it terminates control flow like process.exit, so it is never: that is what lets tsc agree that a function ending in a panic returns, a non-void one included, and that x is not null after if (x === null) { panic(...); } — the guard-then-panic shape src/ uses everywhere in place of an assert. Also exported by nish:io. Capability: none.

const panic: (message: string) => never
messagestringrequired

what stderr says before the exit.

returnsnever

parseFloat

The decimal number at the start of s, as an f64: ASCII whitespace, then the longest decimal literal ([sign] digits [. digits] [e [sign] digits], . digits, or [sign] Infinity), correctly rounded. parseFloat("3.14xyz") is 3.14 and parseFloat("1e") is 1. One deviation from JavaScript: a 0x prefix is read as hexadecimal (parseFloat("0x1A") is 26, where JavaScript stops at the x and gives 0). Under --deterministic a 0x string reads as --emit-ts reads it on every target: the hex integer, correctly rounded, stopping at a hex float's . or p (0x1p3 is 1). Exactly one argument. Capability: none.

const parseFloat: (s: string) => f64
sstringrequired

the text read.

returnsf64

the number, or NaN when there is none (parseFloat("abc"), parseFloat(""), parseFloat(".")).

parseInt

The base-10 integer at the start of s, as an i32: ASCII whitespace, an optional sign, then digits, stopping at the first other character (parseInt("42px") is 42). Three deviations from JavaScript: there is no NaN in an i32, so no digits give 0 (parseInt("abc"), parseInt("")); a value beyond the i32 range saturates as toI32 does (parseInt("99999999999") is 2147483647); and a 0x prefix is not hexadecimal (parseInt("0x10") is 0). Always an i32, under --number-mode f64 too, where Number reads a wider value. Exactly one argument: there is no radix, since base 10 is the only one. A non-string is refused: "parseInt expects a string, got i32". Capability: none.

const parseInt: (s: string) => i32
sstringrequired

the text read.

returnsi32

the integer, or 0 when there are no digits.

peerCredentials

The peer of the Unix socket fd as the kernel recorded it when the connection was made (the connect, or the socketpair): out gets its pid, uid and gid. A peer that has since changed its uid, passed the socket on or closed still reads as it was then. The pid is -1 where Darwin has no LOCAL_PEERPID or the kernel refuses it. A uid or gid of 2^31 or above wraps (-2 is uid 4294967294). out must be an i32[] and not readonly. Not callable in a scope() task or a parallel body.

A call that writes out is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const peerCredentials: (fd: i32, out: i32[]) => i32
fdi32required

the connected Unix socket.

outi32[]required

at least 3 slots, receiving pid, uid and gid.

returnsi32

0; -22 an out shorter than 3, -9 a closed fd, -88 not a socket, -95 not Unix (all before anything is asked), -107 a socket with no peer (a listener, or one never connected), on every platform.

pollAdd

Watch fd for events under token. On Darwin a descriptor added watching nothing is known to the loop but never reported (a disabled read filter), and an add that answers -17 leaves the descriptor under the token it gave rather than the old one. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const pollAdd: (
  loop: i32,
  fd: i32,
  events: i32,
  token: i32,
) => i32
loopi32required

the loop from pollCreate.

fdi32required

the descriptor watched.

eventsi32required

1 readable, 2 writable, 3 both, 0 neither.

tokeni32required

an i32 of the program's choosing, which pollWait reports it under as it went in.

returnsi32

0, or a negative errno: -17 for a descriptor the loop already watches, or for a slot handle another loop watches (a slot is in one loop at a time), -22 for an event bit past 2.

pollCreate

A readiness loop, level-triggered: epoll on Linux, kqueue on Darwin. The descriptor is close-on-exec. A descriptor still ready when the program waits again is reported again, so a loop that handles one pair of several, or leaves a datagram unread, loses nothing. Nothing here allocates. Refused at compile time on wasm32 and the WASI profile (NL2404), and not callable in a scope() task or a parallel body. Capability: net.

const loop = pollCreate();
pollAdd(loop, server, 1, 1);
pollAdd(loop, signalFd(), 1, 2);
const ready: i32[] = new Array<i32>(32);
let running = true;
while (running) {
  const n = pollWait(loop, ready, -1);
  for (let k = 0; k < n; k++) {
    if (ready[2 * k] === 2) {
      running = false;             // SIGTERM or SIGINT
    } else {
      serve(server);               // until it answers -11
    }
  }
}
const pollCreate: () => i32
returnsi32

the loop's descriptor, or a negative errno.

pollModify

New events or a new token for a watched fd. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const pollModify: (
  loop: i32,
  fd: i32,
  events: i32,
  token: i32,
) => i32
loopi32required

the loop from pollCreate.

fdi32required

the descriptor watched.

eventsi32required

1 readable, 2 writable, 3 both, 0 neither.

tokeni32required

the number pollWait reports it under.

returnsi32

0, or a negative errno: -2 for a descriptor the loop does not watch.

pollRemove

Stop watching fd. Closing a descriptor stops the watching too. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const pollRemove: (loop: i32, fd: i32) => i32
loopi32required

the loop from pollCreate.

fdi32required

the descriptor no longer watched.

returnsi32

0, or a negative errno: -2 for a descriptor the loop does not watch.

pollWait

Wait for readiness, filling pairs: ready[2k] token, ready[2k + 1] events (1 readable, 2 writable, with 4 added for a hang-up or an error). Not willreturn, because it can wait forever. It never writes past ready.length. ready must be an i32[] (the tokens are the program's own i32s) and not readonly. A signal that interrupts the wait makes it answer 0, as a timeout does, rather than wait past the deadline; the descriptor signalFd() answers can be added to the loop, and is readable when SIGTERM or SIGINT arrives. Once the process has opened a NET_LISTEN_RING listener with rings, for the rest of its life, an interrupted wait goes on to its deadline, since the rings' own work interrupts it too: watch signalFd() to see a signal.

A UDP socket is always writable, and on Linux one whose both sides are shut is readable, writable and hung up, 7. On Darwin a descriptor both readable and writable is one pair, 3; a descriptor watching nothing is never reported (epoll still reports its hang-up or error as 4); and a peer's half-close is 5 (1|4) where Linux reports 1. Not callable in a scope() task or a parallel body. A call that writes ready is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const pollWait: (
  loop: i32,
  ready: i32[],
  timeoutMs: i32,
) => i32
loopi32required

the loop from pollCreate.

readyi32[]required

receives the pairs; shorter than 2 is -22.

timeoutMsi32required

the most milliseconds to wait; negative: forever (-1).

returnsi32

how many pairs, at most ready.length / 2 and at most 64 (the rest stay ready for the next wait), 0 on a timeout, or a negative errno.

readCString

The NUL-terminated bytes at p, copied into a new string of the program's own: undefined behaviour unless p is a live C string, since nothing proves the bytes end (a dangling or freed pointer, or a buffer with no NUL). It is the copy a string result of a declare function makes, for the pointers C allocated for the caller to free, and C's buffer is never held past the call, so free(p) straight after it is safe.

The parameter is CPtr, so an unnarrowed CPtr | null is refused (`readCString` expects an argument of type CPtr, got CPtr | null) and if (p !== null) comes first. A declare function declared to answer CPtr may still answer NULL, so the call tests p first and panics with ffi-null on NULL (`readCString` read a NULL pointer, exit 1), as readStruct does; declare a result that may be NULL as CPtr | null.

The copy is new on every call and is the calling function's allocation, and it is refused inside a using a = arena() block that would release one held outside it (`readCString(p)` may be allocated inside the `using arena()` block). Under --deny-panics its NULL test is an ffi-null site no proof removes, so the scope refuses the call (the copy's oom beside it is allowed), and the pointer it reads is ffi. It lowers the same on wasm32, where whether the program links is the declare function's question. It has no Node form, as a CPtr comes only from a declare function, which Node cannot call. Capability: unsafe.

const readCString: (p: CPtr) => string
pCPtrrequired

the address a declare function handed back; NULL panics.

returnsstring

a copy of the bytes before the first NUL.

readFileBytesSync

The file's bytes as they are on disk — nothing assumes UTF-8, so a zero byte, a byte of 0x80 or above and an invalid sequence all come back unchanged, and length is the file's size — or null for exactly the paths readFileSyncOrNull answers null for: missing, a directory, a parent that cannot be searched. There is no exiting twin. The array is an ordinary arena u8[] with length === capacity, narrowed with if (b !== null). A file longer than 2^31 - 1 bytes is one it cannot read. A wasm32 build has no file I/O and so no readFileBytesSync. Under Node the answer is Array.from(fs.readFileSync(path)) or null. Capability: fs.read.

const readFileBytesSync: (path: string) => u8[] | null
pathstringrequired

the file to read.

returnsu8[] | null

its bytes, or null.

readFileSync

The whole file as one string; a path that cannot be read as one — missing, a directory, a parent that cannot be searched — prints nish: cannot read <path> to stderr and exits 1. A file longer than 2^31 - 1 bytes is one it cannot read, in both number modes, as in Node. Paths are relative to the working directory, and a NUL byte in path is refused as a missing path is. A wasm32 build has no file I/O and so no readFileSync. Capability: fs.read.

const readFileSync: (path: string) => string
pathstringrequired

the file to read.

returnsstring

its contents.

readFileSyncOrNull

The same read, answering null for every path the other exits over: a missing path, a directory, a parent that cannot be searched, a pipe with no length to ask for. A program can therefore report the missing file itself and carry on; the call subsumes an existsSync and has no time-of-check race. The result is narrowed with if (text !== null) like any other nullable. The 2^31 - 1 byte limit and the NUL rule of readFileSync apply. Capability: fs.read.

const readFileSyncOrNull: (path: string) => string | null
pathstringrequired

the file to read.

returnsstring | null

its contents, or null.

readSignal

Block until SIGTERM or SIGINT arrives. The argument is an i32 in both number modes, as a descriptor is, and an f64, an i64 or a string is refused rather than converted. It can wait forever. A wasm32 build and the wasi profile refuse it (NL2404). No reading under Node, which throws. Also exported by nish:process. Capability: signal.

const readSignal: (fd: i32) => i32
fdi32required

signalFd()'s descriptor.

returnsi32

the signal's number, 15 or 2; -1 for any fd that is not signalFd()'s, and for a read that fails.

readStdin

Up to len bytes of stdin into buf[off, off + len), never blocking. stdin is never made non-blocking, since that flag belongs to the open file description a shell shares with every program it starts: the call asks select with a timeout of 0 before it reads. The range is checked as netRead's is, with the same panic, and buf must be a writable u8[]. Under --profile wasi it waits for its bytes (call waitStdin first); under Node and in a browser it throws; refused at compile time on a freestanding wasm32 target. Capability: tty.

import { readStdin, setRawMode, waitStdin } from "nish:term";

export const main = (): number => {
  setRawMode(true);
  const keys: u8[] = new Array<u8>(16);
  let running = true;
  while (running) {
    if (waitStdin(16)) {
      const n = readStdin(keys, 0, keys.length);
      if (n === 0 || (n < 0 && n !== -11)) {
        running = false; // stdin ended, or reading it failed
      }
      for (let i = 0; i < n && i < keys.length; i++) {
        if (keys[i] === 113) {
          running = false; // q
        }
      }
    }
    // advance and draw one frame
  }
  setRawMode(false);
  return 0;
};
const readStdin: (buf: u8[], off: i32, len: i32) => i32
bufu8[]required

the buffer filled.

offi32required

the first byte of buf written.

leni32required

the most bytes read; a len of 0 answers 0 too, so ask for at least one byte.

returnsi32

the count, 0 at end of stream, or -11 when nothing is waiting.

readStruct

A copy of the C struct at p, in a new instance of the declare class the call's context names: const lc: Lconv = readStruct(localeconv()). A type argument is not written at a call site (readStruct<Lconv>(p) is refused, as identity<i32>(7) is), so the layout comes from an annotation, a parameter or a return type, as Ok(v)'s type does; a call with none, or one whose context is not a declare class, is refused. It copies the layout's size in bytes, so the class must describe the struct's first fields (a prefix is enough) and p must point at that many readable bytes: undefined behaviour otherwise, as with readCString.

The copy is the program's own: C may free or overwrite its struct straight after the call, and a CPtr field of the copy is still C's pointer, read with readCString while C keeps it live. The parameter is CPtr, so an unnarrowed CPtr | null is refused and if (p !== null) comes first.

A NULL p is tested before the copy and panics with the ffi-null kind, naming the layout, since a declare function declared to answer CPtr may still answer NULL. No proof removes that test, so --deny-panics refuses the call; --emit-panics lists it as an ffi-null site, with the copy's oom beside it.

The copy is new on every call and is the calling function's allocation, held by the arena like new. It lowers the same on wasm32, where a pointer is 4 bytes and the layout is sized to match. It has no Node form. Capability: unsafe.

const readStruct: <T>(p: CPtr) => T
pCPtrrequired

the address of a C struct a declare function handed back.

returnsT

a copy of the struct, in the declare class its context names.

readdirSync

The directory's entries, sorted ascending by bytes (not by the file system's order, which neither readdir(3) nor Node's fs.readdirSync sorts) and without . or ..; every other dotfile is an entry. The sort is by bytes like every string comparison here, so it agrees with Node's .sort() for ASCII names and can differ for names that are not. null when the directory cannot be read at all — a missing path, a plain file, a parent that cannot be searched.

An empty directory is an empty array, so the null check is about the directory and not about its contents. A WASI build always answers null: fd_readdir lists a preopened directory rather than a path, which is a different contract. Capability: fs.read.

const readdirSync: (path: string) => string[] | null
pathstringrequired

the directory to list.

returnsstring[] | null

the entry names, or null.

realpathSync

path with every symbolic link resolved and every ., .. and repeated separator removed, as an absolute path — or null when it does not resolve, a path that does not exist included. Every component but the last must exist for POSIX realpath to answer at all, so "does not resolve" is one answer rather than several. The bytes are copied into the arena, so the result is an ordinary string, narrowed with if (p !== null) like any other nullable. Capability: fs.read.

const realpathSync: (path: string) => string | null
pathstringrequired

the path to resolve.

returnsstring | null

the resolved path, or null.

recvFd

Read at most len bytes into buf[off..] from the Unix socket sock, and the first descriptor that came with them into fd[0], or -1 when the message carried none. Every other descriptor in the message is closed before the answer, so a peer cannot leave this process holding descriptors it never asked for; room is made for 8, so the kernel drops the rest of a message that carries more and the bytes are still answered.

The one kept is close-on-exec, so a later spawn does not hand it on, and keeps the sender's blocking mode (it is not made non-blocking, so netRead on a blocking one waits: set what the program needs on it before it joins a loop). The range is checked as netRead's is, with the same panic. buf and fd must not be readonly, and fd must be an i32[]. On Darwin the descriptor is made close-on-exec by a later fcntl, so a child another thread spawns between the two inherits it.

Not callable in a scope() task or a parallel body. A call that writes buf or fd is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const recvFd: (
  sock: i32,
  buf: u8[],
  off: i32,
  len: i32,
  fd: i32[],
) => i32
socki32required

the Unix socket.

bufu8[]required

the buffer filled.

offi32required

the first byte of buf written.

leni32required

the most bytes read, at least 1.

fdi32[]required

receives the descriptor, or -1.

returnsi32

the bytes read, 0 at the end of the stream, -11 when nothing is waiting, or a negative errno; -22 a zero len or an empty fd, -9 a closed sock, -88 not a socket, -95 not Unix (all before anything is read).

renameSync

rename(2): from takes the name to, replacing a file already there in one step on one file system, so a reader sees the old file or the new one and never neither — write a temporary next to the target, then rename it over. Never a panic. A wasm32 build refuses it. Capability: fs.write.

const renameSync: (from: string, to: string) => i32
fromstringrequired

the name moved.

tostringrequired

the name it takes.

returnsi32

0, or a negative errno: -2 ENOENT for a missing from, -18 EXDEV when the two are on different file systems (nothing is copied: write the temporary in the target's directory), -21 EISDIR or -20 ENOTDIR for a file against a directory, -22 EINVAL for a NUL in either path.

secureZero

Every byte of bytes set to zero, in stores neither -O2 nor -flto may drop as dead (#385): how a key, a secret scalar or another secret is cleared once it is used. A statement: used as a value it is `secureZero` returns void and can only be used as a statement (NL2105), and it takes exactly one argument (NL2061). It fills a u8[] only; anything else is `secureZero` fills a `u8[]`, got i32[] (NL2402), a string included, which is immutable.

The call writes its argument, so a readonly u8[] is Cannot `secureZero` through readonly u8[] (declare it u8[] to write through it) (NL2264), and a function that wipes a parameter does not get readonly on it; in a scope's region it is refused where fill is (NL2394). An empty array is a call that clears nothing.

It clears the bytes of the array it is handed and nothing else: a copy taken before (slice, a push into another array, an element read into a local, a register spilled to the stack) is the program's to clear, and nothing clears what the operating system swapped out. It works under the wasi profile; a freestanding wasm module has no wipe. Under Node it is a loop that sets every element to zero, and a collector that moved the array may have left the old bytes behind. Capability: none.

const secureZero: (bytes: u8[]) => void
bytesu8[]required

the buffer to clear.

sendFd

Send buf[off..off+len) over the Unix socket sock with a copy of the descriptor fd (SCM_RIGHTS). The receiver's recvFd gets a new descriptor for the same open file, with its offset and status flags shared, as dup gives; fd stays open here. The descriptor rides on at least one byte of data, so the receiver's read is what tells it a descriptor came. A stream socket can send short: the descriptor travels with the first bytes, so send the rest with netWrite, not sendFd, or the receiver gets a second copy.

The range is checked as netRead's is, with the same panic; buf may be readonly. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const sendFd: (
  sock: i32,
  fd: i32,
  buf: readonly u8[],
  off: i32,
  len: i32,
) => i32
socki32required

the Unix socket.

fdi32required

the descriptor sent.

bufreadonly u8[]required

the bytes sent with it.

offi32required

the first byte sent.

leni32required

how many bytes, at least 1.

returnsi32

the bytes sent, or a negative errno; -22 a zero len or a negative fd, -9 a closed sock or an fd that is not open, -88 a sock that is not a socket, -95 one that is not Unix (checked before anything is sent), -32 a gone peer.

setCpuAffinity

Pin this process to CPU cpu alone (sched_setaffinity). Narrow-only: it never moves a process onto a CPU it was kept off. availableParallelism() answers 1 afterwards, and children started afterwards inherit the mask. A task or a parallel body that calls it is refused as any shared write is. A wasm32 build refuses it (NL2404). Also exported by nish:process. Capability: process.spawn.

const setCpuAffinity: (cpu: i32) => i32
cpui32required

the CPU index.

returnsi32

0, or a negative errno: a CPU outside the mask the process already has (an operator's taskset or cpuset), a negative one, or one at or past the kernel's CPU_SETSIZE is -22 with no change; -95 where the host has no affinity call (Darwin, and under Node).

setIdlePriority

Move this process to SCHED_IDLE with sched_setscheduler(0, SCHED_IDLE, ...), which runs it only when nothing else wants the CPU. Linux only. An unprivileged process can never leave SCHED_IDLE again, and an idle process can starve on a saturated machine, so a caller keeps a normal-priority fallback (setNice(19), or a deadline) for work that must finish. The policy is per thread as setNice's value is: call it at the top of main, and a task or a parallel body that calls it is refused as any shared write is. A wasm32 build refuses it. Throws under Node. Also exported by nish:process. Capability: process.spawn.

const setIdlePriority: () => i32
returnsi32

0, or a negative errno, and -95 where the host has no such policy (Darwin; Linux's EOPNOTSUPP, as nish:net spells it).

setNice

Set this process's nice value to n with setpriority(PRIO_PROCESS, 0, n). Lower-only, even as root, so the priority never rises. Children started afterwards inherit it. Linux keeps the nice value per thread: a call sets the calling thread's and every thread started after it, so it belongs at the top of main, before a scope() or a parallel loop starts the pool, and a task or a parallel body that calls it is refused as any shared write is. It never crashes the program: a failure is only the answer.

A wasm32 build refuses it (NL2404). Throws under Node. Also exported by nish:process. The label is kill's: neither reaches another process, but the priority is the one the program's children inherit, and a step down cannot always be taken back. Capability: process.spawn.

const setNice: (n: i32) => i32
ni32required

the nice value, 0..19.

returnsi32

0, or a negative errno: n outside 0..19 is -22 (EINVAL), and n below the current value is -13 (EACCES), both with no system call.

setRawMode

Raw mode on stdin's terminal, or the mode it had back. No echo, no line editing, no CR-to-NL translation, no flow control (Ctrl-S, Ctrl-Q) and no parity stripping; bytes are 8 bits wide, and a read answers as soon as one byte is there, so a key arrives as its bytes (an arrow as the three of ESC [ A).

ISIG stays on: Ctrl-C is still SIGINT and ends the program, Ctrl-\ is still SIGQUIT and Ctrl-Z still stops it, so none of them arrives as a byte (3, 28, 26); a program that wants Ctrl-C as a key asks for SIGINT through signalFd and handles it in its loop. OPOST stays on, so "\n" still moves to the start of the next line and output needs no "\r\n".

Each setRawMode(true) that enters raw mode saves the termios that was there; it comes back on setRawMode(false), when main returns or process.exit is called, on every panic, and on every signal whose default action ends the program, SIGKILL aside (SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGPIPE, SIGALRM, SIGUSR1, SIGUSR2, SIGPROF, SIGVTALRM, SIGXCPU, SIGXFSZ, SIGSYS, and the faults SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS and SIGSEGV).

For each, a handler is installed only when the program left it at its default action: it restores the terminal, puts the default back and raises the signal again, so the program still dies of it and its parent sees that (exit status 143 for SIGTERM). A program that took SIGTERM or SIGINT through signalFd keeps it and puts the terminal back itself, or by returning.

SIGKILL leaves raw mode behind, and so does a stack overflow on a thread other than the one that called setRawMode(true); stty sane undoes either, as it does a stop by SIGSTOP. Ctrl-Z (SIGTSTP) restores the terminal, stops the program, and once fg or bg continues it enters raw mode again; a program continued in the background stops again, by SIGTTOU, until fg. A program started in the background (app &) that calls setRawMode(true) is stopped by SIGTTOU, as any program that sets the terminal is, and enters raw mode on fg.

Two threads that call it at once take turns, so the termios saved is the one from before either. Asking for the mode it is already in changes nothing and answers 0, so setRawMode(false) is always safe. Under --profile wasi, on a pipe or a file, true is -25 and false is 0; under Node and in a browser it throws; refused at compile time on a freestanding wasm32 target. Capability: tty.

const setRawMode: (on: boolean) => i32
onbooleanrequired

true for raw mode, false for the mode before.

returnsi32

0, -25 when stdin is not a terminal, or the host's -errno when the terminal refuses.

setTerminalRestore

Bytes the runtime writes to the terminal on stdout at exit, on a panic and on every signal that ends the program (SIGKILL aside), before termios is restored; raw mode or not, and setting them installs the same handlers. Typical bytes are the escapes that leave an alternate screen, show the cursor or turn mouse reporting off. Replaces the previous string; "" clears it. The cap is 4096 bytes.

They are written to stdout once, with write alone, at most once however many of those paths race, and after all the program printed (output is not buffered). Ctrl-Z and setRawMode(false) do not end the program, so they write nothing. A signal that lands while the string is replaced writes the old one or the new one, whole. A program sets them once it has switched the terminal and again with each change, last the set that undoes them all. Under --profile wasi it keeps nothing; under Node and in a browser it throws; refused at compile time on a freestanding wasm32 target. Capability: tty.

const setTerminalRestore: (bytes: string) => i32
bytesstringrequired

the bytes written at the end.

returnsi32

0, -25 when stdout is not a terminal ("" is still 0 there), -7 (E2BIG) past NISH_TERM_RESTORE_MAX bytes (4096); both failures keep what was there.

signalFd

A descriptor that becomes readable when SIGTERM or SIGINT arrives. It is the read end of a pipe that a sigaction handler in the runtime's C writes one byte to per signal, so the signals' default action (ending the process) never runs. The handler runs in whichever thread the signal lands on, so a scope() task or a parallel worker running when it is called cannot take the signal and end the process, and nothing is blocked for a spawned child to inherit.

Installing the handler overrides a disposition the process started with, so a signal its parent ignored is heard, as process.on("SIGTERM") hears it under Node. Made once: every later call answers the same descriptor. A child that spawnSync or spawnSyncTo starts afterwards can still be stopped by either signal, because exec resets a caught signal to its default. Signals other than SIGTERM and SIGINT are not in the language. A descriptor rather than a handler, so a server's loop can wait on it beside its sockets with pollWait.

A wasm32 build and the wasi profile refuse it (NL2404). No reading under Node, which delivers a signal only to its event loop: it throws. Also exported by nish:process. Capability: signal.

const signalFd: () => i32
returnsi32

the descriptor, or -1 when it cannot be made.

spawn

Start argv[0] through PATH exactly as spawnSync does — the same vector, environment, streams and working directory — and answer at once, without waiting. The child is the program's until waitPid reaps it; one never reaped stays a zombie until the program exits, as it would in C. Test pid > 0 before handing the answer on: a failure such as -1 (EPERM) passed to waitPid reads as "any child". No reading under Node, which throws. A wasm32 build refuses it (NL2404), and a scope's task or a parallel body that calls it is refused as any shared write is. Also exported by nish:process. Capability: process.spawn.

Under --sandbox with a list of granted programs, the program started cannot start another, as for spawnSync.

const spawn: (argv: string[]) => i32
argvstring[]required

the program and its arguments.

returnsi32

the child's pid, or a negative errno: -22 (EINVAL) for an empty vector or an argument holding a NUL, and posix_spawnp's own error otherwise, so a program that is not there is -2 (ENOENT). Under --sandbox with a list of granted programs, a spawn that cannot be held to one program is refused: -11 (EAGAIN), -38 (ENOSYS), -10 (ECHILD) or the kernel's own error, with a line on stderr.

spawnPiped

The same run with all three streams on pipes, all in memory: the child reads stdin's bytes and then end of file, and whatever it prints is appended to stdout and stderr, which keep what they held. The runtime writes stdin and drains both outputs in one poll loop, so a child that fills one pipe while the parent waits on another cannot deadlock it. When a stream passes 16 MiB (NISH_PIPED_CAP) the child is killed with SIGKILL and that array keeps the first 16 MiB.

A child that exits without reading its stdin is not a failure. The child inherits the environment and working directory, and no descriptor of the program but its three streams; it starts with SIGPIPE as the program had it, and the program's own SIGPIPE from writing to a child that stopped reading is absorbed. The two output arrays are grown by the runtime, so readonly is refused for them, as is a typed-array spelling (Int32Array, ...), whose length is fixed. A wasm32 build refuses it (NL2404). Capability: process.spawn.

Under --sandbox with a list of granted programs, the program started cannot start another, as for spawnSync.

const spawnPiped: (
  argv: string[],
  stdin: readonly u8[],
  stdout: u8[],
  stderr: u8[],
) => i32
argvstring[]required

the program and its arguments.

stdinreadonly u8[]required

the bytes the child reads.

stdoutu8[]required

receives what the child prints on stdout.

stderru8[]required

receives what the child prints on stderr.

returnsi32

the status as spawnSync answers it (the exit code, 128 + n, and -1 for an empty vector, a child that cannot be started, a pipe or poll that fails, and a WASI build), or -2 when a stream passed 16 MiB.

spawnPipedWithin

spawnPiped with a deadline: the same captured run, killed once timeoutMs milliseconds have passed since it started. A negative timeoutMs is no deadline, as pollWait's is, so spawnPipedWithin(argv, stdin, stdout, stderr, -1) is spawnPiped(argv, stdin, stdout, stderr). When the deadline passes the child is killed with SIGKILL and reaped, the answer is -3, and stdout and stderr keep every byte read before the kill.

The deadline covers the whole run, the wait for the child's exit included, and is measured on the monotonic clock. Only the child's own pid is killed: a grandchild it started is not, and one that keeps an output pipe open makes the run wait for it, so a child that exited 0 can still answer -3. The rest is spawnPiped's: the same environment, descriptors, SIGPIPE handling and 16 MiB cap, readonly and typed-array spellings refused for the two output arrays, refused by a wasm32 build (NL2404). Capability: process.spawn.

Under --sandbox with a list of granted programs, the program started cannot start another, as for spawnSync.

const spawnPipedWithin: (
  argv: string[],
  stdin: readonly u8[],
  stdout: u8[],
  stderr: u8[],
  timeoutMs: i32,
) => i32
argvstring[]required

the program and its arguments.

stdinreadonly u8[]required

the bytes the child reads.

stdoutu8[]required

receives what the child prints on stdout.

stderru8[]required

receives what the child prints on stderr.

timeoutMsi32required

the milliseconds the run may take, or a negative number for no deadline.

returnsi32

the status as spawnPiped answers it (the exit code, 128 + n, -1 for a child that cannot be started or a WASI build, -2 when a stream passed 16 MiB), or -3 when the deadline passed and the child was killed.

spawnSync

Run argv[0], searched on PATH, with argv as its argument vector, and wait for it. The child inherits this process's environment, streams and working directory. The argument is checked down to its element type: an i32[] is an array but not a command line. Arguments are passed as bytes, so an embedded NUL truncates one. A wasm32 build and a WASI build have no processes, and a WASI build always answers -1. Capability: process.spawn.

Under --sandbox, a dependency's process.spawn=<program> grants can make a list of the only programs the build may start. A program this builtin starts under such a list cannot start another: an exec by it, or by anything it forks, fails, so a granted #! script runs its interpreter's builtins alone. Where the kernel or a container's seccomp profile refuses what that takes (Docker's default profile does), the spawn fails and one line on stderr says so.

const spawnSync: (argv: string[]) => number
argvstring[]required

the program and its arguments.

returnsnumber

the exit status, or 128 + n when signal n killed it (the shell's convention), or -1 when the vector is empty — there is no argv[0] to run — and whenever the child cannot be started or cannot be waited for.

spawnSyncTo

The same run with each stream sent to a file rather than inherited: each non-empty path is created or truncated at 0644, as writeFileSync does, and a symbolic link as its last component is refused, which answers -1. An empty string leaves that stream inherited, so one call can capture stdout and let stderr through. The two paths must not name one file: each is opened separately, with its own offset, so the streams would overwrite rather than interleave; capture them apart and concatenate. Capability: process.spawn.

Under --sandbox with a list of granted programs, the program started cannot start another, as for spawnSync.

const spawnSyncTo: (
  argv: string[],
  stdoutPath: string,
  stderrPath: string,
) => number
argvstring[]required

the program and its arguments.

stdoutPathstringrequired

the file the child's stdout goes to, or "".

stderrPathstringrequired

the file the child's stderr goes to, or "".

returnsnumber

every answer spawnSync gives — the status, 128 + n, and -1 for an empty vector, a child that cannot be started, a refused link and a WASI build.

spawnWithFds

spawn with the child holding fds[i] as descriptor 3 + i, close-on-exec cleared there. Its streams 0 to 2 are this process's, and no other descriptor of this process reaches it but one opened without close-on-exec, which nothing the runtime opens is. Any order works: fds may list a descriptor that is already its own target ([3]), another entry's target ([4, 3]), or the same one twice. An empty fds is spawn exactly. The child shares each descriptor's open file, its offset and its status flags, O_NONBLOCK among them, and this process keeps its own. Reap the pid with waitPid. No reading under Node, which throws. A wasm32 build refuses it (NL2404). Capability: process.spawn.

Under --sandbox with a list of granted programs, the program started cannot start another, as for spawnSync.

const spawnWithFds: (
  argv: string[],
  fds: readonly i32[],
) => i32
argvstring[]required

the program and its arguments.

fdsreadonly i32[]required

the descriptors handed down, at most 64.

returnsi32

the child's pid, or a negative errno: -22 more than 64 descriptors or a negative one (before anything is opened or started), -9 one that is not open, -24 (or -22 above the descriptor limit) a scratch descriptor the system cannot give. Under --sandbox with a list of granted programs, a spawn that cannot be held to one program is refused: -11 (EAGAIN), -38 (ENOSYS), -10 (ECHILD) or the kernel's own error, with a line on stderr.

statMtimeSync

The modification time of path in milliseconds since the epoch, with the sub-millisecond fraction the file system keeps, computed as Node's mtimeMs is (seconds times 1e3 plus nanoseconds over 1e6, in doubles), so the two print the same digits. stat follows a symbolic link, and a directory has a time of its own. An f64 has no null, so a path that cannot be stat'd answers NaN, JavaScript's own answer for a time that is not one; test it with m !== m. A wasm32 build and the wasi profile have no host to reach and refuse it (NL2404). Under Node it is fs.statSync(path, { throwIfNoEntry: false })?.mtimeMs, or NaN. Also exported by nish:fs. Capability: clock.

const statMtimeSync: (path: string) => f64
pathstringrequired

the file to stat.

returnsf64

milliseconds since the epoch, or NaN when it cannot be stat'd — missing, or a parent that cannot be searched.

tcpAccept

The next waiting connection, as a descriptor of its own, non-blocking and close-on-exec, with the peer's address written into peer. Not willreturn: on a blocking socket the program inherited it waits. Not callable in a scope() task or a parallel body. A call that writes peer is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const tcpAccept: (fd: i32, peer: u8[]) => i32
fdi32required

the listener.

peeru8[]required

at least 18 bytes, receiving the peer's address in the 18-byte form; it must not be readonly. A shorter peer is -22 before anything is accepted, so no connection is taken and lost.

returnsi32

the connection's descriptor, or a slot handle at or above 2^20 from a NET_LISTEN_RING listener, whose peer is written as zeros; -11 when none waits; -23 when a ring listener's slots are all taken; -95 for a datagram socket. A ring listener whose accept found memory short answers -12 or -105 once, as a descriptor does, then pauses accepting for a back-off of 10 ms, doubling to 640 ms while it recurs, and accepts again. Any other errno but -11, -4, -103 or -71 means the listener is broken: it stops accepting and answers that errno from then on, so close it and listen again.

tcpConnect

A new TCP socket, non-blocking and close-on-exec, that starts connecting to addr: an IPv4 address from an IPv4 socket, any other from an IPv6 one. It answers its descriptor at once, while the connection is still being made: the EINPROGRESS (-115) of a non-blocking connect is not a failure, and the loop says when it has finished by reporting the descriptor writable (ask pollAdd for events 2, then connectResult). It holds TCP_NODELAY, so a small write is sent at once. Neither this nor connectResult waits or allocates. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const addr: u8[] = new Array<u8>(18);
netAddress(addr, "127.0.0.1", 8080);
const fd = tcpConnect(addr);          // the descriptor, still connecting
pollAdd(loop, fd, 2, 1);              // writable once it has finished
// ... pollWait until token 1 comes back ...
if (connectResult(fd) === 0) {
  pollModify(loop, fd, 1, 1);         // connected: now wait to read
}
const tcpConnect: (addr: readonly u8[]) => i32
addrreadonly u8[]required

the 18-byte address to connect to; a shorter one is -22 before any socket exists.

returnsi32

the socket's descriptor, or a negative errno; any failure but -115 closes the socket and is answered instead of it.

tcpListen

A listening TCP socket with SO_REUSEADDR, so a restarted server rebinds a port its old connections still hold in TIME_WAIT. An IPv4 host is an IPv4 socket; any other is IPv6 with IPV6_V6ONLY off, so "::" hears IPv4 and IPv6, and on a kernel without IPv6 "::" is IPv4's 0.0.0.0. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const tcpListen: (
  host: string,
  port: i32,
  backlog: i32,
) => i32
hoststringrequired

the numeric address to bind.

porti32required

the port, 0 for any.

backlogi32required

the kernel's queue of unaccepted connections.

returnsi32

the listener's descriptor, or a negative errno: -98 when the port is in use, -22 for a host that is not a literal.

tcpListenFlags

tcpListen's socket, with SO_REUSEPORT for flag 1 and TCP_NODELAY on each accepted socket for flag 2. Flag 1 lets several listeners that all ask for it share one port, each with its own accept queue, whether one process holds them all or each of several processes holds one.

On Linux the connections are spread by a hash of the connection's 4-tuple and only listeners of the same user may share; on Darwin the listeners share the port but one of them takes the connections, so the flag buys a restart without a gap rather than a spread. Flag 2 sets TCP_NODELAY on every connection tcpAccept takes from the listener, on every platform: the runtime sets it on each accepted socket, and a connection on which it cannot be set is closed and its failure answered.

Flag 4, with flag 1, steers by CPU: a new connection goes to the group's listener whose bind order is the index of the CPU that received it (Linux; -95 elsewhere); a CPU past the group's size falls back to the hash. Flags add: 3 is both, 5 and 7 steer. Flag 0 is tcpListen exactly. A port held by a listener without flag 1 is -98 to a listener that asks for it, and the other way round. Refused at compile time on wasm32 and the WASI profile (NL2404). Not callable in a scope() task or a parallel body. Capability: net.

Flag 8 (NET_LISTEN_RING in nish:net) accepts into io_uring slots on Linux, so connections are not bound by the descriptor limit; where rings are refused the listener serves descriptors and netRingState says why. Elsewhere the flag is accepted and does nothing.

const tcpListenFlags: (
  host: string,
  port: i32,
  backlog: i32,
  flags: i32,
) => i32
hoststringrequired

the numeric address to bind.

porti32required

the port, 0 for any.

backlogi32required

the kernel's queue of unaccepted connections.

flagsi32required

1, 2, 4 and 8 as above.

returnsi32

the listener's descriptor, or a negative errno: -22 for any other bit (a negative flags included) or 4 without 1, before a socket is made; -95 for flag 4 off Linux; -98 for a port in use; -23 once the process has opened 31 ring listeners, closed or not.

terminalSize

The size of the terminal on stdout, else stderr, as a fresh array: read it again on each frame to follow a resize. Under Node it is Node's columns and rows; in a browser [-25, 0]; refused at compile time on a freestanding wasm32 target. Capability: tty.

const terminalSize: () => i32[]
returnsi32[]

[columns, rows]; [-errno, 0] when neither is a terminal, [-25, 0] for "not a terminal" (a pipe, a file, --profile wasi), and [0, 0] for a terminal no one set a size for.

toF32

x as an f32; from an f64 it rounds to nearest, and an integer is converted as signed or unsigned by its own signedness. An f32 is unchanged. A bare literal argument is typed f32: toF32(2.75). Capability: none.

const toF32: (x: number | boolean) => f32
xnumber | booleanrequired

the value to convert.

returnsf32

the nearest f32.

toF64

x as an f64; from an f32 it is exact, and an integer is converted as signed or unsigned by its own signedness. An f64 is unchanged. A bare literal argument is typed f64: toF64(3). Capability: none.

const toF64: (x: number | boolean) => f64
xnumber | booleanrequired

the value to convert.

returnsf64

x as an f64.

toI32

x as an i32. An integer of 32 bits or more wraps to its low 32 bits, a narrower one is sign- or zero-extended by its own signedness, and a float saturates (NaN is 0, out of range clamps). An i32 is unchanged, and an integer of the same width and another signedness keeps its bits. The float rule is Rust's as cast, not JavaScript's modulo-2^32 ToInt32: toI32(5e10) is 2147483647, while the integer rule gives toI32(5000000000) as 705032704.

The result of a u8, a u16 or a ranged integer lies in the declared range of x, so const r: integer<0, 255> = toI32(b) costs no check for a u8 b; under --number-mode f64 this is how a number enters an integer<Lo, Hi>. An argument that is not a number is refused, as `toI32` expects a number (i32, i64, or f64), got string. Capability: none.

const toI32: (x: number | boolean) => i32
xnumber | booleanrequired

the value to convert.

returnsi32

x in 32 signed bits.

toI64

x as an i64: a signed source is sign-extended, an unsigned one zero-extended, and a float saturates (NaN is 0, out of range clamps). An i64 is unchanged, and a u64 keeps its bits. Capability: none.

const toI64: (x: number | boolean) => i64
xnumber | booleanrequired

the value to convert.

returnsi64

x in 64 signed bits.

toU16

x as a u16, by toU8's rules at 16 bits: a float saturates into 0 .. 65535. Capability: none.

const toU16: (x: number | boolean) => u16
xnumber | booleanrequired

the value to convert.

returnsu16

x in 16 unsigned bits.

toU32

x as a u32, by toU8's rules at 32 bits: a float saturates into 0 .. 2^32 - 1. From an i32 the bits do not move, so no instruction is emitted. Capability: none.

const toU32: (x: number | boolean) => u32
xnumber | booleanrequired

the value to convert.

returnsu32

x in 32 unsigned bits.

toU64

x as a u64. Widening sign-extends a signed source, so toU64(-1: i32) is 2^64 - 1, as -1i32 as u64 is in Rust; a float saturates into 0 .. 2^64 - 1, so a negative value is 0. From an i64 the bits do not move. The largest u64 values cannot be written as literals (past 2^53), so they are built this way: toU64(0) - toU64(1) is 2^64 - 1. Capability: none.

const toU64: (x: number | boolean) => u64
xnumber | booleanrequired

the value to convert.

returnsu64

x in 64 unsigned bits.

toU8

x as a u8: a wider integer is truncated, and a float saturates into 0 .. 255, so a negative value is 0. An integer source of the same width and another signedness keeps its bits, and a narrower one is zero-extended from an unsigned source and sign-extended from a signed one. The conversion also types a literal, which is how 255 is written for a u8 where no context gives it that type: toU8(255). Capability: none.

const toU8: (x: number | boolean) => u8
xnumber | booleanrequired

the value to convert.

returnsu8

x in 8 unsigned bits.

totalMemory

Bytes of physical memory — _SC_PHYS_PAGES times the page size on Linux, hw.memsize on Darwin. It is the machine's, not a cgroup's limit. Under Node it is os.totalmem(), a bigint as every i64 is there. A wasm32 build refuses it (NL2404). It writes nothing and may be called in a task. Also exported by nish:process. Capability: none.

const totalMemory: () => i64
returnsi64

the byte count, or -1 when the host does not say.

udpBind

A datagram socket, non-blocking and close-on-exec, bound to a numeric host and port the way tcpListen's is, "::" and its IPv4 fallback included. The ECN bits of every datagram are always read. Without flag 1 a port in use is -98. Refused at compile time on wasm32 and the WASI profile (NL2404), and not callable in a scope() task or a parallel body. Capability: net.

const udpBind: (host: string, port: i32, flags: i32) => i32
hoststringrequired

the numeric address to bind.

porti32required

the port, 0 for any.

flagsi32required

flag 1 SO_REUSEPORT, so several sockets that all ask for it share a port and the kernel spreads the datagrams across them; flag 2 UDP_GRO (-95 on Darwin); flag 4, with flag 1 and a group size N from 1 to 255 in bits 8 to 15, steers QUIC: the port's group hands each datagram to its socket number (byte 0 of the Destination Connection ID) mod N, in the order the sockets were bound, and a refused attach closes the socket and answers the errno (-95 on Darwin). Flag 4 without 1, with 2 or with N 0, N without 4, or any other bit is -22.

returnsi32

the socket's descriptor, or a negative errno.

udpRecvFrom

The next datagram, or several GRO coalesced, into buf[off, off + len) in one recvmsg, cut to len if it is longer. An empty datagram is a datagram: the answer is 0 for it. Not willreturn, as udpSendTo. The range is checked as netRead's is, with the same panic. meta must be an i32[] (NL2406), and none of the written arrays may be readonly.

On a socket bound with udpBind flag 2, one GSO send arrives as one datagram of up to 64 KB with meta[0] its segment size, so walk the buffer in steps of that size, the last datagram possibly shorter; without it the datagrams arrive apart with meta[0] 0. The kernel coalesces only datagrams of one flow that arrive after the option is set. On Darwin meta is always 0, 0, and a meta[1] of 0 is also what a datagram that is not ECN-capable reads as.

Not callable in a scope() task or a parallel body. A call that writes buf, from or meta is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const udpRecvFrom: (
  fd: i32,
  buf: u8[],
  off: i32,
  len: i32,
  from: u8[],
  meta: i32[],
) => i32
fdi32required

the UDP socket.

bufu8[]required

the buffer filled.

offi32required

the first byte of buf written.

leni32required

the most bytes read.

fromu8[]required

at least 18 bytes, receiving the sender in the 18-byte form; a shorter one is -22 before anything is taken.

metai32[]required

at least 2 slots, receiving [GRO segment size, ECN]: meta[0] the size of each datagram the kernel coalesced into this one (0 when it coalesced none), meta[1] the ECN bits the datagram arrived with. A shorter one is -22 before anything is taken.

returnsi32

the datagram's length, or a negative errno: -11 when none is waiting.

udpSendTo

buf[off, off + len) to the address to, in one sendmsg. Not willreturn: on a blocking socket the program inherited it waits. The range is checked as netRead's is, with the same panic. On Linux a segment above 0 is GSO: one send of 4,800 bytes with segment = 1200 leaves as four datagrams of 1,200. A socket that is IPv4, bound to an IPv4 host or to "::" on a kernel without IPv6, sends to an ::ffff:a.b.c.d address as IPv4. On Darwin a segment or an ecn above 0 is -95. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const udpSendTo: (
  fd: i32,
  buf: readonly u8[],
  off: i32,
  len: i32,
  to: readonly u8[],
  segment: i32,
  ecn: i32,
) => i32
fdi32required

the UDP socket.

bufreadonly u8[]required

the bytes sent; may be readonly.

offi32required

the first byte sent.

leni32required

how many bytes.

toreadonly u8[]required

the 18-byte destination address; a shorter one is -22.

segmenti32required

the datagram size when above 0: the kernel cuts the payload into datagrams of segment bytes, the last one shorter, so one call sends many; 0 for one datagram. Outside 0..65535 is -22.

ecni32required

the two ECN bits of the IP header: 0 not ECN-capable, 1 ECT(1), 2 ECT(0), 3 CE. Outside 0..3 is -22.

returnsi32

the bytes sent, or a negative errno: -11 when the send buffer is full; -22 also for a payload the kernel will not cut (more segments than it takes in one call, or a segment the route cannot carry).

uncheckedGet

xs[i] with no bounds check: undefined behaviour when i is out of range, which is the whole of the trade. The array holds numbers (i32, i64, u8, u16, u32, u64, f32 or f64) and nothing else, or it is `uncheckedGet` takes an array of numbers (i32, i64, u8, u16, u32, u64, f32 or f64), got string[] (NL2455). The index is an i32, so an f64 one is `uncheckedGet` expects an argument of type i32, got f64. A readonly array may be read.

To the bounds proof it is the load xs[i] is, less the check: it moves no length, and it records no passed check, so a checked xs[i] after it keeps its check. Under --deny-panics it is an allowed unchecked site. Under Node the runtime shim reads xs[i]. Capability: unsafe.

const uncheckedGet: <T extends number>(
  xs: readonly T[],
  i: i32,
) => T
xsreadonly T[]required

the array of numbers to read.

ii32required

the index, trusted to be in range.

returnsT

the element at i.

uncheckedSet

xs[i] = v with no bounds check: undefined behaviour when i is out of range. A statement. The array holds numbers, as for uncheckedGet (NL2455), the index is an i32, and the value stored is the element type. A readonly array may not be written (Cannot `uncheckedSet` through readonly u8[]). A number is copied in and held by nothing, so the store needs none of the escape and inline-array reasoning xs[i] = v carries; an array field handed to it is a value and is not stored inline.

The store is a write of the array for every rule that asks, the rule for a parallel body included. To the bounds proof it is the store xs[i] = v is, less the check, and a resize in the value stored still takes the length away. Under --deny-panics it is an allowed unchecked site. Under Node the runtime shim stores xs[i] = v. Capability: unsafe.

const uncheckedSet: <T extends number>(
  xs: T[],
  i: i32,
  v: T,
) => void
xsT[]required

the array of numbers to write.

ii32required

the index, trusted to be in range.

vTrequired

the value stored.

unixAccept

The next connection on a Unix listener, non-blocking and close-on-exec. No peer address is written: a Unix client is seldom bound. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const unixAccept: (fd: i32) => i32
fdi32required

the listener.

returnsi32

the connection's descriptor; -11 when none is waiting.

unixConnect

A new socket, non-blocking and close-on-exec, connected to the listener at path. A relative path is the working directory's. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const unixConnect: (path: string) => i32
pathstringrequired

the socket file, or @name; it must be a string.

returnsi32

the socket's descriptor, or a negative errno: -111 when nothing listens there, -2 when there is no such file, -11 a full backlog on Linux (-111 on Darwin; the socket is closed, try again later), and the path refusals unixListen has.

unixListen

A listening Unix stream socket at path (@name: Linux's abstract namespace), its file mode 0600, so only its owner may connect. A Unix socket is a descriptor like any other: netRead, netWrite, netShutdown, netClose and the readiness loop take it, and a gone peer is -32. The path is bytes up to the first NUL, so a NUL inside it is -22, as an empty path is.

It must fit sun_path with its NUL: 107 bytes on Linux, 103 on Darwin, measured on the string as written; a longer one is -36 before a socket exists. An abstract name leaves no file; its name is at most 107 bytes, a bare @ is -22, and on Darwin every @ path is -95. A file whose name starts with @ is spelled ./@name. A bind never replaces a file. Closing a listener does not unlink its file: unlinkSync it when the server stops, or let the next start's NET_UNIX_UNLINK_STALE clear it.

A failure after the bind closes the socket and unlinks the file it made. A connect needs write permission on the file and search permission on every directory above it, which is the real boundary: put the socket in a directory only the users who may connect can reach. With NET_UNIX_UNLINK_STALE, the runtime connects to an existing socket file and unlinks it only on a refusal; between the probe and the unlink another process can bind the path, so the directory must be the program's own. Refused at compile time on wasm32 and the WASI profile (NL2404). Not callable in a scope() task or a parallel body. Capability: net.

const unixListen: (
  path: string,
  backlog: i32,
  flags: i32,
) => i32
pathstringrequired

the socket file, or @name; it must be a string.

backlogi32required

the kernel's queue of unaccepted connections.

flagsi32required

0, or NET_UNIX_UNLINK_STALE.

returnsi32

the listener's descriptor, or a negative errno: a path that exists is -98, unless flags holds NET_UNIX_UNLINK_STALE and the file is a socket nothing listens on (a live listener, even with a full backlog, stays -98); -17 when that flag finds something that is not a socket, which is left alone; -95 on Darwin when that flag meets a socket file, which is left alone, since the probe cannot tell a dead file from a full backlog; -36 a path too long, -22 an empty path, a bare @, a NUL inside or any other flag bit.

unixListenMode

unixListen with the socket file's mode chosen, set between the bind and the listen so no connect gets in under a wider one. Not callable in a scope() task or a parallel body. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const unixListenMode: (
  path: string,
  backlog: i32,
  flags: i32,
  mode: i32,
) => i32
pathstringrequired

the socket file.

backlogi32required

the kernel's queue of unaccepted connections.

flagsi32required

0, or NET_UNIX_UNLINK_STALE.

modei32required

the file's mode, 0 to 0o777 and no other bits.

returnsi32

the listener's descriptor, or a negative errno; -22 for a mode outside that range or an @name, which has no file to give a mode to, and the refusals of unixListen.

unixSocketPair

Two connected sockets into fds[0] and fds[1], non-blocking and close-on-exec: a channel without a name for a child process or one side of a program. fds must be an i32[] and not readonly. Not callable in a scope() task or a parallel body. A call that writes fds is refused in a scope's region on an array a task may read, as fill is. Refused at compile time on wasm32 and the WASI profile (NL2404). Capability: net.

const unixSocketPair: (kind: i32, fds: i32[]) => i32
kindi32required

NET_UNIX_STREAM or NET_UNIX_SEQPACKET (-95 on Darwin), which keeps each write one message so a read returns one message, never two run together.

fdsi32[]required

at least 2 slots, receiving the pair.

returnsi32

0; -22 another kind or an fds shorter than 2, before a socket exists.

unlinkSync

unlink(2): the name path removed, and a symbolic link itself rather than what it names. A directory is refused, not removed, with no fallback to rmdir. Never a panic. A wasm32 build refuses it. Capability: fs.write.

const unlinkSync: (path: string) => i32
pathstringrequired

the name to remove.

returnsi32

0, or a negative errno: -2 ENOENT for a missing path, -21 EISDIR on Linux or -1 EPERM where the kernel answers so, for a directory, -22 EINVAL for a NUL in path.

waitPid

Reap a child and answer a fresh two-element array (the language has no tuple). pid is a child's, or -1 for any child. After signalFd() a blocking wait never sees EINTR, because that handler is installed with SA_RESTART and the wait restarts, and it cannot be woken by SIGTERM either: a supervisor that must answer a signal while its children run reaps with flag 1 (WNOHANG) on each tick of a pollWait loop that also watches the signal descriptor, and stops its children with kill when readSignal answers.

No reading under Node, which throws, naming itself. A wasm32 build refuses it (NL2404), and a scope's task or a parallel body that calls it is refused as any shared write is. Also exported by nish:process. Capability: process.spawn.

const waitPid: (pid: i32, flags: i32) => i32[]
pidi32required

the child to wait for, or -1.

flagsi32required

0, or 1 for WNOHANG; any other bit is [-22, 0], as is a pid that is neither -1 nor positive.

returnsi32[]

[pid, status], the status as spawnSync answers it (the exit code, or 128 + n when signal n ended it); under WNOHANG [0, 0] means a child remains and none has exited; a failure is [-errno, 0]: [-10, 0] (ECHILD) with no child to wait for, [-4, 0] (EINTR) when a signal interrupted the wait.

waitStdin

Wait for stdin to be readable, or timeoutMs milliseconds to pass: the frame clock of a terminal program, which costs nothing when a key arrives early. Its end and an error count as readable, so the read after it answers at once, with 0 or a negative errno that is not -11, which a loop treats as the end.

A signal that ends the wait early gives false, except a Ctrl-Z and fg once setRawMode(true) has caught SIGTSTP, after which the wait goes on for what is left of the timeout; before raw mode the system's default stop decides (Linux goes on with what is left, Darwin ends the wait). Not willreturn. Under --profile wasi it waits at least 10 ms; under Node it throws; refused at compile time on a freestanding wasm32 target. Capability: tty.

const waitStdin: (timeoutMs: i32) => boolean
timeoutMsi32required

the most milliseconds to wait; negative: forever.

returnsboolean

true when it is readable, false when the time passed or a signal ended the wait.

wallClockNanos

CLOCK_REALTIME in nanoseconds since 1970-01-01 UTC, for dating an event: Date.now's clock at a nanosecond's grain and as an i64. It can go backwards when the system time is set, so a duration is monotonicNanos's job, not this one's. Not refused on wasm32. Also exported by nish:process. Capability: clock.

const wallClockNanos: () => i64
returnsi64

nanoseconds since the epoch.

wrappingAdd

a + b wrapped to the operands' width, i32 or i64: defined for every pair, where the operator + panics on signed overflow. The two operands are one type, which is also the answer: `wrappingMul` takes i32 or i64 operands (convert with toI32 or toI64), got u32 is NL2454 (the unsigned words already wrap), and two widths are `wrappingAdd` needs every operand of one type, got i32 and i64 (NL2400). A bare literal takes the other operand's type, wherever it stands. wrappingAdd(2147483647, 1) is -2147483648.

In a module constant's initialiser the call folds, wrapping, where 2147483647 + 1 is refused; it is the one call such an initialiser may make. It is not a site under --deny-panics, as it cannot panic. Under Node the runtime shim computes (a + b) | 0 on an i32 and BigInt.asIntN(64, ...) on the BigInt an i64 is there. Capability: unsafe.

const wrappingAdd: <T extends i32 | i64>(a: T, b: T) => T
aTrequired

one operand.

bTrequired

the other, of the same type.

returnsT

the low bits of the sum.

wrappingMul

a * b wrapped to the operands' width, by wrappingAdd's rules: wrappingMul(INT64_MAX, 2) is -2. Under Node the runtime shim computes Math.imul on an i32. Capability: unsafe.

const wrappingMul: <T extends i32 | i64>(a: T, b: T) => T
aTrequired

one operand.

bTrequired

the other, of the same type.

returnsT

the low bits of the product.

wrappingSub

a - b wrapped to the operands' width, by wrappingAdd's rules, so wrappingSub(0, x) is a negation that wraps. Under Node the runtime shim computes (a - b) | 0 on an i32. Capability: unsafe.

const wrappingSub: <T extends i32 | i64>(a: T, b: T) => T
aTrequired

the minuend.

bTrequired

the subtrahend, of the same type.

returnsT

the low bits of the difference.

write

s to stdout with no trailing newline and no conversion (a string only); statement position. A native string is {len, bytes}, never validated as UTF-8, and its len bytes leave as they are, so a string built by String.fromBytes from any bytes, all 256 values included, leaves exactly as it came in. That route is native-only: under the prelude String.fromBytes makes each byte one UTF-16 unit, which leaves as UTF-8, so a byte above 127 becomes two, and under --emit-ts the bytes decode as UTF-8 and a byte that is not UTF-8 becomes U+FFFD. writeBytes is the route for bytes that are not text. Also exported by nish:io. Capability: none.

const write: (s: string) => void
sstringrequired

the text written.

writeBytes

bytes[off .. off + len) to stdout, every byte as it is, with no conversion — the one way to send bytes that are not text, a byte of 0x80 or above or a zero byte included. A loop of write(2) sends them all, retried on an interrupted call. A pipe whose reader has gone raises SIGPIPE natively, as it does for write, where Node answers -32 EPIPE.

off and len are netWrite's buffer range, checked once after the arguments are evaluated: 0 <= off, 0 <= len and off + len <= bytes.length, and anything else panics, as dst.set does, with slice out of range: [off, off+len) of length n and exits 1. The shape is netWrite's with the descriptor fixed at 1. Under Node the range is the same check and the bytes go to fs.writeSync(1, ...). A wasm32 build has no stdout to reach and refuses it. Also exported by nish:io. Capability: none.

const writeBytes: (
  bytes: readonly u8[],
  off: i32,
  len: i32,
) => i32
bytesreadonly u8[]required

the buffer to send.

offi32required

the first byte sent; 0 <= off.

leni32required

how many bytes; 0 <= len and off + len <= bytes.length.

returnsi32

len, or a negative errno if the stream refuses them (-9 EBADF on a closed descriptor), never a panic.

writeError

s to stderr, likewise: no trailing newline, no conversion, statement position, the same byte-for-byte rule for a string. Also exported by nish:io. Capability: none.

const writeError: (s: string) => void
sstringrequired

the text written.

writeFileBytesSync

The file's contents replaced by bytes, created at 0644 when missing, the array's bytes written as they are: readFileBytesSync's other half. A symbolic link as the last component is refused, as for writeFileSync. Where writeFileSync exits, this answers, so a program can report the failure and carry on. Never an exit and never a panic. A wasm32 build refuses it. Capability: fs.write.

const writeFileBytesSync: (
  path: string,
  bytes: readonly u8[],
) => i32
pathstringrequired

the file to write.

bytesreadonly u8[]required

its new contents.

returnsi32

the byte count (bytes.length), or a negative errno: -2 ENOENT for a missing directory, -13 EACCES, -21 EISDIR, -40 ELOOP for the refused link, -22 EINVAL for a NUL in path.

writeFileSync

The file's contents replaced by data, created at 0644 when missing; statement position. A symbolic link as the last component of the path is refused rather than followed, natively and under Node alike (a Node writeFileSync would follow it), and a path that cannot be written prints nish: cannot write <path> and exits 1. The string's bytes are written as they are. Capability: fs.write.

const writeFileSync: (path: string, data: string) => void
pathstringrequired

the file to write.

datastringrequired

its new contents.

writeFileSyncMode

writeFileSync with an explicit mode: the file is exactly mode (0o600 for a secret) before a byte of data is in it, whatever the umask or a file already there had. The open passes mode and an fchmod(2) sets it before the first byte is written, so the umask cannot widen it, a file that already existed at 0644 is narrowed before it holds the new contents, and no reader that opens it afterwards finds the secret under the old mode.

A descriptor opened before, while the file was wider, is not revoked and still reads what is written. A symbolic link at the path is refused (-40), its target untouched. The file is truncated and written in place, so a crash or a failed write leaves it empty or partial, and a file this process may write but does not own is emptied before the mode change answers -1 (EPERM).

For a file that must be the old one or the new one, write a temporary name beside the target with this and move it over with renameSync. Never an exit and never a panic. A wasm32 build refuses it, and a WASI build answers -ENOSYS, as WASI has no file modes to set. Capability: fs.write.

const writeFileSyncMode: (
  path: string,
  data: string,
  mode: i32,
) => i32
pathstringrequired

the file to write.

datastringrequired

its new contents.

modei32required

the file's mode, 0..0o777.

returnsi32

the byte count, or a negative errno: -22 for a mode outside 0..0o777, the setuid, setgid and sticky bits included (they are refused, not applied), or a NUL in path; -2 ENOENT for a missing directory; -13 EACCES; -40 for the refused link.

Interfaces

Array

An array. Int32Array, Float32Array, Float64Array and BigInt64Array name i32[], f32[], f64[] and i64[], the same type with no second layout, but a receiver spelled with one of the four refuses push and pop (NL2415), because a typed array in TypeScript has a fixed length and a call to either is a TypeError there: "push is not a method of Float64Array, whose length is fixed: declare it f64[] to push and pop". Every other array operation is unchanged, and a Float64Array is an f64[] wherever one is expected.

The refusal follows the spelling the program wrote, carried by: new X(n); an identifier annotated with the name (directly, as the one member of X | null, or through a type alias) or unannotated and initialised with such a receiver; a field declared with the name; a call whose callee declares it as its return type; a call of a generic function whose return type is a type parameter that an argument binds to such a receiver; a value read out of a Map whose value type is spelled with a name; an element of an array spelled with a name; and a ternary or ?? either of whose operands carries it.

A member of a generic class instantiated at one of the names does not carry it, and a typed array that flows into a binding spelled T[] may be pushed there. A numeric literal argument to push, indexOf or fill takes the element type, so wide.push(3) on an i64[] pushes an i64 three. An unknown method is refused with the supported list: "Unknown method shift on i32[]"; there is no shift, find or toString on an array.

interface Array<T>
Member
length: number Gets or sets the length of the array. This is a number one higher than the highest index in the array.
every(predicate: (value: T, index: number) => boolean): boolean Whether predicate answers true for every element, stopping at the first that does not, as Array.prototype.every does; an empty array answers true. The callback rules are map's. Capability: none.
fill(value: T, start?: number, end?: number): this Store value into every slot of [start, end), each end relative (a negative one counts back from the length) and then clamped into [0, a.length], as TypedArray.prototype.fill's are, so no range is out of range, a reversed range fills nothing, and fill never panics. Arrays of numbers only, of any width and ranged integers included (a ranged element checks value once, before the fill); on any other array it is refused: "set copies bytes, so it needs an array whose elements are numbers (u8[], i32[], f64[], ...), got string[]" (NL2395).

value is the element type ("fill expects u8 (the element type of u8[]), got string"), one to three arguments are taken (NL2398), and each end is a number. It is a statement: its answer cannot be used as a value, and JavaScript's answer is the array the program already holds.

A float end converts as JavaScript's ToIntegerOrInfinity does: NaN is 0, a fraction truncates toward zero (2.7 is 2, -0.5 is 0), and an infinity or a value past the i64 range saturates, then clamps, so in f64 mode a.fill(v, 0, 1 / 0) fills all of it. An unsigned end is never negative, whatever its width: a u64 of 2^63 or more as a start fills nothing and as an end fills to the length. Natively a u8[] fill is one memset.

Under Node it is Array.prototype.fill, which has TypedArray.prototype.fill's meaning for every argument Nish admits, except that an i64 or u64 end is a bigint there and throws a TypeError, as all 64-bit arithmetic does. A readonly T[] refuses it: "Cannot fill through readonly u8[] (declare it u8[] to write through it)". Capability: none.
filter(predicate: (value: T, index: number) => boolean): T[] A new array of the elements for which predicate answers true, in order, as Array.prototype.filter gives. The predicate answers a boolean and takes the element, or the element and its index, under the callback rules of map. Capability: none.
findIndex(predicate: (value: T, index: number) => boolean): number The index of the first element for which predicate answers true, or -1, as Array.prototype.findIndex gives. The callback rules are map's. There is no find: TypeScript types its answer T | undefined and Nish has no undefined, so xs.find(...) is refused (NL2697) and points here. Capability: none.
indexOf(searchElement: T, fromIndex?: number): number The first index whose element is === searchElement: strings by content, classes, interfaces and arrays by identity, floats by == on the number (so a NaN element is never found, as in JavaScript). One argument; an argument of another type than the element is refused. Capability: none.
join(separator?: string): string The elements joined by separator. string[] only: "join requires string[], got i32[]", because converting an element would allocate once per element. One pass sums the lengths, then one allocation holds the result. Like a concatenation, the result is held to 2^31 − 1 bytes: a longer one fails as an allocation does, nish: out of memory and exit 1, before anything is allocated. Capability: none.
map<U>(callbackfn: (value: T, index: number) => U): U[] A new array of callbackfn(element) for each element, in order, as Array.prototype.map gives. The callback takes the element, or the element and its index; a third parameter (JavaScript's array argument) is refused (NL2698), as is a second argument to map itself. It is a top-level function or an arrow reading only const locals and parameters, and the call compiles to a loop that calls it directly (std/array's map). Capability: none.
pop(): T | undefined Remove the last element. An empty array panics and exits 1 (index out of range: 0 >= 0): there is no undefined to return, so the answer is T in Nish. Behind a test that the array holds an element, such as if (a.length > 0), the check is proven away. The capacity is untouched, so the next push reuses the storage. Takes no argument. Capability: none.
push(...items: T[]): number Append one element, growing the capacity by doubling (4 from an empty array). An array never grows past 2^31 − 1 elements, in either number mode: the push that would fails as an allocation does, nish: out of memory and exit 1. An element of the wrong type is refused: "Cannot push string onto i32[]". A readonly T[] refuses it under its own name. Capability: none.
set(source: readonly T[], offset?: number): void Copy every element of source into this array from offset on, with TypedArray.prototype.set's meaning. Arrays of numbers only, of any width and ranged integers included, and source has this array's element type (a readonly array may be the source, since it is only read); another element type is refused: "set copies from an array of the receiver's element type, so it expects u8[], got i32[]" (NL2396), and a non-number receiver as for fill (NL2395). One or two arguments (NL2397). It is a statement: "set returns void and can only be used as a statement".

The range written is checked: 0 <= offset and offset + source.length <= a.length, or the program panics with slice out of range: [offset, offset + src.length) of length a.length and exits 1, the message s.slice gives; a range that ends exactly at a.length, and an empty source at a.length, are in range, where JavaScript throws a RangeError for exactly these offsets. An overlapping source (a.set(a), or two headers over one buffer from a C host) is copied as if it were read first.

A float offset converts as for fill's ends (NaN is 0, a fraction truncates, an infinity or a value past the i64 range saturates), and a saturated offset fails the range check with the saturated value in the message, for example slice out of range: [9223372036854775807, -9223372036854775808) of length 4 for 1e300. An unsigned offset is never negative: a u64 of 2^63 or more panics, printed signed. A readonly T[] refuses it: "Cannot set through readonly u8[] (declare it u8[] to write through it)".

Under Node, runtime/nish.mjs adds set to Array.prototype with the copy-first semantics and the native panic; a TypeScript host without it has no set on a plain array, and an i64 or u64 offset is a bigint there and throws a TypeError. Capability: none.
slice(start?: number, end?: number): T[] A copy of the elements from start up to end, in a new array, with string slice's rule: the range must satisfy 0 <= start <= end <= length, and anything else panics with slice out of range: [start, end) of length n and exits 1, where JavaScript counts a negative index back from the length and clamps the rest. start is 0 and end the length by default; a third argument is refused (NL2699). Under Node the prelude's sliceArray applies the same check. Capability: none.
some(predicate: (value: T, index: number) => boolean): boolean Whether predicate answers true for some element, stopping at the first that does, as Array.prototype.some does; an empty array answers false. The callback rules are map's. Capability: none.
sort(compareFn?: (a: T, b: T) => number): this Sort in place, stably, as Array.prototype.sort does: element for element Node's order for any consistent comparator. The comparator is required (NL2620: a.sort() compares as strings in JavaScript and is refused, "sort needs a comparator: write xs.sort((a, b) => a - b)") and is the one argument (NL2619: "sort takes one comparator"); only "positive or not" is read of its answer, so -0 and NaN count as zero. A readonly T[] ("Cannot sort through readonly") and process.argv ("process.argv is read-only") are refused.

The comparator is a compile-time function argument: a top-level function, or an arrow reading only the const locals and parameters of the function it is written in; an arrow reading a let is refused. The sort costs one scratch array of n elements, released before it returns. (a, b) => a - b is checked arithmetic on i32 elements: two a full range apart ([2147483647, -1]) panic with attempt to subtract with overflow, where (a, b) => (a > b ? 1 : a < b ? -1 : 0) cannot overflow.

Where JavaScript leaves the order to the implementation, so does Nish: an array holding NaN under (a, b) => a - b, or a comparator that is not a consistent order, comes out a permutation of its elements but not necessarily Node's permutation; give NaN a place of its own in the comparator to agree. Under Node and --emit-ts the call is the platform's own Array.prototype.sort. Capability: none.

CPtr

CPtr: the address a declare function hands back, opaque and eight bytes wide (i8* in the IR). It is C's, not arena memory, and its lifetime is the C library's business. docs/LANGUAGE.md has the rules — it may be written in a declare function signature and on a local that holds one, compared with null or with another CPtr, assigned, and passed back to C, and that is all.

A field, an array element, a Result arm, a type argument, and the parameters or return type of a function the program defines are each refused (`CPtr` cannot be ...: a foreign pointer may only appear in a `declare function` signature or on a local bound to one). There is no arithmetic (p + 1), no index (Cannot index a value of type CPtr), no dereference and no member. A CPtr | null reaches C only as the literal null or a pointer narrowed with !== null (NL2539). readCString from nish:unsafe copies the string at one.

An empty interface with a private brand rather than unknown or a type alias: tsc has to refuse the arithmetic and the dereference nish refuses, and it has to refuse assigning any other value to one. The brand is what makes it nominal, so a {} does not satisfy it; the name is never written, so the declaration costs a reader nothing.

interface CPtr
Member
readonly __nishForeignPointer: unique symbol The private brand that makes CPtr nominal. Not a field: nothing reads or writes it.

Console

The two output streams, with Nish's one-argument signatures. Numbers print as JavaScript's String(x): exact decimal for i32/i64, shortest round-trip digits for f64 (0.1, 1e+21, 1e-7, NaN, Infinity, -0 as 0); booleans print true/false.

interface Console
Member
error(x: string | number | boolean): void The same, on stderr — the stream a compiler's diagnostics belong on. Identical rules and identical messages under its own name. Capability: none.
log(x: string | number | boolean): void Writes x and a newline to stdout with one write(2); statement position only (as a value it is refused); exactly one argument. Arrays and objects are rejected: it accepts a string, a number or a boolean. In a parallel body it is refused, as output is a write the caller can see. Capability: none.

DateConstructor

Date, merged into the DateConstructor lib.es2022 declares. Nish has no Date object: Date.now() is its one member, and new Date(), Date(), Date.parse, Date.UTC, any other member, and Date or Date.now used as a value are each refused: "new Date() is refused: Nish has no Date object; the one Date member is Date.now(), the wall clock in milliseconds" (NL2401).

interface DateConstructor
Member
now(): number The wall clock, CLOCK_REALTIME, in whole milliseconds since 1970-01-01 UTC, as JavaScript answers it: the milliseconds are counted as integers and then converted, so the value is exact and a time before 1970 floors. An f64 in both number modes, because an i32 of milliseconds overflowed in January 1970. It can go backwards when the clock is corrected, so an interval is monotonicNanos's job, not this one's. A wasm32 build has no operating system to ask, and refuses it. Capability: clock.

Disposable

A value using may bind: one whose [Symbol.dispose]() ends its scope.

interface Disposable
Member
[Symbol.dispose](): void Ends the value's scope. The compiler runs it on every exit from the using block; a call by name is refused.

Map

An insertion-ordered map with SameValueZero keys (-0 is +0 and NaN is NaN), a builtin with no import. A key is a string, a number of any width in either mode (f32 and f64 included), a boolean, an enum or a class instance (by identity); not an interface, an array, a nullable or a Result: "Point cannot be the key type of Map<Point, i32>: a key is hashed and compared by value, or by identity for a class instance".

A -0 key is stored as +0 by every insert path, so a walk over keys() yields +0. A value is anything but void and an interface, whose record would be copied into the table rather than shared: "Point cannot be the value type of Map<string, Point>".

new Map<K, V>() takes no arguments ("new Map<string, i32> takes no arguments in this version"); the type arguments are written out, except that a const or let annotated with the type takes them from the annotation, and a bare new Map() is refused: "Map is generic: it must be written with its type arguments". The members are JavaScript's, less entries (there is no destructuring); forEach(f) is the for...of walk with f, an arrow or a top-level function of the value and optionally the key, inlined; anything else is refused as if it did not exist. set answers the receiver, so calls chain.

keys() and values() are iterators, admitted only as the iterable of a for...of: stored, passed, returned or dropped, they are refused (NL2372, NL2373, NL2374, NL2358), and for (const e of m) needs entries() (NL2375). The walk visits entries in insertion order, skips a deleted key not yet reached, visits a key set during the walk later in the same walk, and keeps a re-set key in its place, as JavaScript's does.

At most 2^24 − 1 entries (one fewer than Node's 2^24); one more panics with Map maximum size exceeded, after first compacting away dead entries (not while a loop walks the table). String keys are hashed with SipHash-1-3 under a per-process random key drawn from the system's entropy source before main, and an integer, boolean or enum key under a per-process random multiply-add-shift; if the entropy source fails the program panics before main: "Map: the system's entropy source failed".

A float key and a class instance key are not keyed, so a program keying a table by floats a peer chose converts them to a string or a scaled integer first. On wasm32 the key comes from WASI's random_get, and a reactor module is keyed only once its host calls _initialize. A pair of i32s is one i64 key: (toI64(hi) << toI64(32)) | toI64(toU32(lo)). nish/map adds reserve(m, n) and getOrInsert(m, k, v), which JavaScript's Map has no call for. A module that declares or imports its own Map gets no implicit import.

interface Map<K, V>
Member
readonly size: number
clear(): void Remove every entry. Capability: none.
delete(key: K): boolean Remove key's entry. Setting the key again appends a new entry at the end. Capability: none.
get(key: K): V | undefined The value under key, one probe. The V | undefined is a maybe, admitted only as the initialiser of a const (unannotated, or annotated with the maybe type), the left of ??, or an operand of === undefined or !== undefined. A const so bound reads as V in the region a test proves it present (if (a === undefined) return included), and nowhere else.

Any other place is refused with a message naming it: a let (NL2361), an argument (NL2362), a return (NL2363), a field (NL2364), an array element (NL2365), a template literal hole (NL2366), an operand of another operator (NL2367), the default of another ?? (NL2371), a const annotated V (NL2368), or anywhere else (NL2369). When V is nullable, ?? replaces a stored null as well. get is called, never read as a value. Capability: none.
has(key: K): boolean Whether key is present. One probe. Capability: none.
set(key: K, value: V): this Put value under key, replacing any value there. A new key is appended past the end of the order; a key already there keeps its place. Calls chain. Capability: none.

Math

Math. The f64-only functions (sqrt, floor, ceil, trunc, sin, cos, tan, exp, log, pow, round, atan2, hypot) refuse i32 and i64 arguments (and an f32 one): Math.sqrt(x) on an i32 is "Math.sqrt requires an f64 argument, got i32 (use --number-mode f64 or toF64(x))". number in i32 mode is an i32, so write Math.sqrt(toF64(n)) or use f64 mode. A numeric literal argument is typed f64 by context (Math.sqrt(2) works in both modes); a literal operand of Math.min or Math.max takes the other operand's type (Math.max(x, 0)). Math.abs, Math.min, Math.max and Math.sign also work on an f32. Math.PI and Math.E are available in both number modes.

interface Math
Member
readonly E: number The mathematical constant e. This is Euler's number, the base of natural logarithms.
readonly PI: number Pi. This is the ratio of the circumference of a circle to its diameter.
abs(x: number): number The magnitude of x, for any numeric type, in that type: wrapping for INT_MIN (Math.abs(-2147483648) answers itself), and on an unsigned type the value itself. Capability: none.
atan2(y: number, x: number): number The angle of the point (x, y), with ECMAScript's special cases (atan2(0, -0) is π, atan2(-0, -0) is −π). An f32 argument is refused: "Math.atan2 requires an f64 argument, got f32 (use --number-mode f64 or toF64(x))". Capability: none.
ceil(x: number): number The smallest integer not below x. Runs on the same two paths as floor, with the same bits on either. Capability: none.
clz32(x: number): number The leading zero bits of x's 32 bits, JavaScript's answer (an i32 and a u32 are the bits ToUint32 gives), so 0 answers 32. The answer is ranged, so 31 - Math.clz32(word & (0 - word)), the index of a word's lowest set bit, needs no overflow check. Any other operand type is refused rather than converted: "Math.clz32 expects an i32 or a u32, got f64 (convert with toI32 or toU32)". Capability: none.
cos(x: number): number The cosine. Capability: none.
exp(x: number): number e to the power x. Capability: none.
floor(x: number): number The largest integer not above x. In an x86-64 module that is not a wasm build, the runtime runs SSE4.1's roundsd on a CPU that has it and libm's routine on one that does not, chosen once before main; the answers are the same bits on either path, and NISH_SIMD=scalar pins libm. Capability: none.
hypot(...values: number[]): number The length of (x, y), with ECMAScript's special cases (hypot(Infinity, NaN) is Infinity). Exactly two arguments, not JavaScript's any number: a third is refused with "Math.hypot expects exactly 2 arguments, got 3". Capability: none.
imul(x: number, y: number): number The low 32 bits of the product, read signed, with no overflow check (Math.imul(0x7fffffff, 2) is -2), which is JavaScript's answer for any operands an i32 or a u32 holds. Any other operand type is refused rather than converted: "Math.imul expects an i32 or a u32, got f64 (convert with toI32 or toU32)". Capability: none.
log(x: number): number The natural logarithm. Capability: none.
max(...values: number[]): number The larger of exactly two operands of one numeric type, in that type: a signed integer compares signed, an unsigned one unsigned. On floats, JavaScript's answer: a NaN operand gives NaN and -0 is below +0 (Math.max(-0, 0) is 0). A count other than two is refused, as for min. A numeric literal operand takes the other operand's type. Capability: none.
min(...values: number[]): number The smaller of exactly two operands of one numeric type, in that type: a signed integer compares signed, an unsigned one unsigned. On floats, JavaScript's answer: a NaN operand gives NaN and -0 is below +0 (Math.min(0, -0) is -0). One operand is refused: "Math.min expects exactly 2 arguments, got 1". A numeric literal operand takes the other operand's type. Capability: none.
pow(x: number, y: number): number x to the power y, ECMAScript's answer where it and C99 differ: pow(x, NaN) and pow(±1, ±Infinity) are NaN (C gives 1); pow(x, ±0) is 1, pow(NaN, 0) is 1; every other special case agrees with C. Capability: none.
random(): number xorshift64* in the runtime, seeded from time and pid. Capability: entropy.
round(x: number): number JavaScript's round-half-up, with x's sign kept: 2.5 -> 3, -2.5 -> -2, 0.49999999999999994 -> 0, and a value in [-0.5, 0) or -0 itself -> -0 (Math.round(-0.3) is -0, in Node too); NaN -> NaN. Capability: none.
sign(x: number): number -1, 0 or 1 in x's own type (a ranged x answers its base type); a float's -0 and NaN come back as JavaScript gives them, and an unsigned x answers 0 or 1. A non-number is refused: "Math.sign expects a number, got string". Capability: none.
sin(x: number): number The sine. Capability: none.
sqrt(x: number): number The square root. Capability: none.
tan(x: number): number The tangent, fdlibm's, compiled into the module so that no target calls libm: exact near every multiple of π/2 and within one ulp. Capability: none.
trunc(x: number): number x with its fraction dropped. Runs on the same two paths as floor, with the same bits on either. Capability: none.

NumberConstructor

Number(value): value as an f64, in both number modes. Nish has no new Number and no member of Number; the call is the conversion, merged into the NumberConstructor lib.es2022 declares.

A string is parsed with JavaScript's Number(s) rules: ASCII whitespace ( \t\n\v\f\r, not the Unicode spaces JavaScript also trims) is trimmed on both sides, then the whole string must be one literal, so Number("") and Number(" ") are 0, Number(" 7.5 ") is 7.5, and Number("12px"), Number("1e") and Number("nan") are NaN. Number("0x1A") is 26, as in JavaScript, and a hex float such as 0x1p3 is also accepted, which JavaScript rejects; the 0b and 0o prefixes are NaN, which JavaScript reads. Under --deterministic a 0x string reads as --emit-ts reads it on every target: a hex float is NaN, and a hex integer is correctly rounded whatever the C library.

An i32 or an i64 converts as toF64 does, a boolean is 1 or 0, and an f64 is itself. A numeric literal argument is typed f64 (Number(2.5) works in i32 mode). Exactly one argument; anything other than a string, a number or a boolean is refused: "Number expects a string, number, or boolean, got i32[]". Capability: none.

interface NumberConstructor

value as an f64, by the rules on NumberConstructor above. Capability: none.

NumberConstructor(value?: any): number
valueany

a string, an i32, an i64, an f64 or a boolean; nish requires it, though lib's signature marks it optional.

returnsnumber

an f64, in both number modes.

Process

The running process: its exit, its command line and its host.

interface Process
Member
readonly arch: string The architecture: "x64", "arm64", or "unknown". Like platform, it names the target of the build, cannot be assigned to and is not callable. Capability: none.
readonly argv: string[] The command line; argv[0] is the program path, as in C — one index earlier than Node's, which puts node first. Each argument is the bytes the operating system passed, as a UTF-8 string. Read-only: an assignment to it or an element, op=, ++, -- and push are refused. It is an ordinary string[] (length, a[i], for...of, passing it on) built once before the program runs and living outside the arena, and it needs a main entry point: a program without one, such as a wasm or N-API library, refuses every use with `process.argv` requires a `main` entry point. Under the wasi profile the WASI host supplies the arguments. Capability: none.
readonly platform: string The operating system the program runs on, spelled as Node spells it: "linux", "darwin", or "unknown" for anything the compiler has no target triple for (every WASI build). It is settled when the runtime is compiled, so a cross build reports the target, and it cannot be assigned to. It carries no entry-point rule, so a wasm or N-API library may read it. Capability: none.
exit(code: i32): never Ends the program with code, through libc's exit(code), which flushes stdio; the arena is abandoned to the operating system. Statement position, and a terminator: never is how TypeScript spells that, so a function ending in process.exit(c) satisfies its return type in tsc as it does in nish, and code after it is Unreachable code after process.exit. A numeric literal code is an i32 in either number mode. In a parallel body it is refused, as output is. Capability: exit.

ReadonlyArray

readonly T[], or ReadonlyArray<T> under the other spelling: the same array, which may not be written through. It is the same header, the same pointer and the same layout as T[]; the annotation is a promise the checker keeps, and a --emit-header prototype spells such a parameter const nish_array *.

Everything that reads works (length, a[i], for...of, indexOf, join, map, filter, some, every, findIndex, slice, passing it on to another readonly T[]); every write is refused under its own name, an element store ("Cannot assign to an element of readonly i32[] (declare it i32[] to write through it)"), push, pop, set, fill and sort included. A T[] widens into a readonly T[], and never back: "Argument 1 of fill: expected i32[], got readonly i32[]". It is shallow, as TypeScript's is: the element of a readonly T[][] is a mutable T[].

It is a type, not a parameter modifier, so it is legal wherever an array type is (a class field, a return type, a const's annotation). readonly goes on an array type and nothing else: "readonly is only permitted on an array type, got i32". process.argv is read-only under a rule of its own.

interface ReadonlyArray<T>
Member
readonly length: number Gets the length of the array. This is a number one higher than the highest element defined in an array.
every(predicate: (value: T, index: number) => boolean): boolean Whether predicate answers true for every element, stopping at the first that does not, as Array.prototype.every does; an empty array answers true. The callback rules are map's. Capability: none.
filter(predicate: (value: T, index: number) => boolean): T[] A new array of the elements for which predicate answers true, in order, as Array.prototype.filter gives. The predicate answers a boolean and takes the element, or the element and its index, under the callback rules of map. Capability: none.
findIndex(predicate: (value: T, index: number) => boolean): number The index of the first element for which predicate answers true, or -1, as Array.prototype.findIndex gives. The callback rules are map's. There is no find: TypeScript types its answer T | undefined and Nish has no undefined, so xs.find(...) is refused (NL2697) and points here. Capability: none.
indexOf(searchElement: T, fromIndex?: number): number The first index whose element is === searchElement, as on T[]: one argument, strings by content, classes, interfaces and arrays by identity, and a NaN element is never found. Capability: none.
join(separator?: string): string The elements joined by separator, as on string[]: string[] only, and the result is held to 2^31 − 1 bytes. Capability: none.
map<U>(callbackfn: (value: T, index: number) => U): U[] A new array of callbackfn(element) for each element, in order, as Array.prototype.map gives. The callback takes the element, or the element and its index; a third parameter (JavaScript's array argument) is refused (NL2698), as is a second argument to map itself. It is a top-level function or an arrow reading only const locals and parameters, and the call compiles to a loop that calls it directly (std/array's map). Capability: none.
slice(start?: number, end?: number): T[] A copy of the elements from start up to end, in a new array, with string slice's rule: the range must satisfy 0 <= start <= end <= length, and anything else panics with slice out of range: [start, end) of length n and exits 1, where JavaScript counts a negative index back from the length and clamps the rest. start is 0 and end the length by default; a third argument is refused (NL2699). Under Node the prelude's sliceArray applies the same check. Capability: none.
some(predicate: (value: T, index: number) => boolean): boolean Whether predicate answers true for some element, stopping at the first that does, as Array.prototype.some does; an empty array answers false. The callback rules are map's. Capability: none.

ResultMethods

The methods every Result carries. r.ok is the same bit as a plain boolean, r.value reads only where the checker proved isOk() and r.error only where it proved isErr(). A narrowing applies to a variable, not a property path, ends at any assignment to that variable, and holds in if, &&, ||, ! and the ternary. There is no unwrap() (expect insists on a reason) and no map or andThen. Capability: none.

interface ResultMethods<T, E>
Member
expect(message: string): T The success payload, or message on stderr and exit 1: the failure arm ends the program, the same ending panic has. Capability: none.
isErr(): this is ResultErr<E> & ResultMethods<T, E> True when this is the failure arm; narrows r the other way. Capability: none.
isOk(): this is ResultOk<T> & ResultMethods<T, E> True when this is the success arm; narrows r where it is a condition. Capability: none.
orReturn(): T The success payload, or an early return Err(error) from the enclosing function — Rust's ?. nish additionally requires that function to return a Result whose error arm accepts E, with no implicit error conversion (a mismatch is refused; convert by hand with if (r.isErr()) { return Err(...); }); tsc cannot check that. It is refused in a function that returns anything else, main returning i32 included. Capability: none.
unwrapOr(fallback: T): T The success payload, or fallback when this is the failure arm. In f64 mode a numeric literal fallback takes no type from the Result, so write toI32(...) or the like. Capability: none.

Set

An insertion-ordered set with SameValueZero members, a builtin with no import. A member is what a Map key may be (and -0 is stored as +0). new Set<T>() takes no arguments ("new Set<string> takes no arguments in this version"). keys() and values() are one walk, as JavaScript's are, admitted only as the iterable of a for...of, which also takes the set itself: for (const x of s). At most 2^24 − 1 members; one more panics with Set maximum size exceeded. Hashing, the entropy source and the walk's rules are Map's. add and has are one probe each, and if (!s.has(x)) { s.add(x); ... } with the add first in the branch asks about the member once.

interface Set<T>
Member
readonly size: number
add(value: T): this Add value; a member already there keeps its place. Calls chain. Capability: none.
clear(): void Remove every member. Capability: none.
delete(value: T): boolean Remove value. Adding it again appends it at the end of the order. Capability: none.
has(value: T): boolean Whether value is a member. One probe. Capability: none.

String

A string: UTF-8 bytes. Every offset is a byte offset, like length, so cutting a multi-byte character in half is possible and produces bytes that are not a valid string. Under Node a string is UTF-16, so an offset, a length or a code unit of text that is not ASCII differs there (NL8001 warns wherever such a number meets a fact not counted in bytes). An unknown method is refused with the supported list: "Unknown method codePointAt on string"; there is no charAt, toUpperCase or toString.

interface String
Member
readonly length: number Returns the length of a String object.
charCodeAt(index: number): number The byte at index, bounds-checked as a[i] is: out of range panics and exits 1, where JavaScript answers NaN, which number cannot hold. One argument. Under Node it is a UTF-16 code unit, so a byte above 127 differs (NL8001). Capability: none.
endsWith(searchString: string, endPosition?: number): boolean Whether searchString's bytes are a suffix; one longer than the string is false. One argument. Capability: none.
indexOf(searchString: string, position?: number): number The first byte offset at or after position at which searchString occurs. position is clamped into [0, s.length] first, as in JavaScript: a negative start searches from 0, a start past the end finds nothing, and the empty needle answers the clamped start, so s.indexOf("") is 0, s.indexOf("", 3) is 3 and s.indexOf("", 99) is s.length. A float start converts as JavaScript's ToIntegerOrInfinity does (a fraction truncates and NaN is 0), and an unsigned one is clamped from above only, so a u64 past 2^63 is past the end.

The search allocates nothing, so a loop at = s.indexOf(sub, at + sub.length) copies nothing. Under Node it is the same call to String.prototype.indexOf, whose answers differ only where every offset does, on text that is not ASCII (NL8001). Capability: none.
slice(start?: number, end?: number): string The same bytes, without the clamp: anything outside 0 <= start <= end <= s.length panics with slice out of range: [start, end) of length len and exits 1, where JavaScript counts a negative offset from the end and answers "" for a reversed pair. An in-range non-negative pair gives exactly what JavaScript's String.prototype.slice gives. A bound that is a negative literal, or that no proof places inside [0, length], is reported by NL8002. Capability: none.
startsWith(searchString: string, position?: number): boolean Whether searchString's bytes are a prefix. One argument. Capability: none.
substring(start: number, end?: number): string The bytes of [start, end). Both ends are clamped into [0, s.length] and then swapped into order, as in JavaScript, so s.substring(5, 0) is s.substring(0, 5) and a negative offset is 0. In a loop, a bound the compiler cannot place in [0, s.length] keeps the clamp and is reported by a performance warning; a test that reaches the call (if (a >= 0 && a <= s.length)) removes it, and slice has no clamp at all. Capability: none.

StringConstructor

String.fromBytes is Nish's, not JavaScript's, so it merges into the StringConstructor lib.es2022 declares. Under runtime/nish.mjs each byte becomes one UTF-16 unit, as String.fromCharCode's does, so ASCII agrees with a native build and a byte above 127 does not; under --emit-ts the bytes decode as UTF-8, and a sequence that is not UTF-8 becomes U+FFFD.

interface StringConstructor
Member
fromBytes(bytes: readonly u8[], start: number, end: number): string The bytes of bytes[start..end) as one string, with one range check, one allocation and one copy. The range is s.slice's, 0 <= start <= end <= bytes.length, checked once after all three arguments are evaluated; anything else panics with slice out of range: [start, end) of length len and exits 1. bytes is a u8[] reached any way an array is, readonly or not; a wider element or a u8[] | null is refused (NL2268). Both ends are required (NL2060) and are numbers (NL2058).

Nothing validates the bytes as UTF-8: a multi-byte character copied whole is that character, and a range that cuts one is bytes that are not a valid string. Natively the string's bytes are the array's, so write or writeFileSync sends any bytes back out unchanged; bytes that are not text go out through writeBytes and writeFileBytesSync, which agree on every host. Capability: none.
fromCharCode(...codes: number[]): string The one-byte string of c & 0xFF, the inverse of charCodeAt. One argument. A value above 127 makes a byte that is not valid UTF-8 on its own; nothing validates it. Under Node it is one UTF-16 unit, so ASCII agrees and a byte above 127 does not. Capability: none.

SymbolConstructor

The disposable protocol using reads: declared here so that a program using nish/threads's scope, a Mutex's lock, arena() or a handle class needs no "ESNext.Disposable" in its lib. nish takes using only for a scope(), a lock(), an arena() or a new of a handle class, and any other using initialiser is refused.

A handle class is a class with exactly one readonly CPtr or CPtr | null field: it owns the C resource the pointer names, and its [Symbol.dispose](): void is close(this.file); or const p = this.file; if (p !== null) { close(p); } for a declare function close of one parameter. using of a handle class closes it at every exit of its block, once, in the reverse of the order the declarators opened; a panic and process.exit do not close. --deny ffi refuses that using. Any other class that declares [Symbol.dispose] is refused.

The compiler emits the join, the release, the unlock or the close itself, and [Symbol.dispose] is never called by name.

interface SymbolConstructor
Member
readonly dispose: unique symbol The key of the method using calls when its block ends.

Objects

Arena

The arena the runtime allocates from, read. Both members are available in both number modes. Arena has no release and no reset: a call to either is an unknown builtin (NL2244). A parallel body or a task may not call Arena.mark or Arena.used, as each thread has an arena of its own. A function that calls Arena.mark in its own body never gets an automatic arena scope, so the position it reads is never moved under it by a scope it did not write.

const Arena: { ... }
Member
mark(): i64 The current bump address. It only reads the arena, but is recorded as a write, so a caller is never hoisted across an allocation, and a function that calls it is never the callee of a tail call whose scope release moved ahead of it. Capability: none.
used(): i64 Bytes bumped in the current chunk: the number the memory tests watch. Recorded as a write, as mark is. Capability: none.

crypto

The system's random source, with its one member.

const crypto: { ... }
Member
getRandomValues(bytes: u8[]): void Every byte of bytes from the kernel's CSPRNG (getrandom(2) on Linux, looping over EINTR and short reads; getentropy(3) in 256-byte chunks on macOS); at most 65,536 bytes a call. A u8[] only, where the Web API takes any integer typed array: the byte is the unit a key or a nonce is written in, and anything else is refused at compile time (NL2402). A statement, where the Web API also answers its argument, which the caller already holds. An empty array is filled with nothing.

The array is written, so a readonly u8[] is refused (and, inside a scope() region, an array a task may read). More than 65,536 bytes is a panic, crypto.getRandomValues: <n> bytes asked for, and one call fills at most 65536, exit 1. A source that fails is a panic too; nothing weaker is ever substituted. It is the source for a key. crypto has no other member (NL2403, for example crypto.randomUUID). Refused at compile time on wasm32 and the WASI profile (NL2404). Under Node the prelude fills a plain u8[] too and panics past 65,536 with the same words; without the prelude it takes only a typed array. Capability: entropy.

Types

HostHandle

HostHandle<"kind">: an object the page holds (a canvas, a GPU buffer, a node), passed to and from a host module's functions as the small integer the page's table keys it by (docs/LANGUAGE.md -> Host modules). It is an i32 in the wasm module. It may be stored anywhere a scalar goes and compared with === or !== against a handle of the same kind or the literal 0; a different kind, arithmetic, and a conversion to or from a number, an as included, are refused, and only a host function that returns one makes one.

In TypeScript a branded number or 0. tsc takes 0 (a handle's start, a field default, h === 0) and a handle of the same kind, and refuses any other number, a plain number and a handle of another kind, as nish does. It cannot refuse arithmetic on a handle or an as cast, which nish does; a handle stays assignable to number.

type HostHandle<K extends string> = number & { readonly __nishHostKind: K } | 0

Result

The outcome of an operation that can fail. T may be void for an operation with nothing to hand back, and then the Result carries no value; E may not be void, since a failure that says nothing is what panic is for. A Result is immutable once built, and Result<T, E> | null is refused. A Result may not be dropped: a call that answers one may not stand as an expression statement, and a local that holds one must be read.

type Result<T, E> = ResultOk<T> | ResultErr<E> & ResultMethods<T, E>

ResultErr

The failure arm.

type ResultErr<E> = unknown

ResultOk

The success arm of a Result, as the discriminant proves it.

type ResultOk<T> = unknown

f32

A 32-bit IEEE-754 float. It is never the lowering of number, and f32 + f64 is a type error; toF32 converts to it.

type f32 = number

f64

A 64-bit IEEE-754 float: number in f64 mode, and JavaScript's number. It is available in both number modes.

type f64 = number

i32

A 32-bit signed integer: number in i32 mode, and the type of an array index. Signed overflow panics (wrappingAdd, wrappingSub and wrappingMul from nish:unsafe wrap), and it never mixes implicitly with another width.

type i32 = number

i64

A 64-bit signed integer; it never mixes with an i32 without toI64 or toI32. It is never the lowering of number, a literal takes it only from context, signed overflow panics, and it crosses to JavaScript as a bigint.

type i64 = number

integer

An i32 the compiler knows lies in [Lo, Hi]. The bounds are numeric literal types, and tsc checks only that; the range itself is nish's. A ranged value is its base type wherever one is expected, and arithmetic on it that provably stays inside 32 bits needs no overflow check: Math.clz32 answers an integer<0, 32>, so 31 - Math.clz32(w) is checked by nothing (docs/LANGUAGE.md -> Types).

The bounds are two integer literals, a sign allowed, with Lo <= Hi and both in i32; integer<0, 0xFF> and integer<0, 255> are one type. Any other spelling is refused, as is a numeric literal type anywhere but a bound, a declare function signature that names a range, and new Array<integer<1, 9>>(n), whose zero fill lies outside the range. integer is reserved: no alias, enum, class, interface or function may take the name.

Entering a range is checked: an annotated initialiser, an assignment, an argument, a return, a field, an array element, an element store and push. The source must be an i32 or another ranged type (a u8 is not an integer<0, 255>; under --number-mode f64 a value enters through toI32). A literal outside the range is a compile error, Literal `12` is outside the range of integer<0, 9>; any other source is compared once and the program panics outside the range, printing value out of range: expected integer<0, 255> and exiting 1. The compiler writes no compare where it proves the entry, such as a loop counter below the bound. Under Node nothing is checked.

Leaving a range is free: every operator reads a ranged value as i32, so r + 1 is an i32. A const without an annotation keeps the range and a let widens to i32. The type is an i32 in the IR, in memory and at the C ABI, in both number modes.

type integer<Lo extends number, Hi extends number> = number

u16

A 16-bit unsigned integer. Its arithmetic wraps; toU16 converts to it.

type u16 = number

u32

A 32-bit unsigned integer: same width as i32, the other signedness, so u32 + i32 is a type error. Its arithmetic wraps; toU32 converts to it.

type u32 = number

u64

A 64-bit unsigned integer: same width as i64, the other signedness. Its arithmetic wraps, toU64 converts to it, and it crosses to JavaScript as a bigint.

type u64 = number

u8

An 8-bit unsigned integer, the element of a byte buffer (u8[]). Unsigned arithmetic wraps, in both number modes; toU8 converts to it.

type u8 = number

Constants

NET_​LISTEN_​RING

NET_LISTEN_RING: i32

tcpListenFlags flag 8: accept into io_uring slots instead of descriptors (WP63 S2, Linux). A connection accepted from such a listener is a slot handle, a number at or above 2^20 that netRead, netWrite, netWrite2, netClose, netLocalPort and the poll loop take as they take a descriptor, except that a slot is in one poll loop at a time (a second loop's pollAdd answers -17); netSetOption answers -95 and every other call -9. A program can so hold more connections than its descriptor limit. Where the kernel refuses rings the listener serves descriptors, and netRingState says why. Inert on Darwin. Capability: none.

NET_​SO_​KEEPALIVE

NET_SO_KEEPALIVE: i32

netSetOption id 3, SO_KEEPALIVE: value 1 probes an idle connection, 0 does not. Capability: none.

NET_​SO_​RCVBUF

NET_SO_RCVBUF: i32

netSetOption id 5, SO_RCVBUF: the receive buffer, value in bytes; Linux doubles the value it stores. Capability: none.

NET_​SO_​SNDBUF

NET_SO_SNDBUF: i32

netSetOption id 4, SO_SNDBUF: the send buffer, value in bytes; Linux doubles the value it stores. Capability: none.

NET_​TCP_​NODELAY

NET_TCP_NODELAY: i32

netSetOption id 1, TCP_NODELAY: value 1 sends a small write at once, 0 lets Nagle's algorithm batch it. Folds to its number in the IR; cannot be assigned and is not a module constant, so a module constant cannot be initialised from it. A local of the same name shadows the global spelling. Capability: none.

NET_​TCP_​QUICKACK

NET_TCP_QUICKACK: i32

netSetOption id 2, TCP_QUICKACK (Linux; -95 elsewhere): value 1 acknowledges at once, 0 lets the kernel delay the ACK. Linux does not keep quick-ACK mode: the kernel leaves it on its own, so a server that wants a mode sets it again after every response. Capability: none.

NET_​UNIX_​SEQPACKET

NET_UNIX_SEQPACKET: i32

unixSocketPair kind 2: each write one message (SOCK_SEQPACKET); -95 on Darwin. Capability: none.

NET_​UNIX_​STREAM

NET_UNIX_STREAM: i32

unixSocketPair kind 1: a byte stream, as a connection is. Capability: none.

NET_​UNIX_​UNLINK_​STALE

NET_UNIX_UNLINK_STALE: i32

unixListen flag 1: unlink a socket file nothing listens on, then bind. It clears only the file a server that died left. On Darwin it never unlinks one. It has the same value as NET_UNIX_STREAM, so the checker cannot tell one passed where another belongs: name the one the call takes. Capability: none.

console

console: Console

The program's console: log to stdout, error to stderr.

process

process: Process

The running process.