sysl

Patterns and matching

Every pattern form, how arms are chosen, what guards do to exhaustiveness, and what alternatives may bind.

match is an expression: it yields a value in value position and acts as ordinary control flow in statement position. It consists of a scrutinee and a sequence of arms, each an ordered list of patterns, an optional guard, and a body.

classify(n: int) -> string
    n match
        0         -> "zero"
        1 | 2 | 3 -> "small"
        4..10     -> "medium"
        else         "large"

print(classify(0), classify(2), classify(7), classify(99))
zero small medium large

The keyword goes after the value. A match transforms the value to its left, so matches can be chained: x match … match … reads in the order the values flow. It binds more loosely than every operator, so the scrutinee is the whole expression before it — a < b match matches on the comparison, and parentheses narrow it. A parenthesised match is an operand of any operator, a + (k match …) * b (expressions).

The else arm has no ->. The arrow separates a pattern from its body, and else is not a pattern but the fallback, which takes its body the way an if‘s else does.

classify(n: int) -> string
    n match
        0    -> "zero"
        else -> "other"

print(classify(0))
the 'else' arm takes its body directly, with no '->' — 'else' names no pattern to separate one from

Two evaluation guarantees:

  • The scrutinee is evaluated exactly once. A side-effecting scrutinee runs one time, and the arms test against the resulting value.
  • Arms are tried top to bottom, and the first whose pattern matches — and whose guard, if any, holds — wins, so a specific arm above a general one takes precedence.

The pattern forms

patternexamplematches
wildcard_anything, binds nothing
else armelse …anything; the catch-all spelling in tail position
literal0, 'a', "hi", truea value equal to the literal
literal, convertedu8(';'), i32(-1), u16(0x41)a value equal to the literal, converted as the expression u8(';') would be
range3..7, 0..<10, 'a'..'z', u8('a')..u8('z'), i8::Min..-1, `LO`..`HI`a value in the range
bindr, otheranything, and binds it to the name
variantCircle(r), Empty, Shape.Emptythat variant, binding each sub-pattern to a field
nestedWrap(Val(v))a variant whose payload itself matches a sub-pattern
struct, positionalPoint(a, b)a struct, binding every field by position
struct, namedPoint{x, y}, Point{x: a}a struct, binding fields by name; unlisted fields unconstrained
tuple(a, b), (a, _)a tuple, by position
unit()unit‘s one value — so it always matches one
namedc @ Circle(r)what the sub-pattern matches, binding the whole value too

Literal patterns match any type with equality; range patterns need a contiguous order. A literal pattern works on the integers, char, string and bool. A match on a bool is exhaustive with both arms present and no catch-all:

word(b: bool) -> string
    b match
        true  -> "yes"
        false -> "no"

print(word(true), word(false))
yes no

A range pattern is restricted to the numeric types and char, over which a contiguous interval is meaningful. string is excluded, since "a".."z" has no useful meaning; a string is matched by literal or by binding.

() is unit‘s pattern, the tuple with no parts. unit has one value, so () always matches and covers the type alone. Ok(()) is therefore an arm, and Ok(()) with Err(…) is an exhaustive match:

check(n: int) -> Result[unit, string] = if n > 0 then Ok(()) else Err("too low")

for n in [1, 0]
    check(n) match
        Ok(()) -> print("ok")
        Err(why) -> print(why)
ok
too low

Against any other type it is refused:

var p = 1
p match
    () -> print(p)
    _ -> print(0)
'()' matches unit, but the value is int

The bare-name rule

A bare identifier in pattern position is a nullary-variant pattern when it names a nullary variant of the scrutinee’s enum, and a binding otherwise.

enum Shape
    Empty
    Circle(r: int)

name(s: Shape) -> string
    s match
        Empty     -> "empty"
        Circle(r) -> "circle " + r.to_string()

print(name(Empty), name(Circle(3)))
empty circle 3

A bare name that is a data variant is a diagnostic rather than a binding, so a payload-carrying variant written without its payload cannot silently become a catch-all:

enum Shape
    Empty
    Circle(r: int)

name(s: Shape) -> string
    s match
        Empty  -> "empty"
        Circle -> "circle"

print(name(Empty))
variant 'Circle' carries data — match it as 'Circle(…)'

Rust and Swift resolve bare names the same way; sysl makes the data-variant case an error rather than a lint.

A qualified name is a pattern wherever a bare one is. Shape.Empty matches exactly as Empty does, so long as the path names the scrutinee’s own enum, under any spelling of it (its full path, an import alias, a local name). A path naming a different enum is refused, even when the scrutinee’s enum has a variant of the same name — as Rust refuses it — rather than being read as the scrutinee’s own variant:

enum Light
    Red
    Green

enum Signal
    Red
    Blue

describe(l: Light) -> string
    l match
        Signal.Red -> "stop"
        else "go"
pattern is Signal but the value is Light

A qualified name can never be a binding, because no declared name contains a dot, so one that resolves to neither a variant nor a constant is a diagnostic rather than a new local.

A const declared inside a function body is a constant here too, and is nearer than one at the top of a file: it is compared against, not bound.

A name that is both a variant and a constant is the variant against its enum and the constant against anything else — the scrutinee’s type is what the pattern expects, as an expected type chooses at a construction:

enum Level
    High
    Low

const High = 9

describe(l: Level) -> string = l match
    High -> "high"
    Low  -> "low"

rank(n: int) -> string = n match
    High -> "nine"
    _    -> "other"

print(describe(High), rank(9), rank(3))
high nine other

A backticked name references rather than binds

The rule above resolves a bare name against a narrow set — the scrutinee’s nullary variants, then the constants — and binds otherwise. A val, a local or a parameter therefore cannot be referenced by a bare name: each is storage read at run time, so there is no compile-time value for the pattern to compare against.

A backtick-quoted name makes the arm a test: an ordinary equality against whatever the name holds when the match runs:

describe(n: int, limit: int) -> string
    n match
        `limit` -> "at the limit"
        else "elsewhere"

print(describe(10, 10), describe(3, 10))
at the limit elsewhere

Written bare, limit would bind, matching everything and leaving the second arm unreachable. The spelling alone shows which is meant, so a reader does not need to know what is in scope.

Three consequences follow. A quoted name that resolves to nothing is a diagnostic, not a new local. A const still folds to its literal, so quoting one changes only how the arm reads. And a run-time equality contributes nothing to exhaustiveness, so an arm written this way never covers a case and a catch-all is still required.

A quoted name may stand as either bound of a range, beside a literal or a type’s bound, after is as in an arm. The bound is whatever the name holds when the match runs, so a range over a val covers nothing for exhaustiveness either:

val LO = 2
val HI = 5

size(n: int) -> string = n match
    `LO`..<`HI` -> "inside"
    `HI`..9     -> "upper"
    else "outside"

main()
    print(size(3), size(7), size(0), 4 is `LO`..`HI`)
inside upper outside true

It cannot appear in a binding, where there is no other arm to take when the value differs:

val limit = 10
val (`limit`, b) = (3, 4)

print(b)
a binding cannot test a value

Alternatives across lines

A long list of alternatives may be written one to a line, with the | either ending the line above or, as Rust and rustfmt write it, beginning the line below. A | may also precede an arm’s first alternative. The leading bars are optional and mean nothing:

classify(n: int) -> string
    n match
        1
        | 2
        | 3 -> "small"
        | 4 | 5 -> "medium"
        10 |
        20 -> "round"
        _ -> "other"

print(classify(2), classify(5), classify(20), classify(7))
small medium round other

A line beginning with | continues the pattern above only until that arm’s ->. After a finished arm it begins an arm of its own, so 1 -> a followed by | 2 -> b is two arms. The continuation lines are written at the arms’ own margin, and a | inside brackets is the bitwise operator it always was.

Alternatives bind the same names

1 | 2 | 3 is one arm matching any of three literals. Alternatives may bind, as in Rust, when every one of them binds the same names at the same types. The body cannot know which alternative matched, so each name it reads has to stand for something whichever one did:

enum Box
    One(v: int)
    Two(v: int)
    Pair(a: int, b: int)

get(b: Box) -> int
    b match
        One(v) | Two(v) | Pair(_, v) -> v

print(get(One(1)), get(Two(2)), get(Pair(3, 4)))
1 2 4

The same holds of an is test, so if b is One(v) | Two(v) names v in its branch. A name one alternative binds and another does not is refused, and so is a name bound at two types:

enum Box
    One(v: int)
    Two(v: int)
    Empty

get(b: Box) -> int
    b match
        One(v) | Empty -> v
        Two(v) -> v

print(get(One(1)))
'v' is bound by one alternative joined by '|' and not by another
enum Cell
    Num(v: int)
    Text(v: string)

show(c: Cell) -> string
    c match
        Num(v) | Text(v) -> s"$v"

print(show(Num(1)))
'v' is bound as int by one alternative joined by '|' and as string by another

A pattern binds by copy, so there is no mutability or ref mode for the alternatives to disagree on.

A guard is asked once for each alternative that matches, in order, with that alternative’s bindings. Pair(v, _) | Pair(_, v) if v > 10 takes Pair(3, 40) through its second alternative after the first one’s guard said no:

enum Box
    One(v: int)
    Pair(a: int, b: int)

big(b: Box) -> string
    b match
        Pair(v, _) | Pair(_, v) if v > 10 -> s"big $v"
        _ -> "small"

print(big(Pair(3, 40)), big(Pair(50, 1)), big(Pair(1, 2)), big(One(99)))
big 40 big 50 small small

Alternatives inside a pattern

A | may stand at any position inside a pattern, not only between whole ones: in a variant’s parentheses, in a tuple’s part, in a struct field, after an @ in parentheses. Some(1 | 2) is the arm Some(1) | Some(2), and coverage counts it that way, so Some(_) and None still finish the match. Parentheses around alternatives group them, and the binding rule above applies to whatever alternatives the |s make:

enum Shape
    Circle(r: int)
    Square(side: int)
    Dot

classify(o: Option[int]) -> string
    o match
        Some(1 | 2) -> "small"
        Some(_) -> "other"
        None -> "none"

radius(o: Option[Shape]) -> int
    o match
        Some(Circle(r) | Square(r)) -> r
        Some(Dot) | None -> 0

grid(t: (int, char)) -> string
    t match
        (0 | 1, 'a' | 'b') -> "corner"
        (n @ (5 | 6), _) -> s"edge $n"
        _ -> "inside"

print(classify(Some(2)), classify(Some(7)), classify(None))
print(radius(Some(Square(4))), radius(None))
print(grid((1, 'b')), grid((6, 'z')), grid((3, 'a')))
small other none
4 0
corner edge 6 inside

Each | multiplies: (1 | 2, 3 | 4) is four alternatives. A pattern that would spread into more than 1024 is refused. A val, a var or a for may hold alternatives too, as long as together they cover every value, which is what makes the pattern irrefutable.

A name may be bound twice in one match, but not in one pattern

Each arm is its own scope, so two arms may reuse a name freely. Inside one pattern a repeat is refused, because each name is bound once however deeply the pattern nests, and a second binding would silently refer to a different part of the value:

struct Point
    x: int
    y: int

var p = Point(3, 3)

p match
    Point(v, v) -> print(v)
'v' is bound twice in one pattern, and the second would quietly stand for a different part of the value — rename it, or compare the two in a guard

Point(v, v) looks like a test that the two fields are equal, but no pattern compares two parts of the value; that is what a guard is for. Scala, Rust, OCaml and Haskell all refuse it for the same reason.

n @ pat — matching and naming at once

A pattern that takes a value apart gives the arm only the parts. Where the arm also needs the whole value — to pass it on, store it or return it — @ binds it beside them:

enum Shape
    Circle(r: int)
    Rect(w: int, h: int)

area(s: Shape) -> int
    s match
        Circle(r) -> r * r * 3
        Rect(w, h) -> w * h

describe(s: Shape) -> string
    s match
        c @ Circle(r) -> s"circle r=$r area=${area(c)}"
        other -> s"other, area=${area(other)}"

print(describe(Circle(2)))
circle r=2 area=12

Without it the arm would have to either destructure and lose the whole value, or bind it and test the shape again inside the body.

A binding is not a test, so a named arm covers exactly what the sub-pattern covers: it neither requires nor makes unreachable any other arm. It nests, since the part after the @ is an ordinary pattern: whole @ One(part @ Val(n)) names three things at three depths. It is also read at an is test and at a binding, where var whole @ Point{x, y} = p gives the value a name alongside its fields.

The name must be one a program could declare, so a qualified name is refused: a binding introduces a local, and a local’s name has no dot.

This @ and an annotation’s are the same character but never conflict. An annotation’s @ is a prefix, on its own line above a declaration; this one is infix, between a name and a pattern. No declaration can appear where a pattern is read, so the two positions never overlap. Scala uses the same arrangement.

Struct patterns

A struct can be destructured in two ways, which serve different purposes.

struct Point
    x: int
    y: int

describe(p: Point) -> string
    p match
        Point(0, 0) -> "origin"
        Point{x: a} -> "x is " + a.to_string()

print(describe(Point(0, 0)), describe(Point(5, 1)))
origin x is 5

Positional (Point(a, b)) is total. It mirrors positional construction and must name every field, with _ to skip one. Adding a field to the struct therefore makes each positional match an arity error, as a new enum variant makes a match non-exhaustive. Use it where every field must be handled.

Named-field (Point{x, y}) is partial. It binds by field name, so it is order-independent, supports renaming ({x: a} binds field x to a), and may list a subset — any field left out is unconstrained. Adding a field never breaks a named pattern. Use it to take only the fields you need. There is no .. token, because the positional form already covers the total case.

Point(a, b) has the same syntax as a variant pattern but is not ambiguous: the compiler resolves it by what Point denotes. A struct type gives a struct pattern and an enum variant a variant pattern, by the same name resolution the bare-name rule uses.

A tuple pattern is a struct pattern without the name. (a, b) binds both components, (a, _) binds one, and nesting works. A tuple has one shape, so a tuple pattern is irrefutable and covers its position for exhaustiveness exactly as a struct pattern does.

Both forms compose with everything else: a struct pattern nests inside a variant pattern and vice versa, and each bound sub-pattern is itself any pattern in this table.

A pattern at a binding

Patterns are not limited to match. A val or var binding takes one too, and so does the variable of a for loop, which binds as a binding does and follows every rule in this section:

struct Counter
    n: int

pair(c: *Counter) -> (int, int)
    c.n = c.n + 1
    (1, 2)

once()
    var c = Counter(0)

    val ((p, q), r) = (pair(&c), 3)

    print(p, q, r, c.n)

shape()
    val ((x, y), _) = ((3, 4), 5)
    var (lo, hi) = (0, 10)

    hi += 1

    print(x, y, lo, hi)

once()
shape()
1 2 3 1
3 4 0 11

The value is evaluated exactly once, as a scrutinee is: it is stored in an unnamed temporary, and every part is a field read of that temporary. pair() runs once however many names are bound from it; the 1 at the end of the first line is the count.

A var pattern makes every name it binds assignable and a val pattern makes each write-once, exactly as the single-name forms do. A _ binds nothing and skips its part. Where there is no keyword — a match arm, an is, an @ — the binding is written once, as a name with no var before it is.

Because the value is evaluated once, before any name is bound, a swap works as expected:

show()
    var (a, b) = (1, 2)
    val (c, d) = (b, a)

    print(a, b, c, d)

show()
1 2 2 1

Only an irrefutable pattern may stand there

A binding has no other arm to take, so the patterns allowed in one are exactly those that cannot fail — a tuple pattern, either struct form, a name, a wildcard, any nesting of these, and alternatives that together cover the type — and every pattern in the table above that is a test is refused, with a diagnostic naming it.

A for header is a binding under this rule just as a val is: a loop has nowhere to send an element of an unexpected shape, so it accepts the same subset and refuses the same patterns with the same message.

A struct qualifies because it has exactly one shape, as a tuple does, and both struct forms are allowed:

struct Point
    x: int
    y: int

struct Pair
    both: (int, int)

show()
    val Point{y, x} = Point(3, 4)
    val Point(a, b) = Point(5, 6)
    val (Point{x: px}, k) = (Point(7, 8), 9)
    val Pair((lo, hi)) = Pair((10, 11))

    print(x, y, a, b, px, k, lo, hi)

show()
3 4 5 6 7 9 10 11

The two forms differ here as they do in a match. The named form may leave fields out, and an unlisted field binds nothing. The positional form names every field, so adding a field to the struct makes each positional binding an error to revisit rather than one that silently binds the same names:

struct Point
    x: int
    y: int
    z: int

show()
    val Point(x, y) = Point(1, 2, 3)

    print(x)

show()
struct 'Point' has 3 fields, but 2 sub-patterns were given

Name(…) is resolved as a struct pattern here by the ordinary rule: the value’s type decides between a struct pattern and a variant pattern, exactly as in an arm.

A literal is a test:

show()
    val (1, b) = (1, 2)

    print(b)

show()
a binding cannot test a value — this pattern matches only some values, and a binding has no other arm to take when it does not match

So is a range, with the same diagnostic.

A variant is a choice among shapes, and has its own diagnostic:

enum Shape
    Circle(r: int)
    Square(s: int)

show()
    val (Circle(r), b) = (Circle(1), 2)

    print(r, b)

show()
a binding cannot choose among variants — this pattern matches one of several shapes, and a binding has no other arm to take when the value has another

Each of these belongs in a match, where a value that does not match can go to another arm.

Alternatives at a binding

A pattern of |-alternatives is irrefutable when the alternatives together cover every value, so a binding takes one, as Rust’s let (Ok(x) | Err(x)) = r; does. Each name is bound from whichever alternative matched. The alternatives are written in parentheses, and a | inside a part spreads as it does in an arm, so (a, (Ok(b) | Err(b))) is the two alternatives (a, Ok(b)) | (a, Err(b)):

enum Reading
    Celsius(v: int)
    Fahrenheit(v: int)

either(r: Result[int, int]) -> int
    val (Ok(x) | Err(x)) = r
    x

tagged(t: (string, Result[int, int])) -> string
    val (name, (Ok(n) | Err(n))) = t
    s"$name=$n"

raw(r: Reading) -> int
    var (Celsius(v) | Fahrenheit(v)) = r

    v += 1000
    v

val rs: [3]Result[int, int] = [Ok(1), Err(2), Ok(3)]

print(either(Ok(3)), either(Err(7)), tagged(("k", Err(9))), raw(Fahrenheit(5)))

for (Ok(v) | Err(v)) in rs
    print(v)
3 7 k=9 1005
1
2
3

The alternatives owe everything an arm’s alternatives owe: the same names at the same types, and no alternative that an earlier one already matches, which is dead here as it is in a match. What a binding adds is that there is no other arm, so alternatives that leave a value out are refused:

enum Shape
    Circle(r: int)
    Square(r: int)
    Dot

size(s: Shape) -> int
    val (Circle(r) | Square(r)) = s
    r

print(size(Dot))
a binding cannot choose among variants — these alternatives miss Dot, and a binding has no other arm to take when the value has another

Alternatives of a value that is not an enum are refused in a test’s words when they do not cover it — val (1 | 2) = n:

show(n: int)
    val (1 | 2) = n

    print(n)

show(1)
a binding cannot test a value — these alternatives match only some values, and a binding has no other arm to take when none of them matches

The shape has to line up

A tuple pattern is irrefutable for the tuple it describes, so the arity is checked where it is written rather than at run time:

show()
    val (a, b, c) = (1, 2)

    print(a)

show()
this pattern takes 3 parts, and a (int, int) has 2 parts to give it

Taking apart a value that is not a tuple at all has its own diagnostic:

show()
    val (a, b) = 5

    print(a)

show()
one int is not something to take apart — only a tuple is

And a name may appear once:

show()
    val (a, a) = (1, 2)

    print(a)

show()
'a' is named twice in one binding

A binding a match makes is written once

At a val or a var the keyword decides. In a match arm, in an is, and under @ there is no keyword, so a pattern binding means what a name without var means everywhere else in sysl: it is written once. Assignment to one is refused, and so is &, as for a val.

The reason is that the binding is a copy. A pattern gives the arm the part it matched rather than a view into the original value — a payload binding is a copy — so a write to the name would change only that copy, which is discarded when the arm ends, while appearing to change the matched value.

enum Cell
    Empty
    Full(v: int)

var d = Full(1)

d match
    Full(n) -> n = 99
    Empty -> print("empty")
a pattern binding is written once, because it holds a copy of what it matched — so assignment would reach that copy rather than the value it came from. Where you mean to change something, take a 'var' from the binding first

To change a copy, declare it with var; the matched value is unchanged:

enum Cell
    Empty
    Full(v: int)

var d = Full(1)

d match
    Full(n) ->
        var m = n
        m = 99
        print(m)
    Empty -> print("empty")

d match
    Full(n) -> print(n)
    Empty -> print("empty")
99
1

Rust and Swift refuse the same write and each have a syntax for a mutable copy — Some(mut n), case .full(var n). sysl has none: a var declared from the binding is short, and it makes the copy explicit.

The rule is about the binding, not about what it can reach

Where the payload is a &T, the copy is the reference, so a store through it reaches the object the enum holds — see refcounts survive destructuring. Field selection dereferences, so e.value = 99 is a write through the reference and does not require the binding to be writable:

struct Entry
    value: int

enum Slot
    Empty
    Filled(e: &Entry)

var s = Filled(Entry(1))

s match
    Filled(e) -> e.value = 99
    Empty -> print("empty")

s match
    Filled(e) -> print(e.value)
    Empty -> print("empty")
99

The name is still written once, so it cannot be rebound to another object: e = other in the arm above is refused as at the top of this section, even though the payload is a reference.

Guards

An arm may carry an if guard, evaluated after its pattern matches.

band(n: int) -> string
    n match
        1..10 if n > 5 -> "high"
        1..10          -> "low"
        else              "out"

print(band(7), band(2), band(50))
high low out

A guard is any boolean expression, a bare name included. The -> after it is the arm’s, never the arrow of a closure; a closure inside a guard is written in parentheses, as an argument.

pick(n: int, wide: bool) -> string
    n match
        1..10 if wide -> "wide"
        else "other"

print(pick(3, true), pick(3, false))
wide other

Three rules:

  • A guard runs only when its pattern has already matched, never for an arm that was ruled out, so a side-effecting guard runs only for arms whose pattern fits.
  • A failed guard falls through to a later overlapping arm. The two 1..10 arms above rely on first-match order plus fallthrough; they are not disjoint cases.
  • A guarded arm does not count toward exhaustiveness. The compiler cannot prove a guard holds, so a guarded arm never covers a case: a match covered only by guarded arms still needs a catch-all. This is Rust’s rule.

Exhaustiveness

A match on a data enum must cover every value or carry an unguarded catch-all, and a gap names what is missing:

enum Shape
    Circle(r: int)
    Rect(w: int, h: int)

area(s: Shape) -> int
    s match
        Circle(r) -> r * r

print(area(Circle(2)))
match on 'Shape' is not exhaustive; missing Rect (add an 'else' arm)

This is the main benefit of a closed sum type: adding a variant makes every match on it without a catch-all report what it now misses.

Four rules decide what counts as covered.

Coverage is about which values are guaranteed to be handled, not which tags appear, and the arms are considered together. Some(Halt), Some(Push) and None together cover an Option[Op] even though none of them covers a variant alone, and Some(0) alone does not cover Some, because a Some holding a non-zero value is not handled.

What is missing is reported at the depth where it is missing. A gap inside a payload is reported as missing Some(Push) rather than missing Some, and a position no arm narrowed is reported as a _ standing for all its values, rather than as one line per combination.

A type is covered by listing its values only when it has a finite, known set of them — an enum’s variants, a struct’s single shape, bool‘s two values, and every value of a fixed-width integer or a char. Literals and ranges complete an integer the way variants complete an enum, as they do in Rust: 0..127 and 128..255 cover a u8, and so do i8::Min..-1, 0 and 1..i8::Max an i8, at any width from u1 to u256. A type’s Min and Max may stand in a pattern as values.

half(b: u8) -> string = b match
    0..127   -> "low"
    128..255 -> "high"

sign(n: i8) -> int = n match
    i8::Min..-1 -> -1
    0           -> 0
    1..i8::Max  -> 1

print(half(0), half(255), sign(-128), sign(0), sign(127))
low high -1 0 1

A gap is named as the ranges that are missing, a type’s own bound written as its Min or Max:

code(b: u16) -> string = b match
    0..9    -> "digit"
    20..255 -> "byte"

print(code(3))
match on 'ushort' is not exhaustive; missing 10..19, 256..ushort::Max (add an 'else' arm)

A char is a Unicode scalar value, so it is covered by '\0'..'\u{D7FF}' and '\u{E000}'..'\u{10FFFF}'; the surrogates between them are no value of it. usize and isize are never completed by ranges, as in Rust: their width is the target’s, so ranges that cover one on a 64-bit machine would leave a gap on a 32-bit one, and a match on one that yields a value needs an else:

slot(n: usize) -> int = n match
    0..9           -> 0
    10..usize::Max -> 1

print(slot(3))
a 'match' on 'usize' that yields a value needs an 'else' arm — its width is the target's, so no ranges are treated as covering it

Every other type — a float, a string — is covered only by a wildcard or a binding, so 1.0 -> … on a real still needs an else.

A scalar match must be exhaustive only when it is used for a value. In statement position a non-exhaustive scalar match is allowed, and an unmatched value does nothing. An enum match is checked for exhaustiveness in both positions, because falling off the end of one has no defined result even for effect. For a single-variant test without a catch-all, use is; see expressions.

A catch-all is a wildcard or a binding in tail position, in an unguarded arm. else and _ are equivalent to the analyzer; else is the conventional form in tail position, and _ the form used inside a | or a nested pattern.

Dead arms

A pattern that can never match is an error. The arms are tried in order, so a pattern is dead when every value it matches is already matched by the arms above it. The refusal sits at the dead pattern and names the earlier arms that cover it between them. This is Rust’s unreachable_patterns rule, made an error rather than a warning.

enum Colour
    Red
    Green
    Blue

code(c: Colour) -> int = c match
    Red -> 1
    Green -> 2
    Red -> 3
    else 4

print(code(Blue))
unreachable pattern 'Red': every value it matches is already matched by the arm on line 7

The same question is asked of every pattern:

  • A catch-all ends the match. Any arm after _, after a bare binding, or after an else is dead. So is an else after arms that already cover every value.
  • Literals and ranges are compared as the values they are. 3 after 0..9 is dead, TWO after 2 is dead when const TWO = 2, and 2..7 after 1..5 and 4..9 is dead, because the two ranges cover it between them. 5 after 1..<5 is alive. A const written inside the body is compared the same way: it never binds.
  • A constant of an enum is the variant it came to, as a const pattern is in Rust. W after Write is dead when const W = Access.Write, and so is Write after W; constants naming every variant cover the enum with no _, and a _ after only some of them is alive.
  • Nested patterns, tuples and structs are read position by position. Some(Red) twice is dead, and so is Some(_) after Some(Red), Some(Green) and Some(Blue).
  • Each | alternative is checked on its own. It is dead if the earlier arms cover it, or the alternatives before it in the same arm, or the two together. The same holds for the alternatives of an is test, and for a | inside a pattern: in Some(1 | 1) the second 1 is dead, and it is the one reported. A part written with a | is dead only when no value can reach it whichever alternatives the other parts take, so (1 | 2, 3 | 4) after an arm (2, 4) is not dead.
  • A guarded arm covers nothing, just as it counts for nothing toward exhaustiveness. A guarded arm can still be dead itself. Inside a guarded arm whose alternatives bind a name, an earlier alternative does not cover a later one either: the guard is asked again with the later alternative’s bindings, so Pair(v, _) | Pair(_, v) if v > 10 is two different questions. With nothing bound, Red | Red if b asks the same one twice, and the second Red is dead.
pick(o: Option[bool]) -> int = o match
    Some(true) -> 1
    Some(false) | Some(_) -> 2
    None -> 3

print(pick(None))
unreachable pattern 'Some(_)': every value it matches is already matched by the arm on line 2 and an earlier alternative of this arm

The answer agrees with exhaustiveness, so a match can always be written that is neither short nor dead. Literals and ranges that fill a fixed-width integer or a char complete it, so a wildcard after them is dead; ones that leave a value out, or that range over a float, a string, a usize or an isize, never complete it, so a wildcard after them is never dead:

half(b: u8) -> string = b match
    0..127   -> "low"
    128..255 -> "high"
    _        -> "neither"

print(half(3))
unreachable pattern '_': every value it matches is already matched by the arms on lines 2 and 3

Two ranges that overlap are not refused unless one of them is dead: the reference’s guarded 1..10 arms overlap on purpose, and with no warning tier an overlap Rust would lint has nowhere to go but an error. Matching against storage, such as `limit` naming a val, compares with a value the compiler does not know. Such an arm covers nothing below it, and it is dead only after an arm that matches everything.

The type of a match

A match used for a value takes the common type of its arms. When every arm yields the same non-unit type, that is the match’s type; a match whose arms only perform actions is unit.

An arm that does not finish imposes no type. An arm that aborts or returns has type never, so it is set aside before the others are compared:

first(o: Option[int]) -> int
    o match
        Some(v) -> v
        None    -> return 0

print(first(Some(41)) + 1, first(None))
42 0

Exhaustiveness is unaffected: a diverging arm still covers only what its pattern covers.

Disagreeing arm types are a diagnostic, not a silent unit. When the arms yield different non-unit types that cannot be unified, the match is a type error reported at the match, rather than a unit that causes a confusing error later at the use site.

A &T context applies to each arm, not to the whole match. Under a &Point expectation, an arm yielding a bound &Point payload and an arm building a new Point both become &Point: the value arm is boxed individually and the reference arm passes through unchanged. Boxing the whole match instead would fail, because an arm that is already a &Point cannot be turned back into a value.

Refcounts survive destructuring

Pattern matching follows the memory model with no special rule. The two cases below are where a hand-written tagged union in C typically leaks or double-frees.

Binding a &T payload out of an enum retains it. Full(p) -> p passes the bound reference beyond the enum it came from, so the payload is retained on binding and released once when the binding dies: the extracted reference may outlive the enum, and the count stays exact.

A binding under a failed guard is released exactly once. When Full(p) if p.x > 100 fails and control falls through, the p bound for the guard is released before the next arm is tried, with no double free and no leak.

Matching through a reference

A shape reaches through a &T. A variant, struct or tuple pattern matched against a &Enum or a &Struct matches what the reference holds, as field selection reads through one. It reaches at every depth: where a payload or a field is a &T, the pattern written in its place is matched against what that reference holds, so a recursive type is taken apart several levels at once. A &sync T is reached through the same way, and so is a reference to a reference.

enum Tree
    Leaf(v: int)
    Node(l: &Tree, r: &Tree)

sum(t: &Tree) -> int
    t match
        Leaf(v) -> v
        Node(Leaf(a), r) -> a + sum(r)
        Node(l, r) -> sum(l) + sum(r)

describe(o: Option[&Tree]) -> string
    o match
        Some(Leaf(v)) -> s"a leaf holding $v"
        Some(Node(_, _)) -> "a node"
        None -> "nothing"

val t: &Tree = Node(Node(Leaf(1), Leaf(2)), Node(Leaf(3), Leaf(4)))

print(sum(t))
print(describe(Some(t)), "/", describe(None))

if t is Node(Node(Leaf(a), _), _) then print("leftmost:", a)
10
a node / nothing
leftmost: 1

Every place a pattern stands reaches through a reference the same way: an is test, a while … is loop, a binding, a for header, function clauses, | alternatives and a guarded arm. Coverage is judged on what the reference holds, so the arms above cover a &Tree as they would cover a Tree.

What does not take a shape apart still meets the reference itself. A name binds the reference — a second name for the same object, never a copy of what it holds — and so does the name in n @ Node(…). _ matches the reference, and a literal compares against it. A match may mix the two: an arm Leaf(v) reaches through and an arm other binds the reference.

Reading through the reference costs nothing the written dereference does not. The reference itself is neither copied nor counted: the arms read what it holds while it is alive, and only a name the arm binds takes a share of what it is bound to (see refcounts survive destructuring). A match whose every arm reaches through is lowered exactly as *t match is: the referent read once, its tag switched on.

A raw pointer is not reached through. A *T may point at nothing, and a shape over one would read it with no sign of the read, so its dereference is written:

enum Slot
    Empty
    Full(n: int)

var s = Full(1)
val p: *Slot = &s

p match
    Full(n) -> print(n)
    Empty -> print("empty")
a pattern reaches through a '&T' but not through a raw pointer, which may point at nothing, so match what it holds: '*x match'

*p match is the form, and *t match remains a correct spelling for a &T too.

A payload binding is a copy

Reaching through a reference determines which value is matched. It does not make the names bound in the arms into views of the payload: a payload binding is initialized by copy, whether or not the match went through a reference. Changing the copy leaves the enum unchanged.

The binding itself is written once, so the change is made to a var declared from it, which makes the copy explicit.

struct Reading
    id: int
    value: int

enum Slot
    Empty
    Full(r: Reading)

var s: &Slot = Full(Reading(1, 10))

s match
    Full(r) ->
        var mine = r
        mine.value = 99
    Empty -> print("empty")

s match
    Full(r) -> print("through a reference:", r.value)
    Empty -> print("empty")

var v = Full(Reading(1, 10))

v match
    Full(r) ->
        var mine = r
        mine.value = 99
    Empty -> print("empty")

v match
    Full(r) -> print("by value:", r.value)
    Empty -> print("empty")
through a reference: 10
by value: 10

Both reads give the value the enum was built with: neither mine.value = 99 reached the enum. A binding is a local holding a copy of the payload; to change what a &Slot holds, assign a variant to it.

The copy is the whole payload, so matching a reference to an enum whose variant carries a large struct copies that struct into the arm. A binding does not copy the object behind a &T payload: that payload is a reference, and copying it retains the object rather than duplicating it, as described under Refcounts survive destructuring above.

Changing state held in an Option

State kept in an Option[Recorder] cannot be changed through the binding: the binding holds a copy, and a write to it is refused. Hold the state as an Option[&Recorder] instead. The binding then copies the reference, so a write through it reaches the object, and the change is still there after the if ends. A type with a Drop is held as a &T already, so a file or a volume kept in an Option takes this form without any change.

struct Recorder
    frames: int
    bytes: int

var current: Option[&Recorder] = Some(Recorder(0, 0))

record(n: int)
    if current is Some(rec)
        rec.frames += 1
        rec.bytes += n

record(512)
record(256)

if current is Some(rec)
    print("frames:", rec.frames, "bytes:", rec.bytes)
frames: 2 bytes: 768

Nothing is assigned back into the Some. To replace the object, or to empty the Option, assign to current itself.


Next: memory.

Search

Esc
↑↓ to navigate ↵ to open Esc to close