Expressions

Evaluation is left to right, operands before operators, as in JavaScript; the specific orders for compound assignment and element assignment are under Semantics decisions.

Operators

Operator Works on Gives
+ - * / % two numbers of one type that type
+ two string string
unary - any numeric type same
unary ! boolean boolean
& | ^ two integers of one type that type
<< >> >>> two integers of one type that type
unary ~ any integer type same
< <= > >= two numbers of one type boolean
=== !== two values of one type boolean
== != forbidden –
&& || two boolean boolean
c ? a : b boolean, two of one type that type
a ?? d a Map.get result V
a ?? d a T | null T or T | null
x = e a mutable target the target's type
x op= e (+= -= *= /= %=) a numeric mutable target the target's type
x op= e (&= |= ^= <<= >>= >>>=) an integer mutable target the target's type
++x --x x++ x-- numeric mutable local new / old value
, forbidden –
a?.b ?? d, a?.m() ?? d a T | null chain the last link's type
await f(x) a direct async call the call's T
== != ?.[ ?.() in instanceof typeof delete void yield forbidden –
** **= not supported –
+x not supported –

+ - * / % take two numbers of one type (i32, i64, u8, u16, u32, u64, f32, or f64) and give that type. On the signed integer widths an overflow branches to nish_panic_overflow (Semantics decisions); it is plain through a nish:unsafe wrapping* call. An integer division is preceded by a divisor check that branches to nish_panic_div (Checked integer division).

  • Lowering: add sub mul / fadd fsub fmul fdiv frem (on float for an f32, double for an f64); on a page module (above, Math.sin) or under --deterministic a float % or %= is a call to std/math.ts's fmodF64 in place of frem, whose libm fmod that link lacks, an f32 widened to f64 and the exact result narrowed back; on the signed integer widths nsw where proven to fit and otherwise llvm.s*.with.overflow and a branch to nish_panic_overflow, plain through a nish:unsafe wrapping* call, never nuw; integer sdiv / srem (udiv / urem on an unsigned type) are preceded by a divisor check that branches to nish_panic_div.
  • Tests: add, locals, i64_basic, f64_mode, div_checked, ovf_checked, ovf_matrix, u_arith_wrap, u_udiv_urem, f32_arith, wasm_math_rem; reject_type_mismatch, reject_u_mixed_signedness, reject_f32_mixed

+ on two string gives a string.

  • Lowering: nish_str_concat.
  • Tests: str_concat; reject_str_plus_number (no implicit string conversion)

unary - takes any numeric type and gives the same type.

  • Lowering: sub <T> 0, x for an integer, fneg float / fneg double for a float.
  • Tests: cf_if (-x), i64_basic, f32_arith; f64 (CLI only)

unary ! takes a boolean and gives a boolean.

  • Lowering: xor i1 x, true.
  • Tests: cf_logical; !s on a string is Unsupported unary operator `!` on string (CLI only)

& | ^ take two integers of one type and give that type.

  • Lowering: and / or / xor, one instruction, no panic path.
  • Tests: bit_and_or_xor, bit_i64, bit_attributes; reject_bit_f64, reject_bit_width, reject_bit_number_mode, reject_bit_boolean (Operator `&` is not available on boolean (use `&&`))

<< >> >>> take two integers of one type and give that type. >> is sign-filling on a signed type and zero-filling on an unsigned one, so >> and >>> are the same instruction there; >>> is always zero-filling. The count is masked to the operand width (31, 63, or 7/15 on the narrow unsigned widths); see Shifts.

  • Lowering: shl; >> is ashr (sign-filling) on a signed type and lshr (zero-filling) on an unsigned one; >>> is always lshr. A constant count is masked at compile time and emits no and.
  • Tests: bit_shifts, bit_shift_const, bit_shift_fill, bit_shift_narrow, bit_i64, u_shift_logical; reject_u_shift_mixed; tests/differential/corpus/bit_shifts

unary ~ takes any integer type and gives the same type.

  • Lowering: xor x, -1 (LLVM has no not).
  • Tests: bit_not; reject_bit_not (Operator `~` requires an integer operand, got f64)

< <= > >= take two numbers of one type (i32, i64, the unsigned widths, f32, or f64), and nothing else, and give a boolean.

  • Lowering: icmp slt ... signed, icmp ult ... unsigned, fcmp olt ... for both float widths.
  • Tests: cf_if, f64_mode, u_compare_above_intmax, f32_arith; booleans (reject_bool_ordering), strings (reject_str_lt, reject_str_lt_str), and structs (reject_cls_ordering) are Operator `<` requires two numeric operands, got boolean and boolean

=== !== take any two values of the same type except void, and give a boolean. A T | null compares only against the literal null. Strings compare by content; arrays and objects by identity (the pointer). On an f64, x !== x is true for NaN. a === undefined is allowed for a Map.get result only, and tests its found bit, negated.

  • Lowering: integers and booleans: icmp eq / icmp ne; f64: fcmp oeq / fcmp une (so x !== x is true for NaN); strings: nish_str_eq (content); arrays and objects: icmp eq on the pointer (identity); p === null: icmp eq against null; a === undefined, for a Map.get result only: its found bit, negated.
  • Tests: str_eq, cls_this_method_call, conversions, mem_nullable, map_get_narrow; arrays (CLI only); reject_null_compare_two, reject_map_get_undefined_compare

== != are forbidden.

  • Tests: reject_loose_equality, reject_loose_inequality

&& || take two boolean and give a boolean, short-circuit.

  • Lowering: short-circuit: br + phi.
  • Tests: cf_logical; reject_cf_logical_numbers (requires boolean operands)

c ? a : b takes c: boolean, and a, b of the same non-void type, and gives that type.

  • Lowering: br + phi.
  • Tests: cf_ternary; reject_cf_ternary_mismatch, reject_cf_ternary_void

a ?? d on a Map.get result: a is a Map.get result (V | undefined) and d a V; it gives a V. It sits at the level of ||, and is not mixed with || or && unparenthesised (Map and Set).

  • Lowering: br to valueAt or d, then phi; select for a const with a literal or a name as d.
  • Tests: map_get_nullish, map_get_narrow, map_get_pointer_value; reject_nullish, reject_nullish_default_type, reject_nullish_mixed_or

a ?? d on a nullable: a is a T | null that is not an element read, and d a T or a T | null, with the same precedence. It gives a T, or a T | null for a nullable d (Nullable types).

  • Lowering: icmp ne against null, then select for a literal or a name as d; otherwise br to d and phi.
  • Tests: nullish_nullable, nullish_nullable_field, nullish_nullable_default_null, nullish_nullable_default_context, nullish_nullable_escapes; reject_nullish_nullable, reject_nullish_element, reject_nullish_nullable_default_type

x = e assigns to a mutable local, field, or element; e is of the target's type, and the expression gives the target's type.

  • Lowering: store.
  • Tests: locals, cls_field_write, arr_index_read_write

x op= e (+= -= *= /= %=) works on a numeric mutable local, numeric field, or numeric element, with e of the same type, and gives the target's type.

  • Lowering: load, op, store.
  • Tests: cf_compound_assign, cls_compound_field, arr_index_read_write; reject_cf_compound_const, reject_cf_compound_string, reject_cf_compound_widths

x op= e (&= |= ^= <<= >>= >>>=) works on a mutable local, field, or element of integer type, with e of the same type, and gives the target's type. The shift forms use the same shift-count mask. The target expression is evaluated exactly once.

  • Lowering: load, op, store, with the same shift-count mask; a field is addressed by one GEP and an element bounds-checked once, so the target expression is evaluated exactly once.
  • Tests: bit_compound, cls_field_bitwise_assign, arr_element_bitwise_assign; reject_cls_field_bitwise_readonly, reject_arr_element_bitwise_f64; tests/differential/corpus/bit_compound_target

++x --x x++ x-- work on a numeric mutable local only, and give the new / old value.

  • Lowering: load, add 1, store.
  • Tests: cf_incdec; reject_cf_incdec_param, reject_cls_field_incdec

, is forbidden.

  • Tests: reject_comma_expression

a?.b ?? d, a?.m() ?? d take a, a T | null, and a chain of ?. and . links, field reads, length and method calls, that is the left operand of ??. It gives the last link's type, as a ?? d on a T | null types it (Nullable types).

  • Lowering: icmp eq against null at each ?. link's receiver, then br to nullish.default; phi at nullish.end.
  • Tests: optional_chain_field, optional_chain_order, optional_chain_generic, optional_chain_bounds; reject_optional_chain, reject_optional_chain_never_null

await f(x) takes a direct call to an async function, at the top of a statement in an async function, and gives the call's T (Async functions).

  • Lowering: a call when f awaits nothing; otherwise f's frame is laid out in the caller's, @f.resume is called, and the caller saves its state and answers false while it pends.
  • Tests: async_await_single, async_await_chain, async_lowered; reject_await, reject_async_await_value, reject_async_await_nested

== != ?.[ ?.() in instanceof typeof delete void yield are forbidden by the validator (Forbidden constructs).

  • Tests: reject_loose_equality, reject_optional_chain_element, reject_optional_call, reject_in_operator, reject_instanceof, reject_typeof_operator, reject_delete, reject_void_expression, reject_yield

** **= are not supported: Unsupported binary operator `**` / Unsupported assignment operator `**=`.

  • Tests: reject_op_exponent, reject_op_exponent_template, reject_exponent_assign_local, reject_cls_compound_operator

+x is not supported.

  • Tests: Unsupported unary operator (CLI only)

Checked integer division

a / b and a % b on i32 or i64 follow Rust, not C: the divisor is checked first, and a zero divisor or MIN / -1 (-2147483648 / -1, -9223372036854775808 / -1, and the same for %) prints attempt to divide by zero or attempt to divide with overflow to stderr and exits with status 1 (tests/cases/div_checked, div_zero_panic, div_overflow_panic; tests/differential/corpus/int_div_zero, int_div_overflow). Otherwise the result is the truncating sdiv / srem: -7 / 2 is -3, -7 % 3 is -1, -2147483648 / 1 is -2147483648. The check is two compares and a branch to a cold div.fail block that calls the noreturn nish_panic_div; because that path exists, a function containing an integer division is neither willreturn nor readnone, exactly like one containing a checked a[i]. The rule applies to /, %, /=, and %= on locals, fields, and elements. A divisor the checker proves is left unchecked, as a proven index is: one that is neither 0 nor -1 — a constant (a / 2, a % -3, a folded module constant), a ranged or unsigned divisor whose declared range leaves both out, a local behind d > 0 or behind d !== 0 && d !== -1 — or one that is not 0 against a dividend known to be non-negative, which cannot be the minimum. Such a division is the bare sdiv / srem and no div.fail block (tests/cases/panics_divide, deny_panics_clean). Floating-point division is never checked: x / 0 on f64 is Infinity and 0 / 0 is NaN.

Unsigned division is checked more cheaply. udiv and urem have no overflow case at all — there is no unsigned value whose negation leaves the range, so MIN / -1 has no counterpart — and the check collapses to a single compare against zero, with no and and no or. tests/cases/u_div_one_check pins the signed and the unsigned sequence side by side:

; u32 a / b                          ; i32 a / b
%0 = icmp eq i32 %b, 0               %0 = icmp eq i32 %b, 0
br i1 %0, ...                        %1 = icmp eq i32 %a, -2147483648
                                     %2 = icmp eq i32 %b, -1
                                     %3 = and i1 %1, %2
                                     %4 = or i1 %0, %3
                                     br i1 %4, ...

A zero divisor still prints attempt to divide by zero and exits 1, and the function still loses willreturn because the panic is noreturn; attempt to divide with overflow is simply unreachable on an unsigned type.

Calls

  • f(args) calls a top-level function or an imported one, or — inside a template — a function parameter, which is a direct call to the function the instantiation was given; the callee must be a plain identifier (Only direct calls to named functions are supported), known (Unknown function `String` (CLI only)), and called with matching arity and types (see Functions).
  • obj.method(args) calls a class method with obj as this (tests/cases/cls_this_method_call); this.method(args) inside a method likewise.
  • An array has the methods of Arrays and strings as receivers (tests/cases/arr_push); any other is Unknown method `shift` on i32[] (supported: push, pop, …).
  • Builtins are called by dotted name (console.log, Math.sqrt, process.exit) or bare name (toI32, parseInt, Number, readFileSync); a user function with the same bare name shadows the builtin. Unknown dotted builtins are Unknown builtin `Math.foo` (tests/cases/reject_unknown_builtin).

new

  • new C(args) for a class: allocates sizeof(C) bytes in the arena, or on the stack when the object provably does not escape (Memory model), and runs the constructor (or the inline initializers) (tests/cases/cls_point, mem_stack_struct).
  • new Array<T>(n): n zero-filled elements; T must be a scalar, a nish:simd vector (every lane zero) or a U | null (whose zero fill is null); type argument and length required (tests/cases/arr_new_zeroed, mem_nullable, simd_zero_fill; reject_arr_new_string: would zero-fill with null string values). A length no array can hold panics with array length out of range before anything is allocated: past 2^31 − 1 under --number-mode i32, past 2^53 under f64, a negative i32 or i64 (a ranged integer is read as an i32, so it is checked as one), or a NaN. A narrower unsigned length and a literal up to 2^31 − 1 are not checked (tests/cases/cg_sec_new_array_guard, cg_sec_new_array_negative, tests/link/cg_sec_new_array_*; docs/security/codegen.md, CG-1 and CG-2).
  • new Int32Array(n), new Float64Array(n), new BigInt64Array(n): the same as new Array<i32>(n), new Array<f64>(n), new Array<i64>(n), with the same lowering (tests/cases/arr_typed_views), and no push or pop on the result (Typed-array names have no push or pop); a type argument is `new Int32Array` takes no type argument (reject_arr_typed_view_typearg).
  • Anything else is Unsupported `new X` / Unknown class `X`; new Function and new Proxy are forbidden (reject_new_function, reject_proxy).

Member access

  • s.length on a string: the UTF-8 byte length as a number (tests/cases/str_length; reject_length_on_number, reject_unknown_property).
  • a.length on an array: read-only (tests/cases/arr_length; Cannot assign to `length` of i32[], reject_arr_length_assign).
  • p.f on a class or interface value (tests/cases/cls_point).
  • Math.PI, Math.E (tests/cases/math_i32); process.argv, process.platform, process.arch (see process); Arena.* (see Arena). Any other bare identifier before a dot is Unknown identifier `os` (CLI only).
  • Member access on a T | null value requires narrowing first, or a ?. in a chain that ends in ?? (Nullable types; tests/cases/reject_optional_chain).

Element access

a[i] requires an array a (Cannot index a value of type i32, tests/cases/reject_arr_index_non_array) and a numeric i (Array index must be a number, got string, reject_arr_string_index). The index is sign-extended from i32 (or truncated toward zero from double in f64 mode) to i64 and checked against len with an unsigned compare, so negative indices fail too (tests/cases/arr_bounds_panic, arr_index_read_write, arr_f64).

The check is not emitted when the checker has proved the index in range (WP15 §2.1/§2.2). The proof is flow-sensitive. A fact's index is a local or a parameter, and its length holder w is a local, a parameter, or a property path — a local, a parameter or this, then field reads: h.xs, this.state.idx (#106). An access w[i] needs i >= 0 and i < w.length, and both come from the program as written:

  • i >= 0 from a literal initialiser, from i = w.length, from a test that reaches the access (if (i >= 0), 0 <= i, the false arm of i < 0), or from the type — an u8/u16/u32/u64 index is never negative, and neither is an integer<Lo, Hi> with Lo >= 0.

  • a bound read off the type. A declared range bounds its index from above as well: a u8 is below 256, a u16 below 65536 and an integer<Lo, Hi> below Hi + 1, so with a length guard that covers the range (if (table.length < 256) { return }) the access needs no check. const k = toI32(b) keeps the bound of a u8 or u16 b, because the conversion is a zext. A u32 or u64 has no upper bound an i32 fact can carry, and a range wider than the length that is known keeps its check (tests/cases/arr_bounds_ranged). Nothing is recorded and nothing is forgotten: every write into a ranged place is an entry, so the value is inside its range at every point.

  • i < w.length from a test that reaches the access — a loop condition, an if, the right operand of &&, the statements after if (i >= w.length) { return; } — or, through const n = w.length, from i < n. A constant index w[3] needs w.length >= 4 instead, which a length guard (if (w.length >= 4)) or an array literal of known size gives.

  • for a u8, u16 or u32 index, toU32(i) < toU32(w.length) — or i < toU32(w.length) for a u32 — the same way: an unsigned index cannot be compared with the i32 length as it is, its type is its lower end, and this is the upper one. toU32 widens a u8 or u16 and is the identity on a u32, and of a length it can only answer the length or less (in f64 mode it is a saturating fptoui), so the u32 compare is i < w.length or stronger. Only in the test itself: a u32 copy of the length is not a length, because toU32(w.length) - toU32(1) wraps on an empty array. A u64 index is not credited — toU32 keeps its low 32 bits — and neither is toI32(i) < w.length on a u32, which reads an index past 2^31 - 1 as negative (tests/cases/arr_bounds_unsigned_guard, arr_bounds_unsigned_guard_f64; arr_bounds_unsigned_guard_kept keeps every check).

  • a guard that ends the path. After if (i < 0 || i >= w.length) { … } the negation of the test holds for the rest of the block when the guarded branch ends in return, break, continue, or a call to the builtin panic(…) or process.exit(…) (exit from nish:process too). Only the builtins count: a parameter or local called process, or a function parameter called panic, is the call it resolves to and falls through, and so does any other call. Such an access keeps its check and the NL9007 warning (tests/cases/bounds_panic_guard, bounds_exit_guard; bounds_guard_not_exit, bounds_guard_shadowed_exit and bounds_guard_shadowed_panic keep it). Map.keyAt, Map.valueAt and Set.keyAt in std/collections.ts guard their reads this way.

  • both at once from a check that has already passed. A checked w[i], read, store or compound assignment, and a checked s.charCodeAt(i) either panic or leave 0 <= i < w.length behind, because the panic does not return; a checked w[3] leaves w.length >= 4. So the same index on the same holder is proved on every path that runs through the first check, until one of the rules below ends the fact — which they do exactly as they end a fact a test wrote. const t = v[i]; v[i] = v[j]; v[j] = t carries two checks, not four. The fact is taken where the emitter runs the check: v[i] = v[j] checks v[j] before v[i], and v[i] op= x checks before x runs. A store whose value calls anything proves nothing about a path holder, because its check passed on the array the path named before the call (tests/cases/arr_repeat_check, arr_repeat_check_local; the repeats that keep their check are arr_repeat_check_call, _push, _field_store, _reassign and _flow, and arr_repeat_check_panic panics past the end on three of them).

    toI32(w.length) is w.length wherever a length appears above: in the hoist const n: i32 = toI32(w.length), in i < toI32(w.length) and in a length guard. It is the spelling that compiles in both number modes — under --number-mode f64 .length is an f64, and i < w.length with an i32 i is a type error — so a program written for both (std/text is one) keeps every proof the bare hoist gets. It is sound in both: in i32 mode the conversion is the identity, and in f64 mode it is a saturating fptosi of an exact integer, which can only answer the length or less, never a negative. Only the builtin counts: a user function named toI32 wins over the builtin and may answer anything, so it proves nothing (tests/cases/perf_bounds_toi32_user, which panics on the pass past the end), and neither does toI32 of anything that is not a bare length (perf_bounds_toi32_loop). The builtin converts inline and calls nothing, so unlike any other call it leaves the array-length facts standing, and const m: i32 = toI32(ys.length) does not undo the const n: i32 = toI32(xs.length) above it (perf_bounds_toi32, perf_bounds_toi32_f64).

  • i - c and w.length - c (c a non-negative literal) carry bounds too: removing c lowers every floor of i by c — i >= 1, which if (i !== 0) on a non-negative i gives, leaves i - 1 >= 0 — and with c >= 1 turns i <= w.length into i - 1 < w.length; w.length - 1 is below the length whatever the array holds. A copy let j = i has every bound i has (tests/cases/arr_range_call_countdown).

  • i + c (c a literal of 1 or more) is an index too, and a test on it is a bound on i. i + c < w.length says the length reaches c past i, and so does i + c < n with n a hoisted length; i + c <= w.length reaches c - 1; i + c < N, for a literal N, is i < N - c. An access w[i + k] then needs i >= 0 and a reach of at least k, or a literal bound i < M with w.length >= M + k, so a loop that reads four elements a pass under i + 3 < w.length keeps none of its four checks. A checked w[i + c] that ran leaves i + c < w.length behind, and nothing about i >= 0. Both halves rest on the sum being exact: a signed i + c panics on overflow or is proven not to overflow, so it is never a wrap to a small value. For an unsigned i, whose add wraps by definition, an offset proves nothing and the check stays (tests/cases/arr_bounds_offset; arr_bounds_offset_reach reads one past its reach and arr_bounds_offset_floor has no floor, and each keeps its check and panics).

  • Any other integer index is proved by its range. Where none of the rules above proves w[e], the values e can take decide: every local's bounds from the facts above and its declared range, carried through +, -, *, a mask, a conversion and a call's known return range; a quotient converted to its own type, toI32(a / 4) of i32 operands (or toU8, toU16, toU32 of theirs), keeps the quotient's range, since that conversion emits nothing. If the lowest is not negative and the highest is below a length w is known to have (w.length >= n, from an array literal, a new Array(n), a guard or a check that ran), the access needs no check: freeMaxs[c + r] and freeMins[c - r + 7] with r and c each below 8 into arrays made with 16, or cells[r * 4 + c] over a 4 by 4 board. The range is the value's own only where the arithmetic is exact, which is a signed i32 or i64; an unsigned index, whose arithmetic wraps by definition, and an f64 one keep their check. The length is the one the index leaves behind, so a call inside the index that shrinks the array, a new whose constructor does included, proves nothing (tests/cases/arr_bounds_range; arr_bounds_range_past reaches the length, arr_bounds_range_negative goes below zero, and arr_bounds_range_call and arr_bounds_range_new shrink the array, and each keeps its check and panics; arr_bounds_range_kept keeps its own).

  • A helper's fresh array has the length it was built with. A length w is known to have comes from an array literal or new Array(n) written in place, and also from a call of a function that builds one and returns it: const xs = filled(8), or this.rows = filled(8), starts xs or this.rows with 8 elements when filled declares const arr = new Array<T>(n) (a typed-array new or an array literal too), touches it only by indexing it, reading arr.length and arr.push(...), and returns it. Every return hands back that local or a fresh array written in place, and the call gives the shortest of them. A size is a literal, a constant of the helper's module (read where the call is in that module), or a parameter, whose argument gives the length by its declared floor: a literal, a constant or a ranged type's Lo. The helper's body is read as written, so the rule takes only what it can see there: a plain function, not a method, a generic or an arrow; a body with no arrow, nested function, class or try; a size whose name the body never declares again or writes. The array may be handed to a function of the same module whose parameter keeps its length in turn: the parameter is only indexed, read for .length, pushed to, or handed on to another such parameter, recursion included, and never returned. Storing the array, pop, returning it from a callee, a method's or a builtin's argument, or any other use gives no length, because each is a way another holder could shrink it; so does a helper in another module that hands its array on, whose call the caller's module cannot resolve. A store recv.f = filled(8) gives one only when recv is this or a const local, which the call cannot point elsewhere (tests/cases/arr_bounds_returned, arr_bounds_returned_through; arr_bounds_returned_pop, _passed, _stored, _least, _rebind, _shadow, _shadow_param, _through_return, _through_deep, _through_cycle, _through_store, _through_param and _through_memo each keep their check and panic; tests/link/arr_bounds_returned_import keeps its check; arr_bounds_returned_kept keeps its seven).

A fact ends where it stops being true: at any assignment to i that is not i = i + <non-negative literal> (i++ and i += n included) or i = i - <non-negative literal> (i-- and i -= n included), at any assignment to w, and — for an array — at any call to something that may resize it, because a callee holding the same array may push or pop and move len (tests/cases/arr_bounds_shrink_panic is the program that still panics because of that rule). A decrement keeps the upper bounds and loses the lower ones, the mirror of an increment, so the loop that counts down from the last index needs only its own i >= 0. A string's length cannot change once the variable holding it is bound, so a string fact survives calls, which is what makes a scanner's cursor check-free (tests/cases/str_bounds_proven). The increment exception needs nsw: the step past INT_MAX panics, so the lower bound holds for the same reason the overflow check is there; a counter stepped with wrappingAdd has no lower bound, and its check stays. An f64 index is never proved, because a bound on the double is not a bound on its truncation. tests/cases/arr_bounds_proven and perf_bounds_quiet pin the proofs; the surviving checks warn, below.

A fact is taken where it is true, and only then. Two orderings decide that, for a local and a path alike:

  • in a && b and a || b, a's facts are proved before b runs, so they reach the code the condition guards only if nothing b does can undo them. A call, an assignment or a field store in b drops them by the rules below, and i < xs.length && xs.pop() > 0 proves nothing about xs[i] (arr_bounds_cond_effect, arr_bounds_cond_assign, and the path forms arr_path_cond_*: a call, a store, a root reassignment, ||, a ternary, a while, a string path, a generic class and f64 mode);
  • an element store is judged where its check runs against the values it stores through. a[i] op= v checks before v runs and is judged there. a[i] = v reads a and i, runs v, then checks, so it is proved only if v leaves i and a alone: xs[i] = (i = 0) keeps its check (arr_bounds_store_rhs, arr_path_store_rhs, arr_path_store_rhs_compound). A field store evaluates its receiver before its value, and g.hs[i].n = (i = 0) is judged that way round (arr_path_store_rhs_field);
  • a for update and a do/while condition are reached from the end of the body and from every continue, so they are judged against what holds on all of those edges: a continue branch that rebinds the array, moves the index or calls anything takes the proof away from the update or the condition (arr_path_continue_for, arr_path_continue_do, arr_bounds_continue_for, arr_bounds_continue_do), and one that does none of that keeps it (arr_bounds_continue_proven). A continue in a switch clause reaches the loop's update (arr_bounds_continue_switch), and one in an inner loop reaches only the inner update (arr_bounds_continue_nested);
  • the code after a for or a while is reached where the condition fails and from every break, which leaves with the body's writes applied. A fact the condition re-established about something the body then changed does not survive the loop (arr_bounds_break_for, arr_bounds_break_while, arr_bounds_break_for_string, arr_bounds_break_while_string). A break in a switch clause leaves only the switch;
  • r.unwrapOr(d) evaluates d and r.expect(m) evaluates m only when r is an Err, so neither argument proves anything after the call. What d might undo is undone, and m is followed by the exit (arr_bounds_lazy_unwrap_or, arr_bounds_lazy_expect).

All of these were unsound for locals before property paths existed; the fixes and the tests cover both.

A property path has to earn what a local gets for free, because a field can be written through an alias and a local cannot. h.xs.length proves h.xs[i] only while nothing between the test and the access can rebind the path or resize the array, and a path fact ends at:

  • a store to a field whose name is anywhere on the path, through any holder — g.xs = ys ends h.xs's facts even where g is a different object, because the name is compared rather than the aliasing guessed (arr_path_reassign, arr_path_alias_store);
  • a store of a whole element into an array of inline records, which rewrites a record in place with no field name written (arr_path_record_store). It ends the facts of a path with a link read off a holder declared as that record type — r.xs for const r = rs[0] — because a struct field is a pointer and interfaces are nominal, so nothing else can point into the slot. An array of classes holds pointers, so a store there rewrites no object and ends nothing;
  • an assignment to the root (arr_path_root);
  • any call and any new that may resize an array or store to a field on the path, for a string path as well as an array one: a callee may push or pop the array or store a new value in the field, and a pop through a second holder of the same array is a call too (arr_path_callee_pop, arr_path_callee_string, arr_path_alias_shrink). charCodeAt and the builtin toI32 call nothing, as they do for a local; what else a call may do is its summary, below.

A path is never built through a link whose declared type is nullable — the root's included — whatever a guard narrowed it to, and neither is one whose last link is T[] | null (arr_path_nullable). Each of those tests is a program that proves i < h.xs.length, breaks it by one rule, and reads h.xs[i]; each must panic, and each reads past the array with its rule removed. arr_path_hold pins where the fact holds, and tests/cases/arr_header_hoist pins the measured point of it: a loop over h.xs compiles to the loop const xs = h.xs does, with one bounds check fewer than before and so one loop exit fewer. The hoist that lifts h.xs out of the loop refuses a loop that stores a whole element into an array of inline records, by the same rule the proof drops its path facts by (arr_header_hoist_record_store), and keeps hoisting through a store into an array of classes (arr_header_hoist_record_class) and a path read off classes beside a record store (arr_header_hoist_record_class_root). A path the proof cannot take keeps its check without a warning, because the rewrite the warning would name is that const xs = h.xs hoist.

What crosses a call (WP15 §2.4). Once every body is checked, each function gets a summary of what it can do to a caller's facts: the field names it — or anything it calls — may store to, and the record types it may store whole. A function that calls push, pop or any builtin handed an array or an object, Arena, a foreign function or an instantiation has no summary, and a call to it ends every array and path fact as above. A call with a summary resizes no array, so it keeps every array-length fact and every path fact whose fields and links it leaves alone: c.touch(), which stores calls, keeps i < xs.length and i < c.v.length (arr_range_call_loop), and one that stores v ends c.v's facts (arr_range_call_rebind). A builtin handed only numbers, booleans and strings — console.log, panic, a string method — has the empty summary, since a call handed no function reference can reach only what it is handed: the one mutable module state, module storage, is named only by the program's code (its module's, or an importer's when it is exported), never reached by a builtin, and its length never changes, so no call can end a length fact about it.

A function every call to which the compiler can see is entered with what every call site proves about its parameters: a floor and an upper bound of an integer parameter, and length facts about a holder read off a parameter or this — this.v.length >= 6, i < this.v.length. Each site is judged once its arguments have run, a fact about the local an argument named is carried only while no later argument writes it (arr_range_call_arg_rebind), and an argument handed to a parameter of a different integer type carries nothing. The sites are joined — the weaker floor, the higher bound, the shorter length, a relation only where every site states it (arr_range_call_two_sites, arr_range_call_no_proof) — and recursion is a fixpoint, so permute(n) calling permute(n - 1) under if (n !== 0) keeps n <= 6 and a recursion that grows its index keeps nothing (arr_range_call_grow). Inside the function the facts end by the rules above (arr_range_call_rebind_callee). Not entered with anything: main; an exported function or a method of an exported class, since a host may call it with anything (arr_range_call_exported) — unless the build is a closed-world --link, where export means only "importable" (see export and import: tests/link/range_export, and range_export_unproven for a caller that proves nothing); a hidden one, a constructor, a lifted arrow, a function taking a compile-time function, and any function called from an arrow or from an instantiation's body (arr_range_call_arrow, arr_range_call_generic). AWFY Permute with its class not exported is proved throughout: swap carries no check (arr_range_call), and with it exported the same holds in a --link build.

A generic's instantiations are proved one at a time, each against its own verdicts: rs[0] = x rewrites a record when T is an inline record and stores a pointer or a value otherwise, so an access one instantiation proves may keep its check in another (arr_bounds_generic_instances, and the _prim, _method and _iface forms).

The proof changes what the program costs, never what it means: an out-of-range index that reaches a check still panics. uncheckedGet and uncheckedSet from nish:unsafe are the opposite trade and a separate thing: each removes the check at its own site and makes an out-of-range index there undefined behaviour.

String-keyed access is forbidden by the validator (reject_string_key_access, reject_non_numeric_index), and so is an index outside the "numeric-shaped" forms listed under Forbidden constructs: a[k++] and a[--k] are Element access requires a numeric index (CLI only).

Array literals

[a, b, c] allocates a header and n elements; every element must have one type (Array literal elements must all have the same type, tests/cases/reject_arr_mixed_literal). [] needs a contextual T[] type (annotation, return type, assignment target, push argument, enclosing literal, or parameter) (Empty array literal needs a type annotation, reject_arr_empty_literal; tests/cases/arr_push, arr_literal). Holes and spread are not supported (Holes in array literals are not supported, reject_arr_hole; Spread in array literals is not supported, reject_arr_spread).

Arrays of records are contiguous

An array whose element type is an interface is one block of records, N of them end to end at exactly the stride and alignment clang gives the matching C array. ps[i] is an interior pointer into that block — a getelementptr, with no pointer to load and chase — which is what makes a loop over Point[] vectorisable and what lets a C host read ((struct Point *)a->data)[i] (tests/cases/arr_struct_contiguous, tests/layout/structs.c).

Three element kinds are not records and keep one pointer per slot:

  • a class. The two struct kinds already mean different things: an interface is fields and nothing else, so copying one into a slot cannot be told apart from pointing at it, while a class has identity — a constructor and methods that run on one object — and every other position in the language passes a class value by reference.
  • an interface some class implements. That array is the language's only polymorphic container (tests/cases/cls_implements_prefix): a Shape[] holds a Square and a Circle at once, and both are longer than Shape, so a value slot would copy the prefix and drop the rest. The property is program-wide — one compilation, one layout for Shape[] in every module of it.
  • a T | null of any kind: a null element has no bytes to be, and null is the pointer. That spelling is also how to ask for a sparse array of records.

Three consequences, each of them a rule:

  • A record put into an array is copied into the slot. ps.push(p), ps[i] = p and [p, q] copy sizeof bytes, exactly as a C array of structs does; afterwards ps[i] and p are two records, and writing one does not change the other (tests/cases/arr_struct_push_copy).
  • An element reference may not be held across a mutation of its array. push may move the block (nish_array_grow bumps a fresh one and copies) and pop hands the slot back to the next push, so a pointer taken before either names memory that is no longer the element. A const bound to a[i] or a.pop(), and the variable of a for (const p of a), are element references; using one after a push or pop on the same array — or after a call that could push through it, which is any call handed the array as a non-readonly parameter — is `p` refers to an element of `ps`, and `ps.push(...)` may move or reuse that storage; index `ps` again afterwards rather than holding the element across it (reject_arr_element_across_push, reject_arr_element_loop_push). A second name for the element is one too: const q = p, q = p (in a nested block as well, since q outlives it), and either side of c ? p : r or m ?? p (tests/cases/arr_ref_alias_*); a call's result is not, since a helper may return a copy (arr_ref_alias_clone). A loop is checked as a whole, because a push at the bottom of the body reaches a reference taken at the top on the next pass. ps.push(ps[i]) is refused for the same reason, in one message of its own (reject_arr_element_push_self).

The rule rejects some programs that would have been safe — a call is taken to mutate every mutable array it is handed, because whether the callee pushes is a whole-program question the checker does not answer. readonly T[] is how a signature promises it does not.

Fixed-length array fields are stored inline

A class field f: T[] is normally one pointer to an array header that lives somewhere else in the arena, so this.f[i] loads the pointer, then the header's data, then the element. When the whole program shows that the field can only ever hold an array nobody else can reach, of a length known at every assignment, the compiler stores the header and its elements inside the object instead, and this.f[i] becomes a load at a constant offset from this (tests/cases/cls_inline_array). This is a layout decision, not a language rule: no program can tell the two layouts apart, which is the whole of what the conditions below guarantee.

A field qualifies only when all of these hold, over every module of the program:

  • Every assignment is a fresh array of a constant length, as a statement of its own (x.f = e;, never y = x.f = e): an array literal of n elements ([] is one, with n = 0), new Array<T>(n) or a typed-array new with an integer literal n, or a call to a top-level function that is proven to return a fresh array whose length is a constant or one of its parameters, passed a literal there. That function returns only new Array<T>(p), a literal, or a const local initialised with one, which it only indexes and reads .length of (filledBooleans(8) in AWFY Queens, tests/cases/cls_inline_array_call). The slot is sized for the largest length K any assignment gives; the header still records the current length, so .length answers what it always did.
  • Nothing takes the field as a value. x.f[i] (read, write, compound) and x.f.length are the only uses. Reading it into a local, passing it to a function, returning it, iterating it with for ... of, capturing it, or calling any method on it — push and pop included — keeps today's layout (cls_inline_array_local, cls_inline_array_push, cls_inline_array_passed).
  • Every assignment's length is a literal. A length the compiler does not know cannot size a slot, and the field is boxed instead (below, cls_inline_array_dynamic).
  • No element access can reassign the field under itself. x.f[i] evaluates x.f before i, and x.f[i] = v before v; when the index or the value calls something that can assign f (directly or through its own calls), the access uses the array f held before, which a single set of slots cannot be. Such a field keeps today's layout (tests/cases/arr_repeat_check_call, cls_inline_array_order).
  • No host can see the class's layout. The class is not host-visible as export decides it for a call (hostVisible in src/visibility.ts): an exported class keeps today's layout in every build that is not a closed-world --link. And no build that describes or shares layouts with code this compiler did not write inlines anything at all — --emit-header (whose C structs list every class), --emit-dts, --emit-napi, a wasm target, --profile wasi, or a module that declares a C function (cls_inline_array_header, tests/link/cls_inline_array_*).
  • It is a plain class: not generic, not one that implements an interface, and its element type is not a record (an inline record would hand out interior pointers into the object).
  • K elements fit in 256 bytes and K is at least 1. The cap bounds how much an object grows, since every object of the class carries the slots whether it uses them or not. It does not bound the cost of reassigning: a literal or new Array writes the slots in place and allocates nothing, which is faster than the pointer layout at every K measured, while an assignment from a call still makes its array and then copies it, a cost that is about the same at 8 slots as at 64. A field reassigned from a call and read fewer than a few dozen times per assignment is therefore slower inline; the measurement is in the header of src/inline-arrays.ts.

A field that fails only on its lengths is boxed. When every condition holds except that some assignment's fresh array has a length the compiler does not know (new Array<T>(n) with a parameter n, a fresh-returning call passed a non-literal), or except that K elements would pass 256 bytes, the object holds only the array's length and data pointer, 16 bytes as { i64, i8* }, and the elements are one block of their own (tests/cases/cls_boxed_array). Against the pointer layout this drops the separate 24-byte header and its allocation: an object with a boxed field is 8 bytes larger and its array 24 bytes smaller, and this.f[i] loads data from this directly instead of first loading the header's address. A literal or new Array allocates the data block alone; an assignment from a call takes the len and data of the array the call made. Reference semantics are unchanged for the same reason as inline: no one else ever holds the array. A field taken as a value anywhere, push included, keeps the pointer layout (cls_boxed_array_push).

Why reference semantics are unchanged: the object is still a pointer, so a class holding an inline field can be stored in arrays and passed around as before. Assigning the field copies the fresh array's elements into the slot (an array literal and new Array write the slot directly and allocate nothing). That copy is observable only through another reference to the fresh array or to the field's array, and neither exists — the first because it is fresh, the second because the field is never taken as a value. An inline array lives and dies with its object, on the stack when the object does.

Template literals

`text ${e} text` accepts holes of type string, number, i64, f64, or boolean (Template literal hole must be string, number, or boolean); each hole is converted and the parts are concatenated left to right (tests/cases/str_template, i64_basic). `${s}` with a single string hole is s itself (tests/cases/str_param_passthrough).

A concatenation or a template whose result would pass 2^31 − 1 bytes fails as an allocation does, nish: out of memory and exit 1, in both number modes (docs/security/runtime.md, RT-2), and so does a join whose result would (CG-3 in docs/security/codegen.md; tests/link/cg_sec_join_limit). No string can therefore pass that length.

this and object literals

See Classes and Interfaces.