Expressions
Calls
Calling functions and methods, with positional and named arguments, explicit type arguments, and the rules that decide which callable a name refers to.
since 0.1.0-alpha.1linuxwindowswasm
Description
f(args) // function call; the overload is chosen by the argument types
f(x, label: value) // positional arguments first; named arguments may follow in any order
obj.method(args) // method call; the overload is chosen by the argument types
f::<int>(args) // explicit type arguments for a generic function
obj.method::<R>(args) // explicit type arguments for a generic method
A call is resolved as one set of bindings from arguments to parameters. Functions, methods, constructors and attributes all use the same spelling and the same rules. Constructing an object is covered by lang.construction.
Positional arguments come first and bind the parameters from the left. Named arguments (name: value) bind the parameter with that name and may appear in any order after the positional ones. A parameter that receives no argument takes its declared default value.
When a callable has several overloads, the compiler picks the one whose parameter types fit the argument types best; between two equally good fits it prefers the one that needs fewer defaults, and an exact tie goes to the overload declared first.
A call that no overload accepts is a compile error that names the callee. With one candidate the error gives its reason (call to 'run': argument for parameter 'cb' has type '(int) => int', expected '(int) => void'); with several it lists the argument types (no overload of 'encode' matches the arguments (T)) and adds a note per candidate, at its declaration, with the reason it does not apply (at most three notes, then a count of the rest). A method is named with its receiver's class (Registry.add).
Positional, named and default arguments, and explicit type arguments
use io::console;
string greet(string name, string greeting) => "${greeting}, ${name}!";
string fmt(string text, int width = 5, string pad = ".") => "${text}${width}${pad}";
T identity<T>(T v) => v;
class Printer {
string show<R>(R v) => "<${v}>";
}
console.writeln(greet("Ada", "Hello"));
console.writeln(greet("Ada", greeting: "Hi"));
console.writeln(greet(greeting: "Hey", name: "Bo"));
console.writeln(fmt("x"));
console.writeln(fmt("x", pad: "!"));
console.writeln(fmt("x", pad: "!", width: 2));
console.writeln(identity::<float>(2));
console.writeln(Printer().show::<int>(5));
Hello, Ada!
Hi, Ada!
Hey, Bo!
x5.
x5!
x2!
2.0e0
<5>
Rules
-
A collection verb (
add,addAll,insertAt,removeAt,clear,set,remove) is amutatingcall on a collection: its receiver must be a place (a local, a field, a global, an element,this), and a temporary receiver (mk().add(1),[1].add(2)) is a compile error. This changes behaviour for existing programs: the arguments are evaluated first and the place's current value is read afterwards, sog.add(f())sees whatfitself appended tog. A verb returns nothing, so its value cannot be used (b = a.add(1),f(a.add(1)),a.add(1).add(2)are errors). -
Positional arguments must precede named arguments. A positional argument after a named one is a compile error.
-
A named argument binds the parameter with that name. An unknown name, or a second binding of the same parameter, is an error.
-
An omitted parameter takes its declared default. A default must be a compile-time constant and cannot refer to another parameter or to
this. -
Explicit type arguments
::<T, ...>follow the complete callee and must be followed by(. They must name exactly as many types as the callable has type parameters, and they are authoritative: an argument whose type conflicts with a parameter that the explicit types pin is a compile error at that argument. -
Without a following
(, a::-reached callable is not a call but a method reference. Seelang.method-references. -
A method call
recv.m(a, b)evaluates the receiver expression first, including a getter read when the receiver is accessor-backed, and then the arguments from left to right. An argument that reassigns what the receiver expression read does not change the receiver of the call. -
A call through a function value, such as a local, parameter, global or field of function type, or any other callee expression like
make()(x), evaluates the callee first and then the arguments from left to right. An argument that reassigns the variable does not change the function that is called. -
The one exception is a
mutatingcall on a struct place, such ash.p.bump(x),gq.bump(x)orp.bump(x)on a struct variable. The place's root (h) is evaluated first. Its field reads (.p), or the struct variable or global that is the receiver, are taken after the arguments. The call therefore runs on the record the place holds once the arguments have run, so an argument that stores a new struct into the place is seen by the call. -
That exception goes by the receiver's declared type, not by what it holds at run time. A receiver typed as an interface, or as a generic or optional type that may hold a struct or a collection (
Array,Map,Set), is read first like a class receiver, also when it holds a struct or a collection and the call ismutatingor a collection verb. The call runs to its end on the value it read: an argument that stores a new value into the field does not change the call; for a call that is not a collection verb, the field then keeps the new value. A collection verb called this way then stores its result into the place, so it replaces a value an argument stored there: throughIIterable<int> f,h.f.add(h.g())wheregappends7leaves[1, 2], while the typedArray<int>form runs the argument first and leaves[1, 7, 2]. -
The element order. Every store into an element (an
Arrayelement or aMapvalue, whatever its type:a[i] = v,m[k] = v,ps[i].x = v,ps[i].prop = v), every compound store into one (a[i] += v,ps[i].x += v), and everymutatingcall on an element place (ps[i].m(a)) read in ONE order, whatever the element's type or the member's kind (a field and an accessor may differ in what the write does, never in the order of the reads around it):- the root of the place and every index on the way, once, first, from the variable outward;
- the arguments, or the right-hand side;
- a hop read through an accessor (a getter, or a pair's
get), as the last read of the receiver, with the collection itself; the element's copy, and the check's hold, are taken here; a compound store reads the element here, after its right-hand side; - the call or the store, and through a get/set pair its setter last.
So
a[f()] = g()runsf,g, then the store;a[f()] += g()runsf,g, the read, the store;m[k()] = g()runsk,g, the store. The right-hand side always runs before the element is written, so one that writes the collection loses nothing. Only a?.hop on the way moves its getter read ahead of the arguments (member access). Since value-model M5 the index runs before the right-hand side and a compound store reads the element after it (both used to run the other way); this changes the output of a store whose index and right-hand side both have side effects. -
An array element or a map value of struct type is such a place too (
xs[i].bump(x),xs[i].p.bump(x),m[k].bump(x)). Every index on the way to the element (i, andjingrid[j].cells[i].bump()) is evaluated once, before the arguments; the element is read after them. The call then runs on a copy of the element, which is stored back into the collection when the call returns. While the call runs, changing that collection's value is a run-time error; reads are fine. A write counts whatever path it takes: a store intoxs[i]or another element or key, a swap, a removal of the keykor of an index, a verb (add,removeAt,remove), amutatingcall on another element, a replacement of the collection. When the call returns, such a write raises aRuntimeExceptionthat names the collection, the element and the remedy: copy the element out, call the method on the copy and store it back, or change the collection after the call. The write stays and the copy is dropped; a class instance held in a maybe-typed collection keeps its own changes, being shared. A call that throws propagates its own exception: the copy is stored back when the collection was not written and dropped when it was. A call that leaves the place holding the very collection it started with (it restores it, or assigns it to itself), or writes an equal value (xs[1] = xs[1]), raises nothing and loses nothing. A write to another collection is no error, nor is a write to an outer collection that leaves the element's own collection in place. This changes behaviour for existing programs (the store-back used to overwrite such a write). The window opens after the place's indices ran, so an index that writes the collection is no error. An element of a maybe-typed collection (Array<IB>,Map<string, IB>) takes the same rule for amutatingcall, and so does asetaccessor on an element. A getter-only, static-getter or class-typed accessor-pair hop that yields an object on the way to the collection runs its getter once for the call, and the check and the store-back go through the object it returned, as for a call root. Through a property with both agetand asetthat yields the collection itself or a struct holding it, the getter is read again for the check: a changed value raises before the set, otherwise the set writes the copy back (get, change, set). A getter that builds a fresh collection on every read raises nothing when nothing was written. A non-mutatingcall on any element reads a copy of it. -
The receiver is the place; operands are values.
-
A
mutatingcall's receiver is always the variable or place you named, never a copy of it: the call's change lands there on every engine, whatever the arguments do (i.bump(i.bump(1))bumpsitwice). -
A receiver read from a field of a class object, of a struct, or from a global — whether its type is a struct or may hold one (an interface, a generic or optional type, a
latefield) — is that slot's struct for the whole call,mutatingor not, with or without arguments. A change that an argument or the method body makes to it in place is seen throughthis(h.b.look(h.b.add(1))andh.d.peek(h.d.add(5))run on the struct after theadd). An argument that stores a new value into the slot leaves the call on the struct it read. -
A non-
mutatingcall's receiver that is a local variable, a parameter orthisis read like an earlier operand: if a later argument writes it, the call sees the value from before that argument ran. A field of a local (w.b) is a place like any field. This changes behaviour for existing programs: a non-mutatingcall on such a field now runs on the field, sow.b.look(w.b.add(1))prints22where it printed12. -
Every other operand is its value at the point it is read, a struct included. This covers an argument, both operands of an operator, the indexed value and the index of an index read, the index of an index store, an element of an array literal and an interpolated piece. A later operand that changes that struct in place does not change the operand, and neither does the operator's or indexer's body (
two(h.b, h.b.add(1))passesh.bas it was before theadd). An operator's or indexer's body gets its parameter as its own copy, as a function does, so changing it changes nothing in the caller. -
A
mutatingcall on a temporary struct — a call result (xs.at(0).bump()), a construction, an assignment's value ((a = b).bump()), a?:,matchor??result, a property with only agetaccessor — is a compile error, because its change would be lost. Seelang.reference-and-value-semantics. -
A
mutatingcall or a collection verb inside a lambda on a captured value is a compile error, because the lambda captured the value by copy and the change would be lost:p.bump()with a struct localp,xs.add(1)with anArraylocalxs,ps[0].bump()andw.xs.add(1)through a captured struct or collection (cannot call mutating method 'add' on captured 'xs' in a lambda: ...). Return the new value from the lambda instead, or (oncerefparameters land) take the variable as arefparameter. Which calls count is theconstrule's, by the receiver's declared type, never by what it holds at run time: amutatingcall or a collection verb through a captured value typed as an interface or an optional (ib.add(1)withIB ib,ob?.add(1)) is an error too, also when it holds a class instance, and the message then also names the narrow to the class or a class-typed capture. A call on a receiver whose declared type is a class, or an optional of a class (om?.bump()withC? om), is allowed,mutatingor not, since the object is shared (as it is through aconstorreadonlyclass variable). Inside a struct method, amutatingcall onthisin a lambda (bump(),this.bump()) is the same error, sincethisis captured by copy. Seelang.primary-expressions.
Which callable does a bare name call
Inside a class body, an unqualified call f(args) is resolved in this order:
- a local variable or parameter of function type named
f; - a callable member of the class named
f, including inherited members, so a bare call in a derived class reaches a base-class method; - a free function named
f; - a global variable of function type named
f.
Outside a class the same order applies without step 2. A global of function type is called like a function, from any function or method that can see it, and the call runs whatever function the variable holds at that moment:
Calling a global of function type
use io::console;
(int) => int scale = (int x) => x * 2;
int twice(int v) => scale(v) + scale(v);
console.writeln(scale(21));
scale = (int x) => x * 10;
console.writeln(twice(1));
42
20
A global of function type declared in a namespace is called the same way through its qualified name, N::scale(21), and the arguments are checked against the function type it is declared with.
A callable member shadows a free function of the same name completely. If the member exists but none of its overloads accepts the arguments, the call is an error: it does not fall back to a free function that would have fitted. To reach the free function, qualify it with its namespace (NS::f(args)). A plain data field with the same name as a free function does not shadow it, so a call still reaches the function. Neither does a get/set accessor. What counts is the class the call is written in, including what it inherits: a method that only a subclass declares does not take over a bare call written in the base class, although an override of a member the base class does declare is dispatched as usual. The rule is the same for code that runs at compile time (a comptime initializer calling such a method gets the same target as the program at run time).
A bare name used as a value, not called, follows a similar order: a local or parameter first, then a data member of the class, including inherited ones and including fields of function type, and only then a global or free function. So inside a class, apply(handler) passes the field handler even when a free function of that name exists.
A class member shadows a free function
use io::console;
string tag(int n) => "free";
string handler(int n) => "free handler";
string apply((int) => string f) => f(1);
class C {
string tag(int n) => "member";
string which() => tag(1);
(int) => string handler = (n) => "field handler";
string run() => apply(handler);
}
console.writeln(C().which());
console.writeln(tag(1));
console.writeln(C().run());
console.writeln(apply(handler));
member
free
field handler
free handler
Examples
use io::console;
string fmt(string text, int width = 5) => "${text}${width}";
console.writeln(fmt(width: 2, "x"));
// error: positional argument after named argument
int f<T>(T x) => 1;
console.writeln(f::<int, string>(3));
// error: call to 'f' expects 1 explicit type argument, got 2
console.writeln(f::<int>("s"));
// error: argument for parameter 'x' has type 'string', expected 'int'
Explicit type arguments on functions and methods
use io::console;
class Mapper {
R wrap<R>(R v) => v;
}
T first<T>(Array<T> xs) => xs.at(0);
console.writeln(first::<string>(["a", "b"]));
console.writeln(Mapper().wrap::<int>(3) + 1);
a
4
A receiver typed as an interface is read before the arguments, even though it holds a struct here. The call finishes on the old value, and the field keeps the one swap stored:
A receiver typed as an interface is read first
use io::console;
interface IB {
mutating int add(int n);
int get();
}
struct B : IB {
int v;
new B(int a) { v = a; }
mutating int add(int n) { v = v + n; return v; }
int get() => v;
}
class H {
IB b = B(1);
int swap() { b = B(50); return 2; }
}
H h = H();
console.writeln(h.b.add(h.swap()));
console.writeln(h.b.get());
3
50
The same field read as an argument is its value at the read, and read as a receiver it is the field's struct for the call:
An operand is a value, a receiver is the place
use io::console;
interface IB {
mutating int add(int n);
int look(int n);
int get();
}
struct B : IB {
int v;
new B(int a) { v = a; }
mutating int add(int n) { v = v + n; return v; }
int look(int n) => v * 10 + n;
int get() => v;
}
class H {
IB b = B(1);
}
int two(IB a, int n) => a.get() + n;
H h = H();
console.writeln(two(h.b, h.b.add(1)));
h = H();
console.writeln(h.b.look(h.b.add(1)));
3
22
Notes
Defaults on parameters whose type is a type variable are not supported.
See also
- Array — An ordered sequence of values of one type,
Array<T>, with value semantics. - Construction — Creating objects by naming the type, choosing a constructor by label, supplying type arguments, and building a class that declares no constructor.