mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 00:44:27 +00:00
docs: enums, match, generics and the standard library (English and Polish)
This commit is contained in:
parent
ea6d2a57e5
commit
94e41484dd
6 changed files with 275 additions and 13 deletions
|
|
@ -106,7 +106,9 @@ Pick the guide that fits you:
|
|||
| Text | `"a" + "b"`, `str(42)`, `int("42")`, `s.split(",")`, `s.upper()`, `s[0]` |
|
||||
| Control | `if` / `else if` / `else`, `while`, `for i in 0..10`, `break`, `continue`, `defer` |
|
||||
| Memory | automatic for arrays, text and structs; `new(...)` / `free(...)` for your own heap structures |
|
||||
| Modules | `import shapes` → `shapes.area(b)` |
|
||||
| Enums, match | `enum Color { Red, Green }`, `match c { Red -> ... else -> ... }` (also as a value) |
|
||||
| Generics | `fn max[T](T a, T b) -> T`, `struct Stack[T]`, `Stack[int]()` |
|
||||
| Modules | `import shapes` → `shapes.area(b)`; the standard library: `json`, `path`, `time`, `proc` |
|
||||
| C interop | `import "stdio.h"`, `link "glfw"`, `link "mine.c"`, `addr(fn)` for callbacks |
|
||||
| I/O | `print(...)`, `input("? ")`, `read_file`, `write_file`, `shell` |
|
||||
| Tools | `finch run/build/ir/lsp`, `--target windows/arm64/macos`, `-g` for gdb/lldb, `-O0` |
|
||||
|
|
@ -148,8 +150,8 @@ Pick the guide that fits you:
|
|||
- [x] Language server (`finch lsp`) and a VS Code extension
|
||||
- [x] macOS and ARM64 (Linux and Apple Silicon), with their C calling conventions; Kate support
|
||||
- [x] Methods on structs, maps, errors as values (`!`, `or`, `try`)
|
||||
- [ ] Generics, `match`, enums
|
||||
- [ ] A standard library in Finch (JSON, paths, time, processes)
|
||||
- [x] Generics (`fn max[T]`, `struct Stack[T]`), `match`, enums
|
||||
- [x] A standard library in Finch: `json`, `path`, `time`, `proc`
|
||||
|
||||
## Layout
|
||||
|
||||
|
|
|
|||
|
|
@ -105,7 +105,9 @@ Wybierz przewodnik dla siebie:
|
|||
| Tekst | `"a" + "b"`, `str(42)`, `int("42")`, `s.split(",")`, `s.upper()`, `s[0]` |
|
||||
| Sterowanie | `if` / `else if` / `else`, `while`, `for i in 0..10`, `break`, `continue`, `defer` |
|
||||
| Pamięć | automatyczna dla tablic, tekstów i struktur; `new(...)` / `free(...)` dla własnych struktur na stercie |
|
||||
| Moduły | `import ksztalty` → `ksztalty.pole(p)` |
|
||||
| Enumy, match | `enum Kolor { Czerwony, Zielony }`, `match k { Czerwony -> ... else -> ... }` (także jako wartość) |
|
||||
| Generyki | `fn max[T](T a, T b) -> T`, `struct Stos[T]`, `Stos[int]()` |
|
||||
| Moduły | `import ksztalty` → `ksztalty.pole(p)`; biblioteka standardowa: `json`, `path`, `time`, `proc` |
|
||||
| Współpraca z C | `import "stdio.h"`, `link "glfw"`, `link "moje.c"`, `addr(fn)` dla callbacków |
|
||||
| Wejście/wyjście | `print(...)`, `input("? ")`, `read_file`, `write_file`, `shell` |
|
||||
| Narzędzia | `finch run/build/ir/lsp`, `--target windows/arm64/macos`, `-g` dla gdb/lldb, `-O0` |
|
||||
|
|
@ -147,8 +149,8 @@ Wybierz przewodnik dla siebie:
|
|||
- [x] Serwer języka (`finch lsp`) i rozszerzenie VS Code
|
||||
- [x] macOS i ARM64 (Linux i Apple Silicon) z ich konwencjami wywołań C; obsługa Kate
|
||||
- [x] Metody w strukturach, mapy, błędy jako wartości (`!`, `or`, `try`)
|
||||
- [ ] Typy generyczne, `match`, enumy
|
||||
- [ ] Biblioteka standardowa w Finchu (JSON, ścieżki, czas, procesy)
|
||||
- [x] Typy generyczne (`fn max[T]`, `struct Stos[T]`), `match`, enumy
|
||||
- [x] Biblioteka standardowa w Finchu: `json`, `path`, `time`, `proc`
|
||||
|
||||
## Struktura
|
||||
|
||||
|
|
|
|||
|
|
@ -370,7 +370,35 @@ Any LSP editor: `finch lsp`.
|
|||
|
||||
---
|
||||
|
||||
## Enums and `match`
|
||||
|
||||
```
|
||||
enum Color { Red, Green, Blue } enum Status { Ok = 200, NotFound = 404 }
|
||||
c := Color.Green int(c) Color(2) c == Color.Red // == and != only; Color(7) is an error
|
||||
fn Color.next() -> Color { ... } // methods work
|
||||
|
||||
match c { Red -> ... Green, Blue -> { ... } else -> ... } // bare variant names; every variant or else
|
||||
x := match n { 1, 2 -> "few" else -> "many" } // an expression: every arm the same type
|
||||
```
|
||||
|
||||
## Generics
|
||||
|
||||
```
|
||||
fn max[T](T a, T b) -> T { ... } max(3, 9) max[float](1, 2.5) // worked out, or written out
|
||||
struct Stack[T] { []T items } fn Stack[T].push(T x) { ... } // the type goes with it:
|
||||
s := Stack[int]() Stack[int] t Pair[str, int]("age", 31) // never just Stack()
|
||||
```
|
||||
|
||||
## Standard library (`import name`; your own file of that name wins)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `path` | `join(a, b)` `base(p)` `dir(p)` `ext(p)` `stem(p)` `parts(p)` `clean(p)` `is_abs(p)` |
|
||||
| `time` | `now()` `millis()` `sleep(ms)` `date(t)` `local(t)` `format(t, fmt)` `days_in_month(y, m)` |
|
||||
| `proc` | `run(cmd)` `output(cmd)` (fails with its output) `env(name, fallback)` `pid()` `cwd()` |
|
||||
| `json` | `parse(text)` `stringify(v)` `pretty(v)` `new_text/number/bool/null/list/object` `v.get(k)` `v.at(i)` `v.set(k, x)` `v.push(x)` `v.has(k)` `v.str_or(d)` `v.int_or(d)` `v.float_or(d)` `v.bool_or(d)` |
|
||||
|
||||
## Keywords
|
||||
|
||||
`fn return if else while for in break continue true false null import link struct defer or try`
|
||||
`fn return if else while for in break continue true false null import link struct enum match defer or try`
|
||||
(and `self` inside methods)
|
||||
|
|
|
|||
|
|
@ -33,7 +33,10 @@ compiler works inside. For that, see the [guide for engineers](for-engineers.md)
|
|||
20. [Debugging](#20-debugging)
|
||||
21. [Troubleshooting](#21-troubleshooting)
|
||||
22. [Project layout and tests](#22-project-layout-and-tests)
|
||||
23. [Current limits](#23-current-limits)
|
||||
23. [Enums and match](#23-enums-and-match)
|
||||
24. [Generics](#24-generics)
|
||||
25. [The standard library](#25-the-standard-library)
|
||||
26. [Current limits](#26-current-limits)
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -961,11 +964,108 @@ python3 tests/lsp_test.py # the language server
|
|||
|
||||
---
|
||||
|
||||
## 23. Current limits
|
||||
## 23. Enums and match
|
||||
|
||||
An **enum** is a type with a short list of named values.
|
||||
|
||||
```
|
||||
enum Color { Red, Green, Blue }
|
||||
enum Status { Ok = 200, NotFound = 404 } // give a variant a number if it needs one
|
||||
|
||||
c := Color.Green
|
||||
print(c) // Green
|
||||
print(int(Status.NotFound)) // 404
|
||||
print(Color(2)) // Blue: a number turned into the enum (checked: Color(7) is an error)
|
||||
```
|
||||
|
||||
Variants are written `Color.Red`. They can be compared with `==` and `!=` (not with `<`), used as map keys,
|
||||
struct fields and array elements, and an enum can have methods like a struct: `fn Color.next() -> Color { ... }`.
|
||||
|
||||
**match** picks what to do from a value, instead of a ladder of `if`:
|
||||
|
||||
```
|
||||
match c {
|
||||
Red -> print("warm") // inside a match on an enum, the bare name is enough
|
||||
Green, Blue -> print("cool") // several values for one arm
|
||||
}
|
||||
|
||||
size := match n { // as an expression: it gives a value
|
||||
1, 2, 3 -> "small"
|
||||
4, 5 -> "medium"
|
||||
else -> "large"
|
||||
}
|
||||
|
||||
match word {
|
||||
"quit" -> {
|
||||
print("bye")
|
||||
return
|
||||
}
|
||||
else -> print("what?")
|
||||
}
|
||||
```
|
||||
|
||||
`match` works on enums, whole numbers, chars, text and bools. The arms are tried in order. A match on an enum has to
|
||||
handle **every variant** or end with `else` (the compiler says which are missing); any other match needs `else`.
|
||||
In an expression, every arm gives the same type.
|
||||
|
||||
## 24. Generics
|
||||
|
||||
Write a function or a struct once for any type, with the type as a name in square brackets:
|
||||
|
||||
```
|
||||
fn max[T](T a, T b) -> T {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
struct Stack[T] {
|
||||
[]T items
|
||||
}
|
||||
|
||||
fn Stack[T].push(T x) {
|
||||
self.items.push(x)
|
||||
}
|
||||
|
||||
print(max(3, 9), max("apple", "pear")) // T is worked out from the arguments
|
||||
print(max[float](1, 2.5)) // or written out, where it can't be worked out
|
||||
s := Stack[int]() // a generic struct is always written with its type
|
||||
s.push(7)
|
||||
```
|
||||
|
||||
Several parameters work (`struct Pair[A, B]`), and so do nested types (`Stack[Pair[int, str]]`). Each use makes its
|
||||
own copy of the code, so a generic is as fast as code written by hand. There are no constraints: if `T` can't do
|
||||
what the function does (`a > b` on a struct), the error says so and tells which version it was building, like
|
||||
`(while building bigger[Point])`.
|
||||
|
||||
## 25. The standard library
|
||||
|
||||
Modules that come with Finch, written in Finch. `import json` finds `json.fch` next to your file first, and the
|
||||
library's second, so your own file of the same name wins.
|
||||
|
||||
| Module | What it does |
|
||||
|---|---|
|
||||
| `path` | `join`, `base`, `dir`, `ext`, `stem`, `parts`, `clean`, `is_abs`: paths as text, separated by `/` |
|
||||
| `time` | `now()`, `millis()` (a clock for measuring), `sleep(ms)`, `date(t)`, `local(t)`, `format(t, "%Y-%m-%d")`, `days_in_month` |
|
||||
| `proc` | `run(cmd)` (the exit code), `output(cmd)` (what it printed; an error if it failed), `env(name, fallback)`, `pid()`, `cwd()` |
|
||||
| `json` | `parse(text)`, `stringify(v)`, `pretty(v)`, and the value type `Json` with `get`, `at`, `set`, `push`, `has`, `str_or`, `int_or` ... |
|
||||
|
||||
```
|
||||
import json
|
||||
import path
|
||||
|
||||
doc := try json.parse(read_file("config.json"))
|
||||
name := doc.get("name").str_or("unnamed") // a missing key is null, so chains never fail
|
||||
doc.set("name", json.new_text(name + "!"))
|
||||
write_file(path.join("out", "config.json"), json.pretty(doc))
|
||||
```
|
||||
|
||||
## 26. Current limits
|
||||
|
||||
Not there yet:
|
||||
|
||||
- Generics (your own `List[T]`), interfaces, `match`, enums written in Finch.
|
||||
- Interfaces, and enums whose variants carry values (`Circle(radius)`).
|
||||
- Unicode-aware text: `.len`, `s[i]` and `upper()` work on bytes / ASCII.
|
||||
- Threads.
|
||||
- Windows on ARM64, 32-bit systems, WebAssembly.
|
||||
|
|
|
|||
|
|
@ -33,7 +33,10 @@ kompilator działa w środku. Do tego służy [przewodnik dla inżynierów](dla-
|
|||
20. [Debugowanie](#20-debugowanie)
|
||||
21. [Rozwiązywanie problemów](#21-rozwiązywanie-problemów)
|
||||
22. [Struktura projektu i testy](#22-struktura-projektu-i-testy)
|
||||
23. [Obecne ograniczenia](#23-obecne-ograniczenia)
|
||||
23. [Enumy i match](#23-enumy-i-match)
|
||||
24. [Typy generyczne](#24-typy-generyczne)
|
||||
25. [Biblioteka standardowa](#25-biblioteka-standardowa)
|
||||
26. [Obecne ograniczenia](#26-obecne-ograniczenia)
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -964,11 +967,108 @@ python3 tests/lsp_test.py # serwer języka
|
|||
|
||||
---
|
||||
|
||||
## 23. Obecne ograniczenia
|
||||
## 23. Enumy i match
|
||||
|
||||
**Enum** to typ z krótką listą nazwanych wartości.
|
||||
|
||||
```
|
||||
enum Kolor { Czerwony, Zielony, Niebieski }
|
||||
enum Status { Ok = 200, Brak = 404 } // wariantowi można nadać numer
|
||||
|
||||
k := Kolor.Zielony
|
||||
print(k) // Zielony
|
||||
print(int(Status.Brak)) // 404
|
||||
print(Kolor(2)) // Niebieski: liczba zamieniona na enum (sprawdzana: Kolor(7) to błąd)
|
||||
```
|
||||
|
||||
Warianty pisze się `Kolor.Czerwony`. Można je porównywać przez `==` i `!=` (nie przez `<`), używać jako klucze map,
|
||||
pola struktur i elementy tablic, a enum może mieć metody jak struktura: `fn Kolor.nastepny() -> Kolor { ... }`.
|
||||
|
||||
**match** wybiera, co zrobić, na podstawie wartości — zamiast drabinki `if`:
|
||||
|
||||
```
|
||||
match k {
|
||||
Czerwony -> print("ciepły") // w matchu na enumie wystarczy sama nazwa
|
||||
Zielony, Niebieski -> print("zimny") // kilka wartości w jednej gałęzi
|
||||
}
|
||||
|
||||
rozmiar := match n { // jako wyrażenie: daje wartość
|
||||
1, 2, 3 -> "mały"
|
||||
4, 5 -> "średni"
|
||||
else -> "duży"
|
||||
}
|
||||
|
||||
match slowo {
|
||||
"koniec" -> {
|
||||
print("pa")
|
||||
return
|
||||
}
|
||||
else -> print("co?")
|
||||
}
|
||||
```
|
||||
|
||||
`match` działa na enumach, liczbach całkowitych, znakach, tekście i bool. Gałęzie sprawdzane są po kolei. Match na
|
||||
enumie musi obsłużyć **każdy wariant** albo kończyć się `else` (kompilator wskaże brakujące); każdy inny match
|
||||
potrzebuje `else`. W wyrażeniu wszystkie gałęzie dają ten sam typ.
|
||||
|
||||
## 24. Typy generyczne
|
||||
|
||||
Napisz funkcję lub strukturę raz dla dowolnego typu, z typem jako nazwą w nawiasach kwadratowych:
|
||||
|
||||
```
|
||||
fn max[T](T a, T b) -> T {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
struct Stos[T] {
|
||||
[]T elementy
|
||||
}
|
||||
|
||||
fn Stos[T].dodaj(T x) {
|
||||
self.elementy.push(x)
|
||||
}
|
||||
|
||||
print(max(3, 9), max("jabłko", "gruszka")) // T wynika z argumentów
|
||||
print(max[float](1, 2.5)) // albo zapisane wprost, gdzie nie da się go ustalić
|
||||
s := Stos[int]() // generyczną strukturę zawsze pisze się z typem
|
||||
s.dodaj(7)
|
||||
```
|
||||
|
||||
Parametrów może być kilka (`struct Para[A, B]`), typy można zagnieżdżać (`Stos[Para[int, str]]`). Każde użycie tworzy
|
||||
własną kopię kodu, więc generyk jest tak szybki jak kod napisany ręcznie. Nie ma ograniczeń: jeśli `T` nie potrafi
|
||||
tego, co robi funkcja (`a > b` na strukturze), błąd mówi o tym i podaje, którą wersję budowano, np.
|
||||
`(while building wiekszy[Punkt])`.
|
||||
|
||||
## 25. Biblioteka standardowa
|
||||
|
||||
Moduły dołączone do Fincha, napisane w Finchu. `import json` szuka najpierw `json.fch` obok Twojego pliku, potem w
|
||||
bibliotece — więc Twój własny plik o tej nazwie ma pierwszeństwo.
|
||||
|
||||
| Moduł | Co robi |
|
||||
|---|---|
|
||||
| `path` | `join`, `base`, `dir`, `ext`, `stem`, `parts`, `clean`, `is_abs`: ścieżki jako tekst, rozdzielone `/` |
|
||||
| `time` | `now()`, `millis()` (zegar do mierzenia), `sleep(ms)`, `date(t)`, `local(t)`, `format(t, "%Y-%m-%d")`, `days_in_month` |
|
||||
| `proc` | `run(cmd)` (kod wyjścia), `output(cmd)` (co wypisało; błąd, jeśli się nie udało), `env(nazwa, domyślna)`, `pid()`, `cwd()` |
|
||||
| `json` | `parse(tekst)`, `stringify(v)`, `pretty(v)` oraz typ wartości `Json` z `get`, `at`, `set`, `push`, `has`, `str_or`, `int_or` ... |
|
||||
|
||||
```
|
||||
import json
|
||||
import path
|
||||
|
||||
dok := try json.parse(read_file("config.json"))
|
||||
nazwa := dok.get("name").str_or("bez nazwy") // brakujący klucz to null, więc łańcuch nigdy się nie psuje
|
||||
dok.set("name", json.new_text(nazwa + "!"))
|
||||
write_file(path.join("out", "config.json"), json.pretty(dok))
|
||||
```
|
||||
|
||||
## 26. Obecne ograniczenia
|
||||
|
||||
Jeszcze nie ma:
|
||||
|
||||
- Typów generycznych (własnego `Lista[T]`), interfejsów, `match`, enumów pisanych w Finchu.
|
||||
- Interfejsów i enumów, których warianty niosą wartości (`Kolo(promien)`).
|
||||
- Tekstu świadomego Unicode: `.len`, `s[i]` i `upper()` działają na bajtach / ASCII.
|
||||
- Wątków.
|
||||
- Windowsa na ARM64, systemów 32-bitowych, WebAssembly.
|
||||
|
|
|
|||
|
|
@ -370,6 +370,34 @@ Każdy edytor z LSP: `finch lsp`.
|
|||
|
||||
---
|
||||
|
||||
## Enumy i `match`
|
||||
|
||||
```
|
||||
enum Kolor { Czerwony, Zielony } enum Status { Ok = 200, Brak = 404 }
|
||||
k := Kolor.Zielony int(k) Kolor(1) k == Kolor.Czerwony // tylko == i !=; Kolor(7) to błąd
|
||||
fn Kolor.nastepny() -> Kolor { ... } // metody działają
|
||||
|
||||
match k { Czerwony -> ... Zielony -> { ... } else -> ... } // same nazwy wariantów; każdy wariant albo else
|
||||
x := match n { 1, 2 -> "mało" else -> "dużo" } // wyrażenie: gałęzie tego samego typu
|
||||
```
|
||||
|
||||
## Typy generyczne
|
||||
|
||||
```
|
||||
fn max[T](T a, T b) -> T { ... } max(3, 9) max[float](1, 2.5) // wynika z argumentów albo zapisane
|
||||
struct Stos[T] { []T elementy } fn Stos[T].dodaj(T x) { ... } // typ zawsze podaje się przy tworzeniu:
|
||||
s := Stos[int]() Stos[int] t Para[str, int]("wiek", 31) // nigdy samo Stos()
|
||||
```
|
||||
|
||||
## Biblioteka standardowa (`import nazwa`; własny plik o tej nazwie ma pierwszeństwo)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `path` | `join(a, b)` `base(p)` `dir(p)` `ext(p)` `stem(p)` `parts(p)` `clean(p)` `is_abs(p)` |
|
||||
| `time` | `now()` `millis()` `sleep(ms)` `date(t)` `local(t)` `format(t, fmt)` `days_in_month(r, m)` |
|
||||
| `proc` | `run(cmd)` `output(cmd)` (błąd z jego wyjściem) `env(nazwa, domyślna)` `pid()` `cwd()` |
|
||||
| `json` | `parse(tekst)` `stringify(v)` `pretty(v)` `new_text/number/bool/null/list/object` `v.get(k)` `v.at(i)` `v.set(k, x)` `v.push(x)` `v.has(k)` `v.str_or(d)` `v.int_or(d)` `v.float_or(d)` `v.bool_or(d)` |
|
||||
|
||||
## Słowa kluczowe
|
||||
|
||||
| Słowo | Po polsku |
|
||||
|
|
@ -383,6 +411,8 @@ Każdy edytor z LSP: `finch lsp`.
|
|||
| `true` / `false` / `null` | prawda / fałsz / nic |
|
||||
| `import` / `link` | zaimportuj / dolinkuj |
|
||||
| `struct` | struktura |
|
||||
| `enum` | wyliczenie |
|
||||
| `match` | dopasuj |
|
||||
| `defer` | odłóż (na koniec bloku) |
|
||||
| `or` | albo (co zrobić przy porażce) |
|
||||
| `try` | spróbuj (porażkę przekaż dalej) |
|
||||
|
|
|
|||
Loading…
Reference in a new issue