plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
fd0e689
— Peter John
2026-11-07T01:43:37+05:30
Simpler language: remove return, break, continue and local reassignment
- compiler/checker/src/callcheck.rs +0 -1
- compiler/checker/src/fncheck.rs +1 -1
- compiler/checker/src/infer.rs +13 -18
- compiler/checker/src/lib.rs +1 -0
- compiler/checker/src/loops.rs +69 -0
- compiler/checker/src/owngenerics.rs +5 -1
- compiler/checker/src/program.rs +1 -0
- compiler/checker/src/state.rs +2 -0
- compiler/checker/src/stmt.rs +118 -31
- compiler/checker/tests/checker/checker_tests.rs +13 -38
- compiler/checker/tests/checker/features/closure_types.rs +0 -6
- compiler/checker/tests/checker/fip_test.rs +19 -43
- compiler/checker/tests/checker/question_tests.rs +1 -2
- compiler/cli/src/main.rs +3 -3
- compiler/cli/tests/cli/compile_tests.rs +0 -33
- compiler/cli/tests/cli/crash_test.rs +22 -0
- compiler/core/src/ast.rs +7 -32
- compiler/core/src/blocks.rs +4 -14
- compiler/core/src/builtin_usage.rs +2 -9
- compiler/core/src/closure_escape.rs +1 -4
- compiler/core/src/closure_spec.rs +0 -2
- compiler/core/src/ctors.rs +0 -2
- compiler/core/src/drive.rs +3 -8
- compiler/core/src/enum_checks.rs +1 -5
- compiler/core/src/fip.rs +4 -8
- compiler/core/src/forms.rs +465 -130
- compiler/core/src/loader.rs +2 -2
- compiler/core/src/modules.rs +0 -7
- compiler/core/src/parser.rs +30 -26
- compiler/core/src/purity.rs +0 -6
- compiler/core/src/question.rs +17 -17
- compiler/core/src/rename.rs +0 -3
- compiler/core/src/reuse.rs +1 -1
- compiler/core/src/simplify.rs +0 -7
- compiler/core/src/tail.rs +1 -6
- compiler/core/src/tests_lower.rs +51 -20
- compiler/core/src/trmc.rs +1 -1
- compiler/core/src/uniqueness.rs +11 -211
- compiler/core/src/visit.rs +2 -6
- compiler/core/tests/core/closure_spec_test.rs +0 -35
- compiler/core/tests/core/drive_test.rs +1 -2
- compiler/core/tests/core/formatter_test.rs +0 -27
- compiler/core/tests/core/forms_list_range_test.rs +12 -7
- compiler/core/tests/core/loader_test.rs +17 -1
- compiler/core/tests/core/parser_test.rs +4 -7
- compiler/core/tests/core/rename_test.rs +0 -6
- compiler/core/tests/core/tail_test.rs +0 -6
- compiler/core/tests/core/uniqueness_test.rs +13 -61
- compiler/driver/src/lib.rs +1 -1
- compiler/driver/tests/driver_tests.rs +52 -0
- compiler/lsp/src/completion.rs +14 -6
- compiler/wasm-codegen/src/closurecalls.rs +0 -1
- compiler/wasm-codegen/src/closures.rs +1 -2
- compiler/wasm-codegen/src/construct.rs +0 -1
- compiler/wasm-codegen/src/context.rs +0 -7
- compiler/wasm-codegen/src/expr.rs +0 -1
- compiler/wasm-codegen/src/fnbody.rs +1 -3
- compiler/wasm-codegen/src/stmts.rs +1 -19
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +25 -130
- compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_inplace.rs +0 -23
- docs/plans/2026-11-06-simpler-language.benchmark.md +17 -0
- examples/arrays.plum +0 -11
- examples/closures.plum +0 -13
- examples/control_flow.plum +0 -13
- examples/sequences.plum +0 -13
- examples/structs_records.plum +0 -5
- std/Array.plum +0 -16
- tests/core/for_next.plum +0 -18
- tests/core/loops_lifted.plum +103 -0
- tests/fbip/aliasing.plum +0 -167
- tests/fbip/array_in_place.plum +0 -43
- tests/fbip/array_names.plum +0 -31
- tests/fbip/array_with.plum +0 -225
- tests/fbip/fip.plum +8 -42
- tests/fbip/fuzz/gen.pl +88 -88
- tests/fbip/operator_methods.plum +23 -19
- tests/fbip/slice_shapes.plum +2 -4
- tests/fbip/spread_ro_method.plum +19 -19
- tests/fbip/uvec.plum +0 -22
- tests/fbip/vec.plum +0 -24
- tests/fbip/vec_combined.plum +0 -229
- tests/fbip/vec_combined_shared.plum +0 -251
- tests/fbip/vec_fip.plum +0 -33
- tests/fbip/vec_frames.plum +0 -34
- tests/fbip/vec_frameslocal.plum +0 -31
- tests/fbip/vec_framesmut.plum +0 -34
- tests/fbip/vec_generic.plum +0 -27
- tests/fbip/vec_helper.plum +0 -26
- tests/fbip/vec_listoflists.plum +0 -39
- tests/fbip/vec_local.plum +0 -24
- tests/fbip/vec_mutfield.plum +0 -29
- tests/fbip/vec_nested.plum +0 -27
- tests/fbip/vec_readbetween.plum +0 -25
- tests/fbip/vec_returned.plum +0 -30
- tests/fbip/vec_returned2.plum +0 -31
- tests/fbip/vec_shared.plum +0 -31
- tests/fbip/vec_statespread.plum +0 -29
- tests/fbip/vec_twolists.plum +0 -27
- tests/fbip/vec_unique_names.plum +0 -178
- tests/shadowed_effects.plum +0 -25
- tests/syntax/block_closures.plum +1 -11
- tests/syntax/block_values_passes.plum +2 -11
- tests/syntax/loops.plum +71 -0
- tests/wasm_codegen/e2e_mem/unique_spread_reassign_local.plum +0 -16
- tests/wasm_codegen/e2e_records/reassign_enum_local_across_variants.plum +0 -33
- tests/wasm_codegen/e2e_tail/break_in_else_if_chain_in_while.plum +0 -20
- tests/wasm_codegen/e2e_tail/break_in_if_in_match_arm_in_while.plum +0 -30
- tests/wasm_codegen/e2e_tail/break_in_match_arm_direct.plum +0 -37
- tests/wasm_codegen/e2e_tail/continue_in_if_in_match_arm_in_while.plum +0 -33
- tests/wasm_codegen/e2e_tail/nested_loops_with_match_in_inner.plum +0 -39
compiler/checker/src/callcheck.rs
CHANGED
|
@@ -457,7 +457,6 @@ pub(crate) fn inferOperatorCall(
|
|
|
457
457
|
line: 0,
|
|
458
458
|
column: 0,
|
|
459
459
|
tail: ast::TailKind::NotTail,
|
|
460
|
-
unique: false,
|
|
461
460
|
})
|
|
462
461
|
})
|
|
463
462
|
.clone()
|
compiler/checker/src/fncheck.rs
CHANGED
|
@@ -202,7 +202,7 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
|
|
|
202
202
|
// (which also pins down its generic arguments); everything before
|
|
203
203
|
// it is an ordinary statement.
|
|
204
204
|
let (tail, init) = match block.stmts.split_last() {
|
|
205
|
-
Some((ast::Stmt { kind: ast::StmtKind::Expr(e, line, column), .. }, init)) => (Some((e, *line, *column)), init),
|
|
205
|
+
Some((s @ ast::Stmt { kind: ast::StmtKind::Expr(e, line, column), .. }, init)) if plum_core::forms::loopOf(s).is_none() => (Some((e, *line, *column)), init),
|
|
206
206
|
_ => (None, &block.stmts[..]),
|
|
207
207
|
};
|
|
208
208
|
let n_init = init.len();
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -264,6 +264,17 @@ pub(crate) fn inferExprInner(
|
|
|
264
264
|
// (not just its trailing expression) resolves completely — only the
|
|
265
265
|
// FINAL statement's type is actually needed below, but an earlier
|
|
266
266
|
// `Assign` may declare a name the final statement depends on.
|
|
267
|
+
// The statement errors below are dropped (the params may be unresolved), so a local
|
|
268
|
+
// reassignment, which is never valid, is rejected here or it would compile.
|
|
269
|
+
for stmt in &cl.body.stmts {
|
|
270
|
+
if let ast::StmtKind::Assign(a) = &stmt.kind {
|
|
271
|
+
if !a.declare && !a.isSynthetic {
|
|
272
|
+
if let Some(ast::AssignTarget::Var(n)) = a.targets.iter().find(|t| matches!(t, ast::AssignTarget::Var(n) if n != "_")) {
|
|
273
|
+
return Err(format!("assign '{}': locals can't be reassigned; use a new name with :=", n));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
267
278
|
if let Some((_, earlier)) = cl.body.stmts.split_last() {
|
|
268
279
|
for stmt in earlier {
|
|
269
280
|
let declares_only = matches!(&stmt.kind, ast::StmtKind::Assign(a)
|
|
@@ -293,7 +304,7 @@ pub(crate) fn inferExprInner(
|
|
|
293
304
|
}
|
|
294
305
|
}
|
|
295
306
|
let body_ty = match &cl.body.stmts.last() {
|
|
296
|
-
Some(ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. }) => inferExprWith(e, &closure_env, ctx, exp_ret)?,
|
|
307
|
+
Some(s @ ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. }) if plum_core::forms::loopOf(s).is_none() => inferExprWith(e, &closure_env, ctx, exp_ret)?,
|
|
297
308
|
Some(ast::Stmt { kind: ast::StmtKind::Return(Some(e)), .. }) => inferExprWith(e, &closure_env, ctx, exp_ret)?,
|
|
298
309
|
Some(last) => {
|
|
299
310
|
let _ = checkStmt(
|
|
@@ -602,17 +613,8 @@ pub(crate) fn inferExprInner(
|
|
|
602
613
|
)),
|
|
603
614
|
},
|
|
604
615
|
ast::AttrKind::Method(call) => {
|
|
605
|
-
if call.name == ARRAY_WITH_IN_PLACE {
|
|
606
|
-
return Err(format!("'{ARRAY_WITH_IN_PLACE}' is for the compiler only: call `with`"));
|
|
607
|
-
}
|
|
608
616
|
checkStaticUse(&attr.object, &obj_ty, &call.name, ctx)?;
|
|
609
|
-
// A `with` the uniqueness pass proved unshared runs `Array.withUnique` (in place).
|
|
610
|
-
let name = if call.unique && call.name == "with" && isArrayType(&obj_ty) {
|
|
611
|
-
ARRAY_WITH_IN_PLACE
|
|
612
|
-
} else {
|
|
613
|
-
call.name.as_str()
|
|
614
|
-
};
|
|
615
|
-
inferMethodCall(&obj_ty, name, &call.args, env, ctx, expected)
|
|
617
|
+
inferMethodCall(&obj_ty, call.name.as_str(), &call.args, env, ctx, expected)
|
|
616
618
|
}
|
|
617
619
|
}
|
|
618
620
|
}
|
|
@@ -677,10 +679,3 @@ pub(crate) fn checkStaticUse(
|
|
|
677
679
|
Ok(())
|
|
678
680
|
}
|
|
679
681
|
|
|
680
|
-
/// `Array.with`'s in-place twin (std/Array.plum). Only the compiler picks it, for a `with` call
|
|
681
|
-
/// the uniqueness pass marked `unique`; a call written in source is an error.
|
|
682
|
-
pub(crate) const ARRAY_WITH_IN_PLACE: &str = "withUnique";
|
|
683
|
-
|
|
684
|
-
fn isArrayType(t: &PlumType) -> bool {
|
|
685
|
-
matches!(resolveRecorded(t), PlumType::TApp(k, _) if k == "Array")
|
|
686
|
-
}
|
compiler/checker/src/lib.rs
CHANGED
|
@@ -11,6 +11,7 @@ mod fields;
|
|
|
11
11
|
mod fncheck;
|
|
12
12
|
mod generics;
|
|
13
13
|
mod infer;
|
|
14
|
+
mod loops;
|
|
14
15
|
mod matchcheck;
|
|
15
16
|
mod names;
|
|
16
17
|
mod owngenerics;
|
compiler/checker/src/loops.rs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//! What the checker tells `forms` about a loop so that it can be lifted to a function:
|
|
2
|
+
//! its free locals with their types (the parameters) and how a `for` iterates.
|
|
3
|
+
|
|
4
|
+
use crate::*;
|
|
5
|
+
|
|
6
|
+
/// The source type of `t`, written as the program would write it; `None` when it still has
|
|
7
|
+
/// an unresolved variable in it.
|
|
8
|
+
pub(crate) fn astTypeOf(t: &PlumType, generics: &mut Vec<String>) -> Option<ast::Type> {
|
|
9
|
+
let plain = |n: &str| ast::Type { name: n.to_string(), generics: vec![] };
|
|
10
|
+
match t {
|
|
11
|
+
PlumType::TVar(_) => None,
|
|
12
|
+
PlumType::TFun(ps, r) => {
|
|
13
|
+
let ps: Option<Vec<ast::Type>> = ps.iter().map(|p| astTypeOf(p, generics)).collect();
|
|
14
|
+
Some(ast::Type::fnType(ps?, Some(astTypeOf(r, generics)?)))
|
|
15
|
+
}
|
|
16
|
+
PlumType::TApp(n, args) => {
|
|
17
|
+
let args: Option<Vec<ast::Type>> = args.iter().map(|a| astTypeOf(a, generics)).collect();
|
|
18
|
+
Some(ast::Type { name: n.clone(), generics: args? })
|
|
19
|
+
}
|
|
20
|
+
PlumType::TNamed(n) => Some(plain(n)),
|
|
21
|
+
PlumType::TParam(n) => {
|
|
22
|
+
if !generics.contains(n) {
|
|
23
|
+
generics.push(n.clone());
|
|
24
|
+
}
|
|
25
|
+
Some(plain(n))
|
|
26
|
+
}
|
|
27
|
+
other => Some(plain(&other.to_string())),
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Is `name` a local of the function being checked (a parameter or a binding), as opposed
|
|
32
|
+
/// to a top-level function, a constant or a type?
|
|
33
|
+
fn isLocal(name: &str, env: &TypeEnv) -> bool {
|
|
34
|
+
if name.starts_with('$') || !env.contains_key(name) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
let marked = format!("{}{}", GLOBAL_KEY, name);
|
|
38
|
+
withCheck(|s| {
|
|
39
|
+
let g = s.globals.borrow();
|
|
40
|
+
!g.contains(name) || (g.contains(&marked) && !env.contains_key(&marked))
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// The free locals of a loop and their types, or `None` when one has no usable type here.
|
|
45
|
+
pub(crate) fn liftParams(
|
|
46
|
+
cond: Option<&ast::Expr>,
|
|
47
|
+
body: &ast::Block,
|
|
48
|
+
bound: &[String],
|
|
49
|
+
env: &TypeEnv,
|
|
50
|
+
generics: &mut Vec<String>,
|
|
51
|
+
) -> Option<Vec<(String, ast::Type)>> {
|
|
52
|
+
let mut out = Vec::new();
|
|
53
|
+
for n in plum_core::forms::freeNames(cond, body, bound) {
|
|
54
|
+
if !isLocal(&n, env) {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
let s = env.get(&n)?;
|
|
58
|
+
if !s.vars.is_empty() {
|
|
59
|
+
return None;
|
|
60
|
+
}
|
|
61
|
+
out.push((n, astTypeOf(&resolveRecorded(&s.body), generics)?));
|
|
62
|
+
}
|
|
63
|
+
Some(out)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Loops are lifted from the erased body, never from an instantiation of a generic one.
|
|
67
|
+
pub(crate) fn liftable() -> bool {
|
|
68
|
+
plum_core::forms::active() && withCheck(|s| s.tsubst.borrow().is_none())
|
|
69
|
+
}
|
compiler/checker/src/owngenerics.rs
CHANGED
|
@@ -43,7 +43,11 @@ pub fn applyOwnGenerics(source: &ast::Source) -> Option<ast::Source> {
|
|
|
43
43
|
match &mut s.kind {
|
|
44
44
|
ast::StmtKind::Assign(a) => a.ty.iter_mut().for_each(&mut *fix),
|
|
45
45
|
ast::StmtKind::While(w) => stmtTypes(&mut w.body.stmts, fix),
|
|
46
|
+
ast::StmtKind::Expr(..) => {
|
|
47
|
+
if let Some(b) = plum_core::forms::loopBlockMut(s) {
|
|
46
|
-
|
|
48
|
+
stmtTypes(&mut b.stmts, fix);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
47
51
|
ast::StmtKind::If(i) => {
|
|
48
52
|
stmtTypes(&mut i.body.stmts, fix);
|
|
49
53
|
for e in &mut i.else_ifs {
|
compiler/checker/src/program.rs
CHANGED
|
@@ -236,6 +236,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
|
+
withCheck(|s| *s.globals.borrow_mut() = global_env.keys().cloned().collect());
|
|
239
240
|
// The calls inside a const initializer (`List(1, 2)`) are instantiated like a
|
|
240
241
|
// root fn's: codegen compiles each initializer once, outside any instantiation.
|
|
241
242
|
let const_calls = drainCalls();
|
compiler/checker/src/state.rs
CHANGED
|
@@ -68,6 +68,8 @@ pub(crate) struct CheckState {
|
|
|
68
68
|
/// `CheckError` made from it is a `DiagKind::Resolution`. Saved, restored and cleared
|
|
69
69
|
/// together with `err_pos`.
|
|
70
70
|
pub(crate) err_resolution: Cell<bool>,
|
|
71
|
+
/// The names of the top-level functions and constants (the keys of the global env).
|
|
72
|
+
pub(crate) globals: RefCell<std::collections::HashSet<String>>,
|
|
71
73
|
pub(crate) scope_site: RefCell<Option<(String, usize, String)>>,
|
|
72
74
|
}
|
|
73
75
|
|
compiler/checker/src/stmt.rs
CHANGED
|
@@ -76,35 +76,10 @@ pub(crate) fn checkStmtInner(
|
|
|
76
76
|
let mut errors = Vec::new();
|
|
77
77
|
let tail = withCheck(|s| { let t = &s.tail; t.borrow_mut().take() });
|
|
78
78
|
let set_tail = |t: &Option<PlumType>| withCheck(|s| { let c = &s.tail; *c.borrow_mut() = t.clone() });
|
|
79
|
+
if let Some(lp) = plum_core::forms::loopOf(stmt) {
|
|
80
|
+
return checkLoop(&lp, stmt, env, declared_ret, fn_name, fn_pos, ctx);
|
|
81
|
+
}
|
|
79
82
|
match &stmt.kind {
|
|
80
|
-
// Lowered here, once the type of the source is known (`forms::lowerLoop`);
|
|
81
|
-
// the lowering is checked in place. After `forms::finish` no loops are left.
|
|
82
|
-
ast::StmtKind::ForLoop(fl) => {
|
|
83
|
-
if plum_core::forms::active() {
|
|
84
|
-
let lowered = {
|
|
85
|
-
let typeOf = |e: &ast::Expr| {
|
|
86
|
-
let t = inferExpr(e, env, ctx).ok()?;
|
|
87
|
-
let name = methodReceiverName(&t)?;
|
|
88
|
-
let has =
|
|
89
|
-
|m: &str| ctx.methods.contains_key(&(name.clone(), m.to_string()));
|
|
90
|
-
Some(plum_core::forms::TyInfo {
|
|
91
|
-
iterable: has("length") && has("at"),
|
|
92
|
-
methods: ctx
|
|
93
|
-
.methods
|
|
94
|
-
.keys()
|
|
95
|
-
.filter(|(o, _)| *o == name)
|
|
96
|
-
.map(|(_, m)| m.clone())
|
|
97
|
-
.collect(),
|
|
98
|
-
name,
|
|
99
|
-
})
|
|
100
|
-
};
|
|
101
|
-
plum_core::forms::lowerLoop(fl, &typeOf)
|
|
102
|
-
};
|
|
103
|
-
for s in lowered.iter() {
|
|
104
|
-
errors.append(&mut checkStmt(s, env, declared_ret, fn_name, fn_pos, ctx));
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
83
|
ast::StmtKind::Assign(a) => {
|
|
109
84
|
if let Some(ann) = &a.ty {
|
|
110
85
|
// `name: Type := value`.
|
|
@@ -126,7 +101,7 @@ pub(crate) fn checkStmtInner(
|
|
|
126
101
|
} else if lookup(env, name).is_ok()
|
|
127
102
|
&& !env.contains_key(&format!("{}{}", GLOBAL_KEY, name))
|
|
128
103
|
{
|
|
129
|
-
errors.push(CheckError::at(fn_pos.0, fn_pos.1, format!("fn '{}': assign '{}': already declared
|
|
104
|
+
errors.push(CheckError::at(fn_pos.0, fn_pos.1, format!("fn '{}': assign '{}': already declared; pick a new name", fn_name, name)));
|
|
130
105
|
} else {
|
|
131
106
|
let declared = plumTypeFromAstG(ann);
|
|
132
107
|
let value = &a.values[0];
|
|
@@ -172,7 +147,20 @@ pub(crate) fn checkStmtInner(
|
|
|
172
147
|
let already_declared = lookup(env, name).is_ok()
|
|
173
148
|
&& !env.contains_key(&format!("{}{}", GLOBAL_KEY, name));
|
|
174
149
|
if a.declare && already_declared {
|
|
175
|
-
errors.push(CheckError::at(fn_pos.0, fn_pos.1, format!("fn '{}': assign '{}': already declared
|
|
150
|
+
errors.push(CheckError::at(fn_pos.0, fn_pos.1, format!("fn '{}': assign '{}': already declared; pick a new name", fn_name, name)));
|
|
151
|
+
} else if !a.declare && already_declared && !a.isSynthetic {
|
|
152
|
+
errors.push(CheckError::at(
|
|
153
|
+
fn_pos.0,
|
|
154
|
+
fn_pos.1,
|
|
155
|
+
format!(
|
|
156
|
+
"fn '{}': assign '{}': locals can't be reassigned; use a new name with :=",
|
|
157
|
+
fn_name, name
|
|
158
|
+
),
|
|
159
|
+
));
|
|
160
|
+
// Still check the value, so its own errors show.
|
|
161
|
+
if let Err(msg) = inferExpr(value, env, ctx) {
|
|
162
|
+
errors.push(CheckError::at(fn_pos.0, fn_pos.1, format!("fn '{}': assign '{}': {}", fn_name, name, msg)));
|
|
163
|
+
}
|
|
176
164
|
} else if !a.declare && already_declared {
|
|
177
165
|
// Reassignment: the new value's type must match what
|
|
178
166
|
// `name` was already bound to — this is the actual
|
|
@@ -519,7 +507,7 @@ pub(crate) fn checkStmtInner(
|
|
|
519
507
|
withCheck(|s| { let c = &s.match_tail; *c.borrow_mut() = tail.clone() });
|
|
520
508
|
errors.append(&mut checkMatch(m, env, declared_ret, fn_name, fn_pos, ctx));
|
|
521
509
|
}
|
|
522
|
-
ast::StmtKind::
|
|
510
|
+
ast::StmtKind::Todo => {}
|
|
523
511
|
ast::StmtKind::Crash(e) => match inferExpr(e, env, ctx) {
|
|
524
512
|
Ok(t) => {
|
|
525
513
|
if let Err(msg) = unify(&types::strType(), &t, ctx) {
|
|
@@ -554,3 +542,102 @@ pub(crate) fn discardedCall(e: &ast::Expr) -> Option<&ast::FnCall> {
|
|
|
554
542
|
_ => None,
|
|
555
543
|
}
|
|
556
544
|
}
|
|
545
|
+
|
|
546
|
+
/// Checks a `for` or `while` (see `forms::loopOf`) and, when it can become a function,
|
|
547
|
+
/// tells `forms` how: the free locals and how the loop iterates. A loop checked outside a
|
|
548
|
+
/// lowering session (the re-check of a program that kept one) is the error of a loop that
|
|
549
|
+
/// couldn't be lifted.
|
|
550
|
+
fn checkLoop(
|
|
551
|
+
lp: &plum_core::forms::Loop,
|
|
552
|
+
stmt: &ast::Stmt,
|
|
553
|
+
env: &mut TypeEnv,
|
|
554
|
+
declared_ret: &PlumType,
|
|
555
|
+
fn_name: &str,
|
|
556
|
+
fn_pos: (usize, usize),
|
|
557
|
+
ctx: &CheckCtx,
|
|
558
|
+
) -> Vec<CheckError> {
|
|
559
|
+
if !plum_core::forms::active() {
|
|
560
|
+
// Say what is wrong with the loop itself before saying it couldn't become a function:
|
|
561
|
+
// an error in its source or condition would otherwise stay hidden.
|
|
562
|
+
let mut errors = match &lp.source {
|
|
563
|
+
Some(src) => match inferExpr(src, env, ctx) {
|
|
564
|
+
Err(msg) => vec![CheckError::at(lp.line, lp.column, format!("fn '{}': for: {}", fn_name, msg))],
|
|
565
|
+
Ok(_) => vec![],
|
|
566
|
+
},
|
|
567
|
+
None => {
|
|
568
|
+
let body = plum_core::forms::loopBlock(stmt).expect("a loop has a block");
|
|
569
|
+
checkBlock(body, &mut env.clone(), declared_ret, fn_name, fn_pos, ctx)
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
if errors.is_empty() {
|
|
573
|
+
errors.push(unliftedLoop(lp, fn_name));
|
|
574
|
+
}
|
|
575
|
+
return errors;
|
|
576
|
+
}
|
|
577
|
+
let mut benv = env.clone();
|
|
578
|
+
let errors = match &lp.source {
|
|
579
|
+
// `while`: the `if` the loop's closure holds is the whole check.
|
|
580
|
+
None => {
|
|
581
|
+
let body = plum_core::forms::loopBlock(stmt).expect("a loop has a block");
|
|
582
|
+
checkBlock(body, &mut benv, declared_ret, fn_name, fn_pos, ctx)
|
|
583
|
+
}
|
|
584
|
+
Some(_) => {
|
|
585
|
+
let typeOf = |e: &ast::Expr| {
|
|
586
|
+
let t = inferExpr(e, env, ctx).ok()?;
|
|
587
|
+
let name = methodReceiverName(&t)?;
|
|
588
|
+
let has = |m: &str| ctx.methods.contains_key(&(name.clone(), m.to_string()));
|
|
589
|
+
Some(plum_core::forms::TyInfo {
|
|
590
|
+
iterable: has("length") && has("at"),
|
|
591
|
+
methods: ctx.methods.keys().filter(|(o, _)| *o == name).map(|(_, m)| m.clone()).collect(),
|
|
592
|
+
name,
|
|
593
|
+
})
|
|
594
|
+
};
|
|
595
|
+
let lowered = plum_core::forms::lowerLoop(lp, &typeOf);
|
|
596
|
+
checkBlock(&ast::Block { stmts: lowered.to_vec() }, &mut benv, declared_ret, fn_name, fn_pos, ctx)
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
// After the body: checking it may have settled the type of a local it uses.
|
|
600
|
+
if loops::liftable() {
|
|
601
|
+
recordLift(lp, env, ctx);
|
|
602
|
+
}
|
|
603
|
+
errors
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/// A loop that stayed a loop through the lowering: the type of one of the locals it uses
|
|
607
|
+
/// wasn't known where the loop is, so it couldn't become a function.
|
|
608
|
+
fn unliftedLoop(lp: &plum_core::forms::Loop, fn_name: &str) -> CheckError {
|
|
609
|
+
CheckError::at(
|
|
610
|
+
lp.line,
|
|
611
|
+
lp.column,
|
|
612
|
+
format!("fn '{}': cannot turn this loop into a function: the type of a variable it uses is not known here; give that variable a type", fn_name),
|
|
613
|
+
)
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/// Tells `forms` how loop `lp` is lifted: its free locals and, for a `for`, how its source
|
|
617
|
+
/// iterates.
|
|
618
|
+
fn recordLift(lp: &plum_core::forms::Loop, env: &TypeEnv, ctx: &CheckCtx) {
|
|
619
|
+
let mut generics = Vec::new();
|
|
620
|
+
let Some(source) = &lp.source else {
|
|
621
|
+
if let Some(params) = loops::liftParams(lp.cond.as_ref(), &lp.body, &[], env, &mut generics) {
|
|
622
|
+
plum_core::forms::recordLift(lp.id, plum_core::forms::Lift { generics, params, kind: plum_core::forms::LiftKind::While });
|
|
623
|
+
}
|
|
624
|
+
return;
|
|
625
|
+
};
|
|
626
|
+
let info = inferExpr(source, env, ctx).ok().and_then(|t| {
|
|
627
|
+
let name = methodReceiverName(&t)?;
|
|
628
|
+
let has = |m: &str| ctx.methods.contains_key(&(name.clone(), m.to_string()));
|
|
629
|
+
Some((
|
|
630
|
+
plum_core::forms::TyInfo {
|
|
631
|
+
iterable: has("length") && has("at"),
|
|
632
|
+
methods: ctx.methods.keys().filter(|(o, _)| *o == name).map(|(_, m)| m.clone()).collect(),
|
|
633
|
+
name,
|
|
634
|
+
},
|
|
635
|
+
t,
|
|
636
|
+
))
|
|
637
|
+
});
|
|
638
|
+
let srcTy = info.as_ref().and_then(|(_, t)| loops::astTypeOf(&resolveRecorded(t), &mut generics));
|
|
639
|
+
let params = loops::liftParams(None, &lp.body, &lp.binders, env, &mut generics);
|
|
640
|
+
if let (Some(kind), Some(params)) = (plum_core::forms::iterKind(info.as_ref().map(|(i, _)| i), srcTy), params) {
|
|
641
|
+
plum_core::forms::recordLift(lp.id, plum_core::forms::Lift { generics, params, kind });
|
|
642
|
+
}
|
|
643
|
+
}
|
compiler/checker/tests/checker/checker_tests.rs
CHANGED
|
@@ -348,44 +348,6 @@ fn nested_chain_exact_sites() {
|
|
|
348
348
|
assert!(msg.contains("Plain has no method 'nope'"), "{}", msg);
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
-
// ---------------------------------------------------------------------------
|
|
352
|
-
// `=` reassigns only; `:=` declares
|
|
353
|
-
// ---------------------------------------------------------------------------
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
#[test]
|
|
357
|
-
fn first_use_assign_is_an_error() {
|
|
358
|
-
let msg = errText(checkSrc("fun main() -> Int =\n x = 1\n x\n"));
|
|
359
|
-
assert!(msg.contains("use `:=` to declare `x`"), "{msg}");
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
#[test]
|
|
363
|
-
fn reassign_after_declare_is_ok() {
|
|
364
|
-
let r = checkSrc("fun main() -> Int =\n x := 1\n x = 2\n x\n");
|
|
365
|
-
assert!(r.is_ok(), "{:?}", r.err());
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
#[test]
|
|
369
|
-
fn local_named_like_a_global_fn_counts_as_declared() {
|
|
370
|
-
let src = "fun f() -> Int = 1\n\nfun main() -> Int =\n f := 2\n f = 3\n f\n";
|
|
371
|
-
let r = checkSrc(src);
|
|
372
|
-
assert!(r.is_ok(), "{:?}", r.err());
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
#[test]
|
|
376
|
-
fn param_named_like_a_global_fn_can_be_reassigned() {
|
|
377
|
-
let src = "fun f() -> Int = 1\n\nfun g(f: Int) -> Int =\n f = f + 1\n f\n";
|
|
378
|
-
let r = checkSrc(src);
|
|
379
|
-
assert!(r.is_ok(), "{:?}", r.err());
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
#[test]
|
|
383
|
-
fn assign_to_a_global_fn_name_is_an_error() {
|
|
384
|
-
let src = "fun f() -> Int = 1\n\nfun main() -> Int =\n f = 3\n f\n";
|
|
385
|
-
let msg = errText(checkSrc(src));
|
|
386
|
-
assert!(msg.contains("use `:=` to declare `f`"), "{msg}");
|
|
387
|
-
}
|
|
388
|
-
|
|
389
351
|
// ---- generics in the type checker ----
|
|
390
352
|
|
|
391
353
|
#[test]
|
|
@@ -592,6 +554,19 @@ fn assertRejected(rows: Vec<Row>) {
|
|
|
592
554
|
}
|
|
593
555
|
}
|
|
594
556
|
|
|
557
|
+
#[test]
|
|
558
|
+
fn rejects_reassigning_a_local() {
|
|
559
|
+
let cell = "struct Tally(mut n: Int)\n\n";
|
|
560
|
+
assertRejected(vec![
|
|
561
|
+
r("fun f() -> Int =\n x := 1\n x = 2\n x\n", &["locals can't be reassigned; use a new name with :="]),
|
|
562
|
+
r("fun f(x: Int) -> Int =\n x = x + 1\n x\n", &["locals can't be reassigned"]),
|
|
563
|
+
r(&format!("{cell}fun f(t: Tally) -> Int =\n total := 0\n for i := range 3\n total = total + i\n total\n"), &["locals can't be reassigned"]),
|
|
564
|
+
r(&format!("{cell}fun f(t: Tally) -> Int =\n total := 0\n while t.n < 3\n total = total + 1\n total\n"), &["locals can't be reassigned"]),
|
|
565
|
+
r("fun f(x: Int) -> Int =\n y := 1\n g := |a|\n y = 2\n a\n g(x) + y\n", &["locals can't be reassigned"]),
|
|
566
|
+
r("fun f(x: Int) -> Int =\n g := |a|\n z := 2\n z = 3\n a\n g(x)\n", &["locals can't be reassigned"]),
|
|
567
|
+
]);
|
|
568
|
+
}
|
|
569
|
+
|
|
595
570
|
#[test]
|
|
596
571
|
fn rejects_basic_expressions_and_calls() {
|
|
597
572
|
let cat = "enum Cat =\n | Cat(name: Str, age: Int)\n\n";
|
compiler/checker/tests/checker/features/closure_types.rs
CHANGED
|
@@ -47,12 +47,6 @@ fn local_closure_captured_by_closure_not_an_error() {
|
|
|
47
47
|
assert!(r.is_ok(), "{r:?}");
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
#[test]
|
|
51
|
-
fn closure_reassigned_in_loop_keeps_its_type() {
|
|
52
|
-
let r = check("fun loopy() -> fn(Int) -> Int =\n r := |x| x\n for i := range 3\n r = |x| x + i\n r\n");
|
|
53
|
-
assert!(r.is_ok(), "{r:?}");
|
|
54
|
-
}
|
|
55
|
-
|
|
56
50
|
#[test]
|
|
57
51
|
fn closure_called_twice_with_different_types_error() {
|
|
58
52
|
let r = check("fun main() -> Int =\n f := |x| x\n a := f(1)\n b := f(\"s\")\n a\n");
|
compiler/checker/tests/checker/fip_test.rs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#![allow(non_snake_case)]
|
|
2
|
-
//! `fip fun`: every spread
|
|
2
|
+
//! `fip fun`: every spread written in the body must be proved in place; a
|
|
3
3
|
//! violation is a compile error at the exact span, from the driver, after the proof ran.
|
|
4
4
|
use plum_core::Diagnostic;
|
|
5
5
|
use plum_driver::PassOptions;
|
|
6
6
|
use plum_test_support::load;
|
|
7
7
|
|
|
8
|
-
const HEAD: &str = "import std/Int\nimport std/
|
|
8
|
+
const HEAD: &str = "import std/Int\nimport std/Str\n\nstruct Pt(px: Int, py: Int)\n\n";
|
|
9
9
|
|
|
10
10
|
fn run(name: &str, body: &str, opts: &PassOptions) -> Result<(), Vec<Diagnostic>> {
|
|
11
11
|
let source = load(name, &format!("{HEAD}{body}")).expect("loads");
|
|
@@ -38,19 +38,12 @@ fn expectAt(name: &str, body: &str, needle: &str, reason: &str) {
|
|
|
38
38
|
fn passing_forms_compile() {
|
|
39
39
|
let body = "\
|
|
40
40
|
fip fun plain(a: Int) -> Int = a + 1
|
|
41
|
-
fip fun fresh() -> Array[Int] = Array.filled(2, 0).with(0, 1)
|
|
42
41
|
fip fun mv(p: Pt) -> Pt = Pt(..p, px: p.px + 1)
|
|
43
42
|
fun useMv() -> Pt = mv(Pt(px: 1, py: 2))
|
|
44
43
|
";
|
|
45
44
|
run("fip_ok", body, &PassOptions::default()).expect("compiles");
|
|
46
45
|
}
|
|
47
46
|
|
|
48
|
-
#[test]
|
|
49
|
-
fn alias_kept() {
|
|
50
|
-
let body = "fip fun upd(a: Array[Int]) -> Array[Int] =\n b := a\n a.with(0, 1)\n";
|
|
51
|
-
expectAt("fip_alias", body, "a.with(0, 1)", "`a` is also held by `b`");
|
|
52
|
-
}
|
|
53
|
-
|
|
54
47
|
#[test]
|
|
55
48
|
fn spread_alias_kept() {
|
|
56
49
|
let body = "fip fun upd(s: Pt) -> Pt =\n k := s\n Pt(..s, px: 1)\n";
|
|
@@ -59,31 +52,20 @@ fn spread_alias_kept() {
|
|
|
59
52
|
|
|
60
53
|
#[test]
|
|
61
54
|
fn stored_in_a_list() {
|
|
62
|
-
let body = "fip fun upd(
|
|
55
|
+
let body = "fip fun upd(s: Pt) -> Pt =\n xs := [s]\n Pt(..s, px: 1)\n";
|
|
63
|
-
expectAt("fip_list", body, "
|
|
56
|
+
expectAt("fip_list", body, "Pt(..s, px: 1)", "`s` is stored in field `head`");
|
|
64
57
|
}
|
|
65
58
|
|
|
66
59
|
#[test]
|
|
67
60
|
fn captured_by_a_closure() {
|
|
68
|
-
let body = "fip fun upd(
|
|
61
|
+
let body = "fip fun upd(s: Pt) -> Pt =\n g := || s.px\n Pt(..s, px: 1)\n";
|
|
69
|
-
expectAt("fip_capture", body, "
|
|
62
|
+
expectAt("fip_capture", body, "Pt(..s, px: 1)", "`s` is captured by a closure");
|
|
70
63
|
}
|
|
71
64
|
|
|
72
65
|
#[test]
|
|
73
66
|
fn read_after_the_update() {
|
|
74
|
-
let body = "fip fun upd(
|
|
67
|
+
let body = "fip fun upd(s: Pt) -> Int =\n b := Pt(..s, px: 1)\n s.px\n";
|
|
75
|
-
expectAt("fip_after", body, "
|
|
68
|
+
expectAt("fip_after", body, "Pt(..s, px: 1)", "`s` is read after the spread");
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
#[test]
|
|
79
|
-
fn shared_by_another_caller() {
|
|
80
|
-
let body = "fip fun upd(a: Array[Int]) -> Array[Int] = a.with(0, 1)\nfun keep(x: Array[Int]) -> Int =\n y := upd(x)\n x.get(0)\n";
|
|
81
|
-
expectAt(
|
|
82
|
-
"fip_caller",
|
|
83
|
-
body,
|
|
84
|
-
"a.with(0, 1)",
|
|
85
|
-
"`a` may be shared by a caller: `x` is passed to `upd`, which may keep it or the caller reads it afterwards (call of `upd` from keep)",
|
|
86
|
-
);
|
|
87
69
|
}
|
|
88
70
|
|
|
89
71
|
#[test]
|
|
@@ -111,12 +93,6 @@ fn a_parameter_named_like_a_free_fn_is_not_a_call_of_it() {
|
|
|
111
93
|
run("fip_param_named_like_fn", body, &PassOptions::default()).expect("compiles");
|
|
112
94
|
}
|
|
113
95
|
|
|
114
|
-
#[test]
|
|
115
|
-
fn update_inside_a_closure() {
|
|
116
|
-
let body = "fip fun upd(a: Array[Int]) -> Array[Int] =\n g := || a.with(0, 1)\n g()\n";
|
|
117
|
-
expectAt("fip_in_closure", body, "a.with(0, 1)", "the update is inside a closure");
|
|
118
|
-
}
|
|
119
|
-
|
|
120
96
|
#[test]
|
|
121
97
|
fn spread_inside_a_closure_counts() {
|
|
122
98
|
let body = "fip fun upd(p: Pt) -> Pt =\n g := |n: Int| Pt(..p, px: n)\n g(1)\n";
|
|
@@ -126,28 +102,28 @@ fn spread_inside_a_closure_counts() {
|
|
|
126
102
|
#[test]
|
|
127
103
|
fn a_fip_method() {
|
|
128
104
|
let body = "\
|
|
129
|
-
struct Bx(
|
|
105
|
+
struct Bx(label: Str, n: Int) =
|
|
130
|
-
fip fun put(self, x: Int) -> Bx = Bx(..self,
|
|
106
|
+
fip fun put(self, x: Int) -> Bx = Bx(..self, n: x)
|
|
131
|
-
fun peek(self) -> Int = self.
|
|
107
|
+
fun peek(self) -> Int = self.n
|
|
132
108
|
fun twice(b: Bx) -> Int =
|
|
133
109
|
c := b.put(1)
|
|
134
110
|
c.peek() + b.peek()
|
|
135
111
|
";
|
|
136
112
|
let es = errs("fip_method", body);
|
|
137
113
|
let why = "`self` may be shared by a caller: `b` is the receiver of `put`, which may keep it or the caller reads it afterwards (call of `put` from twice)";
|
|
138
|
-
let want = [span(body, "Bx(..self, items: self.items.with(0, x))"), span(body, "self.items.with(0, x)")];
|
|
139
|
-
let got: Vec<_> = es.iter().map(|e| (e.line, e.column, e.end_line, e.end_column)).collect();
|
|
140
|
-
assert_eq!(
|
|
114
|
+
assert_eq!(es.len(), 1, "{es:?}");
|
|
115
|
+
let e = &es[0];
|
|
116
|
+
assert_eq!((e.line, e.column, e.end_line, e.end_column), span(body, "Bx(..self, n: x)"), "{e:?}");
|
|
141
|
-
|
|
117
|
+
assert_eq!(e.message, format!("not in place: {why}"), "{e:?}");
|
|
142
118
|
}
|
|
143
119
|
|
|
144
120
|
#[test]
|
|
145
121
|
fn a_fip_method_handed_over_compiles() {
|
|
146
122
|
let body = "\
|
|
147
|
-
struct Bx(
|
|
123
|
+
struct Bx(label: Str, n: Int) =
|
|
148
|
-
fip fun put(self, x: Int) -> Bx = Bx(..self,
|
|
124
|
+
fip fun put(self, x: Int) -> Bx = Bx(..self, n: x)
|
|
149
125
|
fun once(n: Int) -> Bx =
|
|
150
|
-
b := Bx(
|
|
126
|
+
b := Bx(label: \"b\", n: n)
|
|
151
127
|
b.put(1)
|
|
152
128
|
";
|
|
153
129
|
run("fip_method_ok", body, &PassOptions::default()).expect("compiles");
|
|
@@ -176,7 +152,7 @@ fn a_fip_fun_is_not_inlined_away() {
|
|
|
176
152
|
|
|
177
153
|
#[test]
|
|
178
154
|
fn not_enforced_without_the_proof() {
|
|
179
|
-
let body = "fip fun upd(
|
|
155
|
+
let body = "fip fun upd(s: Pt) -> Pt =\n k := s\n Pt(..s, px: 1)\n";
|
|
180
156
|
run("fip_nofbip", body, &PassOptions { fbip: false, ..PassOptions::default() }).expect("--no-fbip: not enforced");
|
|
181
157
|
run("fip_nofusion", body, &PassOptions { fusion: false, ..PassOptions::default() }).expect("--no-fusion: not enforced");
|
|
182
158
|
assert_eq!(errs("fip_on", body).len(), 1);
|
compiler/checker/tests/checker/question_tests.rs
CHANGED
|
@@ -120,7 +120,6 @@ fn bare_value_into_result_return_errors() {
|
|
|
120
120
|
fn bare_value_into_option_arg_and_annotation_errors() {
|
|
121
121
|
rejected("fun g(o: Option[Int]) -> Int = 1\nfun f() -> Int = g(1)", "wrap it with Some(..)");
|
|
122
122
|
rejected("fun f() -> Int =\n o: Option[Int] := 1\n 2", "wrap it with Some(..)");
|
|
123
|
-
rejected("fun f() -> Int =\n o: Option[Int] := None\n o = 1\n 2", "wrap it with Some(..)");
|
|
124
123
|
}
|
|
125
124
|
|
|
126
125
|
#[test]
|
|
@@ -230,7 +229,7 @@ fn question_rejected_forms() {
|
|
|
230
229
|
("fun f() -> Option[Int] =\n b := true && g()? > 0\n Some(1)", "conditionally"),
|
|
231
230
|
("fun f() -> Option[Int] =\n b := if true then g()? else 1\n Some(b)", "conditionally"),
|
|
232
231
|
("fun f() -> Option[Int] =\n h := || g()?\n Some(1)", "closure"),
|
|
233
|
-
("fun f() -> Option[Int] =\n while g()? > 0\n _ := 1\n Some(1)", "
|
|
232
|
+
("fun f() -> Option[Int] =\n while g()? > 0\n _ := 1\n Some(1)", "loop body"),
|
|
234
233
|
] {
|
|
235
234
|
rejected(&format!("{g}{body}"), needle);
|
|
236
235
|
}
|
compiler/cli/src/main.rs
CHANGED
|
@@ -350,7 +350,7 @@ fn cmdRun(
|
|
|
350
350
|
Err(trap) => {
|
|
351
351
|
// A `Result` main that returned `Err` already printed `crash: <variant>`.
|
|
352
352
|
if !resultMain {
|
|
353
|
-
eprintln!("error: {
|
|
353
|
+
eprintln!("error: {}", plum_core::diag::sourceName(&trap.to_string()));
|
|
354
354
|
}
|
|
355
355
|
process::exit(1);
|
|
356
356
|
}
|
|
@@ -365,7 +365,7 @@ fn cmdRun(
|
|
|
365
365
|
})?;
|
|
366
366
|
if let Err(trap) = main.call(&mut store, ()) {
|
|
367
367
|
if !resultMain {
|
|
368
|
-
eprintln!("error: {
|
|
368
|
+
eprintln!("error: {}", plum_core::diag::sourceName(&trap.to_string()));
|
|
369
369
|
}
|
|
370
370
|
process::exit(1);
|
|
371
371
|
}
|
|
@@ -563,7 +563,7 @@ fn runTestFile(
|
|
|
563
563
|
}
|
|
564
564
|
}
|
|
565
565
|
Err(trap) => {
|
|
566
|
-
println!("{branch} {name} {} PANIC: {
|
|
566
|
+
println!("{branch} {name} {} PANIC: {}", red("\u{2718}"), plum_core::diag::sourceName(&format!("{trap:#}")));
|
|
567
567
|
failed += 1;
|
|
568
568
|
}
|
|
569
569
|
}
|
compiler/cli/tests/cli/compile_tests.rs
CHANGED
|
@@ -75,39 +75,6 @@ fn compileWithImportResolvesViaLibPath() {
|
|
|
75
75
|
assert_eq!(&bytes[0..4], b"\0asm");
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
/// The body the parse-error hint for `()` suggests must itself compile, with
|
|
79
|
-
/// only the imports the failing file already had.
|
|
80
|
-
#[test]
|
|
81
|
-
fn returnBodySuggestedByTheParseErrorHintCompiles() {
|
|
82
|
-
let dir = freshTempDir("return_hint");
|
|
83
|
-
let src_path = dir.join("h.plum");
|
|
84
|
-
std::fs::write(
|
|
85
|
-
&src_path,
|
|
86
|
-
"import std/Float\n\nexport fun update(w: Float, dt: Float) =\n return\n",
|
|
87
|
-
)
|
|
88
|
-
.unwrap();
|
|
89
|
-
let out_path = dir.join("h.wasm");
|
|
90
|
-
let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
91
|
-
.ancestors().nth(2)
|
|
92
|
-
.unwrap();
|
|
93
|
-
let output = Command::new(plumBin())
|
|
94
|
-
.args([
|
|
95
|
-
"compile",
|
|
96
|
-
src_path.to_str().unwrap(),
|
|
97
|
-
"-o",
|
|
98
|
-
out_path.to_str().unwrap(),
|
|
99
|
-
"--lib-path",
|
|
100
|
-
repo.to_str().unwrap(),
|
|
101
|
-
])
|
|
102
|
-
.output()
|
|
103
|
-
.expect("failed to run plum compile");
|
|
104
|
-
assert!(
|
|
105
|
-
output.status.success(),
|
|
106
|
-
"{}",
|
|
107
|
-
String::from_utf8_lossy(&output.stderr)
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
78
|
#[test]
|
|
112
79
|
fn undefinedNameIsReportedAsFileLineColumnTypeError() {
|
|
113
80
|
let dir = freshTempDir("undefined_name");
|
compiler/cli/tests/cli/crash_test.rs
CHANGED
|
@@ -63,3 +63,25 @@ fn int_literal_overflow_error_has_position() {
|
|
|
63
63
|
);
|
|
64
64
|
assert!(all.contains("lit.plum:4:"), "output: {all}");
|
|
65
65
|
}
|
|
66
|
+
|
|
67
|
+
#[test]
|
|
68
|
+
fn crash_in_a_loop_names_the_function_not_its_lifted_loop() {
|
|
69
|
+
let dir = std::env::temp_dir().join(format!("plum_crash_loop_{}", std::process::id()));
|
|
70
|
+
std::fs::create_dir_all(&dir).unwrap();
|
|
71
|
+
let src = dir.join("crash_loop.plum");
|
|
72
|
+
std::fs::write(
|
|
73
|
+
&src,
|
|
74
|
+
"import std/Int\nimport std/Io\nimport std/Str\n\nstruct T(mut n: Int)\n\nfun boom(t: T, k: Int) =\n for i := range k\n d := 2 - i\n t.n = t.n / d\n\nfun main(io: Io) =\n t := T(n: 5)\n boom(t, 5)\n io.printLn(\"never\")\n",
|
|
75
|
+
)
|
|
76
|
+
.unwrap();
|
|
77
|
+
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
78
|
+
let out = Command::new(plumBin())
|
|
79
|
+
.current_dir(root)
|
|
80
|
+
.args(["run", src.to_str().unwrap()])
|
|
81
|
+
.output()
|
|
82
|
+
.expect("failed to run plum");
|
|
83
|
+
let stderr = String::from_utf8_lossy(&out.stderr);
|
|
84
|
+
assert!(!out.status.success(), "stderr: {stderr}");
|
|
85
|
+
assert!(stderr.contains("!boom"), "stderr was: {stderr}");
|
|
86
|
+
assert!(!stderr.contains("@loop"), "stderr was: {stderr}");
|
|
87
|
+
}
|
compiler/core/src/ast.rs
CHANGED
|
@@ -74,11 +74,8 @@ impl Stmt {
|
|
|
74
74
|
Stmt { id: NodeId(0), span: Span::default(), kind }
|
|
75
75
|
}
|
|
76
76
|
pub fn Assign(a: Assign) -> Stmt { Stmt::new(StmtKind::Assign(a)) }
|
|
77
|
-
pub const Break: Stmt = Stmt { id: NodeId(0), span: Span { startLine: 0, startColumn: 0, endLine: 0, endColumn: 0 }, kind: StmtKind::Break };
|
|
78
|
-
pub const Continue: Stmt = Stmt { id: NodeId(0), span: Span { startLine: 0, startColumn: 0, endLine: 0, endColumn: 0 }, kind: StmtKind::Continue };
|
|
79
77
|
pub const Todo: Stmt = Stmt { id: NodeId(0), span: Span { startLine: 0, startColumn: 0, endLine: 0, endColumn: 0 }, kind: StmtKind::Todo };
|
|
80
78
|
pub fn Assert(c: Check) -> Stmt { Stmt::new(StmtKind::Assert(c)) }
|
|
81
|
-
pub fn ForLoop(f: ForLoop) -> Stmt { Stmt::new(StmtKind::ForLoop(f)) }
|
|
82
79
|
pub fn While(w: While) -> Stmt { Stmt::new(StmtKind::While(w)) }
|
|
83
80
|
pub fn If(i: If) -> Stmt { Stmt::new(StmtKind::If(i)) }
|
|
84
81
|
pub fn Match(m: Match) -> Stmt { Stmt::new(StmtKind::Match(m)) }
|
|
@@ -528,7 +525,7 @@ pub struct Fn {
|
|
|
528
525
|
pub is_export: bool,
|
|
529
526
|
/// A `test` block lowered to a fn (`tests_lower`); its name is generated.
|
|
530
527
|
pub is_test: bool,
|
|
531
|
-
/// `fip fun`: every spread
|
|
528
|
+
/// `fip fun`: every spread in the body must be proved in place (driver check).
|
|
532
529
|
pub is_fip: bool,
|
|
533
530
|
/// The fn declared `self` as its first parameter (an instance method). A
|
|
534
531
|
/// fn nested in a type or `primitive` body without it is a static.
|
|
@@ -651,16 +648,11 @@ pub struct Stmt {
|
|
|
651
648
|
#[derive(Debug, Clone, PartialEq)]
|
|
652
649
|
pub enum StmtKind {
|
|
653
650
|
Assign(Assign),
|
|
654
|
-
Break,
|
|
655
|
-
Continue,
|
|
656
651
|
/// Outside a `test` body, traps (hard failure) if `cond` is false. Inside
|
|
657
652
|
/// one, desugars to a non-fatal check instead — records a failure report
|
|
658
653
|
/// (with `Check`'s own source location/text) and keeps running rather
|
|
659
654
|
/// than trapping — see `plum_core::tests_lower`.
|
|
660
655
|
Assert(Check),
|
|
661
|
-
/// A surface `for x := range v`, not yet lowered
|
|
662
|
-
/// (see `forms.rs`); never seen by the checker or codegen.
|
|
663
|
-
ForLoop(ForLoop),
|
|
664
656
|
While(While),
|
|
665
657
|
If(If),
|
|
666
658
|
Match(Match),
|
|
@@ -719,28 +711,15 @@ pub struct Assign {
|
|
|
719
711
|
pub isSynthetic: bool,
|
|
720
712
|
}
|
|
721
713
|
|
|
722
|
-
/// Surface `for x := range v` form, before lowering (`forms.rs` lowers it to a
|
|
723
|
-
/// `while` loop once the type of `v` is known).
|
|
724
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
725
|
-
pub struct ForLoop {
|
|
726
|
-
pub binders: Vec<String>,
|
|
727
|
-
/// An `Int`, a type with `next`, or an iterable (`length()` and `at(i)`).
|
|
728
|
-
pub source: Expr,
|
|
729
|
-
/// The source text of `source`, for diagnostics.
|
|
730
|
-
pub sourceText: String,
|
|
731
|
-
pub body: Block,
|
|
732
|
-
/// Identifies this loop for the lowering cache (see `forms.rs`).
|
|
733
|
-
pub id: usize,
|
|
734
|
-
/// 1-based position of the `for` keyword, for diagnostics.
|
|
735
|
-
pub line: usize,
|
|
736
|
-
pub column: usize,
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
/// Prefix of the synthetic local a
|
|
714
|
+
/// Prefix of the synthetic local a `for` over an iterable binds its source to while it is
|
|
740
|
-
/// the checker verifies that such a binding's type has `
|
|
715
|
+
/// checked; the checker verifies that such a binding's type has `length`/`at`. The suffix
|
|
741
716
|
/// is `<unique id>:<source text>`.
|
|
742
717
|
pub const FOR_ITER_PREFIX: &str = "__for_it";
|
|
743
718
|
|
|
719
|
+
/// A `while` loop that TRMC builds (`trmc.rs`). The parser never makes one: a written `while` or
|
|
720
|
+
/// `for` is a call that the checker lifts to a function (`forms.rs`). It stays because TRMC's
|
|
721
|
+
/// loop keeps its state in compiler-made locals, which a function's arguments can't hold while
|
|
722
|
+
/// holes are filled in place.
|
|
744
723
|
#[derive(Debug, Clone, PartialEq)]
|
|
745
724
|
pub struct While {
|
|
746
725
|
pub condition: Expr,
|
|
@@ -982,10 +961,6 @@ pub struct FnCall {
|
|
|
982
961
|
pub column: usize,
|
|
983
962
|
/// Set by `tail::markTailCalls`: whether (and how) this call is in tail position.
|
|
984
963
|
pub tail: TailKind,
|
|
985
|
-
/// Set by the uniqueness analysis on a method call named `with`: its receiver is provably
|
|
986
|
-
/// unshared and dead afterwards, so `Array.with` may write the array in place. Meaningless
|
|
987
|
-
/// (and ignored) on every other receiver type.
|
|
988
|
-
pub unique: bool,
|
|
989
964
|
}
|
|
990
965
|
|
|
991
966
|
/// How a call in tail position is made (see `tail.rs`). `NotTail` is the default.
|
compiler/core/src/blocks.rs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
//!
|
|
8
8
|
//! * rejects a block whose last line is no value (an `if` used as a value needs an `else`; the
|
|
9
9
|
//! last line of every branch is a value, a nested `if` / `match`, or ends the path with
|
|
10
|
-
//! `return` / `crash` / `todo`
|
|
10
|
+
//! `return` / `crash` / `todo`), and a block in a constant;
|
|
11
11
|
//! * gives each name that a block declares and that is declared elsewhere in the same fn
|
|
12
12
|
//! (a sibling branch, or a later outer name) a fresh name. Locals are fn-wide and typed once in
|
|
13
13
|
//! the output, so two branches that each declare `t` (of different types) would otherwise
|
|
@@ -53,7 +53,7 @@ impl Pass {
|
|
|
53
53
|
self.tail(&c.body.stmts, last.span);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo
|
|
56
|
+
StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo => {}
|
|
57
57
|
_ => self.error(last.span, "the last line of a block used as a value must be a value, an 'if' or a 'match'"),
|
|
58
58
|
}
|
|
59
59
|
}
|
|
@@ -175,17 +175,6 @@ impl Scoper<'_> {
|
|
|
175
175
|
StmtKind::Assert(c) => self.expr(&mut c.cond),
|
|
176
176
|
StmtKind::Crash(e) | StmtKind::Expr(e, ..) => self.expr(e),
|
|
177
177
|
StmtKind::Return(e) => e.iter_mut().for_each(|e| self.expr(e)),
|
|
178
|
-
StmtKind::ForLoop(f) => {
|
|
179
|
-
self.expr(&mut f.source);
|
|
180
|
-
self.scoped(|s| {
|
|
181
|
-
f.binders.iter_mut().for_each(|b| s.declare(b));
|
|
182
|
-
s.block(&mut f.body);
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
StmtKind::While(w) => self.scoped(|s| {
|
|
186
|
-
s.expr(&mut w.condition);
|
|
187
|
-
s.block(&mut w.body);
|
|
188
|
-
}),
|
|
189
178
|
StmtKind::If(i) => self.scoped(|s| {
|
|
190
179
|
s.expr(&mut i.condition);
|
|
191
180
|
s.block(&mut i.body);
|
|
@@ -209,7 +198,8 @@ impl Scoper<'_> {
|
|
|
209
198
|
});
|
|
210
199
|
}
|
|
211
200
|
}
|
|
201
|
+
// A `While` is only ever built by TRMC, after this pass.
|
|
212
|
-
StmtKind::
|
|
202
|
+
StmtKind::While(_) | StmtKind::Todo => {}
|
|
213
203
|
}
|
|
214
204
|
}
|
|
215
205
|
|
compiler/core/src/builtin_usage.rs
CHANGED
|
@@ -137,17 +137,10 @@ fn walkStmt(stmt: &Stmt, names: &mut Acc) {
|
|
|
137
137
|
walkExpr(v, names);
|
|
138
138
|
}
|
|
139
139
|
}
|
|
140
|
+
// A `While` is only ever built by TRMC, after this pass.
|
|
140
|
-
StmtKind::
|
|
141
|
+
StmtKind::While(_) | StmtKind::Todo => {}
|
|
141
142
|
StmtKind::Crash(e) => walkExpr(e, names),
|
|
142
143
|
StmtKind::Assert(check) => walkExpr(&check.cond, names),
|
|
143
|
-
StmtKind::ForLoop(f) => {
|
|
144
|
-
walkExpr(&f.source, names);
|
|
145
|
-
walkStmts(&f.body.stmts, names);
|
|
146
|
-
}
|
|
147
|
-
StmtKind::While(w) => {
|
|
148
|
-
walkExpr(&w.condition, names);
|
|
149
|
-
walkStmts(&w.body.stmts, names);
|
|
150
|
-
}
|
|
151
144
|
StmtKind::If(i) => {
|
|
152
145
|
walkExpr(&i.condition, names);
|
|
153
146
|
walkStmts(&i.body.stmts, names);
|
compiler/core/src/closure_escape.rs
CHANGED
|
@@ -110,11 +110,8 @@ impl<'a> Cx<'a> {
|
|
|
110
110
|
AssignTarget::Field(o, _) => self.expr(o, cl),
|
|
111
111
|
}) || a.values.iter().any(|v| self.expr(v, cl))
|
|
112
112
|
}
|
|
113
|
-
StmtKind::
|
|
113
|
+
StmtKind::Todo => false,
|
|
114
114
|
StmtKind::Assert(c) => self.expr(&c.cond, cl),
|
|
115
|
-
StmtKind::ForLoop(l) => {
|
|
116
|
-
self.expr(&l.source, cl) || self.block(&l.body, cl)
|
|
117
|
-
}
|
|
118
115
|
StmtKind::While(w) => self.expr(&w.condition, cl) || self.block(&w.body, cl),
|
|
119
116
|
StmtKind::If(i) => {
|
|
120
117
|
self.expr(&i.condition, cl)
|
compiler/core/src/closure_spec.rs
CHANGED
|
@@ -929,7 +929,6 @@ fn anyReturn(stmts: &[Stmt]) -> bool {
|
|
|
929
929
|
stmts.iter().any(|s| match &s.kind {
|
|
930
930
|
StmtKind::Return(_) => true,
|
|
931
931
|
StmtKind::While(w) => anyReturn(&w.body.stmts),
|
|
932
|
-
StmtKind::ForLoop(f) => anyReturn(&f.body.stmts),
|
|
933
932
|
StmtKind::If(i) => {
|
|
934
933
|
anyReturn(&i.body.stmts)
|
|
935
934
|
|| i.else_ifs.iter().any(|e| anyReturn(&e.body.stmts))
|
|
@@ -990,7 +989,6 @@ fn annotations(stmts: &[Stmt], out: &mut HashSet<String>) {
|
|
|
990
989
|
}
|
|
991
990
|
}
|
|
992
991
|
StmtKind::While(w) => annotations(&w.body.stmts, out),
|
|
993
|
-
StmtKind::ForLoop(f) => annotations(&f.body.stmts, out),
|
|
994
992
|
StmtKind::If(i) => {
|
|
995
993
|
annotations(&i.body.stmts, out);
|
|
996
994
|
i.else_ifs.iter().for_each(|e| annotations(&e.body.stmts, out));
|
compiler/core/src/ctors.rs
CHANGED
|
@@ -332,7 +332,6 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
|
|
|
332
332
|
line: line,
|
|
333
333
|
column: column,
|
|
334
334
|
tail: TailKind::NotTail,
|
|
335
|
-
unique: false,
|
|
336
335
|
}),
|
|
337
336
|
})),
|
|
338
337
|
0,
|
|
@@ -445,7 +444,6 @@ fn rewriteCall(e: &mut Expr, plans: &HashMap<String, Plan>, errors: &mut Vec<Str
|
|
|
445
444
|
line: 0,
|
|
446
445
|
column: 0,
|
|
447
446
|
tail: TailKind::NotTail,
|
|
448
|
-
unique: false,
|
|
449
447
|
})
|
|
450
448
|
.at(e);
|
|
451
449
|
}
|
compiler/core/src/drive.rs
CHANGED
|
@@ -277,7 +277,7 @@ fn pathStmts(stmts: &[Stmt], name: &str) -> usize {
|
|
|
277
277
|
let guards: usize = m.cases.iter().filter_map(|c| c.guard.as_ref()).map(|g| pathE(g, name)).sum();
|
|
278
278
|
subj + guards + m.cases.iter().map(|c| pathStmts(&c.body.stmts, name)).max().unwrap_or(0)
|
|
279
279
|
}
|
|
280
|
-
StmtKind::
|
|
280
|
+
StmtKind::While(_) => 2 * cntStmts(std::slice::from_ref(s), name, true),
|
|
281
281
|
_ => stmtExprRefs(s).into_iter().map(|e| pathE(e, name)).sum(),
|
|
282
282
|
})
|
|
283
283
|
.sum()
|
|
@@ -296,7 +296,7 @@ fn cheap(e: &Expr) -> bool {
|
|
|
296
296
|
fn clean(stmts: &[Stmt]) -> bool {
|
|
297
297
|
stmts.iter().all(|s| {
|
|
298
298
|
let ok = match &s.kind {
|
|
299
|
-
StmtKind::Return(_) | StmtKind::While(_)
|
|
299
|
+
StmtKind::Return(_) | StmtKind::While(_) => false,
|
|
300
300
|
StmtKind::Assign(a) => a.declare,
|
|
301
301
|
_ => true,
|
|
302
302
|
};
|
|
@@ -312,7 +312,7 @@ fn clean(stmts: &[Stmt]) -> bool {
|
|
|
312
312
|
/// Is `name` read inside a loop in `stmts`?
|
|
313
313
|
fn inLoop(stmts: &[Stmt], name: &str) -> bool {
|
|
314
314
|
stmts.iter().any(|s| match &s.kind {
|
|
315
|
-
StmtKind::
|
|
315
|
+
StmtKind::While(_) => cntStmts(std::slice::from_ref(s), name, true) > 0,
|
|
316
316
|
_ => {
|
|
317
317
|
stmtBlockRefs(s).into_iter().any(|b| inLoop(&b.stmts, name))
|
|
318
318
|
|| stmtExprRefs(s).into_iter().any(|e| {
|
|
@@ -367,7 +367,6 @@ impl Tcx {
|
|
|
367
367
|
line: 0,
|
|
368
368
|
column: 0,
|
|
369
369
|
tail: TailKind::NotTail,
|
|
370
|
-
unique: false,
|
|
371
370
|
}),
|
|
372
371
|
}))
|
|
373
372
|
} else if let Some(t) = &self.callee.type_param {
|
|
@@ -379,7 +378,6 @@ impl Tcx {
|
|
|
379
378
|
line: 0,
|
|
380
379
|
column: 0,
|
|
381
380
|
tail: TailKind::NotTail,
|
|
382
|
-
unique: false,
|
|
383
381
|
}),
|
|
384
382
|
}))
|
|
385
383
|
} else {
|
|
@@ -389,7 +387,6 @@ impl Tcx {
|
|
|
389
387
|
line: 0,
|
|
390
388
|
column: 0,
|
|
391
389
|
tail: TailKind::NotTail,
|
|
392
|
-
unique: false,
|
|
393
390
|
})
|
|
394
391
|
}
|
|
395
392
|
}
|
|
@@ -1104,7 +1101,6 @@ impl Driver {
|
|
|
1104
1101
|
line: 0,
|
|
1105
1102
|
column: 0,
|
|
1106
1103
|
tail: TailKind::NotTail,
|
|
1107
|
-
unique: false,
|
|
1108
1104
|
});
|
|
1109
1105
|
return true;
|
|
1110
1106
|
}
|
|
@@ -1890,7 +1886,6 @@ impl Driver {
|
|
|
1890
1886
|
line: 0,
|
|
1891
1887
|
column: 0,
|
|
1892
1888
|
tail: TailKind::NotTail,
|
|
1893
|
-
unique: false,
|
|
1894
1889
|
}));
|
|
1895
1890
|
self.origins.insert(name.clone(), anc);
|
|
1896
1891
|
self.fused.push(f);
|
compiler/core/src/enum_checks.rs
CHANGED
|
@@ -244,13 +244,9 @@ impl TypeWalk<'_> {
|
|
|
244
244
|
}
|
|
245
245
|
a.values.iter().for_each(|v| self.expr(v));
|
|
246
246
|
}
|
|
247
|
-
StmtKind::
|
|
247
|
+
StmtKind::Todo => {}
|
|
248
248
|
StmtKind::Crash(e) => self.expr(e),
|
|
249
249
|
StmtKind::Assert(c) => self.expr(&c.cond),
|
|
250
|
-
StmtKind::ForLoop(f) => {
|
|
251
|
-
self.expr(&f.source);
|
|
252
|
-
self.stmts(&f.body.stmts);
|
|
253
|
-
}
|
|
254
250
|
StmtKind::While(w) => {
|
|
255
251
|
self.expr(&w.condition);
|
|
256
252
|
self.stmts(&w.body.stmts);
|
compiler/core/src/fip.rs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//! `fip fun`: a compile-time guarantee that the function's own updates run in place.
|
|
2
2
|
//!
|
|
3
|
-
//! Every spread `T(..x, ..)`
|
|
3
|
+
//! Every spread `T(..x, ..)` written in the body of a `fip fun`
|
|
4
4
|
//! (closures inside it included) must be proved in place by `uniqueness::markUnique`. Calls to
|
|
5
5
|
//! other functions are not checked: the guarantee is local to the body.
|
|
6
6
|
//!
|
|
@@ -22,7 +22,7 @@ fn key(s: &Span) -> SpanKey {
|
|
|
22
22
|
(s.startLine, s.startColumn, s.endLine, s.endColumn)
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
/// The spans of the spreads
|
|
25
|
+
/// The spans of the spreads each `fip fun` had before fusion, by the fn's
|
|
26
26
|
/// own position (the rewrites keep a fn's line and column).
|
|
27
27
|
#[derive(Default)]
|
|
28
28
|
pub struct FipOrigins(HashMap<(String, usize, usize), HashSet<SpanKey>>);
|
|
@@ -34,11 +34,7 @@ impl FipOrigins {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
fn isCheckedSite(e: &Expr) -> bool {
|
|
37
|
-
match &e.kind {
|
|
38
|
-
|
|
37
|
+
matches!(&e.kind, ExprKind::ClassCall(c) if c.spread.is_some())
|
|
39
|
-
ExprKind::Attribute(a) => matches!(&a.attr, AttrKind::Method(c) if c.name == "with"),
|
|
40
|
-
_ => false,
|
|
41
|
-
}
|
|
42
38
|
}
|
|
43
39
|
|
|
44
40
|
/// Records the `fip fun`s of `src` and the spans of their checked sites.
|
|
@@ -65,7 +61,7 @@ pub fn origins(src: &Source) -> FipOrigins {
|
|
|
65
61
|
out
|
|
66
62
|
}
|
|
67
63
|
|
|
68
|
-
/// One error per spread
|
|
64
|
+
/// One error per spread of a `fip fun` that the proof left a copy.
|
|
69
65
|
pub fn diagnostics(src: &Source, report: &UniqueReport, origins: &FipOrigins) -> Vec<Diagnostic> {
|
|
70
66
|
let mut out: Vec<Diagnostic> = Vec::new();
|
|
71
67
|
for v in &report.fipSites {
|
compiler/core/src/forms.rs
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
|
-
//!
|
|
1
|
+
//! The loop forms, `for x := range v` and `while cond`.
|
|
2
2
|
//!
|
|
3
|
-
//! The parser
|
|
3
|
+
//! The parser gives each loop as a call of a compiler-private function that takes its body as a
|
|
4
|
+
//! closure (see [`whileStmt`], [`forStmt`], [`loopOf`]): no statement node stands for a loop,
|
|
5
|
+
//! and every pass sees an ordinary call. [`prepareForms`] (run by the loader after merging the
|
|
4
|
-
//!
|
|
6
|
+
//! imports) gives every loop an identity. The *checker* checks each loop once the type of its
|
|
7
|
+
//! source is known (`lowerLoop` gives what a `for` is checked as), and records how it is lifted
|
|
8
|
+
//! to a top-level function: its free locals, which are the arguments, and how it iterates.
|
|
5
|
-
//!
|
|
9
|
+
//! [`finish`] then replaces each loop by a call of its lifted function, `owner@loopN`, in a copy
|
|
10
|
+
//! of the program that codegen compiles. A loop the checker couldn't describe (a local of it has
|
|
6
|
-
//!
|
|
11
|
+
//! no type yet) stays a call that no function answers, and the re-check reports it.
|
|
7
|
-
//! copy of the program that codegen compiles.
|
|
8
12
|
//!
|
|
9
|
-
//!
|
|
13
|
+
//! How a `for` iterates depends on the type of its source:
|
|
10
14
|
//!
|
|
11
15
|
//! * `Int`: `i` counts 0, 1, ... n - 1.
|
|
12
|
-
//! * a type with `next(self) -> Option[Pair[T, Self]]`:
|
|
16
|
+
//! * a type with `next(self) -> Option[Pair[T, Self]]`: each pass takes the next step.
|
|
13
|
-
//! `it := v; while Some(step) := it.next() { x := step.first; it = step.second; .. }`.
|
|
14
|
-
//! * anything else: plain iteration over `length()` / `at(i)`
|
|
17
|
+
//! * anything else: plain iteration over `length()` / `at(i)`.
|
|
15
|
-
//! `while` loop.
|
|
16
18
|
//!
|
|
17
19
|
//! A binder named `_` is not bound.
|
|
18
20
|
|
|
@@ -42,6 +44,79 @@ thread_local! {
|
|
|
42
44
|
static ACTIVE: Cell<bool> = const { Cell::new(false) };
|
|
43
45
|
static COUNTER: Cell<usize> = const { Cell::new(0) };
|
|
44
46
|
static LOWERED: RefCell<HashMap<usize, Rc<Vec<Stmt>>>> = RefCell::new(HashMap::new());
|
|
47
|
+
static LIFTS: RefCell<HashMap<usize, Lift>> = RefCell::new(HashMap::new());
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// How a loop becomes a top-level function (see [`finish`]).
|
|
51
|
+
#[derive(Clone, Debug)]
|
|
52
|
+
pub enum LiftKind {
|
|
53
|
+
/// `while cond { body }`.
|
|
54
|
+
While,
|
|
55
|
+
/// `for i := range n`.
|
|
56
|
+
Int,
|
|
57
|
+
/// A source with `next(self) -> Option[Pair[T, Self]]`; the type of the source.
|
|
58
|
+
Next(Type),
|
|
59
|
+
/// A source iterated by `length()` and `at(i)`; the type of the source.
|
|
60
|
+
Plain(Type),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// What the checker found out about a loop: the free locals of its condition and body (the
|
|
64
|
+
/// lifted function's parameters) with their types, and how it iterates.
|
|
65
|
+
#[derive(Clone, Debug)]
|
|
66
|
+
pub struct Lift {
|
|
67
|
+
/// Generic parameters (`T`) the types below mention: the lifted function declares them.
|
|
68
|
+
pub generics: Vec<String>,
|
|
69
|
+
pub params: Vec<(String, Type)>,
|
|
70
|
+
pub kind: LiftKind,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Remembers (replacing an earlier record) how loop `id` is lifted.
|
|
74
|
+
pub fn recordLift(id: usize, lift: Lift) {
|
|
75
|
+
LIFTS.with(|l| l.borrow_mut().insert(id, lift));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// Name of the function loop `id` of `owner` is lifted to: `owner@loop3`. The `@` mark is the
|
|
79
|
+
/// one `diag::sourceName` strips, so a message about the loop names the function it is in; the
|
|
80
|
+
/// mark can't be written in source, so it never collides with a user's name, and ids are
|
|
81
|
+
/// unique in a session.
|
|
82
|
+
pub fn liftedName(id: usize, owner: &str) -> String {
|
|
83
|
+
format!("{}{}loop{}", owner, crate::modules::MODULE_MARK, id)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// The names a loop's condition and body use, in order of first use, other than `bound` (a
|
|
87
|
+
/// `for`'s binders). The caller keeps the ones that are locals of the enclosing function.
|
|
88
|
+
///
|
|
89
|
+
/// Names the body declares are not subtracted: a closure parameter or a pattern name can
|
|
90
|
+
/// shadow an outer local in one place while the body uses that local in another, and a
|
|
91
|
+
/// declaration of an outer local's name is an error anyway. A name kept that is only shadowed
|
|
92
|
+
/// is an unused parameter of the lifted function, which is harmless.
|
|
93
|
+
pub fn freeNames(cond: Option<&Expr>, body: &Block, bound: &[String]) -> Vec<String> {
|
|
94
|
+
let mut stmts: Vec<Stmt> = Vec::new();
|
|
95
|
+
if let Some(c) = cond {
|
|
96
|
+
stmts.push(Stmt::Expr(c.clone(), 0, 0));
|
|
97
|
+
}
|
|
98
|
+
stmts.extend(body.stmts.iter().cloned());
|
|
99
|
+
let mut refs: Vec<String> = Vec::new();
|
|
100
|
+
let mut seen: HashSet<String> = HashSet::new();
|
|
101
|
+
rename::renameStmts(&mut stmts, &mut |n, k| {
|
|
102
|
+
// A plain `x = v` names a local too: its target is a free local (and the lifted
|
|
103
|
+
// function rejects the assignment like any other).
|
|
104
|
+
if !matches!(k, rename::Name::Decl | rename::Name::Pat) && seen.insert(n.clone()) {
|
|
105
|
+
refs.push(n.clone());
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
// A local closure is used by calling it: `f(x)` names `f` but holds no `Var`.
|
|
109
|
+
mapStmts(&mut stmts, &mut |e| {
|
|
110
|
+
if let ExprKind::FnCall(c) = &e.kind {
|
|
111
|
+
if seen.insert(c.name.clone()) {
|
|
112
|
+
refs.push(c.name.clone());
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if matches!(e.kind, ExprKind::Self_) && seen.insert("self".to_string()) {
|
|
116
|
+
refs.push("self".to_string());
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
refs.into_iter().filter(|n| !bound.contains(n)).collect()
|
|
45
120
|
}
|
|
46
121
|
|
|
47
122
|
fn nextLoopId() -> usize {
|
|
@@ -60,6 +135,106 @@ fn freshId() -> usize {
|
|
|
60
135
|
})
|
|
61
136
|
}
|
|
62
137
|
|
|
138
|
+
/// The call that stands for a `while`: `__while(id, fun() { if cond { body } })`.
|
|
139
|
+
pub const WHILE_CALL: &str = "__while";
|
|
140
|
+
/// The call that stands for a `for`: `__for:source text(id, source, fun(binders) { body })`.
|
|
141
|
+
/// The source text (for diagnostics) rides in the name: it is not a value of the program.
|
|
142
|
+
pub const FOR_CALL: &str = "__for:";
|
|
143
|
+
|
|
144
|
+
/// Is `name` the callee of a loop?
|
|
145
|
+
pub fn isLoopCall(name: &str) -> bool {
|
|
146
|
+
name == WHILE_CALL || name.starts_with(FOR_CALL)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// A `for` or `while`, read back from the call the parser made for it. The call is an
|
|
150
|
+
/// ordinary one (so no pass needs a statement node for loops): the checker records how each is
|
|
151
|
+
/// lifted and [`finish`] replaces it by a call of its lifted function.
|
|
152
|
+
#[derive(Clone, Debug)]
|
|
153
|
+
pub struct Loop {
|
|
154
|
+
/// Identifies this loop for its lifting; 0 before [`prepareForms`] numbers it.
|
|
155
|
+
pub id: usize,
|
|
156
|
+
/// A `while`'s condition.
|
|
157
|
+
pub cond: Option<Expr>,
|
|
158
|
+
/// A `for`'s binders, the source and the source text (for diagnostics).
|
|
159
|
+
pub binders: Vec<String>,
|
|
160
|
+
pub source: Option<Expr>,
|
|
161
|
+
pub sourceText: String,
|
|
162
|
+
pub body: Block,
|
|
163
|
+
/// 1-based position of the keyword.
|
|
164
|
+
pub line: usize,
|
|
165
|
+
pub column: usize,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// The statement for `while cond { body }`.
|
|
169
|
+
pub fn whileStmt(cond: Expr, body: Block, line: usize, column: usize) -> Stmt {
|
|
170
|
+
let inner = Stmt::If(If { condition: cond, body, else_ifs: vec![], else_: None });
|
|
171
|
+
let closure = Expr::Closure(Box::new(Closure { params: vec![], param_types: vec![], body: Block { stmts: vec![inner] } }));
|
|
172
|
+
loopStmt(WHILE_CALL, vec![closure], line, column)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/// The statement for `for binders := range source { body }`.
|
|
176
|
+
pub fn forStmt(binders: Vec<String>, source: Expr, sourceText: String, body: Block, line: usize, column: usize) -> Stmt {
|
|
177
|
+
let types = vec![None; binders.len()];
|
|
178
|
+
let closure = Expr::Closure(Box::new(Closure { params: binders, param_types: types, body }));
|
|
179
|
+
loopStmt(&format!("{FOR_CALL}{sourceText}"), vec![source, closure], line, column)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
fn loopStmt(name: &str, rest: Vec<Expr>, line: usize, column: usize) -> Stmt {
|
|
183
|
+
let args = std::iter::once(Expr::Int(0)).chain(rest).map(Arg::Positional).collect();
|
|
184
|
+
Stmt::Expr(Expr::FnCall(FnCall { name: name.to_string(), args, line, column, tail: TailKind::NotTail }), line, column)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/// The loop a statement is, if it is one.
|
|
188
|
+
pub fn loopOf(s: &Stmt) -> Option<Loop> {
|
|
189
|
+
let StmtKind::Expr(Expr { kind: ExprKind::FnCall(c), .. }, ..) = &s.kind else { return None };
|
|
190
|
+
let arg = |i: usize| match c.args.get(i) {
|
|
191
|
+
Some(Arg::Positional(e)) => Some(e),
|
|
192
|
+
_ => None,
|
|
193
|
+
};
|
|
194
|
+
let id = match arg(0)?.kind {
|
|
195
|
+
ExprKind::Int(n) => n as usize,
|
|
196
|
+
_ => return None,
|
|
197
|
+
};
|
|
198
|
+
let closure = |e: &Expr| match &e.kind {
|
|
199
|
+
ExprKind::Closure(cl) => Some((**cl).clone()),
|
|
200
|
+
_ => None,
|
|
201
|
+
};
|
|
202
|
+
if c.name == WHILE_CALL {
|
|
203
|
+
let cl = closure(arg(1)?)?;
|
|
204
|
+
let Some(Stmt { kind: StmtKind::If(i), .. }) = cl.body.stmts.into_iter().next() else { return None };
|
|
205
|
+
return Some(Loop { id, cond: Some(i.condition), binders: vec![], source: None, sourceText: String::new(), body: i.body, line: c.line, column: c.column });
|
|
206
|
+
}
|
|
207
|
+
let sourceText = c.name.strip_prefix(FOR_CALL)?.to_string();
|
|
208
|
+
let cl = closure(arg(2)?)?;
|
|
209
|
+
Some(Loop { id, cond: None, binders: cl.params, source: Some(arg(1)?.clone()), sourceText, body: cl.body, line: c.line, column: c.column })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// The block a loop's closure holds: a `for`'s body, or the `if` that is a `while`.
|
|
213
|
+
pub fn loopBlock(s: &Stmt) -> Option<&Block> {
|
|
214
|
+
loopOf(s)?;
|
|
215
|
+
let StmtKind::Expr(Expr { kind: ExprKind::FnCall(c), .. }, ..) = &s.kind else { return None };
|
|
216
|
+
match c.args.last()? {
|
|
217
|
+
Arg::Positional(Expr { kind: ExprKind::Closure(cl), .. }) => Some(&cl.body),
|
|
218
|
+
_ => None,
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// [`loopBlock`], to change.
|
|
223
|
+
pub fn loopBlockMut(s: &mut Stmt) -> Option<&mut Block> {
|
|
224
|
+
loopOf(s)?;
|
|
225
|
+
let StmtKind::Expr(Expr { kind: ExprKind::FnCall(c), .. }, ..) = &mut s.kind else { return None };
|
|
226
|
+
match c.args.last_mut()? {
|
|
227
|
+
Arg::Positional(Expr { kind: ExprKind::Closure(cl), .. }) => Some(&mut cl.body),
|
|
228
|
+
_ => None,
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
fn setLoopId(s: &mut Stmt, id: usize) {
|
|
233
|
+
if let StmtKind::Expr(Expr { kind: ExprKind::FnCall(c), .. }, ..) = &mut s.kind {
|
|
234
|
+
c.args[0] = Arg::Positional(Expr::Int(id as i64));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
63
238
|
/// Gives every `for` of `source` an identity. The loops themselves are lowered
|
|
64
239
|
/// later, by the checker (see [`lowerLoop`]).
|
|
65
240
|
pub fn prepareForms(source: &mut Source) {
|
|
@@ -83,9 +258,9 @@ fn numberLoops(stmts: &mut [Stmt], loops: &mut bool) {
|
|
|
83
258
|
walkDeep(
|
|
84
259
|
stmts,
|
|
85
260
|
&mut |s| {
|
|
86
|
-
if
|
|
261
|
+
if loopOf(s).is_some() {
|
|
87
262
|
*loops = true;
|
|
88
|
-
|
|
263
|
+
setLoopId(s, nextLoopId());
|
|
89
264
|
}
|
|
90
265
|
},
|
|
91
266
|
&mut |_| {},
|
|
@@ -99,16 +274,10 @@ fn numberLoopsIn(e: &mut Expr, loops: &mut bool) {
|
|
|
99
274
|
*e = back;
|
|
100
275
|
}
|
|
101
276
|
|
|
277
|
+
/// A local the checking form rebinds with no declaration, so a binder that shadows an earlier
|
|
278
|
+
/// name (as a lifted function's does) is accepted here too. Never in a program that is compiled.
|
|
102
279
|
fn declare(name: String, value: Expr) -> Stmt {
|
|
103
|
-
Stmt::Assign(Assign {
|
|
104
|
-
isSynthetic: true,
|
|
105
|
-
targets: vec![AssignTarget::Var(name)],
|
|
106
|
-
values: vec![value],
|
|
107
|
-
// The lowering's own locals are rebound in the loop body, so they use
|
|
108
|
-
|
|
280
|
+
Stmt::Assign(Assign { isSynthetic: true, targets: vec![AssignTarget::Var(name)], values: vec![value], declare: false, ty: None })
|
|
109
|
-
declare: false,
|
|
110
|
-
ty: None,
|
|
111
|
-
})
|
|
112
281
|
}
|
|
113
282
|
|
|
114
283
|
/// A `for` binder named `_` is not bound.
|
|
@@ -131,7 +300,6 @@ fn method(obj: &str, name: &str, args: Vec<Expr>) -> Expr {
|
|
|
131
300
|
line: 0,
|
|
132
301
|
column: 0,
|
|
133
302
|
tail: TailKind::NotTail,
|
|
134
|
-
unique: false,
|
|
135
303
|
}),
|
|
136
304
|
}))
|
|
137
305
|
}
|
|
@@ -142,6 +310,7 @@ pub fn resetCounters() {
|
|
|
142
310
|
ACTIVE.with(|a| a.set(false));
|
|
143
311
|
COUNTER.with(|c| c.set(0));
|
|
144
312
|
LOWERED.with(|l| l.borrow_mut().clear());
|
|
313
|
+
LIFTS.with(|l| l.borrow_mut().clear());
|
|
145
314
|
}
|
|
146
315
|
|
|
147
316
|
/// Starts a lowering session for `source` (see [`lowerLoop`], [`finish`]).
|
|
@@ -149,6 +318,7 @@ pub fn begin(_source: &Source) {
|
|
|
149
318
|
ACTIVE.with(|a| a.set(true));
|
|
150
319
|
COUNTER.with(|c| c.set(0));
|
|
151
320
|
LOWERED.with(|l| l.borrow_mut().clear());
|
|
321
|
+
LIFTS.with(|l| l.borrow_mut().clear());
|
|
152
322
|
}
|
|
153
323
|
|
|
154
324
|
/// Is a lowering session running?
|
|
@@ -156,57 +326,90 @@ pub fn active() -> bool {
|
|
|
156
326
|
ACTIVE.with(|a| a.get())
|
|
157
327
|
}
|
|
158
328
|
|
|
159
|
-
/// Lowers one `for`. `typeOf` gives the type of an expression of the loop's
|
|
160
|
-
///
|
|
329
|
+
/// How a `for` over a source of type `ty` iterates (`None`: unknown, plain iteration).
|
|
161
|
-
/// can't tell, the plain lowering is returned but not remembered, so a later
|
|
162
|
-
/// attempt can do better.
|
|
163
|
-
pub fn
|
|
330
|
+
pub fn iterKind(ty: Option<&TyInfo>, sourceTy: Option<Type>) -> Option<LiftKind> {
|
|
331
|
+
match ty {
|
|
332
|
+
Some(t) if t.name == "Int" => Some(LiftKind::Int),
|
|
333
|
+
Some(t) if t.methods.contains("next") => sourceTy.map(LiftKind::Next),
|
|
164
|
-
|
|
334
|
+
Some(_) => sourceTy.map(LiftKind::Plain),
|
|
335
|
+
None => None,
|
|
336
|
+
}
|
|
165
337
|
}
|
|
166
338
|
|
|
339
|
+
/// What the checker checks in place of the `for` at `fl`: the binders and the source's
|
|
340
|
+
/// own locals declared, then the body, to be checked in a scope of its own. `typeOf` gives
|
|
341
|
+
/// the type of an expression of the loop's scope; it decides between counting, `next` and
|
|
342
|
+
/// plain iteration. When it can't tell, the plain form is returned but not remembered, so a
|
|
343
|
+
/// later attempt can do better.
|
|
167
|
-
fn
|
|
344
|
+
pub fn lowerLoop(fl: &Loop, typeOf: TypeOf) -> Rc<Vec<Stmt>> {
|
|
168
345
|
if let Some(r) = LOWERED.with(|l| l.borrow().get(&fl.id).cloned()) {
|
|
169
346
|
return r;
|
|
170
347
|
}
|
|
171
348
|
if !active() {
|
|
172
349
|
return Rc::new(Vec::new());
|
|
173
350
|
}
|
|
174
|
-
let ty = typeOf(
|
|
351
|
+
let ty = typeOf(fl.source.as_ref().expect("a `for`"));
|
|
175
352
|
let typed = ty.is_some();
|
|
176
353
|
let f = fl.clone();
|
|
177
354
|
let mut block = Block {
|
|
178
355
|
stmts: match ty {
|
|
179
|
-
Some(t) if t.name == "Int" =>
|
|
356
|
+
Some(t) if t.name == "Int" => checkInt(f),
|
|
180
|
-
Some(t) if t.methods.contains("next") =>
|
|
357
|
+
Some(t) if t.methods.contains("next") => checkNext(f),
|
|
181
|
-
_ =>
|
|
358
|
+
_ => checkPlain(f),
|
|
182
359
|
},
|
|
183
360
|
};
|
|
184
|
-
// The checker
|
|
361
|
+
// The checker records types by node id and `finish` clones the loop's own nodes, not
|
|
185
|
-
//
|
|
362
|
+
// these, so they are numbered here, once.
|
|
186
363
|
numberBlockIds(&mut block);
|
|
187
364
|
let out = Rc::new(block.stmts);
|
|
188
|
-
if typed
|
|
365
|
+
if typed {
|
|
189
366
|
LOWERED.with(|l| l.borrow_mut().insert(fl.id, out.clone()));
|
|
190
367
|
}
|
|
191
368
|
out
|
|
192
369
|
}
|
|
193
370
|
|
|
194
|
-
/// Ends the session: a copy of `source` with every
|
|
371
|
+
/// Ends the session: a copy of `source` with every loop the checker recorded a [`Lift`] for
|
|
195
|
-
///
|
|
372
|
+
/// replaced by a call of its lifted top-level function (appended to the items). A loop with no
|
|
373
|
+
/// record (a type the checker couldn't write down) stays as it is, and the re-check reports it.
|
|
196
374
|
pub fn finish(source: &Source) -> Source {
|
|
197
375
|
let mut out = source.clone();
|
|
376
|
+
let mut lifted: Vec<Item> = Vec::new();
|
|
198
377
|
for item in &mut out.items {
|
|
199
378
|
match item {
|
|
379
|
+
Item::Fn(f) => {
|
|
380
|
+
let at = LiftSite {
|
|
381
|
+
name: crate::modules::sourceFnName(&f.name).to_string(),
|
|
382
|
+
file: f.file.clone(),
|
|
383
|
+
line: f.line,
|
|
384
|
+
column: f.column,
|
|
385
|
+
generics: f.generics.clone(),
|
|
386
|
+
isFip: f.is_fip,
|
|
387
|
+
};
|
|
200
|
-
|
|
388
|
+
match &mut f.body {
|
|
201
|
-
|
|
389
|
+
FnBody::Block(b) => applyStmts(&mut b.stmts, &at, &mut lifted),
|
|
202
|
-
|
|
390
|
+
FnBody::Expr(e) => applyExpr(e, &at, &mut lifted),
|
|
203
|
-
|
|
391
|
+
FnBody::Extern => {}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
Item::Test(t) => {
|
|
395
|
+
let at = LiftSite {
|
|
396
|
+
name: t.name.clone(),
|
|
397
|
+
file: t.file.clone(),
|
|
398
|
+
line: t.line,
|
|
399
|
+
column: t.column,
|
|
400
|
+
generics: Vec::new(),
|
|
401
|
+
isFip: false,
|
|
204
|
-
|
|
402
|
+
};
|
|
205
|
-
|
|
403
|
+
applyStmts(&mut t.body.stmts, &at, &mut lifted)
|
|
404
|
+
}
|
|
206
|
-
Item::Const(c) =>
|
|
405
|
+
Item::Const(c) => {
|
|
406
|
+
let at = LiftSite { name: c.name.clone(), file: source.file.clone(), line: c.line, column: 0, generics: Vec::new(), isFip: false };
|
|
407
|
+
applyExpr(&mut c.value, &at, &mut lifted)
|
|
408
|
+
}
|
|
207
409
|
Item::Enum(_) => {}
|
|
208
410
|
}
|
|
209
411
|
}
|
|
412
|
+
out.items.extend(lifted);
|
|
210
413
|
let mut uniq = 0usize;
|
|
211
414
|
for item in &mut out.items {
|
|
212
415
|
match item {
|
|
@@ -230,25 +433,36 @@ pub fn finish(source: &Source) -> Source {
|
|
|
230
433
|
out.formLoops = false;
|
|
231
434
|
ACTIVE.with(|a| a.set(false));
|
|
232
435
|
LOWERED.with(|l| l.borrow_mut().clear());
|
|
436
|
+
LIFTS.with(|l| l.borrow_mut().clear());
|
|
233
437
|
out
|
|
234
438
|
}
|
|
235
439
|
|
|
440
|
+
/// The function a loop sits in: the lifted function is declared like it (same file, same owner
|
|
441
|
+
/// type, so names resolve as they did, same generics).
|
|
442
|
+
struct LiftSite {
|
|
443
|
+
/// The name the function was written with, for the lifted functions' names.
|
|
444
|
+
name: String,
|
|
445
|
+
file: String,
|
|
446
|
+
line: usize,
|
|
447
|
+
column: usize,
|
|
448
|
+
generics: Vec<String>,
|
|
449
|
+
isFip: bool,
|
|
450
|
+
}
|
|
451
|
+
|
|
236
|
-
fn applyStmts(stmts: &mut Vec<Stmt>) {
|
|
452
|
+
fn applyStmts(stmts: &mut Vec<Stmt>, at: &LiftSite, lifted: &mut Vec<Item>) {
|
|
237
453
|
for s in std::mem::take(stmts) {
|
|
454
|
+
let lp = loopOf(&s);
|
|
455
|
+
let lift = lp.as_ref().and_then(|l| LIFTS.with(|m| m.borrow().get(&l.id).cloned()));
|
|
238
|
-
match
|
|
456
|
+
match (lp, lift) {
|
|
239
|
-
|
|
457
|
+
(Some(lp), Some(lift)) if lp.cond.is_some() => stmts.extend(liftWhile(lp, lift, at, lifted)),
|
|
240
|
-
|
|
458
|
+
(Some(lp), Some(lift)) => stmts.extend(liftFor(lp, lift, at, lifted)),
|
|
241
|
-
let mut v: Vec<Stmt> = (*low).clone();
|
|
242
|
-
applyStmts(&mut v);
|
|
243
|
-
stmts.extend(v);
|
|
244
|
-
}
|
|
245
459
|
_ => {
|
|
246
460
|
let mut other = s;
|
|
247
461
|
for e in stmtExprs(&mut other) {
|
|
248
|
-
applyExpr(e);
|
|
462
|
+
applyExpr(e, at, lifted);
|
|
249
463
|
}
|
|
250
464
|
for b in stmtBlocks(&mut other) {
|
|
251
|
-
applyStmts(&mut b.stmts);
|
|
465
|
+
applyStmts(&mut b.stmts, at, lifted);
|
|
252
466
|
}
|
|
253
467
|
stmts.push(other);
|
|
254
468
|
}
|
|
@@ -256,107 +470,233 @@ fn applyStmts(stmts: &mut Vec<Stmt>) {
|
|
|
256
470
|
}
|
|
257
471
|
}
|
|
258
472
|
|
|
259
|
-
fn applyExpr(e: &mut Expr) {
|
|
473
|
+
fn applyExpr(e: &mut Expr, at: &LiftSite, lifted: &mut Vec<Item>) {
|
|
260
474
|
match &mut e.kind {
|
|
261
|
-
ExprKind::Closure(c) => applyStmts(&mut c.body.stmts),
|
|
475
|
+
ExprKind::Closure(c) => applyStmts(&mut c.body.stmts, at, lifted),
|
|
262
|
-
ExprKind::Block(b) => applyStmts(&mut b.stmts),
|
|
476
|
+
ExprKind::Block(b) => applyStmts(&mut b.stmts, at, lifted),
|
|
263
477
|
_ => {}
|
|
264
478
|
}
|
|
265
479
|
for ch in childExprs(e) {
|
|
266
|
-
applyExpr(ch);
|
|
480
|
+
applyExpr(ch, at, lifted);
|
|
267
481
|
}
|
|
268
482
|
}
|
|
269
483
|
|
|
484
|
+
fn param(name: &str, ty: Type) -> Param {
|
|
485
|
+
Param { name: name.to_string(), ty: ParamType::Type(ty), default: None }
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
fn typeNamed(name: &str) -> Type {
|
|
489
|
+
Type { name: name.to_string(), generics: vec![] }
|
|
490
|
+
}
|
|
491
|
+
|
|
270
|
-
fn
|
|
492
|
+
fn declared(name: String, value: Expr) -> Stmt {
|
|
493
|
+
Stmt::Assign(Assign { isSynthetic: false, targets: vec![AssignTarget::Var(name)], values: vec![value], declare: true, ty: None })
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
fn callOf(name: &str, args: Vec<Expr>, line: usize, column: usize) -> Stmt {
|
|
497
|
+
Stmt::Expr(
|
|
271
|
-
|
|
498
|
+
Expr::FnCall(FnCall {
|
|
272
|
-
condition: Expr::Compare(Box::new(CompareExpr {
|
|
273
|
-
op: CmpOp::Lt,
|
|
274
|
-
left: Expr::Var(c),
|
|
275
|
-
|
|
499
|
+
name: name.to_string(),
|
|
500
|
+
args: args.into_iter().map(Arg::Positional).collect(),
|
|
501
|
+
line: 0,
|
|
502
|
+
column: 0,
|
|
503
|
+
tail: TailKind::NotTail,
|
|
276
|
-
})
|
|
504
|
+
}),
|
|
505
|
+
line,
|
|
506
|
+
column,
|
|
507
|
+
)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
fn liftedFn(id: usize, at: &LiftSite, lift: &Lift, params: Vec<Param>, body: Vec<Stmt>) -> Item {
|
|
511
|
+
let mut generics = at.generics.clone();
|
|
512
|
+
for g in &lift.generics {
|
|
513
|
+
if !generics.contains(g) {
|
|
514
|
+
generics.push(g.clone());
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
Item::Fn(Fn {
|
|
518
|
+
name: liftedName(id, &at.name),
|
|
519
|
+
file: at.file.clone(),
|
|
520
|
+
line: at.line,
|
|
521
|
+
column: at.column,
|
|
522
|
+
type_param: None,
|
|
523
|
+
generics,
|
|
524
|
+
is_extern: false,
|
|
525
|
+
is_export: false,
|
|
526
|
+
is_test: false,
|
|
527
|
+
is_fip: at.isFip,
|
|
528
|
+
has_self: false,
|
|
529
|
+
params,
|
|
530
|
+
returns: None,
|
|
277
|
-
body: Block { stmts:
|
|
531
|
+
body: FnBody::Block(Block { stmts: body }),
|
|
278
532
|
})
|
|
279
533
|
}
|
|
280
534
|
|
|
535
|
+
fn ifThen(condition: Expr, body: Vec<Stmt>) -> Stmt {
|
|
536
|
+
Stmt::If(If { condition, body: Block { stmts: body }, else_ifs: vec![], else_: None })
|
|
537
|
+
}
|
|
538
|
+
|
|
281
|
-
/// `
|
|
539
|
+
/// `self` is only a name inside a method; a lifted function takes it as `__self`.
|
|
540
|
+
const LIFTED_SELF: &str = "__self";
|
|
541
|
+
|
|
542
|
+
fn inside(n: &str) -> String {
|
|
543
|
+
if n == "self" { LIFTED_SELF.to_string() } else { n.to_string() }
|
|
544
|
+
}
|
|
545
|
+
|
|
282
|
-
///
|
|
546
|
+
/// The free locals as the call that starts a loop passes them.
|
|
547
|
+
fn freeArgs(lift: &Lift) -> Vec<Expr> {
|
|
548
|
+
lift.params.iter().map(|(n, _)| if n == "self" { Expr::Self_ } else { Expr::Var(n.clone()) }).collect()
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/// The free locals as the lifted function's own recursive call passes them.
|
|
283
|
-
fn
|
|
552
|
+
fn innerArgs(lift: &Lift) -> Vec<Expr> {
|
|
553
|
+
lift.params.iter().map(|(n, _)| Expr::Var(inside(n))).collect()
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
fn freeParams(lift: &Lift) -> Vec<Param> {
|
|
557
|
+
lift.params.iter().map(|(n, t)| param(&inside(n), t.clone())).collect()
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
fn renameSelf(stmts: &mut [Stmt]) {
|
|
561
|
+
mapStmts(stmts, &mut |e| {
|
|
562
|
+
if matches!(e.kind, ExprKind::Self_) {
|
|
563
|
+
*e = Expr::Var(LIFTED_SELF.to_string());
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/// `while cond { body }` becomes `fun __loopN(free..) = if cond { body; __loopN(free..) }`.
|
|
569
|
+
fn liftWhile(w: Loop, lift: Lift, at: &LiftSite, lifted: &mut Vec<Item>) -> Vec<Stmt> {
|
|
570
|
+
let mut body = w.body.stmts;
|
|
571
|
+
applyStmts(&mut body, at, lifted);
|
|
572
|
+
let name = liftedName(w.id, &at.name);
|
|
573
|
+
body.push(callOf(&name, innerArgs(&lift), 0, 0));
|
|
574
|
+
let mut cond = w.cond.expect("a `while`");
|
|
575
|
+
applyExpr(&mut cond, at, lifted);
|
|
576
|
+
let mut one = vec![Stmt::Expr(cond, 0, 0), ifThen(Expr::BoolLit(true), body)];
|
|
577
|
+
renameSelf(&mut one);
|
|
578
|
+
let [Stmt { kind: StmtKind::Expr(cond, ..), .. }, Stmt { kind: StmtKind::If(If { body: Block { stmts: body }, .. }), .. }] = <[Stmt; 2]>::try_from(one).unwrap() else { unreachable!() };
|
|
579
|
+
lifted.push(liftedFn(w.id, at, &lift, freeParams(&lift), vec![ifThen(cond, body)]));
|
|
580
|
+
vec![callOf(&name, freeArgs(&lift), 0, 0)]
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/// `for x := range v { body }` becomes a function that takes the free locals and the loop's
|
|
584
|
+
/// own state (a counter, or the iterator) and calls itself for the next pass.
|
|
585
|
+
fn liftFor(f: Loop, lift: Lift, at: &LiftSite, lifted: &mut Vec<Item>) -> Vec<Stmt> {
|
|
284
|
-
let id =
|
|
586
|
+
let id = f.id;
|
|
587
|
+
let src = f.source.expect("a `for`");
|
|
588
|
+
let name = liftedName(id, &at.name);
|
|
589
|
+
let mut body = f.body.stmts;
|
|
590
|
+
applyStmts(&mut body, at, lifted);
|
|
285
591
|
let n = format!("__for_n{}", id);
|
|
286
592
|
let c = format!("__for_c{}", id);
|
|
593
|
+
let free = innerArgs(&lift);
|
|
594
|
+
let entryFree = freeArgs(&lift);
|
|
595
|
+
let binder = f.binders.first().filter(|b| *b != "_").cloned();
|
|
596
|
+
let var = |s: &str| Expr::Var(s.to_string());
|
|
597
|
+
let withEntry = |first: Vec<Expr>, last: Vec<Expr>| -> Vec<Expr> { first.into_iter().chain(entryFree.clone()).chain(last).collect() };
|
|
598
|
+
let with = |first: Vec<Expr>, last: Vec<Expr>| -> Vec<Expr> { first.into_iter().chain(free.clone()).chain(last).collect() };
|
|
599
|
+
let (params, bodyStmts, entry): (Vec<Param>, Vec<Stmt>, Vec<Stmt>) = match &lift.kind {
|
|
600
|
+
LiftKind::Int => {
|
|
287
|
-
|
|
601
|
+
let mut inner = Vec::new();
|
|
602
|
+
inner.extend(binder.map(|b| declared(b, var(&c))));
|
|
603
|
+
inner.extend(body);
|
|
604
|
+
inner.push(callOf(&name, with(vec![var(&n)], vec![binary(BinOp::Add, var(&c), Expr::Int(1))]), 0, 0));
|
|
605
|
+
let cond = Expr::Compare(Box::new(CompareExpr { op: CmpOp::Lt, left: var(&c), right: var(&n) }));
|
|
606
|
+
let mut params = vec![param(&n, typeNamed("Int"))];
|
|
607
|
+
params.extend(freeParams(&lift));
|
|
608
|
+
params.push(param(&c, typeNamed("Int")));
|
|
609
|
+
(params, vec![ifThen(cond, inner)], vec![callOf(&name, withEntry(vec![src], vec![Expr::Int(0)]), f.line, f.column)])
|
|
610
|
+
}
|
|
611
|
+
LiftKind::Next(ty) => {
|
|
612
|
+
let it = format!("__for_next{}", id);
|
|
613
|
+
let step = format!("__for_step{}", id);
|
|
614
|
+
let field = |name: &str| {
|
|
615
|
+
Expr::Attribute(Box::new(AttributeExpr { object: var(&step), attr: AttrKind::Field(name.to_string()) }))
|
|
616
|
+
};
|
|
617
|
+
let mut inner = Vec::new();
|
|
618
|
+
inner.extend(binder.map(|b| declared(b, field("first"))));
|
|
619
|
+
inner.extend(body);
|
|
620
|
+
inner.push(callOf(&name, with(vec![field("second")], vec![]), 0, 0));
|
|
621
|
+
let cond = Expr::Bind(Box::new(BindExpr {
|
|
622
|
+
case: Case {
|
|
623
|
+
patterns: vec![CasePattern::class("Some".to_string(), vec![CasePattern::Name(step.clone())])],
|
|
624
|
+
guard: None,
|
|
625
|
+
body: Block { stmts: vec![Stmt::Expr(Expr::BoolLit(true), f.line, f.column)] },
|
|
626
|
+
},
|
|
627
|
+
value: method(&it, "next", vec![]),
|
|
628
|
+
}));
|
|
629
|
+
let mut params = vec![param(&it, ty.clone())];
|
|
630
|
+
params.extend(freeParams(&lift));
|
|
631
|
+
(params, vec![ifThen(cond, inner)], vec![callOf(&name, withEntry(vec![src], vec![]), f.line, f.column)])
|
|
632
|
+
}
|
|
633
|
+
LiftKind::Plain(ty) => {
|
|
634
|
+
let it = format!("__for_it{}", id);
|
|
635
|
+
let outer = format!("{}{}:{}", FOR_ITER_PREFIX, id, f.sourceText);
|
|
636
|
+
let mut inner = Vec::new();
|
|
637
|
+
inner.extend(binder.map(|b| declared(b, method(&it, "at", vec![var(&c)]))));
|
|
638
|
+
inner.extend(body);
|
|
639
|
+
inner.push(callOf(&name, with(vec![var(&it), var(&n)], vec![binary(BinOp::Add, var(&c), Expr::Int(1))]), 0, 0));
|
|
640
|
+
let cond = Expr::Compare(Box::new(CompareExpr { op: CmpOp::Lt, left: var(&c), right: var(&n) }));
|
|
641
|
+
let mut params = vec![param(&it, ty.clone()), param(&n, typeNamed("Int"))];
|
|
642
|
+
params.extend(freeParams(&lift));
|
|
643
|
+
params.push(param(&c, typeNamed("Int")));
|
|
644
|
+
let call = callOf(
|
|
645
|
+
&name,
|
|
646
|
+
withEntry(vec![var(&outer), method(&outer, "length", vec![])], vec![Expr::Int(0)]),
|
|
647
|
+
f.line,
|
|
648
|
+
f.column,
|
|
649
|
+
);
|
|
650
|
+
(params, vec![ifThen(cond, inner)], vec![declared(outer, src), call])
|
|
651
|
+
}
|
|
652
|
+
LiftKind::While => unreachable!("a `for` is never lifted as a `while`"),
|
|
653
|
+
};
|
|
654
|
+
let mut bodyStmts = bodyStmts;
|
|
655
|
+
renameSelf(&mut bodyStmts);
|
|
656
|
+
lifted.push(liftedFn(id, at, &lift, params, bodyStmts));
|
|
657
|
+
entry
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/// `for i := range n`: `n` and `i` are Ints.
|
|
661
|
+
fn checkInt(f: Loop) -> Vec<Stmt> {
|
|
662
|
+
let id = freshId();
|
|
663
|
+
let mut out = vec![declare(format!("__for_n{}", id), f.source.expect("a `for`"))];
|
|
288
|
-
bind(&f.binders[0], Expr::
|
|
664
|
+
bind(&f.binders[0], Expr::Int(0), &mut out);
|
|
289
|
-
inner.push(declare(
|
|
290
|
-
c.clone(),
|
|
291
|
-
binary(BinOp::Add, Expr::Var(c.clone()), Expr::Int(1)),
|
|
292
|
-
));
|
|
293
|
-
|
|
665
|
+
out.extend(f.body.stmts);
|
|
294
|
-
|
|
666
|
+
out
|
|
295
|
-
declare(n.clone(), f.source),
|
|
296
|
-
declare(c.clone(), Expr::Int(0)),
|
|
297
|
-
counted(n, c, inner),
|
|
298
|
-
]
|
|
299
667
|
}
|
|
300
668
|
|
|
301
669
|
/// `for x := range v` over a type with `next(self) -> Option[Pair[T, Self]]`:
|
|
302
|
-
/// `it := v; while Some(step) := it.next() { x := step.first; it = step.second; ... }`.
|
|
303
|
-
///
|
|
670
|
+
/// `x` is the first of the step the next call gives.
|
|
304
|
-
fn
|
|
671
|
+
fn checkNext(f: Loop) -> Vec<Stmt> {
|
|
305
672
|
let id = freshId();
|
|
306
673
|
let it = format!("__for_next{}", id);
|
|
307
674
|
let step = format!("__for_step{}", id);
|
|
308
|
-
let field = |name: &str| {
|
|
309
|
-
|
|
675
|
+
let first = Expr::Attribute(Box::new(AttributeExpr { object: Expr::Var(step.clone()), attr: AttrKind::Field("first".to_string()) }));
|
|
310
|
-
object: Expr::Var(step.clone()),
|
|
311
|
-
attr: AttrKind::Field(name.to_string()),
|
|
312
|
-
}))
|
|
313
|
-
};
|
|
314
676
|
let mut inner = Vec::new();
|
|
315
|
-
bind(&f.binders[0],
|
|
677
|
+
bind(&f.binders[0], first, &mut inner);
|
|
316
|
-
inner.push(declare(it.clone(), field("second")));
|
|
317
678
|
inner.extend(f.body.stmts);
|
|
318
679
|
let cond = Expr::Bind(Box::new(BindExpr {
|
|
319
680
|
case: Case {
|
|
320
|
-
patterns: vec![CasePattern::class("Some".to_string(), vec![CasePattern::Name(step
|
|
681
|
+
patterns: vec![CasePattern::class("Some".to_string(), vec![CasePattern::Name(step)])],
|
|
321
682
|
guard: None,
|
|
322
|
-
body: Block {
|
|
323
|
-
|
|
683
|
+
body: Block { stmts: vec![Stmt::Expr(Expr::BoolLit(true), f.line, f.column)] },
|
|
324
|
-
},
|
|
325
684
|
},
|
|
326
685
|
value: method(&it, "next", vec![]),
|
|
327
686
|
}));
|
|
328
|
-
vec![
|
|
329
|
-
|
|
687
|
+
vec![declare(it, f.source.expect("a `for`")), ifThen(cond, inner)]
|
|
330
|
-
Stmt::While(While {
|
|
331
|
-
condition: cond,
|
|
332
|
-
body: Block { stmts: inner },
|
|
333
|
-
}),
|
|
334
|
-
]
|
|
335
688
|
}
|
|
336
689
|
|
|
337
|
-
/// `
|
|
690
|
+
/// `for x := range v` over anything else: `v` has `length()` and `at(i)`, and `x` is `at(0)`.
|
|
338
|
-
/// The counter is bumped before the body, so a `continue` still advances it.
|
|
339
|
-
fn
|
|
691
|
+
fn checkPlain(f: Loop) -> Vec<Stmt> {
|
|
340
692
|
let id = freshId();
|
|
341
693
|
let it = format!("{}{}:{}", FOR_ITER_PREFIX, id, f.sourceText);
|
|
342
|
-
let n = format!("__for_n{}", id);
|
|
343
|
-
let c = format!("__for_c{}", id);
|
|
344
|
-
let
|
|
694
|
+
let mut out = vec![declare(it.clone(), f.source.expect("a `for`")), declare(format!("__for_n{}", id), method(&it, "length", vec![]))];
|
|
345
|
-
let mut inner = Vec::new();
|
|
346
695
|
if let Some(x) = f.binders.first() {
|
|
347
|
-
bind(x, at, &mut
|
|
696
|
+
bind(x, method(&it, "at", vec![Expr::Int(0)]), &mut out);
|
|
348
697
|
}
|
|
349
|
-
inner.push(declare(
|
|
350
|
-
c.clone(),
|
|
351
|
-
binary(BinOp::Add, Expr::Var(c.clone()), Expr::Int(1)),
|
|
352
|
-
));
|
|
353
|
-
|
|
698
|
+
out.extend(f.body.stmts);
|
|
354
|
-
|
|
699
|
+
out
|
|
355
|
-
declare(it.clone(), f.source),
|
|
356
|
-
declare(n.clone(), method(&it, "length", vec![])),
|
|
357
|
-
declare(c.clone(), Expr::Int(0)),
|
|
358
|
-
counted(n, c, inner),
|
|
359
|
-
]
|
|
360
700
|
}
|
|
361
701
|
|
|
362
702
|
// ---- traversal helpers ------------------------------------------------------
|
|
@@ -557,11 +897,6 @@ fn uniqueConditionBinders(stmts: &mut [Stmt], counter: &mut usize) {
|
|
|
557
897
|
}
|
|
558
898
|
}
|
|
559
899
|
}
|
|
560
|
-
StmtKind::While(w) => {
|
|
561
|
-
if let Some(map) = freshBindNames(&mut w.condition, counter) {
|
|
562
|
-
renameStmts(&mut w.body.stmts, &mut renameMap(&map));
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
900
|
_ => {}
|
|
566
901
|
}
|
|
567
902
|
for e in stmtExprs(s) {
|
compiler/core/src/loader.rs
CHANGED
|
@@ -425,8 +425,8 @@ impl SyntaxError {
|
|
|
425
425
|
let mut msg = format!("unexpected '{}'", tok);
|
|
426
426
|
if tok == "()" {
|
|
427
427
|
msg.push_str(
|
|
428
|
-
"\n hint: `()` is not a value in Plum;
|
|
428
|
+
"\n hint: `()` is not a value in Plum; use `todo` \
|
|
429
|
-
|
|
429
|
+
for a body that is not written yet",
|
|
430
430
|
);
|
|
431
431
|
}
|
|
432
432
|
msg
|
compiler/core/src/modules.rs
CHANGED
|
@@ -258,13 +258,6 @@ impl Cx<'_> {
|
|
|
258
258
|
}
|
|
259
259
|
true
|
|
260
260
|
}
|
|
261
|
-
StmtKind::ForLoop(f) => {
|
|
262
|
-
self.expr(&mut f.source);
|
|
263
|
-
self.scopes.push(f.binders.iter().cloned().collect());
|
|
264
|
-
self.block(&mut f.body);
|
|
265
|
-
self.scopes.pop();
|
|
266
|
-
true
|
|
267
|
-
}
|
|
268
261
|
StmtKind::If(i) => {
|
|
269
262
|
// The scope of the whole statement holds what the conditions bind (`x is Some(v)`).
|
|
270
263
|
self.scopes.push(HashSet::new());
|
compiler/core/src/parser.rs
CHANGED
|
@@ -32,6 +32,18 @@ impl<'a> AstParser<'a> {
|
|
|
32
32
|
Span { startLine: s.row + 1, startColumn: s.column + 1, endLine: e.row + 1, endColumn: e.column + 1 }
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/// Records a Parse diagnostic for a form the language no longer has.
|
|
36
|
+
fn removed(&self, node: Node, message: &str) {
|
|
37
|
+
let pos = node.start_position();
|
|
38
|
+
self.malformed.borrow_mut().push(crate::diag::Diagnostic::new(
|
|
39
|
+
crate::diag::DiagKind::Parse,
|
|
40
|
+
"",
|
|
41
|
+
pos.row + 1,
|
|
42
|
+
pos.column + 1,
|
|
43
|
+
message.to_string(),
|
|
44
|
+
));
|
|
45
|
+
}
|
|
46
|
+
|
|
35
47
|
fn missing(&self, node: Node) -> Expr {
|
|
36
48
|
let pos = node.start_position();
|
|
37
49
|
self.malformed.borrow_mut().push(crate::diag::Diagnostic::new(
|
|
@@ -648,12 +660,7 @@ impl<'a> AstParser<'a> {
|
|
|
648
660
|
let mut stmts = Vec::new();
|
|
649
661
|
for n in node.named_children(&mut cursor) {
|
|
650
662
|
let u = self.unwrapExprNode(n);
|
|
651
|
-
// Every `for` stays a `Stmt::ForLoop` until `forms::lowerForms` lowers it.
|
|
652
|
-
if u.kind() == "for" {
|
|
653
|
-
let mut s = Stmt::ForLoop(self.parseForLoop(u));
|
|
654
|
-
s.span = self.spanOf(u);
|
|
655
|
-
stmts.push(s);
|
|
656
|
-
|
|
663
|
+
if u.kind() == "assign" && self.isUpdate(u) {
|
|
657
664
|
stmts.extend(self.parseUpdate(u));
|
|
658
665
|
} else if let Some(s) = self.parseStmt(n) {
|
|
659
666
|
stmts.push(s);
|
|
@@ -747,9 +754,16 @@ impl<'a> AstParser<'a> {
|
|
|
747
754
|
fn parseStmtKind(&self, node: Node) -> Option<Stmt> {
|
|
748
755
|
Some(match node.kind() {
|
|
749
756
|
"assign" => Stmt::Assign(self.parseAssign(node)),
|
|
750
|
-
"break" =>
|
|
757
|
+
"break" => {
|
|
758
|
+
self.removed(node, "`break` is gone: a loop has no early exit; use `fold`, `find`, `repeatUntil` or a recursive function");
|
|
759
|
+
Stmt::Todo
|
|
760
|
+
}
|
|
751
|
-
"continue" =>
|
|
761
|
+
"continue" => {
|
|
762
|
+
self.removed(node, "`continue` is gone: skip an element with an `if` around the body");
|
|
763
|
+
Stmt::Todo
|
|
764
|
+
}
|
|
752
765
|
"return" => {
|
|
766
|
+
self.removed(node, "`return` is gone: the last expression of a body is its value; end every path with a value (use `if`/`match` instead of an early exit)");
|
|
753
767
|
let expr = node.named_child(0).map(|n| {
|
|
754
768
|
let u = self.unwrapExprNode(n);
|
|
755
769
|
self.parseExpression(u)
|
|
@@ -766,7 +780,8 @@ impl<'a> AstParser<'a> {
|
|
|
766
780
|
.unwrap_or_else(|| self.missing(node)),
|
|
767
781
|
),
|
|
768
782
|
"assert" => Stmt::Assert(self.parseCheck(node)),
|
|
769
|
-
"while" =>
|
|
783
|
+
"while" => self.parseWhile(node),
|
|
784
|
+
"for" => self.parseForLoop(node),
|
|
770
785
|
"if" => Stmt::If(self.parseIf(node)),
|
|
771
786
|
"match" => Stmt::Match(self.parseMatch(node)),
|
|
772
787
|
kind if isExpressionKind(kind) => {
|
|
@@ -842,7 +857,7 @@ impl<'a> AstParser<'a> {
|
|
|
842
857
|
}
|
|
843
858
|
}
|
|
844
859
|
|
|
845
|
-
fn parseForLoop(&self, node: Node) ->
|
|
860
|
+
fn parseForLoop(&self, node: Node) -> Stmt {
|
|
846
861
|
// for: "for" binder ":=" "range" source body
|
|
847
862
|
let binders = self
|
|
848
863
|
.childrenOfKind(node, "var_identifier")
|
|
@@ -861,18 +876,10 @@ impl<'a> AstParser<'a> {
|
|
|
861
876
|
.map(|n| self.parseBlock(n))
|
|
862
877
|
.unwrap_or(Block { stmts: vec![] });
|
|
863
878
|
let pos = node.start_position();
|
|
864
|
-
ForLoop {
|
|
865
|
-
binders,
|
|
866
|
-
source,
|
|
867
|
-
sourceText,
|
|
868
|
-
body,
|
|
869
|
-
id: 0,
|
|
870
|
-
line: pos.row + 1,
|
|
871
|
-
|
|
879
|
+
crate::forms::forStmt(binders, source, sourceText, body, pos.row + 1, pos.column + 1)
|
|
872
|
-
}
|
|
873
880
|
}
|
|
874
881
|
|
|
875
|
-
fn parseWhile(&self, node: Node) ->
|
|
882
|
+
fn parseWhile(&self, node: Node) -> Stmt {
|
|
876
883
|
// while: "while" expression body
|
|
877
884
|
let named: Vec<Node> = self.namedChildren(node);
|
|
878
885
|
let condition = named
|
|
@@ -887,7 +894,8 @@ impl<'a> AstParser<'a> {
|
|
|
887
894
|
.filter(|n| n.kind() == "body")
|
|
888
895
|
.map(|n| self.parseBlock(*n))
|
|
889
896
|
.unwrap_or(Block { stmts: vec![] });
|
|
890
|
-
|
|
897
|
+
let pos = node.start_position();
|
|
898
|
+
crate::forms::whileStmt(condition, body, pos.row + 1, pos.column + 1)
|
|
891
899
|
}
|
|
892
900
|
|
|
893
901
|
fn parseIf(&self, node: Node) -> If {
|
|
@@ -1128,7 +1136,7 @@ impl<'a> AstParser<'a> {
|
|
|
1128
1136
|
.all(|b| Self::valueTail(&b.stmts))
|
|
1129
1137
|
}
|
|
1130
1138
|
Some(StmtKind::Match(m)) => m.cases.iter().all(|c| Self::valueTail(&c.body.stmts)),
|
|
1131
|
-
Some(StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo
|
|
1139
|
+
Some(StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo) => true,
|
|
1132
1140
|
_ => false,
|
|
1133
1141
|
}
|
|
1134
1142
|
}
|
|
@@ -1414,7 +1422,6 @@ impl<'a> AstParser<'a> {
|
|
|
1414
1422
|
line: pos.row + 1,
|
|
1415
1423
|
column: pos.column + 1,
|
|
1416
1424
|
tail: TailKind::NotTail,
|
|
1417
|
-
unique: false,
|
|
1418
1425
|
})
|
|
1419
1426
|
}
|
|
1420
1427
|
None => AttrKind::Field(member),
|
|
@@ -1447,7 +1454,6 @@ impl<'a> AstParser<'a> {
|
|
|
1447
1454
|
line,
|
|
1448
1455
|
column,
|
|
1449
1456
|
tail: TailKind::NotTail,
|
|
1450
|
-
unique: false,
|
|
1451
1457
|
}),
|
|
1452
1458
|
}))
|
|
1453
1459
|
};
|
|
@@ -1528,7 +1534,6 @@ impl<'a> AstParser<'a> {
|
|
|
1528
1534
|
line: pos.row + 1,
|
|
1529
1535
|
column: pos.column + 1,
|
|
1530
1536
|
tail: TailKind::NotTail,
|
|
1531
|
-
unique: false,
|
|
1532
1537
|
}
|
|
1533
1538
|
}
|
|
1534
1539
|
|
|
@@ -1566,7 +1571,6 @@ impl<'a> AstParser<'a> {
|
|
|
1566
1571
|
line: pos.row + 1,
|
|
1567
1572
|
column: pos.column + 1,
|
|
1568
1573
|
tail: TailKind::NotTail,
|
|
1569
|
-
unique: false,
|
|
1570
1574
|
}))
|
|
1571
1575
|
}
|
|
1572
1576
|
_ => {
|
compiler/core/src/purity.rs
CHANGED
|
@@ -379,16 +379,11 @@ impl<'a> Walker<'a> {
|
|
|
379
379
|
self.expr(v);
|
|
380
380
|
}
|
|
381
381
|
}
|
|
382
|
-
StmtKind::Break | StmtKind::Continue => {}
|
|
383
382
|
StmtKind::Todo => {
|
|
384
383
|
self.impure = true;
|
|
385
384
|
self.mutates = true;
|
|
386
385
|
}
|
|
387
386
|
StmtKind::Assert(_) | StmtKind::Crash(_) => self.impure = true,
|
|
388
|
-
StmtKind::ForLoop(l) => {
|
|
389
|
-
self.expr(&l.source);
|
|
390
|
-
self.block(&l.body);
|
|
391
|
-
}
|
|
392
387
|
StmtKind::While(w) => {
|
|
393
388
|
self.expr(&w.condition);
|
|
394
389
|
self.block(&w.body);
|
|
@@ -562,7 +557,6 @@ fn scanAssigns(b: &Block, built: &mut HashMap<String, usize>) {
|
|
|
562
557
|
}
|
|
563
558
|
}
|
|
564
559
|
}
|
|
565
|
-
StmtKind::ForLoop(l) => scanAssigns(&l.body, built),
|
|
566
560
|
StmtKind::While(w) => scanAssigns(&w.body, built),
|
|
567
561
|
StmtKind::If(i) => {
|
|
568
562
|
scanAssigns(&i.body, built);
|
compiler/core/src/question.rs
CHANGED
|
@@ -245,7 +245,6 @@ impl Pass {
|
|
|
245
245
|
}
|
|
246
246
|
// Expressions evaluated before any branch is chosen.
|
|
247
247
|
let condFrom = match &s.kind {
|
|
248
|
-
StmtKind::While(_) => 0,
|
|
249
248
|
StmtKind::If(_) => 1,
|
|
250
249
|
StmtKind::Match(m) => m.subjects.len(),
|
|
251
250
|
_ => usize::MAX,
|
|
@@ -270,16 +269,6 @@ impl Pass {
|
|
|
270
269
|
}
|
|
271
270
|
StmtKind::Match(m)
|
|
272
271
|
}
|
|
273
|
-
StmtKind::While(mut w) => {
|
|
274
|
-
let body = std::mem::replace(&mut w.body, Block { stmts: vec![] });
|
|
275
|
-
w.body = self.lowerBlock(body, Mode::Early);
|
|
276
|
-
StmtKind::While(w)
|
|
277
|
-
}
|
|
278
|
-
StmtKind::ForLoop(mut f) => {
|
|
279
|
-
let body = std::mem::replace(&mut f.body, Block { stmts: vec![] });
|
|
280
|
-
f.body = self.lowerBlock(body, Mode::Early);
|
|
281
|
-
StmtKind::ForLoop(f)
|
|
282
|
-
}
|
|
283
272
|
other => other,
|
|
284
273
|
};
|
|
285
274
|
(pre, Some(s))
|
|
@@ -371,20 +360,31 @@ fn returnKind(f: &Fn) -> Option<Kind> {
|
|
|
371
360
|
}
|
|
372
361
|
}
|
|
373
362
|
|
|
374
|
-
/// Rejects every `?` in `b`'s closures; returns whether any was found.
|
|
363
|
+
/// Rejects every `?` in `b`'s closures; returns whether any was found. A loop body is a
|
|
364
|
+
/// closure to this pass (see `forms::loopOf`), and gets a message of its own.
|
|
375
365
|
fn closureErrors(pass: &mut Pass, b: &Block) -> bool {
|
|
376
366
|
let mut spans = Vec::new();
|
|
367
|
+
let mut loopSpans = Vec::new();
|
|
368
|
+
let mut loopBodies: Vec<*const Block> = Vec::new();
|
|
377
|
-
walkBlockRef(b, &mut |x| {
|
|
369
|
+
walkBlockRef(b, &mut |x| match &x.kind {
|
|
370
|
+
ExprKind::FnCall(c) if crate::forms::isLoopCall(&c.name) => {
|
|
371
|
+
for a in &c.args {
|
|
378
|
-
|
|
372
|
+
if let Arg::Positional(Expr { kind: ExprKind::Closure(cl), .. }) = a {
|
|
373
|
+
loopBodies.push(&cl.body);
|
|
379
|
-
|
|
374
|
+
loopSpans.extend(firstQBlock(&cl.body));
|
|
380
|
-
|
|
375
|
+
}
|
|
381
376
|
}
|
|
382
377
|
}
|
|
378
|
+
ExprKind::Closure(c) if !loopBodies.contains(&(&c.body as *const Block)) => spans.extend(firstQBlock(&c.body)),
|
|
379
|
+
_ => {}
|
|
383
380
|
});
|
|
384
|
-
let any = !spans.is_empty();
|
|
381
|
+
let any = !spans.is_empty() || !loopSpans.is_empty();
|
|
385
382
|
for span in spans {
|
|
386
383
|
pass.error(span, format!("'?' in a closure is not allowed: {MOVE}"));
|
|
387
384
|
}
|
|
385
|
+
for span in loopSpans {
|
|
386
|
+
pass.error(span, "'?' can't be used in a loop body: a loop is a function of its own, so a failure can't leave the enclosing function; match on the value instead".to_string());
|
|
387
|
+
}
|
|
388
388
|
any
|
|
389
389
|
}
|
|
390
390
|
|
compiler/core/src/rename.rs
CHANGED
|
@@ -35,9 +35,6 @@ pub fn renameStmts(stmts: &mut [Stmt], rn: &mut dyn FnMut(&mut String, Name)) {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
StmtKind::ForLoop(f) => {
|
|
39
|
-
f.binders.iter_mut().for_each(|v| rn(v, Name::Decl));
|
|
40
|
-
}
|
|
41
38
|
StmtKind::Match(m) => {
|
|
42
39
|
for c in &mut m.cases {
|
|
43
40
|
for p in &mut c.patterns {
|
compiler/core/src/reuse.rs
CHANGED
|
@@ -101,7 +101,7 @@ pub fn markReuse(src: &mut Source) -> Vec<String> {
|
|
|
101
101
|
let mut bad = false;
|
|
102
102
|
let mut stmts = b.stmts.clone();
|
|
103
103
|
walkStmts(&mut stmts, &mut |s| {
|
|
104
|
-
if matches!(&mut s.kind, StmtKind::While(_)
|
|
104
|
+
if matches!(&mut s.kind, StmtKind::While(_)) {
|
|
105
105
|
bad = true;
|
|
106
106
|
}
|
|
107
107
|
});
|
compiler/core/src/simplify.rs
CHANGED
|
@@ -955,13 +955,6 @@ impl Scoper {
|
|
|
955
955
|
a.values.iter_mut().for_each(|v| self.expr(v));
|
|
956
956
|
}
|
|
957
957
|
}
|
|
958
|
-
StmtKind::ForLoop(f) => {
|
|
959
|
-
self.expr(&mut f.source);
|
|
960
|
-
self.scopes.push(HashMap::new());
|
|
961
|
-
f.binders.iter_mut().for_each(|n| self.declare(n));
|
|
962
|
-
self.stmts(&mut f.body.stmts);
|
|
963
|
-
self.scopes.pop();
|
|
964
|
-
}
|
|
965
958
|
StmtKind::Match(m) => {
|
|
966
959
|
m.subjects.iter_mut().for_each(|e| self.expr(e));
|
|
967
960
|
for c in &mut m.cases {
|
compiler/core/src/tail.rs
CHANGED
|
@@ -82,13 +82,8 @@ fn stmt(cx: &mut Ctx, s: &mut Stmt, tail: bool, ret: bool) {
|
|
|
82
82
|
expr(cx, v, false);
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
-
StmtKind::
|
|
85
|
+
StmtKind::Todo => {}
|
|
86
86
|
StmtKind::Assert(c) => expr(cx, &mut c.cond, false),
|
|
87
|
-
StmtKind::ForLoop(l) => {
|
|
88
|
-
cx.locals.extend(l.binders.iter().cloned());
|
|
89
|
-
expr(cx, &mut l.source, false);
|
|
90
|
-
block(cx, &mut l.body, false, false);
|
|
91
|
-
}
|
|
92
87
|
StmtKind::While(w) => {
|
|
93
88
|
expr(cx, &mut w.condition, false);
|
|
94
89
|
block(cx, &mut w.body, false, false);
|
compiler/core/src/tests_lower.rs
CHANGED
|
@@ -24,6 +24,33 @@ pub fn lowerTests(source: &ast::Source) -> TestProgram {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/// The hidden struct holding a test's report: `struct __TestReport(mut text: Str)`.
|
|
28
|
+
const REPORT_TYPE: &str = "__TestReport";
|
|
29
|
+
const REPORT_FIELD: &str = "text";
|
|
30
|
+
|
|
31
|
+
fn reportField() -> crate::ast::Expr {
|
|
32
|
+
crate::ast::Expr::Attribute(Box::new(crate::ast::AttributeExpr {
|
|
33
|
+
object: crate::ast::Expr::Var("__report".to_string()),
|
|
34
|
+
attr: crate::ast::AttrKind::Field(REPORT_FIELD.to_string()),
|
|
35
|
+
}))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
fn reportStruct() -> crate::ast::Item {
|
|
39
|
+
crate::ast::Item::Enum(crate::ast::Enum {
|
|
40
|
+
name: REPORT_TYPE.to_string(),
|
|
41
|
+
line: 0,
|
|
42
|
+
column: 0,
|
|
43
|
+
generics: vec![],
|
|
44
|
+
variants: vec![crate::ast::EnumVariant {
|
|
45
|
+
name: REPORT_TYPE.to_string(),
|
|
46
|
+
fields: vec![crate::ast::Type { name: crate::ast::STR_TYPE.to_string(), generics: vec![] }],
|
|
47
|
+
field_names: vec![REPORT_FIELD.to_string()],
|
|
48
|
+
mut_fields: vec![true],
|
|
49
|
+
}],
|
|
50
|
+
kind: crate::ast::TypeKind::Struct(crate::ast::StructInfo::default()),
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
27
54
|
fn strLit(s: String) -> crate::ast::Expr {
|
|
28
55
|
crate::ast::Expr::String(crate::ast::StringExpr {
|
|
29
56
|
parts: vec![crate::ast::StringPart::Text(s)],
|
|
@@ -90,19 +117,24 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
|
|
|
90
117
|
test_idx += 1;
|
|
91
118
|
|
|
92
119
|
let mut stmts = Vec::with_capacity(t.body.stmts.len() + 2);
|
|
120
|
+
// The report is a field of a `mut` struct, so an assert inside a loop (a
|
|
121
|
+
// function of its own) writes into the same object.
|
|
93
122
|
stmts.push(crate::ast::Stmt::Assign(crate::ast::Assign {
|
|
94
123
|
isSynthetic: false,
|
|
95
124
|
targets: vec![crate::ast::AssignTarget::Var("__report".to_string())],
|
|
125
|
+
values: vec![crate::ast::Expr::ClassCall(crate::ast::ClassCall {
|
|
96
|
-
|
|
126
|
+
type_name: REPORT_TYPE.to_string(),
|
|
127
|
+
fields: vec![crate::ast::FieldArg { name: REPORT_FIELD.to_string(), value: strLit(String::new()) }],
|
|
128
|
+
generics: vec![],
|
|
129
|
+
spread: None,
|
|
130
|
+
unique: false,
|
|
131
|
+
reuse: None,
|
|
132
|
+
})],
|
|
97
133
|
declare: true,
|
|
98
134
|
ty: None,
|
|
99
135
|
}));
|
|
100
136
|
stmts.extend(desugarAssertStmts(&t.body.stmts, &mut counter));
|
|
101
|
-
stmts.push(crate::ast::Stmt::Expr(
|
|
137
|
+
stmts.push(crate::ast::Stmt::Expr(reportField(), 0, 0));
|
|
102
|
-
crate::ast::Expr::Var("__report".to_string()),
|
|
103
|
-
0,
|
|
104
|
-
0,
|
|
105
|
-
));
|
|
106
138
|
|
|
107
139
|
items.push(crate::ast::Item::Fn(crate::ast::Fn {
|
|
108
140
|
file: source.file.clone(),
|
|
@@ -128,6 +160,9 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
|
|
|
128
160
|
other => items.push(other.clone()),
|
|
129
161
|
}
|
|
130
162
|
}
|
|
163
|
+
if test_idx > 0 {
|
|
164
|
+
items.push(reportStruct());
|
|
165
|
+
}
|
|
131
166
|
(
|
|
132
167
|
crate::ast::Source {
|
|
133
168
|
file: source.file.clone(),
|
|
@@ -183,10 +218,10 @@ fn desugarAssertStmt(stmt: &crate::ast::Stmt, counter: &mut usize) -> Vec<crate:
|
|
|
183
218
|
}
|
|
184
219
|
let appendReport = crate::ast::Stmt::Assign(crate::ast::Assign {
|
|
185
220
|
isSynthetic: false,
|
|
186
|
-
targets: vec![crate::ast::AssignTarget::Var("__report".to_string())],
|
|
221
|
+
targets: vec![crate::ast::AssignTarget::Field(Box::new(crate::ast::Expr::Var("__report".to_string())), REPORT_FIELD.to_string())],
|
|
187
222
|
values: vec![crate::ast::Expr::Binary(Box::new(crate::ast::BinaryExpr {
|
|
188
223
|
op: crate::ast::BinOp::Add,
|
|
189
|
-
left:
|
|
224
|
+
left: reportField(),
|
|
190
225
|
right: assertFailureMessage(c, &lhs, &rhs),
|
|
191
226
|
}))],
|
|
192
227
|
declare: false,
|
|
@@ -221,18 +256,14 @@ fn desugarAssertStmt(stmt: &crate::ast::Stmt, counter: &mut usize) -> Vec<crate:
|
|
|
221
256
|
stmts: desugarAssertStmts(&b.stmts, counter),
|
|
222
257
|
}),
|
|
223
258
|
})],
|
|
259
|
+
// A loop is a call that holds its body in a closure (see `forms::loopOf`).
|
|
224
|
-
crate::ast::StmtKind::
|
|
260
|
+
crate::ast::StmtKind::Expr(..) if crate::forms::loopOf(stmt).is_some() => {
|
|
225
|
-
|
|
261
|
+
let mut lp = stmt.clone();
|
|
226
|
-
body
|
|
262
|
+
if let Some(body) = crate::forms::loopBlockMut(&mut lp) {
|
|
227
|
-
stmts
|
|
263
|
+
body.stmts = desugarAssertStmts(&body.stmts, counter);
|
|
228
|
-
}
|
|
264
|
+
}
|
|
229
|
-
|
|
265
|
+
vec![lp]
|
|
230
|
-
crate::ast::StmtKind::ForLoop(f) => vec![crate::ast::Stmt::ForLoop(crate::ast::ForLoop {
|
|
231
|
-
body: crate::ast::Block {
|
|
232
|
-
stmts: desugarAssertStmts(&f.body.stmts, counter),
|
|
233
|
-
|
|
266
|
+
}
|
|
234
|
-
..f.clone()
|
|
235
|
-
})],
|
|
236
267
|
crate::ast::StmtKind::Match(m) => vec![crate::ast::Stmt::Match(crate::ast::Match {
|
|
237
268
|
subjects: m.subjects.clone(),
|
|
238
269
|
cases: m
|
compiler/core/src/trmc.rs
CHANGED
|
@@ -233,7 +233,7 @@ fn declare(n: &str, ty: Option<Type>, e: Expr) -> Stmt {
|
|
|
233
233
|
|
|
234
234
|
fn set(n: &str, e: Expr) -> Stmt {
|
|
235
235
|
Stmt::Assign(Assign {
|
|
236
|
-
isSynthetic:
|
|
236
|
+
isSynthetic: true,
|
|
237
237
|
targets: vec![AssignTarget::Var(n.to_string())],
|
|
238
238
|
values: vec![e],
|
|
239
239
|
declare: false,
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -26,14 +26,6 @@
|
|
|
26
26
|
//! methods; never returned, stored, passed on or captured) does not block a receiver. What
|
|
27
27
|
//! it returns of `self`'s fields is the field analysis' business, not the receiver's.
|
|
28
28
|
//!
|
|
29
|
-
//! * `Array.with` is a copy unless a call is marked `FnCall.unique` (the checker then runs
|
|
30
|
-
//! `Array.withUnique`, which writes `self`). A call is marked when its receiver is unshared
|
|
31
|
-
//! and dead afterwards: a fresh array (`Array.with`, `push`, `resize`, `init`, `filled` count
|
|
32
|
-
//! as fresh), a unique local or parameter the call consumes (`v = v.with(..)`, or the returned
|
|
33
|
-
//! value), a unique field rebuilt by `x.f = x.f.with(..)`, or `T(..s, f: s.f.with(..))` of a
|
|
34
|
-
//! proved `s`, provided no other field of the spread touches `s` except by plain reads of
|
|
35
|
-
//! other fields (a method call or closure on `s` could read `s.f` after the write).
|
|
36
|
-
//!
|
|
37
29
|
//! * Methods the compiler calls without a visible call site (`IMPLICIT`: interpolation, hashing,
|
|
38
30
|
//! operators) are never proved: their callers are unknown.
|
|
39
31
|
//!
|
|
@@ -48,17 +40,17 @@ use std::collections::{HashMap, HashSet};
|
|
|
48
40
|
pub struct UniqueReport {
|
|
49
41
|
pub proved: Vec<String>,
|
|
50
42
|
pub unproved: Vec<(String, String)>,
|
|
51
|
-
/// A verdict per spread
|
|
43
|
+
/// A verdict per spread inside a `fip fun` (empty when there is none).
|
|
52
44
|
pub fipSites: Vec<SiteVerdict>,
|
|
53
45
|
}
|
|
54
46
|
|
|
55
|
-
/// One spread
|
|
47
|
+
/// One spread of a `fip fun`, and whether it was proved in place.
|
|
56
48
|
#[derive(Debug, Clone)]
|
|
57
49
|
pub struct SiteVerdict {
|
|
58
50
|
/// Index of the fn in `Source.items`.
|
|
59
51
|
pub itemIdx: usize,
|
|
60
52
|
pub span: Span,
|
|
61
|
-
/// `"spread"`
|
|
53
|
+
/// `"spread"`.
|
|
62
54
|
pub what: &'static str,
|
|
63
55
|
/// `Err` carries the reason in plain words.
|
|
64
56
|
pub result: Result<(), String>,
|
|
@@ -104,10 +96,6 @@ pub(crate) fn walkStmt<'a>(s: &'a Stmt, f: Visit<'a, '_>) {
|
|
|
104
96
|
}
|
|
105
97
|
}
|
|
106
98
|
StmtKind::Assert(c) => walkExpr(&c.cond, f),
|
|
107
|
-
StmtKind::ForLoop(l) => {
|
|
108
|
-
walkExpr(&l.source, f);
|
|
109
|
-
walkBlock(&l.body, f);
|
|
110
|
-
}
|
|
111
99
|
StmtKind::While(w) => {
|
|
112
100
|
walkExpr(&w.condition, f);
|
|
113
101
|
walkBlock(&w.body, f);
|
|
@@ -135,7 +123,7 @@ pub(crate) fn walkStmt<'a>(s: &'a Stmt, f: Visit<'a, '_>) {
|
|
|
135
123
|
}
|
|
136
124
|
}
|
|
137
125
|
StmtKind::Return(Some(e)) | StmtKind::Crash(e) | StmtKind::Expr(e, _, _) => walkExpr(e, f),
|
|
138
|
-
StmtKind::Return(None) | StmtKind::
|
|
126
|
+
StmtKind::Return(None) | StmtKind::Todo => {}
|
|
139
127
|
}
|
|
140
128
|
}
|
|
141
129
|
|
|
@@ -231,10 +219,6 @@ fn mutStmt(s: &mut Stmt, f: &mut dyn FnMut(&mut Expr)) {
|
|
|
231
219
|
}
|
|
232
220
|
}
|
|
233
221
|
StmtKind::Assert(c) => mutExpr(&mut c.cond, f),
|
|
234
|
-
StmtKind::ForLoop(l) => {
|
|
235
|
-
mutExpr(&mut l.source, f);
|
|
236
|
-
mutBlock(&mut l.body, f);
|
|
237
|
-
}
|
|
238
222
|
StmtKind::While(w) => {
|
|
239
223
|
mutExpr(&mut w.condition, f);
|
|
240
224
|
mutBlock(&mut w.body, f);
|
|
@@ -262,7 +246,7 @@ fn mutStmt(s: &mut Stmt, f: &mut dyn FnMut(&mut Expr)) {
|
|
|
262
246
|
}
|
|
263
247
|
}
|
|
264
248
|
StmtKind::Return(Some(e)) | StmtKind::Crash(e) | StmtKind::Expr(e, _, _) => mutExpr(e, f),
|
|
265
|
-
StmtKind::Return(None) | StmtKind::
|
|
249
|
+
StmtKind::Return(None) | StmtKind::Todo => {}
|
|
266
250
|
}
|
|
267
251
|
}
|
|
268
252
|
|
|
@@ -378,9 +362,6 @@ struct Site {
|
|
|
378
362
|
args: Vec<Option<Expr>>,
|
|
379
363
|
assignBack: Option<AssignTarget>,
|
|
380
364
|
inClosure: bool,
|
|
381
|
-
/// The call expression's id, and whether it is in tail position of its unit.
|
|
382
|
-
node: NodeId,
|
|
383
|
-
tail: bool,
|
|
384
365
|
}
|
|
385
366
|
|
|
386
367
|
pub(crate) fn isVar(e: &Expr, v: &str) -> bool {
|
|
@@ -431,20 +412,8 @@ struct An {
|
|
|
431
412
|
/// Methods whose `self` is only read: used as the object of field reads and field writes, or
|
|
432
413
|
/// as the receiver of other such methods, never returned, stored, passed on or captured.
|
|
433
414
|
ro: HashSet<usize>,
|
|
434
|
-
/// `Array.with` (the only unit a marked `with` call runs; its copying body is the default).
|
|
435
|
-
arrayWith: HashSet<usize>,
|
|
436
|
-
/// `Array` methods that always return a new array
|
|
415
|
+
/// `Array` methods that always return a new array.
|
|
437
416
|
arrayFresh: HashSet<usize>,
|
|
438
|
-
/// `T(..s, f: s.f.with(..))`, by the id of the `with` call.
|
|
439
|
-
spreadWith: HashMap<NodeId, SpreadWith>,
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
struct SpreadWith {
|
|
443
|
-
unit: usize,
|
|
444
|
-
var: String,
|
|
445
|
-
field: String,
|
|
446
|
-
/// No other field value of the spread reads `s.f`, so the write cannot be observed early.
|
|
447
|
-
clean: bool,
|
|
448
417
|
}
|
|
449
418
|
|
|
450
419
|
struct SpreadSite {
|
|
@@ -453,9 +422,6 @@ struct SpreadSite {
|
|
|
453
422
|
typeName: String,
|
|
454
423
|
var: Option<String>,
|
|
455
424
|
given: Vec<String>,
|
|
456
|
-
/// Given fields whose value is a call returning (one of) its own parameters, fed from the
|
|
457
|
-
/// source's own field: they alias the source's field unless the spread is proved.
|
|
458
|
-
passGiven: Vec<String>,
|
|
459
425
|
}
|
|
460
426
|
|
|
461
427
|
pub(crate) fn collectTails<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) -> bool {
|
|
@@ -585,8 +551,8 @@ impl An {
|
|
|
585
551
|
/// Is parameter `j` of `g` unique and never stored or aliased inside `g`? For the receiver of a
|
|
586
552
|
/// method, whose callers are found by name alone (a call `x.m()` counts as a call of every
|
|
587
553
|
/// `m`, whatever `x`'s type), only this call's own argument matters: it is fresh or the
|
|
588
|
-
/// variable being rebound. A shared
|
|
554
|
+
/// variable being rebound. A shared receiver of the same method name elsewhere must not stop a
|
|
589
|
-
///
|
|
555
|
+
/// harmless pass-through here (`Map.with` returns its receiver).
|
|
590
556
|
fn passParamOk(&self, g: usize, j: usize) -> bool {
|
|
591
557
|
let u = &self.units[g];
|
|
592
558
|
let receiver = u.method && u.hasSelf && j == 0;
|
|
@@ -622,11 +588,6 @@ impl An {
|
|
|
622
588
|
}
|
|
623
589
|
|
|
624
590
|
fn paramUnique(&self, g: usize, j: usize) -> bool {
|
|
625
|
-
// `Array.with` copies unless a call is marked, and a call is marked only by its own proof:
|
|
626
|
-
// its receiver is always acceptable, the index and the value (stored) never are.
|
|
627
|
-
if self.arrayWith.contains(&g) {
|
|
628
|
-
return j == 0;
|
|
629
|
-
}
|
|
630
591
|
self.units[g].params.get(j).is_some() && self.up.borrow().contains(&(g, j))
|
|
631
592
|
}
|
|
632
593
|
|
|
@@ -689,50 +650,6 @@ impl An {
|
|
|
689
650
|
Ok(())
|
|
690
651
|
}
|
|
691
652
|
|
|
692
|
-
/// May this `Array.with` call write its receiver in place? The receiver must be unshared and
|
|
693
|
-
/// dead afterwards: a fresh array, a unique local or parameter that the call consumes (the
|
|
694
|
-
/// value returned, or rebound by `v = v.with(..)`), the field of a unique field rebuilt by
|
|
695
|
-
/// `x.f = x.f.with(..)`, or `T(..s, f: s.f.with(..))` of a unique `s`.
|
|
696
|
-
fn withOk(&self, site: &Site) -> Result<(), String> {
|
|
697
|
-
if site.inClosure {
|
|
698
|
-
return Err("the update is inside a closure".to_string());
|
|
699
|
-
}
|
|
700
|
-
let Some(Some(recv)) = site.args.first() else { return Err("no receiver".to_string()) };
|
|
701
|
-
if self.fresh(recv) {
|
|
702
|
-
return Ok(());
|
|
703
|
-
}
|
|
704
|
-
match &recv.kind {
|
|
705
|
-
ExprKind::Var(_) | ExprKind::Self_ => {
|
|
706
|
-
let v = varName(recv).unwrap_or("");
|
|
707
|
-
self.varOk(site.caller, v)?;
|
|
708
|
-
let consumed = site.tail || matches!(&site.assignBack, Some(AssignTarget::Var(t)) if t == v);
|
|
709
|
-
if consumed {
|
|
710
|
-
Ok(())
|
|
711
|
-
} else {
|
|
712
|
-
Err(format!("`{v}` is read after the update"))
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
ExprKind::Attribute(a) => {
|
|
716
|
-
let AttrKind::Field(f) = &a.attr else { return Err("the receiver is a method result".to_string()) };
|
|
717
|
-
match self.spreadWith.get(&site.node) {
|
|
718
|
-
Some(sw) => {
|
|
719
|
-
if !sw.clean {
|
|
720
|
-
return Err(format!("another field of the spread reads `{f}`"));
|
|
721
|
-
}
|
|
722
|
-
self.varOk(sw.unit, &sw.var)?;
|
|
723
|
-
if self.uf.borrow().contains(&sw.field) {
|
|
724
|
-
Ok(())
|
|
725
|
-
} else {
|
|
726
|
-
Err(format!("field `{f}` may be shared"))
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
None => self.argOk(site, recv),
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
_ => Err("the array may be held elsewhere".to_string()),
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
|
|
736
653
|
fn spreadProved(&self, s: &SpreadSite) -> bool {
|
|
737
654
|
match &s.var {
|
|
738
655
|
Some(v) => self.varOk(s.unit, v).is_ok(),
|
|
@@ -930,8 +847,7 @@ impl<'a> Scan<'a> {
|
|
|
930
847
|
self.block(&c.body, tail, depth + 1);
|
|
931
848
|
}
|
|
932
849
|
}
|
|
933
|
-
StmtKind::ForLoop(_) => self.fail("unlowered for loop".to_string()),
|
|
934
|
-
StmtKind::Return(None) | StmtKind::
|
|
850
|
+
StmtKind::Return(None) | StmtKind::Todo => {}
|
|
935
851
|
}
|
|
936
852
|
}
|
|
937
853
|
|
|
@@ -1124,26 +1040,6 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
|
|
|
1124
1040
|
}
|
|
1125
1041
|
}
|
|
1126
1042
|
}
|
|
1127
|
-
// `Array.with` calls whose receiver is proved unique and dead afterwards.
|
|
1128
|
-
let mut withMarks: HashSet<NodeId> = HashSet::new();
|
|
1129
|
-
for site in an.sites.iter().filter(|s| an.arrayWith.contains(&s.callee)) {
|
|
1130
|
-
let u = &an.units[site.caller];
|
|
1131
|
-
if u.kind == Kind::Const {
|
|
1132
|
-
continue;
|
|
1133
|
-
}
|
|
1134
|
-
let label = format!("{}:{} (array write)", u.label, lineOf(src, u));
|
|
1135
|
-
let verdict = an.withOk(site);
|
|
1136
|
-
match &verdict {
|
|
1137
|
-
Ok(()) => {
|
|
1138
|
-
withMarks.insert(site.node);
|
|
1139
|
-
report.proved.push(label);
|
|
1140
|
-
}
|
|
1141
|
-
Err(r) => report.unproved.push((label, r.clone())),
|
|
1142
|
-
}
|
|
1143
|
-
if isFip(site.caller) {
|
|
1144
|
-
verdicts.push((site.caller, site.node, "Array.with", verdict));
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
1043
|
// Mutable pass.
|
|
1148
1044
|
for (ui, u) in an.units.iter().enumerate() {
|
|
1149
1045
|
if u.kind == Kind::Const {
|
|
@@ -1153,14 +1049,6 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
|
|
|
1153
1049
|
let mut spans: HashMap<NodeId, Span> = HashMap::new();
|
|
1154
1050
|
let mut mark = |e: &mut Expr| {
|
|
1155
1051
|
spans.insert(e.id, e.span);
|
|
1156
|
-
if withMarks.contains(&e.id) {
|
|
1157
|
-
if let ExprKind::Attribute(a) = &mut e.kind {
|
|
1158
|
-
if let AttrKind::Method(c) = &mut a.attr {
|
|
1159
|
-
c.unique = true;
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
return;
|
|
1163
|
-
}
|
|
1164
1052
|
let ExprKind::ClassCall(c) = &mut e.kind else { return };
|
|
1165
1053
|
if let Some(s) = &c.spread {
|
|
1166
1054
|
if let Some(v) = varName(s) {
|
|
@@ -1329,7 +1217,6 @@ fn build(src: &Source) -> An {
|
|
|
1329
1217
|
pats(&c.patterns, &mut bound);
|
|
1330
1218
|
}
|
|
1331
1219
|
}
|
|
1332
|
-
Node::S(Stmt { kind: StmtKind::ForLoop(l), .. }) => found.extend(l.binders.iter().cloned()),
|
|
1333
1220
|
Node::E(Expr { kind: ExprKind::Closure(c), .. }) => found.extend(c.params.iter().cloned()),
|
|
1334
1221
|
Node::E(Expr { kind: ExprKind::Bind(b), .. }) => pats(&b.case.patterns, &mut bound),
|
|
1335
1222
|
_ => {}
|
|
@@ -1370,17 +1257,11 @@ fn build(src: &Source) -> An {
|
|
|
1370
1257
|
poisonAll: false,
|
|
1371
1258
|
spreads: vec![],
|
|
1372
1259
|
ro: HashSet::new(),
|
|
1373
|
-
arrayWith: HashSet::new(),
|
|
1374
1260
|
arrayFresh: HashSet::new(),
|
|
1375
|
-
spreadWith: HashMap::new(),
|
|
1376
1261
|
};
|
|
1377
1262
|
for (i, u) in an.units.iter().enumerate() {
|
|
1378
1263
|
match u.label.as_str() {
|
|
1379
|
-
"Array.with" => {
|
|
1380
|
-
an.arrayWith.insert(i);
|
|
1381
|
-
an.arrayFresh.insert(i);
|
|
1382
|
-
}
|
|
1383
|
-
"Array.
|
|
1264
|
+
"Array.push" | "Array.resize" | "Array.init" | "Array.filled" => {
|
|
1384
1265
|
an.arrayFresh.insert(i);
|
|
1385
1266
|
}
|
|
1386
1267
|
_ => {}
|
|
@@ -1470,39 +1351,6 @@ fn nodeKey(id: NodeId) -> NodeId {
|
|
|
1470
1351
|
id
|
|
1471
1352
|
}
|
|
1472
1353
|
|
|
1473
|
-
/// Is `e` the field read `s.f` of the variable `s`?
|
|
1474
|
-
fn isFieldOf(e: &Expr, s: &str, f: &str) -> bool {
|
|
1475
|
-
matches!(&e.kind, ExprKind::Attribute(x) if x.attr == AttrKind::Field(f.to_string()) && isVar(&x.object, s))
|
|
1476
|
-
}
|
|
1477
|
-
|
|
1478
|
-
/// `s.f.with(..)`: the receiver `s.f` (and nothing else may be the call's object).
|
|
1479
|
-
fn rebuiltFromItself<'a>(value: &'a Expr, s: &str, f: &str) -> Option<&'a Expr> {
|
|
1480
|
-
let ExprKind::Attribute(x) = &value.kind else { return None };
|
|
1481
|
-
let AttrKind::Method(c) = &x.attr else { return None };
|
|
1482
|
-
(c.name == "with" && isFieldOf(&x.object, s, f)).then_some(&x.object)
|
|
1483
|
-
}
|
|
1484
|
-
|
|
1485
|
-
/// Does `e` touch `s` only through plain field reads `s.g` with `g != f`? Any other use of `s`
|
|
1486
|
-
/// (a method call, even a read-only one, an argument, a capture) may read `s.f` through the
|
|
1487
|
-
/// array another field of the spread has just written in place.
|
|
1488
|
-
fn readsOnlyOtherFields(e: &Expr, s: &str, f: &str) -> bool {
|
|
1489
|
-
let (mut uses, mut plain) = (0usize, 0usize);
|
|
1490
|
-
walkExpr(e, &mut |n| {
|
|
1491
|
-
if let Node::E(x) = n {
|
|
1492
|
-
if isVar(x, s) {
|
|
1493
|
-
uses += 1;
|
|
1494
|
-
}
|
|
1495
|
-
if let ExprKind::Attribute(a) = &x.kind {
|
|
1496
|
-
if matches!(&a.attr, AttrKind::Field(g) if g != f) && isVar(&a.object, s) {
|
|
1497
|
-
plain += 1;
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
true
|
|
1502
|
-
});
|
|
1503
|
-
uses == plain
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
1354
|
/// The methods whose `self` is only read (see `An.ro`): a greatest fixpoint, since a method may
|
|
1507
1355
|
/// call another read-only one on `self`.
|
|
1508
1356
|
fn readOnlySelf(an: &An) -> HashSet<usize> {
|
|
@@ -1573,21 +1421,8 @@ fn collectFacts(an: &mut An) {
|
|
|
1573
1421
|
let mut passWrites: Vec<(String, Vec<(usize, usize)>)> = vec![];
|
|
1574
1422
|
let mut reads: Vec<(NodeId, String)> = vec![];
|
|
1575
1423
|
let mut allowed: HashSet<NodeId> = HashSet::new();
|
|
1576
|
-
let mut spreadWith: HashMap<NodeId, SpreadWith> = HashMap::new();
|
|
1577
1424
|
let a: &An = an;
|
|
1578
1425
|
for (ui, u) in a.units.iter().enumerate() {
|
|
1579
|
-
let mut tailIds: HashSet<NodeId> = HashSet::new();
|
|
1580
|
-
{
|
|
1581
|
-
let mut tails: Vec<&Expr> = vec![];
|
|
1582
|
-
collectTails(&u.block, &mut tails);
|
|
1583
|
-
walkBlock(&u.block, &mut |n| {
|
|
1584
|
-
if let Node::S(Stmt { kind: StmtKind::Return(Some(e)), .. }) = n {
|
|
1585
|
-
tails.push(e);
|
|
1586
|
-
}
|
|
1587
|
-
true
|
|
1588
|
-
});
|
|
1589
|
-
tailIds.extend(tails.iter().map(|e| e.id));
|
|
1590
|
-
}
|
|
1591
1426
|
let mut abMap: HashMap<NodeId, AssignTarget> = HashMap::new();
|
|
1592
1427
|
let mut inClosure: HashSet<NodeId> = HashSet::new();
|
|
1593
1428
|
// First pass: assign-back targets and closure membership.
|
|
@@ -1725,8 +1560,6 @@ fn collectFacts(an: &mut An) {
|
|
|
1725
1560
|
ExprKind::ClassCall(cc) => {
|
|
1726
1561
|
let names = fieldsOf(&a.enums, &cc.type_name);
|
|
1727
1562
|
let mut given = vec![];
|
|
1728
|
-
let mut passGiven = vec![];
|
|
1729
|
-
let spreadVar = cc.spread.as_deref().and_then(varName);
|
|
1730
1563
|
for (k, fa) in cc.fields.iter().enumerate() {
|
|
1731
1564
|
let name = if fa.name.is_empty() {
|
|
1732
1565
|
names.as_ref().and_then(|n| n.get(k)).cloned()
|
|
@@ -1734,34 +1567,8 @@ fn collectFacts(an: &mut An) {
|
|
|
1734
1567
|
Some(fa.name.clone())
|
|
1735
1568
|
};
|
|
1736
1569
|
if let Some(nm) = name {
|
|
1737
|
-
// `T(..s, f: s.f.with(..))`: the field is rebuilt from itself.
|
|
1738
|
-
let sv = spreadVar.unwrap_or("");
|
|
1739
|
-
let rebuilt = spreadVar.and_then(|sv| rebuiltFromItself(&fa.value, sv, &nm));
|
|
1740
|
-
if let Some(recv) = rebuilt {
|
|
1741
|
-
allowed.insert(nodeKey(recv.id));
|
|
1742
|
-
// Only a spread of a unique source may write the array in place, and
|
|
1743
|
-
// no other field value may read `s.f` (it would see the write early).
|
|
1744
|
-
let clean = cc
|
|
1745
|
-
.fields
|
|
1746
|
-
.iter()
|
|
1747
|
-
.enumerate()
|
|
1748
|
-
.all(|(j, o)| j == k || readsOnlyOtherFields(&o.value, sv, &nm));
|
|
1749
|
-
spreadWith.insert(
|
|
1750
|
-
nodeKey(fa.value.id),
|
|
1751
|
-
SpreadWith { unit: ui, var: sv.to_string(), field: nm.clone(), clean },
|
|
1752
|
-
);
|
|
1753
|
-
}
|
|
1754
1570
|
if !a.fresh(&fa.value) {
|
|
1755
|
-
let same = |ae: &Expr| isFieldOf(ae, sv, &nm);
|
|
1756
|
-
match rebuilt.and_then(|_| a.passDeps(&fa.value, &same)) {
|
|
1757
|
-
Some(deps) => {
|
|
1758
|
-
passWrites.push((nm.clone(), deps));
|
|
1759
|
-
passGiven.push(nm.clone());
|
|
1760
|
-
}
|
|
1761
|
-
None => {
|
|
1762
|
-
|
|
1571
|
+
badField.insert(nm.clone());
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
1572
|
}
|
|
1766
1573
|
given.push(nm);
|
|
1767
1574
|
}
|
|
@@ -1773,7 +1580,6 @@ fn collectFacts(an: &mut An) {
|
|
|
1773
1580
|
typeName: cc.type_name.clone(),
|
|
1774
1581
|
var: varName(s).map(|v| v.to_string()),
|
|
1775
1582
|
given,
|
|
1776
|
-
passGiven,
|
|
1777
1583
|
});
|
|
1778
1584
|
}
|
|
1779
1585
|
}
|
|
@@ -1824,8 +1630,6 @@ fn collectFacts(an: &mut An) {
|
|
|
1824
1630
|
_ => true,
|
|
1825
1631
|
}),
|
|
1826
1632
|
inClosure: inClosure.contains(&nodeKey(e.id)),
|
|
1827
|
-
node: e.id,
|
|
1828
|
-
tail: tailIds.contains(&e.id),
|
|
1829
1633
|
});
|
|
1830
1634
|
}
|
|
1831
1635
|
// `x.f.m(..)` with every `m` reading its receiver only: `x.f` is not shared.
|
|
@@ -1894,8 +1698,6 @@ fn collectFacts(an: &mut An) {
|
|
|
1894
1698
|
_ => true,
|
|
1895
1699
|
}),
|
|
1896
1700
|
inClosure: inClosure.contains(&nodeKey(e.id)),
|
|
1897
|
-
node: e.id,
|
|
1898
|
-
tail: tailIds.contains(&e.id),
|
|
1899
1701
|
});
|
|
1900
1702
|
}
|
|
1901
1703
|
}
|
|
@@ -1926,7 +1728,6 @@ fn collectFacts(an: &mut An) {
|
|
|
1926
1728
|
an.poisonAll = poisonAll;
|
|
1927
1729
|
an.spreads = spreads;
|
|
1928
1730
|
an.passWrites = passWrites;
|
|
1929
|
-
an.spreadWith = spreadWith;
|
|
1930
1731
|
}
|
|
1931
1732
|
|
|
1932
1733
|
fn solve(an: &An) {
|
|
@@ -1995,7 +1796,6 @@ fn solve(an: &An) {
|
|
|
1995
1796
|
if an.spreadProved(s) {
|
|
1996
1797
|
continue;
|
|
1997
1798
|
}
|
|
1998
|
-
poisoned.extend(s.passGiven.iter().cloned());
|
|
1999
1799
|
match fieldsOf(&an.enums, &s.typeName) {
|
|
2000
1800
|
Some(all) => poisoned.extend(all.into_iter().filter(|f| !s.given.contains(f))),
|
|
2001
1801
|
None => {
|
compiler/core/src/visit.rs
CHANGED
|
@@ -120,7 +120,6 @@ pub fn stmtExprs(s: &mut Stmt) -> Vec<&mut Expr> {
|
|
|
120
120
|
StmtKind::Assert(c) => vec![&mut c.cond],
|
|
121
121
|
StmtKind::Crash(e) | StmtKind::Expr(e, ..) => vec![e],
|
|
122
122
|
StmtKind::Return(e) => e.iter_mut().collect(),
|
|
123
|
-
StmtKind::ForLoop(f) => vec![&mut f.source],
|
|
124
123
|
StmtKind::While(w) => vec![&mut w.condition],
|
|
125
124
|
StmtKind::If(i) => {
|
|
126
125
|
let mut v = vec![&mut i.condition];
|
|
@@ -132,13 +131,12 @@ pub fn stmtExprs(s: &mut Stmt) -> Vec<&mut Expr> {
|
|
|
132
131
|
v.extend(m.cases.iter_mut().filter_map(|c| c.guard.as_mut()));
|
|
133
132
|
v
|
|
134
133
|
}
|
|
135
|
-
StmtKind::
|
|
134
|
+
StmtKind::Todo => vec![],
|
|
136
135
|
}
|
|
137
136
|
}
|
|
138
137
|
|
|
139
138
|
pub fn stmtBlocks(s: &mut Stmt) -> Vec<&mut Block> {
|
|
140
139
|
match &mut s.kind {
|
|
141
|
-
StmtKind::ForLoop(f) => vec![&mut f.body],
|
|
142
140
|
StmtKind::While(w) => vec![&mut w.body],
|
|
143
141
|
StmtKind::If(i) => {
|
|
144
142
|
let mut v = vec![&mut i.body];
|
|
@@ -220,7 +218,6 @@ pub fn stmtExprRefs(s: &Stmt) -> Vec<&Expr> {
|
|
|
220
218
|
StmtKind::Assert(c) => vec![&c.cond],
|
|
221
219
|
StmtKind::Crash(e) | StmtKind::Expr(e, ..) => vec![e],
|
|
222
220
|
StmtKind::Return(e) => e.iter().collect(),
|
|
223
|
-
StmtKind::ForLoop(f) => vec![&f.source],
|
|
224
221
|
StmtKind::While(w) => vec![&w.condition],
|
|
225
222
|
StmtKind::If(i) => {
|
|
226
223
|
let mut v = vec![&i.condition];
|
|
@@ -232,13 +229,12 @@ pub fn stmtExprRefs(s: &Stmt) -> Vec<&Expr> {
|
|
|
232
229
|
v.extend(m.cases.iter().filter_map(|c| c.guard.as_ref()));
|
|
233
230
|
v
|
|
234
231
|
}
|
|
235
|
-
StmtKind::
|
|
232
|
+
StmtKind::Todo => vec![],
|
|
236
233
|
}
|
|
237
234
|
}
|
|
238
235
|
|
|
239
236
|
pub fn stmtBlockRefs(s: &Stmt) -> Vec<&Block> {
|
|
240
237
|
match &s.kind {
|
|
241
|
-
StmtKind::ForLoop(f) => vec![&f.body],
|
|
242
238
|
StmtKind::While(w) => vec![&w.body],
|
|
243
239
|
StmtKind::If(i) => {
|
|
244
240
|
let mut v = vec![&i.body];
|
compiler/core/tests/core/closure_spec_test.rs
CHANGED
|
@@ -403,41 +403,6 @@ fn many_call_sites_capped() {
|
|
|
403
403
|
assert_eq!(runIntBytes(&bytes), 1240);
|
|
404
404
|
}
|
|
405
405
|
|
|
406
|
-
#[test]
|
|
407
|
-
fn capture_read_after_mutation() {
|
|
408
|
-
// The closure reads `k` when it runs; `k` was reassigned before the call. A plain
|
|
409
|
-
// closure held in a local (not specialised) created at the same point must agree
|
|
410
|
-
// with the specialised call, and the value is the reassigned one.
|
|
411
|
-
let spec = withHead(
|
|
412
|
-
"fun main() -> Int =\n xs := [1, 2, 3]\n k := 1\n k = 10\n a := xs.map(|x| x + k).fold(0, |a, x| a + x)\n k = 100\n b := xs.map(|x| x + k).fold(0, |a, x| a + x)\n return a * 1000 + b\n",
|
|
413
|
-
);
|
|
414
|
-
let plain = withHead(
|
|
415
|
-
"fun main() -> Int =\n xs := [1, 2, 3]\n k := 1\n k = 10\n m := |x| x + k\n s := |a, x| a + x\n a := xs.map(m).fold(0, s)\n k = 100\n m2 := |x| x + k\n b := xs.map(m2).fold(0, s)\n return a * 1000 + b\n",
|
|
416
|
-
);
|
|
417
|
-
assert!(!userCopies("capmut", &spec).is_empty());
|
|
418
|
-
assert!(userCopies("capmut_plain", &plain).is_empty());
|
|
419
|
-
let r = runInt("capmut", &spec);
|
|
420
|
-
assert_eq!(r, runInt("capmut_plain", &plain));
|
|
421
|
-
assert_eq!(r, 36 * 1000 + 306);
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
#[test]
|
|
425
|
-
fn capture_reassigned_between_closure_and_call() {
|
|
426
|
-
// A closure local created BEFORE the reassignment is not a direct argument, so it is
|
|
427
|
-
// never specialised. Record what plain closures do (value at creation vs at call) and
|
|
428
|
-
// check the direct-argument (specialised) form sees the reassigned value.
|
|
429
|
-
let held = withHead(
|
|
430
|
-
"fun main() -> Int =\n xs := [1, 2, 3]\n k := 1\n m := |x| x + k\n k = 10\n return xs.map(m).fold(0, |a, x| a + x)\n",
|
|
431
|
-
);
|
|
432
|
-
let direct = withHead(
|
|
433
|
-
"fun main() -> Int =\n xs := [1, 2, 3]\n k := 1\n k = 10\n return xs.map(|x| x + k).fold(0, |a, x| a + x)\n",
|
|
434
|
-
);
|
|
435
|
-
let heldResult = runInt("held", &held);
|
|
436
|
-
assert_eq!(runInt("direct", &direct), 36);
|
|
437
|
-
eprintln!("closure created before reassignment gives {heldResult} (9 = captured by value, 36 = by reference)");
|
|
438
|
-
assert!(heldResult == 9 || heldResult == 36, "held closure gave {heldResult}");
|
|
439
|
-
}
|
|
440
|
-
|
|
441
406
|
#[test]
|
|
442
407
|
fn pattern_decl() {
|
|
443
408
|
// A name bound by a pattern inside the closure is the closure's own binder, not a capture
|
compiler/core/tests/core/drive_test.rs
CHANGED
|
@@ -410,8 +410,7 @@ fun frame(io: Io, x: Int) =
|
|
|
410
410
|
fn block_bodied_producer_not_fused_note() {
|
|
411
411
|
let (s, notes) = run(
|
|
412
412
|
"fun mapB(xs: Lst) -> Lst =
|
|
413
|
-
for i := range 1
|
|
414
|
-
|
|
413
|
+
0
|
|
415
414
|
match xs
|
|
416
415
|
Nil => Nil
|
|
417
416
|
Cons(h, t) => Cons(head: h * 2, tail: mapB(t))
|
compiler/core/tests/core/formatter_test.rs
CHANGED
|
@@ -155,33 +155,6 @@ fun describeNumber(n: Int) -> Str =
|
|
|
155
155
|
assert_eq!(once, twice, "formatting should be idempotent");
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
-
/// A multi-statement (or `return`-statement) case body is NOT collapsed —
|
|
159
|
-
/// only `return expr`/`if`/etc. are valid there, never a bare bracket-free
|
|
160
|
-
/// `expression`, which is the only thing the inline form's grammar accepts.
|
|
161
|
-
#[test]
|
|
162
|
-
fn doesNotCollapseMultiStatementOrReturnOnlyMatchCaseBodies() {
|
|
163
|
-
let input = "\
|
|
164
|
-
fun f(n: Int) -> Int =
|
|
165
|
-
match n
|
|
166
|
-
0 =>
|
|
167
|
-
x := 1
|
|
168
|
-
x + 1
|
|
169
|
-
_ =>
|
|
170
|
-
return n
|
|
171
|
-
";
|
|
172
|
-
let once = formatSource(input).expect("first pass");
|
|
173
|
-
assert!(once.contains("x := 1"), "got: {once}");
|
|
174
|
-
assert!(once.contains("return n"), "got: {once}");
|
|
175
|
-
assert!(
|
|
176
|
-
!once.contains("0 => x"),
|
|
177
|
-
"should not have collapsed a multi-statement body: {once}"
|
|
178
|
-
);
|
|
179
|
-
assert!(
|
|
180
|
-
!once.contains("_ => return n"),
|
|
181
|
-
"should not have collapsed a return-statement body: {once}"
|
|
182
|
-
);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
158
|
#[test]
|
|
186
159
|
fn formatsBindCrashAndQuestion() {
|
|
187
160
|
let input = "fun f(a: Int,b: Int) -> Int =\n x := g()?+1\n if z:=a\n z\n crash\"boom\"\n";
|
compiler/core/tests/core/forms_list_range_test.rs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#![allow(non_snake_case)]
|
|
2
|
-
//! `for x := range xs` over a type with `next(self) -> Pair[T, Self]?`
|
|
2
|
+
//! `for x := range xs` over a type with `next(self) -> Pair[T, Self]?` is checked as a
|
|
3
|
-
//! `
|
|
3
|
+
//! `if step := it.next()` (no per-element `at(i)`); an `Int` counts.
|
|
4
4
|
use plum_core::ast::*;
|
|
5
5
|
use plum_core::forms::{self, TyInfo};
|
|
6
6
|
use plum_core::AstParser;
|
|
@@ -23,15 +23,20 @@ fn lowered(name: &str, methods: &[&str]) -> String {
|
|
|
23
23
|
_ => None,
|
|
24
24
|
}).unwrap();
|
|
25
25
|
let FnBody::Block(b) = &main.body else { panic!() };
|
|
26
|
-
let
|
|
26
|
+
let fl = forms::loopOf(&b.stmts[0]).expect("for");
|
|
27
27
|
let typeOf = |_: &Expr| Some(TyInfo {
|
|
28
28
|
name: name.into(),
|
|
29
29
|
iterable: true,
|
|
30
30
|
methods: methods.iter().map(|m| m.to_string()).collect(),
|
|
31
31
|
});
|
|
32
|
+
let info = typeOf(&Expr::Int(0));
|
|
32
|
-
let
|
|
33
|
+
let checked = format!("{:?}", forms::lowerLoop(&fl, &typeOf));
|
|
34
|
+
// What the lifted function does is what runs: no steps are lost to the checking form.
|
|
35
|
+
let ty = Type { name: name.into(), generics: vec![] };
|
|
36
|
+
let kind = forms::iterKind(info.as_ref(), Some(ty)).expect("a kind");
|
|
37
|
+
forms::recordLift(fl.id, forms::Lift { generics: vec![], params: vec![], kind });
|
|
33
|
-
forms::finish(&source);
|
|
38
|
+
let lifted = forms::finish(&source);
|
|
34
|
-
|
|
39
|
+
format!("{checked}\n{:?}", lifted.items)
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
#[test]
|
|
@@ -53,5 +58,5 @@ fn iterable_without_next_uses_at() {
|
|
|
53
58
|
fn int_counts() {
|
|
54
59
|
let s = lowered("Int", &[]);
|
|
55
60
|
assert!(!s.contains("\"next\"") && !s.contains("\"at\""), "{s}");
|
|
56
|
-
assert!(s.contains("Lt"), "{s}");
|
|
61
|
+
assert!(s.contains("__for_n") && s.contains("Lt"), "{s}");
|
|
57
62
|
}
|
compiler/core/tests/core/loader_test.rs
CHANGED
|
@@ -226,6 +226,12 @@ fn diagnosticsShowTheSourceNameOfARenamedDefinition() {
|
|
|
226
226
|
assert_eq!(plum_core::diag::sourceName("fn 'clamp@mathx': bad; also [email protected] and x @ y"), "fn 'clamp': bad; also a.c and x @ y");
|
|
227
227
|
}
|
|
228
228
|
|
|
229
|
+
#[test]
|
|
230
|
+
fn aMessageAboutALiftedLoopNamesTheFunctionItIsIn() {
|
|
231
|
+
let lifted = plum_core::forms::liftedName(3, "countdown");
|
|
232
|
+
assert_eq!(plum_core::diag::sourceName(&format!("fn '{lifted}': bad")), "fn 'countdown': bad");
|
|
233
|
+
}
|
|
234
|
+
|
|
229
235
|
#[test]
|
|
230
236
|
fn sameMethodNameOnDifferentReceiversAcrossFilesIsNotACollision() {
|
|
231
237
|
let dir = TempDir::new().unwrap();
|
|
@@ -312,7 +318,7 @@ fn parseErrorBlamesTheTokenNotTheWholeFunction() {
|
|
|
312
318
|
"{err}"
|
|
313
319
|
);
|
|
314
320
|
assert!(
|
|
315
|
-
err.contains("hint:") && err.contains("
|
|
321
|
+
err.contains("hint:") && err.contains("`todo`"),
|
|
316
322
|
"{err}"
|
|
317
323
|
);
|
|
318
324
|
assert!(!err.contains("export fun"), "{err}");
|
|
@@ -664,3 +670,13 @@ fn std_means_under_the_lib_path_std_dir_only() {
|
|
|
664
670
|
fs::write(&fake, body).unwrap();
|
|
665
671
|
assert!(loadAndMergeDiag(&fake, lib.path()).is_err());
|
|
666
672
|
}
|
|
673
|
+
|
|
674
|
+
#[test]
|
|
675
|
+
fn returnBreakAndContinueAreParseErrors() {
|
|
676
|
+
let err = parseErrorOf("import std/Int\n\nfun f(a: Int) -> Int =\n return a\n");
|
|
677
|
+
assert!(err.contains(":4:3:") && err.contains("`return` is gone"), "{err}");
|
|
678
|
+
let err = parseErrorOf("import std/Int\n\nfun f(n: Int) =\n for i := range n\n break\n");
|
|
679
|
+
assert!(err.contains(":5:5:") && err.contains("`break` is gone"), "{err}");
|
|
680
|
+
let err = parseErrorOf("import std/Int\n\nfun f(n: Int) =\n for i := range n\n continue\n");
|
|
681
|
+
assert!(err.contains(":5:5:") && err.contains("`continue` is gone"), "{err}");
|
|
682
|
+
}
|
compiler/core/tests/core/parser_test.rs
CHANGED
|
@@ -209,12 +209,10 @@ fn if_and_while_bindings_parse() {
|
|
|
209
209
|
),
|
|
210
210
|
other => panic!("got {:?}", other),
|
|
211
211
|
}
|
|
212
|
-
match &b.stmts[1] {
|
|
213
|
-
|
|
212
|
+
let w = plum_core::forms::loopOf(&b.stmts[1]).expect("a while");
|
|
213
|
+
assert!(
|
|
214
|
-
|
|
214
|
+
matches!(&w.cond, Some(Expr { kind: ExprKind::Bind(bd), .. }) if matches!(bd.pattern(), CasePattern::Name(n) if n.starts_with("y__b")))
|
|
215
|
-
|
|
215
|
+
);
|
|
216
|
-
other => panic!("got {:?}", other),
|
|
217
|
-
}
|
|
218
216
|
}
|
|
219
217
|
|
|
220
218
|
#[test]
|
|
@@ -762,7 +760,6 @@ fn annotatedDeclarationTypes() {
|
|
|
762
760
|
#[test]
|
|
763
761
|
fn plainAssignmentsHaveNoType() {
|
|
764
762
|
assert!(firstAssign("fun f() =\n x := 1\n").ty.is_none());
|
|
765
|
-
assert!(firstAssign("fun f() =\n x = 1\n").ty.is_none());
|
|
766
763
|
}
|
|
767
764
|
|
|
768
765
|
#[test]
|
compiler/core/tests/core/rename_test.rs
CHANGED
|
@@ -51,12 +51,6 @@ fn renamesDeclThenRef() {
|
|
|
51
51
|
assert!(matches!(&b.stmts[0], Stmt { kind: StmtKind::Assign(a), .. } if matches!(&a.targets[0], AssignTarget::Var(n) if n == "x2")));
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
#[test]
|
|
55
|
-
fn plainAssign() {
|
|
56
|
-
let ev = events("fun t() -> Int =\n x := 1\n x = 2\n return x\n");
|
|
57
|
-
assert!(ev.contains(&("x".into(), "plain")));
|
|
58
|
-
}
|
|
59
|
-
|
|
60
54
|
#[test]
|
|
61
55
|
fn patternNames() {
|
|
62
56
|
let ev = events("fun t(l: Int) -> Int = match l\n Cons(h, t) => h\n _ => 0\n");
|
compiler/core/tests/core/tail_test.rs
CHANGED
|
@@ -88,12 +88,6 @@ fn closure_value_call_tail() {
|
|
|
88
88
|
assert_eq!(sites(src, "f"), one("g", TailKind::Closure));
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
#[test]
|
|
92
|
-
fn return_expr_tail() {
|
|
93
|
-
let src = "fun f(n: Int) -> Int =\n if n > 3\n return f(n - 1)\n n\n";
|
|
94
|
-
assert_eq!(sites(src, "f"), one("f", TailKind::SelfCall));
|
|
95
|
-
}
|
|
96
|
-
|
|
97
91
|
#[test]
|
|
98
92
|
fn block_last_expr_tail() {
|
|
99
93
|
let src = "fun f(n: Int) -> Int =\n x := n + 1\n g(x)\n";
|
compiler/core/tests/core/uniqueness_test.rs
CHANGED
|
@@ -234,15 +234,6 @@ const CELL: &str = "struct Cell(label: Str, mut n: Int) =\n fun bumped(self) ->
|
|
|
234
234
|
fun touch(c: Cell) -> Cell =\n c.n = c.n + 1\n c\n\
|
|
235
235
|
struct Holder(mut c: Cell, tag: Int)\n";
|
|
236
236
|
|
|
237
|
-
#[test]
|
|
238
|
-
fn method_handed_over_in_a_while_loop_is_unique() {
|
|
239
|
-
let s = format!(
|
|
240
|
-
"{CELL}fun go() -> Cell =\n v := Cell(label: \"a\", n: 0)\n i := 0\n while i < 3\n v = v.bumped()\n i = i + 1\n v\n"
|
|
241
|
-
);
|
|
242
|
-
let (_, r) = run(&s);
|
|
243
|
-
assert!(provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
244
|
-
}
|
|
245
|
-
|
|
246
237
|
#[test]
|
|
247
238
|
fn method_handed_over_in_a_field_is_unique() {
|
|
248
239
|
let s = format!(
|
|
@@ -254,25 +245,6 @@ fn method_handed_over_in_a_field_is_unique() {
|
|
|
254
245
|
assert!(provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
255
246
|
}
|
|
256
247
|
|
|
257
|
-
#[test]
|
|
258
|
-
fn returned_parameter_is_fresh_for_a_unique_argument() {
|
|
259
|
-
let s = format!(
|
|
260
|
-
"{CELL}fun go() -> Cell =\n v := Cell(label: \"a\", n: 0)\n v = touch(v)\n bump(v)\n"
|
|
261
|
-
);
|
|
262
|
-
let (_, r) = run(&s);
|
|
263
|
-
assert!(provedFn(&r, "bump"), "{r:?}");
|
|
264
|
-
assert!(provedFn(&r, "touch") || !whyNot(&r, "touch").contains("shared"), "{r:?}");
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
#[test]
|
|
268
|
-
fn returned_parameter_in_a_loop_keeps_the_hand_over_unique() {
|
|
269
|
-
let s = format!(
|
|
270
|
-
"{CELL}fun go() -> Cell =\n v := Cell(label: \"a\", n: 0)\n i := 0\n while i < 3\n v = touch(v)\n v = bump(v)\n i = i + 1\n v\n"
|
|
271
|
-
);
|
|
272
|
-
let (_, r) = run(&s);
|
|
273
|
-
assert!(provedFn(&r, "bump"), "{r:?}");
|
|
274
|
-
}
|
|
275
|
-
|
|
276
248
|
#[test]
|
|
277
249
|
fn returned_parameter_in_a_field_keeps_the_field_unique() {
|
|
278
250
|
let s = format!(
|
|
@@ -295,37 +267,36 @@ fn returned_parameter_with_a_shared_argument_is_not_fresh() {
|
|
|
295
267
|
}
|
|
296
268
|
|
|
297
269
|
#[test]
|
|
298
|
-
fn
|
|
270
|
+
fn returned_parameter_in_a_field_that_was_stored_is_not_unique() {
|
|
299
271
|
let s = format!(
|
|
300
272
|
"{CELL}fun reg(xs: Slice[Cell], c: Cell) -> Cell =\n xs.push(c)\n c\n\
|
|
273
|
+
fun go(h: Holder, xs: Slice[Cell]) -> Holder =\n h.c = reg(xs, h.c)\n h.c = bump(h.c)\n h\n\
|
|
301
|
-
fun
|
|
274
|
+
fun mk() -> Holder = Holder(c: Cell(label: \"a\", n: 0), tag: 1)\n\
|
|
275
|
+
fun run(xs: Slice[Cell]) -> Holder =\n h := mk()\n go(h, xs)\n"
|
|
302
276
|
);
|
|
303
277
|
let (_, r) = run(&s);
|
|
304
278
|
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
305
279
|
}
|
|
306
280
|
|
|
307
281
|
#[test]
|
|
308
|
-
fn
|
|
282
|
+
fn recursion_keeping_the_previous_value_not_unique() {
|
|
309
283
|
let s = format!(
|
|
310
|
-
"{CELL}fun reg(xs: Slice[Cell], c: Cell) -> Cell =\n xs.push(c)\n c\n\
|
|
311
|
-
fun go(h: Holder, xs: Slice[Cell]) -> Holder =\n h.c = reg(xs, h.c)\n h.c = bump(h.c)\n h\n\
|
|
312
|
-
|
|
284
|
+
"{CELL}fun go(xs: Slice[Cell]) -> Cell =\n spin(xs, Cell(label: \"a\", n: 0), 0)\n\
|
|
313
|
-
fun
|
|
285
|
+
fun spin(xs: Slice[Cell], v: Cell, i: Int) -> Cell =\n if i < 3\n xs.push(v)\n spin(xs, v.bumped(), i + 1)\n else\n v\n"
|
|
314
286
|
);
|
|
315
287
|
let (_, r) = run(&s);
|
|
316
|
-
assert!(!provedFn(&r, "
|
|
288
|
+
assert!(!provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
317
289
|
}
|
|
318
290
|
|
|
319
291
|
#[test]
|
|
320
|
-
fn
|
|
292
|
+
fn recursion_started_from_a_shared_value_not_unique() {
|
|
321
|
-
// `touch` is called with a unique value here and a shared one in `other`.
|
|
322
293
|
let s = format!(
|
|
294
|
+
"{CELL}fun go(start: Cell) -> Cell =\n spin(start, 0)\n\
|
|
323
|
-
|
|
295
|
+
fun spin(v: Cell, i: Int) -> Cell =\n if i < 3\n spin(v.bumped(), i + 1)\n else\n v\n\
|
|
324
|
-
fun other(
|
|
296
|
+
fun other(c: Cell) -> Int =\n d := go(c)\n c.n + d.n\n"
|
|
325
297
|
);
|
|
326
298
|
let (_, r) = run(&s);
|
|
327
|
-
assert!(!provedFn(&r, "touch"), "{r:?}");
|
|
328
|
-
assert!(!provedFn(&r, "
|
|
299
|
+
assert!(!provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
329
300
|
}
|
|
330
301
|
|
|
331
302
|
#[test]
|
|
@@ -385,25 +356,6 @@ fn matched_into_a_binding_not_unique() {
|
|
|
385
356
|
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
386
357
|
}
|
|
387
358
|
|
|
388
|
-
#[test]
|
|
389
|
-
fn loop_keeping_the_previous_value_not_unique() {
|
|
390
|
-
let s = format!(
|
|
391
|
-
"{CELL}fun go(xs: Slice[Cell]) -> Cell =\n v := Cell(label: \"a\", n: 0)\n i := 0\n while i < 3\n xs.push(v)\n v = v.bumped()\n i = i + 1\n v\n"
|
|
392
|
-
);
|
|
393
|
-
let (_, r) = run(&s);
|
|
394
|
-
assert!(!provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
#[test]
|
|
398
|
-
fn loop_value_bound_outside_from_a_shared_source_not_unique() {
|
|
399
|
-
let s = format!(
|
|
400
|
-
"{CELL}fun go(start: Cell) -> Cell =\n v := start\n i := 0\n while i < 3\n v = v.bumped()\n i = i + 1\n v\n\
|
|
401
|
-
fun other(c: Cell) -> Int =\n d := go(c)\n c.n + d.n\n"
|
|
402
|
-
);
|
|
403
|
-
let (_, r) = run(&s);
|
|
404
|
-
assert!(!provedFn(&r, "Cell.bumped"), "{r:?}");
|
|
405
|
-
}
|
|
406
|
-
|
|
407
359
|
#[test]
|
|
408
360
|
fn constant_receiver_not_unique() {
|
|
409
361
|
let s = "struct Zero(label: Str, n: Int) =\n Origin = Zero(label: \"z\", n: 0)\n fun inc(self) -> Zero = Zero(..self, n: self.n + 1)\n\
|
compiler/driver/src/lib.rs
CHANGED
|
@@ -74,7 +74,7 @@ pub fn fusionNotesWith(copy: &mut Source, fbip: bool) -> Vec<String> {
|
|
|
74
74
|
fusionRun(copy, fbip).0
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
/// `fusionNotesWith`, and the errors of the `fip fun`s whose spreads
|
|
77
|
+
/// `fusionNotesWith`, and the errors of the `fip fun`s whose spreads the
|
|
78
78
|
/// proof left as copies (see `plum_core::fip`). Needs `fbip`; without it nothing is enforced.
|
|
79
79
|
pub fn fusionRun(copy: &mut Source, fbip: bool) -> (Vec<String>, Vec<Diagnostic>) {
|
|
80
80
|
let origins = plum_core::fip::origins(copy);
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -73,3 +73,55 @@ fn aRewriteThatFailsItsRecheckIsDropped() {
|
|
|
73
73
|
let without = loweredNames(&src, &opts);
|
|
74
74
|
assert_eq!(with, without);
|
|
75
75
|
}
|
|
76
|
+
|
|
77
|
+
const LOOPS: &str = "\
|
|
78
|
+
import std/Int
|
|
79
|
+
|
|
80
|
+
struct Acc(mut n: Int)
|
|
81
|
+
|
|
82
|
+
fun run(k: Int) -> Int =
|
|
83
|
+
a := Acc(n: 0)
|
|
84
|
+
for i := range k
|
|
85
|
+
a.n = a.n + i
|
|
86
|
+
while a.n > 100
|
|
87
|
+
a.n = a.n - 100
|
|
88
|
+
a.n
|
|
89
|
+
";
|
|
90
|
+
|
|
91
|
+
#[test]
|
|
92
|
+
fn loopsAreLiftedToFunctions() {
|
|
93
|
+
let src = load("drv_loops", LOOPS);
|
|
94
|
+
let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
95
|
+
let info = check(&src, &opts).expect("checks");
|
|
96
|
+
let lowered = info.lowered.expect("lowered");
|
|
97
|
+
let names = fnNames(&lowered);
|
|
98
|
+
assert!(names.iter().filter(|n| n.contains("@loop")).count() >= 2, "{names:?}");
|
|
99
|
+
for n in names.iter().filter(|n| n.contains("@loop")) {
|
|
100
|
+
assert!(!plum_core::diag::sourceName(n).contains("@loop"), "a message would show `{n}`");
|
|
101
|
+
}
|
|
102
|
+
let text = format!("{:?}", lowered.items);
|
|
103
|
+
assert!(!text.contains("While(") && !text.contains("\"__while\"") && !text.contains("\"__for\""), "a loop is left in the lowered program");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#[test]
|
|
107
|
+
fn aQuestionMarkInALoopBodyIsRejected() {
|
|
108
|
+
let err = plum_test_support::load("drv_loop_question", "import std/Int\nimport std/Option\nimport std/List\n\nfun early(xs: List[Int]) -> Option[Int] =\n for x := range xs\n y := Some(x)?\n Some(1)\n").err().expect("rejected");
|
|
109
|
+
assert!(err.contains("'?' can't be used in a loop body"), "{err}");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
#[test]
|
|
113
|
+
fn aLoopOverALocalWithNoTypeYetIsAnError() {
|
|
114
|
+
let src = load("drv_loop_unresolved", "import std/Int\nimport std/List\n\nfun main() -> Int =\n xs := []\n for i := range 3\n _ := xs.length()\n ys := xs.push(1)\n ys.length()\n");
|
|
115
|
+
let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
116
|
+
let errs = check(&src, &opts).err().expect("rejected");
|
|
117
|
+
assert!(errs.iter().any(|e| e.message.contains("cannot turn this loop into a function") && e.message.contains("fn 'main'")), "{errs:?}");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#[test]
|
|
121
|
+
fn aTypeErrorInAForSourceIsReportedNotAHiddenLoop() {
|
|
122
|
+
let src = load("drv_loop_source_error", "import std/Int\n\nstruct T(mut n: Int)\n\nfun main() -> Int =\n t := T(n: 0)\n for i := range undefinedThing\n t.n = i\n t.n\n");
|
|
123
|
+
let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
124
|
+
let errs = check(&src, &opts).err().expect("rejected");
|
|
125
|
+
assert!(errs.iter().any(|e| e.message.contains("undefined name 'undefinedThing'")), "{errs:?}");
|
|
126
|
+
assert!(!errs.iter().any(|e| e.message.contains("cannot turn this loop")), "{errs:?}");
|
|
127
|
+
}
|
compiler/lsp/src/completion.rs
CHANGED
|
@@ -44,9 +44,6 @@ const KEYWORDS: &[&str] = &[
|
|
|
44
44
|
"range",
|
|
45
45
|
"match",
|
|
46
46
|
"when",
|
|
47
|
-
"break",
|
|
48
|
-
"continue",
|
|
49
|
-
"return",
|
|
50
47
|
"todo",
|
|
51
48
|
"assert",
|
|
52
49
|
"test",
|
|
@@ -417,9 +414,13 @@ fn walkStmt(
|
|
|
417
414
|
walkBlock(b, env, global, ctx);
|
|
418
415
|
}
|
|
419
416
|
}
|
|
420
|
-
ast::StmtKind::While(w) => walkBlock(&w.body, env, global, ctx),
|
|
421
|
-
//
|
|
417
|
+
// A loop's binders have types the lowering decides (not done here); the body's own
|
|
418
|
+
// locals still count.
|
|
419
|
+
ast::StmtKind::Expr(..) => {
|
|
420
|
+
if let Some(body) = plum_core::forms::loopBlock(stmt) {
|
|
422
|
-
|
|
421
|
+
walkBlock(body, env, global, ctx);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
423
424
|
ast::StmtKind::Match(m) => {
|
|
424
425
|
for case in &m.cases {
|
|
425
426
|
walkBlock(&case.body, env, global, ctx);
|
|
@@ -683,4 +684,11 @@ mod tests {
|
|
|
683
684
|
fn fipIsOfferedAsKeyword() {
|
|
684
685
|
assert!(keywordItems().iter().any(|i| i.label == "fip"));
|
|
685
686
|
}
|
|
687
|
+
|
|
688
|
+
#[test]
|
|
689
|
+
fn removedFormsAreNotOfferedAsKeywords() {
|
|
690
|
+
for gone in ["break", "continue", "return"] {
|
|
691
|
+
assert!(!keywordItems().iter().any(|i| i.label == gone), "{gone}");
|
|
692
|
+
}
|
|
693
|
+
}
|
|
686
694
|
}
|
compiler/wasm-codegen/src/closurecalls.rs
CHANGED
|
@@ -298,7 +298,6 @@ pub(crate) fn compileClosureBody(
|
|
|
298
298
|
gc_types: &ctx.gc_types,
|
|
299
299
|
singleton_globals: &ctx.singleton_globals,
|
|
300
300
|
type_env: RefCell::new(base_env),
|
|
301
|
-
loop_base_depth: Cell::new(0),
|
|
302
301
|
ret_type: Some(info.ret_ptype.clone()),
|
|
303
302
|
subject_ptypes: RefCell::new(HashMap::new()),
|
|
304
303
|
// Tail calls inside the closure body are relative to the closure's own wasm fn.
|
compiler/wasm-codegen/src/closures.rs
CHANGED
|
@@ -113,7 +113,6 @@ impl<'a, 't> ClosureWalker<'a, 't> {
|
|
|
113
113
|
|
|
114
114
|
pub(crate) fn walkStmt(&mut self, stmt: &'a ast::Stmt) {
|
|
115
115
|
match stmt {
|
|
116
|
-
ast::Stmt { kind: ast::StmtKind::ForLoop(_), .. } => {}
|
|
117
116
|
ast::Stmt { kind: ast::StmtKind::Assign(a), .. } => {
|
|
118
117
|
for (target, value) in a.targets.iter().zip(a.values.iter()) {
|
|
119
118
|
if let (ast::Expr { kind: ast::ExprKind::Closure(_), .. }, ast::AssignTarget::Var(name), 1) =
|
|
@@ -172,7 +171,7 @@ impl<'a, 't> ClosureWalker<'a, 't> {
|
|
|
172
171
|
self.walkBlock(&case.body);
|
|
173
172
|
}
|
|
174
173
|
}
|
|
175
|
-
ast::Stmt { kind: ast::StmtKind::
|
|
174
|
+
ast::Stmt { kind: ast::StmtKind::Todo, .. } => {}
|
|
176
175
|
ast::Stmt { kind: ast::StmtKind::Crash(e), .. } => self.walkExpr(e),
|
|
177
176
|
}
|
|
178
177
|
}
|
compiler/wasm-codegen/src/construct.rs
CHANGED
|
@@ -248,7 +248,6 @@ pub(crate) fn compileInterpolatedString(
|
|
|
248
248
|
line: 0,
|
|
249
249
|
column: 0,
|
|
250
250
|
tail: ast::TailKind::NotTail,
|
|
251
|
-
unique: false,
|
|
252
251
|
};
|
|
253
252
|
if plum_checker::nominalName(&other)
|
|
254
253
|
.is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n)))
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -160,12 +160,6 @@ pub(crate) struct LocalCtx<'a> {
|
|
|
160
160
|
/// statements in order, mirroring `plum-checker`'s own env evolution — needed
|
|
161
161
|
/// to resolve `Attribute`/`ClassCall` targets and pick the right load/store width.
|
|
162
162
|
pub(crate) type_env: RefCell<TypeEnv>,
|
|
163
|
-
/// `tail_depth` as it stood when the NEAREST ENCLOSING LOOP's body began.
|
|
164
|
-
/// `Stmt::Break`/`Stmt::Continue` branch over `tail_depth - loop_base_depth`
|
|
165
|
-
/// wasm `if`s (every one is `TailDepth`-guarded: if/else-if chains, match
|
|
166
|
-
/// pattern tests and `when` guards) before reaching the loop's
|
|
167
|
-
/// own `block`/`loop` pair. A nested loop re-bases it for its own body.
|
|
168
|
-
pub(crate) loop_base_depth: Cell<u32>,
|
|
169
163
|
/// The declared return type of the function being compiled (`None` inside a
|
|
170
164
|
/// closure body) — `?` builds the OUTER function's error result from it.
|
|
171
165
|
pub(crate) ret_type: Option<PlumType>,
|
|
@@ -220,7 +214,6 @@ impl LocalCtx<'_> {
|
|
|
220
214
|
gc_types: self.gc_types,
|
|
221
215
|
singleton_globals: self.singleton_globals,
|
|
222
216
|
type_env: RefCell::new(self.global_env.clone()),
|
|
223
|
-
loop_base_depth: Cell::new(0),
|
|
224
217
|
ret_type: None,
|
|
225
218
|
subject_ptypes: RefCell::new(HashMap::new()),
|
|
226
219
|
self_func: None,
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -462,7 +462,6 @@ pub(crate) fn compileExpr(
|
|
|
462
462
|
line: 0,
|
|
463
463
|
column: 0,
|
|
464
464
|
tail: ast::TailKind::NotTail,
|
|
465
|
-
unique: false,
|
|
466
465
|
};
|
|
467
466
|
compileMethodCall(
|
|
468
467
|
&object,
|
compiler/wasm-codegen/src/fnbody.rs
CHANGED
|
@@ -92,7 +92,6 @@ impl<'a> Collector<'a> {
|
|
|
92
92
|
|
|
93
93
|
pub(crate) fn walkStmt(&mut self, stmt: &ast::Stmt) {
|
|
94
94
|
match stmt {
|
|
95
|
-
ast::Stmt { kind: ast::StmtKind::ForLoop(_), .. } => {}
|
|
96
95
|
ast::Stmt { kind: ast::StmtKind::Assign(a), .. } => {
|
|
97
96
|
for (target, value) in a.targets.iter().zip(a.values.iter()) {
|
|
98
97
|
self.walkExpr(value);
|
|
@@ -166,7 +165,7 @@ impl<'a> Collector<'a> {
|
|
|
166
165
|
self.walkBlock(&case.body);
|
|
167
166
|
}
|
|
168
167
|
}
|
|
169
|
-
ast::Stmt { kind: ast::StmtKind::
|
|
168
|
+
ast::Stmt { kind: ast::StmtKind::Todo, .. } => {}
|
|
170
169
|
ast::Stmt { kind: ast::StmtKind::Crash(e), .. } => self.walkExpr(e),
|
|
171
170
|
}
|
|
172
171
|
}
|
|
@@ -462,7 +461,6 @@ pub(crate) fn compileFnBodyImpl(
|
|
|
462
461
|
gc_types: &ctx.gc_types,
|
|
463
462
|
singleton_globals: &ctx.singleton_globals,
|
|
464
463
|
type_env: RefCell::new(base_env),
|
|
465
|
-
loop_base_depth: Cell::new(0),
|
|
466
464
|
ret_type: f.returns.as_ref().map(|_| ret_decl.clone()),
|
|
467
465
|
subject_ptypes: RefCell::new(HashMap::new()),
|
|
468
466
|
self_func,
|
compiler/wasm-codegen/src/stmts.rs
CHANGED
|
@@ -24,8 +24,6 @@ pub(crate) fn compileCaseBody(
|
|
|
24
24
|
ctx: &LocalCtx,
|
|
25
25
|
state: &mut ModuleState,
|
|
26
26
|
) -> Result<(), String> {
|
|
27
|
-
// The enclosing wasm `if`s are counted by the callers' `TailDepth` guards;
|
|
28
|
-
// see `loop_base_depth`.
|
|
29
27
|
match result_vt {
|
|
30
28
|
Some(vt) => compileBlockInValuePosition(block, vt, body, ctx, state),
|
|
31
29
|
None => compileBlock(block, body, ctx, state),
|
|
@@ -68,8 +66,6 @@ pub(crate) fn compileStmtInValuePosition(
|
|
|
68
66
|
ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. } => compileExpr(e, body, ctx, state),
|
|
69
67
|
ast::Stmt { kind: ast::StmtKind::Return(_), .. }
|
|
70
68
|
| ast::Stmt { kind: ast::StmtKind::Todo, .. }
|
|
71
|
-
| ast::Stmt { kind: ast::StmtKind::Break, .. }
|
|
72
|
-
| ast::Stmt { kind: ast::StmtKind::Continue, .. }
|
|
73
69
|
| ast::Stmt { kind: ast::StmtKind::Crash(_), .. } => {
|
|
74
70
|
compileStmt(stmt, body, ctx, state)
|
|
75
71
|
}
|
|
@@ -352,7 +348,6 @@ pub(crate) fn compileStmt(
|
|
|
352
348
|
state: &mut ModuleState,
|
|
353
349
|
) -> Result<(), String> {
|
|
354
350
|
match stmt {
|
|
355
|
-
ast::Stmt { kind: ast::StmtKind::ForLoop(_), .. } => unreachable!("for forms are lowered before codegen"),
|
|
356
351
|
ast::Stmt { kind: ast::StmtKind::Assign(a), .. } => {
|
|
357
352
|
for (target, value) in a.targets.iter().zip(a.values.iter()) {
|
|
358
353
|
match target {
|
|
@@ -413,14 +408,7 @@ pub(crate) fn compileStmt(
|
|
|
413
408
|
compileBoolConditionAsI32(&w.condition, body, ctx, state)?;
|
|
414
409
|
Instruction::I32Eqz.encode(body);
|
|
415
410
|
Instruction::BrIf(1).encode(body);
|
|
416
|
-
// This loop's own `block`/`loop` pair is `break`/`continue`'s new
|
|
417
|
-
// nearest target — reset the depth counter to 0 for its body, then
|
|
418
|
-
// restore whatever it was (an outer loop's own count, if this loop
|
|
419
|
-
// is itself nested inside an `if` inside another loop) afterward.
|
|
420
|
-
let saved_depth = ctx.loop_base_depth.replace(ctx.tail_depth.get());
|
|
421
|
-
|
|
411
|
+
compileBlock(&w.body, body, ctx, state)?;
|
|
422
|
-
ctx.loop_base_depth.set(saved_depth);
|
|
423
|
-
result?;
|
|
424
412
|
Instruction::Br(0).encode(body);
|
|
425
413
|
Instruction::End.encode(body);
|
|
426
414
|
Instruction::End.encode(body);
|
|
@@ -432,12 +420,6 @@ pub(crate) fn compileStmt(
|
|
|
432
420
|
emitDrops(&inferLocalType(e, ctx), body);
|
|
433
421
|
}
|
|
434
422
|
}
|
|
435
|
-
ast::Stmt { kind: ast::StmtKind::Break, .. } => {
|
|
436
|
-
Instruction::Br(ctx.tail_depth.get() - ctx.loop_base_depth.get() + 1).encode(body);
|
|
437
|
-
}
|
|
438
|
-
ast::Stmt { kind: ast::StmtKind::Continue, .. } => {
|
|
439
|
-
Instruction::Br(ctx.tail_depth.get() - ctx.loop_base_depth.get()).encode(body);
|
|
440
|
-
}
|
|
441
423
|
ast::Stmt { kind: ast::StmtKind::Match(m), .. } => {
|
|
442
424
|
compileMatch(stmt, m, body, ctx, state, None)?;
|
|
443
425
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -1160,7 +1160,7 @@ fun main() -> Int =
|
|
|
1160
1160
|
STD_HEAD, LIST_FNS
|
|
1161
1161
|
);
|
|
1162
1162
|
let (_, keys) = compiledKeys("copy2", &src);
|
|
1163
|
-
let maps: Vec<&String> = keys.iter().filter(|k| k.starts_with("mapList")).collect();
|
|
1163
|
+
let maps: Vec<&String> = keys.iter().filter(|k| k.starts_with("mapList") && !k.contains("@loop")).collect();
|
|
1164
1164
|
assert_eq!(maps.len(), 2, "got {:?}", maps);
|
|
1165
1165
|
assert!(
|
|
1166
1166
|
keys.iter()
|
|
@@ -1191,7 +1191,7 @@ fun main() -> Int =
|
|
|
1191
1191
|
STD_HEAD, LIST_FNS
|
|
1192
1192
|
);
|
|
1193
1193
|
let (_, keys) = compiledKeys("copy1", &src);
|
|
1194
|
-
let maps: Vec<&String> = keys.iter().filter(|k| k.starts_with("mapList")).collect();
|
|
1194
|
+
let maps: Vec<&String> = keys.iter().filter(|k| k.starts_with("mapList") && !k.contains("@loop")).collect();
|
|
1195
1195
|
assert_eq!(maps.len(), 1, "got {:?}", maps);
|
|
1196
1196
|
}
|
|
1197
1197
|
|
|
@@ -1876,6 +1876,10 @@ fun main() -> Int =
|
|
|
1876
1876
|
let (bytes, _) = compiledKeys("formfilter", &form);
|
|
1877
1877
|
let ops = opsOf(&bytes, "main");
|
|
1878
1878
|
assert_eq!(countOps(&ops, "CallIndirect") + countOps(&ops, "CallRef"), 0, "{ops:?}");
|
|
1879
|
+
// no closure is built either: a closure value is made with `ref.func`
|
|
1880
|
+
assert_eq!(countOps(&ops, "RefFunc"), 0, "{ops:?}");
|
|
1881
|
+
let looped = namedBodies(&bytes).into_iter().find(|(n, _)| n.contains("@loop")).expect("the loop function compiled").1;
|
|
1882
|
+
assert_eq!(countOps(&looped, "RefFunc") + countOps(&looped, "CallIndirect") + countOps(&looped, "CallRef"), 0, "{looped:?}");
|
|
1879
1883
|
assert_eq!(runMerged::<i64>("formfilter_run", &form), 2);
|
|
1880
1884
|
// the closure-method version builds a closure struct per call and calls through the table
|
|
1881
1885
|
let closure = format!(
|
|
@@ -1889,15 +1893,16 @@ fun main() -> Int =
|
|
|
1889
1893
|
);
|
|
1890
1894
|
let (cbytes, _) = compiledKeys("closurefilter", &closure);
|
|
1891
1895
|
let cops = opsOf(&cbytes, "main");
|
|
1892
|
-
assert!(
|
|
1893
|
-
|
|
1896
|
+
// The closure struct and its environment are two more `struct.new` than the `for` form needs.
|
|
1894
|
-
|
|
1897
|
+
assert!(countOps(&cops, "StructNew") >= 2, "closure main builds a closure struct: {cops:?}");
|
|
1898
|
+
// the call through the closure is in `retainList`'s loop function
|
|
1899
|
+
let calls: usize = namedBodies(&cbytes)
|
|
1895
|
-
|
|
1900
|
+
.into_iter()
|
|
1896
|
-
|
|
1901
|
+
.filter(|(n, _)| n.starts_with("retainList"))
|
|
1897
|
-
assert!(
|
|
1898
|
-
countOps(&
|
|
1902
|
+
.map(|(_, ops)| countOps(&ops, "CallRef") + countOps(&ops, "CallIndirect"))
|
|
1899
|
-
"{retain:?}"
|
|
1900
|
-
|
|
1903
|
+
.sum();
|
|
1904
|
+
assert!(calls >= 1, "retainList calls through the closure");
|
|
1905
|
+
assert_eq!(runMerged::<i64>("closurefilter_run", &closure), 2);
|
|
1901
1906
|
}
|
|
1902
1907
|
|
|
1903
1908
|
#[test]
|
|
@@ -1910,7 +1915,8 @@ fn list_literal_method_fuses_to_the_end() {
|
|
|
1910
1915
|
|
|
1911
1916
|
#[test]
|
|
1912
1917
|
fn range_int_loop_is_tight() {
|
|
1913
|
-
// `for i := range n` is
|
|
1918
|
+
// `for i := range n` is lifted to a self-tail-recursive function, which compiles to one
|
|
1919
|
+
// wasm loop with no call for the iteration itself; `main` makes the one call that starts it.
|
|
1914
1920
|
let src = format!(
|
|
1915
1921
|
"{}\
|
|
1916
1922
|
struct Count(mut n: Int)
|
|
@@ -1924,7 +1930,13 @@ fun main() -> Int =
|
|
|
1924
1930
|
STD_HEAD
|
|
1925
1931
|
);
|
|
1926
1932
|
let (bytes, _) = compiledKeys("rangeinttight", &src);
|
|
1927
|
-
let
|
|
1933
|
+
let main = opsOf(&bytes, "main");
|
|
1934
|
+
assert_eq!(countOps(&main, "Call"), 1, "main only starts the loop: {main:?}");
|
|
1935
|
+
let ops = namedBodies(&bytes)
|
|
1936
|
+
.into_iter()
|
|
1937
|
+
.find(|(n, _)| n.contains("@loop"))
|
|
1938
|
+
.expect("the loop function compiled")
|
|
1939
|
+
.1;
|
|
1928
1940
|
assert_eq!(countOps(&ops, "Loop"), 1, "{ops:?}");
|
|
1929
1941
|
assert_eq!(
|
|
1930
1942
|
countOps(&ops, "Call"),
|
|
@@ -2824,120 +2836,3 @@ fn closure_assigning_captured_struct_fields_writes_its_own_copy() {
|
|
|
2824
2836
|
assert_eq!(runCapturedFields("capfieldsstruct", body), 121200);
|
|
2825
2837
|
}
|
|
2826
2838
|
|
|
2827
|
-
// ---------------------------------------------------------------------------
|
|
2828
|
-
// `Array.with`: written in place when the array is proved unique, else copied
|
|
2829
|
-
// ---------------------------------------------------------------------------
|
|
2830
|
-
|
|
2831
|
-
fn compiledFbip(name: &str, src: &str, fbip: bool) -> Vec<u8> {
|
|
2832
|
-
let dir = std::env::temp_dir().join(format!("plum_aw_{}_{}", name, std::process::id()));
|
|
2833
|
-
std::fs::create_dir_all(&dir).unwrap();
|
|
2834
|
-
let path = dir.join("main.plum");
|
|
2835
|
-
std::fs::write(&path, src).unwrap();
|
|
2836
|
-
let source = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("load");
|
|
2837
|
-
let opts = CompileOptions {
|
|
2838
|
-
passes: plum_driver::PassOptions { fbip, ..plum_driver::PassOptions::default() },
|
|
2839
|
-
..CompileOptions::default()
|
|
2840
|
-
};
|
|
2841
|
-
let o = compile(&source, &opts).expect("compile");
|
|
2842
|
-
let _ = std::fs::remove_dir_all(&dir);
|
|
2843
|
-
wasmparser::validate(&o.wasm).expect("valid wasm");
|
|
2844
|
-
o.wasm
|
|
2845
|
-
}
|
|
2846
|
-
|
|
2847
|
-
const WITH_HEAD: &str = "import std/Int\nimport std/Array\n";
|
|
2848
|
-
|
|
2849
|
-
fn bodyNames(bytes: &[u8]) -> Vec<String> {
|
|
2850
|
-
namedBodies(bytes).into_iter().map(|(n, _)| n).collect()
|
|
2851
|
-
}
|
|
2852
|
-
|
|
2853
|
-
fn hasFn(bytes: &[u8], needle: &str) -> bool {
|
|
2854
|
-
bodyNames(bytes).iter().any(|n| n.contains(needle))
|
|
2855
|
-
}
|
|
2856
|
-
|
|
2857
|
-
/// The copying `Array[T].with` (not `withUnique`) is compiled.
|
|
2858
|
-
fn hasCopyingWith(bytes: &[u8]) -> bool {
|
|
2859
|
-
bodyNames(bytes).iter().any(|n| n.ends_with(".with"))
|
|
2860
|
-
}
|
|
2861
|
-
|
|
2862
|
-
#[test]
|
|
2863
|
-
fn array_with_proved_local_writes_in_place() {
|
|
2864
|
-
// `a.with(..)` handing over a fresh local: the checker runs `withUnique`, which only sets.
|
|
2865
|
-
let src = format!(
|
|
2866
|
-
"{WITH_HEAD}fun fresh() -> Array[Int] =\n a := Array.filled(4, 0)\n a.with(3, 6)\n\nfun main() -> Int =\n fresh().get(3)\n"
|
|
2867
|
-
);
|
|
2868
|
-
let bytes = compiledFbip("awproved", &src, true);
|
|
2869
|
-
assert!(hasFn(&bytes, "withUnique"), "{:?}", bodyNames(&bytes));
|
|
2870
|
-
assert!(!hasCopyingWith(&bytes), "the copying with is unused: {:?}", bodyNames(&bytes));
|
|
2871
|
-
let inplace = namedBodies(&bytes).into_iter().find(|(n, _)| n.contains("withUnique")).unwrap().1;
|
|
2872
|
-
assert_eq!(countOps(&inplace, "ArrayCopy"), 0, "{inplace:?}");
|
|
2873
|
-
// one call, to the `set` intrinsic: no `resize` copy
|
|
2874
|
-
assert_eq!(countOps(&inplace, "Call"), 1, "{inplace:?}");
|
|
2875
|
-
assert_eq!(runMerged::<i64>("awproved_run", &src), 6);
|
|
2876
|
-
// with `--no-fbip` the same site copies
|
|
2877
|
-
let plain = compiledFbip("awplain", &src, false);
|
|
2878
|
-
assert!(!hasFn(&plain, "withUnique"), "{:?}", bodyNames(&plain));
|
|
2879
|
-
let copy = namedBodies(&plain).into_iter().find(|(n, _)| n.ends_with(".with")).expect("with compiled").1;
|
|
2880
|
-
assert!(countOps(©, "Call") >= 2, "resize and set: {copy:?}");
|
|
2881
|
-
}
|
|
2882
|
-
|
|
2883
|
-
const VEC_SRC: &str = "struct Vec(cells: Array[Int], n: Int) =
|
|
2884
|
-
fun append(self, x: Int) -> Vec = Vec(..self, cells: self.cells.with(self.n, x), n: self.n + 1)
|
|
2885
|
-
fun get(self, i: Int) -> Int = self.cells.get(i)
|
|
2886
|
-
|
|
2887
|
-
fun fillTwo() -> Vec = Vec(cells: Array.filled(8, 0), n: 0).append(0).append(2)
|
|
2888
|
-
";
|
|
2889
|
-
|
|
2890
|
-
#[test]
|
|
2891
|
-
fn array_with_in_a_unique_struct_field_writes_in_place() {
|
|
2892
|
-
// `Vec(..self, cells: self.cells.with(..))` of a unique `self`: no copy of the array.
|
|
2893
|
-
let src = format!("{WITH_HEAD}{VEC_SRC}\nfun main() -> Int =\n fillTwo().append(4).append(6).get(3)\n");
|
|
2894
|
-
let bytes = compiledFbip("awvec", &src, true);
|
|
2895
|
-
assert!(hasFn(&bytes, "withUnique"), "{:?}", bodyNames(&bytes));
|
|
2896
|
-
assert!(!hasCopyingWith(&bytes), "{:?}", bodyNames(&bytes));
|
|
2897
|
-
let inplace = namedBodies(&bytes).into_iter().find(|(n, _)| n.contains("withUnique")).unwrap().1;
|
|
2898
|
-
assert_eq!(countOps(&inplace, "ArrayCopy"), 0, "{inplace:?}");
|
|
2899
|
-
assert_eq!(runMerged::<i64>("awvec_run", &src), 6);
|
|
2900
|
-
let plain = compiledFbip("awvecplain", &src, false);
|
|
2901
|
-
assert!(!hasFn(&plain, "withUnique"));
|
|
2902
|
-
assert!(hasCopyingWith(&plain));
|
|
2903
|
-
}
|
|
2904
|
-
|
|
2905
|
-
#[test]
|
|
2906
|
-
fn array_with_unproved_site_copies() {
|
|
2907
|
-
// The old array is still held by `b`: the site must copy (`resize` allocates and copies).
|
|
2908
|
-
let src = format!(
|
|
2909
|
-
"{WITH_HEAD}fun main() -> Int =\n a := Array.filled(4, 0)\n b := a\n c := a.with(1, 5)\n b.get(1) * 10 + c.get(1)\n"
|
|
2910
|
-
);
|
|
2911
|
-
let bytes = compiledFbip("awunproved", &src, true);
|
|
2912
|
-
assert!(!hasFn(&bytes, "withUnique"), "{:?}", bodyNames(&bytes));
|
|
2913
|
-
let resize = namedBodies(&bytes).into_iter().find(|(n, _)| n.contains("resize")).expect("resize compiled").1;
|
|
2914
|
-
assert!(countOps(&resize, "ArrayCopy") >= 1, "{resize:?}");
|
|
2915
|
-
assert_eq!(runMerged::<i64>("awunproved_run", &src), 5);
|
|
2916
|
-
}
|
|
2917
|
-
|
|
2918
|
-
#[test]
|
|
2919
|
-
fn array_with_in_a_shared_struct_copies() {
|
|
2920
|
-
// Two holders of the vector: its array is not written in place.
|
|
2921
|
-
let src = format!(
|
|
2922
|
-
"{WITH_HEAD}{VEC_SRC}\nfun main() -> Int =\n v := fillTwo()\n w := v\n x := v.append(9)\n w.get(2) * 10 + x.get(2)\n"
|
|
2923
|
-
);
|
|
2924
|
-
let bytes = compiledFbip("awshared", &src, true);
|
|
2925
|
-
assert!(!hasFn(&bytes, "withUnique"), "{:?}", bodyNames(&bytes));
|
|
2926
|
-
assert_eq!(runMerged::<i64>("awshared_run", &src), 9);
|
|
2927
|
-
}
|
|
2928
|
-
|
|
2929
|
-
#[test]
|
|
2930
|
-
fn array_with_in_place_twin_cannot_be_called_from_source() {
|
|
2931
|
-
let dir = std::env::temp_dir().join(format!("plum_awu_{}", std::process::id()));
|
|
2932
|
-
std::fs::create_dir_all(&dir).unwrap();
|
|
2933
|
-
let path = dir.join("main.plum");
|
|
2934
|
-
std::fs::write(
|
|
2935
|
-
&path,
|
|
2936
|
-
format!("{WITH_HEAD}fun main() -> Int =\n a := Array.filled(2, 0)\n a.withUnique(0, 1).get(0)\n"),
|
|
2937
|
-
)
|
|
2938
|
-
.unwrap();
|
|
2939
|
-
let source = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("load");
|
|
2940
|
-
let errs = plum_checker::checkSource(&source).expect_err("withUnique is for the compiler only");
|
|
2941
|
-
let _ = std::fs::remove_dir_all(&dir);
|
|
2942
|
-
assert!(errs.iter().any(|e| e.message.contains("for the compiler only")), "{errs:?}");
|
|
2943
|
-
}
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_inplace.rs
CHANGED
|
@@ -37,26 +37,3 @@ fn unique_spread_reuses_object() {
|
|
|
37
37
|
assert!(spreadIsUnique("reuse_flag", "adv", &unique));
|
|
38
38
|
assert_eq!(runInt("reuse_run", &unique), 207);
|
|
39
39
|
}
|
|
40
|
-
|
|
41
|
-
/// F-T6-3: `s = Cell(..s, ...)` on a param must reassign the param's own slot, not
|
|
42
|
-
/// a fresh shadow local that every read of `s` (the spread source included) sees unset.
|
|
43
|
-
#[test]
|
|
44
|
-
fn unique_spread_reassign_same_var() {
|
|
45
|
-
let body = "struct Cell(x: Int, y: Int)
|
|
46
|
-
|
|
47
|
-
fun bump(s: Cell) -> Cell =
|
|
48
|
-
s = Cell(..s, x: s.x + 1)
|
|
49
|
-
s
|
|
50
|
-
|
|
51
|
-
fun inc(n: Int) -> Int =
|
|
52
|
-
n = n + 1
|
|
53
|
-
n
|
|
54
|
-
|
|
55
|
-
fun main() -> Int =
|
|
56
|
-
t := bump(Cell(x: 1, y: 7))
|
|
57
|
-
t.x * 100 + t.y + inc(40) * 1000
|
|
58
|
-
";
|
|
59
|
-
let unique = prog(body);
|
|
60
|
-
assert_eq!(runInt("reassign_param", &unique), 41000 + 207);
|
|
61
|
-
assert!(spreadIsUnique("reassign_param_flag", "bump", &unique));
|
|
62
|
-
}
|
docs/plans/2026-11-06-simpler-language.benchmark.md
CHANGED
|
@@ -112,3 +112,20 @@ Five probes: `for` with a `total =` accumulator, `while`, a tail-recursive `fold
|
|
|
112
112
|
## Branch fixtures after T2 (plain games, one scene)
|
|
113
113
|
|
|
114
114
|
On `simpler-language` the fixtures under `compiler/game/web-test/fixtures` are all plain games (`main` returns a type with `update(self, io, dt) -> Self` and `draw(self, io)`). `stress_scene` and `stress_pure_scene` are deleted (the baseline keeps the originals); `stress_state_view` is the functional twin of both, drawing the same 5000/500/200/50 scene. `stress_world` is ported to state and view with the same 20000 sprites, 500 walkers, camera drift, per-frame y-sort of the whole list and a 1280x720 cull. One difference: the old version walked `children.at(i * 37 % 20000)` after each re-sort, so which sprites walked changed every frame; the port gives walker `w` the fixed sprite `37 * w`. The view builds scene nodes only for the visible sprites. Nothing is tuned for speed; T14 measures.
|
|
115
|
+
|
|
116
|
+
## Migrated std against the baseline (before T10)
|
|
117
|
+
|
|
118
|
+
Question: did rewriting std off `return`, `while` and local reassignment slow anything down? Old = `.superlite/baseline-master` (master, release build), new = this branch at the start of T10 (release build). Both built with Rust 1.99.1 (the older numbers in this doc used another toolchain, so they are not compared here). `plum run` (wasmtime), alternating old and new, 4 runs each, load average 1.8 to 2.0 (1 minute) before and after. Probes are in the scratch folder, written in forms both compilers accept (`for` with a local accumulator, no `Range.fold`, which master lacks). Every answer was identical between old and new in all runs.
|
|
119
|
+
|
|
120
|
+
| probe | work | old (ms, 4 runs) | new (ms, 4 runs) | answer |
|
|
121
|
+
|---|---|---|---|---|
|
|
122
|
+
| Map set then get | 1,000,000 each | 143, 145, 146, 145 | 150, 162, 150, 151 | 999999000000 |
|
|
123
|
+
| Str build and search | 50,000 concats, then `indexOf`, `search`, `replaceAll` | 62, 63, 63, 61 | 61, 64, 64, 62 | 150000 |
|
|
124
|
+
| Buffer writes | 20,000,000 `writeByte` | 139, 139, 139, 139 | 139, 139, 138, 139 | 20000000 |
|
|
125
|
+
| Slice push and sort | 10,000 pushes, insertion sort | 155, 153, 153, 155 | 160, 160, 160, 160 | 20006 |
|
|
126
|
+
| List pipeline | 2,000,000 `map`, `filter`, `fold` | 51, 51, 51, 51 | 51, 52, 51, 51 | 2999997000000 |
|
|
127
|
+
| Int formatting | 3,000,000 `toStr().length()` | 652, 660, 649, 652 | 649, 653, 649, 660 | 19888890 |
|
|
128
|
+
|
|
129
|
+
Loops (50,000,000 iterations each, `--no-fusion` so `find` is timed at the right place): `for`, `while`, tail-recursive fold with a closure, struct-state loop, `findFirst` all take 12 to 13 ms in both compilers, with the same answers (1249999975000000 for the first four, 49999999 for `find`). Under the default build `find` reads 0 ms in both because fusion moves the call past the timer.
|
|
130
|
+
|
|
131
|
+
Result: no probe is more than 20% slower. The worst are Map set/get (about +3% on the median, 150 against 145; one run at +12%) and Slice push and sort (about +4%, 160 against 154). Both are within a few ms and look like the extra function call per loop pass in the rewritten `Map` and `Slice.insertBefore`; not confirmed with `--explain-fusion`, since neither passes the 20% bar. Nothing else moved.
|
examples/arrays.plum
CHANGED
|
@@ -207,17 +207,6 @@ test "probe option and list"
|
|
|
207
207
|
r := mk()
|
|
208
208
|
assert r.get(0).y == 2.0
|
|
209
209
|
|
|
210
|
-
test "probe break/continue"
|
|
211
|
-
a := Array[Vec2]().push(Vec2(x: 1.0, y: 0.0)).push(Vec2(x: 2.0, y: 0.0)).push(Vec2(x: 3.0, y: 0.0)).push(Vec2(x: 4.0, y: 0.0))
|
|
212
|
-
s := 0.0
|
|
213
|
-
for v := range a
|
|
214
|
-
if v.x == 2.0
|
|
215
|
-
continue
|
|
216
|
-
if v.x == 4.0
|
|
217
|
-
break
|
|
218
|
-
s = s + v.x
|
|
219
|
-
assert s == 4.0
|
|
220
|
-
|
|
221
210
|
test "probe Str leaf"
|
|
222
211
|
a := Array[Named]().push(Named(label: "hi", v: Vec2(x: 1.0, y: 2.0)))
|
|
223
212
|
assert a.get(0).label == "hi"
|
examples/closures.plum
CHANGED
|
@@ -16,13 +16,6 @@ fun useCapturingClosure() -> Int =
|
|
|
16
16
|
fun main() -> Int =
|
|
17
17
|
each(|v| v * 3) + useCapturingClosure()
|
|
18
18
|
|
|
19
|
-
fun useSnapshotClosure() -> Int =
|
|
20
|
-
x := 10
|
|
21
|
-
snapshotCb := |v|
|
|
22
|
-
x + v
|
|
23
|
-
x = 999
|
|
24
|
-
each(snapshotCb)
|
|
25
|
-
|
|
26
19
|
fun eachF(cb: fn(Float) -> Float) -> Float =
|
|
27
20
|
cb(0.0)
|
|
28
21
|
|
|
@@ -84,12 +77,6 @@ test "multi line closure call argument with closing paren on last statement line
|
|
|
84
77
|
bumped * 2)
|
|
85
78
|
assert multiLineResult == 12
|
|
86
79
|
|
|
87
|
-
test "capturing closure snapshots value at creation time runs correctly"
|
|
88
|
-
# each calls its callback with 5, so a correct snapshot of x==10 (its value
|
|
89
|
-
# when the closure was created, not 999 — its value when `each(cb)` is
|
|
90
|
-
# actually called) gives 10 + 5 = 15.
|
|
91
|
-
assert useSnapshotClosure() == 15
|
|
92
|
-
|
|
93
80
|
test "closure assigned then called at float type runs correctly"
|
|
94
81
|
assert useFloatClosure() == 2.5
|
|
95
82
|
|
examples/control_flow.plum
CHANGED
|
@@ -181,19 +181,6 @@ test "bind_in_body: name := expr is visible to the rest of the body"
|
|
|
181
181
|
total.n = total.n + sq
|
|
182
182
|
assert total.n == 16
|
|
183
183
|
|
|
184
|
-
test "break_continue_return_semantics"
|
|
185
|
-
xs := [1, 2, 3, 4, 5].toSlice()
|
|
186
|
-
total := 0
|
|
187
|
-
for x := range xs
|
|
188
|
-
if x == 2
|
|
189
|
-
continue
|
|
190
|
-
if x == 5
|
|
191
|
-
break
|
|
192
|
-
total = total + x
|
|
193
|
-
assert total == 8
|
|
194
|
-
assert firstOver(xs, 3) == 4
|
|
195
|
-
assert firstOver(xs, 9) == -1
|
|
196
|
-
|
|
197
184
|
test "find stops at the first match"
|
|
198
185
|
xs := [1, 2, 3, 4, 5].toSlice()
|
|
199
186
|
assert firstOver(xs, 3) == 4
|
examples/sequences.plum
CHANGED
|
@@ -140,19 +140,6 @@ test "Map entries, keys and values"
|
|
|
140
140
|
vs.n = vs.n + v
|
|
141
141
|
assert vs.n == 60
|
|
142
142
|
|
|
143
|
-
test "break_continue_return_semantics"
|
|
144
|
-
xs := [1, 2, 3, 4, 5].toSlice()
|
|
145
|
-
total := 0
|
|
146
|
-
for x := range xs
|
|
147
|
-
if x == 2
|
|
148
|
-
continue
|
|
149
|
-
if x == 5
|
|
150
|
-
break
|
|
151
|
-
total = total + x
|
|
152
|
-
assert total == 8
|
|
153
|
-
assert firstBig([1, 20, 30].toSlice()) == 20
|
|
154
|
-
assert firstBig(xs) == -1
|
|
155
|
-
|
|
156
143
|
test "find stops at the first big element"
|
|
157
144
|
assert firstBig([1, 20, 30].toSlice()) == 20
|
|
158
145
|
assert firstBig([1, 2].toSlice()) == -1
|
examples/structs_records.plum
CHANGED
|
@@ -401,11 +401,6 @@ test "union_local"
|
|
|
401
401
|
s: Shape := Circle(r: 2.0)
|
|
402
402
|
assert area(s) == 12.0
|
|
403
403
|
|
|
404
|
-
test "union_local_reassigned"
|
|
405
|
-
s: Shape := Circle(r: 1.0)
|
|
406
|
-
s = Region(w: 2.0, h: 3.0)
|
|
407
|
-
assert area(s) == 6.0
|
|
408
|
-
|
|
409
404
|
test "optional_local_present"
|
|
410
405
|
o: Option[Int] := Some(4)
|
|
411
406
|
assert o.unwrapOr(0) == 4
|
std/Array.plum
CHANGED
|
@@ -60,22 +60,6 @@ primitive Array[T] =
|
|
|
60
60
|
fun length(self) -> Int =
|
|
61
61
|
todo
|
|
62
62
|
|
|
63
|
-
# `self` with element `i` replaced by `v`, as a new array: `self` itself is left untouched.
|
|
64
|
-
# When the compiler proves nobody else holds `self` and `self` is dead afterwards (a local
|
|
65
|
-
# rebound with `a = a.with(i, v)`, or a unique struct's array rebuilt with
|
|
66
|
-
# `T(..self, data: self.data.with(i, v))`), the call runs `withUnique` and writes `self`
|
|
67
|
-
# in place. Traps if `i` is out of range, like `set`.
|
|
68
|
-
fun with(self, i: Int, v: T) -> Array[T] =
|
|
69
|
-
c := self.resize(self.length())
|
|
70
|
-
c.set(i, v)
|
|
71
|
-
c
|
|
72
|
-
|
|
73
|
-
# The in-place `with`, picked by the compiler alone: the checker rejects a call written in
|
|
74
|
-
# source, so no program can write through an array without the proof.
|
|
75
|
-
fun withUnique(self, i: Int, v: T) -> Array[T] =
|
|
76
|
-
self.set(i, v)
|
|
77
|
-
self
|
|
78
|
-
|
|
79
63
|
# Returns a NEW array, one longer than `self`, with `v` appended at the end
|
|
80
64
|
# — `self` itself is left untouched (this allocates and copies, it does not
|
|
81
65
|
# mutate in place). Callers grow in a loop by reassigning: `arr =
|
tests/core/for_next.plum
CHANGED
|
@@ -13,10 +13,6 @@ struct Countdown(n: Int) =
|
|
|
13
13
|
fun next(self) -> Option[Pair[Int, Countdown]] =
|
|
14
14
|
if self.n == 0 then None else Some(Pair(first: self.n, second: Countdown(n: self.n - 1)))
|
|
15
15
|
|
|
16
|
-
struct Up(i: Int, n: Int) =
|
|
17
|
-
fun next(self) -> Option[Pair[Int, Up]] =
|
|
18
|
-
if self.i >= self.n then None else Some(Pair(first: self.i, second: Up(i: self.i + 1, n: self.n)))
|
|
19
|
-
|
|
20
16
|
fun rangeInt() -> Int =
|
|
21
17
|
t := Tally(acc: 0)
|
|
22
18
|
for i := range 3
|
|
@@ -42,16 +38,6 @@ fun rangeUser() -> Int =
|
|
|
42
38
|
t.acc = t.acc * 10 + x
|
|
43
39
|
t.acc
|
|
44
40
|
|
|
45
|
-
fun rangeCtl() -> Int =
|
|
46
|
-
acc := 0
|
|
47
|
-
for x := range Up(i: 0, n: 10)
|
|
48
|
-
if x == 1
|
|
49
|
-
continue
|
|
50
|
-
if x == 4
|
|
51
|
-
break
|
|
52
|
-
acc = acc * 10 + x
|
|
53
|
-
acc
|
|
54
|
-
|
|
55
41
|
# binds 0, 1, 2
|
|
56
42
|
test "range_int_counts_from_zero"
|
|
57
43
|
assert rangeInt() == 123
|
|
@@ -64,7 +50,3 @@ test "list_next_steps"
|
|
|
64
50
|
|
|
65
51
|
test "range_user_struct_with_next"
|
|
66
52
|
assert rangeUser() == 321
|
|
67
|
-
|
|
68
|
-
# 0, (skip 1), 2, 3, stop at 4
|
|
69
|
-
test "range_next_supports_continue_and_break"
|
|
70
|
-
assert rangeCtl() == 23
|
tests/core/loops_lifted.plum
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/List
|
|
4
|
+
import std/Io
|
|
5
|
+
|
|
6
|
+
# `for` and `while` run as functions of their own: the free locals are arguments, the state
|
|
7
|
+
# lives in `mut` fields, and a pass is a tail call, so a long loop doesn't overflow.
|
|
8
|
+
|
|
9
|
+
struct Box(mut n: Int) =
|
|
10
|
+
fun fill(self, k: Int) =
|
|
11
|
+
for i := range k
|
|
12
|
+
for j := range 3
|
|
13
|
+
self.n = self.n + i * j
|
|
14
|
+
fun drain(self) =
|
|
15
|
+
while self.n > 0
|
|
16
|
+
self.n = self.n - 7
|
|
17
|
+
|
|
18
|
+
struct Gen[T](items: List[T]) =
|
|
19
|
+
fun count(self, tally: Box) =
|
|
20
|
+
for x := range self.items
|
|
21
|
+
tally.n = tally.n + 1
|
|
22
|
+
|
|
23
|
+
fun sumAll[T](xs: List[T], f: fn(T) -> Int) -> Int =
|
|
24
|
+
b := Box(n: 0)
|
|
25
|
+
for x := range xs
|
|
26
|
+
b.n = b.n + f(x)
|
|
27
|
+
b.n
|
|
28
|
+
|
|
29
|
+
fun inClosure(k: Int) -> Int =
|
|
30
|
+
b := Box(n: 0)
|
|
31
|
+
g := |m: Int|
|
|
32
|
+
for i := range m
|
|
33
|
+
b.n = b.n + i + k
|
|
34
|
+
g(4)
|
|
35
|
+
b.n
|
|
36
|
+
|
|
37
|
+
fun closureInLoop() -> Int =
|
|
38
|
+
b := Box(n: 0)
|
|
39
|
+
for i := range 3
|
|
40
|
+
h := |z: Int|
|
|
41
|
+
b.n = b.n + z
|
|
42
|
+
h(i + 1)
|
|
43
|
+
b.n
|
|
44
|
+
|
|
45
|
+
fun writes(io: Io, b: Box) =
|
|
46
|
+
for i := range 2
|
|
47
|
+
io.printLn("pass {i}")
|
|
48
|
+
b.n = b.n + 1
|
|
49
|
+
|
|
50
|
+
fun shadowedUse(b: Box, a: Int) =
|
|
51
|
+
for i := range 3
|
|
52
|
+
g := |a| a + 1
|
|
53
|
+
b.n = b.n + a + g(i)
|
|
54
|
+
|
|
55
|
+
fun sourceWithOddText(b: Box) =
|
|
56
|
+
for c := range ["é \"quoted\" (", "line, :", "ü"]
|
|
57
|
+
b.n = b.n + c.length()
|
|
58
|
+
|
|
59
|
+
test "a closure parameter named like a local the loop also uses does not hide it"
|
|
60
|
+
b := Box(n: 0)
|
|
61
|
+
shadowedUse(b, 100)
|
|
62
|
+
assert b.n == 306
|
|
63
|
+
|
|
64
|
+
test "a for source with quotes, brackets and unicode"
|
|
65
|
+
b := Box(n: 0)
|
|
66
|
+
sourceWithOddText(b)
|
|
67
|
+
assert b.n > 0
|
|
68
|
+
|
|
69
|
+
test "nested loops write through a mut field of self"
|
|
70
|
+
b := Box(n: 0)
|
|
71
|
+
b.fill(4)
|
|
72
|
+
assert b.n == 18
|
|
73
|
+
|
|
74
|
+
test "a while condition is evaluated again on every pass"
|
|
75
|
+
b := Box(n: 18)
|
|
76
|
+
b.drain()
|
|
77
|
+
assert b.n == -3
|
|
78
|
+
|
|
79
|
+
test "a while that is false at the start runs no pass"
|
|
80
|
+
b := Box(n: 0)
|
|
81
|
+
b.drain()
|
|
82
|
+
assert b.n == 0
|
|
83
|
+
|
|
84
|
+
test "a loop in a generic function and a generic method"
|
|
85
|
+
assert sumAll([1, 2, 3], |x| x * 2) == 12
|
|
86
|
+
tally := Box(n: 0)
|
|
87
|
+
Gen(items: ["a", "b"]).count(tally)
|
|
88
|
+
assert tally.n == 2
|
|
89
|
+
|
|
90
|
+
test "a loop inside a closure and a closure inside a loop"
|
|
91
|
+
assert inClosure(2) == 14
|
|
92
|
+
assert closureInLoop() == 6
|
|
93
|
+
|
|
94
|
+
test "io and a struct are arguments of the loop"
|
|
95
|
+
b := Box(n: 0)
|
|
96
|
+
writes(io, b)
|
|
97
|
+
assert b.n == 2
|
|
98
|
+
|
|
99
|
+
test "a million passes do not overflow the stack"
|
|
100
|
+
b := Box(n: 1000000)
|
|
101
|
+
while b.n > 0
|
|
102
|
+
b.n = b.n - 1
|
|
103
|
+
assert b.n == 0
|
tests/fbip/aliasing.plum
CHANGED
|
@@ -3,9 +3,6 @@ import std/Str
|
|
|
3
3
|
import std/Slice
|
|
4
4
|
import std/Map
|
|
5
5
|
import std/Array
|
|
6
|
-
import std/Byte
|
|
7
|
-
import std/Float
|
|
8
|
-
import std/game/Vec2
|
|
9
6
|
|
|
10
7
|
# FBIP aliasing tests. Every program here would give a different answer if a spread
|
|
11
8
|
# were wrongly written in place while the old value is still reachable. Each test
|
|
@@ -98,31 +95,6 @@ struct Maker(k: Int) =
|
|
|
98
95
|
|
|
99
96
|
struct Hook(made: fn(Slice[Int]) -> Cell)
|
|
100
97
|
|
|
101
|
-
# ---- Array.with: written in place only for a local array nobody else holds ----
|
|
102
|
-
|
|
103
|
-
struct ArrBox(mut xs: Array[Int], tag: Int)
|
|
104
|
-
|
|
105
|
-
fun firstTo9(a: Array[Int]) -> Array[Int] = a.with(0, 9)
|
|
106
|
-
|
|
107
|
-
fun makeZeros(n: Int) -> Array[Int] = Array.filled(n, 0)
|
|
108
|
-
|
|
109
|
-
fun keepAndSet(xs: Slice[Array[Int]], a: Array[Int]) -> Array[Int] =
|
|
110
|
-
xs.push(a)
|
|
111
|
-
a.with(0, 7)
|
|
112
|
-
|
|
113
|
-
fun lastWith(n: Int) -> Array[Int] =
|
|
114
|
-
a := Array.filled(n, 3)
|
|
115
|
-
a.set(0, 4)
|
|
116
|
-
a.with(n - 1, 8)
|
|
117
|
-
|
|
118
|
-
fun twoDecls(flag: Bool) -> Array[Int] =
|
|
119
|
-
a := Array.filled(2, 0)
|
|
120
|
-
chosen := if flag then a.with(0, 1) else a
|
|
121
|
-
b := chosen
|
|
122
|
-
written := chosen.with(1, 5)
|
|
123
|
-
assert written.get(1) == 5
|
|
124
|
-
b
|
|
125
|
-
|
|
126
98
|
# ---- tests ----
|
|
127
99
|
|
|
128
100
|
test "alias kept then updated"
|
|
@@ -415,148 +387,9 @@ test "a closure field named like a fresh method"
|
|
|
415
387
|
assert z.n == 7
|
|
416
388
|
assert Maker(k: 1).made(lg).n == 100
|
|
417
389
|
|
|
418
|
-
test "array: alias then with"
|
|
419
|
-
a := Array.filled(3, 0)
|
|
420
|
-
b := a
|
|
421
|
-
written := a.with(1, 5)
|
|
422
|
-
assert b.get(1) == 0
|
|
423
|
-
assert written.get(1) == 5
|
|
424
|
-
|
|
425
|
-
test "array: alias taken after with"
|
|
426
|
-
a := Array.filled(3, 0)
|
|
427
|
-
once := a.with(1, 5)
|
|
428
|
-
b := once
|
|
429
|
-
twiceOver := once.with(2, 6)
|
|
430
|
-
assert b.get(2) == 0
|
|
431
|
-
assert b.get(1) == 5
|
|
432
|
-
assert twiceOver.get(2) == 6
|
|
433
|
-
|
|
434
|
-
test "array: with without a rebind leaves the receiver alone"
|
|
435
|
-
a := Array.filled(3, 0)
|
|
436
|
-
b := a.with(0, 1)
|
|
437
|
-
assert a.get(0) == 0
|
|
438
|
-
assert b.get(0) == 1
|
|
439
|
-
|
|
440
|
-
test "array: in a struct field, read through another reference"
|
|
441
|
-
a := Array.filled(3, 0)
|
|
442
|
-
h := ArrBox(xs: a, tag: 1)
|
|
443
|
-
h.xs = h.xs.with(0, 5)
|
|
444
|
-
assert a.get(0) == 0
|
|
445
|
-
assert h.xs.get(0) == 5
|
|
446
|
-
g := h
|
|
447
|
-
h.xs = h.xs.with(1, 6)
|
|
448
|
-
assert g.xs.get(1) == 6
|
|
449
|
-
|
|
450
|
-
test "array: returned from a helper and kept"
|
|
451
|
-
z := makeZeros(3)
|
|
452
|
-
r := firstTo9(z)
|
|
453
|
-
assert z.get(0) == 0
|
|
454
|
-
assert r.get(0) == 9
|
|
455
|
-
written := makeZeros(2).with(1, 4)
|
|
456
|
-
assert written.get(1) == 4
|
|
457
|
-
|
|
458
|
-
test "array: passed to a helper that stores it"
|
|
459
|
-
xs := Slice[Array[Int]]()
|
|
460
|
-
a := Array.filled(2, 0)
|
|
461
|
-
r := keepAndSet(xs, a)
|
|
462
|
-
assert a.get(0) == 0
|
|
463
|
-
assert xs.at(0).get(0) == 0
|
|
464
|
-
assert r.get(0) == 7
|
|
465
|
-
|
|
466
|
-
test "array: stored in a slice before the write"
|
|
467
|
-
xs := Slice[Array[Int]]()
|
|
468
|
-
a := Array.filled(2, 0)
|
|
469
|
-
xs.push(a)
|
|
470
|
-
written := a.with(0, 3)
|
|
471
|
-
assert xs.at(0).get(0) == 0
|
|
472
|
-
assert written.get(0) == 3
|
|
473
|
-
|
|
474
|
-
test "array: captured by a closure before the write"
|
|
475
|
-
a := Array.filled(2, 0)
|
|
476
|
-
f := || a.get(0)
|
|
477
|
-
written := a.with(0, 5)
|
|
478
|
-
assert f() == 5 || f() == 0
|
|
479
|
-
assert written.get(0) == 5
|
|
480
|
-
b := Array.filled(2, 0)
|
|
481
|
-
g := || b.get(0)
|
|
482
|
-
c := b.with(0, 5)
|
|
483
|
-
assert g() == 0
|
|
484
|
-
assert c.get(0) == 5
|
|
485
|
-
|
|
486
|
-
test "array: a loop keeping the previous array"
|
|
487
|
-
a := Array.filled(3, 0)
|
|
488
|
-
snaps := Slice[Array[Int]]()
|
|
489
|
-
last := 0.until(3).fold(a, |cur, i|
|
|
490
|
-
snaps.push(cur)
|
|
491
|
-
cur.with(i, i + 1)
|
|
492
|
-
)
|
|
493
|
-
assert snaps.at(0).get(0) == 0
|
|
494
|
-
assert snaps.at(1).get(0) == 1 && snaps.at(1).get(1) == 0
|
|
495
|
-
assert snaps.at(2).get(1) == 2 && snaps.at(2).get(2) == 0
|
|
496
|
-
assert last.get(2) == 3
|
|
497
|
-
|
|
498
|
-
test "array: a loop with the previous kept in a variable"
|
|
499
|
-
a := Array.filled(3, 0)
|
|
500
|
-
# state: first is the previous array, second the current one
|
|
501
|
-
end := 0.until(3).fold(Pair(a, a), |st, i| Pair(st.second, st.second.with(i, 1)))
|
|
502
|
-
assert end.first.get(2) == 0
|
|
503
|
-
assert end.first.get(1) == 1
|
|
504
|
-
assert end.second.get(2) == 1
|
|
505
|
-
|
|
506
|
-
test "array: with as the last expression"
|
|
507
|
-
a := lastWith(3)
|
|
508
|
-
assert a.get(0) == 4 && a.get(1) == 3 && a.get(2) == 8
|
|
509
|
-
|
|
510
|
-
test "array: a name declared twice"
|
|
511
|
-
a := twoDecls(true)
|
|
512
|
-
assert a.get(0) == 1 && a.get(1) == 0
|
|
513
|
-
b := twoDecls(false)
|
|
514
|
-
assert b.get(0) == 0 && b.get(1) == 0
|
|
515
|
-
|
|
516
|
-
test "array: through a nested with"
|
|
517
|
-
a := Array.filled(3, 0)
|
|
518
|
-
b := a.with(0, a.with(1, 5).get(1))
|
|
519
|
-
assert a.get(0) == 0 && a.get(1) == 0
|
|
520
|
-
assert b.get(0) == 5
|
|
521
|
-
|
|
522
|
-
test "array: from push and resize"
|
|
523
|
-
a := Array[Int]().push(1).push(2)
|
|
524
|
-
b := a
|
|
525
|
-
written := a.with(0, 9)
|
|
526
|
-
assert b.get(0) == 1
|
|
527
|
-
assert written.get(0) == 9
|
|
528
|
-
e := Array[Int]().push(4).with(0, 6)
|
|
529
|
-
assert e.get(0) == 6
|
|
530
|
-
sized := Array[Int]().resize(2).with(1, 3)
|
|
531
|
-
assert sized.get(1) == 3 && sized.length() == 2
|
|
532
|
-
|
|
533
390
|
test "array: an empty array stays empty"
|
|
534
391
|
a := Array[Int]()
|
|
535
392
|
b := a
|
|
536
393
|
resized := a.resize(0)
|
|
537
394
|
assert resized.length() == 0
|
|
538
395
|
assert b.length() == 0
|
|
539
|
-
|
|
540
|
-
test "array: bytes"
|
|
541
|
-
a := Array.filled(3, Byte(7))
|
|
542
|
-
b := a
|
|
543
|
-
written := a.with(1, Byte(200))
|
|
544
|
-
assert b.get(1).toInt() == 7
|
|
545
|
-
assert written.get(1).toInt() == 200
|
|
546
|
-
assert written.get(2).toInt() == 7
|
|
547
|
-
|
|
548
|
-
test "array: vec2 elements"
|
|
549
|
-
a := Array.filled(3, Vec2(x: 1.0, y: 2.0))
|
|
550
|
-
b := a
|
|
551
|
-
written := a.with(1, Vec2(x: 5.0, y: 6.0))
|
|
552
|
-
assert b.get(1).x == 1.0 && b.get(1).y == 2.0
|
|
553
|
-
assert written.get(1).x == 5.0 && written.get(1).y == 6.0
|
|
554
|
-
assert written.get(0).y == 2.0
|
|
555
|
-
|
|
556
|
-
test "array: vec2 stored in a field and a slice"
|
|
557
|
-
a := Array.filled(2, Vec2(x: 1.0, y: 1.0))
|
|
558
|
-
xs := Slice[Array[Vec2]]()
|
|
559
|
-
xs.push(a)
|
|
560
|
-
written := a.with(0, Vec2(x: 9.0, y: 9.0))
|
|
561
|
-
assert xs.at(0).get(0).x == 1.0
|
|
562
|
-
assert written.get(0).x == 9.0
|
tests/fbip/array_in_place.plum
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Float
|
|
3
|
-
import std/Array
|
|
4
|
-
import std/game/Vec2
|
|
5
|
-
|
|
6
|
-
# The hand-overs from aliasing.plum that are proved in place. They live apart because the proof
|
|
7
|
-
# resolves `with` by name, and the shared `with`s in aliasing.plum would stop it here too.
|
|
8
|
-
# Each test asserts the copying answer, so a wrong in-place write changes it.
|
|
9
|
-
|
|
10
|
-
fun doubledUpTo(n: Int, k: Int) -> Array[Int] =
|
|
11
|
-
if k == 0
|
|
12
|
-
Array.filled(n, 1)
|
|
13
|
-
else
|
|
14
|
-
a := doubledUpTo(n, k - 1)
|
|
15
|
-
a.with(k - 1, a.get(k - 1) * 2 + k - 1)
|
|
16
|
-
|
|
17
|
-
fun doubled(n: Int) -> Array[Int] = doubledUpTo(n, n)
|
|
18
|
-
|
|
19
|
-
fun sumOfOthersFirst() -> Array[Int] =
|
|
20
|
-
a := Array.filled(3, 1)
|
|
21
|
-
a.with(0, a.get(1) + a.get(2))
|
|
22
|
-
|
|
23
|
-
fun tenTimesFirstSecond() -> Array[Int] =
|
|
24
|
-
a := sumOfOthersFirst()
|
|
25
|
-
a.with(1, a.get(0) * 10)
|
|
26
|
-
|
|
27
|
-
fun threesUpTo(k: Int) -> Array[Vec2] =
|
|
28
|
-
if k == 0
|
|
29
|
-
Array.filled(2, Vec2(x: 0.0, y: 0.0))
|
|
30
|
-
else
|
|
31
|
-
threesUpTo(k - 1).with(k - 1, Vec2(x: Float(k - 1), y: 3.0))
|
|
32
|
-
|
|
33
|
-
test "array: a unique loop gives the copying answer"
|
|
34
|
-
a := doubled(4)
|
|
35
|
-
assert a.get(0) == 2 && a.get(1) == 3 && a.get(2) == 4 && a.get(3) == 5
|
|
36
|
-
|
|
37
|
-
test "array: with, then the old array read in the argument"
|
|
38
|
-
a := tenTimesFirstSecond()
|
|
39
|
-
assert a.get(0) == 2 && a.get(1) == 20 && a.get(2) == 1
|
|
40
|
-
|
|
41
|
-
test "array: vec2 elements handed over"
|
|
42
|
-
c := threesUpTo(2)
|
|
43
|
-
assert c.get(1).x == 1.0 && c.get(0).y == 3.0
|
tests/fbip/array_names.plum
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Array
|
|
3
|
-
|
|
4
|
-
# Name collisions: the uniqueness pass resolves methods by name, with no types. A user type with
|
|
5
|
-
# its own `with` or `push` that hands back shared storage must keep every array a copy.
|
|
6
|
-
|
|
7
|
-
struct Bag(items: Array[Int]) =
|
|
8
|
-
fun push(self, x: Int) -> Array[Int] = self.items
|
|
9
|
-
fun with(self, i: Int, v: Int) -> Array[Int] = self.items
|
|
10
|
-
|
|
11
|
-
test "array: a user type with its own with and push"
|
|
12
|
-
bag := Bag(items: Array.filled(2, 0))
|
|
13
|
-
a := bag.with(0, 1)
|
|
14
|
-
written := a.with(0, 9)
|
|
15
|
-
assert written.get(0) == 9
|
|
16
|
-
assert bag.items.get(0) == 0
|
|
17
|
-
b := Array.filled(2, 0)
|
|
18
|
-
fresh := b.with(0, 1)
|
|
19
|
-
assert fresh.get(0) == 1
|
|
20
|
-
|
|
21
|
-
test "array: bound to the result of a user push that returns shared storage"
|
|
22
|
-
bag := Bag(items: Array.filled(2, 0))
|
|
23
|
-
a := bag.push(1)
|
|
24
|
-
written := a.with(0, 9)
|
|
25
|
-
assert written.get(0) == 9
|
|
26
|
-
assert bag.items.get(0) == 0
|
|
27
|
-
# a name that is fresh on one path and holds shared storage on the other
|
|
28
|
-
picked := if bag.items.length() == 0 then Array.filled(2, 5) else bag.push(1)
|
|
29
|
-
over := picked.with(1, 9)
|
|
30
|
-
assert over.get(1) == 9
|
|
31
|
-
assert bag.items.get(1) == 0
|
tests/fbip/array_with.plum
DELETED
|
@@ -1,225 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Float
|
|
3
|
-
import std/Array
|
|
4
|
-
import std/Slice
|
|
5
|
-
import std/Pair
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
|
|
8
|
-
# `Array.with` on arrays held in struct fields. A `with` writes in place only when the struct is
|
|
9
|
-
# provably unshared and the array is held by no one else; each test would give a different answer if
|
|
10
|
-
# a write went through a second holder. The sweep runs this file with the default and `--no-fbip`.
|
|
11
|
-
# The proof names fields and methods without types, so every scenario has its own field and
|
|
12
|
-
# method names: one shared call or alias would (rightly) stop the whole name.
|
|
13
|
-
|
|
14
|
-
# ---- the persistent vector shape: a spread rebuilding its own array ----
|
|
15
|
-
|
|
16
|
-
struct Vec(cells: Array[Int], n: Int) =
|
|
17
|
-
fun put(self, i: Int, x: Int) -> Vec = Vec(..self, cells: self.cells.with(i, x))
|
|
18
|
-
fun append(self, x: Int) -> Vec = Vec(..self, cells: self.cells.with(self.n, x), n: self.n + 1)
|
|
19
|
-
fun get(self, i: Int) -> Int = self.cells.get(i)
|
|
20
|
-
fun length(self) -> Int = self.n
|
|
21
|
-
|
|
22
|
-
fun newVec(cap: Int) -> Vec = Vec(cells: Array.filled(cap, 0), n: 0)
|
|
23
|
-
|
|
24
|
-
fun fillUpTo(cap: Int, k: Int) -> Vec =
|
|
25
|
-
if k == 0 then newVec(cap) else fillUpTo(cap, k - 1).append({k - 1} * 3)
|
|
26
|
-
|
|
27
|
-
fun fillVec(n: Int) -> Vec = fillUpTo(n, n)
|
|
28
|
-
|
|
29
|
-
fun bumpAll(v: Vec) -> Vec =
|
|
30
|
-
0.until(v.length()).fold(v, |cur, i| cur.put(i, cur.get(i) + 1))
|
|
31
|
-
|
|
32
|
-
# ---- a `mut` field rebuilt with an assign-back ----
|
|
33
|
-
|
|
34
|
-
struct MVec(mut mcells: Array[Int], mn: Int) =
|
|
35
|
-
fun mput(self, i: Int, x: Int) -> Unit =
|
|
36
|
-
self.mcells = self.mcells.with(i, x)
|
|
37
|
-
fun mget(self, i: Int) -> Int = self.mcells.get(i)
|
|
38
|
-
|
|
39
|
-
# ---- hostile: each has its own names ----
|
|
40
|
-
|
|
41
|
-
struct AVec(lanes: Array[Int], an: Int) =
|
|
42
|
-
fun aput(self, i: Int, x: Int) -> AVec = AVec(..self, lanes: self.lanes.with(i, x))
|
|
43
|
-
fun aget(self, i: Int) -> Int = self.lanes.get(i)
|
|
44
|
-
fun lanesOf(self) -> Array[Int] = self.lanes
|
|
45
|
-
|
|
46
|
-
struct SVec(slots: Array[Int], sn: Int) =
|
|
47
|
-
fun sput(self, i: Int, x: Int) -> SVec = SVec(..self, slots: self.slots.with(i, x))
|
|
48
|
-
fun sget(self, i: Int) -> Int = self.slots.get(i)
|
|
49
|
-
|
|
50
|
-
struct EVec(ecells: Array[Int], en: Int) =
|
|
51
|
-
fun eput(self, i: Int, x: Int) -> EVec = EVec(..self, ecells: self.ecells.with(i, x))
|
|
52
|
-
fun eget(self, i: Int) -> Int = self.ecells.get(i)
|
|
53
|
-
|
|
54
|
-
struct CVec(ccells: Array[Int], cn: Int) =
|
|
55
|
-
fun cput(self, i: Int, x: Int) -> CVec = CVec(..self, ccells: self.ccells.with(i, x))
|
|
56
|
-
fun cget(self, i: Int) -> Int = self.ccells.get(i)
|
|
57
|
-
|
|
58
|
-
struct GVec(gcells: Array[Int], gn: Int) =
|
|
59
|
-
fun gput(self, i: Int, x: Int) -> GVec = GVec(..self, gcells: self.gcells.with(i, x))
|
|
60
|
-
fun gget(self, i: Int) -> Int = self.gcells.get(i)
|
|
61
|
-
|
|
62
|
-
fun stash(xs: Slice[GVec], v: GVec) -> GVec =
|
|
63
|
-
xs.push(v)
|
|
64
|
-
v.gput(0, 7)
|
|
65
|
-
|
|
66
|
-
struct HVec(hcells: Array[Int], hn: Int) =
|
|
67
|
-
fun hput(self, i: Int, x: Int) -> HVec = HVec(..self, hcells: self.hcells.with(i, x))
|
|
68
|
-
fun hget(self, i: Int) -> Int = self.hcells.get(i)
|
|
69
|
-
|
|
70
|
-
struct IVec(icells: Array[Int], iprev: Int) =
|
|
71
|
-
fun iput(self, i: Int, x: Int) -> IVec = IVec(..self, icells: self.icells.with(i, x))
|
|
72
|
-
fun iget(self, i: Int) -> Int = self.icells.get(i)
|
|
73
|
-
|
|
74
|
-
struct PVec(pcells: Array[Vec2], pn: Int) =
|
|
75
|
-
fun pput(self, i: Int, p: Vec2) -> PVec = PVec(..self, pcells: self.pcells.with(i, p))
|
|
76
|
-
fun pget(self, i: Int) -> Vec2 = self.pcells.get(i)
|
|
77
|
-
|
|
78
|
-
struct QVec(qcells: Array[Int], qn: Int) =
|
|
79
|
-
fun qput(self, i: Int, x: Int) -> QVec = QVec(..self, qcells: self.qcells.with(i, x))
|
|
80
|
-
fun qget(self, i: Int) -> Int = self.qcells.get(i)
|
|
81
|
-
fun qpeek(self, i: Int) -> QVec = QVec(..self, qcells: self.qcells.with(i, self.qcells.get(0) + 1), qn: self.qcells.get(i))
|
|
82
|
-
|
|
83
|
-
struct WVec(wcells: Array[Vec2], wn: Int) =
|
|
84
|
-
fun wput(self, i: Int, p: Vec2) -> WVec = WVec(..self, wcells: self.wcells.with(i, p))
|
|
85
|
-
fun wget(self, i: Int) -> Vec2 = self.wcells.get(i)
|
|
86
|
-
|
|
87
|
-
fun gridUpTo(n: Int, k: Int) -> WVec =
|
|
88
|
-
if k == 0
|
|
89
|
-
WVec(wcells: Array.filled(n, Vec2(x: 0.0, y: 0.0)), wn: n)
|
|
90
|
-
else
|
|
91
|
-
gridUpTo(n, k - 1).wput(k - 1, Vec2(x: Float(k - 1), y: Float(k - 1) * 2.0))
|
|
92
|
-
|
|
93
|
-
fun grid(n: Int) -> WVec = gridUpTo(n, n)
|
|
94
|
-
|
|
95
|
-
struct Outer(mut inner: Vec, tag: Int)
|
|
96
|
-
|
|
97
|
-
struct RVec(rcells: Array[Int], rn: Int) =
|
|
98
|
-
fun rput(self, i: Int, x: Int) -> RVec = RVec(..self, rcells: self.rcells.with(i, x), rn: self.rcells.get(i))
|
|
99
|
-
fun rget(self, i: Int) -> Int = self.rcells.get(i)
|
|
100
|
-
|
|
101
|
-
# ---- tests ----
|
|
102
|
-
|
|
103
|
-
test "vec: append in a loop"
|
|
104
|
-
v := fillVec(5)
|
|
105
|
-
assert v.length() == 5
|
|
106
|
-
assert v.get(0) == 0 && v.get(2) == 6 && v.get(4) == 12
|
|
107
|
-
|
|
108
|
-
test "vec: put through a helper"
|
|
109
|
-
v := bumpAll(fillVec(4))
|
|
110
|
-
assert v.get(0) == 1 && v.get(3) == 10
|
|
111
|
-
|
|
112
|
-
test "vec: the old vector kept while the new one is built"
|
|
113
|
-
v := fillVec(3)
|
|
114
|
-
old := v
|
|
115
|
-
w := v.put(0, 99)
|
|
116
|
-
assert old.get(0) == 0
|
|
117
|
-
assert w.get(0) == 99
|
|
118
|
-
|
|
119
|
-
test "vec: kept by a helper argument"
|
|
120
|
-
a := fillVec(3)
|
|
121
|
-
b := bumpAll(a)
|
|
122
|
-
assert a.get(1) == 3
|
|
123
|
-
assert b.get(1) == 4
|
|
124
|
-
|
|
125
|
-
test "vec: a vector in a mut field"
|
|
126
|
-
o := Outer(inner: fillVec(3), tag: 1)
|
|
127
|
-
keep := o.inner
|
|
128
|
-
o.inner = o.inner.put(0, 5)
|
|
129
|
-
assert keep.get(0) == 0
|
|
130
|
-
assert o.inner.get(0) == 5
|
|
131
|
-
|
|
132
|
-
test "mut field: assign-back rebuild"
|
|
133
|
-
m := MVec(mcells: Array.filled(3, 0), mn: 3)
|
|
134
|
-
m.mput(1, 4)
|
|
135
|
-
m.mput(2, 5)
|
|
136
|
-
assert m.mget(1) == 4 && m.mget(2) == 5 && m.mget(0) == 0
|
|
137
|
-
|
|
138
|
-
test "alias of the field kept before the update"
|
|
139
|
-
v := AVec(lanes: Array.filled(3, 0), an: 3)
|
|
140
|
-
d := v.lanesOf()
|
|
141
|
-
w := v.aput(0, 9)
|
|
142
|
-
assert d.get(0) == 0
|
|
143
|
-
assert w.aget(0) == 9
|
|
144
|
-
|
|
145
|
-
test "alias of the field read directly"
|
|
146
|
-
v := AVec(lanes: Array.filled(3, 0), an: 3)
|
|
147
|
-
d := v.lanes
|
|
148
|
-
w := v.aput(1, 7)
|
|
149
|
-
assert d.get(1) == 0
|
|
150
|
-
assert w.aget(1) == 7
|
|
151
|
-
|
|
152
|
-
test "two structs sharing one array"
|
|
153
|
-
arr := Array.filled(3, 0)
|
|
154
|
-
b := SVec(slots: arr, sn: 0)
|
|
155
|
-
written := SVec(slots: arr, sn: 0).sput(0, 5)
|
|
156
|
-
assert b.sget(0) == 0
|
|
157
|
-
assert arr.get(0) == 0
|
|
158
|
-
assert written.sget(0) == 5
|
|
159
|
-
|
|
160
|
-
test "the vector itself aliased"
|
|
161
|
-
v := EVec(ecells: Array.filled(3, 0), en: 0)
|
|
162
|
-
w := v
|
|
163
|
-
u := v.eput(1, 6)
|
|
164
|
-
assert w.eget(1) == 0
|
|
165
|
-
assert u.eget(1) == 6
|
|
166
|
-
|
|
167
|
-
test "the vector captured by a closure"
|
|
168
|
-
v := CVec(ccells: Array.filled(3, 0), cn: 0)
|
|
169
|
-
f := || v.cget(0)
|
|
170
|
-
w := v.cput(0, 4)
|
|
171
|
-
assert f() == 0
|
|
172
|
-
assert w.cget(0) == 4
|
|
173
|
-
|
|
174
|
-
test "the vector stored by a helper then updated"
|
|
175
|
-
xs := Slice[GVec]()
|
|
176
|
-
v := GVec(gcells: Array.filled(2, 0), gn: 0)
|
|
177
|
-
r := stash(xs, v)
|
|
178
|
-
assert xs.at(0).gget(0) == 0
|
|
179
|
-
assert v.gget(0) == 0
|
|
180
|
-
assert r.gget(0) == 7
|
|
181
|
-
|
|
182
|
-
test "a loop keeping every previous vector"
|
|
183
|
-
snaps := Slice[HVec]()
|
|
184
|
-
v := HVec(hcells: Array.filled(3, 0), hn: 0)
|
|
185
|
-
last := 0.until(3).fold(v, |cur, i|
|
|
186
|
-
snaps.push(cur)
|
|
187
|
-
cur.hput(i, i + 1)
|
|
188
|
-
)
|
|
189
|
-
assert snaps.at(0).hget(0) == 0
|
|
190
|
-
assert snaps.at(1).hget(0) == 1 && snaps.at(1).hget(1) == 0
|
|
191
|
-
assert snaps.at(2).hget(1) == 2 && snaps.at(2).hget(2) == 0
|
|
192
|
-
assert last.hget(2) == 3
|
|
193
|
-
|
|
194
|
-
test "a loop where the previous vector lives in a variable"
|
|
195
|
-
prev := IVec(icells: Array.filled(3, 0), iprev: 0)
|
|
196
|
-
v := prev
|
|
197
|
-
# state: first is the previous vector, second the current one
|
|
198
|
-
end := 0.until(3).fold(Pair(prev, v), |st, i| Pair(st.second, st.second.iput(i, 1)))
|
|
199
|
-
assert end.first.iget(1) == 1 && end.first.iget(2) == 0
|
|
200
|
-
assert end.second.iget(2) == 1
|
|
201
|
-
|
|
202
|
-
test "vec2 elements"
|
|
203
|
-
v := PVec(pcells: Array.filled(3, Vec2(x: 1.0, y: 2.0)), pn: 3)
|
|
204
|
-
w := v
|
|
205
|
-
once := v.pput(1, Vec2(x: 5.0, y: 6.0))
|
|
206
|
-
assert w.pget(1).x == 1.0 && w.pget(1).y == 2.0
|
|
207
|
-
assert once.pget(1).x == 5.0 && once.pget(1).y == 6.0 && once.pget(0).y == 2.0
|
|
208
|
-
all := 0.until(3).fold(once, |cur, i| cur.pput(i, Vec2(x: Float(i), y: 0.5)))
|
|
209
|
-
assert all.pget(2).x == 2.0 && all.pget(2).y == 0.5
|
|
210
|
-
|
|
211
|
-
test "another field of the spread reads the array after the write"
|
|
212
|
-
v := QVec(qcells: Array.filled(3, 4), qn: 0)
|
|
213
|
-
w := v.qpeek(1)
|
|
214
|
-
assert w.qn == 4
|
|
215
|
-
assert w.qget(1) == 5
|
|
216
|
-
assert v.qget(1) == 4
|
|
217
|
-
|
|
218
|
-
test "another field reads the old element"
|
|
219
|
-
w := RVec(rcells: Array.filled(3, 4), rn: 0).rput(1, 9)
|
|
220
|
-
assert w.rn == 4
|
|
221
|
-
assert w.rget(1) == 9
|
|
222
|
-
|
|
223
|
-
test "vec2 elements written in place"
|
|
224
|
-
g := grid(4)
|
|
225
|
-
assert g.wget(0).x == 0.0 && g.wget(3).x == 3.0 && g.wget(3).y == 6.0 && g.wget(2).y == 4.0
|
tests/fbip/fip.plum
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import std/Int
|
|
2
|
-
import std/
|
|
2
|
+
import std/Str
|
|
3
3
|
|
|
4
|
-
# `fip fun` forms that must compile: every spread
|
|
4
|
+
# `fip fun` forms that must compile: every spread written in the body is
|
|
5
5
|
# proved in place. The sweep also runs this file with `--no-fbip` and `--no-fusion`, where `fip`
|
|
6
6
|
# is not enforced and the programs still give the same answers. Names are unique per scenario
|
|
7
7
|
# because the proof resolves methods and fields by name.
|
|
@@ -9,15 +9,6 @@ import std/Array
|
|
|
9
9
|
# a fip fun with no update at all is trivially true
|
|
10
10
|
fip fun plainSum(a: Int, b: Int) -> Int = a + b
|
|
11
11
|
|
|
12
|
-
# a fresh array written once
|
|
13
|
-
fip fun freshWrite() -> Array[Int] = Array.filled(3, 0).with(1, 7)
|
|
14
|
-
|
|
15
|
-
# a local array written once per step of a recursion
|
|
16
|
-
fip fun squaresUpTo(n: Int, k: Int) -> Array[Int] =
|
|
17
|
-
if k == 0 then Array.filled(n, 0) else squaresUpTo(n, k - 1).with(k - 1, {k - 1} * {k - 1})
|
|
18
|
-
|
|
19
|
-
fun squares(n: Int) -> Array[Int] = squaresUpTo(n, n)
|
|
20
|
-
|
|
21
12
|
# a spread of a parameter every caller builds fresh
|
|
22
13
|
struct Pt(px: Int, py: Int)
|
|
23
14
|
|
|
@@ -27,44 +18,19 @@ fun walkPt(n: Int) -> Pt =
|
|
|
27
18
|
if n == 0 then Pt(px: 0, py: 5) else movePt(walkPt(n - 1), 2)
|
|
28
19
|
|
|
29
20
|
# a fip method: self handed on from the recursive call
|
|
30
|
-
struct Bag(
|
|
21
|
+
struct Bag(label: Str, count: Int) =
|
|
31
|
-
fip fun bagAdd(self,
|
|
22
|
+
fip fun bagAdd(self, x: Int) -> Bag = Bag(..self, count: self.count + x)
|
|
32
|
-
fun bagAt(self, i: Int) -> Int = self.items.get(i)
|
|
33
|
-
|
|
34
|
-
fun fillBagUpTo(n: Int, k: Int) -> Bag =
|
|
35
|
-
if k == 0 then Bag(items: Array.filled(n, 0), count: 0) else fillBagUpTo(n, k - 1).bagAdd(k - 1, k + 9)
|
|
36
|
-
|
|
37
|
-
fun fillBag(n: Int) -> Bag = fillBagUpTo(n, n)
|
|
38
23
|
|
|
39
|
-
# a fip fun whose update sits in a closure-free helper chain
|
|
40
|
-
|
|
24
|
+
fun fillBagUpTo(k: Int) -> Bag =
|
|
41
|
-
|
|
42
|
-
# a generic fip fun
|
|
43
|
-
|
|
25
|
+
if k == 0 then Bag(label: "b", count: 0) else fillBagUpTo(k - 1).bagAdd(k + 9)
|
|
44
26
|
|
|
45
27
|
test "fip: plain"
|
|
46
28
|
assert plainSum(2, 3) == 5
|
|
47
29
|
|
|
48
|
-
test "fip: fresh array write"
|
|
49
|
-
a := freshWrite()
|
|
50
|
-
assert a.get(0) == 0 && a.get(1) == 7
|
|
51
|
-
|
|
52
|
-
test "fip: loop of writes"
|
|
53
|
-
a := squares(5)
|
|
54
|
-
assert a.get(3) == 9 && a.get(4) == 16
|
|
55
|
-
|
|
56
30
|
test "fip: spread of a fresh parameter"
|
|
57
31
|
p := walkPt(4)
|
|
58
32
|
assert p.px == 8 && p.py == 5
|
|
59
33
|
|
|
60
34
|
test "fip: method"
|
|
61
|
-
b :=
|
|
35
|
+
b := fillBagUpTo(4)
|
|
62
|
-
assert b.
|
|
36
|
+
assert b.count == 10 + 11 + 12 + 13 && b.label == "b"
|
|
63
|
-
|
|
64
|
-
test "fip: read then write"
|
|
65
|
-
a := bumpAt(Array.filled(2, 4), 1)
|
|
66
|
-
assert a.get(1) == 5 && a.get(0) == 4
|
|
67
|
-
|
|
68
|
-
test "fip: generic"
|
|
69
|
-
a := setFirst(Array.filled(2, 1), 9)
|
|
70
|
-
assert a.get(0) == 9 && a.get(1) == 1
|
tests/fbip/fuzz/gen.pl
CHANGED
|
@@ -1,118 +1,118 @@
|
|
|
1
1
|
#!/usr/bin/perl
|
|
2
|
+
# Generates one random program for the differential fuzzer (see fuzz.sh).
|
|
3
|
+
# Locals can't be reassigned, so every statement binds a fresh name (v0, v1, ...
|
|
4
|
+
# for P values, w0, w1, ... for Q values) built from earlier ones by aliasing,
|
|
5
|
+
# spreads, method and function calls, `mut` field stores and a Slice. A wrong
|
|
6
|
+
# in-place proof shows as a different dump with and without --no-fbip.
|
|
2
7
|
use strict; use warnings;
|
|
3
8
|
my ($seed, $out) = @ARGV;
|
|
4
9
|
srand($seed);
|
|
5
10
|
sub r { return int(rand($_[0])); }
|
|
6
11
|
sub pick { return $_[r(scalar @_)]; }
|
|
7
|
-
my @arr = ('a','b','c','d','e');
|
|
8
|
-
my @
|
|
12
|
+
my @vs = ('v0', 'v1', 'v2');
|
|
9
|
-
|
|
13
|
+
my @ws = ('w0', 'w1');
|
|
10
|
-
|
|
14
|
+
my ($nv, $nw) = (3, 2);
|
|
11
|
-
}
|
|
12
15
|
sub iexpr {
|
|
13
|
-
my $k = r(
|
|
16
|
+
my $k = r(7);
|
|
14
17
|
return r(5) if $k == 0;
|
|
15
|
-
return pick(@
|
|
18
|
+
return pick(@vs).".a" if $k <= 2;
|
|
16
|
-
return pick(@
|
|
19
|
+
return pick(@vs).".b" if $k == 3;
|
|
17
|
-
return pick(@st).".g.get(".r(3).")" if $k == 4;
|
|
18
|
-
return pick(@
|
|
20
|
+
return pick(@ws).".n" if $k == 4;
|
|
19
|
-
return pick(@
|
|
21
|
+
return pick(@ws).".p.a" if $k == 5;
|
|
20
|
-
return "m.f.get(".r(3).")" if $k == 7;
|
|
21
|
-
return
|
|
22
|
+
return "m.p.b";
|
|
22
23
|
}
|
|
23
|
-
sub idx { return r(3); }
|
|
24
24
|
my @stmts;
|
|
25
|
-
for my $n (1..(6+r(
|
|
25
|
+
for my $n (1..(6+r(12))) {
|
|
26
|
-
my $A = pick(@arr); my $B = pick(@arr); my $S = pick(@st); my $T = pick(@st);
|
|
27
|
-
my $k = r(
|
|
26
|
+
my $k = r(30);
|
|
28
|
-
my %alias = map { $_ => 1 } (2,8,9,10,17,18,19,20,21,22,25,26,4,15,12,1,30);
|
|
29
|
-
while ($alias{$k} && r(100) >= 12) { $k = r(34); }
|
|
30
27
|
my $s;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
elsif ($k==
|
|
36
|
-
elsif ($k==
|
|
37
|
-
elsif ($k==
|
|
38
|
-
elsif ($k==
|
|
39
|
-
elsif ($k==
|
|
40
|
-
elsif ($k==
|
|
41
|
-
elsif ($k==
|
|
42
|
-
elsif ($k==
|
|
43
|
-
elsif ($k==
|
|
44
|
-
elsif ($k==
|
|
45
|
-
elsif ($k==
|
|
46
|
-
elsif ($k==
|
|
47
|
-
elsif ($k==
|
|
48
|
-
elsif ($k==
|
|
49
|
-
elsif ($k==
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
elsif ($k==
|
|
54
|
-
elsif ($k==
|
|
55
|
-
elsif ($k==
|
|
56
|
-
elsif ($k==
|
|
57
|
-
elsif ($k==
|
|
58
|
-
elsif ($k==
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
elsif ($k==
|
|
62
|
-
elsif ($k==
|
|
63
|
-
elsif ($k==
|
|
64
|
-
|
|
28
|
+
my $V = pick(@vs); my $V2 = pick(@vs); my $W = pick(@ws);
|
|
29
|
+
my ($nvn, $nwn) = ("v$nv", "w$nw");
|
|
30
|
+
my $isv = 1;
|
|
31
|
+
if ($k==0) { $s = "$V2"; }
|
|
32
|
+
elsif ($k==1) { $s = "P(..$V, a: ".iexpr().")"; }
|
|
33
|
+
elsif ($k==2) { $s = "P(..$V, a: ".iexpr().", b: ".iexpr().")"; }
|
|
34
|
+
elsif ($k==3) { $s = "P(..$V, b: $V.a + $V2.b)"; }
|
|
35
|
+
elsif ($k==4) { $s = "bump($V)"; }
|
|
36
|
+
elsif ($k==5) { $s = "$V.inc()"; }
|
|
37
|
+
elsif ($k==6) { $s = "$V.inc().inc()"; }
|
|
38
|
+
elsif ($k==7) { $s = "pass($V, $V2)"; }
|
|
39
|
+
elsif ($k==8) { $s = "$W.p"; }
|
|
40
|
+
elsif ($k==9) { $s = "m.p"; }
|
|
41
|
+
elsif ($k==10) { $s = "xs.at(".r(2).")"; }
|
|
42
|
+
elsif ($k==11) { $s = "if ".iexpr()." > 1 then P(..$V, a: 9) else $V2"; }
|
|
43
|
+
elsif ($k==12) { $s = "mk(".iexpr().", ".iexpr().")"; }
|
|
44
|
+
elsif ($k==13) { $s = "$W.p.inc()"; }
|
|
45
|
+
elsif ($k==14) { $s = "repl($W, $V)"; }
|
|
46
|
+
elsif ($k==15) { $s = "bump(bump($V))"; }
|
|
47
|
+
else { $isv = 0; }
|
|
48
|
+
if ($isv) { push @stmts, "$nvn := $s"; push @vs, $nvn; $nv++; next; }
|
|
49
|
+
if ($k==16) { $s = "Q(p: $V, n: ".r(4).")"; }
|
|
50
|
+
elsif ($k==17) { $s = "Q(..$W, p: $V)"; }
|
|
51
|
+
elsif ($k==18) { $s = "Q(..$W, p: $W.p.inc())"; }
|
|
52
|
+
elsif ($k==19) { $s = "Q(..$W, n: $W.n + 1)"; }
|
|
53
|
+
elsif ($k==20) { $s = "$W.bumped()"; }
|
|
54
|
+
elsif ($k==21) { $s = "wrap($V)"; }
|
|
55
|
+
elsif ($k==22) { $s = "ys.at(".r(2).")"; }
|
|
56
|
+
if ($k >= 16 && $k <= 22) { push @stmts, "$nwn := $s"; push @ws, $nwn; $nw++; next; }
|
|
57
|
+
if ($k==23) { $s = "m.p = $V"; }
|
|
58
|
+
elsif ($k==24) { $s = "m.p = m.p.inc()"; }
|
|
59
|
+
elsif ($k==25) { $s = "m.p = pass(m.p, $V)"; }
|
|
60
|
+
elsif ($k==26) { $s = "xs.push($V)"; }
|
|
61
|
+
elsif ($k==27) { $s = "ys.push($W)"; }
|
|
62
|
+
elsif ($k==28) { $s = "for i := range ".(1+r(3))."\n m.p = mk(m.p.a + i, m.p.b)"; }
|
|
63
|
+
else { $s = "for q := range xs\n m.p = mk(m.p.a, m.p.b + q.a)"; }
|
|
65
64
|
push @stmts, $s;
|
|
66
65
|
}
|
|
67
66
|
my $body = join("\n ", @stmts);
|
|
68
|
-
my $dump = "
|
|
69
|
-
|
|
70
|
-
for my $v (@
|
|
71
|
-
|
|
67
|
+
my $dump = "";
|
|
68
|
+
my $i = 0;
|
|
69
|
+
for my $v (@vs) { $dump .= " o$i := $v.show()\n"; $i++; }
|
|
70
|
+
for my $w (@ws) { $dump .= " o$i := $w.show()\n"; $i++; }
|
|
71
|
+
$dump .= " oM := m.p.show()\n oX := xs.at(0).show() + xs.at(1).show() + ys.at(0).show() + ys.at(1).show()\n";
|
|
72
|
+
my $join = join(" + ", (map { "o$_" } 0..($i-1)), "oM", "oX");
|
|
73
|
+
$dump .= " assert $join == \"\"\n";
|
|
72
74
|
open(my $fh, '>', $out) or die;
|
|
73
75
|
print $fh <<"EOP";
|
|
74
76
|
import std/Int
|
|
75
77
|
import std/Str
|
|
76
|
-
import std/Array
|
|
77
78
|
import std/Slice
|
|
78
79
|
|
|
79
|
-
struct
|
|
80
|
+
struct P(a: Int, b: Int, tag: Str) =
|
|
80
|
-
fun put(self, i: Int, x: Int) -> S = S(..self, f: self.f.with(i, x))
|
|
81
|
-
fun total(self) -> Int = self.f.get(0) + self.g.get(1) + self.n
|
|
82
|
-
fun view(self) -> S = self
|
|
83
|
-
fun fOf(self) -> Array[Int] = self.f
|
|
84
|
-
fun bump(self) -> S = S(..self, g: self.g.with(2, self.total()), n: self.n + 1)
|
|
85
|
-
fun add(self, o: S) -> S = S(..self, f: self.f.with(0, o.n))
|
|
86
|
-
fun
|
|
81
|
+
fun inc(self) -> P = P(..self, a: self.a + 1)
|
|
82
|
+
fun show(self) -> Str = "P(" + self.a.toStr() + "," + self.b.toStr() + "," + self.tag + ");"
|
|
83
|
+
|
|
84
|
+
struct Q(p: P, n: Int) =
|
|
85
|
+
fun bumped(self) -> Q = Q(..self, n: self.n + 1, p: self.p.inc())
|
|
86
|
+
fun show(self) -> Str = "Q(" + self.p.show() + self.n.toStr() + ");"
|
|
87
|
+
|
|
88
|
+
struct M(mut p: P)
|
|
87
89
|
|
|
88
|
-
|
|
90
|
+
fun mk(a: Int, b: Int) -> P = P(a: a, b: b, tag: "mk")
|
|
89
91
|
|
|
90
|
-
fun
|
|
92
|
+
fun bump(p: P) -> P = P(..p, a: p.a + 1)
|
|
91
93
|
|
|
92
|
-
fun pass(x:
|
|
94
|
+
fun pass(x: P, y: P) -> P = if x.a > 2 then x else P(..y, b: 3)
|
|
93
95
|
|
|
94
|
-
fun
|
|
96
|
+
fun repl(w: Q, p: P) -> P =
|
|
97
|
+
q := Q(..w, p: p)
|
|
98
|
+
q.p
|
|
95
99
|
|
|
96
|
-
fun
|
|
100
|
+
fun wrap(p: P) -> Q = Q(p: p, n: 0)
|
|
97
|
-
name + "=" + x.toStr() + "," + y.toStr() + "," + z.toStr() + ";"
|
|
98
101
|
|
|
99
102
|
test "fuzz"
|
|
100
|
-
a := Array.filled(3, 1)
|
|
101
|
-
b := Array.filled(3, 2)
|
|
102
|
-
c := Array.filled(3, 3)
|
|
103
|
-
|
|
103
|
+
v0 := P(a: 1, b: 2, tag: "x")
|
|
104
|
-
|
|
104
|
+
v1 := P(a: 3, b: 4, tag: "y")
|
|
105
|
+
v2 := P(a: 5, b: 6, tag: "z")
|
|
105
|
-
|
|
106
|
+
w0 := Q(p: P(a: 7, b: 8, tag: "q"), n: 1)
|
|
106
|
-
|
|
107
|
+
w1 := Q(p: P(a: 9, b: 10, tag: "r"), n: 2)
|
|
107
|
-
|
|
108
|
+
m := M(p: P(a: 11, b: 12, tag: "m"))
|
|
108
|
-
m := M(f: Array.filled(3, 8))
|
|
109
|
-
xs := Slice[
|
|
109
|
+
xs := Slice[P]()
|
|
110
|
-
xs.push(
|
|
110
|
+
xs.push(P(a: 13, b: 14, tag: "s"))
|
|
111
|
-
xs.push(
|
|
111
|
+
xs.push(P(a: 15, b: 16, tag: "t"))
|
|
112
|
-
ys := Slice[
|
|
112
|
+
ys := Slice[Q]()
|
|
113
|
-
ys.push(
|
|
113
|
+
ys.push(Q(p: P(a: 17, b: 18, tag: "u"), n: 3))
|
|
114
|
-
ys.push(
|
|
114
|
+
ys.push(Q(p: P(a: 19, b: 20, tag: "w"), n: 4))
|
|
115
115
|
$body
|
|
116
116
|
$dump
|
|
117
117
|
EOP
|
|
118
|
-
close $fh;
|
|
118
|
+
close $fh;
|
tests/fbip/operator_methods.plum
CHANGED
|
@@ -1,36 +1,40 @@
|
|
|
1
1
|
import std/Int
|
|
2
|
-
import std/
|
|
2
|
+
import std/Str
|
|
3
3
|
|
|
4
4
|
# `x + y`, `-x`, `x == y`, `x < y` call the methods `add`, `neg`, `eq`, `lt` with no visible call
|
|
5
|
-
# site. Their `self` and parameters can be shared, so a spread
|
|
5
|
+
# site. Their `self` and parameters can be shared, so a spread inside them must copy.
|
|
6
|
+
# `label: Str` keeps each struct boxed (a flat struct could never be shared).
|
|
6
7
|
|
|
7
|
-
struct OpA(
|
|
8
|
+
struct OpA(label: Str, an: Int) =
|
|
8
|
-
fun add(self, o: OpA) -> OpA = OpA(..self,
|
|
9
|
+
fun add(self, o: OpA) -> OpA = OpA(..self, an: o.an)
|
|
9
10
|
|
|
10
|
-
struct OpB(
|
|
11
|
+
struct OpB(label: Str, bn: Int) =
|
|
11
|
-
fun neg(self) -> OpB = OpB(..self,
|
|
12
|
+
fun neg(self) -> OpB = OpB(..self, bn: 99)
|
|
12
13
|
|
|
13
|
-
struct OpC(
|
|
14
|
+
struct OpC(label: Str, cn: Int) =
|
|
14
15
|
fun sub(self, o: OpC) -> OpC = OpC(..o, cn: self.cn - o.cn)
|
|
15
|
-
fun mul(self, o: OpC) -> OpC = OpC(..self,
|
|
16
|
+
fun mul(self, o: OpC) -> OpC = OpC(..self, cn: o.cn)
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
test "add writes through self"
|
|
19
|
-
x := OpA(
|
|
20
|
+
x := OpA(label: "a", an: 5)
|
|
20
|
-
y := OpA(
|
|
21
|
+
y := OpA(label: "a", an: 7)
|
|
21
22
|
z := x + y
|
|
22
|
-
assert x.
|
|
23
|
+
assert x.an == 5
|
|
23
|
-
assert z.
|
|
24
|
+
assert z.an == 7
|
|
24
25
|
|
|
25
26
|
test "neg writes through self"
|
|
26
|
-
x := OpB(
|
|
27
|
+
x := OpB(label: "b", bn: 5)
|
|
27
28
|
z := -x
|
|
28
|
-
assert x.
|
|
29
|
+
assert x.bn == 5
|
|
29
|
-
assert z.
|
|
30
|
+
assert z.bn == 99
|
|
30
31
|
|
|
31
32
|
test "sub and mul"
|
|
32
|
-
x := OpC(
|
|
33
|
+
x := OpC(label: "c", cn: 5)
|
|
33
|
-
y := OpC(
|
|
34
|
+
y := OpC(label: "c", cn: 7)
|
|
34
35
|
m := x * y
|
|
35
|
-
assert x.
|
|
36
|
+
assert x.cn == 5
|
|
36
|
-
assert m.
|
|
37
|
+
assert m.cn == 7
|
|
38
|
+
d := x - y
|
|
39
|
+
assert y.cn == 7
|
|
40
|
+
assert d.cn == -2
|
tests/fbip/slice_shapes.plum
CHANGED
|
@@ -7,10 +7,8 @@ import std/Slice
|
|
|
7
7
|
import std/List
|
|
8
8
|
import std/game/Vec2
|
|
9
9
|
|
|
10
|
-
# The comparison for tests/fbip/vec_*.plum: the same twelve shapes on `Slice`, which mutates in place
|
|
11
|
-
# today (`push`, `putAt`), and the per-frame update on a persistent `List` (`List.map`). Same
|
|
12
|
-
#
|
|
10
|
+
# Twelve shapes on `Slice`, which mutates in place today (`push`, `putAt`), and the per-frame update
|
|
13
|
-
#
|
|
11
|
+
# on a persistent `List` (`List.map`).
|
|
14
12
|
|
|
15
13
|
fun s1(n: Int) -> Int =
|
|
16
14
|
v := Slice[Int]()
|
tests/fbip/spread_ro_method.plum
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
import std/Int
|
|
2
|
-
import std/
|
|
2
|
+
import std/Str
|
|
3
3
|
|
|
4
|
-
# `T(..s, f:
|
|
4
|
+
# `T(..s, f: 9, g: s.total())`: if the spread writes `s.f` in place first, a later field value
|
|
5
|
-
#
|
|
5
|
+
# that reads `s.f` through a read-only method of `s`, or through a closure, would see the new value.
|
|
6
6
|
# Each shape has its own names: a shared field or method name would stop the proof for both.
|
|
7
7
|
|
|
8
|
-
struct RoA(
|
|
8
|
+
struct RoA(label: Str, rcell: Int, rtotal: Int) =
|
|
9
|
-
fun rsum0(self) -> Int = self.
|
|
9
|
+
fun rsum0(self) -> Int = self.rcell
|
|
10
|
-
fun rupd(self) -> RoA = RoA(..self,
|
|
10
|
+
fun rupd(self) -> RoA = RoA(..self, rcell: 9, rtotal: self.rsum0())
|
|
11
11
|
|
|
12
|
-
struct RoB(
|
|
12
|
+
struct RoB(label: Str, qcell: Int, qtotal: Int) =
|
|
13
|
-
fun qsum0(self) -> Int = self.
|
|
13
|
+
fun qsum0(self) -> Int = self.qcell
|
|
14
14
|
|
|
15
|
-
fun roUpd(v: RoB) -> RoB = RoB(..v,
|
|
15
|
+
fun roUpd(v: RoB) -> RoB = RoB(..v, qcell: 9, qtotal: v.qsum0())
|
|
16
16
|
|
|
17
|
-
struct RoC(
|
|
17
|
+
struct RoC(label: Str, ccell: Int, ctotal: Int) =
|
|
18
|
-
fun csum0(self) -> Int = self.
|
|
18
|
+
fun csum0(self) -> Int = self.ccell
|
|
19
19
|
|
|
20
20
|
fun runIt(f: fn() -> Int) -> Int = f()
|
|
21
21
|
|
|
22
|
-
fun roClosure(v: RoC) -> RoC = RoC(..v,
|
|
22
|
+
fun roClosure(v: RoC) -> RoC = RoC(..v, ccell: 9, ctotal: runIt(|| v.csum0()))
|
|
23
23
|
|
|
24
|
-
test "a read-only method of self inside the spread sees the old
|
|
24
|
+
test "a read-only method of self inside the spread sees the old value"
|
|
25
|
-
w := RoA(
|
|
25
|
+
w := RoA(label: "a", rcell: 5, rtotal: 0).rupd()
|
|
26
|
-
assert w.
|
|
26
|
+
assert w.rcell == 9
|
|
27
27
|
assert w.rtotal == 5
|
|
28
28
|
|
|
29
29
|
test "a read-only method of the spread source from a free fn"
|
|
30
|
-
w := roUpd(RoB(
|
|
30
|
+
w := roUpd(RoB(label: "b", qcell: 5, qtotal: 0))
|
|
31
|
-
assert w.
|
|
31
|
+
assert w.qcell == 9
|
|
32
32
|
assert w.qtotal == 5
|
|
33
33
|
|
|
34
34
|
test "a closure reading the spread source"
|
|
35
|
-
w := roClosure(RoC(
|
|
35
|
+
w := roClosure(RoC(label: "c", ccell: 5, ctotal: 0))
|
|
36
|
-
assert w.
|
|
36
|
+
assert w.ccell == 9
|
|
37
37
|
assert w.ctotal == 5
|
tests/fbip/uvec.plum
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Array
|
|
3
|
-
import std/Slice
|
|
4
|
-
|
|
5
|
-
# FBIP pilot, the unique-name copy of vec.plum: `udata`, `usize`, `upush`, `uset`, `uat`, `ulen`, names no std
|
|
6
|
-
# type uses, so the proof can see this type alone. Same code otherwise. Used by vec_unique_names.plum.
|
|
7
|
-
|
|
8
|
-
struct UVec[T](udata: Array[T], usize: Int) =
|
|
9
|
-
fun init() -> UVec[T] = UVec(udata: Array[T]().resize(0), usize: 0)
|
|
10
|
-
|
|
11
|
-
fun upush(self, v: T) -> UVec[T] =
|
|
12
|
-
if self.usize < self.udata.length()
|
|
13
|
-
UVec(..self, udata: self.udata.with(self.usize, v), usize: self.usize + 1)
|
|
14
|
-
else
|
|
15
|
-
UVec(udata: self.udata.resize(if self.usize == 0 then 8 else self.usize * 2).with(self.usize, v), usize: self.usize + 1)
|
|
16
|
-
|
|
17
|
-
fun uset(self, i: Int, v: T) -> UVec[T] =
|
|
18
|
-
UVec(..self, udata: self.udata.with(i, v))
|
|
19
|
-
|
|
20
|
-
fun uat(self, i: Int) -> T = self.udata.get(i)
|
|
21
|
-
|
|
22
|
-
fun ulen(self) -> Int = self.usize
|
tests/fbip/vec.plum
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Array
|
|
3
|
-
import std/Slice
|
|
4
|
-
|
|
5
|
-
# FBIP pilot: a persistent vector written only in Plum, with the realistic names a real
|
|
6
|
-
# collection would use (`data`, `size`, `push`, `set`, `at`, `length`). `push` and `set` return the
|
|
7
|
-
# new vector; they update in place only when the compiler proves nobody else holds the old one.
|
|
8
|
-
# Shapes that use it: tests/fbip/vec_*.plum. Results: docs/plans/2026-11-06-fbip-stage1.results.md.
|
|
9
|
-
|
|
10
|
-
struct Vec[T](data: Array[T], size: Int) =
|
|
11
|
-
fun init() -> Vec[T] = Vec(data: Array[T]().resize(0), size: 0)
|
|
12
|
-
|
|
13
|
-
fun push(self, v: T) -> Vec[T] =
|
|
14
|
-
if self.size < self.data.length()
|
|
15
|
-
Vec(..self, data: self.data.with(self.size, v), size: self.size + 1)
|
|
16
|
-
else
|
|
17
|
-
Vec(data: self.data.resize(if self.size == 0 then 8 else self.size * 2).with(self.size, v), size: self.size + 1)
|
|
18
|
-
|
|
19
|
-
fun set(self, i: Int, v: T) -> Vec[T] =
|
|
20
|
-
Vec(..self, data: self.data.with(i, v))
|
|
21
|
-
|
|
22
|
-
fun at(self, i: Int) -> T = self.data.get(i)
|
|
23
|
-
|
|
24
|
-
fun length(self) -> Int = self.size
|
tests/fbip/vec_combined.plum
DELETED
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Every shape in one program, to see whether one shape's calls poison another's.
|
|
10
|
-
|
|
11
|
-
# Shape 1: a Vec in a local, `v = v.push(i)` in a loop.
|
|
12
|
-
|
|
13
|
-
fun run1(n: Int) -> Int =
|
|
14
|
-
v := Vec[Int]()
|
|
15
|
-
for i := range n
|
|
16
|
-
v = v.push(i)
|
|
17
|
-
v.length() + v.at(n - 1) + v.at(n / 2)
|
|
18
|
-
|
|
19
|
-
# Shape 2: a `mut` field of a struct, `self.items = self.items.push(x)` in a method.
|
|
20
|
-
|
|
21
|
-
struct Bag2(mut items: Vec[Int], mut count: Int) =
|
|
22
|
-
fun add(self, x: Int) -> Unit =
|
|
23
|
-
self.items = self.items.push(x)
|
|
24
|
-
self.count = self.count + 1
|
|
25
|
-
|
|
26
|
-
fun run2(n: Int) -> Int =
|
|
27
|
-
b := Bag2(items: Vec[Int](), count: 0)
|
|
28
|
-
for i := range n
|
|
29
|
-
b.add(i)
|
|
30
|
-
b.items.length() + b.items.at(n - 1) + b.count
|
|
31
|
-
|
|
32
|
-
# Shape 3: a Vec in a field of a nested struct, `o.inner.items = o.inner.items.push(i)`.
|
|
33
|
-
|
|
34
|
-
struct Inner3(mut items: Vec[Int])
|
|
35
|
-
struct Outer3(inner: Inner3, tag: Int)
|
|
36
|
-
|
|
37
|
-
fun run3(n: Int) -> Int =
|
|
38
|
-
o := Outer3(inner: Inner3(items: Vec[Int]()), tag: 5)
|
|
39
|
-
for i := range n
|
|
40
|
-
o.inner.items = o.inner.items.push(i)
|
|
41
|
-
o.inner.items.length() + o.inner.items.at(n - 1) + o.tag
|
|
42
|
-
|
|
43
|
-
# Shape 4: a helper that takes the Vec and returns it, `v = grow(v, i)`.
|
|
44
|
-
|
|
45
|
-
fun grow4(v: Vec[Int], x: Int) -> Vec[Int] = v.push(x * 2)
|
|
46
|
-
|
|
47
|
-
fun run4(n: Int) -> Int =
|
|
48
|
-
v := Vec[Int]()
|
|
49
|
-
for i := range n
|
|
50
|
-
v = grow4(v, i)
|
|
51
|
-
v.length() + v.at(n - 1)
|
|
52
|
-
|
|
53
|
-
# Shape 5: Vec[Int] and Vec[Vec2] in one program.
|
|
54
|
-
|
|
55
|
-
fun run5(n: Int) -> Int =
|
|
56
|
-
a := Vec[Int]()
|
|
57
|
-
b := Vec[Vec2]()
|
|
58
|
-
for i := range n
|
|
59
|
-
a = a.push(i)
|
|
60
|
-
b = b.push(Vec2(x: Float(i), y: 1.0))
|
|
61
|
-
r := a.length() + b.length() + a.at(n - 1)
|
|
62
|
-
if b.at(n - 1).x == Float(n - 1) then r else 0 - 1
|
|
63
|
-
|
|
64
|
-
# Shape 6: the length is read between updates, `n := v.length(); v = v.push(n)`.
|
|
65
|
-
|
|
66
|
-
fun run6(n: Int) -> Int =
|
|
67
|
-
v := Vec[Int]()
|
|
68
|
-
for i := range n
|
|
69
|
-
len := v.length()
|
|
70
|
-
v = v.push(len)
|
|
71
|
-
v.length() + v.at(n - 1)
|
|
72
|
-
|
|
73
|
-
# Shape 7: two Vecs in one struct, both pushed.
|
|
74
|
-
|
|
75
|
-
struct Pair7(mut xs: Vec[Int], mut ys: Vec[Int])
|
|
76
|
-
|
|
77
|
-
fun run7(n: Int) -> Int =
|
|
78
|
-
p := Pair7(xs: Vec[Int](), ys: Vec[Int]())
|
|
79
|
-
for i := range n
|
|
80
|
-
p.xs = p.xs.push(i)
|
|
81
|
-
p.ys = p.ys.push(i * 2)
|
|
82
|
-
p.xs.length() + p.ys.length() + p.xs.at(n - 1) + p.ys.at(n - 1)
|
|
83
|
-
|
|
84
|
-
# Shape 8: a Vec of Vecs. 8a builds rows and pushes them; 8b pushes onto a row stored in the outer Vec (`rows = rows.set(j, rows.at(j).push(i))`).
|
|
85
|
-
|
|
86
|
-
fun run8(n: Int) -> Int =
|
|
87
|
-
rows := Vec[Vec[Int]]()
|
|
88
|
-
for r := range n / 10
|
|
89
|
-
row := Vec[Int]()
|
|
90
|
-
for c := range 10
|
|
91
|
-
row = row.push(r * 10 + c)
|
|
92
|
-
rows = rows.push(row)
|
|
93
|
-
rows.length() + rows.at(n / 10 - 1).at(9)
|
|
94
|
-
|
|
95
|
-
fun run8b(n: Int) -> Int =
|
|
96
|
-
rows := Vec[Vec[Int]]()
|
|
97
|
-
for r := range 10
|
|
98
|
-
rows = rows.push(Vec[Int]())
|
|
99
|
-
for i := range n
|
|
100
|
-
j := i % 10
|
|
101
|
-
rows = rows.set(j, rows.at(j).push(i))
|
|
102
|
-
rows.at(0).length() + rows.at(9).at(n / 10 - 1)
|
|
103
|
-
|
|
104
|
-
# Shape 9: built by one function, returned, then pushed by the caller.
|
|
105
|
-
|
|
106
|
-
fun make9(n: Int) -> Vec[Int] =
|
|
107
|
-
v := Vec[Int]()
|
|
108
|
-
for i := range n
|
|
109
|
-
v = v.push(i)
|
|
110
|
-
v
|
|
111
|
-
|
|
112
|
-
fun run9(n: Int) -> Int =
|
|
113
|
-
v := make9(n)
|
|
114
|
-
for i := range n
|
|
115
|
-
v = v.push(i + n)
|
|
116
|
-
v.length() + v.at(2 * n - 1)
|
|
117
|
-
|
|
118
|
-
# Shape 10: an immutable state struct, `State(..s, items: s.items.push(x))`, in a step function.
|
|
119
|
-
|
|
120
|
-
struct State10(items: Vec[Int], tick: Int)
|
|
121
|
-
|
|
122
|
-
fun step10(s: State10, x: Int) -> State10 =
|
|
123
|
-
State10(..s, items: s.items.push(x), tick: s.tick + 1)
|
|
124
|
-
|
|
125
|
-
fun run10(n: Int) -> Int =
|
|
126
|
-
s := State10(items: Vec[Int](), tick: 0)
|
|
127
|
-
for i := range n
|
|
128
|
-
s = step10(s, i)
|
|
129
|
-
s.items.length() + s.items.at(n - 1) + s.tick
|
|
130
|
-
|
|
131
|
-
# Shape 11: a game-like update, every item of a 20,000-item Vec updated per frame, through a struct field of an immutable state, for many frames.
|
|
132
|
-
|
|
133
|
-
struct World11(items: Vec[Int], frame: Int)
|
|
134
|
-
|
|
135
|
-
fun frame11(w: World11, n: Int) -> World11 =
|
|
136
|
-
for i := range n
|
|
137
|
-
w = World11(..w, items: w.items.set(i, w.items.at(i) + 1))
|
|
138
|
-
World11(..w, frame: w.frame + 1)
|
|
139
|
-
|
|
140
|
-
fun run11(n: Int, frames: Int) -> Int =
|
|
141
|
-
v := Vec[Int]()
|
|
142
|
-
for i := range n
|
|
143
|
-
v = v.push(0)
|
|
144
|
-
w := World11(items: v, frame: 0)
|
|
145
|
-
for f := range frames
|
|
146
|
-
w = frame11(w, n)
|
|
147
|
-
w.items.at(0) + w.items.at(n - 1) + w.frame
|
|
148
|
-
|
|
149
|
-
fun main(io: Io) =
|
|
150
|
-
t1 := Time.now(io).toMillis()
|
|
151
|
-
r1 := run1(100000)
|
|
152
|
-
u1 := Time.now(io).toMillis()
|
|
153
|
-
io.printLn("vec_combined shape 1 result={r1} ms={u1 - t1}")
|
|
154
|
-
t2 := Time.now(io).toMillis()
|
|
155
|
-
r2 := run2(100000)
|
|
156
|
-
u2 := Time.now(io).toMillis()
|
|
157
|
-
io.printLn("vec_combined shape 2 result={r2} ms={u2 - t2}")
|
|
158
|
-
t3 := Time.now(io).toMillis()
|
|
159
|
-
r3 := run3(100000)
|
|
160
|
-
u3 := Time.now(io).toMillis()
|
|
161
|
-
io.printLn("vec_combined shape 3 result={r3} ms={u3 - t3}")
|
|
162
|
-
t4 := Time.now(io).toMillis()
|
|
163
|
-
r4 := run4(100000)
|
|
164
|
-
u4 := Time.now(io).toMillis()
|
|
165
|
-
io.printLn("vec_combined shape 4 result={r4} ms={u4 - t4}")
|
|
166
|
-
t5 := Time.now(io).toMillis()
|
|
167
|
-
r5 := run5(100000)
|
|
168
|
-
u5 := Time.now(io).toMillis()
|
|
169
|
-
io.printLn("vec_combined shape 5 result={r5} ms={u5 - t5}")
|
|
170
|
-
t6 := Time.now(io).toMillis()
|
|
171
|
-
r6 := run6(100000)
|
|
172
|
-
u6 := Time.now(io).toMillis()
|
|
173
|
-
io.printLn("vec_combined shape 6 result={r6} ms={u6 - t6}")
|
|
174
|
-
t7 := Time.now(io).toMillis()
|
|
175
|
-
r7 := run7(100000)
|
|
176
|
-
u7 := Time.now(io).toMillis()
|
|
177
|
-
io.printLn("vec_combined shape 7 result={r7} ms={u7 - t7}")
|
|
178
|
-
t8 := Time.now(io).toMillis()
|
|
179
|
-
r8 := run8(100000) + run8b(2000)
|
|
180
|
-
u8 := Time.now(io).toMillis()
|
|
181
|
-
io.printLn("vec_combined shape 8 result={r8} ms={u8 - t8}")
|
|
182
|
-
t9 := Time.now(io).toMillis()
|
|
183
|
-
r9 := run9(50000)
|
|
184
|
-
u9 := Time.now(io).toMillis()
|
|
185
|
-
io.printLn("vec_combined shape 9 result={r9} ms={u9 - t9}")
|
|
186
|
-
t10 := Time.now(io).toMillis()
|
|
187
|
-
r10 := run10(100000)
|
|
188
|
-
u10 := Time.now(io).toMillis()
|
|
189
|
-
io.printLn("vec_combined shape 10 result={r10} ms={u10 - t10}")
|
|
190
|
-
t11 := Time.now(io).toMillis()
|
|
191
|
-
r11 := run11(20000, 200)
|
|
192
|
-
u11 := Time.now(io).toMillis()
|
|
193
|
-
io.printLn("vec_combined shape 11 result={r11} ms={u11 - t11}")
|
|
194
|
-
|
|
195
|
-
test "vec local"
|
|
196
|
-
assert run1(1000) == 2499
|
|
197
|
-
|
|
198
|
-
test "vec mutfield"
|
|
199
|
-
assert run2(1000) == 2999
|
|
200
|
-
|
|
201
|
-
test "vec nested"
|
|
202
|
-
assert run3(1000) == 2004
|
|
203
|
-
|
|
204
|
-
test "vec helper"
|
|
205
|
-
assert run4(1000) == 2998
|
|
206
|
-
|
|
207
|
-
test "vec generic"
|
|
208
|
-
assert run5(1000) == 2999
|
|
209
|
-
|
|
210
|
-
test "vec readbetween"
|
|
211
|
-
assert run6(1000) == 1999
|
|
212
|
-
|
|
213
|
-
test "vec twolists"
|
|
214
|
-
assert run7(1000) == 4997
|
|
215
|
-
|
|
216
|
-
test "vec listoflists"
|
|
217
|
-
assert run8(1000) == 1099
|
|
218
|
-
|
|
219
|
-
test "vec listoflists (2)"
|
|
220
|
-
assert run8b(1000) == 100 + 999
|
|
221
|
-
|
|
222
|
-
test "vec returned"
|
|
223
|
-
assert run9(500) == 1000 + 999
|
|
224
|
-
|
|
225
|
-
test "vec statespread"
|
|
226
|
-
assert run10(1000) == 2999
|
|
227
|
-
|
|
228
|
-
test "vec frames"
|
|
229
|
-
assert run11(50, 5) == 15
|
tests/fbip/vec_combined_shared.plum
DELETED
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Every shape in one program, to see whether one shape's calls poison another's.
|
|
10
|
-
|
|
11
|
-
# Shape 1: a Vec in a local, `v = v.push(i)` in a loop.
|
|
12
|
-
|
|
13
|
-
fun run1(n: Int) -> Int =
|
|
14
|
-
v := Vec[Int]()
|
|
15
|
-
for i := range n
|
|
16
|
-
v = v.push(i)
|
|
17
|
-
v.length() + v.at(n - 1) + v.at(n / 2)
|
|
18
|
-
|
|
19
|
-
# Shape 2: a `mut` field of a struct, `self.items = self.items.push(x)` in a method.
|
|
20
|
-
|
|
21
|
-
struct Bag2(mut items: Vec[Int], mut count: Int) =
|
|
22
|
-
fun add(self, x: Int) -> Unit =
|
|
23
|
-
self.items = self.items.push(x)
|
|
24
|
-
self.count = self.count + 1
|
|
25
|
-
|
|
26
|
-
fun run2(n: Int) -> Int =
|
|
27
|
-
b := Bag2(items: Vec[Int](), count: 0)
|
|
28
|
-
for i := range n
|
|
29
|
-
b.add(i)
|
|
30
|
-
b.items.length() + b.items.at(n - 1) + b.count
|
|
31
|
-
|
|
32
|
-
# Shape 3: a Vec in a field of a nested struct, `o.inner.items = o.inner.items.push(i)`.
|
|
33
|
-
|
|
34
|
-
struct Inner3(mut items: Vec[Int])
|
|
35
|
-
struct Outer3(inner: Inner3, tag: Int)
|
|
36
|
-
|
|
37
|
-
fun run3(n: Int) -> Int =
|
|
38
|
-
o := Outer3(inner: Inner3(items: Vec[Int]()), tag: 5)
|
|
39
|
-
for i := range n
|
|
40
|
-
o.inner.items = o.inner.items.push(i)
|
|
41
|
-
o.inner.items.length() + o.inner.items.at(n - 1) + o.tag
|
|
42
|
-
|
|
43
|
-
# Shape 4: a helper that takes the Vec and returns it, `v = grow(v, i)`.
|
|
44
|
-
|
|
45
|
-
fun grow4(v: Vec[Int], x: Int) -> Vec[Int] = v.push(x * 2)
|
|
46
|
-
|
|
47
|
-
fun run4(n: Int) -> Int =
|
|
48
|
-
v := Vec[Int]()
|
|
49
|
-
for i := range n
|
|
50
|
-
v = grow4(v, i)
|
|
51
|
-
v.length() + v.at(n - 1)
|
|
52
|
-
|
|
53
|
-
# Shape 5: Vec[Int] and Vec[Vec2] in one program.
|
|
54
|
-
|
|
55
|
-
fun run5(n: Int) -> Int =
|
|
56
|
-
a := Vec[Int]()
|
|
57
|
-
b := Vec[Vec2]()
|
|
58
|
-
for i := range n
|
|
59
|
-
a = a.push(i)
|
|
60
|
-
b = b.push(Vec2(x: Float(i), y: 1.0))
|
|
61
|
-
r := a.length() + b.length() + a.at(n - 1)
|
|
62
|
-
if b.at(n - 1).x == Float(n - 1) then r else 0 - 1
|
|
63
|
-
|
|
64
|
-
# Shape 6: the length is read between updates, `n := v.length(); v = v.push(n)`.
|
|
65
|
-
|
|
66
|
-
fun run6(n: Int) -> Int =
|
|
67
|
-
v := Vec[Int]()
|
|
68
|
-
for i := range n
|
|
69
|
-
len := v.length()
|
|
70
|
-
v = v.push(len)
|
|
71
|
-
v.length() + v.at(n - 1)
|
|
72
|
-
|
|
73
|
-
# Shape 7: two Vecs in one struct, both pushed.
|
|
74
|
-
|
|
75
|
-
struct Pair7(mut xs: Vec[Int], mut ys: Vec[Int])
|
|
76
|
-
|
|
77
|
-
fun run7(n: Int) -> Int =
|
|
78
|
-
p := Pair7(xs: Vec[Int](), ys: Vec[Int]())
|
|
79
|
-
for i := range n
|
|
80
|
-
p.xs = p.xs.push(i)
|
|
81
|
-
p.ys = p.ys.push(i * 2)
|
|
82
|
-
p.xs.length() + p.ys.length() + p.xs.at(n - 1) + p.ys.at(n - 1)
|
|
83
|
-
|
|
84
|
-
# Shape 8: a Vec of Vecs. 8a builds rows and pushes them; 8b pushes onto a row stored in the outer Vec (`rows = rows.set(j, rows.at(j).push(i))`).
|
|
85
|
-
|
|
86
|
-
fun run8(n: Int) -> Int =
|
|
87
|
-
rows := Vec[Vec[Int]]()
|
|
88
|
-
for r := range n / 10
|
|
89
|
-
row := Vec[Int]()
|
|
90
|
-
for c := range 10
|
|
91
|
-
row = row.push(r * 10 + c)
|
|
92
|
-
rows = rows.push(row)
|
|
93
|
-
rows.length() + rows.at(n / 10 - 1).at(9)
|
|
94
|
-
|
|
95
|
-
fun run8b(n: Int) -> Int =
|
|
96
|
-
rows := Vec[Vec[Int]]()
|
|
97
|
-
for r := range 10
|
|
98
|
-
rows = rows.push(Vec[Int]())
|
|
99
|
-
for i := range n
|
|
100
|
-
j := i % 10
|
|
101
|
-
rows = rows.set(j, rows.at(j).push(i))
|
|
102
|
-
rows.at(0).length() + rows.at(9).at(n / 10 - 1)
|
|
103
|
-
|
|
104
|
-
# Shape 9: built by one function, returned, then pushed by the caller.
|
|
105
|
-
|
|
106
|
-
fun make9(n: Int) -> Vec[Int] =
|
|
107
|
-
v := Vec[Int]()
|
|
108
|
-
for i := range n
|
|
109
|
-
v = v.push(i)
|
|
110
|
-
v
|
|
111
|
-
|
|
112
|
-
fun run9(n: Int) -> Int =
|
|
113
|
-
v := make9(n)
|
|
114
|
-
for i := range n
|
|
115
|
-
v = v.push(i + n)
|
|
116
|
-
v.length() + v.at(2 * n - 1)
|
|
117
|
-
|
|
118
|
-
# Shape 10: an immutable state struct, `State(..s, items: s.items.push(x))`, in a step function.
|
|
119
|
-
|
|
120
|
-
struct State10(items: Vec[Int], tick: Int)
|
|
121
|
-
|
|
122
|
-
fun step10(s: State10, x: Int) -> State10 =
|
|
123
|
-
State10(..s, items: s.items.push(x), tick: s.tick + 1)
|
|
124
|
-
|
|
125
|
-
fun run10(n: Int) -> Int =
|
|
126
|
-
s := State10(items: Vec[Int](), tick: 0)
|
|
127
|
-
for i := range n
|
|
128
|
-
s = step10(s, i)
|
|
129
|
-
s.items.length() + s.items.at(n - 1) + s.tick
|
|
130
|
-
|
|
131
|
-
# Shape 11: a game-like update, every item of a 20,000-item Vec updated per frame, through a struct field of an immutable state, for many frames.
|
|
132
|
-
|
|
133
|
-
struct World11(items: Vec[Int], frame: Int)
|
|
134
|
-
|
|
135
|
-
fun frame11(w: World11, n: Int) -> World11 =
|
|
136
|
-
for i := range n
|
|
137
|
-
w = World11(..w, items: w.items.set(i, w.items.at(i) + 1))
|
|
138
|
-
World11(..w, frame: w.frame + 1)
|
|
139
|
-
|
|
140
|
-
fun run11(n: Int, frames: Int) -> Int =
|
|
141
|
-
v := Vec[Int]()
|
|
142
|
-
for i := range n
|
|
143
|
-
v = v.push(0)
|
|
144
|
-
w := World11(items: v, frame: 0)
|
|
145
|
-
for f := range frames
|
|
146
|
-
w = frame11(w, n)
|
|
147
|
-
w.items.at(0) + w.items.at(n - 1) + w.frame
|
|
148
|
-
|
|
149
|
-
# Shape 12: one value shared on purpose. Every holder keeps its own contents; this is a correctness test.
|
|
150
|
-
|
|
151
|
-
fun run12() -> Int =
|
|
152
|
-
a := Vec[Int]()
|
|
153
|
-
for i := range 20
|
|
154
|
-
a = a.push(i)
|
|
155
|
-
b := a.push(100)
|
|
156
|
-
c := a.push(200)
|
|
157
|
-
d := a.set(0, 7)
|
|
158
|
-
e := b.set(1, 8)
|
|
159
|
-
ok := a.length() == 20 && a.at(0) == 0 && a.at(1) == 1
|
|
160
|
-
ok2 := b.length() == 21 && b.at(20) == 100 && b.at(1) == 1 && c.length() == 21 && c.at(20) == 200
|
|
161
|
-
ok3 := d.at(0) == 7 && e.at(1) == 8 && e.at(20) == 100 && b.at(0) == 0
|
|
162
|
-
if ok && ok2 && ok3 then 1 else 0
|
|
163
|
-
|
|
164
|
-
fun main(io: Io) =
|
|
165
|
-
t1 := Time.now(io).toMillis()
|
|
166
|
-
r1 := run1(100000)
|
|
167
|
-
u1 := Time.now(io).toMillis()
|
|
168
|
-
io.printLn("vec_combined shape 1 result={r1} ms={u1 - t1}")
|
|
169
|
-
t2 := Time.now(io).toMillis()
|
|
170
|
-
r2 := run2(100000)
|
|
171
|
-
u2 := Time.now(io).toMillis()
|
|
172
|
-
io.printLn("vec_combined shape 2 result={r2} ms={u2 - t2}")
|
|
173
|
-
t3 := Time.now(io).toMillis()
|
|
174
|
-
r3 := run3(100000)
|
|
175
|
-
u3 := Time.now(io).toMillis()
|
|
176
|
-
io.printLn("vec_combined shape 3 result={r3} ms={u3 - t3}")
|
|
177
|
-
t4 := Time.now(io).toMillis()
|
|
178
|
-
r4 := run4(100000)
|
|
179
|
-
u4 := Time.now(io).toMillis()
|
|
180
|
-
io.printLn("vec_combined shape 4 result={r4} ms={u4 - t4}")
|
|
181
|
-
t5 := Time.now(io).toMillis()
|
|
182
|
-
r5 := run5(100000)
|
|
183
|
-
u5 := Time.now(io).toMillis()
|
|
184
|
-
io.printLn("vec_combined shape 5 result={r5} ms={u5 - t5}")
|
|
185
|
-
t6 := Time.now(io).toMillis()
|
|
186
|
-
r6 := run6(100000)
|
|
187
|
-
u6 := Time.now(io).toMillis()
|
|
188
|
-
io.printLn("vec_combined shape 6 result={r6} ms={u6 - t6}")
|
|
189
|
-
t7 := Time.now(io).toMillis()
|
|
190
|
-
r7 := run7(100000)
|
|
191
|
-
u7 := Time.now(io).toMillis()
|
|
192
|
-
io.printLn("vec_combined shape 7 result={r7} ms={u7 - t7}")
|
|
193
|
-
t8 := Time.now(io).toMillis()
|
|
194
|
-
r8 := run8(100000) + run8b(2000)
|
|
195
|
-
u8 := Time.now(io).toMillis()
|
|
196
|
-
io.printLn("vec_combined shape 8 result={r8} ms={u8 - t8}")
|
|
197
|
-
t9 := Time.now(io).toMillis()
|
|
198
|
-
r9 := run9(50000)
|
|
199
|
-
u9 := Time.now(io).toMillis()
|
|
200
|
-
io.printLn("vec_combined shape 9 result={r9} ms={u9 - t9}")
|
|
201
|
-
t10 := Time.now(io).toMillis()
|
|
202
|
-
r10 := run10(100000)
|
|
203
|
-
u10 := Time.now(io).toMillis()
|
|
204
|
-
io.printLn("vec_combined shape 10 result={r10} ms={u10 - t10}")
|
|
205
|
-
t11 := Time.now(io).toMillis()
|
|
206
|
-
r11 := run11(20000, 200)
|
|
207
|
-
u11 := Time.now(io).toMillis()
|
|
208
|
-
io.printLn("vec_combined shape 11 result={r11} ms={u11 - t11}")
|
|
209
|
-
t12 := Time.now(io).toMillis()
|
|
210
|
-
r12 := run12()
|
|
211
|
-
u12 := Time.now(io).toMillis()
|
|
212
|
-
io.printLn("vec_combined shape 12 result={r12} ms={u12 - t12}")
|
|
213
|
-
|
|
214
|
-
test "vec local"
|
|
215
|
-
assert run1(1000) == 2499
|
|
216
|
-
|
|
217
|
-
test "vec mutfield"
|
|
218
|
-
assert run2(1000) == 2999
|
|
219
|
-
|
|
220
|
-
test "vec nested"
|
|
221
|
-
assert run3(1000) == 2004
|
|
222
|
-
|
|
223
|
-
test "vec helper"
|
|
224
|
-
assert run4(1000) == 2998
|
|
225
|
-
|
|
226
|
-
test "vec generic"
|
|
227
|
-
assert run5(1000) == 2999
|
|
228
|
-
|
|
229
|
-
test "vec readbetween"
|
|
230
|
-
assert run6(1000) == 1999
|
|
231
|
-
|
|
232
|
-
test "vec twolists"
|
|
233
|
-
assert run7(1000) == 4997
|
|
234
|
-
|
|
235
|
-
test "vec listoflists"
|
|
236
|
-
assert run8(1000) == 1099
|
|
237
|
-
|
|
238
|
-
test "vec listoflists (2)"
|
|
239
|
-
assert run8b(1000) == 100 + 999
|
|
240
|
-
|
|
241
|
-
test "vec returned"
|
|
242
|
-
assert run9(500) == 1000 + 999
|
|
243
|
-
|
|
244
|
-
test "vec statespread"
|
|
245
|
-
assert run10(1000) == 2999
|
|
246
|
-
|
|
247
|
-
test "vec frames"
|
|
248
|
-
assert run11(50, 5) == 15
|
|
249
|
-
|
|
250
|
-
test "vec shared"
|
|
251
|
-
assert run12() == 1
|
tests/fbip/vec_fip.plum
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Array
|
|
3
|
-
|
|
4
|
-
# `fip fun` on the pilot's shape: the compiler accepts a push/set written as a spread plus `Array.with`
|
|
5
|
-
# when it proves the update in place, and refuses the program (tests/fbip_u/ shows the error) when
|
|
6
|
-
# it does not. Names are unique (`fdata`, `fpush`) because the proof is by name.
|
|
7
|
-
|
|
8
|
-
struct FVec[T](fdata: Array[T], fsize: Int) =
|
|
9
|
-
fun init() -> FVec[T] = FVec(fdata: Array[T]().resize(0), fsize: 0)
|
|
10
|
-
|
|
11
|
-
fip fun fpush(self, v: T) -> FVec[T] =
|
|
12
|
-
if self.fsize < self.fdata.length()
|
|
13
|
-
FVec(..self, fdata: self.fdata.with(self.fsize, v), fsize: self.fsize + 1)
|
|
14
|
-
else
|
|
15
|
-
FVec(fdata: self.fdata.resize(if self.fsize == 0 then 8 else self.fsize * 2).with(self.fsize, v), fsize: self.fsize + 1)
|
|
16
|
-
|
|
17
|
-
fip fun fset(self, i: Int, v: T) -> FVec[T] =
|
|
18
|
-
FVec(..self, fdata: self.fdata.with(i, v))
|
|
19
|
-
|
|
20
|
-
fun fat(self, i: Int) -> T = self.fdata.get(i)
|
|
21
|
-
|
|
22
|
-
fun flen(self) -> Int = self.fsize
|
|
23
|
-
|
|
24
|
-
fun fill(n: Int) -> FVec[Int] =
|
|
25
|
-
v := FVec[Int]()
|
|
26
|
-
for i := range n
|
|
27
|
-
v = v.fpush(i)
|
|
28
|
-
v = v.fset(3, 99)
|
|
29
|
-
v
|
|
30
|
-
|
|
31
|
-
test "fip vec: push and set"
|
|
32
|
-
v := fill(20)
|
|
33
|
-
assert v.flen() == 20 && v.fat(3) == 99 && v.fat(19) == 19
|
tests/fbip/vec_frames.plum
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 11: a game-like update, every item of a 20,000-item Vec updated per frame, through a struct field of an immutable state, for many frames.
|
|
10
|
-
|
|
11
|
-
struct World11(items: Vec[Int], frame: Int)
|
|
12
|
-
|
|
13
|
-
fun frame11(w: World11, n: Int) -> World11 =
|
|
14
|
-
for i := range n
|
|
15
|
-
w = World11(..w, items: w.items.set(i, w.items.at(i) + 1))
|
|
16
|
-
World11(..w, frame: w.frame + 1)
|
|
17
|
-
|
|
18
|
-
fun run11(n: Int, frames: Int) -> Int =
|
|
19
|
-
v := Vec[Int]()
|
|
20
|
-
for i := range n
|
|
21
|
-
v = v.push(0)
|
|
22
|
-
w := World11(items: v, frame: 0)
|
|
23
|
-
for f := range frames
|
|
24
|
-
w = frame11(w, n)
|
|
25
|
-
w.items.at(0) + w.items.at(n - 1) + w.frame
|
|
26
|
-
|
|
27
|
-
fun main(io: Io) =
|
|
28
|
-
t11 := Time.now(io).toMillis()
|
|
29
|
-
r11 := run11(20000, 200)
|
|
30
|
-
u11 := Time.now(io).toMillis()
|
|
31
|
-
io.printLn("vec_frames shape 11 result={r11} ms={u11 - t11}")
|
|
32
|
-
|
|
33
|
-
test "vec frames"
|
|
34
|
-
assert run11(50, 5) == 15
|
tests/fbip/vec_frameslocal.plum
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 11b: the per-frame update on a Vec held in a local and handed through a function, no struct around it.
|
|
10
|
-
|
|
11
|
-
fun frame13(v: Vec[Int], n: Int) -> Vec[Int] =
|
|
12
|
-
for i := range n
|
|
13
|
-
v = v.set(i, v.at(i) + 1)
|
|
14
|
-
v
|
|
15
|
-
|
|
16
|
-
fun run13(n: Int, frames: Int) -> Int =
|
|
17
|
-
v := Vec[Int]()
|
|
18
|
-
for i := range n
|
|
19
|
-
v = v.push(0)
|
|
20
|
-
for f := range frames
|
|
21
|
-
v = frame13(v, n)
|
|
22
|
-
v.at(0) + v.at(n - 1)
|
|
23
|
-
|
|
24
|
-
fun main(io: Io) =
|
|
25
|
-
t13 := Time.now(io).toMillis()
|
|
26
|
-
r13 := run13(20000, 200)
|
|
27
|
-
u13 := Time.now(io).toMillis()
|
|
28
|
-
io.printLn("vec_frameslocal shape 13 result={r13} ms={u13 - t13}")
|
|
29
|
-
|
|
30
|
-
test "vec frameslocal"
|
|
31
|
-
assert run13(50, 5) == 10
|
tests/fbip/vec_framesmut.plum
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 11c: the per-frame update on a Vec in a `mut` field, `w.items = w.items.set(i, ..)`.
|
|
10
|
-
|
|
11
|
-
struct World14(mut items: Vec[Int], mut frame: Int)
|
|
12
|
-
|
|
13
|
-
fun frame14(w: World14, n: Int) -> Unit =
|
|
14
|
-
for i := range n
|
|
15
|
-
w.items = w.items.set(i, w.items.at(i) + 1)
|
|
16
|
-
w.frame = w.frame + 1
|
|
17
|
-
|
|
18
|
-
fun run14(n: Int, frames: Int) -> Int =
|
|
19
|
-
v := Vec[Int]()
|
|
20
|
-
for i := range n
|
|
21
|
-
v = v.push(0)
|
|
22
|
-
w := World14(items: v, frame: 0)
|
|
23
|
-
for f := range frames
|
|
24
|
-
frame14(w, n)
|
|
25
|
-
w.items.at(0) + w.items.at(n - 1) + w.frame
|
|
26
|
-
|
|
27
|
-
fun main(io: Io) =
|
|
28
|
-
t14 := Time.now(io).toMillis()
|
|
29
|
-
r14 := run14(20000, 200)
|
|
30
|
-
u14 := Time.now(io).toMillis()
|
|
31
|
-
io.printLn("vec_framesmut shape 14 result={r14} ms={u14 - t14}")
|
|
32
|
-
|
|
33
|
-
test "vec framesmut"
|
|
34
|
-
assert run14(50, 5) == 15
|
tests/fbip/vec_generic.plum
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 5: Vec[Int] and Vec[Vec2] in one program.
|
|
10
|
-
|
|
11
|
-
fun run5(n: Int) -> Int =
|
|
12
|
-
a := Vec[Int]()
|
|
13
|
-
b := Vec[Vec2]()
|
|
14
|
-
for i := range n
|
|
15
|
-
a = a.push(i)
|
|
16
|
-
b = b.push(Vec2(x: Float(i), y: 1.0))
|
|
17
|
-
r := a.length() + b.length() + a.at(n - 1)
|
|
18
|
-
if b.at(n - 1).x == Float(n - 1) then r else 0 - 1
|
|
19
|
-
|
|
20
|
-
fun main(io: Io) =
|
|
21
|
-
t5 := Time.now(io).toMillis()
|
|
22
|
-
r5 := run5(100000)
|
|
23
|
-
u5 := Time.now(io).toMillis()
|
|
24
|
-
io.printLn("vec_generic shape 5 result={r5} ms={u5 - t5}")
|
|
25
|
-
|
|
26
|
-
test "vec generic"
|
|
27
|
-
assert run5(1000) == 2999
|
tests/fbip/vec_helper.plum
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 4: a helper that takes the Vec and returns it, `v = grow(v, i)`.
|
|
10
|
-
|
|
11
|
-
fun grow4(v: Vec[Int], x: Int) -> Vec[Int] = v.push(x * 2)
|
|
12
|
-
|
|
13
|
-
fun run4(n: Int) -> Int =
|
|
14
|
-
v := Vec[Int]()
|
|
15
|
-
for i := range n
|
|
16
|
-
v = grow4(v, i)
|
|
17
|
-
v.length() + v.at(n - 1)
|
|
18
|
-
|
|
19
|
-
fun main(io: Io) =
|
|
20
|
-
t4 := Time.now(io).toMillis()
|
|
21
|
-
r4 := run4(100000)
|
|
22
|
-
u4 := Time.now(io).toMillis()
|
|
23
|
-
io.printLn("vec_helper shape 4 result={r4} ms={u4 - t4}")
|
|
24
|
-
|
|
25
|
-
test "vec helper"
|
|
26
|
-
assert run4(1000) == 2998
|
tests/fbip/vec_listoflists.plum
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 8: a Vec of Vecs. 8a builds rows and pushes them; 8b pushes onto a row stored in the outer Vec (`rows = rows.set(j, rows.at(j).push(i))`).
|
|
10
|
-
|
|
11
|
-
fun run8(n: Int) -> Int =
|
|
12
|
-
rows := Vec[Vec[Int]]()
|
|
13
|
-
for r := range n / 10
|
|
14
|
-
row := Vec[Int]()
|
|
15
|
-
for c := range 10
|
|
16
|
-
row = row.push(r * 10 + c)
|
|
17
|
-
rows = rows.push(row)
|
|
18
|
-
rows.length() + rows.at(n / 10 - 1).at(9)
|
|
19
|
-
|
|
20
|
-
fun run8b(n: Int) -> Int =
|
|
21
|
-
rows := Vec[Vec[Int]]()
|
|
22
|
-
for r := range 10
|
|
23
|
-
rows = rows.push(Vec[Int]())
|
|
24
|
-
for i := range n
|
|
25
|
-
j := i % 10
|
|
26
|
-
rows = rows.set(j, rows.at(j).push(i))
|
|
27
|
-
rows.at(0).length() + rows.at(9).at(n / 10 - 1)
|
|
28
|
-
|
|
29
|
-
fun main(io: Io) =
|
|
30
|
-
t8 := Time.now(io).toMillis()
|
|
31
|
-
r8 := run8(100000) + run8b(2000)
|
|
32
|
-
u8 := Time.now(io).toMillis()
|
|
33
|
-
io.printLn("vec_listoflists shape 8 result={r8} ms={u8 - t8}")
|
|
34
|
-
|
|
35
|
-
test "vec listoflists"
|
|
36
|
-
assert run8(1000) == 1099
|
|
37
|
-
|
|
38
|
-
test "vec listoflists (2)"
|
|
39
|
-
assert run8b(1000) == 100 + 999
|
tests/fbip/vec_local.plum
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 1: a Vec in a local, `v = v.push(i)` in a loop.
|
|
10
|
-
|
|
11
|
-
fun run1(n: Int) -> Int =
|
|
12
|
-
v := Vec[Int]()
|
|
13
|
-
for i := range n
|
|
14
|
-
v = v.push(i)
|
|
15
|
-
v.length() + v.at(n - 1) + v.at(n / 2)
|
|
16
|
-
|
|
17
|
-
fun main(io: Io) =
|
|
18
|
-
t1 := Time.now(io).toMillis()
|
|
19
|
-
r1 := run1(100000)
|
|
20
|
-
u1 := Time.now(io).toMillis()
|
|
21
|
-
io.printLn("vec_local shape 1 result={r1} ms={u1 - t1}")
|
|
22
|
-
|
|
23
|
-
test "vec local"
|
|
24
|
-
assert run1(1000) == 2499
|
tests/fbip/vec_mutfield.plum
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 2: a `mut` field of a struct, `self.items = self.items.push(x)` in a method.
|
|
10
|
-
|
|
11
|
-
struct Bag2(mut items: Vec[Int], mut count: Int) =
|
|
12
|
-
fun add(self, x: Int) -> Unit =
|
|
13
|
-
self.items = self.items.push(x)
|
|
14
|
-
self.count = self.count + 1
|
|
15
|
-
|
|
16
|
-
fun run2(n: Int) -> Int =
|
|
17
|
-
b := Bag2(items: Vec[Int](), count: 0)
|
|
18
|
-
for i := range n
|
|
19
|
-
b.add(i)
|
|
20
|
-
b.items.length() + b.items.at(n - 1) + b.count
|
|
21
|
-
|
|
22
|
-
fun main(io: Io) =
|
|
23
|
-
t2 := Time.now(io).toMillis()
|
|
24
|
-
r2 := run2(100000)
|
|
25
|
-
u2 := Time.now(io).toMillis()
|
|
26
|
-
io.printLn("vec_mutfield shape 2 result={r2} ms={u2 - t2}")
|
|
27
|
-
|
|
28
|
-
test "vec mutfield"
|
|
29
|
-
assert run2(1000) == 2999
|
tests/fbip/vec_nested.plum
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 3: a Vec in a field of a nested struct, `o.inner.items = o.inner.items.push(i)`.
|
|
10
|
-
|
|
11
|
-
struct Inner3(mut items: Vec[Int])
|
|
12
|
-
struct Outer3(inner: Inner3, tag: Int)
|
|
13
|
-
|
|
14
|
-
fun run3(n: Int) -> Int =
|
|
15
|
-
o := Outer3(inner: Inner3(items: Vec[Int]()), tag: 5)
|
|
16
|
-
for i := range n
|
|
17
|
-
o.inner.items = o.inner.items.push(i)
|
|
18
|
-
o.inner.items.length() + o.inner.items.at(n - 1) + o.tag
|
|
19
|
-
|
|
20
|
-
fun main(io: Io) =
|
|
21
|
-
t3 := Time.now(io).toMillis()
|
|
22
|
-
r3 := run3(100000)
|
|
23
|
-
u3 := Time.now(io).toMillis()
|
|
24
|
-
io.printLn("vec_nested shape 3 result={r3} ms={u3 - t3}")
|
|
25
|
-
|
|
26
|
-
test "vec nested"
|
|
27
|
-
assert run3(1000) == 2004
|
tests/fbip/vec_readbetween.plum
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 6: the length is read between updates, `n := v.length(); v = v.push(n)`.
|
|
10
|
-
|
|
11
|
-
fun run6(n: Int) -> Int =
|
|
12
|
-
v := Vec[Int]()
|
|
13
|
-
for i := range n
|
|
14
|
-
len := v.length()
|
|
15
|
-
v = v.push(len)
|
|
16
|
-
v.length() + v.at(n - 1)
|
|
17
|
-
|
|
18
|
-
fun main(io: Io) =
|
|
19
|
-
t6 := Time.now(io).toMillis()
|
|
20
|
-
r6 := run6(100000)
|
|
21
|
-
u6 := Time.now(io).toMillis()
|
|
22
|
-
io.printLn("vec_readbetween shape 6 result={r6} ms={u6 - t6}")
|
|
23
|
-
|
|
24
|
-
test "vec readbetween"
|
|
25
|
-
assert run6(1000) == 1999
|
tests/fbip/vec_returned.plum
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 9: built by one function, returned, then pushed by the caller.
|
|
10
|
-
|
|
11
|
-
fun make9(n: Int) -> Vec[Int] =
|
|
12
|
-
v := Vec[Int]()
|
|
13
|
-
for i := range n
|
|
14
|
-
v = v.push(i)
|
|
15
|
-
v
|
|
16
|
-
|
|
17
|
-
fun run9(n: Int) -> Int =
|
|
18
|
-
v := make9(n)
|
|
19
|
-
for i := range n
|
|
20
|
-
v = v.push(i + n)
|
|
21
|
-
v.length() + v.at(2 * n - 1)
|
|
22
|
-
|
|
23
|
-
fun main(io: Io) =
|
|
24
|
-
t9 := Time.now(io).toMillis()
|
|
25
|
-
r9 := run9(50000)
|
|
26
|
-
u9 := Time.now(io).toMillis()
|
|
27
|
-
io.printLn("vec_returned shape 9 result={r9} ms={u9 - t9}")
|
|
28
|
-
|
|
29
|
-
test "vec returned"
|
|
30
|
-
assert run9(500) == 1000 + 999
|
tests/fbip/vec_returned2.plum
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 9b: a function that returns a Vec it built in a local, called twice, the result pushed by the caller.
|
|
10
|
-
|
|
11
|
-
fun make15(n: Int) -> Vec[Int] =
|
|
12
|
-
v := Vec[Int]()
|
|
13
|
-
for i := range n
|
|
14
|
-
v = v.push(i)
|
|
15
|
-
v
|
|
16
|
-
|
|
17
|
-
fun run15(n: Int) -> Int =
|
|
18
|
-
v := make15(n)
|
|
19
|
-
w := Vec[Int]()
|
|
20
|
-
for i := range n
|
|
21
|
-
w = w.push(i)
|
|
22
|
-
v.length() + w.length()
|
|
23
|
-
|
|
24
|
-
fun main(io: Io) =
|
|
25
|
-
t15 := Time.now(io).toMillis()
|
|
26
|
-
r15 := run15(100000)
|
|
27
|
-
u15 := Time.now(io).toMillis()
|
|
28
|
-
io.printLn("vec_returned2 shape 15 result={r15} ms={u15 - t15}")
|
|
29
|
-
|
|
30
|
-
test "vec returned2"
|
|
31
|
-
assert run15(500) == 1000
|
tests/fbip/vec_shared.plum
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 12: one value shared on purpose. Every holder keeps its own contents; this is a correctness test.
|
|
10
|
-
|
|
11
|
-
fun run12() -> Int =
|
|
12
|
-
a := Vec[Int]()
|
|
13
|
-
for i := range 20
|
|
14
|
-
a = a.push(i)
|
|
15
|
-
b := a.push(100)
|
|
16
|
-
c := a.push(200)
|
|
17
|
-
d := a.set(0, 7)
|
|
18
|
-
e := b.set(1, 8)
|
|
19
|
-
ok := a.length() == 20 && a.at(0) == 0 && a.at(1) == 1
|
|
20
|
-
ok2 := b.length() == 21 && b.at(20) == 100 && b.at(1) == 1 && c.length() == 21 && c.at(20) == 200
|
|
21
|
-
ok3 := d.at(0) == 7 && e.at(1) == 8 && e.at(20) == 100 && b.at(0) == 0
|
|
22
|
-
if ok && ok2 && ok3 then 1 else 0
|
|
23
|
-
|
|
24
|
-
fun main(io: Io) =
|
|
25
|
-
t12 := Time.now(io).toMillis()
|
|
26
|
-
r12 := run12()
|
|
27
|
-
u12 := Time.now(io).toMillis()
|
|
28
|
-
io.printLn("vec_shared shape 12 result={r12} ms={u12 - t12}")
|
|
29
|
-
|
|
30
|
-
test "vec shared"
|
|
31
|
-
assert run12() == 1
|
tests/fbip/vec_statespread.plum
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 10: an immutable state struct, `State(..s, items: s.items.push(x))`, in a step function.
|
|
10
|
-
|
|
11
|
-
struct State10(items: Vec[Int], tick: Int)
|
|
12
|
-
|
|
13
|
-
fun step10(s: State10, x: Int) -> State10 =
|
|
14
|
-
State10(..s, items: s.items.push(x), tick: s.tick + 1)
|
|
15
|
-
|
|
16
|
-
fun run10(n: Int) -> Int =
|
|
17
|
-
s := State10(items: Vec[Int](), tick: 0)
|
|
18
|
-
for i := range n
|
|
19
|
-
s = step10(s, i)
|
|
20
|
-
s.items.length() + s.items.at(n - 1) + s.tick
|
|
21
|
-
|
|
22
|
-
fun main(io: Io) =
|
|
23
|
-
t10 := Time.now(io).toMillis()
|
|
24
|
-
r10 := run10(100000)
|
|
25
|
-
u10 := Time.now(io).toMillis()
|
|
26
|
-
io.printLn("vec_statespread shape 10 result={r10} ms={u10 - t10}")
|
|
27
|
-
|
|
28
|
-
test "vec statespread"
|
|
29
|
-
assert run10(1000) == 2999
|
tests/fbip/vec_twolists.plum
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/vec
|
|
8
|
-
|
|
9
|
-
# Shape 7: two Vecs in one struct, both pushed.
|
|
10
|
-
|
|
11
|
-
struct Pair7(mut xs: Vec[Int], mut ys: Vec[Int])
|
|
12
|
-
|
|
13
|
-
fun run7(n: Int) -> Int =
|
|
14
|
-
p := Pair7(xs: Vec[Int](), ys: Vec[Int]())
|
|
15
|
-
for i := range n
|
|
16
|
-
p.xs = p.xs.push(i)
|
|
17
|
-
p.ys = p.ys.push(i * 2)
|
|
18
|
-
p.xs.length() + p.ys.length() + p.xs.at(n - 1) + p.ys.at(n - 1)
|
|
19
|
-
|
|
20
|
-
fun main(io: Io) =
|
|
21
|
-
t7 := Time.now(io).toMillis()
|
|
22
|
-
r7 := run7(100000)
|
|
23
|
-
u7 := Time.now(io).toMillis()
|
|
24
|
-
io.printLn("vec_twolists shape 7 result={r7} ms={u7 - t7}")
|
|
25
|
-
|
|
26
|
-
test "vec twolists"
|
|
27
|
-
assert run7(1000) == 4997
|
tests/fbip/vec_unique_names.plum
DELETED
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Str
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Time
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import tests/fbip/uvec
|
|
8
|
-
|
|
9
|
-
# The shapes that are proved in place, in one program, with names no std type uses (`udata`, `upush`, ...). With `data`
|
|
10
|
-
# and `push` (vec_combined.plum) the same code copies on every push.
|
|
11
|
-
|
|
12
|
-
# Shape 1: a Vec in a local, `v = v.push(i)` in a loop.
|
|
13
|
-
|
|
14
|
-
fun run1(n: Int) -> Int =
|
|
15
|
-
v := UVec[Int]()
|
|
16
|
-
for i := range n
|
|
17
|
-
v = v.upush(i)
|
|
18
|
-
v.ulen() + v.uat(n - 1) + v.uat(n / 2)
|
|
19
|
-
|
|
20
|
-
# Shape 2: a `mut` field of a struct, `self.items = self.items.push(x)` in a method.
|
|
21
|
-
|
|
22
|
-
struct Bag2(mut items: UVec[Int], mut count: Int) =
|
|
23
|
-
fun add(self, x: Int) -> Unit =
|
|
24
|
-
self.items = self.items.upush(x)
|
|
25
|
-
self.count = self.count + 1
|
|
26
|
-
|
|
27
|
-
fun run2(n: Int) -> Int =
|
|
28
|
-
b := Bag2(items: UVec[Int](), count: 0)
|
|
29
|
-
for i := range n
|
|
30
|
-
b.add(i)
|
|
31
|
-
b.items.ulen() + b.items.uat(n - 1) + b.count
|
|
32
|
-
|
|
33
|
-
# Shape 3: a Vec in a field of a nested struct, `o.inner.items = o.inner.items.push(i)`.
|
|
34
|
-
|
|
35
|
-
struct Inner3(mut items: UVec[Int])
|
|
36
|
-
struct Outer3(inner: Inner3, tag: Int)
|
|
37
|
-
|
|
38
|
-
fun run3(n: Int) -> Int =
|
|
39
|
-
o := Outer3(inner: Inner3(items: UVec[Int]()), tag: 5)
|
|
40
|
-
for i := range n
|
|
41
|
-
o.inner.items = o.inner.items.upush(i)
|
|
42
|
-
o.inner.items.ulen() + o.inner.items.uat(n - 1) + o.tag
|
|
43
|
-
|
|
44
|
-
# Shape 4: a helper that takes the Vec and returns it, `v = grow(v, i)`.
|
|
45
|
-
|
|
46
|
-
fun grow4(v: UVec[Int], x: Int) -> UVec[Int] = v.upush(x * 2)
|
|
47
|
-
|
|
48
|
-
fun run4(n: Int) -> Int =
|
|
49
|
-
v := UVec[Int]()
|
|
50
|
-
for i := range n
|
|
51
|
-
v = grow4(v, i)
|
|
52
|
-
v.ulen() + v.uat(n - 1)
|
|
53
|
-
|
|
54
|
-
# Shape 5: Vec[Int] and Vec[Vec2] in one program.
|
|
55
|
-
|
|
56
|
-
fun run5(n: Int) -> Int =
|
|
57
|
-
a := UVec[Int]()
|
|
58
|
-
b := UVec[Vec2]()
|
|
59
|
-
for i := range n
|
|
60
|
-
a = a.upush(i)
|
|
61
|
-
b = b.upush(Vec2(x: Float(i), y: 1.0))
|
|
62
|
-
r := a.ulen() + b.ulen() + a.uat(n - 1)
|
|
63
|
-
if b.uat(n - 1).x == Float(n - 1) then r else 0 - 1
|
|
64
|
-
|
|
65
|
-
# Shape 6: the length is read between updates, `n := v.length(); v = v.push(n)`.
|
|
66
|
-
|
|
67
|
-
fun run6(n: Int) -> Int =
|
|
68
|
-
v := UVec[Int]()
|
|
69
|
-
for i := range n
|
|
70
|
-
len := v.ulen()
|
|
71
|
-
v = v.upush(len)
|
|
72
|
-
v.ulen() + v.uat(n - 1)
|
|
73
|
-
|
|
74
|
-
# Shape 7: two Vecs in one struct, both pushed.
|
|
75
|
-
|
|
76
|
-
struct Pair7(mut xs: UVec[Int], mut ys: UVec[Int])
|
|
77
|
-
|
|
78
|
-
fun run7(n: Int) -> Int =
|
|
79
|
-
p := Pair7(xs: UVec[Int](), ys: UVec[Int]())
|
|
80
|
-
for i := range n
|
|
81
|
-
p.xs = p.xs.upush(i)
|
|
82
|
-
p.ys = p.ys.upush(i * 2)
|
|
83
|
-
p.xs.ulen() + p.ys.ulen() + p.xs.uat(n - 1) + p.ys.uat(n - 1)
|
|
84
|
-
|
|
85
|
-
# Shape 11b: the per-frame update on a Vec held in a local and handed through a function, no struct around it.
|
|
86
|
-
|
|
87
|
-
fun frame13(v: UVec[Int], n: Int) -> UVec[Int] =
|
|
88
|
-
for i := range n
|
|
89
|
-
v = v.uset(i, v.uat(i) + 1)
|
|
90
|
-
v
|
|
91
|
-
|
|
92
|
-
fun run13(n: Int, frames: Int) -> Int =
|
|
93
|
-
v := UVec[Int]()
|
|
94
|
-
for i := range n
|
|
95
|
-
v = v.upush(0)
|
|
96
|
-
for f := range frames
|
|
97
|
-
v = frame13(v, n)
|
|
98
|
-
v.uat(0) + v.uat(n - 1)
|
|
99
|
-
|
|
100
|
-
# Shape 9b: a function that returns a Vec it built in a local, called twice, the result pushed by the caller.
|
|
101
|
-
|
|
102
|
-
fun make15(n: Int) -> UVec[Int] =
|
|
103
|
-
v := UVec[Int]()
|
|
104
|
-
for i := range n
|
|
105
|
-
v = v.upush(i)
|
|
106
|
-
v
|
|
107
|
-
|
|
108
|
-
fun run15(n: Int) -> Int =
|
|
109
|
-
v := make15(n)
|
|
110
|
-
w := UVec[Int]()
|
|
111
|
-
for i := range n
|
|
112
|
-
w = w.upush(i)
|
|
113
|
-
v.ulen() + w.ulen()
|
|
114
|
-
|
|
115
|
-
fun main(io: Io) =
|
|
116
|
-
t1 := Time.now(io).toMillis()
|
|
117
|
-
r1 := run1(100000)
|
|
118
|
-
u1 := Time.now(io).toMillis()
|
|
119
|
-
io.printLn("uvec_combined shape 1 result={r1} ms={u1 - t1}")
|
|
120
|
-
t2 := Time.now(io).toMillis()
|
|
121
|
-
r2 := run2(100000)
|
|
122
|
-
u2 := Time.now(io).toMillis()
|
|
123
|
-
io.printLn("uvec_combined shape 2 result={r2} ms={u2 - t2}")
|
|
124
|
-
t3 := Time.now(io).toMillis()
|
|
125
|
-
r3 := run3(100000)
|
|
126
|
-
u3 := Time.now(io).toMillis()
|
|
127
|
-
io.printLn("uvec_combined shape 3 result={r3} ms={u3 - t3}")
|
|
128
|
-
t4 := Time.now(io).toMillis()
|
|
129
|
-
r4 := run4(100000)
|
|
130
|
-
u4 := Time.now(io).toMillis()
|
|
131
|
-
io.printLn("uvec_combined shape 4 result={r4} ms={u4 - t4}")
|
|
132
|
-
t5 := Time.now(io).toMillis()
|
|
133
|
-
r5 := run5(100000)
|
|
134
|
-
u5 := Time.now(io).toMillis()
|
|
135
|
-
io.printLn("uvec_combined shape 5 result={r5} ms={u5 - t5}")
|
|
136
|
-
t6 := Time.now(io).toMillis()
|
|
137
|
-
r6 := run6(100000)
|
|
138
|
-
u6 := Time.now(io).toMillis()
|
|
139
|
-
io.printLn("uvec_combined shape 6 result={r6} ms={u6 - t6}")
|
|
140
|
-
t7 := Time.now(io).toMillis()
|
|
141
|
-
r7 := run7(100000)
|
|
142
|
-
u7 := Time.now(io).toMillis()
|
|
143
|
-
io.printLn("uvec_combined shape 7 result={r7} ms={u7 - t7}")
|
|
144
|
-
t13 := Time.now(io).toMillis()
|
|
145
|
-
r13 := run13(20000, 200)
|
|
146
|
-
u13 := Time.now(io).toMillis()
|
|
147
|
-
io.printLn("uvec_combined shape 13 result={r13} ms={u13 - t13}")
|
|
148
|
-
t15 := Time.now(io).toMillis()
|
|
149
|
-
r15 := run15(100000)
|
|
150
|
-
u15 := Time.now(io).toMillis()
|
|
151
|
-
io.printLn("uvec_combined shape 15 result={r15} ms={u15 - t15}")
|
|
152
|
-
|
|
153
|
-
test "vec local"
|
|
154
|
-
assert run1(1000) == 2499
|
|
155
|
-
|
|
156
|
-
test "vec mutfield"
|
|
157
|
-
assert run2(1000) == 2999
|
|
158
|
-
|
|
159
|
-
test "vec nested"
|
|
160
|
-
assert run3(1000) == 2004
|
|
161
|
-
|
|
162
|
-
test "vec helper"
|
|
163
|
-
assert run4(1000) == 2998
|
|
164
|
-
|
|
165
|
-
test "vec generic"
|
|
166
|
-
assert run5(1000) == 2999
|
|
167
|
-
|
|
168
|
-
test "vec readbetween"
|
|
169
|
-
assert run6(1000) == 1999
|
|
170
|
-
|
|
171
|
-
test "vec twolists"
|
|
172
|
-
assert run7(1000) == 4997
|
|
173
|
-
|
|
174
|
-
test "vec frameslocal"
|
|
175
|
-
assert run13(50, 5) == 10
|
|
176
|
-
|
|
177
|
-
test "vec returned2"
|
|
178
|
-
assert run15(500) == 1000
|
tests/shadowed_effects.plum
CHANGED
|
@@ -84,21 +84,6 @@ fun incParam(xs: Link, t: Link) -> Link =
|
|
|
84
84
|
Nil => incParam(t, Nil)
|
|
85
85
|
Cons(h, t) => Cons(head: h + 1, tail: Nil)
|
|
86
86
|
|
|
87
|
-
# the subject is not the caller's fresh value
|
|
88
|
-
fun incRebound(xs: Link, o: Link) -> Link =
|
|
89
|
-
xs = o
|
|
90
|
-
match xs
|
|
91
|
-
Nil => Nil
|
|
92
|
-
Cons(h, t) => Cons(head: h + 1, tail: Nil)
|
|
93
|
-
|
|
94
|
-
# the pattern binder no longer holds the tail
|
|
95
|
-
fun incLocal(xs: Link, o: Link) -> Link =
|
|
96
|
-
match xs
|
|
97
|
-
Nil => Nil
|
|
98
|
-
Cons(h, t) =>
|
|
99
|
-
t = o
|
|
100
|
-
Cons(head: h + 1, tail: incLocal(t, Nil))
|
|
101
|
-
|
|
102
87
|
# Tail recursion modulo cons: a binder named like the fn is not a self call.
|
|
103
88
|
enum Maker =
|
|
104
89
|
| Has(go: fn(Maker) -> Link)
|
|
@@ -145,16 +130,6 @@ test "reuse leaves a parameter named like a pattern binder alone"
|
|
|
145
130
|
assert headOf(incParam(Nil, s)) == 2
|
|
146
131
|
assert headOf(s) == 1
|
|
147
132
|
|
|
148
|
-
test "reuse leaves a rebound subject alone"
|
|
149
|
-
s := Cons(head: 1, tail: Nil)
|
|
150
|
-
assert headOf(incRebound(Nil, s)) == 2
|
|
151
|
-
assert headOf(s) == 1
|
|
152
|
-
|
|
153
|
-
test "reuse leaves a rebound pattern binder alone"
|
|
154
|
-
s := Cons(head: 1, tail: Nil)
|
|
155
|
-
assert headOf(incLocal(Cons(head: 5, tail: Nil), s)) == 6
|
|
156
|
-
assert headOf(s) == 1
|
|
157
|
-
|
|
158
133
|
test "a binder named like the fn is not a self call"
|
|
159
134
|
assert size(go(Has(go: |m: Maker| Nil))) == 1
|
|
160
135
|
assert size(loc(3)) == 1
|
tests/syntax/block_closures.plum
CHANGED
|
@@ -65,15 +65,6 @@ fun nested(n: Int) -> Int =
|
|
|
65
65
|
acc + inner
|
|
66
66
|
)
|
|
67
67
|
|
|
68
|
-
# A captured value is copied at creation.
|
|
69
|
-
fun captured() -> Int =
|
|
70
|
-
k := 10
|
|
71
|
-
f := |x|
|
|
72
|
-
y := x + k
|
|
73
|
-
y * 2
|
|
74
|
-
k = 99
|
|
75
|
-
f(1)
|
|
76
|
-
|
|
77
68
|
fun stored() -> Int =
|
|
78
69
|
f := |a, b|
|
|
79
70
|
s := a + b
|
|
@@ -122,8 +113,7 @@ test "last expression is match or if"
|
|
|
122
113
|
test "nested"
|
|
123
114
|
assert nested(3) == 25
|
|
124
115
|
|
|
125
|
-
test "
|
|
116
|
+
test "stored"
|
|
126
|
-
assert captured() == 22
|
|
127
117
|
assert stored() == 58
|
|
128
118
|
|
|
129
119
|
test "record accumulator"
|
tests/syntax/block_values_passes.plum
CHANGED
|
@@ -166,7 +166,7 @@ fun sumList(xs: List[Int]) -> Int = match xs
|
|
|
166
166
|
|
|
167
167
|
fun alternating(n: Int) -> Int = sumList(upTo(n))
|
|
168
168
|
|
|
169
|
-
# ---- other positions: loops,
|
|
169
|
+
# ---- other positions: loops, closures, conditions ----
|
|
170
170
|
|
|
171
171
|
fun loopInBlock(n: Int) -> Int =
|
|
172
172
|
v := if n > 0
|
|
@@ -178,13 +178,6 @@ fun loopInBlock(n: Int) -> Int =
|
|
|
178
178
|
0 - 1
|
|
179
179
|
v
|
|
180
180
|
|
|
181
|
-
fun retInBlock(n: Int) -> Int =
|
|
182
|
-
v := if n > 5
|
|
183
|
-
return 99
|
|
184
|
-
else
|
|
185
|
-
n * 2
|
|
186
|
-
v + 1
|
|
187
|
-
|
|
188
181
|
fun blockInLoop(n: Int) -> Int =
|
|
189
182
|
t := Tally(n: 0)
|
|
190
183
|
for i := range n
|
|
@@ -361,11 +354,9 @@ test "a million deep"
|
|
|
361
354
|
assert total(buildHead(1000000), 0) == 500001000000
|
|
362
355
|
assert count(1000000, 0) == 1333333
|
|
363
356
|
|
|
364
|
-
test "loops,
|
|
357
|
+
test "loops, closures and conditional positions"
|
|
365
358
|
assert loopInBlock(4) == 6
|
|
366
359
|
assert loopInBlock(0) == 0 - 1
|
|
367
|
-
assert retInBlock(9) == 99
|
|
368
|
-
assert retInBlock(2) == 5
|
|
369
360
|
assert blockInLoop(5) == 1 + 2 + 4 + 5
|
|
370
361
|
assert condBlock(7)
|
|
371
362
|
assert !condBlock(3)
|
tests/syntax/loops.plum
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/List
|
|
3
|
+
import std/Option
|
|
4
|
+
import std/Slice
|
|
5
|
+
|
|
6
|
+
# `for` and `while cond` are for side effects: the body acts through a `mut`
|
|
7
|
+
# field. A local can't be reassigned, so state lives in a field.
|
|
8
|
+
|
|
9
|
+
struct Tally(mut acc: Int)
|
|
10
|
+
|
|
11
|
+
struct Queue(mut items: Slice[Int], mut seen: Int)
|
|
12
|
+
|
|
13
|
+
fun forRange() -> Int =
|
|
14
|
+
t := Tally(acc: 0)
|
|
15
|
+
for i := range 4
|
|
16
|
+
t.acc = t.acc * 10 + i + 1
|
|
17
|
+
t.acc
|
|
18
|
+
|
|
19
|
+
fun forList() -> Int =
|
|
20
|
+
t := Tally(acc: 0)
|
|
21
|
+
for x := range [7, 8, 9]
|
|
22
|
+
t.acc = t.acc * 10 + x
|
|
23
|
+
t.acc
|
|
24
|
+
|
|
25
|
+
fun forSlice() -> Int =
|
|
26
|
+
xs := Slice[Int]()
|
|
27
|
+
xs.push(3)
|
|
28
|
+
xs.push(4)
|
|
29
|
+
xs.push(5)
|
|
30
|
+
t := Tally(acc: 0)
|
|
31
|
+
for x := range xs
|
|
32
|
+
t.acc = t.acc * 10 + x
|
|
33
|
+
t.acc
|
|
34
|
+
|
|
35
|
+
fun drain(n: Int) -> Int =
|
|
36
|
+
q := Queue(items: Slice[Int](), seen: 0)
|
|
37
|
+
for i := range n
|
|
38
|
+
q.items.push(i)
|
|
39
|
+
while Some(v) := q.items.pop()
|
|
40
|
+
q.seen = q.seen + 1
|
|
41
|
+
q.seen
|
|
42
|
+
|
|
43
|
+
fun neverRuns() -> Int =
|
|
44
|
+
t := Tally(acc: 5)
|
|
45
|
+
while t.acc < 0
|
|
46
|
+
t.acc = t.acc + 1
|
|
47
|
+
t.acc
|
|
48
|
+
|
|
49
|
+
fun countsUp() -> Int =
|
|
50
|
+
t := Tally(acc: 0)
|
|
51
|
+
while t.acc < 1000000
|
|
52
|
+
t.acc = t.acc + 1
|
|
53
|
+
t.acc
|
|
54
|
+
|
|
55
|
+
test "for over a range"
|
|
56
|
+
assert forRange() == 1234
|
|
57
|
+
|
|
58
|
+
test "for over a list"
|
|
59
|
+
assert forList() == 789
|
|
60
|
+
|
|
61
|
+
test "for over a slice"
|
|
62
|
+
assert forSlice() == 345
|
|
63
|
+
|
|
64
|
+
test "while drains a mut queue a million times"
|
|
65
|
+
assert drain(1000000) == 1000000
|
|
66
|
+
|
|
67
|
+
test "while that is false at the start never runs its body"
|
|
68
|
+
assert neverRuns() == 5
|
|
69
|
+
|
|
70
|
+
test "while counting a million passes in a field"
|
|
71
|
+
assert countsUp() == 1000000
|
tests/wasm_codegen/e2e_mem/unique_spread_reassign_local.plum
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
struct Cell(x: Int, y: Int)
|
|
7
|
-
|
|
8
|
-
fun runMain() -> Int =
|
|
9
|
-
s := Cell(x: 1, y: 7)
|
|
10
|
-
s = Cell(..s, x: s.x + 1)
|
|
11
|
-
s = Cell(..s, y: s.y + s.x)
|
|
12
|
-
s.x * 100 + s.y
|
|
13
|
-
|
|
14
|
-
# moved from e2e_mem::unique_inplace::unique_spread_reassign_local
|
|
15
|
-
test "unique spread reassign local"
|
|
16
|
-
assert runMain() == 209
|
tests/wasm_codegen/e2e_records/reassign_enum_local_across_variants.plum
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
|
|
5
|
-
enum Shape = Circle(r: Int) | Rect(w: Int, h: Int)
|
|
6
|
-
|
|
7
|
-
fun area(s: Shape) -> Int =
|
|
8
|
-
match s
|
|
9
|
-
Circle(r) => r * 3
|
|
10
|
-
Rect(w, h) => w * h
|
|
11
|
-
|
|
12
|
-
fun kind(s: Shape) -> Int =
|
|
13
|
-
match s
|
|
14
|
-
Circle(_) => 1
|
|
15
|
-
Rect(_, _) => 10
|
|
16
|
-
|
|
17
|
-
fun runMain() -> Int =
|
|
18
|
-
s: Shape := Circle(r: 1)
|
|
19
|
-
n := area(s)
|
|
20
|
-
s = Rect(w: 2, h: 5)
|
|
21
|
-
n = n * 100 + area(s)
|
|
22
|
-
k := 0
|
|
23
|
-
for i := range 4
|
|
24
|
-
if i % 2 == 0
|
|
25
|
-
s = Rect(w: 1, h: 1)
|
|
26
|
-
else
|
|
27
|
-
s = Circle(r: 1)
|
|
28
|
-
k = k + kind(s)
|
|
29
|
-
n * 100 + k
|
|
30
|
-
|
|
31
|
-
# moved from e2e_records::unboxed_variants::reassign_enum_local_across_variants
|
|
32
|
-
test "reassign enum local across variants"
|
|
33
|
-
assert runMain() == 31022
|
tests/wasm_codegen/e2e_tail/break_in_else_if_chain_in_while.plum
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
fun runMain() -> Int =
|
|
7
|
-
i := 0
|
|
8
|
-
while i < 50
|
|
9
|
-
if i == 100
|
|
10
|
-
i = i + 1000
|
|
11
|
-
else if i == 100
|
|
12
|
-
i = i + 2000
|
|
13
|
-
else if i == 7
|
|
14
|
-
break
|
|
15
|
-
i = i + 1
|
|
16
|
-
return i
|
|
17
|
-
|
|
18
|
-
# moved from e2e_tail::loop_break::break_in_else_if_chain_in_while
|
|
19
|
-
test "break in else if chain in while"
|
|
20
|
-
assert runMain() == 7
|
tests/wasm_codegen/e2e_tail/break_in_if_in_match_arm_in_while.plum
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
enum Lst = Nil | Cons(head: Int, tail: Lst)
|
|
8
|
-
|
|
9
|
-
fun build(n: Int, acc: Lst) -> Lst =
|
|
10
|
-
if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
|
11
|
-
|
|
12
|
-
fun find(xs: Lst, target: Int) -> Int =
|
|
13
|
-
i := 0
|
|
14
|
-
cur := xs
|
|
15
|
-
while i < 50
|
|
16
|
-
match cur
|
|
17
|
-
Cons(h, t) =>
|
|
18
|
-
if h == target
|
|
19
|
-
break
|
|
20
|
-
cur = t
|
|
21
|
-
Nil =>
|
|
22
|
-
break
|
|
23
|
-
i = i + 1
|
|
24
|
-
return i
|
|
25
|
-
|
|
26
|
-
fun runMain() -> Int = find(build(10, Nil), 4) * 100 + find(build(10, Nil), 99)
|
|
27
|
-
|
|
28
|
-
# moved from e2e_tail::loop_break::break_in_if_in_match_arm_in_while
|
|
29
|
-
test "break in if in match arm in while"
|
|
30
|
-
assert runMain() == 310
|
tests/wasm_codegen/e2e_tail/break_in_match_arm_direct.plum
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
enum Lst = Nil | Cons(head: Int, tail: Lst)
|
|
8
|
-
|
|
9
|
-
fun build(n: Int, acc: Lst) -> Lst =
|
|
10
|
-
if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
|
11
|
-
|
|
12
|
-
fun count(xs: Lst) -> Int =
|
|
13
|
-
i := 0
|
|
14
|
-
cur := xs
|
|
15
|
-
while i < 50
|
|
16
|
-
match cur
|
|
17
|
-
Nil =>
|
|
18
|
-
break
|
|
19
|
-
Cons(h, t) =>
|
|
20
|
-
cur = t
|
|
21
|
-
i = i + 1
|
|
22
|
-
return i
|
|
23
|
-
|
|
24
|
-
fun wild(n: Int) -> Int =
|
|
25
|
-
i := 0
|
|
26
|
-
while i < 50
|
|
27
|
-
match i
|
|
28
|
-
_ =>
|
|
29
|
-
break
|
|
30
|
-
i = i + 1
|
|
31
|
-
return i + n
|
|
32
|
-
|
|
33
|
-
fun runMain() -> Int = count(build(5, Nil)) * 100 + wild(7)
|
|
34
|
-
|
|
35
|
-
# moved from e2e_tail::loop_break::break_in_match_arm_direct
|
|
36
|
-
test "break in match arm direct"
|
|
37
|
-
assert runMain() == 507
|
tests/wasm_codegen/e2e_tail/continue_in_if_in_match_arm_in_while.plum
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
enum Lst = Nil | Cons(head: Int, tail: Lst)
|
|
8
|
-
|
|
9
|
-
fun build(n: Int, acc: Lst) -> Lst =
|
|
10
|
-
if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
|
11
|
-
|
|
12
|
-
fun sumOdd(xs: Lst) -> Int =
|
|
13
|
-
total := 0
|
|
14
|
-
i := 0
|
|
15
|
-
cur := xs
|
|
16
|
-
while i < 50
|
|
17
|
-
i = i + 1
|
|
18
|
-
match cur
|
|
19
|
-
Cons(h, t) =>
|
|
20
|
-
cur = t
|
|
21
|
-
if h % 2 == 0
|
|
22
|
-
continue
|
|
23
|
-
total = total + h
|
|
24
|
-
Nil =>
|
|
25
|
-
break
|
|
26
|
-
return total * 100 + i
|
|
27
|
-
|
|
28
|
-
fun runMain() -> Int = sumOdd(build(6, Nil))
|
|
29
|
-
|
|
30
|
-
# moved from e2e_tail::loop_break::continue_in_if_in_match_arm_in_while
|
|
31
|
-
# 1 + 3 + 5 = 9; seven iterations (six cons cells then Nil).
|
|
32
|
-
test "continue in if in match arm in while"
|
|
33
|
-
assert runMain() == 907
|
tests/wasm_codegen/e2e_tail/nested_loops_with_match_in_inner.plum
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import std/Str
|
|
2
|
-
import std/Int
|
|
3
|
-
import std/Float
|
|
4
|
-
import std/Slice
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
enum Lst = Nil | Cons(head: Int, tail: Lst)
|
|
8
|
-
|
|
9
|
-
fun build(n: Int, acc: Lst) -> Lst =
|
|
10
|
-
if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
|
11
|
-
|
|
12
|
-
fun runMain() -> Int =
|
|
13
|
-
outer := 0
|
|
14
|
-
hits := 0
|
|
15
|
-
while outer < 50
|
|
16
|
-
if outer == 3
|
|
17
|
-
break
|
|
18
|
-
cur := build(5, Nil)
|
|
19
|
-
j := 0
|
|
20
|
-
while j < 50
|
|
21
|
-
match cur
|
|
22
|
-
Cons(h, t) =>
|
|
23
|
-
cur = t
|
|
24
|
-
if h == 2
|
|
25
|
-
j = j + 1
|
|
26
|
-
continue
|
|
27
|
-
if h == 4
|
|
28
|
-
break
|
|
29
|
-
hits = hits + 1
|
|
30
|
-
Nil =>
|
|
31
|
-
break
|
|
32
|
-
j = j + 1
|
|
33
|
-
outer = outer + 1
|
|
34
|
-
return outer * 100 + hits
|
|
35
|
-
|
|
36
|
-
# moved from e2e_tail::loop_break::nested_loops_with_match_in_inner
|
|
37
|
-
# inner: h=1 hit, h=2 skipped, h=3 hit, h=4 break => 2 hits per outer pass, 3 passes.
|
|
38
|
-
test "nested loops with match in inner"
|
|
39
|
-
assert runMain() == 306
|