plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
f4d8212
— Peter John
2026-11-10T15:46:53+05:30
Checker: [] needs a known type where it is written
- compiler/checker/src/fncheck.rs +3 -0
- compiler/checker/src/infer.rs +5 -1
- compiler/checker/src/program.rs +2 -0
- compiler/checker/src/state.rs +5 -0
- compiler/checker/src/stmt.rs +57 -0
- compiler/checker/tests/checker/features/empty_list.rs +81 -0
- compiler/checker/tests/checker/features/mod.rs +1 -0
- compiler/checker/tests/checker/features/review_fixes.rs +4 -2
- compiler/core/src/ast.rs +10 -0
- compiler/core/src/parser.rs +4 -0
- docs/language.md +2 -0
- tests/core/late_typed_locals.plum +4 -3
compiler/checker/src/fncheck.rs
CHANGED
|
@@ -33,8 +33,11 @@ pub(crate) fn checkFn(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<
|
|
|
33
33
|
};
|
|
34
34
|
withFnScope(f, &owner, || {
|
|
35
35
|
withBounds(f, || {
|
|
36
|
+
let firstEmpty = withCheck(|s| s.pending_seq.get());
|
|
36
37
|
let mut errors = checkParamDefaults(f, global_env, ctx);
|
|
37
38
|
errors.append(&mut checkFnBody(f, global_env, ctx));
|
|
39
|
+
// An expression body has no statement to check its `[]`s.
|
|
40
|
+
errors.extend(crate::stmt::emptyListErrors(firstEmpty, &f.name));
|
|
38
41
|
errors
|
|
39
42
|
})
|
|
40
43
|
})
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -175,7 +175,11 @@ pub(crate) fn inferExprInner(
|
|
|
175
175
|
_ => match ctx.enum_variants.get(n) {
|
|
176
176
|
Some(info) => {
|
|
177
177
|
let (_, result, binds) = startVariant(info, &[], expected);
|
|
178
|
-
|
|
178
|
+
let ty = substVars(&result, &binds);
|
|
179
|
+
if ast::isEmptyListLiteral(expr) {
|
|
180
|
+
crate::stmt::noteEmptyList(expr, &ty);
|
|
181
|
+
}
|
|
182
|
+
Ok(ty)
|
|
179
183
|
}
|
|
180
184
|
None => match constUseError(n, env, ctx) {
|
|
181
185
|
Some(msg) => Err(msg),
|
compiler/checker/src/program.rs
CHANGED
|
@@ -391,6 +391,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
391
391
|
if source.hasPrimitiveIo() {
|
|
392
392
|
env.insert("io".to_string(), TypeScheme::mono(PlumType::TNamed("Io".to_string())));
|
|
393
393
|
}
|
|
394
|
+
let firstEmpty = withCheck(|s| s.pending_seq.get());
|
|
394
395
|
let mut block_errors = checkBlock(
|
|
395
396
|
&t.body,
|
|
396
397
|
&mut env,
|
|
@@ -399,6 +400,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
399
400
|
(t.line, t.column),
|
|
400
401
|
&ctx,
|
|
401
402
|
);
|
|
403
|
+
block_errors.extend(crate::stmt::emptyListErrors(firstEmpty, &format!("test \"{}\"", t.name)));
|
|
402
404
|
errors.append(&mut block_errors);
|
|
403
405
|
if let Some(prev) = prevFile {
|
|
404
406
|
setCurrentFile(&prev);
|
compiler/checker/src/state.rs
CHANGED
|
@@ -68,6 +68,11 @@ pub(crate) struct CheckState {
|
|
|
68
68
|
pub(crate) scope: RefCell<plum_core::generics::Scope>,
|
|
69
69
|
/// The file of the declaration being checked, stamped on every error made meanwhile.
|
|
70
70
|
pub(crate) cur_file: RefCell<String>,
|
|
71
|
+
/// Empty list literals `[]` whose element type was not known where they were inferred:
|
|
72
|
+
/// the expression's id, the order it was first seen in, its span and its type. The
|
|
73
|
+
/// statement it is written in must fix the type (`stmt::emptyListErrors`).
|
|
74
|
+
pub(crate) pending_empty: RefCell<Vec<(plum_core::ast::NodeId, u32, ErrSpan, crate::PlumType)>>,
|
|
75
|
+
pub(crate) pending_seq: Cell<u32>,
|
|
71
76
|
/// The inference failure in flight is a name-resolution one (an undefined name), so the
|
|
72
77
|
/// `CheckError` made from it is a `DiagKind::Resolution`. Saved, restored and cleared
|
|
73
78
|
/// together with `err_pos`.
|
compiler/checker/src/stmt.rs
CHANGED
|
@@ -46,6 +46,51 @@ pub(crate) fn inferBlockValue(
|
|
|
46
46
|
Ok(substVars(&joined, &binds))
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/// Remembers the `[]` at `e`, inferred as `ty`, until the statement it is written in ends
|
|
50
|
+
/// (`emptyListErrors`), unless its element type is already known. Inferring it again (a closure
|
|
51
|
+
/// body checked a second time with its parameter types) replaces what the first time found.
|
|
52
|
+
pub(crate) fn noteEmptyList(e: &ast::Expr, ty: &PlumType) {
|
|
53
|
+
let Some(span) = spanOf(e) else { return };
|
|
54
|
+
let open = hasInferVars(&resolveRecorded(ty));
|
|
55
|
+
withCheck(|s| {
|
|
56
|
+
let mut p = s.pending_empty.borrow_mut();
|
|
57
|
+
let at = p.iter().position(|x| x.0 == e.id);
|
|
58
|
+
match (at, open) {
|
|
59
|
+
(Some(i), true) => p[i].3 = ty.clone(),
|
|
60
|
+
(Some(i), false) => {
|
|
61
|
+
p.remove(i);
|
|
62
|
+
}
|
|
63
|
+
(None, true) => {
|
|
64
|
+
let n = s.pending_seq.get();
|
|
65
|
+
s.pending_seq.set(n + 1);
|
|
66
|
+
p.push((e.id, n, span, ty.clone()));
|
|
67
|
+
}
|
|
68
|
+
(None, false) => {}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// An error for each `[]` first inferred at or after `from` whose element type is still not
|
|
74
|
+
/// known: nothing where it is written (an annotation, a parameter, a field, the returned
|
|
75
|
+
/// type, a sibling element, the rest of its statement) says what the list holds, and a later
|
|
76
|
+
/// statement's use does not type it.
|
|
77
|
+
pub(crate) fn emptyListErrors(from: u32, fn_name: &str) -> Vec<CheckError> {
|
|
78
|
+
let done: Vec<_> = withCheck(|s| {
|
|
79
|
+
let mut p = s.pending_empty.borrow_mut();
|
|
80
|
+
let (done, keep) = std::mem::take(&mut *p).into_iter().partition(|x| x.1 >= from);
|
|
81
|
+
*p = keep;
|
|
82
|
+
done
|
|
83
|
+
});
|
|
84
|
+
done.into_iter()
|
|
85
|
+
.filter(|(_, _, _, ty)| hasInferVars(&resolveRecorded(ty)))
|
|
86
|
+
.map(|(_, _, ((l, c), (el, ec)), _)| {
|
|
87
|
+
let msg = "the type of `[]` is not known here: annotate it, e.g. `xs: List[Int] := []`";
|
|
88
|
+
let msg = if fn_name.is_empty() { msg.to_string() } else { format!("fn '{}': {}", fn_name, msg) };
|
|
89
|
+
CheckError::at(l, c, msg).with_end(el, ec)
|
|
90
|
+
})
|
|
91
|
+
.collect()
|
|
92
|
+
}
|
|
93
|
+
|
|
49
94
|
pub(crate) fn checkStmt(
|
|
50
95
|
stmt: &ast::Stmt,
|
|
51
96
|
env: &mut TypeEnv,
|
|
@@ -55,6 +100,15 @@ pub(crate) fn checkStmt(
|
|
|
55
100
|
ctx: &CheckCtx,
|
|
56
101
|
) -> Vec<CheckError> {
|
|
57
102
|
let prev_ret = withCheck(|s| s.cur_ret.replace(Some(declared_ret.clone())));
|
|
103
|
+
// The last value of a block `if` / `match` used as a value is typed by the statement the
|
|
104
|
+
// block is in: its `[]`s are left to that statement.
|
|
105
|
+
// So are those of an `assert a == b`'s operands, which the test lowering binds to hidden
|
|
106
|
+
// locals first (`__lhs_N := a`): the comparison types them, and the fn's end checks them.
|
|
107
|
+
let isBlockValue = withCheck(|s| matches!(&*s.tail.borrow(), Some(PlumType::TVar(n)) if n == BLOCK_TAIL))
|
|
108
|
+
|| matches!(&stmt.kind, ast::StmtKind::Assign(a) if a.declare && a.targets.iter().all(|t| {
|
|
109
|
+
matches!(t, ast::AssignTarget::Var(n) if n.starts_with("__lhs_") || n.starts_with("__rhs_"))
|
|
110
|
+
}));
|
|
111
|
+
let firstEmpty = withCheck(|s| s.pending_seq.get());
|
|
58
112
|
let (mut errors, pos, _) = withFailure(|| checkStmtInner(stmt, env, declared_ret, fn_name, fn_pos, ctx));
|
|
59
113
|
withCheck(|s| *s.cur_ret.borrow_mut() = prev_ret);
|
|
60
114
|
// With no failing node to point at, an error is the statement's own: at its span, not at
|
|
@@ -71,6 +125,9 @@ pub(crate) fn checkStmt(
|
|
|
71
125
|
e.end_column = ec;
|
|
72
126
|
}
|
|
73
127
|
}
|
|
128
|
+
if !isBlockValue {
|
|
129
|
+
errors.extend(emptyListErrors(firstEmpty, fn_name));
|
|
130
|
+
}
|
|
74
131
|
errors
|
|
75
132
|
}
|
|
76
133
|
|
compiler/checker/tests/checker/features/empty_list.rs
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
//! `[]` needs its type where it is written: an annotation, a parameter, a return type, a
|
|
2
|
+
//! field, a sibling element or the rest of its statement. A later statement does not type it.
|
|
3
|
+
use plum_checker::checkSource;
|
|
4
|
+
|
|
5
|
+
const PRE: &str = "import std/Int\nimport std/Str\nimport std/Option\nimport std/collections/List\nimport std/encoding/Json\n\nstruct Holder(xs: List[Int], y: Int)\n\nstruct Box[T](items: List[T])\n\nfun count(xs: List[Int]) -> Int =\n xs.length()\n\n";
|
|
6
|
+
|
|
7
|
+
/// The errors of `PRE` + `body`, as (line, column, message).
|
|
8
|
+
fn errors(name: &str, body: &str) -> Vec<(u32, u32, String)> {
|
|
9
|
+
let source = plum_test_support::load(name, &format!("{PRE}{body}")).unwrap();
|
|
10
|
+
match checkSource(&source) {
|
|
11
|
+
Ok(_) => vec![],
|
|
12
|
+
Err(es) => es.into_iter().map(|e| (e.line as u32, e.column as u32, e.message)).collect(),
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const LINE: u32 = 14; // the first line of `body`
|
|
17
|
+
const UNKNOWN: &str = "the type of `[]` is not known here";
|
|
18
|
+
|
|
19
|
+
#[test]
|
|
20
|
+
fn emptyListTypedOnlyByALaterUseIsRejectedAtTheBrackets() {
|
|
21
|
+
let es = errors("el_late", "fun main() -> Int =\n e := []\n f := if true then [\"a\"] else e\n f.length()\n");
|
|
22
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
23
|
+
let (line, column, message) = &es[0];
|
|
24
|
+
assert_eq!((*line, *column), (LINE + 1, 8), "{es:?}");
|
|
25
|
+
assert!(message.contains(UNKNOWN), "{es:?}");
|
|
26
|
+
assert!(message.contains("xs: List[Int] := []"), "{es:?}");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
#[test]
|
|
30
|
+
fn emptyListWithNoUseIsRejected() {
|
|
31
|
+
let es = errors("el_unused", "fun main() -> Int =\n e := []\n 0\n");
|
|
32
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN)), "{es:?}");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#[test]
|
|
36
|
+
fn nestedEmptyListsWithNothingToTypeThemAreRejected() {
|
|
37
|
+
let es = errors("el_nested", "fun main() -> Int =\n e := [[]]\n e.length()\n");
|
|
38
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && (e.0, e.1) == (LINE + 1, 9)), "{es:?}");
|
|
39
|
+
let es = errors("el_some", "fun main() -> Int =\n o := Some([])\n 0\n");
|
|
40
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && (e.0, e.1) == (LINE + 1, 13)), "{es:?}");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/// Inside a closure, a loop body and a test: each statement is checked for itself.
|
|
44
|
+
#[test]
|
|
45
|
+
fn emptyListInANestedScopeIsRejected() {
|
|
46
|
+
let es = errors("el_closure_body", "fun main() -> Int =\n f := |n: Int|\n e := []\n n\n f(1)\n");
|
|
47
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && e.0 == LINE + 2), "{es:?}");
|
|
48
|
+
let es = errors("el_branch", "fun main() -> Int =\n if true\n e := []\n 1\n else\n 0\n");
|
|
49
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && e.0 == LINE + 2), "{es:?}");
|
|
50
|
+
let es = errors("el_expr_body", "fun main() -> Bool = Some([]).isSome()\n");
|
|
51
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && (e.0, e.1) == (LINE, 27)), "{es:?}");
|
|
52
|
+
let es = errors("el_test", "fun main() -> Int = 0\n\ntest \"t\"\n e := []\n assert true\n");
|
|
53
|
+
assert!(es.iter().any(|e| e.2.contains(UNKNOWN) && e.0 == LINE + 3), "{es:?}");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#[test]
|
|
57
|
+
fn emptyListIsAcceptedWhereItsTypeIsKnown() {
|
|
58
|
+
let cases = [
|
|
59
|
+
("el_ann", "fun main() -> Int =\n xs: List[Int] := []\n xs.length()\n"),
|
|
60
|
+
("el_arg", "fun main() -> Int =\n count([])\n"),
|
|
61
|
+
("el_ret", "fun none() -> List[Str] =\n []\n"),
|
|
62
|
+
("el_ret_expr", "fun none() -> List[Str] = []\n"),
|
|
63
|
+
("el_field", "fun main() -> Int =\n h := Holder(xs: [], y: 0)\n h.y\n"),
|
|
64
|
+
("el_generic_field", "fun main() -> Int =\n b: Box[Int] := Box(items: [])\n b.items.length()\n"),
|
|
65
|
+
("el_sibling", "fun main() -> Int =\n n := [[], [1]]\n n.length()\n"),
|
|
66
|
+
("el_sibling_deep", "fun main() -> Int =\n n := [[[]], [[1]]]\n n.length()\n"),
|
|
67
|
+
("el_json", "fun main() -> Json =\n Json.array([])\n"),
|
|
68
|
+
("el_some", "fun main() -> Int =\n o: Option[List[Int]] := Some([])\n 0\n"),
|
|
69
|
+
("el_closure", "fun main() -> Int =\n f := |zs: List[Int]| zs.length()\n f([])\n"),
|
|
70
|
+
("el_fold_seed", "fun main() -> Int =\n r := [1, 2].fold([], |acc, x| Cons(head: x, tail: acc))\n r.length()\n"),
|
|
71
|
+
("el_inline_if", "fun main() -> Int =\n w := if true then [] else [2]\n w.length()\n"),
|
|
72
|
+
("el_block_if", "fun main() -> Int =\n v := if true\n []\n else\n [1]\n v.length()\n"),
|
|
73
|
+
("el_match_arm", "fun rest(xs: List[Int]) -> List[Int] = match xs\n Nil => []\n Cons(_, t) => t\n"),
|
|
74
|
+
("el_assert", "fun main() -> Int = 0\n\ntest \"t\"\n e: List[Int] := []\n assert e == []\n assert [] != [1]\n"),
|
|
75
|
+
("el_explicit_nil", "fun main() -> Int =\n p := Nil\n q := if true then [1] else p\n q.length()\n"),
|
|
76
|
+
];
|
|
77
|
+
for (name, body) in cases {
|
|
78
|
+
let es = errors(name, body);
|
|
79
|
+
assert!(es.is_empty(), "{name}: {es:?}");
|
|
80
|
+
}
|
|
81
|
+
}
|
compiler/checker/tests/checker/features/mod.rs
CHANGED
|
@@ -10,3 +10,4 @@ mod primitive_generics;
|
|
|
10
10
|
mod review_fixes;
|
|
11
11
|
mod types;
|
|
12
12
|
mod variant_pattern;
|
|
13
|
+
mod empty_list;
|
compiler/checker/tests/checker/features/review_fixes.rs
CHANGED
|
@@ -91,9 +91,11 @@ fn unpinnedGenericWhoseUnitCopyFailsIsAnErrorAtTheCall() {
|
|
|
91
91
|
|
|
92
92
|
#[test]
|
|
93
93
|
fn methodOnAValueOfUnknownTypeIsAnError() {
|
|
94
|
-
let src = "import std/collections/List\nimport std/Str\nfun f() -> Int =\n xs :=
|
|
94
|
+
let src = "import std/collections/List\nimport std/Str\nfun f() -> Int =\n xs := Nil\n ys := xs.map(|x| x.length())\n ys.length()\n";
|
|
95
95
|
expectAt(src, "can't work out the type of the value 'length' is called on", 5, 20);
|
|
96
|
-
expectOk("import std/collections/List\nfun f() -> Int =\n xs :=
|
|
96
|
+
expectOk("import std/collections/List\nfun f() -> Int =\n xs := Nil\n xs.length()\n");
|
|
97
|
+
// An empty list literal is an error where it is written (see `features::empty_list`).
|
|
98
|
+
expectAt("import std/collections/List\nfun f() -> Int =\n xs := []\n xs.length()\n", "the type of `[]` is not known here", 3, 9);
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
#[test]
|
compiler/core/src/ast.rs
CHANGED
|
@@ -1111,6 +1111,16 @@ pub enum Arg {
|
|
|
1111
1111
|
Keyword { name: String, value: Expr },
|
|
1112
1112
|
}
|
|
1113
1113
|
|
|
1114
|
+
/// Whether `e` is an empty list literal `[]`. The parser writes it as the variant `Nil` with a
|
|
1115
|
+
/// span of exactly two columns on one line, which no `Nil` written out (three letters) has,
|
|
1116
|
+
/// so the mark survives every copy of the expression.
|
|
1117
|
+
pub fn isEmptyListLiteral(e: &Expr) -> bool {
|
|
1118
|
+
matches!(&e.kind, ExprKind::TypeName(n) if n == "Nil")
|
|
1119
|
+
&& e.span.startLine != 0
|
|
1120
|
+
&& e.span.startLine == e.span.endLine
|
|
1121
|
+
&& e.span.endColumn == e.span.startColumn + 2
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1114
1124
|
#[derive(Debug, Clone, PartialEq)]
|
|
1115
1125
|
pub struct ClassCall {
|
|
1116
1126
|
pub type_name: String,
|
compiler/core/src/parser.rs
CHANGED
|
@@ -1563,6 +1563,10 @@ impl<'a> AstParser<'a> {
|
|
|
1563
1563
|
}
|
|
1564
1564
|
// Built back to front: `[a, b]` is `Cons(head: a, tail: Cons(head: b, tail: Nil))`.
|
|
1565
1565
|
let mut out = Expr::TypeName("Nil".to_string());
|
|
1566
|
+
if elems.is_empty() {
|
|
1567
|
+
// `[]`: a `Nil` whose span is the two brackets (see `ast::isEmptyListLiteral`).
|
|
1568
|
+
out.span = Span { startLine: line, startColumn: column, endLine: line, endColumn: column + 2 };
|
|
1569
|
+
}
|
|
1566
1570
|
for e in elems.into_iter().rev() {
|
|
1567
1571
|
let value = match e.kind() {
|
|
1568
1572
|
"pair_argument" => e.named_child(0).map(expr).unwrap_or_else(|| self.missing(node)),
|
docs/language.md
CHANGED
|
@@ -354,6 +354,8 @@ fun main() =
|
|
|
354
354
|
|
|
355
355
|
A `List` is `Nil` or `Cons(head, tail)`, so you can match on it. Indexing a `List` is slow, so reach for a `Slice` when you need it.
|
|
356
356
|
|
|
357
|
+
An empty list `[]` needs its type where it is written: an annotation (`xs: List[Int] := []`), the parameter, field or return type it is given to, a sibling element (`[[], [1]]`), or the rest of its own statement (`xs.fold([], |acc, x| Cons(head: x, tail: acc))`). A later statement doesn't type it: `e := []` alone is an error at the `[]`.
|
|
358
|
+
|
|
357
359
|
A `Map` is persistent, like a `List`: `m.with(k, v)` and `m.remove(k)` return a new map that shares most of its nodes with `m`, and `m` stays as it was. A map literal `[k => v, ..]` is `Map.empty().with(k, v)...`, so a later duplicate key wins. Keys are kept in order by their `compare` method, which `Int`, `Float`, `Str`, `Bool` and `Byte` have and a struct can define, and every walk goes in key order. See [the standard library](std.md#collections).
|
|
358
360
|
|
|
359
361
|
## Loops
|
tests/core/late_typed_locals.plum
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
# Probe for master 9b8580b (F-final 14), late-typed locals: a local declared as `None`
|
|
1
|
+
# Probe for master 9b8580b (F-final 14), late-typed locals: a local declared as `None` or
|
|
2
|
-
# `Err(..)`
|
|
2
|
+
# `Err(..)` takes its full type from where it is used. An empty list `[]` does not: it needs
|
|
3
|
+
# its type where it is written (an annotation here). The branch has no local
|
|
3
4
|
# reassignment, so the probe uses the other branch of an `if`. Not reproduced: passes unchanged.
|
|
4
5
|
import std/Int
|
|
5
6
|
import std/Float
|
|
@@ -29,7 +30,7 @@ test "late"
|
|
|
29
30
|
Some(s) => "got {s}"
|
|
30
31
|
None => "none"
|
|
31
32
|
assert got == "got hello"
|
|
32
|
-
e := []
|
|
33
|
+
e: List[Str] := []
|
|
33
34
|
f := if true then ["a", "b"] else e
|
|
34
35
|
assert f.length() == 2
|
|
35
36
|
assert f.at(0) == "a"
|