plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
7757280
— Peter John
2026-11-06T19:40:29+05:30
Block if and match values are real expressions
- compiler/checker/src/closurehints.rs +1 -0
- compiler/checker/src/fields.rs +5 -0
- compiler/checker/src/fncheck.rs +1 -0
- compiler/checker/src/infer.rs +2 -5
- compiler/checker/src/matchcheck.rs +0 -1
- compiler/checker/src/state.rs +6 -0
- compiler/checker/src/stmt.rs +54 -32
- compiler/checker/tests/checker/syntax_tests.rs +49 -5
- compiler/core/src/ast.rs +6 -3
- compiler/core/src/blocks.rs +259 -229
- compiler/core/src/closure_spec.rs +20 -1
- compiler/core/src/drive.rs +47 -21
- compiler/core/src/forms.rs +24 -7
- compiler/core/src/lower.rs +1 -1
- compiler/core/src/modules.rs +6 -0
- compiler/core/src/question.rs +18 -1
- compiler/core/src/rename.rs +2 -0
- compiler/core/src/simplify.rs +23 -2
- compiler/core/src/tail.rs +2 -0
- compiler/core/src/trmc.rs +5 -2
- compiler/core/src/uniqueness.rs +7 -0
- compiler/core/src/visit.rs +23 -0
- compiler/core/tests/core/syntax_test.rs +33 -6
- compiler/wasm-codegen/src/closures.rs +8 -2
- compiler/wasm-codegen/src/expr.rs +11 -2
- compiler/wasm-codegen/src/fnbody.rs +5 -2
- compiler/wasm-codegen/src/freevars.rs +7 -0
- compiler/wasm-codegen/src/stmts.rs +5 -1
- tests/syntax/block_values.plum +15 -2
- tests/syntax/block_values_passes.plum +383 -0
compiler/checker/src/closurehints.rs
CHANGED
|
@@ -144,6 +144,7 @@ pub(crate) fn firstCallInExpr<'a>(expr: &'a ast::Expr, name: &str) -> Option<Clo
|
|
|
144
144
|
_ => None,
|
|
145
145
|
}),
|
|
146
146
|
ast::Expr { kind: ast::ExprKind::ClassCall(c), .. } => c.fields.iter().find_map(|f| firstCallInExpr(&f.value, name)),
|
|
147
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => b.stmts.iter().find_map(|s| firstCallInStmt(s, name)),
|
|
147
148
|
ast::Expr { kind: ast::ExprKind::String(s), .. } => s.parts.iter().find_map(|p| match p {
|
|
148
149
|
ast::StringPart::Interp(e) => firstCallInExpr(e, name),
|
|
149
150
|
_ => None,
|
compiler/checker/src/fields.rs
CHANGED
|
@@ -85,6 +85,11 @@ pub(crate) fn resolveClosureParamFromFieldUsage(
|
|
|
85
85
|
scanExpr(&t.then, params, ctx, resolved);
|
|
86
86
|
scanExpr(&t.else_, params, ctx, resolved);
|
|
87
87
|
}
|
|
88
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => {
|
|
89
|
+
for s in &b.stmts {
|
|
90
|
+
resolveClosureParamFromFieldUsage(s, params, ctx, resolved);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
88
93
|
_ => {}
|
|
89
94
|
}
|
|
90
95
|
}
|
compiler/checker/src/fncheck.rs
CHANGED
|
@@ -190,6 +190,7 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
|
|
|
190
190
|
.map(|r| plumTypeFromAstG(r))
|
|
191
191
|
.unwrap_or(PlumType::TUnit);
|
|
192
192
|
|
|
193
|
+
withCheck(|s| *s.cur_ret.borrow_mut() = Some(declared_ret.clone()));
|
|
193
194
|
match &f.body {
|
|
194
195
|
ast::FnBody::Expr(e) => {
|
|
195
196
|
if let Some(err) = checkReturned(e, &env, ctx, &declared_ret, &f.name, (f.line, f.column)) {
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -186,11 +186,8 @@ pub(crate) fn inferExprInner(
|
|
|
186
186
|
ast::Expr { kind: ast::ExprKind::Question(_), .. } => {
|
|
187
187
|
Err("'?' is not allowed here: it was not lowered (see the earlier error)".to_string())
|
|
188
188
|
}
|
|
189
|
-
//
|
|
189
|
+
// A block `if` / `match` used as a value: typed as the join of its branches.
|
|
190
|
-
// sits where no statement can come first.
|
|
191
|
-
ast::Expr { kind: ast::ExprKind::Block(
|
|
190
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => inferBlockValue(b, env, ctx, expected),
|
|
192
|
-
Err("a block 'if' or 'match' used as a value is not allowed here".to_string())
|
|
193
|
-
}
|
|
194
191
|
ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => {
|
|
195
192
|
let self_name = withCheck(|s| s.closure_self.borrow_mut().take());
|
|
196
193
|
let mut closure_env = env.clone();
|
compiler/checker/src/matchcheck.rs
CHANGED
|
@@ -305,7 +305,6 @@ pub(crate) fn checkMatch(
|
|
|
305
305
|
fn_pos,
|
|
306
306
|
ctx,
|
|
307
307
|
));
|
|
308
|
-
crate::stmt::hoistBlockVars(&case_env, env);
|
|
309
308
|
}
|
|
310
309
|
errors
|
|
311
310
|
}
|
compiler/checker/src/state.rs
CHANGED
|
@@ -47,6 +47,12 @@ pub(crate) struct CheckState {
|
|
|
47
47
|
/// value must have, so its generic arguments are pinned like a returned expression's.
|
|
48
48
|
pub(crate) tail: RefCell<Option<PlumType>>,
|
|
49
49
|
pub(crate) match_tail: RefCell<Option<PlumType>>,
|
|
50
|
+
/// One entry per block `if` / `match` value being checked (innermost last): the type its
|
|
51
|
+
/// context expects, and the type of every branch's last value, in order (`inferBlockValue`).
|
|
52
|
+
pub(crate) block_vals: RefCell<Vec<(Option<PlumType>, Vec<PlumType>)>>,
|
|
53
|
+
/// The declared return type of the fn (or closure) whose statement is being checked, for a
|
|
54
|
+
/// `return` inside a block value.
|
|
55
|
+
pub(crate) cur_ret: RefCell<Option<PlumType>>,
|
|
50
56
|
/// Operator expressions (by node id) on non-primitive operands -> the synthetic method call
|
|
51
57
|
/// (`a + b` -> `a.add(b)`) they resolve to.
|
|
52
58
|
pub(crate) op_calls: RefCell<HashMap<plum_core::ast::NodeId, std::rc::Rc<ast::FnCall>>>,
|
compiler/checker/src/stmt.rs
CHANGED
|
@@ -2,15 +2,45 @@
|
|
|
2
2
|
|
|
3
3
|
use crate::*;
|
|
4
4
|
|
|
5
|
+
/// The `tail` type of the last statement of a block `if` / `match` used as a value: its branches
|
|
6
|
+
/// report their type to `inferBlockValue` instead of checking it against a known type.
|
|
7
|
+
pub(crate) const BLOCK_TAIL: &str = "__block_value";
|
|
8
|
+
|
|
5
|
-
///
|
|
9
|
+
/// The type of a block `if` / `match` used as a value (`v := if a` + indented branches): its
|
|
6
|
-
/// every branch (`plum_core::blocks`); that variable belongs to the code after the statement,
|
|
7
|
-
///
|
|
10
|
+
/// statements are checked in a scope of their own, and the value is the join of the last value of
|
|
11
|
+
/// every branch (a branch that returns, crashes or loops on has none). Each branch pins what the
|
|
12
|
+
/// others leave open (`Ok(1)` / `Err(Bad)`), as for an inline `if`.
|
|
13
|
+
pub(crate) fn inferBlockValue(
|
|
14
|
+
b: &ast::Block,
|
|
15
|
+
env: &TypeEnv,
|
|
16
|
+
ctx: &CheckCtx,
|
|
17
|
+
expected: Option<&PlumType>,
|
|
18
|
+
) -> Result<PlumType, String> {
|
|
19
|
+
let ret = withCheck(|s| s.cur_ret.borrow().clone()).unwrap_or_else(|| PlumType::TVar("_".to_string()));
|
|
8
|
-
|
|
20
|
+
withCheck(|s| s.block_vals.borrow_mut().push((expected.cloned(), Vec::new())));
|
|
9
|
-
for (k, v) in from {
|
|
10
|
-
if k.starts_with(plum_core::blocks::BLOCK_VAR_PREFIX) && !into.contains_key(k) {
|
|
11
|
-
|
|
21
|
+
let mut benv = env.clone();
|
|
22
|
+
withCheck(|s| *s.tail.borrow_mut() = Some(PlumType::TVar(BLOCK_TAIL.to_string())));
|
|
23
|
+
let errors = checkBlock(b, &mut benv, &ret, "", (0, 0), ctx);
|
|
24
|
+
withCheck(|s| *s.tail.borrow_mut() = None);
|
|
25
|
+
let (_, vals) = withCheck(|s| s.block_vals.borrow_mut().pop()).unwrap_or_default();
|
|
26
|
+
if let Some(first) = errors.into_iter().next() {
|
|
27
|
+
if first.line > 0 {
|
|
28
|
+
withCheck(|s| s.err_pos.set(Some(((first.line, first.column), (first.end_line, first.end_column)))));
|
|
12
29
|
}
|
|
30
|
+
let msg = first.message.strip_prefix("fn '': ").unwrap_or(&first.message).to_string();
|
|
31
|
+
return Err(msg);
|
|
13
32
|
}
|
|
33
|
+
let mut vals = vals.into_iter();
|
|
34
|
+
let Some(joined) = vals.next() else {
|
|
35
|
+
return Ok(PlumType::TVar("_".to_string()));
|
|
36
|
+
};
|
|
37
|
+
let mut binds = Binds::new();
|
|
38
|
+
for t in vals {
|
|
39
|
+
unify(&joined, &t, ctx).map_err(|e| format!("the branches of an 'if' or 'match' used as a value differ: {e}"))?;
|
|
40
|
+
bindMatch(&joined, &t, &mut binds);
|
|
41
|
+
bindMatch(&t, &joined, &mut binds);
|
|
42
|
+
}
|
|
43
|
+
Ok(substVars(&joined, &binds))
|
|
14
44
|
}
|
|
15
45
|
|
|
16
46
|
pub(crate) fn checkStmt(
|
|
@@ -21,7 +51,9 @@ pub(crate) fn checkStmt(
|
|
|
21
51
|
fn_pos: (usize, usize),
|
|
22
52
|
ctx: &CheckCtx,
|
|
23
53
|
) -> Vec<CheckError> {
|
|
54
|
+
let prev_ret = withCheck(|s| s.cur_ret.replace(Some(declared_ret.clone())));
|
|
24
55
|
let (mut errors, pos, _) = withFailure(|| checkStmtInner(stmt, env, declared_ret, fn_name, fn_pos, ctx));
|
|
56
|
+
withCheck(|s| *s.cur_ret.borrow_mut() = prev_ret);
|
|
25
57
|
if let Some(((l, c), (el, ec))) = pos {
|
|
26
58
|
for e in errors.iter_mut().filter(|e| (e.line, e.column) == fn_pos) {
|
|
27
59
|
e.line = l;
|
|
@@ -30,21 +62,6 @@ pub(crate) fn checkStmt(
|
|
|
30
62
|
e.end_column = ec;
|
|
31
63
|
}
|
|
32
64
|
}
|
|
33
|
-
// A branch value of a block `if` / `match` used as a value (`plum_core::blocks`).
|
|
34
|
-
for e in errors.iter_mut() {
|
|
35
|
-
let marker = format!("assign '{}", plum_core::blocks::BLOCK_VAR_PREFIX);
|
|
36
|
-
if let Some(i) = e.message.find(&marker) {
|
|
37
|
-
let rest = e.message[i..].split_once("': ").map(|x| x.1.to_string()).unwrap_or_default();
|
|
38
|
-
let fnPart = e.message[..i].trim_end_matches(": ").to_string();
|
|
39
|
-
e.message = format!("{fnPart}: the branches of an 'if' or 'match' used as a value differ: {rest}");
|
|
40
|
-
if stmt.span.startLine > 0 {
|
|
41
|
-
e.line = stmt.span.startLine;
|
|
42
|
-
e.column = stmt.span.startColumn;
|
|
43
|
-
e.end_line = stmt.span.endLine;
|
|
44
|
-
e.end_column = stmt.span.endColumn;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
65
|
errors
|
|
49
66
|
}
|
|
50
67
|
|
|
@@ -172,13 +189,6 @@ pub(crate) fn checkStmtInner(
|
|
|
172
189
|
fn_pos.1,
|
|
173
190
|
format!("fn '{}': assign '{}': {}", fn_name, name, msg),
|
|
174
191
|
));
|
|
175
|
-
} else if name.starts_with(plum_core::blocks::BLOCK_VAR_PREFIX) {
|
|
176
|
-
// Each branch pins what the other leaves open (`Ok(1)` /
|
|
177
|
-
// `Err(Bad)`); bind both ways so every branch builds the
|
|
178
|
-
// one joined instantiation (as an inline `if` does).
|
|
179
|
-
let mut binds = Binds::new();
|
|
180
|
-
bindMatch(&existing, &t, &mut binds);
|
|
181
|
-
bindMatch(&t, &existing, &mut binds);
|
|
182
192
|
} else if matches!(existing, PlumType::TVar(_)) {
|
|
183
193
|
// `unify` never narrows a `TVar` itself —
|
|
184
194
|
// once a concrete type is available, record
|
|
@@ -363,7 +373,6 @@ pub(crate) fn checkStmtInner(
|
|
|
363
373
|
fn_pos,
|
|
364
374
|
ctx,
|
|
365
375
|
));
|
|
366
|
-
hoistBlockVars(&benv, env);
|
|
367
376
|
for ei in &if_.else_ifs {
|
|
368
377
|
match inferExpr(&ei.condition, env, ctx) {
|
|
369
378
|
Ok(t) => {
|
|
@@ -394,7 +403,6 @@ pub(crate) fn checkStmtInner(
|
|
|
394
403
|
fn_pos,
|
|
395
404
|
ctx,
|
|
396
405
|
));
|
|
397
|
-
hoistBlockVars(&eenv, env);
|
|
398
406
|
}
|
|
399
407
|
if let Some(else_block) = &if_.else_ {
|
|
400
408
|
set_tail(&tail);
|
|
@@ -436,12 +444,26 @@ pub(crate) fn checkStmtInner(
|
|
|
436
444
|
));
|
|
437
445
|
}
|
|
438
446
|
ast::StmtKind::Expr(e, line, column) => {
|
|
447
|
+
let collecting = matches!(&tail, Some(PlumType::TVar(n)) if n == BLOCK_TAIL);
|
|
448
|
+
let expected = if collecting {
|
|
449
|
+
withCheck(|s| s.block_vals.borrow().last().and_then(|v| v.0.clone()))
|
|
450
|
+
} else {
|
|
451
|
+
tail.clone()
|
|
452
|
+
};
|
|
439
|
-
match inferExprWith(e, env, ctx,
|
|
453
|
+
match inferExprWith(e, env, ctx, expected.as_ref()) {
|
|
440
454
|
Err(msg) => errors.push(CheckError::at(
|
|
441
455
|
*line,
|
|
442
456
|
*column,
|
|
443
457
|
format!("fn '{}': {}", fn_name, msg),
|
|
444
458
|
)),
|
|
459
|
+
// The last value of a branch of a block value (`inferBlockValue` joins them).
|
|
460
|
+
Ok(t) if collecting => {
|
|
461
|
+
withCheck(|s| {
|
|
462
|
+
if let Some(top) = s.block_vals.borrow_mut().last_mut() {
|
|
463
|
+
top.1.push(t);
|
|
464
|
+
}
|
|
465
|
+
});
|
|
466
|
+
}
|
|
445
467
|
// A value-producing tail is the block's value, not a discard.
|
|
446
468
|
Ok(t) if tail.is_none() => {
|
|
447
469
|
if let Some(call) = discardedCall(e) {
|
compiler/checker/tests/checker/syntax_tests.rs
CHANGED
|
@@ -67,16 +67,60 @@ fn block_branches_must_agree() {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
#[test]
|
|
70
|
-
fn
|
|
70
|
+
fn block_in_conditional_position_is_a_real_expression() {
|
|
71
|
+
// evaluated only when the left side allows it, like any other operand
|
|
72
|
+
ok("fun f(a: Bool, b: Bool) -> Bool =\n a && { if b\n true\n else\n false }");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#[test]
|
|
76
|
+
fn question_in_a_value_branch_is_an_error() {
|
|
77
|
+
rejected(
|
|
78
|
+
"fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n v := if a\n h := half(n)?\n h + 1\n else\n 0\n Ok(v)",
|
|
79
|
+
"move it into a function, or use 'match'",
|
|
80
|
+
);
|
|
81
|
+
// also as the branch's value, and in a `match` branch
|
|
82
|
+
rejected(
|
|
83
|
+
"fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n v := if a\n half(n)?\n else\n 0\n Ok(v)",
|
|
84
|
+
"'?' in a block 'if' or 'match' used as a value is not allowed",
|
|
85
|
+
);
|
|
86
|
+
rejected(
|
|
87
|
+
"fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n v := match a\n true => half(n)?\n false => 0\n Ok(v)",
|
|
88
|
+
"'?' in a block 'if' or 'match' used as a value is not allowed",
|
|
89
|
+
);
|
|
90
|
+
// in the condition of the block's `if` too
|
|
91
|
+
rejected(
|
|
92
|
+
"fun f(n: Int) -> Result[Int, Oops] =\n v := if half(n)? > 1\n 1\n else\n 0\n Ok(v)",
|
|
93
|
+
"'?' in a block 'if' or 'match' used as a value is not allowed",
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
#[test]
|
|
98
|
+
fn question_in_a_tail_branch_still_works() {
|
|
99
|
+
ok("fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n if a\n h := half(n)?\n Ok(h + 1)\n else\n Ok(0)");
|
|
100
|
+
ok("fun f(a: Bool, n: Int) -> Result[Int, Oops] =\n match a\n true =>\n h := half(n)?\n Ok(h)\n false => Ok(0)");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
#[test]
|
|
104
|
+
fn block_value_branches_may_reuse_names() {
|
|
105
|
+
ok("fun f(a: Bool) -> Int =\n v := if a\n t := 1\n t\n else\n t := 2\n t + 1\n t := 9\n v + t");
|
|
106
|
+
// a name visible where the block sits is still \"already declared\"
|
|
107
|
+
rejected(
|
|
108
|
+
"fun f(a: Bool) -> Int =\n t := 9\n v := if a\n t := 1\n t\n else\n 2\n v + t",
|
|
109
|
+
"already declared",
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
#[test]
|
|
114
|
+
fn block_value_names_do_not_leak() {
|
|
71
115
|
rejected(
|
|
72
|
-
"fun f(a: Bool
|
|
116
|
+
"fun f(a: Bool) -> Int =\n v := if a\n t := 1\n t\n else\n 2\n v + t",
|
|
73
|
-
"
|
|
117
|
+
"t",
|
|
74
118
|
);
|
|
75
119
|
}
|
|
76
120
|
|
|
77
121
|
#[test]
|
|
78
|
-
fn
|
|
122
|
+
fn block_value_last_line_must_be_a_value() {
|
|
79
|
-
|
|
123
|
+
rejected("fun f(a: Bool) -> Int =\n v := if a\n t := 1\n else\n 2\n v", "must be a value");
|
|
80
124
|
}
|
|
81
125
|
|
|
82
126
|
#[test]
|
compiler/core/src/ast.rs
CHANGED
|
@@ -867,9 +867,12 @@ pub enum ExprKind {
|
|
|
867
867
|
TypeName(String),
|
|
868
868
|
/// `|params| body`
|
|
869
869
|
Closure(Box<Closure>),
|
|
870
|
-
/// A block `if` / `match` used as a value (`v := if a` + indented branches)
|
|
870
|
+
/// A block `if` / `match` used as a value (`v := if a` + indented branches), or the temporaries
|
|
871
|
-
/// only statement is that `if` / `match` (or, after a lowering, any statements); its last
|
|
872
|
-
///
|
|
871
|
+
/// and value of a spread path: statements run in order, and the last value of every path
|
|
872
|
+
/// through the last statement is the result. A real expression in every pass (the checker
|
|
873
|
+
/// types it as the join of its branches, codegen emits wasm control flow with a result).
|
|
874
|
+
/// Runs inline, in the enclosing fn's frame, but its declarations are scoped to it
|
|
875
|
+
/// (`blocks.rs` renames a name that is declared again elsewhere in the fn).
|
|
873
876
|
Block(Box<Block>),
|
|
874
877
|
}
|
|
875
878
|
|
compiler/core/src/blocks.rs
CHANGED
|
@@ -1,302 +1,332 @@
|
|
|
1
|
-
//!
|
|
1
|
+
//! Block `if` / `match` used as values (`ExprKind::Block`): checks before the type checker, and
|
|
2
|
+
//! scoping of the names a block declares.
|
|
2
3
|
//!
|
|
3
|
-
//! `v := if a` + indented branches becomes the statement `if a` whose branches end in
|
|
4
|
-
//!
|
|
4
|
+
//! A block value stays a real expression through every pass: the checker types it as the join of
|
|
5
|
-
//! after the `if`, see `hoistedVars` in the checker), followed by `v := __blkN`. So no
|
|
6
|
-
//!
|
|
5
|
+
//! its branches' last values, and codegen compiles it as wasm control flow with a result. This
|
|
6
|
+
//! pass only
|
|
7
7
|
//!
|
|
8
|
-
//! * Several blocks in one statement are lifted in evaluation order; an earlier operand that is
|
|
9
|
-
//! not trivial is bound to a temporary first, so the order is kept (same rule as `question.rs`).
|
|
10
|
-
//! * A block in a conditionally evaluated position (the right side of `&&` / `||`, a branch of an
|
|
11
|
-
//! inline `if`, an `else if` condition, a `when` guard, a loop condition) is an error: bind it
|
|
12
|
-
//! to a local first.
|
|
13
|
-
//! *
|
|
8
|
+
//! * rejects a block whose last line is no value (an `if` used as a value needs an `else`; the
|
|
14
|
-
//!
|
|
9
|
+
//! last line of every branch is a value, a nested `if` / `match`, or ends the path with
|
|
10
|
+
//! `return` / `crash` / `todo` / `break` / `continue`), and a block in a constant;
|
|
15
|
-
//!
|
|
11
|
+
//! * gives each name that a block declares and that is declared elsewhere in the same fn
|
|
12
|
+
//! (a sibling branch, or a later outer name) a fresh name. Locals are fn-wide and typed once in
|
|
13
|
+
//! the output, so two branches that each declare `t` (of different types) would otherwise
|
|
14
|
+
//! share one wasm local. A name that is already visible where the block sits is left alone:
|
|
15
|
+
//! declaring it again is the checker's "already declared" error, as it is for an `if` statement.
|
|
16
|
+
//!
|
|
17
|
+
//! `?` inside a block value is rejected by `question.rs`.
|
|
16
18
|
use crate::ast::*;
|
|
17
19
|
use crate::diag::{DiagKind, Diagnostic};
|
|
20
|
+
use crate::rename::{renameStmts, Name};
|
|
18
21
|
use crate::visit::*;
|
|
19
|
-
|
|
20
|
-
/// Prefix of the variables that carry a block's value (the checker hoists them out of branches).
|
|
21
|
-
pub const BLOCK_VAR_PREFIX: &str = "__blk";
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
use std::collections::HashMap;
|
|
24
23
|
|
|
25
24
|
struct Pass {
|
|
26
25
|
file: String,
|
|
27
|
-
fresh: usize,
|
|
28
26
|
errors: Vec<Diagnostic>,
|
|
29
27
|
}
|
|
30
28
|
|
|
29
|
+
impl Pass {
|
|
31
|
-
fn
|
|
30
|
+
fn error(&mut self, span: Span, msg: &str) {
|
|
32
|
-
|
|
31
|
+
self.errors.push(Diagnostic::new(DiagKind::Type, self.file.clone(), span.startLine, span.startColumn, msg));
|
|
33
|
-
}
|
|
32
|
+
}
|
|
34
33
|
|
|
34
|
+
/// The last line of every path through `stmts` is a value (or leaves the path).
|
|
35
|
-
fn
|
|
35
|
+
fn tail(&mut self, stmts: &[Stmt], at: Span) {
|
|
36
|
+
let Some(last) = stmts.last() else {
|
|
37
|
+
self.error(at, "a block used as a value needs a value on its last line");
|
|
38
|
+
return;
|
|
39
|
+
};
|
|
40
|
+
match &last.kind {
|
|
36
|
-
|
|
41
|
+
StmtKind::Expr(..) => {}
|
|
42
|
+
StmtKind::If(i) => {
|
|
43
|
+
if i.else_.is_none() {
|
|
44
|
+
self.error(last.span, "an 'if' used as a value needs an 'else'");
|
|
45
|
+
}
|
|
46
|
+
let bodies = std::iter::once(&i.body).chain(i.else_ifs.iter().map(|e| &e.body)).chain(i.else_.iter());
|
|
47
|
+
for b in bodies {
|
|
48
|
+
self.tail(&b.stmts, last.span);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
StmtKind::Match(m) => {
|
|
37
|
-
|
|
52
|
+
for c in &m.cases {
|
|
53
|
+
self.tail(&c.body.stmts, last.span);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo | StmtKind::Break | StmtKind::Continue => {}
|
|
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
|
+
}
|
|
38
59
|
}
|
|
39
|
-
childRefs(e).into_iter().find_map(firstBlock)
|
|
40
|
-
}
|
|
41
60
|
|
|
42
|
-
fn
|
|
61
|
+
fn validate(&mut self, e: &Expr) {
|
|
43
|
-
|
|
62
|
+
walkRef(e, &mut |x| {
|
|
44
|
-
ExprKind::Int(_)
|
|
45
|
-
| ExprKind::Float(_)
|
|
46
|
-
| ExprKind::BoolLit(_)
|
|
47
|
-
| ExprKind::Self_
|
|
48
|
-
| ExprKind::Var(_)
|
|
49
|
-
| ExprKind::TypeName(_)
|
|
50
|
-
|
|
63
|
+
if let ExprKind::Block(b) = &x.kind {
|
|
51
|
-
|
|
64
|
+
self.tail(&b.stmts, x.span);
|
|
65
|
+
}
|
|
52
|
-
|
|
66
|
+
});
|
|
53
67
|
}
|
|
54
|
-
}
|
|
55
68
|
|
|
56
|
-
fn
|
|
69
|
+
fn validateBlock(&mut self, b: &Block) {
|
|
70
|
+
walkBlockRef(b, &mut |x| {
|
|
57
|
-
|
|
71
|
+
if let ExprKind::Block(blk) = &x.kind {
|
|
72
|
+
self.tail(&blk.stmts, x.span);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
58
76
|
}
|
|
59
77
|
|
|
60
|
-
fn
|
|
78
|
+
fn firstBlock(e: &Expr) -> Option<Span> {
|
|
61
|
-
|
|
79
|
+
let mut found = None;
|
|
80
|
+
walkRef(e, &mut |x| {
|
|
81
|
+
if found.is_none() && matches!(x.kind, ExprKind::Block(_)) {
|
|
62
|
-
|
|
82
|
+
found = Some(x.span);
|
|
63
|
-
targets: vec![AssignTarget::Var(name)],
|
|
64
|
-
values: vec![value],
|
|
65
|
-
declare: true,
|
|
66
|
-
|
|
83
|
+
}
|
|
67
|
-
isSynthetic: false,
|
|
68
|
-
|
|
84
|
+
});
|
|
69
|
-
|
|
85
|
+
found
|
|
70
|
-
)
|
|
71
86
|
}
|
|
72
87
|
|
|
73
|
-
impl Pass {
|
|
74
|
-
|
|
88
|
+
// ---------- scoping ----------
|
|
75
|
-
self.errors.push(Diagnostic::new(DiagKind::Type, self.file.clone(), span.startLine, span.startColumn, msg));
|
|
76
|
-
}
|
|
77
89
|
|
|
90
|
+
/// Renames the declarations inside block values that clash with a declaration elsewhere in the fn.
|
|
91
|
+
struct Scoper<'a> {
|
|
92
|
+
/// How often each name is declared in the fn (parameters, locals, pattern names, loop
|
|
93
|
+
/// binders, closure parameters).
|
|
94
|
+
count: &'a HashMap<String, usize>,
|
|
95
|
+
fresh: &'a mut usize,
|
|
96
|
+
/// Innermost last: declared name -> the name now used for it.
|
|
97
|
+
scopes: Vec<HashMap<String, String>>,
|
|
98
|
+
/// How many block values enclose the code being walked.
|
|
99
|
+
depth: usize,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
impl Scoper<'_> {
|
|
78
|
-
fn
|
|
103
|
+
fn resolve(&self, n: &str) -> Option<&String> {
|
|
79
|
-
self.fresh += 1;
|
|
80
|
-
|
|
104
|
+
self.scopes.iter().rev().find_map(|s| s.get(n))
|
|
81
105
|
}
|
|
82
106
|
|
|
83
|
-
/// Lowers the closure bodies under `e` (not into blocks: those are lowered when lifted).
|
|
84
|
-
fn
|
|
107
|
+
fn rename(&self, n: &mut String) {
|
|
85
|
-
if let
|
|
108
|
+
if let Some(new) = self.resolve(n) {
|
|
86
|
-
|
|
109
|
+
if new != n {
|
|
87
|
-
|
|
110
|
+
*n = new.clone();
|
|
88
|
-
|
|
111
|
+
}
|
|
89
|
-
for c in childExprs(e) {
|
|
90
|
-
self.closures(c);
|
|
91
112
|
}
|
|
92
113
|
}
|
|
93
114
|
|
|
94
|
-
fn
|
|
115
|
+
fn declare(&mut self, n: &mut String) {
|
|
95
|
-
if
|
|
116
|
+
if n == "_" {
|
|
96
|
-
self.closures(e);
|
|
97
117
|
return;
|
|
98
118
|
}
|
|
99
|
-
if let ExprKind::Block(_) = &e.kind {
|
|
100
|
-
|
|
119
|
+
let old = n.clone();
|
|
101
|
-
|
|
120
|
+
let clash = self.depth > 0 && self.count.get(&old).copied().unwrap_or(0) > 1 && self.resolve(&old).is_none();
|
|
121
|
+
if clash {
|
|
122
|
+
*self.fresh += 1;
|
|
123
|
+
*n = format!("{}__v{}", old, *self.fresh);
|
|
124
|
+
}
|
|
102
|
-
|
|
125
|
+
if let Some(top) = self.scopes.last_mut() {
|
|
103
|
-
let name = self.freshName(&BLOCK_VAR_PREFIX[2..]);
|
|
104
|
-
pre.extend(self.leaves(inner.stmts, &name, span));
|
|
105
|
-
|
|
126
|
+
top.insert(old, n.clone());
|
|
106
|
-
return;
|
|
107
127
|
}
|
|
108
|
-
let condFrom = match &e.kind {
|
|
109
|
-
ExprKind::Bool(_) | ExprKind::InlineIf(_) | ExprKind::Bind(_) => 1,
|
|
110
|
-
_ => usize::MAX,
|
|
111
|
-
};
|
|
112
|
-
self.extractSeq(childExprs(e), condFrom, pre);
|
|
113
128
|
}
|
|
114
129
|
|
|
115
|
-
/// `items` are evaluated in order; those from `condFrom` on only conditionally.
|
|
116
|
-
fn
|
|
130
|
+
fn pattern(&mut self, p: &mut CasePattern) {
|
|
117
|
-
let mut last = None;
|
|
118
|
-
for (j, it) in items.iter().enumerate() {
|
|
119
|
-
if hasBlock(it) {
|
|
120
|
-
if j >= condFrom {
|
|
121
|
-
let span = firstBlock(it).unwrap_or(it.span);
|
|
122
|
-
self.error(span, format!("a block 'if' or 'match' in a conditionally evaluated expression is not allowed: {MOVE}"));
|
|
123
|
-
|
|
131
|
+
match p {
|
|
124
|
-
last = Some(j);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
let Some(last) = last else {
|
|
129
|
-
for it in items {
|
|
130
|
-
self.closures(it);
|
|
131
|
-
}
|
|
132
|
-
return;
|
|
133
|
-
};
|
|
134
|
-
|
|
132
|
+
CasePattern::Name(n) if !isTag(n) => self.declare(n),
|
|
133
|
+
CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|f| self.pattern(f)),
|
|
135
|
-
|
|
134
|
+
_ => {}
|
|
136
|
-
self.closures(it);
|
|
137
|
-
continue;
|
|
138
|
-
}
|
|
139
|
-
if j >= condFrom {
|
|
140
|
-
self.closures(it);
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
self.extract(it, pre);
|
|
144
|
-
if j < last && !isTrivial(it) {
|
|
145
|
-
let tmp = self.freshName("t");
|
|
146
|
-
let span = it.span;
|
|
147
|
-
let taken = std::mem::replace(it, Expr::Var(tmp.clone()));
|
|
148
|
-
it.span = span;
|
|
149
|
-
pre.push(declare(tmp, taken, span));
|
|
150
|
-
}
|
|
151
135
|
}
|
|
152
136
|
}
|
|
153
137
|
|
|
154
|
-
fn
|
|
138
|
+
fn scoped(&mut self, f: impl FnOnce(&mut Self)) {
|
|
155
|
-
|
|
139
|
+
self.scopes.push(HashMap::new());
|
|
156
|
-
|
|
140
|
+
f(self);
|
|
157
|
-
for blk in stmtBlocks(&mut s) {
|
|
158
|
-
let body = std::mem::replace(blk, Block { stmts: vec![] });
|
|
159
|
-
|
|
141
|
+
self.scopes.pop();
|
|
160
|
-
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
fn block(&mut self, b: &mut Block) {
|
|
161
|
-
|
|
145
|
+
self.scoped(|s| s.stmts(&mut b.stmts));
|
|
162
|
-
StmtKind::While(_) => 0,
|
|
163
|
-
StmtKind::If(_) => 1,
|
|
164
|
-
StmtKind::Match(m) => m.subjects.len(),
|
|
165
|
-
_ => usize::MAX,
|
|
166
|
-
|
|
146
|
+
}
|
|
167
|
-
|
|
147
|
+
|
|
168
|
-
|
|
148
|
+
fn stmts(&mut self, stmts: &mut [Stmt]) {
|
|
169
|
-
|
|
149
|
+
for st in stmts {
|
|
170
|
-
|
|
150
|
+
self.stmt(st);
|
|
171
151
|
}
|
|
172
|
-
Block { stmts: out }
|
|
173
152
|
}
|
|
174
153
|
|
|
175
|
-
/// `stmts` with the value of the last statement stored in `name`.
|
|
176
|
-
fn leaves(&mut self, mut stmts: Vec<Stmt>, name: &str, at: Span) -> Vec<Stmt> {
|
|
177
|
-
|
|
154
|
+
fn stmt(&mut self, st: &mut Stmt) {
|
|
178
|
-
self.error(at, "a block used as a value needs a value on its last line".to_string());
|
|
179
|
-
return stmts;
|
|
180
|
-
};
|
|
181
|
-
let Stmt { id, span, kind } = last;
|
|
182
|
-
|
|
155
|
+
match &mut st.kind {
|
|
183
|
-
StmtKind::Expr(e, ..) => StmtKind::Assign(Assign {
|
|
184
|
-
targets: vec![AssignTarget::Var(name.to_string())],
|
|
185
|
-
values: vec![e],
|
|
186
|
-
declare: false,
|
|
187
|
-
ty: None,
|
|
188
|
-
isSynthetic: true,
|
|
189
|
-
}),
|
|
190
|
-
StmtKind::
|
|
156
|
+
StmtKind::Assign(a) => {
|
|
157
|
+
for t in &mut a.targets {
|
|
191
|
-
|
|
158
|
+
if let AssignTarget::Field(o, _) = t {
|
|
192
|
-
|
|
159
|
+
self.expr(o);
|
|
160
|
+
}
|
|
193
161
|
}
|
|
194
|
-
for
|
|
162
|
+
for v in &mut a.values {
|
|
195
|
-
.chain(i.else_ifs.iter_mut().map(|e| &mut e.body))
|
|
196
|
-
.
|
|
163
|
+
self.expr(v);
|
|
197
|
-
{
|
|
198
|
-
let body = std::mem::take(&mut blk.stmts);
|
|
199
|
-
blk.stmts = self.leaves(body, name, span);
|
|
200
164
|
}
|
|
165
|
+
for t in &mut a.targets {
|
|
166
|
+
if let AssignTarget::Var(n) = t {
|
|
167
|
+
if a.declare {
|
|
168
|
+
self.declare(n);
|
|
169
|
+
} else {
|
|
170
|
+
self.rename(n);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
StmtKind::Assert(c) => self.expr(&mut c.cond),
|
|
176
|
+
StmtKind::Crash(e) | StmtKind::Expr(e, ..) => self.expr(e),
|
|
177
|
+
StmtKind::Return(e) => e.iter_mut().for_each(|e| self.expr(e)),
|
|
201
|
-
|
|
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
|
+
});
|
|
202
184
|
}
|
|
185
|
+
StmtKind::While(w) => self.scoped(|s| {
|
|
186
|
+
s.expr(&mut w.condition);
|
|
187
|
+
s.block(&mut w.body);
|
|
188
|
+
}),
|
|
189
|
+
StmtKind::If(i) => self.scoped(|s| {
|
|
190
|
+
s.expr(&mut i.condition);
|
|
191
|
+
s.block(&mut i.body);
|
|
192
|
+
for e in &mut i.else_ifs {
|
|
193
|
+
s.expr(&mut e.condition);
|
|
194
|
+
s.block(&mut e.body);
|
|
195
|
+
}
|
|
196
|
+
if let Some(b) = &mut i.else_ {
|
|
197
|
+
s.block(b);
|
|
198
|
+
}
|
|
199
|
+
}),
|
|
203
|
-
StmtKind::Match(
|
|
200
|
+
StmtKind::Match(m) => {
|
|
201
|
+
m.subjects.iter_mut().for_each(|e| self.expr(e));
|
|
204
202
|
for c in &mut m.cases {
|
|
203
|
+
self.scoped(|s| {
|
|
204
|
+
c.patterns.iter_mut().for_each(|p| s.pattern(p));
|
|
205
|
+
if let Some(g) = &mut c.guard {
|
|
206
|
+
s.expr(g);
|
|
207
|
+
}
|
|
205
|
-
|
|
208
|
+
s.block(&mut c.body);
|
|
206
|
-
|
|
209
|
+
});
|
|
207
210
|
}
|
|
208
|
-
StmtKind::Match(m)
|
|
209
211
|
}
|
|
210
|
-
|
|
212
|
+
StmtKind::Break | StmtKind::Continue | StmtKind::Todo => {}
|
|
211
|
-
other => {
|
|
212
|
-
self.error(span, "the last line of a block used as a value must be a value, an 'if' or a 'match'".to_string());
|
|
213
|
-
other
|
|
214
|
-
|
|
213
|
+
}
|
|
215
|
-
};
|
|
216
|
-
stmts.push(Stmt { id, span, kind });
|
|
217
|
-
stmts
|
|
218
214
|
}
|
|
219
|
-
}
|
|
220
215
|
|
|
216
|
+
fn expr(&mut self, e: &mut Expr) {
|
|
217
|
+
match &mut e.kind {
|
|
218
|
+
ExprKind::Var(n) => self.rename(n),
|
|
219
|
+
ExprKind::Closure(c) => {
|
|
220
|
+
self.scoped(|s| {
|
|
221
|
+
c.params.iter_mut().for_each(|p| s.declare(p));
|
|
222
|
+
s.block(&mut c.body);
|
|
223
|
+
});
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
ExprKind::Block(b) => {
|
|
227
|
+
self.depth += 1;
|
|
228
|
+
self.block(b);
|
|
229
|
+
self.depth -= 1;
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
ExprKind::FnCall(c) => self.rename(&mut c.name),
|
|
233
|
+
ExprKind::Bind(b) => {
|
|
234
|
+
self.expr(&mut b.value);
|
|
235
|
+
for p in &mut b.case.patterns {
|
|
236
|
+
self.pattern(p);
|
|
237
|
+
}
|
|
221
|
-
|
|
238
|
+
if let Some(g) = &mut b.case.guard {
|
|
239
|
+
self.expr(g);
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
_ => {}
|
|
244
|
+
}
|
|
222
|
-
|
|
245
|
+
for c in childExprs(e) {
|
|
246
|
+
self.expr(c);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
223
249
|
}
|
|
224
250
|
|
|
251
|
+
/// How often `body` (with these parameters) declares each name.
|
|
252
|
+
fn declCounts(params: &[Param], body: &Block) -> HashMap<String, usize> {
|
|
253
|
+
let mut count: HashMap<String, usize> = HashMap::new();
|
|
254
|
+
for p in params {
|
|
255
|
+
*count.entry(p.name.clone()).or_default() += 1;
|
|
256
|
+
}
|
|
225
|
-
|
|
257
|
+
let mut note = |n: &mut String, kind: Name| {
|
|
226
|
-
|
|
258
|
+
if matches!(kind, Name::Decl) || (matches!(kind, Name::Pat) && !isTag(n)) {
|
|
259
|
+
*count.entry(n.clone()).or_default() += 1;
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
renameStmts(&mut body.stmts.clone(), &mut note);
|
|
263
|
+
count
|
|
227
264
|
}
|
|
228
265
|
|
|
229
|
-
/// Does some closure body under `e` hold a block value?
|
|
230
|
-
fn
|
|
266
|
+
fn hasBlockValue(b: &Block) -> bool {
|
|
231
267
|
let mut any = false;
|
|
232
|
-
|
|
268
|
+
walkBlockRef(b, &mut |x| any |= matches!(x.kind, ExprKind::Block(_)));
|
|
233
|
-
if let ExprKind::Closure(c) = &x.kind {
|
|
234
|
-
any |= blockHasBlock(&c.body);
|
|
235
|
-
}
|
|
236
|
-
});
|
|
237
269
|
any
|
|
238
270
|
}
|
|
239
271
|
|
|
272
|
+
/// Gives the clashing names of a fn's block values fresh names.
|
|
240
|
-
fn
|
|
273
|
+
fn scopeBody(params: &[Param], body: &mut Block, fresh: &mut usize) {
|
|
241
|
-
let mut any = false;
|
|
242
|
-
walkBlockRef(b, &mut |x| {
|
|
243
|
-
if let ExprKind::Closure(c) = &x.kind {
|
|
244
|
-
|
|
274
|
+
if !hasBlockValue(body) {
|
|
275
|
+
return;
|
|
245
|
-
|
|
276
|
+
}
|
|
277
|
+
let count = declCounts(params, body);
|
|
278
|
+
if count.values().all(|&n| n <= 1) {
|
|
279
|
+
return;
|
|
246
|
-
}
|
|
280
|
+
}
|
|
281
|
+
let mut base: HashMap<String, String> = HashMap::new();
|
|
282
|
+
for p in params {
|
|
283
|
+
base.insert(p.name.clone(), p.name.clone());
|
|
247
|
-
|
|
284
|
+
}
|
|
285
|
+
let mut sc = Scoper { count: &count, fresh, scopes: vec![base], depth: 0 };
|
|
286
|
+
sc.scoped(|s| s.stmts(&mut body.stmts));
|
|
248
287
|
}
|
|
249
288
|
|
|
250
|
-
///
|
|
289
|
+
/// Checks every block value of the program and scopes the names it declares. Returns the errors;
|
|
290
|
+
/// a fn with an error is left as written.
|
|
251
|
-
pub fn
|
|
291
|
+
pub fn prepareBlockValues(source: &mut Source) -> Vec<Diagnostic> {
|
|
252
292
|
let mut errors = Vec::new();
|
|
253
293
|
let mut fresh = 0;
|
|
254
294
|
let file = source.file.clone();
|
|
255
295
|
for item in source.items.iter_mut() {
|
|
256
296
|
match item {
|
|
257
297
|
Item::Fn(f) => {
|
|
298
|
+
let mut pass = Pass { file: f.file.clone(), errors: vec![] };
|
|
258
|
-
|
|
299
|
+
match &mut f.body {
|
|
259
|
-
FnBody::Block(b) =>
|
|
300
|
+
FnBody::Block(b) => pass.validateBlock(b),
|
|
260
|
-
FnBody::Expr(e) =>
|
|
301
|
+
FnBody::Expr(e) => pass.validate(e),
|
|
261
|
-
FnBody::Extern =>
|
|
302
|
+
FnBody::Extern => continue,
|
|
262
|
-
}
|
|
303
|
+
}
|
|
263
|
-
if !
|
|
304
|
+
if !pass.errors.is_empty() {
|
|
305
|
+
errors.append(&mut pass.errors);
|
|
264
306
|
continue;
|
|
265
307
|
}
|
|
266
|
-
let
|
|
308
|
+
let params = f.params.clone();
|
|
267
|
-
|
|
309
|
+
match &mut f.body {
|
|
268
|
-
FnBody::Block(b) =>
|
|
310
|
+
FnBody::Block(b) => scopeBody(¶ms, b, &mut fresh),
|
|
269
311
|
FnBody::Expr(e) => {
|
|
270
312
|
let span = e.span;
|
|
271
313
|
let (line, column) = (span.startLine, span.startColumn);
|
|
272
|
-
let
|
|
314
|
+
let expr = std::mem::replace(e, Expr::Self_);
|
|
273
|
-
Block { stmts: vec![
|
|
315
|
+
let mut blk = Block { stmts: vec![Stmt { id: NodeId(0), span, kind: StmtKind::Expr(expr, line, column) }] };
|
|
316
|
+
scopeBody(¶ms, &mut blk, &mut fresh);
|
|
317
|
+
let Some(Stmt { kind: StmtKind::Expr(back, ..), .. }) = blk.stmts.pop() else { unreachable!() };
|
|
318
|
+
*e = back;
|
|
274
319
|
}
|
|
275
|
-
FnBody::Extern =>
|
|
320
|
+
FnBody::Extern => {}
|
|
276
|
-
};
|
|
277
|
-
let saved = block.clone();
|
|
278
|
-
let out = pass.lowerBlock(block);
|
|
279
|
-
fresh = pass.fresh;
|
|
280
|
-
if pass.errors.is_empty() {
|
|
281
|
-
f.body = FnBody::Block(out);
|
|
282
|
-
} else {
|
|
283
|
-
errors.append(&mut pass.errors);
|
|
284
|
-
f.body = FnBody::Block(saved);
|
|
285
321
|
}
|
|
286
322
|
}
|
|
287
323
|
Item::Test(t) => {
|
|
288
|
-
if blockHasBlock(&t.body) || blockClosureHasBlock(&t.body) {
|
|
289
|
-
|
|
324
|
+
let mut pass = Pass { file: t.file.clone(), errors: vec![] };
|
|
290
|
-
let body = std::mem::replace(&mut t.body, Block { stmts: vec![] });
|
|
291
|
-
let saved = body.clone();
|
|
292
|
-
|
|
325
|
+
pass.validateBlock(&t.body);
|
|
293
|
-
fresh = pass.fresh;
|
|
294
|
-
|
|
326
|
+
if pass.errors.is_empty() {
|
|
295
|
-
|
|
327
|
+
scopeBody(&[], &mut t.body, &mut fresh);
|
|
296
|
-
|
|
328
|
+
} else {
|
|
297
|
-
|
|
329
|
+
errors.append(&mut pass.errors);
|
|
298
|
-
t.body = saved;
|
|
299
|
-
}
|
|
300
330
|
}
|
|
301
331
|
}
|
|
302
332
|
Item::Const(c) => {
|
compiler/core/src/closure_spec.rs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
use crate::ast::*;
|
|
13
13
|
use crate::closure_escape::nonEscapingFnParams;
|
|
14
14
|
use crate::rename::{renameStmts, Name};
|
|
15
|
-
use crate::visit::{
|
|
15
|
+
use crate::visit::{countVar, innerBlockRefs, innerBlocks, stmtBlocks, stmtExprRefs, stmtExprs, visitBlock, visitExpr, walkBlockRef, walkRef};
|
|
16
16
|
use std::collections::{HashMap, HashSet};
|
|
17
17
|
|
|
18
18
|
pub const MAX_COPIES: usize = 8;
|
|
@@ -847,6 +847,9 @@ fn zeroBlock(b: &mut Block) {
|
|
|
847
847
|
for blk in stmtBlocks(s) {
|
|
848
848
|
zeroBlock(blk);
|
|
849
849
|
}
|
|
850
|
+
for e in stmtExprs(s) {
|
|
851
|
+
innerBlocks(e, &mut |b| zeroBlock(b));
|
|
852
|
+
}
|
|
850
853
|
}
|
|
851
854
|
}
|
|
852
855
|
|
|
@@ -878,11 +881,17 @@ fn usesOf(e: &Expr, name: &str) -> (usize, usize) {
|
|
|
878
881
|
});
|
|
879
882
|
}
|
|
880
883
|
match &mut x.kind {
|
|
884
|
+
// The branches of a block value are conditional, and a loop in it repeats.
|
|
881
885
|
ExprKind::Closure(c) => visitBlock(&mut c.body, &mut |y| {
|
|
882
886
|
if matches!(&mut y.kind, ExprKind::Var(n) if n == name) {
|
|
883
887
|
lazy += 1;
|
|
884
888
|
}
|
|
885
889
|
}),
|
|
890
|
+
ExprKind::Block(b) => visitBlock(b, &mut |y| {
|
|
891
|
+
if matches!(&mut y.kind, ExprKind::Var(n) if n == name) {
|
|
892
|
+
lazy += 1;
|
|
893
|
+
}
|
|
894
|
+
}),
|
|
886
895
|
_ => {}
|
|
887
896
|
}
|
|
888
897
|
});
|
|
@@ -910,6 +919,13 @@ fn anyReturn(stmts: &[Stmt]) -> bool {
|
|
|
910
919
|
}
|
|
911
920
|
StmtKind::Match(m) => m.cases.iter().any(|c| anyReturn(&c.body.stmts)),
|
|
912
921
|
_ => false,
|
|
922
|
+
}) || stmts.iter().any(|s| {
|
|
923
|
+
// a `return` inside a block `if` / `match` value
|
|
924
|
+
let mut any = false;
|
|
925
|
+
for e in stmtExprRefs(s) {
|
|
926
|
+
innerBlockRefs(e, &mut |b| any |= anyReturn(&b.stmts));
|
|
927
|
+
}
|
|
928
|
+
any
|
|
913
929
|
})
|
|
914
930
|
}
|
|
915
931
|
|
|
@@ -967,6 +983,9 @@ fn annotations(stmts: &[Stmt], out: &mut HashSet<String>) {
|
|
|
967
983
|
StmtKind::Match(m) => m.cases.iter().for_each(|c| annotations(&c.body.stmts, out)),
|
|
968
984
|
_ => {}
|
|
969
985
|
}
|
|
986
|
+
for e in stmtExprRefs(s) {
|
|
987
|
+
innerBlockRefs(e, &mut |b| annotations(&b.stmts, out));
|
|
988
|
+
}
|
|
970
989
|
}
|
|
971
990
|
}
|
|
972
991
|
|
compiler/core/src/drive.rs
CHANGED
|
@@ -12,7 +12,7 @@ use crate::ast::*;
|
|
|
12
12
|
use crate::generics::Scope;
|
|
13
13
|
use crate::rename::{renameStmts, substPT, substStmts, substType, Name};
|
|
14
14
|
use crate::simplify::{boundNames, calledNames, mentions, pinExpr, simplifyBlock, simplifyBlockIn};
|
|
15
|
-
use crate::visit::{argRef, isTag, walkBlockRef, walkRef};
|
|
15
|
+
use crate::visit::{argRef, innerBlockRefs, isTag, walkBlockRef, walkRef};
|
|
16
16
|
use crate::visit::{childRefs, stmtBlockRefs, stmtBlocks, stmtExprRefs, visitBlock, visitExpr};
|
|
17
17
|
use crate::whistle::embeds;
|
|
18
18
|
use std::collections::{HashMap, HashSet};
|
|
@@ -226,11 +226,11 @@ fn cnt(e: &Expr, name: &str, into: bool) -> usize {
|
|
|
226
226
|
for c in childRefs(e) {
|
|
227
227
|
n += cnt(c, name, into);
|
|
228
228
|
}
|
|
229
|
-
if into {
|
|
230
|
-
|
|
229
|
+
match &e.kind {
|
|
231
|
-
|
|
230
|
+
ExprKind::Closure(c) if into => n += cntStmts(&c.body.stmts, name, into),
|
|
231
|
+
// A block value runs inline: its statements are the fn's own.
|
|
232
|
+
ExprKind::Block(b) => n += cntStmts(&b.stmts, name, into),
|
|
232
|
-
|
|
233
|
+
_ => {}
|
|
233
|
-
}
|
|
234
234
|
}
|
|
235
235
|
n
|
|
236
236
|
}
|
|
@@ -255,6 +255,7 @@ fn pathE(e: &Expr, name: &str) -> usize {
|
|
|
255
255
|
ExprKind::Var(v) => usize::from(v == name),
|
|
256
256
|
ExprKind::InlineIf(i) => pathE(&i.condition, name) + pathE(&i.then, name).max(pathE(&i.else_, name)),
|
|
257
257
|
ExprKind::Closure(_) => 2 * cnt(e, name, true),
|
|
258
|
+
ExprKind::Block(b) => pathStmts(&b.stmts, name),
|
|
258
259
|
_ => childRefs(e).into_iter().map(|c| pathE(c, name)).sum(),
|
|
259
260
|
}
|
|
260
261
|
}
|
|
@@ -291,11 +292,35 @@ fn cheap(e: &Expr) -> bool {
|
|
|
291
292
|
}
|
|
292
293
|
}
|
|
293
294
|
|
|
295
|
+
/// No early `return`, loop or reassignment in `stmts`, block values inside them included.
|
|
296
|
+
fn clean(stmts: &[Stmt]) -> bool {
|
|
297
|
+
stmts.iter().all(|s| {
|
|
298
|
+
let ok = match &s.kind {
|
|
299
|
+
StmtKind::Return(_) | StmtKind::While(_) | StmtKind::ForLoop(_) => false,
|
|
300
|
+
StmtKind::Assign(a) => a.declare,
|
|
301
|
+
_ => true,
|
|
302
|
+
};
|
|
303
|
+
ok && stmtBlockRefs(s).into_iter().all(|b| clean(&b.stmts))
|
|
304
|
+
&& stmtExprRefs(s).into_iter().all(|e| {
|
|
305
|
+
let mut c = true;
|
|
306
|
+
innerBlockRefs(e, &mut |b| c &= clean(&b.stmts));
|
|
307
|
+
c
|
|
308
|
+
})
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
|
|
294
312
|
/// Is `name` read inside a loop in `stmts`?
|
|
295
313
|
fn inLoop(stmts: &[Stmt], name: &str) -> bool {
|
|
296
314
|
stmts.iter().any(|s| match &s.kind {
|
|
297
315
|
StmtKind::ForLoop(_) | StmtKind::While(_) => cntStmts(std::slice::from_ref(s), name, true) > 0,
|
|
316
|
+
_ => {
|
|
298
|
-
|
|
317
|
+
stmtBlockRefs(s).into_iter().any(|b| inLoop(&b.stmts, name))
|
|
318
|
+
|| stmtExprRefs(s).into_iter().any(|e| {
|
|
319
|
+
let mut hit = false;
|
|
320
|
+
innerBlockRefs(e, &mut |b| hit |= inLoop(&b.stmts, name));
|
|
321
|
+
hit
|
|
322
|
+
})
|
|
323
|
+
}
|
|
299
324
|
})
|
|
300
325
|
}
|
|
301
326
|
|
|
@@ -806,7 +831,11 @@ impl Driver {
|
|
|
806
831
|
}
|
|
807
832
|
// the parser gives `= match ..` a one-statement block, the same as `=\n match ..`
|
|
808
833
|
let b = match &f.body {
|
|
809
|
-
FnBody::Expr(
|
|
834
|
+
FnBody::Expr(e) => {
|
|
835
|
+
let mut ok = true;
|
|
836
|
+
innerBlockRefs(e, &mut |b| ok &= clean(&b.stmts));
|
|
837
|
+
return if ok { Ok(()) } else { Err("early return/loop/assignment") };
|
|
838
|
+
}
|
|
810
839
|
FnBody::Block(b) => b,
|
|
811
840
|
FnBody::Extern => return Err("extern"),
|
|
812
841
|
};
|
|
@@ -817,17 +846,6 @@ impl Driver {
|
|
|
817
846
|
if !matches!(&last.kind, StmtKind::Match(_) | StmtKind::Expr(..) | StmtKind::If(_)) {
|
|
818
847
|
return Err("early return/loop/assignment");
|
|
819
848
|
}
|
|
820
|
-
fn clean(stmts: &[Stmt]) -> bool {
|
|
821
|
-
stmts.iter().all(|s| {
|
|
822
|
-
let ok = match &s.kind {
|
|
823
|
-
StmtKind::Return(_) | StmtKind::While(_) | StmtKind::ForLoop(_) => false,
|
|
824
|
-
StmtKind::Assign(a) => a.declare,
|
|
825
|
-
_ => true,
|
|
826
|
-
};
|
|
827
|
-
let mut s = s.clone();
|
|
828
|
-
ok && stmtBlocks(&mut s).into_iter().all(|b| clean(&b.stmts))
|
|
829
|
-
})
|
|
830
|
-
}
|
|
831
849
|
if clean(&b.stmts) { Ok(()) } else { Err("early return/loop/assignment") }
|
|
832
850
|
}
|
|
833
851
|
|
|
@@ -867,7 +885,8 @@ impl Driver {
|
|
|
867
885
|
fn argPure(&self, e: &Expr) -> bool {
|
|
868
886
|
match &e.kind {
|
|
869
887
|
ExprKind::Closure(_) => return true,
|
|
888
|
+
// Statements run in a block value: never moved, duplicated or dropped.
|
|
870
|
-
ExprKind::Bang(_) | ExprKind::Bind(_) => return false,
|
|
889
|
+
ExprKind::Bang(_) | ExprKind::Bind(_) | ExprKind::Block(_) => return false,
|
|
871
890
|
ExprKind::FnCall(c) => {
|
|
872
891
|
let ok = !self.bound.contains(&c.name)
|
|
873
892
|
&& (self.pure.contains(&c.name) || self.ctors.contains(&c.name) || CASTS.contains(&c.name.as_str()));
|
|
@@ -2098,7 +2117,14 @@ impl Driver {
|
|
|
2098
2117
|
match &s.kind {
|
|
2099
2118
|
StmtKind::Assign(a) if a.targets.iter().any(|t| matches!(t, AssignTarget::Field(..))) => false,
|
|
2100
2119
|
StmtKind::Todo => false,
|
|
2120
|
+
_ => {
|
|
2101
|
-
|
|
2121
|
+
stmtBlockRefs(s).into_iter().all(|b| b.stmts.iter().all(|s| self.quietStmt(s)))
|
|
2122
|
+
&& stmtExprRefs(s).into_iter().all(|e| {
|
|
2123
|
+
let mut quiet = true;
|
|
2124
|
+
innerBlockRefs(e, &mut |b| quiet &= b.stmts.iter().all(|s| self.quietStmt(s)));
|
|
2125
|
+
quiet
|
|
2126
|
+
})
|
|
2127
|
+
}
|
|
2102
2128
|
}
|
|
2103
2129
|
}
|
|
2104
2130
|
}
|
compiler/core/src/forms.rs
CHANGED
|
@@ -22,7 +22,7 @@ use std::rc::Rc;
|
|
|
22
22
|
|
|
23
23
|
use crate::ast::*;
|
|
24
24
|
use crate::rename;
|
|
25
|
-
use crate::visit::{childExprs, patternBinders, stmtBlocks, stmtExprs};
|
|
25
|
+
use crate::visit::{childExprs, innerBlocks, patternBinders, stmtBlocks, stmtExprs};
|
|
26
26
|
|
|
27
27
|
/// What the checker knows about the type of an expression.
|
|
28
28
|
pub struct TyInfo {
|
|
@@ -214,6 +214,13 @@ pub fn finish(source: &Source) -> Source {
|
|
|
214
214
|
body: FnBody::Block(b),
|
|
215
215
|
..
|
|
216
216
|
}) => uniquePatternBinders(&mut b.stmts, &mut HashSet::new(), &mut uniq),
|
|
217
|
+
Item::Fn(Fn {
|
|
218
|
+
body: FnBody::Expr(e),
|
|
219
|
+
..
|
|
220
|
+
}) => {
|
|
221
|
+
let mut seen = HashSet::new();
|
|
222
|
+
innerBlocks(e, &mut |b| uniquePatternBinders(&mut b.stmts, &mut seen, &mut uniq));
|
|
223
|
+
}
|
|
217
224
|
Item::Test(t) => {
|
|
218
225
|
uniquePatternBinders(&mut t.body.stmts, &mut HashSet::new(), &mut uniq)
|
|
219
226
|
}
|
|
@@ -250,8 +257,10 @@ fn applyStmts(stmts: &mut Vec<Stmt>) {
|
|
|
250
257
|
}
|
|
251
258
|
|
|
252
259
|
fn applyExpr(e: &mut Expr) {
|
|
253
|
-
|
|
260
|
+
match &mut e.kind {
|
|
254
|
-
applyStmts(&mut c.body.stmts)
|
|
261
|
+
ExprKind::Closure(c) => applyStmts(&mut c.body.stmts),
|
|
262
|
+
ExprKind::Block(b) => applyStmts(&mut b.stmts),
|
|
263
|
+
_ => {}
|
|
255
264
|
}
|
|
256
265
|
for ch in childExprs(e) {
|
|
257
266
|
applyExpr(ch);
|
|
@@ -368,8 +377,10 @@ fn walkDeep(stmts: &mut [Stmt], fs: &mut dyn FnMut(&mut Stmt), fe: &mut dyn FnMu
|
|
|
368
377
|
|
|
369
378
|
fn walkDeepExpr(e: &mut Expr, fs: &mut dyn FnMut(&mut Stmt), fe: &mut dyn FnMut(&mut Expr)) {
|
|
370
379
|
fe(e);
|
|
371
|
-
|
|
380
|
+
match &mut e.kind {
|
|
372
|
-
walkDeep(&mut c.body.stmts, fs, fe)
|
|
381
|
+
ExprKind::Closure(c) => walkDeep(&mut c.body.stmts, fs, fe),
|
|
382
|
+
ExprKind::Block(b) => walkDeep(&mut b.stmts, fs, fe),
|
|
383
|
+
_ => {}
|
|
373
384
|
}
|
|
374
385
|
for ch in childExprs(e) {
|
|
375
386
|
walkDeepExpr(ch, fs, fe);
|
|
@@ -390,6 +401,7 @@ pub fn mapExprsIn(e: &mut Expr, fe: &mut dyn FnMut(&mut Expr)) {
|
|
|
390
401
|
fe(e);
|
|
391
402
|
match &mut e.kind {
|
|
392
403
|
ExprKind::Closure(c) => mapStmts(&mut c.body.stmts, fe),
|
|
404
|
+
ExprKind::Block(b) => mapStmts(&mut b.stmts, fe),
|
|
393
405
|
_ => {}
|
|
394
406
|
}
|
|
395
407
|
for ch in childExprs(e) {
|
|
@@ -470,6 +482,9 @@ fn uniquePatternBinders(stmts: &mut [Stmt], seen: &mut HashSet<String>, counter:
|
|
|
470
482
|
for blk in stmtBlocks(s) {
|
|
471
483
|
uniquePatternBinders(&mut blk.stmts, seen, counter);
|
|
472
484
|
}
|
|
485
|
+
for e in stmtExprs(s) {
|
|
486
|
+
innerBlocks(e, &mut |b| uniquePatternBinders(&mut b.stmts, seen, counter));
|
|
487
|
+
}
|
|
473
488
|
}
|
|
474
489
|
}
|
|
475
490
|
|
|
@@ -564,8 +579,10 @@ fn uniqueConditionBindersExpr(e: &mut Expr, counter: &mut usize) {
|
|
|
564
579
|
renameExpr(&mut t.then, &mut renameMap(&map));
|
|
565
580
|
}
|
|
566
581
|
}
|
|
567
|
-
|
|
582
|
+
match &mut e.kind {
|
|
568
|
-
uniqueConditionBinders(&mut c.body.stmts, counter)
|
|
583
|
+
ExprKind::Closure(c) => uniqueConditionBinders(&mut c.body.stmts, counter),
|
|
584
|
+
ExprKind::Block(b) => uniqueConditionBinders(&mut b.stmts, counter),
|
|
585
|
+
_ => {}
|
|
569
586
|
}
|
|
570
587
|
for ch in childExprs(e) {
|
|
571
588
|
uniqueConditionBindersExpr(ch, counter);
|
compiler/core/src/lower.rs
CHANGED
|
@@ -29,7 +29,7 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
|
29
29
|
if !pathErrors.is_empty() {
|
|
30
30
|
return Err(pathErrors);
|
|
31
31
|
}
|
|
32
|
-
let blockErrors = crate::blocks::
|
|
32
|
+
let blockErrors = crate::blocks::prepareBlockValues(source);
|
|
33
33
|
if !blockErrors.is_empty() {
|
|
34
34
|
return Err(blockErrors);
|
|
35
35
|
}
|
compiler/core/src/modules.rs
CHANGED
|
@@ -289,6 +289,12 @@ impl Cx<'_> {
|
|
|
289
289
|
self.scopes.pop();
|
|
290
290
|
return;
|
|
291
291
|
}
|
|
292
|
+
if let ExprKind::Block(b) = &mut e.kind {
|
|
293
|
+
self.scopes.push(HashSet::new());
|
|
294
|
+
self.block(b);
|
|
295
|
+
self.scopes.pop();
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
292
298
|
for c in childExprs(e) {
|
|
293
299
|
self.expr(c);
|
|
294
300
|
}
|
compiler/core/src/question.rs
CHANGED
|
@@ -14,6 +14,9 @@
|
|
|
14
14
|
//! * Rejected: `?` in a closure, in a conditionally evaluated expression (`&&` / `||` right
|
|
15
15
|
//! side, an inline `if` branch, an `else if` condition, a `when` guard, a loop condition), and
|
|
16
16
|
//! in a fn or test that does not return an Option or a Result.
|
|
17
|
+
//! * Rejected: `?` anywhere in a block `if` / `match` used as a value (`v := if a ...`): the
|
|
18
|
+
//! failure arm would be a hidden `return` in the middle of an expression. Move the `?` into a
|
|
19
|
+
//! function, or use `match`.
|
|
17
20
|
//! * Inside a loop body or a non-tail `if` / `match` branch the failure arm is
|
|
18
21
|
//! `return Err(error: q)` instead of a value (the rest of the body stays in the success arm, so
|
|
19
22
|
//! the code after the match runs as before). std uses `?` there next to `return` today. This
|
|
@@ -55,7 +58,11 @@ pub const UNUSED_PREFIX: &str = "__unused_";
|
|
|
55
58
|
const MOVE: &str = "move it into a function";
|
|
56
59
|
|
|
57
60
|
fn hasQ(e: &Expr) -> bool {
|
|
61
|
+
match &e.kind {
|
|
62
|
+
ExprKind::Question(_) => true,
|
|
63
|
+
ExprKind::Block(b) => blockHasQ(b),
|
|
58
|
-
|
|
64
|
+
_ => childRefs(e).into_iter().any(hasQ),
|
|
65
|
+
}
|
|
59
66
|
}
|
|
60
67
|
|
|
61
68
|
fn blockHasQ(b: &Block) -> bool {
|
|
@@ -123,6 +130,13 @@ impl Pass {
|
|
|
123
130
|
if !hasQ(e) {
|
|
124
131
|
return;
|
|
125
132
|
}
|
|
133
|
+
// A block `if` / `match` value runs inline in the middle of the expression: a failure arm
|
|
134
|
+
// that returns from the fn would be a hidden `return` there. Not rewritten.
|
|
135
|
+
if let ExprKind::Block(b) = &e.kind {
|
|
136
|
+
let span = firstQBlock(b).unwrap_or(e.span);
|
|
137
|
+
self.error(span, format!("'?' in a block 'if' or 'match' used as a value is not allowed: {MOVE}, or use 'match'"));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
126
140
|
if matches!(e.kind, ExprKind::Question(_)) {
|
|
127
141
|
let span = e.span;
|
|
128
142
|
let ExprKind::Question(mut inner) = std::mem::replace(&mut e.kind, ExprKind::Self_) else { unreachable!() };
|
|
@@ -436,6 +450,9 @@ fn topQs(e: &Expr, out: &mut Vec<Span>) {
|
|
|
436
450
|
if matches!(e.kind, ExprKind::Question(_)) {
|
|
437
451
|
out.push(e.span);
|
|
438
452
|
}
|
|
453
|
+
if let ExprKind::Block(b) = &e.kind {
|
|
454
|
+
walkBlockRefTop(b, out);
|
|
455
|
+
}
|
|
439
456
|
for c in childRefs(e) {
|
|
440
457
|
topQs(c, out);
|
|
441
458
|
}
|
compiler/core/src/rename.rs
CHANGED
|
@@ -72,6 +72,7 @@ fn renameExpr(e: &mut Expr, rn: &mut dyn FnMut(&mut String, Name)) {
|
|
|
72
72
|
c.params.iter_mut().for_each(|p| rn(p, Name::Decl));
|
|
73
73
|
renameStmts(&mut c.body.stmts, rn);
|
|
74
74
|
}
|
|
75
|
+
ExprKind::Block(b) => renameStmts(&mut b.stmts, rn),
|
|
75
76
|
_ => {}
|
|
76
77
|
}
|
|
77
78
|
for ch in childExprs(e) {
|
|
@@ -125,6 +126,7 @@ fn substExpr(e: &mut Expr, m: &HashMap<String, Type>) {
|
|
|
125
126
|
}
|
|
126
127
|
substStmts(&mut c.body.stmts, m);
|
|
127
128
|
}
|
|
129
|
+
ExprKind::Block(b) => substStmts(&mut b.stmts, m),
|
|
128
130
|
ExprKind::ClassCall(c) => {
|
|
129
131
|
for t in &mut c.generics {
|
|
130
132
|
*t = substType(t, m);
|
compiler/core/src/simplify.rs
CHANGED
|
@@ -215,12 +215,20 @@ fn usesOf(e: &Expr, name: &str, lazy: bool, acc: &mut (usize, usize)) {
|
|
|
215
215
|
usesOf(&t.then, name, true, acc);
|
|
216
216
|
usesOf(&t.else_, name, true, acc);
|
|
217
217
|
}
|
|
218
|
+
// The branches of a block value are conditional, and a loop in it repeats: every use in
|
|
219
|
+
// it counts as a lazy one.
|
|
218
220
|
ExprKind::Closure(c) => walkBlockRef(&c.body, &mut |x| {
|
|
219
221
|
if matches!(&x.kind, ExprKind::Var(n) if n == name) {
|
|
220
222
|
acc.0 += 1;
|
|
221
223
|
acc.1 += 1;
|
|
222
224
|
}
|
|
223
225
|
}),
|
|
226
|
+
ExprKind::Block(b) => walkBlockRef(b, &mut |x| {
|
|
227
|
+
if matches!(&x.kind, ExprKind::Var(n) if n == name) {
|
|
228
|
+
acc.0 += 1;
|
|
229
|
+
acc.1 += 1;
|
|
230
|
+
}
|
|
231
|
+
}),
|
|
224
232
|
_ => {
|
|
225
233
|
for c in childRefs(e) {
|
|
226
234
|
usesOf(c, name, lazy, acc);
|
|
@@ -278,7 +286,8 @@ impl<'a> Cx<'a> {
|
|
|
278
286
|
ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::BoolLit(_) | ExprKind::Var(_) | ExprKind::TypeName(_)
|
|
279
287
|
| ExprKind::Self_ | ExprKind::Closure(_) => true,
|
|
280
288
|
ExprKind::Binary(b) => !matches!(b.op, BinOp::Div | BinOp::Mod) && self.isPure(&b.left) && self.isPure(&b.right),
|
|
289
|
+
// Statements run in it: not known to be pure, and never moved or dropped.
|
|
281
|
-
ExprKind::Question(_) | ExprKind::Bang(_) | ExprKind::Bind(_) => false,
|
|
290
|
+
ExprKind::Question(_) | ExprKind::Bang(_) | ExprKind::Bind(_) | ExprKind::Block(_) => false,
|
|
282
291
|
ExprKind::FnCall(c) => !self.bound.contains(&c.name) && self.pure.contains(&c.name) && c.args.iter().all(|a| self.isPure(argRef(a))),
|
|
283
292
|
ExprKind::Attribute(a) => match &a.attr {
|
|
284
293
|
AttrKind::Field(_) => self.isPure(&a.object),
|
|
@@ -338,6 +347,11 @@ impl<'a> Cx<'a> {
|
|
|
338
347
|
let b = std::mem::replace(&mut c.body, Block { stmts: vec![] });
|
|
339
348
|
c.body = self.simBlock(b);
|
|
340
349
|
}
|
|
350
|
+
// A block value is simplified like any block; its last statement stays its value.
|
|
351
|
+
ExprKind::Block(blk) => {
|
|
352
|
+
let b = std::mem::replace(&mut **blk, Block { stmts: vec![] });
|
|
353
|
+
**blk = self.simBlock(b);
|
|
354
|
+
}
|
|
341
355
|
_ => {}
|
|
342
356
|
}
|
|
343
357
|
}
|
|
@@ -362,7 +376,12 @@ impl<'a> Cx<'a> {
|
|
|
362
376
|
}
|
|
363
377
|
let f = self.fns[&c.name].clone();
|
|
364
378
|
match self.instantiate(&f, &c.args, lets.is_some()) {
|
|
379
|
+
// A body that is a block value is not inlined as an expression (its constructors
|
|
380
|
+
// cannot be pinned through the statements).
|
|
381
|
+
Some((binds, body))
|
|
382
|
+
if body.stmts.len() == 1
|
|
365
|
-
|
|
383
|
+
&& matches!(&body.stmts[0].kind, StmtKind::Expr(e, ..) if !matches!(e.kind, ExprKind::Block(_))) =>
|
|
384
|
+
{
|
|
366
385
|
let Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) = body.stmts.into_iter().next() else { unreachable!() };
|
|
367
386
|
if lets.is_none() && !binds.is_empty() {
|
|
368
387
|
return Expr::FnCall(c);
|
|
@@ -986,6 +1005,8 @@ impl Scoper {
|
|
|
986
1005
|
self.stmts(&mut c.body.stmts);
|
|
987
1006
|
self.scopes.pop();
|
|
988
1007
|
}
|
|
1008
|
+
// Its locals are its own (`stmts` opens the scope).
|
|
1009
|
+
ExprKind::Block(b) => self.stmts(&mut b.stmts),
|
|
989
1010
|
_ => {
|
|
990
1011
|
for ch in childExprs(e) {
|
|
991
1012
|
self.expr(ch);
|
compiler/core/src/tail.rs
CHANGED
|
@@ -191,6 +191,8 @@ fn expr(cx: &mut Ctx, e: &mut Expr, tail: bool) {
|
|
|
191
191
|
expr(cx, ch, false);
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
|
+
// A block value runs in the middle of an expression: nothing in it is a tail call.
|
|
195
|
+
ExprKind::Block(b) => block(cx, b, false, false),
|
|
194
196
|
ExprKind::Closure(c) => {
|
|
195
197
|
// Tail relative to the closure only; its params are locals.
|
|
196
198
|
cx.locals.extend(c.params.iter().cloned());
|
compiler/core/src/trmc.rs
CHANGED
|
@@ -199,8 +199,11 @@ fn rewriteExprBody(f: &Fn, enums: &[Enum], ret: Type, nullary: String) -> Option
|
|
|
199
199
|
|
|
200
200
|
/// Constructs the rewrite does not handle: `?`/`!`/catch, closures, `return`, `todo`, `crash`.
|
|
201
201
|
fn bannedExpr(e: &Expr) -> bool {
|
|
202
|
-
crate::visit::anyExpr(e, &mut |x| {
|
|
202
|
+
crate::visit::anyExpr(e, &mut |x| match &x.kind {
|
|
203
|
-
|
|
203
|
+
ExprKind::Question(_) | ExprKind::Bang(_) | ExprKind::Closure(_) => true,
|
|
204
|
+
// `return` / `crash` / `todo` inside a block value.
|
|
205
|
+
ExprKind::Block(b) => bannedBlock(b),
|
|
206
|
+
_ => false,
|
|
204
207
|
})
|
|
205
208
|
}
|
|
206
209
|
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -460,6 +460,10 @@ struct SpreadSite {
|
|
|
460
460
|
pub(crate) fn collectTails<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) -> bool {
|
|
461
461
|
match b.stmts.last() {
|
|
462
462
|
Some(Stmt { kind: StmtKind::Expr(e, _, _), .. }) | Some(Stmt { kind: StmtKind::Return(Some(e)), .. }) => {
|
|
463
|
+
// A block value that is the result: its own last values are the tails.
|
|
464
|
+
if let ExprKind::Block(blk) = &e.kind {
|
|
465
|
+
return collectTails(blk, out);
|
|
466
|
+
}
|
|
463
467
|
out.push(e);
|
|
464
468
|
true
|
|
465
469
|
}
|
|
@@ -1008,6 +1012,9 @@ impl<'a> Scan<'a> {
|
|
|
1008
1012
|
self.expr(&i.then, tail, ab);
|
|
1009
1013
|
self.expr(&i.else_, tail, ab);
|
|
1010
1014
|
}
|
|
1015
|
+
// A block value runs its statements in order inside the expression. Its value is in
|
|
1016
|
+
// tail position only when the block is; an assign-back through it is not followed.
|
|
1017
|
+
ExprKind::Block(b) => self.block(b, tail, 99),
|
|
1011
1018
|
ExprKind::FnCall(c) => self.call(c, tail, ab),
|
|
1012
1019
|
ExprKind::ClassCall(cc) => {
|
|
1013
1020
|
match &cc.spread {
|
compiler/core/src/visit.rs
CHANGED
|
@@ -27,6 +27,29 @@ pub fn visitExpr(e: &mut Expr, f: &mut dyn FnMut(&mut Expr)) {
|
|
|
27
27
|
f(e);
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/// Calls `f` on each block value (`ExprKind::Block`) directly inside `e`: not those inside a
|
|
31
|
+
/// closure body, and not those nested in another block value (`f` recurses into its argument).
|
|
32
|
+
pub fn innerBlocks(e: &mut Expr, f: &mut dyn FnMut(&mut Block)) {
|
|
33
|
+
if let ExprKind::Block(b) = &mut e.kind {
|
|
34
|
+
f(b);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
for c in childExprs(e) {
|
|
38
|
+
innerBlocks(c, f);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// `innerBlocks` for a shared reference.
|
|
43
|
+
pub fn innerBlockRefs(e: &Expr, f: &mut dyn FnMut(&Block)) {
|
|
44
|
+
if let ExprKind::Block(b) = &e.kind {
|
|
45
|
+
f(b);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
for c in childRefs(e) {
|
|
49
|
+
innerBlockRefs(c, f);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
30
53
|
fn argExpr(a: &mut Arg) -> &mut Expr {
|
|
31
54
|
match a {
|
|
32
55
|
Arg::Positional(e) | Arg::Keyword { value: e, .. } => e,
|
compiler/core/tests/core/syntax_test.rs
CHANGED
|
@@ -53,13 +53,40 @@ fn update_operator_binds_a_computed_receiver_once() {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
#[test]
|
|
56
|
-
fn
|
|
56
|
+
fn block_if_in_an_expression_slot_stays_a_block_value() {
|
|
57
57
|
let stmts = body("fun f(a: Bool) -> Unit =\n v := if a\n a\n else\n a\n v\n", "f");
|
|
58
|
-
//
|
|
58
|
+
// no hoisting: `v := <block>` is one assignment whose value is the block, holding the `if`
|
|
59
|
+
let StmtKind::Assign(a) = &stmts[0].kind else { panic!("{:?}", stmts[0].kind) };
|
|
60
|
+
let ExprKind::Block(b) = &a.values[0].kind else { panic!("expected a block value, got {:?}", a.values[0].kind) };
|
|
59
|
-
assert!(matches!(stmts
|
|
61
|
+
assert!(matches!(b.stmts.as_slice(), [Stmt { kind: StmtKind::If(_), .. }]));
|
|
62
|
+
assert_eq!(stmts.len(), 2);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
#[test]
|
|
66
|
+
fn clashing_names_in_block_branches_are_renamed_apart() {
|
|
67
|
+
let stmts = body(
|
|
68
|
+
"fun f(a: Bool) -> Unit =\n v := if a\n t := a\n t\n else\n t := a\n t\n t := v\n t\n",
|
|
69
|
+
"f",
|
|
70
|
+
);
|
|
60
|
-
let StmtKind::Assign(a) = &stmts[
|
|
71
|
+
let StmtKind::Assign(a) = &stmts[0].kind else { panic!() };
|
|
72
|
+
let ExprKind::Block(b) = &a.values[0].kind else { panic!() };
|
|
73
|
+
let StmtKind::If(i) = &b.stmts[0].kind else { panic!() };
|
|
74
|
+
let declared = |blk: &Block| match &blk.stmts[0].kind {
|
|
75
|
+
StmtKind::Assign(x) => match &x.targets[0] {
|
|
76
|
+
AssignTarget::Var(n) => n.clone(),
|
|
77
|
+
_ => panic!(),
|
|
78
|
+
},
|
|
79
|
+
_ => panic!(),
|
|
80
|
+
};
|
|
81
|
+
let (first, second) = (declared(&i.body), declared(i.else_.as_ref().unwrap()));
|
|
82
|
+
assert_ne!(first, second);
|
|
83
|
+
assert_ne!(first, "t");
|
|
84
|
+
assert_ne!(second, "t");
|
|
61
|
-
//
|
|
85
|
+
// the use after the declaration follows the rename
|
|
62
|
-
assert!(matches!(&
|
|
86
|
+
assert!(matches!(&i.body.stmts[1].kind, StmtKind::Expr(e, ..) if matches!(&e.kind, ExprKind::Var(n) if *n == first)));
|
|
87
|
+
// the outer `t` is untouched
|
|
88
|
+
let StmtKind::Assign(outer) = &stmts[1].kind else { panic!() };
|
|
89
|
+
assert!(matches!(&outer.targets[0], AssignTarget::Var(n) if n == "t"));
|
|
63
90
|
}
|
|
64
91
|
|
|
65
92
|
#[test]
|
compiler/wasm-codegen/src/closures.rs
CHANGED
|
@@ -187,8 +187,14 @@ impl<'a, 't> ClosureWalker<'a, 't> {
|
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => self.recordClosure(expr, cl),
|
|
190
|
-
//
|
|
190
|
+
// A block value: its locals are in scope only inside it.
|
|
191
|
-
ast::Expr { kind: ast::ExprKind::Block(
|
|
191
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => {
|
|
192
|
+
let saved_locals = self.locals.clone();
|
|
193
|
+
let saved_fn_locals = self.fn_locals.clone();
|
|
194
|
+
self.walkBlock(b);
|
|
195
|
+
self.locals = saved_locals;
|
|
196
|
+
self.fn_locals = saved_fn_locals;
|
|
197
|
+
}
|
|
192
198
|
ast::Expr { kind: ast::ExprKind::Binary(b), .. } => {
|
|
193
199
|
self.walkExpr(&b.left);
|
|
194
200
|
self.walkExpr(&b.right);
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -47,8 +47,17 @@ pub(crate) fn compileExpr(
|
|
|
47
47
|
state: &mut ModuleState,
|
|
48
48
|
) -> Result<(), String> {
|
|
49
49
|
match expr {
|
|
50
|
+
// A block `if` / `match` value: its statements run inline, the last value is the result.
|
|
50
|
-
ast::Expr { kind: ast::ExprKind::Block(
|
|
51
|
+
ast::Expr { kind: ast::ExprKind::Block(blk), .. } => {
|
|
52
|
+
let ty = inferLocalType(expr, ctx);
|
|
53
|
+
if matches!(ty, PlumType::TUnit) {
|
|
51
|
-
|
|
54
|
+
// A Unit-valued branch (a call to a Unit fn) leaves nothing on the stack: run the
|
|
55
|
+
// statements, then the Unit value is the `i64` zero a Unit slot holds.
|
|
56
|
+
compileBlock(blk, body, ctx, state)?;
|
|
57
|
+
Instruction::I64Const(0).encode(body);
|
|
58
|
+
} else {
|
|
59
|
+
compileBlockInValuePosition(blk, plumTypeToValtype(&ty), body, ctx, state)?;
|
|
60
|
+
}
|
|
52
61
|
}
|
|
53
62
|
ast::Expr { kind: ast::ExprKind::Bang(b), .. } => compileEnumUnwrap(expr, &b.value, false, body, ctx, state)?,
|
|
54
63
|
ast::Expr { kind: ast::ExprKind::Bind(b), .. } => {
|
compiler/wasm-codegen/src/fnbody.rs
CHANGED
|
@@ -193,6 +193,9 @@ impl<'a> Collector<'a> {
|
|
|
193
193
|
for fa in &call.fields {
|
|
194
194
|
self.walkExpr(&fa.value);
|
|
195
195
|
}
|
|
196
|
+
if let Some(s) = &call.spread {
|
|
197
|
+
self.walkExpr(s);
|
|
198
|
+
}
|
|
196
199
|
}
|
|
197
200
|
ast::Expr { kind: ast::ExprKind::Binary(b), .. } => {
|
|
198
201
|
self.walkExpr(&b.left);
|
|
@@ -258,8 +261,8 @@ impl<'a> Collector<'a> {
|
|
|
258
261
|
// A closure literal's body has its own locals, belonging to the separate
|
|
259
262
|
// closure function it compiles to — nothing to recurse into here.
|
|
260
263
|
ast::Expr { kind: ast::ExprKind::Closure(_), .. } => {}
|
|
261
|
-
//
|
|
264
|
+
// A block value runs inline in this fn: its locals are this fn's.
|
|
262
|
-
ast::Expr { kind: ast::ExprKind::Block(
|
|
265
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => self.walkBlock(b),
|
|
263
266
|
}
|
|
264
267
|
}
|
|
265
268
|
|
compiler/wasm-codegen/src/freevars.rs
CHANGED
|
@@ -28,6 +28,10 @@ pub(crate) fn collectFreeVars(
|
|
|
28
28
|
|
|
29
29
|
pub(crate) fn fvCollectBoundBlock(block: &ast::Block, bound: &mut std::collections::HashSet<String>) {
|
|
30
30
|
for s in &block.stmts {
|
|
31
|
+
// The locals of a block `if` / `match` value belong to the closure too.
|
|
32
|
+
for e in plum_core::visit::stmtExprRefs(s) {
|
|
33
|
+
plum_core::visit::innerBlockRefs(e, &mut |b| fvCollectBoundBlock(b, bound));
|
|
34
|
+
}
|
|
31
35
|
match s {
|
|
32
36
|
ast::Stmt { kind: ast::StmtKind::Assign(a), .. } => {
|
|
33
37
|
for t in &a.targets {
|
|
@@ -257,6 +261,9 @@ pub(crate) fn fvCollectRefsExpr(
|
|
|
257
261
|
}
|
|
258
262
|
}
|
|
259
263
|
}
|
|
264
|
+
ast::Expr { kind: ast::ExprKind::Block(b), .. } => {
|
|
265
|
+
fvCollectRefsBlock(b, bound, seen, free, env, fn_decls, fn_locals);
|
|
266
|
+
}
|
|
260
267
|
ast::Expr { kind: ast::ExprKind::Closure(inner), .. } => {
|
|
261
268
|
// A name the *inner* closure references that isn't bound by the inner
|
|
262
269
|
// itself (its own params/locals) and isn't bound by *this* (outer)
|
compiler/wasm-codegen/src/stmts.rs
CHANGED
|
@@ -66,7 +66,11 @@ pub(crate) fn compileStmtInValuePosition(
|
|
|
66
66
|
) -> Result<(), String> {
|
|
67
67
|
match stmt {
|
|
68
68
|
ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. } => compileExpr(e, body, ctx, state),
|
|
69
|
+
ast::Stmt { kind: ast::StmtKind::Return(_), .. }
|
|
70
|
+
| ast::Stmt { kind: ast::StmtKind::Todo, .. }
|
|
71
|
+
| ast::Stmt { kind: ast::StmtKind::Break, .. }
|
|
72
|
+
| ast::Stmt { kind: ast::StmtKind::Continue, .. }
|
|
69
|
-
|
|
73
|
+
| ast::Stmt { kind: ast::StmtKind::Crash(_), .. } => {
|
|
70
74
|
compileStmt(stmt, body, ctx, state)
|
|
71
75
|
}
|
|
72
76
|
ast::Stmt { kind: ast::StmtKind::If(if_), .. } => compileIf(if_, Some(result_vt), body, ctx, state),
|
tests/syntax/block_values.plum
CHANGED
|
@@ -12,9 +12,20 @@ enum Oops =
|
|
|
12
12
|
fun half(n: Int) -> Result[Int, Oops] =
|
|
13
13
|
if n % 2 == 0 then Ok(n / 2) else Err(Bad)
|
|
14
14
|
|
|
15
|
+
# A `?` inside a value branch is an error (it would be a hidden `return` in the middle of an
|
|
16
|
+
# expression): the half is computed by a function, or matched.
|
|
15
17
|
fun withQ(a: Bool, n: Int) -> Result[Int, Oops] =
|
|
16
18
|
v := if a
|
|
19
|
+
match half(n)
|
|
20
|
+
Ok(h) => h + 100
|
|
21
|
+
Err(_) => 0 - 50
|
|
22
|
+
else
|
|
23
|
+
7
|
|
24
|
+
Ok(v + 1)
|
|
25
|
+
|
|
26
|
+
fun halfOrBust(a: Bool, n: Int) -> Result[Int, Oops] =
|
|
17
|
-
|
|
27
|
+
h := half(n)?
|
|
28
|
+
v := if a
|
|
18
29
|
h + 100
|
|
19
30
|
else
|
|
20
31
|
7
|
|
@@ -122,7 +133,9 @@ test "blocks"
|
|
|
122
133
|
test "more"
|
|
123
134
|
assert show(withQ(true, 4)) == 103
|
|
124
135
|
assert show(withQ(false, 4)) == 8
|
|
125
|
-
assert show(withQ(true, 3)) == 0 -
|
|
136
|
+
assert show(withQ(true, 3)) == 0 - 49
|
|
137
|
+
assert show(halfOrBust(true, 4)) == 103
|
|
138
|
+
assert show(halfOrBust(true, 3)) == 0 - 1
|
|
126
139
|
assert nested(true, true) == 1
|
|
127
140
|
assert nested(true, false) == 2
|
|
128
141
|
assert nested(false, true) == 3
|
tests/syntax/block_values_passes.plum
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
# Block `if` / `match` values stay real expressions through every pass: scoping of their names,
|
|
2
|
+
# evaluation order, nesting, in-place spreads, generics and flat structs in both branches,
|
|
3
|
+
# fusion of a fn that uses one, and a recursion that runs a million deep.
|
|
4
|
+
import std/Bool
|
|
5
|
+
import std/Float
|
|
6
|
+
import std/Int
|
|
7
|
+
import std/List
|
|
8
|
+
import std/Str
|
|
9
|
+
|
|
10
|
+
# ---- several statements, names reused across the branches and after the block ----
|
|
11
|
+
|
|
12
|
+
fun shadowed(a: Bool, s: Str) -> Str =
|
|
13
|
+
v := if a
|
|
14
|
+
t := 5
|
|
15
|
+
u := t * 2
|
|
16
|
+
"i{u}"
|
|
17
|
+
else
|
|
18
|
+
t := s
|
|
19
|
+
u := t.length()
|
|
20
|
+
"s{t}{u}"
|
|
21
|
+
t := 1.5
|
|
22
|
+
"{v} {t}"
|
|
23
|
+
|
|
24
|
+
fun shadowedMatch(o: Int, s: Str) -> Str =
|
|
25
|
+
v := match o
|
|
26
|
+
0 =>
|
|
27
|
+
t := "zero"
|
|
28
|
+
t
|
|
29
|
+
1 =>
|
|
30
|
+
t := s
|
|
31
|
+
"one{t}"
|
|
32
|
+
n =>
|
|
33
|
+
t := n * 3
|
|
34
|
+
"n{t}"
|
|
35
|
+
t := true
|
|
36
|
+
"{v}{t}"
|
|
37
|
+
|
|
38
|
+
# ---- evaluation order of a block value among the other arguments ----
|
|
39
|
+
|
|
40
|
+
struct Log(mut n: Int)
|
|
41
|
+
|
|
42
|
+
fun tick(l: Log, k: Int) -> Int =
|
|
43
|
+
l.n = l.n * 10 + k
|
|
44
|
+
k
|
|
45
|
+
|
|
46
|
+
fun three(a: Int, b: Int, c: Int) -> Int = a * 100 + b * 10 + c
|
|
47
|
+
|
|
48
|
+
fun order(l: Log, flag: Bool) -> Int =
|
|
49
|
+
three(tick(l, 1), { if flag
|
|
50
|
+
_ := tick(l, 5)
|
|
51
|
+
tick(l, 2)
|
|
52
|
+
else
|
|
53
|
+
tick(l, 3) }, tick(l, 4))
|
|
54
|
+
|
|
55
|
+
# ---- nested block values ----
|
|
56
|
+
|
|
57
|
+
fun nested(a: Bool, b: Bool, n: Int) -> Int =
|
|
58
|
+
v := if a
|
|
59
|
+
w := if b
|
|
60
|
+
x := n + 1
|
|
61
|
+
x * 2
|
|
62
|
+
else
|
|
63
|
+
match n
|
|
64
|
+
0 => 100
|
|
65
|
+
m =>
|
|
66
|
+
x := m * 7
|
|
67
|
+
x
|
|
68
|
+
w + 1
|
|
69
|
+
else
|
|
70
|
+
x := n
|
|
71
|
+
x - 1
|
|
72
|
+
v
|
|
73
|
+
|
|
74
|
+
fun inClosure(xs: List[Int], k: Int) -> List[Int] =
|
|
75
|
+
xs.map(|x| if x > k
|
|
76
|
+
y := x * 10
|
|
77
|
+
y + k
|
|
78
|
+
else
|
|
79
|
+
y := x
|
|
80
|
+
y)
|
|
81
|
+
|
|
82
|
+
# ---- flat structs and enums in both branches, and across generics ----
|
|
83
|
+
|
|
84
|
+
struct Ship(x: Int, y: Int)
|
|
85
|
+
|
|
86
|
+
enum Shape =
|
|
87
|
+
| Round(r: Int)
|
|
88
|
+
| Square(side: Int)
|
|
89
|
+
|
|
90
|
+
fun ship(a: Bool, n: Int) -> Ship =
|
|
91
|
+
s := if a
|
|
92
|
+
Ship(x: n, y: 1)
|
|
93
|
+
else
|
|
94
|
+
t := n * 2
|
|
95
|
+
Ship(x: t, y: 2)
|
|
96
|
+
s
|
|
97
|
+
|
|
98
|
+
fun shape(a: Bool, n: Int) -> Shape =
|
|
99
|
+
s := if a
|
|
100
|
+
Round(r: n)
|
|
101
|
+
else
|
|
102
|
+
Square(side: n + 1)
|
|
103
|
+
s
|
|
104
|
+
|
|
105
|
+
fun area(s: Shape) -> Int = match s
|
|
106
|
+
Round(r) => r * r
|
|
107
|
+
Square(side) => side * side
|
|
108
|
+
|
|
109
|
+
fun pickG[T](a: Bool, x: T, y: T) -> T =
|
|
110
|
+
v := if a
|
|
111
|
+
x
|
|
112
|
+
else
|
|
113
|
+
y
|
|
114
|
+
v
|
|
115
|
+
|
|
116
|
+
fun wrapG[T](a: Bool, x: T) -> Option[T] =
|
|
117
|
+
v := match a
|
|
118
|
+
true => Some(x)
|
|
119
|
+
false => None
|
|
120
|
+
v
|
|
121
|
+
|
|
122
|
+
# ---- both branches return a spread of a unique value ----
|
|
123
|
+
|
|
124
|
+
struct Pt(x: Int, y: Int, z: Int)
|
|
125
|
+
|
|
126
|
+
fun nudge(p: Pt, left: Bool) -> Pt =
|
|
127
|
+
q := if left
|
|
128
|
+
Pt(..p, x: p.x + 1)
|
|
129
|
+
else
|
|
130
|
+
Pt(..p, y: p.y + 1)
|
|
131
|
+
q
|
|
132
|
+
|
|
133
|
+
fun nudgeTwice(p: Pt, left: Bool) -> Pt =
|
|
134
|
+
q := if left
|
|
135
|
+
t := Pt(..p, x: p.x + 1)
|
|
136
|
+
Pt(..t, z: t.z + 5)
|
|
137
|
+
else
|
|
138
|
+
t := Pt(..p, y: p.y + 1)
|
|
139
|
+
Pt(..t, z: t.z + 7)
|
|
140
|
+
q
|
|
141
|
+
|
|
142
|
+
fun shared(p: Pt) -> Int =
|
|
143
|
+
a := nudge(p, true)
|
|
144
|
+
b := nudge(p, false)
|
|
145
|
+
a.x * 100 + b.y * 10 + p.x
|
|
146
|
+
|
|
147
|
+
fun chain(p: Pt, n: Int) -> Pt =
|
|
148
|
+
if n == 0
|
|
149
|
+
p
|
|
150
|
+
else
|
|
151
|
+
chain(nudge(p, n % 2 == 0), n - 1)
|
|
152
|
+
|
|
153
|
+
# ---- a fn that uses a block value fuses with its producer ----
|
|
154
|
+
|
|
155
|
+
fun upTo(n: Int) -> List[Int] =
|
|
156
|
+
if n == 0 then Nil else Cons(n, upTo(n - 1))
|
|
157
|
+
|
|
158
|
+
fun sumList(xs: List[Int]) -> Int = match xs
|
|
159
|
+
Nil => 0
|
|
160
|
+
Cons(h, t) =>
|
|
161
|
+
d := if h % 2 == 0
|
|
162
|
+
h
|
|
163
|
+
else
|
|
164
|
+
0 - h
|
|
165
|
+
d + sumList(t)
|
|
166
|
+
|
|
167
|
+
fun alternating(n: Int) -> Int = sumList(upTo(n))
|
|
168
|
+
|
|
169
|
+
# ---- other positions: loops, return, closures, conditions ----
|
|
170
|
+
|
|
171
|
+
fun loopInBlock(n: Int) -> Int =
|
|
172
|
+
v := if n > 0
|
|
173
|
+
acc := 0
|
|
174
|
+
for i := range n
|
|
175
|
+
acc = acc + i
|
|
176
|
+
acc
|
|
177
|
+
else
|
|
178
|
+
0 - 1
|
|
179
|
+
v
|
|
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
|
+
fun breakInBlock(n: Int) -> Int =
|
|
189
|
+
acc := 0
|
|
190
|
+
i := 0
|
|
191
|
+
while i < n
|
|
192
|
+
i = i + 1
|
|
193
|
+
d := if i == 3
|
|
194
|
+
0
|
|
195
|
+
else
|
|
196
|
+
i
|
|
197
|
+
acc = acc + d
|
|
198
|
+
acc
|
|
199
|
+
|
|
200
|
+
fun condBlock(n: Int) -> Bool =
|
|
201
|
+
n > 0 && { if n > 5
|
|
202
|
+
true
|
|
203
|
+
else
|
|
204
|
+
false }
|
|
205
|
+
|
|
206
|
+
fun capture(n: Int) -> Int =
|
|
207
|
+
v := if n > 0
|
|
208
|
+
base := n * 2
|
|
209
|
+
f := |x| x + base
|
|
210
|
+
f(10)
|
|
211
|
+
else
|
|
212
|
+
1
|
|
213
|
+
v
|
|
214
|
+
|
|
215
|
+
fun capture2(n: Int, xs: List[Int]) -> List[Int] =
|
|
216
|
+
v := if n > 0
|
|
217
|
+
base := n * 2
|
|
218
|
+
xs.map(|x| x + base)
|
|
219
|
+
else
|
|
220
|
+
xs
|
|
221
|
+
v
|
|
222
|
+
|
|
223
|
+
fun whileCond(n: Int) -> Int =
|
|
224
|
+
i := 0
|
|
225
|
+
while { if i < n
|
|
226
|
+
true
|
|
227
|
+
else
|
|
228
|
+
false }
|
|
229
|
+
i = i + 1
|
|
230
|
+
i
|
|
231
|
+
|
|
232
|
+
fun patNames(o: Option[Int], p: Option[Int]) -> Int =
|
|
233
|
+
a := match o
|
|
234
|
+
Some(x) => x
|
|
235
|
+
None => 0
|
|
236
|
+
b := match p
|
|
237
|
+
Some(x) => x * 2
|
|
238
|
+
None => 0
|
|
239
|
+
a + b
|
|
240
|
+
|
|
241
|
+
fun strBlock(a: Bool) -> Str =
|
|
242
|
+
s := if a
|
|
243
|
+
"x"
|
|
244
|
+
else
|
|
245
|
+
"y"
|
|
246
|
+
s
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
struct Tally(mut n: Int)
|
|
250
|
+
|
|
251
|
+
fun bumpBy(t: Tally, k: Int) -> Unit =
|
|
252
|
+
t.n = t.n + k
|
|
253
|
+
|
|
254
|
+
fun unitBlock(t: Tally, a: Bool) -> Int =
|
|
255
|
+
_ := if a
|
|
256
|
+
bumpBy(t, 1)
|
|
257
|
+
else
|
|
258
|
+
bumpBy(t, 10)
|
|
259
|
+
t.n
|
|
260
|
+
|
|
261
|
+
# ---- a million deep ----
|
|
262
|
+
|
|
263
|
+
enum Link = End | Duo(head: Int, tail: Link)
|
|
264
|
+
|
|
265
|
+
fun build(n: Int) -> Link =
|
|
266
|
+
if n == 0
|
|
267
|
+
End
|
|
268
|
+
else
|
|
269
|
+
k := if n % 2 == 0
|
|
270
|
+
n
|
|
271
|
+
else
|
|
272
|
+
n + 1
|
|
273
|
+
Duo(head: k, tail: build(n - 1))
|
|
274
|
+
|
|
275
|
+
fun buildArg(n: Int) -> Link =
|
|
276
|
+
if n == 0
|
|
277
|
+
End
|
|
278
|
+
else
|
|
279
|
+
Duo(head: n, tail: buildArg(if n > 5
|
|
280
|
+
n - 1
|
|
281
|
+
else
|
|
282
|
+
n - 1))
|
|
283
|
+
|
|
284
|
+
fun buildHead(n: Int) -> Link =
|
|
285
|
+
if n == 0
|
|
286
|
+
End
|
|
287
|
+
else
|
|
288
|
+
Duo(head: { if n % 2 == 0
|
|
289
|
+
n
|
|
290
|
+
else
|
|
291
|
+
n + 1 }, tail: buildHead(n - 1))
|
|
292
|
+
|
|
293
|
+
fun total(xs: Link, acc: Int) -> Int =
|
|
294
|
+
match xs
|
|
295
|
+
End => acc
|
|
296
|
+
Duo(h, t) => total(t, acc + h)
|
|
297
|
+
|
|
298
|
+
fun count(n: Int, acc: Int) -> Int =
|
|
299
|
+
if n == 0
|
|
300
|
+
acc
|
|
301
|
+
else
|
|
302
|
+
count(n - 1, if n % 3 == 0
|
|
303
|
+
acc + 2
|
|
304
|
+
else
|
|
305
|
+
acc + 1)
|
|
306
|
+
|
|
307
|
+
test "names reused across branches and after the block"
|
|
308
|
+
assert shadowed(true, "a") == "i10 1.5"
|
|
309
|
+
assert shadowed(false, "ab") == "sab2 1.5"
|
|
310
|
+
assert shadowedMatch(0, "q") == "zerotrue"
|
|
311
|
+
assert shadowedMatch(1, "q") == "oneqtrue"
|
|
312
|
+
assert shadowedMatch(4, "q") == "n12true"
|
|
313
|
+
|
|
314
|
+
test "evaluation order"
|
|
315
|
+
a := Log(n: 0)
|
|
316
|
+
assert order(a, true) == 1 * 100 + 2 * 10 + 4
|
|
317
|
+
assert a.n == 1524
|
|
318
|
+
b := Log(n: 0)
|
|
319
|
+
assert order(b, false) == 1 * 100 + 3 * 10 + 4
|
|
320
|
+
assert b.n == 134
|
|
321
|
+
|
|
322
|
+
test "nested block values"
|
|
323
|
+
assert nested(true, true, 4) == 11
|
|
324
|
+
assert nested(true, false, 0) == 101
|
|
325
|
+
assert nested(true, false, 3) == 22
|
|
326
|
+
assert nested(false, true, 9) == 8
|
|
327
|
+
r := inClosure([1, 5, 9], 4)
|
|
328
|
+
assert r.at(0) == 1
|
|
329
|
+
assert r.at(1) == 54
|
|
330
|
+
assert r.at(2) == 94
|
|
331
|
+
|
|
332
|
+
test "flat structs, enums and generics"
|
|
333
|
+
assert ship(true, 3).x == 3
|
|
334
|
+
assert ship(false, 3).x == 6
|
|
335
|
+
assert ship(false, 3).y == 2
|
|
336
|
+
assert area(shape(true, 3)) == 9
|
|
337
|
+
assert area(shape(false, 3)) == 16
|
|
338
|
+
assert pickG(true, 1, 2) == 1
|
|
339
|
+
assert pickG(false, "a", "b") == "b"
|
|
340
|
+
assert pickG(true, Ship(x: 7, y: 8), Ship(x: 1, y: 2)).y == 8
|
|
341
|
+
assert wrapG(true, 5)! == 5
|
|
342
|
+
assert wrapG(false, 5).isNone()
|
|
343
|
+
|
|
344
|
+
test "spreads in both branches"
|
|
345
|
+
p := Pt(x: 1, y: 2, z: 3)
|
|
346
|
+
assert nudge(p, true).x == 2
|
|
347
|
+
assert nudge(p, false).y == 3
|
|
348
|
+
assert nudgeTwice(p, true).z == 8
|
|
349
|
+
assert nudgeTwice(p, false).z == 10
|
|
350
|
+
assert nudgeTwice(Pt(x: 1, y: 2, z: 3), false).y == 3
|
|
351
|
+
assert shared(p) == 2 * 100 + 3 * 10 + 1
|
|
352
|
+
assert p.x == 1
|
|
353
|
+
assert p.y == 2
|
|
354
|
+
assert chain(Pt(x: 0, y: 0, z: 0), 5).x == 2
|
|
355
|
+
assert chain(Pt(x: 0, y: 0, z: 0), 5).y == 3
|
|
356
|
+
|
|
357
|
+
test "fused with a producer"
|
|
358
|
+
assert alternating(6) == 0 - 1 + 2 - 3 + 4 - 5 + 6
|
|
359
|
+
|
|
360
|
+
test "a million deep"
|
|
361
|
+
assert total(build(1000000), 0) == 500001000000
|
|
362
|
+
assert total(buildArg(1000000), 0) == 500000500000
|
|
363
|
+
assert total(buildHead(1000000), 0) == 500001000000
|
|
364
|
+
assert count(1000000, 0) == 1333333
|
|
365
|
+
|
|
366
|
+
test "loops, return, closures and conditional positions"
|
|
367
|
+
assert loopInBlock(4) == 6
|
|
368
|
+
assert loopInBlock(0) == 0 - 1
|
|
369
|
+
assert retInBlock(9) == 99
|
|
370
|
+
assert retInBlock(2) == 5
|
|
371
|
+
assert breakInBlock(5) == 1 + 2 + 4 + 5
|
|
372
|
+
assert condBlock(7)
|
|
373
|
+
assert !condBlock(3)
|
|
374
|
+
assert capture(3) == 16
|
|
375
|
+
assert capture2(2, [1, 2]).at(1) == 6
|
|
376
|
+
assert whileCond(5) == 5
|
|
377
|
+
assert patNames(Some(1), Some(2)) == 5
|
|
378
|
+
assert strBlock(false) == "y"
|
|
379
|
+
|
|
380
|
+
test "a Unit valued block"
|
|
381
|
+
t := Tally(n: 0)
|
|
382
|
+
assert unitBlock(t, true) == 1
|
|
383
|
+
assert unitBlock(t, false) == 11
|