Statements
Blocks and scope
Every block ({ ... }, loop body, branch) opens a scope. A name may shadow
an outer one in a nested block (CLI only), but redeclaring a name in the
same scope is Duplicate declaration of `y` (CLI only). A let in a
for initializer belongs to the loop (tests/cases/cf_for). A branch or
loop body that is a single statement rather than a block is accepted
(CLI only).
let / const
-
Every declaration needs an initializer (
Variable `x` must be initialized(CLI only)) and takes its type from it; an annotation must match the initializer exactly (Cannot initialize ... with ...). -
Declaring a
void-typed variable isCannot declare a variable of type void(CLI only). A local may be a destructuring pattern,const { x, y } = porlet [a, b] = xs(Destructuring declarations); a module constant may not:Destructured constants are not supported(reject_const_destructured): a module constant's initialiser is a literal, another constant or arithmetic over them (Module constants), folded into each use with no storage of its own, and a pattern's names are reads of a receiver at run time.varis forbidden (tests/cases/reject_var_keyword,reject_var_in_for). -
constfreezes the binding, not the contents:xs[0] = 1andxs.push(1)on aconst xsare fine,xs = []is not (tests/cases/arr_index_read_write;Cannot assign to `x` because it is a const,reject_assign_const,reject_cf_compound_const). -
Locals live in an
allocaslot;opt -mem2regpromotes them (tests/cases/locals).
Destructuring declarations
A const or let in a function body, and the head of a for...of, may be an
object or an array pattern. Each name it binds is one read off the value on
the right, which is evaluated once and never copied:
const { x, y: py } = p // x = p.x, py = p.y
let [a, , c] = xs // a = xs[0], c = xs[2]
for (const { x, y } of points) { ... }
-
An object pattern reads a class or interface value. Each entry is a
field's name,
x, or a field renamed,y: py; the name's type is the field's. A missing field isCannot destructure field `z`: Point has no such field(NL2778,reject_destructure_field). -
An array pattern reads an array. Each name is one element read by its
position, with the bounds check of
xs[i]; a hole,[a, , c], skips a position. An element past the end panics,index out of range: 5 >= 3(destructure_out_of_range), where TypeScript would bindundefined: a name in Nish always holds a value of its type. -
A
for...ofhead destructures each element of an array (destructure_for_of). Over aSetor an iterator it is NL2785 (reject_destructure_for_of_set). Over aMapit is NL2375, the refusal anyfor...ofover aMapgets, before the pattern is read: aMap's entries are[key, value]pairs of two types, a tuple, which this version does not have (reject_destructure_for_of_map,reject_map_iter_entries). -
A name is a fresh local:
letnames may be assigned,constnames may not. A struct's fields are read through its pointer, soconst { x } = pon a stack-allocatedpcosts one load (destructure_stack). -
The receiver. Over a name or a field path (
p,xs,this,o.pt,this.a.items) each name is read straight off it, and the function compiles to the body of its hand-written reads, so every rule about an element ofo.itemsapplies to the pattern as too.items[0](reject_destructure_moved_field). Any other receiver (a call, afor...ofelement) is evaluated once into a hidden copy of its pointer, which no rule names, as no rule names the call inf()[0](reject_destructure_moved_call): unoptimised that is one alloca and one store more than the hand-written reads, and afteropt -O2the bodies are the same (destructure_zero_cost). A pattern works overthisin a method, in an arrow's or an async body, and in a C-styleforinitialiser (destructure_forms). -
An empty pattern,
const {} = p,const [] = xsorconst [,] = xs, binds nothing; its receiver is still evaluated once, for any effect it has (destructure_empty).
Refused, each with its own diagnostic and test:
| Pattern | Diagnostic | Test |
|---|---|---|
[a, b] = xs, ({ x } = p), ({ x: px } = p) (assignment) |
NL2773 Destructuring assignment is not supported |
reject_destructure_assignment, reject_destructure_assignment_object, reject_destructure_assignment_renamed |
{ x = 0 }, [a = 1] (a default) |
NL2774 | reject_destructure_default, reject_destructure_default_array, reject_destructure_for_of_default |
[a, ...rest], { x, ...others } |
NL2775 | reject_destructure_rest, reject_destructure_for_of_rest |
{ p: { x } }, [[a]] (nested) |
NL2776 | reject_destructure_nested, reject_destructure_nested_object, reject_destructure_for_of_nested |
{ ["x"]: a }, { "x": a } |
NL2777 | reject_destructure_key, reject_destructure_key_computed |
{ default: d } (a keyword key) |
NL2778, the key is read as a field's name and no class has that field | reject_destructure_key_keyword |
{ norm } where norm is a method |
NL2778, call it instead | reject_destructure_method |
const { x }: Other = p (an annotation the receiver does not match) |
NL2185 Cannot initialize Other variable `{ x }` with Point |
reject_destructure_annotated |
| a name never read | NL2712, rename it { y: _y } (a shorthand) or _a |
reject_destructure_unread |
a value that may be absent, Point | null or a V | undefined from Map.get |
NL2779, narrow it first | reject_destructure_nullable, reject_destructure_undefined |
a Map |
NL2780, read each value with get |
reject_destructure_map |
a string |
NL2781, read each character by its index | reject_destructure_string |
| an object pattern over a number | NL2782 | reject_destructure_object_of_number |
an array pattern over an object or a Set |
NL2783 | reject_destructure_array_of_object, reject_destructure_set |
let { x }: Point; (no initializer) |
NL2784 | reject_destructure_uninitialized |
a parameter, ({ x }: Point) => x |
Destructured parameters are not supported |
reject_param_destructured |
| a module constant | Destructured constants are not supported |
reject_const_destructured |
var [a] = xs, var { x } = p, for (var [a] of rows) |
NL1036 `var` is forbidden; use `let` or `const`, as for var a |
reject_destructure_var_array, reject_destructure_var_object, reject_destructure_var_for_of |
using [a] = xs, using { s } = scope() |
none of its own: as in TypeScript, using binds only a plain name, so using [a] reads a variable named using and using { is a syntax error |
reject_destructure_using_array, reject_destructure_using_object |
A pattern over await is refused with A pattern may destructure an `await` only of `awaitAll(...)`, whose names are the calls' answers: await into a name, then destructure the name
(nl2193_destructuring_local), but for the answers of
const [a, b] = await awaitAll(f(x), g(y))
(Async functions).
Expression statements
Any expression may be a statement; its value is discarded (CLI only).
console.log(...), process.exit(...), writeFileSync(...) and
appendFileSync(...) return void and may appear only as statements
(can only be used as a statement, tests/cases/reject_console_log_as_value).
return
The expression's type must equal the declared return type
(Return type mismatch: function returns ... but expression is ...); a bare
return is valid only in a void function
(Expected a return value of type ...) (tests/cases/entry_main_void).
if / else
The condition must be boolean: there is no truthiness
(Condition must be boolean, got i32 (Nish has no truthiness),
tests/cases/reject_cf_nonbool_cond). else if chains are nested ifs
(tests/cases/cf_if, cf_if_else_chain).
while, do ... while, for
-
Conditions must be
boolean(tests/cases/cf_while,cf_do_while,cf_for). -
for (init; cond; update): every clause is optional; the initializer is alet/constlist or an expression (tests/cases/cf_break_continueforfor (;;); expression initializer (CLI only)). -
Loop variables are ordinary mutable locals; there is no restriction on
assigning them (
tests/cases/cf_collatz). -
A loop whose condition is absent or the literal
trueand whose body has nobreakfor it never falls through (see Termination); every other loop may run zero times (tests/cases/cf_while,firstPowerOver).
for (const x of a)
-
amust be an array (`for...of` requires an array, got string,tests/cases/reject_arr_forof_non_array; the compatibility dialect walks a string one code point at a time underfor-of-string), or a walk of the globalMaporSet:m.keys(),m.values(), aSetitself,s.keys()ors.values()(MapandSet), or aChannelfromnish/threads, which takes values off it (Channels);xgets the element type and must not be annotated (The `for...of` variable takes the element type; remove the annotation,tests/cases/reject_arr_forof_annotation) or initialised (The `for...of` variable cannot have an initializer,tests/cases/reject_arr_forof_initializer); exactly one variable (`for...of` declares exactly one variable,tests/cases/reject_arr_forof_two_vars); the head is a declaration rather than an assignment to something already declared (`for...of` needs a `const` or `let` declaration,tests/cases/reject_arr_forof_expression);let xmakes it assignable,const xdoes not (tests/cases/reject_arr_forof_const_assign).for awaitis not supported (`for await` is not supported here,tests/wordings/nl2133_for_await), andfor...inis forbidden (Rejected statements). -
ais evaluated once;a.lengthis re-read every iteration, so apushinside the body extends the iteration, as JavaScript's array iterator does (tests/cases/arr_for_of).breakandcontinuework (tests/cases/arr_for_of).
switch
switch (node.kind) {
case KIND_IF:
case KIND_WHILE:
return checkBranch(node);
case KIND_CALL:
return checkCall(node);
default:
return ERROR;
}
-
The discriminant is an integer (
i32,i64,u8,u16,u32,u64; so anumberin the default mode but not under--number-mode f64) or aenumof either kind (Enums), which is ani32in the jump table: a string enum switches on its members' ordinals, never on their strings. Any other type is`switch` requires an integer discriminant, got <type>(tests/cases/reject_switch_string). Only an integer switch lowers to LLVM'sswitchand a jump table; a string switch would have been a chain ofnish_str_eqcalls wearing a switch's clothes, andif/elsesays that honestly. The compatibility dialect admits that chain understring-switch. -
Every
caselabel is an integer constant expression of the discriminant's type: a literal, its negation, a module constant, or an enum member (`case` label must be an integer literal, a module constant, or an enum member,tests/cases/reject_switch_case_not_constant;`case` label is i64 but the discriminant is i32,reject_switch_case_type). A literal takes the discriminant's width, socase 1:on ani64switch is ani64one — and on an enum switch it is`case` label is i32 but the discriminant is Kind(reject_enum_case_label), because the integer a member stands for is not the member. -
Labels are distinct (
Duplicate `case` label `1` in this `switch`,tests/cases/reject_switch_duplicate_case), and there is at most onedefault(`switch` has more than one `default` clause(CLI only)), which may appear anywhere among the clauses. -
A clause falls through, as in TypeScript. A clause whose statements do
not end in
break,return,continueorprocess.exitruns on into the next clause's statements; the IR branches into the next clause's block, with no flag (tests/cases/cf_switch_fallthrough,cf_label_walks). An empty clause falls through the same way, which is howcase 1: case 2:gives several labels one body (tests/cases/cf_switch). A clause reached by falling into it is reached with either label's value: a tag test does not narrow there (reject_switch_fall_narrow), and a local the clauses above it assigned holds its declared type. -
A clause cannot declare a variable directly; wrap its body in a block
(
A `case` clause cannot declare a variable directly,tests/cases/reject_switch_case_declaration). Clauses share one scope in TypeScript, so a declaration in one would be visible but unassigned in the ones below it. -
breakinside aswitchleaves the switch, not an enclosing loop;continuelooks past the switch to the loop (tests/cases/cf_switch_break). A labelledbreakorcontinuenames the loop instead (see below,cf_label_switch). -
A
switchterminates (see Termination) when nobreaktargets it, its last clause terminates, and it has adefaultor is a completeswitchon a union's tag, whose labels name every variant (Discriminated unions,tests/cases/union_switch). Aswitchon an integer or a plain enum without adefaultnever terminates, whatever its labels (reject_union_switch_enum).
break / continue
A label goes on a loop, a block or a switch (outer: for (...),
check: { ... }, sw: switch (...)); on any other statement it is refused
(Labeled statements are forbidden in Nish except on a loop, a block or a `switch`, tests/cases/reject_label_if). break label leaves the statement
the label names, from any depth inside it; continue label starts the next turn
of the loop it names. Each lowers to the branch a hand-kept done flag would
take — to that statement's exit block or its loop's step block — with no flag
(tests/cases/cf_label_loops, cf_label_block, cf_label_switch,
cf_label_walks). Leaving a scoped pass or a Map walk this way releases it
as an unlabelled exit would, and a Secret local a labelled exit skips past
must be wiped first (reject_label_secret_break, reject_label_secret_block).
- A label is not reused inside the statement it names (
Duplicate label 'outer',reject_label_duplicate). -
continue labelnames a loop (A `continue` can only jump to a label of an enclosing loop,reject_label_continue_block), andbreak labela statement around it (A `break` can only jump to a label of an enclosing statement,reject_label_unknown). - A jump does not leave an arrow for a label outside it (
Jump target cannot cross function boundary,reject_label_crosses_arrow).
Unlabelled, break needs an
enclosing loop or switch (`break` outside of a loop or `switch`,
tests/cases/reject_cf_break_outside) and continue an enclosing loop
(`continue` outside of a loop, reject_cf_continue_outside), which it
finds past any switch in between. tests/cases/cf_break_continue,
cf_switch_break.
throw (removed)
throw is forbidden by Phase 0 (tests/cases/reject_throw). Until WP16 it
compiled to llvm.trap — it aborted the process and discarded its value —
which made it an abort wearing the syntax of error handling, and let a program
report a failure in a way no caller could see. The two things it was used for
have their own spelling now:
- a failure a caller should handle is a
Result<T, E>; -
an invariant that cannot hold is
panic(message), which keeps the messagethrowthrew away.
try/catch/finally is forbidden for the same reason
(tests/cases/reject_try_catch).
process.exit(code) as a statement
Terminates the process with code (an i32) and, for control-flow
purposes, the current path: a non-void function may end with it
(tests/cases/process_exit), and code after it is
Unreachable code after process.exit (tests/cases/reject_exit_unreachable).
Termination, definite return, and unreachable code
A statement terminates when control cannot fall out of it: return,
break, continue, process.exit(...), panic(...); an if whose branches
both terminate; a switch with a default or one complete on a union's tag,
no break aimed at it and a terminating last clause; a loop with no condition or the condition true and
no break aimed at it; a labelled block whose statements terminate and no
break names. A break aimed at a statement is an unlabelled one directly
inside it or a labelled one that names it from any depth, so a break outer
in an inner loop makes outer: while (true) one that may finish. Any other
loop may run zero times and does not terminate. Rules (src/statements.ts, checker.ts):
-
A non-
voidfunction's body must terminate (must return a value of type i32 on every path,tests/cases/reject_missing_return,reject_cf_missing_return_loop;if (true) { return 1; }alone is not enough (CLI only)). -
A statement after a terminating one is
Unreachable code after <what>, where<what>isreturn,break,continue,process.exit,an `if` whose branches all return,a `switch` whose clauses all return, oran infinite loop(tests/cases/reject_unreachable,reject_cf_unreachable_after_break,reject_exit_unreachable; theifform (CLI only)).
Mistakes every type accepts
Some lines type-check and still cannot be what their author meant. Rust
warns about most of them and Clippy denies the rest. Here each one is an
error, because it is a bug far more often than it is a choice. Each rule fires only
where the answer is certain, and each has a spelling that says "on purpose".
Rules (src/hygiene.ts):
-
A local is read at least once (NL2712). A
letorconst, afor...ofbinding included, that nothing reads is`x` is declared but never read(reject_unread_local,reject_unread_for_of). Storing into a local is not reading it:n++orn += 1on a line of its own, or as aforloop's step, writesnand uses nothing, so a counter nothing reports is`n` is assigned but its value is never read(reject_unread_local_written);const m = n++reads it. A capture by an arrow is a read. A lone name on its own line,x;, is not a read (reject_unread_lone_name). A name that starts with_is never reported, which is how a loop that only counts its turns is written:for (const _item of xs)(hygiene_quiet). Ausingbinding is exempt, because its block's end uses it. AResultlocal has its own rule (NL2032, Result and error handling). -
A statement has an effect (NL2713). An expression statement with no
call,
new, store,++,--orawaitanywhere in it isThis statement has no effect(reject_no_effect_statement,reject_no_effect_member).state === next;adds(to assign, write `=`). A lone name is left to the rule above. -
A value is not assigned to itself (NL2714).
x = x,p.x = p.xandxs[i] = xs[i]do nothing (reject_self_assign). -
An operator has two different operands (NL2715). With the same
operand on both sides,
===!====!=<<=>>=&&||&|^-/%give an answer that does not depend on it, so the expression is refused (reject_same_operands,reject_same_operands_index). Two operands are the same when they are the same pure expression over the same variables: the same local, field path, element by the same index, or the same operators over those. A literal-only expression is not refused. Onf32andf64,x !== xis the NaN test andx - x === 0the finite test, so only<and>are refused there, which are false for every value (reject_same_operands_float_ordered). To compare a value with itself on purpose, copy it to a secondconstfirst (hygiene_quiet). -
An
else iftests something new (NL2716). A condition the same as an earlier one in the sameif/else ifchain can never pass, because the earlier branch took every case it would match (reject_repeated_condition). A condition with a call in it can answer differently the second time, and is not compared. -
An unsigned value is not compared with zero for its sign (NL2717).
u < 0and0 > uare always false, andu >= 0and0 <= ualways true, for au8,u16,u32oru64(reject_unsigned_zero,reject_unsigned_zero_reversed).
These findings are reported only once every other rule has passed: a program
with any other error is told that error alone (reject_hygiene_held), so
an unread local never crowds out the error that left it unread. They are held
to the program's own package and the standard library. A dependency's
findings are left to its author, as Cargo caps the lints of a crate it pulls
in.
Rejected statements
with (tests/cases/reject_with_statement), try (reject_try_catch),
debugger (reject_debugger), a label on a statement other than a loop, a
block or a switch (reject_label_if),
var (reject_var_keyword), for...in (`for...in` is forbidden in Nish (it enumerates property names, and object layout is fixed at compile time); use `for...of`, NL1056, reject_for_in), nested function, enum, type,
namespace (reject_namespace), declare global (reject_declare_global).
with, try and var are not reserved: a function or a variable may be
called one, and a statement opens only where the word could not be that
name. with (…) is the statement when a statement follows it on the same
line, and var when a name follows it on the same line. try is the
statement when a block follows it on the same line, or when a block follows
it and a handler follows that block (catch {, catch (e) { or finally {,
not a call such as finally();), whatever line breaks and comments sit
between (reject_try_allman_catch, reject_try_allman_finally,
reject_try_comment_newline). A catch binding may be a name or a
destructuring pattern, with or without an annotation, and is refused the same
way (reject_try_catch_destructured). So a try-named block followed by
catch(<a binding>) — a name or a pattern, catch(n) or catch([n]) — and
then a block is a try statement, even where 0.13.0 read a call to a function
named catch (reject_try_catch_call_newline,
reject_try_catch_pattern_call_newline): the one shape of program this rule
stopped compiling. An argument that is no binding, such as catch([1, 2]) or
catch({ first: 1 }), is the call it was (tests/parser/names-catch-array.ts,
names-catch-object.ts). A line break inside a block comment counts as
one, as it does for semicolon insertion. So try alone on a line before a
block that nothing handles is a name and a block, as it was before
(tests/parser/names.ts). tsc reserves all three, so this is Nish
accepting what TypeScript does not, as it did before these statements
parsed.
enum and type are top-level declarations (Enums,
Type aliases); it is only inside a function body that they are
a rejected statement.
The empty statement, a lone ; where a statement stands, is refused in a
body: Unsupported statement in Phase 1: EmptyStatement (NL2260,
tests/cases/reject_stmt_empty). It is the sentence every statement kind with
no checker gets, named by its syntax kind as a nested function or import
is; every other such kind is refused earlier by a rule of its own. It is
refused where a body is checked, so a ; in a template nothing instantiates
still compiles, as it did in every release. A ; at the top level is the
syntax error a module holds only `function`, `class`, `interface`, `const`, `type`, `enum` and `import`, found `;` (NL0001).

