plum

#treesitter#compiler#wasm

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

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


21b11e4 — Peter John 2026-11-10T12:30:56+05:30
Diagnostics say which fns they are in; the partial revert reads that
compiler/checker/src/callsites.rs CHANGED
@@ -139,6 +139,12 @@ pub(crate) struct InstState {
139
139
  pub(crate) info: TypedInfo,
140
140
  /// Per instantiation id: the "in X[T] (called at f:l:c): " chain prefix.
141
141
  pub(crate) chains: Vec<String>,
142
+ /// Per instantiation id: the keys of the fns the copy is in, innermost first (its own
143
+ /// item, then its callers' up to the root fn): a `Diagnostic`'s `inFns`.
144
+ pub(crate) fnsOf: Vec<Vec<String>>,
145
+ /// The key of the root fn whose calls `registerCalls` is registering (`None`: a test
146
+ /// block, or a declaration).
147
+ pub(crate) rootFn: Option<String>,
142
148
  pub(crate) queue: std::collections::VecDeque<usize>,
143
149
  pub(crate) file: String,
144
150
  /// Per callee (owner, name): `calleeGenerics`.
@@ -285,6 +291,10 @@ pub(crate) fn registerCalls(
285
291
  })
286
292
  };
287
293
  let parent_chain = parent.map(|p| st.chains[p].clone()).unwrap_or_default();
294
+ let parent_fns: Vec<String> = match parent {
295
+ Some(p) => st.fnsOf[p].clone(),
296
+ None => st.rootFn.iter().cloned().collect(),
297
+ };
288
298
  let depth = parent_chain.matches("(called at").count();
289
299
  for cs in drainCalls() {
290
300
  let Some(f) = fns.get(&(cs.recv.clone(), cs.name.clone())) else {
@@ -339,7 +349,8 @@ pub(crate) fn registerCalls(
339
349
  };
340
350
  if !bounds.is_empty() {
341
351
  if let Some(msg) = unmetBound(&plum_core::diag::sourceName(&item), &gens, &args, &bounds) {
342
- let e = CheckError::at(cs.line, cs.column, format!("{}call '{}': {}", parent_chain, plum_core::diag::sourceName(&cs.name), msg));
352
+ let e = CheckError::at(cs.line, cs.column, format!("{}call '{}': {}", parent_chain, plum_core::diag::sourceName(&cs.name), msg))
353
+ .in_fns(parent_fns.clone());
343
354
  withCheck(|s| s.bound_errors.borrow_mut().push(e));
344
355
  // Not instantiated: its body's errors would only repeat the unmet bound.
345
356
  continue;
@@ -366,6 +377,9 @@ pub(crate) fn registerCalls(
366
377
  cs.line,
367
378
  cs.column
368
379
  ));
380
+ let mut own = vec![item.clone()];
381
+ own.extend(parent_fns.iter().cloned());
382
+ st.fnsOf.push(own);
369
383
  st.info.instantiations.push(Instantiation {
370
384
  id,
371
385
  item,
compiler/checker/src/program.rs CHANGED
@@ -324,6 +324,8 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
324
324
  let mut inst = InstState {
325
325
  info: TypedInfo::default(),
326
326
  chains: Vec::new(),
327
+ fnsOf: Vec::new(),
328
+ rootFn: None,
327
329
  queue: std::collections::VecDeque::new(),
328
330
  file,
329
331
  defaulted: HashMap::new(),
@@ -379,7 +381,12 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
379
381
  // Its open receivers are typed per instantiation.
380
382
  withCheck(|s| s.open_receivers.borrow_mut().truncate(open_before));
381
383
  } else {
384
+ inst.rootFn = Some(plum_core::ast::fnKey(f));
382
385
  registerCalls(&mut inst, &fn_by_key, &ctx, None);
386
+ inst.rootFn = None;
387
+ }
388
+ for e in &mut local_errors {
389
+ e.inFns = vec![plum_core::ast::fnKey(f)];
383
390
  }
384
391
  errors.append(&mut local_errors);
385
392
  }
@@ -459,14 +466,15 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
459
466
  let mut found = None;
460
467
  while let Some(k) = at {
461
468
  if let Some(d) = inst.defaulted.get(&k) {
462
- found = Some(d);
469
+ found = Some((d, k));
463
470
  }
464
471
  at = inst.info.instantiations[k].parent;
465
472
  }
466
473
  found
467
474
  };
468
- if let (Some(d), false) = (defaulted, errs.is_empty()) {
475
+ if let (Some((d, at)), false) = (defaulted, errs.is_empty()) {
476
+ // the call nothing pinned is in the copy's caller
469
- let e = d.error();
477
+ let e = d.error().in_fns(inst.fnsOf[at][1..].to_vec());
470
478
  if seen_msgs.insert(e.message.clone()) {
471
479
  errors.push(e);
472
480
  }
@@ -479,7 +487,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
479
487
  };
480
488
  let full = format!("{}{}", chain, msg);
481
489
  if seen_msgs.insert(full.clone()) {
482
- errors.push(CheckError { message: full, ..e });
490
+ errors.push(CheckError { message: full, inFns: inst.fnsOf[id].clone(), ..e });
483
491
  }
484
492
  }
485
493
  registerCalls(&mut inst, &fn_by_key, &ctx, Some(id));
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -185,3 +185,32 @@ fn errorInAClosuresLastNonValueStatementIsReported() {
185
185
  assert_eq!(es.len(), 1, "{es:?}");
186
186
  assert_eq!(es[0].line, 12, "{es:?}");
187
187
  }
188
+
189
+ /// An error says which fn it is in as data (`inFns`), so no tool has to read `fn 'x'` out of
190
+ /// the message: a free fn by its name, a method as `Type.method`.
191
+ #[test]
192
+ fn anErrorNamesTheFnItIsIn() {
193
+ let es = errors("struct Box(n: Int) =\n fun get(self) -> Int = true\n\nfun bad() -> Int = true\n\nfun main() -> Int = bad()\n");
194
+ assert_eq!(es.len(), 2, "{es:?}");
195
+ let fns: Vec<&Vec<String>> = es.iter().map(|e| &e.inFns).collect();
196
+ assert!(fns.contains(&&vec!["Box.get".to_string()]), "{es:?}");
197
+ assert!(fns.contains(&&vec!["bad".to_string()]), "{es:?}");
198
+ }
199
+
200
+ /// An error inside a generic fn's copy names the copy's fn first, then the fns whose calls
201
+ /// led to it, out to the root.
202
+ #[test]
203
+ fn anErrorInAGenericCopyNamesItsCallers() {
204
+ let es = errors("fun inner[T](x: T) -> Int = x.nope()\n\nfun outer[T](x: T) -> Int = inner(x)\n\nfun main() -> Int = outer(1)\n");
205
+ assert_eq!(es.len(), 1, "{es:?}");
206
+ assert!(es[0].message.contains("in inner[Int]"), "{es:?}");
207
+ assert_eq!(es[0].inFns, vec!["inner".to_string(), "outer".to_string(), "main".to_string()], "{es:?}");
208
+ }
209
+
210
+ /// A call whose generic nothing pins is an error in the fn that makes the call.
211
+ #[test]
212
+ fn anUnpinnedGenericCallNamesItsCaller() {
213
+ let es = errors("enum Opt[T] =\n | No\n | Yes(v: T)\n\nfun mk[T]() -> Opt[T] = No\n\nfun size[T](o: Opt[T]) -> Int = o.nope()\n\nfun main() -> Int = size(mk())\n");
214
+ let e = es.iter().find(|e| e.message.contains("can't work out")).unwrap_or_else(|| panic!("{es:?}"));
215
+ assert_eq!(e.inFns, vec!["main".to_string()], "{es:?}");
216
+ }
compiler/core/src/ast.rs CHANGED
@@ -1082,6 +1082,15 @@ pub struct FnCall {
1082
1082
  pub type_args: Vec<Type>,
1083
1083
  }
1084
1084
 
1085
+ /// A fn's key: `Type.method` for a member of a type, else its name. What a `Diagnostic`'s
1086
+ /// `inFns` holds.
1087
+ pub fn fnKey(f: &Fn) -> String {
1088
+ match &f.type_param {
1089
+ Some(t) => format!("{}.{}", t, f.name),
1090
+ None => f.name.clone(),
1091
+ }
1092
+ }
1093
+
1085
1094
  /// How a call in tail position is made (see `tail.rs`). `NotTail` is the default.
1086
1095
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1087
1096
  pub enum TailKind {
compiler/core/src/diag.rs CHANGED
@@ -28,12 +28,18 @@ pub struct Diagnostic {
28
28
  pub end_column: usize,
29
29
  pub kind: DiagKind,
30
30
  pub message: String,
31
+ /// The fns the error is in, innermost first, each as its key (`Type.method`, or a free
32
+ /// fn's name, as declared): the fn whose body failed, then for an error inside a generic
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
35
+ /// message's `fn 'x'` / `in X[..]` text.
36
+ pub inFns: Vec<String>,
31
37
  }
32
38
 
33
39
  impl Diagnostic {
34
40
  pub fn new(kind: DiagKind, file: impl Into<String>, line: usize, column: usize, message: impl Into<String>) -> Self {
35
41
  let message: String = message.into();
36
- Diagnostic { file: file.into(), line, column, end_line: 0, end_column: 0, kind, message: sourceName(&message) }
42
+ Diagnostic { file: file.into(), line, column, end_line: 0, end_column: 0, kind, message: sourceName(&message), inFns: Vec::new() }
37
43
  }
38
44
 
39
45
  /// The same diagnostic with the end of the failing node's span (1-based, exclusive).
@@ -43,6 +49,12 @@ impl Diagnostic {
43
49
  self
44
50
  }
45
51
 
52
+ /// The same diagnostic, in the fns `fns` (see `inFns`).
53
+ pub fn in_fns(mut self, fns: Vec<String>) -> Self {
54
+ self.inFns = fns;
55
+ self
56
+ }
57
+
46
58
  /// A diagnostic with no position (and no file).
47
59
  pub fn bare(kind: DiagKind, message: impl Into<String>) -> Self {
48
60
  Diagnostic::new(kind, "", 0, 0, message)
compiler/driver/src/lib.rs CHANGED
@@ -354,40 +354,12 @@ fn adopt(pass: &Pass, st: &mut State, kept: Rc<Source>, mut i2: TypedInfo) {
354
354
  st.info = i2;
355
355
  }
356
356
 
357
- fn fnKey(f: &plum_core::ast::Fn) -> String {
357
+ use plum_core::ast::fnKey;
358
- match &f.type_param {
359
- Some(t) => format!("{}.{}", t, f.name),
360
- None => f.name.clone(),
361
- }
362
- }
363
-
364
- /// The fn names a re-check error is about, innermost first: the `in X[..]` instantiation
365
- /// chain and a `fn 'x'` prefix.
366
- fn namesIn(msg: &str) -> Vec<String> {
367
- let mut out = Vec::new();
368
- let mut rest = msg;
369
- while let Some(i) = rest.find("in ") {
370
- let at = &rest[i + 3..];
371
- let end = at.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.' || c == '$')).unwrap_or(at.len());
372
- if end > 0 && at[end..].starts_with('[') && (i == 0 || rest[..i].ends_with(": ") || rest[..i].ends_with(' ')) {
373
- out.push(at[..end].to_string());
374
- }
375
- rest = &at[end..];
376
- }
377
- if let Some(i) = msg.find("fn '") {
378
- let at = &msg[i + 4..];
379
- if let Some(e) = at.find('\'') {
380
- out.push(at[..e].to_string());
381
- }
382
- }
383
- out.reverse();
384
- out
385
- }
386
358
 
387
359
  /// A failed per-fn rewrite with the fns the errors blame put back as they were in `base`
388
360
  /// (a fn the pass added is removed, with every rewritten fn that calls it), re-checked; a
389
- /// few rounds, each blaming the fns its errors name. `None` when no round checks or an
361
+ /// few rounds, each blaming the fns its errors are in. `None` when no round checks or no
390
- /// error names no rewritten fn: the whole rewrite is then dropped.
362
+ /// error is in a rewritten fn: the whole rewrite is then dropped.
391
363
  fn revertFailing(base: &Source, rewritten: &Source, mut errs: Vec<Diagnostic>) -> Option<(Vec<String>, Rc<Source>, TypedInfo)> {
392
364
  use plum_core::ast::Item;
393
365
  use std::collections::{HashMap, HashSet};
@@ -399,19 +371,12 @@ fn revertFailing(base: &Source, rewritten: &Source, mut errs: Vec<Diagnostic>) -
399
371
  let now: HashMap<String, &plum_core::ast::Fn> =
400
372
  cur.items.iter().filter_map(|i| if let Item::Fn(f) = i { Some((fnKey(f), f)) } else { None }).collect();
401
373
  let changed = |k: &String| now.get(k).is_some_and(|f| old.get(k).is_none_or(|o| !sameFn(o, f)));
402
- // by key, or a method's bare name in a `fn 'name'` prefix
374
+ // Each error blames the innermost fn it is in (`Diagnostic.inFns`, never the message
403
- let byName = |n: &str| -> Vec<String> {
404
- if now.contains_key(n) {
405
- return vec![n.to_string()];
406
- }
407
- now.keys().filter(|k| k.rsplit('.').next() == Some(n)).cloned().collect()
408
- };
409
- // An error in a fn the pass left alone follows from one it changed (a call of `bad`
375
+ // text) that the pass changed. An error in a fn the pass left alone follows from one it
410
- // after `bad`'s signature changed): the next round's re-check tells.
376
+ // changed (a call of `bad` after `bad`'s signature changed): the next round's re-check tells.
411
377
  let mut blamed: HashSet<String> = HashSet::new();
412
378
  for e in &errs {
413
- let names = namesIn(&e.message);
414
- blamed.extend(names.iter().flat_map(|n| byName(n)).find(|k| changed(k)));
379
+ blamed.extend(e.inFns.iter().find(|k| changed(k)).cloned());
415
380
  }
416
381
  if blamed.is_empty() {
417
382
  return None;
compiler/driver/tests/driver_tests.rs CHANGED
@@ -387,6 +387,44 @@ fn aFailingFnRevertsAloneInAPerFnPass() {
387
387
  }
388
388
  }
389
389
 
390
+ const PARTIAL_GENERIC: &str = "\
391
+ import std/Int
392
+
393
+ struct Cell(n: Int) =
394
+ fun good(self) -> Int = self.n + 1
395
+
396
+ fun bad(self) -> Int = self.n * 2
397
+
398
+ fun same[T](x: T) -> T = x
399
+
400
+ fun main() -> Int = Cell(n: 1).good() + Cell(n: 2).bad() + same(3)
401
+ ";
402
+
403
+ /// Breaks the method `Cell.bad` and the generic `same` (their results made a `Bool`).
404
+ fn breakMethodAndGeneric(copy: &mut Source, _: &Env) -> bool {
405
+ for item in &mut copy.items {
406
+ if let Item::Fn(f) = item {
407
+ if f.name == "bad" || f.name == "same" {
408
+ f.returns = Some(plum_core::ast::Type { name: "Bool".to_string(), generics: vec![] });
409
+ }
410
+ }
411
+ }
412
+ true
413
+ }
414
+
415
+ /// The fns a failed re-check blames come from the errors' `inFns`, not from their text: a
416
+ /// method is found by its key (`Cell.bad`), and a generic fn by the copy the error is in
417
+ /// (`in same[Int] (called at ..)` in the message). Both go back alone; the rest is kept.
418
+ #[test]
419
+ fn aFailingMethodAndGenericCopyRevertAlone() {
420
+ let src = load("drv_partial_generic", PARTIAL_GENERIC);
421
+ let pass = Pass { name: "break two", target: Target::Pre, needsHints: false, perFn: true, enabled: |_| true, rewrite: breakMethodAndGeneric };
422
+ let (r, dropped) = plum_driver::checkReport(&src, &PassOptions::default(), &[pass]);
423
+ r.expect("still checks");
424
+ assert_eq!(dropped.len(), 1, "{dropped:?}");
425
+ assert_eq!(dropped[0].reverted, vec!["Cell.bad".to_string(), "same".to_string()], "{dropped:?}");
426
+ }
427
+
390
428
  /// Every game (and the scene-tree benchmark) builds with every pass kept: a rewrite that
391
429
  /// fails its re-check, even in one fn, is reported here.
392
430
  #[test]