Result and error handling

A function that can fail says so in its return type, hands back a Result<T, E>, and the caller cannot get at the success value without first deciding what happens to the failure. There is no throw, no try, and no unwinding anywhere in the language (WP16; wp16-results.md).

const half = (n: i32): Result<i32, string> => {
  if (n % 2 !== 0) {
    return Err("odd");
  }
  return Ok(n / 2);
};

const quarter = (n: i32): Result<i32, string> => {
  const h = half(n).orReturn();   // Rust's `?`: propagate the error
  return half(h);
};

export const main = (): i32 => {
  const outcome = quarter(8);
  if (outcome.isErr()) {
    console.log(outcome.error);
    return 1;
  }
  console.log(outcome.value);
  return 0;
};

The type

Result<T, E> is a built-in type constructor with exactly two arguments — the same kind of thing Array<T> is, built in rather than a user generic class (`Result` needs exactly two type arguments, e.g. `Result<number, string>`, tests/cases/reject_result_type_args).

  • T may be void: Result<void, E> is the fallible operation with nothing to hand back, and it carries no value at all (tests/cases/res_void).
  • E may not be void (`Result<T, void>` is not supported): a failure that says nothing is what panic is for.
  • Result<T, E> | null is refused (tests/cases/reject_result_nullable): the error arm already models absence.
  • A Result is immutable. r.ok = false is Cannot assign to `ok` of Result<i32, string>: a `Result` is immutable once built (tests/cases/reject_result_immutable), which is what keeps a narrowing from being falsified under it.

Each distinct pair of payload types gets one monomorphised struct, %struct.nish_result.<T>.<E> = type { i1, <T>, <E> }, held by pointer and allocated exactly as a class is — so a Result costs what a small object costs, and one that does not outlive its function becomes an entry-block alloca with no allocator call at all (tests/cases/res_stack).

A Result crossing a call boundary is different, and this is the one place its representation is not a pointer. When both payload types are scalars of at most four bytes — void, boolean, u8, u16, i32/number, u32, f32 — it is returned and passed as one i64 instead:

bits  0..31   the discriminant: 1 for Ok, 0 for Err
bits 32..63   the live arm's payload, zero-extended (f32 through a bitcast)

so return Ok(v) is a shift and an or with no allocation at all (tests/cases/res_by_value, and res_by_value_payloads for each payload width), and the receiving side unpacks the word into an object of its own, which every construct below reads exactly as before. Only the value in transit changes: a Result in a field or an array element, and a Result whose payloads do not fit, stay the WP16 pointer.

The word is what a host sees. Between two functions of one module it is { i1, i32, i32 } — the discriminant and one slot per arm, the arm that is not live left undef — because a non-exported function's calling convention is nobody else's business and the word costs two folds this shape does not (WP15 §7b, which took bench/result from 2.59x behind Rust -O3 to parity in two steps). The condition is exactly the one that gives a function internal linkage, so --no-strict-exports returns every function to the word, and an exported function is packed whoever calls it — which is what keeps --emit-header honest (tests/cases/res_export). Nothing about the language changes either way: the two spellings compute the same value and only the register they arrive in differs.

Where that object lives is the ordinary WP6 decision. A callee's unpacked parameter is an entry-block alloca unless a use of the parameter stores the pointer somewhere that outlives the frame — an object literal, push — in which case it is an arena bump like any other escaping allocation (tests/cases/res_by_value_param shows both in one golden).

Eight bytes is where the six supported targets agree about a register rather than a number worth tuning; the measurements, and the one place the packing still costs something against C and Rust, are in wp17-result-abi.md.

The surface

Spelling Meaning Test
Ok(v), Ok() the success value; takes its Result type from the context, as null does. Ok() is the Result<void, E> form res_basic, res_void; reject_result_no_context
Err(e) the failure value, likewise res_basic
r.isOk(), r.isErr() the discriminant test, and what narrows r res_basic
r.ok the same bit as a plain boolean; if (r.ok) narrows too, because a tagged union is how TypeScript itself would spell this res_basic
r.value T, only where the checker proved isOk() res_basic, res_by_value_param; reject_result_value_unchecked, reject_result_by_value_unchecked, reject_result_let_keeps_proof, reject_result_narrowing_assigned_in_chain
r.error E, only where it proved isErr() res_basic; reject_result_error_in_ok_arm
r.orReturn() T when ok; otherwise return Err(r.error) from the enclosing function — Rust's ? res_propagate, res_by_value_propagate; reject_result_propagate_plain, reject_result_propagate_error_type
r.unwrapOr(d) T when ok, d otherwise res_unwrap
r.expect(message) T when ok; otherwise message on stderr and exit 1, the same ending panic has res_unwrap, res_void

There is deliberately no unwrap(): expect(message) says the same thing and insists on a reason. There is no map / andThen / orElse either — they need a callback written at the call, often a closure, which a function reference cannot hold, and through an unknown callee the whole-program pass cannot prove purity, termination or escape. Narrowing plus orReturn() covers what those combinators are for.

The three rules

1. A Result cannot be dropped. A call that answers one may not stand as an expression statement (`Result<i32, string>` must be handled, not discarded, tests/cases/reject_result_discarded), and a local that holds one must be read at least once (`outcome` holds a `Result<i32, string>` that is never inspected, reject_result_unhandled). Handing the value on — an argument, a return — counts as reading it: the responsibility moves with the value, and the receiving signature carries the same rules.

Storing one is handing it on too. An assignment statement — rs[0] = rs[1], r2 = r1 — moves the Result into its target and is not a discard; r2 = r1 reads r1, and r2, a local, must still be inspected (tests/cases/res_result_store, reject_result_store_unread). The value an assignment replaces is dropped, though, so a Result local may not be assigned again while the value it holds has not been read since it was written (`r` is assigned again before its `Result<i32, string>` is inspected, reject_result_overwrite_unread). The check reads the function in source order, with an assignment's right-hand side before its target, so r = retry(r) is accepted, and a read in either branch of an if counts for an assignment after it. An element or a field is not tracked slot by slot, so rs[0] = rs[1] overwrites rs[0] unchecked. In a generic body a discarded value is judged by the type its template declares, as Rust's #[must_use] is: items.pop() on items: T[] drops a T, which is not a Result to the template's author even where T is one, while a template that drops a Result<T, E> it declared, or a concrete Result, is refused at every instantiation (res_result_store, reject_result_generic_discarded). That is what lets a Map hold a Result value (tests/cases/map_value_result, and map_value_result_by_value for one that travels packed).

2. The error arm comes first. r.value is legal only where the checker proved isOk(), r.error only where it proved isErr(). There is no spelling that reaches the success payload without deciding what happens to the failure, so the success path cannot be written before the error path is handled.

Narrowing is the same engine as T | null (src/expressions.ts) and obeys the same rules: it applies to a variable, not a property path; it ends at any assignment to that variable; and it is dropped before a loop that assigns it. All three spellings compose with !, &&, || and the ternary, and hold after an if whose other branch cannot fall through:

Form Where r reads as its ok arm
if (r.isOk()) A else B in A; and after the if when B cannot fall through
if (r.isErr()) A else B in B; and after the if when A cannot fall through
if (r.ok) A else B as isOk()
r.isOk() && e, r.isErr() || e in e
r.isOk() ? a : b in a (and in b for isErr())

A field or element holding a Result is not narrowed; bind it to a local first, exactly as for a nullable. An assignment inside an && or || chain ends the narrowing for the operands after it, as for a nullable (tests/cases/reject_result_narrowing_assigned_in_chain).

A proof stays with its variable. What a test proved is seen only by a proof consumer: the receiver of .ok, .value, .error, isOk(), isErr(), unwrapOr, expect or orReturn, or another narrowing test. Wherever a type is instead inferred from the narrowed variable's value, it is the plain Result<T, E>: a let or const initialiser, a ternary, and an array literal's elements. Arguments, returns and stores already take the declared type they flow into. So inside if (r.ok), const y = r needs its own test before y.value, c ? r : q does too whatever q was narrowed to, and [r] is a Result<T, E>[] that an Err may be pushed onto (tests/cases/reject_result_let_keeps_proof, reject_result_ternary_keeps_proof, reject_result_array_keeps_proof; res_proof_consumers for the tests that make each of them compile). tsc narrows const y = r along with r, so this refuses programs tsc accepts; that is the safe direction, and the rule a reassignment, a pushed element or the other arm of a ternary would otherwise break.

3. Propagation is contagious. r.orReturn() is legal only inside a function that itself returns a Result whose error arm accepts E (`orReturn()` propagates the error, so `main` must return a `Result<T, E>` (it returns i32), and `orReturn()` would propagate IoError but `read` returns Result<i32, string>). A function that propagates a callee's failure therefore has to admit it in its own signature. There is no implicit error conversion — Rust's From<E> needs a trait and Nish has none — so a mismatch is named rather than papered over; convert it by hand with if (r.isErr()) { return Err(...); }.

It is still TypeScript

Every line above parses as TypeScript, and with runtime/nish.d.ts on the include path it type-checks under plain tsc --strict and in an editor too. The declarations model Result as the tagged union TypeScript would use anyway, intersected with the method surface, so if (r.ok) and if (r.isOk()) narrow r in tsc for the same reason and in the same places they narrow here — and tsc refuses r.value before the test just as this compiler does (tests/run.js, "WP16: the ambient declarations").

nish remains the authority: tsc cannot see that a Result may not be dropped, that orReturn() returns early, or that the enclosing function has to return a Result for it to be legal at all. A program tsc accepts may still be rejected here; the reverse is a bug in the declarations.

Interop

A Result crosses the host boundary. --emit-header writes two C types per Result and a signature uses whichever its position calls for:

/* Result<number, number> */

/* the arena object: a `Result` too large to pack, and what a field holds */
struct nish_result_i32_i32 {
  bool ok; /* 1 = value, 0 = error */
  int32_t value;
  int32_t error;
};

/* the by-value form, in either direction: one 64-bit word */
typedef struct nish_result_i32_i32_word {
  int32_t ok; /* 1 = value, 0 = error */
  union { int32_t value; int32_t error; } as;
} nish_result_i32_i32_word;
NISH_RESULT_ASSERT(sizeof(nish_result_i32_i32_word) == 8, "...");

The word is not a description of the ABI, it is the ABI: clang lowers a function returning or taking that type to i64 on every supported native target, which is the same declaration the module already defines (wp17-result-abi.md §3). A C host includes the header and calls across with no glue, in both directions (tests/run.js, the WP17 interop block).

--emit-napi bridges a by-value Result whose payloads are numbers or booleans, in both positions, as the object JS already models — { ok: true, value } or { ok: false, error }. --emit-dts declares the same union for the wasm build, and the generated loader packs an argument and unpacks a result. A Result held by pointer still does not cross either JS boundary: it is arena memory the next call may recycle.

A wasm export's string result is a JS string; a string parameter is not bridged (docs/wp50-wasm-host.md §7). The loader decodes the result's UTF-8 bytes with TextDecoder straight out of the arena, before it releases the call's mark, so the page never holds module memory; an invalid sequence becomes U+FFFD. An export that takes a string is left out of the .d.ts and the loader with argument 1 (s) is `string`, which the wasm bridge carries only as a result: have the page `encodeInto` module storage and pass the byte count (`nish/host/text`): the page writes the text into a u8[] module storage and the module reads it back with textRead (tests/run.js, section host-import-text). Going the other way, textRead(buf, n) answers null for an n that is negative or past the buffer, and each writer (textWrite, textWriteInt, textWriteF64) takes the offset to write at and answers the offset after what it wrote, so writes chain. Text that does not fit writes nothing and answers -1, and a writer handed a -1 offset answers -1 without writing, so a chain that overflowed once stays -1 to its end.

A ranged parameter (integer<Lo, Hi>, Types) crosses as the i32 it is, and is checked where every call passes through (wp31-ranged-integers.md §9):

  • Where the check lives is the linkage condition. A function that --strict-exports makes internal has every caller in view, so each call site checks its argument, where the facts that can prove it free are. Any other function (exported, or every function under --no-strict-exports) can be called by a host with any int32_t, so it checks its ranged parameters in its own prologue, before anything else it does, and its callers in the program pass theirs unchecked (tests/cases/interop_rng_param), so a loop that passes one is given no performance warning for it: no guard at the call would remove the callee's check (interop_rng_loop). Leaving the range there is the same panic as at any other entry, which is what a C host sees (interop_rng_host, driven by interop_rng_host.c).
  • The bridges throw first. The N-API shim reads a ranged argument with napi_get_value_double, and the wasm loader judges the number it was given, so a value that is not an integer in [Lo, Hi] throws RangeError: pick: argument 2 (day) must be an integer in [1, 7] before the call, rather than ending the process. The value is read as a double because ToInt32 would wrap 4294967301 to 5, which is in range; RangeError is what JavaScript throws for new Uint8Array(-1). --emit-napi-async rejects with the same error.
  • The sidecars say the range. --emit-header spells the parameter int32_t and gives the source signature above the prototype, with day: panics outside [1, 7]; --emit-dts spells it number and adds Throws a RangeError unless day is an integer in [1, 7]. A ranged result and a ranged field are int32_t / number with the range in the comment, since a value the program produced is already inside it.
  • A range inside data is not described. An integer<0, 9>[] parameter, a record with a ranged field, or a Result over a range is memory a host writes and nothing checks on entry, so the header gives the function its existing line, not declared; no C spelling for one of its types, and the .d.ts, the loader and the N-API shim leave it out with their own (tests/run.js, the interop_rng block, which builds every sidecar of interop_rng_host.ts, compiles the header under -pedantic and calls the addon and the wasm build from Node).