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 @@ -36,7 +36,7 @@ skip: int() cannot parse "x" as an integer.
- `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`
- `try`/`catch` by error type, a block that gives a value like `if`; `defer`
- modules with `export` / `import`
- standard library: `string`, `regex`, `math`, `json`, `http`, `time`, `fs`, `io`, `os`
- built-in formatter: `rune fmt`
Expand Down
4 changes: 2 additions & 2 deletions docs/src/data/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ print(eval(e)); // -20
```

Fields work as in a [struct](structs.md): they are read-only, defaults
and spread work, and `Expr.Num(obj)` converts an object. An enum that has
and spread work, `Expr.Num { ...obj }` included. An enum that has
variants with fields has no numbers, so `values()`, `Expr(n)` and
`int(v)` are a `TypeError`:

Expand Down Expand Up @@ -263,7 +263,7 @@ impl Side {

print(Side.White.other()); // Side.Black
print(Side.parse("b")); // Side.Black
print(Side.values().map(Side.other)); // [Side.Black, Side.White]
print(Side.values().map(s => s.other())); // [Side.Black, Side.White]
```

An enum is not a struct, so `Side {}` is an error. No variant, and no
Expand Down
29 changes: 15 additions & 14 deletions docs/src/data/methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl Money {
}

fun format(self) {
"%.2f %s".format(self.cents / 100, self.currency)
"{"%.2f".format(self.cents / 100)} {self.currency}"
}
}

Expand Down Expand Up @@ -169,14 +169,10 @@ A struct held in a field of another struct can be changed only from the
outer struct's own `mut self` methods, as in `self.pos.move(1)`; see
[Setting Fields](structs.md#setting-fields).

## Methods as Values
## Calling Only

A method can be passed around like any function:

- `price.format`, without a call, is the method bound to `price`: a
function that takes the remaining arguments;
- `Money.format` is the plain function, which takes the instance as its
first argument. It fits straight into `map` and friends.
A method taking `self` is only called, on an instance. To pass one
along, wrap the call in an arrow function:

```rune
struct Money { cents }
Expand All @@ -186,15 +182,20 @@ impl Money {
}

let prices = [Money { cents: 499 }, Money { cents: 1250 }];
print(prices.map(Money.format)); // ["$4.99", "$12.50"]
print(prices.map(m => m.format())); // ["$4.99", "$12.50"]
```

```rune
struct Money { cents }

impl Money {
fun format(self) { "$%.2f".format(self.cents / 100) }
}

let show = prices[0].format;
print(show()); // $4.99
let show = Money { cents: 499 }.format; // TypeError: Cannot take method 'format' of Money as a value.
```

A mutating method has no variable to write back to when used as a value.
Taking a bound one, `acc.deposit`, is a `TypeError`, and so is calling
`Account.deposit` through `map` or another callback.
A static method is a plain function, so `Money.of` may be passed as is.

## Functions in Fields

Expand Down
30 changes: 13 additions & 17 deletions docs/src/data/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,9 @@ Inside a `mut self` method all of this is allowed: `self.tags.push(x)`,

## Updating with Spread

To get a changed copy without touching the original, spread the struct
into a new literal of the same type and list the fields to change:
`Config { ...base, debug: true }`. Items apply in order, so later ones
win.
A struct literal may spread a struct of its own type, or an object,
then list the fields to change: `Config { ...base, debug: true }`.
Items apply in order, so later ones win.

```rune
struct Config { host, port = 8080, debug = false }
Expand All @@ -149,36 +148,33 @@ print(prod); // Config {host: "example.com", port: 443, debug: false}
print(base); // Config {host: "localhost", port: 8080, debug: false}
```

Only a struct of the same type can be spread into a literal; an object
or another struct type is a runtime error. Use a
[conversion](#converting) to turn an object into a struct.
A struct of another type is a runtime error.

## Converting
## From an Object

Calling a struct type converts a value to it. This is how data from
`json.parse` becomes a struct:
Spreading an object into a struct literal is how data from `json.parse`
becomes a struct:

```rune
struct Config { host, port = 8080 }

let cfg = Config(json.parse(r"""{"host": "example.com"}"""));
let cfg = Config { ...json.parse(r"""{"host": "example.com"}""") };
print(cfg); // Config {host: "example.com", port: 8080}
print(cfg.port); // 8080
```

The object's keys must be exactly the struct's fields; fields with
defaults may be left out. A struct of the same type is returned as is.
Anything else is an error: there are no implicit conversions, and none
between different struct types.
Every key must be a field, and every field without a default must be
given, by the object or by the literal. The check runs when the literal
is built:

```rune
struct Config { host, port = 8080 }
Config({ host: "example.com", timeout: 5 }); // KeyError: Config has no field 'timeout'.
Config { ...{ host: "example.com", timeout: 5 } }; // KeyError: Config has no field 'timeout'.
```

```rune
struct Config { host, port = 8080 }
Config({ port: 80 }); // KeyError: Missing field 'host' of Config.
Config { ...{ port: 80 } }; // KeyError: Missing field 'host' of Config.
```

## Type Tests and Equality
Expand Down
2 changes: 1 addition & 1 deletion docs/src/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct Request { method, path, status, ms }

fun parse(line) {
let [method, path, status, ms] = line.split(" ");
Request { method, path, status: int(status), ms: number(ms) }
Request { method, path, status: number(status), ms: number(ms) }
}

fun kind(req) {
Expand Down
4 changes: 2 additions & 2 deletions docs/src/language/destructuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ print(login); // ann
print(fullName); // Ann Lee
```

Variables from a pattern are immutable, like any `let`. Mark one with
`mut`, or write `let mut { ... }` to make them all mutable:
Variables from a pattern are immutable, like any `let`. Mark each one
that may change with `mut`:

```rune
let { name, age: mut years } = { name: "ann", age: 31 };
Expand Down
39 changes: 14 additions & 25 deletions docs/src/language/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
In Rune an error is an ordinary [struct](../data/structs.md) value.
The runtime throws one when something goes wrong, such as a file that is
missing or a string that is not a number, and your code throws its own
with `throw`. There are three tools for dealing with them:
with `throw`. There are two tools for dealing with them:

- `try`/`catch` runs code and handles the error if one is thrown;
- `try value catch => fallback` is the same thing as an expression, for
the common "use this, or that if it fails" case;
- `defer` runs cleanup code however a block is left.

## try and catch
Expand All @@ -18,7 +16,7 @@ runs with the error, and the program carries on after it.
```rune
fun parsePort(s) {
try {
return int(s);
return number(s);
} catch e {
print("bad port: " + e.message);
return 80;
Expand All @@ -28,7 +26,7 @@ fun parsePort(s) {
print(parsePort("8080"));
print(parsePort("http"));
// 8080
// bad port: int() cannot parse "http" as an integer.
// bad port: number() cannot parse "http" as a number.
// 80
```

Expand Down Expand Up @@ -58,7 +56,7 @@ has the fields `message`, `line` (the line it was thrown on) and
|---|---|---|
| `TypeError` | a value of the wrong type | `1 + nil`, calling a number |
| `ArgumentError` | the wrong number of arguments | `math.sqrt()` |
| `ValueError` | the right type but a bad value | `[].pop()`, `int("x")` |
| `ValueError` | the right type but a bad value | `[].pop()`, `number("x")` |
| `IndexError` | an index out of bounds | `[1, 2][5]` |
| `KeyError` | a missing property or struct field | `{ a: 1 }.b` |
| `NameError` | an undefined variable | |
Expand Down Expand Up @@ -124,50 +122,41 @@ print(setting(config, "port")); // 8080
print(setting(config, "host")); // nil
```

## try as an Expression
## try Gives a Value

`try value catch => fallback` gives `value`, or `fallback` if computing
`value` throws. It turns "parse this, or use a default" into one line:
Like [`if`](conditionals.md#if-as-an-expression), `try` is an
expression: it gives the last expression of the block that ran, the
`try` block or the `catch` that handled the error. That turns "parse
this, or use a default" into one line:

```rune
let port = try int("http") catch => 80;
let port = try { number("http") } catch { 80 };
print(port); // 80
```

A clause can name the error and the types it handles, just like the
statement form: `catch e is T | U => fallback`. Several clauses may
follow one another, and an error none of them handles goes on up.

```rune
fun field(record, key) {
try record[key]
catch e is KeyError => "-"
catch e is TypeError => "not a record"
try { record[key] } catch e is KeyError { "-" } catch e is TypeError { "not a record" }
}

print(field({ id: 7 }, "id")); // 7
print(field({ id: 7 }, "name")); // -
print(field(5, "id")); // not a record

print(try json.parse("[1,") catch e => e is ValueError); // true
print(try { json.parse("[1,") } catch e { e is ValueError }); // true
```

The fallback may also `return`, `break`, `continue` or `throw`. This
A `catch` block may also `return`, `break`, `continue` or `throw`. This
loop keeps only the numbers it can parse:

```rune
let mut ports = [];
for s in ["80", "http", "443"] {
ports.push(try int(s) catch => continue);
ports.push(try { number(s) } catch { continue });
}
print(ports); // [80, 443]
```

Both `value` and each fallback extend as far to the right as they can,
so wrap them in parentheses when they are part of a larger expression.
At the start of a statement, `try {` begins a `try` statement; any other
`try` is an expression.

## throw

`throw` raises a struct instance, either a built-in error or one of your
Expand Down
2 changes: 1 addition & 1 deletion docs/src/language/nil-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ separate `if`:
```rune
fun port(cfg) {
let p = cfg?.port ?? return 80;
int(p)
number(p)
}

print(port({ port: "8080" })); // 8080
Expand Down
2 changes: 1 addition & 1 deletion docs/src/language/numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,5 +194,5 @@ print(math.isInt(json.parse("2"))); // true
print(math.isInt(json.parse("2.0"))); // false
print(int(3.9)); // 3
print(int(-3.9)); // -3
print(int("42") + 1); // 43
print(number("42") + 1); // 43
```
15 changes: 10 additions & 5 deletions docs/src/language/spread-and-rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ let scores = [72, 95, 88];
print(math.max(...scores)); // 95
```

A method call takes no spread:

```rune
let mut xs = [1];
xs.push(...[2, 3]); // Error at '...': Cannot spread arguments into a method call.
```

Sets spread too, in their order, and bytes spread as integers:

```rune
Expand Down Expand Up @@ -64,18 +71,16 @@ let p = Point { x: 1, y: 2 };
print({ ...p, z: 3 }); // {x: 1, y: 2, z: 3}
```

In a struct literal, spreading a struct of the same type makes an updated
copy (see [Structs](../data/structs.md#updating-with-spread)):
In a struct literal, spreading a struct of the same type, or an object,
fills its fields (see [Structs](../data/structs.md#updating-with-spread)):

```rune
struct Point { x, y = 0 }
let p = Point { x: 1, y: 2 };
print(Point { ...p, y: 5 }); // Point {x: 1, y: 5}
print(Point { ...{ x: 3 } }); // Point {x: 3, y: 0}
```

To build a struct from an object, [convert](../data/structs.md#converting)
it: `Point({ ...o, y: 5 })`.

Spreading anything else is a `TypeError`:

```rune
Expand Down
5 changes: 2 additions & 3 deletions docs/src/language/values.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ Everything else is **truthy**, including `"0"`, `[0]` and `{ a: nil }`.

```rune
for v in [nil, false, 0, "", [], {}, map(), "0", [0], { a: nil }] {
print("%q is %s".format(v, if v { "truthy" } else { "falsy" }));
print("{"%q".format(v)} is {if v { "truthy" } else { "falsy" }}");
}
// nil is falsy
// false is falsy
Expand Down Expand Up @@ -295,7 +295,7 @@ print(1 in "123"); // TypeError: Left operand of 'in' must be a string for st
- functions and streams by identity: a function equals only itself.

Values of different kinds are never equal, so `1 == "1"` is `false`. `NaN`
equals nothing, not even itself. `in` and `indexOf` use this same equality.
equals nothing, not even itself. `in` uses this same equality.

```rune
print(1 == 1.0); // true
Expand All @@ -306,7 +306,6 @@ print(nil == false); // false

let cart = [{ id: 1 }, { id: 2 }];
print({ id: 2 } in cart); // true
print(cart.indexOf({ id: 2 })); // 1

let isValid = order => order.qty > 0;
let check = isValid;
Expand Down
5 changes: 2 additions & 3 deletions docs/src/programs/main.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ $ echo $?
2
```

Arguments are always strings; convert them yourself, with `int`,
`number` and the like.
Arguments are always strings; convert them yourself, with `number` and the like.

## Destructuring Arguments

Expand All @@ -45,7 +44,7 @@ names the arguments and gives defaults to the optional ones:
```rune
// repeat.rn
fun main([word, times = "1"]) {
print(word.repeat(int(times)));
print(word.repeat(number(times)));
}
```

Expand Down
11 changes: 4 additions & 7 deletions docs/src/stdlib/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ take an element out.
| `sort([cmp])` | sorts, **in place** |
| `reverse()` | reverses, **in place** |
| `map(f)`, `filter(f)`, `reduce(f[, init])` | transform |
| `every(f)`, `some(f)`, `find(f)`, `findIndex(f)`, `indexOf(v)` | search |
| `every(f)`, `some(f)`, `find(f)`, `findIndex(f)` | search |
| `join(sep)`, `repeat(n)` | build strings and arrays |

Arrays are values, so changing one in place never changes a copy of it:
Expand Down Expand Up @@ -118,7 +118,7 @@ but only when `f` requires two. So `map(int)`, whose `base` is optional,
gets the element alone:

```rune
print(["10", "2", "33"].map(int)); // [10, 2, 33]
print([10.5, 2.9, 33.1].map(int)); // [10, 2, 33]
print(["a", "b"].map((x, i) => "{i}:{x}")); // ["0:a", "1:b"]
print([5, 6, 7, 8].filter((_, i) => i % 2 == 0)); // [5, 7]
```
Expand Down Expand Up @@ -183,8 +183,6 @@ mixed.sort(); // TypeError: array.sort() without a comparator needs all numbers
any. They stop as soon as the answer is known.
- `find(f)` — the first element for which `f` is truthy, or `nil`.
- `findIndex(f)` — the index of that element, or `nil`.
- `indexOf(v)` — the index of the first element equal to `v`, or `nil`.
Arrays and objects compare by content.

To ask only whether a value is there, use [`in`](../language/values.md#membership).

Expand All @@ -201,9 +199,8 @@ print(users.find(u => u.name == "eve")); // nil
print(users.findIndex(u => u.name == "bob")); // 1

print(20 in [10, 20, 30]); // true
print([10, 20, 30].indexOf(30)); // 2
print([10, 20, 30].indexOf(99)); // nil
print([[1, 2], [3, 4]].indexOf([3, 4])); // 1
print([10, 20, 30].findIndex(x => x == 30)); // 2
print([[1, 2], [3, 4]].findIndex(x => x == [3, 4])); // 1
```

`find` returns `nil` when nothing matches, so `??` gives a fallback:
Expand Down
Loading
Loading