From c5c2cf8d71b6e660d6011f9b901db57ba54c5d08 Mon Sep 17 00:00:00 2001 From: Alexander Satretdinov Date: Mon, 16 Nov 2026 17:30:49 +0200 Subject: [PATCH 1/2] jumps need no ; before }; fmt reports syntax errors; buffer text/indexOf/hex/base64; no duplicate parse errors --- pkg/format/format.go | 4 +-- pkg/format/format_test.go | 2 +- pkg/rune/parse_stmt.go | 6 ++++- pkg/rune/parser.go | 5 +++- pkg/rune/scanner.go | 15 +++++++++++ pkg/stdlib/binary.go | 24 ++++++++++++++++++ pkg/stdlib/bytes.go | 25 ------------------- pkg/stdlib/native.go | 2 +- test/bytes/buffer.rn | 9 +++++++ test/jump/no_semicolon_before_brace.rn | 25 +++++++++++++++++++ test/parser_recovery/no_duplicate_errors.rn | 3 +++ .../no_duplicate_errors.stderr | 13 ++++++++++ testdata/disasm/methods.golden | 4 +-- testdata/fmt/syntax_error.golden | 15 +++++++++++ testdata/fmt/syntax_error.rn | 5 ++++ 15 files changed, 124 insertions(+), 33 deletions(-) create mode 100644 test/jump/no_semicolon_before_brace.rn create mode 100644 test/parser_recovery/no_duplicate_errors.rn create mode 100644 test/parser_recovery/no_duplicate_errors.stderr create mode 100644 testdata/fmt/syntax_error.golden create mode 100644 testdata/fmt/syntax_error.rn diff --git a/pkg/format/format.go b/pkg/format/format.go index 6b77317..07f1f09 100644 --- a/pkg/format/format.go +++ b/pkg/format/format.go @@ -64,9 +64,9 @@ type printer struct { trailing []int } -// Source formats src, or returns the scan errors that stop it. +// Source formats src, or returns the syntax errors that stop it. func Source(src []byte) ([]byte, []error) { - tokens, errs := rune.Scan(src) + tokens, errs := rune.Parse(src) if len(errs) > 0 { return nil, errs } diff --git a/pkg/format/format_test.go b/pkg/format/format_test.go index 1c288fa..7433601 100644 --- a/pkg/format/format_test.go +++ b/pkg/format/format_test.go @@ -16,7 +16,7 @@ func TestRepoSources(t *testing.T) { return err } src, _ := os.ReadFile(path) - if _, errs := rune.Scan(src); len(errs) > 0 { + if _, errs := rune.Parse(src); len(errs) > 0 { return nil } diff --git a/pkg/rune/parse_stmt.go b/pkg/rune/parse_stmt.go index d1e7734..983b2b8 100644 --- a/pkg/rune/parse_stmt.go +++ b/pkg/rune/parse_stmt.go @@ -487,7 +487,7 @@ func (s *Parser) statement() (ast.Stmt, error) { return s.expressionStatement() } -// jumpStatement parses `return x;`, `break;` or `continue;` (the keyword +// jumpStatement parses `return x;`, `break;` or `continue;`, the `;` optional before `}` (the keyword // is consumed). func (s *Parser) jumpStatement() (ast.Stmt, error) { keyword := s.previous() @@ -497,6 +497,10 @@ func (s *Parser) jumpStatement() (ast.Stmt, error) { return nil, err } + if s.blockDepth > 0 && s.check(ast.RIGHT_BRACE) { + return j.Stmt, nil + } + if _, err := s.consume(ast.SEMICOLON, fmt.Sprintf("Expect ';' after '%s'.", keyword.Lexeme)); err != nil { return nil, err } diff --git a/pkg/rune/parser.go b/pkg/rune/parser.go index 5a3febd..e5b4e92 100644 --- a/pkg/rune/parser.go +++ b/pkg/rune/parser.go @@ -185,7 +185,10 @@ func (s *Parser) safeDeclaration() ast.Stmt { // recover records err and skips past the statement it is in. func (s *Parser) recover(err error) { - s.errors = append(s.errors, err) + if n := len(s.errors); n == 0 || s.errors[n-1].Error() != err.Error() { + s.errors = append(s.errors, err) + } + s.synchronize() } diff --git a/pkg/rune/scanner.go b/pkg/rune/scanner.go index 851fa54..eda0544 100644 --- a/pkg/rune/scanner.go +++ b/pkg/rune/scanner.go @@ -38,6 +38,21 @@ func Scan(source []byte) ([]ast.Token, []error) { return s.tokens, s.errors } +// Parse scans and parses source as an entry file, for the tokens of +// valid code or every error of invalid code. +func Parse(source []byte) ([]ast.Token, []error) { + s := scan(source, 0) + if s.truncated { + return nil, s.errors + } + + if _, errs := parseFile(s.tokens, false); len(s.errors)+len(errs) > 0 { + return nil, append(s.errors, errs...) + } + + return s.tokens, nil +} + func scan(source []byte, file int) *Scanner { scanner := &Scanner{ source: string(source), diff --git a/pkg/stdlib/binary.go b/pkg/stdlib/binary.go index cb868de..66a1a4c 100644 --- a/pkg/stdlib/binary.go +++ b/pkg/stdlib/binary.go @@ -1,15 +1,19 @@ package stdlib import ( + "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" + "encoding/base64" "encoding/binary" + "encoding/hex" "hash/crc32" "math" "rune/pkg/errors" "rune/pkg/value" "slices" + "unicode/utf8" ) // binaryData is argument i, bytes or a buffer, as what it holds now. @@ -166,6 +170,26 @@ func digest(name string, sum func([]byte) []byte) *Native { // alike; prefix names the type. func readers(prefix string) []*Native { return []*Native{ + {prefix + ".text", 1, 1, func(c *call) value.Value { + b := c.binaryData(0) + switch { + case !c.ok(): + return value.NilValue + case !utf8.Valid(b): + return c.fail(errors.ValueError, "got bytes that are not valid UTF-8.") + } + + return value.NewString(string(b)) + }}, + {prefix + ".indexOf", 2, 2, func(c *call) value.Value { + return found(bytes.Index(c.binaryData(0), c.binaryData(1))) + }}, + {prefix + ".hex", 1, 1, func(c *call) value.Value { + return value.NewString(hex.EncodeToString(c.binaryData(0))) + }}, + {prefix + ".base64", 1, 1, func(c *call) value.Value { + return value.NewString(base64.StdEncoding.EncodeToString(c.binaryData(0))) + }}, readInt(prefix+".uint", false), readInt(prefix+".int", true), {prefix + ".float", 2, 4, func(c *call) value.Value { diff --git a/pkg/stdlib/bytes.go b/pkg/stdlib/bytes.go index 270b912..670a3da 100644 --- a/pkg/stdlib/bytes.go +++ b/pkg/stdlib/bytes.go @@ -7,7 +7,6 @@ import ( "rune/pkg/errors" "rune/pkg/helpers" "rune/pkg/value" - "unicode/utf8" ) func (c *call) bytes(i int) []byte { @@ -19,30 +18,6 @@ func (c *call) bytes(i int) []byte { return c.args[i].Bytes() } -var bytesMethods = []*Native{ - {"bytes.text", 1, 1, func(c *call) value.Value { - b := c.bytes(0) - if !c.ok() { - return value.NilValue - } - - if !utf8.Valid(b) { - return c.fail(errors.ValueError, "got bytes that are not valid UTF-8.") - } - - return value.NewString(string(b)) - }}, - {"bytes.indexOf", 2, 2, func(c *call) value.Value { - return found(bytes.Index(c.bytes(0), c.bytes(1))) - }}, - {"bytes.hex", 1, 1, func(c *call) value.Value { - return value.NewString(hex.EncodeToString(c.bytes(0))) - }}, - {"bytes.base64", 1, 1, func(c *call) value.Value { - return value.NewString(base64.StdEncoding.EncodeToString(c.bytes(0))) - }}, -} - // toBytes is bytes(v): a string's UTF-8, an array of integers from 0 to // 255, or bytes as they are. var toBytes = &Native{"bytes", 1, 1, func(c *call) value.Value { diff --git a/pkg/stdlib/native.go b/pkg/stdlib/native.go index 7599a11..f3e15a2 100644 --- a/pkg/stdlib/native.go +++ b/pkg/stdlib/native.go @@ -373,7 +373,7 @@ var Methods = func() (out []Method) { add(value.Map, true, mapInPlace) add(value.Set, false, setMethods, lenMethod("set")) add(value.Set, true, setInPlace) - add(value.Bytes, false, bytesMethods, readers("bytes"), lenMethod("bytes")) + add(value.Bytes, false, readers("bytes"), lenMethod("bytes")) add(value.Buffer, false, bufferMethods) add(value.Buffer, true, bufferInPlace) add(value.Stream, false, streamMethods) diff --git a/test/bytes/buffer.rn b/test/bytes/buffer.rn index 5fbdf09..358f94f 100644 --- a/test/bytes/buffer.rn +++ b/test/bytes/buffer.rn @@ -56,3 +56,12 @@ b.write("x"); fails(() => { b[0] = 256; }); // expect: ValueError: A buffer holds bytes from 0 to 255, got 256. fails(() => { let mut m = map(); m[b] = 1; }); // expect: TypeError: Cannot use a buffer as a key. print(b.len()); // expect: 1 + +let mut req = bytes.buffer(); +req.write("GET /health\n"); +print(req.text().trim()); // expect: GET /health +print(req.indexOf(b"\n")); // expect: 11 +print(req.indexOf(b"POST")); // expect: nil +print(b"GET /".indexOf(bytes.buffer(b"/"))); // expect: 4 +print(bytes.buffer(b"hi!").hex()); // expect: 686921 +print(bytes.buffer(b"hi!").base64()); // expect: aGkh diff --git a/test/jump/no_semicolon_before_brace.rn b/test/jump/no_semicolon_before_brace.rn new file mode 100644 index 0000000..f647212 --- /dev/null +++ b/test/jump/no_semicolon_before_brace.rn @@ -0,0 +1,25 @@ +fun sign(n) { + if n < 0 { return -1 } + if n == 0 { return 0 } + 1 +} + +print(sign(-5)); // expect: -1 +print(sign(0)); // expect: 0 +print(sign(9)); // expect: 1 + +fun half(n) { + let h = if n % 2 == 0 { n / 2 } else { return nil }; + h +} + +print(half(8)); // expect: 4 +print(half(7)); // expect: nil + +let mut odd = []; +for i in 0..6 { + if i % 2 == 0 { continue } + if i > 4 { break } + odd.push(i); +} +print(odd); // expect: [1, 3] diff --git a/test/parser_recovery/no_duplicate_errors.rn b/test/parser_recovery/no_duplicate_errors.rn new file mode 100644 index 0000000..08aa1dc --- /dev/null +++ b/test/parser_recovery/no_duplicate_errors.rn @@ -0,0 +1,3 @@ +// [line: 3] Error at '}': Expect variable name. +// [line: 3] Error at end: Expect '}' after block. +for i in 0..3 { if i == 1 { let } print(i); } diff --git a/test/parser_recovery/no_duplicate_errors.stderr b/test/parser_recovery/no_duplicate_errors.stderr new file mode 100644 index 0000000..0a17f51 --- /dev/null +++ b/test/parser_recovery/no_duplicate_errors.stderr @@ -0,0 +1,13 @@ +error: Expect variable name. + --> no_duplicate_errors.rn:3:33 + | +2 | // [line: 3] Error at end: Expect '}' after block. +3 | for i in 0..3 { if i == 1 { let } print(i); } + | ^ + +error: Expect '}' after block. + --> no_duplicate_errors.rn:3:46 + | +2 | // [line: 3] Error at end: Expect '}' after block. +3 | for i in 0..3 { if i == 1 { let } print(i); } + | ^ diff --git a/testdata/disasm/methods.golden b/testdata/disasm/methods.golden index d398711..bd14a82 100644 --- a/testdata/disasm/methods.golden +++ b/testdata/disasm/methods.golden @@ -5,9 +5,9 @@ exit: 0 1 LOADK 2 0 1 2 LOADK 3 0 2 3 CLOSURE 4 0 0 - 4 METHOD 4 0 94 + 4 METHOD 4 0 98 5 CLOSURE 4 0 1 - 6 METHOD 4 0 95 + 6 METHOD 4 0 99 7 LOADK 4 0 3 8 STRUCT 2 4 0 9 MOVE 5 2 0 diff --git a/testdata/fmt/syntax_error.golden b/testdata/fmt/syntax_error.golden new file mode 100644 index 0000000..dbf5a87 --- /dev/null +++ b/testdata/fmt/syntax_error.golden @@ -0,0 +1,15 @@ +exit: 65 +-- stdout -- +-- stderr -- +error: Expect expression. + --> syntax_error.rn:1:14 + | +1 | let x = (1 + ; + | ^ + +error: Expect ';' after expression. + --> syntax_error.rn:2:9 + | +1 | let x = (1 + ; +2 | print(x) + | ^ diff --git a/testdata/fmt/syntax_error.rn b/testdata/fmt/syntax_error.rn new file mode 100644 index 0000000..7a1ccfe --- /dev/null +++ b/testdata/fmt/syntax_error.rn @@ -0,0 +1,5 @@ +let x = (1 + ; +print(x) +fun ok() { + 1 +} From 60d82a9324c258efa1b0e8bc9c08a2d33a7c7b6d Mon Sep 17 00:00:00 2001 From: Alexander Satretdinov Date: Mon, 16 Nov 2026 17:30:49 +0200 Subject: [PATCH 2/2] docs: rewrite chapters with clear text and verified examples --- README.md | 6 +- docs/src/contributing/testing.md | 33 +- docs/src/data/arrays.md | 196 ++++++++---- docs/src/data/bytes.md | 176 ++++++----- docs/src/data/enums.md | 247 ++++++++++----- docs/src/data/map-and-set.md | 172 +++++++---- docs/src/data/methods.md | 250 ++++++++------- docs/src/data/structs.md | 149 +++++---- docs/src/errors-and-exit-codes.md | 120 +++++--- docs/src/getting-started.md | 68 ++++- docs/src/internals/performance.md | 129 +++++--- docs/src/introduction.md | 38 ++- docs/src/language/conditionals.md | 120 ++++++-- docs/src/language/destructuring.md | 196 ++++++++---- docs/src/language/error-handling.md | 281 +++++++++++------ docs/src/language/functions.md | 254 ++++++++++----- docs/src/language/loops.md | 211 +++++++++---- docs/src/language/nil-safety.md | 119 +++++--- docs/src/language/numbers.md | 193 ++++++++---- docs/src/language/pattern-matching.md | 424 +++++++++++++++++--------- docs/src/language/spread-and-rest.md | 94 ++++-- docs/src/language/strings.md | 172 +++++++---- docs/src/language/values.md | 287 ++++++++++------- docs/src/language/variables.md | 212 ++++++++----- docs/src/programs/examples.md | 11 +- docs/src/programs/main.md | 57 +++- docs/src/programs/modules.md | 146 ++++++--- docs/src/stdlib/array.md | 225 ++++++++++---- docs/src/stdlib/builtins.md | 170 ++++++++--- docs/src/stdlib/fs.md | 177 ++++++++--- docs/src/stdlib/io.md | 50 ++- docs/src/stdlib/json-http.md | 139 ++++++--- docs/src/stdlib/math.md | 87 ++++-- docs/src/stdlib/object.md | 111 +++++-- docs/src/stdlib/os.md | 104 +++++-- docs/src/stdlib/regex.md | 106 +++++-- docs/src/stdlib/streams.md | 92 ++++-- docs/src/stdlib/string.md | 179 ++++++++--- docs/src/stdlib/time.md | 143 ++++++--- 39 files changed, 4089 insertions(+), 1855 deletions(-) diff --git a/README.md b/README.md index 7ccdc0d..6990eb8 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,9 @@ it somewhere on your `PATH`. ```sh # macOS on Apple silicon; swap the version and platform for yours -curl -LO https://github.com/kryptamine/rune/releases/download/v0.1.0/rune-0.1.0-darwin-arm64.tar.gz -tar -xzf rune-0.1.0-darwin-arm64.tar.gz -sudo mv rune-0.1.0-darwin-arm64/rune /usr/local/bin/ +curl -LO https://github.com/kryptamine/rune/releases/download/v0.3.0/rune-0.3.0-darwin-arm64.tar.gz +tar -xzf rune-0.3.0-darwin-arm64.tar.gz +sudo mv rune-0.3.0-darwin-arm64/rune /usr/local/bin/ rune version ``` diff --git a/docs/src/contributing/testing.md b/docs/src/contributing/testing.md index ade2f2a..1a09e23 100644 --- a/docs/src/contributing/testing.md +++ b/docs/src/contributing/testing.md @@ -2,17 +2,36 @@ ```sh make test # all tests -make test filter=arrays # scripts under test/arrays +make test filter=arrays # only the scripts under test/arrays make update # rewrite golden files after an intended change make cover # coverage make fuzz FUZZTIME=1m # fuzz the whole pipeline ``` -Each `test/**/*.rn` script runs in-process, in parallel, with a 5s timeout. Directives in comments: +## Script tests -- `// expect: ` — next line of stdout; -- `// [line: N] Error...` — compile error, in order; without `[line: N]` it is the comment's line; -- `// expect runtime error: [line: N] ` — uncaught runtime error. +Most tests are Rune scripts, `test/**/*.rn`. Each runs in-process, in +parallel with the others, with a 5 second timeout. Comments in the script +say what it must do: -`foo.stderr` next to `foo.rn` holds the full error report (snippet, caret, trace); a missing file means empty stderr. -`testdata//*.rn` are run through the CLI command (`run`, `disasm`, `fmt`) and compared with `.golden` files: exit code, stdout and stderr. +- `// expect: ` — the next line of stdout. +- `// Error...` — a compile error on this line. Compile errors are + checked in order; `// [line: N] Error...` puts one on line `N`. +- `// expect runtime error: [line: N] ` — the uncaught runtime + error the script ends with. + +```rune +let prices = [30, 120]; +print(prices.len()); // expect: 2 +print(prices[5]); // expect runtime error: [line: 3] IndexError: Index out of bounds: 5 of 2 +``` + +A file `name.stderr` next to `name.rn` holds the full error report the +script prints: the snippet, the caret and the trace. No such file means +stderr must be empty. `make update` writes these files. + +## CLI tests + +`testdata//*.rn` run through the CLI command of their directory, +`run`, `disasm` or `fmt`. Each is compared with its `.golden` file, which +holds the exit code, stdout and stderr. diff --git a/docs/src/data/arrays.md b/docs/src/data/arrays.md index fa7ffff..0e9bbca 100644 --- a/docs/src/data/arrays.md +++ b/docs/src/data/arrays.md @@ -1,36 +1,55 @@ # Arrays -An array is an ordered list of values of any type. `xs[i]` reads element -`i`, counting from `0`, and `xs.len()` is the number of elements. +An array is an ordered list of values. Write one with square brackets; the +elements may be of any type, mixed freely. ```rune let langs = ["go", "rust", "rune"]; -print(langs[0]); // go -print(langs.len()); // 3 +print(langs); // ["go", "rust", "rune"] +print(langs.len()); // 3 let row = [1, 2.5, "three", true, nil, [4]]; -print(row); // [1, 2.5, "three", true, nil, [4]] +print(row); // [1, 2.5, "three", true, nil, [4]] +``` + +## Indexing + +`xs[i]` reads the element at index `i`, counting from `0`. A negative index +counts from the end, so `xs[-1]` is the last element. Arrays nest, and +indexes chain. + +```rune +let langs = ["go", "rust", "rune"]; +print(langs[0]); // go +print(langs[-1]); // rune let grid = [[1, 2], [3, 4]]; -print(grid[1][0]); // 3 +print(grid[1][0]); // 3 ``` -An index must be an integer from `-xs.len()` to `xs.len() - 1`; a negative one -counts from the end, as in strings, bytes, slices and `remove`. One out of -bounds is an `IndexError`, for reading and writing alike. To grow an array, -`push` to it. +An index must be an integer from `-xs.len()` to `xs.len() - 1`. Anything +outside is an `IndexError`, for reading and writing alike: ```rune let langs = ["go", "rust", "rune"]; -print(langs[-1]); // rune -print(langs[3]); // IndexError: Index out of bounds: 3 of 3 +print(langs[3]); // IndexError: Index out of bounds: 3 of 3 ``` -`xs[a..b]` is a new array of the elements from `a` up to `b`, `xs[a..=b]` -up to `b` included; either bound may be left out, and a negative one -counts from the end. Bounds past either end are clamped, so a slice is -never an error but may be empty. `x in xs` tests for an element (see -[Membership](../language/values.md#membership)). +When an element may be missing, read it with `?.[i]`, which gives `nil` +instead, and pick a fallback with `??` (see [Nil Safety](../language/nil-safety.md)): + +```rune +let args = ["report.csv"]; +print(args?.[0] ?? "stdin"); // report.csv +print(args?.[1] ?? "out.txt"); // out.txt +``` + +## Slices + +`xs[a..b]` is a new array of the elements from index `a` up to, but not +including, `b`; `xs[a..=b]` includes `b`. Either bound may be left out, +and a negative bound counts from the end. Bounds past either end are +clamped, so a slice is never an error, though it may be empty. ```rune let xs = [10, 20, 30, 40, 50]; @@ -40,82 +59,149 @@ print(xs[..2]); // [10, 20] print(xs[-2..]); // [40, 50] print(xs[..-1]); // [10, 20, 30, 40] print(xs[3..99]); // [40, 50] -print(30 in xs); // true ``` -Writing an element needs a mutable variable (see [Variables](../language/variables.md)): +`x in xs` tests whether an element is in the array, comparing with `==` +(see [Membership](../language/values.md#membership)): + +```rune +let admins = ["ann", "bob"]; +print("ann" in admins); // true +print("eve" in admins); // false +``` + +## Changing an Array + +Changing an array needs a mutable variable (see +[Variables](../language/variables.md)). Assign to an index to replace an +element, and `push` to add one at the end; an index cannot grow the array. ```rune let mut scores = [70, 85, 90]; scores[0] = 75; scores[1] += 5; scores.push(100); -print(scores); // [75, 90, 90, 100] +print(scores); // [75, 90, 90, 100] +print(scores.pop()); // 100 +print(scores); // [75, 90, 90] ``` -`for x in xs` walks the elements, `for i, x in xs` the indices too. The -elements are taken when the loop starts, so pushing inside the loop does not -extend it. +`insert`, `remove`, `sort`, `reverse` and the other +[array methods](../stdlib/array.md) are listed in the standard library. + +## Iterating + +`for x in xs` walks the elements; `for i, x in xs` gives the index too. ```rune -let todo = ["write docs", "fix bug"]; +let todo = ["write docs", "fix bug", "release"]; for i, task in todo { print("{i + 1}. {task}"); } // 1. write docs // 2. fix bug +// 3. release ``` -`==` compares arrays element by element: +The loop walks the array as it was when the loop began, so pushing inside +the body does not make it run longer: ```rune -print([1, [2, 3]] == [1, [2, 3]]); // true -print([1, 2] == [2, 1]); // false +let mut queue = ["build"]; +for job in queue { + queue.push("after " + job); +} +print(queue); // ["build", "after build"] ``` -Arrays are values, like numbers and strings: assigning one, passing it to -a function, returning it or storing it in an element or a property gives -an independent copy. `push`, `pop` and index assignment change only the -array they are called on. +## Equality + +`==` compares arrays element by element, nested ones included. Order +matters. + +```rune +print([1, [2, 3]] == [1, [2, 3]]); // true +print([1, 2] == [2, 1]); // false +``` + +## Arrays Are Values + +An array behaves like a number or a string: assigning it, passing it to a +function, returning it or storing it somewhere gives an independent copy. +Changing the copy never changes the original. + +```rune +let defaults = ["read"]; +let mut perms = defaults; +perms.push("write"); +print(defaults); // ["read"] +print(perms); // ["read", "write"] +``` + +So a function cannot change the caller's array by accident. It works on +its own copy and returns the result: ```rune -let a = [1, 2]; -let mut b = a; -b.push(3); -print(a); // [1, 2] -print(b); // [1, 2, 3] - -fun grow(xs) { let mut ys = xs; ys.push(0); return ys; } -print(grow(a)); // [1, 2, 0] -print(a); // [1, 2] +fun withTax(prices) { + let mut out = prices; + for i, p in out { + out[i] = p * 1.2; + } + out +} + +let prices = [10, 25]; +print(withTax(prices)); // [12, 30] +print(prices); // [10, 25] +``` + +When a function should change the caller's array, mark the parameter +[`mut`](../language/functions.md#mut-parameters): + +```rune +fun addTag(mut tags, tag) { + if !(tag in tags) { + tags.push(tag); + } +} + +let mut tags = ["new"]; +addTag(tags, "sale"); +addTag(tags, "sale"); +print(tags); // ["new", "sale"] ``` -A copy costs nothing until it is written: the array is copied on its first -change, and only if something else still holds it. +Copies are cheap: an array is copied only when it is written and something +else still holds it, so passing a large array around costs nothing. A write along a path, as in `grid[0][1] = 9` or `grid[0].push(9)`, changes -only the array at the end of it: a copy taken earlier of any array on the -way keeps its value. +only the array it goes through. Copies taken earlier of any part keep their +values: ```rune let mut grid = [[0, 0], [0, 0]]; let row = grid[0]; let before = grid; grid[0][1] = 9; -print(row); // [0, 0] -print(before); // [[0, 0], [0, 0]] -print(grid); // [[0, 9], [0, 0]] +print(grid); // [[0, 9], [0, 0]] +print(row); // [0, 0] +print(before); // [[0, 0], [0, 0]] ``` -A function changes the caller's array only through a -[`mut` parameter](../language/functions.md#mut-parameters). +## Transforming -`map`, `filter`, `sort`, `join` and the rest are -[array methods](../stdlib/array.md). +`map`, `filter`, `reduce` and friends return new arrays, which makes +chains of them read like a pipeline. All of them are in +[Array Methods](../stdlib/array.md). ```rune -let prices = [12, 5, 30, 8]; -print(prices.map(p => p * 2)); // [24, 10, 60, 16] -print(prices.filter(p => p > 10)); // [12, 30] -print(prices.reduce((a, b) => a + b)); // 55 +let orders = [ + { id: 1, total: 30 }, + { id: 2, total: 120 }, + { id: 3, total: 75 }, +]; + +let big = orders.filter(o => o.total > 50).map(o => o.id); +print(big); // [2, 3] +print(orders.reduce((sum, o) => sum + o.total, 0)); // 225 ``` diff --git a/docs/src/data/bytes.md b/docs/src/data/bytes.md index 7cbddcd..51e5952 100644 --- a/docs/src/data/bytes.md +++ b/docs/src/data/bytes.md @@ -1,43 +1,28 @@ # Bytes -`bytes` are immutable binary data: a `b"..."` literal, which takes -`\xNN` escapes and no interpolation, or `bytes(v)` of a string (its UTF-8), -an array of integers from 0 to 255, or bytes. `b[i]` is the integer byte, -`b[a..b]` a slice sharing the data, `x in b` finds a byte or bytes, -`b.len()` the size; `+` joins and `<` compares bytes, `==` by content, and -`for i, x in b` walks them. Bytes are hashable, and print as a literal. +`bytes` are immutable binary data: file headers, network packets, hashes, +anything that is not text. A string holds characters; bytes hold raw +values from 0 to 255. -```rune -let header = b"\x89PNG"; -print(header); // b"\x89PNG" -print(header[0]); // 137 -print(header.len()); // 4 -print(header.hex()); // 89504e47 - -print(bytes("é")); // b"\xc3\xa9" -print(bytes([104, 105])); // b"hi" -print(b"hi" + b"!"); // b"hi!" -print(b"hi" == bytes("hi")); // true - -for i, x in b"hi" { - print("{i}: {x}"); -} -// 0: 104 -// 1: 105 -``` +## Making Bytes -A byte cannot be changed; build new bytes, or use a [buffer](#buffers): +Write a `b"..."` literal, where `\xNN` gives a byte by its hex value (no +interpolation), or convert with `bytes(v)`: a string gives its UTF-8 +encoding, an array gives one byte per integer. ```rune -let mut buf = b"ab"; -buf[0] = 120; // TypeError: Bytes are immutable. +let magic = b"\x89PNG"; +print(magic); // b"\x89PNG" +print(bytes("é")); // b"\xc3\xa9" +print(bytes([104, 105])); // b"hi" ``` -## The bytes namespace +Bytes print as a literal: printable ASCII as is, the rest escaped as +`\n`, `\xNN` and so on. -Besides `bytes(v)` itself, `alloc(n[, fill])` (`n` bytes of `fill`, -default `0`), `fromHex(s)`, `fromBase64(s)` and `buffer([data])`, a new -[buffer](#buffers): +The `bytes` namespace has a few more constructors: `alloc(n[, fill])` +makes `n` bytes of `fill` (default `0`); `fromHex(s)` and `fromBase64(s)` +decode text. ```rune print(bytes.alloc(3)); // b"\x00\x00\x00" @@ -46,38 +31,66 @@ print(bytes.fromHex("cafe")); // b"\xca\xfe" print(bytes.fromBase64("aGk=")); // b"hi" ``` +## Working With Bytes + +Bytes work much like a string or an array: + +- `b[i]` is the byte at `i`, an integer; a negative index counts from the end; +- `b[a..b]` is a slice, which shares the data instead of copying it; +- `b.len()` is the size; +- `x in b` finds a byte or a run of bytes; +- `+` joins, `==` compares content, `<` compares byte by byte; +- `for i, x in b` walks the bytes, and `[...b]` spreads them into an array of integers. + +```rune +let file = b"\x89PNG\r\n\x1a\nIHDR"; +print(file.len()); // 12 +print(file[0]); // 137 +print(file[..4] == b"\x89PNG"); // true +print(b"IHDR" in file); // true +print(file[-4..]); // b"IHDR" +``` + +Bytes are hashable, so they can be [map](map-and-set.md) keys and set +elements. + ## Methods -`text()` (the bytes as UTF-8 text, as a stream's `readText()` reads it; -anything else is a `ValueError`), `indexOf(sub)` (`nil` if missing), `hex()` -and `base64()`. `[...b]` is the bytes as an array of integers, and `+` -joins them; to join many, write them to a [buffer](#buffers). +- `text()` — decodes the bytes as UTF-8; invalid UTF-8 is a `ValueError`; +- `indexOf(sub)` — where `sub` starts, or `nil`; +- `hex()`, `base64()` — encode as text. ```rune let data = b"hello"; -print(data.text()); // hello -print([...data]); // [104, 101, 108, 108, 111] -print(data[1..3]); // b"el" -print(data.indexOf(b"ll")); // 2 -print(data + b", world"); // b"hello, world" -print(data.base64()); // aGVsbG8= +print(data.text()); // hello +print([...data]); // [104, 101, 108, 108, 111] +print(data.indexOf(b"ll")); // 2 +print(data + b", world"); // b"hello, world" +print(data.hex()); // 68656c6c6f +print(data.base64()); // aGVsbG8= ``` ```rune print(b"\xff".text()); // ValueError: bytes.text() got bytes that are not valid UTF-8. ``` -## Binary data +A byte cannot be changed in place. Build new bytes, or use a +[buffer](#buffers): + +```rune +let mut header = b"ab"; +header[0] = 120; // TypeError: Bytes are immutable. +``` -These read numbers at an offset; a read past the end is an `IndexError`. -`order` is `"le"` (the default) or `"be"`. +## Reading Numbers + +Binary formats store numbers as fixed-size or variable-size runs of bytes. +These methods read one at an offset `at`; a read past the end is an +`IndexError`. `order` is `"le"` (little-endian, the default) or `"be"`. - `uint(at, size[, order])`, `int(at, size[, order])` — an integer of 1, 2, 4 or 8 bytes; an 8-byte `uint` keeps all 64 bits, as two's complement; - `float(at[, size[, order]])` — a float of 4 or 8 bytes (the default); -- `uvarint(at)`, `varint(at)` — a varint as `[value, next offset]`, or `nil` if the bytes end first. - -`crc32()` is the IEEE checksum, an integer; `md5()`, `sha1()` and -`sha256()` give the digest as bytes. +- `uvarint(at)`, `varint(at)` — a varint, as `[value, next offset]`, or `nil` if the bytes end first. ```rune let b = b"\x2a\x00\xff\xff\xac\x02"; @@ -85,38 +98,57 @@ print(b.uint(0, 2)); // 42 print(b.uint(0, 2, "be")); // 10752 print(b.int(2, 2)); // -1 print(b.uvarint(4)); // [300, 6] -print(b"hello".crc32()); // 907060870 -print(b"abc".sha256().hex()[..16]); // ba7816bf8f01cfea +``` + +## Checksums and Hashes + +`crc32()` is the IEEE checksum, as an integer. `md5()`, `sha1()` and +`sha256()` give the digest as bytes; `hex()` makes it readable. + +```rune +print(b"hello".crc32()); // 907060870 +print(bytes("hello").sha256().hex()[..16]); // 2cf24dba5fb0a30e ``` ## Buffers -A buffer is binary data that changes in place: `bytes.buffer()` makes an -empty one and `bytes.buffer(data)` one holding a copy of a string, bytes or -another buffer. `buf[i]` reads a byte and `buf[i] = x` sets one; it -iterates, spreads and compares like bytes, and every reading method of -bytes works on it too. Like an array, it needs a `let mut` to change, and -like every value it is [copied](../language/values.md#copies) where it goes. +A buffer is binary data that changes in place, the way to build bytes +piece by piece. `bytes.buffer()` makes an empty one; `bytes.buffer(data)` +starts with a copy of a string, bytes or another buffer. Like an array, it +needs a `let mut` to change, and like every value it is +[copied](../language/values.md#copies) when assigned or passed. + +Writing: - `write(data)` — appends a string, bytes or a buffer; - `writeUint(x, size[, order])`, `writeInt(x, size[, order])`, `writeFloat(x[, size[, order]])`, `writeUvarint(x)`, `writeVarint(x)` — append a number, the counterparts of the reads above; a number that does not fit is a `ValueError`; -- `clear()` empties it; `len()`; -- `buf[a..b]` — a copy as bytes, which later writes leave alone; `buf[..]` copies it all. +- `buf[i] = x` — sets one byte; +- `clear()` — empties it. + +Reading works as on bytes: `buf[i]`, `len()`, `for`, spread, `==`, +`text()`, `indexOf()`, `hex()`, `base64()`, the number reads (`uint`, +`varint`, ...) and the checksums. `buf[a..b]` is a copy as bytes, which +later writes leave alone; `buf[..]` copies it all. -`fs.write`, `fs.append` and a stream's `write` take a buffer as they -take bytes. +A length-prefixed record, as a binary protocol might send it: ```rune -let mut rec = bytes.buffer(); -rec.writeUint(1, 1); -rec.writeUvarint(300); -rec.write("key"); -print(rec); // buffer(b"\x01\xac\x02key") -rec[0] = 2; -print(rec.uvarint(1)); // [300, 3] - -let mut out = bytes.buffer(); -out.writeUint(rec.len(), 4, "be"); -out.write(rec); -print(out[..].hex()); // 0000000602ac026b6579 +let mut body = bytes.buffer(); +body.writeUvarint(300); +body.write("key"); + +let mut packet = bytes.buffer(); +packet.writeUint(body.len(), 4, "be"); +packet.write(body); + +print(packet); // buffer(b"\x00\x00\x00\x05\xac\x02key") +print(packet.hex()); // 00000005ac026b6579 + +let size = packet.uint(0, 4, "be"); +let [id, next] = packet.uvarint(4); +print(size, id); // 5 300 +print(packet[next..next + 3].text()); // key ``` + +`fs.write`, `fs.append` and a stream's `write` take a buffer as they take +bytes. diff --git a/docs/src/data/enums.md b/docs/src/data/enums.md index 5859b68..b7ecaa2 100644 --- a/docs/src/data/enums.md +++ b/docs/src/data/enums.md @@ -1,160 +1,241 @@ # Enums -An enum is a type with a fixed set of named values, its variants, which -may [have fields](#variants-with-fields). A variant is not a number or a string: it equals only itself, prints as -`Type.Variant` and is tested with `is`. Enums are declared at the top -level only and can be used before their declaration. +An enum is a type with a fixed set of named values, called variants. +Use one when a value is one of a few known choices: an order status, a +direction, a log level. Unlike strings, a typo is a compile error, and a +`match` can check that every case is handled. ```rune -enum Color { White, Black } +enum Status { Pending, Paid, Shipped, Cancelled } -let c = Color.White; -print(c); // Color.White -print(c is Color); // true -print(c == Color.Black); // false -print(Color is enum); // true +let s = Status.Paid; +print(s); // Status.Paid +print(s == Status.Paid); // true +print(s == Status.Shipped); // false +print(s is Status); // true ``` -A name that is not a variant is a compile error: +A variant is not a number or a string: it equals only itself and prints +as `Type.Variant`. Enums are declared at the top level only and can be +used before their declaration. + +A name that is not a variant is caught before the program runs: ```rune -enum Color { White, Black } -print(Color.Red); // Error at 'Red': Color has no variant 'Red'. +enum Status { Pending, Paid, Shipped, Cancelled } +print(Status.Payed); // Error at 'Payed': Status has no variant 'Payed'. +``` + +Variants can also [carry fields](#variants-with-fields), which makes +enums a natural fit for values that come in several shapes. + +## Matching + +A variant is a pattern, so `match` turns a variant into whatever it +stands for: + +```rune +enum Status { Pending, Paid, Shipped, Cancelled } + +fun label(s) { + match s { + Status.Pending => "waiting for payment", + Status.Paid | Status.Shipped => "on its way", + Status.Cancelled => "cancelled", + } +} + +print(label(Status.Pending)); // waiting for payment +print(label(Status.Shipped)); // on its way ``` -## Ordinals and conversion +This `match` has no `_` arm, and it does not need one: it lists every +variant. If a variant is later added to `Status`, the compiler points at +each `match` that forgot it; see [Matching every variant](#matching-every-variant). + +## Numbers and Names -Variants are numbered from 0 in declaration order. `int(v)` is a variant's -number and `v.name` its name; calling the enum converts back, from the -number or from the name. `Color.values()` lists the variants in order. +Variants are numbered from 0 in declaration order. `int(v)` gives a +variant's number and `v.name` its name. Calling the enum converts back, +from a number or from a name, and `values()` lists all variants in order. ```rune enum Dir { North, East, South, West } -print(int(Dir.South)); // 2 -print(Dir.South.name); // South -print(Dir(3)); // Dir.West -print(Dir("East")); // Dir.East -print(Dir.values()); // [Dir.North, Dir.East, Dir.South, Dir.West] -print(Dir((int(Dir.West) + 1) % 4)); // Dir.North +print(int(Dir.South)); // 2 +print(Dir.South.name); // South +print(Dir(3)); // Dir.West +print(Dir("East")); // Dir.East +print(Dir.values()); // [Dir.North, Dir.East, Dir.South, Dir.West] ``` +That is enough to turn right by stepping to the next variant and +wrapping around: + +```rune +enum Dir { North, East, South, West } + +fun turnRight(d) { Dir((int(d) + 1) % Dir.values().len()) } + +print(turnRight(Dir.North)); // Dir.East +print(turnRight(Dir.West)); // Dir.North +``` + +A number or name with no variant is a `ValueError`: + ```rune enum Dir { North, East, South, West } Dir(4); // ValueError: Dir has no variant 4. ``` -`json.stringify` writes a variant as its name, so `Dir(name)` reads it -back. Variants are hashable, as map keys and set elements. +`json.stringify` writes a variant as its name, so calling the enum on +the parsed name reads it back. Variants can also be map keys and set +elements. ```rune -enum Dir { North, East } +enum Dir { North, East, South, West } let saved = json.stringify({ facing: Dir.East }); -print(saved); // {"facing":"East"} -print(Dir(json.parse(saved).facing)); // Dir.East +print(saved); // {"facing":"East"} +print(Dir(json.parse(saved).facing)); // Dir.East + +let visits = map([[Dir.North, 2], [Dir.West, 1]]); +print(visits[Dir.North]); // 2 ``` -## Matching +## Variants with Fields + +A variant may have fields, declared like a struct's. Each such variant +is a struct type of its own: build it with `Enum.Variant { ... }`, read +its fields with `.`, and test it with `is`. `v is Enum` holds for every +variant. -A variant is a pattern: +This fits data that comes in several shapes, such as payment methods: ```rune -enum Piece { Pawn, Knight, Bishop, Rook, Queen, King } - -fun worth(p) { - return match p { - Piece.Pawn => 1, - Piece.Knight | Piece.Bishop => 3, - Piece.Rook => 5, - Piece.Queen => 9, - Piece.King => 0, - }; +enum Payment { + Card { last4, brand = "visa" }, + Transfer { iban }, + Cash, } -print(worth(Piece.Bishop)); // 3 +let p = Payment.Card { last4: "4242" }; +print(p); // Payment.Card {last4: "4242", brand: "visa"} +print(p.last4); // 4242 +print(p is Payment.Card); // true +print(p is Payment); // true +print(Payment.Cash is Payment); // true ``` -## Variants with fields +Match on the variant and take its fields apart in one step: + +```rune +enum Payment { + Card { last4, brand = "visa" }, + Transfer { iban }, + Cash, +} + +fun describe(p) { + match p { + Payment.Card { brand, last4 } => "{brand} card ending in {last4}", + Payment.Transfer { iban } => "bank transfer from {iban[..4]}…", + Payment.Cash => "cash on delivery", + } +} + +print(describe(Payment.Card { last4: "4242", brand: "amex" })); // amex card ending in 4242 +print(describe(Payment.Transfer { iban: "DE89370400440532013000" })); // bank transfer from DE89… +print(describe(Payment.Cash)); // cash on delivery +``` -A variant may have fields, declared as a struct's are. `Enum.Variant { ... }` -makes one, and it is a struct of that type: its fields are read with `.`, -matched with `Enum.Variant { ... }` and tested with `is`; `v is Enum` holds -for every variant. +Variants that refer to the enum itself describe trees. Here is a small +expression evaluator: ```rune enum Expr { Num { value }, Add { left, right }, + Mul { left, right }, Neg { expr }, - Zero, } -let e = Expr.Add { left: Expr.Num { value: 1 }, right: Expr.Neg { expr: Expr.Num { value: 3 } } }; -print(e.left.value); // 1 -print(e is Expr.Add); // true -print(e is Expr); // true -print(Expr.Num { value: 5 }); // Expr.Num {value: 5} +fun eval(e) { + match e { + Expr.Num { value } => value, + Expr.Add { left, right } => eval(left) + eval(right), + Expr.Mul { left, right } => eval(left) * eval(right), + Expr.Neg { expr } => -eval(expr), + } +} + +// -(2 + 3) * 4 +let e = Expr.Mul { + left: Expr.Neg { expr: Expr.Add { left: Expr.Num { value: 2 }, right: Expr.Num { value: 3 } } }, + right: Expr.Num { value: 4 }, +}; +print(eval(e)); // -20 ``` -Fields are read-only, defaults and spread work as for structs, and -`Expr.Num(obj)` converts. An enum with such variants has no ordinals: -`values()`, `Expr(n)` and `int(v)` are a `TypeError`. +Fields work as in a [struct](structs.md): they are read-only, defaults +and spread work, and `Expr.Num(obj)` converts an object. An enum that has +variants with fields has no numbers, so `values()`, `Expr(n)` and +`int(v)` are a `TypeError`: ```rune enum Expr { Num { value }, Zero } -print(Expr.Num); // -Expr.values(); // TypeError: Expr has variants with fields; values(), Expr(n) and int() are for enums without. +Expr.values(); // TypeError: Expr has variants with fields; values(), Expr(n) and int() are for enums without. ``` -## Matching every variant +## Matching Every Variant -A `match` that names variants of an enum and has no catch-all arm must -cover them all: a variant is covered by an arm without a guard whose -pattern is the variant, `_ is Enum.Variant`, or `Enum.Variant { ... }` -binding its fields. A missing one is a compile error. +A `match` that names variants of an enum, and has no arm that matches +everything, must cover all of them. A variant counts as covered by an +arm without a guard whose pattern is the variant itself, +`_ is Enum.Variant`, or `Enum.Variant { ... }`. A missing one is a +compile error that names it: ```rune enum Shape { Circle { r }, Square { side }, Dot } fun area(s) { - return match s { - Shape.Circle { r } => 3 * r * r, + match s { + Shape.Circle { r } => math.PI * r * r, Shape.Square { side } => side * side, - Shape.Dot => 0, - }; -} - -print(area(Shape.Square { side: 2 })); // 4 + } +} // Error at 'match': Match does not cover Shape.Dot; add arms or '_ =>'. ``` -```rune -enum Shape { Circle { r }, Square { side }, Dot } -match Shape.Dot { Shape.Dot => print("dot") } // Error at 'match': Match does not cover Shape.Circle, Shape.Square; add arms or '_ =>'. -``` +This is the main reason to prefer an enum over strings: adding a variant +shows you every place that has to handle it. ## Methods -`impl` adds methods, as for a struct; `self` is the variant. Variants -are not changed in place, so methods cannot take `mut self`, nor share a -name with a field of a variant. +`impl` adds methods to an enum, as to a struct; `self` is the variant. +Variants never change in place, so methods cannot take `mut self`, and +they cannot share a name with a field of a variant. ```rune enum Side { White, Black } impl Side { fun other(self) { - return if self == Side.White { Side.Black } else { Side.White }; + if self == Side.White { Side.Black } else { Side.White } } + fun parse(s) { - return if s == "w" { Side.White } else { Side.Black }; + match s { + "w" => Side.White, + "b" => Side.Black, + _ => throw ValueError { message: "unknown side '{s}'" }, + } } } -print(Side.White.other()); // Side.Black -print(Side.parse("b")); // Side.Black -print(Side.values().map(Side.other)); // [Side.Black, Side.White] +print(Side.White.other()); // Side.Black +print(Side.parse("b")); // Side.Black +print(Side.values().map(Side.other)); // [Side.Black, Side.White] ``` -An enum is no struct, so `Color { }` is an error. A variant cannot be -named `values` or `name`, nor can a method taking `self`. +An enum is not a struct, so `Side {}` is an error. No variant, and no +method taking `self`, may be named `values` or `name`. diff --git a/docs/src/data/map-and-set.md b/docs/src/data/map-and-set.md index 20565ca..522f1a0 100644 --- a/docs/src/data/map-and-set.md +++ b/docs/src/data/map-and-set.md @@ -1,29 +1,45 @@ # Map and Set -A map holds values by key, a set unique values. Unlike an object, whose -keys are strings, their keys may be any hashable value; like an object, -they keep keys in the order they were first added. Like every value, a map -or a set is [copied](../language/values.md#copies) where it goes. +A **map** stores values by key; a **set** stores unique values. Use a map +to count, group or index things, and a set to remember what you have seen. + +Both differ from an object in two ways: their keys may be any hashable +value, not just strings, and they are built up at run time rather than +written out field by field. Like an object, they keep keys in the order +they were first added. ```rune let mut stock = map(); stock["apple"] = 3; stock["pear"] = 0; -print(stock["apple"]); // 3 -print(stock); // map {"apple": 3, "pear": 0} +print(stock["apple"]); // 3 +print(stock); // map {"apple": 3, "pear": 0} let mut visitors = set(); visitors.add("ann"); visitors.add("bob"); visitors.add("ann"); -print(visitors); // set {"ann", "bob"} -print(visitors.len()); // 2 +print(visitors); // set {"ann", "bob"} +print(visitors.len()); // 2 +``` + +A classic use: counting words. + +```rune +let words = "the cat saw the dog and the cat".split(" "); + +let mut counts = map(); +for w in words { + counts[w] = (counts?.[w] ?? 0) + 1; +} +print(counts); // map {"the": 3, "cat": 2, "saw": 1, "dog": 1, "and": 1} ``` -## Making one +## Making One -`map()` makes an empty map and `map(src)` one from an object, a struct, another map -or an array of `[key, value]` pairs; `set()` and `set(array)` likewise. +`map()` makes an empty map. `map(src)` makes one from an object, a struct, +another map, or an array of `[key, value]` pairs. `set()` and `set(array)` +work the same way; duplicates in the array are dropped. ```rune print(map({ host: "localhost", port: 8080 })); // map {"host": "localhost", "port": 8080} @@ -33,10 +49,15 @@ print(set(["a", "b", "a"])); // set {"a", "b"} ## Keys -A key is any hashable value: `nil`, a boolean, a number (`1` and `1.0` are -one key; `NaN` is none), a string, bytes, a function, a struct type, or a -struct whose fields are hashable, compared by value. A struct makes a -natural composite key: +A key may be any hashable value: + +- `nil` and booleans; +- numbers, where `1` and `1.0` are the same key and `NaN` cannot be one; +- strings and bytes; +- functions and struct types; +- struct values whose fields are all hashable, compared by value. + +A struct makes a natural composite key, such as a grid position: ```rune struct Pos { x, y } @@ -47,63 +68,90 @@ print(grid[Pos { x: 0, y: 1 }]); // wall print(grid?.[Pos { x: 9, y: 9 }] ?? "floor"); // floor ``` -An array, object, map or set is not hashable, as it can change: +Arrays, objects, maps and sets cannot be keys. To key by a pair of values, +use a struct as above. ```rune let mut seen = map(); seen[[1, 2]] = true; // TypeError: Cannot use an array as a key. ``` -## Reading and writing +## Reading and Writing + +`m[k]` reads a key; a missing key is a `KeyError`. `m?.[k]` gives `nil` +instead, so `m?.[k] ?? fallback` reads with a default. `m[k] = v` adds or +replaces a key, which needs `m` to be mutable. -`m[k]` reads a key and a missing one is a `KeyError`; `m?.[k]` gives `nil` -instead, so `m?.[k] ?? fallback` reads with a default. `m[k] = v` sets -one, like an array element, so `m` must be mutable. +```rune +let prices = map({ apple: 1.5 }); +print(prices?.["kiwi"]); // nil +print(prices?.["kiwi"] ?? 0); // 0 +``` ```rune -let mut prices = map({ apple: 1.5 }); -print(prices?.["kiwi"]); // nil -print(prices?.["kiwi"] ?? 0); // 0 -print(prices["kiwi"]); // KeyError: Key not found: "kiwi". +let prices = map({ apple: 1.5 }); +print(prices["kiwi"]); // KeyError: Key not found: "kiwi". ``` -Map methods: `delete(k)` (whether it was there), `clear()`, and `keys()`, -`values()`, `entries()`, new arrays. Like an array's in-place methods, -`clear` returns `nil`. +A value stored in a map can be changed in place through its key: ```rune -let mut stock = map(); -stock["apple"] = 3; -stock["pear"] = 0; -stock["plum"] = 7; - -print("pear" in stock); // true -print(stock.delete("pear")); // true -print(stock.delete("pear")); // false -print(stock.keys()); // ["apple", "plum"] -print(stock.values()); // [3, 7] -print(stock.entries()); // [["apple", 3], ["plum", 7]] +let mut groups = map(); +groups["admins"] = ["ann"]; +groups["admins"].push("bob"); +print(groups); // map {"admins": ["ann", "bob"]} ``` -A set has `add(x)`, `delete`, `clear`, and `union(s)`, `intersection(s)`, -`difference(s)`, new sets; `[...s]` is its elements as an array. `k in m` tests -a key of a map and `x in s` an element of a set. +## Map Methods + +- `k in m` — whether the key is there; +- `delete(k)` — removes a key and returns whether it was there; +- `clear()` — removes every key; +- `keys()`, `values()`, `entries()` — new arrays, in insertion order; +- `len()` — the number of keys. + +```rune +let mut stock = map({ apple: 3, pear: 0, plum: 7 }); + +print("pear" in stock); // true +print(stock.delete("pear")); // true +print(stock.delete("pear")); // false +print(stock.keys()); // ["apple", "plum"] +print(stock.values()); // [3, 7] +print(stock.entries()); // [["apple", 3], ["plum", 7]] +print(stock.len()); // 2 +``` + +## Set Methods + +- `x in s` — whether the element is there; +- `add(x)`, `delete(x)`, `clear()` — change the set in place; +- `union(s)`, `intersection(s)`, `difference(s)` — new sets; +- `len()` — the number of elements. ```rune let backend = set(["ann", "bob", "eve"]); let frontend = set(["bob", "kim"]); -print("eve" in backend); // true -print(backend.union(frontend)); // set {"ann", "bob", "eve", "kim"} -print(backend.intersection(frontend)); // set {"bob"} -print(backend.difference(frontend)); // set {"ann", "eve"} +print("eve" in backend); // true +print(backend.union(frontend)); // set {"ann", "bob", "eve", "kim"} +print(backend.intersection(frontend)); // set {"bob"} +print(backend.difference(frontend)); // set {"ann", "eve"} +``` + +`[...s]` turns a set into an array, which is the usual way to drop +duplicates while keeping the first-seen order: + +```rune +let ids = [3, 1, 3, 2, 1]; +print([...set(ids)]); // [3, 1, 2] ``` ## Iterating -`m.len()` counts the entries; `for k, v in m` walks a map's keys and values, -`for k in m` its keys, and `for x in s` or `for i, x in s` a set, always -in insertion order. +`for k, v in m` walks a map's keys and values, `for k in m` its keys +alone. `for x in s` walks a set, and `for i, x in s` numbers its elements. +The order is always insertion order. ```rune let stock = map({ apple: 3, plum: 7 }); @@ -114,7 +162,7 @@ for name, n in stock { // plum: 7 ``` -A loop walks the map or set as it was when the loop began, so the body +The loop walks the map or set as it was when the loop began, so the body may change it freely: ```rune @@ -122,20 +170,26 @@ let mut counts = map({ a: 1, b: 2 }); for k in counts { counts[k + "!"] = 0; } -print(counts); // map {"a": 1, "b": 2, "a!": 0, "b!": 0} +print(counts); // map {"a": 1, "b": 2, "a!": 0, "b!": 0} ``` -## Equality and conversion +## Equality and Conversion -`==` compares entries in any order. `[...s]` spreads a set into an array; -`json.stringify` writes a set as an array and a map of string keys as an -object, in order. +`==` compares maps and sets by their entries, in any order. ```rune -print(map({ a: 1, b: 2 }) == map({ b: 2, a: 1 })); // true +print(map({ a: 1, b: 2 }) == map({ b: 2, a: 1 })); // true +print(set([1, 2]) == set([2, 1])); // true +``` -let ids = set([3, 1, 2]); -print([...ids]); // [3, 1, 2] -print(json.stringify(ids)); // [3,1,2] -print(json.stringify(map({ a: 1 }))); // {"a":1} +`json.stringify` writes a set as an array, and a map with string keys as +an object, in insertion order. + +```rune +print(json.stringify(set([3, 1, 2]))); // [3,1,2] +print(json.stringify(map({ a: 1, b: 2 }))); // {"a":1,"b":2} ``` + +Like every value, a map or a set is [copied](../language/values.md#copies) +when assigned or passed; a function changes the caller's one only through +a [`mut` parameter](../language/functions.md#mut-parameters). diff --git a/docs/src/data/methods.md b/docs/src/data/methods.md index 0bbcbff..fdce9d3 100644 --- a/docs/src/data/methods.md +++ b/docs/src/data/methods.md @@ -1,22 +1,26 @@ # Methods -An `impl` block adds methods to a struct declared in the same file. A -method taking `self` first is called on an instance, `self` being the -instance; one without is static and called on the type. +An `impl` block attaches functions to a [struct](structs.md), so the +behavior lives next to the data it works on. A method whose first +parameter is `self` is called on an instance, and `self` is that +instance. A method without `self` is a static method, called on the +type itself; it is the usual place for constructors. ```rune struct Money { cents, currency = "USD" } impl Money { - fun of(amount, currency = "USD") { - return Money { cents: math.round(amount * 100), currency }; - } - fun plus(self, other) { - return Money { ...self, cents: self.cents + other.cents }; - } - fun format(self) { - return "%.2f %s".format(self.cents / 100, self.currency); - } + fun of(amount, currency = "USD") { + Money { cents: math.round(amount * 100), currency } + } + + fun plus(self, other) { + Money { ...self, cents: self.cents + other.cents } + } + + fun format(self) { + "%.2f %s".format(self.cents / 100, self.currency) + } } let price = Money.of(12.5); @@ -25,37 +29,47 @@ print(total.format()); // 13.49 USD print(price.format()); // 12.50 USD ``` -Impl blocks are top-level only, may come before the struct and there may be -several; a method cannot share a name with a field or another method of the -type. A static method is not reachable from an instance: +`Money.of` is static, `plus` and `format` are instance methods. Note that +`plus` does not change `price`: it returns a new `Money`. + +`impl` blocks are top-level only. They may come before the struct, and a +type may have several. A method cannot share its name with a field or +with another method of the type. + +A static method is called only on the type, never on an instance: ```rune struct Money { cents } + impl Money { - fun zero() { return Money { cents: 0 }; } + fun zero() { Money { cents: 0 } } } + Money.zero().zero(); // TypeError: 'zero' is a static method of Money; call it as Money.zero(). ``` -## Mutating methods +## Mutating Methods -`mut self` makes a mutating method, which can set the fields of `self` -(`self.x += 1`, `self["x"] = 1`), or `self` as a whole, as a mutable -variable can. Without `mut`, `self` is immutable. These methods are the -only place a struct's fields are set; see -[Setting fields](structs.md#setting-fields). +A method that takes `mut self` may change the instance: set its fields +(`self.balance += 1`, `self["x"] = 1`), change what they hold +(`self.items.push(x)`) or replace `self` as a whole. Without `mut`, +`self` is read-only. Mutating methods are the only place a struct's +fields can be set; see [Setting Fields](structs.md#setting-fields). ```rune struct Account { owner, balance = 0 } impl Account { - fun deposit(mut self, amount) { - self.balance += amount; - } - fun withdraw(mut self, amount) { - if amount > self.balance { throw ValueError { message: "insufficient funds" }; } - self.balance -= amount; - } + fun deposit(mut self, amount) { + self.balance += amount; + } + + fun withdraw(mut self, amount) { + if amount > self.balance { + throw ValueError { message: "insufficient funds" }; + } + self.balance -= amount; + } } let mut acc = Account { owner: "ann" }; @@ -64,69 +78,62 @@ acc.withdraw(30); print(acc.balance); // 70 ``` -`self` is the receiver itself, as a -[`mut` parameter](../language/functions.md#mut-parameters) is the -caller's variable: the method changes it in place, and it goes back where -the receiver was read from when the method returns or throws. A copy -taken before the call keeps its value. +The call changes the variable it was made on, as a +[`mut` parameter](../language/functions.md#mut-parameters) changes the +caller's variable. A copy taken before the call keeps the old value: + +```rune +struct Cart { items = [] } + +impl Cart { + fun add(mut self, item) { self.items.push(item); } +} + +let mut cart = Cart {}; +let before = cart; +cart.add("tea"); +cart.add("milk"); +print(cart.items); // ["tea", "milk"] +print(before.items); // [] +``` + +If a mutating method throws, whatever it changed before the throw stays +changed. So check first and change after, as `withdraw` does; then a +failed call leaves the instance as it was: ```rune struct Account { owner, balance = 0 } + impl Account { - fun deposit(mut self, amount) { self.balance += amount; } - fun withdraw(mut self, amount) { - if amount > self.balance { throw ValueError { message: "insufficient funds" }; } - self.balance -= amount; - } + fun withdraw(mut self, amount) { + if amount > self.balance { + throw ValueError { message: "insufficient funds" }; + } + self.balance -= amount; + } } let mut acc = Account { owner: "ann", balance: 50 }; -let before = acc; -acc.deposit(10); -print(acc.balance); // 60 -print(before.balance); // 50 try { acc.withdraw(1000); } catch e { - print(e.message); // insufficient funds + print(e.message); // insufficient funds } -print(acc.balance); // 60 +print(acc.balance); // 50 ``` -A method that throws keeps what it changed before the throw, so check -first and change after, as `withdraw` does. +### Where a Mutating Method Can Be Called -The fields' containers are part of the struct too: - -```rune -struct Cart { items = [] } -impl Cart { - fun add(mut self, x) { self.items.push(x); } -} - -let mut cart = Cart {}; -let before = cart; -cart.add("tea"); -print(before.items); // [] -print(cart.items); // ["tea"] -``` - -The receiver must be a mutable variable, or an element, property or -field of a value one holds; through an immutable variable, or on a -struct literal or conversion, the call is a compile error. A struct in a -field of another struct is such a receiver only in the outer struct's -own `mut self` methods, as `self.pos.move(1)`; see -[Setting fields](structs.md#setting-fields). A method called as a value, -as `Account.deposit`, takes no receiver to write back, so calling it is -a `TypeError`. On another -value it is a runtime error, or a compile error when no method of that -name but a mutating one exists. +The receiver must be something that can be changed: a `let mut` +variable, or an element, property or field reached from one. That +includes structs stored in arrays and objects: ```rune struct Account { owner, balance = 0 } + impl Account { - fun deposit(mut self, amount) { self.balance += amount; } + fun deposit(mut self, amount) { self.balance += amount; } } let mut accounts = [Account { owner: "ann" }, Account { owner: "bob" }]; @@ -134,10 +141,14 @@ accounts[1].deposit(25); print(accounts[1]); // Account {owner: "bob", balance: 25} ``` +On an immutable variable, a struct literal or the result of a call, there +is nothing to write the change back to, so it is a compile error: + ```rune struct Account { owner, balance = 0 } + impl Account { - fun deposit(mut self, amount) { self.balance += amount; } + fun deposit(mut self, amount) { self.balance += amount; } } let acc = Account { owner: "ann" }; @@ -146,24 +157,32 @@ acc.deposit(10); // Error at 'acc': Cannot mutate immutable variable 'acc'. ```rune struct Account { owner, balance = 0 } + impl Account { - fun deposit(mut self, amount) { self.balance += amount; } + fun deposit(mut self, amount) { self.balance += amount; } } Account { owner: "ann" }.deposit(10); // Error at 'deposit': Cannot call mutating method 'deposit' of Account: the receiver is not a mutable variable, element or property. ``` -## Methods as values +A struct held in a field of another struct can be changed only from the +outer struct's own `mut self` methods, as in `self.pos.move(1)`; see +[Setting Fields](structs.md#setting-fields). + +## Methods as Values -`acc.format` without a call is the method bound to `acc`, a function taking -the rest of the arguments; `Money.format` is the plain function, taking the -instance first, so `prices.map(Money.format)` works. A mutating method -cannot be taken as a value. +A method can be passed around like any function: + +- `price.format`, without a call, is the method bound to `price`: a + function that takes the remaining arguments; +- `Money.format` is the plain function, which takes the instance as its + first argument. It fits straight into `map` and friends. ```rune struct Money { cents } + impl Money { - fun format(self) { return "$%.2f".format(self.cents / 100); } + fun format(self) { "$%.2f".format(self.cents / 100) } } let prices = [Money { cents: 499 }, Money { cents: 1250 }]; @@ -173,50 +192,73 @@ let show = prices[0].format; print(show()); // $4.99 ``` -## Functions in fields +A mutating method has no variable to write back to when used as a value. +Taking a bound one, `acc.deposit`, is a `TypeError`, and so is calling +`Account.deposit` through `map` or another callback. + +## Functions in Fields -`x.f(args)` always calls a method. A function held in a field is called -as `(x.f)(args)`, or `x["f"](args)`: +A struct field can hold a function. Since `x.f(args)` always calls a +method, call a function stored in a field as `(x.f)(args)` or +`x["f"](args)`: ```rune struct Button { label, onClick } + let save = Button { label: "save", onClick: () => "saved" }; -print((save.onClick)()); // saved +print((save.onClick)()); // saved print(save["onClick"]()); // saved -save.onClick(); // TypeError: Button has no method 'onClick'; call the function in its field as (x.onClick)(). ``` -An object holds data only: a function as the value of one of its -properties is an error. Behavior belongs to a struct and its `impl`; a -table of functions by name is a [map](map-and-set.md): +```rune +struct Button { label, onClick } + +let save = Button { label: "save", onClick: () => "saved" }; +save.onClick(); // TypeError: Button has no method 'onClick'; call the function in its field as (x.onClick)(). +``` + +Plain objects hold data only, so a function cannot be the value of an +object property. Put behavior in a struct and its `impl`. For a lookup +table of functions by name, use a [map](map-and-set.md): ```rune -let handlers = { greet: name => "hi " + name }; // Error at 'greet': Property 'greet' of an object cannot hold a function. +let greeters = map([ + ["en", name => "hello, " + name], + ["es", name => "hola, " + name], +]); + +print(greeters["es"]("ann")); // hola, ann +``` -let greeters = map([["greet", name => "hi " + name]]); -print(greeters["greet"]("ann")); // hi ann +```rune +let handlers = { greet: name => "hi " + name }; // Error at 'greet': Property 'greet' of an object cannot hold a function. ``` -Members of a namespace, as in `math.floor(x)`, are no methods and are -called as they are. +Functions of a namespace, such as `math.floor(x)` or `fs.join(a, b)`, are +not methods; they are plain functions grouped under a name. -## Methods on built-in types +## Methods on Built-in Types -`impl` also takes the built-in types `string`, `number`, `boolean`, -`array`, `object`, `function`, `map`, `set`, `bytes` and `stream`. Their methods must take `self`, not -`mut self`, and are seen by the whole program; a method of the program -wins over a built-in one. -Built-in structs, such as `IOError`, take no methods. +`impl` also works on the built-in types `string`, `number`, `boolean`, +`array`, `object`, `function`, `map`, `set`, `bytes` and `stream`. This +lets you add the helpers your program keeps needing: ```rune impl string { - fun shout(self) { return self.upper() + "!"; } + fun shout(self) { self.upper() + "!" } } impl array { - fun sum(self) { return self.reduce((a, b) => a + b, 0); } + fun sum(self) { self.reduce((a, b) => a + b, 0) } + fun average(self) { self.sum() / self.len() } } -print("hi".shout()); // HI! -print([3, 4, 5].sum()); // 12 +print("hi".shout()); // HI! +print([3, 4, 5].sum()); // 12 +print([3, 4, 5, 8].average()); // 5 ``` + +Methods on built-in types take `self`, never `mut self`, and are visible +to the whole program. If one has the same name as a built-in method, the +program's own wins. Built-in structs, such as `IOError`, cannot get +methods. diff --git a/docs/src/data/structs.md b/docs/src/data/structs.md index 462ce3a..d83cfd8 100644 --- a/docs/src/data/structs.md +++ b/docs/src/data/structs.md @@ -1,33 +1,59 @@ # Structs -A struct is a named record with a fixed set of fields. Fields without a -default are required. Structs are declared at the top level only and can -be used before their declaration. +A struct is a named record with a fixed set of fields. Use one when a +value has a known shape, such as a user, an order or a config: the +compiler checks field names in literals, the type can be tested with +`is` and matched in [patterns](../language/pattern-matching.md#structs), +and [methods](methods.md) can be attached to it. ```rune struct User { name, role = "member", tags = [] } let ann = User { name: "ann" }; -print(ann); // User {name: "ann", role: "member", tags: []} -print(ann.name); // ann -print(ann["role"]); // member +print(ann); // User {name: "ann", role: "member", tags: []} +print(ann.name); // ann +print(ann["role"]); // member +``` + +A field with a default, `role = "member"`, may be left out of a literal; +a field without one is required. Structs are declared at the top level +only and can be used before their declaration. + +When a variable has the same name as a field, write it once: +`User { name }` is short for `User { name: name }`. + +```rune +struct User { name, role = "member" } let name = "bob"; -print(User { name, role: "admin" }); // User {name: "bob", role: "admin", tags: []} +let role = "admin"; +print(User { name, role }); // User {name: "bob", role: "admin"} ``` -`User { name }` is shorthand for `User { name: name }`. +## Defaults + +A default must be a constant: a literal or operators on literals +(`60 * 60`), a [`const`](../language/variables.md#constants), a variant +of an [enum](enums.md) in the same file, an array or object of these, +`map()` or `set()`. -A default is a constant: a literal or operators on literals (`60 * 60`), a -[`const`](../language/variables.md#constants), a variant of an -[enum](enums.md) of the file, an array or object of them, `map()` or -`set()`. Like every value it is [copied](../language/values.md#copies), so -`tags = []` is never shared: +```rune +const DAY = 24 * 60 * 60; + +struct Session { user, ttl = DAY, scopes = ["read"] } + +print(Session { user: "ann" }); // Session {user: "ann", ttl: 86400, scopes: ["read"]} +print(Session { user: "bob", scopes: ["admin"] }); // Session {user: "bob", ttl: 86400, scopes: ["admin"]} +``` + +Like every value in Rune, a default is [copied](../language/values.md#copies), +so two structs never share the same `[]`: ```rune struct User { name, tags = [] } + impl User { - fun tag(mut self, t) { self.tags.push(t); } + fun tag(mut self, t) { self.tags.push(t); } } let mut ann = User { name: "ann" }; @@ -37,8 +63,10 @@ print(ann.tags); // ["admin"] print(bob.tags); // [] ``` -A field that does not exist, or a required one left out, is a compile -error in a literal: +## Typos Are Caught Early + +A misspelled or unknown field, or a required one left out, is a compile +error in a literal, so the program does not even start: ```rune struct User { name, role = "member" } @@ -50,7 +78,7 @@ struct User { name, role = "member" } User { role: "admin" }; // Error at 'User': Missing field 'name' of User. ``` -Reading a field that does not exist is a runtime error: +Reading a field that does not exist fails when it runs: ```rune struct User { name, role = "member" } @@ -58,20 +86,17 @@ let ann = User { name: "ann" }; print(ann.email); // KeyError: User has no field 'email'. ``` -## Setting fields +## Setting Fields -Fields are read-only outside the struct's own -[mutating methods](methods.md#mutating-methods): only `self.x = ...` (or -`self["x"]`, `+=`, `++`, ...) in a `mut self` method sets one. Anywhere -else setting a field of a struct, through a variable, an element or -another struct's field, is a runtime error. To change a struct from -outside, call one of its `mut self` methods or make an updated copy -with [spread](#updating-with-spread). +A struct guards its own data: its fields are set only inside its +[mutating methods](methods.md#mutating-methods), those that take +`mut self`. To change a struct, call one of them: ```rune struct User { name, role = "member" } + impl User { - fun promote(mut self, role) { self.role = role; } + fun promote(mut self, role) { self.role = role; } } let mut ann = User { name: "ann" }; @@ -83,17 +108,18 @@ team[0].promote("lead"); print(team[0].role); // lead ``` +Setting a field anywhere else, through a variable, an array element or +another struct, is an error: + ```rune struct User { name, role = "member" } let mut ann = User { name: "ann" }; ann.role = "admin"; // TypeError: Cannot set field 'role' of User outside its mut self methods. ``` -A struct owns its fields, and what they hold: an array, object, map or -set in a field, or another struct, is part of it. Its `mut self` methods -change them in place (`self.tags.push(x)`, `self.pos.x = 1`, -`self.pos.move(1)`); anywhere else that is the same error as setting the -field. +A struct also owns what its fields hold. An array, object, map, set or +another struct in a field is part of it, so changing it in place, +`ann.tags.push(x)`, counts as setting the field: ```rune struct User { name, tags = [] } @@ -101,30 +127,36 @@ let mut ann = User { name: "ann" }; ann.tags.push("x"); // TypeError: Cannot set field 'tags' of User outside its mut self methods. ``` -## Updating with spread +Inside a `mut self` method all of this is allowed: `self.tags.push(x)`, +`self.pos.x = 1`, `self.pos.move(1)`. -A literal may spread a struct of the same type, as `T { ...t, x: 1 }` -does an update without changing `t`. Items apply in order, later ones -winning. Spreading anything else, an object or a struct of another type, -is a runtime error; an object becomes a struct by -[conversion](#converting). +## Updating with Spread + +To get a changed copy without touching the original, spread the struct +into a new literal of the same type and list the fields to change: +`Config { ...base, debug: true }`. Items apply in order, so later ones +win. ```rune struct Config { host, port = 8080, debug = false } let base = Config { host: "localhost" }; -print(Config { ...base, debug: true }); // Config {host: "localhost", port: 8080, debug: true} -print(Config { debug: true, ...base }); // Config {host: "localhost", port: 8080, debug: false} -print(base); // Config {host: "localhost", port: 8080, debug: false} +let dev = Config { ...base, debug: true }; +let prod = Config { ...base, host: "example.com", port: 443 }; + +print(dev); // Config {host: "localhost", port: 8080, debug: true} +print(prod); // Config {host: "example.com", port: 443, debug: false} +print(base); // Config {host: "localhost", port: 8080, debug: false} ``` +Only a struct of the same type can be spread into a literal; an object +or another struct type is a runtime error. Use a +[conversion](#converting) to turn an object into a struct. + ## Converting -Calling a struct type converts to it. From an object the keys must be -exactly the fields, the defaulted ones optional; a struct of the same -type is returned as is, and any other value is an error. There are no -implicit conversions, and none between struct types. This is how data -from `json.parse` becomes a struct: +Calling a struct type converts a value to it. This is how data from +`json.parse` becomes a struct: ```rune struct Config { host, port = 8080 } @@ -134,6 +166,11 @@ print(cfg); // Config {host: "example.com", port: 8080} print(cfg.port); // 8080 ``` +The object's keys must be exactly the struct's fields; fields with +defaults may be left out. A struct of the same type is returned as is. +Anything else is an error: there are no implicit conversions, and none +between different struct types. + ```rune struct Config { host, port = 8080 } Config({ host: "example.com", timeout: 5 }); // KeyError: Config has no field 'timeout'. @@ -144,15 +181,14 @@ struct Config { host, port = 8080 } Config({ port: 80 }); // KeyError: Missing field 'host' of Config. ``` -## Type checks, equality, fields +## Type Tests and Equality -`v is User` is `true` only for a `User`, never for an object; see +`v is User` is `true` only for a `User`, never for an object that +happens to have the same keys; see [Type Tests](../language/values.md#type-tests). -`==` compares structs field by field and only if they are of the same -struct, so a struct never equals an object. `{ ...s }` copies a struct -into a new object, its fields in declaration order, to walk them or -count them. +`==` compares two structs of the same type field by field. A struct +never equals an object or a struct of another type. ```rune struct User { name, role = "member" } @@ -162,6 +198,16 @@ print(ann is User); // true print({ name: "ann" } is User); // false print(ann == User { name: "ann" }); // true print(ann == { name: "ann", role: "member" }); // false +``` + +## Walking the Fields + +`{ ...s }` copies a struct into a plain object, its fields in +declaration order. Use it to loop over the fields or count them: + +```rune +struct User { name, role = "member" } +let ann = User { name: "ann" }; for field, value in { ...ann } { print("{field}: {value}"); @@ -169,6 +215,5 @@ for field, value in { ...ann } { // name: ann // role: member -print({ ...ann }); // {name: "ann", role: "member"} print({ ...ann }.len()); // 2 ``` diff --git a/docs/src/errors-and-exit-codes.md b/docs/src/errors-and-exit-codes.md index 138619e..2aa0ebb 100644 --- a/docs/src/errors-and-exit-codes.md +++ b/docs/src/errors-and-exit-codes.md @@ -1,33 +1,18 @@ # Errors and Exit Codes -Errors name the file, line and column, show the source with the offending -token underlined, and, when the cause is certain, a hint on how to fix it. -On a terminal they are colored; set `NO_COLOR` to turn that off. A runtime -error also lists the calls it unwound through: +When something goes wrong, Rune tells you where and why. Every error names +the file, line and column, shows the surrounding source with the offending +token underlined, and, when the cause is certain, adds a hint on how to +fix it. On a terminal the report is colored; set `NO_COLOR` to turn that +off. -```rune -fun total(order) { - return order.price * order.qty; -} +Rune finds errors at two moments: when it compiles the program, before any +of it runs, and while it runs. -let orders = [{ price: 10, qty: 2 }, 5]; -print(orders.map(total)); -``` +## Compile Errors -``` -TypeError: Cannot read property 'price' of number. - --> main.rn:2:18 - | -1 | fun total(order) { -2 | return order.price * order.qty; - | ^^^^^ - - at total (main.rn:2) - at array.map (native) - at