Types
Every Nish type maps 1:1 onto one LLVM first-class type. There is no
boxing, no runtime type tag, no structural subtyping (except
implements, below), and no implicit conversion of any kind: two values are
compatible only when their types are identical.
Read from the top down as deep as you need: which type to write, what behaves differently from TypeScript, how each type sits in memory and crosses to C, then the exact rules.
Choosing a type
| To hold | Write |
|---|---|
| A whole number | number, or i64 beyond ±2³¹ |
| A fraction | f64; f32 for half the memory or twice the SIMD lanes |
| A byte, or bits that wrap | u8, u16, u32, u64 |
| True or false | boolean |
| Text | string |
| A list | T[], or readonly T[] when nothing writes it |
| A record | class C, or interface I |
| One of a fixed set of names | enum K |
| A value or nothing | T | null |
| One of several kinds of record | A | B, a tagged union |
| A value or an error | Result<T, E> |
| A function the caller picks | (x: T) => U on a parameter |
| No value | void, as a return type |
Coming from TypeScript
-
numberis one fixed type. It isi32by default andf64under--number-mode f64; nothing else is ever its lowering.f64is available in both modes. -
Nothing converts on its own. Each numeric type is its own type, so
u32 + i32andf32 + f64are type errors. Convert withtoI32,toU8,toF64and the rest (Type rules). -
Signed overflow panics (Semantics decisions),
in
i32andi64alike;wrappingAdd,wrappingSubandwrappingMulfromnish:unsafewrap instead. Unsigned integers always wrap. Ani64takes a literal only by context. - Strings are immutable. Sharing one is always safe, and nothing is ever copied.
-
An array has one element type, and every index is bounds-checked.
readonly T[]refuses every write (Readonly arrays).Int32Array,Float32Array,Float64ArrayandBigInt64Arrayare only other names fori32[],f32[],f64[]andi64[](sameTypeholds, andnew Int32Array(n)isnew Array<i32>(n)), except that a receiver spelled with one has nopushorpop, as in TypeScript (Typed-array names have nopushorpop). -
Only a class, interface, array, string or function reference can be
null. A nullable value allows only=== null/!== null, assignment, narrowing and a??default (Nullable types); a nullable function reference is the tag0(Function references). -
An
enumis its own type, not a spelling ofi32:sameTypefails against every other type (Enums). -
A record's type has a name. Its fields are declared once, in an
interfaceor aclass; an inline object type,{ x: i32 }, is refused wherever a type is written, andtypeonly renames a type that already exists (Interfaces and object literals, Type aliases). -
A function reports failure with a
Result, the only way it can; the payload is unreachable until the discriminant is tested (Result and error handling). - A function type written inline on a parameter of a top-level function names the callee chosen at each call (Function parameters); anywhere else it is the type of a reference to a capture-free top-level function, which can be held, passed, called and compared, nothing else (Function references).
In memory and in C
A number, a boolean or an enum is a plain value. The C column is the
type --emit-header writes; a dash means the type cannot cross to C.
| Type | LLVM | Size / align | C |
|---|---|---|---|
i32, number |
i32 |
4 / 4 | int32_t |
f64, number in f64 mode |
double |
8 / 8 | double |
f32 |
float |
4 / 4 | float |
i64 |
i64 |
8 / 8 | int64_t |
u8 |
i8 |
1 / 1 | uint8_t |
u16 |
i16 |
2 / 2 | uint16_t |
u32 |
i32 |
4 / 4 | uint32_t |
u64 |
i64 |
8 / 8 | uint64_t |
boolean |
i1 |
1 / 1 | bool |
enum K |
i32 |
4 / 4 | — |
void |
void |
— | void |
-
Signed integers are two's-complement, and floats IEEE-754. An unsigned
type shares the LLVM type of its signed twin, and its signedness lives in
the operations (Unsigned integers).
i64andu64cross to JavaScript as abigint. - A
booleaniszeroextat the ABI boundary. -
K.Ais the member's integer (its ordinal, for a string enum), so nothing is emitted for a numericenumdeclaration; a string enum adds one private table of its members' strings (String enums).
Every other type is a pointer, 8 bytes and 8-aligned, to:
-
string, LLVMi8*:{ i64 len, i8 data[len], i8 0 }, 8-aligned and NUL-terminated, sodatais a C string, andlenis the UTF-8 byte length. Literals are module constants; every other string lives in the arena. In C, aconst nish_str *parameter and anish_str *result. -
T[], LLVM%struct.nish_array*: a 24-byte header,{ i64 len, i64 cap, i8* data }, wheredataholdscapelements ofsizeof(T). In C, aconst nish_array *parameter the function only reads, and anish_array *parameter it writes through or anish_array *result. readonly T[]: the same array, aconst nish_array *parameter in C.-
Int32Array,Float32Array,Float64Array,BigInt64Array: the arrays they name. They name the JS typed array a host passes (wp8-interop.md). An unsigned array crosses to a host asUint8Array,Uint16Array,Uint32ArrayorBigUint64Array(wp30-bytes-interop.md), but those four are not spellings in the language: a program writesu8[]. -
class C,interface I, LLVM%struct.C*:%struct.C = type { fields in declaration order }, laid out as clang lays out the same C struct, with no header and no vtable. An object is arena- or stack-allocated (Memory model). Not in C. -
T | null: whateverTpoints to;nullis the constantnull. Not in C. -
A | B, LLVM%union.tagged*:%union.tagged = type { i32 }, the tag every variant begins with. A variant converts by abitcast, and only the tag is read (Discriminated unions). Not in C. -
Result<T, E>, LLVM%struct.nish_result.<T>.<E>*:{ i1 ok, T value, E error }, one struct per pair of payload types, laid out as clang lays out the same C struct. It is passed and returned as onei64when both payloads are scalars of at most 4 bytes, and as{ i1, i32, i32 }, the tag and one slot per arm, between two non-exported functions of one module. In C, anish_result_<T>_<E>_wordby value, and astruct nish_result_<T>_<E> *otherwise.
A function type, (x: T) => U, written inline on a parameter of a
top-level function is no value at all: it has no LLVM type and no parameter,
and the callee is compiled into the instantiation's body as a direct call.
Anywhere else it is a function reference, LLVM i32, 4 / 4: a tag naming
one of the program's functions of that signature, never an address
(Function references). Not in C.
Sources: src/types.ts (TypeTable.llvmType, alignOf; a type is
interned, and two types are the same type exactly when they are the same
i32),
src/interop-abi.ts (cType); tests/cases/i64_basic, f64_mode,
str_literal, arr_literal, cls_point; the ten-struct layout test
tests/layout/structs.ts (offsets and sizeof cross-checked against clang,
wp2-classes.md).
Type rules
-
Accepted type syntax:
number,i32,i64,u8,u16,u32,u64,f32,f64,boolean,string,void,T[],Array<T>(exactly one type argument:`Array` needs exactly one type argument),readonly T[]andReadonlyArray<T>(Readonly arrays),Int32Array,Float32Array,Float64Array,BigInt64Array(no type argument:`Float64Array` takes no type argument (it is an alias of `f64[]`),tests/cases/reject_arr_typed_view_type_annotation_arg; aFloat64Arrayis anf64[]wherever one is expected and vice versa,tests/cases/arr_typed_views,reject_arr_typed_view_mismatch), the name of atypealias or anenum(numeric or string) declared or imported in the module (Type aliases, Enums), one of that enum's members as a type,Kind.If(Enums), and the name of a class or interface declared or imported in the module. Anything else isUnsupported type `...`/Unsupported type reference `...`(src/annotations.ts;tests/cases/reject_union_type,reject_function_type).keyof Tis one of those,Unsupported type `keyof T` (Phase 1 supports number, i32, i64, u8, u16, u32, u64, f32, f64, boolean, string, void)(NL2038), and it is refused in a generic declaration nothing instantiates too, because the rule is a pass over the whole module rather than a step in resolving an annotation (reject_type_keyof,reject_type_keyof_template).keyofis the operator only before a type on its own line, so a class a program nameskeyofis still a type everywhere else (tests/parser/names-declarations.ts).T | null(ornull | T) is accepted whenTis a class, interface, array, string or function reference type; a scalar is`i32 | null` is not supported: only class, interface, array, and string types can be nullable (a scalar has no null value)(tests/cases/reject_nullable_scalar). A type may be parenthesised, and(T | null)[]is where it matters:T | null[]groups the other way and means "aT, or an array ofnull". The parentheses only group — the type inside them is the type — so(A | B)[]is held to the union rules asA | Bis (tests/cases/cls_parenthesized_type,reject_paren_union_type). A union of tagged classes and interfaces is a discriminated union. -
No implicit conversion.
const y: f64 = xwithx: numberin i32 mode isCannot initialize f64 variable ... with i32(CLI only);x + nwithx: i64,n: numberis rejected (tests/cases/reject_i64_mixed); convert explicitly withtoI32,toI64,toU8,toU16,toU32,toU64,toF32,toF64(tests/cases/conversions,u_conv_roundtrip,f32_conversions). Width and signedness are part of the type, sof32 + f64isOperator `+` requires two operands of the same numeric type ... got f32 and f64(tests/cases/reject_f32_mixed) and, even when the LLVM type is shared,u32 + i32isOperator `+` requires two operands of the same numeric type ... got u32 and i32(tests/cases/reject_u_mixed_signedness), and so isu8 * u32(tests/cases/reject_u_mixed_widths). -
Field and element types may be any type except
void(Array elements cannot be void,... cannot have type void). Arrays of arrays (tests/cases/arr_nested), arrays of strings (tests/cases/arr_strings), arrays of class instances and class fields of array type work (CLI only). -
integer<Lo, Hi>is a ranged integer (wp31-ranged-integers.md): ani32the compiler knows lies in[Lo, Hi]. It is ani32in the IR, in memory and at the ABI, in both number modes, andtscreads it as anumberalias (runtime/nish.d.ts).integer<0, 0xFF>andinteger<0, 255>are one type, spelledinteger<0, 255>in a diagnostic and mangledrng.p0.p255in a symbol (rng.m128.p127forinteger<-128, 127>), soBox<integer<0, 255>>is%struct.Box$rng.p0.p255(tests/cases/rng_param,rng_generic).-
The bounds are two integer literals, a sign allowed, with
Lo <= Hiand both ini32. Each other spelling is refused:`integer` needs exactly two bounds, e.g. `integer<0, 255>`(reject_rng_arity,reject_integer_use);A bound of `integer<Lo, Hi>` must be an integer literal, got `MAX`, a constant or a type (reject_rng_bound_not_literal,reject_rng_bound_type);Non-integer literal `1.5` where a bound of `integer<Lo, Hi>` is expected(reject_rng_bound_float);`integer<10, 0>` is an empty range(reject_rng_empty); andBound `4294967295` of `integer<Lo, Hi>` is outside i32(reject_rng_bound_i32,reject_rng_bound_i32_negative). A numeric literal type is parsed wherever a type is and is legal only as one of these bounds:const x: 5andBox<3>areA literal type `5` is only allowed as a bound of `integer<Lo, Hi>`(reject_rng_literal_type,reject_rng_literal_type_argument). -
Entering a range is checked. An annotated initialiser, an assignment
(
=, the compound forms,++and--), an argument to a function, a method or a constructor, areturn, a field or object-literal field, an array-literal element, an element store andpushare entries. The source must be ani32or another ranged type — au8is not aninteger<0, 255>(reject_rng_from_u8), and under--number-mode f64anumberis anf64that enters throughtoI32(x)(reject_rng_from_f64). A literal inside the range and a value of a range inside this one cost nothing; a literal outside it isLiteral `12` is outside the range of integer<0, 9>(reject_rng_literal_outside,reject_rng_literal_outside_negative). Anything else is compared once and the program panics outside the range, printingvalue out of range: expected integer<0, 255>and exiting 1 (rng_param,rng_entries,rng_bitwise,rng_entry_panic,rng_entry_range_panic,rng_entry_push_panic,rng_entry_bitwise_panic). The check is the type's meaning, souncheckedGetanduncheckedSetkeep it, and awrapping*call changes only the arithmetic before it. Under Node nothing is checked, which RUN_UNDER_NODE.md records. -
An entry the compiler can prove is free (WP31 §8). The bounds proof of
Element access judges each entry where the value is
computed, and writes no compare where it already places the value inside
the range. Two sources can be proven. A local is proven one end at a
time: the lower end when
Lois-2147483648, orLo <= 0and the local is known non-negative; the upper end whenHiis2147483647, or the local is known belowHi + 1— by a loop condition, a guard that reaches the entry, a literal it was bound to, or its own declared range. AndtoI32(x)of au8, au16or a ranged value lands inx's declared range, soconst r: integer<0, 255> = toI32(b)costs nothing for au8b.for (let i = 0; i < 256; i++) { const b: integer<0, 255> = i }is the shape §7 recommends, and the loop condition proves it (tests/cases/perf_rng_quiet); so is a call that hands a loop counter to a ranged parameter, which leaves wp31 §12'sgetByteprogram with no check at all (perf_rng_getbyte). A lower end above zero is never proven from a guard, because the proof records no lower bound but zero, and the sum a compound assignment or an increment stores back is never proven at all; both keep their check. A check that survives inside a loop is a performance warning (Diagnostics), and a counter declared with a range is the loop that warns and then panics (perf_rng_counter). -
Leaving a range is free. Every operator reads a ranged value as
i32, sor + 1is ani32,r < 9compares twoi32s andtoI64(r)is asext; mixing one with ani32is never an error, and nothing computes a range. The range survives where nothing is computed: aconstwithout an annotation keeps it and aletwidens toi32(rng_widen); a read of a ranged field, element or result keeps it; and a type argument keeps it, soidentity(r)isidentity<integer<0, 9>>(rng_generic). A counter declared with a range fails its lasti++, which is why the range goes on the value used rather than on the counter (rng_entry_panic). -
Where a range may not go. A
declare functionmay not mention one, because the C side never promised it (reject_rng_declare_function,reject_rng_declare_function_return), andnew Array<integer<1, 9>>(n)is refused because its zero fill is outside the range (reject_rng_array_zero_fill). Under-ga ranged type is aDW_TAG_typedefofintnamedinteger<0, 255>(dbg_rng). -
The name.
integeris on the list of built-in type names, sotype integer = …andenum integerare refused the waytype string = …is (reject_integer_alias,reject_integer_enum). A class, interface or function may not take it either, becauseinteger<0, 255>would then mean two things in the module that declared one:`integer` is reserved for ranged integers (`integer<Lo, Hi>`) and cannot be declared as a class(reject_integer_class,reject_integer_interface,reject_integer_function). A module constant or a local calledintegeris a value, not a type, and is still accepted.
-
The bounds are two integer literals, a sign allowed, with
Numeric literals
A separator goes between two digits and nowhere else, as in TypeScript.
1_000_000, 0xFF_FF and 1_234.5_6 are the values their digits spell, and
so is 1e1_0 in an exponent (tests/cases/math_numeric_separators). Any
other _ is refused by the lexer with TypeScript's words, one error for the
whole literal: after a radix prefix (0x_FF,
tests/cases/reject_separator_after_prefix), at the end (10_,
reject_separator_trailing), either side of the point (1_.5, 1._5:
reject_separator_before_dot, reject_separator_after_dot), straight after
the exponent marker or its sign (1e_5, 1e+_5, reject_separator_exponent),
before the BigInt suffix (0xFF_n, reject_separator_before_bigint_suffix)
and after a leading zero (0_1, reject_separator_leading_zero) are all
Numeric separators are not allowed here (TS6188), and two in a row
(1__0, 0xF__F, reject_separator_doubled) is
Multiple consecutive numeric separators are not permitted (TS6189). The
parser still reads the literal, so the next token does not cost a second
error, and a bound of a ranged type is refused the same way
(integer<0, 0x_FF>, reject_separator_ranged_bound).
A decimal literal does not start with 0 and another digit, as in
TypeScript, and as in a JavaScript module, where Node refuses one as a
SyntaxError. 0, 0.5 and 0e1 are legal, and so is every radix prefix
(tests/cases/leading_zero_legal). A run of octal digits after the zero is a
legacy octal literal: 017, and 017.5 or 07_1 with it, are
Octal literals are not allowed. Use the syntax '0o17' (TS1121), naming the
0o spelling of those digits (tests/cases/reject_leading_zero_octal). Any
other, such as 09, 08.5 or 09e1, is
Decimals with leading zeros are not allowed (TS1489,
reject_leading_zero_decimal). The lexer refuses it and it costs one error,
as a misplaced separator does. Before issue #271, 017 compiled as seventeen.
There are two differences from tsc. tsc reads 017.5 as two tokens and
reports a second error for the .5, but the lexer reports one error for the
whole literal. And -017 suggests 0o17, not -0o17, because the lexer does
not see the sign.
Every spelling is read at the value it spells, in every numeric type,
as TypeScript reads it (#267): 0b1010 is 10, 0o17 is 15, 1_000 is 1000
and 1e5 is 100000 as an i32, an i64, an f64, a module constant or a
bound of integer<Lo, Hi> (tests/cases/literal_spellings). A binary or
octal literal past 2^53 rounds once, to the double TypeScript reads. An
exponent is an integer when its value is one, so 100e-2 is the integer 1 and
1e-1 in an integer position is Non-integer literal `1e-1` where i32 is expected (reject_literal_exponent_fraction); a point always spells a
float. The range rules below read the same value, so 1e10 and a 33-bit
0b literal are Literal `1e10` does not fit in i32
(reject_literal_exponent_overflow, reject_literal_binary_overflow), and an
i64 module constant past 2^53 is refused as an i64 literal is
(reject_literal_const_precision).
A numeric literal has the mode's default type (i32, or f64 in f64 mode)
unless its immediate context demands another numeric type, in which case it
takes that type (src/expressions.ts, checkNumericLiteral;
tests/cases/i64_basic, math_i32, conversions):
| Context | Example | Literal type |
|---|---|---|
| annotated initializer | let x: i64 = 5 |
i64 |
return |
return 5 in a function returning i64 |
i64 |
| argument to a user function | square(5) with x: i64 |
i64 |
| other operand of a binary operator with a known type | x * 2, 2 * x, x < 5, x = 5 |
the other operand's type |
Math.min / Math.max |
Math.max(x, 0) |
the other operand's type |
f64-only Math.*, toF64 |
Math.sqrt(2), toF64(3) |
f64 |
toF32 |
toF32(2.75) |
f32 |
process.exit |
process.exit(1) in f64 mode |
i32 |
Number |
Number(2.5) in i32 mode |
f64 |
element of an array literal whose own context is a T[] |
const bytes: u8[] = [0, 255] |
u8 |
| a class field's literal initializer | b: u8 = 255 |
u8 |
| argument to a constructor | new Pixel(255, 0, 0) |
the parameter's type |
| a field or element assignment target | p.b = 255, bytes[i] = 255 |
the field's / element's type |
| a ternary arm, from the conditional's own context | const x: f64 = c ? 1.5 : 2.5 |
f64 (tests/cases/f64_ternary_literal) |
-5 and (5) count as the literal, on either side of a binary operator:
-1 / z and (1) / z with z: f64 type their literal from z exactly as
1 / z does, and so do -1 * big on an i64 and -1 < z
(tests/cases/math_literal_operand_forms). The other operand still has to be
one of the shapes "known type" names below, so -1 * (cp >> 6) in f64 mode is
refused for the same reason 0xc0 | (cp >> 6) is
(tests/cases/reject_neg_literal_unpeekable). The table is the whole list, so a
position that is not on it leaves the literal at the mode's default however
obvious the intended type looks: an object literal's property value is not on
it, so const p: Pixel = { b: 255 } is Field `b` of `Pixel` expects a value of type u8, got i32 and has to be written toU8(255)
(tests/cases/reject_struct_field_u8, and reject_struct_field_f64 for the
same position in f64 mode); nor is a Result payload, so Ok(3) for a
Result<i32, string> is refused in f64 mode
(tests/cases/reject_res_ok_f64), as unwrapOr's fallback is
(reject_res_unwrap_or_f64); and nor is a method's argument, which is why
the table says a user function and a constructor — b.get(-1) on a method
whose parameter is an i32 is an f64 in f64 mode
(tests/cases/reject_method_arg_literal).
xs.push(3) and xs.indexOf(3) are on the list only through a receiver that
is a plain name: b.xs.push(0) is not (reject_push_field_literal). "Known type" means an already-checked
left operand, a variable, a field or element of one of those, or a call to a
user function or to
toI32/toI64/toU8/toU16/toU32/toU64/toF64. Only the literal's immediate context counts: in i32
mode const f: f64 = 0.1 + 0.2 is rejected because 0.1 is an operand of
+ whose other operand has no known type yet; write const a: f64 = 0.1; const f = a + 0.2 (CLI only). The same rule refuses const b: u8 = 1 + 2,
which is a sum of two i32 literals rather than a literal in a u8 context
(tests/cases/reject_bin_operand_context), and 0xc0 | (cp >> 6) in f64 mode,
because a shift is not one of the shapes "known type" names however plainly it
is an integer: give it a name first, or write toI32(0xc0). A literal in an integer context must be integral
(Non-integer literal `1.5` where i64 is expected,
tests/cases/reject_i64_literal_float); in an i64 context it must also be
at most 2^53 in magnitude (exceeds 2^53 and cannot be written exactly,
tests/cases/reject_i64_literal_precision; an unsigned context has the same
rule, reject_u64_literal_precision) because a numeric literal is read as a
double, as TypeScript reads it, so a larger one is already rounded. Every one of these messages quotes the
literal as it is written, not as the parser cooked it: 0x1FF reads back
as 0x1FF and a rounded literal as the digits in the file. The one exception
is a separator, which the parser drops, so 1_000_000_000_000 in an i32
context reads back as Literal `1000000000000` does not fit in i32. In an unsigned context it must also be non-negative
and fit the width: const b: u8 = -1 is
Negative literal `-1` where u8 is expected (u8 is unsigned)
(tests/cases/reject_u_negative_literal) and const b: u8 = 256 is
Literal `256` does not fit in u8
(tests/cases/reject_u_literal_too_wide). The largest u64 values are past
2^53 and cannot be written at all; build them arithmetically
(toU64(0) - toU64(1) is 2^64 - 1, tests/cases/u_print). The same holds for
the i64 minimum, -2^63: -9223372036854775808 is refused like any literal
past 2^53 (NL2055), although 2^63 happens to be an exact double and its
negation fits. The 2^53 bound is what keeps every literal exact in both
readings, and admitting this value would be a one-literal exception to it for
no gain: in the TypeScript reading i64 is number, so the value is a double
there anyway (NL8009). Build it from the widest literal instead:
const lo: i64 = -9007199254740992; const min: i64 = lo << 10; is -2^63
(tests/cases/neg_literal_i64_min).
Unsigned integers
u8, u16, u32 and u64 are unsigned integers with wrapping arithmetic.
LLVM has no unsigned types, so they lower to i8, i16, i32 and i64 and
the signedness lives entirely in the operations; representing an unsigned
value therefore costs nothing at all, and a u8 field packs a struct as
tightly as a C uint8_t does.
| Operation | On i32 / i64 |
On u8 / u16 / u32 / u64 |
|---|---|---|
+ - *, unary -, ++/-- |
add nsw sub nsw mul nsw where proven to fit, else llvm.s{add,sub,mul}.with.overflow and a branch to the panic; plain through wrappingAdd/wrappingSub/wrappingMul from nish:unsafe |
the same instructions, never flagged or checked: unsigned overflow wraps in both modes |
/ % |
sdiv / srem after a two-part divisor check |
udiv / urem after a single compare (Checked integer division) |
< <= > >= |
icmp slt sle sgt sge |
icmp ult ule ugt uge |
>> |
ashr |
lshr |
>>> |
lshr |
lshr — the same instruction, so the two are synonyms |
=== !== |
icmp eq / icmp ne |
identical (the bits decide) |
| widening conversion | sext |
zext |
| narrowing conversion | trunc |
trunc |
to / from f64 |
sitofp / llvm.fptosi.sat |
uitofp / llvm.fptoui.sat |
Math.abs |
llvm.abs |
nothing: the value is already its own magnitude |
Math.min / Math.max |
llvm.smin / llvm.smax |
llvm.umin / llvm.umax |
console.log(x), `${x}` |
nish_str_from_i32 / _i64 |
zext to i64, then nish_str_from_u64 |
| overflow | a panic, "attempt to add with overflow", exit 1, except a nish:unsafe wrapping* call |
nothing, in either mode: unsigned overflow is defined as wrapping |
The consequences worth knowing:
-
A value above
INT_MAXbehaves.const big: u32 = 4000000000compares, divides and prints as four billion, where the same bits in ani32are -294967296 (tests/cases/u_compare_above_intmax,u_udiv_urem,u_print;tests/differential/corpus/u_div_cmp). -
Division is cheaper. Unsigned division has no overflow case, so its
check is one compare instead of three plus an
andand anor(tests/cases/u_div_one_check). -
Overflow wraps, and unlike the signed types it wraps in every mode:
(255: u8) + 1is0and(0: u8) - 1is255(tests/cases/u_arith_wrap,tests/differential/corpus/u_wrap). Nonuwis ever emitted, neither isnsw, and nothing is checked: wrapping is what hashing and bit-packing are written against, and it is half the reason the unsigned widths exist. -
Mixing is an error.
u32andi32are different types even though both arei32in the IR, and so areu8andu32; there is no implicit conversion anywhere in this language (tests/cases/reject_u_mixed_signedness,reject_u_mixed_widths). -
i32 >>> nstill yields the raw bits read as signed —-1 >>> 0is-1here where JavaScript gives4294967295— because ani32is the only place the result could go. That is now something to avoid rather than something to live with: useu32and the answer is4294967295(tests/cases/u_shift_logical,u_conv_roundtrip;tests/differential/corpus/u_convert_shift).
f32
f32 is 32-bit IEEE-754, LLVM's float. Every operation is the instruction
f64 already uses, one width down — fadd/fsub/fmul/fdiv/frem,
fcmp o*, fneg — and float division is never checked, exactly as for f64
(tests/cases/f32_arith). It exists because a struct of f32 is half the
footprint of one of f64 and gives twice the SIMD lane count:
class Vec3 { x: f32; y: f32; z: f32; hits: u32 } is 16 bytes where three
doubles alone would be 24 (tests/cases/f32_struct).
-
It is not
number.numberisi32orf64depending on--number-mode;f32is always spelledf32, and there is no implicit widening:f32 + f64isOperator `+` requires two operands of the same numeric type ... got f32 and f64(tests/cases/reject_f32_mixed). Convert withtoF32/toF64. -
A literal takes
f32from context the same way it takesf64(const tenth: f32 = 0.1), and is rounded to the nearest float when it is emitted. LLVM writes afloatconstant with the 64-bit hex of the double it equals and requires that double to be exactly a float, so0.1as anf32isfloat 0x3FB99999A0000000— the double nearest to(float) 0.1— and not thef64spelling0x3FB999999999999A(tests/cases/f32_constant). -
Printing gives JavaScript's digits for the float's value.
console.log(x)and`${x}`widen withfpextand reusenish_str_from_f64, soconst tenth: f32 = 0.1prints0.10000000149011612where the same literal as anf64prints0.1(tests/cases/f32_print;tests/differential/corpus/f32_round). -
The f64-only
Mathfunctions stay f64-only.Math.sqrt(x)on anf32is`Math.sqrt` requires an f64 argument, got f32(tests/cases/reject_f32_math_sqrt);Math.abs,Math.minandMath.maxdo work, throughllvm.fabs.f32and the float compare-and-selectminandmaxlower to, and so doesMath.sign. -
Float32Arrayisf32[], one more typed-array alias with no second layout, so a Node host'sFloat32Arraycrosses the boundary the way anInt32Arrayalready does.
Shifts
<<, >> and >>> take two operands of one integer type and produce that
type. There is no implicit conversion, so the shift amount has the same type as
the value (Operator `>>` requires two operands of the same integer type, got u32 and i32, tests/cases/reject_u_shift_mixed), and f64 has no shift at
all.
>> is an arithmetic shift on a signed type (ashr, sign bit replicated) and
a logical one on an unsigned type (lshr, zeros in); >>> is always lshr,
so on an unsigned type the two operators are synonyms and code that is generic
over a width may spell either (tests/cases/u_shift_logical).
The count is masked to the operand width rather than left undefined, which
is what makes x << 33 mean x << 1 instead of the poison LLVM produces for a
shift at or beyond the width. The mask is 31 at 32 bits and 63 at 64,
matching JavaScript; u8 and u16 mask to 7 and 15, their own widths,
since JavaScript has no narrow unsigned type to be compatible with
(tests/cases/bit_shift_narrow). A literal count is masked in the emitter and
written out already masked, so x << 3 is one instruction and no and reaches
the IR; only a computed count costs the mask
(Semantics decisions).
Nullable types
T | null is available for T a class, interface, array, string, or
function reference (tests/cases/mem_nullable;
wp6-memory.md). For a pointer type it is the same
LLVM pointer type as T with the constant null as one more
value, so nothing is boxed; null takes its type from context. A
function reference may be nullable too: it is an
i32 tag, and null is tag 0, which names no function
(tests/cases/fnref_nullable).
-
Where
nullmay appear: an annotated initializer (let p: Node | null = null), a field initializer (next: Node | null = null),returnin a function returningT | null, an argument, a field or element store, an object literal property,push, and a ternary arm (c ? p : nullisT | null). ATis accepted whereverT | nullis expected; the reverse is`null` is not a Node; declare the type as `Node | null`(tests/cases/reject_null_to_nonnull). -
new Array<T | null>(n)is allowed: the zero fill isnull(tests/cases/mem_nullable). -
Comparison:
p === null,p !== null,null === pare pointer compares (icmp eq ... null). Two nullable values cannot be compared with each other (Cannot compare two `string | null` values; compare each with `null`,tests/cases/reject_null_compare_two), and neither can a nullable and a plainT(CLI only): narrow first. -
Narrowing (
src/expressions.ts): inside the region a condition guards, a nullable variable (a local or parameter, never a property path) reads asT:Form Where pisTif (p !== null) A else Bin A; and after theifwhenBcannot fall throughif (p === null) A else Bin B; and after theifwhenAcannot fall through (return,break,continue,process.exit,panic)while (p !== null) A,for (...; p !== null; ...) Ain A, on every iterationp !== null && e,p === null || ein ep !== null ? a : bin a(and inbfor=== null)!cond,(cond),a && b,a || bcomposed as expected A narrowing ends at any assignment to the variable (
cur = cur.nextreads the narrowedcuron the right and then drops it) and before a loop whose body, condition, or update assigns the variable, because the second iteration sees the assigned value (tests/cases/reject_null_narrowing_assigned;reject_null_narrowing_leaksfor a use after the guarded block). Inside an&&or||chain the same holds operand by operand: an operand that assigns the variable ends its narrowing for every operand after it and for the region the chain guards, sop !== null && g((p = null) === null) && p.vis refused, and a test after the assignment narrows again (tests/cases/reject_null_narrowing_assigned_in_chain,res_proof_consumers). Constants and parameters keep their narrowing for the whole region. Property paths are not narrowed:if (n.next !== null) n.next.vis rejected; copy into a local first (CLI only). -
undefinedis not a value ofT | null, but the same narrowing rules hold for aconstbound toMap.get, withundefinedin place ofnull(WP32,MapandSet). -
Access to a field, method, element, or
.lengthon an un-narrowed nullable isCannot read property `value` of `Node | null`; check for null first(tests/cases/reject_null_field_access). -
A default:
a ?? don aT | nullanswersawhere it is notnullanddwhere it is, and runsdonly then, as TypeScript does:nullis nullish, so noundefinedis involved. Its type isTwhendis aT, astsctypes it, so the result needs no narrowing; adthat may itself benullkeeps theT | null(nullish_nullable,nullish_nullable_default_null).dtakes its context fromT, soxs ?? []and an object literal need no annotation; a barenull, or a ternary that may answer one, is checked intoT | null(nullish_nullable_default_context). The left operand is read once, so a property path works here although it never narrows:cur = cur.next ?? cur(nullish_nullable_field). A default that cannot have an effect, a literal or a name, is oneselect; any other is a branch tonullish.defaultand aphi. Anewin the default goes wherever the??goes, as a ternary's arm does (nullish_nullable_escapes), and an arena block is held to both operands (reject_using_arena_nullish).dmust be aTor aT | null:The right operand of `??` stands in for a missing value, so it must be `string`, the type of the value on its left; got `i32`(reject_nullish_nullable_default_type). The left operand may not be an element read, because past the end of the array Node readsundefinedand answersdwhile the bounds check panics:`??` cannot default an element read: past the end of the array, JavaScript answers the default and Nish panics (test the index against `length`, or read the element into a `const` first)(reject_nullish_element). A left operand that cannot benull(a scalar, or a nullable already narrowed toT) keeps Phase 0's refusal,Nullish coalescing `??` is forbidden in Nish (narrow with `!== null` instead)(reject_nullish,reject_nullish_nullable); thenullishfeature of the compatibility dialect admits it. -
An optional chain:
a?.b?.c ?? dreads each link only where the receiver before its?.is notnull, and answersdwhere one is, as TypeScript does. A?.is allowed only in a chain whose value is the left operand of a??, soundefined, whicha?.banswers on its own, is never a value: anywhere else, aconst, an argument, a template hole, an assignment target or behind a parenthesis that ends the chain, it is`?.` is allowed only in a chain that ends in `??`, whose default stands in when a link is `null`: write `a?.b ?? d`, or narrow with `!== null`(reject_optional_chain,reject_optional_chain_paren,reject_optional_chain_argument,reject_optional_chain_assign,reject_optional_chain_template); theoptional-chainingfeature of the compatibility dialect admits a chain that is a statement of its own. A link reads a field, a string's or an array'slength, or calls a method, and its receiver is read asT(optional_chain_field,optional_chain_order,optional_chain_generic,tests/link/optional_chain_modules). The chain's value is its last link's, typed with the default as aT | nullis above, so a number at the end works:o?.next?.id ?? -1is ani32. Only a?.link skips anull: a plain link after one reads what it is given, soa?.next.valuewith a nullablenextisCannot read property `value` of `Node | null`; a link of a `?.` chain that may be `null` needs a `?.` of its own: `a?.next?.value`(reject_optional_chain_link_nullable).?.on a receiver that cannot benull,this, a narrowed local or a builtin namespace, is`a` is never `null` here, so `?.` has nothing to skip: write `.`(reject_optional_chain_never_null,reject_optional_chain_narrowed,reject_optional_chain_this,reject_optional_chain_namespace).?.[i]andf?.()stay refused: an element read inside a chain isOptional chaining `?.` is forbidden in Nish (narrow with `!== null` instead)(reject_optional_chain_element_inner, whichoptional-chainingadmits), one that ends the chain isAn element read cannot end a `?.` chain or be what a `?.` tests: past the end of the array JavaScript answers `undefined` and carries on, and the bounds check panics (test the index against `length`, or narrow the array with `!== null` and read the element into a `const`)(NL1067,reject_optional_chain_element), and an optional call isAn optional call `f?.()` is not supported, with or without `--compat`: call `f()` directly, or narrow `f` with `!== null` first(NL1068,reject_optional_call), in both dialects. A chain that ends in an element read is the element-read refusal above (reject_optional_chain_element_last), and one that ends ingetis`h?.counts.get("a")` ends a `?.` chain in `get`: give the map a default first, then default what `get` answers(reject_optional_chain_map_get). Each?.lowers to anicmp eqagainstnulland a branch tonullish.default, which every link shares, and runs nothing after anulllink, an argument included. What a chain proves about an index holds only where its links ran, so a read after the??keeps its check (optional_chain_bounds). A call in a chain is held to every rule a call is (reject_optional_chain_lock,reject_optional_chain_channel), and aSecreteither operand of the??makes is refused as one nobody owns (reject_optional_chain_secret). -
Attributes: a nullable parameter or return loses
nonnullanddereferenceable;align 8,readonlyandnocapturefollow the usual rules (ARCHITECTURE.md).
Discriminated unions
A union of two or more variants, type Shape = Circle | Square | Tri, is a
pointer to whichever variant it holds, and its first field says which. A
variant is a class or an interface whose first field is its tag: a field
of an enum member type, conventionally
readonly kind: Kind.Circle = Kind.Circle (tests/cases/union_types,
tests/link/union_export across modules). The enum may be numeric or a
string enum, whose member is the tag in memory as its
ordinal (tests/cases/enum_string_union_tag).
enum Kind {
Circle,
Square,
}
class Circle {
readonly kind: Kind.Circle = Kind.Circle;
r: i32 = 1;
}
class Square {
readonly kind: Kind.Square = Kind.Square;
side: i32 = 2;
}
type Shape = Circle | Square;
const label = (s: Shape): string => (s.kind === Kind.Circle ? "circle" : "square");
Typed JSON reads and writes a union of classes by its tag (Typed JSON),
whose value on the wire is the tag member's name, or a string enum member's
string, unless the variant's tag option names another
(tests/link/json_enum_string).
Layout. Every union is the one LLVM type %union.tagged = type { i32 },
behind a pointer. Every variant begins with its i32 tag, so a variant
pointer is a union pointer by a bitcast, and reading the tag is a
getelementptr to field 0 and a load, whichever variant is there:
%4 = bitcast %struct.Circle* %3 to %union.tagged*
...
%0 = getelementptr inbounds %union.tagged, %union.tagged* %s, i32 0, i32 0
%1 = load i32, i32* %0, align 4
Shape | null is the same pointer with null allowed, as
Nullable types are.
What makes a variant. Each rule is checked where the union is spelled, and each has its own code:
-
A variant is a class or an interface that is not generic, so
type R = Ring<i32>named in a union is`Ring<i32>` cannot be a union variant: a variant is a class or an interface that is not generic, because its tag is a field it declares itself(NL2522,reject_union_generic_variant). A generic type spelled with its arguments inside the union,Circle | Ring<i32>, and a member that is a scalar, an enum or an alias of one get the general refusal,Union types other than `T | null` are forbidden in Nish (values have one fixed layout)(NL1053,reject_union_inline_generic,reject_union_untagged_scalar,reject_union_enum_alias_member,reject_union_scalar_alias_member,reject_union_type). -
Its first field is of one enum member type: otherwise
`Point` cannot be a union variant: its first field must be its tag, a field whose type is one member of an enum, such as `readonly kind: Kind.Circle = Kind.Circle`(NL2523,reject_union_untagged,reject_paren_union_type). A first field typed with its whole enum,readonly kind: Kind = Kind.A, holds a tag but types it as every variant's, so the union could not tell its variants apart by it; that is NL2559, which names the member to write:`First` cannot be a union variant: its tag `kind` has the whole enum `Kind` as its type, which every variant shares, so give it the one member it holds instead: `readonly kind: Kind.A = Kind.A`(reject_union_tag_whole_enum). -
The tag is
readonly: otherwise`Circle` cannot be a union variant: its tag `kind` must be `readonly`, because the union tells its variants apart by it(NL2535,reject_union_mutable_tag). -
All the tags come from one enum (NL2524,
reject_union_mixed_enums), the tag field has one name in every variant (NL2525,reject_union_tag_names), and no two variants share a tag (NL2526,reject_union_duplicate_tag). -
A union names at least two different variants, after aliases and nested
unions are flattened:
Circle | Circleis NL2527 (reject_union_one_variant).
Where a union goes. A union is the type of a local, a parameter, a
field, a return, an array element (Shape[], Shape[][], or the members
spelled in place, (Circle | Square)[]), or of any of those made nullable,
and a Map's value is any of those: Map<string, Shape>,
Map<string, Shape[]>, Map<string, Shape | null> (union_map_value).
A union is also a type argument: a generic class's (Box<Shape>,
Box<Box<Shape>>, Stack<Shape>, union_generic_class), a generic
function's or method's type parameter bound to one by its arguments
(union_generic_call), either side of a Result, Result<Shape, E> and
Result<T, Shape> (union_result), and nish/map's getOrInsert and
reserve on a Map<K, Shape> (union_map_helpers). The instance is
monomorphised as for any other type argument, so Box<Shape> is laid out as
a class with a Shape field would be, and a T slot holds the union's one
pointer.
An alias may name another union, which is flattened: with type Round = Circle | Square, type Shape = Round | Tri is the three variants. A value
of a variant, or of a union whose variants are all the wider union's,
converts to the union wherever the union is expected: an argument, a
return, an array literal under a Shape[] annotation, a push, a ternary
arm or a ?? default whose other side is the union
(tests/cases/union_forms), and the same places where a generic's T is
the union: a constructor's or a generic call's argument, Ok(new Circle())
in a function that returns Result<Shape, E> (union_generic_class,
union_generic_call, union_result). Equality on two unions compares the pointers, as
on any object.
Reading. The tag is the one member a union has until a test of the tag
narrows it (below): any other field or method is
`r` cannot be used on the union `Circle | Square`: a union has only its tag `kind` until a test of the tag narrows it to one variant
(NL2528, reject_union_member_field, reject_union_method_call, even when
every variant has it). It reads as the enum, Kind, so it compares, switches
and is passed as one. A union is read-only: a write through it is NL2529, even
to a field every variant has (reject_union_assign_tag).
Comparisons that cannot be true. As in tsc, comparing the tag with a
member no variant has is an error: s.kind === Kind.Tri when no variant is
tagged Kind.Tri is NL2531 (reject_union_disjoint_compare), and
case Kind.Tri: in a switch (s.kind) is NL2532
(reject_union_disjoint_case).
Narrowing. A test of a variable's tag narrows the variable, as in tsc.
Where s.kind === Kind.Circle holds, s reads as a Circle, so its fields
and methods are there; where it fails, s is the union of the variants left,
and when one variant is left it reads as that one
(tests/cases/union_narrowing):
const area = (s: Shape): i32 => {
if (s.kind === Kind.Circle) {
return 3 * s.r * s.r;
}
return s.side * s.side;
};
-
The test narrows the branch it guards: the
thenandelseof anif, the arms of a ternary, the right side of&&(where it held) and of||(where it failed), and the statements after anifwhose branch always leaves (return,break,continue, apanic(...)).!==narrows the other way round, and the operands may be either way round,Kind.Square === s.kind. -
Each
case Kind.X:of aswitch (s.kind)narrowssto its variant, anddefaultto the variants nocasenamed. Acasethat a previous one falls through into narrows nothing. -
A null test composes with it: on
s: Shape | null,s !== null && s.kind === Kind.Circle && s.r > 0readss.r. -
Where an
||held, either side may have made it hold, so the variable is what either side proved: pasts.kind === Kind.Circle || s.kind === Kind.Square,sis aCircle | Square, which has only its tag and whose tag is notKind.Tri. The same goes for the side of an&&where it failed, for an enum variable, for any number of arms and for===mixed with!==; an arm that tests something else leaves the variable as declared (tests/cases/union_narrowing_join;reject_union_narrow_or_if,reject_union_narrow_or_ternary,reject_union_narrow_and_false,reject_enum_narrow_or_if,reject_enum_narrow_or_ternary,reject_enum_narrow_or_three,reject_enum_narrow_or_mixed,reject_enum_narrow_and_false). -
The test may read the variable through an assignment, which answers the
value it stored:
(t = next()).kind === Kind.Squarenarrowst, as(k = next()) === Kind.Anarrows an enumk(reject_union_narrow_test_assign,reject_union_narrow_or_assign,reject_enum_narrow_assign). -
The variable is a parameter or a
letorconstlocal; a narrowedconststays narrowed in a data-parallel arrow that reads it (tests/link/union_narrowing_capture). An assignment to it drops what the tests proved, as for a nullable and a loop that assigns it drops it before its body (reject_union_narrow_dropped,reject_union_narrow_else_assign,reject_union_narrow_loop_assign). -
What a test proved holds past the statement that made it as far as every
way out of it agrees, as in
tsc. After anifwith anelse, the variable is what the arms that fall through left it, joined; after anifwhose one arm falls through, what that arm left, so a chain ofelse ifs whose branches all return leaves the variant no test named and an arm that assigns the variable leaves what it assigned (reject_union_narrow_else_if_chain,reject_union_narrow_arm_assign,reject_nullable_arm_assign). A block's early return narrows what follows the block. An enum local that anif, a ternary, a loop or aswitchstores a member into holds, after it, what it held before or any member stored (reject_enum_held_if_join,reject_enum_held_else_join,reject_enum_held_ternary,reject_enum_held_ternary_assign,reject_enum_held_loop_join,reject_enum_held_switch_join). The join after anifcovers every local and path either arm assigns, one first assigned in theelseincluded (reject_union_narrow_path_if_join,reject_union_narrow_path_if_test), and every one a test inside either arm narrowed, whether or not an arm assigns it: two arms that each leave whenk === Kind.AleaveknotKind.Apast theif, joined with what held before it (tests/cases/union_narrowing_tested_join;reject_enum_if_tested_join,reject_union_narrow_if_tested_join,reject_union_narrow_path_tested_join,reject_union_narrow_nullable_tested_join,reject_enum_else_if_tested_join,reject_enum_if_tested_outer). Aswitchjoins what each of its exits leaves: everybreakout of it, the fall off its last clause and, when nodefaultcovers every member, the case no clause matches; a clause that returns is no exit (tests/cases/union_narrowing_switch_join;reject_union_narrow_path_switch,reject_union_narrow_path_switch_late,reject_enum_switch_join,reject_enum_switch_unmatched), a variable only its clauses' tests narrowed included (reject_enum_switch_tested_join,reject_enum_switch_tag_tested_join). What held before theswitchholds again at the start of each clause and in the case no label matches, whatever an earlier clause stored (reject_union_narrow_switch_kept,reject_enum_switch_kept). A loop is followed to a fixpoint, astscfollows it: the head of awhile,forordoholds what reaches it before the loop, at the end of an iteration and at acontinue(through its update, for afor), joined until it no longer changes; after awhileorforcomes the head with its condition false, joined with everybreak, after adothe end of the body and itscontinues with the condition false, and after afor...ofthe head and thebreaks. A loop inside the body and aswitchinside it are followed the same way, anifor aswitchnarrowing its arms and clauses inside the loop as it does outside one (tests/cases/union_narrowing_loop_flow,tests/cases/union_narrowing_loop_reads;reject_union_loop_while_join,reject_union_loop_do_join,reject_union_loop_condition_reassigned,reject_enum_loop_for_join,reject_enum_loop_do_join,reject_enum_loop_top_of_body,reject_enum_loop_do_continue,reject_enum_loop_break,reject_enum_loop_for_of,reject_enum_loop_nested,reject_enum_loop_switch,reject_enum_loop_switch_store,reject_enum_loop_switch_while,reject_union_loop_switch). A variable the loop only tests, never writes, is followed too (reject_enum_loop_tested_while,reject_enum_loop_tested_do,reject_enum_loop_tested_break,reject_enum_loop_tested_inner,reject_enum_loop_switch_tested,reject_union_loop_tested_while,reject_union_loop_null_tested). A store holds what its value holds where the value is one of: a member; a local of a member type,const m: Kind.B; a call of a function that returns a member type; a field of a member type, or a call of a method that returns one, read throughthis, a local or parameter or a field of one, nullable or not; aconstthe loop declares once, read by its initializer; another enum variable; a union's tag; or a ternary of two of these, each arm read on its side of the condition (reject_enum_loop_ternary_store,reject_enum_loop_copy_store,reject_union_loop_tag_copy,reject_enum_loop_member_local,reject_enum_loop_member_call,reject_enum_loop_field_store,reject_enum_loop_method_store,reject_enum_loop_nullable_receiver,reject_enum_loop_body_const,reject_enum_loop_ternary_narrowed,reject_enum_loop_ternary_tracked,reject_enum_loop_ternary_self). A test against a member, a local of a member type or such a call narrows as outside a loop, and so does a test against another enum variable, by the members it holds there (reject_enum_loop_const_test,reject_union_loop_const_test,reject_enum_loop_held_operand,reject_enum_loop_held_single,reject_enum_loop_held_ternary,reject_union_loop_held_operand;tests/cases/enum_loop_held_several). Aforupdate runs after the body and before the next test, and is followed there (tests/cases/enum_loop_for_update;reject_enum_loop_for_update_store,reject_enum_loop_for_update_cond), and is checked when the body is one refused statement, so both errors are reported (reject_for_update_after_body). A store of any other value holds the whole declared type. Where the loop holds a shape the fixpoint does not follow, a local or path holds, after it and throughout it, every member stored anywhere in it, which may be more thantscknows ("Accepted here, refused bytsc", below). -
A tag compared with an enum variable narrows on the side where they are
equal:
s.kind === k, withkholdingKind.Circle | Kind.Square, makessaCircle | Squarethere, andj === kleaves the enumjone ofk's members. Where they differ, nothing is known, sincekmay hold either, unlesskholds one member, which is then left out (tests/cases/union_narrowing_arms;reject_union_narrow_tag_variable,reject_enum_compare_variable). -
A tag tested through a path — a field
h.k,this.k, a field of a fieldh.s.kind, a literal indexxs[0].kind— stays narrowed for the comparisons after it, so a repeat test of a member already excluded is NL2531, astsc's TS2367 is. A store to the path, to a prefix of it (h.s = t,xs[0] = t) or to its root drops what it held, and the joins above follow a path as they follow a variable; a call does not, as intsc(tests/cases/union_narrowing_paths;reject_union_narrow_path_field,reject_union_narrow_path_this,reject_union_narrow_path_nested,reject_union_narrow_path_index,reject_union_narrow_path_join,reject_union_narrow_path_loop). An index is part of the path when it names one element, as TypeScript 5.5 reads it: a number literal, a parameter, aconst(const i = 0makesxs[i]the pathxs[0], annotated or not, and so doesconst j = iafter an unannotatedconst i = 0, whose type is the literal0), a module constant (const IDX: i32 = 0makesxs[IDX]the pathxs[0]too, andconst A: i32 = -1andconst B: i32 = -1makexs[A]andxs[B]one path), or aletnothing in its block assigns, a closure's body included. Aletthat is assigned or stepped (i = 1,i++), a parenthesised name or any other expression keys no path, soxs[i]is not narrowed through it, and a store through such an index (xs[j] = t) drops nothing, as intsc(tests/cases/union_narrowing_index,union_narrowing_index_const;reject_union_narrow_path_ident,reject_union_narrow_path_steady,reject_union_narrow_path_const_index,reject_union_narrow_path_index_store,reject_union_narrow_path_const_chain,reject_union_narrow_path_negative_index,reject_union_narrow_path_negative_zero,reject_union_narrow_path_module_index,reject_union_narrow_path_module_literal,reject_union_narrow_path_module_ident,reject_union_narrow_path_module_negative). The union read through the path is not narrowed (below). -
A union of two or more variants left still has only its tag
(
reject_union_narrow_none_if,reject_union_narrow_none_ternary,reject_union_narrow_none_and,reject_union_narrow_none_or,reject_union_narrow_none_fallthrough), and a narrowed variant has only its own fields (reject_union_narrow_none_case,reject_union_narrow_none_null,reject_union_narrow_none_reversed).
What a test excluded stays excluded, so a second test of a tag already ruled
out is always false and NL2531, in an if, a ternary or an &&
(reject_union_narrow_second_if, reject_union_narrow_second_ternary,
reject_union_narrow_second_and), and so is its case, NL2532
(reject_union_narrow_dead_case). An enum local holds what it was given: the
tag stored in a local, const k: Kind = s.kind, holds only the variants'
members, and a local given Kind.Circle holds only that member until it is
assigned again, so k === Kind.Tri against a member it cannot hold is NL2531
and case Kind.Tri: of a switch (k) NL2532, as tsc's TS2367 and TS2678 are
(reject_union_tag_local_compare, reject_union_tag_local_case,
reject_enum_held_const, reject_enum_held_let, reject_enum_held_reassign,
reject_union_tag_held_capture).
A test of an enum variable against a member narrows what it holds in the same
forms, as tsc narrows it: k === Kind.A and k !== Kind.A, either way
round, in an if and its else, a ternary, && and ||, after an if whose
branch always leaves, and each case and the default of a switch (k). This
holds for a parameter k: Kind as for the tag local const k: Kind = s.kind,
and an assignment drops it as it drops a union's. So after
if (k === Kind.A) return, k === Kind.A is NL2531 and case Kind.A: NL2532,
as tsc's TS2367 and TS2678 are (tests/cases/enum_narrowing;
reject_enum_narrow_else, reject_enum_narrow_early,
reject_enum_narrow_ternary, reject_enum_narrow_and,
reject_enum_narrow_or, reject_enum_narrow_switch,
reject_enum_narrow_tag_local). Narrowed to one member, the variable is that
member's type, so let j = k is a Kind.A that j = Kind.B does not fit
(reject_enum_narrow_let_member), as in tsc.
A switch whose subject reads a union variant's tag field, with no
default and labels that name every variant the tag can hold, is
complete: no value reaches the case no label
names, so when no break targets the switch and its last clause leaves, the
switch terminates (see Termination) and can end a function that returns a
value, as in tsc. Its unmatched case compiles to LLVM's unreachable. The
tag may be read through a union variable, a field, an element or a call's
result, s.kind, h.shape.kind, shapes[i].kind, and a variable that a test
before the switch left fewer variants needs labels for those only
(tests/cases/union_switch). With a variant unnamed, the switch does not
terminate, and a function that returns a value and ends in it is the
missing-return error, as tsc --strict --noImplicitReturns's TS2366 is
(reject_union_switch_missing_case, reject_union_switch_missing_case_field).
Complete means the tag can hold nothing else: a variant's tag is readonly,
written only with its own member, and a union never crosses the interop
boundary, so no other i32 reaches it.
Stricter than TypeScript. Each of these programs is accepted by
tsc --strict and refused here; each refusal is pinned:
-
No narrowing by assignment.
tscnarrows a union-typed slot to the type of the value last stored in it, so afterlet s: Shape = new Circle()it treatssas aCircle. This version does not track that, so a store of a value that is only some of the variants into a union local, field, element or nullable union is NL2534, and asks for the variant's own type or a value of the whole union (reject_union_narrow_const,reject_union_narrow_assign,reject_union_narrow_field,reject_union_narrow_element,reject_union_narrow_ternary,reject_union_narrow_nullable). A call that returnsShapeis a value of the whole union, and is stored freely. Passing and returning a variant narrows nothing, and is accepted. A test of the tag does narrow (above). -
A union is a type argument, but not a key.
Box<Shape>, a generic function or method whose type parameter binds to a union,Result<Shape, E>/Result<T, Shape>andnish/map's helpers on aMap<K, Shape>are accepted (above), as intsc. Three things stay refused, each under its own rule: a union is not aMaporSetkey, which is the key rule's refusal (NL2353,reject_union_map_key,reject_union_set); a generic class is not a variant (NL2522,reject_union_generic_variant); and a store of a bare variant into a generic instance's union field,b.value = new Square()on aBox<Shape>, is NL2534 as into any union field (reject_union_generic_field_store). A union does not meet a constraint (<T extends HasKind>, NL2328,reject_union_generic_constraint), and an instance over a union is not key material fornish:secret(NL2428,reject_union_generic_secret), nor a class typed JSON writes (NL2486,reject_union_generic_json), nor something a C header or N-API bridge spells (reject_union_generic_export,reject_union_result_export). -
No inferred unions. A union is never inferred: an unannotated ternary
or array literal of two variants is the existing same-type refusal
(
reject_union_ternary_inferred,reject_union_array_inferred; so is one a generic call would bindTto,first([new Square(), new Circle()]),reject_union_generic_inferred), an arrow returning one needs its annotation (reject_union_arrow_result), and a local initialised from the tag without an annotation,const k = s.kindor the tag in afor…of, is NL2530, becausetscwould infer the union of the tags' member types, which this version does not have (reject_union_inferred_tag,reject_union_forof_tag). So is the tag as an element of an unannotated array literal, an arm of an unannotated ternary, or the result of an arrow that binds a type parameter (reject_union_tag_array,reject_union_tag_ternary,reject_union_tag_arrow). An annotation as the enum,const k: Kind = s.kind, is accepted, and the local holds the variants' members (above). An enum variable narrowed to two or more members is the same:const j = kafterif (k === Kind.A) returnis NL2530, sincetscwould inferKind.B | Kind.C(reject_enum_narrow_inferred_set); annotate it asKind. -
No narrowing of a union through a path.
tscnarrows a property path,h.s.kind === Kind.Circlethenh.s.r; this version narrows the tag read through the path (above) but the union only in a variable, so a read of a variant's member through the path is`r` cannot be used on the union `Circle | Square | Tri` read through a property path: a test of the tag narrows a variable, not a path, so copy the union into a local first and test that(NL2558,reject_union_narrow_path). -
A complete
switchreads the union's tag.tsctreats aswitchwhose labels name every member of an enum as complete, and so ends a function in it; this version does so for a union's tag only (above). A plain enum,switch (k)fork: Kind, can arrive from C holding anyi32, so aswitchon a plainKindlocal or field is never complete (reject_union_switch_enum), nor is one on the tag copied into an enum local,const k: Kind = s.kind, or aletone reassigned on another path (reject_union_switch_tag_local,reject_union_switch_tag_local_reassigned). A narrowed path needs every tag of the whole union:switch (h.s.kind)afterif (h.s.kind === Kind.A) returnis complete only withKind.Alabelled too, since a call between the test and theswitchcould have reassignedh.s(reject_union_switch_path_narrowed); a narrowed union local, which nothing reassigns unseen, is complete with the labels of the variants left to it (tests/cases/union_switch_narrowed). Nor is aswitchcomplete on an enum field assigned from a tag,b.k = s.kind, which a call, an alias, a method orthiscan overwrite with any member (reject_union_switch_enum_field_calland its siblings): what decides is the subject's static type, a union's tag field, never what a path was assigned or narrowed to hold. End such a function after theswitch, or give it adefault(tests/cases/union_switch_flow). -
No
never. Where the tests have excluded every variant,tsctypes the variableneverand accepts a read of it; this version has no such type, so the read is`s` has no variant left here: the tests before this read excluded every variant of its union, which TypeScript types `never` and this version has no type for(NL2557,reject_union_narrow_exhausted). -
No narrowing through a stored condition.
tscnarrowsswhere aconstholding a test of its tag is true,const round = s.kind === Kind.Circle; if (round) { s.r }; this version narrows on the test itself only, sos.rthere reads the union (NL2528,reject_union_narrow_aliased). Test the tag in the condition. -
No field shared by every variant.
tscreads a field every variant declares through the union; this version reads only the tag before a test narrows it (NL2528,reject_union_member_field). -
A tag of one member.
tscaccepts a variant whose tag is typed with its whole enum,readonly kind: Kind = Kind.A, which then discriminates nothing; this version asks for the member type (NL2559,reject_union_tag_whole_enum). -
No covariant arrays. A
Circle[]is not aShape[], since a push through the wider type would put aSquareamong the circles; build the array as aShape[](reject_union_covariant_array). -
No object literal of a union. An object literal where a union is
wanted,
area({ kind: Kind.Tri, base: 2 })for aCircle | Triparameter, has no one class to build (reject_union_object_literal): build it into a local annotated as the interface,const t: Tri = { ... }, and pass that. -
No
new Array<Shape>(n), which would fill the array with a zero no variant is (reject_union_new_array). -
No class for its interface variant. A class that implements an
interface variant is not itself a variant, so
tscaccepts aBand implements RingwhereCircle | Ringis wanted and this version does not (reject_union_implements_variant): convert it to the interface first,const r: Ring = new Band(). -
A readonly tag.
tscaccepts a variant whose tag can be reassigned; this version asks forreadonly(NL2535,reject_union_mutable_tag). -
No write through the union.
tscacceptss.x = 1when every variant hasx; this version refuses every write through a union (NL2529,reject_union_assign_tag).
A union is not a class either, so new Shape() names no constructor, as in
tsc (reject_union_new). A value of any other type where a union is
wanted is the existing refusal of its position (reject_union_into_init,
reject_union_into_assign, reject_union_into_arg,
reject_union_into_push, reject_union_into_index,
reject_union_into_nullable, reject_union_field_other,
reject_union_return_other, reject_union_method_arg,
reject_union_ctor_arg, reject_union_array_other,
reject_union_ternary_other, reject_union_nullish_other). A smaller union
stored where a larger one is declared narrows it in tsc, as a variant
does, and is NL2534 too (reject_union_narrow_subunion).
Accepted here, refused by tsc. The loop pass (above) reads less than
tsc in the shapes below, and these are all of them: a variable holds every
member stored anywhere in the loop, or its whole declared type, so a
comparison tsc refuses as TS2367 may compile here. Each is pinned as it
stands, with the expected tsc error written at the comparison, so the case
fails on either side once the gap closes (tests/cases/enum_loop_join_gap):
-
A path. A tag or enum held by a field,
h.k, is joined over the whole loop, not followed through it. -
A store inside an expression. An assignment that is an argument,
keep((j = Kind.C)), an initializer,const t = (j = Kind.C), or the inner store of a chain,k = j = Kind.C, rather than a statement of its own. -
A value the pass cannot read. A store of a field or a method call
read through anything but
this, a local or parameter the loop does not declare, or a field of one — an element,j = gs[0].borj = gs[0].pick(), a call's result,j = makeG().b, a receiver the loop declares,const g = new G(); j = g.b— holds the whole declared type, though the field or method is typed with one member. So does a store of aletthe loop declares, or of aconstit declares from a tracked variable, as the swapconst t: Kind = a; a = b; b = t;does. -
An arm that holds nothing. A ternary arm that reads the stored
variable where the condition leaves it no member, the
kofk = k === Kind.A ? Kind.B : kwhilekholds onlyKind.A, reads as the whole type, as the checker reads a variable narrowed tonever, so the store holds every member from then on. - A wide type. A union of more than 29 variants or an enum of more than 29 members.
try is refused by Nish on its own, a destructuring pattern only ever
declares fresh names rather than storing to a variable (a destructuring
assignment is NL2773, Destructuring declarations),
and an arrow may read a local it captures but never
assign it (NL2586, Function parameters), so no loop
that compiles stores through any of them. A loop that holds a
labelled statement or a labelled break or continue anywhere in its body,
or whose switch has a clause that falls into the next, is one the pass
gives up on: it keeps the checker's widened state.
Across a sidecar. A union has no C spelling yet, so a function exported
through --emit-header or --emit-napi whose parameter or return holds a
union is refused, and so is a union-holding field of any class or interface
the compilation declares, exported or not, under a flag that lays the classes
out as C structs (--emit-header, --emit-napi, --emit-napi-async): a
header lays out every class and interface of the program, a private one too
(reject_union_private_field). A build with --emit-dts alone describes no
class, so there a union field of a class only the module reads — root
storage's graph among them — is accepted; a union in an exported function's
parameter or result is still refused under every sidecar flag. The message is
`tagOf`'s parameter `s` is `Circle | Square`, which holds a union no sidecar can describe: a union has no C spelling in this version
(NL4009, reject_union_export_param, reject_union_export_return,
reject_union_export_field, reject_union_export_array_field). Unions
cross Nish modules freely (tests/link/union_export). A string enum in an
exported function's signature is refused under the same flags for a reason
of its own (NL4019, String enums).

