diff --git a/README.md b/README.md
index 6adff93c..a15c1f72 100644
--- a/README.md
+++ b/README.md
@@ -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`
diff --git a/docs/src/data/enums.md b/docs/src/data/enums.md
index 8cb74e63..25b3d1b8 100644
--- a/docs/src/data/enums.md
+++ b/docs/src/data/enums.md
@@ -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`:
@@ -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
diff --git a/docs/src/data/methods.md b/docs/src/data/methods.md
index fdce9d31..634cb137 100644
--- a/docs/src/data/methods.md
+++ b/docs/src/data/methods.md
@@ -19,7 +19,7 @@ impl Money {
}
fun format(self) {
- "%.2f %s".format(self.cents / 100, self.currency)
+ "{"%.2f".format(self.cents / 100)} {self.currency}"
}
}
@@ -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 }
@@ -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
diff --git a/docs/src/data/structs.md b/docs/src/data/structs.md
index eef6868f..e079bcac 100644
--- a/docs/src/data/structs.md
+++ b/docs/src/data/structs.md
@@ -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 }
@@ -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
diff --git a/docs/src/introduction.md b/docs/src/introduction.md
index 67a6c371..8dd14f89 100644
--- a/docs/src/introduction.md
+++ b/docs/src/introduction.md
@@ -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) {
diff --git a/docs/src/language/destructuring.md b/docs/src/language/destructuring.md
index 81cce2cf..6afb7d46 100644
--- a/docs/src/language/destructuring.md
+++ b/docs/src/language/destructuring.md
@@ -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 };
diff --git a/docs/src/language/error-handling.md b/docs/src/language/error-handling.md
index 4057100b..e533861a 100644
--- a/docs/src/language/error-handling.md
+++ b/docs/src/language/error-handling.md
@@ -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
@@ -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;
@@ -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
```
@@ -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 | |
@@ -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
diff --git a/docs/src/language/nil-safety.md b/docs/src/language/nil-safety.md
index ba0c8f81..1a66632c 100644
--- a/docs/src/language/nil-safety.md
+++ b/docs/src/language/nil-safety.md
@@ -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
diff --git a/docs/src/language/numbers.md b/docs/src/language/numbers.md
index 80cc4dc0..2fdab9d0 100644
--- a/docs/src/language/numbers.md
+++ b/docs/src/language/numbers.md
@@ -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
```
diff --git a/docs/src/language/spread-and-rest.md b/docs/src/language/spread-and-rest.md
index 192dd864..93efcd5d 100644
--- a/docs/src/language/spread-and-rest.md
+++ b/docs/src/language/spread-and-rest.md
@@ -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
@@ -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
diff --git a/docs/src/language/values.md b/docs/src/language/values.md
index a5de0da2..d814ff2c 100644
--- a/docs/src/language/values.md
+++ b/docs/src/language/values.md
@@ -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
@@ -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
@@ -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;
diff --git a/docs/src/programs/main.md b/docs/src/programs/main.md
index f75ae011..f2fbcc49 100644
--- a/docs/src/programs/main.md
+++ b/docs/src/programs/main.md
@@ -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
@@ -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)));
}
```
diff --git a/docs/src/stdlib/array.md b/docs/src/stdlib/array.md
index c69af5c6..e42fd884 100644
--- a/docs/src/stdlib/array.md
+++ b/docs/src/stdlib/array.md
@@ -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:
@@ -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]
```
@@ -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).
@@ -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:
diff --git a/docs/src/stdlib/builtins.md b/docs/src/stdlib/builtins.md
index f429c82c..eeb00861 100644
--- a/docs/src/stdlib/builtins.md
+++ b/docs/src/stdlib/builtins.md
@@ -85,12 +85,9 @@ spaces around it: `"42"`, `" -2.5e1 "`, `"0xff"`, `"1_000"`. The result is
an integer, unless the literal has a fraction or an exponent, or is too big
for a 64-bit integer.
-`int(v)` makes an integer:
-
-- from a number, by cutting off the fraction (toward zero);
-- from a string holding an integer literal, as `number` reads it;
-- with `int(s, base)`, from digits in `base`, 2 to 36, optionally
- separated by `_`.
+`int(v)` makes an integer from a number, by cutting off the fraction
+(toward zero). `int(s, base)` reads the digits of `s` in `base`, 2 to 36,
+optionally separated by `_`.
```rune
print(number("42")); // 42
@@ -100,7 +97,6 @@ print(number("1_000")); // 1000
print(int(3.9)); // 3
print(int(-3.9)); // -3
-print(int("42")); // 42
print(int("ff", 16)); // 255
print(int("0755", 8)); // 493
print(int("1010", 2)); // 10
@@ -111,7 +107,7 @@ Reading the numbers out of a CSV row:
```rune
let row = "2026-11-12,3,12.50";
let [date, qty, price] = row.split(",");
-print(int(qty) * number(price)); // 37.5
+print(number(qty) * number(price)); // 37.5
```
Text that is not a number is a `ValueError`. That includes `".5"`, `"+1"`,
@@ -121,13 +117,13 @@ Text that is not a number is a `ValueError`. That includes `".5"`, `"+1"`,
number("12 apples"); // ValueError: number() cannot parse "12 apples" as a number.
```
-`int` without a base takes only integers:
+A string is read by `number`; `int` takes it only with a base:
```rune
-int("12.5"); // ValueError: int() cannot parse "12.5" as an integer.
+int("12"); // TypeError: int() expects a number as argument 1, got string.
```
-So does `int` with a number too big for a 64-bit integer:
+A number too big for a 64-bit integer is a `ValueError`:
```rune
int(1e300); // ValueError: int() cannot convert 1e+300 to an integer.
diff --git a/docs/src/stdlib/json-http.md b/docs/src/stdlib/json-http.md
index 0d5a63c3..62774097 100644
--- a/docs/src/stdlib/json-http.md
+++ b/docs/src/stdlib/json-http.md
@@ -4,7 +4,6 @@
|---|---|
| `json.parse(s)` | parses JSON text into a value |
| `json.stringify(v[, indent])` | encodes a value as JSON text |
-| `http.get(url)` | fetches a URL, returns the body as a string |
| `http.request(method, url[, opts])` | sends any request, returns an `HttpResponse` |
## json.parse
@@ -33,21 +32,21 @@ print(json.parse("[1, 2.5]")); // [1, 2.5]
print(json.parse("42")); // 42
```
-Calling a [struct](../data/structs.md) type on the result checks its
-shape: every field without a default must be there, and no other key may
-be.
+Spreading the result into a [struct](../data/structs.md) literal checks
+its shape: every field without a default must be there, and no other key
+may be.
```rune
struct Order { id, total, items = [] }
-let order = Order(json.parse(r"""{"id": 8, "total": 5}"""));
+let order = Order { ...json.parse(r"""{"id": 8, "total": 5}""") };
print(order); // Order {id: 8, total: 5, items: []}
print(order.items); // []
```
```rune
struct Order { id, total, items = [] }
-Order(json.parse(r"""{"id": 8}""")); // KeyError: Missing field 'total' of Order.
+Order { ...json.parse(r"""{"id": 8}""") }; // KeyError: Missing field 'total' of Order.
```
Text that is not JSON is a `ValueError`:
@@ -108,27 +107,6 @@ An infinite or NaN number, or a value nested more than 1000 deep, is a
json.stringify({ ratio: math.INF }); // ValueError: json.stringify() cannot encode a non-finite number.
```
-## http.get
-
-`http.get(url)` fetches `url` and returns the body as a string. A network
-error, or any status other than 200, is an `IOError`.
-
-The examples below talk to a made-up `api.example.com`; the output shows
-what such a server would answer.
-
-```rune
-let todos = json.parse(http.get("https://api.example.com/todos")).todos;
-print(todos.filter(t => !t.done).map(t => t.title)); // ["buy milk"]
-```
-
-```rune
-try {
- http.get("https://api.example.com/missing");
-} catch e is IOError {
- print(e.message); // http.get() could not fetch https://api.example.com/missing: status code 404
-}
-```
-
## http.request
`http.request(method, url[, opts])` sends a request and returns an
@@ -149,6 +127,14 @@ object with any of those keys:
- `timeout` — in seconds, 30 by default;
- `stream` — `true` to read the body as a [stream](streams.md).
+The examples below talk to a made-up `api.example.com`; the output shows
+what such a server would answer.
+
+```rune
+let todos = json.parse(http.request("GET", "https://api.example.com/todos").body).todos;
+print(todos.filter(t => !t.done).map(t => t.title)); // ["buy milk"]
+```
+
Creating a user with a JSON body:
```rune
diff --git a/docs/src/stdlib/os.md b/docs/src/stdlib/os.md
index ff420a4e..ee57a5c7 100644
--- a/docs/src/stdlib/os.md
+++ b/docs/src/stdlib/os.md
@@ -18,7 +18,7 @@ gives a default. `setEnv` and `unsetEnv` change the environment of the
program and of the commands it runs.
```rune
-let port = int(os.env("PORT") ?? "8080");
+let port = number(os.env("PORT") ?? "8080");
print(port); // 8080
os.setEnv("APP_MODE", "test");
diff --git a/docs/src/stdlib/regex.md b/docs/src/stdlib/regex.md
index 9dcd9c4e..8f0cf426 100644
--- a/docs/src/stdlib/regex.md
+++ b/docs/src/stdlib/regex.md
@@ -68,7 +68,7 @@ print(regex.find(r"(cat)|(dog)", "dog").groups); // [nil, "dog"]
```rune
let text = "ids: 7, 42, 108";
-print(regex.findAll(r"\d+", text).map(m => int(m.text))); // [7, 42, 108]
+print(regex.findAll(r"\d+", text).map(m => number(m.text))); // [7, 42, 108]
print(regex.findAll(r"\d+", text, 2).map(m => m.text)); // ["7", "42"]
let pairs = regex.findAll(r"(\w+)=(\w+)", "user=ann role=admin");
@@ -92,7 +92,7 @@ With a function, each replacement can be computed:
```rune
let recipe = "3 eggs, 200 g flour, 1 cup milk";
-print(regex.replace(r"\d+", recipe, m => string(int(m.text) * 2)));
+print(regex.replace(r"\d+", recipe, m => string(number(m.text) * 2)));
// 6 eggs, 400 g flour, 2 cup milk
```
diff --git a/docs/src/stdlib/streams.md b/docs/src/stdlib/streams.md
index 142bf4a1..962f16fd 100644
--- a/docs/src/stdlib/streams.md
+++ b/docs/src/stdlib/streams.md
@@ -54,7 +54,7 @@ fs.write(path, "GET /a 200\nPOST /b 500\nGET /c 404\n");
let mut failed = 0;
for i, line in fs.open(path) {
- let status = int(line.split(" ")[2]);
+ let status = number(line.split(" ")[2]);
if status >= 400 {
print("line {i + 1}: {line}");
failed += 1;
diff --git a/docs/src/stdlib/string.md b/docs/src/stdlib/string.md
index 5599d4e1..241f3934 100644
--- a/docs/src/stdlib/string.md
+++ b/docs/src/stdlib/string.md
@@ -127,12 +127,13 @@ print(shift("hello", 3)); // khoor
## format
-`s.format(...)` is printf: `s` is the format, and each `%` verb takes the
-next argument.
+`s.format(...)` is printf for numbers: `s` is the format, and each `%`
+verb takes the next argument. Text goes in by
+[interpolation](../language/strings.md#joining-and-interpolation), and is
+aligned with `padStart` and `padEnd`.
| Verb | Shows |
|---|---|
-| `%s` | a value as `print` shows it |
| `%q` | a value as it appears inside an array (strings quoted) |
| `%d` | an integer |
| `%x`, `%X`, `%o`, `%b` | an integer in hex, upper hex, octal, binary |
@@ -149,11 +150,11 @@ Between `%` and the verb come optional flags, a width and a precision:
- `*` for a width or a precision takes it from the next argument.
```rune
-print("%s has %d items".format("cart", 3)); // cart has 3 items
+print("%d items".format(3)); // 3 items
print("%.2f".format(3.14159)); // 3.14
print("%5.1f%%".format(12.345)); // 12.3%
-print("%03d|%-5s|%5s|".format(7, "ab", "cd")); // 007|ab | cd|
-print("%s and %q".format("hi", "hi")); // hi and "hi"
+print("%03d|%-5d|%5d|".format(7, 12, 34)); // 007|12 | 34|
+print("%q".format("hi")); // "hi"
print("%x %X %o %b".format(255, 255, 8, 5)); // ff FF 10 101
print("%#x".format(255)); // 0xff
print("%+d %e".format(5, 12345.678)); // +5 1.234568e+04
@@ -164,20 +165,20 @@ A receipt, its columns aligned:
```rune
let items = [["coffee", 2, 3.5], ["bagel", 1, 2.25], ["juice", 3, 4]];
for [name, qty, price] in items {
- print("%-8s %2d x %5.2f".format(name, qty, price));
+ print("{name.padEnd(8)} {"%2d x %5.2f".format(qty, price)}");
}
// coffee 2 x 3.50
// bagel 1 x 2.25
// juice 3 x 4.00
```
-With `*`, a column takes the width of its widest value:
+A column can take the width of its widest value:
```rune
let rows = [["GET /users", 12], ["POST /orders/batch", 340]];
let width = rows.reduce((w, [path, _]) => math.max(w, path.len()), 0);
for [path, ms] in rows {
- print("%-*s %4dms".format(width, path, ms));
+ print("{path.padEnd(width)} {"%4d".format(ms)}ms");
}
// GET /users 12ms
// POST /orders/batch 340ms
@@ -191,5 +192,5 @@ an `ArgumentError`:
```
```rune
-"%s and %s".format("tea"); // ArgumentError: string.format() '%s' at 7 has no argument.
+"%d and %d".format(1); // ArgumentError: string.format() '%d' at 7 has no argument.
```
diff --git a/examples/blog/main.rn b/examples/blog/main.rn
index 650bbf85..74f85412 100644
--- a/examples/blog/main.rn
+++ b/examples/blog/main.rn
@@ -17,7 +17,7 @@ fun main(args) {
for p in site.posts {
let tags = p.tags.map(t => "#" + t).join(" ");
- print(" %s %-32s %4d words %s".format(p.date, p.title, p.words, tags));
+ print(" {p.date} {p.title.padEnd(32)} {"%4d".format(p.words)} words {tags}");
}
if site.skipped {
diff --git a/examples/calc.rn b/examples/calc.rn
index 98ad42a8..36e675c3 100644
--- a/examples/calc.rn
+++ b/examples/calc.rn
@@ -305,7 +305,7 @@ fun main(args) {
let mut stats = map();
for line in DEMO {
- let kind = try parse(line).kind() catch => continue;
+ let kind = try { parse(line).kind() } catch { continue };
stats[kind] = (stats?.[kind] ?? 0) + 1;
}
diff --git a/examples/chess.rn b/examples/chess.rn
index c4e576c8..8444ae4f 100644
--- a/examples/chess.rn
+++ b/examples/chess.rn
@@ -203,7 +203,7 @@ impl Position {
for ch in row {
if regex.test(r"^[1-8]$", ch) {
- file += int(ch);
+ file += number(ch);
continue;
}
@@ -240,8 +240,8 @@ impl Position {
}
}
- let epSquare = if ep == "-" { 0 } else { sq("abcdefgh".indexOf(ep[0]), int(ep[1]) - 1) };
- let pos = Position { board, side: if side == "w" { 1 } else { -1 }, castle: rights, ep: epSquare, half: int(half), kings };
+ let epSquare = if ep == "-" { 0 } else { sq("abcdefgh".indexOf(ep[0]), number(ep[1]) - 1) };
+ let pos = Position { board, side: if side == "w" { 1 } else { -1 }, castle: rights, ep: epSquare, half: number(half), kings };
return Position { ...pos, hash: pos.computeHash(), score: pos.computeScore() };
}
@@ -896,7 +896,7 @@ fun scoreText(score) {
fun printInfo({ depth, score, nodes, seconds, pv }) {
let nps = if seconds > 0 { math.round(nodes / seconds) } else { 0 };
- print(" depth %2d %-9s nodes %8d nps %7d pv %s".format(depth, scoreText(score), nodes, nps, pv.join(" ")));
+ print(" depth {"%2d".format(depth)} {scoreText(score).padEnd(9)} nodes {"%8d".format(nodes)} nps {"%7d".format(nps)} pv {pv.join(" ")}");
}
fun search(pos, seconds = 5, maxDepth = 64, report = printInfo) {
@@ -934,7 +934,8 @@ fun demo() {
let start = time.now();
let got = perft(pos, i + 1);
let ms = math.round((time.now() - start) * 1000);
- print(" %-9s depth %d %7d %s %5d ms".format(name, i + 1, got, if got == want { "ok" } else { "WRONG, want {want}" }, ms));
+ let verdict = if got == want { "ok" } else { "WRONG, want {want}" };
+ print(" {name.padEnd(9)} depth {i + 1} {"%7d".format(got)} {verdict} {"%5d".format(ms)} ms");
}
}
@@ -1026,7 +1027,7 @@ fun options(args) {
let value = args?.[i + 1] ?? throw UsageError { message: "{arg} needs a value" };
if arg == "-d" {
- out.depth = int(value);
+ out.depth = number(value);
} else {
out.seconds = number(value);
}
@@ -1049,7 +1050,7 @@ fun main(args) {
match command {
"demo" => demo(),
- "perft" => perftCommand(int(free?.[0] ?? "4"), free[1..].join(" ") || START_FEN),
+ "perft" => perftCommand(number(free?.[0] ?? "4"), free[1..].join(" ") || START_FEN),
"go" => {
let pos = Position.fromFen(free.join(" ") || START_FEN);
print(pos.show());
diff --git a/examples/fetch.rn b/examples/fetch.rn
index e5e8b4ae..cc397425 100644
--- a/examples/fetch.rn
+++ b/examples/fetch.rn
@@ -1,7 +1,7 @@
// Fetching data from URL
try {
- let res = json.parse(http.get("https://dummyjson.com/todos"));
+ let res = json.parse(http.request("GET", "https://dummyjson.com/todos").body);
print(res);
} catch err {
print("Failed to fetch todos: " + err.message);
diff --git a/examples/kv/main.rn b/examples/kv/main.rn
index 207dca21..6ddba558 100644
--- a/examples/kv/main.rn
+++ b/examples/kv/main.rn
@@ -75,12 +75,12 @@ fun demo() {
let mut broken = bytes.buffer(good);
broken[100] ^= 0xFF;
fs.write(first, broken);
- try store.Store.open(dir, opts) catch e is store.KvError => print(" open failed: {e.message}");
+ try { store.Store.open(dir, opts); } catch e is store.KvError { print(" open failed: {e.message}"); }
fs.write(first, good);
print("\n== a second writer");
db = store.Store.open(dir, opts);
- try store.Store.open(dir, opts) catch e is store.KvError => print(" open failed: {e.message.replace(dir, "
")}");
+ try { store.Store.open(dir, opts); } catch e is store.KvError { print(" open failed: {e.message.replace(dir, "")}"); }
print("\n== compaction");
t = time.now();
@@ -170,7 +170,7 @@ fun cli(dir, cmd, rest) {
defer db.close();
return match [cmd, ...rest] {
- ["put", key, value] => db.put(key, try json.parse(value) catch _ => value),
+ ["put", key, value] => db.put(key, try { json.parse(value) } catch { value }),
["get", key] => {
if !db.has(key) {
return 1;
@@ -195,7 +195,7 @@ fun main(args) {
return match args {
[] => demo(),
["bench"] => bench(20000),
- ["bench", n] => bench(int(n)),
+ ["bench", n] => bench(number(n)),
[dir, cmd, ...rest] => cli(dir, cmd, rest),
_ => throw UsageError { message: "usage: main.rn ..." },
};
diff --git a/examples/kv/store.rn b/examples/kv/store.rn
index 77c7f149..00344ccb 100644
--- a/examples/kv/store.rn
+++ b/examples/kv/store.rn
@@ -92,7 +92,7 @@ impl Store {
// sync: fsync after every write, not only flush it to the system
fun open(dir, { maxSegment = 4 << 20, sync = false } = {}) {
fs.mkdir(dir);
- let lock = try fs.lock(fs.join(dir, "LOCK")) catch e is IOError => throw if e.code == "locked" { KvError { message: "{dir} is open elsewhere" } } else { e };
+ let lock = try { fs.lock(fs.join(dir, "LOCK")) } catch e is IOError { throw if e.code == "locked" { KvError { message: "{dir} is open elsewhere" } } else { e } };
let mut db = Store { dir, maxSegment, sync, lock };
try {
@@ -115,7 +115,7 @@ impl Store {
}
}
- let ids = fs.list(self.dir).filter(f => f.name.endsWith(".log")).map(f => int(fs.stem(f.name)));
+ let ids = fs.list(self.dir).filter(f => f.name.endsWith(".log")).map(f => number(fs.stem(f.name)));
for i, id in ids {
self.segs[id] = Segment.at(self.dir, id);
diff --git a/examples/log-report.rn b/examples/log-report.rn
index b2176ee9..3b0145cf 100644
--- a/examples/log-report.rn
+++ b/examples/log-report.rn
@@ -19,8 +19,8 @@ fun parseLine(line, n) {
time,
method,
path: normalize(path),
- status: int(status),
- bytes: if bytes == "-" { 0 } else { int(bytes) },
+ status: number(status),
+ bytes: if bytes == "-" { 0 } else { number(bytes) },
latency: number(latency) * 1000,
};
}
@@ -212,21 +212,21 @@ fun printReport(r) {
for cls in classes {
let n = r.statuses[cls];
- print(" %-4s %s %5d %5.1f%%".format(cls, bar(n, max), n, n / r.total * 100));
+ print(" {cls.padEnd(4)} {bar(n, max)} {"%5d %5.1f%%".format(n, n / r.total * 100)}");
}
print("");
print("top clients:");
for { ip, hits, distinct } in r.topClients() {
- print(" %-15s %4d hits, %d distinct endpoints".format(ip, hits, distinct));
+ print(" {ip.padEnd(15)} {"%4d".format(hits)} hits, {distinct} distinct endpoints");
}
print("");
print("slowest requests:");
for { time, method, path, status, latency } in r.slowest {
let flag = if status >= 500 { " !" } else { "" };
- print(" %8.1f ms %s %s %s → %d%s".format(latency, time, method, path, status, flag));
+ print(" {"%8.1f".format(latency)} ms {time} {method} {path} → {status}{flag}");
}
}
diff --git a/examples/query/expr.rn b/examples/query/expr.rn
index 74d53c81..61ccd7f8 100644
--- a/examples/query/expr.rn
+++ b/examples/query/expr.rn
@@ -62,7 +62,8 @@ export struct Ctx { scope, group = nil }
export fun compile(e, ctx) {
if ctx.group != nil {
- let k = ctx.group.indexOf(ast.sql(e));
+ let text = ast.sql(e);
+ let k = ctx.group.findIndex(g => g == text);
if k != nil {
return row => row[k];
diff --git a/examples/query/main.rn b/examples/query/main.rn
index 447f5449..85300fee 100644
--- a/examples/query/main.rn
+++ b/examples/query/main.rn
@@ -51,7 +51,7 @@ fun showDemo() {
defer fs.removeAll(dir);
- let n = int(os.env("ORDERS") ?? "100000");
+ let n = number(os.env("ORDERS") ?? "100000");
let mut started = time.now();
demo.generate(dir, n);
@@ -62,7 +62,7 @@ fun showDemo() {
for name in demo.TABLES {
started = time.now();
let t = catalog.load(name);
- print("loaded %-10s %7d rows %6.0f ms".format(name, t.rows.len(), (time.now() - started) * 1000));
+ print("loaded {name.padEnd(10)} {"%7d rows %6.0f ms".format(t.rows.len(), (time.now() - started) * 1000)}");
}
for src in demo.QUERIES {
diff --git a/examples/query/parser.rn b/examples/query/parser.rn
index b725cfd2..a9586a43 100644
--- a/examples/query/parser.rn
+++ b/examples/query/parser.rn
@@ -174,7 +174,7 @@ impl Parser {
throw ast.SqlError { message: "{what} takes a whole number", pos: t.pos };
}
- return int(t.text);
+ return number(t.text);
}
fun order(mut self) {
diff --git a/examples/query/plan.rn b/examples/query/plan.rn
index b4e1015e..faafa4c2 100644
--- a/examples/query/plan.rn
+++ b/examples/query/plan.rn
@@ -228,7 +228,8 @@ fun output(q, scope) {
let having = if q.having == nil { nil } else { unalias(q.having) };
let order = q.orderBy.map(({ expr: e, desc }) => {
- let i = ordinal(e, items, "ORDER BY") ?? texts.indexOf(ast.sql(unalias(e)));
+ let text = ast.sql(unalias(e));
+ let i = ordinal(e, items, "ORDER BY") ?? texts.findIndex(t => t == text);
return SortKey { column: i, expr: unalias(e), desc, text: ast.sql(e) };
});
diff --git a/examples/shop.rn b/examples/shop.rn
index df3aee94..8a828500 100644
--- a/examples/shop.rn
+++ b/examples/shop.rn
@@ -111,7 +111,7 @@ fun showCarts(carts) {
let mut top = cart.products[..];
top.sort((a, b) => b.discountedTotal - a.discountedTotal);
for { title, quantity, price, discountPercentage } in top[..3] {
- print(" %-28s %2d × %9s -%4.1f%%".format(title[..28], quantity, money(price), discountPercentage));
+ print(" {title[..28].padEnd(28)} {"%2d".format(quantity)} × {money(price).padStart(9)} -{"%4.1f".format(discountPercentage)}%");
}
}
}
@@ -123,7 +123,7 @@ fun showProducts(query, { products, total }) {
for { id, title, price, rating, stock } in byRating {
let stars = "★".repeat(math.round(rating)) + "☆".repeat(5 - math.round(rating));
let low = if stock < 10 { " low stock: {stock}" } else { "" };
- print(" #%-4d %-32s %9s %s{low}".format(id, title[..32], money(price), stars));
+ print(" #{"%-4d".format(id)} {title[..32].padEnd(32)} {money(price).padStart(9)} {stars}{low}");
}
}
diff --git a/examples/todo.rn b/examples/todo.rn
index 60c68ac2..38211429 100644
--- a/examples/todo.rn
+++ b/examples/todo.rn
@@ -43,14 +43,18 @@ fun daysBetween(from, to) {
fun parseDate(s, now) {
if regex.test(r"^\d{4}-\d{2}-\d{2}$", s) {
- try time.parse(s, DAY) catch e is ValueError => throw UsageError { message: "bad date '{s}'" };
+ try {
+ time.parse(s, DAY);
+ } catch e is ValueError {
+ throw UsageError { message: "bad date '{s}'" };
+ }
return s;
}
let rel = regex.find(r"^\+(\d+)d$", s);
if rel {
- return addDays(now, int(rel.groups[0]));
+ return addDays(now, number(rel.groups[0]));
}
return match s {
@@ -58,7 +62,7 @@ fun parseDate(s, now) {
"tomorrow" => addDays(now, 1),
_ if s in WEEKDAYS => {
let wd = time.date(time.parse(now, DAY)).weekday;
- return addDays(now, (WEEKDAYS.indexOf(s) + 1 - wd + 6) % 7 + 1);
+ return addDays(now, (WEEKDAYS.findIndex(d => d == s) + 1 - wd + 6) % 7 + 1);
},
_ => throw UsageError { message: "bad date '{s}': use YYYY-MM-DD, today, tomorrow, +Nd or a weekday" },
};
@@ -90,7 +94,7 @@ impl Store {
}
let data = json.parse(fs.readText(path));
- return Store { path, tasks: data.tasks.map(o => Task({ ...o, priority: Priority(o.priority) })), nextId: data.nextId };
+ return Store { path, tasks: data.tasks.map(o => Task { ...o, priority: Priority(o.priority) }), nextId: data.nextId };
}
fun save(self) {
@@ -100,7 +104,7 @@ impl Store {
}
fun add(mut self, task) {
- self.tasks.push(Task({ ...task, id: self.nextId }));
+ self.tasks.push(Task { ...task, id: self.nextId });
self.nextId += 1;
return self.nextId - 1;
}
@@ -150,7 +154,7 @@ fun ids(args) {
throw UsageError { message: "bad id '{a}'" };
}
- return int(a);
+ return number(a);
});
}
@@ -183,7 +187,7 @@ fun show(t, now) {
let prio = match t.priority { Priority.High => "↑", Priority.Low => "↓", Priority.Normal => " " };
let due = if t.due != nil { relative(t.due, now) } else { "" };
let tags = t.tags.map(tag => "+" + tag).join(" ");
- return "[%s] %3d %s %-28s %-10s %s".format(mark, t.id, prio, t.text, due, tags).trimEnd();
+ return "[{mark}] {"%3d".format(t.id)} {prio} {t.text.padEnd(28)} {due.padEnd(10)} {tags}".trimEnd();
}
fun list(store, args, now) {
@@ -233,7 +237,7 @@ fun stats(store, now) {
let mut rows = byTag.entries();
rows.sort(([_, a], [_, b]) => b - a);
for [tag, n] in rows {
- print(" %-10s %s %d".format("+" + tag, "#".repeat(n), n));
+ print(" {("+" + tag).padEnd(10)} {"#".repeat(n)} {n}");
}
}
@@ -265,7 +269,7 @@ fun run(mut store, [cmd = "list", ...args], now) {
"edit" => {
let [id = throw UsageError { message: "which task? give an id" }, ...words] = args;
let changes = parseTask(words, now);
- store.update(ids([id])[0], t => Task({ ...t, ...changes, tags: [...t.tags, ...changes.tags] }));
+ store.update(ids([id])[0], t => Task { ...t, ...changes, tags: [...t.tags, ...changes.tags] });
print(" edited #{id}");
},
"stats" => stats(store, now),
diff --git a/examples/validate.rn b/examples/validate.rn
index 8d9121cc..31968cc2 100644
--- a/examples/validate.rn
+++ b/examples/validate.rn
@@ -203,7 +203,7 @@ fun checkUrl({ schemes }, v, path, mut out) {
return fail(out, path, "scheme {scheme} is not allowed, use {schemes.join(" or ")}");
}
- if port != nil && !validPort(int(port)) {
+ if port != nil && !validPort(number(port)) {
return fail(out, path, "port {port} is out of range 1-65535");
}
@@ -216,7 +216,7 @@ fun checkAddr(v, path, mut out) {
}
let m = regex.find(r"^(?:[\w.-]*|\[[0-9a-fA-F:]+\]):(\d+)$", v) ?? return fail(out, path, "{show(v)} is not host:port");
- let port = int(m.groups[0]);
+ let port = number(m.groups[0]);
return if validPort(port) { v } else { fail(out, path, "port {port} is out of range 1-65535") };
}
@@ -457,13 +457,17 @@ fun upgrade(raw, mut notes) {
while true {
let v = cfg?.version ?? 1;
- cfg = try match v {
- 1 => v1to2(cfg, notes),
- 2 => v2to3(cfg, notes),
- LATEST => return cfg,
- _ if v is number && v > LATEST => throw MigrationError { message: "version {v} is newer than this tool knows ({LATEST})" },
- _ => throw MigrationError { message: "unknown version {show(v)}" },
- } catch e is KeyError | TypeError => throw MigrationError { message: "cannot migrate v{v} to v{v + 1}: {e.message}" };
+ cfg = try {
+ match v {
+ 1 => v1to2(cfg, notes),
+ 2 => v2to3(cfg, notes),
+ LATEST => return cfg,
+ _ if v is number && v > LATEST => throw MigrationError { message: "version {v} is newer than this tool knows ({LATEST})" },
+ _ => throw MigrationError { message: "unknown version {show(v)}" },
+ }
+ } catch e is KeyError | TypeError {
+ throw MigrationError { message: "cannot migrate v{v} to v{v + 1}: {e.message}" }
+ };
}
}
@@ -532,12 +536,12 @@ fun parseDuration(s) {
return nil;
}
- return regex.findAll(r"(\d+)(ms|s|m|h)", s).reduce((ms, m) => ms + int(m.groups[0]) * UNITS[m.groups[1]], 0);
+ return regex.findAll(r"(\d+)(ms|s|m|h)", s).reduce((ms, m) => ms + number(m.groups[0]) * UNITS[m.groups[1]], 0);
}
fun parseSize(s) {
let m = regex.find(r"^(\d+)\s*(B|KB|MB|GB)$", s) ?? return nil;
- return int(m.groups[0]) * SIZES[m.groups[1]];
+ return number(m.groups[0]) * SIZES[m.groups[1]];
}
fun inUnits(n, units) {
@@ -560,7 +564,7 @@ fun report(issues) {
for { path, message, level } in issues {
let tag = match level { Level.Error => "error", Level.Warning => "warn" };
- print(" %-5s %-*s %s".format(tag, width, fmtPath(path), message));
+ print(" {tag.padEnd(5)} {fmtPath(path).padEnd(width)} {message}");
}
print(match [errors, warnings] {
@@ -580,7 +584,7 @@ struct UsageError { message }
fun load(path) {
let text = fs.readText(path);
- return try json.parse(text) catch e is ValueError => throw ValueError { message: "{path} is not valid JSON: {e.message}", cause: e };
+ return try { json.parse(text) } catch e is ValueError { throw ValueError { message: "{path} is not valid JSON: {e.message}", cause: e } };
}
fun run([cmd = "help", path = nil, ...flags]) {
diff --git a/pkg/ast/expression.go b/pkg/ast/expression.go
index 6828e446..5fb945a1 100644
--- a/pkg/ast/expression.go
+++ b/pkg/ast/expression.go
@@ -470,6 +470,8 @@ type IfExpr struct {
If *IfStmt
}
+func (n *IfExpr) Values() []Expr { return n.If.Values() }
+
func (n *IfExpr) Accept(v ExprVisitor) (value.Value, error) {
return v.VisitIfExpr(n)
}
@@ -488,22 +490,18 @@ func (n *ThrowExpr) String() string {
return fmt.Sprintf("(throw %v)", n.Value)
}
-// TryExpr is try in an expression: the value of Value or, if it fails, of
-// the first catch clause that matches.
+// TryExpr is a try whose value is used: that of the body or, if it
+// fails, of the first catch clause that matches.
type TryExpr struct {
- Value Expr
- Catches []CatchClause
- Keyword Token
+ Try *TryStmt
}
+func (n *TryExpr) Values() []Expr { return n.Try.Values() }
+
func (n *TryExpr) Accept(v ExprVisitor) (value.Value, error) {
return v.VisitTryExpr(n)
}
-func (n *TryExpr) String() string {
- return fmt.Sprintf("(try %v)", n.Value)
-}
-
// JumpExpr is return, break or continue in an expression; it has no value.
type JumpExpr struct {
Stmt Stmt
diff --git a/pkg/ast/pattern.go b/pkg/ast/pattern.go
index 69d90fe0..0d329f2d 100644
--- a/pkg/ast/pattern.go
+++ b/pkg/ast/pattern.go
@@ -262,6 +262,10 @@ type MatchStmt struct {
Match *MatchExpr
}
+func (n *MatchStmt) Values() []Expr { return n.Match.Values() }
+
+func (n *MatchStmt) AsExpr() Expr { return n.Match }
+
func (n *MatchStmt) Accept(v StmtVisitor) error {
return v.VisitMatchStmt(n)
}
diff --git a/pkg/ast/statement.go b/pkg/ast/statement.go
index 91b21dd9..2f487fc8 100644
--- a/pkg/ast/statement.go
+++ b/pkg/ast/statement.go
@@ -111,6 +111,16 @@ func NewBlockStmt(stmts []Stmt) Stmt {
return &BlockStmt{Stmts: stmts}
}
+// ValuedStmt is a statement that gives a value as the last of a block
+// with one: if, match and try.
+type ValuedStmt interface {
+ Stmt
+ // Values returns the value of each branch, nil for one without.
+ Values() []Expr
+ // AsExpr is the statement as an expression giving that value.
+ AsExpr() Expr
+}
+
// IfStmt is if cond { then } [else ...]; El is nil, a *BlockStmt or an
// *IfStmt.
type IfStmt struct {
@@ -119,8 +129,9 @@ type IfStmt struct {
El Stmt
}
-// Values returns the value of each branch, nil for one without, a missing
-// else included.
+func (n *IfStmt) AsExpr() Expr { return &IfExpr{If: n} }
+
+// Values counts a missing else as a branch without a value.
func (n *IfStmt) Values() []Expr {
vs := []Expr{n.Then.Value()}
@@ -233,25 +244,31 @@ func NewFunctionStmt(name Token, parameters []Binding, body []Stmt) *FunctionStm
// TryStmt runs Body and, if it fails with a runtime error or a throw, runs
// the first catch clause that matches.
type TryStmt struct {
- Body Stmt
+ Body *BlockStmt
Catches []CatchClause
}
-// CatchClause is catch [name [is T | U]] { body }, or in a TryExpr
-// catch [name [is T | U]] => value; without Types it catches any error.
-// The resolver sets Shapes, one per type.
+func (n *TryStmt) AsExpr() Expr { return &TryExpr{Try: n} }
+
+// Values gives the value of the body, then of each catch.
+func (n *TryStmt) Values() []Expr {
+ vs := []Expr{n.Body.Value()}
+ for _, c := range n.Catches {
+ vs = append(vs, c.Body.Value())
+ }
+
+ return vs
+}
+
+// CatchClause is catch [name [is T | U]] { body }; without Types it
+// catches any error. The resolver sets Shapes, one per type.
type CatchClause struct {
Keyword Token
Param *Token
ParamLocal *Local
Types []*VarExpr
Shapes []*value.Shape
- Body []Stmt
- Value Expr
-}
-
-func NewTryStmt(body Stmt, catches []CatchClause) Stmt {
- return &TryStmt{Body: body, Catches: catches}
+ Body *BlockStmt
}
// StructField is a field of a struct declaration; Default, at DefaultAt,
diff --git a/pkg/rune/bench_test.go b/pkg/rune/bench_test.go
index 27d246d6..6fb3a9dc 100644
--- a/pkg/rune/bench_test.go
+++ b/pkg/rune/bench_test.go
@@ -31,7 +31,7 @@ var benchSources = map[string]string{
"mutself": `struct C { n } impl C { fun incr(mut self) { self.n += 1; } } let mut c = C { n: 0 }; for i in 0..20000 { c.incr(); }`,
"objcall": `let o = {a: 1, b: 2}; let mut s = 0; for i in 0..20000 { s += o.len(); }`,
"print": `for i in 0..20000 { print(i); }`,
- "format": `let mut n = 0; for i in 0..20000 { n += "%-8s|%5.2f|%03d".format("ab", 3.14159, i).len(); }`,
+ "format": `let mut n = 0; for i in 0..20000 { n += "%5.2f|%03d".format(3.14159, i).len(); }`,
}
var containerSources = map[string]string{
diff --git a/pkg/rune/bytecode.go b/pkg/rune/bytecode.go
index 34f4ea02..5f9e9091 100644
--- a/pkg/rune/bytecode.go
+++ b/pkg/rune/bytecode.go
@@ -248,7 +248,9 @@ type Proto struct {
consts []value.Value
protos []*Proto
keys [][]string
- upvals []upvalDesc
+ // keyToks locates each key of an object literal's keys, for its errors.
+ keyToks [][]ast.Token
+ upvals []upvalDesc
}
// accepts reports whether f takes n arguments.
diff --git a/pkg/rune/compile.go b/pkg/rune/compile.go
index 5ada718c..f35480d4 100644
--- a/pkg/rune/compile.go
+++ b/pkg/rune/compile.go
@@ -364,12 +364,14 @@ func (fs *funcState) declare(l *ast.Local) int32 {
}
// keyList adds the property names of an object literal or pattern.
-func (fs *funcState) keyList(keys []string) int32 {
+// keyList adds keys to the key lists; toks locates them, or is nil.
+func (fs *funcState) keyList(keys []string, toks []ast.Token) int32 {
for i, k := range keys {
keys[i] = fs.unit.intern(k)
}
fs.proto.keys = append(fs.proto.keys, keys)
+ fs.proto.keyToks = append(fs.proto.keyToks, toks)
return int32(len(fs.proto.keys) - 1)
}
diff --git a/pkg/rune/compile_expr.go b/pkg/rune/compile_expr.go
index 0d3ac80f..9b42ee93 100644
--- a/pkg/rune/compile_expr.go
+++ b/pkg/rune/compile_expr.go
@@ -83,8 +83,6 @@ func assigns(e ast.Expr) bool {
return assigns(n.Left) || assigns(n.Right)
case *ast.ThrowExpr:
return assigns(n.Value)
- case *ast.TryExpr:
- return assigns(n.Value) || slices.ContainsFunc(n.Catches, func(c ast.CatchClause) bool { return assigns(c.Value) })
case *ast.JumpExpr:
r, ok := n.Stmt.(*ast.ReturnStmt)
return ok && assigns(r.Value)
@@ -263,22 +261,16 @@ func fresh(e ast.Expr) bool {
return true
case *ast.LogicalExpr:
return fresh(n.Left) && fresh(n.Right)
- case *ast.IfExpr, *ast.MatchExpr:
- return !slices.ContainsFunc(values(n), func(v ast.Expr) bool { return !fresh(v) })
+ case valuedExpr:
+ return !slices.ContainsFunc(n.Values(), func(v ast.Expr) bool { return !fresh(v) })
}
return false
}
-// values returns what each branch of an if or match expression gives,
-// nil for one that gives nil.
-func values(e ast.Expr) []ast.Expr {
- if n, ok := e.(*ast.IfExpr); ok {
- return n.If.Values()
- }
-
- return e.(*ast.MatchExpr).Values()
-}
+// valuedExpr is an if, match or try giving the value of the branch
+// taken; Values has nil for a branch giving nil.
+type valuedExpr interface{ Values() []ast.Expr }
// paramMove is the Param of the parameter e reads last, or 0: it gives
// its value up only if the caller did.
@@ -369,11 +361,13 @@ func (fs *funcState) expr(e ast.Expr, dst int32) {
case *ast.ObjectExpr:
fs.literal(dst, len(n.Pairs), true, func(i int) ast.Expr { return n.Pairs[i].Value }, func(from, to int, base int32) ins {
keys := make([]string, 0, to-from)
+ toks := make([]ast.Token, 0, to-from)
for _, pair := range n.Pairs[from:to] {
keys = append(keys, pair.Key)
+ toks = append(toks, pair.Token)
}
- return ins{op: opObject, b: base, c: fs.keyList(keys)}
+ return ins{op: opObject, b: base, c: fs.keyList(keys, toks)}
})
case *ast.StructExpr:
fs.structLiteral(n, dst)
@@ -398,7 +392,7 @@ func (fs *funcState) expr(e ast.Expr, dst int32) {
fs.expr(n.Value, dst)
fs.emit(ins{op: opThrow, a: dst}, &n.Keyword)
case *ast.TryExpr:
- fs.tryExpr(n, dst)
+ fs.tryStmt(n.Try, dst)
case *ast.JumpExpr:
fs.stmt(n.Stmt)
default:
@@ -552,8 +546,8 @@ func writesEarly(e ast.Expr) bool {
switch n := unwrap(e).(type) {
case *ast.LogicalExpr, *ast.AssignExpr, *ast.SetIndexExpr, *ast.ThrowExpr, *ast.TryExpr:
return true
- case *ast.IfExpr, *ast.MatchExpr:
- return slices.ContainsFunc(values(n), writesEarly)
+ case valuedExpr:
+ return slices.ContainsFunc(n.Values(), writesEarly)
}
return false
@@ -717,7 +711,7 @@ func (fs *funcState) unary(n *ast.UnaryExpr, dst int32) {
func (fs *funcState) call(n *ast.CallExpr, dst int32) {
spread := slices.ContainsFunc(n.Args, ast.IsSpread)
- if prop, ok := n.Callee.(*ast.IndexExpr); ok && isMethodCall(prop) && !n.Optional && !spread {
+ if prop, ok := n.Callee.(*ast.IndexExpr); ok && isMethodCall(prop) && !n.Optional {
fs.invoke(n, prop, dst)
return
}
diff --git a/pkg/rune/compile_pattern.go b/pkg/rune/compile_pattern.go
index 2b616088..786909e6 100644
--- a/pkg/rune/compile_pattern.go
+++ b/pkg/rune/compile_pattern.go
@@ -26,7 +26,7 @@ func (fs *funcState) destructure(pat ast.Pattern, src int32) {
}
if r := n.Rest; r != nil {
- c := fs.keyList(fieldKeys(n.Fields))
+ c := fs.keyList(fieldKeys(n.Fields), nil)
fs.initialize(r.Local, func(dst int32) {
fs.emit(ins{op: opOmit, a: dst, b: src, c: c}, &n.Brace)
})
@@ -162,7 +162,7 @@ func (fs *funcState) pattern(p ast.Pattern, s int32) []int {
}
if n.Rest != nil {
- c := fs.keyList(fieldKeys(n.Fields))
+ c := fs.keyList(fieldKeys(n.Fields), nil)
fs.emit(ins{op: opOmit, a: fs.locals[n.Rest.Local], b: s, c: c}, &n.Brace)
}
diff --git a/pkg/rune/compile_stmt.go b/pkg/rune/compile_stmt.go
index 5b7a2e20..89b5b1a9 100644
--- a/pkg/rune/compile_stmt.go
+++ b/pkg/rune/compile_stmt.go
@@ -146,7 +146,7 @@ func (fs *funcState) stmt(stmt ast.Stmt) {
case *ast.ReturnStmt:
fs.returnStmt(s)
case *ast.TryStmt:
- fs.tryStmt(s)
+ fs.tryStmt(s, noReg)
case *ast.DeferStmt:
fs.deferStmt(s, func() {})
case *ast.MatchStmt:
@@ -523,18 +523,17 @@ func (fs *funcState) rangeParts(r *ast.RangeExpr) int32 {
return base
}
-func (fs *funcState) tryStmt(s *ast.TryStmt) {
- fs.tryCatch(s.Catches, fs.nactive, func() { fs.stmt(s.Body) }, func(c *ast.CatchClause, r int32) {
- fs.bindCatch(c, r)
- fs.stmts(c.Body)
- })
-}
+// tryStmt compiles s, with the value of the block that ran into dst
+// unless it is noReg; the error goes above every live register.
+func (fs *funcState) tryStmt(s *ast.TryStmt, dst int32) {
+ at := fs.nactive
+ if dst != noReg {
+ at = max(fs.free, dst+1)
+ }
-// tryExpr puts the error above every live register, dst included.
-func (fs *funcState) tryExpr(t *ast.TryExpr, dst int32) {
- fs.tryCatch(t.Catches, max(fs.free, dst+1), func() { fs.expr(t.Value, dst) }, func(c *ast.CatchClause, r int32) {
+ fs.tryCatch(s.Catches, at, func() { fs.block(s.Body, dst) }, func(c *ast.CatchClause, r int32) {
fs.bindCatch(c, r)
- fs.expr(c.Value, dst)
+ fs.block(c.Body, dst)
})
}
diff --git a/pkg/rune/http_test.go b/pkg/rune/http_test.go
index a2a0a42a..adf30c64 100644
--- a/pkg/rune/http_test.go
+++ b/pkg/rune/http_test.go
@@ -48,9 +48,8 @@ func TestHTTPRequest(t *testing.T) {
let nf = http.request("GET", "URL/missing", HttpOptions {});
print(nf.status);
- print(http.get("URL/"));
+ print(http.request("GET", "URL/").body);
- try { http.get("URL/missing"); } catch e is IOError { print("get failed"); }
try { http.request("GET", "URL/slow", { timeout: 0.05 }); } catch e is IOError { print("timed out"); }
try { http.request("GET", "URL/", { body: 1 }); } catch e is TypeError { print(e.message); }
try { http.request("GET", "URL/", { headers: { a: 1 } }); } catch e is TypeError { print(e.message); }
@@ -84,7 +83,6 @@ a, b
true
404
GET
-get failed
timed out
http.request() expects HttpOptions.body to be a string, got number.
http.request() expects header 'a' to be a string, got number.
diff --git a/pkg/rune/interpreter.go b/pkg/rune/interpreter.go
index 4a5a894e..472869a9 100644
--- a/pkg/rune/interpreter.go
+++ b/pkg/rune/interpreter.go
@@ -162,9 +162,11 @@ func (p *Interpreter) CallValue(fn value.Value, args []value.Value, token *ast.T
}
}
+ if isEnum(fn) {
+ return variant(token, fn.TypeShape(), args)
+ }
+
switch fn.Kind() {
- case value.Type:
- return convert(token, fn.TypeShape(), args)
case value.Function:
switch f := fn.Fn().(type) {
case *Closure:
@@ -180,10 +182,6 @@ func (p *Interpreter) CallValue(fn value.Value, args []value.Value, token *ast.T
}
return p.run(len(p.frames) - 1)
- case *BoundMethod:
- return p.CallValue(value.NewFunction(f.fn), append([]value.Value{f.recv}, args...), token)
- case *BoundNative:
- return p.host.CallMethod(f.fn, append([]value.Value{f.recv}, args...), token)
case *stdlib.Native:
return p.host.Call(f, args, token)
}
@@ -197,10 +195,6 @@ func (p *Interpreter) Required(fn value.Value) int {
switch f := fn.Fn().(type) {
case *Closure:
return f.proto.required
- case *BoundMethod:
- return f.fn.proto.required - 1
- case *BoundNative:
- return f.fn.Min() - 1
case *stdlib.Native:
return f.Min()
}
diff --git a/pkg/rune/methods.go b/pkg/rune/methods.go
index 2f382033..d59aa1a1 100644
--- a/pkg/rune/methods.go
+++ b/pkg/rune/methods.go
@@ -9,22 +9,6 @@ import (
"rune/pkg/value"
)
-// BoundMethod is a method read off its receiver, as in p.len.
-type BoundMethod struct {
- recv value.Value
- fn *Closure
-}
-
-func (b *BoundMethod) String() string { return b.fn.String() }
-
-// BoundNative is a built-in method read off its receiver, as in m.keys.
-type BoundNative struct {
- recv value.Value
- fn *stdlib.Native
-}
-
-func (b *BoundNative) String() string { return b.fn.String() }
-
// methodsOf returns the methods of v's type, and the type's name.
func (p *Interpreter) methodsOf(v value.Value) ([]value.Method, string) {
switch v.Kind() {
@@ -74,29 +58,33 @@ func (p *Interpreter) property(tok *ast.Token, t, key value.Value, missing *valu
return value.NilValue, missingMember(tok, t, key.Str(), ms)
}
-// methodValue is m read off t: bound to an instance, or off a struct type
-// the plain function, which takes the instance first.
+// methodValue is m read off t: only a static method, off its type, is a
+// value; a method taking self is only called.
func (p *Interpreter) methodValue(tok *ast.Token, t value.Value, m *value.Method, owner string) (value.Value, error) {
- switch {
- case t.Kind() == value.Type:
- return p.methods[m.ID], nil
- case !m.Self:
- return value.NilValue, staticMethod(tok, owner, m.Name)
- case m.Mut:
- return value.NilValue, errors.NewRuntimeError(errors.TypeError, *tok, fmt.Sprintf(
- "Cannot take mutating method '%s' of %s as a value.", m.Name, owner))
- case m.InPlace:
+ if err := receiverError(tok, t, m, owner); err != nil {
+ return value.NilValue, err
+ }
+
+ if m.Self {
return value.NilValue, errors.NewRuntimeError(errors.TypeError, *tok, fmt.Sprintf(
- "Cannot take in-place method '%s' of %s as a value.", m.Name, owner))
+ "Cannot take method '%s' of %s as a value.", m.Name, owner))
}
- value.Share(t)
+ return p.methods[m.ID], nil
+}
- if nat, ok := p.methods[m.ID].Fn().(*stdlib.Native); ok {
- return value.NewFunction(&BoundNative{recv: t, fn: nat}), nil
+// receiverError is the error of m reached through t of the wrong kind: a
+// method taking self through its type, or a static one through an instance.
+func receiverError(tok *ast.Token, t value.Value, m *value.Method, owner string) error {
+ switch onType := t.Kind() == value.Type; {
+ case onType && m.Self:
+ return errors.NewRuntimeError(errors.TypeError, *tok, fmt.Sprintf(
+ "'%s' is a method of %s values; call it on one.", m.Name, owner))
+ case !onType && !m.Self:
+ return staticMethod(tok, owner, m.Name)
}
- return value.NewFunction(&BoundMethod{recv: t, fn: (*Closure)(p.methods[m.ID].Ptr())}), nil
+ return nil
}
// invoke calls the method t.K[C](args) for the receiver t at R[A+1]:
@@ -123,11 +111,16 @@ func (p *Interpreter) invoke(fr *frame, in Instr, tok *ast.Token) error {
}
return noMethod(tok, t, owner, key.Str(), ms)
+ }
+
+ if err := receiverError(tok, t, m, owner); err != nil {
+ return err
+ }
+
+ switch {
case t.Kind() == value.Type:
p.stack[at] = p.methods[m.ID]
return p.callWithout(at, n, tok)
- case !m.Self:
- return staticMethod(tok, owner, m.Name)
case m.Mut && !in.y():
return errors.NewRuntimeError(errors.TypeError, *tok, mutatingCallError(m.Name, owner))
case m.InPlace && in.x()&1 != 0:
diff --git a/pkg/rune/moves.go b/pkg/rune/moves.go
index 6460c1ed..74ff5acb 100644
--- a/pkg/rune/moves.go
+++ b/pkg/rune/moves.go
@@ -202,11 +202,7 @@ func (lv *liveness) try(live liveSet, catches []ast.CatchClause, body func()) {
caught := liveSet{}
for _, c := range catches {
in := maps.Clone(live)
- if c.Value != nil {
- lv.expr(c.Value, in)
- } else {
- lv.stmts(c.Body, in)
- }
+ lv.stmt(c.Body, in)
caught.add(in)
}
@@ -343,7 +339,7 @@ func (lv *liveness) expr(e ast.Expr, live liveSet) {
clear(live)
lv.expr(n.Value, live)
case *ast.TryExpr:
- lv.try(live, n.Catches, func() { lv.expr(n.Value, live) })
+ lv.stmt(n.Try, live)
case *ast.JumpExpr:
lv.stmt(n.Stmt, live)
case *ast.MatchExpr:
diff --git a/pkg/rune/ops.go b/pkg/rune/ops.go
index 94554870..8c0fef2b 100644
--- a/pkg/rune/ops.go
+++ b/pkg/rune/ops.go
@@ -44,14 +44,18 @@ func setField(token *ast.Token, target, key, v value.Value) error {
return nil
}
-// convert is a call of the struct type shape, which takes one value.
-func convert(token *ast.Token, shape *value.Shape, args []value.Value) (value.Value, error) {
+// isEnum reports whether v is an enum type, which a call gives a variant of.
+func isEnum(v value.Value) bool { return v.Kind() == value.Type && v.TypeShape().Enum }
+
+// variant is a call of the enum type shape: the variant its one argument
+// numbers or names.
+func variant(token *ast.Token, shape *value.Shape, args []value.Value) (value.Value, error) {
if len(args) != 1 {
return value.NilValue, errors.NewRuntimeError(errors.ArgumentError, *token, fmt.Sprintf(
"%s() expects 1 argument, got %d.", shape.Name, len(args)))
}
- return stdlib.Convert(token, shape, args[0])
+ return stdlib.Variant(token, shape, args[0])
}
// propertyTarget fails unless target can have a property set, as only
diff --git a/pkg/rune/parse_expr.go b/pkg/rune/parse_expr.go
index 25c26b6e..9e46f619 100644
--- a/pkg/rune/parse_expr.go
+++ b/pkg/rune/parse_expr.go
@@ -283,10 +283,6 @@ func (s *Parser) unary() (ast.Expr, error) {
return &ast.ThrowExpr{Value: v, Keyword: keyword}, nil
}
- if s.match(ast.TRY) {
- return s.tryExpr()
- }
-
if s.match(ast.RETURN, ast.BREAK, ast.CONTINUE) {
j, err := s.jumpExpr()
if err != nil {
@@ -310,44 +306,6 @@ func (s *Parser) unary() (ast.Expr, error) {
return s.call()
}
-// tryExpr parses `try value catch [name [is T | U]] => value ...`; "try"
-// has already been consumed.
-func (s *Parser) tryExpr() (ast.Expr, error) {
- t := &ast.TryExpr{Keyword: s.previous()}
-
- v, err := s.assignment()
- if err != nil {
- return nil, err
- }
-
- t.Value = v
-
- if _, err := s.consume(ast.CATCH, "Expect 'catch' after try expression."); err != nil {
- return nil, err
- }
-
- for {
- c, err := s.catchHead()
- if err != nil {
- return nil, err
- }
-
- if _, err := s.consume(ast.ARROW, "Expect '=>' after 'catch'."); err != nil {
- return nil, err
- }
-
- if c.Value, err = s.assignment(); err != nil {
- return nil, err
- }
-
- t.Catches = append(t.Catches, c)
-
- if !s.match(ast.CATCH) {
- return t, nil
- }
- }
-}
-
// jumpExpr parses return, break or continue in an expression (the keyword
// is consumed); return takes a value unless what follows ends the expression.
func (s *Parser) jumpExpr() (*ast.JumpExpr, error) {
@@ -410,7 +368,16 @@ func (s *Parser) primary() (ast.Expr, error) {
return nil, err
}
- return &ast.IfExpr{If: st}, nil
+ return st.AsExpr(), nil
+ }
+
+ if s.match(ast.TRY) {
+ st, err := s.tryStatement()
+ if err != nil {
+ return nil, err
+ }
+
+ return st.AsExpr(), nil
}
if s.match(ast.TRUE) {
diff --git a/pkg/rune/parse_stmt.go b/pkg/rune/parse_stmt.go
index 23aeb5ef..d40145f1 100644
--- a/pkg/rune/parse_stmt.go
+++ b/pkg/rune/parse_stmt.go
@@ -347,25 +347,19 @@ func (s *Parser) parameter(i int, rest bool) (ast.Binding, ast.Stmt, error) {
}
func (s *Parser) varDeclaration() (ast.Stmt, error) {
- mutable := s.match(ast.MUT)
-
if s.check(ast.LEFT_BRACE) || s.check(ast.LEFT_BRACKET) {
pat, err := s.destructuring()
if err != nil {
return nil, err
}
- if mutable {
- for _, b := range ast.Bindings(pat) {
- b.Mutable = true
- }
- }
-
init, err := s.patternInitializer()
return &ast.PatternStmt{Pattern: pat, Initializer: init}, err
}
+ mutable := s.match(ast.MUT)
+
name, err := s.consume(ast.IDENTIFIER, "Expect variable name.")
if err != nil {
return nil, err
@@ -434,8 +428,7 @@ func (s *Parser) statement() (ast.Stmt, error) {
return s.deferStatement()
}
- if s.atTryStatement() {
- s.advance()
+ if s.match(ast.TRY) {
return s.tryStatement()
}
@@ -568,15 +561,10 @@ func (s *Parser) blockOf(valued bool) (*ast.BlockStmt, error) {
}
b.Valued = valued
- case *ast.IfStmt:
+ case ast.ValuedStmt:
b.Valued = valued && hasValue(st.Values())
if b.Valued {
- *last = ast.NewExprStmt(&ast.IfExpr{If: st})
- }
- case *ast.MatchStmt:
- b.Valued = valued && hasValue(st.Match.Values())
- if b.Valued {
- *last = ast.NewExprStmt(st.Match)
+ *last = ast.NewExprStmt(st.AsExpr())
}
}
}
@@ -669,9 +657,6 @@ func stmtKeyword(t ast.TokenType) bool {
return false
}
-// atTryStatement reports whether "try {" is ahead; any other try is an expression.
-func (s *Parser) atTryStatement() bool { return s.check(ast.TRY) && s.peekAt(1) == ast.LEFT_BRACE }
-
// body parses an if/else/while/for body, a block.
func (s *Parser) body(after string) (ast.Stmt, error) {
if s.check(ast.LEFT_BRACE) {
@@ -789,14 +774,9 @@ func (s *Parser) forBindings() (key *ast.Binding, val ast.Binding, unpack ast.St
return key, val, unpack, s.match(ast.IN)
}
-// tryStatement parses `try { ... }` and its catch clauses: `catch { ... }`,
-// `catch (name) { ... }` or `catch (name: Type, ...) { ... }`.
-func (s *Parser) tryStatement() (ast.Stmt, error) {
- if _, err := s.consume(ast.LEFT_BRACE, "Expect '{' after 'try'."); err != nil {
- return nil, err
- }
-
- body, err := s.block()
+// tryStatement parses `try { ... }` and its catch clauses, `catch [name [is T | U]] { ... }`.
+func (s *Parser) tryStatement() (*ast.TryStmt, error) {
+ body, err := s.branch("'try'")
if err != nil {
return nil, err
}
@@ -805,38 +785,24 @@ func (s *Parser) tryStatement() (ast.Stmt, error) {
return nil, err
}
- var catches []ast.CatchClause
+ st := &ast.TryStmt{Body: body}
for {
- c, err := s.catchClause()
+ c, err := s.catchHead()
if err != nil {
return nil, err
}
- catches = append(catches, c)
-
- if !s.match(ast.CATCH) {
- break
+ if c.Body, err = s.branch("'catch'"); err != nil {
+ return nil, err
}
- }
- return ast.NewTryStmt(ast.NewBlockStmt(body), catches), nil
-}
+ st.Catches = append(st.Catches, c)
-func (s *Parser) catchClause() (ast.CatchClause, error) {
- c, err := s.catchHead()
- if err != nil {
- return c, err
- }
-
- if _, err := s.consume(ast.LEFT_BRACE, "Expect '{' after 'catch'."); err != nil {
- return c, err
+ if !s.match(ast.CATCH) {
+ return st, nil
+ }
}
-
- handler, err := s.block()
- c.Body = handler
-
- return c, err
}
// catchHead parses what follows "catch": [name [is T | U]].
diff --git a/pkg/rune/resolve_impl.go b/pkg/rune/resolve_impl.go
index 62a51ed0..832a198f 100644
--- a/pkg/rune/resolve_impl.go
+++ b/pkg/rune/resolve_impl.go
@@ -200,15 +200,10 @@ func (p *Resolver) checkMutation(call *ast.CallExpr, prop *ast.IndexExpr) {
}
}
-// staticShape is the struct type of a literal or a conversion, or nil.
+// staticShape is the struct type of a literal, or nil.
func (p *Resolver) staticShape(e ast.Expr) *value.Shape {
- switch r := e.(type) {
- case *ast.StructExpr:
+ if r, ok := e.(*ast.StructExpr); ok {
return r.Shape
- case *ast.CallExpr:
- if t, ok := r.Callee.(*ast.VarExpr); ok {
- return p.structs[t.Local]
- }
}
return nil
diff --git a/pkg/rune/resolver.go b/pkg/rune/resolver.go
index 17bd7530..0d0252b9 100644
--- a/pkg/rune/resolver.go
+++ b/pkg/rune/resolver.go
@@ -380,10 +380,7 @@ func (p *Resolver) VisitTryStmt(tryStmt *ast.TryStmt) error {
}
func (p *Resolver) VisitTryExpr(expr *ast.TryExpr) (value.Value, error) {
- p.resolveExpr(expr.Value)
- p.resolveCatches(expr.Catches)
-
- return value.NilValue, nil
+ return value.NilValue, p.VisitTryStmt(expr.Try)
}
func (p *Resolver) resolveCatches(catches []ast.CatchClause) {
@@ -412,7 +409,7 @@ func (p *Resolver) resolveCatches(catches []ast.CatchClause) {
}
func (p *Resolver) resolveCatch(c *ast.CatchClause) {
- scoped := c.Param != nil || declaresLocals(c.Body)
+ scoped := c.Param != nil || declaresLocals(c.Body.Stmts)
if scoped {
p.beginScope()
defer p.endScope()
@@ -424,9 +421,7 @@ func (p *Resolver) resolveCatch(c *ast.CatchClause) {
p.define(*c.Param)
}
- p.resolveStmts(c.Body)
-
- p.resolveExpr(c.Value)
+ p.resolveStmts(c.Body.Stmts)
}
func (p *Resolver) VisitAssignExpr(expr *ast.AssignExpr) (value.Value, error) {
@@ -459,6 +454,10 @@ func (p *Resolver) VisitCallExpr(callExpr *ast.CallExpr) (value.Value, error) {
if prop, ok := callExpr.Callee.(*ast.IndexExpr); ok && isMethodCall(prop) {
p.checkMutation(callExpr, prop)
+
+ if i := slices.IndexFunc(callExpr.Args, ast.IsSpread); i >= 0 {
+ p.error(callExpr.Args[i].(*ast.SpreadExpr).Token, "Cannot spread arguments into a method call.")
+ }
}
p.inout(callExpr)
diff --git a/pkg/rune/vm_slow.go b/pkg/rune/vm_slow.go
index 484b6027..93cd00c8 100644
--- a/pkg/rune/vm_slow.go
+++ b/pkg/rune/vm_slow.go
@@ -118,7 +118,7 @@ func (p *Interpreter) slow(in Instr) error {
for i, k := range keys {
if !obj.Set(k, regs[in.b()+i]) {
- return functionProperty(tok, k)
+ return functionProperty(&f.keyToks[in.c()][i], k)
}
}
@@ -391,8 +391,8 @@ func (p *Interpreter) slow(in Instr) error {
// called directly gets what site passes on.
func (p *Interpreter) callAt(at, n int, tok *ast.Token, site callSite) error {
fn := p.stack[at]
- if fn.Kind() == value.Type {
- v, err := convert(tok, fn.TypeShape(), p.stack[at+1:at+1+n])
+ if isEnum(fn) {
+ v, err := variant(tok, fn.TypeShape(), p.stack[at+1:at+1+n])
if err == nil {
p.stack[at] = v
}
@@ -407,22 +407,6 @@ func (p *Interpreter) callAt(at, n int, tok *ast.Token, site callSite) error {
switch f := fn.Fn().(type) {
case *Closure:
return p.enter(f, at+1, n, tok, site)
- case *BoundMethod:
- if !f.fn.proto.accepts(n + 1) {
- return argumentError(f.fn.proto, n+1, 1, tok)
- }
-
- p.grow(at + 2 + n)
- copy(p.stack[at+2:], p.stack[at+1:at+1+n])
- p.stack[at], p.stack[at+1] = value.NewFunction(f.fn), f.recv
-
- return p.enter(f.fn, at+1, n+1, tok, callSite{})
- case *BoundNative:
- p.grow(at + 2 + n)
- copy(p.stack[at+2:], p.stack[at+1:at+1+n])
- p.stack[at+1] = f.recv
-
- return p.callNativeMethod(at, n, f.fn, tok)
}
v, err := p.host.Call(fn.Fn().(*stdlib.Native), p.stack[at+1:at+1+n], tok)
@@ -526,13 +510,16 @@ func spreadArgs(src value.Value) ([]value.Value, bool) {
// spreadFields copies src, a struct of type shape, into the field
// registers fields.
func spreadFields(tok *ast.Token, shape *value.Shape, fields []value.Value, src value.Value) error {
- if src.Kind() != value.Struct || src.Shape() != shape {
+ switch {
+ case src.Kind() == value.Object:
+ return stdlib.AssignFields(tok, shape, fields, src.Obj())
+ case src.Kind() == value.Struct && src.Shape() == shape:
+ value.ShareAll(src.Fields())
+ copy(fields, src.Fields())
+ default:
return spreadError(tok, src, shape.Name)
}
- value.ShareAll(src.Fields())
- copy(fields, src.Fields())
-
return nil
}
diff --git a/pkg/stdlib/convert.go b/pkg/stdlib/convert.go
index 5665079a..add7f791 100644
--- a/pkg/stdlib/convert.go
+++ b/pkg/stdlib/convert.go
@@ -10,13 +10,9 @@ import (
"strings"
)
-// Convert is Shape(v): v itself if already of that shape, or a struct
-// built from an object holding every required field and no other.
+// Convert is v as a struct of shape: v itself if already one, or a
+// struct built from an object holding every required field and no other.
func Convert(token *ast.Token, shape *value.Shape, v value.Value) (value.Value, error) {
- if shape.Enum {
- return variantOf(token, shape, v)
- }
-
switch v.Kind() {
case value.Struct:
if v.Shape() == shape {
@@ -30,9 +26,9 @@ func Convert(token *ast.Token, shape *value.Shape, v value.Value) (value.Value,
"Cannot convert %s to %s.", helpers.TypeName(v), shape.Name))
}
-// variantOf is Enum(v): v itself if a variant of it, or the variant at
+// Variant is Enum(v): v itself if a variant of it, or the variant at
// ordinal v, or named v.
-func variantOf(token *ast.Token, shape *value.Shape, v value.Value) (value.Value, error) {
+func Variant(token *ast.Token, shape *value.Shape, v value.Value) (value.Value, error) {
switch {
case shape.Has(v):
return v, nil
@@ -60,22 +56,30 @@ func NotOrdinal(enum *value.Shape) string {
return enum.Name + " has variants with fields; values(), " + enum.Name + "(n) and int() are for enums without."
}
+// AssignFields sets the fields of shape that obj has keys for; a key
+// that is no field is a KeyError.
+func AssignFields(token *ast.Token, shape *value.Shape, fields []value.Value, obj *value.Obj) error {
+ if extra, ok := shape.Assign(fields, obj); !ok {
+ return errors.NewRuntimeError(errors.KeyError, *token, errors.NoField(shape.Name, extra))
+ }
+
+ return nil
+}
+
func structOf(token *ast.Token, shape *value.Shape, obj *value.Obj) (value.Value, error) {
v, fields := value.NewStruct(shape)
for i := range fields {
fields[i] = value.UndefinedValue
}
- extra, known := shape.Assign(fields, obj)
+ if err := AssignFields(token, shape, fields, obj); err != nil {
+ return value.NilValue, err
+ }
if missing, ok := shape.Fill(fields); !ok {
return value.NilValue, errors.NewRuntimeError(errors.KeyError, *token, errors.MissingField(shape.Name, missing))
}
- if !known {
- return value.NilValue, errors.NewRuntimeError(errors.KeyError, *token, errors.NoField(shape.Name, extra))
- }
-
return v, nil
}
@@ -114,7 +118,7 @@ var conversionNatives = []*Native{
return truncate(c, v)
}
- return intLiteral(c)
+ return c.typeError(0, "a number")
}},
}
@@ -142,20 +146,6 @@ func truncate(c *call, v value.Value) value.Value {
return value.NewInt(n)
}
-// intLiteral is int(s): the integer literal s holds, as number reads it.
-func intLiteral(c *call) value.Value {
- s := c.str(0)
- if !c.ok() {
- return value.NilValue
- }
-
- if n, ok := helpers.ParseNumber(strings.TrimSpace(s)); ok && n.IsInt() {
- return n
- }
-
- return c.fail(errors.ValueError, "cannot parse %s as an integer.", helpers.Quoted(c.args[0]))
-}
-
// intInBase is int(s, base): the digits of s in base.
func intInBase(c *call) value.Value {
s, base := c.str(0), c.int(1)
diff --git a/pkg/stdlib/format.go b/pkg/stdlib/format.go
index 3d358861..8e1668e3 100644
--- a/pkg/stdlib/format.go
+++ b/pkg/stdlib/format.go
@@ -13,9 +13,9 @@ import (
// format is printf: %[flags][width][.precision]verb, flags from "-+ 0#".
// A width or precision of * takes the next argument, an integer; a
-// negative width pads on the right. %s shows a value as print does,
-// %q as it shows inside an array; %d %x %X %o %b take integers, %f %e %E
-// %g %G numbers; %% is a percent sign.
+// negative width pads on the right. %q shows a value as it shows inside
+// an array; %d %x %X %o %b take integers, %f %e %E %g %G numbers; %% is
+// a percent sign.
func format(c *call, f string, args []value.Value) value.Value {
b := c.host.buf[:0]
p := printf{c: c, args: args}
@@ -65,11 +65,7 @@ func format(c *call, f string, args []value.Value) value.Value {
// A bare directive needs no fmt.
if len(p.text) == 2 {
- switch v := c.args[j]; {
- case d.verb == 's':
- b = helpers.AppendValue(b, v)
- continue
- case d.verb == 'd' && v.IsInt():
+ if v := c.args[j]; d.verb == 'd' && v.IsInt() {
b = strconv.AppendInt(b, v.Int(), 10)
continue
}
@@ -239,15 +235,6 @@ func formatArg(c *call, verb byte, i int) (any, bool) {
v, h := c.args[i], c.host
switch verb {
- case 's':
- if v.IsString() {
- h.fmtStr = v.Str()
- } else {
- h.tmp = helpers.AppendValue(h.tmp[:0], v)
- h.fmtStr = unsafe.String(unsafe.SliceData(h.tmp), len(h.tmp))
- }
-
- return box(strType, unsafe.Pointer(&h.fmtStr)), true
case 'q':
h.fmtStr = helpers.Quoted(v)
return box(strType, unsafe.Pointer(&h.fmtStr)), true
diff --git a/pkg/stdlib/http.go b/pkg/stdlib/http.go
index 35584223..fc310b5d 100644
--- a/pkg/stdlib/http.go
+++ b/pkg/stdlib/http.go
@@ -34,25 +34,6 @@ var HttpResponse = value.NewShape("HttpResponse", []value.Field{
})
var httpNatives = []*Native{
- {"http.get", 1, 1, func(c *call) value.Value {
- url := c.str(0)
- if !c.ok() {
- return value.NilValue
- }
-
- res, body := c.fetch(http.MethodGet, url, defaultHTTPOpts())
- if !c.ok() {
- return value.NilValue
- }
-
- defer body.Close()
-
- if res.StatusCode != http.StatusOK {
- return c.fail(errors.IOError, "could not fetch %s: status code %d", url, res.StatusCode)
- }
-
- return c.readBody(url, body)
- }},
{"http.request", 2, 3, func(c *call) value.Value {
method, url, opts := c.str(0), c.str(1), c.httpOptions(2)
if !c.ok() {
diff --git a/pkg/stdlib/native.go b/pkg/stdlib/native.go
index f3e15a24..0c3d1398 100644
--- a/pkg/stdlib/native.go
+++ b/pkg/stdlib/native.go
@@ -40,9 +40,9 @@ type Host struct {
// regexes caches the patterns compiled so far.
regexes map[string]*regexp.Regexp
streams map[*Stream]struct{}
- // buf and tmp are scratch for print and format, which box their
- // arguments for fmt in the fields after.
- buf, tmp []byte
+ // buf is scratch for print and format, which box their arguments
+ // for fmt in the fields after.
+ buf []byte
fmtInt int64
fmtFloat float64
fmtStr string
diff --git a/pkg/stdlib/sequences.go b/pkg/stdlib/sequences.go
index 6ceae694..cb8e6b30 100644
--- a/pkg/stdlib/sequences.go
+++ b/pkg/stdlib/sequences.go
@@ -3,7 +3,6 @@ package stdlib
import (
"math"
"rune/pkg/errors"
- "rune/pkg/helpers"
"rune/pkg/value"
"slices"
"strings"
@@ -25,9 +24,6 @@ var arraySequenceMethods = []*Native{
return sharedArray(slices.Repeat(items, n))
}},
- {"array.indexOf", 2, 2, func(c *call) value.Value {
- return found(arrayIndex(c))
- }},
}
// String positions count characters.
@@ -41,8 +37,3 @@ var stringSequenceMethods = []*Native{
return value.NilValue
}},
}
-
-// arrayIndex finds args[1] in the array args[0]; -1 if absent.
-func arrayIndex(c *call) int {
- return slices.IndexFunc(c.arr(0), func(x value.Value) bool { return helpers.IsEqual(x, c.args[1]) })
-}
diff --git a/test/catch/construct.rn b/test/catch/construct.rn
index 80976227..4932879b 100644
--- a/test/catch/construct.rn
+++ b/test/catch/construct.rn
@@ -13,4 +13,4 @@ try {
struct Note { message }
let n = Note { message: "hi" };
print(n.message); // expect: hi
-print(ValueError({ message: "m", line: 3 }).line); // expect: 3
+print(ValueError { ...{ message: "m", line: 3 } }.line); // expect: 3
diff --git a/test/default/basic.rn b/test/default/basic.rn
index 2b61c975..a65c88f7 100644
--- a/test/default/basic.rn
+++ b/test/default/basic.rn
@@ -53,9 +53,6 @@ impl P {
let p = P { x: 1 };
print(p.add()); // expect: 2
print(p.add(5)); // expect: 6
-print([p].map(P.add)); // expect: [2]
-let bound = p.add;
-print(bound()); // expect: 2
print(P.make()); // expect: P {x: 0}
fun main(args = ["unused"]) { print(args); } // expect: []
diff --git a/test/defer/return.rn b/test/defer/return.rn
index bd2f22fc..f0fa87d6 100644
--- a/test/defer/return.rn
+++ b/test/defer/return.rn
@@ -16,7 +16,7 @@ print(value()); // expect: 1
fun early() {
defer print("cleanup");
- let v = try int("x") catch => return 0;
+ let v = try { int("x") } catch { return 0 };
return v;
}
print(early());
diff --git a/test/destructure/array.rn b/test/destructure/array.rn
index 9430a444..6709e4f6 100644
--- a/test/destructure/array.rn
+++ b/test/destructure/array.rn
@@ -12,7 +12,7 @@ print(t); // expect: [2, 3]
let [...all] = [];
print(all); // expect: []
-let mut [p, q] = [1, 2];
+let [mut p, q] = [1, 2];
p += q;
print(p); // expect: 3
diff --git a/test/destructure/defaults.rn b/test/destructure/defaults.rn
index 9e7a6c2a..be00a513 100644
--- a/test/destructure/defaults.rn
+++ b/test/destructure/defaults.rn
@@ -14,7 +14,7 @@ fun page({ title, root = "." }, [w = 80, h = w / 2] = []) {
print(page({ title: "t" })); // expect: t . 80 40
print(page({ title: "t", root: ".." }, [10])); // expect: t .. 10 5
-let mut [p = 0, ...rest] = [];
+let [mut p = 0, ...rest] = [];
print([p, rest]); // expect: [0, []]
let [q, r = 5, ...more] = [1, 2, 3, 4];
diff --git a/test/destructure/let_mut.rn b/test/destructure/let_mut.rn
index db7cd3e8..a7561527 100644
--- a/test/destructure/let_mut.rn
+++ b/test/destructure/let_mut.rn
@@ -1,4 +1,4 @@
-let mut { x, y: why } = { x: 1, y: 2 };
+let { mut x, y: mut why } = { x: 1, y: 2 };
x += 10;
why += 20;
print(x); // expect: 11
diff --git a/test/destructure/let_mut_pattern.rn b/test/destructure/let_mut_pattern.rn
new file mode 100644
index 00000000..316bedf3
--- /dev/null
+++ b/test/destructure/let_mut_pattern.rn
@@ -0,0 +1 @@
+let mut { a } = { a: 1 }; // Error at '{': Expect variable name.
diff --git a/test/destructure/let_mut_pattern.stderr b/test/destructure/let_mut_pattern.stderr
new file mode 100644
index 00000000..8b680d24
--- /dev/null
+++ b/test/destructure/let_mut_pattern.stderr
@@ -0,0 +1,5 @@
+error: Expect variable name.
+ --> let_mut_pattern.rn:1:9
+ |
+1 | let mut { a } = { a: 1 }; // Error at '{': Expect variable name.
+ | ^
diff --git a/test/destructure/nested.rn b/test/destructure/nested.rn
index 41ea4113..d7a3f6a4 100644
--- a/test/destructure/nested.rn
+++ b/test/destructure/nested.rn
@@ -7,7 +7,7 @@ print(size); // expect: 1
let [x, [y, z = 9], { w }] = [1, [2], { w: 4 }];
print(x + y + z + w); // expect: 16
-let mut { pos: [px, py] } = { pos: [1, 2] };
+let { pos: [mut px, py] } = { pos: [1, 2] };
px += 10;
print(px, py); // expect: 11 2
diff --git a/test/destructure/object_rest.rn b/test/destructure/object_rest.rn
index 799b1e18..37b50221 100644
--- a/test/destructure/object_rest.rn
+++ b/test/destructure/object_rest.rn
@@ -24,7 +24,7 @@ print(r); // expect: {w: 2, e: 3}
let src = { s: 1 };
let { ...dup } = src;
-let mut { ...own } = src;
+let { ...mut own } = src;
own.s = 2;
print(src.s); // expect: 1
diff --git a/test/enum/fields.rn b/test/enum/fields.rn
index 3de97bc4..fcc1492c 100644
--- a/test/enum/fields.rn
+++ b/test/enum/fields.rn
@@ -33,7 +33,7 @@ print(Expr.Add is struct); // expect: true
print(Expr.Add { ...e, right: Expr.Zero }.eval()); // expect: 1
print(e == Expr.Add { left: Expr.num(1), right: Expr.Neg { expr: Expr.num(3) } }); // expect: true
print(Expr.num(1) == Expr.Neg { expr: Expr.num(1) }); // expect: false
-print(Expr.Num({ value: 5 })); // expect: Expr.Num {value: 5}
+print(Expr.Num { ...{ value: 5 } }); // expect: Expr.Num {value: 5}
print(Expr(e) == e); // expect: true
let { left, right } = e;
diff --git a/test/enum/methods.rn b/test/enum/methods.rn
index c5d3e270..cbc142e1 100644
--- a/test/enum/methods.rn
+++ b/test/enum/methods.rn
@@ -7,4 +7,4 @@ impl Side {
print(Side.White.other()); // expect: Side.Black
print(Side.parse("b").other()); // expect: Side.White
-print(Side.values().map(Side.other)); // expect: [Side.Black, Side.White]
+print(Side.values().map(s => s.other())); // expect: [Side.Black, Side.White]
diff --git a/test/fs/errors.rn b/test/fs/errors.rn
index c1dd573e..ab559e6c 100644
--- a/test/fs/errors.rn
+++ b/test/fs/errors.rn
@@ -19,6 +19,6 @@ try { fs.rename(missing, fs.join(dir, "g")); } catch e is IOError { print([e.cod
try { fs.removeAll(""); } catch e is ValueError { print(e.message); } // expect: fs.removeAll() got an empty path.
try { fs.write(fs.join(dir, "h"), 1); } catch e is TypeError { print(e.message); } // expect: fs.write() expects a string, bytes or a buffer as argument 2, got number.
-try { http.get("http://127.0.0.1:1"); } catch e is IOError { print(e.code); } // expect: nil
+try { http.request("GET", "http://127.0.0.1:1"); } catch e is IOError { print(e.code); } // expect: nil
fs.removeAll(dir);
diff --git a/test/impl/bound.rn b/test/impl/bound.rn
index 9ff73ea4..2f7e85bf 100644
--- a/test/impl/bound.rn
+++ b/test/impl/bound.rn
@@ -5,11 +5,10 @@ impl Point {
}
let p = Point { x: 10 };
-let f = p.plus;
-print(f(1)); // expect: 11
-print([1, 2].map(p.plus)); // expect: [11, 12]
-print(f is function); // expect: true
print(p?.plus(2)); // expect: 12
let q = nil;
print(q?.plus(2)); // expect: nil
-print(p.plus(...[5])); // expect: 15
+try { let f = p.plus; } catch e is TypeError { print(e.message); } // expect: Cannot take method 'plus' of Point as a value.
+try { let f = Point.plus; } catch e is TypeError { print(e.message); } // expect: 'plus' is a method of Point values; call it on one.
+try { let f = "a".upper; } catch e is TypeError { print(e.message); } // expect: Cannot take method 'upper' of string as a value.
+Point.plus(p, 1); // expect runtime error: [line: 14] TypeError: 'plus' is a method of Point values; call it on one.
diff --git a/test/impl/bound.stderr b/test/impl/bound.stderr
new file mode 100644
index 00000000..2f9f47d1
--- /dev/null
+++ b/test/impl/bound.stderr
@@ -0,0 +1,6 @@
+TypeError: 'plus' is a method of Point values; call it on one.
+ --> bound.rn:14:7
+ |
+13 | try { let f = "a".upper; } catch e is TypeError { print(e.message); } // expect: Cannot take method 'upper' of string as a value.
+14 | Point.plus(p, 1); // expect runtime error: [line: 14] TypeError: 'plus' is a method of Point values; call it on one.
+ | ^^^^
diff --git a/test/impl/bound_mut.rn b/test/impl/bound_mut.rn
index 847018a4..0e5e6d5e 100644
--- a/test/impl/bound_mut.rn
+++ b/test/impl/bound_mut.rn
@@ -5,4 +5,4 @@ impl Counter {
}
let mut c = Counter {};
-let f = c.incr; // expect runtime error: [line: 8] TypeError: Cannot take mutating method 'incr' of Counter as a value.
+let f = c.incr; // expect runtime error: [line: 8] TypeError: Cannot take method 'incr' of Counter as a value.
diff --git a/test/impl/bound_mut.stderr b/test/impl/bound_mut.stderr
index 66d504bb..c16adb6f 100644
--- a/test/impl/bound_mut.stderr
+++ b/test/impl/bound_mut.stderr
@@ -1,6 +1,6 @@
-TypeError: Cannot take mutating method 'incr' of Counter as a value.
+TypeError: Cannot take method 'incr' of Counter as a value.
--> bound_mut.rn:8:11
|
7 | let mut c = Counter {};
-8 | let f = c.incr; // expect runtime error: [line: 8] TypeError: Cannot take mutating method 'incr' of Counter as a value.
+8 | let f = c.incr; // expect runtime error: [line: 8] TypeError: Cannot take method 'incr' of Counter as a value.
| ^^^^
diff --git a/test/impl/builtin_types.rn b/test/impl/builtin_types.rn
index 065f1a1c..eae60b7e 100644
--- a/test/impl/builtin_types.rn
+++ b/test/impl/builtin_types.rn
@@ -29,5 +29,4 @@ print(n.double()); // expect: 8
print({ a: 1, b: 2 }.size()); // expect: 2
print(true.flip()); // expect: false
print((x => x + 3).twice(1)); // expect: 7
-let s = "a".shout;
-print(s()); // expect: A!
+print("a".shout()); // expect: A!
diff --git a/test/impl/mut_self_in_place.rn b/test/impl/mut_self_in_place.rn
index a12bfd29..a4e8b58e 100644
--- a/test/impl/mut_self_in_place.rn
+++ b/test/impl/mut_self_in_place.rn
@@ -9,7 +9,6 @@ impl P {
fun twice(mut self) { self.bump(); self.bump(); self.x *= 10; }
fun keep(mut self) { self.x = 1; kept.push(self); self.x = 2; }
fun alias(mut self) { let before = self; self.x = 5; return before.x; }
- fun bound(mut self) { let f = self.get; self.x = 7; return f(); }
fun get(self) { return self.x; }
fun leak(self) { kept.push(self); }
fun viaLeak(mut self) { self.x = 3; self.leak(); self.x = 4; }
@@ -30,7 +29,6 @@ p.keep();
print([kept[0].x, p.x]); // expect: [1, 2]
print([p.alias(), p.x]); // expect: [2, 5]
-print([p.bound(), p.x]); // expect: [5, 7]
p.viaLeak();
print([kept[1].x, p.x]); // expect: [3, 4]
diff --git a/test/impl/mut_self_local.rn b/test/impl/mut_self_local.rn
index 4653819c..bec3613b 100644
--- a/test/impl/mut_self_local.rn
+++ b/test/impl/mut_self_local.rn
@@ -62,13 +62,6 @@ fun captured() {
}
print(captured()); // expect: 3
-fun bound() {
- let mut p = P { x: 1 };
- let g = p.get;
- p.setX(4);
- return [g(), p.x];
-}
-print(bound()); // expect: [1, 4]
fun nested() {
struct_like();
diff --git a/test/impl/mut_self_temporary.rn b/test/impl/mut_self_temporary.rn
index e0a5eb0e..6389f5d5 100644
--- a/test/impl/mut_self_temporary.rn
+++ b/test/impl/mut_self_temporary.rn
@@ -8,5 +8,5 @@ impl Counter {
fun make() { return Counter {}; }
Counter {}.incr(); // Error at 'incr': Cannot call mutating method 'incr' of Counter: the receiver is not a mutable variable, element or property.
-Counter({ n: 1 }).get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
+Counter { n: 1 }.get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
make().incr(); // Error at 'incr': Cannot call mutating method 'incr': the receiver is not a mutable variable, element or property.
diff --git a/test/impl/mut_self_temporary.stderr b/test/impl/mut_self_temporary.stderr
index e7a450a8..56599479 100644
--- a/test/impl/mut_self_temporary.stderr
+++ b/test/impl/mut_self_temporary.stderr
@@ -5,15 +5,15 @@ error: Cannot call mutating method 'incr' of Counter: the receiver is not a muta
| ^^^^
error: Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
- --> mut_self_temporary.rn:11:19
+ --> mut_self_temporary.rn:11:18
|
10 | Counter {}.incr(); // Error at 'incr': Cannot call mutating method 'incr' of Counter: the receiver is not a mutable variable, element or property.
-11 | Counter({ n: 1 }).get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
- | ^^^
+11 | Counter { n: 1 }.get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
+ | ^^^
error: Cannot call mutating method 'incr': the receiver is not a mutable variable, element or property.
--> mut_self_temporary.rn:12:8
|
-11 | Counter({ n: 1 }).get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
+11 | Counter { n: 1 }.get(); // Error at 'get': Cannot call mutating method 'get' of Counter: the receiver is not a mutable variable, element or property.
12 | make().incr(); // Error at 'incr': Cannot call mutating method 'incr': the receiver is not a mutable variable, element or property.
| ^^^^
diff --git a/test/impl/override_builtin.rn b/test/impl/override_builtin.rn
index 40244b6a..20874033 100644
--- a/test/impl/override_builtin.rn
+++ b/test/impl/override_builtin.rn
@@ -7,7 +7,5 @@ impl map {
}
print([1, 2].map(x => x * 2)); // expect: mine
-let m = [3].map;
-print(m(x => x)); // expect: mine
print(map().get("a")); // expect: own a
print([3, 1, 2].sort()); // expect: nil
diff --git a/test/impl/spread_args.rn b/test/impl/spread_args.rn
new file mode 100644
index 00000000..d53d72f3
--- /dev/null
+++ b/test/impl/spread_args.rn
@@ -0,0 +1,5 @@
+struct P { x }
+impl P { fun plus(self, a) { return self.x + a; } }
+let p = P { x: 1 };
+p.plus(...[2]); // Error at '...': Cannot spread arguments into a method call.
+"a-b".split(...["-"]); // Error at '...': Cannot spread arguments into a method call.
diff --git a/test/impl/spread_args.stderr b/test/impl/spread_args.stderr
new file mode 100644
index 00000000..a3510c88
--- /dev/null
+++ b/test/impl/spread_args.stderr
@@ -0,0 +1,13 @@
+error: Cannot spread arguments into a method call.
+ --> spread_args.rn:4:8
+ |
+3 | let p = P { x: 1 };
+4 | p.plus(...[2]); // Error at '...': Cannot spread arguments into a method call.
+ | ^^^
+
+error: Cannot spread arguments into a method call.
+ --> spread_args.rn:5:13
+ |
+4 | p.plus(...[2]); // Error at '...': Cannot spread arguments into a method call.
+5 | "a-b".split(...["-"]); // Error at '...': Cannot spread arguments into a method call.
+ | ^^^
diff --git a/test/impl/static.rn b/test/impl/static.rn
index f4405008..381dec7b 100644
--- a/test/impl/static.rn
+++ b/test/impl/static.rn
@@ -8,7 +8,6 @@ impl Point {
print(Point.origin()); // expect: Point {x: 0, y: 0}
print(Point.of(1, 2).len()); // expect: 3
-print(Point.len(Point.of(2, 3))); // expect: 5
-let f = Point.len;
-print([Point.of(1, 1), Point.of(2, 2)].map(Point.len)); // expect: [2, 4]
-print(f); // expect:
+let f = Point.of;
+print(f(2, 3).len()); // expect: 5
+print(f); // expect:
diff --git a/test/import/enum_fields.rn b/test/import/enum_fields.rn
index 6be058d2..d9a03e37 100644
--- a/test/import/enum_fields.rn
+++ b/test/import/enum_fields.rn
@@ -16,4 +16,4 @@ for x in xs {
print(xs[1] is s.Shape.Rect); // expect: true
print(xs[1] is s.Shape); // expect: true
-print(s.Shape.Rect({ w: 2, h: 2 })); // expect: Shape.Rect {w: 2, h: 2}
+print(s.Shape.Rect { ...{ w: 2, h: 2 } }); // expect: Shape.Rect {w: 2, h: 2}
diff --git a/test/import/structs.rn b/test/import/structs.rn
index 3199c221..984e0b8c 100644
--- a/test/import/structs.rn
+++ b/test/import/structs.rn
@@ -3,7 +3,7 @@ import _lib.math;
let v = math.Vec { x: 1 };
print(v); // expect: Vec {x: 1, y: 0}
print(v is math.Vec); // expect: true
-print(math.Vec({x: 2, y: 3})); // expect: Vec {x: 2, y: 3}
+print(math.Vec { ...{x: 2, y: 3} }); // expect: Vec {x: 2, y: 3}
fun describe(p) {
return match p {
diff --git a/test/map/basics.rn b/test/map/basics.rn
index 5cbc134a..62007540 100644
--- a/test/map/basics.rn
+++ b/test/map/basics.rn
@@ -45,6 +45,4 @@ print(map([[1, 2]]) == map([[1, 3]])); // expect: false
print(map() == {}); // expect: false
print(json.stringify(map([["b", 1], ["a", [2]]]))); // expect: {"b":1,"a":[2]}
-let keys = o.keys;
-print(keys()); // expect: ["a", "c", "b"]
print([map([[1, "x"]])].map(m => m[1])); // expect: ["x"]
diff --git a/test/mutability/map_set_in_place.rn b/test/mutability/map_set_in_place.rn
index 149724b6..2521b4a1 100644
--- a/test/mutability/map_set_in_place.rn
+++ b/test/mutability/map_set_in_place.rn
@@ -8,7 +8,7 @@ mm["b"] = 2;
print(m); // expect: map {"a": 1}
let a = [2, 1];
-try { let f = a.push; } catch e is TypeError { print(e.message); } // expect: Cannot take in-place method 'push' of array as a value.
+try { let f = a.push; } catch e is TypeError { print(e.message); } // expect: Cannot take method 'push' of array as a value.
// A temporary has no variable to protect.
print([3, 1, 2].sort()); // expect: nil
diff --git a/test/objects/function_value_runtime.rn b/test/objects/function_value_runtime.rn
new file mode 100644
index 00000000..72e27bb8
--- /dev/null
+++ b/test/objects/function_value_runtime.rn
@@ -0,0 +1,3 @@
+let fs = [() => 1];
+let o = { a: 1,
+ b: fs[0] }; // expect runtime error: [line: 3] TypeError: Property 'b' of an object cannot hold a function.
diff --git a/test/objects/function_value_runtime.stderr b/test/objects/function_value_runtime.stderr
new file mode 100644
index 00000000..c855f367
--- /dev/null
+++ b/test/objects/function_value_runtime.stderr
@@ -0,0 +1,8 @@
+TypeError: Property 'b' of an object cannot hold a function.
+ --> function_value_runtime.rn:3:3
+ |
+2 | let o = { a: 1,
+3 | b: fs[0] }; // expect runtime error: [line: 3] TypeError: Property 'b' of an object cannot hold a function.
+ | ^
+ |
+ = hint: objects hold data; give the behavior to a struct with an impl
diff --git a/test/spread/call.rn b/test/spread/call.rn
index fb3286fe..eaa11d3c 100644
--- a/test/spread/call.rn
+++ b/test/spread/call.rn
@@ -7,6 +7,5 @@ print(add(...xs, 3)); // expect: 6
print(add(0, ...xs)); // expect: 3
print(add(...[1, 2, 3])); // expect: 6
print(math.max(...xs, 0)); // expect: 2
-print(Point(...[{ x: 1, y: 2 }])); // expect: Point {x: 1, y: 2}
print([[1, 2, 3]].map(args => add(...args))); // expect: [6]
-add(...xs); // expect runtime error: [line: 12] ArgumentError: Expected 3 arguments but got 2.
+add(...xs); // expect runtime error: [line: 11] ArgumentError: Expected 3 arguments but got 2.
diff --git a/test/spread/call.stderr b/test/spread/call.stderr
index daa0ef00..74a4be1e 100644
--- a/test/spread/call.stderr
+++ b/test/spread/call.stderr
@@ -1,6 +1,6 @@
ArgumentError: Expected 3 arguments but got 2.
- --> call.rn:12:10
+ --> call.rn:11:10
|
-11 | print([[1, 2, 3]].map(args => add(...args))); // expect: [6]
-12 | add(...xs); // expect runtime error: [line: 12] ArgumentError: Expected 3 arguments but got 2.
+10 | print([[1, 2, 3]].map(args => add(...args))); // expect: [6]
+11 | add(...xs); // expect runtime error: [line: 11] ArgumentError: Expected 3 arguments but got 2.
| ^
diff --git a/test/stdlib/arrays.rn b/test/stdlib/arrays.rn
index 71a36b26..fdd9610a 100644
--- a/test/stdlib/arrays.rn
+++ b/test/stdlib/arrays.rn
@@ -12,7 +12,6 @@ print(xs); // expect: [2, 1, 3]
xs.reverse();
print(2 in xs); // expect: true
print([1] in [[1]]); // expect: true
-print(xs.indexOf(9)); // expect: nil
print(xs.sort()); // expect: nil
print(xs); // expect: [1, 2, 3]
xs.sort((a, b) => { return b - a; });
diff --git a/test/stdlib/callback_index.rn b/test/stdlib/callback_index.rn
index 3cbf3cbd..47baf3c1 100644
--- a/test/stdlib/callback_index.rn
+++ b/test/stdlib/callback_index.rn
@@ -8,7 +8,7 @@ print(xs.some((_, i) => i == 5)); // expect: false
print(xs.every((_, i) => i < 3)); // expect: true
// Only a function requiring two arguments gets the index.
-print(["10", "2"].map(int)); // expect: [10, 2]
+print([10.5, 2.9].map(int)); // expect: [10, 2]
print(xs.map((x, sep = "!") => x + sep)); // expect: ["a!", "b!", "c!"]
fun pair(x, i) { return [x, i]; }
@@ -18,5 +18,6 @@ struct Tag { k }
impl Tag {
fun at(self, x, i) { return "{self.k}{x}{i}"; }
}
-print(xs.map(Tag { k: "#" }.at)); // expect: ["#a0", "#b1", "#c2"]
+let tag = Tag { k: "#" };
+print(xs.map((x, i) => tag.at(x, i))); // expect: ["#a0", "#b1", "#c2"]
print([2, 3].map(math.pow)); // expect: [1, 3]
diff --git a/test/stdlib/conversions.rn b/test/stdlib/conversions.rn
index 01d0f73e..87b5618c 100644
--- a/test/stdlib/conversions.rn
+++ b/test/stdlib/conversions.rn
@@ -14,8 +14,6 @@ print(number(" -2.5e1 ")); // expect: -25
print(number("1E+2")); // expect: 100
print(number(7)); // expect: 7
-print(int("42")); // expect: 42
-print(int(" -17 ")); // expect: -17
print(int("ff", 16)); // expect: 255
print(int("101", 2)); // expect: 5
print(int(3.9)); // expect: 3
@@ -37,10 +35,9 @@ for s in ["abc", "inf", "0x", "", "-", ".5", "5.", "+1", "1e", "1e400", "1 2"] {
// expect: number() cannot parse "1 2" as a number.
try { number(nil); } catch e is TypeError { print(e.message); } // expect: number() expects a number or a string as argument 1, got nil.
-try { int("3.5"); } catch e is ValueError { print(e.message); } // expect: int() cannot parse "3.5" as an integer.
-try { int("1e3"); } catch e is ValueError { print(e.message); } // expect: int() cannot parse "1e3" as an integer.
+try { int("42"); } catch e is TypeError { print(e.message); } // expect: int() expects a number as argument 1, got string.
try { int("1__0", 10); } catch e is ValueError { print(e.message); } // expect: int() cannot parse "1__0" as an integer in base 10.
-print(int("1_000"), int(" -0x1F "), int("0b11"), int("f_f", 16), int("0755", 8)); // expect: 1000 -31 3 255 493
+print(int("f_f", 16), int("0755", 8)); // expect: 255 493
try { int("z", 37); } catch e is ValueError { print(e.message); } // expect: int() expects a base from 2 to 36, got 37.
try { int(10, 2); } catch e is TypeError { print(e.message); } // expect: int() expects a string as argument 1, got number.
try { int(math.INF); } catch e is ValueError { print(e.message); } // expect: int() cannot convert inf to an integer.
@@ -59,5 +56,5 @@ try { object([1]); } catch e is TypeError { print(e.message); } // exp
print([1, "a", nil].map(string)); // expect: ["1", "a", "nil"]
print(["hi"].map(bytes)); // expect: [b"hi"]
-print([{ name: "bob" }].map(User)); // expect: [User {name: "bob", role: "guest"}]
+print([{ name: "bob" }].map(o => User { ...o })); // expect: [User {name: "bob", role: "guest"}]
print(map(User { name: "ann" })); // expect: map {"name": "ann", "role": "guest"}
diff --git a/test/stdlib/strings_extra.rn b/test/stdlib/strings_extra.rn
index afa80fee..ac226c2d 100644
--- a/test/stdlib/strings_extra.rn
+++ b/test/stdlib/strings_extra.rn
@@ -5,14 +5,13 @@ print("7".padStart(3, "0")); // expect: 007
print("abc".padStart(8, "12")); // expect: 12121abc
print("é".padEnd(3) + "|"); // expect: é |
print("long".padEnd(2)); // expect: long
-print("%d + %d = %s".format(1, 2, 3)); // expect: 1 + 2 = 3
-print("[%5s][%-5s][%5d][%-4d]".format("ab", "é", 42, 7)); // expect: [ ab][é ][ 42][7 ]
+print("%d + %d = %d".format(1, 2, 3)); // expect: 1 + 2 = 3
+print("[%5d][%-4d]".format(42, 7)); // expect: [ 42][7 ]
print("%.2f %08.3f %e".format(3.14159, 2.5, 1500)); // expect: 3.14 0002.500 1.500000e+03
print("%x %X %o %b %+d".format(255, 255, 8, 5, 3)); // expect: ff FF 10 101 +3
-print("%s %s %q".format([1, "a"], nil, "hi")); // expect: [1, "a"] nil "hi"
-print("100%% %s".format(true)); // expect: 100% true
-print("%.2s".format("héllo")); // expect: hé
-print("[%*s][%-*s][%*s]".format(4, "ab", 4, "é", -4, "x")); // expect: [ ab][é ][x ]
+print("%q %q %q".format([1, "a"], nil, "hi")); // expect: [1, "a"] nil "hi"
+print("100%% %d".format(5)); // expect: 100% 5
+print("[%*d][%-*d][%*d]".format(4, 12, 4, 7, -4, 3)); // expect: [ 12][7 ][3 ]
print("[%.*f][%*.*f][%0*d]".format(2, 3.14159, 7, 1, 2.25, 5, 42)); // expect: [3.14][ 2.2][00042]
try { "ab".charCode(2); } catch e is IndexError { print(e.message); } // expect: string.charCode() index 2 out of bounds of 2 characters.
@@ -26,8 +25,9 @@ try { "%y".format(1); } catch e is ValueError { print(e.message); } // expect: s
try { "%v".format(1); } catch e is ValueError { print(e.message); } // expect: string.format() unknown verb '%v'.
try { "abc %5".format(); } catch e is ValueError { print(e.message); } // expect: string.format() incomplete directive '%5' at 4.
try { "%99999d".format(1); } catch e is ValueError { print(e.message); } // expect: string.format() bad directive '%99999d' at 0.
-try { "%*s".format("4", "a"); } catch e is TypeError { print(e.message); } // expect: string.format() expects an integer as argument 1, got string.
-try { "%*s".format(10000, "a"); } catch e is ValueError { print(e.message); } // expect: string.format() '%*s' at 0 got 10000 for '*', out of range -9999 to 9999.
-try { "%*s".format(3); } catch e is ArgumentError { print(e.message); } // expect: string.format() '%*s' at 0 has no argument.
-try { "%1*s".format(3, "a"); } catch e is ValueError { print(e.message); } // expect: string.format() bad directive '%1*s' at 0.
+try { "%*d".format("4", 1); } catch e is TypeError { print(e.message); } // expect: string.format() expects an integer as argument 1, got string.
+try { "%*d".format(10000, 1); } catch e is ValueError { print(e.message); } // expect: string.format() '%*d' at 0 got 10000 for '*', out of range -9999 to 9999.
+try { "%*d".format(3); } catch e is ArgumentError { print(e.message); } // expect: string.format() '%*d' at 0 has no argument.
+try { "%1*d".format(3, 1); } catch e is ValueError { print(e.message); } // expect: string.format() bad directive '%1*d' at 0.
+try { "%s".format(1); } catch e is ValueError { print(e.message); } // expect: string.format() unknown verb '%s'.
print("[%8q][%-8q][%.3q][%10.4q][%*q][%-*.*q]".format("ab", "ab", "abcdef", [1, 2], 6, "x", 7, 2, "hello")); // expect: [ "ab"]["ab" ]["ab][ [1, ][ "x"]["h ]
diff --git a/test/struct/builtins.rn b/test/struct/builtins.rn
index 67eb2314..8dd6e3e3 100644
--- a/test/struct/builtins.rn
+++ b/test/struct/builtins.rn
@@ -20,4 +20,4 @@ print(o); // expect: {x: 1, y: 0}
o.x = 5;
print(p.x); // expect: 1
print({ ...p } == p); // expect: false
-print(Point({ ...p }) == p); // expect: true
+print(Point { ...{ ...p } } == p); // expect: true
diff --git a/test/struct/call.rn b/test/struct/call.rn
new file mode 100644
index 00000000..bec2b477
--- /dev/null
+++ b/test/struct/call.rn
@@ -0,0 +1,3 @@
+struct Point { x }
+
+print(Point({ x: 1 })); // expect runtime error: [line: 3] TypeError: Can only call functions.
diff --git a/test/struct/call.stderr b/test/struct/call.stderr
new file mode 100644
index 00000000..d6bd30b3
--- /dev/null
+++ b/test/struct/call.stderr
@@ -0,0 +1,5 @@
+TypeError: Can only call functions.
+ --> call.rn:3:21
+ |
+3 | print(Point({ x: 1 })); // expect runtime error: [line: 3] TypeError: Can only call functions.
+ | ^
diff --git a/test/struct/convert.rn b/test/struct/convert.rn
index d238a886..de10f2a1 100644
--- a/test/struct/convert.rn
+++ b/test/struct/convert.rn
@@ -1,18 +1,16 @@
struct Point { x, y = 0 }
struct Box { item, tag = "box" }
-print(Point({x: 1})); // expect: Point {x: 1, y: 0}
-print(Point({"y": 2, "x": 1})); // expect: Point {x: 1, y: 2}
-
-let p = Point { x: 3 };
-print(Point(p) == p); // expect: true
-print(Point({x: [1, 2]}).x); // expect: [1, 2]
-print(Box({item: Point({x: 5})})); // expect: Box {item: Point {x: 5, y: 0}, tag: "box"}
-
-let mk = Point;
-print(mk({x: 7}) is Point); // expect: true
+print(Point { ...{x: 1} }); // expect: Point {x: 1, y: 0}
+print(Point { ...{"y": 2, "x": 1} }); // expect: Point {x: 1, y: 2}
+print(Point { ...{x: [1, 2]} }.x); // expect: [1, 2]
+print(Box { ...{item: Point { ...{x: 5} }} }); // expect: Box {item: Point {x: 5, y: 0}, tag: "box"}
+print(Point { ...{x: 1, y: 2}, y: 3 }); // expect: Point {x: 1, y: 3}
+print(Point { y: 3, ...{x: 1, y: 2} }); // expect: Point {x: 1, y: 2}
let mut o = {x: 1};
-let q = Point(o);
+let q = Point { ...o };
o.x = 2;
print(q.x); // expect: 1
+
+print(Point { x: 1 } == Point { ...{ x: 1 } }); // expect: true
diff --git a/test/struct/convert_arity.rn b/test/struct/convert_arity.rn
deleted file mode 100644
index 09f7c9b9..00000000
--- a/test/struct/convert_arity.rn
+++ /dev/null
@@ -1,3 +0,0 @@
-struct Point { x }
-
-print(Point()); // expect runtime error: [line: 3] ArgumentError: Point() expects 1 argument, got 0.
diff --git a/test/struct/convert_arity.stderr b/test/struct/convert_arity.stderr
deleted file mode 100644
index 2f7ccd91..00000000
--- a/test/struct/convert_arity.stderr
+++ /dev/null
@@ -1,5 +0,0 @@
-ArgumentError: Point() expects 1 argument, got 0.
- --> convert_arity.rn:3:13
- |
-3 | print(Point()); // expect runtime error: [line: 3] ArgumentError: Point() expects 1 argument, got 0.
- | ^
diff --git a/test/struct/convert_extra_key.rn b/test/struct/convert_extra_key.rn
index 2d98f555..c1d5e37b 100644
--- a/test/struct/convert_extra_key.rn
+++ b/test/struct/convert_extra_key.rn
@@ -1,3 +1,3 @@
struct Point { x, y = 0 }
-print(Point({x: 1, z: 2, w: 3})); // expect runtime error: [line: 3] KeyError: Point has no field 'z'.
+print(Point { ...{x: 1, z: 2, w: 3} }); // expect runtime error: [line: 3] KeyError: Point has no field 'z'.
diff --git a/test/struct/convert_extra_key.stderr b/test/struct/convert_extra_key.stderr
index e2879b5b..3a44f7b5 100644
--- a/test/struct/convert_extra_key.stderr
+++ b/test/struct/convert_extra_key.stderr
@@ -1,5 +1,5 @@
KeyError: Point has no field 'z'.
- --> convert_extra_key.rn:3:31
+ --> convert_extra_key.rn:3:15
|
-3 | print(Point({x: 1, z: 2, w: 3})); // expect runtime error: [line: 3] KeyError: Point has no field 'z'.
- | ^
+3 | print(Point { ...{x: 1, z: 2, w: 3} }); // expect runtime error: [line: 3] KeyError: Point has no field 'z'.
+ | ^^^
diff --git a/test/struct/convert_missing_field.rn b/test/struct/convert_missing_field.rn
index 98b5373e..960518b1 100644
--- a/test/struct/convert_missing_field.rn
+++ b/test/struct/convert_missing_field.rn
@@ -1,3 +1,3 @@
struct Point { x, y = 0 }
-print(Point({y: 1})); // expect runtime error: [line: 3] KeyError: Missing field 'x' of Point.
+print(Point { ...{y: 1} }); // expect runtime error: [line: 3] KeyError: Missing field 'x' of Point.
diff --git a/test/struct/convert_missing_field.stderr b/test/struct/convert_missing_field.stderr
index f7f656a7..85055700 100644
--- a/test/struct/convert_missing_field.stderr
+++ b/test/struct/convert_missing_field.stderr
@@ -1,5 +1,5 @@
KeyError: Missing field 'x' of Point.
- --> convert_missing_field.rn:3:19
+ --> convert_missing_field.rn:3:7
|
-3 | print(Point({y: 1})); // expect runtime error: [line: 3] KeyError: Missing field 'x' of Point.
- | ^
+3 | print(Point { ...{y: 1} }); // expect runtime error: [line: 3] KeyError: Missing field 'x' of Point.
+ | ^^^^^
diff --git a/test/struct/convert_not_object.rn b/test/struct/convert_not_object.rn
deleted file mode 100644
index f4c5eb7a..00000000
--- a/test/struct/convert_not_object.rn
+++ /dev/null
@@ -1,3 +0,0 @@
-struct Point { x }
-
-print(Point([1])); // expect runtime error: [line: 3] TypeError: Cannot convert array to Point.
diff --git a/test/struct/convert_not_object.stderr b/test/struct/convert_not_object.stderr
deleted file mode 100644
index d39266f8..00000000
--- a/test/struct/convert_not_object.stderr
+++ /dev/null
@@ -1,5 +0,0 @@
-TypeError: Cannot convert array to Point.
- --> convert_not_object.rn:3:16
- |
-3 | print(Point([1])); // expect runtime error: [line: 3] TypeError: Cannot convert array to Point.
- | ^
diff --git a/test/struct/convert_other_struct.rn b/test/struct/convert_other_struct.rn
index 6b0e6731..b297ec0e 100644
--- a/test/struct/convert_other_struct.rn
+++ b/test/struct/convert_other_struct.rn
@@ -1,4 +1,4 @@
struct Point { x, y }
struct Vec { x, y }
-print(Point(Vec { x: 1, y: 2 })); // expect runtime error: [line: 4] TypeError: Cannot convert Vec to Point.
+print(Point { ...Vec { x: 1, y: 2 } }); // expect runtime error: [line: 4] TypeError: Cannot spread Vec into Point.
diff --git a/test/struct/convert_other_struct.stderr b/test/struct/convert_other_struct.stderr
index f9a02d0a..afffbe80 100644
--- a/test/struct/convert_other_struct.stderr
+++ b/test/struct/convert_other_struct.stderr
@@ -1,5 +1,5 @@
-TypeError: Cannot convert Vec to Point.
- --> convert_other_struct.rn:4:31
+TypeError: Cannot spread Vec into Point.
+ --> convert_other_struct.rn:4:15
|
-4 | print(Point(Vec { x: 1, y: 2 })); // expect runtime error: [line: 4] TypeError: Cannot convert Vec to Point.
- | ^
+4 | print(Point { ...Vec { x: 1, y: 2 } }); // expect runtime error: [line: 4] TypeError: Cannot spread Vec into Point.
+ | ^^^
diff --git a/test/struct/default_own.rn b/test/struct/default_own.rn
index 4a1c125f..85186a57 100644
--- a/test/struct/default_own.rn
+++ b/test/struct/default_own.rn
@@ -15,7 +15,7 @@ a.fill();
print(a); // expect: Bag {xs: [1], o: {a: [1, 2]}, m: map {"k": 1}, s: set {3}, n: -1}
print(b); // expect: Bag {xs: [], o: {a: [1]}, m: map {}, s: set {}, n: -1}
-let c = Bag({ n: 2 });
+let c = Bag { n: 2 };
print(c); // expect: Bag {xs: [], o: {a: [1]}, m: map {}, s: set {}, n: 2}
fun make() { return Bag {}; }
diff --git a/test/struct/spread.rn b/test/struct/spread.rn
index 2128099b..620a531e 100644
--- a/test/struct/spread.rn
+++ b/test/struct/spread.rn
@@ -26,6 +26,7 @@ let log = (s, v) => { order.push(s); return v; };
Point { x: log("x", 1), ...log("spread", p), y: log("y", 2) };
print(order); // expect: ["x", "spread", "y"]
-try { Task { ...{ id: 1, text: "a" } }; } catch e is TypeError { print(e.message); } // expect: Cannot spread object into Task.
+print(Task { ...{ id: 1, text: "a" } }.text); // expect: a
+try { Task { ...{ id: 1, nope: 2 } }; } catch e is KeyError { print(e.message); } // expect: Task has no field 'nope'.
try { Task { ...p }; } catch e is TypeError { print(e.message); } // expect: Cannot spread Point into Task.
-Task { ...[1] }; // expect runtime error: [line: 31] TypeError: Cannot spread array into Task.
+Task { ...[1] }; // expect runtime error: [line: 32] TypeError: Cannot spread array into Task.
diff --git a/test/struct/spread.stderr b/test/struct/spread.stderr
index a5570b78..70c2a4e1 100644
--- a/test/struct/spread.stderr
+++ b/test/struct/spread.stderr
@@ -1,6 +1,6 @@
TypeError: Cannot spread array into Task.
- --> spread.rn:31:8
+ --> spread.rn:32:8
|
-30 | try { Task { ...p }; } catch e is TypeError { print(e.message); } // expect: Cannot spread Point into Task.
-31 | Task { ...[1] }; // expect runtime error: [line: 31] TypeError: Cannot spread array into Task.
+31 | try { Task { ...p }; } catch e is TypeError { print(e.message); } // expect: Cannot spread Point into Task.
+32 | Task { ...[1] }; // expect runtime error: [line: 32] TypeError: Cannot spread array into Task.
| ^^^
diff --git a/test/try/catch_native_error.rn b/test/try/catch_native_error.rn
index 14ba8cc8..05a026cf 100644
--- a/test/try/catch_native_error.rn
+++ b/test/try/catch_native_error.rn
@@ -1,7 +1,7 @@
try {
- http.get(123);
+ http.request("GET", 123);
} catch err {
- print(err.message); // expect: http.get() expects a string as argument 1, got number.
+ print(err.message); // expect: http.request() expects a string as argument 2, got number.
}
try {
diff --git a/test/try/catch_no_braces.rn b/test/try/catch_no_braces.rn
new file mode 100644
index 00000000..b8db765f
--- /dev/null
+++ b/test/try/catch_no_braces.rn
@@ -0,0 +1 @@
+let a = try { 1 } catch => 0; // Error at '=>': Expect '{' after 'catch'.
diff --git a/test/try/catch_no_braces.stderr b/test/try/catch_no_braces.stderr
new file mode 100644
index 00000000..6fbd802d
--- /dev/null
+++ b/test/try/catch_no_braces.stderr
@@ -0,0 +1,5 @@
+error: Expect '{' after 'catch'.
+ --> catch_no_braces.rn:1:25
+ |
+1 | let a = try { 1 } catch => 0; // Error at '=>': Expect '{' after 'catch'.
+ | ^^
diff --git a/test/try/expr.rn b/test/try/expr.rn
index 40b0cfac..9402d700 100644
--- a/test/try/expr.rn
+++ b/test/try/expr.rn
@@ -1,33 +1,48 @@
-print(try int("12") catch => 0); // expect: 12
-print(try int("x") catch => -1); // expect: -1
-print(try int("x") catch e => e is ValueError); // expect: true
+print(try { number("12") } catch { 0 }); // expect: 12
+print(try { number("x") } catch { -1 }); // expect: -1
+print(try { number("x") } catch e { e is ValueError }); // expect: true
-fun read(o) { try o.k catch e is TypeError => "type" catch e is KeyError => "key" }
+fun read(o) { try { o.k } catch e is TypeError { "type" } catch e is KeyError { "key" } }
print([read({}), read(1), read({ k: 2 })]); // expect: ["key", "type", 2]
-print([1, try [].pop() catch => 9, 3]); // expect: [1, 9, 3]
-print(try int("5") + 1 catch => 0); // expect: 6
-print(try (try int("a") catch e is KeyError => 1) catch => 2); // expect: 2
+print([1, try { [].pop() } catch { 9 }, 3]); // expect: [1, 9, 3]
+print(try { number("5") + 1 } catch { 0 }); // expect: 6
+print(try { try { number("a") } catch e is KeyError { 1 } } catch { 2 }); // expect: 2
let mut sum = 0;
-for s in ["1", "a", "3"] { sum += try int(s) catch => continue; }
+for s in ["1", "a", "3"] { sum += try { number(s) } catch { continue }; }
print(sum); // expect: 4
fun double(s) {
- let v = try int(s) catch => return "bad";
+ let v = try { number(s) } catch { return "bad" };
return v * 2;
}
print([double("4"), double("z")]); // expect: [8, "bad"]
-try int("q") catch => print("as a statement"); // expect: as a statement
-print(match 1 { 1 => try int("w") catch => "arm", _ => 0 }); // expect: arm
+print(match 1 { 1 => try { number("w") } catch { "arm" }, _ => 0 }); // expect: arm
let mut y = 5;
-y = try y + int("q") catch => y * 2;
+y = try { y + number("q") } catch { y * 2 };
print(y); // expect: 10
-let f = try int("z") catch e => () => e.message;
-print(f()); // expect: int() cannot parse "z" as an integer.
+let f = try { number("z") } catch e { () => e.message };
+print(f()); // expect: number() cannot parse "z" as a number.
fun pick(a, b, c) { [a, b, c] }
-print(pick(1, try [][0] catch e => e.message, 3)); // expect: [1, "Index out of bounds: 0 of 0", 3]
+print(pick(1, try { [][0] } catch e { e.message }, 3)); // expect: [1, "Index out of bounds: 0 of 0", 3]
+
+let z = try {
+ let n = number("7");
+ n * 2
+} catch {
+ 0
+};
+print(z); // expect: 14
+
+fun last(s) {
+ try { number(s) } catch { -1 }
+}
+print([last("3"), last("q")]); // expect: [3, -1]
+
+let w = try { print("side"); } catch { 1 }; // expect: side
+print(w); // expect: nil
diff --git a/test/try/expr_arrow.rn b/test/try/expr_arrow.rn
deleted file mode 100644
index ed14444c..00000000
--- a/test/try/expr_arrow.rn
+++ /dev/null
@@ -1 +0,0 @@
-let a = try 1 catch 2; // Error at '2': Expect '=>' after 'catch'.
diff --git a/test/try/expr_arrow.stderr b/test/try/expr_arrow.stderr
deleted file mode 100644
index 617ec232..00000000
--- a/test/try/expr_arrow.stderr
+++ /dev/null
@@ -1,5 +0,0 @@
-error: Expect '=>' after 'catch'.
- --> expr_arrow.rn:1:21
- |
-1 | let a = try 1 catch 2; // Error at '2': Expect '=>' after 'catch'.
- | ^
diff --git a/test/try/expr_catch_all.rn b/test/try/expr_catch_all.rn
index f4fd1bc7..2d8d3d44 100644
--- a/test/try/expr_catch_all.rn
+++ b/test/try/expr_catch_all.rn
@@ -1 +1 @@
-let a = try 1 catch => 1 catch e is KeyError => 2; // Error at 'catch': Catch-all must be the last catch clause.
+let a = try { 1 } catch { 1 } catch e is KeyError { 2 }; // Error at 'catch': Catch-all must be the last catch clause.
diff --git a/test/try/expr_catch_all.stderr b/test/try/expr_catch_all.stderr
index d5c87001..8c5892c2 100644
--- a/test/try/expr_catch_all.stderr
+++ b/test/try/expr_catch_all.stderr
@@ -1,5 +1,5 @@
error: Catch-all must be the last catch clause.
- --> expr_catch_all.rn:1:15
+ --> expr_catch_all.rn:1:19
|
-1 | let a = try 1 catch => 1 catch e is KeyError => 2; // Error at 'catch': Catch-all must be the last catch clause.
- | ^^^^^
+1 | let a = try { 1 } catch { 1 } catch e is KeyError { 2 }; // Error at 'catch': Catch-all must be the last catch clause.
+ | ^^^^^
diff --git a/test/try/expr_errors.rn b/test/try/expr_errors.rn
index e94a2aa1..be9da4f7 100644
--- a/test/try/expr_errors.rn
+++ b/test/try/expr_errors.rn
@@ -1 +1 @@
-let a = try 1; // Error at ';': Expect 'catch' after try expression.
+let a = try { 1 }; // Error at ';': Expect 'catch' after try block.
diff --git a/test/try/expr_errors.stderr b/test/try/expr_errors.stderr
index f2962e05..f3ee8f29 100644
--- a/test/try/expr_errors.stderr
+++ b/test/try/expr_errors.stderr
@@ -1,5 +1,5 @@
-error: Expect 'catch' after try expression.
- --> expr_errors.rn:1:14
+error: Expect 'catch' after try block.
+ --> expr_errors.rn:1:18
|
-1 | let a = try 1; // Error at ';': Expect 'catch' after try expression.
- | ^
+1 | let a = try { 1 }; // Error at ';': Expect 'catch' after try block.
+ | ^
diff --git a/test/try/expr_rethrow.rn b/test/try/expr_rethrow.rn
index c7d8b22f..7b4256d0 100644
--- a/test/try/expr_rethrow.rn
+++ b/test/try/expr_rethrow.rn
@@ -1 +1 @@
-let x = try [].pop() catch e is KeyError => 0; // expect runtime error: [line: 1] ValueError: array.pop() got an empty array.
+let x = try { [].pop() } catch e is KeyError { 0 }; // expect runtime error: [line: 1] ValueError: array.pop() got an empty array.
diff --git a/test/try/expr_rethrow.stderr b/test/try/expr_rethrow.stderr
index 7f0499cf..f5306f5f 100644
--- a/test/try/expr_rethrow.stderr
+++ b/test/try/expr_rethrow.stderr
@@ -1,8 +1,8 @@
ValueError: array.pop() got an empty array.
- --> expr_rethrow.rn:1:16
+ --> expr_rethrow.rn:1:18
|
-1 | let x = try [].pop() catch e is KeyError => 0; // expect runtime error: [line: 1] ValueError: array.pop() got an empty array.
- | ^^^
+1 | let x = try { [].pop() } catch e is KeyError { 0 }; // expect runtime error: [line: 1] ValueError: array.pop() got an empty array.
+ | ^^^
at array.pop (native)
at