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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/src/data/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
}

Expand Down
2 changes: 1 addition & 1 deletion docs/src/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}!");
}
```
Expand Down
4 changes: 2 additions & 2 deletions docs/src/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 27 additions & 8 deletions docs/src/language/conditionals.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `;`.
2 changes: 1 addition & 1 deletion docs/src/language/destructuring.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/src/language/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 }
Expand All @@ -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 };
Expand Down
35 changes: 20 additions & 15 deletions docs/src/language/functions.md
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -34,32 +36,35 @@ 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
```

## Arrow Functions

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;
Expand All @@ -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 });
Expand All @@ -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
Expand All @@ -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}";
}

Expand Down
4 changes: 2 additions & 2 deletions docs/src/language/loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/src/language/nil-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ print(5 ?? loadDefault()); // 5
print(nil ?? nil ?? "last"); // last
```

`??` binds looser than `||` and tighter than `? :`.
`??` binds looser than `||`.

## Leaving Early

Expand All @@ -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",`.
2 changes: 1 addition & 1 deletion docs/src/language/numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 10 additions & 4 deletions docs/src/language/pattern-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion docs/src/language/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
2 changes: 1 addition & 1 deletion docs/src/language/values.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/src/stdlib/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/src/stdlib/os.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
2 changes: 1 addition & 1 deletion examples/blog/content/hello-rune.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) };
}
```

Expand Down
16 changes: 9 additions & 7 deletions examples/blog/md/block.rn
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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("<pre><code{cls}>{inline.escape(code.join("\n"))}</code></pre>");
continue;
}
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion examples/blog/site/build.rn
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}

Expand Down
2 changes: 1 addition & 1 deletion examples/blog/site/template.rn
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export fun toc(headings) {
let items = headings
.filter(h => h.level == 2)
.map(h => """<li><a href="#{h.id}">{inline.escape(h.text)}</a></li>""");
return items.len() < 2 ? "" : """<nav class="toc"><ul>{items.join("")}</ul></nav>""";
return if items.len() < 2 { "" } else { """<nav class="toc"><ul>{items.join("")}</ul></nav>""" };
}

export fun postLink(p, root = ".") {
Expand Down
Loading
Loading