LEVIATHAN vd52e79c4 · d52e79c486

Expressions

Primary expressions

Literals, names, this, parentheses, array and range literals, lambdas and string interpolation, the building blocks of every other expression.

since 0.1.0-alpha.1linuxwindowswasm

Description

A primary expression is the smallest unit an operator or a call can act on:

form meaning
42 3.14 "s" true false a literal
name a local variable, a parameter, a member, a function or a type
this the enclosing instance, or the receiver value inside a method of a primitive type
(expr) grouping
[e1, e2, ...] an array literal; a range inside the brackets is spread into its elements
a .. b a range value, both endpoints included
(p1, T2 p2) => expr R (p1, T2 p2) => expr a lambda; each parameter is written without a type or as Type name (a union too: int | string p), an optional return type R comes before the parameter list, and it captures the variables it uses
await expr a suspension point that parks the current task until expr completes
inject Type an explicit injection selector for Type

Literals, grouping, arrays, ranges and lambdas

use io::console;

class Sink {
    int total = 0;
    Sink (<<)(int n) {
        total = total + n;
        return this;
    }
}

void apply((int) => void f) {
    f(5);
}

void main() {
    int x = 5;
    console.writeln((x + 1) * 2);

    Array<int> listed = [10, 20, 30];
    Array<int> spread = [1..4];
    console.writeln(listed);
    console.writeln(spread);

    var inc = (int n) => n + 1;
    console.writeln(inc(4));

    var sum = (int p, int q) => {
        int t = p + q;
        return t * 2;
    };
    console.writeln(sum(1, 2));
    console.writeln(listed.filter(bool (v) => v > 15));

    Sink sink = Sink();
    apply((n) => sink << n);
    console.writeln(sink.total);
}
main();
12
[10, 20, 30]
[1, 2, 3, 4]
5
6
[20, 30]
5

Rules

  • A lambda body is either an expression ((x) => x + 1) or a statement block ((x) => { ...; return y; }).
  • A lambda may write its return type before its parameter list: bool (i) => i % 2 == 0, Foo? (int k) => lookup(k), int | string (int k) => { ... }. A function type is written in parentheses: ((int) => int) (int a) => (int b) => a + b. The expression body, or every return, is checked against the written type as a named function's body is, including the numeric return boundary: float (int n) => n / 2 returns 1.0e0 for 3. Without a written type the return type comes from the body.
  • Where the lambda has a target type, a written return type must be the target's return type or a subtype of it: (int) => Animal f = Dog (int x) => Dog(); is accepted, and (int) => float g = int (int n) => n; is a compile error (lambda return type 'int' does not match 'float', ...); numbers do not convert between function types.
  • A written return type binds a generic callee's type parameter exactly, in method and constructor calls: xs.map(string (x) => "n" + x) is xs.map::<string>((x) => "n" + x). Among overloads, a lambda with a written return type applies only to a parameter whose return type accepts it.
  • An untyped parameter takes its type from the target. A lambda with no target, such as the initializer of a var, must declare the type of every parameter: var id = (x) => x; and var t = int (x) => x; are compile errors (lambda parameter 'x' needs a type: ...).
  • The target reaches into both arms of a conditional, every arm of a match and both operands of ??: (int) => int k = c ? (x) => x + 1 : (y) => y; types both lambdas. An arm that does not fit the target is a compile error at the arm (conditional arm has type 'string', expected 'int'). A type parameter already bound to a function type is a target too: with Array<(int) => int> fs, fs.add((x) => x * 2) types x as int.
  • Name? ( params ) => body followed by : is read as the ? of a conditional. An optional-return lambda used as a conditional's true arm is written in parentheses: b ? (Foo? (int k) => lookup(k)) : h. In the false arm it needs none: b ? h : Foo? (int k) => lookup(k).
  • A lambda checked against a function type, such as a parameter, a variable or a return type, must not declare more parameters than that type passes. Passing (int a, int b) => a + b where (int) => int is expected is a compile error.
  • A lambda with no target type, such as the initializer of a var, has a function type: the declared parameter types and its written return type, or the type its body returns. var l = (string s) => s.length(); makes l a (string) => int, so (int) => int h = l; is a compile error (see lang.type-expressions), and a call through l checks its arguments: l(5) is a compile error. A block body with no return value returns void, so var p = (int a) => { console.writeln(a); }; makes p an (int) => void. A result the body does not determine, such as a block body that only throws, is not checked.
  • A block body with no target type whose return statements give values of different types returns their merge (lang.merged-types): returns of Dog() and Cat() give Animal, and a bare literal beside a typed return takes its type. Returns with no common type, such as Box() and None or 1 and "one", are a compile error; write the return type: var find = Box? (int k) => { if (k > 0) { return Box(); } return None; };. Two spellings of one type, such as Foo and Ns::Foo after uses Ns;, are the same type. Where the lambda has a target type, each return is checked against the target's return type instead.
  • An expression body in a position where the lambda must return void is treated as a statement: its value is discarded, exactly like an expression statement. That is why apply((n) => sink << n) is legal even though << returns its receiver. A block body that returns a value where void is expected is still an error, and a lambda whose expected return type is not void has its body checked against that type.
  • A block body must return a value on every path that reaches its end when the lambda's expected return type is not void: falling off the end of the block, or a bare return;, is a compile error (lambda body does not return a value on every path). A path that cannot reach the end, because it throws or loops forever (while (true) with no break that leaves it), needs no return. A block body that returns a value on some paths and none on others is an error wherever the lambda is used.
  • A lambda captures a primitive local variable (int, float, bool, string) by snapshot: a later change to the variable is not seen by the lambda. A struct or collection local (Array, Map, Set) is captured by copy the same way, and a class instance by reference (the object is shared). To share mutable state, capture an object and change its fields.
  • A lambda cannot write a captured local. Inside a lambda body, assigning a local of an enclosing function or lambda (n = 1, n += 1), storing into a field or element of a captured value (p.x = 1 with a struct p, xs[0] = 1, m["k"] = 1), and calling a mutating method or a collection verb on a captured value (p.bump(), xs.add(1), m.set("k", 1)) are compile errors (cannot assign to captured 'n' in a lambda: the lambda captured 'n' by copy, ...). Such a write would change only the lambda's copy. Return the new value from the lambda and assign it outside, or (once ref parameters land) take the variable as a ref parameter. This changes behaviour for existing programs: such writes used to compile and were silently lost. The rule applies at any depth: a nested lambda that writes a local of an enclosing lambda or function is an error too, and so is a write in a block factory (bind T { ... }), which runs as a lambda (lang.dependency-injection).
  • Which writes count is decided by the declared type, never by what the variable holds at run time. A store into a field or element of a captured struct, Array, Map or Set is a write to the capture, including a store through a struct's set ([]) indexer (b[0] = 7, b[1] += 5), as it is for a const struct (lang.const). A mutating call or a collection verb is a write to the capture when its receiver's declared type is a value type, an interface or an optional (ib.add(1) with IB ib, ob?.add(1) with IB? ob, it.add(1) with IIterable<int> it), also when it holds a class instance. This changes which programs compile. Through an interface the error also names the remedy for a value that holds a class instance: narrow it to that class first, or capture a class-typed variable. A receiver whose declared type is a class, or an optional of a class, holds a shared object (or nothing), so a store into its fields and any call on it, mutating or not, are allowed (box.value = 1, box.xs.add(1), mc.bump(), om?.bump() with C? om); rebinding the captured variable itself (om = C()) is still an error. const and readonly agree: a mutating call through a const or readonly class variable or field compiles too (lang.const). Inside a class method, this is a shared object too, so a lambda may write its fields and call its methods (count += 1, xs.add(1), bump()). Inside a struct method, this is captured by copy like any struct: a field write, an indexer store or a mutating call on it in a lambda (n += 1, this.n = 1, xs.add(1), bump()) is the same error (cannot assign to captured 'this' in a lambda: ...). This changes behaviour for existing programs: those writes compiled and were lost. Writes to the lambda's own parameters and locals and a nested lambda's, and to globals, which are not captured, are allowed. A write through a value typed by a type parameter (x.add(1) with T x) is not checked in the generic body; it is reported where the compiler specializes the body for a binding that makes it a write (type 'P' bound to 'T' of 'k' does not fit its use: cannot call mutating method 'bump' on captured 'x' in a lambda: ...), a gap that bounds on type parameters close.
  • this is available only inside a class body; using it elsewhere is a compile error.
  • A range a .. b includes both endpoints. Inside array brackets the range is spread: [1..4] is [1, 2, 3, 4].
  • Several keywords (get, set, is, in and others) may be used as member names after . or :: and as method names after a return type. They are keywords only at the start of a statement or declaration.

String interpolation

"...${expr}..." inserts the text of expr into the string. It works in both quote styles and is shorthand for concatenating the string pieces with the toString() of each hole, so a hole may contain any expression whose type has a toString().

  • \${ writes a literal ${.
  • A lone $ that is not followed by { is an ordinary character.
  • An empty hole (${}) and an unterminated hole are compile errors.
  • A string literal inside a hole must use the opposite quote style from the string that contains it: "${'has a } in it'}" is valid, while a nested literal with the same quote character ends the outer string at that point.

Interpolation

use io::console;

int x = 5;
console.writeln("x=${x}, next=${x + 1}");
console.writeln("literal \${x} and a $ sign");
console.writeln("${'has a } in it'}");
console.writeln('${"double quotes inside"}');
x=5, next=6
literal ${x} and a $ sign
has a } in it
double quotes inside

Examples

A lambda captures primitives by snapshot and objects by reference

use io::console;

class Box {
    int n = 0;
}

void main() {
    int seen = 0;
    var bump = (int v) => v + 1;
    seen = bump(seen);
    seen = bump(seen);
    console.writeln(seen);

    Box box = Box();
    var inc = () => { box.n = box.n + 1; };
    inc();
    inc();
    console.writeln(box.n);

    int base = 10;
    var add = (int x) => x + base;
    base = 100;
    console.writeln(add(1));
}
main();
2
2
11

Keywords as member names

use io::console;

class Gate {
    int in = 3;
    bool is() => true;
    int get() => 7;
}

Gate g = Gate();
console.writeln(g.in);
console.writeln(g.is());
console.writeln(g.get());
3
true
7

Notes

  • A variable that holds a function value, such as var inc = (int n) => n + 1;, is called with inc(4) inside a function body. Declare such variables inside a function.
  • var declarations infer the type from the initializer. They are accepted in function bodies, in the body of a control statement, at the outermost level of a script and in a namespace body.
  • await and inject are covered with the features they belong to (tasks and dependency injection).

See also

  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.
  • string — An immutable sequence of text, stored as UTF-8.