From 8e54f00a4d1882e425fcb40fb507953c2696c1f4 Mon Sep 17 00:00:00 2001 From: Alexander Satretdinov Date: Mon, 16 Nov 2026 16:59:41 +0200 Subject: [PATCH] blocks give their last expression; if is an expression; drop ? : and fun f() => e; --- README.md | 3 +- docs/src/data/enums.md | 4 +- docs/src/getting-started.md | 2 +- docs/src/introduction.md | 4 +- docs/src/language/conditionals.md | 35 +++- docs/src/language/destructuring.md | 2 +- docs/src/language/error-handling.md | 6 +- docs/src/language/functions.md | 35 ++-- docs/src/language/loops.md | 4 +- docs/src/language/nil-safety.md | 4 +- docs/src/language/numbers.md | 2 +- docs/src/language/pattern-matching.md | 14 +- docs/src/language/strings.md | 2 +- docs/src/language/values.md | 2 +- docs/src/stdlib/fs.md | 2 +- docs/src/stdlib/os.md | 2 +- examples/blog/content/hello-rune.md | 2 +- examples/blog/md/block.rn | 16 +- examples/blog/site/build.rn | 2 +- examples/blog/site/template.rn | 2 +- examples/calc.rn | 42 +++-- examples/chess.rn | 90 +++++----- examples/kv/codec.rn | 2 +- examples/kv/main.rn | 12 +- examples/kv/store.rn | 16 +- examples/log-report.rn | 54 +++--- examples/query/aggregate.rn | 14 +- examples/query/ast.rn | 78 ++++---- examples/query/demo.rn | 8 +- examples/query/expr.rn | 40 ++--- examples/query/main.rn | 8 +- examples/query/output.rn | 14 +- examples/query/parser.rn | 24 +-- examples/query/plan.rn | 60 ++++--- examples/query/table.rn | 6 +- examples/shop.rn | 16 +- examples/todo.rn | 18 +- examples/validate.rn | 38 ++-- extras/nvim/syntax/rune.vim | 2 +- pkg/ast/expression.go | 19 +- pkg/ast/pattern.go | 16 +- pkg/ast/statement.go | 33 +++- pkg/ast/token.go | 3 - pkg/format/format.go | 19 +- pkg/rune/bench_test.go | 2 +- pkg/rune/compile_access.go | 2 - pkg/rune/compile_expr.go | 29 +-- pkg/rune/compile_match.go | 11 +- pkg/rune/compile_stmt.go | 74 ++++++-- pkg/rune/moves.go | 8 +- pkg/rune/parse_expr.go | 49 ++--- pkg/rune/parse_match.go | 8 +- pkg/rune/parse_stmt.go | 170 ++++++++++++------ pkg/rune/report_test.go | 2 +- pkg/rune/resolver.go | 8 +- pkg/rune/scanner.go | 2 +- test/arrow/object_body.rn | 3 +- test/arrow/object_body.stderr | 31 ++-- test/block/loop_tail.rn | 4 + test/block/loop_tail.stderr | 6 + test/conditional/assign.rn | 2 - test/conditional/assign.stderr | 6 - test/conditional/basic.rn | 37 ---- test/conditional/missing_colon.rn | 1 - test/conditional/missing_colon.stderr | 5 - test/default/basic.rn | 2 +- test/enum/basic.rn | 2 +- test/enum/methods.rn | 4 +- test/function/body_must_be_block.rn | 2 +- test/function/body_must_be_block.stderr | 2 +- test/function/expression_body.rn | 21 --- test/function/expression_body_semicolon.rn | 2 - .../function/expression_body_semicolon.stderr | 5 - test/function/tail_value.rn | 65 +++++++ test/if/expression.rn | 59 ++++++ test/if/expression_bare.rn | 1 + test/if/expression_bare.stderr | 5 + test/if/expression_registers.rn | 10 ++ test/if/question.rn | 3 + test/if/question.stderr | 13 ++ test/in/precedence.rn | 2 +- test/is/union.rn | 2 +- test/jump/expression.rn | 2 +- test/throw/expression.rn | 2 +- test/throw/expression_assign.rn | 2 +- test/try/expr.rn | 4 +- testdata/fmt/layout.golden | 7 +- testdata/fmt/layout.rn | 3 +- 88 files changed, 851 insertions(+), 606 deletions(-) create mode 100644 test/block/loop_tail.rn create mode 100644 test/block/loop_tail.stderr delete mode 100644 test/conditional/assign.rn delete mode 100644 test/conditional/assign.stderr delete mode 100644 test/conditional/basic.rn delete mode 100644 test/conditional/missing_colon.rn delete mode 100644 test/conditional/missing_colon.stderr delete mode 100644 test/function/expression_body.rn delete mode 100644 test/function/expression_body_semicolon.rn delete mode 100644 test/function/expression_body_semicolon.stderr create mode 100644 test/function/tail_value.rn create mode 100644 test/if/expression.rn create mode 100644 test/if/expression_bare.rn create mode 100644 test/if/expression_bare.stderr create mode 100644 test/if/expression_registers.rn create mode 100644 test/if/question.rn create mode 100644 test/if/question.stderr diff --git a/README.md b/README.md index b0ddf26f..7ccdc0d8 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,8 @@ skip: int() cannot parse "x" as an integer. - immutable by default (`let` / `let mut`), compile-time `const` - value semantics: arrays, objects, maps, sets and structs copy lazily, `mut` parameters are inout -- structs and enums with fields, `impl` methods, `fun f(x) => expr;` +- 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 - 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 diff --git a/docs/src/data/enums.md b/docs/src/data/enums.md index e646f4c3..5859b688 100644 --- a/docs/src/data/enums.md +++ b/docs/src/data/enums.md @@ -144,10 +144,10 @@ enum Side { White, Black } impl Side { fun other(self) { - return self == Side.White ? Side.Black : Side.White; + return if self == Side.White { Side.Black } else { Side.White }; } fun parse(s) { - return s == "w" ? Side.White : Side.Black; + return if s == "w" { Side.White } else { Side.Black }; } } diff --git a/docs/src/getting-started.md b/docs/src/getting-started.md index c544ca2e..7c64d4c0 100644 --- a/docs/src/getting-started.md +++ b/docs/src/getting-started.md @@ -47,7 +47,7 @@ Arguments after the file go to the program's [`main`](programs/main.md): ```rune fun main(args) { - let name = args.len() > 0 ? args[0] : "world"; + let name = if args.len() > 0 { args[0] } else { "world" }; print("hello, {name}!"); } ``` diff --git a/docs/src/introduction.md b/docs/src/introduction.md index bba3a5bc..271c6bcf 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -51,8 +51,8 @@ Language chapters in order. - [values](language/values.md): `nil`, booleans, 64-bit [numbers](language/numbers.md) (integers and floats), Unicode [strings](language/strings.md) with interpolation `"x = {x}"` - [variables](language/variables.md) immutable by default: `let`, `let mut`, compile-time `const` - every value is [copied](language/values.md#copies) where it goes, containers too, lazily; `mut` parameters change the caller's variable -- `if`/`else`, `? :`, [loops](language/loops.md) `while` and `for x in ...` over arrays, strings, objects and ranges `a..b` -- [functions](language/functions.md): closures, defaults, arrows `x => x * 2`, expression bodies `fun sq(x) => x * x;` +- `if`/`else` as statement or expression, [loops](language/loops.md) `while` and `for x in ...` over arrays, strings, objects and ranges `a..b` +- [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 diff --git a/docs/src/language/conditionals.md b/docs/src/language/conditionals.md index 3057e4ef..ff000993 100644 --- a/docs/src/language/conditionals.md +++ b/docs/src/language/conditionals.md @@ -48,20 +48,39 @@ print(0 || 5); // 5 print("ann" && "admin"); // admin ``` -## Conditional Expressions +## if as an Expression -`c ? a : b` is `a` if `c` is truthy, else `b`; only the chosen branch runs. -It binds looser than `??`, tighter than assignment, and nests to -the right: `a ? b : c ? d : e` is `a ? b : (c ? d : e)`. +A block's value is its last expression when that has no `;` after it; +a block ending with `;` gives `nil`. So `if` is an expression too: its +value is that of the branch taken, `nil` when no branch is. `else if` +chains as usual. ```rune let stock = 3; -let label = stock > 10 ? "in stock" : stock > 0 ? "low" : "sold out"; +let label = if stock > 10 { "in stock" } else if stock > 0 { "low" } else { "sold out" }; print(label); // low let cart = ["tea", "milk"]; -print("{cart.len()} item{cart.len() == 1 ? "" : "s"}"); // 2 items +print("{cart.len()} item{if cart.len() == 1 { "" } else { "s" }}"); // 2 items -let parity = n => n % 2 == 0 ? "even" : "odd"; -print(parity(7)); // odd +print(if stock > 10 { "many" }); // nil ``` + +A branch may run statements before its value: + +```rune +let score = 72; +let grade = if score >= 90 { + "A" +} else { + let gap = 90 - score; + "B, {gap} to A" +}; +print(grade); // B, 18 to A +``` + +After `if` a `{` always starts a block; an object to give goes in +parentheses: `if ok { ({ code: 200 }) } else { nil }`. + +The bodies of `while`, `for` and `defer` have no value, so each of their +statements ends with `;`. diff --git a/docs/src/language/destructuring.md b/docs/src/language/destructuring.md index 0a5d6998..38948968 100644 --- a/docs/src/language/destructuring.md +++ b/docs/src/language/destructuring.md @@ -131,7 +131,7 @@ evaluated only then, and may use the variables before it. ```rune let opts = { title: "Blog", root: nil }; -let { title, theme = "light", root = ".", depth = root == "." ? 0 : 1 } = opts; +let { title, theme = "light", root = ".", depth = if root == "." { 0 } else { 1 } } = opts; print(title); // Blog print(theme); // light diff --git a/docs/src/language/error-handling.md b/docs/src/language/error-handling.md index eaaf9864..6c250ef8 100644 --- a/docs/src/language/error-handling.md +++ b/docs/src/language/error-handling.md @@ -108,7 +108,7 @@ fallback extend as far as they can. let port = try int("http") catch => 80; print(port); // 80 -fun field(o, key) => try o[key] catch e is KeyError => nil catch e is TypeError => "not an object"; +fun field(o, key) { try o[key] catch e is KeyError => nil catch e is TypeError => "not an object" } print(field({ id: 7 }, "id")); // 7 print(field({ id: 7 }, "name")); // nil @@ -159,7 +159,7 @@ throw AgeError { message: "negative age", value: -1 }; // AgeError: negative age ``` `throw` is also an expression, whose operand extends as far as it can, so it -fits where a value is expected: after `??`, in `? :`, or in a match arm. +fits where a value is expected: after `??`, in an `if` branch, or in a match arm. ```rune struct ConfigError { message, key } @@ -169,7 +169,7 @@ fun require(cfg, key) { } fun positive(n) { - return n > 0 ? n : throw ValueError { message: "not positive: {n}" }; + return if n > 0 { n } else { throw ValueError { message: "not positive: {n}" } }; } let cfg = { port: 8080 }; diff --git a/docs/src/language/functions.md b/docs/src/language/functions.md index 5adbf1c7..163f77eb 100644 --- a/docs/src/language/functions.md +++ b/docs/src/language/functions.md @@ -1,7 +1,9 @@ # Functions -`fun name(params) { ... }` declares a function. `return` gives its value; a -function that ends without one returns `nil`. +`fun name(params) { ... }` declares a function. It returns the value of its +body: the last expression, written without a `;`, or an `if` or `match` +that ends it and has values. A body ending with `;` returns `nil`. +`return` leaves early. ```rune fun total(items) { @@ -34,24 +36,27 @@ fun area(w, h) { return w * h; } area(3); // ArgumentError: Expected 2 arguments but got 1. ``` -## Expression Bodies - -`fun name(params) => expression;` returns the expression, as an arrow -function does; the declaration ends with `;`. Methods take this form too. +## Body Values ```rune -fun square(x) => x * x; -fun origin() => ({ x: 0, y: 0 }); +fun square(x) { x * x } +fun origin() { ({ x: 0, y: 0 }) } + +fun sign(n) { + if n < 0 { return "negative"; } + if n == 0 { "zero" } else { "positive" } +} struct Money { cents } impl Money { - fun of(amount) => Money { cents: math.round(amount * 100) }; - fun format(self) => "$%.2f".format(self.cents / 100); + fun of(amount) { Money { cents: math.round(amount * 100) } } + fun format(self) { "$%.2f".format(self.cents / 100) } } print(square(7)); // 49 print(origin()); // {x: 0, y: 0} +print(sign(-2), sign(0)); // negative zero print(Money.of(4.99).format()); // $4.99 ``` @@ -59,7 +64,7 @@ print(Money.of(4.99).format()); // $4.99 A function without a name is an arrow function, an expression, so functions can be passed around inline. An expression body is returned; a -block body works like `fun`'s. +block body works like `fun`'s, giving its last expression. ```rune let add = (a, b) => a + b; @@ -82,8 +87,8 @@ print(users.map(({ name }) => name)); // ["ann", "bob"] print(users.filter(u => u.age >= 18).map(u => u.name)); // ["ann"] ``` -After `=>` a `{` always starts a block, here and in a `fun`'s expression -body or a match arm; an object to return goes in parentheses: +After `=>` a `{` always starts a block, here and in a match arm; an +object to return goes in parentheses: ```rune let origin = () => ({ x: 0, y: 0 }); @@ -94,7 +99,7 @@ print(wrap("ann")); // {name: "ann"} ``` ```rune -let wrap = name => { name }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +let wrap = name => { name: name }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). ``` ## Default Parameters @@ -116,7 +121,7 @@ which it may use, so a mutable default is a new value every call. An explicit `nil` is an argument and gets no default. ```rune -fun greet(name, greeting = "hi", punct = greeting == "hi" ? "!" : ".") { +fun greet(name, greeting = "hi", punct = if greeting == "hi" { "!" } else { "." }) { return "{greeting} {name}{punct}"; } diff --git a/docs/src/language/loops.md b/docs/src/language/loops.md index 1a3a1f54..90d6e80b 100644 --- a/docs/src/language/loops.md +++ b/docs/src/language/loops.md @@ -63,7 +63,7 @@ the array. Anywhere else a range is an array. In brackets it [slices](../data/arrays.md), `xs[1..]`, and in a `match` it is a [pattern](pattern-matching.md#patterns), `200..300 => "ok"`. `..` binds looser than arithmetic and bitwise operators and tighter than comparisons, so `0..n + 1`, -`x in 0..10` and `xs == 1..3` need no parentheses; a `??` or `? :` in a +`x in 0..10` and `xs == 1..3` need no parentheses; a `??` in a bound does. ```rune @@ -137,7 +137,7 @@ Anything else is a `while`: let mut n = 27; let mut steps = 0; while n != 1 { - n = n % 2 == 0 ? math.idiv(n, 2) : 3 * n + 1; + n = if n % 2 == 0 { math.idiv(n, 2) } else { 3 * n + 1 }; steps++; } print(steps); // 111 diff --git a/docs/src/language/nil-safety.md b/docs/src/language/nil-safety.md index 27bd8556..2264821b 100644 --- a/docs/src/language/nil-safety.md +++ b/docs/src/language/nil-safety.md @@ -86,7 +86,7 @@ print(5 ?? loadDefault()); // 5 print(nil ?? nil ?? "last"); // last ``` -`??` binds looser than `||` and tighter than `? :`. +`??` binds looser than `||`. ## Leaving Early @@ -111,5 +111,5 @@ for row in [{ id: 1 }, {}, { id: 3 }] { print(ids); // [1, 3] ``` -They fit in `? :` and match arms too: `n < 10 ? n + 1 : break`, +They fit in `if` branches and match arms too: `if n < 10 { n + 1 } else { break }`, `0 => return "zero",`. diff --git a/docs/src/language/numbers.md b/docs/src/language/numbers.md index 781e6716..0586981d 100644 --- a/docs/src/language/numbers.md +++ b/docs/src/language/numbers.md @@ -50,7 +50,7 @@ print(math.ceil(items / perPage)); // 4 print(-7 % 3); // -1 print(7 / 0); // inf print(0 / 0 == math.NAN); // false -print(0 / 0 ? "truthy" : "falsy"); // falsy +print(if 0 / 0 { "truthy" } else { "falsy" }); // falsy ``` ```rune diff --git a/docs/src/language/pattern-matching.md b/docs/src/language/pattern-matching.md index ebf24157..27b2c835 100644 --- a/docs/src/language/pattern-matching.md +++ b/docs/src/language/pattern-matching.md @@ -21,7 +21,8 @@ print(status(503)); // server error 503 print(status(100)); // unknown ``` -An arm is `pattern => expression` or `pattern => { block }`. Arms are +An arm is `pattern => expression` or `pattern => { block }`, whose value +is the block's last expression, written without a `;`. Arms are separated by `,`, and the last may have one too. `return`, `break`, `continue` and `throw` are expressions, so `pattern => return x,` works. As after an arrow function's `=>`, `{` starts a block: an object is @@ -207,21 +208,26 @@ match 1 { 1 | x => 1, _ => 2 } // Error at 'x': Cannot bind variables in '|' pat ## Expression or Statement -As an expression its value is the arm's; a block arm gives `nil`. No arm matching is a `ValueError`: +As an expression its value is the arm's; a block arm ending with `;` +gives `nil`. No arm matching is a `ValueError`: ```rune let count = 3; let label = match count { 0 => "empty", 1 => "one item", - n => "{n} items", + n => { + let noun = if n < 10 { "items" } else { "many items" }; + "{n} {noun}" + }, }; print(label); // 3 items print(match 7 { 1 => "a" }); // ValueError: No match arm for 7. ``` -At the start of a statement it is a statement: values are dropped, and no +At the start of a statement it is a statement: values are dropped, unless +it ends a block that has a value, as a function body, and no arm matching is a `ValueError` all the same, so add `_ => {}` to ignore the rest. An arm may `return` from the enclosing function: diff --git a/docs/src/language/strings.md b/docs/src/language/strings.md index 10975fa5..318c54af 100644 --- a/docs/src/language/strings.md +++ b/docs/src/language/strings.md @@ -51,7 +51,7 @@ let total = 59.97; print("hi {user.name}"); // hi ann print("roles: {user.roles}"); // roles: ["admin", "ops"] print("{user.roles.len()} roles, total {"%.1f".format(total)}"); // 2 roles, total 60.0 -print("order is {total > 50 ? "big" : "small"}"); // order is big +print("order is {if total > 50 { "big" } else { "small" }}"); // order is big print("set \{name} in the template"); // set {name} in the template ``` diff --git a/docs/src/language/values.md b/docs/src/language/values.md index da9555b3..68706c54 100644 --- a/docs/src/language/values.md +++ b/docs/src/language/values.md @@ -89,7 +89,7 @@ Falsy values are `nil`, `false`, `0`, `NaN` and anything empty: `""`, ```rune for v in [nil, false, 0, "", [], {}, map(), "0", [0], { a: nil }] { - print("%q is %s".format(v, v ? "truthy" : "falsy")); + print("%q is %s".format(v, if v { "truthy" } else { "falsy" })); } // nil is falsy // false is falsy diff --git a/docs/src/stdlib/fs.md b/docs/src/stdlib/fs.md index d8b84c64..3366fd7c 100644 --- a/docs/src/stdlib/fs.md +++ b/docs/src/stdlib/fs.md @@ -49,7 +49,7 @@ fs.rename(fs.join(dir, "draft.md"), fs.join(dir, "post.md")); fs.mkdir(fs.join(dir, "images")); for f in fs.list(dir) { - print("{f.name} {f.isDir ? "dir" : f.size}"); + print("{f.name} {if f.isDir { "dir" } else { f.size }}"); } // backup.md 8 // images dir diff --git a/docs/src/stdlib/os.md b/docs/src/stdlib/os.md index fd7d91b4..b5749319 100644 --- a/docs/src/stdlib/os.md +++ b/docs/src/stdlib/os.md @@ -16,7 +16,7 @@ os.unsetEnv("APP_MODE"); print(os.env("APP_MODE")); // nil print("PATH" in os.environ()); // true -let shell = os.platform == "windows" ? "cmd" : "sh"; +let shell = if os.platform == "windows" { "cmd" } else { "sh" }; print(shell); // sh ``` diff --git a/examples/blog/content/hello-rune.md b/examples/blog/content/hello-rune.md index ad8ae6bc..cc22fc57 100644 --- a/examples/blog/content/hello-rune.md +++ b/examples/blog/content/hello-rune.md @@ -16,7 +16,7 @@ This post was rendered by a Rune program, see [the repo](https://github.com/kryp ```rune fun fib(n) { - return n < 2 ? n : fib(n - 1) + fib(n - 2); + return if n < 2 { n } else { fib(n - 1) + fib(n - 2) }; } ``` diff --git a/examples/blog/md/block.rn b/examples/blog/md/block.rn index b4274a2b..60c75514 100644 --- a/examples/blog/md/block.rn +++ b/examples/blog/md/block.rn @@ -7,13 +7,15 @@ export struct Heading { level, text, id } enum ListKind { Bullet, Numbered } impl ListKind { - fun tag(self) => match self { - ListKind.Bullet => "ul", - ListKind.Numbered => "ol", - }; + fun tag(self) { + match self { + ListKind.Bullet => "ul", + ListKind.Numbered => "ol", + } + } } -export fun slug(s) => regex.replace(r"[^a-z0-9]+", s.lower(), "-").trim("-"); +export fun slug(s) { regex.replace(r"[^a-z0-9]+", s.lower(), "-").trim("-") } export fun render(src) { let lines = src.split("\n"); @@ -38,7 +40,7 @@ export fun render(src) { } i++; - let cls = lang == "" ? "" : " class=\"lang-{lang}\""; + let cls = if lang == "" { "" } else { " class=\"lang-{lang}\"" }; doc.html.push("
{inline.escape(code.join("\n"))}
"); continue; } @@ -113,7 +115,7 @@ fun listItem(line) { } let [marker, text] = m.groups; - return { kind: marker.endsWith(".") ? ListKind.Numbered : ListKind.Bullet, text }; + return { kind: if marker.endsWith(".") { ListKind.Numbered } else { ListKind.Bullet }, text }; } fun startsBlock(line) { diff --git a/examples/blog/site/build.rn b/examples/blog/site/build.rn index caff8339..d22ef4e1 100644 --- a/examples/blog/site/build.rn +++ b/examples/blog/site/build.rn @@ -39,7 +39,7 @@ export fun load(dir, drafts = false) { }); } - posts.sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : 0); + posts.sort((a, b) => if a.date < b.date { 1 } else if a.date > b.date { -1 } else { 0 }); return Site { posts, skipped }; } diff --git a/examples/blog/site/template.rn b/examples/blog/site/template.rn index e67606ab..1a90cf81 100644 --- a/examples/blog/site/template.rn +++ b/examples/blog/site/template.rn @@ -26,7 +26,7 @@ export fun toc(headings) { let items = headings .filter(h => h.level == 2) .map(h => """
  • {inline.escape(h.text)}
  • """); - return items.len() < 2 ? "" : """"""; + return if items.len() < 2 { "" } else { """""" }; } export fun postLink(p, root = ".") { diff --git a/examples/calc.rn b/examples/calc.rn index d3c88381..47afd039 100644 --- a/examples/calc.rn +++ b/examples/calc.rn @@ -18,15 +18,17 @@ enum Node { } impl Node { - fun kind(self) => match self { - _ is Node.Num => "Num", - _ is Node.Var => "Var", - _ is Node.Neg => "Neg", - _ is Node.Binary => "Binary", - _ is Node.Call => "Call", - _ is Node.Assign => "Assign", - _ is Node.FunDef => "FunDef", - }; + fun kind(self) { + match self { + _ is Node.Num => "Num", + _ is Node.Var => "Var", + _ is Node.Neg => "Neg", + _ is Node.Binary => "Binary", + _ is Node.Call => "Call", + _ is Node.Assign => "Assign", + _ is Node.FunDef => "FunDef", + } + } } struct CalcError { message, pos = nil } @@ -59,9 +61,9 @@ let RIGHT_ASSOC = set(["^", "**"]); struct Parser { tokens, i = 0 } impl Parser { - fun new(src) => Parser { tokens: tokenize(src) }; + fun new(src) { Parser { tokens: tokenize(src) } } - fun peek(self) => self.tokens[self.i]; + fun peek(self) { self.tokens[self.i] } fun next(mut self) { let t = self.tokens[self.i]; @@ -120,7 +122,7 @@ impl Parser { } self.next(); - let nextMin = op in RIGHT_ASSOC ? prec : prec + 1; + let nextMin = if op in RIGHT_ASSOC { prec } else { prec + 1 }; left = Node.Binary { op, left, right: self.expr(nextMin) }; } @@ -182,7 +184,7 @@ let BUILTINS = map([ struct Env { vars, funs } impl Env { - fun new() => Env { vars: map({ pi: math.PI }), funs: map() }; + fun new() { Env { vars: map({ pi: math.PI }), funs: map() } } fun eval(mut self, node, locals = {}) { let ev = n => self.eval(n, locals); @@ -198,7 +200,7 @@ impl Env { "+" => a + b, "-" => a - b, "*" => a * b, - "/" => b == 0 ? throw CalcError { message: "division by zero" } : a / b, + "/" => if b == 0 { throw CalcError { message: "division by zero" } } else { a / b }, "%" => a % b, "^" | "**" => math.pow(a, b), }; @@ -238,11 +240,13 @@ impl Env { } } -fun show(v, digits = 6) => match v { - _ is string => v, - _ if math.isInt(v) => string(v), - _ => regex.replace("\\.?0+$", "%.*f".format(digits, v), ""), -}; +fun show(v, digits = 6) { + match v { + _ is string => v, + _ if math.isInt(v) => string(v), + _ => regex.replace("\\.?0+$", "%.*f".format(digits, v), ""), + } +} fun run(mut env, line) { try { diff --git a/examples/chess.rn b/examples/chess.rn index c7e8c931..f1505bdd 100644 --- a/examples/chess.rn +++ b/examples/chess.rn @@ -31,21 +31,21 @@ const INF = 1000000; struct FenError { message } -fun sq(file, rank) => 21 + file + rank * 10; -fun fileOf(s) => s % 10 - 1; -fun rankOf(s) => math.idiv(s, 10) - 2; -fun squareName(s) => "abcdefgh"[fileOf(s)] + string(rankOf(s) + 1); -fun color(side) => (1 - side) >> 1; - -fun encode(from, to, promo = 0, flag = 0) => from | to << 7 | promo << 14 | flag << 17; -fun moveFrom(m) => m & 127; -fun moveTo(m) => m >> 7 & 127; -fun movePromo(m) => m >> 14 & 7; -fun moveFlag(m) => m >> 17; +fun sq(file, rank) { 21 + file + rank * 10 } +fun fileOf(s) { s % 10 - 1 } +fun rankOf(s) { math.idiv(s, 10) - 2 } +fun squareName(s) { "abcdefgh"[fileOf(s)] + string(rankOf(s) + 1) } +fun color(side) { (1 - side) >> 1 } + +fun encode(from, to, promo = 0, flag = 0) { from | to << 7 | promo << 14 | flag << 17 } +fun moveFrom(m) { m & 127 } +fun moveTo(m) { m >> 7 & 127 } +fun movePromo(m) { m >> 14 & 7 } +fun moveFlag(m) { m >> 17 } fun moveName(m) { let promo = movePromo(m); - return squareName(moveFrom(m)) + squareName(moveTo(m)) + (promo != 0 ? PIECE_CHARS[promo] : ""); + return squareName(moveFrom(m)) + squareName(moveTo(m)) + (if promo != 0 { PIECE_CHARS[promo] } else { "" }); } // Piece-square tables from white's side, a8 first (Michniewski's simplified evaluation) @@ -114,7 +114,7 @@ const PST = [ ], ]; -fun pieceIndex(p, s) => (p + 6) * 120 + s; +fun pieceIndex(p, s) { (p + 6) * 120 + s } fun buildSquareScores() { let mut out = [0].repeat(13 * 120); @@ -148,7 +148,7 @@ fun random64() { let PIECE_KEYS = (0..13 * 120).map(_ => random64()); let CASTLE_KEYS = (0..16).map(_ => random64()); -let EP_KEYS = (0..120).map(i => i == 0 ? 0 : random64()); +let EP_KEYS = (0..120).map(i => if i == 0 { 0 } else { random64() }); let SIDE_KEY = random64(); fun castleMask() { @@ -213,11 +213,11 @@ impl Position { throw FenError { message: "bad rank '{row}'" }; } - let p = ch == ch.upper() ? t : -t; + let p = if ch == ch.upper() { t } else { -t }; board[sq(file, rank)] = p; if t == KING { - kings[color(p > 0 ? 1 : -1)] = sq(file, rank); + kings[color(if p > 0 { 1 } else { -1 })] = sq(file, rank); } file++; @@ -240,8 +240,8 @@ impl Position { } } - let epSquare = ep == "-" ? 0 : sq("abcdefgh".indexOf(ep[0]), int(ep[1]) - 1); - let pos = Position { board, side: side == "w" ? 1 : -1, castle: rights, ep: epSquare, half: int(half), kings }; + let epSquare = if ep == "-" { 0 } else { sq("abcdefgh".indexOf(ep[0]), int(ep[1]) - 1) }; + let pos = Position { board, side: if side == "w" { 1 } else { -1 }, castle: rights, ep: epSquare, half: int(half), kings }; return Position { ...pos, hash: pos.computeHash(), score: pos.computeScore() }; } @@ -283,8 +283,8 @@ impl Position { } } - let ep = self.ep == 0 ? "-" : squareName(self.ep); - return "{rows.join("/")} {self.side == 1 ? "w" : "b"} {rights == "" ? "-" : rights} {ep} {self.half} 1"; + let ep = if self.ep == 0 { "-" } else { squareName(self.ep) }; + return "{rows.join("/")} {if self.side == 1 { "w" } else { "b" }} {if rights == "" { "-" } else { rights }} {ep} {self.half} 1"; } fun computeHash(self) { @@ -363,8 +363,8 @@ impl Position { return false; } - fun inCheck(self) => self.attacked(self.kings[color(self.side)], -self.side); - fun leftInCheck(self) => self.attacked(self.kings[color(-self.side)], self.side); + fun inCheck(self) { self.attacked(self.kings[color(self.side)], -self.side) } + fun leftInCheck(self) { self.attacked(self.kings[color(-self.side)], self.side) } fun moves(self, quiet = true) { let b = self.board; @@ -383,11 +383,11 @@ impl Position { if t == PAWN { let fwd = 10 * side; let one = s + fwd; - let promotes = rankOf(one) == (side == 1 ? 7 : 0); + let promotes = rankOf(one) == (if side == 1 { 7 } else { 0 }); if b[one] == EMPTY && (quiet || promotes) { pushPawn(out, s, one, promotes); - let home = rankOf(s) == (side == 1 ? 1 : 6); + let home = rankOf(s) == (if side == 1 { 1 } else { 6 }); if quiet && home && b[one + fwd] == EMPTY { out.push(encode(s, one + fwd, 0, DOUBLE)); } @@ -407,7 +407,7 @@ impl Position { } if t == KNIGHT || t == KING { - for d in t == KNIGHT ? KNIGHT_DIRS : KING_DIRS { + for d in (if t == KNIGHT { KNIGHT_DIRS } else { KING_DIRS }) { let target = b[s + d]; if target == OFF || target * side > 0 { @@ -449,9 +449,9 @@ impl Position { fun castles(self, mut out) { let b = self.board; let side = self.side; - let rank = side == 1 ? 0 : 7; + let rank = if side == 1 { 0 } else { 7 }; let king = sq(4, rank); - let shift = side == 1 ? 0 : 2; + let shift = if side == 1 { 0 } else { 2 }; if self.castle & 1 << shift != 0 && b[king + 1] == EMPTY && b[king + 2] == EMPTY @@ -501,7 +501,7 @@ impl Position { score -= SQUARE_SCORE[pieceIndex(captured, to)]; } - let placed = promo != 0 ? promo * side : p; + let placed = if promo != 0 { promo * side } else { p }; self.board[from] = EMPTY; self.board[to] = placed; h ^= PIECE_KEYS[pieceIndex(placed, to)]; @@ -517,7 +517,7 @@ impl Position { score -= SQUARE_SCORE[pieceIndex(-PAWN * side, victim)]; self.board[victim] = EMPTY; } else if flag == CASTLE { - let [rookFrom, rookTo] = to > from ? [from + 3, from + 1] : [from - 4, from - 1]; + let [rookFrom, rookTo] = if to > from { [from + 3, from + 1] } else { [from - 4, from - 1] }; let rook = ROOK * side; self.board[rookFrom] = EMPTY; self.board[rookTo] = rook; @@ -529,7 +529,7 @@ impl Position { self.kings[color(side)] = to; } - self.half = p == PAWN * side || captured != EMPTY ? 0 : self.half + 1; + self.half = if p == PAWN * side || captured != EMPTY { 0 } else { self.half + 1 }; self.castle &= CASTLE_MASK[from] & CASTLE_MASK[to]; self.hash = h ^ CASTLE_KEYS[self.castle] ^ EP_KEYS[self.ep]; self.score = score; @@ -543,7 +543,7 @@ impl Position { let to = moveTo(m); let side = -self.side; let flag = moveFlag(m); - let p = movePromo(m) != 0 ? PAWN * side : self.board[to]; + let p = if movePromo(m) != 0 { PAWN * side } else { self.board[to] }; self.board[from] = p; self.board[to] = u.captured; @@ -551,7 +551,7 @@ impl Position { if flag == EN_PASSANT { self.board[to - 10 * side] = -PAWN * side; } else if flag == CASTLE { - let [rookFrom, rookTo] = to > from ? [from + 3, from + 1] : [from - 4, from - 1]; + let [rookFrom, rookTo] = if to > from { [from + 3, from + 1] } else { [from - 4, from - 1] }; self.board[rookTo] = EMPTY; self.board[rookFrom] = ROOK * side; } @@ -596,7 +596,7 @@ impl Position { fun pieceChar(p) { let ch = PIECE_CHARS[math.abs(p)]; - return p > 0 ? ch.upper() : ch; + return if p > 0 { ch.upper() } else { ch }; } fun pushPawn(mut out, from, to, promotes) { @@ -617,7 +617,7 @@ fun perft(mut pos, depth) { pos.make(m); if !pos.leftInCheck() { - nodes += depth == 1 ? 1 : perft(pos, depth - 1); + nodes += if depth == 1 { 1 } else { perft(pos, depth - 1) }; } pos.unmake(); @@ -690,7 +690,7 @@ impl Search { } let check = self.pos.inCheck(); - let remaining = check ? depth + 1 : depth; + let remaining = if check { depth + 1 } else { depth }; if remaining <= 0 { return self.quiesce(alpha, beta, ply); @@ -755,10 +755,10 @@ impl Search { } if legal == 0 { - return check ? -MATE + ply : 0; + return if check { -MATE + ply } else { 0 }; } - let bound = best >= beta ? Bound.Lower : best <= alpha ? Bound.Upper : Bound.Exact; + let bound = if best >= beta { Bound.Lower } else if best <= alpha { Bound.Upper } else { Bound.Exact }; self.tt[self.pos.hash] = Entry { depth: remaining, score: toTT(best, ply), bound, move: bestMove }; return best; } @@ -888,14 +888,14 @@ fun fromTT(score, ply) { fun scoreText(score) { if math.abs(score) > MATE - 1000 { let moves = math.idiv(MATE - math.abs(score) + 1, 2); - return score > 0 ? "mate {moves}" : "mated {moves}"; + return if score > 0 { "mate {moves}" } else { "mated {moves}" }; } return "%+.2f".format(score / 100); } fun printInfo({ depth, score, nodes, seconds, pv }) { - let nps = seconds > 0 ? math.round(nodes / seconds) : 0; + let nps = if seconds > 0 { math.round(nodes / seconds) } else { 0 }; print(" depth %2d %-9s nodes %8d nps %7d pv %s".format(depth, scoreText(score), nodes, nps, pv.join(" "))); } @@ -906,7 +906,7 @@ fun search(pos, seconds = 5, maxDepth = 64, report = printInfo) { fun gameOver(mut pos) { if !pos.legalMoves() { - return pos.inCheck() ? (pos.side == 1 ? "black wins by mate" : "white wins by mate") : "stalemate"; + return if pos.inCheck() { if pos.side == 1 { "black wins by mate" } else { "white wins by mate" } } else { "stalemate" }; } if pos.half >= 100 { @@ -934,7 +934,7 @@ fun demo() { let start = time.now(); let got = perft(pos, i + 1); let ms = math.round((time.now() - start) * 1000); - print(" %-9s depth %d %7d %s %5d ms".format(name, i + 1, got, got == want ? "ok" : "WRONG, want {want}", ms)); + print(" %-9s depth %d %7d %s %5d ms".format(name, i + 1, got, if got == want { "ok" } else { "WRONG, want {want}" }, ms)); } } @@ -949,7 +949,7 @@ fun demo() { for ply in 0..12 { let { move } = search(pos, 0.2, 64, nil); - line.push(ply % 2 == 0 ? "{ply / 2 + 1}. {moveName(move)}" : moveName(move)); + line.push(if ply % 2 == 0 { "{ply / 2 + 1}. {moveName(move)}" } else { moveName(move) }); pos.make(move); } @@ -965,7 +965,7 @@ fun perftCommand(depth, fen) { for m in pos.legalMoves() { pos.make(m); - let n = depth <= 1 ? 1 : perft(pos, depth - 1); + let n = if depth <= 1 { 1 } else { perft(pos, depth - 1) }; pos.unmake(); print("{moveName(m)}: {n}"); total += n; @@ -977,7 +977,7 @@ fun perftCommand(depth, fen) { fun play(human, seconds) { let mut pos = Position.fromFen(START_FEN); - print("you play {human == 1 ? "white" : "black"}; moves like e2e4 or e7e8q, 'quit' to stop"); + print("you play {if human == 1 { "white" } else { "black" }}; moves like e2e4 or e7e8q, 'quit' to stop"); while true { print("\n" + pos.show()); @@ -1056,7 +1056,7 @@ fun main(args) { let { move, score } = search(pos, seconds, depth); print("bestmove {moveName(move)} ({scoreText(score)})"); }, - "play" => play(free?.[0] == "black" ? -1 : 1, seconds), + "play" => play(if free?.[0] == "black" { -1 } else { 1 }, seconds), _ => throw UsageError { message: "unknown command '{command}'" }, }; } catch e is UsageError | FenError | ValueError { diff --git a/examples/kv/codec.rn b/examples/kv/codec.rn index 0656c477..bd73dd38 100644 --- a/examples/kv/codec.rn +++ b/examples/kv/codec.rn @@ -12,7 +12,7 @@ export const DEL = 1; export struct Loc { seg, start, recLen, size } impl Loc { - fun valueAt(self) => self.start + self.recLen - self.size; + fun valueAt(self) { self.start + self.recLen - self.size } } export struct Record { kind, key, start, recLen, size } diff --git a/examples/kv/main.rn b/examples/kv/main.rn index 1af723b3..7d33cc43 100644 --- a/examples/kv/main.rn +++ b/examples/kv/main.rn @@ -11,13 +11,13 @@ import .store; import .codec; -fun ms(since) => "%.1f ms".format((time.now() - since) * 1000); +fun ms(since) { "%.1f ms".format((time.now() - since) * 1000) } -fun kb(n) => n < 1024 ? "{n} B" : "%.1f KB".format(n / 1024); +fun kb(n) { if n < 1024 { "{n} B" } else { "%.1f KB".format(n / 1024) } } -fun show(info) => "{info.keys} keys, {info.segments} segments, {kb(info.size)} on disk, {kb(info.dead)} dead"; +fun show(info) { "{info.keys} keys, {info.segments} segments, {kb(info.size)} on disk, {kb(info.dead)} dead" } -fun files(dir) => fs.list(dir).map(f => "{f.name} {kb(f.size)}").join(", "); +fun files(dir) { fs.list(dir).map(f => "{f.name} {kb(f.size)}").join(", ") } fun demo() { let dir = fs.tempDir(); @@ -33,7 +33,7 @@ fun demo() { let mut t = time.now(); for i in 0..2000 { - db.put("user:%04d".format(i), { name: "user {i}", visits: 0, tags: i % 3 == 0 ? ["vip"] : [] }); + db.put("user:%04d".format(i), { name: "user {i}", visits: 0, tags: if i % 3 == 0 { ["vip"] } else { [] } }); } for round in 1..=3 { @@ -184,7 +184,7 @@ fun cli(dir, cmd, rest) { print(json.stringify(db.get(key))); }, - ["del", key] => db.delete(key) ? nil : 1, + ["del", key] => if db.delete(key) { nil } else { 1 }, ["scan", ...prefix] => { for [k, v] in db.scan(prefix.join("")) { print("{k}\t{json.stringify(v)}"); diff --git a/examples/kv/store.rn b/examples/kv/store.rn index 493dbd10..c24ede89 100644 --- a/examples/kv/store.rn +++ b/examples/kv/store.rn @@ -11,9 +11,9 @@ export struct KvError { message } struct Segment { log, hint, size = 0, live = 0, reader = nil } impl Segment { - fun at(dir, id) => Segment { log: fs.join(dir, "%06d.log".format(id)), hint: fs.join(dir, "%06d.hint".format(id)) }; + fun at(dir, id) { Segment { log: fs.join(dir, "%06d.log".format(id)), hint: fs.join(dir, "%06d.hint".format(id)) } } - fun name(self) => fs.base(self.log); + fun name(self) { fs.base(self.log) } fun added(mut self, n, alive) { self.size += n; @@ -92,7 +92,7 @@ impl Store { // sync: fsync after every write, not only flush it to the system fun open(dir, { maxSegment = 4 << 20, sync = false } = {}) { fs.mkdir(dir); - let lock = try fs.lock(fs.join(dir, "LOCK")) catch e is IOError => throw e.code == "locked" ? KvError { message: "{dir} is open elsewhere" } : e; + let lock = try fs.lock(fs.join(dir, "LOCK")) catch e is IOError => throw if e.code == "locked" { KvError { message: "{dir} is open elsewhere" } } else { e }; let mut db = Store { dir, maxSegment, sync, lock }; try { @@ -130,8 +130,8 @@ impl Store { } // A compacted segment, the one with a hint, is never appended to - let last = ids ? ids[-1] : 0; - self.active = last > 0 && !fs.exists(self.segs[last].hint) ? last : last + 1; + let last = if ids { ids[-1] } else { 0 }; + self.active = if last > 0 && !fs.exists(self.segs[last].hint) { last } else { last + 1 }; self.openActive(); rec.ms = (time.now() - started) * 1000; self.recovery = rec; @@ -240,7 +240,7 @@ impl Store { return true; } - fun has(self, key) => key in self.keydir; + fun has(self, key) { key in self.keydir } fun get(mut self, key, fallback = nil) { let loc = self.keydir?.[key] ?? return fallback; @@ -253,9 +253,9 @@ impl Store { return ks; } - fun scan(mut self, prefix = "") => self.keys(prefix).map(k => [k, self.get(k)]); + fun scan(mut self, prefix = "") { self.keys(prefix).map(k => [k, self.get(k)]) } - fun len(self) => self.keydir.len(); + fun len(self) { self.keydir.len() } fun info(self) { let mut size = 0; diff --git a/examples/log-report.rn b/examples/log-report.rn index 705efd4c..d62b706d 100644 --- a/examples/log-report.rn +++ b/examples/log-report.rn @@ -20,31 +20,33 @@ fun parseLine(line, n) { method, path: normalize(path), status: int(status), - bytes: bytes == "-" ? 0 : int(bytes), + bytes: if bytes == "-" { 0 } else { int(bytes) }, latency: number(latency) * 1000, }; } fun normalize(path) { let [base, ..._] = path.split("?"); - return base.split("/").map(seg => regex.test(r"^(\d+|[0-9a-f]{8,})$", seg) ? ":id" : seg).join("/"); + return base.split("/").map(seg => if regex.test(r"^(\d+|[0-9a-f]{8,})$", seg) { ":id" } else { seg }).join("/"); } -fun statusClass(code) => match code { - ..200 => "1xx", - 200..300 => "2xx", - 304 => "304", - 300..400 => "3xx", - 404 => "404", - 429 => "429", - 400..500 => "4xx", - _ => "5xx", -}; +fun statusClass(code) { + match code { + ..200 => "1xx", + 200..300 => "2xx", + 304 => "304", + 300..400 => "3xx", + 404 => "404", + 429 => "429", + 400..500 => "4xx", + _ => "5xx", + } +} struct Stats { count = 0, errors = 0, bytes = 0, latencies = [] } impl Stats { - fun new() => Stats {}; + fun new() { Stats {} } fun add(mut self, { status, bytes, latency }) { self.count++; @@ -63,7 +65,7 @@ impl Stats { return ps.map(p => xs[math.min(xs.len() - 1, math.floor(xs.len() * p / 100))]); } - fun errorRate(self) => self.count == 0 ? 0 : self.errors / self.count * 100; + fun errorRate(self) { if self.count == 0 { 0 } else { self.errors / self.count * 100 } } } const TOP_SLOW = 5; @@ -78,7 +80,7 @@ struct Report { } impl Report { - fun new() => Report {}; + fun new() { Report {} } fun add(mut self, e) { self.total++; @@ -143,7 +145,7 @@ fun analyze(path) { } fun bar(value, max, width = 24) { - let n = max == 0 ? 0 : math.round(value / max * width); + let n = if max == 0 { 0 } else { math.round(value / max * width) }; return "█".repeat(n) + "·".repeat(width - n); } @@ -162,7 +164,7 @@ fun table(headers, rows) { for i, c in cells { let s = string(c); - out.push(i == 0 ? s.padEnd(widths[i]) : s.padStart(widths[i])); + out.push(if i == 0 { s.padEnd(widths[i]) } else { s.padStart(widths[i]) }); } return out.join(" "); @@ -176,7 +178,7 @@ fun table(headers, rows) { } fun printReport(r) { - print("== {r.total} requests, {r.skipped.len()} malformed lines skipped" + (r.skipped ? " (lines {r.skipped[..5].join(", ")})" : "")); + print("== {r.total} requests, {r.skipped.len()} malformed lines skipped" + (if r.skipped { " (lines {r.skipped[..5].join(", ")})" } else { "" })); print(""); let mut rows = []; @@ -223,7 +225,7 @@ fun printReport(r) { print(""); print("slowest requests:"); for { time, method, path, status, latency } in r.slowest { - let flag = status >= 500 ? " !" : ""; + let flag = if status >= 500 { " !" } else { "" }; print(" %8.1f ms %s %s %s → %d%s".format(latency, time, method, path, status, flag)); } } @@ -248,16 +250,16 @@ fun toJson(r) { struct Rng { seed } impl Rng { - fun new(seed) => Rng { seed }; + fun new(seed) { Rng { seed } } fun next(mut self) { self.seed = (self.seed * 1103515245 + 12345) & 0x7fffffff; return self.seed >> 8; } - fun int(mut self, n) => self.next() % n; + fun int(mut self, n) { self.next() % n } - fun pick(mut self, xs) => xs[self.int(xs.len())]; + fun pick(mut self, xs) { xs[self.int(xs.len())] } } const IPS = ["203.0.113.7", "198.51.100.23", "192.0.2.44", "203.0.113.90", "198.51.100.5"]; @@ -270,7 +272,7 @@ let ROUTES = [ Route { method: "POST", path: _ => "/api/orders", ms: 80 }, Route { method: "GET", path: n => "/api/orders/{n % 100000}?expand=items", ms: 35 }, Route { method: "GET", path: _ => "/health", ms: 1 }, - Route { method: "GET", path: n => "/static/app." + (n % 2 == 0 ? "js" : "css"), ms: 3 }, + Route { method: "GET", path: n => "/static/app." + (if n % 2 == 0 { "js" } else { "css" }), ms: 3 }, ]; fun generate(path, n = 400) { @@ -286,16 +288,16 @@ fun generate(path, n = 400) { let roll = rng.int(100); let status = match roll { - ..82 => route.method == "POST" ? 201 : 200, + ..82 => if route.method == "POST" { 201 } else { 200 }, 82..88 => 304, 88..93 => 404, 93..95 => 429, _ => [500, 502, 503][rng.int(3)], }; - let spike = rng.int(50) == 0 ? 40 : 1; + let spike = if rng.int(50) == 0 { 40 } else { 1 }; let latency = route.ms * spike * (0.5 + rng.int(1000) / 1000) / 1000; - let size = status == 304 ? "-" : string(200 + rng.int(8000)); + let size = if status == 304 { "-" } else { string(200 + rng.int(8000)) }; let sec = i * 7; let time = "12/Nov/2026:%02d:%02d:%02d".format(10 + math.idiv(sec, 3600), math.idiv(sec, 60) % 60, sec % 60); diff --git a/examples/query/aggregate.rn b/examples/query/aggregate.rn index 75c3e0d5..6a174af0 100644 --- a/examples/query/aggregate.rn +++ b/examples/query/aggregate.rn @@ -10,7 +10,7 @@ struct AggSpec { fn, arg, distinct } // specs compiles the aggregate calls against the rows' scope. export fun specs(calls, scope) { return calls.map(e => { - if e.args.len() != (e.star ? 0 : 1) { + if e.args.len() != (if e.star { 0 } else { 1 }) { throw ast.SqlError { message: "{e.name} takes one argument", pos: e.pos }; } @@ -20,7 +20,7 @@ export fun specs(calls, scope) { return AggSpec { fn: Agg(e.name[0] + e.name[1..].lower()), - arg: e.star ? nil : expr.compile(e.args[0], expr.Ctx { scope }), + arg: if e.star { nil } else { expr.compile(e.args[0], expr.Ctx { scope }) }, distinct: e.distinct, }; }); @@ -107,15 +107,15 @@ fun finish(a, v) { return match a.fn { Agg.Count => xs.len(), - Agg.Sum => xs ? xs.reduce((x, y) => x + y) : nil, - Agg.Avg => xs ? xs.reduce((x, y) => x + y) / xs.len() : nil, - Agg.Min => xs.reduce((x, y) => expr.compare(x, y) <= 0 ? x : y, nil), - Agg.Max => xs.reduce((x, y) => expr.compare(x, y) >= 0 ? x : y, nil), + Agg.Sum => if xs { xs.reduce((x, y) => x + y) } else { nil }, + Agg.Avg => if xs { xs.reduce((x, y) => x + y) / xs.len() } else { nil }, + Agg.Min => xs.reduce((x, y) => if expr.compare(x, y) <= 0 { x } else { y }, nil), + Agg.Max => xs.reduce((x, y) => if expr.compare(x, y) >= 0 { x } else { y }, nil), }; } return match a.fn { - Agg.Avg => v[1] == 0 ? nil : v[0] / v[1], + Agg.Avg => if v[1] == 0 { nil } else { v[0] / v[1] }, _ => v, }; } diff --git a/examples/query/ast.rn b/examples/query/ast.rn index 43192887..a2ac2e78 100644 --- a/examples/query/ast.rn +++ b/examples/query/ast.rn @@ -35,33 +35,37 @@ export struct Select { export let AGGREGATES = set(["COUNT", "SUM", "AVG", "MIN", "MAX"]); -export fun isAggregate(e) => e is Call && e.name in AGGREGATES; - -export fun sql(e) => match e { - Lit { value: nil } => "NULL", - Lit { value: true } => "TRUE", - Lit { value: false } => "FALSE", - Lit { value: v is string } => "'" + v.replace("'", "''") + "'", - Lit { value } => string(value), - Col { table: nil, name } => name, - Col { table, name } => "{table}.{name}", - Unary { op: "NOT", expr } => "NOT {sql(expr)}", - Unary { op, expr } => op + sql(expr), - Binary { op, left, right } => "{wrap(left)} {op} {wrap(right)}", - Call { name, star: true } => "{name}(*)", - Call { name, args, distinct } => "{name}({distinct ? "DISTINCT " : ""}{args.map(sql).join(", ")})", - IsNull { expr, not } => "{wrap(expr)} IS {not ? "NOT " : ""}NULL", - InList { expr, list, not } => "{wrap(expr)} {not ? "NOT " : ""}IN ({list.map(sql).join(", ")})", - Between { expr, lo, hi, not } => "{wrap(expr)} {not ? "NOT " : ""}BETWEEN {wrap(lo)} AND {wrap(hi)}", - Like { expr, pattern, not } => "{wrap(expr)} {not ? "NOT " : ""}LIKE {sql(pattern)}", - Case { whens, otherwise } => "CASE " + whens.map(([c, v]) => "WHEN {sql(c)} THEN {sql(v)} ").join("") - + (otherwise == nil ? "" : "ELSE {sql(otherwise)} ") + "END", -}; - -fun wrap(e) => match e { - _ is Binary | IsNull | InList | Between | Like => "({sql(e)})", - _ => sql(e), -}; +export fun isAggregate(e) { e is Call && e.name in AGGREGATES } + +export fun sql(e) { + match e { + Lit { value: nil } => "NULL", + Lit { value: true } => "TRUE", + Lit { value: false } => "FALSE", + Lit { value: v is string } => "'" + v.replace("'", "''") + "'", + Lit { value } => string(value), + Col { table: nil, name } => name, + Col { table, name } => "{table}.{name}", + Unary { op: "NOT", expr } => "NOT {sql(expr)}", + Unary { op, expr } => op + sql(expr), + Binary { op, left, right } => "{wrap(left)} {op} {wrap(right)}", + Call { name, star: true } => "{name}(*)", + Call { name, args, distinct } => "{name}({if distinct { "DISTINCT " } else { "" }}{args.map(sql).join(", ")})", + IsNull { expr, not } => "{wrap(expr)} IS {if not { "NOT " } else { "" }}NULL", + InList { expr, list, not } => "{wrap(expr)} {if not { "NOT " } else { "" }}IN ({list.map(sql).join(", ")})", + Between { expr, lo, hi, not } => "{wrap(expr)} {if not { "NOT " } else { "" }}BETWEEN {wrap(lo)} AND {wrap(hi)}", + Like { expr, pattern, not } => "{wrap(expr)} {if not { "NOT " } else { "" }}LIKE {sql(pattern)}", + Case { whens, otherwise } => "CASE " + whens.map(([c, v]) => "WHEN {sql(c)} THEN {sql(v)} ").join("") + + (if otherwise == nil { "" } else { "ELSE {sql(otherwise)} " }) + "END", + } +} + +fun wrap(e) { + match e { + _ is Binary | IsNull | InList | Between | Like => "({sql(e)})", + _ => sql(e), + } +} fun children(e) { return match e { @@ -110,7 +114,7 @@ export fun rewrite(e, f) { _ is Between => Between { ...e, expr: r(e.expr), lo: r(e.lo), hi: r(e.hi) }, _ is Case => Case { whens: e.whens.map(([c, v]) => [r(c), r(v)]), - otherwise: e.otherwise == nil ? nil : r(e.otherwise), + otherwise: if e.otherwise == nil { nil } else { r(e.otherwise) }, }, _ => e, }); @@ -136,13 +140,15 @@ export fun aggregatesIn(e) { return out; } -export fun conjuncts(e) => match e { - nil => [], - Binary { op: "AND", left, right } => [...conjuncts(left), ...conjuncts(right)], - _ => [e], -}; +export fun conjuncts(e) { + match e { + nil => [], + Binary { op: "AND", left, right } => [...conjuncts(left), ...conjuncts(right)], + _ => [e], + } +} -export fun allOf(preds) => preds.reduce((a, b) => Binary { op: "AND", left: a, right: b }); +export fun allOf(preds) { preds.reduce((a, b) => Binary { op: "AND", left: a, right: b }) } export fun suggest(word, options) { let w = word.lower(); @@ -157,7 +163,7 @@ export fun suggest(word, options) { } } - return best == nil ? "" : ", did you mean '{best}'?"; + return if best == nil { "" } else { ", did you mean '{best}'?" }; } fun distance(a, b) { @@ -167,7 +173,7 @@ fun distance(a, b) { let mut cur = [i]; for j in 1..b.len() + 1 { - let cost = a[i - 1] == b[j - 1] ? 0 : 1; + let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 }; cur.push(math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)); } diff --git a/examples/query/demo.rn b/examples/query/demo.rn index 63e91704..5fa70ef4 100644 --- a/examples/query/demo.rn +++ b/examples/query/demo.rn @@ -12,9 +12,9 @@ impl Rng { return (self.state >>> 11) / 9007199254740992; } - fun int(mut self, n) => math.floor(self.next() * n); + fun int(mut self, n) { math.floor(self.next() * n) } - fun pick(mut self, xs) => xs[self.int(xs.len())]; + fun pick(mut self, xs) { xs[self.int(xs.len())] } } const FIRST = ["Ann", "Bob", "Chen", "Dana", "Emil", "Fatima", "Goran", "Hana", "Ivan", "Jo", "Kemal", "Lena", "Mia", "Nils", "Olga", "Priya"]; @@ -34,7 +34,7 @@ export fun generate(dir, orders) { out.write("id,name,country,signup\n"); for id in 1..customers + 1 { - let suffix = rng.int(40) == 0 ? ", Jr." : ""; + let suffix = if rng.int(40) == 0 { ", Jr." } else { "" }; let name = "{rng.pick(FIRST)} {rng.pick(LAST)}{suffix}"; let signup = "2025-%02d-%02d".format(rng.int(12) + 1, rng.int(28) + 1); out.write([id, name, rng.pick(COUNTRIES), signup].map(table.quoteCsv).join(",") + "\n"); @@ -61,7 +61,7 @@ export fun generate(dir, orders) { // a few customers never order: ids above 4900 are skipped let customer = rng.int(customers - 100) + 1; let created = "2026-%02d-%02d".format(rng.int(10) + 1, rng.int(28) + 1); - let coupon = rng.int(5) == 0 ? rng.pick(["WELCOME10", "BLACKFRIDAY", "VIP"]) : ""; + let coupon = if rng.int(5) == 0 { rng.pick(["WELCOME10", "BLACKFRIDAY", "VIP"]) } else { "" }; out.write("{id},{customer},{rng.int(products) + 1},{rng.int(4) + 1},{rng.pick(STATUSES)},{created},{coupon}\n"); } diff --git a/examples/query/expr.rn b/examples/query/expr.rn index fd937d52..74d53c81 100644 --- a/examples/query/expr.rn +++ b/examples/query/expr.rn @@ -8,9 +8,9 @@ struct Field { table, name } export struct Scope { fields = [] } impl Scope { - fun of(alias, columns) => Scope { fields: columns.map(name => Field { table: alias, name }) }; + fun of(alias, columns) { Scope { fields: columns.map(name => Field { table: alias, name }) } } - fun plus(self, other) => Scope { fields: [...self.fields, ...other.fields] }; + fun plus(self, other) { Scope { fields: [...self.fields, ...other.fields] } } fun find(self, col) { let mut found = -1; @@ -45,7 +45,7 @@ impl Scope { throw ast.SqlError { message: "unknown column '{ast.sql(col)}'" + ast.suggest(col.name, names), pos: col.pos }; } - fun covers(self, e) => ast.columnsOf(e).every(c => self.find(c) >= 0); + fun covers(self, e) { ast.columnsOf(e).every(c => self.find(c) >= 0) } // check fails on the first column of e it has not. fun check(self, e) { @@ -88,7 +88,7 @@ export fun compile(e, ctx) { return row => { let v = f(row); - return v == nil ? nil : -v; + return if v == nil { nil } else { -v }; }; }, ast.Unary { op: "NOT", expr } => { @@ -96,7 +96,7 @@ export fun compile(e, ctx) { return row => { let v = f(row); - return v == nil ? nil : !v; + return if v == nil { nil } else { !v }; }; }, ast.Binary { op: "AND", left, right } => { @@ -115,7 +115,7 @@ export fun compile(e, ctx) { return false; } - return a == nil || b == nil ? nil : true; + return if a == nil || b == nil { nil } else { true }; }; }, ast.Binary { op: "OR", left, right } => { @@ -134,7 +134,7 @@ export fun compile(e, ctx) { return true; } - return a == nil || b == nil ? nil : false; + return if a == nil || b == nil { nil } else { false }; }; }, ast.Binary { op, left, right } => binary(op, c(left), c(right)), @@ -150,7 +150,7 @@ export fun compile(e, ctx) { return row => { let v = f(row); - return v == nil ? nil : v in values != not; + return if v == nil { nil } else { v in values != not }; }; } @@ -158,7 +158,7 @@ export fun compile(e, ctx) { return row => { let v = f(row); - return v == nil ? nil : fs.some(g => g(row) == v) != not; + return if v == nil { nil } else { fs.some(g => g(row) == v) != not }; }; }, ast.Between { expr, lo, hi, not } => { @@ -180,13 +180,13 @@ export fun compile(e, ctx) { return row => { let v = f(row); - return v == nil ? nil : regex.test(re, string(v)) != not; + return if v == nil { nil } else { regex.test(re, string(v)) != not }; }; }, ast.Like { pattern } => throw ast.SqlError { message: "LIKE takes a string literal", pos: ast.columnsOf(pattern)?.[0]?.pos }, ast.Case { whens, otherwise } => { let arms = whens.map(([cond, v]) => [c(cond), c(v)]); - let other = otherwise == nil ? (_ => nil) : c(otherwise); + let other = if otherwise == nil { _ => nil } else { c(otherwise) }; return row => { for [cond, v] in arms { @@ -224,15 +224,15 @@ fun binary(op, l, r) { let strict = f => row => { let a = l(row); let b = r(row); - return a == nil || b == nil ? nil : f(a, b); + return if a == nil || b == nil { nil } else { f(a, b) }; }; return match op { "+" => strict((a, b) => a + b), "-" => strict((a, b) => a - b), "*" => strict((a, b) => a * b), - "/" => strict((a, b) => b == 0 ? nil : a / b), - "%" => strict((a, b) => b == 0 ? nil : a % b), + "/" => strict((a, b) => if b == 0 { nil } else { a / b }), + "%" => strict((a, b) => if b == 0 { nil } else { a % b }), "||" => strict((a, b) => string(a) + string(b)), "=" => strict((a, b) => a == b), "<>" => strict((a, b) => a != b), @@ -255,7 +255,7 @@ let SCALARS = { SUBSTR: Scalar { f: (s, start, n = nil) => { let from = math.max(start - 1, 0); - return n == nil ? string(s)[from..] : string(s)[from..from + n]; + return if n == nil { string(s)[from..] } else { string(s)[from..from + n] }; }, min: 2, max: 3, @@ -269,17 +269,17 @@ fun scalar(name, fs, pos) { }; if fs.len() < min || fs.len() > max { - throw ast.SqlError { message: "{name} takes {min == max ? min : "{min} to {max}"} arguments, got {fs.len()}", pos }; + throw ast.SqlError { message: "{name} takes {if min == max { min } else { "{min} to {max}" }} arguments, got {fs.len()}", pos }; } return match fs { [a] => row => { let x = a(row); - return x == nil ? nil : f(x); + return if x == nil { nil } else { f(x) }; }, _ => row => { let xs = fs.map(g => g(row)); - return nil in xs ? nil : f(...xs); + return if nil in xs { nil } else { f(...xs) }; }, }; } @@ -310,8 +310,8 @@ export fun compare(a, b) { } if (a is number) != (b is number) { - return a is number ? -1 : 1; + return if a is number { -1 } else { 1 }; } - return a < b ? -1 : 1; + return if a < b { -1 } else { 1 }; } diff --git a/examples/query/main.rn b/examples/query/main.rn index 0e70debe..4629e0f3 100644 --- a/examples/query/main.rn +++ b/examples/query/main.rn @@ -22,7 +22,7 @@ fun run(src, mut catalog, format) { if q.explain { for i, s in p.steps { - print("{" ".repeat(i)}{i == 0 ? "" : "└ "}{s.label}"); + print("{" ".repeat(i)}{if i == 0 { "" } else { "└ " }}{s.label}"); } return; @@ -31,7 +31,7 @@ fun run(src, mut catalog, format) { let rows = p.execute(); output.write(format, p.columns, rows); if format == "table" { - print("({rows.len()} row{rows.len() == 1 ? "" : "s"}, {"%.1f".format((time.now() - started) * 1000)} ms)"); + print("({rows.len()} row{if rows.len() == 1 { "" } else { "s" }}, {"%.1f".format((time.now() - started) * 1000)} ms)"); } } @@ -112,14 +112,14 @@ fun main(args) { line = io.readLine(); } - return failed > 0 ? 1 : 0; + return if failed > 0 { 1 } else { 0 }; } if rest.len() != 1 { return usage(); } - return tryRun(rest[0], catalog, format) ? 0 : 1; + return if tryRun(rest[0], catalog, format) { 0 } else { 1 }; } fun usage() { diff --git a/examples/query/output.rn b/examples/query/output.rn index ef971392..fe721a41 100644 --- a/examples/query/output.rn +++ b/examples/query/output.rn @@ -29,7 +29,7 @@ fun printTable(columns, rows) { let right = columns.map((_, i) => rows.len() > 0 && rows.every(r => r[i] == nil || r[i] is number)); - let line = row => row.map((c, i) => right[i] ? c.padStart(widths[i]) : c.padEnd(widths[i])).join(" ").trimEnd() + "\n"; + let line = row => row.map((c, i) => if right[i] { c.padStart(widths[i]) } else { c.padEnd(widths[i]) }).join(" ").trimEnd() + "\n"; io.write(line(columns)); io.write(widths.map(w => "─".repeat(w)).join(" ") + "\n"); for row in cells { @@ -37,11 +37,13 @@ fun printTable(columns, rows) { } } -fun cell(v) => match v { - nil => "NULL", - _ is number if !math.isInt(v) => string(math.round(v * 100) / 100), - _ => string(v), -}; +fun cell(v) { + match v { + nil => "NULL", + _ is number if !math.isInt(v) => string(math.round(v * 100) / 100), + _ => string(v), + } +} export fun error(src, e) { io.eprint("error: {e.message}"); diff --git a/examples/query/parser.rn b/examples/query/parser.rn index 82071c54..ccce577f 100644 --- a/examples/query/parser.rn +++ b/examples/query/parser.rn @@ -50,7 +50,7 @@ export fun parse(src) { struct Parser { tokens, i = 0 } impl Parser { - fun peek(self, ahead = 0) => self.tokens[math.min(self.i + ahead, self.tokens.len() - 1)]; + fun peek(self, ahead = 0) { self.tokens[math.min(self.i + ahead, self.tokens.len() - 1)] } fun next(mut self) { let t = self.tokens[self.i]; @@ -84,7 +84,7 @@ impl Parser { fun fail(self, message) { let t = self.peek(); - throw ast.SqlError { message: "{message}, got {t.kind == Kind.Eof ? t.text : "'{t.text}'"}", pos: t.pos }; + throw ast.SqlError { message: "{message}, got {if t.kind == Kind.Eof { t.text } else { "'{t.text}'" }}", pos: t.pos }; } fun atName(self) { @@ -134,7 +134,7 @@ impl Parser { joins.push(ast.Join { left, table, on: self.expr(0) }); } - let where = self.accept("WHERE") ? self.expr(0) : nil; + let where = if self.accept("WHERE") { self.expr(0) } else { nil }; let mut groupBy = []; @@ -143,7 +143,7 @@ impl Parser { groupBy = self.exprs(); } - let having = self.accept("HAVING") ? self.expr(0) : nil; + let having = if self.accept("HAVING") { self.expr(0) } else { nil }; let mut orderBy = []; @@ -155,8 +155,8 @@ impl Parser { } } - let limit = self.accept("LIMIT") ? self.count("LIMIT") : nil; - let offset = self.accept("OFFSET") ? self.count("OFFSET") : 0; + let limit = if self.accept("LIMIT") { self.count("LIMIT") } else { nil }; + let offset = if self.accept("OFFSET") { self.count("OFFSET") } else { 0 }; self.accept(";"); @@ -205,14 +205,14 @@ impl Parser { return ast.Item { expr, alias: self.name("a column alias") }; } - return ast.Item { expr, alias: self.atName() ? self.next().text : nil }; + return ast.Item { expr, alias: if self.atName() { self.next().text } else { nil } }; } fun table(mut self) { let pos = self.peek().pos; let name = self.name("a table name"); self.accept("AS"); - return ast.TableRef { name, alias: self.atName() ? self.next().text : name, pos }; + return ast.TableRef { name, alias: if self.atName() { self.next().text } else { name }, pos }; } fun expr(mut self, minPrec) { @@ -221,7 +221,7 @@ impl Parser { while true { let t = self.peek(); let op = t.word ?? t.text; - let prec = t.kind == Kind.Op || t.kind == Kind.Id ? (PRECEDENCE?.[op] ?? -1) : -1; + let prec = if t.kind == Kind.Op || t.kind == Kind.Id { PRECEDENCE?.[op] ?? -1 } else { -1 }; if prec < minPrec || prec < 0 { break; @@ -233,7 +233,7 @@ impl Parser { "IS" => self.isNull(left), "NOT" => self.postfix(left, self.next().word, true), "IN" | "BETWEEN" | "LIKE" => self.postfix(left, op, false), - _ => ast.Binary { op: op == "!=" ? "<>" : op, left, right: self.expr(prec + 1) }, + _ => ast.Binary { op: if op == "!=" { "<>" } else { op }, left, right: self.expr(prec + 1) }, }; } @@ -320,7 +320,7 @@ impl Parser { } let distinct = self.accept("DISTINCT"); - let args = self.at(")") ? [] : self.exprs(); + let args = if self.at(")") { [] } else { self.exprs() }; self.expect(")"); if distinct && name !in ast.AGGREGATES { @@ -343,7 +343,7 @@ impl Parser { self.fail("expected WHEN"); } - let otherwise = self.accept("ELSE") ? self.expr(0) : nil; + let otherwise = if self.accept("ELSE") { self.expr(0) } else { nil }; self.expect("END"); return ast.Case { whens, otherwise }; } diff --git a/examples/query/plan.rn b/examples/query/plan.rn index e43e60fc..b4e1015e 100644 --- a/examples/query/plan.rn +++ b/examples/query/plan.rn @@ -91,7 +91,7 @@ fun place(conds, base, stages) { let i = stages.findIndex(s => s.joined.covers(c)); if i == nil { - let all = stages ? stages[-1].joined : base; + let all = if stages { stages[-1].joined } else { base }; all.check(c); } @@ -116,24 +116,24 @@ fun filter(conds, ctx) { return rows => rows.filter(r => ok(r) == true); } -fun whereText(conds) => conds ? " where {ast.sql(ast.allOf(conds))}" : ""; +fun whereText(conds) { if conds { " where {ast.sql(ast.allOf(conds))}" } else { "" } } -fun describe(ref) => ref.alias == ref.name ? ref.name : "{ref.name} {ref.alias}"; +fun describe(ref) { if ref.alias == ref.name { ref.name } else { "{ref.name} {ref.alias}" } } // An ON with a conjunct a = b, each side on one table, is a hash join on // it, the rest checked on each match; anything else is a nested loop. fun joinStep(s, pushed) { let { join: j, table, left, right, joined } = s; let rightRows = filter(pushed, expr.Ctx { scope: right }); - let pad = j.left ? right.fields.map(_ => nil) : nil; + let pad = if j.left { right.fields.map(_ => nil) } else { nil }; let parts = ast.conjuncts(j.on); let eq = parts.findIndex(e => sides(e, left, right) != nil); - let rest = eq == nil ? parts : [...parts[..eq], ...parts[eq + 1..]]; - let check = rest ? expr.compile(ast.allOf(rest), expr.Ctx { scope: joined }) : nil; + let rest = if eq == nil { parts } else { [...parts[..eq], ...parts[eq + 1..]] }; + let check = if rest { expr.compile(ast.allOf(rest), expr.Ctx { scope: joined }) } else { nil }; let label = "{describe(j.table)} ({table.rows.len()} rows) on {ast.sql(j.on)}{whereText(pushed)}"; - let outer = j.left ? "left " : ""; + let outer = if j.left { "left " } else { "" }; if eq == nil { return Step { label: "{outer}nested loop join {label}", run: rows => { @@ -168,11 +168,13 @@ fun joinStep(s, pushed) { } }; } -fun sides(e, left, right) => match e { - ast.Binary { op: "=", left: a, right: b } if left.covers(a) && right.covers(b) => [a, b], - ast.Binary { op: "=", left: a, right: b } if left.covers(b) && right.covers(a) => [b, a], - _ => nil, -}; +fun sides(e, left, right) { + match e { + ast.Binary { op: "=", left: a, right: b } if left.covers(a) && right.covers(b) => [a, b], + ast.Binary { op: "=", left: a, right: b } if left.covers(b) && right.covers(a) => [b, a], + _ => nil, + } +} // joinRows pairs each row with the candidates check passes, or with pad if // none does and the join is outer. @@ -209,11 +211,11 @@ fun output(q, scope) { let columns = items.map(columnName); let texts = items.map(it => ast.sql(it.expr)); let aliased = map(items.filter(it => it.alias != nil).map(it => [it.alias, it.expr])); - let unalias = e => ast.rewrite(e, n => n is ast.Col && n.table == nil && n.name in aliased && scope.find(n) < 0 ? aliased[n.name] : n); + let unalias = e => ast.rewrite(e, n => if n is ast.Col && n.table == nil && n.name in aliased && scope.find(n) < 0 { aliased[n.name] } else { n }); let groupBy = q.groupBy.map(e => { let i = ordinal(e, items, "GROUP BY"); - let g = i == nil ? unalias(e) : items[i].expr; + let g = if i == nil { unalias(e) } else { items[i].expr }; let a = ast.aggregatesIn(g)?.[0]; if a != nil { @@ -223,7 +225,7 @@ fun output(q, scope) { return g; }); - let having = q.having == nil ? nil : unalias(q.having); + let having = if q.having == nil { nil } else { unalias(q.having) }; let order = q.orderBy.map(({ expr: e, desc }) => { let i = ordinal(e, items, "ORDER BY") ?? texts.indexOf(ast.sql(unalias(e))); @@ -231,7 +233,7 @@ fun output(q, scope) { }); let mut calls = []; - let computed = [...items.map(it => it.expr), ...(having == nil ? [] : [having]), ...order.filter(o => o.column == nil).map(o => o.expr)]; + let computed = [...items.map(it => it.expr), ...(if having == nil { [] } else { [having] }), ...order.filter(o => o.column == nil).map(o => o.expr)]; for e in computed { for c in ast.aggregatesIn(e) { @@ -247,8 +249,8 @@ fun output(q, scope) { if groupBy || having != nil || calls { let keys = groupBy.map(e => expr.compile(e, ctx)); let aggs = agg.specs(calls, scope); - let by = groupBy ? groupBy.map(ast.sql).join(", ") : "()"; - let computing = calls ? " computing " + calls.map(ast.sql).join(", ") : ""; + let by = if groupBy { groupBy.map(ast.sql).join(", ") } else { "()" }; + let computing = if calls { " computing " + calls.map(ast.sql).join(", ") } else { "" }; steps.push(Step { label: "group by {by}{computing}", run: rows => agg.aggregate(rows, keys, aggs) }); ctx = expr.Ctx { scope, group: [...groupBy, ...calls].map(ast.sql) }; @@ -258,11 +260,11 @@ fun output(q, scope) { } let project = items.map(it => expr.compile(it.expr, ctx)); - let keys = order.map(o => o.column == nil ? expr.compile(o.expr, ctx) : nil); + let keys = order.map(o => if o.column == nil { expr.compile(o.expr, ctx) } else { nil }); let sorted = order.len() > 0; - let stop = !sorted && !q.distinct && q.limit != nil ? q.offset + q.limit : -1; + let stop = if !sorted && !q.distinct && q.limit != nil { q.offset + q.limit } else { -1 }; - steps.push(Step { label: "project {columns.join(", ")}{stop >= 0 ? ", first {stop} rows" : ""}", run: rows => { + steps.push(Step { label: "project {columns.join(", ")}{if stop >= 0 { ", first {stop} rows" } else { "" }}", run: rows => { let mut out = []; for r in rows { @@ -271,7 +273,7 @@ fun output(q, scope) { } let row = project.map(f => f(r)); - out.push(sorted ? [row, order.map((o, i) => o.column != nil ? row[o.column] : (keys[i])(r))] : row); + out.push(if sorted { [row, order.map((o, i) => if o.column != nil { row[o.column] } else { (keys[i])(r) })] } else { row }); } return out; @@ -283,7 +285,7 @@ fun output(q, scope) { let mut out = []; for r in rows { - let k = string(sorted ? r[0] : r); + let k = string(if sorted { r[0] } else { r }); if k in seen { continue; @@ -298,14 +300,14 @@ fun output(q, scope) { } if sorted { - steps.push(Step { label: "sort by {order.map(o => o.text + (o.desc ? " desc" : "")).join(", ")}", run: rows => { + steps.push(Step { label: "sort by {order.map(o => o.text + (if o.desc { " desc" } else { "" })).join(", ")}", run: rows => { let mut out = rows[..]; out.sort((a, b) => { for i, o in order { let c = expr.compare(a[1][i], b[1][i]); if c != 0 { - return o.desc ? -c : c; + return if o.desc { -c } else { c }; } } @@ -317,8 +319,8 @@ fun output(q, scope) { } if q.limit != nil || q.offset > 0 { - let end = q.limit == nil ? nil : q.offset + q.limit; - steps.push(Step { label: "limit {q.limit ?? "all"} offset {q.offset}", run: rows => end == nil ? rows[q.offset..] : rows[q.offset..end] }); + let end = if q.limit == nil { nil } else { q.offset + q.limit }; + steps.push(Step { label: "limit {q.limit ?? "all"} offset {q.offset}", run: rows => if end == nil { rows[q.offset..] } else { rows[q.offset..end] } }); } return Plan { steps, columns }; @@ -333,7 +335,7 @@ fun ordinal(e, items, clause) { let n = e.value; if !math.isInt(n) || n < 1 || n > items.len() { - throw ast.SqlError { message: "{clause} {n}: the query has {items.len()} column{items.len() == 1 ? "" : "s"}" }; + throw ast.SqlError { message: "{clause} {n}: the query has {items.len()} column{if items.len() == 1 { "" } else { "s" }}" }; } return n - 1; @@ -362,4 +364,4 @@ fun expandStars(items, scope) { return out; } -fun columnName(it) => it.alias ?? (it.expr is ast.Col ? it.expr.name : ast.sql(it.expr)); +fun columnName(it) { it.alias ?? (if it.expr is ast.Col { it.expr.name } else { ast.sql(it.expr) }) } diff --git a/examples/query/table.rn b/examples/query/table.rn index 80f17362..2a85d41b 100644 --- a/examples/query/table.rn +++ b/examples/query/table.rn @@ -7,7 +7,7 @@ export struct Table { name, columns, rows } export struct Catalog { dir, tables = map() } impl Catalog { - fun new(dir) => Catalog { dir }; + fun new(dir) { Catalog { dir } } fun load(mut self, name, pos = nil) { let cached = self.tables?.[name]; @@ -126,6 +126,6 @@ fun splitCsv(line) { } export fun quoteCsv(v) { - let s = v == nil ? "" : string(v); - return "," in s || "\"" in s ? "\"" + s.replace("\"", "\"\"") + "\"" : s; + let s = if v == nil { "" } else { string(v) }; + return if "," in s || "\"" in s { "\"" + s.replace("\"", "\"\"") + "\"" } else { s }; } diff --git a/examples/shop.rn b/examples/shop.rn index 8543e414..fb57ce20 100644 --- a/examples/shop.rn +++ b/examples/shop.rn @@ -11,7 +11,7 @@ struct ApiError { message, status, path } struct Client { base = BASE, token = nil, refreshToken = nil, refreshes = 0 } impl Client { - fun new() => Client {}; + fun new() { Client {} } fun login(mut self, username, password) { let r = self.send("POST", "/auth/login", { username, password, expiresInMins: 30 }); @@ -31,8 +31,8 @@ impl Client { self.token = "expired"; } - fun get(mut self, path) => self.authed("GET", path); - fun post(mut self, path, body) => self.authed("POST", path, body); + fun get(mut self, path) { self.authed("GET", path) } + fun post(mut self, path, body) { self.authed("POST", path, body) } // 401 means the access token expired: refresh once and retry. fun authed(mut self, method, path, body = nil) { @@ -61,11 +61,11 @@ impl Client { let r = http.request(method, self.base + path, { headers, - body: body == nil ? nil : json.stringify(body), + body: if body == nil { nil } else { json.stringify(body) }, timeout: 10, }); - let data = r.body == "" ? nil : json.parse(r.body); + let data = if r.body == "" { nil } else { json.parse(r.body) }; if r.status >= 400 { throw ApiError { message: data?.message ?? "HTTP {r.status}", status: r.status, path }; @@ -87,13 +87,13 @@ fun urlEncode(s) { for _, b in bytes(s) { let c = string.fromCharCode(b); - out += regex.test(r"^[A-Za-z0-9\-_.~]$", c) ? c : "%%%02X".format(b); + out += if regex.test(r"^[A-Za-z0-9\-_.~]$", c) { c } else { "%%%02X".format(b) }; } return out; } -fun money(n) => "$%.2f".format(n); +fun money(n) { "$%.2f".format(n) } fun section(title) { print(""); @@ -122,7 +122,7 @@ fun showProducts(query, { products, total }) { byRating.sort((a, b) => b.rating - a.rating); for { id, title, price, rating, stock } in byRating { let stars = "★".repeat(math.round(rating)) + "☆".repeat(5 - math.round(rating)); - let low = stock < 10 ? " low stock: {stock}" : ""; + let low = if stock < 10 { " low stock: {stock}" } else { "" }; print(" #%-4d %-32s %9s %s{low}".format(id, title[..32], money(price), stars)); } } diff --git a/examples/todo.rn b/examples/todo.rn index 360400c9..3fa25f03 100644 --- a/examples/todo.rn +++ b/examples/todo.rn @@ -24,13 +24,13 @@ struct UsageError { message } enum Priority { Low, Normal, High } -fun priorityNamed(word) => Priority.values().find(p => p.name.lower() == word); +fun priorityNamed(word) { Priority.values().find(p => p.name.lower() == word) } const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]; const DAY = "%Y-%m-%d"; // --- dates: local calendar days, as YYYY-MM-DD --- -fun today() => time.format(time.now(), DAY); +fun today() { time.format(time.now(), DAY) } fun addDays(day, n) { let d = time.date(time.parse(day, DAY)); @@ -79,7 +79,7 @@ fun relative(day, now) { // --- storage --- -fun defaultPath() => os.env("TODO_FILE") ?? fs.join(os.env("HOME") ?? ".", ".todo.json"); +fun defaultPath() { os.env("TODO_FILE") ?? fs.join(os.env("HOME") ?? ".", ".todo.json") } struct Store { path, tasks = [], nextId = 1 } @@ -115,7 +115,7 @@ impl Store { return self.tasks[i]; } - fun remove(mut self, id) => self.tasks.remove(self.find(id)); + fun remove(mut self, id) { self.tasks.remove(self.find(id)) } } // --- commands --- @@ -156,7 +156,7 @@ fun ids(args) { fun byUrgency(a, b) { if (a.completed == nil) != (b.completed == nil) { - return a.completed == nil ? -1 : 1; + return if a.completed == nil { -1 } else { 1 }; } if a.due != b.due { @@ -168,7 +168,7 @@ fun byUrgency(a, b) { return -1; } - return a.due < b.due ? -1 : 1; + return if a.due < b.due { -1 } else { 1 }; } if a.priority != b.priority { @@ -179,9 +179,9 @@ fun byUrgency(a, b) { } fun show(t, now) { - let mark = t.completed != nil ? "x" : t.due != nil && t.due < now ? "!" : " "; + let mark = if t.completed != nil { "x" } else if t.due != nil && t.due < now { "!" } else { " " }; let prio = match t.priority { Priority.High => "↑", Priority.Low => "↓", Priority.Normal => " " }; - let due = t.due != nil ? relative(t.due, now) : ""; + let due = if t.due != nil { relative(t.due, now) } else { "" }; let tags = t.tags.map(tag => "+" + tag).join(" "); return "[%s] %3d %s %-28s %-10s %s".format(mark, t.id, prio, t.text, due, tags).trimEnd(); } @@ -273,7 +273,7 @@ fun run(mut store, [cmd = "list", ...args], now) { _ => throw UsageError { message: "unknown command '{cmd}'" }, } - return cmd in ["list", "ls", "stats", "help"] ? nil : store; + return if cmd in ["list", "ls", "stats", "help"] { nil } else { store }; } fun usage() { diff --git a/examples/validate.rn b/examples/validate.rn index 2143b919..7a29294b 100644 --- a/examples/validate.rn +++ b/examples/validate.rn @@ -118,7 +118,7 @@ fun check(s, v, path, mut out) { return bounded(v, min, max, path, out); }, - _ is Flag => want(v is boolean, "boolean", v, path, out) ? v : nil, + _ is Flag => if want(v is boolean, "boolean", v, path, out) { v } else { nil }, Duration { min, max } => { if !want(v is string, "string", v, path, out) { return nil; @@ -149,7 +149,7 @@ fun want(ok, t, v, path, mut out) { return true; } - fail(out, path, "expected {t}, got {v == nil ? "null" : show(v)}"); + fail(out, path, "expected {t}, got {if v == nil { "null" } else { show(v) }}"); return false; } @@ -175,7 +175,7 @@ fun checkStr({ min, max, pattern, like, oneOf }, v, path, mut out) { } if v.len() < min { - return fail(out, path, min == 1 ? "must not be empty" : "shorter than {min} characters"); + return fail(out, path, if min == 1 { "must not be empty" } else { "shorter than {min} characters" }); } if max != nil && v.len() > max { @@ -217,10 +217,10 @@ fun checkAddr(v, path, mut out) { let m = regex.find(r"^(?:[\w.-]*|\[[0-9a-fA-F:]+\]):(\d+)$", v) ?? return fail(out, path, "{show(v)} is not host:port"); let port = int(m.groups[0]); - return validPort(port) ? v : fail(out, path, "port {port} is out of range 1-65535"); + return if validPort(port) { v } else { fail(out, path, "port {port} is out of range 1-65535") }; } -fun validPort(p) => p >= 1 && p <= 65535; +fun validPort(p) { p >= 1 && p <= 65535 } fun checkList({ of, min, max, unique }, v, path, mut out) { if !want(v is array, "array", v, path, out) { @@ -228,7 +228,7 @@ fun checkList({ of, min, max, unique }, v, path, mut out) { } if v.len() < min { - fail(out, path, min == 1 ? "must not be empty" : "needs at least {min} items"); + fail(out, path, if min == 1 { "must not be empty" } else { "needs at least {min} items" }); } if max != nil && v.len() > max { @@ -246,7 +246,7 @@ fun checkList({ of, min, max, unique }, v, path, mut out) { continue; } - let [key, keyAt] = unique == true ? [item, at] : [item is object ? item?.[unique] : nil, [...at, unique]]; + let [key, keyAt] = if unique == true { [item, at] } else { [if item is object { item?.[unique] } else { nil }, [...at, unique]] }; if key !is string | number { continue; @@ -268,7 +268,7 @@ fun checkDict({ of, key, min }, v, path, mut out) { } if v.len() < min { - fail(out, path, min == 1 ? "must not be empty" : "needs at least {min} entries"); + fail(out, path, if min == 1 { "must not be empty" } else { "needs at least {min} entries" }); } let mut entries = {}; @@ -439,7 +439,7 @@ fun v2to3(cfg, mut notes) { notes.push("backends → upstreams, keyed by name"); let next = routes.map(({ path, backend, auth = "none", ...more }) => { - return { pattern: path.endsWith("/") ? path + "*" : path, upstream: backend, ...more, auth: { type: auth } }; + return { pattern: if path.endsWith("/") { path + "*" } else { path }, upstream: backend, ...more, auth: { type: auth } }; }); notes.push("routes: path → pattern, backend → upstream, auth \"name\" → auth.type"); @@ -475,17 +475,17 @@ fun fmtPath(path) { for seg in path { s += match seg { _ is number => "[{seg}]", - _ if regex.test(r"^[A-Za-z_][\w-]*$", seg) => s == "" ? seg : "." + seg, + _ if regex.test(r"^[A-Za-z_][\w-]*$", seg) => if s == "" { seg } else { "." + seg }, _ => "[%q]".format(seg), }; } - return s == "" ? "(root)" : s; + return if s == "" { "(root)" } else { s }; } fun show(v) { let s = "%q".format(v); - return s.len() > 40 ? s[..37] + "..." : s; + return if s.len() > 40 { s[..37] + "..." } else { s }; } fun suggest(word, options) { @@ -500,7 +500,7 @@ fun suggest(word, options) { } } - return best == nil ? "" : ", did you mean {show(best)}?"; + return if best == nil { "" } else { ", did you mean {show(best)}?" }; } fun distance(a, b) { @@ -514,7 +514,7 @@ fun distance(a, b) { let mut row = [i]; for j in 1..b.len() + 1 { - let cost = a[i - 1] == b[j - 1] ? 0 : 1; + let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 }; row.push(math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost)); } @@ -550,8 +550,8 @@ fun inUnits(n, units) { return string(n); } -fun duration(ms) => inUnits(ms, UNITS); -fun size(n) => inUnits(n, SIZES); +fun duration(ms) { inUnits(ms, UNITS) } +fun size(n) { inUnits(n, SIZES) } fun report(issues) { let errors = issues.filter(i => i.level == Level.Error).len(); @@ -572,7 +572,7 @@ fun report(issues) { return errors; } -fun plural(n) => n == 1 ? "" : "s"; +fun plural(n) { if n == 1 { "" } else { "s" } } // --- commands --- @@ -607,7 +607,7 @@ fun run([cmd = "help", path = nil, ...flags]) { io.eprint(" migrated: {n}"); } - return report(validate(cfg).issues) > 0 ? 1 : 0; + return if report(validate(cfg).issues) > 0 { 1 } else { 0 }; }, "migrate" => { for n in notes { @@ -739,7 +739,7 @@ fun demo() { let [cmd, file] = line.split(" "); print("$ validate {line}"); let code = run([cmd, fs.join(dir, file)]); - print(code == 0 ? "" : "(exit {code})\n"); + print(if code == 0 { "" } else { "(exit {code})\n" }); } } diff --git a/extras/nvim/syntax/rune.vim b/extras/nvim/syntax/rune.vim index c0ef0b52..dd1e1774 100644 --- a/extras/nvim/syntax/rune.vim +++ b/extras/nvim/syntax/rune.vim @@ -38,7 +38,7 @@ syn region runeRawString matchgroup=runeBytesPrefix start=+\\|\.\.\.\|\.\.=\|\.\.\|?\.\|??\|?\|[-+*/%=!<>&|^~]=\=" +syn match runeOperator "=>\|\.\.\.\|\.\.=\|\.\.\|?\.\|??\|[-+*/%=!<>&|^~]=\=" syn keyword runeTodo contained TODO FIXME XXX NOTE syn match runeComment "//.*$" contains=runeTodo,@Spell diff --git a/pkg/ast/expression.go b/pkg/ast/expression.go index f71c3f83..b730c347 100644 --- a/pkg/ast/expression.go +++ b/pkg/ast/expression.go @@ -29,7 +29,7 @@ type ExprVisitor interface { VisitOptionalExpr(optionalExpr *OptionalExpr) (value.Value, error) VisitSpreadExpr(spreadExpr *SpreadExpr) (value.Value, error) VisitComputedExpr(computedExpr *ComputedExpr) (value.Value, error) - VisitConditionalExpr(conditionalExpr *ConditionalExpr) (value.Value, error) + VisitIfExpr(ifExpr *IfExpr) (value.Value, error) VisitThrowExpr(throwExpr *ThrowExpr) (value.Value, error) VisitTryExpr(tryExpr *TryExpr) (value.Value, error) VisitJumpExpr(jumpExpr *JumpExpr) (value.Value, error) @@ -492,19 +492,14 @@ func (n *SliceExpr) String() string { return fmt.Sprintf("(slice %v %v)", n.Target, n.Range) } -// ConditionalExpr is cond ? then : else. -type ConditionalExpr struct { - Cond Expr - Then Expr - Else Expr +// IfExpr is an if whose value is used: that of the branch taken, nil +// when none is. +type IfExpr struct { + If *IfStmt } -func (n *ConditionalExpr) Accept(v ExprVisitor) (value.Value, error) { - return v.VisitConditionalExpr(n) -} - -func (n *ConditionalExpr) String() string { - return fmt.Sprintf("(? %v %v %v)", n.Cond, n.Then, n.Else) +func (n *IfExpr) Accept(v ExprVisitor) (value.Value, error) { + return v.VisitIfExpr(n) } // ThrowExpr is throw in an expression; it has no value. diff --git a/pkg/ast/pattern.go b/pkg/ast/pattern.go index 6cf9a291..bd9f201a 100644 --- a/pkg/ast/pattern.go +++ b/pkg/ast/pattern.go @@ -146,13 +146,13 @@ func Irrefutable(p Pattern) bool { return false } -// MatchArm is pattern [if guard] => body. An expression body is an -// *ExprStmt, whose value is the arm's; any other body gives nil. +// MatchArm is pattern [if guard] => body; an expression body is a valued +// block of it alone. type MatchArm struct { Token Token Pattern Pattern Guard Expr - Body Stmt + Body *BlockStmt } // MatchExpr is match subject { arms }; no arm matching is an error. @@ -162,6 +162,16 @@ type MatchExpr struct { Arms []MatchArm } +// Values returns the value of each arm, nil for one without. +func (n *MatchExpr) Values() []Expr { + vs := make([]Expr, len(n.Arms)) + for i := range n.Arms { + vs[i] = n.Arms[i].Body.Value() + } + + return vs +} + func (n *MatchExpr) Accept(v ExprVisitor) (value.Value, error) { return v.VisitMatchExpr(n) } diff --git a/pkg/ast/statement.go b/pkg/ast/statement.go index 10deaabf..ad07911c 100644 --- a/pkg/ast/statement.go +++ b/pkg/ast/statement.go @@ -154,22 +154,47 @@ func NewExprStmt(expr Expr) Stmt { return &ExprStmt{Expr: expr} } +// BlockStmt is { stmts }; if Valued, its last statement is an *ExprStmt +// written without ';', whose value is the block's. type BlockStmt struct { - Stmts []Stmt + Stmts []Stmt + Valued bool +} + +// Value is the expression whose value the block gives, or nil. +func (b *BlockStmt) Value() Expr { + if !b.Valued { + return nil + } + + return b.Stmts[len(b.Stmts)-1].(*ExprStmt).Expr } func NewBlockStmt(stmts []Stmt) Stmt { return &BlockStmt{Stmts: stmts} } +// IfStmt is if cond { then } [else ...]; El is nil, a *BlockStmt or an +// *IfStmt. type IfStmt struct { Condition Expr - Then Stmt + Then *BlockStmt El Stmt } -func NewIfStmt(condition Expr, then Stmt, el Stmt) Stmt { - return &IfStmt{Condition: condition, Then: then, El: el} +// Values returns the value of each branch, nil for one without, a missing +// else included. +func (n *IfStmt) Values() []Expr { + vs := []Expr{n.Then.Value()} + + switch el := n.El.(type) { + case *BlockStmt: + return append(vs, el.Value()) + case *IfStmt: + return append(vs, el.Values()...) + } + + return append(vs, nil) } type WhileStmt struct { diff --git a/pkg/ast/token.go b/pkg/ast/token.go index 0b5256f7..e04d85d6 100644 --- a/pkg/ast/token.go +++ b/pkg/ast/token.go @@ -83,7 +83,6 @@ const ( DOT_DOT DOT_DOT_EQUAL DOT_DOT_DOT - QUESTION QUESTION_DOT QUESTION_QUESTION ARROW @@ -183,8 +182,6 @@ func (tokenType TokenType) String() string { return "DOT_DOT_EQUAL" case DOT_DOT_DOT: return "DOT_DOT_DOT" - case QUESTION: - return "QUESTION" case QUESTION_DOT: return "QUESTION_DOT" case QUESTION_QUESTION: diff --git a/pkg/format/format.go b/pkg/format/format.go index 1bbb79c0..6b773170 100644 --- a/pkg/format/format.go +++ b/pkg/format/format.go @@ -52,8 +52,6 @@ type comment struct { type frame struct { open ast.TokenType indent int - // pending counts the ? of conditionals waiting for their :. - pending int } type printer struct { @@ -134,7 +132,10 @@ func split(s string, tokens []ast.Token) ([]atom, []comment) { func layout(atoms []atom) { type frame struct { brace, multi bool - start int + // broke is set once a statement of the block ends with a ;, which + // puts its value, if any, and the } on lines of their own. + broke bool + start int } stack := []frame{{brace: true}} for i := range atoms { @@ -152,6 +153,9 @@ func layout(atoms []atom) { case closer(t) && len(stack) > 1: inner := stack[len(stack)-1] stack = stack[:len(stack)-1] + if inner.broke { + lineBreak(&atoms[i], 1) + } stack[len(stack)-1].multi = stack[len(stack)-1].multi || inner.multi || t == ast.RIGHT_BRACE && atoms[i].before.breaks > 0 end = t == ast.RIGHT_BRACE && next != nil && next.before.breaks > 0 && !continuesBlock(next) @@ -166,6 +170,7 @@ func layout(atoms []atom) { if t == ast.SEMICOLON && next != nil { lineBreak(next, 1) lineBreak(&atoms[top.start], 1) + top.broke = true } if top.multi { lineBreak(&atoms[top.start], 2) @@ -329,13 +334,9 @@ func (p *printer) continues() bool { return true } -// track keeps the brackets and conditionals open after a. +// track keeps the brackets open after a. func (p *printer) track(a, next *atom) { switch t := a.tok.TokenType; { - case t == ast.QUESTION: - p.top().pending++ - case t == ast.COLON && p.top().pending > 0: - p.top().pending-- case opener(t): base := p.line if p.bodyBrace(t, next) { @@ -390,7 +391,7 @@ func (p *printer) spaceBefore(a *atom) bool { } return !prev.ended() case t == ast.COLON: - return p.top().pending > 0 + return false } return true } diff --git a/pkg/rune/bench_test.go b/pkg/rune/bench_test.go index 9d5c1211..aa1cc9e9 100644 --- a/pkg/rune/bench_test.go +++ b/pkg/rune/bench_test.go @@ -116,7 +116,7 @@ func TestMovesDoNotCopy(t *testing.T) { "rebind": `let mut a = [0].repeat(1000); for k in 0..%d { let mut b = a; b[0] = k; a = b; let c = [0].repeat(1000); }`, "pass": `fun first(xs) { return xs[0]; } for k in 0..%d { let mut a = [0].repeat(1000); first(a); a[0] = 1; }`, "passlast": `fun put(mut xs) { xs[0] = 1; } for k in 0..%d { let mut a = [0].repeat(1000); let mut b = a; put(b); }`, - "cond": `fun pick(c) { let mut a = [0].repeat(1000); let mut b = [1]; return c ? a : b; } for k in 0..%d { let mut xs = pick(k %% 2 == 0); xs[0] = 1; }`, + "cond": `fun pick(c) { let mut a = [0].repeat(1000); let mut b = [1]; if c { a } else { b } } for k in 0..%d { let mut xs = pick(k %% 2 == 0); xs[0] = 1; }`, } { t.Run(name, func(t *testing.T) { if one, many := allocated(t, src, 1), allocated(t, src, 101); many-one > 100*20<<10 { diff --git a/pkg/rune/compile_access.go b/pkg/rune/compile_access.go index c43acc10..d8a1bfba 100644 --- a/pkg/rune/compile_access.go +++ b/pkg/rune/compile_access.go @@ -232,8 +232,6 @@ func reads(e ast.Expr) bool { return reads(n.Left) && reads(n.Right) case *ast.LogicalExpr: return reads(n.Left) && reads(n.Right) - case *ast.ConditionalExpr: - return reads(n.Cond) && reads(n.Then) && reads(n.Else) case *ast.IndexExpr: return reads(n.Array) && reads(n.Index) case *ast.InterpolationExpr: diff --git a/pkg/rune/compile_expr.go b/pkg/rune/compile_expr.go index ab2381b7..064cbe60 100644 --- a/pkg/rune/compile_expr.go +++ b/pkg/rune/compile_expr.go @@ -81,8 +81,6 @@ func assigns(e ast.Expr) bool { return assigns(n.Left) || assigns(n.Right) case *ast.LogicalExpr: return assigns(n.Left) || assigns(n.Right) - case *ast.ConditionalExpr: - return assigns(n.Cond) || assigns(n.Then) || assigns(n.Else) case *ast.ThrowExpr: return assigns(n.Value) case *ast.TryExpr: @@ -265,13 +263,23 @@ func fresh(e ast.Expr) bool { return true case *ast.LogicalExpr: return fresh(n.Left) && fresh(n.Right) - case *ast.ConditionalExpr: - return fresh(n.Then) && fresh(n.Else) + case *ast.IfExpr, *ast.MatchExpr: + return !slices.ContainsFunc(values(n), func(v ast.Expr) bool { return !fresh(v) }) } return false } +// values returns what each branch of an if or match expression gives, +// nil for one that gives nil. +func values(e ast.Expr) []ast.Expr { + if n, ok := e.(*ast.IfExpr); ok { + return n.If.Values() + } + + return e.(*ast.MatchExpr).Values() +} + // paramMove is the Param of the parameter e reads last, or 0: it gives // its value up only if the caller did. func paramMove(e ast.Expr) int { @@ -386,13 +394,8 @@ func (fs *funcState) expr(e ast.Expr, dst int32) { fs.emit(ins{op: opClosure, a: dst, c: fs.function(n.Decl)}, nil) case *ast.MatchExpr: fs.match(n, dst) - case *ast.ConditionalExpr: - toElse := fs.jumpIf(n.Cond, false) - fs.expr(n.Then, dst) - end := fs.emit(ins{op: opJmp}, nil) - fs.patch(toElse) - fs.expr(n.Else, dst) - fs.patch([]int{end}) + case *ast.IfExpr: + fs.ifStmt(n.If, dst) case *ast.ThrowExpr: fs.expr(n.Value, dst) fs.emit(ins{op: opThrow, a: dst}, &n.Keyword) @@ -553,8 +556,8 @@ func writesEarly(e ast.Expr) bool { return true case *ast.UpdateExpr: return !n.Prefix - case *ast.ConditionalExpr: - return writesEarly(n.Then) || writesEarly(n.Else) + case *ast.IfExpr, *ast.MatchExpr: + return slices.ContainsFunc(values(n), writesEarly) } return false diff --git a/pkg/rune/compile_match.go b/pkg/rune/compile_match.go index a5c9d4a0..eb934ef8 100644 --- a/pkg/rune/compile_match.go +++ b/pkg/rune/compile_match.go @@ -68,16 +68,7 @@ func (fs *funcState) arm(arm *ast.MatchArm, subj, dst int32) []int { miss = append(miss, fs.jumpIf(arm.Guard, false)...) } - if e, ok := arm.Body.(*ast.ExprStmt); ok && dst != noReg { - fs.expr(e.Expr, dst) - return miss - } - - fs.stmt(arm.Body) - - if dst != noReg { - fs.emit(ins{op: opLoadK, a: dst, c: fs.constant(value.NilValue)}, nil) - } + fs.block(arm.Body, dst) return miss } diff --git a/pkg/rune/compile_stmt.go b/pkg/rune/compile_stmt.go index 126f1a25..26d5dfc7 100644 --- a/pkg/rune/compile_stmt.go +++ b/pkg/rune/compile_stmt.go @@ -7,24 +7,32 @@ import ( "slices" ) -func (fs *funcState) stmts(stmts []ast.Stmt) { +func (fs *funcState) stmts(stmts []ast.Stmt) { fs.stmtsThen(stmts, nil) } + +// stmtsThen compiles stmts and then last, if any, before the defers among +// stmts run. +func (fs *funcState) stmtsThen(stmts []ast.Stmt, last func()) { for i, s := range stmts { if d, ok := s.(*ast.DeferStmt); ok { - fs.deferStmt(d, stmts[i+1:]) + fs.deferStmt(d, func() { fs.stmtsThen(stmts[i+1:], last) }) return } fs.stmt(s) fs.free = fs.nactive } + + if last != nil { + last() + } } -// deferStmt compiles rest, the statements after d, then d's body: on -// the way out of rest, and if rest fails, before the error goes on up. -func (fs *funcState) deferStmt(d *ast.DeferStmt, rest []ast.Stmt) { +// deferStmt compiles rest, what follows d, then d's body: on the way out +// of rest, and if rest fails, before the error goes on up. +func (fs *funcState) deferStmt(d *ast.DeferStmt, rest func()) { at := fs.nactive run := func() { fs.runDefer(d.Body) } - try := fs.handled(ins{op: opTry, a: at, x: 1}, &unwind{leave: run, try: true}, func() { fs.stmts(rest) }) + try := fs.handled(ins{op: opTry, a: at, x: 1}, &unwind{leave: run, try: true}, rest) run() fs.rethrowAfter(try, at, run) } @@ -128,9 +136,9 @@ func (fs *funcState) stmt(stmt ast.Stmt) { case *ast.ArrayDestructureStmt: fs.unpack(s) case *ast.BlockStmt: - fs.scoped(func() { fs.stmts(s.Stmts) }) + fs.block(s, noReg) case *ast.IfStmt: - fs.ifStmt(s) + fs.ifStmt(s, noReg) case *ast.WhileStmt: fs.whileStmt(s) case *ast.ForInStmt: @@ -142,7 +150,7 @@ func (fs *funcState) stmt(stmt ast.Stmt) { case *ast.TryStmt: fs.tryStmt(s) case *ast.DeferStmt: - fs.deferStmt(s, nil) + fs.deferStmt(s, func() {}) case *ast.MatchStmt: fs.match(s.Match, noReg) case *ast.StructStmt, *ast.ImplStmt: @@ -394,21 +402,61 @@ func (fs *funcState) functionStmt(s *ast.FunctionStmt) { fs.emit(ins{op: opSetCell, a: r, b: t}, nil) } -func (fs *funcState) ifStmt(s *ast.IfStmt) { +// 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.scoped(func() { fs.stmt(s.Then) }) + fs.block(s.Then, dst) - if s.El == nil { + if s.El == nil && dst == noReg { fs.patch(skip) return } end := fs.emit(ins{op: opJmp}, nil) fs.patch(skip) - fs.scoped(func() { fs.stmt(s.El) }) + + switch el := s.El.(type) { + case nil: + fs.emit(ins{op: opLoadK, a: dst, c: fs.constant(value.NilValue)}, nil) + case *ast.IfStmt: + fs.ifStmt(el, dst) + case *ast.BlockStmt: + fs.block(el, dst) + } + fs.patch([]int{end}) } +// block compiles b, with its value into dst unless it is noReg. Its +// locals go above the temporaries live in the expression it may be in. +func (fs *funcState) block(b *ast.BlockStmt, dst int32) { + free := fs.free + defer func() { fs.free = free }() + + fs.scoped(func() { + fs.nactive = free + + if dst == noReg { + fs.stmts(b.Stmts) + return + } + + stmts := b.Stmts + if b.Valued { + stmts = stmts[:len(stmts)-1] + } + + fs.stmtsThen(stmts, func() { + if v := b.Value(); v != nil { + fs.expr(v, dst) + } else { + fs.emit(ins{op: opLoadK, a: dst, c: fs.constant(value.NilValue)}, nil) + } + }) + }) +} + // whileStmt tests at the bottom, so an iteration runs one jump. func (fs *funcState) whileStmt(s *ast.WhileStmt) { enter := fs.emit(ins{op: opJmp}, nil) diff --git a/pkg/rune/moves.go b/pkg/rune/moves.go index 4cf033f1..4642b45a 100644 --- a/pkg/rune/moves.go +++ b/pkg/rune/moves.go @@ -271,12 +271,8 @@ func (lv *liveness) expr(e ast.Expr, live liveSet) { lv.expr(n.Right, right) live.add(right) lv.expr(n.Left, live) - case *ast.ConditionalExpr: - then := maps.Clone(live) - lv.expr(n.Then, then) - lv.expr(n.Else, live) - live.add(then) - lv.expr(n.Cond, live) + case *ast.IfExpr: + lv.stmt(n.If, live) case *ast.AssignExpr: lv.named[n.Local]++ delete(live, n.Local) diff --git a/pkg/rune/parse_expr.go b/pkg/rune/parse_expr.go index 2dc7455c..f46b45cf 100644 --- a/pkg/rune/parse_expr.go +++ b/pkg/rune/parse_expr.go @@ -16,7 +16,7 @@ func (s *Parser) assignment() (ast.Expr, error) { return fn, err } - expr, err := s.conditional() + expr, err := s.nullish() if err != nil { return nil, err @@ -77,30 +77,6 @@ var compoundOps = map[ast.TokenType]ast.TokenType{ ast.GREATER_GREATER_GREATER_EQUAL: ast.GREATER_GREATER_GREATER, } -// conditional parses cond ? then : else, right-associative. -func (s *Parser) conditional() (ast.Expr, error) { - cond, err := s.nullish() - if err != nil || !s.match(ast.QUESTION) { - return cond, err - } - - then, err := s.expressionWithStructs(structsAll) - if err != nil { - return nil, err - } - - if _, err := s.consume(ast.COLON, "Expect ':' after then branch of '?'."); err != nil { - return nil, err - } - - els, err := s.assignment() - if err != nil { - return nil, err - } - - return &ast.ConditionalExpr{Cond: cond, Then: then, Else: els}, nil -} - // rangeExpr parses a..b and a..=b, which bind looser than the bitwise and // arithmetic operators and tighter than comparisons. func (s *Parser) rangeExpr() (ast.Expr, error) { @@ -489,6 +465,15 @@ func (s *Parser) primary() (ast.Expr, error) { return s.matchExpr() } + if s.match(ast.IF) { + st, err := s.ifStatement() + if err != nil { + return nil, err + } + + return &ast.IfExpr{If: st}, nil + } + if s.match(ast.TRUE) { return ast.NewLiteralExpr(ast.TRUE, true), nil } @@ -798,7 +783,7 @@ func (s *Parser) arrowFunction() (fn ast.Expr, ok bool, err error) { return nil, false, nil } - body, _, err := s.arrowBody(s.advance()) + body, err := s.arrowBody(s.advance()) if err != nil { return nil, true, err } @@ -822,14 +807,14 @@ func (s *Parser) arrowParams() (params, bool) { } // arrowBody parses a block, or an expression whose value is returned. -func (s *Parser) arrowBody(arrow ast.Token) (body []ast.Stmt, expr bool, err error) { - if body, ok, err := s.braceBody(); ok { - return body, false, err +func (s *Parser) arrowBody(arrow ast.Token) ([]ast.Stmt, error) { + if s.check(ast.LEFT_BRACE) { + return s.functionBody() } e, err := s.assignment() - return []ast.Stmt{ast.NewReturnStmt(e, arrow)}, true, err + return []ast.Stmt{ast.NewReturnStmt(e, arrow)}, err } func anonName(at ast.Token) ast.Token { @@ -841,7 +826,7 @@ func anonName(at ast.Token) ast.Token { // isObjectLiteralStart reports whether the upcoming tokens can only // start an object literal: "{" and a property name and ":", a shorthand -// property, "..." or a computed key. +// property and ",", "..." or a computed key. func (s *Parser) isObjectLiteralStart() bool { if !s.check(ast.LEFT_BRACE) { return false @@ -851,7 +836,7 @@ func (s *Parser) isObjectLiteralStart() bool { return key == ast.DOT_DOT_DOT || key == ast.LEFT_BRACKET && s.computedKeyStart() || (key == ast.IDENTIFIER || key == ast.STRING) && after == ast.COLON || - key == ast.IDENTIFIER && endsItem(after) + key == ast.IDENTIFIER && after == ast.COMMA } // computedKeyStart reports whether the "[" after the "{" closes before a diff --git a/pkg/rune/parse_match.go b/pkg/rune/parse_match.go index fc341d5d..070565d2 100644 --- a/pkg/rune/parse_match.go +++ b/pkg/rune/parse_match.go @@ -78,14 +78,14 @@ func (s *Parser) matchArm() (ast.MatchArm, error) { } // armBody parses a block or an expression. -func (s *Parser) armBody() (ast.Stmt, error) { - if stmts, ok, err := s.braceBody(); ok { - return ast.NewBlockStmt(stmts), err +func (s *Parser) armBody() (*ast.BlockStmt, error) { + if s.check(ast.LEFT_BRACE) { + return s.braced(true) } e, err := s.expression() - return ast.NewExprStmt(e), err + return &ast.BlockStmt{Stmts: []ast.Stmt{ast.NewExprStmt(e)}, Valued: true}, err } // matchPattern parses a pattern: alternatives separated by "|". diff --git a/pkg/rune/parse_stmt.go b/pkg/rune/parse_stmt.go index 7be31517..d1e77342 100644 --- a/pkg/rune/parse_stmt.go +++ b/pkg/rune/parse_stmt.go @@ -2,6 +2,7 @@ package rune import ( "fmt" + "slices" "rune/pkg/ast" "rune/pkg/errors" @@ -197,47 +198,53 @@ func (s *Parser) function(kind string) (ast.Stmt, error) { return nil, err } - fn, expr, err := s.functionRest(name) + fn, err := s.functionRest(name) if err != nil { return nil, err } - if expr { - if _, err := s.consume(ast.SEMICOLON, "Expect ';' after function body."); err != nil { - return nil, err - } - } - return fn, nil } const maxArity = 8 -// functionRest parses a function's parameter list and body, a block or -// "=> body" as an arrow function's; expr reports an expression body. The +// functionRest parses a function's parameter list and block body; the // opening "(" has already been consumed. -func (s *Parser) functionRest(name ast.Token) (fn *ast.FunctionStmt, expr bool, err error) { +func (s *Parser) functionRest(name ast.Token) (*ast.FunctionStmt, error) { params, err := s.parameters() if err != nil { - return nil, false, err + return nil, err } - var body []ast.Stmt - - if s.check(ast.ARROW) { - body, expr, err = s.arrowBody(s.advance()) - } else if _, err = s.consume(ast.LEFT_BRACE, "Expect '{' or '=>' before function body."); err == nil { - body, err = s.block() + if !s.check(ast.LEFT_BRACE) { + return nil, errors.NewSyntaxError(s.peek(), "Expect '{' before function body.") } + body, err := s.functionBody() if err != nil { - return nil, false, err + return nil, err } - fn = params.function(name, body) + fn := params.function(name, body) s.inout |= argInout(fn) - return fn, expr, nil + return fn, nil +} + +// functionBody parses a block whose value the function returns. +func (s *Parser) functionBody() ([]ast.Stmt, error) { + brace := s.peek() + + b, err := s.braced(true) + if err != nil { + return nil, err + } + + if v := b.Value(); v != nil { + b.Stmts[len(b.Stmts)-1] = ast.NewReturnStmt(v, brace) + } + + return b.Stmts, nil } // params is a parameter list; patterns destructure pattern parameters @@ -455,12 +462,13 @@ func (s *Parser) statement() (ast.Stmt, error) { return &ast.MatchStmt{Match: m}, nil } - if block, ok, err := s.braceBody(); ok { + if s.check(ast.LEFT_BRACE) { + b, err := s.braced(false) if err != nil { return nil, err } - return ast.NewBlockStmt(block), nil + return b, nil } if s.match(ast.FOR) { @@ -468,7 +476,12 @@ func (s *Parser) statement() (ast.Stmt, error) { } if s.match(ast.IF) { - return s.ifStatement() + st, err := s.ifStatement() + if err != nil { + return nil, err + } + + return st, nil } return s.expressionStatement() @@ -497,6 +510,11 @@ func (s *Parser) expressionStatement() (ast.Stmt, error) { return nil, err } + // A block ends here: it decides what a missing ';' means. + if s.blockDepth > 0 && s.check(ast.RIGHT_BRACE) { + return ast.NewExprStmt(expr), nil + } + _, err = s.consume(ast.SEMICOLON, "Expect ';' after expression.") if err != nil { return nil, foreignKeyword(expr, err) @@ -505,72 +523,120 @@ func (s *Parser) expressionStatement() (ast.Stmt, error) { return ast.NewExprStmt(expr), nil } -// braceBody parses a block if "{" is next; ok reports whether it was. -func (s *Parser) braceBody() (stmts []ast.Stmt, ok bool, err error) { - if !s.check(ast.LEFT_BRACE) { - return nil, false, nil - } - +// braced parses a block if "{" is next; if valued, it may end in a value. +func (s *Parser) braced(valued bool) (*ast.BlockStmt, error) { if s.isObjectLiteralStart() { - return nil, true, errors.NewSyntaxError(s.peek(), "A '{' here starts a block; wrap an object in parentheses: ({ ... }).") + return nil, errors.NewSyntaxError(s.peek(), "A '{' here starts a block; wrap an object in parentheses: ({ ... }).") } s.advance() defer s.allowStructs(structsAll)() - stmts, err = s.block() - - return stmts, true, err + return s.blockOf(valued) } func (s *Parser) block() ([]ast.Stmt, error) { - var stmts []ast.Stmt + b, err := s.blockOf(false) + if err != nil { + return nil, err + } + + return b.Stmts, nil +} + +// blockOf parses statements up to "}". The last one, when no ';' ends +// it, is the value of a valued block: an expression, or an if or match +// with values. +func (s *Parser) blockOf(valued bool) (*ast.BlockStmt, error) { + b := &ast.BlockStmt{} outer := s.blockDepth s.blockDepth = s.depth[s.current] defer func() { s.blockDepth = outer }() + open := false + for !s.check(ast.RIGHT_BRACE) && !s.isAtEnd() { - if stmt := s.safeDeclaration(); stmt != nil { - stmts = append(stmts, stmt) + stmt := s.safeDeclaration() + open = stmt != nil && s.previous().TokenType != ast.SEMICOLON + + if stmt != nil { + b.Stmts = append(b.Stmts, stmt) } } - _, err := s.consume(ast.RIGHT_BRACE, "Expect '}' after block.") - if err != nil { + if open { + last := &b.Stmts[len(b.Stmts)-1] + + switch st := (*last).(type) { + case *ast.ExprStmt: + if !valued { + s.errors = append(s.errors, foreignKeyword(st.Expr, errors.NewMissingError(s.previous(), s.peek(), "Expect ';' after expression."))) + } + + b.Valued = valued + case *ast.IfStmt: + b.Valued = valued && hasValue(st.Values()) + if b.Valued { + *last = ast.NewExprStmt(&ast.IfExpr{If: st}) + } + case *ast.MatchStmt: + b.Valued = valued && hasValue(st.Match.Values()) + if b.Valued { + *last = ast.NewExprStmt(st.Match) + } + } + } + + if _, err := s.consume(ast.RIGHT_BRACE, "Expect '}' after block."); err != nil { return nil, err } - return stmts, nil + return b, nil } -func (s *Parser) ifStatement() (ast.Stmt, error) { +func hasValue(values []ast.Expr) bool { + return slices.ContainsFunc(values, func(e ast.Expr) bool { return e != nil }) +} + +func (s *Parser) ifStatement() (*ast.IfStmt, error) { condition, err := s.expressionWithStructs(structsNone) if err != nil { return nil, err } - then, err := s.body("if condition") + then, err := s.branch("if condition") if err != nil { return nil, err } - var el ast.Stmt + st := &ast.IfStmt{Condition: condition, Then: then} - if s.match(ast.ELSE) { - if s.match(ast.IF) { - el, err = s.ifStatement() - } else { - el, err = s.body("'else'") - } + if !s.match(ast.ELSE) { + return st, nil + } - if err != nil { - return nil, err - } + if s.match(ast.IF) { + el, err := s.ifStatement() + st.El = el + + return st, err + } + + el, err := s.branch("'else'") + st.El = el + + return st, err +} + +// branch parses the block of an if or else. +func (s *Parser) branch(after string) (*ast.BlockStmt, error) { + if !s.check(ast.LEFT_BRACE) { + return nil, errors.NewSyntaxError(s.peek(), fmt.Sprintf("Expect '{' after %s.", after)) } - return ast.NewIfStmt(condition, then, el), nil + return s.braced(true) } // stmtKeyword reports whether t starts a statement that is no diff --git a/pkg/rune/report_test.go b/pkg/rune/report_test.go index 4817c25e..d4c22a3b 100644 --- a/pkg/rune/report_test.go +++ b/pkg/rune/report_test.go @@ -139,7 +139,7 @@ func TestHints(t *testing.T) { {"typo of a field", "struct User { name }\nprint(User { name: 1 }.nmae);\n", "did you mean 'name'?"}, {"typo of a field in a literal", "struct User { name }\nUser { nmae: 1 };\n", "did you mean 'name'?"}, {"typo of a property", "let o = {width: 1};\nprint(o.widht);\n", "did you mean 'width'?"}, - {"typo of a method", "struct U {}\nimpl U { fun greet(self) => 1; }\nU {}.gret();\n", "did you mean 'greet'?"}, + {"typo of a method", "struct U {}\nimpl U { fun greet(self) { 1 } }\nU {}.gret();\n", "did you mean 'greet'?"}, {"method of another language", "print([1].length);\n", "use 'len' instead"}, {"membership method", "print([1].includes(1));\n", "test membership with the in operator: 'x in xs'"}, {"assign to immutable", "let a = 1;\na = 2;\n", "declare it as 'mut a' on line 1"}, diff --git a/pkg/rune/resolver.go b/pkg/rune/resolver.go index 33962ee3..0f3d29bc 100644 --- a/pkg/rune/resolver.go +++ b/pkg/rune/resolver.go @@ -526,12 +526,8 @@ func (p *Resolver) VisitLogicalExpr(expr *ast.LogicalExpr) (value.Value, error) return value.NilValue, nil } -func (p *Resolver) VisitConditionalExpr(expr *ast.ConditionalExpr) (value.Value, error) { - p.resolveExpr(expr.Cond) - p.resolveExpr(expr.Then) - p.resolveExpr(expr.Else) - - return value.NilValue, nil +func (p *Resolver) VisitIfExpr(expr *ast.IfExpr) (value.Value, error) { + return value.NilValue, p.VisitIfStmt(expr.If) } func (p *Resolver) VisitThrowExpr(expr *ast.ThrowExpr) (value.Value, error) { diff --git a/pkg/rune/scanner.go b/pkg/rune/scanner.go index 35055a76..851fa54f 100644 --- a/pkg/rune/scanner.go +++ b/pkg/rune/scanner.go @@ -138,7 +138,7 @@ func (s *Scanner) scanToken() { case s.match('?'): s.addToken(ast.QUESTION_QUESTION) default: - s.addToken(ast.QUESTION) + s.errorAt("Unexpected character: ?") } case '-': switch { diff --git a/test/arrow/object_body.rn b/test/arrow/object_body.rn index 4f41a384..1f35b9b0 100644 --- a/test/arrow/object_body.rn +++ b/test/arrow/object_body.rn @@ -1,5 +1,4 @@ -let b = x => { x }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). let c = () => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). let d = () => { ...{} }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). -fun e() => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +fun e() { a: 1 } // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). match 1 { 1 => { a: 1 }, _ => 2 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). diff --git a/test/arrow/object_body.stderr b/test/arrow/object_body.stderr index 6be2e983..026b4215 100644 --- a/test/arrow/object_body.stderr +++ b/test/arrow/object_body.stderr @@ -1,33 +1,26 @@ error: A '{' here starts a block; wrap an object in parentheses: ({ ... }). - --> object_body.rn:1:14 + --> object_body.rn:1:15 | -1 | let b = x => { x }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). - | ^ - -error: A '{' here starts a block; wrap an object in parentheses: ({ ... }). - --> object_body.rn:2:15 - | -1 | let b = x => { x }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). -2 | let c = () => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +1 | let c = () => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). | ^ error: A '{' here starts a block; wrap an object in parentheses: ({ ... }). - --> object_body.rn:3:15 + --> object_body.rn:2:15 | -2 | let c = () => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). -3 | let d = () => { ...{} }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +1 | let c = () => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +2 | let d = () => { ...{} }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). | ^ error: A '{' here starts a block; wrap an object in parentheses: ({ ... }). - --> object_body.rn:4:12 + --> object_body.rn:3:9 | -3 | let d = () => { ...{} }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). -4 | fun e() => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). - | ^ +2 | let d = () => { ...{} }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +3 | fun e() { a: 1 } // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). + | ^ error: A '{' here starts a block; wrap an object in parentheses: ({ ... }). - --> object_body.rn:5:16 + --> object_body.rn:4:16 | -4 | fun e() => { a: 1 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). -5 | match 1 { 1 => { a: 1 }, _ => 2 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +3 | fun e() { a: 1 } // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). +4 | match 1 { 1 => { a: 1 }, _ => 2 }; // Error at '{': A '{' here starts a block; wrap an object in parentheses: ({ ... }). | ^ diff --git a/test/block/loop_tail.rn b/test/block/loop_tail.rn new file mode 100644 index 00000000..042e5444 --- /dev/null +++ b/test/block/loop_tail.rn @@ -0,0 +1,4 @@ +// [line: 4] Error at '}': Expect ';' after expression. +for i in 0..2 { + i +} diff --git a/test/block/loop_tail.stderr b/test/block/loop_tail.stderr new file mode 100644 index 00000000..619fb687 --- /dev/null +++ b/test/block/loop_tail.stderr @@ -0,0 +1,6 @@ +error: Expect ';' after expression. + --> loop_tail.rn:3:6 + | +2 | for i in 0..2 { +3 | i + | ^ diff --git a/test/conditional/assign.rn b/test/conditional/assign.rn deleted file mode 100644 index bfc1aa8e..00000000 --- a/test/conditional/assign.rn +++ /dev/null @@ -1,2 +0,0 @@ -let mut a = 1; -(true ? a : a) = 2; // [line: 2] Error at '=': Invalid assignment target. diff --git a/test/conditional/assign.stderr b/test/conditional/assign.stderr deleted file mode 100644 index 90817a79..00000000 --- a/test/conditional/assign.stderr +++ /dev/null @@ -1,6 +0,0 @@ -error: Invalid assignment target. - --> assign.rn:2:16 - | -1 | let mut a = 1; -2 | (true ? a : a) = 2; // [line: 2] Error at '=': Invalid assignment target. - | ^ diff --git a/test/conditional/basic.rn b/test/conditional/basic.rn deleted file mode 100644 index b80ade90..00000000 --- a/test/conditional/basic.rn +++ /dev/null @@ -1,37 +0,0 @@ -let x = 5; -print(x > 3 ? "big" : "small"); // expect: big -print(x > 9 ? "a" : x > 4 ? "b" : "c"); // expect: b -print((x > 9 ? 1 : 2) + 1); // expect: 3 -print(nil ? 1 : 0); // expect: 0 -print(0 ? 1 : 0); // expect: 0 -print([] ? 1 : 0); // expect: 0 -print([0] ? 1 : 0); // expect: 1 - -let parity = n => n % 2 == 0 ? "even" : "odd"; -print([1, 2, 3].map(parity)); // expect: ["odd", "even", "odd"] - -let mut y = 1; -y = y > 0 ? y + 10 : y; -print(y); // expect: 11 - -let mut z = 0; -let w = true ? z = 7 : 0; -print([z, w]); // expect: [7, 7] - -let mut calls = []; -fun log(v) { calls.push(v); return v; } -log(true) ? log("then") : log("else"); -print(calls); // expect: [true, "then"] - -print({ a: x == 5 ? 1 : 2 }); // expect: {a: 1} -print(0..(x > 2 ? 3 : 1)); // expect: [0, 1, 2] -print("{x > 0 ? "pos" : "neg"}"); // expect: pos - -let pick = true ? (a => a * 2) : (a => a); -print(pick(4)); // expect: 8 - -struct P { x } -let p = x > 0 ? P { x } : nil; -print(p); // expect: P {x: 5} - -if (x > 0 ? true : false) { print("ok"); } // expect: ok diff --git a/test/conditional/missing_colon.rn b/test/conditional/missing_colon.rn deleted file mode 100644 index 702368eb..00000000 --- a/test/conditional/missing_colon.rn +++ /dev/null @@ -1 +0,0 @@ -print(1 ? 2); // [line: 1] Error at ')': Expect ':' after then branch of '?'. diff --git a/test/conditional/missing_colon.stderr b/test/conditional/missing_colon.stderr deleted file mode 100644 index 84e23d76..00000000 --- a/test/conditional/missing_colon.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Expect ':' after then branch of '?'. - --> missing_colon.rn:1:12 - | -1 | print(1 ? 2); // [line: 1] Error at ')': Expect ':' after then branch of '?'. - | ^ diff --git a/test/default/basic.rn b/test/default/basic.rn index cbac6c15..53caac3f 100644 --- a/test/default/basic.rn +++ b/test/default/basic.rn @@ -1,4 +1,4 @@ -fun greet(name, greeting = "hi", punct = greeting == "hi" ? "!" : ".") { +fun greet(name, greeting = "hi", punct = if greeting == "hi" { "!" } else { "." }) { return "{greeting} {name}{punct}"; } diff --git a/test/enum/basic.rn b/test/enum/basic.rn index 475b0fbc..576d9efd 100644 --- a/test/enum/basic.rn +++ b/test/enum/basic.rn @@ -10,7 +10,7 @@ print(c is Color); // expect: true print("White" is Color); // expect: false print(c == Color.White); // expect: true print(c == Color.Black); // expect: false -print(c ? "yes" : "no"); // expect: yes +print(if c { "yes" } else { "no" }); // expect: yes let alias = Color; print(alias.Black); // expect: Color.Black diff --git a/test/enum/methods.rn b/test/enum/methods.rn index 51671902..c5d3e270 100644 --- a/test/enum/methods.rn +++ b/test/enum/methods.rn @@ -1,8 +1,8 @@ enum Side { White, Black } impl Side { - fun other(self) { return self == Side.White ? Side.Black : Side.White; } - fun parse(s) { return s == "w" ? Side.White : Side.Black; } + fun other(self) { return if self == Side.White { Side.Black } else { Side.White }; } + fun parse(s) { return if s == "w" { Side.White } else { Side.Black }; } } print(Side.White.other()); // expect: Side.Black diff --git a/test/function/body_must_be_block.rn b/test/function/body_must_be_block.rn index 129f074d..1a11ac27 100644 --- a/test/function/body_must_be_block.rn +++ b/test/function/body_must_be_block.rn @@ -1,3 +1,3 @@ -// [line: 3] Error at '123': Expect '{' or '=>' before function body. +// [line: 3] Error at '123': Expect '{' before function body. // [c line 4] Error at end: Expect '}' after block. fun f() 123; diff --git a/test/function/body_must_be_block.stderr b/test/function/body_must_be_block.stderr index d803b0de..dbc29318 100644 --- a/test/function/body_must_be_block.stderr +++ b/test/function/body_must_be_block.stderr @@ -1,4 +1,4 @@ -error: Expect '{' or '=>' before function body. +error: Expect '{' before function body. --> body_must_be_block.rn:3:9 | 2 | // [c line 4] Error at end: Expect '}' after block. diff --git a/test/function/expression_body.rn b/test/function/expression_body.rn deleted file mode 100644 index db5981c4..00000000 --- a/test/function/expression_body.rn +++ /dev/null @@ -1,21 +0,0 @@ -fun sq(x) => x * x; -print(sq(4)); // expect: 16 - -fun origin() => ({ x: 0, y: 0 }); -print(origin()); // expect: {x: 0, y: 0} - -fun log(m) => { print("log " + m); } -log("hi"); // expect: log hi - -fun sign(n) => n < 0 ? throw ValueError { message: "negative" } : n; -print(sign(2)); // expect: 2 - -struct P { x } -impl P { - fun of(x) => P { x }; - fun double(self) => self.x * 2; -} -print(P.of(3).double()); // expect: 6 - -let add = (a, b = 2) => a + b; -print(add(1)); // expect: 3 diff --git a/test/function/expression_body_semicolon.rn b/test/function/expression_body_semicolon.rn deleted file mode 100644 index 34db608a..00000000 --- a/test/function/expression_body_semicolon.rn +++ /dev/null @@ -1,2 +0,0 @@ -fun f() => 1 -print(f()); // [line: 2] Error at 'print': Expect ';' after function body. diff --git a/test/function/expression_body_semicolon.stderr b/test/function/expression_body_semicolon.stderr deleted file mode 100644 index 7dca0930..00000000 --- a/test/function/expression_body_semicolon.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Expect ';' after function body. - --> expression_body_semicolon.rn:1:13 - | -1 | fun f() => 1 - | ^ diff --git a/test/function/tail_value.rn b/test/function/tail_value.rn new file mode 100644 index 00000000..0610702c --- /dev/null +++ b/test/function/tail_value.rn @@ -0,0 +1,65 @@ +fun sq(x) { x * x } +print(sq(4)); // expect: 16 + +fun origin() { ({ x: 0, y: 0 }) } +print(origin()); // expect: {x: 0, y: 0} + +fun log(m) { print("log " + m); } +print(log("hi")); // expect: log hi +// expect: nil + +fun sign(n) { if n < 0 { throw ValueError { message: "negative" } } else { n } } +print(sign(2)); // expect: 2 + +fun early(n) { + if n > 0 { return "pos"; } + let s = "non-pos {n}"; + s +} +print(early(1), early(0)); // expect: pos non-pos 0 + +fun grade(n) { + match n { + 90.. => "A", + n if n >= 50 => { + let gap = 90 - n; + "B, {gap} to A" + }, + _ => "F", + } +} +print(grade(95), grade(70), grade(1)); // expect: A B, 20 to A F + +fun pick(c) { + let t = "yes"; + if c { t } else { "no" } +} +print(pick(true), pick(false)); // expect: yes no + +struct P { x } +impl P { + fun of(x) { P { x } } + fun double(self) { self.x * 2 } +} +print(P.of(3).double()); // expect: 6 + +let add = (a, b = 2) => a + b; +print(add(1)); // expect: 3 + +let twice = x => { + let y = x * 2; + y +}; +print(twice(4)); // expect: 8 + +let shorthand = name => { name }; +print(shorthand("ann")); // expect: ann + +fun withDefer() { + let mut xs = [1]; + defer { print("deferred", xs); } + xs.push(2); + xs +} +print(withDefer()); // expect: deferred [1, 2] +// expect: [1, 2] diff --git a/test/if/expression.rn b/test/if/expression.rn new file mode 100644 index 00000000..bb73bd12 --- /dev/null +++ b/test/if/expression.rn @@ -0,0 +1,59 @@ +let x = 5; +print(if x > 3 { "big" } else { "small" }); // expect: big +print(if x > 9 { "a" } else if x > 4 { "b" } else { "c" }); // expect: b +print((if x > 9 { 1 } else { 2 }) + 1); // expect: 3 +print(if nil { 1 } else { 0 }); // expect: 0 +print(if [0] { 1 } else { 0 }); // expect: 1 +print(if x > 9 { 1 }); // expect: nil +print(if x > 9 { 1 } else if x > 7 { 2 }); // expect: nil +print(if x > 3 { print("side"); }); // expect: side +// expect: nil + +let parity = n => if n % 2 == 0 { "even" } else { "odd" }; +print([1, 2, 3].map(parity)); // expect: ["odd", "even", "odd"] + +let mut y = 1; +y = if y > 0 { y + 10 } else { y }; +print(y); // expect: 11 + +let label = if x > 0 { + let doubled = x * 2; + "pos {doubled}" +} else { + "neg" +}; +print(label); // expect: pos 10 + +let mut calls = []; +fun log(v) { calls.push(v); v } +if log(true) { log("then") } else { log("else") } +print(calls); // expect: [true, "then"] + +print({ a: if x == 5 { 1 } else { 2 } }); // expect: {a: 1} +print(0..(if x > 2 { 3 } else { 1 })); // expect: [0, 1, 2] +print("{if x > 0 { "pos" } else { "neg" }}"); // expect: pos + +let pick = if true { a => a * 2 } else { a => a }; +print(pick(4)); // expect: 8 + +struct P { x } +let p = if x > 0 { P { x } } else { nil }; +print(p); // expect: P {x: 5} + +let obj = if x > 0 { ({ x }) } else { ({}) }; +print(obj); // expect: {x: 5} + +let mut src = [1]; +let copy = if true { src } else { [] }; +src.push(2); +print(src, copy); // expect: [1, 2] [1] + +let shadow = if true { let x = 1; x } else { 0 }; +print(shadow, x); // expect: 1 5 + +let mut n = 0; +let looped = if true { + for i in 0..3 { n += i; } + n +}; +print(looped); // expect: 3 diff --git a/test/if/expression_bare.rn b/test/if/expression_bare.rn new file mode 100644 index 00000000..a00df9c8 --- /dev/null +++ b/test/if/expression_bare.rn @@ -0,0 +1 @@ +let b = if true 1 else 2; // Error at '1': Expect '{' after if condition. diff --git a/test/if/expression_bare.stderr b/test/if/expression_bare.stderr new file mode 100644 index 00000000..28d73397 --- /dev/null +++ b/test/if/expression_bare.stderr @@ -0,0 +1,5 @@ +error: Expect '{' after if condition. + --> expression_bare.rn:1:17 + | +1 | let b = if true 1 else 2; // Error at '1': Expect '{' after if condition. + | ^ diff --git a/test/if/expression_registers.rn b/test/if/expression_registers.rn new file mode 100644 index 00000000..2b48b70b --- /dev/null +++ b/test/if/expression_registers.rn @@ -0,0 +1,10 @@ +let f = (a, b, c) => [a, b, c]; +print(f(1, if true { let t = 2; t * 10 } else { 0 }, 3)); // expect: [1, 20, 3] +print(f(1, if false { 0 } else { let mut u = [5]; u.push(6); u }, 3)); // expect: [1, [5, 6], 3] +print(f(match 2 { n => { let m = n + 1; m } }, 0, if true { 9 })); // expect: [3, 0, 9] + +let obj = { a: 1, b: if true { let x = "x"; x + x } else { "" }, c: 3 }; +print(obj); // expect: {a: 1, b: "xx", c: 3} + +let s = "p" + (if true { let q = "q"; q } else { "" }) + "r"; +print(s); // expect: pqr diff --git a/test/if/question.rn b/test/if/question.rn new file mode 100644 index 00000000..058327da --- /dev/null +++ b/test/if/question.rn @@ -0,0 +1,3 @@ +// [line: 3] Error: Unexpected character: ? +// [line: 3] Error at '1': Expect ';' after variable declaration. +let a = true ? 1 : 2; diff --git a/test/if/question.stderr b/test/if/question.stderr new file mode 100644 index 00000000..aa674eb1 --- /dev/null +++ b/test/if/question.stderr @@ -0,0 +1,13 @@ +error: Unexpected character: ? + --> question.rn:3:14 + | +2 | // [line: 3] Error at '1': Expect ';' after variable declaration. +3 | let a = true ? 1 : 2; + | ^ + +error: Expect ';' after variable declaration. + --> question.rn:3:16 + | +2 | // [line: 3] Error at '1': Expect ';' after variable declaration. +3 | let a = true ? 1 : 2; + | ^ diff --git a/test/in/precedence.rn b/test/in/precedence.rn index 7c3079bb..6ae62ae4 100644 --- a/test/in/precedence.rn +++ b/test/in/precedence.rn @@ -1,6 +1,6 @@ let xs = [2, false]; print(1 + 1 in xs); // expect: true print(1 in xs == false); // expect: true -print(1 in xs ? "y" : "n"); // expect: n +print(if 1 in xs { "y" } else { "n" }); // expect: n print(!(1 in xs)); // expect: true print(nil ?? 2 in xs); // expect: true diff --git a/test/is/union.rn b/test/is/union.rn index aa8b0888..7a5401cc 100644 --- a/test/is/union.rn +++ b/test/is/union.rn @@ -8,7 +8,7 @@ print(1 !is number | string); // expect: false print(nil !is number | string); // expect: true print(P { x: 2 } is array | T); // expect: true print(1 is string | number == true); // expect: true -print("a" is string | number ? 1 : 2); // expect: 1 +print(if "a" is string | number { 1 } else { 2 }); // expect: 1 x = x is string | number; print(x); // expect: true print([1, "a", nil].map(v => v is nil | string)); // expect: [false, true, true] diff --git a/test/jump/expression.rn b/test/jump/expression.rn index 13b00af6..8f0e9a24 100644 --- a/test/jump/expression.rn +++ b/test/jump/expression.rn @@ -23,7 +23,7 @@ print(out); // expect: [1, 3, 5] let mut n = 0; while true { - n = n < 3 ? n + 1 : break; + n = if n < 3 { n + 1 } else { break; }; } print(n); // expect: 3 diff --git a/test/throw/expression.rn b/test/throw/expression.rn index d5028c73..10f83241 100644 --- a/test/throw/expression.rn +++ b/test/throw/expression.rn @@ -13,7 +13,7 @@ try { } fun sign(n) { - return n > 0 ? 1 : n < 0 ? -1 : throw E { message: "zero" }; + return if n > 0 { 1 } else if n < 0 { -1 } else { throw E { message: "zero" } }; } print(sign(-3)); // expect: -1 diff --git a/test/throw/expression_assign.rn b/test/throw/expression_assign.rn index b15adc6a..f37273b9 100644 --- a/test/throw/expression_assign.rn +++ b/test/throw/expression_assign.rn @@ -2,7 +2,7 @@ struct E { message } let mut x = 1; try { - x = false ? 2 : throw E { message: "m" }; + x = if false { 2 } else { throw E { message: "m" } }; } catch { print(x); // expect: 1 } diff --git a/test/try/expr.rn b/test/try/expr.rn index fb0b863d..40b0cfac 100644 --- a/test/try/expr.rn +++ b/test/try/expr.rn @@ -2,7 +2,7 @@ print(try int("12") catch => 0); // expect: 12 print(try int("x") catch => -1); // expect: -1 print(try int("x") catch e => e is ValueError); // expect: true -fun read(o) => try o.k catch e is TypeError => "type" catch e is KeyError => "key"; +fun read(o) { try o.k catch e is TypeError => "type" catch e is KeyError => "key" } print([read({}), read(1), read({ k: 2 })]); // expect: ["key", "type", 2] print([1, try [].pop() catch => 9, 3]); // expect: [1, 9, 3] @@ -29,5 +29,5 @@ print(y); // expect: 10 let f = try int("z") catch e => () => e.message; print(f()); // expect: int() cannot parse "z" as an integer. -fun pick(a, b, c) => [a, b, c]; +fun pick(a, b, c) { [a, b, c] } print(pick(1, try [][0] catch e => e.message, 3)); // expect: [1, "Index out of bounds: 0 of 0", 3] diff --git a/testdata/fmt/layout.golden b/testdata/fmt/layout.golden index fe2228ec..970b20e5 100644 --- a/testdata/fmt/layout.golden +++ b/testdata/fmt/layout.golden @@ -32,7 +32,12 @@ fun main() { let r = xs .map(x => x * 2) .filter(x => x > 1); - let q = c ? 1 : { a: 2 }; + let q = if c { 1 } else { ({ a: 2 }) }; + + let t = if c { + let n = 1; + n * 2 + } else { 0 }; let m = match v { Point { x, y: 0 } => x, diff --git a/testdata/fmt/layout.rn b/testdata/fmt/layout.rn index fd28a3d0..5a5eb6db 100644 --- a/testdata/fmt/layout.rn +++ b/testdata/fmt/layout.rn @@ -25,7 +25,8 @@ fun main(){ let r = xs .map(x=>x*2) .filter(x => x>1); - let q = c?1:{a:2}; + let q = if c{1}else{({a:2})}; + let t = if c { let n = 1; n*2 } else { 0 }; let m = match v { Point{x,y:0} => x, [a,..._] | [] => 0,