plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


5d38480 — Peter John 2026-11-11T07:26:53+05:30
Plans: the compile-time layer review plan the backlog points at
docs/plans/2026-11-09-comptime-generics.review.md ADDED
@@ -0,0 +1,116 @@
1
+ # Compile-time built-ins, generics and a faster game engine: review plan
2
+
3
+ Branch: built on `superlite/sessions/comptime-generics` (forked from `simpler-language`), merged back into `simpler-language` only with your yes. Not ported to `master`.
4
+
5
+ ## Summary
6
+ Plum has one compile-time built-in today, `@typeName`. This plan gives it a Zig-style compile-time layer: ask a type what it has (`@hasMethod`, `@fields`), loop over a struct's fields while compiling, branch on that with the dead branch removed, raise your own compile errors, bake files into the program, fold constants and run pure functions while compiling, and pass numbers and types as compile-time values. Generics move to `<>`, infer more, and get faster: no allocation for `Option` of a reference, and trait calls that jump straight to the method instead of testing every kind in turn. The game engine then uses all of it: the scene tree skips actors that did not change, makes fewer calls per actor, stores children in a flat chunked vector, and gets replay checksums, snapshots and tweening written once in std by reflection rather than by hand per struct.
7
+
8
+ ## What you will get
9
+ - **Reflection:** `@hasMethod(T, "draw")`, `@hasField(T, "x")`, `@fields(T)` (name and type of each field), `@field(value, name)` to read a field by a compile-time name, and `comptime for f := range @fields(T)` unrolled per type.
10
+ - **Compile-time branching:** `comptime if @hasMethod(T, "draw") { .. }`: the branch that does not hold is never type-checked or emitted, so generic code can use methods only some types have.
11
+ - **`@compileError("msg")`:** a custom error from a generic or a branch that should never be reached, with the usual "in f<T> (called at ..)" chain.
12
+ - **`@embedFile("art/ship.png")`:** the file's bytes as a constant `Buffer` inside the wasm, with the path relative to the source file. Games ship as one wasm with their assets.
13
+ - **`@src()`:** file, line and column of the call, used by `assert` and the test runner.
14
+ - **Const eval:** top-level and type constants are computed while compiling (arithmetic, strings, structs, lists, maps) and stored as data, not recomputed at each use. `comptime fun` marks a pure function (no `Io`) that may run while compiling, e.g. a sine table or a level layout. `comptime expr` forces a value to be computed while compiling.
15
+ - **Types as values:** value generics (`struct Grid<W: Int, H: Int>`, with `W` usable as a constant), type aliases (`type Board = Grid<8, 8>`), and `comptime fun Storage<T>() -> type` that picks a type by conditions while compiling.
16
+ - **`<>` generics, traits in `[]`:** `struct Ship<M>[Actor<M>, Clickable](..)` replaces `is Actor[M], Clickable`; `struct Ship<M>`, `fun map<B>(..)`, `stage.findAs<Orb>(id)`, `Option<Int>`, rewritten across std, examples, tests, docs and the grammar in one step.
17
+ - **Better inference:** a type parameter left open is inferred from later uses of the value, else a clear error ("can't work out T for findAs; write findAs<Orb>(..)") instead of silently becoming `Unit`. Default type parameters: `struct Store<S, M = Unit>`.
18
+ - **Generic speed:** `Option` of a reference is a nullable reference, so `Some` allocates nothing. `for` loops over iterators stop allocating a `Some` per step. Trait calls go through a type number and one jump table, at the same cost for 2 kinds or 50. Closure specialisation handles more shapes (closures with `return`, more than 8 copies when they are small).
19
+ - **Engine:** the scene step keeps a node untouched when its actor and children did not change; drops the extra `gone` check and caches `key`/`place` per node; holds children in a 32-way chunked vector (a loop, no 10k-deep recursion); std derives `hash`, `eq`, `toStr`, `lerp` and JSON for any struct by reflection; `Replay` records a state checksum per tick and can snapshot and rewind; `Anim` gains easing and `lerp` tweens.
20
+ - **Proof:** the scene tree benchmark gains a "mostly static" workload, and before/after numbers go in a results doc.
21
+
22
+ ## What will be built
23
+ | Part | What it does | Size | Built by |
24
+ |---|---|---|---|
25
+ | `<>` syntax | Grammar, parser, type printing and every generic in std, examples, tests, docs move to `<>` | L | a careful helper |
26
+ | Compile-time core | Evaluates built-ins per generic copy, folds `comptime if`, adds `@compileError`, `@src` | L | a careful helper |
27
+ | Reflection | `@hasMethod`, `@hasField`, `@fields`, `@field`, unrolled `comptime for` | L | a careful helper |
28
+ | Embedded files | `@embedFile` reads the file and stores it as a wasm data segment | S | a fast helper |
29
+ | Compile-time evaluator | Runs pure Plum while compiling, for constants and `comptime fun` | L | a careful helper |
30
+ | Constants as data | Folded constants stored once as wasm data or globals | M | a careful helper |
31
+ | Types as values | Value generics, type aliases, `comptime fun .. -> type` | L | a careful helper |
32
+ | Inference | Open parameters inferred from later uses or reported; default type parameters | M | a careful helper |
33
+ | Nullable Option | `Option` of a reference stored as a nullable reference; allocation-free `for` loops | M | a careful helper |
34
+ | Trait jump table | One type number per implementer, a jump table per trait call | M | a careful helper |
35
+ | Closure specialisation | Accepts `return` in closures; lifts the 8-copy cap for small closures | M | a careful helper |
36
+ | Scene tree speed | Skip unchanged nodes, fewer calls per actor, cached `key`/`place` | M | a careful helper |
37
+ | Chunked children | 32-way persistent vector replacing the sibling chain | M | a careful helper |
38
+ | Derives in std | `hash`, `eq`, `toStr`, `lerp`, JSON written once with reflection | M | a careful helper |
39
+ | Replay and tweens | Per-tick checksums, snapshot and rewind; easing and `lerp` in `Anim` | M | a careful helper |
40
+ | Benchmark and docs | "Mostly static" workload, before/after numbers, language and game docs | M | a fast helper |
41
+
42
+ ## How it fits together
43
+ ```mermaid
44
+ flowchart LR
45
+ S["Source with <> generics"] --> P[Parser]
46
+ P --> C[Type checker]
47
+ C --> G["Generic copies, one per type"]
48
+ G --> CT["Compile-time core: built-ins, comptime if, comptime for"]
49
+ CT --> EV["Compile-time evaluator: constants, comptime fun, type fns"]
50
+ EV --> W[Wasm code generator]
51
+ W --> OPT["Nullable Option, trait jump table"]
52
+ OPT --> OUT[One wasm file]
53
+ STD["std: derives, Replay, Anim"] --> P
54
+ ENG["Scene tree: skip unchanged, chunked children"] --> P
55
+ ```
56
+
57
+ ## How it gets built
58
+ ```mermaid
59
+ flowchart TB
60
+ W1["Wave 1, alone: <> syntax across everything"]
61
+ subgraph W2["Wave 2, in parallel"]
62
+ A[Compile-time core]
63
+ B[Embedded files]
64
+ C[Inference]
65
+ D[Nullable Option]
66
+ E[Trait jump table]
67
+ F[Scene tree speed and chunked children]
68
+ end
69
+ subgraph W3["Wave 3, in parallel"]
70
+ G[Reflection]
71
+ H[Evaluator and constants]
72
+ I[Closure specialisation]
73
+ end
74
+ subgraph W4["Wave 4, in parallel"]
75
+ J[Types as values]
76
+ K[Derives, Replay, tweens]
77
+ end
78
+ W1 --> W2 --> W3 --> W4 --> R["Benchmark, docs, final review"]
79
+ ```
80
+ The `<>` rewrite goes first and alone because it touches nearly every file; anything built in parallel with it would conflict. Each task runs the full `test-all.sh` before its commit.
81
+
82
+ ## Decisions you can change
83
+ - Trait list on a type: DECIDED (user 2026-11-10): `struct Ship<M>[Actor<M>, Clickable](x: Float, y: Float)`; `<>` for type parameters, `[]` for the trait list, `()` for fields. The `is` clause is removed in the same rewrite. Rejected: `struct Ship[M](Actor[M], Clickable)(..)` (two paren lists side by side) and keeping `is`.
84
+ - Compile-time loop and branch keywords: `comptime for` / `comptime if` (default, as Zig) | `inline for` / `static if`.
85
+ - Compile-time evaluator: a small interpreter inside the compiler for pure Plum (default; fast, works with no engine) | compile the expression to wasm and run it while compiling (full language, slower builds).
86
+ - What `comptime fun .. -> type` can return: an existing or generic type picked by conditions (default) | also new struct types built field by field, Zig-style (much larger: the checker would see types appear while it runs).
87
+ - Trait calls: type number plus jump table (default) | a per-type method table called indirectly.
88
+ - `@embedFile` limit: 16 MB per file (default) | none.
89
+ - Open type parameter: infer from later uses, else error (default) | always error, asking for `<..>`.
90
+ - Derives: opt-in per struct with `is Hash, Eq, Show` (default) | every struct gets them automatically.
91
+
92
+ ## Risks
93
+ - **`<>` against less-than:** `a < b > (c)` could read as a call. The rule: `name<..>` is type arguments only when the closing `>` is followed by `(`, `.` or `)`, as C# and Kotlin do, and `>>` is split in nested types. Grammar tests cover the cases that could be read either way.
94
+ - **Per-copy evaluation:** today codegen compiles each generic copy from the one shared body. `comptime if/for` makes copies differ, so each copy needs its own expanded body. The checker builds it and codegen reads it, with a test that two copies of the same function emit different code.
95
+ - **Evaluator drift:** the compile-time interpreter could disagree with compiled wasm. Every evaluator test also runs the same code compiled and compares the results.
96
+ - **Nullable Option:** `Option<Option<Ship>>` cannot use null twice; nested options keep the boxed layout. Tests cover it.
97
+ - **Fusion and FBIP passes** run before generic copies exist, so they see `comptime if` unfolded. They must leave it alone; checked with `--no-fusion` and `--no-fbip` in every test run.
98
+ - **Scope:** about 16 parts. If one part stalls, the waves after it still land in order; the final review lists anything left.
99
+
100
+ ## Out of scope
101
+ - Porting any of this to `master` or the self-hosting compiler.
102
+ - Pointer and memory built-ins (`@sizeOf`, `@ptrCast`, `@alignOf`): Plum is garbage-collected wasm, where they mean nothing.
103
+ - A new renderer, actor keys, or other backlog engine items not listed above.
104
+ - Pushing or merging to `simpler-language` without your yes.
105
+
106
+ ## How we will know it works
107
+ - `compiler/scripts/test-all.sh` ends with `ALL PASSED` after every wave, including the `--no-fbip` and `--no-fusion` runs.
108
+ - A generic `describe<T>(x: T)` prints every field of three different structs, uses `draw` only where `@hasMethod` says so, and a wrong use gives your `@compileError` text.
109
+ - A game loads a sprite through `@embedFile` and runs in the browser from one wasm.
110
+ - A `comptime` sine table of 256 entries is in the wasm as data, and no code computes it at start.
111
+ - `findAs<Orb>(id)` with the type argument left out is either inferred or an error naming `T`, never `Unit`.
112
+ - The scene tree benchmark: for-loop and trait-dispatch microbenchmarks and the new "mostly static" workload are faster than today, and no other workload is more than 5% slower. Checksums match.
113
+ - `Replay` played back twice gives the same per-tick checksums, and rewinding to a snapshot then replaying matches.
114
+
115
+ ## Rough time and cost
116
+ Rough, until the machine plan is linted: about 16 to 20 tasks in 4 waves plus a final review, several hours of wall time. Cost is not reported, as you asked earlier.