plum

#treesitter#compiler#wasm

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

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


be6ccaa — Peter John 2026-11-16T17:06:37+05:30
T7 review fixes, tests and docs: test-all's sweep also runs compiler/game/web-test/fixtures/tests (stress_state_view's 3 tests ran nowhere); Os chmod read back by what the bits allow (0o400 refuses a write, 0o600 allows it; Os has no stat and readFile of an unreadable file is Ok); a silent sound's commands checked against the recorded host calls (compiler/game host_test aSilentSoundsCommandsCallNoHost, fixture cmd_sound_fixture.plum: a tick's Play/Loop/Stop of Sound.Silent and of sound 3, only sound 3's reach the host); Orbit Runner's 600-tick recorded run pinned (`PlayingScreenHelpers.pinned`: an orb then a mine right of the ship, the rest away; `heldRight`), so it scores 10 and loses a life whatever the seed (checked on 8 seeds); old_forms_test asserts the full "undefined name 'palette'" error; game_in_place_test guards Clockwork (OrreryScreen.update 4, stepped, Body.place) and Menu (Body.place, Game.goTo$unique, Game.obey 4); tests/std/base64.plum merged into tests/std/encoding/Base64.plum (`Base64Helpers.bytes`). Docs: language.md (an imported main is its [App] primitive's static, `OrbitRunner.main(io)`, nothing global; a game is `main` returning a `Game`; the error chain qualified, `in Demo.outer<Plain>`; the @stepsWhen sample after its paragraph; `GraphHelpers.sample()` as the zero-parameter helper; std and examples only compiled by the sweep), tools.md (the same three), std.md (funs without parameters), game.md's Beside master row (ViewProbe and Stepper in tests/std/game/View.plum), AGENTS.md (the sweep's folders)
AGENTS.md CHANGED
@@ -10,7 +10,7 @@ After every commit to `master`, push it with the `repo-push` command (never `git
10
10
 
11
11
  ## Before every commit
12
12
 
13
- Run `compiler/scripts/test-all.sh`. It builds, runs every test executable (not just the Plum sweep, even when only `.plum` files changed), then runs `target/debug/plum test std examples tests` with the default, `--no-fbip` and `--no-fusion`, and ends with `ALL PASSED` or `FAILED: <n>`. A change to `std` can break Rust tests that the sweep never runs.
13
+ Run `compiler/scripts/test-all.sh`. It builds, runs every test executable (not just the Plum sweep, even when only `.plum` files changed), then runs `target/debug/plum test std examples tests compiler/game/web-test/fixtures/tests` with the default, `--no-fbip` and `--no-fusion`, and ends with `ALL PASSED` or `FAILED: <n>`. A change to `std` can break Rust tests that the sweep never runs.
14
14
 
15
15
  ## Models
16
16
 
compiler/cli/tests/cli/game_in_place_test.rs CHANGED
@@ -27,6 +27,12 @@
27
27
  //! actors' own steps are one spread each, their bodies' steps joined to it by the derive.
28
28
  //! `PlayingScreen.update`'s `Hit` reads the ship into a local before the spread, as `Caught`
29
29
  //! does, so the ring made at its position doesn't read `self` after `ship` is written.
30
+ //!
31
+ //! Clockwork and Menu (master's games, ported 2026-11-16): Clockwork's `OrreryScreen.update`
32
+ //! (4: the pause, pick, front and tick arms), the derived `stepped` and `Body.place` are in
33
+ //! place; Menu's screens have no spread in place of their own (each `view` keeps `self`), so
34
+ //! its guard is `Body.place` (the turning square) and the screen change its `GoTo` makes
35
+ //! (`Game.goTo$unique`, `Game.obey`'s 4).
30
36
 
31
37
  use std::collections::BTreeMap;
32
38
  use std::process::Command;
@@ -95,3 +101,17 @@ fn balloonPopKeepsItsInPlaceSpreads() {
95
101
  want.extend([("PlaygroundScreen.update", 1), ("Body.place", 1)]);
96
102
  assertKept("examples/games/balloonpop/BalloonPop.plum", &want);
97
103
  }
104
+
105
+ #[test]
106
+ fn clockworkKeepsItsInPlaceSpreads() {
107
+ let mut want = TICK.to_vec();
108
+ want.extend([("OrreryScreen.update", 4), ("OrreryScreen.stepped", 1), ("Body.place", 1)]);
109
+ assertKept("examples/games/clockwork/Clockwork.plum", &want);
110
+ }
111
+
112
+ #[test]
113
+ fn menuKeepsItsInPlaceSpreads() {
114
+ let mut want = TICK.to_vec();
115
+ want.extend([("Game.obey", 4), ("Game.goTo$unique", 1), ("Body.place", 1)]);
116
+ assertKept("examples/games/menu/Menu.plum", &want);
117
+ }
compiler/cli/tests/cli/old_forms_test.rs CHANGED
@@ -30,7 +30,10 @@ fn compileOutcome(name: &str, src: &str) -> (bool, String) {
30
30
  fn theOldModuleFormIsAnError() {
31
31
  let (ok, text) = compileOutcome("palette", "import std/Int\nimport tests/modules/Palette\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n palette.shade(50)\n");
32
32
  assert!(!ok, "{text}");
33
+ assert!(
34
+ text.contains("undefined name 'palette': a module has no functions of its own (nothing is global); `shade` is a static of `Palette`: write `Palette.shade`"),
33
- assert!(text.contains("shade"), "{text}");
35
+ "{text}"
36
+ );
34
37
  let (ok, text) = compileOutcome("modern", "import std/Int\nimport tests/modules/Palette\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n Palette.shade(50)\n");
35
38
  assert!(ok, "{text}");
36
39
  }
compiler/game/tests/fixtures/cmd_sound_fixture.plum ADDED
@@ -0,0 +1,32 @@
1
+ module cmd_sound_fixture
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Io
7
+ import std/collections/List
8
+ import std/game/Audio
9
+ import std/game/Cmd
10
+ import std/game/Screen
11
+ import std/game/ScreenSlice
12
+ import std/game/Game
13
+ import std/game/View
14
+ import std/App
15
+
16
+ # The first tick asks for the silent sound's play, loop and stop, then sound 3's play and
17
+ # stop: the game does them once the tick is over, and only sound 3's reach the host.
18
+ struct State[ScreenSlice<Float>](frames: Int) =
19
+ fun name(self) -> Str = "page"
20
+
21
+ fun subscriptions(self) -> List<Sub<Float>> = [OnFrame(|dt| dt)]
22
+
23
+ fun update(self, dt: Float) -> Next<State, Float> =
24
+ cmds: List<Cmd> := if self.frames == 0 then [Play(sound: Sound.Silent, volume: 1.0), Loop(sound: Sound.Silent, volume: 1.0), Stop(sound: Sound.Silent), Play(sound: Sound(id: 3), volume: 0.5), Stop(sound: Sound(id: 3))] else []
25
+ Next(state: State(frames: self.frames + 1), cmds: cmds)
26
+
27
+ fun view(self) -> List<View> = []
28
+
29
+ primitive CmdSoundFixture[App] =
30
+ fun main(io: Io) -> Game =
31
+ s: Screen := State(frames: 0)
32
+ Game(screens: [s])
compiler/game/tests/host_test.rs CHANGED
@@ -955,3 +955,17 @@ fn aBlendWrapsItsChildrenAndALineIsDrawnThroughItsPlace() {
955
955
  tapKey(&mut g, 67);
956
956
  assertCallsNear(&drawn(&mut g), &want);
957
957
  }
958
+
959
+ /// tests/fixtures/cmd_sound_fixture.plum: a tick's sound commands reach the host after it,
960
+ /// those of `Sound.Silent` never.
961
+ #[test]
962
+ fn aSilentSoundsCommandsCallNoHost() {
963
+ let wasm = compile(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cmd_sound_fixture.plum"));
964
+ let mut g = PlumGame::load(&wasm, Recorder::new()).expect("load game");
965
+ g.init().expect("init");
966
+ g.backend_mut().calls.clear();
967
+ g.update(1.0 / 60.0).expect("update");
968
+ g.update(1.0 / 60.0).expect("update");
969
+ let sounds: Vec<&String> = g.backend().calls.iter().filter(|c| c.starts_with("sound")).collect();
970
+ assert_eq!(sounds, ["soundPlay(3,0.5)", "soundStop(3)"]);
971
+ }
compiler/scripts/test-all.sh CHANGED
@@ -48,12 +48,13 @@ failureLines() {
48
48
  }
49
49
 
50
50
  # The three modes run side by side (each one's slow tail overlaps the others'), reported in order.
51
+ # compiler/game/web-test/fixtures/tests tests the web-test fixtures (stress_state_view) natively.
51
52
  modes='default --no-fbip --no-fusion'
52
53
  for mode in $modes; do
53
54
  flag=$mode
54
55
  [ "$mode" = default ] && flag=""
55
56
  # shellcheck disable=SC2086
56
- { target/debug/plum test $flag std examples tests > "$tmp/sweep$mode.out" 2>&1; echo $? > "$tmp/sweep$mode.status"; } &
57
+ { target/debug/plum test $flag std examples tests compiler/game/web-test/fixtures/tests > "$tmp/sweep$mode.out" 2>&1; echo $? > "$tmp/sweep$mode.status"; } &
57
58
  done
58
59
  wait
59
60
  for mode in $modes; do
docs/game.md CHANGED
@@ -530,7 +530,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
530
530
  | `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
531
531
  | the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
532
532
  | a view literal's `if`, `for`, `..` elements | `if` and `..` items and children blocks (`Overlay(..) {` + an item a line + `}`); no `for` item: `..xs.map(..)` | a `for` item would be a second way to write a `map` |
533
- | std's test helper types private (`_ViewProbe`, `_KitScreen`, ..) | public names (`ViewProbe`, `Stepper`, ..) | a type's name here is the module's: a game's own `Stepper` beside std's compiles, so there is no clash to avoid (checked with a probe) |
533
+ | std's test helper types private (`_ViewProbe`, `_KitScreen`, ..) | public names, in the tests mirror and not in std (`ViewProbe` and `Stepper` in tests/std/game/View.plum) | a type's name here is the module's: a game's own `Stepper` beside that test's compiles, so there is no clash to avoid (checked with a probe) |
534
534
  | `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
535
535
 
536
536
  The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), no `restart`, pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, frames on demand in the hosts (`frameIdle`, the browser waiting for input, `PlumGame::idle`), `plum run --dev` (its keys, its line, the page's Cmd key fixes), and `plum compile <folder>`. Orbit Runner's state checksum was master's (925878360) until its rules returned what happened as `then` actions (the mines are checked before more are added for the tick's points, and a restart starts at once), 946756219 then, 818414470 since the Elm-style screens (the subscriptions are read once a tick, so the tick Enter restarts on steers nothing), and 181767343 since the rules (counter-based draws, so every spawn lands elsewhere; each orb caught is its own action).
docs/language.md CHANGED
@@ -235,6 +235,11 @@ primitive Demo[App] =
235
235
 
236
236
  **Field attributes and derived methods:** a field may start with an attribute, `@name(expr)`. The one there is is `@stepsWhen(cond)`, for std/game's derived stepping: every struct that is a `Screen` gets a `stepped(self, dt)` written out by the compiler before checking, which steps each field holding actors (an `Actor`, a `List` of actors or an `Option` of one, a `List<View>`, the others as they are); an `Actor` that lists `Steps` has those fields stepped after its own `step`. `@stepsWhen(cond)` steps its field only while `cond`, an expression on `self`, holds. What is derived is an ordinary method, the same static construction one would write (`Screen(..self, ship: self.ship.step(dt), ..)`), so it costs nothing at run time; a screen that writes its own `stepped` keeps it. Any other attribute name is an error, and so is `@stepsWhen` on a field holding no actors or of a type that is neither a screen nor lists `Steps`, and `Steps` on a screen. See docs/game.md, "Stepping".
237
237
 
238
+ ```plum
239
+ struct PlayingScreen[ScreenSlice<PlayAction>](over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>) =
240
+ fun name(self) -> Str = "play"
241
+ ```
242
+
238
243
  A type that lists `Show` (std/Str, `trait Show = fun toStr(self) -> Str`) and writes no `toStr` gets one derived the same way: its variant's name and its fields' values in order, each as it interpolates (`Steer(1.0, -1.0)`, `Hit`; a struct `Spot(1, 2)`, one with no fields its name), so it interpolates (`"{a}"`) and meets a `T: Show` bound. A type that writes its own `toStr` keeps it. A field whose type is one of the program's structs or enums with no `toStr` that doesn't list `Show` either is an error at the type, since it couldn't go in the string:
239
244
 
240
245
  ```plum
@@ -247,11 +252,6 @@ enum PlayAction[Show] =
247
252
  # Hit => "Hit"
248
253
  ```
249
254
 
250
- ```plum
251
- struct PlayingScreen[ScreenSlice<PlayAction>](over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>) =
252
- fun name(self) -> Str = "play"
253
- ```
254
-
255
255
  **Setting up extra fields:** the header lists what callers pass. Anything else is set in `init`, which runs on construction.
256
256
 
257
257
  ```plum
@@ -614,8 +614,8 @@ primitive Lists =
614
614
  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:
615
615
 
616
616
  ```
617
- in outer<Plain> (called at main.plum:9:3):
617
+ in Demo.outer<Plain> (called at main.plum:9:3):
618
- in maxOf<Plain> (called at main.plum:5:3):
618
+ in Demo.maxOf<Plain> (called at main.plum:5:3):
619
619
  Plain has no method 'lt'
620
620
  ```
621
621
 
@@ -998,7 +998,7 @@ primitive Demo[App] =
998
998
  Shapes.clamp(500) + Shapes.Limit + p.x
999
999
  ```
1000
1000
 
1001
- Two modules that define the same type name are an error, so each file's helpers sit in a primitive of its own name. The program's `main` is the entry file's; the `main` of an imported file (a benchmark driver importing a game's main file) is an ordinary function of that module, reached through the module's name, the last part of the path in lowercase (`orbitrunner.main(io)`); a local with the same name as a module hides the module. `main` is the only function a file may have outside a type.
1001
+ Two modules that define the same type name are an error, so each file's helpers sit in a primitive of its own name. The program's `main` is the entry file's, a static of its `[App]` primitive (std/App); the `main` of an imported file (a test or a benchmark driver importing a game's main file) is an ordinary static of that file's `[App]` primitive (`OrbitRunner.main(io)`). Nothing is global: every function is in a type.
1002
1002
 
1003
1003
  Constants can be any pure expression, and they may refer to each other in any order. std's game modules work the same way: `import std/game/Gfx` gives `Gfx.drawRect(io, ..)`, and `import std/math/Math` gives the primitive `Math`, and `Math.sqrt(2.0)`.
1004
1004
 
@@ -1014,7 +1014,7 @@ primitive Clock =
1014
1014
 
1015
1015
  ## Tests
1016
1016
 
1017
- Tests live in their own files, in a `tests` folder that mirrors the code: the tests of `arith.plum` go in `tests/arith.plum`, those of `std/collections/Map.plum` in `tests/std/collections/Map.plum`, and those of a game's `screens/PlayingScreen.plum` in `tests/examples/games/orbitrunner/screens/PlayingScreen.plum`. A test file imports the file it tests and holds a `primitive` that lists `UnitTest` (from `std/Test`). Each of its funs without parameters is one test, named `<Primitive>.<fun>`; a fun with parameters is a helper. Helpers without parameters go in another `primitive` of the file, one that does not list `UnitTest` (std's tests keep theirs in `<Type>Helpers`, as `MapHelpers.valid(m)`):
1017
+ Tests live in their own files, in a `tests` folder that mirrors the code: the tests of `arith.plum` go in `tests/arith.plum`, those of `std/collections/Map.plum` in `tests/std/collections/Map.plum`, and those of a game's `screens/PlayingScreen.plum` in `tests/examples/games/orbitrunner/screens/PlayingScreen.plum`. A test file imports the file it tests and holds a `primitive` that lists `UnitTest` (from `std/Test`). Each of its funs without parameters is one test, named `<Primitive>.<fun>`; a fun with parameters is a helper. Helpers without parameters go in another `primitive` of the file, one that does not list `UnitTest` (std's tests keep theirs in `<Type>Helpers`, as `GraphHelpers.sample()`):
1018
1018
 
1019
1019
  ```plum
1020
1020
  # tests/arith.plum
@@ -1035,7 +1035,7 @@ $ plum test tests/arith.plum
1035
1035
  1 passed, 0 failed
1036
1036
  ```
1037
1037
 
1038
- A failing `assert` in a test is reported and the test goes on; a failing `assert` on `==` prints both values. `plum test` accepts files and folders (`plum test std examples tests` tests everything here, and a file without tests is still compiled), and `--filter` runs the tests whose name contains its text. A `UnitTest` primitive in a file with no `tests` folder in its path is an error that names the mirror to move it to. `std/Test` adds helpers like `Test.expectEq`.
1038
+ A failing `assert` in a test is reported and the test goes on; a failing `assert` on `==` prints both values. `plum test` accepts files and folders (`plum test std examples tests` tests everything here: a file without tests is still compiled, so `std` and `examples`, whose tests are in the `tests` mirror, are only compiled), and `--filter` runs the tests whose name contains its text. A `UnitTest` primitive in a file with no `tests` folder in its path is an error that names the mirror to move it to. `std/Test` adds helpers like `Test.expectEq`.
1039
1039
 
1040
1040
  ## Talking to the outside world
1041
1041
 
@@ -1063,6 +1063,6 @@ This means a function that doesn't receive an `Io` can't have outside effects, w
1063
1063
  | nothing | exit code 0 |
1064
1064
  | `Int` | prints the value, exit code 0 |
1065
1065
  | `Result` | an `Err` stops the program and prints the error's name, exit code 1 |
1066
- | a type with `update` and `draw` methods | a [game](game.md): `plum run` opens it in the browser |
1066
+ | a `Game` (std/game/Game) | a [game](game.md): `plum run` opens it in the browser |
1067
1067
 
1068
1068
  `export fun` makes a function callable from the host under its own name, for programs embedded in something else. Like `main` it is an entry point, so it goes in the program's `[App]` primitive (`primitive Plugin[App] =` then ` export fun update(dt: Float) = ..`); the host calls it as `update`, not `Plugin.update`.
docs/std.md CHANGED
@@ -269,7 +269,7 @@ primitive Demo[App] =
269
269
 
270
270
  ## Testing
271
271
 
272
- Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the funs of a `primitive XTest[UnitTest]` ([Tests](language.md#tests)). `std/Test` declares the `UnitTest` trait. `assert` covers most tests, and `std/Test` adds `Test.expectEq`, `expectNotEq`, `expectTrue`, `expectFalse`, `expectSuccess` and `expectFailure`.
272
+ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the funs without parameters of a `primitive XTest[UnitTest]` ([Tests](language.md#tests)). `std/Test` declares the `UnitTest` trait. `assert` covers most tests, and `std/Test` adds `Test.expectEq`, `expectNotEq`, `expectTrue`, `expectFalse`, `expectSuccess` and `expectFailure`.
273
273
 
274
274
  ## Game screens and slices
275
275
 
docs/tools.md CHANGED
@@ -6,9 +6,9 @@
6
6
 
7
7
  | Command | What it does |
8
8
  |---|---|
9
- | `plum run file.plum` | Compile and run. A program whose `main` returns a [game](game.md), a type with `update` and `draw`, opens in the browser. Given a folder (`plum run examples/games/orbitrunner`), it runs the one `.plum` file in the folder with the program's `primitive <Name>[App]` (its `main`); `plum build` and `plum compile` do the same |
9
+ | `plum run file.plum` | Compile and run. A program whose `main` returns a [game](game.md), a `Game` (std/game/Game), opens in the browser. Given a folder (`plum run examples/games/orbitrunner`), it runs the one `.plum` file in the folder with the program's `primitive <Name>[App]` (its `main`); `plum build` and `plum compile` do the same |
10
10
  | `plum run file.plum -- a b` | Run with arguments: the words after `--` are the program's `io.args()` (here `a` and `b`). A `plum build` executable gets its own arguments the same way; `plum test` and a game in the browser get none |
11
- | `plum test tests/ file.plum` | Run the tests (the funs of each `primitive XTest[UnitTest]`) in files and folders |
11
+ | `plum test tests/ file.plum` | Run the tests (the funs without parameters of each `primitive XTest[UnitTest]`) in files and folders |
12
12
  | `plum check file.plum dir/` | Type-check files and folders without compiling or running them |
13
13
  | `plum compile file.plum` | Write `file.wasm` (`-o` names the file). Given a folder, the `.wasm` of its file with `main` is written beside that file |
14
14
  | `plum build file.plum` | Make a native executable, or for a game, a static site |
@@ -81,7 +81,7 @@ You need a recent stable Rust toolchain and a C compiler.
81
81
  cargo install --path compiler/cli
82
82
  ```
83
83
 
84
- This installs `plum` to `~/.cargo/bin`. Run it again after pulling changes. While working on the compiler, use `cargo run -p plum-cli --` instead, and run `compiler/scripts/test-all.sh` before a commit: it builds, runs every Rust test, `plum test std examples tests` in the default, `--no-fbip` and `--no-fusion` modes, and the grammar's corpus when the `tree-sitter` CLI is installed, and ends with `ALL PASSED` (naming a step it skipped) or `FAILED: <n>`. A Rust test executable still running after 15 minutes (`TEST_ALL_DEADLINE` seconds) is stopped and fails as `(timeout)`.
84
+ This installs `plum` to `~/.cargo/bin`. Run it again after pulling changes. While working on the compiler, use `cargo run -p plum-cli --` instead, and run `compiler/scripts/test-all.sh` before a commit: it builds, runs every Rust test, `plum test std examples tests compiler/game/web-test/fixtures/tests` in the default, `--no-fbip` and `--no-fusion` modes (`std` and `examples` hold no tests, their tests are in the `tests` mirror, so they are only compiled), and the grammar's corpus when the `tree-sitter` CLI is installed, and ends with `ALL PASSED` (naming a step it skipped) or `FAILED: <n>`. A Rust test executable still running after 15 minutes (`TEST_ALL_DEADLINE` seconds) is stopped and fails as `(timeout)`.
85
85
 
86
86
  `plum build` of a program that is not a game compiles the `compiler/runtime` crate with cargo, so it needs this source tree and cargo on `PATH`.
87
87
 
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -349,19 +349,21 @@ primitive PlayingScreenTest[UnitTest] =
349
349
  assert PlayingScreenHelpers.hud(u) == "Score 0, Best 100"
350
350
  assert p.orbs.at(0).body.pos.x != PlayingScreenHelpers.mounted(io, 42, 0, 3).screen.orbs.at(0).body.pos.x
351
351
 
352
- # a recorded run of 600 ticks replays to the same score and positions
352
+ # a recorded run of 600 ticks replays to the same score and positions: the field pinned
353
+ # (an orb, then a mine, right of the ship, the rest away) and Right held, so the run
354
+ # catches the orb and hits the mine whatever the seed deals
353
355
  fun aRecordedRunOf600TicksReplaysTo() =
354
- a := PlayingScreenHelpers.framesUntil(PlayingScreenHelpers.mounted(io, 44, 0, PlayingScreen.StartLives).record(44), 0, 600)
356
+ a := PlayingScreenHelpers.heldRight(PlayingScreenHelpers.pinned(io, 44).record(44), 0, 600)
355
357
  r := a.recorded()
356
358
  assert r.length() == a.game.ticks
357
359
  assert a.screen.score > 0
358
360
  assert a.screen.lives < PlayingScreen.StartLives
359
361
  back := Replay.decode(r.encode()).unwrap()
360
362
  assert back.seed == 44
361
- b := PlayingScreenHelpers.mounted(io, back.seed, 0, PlayingScreen.StartLives).replay(back)
363
+ b := PlayingScreenHelpers.pinned(io, back.seed).replay(back)
362
364
  assert PlayingScreenHelpers.sameRun(b.screen, a.screen)
363
365
  assert b.screen.score == a.screen.score
364
- c := PlayingScreenHelpers.mounted(io, 45, 0, PlayingScreen.StartLives).replay(back)
366
+ c := PlayingScreenHelpers.pinned(io, 45).replay(back)
365
367
  assert !PlayingScreenHelpers.sameRun(c.screen, a.screen)
366
368
 
367
369
  # a recorded run through game over and a restart replays to the same state
@@ -470,6 +472,19 @@ primitive PlayingScreenHelpers =
470
472
 
471
473
  fun frameDt(f: Int) -> Float = 0.0166 + Float(f % 3) * 0.004 - 0.004
472
474
 
475
+ # The field of `seed` with its orbs and mines away but orb 0 60 right of the ship and
476
+ # mine 0 160 right of it, all standing still.
477
+ fun pinned(io: Io, seed: Int) -> TestRig<PlayingScreen> =
478
+ s := cleared(PlayingScreen.at(seed, Assets.none(), 0, PlayingScreen.StartLives))
479
+ at := s.ship.body.pos
480
+ orb := Orb(..s.orbs.at(0), body: Body(pos: Vec2(x: at.x + 60.0, y: at.y)))
481
+ mine := Mine(..s.mines.at(0), body: Body(pos: Vec2(x: at.x + 160.0, y: at.y)))
482
+ TestRig.mount(io, PlayingScreen(..s, orbs: Cons(orb, rest(s.orbs)), mines: Cons(mine, rest(s.mines))))
483
+
484
+ # Frames with Right held until `until` ticks.
485
+ fun heldRight(t: TestRig<PlayingScreen>, f: Int, until: Int) -> TestRig<PlayingScreen> =
486
+ if t.game.ticks >= until then t else heldRight(t.frame(Input(held: Held(keys: [Key.Right])), frameDt(f)), f + 1, until)
487
+
473
488
  fun framesUntil(t: TestRig<PlayingScreen>, f: Int, until: Int) -> TestRig<PlayingScreen> =
474
489
  if t.game.ticks >= until then t else framesUntil(t.frame(runInput(f, t.screen), frameDt(f)), f + 1, until)
475
490
 
tests/std/Os.plum CHANGED
@@ -75,12 +75,18 @@ primitive OsTest[UnitTest] =
75
75
  Os.remove(io, path)!
76
76
  Os.rmdir(io, dir)!
77
77
 
78
- # chmod changes a file's permission bits
78
+ # chmod changes a file's permission bits, read back by what they allow (Os has no stat):
79
+ # no write with 0o400, a write again with 0o600
79
80
  fun chmodChangesAFilesPermissionBits() =
80
81
  dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
81
82
  path := "{dir}/a.txt"
82
83
  Os.writeFile(io, path, "x")!
84
+ Os.chmod(io, path, 256)! # 0o400
85
+ assert Os.writeFile(io, path, "y").isErr()
86
+ assert Os.readFile(io, path)! == "x"
83
87
  Os.chmod(io, path, 384)! # 0o600
88
+ Os.writeFile(io, path, "y")!
89
+ assert Os.readFile(io, path)! == "y"
84
90
  Os.remove(io, path)!
85
91
  Os.rmdir(io, dir)!
86
92
 
tests/std/base64.plum DELETED
@@ -1,38 +0,0 @@
1
- import std/Int
2
- import std/Str
3
- import std/Buffer
4
- import std/Byte
5
- import std/Option
6
- import std/Result
7
- import std/encoding/Base64
8
- import std/Test
9
-
10
- primitive Base64Test[UnitTest] =
11
- # every variant round-trips every length and byte, padding and line breaks included
12
- fun everyVariantRoundTripsEveryLengthAndByte() =
13
- bad := Range.until(0, 300).fold(0, |acc, n|
14
- data := base64TestBytes(n * 7919 + 1, n % 100)
15
- ok := Base64.decode(Base64.encode(data))! == data && Base64.decode(Base64.encode(data, "+", "/", ""))! == data && Base64.decodeUrl(Base64.encodeUrl(data))! == data && Base64.decodeUrl(Base64.encodeUrl(data, true))! == data && Base64.decode(Base64.encodePem(data))! == data && Base64.decode(Base64.encodeMime(data))! == data
16
- if ok then acc else acc + 1
17
- )
18
- assert bad == 0
19
- assert Base64.encode(base64TestBytes(3, 57)).length() == 76 && Base64.encodeMime(base64TestBytes(3, 58)).split("\r\n", 0).length() == 2
20
- assert Base64.encodePem(base64TestBytes(3, 48)).length() == 64
21
-
22
- # invalid input: data after padding, a lone last character, other alphabets
23
- fun invalidInputDataAfterPaddingALoneLast() =
24
- assert Base64.decode("Zg==Zg==").isErr() && Base64.decode("Zg=g").isErr() && Base64.decode("=Zg").isErr()
25
- assert Base64.decode("Zm9vY").isErr() && Base64.decode("Z").isErr() && Base64.decode("Z===").isErr()
26
- assert Base64.decode("Zm9vYg")! == "foob" && Base64.decode("Zm9vYmE")! == "fooba"
27
- assert Base64.decode("Zm9v YmFy\n")! == "foobar" && Base64.decode("Zg= =")! == "f" && Base64.decode("")! == ""
28
- assert Base64.decode("Zm9v_mFy").isErr() && Base64.decodeUrl("Zm9v/mFy").isErr() && Base64.decode("Zm9v\u0000").isErr()
29
-
30
- # `n` pseudo-random bytes from the generator state `x`.
31
- fun base64TestBytes(x: Int, n: Int) -> Str =
32
- buf := Buffer()
33
- _ := Range.until(0, n).fold(x, |s, i|
34
- next := {s * 6364136223846793005 + 1442695040888963407}
35
- buf.writeByte(Byte({next >> 33} & 0xFF))
36
- next
37
- )
38
- buf.toStr()
tests/std/encoding/Base64.plum CHANGED
@@ -1,5 +1,6 @@
1
1
  import std/Str
2
2
  import std/Buffer
3
+ import std/Byte
3
4
  import std/Int
4
5
  import std/Float
5
6
  import std/Option
@@ -40,3 +41,33 @@ primitive Base64Test[UnitTest] =
40
41
  assert Base64.encodeMime(long).split("\r\n", 0).at(0).length() == 76
41
42
  assert Base64.decode(Base64.encodePem(long))! == long
42
43
  assert Base64.decode(Base64.encodeMime("hi there"))! == "hi there"
44
+
45
+ # every variant round-trips every length and byte, padding and line breaks included
46
+ fun everyVariantRoundTripsEveryLengthAndByte() =
47
+ bad := Range.until(0, 300).fold(0, |acc, n|
48
+ data := Base64Helpers.bytes(n * 7919 + 1, n % 100)
49
+ ok := Base64.decode(Base64.encode(data))! == data && Base64.decode(Base64.encode(data, "+", "/", ""))! == data && Base64.decodeUrl(Base64.encodeUrl(data))! == data && Base64.decodeUrl(Base64.encodeUrl(data, true))! == data && Base64.decode(Base64.encodePem(data))! == data && Base64.decode(Base64.encodeMime(data))! == data
50
+ if ok then acc else acc + 1
51
+ )
52
+ assert bad == 0
53
+ assert Base64.encode(Base64Helpers.bytes(3, 57)).length() == 76 && Base64.encodeMime(Base64Helpers.bytes(3, 58)).split("\r\n", 0).length() == 2
54
+ assert Base64.encodePem(Base64Helpers.bytes(3, 48)).length() == 64
55
+
56
+ # invalid input: data after padding, a lone last character, other alphabets
57
+ fun invalidInputDataAfterPaddingALoneLast() =
58
+ assert Base64.decode("Zg==Zg==").isErr() && Base64.decode("Zg=g").isErr() && Base64.decode("=Zg").isErr()
59
+ assert Base64.decode("Zm9vY").isErr() && Base64.decode("Z").isErr() && Base64.decode("Z===").isErr()
60
+ assert Base64.decode("Zm9vYg")! == "foob" && Base64.decode("Zm9vYmE")! == "fooba"
61
+ assert Base64.decode("Zm9v YmFy\n")! == "foobar" && Base64.decode("Zg= =")! == "f" && Base64.decode("")! == ""
62
+ assert Base64.decode("Zm9v_mFy").isErr() && Base64.decodeUrl("Zm9v/mFy").isErr() && Base64.decode("Zm9v\u0000").isErr()
63
+
64
+ primitive Base64Helpers =
65
+ # `n` pseudo-random bytes from the generator state `x`.
66
+ fun bytes(x: Int, n: Int) -> Str =
67
+ buf := Buffer()
68
+ _ := Range.until(0, n).fold(x, |s, i|
69
+ next := {s * 6364136223846793005 + 1442695040888963407}
70
+ buf.writeByte(Byte({next >> 33} & 0xFF))
71
+ next
72
+ )
73
+ buf.toStr()
tests/std/game/Cmd.plum CHANGED
@@ -13,6 +13,8 @@ primitive CmdTest[UnitTest] =
13
13
  assert Cmd.names(cmds) == "goTo(play) exit undo redo rewindTo(12) play(-1, 0.5) loop(3, 1.0) stop(3)"
14
14
  assert cmds.filter(|c| c.travels()).length() == 3
15
15
 
16
+ # `plum test`'s host traps on any game call, so getting to the end is the check; the
17
+ # recorded calls are checked in compiler/game/tests/host_test.rs, aSilentSoundsCommandsCallNoHost
16
18
  fun aSilentSoundsCommandsCallNoHost() =
17
19
  Play(sound: Sound.Silent, volume: 1.0).sound(io)
18
20
  Loop(sound: Sound.Silent, volume: 1.0).sound(io)