plum

#treesitter#compiler#wasm

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

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


e68034d — Peter John 2026-11-10T12:30:56+05:30
Checker: errors in a closure's statements are reported
compiler/checker/src/infer.rs CHANGED
@@ -277,7 +277,7 @@ pub(crate) fn inferExprInner(
277
277
  // (not just its trailing expression) resolves completely — only the
278
278
  // FINAL statement's type is actually needed below, but an earlier
279
279
  // `Assign` may declare a name the final statement depends on.
280
- // The statement errors below are dropped (the params may be unresolved), so a local
280
+ // The statement errors below are dropped while a param is unresolved, so a local
281
281
  // reassignment, which is never valid, is rejected here or it would compile.
282
282
  for stmt in &cl.body.stmts {
283
283
  if let ast::StmtKind::Assign(a) = &stmt.kind {
@@ -288,6 +288,7 @@ pub(crate) fn inferExprInner(
288
288
  }
289
289
  }
290
290
  }
291
+ let params_known = !param_types.iter().any(hasTypeVars);
291
292
  if let Some((_, earlier)) = cl.body.stmts.split_last() {
292
293
  for stmt in earlier {
293
294
  let declares_only = matches!(&stmt.kind, ast::StmtKind::Assign(a)
@@ -303,9 +304,9 @@ pub(crate) fn inferExprInner(
303
304
  } else {
304
305
  // Walk every other statement (`if`, loops, `match`, plain
305
306
  // calls, field assignments like `m.x = k`) so the types of the expressions inside are
306
- // recorded for codegen. Errors are deliberately dropped:
307
+ // recorded for codegen. Its errors are reported once every parameter
307
- // the closure's params may still be unresolved here.
308
+ // has a type (an unresolved one would make them guesses).
308
- let _ = checkStmt(
309
+ let errs = checkStmt(
309
310
  stmt,
310
311
  &mut closure_env,
311
312
  &PlumType::TVar("_".into()),
@@ -313,6 +314,7 @@ pub(crate) fn inferExprInner(
313
314
  (0, 0),
314
315
  ctx,
315
316
  );
317
+ closureStmtError(errs, stmt, params_known)?;
316
318
  }
317
319
  }
318
320
  }
@@ -320,7 +322,7 @@ pub(crate) fn inferExprInner(
320
322
  Some(s @ ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. }) if plum_core::forms::loopOf(s).is_none() => inferExprWith(e, &closure_env, ctx, exp_ret)?,
321
323
  Some(ast::Stmt { kind: ast::StmtKind::Return(Some(e)), .. }) => inferExprWith(e, &closure_env, ctx, exp_ret)?,
322
324
  Some(last) => {
323
- let _ = checkStmt(
325
+ let errs = checkStmt(
324
326
  last,
325
327
  &mut closure_env,
326
328
  &PlumType::TVar("_".into()),
@@ -328,6 +330,7 @@ pub(crate) fn inferExprInner(
328
330
  (0, 0),
329
331
  ctx,
330
332
  );
333
+ closureStmtError(errs, last, params_known)?;
331
334
  PlumType::TUnit
332
335
  }
333
336
  None => PlumType::TUnit,
@@ -749,3 +752,33 @@ pub(crate) fn checkStaticUse(
749
752
  Ok(())
750
753
  }
751
754
 
755
+
756
+ /// Whether `t` still has a type variable in it.
757
+ fn hasTypeVars(t: &PlumType) -> bool {
758
+ match t {
759
+ PlumType::TVar(_) => true,
760
+ PlumType::TApp(_, a) => a.iter().any(hasTypeVars),
761
+ PlumType::TFun(ps, r) => ps.iter().any(hasTypeVars) || hasTypeVars(r),
762
+ _ => false,
763
+ }
764
+ }
765
+
766
+ /// The first error of a closure body's statement `stmt` as the closure's own failure, at the
767
+ /// error's position (the failing node's, else the statement's). `Ok` when there is none, or
768
+ /// while a parameter has no type yet (`known` false): the statement is checked again later.
769
+ fn closureStmtError(errs: Vec<CheckError>, stmt: &ast::Stmt, known: bool) -> Result<(), String> {
770
+ let Some(first) = errs.into_iter().next().filter(|_| known) else { return Ok(()) };
771
+ let sp = &stmt.span;
772
+ let pos = if first.line > 0 {
773
+ Some(((first.line, first.column), (first.end_line, first.end_column)))
774
+ } else {
775
+ (sp.startLine != 0).then_some(((sp.startLine, sp.startColumn), (sp.endLine, sp.endColumn)))
776
+ };
777
+ if let Some(p) = pos {
778
+ withCheck(|s| s.err_pos.set(Some(p)));
779
+ }
780
+ if first.kind == DiagKind::Resolution {
781
+ withCheck(|s| s.err_resolution.set(true));
782
+ }
783
+ Err(first.message.strip_prefix("fn 'closure': ").unwrap_or(&first.message).to_string())
784
+ }
compiler/checker/src/stmt.rs CHANGED
@@ -490,11 +490,13 @@ pub(crate) fn checkStmtInner(
490
490
  tail.clone()
491
491
  };
492
492
  match inferExprWith(e, env, ctx, expected.as_ref()) {
493
- Err(msg) => errors.push(CheckError::at(
493
+ Err(msg) => {
494
+ // At the statement; a failing node on a later line (a statement inside a
494
- *line,
495
+ // closure's indented body) is reported there instead.
496
+ let inner = withCheck(|s| s.err_pos.get()).filter(|p| *line != 0 && p.0 .0 > *line);
495
- *column,
497
+ let ((l, c), (el, ec)) = inner.unwrap_or(((*line, *column), (0, 0)));
496
- format!("fn '{}': {}", fn_name, msg),
498
+ errors.push(CheckError::at(l, c, format!("fn '{}': {}", fn_name, msg)).with_end(el, ec));
497
- )),
499
+ }
498
500
  // The last value of a branch of a block value (`inferBlockValue` joins them).
499
501
  Ok(t) if collecting => {
500
502
  withCheck(|s| {
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -155,3 +155,33 @@ fn interpolationTypeErrorPositionsInNestedAndMultiLineStrings() {
155
155
  assert!(es[0].message.contains("expected Dur, found Tm"), "{es:?}");
156
156
  assert_eq!((es[0].line, es[0].column), (7, 39), "{es:?}");
157
157
  }
158
+
159
+ const BOX: &str = "struct Box(mut n: Int) =\n fun put(self, v: Int) -> Unit =\n self.n = v\n\nfun run(f: fn(Int) -> Int) -> Int = f(1)\n\nfun each(f: fn(Int) -> Unit) -> Unit = f(1)\n\n";
160
+
161
+ /// A statement that is not a closure's last one is checked like any other: its error was
162
+ /// dropped (the body compiled, or failed later in codegen).
163
+ #[test]
164
+ fn errorInAClosuresEarlierStatementIsReportedAtThatStatement() {
165
+ let es = errors(&format!("{BOX}fun main() -> Int =\n b := Box(n: 0)\n g := |x: Int|\n b.put(\"no\")\n x + 1\n run(g)\n"));
166
+ assert_eq!(es.len(), 1, "{es:?}");
167
+ assert_eq!(es[0].line, 12, "{es:?}");
168
+ assert!(es[0].message.contains("expected Int, found Str"), "{es:?}");
169
+ }
170
+
171
+ /// The same for a closure passed straight to a call, its parameter typed by the callee; the
172
+ /// error is on the closure's line, not on the line the call starts at.
173
+ #[test]
174
+ fn errorInAClosureArgumentsEarlierStatementIsReportedAtThatStatement() {
175
+ let es = errors(&format!("{BOX}fun main() -> Int =\n b := Box(n: 0)\n each(|x|\n b.put(x.missing())\n b.put(x)\n )\n b.n\n"));
176
+ assert_eq!(es.len(), 1, "{es:?}");
177
+ assert_eq!((es[0].line, es[0].column), (12, 5), "{es:?}");
178
+ assert!(es[0].message.contains("Int has no method 'missing'"), "{es:?}");
179
+ }
180
+
181
+ /// A closure's last statement that is not a value (a field write) is checked too.
182
+ #[test]
183
+ fn errorInAClosuresLastNonValueStatementIsReported() {
184
+ let es = errors(&format!("{BOX}fun main() -> Int =\n b := Box(n: 0)\n each(|x|\n b.n = \"no\"\n )\n b.n\n"));
185
+ assert_eq!(es.len(), 1, "{es:?}");
186
+ assert_eq!(es[0].line, 12, "{es:?}");
187
+ }