Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ skip: int() cannot parse "x" as an integer.
- value semantics: arrays, objects, maps, sets and structs copy lazily, `mut` parameters are inout
- structs and enums with fields, `impl` methods
- blocks give their last expression: `fun sq(x) { x * x }`, `if c { a } else { b }`, block match arms
- `match` on literals, ranges (`200..300`, `500..`), types, structs, arrays and enums, exhaustive over enum variants; destructuring, spread, rest
- `match` on literals, ranges (`200..300`, `500..`), types, structs, arrays and enums, exhaustive over enum variants; the same nested patterns in `let`, parameters and `if x is { status: 200, body }`; spread, rest
- membership `x in xs` (a range without making it), slices `xs[1..]`, `s[..-1]`
- nil-safe chains `a?.b ?? c`; `return` / `break` / `continue` / `throw` as expressions
- `try`/`catch` by error type, as a statement or an expression; `defer`
Expand Down
39 changes: 34 additions & 5 deletions docs/src/data/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,35 @@ This `match` has no `_` arm, and it does not need one: it lists every
variant. If a variant is later added to `Status`, the compiler points at
each `match` that forgot it; see [Matching every variant](#matching-every-variant).

When every arm names a variant of one enum, say so once in the head,
`match s is Status`, and name the variants bare. The value must then be a
`Status`; anything else is a `ValueError`, as when no arm matches:

```rune
enum Status { Pending, Paid, Shipped, Cancelled }

fun label(s) {
match s is Status {
Pending => "waiting for payment",
Paid | Shipped => "on its way",
Cancelled => "cancelled",
}
}

print(label(Status.Shipped)); // on its way
print(label("paid")); // ValueError: No match arm for "paid".
```

A bare name in such a match is always a variant, so a typo is caught:

```rune
enum Status { Pending, Paid }
match Status.Paid is Status { Pendin => 1, _ => 2 }; // Error at 'Pendin': Status has no variant 'Pendin'.
```

To match on whether a value is a `Status`, put the test in parentheses:
`match (s is Status) { true => ..., false => ... }`.

## Numbers and Names

Variants are numbered from 0 in declaration order. `int(v)` gives a
Expand Down Expand Up @@ -161,11 +190,11 @@ enum Expr {
}

fun eval(e) {
match e {
Expr.Num { value } => value,
Expr.Add { left, right } => eval(left) + eval(right),
Expr.Mul { left, right } => eval(left) * eval(right),
Expr.Neg { expr } => -eval(expr),
match e is Expr {
Num { value } => value,
Add { left, right } => eval(left) + eval(right),
Mul { left, right } => eval(left) * eval(right),
Neg { expr } => -eval(expr),
}
}

Expand Down
2 changes: 1 addition & 1 deletion docs/src/data/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Config({ port: 80 }); // KeyError: Missing field 'host' of Config.

`v is User` is `true` only for a `User`, never for an object that
happens to have the same keys; see
[Type Tests](../language/values.md#type-tests).
[Type Tests](../language/values.md#type-tests-and-patterns).

`==` compares two structs of the same type field by field. A struct
never equals an object or a struct of another type.
Expand Down
2 changes: 1 addition & 1 deletion docs/src/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ Language chapters in order.
- [functions](language/functions.md): closures, defaults, arrows `x => x * 2`, bodies give their last expression `fun sq(x) { x * x }`
- [spread and rest](language/spread-and-rest.md), [destructuring](language/destructuring.md): `let [head, ...tail] = xs;`
- [nil safety](language/nil-safety.md): `resp?.data?.items ?? []`
- [pattern matching](language/pattern-matching.md) on literals, ranges, types, structs, arrays and enums, exhaustive over enum variants
- [pattern matching](language/pattern-matching.md) on literals, ranges, types, structs, arrays and enums, exhaustive over enum variants; the same nested patterns in `let`, parameters and `if x is { status: 200, body }`
- [errors](language/error-handling.md): `throw`, `try`/`catch` by type, `try` as an expression, `defer`
- `return`, `break`, `continue` and `throw` as expressions: `let v = x ?? return nil;`

Expand Down
5 changes: 4 additions & 1 deletion docs/src/language/conditionals.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,7 @@ for amount in [20, -5, 0, 40, 999] {
print(paid); // [20, 40]
```

To choose between many values, see [`match`](pattern-matching.md).
To test the shape of a value and take it apart in one step, as in
`if resp is { status: 200, body } { ... }`, see
[Binding in Conditions](values.md#binding-in-conditions). To choose
between many values, see [`match`](pattern-matching.md).
50 changes: 49 additions & 1 deletion docs/src/language/destructuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ reading `user.name` and `user.age` into two variables by hand, you write
the shape you expect and Rune fills in the names. Patterns work in `let`,
in function parameters and in `for`-`in` variables.

These are the same patterns as in [`match`](pattern-matching.md) and
[`is`](values.md#type-tests-and-patterns). The difference is what happens
when the value does not fit: `match` tries the next arm, `is` gives
`false`, and destructuring fails with an error.

## Objects and Structs

An object pattern binds properties to variables of the same name:
Expand Down Expand Up @@ -178,7 +183,50 @@ Anything that is not an array is a `TypeError`:
let [a, b] = "ab"; // TypeError: Cannot destructure string as an array.
```

Patterns do not nest: each element or property binds a plain variable.
## Nesting

A property or element can be a pattern itself, so one `let` reaches deep
into a value:

```rune
let resp = { user: { name: "ann", tags: ["admin", "ops", "dev"] }, status: 200 };
let { user: { name, tags: [first, ...others] }, status } = resp;

print(name); // ann
print(first); // admin
print(others); // ["ops", "dev"]
print(status); // 200
```

The same key may appear twice, to keep the whole value and take it apart
too:

```rune
let { pos, pos: { x } } = { pos: { x: 3, y: 4 } };
print(pos); // {x: 3, y: 4}
print(x); // 3
```

Nested patterns work in parameters and `for` loops as well:

```rune
fun label({ name, size: [w, h] }) { "{name} {w}x{h}" }
print(label({ name: "logo", size: [64, 32] })); // logo 64x32

for [day, { hits }] in [["mon", { hits: 10 }], ["tue", { hits: 3 }]] {
print("{day}: {hits}");
}
// mon: 10
// tue: 3
```

A pattern here only takes a value apart. Testing it, with a literal, a
range, `|` or a type, belongs in [`match`](pattern-matching.md) or
[`is`](values.md#type-tests-and-patterns):

```rune
let [cmd, "now"] = ["run", "now"]; // Error at '"now"': This pattern only takes a value apart; test the value with match or 'is'.
```

## Defaults

Expand Down
29 changes: 19 additions & 10 deletions docs/src/language/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ program at once, and `os.exit` exits even from inside `try`.
## Catching by Type

`catch e is T` catches only errors of type `T`; `catch e is T | U`
catches either. This is the same [test](values.md#type-tests) as
catches either. This is the same [test](values.md#type-tests-and-patterns) as
`v is T`. Clauses are tried in order. An error that no clause takes goes
on up to the caller, with its trace intact. A clause without a type
catches everything, so it must come last.
Expand Down Expand Up @@ -264,23 +264,24 @@ try {

## defer

`defer { ... }` schedules a block to run when the enclosing block is
left: at its end, by `return`, `break` or `continue`, or by an error,
which then carries on up. It keeps cleanup next to the setup it undoes,
so it cannot be forgotten on an early exit.
`defer expression;` schedules an expression to run when the enclosing
block is left: at its end, by `return`, `break` or `continue`, or by an
error, which then carries on up. It keeps cleanup next to the setup it
undoes, so it cannot be forgotten on an early exit. For cleanup of
several statements, defer a block: `defer { ... }`.

```rune
fun save(path, lines) {
let out = fs.open(path, "w");
defer { out.close(); }
defer out.close();

for line in lines {
out.write(line + "\n");
}
}

let dir = fs.tempDir();
defer { fs.removeAll(dir); }
defer fs.removeAll(dir);

let path = fs.join(dir, "todo.txt");
save(path, ["milk", "tea"]);
Expand All @@ -292,7 +293,7 @@ order, last registered first:

```rune
fun step(n) {
defer { print("step {n}: cleanup"); }
defer print("step {n}: cleanup");
if n == 0 {
throw ValueError { message: "step 0 failed" };
}
Expand All @@ -313,8 +314,8 @@ try {

```rune
fun pipeline() {
defer { print("close file"); }
defer { print("flush buffer"); }
defer print("close file");
defer print("flush buffer");
print("write data");
}

Expand All @@ -324,6 +325,14 @@ pipeline();
// close file
```

A single expression is deferred without braces:

```rune
fun f() {
defer { print("bye"); } // Error at 'defer': Defer one expression without braces: defer expression;
}
```

A `return` computes its value before the defers run. A defer's body
cannot itself `return`, nor `break` or `continue` out of itself:

Expand Down
4 changes: 3 additions & 1 deletion docs/src/language/loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,9 @@ while stack {
```

The condition is tested for [truthiness](values.md#truthiness), so
`while stack` runs until the array is empty. Here is a loop that counts
`while stack` runs until the array is empty. With a pattern,
`while queue.pop() is { id } { ... }` runs as long as the value matches;
see [Binding in Conditions](values.md#binding-in-conditions). Here is a loop that counts
the steps of the Collatz sequence from 27 to 1:

```rune
Expand Down
61 changes: 57 additions & 4 deletions docs/src/language/pattern-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ leave the function or the loop: `"quit" => return "bye",`.
| `LIMIT`, `m.LIMIT` | a value equal to the [constant](variables.md#constants) |
| `a..b`, `a..=b`, `a..`, `..b`, `..=b` | a number in the range |
| `p \| q` | a value either pattern matches |
| `_ is T`, `name is T \| U` | a value of the given [type](values.md#type-tests) |
| `_ is T`, `name is T \| U`, `name is P` | a value of the given [type](values.md#type-tests-and-patterns), or one `P` matches, bound to `name` |
| `Point { x, y: 0 }` | a `Point` whose fields match |
| `Color.White`, `Expr.Num { value }` | that [enum](../data/enums.md) variant |
| `{ key, "other key": p }` | an object or struct that has the keys |
| `[p, q]`, `[p, ...rest]` | an array of that many elements, or at least that many |
| `{ key, "other key": p, key = d, ...rest }` | an object or struct that has the keys |
| `[p, q]`, `[p, q = d]`, `[p, ...rest]` | an array of that many elements, or at least that many |

Any pattern may be followed by a guard, `pattern if condition`, which is
checked after the pattern matches.
Expand Down Expand Up @@ -196,7 +196,7 @@ still needs `_ =>` for values that are not numbers.
`name is T` matches a value of type `T` and binds it; `_ is T` only
tests. `T` is a struct, an enum or a built-in type such as `string`,
`number` or `nil`, and `T | U` accepts either. It is the same test as
[`v is T`](values.md#type-tests).
[`v is T`](values.md#type-tests-and-patterns).

```rune
fun describe(v) {
Expand All @@ -217,6 +217,28 @@ print(describe({ id: 1 })); // a collection
print(describe(true)); // something else
```

After `is` comes any pattern, in which a bare name is a type. So `name is P`
binds the whole value once `P` matches it, which a guard would otherwise
have to check:

```rune
struct Point { x, y = 0 }

fun classify(v) {
match v {
n is 1..10 => "small {n}",
p is Point { x: 0 } => "on the axis: {p}",
s is "yes" | "no" => "answer {s}",
_ => "other",
}
}

print(classify(3)); // small 3
print(classify(Point { x: 0, y: 2 })); // on the axis: Point {x: 0, y: 2}
print(classify("no")); // answer no
print(classify(42)); // other
```

## Structs

`Point { x, y: 0 }` first checks that the value is a `Point`, then
Expand Down Expand Up @@ -321,6 +343,37 @@ for pair in results.entries() {
// skipped: 2
```

## Defaults and Rest

A property or element may have a default, `name = value`, used when it is
missing, so one arm covers data with optional parts. `...rest` in an
object pattern binds an object of the other keys. These work exactly as
in [destructuring](destructuring.md#defaults):

```rune
fun command(args) {
match args {
[cmd, target = "."] => "{cmd} {target}",
_ => "usage: cmd [target]",
}
}

print(command(["ls"])); // ls .
print(command(["ls", "/tmp"])); // ls /tmp
print(command(["ls", "a", "b"])); // usage: cmd [target]

fun user(v) {
match v {
{ name, role = "member", ...extra } => "{name} ({role}) {extra}",
_ => "not a user",
}
}

print(user({ name: "ann" })); // ann (member) {}
print(user({ name: "bob", role: "admin", id: 7 })); // bob (admin) {id: 7}
print(user(5)); // not a user
```

## Expression or Statement

Used as a value, `match` gives the value of the arm that ran. A block
Expand Down
Loading
Loading