Operators and control flow

Sysl’s operator set and precedence, comparison chains, blocks that yield values, if, while, match and return.

Operators

Avin has Sysl’s operator set and precedence. Operators are trait methods (+ is Add, < is Ord, == is Eq), so a generic needs the bound that supplies one, and a user type gains one through an impl. A data type or a class may also define the arithmetic and ordering operators as ordinary methods, with any operand and result types: start + delay with an Instant and a Duration.

OperatorTraitMethod
+ - * / %Add Sub Mul Div Remadd subtract multiply divide remainder
unary -Negnegate
== !=Eqequals, and its negation
< <= > >=Ordless lessOrEqual greater greaterOrEqual

Each method takes and yields the implementing type: add(other: Self) -> Self. Ord requires Eq; a type implements its compare(other: Self) -> int, negative, zero or positive, and inherits the four comparisons from it, implementing any of them as well where it can answer more directly. The built-in types implement the traits their operators have, so int is an Add and an Ord, and string is an Add (joining) and an Ord. Both operands of an operator reached through its trait are of one type, with one conversion: an integer beside a value of a type that implements FromInteger, such as BigInt, is converted to that type, on either side, so big * i, 1 + big and big < n read as they would on integers (types). The wrapping, saturating and shift operators belong to the built-in types alone; &, ^ and | are the integers’ and bytes’ bitwise operators, and on any other type the methods of those names.

Add and Mul also name their identities, as static members of the implementing type: static zero() -> Self, which add leaves a value unchanged by, and static one() -> Self, which multiply does. Every implementation gives them: the integers’ are 0 and 1 at each width but i1, which holds 0 and -1 and has no 1: i1.one() is a compile error, and one() reached at i1 through a generic traps; real‘s 0.0 and 1.0, and string‘s zero is the empty string. Generic code reaches them through the bound:

total[T: Add](items: Vector[T]) -> T
  var sum = T.zero()
  for x in items
    sum = sum + x
  sum

data Point(x: int, y: int)

impl Add for Point
  add(other: Point) -> Point = Point(x + other.x, y + other.y)
  static zero() -> Point = Point(0, 0)
FamilyOperators
Arithmeticunary + -; + - * / %
Explicit wrapping+% -% *%
Explicit saturation+\| -\| *\|
Bitwise~ & ^ \|
Shifts<< >> (shifts bind like multiplication)
Logical!, short-circuit && \|\|
Comparison== != < <= > >=, chained
Identity=== !== (one side a reference type; see identity)
Range.. ..<
Cons::, prepending to a List (right-associative)
Pattern testis, is not
Propagationpostfix ?
Assignment= and compound forms (+=, <<=, +%=, …)
Yielding assignment:= and compound forms, which return the stored value
Updateprefix and postfix ++ --; prefix yields the new value, postfix the old
Symbol methodsany other run of operator characters names a method, called infix at the level of its first character, or tightest when it has a ~ in it: xs ++ ys, x +: xs, a <~ b, x #:: rest

An operator is the longest run of the characters + - * / % < > = ! & | ^ ~ : ? #, so a prefix operator written directly after another operator needs a space: a = -1, x * -y. A run stops before //, which begins a comment. The range operators .. and ..< are spelled with dots, which are not operator characters.

Bitwise operators bind more tightly than comparisons: x & mask == 0 tests the masked value. Within the bitwise family, & binds tightest, then ^, then |. Shifts bind at the multiplicative level, so 1 + 2 << 3 is 17. A shift count at least as large as the width shifts everything out. It is not masked.

:: binds more loosely than every arithmetic and bitwise operator and more tightly than ranges and comparisons (the full table, with the methods named by symbols, is under methods named by symbols), and it groups to the right: n + 1 :: rest is (n + 1) :: rest, and 1 :: 2 :: [] is 1 :: (2 :: []).

Sysl’s pointer operators (prefix * and &) and await are not part of Avin.

Infix method calls

Any method that takes one argument can be called as an infix operator, without the dot and the parentheses: a max b is a.max(b), and xs zip ys is xs.zip(ys). The caller chooses the form; the method’s author does not mark it. a m (b, c) passes the tuple (b, c) as the one argument.

An infix call by a word groups to the left and binds more loosely than the arithmetic, bitwise, shift, cons and range operators, and more tightly than comparisons, is, && and || (a method named by a symbol binds by its first character): a max b + 1 is a max (b + 1), a max b max c is (a max b) max c, and xs contains x && ok is (xs contains x) && ok. There is no postfix form: xs size is an error, written xs.size.

An infix call stays on one line. A line that ends with the method’s name continues it: the argument is the indented block on the lines that follow.

val widest = current max
  measure(header) + padding

A name that starts a line never continues the line above, inside brackets too: end the line with the name instead. A method named by a symbol is an operator and may start a continuation line. An indented block after a call is the call’s trailing block, except that one holding only a name and an operand is reported as this mistake.

The call is resolved exactly as a.m(b) is: overloads are chosen by the argument’s type, a trait or open method dispatches on the receiver’s class, an impl adds methods that can be called this way, and a generic method’s type arguments are inferred. The name must be a method of the receiver’s type that can take one argument, which a method with a repeated last parameter can: w surround "!" gives surround(marks: string*) one mark. A field holding a function is not called infix, and neither is a function m(a, b) declared outside the type: a m b never means m(a, b). A method of two parameters is not called infix even with a tuple after its name: a put (1, 2) against put(i: int, j: int) is an error that says to write a.put(1, 2).

A word that keeps its meaning after an operand, such as then, do, else, if, is or match, is never read as a method’s name, so if a max b then c and n is int read as before.

Methods named by symbols

A method may be named by a run of operator characters, declared like any other method in a class, trait, object or impl, and called infix or dotted:

class Bag(val items: Vector[int])
  ++(other: Bag) -> Bag = Bag(items ++ other.items)
  +:(x: int) -> Bag = Bag(x +: items)

a ++ b is a.++(b), and a.++(b) may be written as such. A function outside a type cannot be named by a symbol. Some of the language’s own operators are not method names: declaring a method named == is an error that says to implement Eq. The reserved spellings are the wrapping and saturating +% -% *% +| -| *|, && ||, == != === !==, ::, = := : ? -> =>, and each yielding compound form such as +:= and <<:=. Every other run is free, ++, --, >>> and the plain compound spellings += and -= among them.

&, ^, |, ~ between two operands, and the shifts << and >>, are free too, on every type but the integers and bytes, whose bitwise and shift operators are the machine’s: a method of one of these names on int or byte, in an extension too, is an error. On any other type, a | b calls a‘s method | and a >> b its method >>, each at its operator’s own level, so a parser combinator (p >> f), a set of flags, a stream or a query builder can be written with them. Prefix ~ stays the integers’ and bytes’ complement, and ~a on another type calls its method ~ taking no argument, an operator method, and is an error where it has none.

data Flags(bits: int)

impl Flags
  |(other: Flags) -> Flags = Flags(bits | other.bits)
  &(other: Flags) -> Flags = Flags(bits & other.bits)

val rw = Flags(1) | Flags(2)

Operator methods

The arithmetic operators + - * / % and the orderings < <= > >= are free method names on a data type, a class or a trait, with any operand and result types, and overloaded by the operand’s type like any method. a + b calls a‘s method + where a‘s type, or a type parameter’s bound, has one taking one argument, at the built-in +‘s own precedence, so a + b * k is a + (b * k) whichever of them are methods:

data Instant(epochMicros: long)

impl Instant
  +(d: Duration) -> Instant = Instant(epochMicros + d.micros)
  -(d: Duration) -> Instant = Instant(epochMicros - d.micros)
  -(earlier: Instant) -> Duration = Duration(epochMicros - earlier.epochMicros)

class Vec(val x: real, val y: real)
  *(k: real) -> Vec = Vec(x * k, y * k)
  *(other: Vec) -> real = x * other.x + y * other.y
  -() -> Vec = Vec(-x, -y)

val deadline = start + timeout
val waited = now - start
val scaled = v * 2.0
val flipped = -v

A prefix -a calls a method - taking no argument, and so do the other prefix operators: !a calls a method !, ~a a method ~ and +a a method +, each taking no argument and yielding whatever it is declared to, at the prefix level, so !a.b is !(a.b) and ~a + b is (~a) + b. A method ! takes no argument at all, since ! has no binary form; ~ and + may also be overloaded with one argument for a ~ b and a + b, which a prefix operator never calls. A query builder’s !cond builds the negated condition and a bit set’s ~bits its complement:

data Cond(sql: string)

impl Cond
  !() -> Cond = Cond(s"NOT ($sql)")

class Bits(val word: int)
  ~() -> Bits = Bits(~word & 255)
  +() -> int = word

trait Flip
  !() -> Self

twice[T: Flip](x: T) -> T = ! !x

A trait may declare them, so a type parameter bounded by it has them, and a value of the trait dispatches on its class. Two prefix operators written together are one name, so nested ones are written apart: ! !x, - ~x. In an if, a while or an operand of && and ||, !a is a condition only where it is a bool: if !stack reads where the method ! yields bool, and is an error where it yields a Cond. A prefix !, ~ or + on a type with no method of its name keeps its own meaning, so it is an error on a data type or a class: ! needs a bool, ~ an integer or a byte, and + a number. No core trait stands behind them, as Neg stands behind -.

Where a type has no method of an operator’s name, the operator is its core trait’s, Add‘s add for +, as it always is in generic code: a type with both a method + and an impl Add has its method called by a + b and add called by a function bounded by Add. a < b alone calls the method <, whatever it yields, so a query builder’s age < 30 can build a condition. A comparison by a method chains when it yields bool: lo <= x < hi through methods <= and < is a comparison chain, and a link whose method yields anything else makes the chain an error. x += y and the other compound forms assign through the method: deadline += grace is deadline = deadline + grace.

The built-in types keep their operators: a method of one of these names on int, real, byte, char, string, bool or a tuple, in an extension or a trait implementation, is an error, so + on two ints is always the machine’s addition, and so is a method !, or ~ taking no argument, there: ! on a bool is always its negation. == and != stay Eq‘s.

One exception puts a built-in value on an operator’s left. An impl adding methods to int, long, real, byte, char, string or bool, in the type’s module or as an extension, may add a binary operator method, an arithmetic, ordering, bitwise or shift one, whose one parameter is of a type the program declares: a data type, a class, a trait or an opaque type, of any type arguments. Its operand is never built-in, so an operator between two built-in values still never reaches a method. k * v with k a real calls real‘s method * taking v‘s type, chosen statically by that type like any overload; where the left type has no method of the name the operator keeps its own meaning. An integer literal on the left is an int where int has a method taking the right operand, and otherwise the long, then the real, that has one, so 2 * v reads as it is written. A trait implementation cannot add one, and a method of this kind taking a built-in type, a tuple, a function, a union or a type parameter is an error. An extension’s is seen where its module is imported, as every extension method is:

data Vec(x: real, y: real)

impl Vec
  *(k: real) -> Vec = Vec(x * k, y * k)

impl real
  *(v: Vec) -> Vec = v * self

val doubled = 2.0 * v
val tripled = 3 * v

A symbol method’s call binds at the level of the language’s operator its name’s first character belongs to, so a name reads with the operator it resembles, unless the method declares another (below). One character overrides the first: a name with ~ anywhere in it binds at the tightest symbol level, so ~, ~>, <~, <~>, ~! and ^~ all bind together, the way a grammar’s sequencing operators are read. A leading # is passed over, so a name starting with # binds at the level of its first other character: #:: binds as :: does and #+ as +. A name of # alone, ##, binds at the tightest symbol level, and a single # is no operator. The levels, tightest first:

LevelOperatorsSymbol methods whose name starts with
Prefixunary - + ! ~
Other symbols~ ?, and any character no lower level takes: ~>, ??; and every name with a ~ in it: <~, ^~
Multiplicative* / % << >> *% *\|* / %, << and >>: *:, <<<
Additive+ - +% -% +\| -\|+ -: ++, +:, --
Bitwise and&&: &&&
Bitwise exclusive or^^: ^^
Bitwise or\|\|: \|>
Cons:::: :+, :::, #::
Range.. ..<
Named callsa max b
Comparison== != < <= > >= === !==, is< > = !: <=>, <>, !!
Logical and&&none; a method declared @precedence("&&")
Logical or\|\|none; a method declared @precedence("\|\|")
Assignment= := and compound formsa name ending in = that is not a comparison: +=, ++=, \|=

So a ++ b + c is (a ++ b) + c, a ++ b * c is a ++ (b * c), xs ++ ys :+ z is (xs ++ ys) :+ z, and xs ++ ys == zs compares the joined sequence. A grammar written with combinators reads as it would on paper: a ~ b ^^ f | c ~ d is ((a ~ b) ^^ f) | (c ~ d), "[" ~> items <~ "]" ^^ f is (("[" ~> items) <~ "]") ^^ f, and a <~ b ~ c is (a <~ b) ~ c. A ~ name ending in = is still a compound assignment: p ~= q is p = p ~ q.

A symbol call groups to the left, except that a name ending in : groups to the right and takes its receiver on the right: x +: xs is xs.+:(x), and a +: b +: xs is a +: (b +: xs). The operands are still evaluated in the order written, x before xs. Operators of one level that group in opposite directions, whether symbol methods or the language’s own, do not mix without parentheses: a ++ b +: c, a + b +: c and 1 :: xs :+ 2 are errors, and (a ++ b) :+ c and 1 :: (xs :+ 2) are not. Operators of different levels need none: 1 +: xs :+ 2 is (1 +: xs) :+ 2.

A declared precedence

A method named by a symbol may declare the level its calls bind at, by naming the language’s operator of that level in @precedence, and that its calls group to the right with @groupsRight:

class Parser(val name: string)
  ~(next: Parser) -> Parser = Parser(s"$name ~ ${next.name}")
  @precedence("|")
  <|>(other: Parser) -> Parser = Parser(s"$name | ${other.name}")

class Num(val n: int)
  @groupsRight
  ^^(e: Num) -> Num = Num(power(n, e.n))

data Cond(sql: string)

class Column(val name: string)
  >=(v: int) -> Cond = Cond(s"$name >= $v")

class Rows(val sql: string)
  @precedence("||")
  |>(c: Cond) -> Rows = Rows(s"$sql WHERE ${c.sql}")

val p = a ~ b <|> c ~ d             // (a ~ b) <|> (c ~ d), where `<|>` would bind as `<` does
val big = two ^^ three ^^ two       // two ^^ (three ^^ two)
val adults = people |> age >= 18    // people |> (age >= 18)

The level is one row of the table, named by any operator of it: "~" for the tightest symbol level, "*", "+", "&", "^", "|", "::", "==", and the two only a declaration reaches, "&&" and "||"; "-", "<<" or "!=" name their rows as well. No level is added, so the table stays the whole account of how an expression reads, and a declared call binds exactly as the operator its declaration names does. A range, an assignment or the named-call level is not one a method may take. @groupsRight keeps the receiver on the left, a ^^ b ^^ c being a.^^(b.^^(c)); only a name ending in : takes its receiver on the right. A name ending in : groups right already, and @groupsRight on one is an error; @precedence on one moves its level and keeps its grouping. A declared grouping follows the rule against mixing: a ^^ b ^ c is an error, as is a <=< b < c where <=< is declared at "==" grouping right.

A declaration belongs to the method’s name, across the whole program, because a program is parsed before any type is known: a <|> b is read the same way whatever a turns out to be, in the declaring module, in every module that imports it, and in any module holding a value of the type without naming it. So every method of one name in a program binds alike. An overload, another type’s method, a trait’s declaration and each of its implementations either carry the same declaration or one that reads the same, and a method of the name declaring nothing agrees only where the declaration restates what the name gives. Any other is an error naming both methods, reported at the program’s method where the other is the standard library’s: a program cannot declare :+ at *‘s level, since the library’s sequences already read it as ::.

Only a method named by a symbol the language does not use may declare: @precedence on +, |, < or ==, which keep their levels, on an assignment such as ++=, on a method named by a word, which binds as every named call does, and on a function is an error.

A right operand taken by name

A companion object may declare an operator whose name ends in : as a function of two parameters, the left operand and then the right, with the right by name. Then x op: r, where r‘s type is the companion’s class or data type, calls the companion’s op:(x, r): x is evaluated where it is written and r is passed unevaluated, as any by-name argument is. The library’s lazy list is built this way, so 0 #:: 1 #:: rest evaluates rest only when the list’s third cell is read:

class Chain(val label: string, private val after: () -> Chain)
  next() -> Chain = after()

object Chain
  #::(label: string, rest: -> Chain) -> Chain = Chain(label, () -> rest)

endless(n: int) -> Chain = s"c$n" #:: endless(n + 1) // returns; each next() makes one more
  • The right operand’s type decides, and it is known without evaluating it: where that type’s companion declares such an op:, it is called, and it may be called dotted too, Chain.#::("a", rest). A type with a method op: of its own, or one from an impl, whose companion also declares one, makes x op: r an error naming both.
  • Wherever some companion declares op: so, the right operand of every x op: r is checked as a delayed expression, since its type is known only once it is checked. On a type whose op: is an ordinary method, the right operand is then evaluated once, at the call, after x, as a strict receiver is; a return, break or continue leaving it is an error, as in any delayed expression. Operators no companion declares so, +: and :: among them, are unaffected.
  • A companion’s op: with a strict second parameter is not called infix; it is an ordinary function of the object.

There are no prefix or postfix symbol methods, beyond the methods -, !, ~ and + taking no argument that the prefix operators call. ++ and -- keep their update meaning when no operand follows them on the line: i++ and ++i update i, and xs ++ ys calls ++. An operand here is a name, a literal or an opening bracket on the same line, or an indented block on the next; so a ++ -b, with a prefix operator after ++, is (a++) - b, written a ++ (-b) to join.

x op= y calls x‘s method named op= when the type of x has one: buffer += 3 appends, and the buffer need not be a var. Otherwise op= assigns. Where op is one of the language’s arithmetic, wrapping, saturating, shift or bitwise operators, it is the compound assignment it has always been; where op is a symbol method, or &, ^, |, <<, >> or an operator method on a type that has a method of that name, x op= y is x = x op y, so flags |= Flags(4) combines flags into a var, and xs ++= ys joins onto a var vector and xs :+= 4 appends to it. The target is a var local, a var field, a module value or an element xs(i), and its object and indices are evaluated once. A right-grouping name has no compound form, and the yielding forms (+:=) belong to the language’s operators alone. A multiple assignment uses only the language’s compound forms.

Continuation lines

A line that starts with a binary operator or a member’s ., indented deeper than the line above it, continues the expression that line left open:

val atom = number
  | symbol("(") ~> later(expr) <~ symbol(")")
  | ident ^^ Var

val total = a
  + b * c
  - d

val names = people
  .filter(_.age >= 18)
  .map(_.name)
  .sorted

The line break means nothing to precedence: the operators group exactly as they would on one line, so total is (a + (b * c)) - d, atom has three alternatives, and a + b with * c on the next line is a + (b * c). A comparison chain goes on across the lines too. A . binds as it does on one line, to the operand right before it, so names is people.filter(…).map(…).sorted, and a + b with .toString on the next line is a + b.toString.

  • What starts one. Every operator that stands between two operands: the arithmetic, wrapping, saturating, shift, bitwise, comparison, logical, range and cons operators, a method named by a symbol, ~, and ++ or -- with an operand after it. - and + there are binary, written - d or -d. And the . of a member, a method call or a field read, after which the line goes on as any line does: with ? (.get("a")?), more members, calls and operators. A word never starts one (a named infix call ends its line instead, as above), and neither do !, ?, a bracket, = and the compound assignments.
  • Where. Wherever an expression ends a line and has a complete operand: a binding’s value, an assignment, a return value, a call’s argument, a match arm’s or a lambda’s body, a branch of a one-line if, an expression statement.
  • How far. Each following line that starts with such an operator or a . and is still deeper than the line the expression began on continues it, at the depth of a continuation line above it or deeper (indentation that matches no line above is an error, as in any block); the depth means nothing beyond that. The expression ends at the first line back at the depth it began on, or shallower, so a . line at the depth the expression began on is a new statement and an error. A line inside the continuation that does not start with an operator or a . is an error, except a call’s trailing block or an infix call’s argument, indented under its own line as usual.
  • Blank lines and comments between continuation lines are skipped, as they are everywhere.
  • Not after a header. The indented lines after the test of if, elif, while and do … while, a for source and a class’s parents are the form’s body. There, and wherever else an indented block follows a word or a symbol that is not a complete operand (=, ->, else, do, then, a declaration’s signature), a line that starts with -x is a block’s line:
negate(x: int) -> int
  -x

sign(x: int) -> int
  if x < 0
    -1
  else
    1

Inside brackets a line break is not significant, so a line in a call’s arguments may start with any operator at any depth, a method named by a symbol included. A block opened inside the brackets, a lambda’s body, starts its own lines again, where a comma list is a tuple, until its last line: a line that closes a bracket opened before the block ends the block at its first comma, and the items after that comma are the bracket’s own. So spawn(() -> … a + f(n), 67108864) passes the lambda yielding a + f(n) and 67108864, as spawn(() -> a + f(n), 67108864) does; a tuple the block yields there is written in parentheses, (a, b)), and a closing bracket on a line of its own leaves the line above a tuple. Blocks nested in the same brackets, an if‘s, a match‘s or an inner lambda’s, all end at that comma.

Trailing blocks

An indented block on the lines after a call is the call’s last argument. The call’s line ends right after its ), and the block is given to the callee’s last parameter:

retry(3)
  fetch(url)

withFile("data.txt") f ->
  process(f)

zipWith(xs, ys) (x, y) ->
  x * y

A by-name parameter (body: -> T) takes the block as its delayed expression, evaluated at each read of the parameter and not at the call, so retry(3) runs fetch(url) as many times as retry reads body. A function parameter takes a lambda whose body is the block: its parameters end the call’s line before ->, one name (f ->) or a parenthesized list ((x, y) ->, (x: int) ->), as an ordinary lambda’s would be written.

A callee with no other arguments is written without parentheses: a name, a member or a type application, then the block, or one parameter name and ->:

scope s ->
  s.spawn
    part(1)

xs.foreach x ->
  println(x)

A lambda of several parameters needs the call’s parentheses before it, run() (x, y) ->: the parentheses right after a callee’s name always hold its arguments.

The block’s position does not depend on the written arguments. With parentheses it comes after them, and it still goes to the last parameter, past any defaulted one in between: against labelled(label: string, width: int = 4, body: -> string), labelled("box") and a block gives width its default. Positional and named arguments bind as they would without the block, and overloads are chosen with it: a candidate whose last parameter cannot take a block does not fit.

A trailing block applies wherever an expression ends a line: a statement, a binding’s value (val r = retry(3) and a block), an assignment, a return value, a lambda’s or a match arm’s body, the argument of an infix call, the operand of an operator. Inside brackets a line break is not significant, so a call written inside another call’s parentheses takes no block. The forms that already put an indented block after their line keep it:

  • The test of if, elif, while and do … while, a for source and its if guards, and a class’s or object’s parents: the block is the form’s body, so if ready(x) and a block tests ready(x).
  • A local function’s header: helper() or helper(n: int) and an indented block declare a local function. A header’s parameters are typed, so retry(3) and retry(n) are calls. A call with no arguments and a block is written without parentheses.
  • A line that ends with an infix call’s method name, current max: the block is its argument.
  • x match and the bare match function: the block holds the arms.
  • A block whose one line is a name and a single operand, add 2, reads as the method and argument of an infix call that should have ended the line above, and is reported as that.
  • A block whose first line starts with a binary operator is a continuation line: f(1) and - x is f(1) - x.

It is an error to write a trailing block for a call whose last parameter is neither by-name nor a function (the message names the parameter and its type), whose last parameter is already given, or whose callee takes no arguments. A lambda on the call’s own line, f(1) x -> x, is not a trailing form; it is written inside the parentheses.

Comparison chains

a < b <= c is one expression. Operands are evaluated left to right, each middle operand exactly once, and evaluation stops at the first failing link. Parenthesizing a comparison makes it an ordinary bool operand: (a < b) == flag.

A link may call its left operand’s operator method <, <=, > or >=, and links of methods mix with built-in links, == and != among them. Each link chooses its own method among the overloads, by its two operands, so start < t <= limit may call Instant < Instant and then Instant <= Duration. A chain is allowed when every link yields bool; a link whose method yields anything else, as a query builder’s age < 30 yielding a condition, makes the chain an error that names the link, its method and the type it yields, and says to join the comparisons with && or to parenthesize one. The same comparison alone yields whatever its method yields.

Blocks

A block yields its last expression. val bindings are immutable and var bindings mutable; both are scoped to their block. A block whose last item is a declaration yields unit. In statement position a value is discarded, and the branches of an unused if or match need not agree on a type.

answer() -> int
  val result =
    val base = 21
    base * 2
  result

A binding may take a value apart by a pattern that cannot fail: val q, r = divmod(17, 5), or var (lo, hi) = 0, 10, in which every name is a var. A pattern that could fail, such as a literal or a variant of a type with several, belongs in a match.

Multiple assignment

a, b = b, a assigns several places at once. The whole right side is made before any place changes, so this swaps a and b with no temporary. The right side is a tuple, written out or computed (q, r = divmod(n, 10)), with one part per place; a place _ discards its part. The places may be parenthesized: (a, b) = (b, a).

A place is a var local or a var field, written obj.field, self.field, or by its bare name inside its class: self.lo, self.hi = hi, lo, or a module-level var, by its bare name or another module’s through that module’s name: low, store.high = high, low. The object a field belongs to is evaluated first, left to right across the places, before anything else; then the right side is made, then every place is stored.

The compound forms read every place first, then make the right side, then combine and store: a, b += b, a adds each to the other using the values the statement started with.

A multiple assignment is a statement, not an expression: it has no := form, and it fills a whole line, so it is not the body of a one-line if or while.

extendedGcd(a: int, b: int) -> (int, int, int)
  var r0, r1 = a, b
  var s0, s1 = 1, 0
  var t0, t1 = 0, 1
  while r1 != 0
    val q = r0 / r1
    r0, r1 = r1, r0 - q * r1
    s0, s1 = s1, s0 - q * s1
    t0, t1 = t1, t0 - q * t1
  r0, s0, t0

if

label(n: int) -> string
  if n < 0 then "negative"
  elif n == 0 then "zero"
  else "positive"

A one-line branch needs then; an indented branch may omit it. The condition must be a bool. Without an else, an if yields unit.

while

val found = while n < 10 do
  n += 1
  if n == 5 then break n
else -1

The condition is tested before each iteration, and continue returns to that test. break exits the nearest loop and may carry a value, in which case every break value and the loop’s else must agree. The else runs on normal completion. Without an else, normal completion yields unit. A while true loop that no break leaves never finishes, so its type is Nothing.

loop

var k = 0

val found = loop
  k += 5
  if k > 12 then break k * 2

loop repeats its body until a break or return leaves it; continue starts the body again. A one-line loop is written loop do step(). Only a break ends a loop, so there is no else: with break value, every break value must agree and is the value of the loop, and a break without one makes the loop unit. A loop that no break leaves never finishes, so its type is Nothing, and a function may end in one. loop is a keyword and cannot be used as a name.

do … while

digits(n: int) -> string
    var rest = n
    var s = ""

    do
        s = s"${rest % 10}" + s
        rest /= 10
    while rest > 0

    s

var i = 0
do i += 1 while i < 4

The test comes at the end, so the body runs at least once. The body is an indented block with while test on the line that closes it, or a single statement on one line. The value rules are while‘s: a break carries the loop’s value, and an else after the test runs when the test fails, so every break value and the else must agree.

continue runs the test, not the body again. The test cannot read names the body declared, since the body’s scope has ended. A do that starts a line always opens this form; the do of a one-line while body follows its header, so the two never meet.

match

subject match is followed by indented pattern -> body arms and an optional else. It is an expression, checked for exhaustiveness. An arm’s body written on its own line fills that line, so a comma list there is a tuple without parentheses (_ -> 0, 1). Inside brackets whose commas separate items (call arguments, tuple and collection literals, a with change) a comma after a one-line arm’s body ends the arm, the match and the item, as it ends a return value: in f(x match … _ -> 0, "a") the match is the first argument and "a" the second, which may also stand on the line after the arms. A tuple body there is written in parentheses, _ -> (0, 1); a comma after an arm that more arms follow is an error that says so. An arm’s indented body is a block and starts a line again, up to a last line that closes the brackets, which ends at its comma as any block’s does. Patterns include:

  • literals, including negative numbers;
  • inclusive and exclusive literal ranges ('a'..'z', 0..<10);
  • comparison patterns, which bind the value to a name or _ beside one literal bound or between two: n < 0, n >= 100, 0 <= n < 10, 'a' <= c <= 'z'. Between two bounds the comparisons are < or <=;
  • n + k, where k is a positive integer literal: it matches an integer of at least k and binds n to the value minus k, which never overflows;
  • constructors with nested patterns, tuples and ();
  • a variant with fields named alone, bare or qualified (Shipped, Status.Shipped), which tests for the variant and binds none of its fields, as Shipped(_, _) does with one _ per field; Shipped(), with parentheses, is matched against the fields by number;
  • extractor patterns, Name(p1, p2) where Name is a value implementing Extractor, BoolExtractor or SeqExtractor;
  • list patterns: head :: tail matches a non-empty List, grouping to the right (first :: second :: rest);
  • sequence patterns: [] matches an empty sequence and [a, b] a sequence of exactly two elements;
  • type patterns (d: Dog, _: Dog), which also take a union apart, member by member; a union in a type pattern is parenthesized, x: (int | string). A built-in type’s name alone, int or string, is the type pattern _: int;
  • alternatives (1 | 2 | 3), which bind no names and may continue across lines with a leading or trailing |;
  • named patterns (whole @ Some(x));
  • _.

Ranges and comparison patterns match integers, bytes and chars; n + k matches integers. Every pattern form may appear wherever a pattern does, nested inside a constructor (Some(n > 0)) or in a function’s clauses.

A guard (n if n > 0 ->) is evaluated at most once per arm. Literals, ranges, comparison patterns and n + k count toward exhaustiveness by the values they leave out, so arms that together reach every integer need no catch-all:

bucket(n: int) -> string = n match
  n < 0 -> "negative"
  0 <= n < 10 -> "digit"
  n >= 10 -> "large"

Guards do not count, since a guard may fail.

An arm on a refined variant learns the type equalities its result gives, and coverage counts only the variants possible at the type matched.

A type pattern, x: T, matches a value whose type at run time is T and binds it to x as a T; _: T tests without binding. For a class or a trait it matches an instance of any subclass or conforming class, and for a generic type it compares the type arguments exactly (Box[int] is not a Box[string]). The value matched may be an Any, or of a trait’s or an open class’s type, to be taken down to a class. A downcast is written this way, never as a cast:

legs(a: Animal) -> int = a match
  d: Dog -> d.legs
  b: Bird -> b.legs
  _ -> 0

A tuple’s type at run time is the one it was made with, so a tuple type pattern compares that type, not the classes of the objects inside it: t: (Animal, int) holding a Dog does not match _: (Dog, int), nor does (a, 1) with a: Animal as an Any, while a tuple made as a (Dog, int) matches it wherever it is held. A tuple’s type is seen as another where each part converts with no box: a part that is an object is its own Any, so ("a", "b") matches _: (Any, string), while (1, "b") does not, its int being no object, and an (int, bool) matches _: (int | string, bool) only when made with that union there. A part naming a union of objects, _: (Dog | Cat, int), takes the object the tuple holds there when it is one of the union’s members, whatever the part was made as. A pattern on a tuple of known type that no tuple of that type could match is an error, as any such type pattern is. Each part is tested on its own by a tuple pattern with a type pattern inside it, (d: Dog, n) -> …, on a value of a tuple type; an Any is first matched by its tuple type, p: (Animal, int).

A type pattern that can never match, such as s: string on an int, is an error.

Type names in patterns

A type’s name is a type pattern by itself. Each name in the table of built-in types, int, long, byte, real, char, bool, string, unit and every sized integer iN, stands for _: T wherever a pattern does: x is int tests that x holds an int, and x is not string that it holds no string. So does the name of any other type in scope that is no variant: a class, a trait, an object, a data type, an alias, Any and a type parameter, so a is Dog tests for a Dog. A variant’s name is still the variant, so data Cell(value: int) makes Cell the variant’s pattern, and Circle matches the variant Circle. It keeps a type test short where one is wanted most:

kind(x: Any) -> string = x match
  int | long -> "an integer"
  string -> "text"
  _ -> "something else"

size(v: int | string) -> int = v match
  int -> 1
  string -> 2

The name tests and binds nothing, so the value is bound beside its type as n: int, or whole as n @ int, and _: int | string and _: Dog | Bird are two such alternatives. A generic type’s name alone is an error, since a type pattern compares the type arguments: x is Box asks for _: Box[int] or whichever arguments are meant, and _: Vector[int] and v: Vector[int] stay as they are.

Because a type’s name in a pattern always tests the type, it never names a value. A local, a parameter or a lambda’s parameter named after a type in scope (val Cell = 3, f(Dog: int)) is an error, and so is a pattern binding it (Dog: Animal, Count @ Some(_)). A built-in type’s name is refused as a field’s name too, and in every binding position of a pattern (int: T, int @ p, int + 1, 0 <= int < 9, int*). It reaches coverage and reachability as the type pattern it is: int covers the int member of a union, and an arm after _, after another int or after a supertype’s name is never reached. A type pattern covers every value only when its type is one the matched value already has, so a match on an Any needs a _ arm. A literal does not match an Any; match its type first (n: int if n == 5). In a function’s clauses a type pattern takes an argument apart like any other (size(s: string) = …), but one naming the parameter’s own type is an error, since the signature already says it. In a destructuring binding, whose : begins the binding’s type, a type pattern is in parentheses. A function type in a type pattern is written in parentheses, because an arm’s -> follows it: f: ((int) -> int) -> ….

A match that does not cover every value names one it leaves out, written as a pattern: this `match` does not cover every Shape value, such as `Rect(_, _)`. A value is named only where no arm can match it whatever its extractors answer; where only extractors stand between the arms and every value, the message says so instead: this `match` does not cover every int value, since an extractor may answer that it does not match; add an arm for the rest, such as `_`.

An arm no value can reach is an error: one after _ or a binding, one after a pattern that covers the whole type, and one whose values earlier arms already match, alone or together. The message names the earlier arm that covers it, by its pattern and line. A guard never hides the arms after it, since it may fail; an extractor and a type test are taken to match every value in the arm judged and none in the arms above it, so an arm is called unreachable only when it is, whatever the extractors answer.

data Phase
  Open
  Closing

code(p: Phase) -> int = p match
  Open -> 1
  Live -> 2 // binds a new name, matching every Phase
  Closing -> 3 // error: this arm is never reached: the arm `Live` on line 7 already matches
  // every value it would; `Live` binds a new value there, since no variant
  // `Live` is in scope

A bare name that is neither a variant nor a type in scope binds, so a variant’s name misspelled or not imported matches everything; the message says so when the covering arm’s name starts with a capital letter.

Extractor patterns

A pattern Name(p1, p2) whose Name is not a variant is an extractor: a value, such as an object, a class’s companion, a local or a parameter, whose type implements one of the core library’s extractor traits. The conformance makes the extractor; a method merely named unapply does not. The matched value is passed to the trait’s method, and its answer decides the match:

  • BoolExtractor[A], with unapply(value: A) -> bool, matches where it answers true, and is written with no patterns, Even();
  • Extractor[A, B], with unapply(value: A) -> Option[B], matches its Some: one pattern matches the value whole, and several match the parts of a tuple of as many, Split(key, value) for an Extractor[string, (string, string)];
  • SeqExtractor[A, S], with unapplySeq(value: A) -> Option[S], S a sequence, matches its Some as a sequence pattern does, so Words(first, second) needs exactly two elements and Words(first, rest*) one or more.
object Twice: Extractor[int, int]
  override unapply(n: int) -> Option[int] = if n % 2 == 0 then Some(n / 2) else None

object Even: BoolExtractor[int]
  override unapply(n: int) -> bool = n % 2 == 0

describe(n: int) -> string = n match
  Twice(Twice(q)) -> s"four times $q"
  Twice(h) if h > 100 -> "a large double"
  Even() -> "even"
  _ -> "odd"

val date = Regex("(\\d{4})-(\\d\\d)-(\\d\\d)")
"2024-06-30" match
  date(year, month, day) -> …

The traits are ordinary ones: A is contravariant and B and S covariant, so an Extractor[Animal, string] takes a Dog; an extractor may be held in a value of the trait’s type, passed as a parameter, e: Extractor[string, int], or bound on a type parameter, [E: BoolExtractor[int]]; a data type implements one through an impl; and a subclass keeps its superclass’s conformance. A generic extractor is a value of a generic class, class Pair[A]: Extractor[List[A], (A, A)] matched as pair(a, b) with val pair = Pair[A](). A type implements each trait at one type argument; the trait whose A takes the matched value serves, and where an unapply trait and SeqExtractor both take it, the unapply one does. A type’s name is no value, so it is no extractor whatever static members it has. A pattern naming a value whose type implements no extractor trait is an error that names the trait to implement, from the type’s own unapply or unapplySeq where it has one.

A variant of the name is always the variant, so a data type’s companion implements an extractor trait to be matched by name, not to change what its variant’s pattern means. The method’s parameter accepts the matched value’s type, as any call’s argument would. The method is called once each time the pattern is tested, the patterns inside it are matched against its answer, and its names are bound like any pattern’s; extractors nest, take guards, and appear in is, alternatives, clauses and match functions. An extractor may answer that it does not match, so it never counts toward exhaustiveness: a match relying on one needs a catch-all, and a binding’s or a for‘s pattern, which must cover every value, cannot hold one.

Match functions

A match with nothing before it is a function of one value, which its arms match. The arms are exactly those of a match: patterns, if guards, -> and block bodies. One arm may stand on the match line; several go in an indented block, which may open inside parentheses or after an infix method’s name at the end of a line:

val radii = shapes.collect(match Circle(r) -> r)

val sizes = shapes.map(match
  Circle(r) -> r * r * 3.14
  Rect(w, h) -> w * h)

val firstBig = shapes collectFirst match
  Circle(r) if r > 10.0 -> r

The type of the value it matches comes from the type expected where it is written, as a lambda’s parameter type does; a match function with no expected type is an error asking for one. Where a function type A -> B is expected, the function is x -> x match … and its arms must cover every A, as any match‘s do: pairs.map(match (k, v) -> s"$k=$v"). A function of two or more parameters is not a match function’s type.

Where a PartialFunction[A, B] is expected, the arms need not cover every A: the function is defined at the values some arm matches. A partial function made this way tests its patterns and guards once each time it is called, lifted or given to applyOrElse; isDefinedAt tests them without running an arm’s body.

is

x is P tests a value against any pattern a match arm takes and yields a bool; x is not P is its negation. order.status is Shipped asks only which variant it is, whatever fields Shipped has, and x is int which type it holds, since a built-in type’s name is a type pattern by itself. not is a keyword only there, directly after is, where it always negates: x is not(y) tests the pattern (y). Everywhere else not is an ordinary name, so a function, method, parameter or local may be called not and not(p) calls it. The names P binds are in scope only where the test is known to have matched:

area(shape: Option[Shape]) -> int
  if shape is not Some(Rect(w, h)) then return 0
  w * h

total(xs: List[int]) -> int
  var rest = xs
  var sum = 0
  while rest is head :: more
    sum += head
    rest = more
  sum
  • if x is P binds them in the then branch, while x is P in the body, and a && b in b.
  • x is not P binds them where the test failed: the else of an if, the else of a while, and the right operand of ||.
  • ! swaps the two: !(x is P) binds like x is not P.
  • A condition binds its operands’ names where it holds, for &&, or where it fails, for ||. Neither side of a is P(v) || b is Q(v) holds wherever the whole does, so the then branch sees no v.
  • After an if whose one branch never finishes (a return, break, continue or trap), the rest of the block sees the names bound for the other branch, as w and h above.

Nowhere else: not in the other branch, not after an if both of whose branches finish, not in the test of do … while, and not after an is used as a value (val big = o is Some(n) && n > 100). Using a name outside its scope is an error that says so. A condition binds a name once; its names may shadow the enclosing block’s, as an arm’s may, except those the block keeps after an if.

return and end markers

return expr exits the enclosing function. Inside a lambda it exits the lambda. Where a return or break value fills a line, a comma list is a tuple without parentheses (return a, b); inside brackets whose commas separate items (call arguments, tuple and collection literals) the value stops at the comma, so f(a = return 1, b = 2) has two arguments and a tuple is written return (1, 2). An indented block inside the brackets starts a line again. Optional end markers (end if, end while, end match, end val, end name) are checked against the construct they close.

defer

defer stmt runs stmt when control leaves the block the defer is written in. What a program takes from outside itself, a file, a connection, a temporary directory, a started command, is given back by a defer written beside the code that took it, rather than at every way out:

copy(from: string, to: string) -> Result[unit, IoError]
  val source = fs.open(from)?
  defer source.close()
  val target = fs.create(to)?
  defer target.close()
  target.write(source.readAll()?)?
  target.close()

It runs on every ordinary way out of its block: falling off the end, return, ? taking its failure arm, and break or continue leaving a loop the block is in. The statement is a single statement on the defer line, or an indented block below it (end defer may close that block).

A deferred statement belongs to its block: a function’s or a lambda’s body, a branch of if, an arm of match, a loop’s body, a turn of an actor, or any indented block. A loop body’s statements run at the end of every turn, so each turn’s resource is given back before the next is taken; a continue or break runs them too, and a break or continue of an outer loop runs the inner loops’ as well. A nested block’s run at its own end, before the code after it.

Several run in the reverse of the order they were written, so resources are given back in the reverse of the order they were taken, and a later one may use what an earlier one guards.

Only a defer that was reached runs. It is a statement, not a declaration: one after a return that left, or in a branch not taken, never runs, and one a call reached is not carried into the next call.

A deferred statement reads its names when it runs. Nothing is evaluated where the defer is written; a var changed after it is seen changed. The value a block yields, and the value of a return or a break, are computed first, then the deferred statements run, so a statement that changes a var does not change a value already computed:

next() -> int
  var n = 1
  defer n = 100
  n // 1

No jump may leave a deferred statement, at any depth: no return, no ?, and no break or continue of a loop outside it, since it runs while its block is already being left. A loop written inside it is its own, and a lambda or a local function written inside it may return from itself. A defer inside a deferred statement belongs to that statement’s block and runs at its end.

A defer is a statement of a block. As a value (a binding’s value, an argument, a one-line function’s body), as a one-line branch (if c then defer f()), or in a class body, it is refused. Its statement’s value is discarded, so defer f.close() on a close that answers a Result gives the Result up; a program that wants the Err closes on its success path first, which a resource’s close allows, since closing twice does nothing.

A deferred statement takes a call out of tail position. A self-call while one is waiting to run, the value of a return included, is a real call, and @tailrec refuses it.

A trap runs nothing. A trap stops the program, or the actor’s turn, where it happens, without running the deferred statements of the functions it stops: the program’s state is already wrong, and cleanup run against it could do harm. An actor’s stopping block still runs, as for any failed turn. A program ended by process.exit runs none either; a file or a connection left open then is closed when the collector frees it.

A cancelled thread runs them all. Cancellation stops a thread at a known point, a wait or a loop’s poll, where nothing is in doubt, so the deferred statements of every frame it drops run there, innermost first, as leaving their blocks any other way would run them: a cancelled query can still tell its server, a transaction roll back, a lease go back to its pool. A deferred statement runs to its end once begun: the cancellation does not stop it inside one, even where it waits, and the thread stops at its next cancellation point after. One that traps stops the program.

fetch(pool: Pool[Conn, IoError]) -> Result[Rows, PoolError[IoError]] = pool.use(c ->
  defer c.cancelIfBusy() // runs if the thread is cancelled while the query waits
  c.query("select ..."))

Search

Esc
↑↓ to navigate ↵ to open Esc to close