plum

#treesitter#compiler#wasm

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

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


e797f07 — Peter John 2026-11-09T14:17:45+05:30
Traits docs, examples/traits.plum, and std/game/Store (actor-trait task 5)
Files changed (4) hide show
  1. docs/language.md +102 -2
  2. docs/std.md +30 -0
  3. examples/traits.plum +145 -0
  4. std/game/Store.plum +107 -0
docs/language.md CHANGED
@@ -18,6 +18,7 @@ A Plum function is a tree of expressions. There is no `return`, `break` or `cont
18
18
  - [Generics](#generics)
19
19
  - [Methods, statics and constants](#methods-statics-and-constants)
20
20
  - [Operators on your own types](#operators-on-your-own-types)
21
+ - [Traits](#traits)
21
22
  - [Modules](#modules)
22
23
  - [Tests](#tests)
23
24
  - [Talking to the outside world](#talking-to-the-outside-world)
@@ -462,7 +463,7 @@ fun first[Elem](xs: List[Elem], fallback: Elem) -> Elem = match xs
462
463
  Cons(h, _) => h
463
464
  ```
464
465
 
465
- Parameters have no constraints. If `show[T]` calls `x.toStr()`, it works for any type that has `toStr`, and any other type gets an error showing how the call got there:
466
+ A parameter with no bound (see [Traits](#bounds)) is duck-typed. If `show[T]` calls `x.toStr()`, it works for any type that has `toStr`, and any other type gets an error showing how the call got there:
466
467
 
467
468
  ```
468
469
  in outer[Plain] (called at main.plum:9:3):
@@ -472,7 +473,7 @@ in outer[Plain] (called at main.plum:9:3):
472
473
 
473
474
  Each type gets its own compiled copy, so a `Slice[Float]` stores plain floats with no boxing.
474
475
 
475
- If the compiler can't work out a type parameter, annotate the value: `empty: List[Int] := Nil`.
476
+ If the compiler can't work out a type parameter, annotate the value (`empty: List[Int] := Nil`) or give the call its type arguments: `firstOf[Rect](shapes)`, `stage.findAs[Orb](id)`. They name the callee's own generics in the order it declares them.
476
477
 
477
478
  ## Methods, statics and constants
478
479
 
@@ -524,6 +525,105 @@ struct Vec2(x: Float, y: Float) =
524
525
  Vec2(x: self.x * s, y: self.y * s)
525
526
  ```
526
527
 
528
+ ## Traits
529
+
530
+ A trait is a list of methods. A type that implements it can be used wherever the trait is expected, mixed with other types that implement it.
531
+
532
+ ```plum
533
+ trait Shape =
534
+ fun area(self) -> Float # required: no body
535
+ fun name(self) -> Str = "shape" # optional: the body is the default
536
+ fun big(self) -> Bool = self.area() > 10.0 # a default may call the trait's methods
537
+ fun scaled(self, by: Float = 2.0) -> Self # `Self` is the implementing type
538
+ ```
539
+
540
+ A trait has no fields, and a default can use only the trait's other methods on `self`.
541
+
542
+ **Implementing** one: write `is Shape` (or `is A, B[X]`) after a struct's or enum's fields. The type must define every required method, with the trait's signature and `Self` replaced by the type. It may define any optional method; the others take the trait's default.
543
+
544
+ ```plum
545
+ struct Rect(w: Float, h: Float) is Shape =
546
+ fun area(self) -> Float = self.w * self.h
547
+ fun scaled(self, by: Float = 2.0) -> Rect = Rect(w: self.w * by, h: self.h * by)
548
+
549
+ enum Dot is Shape =
550
+ | Big
551
+ | Small
552
+
553
+ fun area(self) -> Float = match self
554
+ Big => 1.0
555
+ Small => 0.0
556
+
557
+ fun scaled(self, by: Float = 2.0) -> Dot = if by > 1.0 then Big else Small
558
+ ```
559
+
560
+ A type implements a trait only where the type is declared. A method with a trait method's name but another signature is an error, so a typo can't fall back to the default.
561
+
562
+ **Trait objects.** The trait's name used as a type (`Shape`, `List[Shape]`, `fn(Shape) -> Shape`) holds a value of any type that implements it. On it you can call the trait's methods and nothing else, and each call runs the value's own method or the default:
563
+
564
+ ```plum
565
+ fun total(xs: List[Shape]) -> Float = xs.fold(0.0, |acc, s| acc + s.area())
566
+
567
+ fun main() -> Float =
568
+ total([Rect(w: 2.0, h: 3.0), Big])
569
+ ```
570
+
571
+ - A method returning `Self` returns a trait object when called on one (`s.scaled()` is a `Shape`) and the type itself when called on it (`rect.scaled()` is a `Rect`). `Self` inside another type works the same way: a `fun split(self) -> List[Self]` called on a `Shape` gives a `List[Shape]`.
572
+ - A call on a trait object that leaves out arguments gets the defaults the trait declares (`s.scaled()` is `s.scaled(2.0)`), whatever defaults the type's own method has. Such a default can't mention `Self` or the trait's type parameters, since the call doesn't know the type.
573
+ - `==` on two trait objects is true when they hold the same type and that type's `==` says the values are equal (a type without `eq` compares by identity).
574
+
575
+ **Getting the type back.** In a `match`, `Type as name` matches a trait object holding a `Type`, and binds it as one. It is the only downcast.
576
+
577
+ ```plum
578
+ fun widthOf(s: Shape) -> Float = match s
579
+ Rect as r => r.w
580
+ _ => 0.0
581
+ ```
582
+
583
+ The type may be a generic parameter (`T as t`, with `T` set by the caller: `firstOf[Rect](xs)`), or a generic type whose arguments the trait object fixes (`Keep as k` on a `Reducer[Int]` binds a `Keep[Int]`). It can't be another trait.
584
+
585
+ **Type parameters.** A trait takes them like a struct, and an implementer names them:
586
+
587
+ ```plum
588
+ trait Reducer[M] =
589
+ fun update(self, msg: M) -> Self
590
+
591
+ struct Counter(n: Int) is Reducer[Int] =
592
+ fun update(self, msg: Int) -> Counter = Counter(n: self.n + msg)
593
+
594
+ # A generic type implements a trait with its own parameter.
595
+ struct Keep[M](last: M) is Reducer[M] =
596
+ fun update(self, msg: M) -> Keep[M] = Keep(last: msg)
597
+ ```
598
+
599
+ `Reducer[Int]` is a trait object, and two of them are the same type when their arguments are equal. A generic implementer built where its trait is expected takes the trait's arguments (`Keep(..)` as a `Reducer[Int]` is a `Keep[Int]`); one built first and used there later takes them from that first use.
600
+
601
+ ### Bounds
602
+
603
+ `[T: Shape]` (or `[T: Tr[X]]`, `[T: A + B]`) on a fn, method, struct or enum says `T` must implement the trait. In the body a `T` has the trait's methods, and one returning `Self` returns a `T`. A bound's arguments may name the other parameters:
604
+
605
+ ```plum
606
+ fun doubled[T: Shape](x: T) -> T = x.scaled(2.0)
607
+
608
+ fun replay[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
609
+ ```
610
+
611
+ Each use is checked to meet the bound. Generics are compiled per type, so a call on a bounded `T` goes straight to the type's method. Bounds and trait objects are different things: `List[Shape]` holds any mix of shapes, while `Store[Counter, Int]` holds exactly a `Counter`.
612
+
613
+ ### Coercion
614
+
615
+ A value of an implementing type becomes a trait object, with no cast, where one is expected as a whole value: an argument, an annotated local, a field, a list element, a returned value. Inside another type it doesn't: a `List[Rect]` is not a `List[Shape]`, and neither is an `Option[Rect]` an `Option[Shape]`, because the two are stored differently. Build the value as the trait object from the start (`xs: List[Shape] := [Rect(..)]`), or map it, since a closure's result is a whole value: `shapes: List[Shape] := rects.map(|r| r)`.
616
+
617
+ ### Errors
618
+
619
+ - a required method missing, or a method with a trait method's name and another signature;
620
+ - a duplicate `is` entry, or a type implementing the same trait twice with methods that clash;
621
+ - `Self` outside a trait;
622
+ - a method that isn't in the trait called on a trait object, or a field read on one (match `Type as x` first);
623
+ - a value used as a trait it doesn't implement, or a downcast to a type that doesn't implement it;
624
+ - a bound not met at a use, naming the missing trait;
625
+ - a method whose `Self` inside a parameter or the result can't be checked with the trait object there (`xs: List[Rect] := ..; xs` as a `List[Self]`): build the value where it is returned.
626
+
527
627
  ## Modules
528
628
 
529
629
  Each file is a module. A file starts with its imports. Nothing is implicit, not even `Int` or `Str` methods, and each file imports what it uses.
docs/std.md CHANGED
@@ -17,6 +17,7 @@ The [game engine](game.md) has its own page.
17
17
  | [`os`, `http`](#files-and-network) | files and the network |
18
18
  | [`Time`, `Random`, `Uuid`, `base64`, `Aabb`](#utilities) | utilities |
19
19
  | [`testing`](#testing) | helpers for tests |
20
+ | [`game/Store`](#game-state-store) | a game's state as a `Reducer`, and its messages |
20
21
 
21
22
  ## Numbers
22
23
 
@@ -188,3 +189,32 @@ fun main(io: Io) =
188
189
  ## Testing
189
190
 
190
191
  `assert` covers most tests. `std/testing` adds `testing.expectEq`, `expectNotEq`, `expectTrue`, `expectFalse`, `expectSuccess` and `expectFailure`.
192
+
193
+ ## Game state: Store
194
+
195
+ `std/game/Store` holds a game's state and the messages that change it. The state implements `trait Reducer[M]` (see [Traits](language.md#traits)): `update(self, msg: M) -> Self` is the rules, pure and with no `Io`, so the same messages from the same state give the same state; `handle(self, io: Io, msg: M)` is a message's effects (a sound, a save) and does nothing unless the state overrides it.
196
+
197
+ ```plum
198
+ import std/Int
199
+ import std/Io
200
+ import std/Str
201
+ import std/List
202
+ import std/game/Store
203
+
204
+ enum Msg = Collected(points: Int) | Hurt
205
+
206
+ struct Run(score: Int, lives: Int) is Reducer[Msg] =
207
+ fun update(self, msg: Msg) -> Run = match msg
208
+ Collected(p) => Run(..self, score: self.score + p)
209
+ Hurt => Run(..self, lives: self.lives - 1)
210
+
211
+ fun main(io: Io) =
212
+ s := Store.of(Run(score: 0, lives: 3)).dispatch(Collected(points: 5)).dispatch(Hurt)
213
+ done := s.flush(io) # handle(io, msg) for each message, oldest first
214
+ io.printLn("{done.state.score} {done.state.lives}")
215
+ ```
216
+
217
+ - **`Store[S: Reducer[M], M]`**: `Store.of(state)`, `dispatch(msg)` (reduces now and queues the message), `dispatchAll(msgs)`, `pending()` (the queued messages, oldest first), `flush(io)` (calls `handle` on the state for each queued message in order, then empties the queue), and the field `state`. A store is a value: `dispatch` and `flush` return a new one.
218
+ - **`store.replay(s, msgs)`**: the state after `msgs`, with no store and no effects.
219
+
220
+ Only the game loop drives a store; a game writes its `Reducer`.
examples/traits.plum ADDED
@@ -0,0 +1,145 @@
1
+ # Traits: a list of methods a type can implement. A trait's name used as a type is a
2
+ # value of any type that implements it (a trait object); a call on one goes to the
3
+ # value's own type. `T as x` in a `match` gets the concrete type back. A trait may take
4
+ # type parameters, and a generic parameter may be bounded by traits.
5
+ module traits
6
+ import std/Str
7
+ import std/Int
8
+ import std/Float
9
+ import std/List
10
+ import std/Option
11
+
12
+ # Required methods have no body; a method with a body is optional and the body is its
13
+ # default. A default may call the trait's other methods on `self`. `Self` is the type
14
+ # that implements the trait.
15
+ trait Shape =
16
+ fun area(self) -> Float
17
+ fun name(self) -> Str = "shape"
18
+ fun big(self) -> Bool = self.area() > 10.0
19
+ fun scaled(self, by: Float = 2.0) -> Self
20
+
21
+ # `is Shape` after the fields. Each required method must be there, with the trait's
22
+ # signature and `Self` as the type; the optional ones may be.
23
+ struct Rect(w: Float, h: Float) is Shape =
24
+ fun area(self) -> Float = self.w * self.h
25
+ fun name(self) -> Str = "rect"
26
+ fun scaled(self, by: Float = 2.0) -> Rect = Rect(w: self.w * by, h: self.h * by)
27
+
28
+ struct Circle(r: Float) is Shape =
29
+ fun area(self) -> Float = 3.0 * self.r * self.r
30
+ fun scaled(self, by: Float = 2.0) -> Circle = Circle(r: self.r * by)
31
+
32
+ # An enum implements a trait with the usual `match self`.
33
+ enum Dot is Shape =
34
+ | Big
35
+ | Small
36
+
37
+ fun area(self) -> Float = match self
38
+ Big => 1.0
39
+ Small => 0.0
40
+
41
+ fun scaled(self, by: Float = 2.0) -> Dot = if by > 1.0 then Big else Small
42
+
43
+ # A trait object: any shape. `scaled` returns `Self`, so on a `Shape` it returns a `Shape`.
44
+ fun total(xs: List[Shape]) -> Float = xs.fold(0.0, |acc, s| acc + s.area())
45
+
46
+ fun grow(xs: List[Shape]) -> List[Shape] = xs.map(|s| s.scaled())
47
+
48
+ # A downcast: `Rect as r` matches when the shape is a `Rect`, and `r` is a `Rect`.
49
+ fun widthOf(s: Shape) -> Float = match s
50
+ Rect as r => r.w
51
+ Circle as c => c.r * 2.0
52
+ _ => 0.0
53
+
54
+ # A generic downcast: `T` is the type the caller asks for.
55
+ fun firstOf[T](xs: List[Shape]) -> Option[T] = match xs
56
+ Cons(s, rest) => match s
57
+ T as t => Some(t)
58
+ _ => firstOf(rest)
59
+ Nil => None
60
+
61
+ # A bound: `T` must implement `Shape`. Calls on it go straight to T's methods, and a
62
+ # method returning `Self` returns a `T`.
63
+ fun doubled[T: Shape](x: T) -> T = x.scaled(2.0)
64
+
65
+ # A trait with a type parameter.
66
+ trait Reducer[M] =
67
+ fun update(self, msg: M) -> Self
68
+ fun seen(self) -> Int = 0
69
+
70
+ struct Counter(n: Int, count: Int) is Reducer[Int] =
71
+ fun update(self, msg: Int) -> Counter = Counter(n: self.n + msg, count: self.count + 1)
72
+ fun seen(self) -> Int = self.count
73
+
74
+ struct Words(text: Str) is Reducer[Str] =
75
+ fun update(self, msg: Str) -> Words = Words(text: self.text + msg)
76
+
77
+ fun replay[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
78
+
79
+ # A generic type implements a generic trait with its own parameter.
80
+ trait Widget[M] =
81
+ fun key(self) -> Int
82
+ fun click(self) -> Option[M] = None
83
+
84
+ struct Button[M](id: Int, onClick: M) is Widget[M] =
85
+ fun key(self) -> Int = self.id
86
+ fun click(self) -> Option[M] = Some(self.onClick)
87
+
88
+ struct Label[M](id: Int, text: Str) is Widget[M] =
89
+ fun key(self) -> Int = self.id
90
+
91
+ enum Msg = Start | Quit
92
+
93
+ fun clicks(ws: List[Widget[Msg]]) -> Int = ws.fold(0, |n, w| if w.click().isSome() then n + 1 else n)
94
+
95
+ test "a call on a trait object goes to the value's own method or the default"
96
+ xs: List[Shape] := [Rect(w: 2.0, h: 3.0), Circle(r: 1.0), Big]
97
+ assert total(xs) == 10.0
98
+ assert xs.map(|s| s.name()).get(0).unwrap() == "rect"
99
+ assert xs.map(|s| s.name()).get(1).unwrap() == "shape"
100
+ assert !xs.get(0).unwrap().big()
101
+
102
+ test "a Self method returns a trait object, and the trait's default argument fills in"
103
+ ys := grow([Rect(w: 2.0, h: 3.0), Small])
104
+ assert total(ys) == 25.0
105
+ s: Shape := Circle(r: 1.0)
106
+ assert s.scaled().area() == 12.0
107
+ assert s.scaled(3.0).area() == 27.0
108
+
109
+ test "an implementer becomes a trait object as a whole value, not inside a list"
110
+ rects := [Rect(w: 1.0, h: 1.0), Rect(w: 2.0, h: 1.0)]
111
+ shapes: List[Shape] := rects.map(|r| r)
112
+ assert total(shapes) == 3.0
113
+
114
+ test "on a concrete type, Self is that type"
115
+ r := Rect(w: 1.0, h: 1.0).scaled(4.0)
116
+ assert r.w == 4.0
117
+ assert doubled(Circle(r: 1.0)).r == 2.0
118
+
119
+ test "downcasts get the concrete type back"
120
+ assert widthOf(Rect(w: 5.0, h: 1.0)) == 5.0
121
+ assert widthOf(Circle(r: 2.0)) == 4.0
122
+ assert widthOf(Big) == 0.0
123
+ xs: List[Shape] := [Big, Circle(r: 3.0), Rect(w: 7.0, h: 1.0)]
124
+ assert firstOf[Rect](xs).unwrap().w == 7.0
125
+ assert firstOf[Circle](xs).unwrap().r == 3.0
126
+
127
+ test "a trait with a type parameter, as a bound"
128
+ c := replay(Counter(n: 0, count: 0), [1, 2, 3])
129
+ assert c.n == 6 && c.seen() == 3
130
+ assert replay(Words(text: ""), ["a", "b"]).text == "ab"
131
+ r: Reducer[Int] := Counter(n: 0, count: 0)
132
+ assert r.update(5).seen() == 1
133
+
134
+ test "generic implementers in a list of a generic trait object"
135
+ ws: List[Widget[Msg]] := [Button(id: 1, onClick: Start), Label(id: 2, text: "hi"), Button(id: 3, onClick: Quit)]
136
+ assert clicks(ws) == 2
137
+ assert ws.fold(0, |n, w| n + w.key()) == 6
138
+
139
+ test "== on trait objects: the same type and an equal value"
140
+ a: Shape := Rect(w: 1.0, h: 2.0)
141
+ b: Shape := Rect(w: 1.0, h: 2.0)
142
+ c: Shape := Circle(r: 1.0)
143
+ assert a == a
144
+ assert a != c
145
+ assert {a == b} == false
std/game/Store.plum ADDED
@@ -0,0 +1,107 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/List
5
+ import std/Slice
6
+ import std/Io
7
+
8
+ # A game's state and the messages that change it. The state is a `Reducer[M]`: `update`
9
+ # is the rules (pure, no `Io`: the same messages from the same state give the same state,
10
+ # which is what makes a run replayable), and `handle` is the effects of a message (a sound,
11
+ # a save), run after the tick with the final state.
12
+ #
13
+ # A `Store` holds the state and the messages of the tick so far. `dispatch` reduces a
14
+ # message at once and queues it; `flush(io)` runs `handle` for each queued message, in
15
+ # the order they were dispatched, and empties the queue. Only `Game` drives a store (see
16
+ # docs/plans/2026-11-09-actor-trait.md, "One way to make a game"): a game writes its
17
+ # `Reducer`, never a loop that dispatches.
18
+ #
19
+ # A store is a value: `dispatch` and `flush` return a new store and leave the old one as
20
+ # it was. The queue is a `List` with the newest message first.
21
+
22
+ trait Reducer[M] =
23
+ # The rules: the state after `msg`.
24
+ fun update(self, msg: M) -> Self
25
+
26
+ # The effects of `msg`, run by `Store.flush` after the tick. None by default.
27
+ fun handle(self, io: Io, msg: M) = Unit
28
+
29
+ struct Store[S: Reducer[M], M](state: S, queue: List[M]) =
30
+ # A store holding `state` with nothing queued.
31
+ fun of(state: S) -> Store[S, M] = Store(state: state, queue: Nil)
32
+
33
+ # Reduces `msg` into the state now and queues it for `flush`.
34
+ fun dispatch(self, msg: M) -> Store[S, M] =
35
+ Store(state: self.state.update(msg), queue: Cons(msg, self.queue))
36
+
37
+ # Each message of `msgs`, in order, as `dispatch` does.
38
+ fun dispatchAll(self, msgs: List[M]) -> Store[S, M] = msgs.fold(self, |st, m| st.dispatch(m))
39
+
40
+ # The queued messages, oldest first.
41
+ fun pending(self) -> List[M] = self.queue.reverse()
42
+
43
+ # Runs `handle` on the state for each queued message, oldest first, and empties the queue.
44
+ fun flush(self, io: Io) -> Store[S, M] =
45
+ st := self.state
46
+ self.pending().each(|m| st.handle(io, m))
47
+ Store(state: st, queue: Nil)
48
+
49
+ # The state after each of `msgs` in order, with no effects: what a recorded run of
50
+ # messages leads to.
51
+ fun replay[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
52
+
53
+ enum StoreTestMsg = Add(n: Int) | Reset | Note(n: Int)
54
+
55
+ struct StoreTally(total: Int, count: Int, log: Slice[Int]) is Reducer[StoreTestMsg] =
56
+ fun update(self, msg: StoreTestMsg) -> StoreTally = match msg
57
+ Add(n) => StoreTally(..self, total: self.total + n, count: self.count + 1)
58
+ Reset => StoreTally(..self, total: 0, count: self.count + 1)
59
+ Note(_) => self
60
+
61
+ # Records what it saw, so a test can check the order and the state it ran with.
62
+ fun handle(self, io: Io, msg: StoreTestMsg) = match msg
63
+ Add(n) => self.log.push(n)
64
+ Reset => self.log.push(-1)
65
+ Note(n) => self.log.push(n * 1000 + self.total)
66
+
67
+ struct StoreQuiet(n: Int) is Reducer[Int] =
68
+ fun update(self, msg: Int) -> StoreQuiet = StoreQuiet(n: self.n + msg)
69
+
70
+ test "dispatch reduces at once and queues"
71
+ s := Store.of(StoreTally(total: 0, count: 0, log: Slice()))
72
+ t := s.dispatch(Add(n: 2)).dispatch(Add(n: 3))
73
+ assert t.state.total == 5
74
+ assert t.state.count == 2
75
+ assert t.pending().length() == 2
76
+ assert t.state.log.length() == 0
77
+ assert s.state.total == 0
78
+ assert s.pending().isEmpty()
79
+
80
+ test "flush handles each queued message in order with the final state, then clears"
81
+ log: Slice[Int] := Slice()
82
+ s := Store.of(StoreTally(total: 0, count: 0, log: log))
83
+ t := s.dispatchAll([Add(n: 2), Reset, Add(n: 7), Note(n: 1)])
84
+ assert t.state.total == 7
85
+ u := t.flush(io)
86
+ assert u.pending().isEmpty()
87
+ assert u.state.total == 7
88
+ assert log.length() == 4
89
+ assert log.at(0) == 2
90
+ assert log.at(1) == -1
91
+ assert log.at(2) == 7
92
+ assert log.at(3) == 1007
93
+ v := u.flush(io)
94
+ assert log.length() == 4
95
+ assert v.state.count == 3
96
+
97
+ test "a reducer without handle has no effects"
98
+ s := Store.of(StoreQuiet(n: 1)).dispatch(2).dispatch(3)
99
+ assert s.state.n == 6
100
+ assert s.flush(io).state.n == 6
101
+ assert s.flush(io).pending().isEmpty()
102
+
103
+ test "replay reduces messages with no store"
104
+ assert replay(StoreQuiet(n: 0), [1, 2, 3]).n == 6
105
+ t := replay(StoreTally(total: 0, count: 0, log: Slice()), [Add(n: 4), Reset, Add(n: 1)])
106
+ assert t.total == 1 && t.count == 3
107
+ assert t.log.length() == 0