plum

#treesitter#compiler#wasm

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

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


575186f — Peter John 2026-11-10T19:52:54+05:30
Checker: a struct, payload variant, type or unknown name alone is no value
compiler/checker/src/infer.rs CHANGED
@@ -212,6 +212,20 @@ pub(crate) fn inferExprInner(
212
212
  ast::Expr { kind: ast::ExprKind::TypeName(n), .. } => match lookup(env, n) {
213
213
  Ok(ty) if !matches!(ty, PlumType::TVar(_)) => Ok(ty),
214
214
  _ => match ctx.enum_variants.get(n) {
215
+ // `Boxed` / `Circle` alone, for a struct or a variant with fields: only a
216
+ // call makes one (`Type.name` reads the type instead).
217
+ Some(info) if !info.field_types.is_empty() && !withCheck(|s| s.type_receiver.replace(false)) => {
218
+ let what = if info.enum_name == *n { "struct" } else { "variant" };
219
+ let fields: Vec<String> = if info.field_names.len() == info.field_types.len() {
220
+ info.field_names.iter().map(|f| format!("{f}: ..")).collect()
221
+ } else {
222
+ info.field_types.iter().map(|_| "..".to_string()).collect()
223
+ };
224
+ Err(format!(
225
+ "{what} '{n}' has fields, so it isn't a value on its own: construct one with `{n}({})`",
226
+ fields.join(", ")
227
+ ))
228
+ }
215
229
  Some(info) => {
216
230
  let (_, result, binds) = startVariant(info, &[], expected);
217
231
  let ty = substVars(&result, &binds);
@@ -222,7 +236,21 @@ pub(crate) fn inferExprInner(
222
236
  }
223
237
  None => match constUseError(n, env, ctx) {
224
238
  Some(msg) => Err(msg),
239
+ // A bare capitalised name that is no constant, variant or type: codegen
240
+ // has no value for it.
241
+ None if !n.contains(ast::MEMBER_SEP) && !withCheck(|s| s.type_receiver.get()) => {
242
+ if isKnownType(n, env, ctx) {
243
+ Err(format!("'{n}' is a type, not a value: call one of its statics (`{n}.name(..)`) or construct one"))
244
+ } else {
245
+ markResolution();
246
+ let hint = match n.as_str() {
247
+ "True" | "False" => format!("; the Bool values are `{}`", n.to_lowercase()),
248
+ _ => String::new(),
249
+ };
250
+ Err(format!("unknown name '{n}': not a constant, a variant or a type{hint}"))
251
+ }
252
+ }
225
- // Unmodeled/builtin type name: allow, codegen will catch.
253
+ // A type or a type's member as the receiver of a call or a read.
226
254
  None => Ok(PlumType::TNamed(n.to_string())),
227
255
  },
228
256
  },
@@ -578,8 +606,10 @@ pub(crate) fn inferExprInner(
578
606
  // The receiver is a temporary (never recorded); the ARGUMENTS stay
579
607
  // the original nodes so their types are recorded for codegen.
580
608
  let receiver = ast::Expr::TypeName(call.name.clone());
609
+ let saved = withCheck(|s| s.type_receiver.replace(true));
581
- let obj_ty = inferExprInner(&receiver, env, ctx, None)?;
610
+ let obj_ty = inferExprInner(&receiver, env, ctx, None);
611
+ withCheck(|s| s.type_receiver.set(saved));
582
- return inferMethodCall(&obj_ty, "init", &call.args, env, ctx, expected);
612
+ return inferMethodCall(&obj_ty?, "init", &call.args, env, ctx, expected);
583
613
  }
584
614
  if let Some(info) = ctx.enum_variants.get(&call.name) {
585
615
  if call.args.len() != info.field_types.len() {
@@ -709,7 +739,11 @@ pub(crate) fn inferExprInner(
709
739
  inferClassCallRaw(call, env, ctx, expected)
710
740
  }
711
741
  ast::Expr { kind: ast::ExprKind::Attribute(attr), .. } => {
742
+ let on_type = matches!(attr.object.kind, ast::ExprKind::TypeName(_));
743
+ let saved = withCheck(|s| s.type_receiver.replace(on_type));
712
- let obj_ty = resolveRecorded(&inferExpr(&attr.object, env, ctx)?);
744
+ let obj_ty = inferExpr(&attr.object, env, ctx);
745
+ withCheck(|s| s.type_receiver.set(saved));
746
+ let obj_ty = resolveRecorded(&obj_ty?);
713
747
  match &attr.attr {
714
748
  ast::AttrKind::Field(field_name) if isTraitObject(&obj_ty) => Err(format!(
715
749
  "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"
compiler/checker/src/state.rs CHANGED
@@ -63,6 +63,9 @@ pub(crate) struct CheckState {
63
63
  /// Set around the top-level pattern of a `Pat := v` test: the next `checkPattern`
64
64
  /// call (that top pattern) takes it, so only that one may be a bare payload variant.
65
65
  pub(crate) allow_bare_top: Cell<bool>,
66
+ /// Set while inferring the `Type` of `Type.name`: there a struct or payload variant
67
+ /// names its type, where anywhere else it would be a value it can't be.
68
+ pub(crate) type_receiver: Cell<bool>,
66
69
  /// Generic names in scope in the fn (or enum) whose types are being converted, and
67
70
  /// where it is (file, line, fn name) for the implicit-generic report.
68
71
  pub(crate) scope: RefCell<plum_core::generics::Scope>,
compiler/checker/tests/checker/checker_tests.rs CHANGED
@@ -596,7 +596,7 @@ fn rejects_basic_expressions_and_calls() {
596
596
  r("fun g(x: Int) =\n y := x + 1\n y\n", &["return type mismatch"]),
597
597
  r("fun main() -> Int =\n n := 1\n f := ||\n n = 5\n n := 0\n n\n f()\n", &["locals can't be reassigned"]),
598
598
  r("fun f(c: Bool) -> Int =\n if c then 1 else \"no\"\n", &["inline if branches"]),
599
- r("fun f() -> Bool =\n True\n", &["found True"]),
599
+ r("fun f() -> Bool =\n True\n", &["unknown name 'True'", "the Bool values are `true`"]),
600
600
  // Ported from master 9b8580b: an unknown static or method of a declared type was a
601
601
  // codegen error with no position.
602
602
  r("struct P(x: Int)\n\nfun f() -> Int =\n p := P.nope()\n 1\n", &["P has no method 'nope'"]),
compiler/checker/tests/checker/review_tests.rs CHANGED
@@ -1,5 +1,4 @@
1
1
  #![allow(non_snake_case)]
2
- #![allow(dead_code)]
3
2
  //! Programs the checker used to accept and leave to codegen (or to run wrongly).
4
3
  use plum_checker::checkSource;
5
4
 
@@ -23,6 +22,36 @@ fn ok(body: &str) {
23
22
  }
24
23
  }
25
24
 
25
+ #[test]
26
+ fn a_bare_struct_name_is_not_a_value() {
27
+ let e = errorWith("struct Boxed(x: Int)\n\nfun k(x: Boxed) -> Boxed = Boxed", "struct 'Boxed' has fields");
28
+ assert!(e.message.contains("`Boxed(x: ..)`"), "{e:?}");
29
+ assert_eq!((e.line, e.column), (3, 28), "{e:?}");
30
+ }
31
+
32
+ #[test]
33
+ fn a_bare_payload_variant_is_not_a_value() {
34
+ errorWith("enum Sh =\n | Circ(r: Int)\n | Sq(s: Int)\n\nfun k() -> Sh = Circ", "variant 'Circ' has fields");
35
+ }
36
+
37
+ #[test]
38
+ fn a_payload_free_variant_and_a_type_receiver_still_are() {
39
+ ok("enum C = Red | Green\n\nfun k() -> C = Red");
40
+ ok("struct Boxed(x: Int) =\n fun make(n: Int) -> Boxed = Boxed(x: n)\n\nfun k() -> Boxed = Boxed.make(1)");
41
+ ok("enum Cell =\n | Empty\n | Full(n: Int)\n\n fun init(n: Int) -> Cell = if n <= 0 then Empty else Full(n: n)\n\nfun k() -> Cell = Cell(5)");
42
+ }
43
+
44
+ #[test]
45
+ fn an_unknown_capitalised_name_is_an_error() {
46
+ let e = errorWith("fun k() -> Int =\n x := Foo\n 1", "unknown name 'Foo'");
47
+ assert_eq!((e.line, e.column), (2, 8), "{e:?}");
48
+ }
49
+
50
+ #[test]
51
+ fn a_type_name_alone_is_not_a_value() {
52
+ errorWith("enum C = Red | Green\n\nfun k() -> Int =\n x := C\n 1", "'C' is a type, not a value");
53
+ }
54
+
26
55
  fn stdErrors(name: &str, body: &str) -> Vec<String> {
27
56
  plum_test_support::checkErrors(name, &format!("import std/Int\nimport std/Str\nimport std/Option\nimport std/collections/List\n\n{body}\n"))
28
57
  }