# Plumlang documentation > Plumlang is a small, fast, memory-safe programming language with easy syntax, static types, tasks and a built-in HTTP server, shipped as one binary. An Elixpo production. Plumlang source files end in `.plum`. `plum check FILE` reports every error without running anything; `plum run FILE` runs a program; `plum stdlib MODULE` lists a module's functions. Keywords keep a garden theme: `plant` (variable), `root` (constant), `branch` (function), `tree` (class), `seed` (import), `drop` (print), `good` / `bad` (true / false). Plumlang is new: read the documentation instead of guessing its syntax from other languages. Every docs page is also available as Markdown at its URL plus `index.md`. Install: `curl -fsSL https://github.com/plumlang/plumlang/releases/latest/download/install.sh | sh` (Linux, macOS) or `irm https://github.com/plumlang/plumlang/releases/latest/download/install.ps1 | iex` (Windows PowerShell). Details: https://plum.elixpo.com/docs/install/ This file holds the whole language on one page, then the tour, the language specification, the standard library, the tools (packages, language server, REPL, WebAssembly), and every error code, as Markdown. It is generated from https://plum.elixpo.com and the docs of https://github.com/plumlang/plumlang at commit 9e6dffaa344c. Each part starts with the URL of its page. --- Source: https://plum.elixpo.com/docs/reference/ # Plumlang reference > The whole language on one page, for a quick read or for a coding agent. The whole language on one page, for people who know another language and for coding agents. The [specification](https://plum.elixpo.com/docs/language/) is the full contract; this page is checked by `make test`: every `plum` block passes `plum check`, and every `output` block is exactly what the block before it prints. ## Rules that differ from other languages - Print with `drop(...)`, always with parentheses. There is no `print`. - Variables are `plant`, constants `root`, functions `branch`, classes `tree`, imports `seed`. Booleans are `good` / `bad` (`true` / `false` also work). The absent value is `none`. - No semicolons; a statement ends at the end of its line. Comments start with `#`; there are no block comments. - Types follow names: `x: int`, `branch f(a: int) -> str`. Parameter types and non-`none` results are always written; local types are inferred. - No truthiness: conditions must be `bool` (`if n > 0`, not `if n`). - `/` always gives a `float`; `//` is integer division. Integer overflow is an error, never wrap-around. - `and`, `or`, `not`: there is no `&&`, `||`, `!`, `++` or `--`. - Only `T?` types can be `none`. Use `??`, `?.` or `if plant x = opt`. - Strings, lists, maps and sets are values: assigning copies them. Tree objects are shared references. - An empty list or map needs a type: `plant xs: list[int] = []`, `plant m: map[str, int] = {:}`. ## A complete program ```plum seed math root GREETING = "Hello" tree Planet { name: str radius_km: float branch area() -> float => 4.0 * math.PI * self.radius_km ** 2 } plant planets = [Planet("Mercury", 2439.7), Planet("Earth", 6371.0)] for p in planets { drop("{GREETING}, {p.name}! {p.area():.0} km²") } ``` ```output Hello, Mercury! 74796748 km² Hello, Earth! 510064472 km² ``` ## Values and types | Type | Literals | |---|---| | `int` (64-bit) | `42`, `1_000_000`, `0xFF`, `0o755`, `0b1010` | | `float` (64-bit) | `3.14`, `1e9`, `2.5e-3` (not `.5` or `5.`) | | `bool` | `good`, `bad` | | `str` (UTF-8, immutable) | `"text"`, `"tab\t, unicode \u{1F351}"`, `"""multi-line"""` | | `byte` | `byte(255)` | | `none` | `none` | | `list[T]` | `[1, 2, 3]` | | `map[K, V]` | `{"a": 1}`, empty `{:}` | | `set[T]` | `set([1, 2])` | | `T?` | a `T` or `none` | | `(int, int) -> int` | a function | ```plum plant count = 3 # int, inferred plant ratio: float = 1 # an int becomes a float where a float is expected plant name: str? = none plant total = 7 / 2 # 3.5: / always gives a float plant whole = 7 // 2 # 3 plant text = str(42) + " " + str(1.5) plant parsed = int("42") # throws ParseError on bad input plant safe = try int("x") ?? 0 # try as an expression: an error becomes none drop(count, ratio, name ?? "anon", total, whole, text, parsed, safe, type_of(ratio)) ``` ```output 3 1.0 anon 3.5 3 42 1.5 42 0 float ``` ## Strings ```plum plant name = "Ada" plant price = 3.14159 drop("Hello, {name}! {2 + 2} {price:.2} [{name:>6}] [{name:<6}] {255:x}") drop(name.upper(), name.lower(), len(name), name[0], name[1..3]) drop("a,b,c".split(","), " hi ".trim(), "plum".replace("p", "P")) drop("plum".starts_with("pl"), "plum".contains("lu"), "plum".find("u") ?? -1) plant poem = """ Roses are red, Plums are purple. """ drop(poem.lines()) ``` ```output Hello, Ada! 4 3.14 [ Ada] [Ada ] ff ADA ada 3 A da ["a", "b", "c"] hi Plum good good 2 ["Roses are red,", "Plums are purple."] ``` String methods: `upper lower trim trim_start trim_end split lines chars contains starts_with ends_with find count replace repeat reverse pad_start pad_end is_digit is_alpha is_space byte_len url_encode url_decode`. `plum stdlib str` lists them with signatures. ## Operators From lowest to highest precedence: `??` · `or` · `and` · `not` · `== != < <= > >= is in` · `.. ..=` · `|` · `^` · `&` · `<< >>` · `+ -` · `* / // %` · unary `- ~` · `**` · `as` · call, index, `.`, `?.`. Comparisons don't chain (`a < b < c` is an error). `x in xs` tests membership in a list, set, map (keys) or string. Compound assignment: `+= -= *= /= //= %= **= &= |= ^= <<= >>=`. ## Collections ```plum plant xs = [3, 1, 2] xs.push(4) drop(xs, len(xs), xs[0], xs[1..3], xs.sorted(), 2 in xs) drop(xs.map((n) => n * 10), xs.filter((n) => n > 1), xs.reduce((a, n) => a + n, 0)) drop(xs.sorted_by((n) => -n), xs.any((n) => n > 3), xs.all((n) => n > 0), xs.find((n) => n > 2) ?? 0) for i, x in xs.enumerate() { drop(i, x) } plant ages: map[str, int] = {:} ages["Ada"] = 36 ages["Alan"] = 41 drop(ages, ages.get("Bob") ?? 0, "Ada" in ages, ages.keys()) for name, age in ages { drop("{name} is {age}") } plant seen = set([1, 2, 2]) seen.add(3) drop(seen, len(seen)) plant a = [1, 2] plant b = a # a copy: lists are values b.push(3) drop(a, b) ``` ```output [3, 1, 2, 4] 4 3 [1, 2] [1, 2, 3, 4] good [30, 10, 20, 40] [3, 2, 4] 10 [4, 3, 2, 1] good good 3 0 3 1 1 2 2 3 4 {"Ada": 36, "Alan": 41} 0 good ["Ada", "Alan"] Ada is 36 Alan is 41 set([1, 2, 3]) 3 [1, 2] [1, 2, 3] ``` | Type | Methods | |---|---| | `list[T]` | `push pop insert remove_at clear reverse sort sorted sorted_by contains index_of join map filter reduce any all find enumerate` | | `map[K, V]` | `get remove keys values clear` (`m[k]` throws `KeyError` if missing; `m.get(k)` gives `V?`) | | `set[T]` | `add remove contains clear` | ## Control flow ```plum plant score = 85 if score >= 90 { drop("A") } else if score >= 80 { drop("B") } else { drop("C") } plant label = if score == 1 { "point" } else { "points" } for i in 0..3 { # 0 1 2; 0..=3 includes 3 if i == 1 { continue } drop(i) } plant n = 10 while n > 0 { n -= 4 } plant command = "stop" match command { "start" => drop("starting") "stop", "halt" => drop("stopping") else => drop("unknown") } plant grade = match score { 90..=100 => "excellent" 50..90 => "pass" else => "fail" } drop(label, n, grade) ``` ```output B 0 2 stopping points -2 pass ``` ## Functions ```plum branch add(a: int, b: int) -> int { return a + b } branch square(x: int) -> int => x * x branch connect(host: str, port: int = 80, secure: bool = bad) -> str { return "{host}:{port} secure={secure}" } branch greet(name: str) { # no result type: returns none drop("Hello, {name}") } plant double = (x: int) => x * 2 plant apply = (f: (int) -> int, x: int) => f(x) drop(add(2, 3), square(4), apply(double, 21)) drop(connect("example.com", secure: good)) greet("Ada") ``` ```output 5 16 42 example.com:80 secure=good Hello, Ada ``` Parameters are read-only. A function cannot change a caller's list; it returns a new one, or takes a tree object, which is shared. ## Trees (classes), traits and kinds ```plum trait Shape { branch area() -> float branch name() -> str => "shape" # a default method } tree Circle : Shape { radius: float branch area() -> float => 3.14159 * self.radius ** 2 branch name() -> str => "circle" } tree Account { owner: str balance: float = 0.0 # fields with defaults may be left out _audit: list[str] = [] # _names are private branch deposit(amount: float) { if amount <= 0 { throw ValueError("deposit must be positive") } self.balance += amount # fields are always reached through self self._audit.push("deposit {amount}") } branch to_str() -> str => "{self.owner}: {self.balance:.2}" # how it prints } tree Savings : Account { # single inheritance rate: float = 0.02 branch deposit(amount: float) { super.deposit(amount * (1.0 + self.rate)) } } tree Temperature { celsius: float branch init(fahrenheit: float) { # a custom constructor self.celsius = (fahrenheit - 32.0) * 5.0 / 9.0 } } kind Direction { North, East, South, West } kind Payment { Cash Card(last4: str) } branch describe(p: Payment) -> str => match p { Cash => "cash" Card(digits) => "card ending {digits}" } plant acct = Account("Ada") acct.deposit(50) plant shared = acct # the same object, not a copy shared.deposit(25) plant saver = Savings("Grace") saver.deposit(100) plant shapes: list[Shape] = [Circle(1.0)] drop(acct, saver, shapes[0].name(), shapes[0] is Shape) drop(Temperature(212.0).celsius, Direction.North, describe(Payment.Card("4242"))) ``` ```output Ada: 75.00 Grace: 102.00 circle good 100.0 Direction.North card ending 4242 ``` Methods the language calls: `to_str() -> str` (printing), `equals(other: T) -> bool` (`==`), `compare(other: T) -> int` (`<`, `sorted`), and `plus`, `minus`, `times`, `divided_by`, `negate` (operators). Without `equals`, `==` on tree objects asks whether they are the same object. A `match` on a kind must cover every case, or end with `else`. ## Optionals ```plum branch find_user(id: int) -> str? => if id == 1 { "ada" } else { none } plant who = find_user(2) drop(who ?? "nobody") # a default drop(find_user(1)?.upper()) # a none-safe call gives a str? if plant name = find_user(1) { # unwrap: name is a str inside drop("found {name}") } ``` ```output nobody ADA found ada ``` ## Errors ```plum tree NotFound : Error { path: str } branch load(path: str) -> str { throw NotFound("no such file", path) } try { load("config.txt") } catch e: NotFound { drop("missing: {e.path}") } catch e { drop("other: {e.message}") } finally { drop("done") } try { plant xs = [1] drop(xs[5]) } catch e: IndexError { drop("caught {type_of(e)}") } ``` ```output missing: config.txt done caught IndexError ``` Built-in error trees: `Error` (the base, with `message`), `ValueError`, `ParseError`, `IndexError`, `KeyError`, `OverflowError`, `ZeroDivisionError`, `IOError`, `NetError`, `AssertError`. An uncaught error prints a stack trace and exits with code 1. ## Modules and packages ```text seed math # standard library: math.sqrt(2.0) seed net.http # use as http.server() seed net.http as web # an alias seed math { sqrt, PI } # names brought in directly seed ./shapes # shapes.plum next to this file: shapes.area(c) seed ./models/user as user # models/user.plum ``` Every file is a module; its top-level code runs once, on first import. Imports come first in a file. Names starting with `_` are private. A folder with a `plum.toml` (`[package]` with `name`, `version`, `entry`) is a package: `plum run folder` runs its entry file. ## Tasks and channels ```plum seed time branch slow_square(n: int) -> int { time.sleep(0.01) return n * n } plant job = spawn slow_square(7) # runs concurrently; no async/await plant ch = Channel[int]() spawn (() => { for i in 0..3 { ch.send(i) } ch.close() })() for n in ch { drop("got {n}") } drop(job.wait()) ``` ```output got 0 got 1 got 2 49 ``` Tasks run on one thread and share nothing: values are copied into a task, and they talk through channels. A call that waits (network, files, timers, channels) pauses only its own task. ## Standard library | Module | For | |---|---| | `math` | numbers, constants, random numbers | | `str` | string methods (always available) | | `io` | standard input, output, error | | `os` | arguments, environment, running commands | | `time` | clocks, sleeping, dates | | `fs` | files and directories | | `json` | parse and produce JSON (`Json` values) | | `net` | TCP, UDP, TLS, DNS | | `net.http` | an HTTP(S) server and client | Built-in functions, no `seed` needed: `drop`, `ask`, `len`, `int`, `float`, `str`, `byte`, `type_of`, `assert`, `exit`. ```plum seed net.http plant app = http.server() app.get("/hello/:name", (req) => http.text("Hello, {req.params["name"]}!")) app.listen(8080) ``` `plum stdlib` lists every function with its signature; each module has a page in [docs/stdlib](https://plum.elixpo.com/docs/stdlib/). ## The plum command ```text plum run program.plum [args...] run a program (or a folder with plum.toml) plum check program.plum report every error without running plum fmt files-or-folders... format in place (--check, --stdout) plum stdlib [module] list the standard library plum lsp the language server for editors (lsp.md) plum run --check-leaks file.plum report objects kept alive by cycles plum run --mem-stats file.plum report memory used plum version ``` Exit codes: 0 success, 1 the program failed, 2 wrong usage, 3 unreadable source. Errors give `file:line:column`, an error code (`E0402`), what is wrong and a hint; [errors.md](https://plum.elixpo.com/docs/errors/) explains each code. ## For coding agents - Run `plum check file.plum` after every edit, and fix the errors it reports before running. It reports all of them at once. - When a method name is unsure, run `plum stdlib` or `plum stdlib MODULE` rather than guessing names from other languages. - Format with `plum fmt`. --- Source: https://plum.elixpo.com/docs/tour/ # A tour of Plumlang > Learn the language in eleven short steps, each with programs you can run. Each step is one idea, with small complete programs and the output they print. No programming experience is assumed. The keywords keep a garden theme: you `plant` a variable, `drop` a value on the screen, grow a `branch` (a function) and a `tree` (a class), and `seed` a module. Everything else reads like English: `and`, `or`, `not`, `if`, `for`. ## How to follow along [Install Plumlang](https://plum.elixpo.com/docs/install/), save a program in a file ending in `.plum`, and run it: ```bash plum check hello.plum # find mistakes, run nothing plum run hello.plum # run it ``` ## The steps 1. [Hello, world](https://plum.elixpo.com/docs/tour/hello-world/): printing, comments and running a program. 2. [Values and variables](https://plum.elixpo.com/docs/tour/values/): numbers, text, `plant` and `root`. 3. [Making decisions and loops](https://plum.elixpo.com/docs/tour/control-flow/): `if`, `match`, `while` and `for`. 4. [Functions](https://plum.elixpo.com/docs/tour/functions/): `branch`, default and named arguments, lambdas. 5. [Lists, maps and missing values](https://plum.elixpo.com/docs/tour/collections/): collections and `none`. 6. [Trees: your own types](https://plum.elixpo.com/docs/tour/trees/): fields, methods and inheritance. 7. [Traits and kinds](https://plum.elixpo.com/docs/tour/traits-and-kinds/): shared behaviour and fixed sets of cases. 8. [When things go wrong](https://plum.elixpo.com/docs/tour/errors/): compile errors, `throw`, `try` and `catch`. 9. [Modules](https://plum.elixpo.com/docs/tour/modules/): `seed`, the standard library and programs of several files. 10. [Tasks](https://plum.elixpo.com/docs/tour/tasks/): doing several things at once with `spawn` and channels. 11. [A web server](https://plum.elixpo.com/docs/tour/web-server/): `net.http` in a few lines. The tour shows the common path. The [language reference](https://plum.elixpo.com/docs/language/) has the exact rules, and the [standard library](https://plum.elixpo.com/docs/stdlib/) documents every module. --- Source: https://plum.elixpo.com/docs/tour/hello-world/ # Hello, world Here is a whole Plumlang program: ```plum drop("Hello, world!") ``` ```text output Hello, world! ``` `drop` prints its values on a line of their own. There is no `main` function to write and nothing to import: a program starts at its first line and runs to its last. ## Running it Save the program as `hello.plum` and run it: ```bash plum run hello.plum # or just: plum hello.plum ``` `plum` first checks the whole program, then runs it. If there is a mistake, it says where, and usually how to fix it, before anything runs. ## Printing several things `drop` takes any number of values, of any type, and separates them with a space: ```plum drop("The answer is", 42) drop(1, 2.5, good) drop() drop("done") ``` ```text output The answer is 42 1 2.5 good done ``` `drop()` with nothing in it prints an empty line. `good` is how Plumlang spells *true*; you'll meet it again in the next step. ## Comments A `#` starts a comment, which runs to the end of the line. Plumlang ignores it; it is there for people reading the code. ```plum # Greet the reader. drop("Hello") # a comment can follow code too ``` ```text output Hello ``` ## One statement per line A statement ends at the end of its line; there are no semicolons. A long statement can carry on to the next line when the line ends inside brackets, or with an operator or a comma: ```plum drop("one", "two") ``` ```text output one two ``` Next: [values and variables](https://plum.elixpo.com/docs/tour/values/). --- Source: https://plum.elixpo.com/docs/tour/values/ # Values and variables Programs work with values: numbers, text, and *yes or no*. Every value has a type, and Plumlang knows the type of everything before the program runs. ## The basic types | Type | What it holds | Examples | |---|---|---| | `int` | whole numbers | `42`, `-7`, `1_000_000` | | `float` | numbers with a fraction | `3.14`, `0.5`, `6.022e23` | | `str` | text | `"Hello"` | | `bool` | yes or no | `good`, `bad` | `good` and `bad` are Plumlang's *true* and *false* (and `true` and `false` work too). ## plant and root `plant` makes a variable, a name for a value that can change. `root` makes a constant, which can't: ```plum plant score = 0 score = score + 10 score += 5 root MAX_SCORE = 100 drop(score, "out of", MAX_SCORE) ``` ```text output 15 out of 100 ``` Changing `MAX_SCORE` would be a compile error. Constants are written in capitals by convention. You didn't write any types above: Plumlang worked out that `score` is an `int` from its value. You can write the type after the name when you want to, or when there is nothing to work it out from: ```plum plant ratio: float = 1 plant name: str = "Ada" drop(ratio, name) ``` ```text output 1.0 Ada ``` ## Arithmetic `+ - *` work as you'd expect. Division `/` always gives a `float`, and `//` divides whole numbers and drops the remainder; `%` is the remainder and `**` the power. ```plum drop(7 / 2, 7 // 2, 7 % 2, 2 ** 10) drop(1 + 2 * 3, (1 + 2) * 3) ``` ```text output 3.5 3 1 1024 7 9 ``` An `int` that grows too large for 64 bits is an error, never a silent wrong answer. ## Text and interpolation Strings use double quotes. Write `{...}` inside a string to put a value into it: ```plum plant name = "Ada" plant items = 3 drop("Hello, {name}! You have {items} items, {items * 2} after doubling.") plant price = 4.5 drop("Total: {price * items:.2}") ``` ```text output Hello, Ada! You have 3 items, 6 after doubling. Total: 13.50 ``` A `:` after the value formats it: `:.2` keeps two digits after the point. `+` joins strings, and `len` counts their characters: ```plum plant greeting = "Hello, " + "world" drop(greeting, len(greeting)) drop(greeting.upper()) ``` ```text output Hello, world 12 HELLO, WORLD ``` ## Converting between types An `int` becomes a `float` wherever a `float` is wanted. Every other conversion is written out: ```plum drop(int(3.9), float(3), str(42) + "!") drop(int("42") + 1) ``` ```text output 3 3.0 42! 43 ``` Nothing is ever *truthy* or *falsy* in Plumlang: a number is not a `bool`. Where a condition is needed you write the comparison you mean, like `count > 0`. Next: [making decisions and loops](https://plum.elixpo.com/docs/tour/control-flow/). --- Source: https://plum.elixpo.com/docs/tour/control-flow/ # Making decisions and loops ## if and else ```plum plant score = 84 if score >= 90 { drop("A") } else if score >= 80 { drop("B") } else { drop("C") } ``` ```text output B ``` The condition needs no brackets around it, but the block always has braces, and the opening brace goes on the same line. A condition must be a `bool`: compare with `==`, `!=`, `<`, `<=`, `>`, `>=`, and combine with `and`, `or` and `not`. ```plum plant age = 20 plant banned = bad if age >= 18 and not banned { drop("Welcome") } ``` ```text output Welcome ``` When both branches are a single value, `if` can be used as a value: ```plum plant count = 1 plant label = if count == 1 { "item" } else { "items" } drop("{count} {label}") ``` ```text output 1 item ``` ## match `match` compares a value against several patterns and runs the first that fits. It must cover every case, so it usually ends with `else`: ```plum plant command = "halt" match command { "start" => drop("starting") "stop", "halt" => drop("stopping") else => drop("unknown command: {command}") } plant age = 15 plant group = match age { 0..13 => "child" 13..20 => "teen" else => "adult" } drop(group) ``` ```text output stopping teen ``` `0..13` is a *range*: the numbers from 0 up to, but not including, 13. `0..=13` would include 13. ## while A `while` loop repeats as long as its condition holds: ```plum plant n = 10 while n > 0 { drop(n) n -= 4 } ``` ```text output 10 6 2 ``` ## for A `for` loop walks over a range, or over the items of a list, a map or a string: ```plum for i in 0..3 { drop("round", i) } for fruit in ["plum", "pear", "fig"] { drop(fruit) } for i, fruit in ["plum", "pear"].enumerate() { drop("{i}: {fruit}") } ``` ```text output round 0 round 1 round 2 plum pear fig 0: plum 1: pear ``` There is no C-style `for (i = 0; i < n; i++)`: a range says the same thing without the setup. ## break and continue `break` leaves a loop early; `continue` skips to its next round: ```plum for n in 1..20 { if n % 2 == 0 { continue } if n > 7 { break } drop(n) } ``` ```text output 1 3 5 7 ``` Next: [functions](https://plum.elixpo.com/docs/tour/functions/). --- Source: https://plum.elixpo.com/docs/tour/functions/ # Functions A function is declared with `branch`. Its parameters always have types, and its result type follows `->`: ```plum branch add(a: int, b: int) -> int { return a + b } branch greet(name: str) { drop("Hello, {name}") } drop(add(2, 3)) greet("Ada") ``` ```text output 5 Hello, Ada ``` `greet` returns nothing, so it has no `->`. A function that does return a value must return one on every path; the compiler checks. Functions can be called before the line that declares them, so you can put the main part of a program first and the helpers after it. ## One-line functions When the body is a single expression, `=>` replaces the braces and the `return`: ```plum branch square(x: int) -> int => x * x drop(square(12)) ``` ```text output 144 ``` ## Default and named arguments A parameter can have a default value, which makes it optional. Arguments can also be passed by name, after the positional ones: ```plum branch connect(host: str, port: int = 80, secure: bool = bad) { drop("{host}:{port} secure={secure}") } connect("example.com") connect("example.com", 443, secure: good) connect("example.com", secure: good) ``` ```text output example.com:80 secure=bad example.com:443 secure=good example.com:80 secure=good ``` ## Parameters are read-only Inside a function, its parameters are constants. Lists, maps and strings are *values* in Plumlang, so a function gets its own copy and can never change the caller's list behind its back; it returns a new one instead. ```plum branch with_bonus(scores: list[int]) -> list[int] { plant result = scores result.push(100) return result } plant mine = [70, 85] drop(with_bonus(mine)) drop(mine) ``` ```text output [70, 85, 100] [70, 85] ``` ## Functions as values A function is a value too. A *lambda* is a function without a name, written `(parameters) => expression`. Lambdas are handy with list methods like `map`, `filter` and `reduce`: ```plum plant numbers = [1, 2, 3, 4, 5, 6] plant evens = numbers.filter((n) => n % 2 == 0) plant squares = numbers.map((n) => n * n) plant total = numbers.reduce((a, b) => a + b, 0) drop(evens, squares, total) plant double = (x: int) => x * 2 drop(double(21)) ``` ```text output [2, 4, 6] [1, 4, 9, 16, 25, 36] 21 42 ``` The lambda's parameter types can be left out when Plumlang can tell them from where the lambda is used, as with `filter` above. ## Recursion A function may call itself: ```plum branch factorial(n: int) -> int { if n <= 1 { return 1 } return n * factorial(n - 1) } drop(factorial(20)) ``` ```text output 2432902008176640000 ``` `factorial(21)` doesn't fit in 64 bits, so it stops with an `OverflowError` instead of printing a wrong number. Next: [lists, maps and missing values](https://plum.elixpo.com/docs/tour/collections/). --- Source: https://plum.elixpo.com/docs/tour/collections/ # Lists, maps and missing values ## Lists A list holds values of one type, in order. Indexes start at 0. ```plum plant fruits = ["plum", "pear"] fruits.push("fig") drop(fruits, len(fruits)) drop(fruits[0], fruits[len(fruits) - 1]) drop(fruits[0..2]) drop("pear" in fruits) ``` ```text output ["plum", "pear", "fig"] 3 plum fig ["plum", "pear"] good ``` `fruits[0..2]` is a *slice*, a new list of items 0 and 1. Reading past the end of a list is an error with a clear message, never a crash or a random value. An empty list needs its type written, since there is nothing in it to go by: ```plum plant scores: list[int] = [] for i in 0..4 { scores.push(i * 10) } drop(scores) scores.reverse() drop(scores) ``` ```text output [0, 10, 20, 30] [30, 20, 10, 0] ``` ## Maps A map connects keys to values, and remembers the order keys were added in: ```plum plant ages = {"ada": 36, "grace": 45} ages["linus"] = 28 ages["ada"] += 1 drop(ages) drop(ages["grace"], "bob" in ages) for name, age in ages { drop("{name} is {age}") } ``` ```text output {"ada": 37, "grace": 45, "linus": 28} 45 bad ada is 37 grace is 45 linus is 28 ``` The empty map is written `{:}`, with its type: `plant counts: map[str, int] = {:}`. ## Sets A set keeps each value once: ```plum plant seen = set(["plum", "pear", "plum"]) seen.add("fig") drop(seen, len(seen), seen.contains("pear")) ``` ```text output set(["plum", "pear", "fig"]) 3 good ``` ## Copies, not surprises Strings, lists, maps and sets are *values*. Assigning one to another variable gives that variable its own copy: ```plum plant a = [1, 2, 3] plant b = a b.push(4) drop(a) drop(b) ``` ```text output [1, 2, 3] [1, 2, 3, 4] ``` Copying is cheap: the two share their data until one of them changes it. ## Missing values: none A plain `str` always holds a string; it can never be missing. When a value may be absent, its type ends with `?`, and `none` is the absent value. Plumlang makes you deal with `none` before you use the value, so a missing value can't crash your program. ```plum plant ages = {"ada": 36} plant found = ages.get("ada") # an int? : the age, or none plant missing = ages.get("bob") drop(found, missing) drop(missing ?? 0) if plant age = ages.get("ada") { drop("ada is {age}") } ``` ```text output 36 none 0 ada is 36 ``` - `??` gives a default when the value on its left is `none`. - `if plant name = value { ... }` runs the block only when the value is there, and inside it `name` is a plain, never-missing value. `ages["bob"]` would stop the program with a `KeyError`; `ages.get("bob")` asks instead, and gives `none`. Next: [trees, your own types](https://plum.elixpo.com/docs/tour/trees/). --- Source: https://plum.elixpo.com/docs/tour/trees/ # Trees: your own types A `tree` is Plumlang's class: a type you define, made of *fields* (the data) and *methods* (functions that work on it). ```plum tree Account { owner: str balance: float = 0.0 branch deposit(amount: float) { self.balance += amount } branch to_str() -> str => "{self.owner}: {self.balance:.2}" } plant acct = Account("Ada") acct.deposit(50) acct.deposit(12.5) drop(acct) drop(acct.balance) ``` ```text output Ada: 62.50 62.5 ``` - Calling the tree's name makes an object. The arguments fill the fields in order; `balance` has a default, so it can be left out. - Inside a method, `self` is the object. Fields are always reached through it, as `self.balance`, so a field is never mistaken for a local variable. - A `to_str` method decides how the object prints, in `drop` and in `{interpolation}`. Without one it prints as ``. Fields with defaults can also be given by name: `Account("Grace", balance: 100.0)`. ## init When building an object takes more than filling in fields, give the tree an `init` method. Calling the tree's name then calls `init`: ```plum tree Temperature { celsius: float branch init(fahrenheit: float) { self.celsius = (fahrenheit - 32.0) * 5.0 / 9.0 } } plant t = Temperature(212.0) drop(t.celsius) ``` ```text output 100.0 ``` ## Objects are shared Unlike lists and maps, objects are not copied. Two names can refer to the same object, and a change through one is seen through the other: ```plum tree Counter { count: int = 0 branch tick() { self.count += 1 } } plant a = Counter() plant b = a b.tick() b.tick() drop(a.count) ``` ```text output 2 ``` ## Inheritance A tree can extend one other tree with `:`. It gets the parent's fields and methods, can add its own, and can replace (override) methods. `super.method()` calls the parent's version. ```plum tree Animal { name: str branch speak() -> str => "..." branch intro() -> str => "{self.name} says {self.speak()}" } tree Dog : Animal { branch speak() -> str => "woof" } tree Puppy : Dog { branch speak() -> str => super.speak() + " (squeaky)" } plant pets: list[Animal] = [Dog("Rex"), Puppy("Bit"), Animal("Generic")] for pet in pets { drop(pet.intro()) } ``` ```text output Rex says woof Bit says woof (squeaky) Generic says ... ``` A `Dog` can go anywhere an `Animal` is expected, as in the list above. ## Private names Fields and methods whose names start with `_` can only be used by the tree itself (and the trees that extend it): ```plum tree Wallet { _cents: int = 0 branch add(cents: int) { self._cents += cents } branch total() -> str => "{self._cents // 100}.{self._cents % 100:02}" } plant w = Wallet() w.add(1250) w.add(5) drop(w.total()) ``` ```text output 12.55 ``` Next: [traits and kinds](https://plum.elixpo.com/docs/tour/traits-and-kinds/). --- Source: https://plum.elixpo.com/docs/tour/traits-and-kinds/ # Traits and kinds ## Traits A `trait` lists methods that a tree promises to have. Any tree that has the trait can be used where the trait is expected, whatever else it is. ```plum trait Shape { branch area() -> float branch name() -> str => "shape" branch summary() -> str => "{self.name()} with area {self.area():.2}" } tree Circle : Shape { radius: float branch area() -> float => 3.14159 * self.radius ** 2 branch name() -> str => "circle" } tree Rect : Shape { width: float height: float branch area() -> float => self.width * self.height } plant shapes: list[Shape] = [Circle(1.0), Rect(2.0, 3.0)] for s in shapes { drop(s.summary()) } drop(shapes[0] is Circle) ``` ```text output circle with area 3.14 shape with area 6.00 good ``` `area` has no body in the trait, so every tree with the trait must write one; forgetting it is a compile error. `name` and `summary` have bodies, which trees get for free and may replace. `x is Type` asks what an object really is. A tree that extends another tree names its parent first, then its traits: `tree Dog : Animal, Pet { ... }`. ## Kinds A `kind` is a type with a fixed set of cases, like the four directions: ```plum kind Direction { North, East, South, West } plant heading = Direction.North drop(heading, heading == Direction.North) ``` ```text output Direction.North good ``` Cases can carry values. `match` takes them apart, and must cover every case, so adding a case later points you at every `match` that needs it: ```plum kind Shape { Circle(radius: float) Rect(width: float, height: float) } branch area(s: Shape) -> float => match s { Circle(r) => 3.14159 * r ** 2 Rect(w, h) => w * h } plant shapes = [Shape.Circle(1.0), Shape.Rect(2.0, 3.0)] for s in shapes { drop(s, area(s)) } ``` ```text output Shape.Circle(1.0) 3.14159 Shape.Rect(2.0, 3.0) 6.0 ``` Kind values are values, like numbers: two are equal when they are the same case with equal contents. Next: [when things go wrong](https://plum.elixpo.com/docs/tour/errors/). --- Source: https://plum.elixpo.com/docs/tour/errors/ # When things go wrong Plumlang has two kinds of mistakes, and tells you about both in plain words. ## Compile errors Most mistakes are found before the program runs: a misspelled name, a string where a number should be, a missing `return`. `plum` shows the line, underlines the problem, and suggests a fix: ```plum norun plant total = 0 for i in 0..3 { totl += i } drop(total) ``` ```text total.plum:3:5: error[E0301]: unknown name 'totl'; did you mean 'total'? 3 | totl += i | ^~~~ 1 error ``` Adding a number to a string is caught the same way, with a hint: ```text count.plum:2:17: error[E0403]: can't add str and int; to put a value in text, use interpolation: "text {value}" 2 | plant message = "items: " + count | ^~~~~~~~~~~~~~~~~ 1 error ``` Every error has a code, like `E0301`. The [error codes](https://plum.elixpo.com/docs/errors/) page explains each one with an example and its fix. `plum check file.plum` reports every error in a file without running it. ## Runtime errors Some problems can only happen while the program runs: a file that isn't there, a list index out of range, a number too big for 64 bits. These *throw* an error. If nothing catches it, the program stops with a message and a stack trace showing where it happened. ## try and catch `try` runs a block, and `catch` handles an error thrown inside it: ```plum plant numbers = [1, 2, 3] try { drop(numbers[10]) } catch e: IndexError { drop("no such item:", e.message) } try { drop(int("forty-two")) } catch e { drop("that wasn't a number") } ``` ```text output no such item: index 10 is out of range: the list has 3 items (0 to 2) that wasn't a number ``` `catch e: IndexError` catches only that kind of error; a plain `catch e` catches any error. A `finally { }` block after the catches runs however the `try` ends, which is the place to tidy up. ## Your own errors Errors are trees that extend the built-in `Error` tree, which has a `message`. Make your own by extending it, and `throw` one when something is wrong: ```plum tree Overdrawn : Error { short_by: float } tree Account { balance: float = 0.0 branch withdraw(amount: float) { if amount > self.balance { throw Overdrawn("not enough money", amount - self.balance) } self.balance -= amount } } plant acct = Account(20.0) try { acct.withdraw(50.0) } catch e: Overdrawn { drop("{e.message}: short by {e.short_by:.2}") } ``` ```text output not enough money: short by 30.00 ``` ## try as a value When all you need is a fallback, `try` before an expression turns an error into `none`, and `??` supplies the default: ```plum plant text = "8O80" plant port = try int(text) ?? 8080 drop(port) ``` ```text output 8080 ``` Next: [modules](https://plum.elixpo.com/docs/tour/modules/). --- Source: https://plum.elixpo.com/docs/tour/modules/ # Modules ## The standard library `seed` brings a module into your program. The standard library has modules for maths, text, files, time, JSON, networking and the web: ```plum seed math seed time drop(math.sqrt(2.0)) drop(math.max(3, 9), math.round(math.PI, digits: 2)) drop(time.now() > 0.0) ``` ```text output 1.4142135623730951 9 3.14 good ``` A module can be renamed with `as`, or its names brought in directly: ```plum seed math as m seed math { sqrt, PI } drop(m.floor(2.7), sqrt(16.0), PI > 3.0) ``` ```text output 2 4.0 good ``` Strings, lists and maps need no `seed`: their methods are always there. `plum stdlib` lists every module's functions, and the [standard library](https://plum.elixpo.com/docs/stdlib/) pages document them. ## Your own modules Every `.plum` file is a module. Say `shapes.plum` holds: ```plum norun root PI = 3.14159 branch circle_area(r: float) -> float => PI * r ** 2 branch _helper() { } # starts with _: private to this file ``` Another file next to it imports it by its path, starting with `./`: ```plum norun seed ./shapes drop(shapes.circle_area(2.0)) ``` `seed ./models/user as user` reaches into folders, and `seed ./shapes { circle_area }` brings names in directly, just as with the standard library. Names that start with `_` stay private to their file. Each file runs once, the first time something imports it, so a module can set itself up with ordinary statements at its top level. ## Packages A folder with a `plum.toml` file is a package. Its `entry` file is the program: ```toml [package] name = "garden" version = "0.1.0" entry = "main.plum" ``` `plum run garden` then runs `garden/main.plum`. The repository's [garden example](https://github.com/plumlang/plumlang/tree/main/examples/garden) is a small program in several files. Next: [tasks](https://plum.elixpo.com/docs/tour/tasks/). --- Source: https://plum.elixpo.com/docs/tour/tasks/ # Tasks A *task* is a piece of work that runs alongside the rest of your program. `spawn` starts one and gives back a `Task`; its `wait()` method returns the result when the task is done. ```plum seed time branch fetch(n: int) -> int { time.sleep(0.1) # stands in for a slow download return n * 10 } plant start = time.clock() plant jobs = [spawn fetch(1), spawn fetch(2), spawn fetch(3)] for job in jobs { drop(job.wait()) } drop("about 0.1 seconds in all:", time.clock() - start < 0.25) ``` ```text output 10 20 30 about 0.1 seconds in all: good ``` The three tasks wait at the same time, so the whole program takes about 0.1 seconds, not 0.3. ## No async, no await A task pauses only when it waits for something: a timer, the network, a file, another task. Other tasks run meanwhile. The code looks the same whether it runs in a task or not: there is no `async`, no `await`, and no separate *async* version of any library function. ## Channels Tasks don't share variables. Each gets its own copy of the values it is given, so two tasks can never trample on each other's data. To talk, they use a *channel*: one task `send`s values, another receives them. ```plum plant results = Channel[str]() spawn (() => { for name in ["plum", "pear", "fig"] { results.send(name.upper()) } results.close() })() for r in results { drop(r) } ``` ```text output PLUM PEAR FIG ``` `for r in results` receives until the channel is closed and empty. `spawn (() => { ... })()` starts a task from a lambda written on the spot. ## What happens when a task fails An error in a task is not lost: `wait()` throws it, so you can catch it as usual. An error nothing waited for is printed when the program ends, and if every task is stuck waiting for another, Plumlang reports the deadlock instead of hanging. All tasks take turns on one thread, so thousands of them are cheap. The [`Task` and `Channel`](https://plum.elixpo.com/docs/stdlib/task-methods/) page has the details. Next: [a web server](https://plum.elixpo.com/docs/tour/web-server/). --- Source: https://plum.elixpo.com/docs/tour/web-server/ # A web server The standard library includes `net.http`, an HTTP/1.1 server and client. A complete web server: ```plum norun seed net.http plant app = http.server() app.get("/", (req) => http.html("

Hello from Plumlang

")) app.get("/hello/:name", (req) => http.text("Hello, {req.params["name"]}!")) drop("Listening on http://localhost:8080") app.listen(8080) ``` Run it, and open `http://localhost:8080/hello/you` in a browser. - `http.server()` makes a server; `app.get(pattern, handler)` adds a route. A handler takes the request and returns a response. - `:name` in a pattern matches one part of the path, and the request's `params` map holds what it matched. - `http.text`, `http.html` and `http.json` make responses. - Each connection is served by a task of its own, so one slow client holds up nobody. ## Query strings and JSON ```plum norun app.get("/add", (req) => { plant a = int(req.query.get("a") ?? "0") plant b = int(req.query.get("b") ?? "0") return http.json({"a": a, "b": b, "sum": a + b}) }) ``` `/add?a=2&b=40` answers `{"a":2,"b":40,"sum":42}`. ## The client, and a server that tests itself `http.get` fetches a URL. Here the server starts in the background on a free port, asks itself a few questions, and stops, which is how the examples in the repository test themselves: ```plum seed net.http plant app = http.server() app.get("/hello/:name", (req) => http.text("Hello, {req.params["name"]}!")) app.get("/add", (req) => { plant a = int(req.query.get("a") ?? "0") plant b = int(req.query.get("b") ?? "0") return http.json({"a": a, "b": b, "sum": a + b}) }) plant port = app.start(0, host: "127.0.0.1") plant base = "http://127.0.0.1:{port}" drop(http.get(base + "/hello/garden").body) drop(http.get(base + "/add?a=2&b=40").body) drop(http.get(base + "/missing").status) app.stop() ``` ```text output Hello, garden! {"a":2,"b":40,"sum":42} 404 ``` The [`net.http`](https://plum.elixpo.com/docs/stdlib/net-http/) page covers the rest: middleware, static files, HTTPS, and the client's `post` and `post_json`. ## Where to go next You've seen most of Plumlang. From here: - The [language reference](https://plum.elixpo.com/docs/language/) describes every part of the language exactly. - The [standard library](https://plum.elixpo.com/docs/stdlib/) documents each module. - The [examples](https://github.com/plumlang/plumlang/tree/main/examples) in the repository are small, complete programs: a bank, shapes, a to-do list, an echo server and a REST API. - Questions and ideas are welcome in [GitHub Discussions](https://github.com/plumlang/plumlang/discussions). --- Source: https://plum.elixpo.com/docs/language/ # Language reference > The exact rules of the language: the specification, one section per page. Version 0.1 (draft). This document says what Plumlang programs mean. The implementation follows it; a change to the language changes this document, the tests and the implementation in the same pull request (PREAMBLE 2.5). Sections marked **(Stage N)** describe behaviour that lands with that stage of the [roadmap](https://github.com/plumlang/plumlang/issues/36); until then the compiler reports them as not yet supported. ## Sections - [1. Design principles](https://plum.elixpo.com/docs/language/design-principles/) - [2. Source text](https://plum.elixpo.com/docs/language/source-text/) - [3. Types](https://plum.elixpo.com/docs/language/types/) - [4. Variables and expressions](https://plum.elixpo.com/docs/language/variables-and-expressions/) - [5. Statements](https://plum.elixpo.com/docs/language/statements/) - [6. Functions](https://plum.elixpo.com/docs/language/functions/) - [7. Built-in functions](https://plum.elixpo.com/docs/language/built-in-functions/) - [8. Trees: classes and objects](https://plum.elixpo.com/docs/language/trees-classes-and-objects/) (Stage 5) - [9. Modules](https://plum.elixpo.com/docs/language/modules/) (Stage 5) - [10. Errors](https://plum.elixpo.com/docs/language/errors/) (Stage 5) - [11. Values and memory](https://plum.elixpo.com/docs/language/values-and-memory/) - [12. Tasks and concurrency](https://plum.elixpo.com/docs/language/tasks-and-concurrency/) (Stage 5) - [13. The standard library](https://plum.elixpo.com/docs/language/the-standard-library/) - [14. Running programs](https://plum.elixpo.com/docs/language/running-programs/) - [15. Changes from the Python prototype](https://plum.elixpo.com/docs/language/changes-from-the-python-prototype/) - [16. Open questions](https://plum.elixpo.com/docs/language/open-questions/) --- Source: https://plum.elixpo.com/docs/language/design-principles/ # Design principles 1. **Easy to write comes first.** One clear way to do each thing. When two designs are equally powerful, the one a beginner reads correctly wins. 2. **Safe by default.** No null crashes, no out-of-bounds reads, no integer wrap-around, no data races, no use-after-free. Mistakes are errors with a location and a hint, preferably before the program runs. 3. **Predictable memory.** Values are freed the moment they are no longer used. There is no garbage-collector pause and no manual freeing. 4. **Small.** Every feature earns its place. A first program: ```plum drop("Hello, world!") ``` A taste of most of the language: ```plum seed math root GREETING = "Hello" tree Planet { name: str radius_km: float branch area() -> float { return 4.0 * math.PI * self.radius_km ** 2 } } plant planets = [Planet("Mercury", 2439.7), Planet("Earth", 6371.0)] for p in planets { drop("{GREETING}, {p.name}! Surface: {p.area()} km²") } ``` --- Source: https://plum.elixpo.com/docs/language/source-text/ # Source text ## 2.1 Files A Plumlang source file is UTF-8 text with the extension `.plum`. A byte order mark at the start is ignored. Line endings may be `\n` or `\r\n`. Code may nest up to 1000 deep: brackets, blocks, types and lambdas inside each other, with each operator of a chain like `a + b + c` counting one level. Deeper code is a compile error (E0218), never a crash. Other limits, each a compile error: a function, lambda or kind case has at most 255 parameters (E0219); a tree has at most 255 fields with its parents' (E0429); a tree or trait extends trees and traits at most 32 deep (E0428), and never itself (E0427). ## 2.2 Comments A comment starts with `#` and runs to the end of the line. ```plum # A whole-line comment plant total = 0 # a comment after code ``` There are no block comments. ## 2.3 Statements and lines A statement ends at the end of its line. There are no semicolons. A statement continues onto the next line when the line ends inside an open `(`, `[` or `{`, or ends with a binary operator, `,`, `.` or `->`: ```plum plant total = price + tax + shipping plant names = [ "Ada", "Grace", ] ``` A trailing comma is allowed in every list of items. ## 2.4 Identifiers An identifier starts with a letter or `_` and continues with letters, digits and `_`. Letters are ASCII `a`–`z` and `A`–`Z`. Identifiers are case-sensitive. By convention, which the formatter and the linter follow: | Kind | Style | Example | |---|---|---| | Variables, functions, fields, modules | `snake_case` | `total_price`, `read_file` | | Constants | `UPPER_SNAKE_CASE` | `MAX_USERS` | | Types (`tree`, `trait`, `kind`) | `PascalCase` | `HttpRequest` | A name starting with `_` is private to its module or tree (section 9.4). ## 2.5 Keywords These words are reserved and cannot be used as identifiers: | Keyword | Meaning | |---|---| | `plant` | declare a variable | | `root` | declare a constant | | `branch` | declare a function or method | | `tree` | declare a class | | `trait` | declare an interface | | `kind` | declare an enumeration | | `seed` | import a module | | `good`, `bad` | the boolean values true and false | | `none` | the absent value | | `if`, `else`, `match` | choose | | `for`, `in`, `while`, `break`, `continue` | repeat | | `return` | leave a function | | `and`, `or`, `not` | logic | | `is` | type test | | `as` | conversion, import alias | | `self`, `super` | the current object, its parent tree | | `throw`, `try`, `catch`, `finally` | errors | | `spawn` | start a task | | `weak` | a non-owning reference | `true` and `false` are also accepted as spellings of `good` and `bad`, so programs from other languages read naturally. The formatter keeps whichever spelling a file uses. ## 2.6 Literals **Integers** are written in decimal, hexadecimal (`0x`), octal (`0o`) or binary (`0b`). `_` may separate digits. ```plum 42 1_000_000 0xFF 0o755 0b1010_0101 ``` An integer literal that does not fit in 64 bits is a compile error. **Floats** have a `.` with digits on both sides, an exponent, or both. ```plum 3.14 0.5 1e9 6.022e23 2.5e-3 ``` `.5` and `5.` are not floats; write `0.5` and `5.0`. **Booleans** are `good` and `bad` (or `true` and `false`). **Strings** are written in double quotes. There is one string syntax. ```plum "Hello" "Tab:\t, newline:\n, quote: \", backslash: \\" "Unicode: \u{1F351}" ``` | Escape | Meaning | |---|---| | `\n` `\t` `\r` `\0` | newline, tab, carriage return, NUL | | `\\` `\"` | backslash, double quote | | `\{` `\}` | literal braces | | `\u{XXXX}` | a Unicode code point, 1 to 6 hex digits | Any other escape is a compile error. **Interpolation**: `{expression}` inside a string is replaced by the expression's text (section 4.10). ```plum plant name = "Ada" drop("Hello, {name}! 2 + 2 = {2 + 2}") ``` **Multi-line strings** use triple quotes. The first newline after the opening `"""` is dropped, and the indentation of the closing `"""` is removed from every line: ```plum plant poem = """ Roses are red, Plums are purple. """ # poem == "Roses are red,\nPlums are purple.\n" ``` **Lists** `[1, 2, 3]`, **maps** `{"a": 1, "b": 2}`, and the empty map `{:}` are described in section 3.4. --- Source: https://plum.elixpo.com/docs/language/types/ # Types Plumlang is statically typed: every expression has a type known before the program runs, and type mistakes are compile errors. Most types are inferred, so they rarely need writing. ## 3.1 Basic types | Type | Values | Notes | |---|---|---| | `int` | 64-bit signed integers | Overflow is a runtime error, never wrap-around | | `float` | 64-bit IEEE 754 numbers | | | `bool` | `good`, `bad` | | | `str` | immutable UTF-8 text | | | `byte` | integers 0 to 255 | For binary data, in `list[byte]` | | `none` | the single value `none` | The type of functions that return nothing | ## 3.2 Conversions There is exactly one implicit conversion: **an `int` becomes a `float`** where a `float` is expected, including in arithmetic that mixes them. ```plum plant x: float = 5 # 5.0 plant y = 2 * 1.5 # 3.0, a float ``` Every other conversion is written: | Conversion | Result | |---|---| | `int(3.9)` | `3` (truncates toward zero; error if out of range or NaN) | | `float(3)` | `3.0` | | `str(42)`, `str(1.5)`, `str(good)` | `"42"`, `"1.5"`, `"good"` | | `int("42")`, `float("1.5")` | parse, or throw a `ParseError` | | `bool(x)` | not allowed: write the comparison you mean | There is no truthiness: `if count {` is a type error; write `if count > 0 {`. ## 3.2.1 How values print `str()`, `drop` and interpolation turn values into text the same way: | Value | Text | |---|---| | `int` | decimal digits: `42`, `-7` | | `float` | the shortest text that reads back as the same number, always with a `.` or an exponent. Exponents from −4 to 15 are written out (`1.0`, `0.0025`, `1000000000.0`), others in scientific notation (`1e+20`, `1e-05`); also `inf`, `-inf`, `nan` | | `bool` | `good` or `bad` | | `str` | the text itself, without quotes | | `none` | `none` | | list, map, set | `[1, 2]`, `{"a": 1}`, `set([1, 2])`, with strings inside quoted | | tree | its `to_str()` (trait `Show`), else `` | Values nested more than 256 deep (a long chain of kind values, say) print their outer 256 levels and `...` for what is inside, so printing never runs out of stack. The depth counts through `to_str()` methods that print values of their own. ## 3.3 Optional types `T?` is either a `T` or `none`. Only optional types can hold `none`, so a plain `str` is never absent, and nothing crashes on a missing value. ```plum plant nickname: str? = none drop(nickname ?? "no nickname") # default when none if plant n = nickname { # unwrap drop("Called {n}") # n is a str here } drop(nickname?.upper()) # none-safe call: a str? ``` ## 3.4 Collections | Type | Literal | Notes | |---|---|---| | `list[T]` | `[1, 2, 3]`, `[]` | Ordered, growable. Index from 0 | | `map[K, V]` | `{"a": 1}`, `{:}` | Keys are `int`, `str`, `bool`, `byte` or a `kind`; insertion order is kept | | `set[T]` | `set([1, 2])` | Unique values, insertion order kept | The empty literals `[]` and `{:}` need a type from context: ```plum plant names: list[str] = [] plant ages: map[str, int] = {:} ``` Reading a list out of bounds, or a missing map key with `m[k]`, is a runtime error; `m.get(k)` returns `V?` instead. ## 3.5 Function types `(int, int) -> int` is the type of a function taking two `int`s and returning an `int`. `() -> none` takes nothing and returns nothing. ## 3.6 User-defined types `tree` declares a class (section 8), `trait` an interface (section 8.5), and `kind` an enumeration (section 8.6). ## 3.7 Type annotations Annotations follow a name after `:`. They are needed on function parameters, function results other than `none`, tree fields, and where inference has nothing to go on (empty collections, `none`). ```plum plant count = 0 # int, inferred plant ratio: float = 1 # float plant scores: list[int] = [] ``` --- Source: https://plum.elixpo.com/docs/language/variables-and-expressions/ # Variables and expressions ## 4.1 Declarations `plant` declares a variable, `root` a constant. A declaration always has a value. ```plum plant score = 0 score = score + 10 # fine: plant can change root MAX_SCORE = 100 MAX_SCORE = 200 # compile error: MAX_SCORE is a root ``` Using a variable before it is declared is a compile error. Declaring the same name twice in one block is a compile error; an inner block may shadow an outer name. ## 4.2 Scope A name is visible from its declaration to the end of the block `{ }` that contains it. Names declared at the top level of a file belong to the module (section 9). ## 4.3 Assignment `=` assigns to a `plant` variable, a list element, a map entry or a field. Assignment is a statement, not an expression: `if x = 5 {` is a syntax error. Compound assignment applies an operator and assigns: `+=` `-=` `*=` `/=` `//=` `%=` `**=` `&=` `|=` `^=` `<<=` `>>=`. `x += 1` means `x = x + 1`, with the same type rules. There is no `++` or `--`. ## 4.4 Arithmetic | Operator | Meaning | Types | |---|---|---| | `a + b` | add | numbers; `str + str` and `list + list` concatenate | | `a - b` | subtract | numbers | | `a * b` | multiply | numbers | | `a / b` | divide | numbers; **always a `float`**: `7 / 2 == 3.5` | | `a // b` | floor division | `int // int` is an `int`: `7 // 2 == 3`, `-7 // 2 == -4` | | `a % b` | remainder, same sign as `b` | numbers: `-7 % 2 == 1` | | `a ** b` | power | `int ** int` is an `int` (exponent must be ≥ 0); otherwise `float` | | `-a` | negate | numbers | Integer overflow, `//` or `%` by zero, and `int ** negative` are runtime errors. Float division by zero follows IEEE 754 (`inf`, `nan`). `+ - * /` and `-a` also work on objects whose tree has the matching method (`plus`, `minus`, `times`, `divided_by`, `negate`; section 8.5). ## 4.5 Comparison `==` `!=` `<` `<=` `>` `>=`. Both sides must have the same type, except that `int` and `float` compare by value. Strings compare by Unicode code point; lists and maps compare element by element with `==`. Trees compare by identity unless they implement `Equal` (section 8.5). `<` `<=` `>` `>=` work on numbers, on strings, and on objects whose tree implements `Order` (a `compare` method, section 8.5). Comparisons do not chain: `a < b < c` is a syntax error; write `a < b and b < c`. ## 4.6 Logic `and`, `or` and `not` take and give `bool`. `and` and `or` evaluate the right side only when needed. ```plum if age >= 18 and not banned { drop("Welcome") } ``` ## 4.7 Bitwise On `int` (and `byte`) only: `&` and, `|` or, `^` xor, `~` not, `<<` and `>>` shifts. A shift count must be between 0 and 63; `>>` is arithmetic. ## 4.8 Precedence From lowest to highest; operators on one row group left to right, except `**`, which groups right to left. | Level | Operators | |---|---| | 1 | `??` | | 2 | `or` | | 3 | `and` | | 4 | `not` | | 5 | `==` `!=` `<` `<=` `>` `>=` `is` `in` | | 6 | `..` `..=` | | 7 | `\|` | | 8 | `^` | | 9 | `&` | | 10 | `<<` `>>` | | 11 | `+` `-` | | 12 | `*` `/` `//` `%` | | 13 | unary `-` `~` | | 14 | `**` | | 15 | `as` | | 16 | call `f()`, index `a[i]`, field `a.b`, `a?.b` | So `-2 ** 2 == -4`, `1 + 2 * 3 == 7`, and `0..n + 1` is `0..(n + 1)`. Bitwise operators bind tighter than comparisons, as in Rust, Go and Swift: `flags & MASK == 0` means `(flags & MASK) == 0`, avoiding the C trap. ## 4.9 Membership and type tests `x in collection` tests membership in a list, set, map (keys) or string (substring). `value is Type` tests the runtime type of a trait or optional value. ## 4.10 Interpolation `"{expr}"` converts the value with `str()`. A tree converts with its `to_str()` method if it has one (trait `Show`), else as ``. Formatting options follow a `:`: ```plum drop("{price:.2}") # 2 digits after the point drop("{count:5}") # right-aligned in 5 columns drop("{name:<10}|") # left-aligned drop("{n:x} {n:b}") # hex, binary ``` ## 4.11 Ranges `a..b` is the integers from `a` up to but not including `b`; `a..=b` includes `b`. A range is written where it is used, in a `for` loop, a slice, after `in`, or as a `match` pattern; it is not a value that can be stored or passed: ```plum for i in 0..5 { } # 0 1 2 3 4 plant middle = items[1..3] # a new list of items 1 and 2 plant word = text[0..5] # characters 0 to 4 if age in 13..=19 { } # 13 <= age and age <= 19 ``` --- Source: https://plum.elixpo.com/docs/language/statements/ # Statements ## 5.1 Blocks A block is a sequence of statements in `{ }`. The opening brace goes on the same line as the statement that owns it. ## 5.2 if ```plum if score >= 90 { drop("A") } else if score >= 80 { drop("B") } else { drop("C") } ``` The condition must be a `bool`. No parentheses are needed around it. `if` is also an expression when both branches are single expressions: ```plum plant label = if count == 1 { "item" } else { "items" } ``` ## 5.3 match `match` picks the first arm whose pattern fits. It must cover every case; `else` covers the rest. ```plum match command { "start" => start() "stop", "halt" => stop() else => drop("Unknown command: {command}") } match shape { Circle(r) => drop("circle of radius {r}") Square(side) => drop("square of side {side}") } ``` Patterns are literals, `kind` cases with their values (section 8.6), ranges (`0..10`), and `_`, which matches anything. `match` is also an expression when every arm is a single expression. ## 5.4 while ```plum plant n = 10 while n > 0 { n -= 3 } ``` ## 5.5 for `for` walks over a range, a list, a set, a map, a string (its characters) or anything with an `iter()` method (trait `Iterable`). ```plum for i in 0..10 { drop(i) } for name in names { drop(name) } for i, name in names.enumerate() { drop("{i}: {name}") } for key, value in ages { drop("{key} is {value}") } ``` The loop variable is a new constant on each iteration. A loop goes over the collection as it was when the loop started: since collections are values (section 11.1), changing the variable inside the loop changes the variable, not the loop. ```plum plant xs = [1, 2] for x in xs { xs.push(x) } # runs twice; xs is then [1, 2, 1, 2] ``` There is no C-style `for (init; condition; step)`; use a range or `while`. ## 5.6 break and continue `break` leaves the innermost loop; `continue` starts its next iteration. Outside a loop they are compile errors. ## 5.7 Expression statements A call can stand on its own as a statement. Any other expression standing alone (`x + 1`) is a compile error, since its value would be lost. --- Source: https://plum.elixpo.com/docs/language/functions/ # Functions ## 6.1 Declaring and calling ```plum branch add(a: int, b: int) -> int { return a + b } branch greet(name: str) { # returns none drop("Hello, {name}") } drop(add(2, 3)) greet("Ada") ``` Parameter types are always written. The result type is written after `->` and left out for functions that return nothing. A function whose result is not `none` must `return` a value on every path; the compiler checks. A function body that is a single expression can use `=>`: ```plum branch square(x: int) -> int => x * x ``` Functions can be called before their declaration in the same module. A function may use module variables declared anywhere in the module, but using one before its `plant` or `root` line has run (a call made above the declaration) is a runtime `Error`, not a value of the wrong type: ```plum branch greet() -> str => "Hello, {name}" drop(greet()) # Error: a module variable was used before its `plant` line ran plant name = "Ada" drop(greet()) # Hello, Ada ``` Using a module variable above its declaration outside a function is a compile error (E0303). ## 6.2 Default and named arguments ```plum branch connect(host: str, port: int = 80, secure: bool = bad) { } connect("example.com") connect("example.com", 443, secure: good) connect("example.com", secure: good) ``` Defaults must be constants or literals. Named arguments come after positional ones. ## 6.3 Parameters are read-only Parameters are constants inside the function. Because strings, lists and maps are values (section 11), a function cannot change the caller's list; it returns a new one, or takes a tree, whose objects are shared. ## 6.4 Function values and closures Functions are values. A lambda is written `(params) => expression` or `(params) => { statements }`: ```plum plant double = (x: int) => x * 2 plant evens = numbers.filter((n) => n % 2 == 0) plant sorted = people.sorted_by((p) => p.age) ``` Lambda parameter types can be left out when the context gives them, as in `filter` above. A lambda captures the variables it uses; it sees their current values (a captured `plant` can be changed by the lambda only if it is declared in an enclosing function, not across tasks). ## 6.5 Recursion Functions may call themselves. Deep recursion past the stack limit (by default 10,000 frames) is a runtime error, not a crash. Calls made from inside the runtime (a `to_str` running while something prints, the function given to `map` or `filter`) may nest 100 deep; past that is also a runtime error. --- Source: https://plum.elixpo.com/docs/language/built-in-functions/ # Built-in functions These are always available without `seed`: | Function | Meaning | |---|---| | `drop(values...)` | print the values separated by spaces, then a newline | | `ask(prompt: str = "") -> str?` | print the prompt, read a line from standard input; `none` at end of input | | `len(x) -> int` | length of a string (in characters), list, map or set | | `int`, `float`, `str`, `byte` | conversions (section 3.2) | | `type_of(x) -> str` | the type's name, for messages and debugging | | `assert(cond: bool, message: str = "")` | throw an `AssertError` if `cond` is `bad` | | `exit(code: int = 0)` | end the program | `drop` is an ordinary function, not a statement: it is always called with parentheses, `drop("hi")`. --- Source: https://plum.elixpo.com/docs/language/trees-classes-and-objects/ # Trees: classes and objects ## 8.1 Declaring a tree A `tree` groups fields and the methods that work on them: ```plum tree Account { owner: str balance: float = 0.0 branch deposit(amount: float) { if amount <= 0 { throw ValueError("deposit must be positive") } self.balance += amount } branch to_str() -> str => "{self.owner}: {self.balance:.2}" } plant acct = Account("Ada") # balance takes its default acct.deposit(50) drop(acct) # Ada: 50.00 ``` Inside a method, `self` is the object; fields and methods are always reached through it (`self.balance`), so a field is never confused with a local variable. ## 8.2 Construction Calling the tree's name creates an object. By default the arguments fill the fields in declaration order; fields with defaults may be left out or named: `Account("Ada", balance: 10.0)`. A tree may define `init` to construct objects differently. When it does, calls to the tree's name call `init`. Fields with defaults are set first; `init` must then set every field without a default, in its opening statements (`self.field = value`), before anything else uses `self`. A tree that inherits `init` and adds a field without a default needs its own `init`. ```plum tree Temperature { celsius: float branch init(fahrenheit: float) { self.celsius = (fahrenheit - 32.0) * 5.0 / 9.0 } } ``` ## 8.3 Objects are shared Tree objects are reference values: assigning or passing one shares the same object, and changes through one name are seen through every name. Every other value in Plumlang is copied (section 11). For a tree without `equals`, `a == b` asks whether two names refer to the same object (section 4.5). ## 8.4 Inheritance A tree can extend one other tree. It inherits the fields and methods, adds its own, and can override methods. `super.method()` calls the parent's version. ```plum tree Animal { name: str branch speak() -> str => "..." } tree Dog : Animal { branch speak() -> str => "{self.name} says woof" } plant pets: list[Animal] = [Dog("Rex"), Animal("Generic")] for pet in pets { drop(pet.speak()) } ``` A `Dog` can be used wherever an `Animal` is expected. There is no multiple inheritance; use traits. ## 8.5 Traits A `trait` lists methods a tree promises to have. A tree implements traits by naming them after `:`, after its parent tree if it has one: ```plum trait Shape { branch area() -> float branch name() -> str => "shape" # a default method } tree Circle : Shape { radius: float branch area() -> float => 3.14159 * self.radius ** 2 } branch total_area(shapes: list[Shape]) -> float { plant sum = 0.0 for s in shapes { sum += s.area() } return sum } ``` Missing methods are compile errors, and a tree's version of a trait's method (or of a parent's method it overrides) must have exactly the same parameters and result. `x is Shape` asks whether an object's tree has the trait. Some methods the language calls itself: - `to_str() -> str` is how an object prints: in `drop`, `str()` and interpolation, and inside a printed list or map. Without it, an object prints as ``. - `equals(other: T) -> bool`, where `T` is the tree or one it extends, is what `a == b` and `a != b` mean when `a`'s type is a tree with `equals` (trait `Equal`). Without it, `==` asks whether both are the same object. In a list whose item type has `equals` (also lists of such lists), `contains`, `index_of`, `x in list` and `==` between lists use it too, calling each item's `equals`. Elsewhere in collections (map keys and values, sets, a list of a parent tree whose subclass alone has `equals`) objects compare by identity. - `compare(other: T) -> int` (trait `Order`) is what `a < b`, `a <= b`, `a > b` and `a >= b` mean: it returns a negative number if `self` comes before `other`, zero if neither does, and a positive number if `self` comes after. A list whose item type has `compare` can `sort()` and `sorted()`; the sort is stable. A `compare` that throws stops the sort with its error. - The arithmetic operators call these methods (on the left object): | Operator | Method | |---|---| | `a + b` | `plus(other: T) -> T` | | `a - b` | `minus(other: T) -> T` | | `a * b` | `times(other: T) -> T`, or `times(k: int)` / `times(k: float)` | | `a / b` | `divided_by(other: T) -> T`, or `divided_by(k: int)` / `divided_by(k: float)` | | `-a` | `negate() -> T` | `T` is the tree or one it extends (or a trait it has), and the result is too; `times` and `divided_by` may take a number instead, to scale. Compound assignment uses them as well: `v += w` is `v = v + w`. The object must be on the left: `v * 2.0` works, `2.0 * v` doesn't. ```plum tree Vector { x: float y: float branch plus(other: Vector) -> Vector => Vector(self.x + other.x, self.y + other.y) branch times(k: float) -> Vector => Vector(self.x * k, self.y * k) branch negate() -> Vector => Vector(-self.x, -self.y) } plant v = Vector(1.0, 2.0) + Vector(3.0, 4.0) * 2.0 # (7.0, 10.0) v += -v # (0.0, 0.0) ``` These methods are found in the object's own tree, so a subclass that overrides one changes what the operator does, even where the object's type is the parent. Their shapes are fixed (E0424), and an override has the same parameters and result as the method it overrides (E0421). `Hash` (`hash`, for map keys) and `Iterable` (`iter`, for `for`) come with the standard library. Fields and methods whose names start with `_` are private to the tree and the trees that extend it (section 9.4). ## 8.6 Kinds: enumerations A `kind` is a type with a fixed set of cases. Cases may carry values. ```plum kind Direction { North, East, South, West } kind Shape { Circle(radius: float) Rect(width: float, height: float) } branch area(s: Shape) -> float => match s { Circle(r) => 3.14159 * r ** 2 Rect(w, h) => w * h } plant heading = Direction.North ``` `match` on a kind must cover every case. A kind's values are values like numbers and strings: two are equal when they are the same case with equal contents (`Shape.Rect(2.0, 3.0) == Shape.Rect(2.0, 3.0)`), and they print as written: `Direction.North`, `Shape.Circle(1.0)`. `type_of` gives the kind's name. --- Source: https://plum.elixpo.com/docs/language/modules/ # Modules ## 9.1 Files are modules Every `.plum` file is a module. Its top-level statements run once, in order, the first time it is imported, or when it is the program being run. A program needs no `main` function. A module's functions exist before its first statement runs; its variables exist once their declaration has run (section 6.1). ## 9.2 seed `seed` imports a module, by standard-library name or by path relative to the importing file: ```plum seed math # standard library: math.sqrt(2.0) seed net.http # use as http.server() seed net.http as web # use as web.server() seed ./shapes # the file shapes.plum next to this one seed ./models/user as user # models/user.plum seed math { sqrt, PI } # bring names in directly: sqrt(PI) ``` A module's name is the last part of its path. Imports must come before other statements. Circular imports are a compile error that shows the cycle (E0311). With `seed ./shapes`, the module's names are reached through it: `shapes.area(c)`, and in types `shapes.Circle`. With `seed ./shapes { Circle, area }`, those names are used directly. Either way the names are the module's own: a variable it changes is changed for everyone who imported it. Its kinds' cases can be used bare in `match` patterns (`Round =>`). Each file is loaded once, however many modules import it, and its top-level statements run once, before the statements of the first module that imports it. A file may be named like a keyword (`seed ./models/plant`). ## 9.3 Packages A directory with a `plum.toml` is a package; its `entry` file is the program, so `plum run my-project` runs it. ```toml [package] name = "weather-api" version = "0.1.0" entry = "main.plum" lib = "lib.plum" # what `seed weather_api` imports (default: entry) [dependencies] colors = "^1.0" ``` Packages published on Orchard, Plumlang's registry, are added with `plum add NAME` and seeded by name. A name that isn't a standard module (nor under one, like `net.x`) is a package: `seed colors` imports the package's `lib` file, and `seed colors.palette.dark` its file `palette/dark.plum`. A `-` in a package's name is written `_` in `seed` (`seed weather_api` for `weather-api`). The module's name is the last part, as for other modules. A module may seed only the packages its own `plum.toml` lists under `[dependencies]` (E0908); which version is used comes from the project's `plum.lock`, and a declared package that isn't installed is E0909. The project is the nearest directory with a `plum.toml` above the file being run. Version ranges, the lock file and the commands are described in [orchard.md](https://plum.elixpo.com/docs/tools/orchard/). ## 9.4 Visibility Every top-level name is visible to modules that import it, except names starting with `_`, which are private to their module. Fields and methods starting with `_` are private to their tree (and the trees that extend it). --- Source: https://plum.elixpo.com/docs/language/errors/ # Errors ## 10.1 Two kinds of mistakes **Compile errors** (wrong types, unknown names, syntax) stop the program before it starts, with the file, line, column, what is wrong and a hint. **Runtime errors** happen while the program runs: a file that cannot be opened, a list index out of range, integer overflow. A runtime error that is not caught ends the program with a message and a stack trace, and exit code 1. The message names the error's tree, so you know what to catch: ```text bank.plum:8: Overdrawn: not enough money in withdraw, line 8 in pay, line 13 in
, line 16 ``` ## 10.2 throw, try, catch Errors are trees that extend the built-in `Error` tree, which has a `message: str`. ```plum tree NotFound : Error { path: str } branch load(path: str) -> str { if not fs.exists(path) { throw NotFound("no such file", path) } return fs.read(path) } try { plant text = load("config.txt") drop(text) } catch e: NotFound { drop("Missing: {e.path}") } catch e { drop("Something else went wrong: {e.message}") } ``` `catch e: Type` catches that error tree and the trees that extend it; a plain `catch e` catches every error, and `e` is an `Error`. Catches are tried in order, and an error none of them takes goes on to the next `try` out. An error thrown inside a `catch` also goes to the next `try` out. A `try` may end with `finally { }`, which runs however the `try` ends: normally, through a catch, with an error no catch took (which then carries on), or by `return`, `break` or `continue`. An error thrown inside `finally` replaces the one in flight. `exit()` ends the program at once, without running `finally` blocks. Rethrowing a caught error with `throw e` keeps the place it was first thrown, so the stack trace still points at the real problem. `try` is also an expression that turns an error into `none`: ```plum plant port = try int(text) ?? 8080 ``` The built-in error trees include `ValueError`, `ParseError`, `IndexError`, `KeyError`, `OverflowError`, `ZeroDivisionError`, `IOError`, `NetError` and `AssertError`. The errors the language itself raises are these: | Error | Raised by | |---|---| | `OverflowError` | int arithmetic that doesn't fit in 64 bits; `int(f)` of a float too large | | `ZeroDivisionError` | `//` or `%` by an int zero | | `IndexError` | a list or string index or slice out of range; `pop()` on an empty list; `insert`/`remove_at` out of range | | `KeyError` | `m[k]` for a key not in the map | | `ParseError` | `int(text)` or `float(text)` of text that isn't a number | | `ValueError` | `byte(n)` out of 0 to 255; an int power with a negative exponent; a shift count out of 0 to 63; a format that doesn't fit the value; a `str` or list larger than it may be (11.4) | | `AssertError` | `assert(condition)` when the condition is `bad` | | `Error` | too much recursion; a module variable used before its declaration ran (6.1) | --- Source: https://plum.elixpo.com/docs/language/values-and-memory/ # Values and memory ## 11.1 Value types and reference types Numbers, booleans, `none`, strings, lists, maps, sets and kinds are **values**: assigning or passing one gives the receiver its own copy, so changing one never changes the other. ```plum plant a = [1, 2, 3] plant b = a b.push(4) drop(a) # [1, 2, 3] drop(b) # [1, 2, 3, 4] ``` Copies are cheap: the data is shared until one side changes it, and only then copied (copy-on-write). Tree objects are **references**: assigning or passing one shares the object (section 8.3). ## 11.2 Memory is reclaimed automatically and at once Every value is freed as soon as nothing refers to it anymore, by reference counting. There is no garbage collector, so there are no pauses, and memory use follows the program. Files and sockets close when their last reference goes away, as well as when `close()` is called. ## 11.3 Cycles and weak references Two tree objects that refer to each other keep each other alive. Break the cycle by making the back-reference `weak`; a weak reference does not keep its object alive and reads as `none` once the object is gone, so its type is optional: ```plum tree Node { children: list[Node] = [] parent: weak Node? = none } ``` `weak` goes on a field whose type is an optional tree or trait (E0425). Assigning an object to a weak field doesn't keep it alive; reading the field gives the object while something else holds it, and `none` after. `plum run --check-leaks program.plum` reports, when the program ends, the tree objects still alive because they are in a cycle, by tree and the line that made them, and exits with code 1 if there are any: ```text leak check: 2 objects are still alive in reference cycles: 1 Pair, made on line 29 1 Pair, made on line 30 hint: make one direction of each cycle weak, like 'parent: weak Node? = none' ``` ## 11.4 What the runtime guarantees No Plumlang program can read or write memory it does not own: every index is checked, there are no raw pointers, and objects are never used after they are freed. A `str` holds at most 1 GiB (2^30 bytes) and a list at most 2^27 (134,217,728) items; making a larger one (with `+`, `repeat`, `join`, `push`...) throws a `ValueError` before any memory is taken. A program that runs out of memory otherwise ends with `plum: error: out of memory` and exit code 1. Values may nest as deep as memory allows: comparing, copying and freeing them doesn't recurse in the runtime, and printing stops at a depth (section 3.2.1). ## 11.5 Measuring memory `plum run --mem-stats program.plum` prints to standard error, when the program ends, how much memory the run used: ```text memory used by this run (--mem-stats): peak in use 82,456 bytes (80.5 KB) allocated in all 167,008 bytes (163.1 KB) still in use at exit 0 bytes allocations 3,014 resizes 12 frees 3,014 values made: strings 2,001 lists 1 maps 0 ... ``` Bytes are the sizes of the blocks the C library hands out, counted from the start of the run to its end (compiling comes before and isn't counted). "Still in use at exit" is what the run allocated and didn't free: more than 0 means objects left alive in reference cycles (find them with `--check-leaks`). Values made are counted by kind: strings, lists, maps, sets, tree objects, kind values, closures, captured variables, weak references, tasks and channels. Without `--mem-stats` nothing is counted and the run costs the same. --- Source: https://plum.elixpo.com/docs/language/tasks-and-concurrency/ # Tasks and concurrency ## 12.1 spawn `spawn` runs a function call as a **task**, a lightweight thread of work. The program keeps going without waiting for it. ```plum plant job = spawn download("https://example.com/a.txt") drop("downloading...") plant text = job.wait() # wait for the result (or its error) ``` `spawn` returns a `Task[T]`, where `T` is the call's result type. `task.wait()` returns the result, or throws the task's error. ## 12.2 No async/await Calls that wait for the outside world (network, files, timers, `ask`) pause only the task that made them; other tasks keep running. Code is written the same way whether or not it runs in a task: there is no `async`, no `await`, and no separate "async" version of any library. ## 12.3 Sharing between tasks Tasks do not share variables. A task gets its own copy of the values it is given, and tree objects cannot be passed to a task (a compile error) unless the tree is marked `shared`, which allows only fields that are themselves values and makes each method call atomic. Tasks communicate through channels: ```plum plant ch = Channel[int]() spawn (() => { for i in 0..3 { ch.send(i) } ch.close() })() for n in ch { drop(n) } # 0 1 2 ``` So there are no data races by construction. All tasks run on one operating system thread in 1.0; using several cores is planned after 1.0. ## 12.4 Taking turns A task runs until it waits: for a channel, another task, a timer, or input and output. Then the next task in line runs. `time.sleep(0)` gives the others a turn. `Channel[T]()` has no limit; `Channel[T](capacity: n)` makes `send` wait while `n` values wait to be received. `for x in ch` receives until the channel is closed and empty, and `receive()` gives `none` then. Waiting can't happen inside a callback the runtime is running (the function given to `map` or `filter`, a `to_str`): that is an `Error`. `time.sleep` inside one simply waits, holding up the other tasks. The program ends when its own code ends, stopping the tasks still running. A task's error is thrown by `wait()`; one that nothing waited for is printed when the program ends, and the exit code is 1. When every task waits and nothing can wake them, the program ends with a deadlock error. --- Source: https://plum.elixpo.com/docs/language/the-standard-library/ # The standard library Modules are imported with `seed`. The 1.0 library is planned as: | Module | Contents | |---|---| | `math` | constants and functions on numbers, random numbers | | `string` | the methods of `str` (always available on strings) | | `list`, `map`, `set` | the methods of collections (always available) | | `io` | standard input and output, formatting | | `fs` | files and directories | | `os` | arguments, environment, processes, exit | | `time` | clocks, dates, durations, `sleep` | | `json` | parse and produce JSON, mapped to maps, lists and trees | | `net` | TCP and UDP sockets, TLS, DNS | | `net.http` | an HTTP and HTTPS server and client | | `test` | assertions and a test runner (`plum test`) | Each module is documented in `docs/stdlib/` as it lands, and `plum stdlib` lists the functions of every module with their signatures. The methods of `str` are documented as the `str` page there. A web server, for a taste: ```plum seed net.http plant app = http.server() app.get("/hello/:name", (req) => http.text("Hello, {req.params["name"]}!")) app.listen(8080) ``` Each connection runs in its own task (section 12). `docs/stdlib/net.http.md` describes the server (routes with `:params`, middleware, static files) and the client (`http.get`, `http.post_json`, ...). Some standard modules, like `net.http`, are written in Plumlang and built into `plum`. --- Source: https://plum.elixpo.com/docs/language/running-programs/ # Running programs ``` plum run program.plum [args...] # run a program plum run --check-leaks program.plum # ...and report objects left in cycles (11.3) plum run --mem-stats program.plum # ...and print the memory it used (11.5) plum program.plum [args...] # the same plum check program.plum # check for errors without running plum test # run tests (Stage 5) plum fmt files-or-directories... # format source files in place (14.1) plum fmt --check paths... # ...change nothing; list files that would change plum fmt - # format standard input to standard output plum # interactive prompt, on a terminal (14.2) plum repl # the interactive prompt, also with piped input plum lsp # the language server, for editors (docs/lsp.md) ``` Exit codes: 0 success, 1 the program failed (compile or runtime error, or `exit(1)`), 2 the command was used wrongly, 3 a source file could not be read. ## 14.1 Formatting `plum fmt` gives source code one canonical layout. It formats the files it is given, and every `.plum` file under the directories it is given; `--check` changes nothing, lists the files that would change and exits 1 if there are any; `--stdout` writes the result to standard output instead of the file. A file with syntax errors is reported and left as it is (exit 1). The layout: - four spaces per level; `{` ends its line and `}` starts its own; - one space around binary operators and after commas, none around `..`; - at most one blank line between statements, none at the start or end of a block, and one before and after a top-level `branch`, `tree`, `trait` or `kind` that takes more than one line; - a list, map, call, parameter list or kind that the source spreads over several lines gets one item per line, with a trailing comma (kind cases go without); one on a single line stays on one line. An `if` expression over several lines puts each branch on lines of its own; - literals keep their spelling (`0xFF`, `1_000`, escapes, `"""` strings, `true`), and parentheses the source wrote are kept; - a comment on a line of its own stays on a line of its own, before what follows it; one after code stays after that code, and trailing comments on neighbouring lines are lined up. Formatting never changes what a program means, and formatting a formatted file changes nothing. ## 14.2 The interactive prompt `plum` with no arguments, when standard input is a terminal, starts a REPL; with piped input it prints the help instead (`plum repl` reads piped input as entries, without prompts). Each entry, a line, or several lines while a bracket is open, a line ends with an operator, `,` or `=>`, or a `"""` string is open, is checked and run at once, as if it were the next part of one program: - What an entry declares (variables, functions, trees, traits, kinds and `seed` imports) is there for the entries after it. An entry may declare a name again; the new declaration hides the old one from then on, while code written before keeps the old one. - An entry that is one expression prints its value as `drop` would (an object through its `to_str`) and its type: `= 42 : int`. A `none` value prints nothing. Such an expression is not an unused value (5.7). - An entry with a compile error or a runtime error reports it and leaves nothing it declared behind; what earlier entries made is kept. Imported files are loaded and run once, by the first entry that imports them. - Tasks run while an entry runs, and the entry ends when its own code does; tasks still running carry on while later entries run (12). - `exit(n)` ends the session with exit code `n`; otherwise it ends with 0 at the end of the input, `:quit` or Ctrl-D. Commands start with `:`: `:help`, `:type expr` (the expression's type, without running it), `:load file.plum` (run a file's code as an entry), `:reset` (forget every declaration) and `:quit` (or `:q`). --- Source: https://plum.elixpo.com/docs/language/changes-from-the-python-prototype/ # Changes from the Python prototype The Python prototype (plum-lang v0.1 to v0.10) introduced the garden keywords; Plumlang keeps them and changes the rest where the prototype was hard to read or unsafe: | Prototype | Plumlang | Why | |---|---|---| | `plant int x = 5` | `plant x = 5`, `plant x: int = 5` | Inference; the type follows the name everywhere | | `branch int add(int a, int b)` | `branch add(a: int, b: int) -> int` | The same `name: type` order as variables | | `drop x` and `drop(x)` | `drop(x)` only | One way; `drop` is an ordinary function | | `&&` `\|\|` `!` | `and` `or` `not` | Reads as English, and frees `!` | | `++` `--` | `x += 1` | One way to add one; no prefix/postfix puzzles | | C-style `for (init; cond; step)` | `for i in 0..n`, `while` | Fewer ways to write a loop, no off-by-one setup | | `if (cond)` | `if cond` | Parentheses optional, like any expression | | Every number a float (`25.0`) | `int` and `float` are separate | `drop(25)` prints `25` | | `10 / 2` gives `5.0` | `/` gives a float, `//` an int | Kept, and made explicit | | Mixed `#`, `//`, `--` comments | `#` only | One comment syntax | | Type errors while running | Type errors before running | Caught early, with a location | | Python exceptions leak out | Plumlang errors with a stack trace | Messages about your program, not the interpreter | --- Source: https://plum.elixpo.com/docs/language/open-questions/ # Open questions To be settled before the parser (#10) depends on them: 1. Should `trait` have a garden-themed name, like the other declaration keywords? The current choice is `trait`, the term most programmers already know. 2. `true`/`false` as alternative spellings of `good`/`bad` (section 2.5): keep both, or allow only one? 3. Generic trees and functions (`tree Stack[T]`) are left out of 1.0 except for the built-in collections. Are they needed for 1.0? --- Source: https://plum.elixpo.com/docs/stdlib/ # The standard library > The modules built into plum: numbers, text, files, time, JSON, tasks, sockets and HTTP. Modules are imported with `seed` (spec section 9.2): ```plum seed math # math.sqrt(2.0) seed math as m # m.sqrt(2.0) seed math { sqrt, PI } # sqrt(PI) ``` | Module | Contents | |---|---| | [`math`](https://plum.elixpo.com/docs/stdlib/math/) | constants and functions on numbers, and random numbers | | [`str`](https://plum.elixpo.com/docs/stdlib/str/) | the methods of strings, always available without `seed` | | [`io`](https://plum.elixpo.com/docs/stdlib/io/) | standard input, output and error | | [`os`](https://plum.elixpo.com/docs/stdlib/os/) | the program's arguments, the environment and running commands | | [`time`](https://plum.elixpo.com/docs/stdlib/time/) | clocks, sleeping and dates | | [`fs`](https://plum.elixpo.com/docs/stdlib/fs/) | files and directories | | [`json`](https://plum.elixpo.com/docs/stdlib/json/) | parse and produce JSON; [`Json` values](https://plum.elixpo.com/docs/stdlib/json-value/) | | [`Task` and `Channel`](https://plum.elixpo.com/docs/stdlib/task-methods/) | waiting for tasks, channels between them (no `seed`) | | [`net`](https://plum.elixpo.com/docs/stdlib/net/) | TCP and UDP sockets, DNS; [`Listener`](https://plum.elixpo.com/docs/stdlib/net-listener/), [`Connection`](https://plum.elixpo.com/docs/stdlib/net-connection/), [`UdpSocket`](https://plum.elixpo.com/docs/stdlib/net-udp/) | | [`net.http`](https://plum.elixpo.com/docs/stdlib/net-http/) | an HTTP/1.1 server and client, written in Plumlang | | [`hash`](https://plum.elixpo.com/docs/stdlib/hash/) | cryptographic digests: SHA-256 | `plum stdlib` lists every module's functions with their signatures, and `plum stdlib math` one module's. The reference table on each page is generated from the same list (`make stdlib-doc`), and `make test` fails if a page falls behind. In signatures, `num` means an `int` or a `float`: a `num` result is an `int` when every `num` argument is an `int`. A parameter written with `= default` can be left out. Errors that the functions throw are listed with each module. To add a module, see [writing a module](https://plum.elixpo.com/docs/stdlib/writing-a-module/). --- Source: https://plum.elixpo.com/docs/stdlib/math/ # math ```plum seed math drop(math.sqrt(2.0)) # 1.4142135623730951 drop(math.max(3, 9), math.abs(-2.5)) # 9 2.5 drop(math.round(3.14159, digits: 2)) # 3.14 drop(math.random_int(1, 6)) # a die roll ``` Angles are in radians. Functions that take a `float` also take an `int`. ## Errors - `ValueError`: `sqrt` of a negative number; `log` of 0 or less, or with a base of 0 or less or 1; `asin` / `acos` outside -1 to 1; `clamp` or `random_int` with `low` above `high`; `round` with more than 15 digits either way. - `OverflowError`: `abs(MIN_INT)`; `floor` / `ceil` of a float too large for an int, or of NAN. ## Random numbers Each program starts its random numbers from a seed the operating system picks, so runs differ. `math.seed_random(n)` restarts them from `n`: the same seed gives the same numbers, on every platform (the generator is xoshiro256**, seeded with splitmix64). They are not for cryptography. ## Reference | Name | Signature | What it does | |---|---|---| | `abs` | `abs(x: num) -> num` | the value without its sign | | `min` | `min(a: num, b: num) -> num` | the smaller of two numbers | | `max` | `max(a: num, b: num) -> num` | the larger of two numbers | | `clamp` | `clamp(x: num, low: num, high: num) -> num` | x kept within low to high | | `floor` | `floor(x: float) -> int` | the int at or below x | | `ceil` | `ceil(x: float) -> int` | the int at or above x | | `round` | `round(x: float, digits: int = 0) -> float` | x rounded to that many decimals; halves go away from zero | | `sqrt` | `sqrt(x: float) -> float` | the square root | | `exp` | `exp(x: float) -> float` | e to the power x | | `log` | `log(x: float, base: float = E) -> float` | the logarithm, natural by default | | `sin` | `sin(x: float) -> float` | sine of an angle in radians | | `cos` | `cos(x: float) -> float` | cosine of an angle in radians | | `tan` | `tan(x: float) -> float` | tangent of an angle in radians | | `asin` | `asin(x: float) -> float` | the angle whose sine is x | | `acos` | `acos(x: float) -> float` | the angle whose cosine is x | | `atan` | `atan(x: float) -> float` | the angle whose tangent is x | | `atan2` | `atan2(y: float, x: float) -> float` | the angle of the point (x, y) | | `is_nan` | `is_nan(x: float) -> bool` | is x not a number (NAN)? | | `is_finite` | `is_finite(x: float) -> bool` | is x neither infinite nor NAN? | | `random` | `random() -> float` | a random float from 0 up to (not including) 1 | | `random_int` | `random_int(low: int, high: int) -> int` | a random int from low to high, both included | | `seed_random` | `seed_random(value: int)` | restart the random numbers, so they repeat | | `PI` | `PI: float` | the ratio of a circle's circumference to its diameter | | `TAU` | `TAU: float` | 2 * PI, a full turn in radians | | `E` | `E: float` | the base of natural logarithms | | `INF` | `INF: float` | positive infinity | | `MAX_INT` | `MAX_INT: int` | the largest int | | `MIN_INT` | `MIN_INT: int` | the smallest int | --- Source: https://plum.elixpo.com/docs/stdlib/str/ # str The methods of strings. They need no `seed`: ```plum plant line = " name = Ada " plant parts = line.split("=") drop(parts[0].trim(), parts[1].trim().upper()) # name ADA drop("plum".pad_start(6, fill: "*")) # **plum ``` Strings are UTF-8. Positions and lengths count characters, as indexing does (`find` gives a character position). `upper`, `lower` and the `is_` tests know ASCII letters, digits and whitespace only. ## Errors - `ValueError`: `split("")`, `count("")` or `replace("", ...)` (the text to look for is empty); `repeat` with a negative count or a result too long; `pad_start` / `pad_end` with a fill that isn't one character. ## Reference | Name | Signature | What it does | |---|---|---| | `upper` | `upper(self: str) -> str` | the text in capitals (ASCII letters) | | `lower` | `lower(self: str) -> str` | the text in small letters (ASCII letters) | | `trim` | `trim(self: str) -> str` | without whitespace at either end | | `trim_start` | `trim_start(self: str) -> str` | without whitespace at the start | | `trim_end` | `trim_end(self: str) -> str` | without whitespace at the end | | `split` | `split(self: str, separator: str = "") -> list[str]` | the pieces between separators; with none given, the words between whitespace | | `lines` | `lines(self: str) -> list[str]` | the lines, without their line breaks | | `chars` | `chars(self: str) -> list[str]` | each character as a str | | `contains` | `contains(self: str, part: str) -> bool` | does the text contain part? | | `starts_with` | `starts_with(self: str, prefix: str) -> bool` | does the text start with prefix? | | `ends_with` | `ends_with(self: str, suffix: str) -> bool` | does the text end with suffix? | | `find` | `find(self: str, part: str) -> int?` | the position of the first part, or none | | `count` | `count(self: str, part: str) -> int` | how many times part appears | | `replace` | `replace(self: str, old: str, new: str) -> str` | every old replaced with new | | `repeat` | `repeat(self: str, times: int) -> str` | the text that many times over | | `reverse` | `reverse(self: str) -> str` | the characters in reverse order | | `pad_start` | `pad_start(self: str, width: int, fill: str = " ") -> str` | filled at the start up to width characters | | `pad_end` | `pad_end(self: str, width: int, fill: str = " ") -> str` | filled at the end up to width characters | | `is_digit` | `is_digit(self: str) -> bool` | is every character 0 to 9? | | `is_alpha` | `is_alpha(self: str) -> bool` | is every character a letter (ASCII)? | | `is_space` | `is_space(self: str) -> bool` | is every character whitespace? | | `byte_len` | `byte_len(self: str) -> int` | the length in bytes of its UTF-8 (len() counts characters) | | `url_encode` | `url_encode(self: str) -> str` | for a URL: all but letters, digits and - _ . ~ as %XX | | `url_decode` | `url_decode(self: str) -> str` | %XX escapes back to text, and + to a space | --- Source: https://plum.elixpo.com/docs/stdlib/io/ # io Standard input, output and error. `drop` and `ask` cover most programs; `io` is for output without `drop`'s spaces and newline, for errors, and for reading all of the input. ```plum seed io io.write("Loading") for i in 0..3 { io.write(".") } io.write("\n") io.write_err("warning: no config file\n") plant text = io.read_all() # everything piped in ``` Output to standard output is buffered: `io.flush()` sends it now (reading input flushes it first, so prompts appear). ## Reference | Name | Signature | What it does | |---|---|---| | `write` | `write(text: str)` | write text to standard output, as it is | | `write_err` | `write_err(text: str)` | write text to standard error, as it is | | `flush` | `flush()` | send what's waiting in standard output now | | `read_line` | `read_line() -> str?` | a line from standard input without its line break; none at the end | | `read_all` | `read_all() -> str` | everything left on standard input | --- Source: https://plum.elixpo.com/docs/stdlib/os/ # os The program's arguments, the environment, and running commands. To end the program, use the built-in `exit(code)`. ```plum seed os plant args = os.args() # plum run greet.plum Ada → ["Ada"] plant name = if len(args) > 0 { args[0] } else { "friend" } drop("Hello, {name}! ({os.platform()})") plant home = os.env("HOME") ?? "unknown" ``` `os.run` runs a command through the system's shell (`sh` on Linux and macOS, `cmd` on Windows) and gives its exit code; a command ended by a signal gives 128 plus the signal's number. Never build a command from text a user typed: the shell would run whatever it says. ## Errors - `IOError`: `run` when the shell can't be started; `cwd` when the working directory can't be read. - `ValueError`: `run` with a command containing a zero byte. ## Reference | Name | Signature | What it does | |---|---|---| | `args` | `args() -> list[str]` | the arguments after the program's file: plum run app.plum a b gives ["a", "b"] | | `env` | `env(name: str) -> str?` | an environment variable, or none if it isn't set | | `platform` | `platform() -> str` | "linux", "macos", "windows", "unix", or "wasm" in the browser | | `cwd` | `cwd() -> str` | the working directory | | `run` | `run(command: str) -> int` | run a command through the system's shell and give its exit code | --- Source: https://plum.elixpo.com/docs/stdlib/time/ # time Clocks, sleeping and dates. Times are `float` seconds since 1970-01-01 00:00 UTC, as `time.now()` gives them. ```plum seed time plant start = time.clock() time.sleep(0.5) drop("took {time.clock() - start:.2} s") drop(time.format(time.now())) # 2026-11-13 21:04:05 drop(time.format(time.now(), "%d %B %Y", utc: good)) # 13 November 2026 drop(time.parts(time.now())["weekday"]) # 1 Monday … 7 Sunday ``` `clock` is for measuring how long something takes: it never goes back, even when the time of day is changed. `now` is the time of day. Dates are local time unless `utc: good` is given. `format` knows these patterns, the same on every platform: | Pattern | Gives | Pattern | Gives | |---|---|---|---| | `%Y` | year, 2026 | `%y` | year, 26 | | `%m` | month, 01 to 12 | `%B` / `%b` | month name, November / Nov | | `%d` | day, 01 to 31 | `%A` / `%a` | weekday name, Friday / Fri | | `%H` | hour, 00 to 23 | `%p` | AM or PM | | `%M` | minute | `%S` | second | | `%j` | day of the year, 001 to 366 | `%Z` | time zone name | | `%%` | a `%` | | | ## Errors - `ValueError`: `sleep` with a negative time (or more than 10,000,000 seconds); `format` with a pattern not listed above; `format` / `parts` of a time outside the years 1 to 9999. ## Reference | Name | Signature | What it does | |---|---|---| | `now` | `now() -> float` | the time of day: seconds since 1970-01-01 00:00 UTC | | `clock` | `clock() -> float` | seconds on a clock that never goes back, for measuring how long things take | | `sleep` | `sleep(seconds: float)` | wait that many seconds | | `format` | `format(t: float, pattern: str = "%Y-%m-%d %H:%M:%S", utc: bool = bad) -> str` | a time as text; local time unless utc | | `parts` | `parts(t: float, utc: bool = bad) -> map[str, int]` | year, month, day, hour, minute, second, weekday (1 Monday to 7 Sunday) and yearday | --- Source: https://plum.elixpo.com/docs/stdlib/fs/ # fs Files and directories. Text is read and written as it is (UTF-8, no newline translation), and paths use `/` on every platform (Windows accepts it too). ```plum seed fs fs.write("notes.txt", "first line\n") fs.append("notes.txt", "second line\n") for line in fs.read("notes.txt").lines() { drop(line) } if not fs.exists("out") { fs.make_dir("out") } drop(fs.list(".")) # the names here, sorted ``` ## Errors Every function that touches the disk throws `IOError` when the operating system refuses, with its reason: a missing file, no permission, a directory that isn't empty, and so on. `exists` and `is_dir` never throw. An empty path, or one containing a zero byte, is an `IOError` too. ```plum try { plant config = fs.read("config.txt") } catch e: IOError { drop("no config: {e.message}") } ``` ## Reference | Name | Signature | What it does | |---|---|---| | `read` | `read(path: str) -> str` | the whole file as text | | `write` | `write(path: str, text: str)` | make or replace the file with text | | `append` | `append(path: str, text: str)` | add text to the end of the file | | `exists` | `exists(path: str) -> bool` | is there a file or directory at path? | | `is_dir` | `is_dir(path: str) -> bool` | is path a directory? | | `remove` | `remove(path: str)` | delete a file, or an empty directory | | `rename` | `rename(from: str, to: str)` | move or rename a file or directory | | `make_dir` | `make_dir(path: str)` | make a directory (fine if it already exists) | | `list` | `list(path: str) -> list[str]` | the names in a directory, sorted | | `temp_dir` | `temp_dir() -> str` | a directory for temporary files | --- Source: https://plum.elixpo.com/docs/stdlib/json/ # json Parse and produce JSON. A parsed document is a `Json` value: take it apart with its methods ([`json.value`](https://plum.elixpo.com/docs/stdlib/json-value/)), which give `none` or null instead of failing, so a lookup can go several levels deep and end with `??`: ```plum seed json plant data = json.parse(fs.read("config.json")) plant port = data.get("server").get("port").int() ?? 8080 for user in data.get("users").list() ?? [] { drop(user.get("name").str() ?? "(no name)") } ``` Anything made of plain data can be a `Json`: numbers, strings, bools, `none`, lists, `map[str, ...]`, and tree objects (written as their fields). A list or map literal whose expected type is `Json` may mix types: ```plum plant body: Json = {"name": "Ada", "age": 36, "tags": ["admin", 1]} drop(json.stringify(body)) # {"name":"Ada","age":36,"tags":["admin",1]} drop(json.stringify(body, indent: 2)) # one member per line ``` How JSON and Plumlang values match: | JSON | Plumlang | |---|---| | `null` | `none` | | `true`, `false` | `good`, `bad` | | a number without a fraction or exponent that fits | `int` | | any other number | `float` | | a string | `str` (escapes, including `\u` pairs, become UTF-8) | | an array | `list[Json]` | | an object | `map[str, Json]`, keys in their order | Writing also takes sets (as arrays) and tree objects (as objects of their fields; a weak field is written as what it refers to, or null). ## Errors - `ParseError` from `parse`: the message gives the line and column, like `json.parse: line 3, column 9: expected ':' after the key`. Nesting deeper than 512 is refused. - `ValueError` from `stringify`: infinity or NAN, a map whose keys aren't strings, a kind's value, a function, or nesting deeper than 512 (an object that contains itself). Writing JSON inside a Plumlang string needs `\{` and `\}`, since braces start interpolation there; JSON usually comes from a file or the network instead. ## Reference | Name | Signature | What it does | |---|---|---| | `parse` | `parse(text: str) -> Json` | JSON text as a Json value; a ParseError says where it went wrong | | `stringify` | `stringify(value: Json, indent: int = 0) -> str` | a value as JSON text, on one line or indented by that many spaces | --- Source: https://plum.elixpo.com/docs/stdlib/json-value/ # Json values The methods of `Json` values (from `json.parse`, or any plain data given the type `Json`). They need no `seed`. None of them fail: asking a value for something it isn't gives `none` (for the typed answers) or null (for `get` and `at`), so lookups chain: ```plum plant city = data.get("address").get("city").str() ?? "unknown" plant first = data.get("items").at(0) drop(first.type_name()) # "object", "list", "string", ... ``` `int()` gives a number only if it is whole (`3.0` gives 3, `3.5` gives none); `float()` gives any number. ## Reference | Name | Signature | What it does | |---|---|---| | `get` | `get(self: Json, key: str) -> Json` | an object's member; null if it's missing or this isn't an object | | `at` | `at(self: Json, index: int) -> Json` | a list's item (-1 is the last); null if out of range or this isn't a list | | `len` | `len(self: Json) -> int` | the items of a list, members of an object or characters of a string; else 0 | | `keys` | `keys(self: Json) -> list[str]` | an object's keys in order; else [] | | `type_name` | `type_name(self: Json) -> str` | "null", "bool", "number", "string", "list" or "object" | | `is_null` | `is_null(self: Json) -> bool` | is this null? | | `str` | `str(self: Json) -> str?` | the string, or none if this isn't one | | `int` | `int(self: Json) -> int?` | the number as an int, or none if it isn't a whole one | | `float` | `float(self: Json) -> float?` | the number as a float, or none | | `bool` | `bool(self: Json) -> bool?` | the bool, or none | | `list` | `list(self: Json) -> list[Json]?` | the list, or none | | `map` | `map(self: Json) -> map[str, Json]?` | the object as a map, or none | --- Source: https://plum.elixpo.com/docs/stdlib/task-methods/ # Task and Channel The methods of tasks and channels (spec section 12). They need no `seed`. ```plum seed time branch fetch(n: int) -> int { time.sleep(0.1) # other tasks run meanwhile return n * 10 } plant jobs = [spawn fetch(1), spawn fetch(2), spawn fetch(3)] for j in jobs { drop(j.wait()) # 10, 20, 30: after about 0.1 s in all, not 0.3 s } ``` `wait()` and `receive()` can't be called inside a callback (`map`, `filter`, `to_str`, ...), since a task can only wait when nothing else is running; use a `for` loop, as above. A channel carries values from task to task. `for x in channel` receives until the channel is closed and empty. `Channel[T]()` has no limit; `Channel[T](capacity: n)` makes `send` wait while `n` values are waiting to be received. ```plum plant results = Channel[str]() spawn (() => { for name in ["a", "b", "c"] { results.send(name.upper()) } results.close() })() for r in results { drop(r) } ``` ## How tasks run All tasks run on one thread, taking turns: a task runs until it waits (for a channel, another task, or `time.sleep`), and then the next one in line runs. `time.sleep(0)` gives the others a turn. So two tasks never run at the same moment, and nothing needs locking. A task costs a few kilobytes, so thousands of them are fine. The program ends when its own code ends; tasks still running then are stopped. A task that fails is not lost: `wait()` throws its error, and an error nothing waited for is printed when the program ends (exit code 1). If every task is waiting and nothing can wake them, that's a deadlock, also reported, with exit code 1. ## Errors - `wait()` throws the task's error, with the trace of where it happened. - `Error`: `send()` on a closed channel; `wait()`, `receive()` or a full `send()` inside a callback; a task waiting for itself. - `ValueError`: a negative channel capacity. ## Reference The signatures use `T` for the task's result or the channel's values. | Name | Signature | What it does | |---|---|---| | `wait` | `wait(self: Task[T]) -> T` | the task's result once it ends; if it failed, its error is thrown here | | `done` | `done(self: Task[T]) -> bool` | has the task ended? | | `new_channel` | `new_channel(capacity: int = 0) -> Channel[T]` | Channel[T](capacity): a channel; a capacity of 0 means no limit | | `send` | `send(self: Channel[T], value: T)` | put a value in the channel; waits for room if it has a capacity and is full | | `receive` | `receive(self: Channel[T]) -> T?` | the next value, waiting for one; none once the channel is closed and empty | | `close` | `close(self: Channel[T])` | no more values: receivers get what's left, then none | --- Source: https://plum.elixpo.com/docs/stdlib/net/ # net TCP and UDP sockets, TLS, and DNS. A program that serves many connections gives each one a task (spec section 12): while a task waits for its socket, the others run. ```plum seed net branch serve(conn: Connection) { plant line = conn.read_line() while line != none { conn.write("you said: {line ?? ""}\n") line = conn.read_line() } } plant server = net.listen(8080) while good { plant conn = server.accept() spawn ((c: Connection) => serve(c))(conn) } ``` A client: ```plum plant c = net.connect("example.com", 80, timeout: 5.0) c.write("HEAD / HTTP/1.0\r\nHost: example.com\r\n\r\n") drop(c.read_line()) c.close() ``` ## TLS `net.tls_connect` is `connect` with TLS (1.2 or 1.3) on top; the `Connection` it gives reads and writes like any other: ```plum plant c = net.tls_connect("example.com", 443, timeout: 10.0) c.write("HEAD / HTTP/1.0\r\nHost: example.com\r\n\r\n") drop(c.read_line()) c.close() ``` The server's certificate is checked against the system's trusted CA certificates and against the host name. The trusted CAs are, in order: the file `SSL_CERT_FILE` names, if it is set; the system's bundle on Linux and the BSDs (`/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, `/etc/ssl/ca-bundle.pem`, `/etc/ssl/cert.pem`) and macOS (`/etc/ssl/cert.pem`); the `ROOT` store on Windows. They are read once, by the first connection that needs them. `ca_file: "my-ca.pem"` trusts the CAs in that PEM file instead (a private CA, a test server), and `verify: bad` checks nothing at all: the connection is encrypted, but anyone in the middle can read it. A TLS server takes its certificate chain and private key from PEM files: ```plum plant server = net.listen_tls(8443, "cert.pem", "key.pem") while good { plant conn = server.accept() spawn ((c: Connection) => serve(c))(conn) } ``` `accept()` returns as soon as a client connects. The handshake is made by the connection's first `read` or `write`, in the task that serves it, so a client that is slow to finish it holds up no one else; a client whose handshake fails shows up as a `NetError` from that `read` or `write`. TLS is Mbed TLS 4.1 (`vendor/mbedtls`), built into `plum`. Handshakes wait like everything else here: other tasks run while one does. The handles are [`Listener`](https://plum.elixpo.com/docs/stdlib/net-listener/), [`Connection`](https://plum.elixpo.com/docs/stdlib/net-connection/) and [`UdpSocket`](https://plum.elixpo.com/docs/stdlib/net-udp/). They close when the program closes them, or when nothing refers to them any more. ## Waiting and time limits Every socket is non-blocking underneath: `accept`, `connect`, `tls_connect`, `read`, `read_line`, `write` and `receive` let other tasks run while they wait. The time limit of `tls_connect` covers both the connection and the handshake. Each takes a `timeout` in seconds (0, the default, means no limit) and throws `NetError` with `...: timed out` when it runs out. Looking a name up (`connect`, `resolve`, `send_to` with a host name) waits without letting other tasks run. The scheduler waits on sockets with epoll on Linux, kqueue on macOS and the BSDs, and `WSAPoll` on Windows: idle connections cost nothing while they wait. See `bench/net/idle.plum` and `bench/README.md` (10,000 idle connections). ## Errors - `NetError`: anything the network or the system refuses, with its reason (`connect to example.com port 81: Connection refused`), a name that can't be looked up, a time limit running out, a closed handle. For TLS also a certificate that doesn't verify (`tls_connect to example.com port 443: certificate verify failed: the certificate is not correctly signed by the trusted CA`), a handshake that fails, and certificate or key files that can't be read. - `ValueError`: a port outside 0 to 65,535 (1 to 65,535 to connect), a negative timeout, a `read` size outside 1 byte to 16 MB, a datagram over 65,507 bytes. ## Reference | Name | Signature | What it does | |---|---|---| | `listen` | `listen(port: int, host: str = "0.0.0.0") -> Listener` | a TCP listener on a port (0 picks a free one); listener.accept() takes connections | | `connect` | `connect(host: str, port: int, timeout: float = 0) -> Connection` | a TCP connection to host and port | | `tls_connect` | `tls_connect(host: str, port: int, timeout: float = 0, verify: bool = good, ca_file: str = "") -> Connection` | a TLS connection to host and port, its certificate checked against the system's trusted CAs (or ca_file) and the host name, unless verify is bad | | `listen_tls` | `listen_tls(port: int, cert_file: str, key_file: str, host: str = "0.0.0.0") -> Listener` | a TLS listener, with a certificate chain and private key from PEM files; accept() takes connections, which make the handshake on their first read or write | | `udp` | `udp(port: int = 0, host: str = "0.0.0.0") -> UdpSocket` | a UDP socket on a port (0 picks a free one) | | `resolve` | `resolve(host: str) -> list[str]` | the addresses a host name has | --- Source: https://plum.elixpo.com/docs/stdlib/net-listener/ # Listener The methods of `Listener` values from the [`net`](https://plum.elixpo.com/docs/stdlib/net/) module. They need no `seed` of their own. ## Reference | Name | Signature | What it does | |---|---|---| | `accept` | `accept(self: Listener, timeout: float = 0) -> Connection` | the next connection, waiting for one | | `port` | `port(self: Listener) -> int` | the port it listens on | | `close` | `close(self: Listener)` | stop listening | --- Source: https://plum.elixpo.com/docs/stdlib/net-connection/ # Connection The methods of `Connection` values from the [`net`](https://plum.elixpo.com/docs/stdlib/net/) module. They need no `seed` of their own. ## Reference | Name | Signature | What it does | |---|---|---| | `read` | `read(self: Connection, max: int = 65536, timeout: float = 0) -> str?` | what has arrived (waiting for something), up to max bytes; none once the other end closes | | `read_line` | `read_line(self: Connection, timeout: float = 0) -> str?` | the next line, without its line break; none at the end | | `write` | `write(self: Connection, text: str, timeout: float = 0)` | send all of text, waiting for room as needed | | `remote` | `remote(self: Connection) -> str` | the other end, as "host:port" | | `port` | `port(self: Connection) -> int` | this end's port | | `close` | `close(self: Connection)` | close the connection | --- Source: https://plum.elixpo.com/docs/stdlib/net-udp/ # UdpSocket The methods of `UdpSocket` values from the [`net`](https://plum.elixpo.com/docs/stdlib/net/) module. They need no `seed` of their own. ## Reference | Name | Signature | What it does | |---|---|---| | `send_to` | `send_to(self: UdpSocket, host: str, port: int, text: str)` | send one datagram | | `receive` | `receive(self: UdpSocket, max: int = 65536, timeout: float = 0) -> str` | the next datagram, waiting for one | | `sender` | `sender(self: UdpSocket) -> str` | where the last datagram received came from, as "host:port" | | `port` | `port(self: UdpSocket) -> int` | the port it is on | | `close` | `close(self: UdpSocket)` | close the socket | --- Source: https://plum.elixpo.com/docs/stdlib/net-http/ # net.http An HTTP/1.1 server and client, over plain TCP or TLS (HTTPS). `seed net.http` makes it `http`. ```plum seed net.http plant app = http.server() app.get("/hello/:name", (req) => http.text("Hello, {req.params["name"]}!")) app.listen(8080) ``` Each connection is served by a task of its own (spec section 12), so a slow client holds up nobody. The module is written in Plumlang (`src/stdlib/plum/net_http.plum`) on top of `net`, tasks and `json`, and built into the binary. ## The server | Call | What it does | |---|---| | `http.server() -> Server` | a server with no routes yet | | `app.get(pattern, handler)`, `post`, `put`, `patch`, `delete` | a route; `handler` is `(Request) -> Response` | | `app.route(method, pattern, handler)` | a route for any method | | `app.use(middleware)` | `(req, next) => ...` runs around every request; call `next(req)` to go on, or return a response yourself | | `app.static(prefix, dir)` | `GET prefix/a.css` serves `dir/a.css`; `index.html` for a directory; nothing outside `dir` | | `app.listen(port = 8080, host = "0.0.0.0")` | serve until the program ends | | `app.start(port = 8080, host = "0.0.0.0") -> int` | serve in the background; the port (0 picks a free one) | | `app.listen_tls(port, cert_file, key_file, host = "0.0.0.0")` | `listen` over HTTPS, with a certificate chain and private key from PEM files | | `app.start_tls(port, cert_file, key_file, host = "0.0.0.0") -> int` | `start` over HTTPS | | `app.stop()` | stop accepting connections | | `app.handle(req) -> Response` | the response to a request, without any network: for tests | | `app.log_errors` | print handlers' errors to standard error (default `good`) | Patterns match whole paths, part by part: `/users/:id/posts/:post` fills `req.params["id"]` and `req.params["post"]`. A path that matches no route is 404; one that matches with another method is 405. `HEAD` is answered by the `GET` route, without the body. An error a handler doesn't catch becomes a 500 response (and is logged). Connections are kept alive between requests (HTTP/1.1), and closed after 30 seconds without one. Over HTTPS, each connection's TLS handshake is made in its own task (see [net](https://plum.elixpo.com/docs/stdlib/net/#tls)). Bodies are limited to 16 MB and requests to 100 headers. ### Request | Field or method | | |---|---| | `method`, `path` | `"GET"`, `"/users/7"` | | `query` | `map[str, str]` of `?a=1&b=two`, decoded | | `params` | `map[str, str]` from the route pattern | | `headers` | `map[str, str]`, names in small letters | | `body` | the body as text | | `remote` | the client, as `"host:port"` | | `header(name) -> str?` | one header, any case | | `json() -> Json` | the body parsed as JSON (a `ParseError` if it isn't) | ### Responses | Call | | |---|---| | `http.text(body, status = 200)` | `text/plain` | | `http.html(body, status = 200)` | `text/html` | | `http.json(value, status = 200)` | `value` (any `Json`) as `application/json` | | `http.redirect(to, status = 302)` | a `location` header | | `http.status(code, message = "")` | just a status, with its reason or `message` as the body | | `Response(status, body, headers)` | anything else | A `Response` has `status`, `body` and `headers`, and `header(name)`, `with_header(name, value)` (returns itself, for chaining), `json()` and `ok()` (a 2xx status). It prints as `404 Not Found`. ## The client | Call | | |---|---| | `http.get(url, headers = {:}, timeout = 30.0, verify = good, ca_file = "") -> Response` | | | `http.post(url, body, content_type = "text/plain; charset=utf-8", headers = {:}, timeout = 30.0, verify = good, ca_file = "")` | | | `http.post_json(url, value, headers = {:}, timeout = 30.0, verify = good, ca_file = "")` | `value` (any `Json`) as the JSON body | | `http.request(method, url, body = "", headers = {:}, timeout = 30.0, verify = good, ca_file = "")` | any method | URLs are `http://host[:port]/path` (port 80) or `https://host[:port]/path` (port 443). An `https://` server's certificate is checked against the system's trusted CAs and the host name, as `net.tls_connect` does: `ca_file` trusts the CAs in a PEM file instead, and `verify: bad` turns the check off. They give the response whatever its status (check `res.ok()` or `res.status`). Bodies sent with a length, in chunks, or up to the end of the connection are all read. ```plum plant res = http.post_json("http://localhost:8080/notes", {"text": "water the plants"}) if res.ok() { drop(res.json().get("id").int()) } ``` ## Errors - `NetError`: the server can't be reached, the connection breaks, a time limit runs out, the answer isn't HTTP, or (`https://`) the server's certificate doesn't verify or the TLS handshake fails. - `ValueError`: a URL that isn't `http://` or `https://host[:port]/path`. ## Speed `bench/net/http_load.py` drives `bench/net/http_server.plum` with 8 keep-alive connections (Python clients, one process each; Linux x86_64, GCC `-O2`): about 127,000 text responses and 112,000 JSON responses a second, 0.06 to 0.07 ms per request at the median, 0.12 to 0.16 ms at the 99th percentile. The server is one thread; the Python clients are the limit at one connection (about 20,000 a second). ## Examples `examples/http/hello.plum` and `examples/http/rest_api.plum` (a JSON API storing notes in a file, with an API-key middleware). --- Source: https://plum.elixpo.com/docs/stdlib/hash/ # hash Cryptographic digests of text. A digest is a short fingerprint of some bytes: the same bytes always give the same digest, and any change, even of one bit, gives a different one. Use it to check that a download arrived intact or that two files are the same. ```plum seed hash drop(hash.sha256("abc")) # ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad plant text = fs.read("bundle.plumpkg") if hash.sha256(text) != expected { throw ValueError("the download is corrupt") } ``` `sha256` hashes the string's bytes (its UTF-8), zero bytes included, and gives the digest as 64 lowercase hex digits. It comes from the vendored Mbed TLS. Compare digests with `==`; the comparison is not constant-time, so don't use it to check secrets such as passwords. ## Errors - `ValueError` from `sha256` if the crypto library fails to start, which shouldn't happen. ## Reference | Name | Signature | What it does | |---|---|---| | `sha256` | `sha256(text: str) -> str` | the SHA-256 digest of the text's bytes, as 64 lowercase hex digits | --- Source: https://plum.elixpo.com/docs/stdlib/writing-a-module/ # Writing a standard module A standard module is a table of C functions that Plumlang code calls. This page shows how to add one, using a made-up `colour` module. Read [CONTRIBUTING.md](https://github.com/plumlang/plumlang/blob/main/CONTRIBUTING.md) and [AGENTS.md](https://github.com/plumlang/plumlang/blob/main/AGENTS.md) first: C11, no dependencies, warnings as errors, memory-safe. ## 1. The functions Make `src/stdlib/colour.c`. A native function gets its arguments (borrowed: don't release them), stores its result with a reference of its own, and returns `true`; on failure it throws and returns `false`. ```c /* SPDX-License-Identifier: LicenseRef-Plumlang-Commercial-1.0 */ /* The colour module: colours as #rrggbb text. */ #include "stdlib/native.h" #include #define ARGS PlumNative *n, const PlumValue *args, int argc, PlumValue *result /* rgb(r, g, b) -> "#rrggbb" */ static bool c_rgb(ARGS) { (void)argc; for (int i = 0; i < 3; i++) { if (args[i].as.i < 0 || args[i].as.i > 255) { return plum_native_throw(n, PLUM_ERROR_VALUE, "rgb: %lld is out of 0 to 255", (long long)args[i].as.i); } } char text[8]; snprintf(text, sizeof text, "#%02x%02x%02x", (int)args[0].as.i, (int)args[1].as.i, (int)args[2].as.i); *result = plum_str_value(text, 7); return true; } static const PlumNativeFunction functions[] = { {"rgb", "(r: int, g: int, b: int) -> str", c_rgb, "a colour as #rrggbb text"}, }; const PlumNativeModule plum_module_colour = { "colour", "colours as #rrggbb text", functions, sizeof functions / sizeof functions[0], NULL, 0, }; ``` - **The signature string is the function's type.** The type checker reads it, so `colour.rgb(1, "x", 3)` is a compile error and your C code can trust its arguments: an `int` parameter always holds an int, a `str` parameter a string (`plum_as_string(args[i])`). Types: `int float str bool byte none Json`, `list[T]`, `map[K, V]`, `set[T]`, `T?`, and `num` for int-or-float (a `num` result is an int when every `num` argument is). - **A parameter written `= default` may be left out;** the function then sees `none` in its place and applies the default itself. - **Methods of a type** (like those of `str`) are a module whose functions take `self` first: see `src/stdlib/string.c`. - **Constants** go in a `PlumNativeConstant` table (see `math.c`). ## 2. What a native function can use All in `src/stdlib/native.h`: | | | |---|---| | `plum_native_throw(n, PLUM_ERROR_VALUE, fmt, ...)` | throw a built-in error (`VALUE`, `PARSE`, `INDEX`, `KEY`, `IO`, `NET`, ...); returns false | | `plum_str_value(chars, len)`, `plum_int`, `plum_float`, `plum_bool`, `plum_none` | make results | | `plum_list_new`, `plum_list_push`, `plum_native_new_map` + `plum_table_put` | make lists and maps (maps through `plum_native_new_map`, so they hash with the program's key) | | `plum_num(v)` | a `num` argument as a double | | `plum_native_text(n, v)` | any value as text, through its `to_str` | | `plum_native_random(n)` | random bits from the program's generator | | `plum_native_wait_io`, `plum_native_call_state`, `plum_native_sleep` | for functions that wait (see `net.c`): other tasks run meanwhile | Strings are bytes (UTF-8 by convention); `len()` counts characters, `byte_len()` bytes. Use `plum_alloc` and friends (`src/util/alloc.h`) for memory, never `malloc`, and check every bound. ## 3. Register it - Declare `extern const PlumNativeModule plum_module_colour;` in `src/stdlib/native.h`. - Add `&plum_module_colour` at the **end** of the list in `src/stdlib/registry.c` (a function's number depends on its module's place, so don't reorder). The Makefile and CMake pick up new `.c` files by themselves. Now `seed colour` works, and `plum stdlib colour` lists it. ## 4. Document it Make `docs/stdlib/colour.md` with an introduction, examples, the errors it throws, and an empty reference section: ```markdown ## Reference ``` Run `make stdlib-doc` to fill the table from your signatures and doc lines. Add the module to `docs/stdlib/README.md`'s table. `make test` fails if a module has no page or its table is out of date. ## 5. Test it Golden tests in `tests/lang/stdlib/` (see `tests/lang/README.md`): `colour.plum` with its expected output in `colour.out`, and error cases in `error_colour.plum` / `.err`. Write the program, run `make golden-update`, and **read** the `.out` file it wrote: that's the expectation now. Cover the edges: empty input, the largest and smallest values, bad input, and what it throws. ```bash make test # unit, golden and docs checks make sanitize test # again under ASan + UBSan: no leaks, no undefined behaviour make format # clang-format 18.1.8 (pip install clang-format==18.1.8) ``` Add a line to `CHANGELOG.md` under `## Unreleased`, and open a pull request that says what you added and how you tested it. ## Writing it in Plumlang instead A module can also be written in Plumlang, like `net.http`: put it in `src/stdlib/plum/` (`net_http.plum` is `net.http`), start it with a `# module:` comment, and run `make stdlib-embed` to build it into the binary. That suits code that mostly calls other modules; byte-level work belongs in C. --- Source: https://plum.elixpo.com/docs/tools/orchard/ # Orchard: packages > Find, add and publish packages with the plum command and the Orchard registry. Orchard is Plumlang's package registry. A package is a directory with a `plum.toml`; Orchard keeps an index of published packages, and the `plum` command adds them to a project, locks their exact versions and checksums, and installs them. The language side, `seed weather`, is spec section 9.3. Orchard begins as a git repository, [plumlang/registry](https://github.com/plumlang/registry): an index of JSON files and the packages' bundles, with no server and no accounts. The client reads one base URL, so a CDN or a hosted API can take its place later without changing any command. ## Using packages Run the commands in the project's directory, the one with `plum.toml`: ```sh plum search weather # find packages plum add weather # add the newest version, as ^VERSION plum add weather@~1.2 # or a range of your choice plum install # install exactly what plum.lock lists plum remove weather ``` `plum add` resolves the package and everything it needs, installs it, writes `plum.lock`, and only then adds the line to `[dependencies]` in `plum.toml` (the rest of the file is left as it was). If anything fails, neither file changes. Then, in any file of the project: ```plum seed weather # the package's lib file: weather.forecast(...) seed weather.client # its client.plum: client.get(...) seed weather.api.v2 # its api/v2.plum seed weather { forecast } # names brought in directly ``` - **Standard modules win.** `seed json` is always the standard module, and so is anything under a standard module's name (`seed net.whatever`). Orchard refuses packages with those names. - **`-` is written `_`.** Package names may have `-`, which a `seed` can't; seed `hello-orchard` as `seed hello_orchard`. Names never have `_`, so this is never ambiguous. - **Only declared packages.** A module may seed only the packages its `plum.toml` lists: a project's files the project's dependencies, a package's files that package's own. Anything else is error E0908, with the hint `plum add NAME`. A declared package that isn't installed is E0909: run `plum install`. - The project is the nearest directory with a `plum.toml`, from the file being run upwards. Commit `plum.toml` and `plum.lock`. Someone who clones the project runs `plum install` and gets the same versions, checked against the same checksums. ## The manifest: plum.toml ```toml [package] name = "weather" # required version = "1.2.0" # required: MAJOR.MINOR.PATCH entry = "main.plum" # required: what `plum run .` runs lib = "lib.plum" # what `seed weather` imports (default: entry) description = "Forecasts from open weather APIs" license = "MIT" authors = ["Ada "] repository = "https://github.com/ada/weather" # needed to publish keywords = ["weather", "http"] plum = ">=0.1" # the Plumlang versions it works with [dependencies] colors = "^1.0" ``` `plum.toml` is read by a small, strict part of TOML: `[tables]`, `key = "string"` (or `'literal'`), lists of strings, which may run over several lines, and `#` comments. Every value is a string or a list of strings; there are no numbers, booleans, inline tables or arrays of tables. A misspelt key is an error, not ignored. Every problem is reported at its line and column with a code (E0901 to E0911 in [errors.md](https://plum.elixpo.com/docs/errors/)). - **Names**: 2 to 40 lowercase letters, digits and single `-`, starting with a letter and not ending with `-`. Not a standard module's name, `plum`, `std`, `stdlib` or `orchard`, and not a keyword once `-` becomes `_` (so not `tree`). - **Versions** are exactly three numbers, `MAJOR.MINOR.PATCH`, without leading zeros. There are no pre-release or build labels (`1.0.0-beta`). - **`entry` and `lib`** name `.plum` files inside the package. - **Description**: at most 300 bytes. **Keywords**: at most 10, each 1 to 30 lowercase letters, digits and `-`. - **`plum`** is a version range. Installing a package whose range doesn't include the running `plum` prints a warning. ### Version ranges One requirement per dependency: | Range | Means | Example | |---|---|---| | `^1.2.3` | the same left-most non-zero number | `>=1.2.3, <2.0.0`; `^0.2.3` is `<0.3.0`; `^0.0.3` is `<0.0.4` | | `~1.2.3` | the same minor version | `>=1.2.3, <1.3.0`; `~1` is `<2.0.0` | | `=1.2.3` | exactly | `=1.2` is any `1.2.x` | | `>=1.2` | at least | | | `*` | any version | | | `1.2` | the same as `^1.2` | | Parts left out are zeros: `^1.2` is `^1.2.0`. ### Resolution Each package is installed in one version, shared by everything in the project that needs it. For each package, `plum` takes every requirement on it (from the project and from the packages it already chose) and picks: 1. the version in `plum.lock`, if there is one and it satisfies them all (so adding a package doesn't upgrade the others); 2. otherwise the highest version that satisfies them all and isn't yanked. It repeats until nothing changes. When no version fits, error E0922 names every requirer and its range: ```text plum: error[E0922]: version conflict for 'colors': paint 1.0.0 requires colors ^1.0, brush 1.0.0 requires colors ^2.0; no version satisfies them all hint: change one of the ranges so they overlap ``` ## The lock file: plum.lock Written by `plum add`, `plum remove` and `plum install`; never edited by hand. TOML, one table per package, in name order: ```toml # plum.lock: the exact packages this project uses, written by plum. # Commit it with the project; don't edit it by hand. [packages.colors] version = "1.0.0" sha256 = "5b0c...e1" dependencies = [] [packages.paint] version = "1.0.0" sha256 = "9f3a...07" dependencies = ["colors"] ``` `plum install` installs exactly these, verifying each bundle's sha256 before unpacking it. If `plum.toml` changed so the lock no longer fits (a dependency added by hand, a range the locked version is outside), it resolves again, keeping every locked version that still fits. ## The cache Packages are unpacked once and shared by every project: | | Directory | |---|---| | `PLUM_HOME` set | `$PLUM_HOME/orchard/NAME/VERSION/` | | Linux, macOS | `~/.plum/orchard/NAME/VERSION/` | | Windows | `%LOCALAPPDATA%\plum\orchard\NAME\VERSION\` (else `%USERPROFILE%\.plum\orchard\...`) | A version is unpacked into `VERSION.part`, checked, and then renamed into place, so a failed install leaves nothing half-written. The file `.orchard-sha256` in each version records the bundle it came from; `plum install` downloads again when it doesn't match the lock. The cache can be deleted at any time. ## The registry `PLUM_ORCHARD` sets the base URL; the default is `https://raw.githubusercontent.com/plumlang/registry/main`. It may be `https://`, `http://` (for tests and mirrors) or `file:///path` (an index on disk). Redirects are followed, up to five. ```text index/we/weather.json the package's index file (first two letters of the name) packages/weather/1.2.0.plumpkg the bundles search.json every package, for search and the website ``` ### Index files ```json { "name": "weather", "owners": ["ada"], "description": "Forecasts from open weather APIs", "repository": "https://github.com/ada/weather", "keywords": ["weather", "http"], "versions": [ { "version": "1.2.0", "sha256": "64 lowercase hex digits: the bundle's SHA-256", "dependencies": {"colors": "^1.0"}, "plum": ">=0.1", "published": "2026-11-15T10:00:00Z", "yanked": false } ] } ``` `owners` are GitHub logins: the first publisher owns the name, and only owners publish new versions or yank. `plum` reads `name` and `versions`; the rest is for people and the website. ### search.json ```json {"packages": [{"name": "weather", "version": "1.2.0", "description": "...", "keywords": ["weather"]}]} ``` `version` is the newest version that isn't yanked. `plum search` matches every word given against the name, description and keywords, ignoring case. ### Bundles: .plumpkg A bundle is one UTF-8 JSON object: ```json {"files":{"lib.plum":"...","plum.toml":"..."},"format":1,"name":"weather","version":"1.2.0"} ``` - **Byte for byte reproducible.** Every object's keys are in byte order, with no spaces; files are their text with `\r\n` made `\n`. The same source gives the same bytes, and so the same sha256, on every platform. - **Text only.** `.plum` files anywhere in the package, and `plum.toml`, `README.md` and `LICENSE*` at its top; each valid UTF-8. Directories starting with `.` (`.git`) and every other file are left out. - **At most 1 MB** (1,048,576 bytes) in all. - **Safe paths.** `/` between parts; each part letters, digits, `_`, `-` and `.`, not starting with `.` or `-` or ending with `.`; no `..`, absolute paths, backslashes, drive letters or device names (`CON`, `NUL`); at most 16 levels and 200 characters; no two paths that differ only in case. Installing checks, in order: the bundle's sha256 against the lock (E0920); its size, format, name and version (E0924); every path (E0921), all before writing anything; then the unpacked `plum.toml`. ## Publishing 1. Make the package: a `plum.toml` with a name, version, entry, and `repository = "https://github.com/OWNER/REPO"`. 2. `plum package` checks it: the manifest, `plum check` on every `.plum` file (installing its dependencies first), the file set and the size. It writes `NAME-VERSION.plumpkg` and prints its sha256. 3. Tag the release in your repository and push the tag. 4. `plum publish` (or `plum publish --tag TAG`; the default is `vVERSION`) runs the same checks and prints a link that opens a prefilled publish request on plumlang/registry: the package, the repository and the tag. Submit it while signed in to GitHub. A workflow in plumlang/registry checks out the tag, runs the latest released `plum package` on it, checks that the name is free (or that you own it) and that the version is new and higher than the last, then commits the bundle and the index, and replies on the issue. The bundle Orchard serves is the one it built, not one you uploaded. **Yanking.** An owner opens a "yank" issue on plumlang/registry. The version stays installable from lock files that already have it, but is never chosen again. Versions are never deleted or replaced. ## How it is built The commands are a Plumlang program built into `plum`, `src/stdlib/plum/plum_orchard.plum`, using `net.http`, `json`, `fs` and `hash`. What must be C is in `src/orchard/`: the TOML subset, the manifest and lock file, versions, ranges, names and paths, finding a package for `seed` (`packages.c`, used by the loader), and an internal module, `plum.pkg`, that gives the program those, plus `plum check`. Internal modules (`plum.*`) can be seeded only by modules built into `plum`. The tests are `tests/orchard.sh`, which builds an index from `tests/orchard/packages` and runs every command against it offline, and the unit tests in `tests/unit/test_orchard.c`. --- Source: https://plum.elixpo.com/docs/tools/lsp/ # The language server: `plum lsp` > plum lsp: errors as you type, hover, go to definition and completion in any editor. `plum lsp` is a [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) server built into the `plum` binary. An editor starts it and talks to it on standard input and output; there is nothing else to install. It checks files as `plum check` does, without compiling or running them. ``` plum lsp # the server, on standard input and output plum lsp --stdio # the same (some editors add the flag) ``` ## What it does | Capability | What you get | |---|---| | Diagnostics | Every error and warning `plum check` reports, with the same code (`E0402`, `W0502`, ...), message and place, on opening a file and on every change. A file you import that isn't open gets its own diagnostics too. | | Hover | The type of the name or expression under the cursor; the signature of functions, methods and standard-library functions, with their one-line documentation; a tree's, trait's or kind's header; a field's declaration. | | Go to definition | Local variables, parameters, loop names, functions, trees, traits, kinds and their cases, fields and methods (through the receiver's type, parents included), and names imported from other files: `seed ./shapes { Circle }`, `shapes.area`, and the `./shapes` of the `seed` itself. | | Completion | The names in scope at the cursor (locals, parameters, top-level names, imports, built-ins and keywords). After a `.`: a tree's fields and methods, the methods of `list`, `map`, `set`, `str`, `Json`, tasks, channels and sockets, a kind's cases, and the functions and constants of a standard module or the names a file module exports. | | Document symbols | The outline: functions, trees and traits with their fields and methods, kinds with their cases, top-level variables, constants and imports. | | Formatting | The whole file in `plum fmt`'s layout (spec 14.1). A file with syntax errors is left alone. | Details: - **Text sync** is the whole text on every change (`TextDocumentSyncKind.Full`). Each change is checked at once; a file of a few thousand lines takes milliseconds. - **Unsaved files.** When an open file imports another file that is also open, it sees the editor's text of it, saved or not. Changing a file checks again the open files that import it. - **Half-typed code.** Where `plum check` stops at the first file with errors, the server goes on, so names still resolve and hover and completion still work on a line you are in the middle of typing. A file whose names don't all resolve has no types, so completion after a dot then offers nothing for values, but still offers a module's members and a kind's cases. - **Positions** are in UTF-16 code units, the protocol's default. - **Robustness.** Malformed JSON, a message without `Content-Length`, unknown methods (answered with `MethodNotFound`, `-32601`) and requests before `initialize` are answered with an error, and the server carries on. It exits on `exit`, with 0 after a `shutdown` request and 1 without one, or when its input ends. ## Editors The server needs only the path of `plum`; with `plum` on your `PATH`, the command is `plum lsp`. Associate the `.plum` extension with a `plum` language. ### VS Code Install the **Plumlang** extension (from the Marketplace or Open VSX). It starts `plum lsp` itself. Settings: | Setting | Default | | |---|---|---| | `plum.path` | `plum` | the `plum` binary, if it isn't on `PATH` | | `plum.lsp.enabled` | `true` | turn the language server off (highlighting stays) | ### Neovim (0.11 and later, built-in LSP) ```lua vim.filetype.add({ extension = { plum = "plum" } }) vim.lsp.config("plum", { cmd = { "plum", "lsp" }, filetypes = { "plum" }, root_markers = { "plum.toml", ".git" }, }) vim.lsp.enable("plum") ``` On Neovim 0.10, start it from an autocommand instead: ```lua vim.api.nvim_create_autocmd("FileType", { pattern = "plum", callback = function(args) vim.lsp.start({ name = "plum", cmd = { "plum", "lsp" }, root_dir = vim.fs.root(args.buf, { "plum.toml", ".git" }), }) end, }) ``` Formatting on save: `vim.lsp.buf.format()` in a `BufWritePre` autocommand. ### Helix In `~/.config/helix/languages.toml`: ```toml [language-server.plum] command = "plum" args = ["lsp"] [[language]] name = "plum" scope = "source.plum" file-types = ["plum"] roots = ["plum.toml"] comment-token = "#" indent = { tab-width = 4, unit = " " } language-servers = ["plum"] auto-format = true ``` ### Zed In `settings.json`, until there is a Zed extension for Plumlang: ```json { "file_types": { "Plumlang": ["plum"] }, "lsp": { "plum": { "binary": { "path": "plum", "arguments": ["lsp"] } } }, "languages": { "Plumlang": { "language_servers": ["plum"], "format_on_save": "language_server" } } } ``` Zed attaches a language server to a language that an extension defines, so this needs a minimal language extension (a `config.toml` with `name = "Plumlang"`, `path_suffixes = ["plum"]`, `line_comments = ["# "]`) installed with *zed: install dev extension*. ### Emacs (eglot) ```elisp (define-derived-mode plum-mode prog-mode "Plum" (setq-local comment-start "# ")) (add-to-list 'auto-mode-alist '("\\.plum\\'" . plum-mode)) (with-eval-after-load 'eglot (add-to-list 'eglot-server-programs '(plum-mode "plum" "lsp"))) (add-hook 'plum-mode-hook #'eglot-ensure) ``` ### Any other editor Run `plum lsp` as the server command for `.plum` files, talking over stdio. No initialization options are needed. ## How it works The server lives in `src/lsp/`: `server.c` reads and writes messages and keeps the open files, `analysis.c` checks a file and answers questions about it, `json.c` and `text.c` are its JSON and its positions. A file is lexed, parsed, resolved and type-checked with the same code `plum check` uses, into the same diagnostics; the compiler and the VM are never involved. The resolver already links every name in the syntax tree to its symbol, which knows where it was declared, and the type checker gives every expression and symbol its type. So the server keeps no extra table while checking: it answers each request by walking the checked tree to the name or expression at the cursor. Checking for `plum run` costs exactly what it did before. Completion after a dot checks the file once more with a placeholder name after the dot, so the value before the dot has a type even while the line is incomplete. The tests are recorded sessions: `tests/lsp/*.in`, run by `tests/lsp.sh` and compared with `tests/lsp/*.out`. --- Source: https://plum.elixpo.com/docs/tools/repl/ # The REPL > Type Plumlang at a prompt and see each result at once. `plum` with no arguments, on a terminal, starts an interactive prompt: type Plumlang, press Enter, and it runs at once. `plum repl` does the same and also reads piped input. The rules are in [spec section 14.2](https://plum.elixpo.com/docs/language/running-programs/#142-the-interactive-prompt). ``` $ plum Plumlang 0.0.1. Type :help for help, :quit to leave. plum> plant x = 20 plum> x * 2 + 2 = 42 : int plum> branch greet(name: str) -> str { ... return "hello, {name}" ... } plum> greet("ada") = hello, ada : str plum> :type greet (str) -> str plum> seed math plum> math.sqrt(2.0) = 1.4142135623730951 : float plum> x // 0 :1: ZeroDivisionError: division by zero: 20 // 0 in
, line 1 plum> x = 20 : int plum> :quit ``` ## Entries An entry is a line, or several: it goes on to the next line (with the `...` prompt) while a bracket is open, a line ends with an operator, `,`, `=` or `=>`, or a `"""` string is open. Ctrl-C drops the entry being typed. - What an entry declares stays for the entries after it: variables, functions, trees, traits, kinds and `seed` imports. Declaring a name again hides the old one from then on. - An entry that is one expression prints its value, as `drop` would, and its type: `= [1, 2] : list[int]`. A `none` value prints nothing. - A compile error shows the usual diagnostic, pointing into the entry. A runtime error shows its message and where it happened. Either way the session goes on with what earlier entries made; the failed entry leaves nothing it declared behind. - `seed ./file` is relative to the directory `plum` was started in. A file is loaded and run once, by the first entry that imports it. - Tasks run while an entry runs. The entry ends when its own code does; tasks still running carry on while later entries run, so `plant t = spawn work()` in one entry and `t.wait()` in the next works. - `exit(n)` ends the session with exit code `n`. ## Commands | Command | | |---|---| | `:help` | The commands and keys. | | `:type expr` | The type of an expression, without running it. | | `:load file.plum` | Run a file's code as an entry; its declarations stay. | | `:reset` | Forget everything declared so far. | | `:quit`, `:q` | Leave (so do Ctrl-D on an empty line and `exit()`). | ## Keys | Key | | |---|---| | Left, Right (Ctrl-B, Ctrl-F) | Move the cursor. | | Home, End (Ctrl-A, Ctrl-E) | To the start or end of the line. | | Backspace, Delete | Delete before or under the cursor. | | Up, Down (Ctrl-P, Ctrl-N) | Earlier lines. | | Ctrl-U, Ctrl-K | Delete to the start or end of the line. | | Ctrl-W | Delete the word before the cursor. | | Ctrl-L | Clear the screen. | | Ctrl-C | Drop the entry being typed. | | Ctrl-D | Leave, on an empty line; otherwise delete under the cursor. | The history keeps the last 1000 lines in `.plum_history` in the home directory (`$HOME`, or `%USERPROFILE%` on Windows). Set `PLUM_HISTORY` to another file, or to nothing to keep no history file. The line editor is built in: raw mode through termios on Linux and macOS, the console's key events on Windows. Without a terminal (input from a pipe or a file), lines are read as they come, with no prompts, which is how the tests in `tests/repl/` drive it. Ctrl-C while an entry runs stops `plum`. --- Source: https://plum.elixpo.com/docs/tools/wasm/ # Plumlang in the browser > Run Plumlang in a web page with the WebAssembly build, as the playground does. `make wasm` builds `plum` for WebAssembly, so a web page can run Plumlang programs without a server: the playground at [plum.elixpo.com/playground](https://plum.elixpo.com/playground/) is built on it. This page is for anyone embedding it in a page of their own. ## Building ```sh make wasm # build/wasm/plum.js and build/wasm/plum.wasm ``` It uses Emscripten's `emcc` if it is on the `PATH`, or else the `emscripten/emsdk` image the Makefile pins (`EMSDK_IMAGE`), through Docker. Every release also carries the two files as `plum-X.Y.Z-wasm.tar.gz`, listed in `SHA256SUMS` with a build attestation like the other archives ([releasing.md](https://github.com/plumlang/plumlang/blob/main/docs/releasing.md)). | File | What | |---|---| | `plum.js` | An ES module (Emscripten's `MODULARIZE` and `EXPORT_ES6`) whose default export creates an instance. | | `plum.wasm` | The compiler, VM and standard library: about 480 KB, 190 KB gzipped. `plum.js` fetches it from the same folder. | Serve `plum.wasm` as `application/wasm` so the browser can compile it while it downloads. No other headers are needed: the build uses no threads, so no `Cross-Origin-Opener-Policy` / `-Embedder-Policy`. Nothing is bundled into it (no files, no preload), and memory starts at 32 MB and grows as needed up to 256 MB. ## The API ```js import createPlum from "./plum.js"; const plum = await createPlum(); const result = plum.run('drop("Hello, browser!")', { onStdout: (text) => output.append(text), // as the program writes it onStderr: (text) => output.append(text), }); // result: { exitCode: 0, stdout: "Hello, browser!\n", stderr: "" } plum.check('plant x: int = "a"\n'); // [{ severity: "error", code: "E0402", message: "expected int, found str", // line: 1, column: 16, endLine: 1, endColumn: 19 }] plum.format("plant x=1\n"); // { ok: true, text: "plant x = 1\n" } // or, with syntax errors: { ok: false, diagnostics: [...] } plum.version; // the version of plum, such as "0.1.0" ``` **`run(source, options?)`** checks, compiles and runs a program, as `plum run main.plum` does, and returns `{ exitCode, stdout, stderr }`. Compile errors and runtime errors go to standard error exactly as the command line prints them (without colours), naming the program `main.plum`. Output reaches `onStdout` and `onStderr` as it is written, a line at a time (or when the program flushes). The options: | Option | Default | What | |---|---|---| | `onStdout`, `onStderr` | none | `(text) => void`, called as output is written. | | `maxSteps` | 50,000,000 | Calls and backward jumps (loops) before the program is stopped: about a second of work. | | `maxMemory` | 64 MB | Bytes of values in use before the program is stopped. | | `maxSleep` | 5 | Seconds the program may spend waiting in `time.sleep`; `false` refuses sleeping. | **`check(source)`** returns the diagnostics of `plum check` as an array in source order. Lines and columns count from 1, and columns count UTF-16 code units, as JavaScript strings do, so they index the editor's text directly. `severity` is `"error"` or `"warning"`; `code` is documented in [errors.md](https://plum.elixpo.com/docs/errors/). **`format(source)`** returns the text `plum fmt` would write, or the syntax errors that stop it. Each call is synchronous. An instance can run any number of programs one after another; nothing carries over between runs. If a call throws (plum itself failed, which a program should never cause), the instance is marked `plum.broken` and further calls throw: create a new one. ## What a program can do Every run is **sandboxed**: the functions that reach outside the page throw an `IOError` ("isn't allowed in this run (sandbox)"): the `fs` module, the network (`net`, `net.http`), and `os.run`. There are no other files, so `seed ./file` and packages report that they can't be found. TLS is not built in at all (a `NetError` says so). Everything else works as it does natively: trees, traits, errors, the standard library's modules that stay inside the program (`math`, `json`, `hash`, `io`, and `time`'s clocks and dates), and **tasks and channels**, which run on the VM's own scheduler. `os.platform()` returns `"wasm"`. **Input**: standard input is always at its end, so `ask()` and `io.read_line()` return none and `io.read_all()` an empty string. **Limits**: an endless loop stops at the step limit with `main.plum: Error: stopped after 50000000 steps, the limit of this run` and exit code 1, instead of freezing the page; a runaway list stops at the memory limit the same way. **Sleeping**: `time.sleep` works, up to `maxSleep` seconds of waiting in all over a run. Tasks asleep at the same time wait together (a thousand tasks each sleeping 0.1 s cost 0.1 s), and a sleep that would go past the limit stops the program with a message. The build has no Asyncify, which would make every call asynchronous and the module much larger: a sleep waits on the clock instead, so the thread is busy while it waits. That is why the playground runs plum in a **Web Worker**, which is what we recommend for any page: ```js // worker.js import createPlum from "./plum.js"; const ready = createPlum(); // load once; messages wait for it self.onmessage = async ({ data: { id, source } }) => { const plum = await ready; const result = plum.run(source, { onStdout: (text) => self.postMessage({ id, stream: "stdout", text }), onStderr: (text) => self.postMessage({ id, stream: "stderr", text }), }); self.postMessage({ id, done: true, exitCode: result.exitCode }); }; // the page const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" }); ``` The page stays responsive while a program runs, output arrives as it is printed, and a Stop button can simply `worker.terminate()` and start a new worker. ## How it is built The C sources are the same as the native build's. The pieces that differ: | File | What | |---|---| | `src/wasm/playground.c` | Run, check and format a program held in memory, with the sandbox and limits. Plain C, built into every `plum` and unit-tested natively. | | `src/wasm/bindings.c` | The exports to JavaScript, and the streams that send output to it (Emscripten only). | | `src/wasm/api.js` | The JavaScript API above, added to the module with `--post-js`. | | `src/stdlib/platform.c` | No sockets to poll; sleeping waits on the clock. | | `src/stdlib/net.c` | Socket calls fail as with no network, which keeps Emscripten's socket and file-system emulation out of the build. | | `src/stdlib/tls.c` | `PLUM_NO_TLS`: TLS calls fail with a reason. Mbed TLS's crypto stays, for `hash`. | `tests/wasm.sh` (part of `make test` when a wasm build and Node are there) runs the examples, the blocks of [reference.md](https://plum.elixpo.com/docs/reference/) and the golden tests that need no files or network in one instance under Node, and checks that each prints exactly what native `plum run` prints; it also checks that an endless loop stops and that the sandbox holds. --- Source: https://plum.elixpo.com/docs/errors/ # Error codes > Every compiler error code, with an example that causes it and the fix. Every compile error has a code, shown as `error[E0201]`. This page explains each one, with an example that causes it and the fix. | Range | Stage | |---|---| | E01xx | Reading the source text (lexer) | | E02xx | Syntax (parser) | | E03xx | Names | | E04xx | Types | | E05xx | Control flow | | W05xx | Control-flow warnings (the program still runs) | | E06xx | Compiling to bytecode | | E09xx | Packages: `plum.toml`, `plum.lock`, seeding packages and the `plum add` family ([orchard.md](https://plum.elixpo.com/docs/tools/orchard/)) | Codes never change meaning. A retired code is marked retired, not reused. `make test` checks that every code in the compiler is documented here and that every code documented here is still used. ## Characters ### E0101 The file contains bytes that are not valid UTF-8. Plumlang source files must be UTF-8; save the file with UTF-8 encoding in your editor. ### E0102 A character that has no meaning in Plumlang, such as `@` or `$`, outside a string or comment. ```plum plant price = $5 # error plant price = 5 # fix ``` ### E0103 An operator from another language. Plumlang spells logic with words and has no increment operators. ```plum if a && !b { } # error if a and not b { } # fix count++ # error count += 1 # fix ``` ### E0104 A semicolon. A statement ends at the end of its line. ```plum plant x = 1; # error plant x = 1 # fix ``` ### E0105 A single-quoted string. Strings use double quotes. ```plum plant name = 'Ada' # error plant name = "Ada" # fix ``` ## Numbers ### E0110 A `_` that is not between two digits. `_` only separates digits. ```plum plant n = 1_ # error plant n = 1__000 # error plant n = 1_000 # fix ``` ### E0111 A digit that does not exist in the number's base. ```plum plant b = 0b102 # error: binary has only 0 and 1 plant b = 0b101 # fix ``` ### E0112 A letter straight after a number. ```plum plant n = 12abc # error plant n = 12 # fix ``` ### E0113 `0x`, `0o` or `0b` with no digits after it. ```plum plant mask = 0x # error plant mask = 0xFF # fix ``` ### E0114 An exponent with no digits. ```plum plant big = 1e # error plant big = 1e9 # fix ``` ### E0115 A number that starts with `0`. In some languages that means octal, so Plumlang asks you to say which you meant. ```plum plant mode = 0755 # error plant mode = 755 # fix, decimal plant mode = 0o755 # fix, octal ``` ### E0116 An integer larger than the largest `int`, 9223372036854775807. ### E0117 A float too large to represent, such as `1e999`. ## Strings ### E0120 A string with no closing quote. A `"` string must end on the line it starts on; use `"""` for text over several lines. ```plum drop("Hello) # error drop("Hello") # fix ``` ### E0121 An escape that doesn't exist. The escapes are `\n` `\t` `\r` `\0` `\\` `\"` `\{` `\}` and `\u{...}`. ```plum drop("a\qb") # error drop("a\\qb") # fix: a literal backslash ``` ### E0122 `\u` without braces. ```plum drop("A") # error drop("\u{41}") # fix ``` ### E0123 `\u{...}` with no digits, a non-hexadecimal digit, or more than six digits. ### E0124 `\u{...}` with a number that is not a Unicode character: above `10FFFF`, or a surrogate (`D800` to `DFFF`). ### E0125 A `}` in a string. Braces start and end interpolation, so a literal one is written `\}`. ```plum drop("a } b") # error drop("a \} b") # fix ``` ### E0126 In a `"""` string, a line indented less than the closing `"""`. That indentation is removed from every line, so no line may have less. ```plum plant s = """ first second # error: indented less than the closing """ """ ``` ### E0127 An interpolation with `:` but no format after it. ```plum drop("{price:}") # error drop("{price:.2}") # fix ``` ## Brackets ### E0130 A `(`, `[` or `{` that is never closed. When the next line starts a new statement, the error points at the open bracket. ```plum drop((1 + 2) # error: the first ( is never closed drop((1 + 2)) # fix ``` ### E0131 A closing bracket of the wrong kind. ```plum plant xs = [1, 2) # error plant xs = [1, 2] # fix ``` ### E0132 A closing bracket with nothing to close. ```plum plant y = 3] # error plant y = 3 # fix ``` ## Syntax ### E0201 Something other than what the grammar allows here. The message says what was expected and what was found. ```plum f(x, , y) # error: expected an expression, found ',' ``` ### E0202 Chained comparisons. `a < b < c` does not mean what it does in maths. ```plum if 0 < x < 10 { } # error if 0 < x and x < 10 { } # fix ``` ### E0203 Chained ranges, such as `0..1..2`. ### E0204 `{}` in a value. It could be an empty block or an empty map, so the empty map is written `{:}`. ```plum plant ages: map[str, int] = {} # error plant ages: map[str, int] = {:} # fix ``` ### E0205 An `if` used as a value without `else`. A value needs a result either way. ```plum plant label = if n == 1 { "item" } # error plant label = if n == 1 { "item" } else { "items" } # fix ``` ### E0206 `spawn` with something other than a function call. ```plum spawn worker # error spawn worker() # fix ``` ### E0207 A positional argument after a named one. ```plum connect(secure: good, "example.com") # error connect("example.com", secure: good) # fix ``` ### E0208 A type made optional twice, such as `int??`. One `?` is enough. ### E0209 An assignment whose left side cannot be assigned: only a variable, a field or a list or map element can. ```plum 5 = x # error f() += 1 # error a?.b = 3 # error: assign through a known object instead ``` ### E0210 A `plant` or `root` without a value. ```plum plant count # error plant count = 0 # fix ``` ### E0211 A parameter without a default after one with a default. ```plum branch f(a: int = 1, b: int) { } # error branch f(b: int, a: int = 1) { } # fix ``` ### E0212 A `try` block with neither `catch` nor `finally`. ### E0213 A field written with `plant` or `root` inside a tree. ```plum tree Point { plant x = 0 # error x: int = 0 # fix } ``` ### E0214 A `kind` with no cases. ### E0215 A `seed` after other statements. Imports go at the top of the file. ### E0216 A `{` at the start of a statement. Plumlang has no free-standing blocks; for an empty map write `plant m = {:}`. ### E0217 A keyword used as a field's name, like `kind: Kind` or `match: str`. Keywords can't name anything; pick another name (`kind_`, `shape_kind`). ### E0218 Code nested more than 1000 deep: brackets inside brackets, blocks inside blocks, or a chain of more than 1000 operators (`a + b + c + ...`, each operator counting one). Every stage of the compiler walks the program recursively, and the limit keeps that safe. Code written by hand never comes near it; generated code can. Split the expression with variables, or the code into functions. ```plum plant total = a1 + a2 + ... + a2000 # error plant first = a1 + a2 + ... + a1000 # fix plant total = first + a1001 + ... + a2000 ``` ### E0219 A function, method, lambda, kind case or function type with more than 255 parameters. Pass the values in a list, a map or a tree instead. ## Names ### E0301 A name that isn't declared anywhere visible. If it is close to a name that exists, the message suggests it; names from other languages get the Plumlang word. ```plum plant score = 10 drop(scroe) # error: did you mean 'score'? print("hi") # error: Plumlang prints with drop(...) ``` ### E0302 The same name declared twice in one scope. An inner block may reuse an outer name, but a function's body shares its parameters' scope. ```plum branch greet(name: str) { plant name = "x" # error: already declared, as a parameter } ``` ### E0303 A module variable used before the line that declares it. Functions, trees, traits and kinds can be used anywhere in the file; variables only after their `plant` or `root` line (inside a function body, any module variable is visible, since the body runs later). ```plum drop(total) # error plant total = 5 ``` ### E0304 A change to something that can't change: a `root` constant, a parameter, a loop variable, a function or a type. ```plum root MAX = 100 MAX = 200 # error: declare it with 'plant' to change it ``` ### E0305 A type that doesn't exist, or a name used as a type that isn't one. ```plum plant s: Strng = "" # error: did you mean 'str'? plant b: boolean = good # error: in Plumlang it is 'bool' ``` ### E0306 `self` or `super` outside a method of a tree. ### E0307 `return` outside a function. ### E0308 A `seed` of a module that doesn't exist: a standard module name that isn't one (the message lists them; `plum stdlib` shows their functions), or a file that can't be read (`seed ./shapes` looks for `shapes.plum` next to the importing file). ### E0309 Something in a `match` pattern that can't be one. A pattern is a literal, a range, a kind case (with names to bind its values), a `root` constant, or `_`. A bare name doesn't match anything: use `else`. ```plum match light { Red => stop() other => go() # error else => go() # fix } ``` ### E0310 A `tree`, `trait` or `kind` declared inside a function. Declare it at the top of the file. ### E0311 Modules that import each other in a circle: `a` imports `b`, which imports `a` (perhaps through others). The message shows the whole circle. Move what both need into a module of its own that both import. ## Types ### E0401 A value that is computed and then thrown away. A line on its own must do something: call a function, assign, declare. ```plum total + 1 # error: the sum goes nowhere total += 1 # fix x == 5 # error: did you mean '='? ``` ### E0402 A value of the wrong type. The only automatic conversion is int to float; everything else is written: `int(x)`, `float(x)`, `str(x)`. ```plum plant count: int = "5" # error plant count: int = int("5") # fix plant n = 5 n /= 2 # error: '/=' makes a float; use '//=' ``` ### E0403 An operator used on values it doesn't work on: adding text and a number, comparing values that are never equal, bitwise operators on floats. On objects, an operator needs its method in the object's tree (`plus` for `+`, `compare` for `<`, ... spec 8.5), taking the value on the right. ```plum drop("total: " + 5) # error drop("total: {5}") # fix: interpolation ``` ### E0404 A condition that isn't a bool. Plumlang has no "truthiness": write the comparison you mean. ```plum if count { } # error if count > 0 { } # fix ``` ### E0405 A call of something that isn't a function: a number, a trait, a kind. ### E0406 The wrong number of arguments, or a required argument left out. ```plum branch add(a: int, b: int) -> int => a + b add(1) # error: missing 'b' ``` ### E0407 A named argument the function doesn't have, or an argument given twice. ### E0408 A value that may be `none` used as if it were always there. Give a default with `??`, call through it with `?.`, or check it with `if plant`. ```plum plant nickname: str? = ask("Nickname? ") drop(nickname.upper()) # error drop(nickname?.upper() ?? "none") # fix if plant n = nickname { drop(n) } # fix ``` ### E0409 A type the checker can't work out: `none`, `[]` or `{:}` with nothing to say what they hold. Write the type. ```plum plant names = [] # error plant names: list[str] = [] # fix ``` ### E0410 Indexing with the wrong type of index, or indexing something that can't be indexed. ### E0411 A `return` that doesn't fit its function: a value from a function with no `->` result, or no value from one that has it. ### E0412 A `for` loop over something that isn't a range, list, set, map, string or channel; or two loop names over something other than a map. ```plum for i, x in items { } # error for i, x in items.enumerate() { } # fix ``` ### E0413 Throwing or catching something that isn't an error. Errors are trees that extend `Error` (or one of the built-in error trees). ```plum throw "failed" # error throw ValueError("failed") # fix ``` ### E0414 A type with the wrong number of type arguments: `list` needs one (`list[int]`), `map` two (`map[str, int]`), `int` none. ### E0418 A range (`0..5`) used as a value. A range is written where it is used: in a `for` loop, a slice, after `in`, or as a `match` pattern. ```plum plant r = 0..5 # error for i in 0..5 { } # fix ``` ### E0415 A field, method or kind case that doesn't exist. ### E0416 A conversion that isn't allowed: `bool(x)` (write the comparison), `as` between non-numbers (use `int(...)`, `str(...)`), or converting a value that can't be converted. ### E0417 A `match` pattern that can't match the value: a case of another kind, a literal of another type, or a case pattern naming the wrong number of values. ### E0420 A tree names a trait but doesn't have one of the trait's methods (and the trait gives no default). Add the method with the trait's parameters and result. ### E0421 A method that overrides a parent's method, or provides a trait's, with different parameters or a different result. Code that calls it through the parent or the trait passes what that declaration says, so the types must be the same. ```plum tree Animal { branch speak() -> str => "..." } tree Dog : Animal { branch speak(loud: bool) -> str => "woof" } # E0421 ``` ### E0422 A field without a default that nothing sets. A tree with `init` must set each such field at the start of `init` (`self.name = name`), before anything else uses `self`; a tree that adds such a field needs its own `init` if its parent has one. ```plum tree Point { x: float y: float branch init(r: float) { self.x = r drop(self) # E0422: self.y isn't set yet } } ``` ### E0423 A field or method whose name starts with `_` used outside its tree's methods (or those of trees extending it). The underscore makes it private. ### E0424 A method the language calls itself, written with the wrong shape: `to_str() -> str` (for printing), `equals(other: ) -> bool` (for `==`), `compare(other: ) -> int` (for `<`, `<=`, `>`, `>=` and sorting), the operator methods `plus`, `minus` (`+`, `-`), `times`, `divided_by` (`*`, `/`) taking `` (`times` and `divided_by` may take an `int` or `float` instead) and returning ``, `negate() -> ` (unary `-`), and `init(...)` with no result. `` means the tree, a tree it extends or a trait it has. ```plum tree Money { cents: int branch plus(other: int) -> Money => Money(self.cents + other) # E0424 } ``` Write `plus(other: Money) -> Money`; to add a number, give the tree another method (`add_cents(n: int)`) and call it by name. ### E0425 `weak` on a field whose type isn't an optional tree or trait. A weak reference reads as `none` once its object is freed, so its type must be optional, like `parent: weak Node? = none`; numbers, strings and collections are values and can't be weak. ### E0426 A tree object given to `spawn`, as an argument or as the object whose method the task would run (also inside a list or map). Tasks don't share objects (spec 12.3): give the task the plain values it needs, and send results back through a `Channel`. ### E0427 A tree or trait that extends itself, directly or through the trees and traits it extends. Break the circle. ```plum tree A : B {} # error: A extends B, which extends A tree B : A {} ``` ### E0428 A tree or trait that extends trees and traits more than 32 deep (counting itself). Make the hierarchy flatter: hold a value instead of extending its tree, or merge levels. ### E0429 A tree with more than 255 fields, counting the fields of the trees it extends. Its constructor would take more arguments than a call can pass; group related fields into a tree of their own. ## Control flow ### E0501 A function with a result (`-> type`) that can finish without returning one. Every path must end in `return` (or `throw`). ```plum branch sign(n: int) -> str { if n > 0 { return "positive" } if n < 0 { return "negative" } } # error: no return when n is 0 ``` Add `return "zero"` at the end, or make the last `if` an `if ... else`. ### E0502 `break` or `continue` outside a loop. A lambda is a new function, so a `break` inside one doesn't reach a loop around it. ### E0503 A `match` that doesn't cover every possible value (spec 5.3): a kind case left out, a bool match without both `good` and `bad`, or a match on a number or string without an `else` arm. ```plum kind Light { Red, Yellow, Green } match light { Red => stop() Green => go() } # error: doesn't cover 'Yellow' ``` ## Warnings ### W0501 Code after a `return`, `throw`, `break` or `continue` that can never run. ### W0502 A variable that is declared but never used. Remove it, or start its name with `_` to say it is unused on purpose. ## Compiling ### E0601 A feature the compiler can't turn into bytecode yet. The program is correct (`plum check` accepts it), but it can't run until the feature is built; the roadmap is issue #36. Today that is mostly using a function of a module, a method or a kind case as a value: wrap it in a lambda, like `plant f = (x: float) => math.sqrt(x)`. ### E0602 A limit of the bytecode format: a function with more than 65,535 constants or local variables, or a block or loop too long to jump over. Split the function into smaller ones. ## Packages Errors in `plum.toml` and `plum.lock` are shown like compile errors, at their line and column. They stop `plum run` of a package directory, every `seed` of a package, and the package commands. See [orchard.md](https://plum.elixpo.com/docs/tools/orchard/). ### E0901 `plum.toml` or `plum.lock` isn't in the TOML that Plumlang reads: a small, strict part of TOML with `[tables]`, `key = "strings"`, `'literal strings'`, lists of strings and `#` comments. Numbers, booleans, inline tables, `[[arrays of tables]]`, dotted keys and multi-line strings are not accepted; write every value as a string. ```toml version = 1.0 # error version = "1.0.0" # fix ``` ### E0902 A key set twice in one table, a `[table]` declared twice, or a name used both as a key and as a table. Keep one. ### E0903 A table or key `plum.toml` doesn't have, usually a misspelling. The tables are `[package]` and `[dependencies]`; the keys of `[package]` are `name`, `version`, `entry`, `lib`, `description`, `license`, `authors`, `repository`, `keywords` and `plum`. ### E0904 A field that is missing or of the wrong shape: `[package]` needs `name`, `version` and `entry`; `authors` and `keywords` are lists of strings, the others strings. A description has at most 300 bytes, and a package at most 10 keywords of 1 to 30 lowercase letters, digits and `-`. ### E0905 A package name that can't be used, as the package's own name or a dependency's: a name has 2 to 40 lowercase letters, digits and single `-`, starts with a letter, and doesn't end with `-`. It can't be a standard module's name (`json`, `net`, `hash`...), `plum`, `std`, `stdlib` or `orchard`, or a keyword once its `-` become `_`. A package can't depend on itself. ### E0906 A version that isn't three numbers, `MAJOR.MINOR.PATCH`, like `"1.4.0"`. Numbers have no leading zeros; pre-release labels (`1.0.0-beta`) aren't supported. ### E0907 A version range that isn't one of `^1.2` (compatible: the same left-most non-zero number), `~1.2.3` (the same minor version), `=1.2.3` (exactly), `>=1.2` (at least) or `*` (any). A bare version, `"1.2"`, means `^1.2`. ### E0908 A `seed` of a package the module's `plum.toml` doesn't list in `[dependencies]`. Standard modules come first; any other name is a package, and only declared ones can be seeded. Add it with `plum add NAME`. Inside an installed package, the package's own `plum.toml` must list it. (A file with no `plum.toml` above it gets E0308 instead.) In `plum remove`, the package isn't a dependency. ```plum seed weather # error: run `plum add weather` first ``` ### E0909 A `seed` of a declared package that isn't installed: there is no `plum.lock`, the lock doesn't list it, or the cache doesn't hold the version it names (or holds a damaged copy). Run `plum install`. ### E0910 A `plum.lock` that `plum` didn't write: every table is `[packages.NAME]` with a `version`, a `sha256` of 64 lowercase hex digits, and `dependencies`, a list of names. Delete it and run `plum install` to write it again. ### E0911 An `entry` or `lib` that doesn't name a `.plum` file inside the package: a relative path with `/` between its parts, without `..`, a drive letter or a part starting with `.`. ### E0920 `plum install` or `plum add` downloaded a bundle whose sha256 isn't the one `plum.lock` (or the index) records. Nothing is unpacked. The bundle changed after it was locked, or the download was tampered with. If the package was legitimately republished, remove it from `plum.lock` and run `plum install`. ### E0921 A bundle holds a path that could write outside its package: `..`, an absolute path, a drive letter, a backslash, a part starting with `.`, a device name like `NUL`, a file a package doesn't hold, or two names that differ only in case. The whole bundle is refused before anything is written. Report the package to the registry. ### E0922 No version of a package satisfies every requirement: the message names each package that asks for it, with its range (`paint 1.0.0 requires colors ^1.0, brush 1.0.0 requires colors ^2.0`), and says when a yanked version would have fit. Change a range so they overlap. ### E0923 Orchard has no such package or bundle, `PLUM_ORCHARD` isn't an `https://`, `http://` or `file://` URL, or the server answered with an error. `plum search` finds the right name. ### E0924 A file from Orchard isn't what it should be: an index or `search.json` that isn't valid, or a bundle that isn't JSON, is over 1 MB, has a format this `plum` doesn't know, holds non-text files, or holds another package's `plum.toml`. ### E0925 `plum package` (or `plum publish`) refused the package: a file of it has compile errors (`plum check` runs on every `.plum` file), isn't UTF-8 text, has a name a package can't hold, the bundle is over 1 MB, `entry` or `lib` isn't among its files, or (to publish) `repository` isn't a `https://github.com/OWNER/REPO` URL.