plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
ac18475
— Peter John
2026-11-10T11:39:15+05:30
checker: reject what codegen or the run failed on, errors at the code
- compiler/checker/src/callcheck.rs +65 -5
- compiler/checker/src/callsites.rs +102 -24
- compiler/checker/src/declchecks.rs +61 -1
- compiler/checker/src/env.rs +17 -0
- compiler/checker/src/fields.rs +7 -9
- compiler/checker/src/fncheck.rs +13 -0
- compiler/checker/src/generics.rs +6 -6
- compiler/checker/src/identity.rs +1 -1
- compiler/checker/src/infer.rs +48 -4
- compiler/checker/src/matchcheck.rs +41 -6
- compiler/checker/src/names.rs +45 -0
- compiler/checker/src/patterns.rs +4 -4
- compiler/checker/src/program.rs +69 -17
- compiler/checker/src/state.rs +4 -0
- compiler/checker/src/stmt.rs +43 -2
- compiler/checker/src/tables.rs +75 -6
- compiler/checker/tests/checker/features/mod.rs +1 -0
- compiler/checker/tests/checker/features/review_fixes.rs +214 -0
- compiler/checker/tests/checker/fip_test.rs +2 -1
- compiler/cli/tests/cli/old_forms_test.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_types/synthetic_sites.rs +2 -1
compiler/checker/src/callcheck.rs
CHANGED
|
@@ -60,6 +60,9 @@ pub(crate) fn inferClassCallRaw(
|
|
|
60
60
|
ctx: &CheckCtx,
|
|
61
61
|
expected: Option<&PlumType>,
|
|
62
62
|
) -> Result<PlumType, String> {
|
|
63
|
+
if let Some(n) = firstDuplicate(call.fields.iter().map(|f| f.name.as_str())) {
|
|
64
|
+
return Err(format!("'{}(..)': field '{n}' is given twice", call.type_name));
|
|
65
|
+
}
|
|
63
66
|
let explicit: Vec<PlumType> = call.generics.iter().map(plumTypeFromAstG).collect();
|
|
64
67
|
// A zero-arg `Type()` construction with a nested, no-param `fun init() ->
|
|
65
68
|
// Type = ...` method declared is sugar for calling that method — the
|
|
@@ -159,7 +162,17 @@ pub(crate) fn inferClassCallRaw(
|
|
|
159
162
|
}
|
|
160
163
|
match &call.spread {
|
|
161
164
|
Some(spread) => {
|
|
162
|
-
checkSpreadSource(spread, &call.type_name, &info.enum_name, env, ctx)?
|
|
165
|
+
checkSpreadSource(spread, &call.type_name, &info.enum_name, env, ctx)?;
|
|
166
|
+
// The source is typed as the whole enum, so it may hold another variant:
|
|
167
|
+
// reading a field of `A` from it traps at run time. With every field
|
|
168
|
+
// given nothing is read from it.
|
|
169
|
+
let others = ctx.enum_variants.variantsOf(&info.enum_name).nth(1).is_some();
|
|
170
|
+
if let (true, Some(missing)) = (others, info.field_names.iter().find(|n| !call.fields.iter().any(|fa| &fa.name == *n))) {
|
|
171
|
+
return Err(format!(
|
|
172
|
+
"spread source for '{}': a {} may be another variant than {}, so its '{}' can't be read; match it first (`{}(..) => ..`) and build from the fields",
|
|
173
|
+
call.type_name, info.enum_name, call.type_name, missing, call.type_name
|
|
174
|
+
));
|
|
175
|
+
}
|
|
163
176
|
}
|
|
164
177
|
None => {
|
|
165
178
|
for field_name in &info.field_names {
|
|
@@ -200,6 +213,11 @@ pub(crate) fn inferClassCallRaw(
|
|
|
200
213
|
let (_, result, binds) = startVariant(info, &explicit, expected);
|
|
201
214
|
Ok(substVars(&result, &binds))
|
|
202
215
|
}
|
|
216
|
+
// A list literal builds std's `Cons` cells: without std/List there are none.
|
|
217
|
+
None if call.type_name == "Cons" => {
|
|
218
|
+
markResolution();
|
|
219
|
+
Err("a list literal `[..]` builds a std List: import std/List".to_string())
|
|
220
|
+
}
|
|
203
221
|
_ => Ok(PlumType::TNamed(call.type_name.clone())),
|
|
204
222
|
}
|
|
205
223
|
}
|
|
@@ -266,6 +284,22 @@ pub(crate) fn checkCallArgs(
|
|
|
266
284
|
|
|
267
285
|
/// Binds a call's explicit type arguments (`findAs[Orb](..)`): the `i`th one is the
|
|
268
286
|
/// callee's `i`th declared generic, whose variable at this call is in `call_map`.
|
|
287
|
+
/// A call with no type arguments to a fn or method with a generic only its body uses
|
|
288
|
+
/// (`fun show[T]() -> Str`): nothing at the call sets that generic.
|
|
289
|
+
pub(crate) fn checkUnsetGenerics(owner: Option<&str>, name: &str, call_map: &BTreeMap<String, PlumType>) -> Result<(), String> {
|
|
290
|
+
let declared = withCheck(|s| {
|
|
291
|
+
s.fn_generics.borrow().get(&(owner.map(str::to_string), name.to_string())).cloned()
|
|
292
|
+
})
|
|
293
|
+
.unwrap_or_default();
|
|
294
|
+
let unset: Vec<&str> = declared.iter().filter(|g| !call_map.contains_key(*g)).map(|g| g.as_str()).collect();
|
|
295
|
+
if unset.is_empty() {
|
|
296
|
+
return Ok(());
|
|
297
|
+
}
|
|
298
|
+
let shown = plum_core::diag::sourceName(name);
|
|
299
|
+
let ints = vec!["Int"; declared.len()].join(", ");
|
|
300
|
+
Err(format!("can't work out {} for '{shown}'; write {shown}[{ints}](..)", unset.join(", ")))
|
|
301
|
+
}
|
|
302
|
+
|
|
269
303
|
pub(crate) fn applyTypeArgs(
|
|
270
304
|
label: &str,
|
|
271
305
|
owner: Option<&str>,
|
|
@@ -275,13 +309,13 @@ pub(crate) fn applyTypeArgs(
|
|
|
275
309
|
binds: &mut Binds,
|
|
276
310
|
ctx: &CheckCtx,
|
|
277
311
|
) -> Result<(), String> {
|
|
278
|
-
if type_args.is_empty() {
|
|
279
|
-
return Ok(());
|
|
280
|
-
}
|
|
281
312
|
let declared = withCheck(|s| {
|
|
282
313
|
s.fn_generics.borrow().get(&(owner.map(str::to_string), name.to_string())).cloned()
|
|
283
314
|
});
|
|
284
315
|
let declared = declared.unwrap_or_default();
|
|
316
|
+
if type_args.is_empty() {
|
|
317
|
+
return Ok(());
|
|
318
|
+
}
|
|
285
319
|
if declared.len() != type_args.len() {
|
|
286
320
|
return Err(format!(
|
|
287
321
|
"{label}: takes {} type argument(s), got {}",
|
|
@@ -308,6 +342,23 @@ pub(crate) fn applyTypeArgs(
|
|
|
308
342
|
Ok(())
|
|
309
343
|
}
|
|
310
344
|
|
|
345
|
+
/// The names of the methods of the type named `class` (a range of the sorted table).
|
|
346
|
+
pub(crate) fn methodNamesOf<C: FromIterator<String>>(class: &str, ctx: &CheckCtx) -> C {
|
|
347
|
+
ctx.methods
|
|
348
|
+
.range((class.to_string(), String::new())..)
|
|
349
|
+
.take_while(|((o, _), _)| o == class)
|
|
350
|
+
.map(|((_, m), _)| m.clone())
|
|
351
|
+
.collect()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/// Whether the type named `class` declares any method (a range lookup in the sorted table).
|
|
355
|
+
pub(crate) fn hasAnyMethod(class: &str, ctx: &CheckCtx) -> bool {
|
|
356
|
+
ctx.methods
|
|
357
|
+
.range((class.to_string(), String::new())..)
|
|
358
|
+
.next()
|
|
359
|
+
.is_some_and(|((o, _), _)| o == class)
|
|
360
|
+
}
|
|
361
|
+
|
|
311
362
|
pub(crate) fn inferMethodCall(
|
|
312
363
|
obj_ty: &PlumType,
|
|
313
364
|
name: &str,
|
|
@@ -385,6 +436,9 @@ pub(crate) fn inferMethodCallWith(
|
|
|
385
436
|
// result is a wildcard, and the real check happens per instantiation.
|
|
386
437
|
return Ok(PlumType::TVar("_".to_string()));
|
|
387
438
|
}
|
|
439
|
+
if matches!(obj_ty, PlumType::TUnit) {
|
|
440
|
+
return Err(format!("Unit has no method '{}': the value is the result of something that returns nothing", name));
|
|
441
|
+
}
|
|
388
442
|
let Some(class_name) = methodReceiverName(obj_ty) else {
|
|
389
443
|
// Inside an instantiation a concrete receiver with no method table at
|
|
390
444
|
// all (unit, fn type) has no methods.
|
|
@@ -430,7 +484,10 @@ pub(crate) fn inferMethodCallWith(
|
|
|
430
484
|
)
|
|
431
485
|
// A declared type's static or method (`P.make(3)`, `p.make(3)`): a
|
|
432
486
|
// typo'd name was a codegen error with no position.
|
|
433
|
-
|| matches!(obj_ty, PlumType::TNamed(n) if ctx.enum_variants.
|
|
487
|
+
|| matches!(obj_ty, PlumType::TNamed(n) if ctx.enum_variants.isEnum(n))
|
|
488
|
+
// A type with methods of its own but not this one (`io.println` on the
|
|
489
|
+
// primitive `Io`).
|
|
490
|
+
|| hasAnyMethod(&class_name, ctx))
|
|
434
491
|
{
|
|
435
492
|
return Err(format!("{} has no method '{}'", obj_ty, name));
|
|
436
493
|
}
|
|
@@ -454,6 +511,9 @@ pub(crate) fn inferMethodCallWith(
|
|
|
454
511
|
let mut binds = Binds::new();
|
|
455
512
|
let label = format!("method '{}.{}'", class_name, name);
|
|
456
513
|
applyTypeArgs(&label, Some(&class_name), name, type_args, &mut call_map, &mut binds, ctx)?;
|
|
514
|
+
if type_args.is_empty() {
|
|
515
|
+
checkUnsetGenerics(Some(&class_name), name, &call_map)?;
|
|
516
|
+
}
|
|
457
517
|
if let Some(exp) = expected {
|
|
458
518
|
bindMatch(&ret, exp, &mut binds);
|
|
459
519
|
}
|
compiler/checker/src/callsites.rs
CHANGED
|
@@ -11,6 +11,8 @@ pub(crate) struct CallSite {
|
|
|
11
11
|
args: BTreeMap<String, PlumType>,
|
|
12
12
|
line: usize,
|
|
13
13
|
column: usize,
|
|
14
|
+
/// The file the call is in, for the "called at" of a chain.
|
|
15
|
+
file: String,
|
|
14
16
|
/// Id of the call expression (or, for an implicit call, of the expression it is made on).
|
|
15
17
|
expr: ast::NodeId,
|
|
16
18
|
/// A call codegen makes on its own (string interpolation's `toStr`), not written in source.
|
|
@@ -20,6 +22,17 @@ pub(crate) struct CallSite {
|
|
|
20
22
|
dispatch: bool,
|
|
21
23
|
}
|
|
22
24
|
|
|
25
|
+
/// The file of the declaration being checked.
|
|
26
|
+
fn shownFile() -> String {
|
|
27
|
+
crate::state::currentFile()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// `file` relative to the working directory when under it, as diagnostics show it.
|
|
31
|
+
fn displayFile(file: &str) -> String {
|
|
32
|
+
let rel = std::env::current_dir().ok().and_then(|d| std::path::Path::new(file).strip_prefix(d).ok().map(|p| p.display().to_string()));
|
|
33
|
+
rel.unwrap_or_else(|| file.to_string())
|
|
34
|
+
}
|
|
35
|
+
|
|
23
36
|
pub(crate) fn recordCall(recv: Option<&str>, name: &str, args: BTreeMap<String, PlumType>) {
|
|
24
37
|
recordCallAt(withCheck(|s| { let e = &s.cur_expr; e.get() }), false, recv, name, args);
|
|
25
38
|
}
|
|
@@ -44,6 +57,7 @@ pub(crate) fn recordCallAt(
|
|
|
44
57
|
args,
|
|
45
58
|
line,
|
|
46
59
|
column,
|
|
60
|
+
file: shownFile(),
|
|
47
61
|
expr,
|
|
48
62
|
implicit,
|
|
49
63
|
dispatch: false,
|
|
@@ -87,6 +101,7 @@ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
|
|
|
87
101
|
args: b,
|
|
88
102
|
line,
|
|
89
103
|
column,
|
|
104
|
+
file: shownFile(),
|
|
90
105
|
expr,
|
|
91
106
|
implicit: false,
|
|
92
107
|
dispatch: true,
|
|
@@ -126,6 +141,31 @@ pub(crate) struct InstState {
|
|
|
126
141
|
pub(crate) chains: Vec<String>,
|
|
127
142
|
pub(crate) queue: std::collections::VecDeque<usize>,
|
|
128
143
|
pub(crate) file: String,
|
|
144
|
+
/// Per callee (owner, name): `calleeGenerics`.
|
|
145
|
+
pub(crate) generics_of: HashMap<(Option<String>, String), (Vec<String>, Vec<String>, Vec<String>)>,
|
|
146
|
+
/// The instantiations made with a generic nothing pinned, defaulted to `Unit`.
|
|
147
|
+
pub(crate) defaulted: HashMap<usize, Defaulted>,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/// A call whose `generics` nothing pinned (see `registerCalls`).
|
|
151
|
+
pub(crate) struct Defaulted {
|
|
152
|
+
pub(crate) generics: Vec<String>,
|
|
153
|
+
pub(crate) name: String,
|
|
154
|
+
pub(crate) line: usize,
|
|
155
|
+
pub(crate) column: usize,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
impl Defaulted {
|
|
159
|
+
/// The error of the call when its `Unit` copy doesn't check.
|
|
160
|
+
pub(crate) fn error(&self) -> CheckError {
|
|
161
|
+
let g = self.generics.join(", ");
|
|
162
|
+
let ints = vec!["Int"; self.generics.len()].join(", ");
|
|
163
|
+
CheckError::at(
|
|
164
|
+
self.line,
|
|
165
|
+
self.column,
|
|
166
|
+
format!("can't work out {g} for '{}'; annotate the result or write {}[{ints}](..)", self.name, self.name),
|
|
167
|
+
)
|
|
168
|
+
}
|
|
129
169
|
}
|
|
130
170
|
|
|
131
171
|
/// (A generic body keeps its `DiagKind::Resolution` errors even when uninstantiated; every
|
|
@@ -180,6 +220,17 @@ pub(crate) fn hasInferVars(t: &PlumType) -> bool {
|
|
|
180
220
|
}
|
|
181
221
|
}
|
|
182
222
|
|
|
223
|
+
/// Whether `t` mentions a generic parameter (`TParam`), as an erased generic body's types do.
|
|
224
|
+
pub(crate) fn hasTParams(t: &PlumType) -> bool {
|
|
225
|
+
use PlumType::*;
|
|
226
|
+
match t {
|
|
227
|
+
TParam(_) => true,
|
|
228
|
+
TApp(_, a) => a.iter().any(hasTParams),
|
|
229
|
+
TFun(ps, r) => ps.iter().any(hasTParams) || hasTParams(r),
|
|
230
|
+
_ => false,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
183
234
|
pub(crate) fn hasFreeVars(t: &PlumType) -> bool {
|
|
184
235
|
use PlumType::*;
|
|
185
236
|
match t {
|
|
@@ -190,6 +241,34 @@ pub(crate) fn hasFreeVars(t: &PlumType) -> bool {
|
|
|
190
241
|
}
|
|
191
242
|
}
|
|
192
243
|
|
|
244
|
+
/// A callee's generic names (`fnGenericNames`), its owner type's generics, and (for a
|
|
245
|
+
/// static) the generics its signature mentions: worked out once per callee.
|
|
246
|
+
/// A static method of a generic type whose signature never mentions an owner generic
|
|
247
|
+
/// (`Box[T].ints(n) -> Box[Int]` called as `Box.ints(3)`): nothing at the call pins it, and
|
|
248
|
+
/// nothing in the signature depends on it, so any one copy will do — `registerCalls` pins it
|
|
249
|
+
/// to `Unit`. Likewise a method called on a bare nullary variant (`Nil.fold(0, f)`): the
|
|
250
|
+
/// checker accepted the call with nothing fixing `T`, and no element of that type exists
|
|
251
|
+
/// at run time.
|
|
252
|
+
fn calleeGenerics(f: &ast::Fn, ctx: &CheckCtx) -> (Vec<String>, Vec<String>, Vec<String>) {
|
|
253
|
+
let gens = fnGenericNames(f, ctx);
|
|
254
|
+
let owner_gens: Vec<String> = match &f.type_param {
|
|
255
|
+
Some(r) => enumGenericsOf(r, ctx).to_vec(),
|
|
256
|
+
None => Vec::new(),
|
|
257
|
+
};
|
|
258
|
+
let mut sig_free = Vec::new();
|
|
259
|
+
if !f.has_self && !gens.is_empty() {
|
|
260
|
+
withFnScope(f, &owner_gens, || {
|
|
261
|
+
for p in &f.params {
|
|
262
|
+
freeTParams(¶mTypeG(&p.ty), &mut sig_free);
|
|
263
|
+
}
|
|
264
|
+
if let Some(r) = &f.returns {
|
|
265
|
+
freeTParams(&plumTypeFromAstG(r), &mut sig_free);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
(gens, owner_gens, sig_free)
|
|
270
|
+
}
|
|
271
|
+
|
|
193
272
|
/// Turns the generic calls recorded while checking one body into new
|
|
194
273
|
/// instantiations (memoized by item + concrete type args).
|
|
195
274
|
pub(crate) fn registerCalls(
|
|
@@ -211,38 +290,32 @@ pub(crate) fn registerCalls(
|
|
|
211
290
|
let Some(f) = fns.get(&(cs.recv.clone(), cs.name.clone())) else {
|
|
212
291
|
continue;
|
|
213
292
|
};
|
|
293
|
+
let key = (cs.recv.clone(), cs.name.clone());
|
|
294
|
+
if !st.generics_of.contains_key(&key) {
|
|
214
|
-
|
|
295
|
+
let g = calleeGenerics(f, ctx);
|
|
296
|
+
st.generics_of.insert(key.clone(), g);
|
|
297
|
+
}
|
|
298
|
+
let (gens, owner_gens, sig_free) = &st.generics_of[&key];
|
|
299
|
+
let (gens, owner_gens, sig_free) = (gens.clone(), owner_gens.clone(), sig_free.clone());
|
|
215
300
|
if gens.is_empty() || depth >= 24 || st.info.instantiations.len() >= 20000 {
|
|
216
301
|
continue;
|
|
217
302
|
}
|
|
218
|
-
// A static method of a generic type whose signature never mentions an
|
|
219
|
-
// owner generic (`Box[T].ints(n) -> Box[Int]` called as `Box.ints(3)`):
|
|
220
|
-
// nothing at the call pins it, and nothing in the signature depends on
|
|
221
|
-
// it, so any one copy will do — pin it to `Unit`. Likewise a method called on a bare
|
|
222
|
-
// nullary variant (`Nil.fold(0, f)`): the checker accepted the call with nothing
|
|
223
|
-
// fixing `T`, and no element of that type exists at run time.
|
|
224
|
-
let owner_gens: Vec<String> = match &f.type_param {
|
|
225
|
-
Some(r) => enumGenericsOf(r, ctx).to_vec(),
|
|
226
|
-
None => Vec::new(),
|
|
227
|
-
};
|
|
228
|
-
let mut sig_free = Vec::new();
|
|
229
|
-
if !f.has_self {
|
|
230
|
-
withFnScope(f, &owner_gens, || {
|
|
231
|
-
for p in &f.params {
|
|
232
|
-
freeTParams(¶mTypeG(&p.ty), &mut sig_free);
|
|
233
|
-
}
|
|
234
|
-
if let Some(r) = &f.returns {
|
|
235
|
-
freeTParams(&plumTypeFromAstG(r), &mut sig_free);
|
|
236
|
-
}
|
|
237
|
-
});
|
|
238
|
-
}
|
|
239
303
|
let mut args = Vec::new();
|
|
304
|
+
// The generics nothing at the call pinned (`o := mk()` with `mk[T]() -> Option[T]`,
|
|
305
|
+
// used only as `o.isNone()`): no value of such a type is ever made or read, and the
|
|
306
|
+
// call's recorded types default the variable to `Unit` (`checkSourceOnce`), so the
|
|
307
|
+
// copy compiled is the `Unit` one. If that copy doesn't check, the call is the error.
|
|
308
|
+
let mut defaulted = Vec::new();
|
|
240
309
|
for g in &gens {
|
|
241
310
|
match cs.args.get(g).map(subst) {
|
|
242
311
|
Some(t) if !hasFreeVars(&t) => args.push(t),
|
|
243
312
|
_ if owner_gens.contains(g) && !sig_free.contains(g) => {
|
|
244
313
|
args.push(PlumType::TUnit)
|
|
245
314
|
}
|
|
315
|
+
Some(t) if !hasTParams(&t) => {
|
|
316
|
+
defaulted.push(g.clone());
|
|
317
|
+
args.push(defaultVars(&t));
|
|
318
|
+
}
|
|
246
319
|
_ => break,
|
|
247
320
|
}
|
|
248
321
|
}
|
|
@@ -268,6 +341,8 @@ pub(crate) fn registerCalls(
|
|
|
268
341
|
if let Some(msg) = unmetBound(&plum_core::diag::sourceName(&item), &gens, &args, &bounds) {
|
|
269
342
|
let e = CheckError::at(cs.line, cs.column, format!("{}call '{}': {}", parent_chain, plum_core::diag::sourceName(&cs.name), msg));
|
|
270
343
|
withCheck(|s| s.bound_errors.borrow_mut().push(e));
|
|
344
|
+
// Not instantiated: its body's errors would only repeat the unmet bound.
|
|
345
|
+
continue;
|
|
271
346
|
}
|
|
272
347
|
}
|
|
273
348
|
}
|
|
@@ -285,9 +360,9 @@ pub(crate) fn registerCalls(
|
|
|
285
360
|
st.chains.push(format!(
|
|
286
361
|
"{}in {}[{}] (called at {}:{}:{}): ",
|
|
287
362
|
parent_chain,
|
|
288
|
-
item,
|
|
363
|
+
plum_core::diag::sourceName(&item),
|
|
289
364
|
arg_str.join(", "),
|
|
290
|
-
st.file,
|
|
365
|
+
if cs.file.is_empty() { st.file.clone() } else { displayFile(&cs.file) },
|
|
291
366
|
cs.line,
|
|
292
367
|
cs.column
|
|
293
368
|
));
|
|
@@ -303,6 +378,9 @@ pub(crate) fn registerCalls(
|
|
|
303
378
|
called_at_column: cs.column,
|
|
304
379
|
});
|
|
305
380
|
st.info.inst_index.insert(key, id);
|
|
381
|
+
if !defaulted.is_empty() {
|
|
382
|
+
st.defaulted.insert(id, Defaulted { generics: defaulted, name: plum_core::diag::sourceName(&cs.name), line: cs.line, column: cs.column });
|
|
383
|
+
}
|
|
306
384
|
if !cs.dispatch {
|
|
307
385
|
st.info.call_inst.insert((parent, cs.expr, cs.implicit), id);
|
|
308
386
|
}
|
compiler/checker/src/declchecks.rs
CHANGED
|
@@ -33,6 +33,18 @@ pub(crate) fn checkBareGenericTypes(source: &ast::Source) -> Vec<CheckError> {
|
|
|
33
33
|
generic_enums: &BTreeMap<&str, usize>,
|
|
34
34
|
errors: &mut Vec<CheckError>,
|
|
35
35
|
) {
|
|
36
|
+
// `Box[Int, Int]` for `struct Box[T]`: the wrong number of type arguments.
|
|
37
|
+
if !t.generics.is_empty() && !params.isGeneric(&t.name) {
|
|
38
|
+
if let Some(&n) = generic_enums.get(t.name.as_str()) {
|
|
39
|
+
if n != t.generics.len() {
|
|
40
|
+
errors.push(CheckError::at(
|
|
41
|
+
line,
|
|
42
|
+
column,
|
|
43
|
+
format!("type '{}' takes {} type argument(s), got {}", t.name, n, t.generics.len()),
|
|
44
|
+
));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
36
48
|
if t.generics.is_empty() && scope != Some(t.name.as_str()) && !params.isGeneric(&t.name) {
|
|
37
49
|
if generic_enums.contains_key(t.name.as_str()) {
|
|
38
50
|
errors.push(CheckError::at(
|
|
@@ -305,6 +317,54 @@ pub(crate) fn checkConstDecls(source: &ast::Source) -> Vec<CheckError> {
|
|
|
305
317
|
errors
|
|
306
318
|
}
|
|
307
319
|
|
|
320
|
+
/// The first name of `names` seen twice.
|
|
321
|
+
pub(crate) fn firstDuplicate<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
|
|
322
|
+
let mut seen = std::collections::HashSet::new();
|
|
323
|
+
names.into_iter().find(|n| *n != "_" && !seen.insert(*n))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// Names a declaration gives twice: a fn's parameters or generics, a type's variants,
|
|
327
|
+
/// fields or generics. The later one would silently win (or both would be compiled).
|
|
328
|
+
pub(crate) fn checkDuplicateNames(source: &ast::Source) -> Vec<CheckError> {
|
|
329
|
+
let mut errors = Vec::new();
|
|
330
|
+
for item in &source.items {
|
|
331
|
+
match item {
|
|
332
|
+
ast::Item::Fn(f) => {
|
|
333
|
+
let label = match &f.type_param {
|
|
334
|
+
Some(r) => format!("{}.{}", r, f.name),
|
|
335
|
+
None => f.name.clone(),
|
|
336
|
+
};
|
|
337
|
+
if let Some(n) = firstDuplicate(f.params.iter().map(|p| p.name.as_str())) {
|
|
338
|
+
errors.push(CheckError::at(f.line, f.column, format!("fn '{label}': parameter '{n}' is declared twice")));
|
|
339
|
+
}
|
|
340
|
+
if let Some(n) = firstDuplicate(f.generics.iter().map(|g| g.as_str())) {
|
|
341
|
+
errors.push(CheckError::at(f.line, f.column, format!("fn '{label}': type parameter '{n}' is declared twice")));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
ast::Item::Enum(e) => {
|
|
345
|
+
if let Some(n) = firstDuplicate(e.generics.iter().map(|g| g.name.as_str())) {
|
|
346
|
+
errors.push(CheckError::at(e.line, e.column, format!("{}: type parameter '{n}' is declared twice", e.name)));
|
|
347
|
+
}
|
|
348
|
+
if let Some(n) = firstDuplicate(e.variants.iter().map(|v| v.name.as_str())) {
|
|
349
|
+
errors.push(CheckError::at(e.line, e.column, format!("{}: variant '{n}' is declared twice", e.name)));
|
|
350
|
+
}
|
|
351
|
+
for v in &e.variants {
|
|
352
|
+
if let Some(n) = firstDuplicate(v.field_names.iter().map(|f| f.as_str())) {
|
|
353
|
+
errors.push(CheckError::at(e.line, e.column, format!("{}: field '{n}' is declared twice", v.name)));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
ast::Item::Trait(t) => {
|
|
358
|
+
if let Some(n) = firstDuplicate(t.generics.iter().map(|g| g.name.as_str())) {
|
|
359
|
+
errors.push(CheckError::at(t.line, t.column, format!("{}: type parameter '{n}' is declared twice", t.name)));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
_ => {}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
errors
|
|
366
|
+
}
|
|
367
|
+
|
|
308
368
|
/// Does `t` name a type: one with consts, methods, statics or variants?
|
|
309
369
|
pub(crate) fn isKnownType(t: &str, env: &TypeEnv, ctx: &CheckCtx) -> bool {
|
|
310
370
|
let prefix = format!("{}{}", t, ast::MEMBER_SEP);
|
|
@@ -318,7 +378,7 @@ pub(crate) fn isKnownType(t: &str, env: &TypeEnv, ctx: &CheckCtx) -> bool {
|
|
|
318
378
|
.is_some_and(|(owner, _)| owner == t)
|
|
319
379
|
})
|
|
320
380
|
|| ctx.enum_params.contains_key(t)
|
|
321
|
-
|| ctx.enum_variants.
|
|
381
|
+
|| ctx.enum_variants.isEnum(t)
|
|
322
382
|
}
|
|
323
383
|
|
|
324
384
|
/// The error for a `TypeName` that is neither a global, a variant nor a type
|
compiler/checker/src/env.rs
CHANGED
|
@@ -86,6 +86,23 @@ impl TypeEnv {
|
|
|
86
86
|
.any(|(k, _)| !matches!(self.own.get(k), Some(None)))
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/// The bindings whose name starts with `prefix`, in key order (a range lookup, not a
|
|
90
|
+
/// scan of every global).
|
|
91
|
+
pub fn withPrefix<'a>(&'a self, prefix: &'a str) -> impl Iterator<Item = (&'a String, &'a TypeScheme)> + 'a {
|
|
92
|
+
let from = || (std::ops::Bound::Included(prefix), std::ops::Bound::Unbounded);
|
|
93
|
+
let own = self
|
|
94
|
+
.own
|
|
95
|
+
.range::<str, _>(from())
|
|
96
|
+
.take_while(move |(k, _)| k.starts_with(prefix))
|
|
97
|
+
.filter_map(|(k, v)| v.as_ref().map(|v| (k, v)));
|
|
98
|
+
let base = self
|
|
99
|
+
.base
|
|
100
|
+
.range::<str, _>(from())
|
|
101
|
+
.take_while(move |(k, _)| k.starts_with(prefix))
|
|
102
|
+
.filter(move |(k, _)| !self.own.contains_key(k.as_str()));
|
|
103
|
+
own.chain(base)
|
|
104
|
+
}
|
|
105
|
+
|
|
89
106
|
pub fn iter(&self) -> Iter<'_> {
|
|
90
107
|
Iter { base: self.base.iter().peekable(), own: self.own.iter().peekable() }
|
|
91
108
|
}
|
compiler/checker/src/fields.rs
CHANGED
|
@@ -10,8 +10,9 @@ pub(crate) fn immutableFieldOwner(obj_ty: &PlumType, field: &str, ctx: &CheckCtx
|
|
|
10
10
|
};
|
|
11
11
|
let owners: Vec<&EnumVariantInfo> = ctx
|
|
12
12
|
.enum_variants
|
|
13
|
-
.
|
|
13
|
+
.variantsOf(n)
|
|
14
|
+
.map(|(_, i)| i)
|
|
14
|
-
.filter(|i| i.
|
|
15
|
+
.filter(|i| i.field_names.iter().any(|f| f == field))
|
|
15
16
|
.collect();
|
|
16
17
|
let [info] = owners.as_slice() else { return None };
|
|
17
18
|
if info.is_value {
|
|
@@ -145,10 +146,9 @@ pub(crate) fn lookupFieldType(
|
|
|
145
146
|
None => {
|
|
146
147
|
let owners: Vec<&EnumVariantInfo> = ctx
|
|
147
148
|
.enum_variants
|
|
148
|
-
.
|
|
149
|
+
.variantsOf(class_name)
|
|
149
|
-
.
|
|
150
|
+
.map(|(_, i)| i)
|
|
150
|
-
|
|
151
|
+
.filter(|info| info.field_names.iter().any(|n| n == field_name))
|
|
151
|
-
})
|
|
152
152
|
.collect();
|
|
153
153
|
match owners.as_slice() {
|
|
154
154
|
[info] => {
|
|
@@ -168,9 +168,7 @@ pub(crate) fn lookupFieldType(
|
|
|
168
168
|
// codegen will catch a genuine mismatch, exactly as it always has).
|
|
169
169
|
// Distinguish by whether any variant belonging to this enum name
|
|
170
170
|
// declares named fields at all.
|
|
171
|
-
[] if ctx.enum_variants.values().any(|info| {
|
|
172
|
-
|
|
171
|
+
[] if ctx.enum_variants.variantsOf(class_name).any(|(_, info)| !info.field_names.is_empty()) =>
|
|
173
|
-
}) =>
|
|
174
172
|
{
|
|
175
173
|
Err(format!(
|
|
176
174
|
"no field '{}' on type '{}'",
|
compiler/checker/src/fncheck.rs
CHANGED
|
@@ -229,6 +229,19 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
|
|
|
229
229
|
if let Some(err) = checkReturned(last_expr, &env, ctx, &declared_ret, &f.name, (line, column)) {
|
|
230
230
|
errors.push(err);
|
|
231
231
|
}
|
|
232
|
+
} else if let Some(last @ ast::Stmt { kind: ast::StmtKind::Assign(_), .. }) = block.stmts.last() {
|
|
233
|
+
// A body ending in a declaration has no value to return.
|
|
234
|
+
if !matches!(declared_ret, PlumType::TUnit) && errors.is_empty() {
|
|
235
|
+
let (l, c) = if last.span.startLine > 0 { (last.span.startLine, last.span.startColumn) } else { (f.line, f.column) };
|
|
236
|
+
errors.push(CheckError::at(
|
|
237
|
+
l,
|
|
238
|
+
c,
|
|
239
|
+
format!(
|
|
240
|
+
"fn '{}': the body ends in a declaration, so it has no value; end it with the {} to return",
|
|
241
|
+
f.name, declared_ret
|
|
242
|
+
),
|
|
243
|
+
));
|
|
244
|
+
}
|
|
232
245
|
}
|
|
233
246
|
}
|
|
234
247
|
// Ruled out (and returned early) by the `is_extern`/body coherence check above.
|
compiler/checker/src/generics.rs
CHANGED
|
@@ -45,9 +45,9 @@ pub(crate) fn ownerGenericsIn(
|
|
|
45
45
|
prims: &PrimitiveGenerics,
|
|
46
46
|
) -> Vec<String> {
|
|
47
47
|
enum_variants
|
|
48
|
+
.variantsOf(recv)
|
|
48
|
-
.
|
|
49
|
+
.next()
|
|
49
|
-
.find(|i| i.enum_name == recv)
|
|
50
|
-
.map(|i| i.generics.clone())
|
|
50
|
+
.map(|(_, i)| i.generics.clone())
|
|
51
51
|
.or_else(|| prims.get(recv).cloned())
|
|
52
52
|
.unwrap_or_default()
|
|
53
53
|
}
|
|
@@ -61,9 +61,9 @@ pub fn enumGenericParams(e: &ast::Enum) -> Vec<String> {
|
|
|
61
61
|
/// The generic parameter names of enum `name` (empty if non-generic/unknown).
|
|
62
62
|
pub(crate) fn enumGenericsOf<'a>(name: &str, ctx: &'a CheckCtx) -> &'a [String] {
|
|
63
63
|
ctx.enum_variants
|
|
64
|
+
.variantsOf(name)
|
|
64
|
-
.
|
|
65
|
+
.next()
|
|
65
|
-
.find(|i| i.enum_name == name)
|
|
66
|
-
.map(|i| i.generics.as_slice())
|
|
66
|
+
.map(|(_, i)| i.generics.as_slice())
|
|
67
67
|
.or_else(|| ctx.primitive_generics.get(name).map(|g| g.as_slice()))
|
|
68
68
|
.unwrap_or(&[])
|
|
69
69
|
}
|
compiler/checker/src/identity.rs
CHANGED
|
@@ -41,7 +41,7 @@ fn whyNotHeap(t: &PlumType, ctx: &CheckCtx) -> Option<&'static str> {
|
|
|
41
41
|
PlumType::TFun(..) => Some("is a function"),
|
|
42
42
|
PlumType::TParam(_) | PlumType::TVar(_) => Some("is a type parameter, which may be a scalar"),
|
|
43
43
|
PlumType::TNamed(n) if n == ast::IO_TYPE => Some("is a capability, not an object"),
|
|
44
|
-
PlumType::TNamed(n) if ctx.enum_variants.
|
|
44
|
+
PlumType::TNamed(n) if ctx.enum_variants.variantsOf(n).any(|(_, i)| i.is_value) => {
|
|
45
45
|
Some("is a flat struct, copied by value")
|
|
46
46
|
}
|
|
47
47
|
_ => None,
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -73,6 +73,9 @@ pub(crate) fn bindCondEnv(cond: &ast::Expr, env: &TypeEnv, ctx: &CheckCtx) -> Re
|
|
|
73
73
|
benv.insert(n.clone(), TypeScheme::mono(PlumType::TVar("_".to_string())));
|
|
74
74
|
}
|
|
75
75
|
pat => {
|
|
76
|
+
if let Some(n) = duplicateBinder(std::slice::from_ref(pat)) {
|
|
77
|
+
return Err(format!("'{n}' is bound twice in one pattern"));
|
|
78
|
+
}
|
|
76
79
|
withCheck(|s| { let c = &s.allow_bare_top; c.set(true) });
|
|
77
80
|
let r = checkPattern(pat, &ty, &mut benv, ctx);
|
|
78
81
|
withCheck(|s| { let c = &s.allow_bare_top; c.set(false) });
|
|
@@ -191,6 +194,13 @@ pub(crate) fn inferExprInner(
|
|
|
191
194
|
ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => {
|
|
192
195
|
let self_name = withCheck(|s| s.closure_self.borrow_mut().take());
|
|
193
196
|
let mut closure_env = env.clone();
|
|
197
|
+
// An enclosing closure's own signature is not callable from in here: it is only
|
|
198
|
+
// bound once that closure is done (codegen has no value to capture yet).
|
|
199
|
+
let outer: Vec<String> = closure_env.withPrefix(SELF_KEY).map(|(k, _)| k.clone()).collect();
|
|
200
|
+
for k in outer {
|
|
201
|
+
closure_env.remove(&k);
|
|
202
|
+
closure_env.insert(format!("{}{}", NESTED_SELF_KEY, &k[SELF_KEY.len()..]), TypeScheme::mono(PlumType::TUnit));
|
|
203
|
+
}
|
|
194
204
|
let param_names: std::collections::HashSet<&str> =
|
|
195
205
|
cl.params.iter().map(|s| s.as_str()).collect();
|
|
196
206
|
let mut resolved_from_usage: BTreeMap<String, PlumType> = BTreeMap::new();
|
|
@@ -213,6 +223,9 @@ pub(crate) fn inferExprInner(
|
|
|
213
223
|
Some((v, strict)) => (Some(v), strict),
|
|
214
224
|
None => (None, false),
|
|
215
225
|
};
|
|
226
|
+
if let Some(n) = firstDuplicate(cl.params.iter().map(|p| p.as_str())) {
|
|
227
|
+
return Err(format!("closure parameter '{n}' is declared twice"));
|
|
228
|
+
}
|
|
216
229
|
let mut param_types: Vec<PlumType> = Vec::new();
|
|
217
230
|
for (i, p) in cl.params.iter().enumerate() {
|
|
218
231
|
let declared = cl.param_types.get(i).and_then(|t| t.as_ref()).map(plumTypeFromAstG);
|
|
@@ -478,7 +491,7 @@ pub(crate) fn inferExprInner(
|
|
|
478
491
|
// `Link(1, 2)` is `Link.init(1, 2)`; variant names win (they are in
|
|
479
492
|
// `enum_variants` under their own key).
|
|
480
493
|
let isEnumName = !ctx.enum_variants.contains_key(&call.name)
|
|
481
|
-
&& ctx.enum_variants.
|
|
494
|
+
&& ctx.enum_variants.isEnum(&call.name);
|
|
482
495
|
let hasInit = ctx
|
|
483
496
|
.methods
|
|
484
497
|
.contains_key(&(call.name.clone(), "init".to_string()));
|
|
@@ -544,6 +557,10 @@ pub(crate) fn inferExprInner(
|
|
|
544
557
|
let mut binds = Binds::new();
|
|
545
558
|
let label = format!("call '{}'", call.name);
|
|
546
559
|
applyTypeArgs(&label, None, &call.name, &call.type_args, &mut call_map, &mut binds, ctx)?;
|
|
560
|
+
// (A local fn value named like a top-level fn has no generics.)
|
|
561
|
+
if call.type_args.is_empty() && env.contains_key(&format!("{}{}", GLOBAL_KEY, call.name)) {
|
|
562
|
+
checkUnsetGenerics(None, &call.name, &call_map)?;
|
|
563
|
+
}
|
|
547
564
|
if let Some(exp) = expected {
|
|
548
565
|
bindMatch(&ret, exp, &mut binds);
|
|
549
566
|
}
|
|
@@ -563,6 +580,15 @@ pub(crate) fn inferExprInner(
|
|
|
563
580
|
recordCall(None, &call.name, call_map);
|
|
564
581
|
Ok(substVars(&ret, &binds))
|
|
565
582
|
}
|
|
583
|
+
// A name whose declaration failed (bound as the wildcard so its uses don't
|
|
584
|
+
// cascade), or an erased generic body's unknown value: its arguments are still
|
|
585
|
+
// typed, and the error, if any, is the declaration's.
|
|
586
|
+
Ok(PlumType::TVar(v)) if v == "_" => {
|
|
587
|
+
for a in &call.args {
|
|
588
|
+
inferExpr(argExpr(a), env, ctx)?;
|
|
589
|
+
}
|
|
590
|
+
Ok(PlumType::TVar("_".to_string()))
|
|
591
|
+
}
|
|
566
592
|
Ok(_) => Err(format!("'{}' is not a function", call.name)),
|
|
567
593
|
// `k => v` desugars to `Pair(k, v)`; without std/Map there is no Pair.
|
|
568
594
|
Err(_) if call.name == "Pair" => {
|
|
@@ -570,13 +596,23 @@ pub(crate) fn inferExprInner(
|
|
|
570
596
|
markResolution();
|
|
571
597
|
Err(message)
|
|
572
598
|
}
|
|
573
|
-
//
|
|
599
|
+
// A closure calling itself (`SELF_KEY`; its name is bound only once it is
|
|
574
|
-
//
|
|
600
|
+
// done): its arguments are typed against its own parameters, and recorded.
|
|
575
601
|
Err(_) => {
|
|
576
602
|
let own = match env.get(&format!("{}{}", SELF_KEY, call.name)).map(|s| &*s.body) {
|
|
577
603
|
Some(PlumType::TFun(ps, _)) => Some(ps.clone()),
|
|
578
604
|
_ => None,
|
|
579
605
|
};
|
|
606
|
+
if own.is_none() {
|
|
607
|
+
markResolution();
|
|
608
|
+
if env.contains_key(&format!("{}{}", NESTED_SELF_KEY, call.name)) {
|
|
609
|
+
return Err(format!(
|
|
610
|
+
"'{0}' can call itself only from its own body, not from a closure inside it; make '{0}' a `fun`",
|
|
611
|
+
call.name
|
|
612
|
+
));
|
|
613
|
+
}
|
|
614
|
+
return Err(undefinedFunction(&call.name, env));
|
|
615
|
+
}
|
|
580
616
|
if let Some(ps) = &own {
|
|
581
617
|
if call.args.len() != ps.len() {
|
|
582
618
|
return Err(format!(
|
|
@@ -632,6 +668,14 @@ pub(crate) fn inferExprInner(
|
|
|
632
668
|
)),
|
|
633
669
|
},
|
|
634
670
|
ast::AttrKind::Method(call) => {
|
|
671
|
+
if matches!(&obj_ty, PlumType::TVar(n) if isInferVar(n)) && !withCheck(|s| s.inst_mode.get()) {
|
|
672
|
+
let (l, c) = (call.line, call.column);
|
|
673
|
+
let e = CheckError::at(l, c, format!(
|
|
674
|
+
"can't work out the type of the value '{}' is called on; annotate it (e.g. `xs: List[Int] := []`, `|x: Str| ..`)",
|
|
675
|
+
call.name
|
|
676
|
+
));
|
|
677
|
+
withCheck(|s| s.open_receivers.borrow_mut().push((attr.object.id, e)));
|
|
678
|
+
}
|
|
635
679
|
checkStaticUse(&attr.object, &obj_ty, &call.name, ctx)?;
|
|
636
680
|
inferMethodCallWith(&obj_ty, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected)
|
|
637
681
|
}
|
|
@@ -644,7 +688,7 @@ pub(crate) fn inferExprInner(
|
|
|
644
688
|
/// `field` (fields are read by pattern there). Empty for structs and when none has it.
|
|
645
689
|
pub(crate) fn variantsWithField(en: &str, field: &str, ctx: &CheckCtx) -> Vec<String> {
|
|
646
690
|
let vs: Vec<(&String, &EnumVariantInfo)> =
|
|
647
|
-
ctx.enum_variants.
|
|
691
|
+
ctx.enum_variants.variantsOf(en).collect();
|
|
648
692
|
if vs.len() < 2 {
|
|
649
693
|
return Vec::new();
|
|
650
694
|
}
|
compiler/checker/src/matchcheck.rs
CHANGED
|
@@ -58,11 +58,7 @@ pub(crate) fn coverCtors(ty: &PlumType, ctx: &CheckCtx) -> Option<(String, Vec<C
|
|
|
58
58
|
.collect(),
|
|
59
59
|
)),
|
|
60
60
|
PlumType::TNamed(enum_name) | PlumType::TApp(enum_name, _) => {
|
|
61
|
-
let mut vs: Vec<(&String, &EnumVariantInfo)> = ctx
|
|
61
|
+
let mut vs: Vec<(&String, &EnumVariantInfo)> = ctx.enum_variants.variantsOf(enum_name).collect();
|
|
62
|
-
.enum_variants
|
|
63
|
-
.iter()
|
|
64
|
-
.filter(|(_, i)| &i.enum_name == enum_name)
|
|
65
|
-
.collect();
|
|
66
62
|
if vs.is_empty() {
|
|
67
63
|
return None;
|
|
68
64
|
}
|
|
@@ -214,6 +210,10 @@ pub(crate) fn checkMatch(
|
|
|
214
210
|
return errors; // a subject failed to type — cases can't be checked meaningfully
|
|
215
211
|
}
|
|
216
212
|
|
|
213
|
+
// The index of a "non-exhaustive" error, dropped again when a pattern is malformed (the
|
|
214
|
+
// arm it doesn't count is the user's, written wrong).
|
|
215
|
+
let mut exhaustive_at = None;
|
|
216
|
+
let mut bad_pattern = false;
|
|
217
217
|
if let [subject_ty] = subject_types.as_slice() {
|
|
218
218
|
let subject = resolveRecorded(subject_ty);
|
|
219
219
|
if isTraitObject(&subject)
|
|
@@ -237,6 +237,7 @@ pub(crate) fn checkMatch(
|
|
|
237
237
|
if let Err(CoverFail::Reported(label, missing)) =
|
|
238
238
|
coverRows(rows, std::slice::from_ref(subject_ty), ctx)
|
|
239
239
|
{
|
|
240
|
+
exhaustive_at = Some(errors.len());
|
|
240
241
|
errors.push(CheckError::at(
|
|
241
242
|
fn_pos.0,
|
|
242
243
|
fn_pos.1,
|
|
@@ -252,6 +253,13 @@ pub(crate) fn checkMatch(
|
|
|
252
253
|
|
|
253
254
|
for case in &m.cases {
|
|
254
255
|
let mut case_env = env.clone();
|
|
256
|
+
if let Some(n) = duplicateBinder(&case.patterns) {
|
|
257
|
+
errors.push(CheckError::at(
|
|
258
|
+
fn_pos.0,
|
|
259
|
+
fn_pos.1,
|
|
260
|
+
format!("fn '{}': match case: '{}' is bound twice in one pattern", fn_name, n),
|
|
261
|
+
));
|
|
262
|
+
}
|
|
255
263
|
if case.patterns.len() == subject_types.len() {
|
|
256
264
|
for (pat, sty) in case.patterns.iter().zip(subject_types.iter()) {
|
|
257
265
|
if let Err(msg) = checkPattern(pat, sty, &mut case_env, ctx) {
|
|
@@ -260,6 +268,15 @@ pub(crate) fn checkMatch(
|
|
|
260
268
|
fn_pos.1,
|
|
261
269
|
format!("fn '{}': match case: {}", fn_name, msg),
|
|
262
270
|
));
|
|
271
|
+
bad_pattern = true;
|
|
272
|
+
// Its names are still bound, so the arm's body doesn't cascade.
|
|
273
|
+
let mut names = Vec::new();
|
|
274
|
+
plum_core::visit::patternBinders(pat, &mut names);
|
|
275
|
+
for n in names {
|
|
276
|
+
if !case_env.contains_key(&n) {
|
|
277
|
+
bindLocal(&mut case_env, &n, TypeScheme::mono(PlumType::TVar("_".to_string())));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
263
280
|
}
|
|
264
281
|
}
|
|
265
282
|
} else {
|
|
@@ -275,7 +292,7 @@ pub(crate) fn checkMatch(
|
|
|
275
292
|
));
|
|
276
293
|
}
|
|
277
294
|
// A discarded `f()?` (`plum_core::question`): the unwrapped value must be Unit.
|
|
278
|
-
for (k, v) in case_env.
|
|
295
|
+
for (k, v) in case_env.withPrefix(plum_core::question::UNUSED_PREFIX) {
|
|
279
296
|
let ty = resolveRecorded(&v.body);
|
|
280
297
|
if !matches!(ty, PlumType::TUnit | PlumType::TVar(_)) {
|
|
281
298
|
let callee = k[plum_core::question::UNUSED_PREFIX.len()..].rsplit_once('_').map(|x| x.0).unwrap_or("value");
|
|
@@ -319,5 +336,23 @@ pub(crate) fn checkMatch(
|
|
|
319
336
|
ctx,
|
|
320
337
|
));
|
|
321
338
|
}
|
|
339
|
+
if let (Some(i), true) = (exhaustive_at, bad_pattern) {
|
|
340
|
+
errors.remove(i);
|
|
341
|
+
}
|
|
322
342
|
errors
|
|
323
343
|
}
|
|
344
|
+
|
|
345
|
+
/// A name the patterns of one case bind twice (`P(a, a)`): the later binding would win.
|
|
346
|
+
pub(crate) fn duplicateBinder(patterns: &[ast::CasePattern]) -> Option<String> {
|
|
347
|
+
let mut names = Vec::new();
|
|
348
|
+
for p in patterns {
|
|
349
|
+
plum_core::visit::patternBinders(p, &mut names);
|
|
350
|
+
}
|
|
351
|
+
let n = firstDuplicate(names.iter().map(|n| n.as_str()))?;
|
|
352
|
+
// `forms` renames a binder bound earlier in the fn to `name__N` (both copies here).
|
|
353
|
+
let shown = match n.rsplit_once("__") {
|
|
354
|
+
Some((base, k)) if !base.is_empty() && !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()) => base,
|
|
355
|
+
_ => n,
|
|
356
|
+
};
|
|
357
|
+
Some(plum_core::diag::sourceName(shown))
|
|
358
|
+
}
|
compiler/checker/src/names.rs
CHANGED
|
@@ -12,6 +12,10 @@ pub(crate) const GLOBAL_KEY: &str = "$global:";
|
|
|
12
12
|
/// the closure is done; a self-call is the one use of this entry.
|
|
13
13
|
pub(crate) const SELF_KEY: &str = "$self:";
|
|
14
14
|
|
|
15
|
+
/// Env key prefix marking, inside a closure nested in a self-calling one, the outer
|
|
16
|
+
/// closure's name: a call to it from there is an error of its own (see `SELF_KEY`).
|
|
17
|
+
pub(crate) const NESTED_SELF_KEY: &str = "$nestedself:";
|
|
18
|
+
|
|
15
19
|
/// Binds the local `name`; a local named like a top-level fn shadows it, so it no
|
|
16
20
|
/// longer counts as that fn (a later `name = v` reassigns the local).
|
|
17
21
|
pub(crate) fn bindLocal(env: &mut TypeEnv, name: &str, scheme: TypeScheme) {
|
|
@@ -32,3 +36,44 @@ pub fn lookup(env: &TypeEnv, name: &str) -> Result<PlumType, String> {
|
|
|
32
36
|
pub(crate) fn undefinedName(name: &str) -> String {
|
|
33
37
|
format!("undefined name '{}'", name)
|
|
34
38
|
}
|
|
39
|
+
|
|
40
|
+
/// "undefined function 'name'" for a call whose callee is bound nowhere, with the closest
|
|
41
|
+
/// function or local in scope as a suggestion when one is near enough (`prinln` -> `println`).
|
|
42
|
+
pub(crate) fn undefinedFunction(name: &str, env: &TypeEnv) -> String {
|
|
43
|
+
if name == "Cons" {
|
|
44
|
+
return "a list literal `[..]` builds a std List: import std/List".to_string();
|
|
45
|
+
}
|
|
46
|
+
let candidates = env
|
|
47
|
+
.iter()
|
|
48
|
+
.filter(|(k, s)| !k.starts_with('$') && !k.starts_with("__") && matches!(&*s.body, PlumType::TFun(..)))
|
|
49
|
+
.map(|(k, _)| k.as_str());
|
|
50
|
+
match closestName(name, candidates) {
|
|
51
|
+
Some(c) => format!("undefined function '{name}'; did you mean '{c}'?"),
|
|
52
|
+
None => format!("undefined function '{name}'"),
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// The candidate nearest to `name` by edit distance, if it is within a third of its length
|
|
57
|
+
/// (at least 1): a typo, not an unrelated name.
|
|
58
|
+
pub(crate) fn closestName<'a>(name: &str, candidates: impl Iterator<Item = &'a str>) -> Option<&'a str> {
|
|
59
|
+
let limit = (name.chars().count() / 3).max(1);
|
|
60
|
+
candidates
|
|
61
|
+
.filter(|c| *c != name)
|
|
62
|
+
.map(|c| (editDistance(&name.to_lowercase(), &c.to_lowercase()), c))
|
|
63
|
+
.filter(|(d, _)| *d <= limit)
|
|
64
|
+
.min_by_key(|(d, c)| (*d, *c))
|
|
65
|
+
.map(|(_, c)| c)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fn editDistance(a: &str, b: &str) -> usize {
|
|
69
|
+
let b: Vec<char> = b.chars().collect();
|
|
70
|
+
let mut prev: Vec<usize> = (0..=b.len()).collect();
|
|
71
|
+
for (i, ca) in a.chars().enumerate() {
|
|
72
|
+
let mut cur = vec![i + 1; b.len() + 1];
|
|
73
|
+
for (j, cb) in b.iter().enumerate() {
|
|
74
|
+
cur[j + 1] = (prev[j] + usize::from(ca != *cb)).min(prev[j + 1] + 1).min(cur[j] + 1);
|
|
75
|
+
}
|
|
76
|
+
prev = cur;
|
|
77
|
+
}
|
|
78
|
+
prev[b.len()]
|
|
79
|
+
}
|
compiler/checker/src/patterns.rs
CHANGED
|
@@ -24,8 +24,8 @@ pub(crate) fn checkVariantPinned(
|
|
|
24
24
|
pub(crate) fn lowercaseTagMatch(n: &str, subject_ty: &PlumType, ctx: &CheckCtx) -> Option<String> {
|
|
25
25
|
let subject = nominalName(subject_ty)?;
|
|
26
26
|
ctx.enum_variants
|
|
27
|
-
.
|
|
27
|
+
.variantsOf(&subject)
|
|
28
|
-
.filter(|(k,
|
|
28
|
+
.filter(|(k, _)| k.as_str() != subject)
|
|
29
29
|
.map(|(k, _)| k.strip_prefix(&format!("{subject}__")).unwrap_or(k))
|
|
30
30
|
.find(|k| k.eq_ignore_ascii_case(n))
|
|
31
31
|
.map(|k| k.to_string())
|
|
@@ -157,7 +157,7 @@ fn downcastTarget(ty: &str, args: &[ast::Type], subject: &PlumType, ctx: &CheckC
|
|
|
157
157
|
let shown = plumTypeFromAstG(&written);
|
|
158
158
|
let want = if let Some(t) = currentTraits().traits.get(ty) {
|
|
159
159
|
t.generics.len()
|
|
160
|
-
} else if let Some(info) = ctx.enum_variants.
|
|
160
|
+
} else if let Some((_, info)) = ctx.enum_variants.variantsOf(ty).next() {
|
|
161
161
|
info.generics.len()
|
|
162
162
|
} else if withCheck(|s| s.scope.borrow().isGeneric(ty)) {
|
|
163
163
|
return Err(format!("`{shown} as ..`: {ty} is a type parameter and takes no type arguments"));
|
|
@@ -186,7 +186,7 @@ fn downcastTarget(ty: &str, args: &[ast::Type], subject: &PlumType, ctx: &CheckC
|
|
|
186
186
|
if isTraitObject(&PlumType::TNamed(ty.to_string())) {
|
|
187
187
|
return Ok(PlumType::TNamed(ty.to_string()));
|
|
188
188
|
}
|
|
189
|
-
let declared = ctx.enum_variants.
|
|
189
|
+
let declared = ctx.enum_variants.variantsOf(ty).next().map(|(_, i)| i);
|
|
190
190
|
match declared {
|
|
191
191
|
// A generic implementer takes its arguments from the trait object's.
|
|
192
192
|
Some(info) if !info.generics.is_empty() => match currentTraits().genericDowncast(ty, subject) {
|
compiler/checker/src/program.rs
CHANGED
|
@@ -122,22 +122,25 @@ pub(crate) fn ioCapabilityErrors(source: &ast::Source) -> Vec<CheckError> {
|
|
|
122
122
|
if !source.hasPrimitiveIo() {
|
|
123
123
|
return errors;
|
|
124
124
|
}
|
|
125
|
+
// Read in place: a copy of every body per check was most of this check's cost.
|
|
125
|
-
let mut
|
|
126
|
+
let mut visit = |e: &ast::Expr| match e {
|
|
126
|
-
plum_core::forms::mapExprs(body, &mut |e| match e {
|
|
127
|
-
|
|
127
|
+
ast::Expr { kind: ast::ExprKind::FnCall(c), .. } if c.name == ast::IO_TYPE => {
|
|
128
|
-
|
|
128
|
+
errors.push(CheckError::at(c.line, c.column, "Io has no constructor".to_string()));
|
|
129
|
-
|
|
129
|
+
}
|
|
130
|
-
|
|
130
|
+
ast::Expr { kind: ast::ExprKind::ClassCall(c), .. } if c.type_name == ast::IO_TYPE => {
|
|
131
|
-
|
|
131
|
+
errors.push(CheckError::at(0, 0, "Io has no constructor".to_string()));
|
|
132
|
-
|
|
132
|
+
}
|
|
133
|
-
|
|
133
|
+
_ => {}
|
|
134
|
-
});
|
|
135
134
|
};
|
|
136
135
|
for item in &source.items {
|
|
137
136
|
match item {
|
|
138
|
-
ast::Item::Fn(f) if !f.is_extern =>
|
|
137
|
+
ast::Item::Fn(f) if !f.is_extern => match &f.body {
|
|
138
|
+
ast::FnBody::Expr(e) => plum_core::visit::walkRef(e, &mut visit),
|
|
139
|
+
ast::FnBody::Block(b) => plum_core::visit::walkBlockRef(b, &mut visit),
|
|
140
|
+
ast::FnBody::Extern => {}
|
|
141
|
+
},
|
|
139
|
-
ast::Item::Test(t) =>
|
|
142
|
+
ast::Item::Test(t) => plum_core::visit::walkBlockRef(&t.body, &mut visit),
|
|
140
|
-
ast::Item::Const(c) =>
|
|
143
|
+
ast::Item::Const(c) => plum_core::visit::walkRef(&c.value, &mut visit),
|
|
141
144
|
_ => {}
|
|
142
145
|
}
|
|
143
146
|
}
|
|
@@ -177,6 +180,25 @@ pub(crate) fn checkSourceOnce(source: &ast::Source) -> (CheckResult<()>, TypedIn
|
|
|
177
180
|
withCheck(|s| { let r = &s.calls; r.borrow_mut().take() });
|
|
178
181
|
withCheck(|s| { let s = &s.tsubst; *s.borrow_mut() = None });
|
|
179
182
|
withCheck(|s| { let m = &s.inst_mode; m.set(false) });
|
|
183
|
+
// A method called on a value whose type nothing ever fixed.
|
|
184
|
+
let open = withCheck(|s| std::mem::take(&mut *s.open_receivers.borrow_mut()));
|
|
185
|
+
let mut open_errors: Vec<CheckError> = Vec::new();
|
|
186
|
+
for (id, e) in open {
|
|
187
|
+
let unresolved = match recorded.get(&(id, false)) {
|
|
188
|
+
Some(t) => matches!(substVars(t, &binds), PlumType::TVar(_)),
|
|
189
|
+
None => false,
|
|
190
|
+
};
|
|
191
|
+
if unresolved && !open_errors.iter().any(|o| o.line == e.line && o.column == e.column) {
|
|
192
|
+
open_errors.push(e);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
let result = if open_errors.is_empty() {
|
|
196
|
+
result
|
|
197
|
+
} else {
|
|
198
|
+
let mut errs = result.err().unwrap_or_default();
|
|
199
|
+
errs.extend(open_errors);
|
|
200
|
+
Err(errs)
|
|
201
|
+
};
|
|
180
202
|
// Zonk: apply the final substitution; a variable nothing ever constrained
|
|
181
203
|
// (an unused `None`, an empty literal, ...) is defaulted to `Unit`, since
|
|
182
204
|
// no value of it can ever be observed.
|
|
@@ -205,14 +227,16 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
205
227
|
errors.extend(checkUnknownTypes(source));
|
|
206
228
|
errors.extend(checkConstDecls(source));
|
|
207
229
|
errors.extend(checkBareGenericTypes(source));
|
|
230
|
+
errors.extend(checkDuplicateNames(source));
|
|
208
231
|
errors.extend(
|
|
209
232
|
source
|
|
210
233
|
.formErrors
|
|
211
234
|
.iter()
|
|
212
235
|
.map(|(l, c, m)| CheckError::at(*l, *c, m.clone())),
|
|
213
236
|
);
|
|
214
|
-
let (mut global_env, methods, enum_variants) = buildGlobalTables(source);
|
|
215
237
|
let traits = std::rc::Rc::new(buildTraits(source));
|
|
238
|
+
let primitive_generics = buildPrimitiveGenerics(source);
|
|
239
|
+
let (mut global_env, methods, enum_variants) = buildGlobalTablesWith(source, &traits, &primitive_generics);
|
|
216
240
|
withCheck(|s| *s.traits.borrow_mut() = traits.clone());
|
|
217
241
|
withCheck(|s| {
|
|
218
242
|
*s.fn_generics.borrow_mut() = source
|
|
@@ -238,8 +262,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
238
262
|
errors.extend(selfOutsideTrait(source));
|
|
239
263
|
// Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
|
|
240
264
|
let enum_params = EnumParams::new();
|
|
241
|
-
let min_required =
|
|
265
|
+
let min_required = buildMinRequiredArgsWith(source, &traits);
|
|
242
|
-
let primitive_generics = buildPrimitiveGenerics(source);
|
|
243
266
|
let statics = buildStaticMethods(source);
|
|
244
267
|
let ctx = CheckCtx {
|
|
245
268
|
methods: &methods,
|
|
@@ -303,6 +326,8 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
303
326
|
chains: Vec::new(),
|
|
304
327
|
queue: std::collections::VecDeque::new(),
|
|
305
328
|
file,
|
|
329
|
+
defaulted: HashMap::new(),
|
|
330
|
+
generics_of: HashMap::new(),
|
|
306
331
|
};
|
|
307
332
|
drainCalls();
|
|
308
333
|
withCheck(|s| { let c = &s.calls; {
|
|
@@ -339,6 +364,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
339
364
|
errors.push(e);
|
|
340
365
|
continue;
|
|
341
366
|
}
|
|
367
|
+
let open_before = withCheck(|s| s.open_receivers.borrow().len());
|
|
342
368
|
let mut local_errors = checkFn(f, &global_env, &ctx);
|
|
343
369
|
// A trait default's copy in an implementer: its errors are the default's own,
|
|
344
370
|
// reported once where the trait's default is checked.
|
|
@@ -350,6 +376,8 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
350
376
|
if !fnGenericNames(f, &ctx).is_empty() {
|
|
351
377
|
local_errors.retain(|e| e.kind == types::DiagKind::Resolution);
|
|
352
378
|
drainCalls();
|
|
379
|
+
// Its open receivers are typed per instantiation.
|
|
380
|
+
withCheck(|s| s.open_receivers.borrow_mut().truncate(open_before));
|
|
353
381
|
} else {
|
|
354
382
|
registerCalls(&mut inst, &fn_by_key, &ctx, None);
|
|
355
383
|
}
|
|
@@ -425,6 +453,25 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
425
453
|
inst.info.inst_expr_types.insert((id, node), t);
|
|
426
454
|
}
|
|
427
455
|
}
|
|
456
|
+
// A copy made for a generic nothing pinned (or one it reached): the call is the error.
|
|
457
|
+
let defaulted = {
|
|
458
|
+
let mut at = Some(id);
|
|
459
|
+
let mut found = None;
|
|
460
|
+
while let Some(k) = at {
|
|
461
|
+
if let Some(d) = inst.defaulted.get(&k) {
|
|
462
|
+
found = Some(d);
|
|
463
|
+
}
|
|
464
|
+
at = inst.info.instantiations[k].parent;
|
|
465
|
+
}
|
|
466
|
+
found
|
|
467
|
+
};
|
|
468
|
+
if let (Some(d), false) = (defaulted, errs.is_empty()) {
|
|
469
|
+
let e = d.error();
|
|
470
|
+
if seen_msgs.insert(e.message.clone()) {
|
|
471
|
+
errors.push(e);
|
|
472
|
+
}
|
|
473
|
+
errs.clear();
|
|
474
|
+
}
|
|
428
475
|
for e in errs {
|
|
429
476
|
let msg = match (e.message.strip_prefix("fn '"), e.message.find("': ")) {
|
|
430
477
|
(Some(_), Some(k)) => e.message[k + 3..].to_string(),
|
|
@@ -438,7 +485,12 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
438
485
|
registerCalls(&mut inst, &fn_by_key, &ctx, Some(id));
|
|
439
486
|
}
|
|
440
487
|
|
|
488
|
+
// A call with an unmet bound is never instantiated, so each later call reports it again.
|
|
441
|
-
|
|
489
|
+
for e in withCheck(|s| std::mem::take(&mut *s.bound_errors.borrow_mut())) {
|
|
490
|
+
if !errors.iter().any(|o| o.message == e.message && o.line == e.line && o.column == e.column) {
|
|
491
|
+
errors.push(e);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
442
494
|
inst.info.traits = traits;
|
|
443
495
|
let result = if errors.is_empty() {
|
|
444
496
|
Ok(())
|
compiler/checker/src/state.rs
CHANGED
|
@@ -86,6 +86,10 @@ pub(crate) struct CheckState {
|
|
|
86
86
|
/// Each fn's and method's own declared generics, in order ((owner, name) -> names), for
|
|
87
87
|
/// a call's explicit type arguments (`findAs[Orb](..)`).
|
|
88
88
|
pub(crate) fn_generics: RefCell<HashMap<(Option<String>, String), Vec<String>>>,
|
|
89
|
+
/// Method calls on a value whose type was still an inference variable when the call was
|
|
90
|
+
/// typed (`xs := []` then `xs.map(|x| x.length())`), by the receiver's node id: an error
|
|
91
|
+
/// if nothing ever fixed that type (`checkSourceOnce`), as codegen would see `Unit`.
|
|
92
|
+
pub(crate) open_receivers: RefCell<Vec<(ast::NodeId, crate::types::CheckError)>>,
|
|
89
93
|
}
|
|
90
94
|
|
|
91
95
|
thread_local! {
|
compiler/checker/src/stmt.rs
CHANGED
|
@@ -57,6 +57,12 @@ pub(crate) fn checkStmt(
|
|
|
57
57
|
let prev_ret = withCheck(|s| s.cur_ret.replace(Some(declared_ret.clone())));
|
|
58
58
|
let (mut errors, pos, _) = withFailure(|| checkStmtInner(stmt, env, declared_ret, fn_name, fn_pos, ctx));
|
|
59
59
|
withCheck(|s| *s.cur_ret.borrow_mut() = prev_ret);
|
|
60
|
+
// With no failing node to point at, an error is the statement's own: at its span, not at
|
|
61
|
+
// the enclosing fn's line (a statement a pass built has none, and keeps `fn_pos`).
|
|
62
|
+
let sp = &stmt.span;
|
|
63
|
+
let pos = pos.or_else(|| {
|
|
64
|
+
(sp.startLine != 0).then_some(((sp.startLine, sp.startColumn), (sp.endLine, sp.endColumn)))
|
|
65
|
+
});
|
|
60
66
|
if let Some(((l, c), (el, ec))) = pos {
|
|
61
67
|
for e in errors.iter_mut().filter(|e| (e.line, e.column) == fn_pos) {
|
|
62
68
|
e.line = l;
|
|
@@ -108,6 +114,10 @@ pub(crate) fn checkStmtInner(
|
|
|
108
114
|
} else {
|
|
109
115
|
let declared = plumTypeFromAstG(ann);
|
|
110
116
|
let value = &a.values[0];
|
|
117
|
+
// `f: fn(Int) -> Int := |n| .. f(n - 1)` calls itself, as an unannotated one may.
|
|
118
|
+
if matches!(value.kind, ast::ExprKind::Closure(_)) {
|
|
119
|
+
withCheck(|s| *s.closure_self.borrow_mut() = Some(name.to_string()));
|
|
120
|
+
}
|
|
111
121
|
match inferExprWith(value, env, ctx, Some(&declared)) {
|
|
112
122
|
Ok(t) => match unifyArg(&declared, &t, value, ctx) {
|
|
113
123
|
Ok(()) => {
|
|
@@ -141,6 +151,24 @@ pub(crate) fn checkStmtInner(
|
|
|
141
151
|
}
|
|
142
152
|
return errors;
|
|
143
153
|
}
|
|
154
|
+
if a.targets.len() != a.values.len() {
|
|
155
|
+
errors.push(CheckError::at(
|
|
156
|
+
fn_pos.0,
|
|
157
|
+
fn_pos.1,
|
|
158
|
+
format!(
|
|
159
|
+
"fn '{}': assign: {} name(s) but {} value(s); give one value per name",
|
|
160
|
+
fn_name,
|
|
161
|
+
a.targets.len(),
|
|
162
|
+
a.values.len()
|
|
163
|
+
),
|
|
164
|
+
));
|
|
165
|
+
// The names without a value are still declared: no "undefined name" later.
|
|
166
|
+
for t in a.targets.iter().skip(a.values.len()) {
|
|
167
|
+
if let ast::AssignTarget::Var(n) = t {
|
|
168
|
+
bindLocal(env, n, TypeScheme::mono(PlumType::TVar("_".to_string())));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
144
172
|
for (target, value) in a.targets.iter().zip(a.values.iter()) {
|
|
145
173
|
match target {
|
|
146
174
|
// `_ := value` evaluates and drops the value; nothing is bound.
|
|
@@ -220,6 +248,19 @@ pub(crate) fn checkStmtInner(
|
|
|
220
248
|
withCheck(|s| *s.closure_self.borrow_mut() = Some(name.clone()));
|
|
221
249
|
}
|
|
222
250
|
match inferExpr(value, env, ctx) {
|
|
251
|
+
// A local can't hold the result of a call that returns nothing.
|
|
252
|
+
Ok(PlumType::TUnit) if !a.isSynthetic && discardedCall(value).is_some() => {
|
|
253
|
+
let callee = discardedCall(value).map(|c| c.name.clone()).unwrap_or_default();
|
|
254
|
+
errors.push(CheckError::at(
|
|
255
|
+
fn_pos.0,
|
|
256
|
+
fn_pos.1,
|
|
257
|
+
format!(
|
|
258
|
+
"fn '{}': assign '{}': '{}' returns nothing (Unit), so there is no value to keep; call it as a statement",
|
|
259
|
+
fn_name, name, plum_core::diag::sourceName(&callee)
|
|
260
|
+
),
|
|
261
|
+
));
|
|
262
|
+
bindLocal(env, name, TypeScheme::mono(PlumType::TVar("_".to_string())));
|
|
263
|
+
}
|
|
223
264
|
Ok(t) => {
|
|
224
265
|
if let Some(rest) = name.strip_prefix(ast::FOR_ITER_PREFIX) {
|
|
225
266
|
// A lowered iterable `for`: the source needs
|
|
@@ -598,7 +639,7 @@ fn checkLoop(
|
|
|
598
639
|
let has = |m: &str| ctx.methods.contains_key(&(name.clone(), m.to_string()));
|
|
599
640
|
Some(plum_core::forms::TyInfo {
|
|
600
641
|
iterable: has("length") && has("at"),
|
|
601
|
-
methods:
|
|
642
|
+
methods: methodNamesOf(&name, ctx),
|
|
602
643
|
name,
|
|
603
644
|
})
|
|
604
645
|
};
|
|
@@ -639,7 +680,7 @@ fn recordLift(lp: &plum_core::forms::Loop, env: &TypeEnv, ctx: &CheckCtx) {
|
|
|
639
680
|
Some((
|
|
640
681
|
plum_core::forms::TyInfo {
|
|
641
682
|
iterable: has("length") && has("at"),
|
|
642
|
-
methods:
|
|
683
|
+
methods: methodNamesOf(&name, ctx),
|
|
643
684
|
name,
|
|
644
685
|
},
|
|
645
686
|
t,
|
compiler/checker/src/tables.rs
CHANGED
|
@@ -27,7 +27,67 @@ pub struct EnumVariantInfo {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/// Enum variant name -> its info, e.g. `"Red" -> { enum_name: "Color", tag: 1, field_types: [] }`.
|
|
30
|
+
/// Read as the map it derefs to; also indexed by enum name (`variantsOf`), so a lookup by
|
|
31
|
+
/// the enum is not a scan of every variant of the program.
|
|
32
|
+
#[derive(Debug, Clone, Default, PartialEq)]
|
|
33
|
+
pub struct EnumVariants {
|
|
34
|
+
map: BTreeMap<String, EnumVariantInfo>,
|
|
35
|
+
/// Enum name -> its variants' names, in declaration (tag) order.
|
|
36
|
+
by_enum: BTreeMap<String, Vec<String>>,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
impl EnumVariants {
|
|
40
|
+
pub fn new() -> Self {
|
|
41
|
+
Self::default()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
pub fn insert(&mut self, variant: String, info: EnumVariantInfo) -> Option<EnumVariantInfo> {
|
|
45
|
+
let names = self.by_enum.entry(info.enum_name.clone()).or_default();
|
|
46
|
+
if !names.contains(&variant) {
|
|
47
|
+
names.push(variant.clone());
|
|
48
|
+
}
|
|
49
|
+
let prev = self.map.insert(variant.clone(), info);
|
|
50
|
+
if let Some(p) = &prev {
|
|
51
|
+
if p.enum_name != self.map[&variant].enum_name {
|
|
52
|
+
if let Some(old) = self.by_enum.get_mut(&p.enum_name) {
|
|
53
|
+
old.retain(|n| n != &variant);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
prev
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// The variants of enum `enum_name` (name and info), in tag order; none if it isn't one.
|
|
61
|
+
pub fn variantsOf<'a>(&'a self, enum_name: &str) -> impl Iterator<Item = (&'a String, &'a EnumVariantInfo)> + 'a {
|
|
62
|
+
self.by_enum
|
|
63
|
+
.get(enum_name)
|
|
64
|
+
.into_iter()
|
|
65
|
+
.flatten()
|
|
66
|
+
.filter_map(move |v| self.map.get_key_value(v))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// Whether `name` is a declared enum (or struct).
|
|
70
|
+
pub fn isEnum(&self, name: &str) -> bool {
|
|
71
|
+
self.by_enum.get(name).is_some_and(|v| !v.is_empty())
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
impl std::ops::Deref for EnumVariants {
|
|
30
|
-
|
|
76
|
+
type Target = BTreeMap<String, EnumVariantInfo>;
|
|
77
|
+
fn deref(&self) -> &Self::Target {
|
|
78
|
+
&self.map
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
impl FromIterator<(String, EnumVariantInfo)> for EnumVariants {
|
|
83
|
+
fn from_iter<I: IntoIterator<Item = (String, EnumVariantInfo)>>(it: I) -> Self {
|
|
84
|
+
let mut e = EnumVariants::new();
|
|
85
|
+
for (k, v) in it {
|
|
86
|
+
e.insert(k, v);
|
|
87
|
+
}
|
|
88
|
+
e
|
|
89
|
+
}
|
|
90
|
+
}
|
|
31
91
|
|
|
32
92
|
/// Shared fields of every subtyped trait (`trait Actor(x: Int)`), keyed by the trait's
|
|
33
93
|
/// name — e.g. `"Actor" -> [("x", TInt)]`. Filled in by codegen (`addTraitParams`);
|
|
@@ -85,6 +145,11 @@ pub fn buildStaticMethods(source: &ast::Source) -> StaticMethods {
|
|
|
85
145
|
}
|
|
86
146
|
|
|
87
147
|
pub fn buildMinRequiredArgs(source: &ast::Source) -> MinRequiredArgs {
|
|
148
|
+
buildMinRequiredArgsWith(source, &buildTraits(source))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// `buildMinRequiredArgs` with the program's traits already built.
|
|
152
|
+
pub(crate) fn buildMinRequiredArgsWith(source: &ast::Source, traits: &crate::traits::Traits) -> MinRequiredArgs {
|
|
88
153
|
let mut result = MinRequiredArgs::new();
|
|
89
154
|
for item in &source.items {
|
|
90
155
|
if let ast::Item::Fn(f) = item {
|
|
@@ -99,7 +164,7 @@ pub fn buildMinRequiredArgs(source: &ast::Source) -> MinRequiredArgs {
|
|
|
99
164
|
result.insert((f.type_param.clone(), f.name.clone()), required);
|
|
100
165
|
}
|
|
101
166
|
}
|
|
102
|
-
addTraitMethods(
|
|
167
|
+
addTraitMethods(traits, &mut MethodEnv::new(), Some(&mut result));
|
|
103
168
|
result
|
|
104
169
|
}
|
|
105
170
|
|
|
@@ -121,10 +186,15 @@ pub struct CheckCtx<'a> {
|
|
|
121
186
|
/// `plum-wasm-codegen`, which needs the same tables to resolve `self`, field access,
|
|
122
187
|
/// and method dispatch during code generation.
|
|
123
188
|
pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVariants) {
|
|
189
|
+
buildGlobalTablesWith(source, &buildTraits(source), &buildPrimitiveGenerics(source))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// `buildGlobalTables` with the program's traits and primitive generics already built.
|
|
193
|
+
pub(crate) fn buildGlobalTablesWith(source: &ast::Source, traits: &crate::traits::Traits, prims: &PrimitiveGenerics) -> (TypeEnv, MethodEnv, EnumVariants) {
|
|
124
194
|
let conv = plumTypeFromAstG;
|
|
125
195
|
let mut global_env: TypeEnv = TypeEnv::new();
|
|
126
196
|
let mut methods: MethodEnv = BTreeMap::new();
|
|
127
|
-
let mut enum_variants: EnumVariants =
|
|
197
|
+
let mut enum_variants: EnumVariants = EnumVariants::new();
|
|
128
198
|
|
|
129
199
|
let flat = plum_core::layout::flatStructs(&source.items);
|
|
130
200
|
for item in &source.items {
|
|
@@ -155,7 +225,6 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVaria
|
|
|
155
225
|
_ => {}
|
|
156
226
|
}
|
|
157
227
|
}
|
|
158
|
-
let prims = buildPrimitiveGenerics(source);
|
|
159
228
|
|
|
160
229
|
// Second pass: register top-level function/method signatures and consts.
|
|
161
230
|
// Methods (`name<Receiver>(...)`) live in `methods`, keyed by receiver type,
|
|
@@ -166,7 +235,7 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVaria
|
|
|
166
235
|
let owner = f
|
|
167
236
|
.type_param
|
|
168
237
|
.as_deref()
|
|
169
|
-
.map(|r| ownerGenericsIn(r, &enum_variants,
|
|
238
|
+
.map(|r| ownerGenericsIn(r, &enum_variants, prims))
|
|
170
239
|
.unwrap_or_default();
|
|
171
240
|
let saved = setScope(
|
|
172
241
|
Scope::of(&owner, f),
|
|
@@ -225,7 +294,7 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVaria
|
|
|
225
294
|
}
|
|
226
295
|
}
|
|
227
296
|
|
|
228
|
-
addTraitMethods(
|
|
297
|
+
addTraitMethods(traits, &mut methods, None);
|
|
229
298
|
// Shared by every scope cloned from it (see `TypeEnv`).
|
|
230
299
|
global_env.freeze();
|
|
231
300
|
(global_env, methods, enum_variants)
|
compiler/checker/tests/checker/features/mod.rs
CHANGED
|
@@ -7,5 +7,6 @@ mod mutability;
|
|
|
7
7
|
mod optional_unpinned;
|
|
8
8
|
mod pattern_casing;
|
|
9
9
|
mod primitive_generics;
|
|
10
|
+
mod review_fixes;
|
|
10
11
|
mod types;
|
|
11
12
|
mod variant_pattern;
|
compiler/checker/tests/checker/features/review_fixes.rs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
//! Programs the checker used to accept (and codegen or the run then failed on), or
|
|
2
|
+
//! reported at the wrong place: each is now an error at the offending code.
|
|
3
|
+
use plum_core::Diagnostic;
|
|
4
|
+
|
|
5
|
+
const PRE: &str = "import std/Int\nimport std/Option\n";
|
|
6
|
+
|
|
7
|
+
/// Loads `src` (after `PRE`) with std and checks it; the errors, or the load error.
|
|
8
|
+
fn diags(src: &str) -> Vec<Diagnostic> {
|
|
9
|
+
let text = format!("{PRE}{src}");
|
|
10
|
+
let source = match plum_core::loader::loadAndMergeDiag(&write(&text), &plum_test_support::repoRoot()) {
|
|
11
|
+
Ok(s) => s,
|
|
12
|
+
Err(ds) => return ds,
|
|
13
|
+
};
|
|
14
|
+
match plum_driver::check(&source, &plum_driver::PassOptions::default()) {
|
|
15
|
+
Ok(_) => vec![],
|
|
16
|
+
Err(es) => es,
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
fn write(text: &str) -> std::path::PathBuf {
|
|
21
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
22
|
+
static N: AtomicUsize = AtomicUsize::new(0);
|
|
23
|
+
let dir = std::env::temp_dir().join(format!("plum_review_{}_{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst)));
|
|
24
|
+
std::fs::create_dir_all(&dir).unwrap();
|
|
25
|
+
let path = dir.join("main.plum");
|
|
26
|
+
std::fs::write(&path, text).unwrap();
|
|
27
|
+
path
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// The one error whose message contains `needle`, at `(line, column)` of the user's source
|
|
31
|
+
/// (lines counted from the first line after `PRE`).
|
|
32
|
+
fn expectAt(src: &str, needle: &str, line: usize, column: usize) {
|
|
33
|
+
let es = diags(src);
|
|
34
|
+
let e = es.iter().find(|e| e.message.contains(needle)).unwrap_or_else(|| panic!("no error with {needle:?}: {es:?}"));
|
|
35
|
+
let pre = PRE.lines().count();
|
|
36
|
+
assert_eq!((e.line, e.column), (line + pre, column), "{e:?}");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
fn expectOk(src: &str) {
|
|
40
|
+
let es = diags(src);
|
|
41
|
+
assert!(es.is_empty(), "{es:?}");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
#[test]
|
|
45
|
+
fn callToAnUndefinedFunctionIsAnErrorAtTheCall() {
|
|
46
|
+
expectAt("fun main() -> Int =\n nope(1)\n", "undefined function 'nope'", 2, 3);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#[test]
|
|
50
|
+
fn undefinedFunctionSuggestsTheClosestName() {
|
|
51
|
+
let es = diags("fun double(n: Int) -> Int = n * 2\n\nfun main() -> Int = doubel(2)\n");
|
|
52
|
+
assert!(es.iter().any(|e| e.message.contains("undefined function 'doubel'; did you mean 'double'?")), "{es:?}");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#[test]
|
|
56
|
+
fn mutuallyRecursiveClosuresAreRejected() {
|
|
57
|
+
let es = diags("test \"x\"\n ev := |n: Int| if n == 0 then true else od(n - 1)\n od := |n: Int| if n == 0 then false else ev(n - 1)\n assert ev(4)\n");
|
|
58
|
+
assert!(es.iter().any(|e| e.message.contains("undefined function 'od'")), "{es:?}");
|
|
59
|
+
// The failed declaration doesn't cascade into "'ev' is not a function".
|
|
60
|
+
assert!(!es.iter().any(|e| e.message.contains("is not a function")), "{es:?}");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#[test]
|
|
64
|
+
fn closureSelfCallStillWorks() {
|
|
65
|
+
expectOk("test \"x\"\n fact := |n: Int| if n <= 1 then 1 else n * fact(n - 1)\n assert fact(5) == 120\n");
|
|
66
|
+
expectOk("test \"x\"\n f: fn(Int) -> Int := |n| if n <= 0 then 0 else f(n - 1)\n assert f(3) == 0\n");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#[test]
|
|
70
|
+
fn unknownMethodOnAPrimitiveIsAnError() {
|
|
71
|
+
let es = diags("import std/Io\nimport std/Str\nfun main(io: Io) =\n io.println(\"hi\")\n");
|
|
72
|
+
assert!(es.iter().any(|e| e.message.contains("Io has no method 'println'")), "{es:?}");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#[test]
|
|
76
|
+
fn unpinnedGenericCallCompilesItsUnitCopy() {
|
|
77
|
+
let src = "fun mk[T]() -> Option[T] = None\n\ntest \"x\"\n o := mk()\n assert o.isNone()\n";
|
|
78
|
+
expectOk(src);
|
|
79
|
+
let src = "struct Box[T](v: Option[T]) =\n fun get(self) -> Option[T] = self.v\n\nfun empty[T]() -> Box[T] = Box(v: None)\n\nfun main() -> Bool =\n b := empty()\n b.get().isNone()\n";
|
|
80
|
+
expectOk(src);
|
|
81
|
+
plum_test_support::compile("unpinned_box", &format!("{PRE}{src}"));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
#[test]
|
|
85
|
+
fn unpinnedGenericWhoseUnitCopyFailsIsAnErrorAtTheCall() {
|
|
86
|
+
let src = "import std/Str\nimport std/List\nfun mk[T]() -> List[T] =\n xs: List[T] := []\n _ := xs.map(|x| x.toStr())\n xs\n\nfun main() -> Int = mk().length()\n";
|
|
87
|
+
expectAt(src, "can't work out T for 'mk'; annotate the result or write mk[Int](..)", 8, 21);
|
|
88
|
+
// A generic only its body uses is set by nothing at the call.
|
|
89
|
+
let src = "import std/Str\nfun show[T]() -> Str =\n o: Option[T] := None\n match o\n Some(x) => x.toStr()\n None => \"none\"\n\nfun main() -> Str = show()\n";
|
|
90
|
+
expectAt(src, "can't work out T for 'show'; write show[Int](..)", 8, 21);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
#[test]
|
|
94
|
+
fn methodOnAValueOfUnknownTypeIsAnError() {
|
|
95
|
+
let src = "import std/List\nimport std/Str\nfun f() -> Int =\n xs := []\n ys := xs.map(|x| x.length())\n ys.length()\n";
|
|
96
|
+
expectAt(src, "can't work out the type of the value 'length' is called on", 5, 20);
|
|
97
|
+
expectOk("import std/List\nfun f() -> Int =\n xs := []\n xs.length()\n");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
#[test]
|
|
101
|
+
fn statementErrorsAreAtTheStatement() {
|
|
102
|
+
expectAt("fun f(x: Int) -> Int =\n y := 1\n y := 2\n x\n", "already declared", 3, 3);
|
|
103
|
+
expectAt("import std/Str\nstruct T(mut n: Int)\n\ntest \"x\"\n t := T(n: 1)\n t.n = \"s\"\n assert t.n == 1\n", "assign 't.n'", 6, 3);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#[test]
|
|
107
|
+
fn assignCountsMustMatch() {
|
|
108
|
+
expectAt("test \"x\"\n a, b, c := 1, 2\n assert a == 1\n", "3 name(s) but 2 value(s)", 2, 3);
|
|
109
|
+
expectAt("test \"x\"\n a, b := 1, 2, 3\n assert a == 1\n", "2 name(s) but 3 value(s)", 2, 3);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
#[test]
|
|
113
|
+
fn duplicateNamesAreErrors() {
|
|
114
|
+
let cases = [
|
|
115
|
+
("fun f(a: Int, a: Int) -> Int = a\n", "parameter 'a' is declared twice"),
|
|
116
|
+
("fun f[T, T](x: T) -> T = x\n", "type parameter 'T' is declared twice"),
|
|
117
|
+
("struct P(x: Int, x: Int)\n", "field 'x' is declared twice"),
|
|
118
|
+
("enum E =\n | A\n | A\n", "variant 'A' is declared twice"),
|
|
119
|
+
("test \"x\"\n f := |a: Int, a: Int| a\n assert f(1, 2) == 1\n", "closure parameter 'a' is declared twice"),
|
|
120
|
+
("struct P(x: Int, y: Int)\n\ntest \"x\"\n p := P(x: 1, x: 2, y: 3)\n assert p.x == 2\n", "field 'x' is given twice"),
|
|
121
|
+
("struct P(x: Int, y: Int)\n\ntest \"x\"\n p := P(x: 1, y: 2)\n q := P(..p, x: 3, x: 4)\n assert q.x == 4\n", "field 'x' is given twice"),
|
|
122
|
+
("struct P(x: Int, y: Int)\n\nfun f(p: P) -> Int = match p\n P(a, a) => a\n", "'a' is bound twice in one pattern"),
|
|
123
|
+
("test \"x\"\n assert 1 == 1\n\ntest \"x\"\n assert 2 == 2\n", "duplicate test \"x\""),
|
|
124
|
+
("fun f() -> Int = 1\n\nfun f() -> Int = 2\n", "duplicate declaration of function 'f': already declared at line 3"),
|
|
125
|
+
];
|
|
126
|
+
for (src, needle) in cases {
|
|
127
|
+
let es = diags(src);
|
|
128
|
+
assert!(es.iter().any(|e| e.message.contains(needle)), "{src}\n{needle}\n{es:?}");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
#[test]
|
|
133
|
+
fn bindingAUnitResultIsAnError() {
|
|
134
|
+
let src = "struct T(mut n: Int)\n\nfun g(t: T) =\n t.n = 2\n\ntest \"x\"\n t := T(n: 1)\n u := g(t)\n assert t.n == 2\n";
|
|
135
|
+
expectAt(src, "'g' returns nothing", 8, 3);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#[test]
|
|
139
|
+
fn bodyEndingInADeclarationIsAnError() {
|
|
140
|
+
expectAt("fun f() -> Int =\n x := 1\n", "the body ends in a declaration", 2, 3);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#[test]
|
|
144
|
+
fn missingImportIsAtTheUseWithoutThePath() {
|
|
145
|
+
let es = diags("fun f() -> Str = \"a\"\n");
|
|
146
|
+
let e = es.iter().find(|e| e.message.contains("uses type 'Str' but doesn't import it")).expect("missing import");
|
|
147
|
+
assert!(!e.message.contains("main.plum"), "{e:?}");
|
|
148
|
+
assert_eq!(e.line, 1 + PRE.lines().count(), "{e:?}");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
#[test]
|
|
152
|
+
fn spreadFromAWholeEnumMustGiveEveryField() {
|
|
153
|
+
let e = "enum E =\n | A(x: Int, z: Int)\n | B(x: Int, y: Int)\n\n";
|
|
154
|
+
let es = diags(&format!("{e}fun f(e: E) -> E = A(..e, x: 5)\n"));
|
|
155
|
+
assert!(es.iter().any(|m| m.message.contains("a E may be another variant than A, so its 'z' can't be read")), "{es:?}");
|
|
156
|
+
// Nothing is read from the source when every field is given; a struct has one variant.
|
|
157
|
+
expectOk(&format!("{e}fun f(e: E) -> E = A(..e, x: 5, z: 6)\n"));
|
|
158
|
+
expectOk("struct P(x: Int, y: Int)\n\nfun mv(p: P) -> P = P(..p, x: p.x + 1)\n");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
#[test]
|
|
162
|
+
fn wrongTypeArgumentCountIsSaidSo() {
|
|
163
|
+
let es = diags("struct Box[T](v: T)\n\nfun f(b: Box[Int, Int]) -> Int = 1\n");
|
|
164
|
+
assert!(es.iter().any(|e| e.message.contains("type 'Box' takes 1 type argument(s), got 2")), "{es:?}");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#[test]
|
|
168
|
+
fn unmetBoundIsOneError() {
|
|
169
|
+
let src = "trait Sh =\n fun area(self) -> Int\n\nstruct A(n: Int)\n\nfun ar[T: Sh](x: T) -> Int = x.area()\n\nfun main() -> Int = ar(A(n: 1))\n";
|
|
170
|
+
let es = diags(src);
|
|
171
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
172
|
+
assert!(es[0].message.contains("A does not implement Sh"), "{es:?}");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#[test]
|
|
176
|
+
fn callChainNamesTheFile() {
|
|
177
|
+
let src = "fun nm[T](x: T) -> Int = x.nope()\n\nfun main() -> Int = nm(1)\n";
|
|
178
|
+
let es = diags(src);
|
|
179
|
+
let e = es.iter().find(|e| e.message.contains("Int has no method 'nope'")).expect("error");
|
|
180
|
+
assert!(e.message.contains("main.plum:5:21)"), "{e:?}");
|
|
181
|
+
assert!(!e.message.contains("<source>"), "{e:?}");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
#[test]
|
|
185
|
+
fn malformedPatternDoesNotCascade() {
|
|
186
|
+
let src = "enum Sh =\n | Ci(r: Int)\n | Sq(s: Int)\n\nfun f(s: Sh) -> Int = match s\n Ci(a, b) => a\n Sq(s) => s\n";
|
|
187
|
+
let es = diags(src);
|
|
188
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
189
|
+
assert!(es[0].message.contains("expects 1 field(s), got 2"), "{es:?}");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#[test]
|
|
193
|
+
fn nestedClosureCallingTheOuterOneIsAnError() {
|
|
194
|
+
let src = "test \"x\"\n outer := |n: Int|\n inner := |m: Int| if m <= 0 then 0 else outer(m - 1)\n inner(n)\n assert outer(3) == 0\n";
|
|
195
|
+
let es = diags(src);
|
|
196
|
+
assert!(es.iter().any(|e| e.message.contains("'outer' can call itself only from its own body")), "{es:?}");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#[test]
|
|
200
|
+
fn failingCompareInATestIsAtTheAssert() {
|
|
201
|
+
// `plum test` checks the program with its tests lowered to functions.
|
|
202
|
+
let text = format!("{PRE}import std/Str\ntest \"x\"\n y := 1\n assert y == \"a\"\n");
|
|
203
|
+
let source = plum_core::loader::loadAndMergeDiag(&write(&text), &plum_test_support::repoRoot()).expect("loads");
|
|
204
|
+
let lowered = plum_core::tests_lower::lowerTests(&source).source;
|
|
205
|
+
let es = plum_driver::check(&lowered, &plum_driver::PassOptions::default()).expect_err("mismatch");
|
|
206
|
+
let e = es.iter().find(|e| e.message.contains("compare op")).expect("compare error");
|
|
207
|
+
assert_eq!((e.line, e.column), (6, 3), "{es:?}");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#[test]
|
|
211
|
+
fn listLiteralWithoutStdListSaysToImportIt() {
|
|
212
|
+
let es = diags("fun main() -> Int =\n xs := [1, 2]\n 1\n");
|
|
213
|
+
assert!(es.iter().any(|e| e.message.contains("import std/List")), "{es:?}");
|
|
214
|
+
}
|
compiler/checker/tests/checker/fip_test.rs
CHANGED
|
@@ -5,7 +5,8 @@ use plum_core::Diagnostic;
|
|
|
5
5
|
use plum_driver::PassOptions;
|
|
6
6
|
use plum_test_support::load;
|
|
7
7
|
|
|
8
|
+
// std/List for the list literal of `stored_in_a_list`.
|
|
8
|
-
const HEAD: &str = "import std/Int\nimport std/Str\n\nstruct Pt(px: Int, py: Int)\n\n";
|
|
9
|
+
const HEAD: &str = "import std/Int\nimport std/Str\nimport std/List\n\nstruct Pt(px: Int, py: Int)\n\n";
|
|
9
10
|
|
|
10
11
|
fn run(name: &str, body: &str, opts: &PassOptions) -> Result<(), Vec<Diagnostic>> {
|
|
11
12
|
let source = load(name, &format!("{HEAD}{body}")).expect("loads");
|
compiler/cli/tests/cli/old_forms_test.rs
CHANGED
|
@@ -48,7 +48,7 @@ fn hostCallsAreNoLongerMethodsOfIo() {
|
|
|
48
48
|
"import std/Io\nimport std/game/Color\nimport std/game/gfx\n\nfun main(io: Io) =\n io.clear(Color.Black)\n",
|
|
49
49
|
);
|
|
50
50
|
assert!(!ok, "{text}");
|
|
51
|
-
assert!(text.contains("Io
|
|
51
|
+
assert!(text.contains("Io has no method 'clear'"), "{text}");
|
|
52
52
|
let (ok, text) = compileOutcome(
|
|
53
53
|
"gfxclear",
|
|
54
54
|
"import std/Io\nimport std/game/Color\nimport std/game/gfx\n\nfun main(io: Io) =\n gfx.clear(io, Color.Black)\n",
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_types/synthetic_sites.rs
CHANGED
|
@@ -18,7 +18,8 @@ fn unknown_function_outranks_a_missing_argument_type() {
|
|
|
18
18
|
let src = prog(&format!("fun main() -> Int =\n{body}"));
|
|
19
19
|
let source = load(name, &src).expect("loads");
|
|
20
20
|
let err = compileSource(&source).expect_err("unknown function");
|
|
21
|
+
// The checker reports it now, at the call.
|
|
21
|
-
assert!(err.contains("
|
|
22
|
+
assert!(err.contains("undefined function 'nosuch'"), "{name}: {err}");
|
|
22
23
|
assert!(!err.contains("no type recorded"), "{name}: {err}");
|
|
23
24
|
}
|
|
24
25
|
}
|