plum

#treesitter#compiler#wasm

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

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


a39a0c4 — Peter John 2026-11-16T17:32:00+05:30
T7 compiler review fixes: cell reuse and uniqueness never trust a static called through a type parameter (`T.bump(v)` with `T` a type parameter, `Self` or a trait may be any type's `bump`: reuse drops every candidate static of that name, uniqueness's static-as-value escape covers every owner's and `methodRecvKnown` no longer moves such a call to a `$unique` version; closure_spec, closure_escape and the purity lookups fail safe); a `[UnitTest]` fun is a test only without parameters and without a return type (or `-> Unit`), so `fun sample() -> Graph` is a helper; a static of a generic type used as a value is a checker error (`static 'Holder.twice' of the generic type 'Holder' can't be used as a value`), not a codegen error; uniqueness's bounded-parameter stamp (`boundedParams`) leaves out every name bound again in the body through the renamer: closure parameters and loop binders too; an imported `[App]` file's entry points (`main`, `export fun`s) become statics again, not exported, and the file's bare calls of them are qualified (`main()` is `Game1.main()`, not the program's main; parser `qualifyStaticCalls`); the same test name in two files is an error naming both; a list literal's `plain` excludes `/`, `%` and interpolations, so the item runs first; `[Show]` on a field holding a function or a trait object without `toStr` (in a type argument too) is an error at the type; the parse cache's folder stem is the executable's stem and a hash of its full path (`plum.1a2b3c4d`), so a debug and a release build sharing PLUM_CACHE_DIR don't prune each other. Checked, no change: field defaults of generic owners are checked at the declaration (`TNamed(owner)` is the owner marker every OWNER_KEY use reads); constructions run their written values in written order, then the defaults in declaration order (docs now say so). Tests: e2e_mem/reuse static_through_a_type_parameter_not_reused, tests/fbip/reuse_through_type_param.plum, tests_lower aZeroParameterFunWithAResultIsAHelper, review_tests a_static_of_a_generic_type_is_not_a_value, uniqueness_fold aShadowingClosureParamOrLoopBinderIsNotTheBoundedParam, modules_tests an_imported_apps_entry_points_are_statics_and_its_bare_calls_name_them, loader aTestOfTheSameNameInTwoFilesIsAnError, list_literal aDivisionOrAnInterpolationAfterAConditionalItemKeepsTheOrder, diagnostic_tests showRefusesFunctionsAndTraitsWithoutToStr and aGenericTypesFieldDefaultIsCheckedAtTheDefault, parse_cache twoExecutablesOfOneNameDoNotPruneEachOther. Docs: language.md (tests: no return type, one name per program; statics of generic types as values; defaults' order), tools.md (tests, cache folders), std.md, std/Test.plum, the CLI's help
compiler/checker/src/infer.rs CHANGED
@@ -766,13 +766,15 @@ pub(crate) fn inferExprInner(
766
766
  ast::AttrKind::Field(field_name) if isTraitObject(&obj_ty) => Err(format!(
767
767
  "no field '{field_name}' on {obj_ty}: a trait object has only its trait's methods; match `Type as x` to read a type's fields"
768
768
  )),
769
- // `Type.f` without a call of an extern or generic static: codegen can't make a
769
+ // `Type.f` without a call of an extern or generic static, or of a static of a
770
+ // generic type (`Holder<T>`): codegen can't make a closure of a host call or of a
770
- // closure of a host call or of a fn with no one type (as for a free fn above).
771
+ // fn with no one type (as for a free fn above).
771
772
  ast::AttrKind::Field(field_name)
772
773
  if on_type
773
774
  && methodReceiverName(&obj_ty).is_some_and(|c| {
774
775
  ctx.statics.is_some_and(|st| st.contains(&(c.clone(), field_name.clone())))
775
776
  && (withCheck(|s| s.extern_fns.borrow().contains(&format!("{c}{}{field_name}", ast::MEMBER_SEP)))
777
+ || !enumGenericsOf(&c, ctx).is_empty()
776
778
  || withCheck(|s| s.fn_generics.borrow().get(&(Some(c.clone()), field_name.clone())).is_some_and(|g| !g.is_empty())))
777
779
  }) =>
778
780
  {
@@ -782,6 +784,10 @@ pub(crate) fn inferExprInner(
782
784
  Err(format!(
783
785
  "extern function '{shown}' can't be used as a value: it is a host call, not a Plum function; wrap it in a closure, e.g. `|io| {shown}(io)`"
784
786
  ))
787
+ } else if !enumGenericsOf(&class, ctx).is_empty() {
788
+ Err(format!(
789
+ "static '{shown}' of the generic type '{class}' can't be used as a value: it is compiled once per type argument; wrap it in a closure, e.g. `|x| {shown}(x)`"
790
+ ))
785
791
  } else {
786
792
  Err(format!(
787
793
  "generic function '{shown}' can't be used as a value: its type is only known where it is called; wrap it in a closure, e.g. `|x| {shown}(x)`"
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -308,6 +308,21 @@ fn frontErrors(src: &str) -> Vec<plum_core::diag::Diagnostic> {
308
308
  plum_core::lower::frontEndDiag(&mut source).expect_err("front end error")
309
309
  }
310
310
 
311
+ /// A generic type's default of a field that doesn't name its `T` is checked at its declaration
312
+ /// too, and may call the type's statics bare or qualified (T7 review).
313
+ #[test]
314
+ fn aGenericTypesFieldDefaultIsCheckedAtTheDefault() {
315
+ let es = errors("struct P<T>(x: T, y: Int = \"no\")\n\nprimitive Main[App] =\n fun main() -> Int = P(x: 1, y: 2).y\n");
316
+ assert_eq!(es.len(), 1, "{es:?}");
317
+ assert!(es[0].message.contains("struct 'P': default of field 'y'"), "{es:?}");
318
+ assert_eq!(es[0].line, 1, "{es:?}");
319
+ let mut fine = plum_test_support::parseRawSource("struct P<T>(x: T, y: Int = zero(), z: Int = P.zero()) =\n fun zero() -> Int = 0\n\nprimitive Main[App] =\n fun main() -> Int = P(x: \"s\").y\n");
320
+ plum_core::lower::frontEndDiag(&mut fine).expect("front end");
321
+ if let Err(es) = checkSource(&fine) {
322
+ panic!("{:?}", es.iter().map(|e| &e.message).collect::<Vec<_>>());
323
+ }
324
+ }
325
+
311
326
  /// A field default is checked at its declaration, whether a construction uses it or not.
312
327
  #[test]
313
328
  fn fieldDefaultMismatchIsAtTheDefault() {
@@ -434,6 +449,24 @@ fn showNeedsEachFieldShown() {
434
449
  assert_eq!(es[0].line, 6, "{es:?}");
435
450
  }
436
451
 
452
+ /// `[Show]` on a field holding a function, or a trait object whose trait has no `toStr` (in a type
453
+ /// argument too: `List<Tr>`), is an error at the type, not in the derived `toStr`
454
+ /// or codegen; a trait with `toStr` and a type parameter's field are shown (T7 review).
455
+ #[test]
456
+ fn showRefusesFunctionsAndTraitsWithoutToStr() {
457
+ let pre = "trait Show =\n fun toStr(self) -> Str\n\ntrait Tr =\n fun n(self) -> Int\n\ntrait Named[Show] =\n fun n(self) -> Int\n\n";
458
+ let main = "\nprimitive Main[App] =\n fun main() -> Int = 1\n";
459
+ let es = frontErrors(&format!("{pre}struct F[Show](k: Int, f: fn(Int) -> Int)\n{main}"));
460
+ assert_eq!(es.len(), 1, "{es:?}");
461
+ assert!(es[0].message.contains("`F` lists `Show`, but its field `f: fn(Int) -> Int` can't be put in a string"), "{es:?}");
462
+ assert_eq!(es[0].line, 10, "{es:?}");
463
+ let es = frontErrors(&format!("{pre}enum E[Show] =\n | A(t: Tr)\n | B(o: List<Tr>)\n{main}"));
464
+ assert_eq!(es.len(), 1, "{es:?}");
465
+ assert!(es[0].message.contains("`t: Tr` and `o: List<Tr>` can't be put in a string"), "{es:?}");
466
+ let mut fine = plum_test_support::parseRawSource(&format!("{pre}struct N[Show](t: Named)\n\nstruct G<T>[Show](v: T)\n{main}"));
467
+ plum_core::lower::frontEndDiag(&mut fine).expect("a trait with `toStr` and a type parameter are shown");
468
+ }
469
+
437
470
  /// `@stepsWhen` goes on a field holding actors of a screen, or of a `[Steps]` actor, whose
438
471
  /// stepping is derived.
439
472
  #[test]
@@ -457,3 +490,4 @@ fn anUnknownFieldAttributeIsAnError() {
457
490
  let es = errors(&format!("{STEPS_TRAITS}struct P[Screen](@later(1) w: W) =\n fun name(self) -> Str = \"p\"\n\nprimitive Main[App] =\n fun main() -> Int = 1\n"));
458
491
  assert!(es.iter().any(|e| e.message.contains("`@later` is not a field attribute")), "{es:?}");
459
492
  }
493
+
compiler/checker/tests/checker/modules_tests.rs CHANGED
@@ -198,6 +198,42 @@ fn an_imported_apps_main_is_a_static() {
198
198
  checkProgram(&loaded).0.unwrap();
199
199
  }
200
200
 
201
+ /// Every entry point of an imported `[App]` file is a static again, not exported (`Game1.ping`),
202
+ /// and the file's bare calls of them name them: `main()` in `Game1.again` is `Game1.main()`,
203
+ /// not the program's `main` (T7 review).
204
+ #[test]
205
+ fn an_imported_apps_entry_points_are_statics_and_its_bare_calls_name_them() {
206
+ let dir = std::env::temp_dir().join(format!("plum_modules_imported_entries_{}", std::process::id()));
207
+ std::fs::create_dir_all(&dir).unwrap();
208
+ std::fs::write(
209
+ dir.join("game.plum"),
210
+ "import std/Int\nimport std/App\nprimitive Game1[App] =\n fun main() -> Int = 40\n\n export fun ping() -> Int = 7\n\n fun again() -> Int = main() + ping()\n",
211
+ )
212
+ .unwrap();
213
+ let path = dir.join("main.plum");
214
+ std::fs::write(&path, "import std/Int\nimport game\nimport std/App\nprimitive Driver[App] =\n fun main() -> Int = Game1.again() + Game1.ping()\n").unwrap();
215
+ let loaded = plum_core::loadAndMergeDiag(&path, &plum_test_support::repoRoot());
216
+ let _ = std::fs::remove_dir_all(&dir);
217
+ let loaded = loaded.unwrap();
218
+ let fnNamed = |n: &str| {
219
+ loaded
220
+ .items
221
+ .iter()
222
+ .find_map(|i| match i {
223
+ plum_core::ast::Item::Fn(f) if f.name == n && f.file.ends_with("game.plum") => Some(f.clone()),
224
+ _ => None,
225
+ })
226
+ .unwrap_or_else(|| panic!("no {n}"))
227
+ };
228
+ let ping = fnNamed("ping");
229
+ assert_eq!(ping.type_param.as_deref(), Some("Game1"));
230
+ assert!(!ping.is_export);
231
+ let again = format!("{:?}", fnNamed("again").body);
232
+ assert!(!again.contains("FnCall(FnCall { name: \"main\""), "{again}");
233
+ assert!(again.matches("TypeName(\"Game1\")").count() == 2, "{again}");
234
+ checkProgram(&loaded).0.unwrap();
235
+ }
236
+
201
237
  /// One way to write a constant: `const Name = value`; the bare form points at `const`.
202
238
  #[test]
203
239
  fn a_constant_without_const_is_an_error() {
compiler/checker/tests/checker/review_tests.rs CHANGED
@@ -240,3 +240,15 @@ fn two_statements_on_one_line_are_a_parse_error() {
240
240
  assert!(e.contains(&format!("unexpected {tok}: a statement can't follow another on the same line")), "{body}: {e}");
241
241
  }
242
242
  }
243
+
244
+ /// A static of a generic type is compiled once per type argument, so it has no one fn to
245
+ /// name as a value: a checker error, never a codegen error or a panic (T7 review).
246
+ #[test]
247
+ fn a_static_of_a_generic_type_is_not_a_value() {
248
+ let e = errorWith(
249
+ "struct Holder<T>(item: T) =\n fun twice(n: Int) -> Int = n * 2\n\nprimitive Main =\n fun apply(f: fn(Int) -> Int, n: Int) -> Int = f(n)\n\n fun k() -> Int = apply(Holder.twice, 3)",
250
+ "static 'Holder.twice' of the generic type 'Holder' can't be used as a value",
251
+ );
252
+ assert!(e.message.contains("`|x| Holder.twice(x)`"), "{e:?}");
253
+ ok("struct Holder<T>(item: T) =\n fun twice(n: Int) -> Int = n * 2\n\nprimitive Main =\n fun apply(f: fn(Int) -> Int, n: Int) -> Int = f(n)\n\n fun k() -> Int = apply(|x| Holder.twice(x), 3)");
254
+ }
compiler/cli/src/main.rs CHANGED
@@ -137,7 +137,7 @@ enum Command {
137
137
  lib_path: Option<std::path::PathBuf>,
138
138
  },
139
139
  /// Compile a Plum source file's (or every file under one or more
140
- /// directories') tests (`primitive XTest[UnitTest]`'s funs without parameters) and run them under wasmtime
140
+ /// directories') tests (`primitive XTest[UnitTest]`'s funs without parameters and return type) and run them under wasmtime
141
141
  Test {
142
142
  /// One or more source files and/or directories (searched recursively for *.plum files)
143
143
  #[arg(required = true)]
compiler/core/src/ast.rs CHANGED
@@ -660,7 +660,8 @@ pub struct Fn {
660
660
  /// the wasm module under its own name, with the `extern fun` boundary ABI.
661
661
  /// Top level only: never a method, never generic, never an error union result.
662
662
  pub is_export: bool,
663
+ /// A test: a fun without parameters or return type (or `-> Unit`) of a
663
- /// A test: a fun without parameters of a `primitive XTest[UnitTest]` (a static, `XTest.fun`).
664
+ /// `primitive XTest[UnitTest]` (a static, `XTest.fun`).
664
665
  /// It may use `io` when std/Io is loaded. `plum test` runs the entry file's tests
665
666
  /// (`tests_lower`); other builds drop them.
666
667
  pub is_test: bool,
compiler/core/src/field_defaults.rs CHANGED
@@ -2,8 +2,9 @@
2
2
  //! and the same on an enum variant's named fields (`| Rect(w: Int, fill: Color = Color.White)`).
3
3
  //!
4
4
  //! A construction that leaves out a field with a default (`Label(x: 16.0, text: "Score")`)
5
- //! gets a fresh copy of the default as that field's value, after the fields it writes, so a
5
+ //! gets a fresh copy of the default as that field's value, after the fields it writes (which
6
+ //! run in the order they are written), the defaults in the order their fields are declared, so
6
- //! default is evaluated at each construction, in the caller, like a parameter's default at a
7
+ //! a default is evaluated at each construction, in the caller, like a parameter's default at a
7
8
  //! call. `Held()` with no arguments counts as a construction. A construction with a spread
8
9
  //! (`Label(..l, text: "x")`) takes the fields it leaves out from its source, as before, and a
9
10
  //! pattern is unaffected. A default sees what is global: types, variants, consts and statics
@@ -68,7 +69,7 @@ fn freeLocals(e: &Expr) -> Vec<String> {
68
69
  }
69
70
 
70
71
  /// Adds the fields `c` leaves out that have a default, each a fresh copy, after the fields
71
- /// it writes. A construction with a spread is left alone.
72
+ /// it writes, in the order the fields are declared. A construction with a spread is left alone.
72
73
  fn fillCall(c: &mut ClassCall, ds: &Defaults) {
73
74
  if c.spread.is_some() {
74
75
  return;
compiler/core/src/list_items.rs CHANGED
@@ -13,9 +13,9 @@
13
13
  //!
14
14
  //! * when `rest` is `Nil` (the item is last) it is written twice: `if c then Cons(head: x, tail:
15
15
  //! Nil) else Nil`;
16
- //! * when the item and every item of `rest` are plain (no call: a variable, a field, a
16
+ //! * when the item and every item of `rest` are plain (no call and no trap: a variable, a
17
- //! literal, a constructor, an operator or an interpolation of those), nothing runs that
17
+ //! field, a literal, a constructor or an operator other than `/` and `%` of those), nothing
18
- //! could tell the order: `{ __li1 := rest; if c then Cons(head: x, tail: __li1) else __li1 }`;
18
+ //! runs that could tell the order: `{ __li1 := rest; if c then Cons(head: x, tail: __li1) else __li1 }`;
19
19
  //! * else the item runs first as an `Option`: `(if c then Some(value: x) else None).spreadOnto(rest)`
20
20
  //! (`if c then ..xs` binds `xs` in a `Some` the same way and spreads it in a `match`).
21
21
  use crate::ast::*;
@@ -31,18 +31,15 @@ pub enum ListItem {
31
31
  If(Expr, Box<ListItem>),
32
32
  }
33
33
 
34
- /// Whether running `e` can't be seen by other code: no call, no block, nothing that binds.
34
+ /// Whether running `e` can't be seen by other code: no call, no block, nothing that binds,
35
- /// A constructor (`Label(..)`, `Some(v)`) builds a value; an interpolation calls `toStr`,
35
+ /// nothing that traps. A constructor (`Label(..)`, `Some(v)`) builds a value; `/` and `%` trap
36
- /// which is taken to be plain.
36
+ /// on a zero divisor and an interpolation calls `toStr`, so they are not plain.
37
37
  fn plain(e: &Expr) -> bool {
38
38
  match &e.kind {
39
39
  ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::BoolLit(_) | ExprKind::Self_ | ExprKind::Var(_) | ExprKind::TypeName(_) => true,
40
40
  ExprKind::Closure(_) => true,
41
- ExprKind::String(s) => s.parts.iter().all(|p| match p {
41
+ ExprKind::String(s) => s.parts.iter().all(|p| matches!(p, StringPart::Text(_))),
42
- StringPart::Text(_) => true,
43
- StringPart::Interp(e) => plain(e),
44
- }),
45
- ExprKind::Binary(b) => plain(&b.left) && plain(&b.right),
42
+ ExprKind::Binary(b) => !matches!(b.op, BinOp::Div | BinOp::Mod) && plain(&b.left) && plain(&b.right),
46
43
  ExprKind::Unary(u) => plain(&u.operand),
47
44
  ExprKind::Bool(b) => plain(&b.left) && plain(&b.right),
48
45
  ExprKind::Not(e) => plain(e),
compiler/core/src/loader.rs CHANGED
@@ -436,20 +436,33 @@ fn oneApp(files: &[Loaded]) -> Loaded_<()> {
436
436
  }
437
437
 
438
438
  /// The program's `main` is the entry file's. An imported file's `[App]` primitive (a test or
439
- /// driver importing a game's main file) keeps its `main` as an ordinary static (`Hello.main`).
439
+ /// driver importing a game's main file) keeps its entry points (`main`, its `export fun`s) as
440
+ /// ordinary statics (`Hello.main`), not exported, and its file's bare calls of them name them
441
+ /// (`main()` is `Hello.main()`, not the program's `main`).
440
442
  fn importedMainsAreStatics(files: &mut [Loaded]) {
441
443
  for f in files.iter_mut().skip(1) {
442
444
  let Some(app) = f.source.primitives.iter().find(|p| p.implements.iter().any(|t| t == APP_TRAIT)) else {
443
445
  continue;
444
446
  };
445
447
  let app = app.name.clone();
448
+ let mut entries: Vec<String> = Vec::new();
446
449
  for item in &mut f.source.items {
447
450
  if let Item::Fn(func) = item {
448
- if func.type_param.is_none() && func.name == "main" && func.column > 1 {
451
+ if func.type_param.is_none() && (func.name == "main" || func.is_export) && !func.has_self && func.column > 1 {
449
452
  func.type_param = Some(app.clone());
453
+ func.is_export = false;
454
+ entries.push(func.name.clone());
450
455
  }
451
456
  }
452
457
  }
458
+ if entries.is_empty() {
459
+ continue;
460
+ }
461
+ for item in &mut f.source.items {
462
+ if let Item::Fn(func) = item {
463
+ crate::parser::qualifyStaticCalls(func, &app, &entries);
464
+ }
465
+ }
453
466
  }
454
467
  }
455
468
 
@@ -1114,9 +1127,9 @@ fn mergeItems(
1114
1127
  );
1115
1128
  let mut test_names: HashMap<String, usize> = HashMap::new();
1116
1129
  for item in &source.items {
1117
- // Tests aren't global symbols (nothing calls them), so identically-named
1118
- // tests in different files aren't a real conflict. Within one file the
1119
- // name is the test's export: two would be one wasm export twice.
1130
+ // A test's name (`XTest.a`) is its export and its label in reports: one per program,
1131
+ // whether the two are in one file or in two (a file importing another's tests, whose
1132
+ // `XTest` would merge with its own).
1120
1133
  if let Item::Fn(t @ crate::ast::Fn { is_test: true, .. }) = item {
1121
1134
  let name = format!("{}.{}", t.type_param.as_deref().unwrap_or_default(), t.name);
1122
1135
  if let Some(first) = test_names.insert(name.clone(), t.line) {
@@ -1128,6 +1141,17 @@ fn mergeItems(
1128
1141
  format!("duplicate test {name}: a test of this name is already at line {first}"),
1129
1142
  )]);
1130
1143
  }
1144
+ let key = format!("test {name}");
1145
+ if let Some(other) = names.get(&key) {
1146
+ return Err(vec![Diagnostic::new(
1147
+ DiagKind::Resolution,
1148
+ displayPath(file),
1149
+ t.line,
1150
+ t.column,
1151
+ format!("duplicate test {name}: declared in both '{}' and '{}': rename one test primitive", displayPath(other), displayPath(file)),
1152
+ )]);
1153
+ }
1154
+ names.insert(key, file.to_path_buf());
1131
1155
  items.push(item.clone());
1132
1156
  continue;
1133
1157
  }
compiler/core/src/parse_cache.rs CHANGED
@@ -117,7 +117,7 @@ impl DiskCache {
117
117
  Some(d) => PathBuf::from(d),
118
118
  None => exe.parent()?.join("plum-cache"),
119
119
  };
120
- let stem = exe.file_stem()?.to_string_lossy().to_string();
120
+ let stem = cacheStem(&exe)?;
121
121
  let dir = root.join(format!("{stem}-{}", hex(hashOf(&compiler))));
122
122
  if !dir.is_dir() {
123
123
  pruneOlder(&root, &stem, &dir);
@@ -163,6 +163,14 @@ impl DiskCache {
163
163
  }
164
164
  }
165
165
 
166
+ /// The name of `exe`'s cache folders, before the build's hash: its file stem and a hash of its
167
+ /// full path (`plum.1a2b3c4d`), so two executables of one name (a debug and a release build)
168
+ /// sharing a `PLUM_CACHE_DIR` keep and prune only their own folders.
169
+ pub fn cacheStem(exe: &Path) -> Option<String> {
170
+ let stem = exe.file_stem()?.to_string_lossy().to_string();
171
+ Some(format!("{stem}.{:08x}", hashOf(exe) as u32))
172
+ }
173
+
166
174
  /// Removes the folders of `stem`'s earlier builds under `root` (all but `keep`).
167
175
  pub fn pruneOlder(root: &Path, stem: &str, keep: &Path) {
168
176
  let Ok(entries) = std::fs::read_dir(root) else { return };
compiler/core/src/parser.rs CHANGED
@@ -163,11 +163,13 @@ impl<'a> AstParser<'a> {
163
163
  let pos = child.start_position();
164
164
  let (mut fns, consts, selfFn) = self.collectBody(child, &name);
165
165
  let implements: Vec<String> = self.parseImplements(child).into_iter().map(|t| t.name).collect();
166
- // A `UnitTest` primitive's funs without parameters are its tests
166
+ // A `UnitTest` primitive's funs without parameters and without a return type
167
- // (`MapTest.anEmptyMap`); the ones with parameters are helpers.
167
+ // (or `-> Unit`) are its tests (`MapTest.anEmptyMap`); the ones with parameters
168
+ // or a result (`fun sample() -> Graph`) are helpers.
168
169
  if implements.iter().any(|t| t == UNIT_TEST_TRAIT) {
169
170
  for f in &mut fns {
171
+ let unit = f.returns.as_ref().is_none_or(|t| t.name == "Unit" && t.generics.is_empty());
170
- f.is_test = f.params.is_empty() && !f.has_self && !f.is_extern;
172
+ f.is_test = f.params.is_empty() && !f.has_self && !f.is_extern && unit;
171
173
  }
172
174
  }
173
175
  if implements.iter().any(|t| t == APP_TRAIT) {
@@ -276,18 +278,7 @@ impl<'a> AstParser<'a> {
276
278
  .map(|n| self.parseConst(n))
277
279
  .collect();
278
280
  for f in &mut fns {
279
- let params: std::collections::HashSet<String> = f.params.iter().map(|p| p.name.clone()).collect();
280
- let mut q = StaticCalls { owner, statics: &statics, scopes: vec![params] };
281
+ qualifyStaticCalls(f, owner, &statics);
281
- for p in &mut f.params {
282
- if let Some(d) = &mut p.default {
283
- q.expr(d);
284
- }
285
- }
286
- match &mut f.body {
287
- FnBody::Block(b) => q.block(b),
288
- FnBody::Expr(e) => q.expr(e),
289
- FnBody::Extern => {}
290
- }
291
282
  }
292
283
  for c in &mut consts {
293
284
  StaticCalls { owner, statics: &statics, scopes: vec![Default::default()] }.expr(&mut c.value);
@@ -2234,6 +2225,23 @@ fn qualifyFieldDefaults(e: &mut Enum, fns: &[Fn], consts: &[Const]) {
2234
2225
  }
2235
2226
  }
2236
2227
 
2228
+ /// Writes `f`'s bare calls of `statics` (statics of `owner`), outside the binders that shadow
2229
+ /// them, as `owner.name(..)`.
2230
+ pub(crate) fn qualifyStaticCalls(f: &mut Fn, owner: &str, statics: &[String]) {
2231
+ let params: std::collections::HashSet<String> = f.params.iter().map(|p| p.name.clone()).collect();
2232
+ let mut q = StaticCalls { owner, statics, scopes: vec![params] };
2233
+ for p in &mut f.params {
2234
+ if let Some(d) = &mut p.default {
2235
+ q.expr(d);
2236
+ }
2237
+ }
2238
+ match &mut f.body {
2239
+ FnBody::Block(b) => q.block(b),
2240
+ FnBody::Expr(e) => q.expr(e),
2241
+ FnBody::Extern => {}
2242
+ }
2243
+ }
2244
+
2237
2245
  struct StaticCalls<'a> {
2238
2246
  owner: &'a str,
2239
2247
  statics: &'a [String],
compiler/core/src/reuse.rs CHANGED
@@ -4,8 +4,9 @@
4
4
  //! tail constructor of the same variant may overwrite that cell (`ClassCall.reuse`)
5
5
  //! instead of allocating. Everything unclear stays an allocation. The proof:
6
6
  //!
7
- //! * `f` is a free, non-exported, uniquely named fn, never used as a value or a method name,
7
+ //! * `f` is a free, non-exported, uniquely named fn (or a static `T.f`), never used as a value or
8
+ //! a method name, nor called through a type parameter, `Self` or a trait (`S.f(..)` may be any
8
- //! with no closures and no loops; `xs` is a plain parameter without default, never rebound
9
+ //! type's `f`), with no closures and no loops; `xs` is a plain parameter without default, never rebound
9
10
  //! or shadowed, whose only use in `f` is as the subject of the `match` that is `f`'s last
10
11
  //! statement.
11
12
  //! * Every call of `f` passes, for `xs`, a deeply fresh value (a constructor tree of scalars and
@@ -136,6 +137,40 @@ pub fn markReuse(src: &mut Source) -> Vec<String> {
136
137
  _ => None,
137
138
  })
138
139
  .collect();
140
+ // A static by its bare name: `T.f(..)` or `T.f` with `T` a type parameter (declared or an
141
+ // implicit single letter), `Self` or a trait may call any type's static `f`, so it rules out
142
+ // every candidate static named `f`.
143
+ let mut byMember: HashMap<String, Vec<usize>> = HashMap::new();
144
+ for (ci, c) in cands.iter().enumerate() {
145
+ if let Item::Fn(f) = &src.items[c.item] {
146
+ if f.type_param.is_some() {
147
+ byMember.entry(f.name.clone()).or_default().push(ci);
148
+ }
149
+ }
150
+ }
151
+ let traits: std::collections::HashSet<&str> = src
152
+ .items
153
+ .iter()
154
+ .filter_map(|it| match it {
155
+ Item::Trait(t) => Some(t.name.as_str()),
156
+ _ => None,
157
+ })
158
+ .collect();
159
+ let mut concrete: std::collections::HashSet<String> = std::collections::HashSet::new();
160
+ for it in &src.items {
161
+ match it {
162
+ Item::Enum(e) => {
163
+ concrete.insert(e.name.clone());
164
+ }
165
+ Item::Fn(f) => {
166
+ if let Some(t) = &f.type_param {
167
+ concrete.insert(t.clone());
168
+ }
169
+ }
170
+ _ => {}
171
+ }
172
+ }
173
+ concrete.retain(|t| !traits.contains(t.as_str()) && t != SELF_TYPE);
139
174
  // Per candidate: the match's pattern binders bound once in it.
140
175
  let inners: Vec<Vec<String>> = cands
141
176
  .iter()
@@ -180,6 +215,15 @@ pub fn markReuse(src: &mut Source) -> Vec<String> {
180
215
  // `T.f(..)` calls the static `T.f`, checked as a call of a free fn is; `T.f`
181
216
  // without a call is the static as a value, whose callers are unknown.
182
217
  if let ExprKind::TypeName(t) = &a.object.kind {
218
+ if !concrete.contains(t.as_str()) {
219
+ let member = match &a.attr {
220
+ AttrKind::Method(mc) => &mc.name,
221
+ AttrKind::Field(n) => n,
222
+ };
223
+ for &ci in byMember.get(member).into_iter().flatten() {
224
+ ok[ci] = false;
225
+ }
226
+ }
183
227
  match &a.attr {
184
228
  AttrKind::Method(mc) => {
185
229
  if let Some(&ci) = byName.get(&format!("{t}{MEMBER_SEP}{}", mc.name)) {
compiler/core/src/show_derive.rs CHANGED
@@ -15,8 +15,11 @@
15
15
  //! that writes its own `toStr` keeps it. A variant the loader renamed in a clash (`Tick@menu`,
16
16
  //! as two files declare `Tick`) is shown by the name it was written with (`Tick(..)`).
17
17
  //!
18
- //! Error, at the type: a field whose type is a struct or an enum of the program that has no
18
+ //! Errors, at the type: a field whose type is a struct or an enum of the program that has no
19
- //! `toStr` and doesn't list `Show` (it couldn't be put in the string).
19
+ //! `toStr` and doesn't list `Show`, and a field holding a function or a trait object whose
20
+ //! trait has no `toStr` (they couldn't be put in the string). A field of a type parameter
21
+ //! (`struct Box<T>[Show](v: T)`) is shown as its type argument is, checked where `toStr` is
22
+ //! used with one.
20
23
 
21
24
  use crate::ast::*;
22
25
  use crate::diag::{DiagKind, Diagnostic};
@@ -59,6 +62,28 @@ pub fn deriveShow(source: &mut Source) -> Vec<Diagnostic> {
59
62
  .filter(|(_, t)| declared(&t.name) && !hasToStr(&t.name))
60
63
  .map(|(f, t)| format!("`{f}: {}`", t.name))
61
64
  .collect();
65
+ // A function, or a trait object whose trait has no `toStr`, can't be put in a string
66
+ // (in the field's type itself or an argument of it: `List<Tr>`).
67
+ let never: Vec<String> = e
68
+ .variants
69
+ .iter()
70
+ .flat_map(|v| v.field_names.iter().zip(&v.fields))
71
+ .filter(|(_, t)| neverShown(t, &source.items))
72
+ .map(|(f, t)| format!("`{f}: {}`", typeText(t)))
73
+ .collect();
74
+ if !never.is_empty() {
75
+ errors.push(Diagnostic::new(
76
+ DiagKind::Type,
77
+ e.file.clone(),
78
+ e.line,
79
+ e.column,
80
+ format!(
81
+ "`{name}` lists `Show`, but its field {} can't be put in a string (a function, or a trait without `toStr`): give `{name}` its own `fun toStr(self) -> Str`",
82
+ never.join(" and ")
83
+ ),
84
+ ));
85
+ continue;
86
+ }
62
87
  if !unshown.is_empty() {
63
88
  errors.push(Diagnostic::new(
64
89
  DiagKind::Type,
@@ -124,6 +149,44 @@ pub fn deriveShow(source: &mut Source) -> Vec<Diagnostic> {
124
149
  errors
125
150
  }
126
151
 
152
+ /// Whether a value of type `t` can never be interpolated: a function type, or a trait whose
153
+ /// methods (its supertraits' included) have no `toStr`, in `t` or in one of its type arguments.
154
+ fn neverShown(t: &Type, items: &[Item]) -> bool {
155
+ if t.name == FN_TYPE_NAME {
156
+ return true;
157
+ }
158
+ if let Some(tr) = items.iter().find_map(|i| match i {
159
+ Item::Trait(tr) if tr.name == t.name => Some(tr),
160
+ _ => None,
161
+ }) {
162
+ if !traitHasToStr(tr, items, 0) {
163
+ return true;
164
+ }
165
+ }
166
+ t.generics.iter().any(|g| neverShown(g, items))
167
+ }
168
+
169
+ fn traitHasToStr(tr: &Trait, items: &[Item], depth: usize) -> bool {
170
+ tr.methods.iter().any(|m| m.sig.name == "toStr")
171
+ || (depth < 16
172
+ && tr.supers.iter().any(|s| {
173
+ items.iter().any(|i| matches!(i, Item::Trait(st) if st.name == s.name && traitHasToStr(st, items, depth + 1)))
174
+ }))
175
+ }
176
+
177
+ /// `t` as written: `fn(Int) -> Int`, `List<Tr>`.
178
+ fn typeText(t: &Type) -> String {
179
+ if t.name == FN_TYPE_NAME {
180
+ let (ret, params) = t.generics.split_last().map_or((String::new(), &[][..]), |(r, ps)| (typeText(r), ps));
181
+ return format!("fn({}) -> {ret}", params.iter().map(typeText).collect::<Vec<_>>().join(", "));
182
+ }
183
+ if t.generics.is_empty() {
184
+ t.name.clone()
185
+ } else {
186
+ format!("{}<{}>", t.name, t.generics.iter().map(typeText).collect::<Vec<_>>().join(", "))
187
+ }
188
+ }
189
+
127
190
  /// Gives each pattern of the derived `match` that names a renamed variant by its source name
128
191
  /// the variant's renamed one (`Tick` to `Tick@menu`): the text the derive parses can't spell it.
129
192
  fn renamePatterns(b: &mut Block, renamed: &HashMap<String, String>) {
compiler/core/src/uniqueness.rs CHANGED
@@ -604,7 +604,34 @@ fn fieldKey(owner: &str, f: &str) -> String {
604
604
  format!("{owner}.{f}")
605
605
  }
606
606
 
607
+ /// `f`'s parameters typed by a bounded type parameter (`s: S` with `S: Tr`), each with its first
608
+ /// bound: a method call on one runs a method of the bound's implementers. A name bound again in
609
+ /// `body` (a local, `x = v`, a pattern binder, a closure parameter, a loop binder) is left out, as
610
+ /// a call on it may be on another value.
611
+ pub fn boundedParams(f: &Fn, body: &Block) -> HashMap<String, String> {
612
+ let mut rebound: HashSet<String> = HashSet::new();
613
+ renameStmts(&mut body.stmts.clone(), &mut |n, kind| {
614
+ if kind != crate::rename::Name::Ref {
615
+ rebound.insert(n.clone());
616
+ }
617
+ });
618
+ f.params
619
+ .iter()
620
+ .filter_map(|p| {
621
+ let ParamType::Type(t) = &p.ty else { return None };
622
+ let b = f.bounds.iter().find(|(g, _)| *g == t.name).and_then(|(_, bs)| bs.first())?;
623
+ (!rebound.contains(&p.name)).then(|| (p.name.clone(), b.name.clone()))
624
+ })
625
+ .collect()
626
+ }
627
+
607
628
  impl An {
629
+ /// `t` (the object of `t.f(..)`) is a type that owns fns, not a type parameter, `Self` or a
630
+ /// trait, whose `t.f` may be any type's `f`.
631
+ fn isOwner(&self, t: &str) -> bool {
632
+ !self.traits.contains(t) && t != SELF_TYPE && self.units.iter().any(|u| u.ty.as_deref() == Some(t))
633
+ }
634
+
608
635
  /// The declared type of `e` in `unit`, when it can be read off the program: `self`, a parameter
609
636
  /// or a local bound once to a constructor, a constructor, and a field of one of those. Anything
610
637
  /// else (a call result, a generic field) is unknown, and then the field tables treat a read or
@@ -2415,41 +2442,7 @@ fn build(src: &Source, distrust: &HashSet<String>) -> An {
2415
2442
  let paramBound: Vec<HashMap<String, String>> = units
2416
2443
  .iter()
2417
2444
  .map(|u| match (&u.kind, &src.items[u.itemIdx]) {
2418
- (Kind::Fn, Item::Fn(f)) => {
2445
+ (Kind::Fn, Item::Fn(f)) => boundedParams(f, &u.block),
2419
- // Names bound again in the body (a local, a pattern binder) are left out.
2420
- let mut rebound: HashSet<String> = HashSet::new();
2421
- walkBlock(&u.block, &mut |n| {
2422
- match n {
2423
- Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
2424
- for t in &a.targets {
2425
- if let AssignTarget::Var(v) = t {
2426
- rebound.insert(v.clone());
2427
- }
2428
- }
2429
- }
2430
- Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
2431
- let mut names = vec![];
2432
- m.cases.iter().flat_map(|c| &c.patterns).for_each(|p| crate::visit::patternBinders(p, &mut names));
2433
- rebound.extend(names);
2434
- }
2435
- Node::E(Expr { kind: ExprKind::Bind(b), .. }) => {
2436
- let mut names = vec![];
2437
- b.case.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
2438
- rebound.extend(names);
2439
- }
2440
- _ => {}
2441
- }
2442
- true
2443
- });
2444
- f.params
2445
- .iter()
2446
- .filter_map(|p| {
2447
- let ParamType::Type(t) = &p.ty else { return None };
2448
- let b = f.bounds.iter().find(|(g, _)| *g == t.name).and_then(|(_, bs)| bs.first())?;
2449
- (!rebound.contains(&p.name)).then(|| (p.name.clone(), b.name.clone()))
2450
- })
2451
- .collect()
2452
- }
2453
2446
  _ => HashMap::new(),
2454
2447
  })
2455
2448
  .collect();
@@ -4021,9 +4014,12 @@ fn collectFacts(an: &mut An) {
4021
4014
  }
4022
4015
  // `T.f` without a call is the static `f` as a value: its callers are
4023
4016
  // unknown, as a free fn's are when it is named as a value.
4017
+ // `T.f` with `T` a type parameter (or `Self`, a trait: no fn's owner) may be
4018
+ // any type's static `f`.
4024
4019
  if let ExprKind::TypeName(t) = &x.object.kind {
4020
+ let owner = a.isOwner(t);
4025
4021
  for (g, u) in a.units.iter().enumerate() {
4026
- if u.kind == Kind::Fn && !u.hasSelf && u.ty.as_deref() == Some(t.as_str()) && &u.name == f {
4022
+ if u.kind == Kind::Fn && !u.hasSelf && (!owner || u.ty.as_deref() == Some(t.as_str())) && &u.name == f {
4027
4023
  escaped.insert(g);
4028
4024
  }
4029
4025
  }
@@ -4595,7 +4591,8 @@ fn methodRecvKnown(an: &An, caller: usize, node: NodeId, src: &Source) -> bool {
4595
4591
  if let ExprKind::Attribute(a) = &e.kind {
4596
4592
  if let AttrKind::Method(c) = &a.attr {
4597
4593
  // A static's call names its type (`Cells.bump(c)`), so it reaches one fn.
4594
+ // `T.f(..)` with `T` a type parameter may reach any type's `f`.
4598
- let onType = matches!(&a.object.kind, ExprKind::TypeName(t) if !an.traits.contains(t));
4595
+ let onType = matches!(&a.object.kind, ExprKind::TypeName(t) if an.isOwner(t));
4599
4596
  known = onType || c.recv.as_ref().is_some_and(|t| !an.traits.contains(t));
4600
4597
  }
4601
4598
  }
compiler/core/tests/core/list_literal_test.rs CHANGED
@@ -97,3 +97,19 @@ fn plainLiteralHasNoError() {
97
97
  let source = plum_test_support::parseRawSource(&main_("m := [1, 2]"));
98
98
  assert!(source.formErrors.is_empty());
99
99
  }
100
+
101
+ /// A conditional item before plain items binds the rest first (`__li := rest`), which runs it
102
+ /// before the item: only when nothing in them can trap or call code. `/` and `%` trap on zero and
103
+ /// an interpolation calls `toStr`, so with one of them the item runs first, as an `Option`
104
+ /// spread onto the rest (T7 review).
105
+ #[test]
106
+ fn aDivisionOrAnInterpolationAfterAConditionalItemKeepsTheOrder() {
107
+ let bound = render(&firstValue(&main_("xs := [if c then a, b + d]")));
108
+ assert!(!bound.contains("spreadOnto"), "{bound}");
109
+ for rest in ["b / d", "b % d", "\"${b}\""] {
110
+ let e = render(&firstValue(&main_(&format!("xs := [if c then a, {rest}]"))));
111
+ assert!(e.contains("spreadOnto"), "{rest}: {e}");
112
+ }
113
+ let e = render(&firstValue(&main_("xs := [if c then a / d, b]")));
114
+ assert!(e.contains("spreadOnto"), "{e}");
115
+ }
compiler/core/tests/core/loader_test.rs CHANGED
@@ -669,3 +669,17 @@ fn aTestFileImportsWhatItTests() {
669
669
  loadAndMergeDiag(&lib.join("tests/x/thing.plum"), &lib).expect("the mirror imports what it tests");
670
670
  loadAndMergeDiag(&other, &lib).expect("another test file imports the source, not its mirror");
671
671
  }
672
+
673
+ /// Two files declaring the same test (`ATest.a`) would merge into one test primitive: an error
674
+ /// that names both files (T7 review).
675
+ #[test]
676
+ fn aTestOfTheSameNameInTwoFilesIsAnError() {
677
+ let dir = TempDir::new().unwrap();
678
+ let lib_path = dir.path().join("libs");
679
+ writeLibFile(&lib_path, "std/Test", "trait UnitTest\n");
680
+ writeLibFile(&lib_path, "tests/other", "import std/Test\n\nprimitive ATest[UnitTest] =\n fun a() =\n Unit\n");
681
+ let entry = writeLibFile(&lib_path, "tests/main", "import std/Test\nimport tests/other\n\nprimitive ATest[UnitTest] =\n fun a() =\n Unit\n");
682
+ let errs = loadAndMergeDiag(&entry, &lib_path).expect_err("a duplicate test");
683
+ let text = errs.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n");
684
+ assert!(text.contains("duplicate test ATest.a: declared in both") && text.contains("other.plum") && text.contains("main.plum"), "{text}");
685
+ }
compiler/core/tests/core/parse_cache_test.rs CHANGED
@@ -146,6 +146,29 @@ fn olderBuildsOfTheSameProgramArePruned() {
146
146
  assert_eq!(left, ["other-0123456789abcdef", "plum-fedcba9876543210", "plum-lsp-0123456789abcdef", "plum-notahash"]);
147
147
  }
148
148
 
149
+ /// A debug and a release `plum` sharing one `PLUM_CACHE_DIR` have stems of their own, so a new
150
+ /// build of one prunes its earlier folders and leaves the other's (T7 review).
151
+ #[test]
152
+ fn twoExecutablesOfOneNameDoNotPruneEachOther() {
153
+ let dir = TempDir::new().unwrap();
154
+ let debug = plum_core::parse_cache::cacheStem(std::path::Path::new("/w/target/debug/plum")).unwrap();
155
+ let release = plum_core::parse_cache::cacheStem(std::path::Path::new("/w/target/release/plum")).unwrap();
156
+ assert_ne!(debug, release);
157
+ assert!(debug.starts_with("plum.") && release.starts_with("plum."), "{debug} {release}");
158
+ let old = format!("{debug}-0123456789abcdef");
159
+ let keep = format!("{debug}-fedcba9876543210");
160
+ let other = format!("{release}-0123456789abcdef");
161
+ for name in [&old, &keep, &other] {
162
+ std::fs::create_dir_all(dir.path().join(name)).unwrap();
163
+ }
164
+ plum_core::parse_cache::pruneOlder(dir.path(), &debug, &dir.path().join(&keep));
165
+ let mut left: Vec<String> = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect();
166
+ left.sort();
167
+ let mut want = vec![keep, other];
168
+ want.sort();
169
+ assert_eq!(left, want);
170
+ }
171
+
149
172
  fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
150
173
  let p = dir.join(format!("{name}.plum"));
151
174
  std::fs::write(&p, text).unwrap();
compiler/core/tests/core/tests_lower_test.rs CHANGED
@@ -39,3 +39,15 @@ fn failureMessageText() {
39
39
  assert!(dbg.contains("\\n Actual: "));
40
40
  assert_eq!(ASSERT_REPORT_MARK, "\u{1}assert-report");
41
41
  }
42
+
43
+ /// A fun without parameters that returns a value is a helper, not a test; `-> Unit` is a test.
44
+ #[test]
45
+ fn aZeroParameterFunWithAResultIsAHelper() {
46
+ let src = plum_test_support::parseRawSource(
47
+ "import std/Test\nprimitive SampleTest[UnitTest] =\n fun a() =\n assert sample() == 2\n\n fun b() -> Unit =\n assert 1 == 1\n\n fun sample() -> Int = 2\n",
48
+ );
49
+ assert!(!fnNamed(&src, "sample").is_test);
50
+ assert!(fnNamed(&src, "b").is_test);
51
+ let p = lowerTests(&src);
52
+ assert_eq!(p.names, vec!["SampleTest.a", "SampleTest.b"]);
53
+ }
compiler/core/tests/core/uniqueness_fold_test.rs CHANGED
@@ -101,3 +101,23 @@ fn aNativeBodyMayKeepWhatItIsGiven() {
101
101
  let r = run("struct Pt(x: Int, y: Int)\nprimitive Main =\n fun keep(p: Pt) = @native\n\n fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n Main.keep(t)\n Pt(..t, y: 1)\n");
102
102
  assert!(!proved(&r, "Main.go:5"), "{r:?}");
103
103
  }
104
+
105
+ /// A closure parameter or a loop binder that shadows a parameter of a bounded type parameter
106
+ /// (`s: S` with `S: Tr`) is not that parameter: a call `s.look(u)` on it may run any `look`, so
107
+ /// it is not resolved among `Tr`'s implementers alone (T7 review).
108
+ #[test]
109
+ fn aShadowingClosureParamOrLoopBinderIsNotTheBoundedParam() {
110
+ let pre = "trait Tr =\n fun look(self, q: Pt) -> Int\nstruct Pt(x: Int, y: Int)\nprimitive Main =\n";
111
+ let bounds = |body: &str| {
112
+ let s = plum_test_support::parseRawSource(&format!("{pre}{body}"));
113
+ let f = s.items.iter().find_map(|i| match i { plum_core::ast::Item::Fn(f) if f.name == "go" => Some(f), _ => None }).expect("go");
114
+ let plum_core::ast::FnBody::Block(b) = &f.body else { panic!("block body") };
115
+ plum_core::uniqueness::boundedParams(f, b)
116
+ };
117
+ let plain = bounds(" fun go<S: Tr>(s: S, ps: List<Pt>) -> Int =\n n := s.look(Pt(x: 0, y: 0))\n n\n");
118
+ assert_eq!(plain.get("s").map(String::as_str), Some("Tr"));
119
+ let closure = bounds(" fun go<S: Tr>(s: S, ps: List<Pt>) -> List<Int> =\n f := |s| s.look(Pt(x: 0, y: 0))\n ps.map(f)\n");
120
+ assert!(closure.is_empty(), "{closure:?}");
121
+ let looped = bounds(" fun go<S: Tr>(s: S, ps: List<Pt>) -> Int =\n n := 0\n for s := range ps\n n = n + s.x\n n\n");
122
+ assert!(looped.is_empty(), "{looped:?}");
123
+ }
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/reuse.rs CHANGED
@@ -163,3 +163,36 @@ primitive Main[App] =
163
163
  ");
164
164
  assert_eq!(runInt("swap_run", &p, true), 71);
165
165
  }
166
+
167
+ /// `T.bump(v)` calls the static `Chain.bump` through a type parameter: its argument is a
168
+ /// shared variable, so `bump`'s matched cell must not be overwritten (T7 review).
169
+ const THROUGH_T: &str = "
170
+ enum Chain =
171
+ | End
172
+ | Link(head: Int, tail: Chain)
173
+
174
+ fun bump(xs: Chain) -> Chain = match xs
175
+ End => End
176
+ Link(h, t) => Link(head: h + 1, tail: t)
177
+
178
+ fun first(self) -> Int = match self
179
+ End => 0
180
+ Link(h, _) => h
181
+
182
+ primitive Main[App] =
183
+ fun twice<T>(v: T) -> T = T.bump(v)
184
+
185
+ fun main() -> Int =
186
+ a := Link(head: 1, tail: End)
187
+ b: Chain := Main.twice(a)
188
+ a.first() * 10 + b.first()
189
+ ";
190
+
191
+ #[test]
192
+ fn static_through_a_type_parameter_not_reused() {
193
+ let p = format!("{PRE}{THROUGH_T}");
194
+ let mut s = load("through_t", &p, false).expect("load");
195
+ let marked = plum_core::reuse::markReuse(&mut s);
196
+ assert!(!marked.iter().any(|l| l.contains("bump")), "{marked:?}");
197
+ assert_eq!(runInt("through_t_run", &p, true), 12);
198
+ }
docs/language.md CHANGED
@@ -181,7 +181,7 @@ primitive Demo[App] =
181
181
 
182
182
  Fields can't change unless they are marked `mut`. A spread, `User(..ann, age: 32)`, makes an updated value, and the compiler writes it in place when the old value isn't used again. The source of a spread can be any expression, such as a call, a constant or a field (`User(..load(), age: 32)`). It runs once, before the values written after it. Constructor values run in the order they are written, not the order the fields are declared.
183
183
 
184
- **Field defaults:** a field may have a default, `name: T = value`. A construction names its fields, and may leave out one with a default: it gets a fresh copy of the default, evaluated at that construction after the values written there, so a `Slice<Int>()` default is a new slice for every value. A construction that leaves out everything is written `Tag()`.
184
+ **Field defaults:** a field may have a default, `name: T = value`. A construction names its fields, and may leave out one with a default: it gets a fresh copy of the default, evaluated at that construction after the values written there (several defaults in the order their fields are declared), so a `Slice<Int>()` default is a new slice for every value. A construction that leaves out everything is written `Tag()`.
185
185
 
186
186
  ```plum
187
187
  import std/App
@@ -203,7 +203,7 @@ primitive Demo[App] =
203
203
  ```
204
204
 
205
205
  - A default sees what is global: types, variants, constants and statics (`Tag.Base`, `Color.White`, `Color.rgb(..)`; a bare `Base` or static call in it is the type's own, as in its methods). It can't name another field, `self` or a local, since it runs in each caller; that is an error at the default.
206
- - A default is typed against its field where it is declared, and again at each construction, so a default of a generic struct's `List<T>` field (`items: List<T> = []`) gets each construction's `T`.
206
+ - A default is typed against its field where it is declared, and again at each construction, so a default of a generic struct's `List<T>` field (`items: List<T> = []`) gets each construction's `T`; one whose field doesn't name `T` is checked where it is declared, as any other.
207
207
  - A field without a default must be given; a spread (`Tag(..a, ..)`) and a pattern (`Tag(text, size, side, marks)`) are unaffected. Defaults that construct each other (`struct A(b: B = B())`, `struct B(a: A = A())`) are an error.
208
208
  - An enum variant's fields may have defaults too: `| Rect(w: Float, fill: Color = Color.White)`.
209
209
 
@@ -594,7 +594,7 @@ Add a type when the compiler can't work one out: `|b: Box| b.get()`. Passing a c
594
594
 
595
595
  `Closures.adder(1)(2)` isn't supported yet, so bind the result to a name first.
596
596
 
597
- A static is a value too (`Closures.apply(Numbers.sign, 5)`), unless it is generic or `extern`: wrap those in a closure, `|x| Ids.id(x)`.
597
+ A static is a value too (`Closures.apply(Numbers.sign, 5)`), unless it is generic, `extern` or a static of a generic type (`Holder<T>`'s): wrap those in a closure, `|x| Ids.id(x)`.
598
598
 
599
599
  ## Generics
600
600
 
@@ -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 `GraphHelpers.sample()`):
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 and without a return type (or with `-> Unit`) is one test, named `<Primitive>.<fun>`; a fun with parameters or a return type is a helper. A test's name is one per program, so two files declaring the same `<Primitive>.<fun>` (one importing the other) are an error. Helpers that return nothing and take no parameters go in another `primitive` of the file, one that does not list `UnitTest` (std's tests keep their helpers in `<Type>Helpers`, as `GraphHelpers.sample()`):
1018
1018
 
1019
1019
  ```plum
1020
1020
  # tests/arith.plum
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 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`.
272
+ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the funs without parameters and return type 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
@@ -8,7 +8,7 @@
8
8
  |---|---|
9
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 without parameters of each `primitive XTest[UnitTest]`) in files and folders |
11
+ | `plum test tests/ file.plum` | Run the tests (the funs without parameters and return type 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 |
@@ -53,7 +53,7 @@ Folders are tested one file per process, as many at once as there are cores (`PL
53
53
  | `--explain-fusion` | Print each optimisation decision and how each struct is stored |
54
54
  | `--no-cache` | Parse every file again: don't read or write the parse cache (any command) |
55
55
 
56
- **The parse cache.** Each file a program imports is parsed once and reused: in memory by every program of one run (`plum check` checks its files side by side, sharing it) and on disk across runs, in `plum-cache/` beside the `plum` executable (`target/debug/plum-cache/` for a build from source). An entry is the file's exact text, its parse and the build of `plum` that wrote it, so an edited file, or a rebuilt `plum`, never reads an old one; a partial or damaged entry is ignored, and a new build of `plum` removes the folder of its earlier one. Only the parse is cached: resolving names and type checking run over the whole program each time, as do the optimisations and code generation, so the output is the same with the cache or without it. The language server keeps the cache in memory only.
56
+ **The parse cache.** Each file a program imports is parsed once and reused: in memory by every program of one run (`plum check` checks its files side by side, sharing it) and on disk across runs, in `plum-cache/` beside the `plum` executable (`target/debug/plum-cache/` for a build from source). An entry is the file's exact text, its parse and the build of `plum` that wrote it, so an edited file, or a rebuilt `plum`, never reads an old one; a partial or damaged entry is ignored, and a new build of `plum` removes the folder of its earlier one (only its own: a debug and a release `plum` sharing a `PLUM_CACHE_DIR` keep separate folders). Only the parse is cached: resolving names and type checking run over the whole program each time, as do the optimisations and code generation, so the output is the same with the cache or without it. The language server keeps the cache in memory only.
57
57
 
58
58
  **Environment variables:**
59
59
 
std/Test.plum CHANGED
@@ -12,8 +12,8 @@ import std/Result
12
12
  #
13
13
  # A test file lives under `tests/` (`tests/std/collections/Map.plum` for
14
14
  # `std/collections/Map.plum`) and holds a `primitive` that lists `UnitTest`. Each of its
15
- # funs without parameters is one test, named `<Primitive>.<fun>`; a fun with parameters
15
+ # funs without parameters and without a return type is one test, named `<Primitive>.<fun>`;
16
- # is a helper. `plum test` runs them all:
16
+ # a fun with parameters or a return type is a helper. `plum test` runs them all:
17
17
  #
18
18
  # primitive MathTest[UnitTest] =
19
19
  # fun addWorks() =
tests/fbip/reuse_through_type_param.plum ADDED
@@ -0,0 +1,44 @@
1
+ import std/Int
2
+ import std/Test
3
+
4
+ # A static called through a type parameter (`T.bump(v)`) may be any type's `bump`: cell reuse
5
+ # and in-place spreads never overwrite the argument the caller still holds.
6
+
7
+ enum Chain =
8
+ | End
9
+ | Link(head: Int, tail: Chain)
10
+
11
+ fun bump(xs: Chain) -> Chain = match xs
12
+ End => End
13
+ Link(h, t) => Link(head: h + 1, tail: t)
14
+
15
+ fun first(self) -> Int = match self
16
+ End => 0
17
+ Link(h, _) => h
18
+
19
+ struct Big(a: Int, b: Int, c: Int, d: Int, e: Int) =
20
+ fun bump(p: Big) -> Big = Big(..p, a: p.a + 10)
21
+
22
+ primitive ReuseThroughTypeParamTest[UnitTest] =
23
+ # a matched cell is not reused when the static is called through a type parameter
24
+ fun aMatchedCellIsNotReusedThroughATypeParameter() =
25
+ a := Link(head: 1, tail: End)
26
+ b: Chain := twice(a)
27
+ assert a.first() == 1
28
+ assert b.first() == 2
29
+
30
+ # a spread is not written in place when the static is called through a type parameter
31
+ fun aSpreadIsNotWrittenInPlaceThroughATypeParameter() =
32
+ a := Big(a: 1, b: 2, c: 3, d: 4, e: 5)
33
+ b: Big := twice(a)
34
+ assert a.a == 1
35
+ assert b.a == 11
36
+
37
+ # a fresh value through a type parameter is bumped as well
38
+ fun aFreshValueThroughATypeParameterIsBumped() =
39
+ b: Big := twice(Big(a: 1, b: 2, c: 3, d: 4, e: 5))
40
+ c: Chain := twice(Link(head: 5, tail: End))
41
+ assert b.a == 11
42
+ assert c.first() == 6
43
+
44
+ fun twice<T>(v: T) -> T = T.bump(v)