plum

#treesitter#compiler#wasm

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

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


2b50f5d — Peter John 2026-11-13T18:54:45+05:30
tests are statics: `Item::Test` and `ast::Test` are gone; the parser marks a `[UnitTest]` primitive's funs without parameters `Fn::is_test` and keeps them as statics (`MapTest.adds`); the checker gives a test `io` when std/Io is loaded and names it in errors by `ast::testLabel` (`__test_MapTest__adds`, shown as `test MapTest.adds` by `diag::sourceName`, loops lifted out of it too); `tests_lower` rewrites the entry file's tests in place (report body, `Str` result, `io` parameter), drops imported files' tests and exports each by its key (`test#MapTest.adds`), codegen finds it by key; a non-test build drops the tests before checking (the driver's strip is gone); loader's duplicate-test check on the statics; every pass's `Item::Test` arm removed (uniqueness, forms, binders, blocks, ctors, question, modules, spread_paths, reuse, prune, enum_checks, builtin_usage, compile_builtins, LSP); `plum test` runs the same 1395 tests with the same names, assert reports and filters unchanged, a crash now names the test frame; checker: a static of a generic type whose arguments fail in a generic body's erased pass (closure specialisation's capture made generic) binds the owner's open variables to its generics instead of leaving the receiver `Queued<_t>` to default to `Queued<Unit>`, a type no value has whose trait methods were never compiled (tests/traits/generic_static_trait_value.plum); std/game: `Queued.of` replaces the workaround `Effects.queued<A>`; std/game/headless.plum is std/game/TestRig.plum (imports in examples, tests, benchmarks, web-test fixtures; docs/game.md); KdTree: the `push2`/`consIf` comment says what the helpers save now (three times the compile, free at run time); CLI help and comments
Files changed (47) hide show
  1. benchmarks/screen_views/scale.plum +1 -1
  2. compiler/checker/src/callcheck.rs +16 -1
  3. compiler/checker/src/fncheck.rs +19 -5
  4. compiler/checker/src/program.rs +1 -35
  5. compiler/cli/src/main.rs +2 -2
  6. compiler/core/src/ast.rs +17 -23
  7. compiler/core/src/binders.rs +0 -6
  8. compiler/core/src/blocks.rs +0 -9
  9. compiler/core/src/builtin_usage.rs +0 -1
  10. compiler/core/src/compile_builtins.rs +0 -1
  11. compiler/core/src/ctors.rs +0 -7
  12. compiler/core/src/diag.rs +5 -4
  13. compiler/core/src/enum_checks.rs +0 -1
  14. compiler/core/src/forms.rs +3 -17
  15. compiler/core/src/loader.rs +9 -12
  16. compiler/core/src/modules.rs +4 -5
  17. compiler/core/src/parser.rs +6 -23
  18. compiler/core/src/prune.rs +0 -1
  19. compiler/core/src/question.rs +0 -11
  20. compiler/core/src/reuse.rs +0 -1
  21. compiler/core/src/spread_paths.rs +0 -2
  22. compiler/core/src/tail.rs +1 -1
  23. compiler/core/src/tests_lower.rs +30 -61
  24. compiler/core/src/uniqueness.rs +1 -20
  25. compiler/core/tests/core/tests_lower_test.rs +8 -6
  26. compiler/driver/src/lib.rs +0 -4
  27. compiler/game/web-test/fixtures/stress_state_view.plum +1 -1
  28. compiler/game/web-test/fixtures/tests/stress_state_view.plum +1 -1
  29. compiler/lsp/src/completion.rs +0 -1
  30. compiler/wasm-codegen/src/emit.rs +14 -9
  31. compiler/wasm-codegen/src/lib.rs +7 -4
  32. docs/game.md +3 -3
  33. examples/games/clicks.plum +1 -1
  34. examples/games/two_screens.plum +1 -1
  35. std/collections/KdTree.plum +4 -3
  36. std/game/Effects.plum +5 -5
  37. std/game/Game.plum +2 -2
  38. std/game/ScreenSlice.plum +1 -1
  39. std/game/{headless.plum → TestRig.plum} +1 -1
  40. std/game/View.plum +3 -3
  41. tests/benchmarks/screen_views/scale.plum +1 -1
  42. tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +1 -1
  43. tests/examples/games/clicks.plum +1 -1
  44. tests/examples/games/orbitrunner/screens/PlayingScreen.plum +1 -1
  45. tests/examples/games/two_screens.plum +1 -1
  46. tests/port/game/screens.plum +1 -1
  47. tests/traits/generic_static_trait_value.plum +31 -0
benchmarks/screen_views/scale.plum CHANGED
@@ -41,7 +41,7 @@ import std/game/Sprite
41
41
  import std/game/Screen
42
42
  import std/game/ScreenSlice
43
43
  import std/game/Game
44
- import std/game/headless
44
+ import std/game/TestRig
45
45
  import benchmarks/screen_views/timing
46
46
 
47
47
  primitive ScaleBench =
compiler/checker/src/callcheck.rs CHANGED
@@ -550,7 +550,22 @@ pub(crate) fn inferMethodCallWith(
550
550
  .get(&(Some(class_name.to_string()), name.to_string()))
551
551
  .copied()
552
552
  .unwrap_or(params.len());
553
- checkCallArgs(&label, &params, args, required, env, ctx, &mut binds)?;
553
+ if let Err(e) = checkCallArgs(&label, &params, args, required, env, ctx, &mut binds) {
554
+ // A generic body's erased pass may not check an argument the instantiations fix (a
555
+ // closure's capture made generic, `Z` for a `Src<A>`). The type a static call names
556
+ // (`Queued.of(..)` is `Queued<_t>`) must not keep its open variables: they would
557
+ // default to `Unit`, a type no value has and whose trait methods are never compiled.
558
+ if !withCheck(|s| s.inst_mode.get()) && ctx.statics.is_some_and(|st| st.contains(&(class_name.clone(), name.to_string()))) {
559
+ for (g, v) in &owner {
560
+ if let PlumType::TVar(n) = v {
561
+ if isInferVar(n) && !binds.contains_key(n) {
562
+ recordBind(n, &PlumType::TParam(g.clone()));
563
+ }
564
+ }
565
+ }
566
+ }
567
+ return Err(e);
568
+ }
554
569
  recordCall(Some(&class_name), name, call_map);
555
570
  recordDispatch(&resolveRecorded(obj_ty), name);
556
571
  Ok(substVars(&ret, &binds))
compiler/checker/src/fncheck.rs CHANGED
@@ -26,6 +26,15 @@ pub(crate) fn exportFnError(f: &ast::Fn, ctx: &CheckCtx) -> Option<CheckError> {
26
26
  ))
27
27
  }
28
28
 
29
+ /// How `f`'s errors name it: a test by its label (`ast::testLabel`), shown as the test.
30
+ fn fnLabel(f: &ast::Fn) -> String {
31
+ if f.is_test {
32
+ ast::testLabel(f)
33
+ } else {
34
+ f.name.clone()
35
+ }
36
+ }
37
+
29
38
  pub(crate) fn checkFn(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<CheckError> {
30
39
  let owner: Vec<String> = match &f.type_param {
31
40
  Some(r) => enumGenericsOf(r, ctx).to_vec(),
@@ -37,7 +46,7 @@ pub(crate) fn checkFn(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<
37
46
  let mut errors = checkParamDefaults(f, global_env, ctx);
38
47
  errors.append(&mut checkFnBody(f, global_env, ctx));
39
48
  // An expression body has no statement to check its `[]`s.
40
- errors.extend(crate::stmt::emptyListErrors(firstEmpty, &f.name));
49
+ errors.extend(crate::stmt::emptyListErrors(firstEmpty, &fnLabel(f)));
41
50
  errors
42
51
  })
43
52
  })
@@ -194,6 +203,11 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
194
203
  for p in &f.params {
195
204
  bindLocal(&mut env, &p.name, TypeScheme::mono(paramTypeG(&p.ty)));
196
205
  }
206
+ // A test may use `io` when std/Io is loaded (`plum test` passes it).
207
+ if f.is_test && !f.params.iter().any(|p| p.name == "io") && ctx.methods.keys().any(|(t, _)| t == ast::IO_TYPE) {
208
+ env.insert("io".to_string(), TypeScheme::mono(PlumType::TNamed(ast::IO_TYPE.to_string())));
209
+ }
210
+ let label = fnLabel(f);
197
211
 
198
212
  let declared_ret = f
199
213
  .returns
@@ -204,7 +218,7 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
204
218
  withCheck(|s| *s.cur_ret.borrow_mut() = Some(declared_ret.clone()));
205
219
  match &f.body {
206
220
  ast::FnBody::Expr(e) => {
207
- if let Some(err) = checkReturned(e, &env, ctx, &declared_ret, &f.name, (f.line, f.column)) {
221
+ if let Some(err) = checkReturned(e, &env, ctx, &declared_ret, &label, (f.line, f.column)) {
208
222
  errors.push(err);
209
223
  }
210
224
  }
@@ -228,14 +242,14 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
228
242
  stmt,
229
243
  &mut env,
230
244
  &declared_ret,
231
- &f.name,
245
+ &label,
232
246
  (f.line, f.column),
233
247
  ctx,
234
248
  ));
235
249
  withCheck(|s| { let h = &s.closure_hint; *h.borrow_mut() = None });
236
250
  }
237
251
  if let Some((last_expr, line, column)) = tail {
238
- if let Some(err) = checkReturned(last_expr, &env, ctx, &declared_ret, &f.name, (line, column)) {
252
+ if let Some(err) = checkReturned(last_expr, &env, ctx, &declared_ret, &label, (line, column)) {
239
253
  errors.push(err);
240
254
  }
241
255
  } else if let Some(last @ ast::Stmt { kind: ast::StmtKind::Assign(_), .. }) = block.stmts.last() {
@@ -247,7 +261,7 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
247
261
  c,
248
262
  format!(
249
263
  "fn '{}': the body ends in a declaration, so it has no value; end it with the {} to return",
250
- f.name, declared_ret
264
+ label, declared_ret
251
265
  ),
252
266
  ));
253
267
  }
compiler/checker/src/program.rs CHANGED
@@ -139,7 +139,6 @@ pub(crate) fn ioCapabilityErrors(source: &ast::Source) -> Vec<CheckError> {
139
139
  ast::FnBody::Block(b) => plum_core::visit::walkBlockRef(b, &mut visit),
140
140
  ast::FnBody::Extern => {}
141
141
  },
142
- ast::Item::Test(t) => plum_core::visit::walkBlockRef(&t.body, &mut visit),
143
142
  ast::Item::Const(c) => plum_core::visit::walkRef(&c.value, &mut visit),
144
143
  _ => {}
145
144
  }
@@ -362,7 +361,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
362
361
 
363
362
  errors.extend(crate::traits::checkTraitParamDefaults(source, &global_env, &ctx));
364
363
  let defaultsAt = plum_core::trait_defaults::defaultPositions(source);
365
- // Roots: every non-generic fn and every test. A generic fn is only
364
+ // Roots: every non-generic fn (a test too). A generic fn is only
366
365
  // name-resolved here (its body is type-checked per instantiation below).
367
366
  for item in &source.items {
368
367
  if let ast::Item::Fn(f) = item {
@@ -397,39 +396,6 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
397
396
  }
398
397
  }
399
398
 
400
- for item in &source.items {
401
- if let ast::Item::Test(t) = item {
402
- withCheck(|s| { let l = &s.cur_pos; l.set((t.line, t.column)) });
403
- let prevFile = (!t.file.is_empty()).then(|| setCurrentFile(&t.file));
404
- let mut env = global_env.clone();
405
- // A test may use `io` when std/Io is loaded (the test wrapper passes it).
406
- if source.hasPrimitiveIo() {
407
- env.insert("io".to_string(), TypeScheme::mono(PlumType::TNamed("Io".to_string())));
408
- }
409
- let firstEmpty = withCheck(|s| s.pending_seq.get());
410
- let mut block_errors = checkBlock(
411
- &t.body,
412
- &mut env,
413
- &PlumType::TUnit,
414
- &format!("test {}", t.name),
415
- (t.line, t.column),
416
- &ctx,
417
- );
418
- block_errors.extend(crate::stmt::emptyListErrors(firstEmpty, &format!("test {}", t.name)));
419
- errors.append(&mut block_errors);
420
- if let Some(prev) = prevFile {
421
- setCurrentFile(&prev);
422
- }
423
- if !t.file.is_empty() && t.file != source.file {
424
- // An imported file's tests are never compiled (see `desugarTestsToFns`):
425
- // their calls must not instantiate generic fns the program does not use.
426
- drainCalls();
427
- } else {
428
- registerCalls(&mut inst, &fn_by_key, &ctx, None);
429
- }
430
- }
431
- }
432
-
433
399
  // Check each reached instantiation (BFS); its own calls enqueue more.
434
400
  let mut seen_msgs: std::collections::HashSet<String> = std::collections::HashSet::new();
435
401
  while let Some(id) = nextInstantiation(&mut inst, &fn_by_key, &ctx) {
compiler/cli/src/main.rs CHANGED
@@ -129,7 +129,7 @@ enum Command {
129
129
  lib_path: Option<std::path::PathBuf>,
130
130
  },
131
131
  /// Compile a Plum source file's (or every file under one or more
132
- /// directories') `test` blocks and run them under wasmtime
132
+ /// directories') tests (`primitive XTest[UnitTest]`'s funs without parameters) and run them under wasmtime
133
133
  Test {
134
134
  /// One or more source files and/or directories (searched recursively for *.plum files)
135
135
  #[arg(required = true)]
@@ -859,7 +859,7 @@ fn outputWithin(
859
859
  Ok((process::Output { status, stdout, stderr }, timedOut))
860
860
  }
861
861
 
862
- /// Runs every `test` block in one file, printing the Spock-flavored per-test
862
+ /// Runs every test of one file, printing the Spock-flavored per-test
863
863
  /// tree as it goes, and returns `(passed, failed)` counts — shared by both
864
864
  /// the single-file and directory-recursive paths of `cmdTest`.
865
865
  fn runTestFile(file: &std::path::Path, lib_path: &std::path::Path, options: &TestOptions) -> Result<(usize, usize)> {
compiler/core/src/ast.rs CHANGED
@@ -164,7 +164,6 @@ pub fn numberIds(src: &mut Source) {
164
164
  }
165
165
  }
166
166
  Item::Const(c) => numberExpr(&mut c.value, false),
167
- Item::Test(t) => numberBlock(&mut t.body, false),
168
167
  // A trait method's parameter defaults: compiled at a call on a trait object.
169
168
  Item::Trait(t) => {
170
169
  for m in &mut t.methods {
@@ -275,7 +274,6 @@ fn firstNode(src: &Source, bad: &mut dyn FnMut(NodeId) -> bool) -> Option<NodeId
275
274
  FnBody::Extern => None,
276
275
  }),
277
276
  Item::Const(c) => expr(&c.value, bad),
278
- Item::Test(t) => block(&t.body, bad),
279
277
  Item::Enum(_) | Item::Trait(_) => None,
280
278
  };
281
279
  if d.is_some() {
@@ -307,8 +305,7 @@ pub struct Source {
307
305
  pub items: Vec<Item>,
308
306
  /// Source-order tag for every top-level `import`/`item` node (the `module`
309
307
  /// line is excluded), used to check that imports all come before every
310
- /// other declaration and that `test` blocks form one contiguous group at
311
- /// the end of the file.
308
+ /// other declaration.
312
309
  pub topLevelOrder: Vec<TopLevelKind>,
313
310
  /// Errors the parser found that the checker reports (bad list literals): the file
314
311
  /// (set by `stampFile`, so a merged program keeps each one's own), line, column, message.
@@ -337,6 +334,19 @@ pub struct PrimitiveDecl {
337
334
  /// The marker trait (std/Test) of a primitive whose funs without parameters are tests.
338
335
  pub const UNIT_TEST_TRAIT: &str = "UnitTest";
339
336
 
337
+ /// What a test's messages call it (and the fns lifted out of it) until `diag::sourceName`
338
+ /// shows it as `test XTest.fun`: `__test_XTest__fun`. A leading `__` is no Plum name, and a
339
+ /// type's name holds no `__`.
340
+ pub fn testLabel(f: &Fn) -> String {
341
+ format!("__test_{}__{}", f.type_param.as_deref().unwrap_or_default(), f.name)
342
+ }
343
+
344
+ /// `test XTest.fun` for a `testLabel`.
345
+ pub fn testDisplay(label: &str) -> Option<String> {
346
+ let (owner, name) = label.strip_prefix("__test_")?.split_once("__")?;
347
+ Some(format!("test {owner}.{name}"))
348
+ }
349
+
340
350
  /// Compiler built-in types whose API a `primitive` block declares (std only).
341
351
  pub const BUILTIN_PRIMITIVES: [&str; 7] = ["Int", "Float", "Bool", "Str", "Byte", "Array", "Io"];
342
352
 
@@ -374,7 +384,6 @@ impl Source {
374
384
  for item in &mut self.items {
375
385
  match item {
376
386
  Item::Fn(f) => f.file = file.to_string(),
377
- Item::Test(t) => t.file = file.to_string(),
378
387
  Item::Trait(t) => t.file = file.to_string(),
379
388
  _ => {}
380
389
  }
@@ -422,8 +431,6 @@ pub enum Item {
422
431
  Trait(Trait),
423
432
  Fn(Fn),
424
433
  Const(Const),
425
- /// A `UnitTest` primitive's test (see `Test`).
426
- Test(Test),
427
434
  }
428
435
 
429
436
  // ---------- Type definitions ----------
@@ -626,7 +633,9 @@ pub struct Fn {
626
633
  /// the wasm module under its own name, with the `extern fun` boundary ABI.
627
634
  /// Top level only: never a method, never generic, never an error union result.
628
635
  pub is_export: bool,
629
- /// A test (`Item::Test`) lowered to a fn (`tests_lower`); its name is generated.
636
+ /// A test: a fun without parameters of a `primitive XTest[UnitTest]` (a static, `XTest.fun`).
637
+ /// It may use `io` when std/Io is loaded. `plum test` runs the entry file's tests
638
+ /// (`tests_lower`); other builds drop them.
630
639
  pub is_test: bool,
631
640
  /// `fip fun`: every spread in the body must be proved in place (driver check).
632
641
  pub is_fip: bool,
@@ -646,21 +655,6 @@ pub struct Const {
646
655
  pub line: usize,
647
656
  }
648
657
 
649
- /// One test: a fun without parameters of a `primitive XTest[UnitTest]` (the parser makes
650
- /// it this, named `XTest.fun`, instead of a static). Compiled only by `plum test`,
651
- /// stripped from normal builds; an `assert` in it is reported and the test goes on.
652
- #[derive(Debug, Clone, PartialEq)]
653
- pub struct Test {
654
- /// Declaring file (stamped by the loader); `plum test` runs a test only
655
- /// when this is the file it was asked to test.
656
- pub file: String,
657
- pub name: String,
658
- pub body: Block,
659
- /// 1-based source position of the `test` keyword. 0 if unknown.
660
- pub line: usize,
661
- pub column: usize,
662
- }
663
-
664
658
  #[derive(Debug, Clone, PartialEq)]
665
659
  pub struct Param {
666
660
  pub name: String,
compiler/core/src/binders.rs CHANGED
@@ -51,11 +51,6 @@ pub fn freshenShadowingBinders(source: &mut Source) {
51
51
  declared(stmts, &mut taken);
52
52
  walkStmts(stmts, &taken);
53
53
  }
54
- Item::Test(t) => {
55
- let mut taken = HashSet::new();
56
- declared(&mut t.body.stmts, &mut taken);
57
- walkStmts(&mut t.body.stmts, &taken);
58
- }
59
54
  _ => {}
60
55
  }
61
56
  }
@@ -224,7 +219,6 @@ pub fn freshenSiblingDeclarations(source: &mut Source) {
224
219
  FnBody::Extern => {}
225
220
  }
226
221
  }
227
- Item::Test(t) => siblingStmts(&mut t.body.stmts, &mut HashSet::new(), &HashSet::new()),
228
222
  Item::Const(c) => siblingExpr(&mut c.value, &mut HashSet::new(), &HashSet::new()),
229
223
  _ => {}
230
224
  }
compiler/core/src/blocks.rs CHANGED
@@ -311,15 +311,6 @@ pub fn prepareBlockValues(source: &mut Source) -> Vec<Diagnostic> {
311
311
  FnBody::Extern => {}
312
312
  }
313
313
  }
314
- Item::Test(t) => {
315
- let mut pass = Pass { file: t.file.clone(), errors: vec![] };
316
- pass.validateBlock(&t.body);
317
- if pass.errors.is_empty() {
318
- scopeBody(&[], &mut t.body, &mut fresh);
319
- } else {
320
- errors.append(&mut pass.errors);
321
- }
322
- }
323
314
  Item::Const(c) => {
324
315
  if let Some(span) = firstBlock(&c.value) {
325
316
  errors.push(Diagnostic::new(
compiler/core/src/builtin_usage.rs CHANGED
@@ -75,7 +75,6 @@ fn walkSource(source: &Source, names: &mut Acc) -> HashSet<String> {
75
75
  }
76
76
  Item::Fn(f) => walkFn(f, names),
77
77
  Item::Const(c) => walkExpr(&c.value, names),
78
- Item::Test(t) => walkStmts(&t.body.stmts, names),
79
78
  Item::Trait(t) => {
80
79
  for m in &t.methods {
81
80
  walkFn(&m.sig, names);
compiler/core/src/compile_builtins.rs CHANGED
@@ -95,7 +95,6 @@ pub fn declare(source: &mut Source) {
95
95
  FnBody::Extern => {}
96
96
  },
97
97
  Item::Const(c) => crate::visit::walkRef(&c.value, &mut note),
98
- Item::Test(t) => crate::visit::walkBlockRef(&t.body, &mut note),
99
98
  Item::Enum(_) | Item::Trait(_) => {}
100
99
  }
101
100
  }
compiler/core/src/ctors.rs CHANGED
@@ -149,13 +149,6 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
149
149
  match item {
150
150
  Item::Fn(f) => rewriteFn(f, &plans, &mut errors),
151
151
  Item::Const(c) => mapExprsIn(&mut c.value, &mut |e| rewriteCall(e, &plans, &mut errors)),
152
- Item::Test(t) => {
153
- let mut body = FnBody::Block(std::mem::replace(&mut t.body, Block { stmts: vec![] }));
154
- mapExprs(&mut body, &mut |e| rewriteCall(e, &plans, &mut errors));
155
- if let FnBody::Block(b) = body {
156
- t.body = b;
157
- }
158
- }
159
152
  _ => {}
160
153
  }
161
154
  }
compiler/core/src/diag.rs CHANGED
@@ -31,7 +31,7 @@ pub struct Diagnostic {
31
31
  /// The fns the error is in, innermost first, each as its key (`Type.method`, or a free
32
32
  /// fn's name, as declared): the fn whose body failed, then for an error inside a generic
33
33
  /// fn's copy the fns whose calls led to that copy. Empty when the error is in no fn (a
34
- /// declaration, a `test` block) or the stage does not know. Tools read this, never the
34
+ /// declaration) or the stage does not know. Tools read this, never the
35
35
  /// message's `fn 'x'` / `in X<..>` text.
36
36
  pub inFns: Vec<String>,
37
37
  }
@@ -72,7 +72,8 @@ impl fmt::Display for Diagnostic {
72
72
  }
73
73
  }
74
74
 
75
- /// `fn '__test_N'` as the test it was lowered from (`test "adds"`), and no `assign '__lhs_N': `
75
+ /// `fn '__test_MapTest__adds'` (see `ast::testLabel`) as the test it names (`test MapTest.adds`),
76
+ /// and no `assign '__lhs_N': `
76
77
  /// for the hidden locals an `assert a == b` binds its operands to.
77
78
  fn testNames(text: &str) -> String {
78
79
  if !text.contains("'__") {
@@ -82,9 +83,9 @@ fn testNames(text: &str) -> String {
82
83
  while let Some(at) = out.find("fn '__test_") {
83
84
  let name_start = at + "fn '".len();
84
85
  let Some(len) = out[name_start..].find('\'') else { break };
85
- // A loop lifted out of a test is named after it (`__test_0` + a mark + a suffix).
86
+ // A loop lifted out of a test is named after it (the label + a mark + a suffix).
86
87
  let internal: String = out[name_start..name_start + len].chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
87
- let Some(shown) = crate::tests_lower::testDisplayName(&internal) else { break };
88
+ let Some(shown) = crate::ast::testDisplay(&internal) else { break };
88
89
  out.replace_range(at..name_start + len + 1, &shown);
89
90
  }
90
91
  for side in ["__lhs_", "__rhs_"] {
compiler/core/src/enum_checks.rs CHANGED
@@ -184,7 +184,6 @@ pub fn inlineVariantTypeErrors(source: &Source) -> Vec<String> {
184
184
  }
185
185
  Item::Fn(f) => w.func(f),
186
186
  Item::Const(c) => w.expr(&c.value),
187
- Item::Test(t) => w.stmts(&t.body.stmts),
188
187
  Item::Trait(t) => {
189
188
  for m in &t.methods {
190
189
  w.scope = crate::generics::Scope::in_(&typeGenerics, &m.sig);
compiler/core/src/forms.rs CHANGED
@@ -246,7 +246,6 @@ pub fn prepareForms(source: &mut Source) {
246
246
  FnBody::Expr(e) => numberLoopsIn(e, &mut loops),
247
247
  FnBody::Extern => {}
248
248
  },
249
- Item::Test(t) => numberLoops(&mut t.body.stmts, &mut loops),
250
249
  Item::Const(c) => numberLoopsIn(&mut c.value, &mut loops),
251
250
  Item::Enum(_) | Item::Trait(_) => {}
252
251
  }
@@ -379,8 +378,10 @@ pub fn finish(source: &Source) -> Source {
379
378
  for item in &mut out.items {
380
379
  match item {
381
380
  Item::Fn(f) => {
381
+ // A test's loops are named after the test (`diag::sourceName` shows it).
382
+ let name = if f.is_test { crate::ast::testLabel(f) } else { crate::modules::sourceFnName(&f.name).to_string() };
382
383
  let at = LiftSite {
383
- name: crate::modules::sourceFnName(&f.name).to_string(),
384
+ name,
384
385
  file: f.file.clone(),
385
386
  line: f.line,
386
387
  column: f.column,
@@ -393,17 +394,6 @@ pub fn finish(source: &Source) -> Source {
393
394
  FnBody::Extern => {}
394
395
  }
395
396
  }
396
- Item::Test(t) => {
397
- let at = LiftSite {
398
- name: t.name.clone(),
399
- file: t.file.clone(),
400
- line: t.line,
401
- column: t.column,
402
- generics: Vec::new(),
403
- isFip: false,
404
- };
405
- applyStmts(&mut t.body.stmts, &at, &mut lifted)
406
- }
407
397
  Item::Const(c) => {
408
398
  let at = LiftSite { name: c.name.clone(), file: source.file.clone(), line: c.line, column: 0, generics: Vec::new(), isFip: false };
409
399
  applyExpr(&mut c.value, &at, &mut lifted)
@@ -427,9 +417,6 @@ pub fn finish(source: &Source) -> Source {
427
417
  let mut seen = HashSet::new();
428
418
  innerBlocks(e, &mut |b| uniquePatternBinders(&mut b.stmts, &mut seen, &mut uniq));
429
419
  }
430
- Item::Test(t) => {
431
- uniquePatternBinders(&mut t.body.stmts, &mut HashSet::new(), &mut uniq)
432
- }
433
420
  _ => {}
434
421
  }
435
422
  }
@@ -871,7 +858,6 @@ pub fn uniqueConditionBindersIn(items: &mut [Item]) {
871
858
  body: FnBody::Expr(e),
872
859
  ..
873
860
  }) => uniqueConditionBindersExpr(e, &mut counter),
874
- Item::Test(t) => uniqueConditionBinders(&mut t.body.stmts, &mut counter),
875
861
  Item::Const(c) => uniqueConditionBindersExpr(&mut c.value, &mut counter),
876
862
  _ => {}
877
863
  }
compiler/core/src/loader.rs CHANGED
@@ -999,20 +999,20 @@ fn mergeItems(
999
999
  .filter(|p| !BUILTIN_PRIMITIVES.contains(&p.name.as_str()) || !p.generics.is_empty())
1000
1000
  .cloned(),
1001
1001
  );
1002
- let mut test_names: HashMap<&str, usize> = HashMap::new();
1002
+ let mut test_names: HashMap<String, usize> = HashMap::new();
1003
1003
  for item in &source.items {
1004
- // `test` blocks aren't global symbols (nothing references them by
1004
+ // Tests aren't global symbols (nothing calls them), so identically-named
1005
- // name), so identically-named tests in different files aren't a
1005
+ // tests in different files aren't a real conflict. Within one file the
1006
- // real conflict. Within one file the name is the test's export: two would
1006
+ // name is the test's export: two would be one wasm export twice.
1007
- // be one wasm export twice.
1008
- if let Item::Test(t) = item {
1007
+ if let Item::Fn(t @ crate::ast::Fn { is_test: true, .. }) = item {
1008
+ let name = format!("{}.{}", t.type_param.as_deref().unwrap_or_default(), t.name);
1009
- if let Some(first) = test_names.insert(t.name.as_str(), t.line) {
1009
+ if let Some(first) = test_names.insert(name.clone(), t.line) {
1010
1010
  return Err(vec![Diagnostic::new(
1011
1011
  DiagKind::Resolution,
1012
1012
  displayPath(file),
1013
1013
  t.line,
1014
1014
  t.column,
1015
- format!("duplicate test {}: a test of this name is already at line {}", t.name, first),
1015
+ format!("duplicate test {name}: a test of this name is already at line {first}"),
1016
1016
  )]);
1017
1017
  }
1018
1018
  items.push(item.clone());
@@ -1044,7 +1044,7 @@ fn mergeItems(
1044
1044
  let first = items
1045
1045
  .iter()
1046
1046
  .rev()
1047
- .find(|i| !matches!(i, Item::Test(_)) && itemNameKey(i) == key)
1047
+ .find(|i| !matches!(i, Item::Fn(f) if f.is_test) && itemNameKey(i) == key)
1048
1048
  .map(itemLine)
1049
1049
  .unwrap_or(0);
1050
1050
  format!("duplicate declaration of {what}: already declared at line {first}")
@@ -1070,7 +1070,6 @@ fn itemLine(item: &Item) -> usize {
1070
1070
  Item::Trait(t) => t.line,
1071
1071
  Item::Const(c) => c.line,
1072
1072
  Item::Fn(f) => f.line,
1073
- Item::Test(t) => t.line,
1074
1073
  }
1075
1074
  }
1076
1075
 
@@ -1084,7 +1083,6 @@ fn itemDisplayName(item: &Item) -> String {
1084
1083
  Some(r) => format!("method '{}.{}'", r, f.name),
1085
1084
  None => format!("function '{}'", f.name),
1086
1085
  },
1087
- Item::Test(t) => format!("test {}", t.name),
1088
1086
  }
1089
1087
  }
1090
1088
 
@@ -1102,7 +1100,6 @@ fn itemNameKey(item: &Item) -> String {
1102
1100
  Some(recv) => format!("method::{}::{}", recv, f.name),
1103
1101
  None => format!("fn::{}", f.name),
1104
1102
  },
1105
- Item::Test(_) => unreachable!("Item::Test is handled before itemNameKey is called"),
1106
1103
  }
1107
1104
  }
1108
1105
 
compiler/core/src/modules.rs CHANGED
@@ -620,17 +620,16 @@ fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec
620
620
  }
621
621
  }
622
622
  cx.scopes = vec![f.params.iter().map(|p| p.name.clone()).collect()];
623
+ if f.is_test {
624
+ // The test wrapper passes the capability as `io`.
625
+ cx.scopes[0].insert("io".to_string());
626
+ }
623
627
  match &mut f.body {
624
628
  FnBody::Block(b) => cx.block(b),
625
629
  FnBody::Expr(e) => cx.expr(e),
626
630
  FnBody::Extern => {}
627
631
  }
628
632
  }
629
- Item::Test(t) => {
630
- // The test wrapper passes the capability as `io`.
631
- cx.scopes = vec![HashSet::from(["io".to_string()])];
632
- cx.block(&mut t.body);
633
- }
634
633
  Item::Const(c) => {
635
634
  cx.scopes = vec![HashSet::new()];
636
635
  cx.expr(&mut c.value);
compiler/core/src/parser.rs CHANGED
@@ -156,14 +156,15 @@ impl<'a> AstParser<'a> {
156
156
  .map(|n| self.text(n))
157
157
  .unwrap_or_default();
158
158
  let pos = child.start_position();
159
- let (fns, consts, selfFn) = self.collectBody(child, &name);
159
+ let (mut fns, consts, selfFn) = self.collectBody(child, &name);
160
160
  let implements: Vec<String> = self.parseImplements(child).into_iter().map(|t| t.name).collect();
161
161
  // A `UnitTest` primitive's funs without parameters are its tests
162
162
  // (`MapTest.anEmptyMap`); the ones with parameters are helpers.
163
- let unitTest = implements.iter().any(|t| t == UNIT_TEST_TRAIT);
163
+ if implements.iter().any(|t| t == UNIT_TEST_TRAIT) {
164
- let (tests, fns): (Vec<Fn>, Vec<Fn>) =
164
+ for f in &mut fns {
165
- fns.into_iter().partition(|f| unitTest && f.params.is_empty() && !f.has_self && !f.is_extern);
165
+ f.is_test = f.params.is_empty() && !f.has_self && !f.is_extern;
166
- let tests: Vec<Item> = tests.into_iter().map(|f| Item::Test(Self::unitTest(&name, f))).collect();
166
+ }
167
+ }
167
168
  primitives.push(PrimitiveDecl {
168
169
  name: name.clone(),
169
170
  line: pos.row + 1,
@@ -183,7 +184,6 @@ impl<'a> AstParser<'a> {
183
184
  items.push(Item::Fn(f));
184
185
  topLevelOrder.push(TopLevelKind::Other);
185
186
  }
186
- items.extend(tests);
187
187
  topLevelOrder.push(TopLevelKind::Other);
188
188
  }
189
189
  "fn" => {
@@ -610,23 +610,6 @@ impl<'a> AstParser<'a> {
610
610
  }
611
611
  }
612
612
 
613
- /// The test a `UnitTest` primitive's fun without parameters is: named
614
- /// `<Primitive>.<fun>`, its body the fun's.
615
- fn unitTest(owner: &str, f: Fn) -> Test {
616
- let body = match f.body {
617
- FnBody::Block(b) => b,
618
- FnBody::Expr(e) => Block { stmts: vec![Stmt::Expr(e, f.line, f.column)] },
619
- FnBody::Extern => Block { stmts: vec![] },
620
- };
621
- Test {
622
- file: String::new(),
623
- name: format!("{owner}.{}", f.name),
624
- body,
625
- line: f.line,
626
- column: f.column,
627
- }
628
- }
629
-
630
613
  /// assert: "assert" expression. Captures the condition's own literal
631
614
  /// source text and 1-based line/column BEFORE parsing it into an `Expr`
632
615
  /// — see `Check`'s doc comment for why this has to happen this early.
compiler/core/src/prune.rs CHANGED
@@ -147,7 +147,6 @@ pub fn pruneUnreachable(src: &mut Source) -> usize {
147
147
  Item::Enum(e) => refs.contains(&e.name),
148
148
  Item::Trait(t) => refs.contains(&t.name),
149
149
  Item::Const(c) => refs.contains(&c.name) || c.name.rsplit(MEMBER_SEP).next().is_some_and(|n| refs.contains(n)),
150
- Item::Test(_) => false,
151
150
  };
152
151
  if reached {
153
152
  kept[i] = true;
compiler/core/src/question.rs CHANGED
@@ -494,17 +494,6 @@ pub fn lowerQuestions(source: &mut Source) -> Vec<Diagnostic> {
494
494
  ));
495
495
  }
496
496
  }
497
- Item::Test(t) => {
498
- if let Some(span) = firstQBlock(&t.body) {
499
- errors.push(Diagnostic::new(
500
- DiagKind::Type,
501
- t.file.clone(),
502
- span.startLine,
503
- span.startColumn,
504
- "'?' is not allowed in a closure or test: only in a fn returning Option<..> or Result<..>",
505
- ));
506
- }
507
- }
508
497
  Item::Enum(_) => {}
509
498
  Item::Trait(_) => {}
510
499
  }
compiler/core/src/reuse.rs CHANGED
@@ -151,7 +151,6 @@ pub fn markReuse(src: &mut Source) -> Vec<String> {
151
151
  for (idx, it) in src.items.iter().enumerate() {
152
152
  let mut body = match it {
153
153
  Item::Fn(g) => g.body.clone(),
154
- Item::Test(t) => FnBody::Block(t.body.clone()),
155
154
  Item::Const(k) => FnBody::Expr(k.value.clone()),
156
155
  _ => continue,
157
156
  };
compiler/core/src/spread_paths.rs CHANGED
@@ -214,7 +214,6 @@ pub fn lowerSpreadPaths(source: &mut Source) -> Vec<Diagnostic> {
214
214
  let (name, mut errs) = (
215
215
  match item {
216
216
  Item::Fn(f) => f.file.clone(),
217
- Item::Test(t) => t.file.clone(),
218
217
  _ => file.clone(),
219
218
  },
220
219
  Vec::new(),
@@ -229,7 +228,6 @@ pub fn lowerSpreadPaths(source: &mut Source) -> Vec<Diagnostic> {
229
228
  FnBody::Expr(e) => visitExpr(e, &mut visit),
230
229
  FnBody::Extern => {}
231
230
  },
232
- Item::Test(t) => visitBlock(&mut t.body, &mut visit),
233
231
  Item::Const(c) => visitExpr(&mut c.value, &mut visit),
234
232
  Item::Enum(_) | Item::Trait(_) => {}
235
233
  }
compiler/core/src/tail.rs CHANGED
@@ -4,7 +4,7 @@
4
4
  //! Tail position: the value of a fn body, the last expression of a block in tail
5
5
  //! position, each `if`/`match`/inline-`if` arm in tail position, and `return e`.
6
6
  //! Not tail: under `?`/`!`, as an argument or operand, under a loop,
7
- //! inside a `test` (desugared `__test_N` fns), or in an `export fn`. A call inside
7
+ //! inside a test (`Fn::is_test`), or in an `export fn`. A call inside
8
8
  //! a closure body is tail relative to the closure only.
9
9
  use crate::ast::*;
10
10
  use std::collections::HashSet;
compiler/core/src/tests_lower.rs CHANGED
@@ -1,38 +1,21 @@
1
1
  use crate::ast;
2
2
 
3
- /// A source with its `test` blocks lowered into ordinary fns. Type-check
3
+ /// A source whose tests (`Fn::is_test`) are rewritten to report their failed `assert`s.
4
- /// `source` (not the original), then compile it with `extraExports`.
4
+ /// Type-check `source` (not the original), then compile it with `extraExports`.
5
5
  pub struct TestProgram {
6
6
  pub source: ast::Source,
7
+ /// (the test's key `XTest.fun`, its export `test#XTest.fun`), in source order.
7
8
  pub extraExports: Vec<(String, String)>,
9
+ /// `XTest.fun` for each test, in the order of `extraExports`.
8
10
  pub names: Vec<String>,
9
11
  }
10
12
 
11
- thread_local! {
12
- /// The fn each test became -> the test's name, for messages (`testDisplayName`).
13
- static TEST_FNS: std::cell::RefCell<std::collections::BTreeMap<String, String>> = Default::default();
14
- }
15
-
16
- /// `test MapTest.anEmptyMap` for the fn a test was lowered to (`__test_N`).
17
- pub fn testDisplayName(internal: &str) -> Option<String> {
18
- TEST_FNS.with(|t| t.borrow().get(internal).map(|n| format!("test {n}")))
19
- }
20
-
21
13
  /// Temp names (`__lhs_N`) restart at 0 on every call.
22
14
  pub fn lowerTests(source: &ast::Source) -> TestProgram {
23
- let (mut lowered, extraExports) = desugarTestsToFns(source);
15
+ let (mut lowered, extraExports) = desugarTests(source);
24
- TEST_FNS.with(|t| {
25
- *t.borrow_mut() = extraExports
26
- .iter()
27
- .map(|(internal, export)| (internal.clone(), export["test#".len()..].to_string()))
28
- .collect()
29
- });
30
16
  // The desugaring builds nodes (assert messages, temps) with no id.
31
17
  ast::numberIds(&mut lowered);
32
- let names = extraExports
33
- .iter()
34
- .map(|(_, export_name)| export_name["test#".len()..].to_string())
18
+ let names = extraExports.iter().map(|(key, _)| key.clone()).collect();
35
- .collect();
36
19
  TestProgram {
37
20
  source: lowered,
38
21
  extraExports,
@@ -107,17 +90,19 @@ fn assertFailureMessage(c: &crate::ast::Check, lhs: &crate::ast::Expr, rhs: &cra
107
90
  })
108
91
  }
109
92
 
93
+ /// Each test of the entry file stays the static it is (`XTest.fun`), its body made to
94
+ /// collect the failed `assert`s into a report it returns (`Str`, empty when all held); it
95
+ /// takes the `Io` when std/Io is loaded. Tests of imported files are dropped: only the entry
96
+ /// file's own run.
110
- fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(String, String)>) {
97
+ fn desugarTests(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(String, String)>) {
111
98
  let mut items = Vec::with_capacity(source.items.len());
112
99
  let mut extraExports = Vec::new();
113
- let mut test_idx = 0usize;
114
100
  let mut counter = 0usize;
115
- // Tests may use `io` when std/Io is loaded: the export wrapper passes the `Io`.
116
101
  let hasIo = source.hasPrimitiveIo();
117
102
  let ioParam = if hasIo {
118
103
  vec![crate::ast::Param {
119
104
  name: "io".to_string(),
120
- ty: crate::ast::ParamType::Type(crate::ast::Type { name: "Io".to_string(), generics: vec![] }),
105
+ ty: crate::ast::ParamType::Type(crate::ast::Type { name: crate::ast::IO_TYPE.to_string(), generics: vec![] }),
121
106
  default: None,
122
107
  }]
123
108
  } else {
@@ -125,15 +110,14 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
125
110
  };
126
111
  for item in &source.items {
127
112
  match item {
128
- // Tests declared in imported files are not run: only the entry file's own.
129
- crate::ast::Item::Test(t) if !t.file.is_empty() && t.file != source.file => {}
113
+ crate::ast::Item::Fn(t) if t.is_test && !t.file.is_empty() && t.file != source.file => {}
130
- crate::ast::Item::Test(t) => {
114
+ crate::ast::Item::Fn(t) if t.is_test => {
115
+ let body = match &t.body {
116
+ crate::ast::FnBody::Block(b) => b.stmts.clone(),
131
- // Leading "__" can never collide with a real Plum-declared name —
117
+ crate::ast::FnBody::Expr(e) => vec![crate::ast::Stmt::Expr(e.clone(), t.line, t.column)],
132
- // `fn_identifier`/`var_identifier` must start with a lowercase letter.
133
- let internal_name = format!("__test_{}", test_idx);
118
+ crate::ast::FnBody::Extern => vec![],
134
- test_idx += 1;
119
+ };
135
-
136
- let mut stmts = Vec::with_capacity(t.body.stmts.len() + 2);
120
+ let mut stmts = Vec::with_capacity(body.len() + 2);
137
121
  // The report is a field of a `mut` struct, so an assert inside a loop (a
138
122
  // function of its own) writes into the same object.
139
123
  stmts.push(crate::ast::Stmt::Assign(crate::ast::Assign {
@@ -151,35 +135,20 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
151
135
  declare: true,
152
136
  ty: None,
153
137
  }));
154
- stmts.extend(desugarAssertStmts(&t.body.stmts, &mut counter));
138
+ stmts.extend(desugarAssertStmts(&body, &mut counter));
155
139
  stmts.push(crate::ast::Stmt::Expr(reportField(), 0, 0));
156
-
157
- items.push(crate::ast::Item::Fn(crate::ast::Fn {
158
- file: source.file.clone(),
140
+ let mut f = t.clone();
159
- name: internal_name.clone(),
160
- line: t.line,
161
- column: t.column,
162
- type_param: None,
163
- generics: vec![],
164
- is_extern: false,
165
- is_export: false,
166
- is_test: true,
167
- is_fip: false,
168
- bounds: vec![],
169
- has_self: true,
170
- params: ioParam.clone(),
141
+ f.params = ioParam.clone();
171
- returns: Some(crate::ast::Type {
172
- name: crate::ast::STR_TYPE.to_string(),
142
+ f.returns = Some(crate::ast::Type { name: crate::ast::STR_TYPE.to_string(), generics: vec![] });
173
- generics: vec![],
174
- }),
175
- body: crate::ast::FnBody::Block(crate::ast::Block { stmts }),
143
+ f.body = crate::ast::FnBody::Block(crate::ast::Block { stmts });
176
- }));
144
+ let key = crate::ast::fnKey(&f);
177
- extraExports.push((internal_name, format!("test#{}", t.name)));
145
+ extraExports.push((key.clone(), format!("test#{key}")));
146
+ items.push(crate::ast::Item::Fn(f));
178
147
  }
179
148
  other => items.push(other.clone()),
180
149
  }
181
150
  }
182
- if test_idx > 0 {
151
+ if !extraExports.is_empty() {
183
152
  items.push(reportStruct());
184
153
  }
185
154
  (
@@ -200,7 +169,7 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
200
169
  /// Recursively rewrites every `assert cond` (`cond` carrying its own literal
201
170
  /// source text, captured at parse time — see `crate::ast::Check`) into
202
171
  /// `if !cond { __report = "{__report}<text>\n" }`, descending into nested
203
- /// control-flow blocks so an `assert` inside a `test`'s own
172
+ /// control-flow blocks so an `assert` inside a test's own
204
173
  /// `if`/`while`/`for`/`match` still records into the same hidden accumulator.
205
174
  fn desugarAssertStmts(stmts: &[crate::ast::Stmt], counter: &mut usize) -> Vec<crate::ast::Stmt> {
206
175
  stmts.iter().flat_map(|s| desugarAssertStmt(s, counter)).collect()
compiler/core/src/uniqueness.rs CHANGED
@@ -420,7 +420,6 @@ struct UParam {
420
420
  #[derive(PartialEq)]
421
421
  enum Kind {
422
422
  Fn,
423
- Test,
424
423
  Const,
425
424
  }
426
425
 
@@ -514,7 +513,7 @@ struct An {
514
513
  deadSpreads: Vec<Vec<DeadSpread>>,
515
514
  /// `Array` methods that always return a new array.
516
515
  arrayFresh: HashSet<usize>,
517
- /// Per unit, can the program run it? What only unreachable code does (a helper of `test` blocks,
516
+ /// Per unit, can the program run it? What only unreachable code does (a helper of tests,
518
517
  /// in a build) must not make the rest copy.
519
518
  live: Vec<bool>,
520
519
  /// The game's `gameUpdate` and `main`, when `gameUpdate` may take its state uniquely so far: `solve`
@@ -1897,7 +1896,6 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1897
1896
  FnBody::Block(b) => mutBlock(b, &mut mark),
1898
1897
  FnBody::Extern => {}
1899
1898
  },
1900
- Item::Test(t) => mutBlock(&mut t.body, &mut mark),
1901
1899
  _ => {}
1902
1900
  }
1903
1901
  for (_, node, what, result) in verdicts.iter().filter(|v| v.0 == ui) {
@@ -1999,7 +1997,6 @@ fn reuseCandidates(an: &An) -> Vec<bool> {
1999
1997
  fn lineOf(src: &Source, u: &Unit) -> usize {
2000
1998
  match &src.items[u.itemIdx] {
2001
1999
  Item::Fn(f) => f.line,
2002
- Item::Test(t) => t.line,
2003
2000
  Item::Const(c) => c.line,
2004
2001
  _ => 0,
2005
2002
  }
@@ -2154,18 +2151,6 @@ fn build(src: &Source) -> An {
2154
2151
  block,
2155
2152
  });
2156
2153
  }
2157
- Item::Test(t) => units.push(Unit {
2158
- label: format!("test {}", t.name),
2159
- kind: Kind::Test,
2160
- itemIdx: idx,
2161
- free: false,
2162
- method: false,
2163
- hasSelf: false,
2164
- name: String::new(),
2165
- ty: None,
2166
- params: vec![],
2167
- block: t.body.clone(),
2168
- }),
2169
2154
  Item::Const(c) => units.push(Unit {
2170
2155
  label: format!("const {}", c.name),
2171
2156
  kind: Kind::Const,
@@ -2499,7 +2484,6 @@ fn liveUnits(an: &An, src: &Source) -> Vec<bool> {
2499
2484
  let isEntry = |u: &Unit| -> bool {
2500
2485
  match &src.items[u.itemIdx] {
2501
2486
  Item::Fn(f) => f.is_export || f.is_test || (f.type_param.is_none() && ["main", crate::game_entry::GAME_UPDATE, crate::game_entry::GAME_DRAW].contains(&f.name.as_str())),
2502
- Item::Test(_) => true,
2503
2487
  _ => false,
2504
2488
  }
2505
2489
  };
@@ -3864,7 +3848,6 @@ fn retarget(src: &mut Source, itemIdx: usize, node: NodeId, name: &str) -> bool
3864
3848
  FnBody::Block(b) => mutBlock(b, f),
3865
3849
  FnBody::Extern => {}
3866
3850
  },
3867
- Item::Test(t) => mutBlock(&mut t.body, f),
3868
3851
  Item::Const(c) => mutExpr(&mut c.value, f),
3869
3852
  _ => {}
3870
3853
  };
@@ -3900,7 +3883,6 @@ fn renameCalls(src: &mut Source, from: &HashSet<(Option<String>, String)>, to: &
3900
3883
  FnBody::Block(b) => mutBlock(b, &mut rename),
3901
3884
  FnBody::Extern => {}
3902
3885
  },
3903
- Item::Test(t) => mutBlock(&mut t.body, &mut rename),
3904
3886
  Item::Const(c) => mutExpr(&mut c.value, &mut rename),
3905
3887
  _ => {}
3906
3888
  }
@@ -4134,7 +4116,6 @@ fn methodRecvKnown(an: &An, caller: usize, node: NodeId, src: &Source) -> bool {
4134
4116
  FnBody::Block(b) => mutBlock(b, &mut find),
4135
4117
  FnBody::Extern => {}
4136
4118
  },
4137
- Item::Test(t) => mutBlock(&mut t.body, &mut find),
4138
4119
  Item::Const(c) => mutExpr(&mut c.value, &mut find),
4139
4120
  _ => {}
4140
4121
  }
compiler/core/tests/core/tests_lower_test.rs CHANGED
@@ -13,9 +13,11 @@ fn lowersOneTest() {
13
13
  let src = plum_test_support::parseRawSource(SRC);
14
14
  let p = lowerTests(&src);
15
15
  assert_eq!(p.names, vec!["SampleTest.a"]);
16
- assert_eq!(p.extraExports, vec![("__test_0".to_string(), "test#SampleTest.a".to_string())]);
16
+ assert_eq!(p.extraExports, vec![("SampleTest.a".to_string(), "test#SampleTest.a".to_string())]);
17
- assert!(!p.source.items.iter().any(|i| matches!(i, Item::Test(_))));
17
+ // The test stays the static it is, now returning its report.
18
- fnNamed(&p.source, "__test_0");
18
+ let f = fnNamed(&p.source, "a");
19
+ assert!(f.is_test && f.type_param.as_deref() == Some("SampleTest") && !f.has_self);
20
+ assert_eq!(f.returns.as_ref().map(|t| t.name.as_str()), Some("Str"));
19
21
  }
20
22
 
21
23
  #[test]
@@ -23,15 +25,15 @@ fn assertNamesPerCompile() {
23
25
  let src = plum_test_support::parseRawSource(SRC);
24
26
  let a = lowerTests(&src);
25
27
  let b = lowerTests(&src);
26
- assert_eq!(plum_test_support::debugNoIds(&fnNamed(&a.source, "__test_0").body), plum_test_support::debugNoIds(&fnNamed(&b.source, "__test_0").body));
28
+ assert_eq!(plum_test_support::debugNoIds(&fnNamed(&a.source, "a").body), plum_test_support::debugNoIds(&fnNamed(&b.source, "a").body));
27
- let dbg = format!("{:?}", fnNamed(&a.source, "__test_0").body);
29
+ let dbg = format!("{:?}", fnNamed(&a.source, "a").body);
28
30
  assert!(dbg.contains("__lhs_0") && dbg.contains("__rhs_1") && !dbg.contains("__lhs_2"));
29
31
  }
30
32
 
31
33
  #[test]
32
34
  fn failureMessageText() {
33
35
  let src = plum_test_support::parseRawSource(SRC);
34
- let dbg = format!("{:?}", fnNamed(&lowerTests(&src).source, "__test_0").body);
36
+ let dbg = format!("{:?}", fnNamed(&lowerTests(&src).source, "a").body);
35
37
  assert!(dbg.contains("assert-report"));
36
38
  assert!(dbg.contains(" Expected: "));
37
39
  assert!(dbg.contains("\\n Actual: "));
compiler/driver/src/lib.rs CHANGED
@@ -74,9 +74,6 @@ fn closureSpec(copy: &mut Source, env: &Env) -> bool {
74
74
 
75
75
  /// Purity -> simplify -> drive: the `fusion` pass; returns its notes.
76
76
  pub fn driveNotes(copy: &mut Source) -> Vec<String> {
77
- // A build never runs `test` blocks (`plum test` lowers them to fns first, so none is left
78
- // here): their calls must not make production code copy.
79
- copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
80
77
  let pure = plum_core::timing::time("purity", || plum_core::purity::pureFns(copy));
81
78
  let mut notes = plum_core::timing::time("simplify", || plum_core::simplify::simplify(copy, &pure));
82
79
  notes.extend(plum_core::timing::time("drive", || plum_core::drive::drive(copy, &pure)));
@@ -96,7 +93,6 @@ pub fn inPlaceRun(copy: &mut Source, origins: Option<&plum_core::fip::FipOrigins
96
93
  &own
97
94
  }
98
95
  };
99
- copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
100
96
  let rep = plum_core::timing::time("uniqueness", || plum_core::uniqueness::markUnique(copy));
101
97
  let mut notes: Vec<String> = rep.versions.iter().cloned().collect();
102
98
  notes.extend(rep.proved.iter().map(|l| format!("unique spread at {l}")));
compiler/game/web-test/fixtures/stress_state_view.plum CHANGED
@@ -29,7 +29,7 @@ import std/game/Label
29
29
  import std/game/Screen
30
30
  import std/game/ScreenSlice
31
31
  import std/game/Game
32
- import std/game/headless
32
+ import std/game/TestRig
33
33
  import std/Io
34
34
 
35
35
  primitive StressStateView =
compiler/game/web-test/fixtures/tests/stress_state_view.plum CHANGED
@@ -19,7 +19,7 @@ import std/game/Label
19
19
  import std/game/Screen
20
20
  import std/game/ScreenSlice
21
21
  import std/game/Game
22
- import std/game/headless
22
+ import std/game/TestRig
23
23
  import std/Io
24
24
  import stress_state_view
25
25
  import std/Test
compiler/lsp/src/completion.rs CHANGED
@@ -162,7 +162,6 @@ pub fn topLevelItems(source: &ast::Source) -> Vec<CompletionItem> {
162
162
  ..Default::default()
163
163
  });
164
164
  }
165
- ast::Item::Test(_) => {}
166
165
  }
167
166
  }
168
167
  // `primitive` blocks: a constant group (`Key`) or a built-in type's API (`Int`, `Array`),
compiler/wasm-codegen/src/emit.rs CHANGED
@@ -237,18 +237,23 @@ impl<'a> Emit<'a> {
237
237
  pub(crate) fn exportExtras(&mut self) {
238
238
  let Emit { source, extra_exports, module, ctx, .. } = self;
239
239
  for (internal_name, export_name) in extra_exports.iter() {
240
+ // A test is named by its key (`MapTest.adds`), a game's entry by its fn's name.
241
+ let f = source.items.iter().find_map(|it| match it {
242
+ ast::Item::Fn(f) if &plum_core::ast::fnKey(f) == internal_name => Some(f),
243
+ _ => None,
244
+ });
245
+ let key = f.map_or_else(|| internal_name.clone(), fnKey);
240
246
  let idx = *ctx
241
247
  .func_ids
242
- .get(internal_name)
248
+ .get(&key)
243
249
  .expect("extra_exports name was registered as a synthesized Fn item");
244
- let io = source.items.iter().any(|it| matches!(it, ast::Item::Fn(f) if &f.name == internal_name && entryTakesIo(f)));
245
- if io {
250
+ match f {
246
- let f = source.items.iter().find_map(|it| match it { ast::Item::Fn(f) if &f.name == internal_name => Some(f), _ => None }).unwrap();
251
+ Some(f) if entryTakesIo(f) => {
247
- let sig = ctx.func_sigs.get(&fnKey(f)).expect("test fn has a signature");
252
+ let sig = ctx.func_sigs.get(&key).expect("test fn has a signature");
248
- let w = emitEntryWrapper(module, &f.name, idx, sig, false, true);
253
+ let w = emitEntryWrapper(module, &key, idx, sig, false, true);
249
- module.addExport(export_name, ExportKind::Func, w);
254
+ module.addExport(export_name, ExportKind::Func, w);
250
- } else {
255
+ }
251
- module.addExport(export_name, ExportKind::Func, idx);
256
+ _ => module.addExport(export_name, ExportKind::Func, idx),
252
257
  }
253
258
  }
254
259
  }
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -58,8 +58,8 @@ pub(crate) use values::*;
58
58
  /// What `compile` does besides compiling.
59
59
  #[derive(Clone, Copy, Debug)]
60
60
  pub struct CompileOptions {
61
+ /// Make the entry file's tests report their `assert`s and export each as
61
- /// Lower `test` blocks into exported `"test#<name>"` fns (`plum test`); otherwise
62
+ /// `"test#XTest.fun"` (`plum test`); otherwise the tests are dropped.
62
- /// they are stripped.
63
63
  pub tests: bool,
64
64
  /// Which rewrite passes run (`--no-fusion`, `--explain-fusion`).
65
65
  pub passes: plum_driver::PassOptions,
@@ -98,11 +98,14 @@ fn gameExports(game: bool) -> Vec<(String, String)> {
98
98
  }
99
99
 
100
100
  /// The one compile entry: type-checks `source` (passes per `opts.passes`) and compiles it.
101
- /// With `opts.tests`, `test` blocks are first lowered to ordinary fns (see
101
+ /// With `opts.tests`, the tests are first lowered (see `plum_core::tests_lower`) and
102
- /// `plum_core::tests_lower`) and exported. A game's frame entry points are added first.
102
+ /// exported; without, they are dropped, so their calls do not make production code copy. A game's frame entry points are added first.
103
103
  pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Vec<Diagnostic>> {
104
104
  let mut gameSource = source.clone();
105
105
  let game = plum_core::game_entry::lowerGame(&mut gameSource).map_err(|d| vec![d])?;
106
+ if !opts.tests {
107
+ gameSource.items.retain(|i| !matches!(i, ast::Item::Fn(f) if f.is_test));
108
+ }
106
109
  let source = &gameSource;
107
110
  if opts.passes.explain {
108
111
  for line in explainLayouts(source) {
docs/game.md CHANGED
@@ -202,7 +202,7 @@ A kind of your own that takes children has a `children: List<View>` field and re
202
202
 
203
203
  ### How std draws a view
204
204
 
205
- The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/headless reads it.
205
+ The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
206
206
 
207
207
  Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll` and `stepIn` for a screen's `stepped`.
208
208
 
@@ -398,7 +398,7 @@ Put your rules in code that takes no `Io`, test them from a `primitive XTest[Uni
398
398
 
399
399
  ### Testing a screen
400
400
 
401
- `std/game/headless` runs a screen, or a whole game, with no host: the test sends input, runs ticks through the game's own tick, and reads back the screen, what its view draws and what its effects did. A rig is a value, like the game in it: each input and tick returns the next rig.
401
+ `std/game/TestRig` runs a screen, or a whole game, with no host: the test sends input, runs ticks through the game's own tick, and reads back the screen, what its view draws and what its effects did. A rig is a value, like the game in it: each input and tick returns the next rig.
402
402
 
403
403
  ```plum
404
404
  # tests/examples/games/orbitrunner/screens/PlayingScreen.plum
@@ -439,7 +439,7 @@ primitive PlayingScreenTest[UnitTest] =
439
439
  assert !v.screen.over
440
440
  ```
441
441
 
442
- `std/game/headless` is tested by [`tests/port/game/screens.plum`](../tests/port/game/screens.plum) (presses through turned groups and overlays, dispatch order, navigation, transitions and the presses they drop, frames on demand, record and replay, undo and rewind, the stepping and `steps()`, the hud, a camera that follows). `compiler/game/tests/host_test.rs` checks what the native host draws: each scaling's placing and culling, a slide's offsets and backgrounds on both screens, a turned box and label and the hud.
442
+ `std/game/TestRig` is tested by [`tests/port/game/screens.plum`](../tests/port/game/screens.plum) (presses through turned groups and overlays, dispatch order, navigation, transitions and the presses they drop, frames on demand, record and replay, undo and rewind, the stepping and `steps()`, the hud, a camera that follows). `compiler/game/tests/host_test.rs` checks what the native host draws: each scaling's placing and culling, a slide's offsets and backgrounds on both screens, a turned box and label and the hud.
443
443
 
444
444
  ## Beside master
445
445
 
examples/games/clicks.plum CHANGED
@@ -18,7 +18,7 @@ import std/game/Control
18
18
  import std/game/Screen
19
19
  import std/game/ScreenSlice
20
20
  import std/game/Game
21
- import std/game/headless
21
+ import std/game/TestRig
22
22
 
23
23
  enum TapAction = Tapped | Push(dx: Float) | Quit
24
24
 
examples/games/two_screens.plum CHANGED
@@ -14,7 +14,7 @@ import std/game/Control
14
14
  import std/game/Screen
15
15
  import std/game/ScreenSlice
16
16
  import std/game/Game
17
- import std/game/headless
17
+ import std/game/TestRig
18
18
 
19
19
  enum TitleAction = Start
20
20
 
std/collections/KdTree.plum CHANGED
@@ -162,10 +162,11 @@ struct KdTree<V>(root: KdNode<V>, size: Int) =
162
162
  dy := a.y - b.y
163
163
  dx * dx + dy * dy
164
164
 
165
- # `a` then `b` in front of `xs`. The walks build their stacks through this call
165
+ # `a` then `b` in front of `xs`. The walks build their stacks through this static
166
166
  # and `consIf` rather than writing the `Cons` cells into their calls: written
167
- # inline, the fusion stage takes minutes to specialise `kWalk`, `heightWalk` and
167
+ # inline, the fusion stage specialises `kWalk`, `heightWalk` and `entriesWalk` on
168
+ # the just-built lists and the compile takes three times as long. The calls cost
168
- # `entriesWalk` on the just-built lists.
169
+ # nothing at run time: like any small static, they are copied into their callers.
169
170
  fun push2<T>(a: T, b: T, xs: List<T>) -> List<T> =
170
171
  Cons(head: a, tail: Cons(head: b, tail: xs))
171
172
 
std/game/Effects.plum CHANGED
@@ -13,10 +13,10 @@ import std/game/ScreenSlice
13
13
  # is held with the slice as the tick left it (`Queued<A>`), so one list holds the actions
14
14
  # of every screen whatever their types, and the game runs each one's effect (the slice's
15
15
  # `effect(io, a, game)`), in the order dispatched. A test reads the ones that ran with
16
- # `Effects.sent<A>(game.ran)` (std/game/headless's `effects<A>()`).
16
+ # `Effects.sent<A>(game.ran)` (std/game/TestRig's `effects<A>()`).
17
17
  #
18
18
  # The queue of the dispatch running sits in one slot (`Effects.Running`): the game sets it around
19
- # a screen's `deliver`, std/game/headless around its own `dispatch`, and a slice's own
19
+ # a screen's `deliver`, std/game/TestRig around its own `dispatch`, and a slice's own
20
20
  # `dispatch` (a reducer dispatching what happened) queues there. Outside them it is empty
21
21
  # and `dispatch` only reduces.
22
22
 
@@ -27,6 +27,9 @@ trait Effect =
27
27
  struct Queued<A>[Effect](slice: ScreenSlice<A>, action: A) =
28
28
  fun apply(self, io: Io, game: Control) = self.slice.effect(io, self.action, game)
29
29
 
30
+ # `a`, to run with the effect of the slice `s`.
31
+ fun of(s: ScreenSlice<A>, a: A) -> Effect = Queued(slice: s, action: a)
32
+
30
33
  # A delivery's queue, of the slice's action type.
31
34
  trait Sink =
32
35
  fun size(self) -> Int
@@ -39,9 +42,6 @@ primitive Effects =
39
42
  # The queue of the dispatch running: empty outside any, one queue inside one.
40
43
  Running = Slice<Sink>()
41
44
 
42
- # `a`, to run with the effect of the slice `s`.
43
- fun queued<A>(s: ScreenSlice<A>, a: A) -> Effect = Queued(slice: s, action: a)
44
-
45
45
  # The actions of type `A` among `fx`, in order: `Effects.sent<PlayAction>(game.ran)`.
46
46
  fun sent<A>(fx: List<Effect>) -> List<A> =
47
47
  none: List<A> := Nil
std/game/Game.plum CHANGED
@@ -71,7 +71,7 @@ import std/game/History
71
71
  # last frame drawn shows the screen as it is (`frameDrawn`), `idle()` is true. `delivered`,
72
72
  # `skipped` and `draws` count the ticks delivered, the ticks slept through and the frames
73
73
  # drawn, for tests; `ran` and `asked` are the effects that ran in the last tick and what
74
- # they asked of the game (std/game/headless reads them).
74
+ # they asked of the game (std/game/TestRig reads them).
75
75
  #
76
76
  # Undo and time travel (docs/game.md): `timeTravel(cap)` keeps the game's history from its
77
77
  # start (std/game/History), and the game can then go back to any tick it played and
@@ -165,7 +165,7 @@ struct Game(screens: List<Screen>) =
165
165
 
166
166
  # The game after the undos, redos and rewinds the effects asked for, in order (`obey`
167
167
  # keeps them for the end of the tick), which it then forgets: what ends a tick, and the
168
- # kit's `dispatch` (std/game/headless).
168
+ # kit's `dispatch` (std/game/TestRig).
169
169
  fun travelAsked(self, io: Io) -> Game = self.travel.fold(Game(..self, travel: Nil), |g, a| g.travelled(io, a))
170
170
 
171
171
  # The game after a move through its history that an effect asked for.
std/game/ScreenSlice.plum CHANGED
@@ -129,7 +129,7 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
129
129
  None => stepped
130
130
  Effects.endDispatch()
131
131
  final: ScreenSlice<A> := afterTick
132
- fx: List<Effect> := List.fromSlice(q).map(|a| Effects.queued(final, a))
132
+ fx: List<Effect> := List.fromSlice(q).map(|a| Queued.of(final, a))
133
133
  Delivered(screen: afterTick, effects: fx, acted: acted.length() > 0)
134
134
 
135
135
  # `s` after the event `e`, mapped to its action; a pointer event while a transition runs
std/game/{headless.plum → TestRig.plum} RENAMED
@@ -193,7 +193,7 @@ struct TestRig<S>(
193
193
  q.push(a)
194
194
  Effects.endDispatch()
195
195
  final: ScreenSlice<A> := next
196
- fx: List<Effect> := List.fromSlice(q).map(|x| Effects.queued(final, x))
196
+ fx: List<Effect> := List.fromSlice(q).map(|x| Queued.of(final, x))
197
197
  withScreen := Game(..g, screens: Game.setAt(g.screens, g.current, next), wake: true, dirty: true, ran: Nil, asked: Nil)
198
198
  TestRig(..self.forget(), game: withScreen).kept(withScreen.apply(self.io, fx).travelAsked(self.io))
199
199
  _ =>
std/game/View.plum CHANGED
@@ -75,10 +75,10 @@ import std/game/Circle
75
75
  # paintCulled draws them, skipping each `Sized` item whose bounds miss an area, with
76
76
  # what is under it (a screen that `culls()`)
77
77
  # drawnIn lists what they draw, each item with its transform and alpha (`Drawn`):
78
- # std/game/headless's finders look in it
78
+ # std/game/TestRig's finders look in it
79
79
  # hitIn the item a press at a point is on, top-most first: what std's delivery
80
80
  # gives a slice's `onPress`
81
- # worldIn where they draw a given view: its transform (std/game/headless's
81
+ # worldIn where they draw a given view: its transform (std/game/TestRig's
82
82
  # `worldOf`)
83
83
  #
84
84
  # and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind)
@@ -200,7 +200,7 @@ primitive Views =
200
200
 
201
201
  # The transform of the view `a` (its own coordinates to those `m` maps to) where `items`
202
202
  # draw it, found by identity through each item's view, visible or not; None if it is not
203
- # there. std/game/headless's `worldOf` and `click` find a view this way.
203
+ # there. std/game/TestRig's `worldOf` and `click` find a view this way.
204
204
  fun worldIn(items: List<View>, a: View, m: Affine) -> Option<Affine> = match items
205
205
  Nil => None
206
206
  Cons(x, rest) =>
tests/benchmarks/screen_views/scale.plum CHANGED
@@ -17,7 +17,7 @@ import std/game/Sprite
17
17
  import std/game/Screen
18
18
  import std/game/ScreenSlice
19
19
  import std/game/Game
20
- import std/game/headless
20
+ import std/game/TestRig
21
21
  import benchmarks/screen_views/timing
22
22
  import benchmarks/screen_views/scale
23
23
  import std/Test
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -20,7 +20,7 @@ import std/game/Control
20
20
  import std/game/Screen
21
21
  import std/game/ScreenSlice
22
22
  import std/game/Game
23
- import std/game/headless
23
+ import std/game/TestRig
24
24
  import examples/games/balloonpop/actors/Balloon
25
25
  import examples/games/balloonpop/BalloonPop
26
26
  import examples/games/balloonpop/screens/PlaygroundScreen
tests/examples/games/clicks.plum CHANGED
@@ -16,7 +16,7 @@ import std/game/Control
16
16
  import std/game/Screen
17
17
  import std/game/ScreenSlice
18
18
  import std/game/Game
19
- import std/game/headless
19
+ import std/game/TestRig
20
20
  import examples/games/clicks
21
21
  import std/Test
22
22
 
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -21,7 +21,7 @@ import std/game/Control
21
21
  import std/game/Screen
22
22
  import std/game/ScreenSlice
23
23
  import std/game/Game
24
- import std/game/headless
24
+ import std/game/TestRig
25
25
  import examples/games/orbitrunner/actors/Mine
26
26
  import examples/games/orbitrunner/actors/Orb
27
27
  import examples/games/orbitrunner/actors/Ring
tests/examples/games/two_screens.plum CHANGED
@@ -12,7 +12,7 @@ import std/game/Control
12
12
  import std/game/Screen
13
13
  import std/game/ScreenSlice
14
14
  import std/game/Game
15
- import std/game/headless
15
+ import std/game/TestRig
16
16
  import examples/games/two_screens
17
17
  import std/Test
18
18
 
tests/port/game/screens.plum CHANGED
@@ -29,7 +29,7 @@ import std/game/Control
29
29
  import std/game/Screen
30
30
  import std/game/ScreenSlice
31
31
  import std/game/Game
32
- import std/game/headless
32
+ import std/game/TestRig
33
33
  import std/Test
34
34
 
35
35
  enum ProbeAct =
tests/traits/generic_static_trait_value.plum ADDED
@@ -0,0 +1,31 @@
1
+ import std/Int
2
+ import std/Test
3
+ import std/collections/List
4
+
5
+ # A static of a generic struct that returns a trait value, called in a closure of a generic
6
+ # fun: closure specialisation passes the capture as a generic of its own, so the erased check
7
+ # of the call fails and the type it names (`Boxed<_>`) once defaulted to `Boxed<Unit>`, which
8
+ # has no compiled `area` for the trait's dispatch.
9
+
10
+ trait Shape =
11
+ fun area(self) -> Int
12
+
13
+ trait Src<A> =
14
+ fun weight(self, a: A) -> Int
15
+
16
+ struct Twice[Src<Int>](k: Int) =
17
+ fun weight(self, a: Int) -> Int = a * self.k
18
+
19
+ struct Boxed<A>[Shape](s: Src<A>, v: A) =
20
+ fun area(self) -> Int = self.s.weight(self.v)
21
+
22
+ fun of(s: Src<A>, v: A) -> Shape = Boxed(s: s, v: v)
23
+
24
+ primitive GenericStaticTraitValueTest[UnitTest] =
25
+ fun wrapAll<A, S: Src<A>>(s: S, vs: List<A>) -> List<Shape> =
26
+ t: Src<A> := s
27
+ vs.map(|v| Boxed.of(t, v))
28
+
29
+ fun aStaticInAGenericClosure() =
30
+ xs := GenericStaticTraitValueTest.wrapAll<Int, Twice>(Twice(k: 3), Cons(1, Cons(2, Nil)))
31
+ assert xs.fold(0, |acc, x| acc + x.area()) == 9