Dino compiler: language, formatter, language server, docs, editor support

Compiler in Rust (lexer, parser, checker, C codegen), maps, chars,
dino fmt, dino lsp (diagnostics, formatting, outline, definition,
hover, completion, signature help), docs, examples, VS Code/Vim files.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Your NameandClaude Sonnet 5.5 committed 2026-11-07 23:46:12 +01:00
1 parent 3e2779f447
commit eaf9567a36
117 files changed
+19970

No files matched your search

+1
View File
@@ -0,0 +1 @@
target/
Generated
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "dino"
version = "0.1.0"
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "dino"
version = "0.1.0"
edition = "2021"
description = "The Dino programming language compiler"
[dependencies]
+213
View File
@@ -0,0 +1,213 @@
# Dino language spec (draft)
Goal: Go-like simplicity, C++/Rust speed, no GC, no low-level syntax.
Targets: game dev, CLI tools, desktop apps.
## Decisions
- **Methods**: declared inside the struct body. Fields are accessed directly
(`self` available for the whole value). No receiver, no `mut` keyword:
the compiler infers whether a method mutates.
- **Variables**: `var x = 1` creates a changeable variable (type inferred;
`var x: int = 1` with a type). `x = 2` changes it. `const X = 1` is fixed.
- **Types are written after a colon**, everywhere: `var x: int = 1`,
`func area(w: float, h: float): float`, `struct User { name: string, age: int }`,
enum data `Circle(r: float)`, generic bounds `[T: Ordered]`, several results `func f(): (int, error)`.
Names in a row share a type: `(a, b: int)`, `x, y: float`. Without a colon
the compiler explains what to add.
- **Sized numbers**: `i8 i16 i32 u8 u16 u32 u64 f32`; `i64` is `int` and `f64` is
`float` (same type). A number literal takes the type asked for (`var x: u8 = 200`,
`b + 1`, `[1, 2]` as `[]u8`) and a literal that doesn't fit is an error. Different
number types never mix: convert with `u8(x)`, `f32(x)`, `int(x)`, ... Integers wrap
around on overflow; float to integer stops at the nearest end (NaN is 0). Dividing by
zero panics. Unsigned values can't be negated. `f32` prints the shortest text that
reads back the same.
- **Sharing**: `shared T` (reference counted), `weak T` (non-owning).
Everything else is plain ownership, inferred by the compiler.
- **Errors**: Go-style `(value, error)` returns, with `?` to propagate.
- **Missing values**: `T?` with `nil`. Compiler requires a nil check before use.
- **Strings**: interpolation with `"Hello {name}"`; literal brace is `\{`.
- **Visibility**: private by default, `pub` makes it public.
- **Loops**: `for` only: `for i in 0..10`, `for x in items`, `for cond { }`,
`for { }` (infinite), with `step` for strides. No C-style three-part loop.
- **Numbers**: `int` (64-bit) and `float` (64-bit) for everyday code; sized
types `i8 i16 i32 i64 u8 u16 u32 u64 f32 f64` when exact control is needed.
`var a = 42` is `int`, `var b = 3.14` is `float`.
- **print**: `print(a, b, c)` writes values separated by spaces, then a newline.
- **Conversions**: no implicit int/float mixing, except that an integer
literal fits a float (`var x: float = 1`, `x * 2`). Use `int(x)` / `float(x)`.
- **Integer overflow** wraps around; `/` and `%` by zero panic (exit code 2).
- **Evaluation order** is left to right, always (arguments, `&&`/`||` short-circuit).
- **Top-level `const`** may not call functions; uses are replaced by the value.
- **Structs are values**: `var b = a` copies; passing to a function copies.
Methods go inside the struct and see fields directly; `self` is the whole value.
Inside a method, a name resolves as: local/parameter, then field, then method
of the same struct (call it bare: `update(dt)`), then global function/const.
- **Mutation is inferred**: a method that assigns to a field (or calls a mutating
method on `self`) is mutating. Mutating methods can't be called on a `const`
or on a temporary like `make().update()`.
- **Struct literals**: positional `Vec2{1, 2}` needs every field; named
`Player{name: "A"}` may leave fields out (they start at zero: 0, 0.0, false, "").
Initializers run in the order written.
- **Printing a struct** shows `Vec2{x: 1.0, y: 2.0}`. `==` on structs is not
allowed yet; compare fields.
- **Lists** `[]T`: `[1, 2, 3]`, `var xs: []int` (empty), `xs[i]`, `xs[i] = v`,
`xs.len()`, `xs.push(v)`, `xs.pop()`, `xs[1..3]` (a copy), `for x in xs`,
`for i, x in xs`. Lists are values: `var b = a` and passing to a function
copy. A function that never changes a list parameter gets it without a copy
(the compiler works this out); returning a local list moves it.
Looping walks the list as it was when the loop started. `print` shows `[1, 2]`.
Out-of-range index/slice and `pop()` on an empty list panic (exit code 2).
`s.len()` on a string is its length in bytes.
- **Enums** carry data per case: `enum Shape { Circle(r float) Rect(w, h float) Point }`,
with methods inside, like structs. Build a value with the qualified name:
`Shape.Circle(2.0)`, `Shape.Point`. Enums are values (copied like structs); a
case may hold lists. The zero value is the first case. Printing shows
`Shape.Circle(2.0)`. `==` works on enums whose cases carry no data.
An enum can't contain itself directly, but may hold a list of itself.
- **match** is exhaustive: missing cases are a compile error (the message lists
them); `_` covers the rest. Works on enums, int, bool, string.
Patterns: `Circle(r)`, `Rect(w, _)`, `Point`, `Shape.Point`, literals, `_`, or a
lowercase name that takes the whole value. A capitalized name that isn't a case
is an error (never a silent catch-all). Nested patterns come later.
As a statement, arms may be blocks (and may `break`/`continue`/`return`).
As a value (`var x = match ...`, `return match ...`), every arm is a single
expression, or a lone `return`/`break`/`continue`. Arms of a value `match` must
have the same type.
- **Errors**: `error` is a built-in type: nil (no error) or a message. Make one with
`error("msg {x}")`; print it or use it in `"{err}"` (nil prints `nil`).
A function may return several values: `func f(): (int, error)`; take them with
`var n, err = f()` (`_` throws one away). `return v, nil` or the shorthand
`return error("x")` (zero values are filled in). The error ignored by a bare
`f()` statement is a compile error.
`call()?` passes the error up: on error the enclosing function returns it (zero
values for the rest), otherwise `?` gives the value. Needs a function whose last
result is `error`; works on `(T, error)` and `error` calls.
`func main(): error` is allowed: an error prints `error: msg` to stderr, exit code 1.
- **Optionals**: `T?` holds a `T` or `nil`. A `T` converts to `T?` implicitly.
Compare with `x == nil` / `x != nil`. To use the value, check first: the compiler
knows `x` is set inside `if x != nil { }`, after `if x == nil { return }` (or
break/continue), and on the right of `x != nil &&` / `x == nil ||`. Assigning to
`x` forgets that. (Reads are also checked at runtime, so it can never go wrong.)
Not yet: `T?` as a struct field / enum data / list element, `??`, `x!`, `match` on nil,
`?` on optionals.
- **Last use moves**: `var b = a` copies `a`, unless `a` is never used again (and no loop
is in the way): then `b` takes the value and nothing is copied (`src/moves.rs`).
- **Generic functions**: `func max[T: Ordered](a, b: T): T`. The types are worked out from the
arguments (`max(3, 9)`, `first(["a"])`; bare number literals become `int`, or `float` if any is
a float); there is no `max[int](...)` yet. Each set of types gets its own compiled copy, so
generics cost nothing at runtime. Rules after the colon: `Ordered` (numbers and strings) and
`Number`; no rule means anything goes, and a mistake then shows up when the copy is checked
(the message names the types). A generic function that is never used is not checked.
A generic function needs a parameter that mentions its type.
- **Interfaces** are rules for generics, Go-style: no `implements`. A type follows an
interface just by having its methods with the same parameters and result:
`interface Shape { area(): float name(): string }`, then `func show[T: Shape](s: T)`
(also `struct Gallery[T: Shape]`, `[T: m.Shape]` from another file). A type that doesn't
gets a message naming the missing or different method. Generic code may call the methods
the interface lists even if they are private in another file.
- **Interface values**: an interface is also a type: `var s: Shape = Circle{2.0}`, `[]Shape`,
`func f(s: Shape)`, struct fields, results. A struct or enum value with the right methods
converts automatically (the value is copied into the interface value), and `s.area()` calls
the method of whatever is inside. Interface values are values like any other: `var t = s`
copies the inside, and a method that changes the value (`s.scale(2.0)`) changes only that
variable's copy. `nil` is the empty interface value (`s == nil`); calling a method on it
panics (exit code 2). A list can mix types: `var xs: []Shape = [Circle{1.0}, Rect{2.0, 3.0}]`.
Printing shows the value inside. Not yet: turning an interface value back into its type,
one interface value used as another interface, interfaces with type parameters.
Interfaces can't take type parameters yet.
- **Generic structs and enums**: `struct Stack[T] { items: []T func push_item(x: T) { items.push(x) } }`,
`enum Maybe[T] { Some(value: T) None }`. Use them with the types written out:
`Stack[int]{}`, `var s: Stack[string]`, `Pair[string, float]{"pi", 3.14}`,
`Maybe[int].Some(3)`, `func f(): Maybe[int]`, and from another file `m.Stack[int]{}`.
The types are never guessed (`Stack{}` is an error). Like functions, each list of types
becomes its own type (`Stack[int]` prints with its types), rules `[T: Number]` work, and
they may contain themselves through lists (`kids: []Tree[T]`). A capitalized name followed
by `[types]` and then `{` or `.` is read as a generic type, anything else as indexing.
A generic type that is never used is not checked.
- **Shared values**: `var tex = shared Texture{...}` makes one value with a counter. `var b = a`,
passing it, putting it in a list or a struct field all give another owner (no copy of the value);
the value is freed when the last owner goes. Use it like the thing inside: `tex.name`,
`tex.touch()`, `tex.uses = 1`, `match light { ... }`. A change through any owner is seen
by all. Only structs and enums can be shared for now. Written as a type: `shared Texture`.
A shared value is not copied by `var b = a`, so two owners really are one value.
- **Weak pointers**: `weak win` gives a non-owning pointer to a shared value (type `weak Window`;
`weak Window?` means the same). It doesn't keep the value alive, so a window and its buttons
can point at each other without leaking (the button's side is `weak`). `w == nil` /
`w != nil` tell whether the value is still there; using a weak pointer whose value is gone
(or that was never set) panics with a clear message (exit code 2). A weak pointer starts
as `nil` (`Button{label: "x"}`) and can be assigned `nil`. To use the value as an owner, `w.upgrade()` gives a `shared T?`: the shared
value (now with one more owner, so it stays alive while you hold it) or `nil` if it is gone.
Not yet: `==` between shared values (identity), shared lists/strings/numbers.
- **Function values and closures**: the type is `func(int, string): bool` (no `: result` means
nothing is returned). Write one as `func(x: int): int { return x + 1 }`, or short as
`x => x + 1` / `(a, b) => a + b` where the types are known from the place it is used
(a parameter, a typed variable, a return, a struct field) or, for a generic function,
from its other arguments (`map(nums, x => x * 2)`). A top-level function is a value too:
`apply(double, 4)`. Call a function value like a function: `f(3)`, `b.on_click(name)`,
`make()(3)`. A closure **copies** the variables it uses when it is made and keeps its own copies
(so it can count: `n += 1` inside changes only its copy, which persists between calls).
Copying a closure (`var g = f`, passing it) copies its state too. Calling a function value
counts as changing it, like a method that changes `self`. A function value that was never
set panics when called (exit code 2). Not yet: closures with block bodies in short form,
methods as values, several results from a function value, `==` on functions.
- **Memory**: no GC, nothing to write. Every value has exactly one owner and is
freed when its owner's block ends (also on early `return`, `break`, `continue`
and `?`). Lists, structs, enums, optionals, errors and strings all follow this.
Assigning or passing a variable copies it (`var b = a`); a fresh value (a call
result, a literal) or a returned local moves without copying. Strings are
immutable and counted, so copying one only bumps a counter; literals are never
freed. A parameter that the function doesn't change is passed by address, so
passing lists around costs nothing. Every test program runs under the address
sanitizer, so a leak, double free or use after free fails the test.
- **Imports**: `import os` (built-in) or `import utils` (the file `utils.dino` next to the
main file; `import tools.fs` is `tools/fs.dino`, used as `fs.name`). Use things as
`utils.double(2)`, `utils.Vec2{1.0, 2.0}`, `utils.Shape.Circle(1.0)`, `utils.SCALE`,
and `utils.Vec2` in types. Only `pub` functions, consts, types, methods and fields can be used
from another file (fields are private too unless written `pub x: int`). Each file has its own imports and its
own names, so two files may both define `f`. Import cycles and missing files are errors;
errors point at the file they are in. Names of module types print with the module
(`utils.Vec2{...}`). Importing a C library (`import c "x.h"`) is not supported yet.
- **Built-in modules**: `os` (`read_file write_file append_file exists exit env
read_line`, and the value `args`), `math` (`sqrt pow floor ceil round trunc sin cos tan asin acos atan atan2 exp log log10 hypot min max abs PI E`),
`time` (`now sleep`). Text has methods: `upper lower trim split lines fields replace
repeat contains starts_with ends_with index_of to_int to_float`; `[]string` has `join`.
- **Maps** `map[K, V]`: `{"a": 1}` (types guessed), `map[string, int]{}` or `var m: map[string, int] = {}` (empty).
Keys: int/whole-number types, string, bool. Values: anything except `T?`. `m[k] = v` adds or replaces,
`m[k]` panics if the key is missing, `m[k] += 1` treats a missing key as zero, methods `has get get_or
remove keys values len`, `for k, v in m` / `for k in m`. Entries keep insertion order (hash index +
ordered arrays; `remove` is O(n)). Maps are values (`var b = a` copies). Not yet: `==`, generic `map[K,V]` params.
- **Docs**: `docs/` holds learner notes in markdown; a test compiles and runs every example in them.
- **Characters** `char`: one Unicode character, `'a'` `'\n'` `'é'` (escapes `\n \t \r \0 \\ \' \"`). Compare with
`== != < > <= >=`, `match` on them (`'+' => ...`), use as map keys; no arithmetic (`int(c)`, `char(n)`).
`string(x)` (or `"{c}"`) makes text. `for c in s` / `for i, c in s` walk characters (`i` = byte position,
invalid UTF-8 comes out as U+FFFD). `s[i]` is the character starting at byte `i` (panics out of range or
in the middle of a character); strings can't be assigned to. Methods `is_digit is_letter is_alnum is_space
is_upper is_lower upper lower` (ASCII plus Latin-1 letters). Not yet: `s.chars()`, `[]char`→string.
- **Formatter** `dino fmt [--check] <file|folder>..` (`src/fmt.rs`): text based, so comments and blank lines survive.
4-space indent, spaces around binary operators and after `,` `:`, tight `Point{...}` / map literals and `[]T`,
at most one blank line, trailing `//` comments of neighbouring lines aligned. It never moves line breaks (a one-line
block stays one line), indents continuation lines (after an operator, or inside open brackets) one level, and
verifies that the token stream is unchanged before writing. `examples/` must stay formatted (a test checks).
- **Editor support** (`editors/`): `dino lsp` is a language server (`src/lsp.rs`, own JSON in `src/json.rs`, no
dependencies): full-text sync, error diagnostics from the real checker (imports read from disk or from open
buffers; errors in other files shown at the top of the importing file; UTF-16 columns), whole-file formatting.
`editors/vscode` (extension + TextMate grammar), `editors/vim` (syntax), `editors/README.md` (Neovim, Helix, others).
Not yet: hover, go to definition, completion, rename; the compiler reports only the first error.
- **String slicing**: `s[a..b]`, `s[a..]`, `s[..b]` (byte positions, bounds checked; panics with "the length is N").
- **Running**: `dino run file.dino a b c` passes `a b c` to the program (`os.args`).
- **Example**: `examples/calc/` is a multi-file calculator (tokenizer, parser, evaluator, shared scope); `session.txt` / `session.out` are checked by a test.
## Open questions
- Braces vs indentation (currently braces, no semicolons)
- Concurrency details
## Status
Working: functions, int/float/bool/string, var/const, if/else, for (infinite,
while, range with step, over lists), break/continue, string interpolation, print,
structs with methods (value semantics, inferred mutation), lists (value
semantics, bounds checked), enums with data + exhaustive match, errors (`error`,
multi-value returns, `?`), optionals (`T?`, `nil`, narrowing), `dino run`.
Not yet: nested match patterns, `==` on lists/structs, top-level const lists. These give a clear "not supported yet" error.
Known gaps: memory is only freed on normal exits (a panic just ends the program).
+141
View File
@@ -0,0 +1,141 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="190 40 1420 1000" width="1420" height="1000">
<defs>
<filter id="sticker" x="-15%" y="-15%" width="130%" height="140%" color-interpolation-filters="sRGB">
<feMorphology in="SourceAlpha" operator="dilate" radius="34" result="dil"/>
<feGaussianBlur in="dil" stdDeviation="10" result="bl"/>
<feComponentTransfer in="bl" result="blob"><feFuncA type="linear" slope="8" intercept="-3"/></feComponentTransfer>
<feOffset in="blob" dx="22" dy="56" result="o2"/>
<feFlood flood-color="#9AD89D"/><feComposite in2="o2" operator="in" result="s2"/>
<feOffset in="blob" dx="0" dy="30" result="o1"/>
<feFlood flood-color="#4A9A52"/><feComposite in2="o1" operator="in" result="s1"/>
<feFlood flood-color="#FFFFFF"/><feComposite in2="blob" operator="in" result="w"/>
<feMerge><feMergeNode in="s2"/><feMergeNode in="s1"/><feMergeNode in="w"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
<pattern id="facets" width="150" height="150" patternUnits="userSpaceOnUse" patternTransform="rotate(28)">
<rect width="150" height="150" fill="#2B2833"/>
<rect x="0" width="56" height="150" fill="#3A3642"/>
</pattern>
<pattern id="spikes" width="96" height="84" patternUnits="userSpaceOnUse" patternTransform="rotate(-14)">
<rect width="96" height="84" fill="#5DB862"/>
<path d="M10,46 C16,30 26,22 32,20 C36,30 38,40 36,52 Z" fill="#8FD293" opacity=".75"/>
<path d="M58,84 C64,68 74,60 80,58 C84,68 86,78 84,90 Z" fill="#8FD293" opacity=".75"/>
<path d="M58,0 C64,-16 74,-24 80,-26 C84,-16 86,-6 84,6 Z" fill="#8FD293" opacity=".75"/>
</pattern>
<clipPath id="clipTop"><path d="M390.42 333.22Q408.57 333.22 423.58500000000004 340.81Q438.6 348.4 447.18 361.27V275.79999999999995H503.61V520.0H447.18V493.6Q439.26 506.8 424.575 514.72Q409.89 522.64 390.42 522.64Q367.65 522.64 349.16999999999996 510.92499999999995Q330.69 499.21 319.96500000000003 477.595Q309.24 455.98 309.24 427.6Q309.24 399.22 319.96500000000003 377.77Q330.69 356.32 349.16999999999996 344.77Q367.65 333.22 390.42 333.22ZM406.92 382.39Q390.09000000000003 382.39 378.375 394.435Q366.65999999999997 406.48 366.65999999999997 427.6Q366.65999999999997 448.72 378.375 461.095Q390.09000000000003 473.47 406.92 473.47Q423.75 473.47 435.46500000000003 461.26Q447.18 449.05 447.18 427.93Q447.18 406.81 435.46500000000003 394.6Q423.75 382.39 406.92 382.39Z" fill="#000" transform="rotate(-5 412.0 404.5)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M533.25 280.36Q533.25 267.15999999999997 542.655 258.41499999999996Q552.0600000000001 249.67000000000002 566.9100000000001 249.67000000000002Q581.4300000000001 249.67000000000002 590.835 258.41499999999996Q600.24 267.15999999999997 600.24 280.36Q600.24 293.23 590.835 301.975Q581.4300000000001 310.72 566.9100000000001 310.72Q552.0600000000001 310.72 542.655 301.975Q533.25 293.23 533.25 280.36ZM594.96 329.86V514.0H538.5300000000001V329.86Z" fill="#000" transform="rotate(3 566.7 398.5)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M813.0300000000001 416.42V524.0H756.9300000000001V424.01Q756.9300000000001 405.53 747.3600000000001 395.29999999999995Q737.7900000000001 385.07 721.6200000000001 385.07Q705.45 385.07 695.8800000000001 395.29999999999995Q686.3100000000001 405.53 686.3100000000001 424.01V524.0H629.8800000000001V339.86H686.3100000000001V364.28Q694.8900000000001 352.07 709.4100000000001 344.975Q723.9300000000001 337.88 742.08 337.88Q774.4200000000001 337.88 793.7250000000001 358.835Q813.0300000000001 379.78999999999996 813.0300000000001 416.42Z" fill="#000" transform="rotate(-2 720.6 408.5)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M835.0800000000002 425.93Q835.0800000000002 397.55 847.6200000000001 375.935Q860.1600000000002 354.32 881.9400000000002 342.77Q903.7200000000001 331.22 930.7800000000002 331.22Q957.8400000000001 331.22 979.6200000000001 342.77Q1001.4000000000001 354.32 1013.9400000000002 375.935Q1026.4800000000002 397.55 1026.4800000000002 425.93Q1026.4800000000002 454.31 1013.7750000000002 475.925Q1001.0700000000002 497.54 979.1250000000002 509.09000000000003Q957.1800000000002 520.64 930.1200000000001 520.64Q903.0600000000002 520.64 881.4450000000002 509.09000000000003Q859.8300000000002 497.54 847.4550000000002 476.09000000000003Q835.0800000000002 454.64 835.0800000000002 425.93ZM969.0600000000002 425.93Q969.0600000000002 403.82 958.0050000000001 391.94Q946.9500000000002 380.06 930.7800000000002 380.06Q914.2800000000002 380.06 903.3900000000001 391.775Q892.5000000000001 403.49 892.5000000000001 425.93Q892.5000000000001 448.03999999999996 903.2250000000001 459.91999999999996Q913.9500000000002 471.8 930.1200000000001 471.8Q946.2900000000002 471.8 957.6750000000002 459.91999999999996Q969.0600000000002 448.03999999999996 969.0600000000002 425.93Z" fill="#000" transform="rotate(4 930.9 402.5)" stroke="#000" stroke-linejoin="round" stroke-width="22"/></clipPath>
<clipPath id="clipBot"><path d="M684.56 602.2V839.0H629.84V602.2Z" fill="#000" transform="rotate(-3 657.2 727.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M788.0799999999999 649.88Q806.96 649.88 821.2 657.56Q835.4399999999999 665.24 843.12 677.72V652.44H897.8399999999999V831.0H843.12V805.72Q835.12 818.2 820.88 825.88Q806.64 833.56 787.76 833.56Q766.0 833.56 748.0799999999999 822.2Q730.16 810.84 719.76 789.88Q709.36 768.92 709.36 741.4Q709.36 713.88 719.76 693.0799999999999Q730.16 672.28 748.0799999999999 661.0799999999999Q766.0 649.88 788.0799999999999 649.88ZM804.0799999999999 697.56Q787.76 697.56 776.4 709.24Q765.04 720.92 765.04 741.4Q765.04 761.88 776.4 773.88Q787.76 785.88 804.0799999999999 785.88Q820.4 785.88 831.76 774.04Q843.12 762.2 843.12 741.72Q843.12 721.24 831.76 709.4Q820.4 697.56 804.0799999999999 697.56Z" fill="#000" transform="rotate(2 809.0 719.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M1111.12 732.68V837.0H1056.72V740.04Q1056.72 722.12 1047.44 712.2Q1038.1599999999999 702.28 1022.4799999999999 702.28Q1006.8 702.28 997.52 712.2Q988.24 722.12 988.24 740.04V837.0H933.52V658.44H988.24V682.12Q996.56 670.28 1010.64 663.4Q1024.72 656.52 1042.32 656.52Q1073.6799999999998 656.52 1092.3999999999999 676.8399999999999Q1111.12 697.16 1111.12 732.68Z" fill="#000" transform="rotate(-4 1021.5 725.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
<path d="M1268.08 675.72V650.44H1322.8V828.68Q1322.8 853.32 1313.04 873.32Q1303.28 893.32 1283.28 905.1600000000001Q1263.28 917.0 1233.52 917.0Q1193.84 917.0 1169.1999999999998 898.28Q1144.56 879.56 1141.04 847.56H1195.12Q1197.6799999999998 857.8 1207.2799999999997 863.72Q1216.8799999999999 869.64 1230.9599999999998 869.64Q1247.9199999999998 869.64 1258.0 859.88Q1268.08 850.12 1268.08 828.68V803.4Q1260.08 815.88 1246.0 823.72Q1231.9199999999998 831.56 1213.04 831.56Q1190.9599999999998 831.56 1173.04 820.2Q1155.12 808.84 1144.7199999999998 787.88Q1134.32 766.92 1134.32 739.4Q1134.32 711.88 1144.7199999999998 691.0799999999999Q1155.12 670.28 1173.04 659.0799999999999Q1190.9599999999998 647.88 1213.04 647.88Q1231.9199999999998 647.88 1246.1599999999999 655.56Q1260.3999999999999 663.24 1268.08 675.72ZM1229.04 695.56Q1212.7199999999998 695.56 1201.36 707.24Q1190.0 718.92 1190.0 739.4Q1190.0 759.88 1201.36 771.88Q1212.7199999999998 783.88 1229.04 783.88Q1245.36 783.88 1256.7199999999998 772.04Q1268.08 760.2 1268.08 739.72Q1268.08 719.24 1256.7199999999998 707.4Q1245.36 695.56 1229.04 695.56Z" fill="#000" transform="rotate(3 1234.0 717.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/></clipPath>
<symbol id="ldino" viewBox="0 0 400 420">
<g stroke="#8FD293" stroke-width="12" stroke-linejoin="round" stroke-linecap="round">
<path d="M300,300 C345,300 372,282 384,248 C390,270 378,318 330,345 C318,352 304,352 296,348 Z" fill="#5DB862"/>
<path d="M176,66 C182,38 196,26 202,22 C210,30 222,44 226,66 Z" fill="#F2A541"/>
<path d="M262,86 C276,62 292,54 302,52 C304,64 304,82 296,106 Z" fill="#F2A541"/>
<path d="M308,142 C326,126 342,124 352,126 C350,140 342,156 326,176 Z" fill="#F2A541"/>
<path d="M324,214 C340,206 354,208 362,212 C356,226 346,238 330,250 Z" fill="#F2A541"/>
<ellipse cx="148" cy="384" rx="42" ry="20" fill="#5DB862"/>
<ellipse cx="252" cy="384" rx="42" ry="20" fill="#5DB862"/>
<path d="M200,58 C292,58 334,132 334,236 C334,334 282,380 200,380 C118,380 66,334 66,236 C66,132 108,58 200,58 Z" fill="#5DB862"/>
</g>
<path d="M200,236 C258,236 290,276 290,316 C290,356 250,374 200,374 C150,374 110,356 110,316 C110,276 142,236 200,236 Z" fill="#F4EAC8"/>
<g stroke="#C9B98A" stroke-width="5" stroke-linecap="round" fill="none" opacity=".7">
<path d="M150,292 Q200,302 250,292"/>
<path d="M140,326 Q200,338 260,326"/>
</g>
<path d="M200,58 C292,58 334,132 334,236 C334,334 282,380 200,380 C118,380 66,334 66,236 C66,132 108,58 200,58 Z" fill="none" stroke="#8FD293" stroke-width="12"/>
<g fill="#F4EAC8" stroke="#8FD293" stroke-width="4">
<circle cx="124" cy="394" r="7"/><circle cx="146" cy="398" r="7"/><circle cx="168" cy="394" r="7"/>
<circle cx="232" cy="394" r="7"/><circle cx="254" cy="398" r="7"/><circle cx="276" cy="394" r="7"/>
</g>
<g fill="#5DB862" stroke="#8FD293" stroke-width="9" stroke-linejoin="round" stroke-linecap="round">
<path d="M118,248 C98,250 84,264 86,282 C100,288 116,280 126,268 Z"/>
<path d="M282,248 C302,250 316,264 314,282 C300,288 284,280 274,268 Z"/>
</g>
<ellipse cx="114" cy="206" rx="20" ry="11" fill="#FFA3B6" opacity=".95"/>
<ellipse cx="286" cy="206" rx="20" ry="11" fill="#FFA3B6" opacity=".95"/>
<g stroke="#8FD293" stroke-width="9">
<circle cx="154" cy="148" r="42" fill="#FFFFFF"/>
<circle cx="246" cy="148" r="42" fill="#FFFFFF"/>
</g>
<circle cx="164" cy="156" r="21" fill="#26232E"/>
<circle cx="236" cy="156" r="21" fill="#26232E"/>
<circle cx="171" cy="148" r="7" fill="#FFFFFF"/>
<circle cx="243" cy="148" r="7" fill="#FFFFFF"/>
<circle cx="158" cy="166" r="3" fill="#FFFFFF"/>
<circle cx="230" cy="166" r="3" fill="#FFFFFF"/>
<ellipse cx="200" cy="212" rx="50" ry="27" fill="#8FD293" stroke="#8FD293" stroke-width="9"/>
<ellipse cx="186" cy="204" rx="5" ry="4" fill="#26232E"/>
<ellipse cx="214" cy="204" rx="5" ry="4" fill="#26232E"/>
<path d="M207,252 L212,262 L218,251 Z" fill="#FFFFFF" stroke="#26232E" stroke-width="3" stroke-linejoin="round"/>
<path d="M180,248 Q200,262 220,248" fill="none" stroke="#26232E" stroke-width="5" stroke-linecap="round"/>
</symbol>
</defs>
<g filter="url(#sticker)">
<!-- props: braces + egg -->
<g transform="translate(470 175) rotate(-9)">
<rect x="-120" y="-72" width="240" height="144" rx="40" fill="#F2A541"/>
<path d="M-50,-32 L-84,0 L-50,32 M50,-32 L84,0 L50,32 M14,-40 L-14,40" fill="none" stroke="#2B2833" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<g transform="translate(720 175) rotate(14)">
<path d="M0,-92 C52,-92 82,-20 82,26 C82,74 46,100 0,100 C-46,100 -82,74 -82,26 C-82,-20 -52,-92 0,-92 Z" fill="#F4EAC8"/>
<ellipse cx="-30" cy="-20" rx="18" ry="22" fill="#5DB862"/>
<ellipse cx="30" cy="34" rx="24" ry="20" fill="#5DB862"/>
<ellipse cx="-34" cy="58" rx="12" ry="11" fill="#5DB862"/>
<ellipse cx="34" cy="-48" rx="10" ry="12" fill="#5DB862"/>
<clipPath id="eggc"><path d="M0,-92 C52,-92 82,-20 82,26 C82,74 46,100 0,100 C-46,100 -82,74 -82,26 C-82,-20 -52,-92 0,-92 Z"/></clipPath><path clip-path="url(#eggc)" d="M-82,10 L-50,-6 L-28,16 L-4,-8 L20,14 L44,-6 L82,12" fill="none" stroke="#2B2833" stroke-width="8" stroke-linejoin="round" stroke-linecap="round"/>
</g>
<!-- code card -->
<g transform="rotate(3 1260 360)">
<rect x="1030" y="200" width="470" height="330" rx="56" fill="#2B2833"/>
<path d="M1094.796 269.436Q1097.766 269.436 1100.223 270.678Q1102.68 271.92 1104.084 274.026V260.04H1113.318V300.0H1104.084V295.68Q1102.788 297.84 1100.385 299.13599999999997Q1097.982 300.432 1094.796 300.432Q1091.07 300.432 1088.0459999999998 298.515Q1085.022 296.598 1083.2669999999998 293.06100000000004Q1081.512 289.524 1081.512 284.88Q1081.512 280.236 1083.2669999999998 276.726Q1085.022 273.216 1088.0459999999998 271.326Q1091.07 269.436 1094.796 269.436ZM1097.496 277.48199999999997Q1094.742 277.48199999999997 1092.8249999999998 279.453Q1090.908 281.424 1090.908 284.88Q1090.908 288.336 1092.8249999999998 290.361Q1094.742 292.386 1097.496 292.386Q1100.25 292.386 1102.167 290.38800000000003Q1104.084 288.39 1104.084 284.934Q1104.084 281.478 1102.167 279.48Q1100.25 277.48199999999997 1097.496 277.48199999999997Z" fill="#FFFFFF" transform="rotate(0 1098.3 281.1)" />
<path d="M1119.1499999999999 261.76800000000003Q1119.1499999999999 259.608 1120.6889999999999 258.177Q1122.2279999999998 256.746 1124.658 256.746Q1127.0339999999999 256.746 1128.5729999999999 258.177Q1130.1119999999999 259.608 1130.1119999999999 261.76800000000003Q1130.1119999999999 263.874 1128.5729999999999 265.305Q1127.0339999999999 266.736 1124.658 266.736Q1122.2279999999998 266.736 1120.6889999999999 265.305Q1119.1499999999999 263.874 1119.1499999999999 261.76800000000003ZM1129.248 269.868V300.0H1120.014V269.868Z" fill="#FFFFFF" transform="rotate(0 1124.6 281.1)" />
<path d="M1165.914 282.396V300.0H1156.734V283.638Q1156.734 280.614 1155.1680000000001 278.94Q1153.602 277.266 1150.956 277.266Q1148.31 277.266 1146.7440000000001 278.94Q1145.178 280.614 1145.178 283.638V300.0H1135.944V269.868H1145.178V273.864Q1146.582 271.866 1148.958 270.705Q1151.334 269.544 1154.304 269.544Q1159.596 269.544 1162.755 272.97299999999996Q1165.914 276.402 1165.914 282.396Z" fill="#FFFFFF" transform="rotate(0 1150.8 281.1)" />
<path d="M1170.504 284.934Q1170.504 280.29 1172.556 276.75300000000004Q1174.608 273.216 1178.172 271.326Q1181.7359999999999 269.436 1186.164 269.436Q1190.5919999999999 269.436 1194.156 271.326Q1197.72 273.216 1199.772 276.75300000000004Q1201.824 280.29 1201.824 284.934Q1201.824 289.578 1199.745 293.115Q1197.666 296.652 1194.0749999999998 298.54200000000003Q1190.484 300.432 1186.056 300.432Q1181.628 300.432 1178.091 298.54200000000003Q1174.5539999999999 296.652 1172.529 293.142Q1170.504 289.632 1170.504 284.934ZM1192.4279999999999 284.934Q1192.4279999999999 281.316 1190.619 279.37199999999996Q1188.81 277.428 1186.164 277.428Q1183.464 277.428 1181.6819999999998 279.345Q1179.8999999999999 281.262 1179.8999999999999 284.934Q1179.8999999999999 288.552 1181.6549999999997 290.496Q1183.4099999999999 292.44 1186.056 292.44Q1188.702 292.44 1190.565 290.496Q1192.4279999999999 288.552 1192.4279999999999 284.934Z" fill="#FFFFFF" transform="rotate(0 1186.2 281.1)" />
<path d="" fill="#FFFFFF" transform="rotate(0 1209.1 281.1)" />
<path d="M1236.87 269.544V279.318H1234.3319999999999Q1230.876 279.318 1229.1480000000001 280.803Q1227.42 282.288 1227.42 286.014V300.0H1218.186V269.868H1227.42V274.89Q1229.04 272.406 1231.4699999999998 270.975Q1233.8999999999999 269.544 1236.87 269.544Z" fill="#FFFFFF" transform="rotate(0 1226.4 281.1)" />
<path d="M1271.0520000000001 269.868V300.0H1261.818V295.896Q1260.414 297.894 1258.011 299.10900000000004Q1255.608 300.324 1252.692 300.324Q1249.236 300.324 1246.5900000000001 298.78499999999997Q1243.944 297.246 1242.4859999999999 294.33Q1241.028 291.414 1241.028 287.472V269.868H1250.208V286.23Q1250.208 289.254 1251.7740000000001 290.928Q1253.3400000000001 292.602 1255.986 292.602Q1258.6860000000001 292.602 1260.252 290.928Q1261.818 289.254 1261.818 286.23V269.868Z" fill="#FFFFFF" transform="rotate(0 1256.1 281.1)" />
<path d="M1307.664 282.396V300.0H1298.484V283.638Q1298.484 280.614 1296.9180000000001 278.94Q1295.352 277.266 1292.706 277.266Q1290.06 277.266 1288.4940000000001 278.94Q1286.928 280.614 1286.928 283.638V300.0H1277.694V269.868H1286.928V273.864Q1288.332 271.866 1290.708 270.705Q1293.084 269.544 1296.054 269.544Q1301.346 269.544 1304.505 272.97299999999996Q1307.664 276.402 1307.664 282.396Z" fill="#FFFFFF" transform="rotate(0 1292.5 281.1)" />
<path d="M1092.990234375 358.58984375V360.3125H1099.037109375V364.267578125H1092.990234375V380.0H1087.83984375V364.267578125H1083.05859375V360.3125H1087.83984375V358.94140625Q1087.83984375 355.390625 1089.31640625 354.01953125Q1090.79296875 352.6484375 1094.80078125 352.6484375H1099.037109375V356.603515625H1095.01171875Q1093.8515625 356.603515625 1093.4384765625 357.025390625Q1093.025390625 357.447265625 1092.990234375 358.58984375Z M1120.5 367.220703125V380.0H1115.384765625V368.01171875Q1115.384765625 365.8671875 1114.7783203125 364.9443359375Q1114.171875 364.021484375 1112.80078125 364.021484375Q1111.412109375 364.021484375 1110.6123046875 365.26953125Q1109.8125 366.517578125 1109.8125 368.732421875V380.0H1104.697265625V360.3125H1109.8125V363.265625Q1110.357421875 361.630859375 1111.67578125 360.734375Q1112.994140625 359.837890625 1114.857421875 359.837890625Q1117.65234375 359.837890625 1119.076171875 361.6923828125Q1120.5 363.546875 1120.5 367.220703125Z M1157.150390625 362.28125Q1157.73046875 361.033203125 1158.626953125 360.435546875Q1159.5234375 359.837890625 1160.82421875 359.837890625Q1163.373046875 359.837890625 1164.3486328125 361.595703125Q1165.32421875 363.353515625 1165.32421875 368.908203125V380.0H1161.10546875V367.361328125Q1161.10546875 365.1640625 1160.771484375 364.42578125Q1160.4375 363.6875 1159.55859375 363.6875Q1158.6796875 363.6875 1158.328125 364.443359375Q1157.9765625 365.19921875 1157.9765625 367.361328125V380.0H1153.810546875V367.361328125Q1153.810546875 365.19921875 1153.458984375 364.443359375Q1153.107421875 363.6875 1152.228515625 363.6875Q1151.349609375 363.6875 1151.015625 364.42578125Q1150.681640625 365.1640625 1150.681640625 367.361328125V380.0H1146.462890625V360.3125H1150.20703125V362.3515625Q1150.646484375 361.19140625 1151.61328125 360.5146484375Q1152.580078125 359.837890625 1153.775390625 359.837890625Q1154.970703125 359.837890625 1155.955078125 360.5498046875Q1156.939453125 361.26171875 1157.150390625 362.28125Z M1179.0 370.75390625Q1176.1171875 370.75390625 1174.974609375 371.4921875Q1173.83203125 372.23046875 1173.83203125 374.0234375Q1173.83203125 375.359375 1174.623046875 376.150390625Q1175.4140625 376.94140625 1176.767578125 376.94140625Q1178.806640625 376.94140625 1179.931640625 375.4033203125Q1181.056640625 373.865234375 1181.056640625 371.10546875V370.75390625ZM1186.171875 368.767578125V380.0H1181.056640625V377.802734375Q1180.125 379.103515625 1178.666015625 379.806640625Q1177.20703125 380.509765625 1175.44921875 380.509765625Q1172.091796875 380.509765625 1170.2197265625 378.734375Q1168.34765625 376.958984375 1168.34765625 373.77734375Q1168.34765625 370.33203125 1170.580078125 368.6884765625Q1172.8125 367.044921875 1177.48828125 367.044921875H1181.056640625V366.18359375Q1181.056640625 364.935546875 1180.1513671875 364.2939453125Q1179.24609375 363.65234375 1177.48828125 363.65234375Q1175.642578125 363.65234375 1173.9111328125 364.1181640625Q1172.1796875 364.583984375 1170.298828125 365.603515625V361.208984375Q1172.00390625 360.505859375 1173.76171875 360.171875Q1175.51953125 359.837890625 1177.48828125 359.837890625Q1182.287109375 359.837890625 1184.2294921875 361.7890625Q1186.171875 363.740234375 1186.171875 368.767578125Z M1192.25390625 360.3125H1202.44921875V376.044921875H1208.84765625V380.0H1190.8828125V376.044921875H1197.298828125V364.267578125H1192.25390625ZM1197.298828125 350.732421875H1202.44921875V356.744140625H1197.298828125Z M1228.869140625 367.220703125V380.0H1223.75390625V368.01171875Q1223.75390625 365.8671875 1223.1474609375 364.9443359375Q1222.541015625 364.021484375 1221.169921875 364.021484375Q1219.78125 364.021484375 1218.9814453125 365.26953125Q1218.181640625 366.517578125 1218.181640625 368.732421875V380.0H1213.06640625V360.3125H1218.181640625V363.265625Q1218.7265625 361.630859375 1220.044921875 360.734375Q1221.36328125 359.837890625 1223.2265625 359.837890625Q1226.021484375 359.837890625 1227.4453125 361.6923828125Q1228.869140625 363.546875 1228.869140625 367.220703125Z M1247.958984375 352.68359375Q1245.638671875 356.884765625 1244.513671875 360.822265625Q1243.388671875 364.759765625 1243.388671875 368.697265625Q1243.388671875 372.599609375 1244.513671875 376.5634765625Q1245.638671875 380.52734375 1247.958984375 384.74609375H1243.951171875Q1241.15625 380.685546875 1239.802734375 376.7392578125Q1238.44921875 372.79296875 1238.44921875 368.697265625Q1238.44921875 364.619140625 1239.8115234375 360.6552734375Q1241.173828125 356.69140625 1243.951171875 352.68359375Z M1258.822265625 352.68359375H1262.830078125Q1265.607421875 356.69140625 1266.9697265625 360.6552734375Q1268.33203125 364.619140625 1268.33203125 368.697265625Q1268.33203125 372.79296875 1266.978515625 376.7392578125Q1265.625 380.685546875 1262.830078125 384.74609375H1258.822265625Q1261.142578125 380.52734375 1262.267578125 376.5634765625Q1263.392578125 372.599609375 1263.392578125 368.697265625Q1263.392578125 364.759765625 1262.267578125 360.822265625Q1261.142578125 356.884765625Line truncated
<path d="M1143.580078125 413.744140625Q1142.736328125 412.970703125 1141.6025390625 412.583984375Q1140.46875 412.197265625 1139.115234375 412.197265625Q1137.48046875 412.197265625 1136.2587890625 412.7685546875Q1135.037109375 413.33984375 1134.369140625 414.4296875Q1133.947265625 415.09765625 1133.7802734375 416.046875Q1133.61328125 416.99609375 1133.61328125 418.9296875V428.0H1128.462890625V408.3125H1133.61328125V411.37109375Q1134.369140625 409.68359375 1135.93359375 408.7607421875Q1137.498046875 407.837890625 1139.58984375 407.837890625Q1140.64453125 407.837890625 1141.6552734375 408.0927734375Q1142.666015625 408.34765625 1143.580078125 408.83984375Z M1155.849609375 412.021484375Q1154.00390625 412.021484375 1152.94921875 413.6474609375Q1151.89453125 415.2734375 1151.89453125 418.173828125Q1151.89453125 421.07421875 1152.94921875 422.7001953125Q1154.00390625 424.326171875 1155.849609375 424.326171875Q1157.712890625 424.326171875 1158.767578125 422.7001953125Q1159.822265625 421.07421875 1159.822265625 418.173828125Q1159.822265625 415.2734375 1158.767578125 413.6474609375Q1157.712890625 412.021484375 1155.849609375 412.021484375ZM1146.744140625 418.173828125Q1146.744140625 413.41015625 1149.2138671875 410.6240234375Q1151.68359375 407.837890625 1155.849609375 407.837890625Q1160.033203125 407.837890625 1162.5029296875 410.6240234375Q1164.97265625 413.41015625 1164.97265625 418.173828125Q1164.97265625 422.9375 1162.5029296875 425.7236328125Q1160.033203125 428.509765625 1155.849609375 428.509765625Q1151.68359375 428.509765625 1149.2138671875 425.7236328125Q1146.744140625 422.9375 1146.744140625 418.173828125Z M1179.0 418.75390625Q1176.1171875 418.75390625 1174.974609375 419.4921875Q1173.83203125 420.23046875 1173.83203125 422.0234375Q1173.83203125 423.359375 1174.623046875 424.150390625Q1175.4140625 424.94140625 1176.767578125 424.94140625Q1178.806640625 424.94140625 1179.931640625 423.4033203125Q1181.056640625 421.865234375 1181.056640625 419.10546875V418.75390625ZM1186.171875 416.767578125V428.0H1181.056640625V425.802734375Q1180.125 427.103515625 1178.666015625 427.806640625Q1177.20703125 428.509765625 1175.44921875 428.509765625Q1172.091796875 428.509765625 1170.2197265625 426.734375Q1168.34765625 424.958984375 1168.34765625 421.77734375Q1168.34765625 418.33203125 1170.580078125 416.6884765625Q1172.8125 415.044921875 1177.48828125 415.044921875H1181.056640625V414.18359375Q1181.056640625 412.935546875 1180.1513671875 412.2939453125Q1179.24609375 411.65234375 1177.48828125 411.65234375Q1175.642578125 411.65234375 1173.9111328125 412.1181640625Q1172.1796875 412.583984375 1170.298828125 413.603515625V409.208984375Q1172.00390625 408.505859375 1173.76171875 408.171875Q1175.51953125 407.837890625 1177.48828125 407.837890625Q1182.287109375 407.837890625 1184.2294921875 409.7890625Q1186.171875 411.740234375 1186.171875 416.767578125Z M1208.6015625 413.744140625Q1207.7578125 412.970703125 1206.6240234375 412.583984375Q1205.490234375 412.197265625 1204.13671875 412.197265625Q1202.501953125 412.197265625 1201.2802734375 412.7685546875Q1200.05859375 413.33984375 1199.390625 414.4296875Q1198.96875 415.09765625 1198.8017578125 416.046875Q1198.634765625 416.99609375 1198.634765625 418.9296875V428.0H1193.484375V408.3125H1198.634765625V411.37109375Q1199.390625 409.68359375 1200.955078125 408.7607421875Q1202.51953125 407.837890625 1204.611328125 407.837890625Q1205.666015625 407.837890625 1206.6767578125 408.0927734375Q1207.6875 408.34765625 1208.6015625 408.83984375Z M1226.28515625 400.68359375Q1223.96484375 404.884765625 1222.83984375 408.822265625Q1221.71484375 412.759765625 1221.71484375 416.697265625Q1221.71484375 420.599609375 1222.83984375 424.5634765625Q1223.96484375 428.52734375 1226.28515625 432.74609375H1222.27734375Q1219.482421875 428.685546875 1218.12890625 424.7392578125Q1216.775390625 420.79296875 1216.775390625 416.697265625Q1216.775390625 412.619140625 1218.1376953125 408.6552734375Q1219.5 404.69140625 1222.27734375 400.68359375Z M1249.27734375 401.755859375V411.51171875H1244.77734375V401.755859375ZM1240.27734375 401.755859375V411.51171875H1235.77734375V401.755859375Z M1272.216796875 415.220703125V428.0H1267.1015625V416.01171875Q1267.1015625 413.884765625 1266.4951171875 412.970703125Q1265.888671875 412.056640625 1264.517578125 412.056640625Q1263.111328125 412.056640625 1262.3203125 413.2958984375Q1261.529296875 414.53515625 1261.529296875 416.732421875V428.0H1256.4140625V400.6484375H1261.529296875V411.265625Q1262.07421875 409.630859375 1263.392578125 408.734375Q1264.7109375 407.837890625 1266.57421875 407.837890625Q1269.369140625 407.837890625 1270.79296875 409.6923828125Q1272.216796875 411.546875 1272.216796875 415.220703125Z M1278.94921875 408.3125H1289.14453125V424.044921875H1295.54296875V428.0H1277.578125V424.044921875H1283.994140625V412.267578125H1278.94921875ZM1283.994140625 398.732421875H1289.14453125V404.744140625H1283.994140625Z M1314.298828125 401.755859375V411.51171875H1309.798828125V401.755859375ZMLine truncated
<path d="M1083.1640625 478.513671875H1085.291015625Q1087.119140625 478.513671875 1087.751953125 477.7578125Q1088.384765625 477.001953125 1088.384765625 474.48828125V470.884765625Q1088.384765625 468.001953125 1089.24609375 466.806640625Q1090.107421875 465.611328125 1092.3046875 465.2421875Q1090.08984375 464.908203125 1089.2373046875 463.73046875Q1088.384765625 462.552734375 1088.384765625 459.65234375V455.978515625Q1088.384765625 453.5 1087.7607421875 452.744140625Q1087.13671875 451.98828125 1085.291015625 451.98828125H1083.1640625V448.6484375H1085.80078125Q1090.16015625 448.6484375 1091.6279296875 449.9404296875Q1093.095703125 451.232421875 1093.095703125 455.1171875V458.896484375Q1093.095703125 461.55078125 1094.0537109375 462.5615234375Q1095.01171875 463.572265625 1097.490234375 463.572265625H1098.580078125V466.9296875H1097.490234375Q1095.01171875 466.9296875 1094.0537109375 467.94921875Q1093.095703125 468.96875 1093.095703125 471.60546875V475.384765625Q1093.095703125 479.26953125 1091.6279296875 480.5703125Q1090.16015625 481.87109375 1085.80078125 481.87109375H1083.1640625Z" fill="#C9C3D3"/>
</g>
<!-- leaves -->
<g transform="translate(1068 560) rotate(-30)"><path d="M0,0 C30,-46 86,-58 128,-40 C110,4 62,40 0,0 Z" transform="scale(1.25)" fill="#5DB862"/><path d="M10,-4 C46,-22 82,-30 112,-34" transform="scale(1.25)" fill="none" stroke="#3F8F47" stroke-width="6" stroke-linecap="round"/></g>
<g transform="translate(1250 548) rotate(-6)"><path d="M0,0 C30,-46 86,-58 128,-40 C110,4 62,40 0,0 Z" fill="#8FD293"/><path d="M10,-4 C46,-22 82,-30 112,-34" fill="none" stroke="#5DB862" stroke-width="5" stroke-linecap="round"/></g>
<!-- top word -->
<path d="M390.42 333.22Q408.57 333.22 423.58500000000004 340.81Q438.6 348.4 447.18 361.27V275.79999999999995H503.61V520.0H447.18V493.6Q439.26 506.8 424.575 514.72Q409.89 522.64 390.42 522.64Q367.65 522.64 349.16999999999996 510.92499999999995Q330.69 499.21 319.96500000000003 477.595Q309.24 455.98 309.24 427.6Q309.24 399.22 319.96500000000003 377.77Q330.69 356.32 349.16999999999996 344.77Q367.65 333.22 390.42 333.22ZM406.92 382.39Q390.09000000000003 382.39 378.375 394.435Q366.65999999999997 406.48 366.65999999999997 427.6Q366.65999999999997 448.72 378.375 461.095Q390.09000000000003 473.47 406.92 473.47Q423.75 473.47 435.46500000000003 461.26Q447.18 449.05 447.18 427.93Q447.18 406.81 435.46500000000003 394.6Q423.75 382.39 406.92 382.39Z" fill="#2B2833" transform="rotate(-5 412.0 404.5)" stroke="#2B2833" stroke-linejoin="round" stroke-width="22"/>
<path d="M533.25 280.36Q533.25 267.15999999999997 542.655 258.41499999999996Q552.0600000000001 249.67000000000002 566.9100000000001 249.67000000000002Q581.4300000000001 249.67000000000002 590.835 258.41499999999996Q600.24 267.15999999999997 600.24 280.36Q600.24 293.23 590.835 301.975Q581.4300000000001 310.72 566.9100000000001 310.72Q552.0600000000001 310.72 542.655 301.975Q533.25 293.23 533.25 280.36ZM594.96 329.86V514.0H538.5300000000001V329.86Z" fill="#2B2833" transform="rotate(3 566.7 398.5)" stroke="#2B2833" stroke-linejoin="round" stroke-width="22"/>
<path d="M813.0300000000001 416.42V524.0H756.9300000000001V424.01Q756.9300000000001 405.53 747.3600000000001 395.29999999999995Q737.7900000000001 385.07 721.6200000000001 385.07Q705.45 385.07 695.8800000000001 395.29999999999995Q686.3100000000001 405.53 686.3100000000001 424.01V524.0H629.8800000000001V339.86H686.3100000000001V364.28Q694.8900000000001 352.07 709.4100000000001 344.975Q723.9300000000001 337.88 742.08 337.88Q774.4200000000001 337.88 793.7250000000001 358.835Q813.0300000000001 379.78999999999996 813.0300000000001 416.42Z" fill="#2B2833" transform="rotate(-2 720.6 408.5)" stroke="#2B2833" stroke-linejoin="round" stroke-width="22"/>
<path d="M835.0800000000002 425.93Q835.0800000000002 397.55 847.6200000000001 375.935Q860.1600000000002 354.32 881.9400000000002 342.77Q903.7200000000001 331.22 930.7800000000002 331.22Q957.8400000000001 331.22 979.6200000000001 342.77Q1001.4000000000001 354.32 1013.9400000000002 375.935Q1026.4800000000002 397.55 1026.4800000000002 425.93Q1026.4800000000002 454.31 1013.7750000000002 475.925Q1001.0700000000002 497.54 979.1250000000002 509.09000000000003Q957.1800000000002 520.64 930.1200000000001 520.64Q903.0600000000002 520.64 881.4450000000002 509.09000000000003Q859.8300000000002 497.54 847.4550000000002 476.09000000000003Q835.0800000000002 454.64 835.0800000000002 425.93ZM969.0600000000002 425.93Q969.0600000000002 403.82 958.0050000000001 391.94Q946.9500000000002 380.06 930.7800000000002 380.06Q914.2800000000002 380.06 903.3900000000001 391.775Q892.5000000000001 403.49 892.5000000000001 425.93Q892.5000000000001 448.03999999999996 903.2250000000001 459.91999999999996Q913.9500000000002 471.8 930.1200000000001 471.8Q946.2900000000002 471.8 957.6750000000002 459.91999999999996Q969.0600000000002 448.03999999999996 969.0600000000002 425.93Z" fill="#2B2833" transform="rotate(4 930.9 402.5)" stroke="#2B2833" stroke-linejoin="round" stroke-width="22"/>
<g clip-path="url(#clipTop)"><rect x="250" y="250" width="800" height="340" fill="url(#facets)"/></g>
<!-- bottom word -->
<path d="M684.56 602.2V839.0H629.84V602.2Z" fill="#5DB862" transform="rotate(-3 657.2 727.0)" stroke="#5DB862" stroke-linejoin="round" stroke-width="22"/>
<path d="M788.0799999999999 649.88Q806.96 649.88 821.2 657.56Q835.4399999999999 665.24 843.12 677.72V652.44H897.8399999999999V831.0H843.12V805.72Q835.12 818.2 820.88 825.88Q806.64 833.56 787.76 833.56Q766.0 833.56 748.0799999999999 822.2Q730.16 810.84 719.76 789.88Q709.36 768.92 709.36 741.4Q709.36 713.88 719.76 693.0799999999999Q730.16 672.28 748.0799999999999 661.0799999999999Q766.0 649.88 788.0799999999999 649.88ZM804.0799999999999 697.56Q787.76 697.56 776.4 709.24Q765.04 720.92 765.04 741.4Q765.04 761.88 776.4 773.88Q787.76 785.88 804.0799999999999 785.88Q820.4 785.88 831.76 774.04Q843.12 762.2 843.12 741.72Q843.12 721.24 831.76 709.4Q820.4 697.56 804.0799999999999 697.56Z" fill="#5DB862" transform="rotate(2 809.0 719.0)" stroke="#5DB862" stroke-linejoin="round" stroke-width="22"/>
<path d="M1111.12 732.68V837.0H1056.72V740.04Q1056.72 722.12 1047.44 712.2Q1038.1599999999999 702.28 1022.4799999999999 702.28Q1006.8 702.28 997.52 712.2Q988.24 722.12 988.24 740.04V837.0H933.52V658.44H988.24V682.12Q996.56 670.28 1010.64 663.4Q1024.72 656.52 1042.32 656.52Q1073.6799999999998 656.52 1092.3999999999999 676.8399999999999Q1111.12 697.16 1111.12 732.68Z" fill="#5DB862" transform="rotate(-4 1021.5 725.0)" stroke="#5DB862" stroke-linejoin="round" stroke-width="22"/>
<path d="M1268.08 675.72V650.44H1322.8V828.68Q1322.8 853.32 1313.04 873.32Q1303.28 893.32 1283.28 905.1600000000001Q1263.28 917.0 1233.52 917.0Q1193.84 917.0 1169.1999999999998 898.28Q1144.56 879.56 1141.04 847.56H1195.12Q1197.6799999999998 857.8 1207.2799999999997 863.72Q1216.8799999999999 869.64 1230.9599999999998 869.64Q1247.9199999999998 869.64 1258.0 859.88Q1268.08 850.12 1268.08 828.68V803.4Q1260.08 815.88 1246.0 823.72Q1231.9199999999998 831.56 1213.04 831.56Q1190.9599999999998 831.56 1173.04 820.2Q1155.12 808.84 1144.7199999999998 787.88Q1134.32 766.92 1134.32 739.4Q1134.32 711.88 1144.7199999999998 691.0799999999999Q1155.12 670.28 1173.04 659.0799999999999Q1190.9599999999998 647.88 1213.04 647.88Q1231.9199999999998 647.88 1246.1599999999999 655.56Q1260.3999999999999 663.24 1268.08 675.72ZM1229.04 695.56Q1212.7199999999998 695.56 1201.36 707.24Q1190.0 718.92 1190.0 739.4Q1190.0 759.88 1201.36 771.88Q1212.7199999999998 783.88 1229.04 783.88Q1245.36 783.88 1256.7199999999998 772.04Q1268.08 760.2 1268.08 739.72Q1268.08 719.24 1256.7199999999998 707.4Q1245.36 695.56 1229.04 695.56Z" fill="#5DB862" transform="rotate(3 1234.0 717.0)" stroke="#5DB862" stroke-linejoin="round" stroke-width="22"/>
<g clip-path="url(#clipBot)"><rect x="560" y="540" width="800" height="400" fill="url(#spikes)"/></g>
<!-- mascot -->
<use href="#ldino" x="205" y="505" width="400" height="420"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 35 KiB

+55
View File
@@ -0,0 +1,55 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 420" width="400" height="420">
<g stroke="#26232E" stroke-width="7" stroke-linejoin="round" stroke-linecap="round">
<!-- tail (behind body) -->
<path d="M300,300 C345,300 372,282 384,248 C390,270 378,318 330,345 C318,352 304,352 296,348 Z" fill="#7CC47F"/>
<!-- back spikes (behind body) -->
<path d="M176,66 C182,38 196,26 202,22 C210,30 222,44 226,66 Z" fill="#F2A541"/>
<path d="M262,86 C276,62 292,54 302,52 C304,64 304,82 296,106 Z" fill="#F2A541"/>
<path d="M308,142 C326,126 342,124 352,126 C350,140 342,156 326,176 Z" fill="#F2A541"/>
<path d="M324,214 C340,206 354,208 362,212 C356,226 346,238 330,250 Z" fill="#F2A541"/>
<!-- feet -->
<ellipse cx="148" cy="384" rx="42" ry="20" fill="#7CC47F"/>
<ellipse cx="252" cy="384" rx="42" ry="20" fill="#7CC47F"/>
<!-- body -->
<path d="M200,58 C292,58 334,132 334,236 C334,334 282,380 200,380 C118,380 66,334 66,236 C66,132 108,58 200,58 Z" fill="#7CC47F"/>
</g>
<!-- belly -->
<path d="M200,236 C258,236 290,276 290,316 C290,356 250,374 200,374 C150,374 110,356 110,316 C110,276 142,236 200,236 Z" fill="#F4EAC8"/>
<g stroke="#26232E" stroke-width="4" stroke-linecap="round" fill="none" opacity=".35">
<path d="M150,292 Q200,302 250,292"/>
<path d="M140,326 Q200,338 260,326"/>
</g>
<!-- re-stroke body outline over belly -->
<path d="M200,58 C292,58 334,132 334,236 C334,334 282,380 200,380 C118,380 66,334 66,236 C66,132 108,58 200,58 Z" fill="none" stroke="#26232E" stroke-width="7"/>
<!-- toes -->
<g fill="#F4EAC8" stroke="#26232E" stroke-width="4">
<circle cx="124" cy="394" r="7"/><circle cx="146" cy="398" r="7"/><circle cx="168" cy="394" r="7"/>
<circle cx="232" cy="394" r="7"/><circle cx="254" cy="398" r="7"/><circle cx="276" cy="394" r="7"/>
</g>
<!-- tiny arms -->
<g fill="#7CC47F" stroke="#26232E" stroke-width="6" stroke-linejoin="round" stroke-linecap="round">
<path d="M118,248 C98,250 84,264 86,282 C100,288 116,280 126,268 Z"/>
<path d="M282,248 C302,250 316,264 314,282 C300,288 284,280 274,268 Z"/>
</g>
<!-- blush -->
<ellipse cx="114" cy="206" rx="20" ry="11" fill="#FF8FA8" opacity=".8"/>
<ellipse cx="286" cy="206" rx="20" ry="11" fill="#FF8FA8" opacity=".8"/>
<!-- eyes -->
<g stroke="#26232E" stroke-width="6">
<circle cx="154" cy="148" r="42" fill="#FFFFFF"/>
<circle cx="246" cy="148" r="42" fill="#FFFFFF"/>
</g>
<circle cx="164" cy="156" r="21" fill="#26232E"/>
<circle cx="236" cy="156" r="21" fill="#26232E"/>
<circle cx="171" cy="148" r="7" fill="#FFFFFF"/>
<circle cx="243" cy="148" r="7" fill="#FFFFFF"/>
<circle cx="158" cy="166" r="3" fill="#FFFFFF"/>
<circle cx="230" cy="166" r="3" fill="#FFFFFF"/>
<!-- snout -->
<ellipse cx="200" cy="212" rx="50" ry="27" fill="#96D598" stroke="#26232E" stroke-width="6"/>
<ellipse cx="186" cy="204" rx="5" ry="4" fill="#26232E"/>
<ellipse cx="214" cy="204" rx="5" ry="4" fill="#26232E"/>
<!-- mouth + tooth -->
<path d="M207,252 L212,262 L218,251 Z" fill="#FFFFFF" stroke="#26232E" stroke-width="3" stroke-linejoin="round"/>
<path d="M180,248 Q200,262 220,248" fill="none" stroke="#26232E" stroke-width="5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

+100
View File
@@ -0,0 +1,100 @@
# 1. First steps
## Running a program
Save this as `hello.dino`:
```dino
func main() {
print("Hello, Dino!")
}
```
```text
Hello, Dino!
```
Every program starts at `func main()`. Run it from the project folder:
```text
cargo run -q -- run hello.dino
```
The compiler turns your Dino code into C and builds it with your C compiler (`cc`, so you
need gcc or clang installed). If you build the `dino` binary once, the commands are:
| Command | What it does |
|---------|--------------|
| `dino run file.dino [args...]` | Compile and run. Extra words are given to the program (`os.args`). |
| `dino build file.dino -o out` | Make an executable you can keep. |
| `dino check file.dino` | Look for errors without building. |
| `dino emit-c file.dino` | Print the generated C. |
| `dino fmt file-or-folder...` | Tidy the code in place (`--check` only reports). |
## print
`print` takes any number of values, separates them with spaces, and ends the line.
It can print numbers, strings, lists, maps, structs, enums and more.
```dino
func main() {
print("score:", 42, true)
print([1, 2, 3])
print(1.5 + 1.5)
}
```
```text
score: 42 true
[1, 2, 3]
3.0
```
Notice that a float always shows a `.0` so you can tell `3.0` from `3`.
## Comments
```dino
// a comment runs to the end of the line
func main() {
print("hi") // so does this
}
```
```text
hi
```
## Reading the error messages
Dino tries hard to explain mistakes. For example, forgetting that `int` and `float`
don't mix:
```text
error: can't use `int` and `float` together (convert with `float(x)`)
```
When a message offers a hint, try it. If it doesn't make sense, that is a bug in the
message and worth fixing.
## Your editor
`editors/` has colours, live error underlines and format-on-save for VS Code, Neovim, Vim and
Helix (any editor that can run a language server works). See `editors/README.md`. It is the
compiler itself doing the checking, so you see the same messages as in the terminal. The
server is started with `dino lsp`.
## Formatting your code
`dino fmt` rewrites your files in one standard style, so you never argue about spaces:
```text
dino fmt hello.dino # one file
dino fmt src/ # every .dino file in a folder
dino fmt --check src/ # change nothing; exit code 1 if something is untidy
```
It uses 4-space indents, one space around operators, `a: int` colons, `Point{x: 1}` literals,
and at most one blank line in a row. It keeps your comments and **never moves a line break**,
so how you split things across lines is up to you. Trailing `//` comments on neighbouring
lines are lined up. Before saving, it checks that the code means exactly the same thing, and
it refuses files that don't parse.
Next: [Values and types](02-values-and-types.md)
+207
View File
@@ -0,0 +1,207 @@
# 2. Values and types
## Variables
`var` makes a variable you can change. The type is worked out from the value.
```dino
func main() {
var score = 10
score = score + 5
score += 1
print(score)
var name: string = "Dino" // you may write the type after a colon
var ratio: float = 1 // a whole-number literal fits a float
print(name, ratio)
}
```
```text
16
Dino 1.0
```
`const` is a value that never changes. It must be known when the program is compiled
(you can't call functions in it).
```dino
const MAX = 100
const GREETING = "hi"
func main() {
print(MAX * 2, GREETING)
}
```
```text
200 hi
```
> **Types go after a colon, everywhere.** `var x: int`, `func f(a: int): string`,
> `struct S { x: float }`. If you forget, the compiler tells you what to add.
## The basic types
| Type | Example | Notes |
|------|---------|-------|
| `int` | `42` | 64-bit whole number |
| `float` | `3.14` | 64-bit decimal number |
| `bool` | `true`, `false` | |
| `char` | `'a'` | one character (see below) |
| `string` | `"text"` | UTF-8 text, can't be changed in place |
| `error` | `error("oops")` | see [Errors and nil](07-errors-and-nil.md) |
Sized numbers exist for when you need exact control: `i8 i16 i32 u8 u16 u32 u64 f32`
(`i64` is the same as `int`, `f64` the same as `float`).
```dino
func main() {
var small: u8 = 200
var wrapped = small + 100 // whole numbers wrap around: 300 - 256
print(wrapped)
var x = 7
var y = 2
print(x / y, x % y) // whole-number division
print(float(x) / float(y)) // convert before dividing for a decimal answer
}
```
```text
44
3 1
3.5
```
Rules worth remembering:
- Different number types never mix. Convert explicitly: `float(x)`, `int(y)`, `u8(z)`.
- A number literal adapts to the type it is used with (`var b: u8 = 5`).
- Dividing by zero stops the program with a clear message.
- Converting a float to an integer cuts off the decimals.
## Strings
Put values inside text with `{ }`. Write a literal brace as `\{`.
```dino
func main() {
var name = "Ada"
var age = 36
print("Hello {name}, next year you are {age + 1}.")
print("tab\there, quote \" and brace \{ok}")
var s = "Hello" + ", " + "world"
print(s.len(), s.upper(), s.contains("wor"))
}
```
```text
Hello Ada, next year you are 37.
tab here, quote " and brace {ok}
12 HELLO, WORLD true
```
Handy string methods: `len upper lower trim split lines fields replace repeat contains
starts_with ends_with index_of to_int to_float`. See the [cheatsheet](11-cheatsheet.md).
### Slicing
`s[a..b]` is the part from byte `a` up to (not including) `b`. Leave a side out to go to the edge.
```dino
func main() {
var s = "hello world"
print(s[0..5])
print(s[6..])
print(s[..5])
}
```
```text
hello
world
hello
```
A slice outside the string stops the program with a message that shows the length.
`s.len()` counts bytes, so a letter like `é` counts as 2.
### Characters: `char`
A `char` is **one character**, written with single quotes. Double quotes are for text.
```dino
func main() {
var c = 'a'
print(c, c == 'a', c < 'b')
print('é', '\n' == '\n') // any Unicode character; escapes: \n \t \r \0 \\ \'
print(int('a'), char(66)) // a character and its number
print(string(c) + "!") // a character as text: string(c), or "{c}"
}
```
```text
a true true
é true
97 B
a!
```
Going through a string gives characters:
```dino
func main() {
var s = "héllo 42"
var letters = 0
var digits = 0
for c in s {
if c.is_letter() { letters += 1 }
if c.is_digit() { digits += 1 }
}
print(letters, digits)
for i, c in "aé!" { print(i, c) } // i is the byte position
print(s[0], s[1], s[3]) // s[i] is the character that starts at byte i
}
```
```text
5 2
0 a
1 é
3 !
h é l
```
- `s.chars()` gives all the characters as a list (`[]char`), so you can index it by
character number: `var cs = "héllo".chars()` then `cs[1]` is `é` and `cs.len()` is 5.
- `for c in s` walks whole characters, even multi-byte ones like `é` or `😀`.
- `s[i]` takes a **byte** position. If the position is in the middle of a character, or
outside the string, the program stops with a message. For plain English text, position
and character number are the same.
- Strings can't be changed in place, so `s[0] = 'x'` is an error. Build a new string:
`up += string(c.upper())`.
- Methods: `is_digit is_letter is_alnum is_space is_upper is_lower upper lower`.
(`upper`/`lower` change plain English letters.)
- `char` can be compared (`== != < > <= >=`), matched with `match`, and used as a map key.
It does no arithmetic: use `int(c)` and `char(n)` if you need that.
```dino
func kind(c: char): string {
return match c {
'+' => "plus"
' ' => "space"
_ => "other"
}
}
func main() {
var counts: map[char, int] = {}
for c in "banana" { counts[c] += 1 }
print(counts, kind('+'), kind('x'))
}
```
```text
{b: 1, a: 3, n: 2} plus other
```
### Comparing
`==`, `!=`, `<`, `>` work on strings (alphabetical order).
Next: [Control flow](03-control-flow.md)
+140
View File
@@ -0,0 +1,140 @@
# 3. Control flow
## if / else
No parentheses around the condition. The braces are required. The condition must be a `bool`.
```dino
func main() {
var temp = 21
if temp > 30 {
print("hot")
} else if temp > 15 {
print("nice")
} else {
print("cold")
}
}
```
```text
nice
```
Combine conditions with `&&`, `||` and `!`. The right side only runs when needed.
## for: the only loop
There is one keyword for every kind of loop.
```dino
func main() {
for i in 0..3 { // 0, 1, 2: the end is not included
print("i =", i)
}
for i in 0..10 step 4 { // 0, 4, 8
print(i)
}
var names = ["ann", "bo"]
for n in names { // each item
print(n)
}
for i, n in names { // index and item
print(i, n)
}
var k = 0
for k < 3 { // while a condition holds
k += 1
}
print(k)
for { // forever, until break
k += 1
if k > 5 { break }
if k == 4 { continue }
}
print(k)
}
```
```text
i = 0
i = 1
i = 2
0
4
8
ann
bo
0 ann
1 bo
3
6
```
`break` leaves the loop; `continue` jumps to the next round. There is no C-style
`for (i = 0; i < n; i++)`.
Looping over a list walks it as it was when the loop started, so changing the list inside
the loop is safe.
## match
`match` picks a branch by shape. It must cover every possibility, otherwise the compiler
lists what is missing. `_` means "anything else".
```dino
enum Shape {
Circle(r: float)
Rect(w, h: float)
Point
}
func area(s: Shape): float {
return match s {
Circle(r) => 3.0 * r * r
Rect(w, h) => w * h
Point => 0.0
}
}
func describe(n: int): string {
return match n {
0 => "zero"
1 => "one"
_ => "many"
}
}
func main() {
print(area(Shape.Circle(2.0)), area(Shape.Rect(2.0, 3.0)), area(Shape.Point))
print(describe(0), describe(1), describe(7))
}
```
```text
12.0 6.0 0.0
zero one many
```
`match` works on enums, ints, bools and strings. Used as a **value** (like above) each arm
is one expression. Used as a **statement** an arm can be a block:
```dino
func main() {
var cmd = "stop"
match cmd {
"go" => print("going")
"stop" => {
print("stopping")
print("done")
}
_ => print("unknown")
}
}
```
```text
stopping
done
```
Next: [Functions](04-functions.md)
+132
View File
@@ -0,0 +1,132 @@
# 4. Functions
```dino
func add(a: int, b: int): int {
return a + b
}
func greet(name: string) { // no result: nothing after the parentheses
print("hi", name)
}
func main() {
print(add(2, 3))
greet("Ada")
}
```
```text
5
hi Ada
```
Names in a row can share a type: `func area(w, h: float): float`.
## Several results
A function can return more than one value. The most common use is a value and an `error`.
```dino
func divide(a, b: int): (int, error) {
if b == 0 {
return 0, error("cannot divide by zero")
}
return a / b, nil
}
func main() {
var q, err = divide(7, 2)
print(q, err)
var _, err2 = divide(1, 0)
print(err2)
}
```
```text
3 nil
cannot divide by zero
```
More in [Errors and nil](07-errors-and-nil.md).
## Parameters are safe
A parameter is a copy as far as you can tell: changing it inside never changes the caller's
variable. (When a function only *reads* a parameter, the compiler passes it without copying,
so big lists are free to pass around.)
```dino
func grow(xs: []int): []int {
xs.push(99)
return xs
}
func main() {
var a = [1, 2]
var b = grow(a)
print(a, b)
}
```
```text
[1, 2] [1, 2, 99]
```
## Functions are values
A function has a type like `func(int): int`. You can store it, pass it and return it.
```dino
func double(x: int): int { return x * 2 }
func apply(f: func(int): int, x: int): int {
return f(x)
}
func main() {
print(apply(double, 4))
var triple = func(x: int): int { return x * 3 }
print(apply(triple, 4))
print(apply(x => x + 1, 4)) // short form
}
```
```text
8
12
5
```
### Short lambdas
`x => x * 2` and `(a, b) => a + b` are shorthand for a one-expression function. The types
come from where it is used, so it works where Dino already knows what function is expected
(a parameter, a typed variable, a struct field, or another argument of a generic function).
The short form is one expression; for several statements use the long `func(x: int): int { }`.
### Closures remember
A function written inside another can use the variables around it. It **copies** them when
it is created and keeps its own copy from then on.
```dino
func make_counter(): func(): int {
var n = 0
return func(): int {
n += 1
return n
}
}
func main() {
var next = make_counter()
print(next(), next(), next())
var offset = 10
var add = func(x: int): int { return x + offset }
offset = 99 // the closure keeps its own 10
print(add(1))
}
```
```text
1 2 3
11
```
Next: [Lists and maps](05-lists-and-maps.md)
+196
View File
@@ -0,0 +1,196 @@
# 5. Lists and maps
## Lists: `[]T`
An ordered, growable sequence.
```dino
func main() {
var nums = [10, 20, 30]
nums.push(40)
nums[0] = 11
print(nums, nums.len(), nums[1])
print(nums.pop(), nums)
print(nums[1..3]) // a copy of part of the list
var names: []string // empty list: write the type
names.push("ann")
print(names)
var total = 0
for n in nums { total += n }
print(total)
}
```
```text
[11, 20, 30, 40] 4 20
40 [11, 20, 30]
[20, 30]
[ann]
61
```
Facts:
- An empty list needs a type: `var xs: []int`.
- Going outside the list (`nums[9]`) or popping an empty list stops the program with a message.
- **Lists are values.** `var b = a` copies the list. Changing `b` leaves `a` alone.
```dino
func main() {
var a = [1, 2, 3]
var b = a
b.push(4)
print(a, b)
}
```
```text
[1, 2, 3] [1, 2, 3, 4]
```
## Maps: `map[K, V]`
A map finds a value by a **key** instead of a position, like a phone book.
```dino
func main() {
var ages = {"alice": 30, "bob": 25}
ages["carol"] = 41 // add a new entry
ages["bob"] = 26 // change an existing one
print(ages["bob"], ages.len())
print(ages)
}
```
```text
26 3
{alice: 30, bob: 26, carol: 41}
```
### Making a map
```dino
func main() {
var a = {"x": 1, "y": 2} // types are guessed from the entries
var b: map[string, int] = {} // empty: the type comes from the variable
var c = map[int, string]{} // empty: the type is written on the right
b["z"] = 26
c[7] = "seven"
print(a, b, c)
}
```
```text
{x: 1, y: 2} {z: 26} {7: seven}
```
An empty `{}` always needs a type from one of those two places.
### Keys
A key can be an `int` (or another whole-number type), a `string` or a `bool`.
The value can be anything: numbers, strings, lists, structs, even other maps.
### Reading
| Code | Result |
|------|--------|
| `m[k]` | the value; **stops the program** if `k` is missing |
| `m.has(k)` | `true` or `false` |
| `m.get(k)` | the value or `nil` (type `V?`, see [Errors and nil](07-errors-and-nil.md)) |
| `m.get_or(k, d)` | the value, or `d` if `k` is missing |
| `m.len()` | number of entries |
| `m.keys()` | a list of the keys |
| `m.values()` | a list of the values |
```dino
func main() {
var stock = {"apple": 3, "pear": 0}
print(stock.has("apple"), stock.has("fig"))
print(stock.get("apple"), stock.get("fig"))
print(stock.get_or("fig", -1))
print(stock.keys(), stock.values())
}
```
```text
true false
3 nil
-1
[apple, pear] [3, 0]
```
### Changing
`m[k] = v` adds or replaces. `m.remove(k)` deletes (and does nothing if the key is missing).
```dino
func main() {
var m = {"a": 1, "b": 2}
m["c"] = 3
m.remove("a")
print(m)
}
```
```text
{b: 2, c: 3}
```
### Counting: `+=` starts from zero
The most common map job is counting. `m[k] += 1` on a key that isn't there yet starts from
zero, so you don't have to check first.
```dino
func main() {
var counts: map[string, int] = {}
for w in "a b a c b a".split(" ") {
counts[w] += 1
}
print(counts)
}
```
```text
{a: 3, b: 2, c: 1}
```
(Only the compound forms `+= -= *= /= %=` do this. Plain *reading* a missing key with `m[k]` still stops the program.)
### Looping
Entries come out **in the order they were added**, so output is always predictable.
```dino
func main() {
var prices = {"tea": 2.5, "cake": 4.0}
for name, price in prices {
print(name, "costs", price)
}
for name in prices { // just the keys
print(name)
}
}
```
```text
tea costs 2.5
cake costs 4.0
tea
cake
```
### Maps are values too
`var b = a` copies the whole map. A map inside a struct is copied with the struct.
```dino
func main() {
var a = {"x": 1}
var b = a
b["y"] = 2
print(a.len(), b.len())
}
```
```text
1 2
```
Looking things up is fast: it does not slow down as the map grows. (`remove` has to
re-arrange the entries to keep their order, so it is slower on huge maps.)
Next: [Structs and enums](06-structs-and-enums.md)
+139
View File
@@ -0,0 +1,139 @@
# 6. Structs and enums
## Structs
A struct groups related values. **Methods go inside the struct** and see the fields directly.
```dino
struct Player {
name: string
hp: int
x, y: float // names in a row share a type
func hurt(amount: int) { // changes hp, so Dino knows it modifies the player
hp -= amount
}
func alive(): bool {
return hp > 0
}
}
func main() {
var p = Player{name: "Ada", hp: 10} // fields left out start at zero
p.hurt(4)
print(p.hp, p.alive())
print(p)
}
```
```text
6 true
Player{name: Ada, hp: 6, x: 0.0, y: 0.0}
```
Ways to build one:
- Named: `Player{name: "Ada", hp: 10}`. Any field may be left out; it starts at `0`, `0.0`,
`false`, `""` or an empty list.
- Positional: `Vec2{1.0, 2.0}`. Every field must be given.
**You never write `mut`.** A method that assigns to a field is detected as changing the
struct, and the compiler stops you from calling it on a `const` or on a temporary.
Inside a method, a bare name means: a local or parameter first, then a field, then another
method of the same struct (`hurt(2)`), then a global function.
### Structs are values
```dino
struct Point { x, y: int }
func main() {
var a = Point{1, 2}
var b = a
b.x = 99
print(a, b)
}
```
```text
Point{x: 1, y: 2} Point{x: 99, y: 2}
```
`var b = a` is a real copy. If you want one value with several owners, see
[`shared`](08-memory.md).
### Methods that return values, and nested data
```dino
struct Vec2 {
x, y: float
func length_squared(): float {
return (x * x + y * y)
}
func plus(o: Vec2): Vec2 {
return Vec2{x + o.x, y + o.y}
}
}
struct Ship {
pos: Vec2
trail: []Vec2
}
func main() {
var s = Ship{pos: Vec2{1.0, 1.0}}
s.trail.push(s.pos)
s.pos = s.pos.plus(Vec2{2.0, 0.0})
print(s.pos, s.trail, s.pos.length_squared())
}
```
```text
Vec2{x: 3.0, y: 1.0} [Vec2{x: 1.0, y: 1.0}] 10.0
```
`==` on whole structs is not available yet; compare the fields.
## Enums
An enum is "one of these cases", and each case can carry data.
```dino
enum Event {
Quit
Key(code: int)
Click(x, y: int)
func describe(): string {
return match self {
Quit => "quit"
Key(c) => "key {c}"
Click(x, y) => "click at {x},{y}"
}
}
}
func main() {
var e = Event.Click(3, 4)
print(e.describe())
print(Event.Key(65), Event.Quit)
}
```
```text
click at 3,4
Event.Key(65) Event.Quit
```
- Build a value with the qualified name: `Event.Key(65)`, `Event.Quit`.
- Take it apart with [`match`](03-control-flow.md#match), which must cover every case.
- Inside an enum's methods, `self` is the whole value.
- The zero value of an enum is its first case.
- `==` works on enums whose cases carry no data.
## Privacy
Everything is private to its file unless you write `pub`. This matters once you split a
program into several files ([next chapters](10-modules-and-stdlib.md)). Inside one file you
never need `pub`.
Next: [Errors and nil](07-errors-and-nil.md)
+123
View File
@@ -0,0 +1,123 @@
# 7. Errors and nil
Dino has no exceptions. A function that can fail says so in its result, and you handle it.
## error
`error` is a type that is either `nil` (all fine) or holds a message.
```dino
func parse_age(s: string): (int, error) {
var n, err = s.to_int()
if err != nil {
return 0, error("'{s}' is not a number")
}
if n < 0 {
return 0, error("age can't be negative")
}
return n, nil
}
func main() {
var a, err = parse_age("42")
print(a, err)
var b, err2 = parse_age("abc")
print(b, err2)
}
```
```text
42 nil
0 'abc' is not a number
```
- `error("text {value}")` makes an error. It can use `{ }` like any string.
- `var value, err = f()` takes both results. Use `_` to ignore one.
- You can't silently ignore an error: calling a function that returns an error as a bare
statement is a compile error.
## `?`: pass the problem up
Writing `?` after a call means "if this failed, return the error from *my* function too".
Otherwise you get the value.
```dino
func half(n: int): (int, error) {
if n % 2 != 0 { return 0, error("{n} is odd") }
return n / 2, nil
}
func quarter(n: int): (int, error) {
var h = half(n)?
var q = half(h)?
return q, nil
}
func main() {
var a, err = quarter(8)
print(a, err)
var b, err2 = quarter(6)
print(b, err2)
}
```
```text
2 nil
0 3 is odd
```
`?` works in any function whose last result is `error`. `func main(): error` is allowed:
if it returns an error, the program prints `error: message` and exits with code 1.
## Optional values: `T?`
A `T?` is either a `T` or `nil`. It is how Dino says "this might be missing".
```dino
func find(names: []string, wanted: string): int? {
for i, n in names {
if n == wanted { return i }
}
return nil
}
func main() {
var names = ["ann", "bo", "cy"]
var at = find(names, "bo")
if at != nil {
print("found at", at)
}
var missing = find(names, "zed")
print(missing == nil)
}
```
```text
found at 1
true
```
The compiler **requires** the check. It knows a value is set:
- inside `if x != nil { ... }`
- after `if x == nil { return }` (or `break` / `continue`)
- on the right side of `x != nil && ...`
Assigning to `x` makes the compiler forget that. (And even so, using a `nil` value stops the
program with a message instead of misbehaving.)
Maps give you optionals too:
```dino
func main() {
var ports = {"http": 80}
var p = ports.get("https")
if p == nil {
print("no https")
}
}
```
```text
no https
```
Not available yet: `T?` as a struct field or list item, and `??`.
Next: [Memory](08-memory.md)
+140
View File
@@ -0,0 +1,140 @@
# 8. Memory: copies, sharing, and weak pointers
You never write `free`, `new` or `&`. Here is what the compiler does for you.
## One owner
Every value has exactly one owner: a variable, a field, a list slot. When the owner's block
ends, the value is freed. That is true for strings, lists, maps, structs, enums and errors,
and it also happens on an early `return`, `break`, `continue` or `?`.
Giving a value a new owner **copies** it:
```dino
func main() {
var a = [1, 2, 3]
var b = a // b is a real copy
b.push(4)
print(a, b)
}
```
```text
[1, 2, 3] [1, 2, 3, 4]
```
You don't pay for copies you don't need:
- If `a` is never used again, `var b = a` just *moves* the value, with no copying.
- A function that only reads a parameter gets it without a copy.
- Returning a local variable moves it out.
- Strings are immutable and counted, so copying one only bumps a counter.
All tests of the compiler run under a memory checker, so leaks and double frees are caught.
## shared: one value, several owners
Sometimes you really do want several owners of **one** value (a texture used by many
sprites, a window and its buttons). Write `shared`:
```dino
struct Texture {
name: string
uses: int
func touch() { uses += 1 }
}
struct Sprite {
tex: shared Texture
x: int
}
func main() {
var tex = shared Texture{"grass", 0}
var a = Sprite{tex, 1}
var b = Sprite{tex, 2}
a.tex.touch()
b.tex.touch()
print(tex.uses, a.tex.uses)
}
```
```text
2 2
```
- `shared Texture{...}` creates the shared value. The type is written `shared Texture`.
- `var b = a`, passing it to a function, or putting it in a list or field gives another
**owner** instead of copying the value.
- A change through any owner is seen by all.
- The value is freed when the **last** owner goes away.
- Use it just like the value inside: `tex.name`, `tex.touch()`.
- Only structs and enums can be shared for now.
## weak: pointing without owning
If a window owns its buttons and each button owns its window, neither would ever be freed.
Make one side `weak`: it points at the value without keeping it alive.
```dino
struct Window {
title: string
buttons: []shared Button
func add(b: shared Button) { buttons.push(b) }
}
struct Button {
label: string
window: weak Window
func click() {
if window != nil {
print(label, "clicked in", window.title)
} else {
print(label, "clicked, window is gone")
}
}
}
func main() {
var win = shared Window{"Main", []}
var ok = shared Button{"OK", weak win}
win.add(ok)
ok.click()
win = shared Window{"Other", []} // the first window is freed
ok.click()
}
```
```text
OK clicked in Main
OK clicked, window is gone
```
- `weak x` makes a weak pointer to the shared value `x`.
- A weak pointer is **nilable**: `w == nil` tells you the value is gone. `weak T` and
`weak T?` mean the same thing, and it starts as `nil`.
- Using a gone weak pointer stops the program with a clear message.
- To use the value as an owner, call `w.upgrade()`. It gives a `shared T?`: the value
(now with one more owner, so it can't vanish while you hold it) or `nil`.
```dino
struct Node { name: string }
func main() {
var n = shared Node{"root"}
var w = weak n
var again = w.upgrade()
if again != nil {
print(again.name)
}
}
```
```text
root
```
**Rule of thumb:** the owner of something holds it `shared`; anything that merely points
back at it (a child to its parent, a button to its window) holds it `weak`.
Next: [Generics and interfaces](09-generics-and-interfaces.md)
+184
View File
@@ -0,0 +1,184 @@
# 9. Generics and interfaces
## Generic functions
Put the type names in `[ ]` after the function name. The compiler works the real types out
from the arguments.
```dino
func first[T](xs: []T): T {
return xs[0]
}
func biggest[T: Ordered](a, b: T): T {
if a > b { return a }
return b
}
func main() {
print(first([7, 8, 9]), first(["x", "y"]))
print(biggest(3, 9), biggest("pear", "apple"), biggest(1.5, 0.5))
}
```
```text
7 x
9 pear 1.5
```
After the colon you can name a **rule** for the type:
| Rule | Meaning |
|------|---------|
| `Ordered` | can be compared with `<` `>` (numbers and strings) |
| `Number` | numbers only |
| an interface | has certain methods (see below) |
| *(none)* | anything |
Generics cost nothing at run time: every set of types gets its own compiled copy.
A generic function can take functions too, which makes `map` and `filter` easy to write:
```dino
func map[T, U](xs: []T, f: func(T): U): []U {
var out: []U
for x in xs { out.push(f(x)) }
return out
}
func main() {
print(map([1, 2, 3], x => x * 10))
print(map(["a", "bb"], s => s.len()))
}
```
```text
[10, 20, 30]
[1, 2]
```
## Generic types
Structs and enums can take types too. When you **use** one, write the types out.
```dino
struct Stack[T] {
items: []T
func push_item(x: T) { items.push(x) }
func pop_item(): T { return items.pop() }
func size(): int { return items.len() }
}
enum Maybe[T] {
Some(value: T)
None
}
func main() {
var s = Stack[int]{}
s.push_item(1)
s.push_item(2)
print(s.pop_item(), s.size())
var m = Maybe[string].Some("hi")
print(m)
}
```
```text
2 1
Maybe[string].Some(hi)
```
## Interfaces
An interface lists methods. A type follows it just by having those methods, with no
`implements` keyword.
```dino
interface Shape {
area(): float
name(): string
}
struct Square {
side: float
func area(): float { return side * side }
func name(): string { return "square" }
}
struct Circle {
r: float
func area(): float { return 3.0 * r * r }
func name(): string { return "circle" }
}
```
### As a rule for generics
```dino
interface Shape {
area(): float
}
struct Square {
side: float
func area(): float { return side * side }
}
func report[T: Shape](s: T) {
print("area is", s.area())
}
func main() {
report(Square{3.0})
}
```
```text
area is 9.0
```
### As a type (dynamic dispatch)
An interface is also a type of its own. A variable of that type can hold any value that has
the methods, and the right method runs at run time. This is how you build a mixed list.
```dino
interface Shape {
area(): float
name(): string
}
struct Square {
side: float
func area(): float { return side * side }
func name(): string { return "square" }
}
struct Circle {
r: float
func area(): float { return 3.0 * r * r }
func name(): string { return "circle" }
}
func main() {
var shapes: []Shape = [Square{2.0}, Circle{1.0}]
for s in shapes {
print(s.name(), s.area())
}
var one: Shape = Circle{2.0}
print(one.area())
}
```
```text
square 4.0
circle 3.0
12.0
```
Details:
- A struct or enum value converts to the interface automatically. The value is copied in.
- `nil` is the empty interface value; calling a method on it stops the program.
- Not yet: turning an interface value back into its original type, and interfaces that take
their own type parameters.
Next: [Files and the standard library](10-modules-and-stdlib.md)
+123
View File
@@ -0,0 +1,123 @@
# 10. Files and the standard library
## Splitting a program into files
`import utils` brings in the file `utils.dino` that sits next to your main file. Use its
contents with the module name in front. Only things marked `pub` can be used from outside.
`utils.dino`:
```dino
pub const SCALE = 10
pub struct Vec2 {
pub x, y: float
pub func scaled(k: float): Vec2 { return Vec2{x * k, y * k} }
}
pub func double(n: int): int { return n * 2 }
func secret() {} // private: only this file can call it
```
`main.dino`:
```dino
import utils
func main() {
print(utils.double(4), utils.SCALE)
var v = utils.Vec2{1.0, 2.0}
print(v.scaled(3.0))
}
```
- Folders work too: `import tools.fs` is the file `tools/fs.dino`, used as `fs.name`.
- Fields are private as well unless written `pub x: int`.
- Every file has its own names, so two files can both define `helper`.
- Import loops and missing files are errors. An error message names the file it is in.
## Built-in modules
Import them like your own files: `import os`.
### os
| | |
|--|--|
| `os.args` | list of command-line words (`args[0]` is the program) |
| `os.read_file(path)` | `(string, error)` |
| `os.write_file(path, text)` | `error` |
| `os.append_file(path, text)` | `error` |
| `os.exists(path)` | `bool` |
| `os.read_line()` | next line typed on the keyboard, or `nil` at the end |
| `os.env(name)` | the environment variable, or `nil` |
| `os.exit(code)` | stop the program |
### math
`sqrt pow floor ceil round trunc sin cos tan asin acos atan atan2 exp log log10 hypot
min max abs`, and the values `PI` and `E`.
```dino
import math
func main() {
print(math.sqrt(16), math.pow(2, 10), math.max(3, 9), math.PI)
}
```
```text
4.0 1024.0 9 3.14159265358979
```
### time
`time.now()` gives seconds as a float. `time.sleep(seconds)` waits.
### Strings
`upper lower trim split lines fields replace repeat contains starts_with ends_with
index_of to_int to_float`, plus `len()` and slicing.
```dino
func main() {
var csv = " a, b ,c "
for part in csv.split(",") {
print("[" + part.trim() + "]")
}
print("x".repeat(3), "Hello".lower(), "a-b".replace("-", "+"))
print("hello".index_of("l"), "hello".index_of("z"))
}
```
```text
[a]
[b]
[c]
xxx hello a+b
2 -1
```
A list of strings can be joined: `["a", "b"].join("-")`.
## A program that reads input
```dino
import os
func main() {
var total = 0
for {
var line = os.read_line()
if line == nil { break }
var n, err = line.trim().to_int()
if err != nil {
print("skipping:", line)
continue
}
total += n
}
print("total", total)
}
```
Next: [Cheatsheet](11-cheatsheet.md)
+127
View File
@@ -0,0 +1,127 @@
# 11. Cheatsheet
## Basics
```dino
var x = 1 // changeable; type inferred
var y: float = 2 // with a type
const MAX = 100 // fixed
x += 1 // also -= *= /= %=
print("x is {x}", y) // interpolation with { }
```
## Types
`int float bool char string error` · sized: `i8 i16 i32 u8 u16 u32 u64 f32` · `[]T` list ·
`map[K, V]` map · `T?` optional · `shared T` · `weak T` · `func(A, B): R` function.
Convert numbers with `float(x)`, `int(x)`, `u8(x)`.
## Control flow
```dino
if a > b { } else if a == b { } else { }
for i in 0..10 { } // 0..9
for i in 0..10 step 2 { }
for x in list { }
for i, x in list { }
for k, v in map { }
for cond { }
for { break }
match v { 1 => a, _ => b }
```
## Functions
```dino
func add(a, b: int): int { return a + b }
func f(): (int, error) { return 1, nil }
var n, err = f()
var n = f()? // inside a function that returns error
var g = func(x: int): int { return x * 2 }
var h = x => x * 2 // where the type is known
```
## Lists
```dino
var xs = [1, 2, 3] var e: []int
xs.push(4) xs.pop() xs.len()
xs[0] xs[0] = 9 xs[1..3]
```
## Maps
```dino
var m = {"a": 1} var e: map[string, int] = {}
var e2 = map[string, int]{}
m["b"] = 2 // add or replace
m["b"] += 1 // missing key counts as zero
m["a"] // value; stops if missing
m.has("a") m.get("a") // bool, value-or-nil
m.get_or("z", 0) m.len() m.keys() m.values() m.remove("a")
```
## Strings
```dino
s.len() s.upper() s.lower() s.trim() s.split(",") s.lines() s.fields()
s.replace(a, b) s.repeat(n) s.contains(x) s.starts_with(x) s.ends_with(x)
s.index_of(x) s.to_int() s.to_float() s[1..4] s[2..] s[..3]
["a", "b"].join("-")
```
## Characters
```dino
var c = 'a' '\n' 'é' // one character, single quotes
c == 'a' c < 'z' // compare
c.is_digit() c.is_letter() c.is_alnum() c.is_space() c.is_upper() c.is_lower()
c.upper() c.lower()
int(c) char(97) string(c) "{c}" // number <-> char, char -> text
for c in s { } for i, c in s { } // walk a string; i = byte position
s[i] // the char starting at byte i
```
## Structs and enums
```dino
struct P {
name: string
x, y: float
func move(dx: float) { x += dx } // mutation is inferred
}
var p = P{name: "a"} // or positional: P{"a", 0.0, 0.0}
enum E {
A
B(n: int)
}
E.B(3) match e { A => 1, B(n) => n }
```
## Errors and nil
```dino
error("message {x}") err != nil return 0, nil
var v: int? = nil if v != nil { v } if v == nil { return }
```
## Sharing
```dino
var a = shared T{...} var b = a // same value, two owners
var w = weak a w.upgrade() // shared T? (nil if gone)
```
## Generics and interfaces
```dino
func first[T](xs: []T): T { return xs[0] }
func big[T: Ordered](a, b: T): T { ... } // Ordered, Number, or an interface
struct Stack[T] { items: []T } Stack[int]{}
interface Shape { area(): float } // follow it by having the methods
var s: Shape = Circle{1.0}
```
## Files
```dino
import utils // utils.dino next to this file
import tools.fs // tools/fs.dino, used as fs.name
import os // built-in: os math time
pub func f() {} // visible to other files
```
## Commands
`dino run f.dino args…` · `dino build f.dino -o out` · `dino check f.dino` · `dino emit-c f.dino` · `dino fmt path` (`--check` to only report) · `dino lsp` (editor server)
## Things that stop the program (exit code 2)
Divide by zero · list index/slice out of range · `pop` on an empty list · reading a missing
map key with `m[k]` · using a `nil` or gone `weak` value · calling a `nil` function or interface.
+99
View File
@@ -0,0 +1,99 @@
# 12. A real program: the calculator
The folder `examples/calc/` holds a calculator split over five files. It uses almost
everything from these notes. Run it:
```text
cargo run -q -- run examples/calc/main.dino examples/calc/session.txt
```
or type calculations interactively by leaving off the file name.
```text
1 + 2 * 3 = 7.0
2 ^ 3 ^ 2 = 512.0
x = 4
x * 2 + pi = 11.1415926535898
sqrt(16) + max(1, 5)
```
## The pieces
| File | Job | Features it shows |
|------|-----|-------------------|
| `token.dino` | Turns text into tokens | enums, structs, `char`, string slicing, errors |
| `ast.dino` | The shape of a calculation | an enum that holds other nodes |
| `parser.dino` | Builds the tree | a struct with methods, `?`, recursion |
| `eval.dino` | Computes the answer | `match`, maps, function values, closures |
| `main.dino` | Reads lines and prints | `import`, `os`, `shared` |
## 1. Tokens
`"2 * (3 + 4)"` becomes a list of small pieces: a number, an operator, an open
parenthesis and so on. Each has a kind (an enum), its text and its position, so errors can
say "at column 5".
The tokenizer looks at one character at a time (`var c = src[i]`) and decides what
kind of token starts there: `c.is_digit()` starts a number, `c.is_letter()` a name, and so on.
`src[start..i]` cuts the finished piece out of the text.
## 2. The tree
```dino
pub enum Node {
Num(value: float)
Var(name: string)
Neg(inner: []Node)
Bin(op: string, sides: []Node)
Call(name: string, args: []Node)
Assign(name: string, value: []Node)
}
```
An enum can't contain itself directly, so the parts that hold other nodes use a list
(`[]Node`) with one or more items.
## 3. The parser
One method per level of precedence: `sum` calls `product`, which calls `unary`, which calls
`power`, which calls `atom`. Each returns `(Node, error)` and the callers pass problems up
with `?`.
## 4. The evaluator
The scope that remembers variables and functions is two maps:
```dino
pub struct Scope {
variables: map[string, float]
builtins: map[string, Builtin]
...
}
```
A built-in function is a struct holding its name, how many arguments it takes, and a
function value:
```dino
s.builtins["sqrt"] = Builtin{"sqrt", 1, a => math.sqrt(a[0])}
```
`eval` is one big `match` on the node. Looking up a variable is `variables.get(name)`,
which gives `nil` when it isn't there, turned into a friendly error.
## 5. The main file
The scope is created once as `shared`, so every line sees the variables set by the
lines before it, with no need to pass the scope back and forth:
```dino
var scope = shared eval.new_scope()
...
run_line(scope, line)
```
## Try changing it
- Add a function `sin(x)` next to `sqrt`.
- Add `%` as an operator in the tokenizer, parser and `apply`.
- Make `sum` accept any number of arguments.
+50
View File
@@ -0,0 +1,50 @@
# Dino: learn the language
Dino is a small, fast, modern language. It looks like Go, runs like C, and has no
garbage collector, no pointers, and nothing low-level to write. You write plain code;
the compiler works out the memory.
These notes teach it from zero. Read them in order, or jump to the
[cheatsheet](11-cheatsheet.md) when you just need to look something up.
| # | Note | What you learn |
|---|------|----------------|
| 1 | [First steps](01-first-steps.md) | Running a program, `print`, `main` |
| 2 | [Values and types](02-values-and-types.md) | `var`, `const`, numbers, strings |
| 3 | [Control flow](03-control-flow.md) | `if`, `for`, `match` |
| 4 | [Functions](04-functions.md) | Parameters, results, closures |
| 5 | [Lists and maps](05-lists-and-maps.md) | Collections |
| 6 | [Structs and enums](06-structs-and-enums.md) | Your own types, methods |
| 7 | [Errors and nil](07-errors-and-nil.md) | `error`, `?`, `T?` |
| 8 | [Memory](08-memory.md) | Copies, `shared`, `weak` |
| 9 | [Generics and interfaces](09-generics-and-interfaces.md) | Code that works for many types |
| 10 | [Files and the standard library](10-modules-and-stdlib.md) | `import`, `os`, `math`, `time` |
| 11 | [Cheatsheet](11-cheatsheet.md) | Everything on one page |
| 12 | [A real program](12-calculator-walkthrough.md) | A calculator, split over five files |
## How to read the examples
Every `dino` block that has a `func main` is a complete program you can save and run.
The block right after it (marked `text`) shows what it prints.
````
```dino
func main() {
print("hello")
}
```
```text
hello
```
````
## The four ideas behind Dino
1. **Values.** `var b = a` makes a real copy. Change `b` and `a` stays the same.
There are no hidden aliases, which makes programs easy to reason about.
2. **The compiler infers.** You don't write `mut`, lifetimes or `&`. A method that changes
its struct is detected automatically; a parameter that is only read is passed without a copy.
3. **Errors are values.** Functions return `(value, error)` and you pass problems up with `?`.
Missing values are `T?` and the compiler makes you check for `nil`.
4. **Sharing is explicit.** When you really want one value with several owners, you
write `shared`. Everything else has exactly one owner and is freed at the end of its block.
+111
View File
@@ -0,0 +1,111 @@
# Editor support for Dino
Everything here talks to the compiler itself, so what you see in the editor is exactly what
`dino run` would tell you.
| You get | How |
|---------|-----|
| Syntax colours | a grammar file (VS Code, Neovim, Vim) |
| Errors underlined as you type | the language server, `dino lsp` |
| Format the file (and on save) | the same server, using `dino fmt` |
| Outline, go to definition, hover, completion, parameter hints | the same server (reads the file's names; no type checking) |
First put the `dino` program on your `PATH`:
```text
cargo build --release
cp target/release/dino ~/.local/bin/ # or anywhere on your PATH
```
## VS Code
The extension is in `editors/vscode/`.
```text
cd editors/vscode
npm install # downloads the small language-client library
npx @vscode/vsce package # makes dino-0.1.0.vsix
code --install-extension dino-0.1.0.vsix
```
To try it without installing, open the `editors/vscode` folder in VS Code and press **F5**.
If `dino` is not on your `PATH`, set **Dino: Server Path** in the settings to the full path.
Format-on-save and 4-space indents are switched on for `.dino` files by default.
## Neovim
Put the `vim/` folder on your runtime path to get file detection and colours, for example
(with a plugin manager that takes a local path), or copy the two files:
```text
mkdir -p ~/.config/nvim/syntax ~/.config/nvim/ftdetect
cp vim/syntax/dino.vim ~/.config/nvim/syntax/
cp vim/ftdetect/dino.vim ~/.config/nvim/ftdetect/
```
Then in `init.lua` (Neovim 0.8 or newer):
```lua
vim.api.nvim_create_autocmd("FileType", {
pattern = "dino",
callback = function(args)
vim.lsp.start({
name = "dino",
cmd = { "dino", "lsp" },
root_dir = vim.fs.dirname(args.file),
})
vim.bo.shiftwidth = 4
vim.bo.expandtab = true
end,
})
-- format when saving
vim.api.nvim_create_autocmd("BufWritePre", {
pattern = "*.dino",
callback = function() vim.lsp.buf.format({ async = false }) end,
})
```
Plain Vim gets the colours from the same two files (no language server).
## Helix
Add this to `~/.config/helix/languages.toml`:
```toml
[language-server.dino]
command = "dino"
args = ["lsp"]
[[language]]
name = "dino"
scope = "source.dino"
file-types = ["dino"]
comment-token = "//"
indent = { tab-width = 4, unit = " " }
language-servers = ["dino"]
auto-format = true
```
## Any other editor
Anything that can run a language server works: start `dino lsp` (it speaks the standard
protocol over stdin/stdout) for files ending in `.dino`. It supports diagnostics and
whole-file formatting. The grammar for colours is the TextMate file
`vscode/syntaxes/dino.tmLanguage.json`, which Sublime Text, Zed and many others can read.
## What the server does (and doesn't) do yet
- Checks the file every time you type, including the files it imports (from disk, or from
unsaved changes in other open files). The compiler stops at the first error, so you see
one underline at a time.
- An error inside an imported file is shown at the top of the file that imports it.
- Formats the whole file; a file that doesn't parse is left alone.
- Not yet: hover, go to definition, completion, rename.
## Opcode
Opcode (the C++ editor in `~/Desktop/Porn/Linux/Clean/opcode`) knows Dino out of the box: colours,
`//` comments, snippets, the outline, format with `dino fmt -`, and the language server
(`dino lsp`) for errors, go to definition, hover, completion and parameter hints. It only needs
`dino` on your `PATH` (see the top of this page).
+1
View File
@@ -0,0 +1 @@
autocmd BufRead,BufNewFile *.dino setfiletype dino
+37
View File
@@ -0,0 +1,37 @@
" Vim / Neovim syntax highlighting for Dino
if exists("b:current_syntax")
finish
endif
syn keyword dinoControl if else for in step match return break continue
syn keyword dinoDeclare func var const import struct enum interface pub
syn keyword dinoModifier shared weak
syn keyword dinoConstant true false nil
syn keyword dinoType int float bool char string error map i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
syn match dinoTypeName "\<[A-Z][A-Za-z0-9_]*\>"
syn match dinoNumber "\<[0-9][0-9_]*\(\.[0-9][0-9_]*\)\?\>"
syn match dinoCall "\<[a-z_][A-Za-z0-9_]*\ze\s*("
syn match dinoOperator "=>\|\.\.\|==\|!=\|<=\|>=\|&&\|||\|[-+*/%]=\?\|[<>!?=]"
syn match dinoEscape "\\." contained
syn region dinoInterp matchgroup=dinoInterpEdge start="{" end="}" contained contains=TOP
syn region dinoString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=dinoEscape,dinoInterp
syn match dinoChar "'\(\\.\|[^'\\]\)'"
syn region dinoComment start="/\*" end="\*/"
syn match dinoComment "//.*$"
hi def link dinoControl Conditional
hi def link dinoDeclare Keyword
hi def link dinoModifier StorageClass
hi def link dinoConstant Constant
hi def link dinoType Type
hi def link dinoTypeName Type
hi def link dinoNumber Number
hi def link dinoCall Function
hi def link dinoOperator Operator
hi def link dinoEscape SpecialChar
hi def link dinoInterpEdge Delimiter
hi def link dinoString String
hi def link dinoChar Character
hi def link dinoComment Comment
let b:current_syntax = "dino"
+26
View File
@@ -0,0 +1,26 @@
// Starts `dino lsp` and connects the editor to it. All the work is done by the compiler.
const vscode = require('vscode');
const { LanguageClient } = require('vscode-languageclient/node');
let client;
function activate() {
const command = vscode.workspace.getConfiguration('dino').get('serverPath') || 'dino';
client = new LanguageClient(
'dino',
'Dino Language Server',
{ command, args: ['lsp'] },
{ documentSelector: [{ scheme: 'file', language: 'dino' }] }
);
client.start().catch((err) => {
vscode.window.showErrorMessage(
`Could not start "${command} lsp": ${err.message}. Put the dino program on your PATH or set "dino.serverPath".`
);
});
}
function deactivate() {
return client ? client.stop() : undefined;
}
module.exports = { activate, deactivate };
@@ -0,0 +1,19 @@
{
"comments": { "lineComment": "//", "blockComment": ["/*", "*/"] },
"brackets": [["{", "}"], ["[", "]"], ["(", ")"]],
"autoClosingPairs": [
{ "open": "{", "close": "}" },
{ "open": "[", "close": "]" },
{ "open": "(", "close": ")" },
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "'", "close": "'", "notIn": ["string", "comment"] }
],
"surroundingPairs": [["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"]],
"indentationRules": {
"increaseIndentPattern": "[\\{\\[\\(]\\s*(//.*)?$",
"decreaseIndentPattern": "^\\s*[\\}\\]\\)]"
},
"onEnterRules": [
{ "beforeText": "^\\s*//.*$", "action": { "indent": "none", "appendText": "// " } }
]
}
+47
View File
@@ -0,0 +1,47 @@
{
"name": "dino",
"displayName": "Dino",
"description": "Syntax highlighting, error checking and formatting for the Dino language",
"version": "0.1.0",
"publisher": "dino-lang",
"license": "MIT",
"engines": { "vscode": "^1.75.0" },
"categories": ["Programming Languages", "Formatters"],
"activationEvents": ["onLanguage:dino"],
"main": "./extension.js",
"dependencies": { "vscode-languageclient": "^9.0.1" },
"contributes": {
"languages": [
{
"id": "dino",
"aliases": ["Dino", "dino"],
"extensions": [".dino"],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "dino",
"scopeName": "source.dino",
"path": "./syntaxes/dino.tmLanguage.json"
}
],
"configuration": {
"title": "Dino",
"properties": {
"dino.serverPath": {
"type": "string",
"default": "dino",
"description": "The `dino` program that provides the language server (it is started as `dino lsp`)."
}
}
},
"configurationDefaults": {
"[dino]": {
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.formatOnSave": true
}
}
}
}
@@ -0,0 +1,103 @@
{
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
"name": "Dino",
"scopeName": "source.dino",
"patterns": [
{ "include": "#comments" },
{ "include": "#strings" },
{ "include": "#chars" },
{ "include": "#declarations" },
{ "include": "#keywords" },
{ "include": "#constants" },
{ "include": "#numbers" },
{ "include": "#types" },
{ "include": "#calls" },
{ "include": "#operators" }
],
"repository": {
"comments": {
"patterns": [
{ "name": "comment.line.double-slash.dino", "match": "//.*$" },
{ "name": "comment.block.dino", "begin": "/\\*", "end": "\\*/" }
]
},
"strings": {
"name": "string.quoted.double.dino",
"begin": "\"",
"end": "\"",
"patterns": [
{ "name": "constant.character.escape.dino", "match": "\\\\." },
{
"name": "meta.interpolation.dino",
"begin": "\\{",
"end": "\\}",
"beginCaptures": { "0": { "name": "punctuation.section.interpolation.begin.dino" } },
"endCaptures": { "0": { "name": "punctuation.section.interpolation.end.dino" } },
"patterns": [{ "include": "$self" }]
}
]
},
"chars": {
"name": "string.quoted.single.dino",
"match": "'(?:\\\\.|[^'\\\\])'",
"captures": {}
},
"declarations": {
"patterns": [
{
"match": "\\b(func)\\s+([A-Za-z_][A-Za-z0-9_]*)",
"captures": {
"1": { "name": "keyword.declaration.function.dino" },
"2": { "name": "entity.name.function.dino" }
}
},
{
"match": "\\b(struct|enum|interface)\\s+([A-Za-z_][A-Za-z0-9_]*)",
"captures": {
"1": { "name": "keyword.declaration.type.dino" },
"2": { "name": "entity.name.type.dino" }
}
}
]
},
"keywords": {
"patterns": [
{ "name": "keyword.control.dino", "match": "\\b(if|else|for|in|step|match|return|break|continue)\\b" },
{ "name": "keyword.declaration.dino", "match": "\\b(func|var|const|import|struct|enum|interface|pub)\\b" },
{ "name": "storage.modifier.dino", "match": "\\b(shared|weak)\\b" }
]
},
"constants": {
"name": "constant.language.dino",
"match": "\\b(true|false|nil)\\b"
},
"numbers": {
"name": "constant.numeric.dino",
"match": "\\b[0-9][0-9_]*(?:\\.[0-9][0-9_]*)?\\b"
},
"types": {
"patterns": [
{
"name": "support.type.builtin.dino",
"match": "\\b(int|float|bool|char|string|error|map|i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)\\b"
},
{ "name": "entity.name.type.dino", "match": "\\b[A-Z][A-Za-z0-9_]*\\b" }
]
},
"calls": {
"name": "entity.name.function.call.dino",
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*\\()"
},
"operators": {
"patterns": [
{ "name": "keyword.operator.arrow.dino", "match": "=>" },
{ "name": "keyword.operator.range.dino", "match": "\\.\\." },
{ "name": "keyword.operator.comparison.dino", "match": "==|!=|<=|>=|<|>" },
{ "name": "keyword.operator.logical.dino", "match": "&&|\\|\\||!" },
{ "name": "keyword.operator.assignment.dino", "match": "[-+*/%]?=" },
{ "name": "keyword.operator.arithmetic.dino", "match": "[-+*/%]" },
{ "name": "keyword.operator.optional.dino", "match": "\\?" }
]
}
}
}
+29
View File
@@ -0,0 +1,29 @@
// A small CLI tool: count lines and words in files.
import os
struct Stats {
lines: int
words: int
}
func count(path: string): (Stats, error) {
var text = os.read_file(path)? // ? returns the error to the caller
var stats = Stats{}
for line in text.lines() {
stats.lines += 1
stats.words += line.fields().len()
}
return stats, nil
}
func main() {
var args = os.args
for path in args[1..] {
var s, err = count(path)
if err != nil {
print("{path}: error: {err}")
continue
}
print("{path}: {s.lines} lines, {s.words} words")
}
}
+33
View File
@@ -0,0 +1,33 @@
// A game: bouncing square. Structs are values, no heap, no GC.
import gfx
struct Vec2 {
x, y: f32
func add(b: Vec2): Vec2 { return Vec2{x + b.x, y + b.y} }
func scale(k: f32): Vec2 { return Vec2{x * k, y * k} }
}
struct Player {
pos: Vec2
vel: Vec2
size: f32
func update(dt: f32) { // writes pos/vel: inferred as mutating
pos = pos.add(vel.scale(dt))
if pos.x < 0 || pos.x > 800 { vel.x = -vel.x }
if pos.y < 0 || pos.y > 600 { vel.y = -vel.y }
}
}
func main() {
var win = gfx.open("Dino", 800, 600)
var player = Player{pos: Vec2{100, 100}, vel: Vec2{200, 150}, size: 32}
for win.is_open() {
player.update(win.dt())
win.clear(gfx.BLACK)
win.rect(player.pos.x, player.pos.y, player.size, player.size, gfx.GREEN)
win.present()
}
}
+32
View File
@@ -0,0 +1,32 @@
// A desktop-style app: shared state, weak back-references, tasks.
import ui
import task
struct Document {
title: string
text: string
}
struct Editor {
doc: shared Document // many views can share one document
parent: weak Window? // weak: no ownership cycle
}
func main() {
var doc = shared Document{title: "Notes", text: ""}
var win = ui.window("Dino Notes", 640, 480)
var editor = Editor{doc: doc}
win.on_key(func(k: ui.Key) {
editor.doc.text += k.char
})
var ch = task.channel[string]()
task.spawn(func() { // background autosave
for text in ch.recv() { save(text) }
})
win.on_close(func() { ch.send(doc.text) })
win.run()
}
+23
View File
@@ -0,0 +1,23 @@
// Enums with data, generics, interfaces.
enum Shape {
Circle(r: f64)
Rect(w, h: f64)
}
func area(s: Shape): f64 {
return match s {
Circle(r) => 3.14159 * r * r
Rect(w, h) => w * h
}
}
interface Drawable { draw() }
func draw_all[T: Drawable](items: []T) {
for item in items { item.draw() }
}
func max[T: Ordered](a, b: T): T {
if a > b { return a }
return b
}
+37
View File
@@ -0,0 +1,37 @@
struct Tok { first: char }
func kind(c: char): string {
return match c {
'+' => "plus"
'\n' => "newline"
' ' => "space"
_ => "other"
}
}
func main() {
var c = 'a'
print(c, c == 'a', c < 'b', int(c), char(66), string(c) + "!")
var s = "héllo wörld 42"
var letters = 0
var digits = 0
for ch in s {
if ch.is_letter() { letters += 1 }
if ch.is_digit() { digits += 1 }
}
print(letters, digits, s.len())
for i, ch in "aé😀" { print(i, ch) }
print(s[0], s[1], s[3], s[s.len() - 1])
var up = ""
for ch in "dino" { up += string(ch.upper()) }
print(up, 'Q'.lower(), kind('+'), kind('\n'), kind('z'))
var counts: map[char, int] = {}
for ch in "banana" { counts[ch] += 1 }
print(counts)
var w = ""
for ch in "a b c" {
if ch == ' ' { continue }
w += string(ch)
}
print(w, 'a'.is_alnum(), ' '.is_space(), 'A'.is_upper())
}
+9
View File
@@ -0,0 +1,9 @@
a true true 97 B a!
10 2 16
0 a
1 é
3 😀
h é l 2
DINO q plus newline other
{b: 1, a: 3, n: 2}
abc true true true
+74
View File
@@ -0,0 +1,74 @@
struct Button {
label: string
on_click: func(string)
clicks: int
func click() {
clicks += 1
on_click(label)
}
}
func apply(f: func(int): int, x: int): int {
return f(x)
}
func twice(f: func(int): int): func(int): int {
return func(x: int): int { return f(f(x)) }
}
func make_counter(): func(): int {
var n = 0
return func(): int {
n += 1
return n
}
}
func double(x: int): int { return x * 2 }
func map[T, U](xs: []T, f: func(T): U): []U {
var out: []U
for x in xs { out.push(f(x)) }
return out
}
func filter[T](xs: []T, keep: func(T): bool): []T {
var out: []T
for x in xs {
if keep(x) { out.push(x) }
}
return out
}
func main() {
var offset = 10
var add = func(x: int): int { return x + offset }
offset = 99 // the closure kept its own copy
print(add(1), apply(add, 5), apply(double, 4))
print(apply(x => x * x, 7), twice(double)(3), twice(x => x + 1)(0))
var next = make_counter()
var other = make_counter()
print(next(), next(), next(), other())
var snapshot = next // copies the closure, with its state
print(next(), snapshot())
var nums = [1, 2, 3, 4, 5, 6]
print(map(nums, x => x * 10))
print(map(nums, x => "n{x}"))
print(filter(nums, n => n % 2 == 0))
var total = 0
for n in nums { total += apply(double, n) }
print(total)
var log = ""
var b = Button{"OK", func(name: string) { print("clicked", name) }, 0}
b.click()
b.click()
print(b.clicks)
var handlers: []func(int): int
handlers.push(double)
handlers.push(x => x - 1)
for h in handlers { print(h(10)) }
}
+13
View File
@@ -0,0 +1,13 @@
11 15 8
49 12 2
1 2 3 1
4 4
[10, 20, 30, 40, 50, 60]
[n1, n2, n3, n4, n5, n6]
[2, 4, 6]
42
clicked OK
clicked OK
2
20
9
+101
View File
@@ -0,0 +1,101 @@
// A tree: a node holds a list of child trees (a list can hold the enum it is inside).
enum Tree {
Leaf(value: int)
Node(children: []Tree)
func sum(): int {
return match self {
Leaf(v) => v
Node(kids) => sum_all(kids)
}
}
func depth(): int {
return match self {
Leaf(_) => 1
Node(kids) => 1 + deepest(kids)
}
}
}
func sum_all(ts: []Tree): int {
var total = 0
for t in ts {
total += t.sum()
}
return total
}
func deepest(ts: []Tree): int {
var best = 0
for t in ts {
var d = t.depth()
if d > best {
best = d
}
}
return best
}
// Error handling with a plain enum.
enum Result {
Ok(value: int)
Err(msg: string)
}
func divide(a, b: int): Result {
if b == 0 {
return Result.Err("divide by zero")
}
return Result.Ok(a / b)
}
func show(r: Result) {
match r {
Ok(v) => print("ok:", v)
Err(m) => print("error:", m)
}
}
// Data inside an enum is a value like everything else.
enum Msg {
Quit
Say(text: string)
Batch(items: []string)
}
struct Inbox {
last: Msg
count: int
}
func main() {
var tree = Tree.Node([Tree.Leaf(1), Tree.Node([Tree.Leaf(2), Tree.Leaf(3)]), Tree.Leaf(4)])
print("sum", tree.sum(), "depth", tree.depth())
show(divide(10, 2))
show(divide(1, 0))
var m = Msg.Batch(["a", "b"])
var copy = m
match copy {
Batch(items) => {
items.push("c")
print("copy has", items)
}
_ => print("not a batch")
}
print("original still", m)
var inbox = Inbox{Msg.Say("hi"), 1}
var other = inbox
other.last = Msg.Quit
other.count += 1
print(inbox, other)
match inbox.last {
Say(t) => print("said", t)
Quit => print("quit")
Batch(_) => print("batch")
}
}
+7
View File
@@ -0,0 +1,7 @@
sum 10 depth 3
ok: 5
error: divide by zero
copy has [a, b, c]
original still Msg.Batch([a, b])
Inbox{last: Msg.Say(hi), count: 1} Inbox{last: Msg.Quit, count: 2}
said hi
+93
View File
@@ -0,0 +1,93 @@
enum Shape {
Circle(r: float)
Rect(w, h: float)
Point
func area(): float {
return match self {
Circle(r) => 3.14159 * r * r
Rect(w, h) => w * h
Point => 0
}
}
func name(): string {
return match self {
Circle(_) => "circle"
Rect(_, _) => "rectangle"
Point => "point"
}
}
}
enum Color {
Red
Green
Blue
}
func describe(c: Color): string {
return match c {
Color.Red => "warm"
Color.Green => "natural"
Color.Blue => "cool"
}
}
func classify(n: int): string {
return match n {
0 => "zero"
1 => "one"
_ => "many"
}
}
func main() {
var shapes = [Shape.Circle(1.5), Shape.Rect(2, 3), Shape.Point]
for s in shapes {
print(s.name(), s.area())
}
print(shapes)
var c = Color.Green
print(c, describe(c), c == Color.Green, c != Color.Blue)
for i in 0..4 {
print(i, classify(i))
}
// match as a statement can use blocks and loop control
var total = 0.0
for s in shapes {
match s {
Circle(r) => {
total += r
}
Rect(w, _) => {
if w > 100 {
break
}
total += w
}
_ => continue
}
print("so far", total)
}
// bool and string matches
var flag = true
print(match flag {
true => "yes"
false => "no"
})
var cmd = "stop"
match cmd {
"go" => print("going")
"stop" => print("stopping")
other => print("unknown:", other)
}
// the zero value of an enum is its first case
var z: Shape
print(z, Color.Red == (Color.Red))
}
+14
View File
@@ -0,0 +1,14 @@
circle 7.0685775
rectangle 6.0
point 0.0
[Shape.Circle(1.5), Shape.Rect(2.0, 3.0), Shape.Point]
Color.Green natural true true
0 zero
1 one
2 many
3 many
so far 1.5
so far 3.5
yes
stopping
Shape.Circle(0.0) true
+48
View File
@@ -0,0 +1,48 @@
func parse_digit(c: string): (int, error) {
if c == "0" { return 0, nil }
if c == "1" { return 1, nil }
if c == "2" { return 2, nil }
return error("not a digit: {c}")
}
func add_digits(a: string, b: string): (int, error) {
var x = parse_digit(a)?
var y = parse_digit(b)?
return x + y, nil
}
func check(n: int): error {
if n < 0 {
return error("negative: {n}")
}
return nil
}
func run(): error {
check(5)?
print("5 is fine")
check(-3)?
print("never printed")
return nil
}
func main(): error {
var sum, err = add_digits("1", "2")
if err != nil {
print("unexpected:", err)
} else {
print("sum =", sum)
}
var _, bad = add_digits("1", "x")
if bad != nil {
print("failed:", bad)
}
var ok: error = nil
print("ok is", ok)
run()?
print("not reached")
return nil
}
+4
View File
@@ -0,0 +1,4 @@
sum = 3
failed: not a digit: x
ok is nil
5 is fine
+12
View File
@@ -0,0 +1,12 @@
func fib(n: int): int {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
func main() {
for i in 0..15 {
print("fib({i}) = {fib(i)}")
}
}
+15
View File
@@ -0,0 +1,15 @@
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55
fib(11) = 89
fib(12) = 144
fib(13) = 233
fib(14) = 377
+53
View File
@@ -0,0 +1,53 @@
struct Stack[T] {
items: []T
func push_item(x: T) { items.push(x) }
func pop_item(): T { return items.pop() }
func size(): int { return items.len() }
func peek(): T { return items[items.len() - 1] }
}
enum Maybe[T] {
Some(value: T)
None
func or_else(fallback: T): T {
return match self {
Some(v) => v
None => fallback
}
}
}
struct Pair[A, B] {
first: A
second: B
}
struct Tree[T] {
value: T
kids: []Tree[T]
}
func find(xs: []int, x: int): Maybe[int] {
for v in xs {
if v == x { return Maybe[int].Some(v) }
}
return Maybe[int].None
}
func main() {
var s = Stack[int]{}
s.push_item(1)
s.push_item(2)
print(s.size(), s.peek(), s.pop_item(), s.size())
var names: Stack[string]
names.push_item("a")
names.push_item("b")
print(names.peek(), names)
print(find([1, 2, 3], 2).or_else(0), find([1], 9).or_else(-1))
var p = Pair[string, float]{"pi", 3.14}
print(p.first, p.second, p)
var t = Tree[int]{1, [Tree[int]{2, []}]}
print(t.kids.len(), t.kids[0].value)
}
+5
View File
@@ -0,0 +1,5 @@
2 2 2 1
b Stack[string]{items: [a, b]}
2 -1
pi 3.14 Pair[string, float]{first: pi, second: 3.14}
1 2
+3
View File
@@ -0,0 +1,3 @@
func main() {
print("Hello, Dino!")
}
+1
View File
@@ -0,0 +1 @@
Hello, Dino!
+79
View File
@@ -0,0 +1,79 @@
interface Shape {
area(): float
name(): string
scale(k: float)
}
struct Circle {
r: float
func area(): float { return 3.0 * r * r }
func name(): string { return "circle" }
func scale(k: float) { r = r * k }
}
struct Rect {
w, h: float
tag: string
func area(): float { return w * h }
func name(): string { return "rect " + tag }
func scale(k: float) {
w = w * k
h = h * k
}
}
enum Dot {
Small
Big
func area(): float { return 1.0 }
func name(): string { return "dot" }
func scale(k: float) {}
}
struct Scene {
shapes: []Shape
main_shape: Shape
}
func describe(s: Shape): string {
return "{s.name()}: {s.area()}"
}
func biggest(shapes: []Shape): Shape {
var best = shapes[0]
for s in shapes {
if s.area() > best.area() { best = s }
}
return best
}
func total[T: Shape](xs: []T): float {
var sum = 0.0
for x in xs { sum += x.area() }
return sum
}
func main() {
var shapes: []Shape = [Circle{1.0}, Rect{2.0, 3.0, "a"}, Dot.Big]
shapes.push(Circle{2.0})
for s in shapes { print(describe(s)) }
print(biggest(shapes).name())
// interface values are copies: changing one doesn't change the original
var c = Circle{1.0}
var s: Shape = c
s.scale(10.0)
print(c.r, s.area())
var t = s
t.scale(2.0)
print(s.area(), t.area())
var scene = Scene{shapes, Rect{1.0, 1.0, "main"}}
scene.main_shape.scale(3.0)
print(scene.main_shape.area(), scene.shapes.len())
print(scene.main_shape)
var none: Shape
print(none == nil, s == nil)
print(total(shapes))
}
+11
View File
@@ -0,0 +1,11 @@
circle: 3.0
rect a: 6.0
dot: 1.0
circle: 12.0
circle
1.0 300.0
300.0 1200.0
9.0 4
Rect{w: 3.0, h: 3.0, tag: main}
true false
22.0
+72
View File
@@ -0,0 +1,72 @@
interface Shape {
area(): float
name(): string
}
interface Resizable {
scale(k: float)
}
struct Circle {
r: float
func area(): float { return 3.0 * r * r }
func name(): string { return "circle" }
func scale(k: float) { r = r * k }
}
struct Rect {
w, h: float
func area(): float { return w * h }
func name(): string { return "rect" }
}
enum Dot {
Small
Big
func area(): float { return 1.0 }
func name(): string { return "dot" }
}
func describe[T: Shape](s: T): string {
return "{s.name()} with area {s.area()}"
}
func total_area[T: Shape](shapes: []T): float {
var sum = 0.0
for s in shapes { sum += s.area() }
return sum
}
func grow[T: Resizable](s: T): T {
var copy = s
copy.scale(2.0)
return copy
}
struct Gallery[T: Shape] {
items: []T
func add(x: T) { items.push(x) }
func biggest(): float {
var best = 0.0
for it in items {
if it.area() > best { best = it.area() }
}
return best
}
}
func main() {
print(describe(Circle{2.0}))
print(describe(Rect{2.0, 5.0}))
print(describe(Dot.Big))
print(total_area([Circle{1.0}, Circle{2.0}]))
print(grow(Circle{1.5}))
var g = Gallery[Rect]{}
g.add(Rect{1.0, 2.0})
g.add(Rect{3.0, 4.0})
print(g.biggest())
}
+6
View File
@@ -0,0 +1,6 @@
circle with area 12.0
rect with area 10.0
dot with area 1.0
15.0
Circle{r: 3.0}
12.0
+68
View File
@@ -0,0 +1,68 @@
// Lists are values: assigning or passing copies them.
struct Inventory {
items: []string
gold: int
func add(item: string) {
items.push(item)
}
func count(): int {
return items.len()
}
}
func add_one(xs: []int): []int {
xs.push(1)
return xs
}
func first(xs: []int): int {
return xs[0]
}
func main() {
var a = [1, 2, 3]
var b = a
b[0] = 99
b.push(4)
print(a, b)
// a function that changes its parameter works on its own copy
var c = add_one(a)
print(a, c)
print(first(a), first(c))
// structs holding lists copy deeply
var inv = Inventory{[], 10}
inv.add("sword")
var saved = inv
inv.add("shield")
saved.gold = 0
print(inv)
print(saved)
print(inv.count(), saved.count())
// nested lists
var grid = [[1, 2], [3, 4]]
var snapshot = grid
grid[0][1] = 20
grid[1].push(5)
print(grid)
print(snapshot)
// looping over a list while changing it walks the original
var xs = [1, 2, 3]
for x in xs {
xs.push(x * 10)
}
print(xs)
// the loop variable is a copy too
var ys = [1, 2, 3]
for y in ys {
y += 100
print(y)
}
print(ys)
}
+13
View File
@@ -0,0 +1,13 @@
[1, 2, 3] [99, 2, 3, 4]
[1, 2, 3] [1, 2, 3, 1]
1 1
Inventory{items: [sword, shield], gold: 10}
Inventory{items: [sword], gold: 0}
2 1
[[1, 20], [3, 4, 5]]
[[1, 2], [3, 4]]
[1, 2, 3, 10, 20, 30]
101
102
103
[1, 2, 3]
+60
View File
@@ -0,0 +1,60 @@
func sum(xs: []int): int {
var total = 0
for x in xs {
total += x
}
return total
}
func squares(n: int): []int {
var out: []int
for i in 0..n {
out.push(i * i)
}
return out
}
func largest(xs: []int): int {
var best = xs[0]
for x in xs {
if x > best {
best = x
}
}
return best
}
func main() {
var nums = [5, 3, 8, 1]
print(nums, nums.len())
print("sum:", sum(nums), "largest:", largest(nums))
nums.push(10)
nums[0] = 50
nums[1] += 7
print(nums)
print("popped", nums.pop(), "left", nums.len())
var sq = squares(6)
print(sq)
print(sq[1..4], sq[..2], sq[4..])
for i, x in sq {
if i % 2 == 0 {
print("sq[{i}] = {x}")
}
}
// an empty list needs a type
var empty: []string
print(empty, empty.len())
empty.push("a")
empty.push("b")
print(empty, "{empty.len()} items")
var floats: []float = [1, 2.5, 3]
print(floats)
var words = ["dino", "lang"]
print(words[0] + "-" + words[1], words[0].len())
}
+13
View File
@@ -0,0 +1,13 @@
[5, 3, 8, 1] 4
sum: 17 largest: 8
[50, 10, 8, 1, 10]
popped 10 left 4
[0, 1, 4, 9, 16, 25]
[1, 4, 9] [0, 1] [16, 25]
sq[0] = 0
sq[2] = 4
sq[4] = 16
[] 0
[a, b] 2 items
[1.0, 2.5, 3.0]
dino-lang 4
+51
View File
@@ -0,0 +1,51 @@
const LIMIT = 20
func is_prime(n: int): bool {
if n < 2 {
return false
}
var d = 2
for d * d <= n {
if n % d == 0 {
return false
}
d += 1
}
return true
}
func main() {
var sum = 0
for i in 1..11 {
sum += i
}
print("sum 1..10 =", sum)
print("evens:")
for i in 0..LIMIT step 2 {
print(i)
}
print("countdown:")
for i in 5..0 step -1 {
print(i)
}
var primes = ""
for n in 0..LIMIT {
if !is_prime(n) {
continue
}
primes += "{n} "
}
print("primes:", primes)
var k = 0
for {
k += 1
if k == 3 {
break
}
}
print("k =", k)
}
+20
View File
@@ -0,0 +1,20 @@
sum 1..10 = 55
evens:
0
2
4
6
8
10
12
14
16
18
countdown:
5
4
3
2
1
primes: 2 3 5 7 11 13 17 19
k = 3
+48
View File
@@ -0,0 +1,48 @@
struct Team {
name: string
scores: map[string, int]
}
func total(m: map[string, int]): int {
var sum = 0
for k, v in m { sum += v }
return sum
}
func main() {
var ages = {"alice": 30, "bob": 25}
ages["carol"] = 41
ages["bob"] = 26
print(ages["bob"], ages.len(), ages.has("dave"), ages)
print(ages.get("alice"), ages.get("zed"), ages.get_or("zed", -1))
var counts: map[string, int] = {}
for w in "a b a c b a".split(" ") {
counts[w] += 1
}
print(counts)
for k, v in counts { print(k, "->", v) }
for k in counts.keys() { print("key", k) }
print(counts.values(), total(counts))
counts.remove("b")
print(counts, counts.len())
var copy = counts
copy["z"] = 9
print(counts.len(), copy.len())
var nums = map[int, []string]{}
nums[1] = ["x", "y"]
nums[2] = []
nums[1].push("z")
print(nums)
var t = Team{name: "red", scores: {"a": 1}}
t.scores["b"] = 2
var t2 = t
t2.scores["c"] = 3
print(t.scores.len(), t2.scores.len())
var big = map[int, int]{}
for i in 0..2000 { big[i * 7] = i }
var s = 0
for i in 0..2000 { s += big[i * 7] }
print(s, big.len())
for i in 0..1000 { big.remove(i * 7) }
print(big.len())
}
+16
View File
@@ -0,0 +1,16 @@
26 3 false {alice: 30, bob: 26, carol: 41}
30 nil -1
{a: 3, b: 2, c: 1}
a -> 3
b -> 2
c -> 1
key a
key b
key c
[3, 2, 1] 6
{a: 3, c: 1} 2
2 3
{1: [x, y, z], 2: []}
2 3
1999000 2000
1000
+23
View File
@@ -0,0 +1,23 @@
const PI = 3.14159
func area(r: float): float {
return PI * r * r
}
func average(a, b: int): float {
return float(a + b) / 2
}
func main() {
print("area:", area(2))
print("avg:", average(3, 4))
print(10 / 3, 10 % 3, 10.0 / 4)
print(int(7.9), float(3))
var x: float = 1
x *= 2.5
print(x, x > 2, -x)
print("whole float:", 2.0 * 3)
var big = 9223372036854775807
big += 1
print("wraps:", big)
}
+7
View File
@@ -0,0 +1,7 @@
area: 12.56636
avg: 3.5
3 1 2.5
7 3.0
2.5 true -2.5
whole float: 6.0
wraps: -9223372036854775808
+53
View File
@@ -0,0 +1,53 @@
struct User {
name: string
age: int
}
func find(id: int): User? {
if id == 1 {
return User{name: "Ann", age: 30}
}
return nil
}
func first_even(xs: []int): int? {
for x in xs {
if x % 2 == 0 { return x }
}
return nil
}
func describe(id: int): string {
var u = find(id)
if u == nil {
return "nobody"
}
return "{u.name} is {u.age}"
}
func main() {
print(describe(1))
print(describe(2))
var n = first_even([1, 3, 4, 5])
if n != nil {
print("first even:", n + 1)
}
var m: int? = first_even([1, 3])
print("m is", m)
print("n is", n)
var count: int? = 5
if count != nil && count > 3 {
print("big count")
}
count = nil
if count == nil || count > 100 {
print("no count")
}
var list: []int? = nil
if list == nil {
print("no list")
}
}
+8
View File
@@ -0,0 +1,8 @@
Ann is 30
nobody
first even: 5
m is nil
n is 4
big count
no count
no list
+33
View File
@@ -0,0 +1,33 @@
func say(msg: string, v: int): int {
print(msg)
return v
}
func add(a, b, c: int): int {
return a + b + c
}
func yes(msg: string): bool {
print(msg)
return true
}
func no(msg: string): bool {
print(msg)
return false
}
func main() {
print("arguments run left to right:")
print(add(say("first", 1), say("second", 2), say("third", 3)))
print("&& and || short-circuit:")
if no("A") && yes("B") {
print("unreachable")
}
if yes("C") || yes("D") {
print("done")
}
var ok = no("E") || yes("F") && yes("G")
print(ok)
}
+13
View File
@@ -0,0 +1,13 @@
arguments run left to right:
first
second
third
6
&& and || short-circuit:
A
C
done
E
F
G
true
+101
View File
@@ -0,0 +1,101 @@
enum Tok {
Word(w: string)
Num(n: int)
Many(parts: []string)
End
}
func name_of(t: Tok): string {
return match t {
Word(w) => w
Num(n) => "n{n}"
Many(ps) => ps[0] + "..."
End => "end"
}
}
func scan(ts: []Tok): (string, error) {
var acc = ""
for t in ts {
match t {
Word(w) => {
if w == "stop" { break }
if w == "skip" { continue }
acc += w + " "
}
Num(n) => {
if n < 0 { return error("negative " + name_of(t)) }
acc += "{n} "
}
Many(ps) => {
for p in ps {
if p == "x" { continue }
acc += p
}
}
End => { return acc, nil }
}
}
return acc + "|", nil
}
func grid(n: int): [][]string {
var g: [][]string
for i in 0..n {
var row: []string
for j in 0..n { row.push("{i}{j}") }
g.push(row)
}
return g
}
func longest(g: [][]string): string {
var best = ""
for row in g {
for cell in row {
if cell.len() >= best.len() { best = cell }
}
}
return best
}
struct Counter {
seen: []string
func note(s: string): int {
seen.push(s + "")
return seen.len()
}
}
func main() {
var ts = [Tok.Word("a"), Tok.Num(3), Tok.Many(["p", "x", "q"]), Tok.Word("skip"), Tok.Word("b")]
var r0, e0 = scan(ts)
print(r0, e0)
ts.push(Tok.Word("stop"))
ts.push(Tok.Word("never"))
var r, e = scan(ts)
print(r, e)
var bad = [Tok.Word("a"), Tok.Num(-4), Tok.End]
var r2, e2 = scan(bad)
print(r2, e2)
var ok = [Tok.Word("a"), Tok.End, Tok.Word("b")]
var r3, e3 = scan(ok)
print(r3, e3)
var g = grid(3)
g[1][1] = "mid" + "dle"
var h = g
h[0][0] = "changed"
print(g, longest(g), longest(h))
var c = Counter{}
var n = 0
for i in 0..3 { n += c.note("s{i}") }
print(n, c.seen)
var total = 0
for i in 0..50 {
var tmp = "item" + "{i}"
total += tmp.len()
if i % 7 == 0 { continue }
if i > 40 { break }
}
print(total)
}
+7
View File
@@ -0,0 +1,7 @@
a 3 pqb | nil
a 3 pqb | nil
negative n-4
a nil
[[00, 01, 02], [10, middle, 12], [20, 21, 22]] middle changed
6 [s0, s1, s2]
242
+101
View File
@@ -0,0 +1,101 @@
struct Person {
name: string
tags: []string
func greet(): string { return "hi " + name + "!" }
func rename(n: string) { name = n }
func add_tag(t: string) { tags.push(t) }
}
enum Msg {
Text(body: string)
Pair(a: string, items: []string)
Quit
}
func describe(m: Msg): string {
return match m {
Text(b) => "text:" + b
Pair(a, items) => "pair:" + a + "/" + "{items.len()}"
Quit => "quit"
}
}
func join(xs: []string, sep: string): string {
var out = ""
var first = true
for x in xs {
if !first { out += sep }
out += x
first = false
}
return out
}
func find(xs: []string, key: string): string? {
for x in xs {
if x == key { return x }
}
return nil
}
func fails(n: int): (string, error) {
if n > 2 { return error("too big: {n}") }
return "ok {n}", nil
}
func chain(): (string, error) {
var a = fails(1)?
var b = fails(2)?
var c = fails(3)?
return a + b + c, nil
}
func early(xs: []string): string {
var tmp = "tmp" + "1"
for x in xs {
var local = x + "!"
if local == "b!" { return local + tmp }
if local == "a!" { continue }
if local == "z!" { break }
}
return tmp
}
func main() {
var p = Person{"ann", ["x", "y"]}
print(p.greet())
p.rename("bob" + "by")
p.add_tag("z" + "z")
print(p.greet(), p.tags)
var q = p
q.rename("changed")
print(p.name, q.name)
var ms = [Msg.Text("hello"), Msg.Pair("k", ["1", "2"]), Msg.Quit]
for m in ms { print(describe(m)) }
print(join(["a", "b", "c"], ", "))
var words: []string
for i in 0..5 { words.push("w{i}") }
print(words, find(words, "w3"), find(words, "nope"))
var f = find(words, "w2")
if f != nil { print("found", f + "?") }
var s = "x"
for i in 0..4 { s = s + s }
print(s.len())
var v, e = fails(5)
print(v, e)
var w, e2 = chain()
print(w, e2)
print(early(["a", "c"]), early(["q", "b"]), early(["z"]))
var popped = words.pop()
print(popped, words.len())
words[0] = "first" + "!"
print(words)
var copy = words[1..3]
copy.push("end")
print(copy, words)
}
+16
View File
@@ -0,0 +1,16 @@
hi ann!
hi bobby! [x, y, zz]
bobby changed
text:hello
pair:k/2
quit
a, b, c
[w0, w1, w2, w3, w4] w3 nil
found w2?
16
too big: 5
too big: 3
tmp1 b!tmp1 tmp1
w4 4
[first!, w1, w2, w3]
[w1, w2, end] [first!, w1, w2, w3]
+82
View File
@@ -0,0 +1,82 @@
struct Item {
name: string
qty: int
}
struct Box {
items: []Item
label: string
func summary(): string { return label + ":" + "{items.len()}" }
func first(): Item? {
if items.len() == 0 { return nil }
return items[0]
}
}
func mk(n: string, q: int): Item { return Item{n + "_", q} }
func label_of(i: Item): string { return i.name + "#" + "{i.qty}" }
func fresh_box(l: string): Box { return Box{[mk("a", 1), mk("b", 2)], l + l} }
func pick(b: Box, k: int): (Item, error) {
if k >= b.items.len() { return error("no item {k} in " + b.label) }
return b.items[k], nil
}
func total(b: Box): (int, error) {
var t = 0
for i in 0..3 {
var it = pick(b, i)?
t += it.qty
}
return t, nil
}
func rec(n: int): string {
if n == 0 { return "." }
return "{n}" + rec(n - 1)
}
func cmp(a: string, b: string): bool { return a + "x" == b + "x" }
func check(s: string): error {
if s == "bad" + "!" { return error("bad input: " + s) }
return nil
}
func run(): error {
check("fine")?
check("bad" + "!")?
return nil
}
func main() {
print(label_of(mk("z", 9)), fresh_box("q").summary(), fresh_box("r").label)
var b = fresh_box("L")
b.label = b.label + "2"
b.items[0].name = "changed" + "!"
b.items.push(Item{"c", 3})
print(b.summary(), b.items)
var f = b.first()
if f != nil && f.name != "" { print(f.name) }
var it, err = pick(b, 7)
print(it, err)
var t, err2 = total(b)
print(t, err2)
print(rec(3), cmp("a", "a"), cmp("a" + "b", "a"))
var i = 0
for i < 3 && "{i}" != "2" { i += 1 }
print(i)
var msg = match i {
2 => "two" + "!"
_ => "other"
}
print(msg)
print(run())
var e = run()
if e != nil { print("failed:", e) }
var names: []string = ["m" + "1", "m" + "2"]
var out: []string
for n in names { out.push(n + n) }
names = out
print(names, out)
var opt: Item? = mk("o", 1)
if opt != nil { print(opt.name) }
opt = nil
print(opt)
var s = "a"
s += "b" + s
print(s)
}
+14
View File
@@ -0,0 +1,14 @@
z_#9 qq:2 rr
LL2:3 [Item{name: changed!, qty: 1}, Item{name: b_, qty: 2}, Item{name: c, qty: 3}]
changed!
Item{name: , qty: 0} no item 7 in LL2
6 nil
321. true false
2
two!
bad input: bad!
failed: bad input: bad!
[m1m1, m2m2] [m1m1, m2m2]
o_
nil
aba
+69
View File
@@ -0,0 +1,69 @@
struct Texture {
name: string
uses: int
func touch() { uses += 1 }
}
struct Sprite {
tex: shared Texture
x: int
}
struct Window {
title: string
buttons: []shared Button
func add(b: shared Button) { buttons.push(b) }
}
struct Button {
label: string
window: weak Window?
clicks: int
func click() {
clicks += 1
if window != nil {
print(label, "clicked in", window.title)
} else {
print(label, "clicked, window is gone")
}
}
}
func use_texture(t: shared Texture) {
t.touch()
}
func main() {
// several owners of one value: a change through one is seen by all
var tex = shared Texture{"grass", 0}
var a = Sprite{tex, 1}
var b = Sprite{tex, 2}
a.tex.touch()
b.tex.touch()
use_texture(tex)
print(tex.name, tex.uses, a.tex.uses, b.tex.uses)
print(a)
// a window and its buttons point at each other: the button's side is weak
var win = shared Window{"Main", []}
var ok = shared Button{"OK", weak win, 0}
win.add(ok)
ok.click()
win.buttons[0].click()
print(ok.clicks)
var cancel = shared Button{label: "Cancel"}
print(cancel.window == nil)
cancel.window = weak win
print(cancel.window == nil)
cancel.click()
// once the window is gone, the weak pointers know
var saved = ok
win = shared Window{"Other", []}
saved.click()
cancel.click()
}
+10
View File
@@ -0,0 +1,10 @@
grass 3 3 3
Sprite{tex: Texture{name: grass, uses: 3}, x: 1}
OK clicked in Main
OK clicked in Main
2
true
false
Cancel clicked in Main
OK clicked, window is gone
Cancel clicked, window is gone
+45
View File
@@ -0,0 +1,45 @@
func primes_up_to(n: int): []int {
var is_prime: []bool
for i in 0..n + 1 {
is_prime.push(true)
}
is_prime[0] = false
is_prime[1] = false
for i in 2..n + 1 {
if is_prime[i] {
for j in i * i..n + 1 step i {
is_prime[j] = false
}
}
}
var out: []int
for i, p in is_prime {
if p {
out.push(i)
}
}
return out
}
func bubble_sort(xs: []int): []int {
var n = xs.len()
for i in 0..n {
for j in 0..n - i - 1 {
if xs[j] > xs[j + 1] {
var tmp = xs[j]
xs[j] = xs[j + 1]
xs[j + 1] = tmp
}
}
}
return xs
}
func main() {
var ps = primes_up_to(60)
print(ps)
print("count:", ps.len())
var unsorted = [9, 4, 7, 1, 8, 2]
var sorted = bubble_sort(unsorted)
print(unsorted, "->", sorted)
}
+3
View File
@@ -0,0 +1,3 @@
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]
count: 17
[9, 4, 7, 1, 8, 2] -> [1, 2, 4, 7, 8, 9]
+50
View File
@@ -0,0 +1,50 @@
struct Vec2 {
x, y: f32
func add(b: Vec2): Vec2 { return Vec2{x + b.x, y + b.y} }
func scale(k: f32): Vec2 { return Vec2{x * k, y * k} }
}
func average(a: u8, b: u8): u8 {
return u8((int(a) + int(b)) / 2)
}
func main() {
// literals take the type that is asked for
var small: u8 = 250
small += 10 // wraps around: 260 becomes 4
print(small)
var id: i8 = -128
print(id, id - 1)
var big: u64 = 5
big = big * 1000000000000
print(big, big / 7, big % 7)
var n: i32 = 2147483647
print(n + 1)
// f32 prints the shortest text that reads back the same
var speed: f32 = 1.1
print(speed, speed * 2, speed / 3)
var v = Vec2{1.5, 2}
print(v.add(Vec2{0.25, 0.25}).scale(2))
// conversions are explicit
var f = 3.99
print(int(f), u8(f), i8(-200.5), u8(300.7), f32(f))
print(u8(300), i16(70000), u32(-1), int(small) + 1)
print(average(200, 100))
print(u8(7) == 7, small < 10)
var xs: []u8 = [1, 2, 255]
xs[2] += 1
print(xs)
match id {
-128 => print("lowest i8")
_ => print("other")
}
}
+12
View File
@@ -0,0 +1,12 @@
4
-128 127
5000000000000 714285714285 5
-2147483648
1.1 2.2 0.36666667
Vec2{x: 3.5, y: 4.5}
3 3 -128 255 3.99
44 4464 4294967295 5
150
true true
[1, 2, 0]
lowest i8
+50
View File
@@ -0,0 +1,50 @@
import os
import math
import time
func count(path: string): (int, int, error) {
var text = os.read_file(path)?
var words = 0
var lines = 0
for line in text.lines() {
lines += 1
words += line.fields().len()
}
return lines, words, nil
}
func main() {
var csv = " alpha, beta ,gamma,, delta "
var parts = csv.split(",")
for p in parts { print("[" + p.trim() + "]") }
print(parts.len(), parts.join("|"))
print("Hello".upper(), "Hello".lower(), "a-b-c".replace("-", "+"), "ab".repeat(3))
print("hello".contains("ell"), "hello".starts_with("he"), "hello".ends_with("x"), "hello".index_of("l"), "hello".index_of("z"))
var n, err = "42".to_int()
print(n, err)
var bad, err2 = "4x2".to_int()
print(bad, err2)
var f, err3 = "2.5".to_float()
print(f * 2, err3)
print(math.sqrt(16), math.pow(2, 10), math.floor(2.7), math.round(2.5), math.PI)
print(math.min(3, 9), math.max(2.5, 1), math.abs(-7), math.abs(-2.5))
var small: u8 = 7
print(math.min(small, 200), math.max(small, 3))
var t0 = time.now()
time.sleep(0.01)
print(time.now() - t0 >= 0.01)
var err4 = os.write_file("/tmp/dino_std_test.txt", "one two\nthree\n\nfour five six\n")
print(err4)
var lines, words, e5 = count("/tmp/dino_std_test.txt")
print(lines, words, e5)
var l2, w2, e6 = count("/tmp/definitely/not/here.txt")
print(l2, w2, e6)
print(os.exists("/tmp/dino_std_test.txt"), os.exists("/nope"))
print(os.args.len(), os.env("HOME_NOPE_X") == nil)
var home = os.env("PATH")
if home != nil { print(home.len() > 0) }
os.exit(3)
}
+21
View File
@@ -0,0 +1,21 @@
[alpha]
[beta]
[gamma]
[]
[delta]
5 alpha| beta |gamma|| delta
HELLO hello a+b+c ababab
true true false 2 -1
42 nil
0 "4x2" is not a whole number
5.0 nil
4.0 1024.0 2.0 3.0 3.14159265358979
3 2.5 7 2.5
7 7
true
nil
4 6 nil
0 0 cannot read "/tmp/definitely/not/here.txt": No such file or directory
true false
1 true
true
+19
View File
@@ -0,0 +1,19 @@
func greet(name: string): string {
return "Hello, " + name + "!"
}
func main() {
var name = "Dino"
print(greet(name))
var n = 3
print("n is {n}, doubled {n * 2}, big? {n > 2}")
print("pi is about {3.5 + 0.25}")
print("a" < "b", "abc" == "abc", "x" != "x")
print("tab\there \"quoted\" \{braces}")
print("café ünï")
var s = ""
for i in 0..5 {
s += "{i},"
}
print(s)
}
+7
View File
@@ -0,0 +1,7 @@
Hello, Dino!
n is 3, doubled 6, big? true
pi is about 3.75
true true false
tab here "quoted" {braces}
café ünï
0,1,2,3,4,
+80
View File
@@ -0,0 +1,80 @@
struct Vec2 {
x, y: float
func add(b: Vec2): Vec2 {
return Vec2{x + b.x, y + b.y}
}
func scale(k: float): Vec2 {
return Vec2{x * k, y * k}
}
func length_squared(): float {
return x * x + y * y
}
}
struct Player {
name: string
pos: Vec2
vel: Vec2
hp: int
// changes pos and vel, so the compiler treats it as a mutating method
func update(dt: float) {
pos = pos.add(vel.scale(dt))
if pos.x < 0 || pos.x > 100 {
vel.x = -vel.x
}
if pos.y < 0 || pos.y > 100 {
vel.y = -vel.y
}
}
// calls a mutating method, so it mutates too
func step_twice(dt: float) {
update(dt)
update(dt)
}
func hurt(amount: int) {
hp -= amount
if hp < 0 {
hp = 0
}
}
func is_alive(): bool {
return hp > 0
}
func describe(): string {
return "{name} at ({pos.x}, {pos.y}) hp={hp}"
}
}
func main() {
var p = Player{name: "Ana", pos: Vec2{90, 50}, vel: Vec2{10, 5}, hp: 20}
print(p.describe())
p.update(1)
print(p.describe())
p.update(1)
print(p.describe())
p.step_twice(0.5)
print(p.pos)
// omitted fields start at zero
var q = Player{name: "Zed"}
print(q)
print(q.is_alive())
p.hurt(15)
p.hurt(15)
print(p.hp, p.is_alive())
var origin: Vec2
print(origin, origin.length_squared())
print(Vec2{3, 4}.length_squared())
}
+9
View File
@@ -0,0 +1,9 @@
Ana at (90.0, 50.0) hp=20
Ana at (100.0, 55.0) hp=20
Ana at (110.0, 60.0) hp=20
Vec2{x: 110.0, y: 65.0}
Player{name: Zed, pos: Vec2{x: 0.0, y: 0.0}, vel: Vec2{x: 0.0, y: 0.0}, hp: 0}
false
0 false
Vec2{x: 0.0, y: 0.0} 0.0
25.0
+49
View File
@@ -0,0 +1,49 @@
struct Counter {
n: int
func bump(): int {
n += 1
return n
}
}
struct Pair {
left: Counter
right: Counter
}
func bump_copy(c: Counter): int {
return c.bump()
}
func main() {
// assignment copies
var a = Counter{1}
var b = a
b.n = 100
print(a.n, b.n)
// passing to a function copies
print(bump_copy(a), a.n)
// methods change the variable they are called on
a.bump()
a.bump()
print(a.n)
// nested structs are copied as a whole
var p = Pair{Counter{10}, Counter{20}}
var q = p
q.left.bump()
p.right.bump()
p.right.bump()
print(p.left.n, p.right.n, q.left.n, q.right.n)
// reading before a later call in the same expression: the earlier read wins
var c = Counter{0}
print(c.n, c.bump(), c.n)
// constants can be read and used with non-mutating code
const k = Counter{7}
print(k.n)
}
+6
View File
@@ -0,0 +1,6 @@
1 100
2 1
3
10 22 11 20
0 1 1
7
+15
View File
@@ -0,0 +1,15 @@
// The shape of a parsed calculation.
pub enum Node {
Num(value: float)
Var(name: string)
Neg(inner: []Node)
Bin(op: string, sides: []Node)
Call(name: string, args: []Node)
Assign(name: string, value: []Node)
}
// Enums can't hold themselves directly, so children live in a list of one or two.
pub func neg(n: Node): Node { return Node.Neg([n]) }
pub func bin(op: string, l, r: Node): Node { return Node.Bin(op, [l, r]) }
pub func assign(name: string, v: Node): Node { return Node.Assign(name, [v]) }
+83
View File
@@ -0,0 +1,83 @@
// Evaluates a parsed calculation. Variables and functions live in `Scope`.
import ast
import math
pub struct Builtin {
pub name: string
pub arity: int
pub run: func([]float): float
}
pub struct Scope {
variables: map[string, float]
builtins: map[string, Builtin]
pub func set(name: string, v: float) {
variables[name] = v
}
pub func eval(n: ast.Node): (float, error) {
match n {
Num(v) => return v, nil
Var(name) => {
var v = variables.get(name)
if v == nil { return 0.0, error("unknown variable `{name}`") }
return v, nil
}
Neg(inner) => {
var x = eval(inner[0])?
return -x, nil
}
Assign(name, value) => {
var x = eval(value[0])?
set(name, x)
return x, nil
}
Bin(op, sides) => {
var a = eval(sides[0])?
var b = eval(sides[1])?
return apply(op, a, b)
}
Call(name, args) => {
if !builtins.has(name) { return 0.0, error("unknown function `{name}`") }
var b = builtins[name]
if args.len() != b.arity {
return 0.0, error("`{name}` takes {b.arity} argument(s), but {args.len()} given")
}
var vals: []float
for a in args { vals.push(eval(a)?) }
return b.run(vals), nil
}
}
}
func apply(op: string, a, b: float): (float, error) {
match op {
"+" => return a + b, nil
"-" => return a - b, nil
"*" => return a * b, nil
"/" => {
if b == 0.0 { return 0.0, error("division by zero") }
return a / b, nil
}
"%" => {
if b == 0.0 { return 0.0, error("division by zero") }
return a - b * math.floor(a / b), nil
}
"^" => return math.pow(a, b), nil
_ => return 0.0, error("unknown operator `{op}`")
}
}
}
pub func new_scope(): Scope {
var s = Scope{}
s.builtins["sqrt"] = Builtin{"sqrt", 1, a => math.sqrt(a[0])}
s.builtins["abs"] = Builtin{"abs", 1, a => math.abs(a[0])}
s.builtins["max"] = Builtin{"max", 2, a => math.max(a[0], a[1])}
s.builtins["min"] = Builtin{"min", 2, a => math.min(a[0], a[1])}
s.builtins["sum"] = Builtin{"sum", 3, a => a[0] + a[1] + a[2]}
s.set("pi", math.PI)
s.set("e", math.E)
return s
}
+43
View File
@@ -0,0 +1,43 @@
import parser
import eval
import os
// Evaluates one line and prints the answer or the problem.
func run_line(scope: shared eval.Scope, line: string) {
var text = line.trim()
if text == "" { return }
var tree, err = parser.parse(text)
if err != nil {
print(" error:", err)
return
}
var value, err2 = scope.eval(tree)
if err2 != nil {
print(" error:", err2)
return
}
print(" =", value)
}
// Reads lines from the file named on the command line, or from the keyboard.
func main() {
var scope = shared eval.new_scope()
var args = os.args
if args.len() > 1 {
var text, err = os.read_file(args[1])
if err != nil {
print("cannot read", args[1], err)
os.exit(1)
}
for line in text.lines() {
print(line)
run_line(scope, line)
}
return
}
for {
var line = os.read_line()
if line == nil { break }
run_line(scope, line)
}
}
+130
View File
@@ -0,0 +1,130 @@
// Recursive descent: assignment < + - < * / % < unary minus < ^ < calls and atoms.
import token
import ast
pub struct Parser {
tokens: []token.Token
at: int
func peek(): token.Token { return tokens[at] }
func next(): token.Token {
var t = tokens[at]
if at < tokens.len() - 1 { at += 1 }
return t
}
func is_op(text: string): bool {
var t = peek()
return t.kind == token.Kind.Op && t.text == text
}
func expect(kind: token.Kind, what: string): error {
if peek().kind != kind {
return error("expected {what} at column {peek().pos + 1}")
}
next()
return nil
}
pub func statement(): (ast.Node, error) {
// `name = expression`
if peek().kind == token.Kind.Name && at + 1 < tokens.len() {
var after = tokens[at + 1]
if after.kind == token.Kind.Op && after.text == "=" {
var name = next().text
next()
var value = sum()?
return ast.assign(name, value), finish()
}
}
var e = sum()?
return e, finish()
}
func finish(): error {
if peek().kind != token.Kind.End {
return error("unexpected `{peek().text}` at column {peek().pos + 1}")
}
return nil
}
func sum(): (ast.Node, error) {
var left = product()?
for is_op("+") || is_op("-") {
var op = next().text
var right = product()?
left = ast.bin(op, left, right)
}
return left, nil
}
func product(): (ast.Node, error) {
var left = unary()?
for is_op("*") || is_op("/") || is_op("%") {
var op = next().text
var right = unary()?
left = ast.bin(op, left, right)
}
return left, nil
}
func unary(): (ast.Node, error) {
if is_op("-") {
next()
var inner = unary()?
return ast.neg(inner), nil
}
return power()
}
func power(): (ast.Node, error) {
var base = atom()?
if is_op("^") {
next()
var exp = unary()?
return ast.bin("^", base, exp), nil
}
return base, nil
}
func atom(): (ast.Node, error) {
var t = next()
match t.kind {
Num => {
var v, err = t.text.to_float()
if err != nil { return ast.Node.Num(0.0), error("bad number `{t.text}` at column {t.pos + 1}") }
return ast.Node.Num(v), nil
}
Name => {
if peek().kind == token.Kind.Open {
next()
var args: []ast.Node
if peek().kind != token.Kind.Close {
args.push(sum()?)
for is_op(",") {
next()
args.push(sum()?)
}
}
expect(token.Kind.Close, "`)`")?
return ast.Node.Call(t.text, args), nil
}
return ast.Node.Var(t.text), nil
}
Open => {
var inner = sum()?
expect(token.Kind.Close, "`)`")?
return inner, nil
}
End => return ast.Node.Num(0.0), error("the calculation ends too early (column {t.pos + 1})")
_ => return ast.Node.Num(0.0), error("unexpected `{t.text}` at column {t.pos + 1}")
}
}
}
pub func parse(src: string): (ast.Node, error) {
var tokens = token.tokenize(src)?
var p = Parser{tokens, 0}
return p.statement()
}
+30
View File
@@ -0,0 +1,30 @@
1 + 2 * 3
= 7.0
(1 + 2) * 3
= 9.0
-2 ^ 2
= -4.0
2 ^ 3 ^ 2
= 512.0
x = 10 / 4
= 2.5
x * 2 + pi
= 8.14159265358979
sqrt(16) + abs(-3)
= 7.0
max(2, 7) % 4
= 3.0
y
error: unknown variable `y`
1 / 0
error: division by zero
foo(1)
error: unknown function `foo`
sqrt(1, 2)
error: `sqrt` takes 1 argument(s), but 2 given
3 +
error: the calculation ends too early (column 4)
4 $ 4
error: unexpected `$` at column 3
sum(1, 2, 3) * x
= 15.0
+15
View File
@@ -0,0 +1,15 @@
1 + 2 * 3
(1 + 2) * 3
-2 ^ 2
2 ^ 3 ^ 2
x = 10 / 4
x * 2 + pi
sqrt(16) + abs(-3)
max(2, 7) % 4
y
1 / 0
foo(1)
sqrt(1, 2)
3 +
4 $ 4
sum(1, 2, 3) * x
+49
View File
@@ -0,0 +1,49 @@
// Turns the text of a calculation into a list of tokens.
pub enum Kind {
Num
Name
Op
Open
Close
End
}
pub struct Token {
pub kind: Kind
pub text: string
pub pos: int
}
pub func tokenize(src: string): ([]Token, error) {
var tokens: []Token
var i = 0
for i < src.len() {
var c = src[i]
if c == ' ' {
i += 1
continue
}
var start = i
if c.is_digit() || c == '.' {
for i < src.len() && (src[i].is_digit() || src[i] == '.') { i += 1 }
tokens.push(Token{Kind.Num, src[start..i], start})
} else if c.is_letter() || c == '_' {
for i < src.len() && (src[i].is_alnum() || src[i] == '_') { i += 1 }
tokens.push(Token{Kind.Name, src[start..i], start})
} else if "+-*/^%=,".contains(string(c)) {
tokens.push(Token{Kind.Op, string(c), start})
i += 1
} else if c == '(' {
tokens.push(Token{Kind.Open, "(", start})
i += 1
} else if c == ')' {
tokens.push(Token{Kind.Close, ")", start})
i += 1
} else {
return tokens, error("unexpected `{c}` at column {i + 1}")
}
}
tokens.push(Token{Kind.End, "", src.len()})
return tokens, nil
}
+13
View File
@@ -0,0 +1,13 @@
// A module: everything marked `pub` can be used by the file that imports it.
import math
pub const UNIT = 1.0
pub struct Point {
pub x, y: float
pub func dist(other: Point): float {
return math.sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y))
}
}
pub func origin(): Point { return Point{0.0, 0.0} }
+6
View File
@@ -0,0 +1,6 @@
import geometry
func main() {
var p = geometry.Point{3.0, 4.0}
print(p.dist(geometry.origin()), geometry.UNIT)
}
+6
View File
@@ -0,0 +1,6 @@
1 100
2 1
3
10 22 11 20
0 1 1
7
+273
View File
@@ -0,0 +1,273 @@
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub struct Span {
pub line: u32,
pub col: u32,
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.line, self.col)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
pub items: Vec<Item>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Item {
Import(Import),
Func(FuncDecl),
Struct(StructDecl),
Enum(EnumDecl),
Interface(InterfaceDecl),
Const(VarDecl),
}
/// `import os`, `import a.b`, or `import c "SDL2/SDL.h"`.
#[derive(Debug, Clone, PartialEq)]
pub struct Import {
pub alias: Option<String>,
pub path: String,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TypeParam {
pub name: String,
pub constraint: Option<Type>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
pub name: String,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FuncDecl {
pub is_pub: bool,
pub name: String,
pub type_params: Vec<TypeParam>,
pub params: Vec<Param>,
pub ret: Option<Type>,
/// `None` for interface method signatures.
pub body: Option<Block>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
pub is_pub: bool,
pub name: String,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
pub struct StructDecl {
pub is_pub: bool,
pub name: String,
pub type_params: Vec<TypeParam>,
pub fields: Vec<Field>,
pub methods: Vec<FuncDecl>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Variant {
pub name: String,
pub fields: Vec<Param>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EnumDecl {
pub is_pub: bool,
pub name: String,
pub type_params: Vec<TypeParam>,
pub variants: Vec<Variant>,
pub methods: Vec<FuncDecl>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceDecl {
pub is_pub: bool,
pub name: String,
pub type_params: Vec<TypeParam>,
pub methods: Vec<FuncDecl>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
/// `int`, `ui.Key`, `Stack[int]`
Named { path: Vec<String>, args: Vec<Type> },
/// `[]T`
Slice(Box<Type>),
/// `T?`
Optional(Box<Type>),
/// `shared T`
Shared(Box<Type>),
/// `weak T`
Weak(Box<Type>),
/// `(A, B)`, only for multiple return values
Tuple(Vec<Type>),
/// `func(A, B) R`
Func { params: Vec<Type>, ret: Option<Box<Type>> },
}
#[derive(Debug, Clone, PartialEq)]
pub struct Block {
pub stmts: Vec<Stmt>,
pub span: Span,
}
/// `var x = 1`, `var a, b = f()`, `const N int = 5`
#[derive(Debug, Clone, PartialEq)]
pub struct VarDecl {
pub is_pub: bool,
pub is_const: bool,
pub names: Vec<String>,
pub ty: Option<Type>,
pub value: Option<Expr>,
pub span: Span,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
Set,
Add,
Sub,
Mul,
Div,
Rem,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ForKind {
/// `for { }`
Infinite,
/// `for cond { }`
While(Expr),
/// `for x in items { }`, `for i, x in items { }`, `for i in 0..10 step 2 { }`
In { vars: Vec<String>, iter: Expr, step: Option<Expr> },
}
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
Var(VarDecl),
Assign { target: Expr, op: AssignOp, value: Expr, span: Span },
Expr(Expr),
If { cond: Expr, then: Block, else_: Option<Box<Stmt>>, span: Span },
For { kind: ForKind, body: Block, span: Span },
Return { values: Vec<Expr>, span: Span },
Break(Span),
Continue(Span),
Block(Block),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
Neg,
Not,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Or,
And,
Eq,
Ne,
Lt,
Gt,
Le,
Ge,
Add,
Sub,
Mul,
Div,
Rem,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StrPart {
Text(String),
Expr(Expr),
}
#[derive(Debug, Clone, PartialEq)]
pub struct FieldInit {
/// `None` for positional initializers like `Vec2{1, 2}`.
pub name: Option<String>,
pub value: Expr,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
Wildcard,
Int(i64),
Char(char),
Str(String),
Bool(bool),
Nil,
/// A bare name: binds a value, or names a variant without data.
Binding(String),
/// `ok(s)`, `Circle(r)`
Variant { name: String, args: Vec<Pattern> },
}
#[derive(Debug, Clone, PartialEq)]
pub enum ArmBody {
Expr(Expr),
Block(Block),
}
#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
pub span: Span,
pub pattern: Pattern,
pub body: ArmBody,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExprKind {
Int(i64),
Float(f64),
Char(char),
Str(Vec<StrPart>),
Bool(bool),
Nil,
Ident(String),
Array(Vec<Expr>),
/// `{"a": 1}` or `map[string, int]{}`: key/value pairs, with the types written out or left to inference
MapLit { types: Option<(Type, Type)>, entries: Vec<(Expr, Expr)> },
StructLit { ty: Box<Expr>, fields: Vec<FieldInit> },
Unary { op: UnOp, expr: Box<Expr> },
Binary { op: BinOp, lhs: Box<Expr>, rhs: Box<Expr> },
/// `a..b`, `a..`, `..b`
Range { start: Option<Box<Expr>>, end: Option<Box<Expr>> },
Call { callee: Box<Expr>, args: Vec<Expr> },
Index { expr: Box<Expr>, index: Box<Expr> },
/// A generic type with its types written out, before `{` or `.`: `Stack[int]{}`, `Option[int].None`
Generic { expr: Box<Expr>, args: Vec<Type> },
Field { expr: Box<Expr>, name: String },
/// `expr?`: return the error to the caller
Try(Box<Expr>),
/// `shared expr`
Shared(Box<Expr>),
/// `weak x`: a non-owning pointer to a shared value
Weak(Box<Expr>),
Closure { params: Vec<Param>, ret: Option<Type>, body: Block },
/// `x => x * 2`, `(a, b) => a + b`: the types come from where it is used
Lambda { params: Vec<String>, body: Box<Expr> },
Match { scrutinee: Box<Expr>, arms: Vec<MatchArm> },
}
+3823
View File
File diff suppressed because it is too large. Load diff
+2650
View File
File diff suppressed because it is too large. Load diff
+110
View File
@@ -0,0 +1,110 @@
//! Ties the compiler stages together and invokes the C compiler.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{Diag, PResult};
use crate::{check, codegen_c, loader, parser};
/// Dino source -> C source, for a program in a single file.
pub fn compile_to_c(src: &str) -> PResult<String> {
let ast = parser::parse(src)?;
let hir = check::check(&ast)?;
Ok(codegen_c::generate(&hir))
}
/// A whole program: the main file and the files it imports. `read(key)` finds a module
/// (see `loader`). Errors come back already rendered, naming the file they are in.
pub fn compile_project(
main_path: &str,
main_src: &str,
mut read: impl FnMut(&str) -> Option<(String, String)>,
) -> Result<String, String> {
let mut seen: HashMap<String, (String, String)> = HashMap::new();
let loaded = loader::load(main_src, &mut |key| {
let found = read(key);
if let Some((path, src)) = &found {
seen.insert(key.to_string(), (path.clone(), src.clone()));
}
found
});
let render = |d: Diag| -> String {
match d.file.as_deref().and_then(|k| seen.get(k)) {
Some((path, src)) => d.render(path, src),
None if d.file.is_some() => d.render(d.file.as_deref().unwrap(), ""),
None => d.render(main_path, main_src),
}
};
let loaded = loaded.map_err(&render)?;
let modules: Vec<(String, crate::ast::Program)> =
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
let hir = check::check_project(&loaded.main, &modules).map_err(&render)?;
Ok(codegen_c::generate(&hir))
}
/// Compile the program whose main file is `path`; imports are found next to it.
pub fn compile_file(path: &str) -> Result<String, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?;
let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
compile_project(path, &src, |key| {
let file = dir.join(format!("{}.dino", key.replace('.', "/")));
std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s))
})
}
fn unique_name(tag: &str, ext: &str) -> PathBuf {
// the counter makes names differ even when two threads ask in the same nanosecond
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
std::env::temp_dir().join(format!("dino-{}-{}-{}-{}{}", std::process::id(), nanos, n, tag, ext))
}
/// A path for a throw-away executable.
pub fn temp_exe() -> PathBuf {
unique_name("exe", if cfg!(windows) { ".exe" } else { "" })
}
/// Compile C source to an executable with the system C compiler (`$CC`, else `cc`).
pub fn build_exe(c_code: &str, out: &Path) -> Result<(), String> {
build_exe_with(c_code, out, &["-O2", "-std=c11", "-fwrapv", "-w"])
}
/// Like `build_exe`, with explicit compiler flags (used by tests to turn on strict warnings).
pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), String> {
let c_file = unique_name("prog", ".c");
std::fs::write(&c_file, c_code).map_err(|e| format!("cannot write {}: {e}", c_file.display()))?;
let cc = std::env::var("CC").unwrap_or_else(|_| "cc".to_string());
let result = Command::new(&cc)
.args(flags)
.arg("-o")
.arg(out)
.arg(&c_file)
.arg("-lm") // the math functions
.output();
let _ = std::fs::remove_file(&c_file);
match result {
Err(e) => Err(format!("cannot run the C compiler `{cc}`: {e}\nInstall one (gcc or clang) or set $CC.")),
Ok(o) if !o.status.success() => Err(format!(
"the C compiler rejected the generated code (this is a bug in Dino):\n{}",
String::from_utf8_lossy(&o.stderr)
)),
Ok(_) => Ok(()),
}
}
/// Check a whole program without building it, for editors: `main_src` is the text of the main
/// file (it may differ from what is on disk) and `read(key)` finds the other files.
/// The error's `file` says which module it is in (`None`: the main file).
pub fn diagnose(
main_src: &str,
mut read: impl FnMut(&str) -> Option<(String, String)>,
) -> Result<(), Diag> {
let loaded = loader::load(main_src, &mut |key| read(key))?;
let modules: Vec<(String, crate::ast::Program)> =
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
check::check_project(&loaded.main, &modules)?;
Ok(())
}
+50
View File
@@ -0,0 +1,50 @@
use crate::ast::Span;
/// A compiler diagnostic pointing at a place in the source.
#[derive(Debug, Clone, PartialEq)]
pub struct Diag {
pub msg: String,
pub span: Span,
/// The module (file) the span belongs to; `None` for the main file.
pub file: Option<String>,
}
impl Diag {
pub fn new(msg: impl Into<String>, span: Span) -> Diag {
Diag { msg: msg.into(), span, file: None }
}
/// Say which module the error is in (the main file has the empty name).
pub fn in_module(mut self, module: &str) -> Diag {
if self.file.is_none() && !module.is_empty() {
self.file = Some(module.to_string());
}
self
}
/// Render like:
/// ```text
/// error: expected `}`, found end of file
/// --> hello.dino:3:10
/// |
/// 3 | func main() {
/// | ^
/// ```
pub fn render(&self, file: &str, src: &str) -> String {
let line_no = self.span.line as usize;
let line = src.lines().nth(line_no.saturating_sub(1)).unwrap_or("");
let gutter = line_no.to_string().len();
let pad = " ".repeat(gutter);
let caret_pad: String = line
.chars()
.take((self.span.col as usize).saturating_sub(1))
.map(|c| if c == '\t' { '\t' } else { ' ' })
.collect();
format!(
"error: {}\n{pad}--> {}:{}:{}\n{pad} |\n{} | {}\n{pad} | {}^",
self.msg, file, self.span.line, self.span.col, line_no, line, caret_pad
)
}
}
pub type PResult<T> = Result<T, Diag>;
+457
View File
@@ -0,0 +1,457 @@
//! The code formatter behind `dino fmt`.
//!
//! It works on the text, not on the syntax tree, so comments and blank lines survive. It
//! never moves a line break: it fixes the indentation, the spaces between tokens and runs of
//! blank lines. Before handing back the result it lexes both versions and checks that they
//! hold exactly the same tokens, so a formatter bug can never change a program.
use crate::error::Diag;
use crate::lexer::{self, StrPart, Tok};
const INDENT: &str = " ";
#[derive(Clone, Copy, PartialEq, Debug)]
enum Kind {
Word,
Num,
Str,
Char,
Punct,
LineComment,
BlockComment,
}
#[derive(Clone, Debug)]
struct Piece {
kind: Kind,
text: String,
/// How many line breaks come before this piece (0: same line).
newlines: usize,
}
const KEYWORDS: &[&str] = &[
"import", "struct", "enum", "interface", "func", "var", "const", "if", "else", "for", "in", "match", "return",
"break", "continue", "pub", "shared", "weak", "step",
];
/// Words that make a following `{` open a block (rather than a struct or map literal).
const BLOCK_WORDS: &[&str] = &["func", "if", "for", "match", "struct", "enum", "interface", "else"];
const BINARY: &[&str] = &[
"+", "-", "*", "/", "%", "==", "!=", "<", ">", "<=", ">=", "&&", "||", "=", "+=", "-=", "*=", "/=", "%=", "=>",
];
/// Format a whole file. Fails (with the problem) if the file doesn't parse.
pub fn format(src: &str) -> Result<String, Diag> {
crate::parser::parse(src)?;
let pieces = scan(src);
let out = print(&pieces);
// the safety net: the same tokens in, the same tokens out
let before = fingerprint(src)?;
let after = fingerprint(&out).map_err(|d| {
Diag::new(format!("the formatter produced code that doesn't lex ({}); this is a bug in `dino fmt`", d.msg), d.span)
})?;
if before != after {
return Err(Diag::new(
"the formatter would change the meaning of this file; this is a bug in `dino fmt`, nothing was written",
crate::ast::Span::default(),
));
}
Ok(out)
}
/// The tokens of `src`, without positions and without repeated line ends.
fn fingerprint(src: &str) -> Result<Vec<String>, Diag> {
let mut out: Vec<String> = Vec::new();
for t in lexer::lex(src)? {
let s = match &t.tok {
Tok::Str(parts) => {
let mut s = String::from("str:");
for p in parts {
match p {
StrPart::Text(t) => s.push_str(&format!("T{t:?}")),
StrPart::Code { src, .. } => s.push_str(&format!("C{src:?}")),
}
}
s
}
Tok::Newline if out.last().map_or(true, |l| l == "Newline") => continue,
other => format!("{other:?}"),
};
out.push(s);
}
Ok(out)
}
// ---------- reading the text ----------
fn string_end(c: &[char], mut i: usize) -> usize {
i += 1; // opening quote
loop {
match c.get(i) {
None => return i,
Some('\\') => i += 2,
Some('"') => return i + 1,
Some('{') => {
let mut depth = 1;
i += 1;
while depth > 0 {
match c.get(i) {
None => return i,
Some('"') => i = string_end(c, i),
Some('{') => {
depth += 1;
i += 1;
}
Some('}') => {
depth -= 1;
i += 1;
}
_ => i += 1,
}
}
}
_ => i += 1,
}
}
}
fn scan(src: &str) -> Vec<Piece> {
let c: Vec<char> = src.chars().collect();
let mut out: Vec<Piece> = Vec::new();
let mut i = 0;
let mut newlines = 0;
let take = |from: usize, to: usize| -> String { c[from..to.min(c.len())].iter().collect() };
while i < c.len() {
let ch = c[i];
if ch == '\n' {
newlines += 1;
i += 1;
continue;
}
if ch.is_whitespace() {
i += 1;
continue;
}
let start = i;
let kind;
if ch == '/' && c.get(i + 1) == Some(&'/') {
while i < c.len() && c[i] != '\n' {
i += 1;
}
kind = Kind::LineComment;
} else if ch == '/' && c.get(i + 1) == Some(&'*') {
i += 2;
while i < c.len() && !(c[i] == '*' && c.get(i + 1) == Some(&'/')) {
i += 1;
}
i = (i + 2).min(c.len());
kind = Kind::BlockComment;
} else if ch == '"' {
i = string_end(&c, i);
kind = Kind::Str;
} else if ch == '\'' {
let len = if c.get(i + 1) == Some(&'\\') { 4 } else { 3 };
if c.get(i + len - 1) == Some(&'\'') {
i += len;
kind = Kind::Char;
} else {
i += 1;
kind = Kind::Punct;
}
} else if ch.is_ascii_digit() {
while i < c.len() && (c[i].is_ascii_digit() || c[i] == '_') {
i += 1;
}
if c.get(i) == Some(&'.') && c.get(i + 1).map_or(false, |d| d.is_ascii_digit()) {
i += 1;
while i < c.len() && (c[i].is_ascii_digit() || c[i] == '_') {
i += 1;
}
}
kind = Kind::Num;
} else if ch.is_alphabetic() || ch == '_' {
while i < c.len() && (c[i].is_alphanumeric() || c[i] == '_') {
i += 1;
}
kind = Kind::Word;
} else {
let two: String = c[i..(i + 2).min(c.len())].iter().collect();
if ["==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=", "%=", "=>", ".."].contains(&two.as_str()) {
i += 2;
} else {
i += 1;
}
kind = Kind::Punct;
}
let mut text = take(start, i);
if kind == Kind::LineComment {
text = text.trim_end().to_string();
}
out.push(Piece { kind, text, newlines });
newlines = 0;
}
out
}
// ---------- printing ----------
fn is_keyword(p: &Piece) -> bool {
p.kind == Kind::Word && KEYWORDS.contains(&p.text.as_str())
}
fn is_closer(p: &Piece) -> bool {
p.kind == Kind::Punct && matches!(p.text.as_str(), "}" | ")" | "]")
}
fn is_binary(p: &Piece) -> bool {
p.kind == Kind::Punct && BINARY.contains(&p.text.as_str())
}
/// Does a value end with this piece? (Then a following `-` is a subtraction.)
fn ends_value(p: &Piece) -> bool {
match p.kind {
Kind::Num | Kind::Str | Kind::Char => true,
Kind::Word => !is_keyword(p) || matches!(p.text.as_str(), "true" | "false" | "nil"),
Kind::Punct => matches!(p.text.as_str(), ")" | "]" | "}" | "?"),
_ => false,
}
}
/// For each `{`: does it open a block (true) or a struct / map literal (false)?
fn classify_braces(p: &[Piece]) -> Vec<bool> {
let mut out = vec![true; p.len()];
// the groups open at this point; `true` for a block `{`
let mut open: Vec<bool> = Vec::new();
for i in 0..p.len() {
let is_punct = p[i].kind == Kind::Punct;
if is_punct && matches!(p[i].text.as_str(), ")" | "]" | "}") {
open.pop();
}
if is_punct && matches!(p[i].text.as_str(), "(" | "[") {
open.push(false);
}
if !(is_punct && p[i].text == "{") {
continue;
}
// a comma ends an argument or an entry, unless it is in a block (`for k, v in m {`)
let comma_stops = open.last().map_or(false, |b| !*b);
out[i] = 'decide: {
if i == 0 || p[i].newlines > 0 || p[i - 1].text == "=>" {
break 'decide true;
}
// look back over this line, at the same nesting level, for a word that starts a block
let mut depth = 0i32;
let mut j = i;
while j > 0 {
j -= 1;
let t = &p[j];
if t.kind == Kind::Punct {
match t.text.as_str() {
")" | "]" | "}" => depth += 1,
"(" | "[" | "{" => {
depth -= 1;
if depth < 0 {
break;
}
}
"," if depth == 0 && comma_stops => break,
_ => {}
}
} else if depth == 0 && t.kind == Kind::Word && BLOCK_WORDS.contains(&t.text.as_str()) {
break 'decide true;
}
if t.newlines > 0 {
break; // start of the line
}
}
false
};
open.push(out[i]);
}
out
}
struct Open {
line: usize,
/// For `{`: true if it opens a block.
block: bool,
}
fn print(p: &[Piece]) -> String {
let braces = classify_braces(p);
let mut lines: Vec<String> = Vec::new();
let mut cur = String::new();
let mut stack: Vec<Open> = Vec::new();
let mut line_no = 0usize;
let mut cont = false; // the previous line ended with an operator
let mut unary_before = false; // the last piece was a prefix `-` / `!`
// lines that end with a `//` comment, and the byte where the comment starts
let mut comment_lines: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
let distinct = |s: &[Open]| -> usize {
let mut n = 0;
let mut last = usize::MAX;
for o in s {
if o.line != last {
n += 1;
last = o.line;
}
}
n
};
for (i, t) in p.iter().enumerate() {
let prev = if i > 0 { Some(&p[i - 1]) } else { None };
let line_start = i == 0 || t.newlines > 0;
if line_start {
if i > 0 {
lines.push(std::mem::take(&mut cur));
line_no += 1;
cont = prev.map_or(false, |l| is_binary(l) && l.kind == Kind::Punct) && !unary_before;
}
// blank lines: at most one, none after an opening bracket or before a closing one
let after_open = prev.map_or(true, |l| l.kind == Kind::Punct && matches!(l.text.as_str(), "{" | "(" | "["));
if t.newlines > 1 && !after_open && !is_closer(t) && i > 0 {
lines.push(String::new());
line_no += 1;
}
// indentation: leading closers don't count the groups they close
let mut k = 0;
while i + k < p.len() && is_closer(&p[i + k]) && (k == 0 || p[i + k].newlines == 0) {
k += 1;
}
let remaining = stack.len().saturating_sub(k);
let mut level = distinct(&stack[..remaining]);
if cont && !is_closer(t) {
level += 1;
}
for _ in 0..level {
cur.push_str(INDENT);
}
} else if let Some(pr) = prev {
let mut space = gap(pr, t, if i > 1 { Some(&p[i - 2]) } else { None }, unary_before, &stack, braces[i]);
if t.kind == Kind::Punct && t.text == "}" {
space = match stack.last() {
Some(o) if o.block => !(pr.kind == Kind::Punct && pr.text == "{"),
_ => false,
};
}
if space {
cur.push(' ');
}
}
// is this `-` / `!` a prefix operator?
let is_prefix = t.kind == Kind::Punct
&& (t.text == "!" || (t.text == "-" && (line_start || prev.map_or(true, |l| !ends_value(l)))));
unary_before = is_prefix;
if t.kind == Kind::LineComment && !line_start {
comment_lines.insert(lines.len(), cur.len());
}
cur.push_str(&t.text);
if t.kind == Kind::Punct {
match t.text.as_str() {
"(" | "[" => stack.push(Open { line: line_no, block: false }),
"{" => stack.push(Open { line: line_no, block: braces[i] }),
")" | "]" | "}" => {
stack.pop();
}
_ => {}
}
}
}
lines.push(cur);
while lines.last().map_or(false, |l| l.is_empty()) {
lines.pop();
}
align_comments(&mut lines, &comment_lines);
let mut out = lines.join("\n");
out.push('\n');
out
}
/// Lines in a row that end with a `//` comment get their comments in one column.
/// `comment_lines` holds, for each line that has one, where its code ends.
fn align_comments(lines: &mut [String], comment_lines: &std::collections::HashMap<usize, usize>) {
let mut i = 0;
while i < lines.len() {
if !comment_lines.contains_key(&i) {
i += 1;
continue;
}
let mut j = i;
while j < lines.len() && comment_lines.contains_key(&j) {
j += 1;
}
let width = (i..j).map(|k| lines[k][..comment_lines[&k]].trim_end().chars().count()).max().unwrap_or(0);
for k in i..j {
let at = comment_lines[&k];
let code = lines[k][..at].trim_end().to_string();
let comment = lines[k][at..].trim_start().to_string();
let pad = width - code.chars().count() + 1;
lines[k] = format!("{code}{}{comment}", " ".repeat(pad));
}
i = j;
}
}
/// Is there a space between `prev` and `cur` (which are on the same line)?
fn gap(prev: &Piece, cur: &Piece, before_prev: Option<&Piece>, prev_is_prefix: bool, stack: &[Open], cur_block: bool) -> bool {
let (pt, ct) = (prev.text.as_str(), cur.text.as_str());
let punct = |p: &Piece, s: &str| p.kind == Kind::Punct && p.text == s;
if cur.kind == Kind::LineComment || cur.kind == Kind::BlockComment || prev.kind == Kind::BlockComment {
return true;
}
if prev_is_prefix {
return false;
}
if prev.kind == Kind::Punct {
match pt {
"(" | "[" | "." | ".." => return false,
"{" => {
// inside a block: `{ x }`; inside a literal: `{a: 1}`
return stack.last().map_or(true, |o| o.block) && !punct(cur, "}");
}
"," | ";" | ":" => return true,
_ => {}
}
}
if cur.kind == Kind::Punct {
match ct {
")" | "]" | "," | ";" | "?" | ":" | "." | ".." => return false,
"{" => {
if cur_block {
return true;
}
// a literal: `Point{...}`, `map[string, int]{}`, but `= {...}`
let attached = (prev.kind == Kind::Word && prev.text.chars().next().map_or(false, |c| c.is_uppercase()))
|| punct(prev, "]");
return !attached;
}
"(" => {
return match prev.kind {
Kind::Word => is_keyword(prev) && prev.text != "func",
Kind::Punct => !matches!(pt, ")" | "]" | "}"),
_ => true,
};
}
"[" => {
return match prev.kind {
Kind::Word => is_keyword(prev),
Kind::Punct => !matches!(pt, ")" | "]"),
_ => true,
};
}
_ => {}
}
}
// `[]int`, `[][]int`: no space after an empty `[]`
if punct(prev, "]") && before_prev.map_or(false, |b| punct(b, "[")) && (cur.kind == Kind::Word || punct(cur, "[")) {
return false;
}
true
}
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more