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 is Cannot declare a variable of type void (CLI only). A local may be a destructuring pattern, const { x, y } = p or let [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. var is forbidden (tests/cases/reject_var_keyword, reject_var_in_for).
  • const freezes the binding, not the contents: xs[0] = 1 and xs.push(1) on a const xs are 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 alloca slot; opt -mem2reg promotes 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 is Cannot 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 bind undefined: a name in Nish always holds a value of its type.
  • A for...of head destructures each element of an array (destructure_for_of). Over a Set or an iterator it is NL2785 (reject_destructure_for_of_set). Over a Map it is NL2375, the refusal any for...of over a Map gets, before the pattern is read: a Map'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: let names may be assigned, const names may not. A struct's fields are read through its pointer, so const { x } = p on a stack-allocated p costs 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 of o.items applies to the pattern as to o.items[0] (reject_destructure_moved_field). Any other receiver (a call, a for...of element) is evaluated once into a hidden copy of its pointer, which no rule names, as no rule names the call in f()[0] (reject_destructure_moved_call): unoptimised that is one alloca and one store more than the hand-written reads, and after opt -O2 the bodies are the same (destructure_zero_cost). A pattern works over this in a method, in an arrow's or an async body, and in a C-style for initialiser (destructure_forms).
  • An empty pattern, const {} = p, const [] = xs or const [,] = 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 a let/const list or an expression (tests/cases/cf_break_continue for for (;;); 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 true and whose body has no break for it never falls through (see Termination); every other loop may run zero times (tests/cases/cf_while, firstPowerOver).

for (const x of a)

  • a must 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 under for-of-string), or a walk of the global Map or Set: m.keys(), m.values(), a Set itself, s.keys() or s.values() (Map and Set), or a Channel from nish/threads, which takes values off it (Channels); x gets 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 x makes it assignable, const x does not (tests/cases/reject_arr_forof_const_assign). for await is not supported (`for await` is not supported here, tests/wordings/nl2133_for_await), and for...in is forbidden (Rejected statements).
  • a is evaluated once; a.length is re-read every iteration, so a push inside the body extends the iteration, as JavaScript's array iterator does (tests/cases/arr_for_of). break and continue work (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 a number in the default mode but not under --number-mode f64) or a enum of either kind (Enums), which is an i32 in 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's switch and a jump table; a string switch would have been a chain of nish_str_eq calls wearing a switch's clothes, and if/else says that honestly. The compatibility dialect admits that chain under string-switch.
  • Every case label 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, so case 1: on an i64 switch is an i64 one — 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 one default (`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, continue or process.exit runs 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 how case 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.
  • break inside a switch leaves the switch, not an enclosing loop; continue looks past the switch to the loop (tests/cases/cf_switch_break). A labelled break or continue names the loop instead (see below, cf_label_switch).
  • A switch terminates (see Termination) when no break targets it, its last clause terminates, and it has a default or is a complete switch on a union's tag, whose labels name every variant (Discriminated unions, tests/cases/union_switch). A switch on an integer or a plain enum without a default never 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 label names a loop (A `continue` can only jump to a label of an enclosing loop, reject_label_continue_block), and break label a 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 message throw threw 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-void function'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> is return, break, continue, process.exit, an `if` whose branches all return, a `switch` whose clauses all return, or an infinite loop (tests/cases/reject_unreachable, reject_cf_unreachable_after_break, reject_exit_unreachable; the if form (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 let or const, a for...of binding 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++ or n += 1 on a line of its own, or as a for loop's step, writes n and 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). A using binding is exempt, because its block's end uses it. A Result local has its own rule (NL2032, Result and error handling).
  • A statement has an effect (NL2713). An expression statement with no call, new, store, ++, -- or await anywhere in it is This 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.x and xs[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. On f32 and f64, x !== x is the NaN test and x - x === 0 the 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 second const first (hygiene_quiet).
  • An else if tests something new (NL2716). A condition the same as an earlier one in the same if/else if chain 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 < 0 and 0 > u are always false, and u >= 0 and 0 <= u always true, for a u8, u16, u32 or u64 (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).