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:
1 parent
3e2779f447
commit
eaf9567a36
117 files changed
+19970
No files matched your search
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
Reference in new issue
Block a user