LEVIATHAN vd52e79c4 · d52e79c486

Statements

Statements

Declarations, blocks, conditionals, the four loop forms, return, and the order in which a script's top-level statements run.

since 0.1.0-alpha.1linuxwindowswasm

Description

Type name = expr;      var name = expr;       // declaration (var infers the type)
Type name;                                    // declaration with the type's default value
using Type name = expr;                       // deterministic cleanup
expr;                                         // expression statement
{ stmt* }                                     // block
return expr;    => expr;                      // return, and the arrow form of a body
if (cond) stmt [else stmt]
label: while (cond) stmt                      // labeled loop
do stmt while (cond);                         // post-test loop
for (init; cond; step) stmt
for (T x in iterable) stmt                    // ranges, arrays, maps, any iterable
break;      continue;                         // loop control, optionally labeled
throw expr;                                   // expr must implement IException
try stmt catch (Type name?) stmt [catch ...]  // the first matching clause runs
bind ...;   uses NS;   use NS::name (as alias)?;   // imports and bindings
;                                             // empty statement

A declaration introduces a variable. Type name = expr; states the type. var infers the type from the initializer, which must have a type on its own (var xs = []; is a compile error; write Array<int> xs = [];); the variable can be reassigned with values of that type. const Type name = expr; fixes a variable after its initializer. Type name; with no initializer gives the variable the default value of its type: "" for a string, [] for an array, 0 for an int. using declarations are covered by lang.using-statement.

An expression statement evaluates an expression and discards the result.

A block { ... } groups statements and opens a scope: variables declared inside are not visible after the closing brace.

return expr; leaves the enclosing function with a value, and return; leaves a void function. A function body that is a single statement may be written with an arrow, => expr;, where the arrow means return. A function, method, operator or get accessor whose result is not void must return a value on every path: if its end is reachable, or it runs a bare return;, that is a compile error (function 'f' does not return a value on every path, expected 'int'; missing return value). A path that cannot reach the end needs no return: one that ends in return or throw, an if/else, try/catch or match every branch of which ends that way, or a while (true), for (;;) or do ... while (true) loop that no break leaves. A call never ends a path, even one that cannot come back such as env.exit(1), so a value function that ends in one needs a throw after it. Falling off the end of a T? function is an error too; write return None;. Constructors and set accessors are void.

if runs the first branch when the condition holds, else the second branch if there is one. The branches are single statements, usually blocks. while tests its condition before each pass and do ... while tests it after, so a do body always runs at least once. for (init; cond; step) is the C-style loop. for (T x in iterable) visits every element of a range (0..2 includes both ends), of an array, of a map (each element is a Pair with first and second), or of any value that implements IIterable<T>.

The statement forms

use io::console;

int twice(int n) => n * 2;

int clamp(int n) {
    if (n < 0) return 0;
    return n;
}

void inner() {
    {
        int scoped = 1;
        console.writeln(scoped);
    }
    var inferred = "v";
    console.writeln(inferred);
}

int total = 0;
for (int i = 1; i <= 4; i = i + 1) {
    total = total + i;
}
console.writeln(total);

int n = 3;
while (n > 0) {
    console.write("${n}");
    n = n - 1;
}
console.writeln("");

do {
    console.writeln("runs once");
} while (false);

for (int k in 0..2) {
    console.write("k${k}");
}
console.writeln("");

Array<string> names = ["ann", "bo"];
for (string s in names) {
    console.writeln(s);
}

Map<string, int> ages = Map();
ages["ann"] = 30;
for (Pair<string, int> p in ages) {
    console.writeln("${p.first}=${p.second}");
}

string empty;
int zero;
console.writeln("[${empty}] ${zero}");

if (total > 5) console.writeln("big"); else console.writeln("small");
console.writeln(twice(4));
console.writeln(clamp(-3));
inner();
10
321
runs once
k0k1k2
ann
bo
ann=30
[] 0
big
8
0
1
v

Rules

  • A script's top-level statements run in the order they are written, and function and class declarations may appear between them. A top-level variable declaration is the exception: its initializer runs before the first top-level statement, wherever it is written (see lang.const). There is no automatically called main; call your own entry function explicitly.
  • A top-level variable written below a top-level statement gets a warning when its initializer may perform a system effect (any system native, e.g. clock, console, files, sockets, random, environment, processes, timers, threads and channels) or reads state an earlier statement modified: a variable the statement assigns, or one whose fields, elements or object the statement changes, read through it (v.n, v.m()) or copied as a value (see lang.const). Declare the variable and assign it after the statement to run it in order:
warning: the initializer of 't1' runs before the top-level statement at line 2 (top-level initializers run first); declare 't1' and assign it after that statement to run it in order
  • A const variable cannot be assigned after its declaration (cannot assign to const).
  • A top-level variable that no function, method or lambda in the program assigns narrows like a local variable in top-level code, where an assignment ends the narrowing. Inside a function, method or lambda body it narrows only when nothing but its initializer assigns it, because a task can run between top-level statements while the body waits ("'g' cannot be narrowed: it is a global that top-level code assigns, which can run while this body waits; copy it into a local first"). One that some function assigns does not narrow anywhere ("'g' cannot be narrowed: it is a global assigned by function 'reset'; copy it into a local first"), and a lambda body never sees a top-level variable's narrowing, because top-level code may assign it before the lambda runs (lang.unions-and-optionals).
  • An if whose branch always leaves (return, throw, break or continue) is an early exit: the statements after it in the same block see its test false, so if (s == None) return; narrows s to a present value for the rest of the block (lang.unions-and-optionals).
  • A body is exactly one statement. Use a block to run several.
  • for (T x in iterable) accepts a range, an array, a map and any IIterable<T>. With var as the type, the element type is inferred.
  • The loop variable of for (T x in iterable) is bound afresh to each element. Assigning to it in the body changes it only for the rest of that pass: the next pass still takes the next element, so for (int i in 0..9) { i = i * 2; } runs ten times.
  • A for (T x in iterable) over an array, a map or a range value visits the elements the iterable held when the loop started. Arrays and maps are values, so assigning the iterated variable or field in the body (xs = [0], xs[i] = v, xs = xs.add(v), m[k] = v) changes it for the code that follows but not what this loop visits: for (int x in xs) { xs = xs.add(x); } runs once per starting element.
  • The loop-control statements break and continue, the using declaration, and the exception statements throw and try have their own entries: lang.loop-control, lang.labeled-loops, lang.using-statement and lang.exceptions.

Examples

Top-level statements run in order

use io::console;

console.writeln("one");

void later() {
    console.writeln("later");
}

later();
console.writeln("two");
one
later
two

Notes

  • var declarations are accepted in function bodies, in the body of a control statement, at the outermost level of a script and in a namespace body. A top-level or namespace var is typed from its initializer before the program runs, so a function declared above it can read it.
  • Imports and bindings (uses, use, bind) are covered with namespaces and with dependency injection.

See also

  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.
  • Map — An associative collection from keys of type K to values of type V, with value semantics.
  • break and continue — Leaving a loop early or skipping to its next iteration, and what counts as a loop for these statements.
  • Labeled loops — Naming a loop so that break and continue can leave or restart an outer loop from any depth.
  • using — deterministic cleanup — A using declaration owns a resource and closes it exactly once on every way out of its block, in reverse order of declaration.
  • Exceptions: throw, try and catch — Throwing a value that implements IException, catching it by type, and the standard exception hierarchy.
  • const declarations — Fix a local, field, global, parameter or loop binding after its initializer, with the exact rules for each kind of slot.