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(onfloatfor anf32,doublefor anf64); on a page module (above,Math.sin) or under--deterministica float%or%=is a call tostd/math.ts'sfmodF64in place offrem, whose libmfmodthat link lacks, anf32widened tof64and the exact result narrowed back; on the signed integer widthsnswwhere proven to fit and otherwisellvm.s*.with.overflowand a branch tonish_panic_overflow, plain through anish:unsafewrapping*call, nevernuw; integersdiv/srem(udiv/uremon an unsigned type) are preceded by a divisor check that branches tonish_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, xfor an integer,fneg float/fneg doublefor 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;!son a string isUnsupported 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;>>isashr(sign-filling) on a signed type andlshr(zero-filling) on an unsigned one;>>>is alwayslshr. A constant count is masked at compile time and emits noand. -
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 nonot). -
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) areOperator `<` 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(sox !== xis true for NaN); strings:nish_str_eq(content); arrays and objects:icmp eqon the pointer (identity);p === null:icmp eqagainstnull;a === undefined, for aMap.getresult 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:
brtovalueAtord, thenphi;selectfor aconstwith a literal or a name asd. -
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 neagainstnull, thenselectfor a literal or a name asd; otherwisebrtodandphi. -
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 eqagainstnullat each?.link's receiver, thenbrtonullish.default;phiatnullish.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
fawaits nothing; otherwisef's frame is laid out in the caller's,@f.resumeis called, and the caller saves its state and answersfalsewhile 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 withobjasthis(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 isUnknown 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 areUnknown builtin `Math.foo`(tests/cases/reject_unknown_builtin).
new
-
new C(args)for a class: allocatessizeof(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):nzero-filled elements;Tmust be a scalar, anish:simdvector (every lane zero) or aU | null(whose zero fill isnull); 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 witharray length out of rangebefore anything is allocated: past 2^31 − 1 under--number-mode i32, past 2^53 underf64, a negativei32ori64(a ranged integer is read as ani32, 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 asnew Array<i32>(n),new Array<f64>(n),new Array<i64>(n), with the same lowering (tests/cases/arr_typed_views), and nopushorpopon the result (Typed-array names have nopushorpop); 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 Functionandnew Proxyare forbidden (reject_new_function,reject_proxy).
Member access
-
s.lengthon a string: the UTF-8 byte length as anumber(tests/cases/str_length;reject_length_on_number,reject_unknown_property). -
a.lengthon an array: read-only (tests/cases/arr_length;Cannot assign to `length` of i32[],reject_arr_length_assign). p.fon a class or interface value (tests/cases/cls_point).-
Math.PI,Math.E(tests/cases/math_i32);process.argv,process.platform,process.arch(seeprocess);Arena.*(seeArena). Any other bare identifier before a dot isUnknown identifier `os`(CLI only). -
Member access on a
T | nullvalue 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 >= 0from a literal initialiser, fromi = w.length, from a test that reaches the access (if (i >= 0),0 <= i, the false arm ofi < 0), or from the type — anu8/u16/u32/u64index is never negative, and neither is aninteger<Lo, Hi>withLo >= 0. -
a bound read off the type. A declared range bounds its index from above as well: a
u8is below 256, au16below 65536 and aninteger<Lo, Hi>belowHi + 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 au8oru16b, because the conversion is azext. Au32oru64has no upper bound ani32fact 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.lengthfrom a test that reaches the access — a loop condition, anif, the right operand of&&, the statements afterif (i >= w.length) { return; }— or, throughconst n = w.length, fromi < n. A constant indexw[3]needsw.length >= 4instead, which a length guard (if (w.length >= 4)) or an array literal of known size gives. -
for a
u8,u16oru32index,toU32(i) < toU32(w.length)— ori < toU32(w.length)for au32— the same way: an unsigned index cannot be compared with thei32length as it is, its type is its lower end, and this is the upper one.toU32widens au8oru16and is the identity on au32, and of a length it can only answer the length or less (in f64 mode it is a saturatingfptoui), so theu32compare isi < w.lengthor stronger. Only in the test itself: au32copy of the length is not a length, becausetoU32(w.length) - toU32(1)wraps on an empty array. Au64index is not credited —toU32keeps its low 32 bits — and neither istoI32(i) < w.lengthon au32, which reads an index past2^31 - 1as negative (tests/cases/arr_bounds_unsigned_guard,arr_bounds_unsigned_guard_f64;arr_bounds_unsigned_guard_keptkeeps 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 inreturn,break,continue, or a call to the builtinpanic(…)orprocess.exit(…)(exitfromnish:processtoo). Only the builtins count: a parameter or local calledprocess, or a function parameter calledpanic, 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_exitandbounds_guard_shadowed_panickeep it).Map.keyAt,Map.valueAtandSet.keyAtinstd/collections.tsguard 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 checkeds.charCodeAt(i)either panic or leave0 <= i < w.lengthbehind, because the panic does not return; a checkedw[3]leavesw.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] = tcarries two checks, not four. The fact is taken where the emitter runs the check:v[i] = v[j]checksv[j]beforev[i], andv[i] op= xchecks beforexruns. 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 arearr_repeat_check_call,_push,_field_store,_reassignand_flow, andarr_repeat_check_panicpanics past the end on three of them).toI32(w.length)isw.lengthwherever a length appears above: in the hoistconst n: i32 = toI32(w.length), ini < toI32(w.length)and in a length guard. It is the spelling that compiles in both number modes — under--number-mode f64.lengthis anf64, andi < w.lengthwith ani32iis a type error — so a program written for both (std/textis 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 saturatingfptosiof an exact integer, which can only answer the length or less, never a negative. Only the builtin counts: a user function namedtoI32wins 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 doestoI32of 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, andconst m: i32 = toI32(ys.length)does not undo theconst n: i32 = toI32(xs.length)above it (perf_bounds_toi32,perf_bounds_toi32_f64). -
i - candw.length - c(ca non-negative literal) carry bounds too: removingclowers every floor ofibyc—i >= 1, whichif (i !== 0)on a non-negativeigives, leavesi - 1 >= 0— and withc >= 1turnsi <= w.lengthintoi - 1 < w.length;w.length - 1is below the length whatever the array holds. A copylet j = ihas every boundihas (tests/cases/arr_range_call_countdown). -
i + c(ca literal of 1 or more) is an index too, and a test on it is a bound oni.i + c < w.lengthsays the length reachescpasti, and so doesi + c < nwithna hoisted length;i + c <= w.lengthreachesc - 1;i + c < N, for a literalN, isi < N - c. An accessw[i + k]then needsi >= 0and a reach of at leastk, or a literal boundi < Mwithw.length >= M + k, so a loop that reads four elements a pass underi + 3 < w.lengthkeeps none of its four checks. A checkedw[i + c]that ran leavesi + c < w.lengthbehind, and nothing abouti >= 0. Both halves rest on the sum being exact: a signedi + cpanics on overflow or is proven not to overflow, so it is never a wrap to a small value. For an unsignedi, whose add wraps by definition, an offset proves nothing and the check stays (tests/cases/arr_bounds_offset;arr_bounds_offset_reachreads one past its reach andarr_bounds_offset_floorhas 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 valuesecan 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)ofi32operands (ortoU8,toU16,toU32of theirs), keeps the quotient's range, since that conversion emits nothing. If the lowest is not negative and the highest is below a lengthwis known to have (w.length >= n, from an array literal, anew Array(n), a guard or a check that ran), the access needs no check:freeMaxs[c + r]andfreeMins[c - r + 7]withrandceach below 8 into arrays made with 16, orcells[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 signedi32ori64; an unsigned index, whose arithmetic wraps by definition, and anf64one keep their check. The length is the one the index leaves behind, so a call inside the index that shrinks the array, anewwhose constructor does included, proves nothing (tests/cases/arr_bounds_range;arr_bounds_range_pastreaches the length,arr_bounds_range_negativegoes below zero, andarr_bounds_range_callandarr_bounds_range_newshrink the array, and each keeps its check and panics;arr_bounds_range_keptkeeps its own). -
A helper's fresh array has the length it was built with. A length
wis known to have comes from an array literal ornew Array(n)written in place, and also from a call of a function that builds one and returns it:const xs = filled(8), orthis.rows = filled(8), startsxsorthis.rowswith 8 elements whenfilleddeclaresconst arr = new Array<T>(n)(a typed-arraynewor an array literal too), touches it only by indexing it, readingarr.lengthandarr.push(...), and returns it. Everyreturnhands 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'sLo. 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 ortry; 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 storerecv.f = filled(8)gives one only whenrecvisthisor aconstlocal, 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_paramand_through_memoeach keep their check and panic;tests/link/arr_bounds_returned_importkeeps its check;arr_bounds_returned_keptkeeps 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 && banda || b,a's facts are proved beforebruns, so they reach the code the condition guards only if nothingbdoes can undo them. A call, an assignment or a field store inbdrops them by the rules below, andi < xs.length && xs.pop() > 0proves nothing aboutxs[i](arr_bounds_cond_effect,arr_bounds_cond_assign, and the path formsarr_path_cond_*: a call, a store, a root reassignment,||, a ternary, awhile, 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= vchecks beforevruns and is judged there.a[i] = vreadsaandi, runsv, then checks, so it is proved only ifvleavesiandaalone: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, andg.hs[i].n = (i = 0)is judged that way round (arr_path_store_rhs_field); -
a
forupdate and ado/whilecondition are reached from the end of the body and from everycontinue, so they are judged against what holds on all of those edges: acontinuebranch 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). Acontinuein aswitchclause 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
foror awhileis reached where the condition fails and from everybreak, 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). Abreakin aswitchclause leaves only theswitch; -
r.unwrapOr(d)evaluatesdandr.expect(m)evaluatesmonly whenris anErr, so neither argument proves anything after the call. Whatdmight undo is undone, andmis 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 = ysendsh.xs's facts even wheregis 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.xsforconst 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
newthat may resize an array or store to a field on the path, for a string path as well as an array one: a callee maypushorpopthe array or store a new value in the field, and apopthrough a second holder of the same array is a call too (arr_path_callee_pop,arr_path_callee_string,arr_path_alias_shrink).charCodeAtand the builtintoI32call 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: aninterfaceis fields and nothing else, so copying one into a slot cannot be told apart from pointing at it, while aclasshas identity — a constructor and methods that run on one object — and every other position in the language passes a class value by reference. -
an
interfacesome classimplements. That array is the language's only polymorphic container (tests/cases/cls_implements_prefix): aShape[]holds aSquareand aCircleat once, and both are longer thanShape, so a value slot would copy the prefix and drop the rest. The property is program-wide — one compilation, one layout forShape[]in every module of it. -
a
T | nullof any kind: a null element has no bytes to be, andnullis 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] = pand[p, q]copysizeofbytes, exactly as a C array of structs does; afterwardsps[i]andpare 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.
pushmay move the block (nish_array_growbumps a fresh one and copies) andpophands the slot back to the nextpush, so a pointer taken before either names memory that is no longer the element. Aconstbound toa[i]ora.pop(), and the variable of afor (const p of a), are element references; using one after apushorpopon the same array — or after a call that could push through it, which is any call handed the array as a non-readonlyparameter — 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, sinceqoutlives it), and either side ofc ? p : rorm ?? 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 apushat 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;, nevery = x.f = e): an array literal ofnelements ([]is one, withn = 0),new Array<T>(n)or a typed-arraynewwith an integer literaln, 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 onlynew Array<T>(p), a literal, or aconstlocal initialised with one, which it only indexes and reads.lengthof (filledBooleans(8)in AWFY Queens,tests/cases/cls_inline_array_call). The slot is sized for the largest lengthKany assignment gives; the header still records the current length, so.lengthanswers what it always did. -
Nothing takes the field as a value.
x.f[i](read, write, compound) andx.f.lengthare the only uses. Reading it into a local, passing it to a function, returning it, iterating it withfor ... of, capturing it, or calling any method on it —pushandpopincluded — 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]evaluatesx.fbeforei, andx.f[i] = vbeforev; when the index or the value calls something that can assignf(directly or through its own calls), the access uses the arrayfheld 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
exportdecides it for a call (hostVisibleinsrc/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
implementsan interface, and its element type is not a record (an inline record would hand out interior pointers into the object). -
Kelements fit in 256 bytes andKis 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 ornew Arraywrites the slots in place and allocates nothing, which is faster than the pointer layout at everyKmeasured, 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 ofsrc/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.

