diff --git a/README.md b/README.md index 6990eb8..6adff93 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ skip: int() cannot parse "x" as an integer. - value semantics: arrays, objects, maps, sets and structs copy lazily, `mut` parameters are inout - structs and enums with fields, `impl` methods - blocks give their last expression: `fun sq(x) { x * x }`, `if c { a } else { b }`, block match arms -- `match` on literals, ranges (`200..300`, `500..`), types, structs, arrays and enums, exhaustive over enum variants; destructuring, spread, rest +- `match` on literals, ranges (`200..300`, `500..`), types, structs, arrays and enums, exhaustive over enum variants; the same nested patterns in `let`, parameters and `if x is { status: 200, body }`; spread, rest - membership `x in xs` (a range without making it), slices `xs[1..]`, `s[..-1]` - nil-safe chains `a?.b ?? c`; `return` / `break` / `continue` / `throw` as expressions - `try`/`catch` by error type, as a statement or an expression; `defer` diff --git a/docs/src/data/enums.md b/docs/src/data/enums.md index b7ecaa2..8cb74e6 100644 --- a/docs/src/data/enums.md +++ b/docs/src/data/enums.md @@ -53,6 +53,35 @@ This `match` has no `_` arm, and it does not need one: it lists every variant. If a variant is later added to `Status`, the compiler points at each `match` that forgot it; see [Matching every variant](#matching-every-variant). +When every arm names a variant of one enum, say so once in the head, +`match s is Status`, and name the variants bare. The value must then be a +`Status`; anything else is a `ValueError`, as when no arm matches: + +```rune +enum Status { Pending, Paid, Shipped, Cancelled } + +fun label(s) { + match s is Status { + Pending => "waiting for payment", + Paid | Shipped => "on its way", + Cancelled => "cancelled", + } +} + +print(label(Status.Shipped)); // on its way +print(label("paid")); // ValueError: No match arm for "paid". +``` + +A bare name in such a match is always a variant, so a typo is caught: + +```rune +enum Status { Pending, Paid } +match Status.Paid is Status { Pendin => 1, _ => 2 }; // Error at 'Pendin': Status has no variant 'Pendin'. +``` + +To match on whether a value is a `Status`, put the test in parentheses: +`match (s is Status) { true => ..., false => ... }`. + ## Numbers and Names Variants are numbered from 0 in declaration order. `int(v)` gives a @@ -161,11 +190,11 @@ enum Expr { } fun eval(e) { - match e { - Expr.Num { value } => value, - Expr.Add { left, right } => eval(left) + eval(right), - Expr.Mul { left, right } => eval(left) * eval(right), - Expr.Neg { expr } => -eval(expr), + match e is Expr { + Num { value } => value, + Add { left, right } => eval(left) + eval(right), + Mul { left, right } => eval(left) * eval(right), + Neg { expr } => -eval(expr), } } diff --git a/docs/src/data/structs.md b/docs/src/data/structs.md index d83cfd8..eef6868 100644 --- a/docs/src/data/structs.md +++ b/docs/src/data/structs.md @@ -185,7 +185,7 @@ Config({ port: 80 }); // KeyError: Missing field 'host' of Config. `v is User` is `true` only for a `User`, never for an object that happens to have the same keys; see -[Type Tests](../language/values.md#type-tests). +[Type Tests](../language/values.md#type-tests-and-patterns). `==` compares two structs of the same type field by field. A struct never equals an object or a struct of another type. diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 86f86d3..67a6c37 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -71,7 +71,7 @@ Language chapters in order. - [functions](language/functions.md): closures, defaults, arrows `x => x * 2`, bodies give their last expression `fun sq(x) { x * x }` - [spread and rest](language/spread-and-rest.md), [destructuring](language/destructuring.md): `let [head, ...tail] = xs;` - [nil safety](language/nil-safety.md): `resp?.data?.items ?? []` -- [pattern matching](language/pattern-matching.md) on literals, ranges, types, structs, arrays and enums, exhaustive over enum variants +- [pattern matching](language/pattern-matching.md) on literals, ranges, types, structs, arrays and enums, exhaustive over enum variants; the same nested patterns in `let`, parameters and `if x is { status: 200, body }` - [errors](language/error-handling.md): `throw`, `try`/`catch` by type, `try` as an expression, `defer` - `return`, `break`, `continue` and `throw` as expressions: `let v = x ?? return nil;` diff --git a/docs/src/language/conditionals.md b/docs/src/language/conditionals.md index fb9038a..d17543c 100644 --- a/docs/src/language/conditionals.md +++ b/docs/src/language/conditionals.md @@ -147,4 +147,7 @@ for amount in [20, -5, 0, 40, 999] { print(paid); // [20, 40] ``` -To choose between many values, see [`match`](pattern-matching.md). +To test the shape of a value and take it apart in one step, as in +`if resp is { status: 200, body } { ... }`, see +[Binding in Conditions](values.md#binding-in-conditions). To choose +between many values, see [`match`](pattern-matching.md). diff --git a/docs/src/language/destructuring.md b/docs/src/language/destructuring.md index b0674a9..81cce2c 100644 --- a/docs/src/language/destructuring.md +++ b/docs/src/language/destructuring.md @@ -5,6 +5,11 @@ reading `user.name` and `user.age` into two variables by hand, you write the shape you expect and Rune fills in the names. Patterns work in `let`, in function parameters and in `for`-`in` variables. +These are the same patterns as in [`match`](pattern-matching.md) and +[`is`](values.md#type-tests-and-patterns). The difference is what happens +when the value does not fit: `match` tries the next arm, `is` gives +`false`, and destructuring fails with an error. + ## Objects and Structs An object pattern binds properties to variables of the same name: @@ -178,7 +183,50 @@ Anything that is not an array is a `TypeError`: let [a, b] = "ab"; // TypeError: Cannot destructure string as an array. ``` -Patterns do not nest: each element or property binds a plain variable. +## Nesting + +A property or element can be a pattern itself, so one `let` reaches deep +into a value: + +```rune +let resp = { user: { name: "ann", tags: ["admin", "ops", "dev"] }, status: 200 }; +let { user: { name, tags: [first, ...others] }, status } = resp; + +print(name); // ann +print(first); // admin +print(others); // ["ops", "dev"] +print(status); // 200 +``` + +The same key may appear twice, to keep the whole value and take it apart +too: + +```rune +let { pos, pos: { x } } = { pos: { x: 3, y: 4 } }; +print(pos); // {x: 3, y: 4} +print(x); // 3 +``` + +Nested patterns work in parameters and `for` loops as well: + +```rune +fun label({ name, size: [w, h] }) { "{name} {w}x{h}" } +print(label({ name: "logo", size: [64, 32] })); // logo 64x32 + +for [day, { hits }] in [["mon", { hits: 10 }], ["tue", { hits: 3 }]] { + print("{day}: {hits}"); +} +// mon: 10 +// tue: 3 +``` + +A pattern here only takes a value apart. Testing it, with a literal, a +range, `|` or a type, belongs in [`match`](pattern-matching.md) or +[`is`](values.md#type-tests-and-patterns): + +```rune +let [cmd, "now"] = ["run", "now"]; // Error at '"now"': This pattern only takes a value apart; test the value with match or 'is'. +``` ## Defaults diff --git a/docs/src/language/error-handling.md b/docs/src/language/error-handling.md index b7c5e8a..4057100 100644 --- a/docs/src/language/error-handling.md +++ b/docs/src/language/error-handling.md @@ -82,7 +82,7 @@ program at once, and `os.exit` exits even from inside `try`. ## Catching by Type `catch e is T` catches only errors of type `T`; `catch e is T | U` -catches either. This is the same [test](values.md#type-tests) as +catches either. This is the same [test](values.md#type-tests-and-patterns) as `v is T`. Clauses are tried in order. An error that no clause takes goes on up to the caller, with its trace intact. A clause without a type catches everything, so it must come last. @@ -264,15 +264,16 @@ try { ## defer -`defer { ... }` schedules a block to run when the enclosing block is -left: at its end, by `return`, `break` or `continue`, or by an error, -which then carries on up. It keeps cleanup next to the setup it undoes, -so it cannot be forgotten on an early exit. +`defer expression;` schedules an expression to run when the enclosing +block is left: at its end, by `return`, `break` or `continue`, or by an +error, which then carries on up. It keeps cleanup next to the setup it +undoes, so it cannot be forgotten on an early exit. For cleanup of +several statements, defer a block: `defer { ... }`. ```rune fun save(path, lines) { let out = fs.open(path, "w"); - defer { out.close(); } + defer out.close(); for line in lines { out.write(line + "\n"); @@ -280,7 +281,7 @@ fun save(path, lines) { } let dir = fs.tempDir(); -defer { fs.removeAll(dir); } +defer fs.removeAll(dir); let path = fs.join(dir, "todo.txt"); save(path, ["milk", "tea"]); @@ -292,7 +293,7 @@ order, last registered first: ```rune fun step(n) { - defer { print("step {n}: cleanup"); } + defer print("step {n}: cleanup"); if n == 0 { throw ValueError { message: "step 0 failed" }; } @@ -313,8 +314,8 @@ try { ```rune fun pipeline() { - defer { print("close file"); } - defer { print("flush buffer"); } + defer print("close file"); + defer print("flush buffer"); print("write data"); } @@ -324,6 +325,14 @@ pipeline(); // close file ``` +A single expression is deferred without braces: + +```rune +fun f() { + defer { print("bye"); } // Error at 'defer': Defer one expression without braces: defer expression; +} +``` + A `return` computes its value before the defers run. A defer's body cannot itself `return`, nor `break` or `continue` out of itself: diff --git a/docs/src/language/loops.md b/docs/src/language/loops.md index 580b67e..c66b736 100644 --- a/docs/src/language/loops.md +++ b/docs/src/language/loops.md @@ -225,7 +225,9 @@ while stack { ``` The condition is tested for [truthiness](values.md#truthiness), so -`while stack` runs until the array is empty. Here is a loop that counts +`while stack` runs until the array is empty. With a pattern, +`while queue.pop() is { id } { ... }` runs as long as the value matches; +see [Binding in Conditions](values.md#binding-in-conditions). Here is a loop that counts the steps of the Collatz sequence from 27 to 1: ```rune diff --git a/docs/src/language/pattern-matching.md b/docs/src/language/pattern-matching.md index d04db54..7b9c194 100644 --- a/docs/src/language/pattern-matching.md +++ b/docs/src/language/pattern-matching.md @@ -72,11 +72,11 @@ leave the function or the loop: `"quit" => return "bye",`. | `LIMIT`, `m.LIMIT` | a value equal to the [constant](variables.md#constants) | | `a..b`, `a..=b`, `a..`, `..b`, `..=b` | a number in the range | | `p \| q` | a value either pattern matches | -| `_ is T`, `name is T \| U` | a value of the given [type](values.md#type-tests) | +| `_ is T`, `name is T \| U`, `name is P` | a value of the given [type](values.md#type-tests-and-patterns), or one `P` matches, bound to `name` | | `Point { x, y: 0 }` | a `Point` whose fields match | | `Color.White`, `Expr.Num { value }` | that [enum](../data/enums.md) variant | -| `{ key, "other key": p }` | an object or struct that has the keys | -| `[p, q]`, `[p, ...rest]` | an array of that many elements, or at least that many | +| `{ key, "other key": p, key = d, ...rest }` | an object or struct that has the keys | +| `[p, q]`, `[p, q = d]`, `[p, ...rest]` | an array of that many elements, or at least that many | Any pattern may be followed by a guard, `pattern if condition`, which is checked after the pattern matches. @@ -196,7 +196,7 @@ still needs `_ =>` for values that are not numbers. `name is T` matches a value of type `T` and binds it; `_ is T` only tests. `T` is a struct, an enum or a built-in type such as `string`, `number` or `nil`, and `T | U` accepts either. It is the same test as -[`v is T`](values.md#type-tests). +[`v is T`](values.md#type-tests-and-patterns). ```rune fun describe(v) { @@ -217,6 +217,28 @@ print(describe({ id: 1 })); // a collection print(describe(true)); // something else ``` +After `is` comes any pattern, in which a bare name is a type. So `name is P` +binds the whole value once `P` matches it, which a guard would otherwise +have to check: + +```rune +struct Point { x, y = 0 } + +fun classify(v) { + match v { + n is 1..10 => "small {n}", + p is Point { x: 0 } => "on the axis: {p}", + s is "yes" | "no" => "answer {s}", + _ => "other", + } +} + +print(classify(3)); // small 3 +print(classify(Point { x: 0, y: 2 })); // on the axis: Point {x: 0, y: 2} +print(classify("no")); // answer no +print(classify(42)); // other +``` + ## Structs `Point { x, y: 0 }` first checks that the value is a `Point`, then @@ -321,6 +343,37 @@ for pair in results.entries() { // skipped: 2 ``` +## Defaults and Rest + +A property or element may have a default, `name = value`, used when it is +missing, so one arm covers data with optional parts. `...rest` in an +object pattern binds an object of the other keys. These work exactly as +in [destructuring](destructuring.md#defaults): + +```rune +fun command(args) { + match args { + [cmd, target = "."] => "{cmd} {target}", + _ => "usage: cmd [target]", + } +} + +print(command(["ls"])); // ls . +print(command(["ls", "/tmp"])); // ls /tmp +print(command(["ls", "a", "b"])); // usage: cmd [target] + +fun user(v) { + match v { + { name, role = "member", ...extra } => "{name} ({role}) {extra}", + _ => "not a user", + } +} + +print(user({ name: "ann" })); // ann (member) {} +print(user({ name: "bob", role: "admin", id: 7 })); // bob (admin) {id: 7} +print(user(5)); // not a user +``` + ## Expression or Statement Used as a value, `match` gives the value of the arm that ran. A block diff --git a/docs/src/language/values.md b/docs/src/language/values.md index a22a871..a5de0da 100644 --- a/docs/src/language/values.md +++ b/docs/src/language/values.md @@ -94,7 +94,7 @@ does. Functions and streams are not data and are never copied: a "copy" of one is the same function or stream. -## Type Tests +## Type Tests and Patterns `v is T` asks whether `v` has type `T`. `T` is a struct or enum you declared, or one of the built-in type names: @@ -133,6 +133,65 @@ print("42" !is number); // true The same tests appear in [`match`](pattern-matching.md#types) and in [`catch e is T`](error-handling.md#catching-by-type). +After `is` may come any [pattern](pattern-matching.md#patterns), in which +a bare name is a type. `v is P` asks whether the pattern `P` matches `v`: + +```rune +struct Point { x, y = 0 } +enum Dir { North, South } + +let resp = { status: 204, body: "" }; +print(resp is { status: 200..300 }); // true +print(7 is 1..10); // true +print("b" is "a" | "b"); // true +print([1, 2, 3] is [1, ..._]); // true +print(Point { x: 0 } is Point { x: 0 }); // true +print(Dir.South is Dir.North); // false +``` + +### Binding in Conditions + +In the condition of an `if` or a `while`, a pattern after `is` may bind +variables. They hold in the body, and on the right of an `&&` after the +test: + +```rune +fun handle(resp) { + if resp is { status: 200..300, body } && body { + "got {body}" + } else if resp is { status } { + "status {status}" + } else { + "no response" + } +} + +print(handle({ status: 200, body: "hi" })); // got hi +print(handle({ status: 404 })); // status 404 +print(handle(nil)); // no response +``` + +A `while` loop runs as long as the pattern matches, here until the queue +gives something that is not a job: + +```rune +let mut queue = [nil, { id: 2 }, { id: 1 }]; +while queue.pop() is { id } { + print("job {id}"); +} +// job 1 +// job 2 +``` + +To bind the whole value, write `name is P`, as in a +[match arm](pattern-matching.md#types): `while queue.pop() is n is number`. + +Anywhere else, and after `!is` or `||`, a test cannot bind: + +```rune +let ok = { a: 1 } is { a }; // Error at 'a': Only an if or while condition can bind variables with 'is'. +``` + A variable named like a built-in type hides it, and the right side of `is` must be a type: diff --git a/examples/kv/main.rn b/examples/kv/main.rn index 7d33cc4..207dca2 100644 --- a/examples/kv/main.rn +++ b/examples/kv/main.rn @@ -22,9 +22,7 @@ fun files(dir) { fs.list(dir).map(f => "{f.name} {kb(f.size)}").join(", ") } fun demo() { let dir = fs.tempDir(); - defer { - fs.removeAll(dir); - } + defer fs.removeAll(dir); let opts = { maxSegment: 32 << 10 }; @@ -105,9 +103,7 @@ fun demo() { fun bench(n) { let dir = fs.tempDir(); - defer { - fs.removeAll(dir); - } + defer fs.removeAll(dir); let mut db = store.Store.open(dir); let keys = (0..n).map(i => "key:{i}"); @@ -171,9 +167,7 @@ struct UsageError { message } fun cli(dir, cmd, rest) { let mut db = store.Store.open(dir); - defer { - db.close(); - } + defer db.close(); return match [cmd, ...rest] { ["put", key, value] => db.put(key, try json.parse(value) catch _ => value), diff --git a/examples/log-report.rn b/examples/log-report.rn index d62b706..089c16b 100644 --- a/examples/log-report.rn +++ b/examples/log-report.rn @@ -279,9 +279,7 @@ fun generate(path, n = 400) { let mut rng = Rng.new(42); let out = fs.open(path, "w"); - defer { - out.close(); - } + defer out.close(); for i in 0..n { let route = rng.pick(ROUTES); @@ -329,9 +327,7 @@ fun run(path, flags) { fun main(args) { let started = time.now(); - defer { - print("\ndone in %.1f ms".format((time.now() - started) * 1000)); - } + defer print("\ndone in %.1f ms".format((time.now() - started) * 1000)); let [path, ...flags] = args || [nil]; @@ -341,9 +337,7 @@ fun main(args) { let tmp = fs.tempDir(); - defer { - fs.removeAll(tmp); - } + defer fs.removeAll(tmp); let sample = fs.join(tmp, "access.log"); generate(sample); diff --git a/examples/query/main.rn b/examples/query/main.rn index 4629e0f..aa7a042 100644 --- a/examples/query/main.rn +++ b/examples/query/main.rn @@ -49,9 +49,7 @@ fun tryRun(src, mut catalog, format = "table") { fun showDemo() { let dir = fs.tempDir(); - defer { - fs.removeAll(dir); - } + defer fs.removeAll(dir); let n = int(os.env("ORDERS") ?? "100000"); diff --git a/examples/query/table.rn b/examples/query/table.rn index 2a85d41..17de3b5 100644 --- a/examples/query/table.rn +++ b/examples/query/table.rn @@ -33,9 +33,7 @@ impl Catalog { fun loadCsv(path) { let src = fs.open(path); - defer { - src.close(); - } + defer src.close(); let header = src.readLine() ?? throw ast.SqlError { message: "{path} is empty" }; let columns = splitCsv(header).map(c => c.trim()); diff --git a/examples/todo.rn b/examples/todo.rn index 3fa25f0..eb50ba2 100644 --- a/examples/todo.rn +++ b/examples/todo.rn @@ -295,9 +295,7 @@ fun exec(path, args, now) { fun demo() { let dir = fs.tempDir(); - defer { - fs.removeAll(dir); - } + defer fs.removeAll(dir); let path = fs.join(dir, "todo.json"); let now = today(); diff --git a/examples/validate.rn b/examples/validate.rn index 7a29294..8d9121c 100644 --- a/examples/validate.rn +++ b/examples/validate.rn @@ -718,9 +718,7 @@ let BROKEN = r""" fun demo() { let dir = fs.tempDir(); - defer { - fs.removeAll(dir); - } + defer fs.removeAll(dir); let files = { "edge.json": EDGE, "billing.json": BILLING_V1, "broken.json": BROKEN }; diff --git a/pkg/ast/expression.go b/pkg/ast/expression.go index b730c34..54519d5 100644 --- a/pkg/ast/expression.go +++ b/pkg/ast/expression.go @@ -271,19 +271,15 @@ func (n *StructExpr) Accept(v ExprVisitor) (value.Value, error) { return v.VisitStructExpr(n) } -// IsExpr is value is T | U; the resolver sets Shapes[i] when Types[i] -// names a type, else Types[i] is evaluated. +// IsExpr is value is pattern, whose bare names are types; Negate makes it +// value !is pattern. Only a test the resolver marks Cond, of an if or +// while condition, may bind variables, for its body and the right of its &&. type IsExpr struct { - Value Expr - Types []Expr - Token Token - Shapes []*value.Shape - // Negate makes it value !is T | U. - Negate bool -} - -func NewIsExpr(v Expr, types []Expr, token Token, negate bool) Expr { - return &IsExpr{Value: v, Types: types, Token: token, Negate: negate, Shapes: make([]*value.Shape, len(types))} + Value Expr + Pattern Pattern + Token Token + Negate bool + Cond bool } func (n *IsExpr) Accept(v ExprVisitor) (value.Value, error) { diff --git a/pkg/ast/pattern.go b/pkg/ast/pattern.go index bd9f201..69d90fe 100644 --- a/pkg/ast/pattern.go +++ b/pkg/ast/pattern.go @@ -11,9 +11,11 @@ type WildcardPattern struct { Token Token } -// BindPattern binds the value to a variable. +// BindPattern binds the value to a variable; Shorthand is a bare key of +// a field pattern, which binds even the name of a constant. type BindPattern struct { Binding + Shorthand bool } type LiteralPattern struct { @@ -34,12 +36,10 @@ type OrPattern struct { Alts []Pattern } -// FieldPattern matches the property or field Key (by its Lexeme) with -// Pattern; Shorthand is a bare key, binding the value to its name. +// FieldPattern matches the property or field Key (by its Lexeme) with Pattern. type FieldPattern struct { - Key Token - Pattern Pattern - Shorthand bool + Key Token + Pattern Pattern } // StructPattern tests the value is a Type and matches its Fields; the @@ -58,25 +58,41 @@ type VariantPattern struct { Variant Token } -// TypePattern is name is T | U, or _ is T: Inner, a BindPattern or a -// WildcardPattern, after testing the value is one of Types; the resolver -// sets Shapes. -type TypePattern struct { - Inner Pattern - Types []*VarExpr - Shapes []*value.Shape +// IsPattern is name is P, or _ is P: Inner, a BindPattern or a +// WildcardPattern, takes the value once it matches Test. +type IsPattern struct { + Inner Pattern + Test Pattern +} + +// TypeTestPattern is a type on the right of is, matching a value of that +// type; the resolver sets Shape, or in an is expression leaves it nil for +// a Type evaluated when it runs. +type TypeTestPattern struct { + Token Token + Type Expr + Shape *value.Shape } -// ObjectPattern is { key: pattern, ... }, matching an object or a struct -// that has every key; other keys are allowed. +// DefaultPattern is P = default, an element of an array pattern or the +// pattern of a field: a missing value is taken as Default. +type DefaultPattern struct { + Pattern Pattern + Default Expr +} + +// ObjectPattern is { key: pattern, ..., ...rest }, matching an object or a +// struct that has every key without a default; other keys are allowed and +// Rest, unless nil, binds an object of them. type ObjectPattern struct { Brace Token Fields []FieldPattern + Rest *BindPattern } // ArrayPattern is [p, q], matching an array of exactly as many elements, // or, if Open, [p, q, ...rest] or [p, q, ..._], at least as many; Rest -// binds the others, unless nil. +// binds the others, unless nil. Elements with a default may be missing. type ArrayPattern struct { Bracket Token Elems []Pattern @@ -84,6 +100,18 @@ type ArrayPattern struct { Rest *BindPattern } +// Required is the number of elements the value must have: those before +// the first with a default. +func (n *ArrayPattern) Required() int { + for i, e := range n.Elems { + if _, ok := e.(*DefaultPattern); ok { + return i + } + } + + return len(n.Elems) +} + func (*WildcardPattern) patternNode() {} func (*BindPattern) patternNode() {} func (*LiteralPattern) patternNode() {} @@ -91,41 +119,89 @@ func (*RangePattern) patternNode() {} func (*OrPattern) patternNode() {} func (*StructPattern) patternNode() {} func (*ObjectPattern) patternNode() {} -func (*TypePattern) patternNode() {} +func (*IsPattern) patternNode() {} +func (*TypeTestPattern) patternNode() {} +func (*DefaultPattern) patternNode() {} func (*VariantPattern) patternNode() {} func (*ArrayPattern) patternNode() {} +// Walk calls visit on p and, while visit returns true, on the patterns +// matched against parts of the value, in the order they match. +func Walk(p Pattern, visit func(Pattern) bool) { + if !visit(p) { + return + } + + fields := func(fs []FieldPattern) { + for _, f := range fs { + Walk(f.Pattern, visit) + } + } + + switch n := p.(type) { + case *OrPattern: + for _, alt := range n.Alts { + Walk(alt, visit) + } + case *IsPattern: + Walk(n.Test, visit) + Walk(n.Inner, visit) + case *DefaultPattern: + Walk(n.Pattern, visit) + case *StructPattern: + fields(n.Fields) + case *ObjectPattern: + fields(n.Fields) + + if n.Rest != nil { + Walk(n.Rest, visit) + } + case *ArrayPattern: + for _, e := range n.Elems { + Walk(e, visit) + } + + if n.Rest != nil { + Walk(n.Rest, visit) + } + } +} + // Bindings returns the variables p binds; alternatives bind none. func Bindings(p Pattern) []*Binding { var out []*Binding - var walk func(p Pattern) - walk = func(p Pattern) { + Walk(p, func(p Pattern) bool { switch n := p.(type) { + case *OrPattern: + return false case *BindPattern: out = append(out, &n.Binding) - case *TypePattern: - walk(n.Inner) - case *StructPattern: - for _, f := range n.Fields { - walk(f.Pattern) - } - case *ObjectPattern: - for _, f := range n.Fields { - walk(f.Pattern) - } - case *ArrayPattern: - for _, e := range n.Elems { - walk(e) - } + } + + return true + }) - if n.Rest != nil { - out = append(out, &n.Rest.Binding) + return out +} + +// Exprs returns the expressions p evaluates, in order: defaults and types +// evaluated when it runs. +func Exprs(p Pattern) []Expr { + var out []Expr + + Walk(p, func(p Pattern) bool { + switch n := p.(type) { + case *TypeTestPattern: + if n.Shape == nil { + out = append(out, n.Type) } + case *DefaultPattern: + out = append(out, n.Default) } - } - walk(p) + return true + }) return out } @@ -155,11 +231,15 @@ type MatchArm struct { Body *BlockStmt } -// MatchExpr is match subject { arms }; no arm matching is an error. +// MatchExpr is match subject { arms }; no arm matching is an error. With +// Enum, as in match subject is Enum { arms }, the subject must be one of +// its variants, which the arms name bare; the resolver sets EnumShape. type MatchExpr struct { - Keyword Token - Subject Expr - Arms []MatchArm + Keyword Token + Subject Expr + Enum *VarExpr + EnumShape *value.Shape + Arms []MatchArm } // Values returns the value of each arm, nil for one without. diff --git a/pkg/ast/statement.go b/pkg/ast/statement.go index ad07911..91b21dd 100644 --- a/pkg/ast/statement.go +++ b/pkg/ast/statement.go @@ -8,8 +8,7 @@ import ( type StmtVisitor interface { VisitExprStmt(exprStmt *ExprStmt) error VisitVarStmt(VarStmt *VarStmt) error - VisitDestructureStmt(stmt *DestructureStmt) error - VisitArrayDestructureStmt(stmt *ArrayDestructureStmt) error + VisitPatternStmt(stmt *PatternStmt) error VisitBlockStmt(blockStmt *BlockStmt) error VisitIfStmt(ifStmt *IfStmt) error VisitWhileStmt(whileStmt *WhileStmt) error @@ -48,75 +47,15 @@ func NewVarStmt(initializer Expr, binding Binding) Stmt { return &VarStmt{Initializer: initializer, Binding: binding} } -// PatternVar is a variable a pattern binds, and its default, if any, taken -// when the value has no such property or element. -type PatternVar struct { - Binding - Default Expr -} - -// DestructureField binds the property Key (by its Lexeme) of the value. -type DestructureField struct { - Key Token - PatternVar -} - -// DestructureStmt is let { a, mut b = 1, c: d, ...rest } = value; Rest, -// if any, binds an object of the other properties or fields. -type DestructureStmt struct { - Brace Token - Fields []DestructureField - Rest *PatternVar +// PatternStmt is let pattern = value; and the destructuring of a pattern +// parameter or for-in variable: each part the pattern names must be there. +type PatternStmt struct { + Pattern Pattern Initializer Expr } -// ArrayDestructureStmt is let [a, _, mut b = 1, ...rest] = value; Elems -// binds the elements in order, nil for _, and Rest, if any, the others. -type ArrayDestructureStmt struct { - Bracket Token - Elems []*PatternVar - Rest *PatternVar - Initializer Expr -} - -// Required is the number of elements the value must have: those before -// the first with a default. -func (s *ArrayDestructureStmt) Required() int { - for i, e := range s.Elems { - if e != nil && e.Default != nil { - return i - } - } - - return len(s.Elems) -} - -// PatternVars returns the variables a destructuring stmt binds, in order. -func PatternVars(stmt Stmt) []*PatternVar { - var vs []*PatternVar - - switch s := stmt.(type) { - case *DestructureStmt: - for i := range s.Fields { - vs = append(vs, &s.Fields[i].PatternVar) - } - - if s.Rest != nil { - vs = append(vs, s.Rest) - } - case *ArrayDestructureStmt: - for _, e := range s.Elems { - if e != nil { - vs = append(vs, e) - } - } - - if s.Rest != nil { - vs = append(vs, s.Rest) - } - } - - return vs +func (n *PatternStmt) Accept(v StmtVisitor) error { + return v.VisitPatternStmt(n) } // Declared returns the variables stmt declares, structs and discards aside. @@ -128,10 +67,8 @@ func Declared(stmt Stmt) []*Binding { bs = []*Binding{&s.Binding} case *FunctionStmt: bs = []*Binding{&s.Binding} - case *DestructureStmt, *ArrayDestructureStmt: - for _, v := range PatternVars(s) { - bs = append(bs, &v.Binding) - } + case *PatternStmt: + bs = Bindings(s.Pattern) } return slices.DeleteFunc(bs, func(b *Binding) bool { return b.Discards() }) @@ -376,14 +313,6 @@ func (n *VarStmt) Accept(v StmtVisitor) error { return v.VisitVarStmt(n) } -func (n *DestructureStmt) Accept(v StmtVisitor) error { - return v.VisitDestructureStmt(n) -} - -func (n *ArrayDestructureStmt) Accept(v StmtVisitor) error { - return v.VisitArrayDestructureStmt(n) -} - func (n *BlockStmt) Accept(v StmtVisitor) error { return v.VisitBlockStmt(n) } diff --git a/pkg/rune/bytecode.go b/pkg/rune/bytecode.go index f1f4ce3..5c6d37d 100644 --- a/pkg/rune/bytecode.go +++ b/pkg/rune/bytecode.go @@ -60,7 +60,7 @@ const ( opJmpNotType // if R[A] is not of type K[B]: pc = C opJmpNil // if (R[A] is nil) == Y: pc = C opJmpDefined // if R[A] is defined: pc = C - opJmpNotLen // if R[A] is not an array of B elements, or with X at least B: pc = C + opJmpNotLen // if R[A] is not an array of B elements, or with X lenAtLeast at least, lenAtMost at most: pc = C opArray // R[A] = [R[B], ..., R[B+C-1]] opConcat // R[A] = R[B] .. R[B+C-1] as printed, appended to R[A] if X @@ -195,6 +195,8 @@ type ins struct { } const ( + lenAtLeast = 1 + lenAtMost = 2 unpackShift = 10 maxUnpack = 1< 1 { - r = fs.alloc() - } - - var ends []int - - for i, typ := range n.Types { - var t int32 - if n.Shapes[i] != nil { - t = fs.alloc() - fs.emit(ins{op: opLoadK, a: t, c: fs.constant(value.NewType(n.Shapes[i]))}, nil) - } else { - t = fs.exprAny(typ) - } - - fs.emit(ins{op: opIs, a: r, b: v, c: t, y: neg}, &n.Token) - - if i < len(n.Types)-1 { - ends = append(ends, fs.emit(ins{op: opJmpIf, a: r, y: 1 - neg}, nil)) - } - } - - fs.patch(ends) - - if r != dst { - fs.emit(ins{op: opMove, a: dst, b: r}, nil) - } -} diff --git a/pkg/rune/compile_match.go b/pkg/rune/compile_match.go index eb934ef..b8a338d 100644 --- a/pkg/rune/compile_match.go +++ b/pkg/rune/compile_match.go @@ -2,7 +2,6 @@ package rune import ( "rune/pkg/ast" - "rune/pkg/value" ) // match compiles m into dst; for a statement (dst noReg) the value is @@ -19,8 +18,13 @@ func (fs *funcState) match(m *ast.MatchExpr, dst int32) { subj := fs.operand(m.Subject, guards...) fs.nactive = fs.free + var notEnum []int + if m.EnumShape != nil { + notEnum = []int{fs.typeTest(subj, m.EnumShape)} + } + last := &m.Arms[len(m.Arms)-1] - fails := !reachedAll(last) + fails := !reachedAll(last) || notEnum != nil var ends []int @@ -39,6 +43,7 @@ func (fs *funcState) match(m *ast.MatchExpr, dst int32) { } if fails { + fs.patch(notEnum) fs.emit(ins{op: opNoMatch, a: subj}, &m.Keyword) } @@ -56,13 +61,7 @@ func (fs *funcState) arm(arm *ast.MatchArm, subj, dst int32) []int { miss := fs.pattern(arm.Pattern, subj) fs.free = fs.nactive - - for _, b := range bindings { - if b.Local.Captured { - r := fs.locals[b.Local] - fs.emit(ins{op: opNewCell, a: r, b: r}, nil) - } - } + fs.cellBindings(arm.Pattern) if arm.Guard != nil { miss = append(miss, fs.jumpIf(arm.Guard, false)...) @@ -72,186 +71,3 @@ func (fs *funcState) arm(arm *ast.MatchArm, subj, dst int32) []int { return miss } - -// pattern emits the tests of R[s] against p, binding its variables, and -// returns the jumps taken on a mismatch. -func (fs *funcState) pattern(p ast.Pattern, s int32) []int { - switch n := p.(type) { - case *ast.WildcardPattern: - return nil - case *ast.BindPattern: - fs.move(fs.locals[n.Local], s) - - return nil - case *ast.LiteralPattern: - return []int{fs.literalTest(s, n)} - case *ast.RangePattern: - return fs.rangeTest(s, n) - case *ast.OrPattern: - return fs.anyOf(len(n.Alts), func(i int) []int { return fs.pattern(n.Alts[i], s) }) - case *ast.StructPattern: - miss := []int{fs.typeTest(s, n.Shape)} - for _, f := range n.Fields { - miss = append(miss, fs.fieldTest(s, f, false)...) - } - - return miss - case *ast.TypePattern: - return append(fs.isOneOf(s, n.Shapes), fs.pattern(n.Inner, s)...) - case *ast.ObjectPattern: - var miss []int - for _, f := range n.Fields { - miss = append(miss, fs.fieldTest(s, f, true)...) - } - - return miss - case *ast.ArrayPattern: - return fs.arrayTest(s, n) - } - - panic("compile: unknown pattern") -} - -// arrayTest matches R[s] against [p, q, ...rest]: tests the length, then -// unpacks the elements into temporaries and matches each. -func (fs *funcState) arrayTest(s int32, n *ast.ArrayPattern) []int { - count := len(n.Elems) - miss := []int{fs.emit(ins{op: opJmpNotLen, a: s, b: int32(count), x: uint8(boolNum(n.Open))}, nil)} - - if count == 0 && n.Rest == nil { - return miss - } - - free := fs.free - defer func() { fs.free = free }() - - // The length is tested already. - base := fs.unpackTo(s, count, count, n.Rest != nil, true, &n.Bracket) - - for i, e := range n.Elems { - miss = append(miss, fs.pattern(e, base+int32(i))...) - } - - if n.Rest != nil { - fs.pattern(n.Rest, base+int32(count)) - } - - return miss -} - -// anyOf emits n tests, each giving the jumps it takes on a mismatch, and -// returns the jumps taken when all of them miss. -func (fs *funcState) anyOf(n int, test func(i int) []int) []int { - var hits, miss []int - - for i := range n { - miss = test(i) - if i < n-1 { - hits = append(hits, fs.emit(ins{op: opJmp}, nil)) - fs.patch(miss) - } - } - - fs.patch(hits) - - return miss -} - -// isOneOf returns the jumps taken unless R[s] is a struct of one of shapes. -func (fs *funcState) isOneOf(s int32, shapes []*value.Shape) []int { - return fs.anyOf(len(shapes), func(i int) []int { return []int{fs.typeTest(s, shapes[i])} }) -} - -// typeTest jumps unless R[s] is a struct of shape; a type past the -// constants JMPNOTTYPE reaches is tested with IS. -func (fs *funcState) typeTest(s int32, shape *value.Shape) int { - k, ok := fs.operandConst(value.NewType(shape), true, maxAB) - if ok { - return fs.emit(ins{op: opJmpNotType, a: s, b: k}, nil) - } - - t := fs.alloc() - fs.emit(ins{op: opLoadK, a: t, c: k}, nil) - fs.emit(ins{op: opIs, a: t, b: s, c: t}, nil) - - return fs.emit(ins{op: opJmpIf, a: t, y: 0}, nil) -} - -// literalTest jumps unless R[s] == the literal. -func (fs *funcState) literalTest(s int32, n *ast.LiteralPattern) int { - ne := n.Token - ne.TokenType = ast.BANG_EQUAL - - return fs.jumpCmpConst(s, n.Value, cmpNE, 1, &ne) -} - -// rangeTest jumps unless R[s] is a number within the bounds of n. -func (fs *funcState) rangeTest(s int32, n *ast.RangePattern) []int { - miss := []int{fs.typeTest(s, kindTypes["number"])} - - bound := func(b ast.Pattern, cmp uint8) { - if b != nil { - miss = append(miss, fs.jumpCmpConst(s, b.(*ast.LiteralPattern).Value, cmp, 0, &n.Op)) - } - } - - bound(n.Lo, cmpGE) - - if n.Inclusive { - bound(n.Hi, cmpLE) - } else { - bound(n.Hi, cmpLT) - } - - return miss -} - -// jumpCmpConst jumps if (R[s] v) == y. -func (fs *funcState) jumpCmpConst(s int32, v value.Value, cmp, y uint8, tok *ast.Token) int { - k, ok := fs.operandConst(v, true, maxAB) - if ok { - return fs.emit(ins{op: opJmpCmpK, x: cmp, y: y, a: s, b: k}, tok) - } - - t := fs.alloc() - fs.emit(ins{op: opLoadK, a: t, c: k}, nil) - - return fs.emit(ins{op: opJmpCmp, x: cmp, y: y, a: s, b: t}, tok) -} - -// fieldTest matches field f of R[s]: of a struct already known to have -// it, or of an object or struct that may not. -func (fs *funcState) fieldTest(s int32, f ast.FieldPattern, mayMiss bool) []int { - if _, ok := f.Pattern.(*ast.WildcardPattern); ok && !mayMiss { - return nil - } - - free := fs.free - defer func() { fs.free = free }() - - b, bind := f.Pattern.(*ast.BindPattern) - - var t int32 - if bind { - t = fs.locals[b.Local] - } else { - t = fs.alloc() - } - - key := fs.constant(value.NewString(f.Key.Lexeme)) - - var miss []int - - if mayMiss { - fs.emit(ins{op: opTestProp, a: t, b: s, c: key}, nil) - miss = append(miss, fs.emit(ins{op: opJmp}, nil)) - } else { - fs.emit(ins{op: opGetProp, a: t, b: s, c: key}, &f.Key) - } - - if bind { - return miss - } - - return append(miss, fs.pattern(f.Pattern, t)...) -} diff --git a/pkg/rune/compile_pattern.go b/pkg/rune/compile_pattern.go new file mode 100644 index 0000000..2b61608 --- /dev/null +++ b/pkg/rune/compile_pattern.go @@ -0,0 +1,440 @@ +package rune + +import ( + "rune/pkg/ast" + "rune/pkg/value" + "slices" +) + +func (fs *funcState) patternStmt(s *ast.PatternStmt) { + for _, b := range ast.Declared(s) { + fs.predeclare(b.Local) + } + + fs.destructure(s.Pattern, fs.exprAny(s.Initializer)) +} + +// destructure binds the variables of pat to the parts of R[src], each of +// which must be there unless it has a default. +func (fs *funcState) destructure(pat ast.Pattern, src int32) { + switch n := pat.(type) { + case *ast.BindPattern: + fs.initialize(n.Local, func(dst int32) { fs.move(dst, src) }) + case *ast.ObjectPattern: + for _, f := range n.Fields { + fs.destructureField(src, f) + } + + if r := n.Rest; r != nil { + c := fs.keyList(fieldKeys(n.Fields)) + fs.initialize(r.Local, func(dst int32) { + fs.emit(ins{op: opOmit, a: dst, b: src, c: c}, &n.Brace) + }) + } + case *ast.ArrayPattern: + count := len(n.Elems) + base := fs.unpackTo(src, count, n.Required(), n.Rest != nil, n.Open && n.Rest == nil, &n.Bracket) + + for i, e := range n.Elems { + e, def := unwrapDefault(e) + fs.orDefault(base+int32(i), def) + fs.destructure(e, base+int32(i)) + } + + if n.Rest != nil { + fs.destructure(n.Rest, base+int32(count)) + } + } +} + +// destructureField binds the variables of f to its property of R[src]. +func (fs *funcState) destructureField(src int32, f ast.FieldPattern) { + p, def := unwrapDefault(f.Pattern) + if _, ok := p.(*ast.WildcardPattern); ok { + return + } + + get := func(dst int32) { + fs.emit(ins{op: opGetProp, a: dst, b: src, c: fs.constant(value.NewString(f.Key.Lexeme)), x: uint8(boolNum(def != nil))}, &f.Key) + fs.orDefault(dst, def) + fs.emit(ins{op: opShare, a: dst}, nil) + } + + if b, ok := p.(*ast.BindPattern); ok { + fs.initialize(b.Local, get) + return + } + + free := fs.free + t := fs.alloc() + get(t) + fs.destructure(p, t) + fs.free = free +} + +func unwrapDefault(p ast.Pattern) (ast.Pattern, ast.Expr) { + if d, ok := p.(*ast.DefaultPattern); ok { + return d.Pattern, d.Default + } + + return p, nil +} + +func fieldKeys(fields []ast.FieldPattern) []string { + keys := make([]string, len(fields)) + for i, f := range fields { + keys[i] = f.Key.Lexeme + } + + return keys +} + +// condScope compiles body, the condition cond and what it guards, with +// the variables its is tests bind declared first, above the temporaries +// live around it. +func (fs *funcState) condScope(cond ast.Expr, body func()) { + var binds []*ast.Binding + for _, t := range condTests(cond) { + binds = append(binds, ast.Bindings(t.Pattern)...) + } + + if len(binds) == 0 { + body() + return + } + + nactive, free := fs.nactive, fs.free + fs.nactive = fs.free + + for _, b := range binds { + fs.declare(b.Local) + } + + body() + fs.nactive, fs.free = nactive, free +} + +// cellBindings puts each variable pat binds that a closure captures in a cell. +func (fs *funcState) cellBindings(pat ast.Pattern) { + for _, b := range ast.Bindings(pat) { + if b.Local.Captured { + r := fs.locals[b.Local] + fs.emit(ins{op: opNewCell, a: r, b: r}, nil) + } + } +} + +// pattern emits the tests of R[s] against p, binding its variables, and +// returns the jumps taken on a mismatch. +func (fs *funcState) pattern(p ast.Pattern, s int32) []int { + switch n := p.(type) { + case *ast.WildcardPattern: + return nil + case *ast.BindPattern: + fs.move(fs.locals[n.Local], s) + + return nil + case *ast.LiteralPattern: + return []int{fs.literalTest(s, n)} + case *ast.RangePattern: + return fs.rangeTest(s, n) + case *ast.OrPattern: + return fs.anyOf(len(n.Alts), func(i int) []int { return fs.pattern(n.Alts[i], s) }) + case *ast.StructPattern: + miss := []int{fs.typeTest(s, n.Shape)} + for _, f := range n.Fields { + miss = append(miss, fs.fieldTest(s, f, false)...) + } + + return miss + case *ast.IsPattern: + return append(fs.pattern(n.Test, s), fs.pattern(n.Inner, s)...) + case *ast.TypeTestPattern: + return []int{fs.typeTestOf(s, n)} + case *ast.ObjectPattern: + var miss []int + if n.Rest != nil || slices.ContainsFunc(n.Fields, hasDefault) { + miss = append(miss, fs.typeTest(s, value.RecordType)) + } + + for _, f := range n.Fields { + miss = append(miss, fs.fieldTest(s, f, true)...) + } + + if n.Rest != nil { + c := fs.keyList(fieldKeys(n.Fields)) + fs.emit(ins{op: opOmit, a: fs.locals[n.Rest.Local], b: s, c: c}, &n.Brace) + } + + return miss + case *ast.ArrayPattern: + return fs.arrayTest(s, n) + } + + panic("compile: unknown pattern") +} + +func hasDefault(f ast.FieldPattern) bool { + _, ok := f.Pattern.(*ast.DefaultPattern) + return ok +} + +// arrayTest matches R[s] against [p, q = d, ...rest]: tests the length, +// then unpacks the elements into temporaries and matches each. +func (fs *funcState) arrayTest(s int32, n *ast.ArrayPattern) []int { + count, required := len(n.Elems), n.Required() + + var miss []int + if required == count { + miss = []int{fs.emit(ins{op: opJmpNotLen, a: s, b: int32(count), x: uint8(boolNum(n.Open))}, nil)} + } else { + miss = []int{fs.emit(ins{op: opJmpNotLen, a: s, b: int32(required), x: lenAtLeast}, nil)} + if !n.Open { + miss = append(miss, fs.emit(ins{op: opJmpNotLen, a: s, b: int32(count), x: lenAtMost}, nil)) + } + } + + if count == 0 && n.Rest == nil { + return miss + } + + free := fs.free + defer func() { fs.free = free }() + + // The length is tested already. + base := fs.unpackTo(s, count, required, n.Rest != nil, true, &n.Bracket) + + for i, e := range n.Elems { + e, def := unwrapDefault(e) + fs.orDefault(base+int32(i), def) + miss = append(miss, fs.pattern(e, base+int32(i))...) + } + + if n.Rest != nil { + fs.pattern(n.Rest, base+int32(count)) + } + + return miss +} + +// anyOf emits n tests, each giving the jumps it takes on a mismatch, and +// returns the jumps taken when all of them miss. +func (fs *funcState) anyOf(n int, test func(i int) []int) []int { + var hits, miss []int + + for i := range n { + miss = test(i) + if i < n-1 { + hits = append(hits, fs.emit(ins{op: opJmp}, nil)) + fs.patch(miss) + } + } + + fs.patch(hits) + + return miss +} + +// isOneOf returns the jumps taken unless R[s] is a struct of one of shapes. +func (fs *funcState) isOneOf(s int32, shapes []*value.Shape) []int { + return fs.anyOf(len(shapes), func(i int) []int { return []int{fs.typeTest(s, shapes[i])} }) +} + +// typeTestOf jumps unless R[s] is of the type n names, which may be +// evaluated only when it runs. +func (fs *funcState) typeTestOf(s int32, n *ast.TypeTestPattern) int { + if n.Shape != nil { + return fs.typeTest(s, n.Shape) + } + + t := fs.exprAny(n.Type) + r := fs.alloc() + fs.emit(ins{op: opIs, a: r, b: s, c: t}, &n.Token) + + return fs.emit(ins{op: opJmpIf, a: r, y: 0}, nil) +} + +// typeTest jumps unless R[s] is a struct of shape; a type past the +// constants JMPNOTTYPE reaches is tested with IS. +func (fs *funcState) typeTest(s int32, shape *value.Shape) int { + k, ok := fs.operandConst(value.NewType(shape), true, maxAB) + if ok { + return fs.emit(ins{op: opJmpNotType, a: s, b: k}, nil) + } + + t := fs.alloc() + fs.emit(ins{op: opLoadK, a: t, c: k}, nil) + fs.emit(ins{op: opIs, a: t, b: s, c: t}, nil) + + return fs.emit(ins{op: opJmpIf, a: t, y: 0}, nil) +} + +// literalTest jumps unless R[s] == the literal. +func (fs *funcState) literalTest(s int32, n *ast.LiteralPattern) int { + ne := n.Token + ne.TokenType = ast.BANG_EQUAL + + return fs.jumpCmpConst(s, n.Value, cmpNE, 1, &ne) +} + +// rangeTest jumps unless R[s] is a number within the bounds of n. +func (fs *funcState) rangeTest(s int32, n *ast.RangePattern) []int { + miss := []int{fs.typeTest(s, kindTypes["number"])} + + bound := func(b ast.Pattern, cmp uint8) { + if b != nil { + miss = append(miss, fs.jumpCmpConst(s, b.(*ast.LiteralPattern).Value, cmp, 0, &n.Op)) + } + } + + bound(n.Lo, cmpGE) + + if n.Inclusive { + bound(n.Hi, cmpLE) + } else { + bound(n.Hi, cmpLT) + } + + return miss +} + +// jumpCmpConst jumps if (R[s] v) == y. +func (fs *funcState) jumpCmpConst(s int32, v value.Value, cmp, y uint8, tok *ast.Token) int { + k, ok := fs.operandConst(v, true, maxAB) + if ok { + return fs.emit(ins{op: opJmpCmpK, x: cmp, y: y, a: s, b: k}, tok) + } + + t := fs.alloc() + fs.emit(ins{op: opLoadK, a: t, c: k}, nil) + + return fs.emit(ins{op: opJmpCmp, x: cmp, y: y, a: s, b: t}, tok) +} + +// fieldTest matches field f of R[s]: of a struct already known to have +// it, or of an object or struct that may not. +func (fs *funcState) fieldTest(s int32, f ast.FieldPattern, mayMiss bool) []int { + if _, ok := f.Pattern.(*ast.WildcardPattern); ok && !mayMiss { + return nil + } + + free := fs.free + defer func() { fs.free = free }() + + p, def := unwrapDefault(f.Pattern) + b, bind := p.(*ast.BindPattern) + + var t int32 + if bind { + t = fs.locals[b.Local] + } else { + t = fs.alloc() + } + + key := fs.constant(value.NewString(f.Key.Lexeme)) + + var miss []int + + switch { + case !mayMiss: + fs.emit(ins{op: opGetProp, a: t, b: s, c: key}, &f.Key) + case def == nil: + fs.emit(ins{op: opTestProp, a: t, b: s, c: key}, nil) + miss = append(miss, fs.emit(ins{op: opJmp}, nil)) + default: + fs.emit(ins{op: opTestProp, a: t, b: s, c: key}, nil) + missing := fs.emit(ins{op: opJmp}, nil) + found := fs.emit(ins{op: opJmp}, nil) + fs.patch([]int{missing}) + fs.copyExpr(def, t) + fs.patch([]int{found}) + } + + if bind { + return miss + } + + return append(miss, fs.pattern(p, t)...) +} + +// isExpr sets R[dst] to whether the value of n matches its pattern. +func (fs *funcState) isExpr(n *ast.IsExpr, dst int32) { + if types, ok := typeTests(n.Pattern); ok { + fs.isTypes(n, types, dst) + return + } + + miss := fs.isMatch(n) + fs.emit(ins{op: opLoadK, a: dst, c: fs.constant(value.NewBool(!n.Negate))}, nil) + end := fs.emit(ins{op: opJmp}, nil) + fs.patch(miss) + fs.emit(ins{op: opLoadK, a: dst, c: fs.constant(value.NewBool(n.Negate))}, nil) + fs.patch([]int{end}) +} + +// isMatch emits the test of n's pattern, binding its variables, declared +// already, and returns the jumps taken on a mismatch. +func (fs *funcState) isMatch(n *ast.IsExpr) []int { + v := fs.operand(n.Value, ast.Exprs(n.Pattern)...) + miss := fs.pattern(n.Pattern, v) + fs.cellBindings(n.Pattern) + + return miss +} + +// typeTests returns the types of pat, if it only tests for types. +func typeTests(pat ast.Pattern) ([]*ast.TypeTestPattern, bool) { + switch n := pat.(type) { + case *ast.TypeTestPattern: + return []*ast.TypeTestPattern{n}, true + case *ast.OrPattern: + var types []*ast.TypeTestPattern + for _, alt := range n.Alts { + t, ok := alt.(*ast.TypeTestPattern) + if !ok { + return nil, false + } + + types = append(types, t) + } + + return types, true + } + + return nil, false +} + +// isTypes sets R[dst] to whether the value of n is of one of types, +// testing them in order until one decides. +func (fs *funcState) isTypes(n *ast.IsExpr, types []*ast.TypeTestPattern, dst int32) { + v := fs.operand(n.Value, ast.Exprs(n.Pattern)...) + neg := uint8(boolNum(n.Negate)) + r := dst + if len(types) > 1 { + r = fs.alloc() + } + + var ends []int + + for i, typ := range types { + var t int32 + if typ.Shape != nil { + t = fs.alloc() + fs.emit(ins{op: opLoadK, a: t, c: fs.constant(value.NewType(typ.Shape))}, nil) + } else { + t = fs.exprAny(typ.Type) + } + + fs.emit(ins{op: opIs, a: r, b: v, c: t, y: neg}, &typ.Token) + + if i < len(types)-1 { + ends = append(ends, fs.emit(ins{op: opJmpIf, a: r, y: 1 - neg}, nil)) + } + } + + fs.patch(ends) + + if r != dst { + fs.emit(ins{op: opMove, a: dst, b: r}, nil) + } +} diff --git a/pkg/rune/compile_stmt.go b/pkg/rune/compile_stmt.go index 26d5dfc..6be37f8 100644 --- a/pkg/rune/compile_stmt.go +++ b/pkg/rune/compile_stmt.go @@ -131,10 +131,8 @@ func (fs *funcState) stmt(stmt ast.Stmt) { fs.exprStmt(s.Expr) case *ast.VarStmt: fs.varStmt(s) - case *ast.DestructureStmt: - fs.destructure(s) - case *ast.ArrayDestructureStmt: - fs.unpack(s) + case *ast.PatternStmt: + fs.patternStmt(s) case *ast.BlockStmt: fs.block(s, noReg) case *ast.IfStmt: @@ -245,63 +243,6 @@ func (fs *funcState) varStmt(s *ast.VarStmt) { }) } -func (fs *funcState) destructure(s *ast.DestructureStmt) { - for _, b := range ast.Declared(s) { - fs.predeclare(b.Local) - } - - src := fs.exprAny(s.Initializer) - - for i := range s.Fields { - f := &s.Fields[i] - if f.Discards() { - continue - } - fs.initialize(f.Local, func(dst int32) { - fs.emit(ins{op: opGetProp, a: dst, b: src, c: fs.constant(value.NewString(f.Key.Lexeme)), x: uint8(boolNum(f.Default != nil))}, &f.Key) - fs.orDefault(dst, f.Default) - fs.emit(ins{op: opShare, a: dst}, nil) - }) - } - - if r := s.Rest; r != nil && !r.Discards() { - keys := make([]string, len(s.Fields)) - for i, f := range s.Fields { - keys[i] = f.Key.Lexeme - } - - c := fs.keyList(keys) - fs.initialize(r.Local, func(dst int32) { - fs.emit(ins{op: opOmit, a: dst, b: src, c: c}, &s.Brace) - }) - } -} - -// unpack takes the elements into temporaries, then the variables. -func (fs *funcState) unpack(s *ast.ArrayDestructureStmt) { - for _, b := range ast.Declared(s) { - fs.predeclare(b.Local) - } - - src := fs.exprAny(s.Initializer) - n := len(s.Elems) - rest := s.Rest != nil - base := fs.unpackTo(src, n, s.Required(), rest, false, &s.Bracket) - - for i, e := range s.Elems { - if e != nil { - fs.initialize(e.Local, func(dst int32) { - fs.move(dst, base+int32(i)) - fs.orDefault(dst, e.Default) - }) - } - } - - if rest { - fs.initialize(s.Rest.Local, func(dst int32) { fs.move(dst, base+int32(n)) }) - } -} - // unpackTo takes the first n elements of the array R[src], of which // required must be there, into new temporaries, and with rest the others // as an array after them; it returns the first temporary. Without rest @@ -405,8 +346,12 @@ func (fs *funcState) functionStmt(s *ast.FunctionStmt) { // ifStmt compiles s, with the value of the branch taken into dst unless // it is noReg. func (fs *funcState) ifStmt(s *ast.IfStmt, dst int32) { - skip := fs.jumpIf(s.Condition, false) - fs.block(s.Then, dst) + var skip []int + + fs.condScope(s.Condition, func() { + skip = fs.jumpIf(s.Condition, false) + fs.block(s.Then, dst) + }) if s.El == nil && dst == noReg { fs.patch(skip) @@ -459,6 +404,10 @@ func (fs *funcState) block(b *ast.BlockStmt, dst int32) { // whileStmt tests at the bottom, so an iteration runs one jump. func (fs *funcState) whileStmt(s *ast.WhileStmt) { + fs.condScope(s.Condition, func() { fs.while(s) }) +} + +func (fs *funcState) while(s *ast.WhileStmt) { enter := fs.emit(ins{op: opJmp}, nil) body := fs.here() diff --git a/pkg/rune/moves.go b/pkg/rune/moves.go index 4642b45..7feea7b 100644 --- a/pkg/rune/moves.go +++ b/pkg/rune/moves.go @@ -4,6 +4,7 @@ import ( "fmt" "maps" "rune/pkg/ast" + "slices" ) // liveSet holds the variables read again before they are set. @@ -116,10 +117,14 @@ func (lv *liveness) stmt(stmt ast.Stmt, live liveSet) { lv.own(s.Local, live) lv.expr(s.Initializer, live) - case *ast.DestructureStmt: - lv.destructure(s, s.Initializer, live) - case *ast.ArrayDestructureStmt: - lv.destructure(s, s.Initializer, live) + case *ast.PatternStmt: + bs, es := ast.Bindings(s.Pattern), ast.Exprs(s.Pattern) + for _, b := range slices.Backward(bs) { + lv.own(b.Local, live) + } + + lv.exprs(es, live) + lv.expr(s.Initializer, live) case *ast.BlockStmt: lv.stmts(s.Stmts, live) case *ast.IfStmt: @@ -169,16 +174,6 @@ func (lv *liveness) stmt(stmt ast.Stmt, live liveSet) { } } -func (lv *liveness) destructure(s ast.Stmt, init ast.Expr, live liveSet) { - vars := ast.PatternVars(s) - for i := len(vars) - 1; i >= 0; i-- { - lv.own(vars[i].Local, live) - lv.expr(vars[i].Default, live) - } - - lv.expr(init, live) -} - // loop takes live from after a loop to its head. body takes live from // the head, where an iteration ends, back to it, given what is live past // the loop. @@ -234,6 +229,7 @@ func (lv *liveness) match(m *ast.MatchExpr, live liveSet) { lv.stmt(arm.Body, in) in.add(next) lv.expr(arm.Guard, in) + lv.exprs(ast.Exprs(arm.Pattern), in) next.add(in) } @@ -332,11 +328,9 @@ func (lv *liveness) expr(e ast.Expr, live liveSet) { lv.expr(n.Pairs[i].Value, live) } case *ast.IsExpr: - for i := len(n.Types) - 1; i >= 0; i-- { - if n.Shapes[i] == nil { - lv.holds(n.Value, live) - lv.expr(n.Types[i], live) - } + if es := ast.Exprs(n.Pattern); len(es) > 0 { + lv.holds(n.Value, live) + lv.exprs(es, live) } lv.expr(n.Value, live) diff --git a/pkg/rune/parse_expr.go b/pkg/rune/parse_expr.go index f46b45c..c1a841a 100644 --- a/pkg/rune/parse_expr.go +++ b/pkg/rune/parse_expr.go @@ -188,12 +188,12 @@ func (s *Parser) equality() (ast.Expr, error) { operator := s.previous() if t := operator.TokenType; t == ast.IS || t == ast.BANG_IS { - types, err := s.isTypes() + pat, err := s.isPattern() if err != nil { return nil, err } - expr = ast.NewIsExpr(expr, types, operator, t == ast.BANG_IS) + expr = &ast.IsExpr{Value: expr, Pattern: pat, Token: operator, Negate: t == ast.BANG_IS} continue } @@ -209,33 +209,6 @@ func (s *Parser) equality() (ast.Expr, error) { return expr, nil } -// isTypes parses the types after is or !is, joined by '|': nil, struct, -// enum, or an operand that evaluates to a type. -func (s *Parser) isTypes() ([]ast.Expr, error) { - var types []ast.Expr - - for { - var typ ast.Expr - var err error - - if isTypeKeyword(s.peek().TokenType) { - typ, err = s.typeName() - } else { - typ, err = parseBitXor(s) - } - - if err != nil { - return nil, err - } - - types = append(types, typ) - - if !s.match(ast.PIPE) { - return types, nil - } - } -} - func (s *Parser) comparison() (ast.Expr, error) { return s.binaryLevel((*Parser).rangeExpr, ast.GREATER, ast.GREATER_EQUAL, ast.LESS, ast.LESS_EQUAL) } diff --git a/pkg/rune/parse_match.go b/pkg/rune/parse_match.go index 070565d..f0af0dd 100644 --- a/pkg/rune/parse_match.go +++ b/pkg/rune/parse_match.go @@ -3,8 +3,6 @@ package rune import ( "rune/pkg/ast" "rune/pkg/errors" - "rune/pkg/helpers" - "rune/pkg/value" ) // matchExpr parses the rest of match subject { arms } after "match". The @@ -50,7 +48,17 @@ func (s *Parser) matchExpr() (*ast.MatchExpr, error) { return nil, err } - return &ast.MatchExpr{Keyword: keyword, Subject: subject, Arms: arms}, nil + m := &ast.MatchExpr{Keyword: keyword, Subject: subject, Arms: arms} + + if is, ok := subject.(*ast.IsExpr); ok && !is.Negate { + if t, ok := is.Pattern.(*ast.TypeTestPattern); ok { + if v, ok := t.Type.(*ast.VarExpr); ok { + m.Subject, m.Enum = is.Value, v + } + } + } + + return m, nil } func (s *Parser) matchArm() (ast.MatchArm, error) { @@ -87,236 +95,3 @@ func (s *Parser) armBody() (*ast.BlockStmt, error) { return &ast.BlockStmt{Stmts: []ast.Stmt{ast.NewExprStmt(e)}, Valued: true}, err } - -// matchPattern parses a pattern: alternatives separated by "|". -func (s *Parser) matchPattern() (ast.Pattern, error) { - p, err := s.patternAlt() - if err != nil || !s.check(ast.PIPE) { - return p, err - } - - alts := []ast.Pattern{p} - - for s.match(ast.PIPE) { - alt, err := s.patternAlt() - if err != nil { - return nil, err - } - - alts = append(alts, alt) - } - - return &ast.OrPattern{Alts: alts}, nil -} - -// patternAlt parses a pattern, or a range whose bounds are patterns: a -// number or the name of a constant, which the resolver checks. -func (s *Parser) patternAlt() (ast.Pattern, error) { - var lo ast.Pattern - - if !s.check(ast.DOT_DOT) && !s.check(ast.DOT_DOT_EQUAL) { - var err error - if lo, err = s.patternAtom(); err != nil { - return nil, err - } - } - - if !s.match(ast.DOT_DOT, ast.DOT_DOT_EQUAL) { - return lo, nil - } - - pat := &ast.RangePattern{Op: s.previous(), Lo: lo, Inclusive: s.previous().TokenType == ast.DOT_DOT_EQUAL} - - if s.check(ast.NUMBER) || s.check(ast.MINUS) || s.check(ast.IDENTIFIER) { - var err error - if pat.Hi, err = s.patternAtom(); err != nil { - return nil, err - } - } - - switch { - case pat.Hi == nil && pat.Inclusive: - return nil, errors.NewSyntaxError(s.peek(), "Expect upper bound after '..='.") - case pat.Hi == nil && lo == nil: - return nil, errors.NewSyntaxError(s.peek(), "Expect a bound of the range pattern.") - } - - return pat, nil -} - -func (s *Parser) patternAtom() (ast.Pattern, error) { - switch { - case s.match(ast.NUMBER): - return s.numberPattern(s.previous(), false) - case s.match(ast.MINUS): - minus := s.previous() - if _, err := s.consume(ast.NUMBER, "Expect number after '-'."); err != nil { - return nil, err - } - - p, err := s.numberPattern(s.previous(), true) - if p != nil { - p.(*ast.LiteralPattern).Token = minus - } - - return p, err - case s.match(ast.STRING): - return &ast.LiteralPattern{Token: s.previous(), Value: value.NewString(s.previous().Literal)}, nil - case s.match(ast.BYTES): - return &ast.LiteralPattern{Token: s.previous(), Value: value.NewBytes([]byte(s.previous().Literal))}, nil - case s.match(ast.TRUE, ast.FALSE): - return &ast.LiteralPattern{Token: s.previous(), Value: value.NewBool(s.previous().TokenType == ast.TRUE)}, nil - case s.match(ast.NIL): - return &ast.LiteralPattern{Token: s.previous(), Value: value.NilValue}, nil - case s.match(ast.LEFT_BRACE): - brace := s.previous() - - fields, err := s.fieldPatterns(true) - if err == nil && len(fields) == 0 { - s.errors = append(s.errors, errors.NewSyntaxError(brace, "Expect property name in pattern.")) - } - - return &ast.ObjectPattern{Brace: brace, Fields: fields}, err - case s.match(ast.LEFT_BRACKET): - return s.arrayMatchPattern() - case s.check(ast.MUT): - b, err := s.binding("Expect variable name.") - if err != nil { - return nil, err - } - - return s.typePattern(&ast.BindPattern{Binding: b}) - case s.match(ast.IDENTIFIER): - name := s.previous() - - if name.Lexeme == "_" { - return s.typePattern(&ast.WildcardPattern{Token: name}) - } - - t, err := s.qualifiedName(name) - switch { - case err != nil: - return nil, err - case s.match(ast.LEFT_BRACE): - pat := &ast.StructPattern{Type: t} - pat.Fields, err = s.fieldPatterns(false) - - return pat, err - case t.Case != nil: - return &ast.VariantPattern{Module: t.Module, Enum: t.Name, Variant: *t.Case}, nil - case t.Module != nil: - return &ast.VariantPattern{Enum: *t.Module, Variant: t.Name}, nil - } - - return s.typePattern(&ast.BindPattern{Binding: ast.Binding{Name: name}}) - } - - return nil, errors.NewSyntaxError(s.peek(), "Expect pattern.") -} - -// arrayMatchPattern parses [p, q, ...rest] after the "[". -func (s *Parser) arrayMatchPattern() (ast.Pattern, error) { - pat := &ast.ArrayPattern{Bracket: s.previous()} - - for !s.check(ast.RIGHT_BRACKET) && !s.isAtEnd() { - if s.match(ast.DOT_DOT_DOT) { - b, err := s.binding("Expect variable name.") - if err != nil { - return nil, err - } - - pat.Open = true - if !b.Discards() { - pat.Rest = &ast.BindPattern{Binding: b} - } - - if !s.check(ast.RIGHT_BRACKET) { - return nil, errors.NewSyntaxError(s.peek(), "Rest element must be last.") - } - - break - } - - p, err := s.matchPattern() - if err != nil { - return nil, err - } - - pat.Elems = append(pat.Elems, p) - - if !s.match(ast.COMMA) { - break - } - } - - _, err := s.consume(ast.RIGHT_BRACKET, "Expect ']' after pattern.") - - return pat, err -} - -// typePattern parses an optional 'is T | U' after the pattern p, a name or _. -func (s *Parser) typePattern(p ast.Pattern) (ast.Pattern, error) { - if !s.match(ast.IS) { - return p, nil - } - - types, err := s.typeList() - - return &ast.TypePattern{Inner: p, Types: types}, err -} - -func (s *Parser) numberPattern(tok ast.Token, negate bool) (ast.Pattern, error) { - n, _ := helpers.ParseLiteral(tok.Lexeme) - - if negate && n.IsInt() { - n = value.NewInt(-n.Int()) - } else if negate { - n = value.NewNumber(-n.Float()) - } - - return &ast.LiteralPattern{Token: tok, Value: n}, nil -} - -// fieldPatterns parses key: pattern, ... up to "}"; the "{" has already -// been consumed. A bare key, or mut key, binds the value to its name; -// string keys are for objects only. -func (s *Parser) fieldPatterns(object bool) ([]ast.FieldPattern, error) { - var fields []ast.FieldPattern - - err := s.braceList("Duplicate property name.", "Expect '}' after pattern.", func() (string, ast.Token, error) { - if s.check(ast.MUT) { - b, err := s.binding("Expect property name.") - fields = append(fields, ast.FieldPattern{Key: b.Name, Pattern: &ast.BindPattern{Binding: b}}) - - return b.Name.Lexeme, b.Name, err - } - - if !s.match(ast.IDENTIFIER) && !(object && s.match(ast.STRING)) { - return "", s.peek(), errors.NewSyntaxError(s.peek(), "Expect property name.") - } - - key := s.previous() - quoted := key.TokenType == ast.STRING - - if quoted { - key.Lexeme = key.Literal - } - - if !s.match(ast.COLON) { - if quoted { - return "", key, errors.NewSyntaxError(s.peek(), "Expect ':' after string key.") - } - - fields = append(fields, ast.FieldPattern{Key: key, Pattern: &ast.BindPattern{Binding: ast.Binding{Name: key}}, Shorthand: true}) - - return key.Lexeme, key, nil - } - - p, err := s.matchPattern() - fields = append(fields, ast.FieldPattern{Key: key, Pattern: p}) - - return key.Lexeme, key, err - }) - - return fields, err -} diff --git a/pkg/rune/parse_pattern.go b/pkg/rune/parse_pattern.go index ec1d3fe..7591700 100644 --- a/pkg/rune/parse_pattern.go +++ b/pkg/rune/parse_pattern.go @@ -3,242 +3,487 @@ package rune import ( "rune/pkg/ast" "rune/pkg/errors" + "rune/pkg/helpers" + "rune/pkg/value" ) // bindingOrPattern parses a binding, or a pattern binding the variable // named hidden, which the statement returned destructures. func (s *Parser) bindingOrPattern(hiddenName, msg string) (ast.Binding, ast.Stmt, error) { - hidden := func() ast.Binding { - name := s.previous() - name.TokenType = ast.IDENTIFIER - name.Lexeme = hiddenName + if !s.check(ast.LEFT_BRACE) && !s.check(ast.LEFT_BRACKET) { + b, err := s.binding(msg) + return b, nil, err + } - return ast.Binding{Name: name} + name := s.peek() + name.TokenType = ast.IDENTIFIER + name.Lexeme = hiddenName + + pat, err := s.destructuring() + if err != nil { + return ast.Binding{}, nil, err } - switch { - case s.match(ast.LEFT_BRACE): - d, err := s.pattern(false) - if err != nil { - return ast.Binding{}, nil, err - } + return ast.Binding{Name: name}, &ast.PatternStmt{Pattern: pat, Initializer: ast.NewVarExpr(name)}, nil +} - b := hidden() - d.Initializer = ast.NewVarExpr(b.Name) +// destructuring parses the object or array pattern of a let, a parameter +// or a for-in variable, which must bind something. +func (s *Parser) destructuring() (ast.Pattern, error) { + pat, err := s.patternAtom() + if err != nil { + return nil, err + } - return b, d, nil - case s.match(ast.LEFT_BRACKET): - d, err := s.arrayPattern(false) - if err != nil { - return ast.Binding{}, nil, err - } + if a, ok := pat.(*ast.ArrayPattern); ok && len(a.Elems) == 0 && !a.Open { + s.errors = append(s.errors, errors.NewSyntaxError(s.previous(), "Expect variable name in pattern.")) + } - b := hidden() - d.Initializer = ast.NewVarExpr(b.Name) + return pat, nil +} - return b, d, nil - default: - b, err := s.binding(msg) - return b, nil, err +// patternInitializer parses "= value;" after the pattern of a let. +func (s *Parser) patternInitializer() (ast.Expr, error) { + if _, err := s.consume(ast.EQUAL, "Expect '=' after pattern."); err != nil { + return nil, err + } + + initializer, err := s.expression() + if err != nil { + return nil, err } + + _, err = s.consume(ast.SEMICOLON, "Expect ';' after variable declaration.") + + return initializer, err } -// arrayPattern parses [a, mut b, _, ...rest]; the "[" has already been -// consumed. With mutable, every variable is mutable. -func (s *Parser) arrayPattern(mutable bool) (*ast.ArrayDestructureStmt, error) { - d := &ast.ArrayDestructureStmt{Bracket: s.previous()} +// binding parses "name" or "mut name". +func (s *Parser) binding(msg string) (ast.Binding, error) { + mutable := s.match(ast.MUT) + name, err := s.consume(ast.IDENTIFIER, msg) - sawDefault := false + return ast.Binding{Name: name, Mutable: mutable}, err +} - for !s.check(ast.RIGHT_BRACKET) && !s.isAtEnd() { - rest := s.match(ast.DOT_DOT_DOT) +// bindingEnd returns the index of the token after a binding starting i +// tokens ahead, or -1 if there is none. +func (s *Parser) bindingEnd(i int) int { + if s.peekAt(i) == ast.MUT { + i++ + } - b, err := s.binding("Expect variable name.") + if s.peekAt(i) != ast.IDENTIFIER { + return -1 + } + + return i + 1 +} + +// matchPattern parses a pattern: alternatives separated by "|". +func (s *Parser) matchPattern() (ast.Pattern, error) { + return s.alternatives(s.patternAlt) +} + +func (s *Parser) alternatives(alt func() (ast.Pattern, error)) (ast.Pattern, error) { + p, err := alt() + if err != nil || !s.check(ast.PIPE) { + return p, err + } + + alts := []ast.Pattern{p} + + for s.match(ast.PIPE) { + a, err := alt() if err != nil { return nil, err } - b.Mutable = b.Mutable || mutable - skip := b.Discards() + alts = append(alts, a) + } + + return &ast.OrPattern{Alts: alts}, nil +} - def, err := s.patternDefault(rest || skip) - if err != nil { +// patternAlt parses a pattern, or a range whose bounds are patterns: a +// number or the name of a constant, which the resolver checks. +func (s *Parser) patternAlt() (ast.Pattern, error) { + var lo ast.Pattern + + if !s.check(ast.DOT_DOT) && !s.check(ast.DOT_DOT_EQUAL) { + var err error + if lo, err = s.patternAtom(); err != nil { return nil, err } + } + + return s.rangeTail(lo) +} + +// rangeTail parses the rest of a range pattern from lo, if one follows. +func (s *Parser) rangeTail(lo ast.Pattern) (ast.Pattern, error) { + if !s.match(ast.DOT_DOT, ast.DOT_DOT_EQUAL) { + return lo, nil + } + + pat := &ast.RangePattern{Op: s.previous(), Lo: lo, Inclusive: s.previous().TokenType == ast.DOT_DOT_EQUAL} - if def == nil && sawDefault && !rest { - s.errors = append(s.errors, errors.NewSyntaxError(b.Name, "An element without a default cannot follow one with a default.")) + if s.check(ast.NUMBER) || s.check(ast.MINUS) || s.check(ast.IDENTIFIER) { + var err error + if pat.Hi, err = s.patternAtom(); err != nil { + return nil, err } + } - sawDefault = sawDefault || def != nil + switch { + case pat.Hi == nil && pat.Inclusive: + return nil, errors.NewSyntaxError(s.peek(), "Expect upper bound after '..='.") + case pat.Hi == nil && lo == nil: + return nil, errors.NewSyntaxError(s.peek(), "Expect a bound of the range pattern.") + } - v := &ast.PatternVar{Binding: b, Default: def} + return pat, nil +} - switch { - case rest: - d.Rest = v - case skip: - d.Elems = append(d.Elems, nil) - default: - d.Elems = append(d.Elems, v) +func (s *Parser) patternAtom() (ast.Pattern, error) { + switch { + case s.match(ast.NUMBER): + return s.numberPattern(s.previous(), false) + case s.match(ast.MINUS): + minus := s.previous() + if _, err := s.consume(ast.NUMBER, "Expect number after '-'."); err != nil { + return nil, err } - if rest && !s.check(ast.RIGHT_BRACKET) { - return nil, errors.NewSyntaxError(s.peek(), "Rest element must be last.") + p, err := s.numberPattern(s.previous(), true) + if p != nil { + p.(*ast.LiteralPattern).Token = minus } - if !s.match(ast.COMMA) { - break + return p, err + case s.match(ast.STRING): + return &ast.LiteralPattern{Token: s.previous(), Value: value.NewString(s.previous().Literal)}, nil + case s.match(ast.BYTES): + return &ast.LiteralPattern{Token: s.previous(), Value: value.NewBytes([]byte(s.previous().Literal))}, nil + case s.match(ast.TRUE, ast.FALSE): + return &ast.LiteralPattern{Token: s.previous(), Value: value.NewBool(s.previous().TokenType == ast.TRUE)}, nil + case s.match(ast.NIL): + return &ast.LiteralPattern{Token: s.previous(), Value: value.NilValue}, nil + case s.match(ast.LEFT_BRACE): + return s.objectPattern() + case s.match(ast.LEFT_BRACKET): + return s.arrayPattern() + case s.check(ast.MUT): + b, err := s.binding("Expect variable name.") + if err != nil { + return nil, err + } + + return s.isTail(&ast.BindPattern{Binding: b}) + case s.match(ast.IDENTIFIER): + name := s.previous() + + if name.Lexeme == "_" { + return s.isTail(&ast.WildcardPattern{Token: name}) } + + t, err := s.qualifiedName(name) + if err != nil { + return nil, err + } + + if s.match(ast.LEFT_BRACE) { + return s.structPattern(t) + } + + if t.Module != nil { + return namePattern(t), nil + } + + return s.isTail(namePattern(t)) } - if len(d.Elems) == 0 && d.Rest == nil { - s.errors = append(s.errors, errors.NewSyntaxError(s.peek(), "Expect variable name in pattern.")) + return nil, errors.NewSyntaxError(s.peek(), "Expect pattern.") +} + +// namePattern is the pattern of a name: a variant or a constant of a +// module if qualified, else a binding, or a constant the resolver finds. +func namePattern(t *ast.VarExpr) ast.Pattern { + switch { + case t.Case != nil: + return &ast.VariantPattern{Module: t.Module, Enum: t.Name, Variant: *t.Case} + case t.Module != nil: + return &ast.VariantPattern{Enum: *t.Module, Variant: t.Name} } - _, err := s.consume(ast.RIGHT_BRACKET, "Expect ']' after pattern.") + return &ast.BindPattern{Binding: ast.Binding{Name: t.Name}} +} + +func (s *Parser) structPattern(t *ast.VarExpr) (ast.Pattern, error) { + pat := &ast.StructPattern{Type: t} - return d, err + var err error + pat.Fields, _, err = s.fieldPatterns(false) + + return pat, err } -// pattern parses { a, mut b, c: d, "e": f, ...rest }; the "{" has -// already been consumed. With mutable, every variable is mutable. -func (s *Parser) pattern(mutable bool) (*ast.DestructureStmt, error) { - d := &ast.DestructureStmt{Brace: s.previous()} +// objectPattern parses { key: pattern = default, ..., ...rest } after the "{". +func (s *Parser) objectPattern() (ast.Pattern, error) { + pat := &ast.ObjectPattern{Brace: s.previous()} + + var err error + pat.Fields, pat.Rest, err = s.fieldPatterns(true) - for !s.check(ast.RIGHT_BRACE) && !s.isAtEnd() { + if err == nil && len(pat.Fields) == 0 && pat.Rest == nil { + s.errors = append(s.errors, errors.NewSyntaxError(pat.Brace, "Expect property name in pattern.")) + } + + return pat, err +} + +// arrayPattern parses [p, q = default, ...rest] after the "[". +func (s *Parser) arrayPattern() (ast.Pattern, error) { + pat := &ast.ArrayPattern{Bracket: s.previous()} + + sawDefault := false + + for !s.check(ast.RIGHT_BRACKET) && !s.isAtEnd() { if s.match(ast.DOT_DOT_DOT) { - b, err := s.binding("Expect variable name.") + b, err := s.restBinding(ast.RIGHT_BRACKET) if err != nil { return nil, err } - if _, err := s.patternDefault(true); err != nil { - return nil, err + pat.Open = true + if !b.Discards() { + pat.Rest = &ast.BindPattern{Binding: b} } - b.Mutable = b.Mutable || mutable - d.Rest = &ast.PatternVar{Binding: b} + break + } - if !s.check(ast.RIGHT_BRACE) { - return nil, errors.NewSyntaxError(s.peek(), "Rest element must be last.") - } + start := s.peek() - break + p, err := s.matchPattern() + if err != nil { + return nil, err } - f, err := s.patternField() + p, err = s.patternDefault(p) if err != nil { return nil, err } - f.Mutable = f.Mutable || mutable + _, isDefault := p.(*ast.DefaultPattern) + if !isDefault && sawDefault { + s.errors = append(s.errors, errors.NewSyntaxError(start, "An element without a default cannot follow one with a default.")) + } - d.Fields = append(d.Fields, f) + sawDefault = sawDefault || isDefault + pat.Elems = append(pat.Elems, p) if !s.match(ast.COMMA) { break } } - if len(d.Fields) == 0 && d.Rest == nil { - s.errors = append(s.errors, errors.NewSyntaxError(s.peek(), "Expect property name in pattern.")) + _, err := s.consume(ast.RIGHT_BRACKET, "Expect ']' after pattern.") + + return pat, err +} + +// restBinding parses the name after "..." of a rest element, which must +// close its pattern. +func (s *Parser) restBinding(closer ast.TokenType) (ast.Binding, error) { + b, err := s.binding("Expect variable name.") + if err != nil { + return b, err + } + + if s.check(ast.EQUAL) { + return b, errors.NewSyntaxError(s.peek(), "A rest element or _ cannot have a default.") } - _, err := s.consume(ast.RIGHT_BRACE, "Expect '}' after pattern.") + if !s.check(closer) { + return b, errors.NewSyntaxError(s.peek(), "Rest element must be last.") + } - return d, err + return b, nil } -// patternDefault parses the "= value" of the pattern element just parsed, -// if any; a rest element or _ cannot have one. -func (s *Parser) patternDefault(notAllowed bool) (ast.Expr, error) { +// patternDefault parses the "= value" after p, if any, giving p with its +// default; _ cannot have one. +func (s *Parser) patternDefault(p ast.Pattern) (ast.Pattern, error) { if !s.match(ast.EQUAL) { - return nil, nil + return p, nil } - if notAllowed { + if _, ok := p.(*ast.WildcardPattern); ok { return nil, errors.NewSyntaxError(s.previous(), "A rest element or _ cannot have a default.") } - return s.expressionWithStructs(structsAll) + def, err := s.expressionWithStructs(structsAll) + + return &ast.DefaultPattern{Pattern: p, Default: def}, err } -func (s *Parser) patternField() (ast.DestructureField, error) { - f, err := s.patternKey() - if err != nil { - return f, err +// isTail parses an optional 'is P' after the pattern p, a name or _. +func (s *Parser) isTail(p ast.Pattern) (ast.Pattern, error) { + if !s.match(ast.IS) { + return p, nil } - f.Default, err = s.patternDefault(f.Discards()) + test, err := s.isPattern() - return f, err + return &ast.IsPattern{Inner: p, Test: test}, err } -func (s *Parser) patternKey() (ast.DestructureField, error) { - if s.check(ast.MUT) { - b, err := s.binding("Expect property name.") - return ast.DestructureField{Key: b.Name, PatternVar: ast.PatternVar{Binding: b}}, err +// isPattern parses the pattern after 'is', in which a bare name is a type: +// alternatives separated by "|". +func (s *Parser) isPattern() (ast.Pattern, error) { + return s.alternatives(s.isAlt) +} + +func (s *Parser) isAlt() (ast.Pattern, error) { + tok := s.peek() + + switch t := tok.TokenType; { + case isTypeKeyword(t): + return &ast.TypeTestPattern{Token: tok, Type: &ast.VarExpr{Name: s.advance()}}, nil + case t == ast.IDENTIFIER && s.peek().Lexeme != "_" && s.peekAt(1) != ast.IS: + v, err := s.qualifiedName(s.advance()) + if err != nil { + return nil, err + } + + switch { + case s.check(ast.DOT_DOT) || s.check(ast.DOT_DOT_EQUAL): + return s.rangeTail(namePattern(v)) + case s.check(ast.LEFT_BRACE) && s.structPatternAhead(): + s.advance() + return s.structPattern(v) + } + + return &ast.TypeTestPattern{Token: tok, Type: v}, nil + case t == ast.LEFT_PAREN: + e, err := parseBitXor(s) + return &ast.TypeTestPattern{Token: tok, Type: e}, err } - if !s.match(ast.IDENTIFIER, ast.STRING) { - return ast.DestructureField{}, errors.NewSyntaxError(s.peek(), "Expect property name.") + return s.patternAlt() +} + +// structPatternAhead reports whether the "{" ahead, after a type on the +// right of is, opens the fields of a struct pattern rather than a body +// or the arms of a match: no "=>" or ";" in it, and, where "Name {" +// opens a body, a body or an operator after it. +func (s *Parser) structPatternAhead() bool { + depth := 0 + + for i := 0; ; i++ { + switch s.peekAt(i) { + case ast.EOF: + return false + case ast.LEFT_BRACE, ast.LEFT_PAREN, ast.LEFT_BRACKET: + depth++ + case ast.ARROW, ast.SEMICOLON: + if depth == 1 { + return false + } + case ast.RIGHT_BRACE, ast.RIGHT_PAREN, ast.RIGHT_BRACKET: + if depth--; depth > 0 { + continue + } + + if s.structs == structsAll { + return true + } + + switch s.peekAt(i + 1) { + case ast.LEFT_BRACE, ast.AND, ast.OR, ast.RIGHT_PAREN: + return true + } + + return false + } } +} - key := s.previous() - quoted := key.TokenType == ast.STRING +func (s *Parser) numberPattern(tok ast.Token, negate bool) (ast.Pattern, error) { + n, _ := helpers.ParseLiteral(tok.Lexeme) - if quoted { - key.Lexeme = key.Literal + if negate && n.IsInt() { + n = value.NewInt(-n.Int()) + } else if negate { + n = value.NewNumber(-n.Float()) } - if !s.match(ast.COLON) { - if quoted { - return ast.DestructureField{}, errors.NewSyntaxError(s.peek(), "Expect ':' after string key.") + return &ast.LiteralPattern{Token: tok, Value: n}, nil +} + +// fieldPatterns parses key: pattern, ... up to "}"; the "{" has already +// been consumed. A bare key, or mut key, binds the value to its name. +// Objects only have string keys, defaults and a rest, which binds the +// other keys. +func (s *Parser) fieldPatterns(object bool) ([]ast.FieldPattern, *ast.BindPattern, error) { + var fields []ast.FieldPattern + var rest *ast.BindPattern + + err := s.braceList("Duplicate property name.", "Expect '}' after pattern.", func() (string, ast.Token, error) { + if object && s.match(ast.DOT_DOT_DOT) { + b, err := s.restBinding(ast.RIGHT_BRACE) + if err == nil && !b.Discards() { + rest = &ast.BindPattern{Binding: b} + } + + return "", b.Name, err } - return ast.DestructureField{Key: key, PatternVar: ast.PatternVar{Binding: ast.Binding{Name: key}}}, nil - } + f, err := s.fieldPattern(object) + if err != nil { + return "", f.Key, err + } - b, err := s.binding("Expect variable name.") + if object { + f.Pattern, err = s.patternDefault(f.Pattern) + } - return ast.DestructureField{Key: key, PatternVar: ast.PatternVar{Binding: b}}, err -} + fields = append(fields, f) -// binding parses "name" or "mut name". -func (s *Parser) binding(msg string) (ast.Binding, error) { - mutable := s.match(ast.MUT) - name, err := s.consume(ast.IDENTIFIER, msg) + // A key may repeat, to bind its value and take it apart too. + return "", f.Key, err + }) - return ast.Binding{Name: name, Mutable: mutable}, err + return fields, rest, err } -// bindingEnd returns the index of the token after a binding starting i -// tokens ahead, or -1 if there is none. -func (s *Parser) bindingEnd(i int) int { - if s.peekAt(i) == ast.MUT { - i++ +func (s *Parser) fieldPattern(object bool) (ast.FieldPattern, error) { + if s.check(ast.MUT) { + b, err := s.binding("Expect property name.") + return ast.FieldPattern{Key: b.Name, Pattern: &ast.BindPattern{Binding: b}}, err } - if s.peekAt(i) != ast.IDENTIFIER { - return -1 + if !s.match(ast.IDENTIFIER) && !(object && s.match(ast.STRING)) { + return ast.FieldPattern{Key: s.peek()}, errors.NewSyntaxError(s.peek(), "Expect property name.") } - return i + 1 -} + key := s.previous() + quoted := key.TokenType == ast.STRING -// patternInitializer parses "= value;" after the pattern of a let. -func (s *Parser) patternInitializer() (ast.Expr, error) { - if _, err := s.consume(ast.EQUAL, "Expect '=' after pattern."); err != nil { - return nil, err + if quoted { + key.Lexeme = key.Literal } - initializer, err := s.expression() - if err != nil { - return nil, err + if !s.match(ast.COLON) { + if quoted { + return ast.FieldPattern{Key: key}, errors.NewSyntaxError(s.peek(), "Expect ':' after string key.") + } + + return ast.FieldPattern{Key: key, Pattern: &ast.BindPattern{Binding: ast.Binding{Name: key}, Shorthand: true}}, nil } - _, err = s.consume(ast.SEMICOLON, "Expect ';' after variable declaration.") + p, err := s.matchPattern() - return initializer, err + return ast.FieldPattern{Key: key, Pattern: p}, err } diff --git a/pkg/rune/parse_stmt.go b/pkg/rune/parse_stmt.go index 983b2b8..23aeb5e 100644 --- a/pkg/rune/parse_stmt.go +++ b/pkg/rune/parse_stmt.go @@ -349,26 +349,21 @@ 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.match(ast.LEFT_BRACE) { - d, err := s.pattern(mutable) + if s.check(ast.LEFT_BRACE) || s.check(ast.LEFT_BRACKET) { + pat, err := s.destructuring() if err != nil { return nil, err } - d.Initializer, err = s.patternInitializer() - - return d, err - } - - if s.match(ast.LEFT_BRACKET) { - d, err := s.arrayPattern(mutable) - if err != nil { - return nil, err + if mutable { + for _, b := range ast.Bindings(pat) { + b.Mutable = true + } } - d.Initializer, err = s.patternInitializer() + init, err := s.patternInitializer() - return d, err + return &ast.PatternStmt{Pattern: pat, Initializer: init}, err } name, err := s.consume(ast.IDENTIFIER, "Expect variable name.") @@ -436,14 +431,7 @@ func (s *Parser) statement() (ast.Stmt, error) { } if s.match(ast.DEFER) { - keyword := s.previous() - - body, err := s.body("'defer'") - if err != nil { - return nil, err - } - - return &ast.DeferStmt{Keyword: keyword, Body: body}, nil + return s.deferStatement() } if s.atTryStatement() { @@ -604,6 +592,33 @@ func hasValue(values []ast.Expr) bool { return slices.ContainsFunc(values, func(e ast.Expr) bool { return e != nil }) } +// deferStatement parses defer { ... } or defer expression; after "defer". +func (s *Parser) deferStatement() (ast.Stmt, error) { + keyword := s.previous() + + if s.check(ast.LEFT_BRACE) { + body, err := s.statement() + if b, ok := body.(*ast.BlockStmt); ok && len(b.Stmts) == 1 { + if _, ok := b.Stmts[0].(*ast.ExprStmt); ok { + s.errors = append(s.errors, errors.NewSyntaxError(keyword, "Defer one expression without braces: defer expression;")) + } + } + + return &ast.DeferStmt{Keyword: keyword, Body: body}, err + } + + e, err := s.expression() + if err != nil { + return nil, err + } + + if _, err := s.consume(ast.SEMICOLON, "Expect ';' after deferred expression."); err != nil { + return nil, err + } + + return &ast.DeferStmt{Keyword: keyword, Body: ast.NewBlockStmt([]ast.Stmt{ast.NewExprStmt(e)})}, nil +} + func (s *Parser) ifStatement() (*ast.IfStmt, error) { condition, err := s.expressionWithStructs(structsNone) if err != nil { diff --git a/pkg/rune/resolve_match.go b/pkg/rune/resolve_match.go index 9c25f41..e88cb56 100644 --- a/pkg/rune/resolve_match.go +++ b/pkg/rune/resolve_match.go @@ -15,9 +15,17 @@ func (p *Resolver) VisitMatchStmt(stmt *ast.MatchStmt) error { func (p *Resolver) VisitMatchExpr(expr *ast.MatchExpr) (value.Value, error) { p.resolveExpr(expr.Subject) + if expr.Enum != nil { + expr.EnumShape = p.enumNamed(expr.Enum) + } + for i := range expr.Arms { arm := &expr.Arms[i] + if expr.Enum != nil { + arm.Pattern = variantArm(arm.Pattern, expr.Enum, expr.EnumShape) + } + if i > 0 && reachedAll(&expr.Arms[i-1]) { p.error(arm.Token, "Unreachable match arm.") } @@ -41,6 +49,56 @@ func (p *Resolver) VisitMatchExpr(expr *ast.MatchExpr) (value.Value, error) { return value.NilValue, nil } +// enumNamed returns the enum t names, reporting it if it names none. +func (p *Resolver) enumNamed(t *ast.VarExpr) *value.Shape { + s := p.typeNamed(t) + if s == nil || !s.Enum || s.Builtin || s.Parent != nil { + p.error(t.Name, "'"+qualified(t.Module, t.Name)+"' is not an enum; match x is Enum { ... } names its variants bare.") + return nil + } + + return s +} + +// variantArm returns the pattern of an arm of a match on the enum e, of +// type enum unless nil, with the bare names of its variants qualified. +func variantArm(pat ast.Pattern, e *ast.VarExpr, enum *value.Shape) ast.Pattern { + switch n := pat.(type) { + case *ast.BindPattern: + if enum != nil && hasFields(enum, n.Name.Lexeme) { + return &ast.IsPattern{Inner: &ast.WildcardPattern{Token: n.Name}, Test: &ast.TypeTestPattern{Token: n.Name, Type: variantOf(e, n.Name)}} + } + + return namePattern(variantOf(e, n.Name)) + case *ast.StructPattern: + if n.Type.Module == nil { + n.Type = variantOf(e, n.Type.Name) + } + case *ast.OrPattern: + for i, alt := range n.Alts { + n.Alts[i] = variantArm(alt, e, enum) + } + } + + return pat +} + +func hasFields(enum *value.Shape, variant string) bool { + v, ok := enum.Variant(variant) + return ok && v.Kind() == value.Type +} + +// variantOf is the name of the variant v of the enum e, as Enum.v or m.Enum.v. +func variantOf(e *ast.VarExpr, v ast.Token) *ast.VarExpr { + if e.Module != nil { + return &ast.VarExpr{Module: e.Module, Name: e.Name, Case: &v} + } + + enum := e.Name + + return &ast.VarExpr{Module: &enum, Name: v} +} + // checkExhaustive reports a match without a catch-all arm that names // variants of an enum but not all of them. A variant is covered by an arm // without a guard that matches all its values. @@ -71,18 +129,16 @@ func (p *Resolver) checkExhaustive(expr *ast.MatchExpr) { if n.Shape != nil && n.Shape.Parent != nil { cover(n.Shape.Parent, value.NewType(n.Shape), full && fieldsIrrefutable(n.Fields)) } - case *ast.TypePattern: - full = full && ast.Irrefutable(n.Inner) - - for _, t := range n.Shapes { - switch { - case t == nil: - case t.Parent != nil: - cover(t.Parent, value.NewType(t), full) - case t.Enum && !t.Builtin: - for _, v := range t.Variants { - cover(t, v, full) - } + case *ast.IsPattern: + visit(n.Test, full && ast.Irrefutable(n.Inner)) + case *ast.TypeTestPattern: + switch t := n.Shape; { + case t == nil: + case t.Parent != nil: + cover(t.Parent, value.NewType(t), full) + case t.Enum && !t.Builtin: + for _, v := range t.Variants { + cover(t, v, full) } } } @@ -125,180 +181,3 @@ func fieldsIrrefutable(fields []ast.FieldPattern) bool { func reachedAll(arm *ast.MatchArm) bool { return arm.Guard == nil && ast.Irrefutable(arm.Pattern) } - -// resolvePattern returns pat with each bare name of a constant replaced by -// a test of its value; any other bare name binds. -func (p *Resolver) resolvePattern(pat ast.Pattern) ast.Pattern { - switch n := pat.(type) { - case *ast.BindPattern: - if l := p.constNamed(n.Name.Lexeme); l != nil && !n.Mutable { - return p.constPattern(n.Name, l) - } - - p.checkBind(n) - case *ast.TypePattern: - n.Shapes = p.resolveTypes(n.Types) - - if b, ok := n.Inner.(*ast.BindPattern); ok { - p.checkBind(b) - } - case *ast.RangePattern: - n.Lo, n.Hi = p.rangeBound(n.Op, n.Lo), p.rangeBound(n.Op, n.Hi) - - lo, _ := n.Lo.(*ast.LiteralPattern) - hi, _ := n.Hi.(*ast.LiteralPattern) - - if lo != nil && hi != nil && lo.Value.IsNumber() && hi.Value.IsNumber() { - if c, _ := value.CompareNum(lo.Value, hi.Value); c > 0 || c == 0 && !n.Inclusive { - p.error(n.Op, "Range pattern matches no number.") - } - } - case *ast.OrPattern: - for i, alt := range n.Alts { - n.Alts[i] = p.resolvePattern(alt) - - if bs := ast.Bindings(n.Alts[i]); len(bs) > 0 { - p.error(bs[0].Name, "Cannot bind variables in '|' patterns.") - } - } - case *ast.StructPattern: - if t := n.Type; t.Module != nil { - p.resolveExpr(t) - n.Shape = p.structType(t) - } else if n.Shape = p.structNamed(t.Name.Lexeme); n.Shape == nil { - p.error(t.Name, "'"+t.Name.Lexeme+"' is not a struct.") - } - - if n.Shape != nil && n.Shape.Enum { - p.error(n.Type.Name, notStruct(n.Shape)) - } - - for _, f := range n.Fields { - if n.Shape != nil && n.Shape.Index(f.Key.Lexeme) < 0 { - p.noField(f.Key, n.Shape) - } - } - - p.resolveFields(n.Fields) - case *ast.ObjectPattern: - p.resolveFields(n.Fields) - case *ast.ArrayPattern: - for i, e := range n.Elems { - n.Elems[i] = p.resolvePattern(e) - } - - if n.Rest != nil { - p.checkBind(n.Rest) - } - case *ast.VariantPattern: - return p.resolveVariantPattern(n) - } - - return pat -} - -// rangeBound returns the bound b of the range pattern at op, if it has -// one, as the test of its number. -func (p *Resolver) rangeBound(op ast.Token, b ast.Pattern) ast.Pattern { - if b == nil { - return nil - } - - errs := len(p.errors) - b = p.resolvePattern(b) - - // A name that is no constant is reported once, by what it is not. - if lit, ok := b.(*ast.LiteralPattern); (!ok || !lit.Value.IsNumber()) && len(p.errors) == errs { - p.error(op, "A bound of a range pattern must be a number or a constant holding one.") - } - - return b -} - -// resolveTypes returns the type each of types names, reporting those -// that name something else; a missing module member is reported already. -func (p *Resolver) resolveTypes(types []*ast.VarExpr) []*value.Shape { - shapes := make([]*value.Shape, len(types)) - - for i, t := range types { - if shapes[i] = p.typeNamed(t); shapes[i] == nil && (t.Module == nil || t.Local != nil) { - p.error(t.Name, "'"+qualified(t.Module, t.Name)+"' is not a type.") - } - } - - return shapes -} - -// typeNamed resolves t and returns the type it names: a struct type, or -// a built-in one such as string; nil for anything else. -func (p *Resolver) typeNamed(t *ast.VarExpr) *value.Shape { - if s := p.kindType(t); s != nil { - return s - } - - p.resolveExpr(t) - - return p.structs[t.Local] -} - -var kindTypes = func() map[string]*value.Shape { - ts := map[string]*value.Shape{} - for name, k := range builtinKinds { - ts[name] = &value.Shape{Name: name, Builtin: true, Kind: k} - } - - ts["nil"] = &value.Shape{Name: "nil", Builtin: true, Kind: value.Nil} - ts["struct"] = &value.Shape{Name: "struct", Builtin: true, Kind: value.Type} - ts["enum"] = &value.Shape{Name: "enum", Builtin: true, Kind: value.Type, Enum: true} - - return ts -}() - -// kindType returns the built-in type t names, as in v is string, unless -// a declaration or an import hides it. -func (p *Resolver) kindType(t ast.Expr) *value.Shape { - v, ok := t.(*ast.VarExpr) - if !ok || v.Module != nil { - return nil - } - - name := v.Name.Lexeme - if p.lookupScopes(name) != nil || p.mod.topLevel[name] != nil || p.mod.imports[name] != nil { - return nil - } - - return kindTypes[name] -} - -func (p *Resolver) resolveFields(fields []ast.FieldPattern) { - for i := range fields { - if f := &fields[i]; f.Shorthand { - p.checkBind(f.Pattern.(*ast.BindPattern)) - } else { - f.Pattern = p.resolvePattern(f.Pattern) - } - } -} - -func (p *Resolver) checkBind(n *ast.BindPattern) { - if name := n.Name.Lexeme; p.structNamed(name) != nil { - p.error(n.Name, "'"+name+"' is a struct type; test it with '_ is "+name+"'.") - } -} - -// structNamed returns the struct type name denotes here, if it is one. -func (p *Resolver) structNamed(name string) *value.Shape { - if p.lookupScopes(name) != nil { - return nil - } - - if l := p.mod.topLevel[name]; l != nil { - return p.structs[l] - } - - if v, ok := builtinValues()[name]; ok && v.Kind() == value.Type { - return v.TypeShape() - } - - return nil -} diff --git a/pkg/rune/resolve_pattern.go b/pkg/rune/resolve_pattern.go new file mode 100644 index 0000000..710ee67 --- /dev/null +++ b/pkg/rune/resolve_pattern.go @@ -0,0 +1,387 @@ +package rune + +import ( + "rune/pkg/ast" + "rune/pkg/value" +) + +func (p *Resolver) VisitPatternStmt(stmt *ast.PatternStmt) error { + for _, b := range ast.Bindings(stmt.Pattern) { + b.Local = p.declare(*b) + } + + p.resolveExpr(stmt.Initializer) + p.resolveDestructuring(stmt.Pattern) + + return nil +} + +// resolveDestructuring checks pat only takes a value apart, and defines +// its variables in order, each once its default is resolved. +func (p *Resolver) resolveDestructuring(pat ast.Pattern) { + switch n := pat.(type) { + case *ast.WildcardPattern: + case *ast.BindPattern: + p.define(n.Name) + case *ast.DefaultPattern: + p.resolveExpr(n.Default) + p.resolveDestructuring(n.Pattern) + case *ast.ObjectPattern: + for _, f := range n.Fields { + p.resolveDestructuring(f.Pattern) + } + + if n.Rest != nil { + p.define(n.Rest.Name) + } + case *ast.ArrayPattern: + for _, e := range n.Elems { + p.resolveDestructuring(e) + } + + if n.Rest != nil { + p.define(n.Rest.Name) + } + default: + p.error(patternToken(pat), "This pattern only takes a value apart; test the value with match or 'is'.") + } +} + +// condScope resolves the condition cond and then body, in a scope of +// their own when an is test in cond may bind variables. +func (p *Resolver) condScope(cond ast.Expr, body func()) { + tests := condTests(cond) + + binds := false + for _, t := range tests { + t.Cond = true + binds = binds || len(ast.Bindings(t.Pattern)) > 0 + } + + if binds { + p.beginScope() + defer p.endScope() + } + + p.resolveExpr(cond) + body() +} + +// condTests returns the is tests of the condition cond that hold when it +// does: those it is made of with &&. +func condTests(cond ast.Expr) []*ast.IsExpr { + switch n := unwrap(cond).(type) { + case *ast.IsExpr: + if !n.Negate { + return []*ast.IsExpr{n} + } + case *ast.LogicalExpr: + if n.Op.TokenType == ast.AND { + return append(condTests(n.Left), condTests(n.Right)...) + } + } + + return nil +} + +func (p *Resolver) VisitIsExpr(expr *ast.IsExpr) (value.Value, error) { + p.resolveExpr(expr.Value) + expr.Pattern = p.resolveIsTest(expr.Pattern, true) + + bs := ast.Bindings(expr.Pattern) + switch { + case len(bs) == 0: + case expr.Negate: + p.error(bs[0].Name, "Cannot bind variables in a '!is' test.") + case !expr.Cond: + p.error(bs[0].Name, "Only an if or while condition can bind variables with 'is'.") + default: + for _, b := range bs { + b.Local = p.declare(*b) + p.define(b.Name) + } + } + + return value.NilValue, nil +} + +// resolvePattern returns pat with each bare name of a constant replaced by +// a test of its value; any other bare name binds. +func (p *Resolver) resolvePattern(pat ast.Pattern) ast.Pattern { + switch n := pat.(type) { + case *ast.BindPattern: + if l := p.constNamed(n.Name.Lexeme); l != nil && !n.Mutable && !n.Shorthand { + return p.constPattern(n.Name, l) + } + + p.checkBind(n) + case *ast.IsPattern: + if b, ok := n.Inner.(*ast.BindPattern); ok { + p.checkBind(b) + } + + n.Test = p.resolveIsTest(n.Test, false) + case *ast.DefaultPattern: + n.Pattern = p.resolvePattern(n.Pattern) + p.resolveExpr(n.Default) + case *ast.RangePattern: + n.Lo, n.Hi = p.rangeBound(n.Op, n.Lo), p.rangeBound(n.Op, n.Hi) + + lo, _ := n.Lo.(*ast.LiteralPattern) + hi, _ := n.Hi.(*ast.LiteralPattern) + + if lo != nil && hi != nil && lo.Value.IsNumber() && hi.Value.IsNumber() { + if c, _ := value.CompareNum(lo.Value, hi.Value); c > 0 || c == 0 && !n.Inclusive { + p.error(n.Op, "Range pattern matches no number.") + } + } + case *ast.OrPattern: + for i, alt := range n.Alts { + n.Alts[i] = p.resolvePattern(alt) + + if bs := ast.Bindings(n.Alts[i]); len(bs) > 0 { + p.error(bs[0].Name, "Cannot bind variables in '|' patterns.") + } + } + case *ast.StructPattern: + if t := n.Type; t.Module != nil { + p.resolveExpr(t) + n.Shape = p.structType(t) + } else if n.Shape = p.structNamed(t.Name.Lexeme); n.Shape == nil { + p.error(t.Name, "'"+t.Name.Lexeme+"' is not a struct.") + } + + if n.Shape != nil && n.Shape.Enum { + p.error(n.Type.Name, notStruct(n.Shape)) + } + + for _, f := range n.Fields { + if n.Shape != nil && n.Shape.Index(f.Key.Lexeme) < 0 { + p.noField(f.Key, n.Shape) + } + } + + p.resolveFields(n.Fields) + case *ast.ObjectPattern: + p.resolveFields(n.Fields) + + if n.Rest != nil { + p.checkBind(n.Rest) + } + case *ast.ArrayPattern: + for i, e := range n.Elems { + n.Elems[i] = p.resolvePattern(e) + } + + if n.Rest != nil { + p.checkBind(n.Rest) + } + case *ast.VariantPattern: + return p.resolveVariantPattern(n) + } + + return pat +} + +// rangeBound returns the bound b of the range pattern at op, if it has +// one, as the test of its number. +func (p *Resolver) rangeBound(op ast.Token, b ast.Pattern) ast.Pattern { + if b == nil { + return nil + } + + errs := len(p.errors) + b = p.resolvePattern(b) + + // A name that is no constant is reported once, by what it is not. + if lit, ok := b.(*ast.LiteralPattern); (!ok || !lit.Value.IsNumber()) && len(p.errors) == errs { + p.error(op, "A bound of a range pattern must be a number or a constant holding one.") + } + + return b +} + +// resolveIsTest returns the pattern pat on the right of is, in which a +// bare name is a type; with dynamic, one that names none is evaluated +// when the test runs. +func (p *Resolver) resolveIsTest(pat ast.Pattern, dynamic bool) ast.Pattern { + switch n := pat.(type) { + case *ast.OrPattern: + for i, alt := range n.Alts { + n.Alts[i] = p.resolveIsTest(alt, dynamic) + + if bs := ast.Bindings(n.Alts[i]); len(bs) > 0 { + p.error(bs[0].Name, "Cannot bind variables in '|' patterns.") + } + } + + return n + case *ast.TypeTestPattern: + return p.resolveTypeTest(n, dynamic) + } + + return p.resolvePattern(pat) +} + +// resolveTypeTest returns the test of the type n names, or of the value +// a constant or a variant without fields is. +func (p *Resolver) resolveTypeTest(n *ast.TypeTestPattern, dynamic bool) ast.Pattern { + t, ok := n.Type.(*ast.VarExpr) + if !ok { + p.resolveExpr(n.Type) + return n + } + + if p.namesValue(t) { + return p.resolvePattern(namePattern(t)) + } + + if n.Shape = p.typeNamed(t); n.Shape != nil { + return n + } + + if !dynamic && (t.Module == nil || t.Local != nil) { + p.error(t.Name, "'"+qualified(t.Module, t.Name)+"' is not a type.") + } + + return n +} + +// namesValue reports whether t names a value, which a pattern compares +// with, rather than a type: a constant, or a variant without fields. +func (p *Resolver) namesValue(t *ast.VarExpr) bool { + if t.Module == nil { + return p.constNamed(t.Name.Lexeme) != nil + } + + module := p.isModule(&ast.VarExpr{Name: *t.Module}) + if module && t.Case == nil { + l := p.mod.imports[t.Module.Lexeme].exports[t.Name.Lexeme] + return l != nil && l.IsConst + } + + enum, variant := p.localEnum(*t.Module), t.Name + if t.Case != nil { + if !module { + return false + } + + enum, variant = p.structs[p.mod.imports[t.Module.Lexeme].exports[t.Name.Lexeme]], *t.Case + } + + return enum != nil && enum.Enum && hasVariant(enum, variant.Lexeme) && !hasFields(enum, variant.Lexeme) +} + +// resolveTypes returns the type each of types names, reporting those +// that name something else; a missing module member is reported already. +func (p *Resolver) resolveTypes(types []*ast.VarExpr) []*value.Shape { + shapes := make([]*value.Shape, len(types)) + + for i, t := range types { + if shapes[i] = p.typeNamed(t); shapes[i] == nil && (t.Module == nil || t.Local != nil) { + p.error(t.Name, "'"+qualified(t.Module, t.Name)+"' is not a type.") + } + } + + return shapes +} + +// typeNamed resolves t and returns the type it names: a struct type, or +// a built-in one such as string; nil for anything else. +func (p *Resolver) typeNamed(t *ast.VarExpr) *value.Shape { + if s := p.kindType(t); s != nil { + return s + } + + p.resolveExpr(t) + + return p.structs[t.Local] +} + +var kindTypes = func() map[string]*value.Shape { + ts := map[string]*value.Shape{} + for name, k := range builtinKinds { + ts[name] = &value.Shape{Name: name, Builtin: true, Kind: k} + } + + ts["nil"] = &value.Shape{Name: "nil", Builtin: true, Kind: value.Nil} + ts["struct"] = &value.Shape{Name: "struct", Builtin: true, Kind: value.Type} + ts["enum"] = &value.Shape{Name: "enum", Builtin: true, Kind: value.Type, Enum: true} + + return ts +}() + +// kindType returns the built-in type t names, as in v is string, unless +// a declaration or an import hides it. +func (p *Resolver) kindType(t ast.Expr) *value.Shape { + v, ok := t.(*ast.VarExpr) + if !ok || v.Module != nil { + return nil + } + + name := v.Name.Lexeme + if p.lookupScopes(name) != nil || p.mod.topLevel[name] != nil || p.mod.imports[name] != nil { + return nil + } + + return kindTypes[name] +} + +func (p *Resolver) resolveFields(fields []ast.FieldPattern) { + for i := range fields { + fields[i].Pattern = p.resolvePattern(fields[i].Pattern) + } +} + +func (p *Resolver) checkBind(n *ast.BindPattern) { + if name := n.Name.Lexeme; p.structNamed(name) != nil { + p.error(n.Name, "'"+name+"' is a struct type; test it with '_ is "+name+"'.") + } +} + +// structNamed returns the struct type name denotes here, if it is one. +func (p *Resolver) structNamed(name string) *value.Shape { + if p.lookupScopes(name) != nil { + return nil + } + + if l := p.mod.topLevel[name]; l != nil { + return p.structs[l] + } + + if v, ok := builtinValues()[name]; ok && v.Kind() == value.Type { + return v.TypeShape() + } + + return nil +} + +// patternToken returns the token a pattern starts at, for errors. +func patternToken(pat ast.Pattern) ast.Token { + switch n := pat.(type) { + case *ast.WildcardPattern: + return n.Token + case *ast.BindPattern: + return n.Name + case *ast.LiteralPattern: + return n.Token + case *ast.RangePattern: + return n.Op + case *ast.OrPattern: + return patternToken(n.Alts[0]) + case *ast.StructPattern: + return n.Type.Name + case *ast.VariantPattern: + return n.Variant + case *ast.IsPattern: + return patternToken(n.Inner) + case *ast.DefaultPattern: + return patternToken(n.Pattern) + case *ast.ObjectPattern: + return n.Brace + case *ast.ArrayPattern: + return n.Bracket + } + + return ast.Token{} +} diff --git a/pkg/rune/resolver.go b/pkg/rune/resolver.go index 0f3d29b..51e08ac 100644 --- a/pkg/rune/resolver.go +++ b/pkg/rune/resolver.go @@ -193,33 +193,6 @@ func (p *Resolver) VisitVarStmt(stmt *ast.VarStmt) error { return nil } -func (p *Resolver) VisitDestructureStmt(stmt *ast.DestructureStmt) error { - p.resolveDestructure(stmt, stmt.Initializer) - return nil -} - -func (p *Resolver) VisitArrayDestructureStmt(stmt *ast.ArrayDestructureStmt) error { - p.resolveDestructure(stmt, stmt.Initializer) - return nil -} - -// resolveDestructure declares the variables stmt binds, each defined -// once initializer and its default are resolved. -func (p *Resolver) resolveDestructure(stmt ast.Stmt, initializer ast.Expr) { - vars := ast.PatternVars(stmt) - for _, v := range vars { - v.Local = p.declare(v.Binding) - } - - p.resolveExpr(initializer) - - for _, v := range vars { - p.resolveExpr(v.Default) - - p.define(v.Name) - } -} - func (p *Resolver) requireInitialized(name ast.Token, verb string) { if l, exists := p.innermost()[name.Lexeme]; exists && !l.defined { kind := helpers.If(p.isScopesEmpty(), "global", "local") @@ -288,8 +261,7 @@ func declaresLocals(stmts []ast.Stmt) bool { } func (p *Resolver) VisitIfStmt(ifStmt *ast.IfStmt) error { - p.resolveExpr(ifStmt.Condition) - p.resolveStmt(ifStmt.Then) + p.condScope(ifStmt.Condition, func() { p.resolveStmt(ifStmt.Then) }) if ifStmt.El != nil { p.resolveStmt(ifStmt.El) @@ -299,8 +271,7 @@ func (p *Resolver) VisitIfStmt(ifStmt *ast.IfStmt) error { } func (p *Resolver) VisitWhileStmt(whileStmt *ast.WhileStmt) error { - p.resolveExpr(whileStmt.Condition) - p.resolveLoopBody(whileStmt.Body) + p.condScope(whileStmt.Condition, func() { p.resolveLoopBody(whileStmt.Body) }) return nil } @@ -388,20 +359,6 @@ func (p *Resolver) VisitFunctionStmt(fnStmt *ast.FunctionStmt) error { return nil } -func (p *Resolver) VisitIsExpr(expr *ast.IsExpr) (value.Value, error) { - p.resolveExpr(expr.Value) - - for i, typ := range expr.Types { - if t, ok := typ.(*ast.VarExpr); ok { - expr.Shapes[i] = p.typeNamed(t) - } else { - p.resolveExpr(typ) - } - } - - return value.NilValue, nil -} - func (p *Resolver) VisitReturnStmt(returnStmt *ast.ReturnStmt) error { switch { case p.inDefer: diff --git a/pkg/rune/vm.go b/pkg/rune/vm.go index 5e43c0f..e3c5a44 100644 --- a/pkg/rune/vm.go +++ b/pkg/rune/vm.go @@ -413,7 +413,7 @@ reload: } case opJmpNotLen: - if v := at(regs, in.a()); v.Kind() != value.Array || !(len(v.Arr()) == in.b() || in.x() != 0 && len(v.Arr()) > in.b()) { + if v := at(regs, in.a()); v.Kind() != value.Array || !lenFits(len(v.Arr()), in.b(), in.x()) { pc = in.c() } @@ -813,3 +813,9 @@ func compareStrings(op uint8, l, r string) bool { return l != r } } + +// lenFits reports whether n is want, or with lenAtLeast or lenAtMost at +// least or at most want. +func lenFits(n, want int, x uint8) bool { + return n == want || x == lenAtLeast && n > want || x == lenAtMost && n < want +} diff --git a/pkg/value/value.go b/pkg/value/value.go index 1692358..82fb42f 100644 --- a/pkg/value/value.go +++ b/pkg/value/value.go @@ -319,12 +319,16 @@ type Method struct { Self, Mut, InPlace bool } +// RecordType has the objects and the instances of structs: the values +// whose keys a pattern reads. +var RecordType = &Shape{Name: "record", Builtin: true, Kind: Object} + // Has reports whether v is of the type s. func (s *Shape) Has(v Value) bool { k := v.Kind() switch { case k == Struct: - return v.Shape() == s || v.Shape().Parent == s + return v.Shape() == s || v.Shape().Parent == s || s == RecordType case k == Enum: return v.Variant().Shape == s case k == Type && s.Builtin: diff --git a/test/defer/bare_body.rn b/test/defer/bare_body.rn index 75b9ce2..6d7cf03 100644 --- a/test/defer/bare_body.rn +++ b/test/defer/bare_body.rn @@ -1,3 +1,8 @@ fun f() { - defer print("x"); // Error at 'print': Expect '{' after 'defer'. + defer print("cleanup"); + print("work"); } + +f(); +// expect: work +// expect: cleanup diff --git a/test/defer/bare_body.stderr b/test/defer/bare_body.stderr deleted file mode 100644 index 9ec5b59..0000000 --- a/test/defer/bare_body.stderr +++ /dev/null @@ -1,6 +0,0 @@ -error: Expect '{' after 'defer'. - --> bare_body.rn:2:9 - | -1 | fun f() { -2 | defer print("x"); // Error at 'print': Expect '{' after 'defer'. - | ^^^^^ diff --git a/test/defer/braced_expression.rn b/test/defer/braced_expression.rn new file mode 100644 index 0000000..fc09cb4 --- /dev/null +++ b/test/defer/braced_expression.rn @@ -0,0 +1,3 @@ +fun f() { + defer { print("x"); } // Error at 'defer': Defer one expression without braces: defer expression; +} diff --git a/test/defer/braced_expression.stderr b/test/defer/braced_expression.stderr new file mode 100644 index 0000000..d83d91a --- /dev/null +++ b/test/defer/braced_expression.stderr @@ -0,0 +1,6 @@ +error: Defer one expression without braces: defer expression; + --> braced_expression.rn:2:5 + | +1 | fun f() { +2 | defer { print("x"); } // Error at 'defer': Defer one expression without braces: defer expression; + | ^^^^^ diff --git a/test/defer/error.rn b/test/defer/error.rn index 59c242b..b0a0455 100644 --- a/test/defer/error.rn +++ b/test/defer/error.rn @@ -1,5 +1,5 @@ fun fails() { - defer { print("cleanup"); } + defer print("cleanup"); throw ValueError { message: "boom" }; } try { fails(); } catch e { print("caught " + e.message); } @@ -7,7 +7,7 @@ try { fails(); } catch e { print("caught " + e.message); } // expect: caught boom try { - defer { print("inner"); } + defer print("inner"); [][0]; } catch e is IndexError { print("after"); @@ -16,7 +16,7 @@ try { // expect: after fun replaced() { - defer { throw ValueError { message: "from defer" }; } + defer throw ValueError { message: "from defer" }; return 1; } try { replaced(); } catch e { print(e.message); } // expect: from defer diff --git a/test/defer/expression.rn b/test/defer/expression.rn new file mode 100644 index 0000000..572d5ce --- /dev/null +++ b/test/defer/expression.rn @@ -0,0 +1,14 @@ +fun f() { + defer print("close"); + defer { + print("flush"); + print("sync"); + } + print("work"); +} + +f(); +// expect: work +// expect: flush +// expect: sync +// expect: close diff --git a/test/defer/expression_return.rn b/test/defer/expression_return.rn new file mode 100644 index 0000000..552dde6 --- /dev/null +++ b/test/defer/expression_return.rn @@ -0,0 +1,3 @@ +fun f() { + defer return 1; // Error at 'return': Cannot return from a 'defer' body. +} diff --git a/test/defer/expression_return.stderr b/test/defer/expression_return.stderr new file mode 100644 index 0000000..aac9e0a --- /dev/null +++ b/test/defer/expression_return.stderr @@ -0,0 +1,6 @@ +error: Cannot return from a 'defer' body. + --> expression_return.rn:2:11 + | +1 | fun f() { +2 | defer return 1; // Error at 'return': Cannot return from a 'defer' body. + | ^^^^^^ diff --git a/test/defer/loop.rn b/test/defer/loop.rn index 857391e..97eb019 100644 --- a/test/defer/loop.rn +++ b/test/defer/loop.rn @@ -1,5 +1,5 @@ for i in 0..4 { - defer { print("end {i}"); } + defer print("end {i}"); if i == 1 { continue; } if i == 3 { break; } print("body {i}"); @@ -13,7 +13,7 @@ for i in 0..4 { for i in 0..3 { try { - defer { print("try {i}"); } + defer print("try {i}"); if i == 1 { break; } } catch { print("unreachable"); diff --git a/test/defer/order.rn b/test/defer/order.rn index e4ad424..a6eeca0 100644 --- a/test/defer/order.rn +++ b/test/defer/order.rn @@ -1,6 +1,6 @@ fun run() { - defer { print("first registered"); } - defer { print("second registered"); } + defer print("first registered"); + defer print("second registered"); print("body"); } run(); @@ -9,7 +9,7 @@ run(); // expect: first registered { - defer { print("inner block"); } + defer print("inner block"); print("in block"); } print("after block"); diff --git a/test/defer/return.rn b/test/defer/return.rn index 0b5cb88..9c9dd67 100644 --- a/test/defer/return.rn +++ b/test/defer/return.rn @@ -1,5 +1,5 @@ fun sign(x) { - defer { print("deferred {x}"); } + defer print("deferred {x}"); if x > 0 { return "positive"; } return "other"; } @@ -9,13 +9,13 @@ print(sign(1)); fun value() { let mut n = 1; - defer { n = 100; } + defer n = 100; return n; } print(value()); // expect: 1 fun early() { - defer { print("cleanup"); } + defer print("cleanup"); let v = try int("x") catch => return 0; return v; } @@ -26,7 +26,7 @@ print(early()); struct Counter { n = 0 } impl Counter { fun bump(mut self) { - defer { self.n += 10; } + defer self.n += 10; self.n++; return self.n; } diff --git a/test/defer/uncaught.rn b/test/defer/uncaught.rn index 74e916b..9cf567d 100644 --- a/test/defer/uncaught.rn +++ b/test/defer/uncaught.rn @@ -1,6 +1,6 @@ fun inner() { [].pop(); } // expect runtime error: [line: 1] ValueError: array.pop() got an empty array. fun outer() { - defer { print("cleanup"); } // expect: cleanup + defer print("cleanup"); // expect: cleanup inner(); } outer(); diff --git a/test/destructure/empty.rn b/test/destructure/empty.rn index 48bf2a9..11fae3f 100644 --- a/test/destructure/empty.rn +++ b/test/destructure/empty.rn @@ -1 +1 @@ -let {} = {}; // Error at '}': Expect property name in pattern. +let {} = {}; // Error at '{': Expect property name in pattern. diff --git a/test/destructure/empty.stderr b/test/destructure/empty.stderr index e53ccb4..3f53907 100644 --- a/test/destructure/empty.stderr +++ b/test/destructure/empty.stderr @@ -1,5 +1,5 @@ error: Expect property name in pattern. - --> empty.rn:1:6 + --> empty.rn:1:5 | -1 | let {} = {}; // Error at '}': Expect property name in pattern. - | ^ +1 | let {} = {}; // Error at '{': Expect property name in pattern. + | ^ diff --git a/test/destructure/nested.rn b/test/destructure/nested.rn new file mode 100644 index 0000000..41ea411 --- /dev/null +++ b/test/destructure/nested.rn @@ -0,0 +1,25 @@ +let { user: { name, tags: [first, ...more] }, size = 1 } = { user: { name: "ann", tags: ["a", "b", "c"] } }; +print(name); // expect: ann +print(first); // expect: a +print(more); // expect: ["b", "c"] +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] }; +px += 10; +print(px, py); // expect: 11 2 + +let { pos, pos: { x: posX } } = { pos: { x: 3 } }; +print(pos, posX); // expect: {x: 3} 3 + +fun area({ size: [w, h] = [1, 1] }) { w * h } +print(area({ size: [3, 4] })); // expect: 12 +print(area({})); // expect: 1 + +for [key, { n }] in [["a", { n: 1 }], ["b", { n: 2 }]] { + print(key, n); +} +// expect: a 1 +// expect: b 2 diff --git a/test/destructure/nested_missing.rn b/test/destructure/nested_missing.rn new file mode 100644 index 0000000..d048820 --- /dev/null +++ b/test/destructure/nested_missing.rn @@ -0,0 +1 @@ +let { a: { b } } = { a: {} }; // expect runtime error: [line: 1] KeyError: Undefined property 'b'. diff --git a/test/destructure/nested_missing.stderr b/test/destructure/nested_missing.stderr new file mode 100644 index 0000000..66d5021 --- /dev/null +++ b/test/destructure/nested_missing.stderr @@ -0,0 +1,5 @@ +KeyError: Undefined property 'b'. + --> nested_missing.rn:1:12 + | +1 | let { a: { b } } = { a: {} }; // expect runtime error: [line: 1] KeyError: Undefined property 'b'. + | ^ diff --git a/test/destructure/refutable.rn b/test/destructure/refutable.rn new file mode 100644 index 0000000..29f8fb2 --- /dev/null +++ b/test/destructure/refutable.rn @@ -0,0 +1,3 @@ +let [a, 1] = [1, 1]; // Error at '1': This pattern only takes a value apart; test the value with match or 'is'. +let { b: "x" } = { b: "x" }; // Error at '"x"': This pattern only takes a value apart; test the value with match or 'is'. +fun f([c, 2 | 3]) {} // Error at '2': This pattern only takes a value apart; test the value with match or 'is'. diff --git a/test/destructure/refutable.stderr b/test/destructure/refutable.stderr new file mode 100644 index 0000000..4ccf047 --- /dev/null +++ b/test/destructure/refutable.stderr @@ -0,0 +1,19 @@ +error: This pattern only takes a value apart; test the value with match or 'is'. + --> refutable.rn:1:9 + | +1 | let [a, 1] = [1, 1]; // Error at '1': This pattern only takes a value apart; test the value with match or 'is'. + | ^ + +error: This pattern only takes a value apart; test the value with match or 'is'. + --> refutable.rn:2:10 + | +1 | let [a, 1] = [1, 1]; // Error at '1': This pattern only takes a value apart; test the value with match or 'is'. +2 | let { b: "x" } = { b: "x" }; // Error at '"x"': This pattern only takes a value apart; test the value with match or 'is'. + | ^^^ + +error: This pattern only takes a value apart; test the value with match or 'is'. + --> refutable.rn:3:11 + | +2 | let { b: "x" } = { b: "x" }; // Error at '"x"': This pattern only takes a value apart; test the value with match or 'is'. +3 | fun f([c, 2 | 3]) {} // Error at '2': This pattern only takes a value apart; test the value with match or 'is'. + | ^ diff --git a/test/for_in/mut.rn b/test/for_in/mut.rn index f423327..cce37b4 100644 --- a/test/for_in/mut.rn +++ b/test/for_in/mut.rn @@ -58,7 +58,7 @@ print(ys); // expect: [5, 2] fun failing() { let mut zs = [1, 2]; - defer { print(zs); } // expect: [9, 2] + defer print(zs); // expect: [9, 2] for mut z in zs { z = 9; throw Error("stop"); diff --git a/test/function/tail_value.rn b/test/function/tail_value.rn index 0610702..2b0e8bb 100644 --- a/test/function/tail_value.rn +++ b/test/function/tail_value.rn @@ -57,7 +57,7 @@ print(shorthand("ann")); // expect: ann fun withDefer() { let mut xs = [1]; - defer { print("deferred", xs); } + defer print("deferred", xs); xs.push(2); xs } diff --git a/test/is/binding_errors.rn b/test/is/binding_errors.rn new file mode 100644 index 0000000..c9c5571 --- /dev/null +++ b/test/is/binding_errors.rn @@ -0,0 +1,4 @@ +let v = { a: 1 }; +let ok = v is { a }; // Error at 'a': Only an if or while condition can bind variables with 'is'. +if v !is { b } {} // Error at 'b': Cannot bind variables in a '!is' test. +if v is { c } || true {} // Error at 'c': Only an if or while condition can bind variables with 'is'. diff --git a/test/is/binding_errors.stderr b/test/is/binding_errors.stderr new file mode 100644 index 0000000..62fe928 --- /dev/null +++ b/test/is/binding_errors.stderr @@ -0,0 +1,20 @@ +error: Only an if or while condition can bind variables with 'is'. + --> binding_errors.rn:2:17 + | +1 | let v = { a: 1 }; +2 | let ok = v is { a }; // Error at 'a': Only an if or while condition can bind variables with 'is'. + | ^ + +error: Cannot bind variables in a '!is' test. + --> binding_errors.rn:3:12 + | +2 | let ok = v is { a }; // Error at 'a': Only an if or while condition can bind variables with 'is'. +3 | if v !is { b } {} // Error at 'b': Cannot bind variables in a '!is' test. + | ^ + +error: Only an if or while condition can bind variables with 'is'. + --> binding_errors.rn:4:11 + | +3 | if v !is { b } {} // Error at 'b': Cannot bind variables in a '!is' test. +4 | if v is { c } || true {} // Error at 'c': Only an if or while condition can bind variables with 'is'. + | ^ diff --git a/test/is/bindings.rn b/test/is/bindings.rn new file mode 100644 index 0000000..4b242d7 --- /dev/null +++ b/test/is/bindings.rn @@ -0,0 +1,35 @@ +struct Point { x, y = 0 } + +fun handle(r) { + if r is { status: 200..300, body } && body { + "ok: {body}" + } else if r is { status } { + "status {status}" + } else { + "not a response" + } +} + +print(handle({ status: 200, body: "hi" })); // expect: ok: hi +print(handle({ status: 200, body: "" })); // expect: status 200 +print(handle({ status: 404 })); // expect: status 404 +print(handle(5)); // expect: not a response + +let p = Point { x: 3 }; +if p is Point { x } { + print(x); // expect: 3 +} + +let x = 9; +print(if p is Point { x } else { 0 }); // expect: 9 + +let mut queue = [3, "skip", 1, 2]; +let mut total = 0; +let mut later = []; +while queue.pop() is n is number { + total += n; + later.push(() => n); +} +print(total); // expect: 3 +print(later.map(f => f())); // expect: [2, 1] +print(queue); // expect: [3] diff --git a/test/is/patterns.rn b/test/is/patterns.rn new file mode 100644 index 0000000..67b5477 --- /dev/null +++ b/test/is/patterns.rn @@ -0,0 +1,18 @@ +struct Point { x, y = 0 } +enum Dir { North, South } +const LIMIT = 10; + +print(3 is 1..5); // expect: true +print(7 is ..LIMIT); // expect: true +print("b" is "a" | "b"); // expect: true +print(3 is number | string); // expect: true +print({ status: 200, body: "" } is { status: 200..300 }); // expect: true +print([1, 2] is [_, _]); // expect: true +print([1, 2, 3] is [1, ..._]); // expect: true +print(Point { x: 1 } is Point { y: 0 }); // expect: true +print(Dir.North is Dir.North); // expect: true +print(Dir.South is Dir.North); // expect: false +print(Dir.South !is Dir.North); // expect: true +const FIRST = Dir.North; +print(10 is LIMIT); // expect: true +print(Dir.North is FIRST); // expect: true diff --git a/test/is/shadowed.stderr b/test/is/shadowed.stderr index bdb6b41..ad31a16 100644 --- a/test/is/shadowed.stderr +++ b/test/is/shadowed.stderr @@ -1,6 +1,6 @@ TypeError: Right operand of 'is' must be a type, got number. - --> shadowed.rn:2:11 + --> shadowed.rn:2:14 | 1 | let string = 1; 2 | print("a" is string); // expect runtime error: [line: 2] TypeError: Right operand of 'is' must be a type, got number. - | ^^ + | ^^^^^^ diff --git a/test/match/defaults.rn b/test/match/defaults.rn new file mode 100644 index 0000000..da3932f --- /dev/null +++ b/test/match/defaults.rn @@ -0,0 +1,19 @@ +fun describe(v) { + match v { + { kind: "user", name, role = "member" } => "{name} ({role})", + [cmd, arg = "-"] => "{cmd} {arg}", + { id, ...rest } => "#{id} {rest}", + _ => "other", + } +} + +print(describe({ kind: "user", name: "ann" })); // expect: ann (member) +print(describe({ kind: "user", name: "bob", role: "admin" })); // expect: bob (admin) +print(describe(["ls"])); // expect: ls - +print(describe(["rm", "x"])); // expect: rm x +print(describe(["rm", "x", "y"])); // expect: other +print(describe({ id: 7, a: 1, b: 2 })); // expect: #7 {a: 1, b: 2} +print(describe(5)); // expect: other + +print(match 5 { { a = 1 } => "object", _ => "not" }); // expect: not +print(match [[1, 2], 3] { [[a, b], c] => a + b + c, _ => 0 }); // expect: 6 diff --git a/test/match/enum_head.rn b/test/match/enum_head.rn new file mode 100644 index 0000000..2613a23 --- /dev/null +++ b/test/match/enum_head.rn @@ -0,0 +1,21 @@ +enum Payment { + Card { last4, brand = "visa" }, + Transfer { iban }, + Cash, + Credit, +} + +fun describe(p) { + match p is Payment { + Card { brand, last4 } => "{brand} card {last4}", + Transfer => "transfer", + Cash | Credit => "on delivery", + } +} + +print(describe(Payment.Card { last4: "4242" })); // expect: visa card 4242 +print(describe(Payment.Transfer { iban: "DE89" })); // expect: transfer +print(describe(Payment.Credit)); // expect: on delivery +print(match Payment.Cash is Payment { Cash => 1, _ => 2 }); // expect: 1 +print(match (Payment.Cash is Payment) { true => "yes", false => "no" }); // expect: yes +print(match "cash" is Payment { Cash => 1, _ => 2 }); // expect runtime error: [line: 21] ValueError: No match arm for "cash". diff --git a/test/match/enum_head.stderr b/test/match/enum_head.stderr new file mode 100644 index 0000000..f81e709 --- /dev/null +++ b/test/match/enum_head.stderr @@ -0,0 +1,6 @@ +ValueError: No match arm for "cash". + --> enum_head.rn:21:7 + | +20 | print(match (Payment.Cash is Payment) { true => "yes", false => "no" }); // expect: yes +21 | print(match "cash" is Payment { Cash => 1, _ => 2 }); // expect runtime error: [line: 21] ValueError: No match arm for "cash". + | ^^^^^ diff --git a/test/match/enum_head_errors.rn b/test/match/enum_head_errors.rn new file mode 100644 index 0000000..1ecf206 --- /dev/null +++ b/test/match/enum_head_errors.rn @@ -0,0 +1,14 @@ +enum Status { Pending, Paid } +struct Point { x } + +fun f(s) { + match s is Status { Pendin => 1, _ => 2 } // Error at 'Pendin': Status has no variant 'Pendin'. +} + +fun g(s) { + match s is Status { Pending => 1 } // Error at 'match': Match does not cover Status.Paid; add arms or '_ =>'. +} + +fun h(p) { + match p is Point { _ => 1 } // Error at 'Point': 'Point' is not an enum; match x is Enum { ... } names its variants bare. +} diff --git a/test/match/enum_head_errors.stderr b/test/match/enum_head_errors.stderr new file mode 100644 index 0000000..e816158 --- /dev/null +++ b/test/match/enum_head_errors.stderr @@ -0,0 +1,20 @@ +error: Status has no variant 'Pendin'. + --> enum_head_errors.rn:5:25 + | +4 | fun f(s) { +5 | match s is Status { Pendin => 1, _ => 2 } // Error at 'Pendin': Status has no variant 'Pendin'. + | ^^^^^^ + +error: Match does not cover Status.Paid; add arms or '_ =>'. + --> enum_head_errors.rn:9:5 + | +8 | fun g(s) { +9 | match s is Status { Pending => 1 } // Error at 'match': Match does not cover Status.Paid; add arms or '_ =>'. + | ^^^^^ + +error: 'Point' is not an enum; match x is Enum { ... } names its variants bare. + --> enum_head_errors.rn:13:16 + | +12 | fun h(p) { +13 | match p is Point { _ => 1 } // Error at 'Point': 'Point' is not an enum; match x is Enum { ... } names its variants bare. + | ^^^^^ diff --git a/test/match/is_pattern.rn b/test/match/is_pattern.rn new file mode 100644 index 0000000..9a2c48e --- /dev/null +++ b/test/match/is_pattern.rn @@ -0,0 +1,17 @@ +struct Point { x, y = 0 } + +fun f(v) { + match v { + n is 1..10 => "small {n}", + p is Point { x: 0 } => "on the axis: {p}", + s is "a" | "b" => "letter {s}", + n is number => "number {n}", + _ => "other", + } +} + +print(f(3)); // expect: small 3 +print(f(42)); // expect: number 42 +print(f(Point { x: 0, y: 2 })); // expect: on the axis: Point {x: 0, y: 2} +print(f("b")); // expect: letter b +print(f(Point { x: 1 })); // expect: other diff --git a/test/struct/is_not_type.rn b/test/struct/is_not_type.rn index f20af0c..adfa2b3 100644 --- a/test/struct/is_not_type.rn +++ b/test/struct/is_not_type.rn @@ -1,4 +1,6 @@ struct Point { x } let p = Point { x: 1 }; -print(p is 1); // expect runtime error: [line: 4] TypeError: Right operand of 'is' must be a type, got number. +let one = 1; +print(p is 1); // expect: false +print(p is one); // expect runtime error: [line: 6] TypeError: Right operand of 'is' must be a type, got number. diff --git a/test/struct/is_not_type.stderr b/test/struct/is_not_type.stderr index 483b171..39e4048 100644 --- a/test/struct/is_not_type.stderr +++ b/test/struct/is_not_type.stderr @@ -1,6 +1,6 @@ TypeError: Right operand of 'is' must be a type, got number. - --> is_not_type.rn:4:9 + --> is_not_type.rn:6:12 | -3 | let p = Point { x: 1 }; -4 | print(p is 1); // expect runtime error: [line: 4] TypeError: Right operand of 'is' must be a type, got number. - | ^^ +5 | print(p is 1); // expect: false +6 | print(p is one); // expect runtime error: [line: 6] TypeError: Right operand of 'is' must be a type, got number. + | ^^^ diff --git a/test/struct/is_struct_value.stderr b/test/struct/is_struct_value.stderr index ec4a05a..73388d2 100644 --- a/test/struct/is_struct_value.stderr +++ b/test/struct/is_struct_value.stderr @@ -1,6 +1,6 @@ TypeError: Right operand of 'is' must be a type, got Point. - --> is_struct_value.rn:4:9 + --> is_struct_value.rn:4:12 | 3 | let p = Point { x: 1 }; 4 | print(p is p); // expect runtime error: [line: 4] TypeError: Right operand of 'is' must be a type, got Point. - | ^^ + | ^ diff --git a/test/value/inout.rn b/test/value/inout.rn index 6bbfb92..0b24d5e 100644 --- a/test/value/inout.rn +++ b/test/value/inout.rn @@ -54,7 +54,7 @@ try { fail(done); } catch e { print(done); } // expect: ["replaced"] fun failNested() { let mut xs = [0]; - defer { print(xs); } // expect: ["replaced"] + defer print(xs); // expect: ["replaced"] fail(xs); } try { failNested(); } catch e {} diff --git a/test/value/moves.rn b/test/value/moves.rn index 37e1a9e..087be51 100644 --- a/test/value/moves.rn +++ b/test/value/moves.rn @@ -74,7 +74,7 @@ print(caught()); // expect: [1] // A defer reads it on the way out. fun deferred() { let mut x = [1]; - defer { print(x); } + defer print(x); let mut y = x; y.push(2); return y;