plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
7ff9e86
— Peter John
2026-11-06T18:09:23+05:30
Simpler language: ? is a rewrite into match
- compiler/checker/src/fncheck.rs +0 -5
- compiler/checker/src/infer.rs +4 -40
- compiler/checker/src/names.rs +0 -1
- compiler/checker/tests/checker/question_tests.rs +17 -3
- compiler/core/src/closure_spec.rs +0 -1
- compiler/core/src/drive.rs +2 -2
- compiler/core/src/lib.rs +1 -0
- compiler/core/src/lower.rs +4 -0
- compiler/core/src/question.rs +479 -0
- tests/syntax/question.plum +134 -0
compiler/checker/src/fncheck.rs
CHANGED
|
@@ -189,11 +189,6 @@ pub(crate) fn checkFnBody(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) ->
|
|
|
189
189
|
.as_ref()
|
|
190
190
|
.map(|r| plumTypeFromAstG(r))
|
|
191
191
|
.unwrap_or(PlumType::TUnit);
|
|
192
|
-
// Reserved env key read by `?` (see `inferExpr`'s `Expr::Question` arm); closures remove it.
|
|
193
|
-
env.insert(
|
|
194
|
-
RETURN_KEY.to_string(),
|
|
195
|
-
TypeScheme::mono(declared_ret.clone()),
|
|
196
|
-
);
|
|
197
192
|
|
|
198
193
|
match &f.body {
|
|
199
194
|
ast::FnBody::Expr(e) => {
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -181,50 +181,14 @@ pub(crate) fn inferExprInner(
|
|
|
181
181
|
},
|
|
182
182
|
},
|
|
183
183
|
},
|
|
184
|
-
// `expr?`
|
|
184
|
+
// `expr?` is lowered to a `match` before checking (`plum_core::question`); one that
|
|
185
|
+
// is still here was rejected there.
|
|
185
|
-
ast::Expr { kind: ast::ExprKind::Question(
|
|
186
|
+
ast::Expr { kind: ast::ExprKind::Question(_), .. } => {
|
|
186
|
-
let inner_ty = resolveRecorded(&inferExpr(inner, env, ctx)?);
|
|
187
|
-
// An unresolved operand (e.g. `T.fromJson(x)?` in a generic body) is
|
|
188
|
-
// checked per instantiation, like `!`.
|
|
189
|
-
if matches!(inner_ty, PlumType::TVar(_) | PlumType::TParam(_)) {
|
|
190
|
-
return Ok(PlumType::TVar("_".to_string()));
|
|
191
|
-
}
|
|
192
|
-
if let Some(success) = optionResultSuccess(&inner_ty) {
|
|
193
|
-
let PlumType::TApp(kind, iargs) = &inner_ty else { unreachable!() };
|
|
194
|
-
let Some(outer) = env.get(RETURN_KEY).map(|s| resolveRecorded(&s.body)) else {
|
|
195
|
-
return Err(format!(
|
|
196
|
-
|
|
187
|
+
Err("'?' is not allowed here: it was not lowered (see the earlier error)".to_string())
|
|
197
|
-
inner_ty, kind
|
|
198
|
-
));
|
|
199
|
-
};
|
|
200
|
-
match &outer {
|
|
201
|
-
PlumType::TApp(okind, oargs) if okind == kind => {
|
|
202
|
-
if kind == "Result" {
|
|
203
|
-
let (ie, oe) = (resolveRecorded(&iargs[1]), resolveRecorded(&oargs[1]));
|
|
204
|
-
if ie != oe && unify(&ie, &oe, ctx).is_err() {
|
|
205
|
-
return Err(format!(
|
|
206
|
-
"'?' on {} in a fn returning {}: the error types differ; convert with .mapErr(..)",
|
|
207
|
-
inner_ty, outer
|
|
208
|
-
));
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
_ => {
|
|
213
|
-
return Err(format!(
|
|
214
|
-
"'?' on {} needs an enclosing fn returning {}[..], found {}",
|
|
215
|
-
inner_ty, kind, outer
|
|
216
|
-
));
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
return Ok(success);
|
|
220
|
-
}
|
|
221
|
-
Err(format!("'?' requires an Option or a Result, found {}", inner_ty))
|
|
222
188
|
}
|
|
223
189
|
ast::Expr { kind: ast::ExprKind::Closure(cl), .. } => {
|
|
224
190
|
let self_name = withCheck(|s| s.closure_self.borrow_mut().take());
|
|
225
191
|
let mut closure_env = env.clone();
|
|
226
|
-
// A `?` inside a closure is rejected: it has no enclosing fn return type.
|
|
227
|
-
closure_env.remove(RETURN_KEY);
|
|
228
192
|
let param_names: std::collections::HashSet<&str> =
|
|
229
193
|
cl.params.iter().map(|s| s.as_str()).collect();
|
|
230
194
|
let mut resolved_from_usage: BTreeMap<String, PlumType> = BTreeMap::new();
|
compiler/checker/src/names.rs
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
use crate::*;
|
|
4
4
|
|
|
5
|
-
pub(crate) const RETURN_KEY: &str = "$return";
|
|
6
5
|
|
|
7
6
|
/// `TypeEnv` key prefix marking a name as a top-level function (a local of the
|
|
8
7
|
/// same name shadows it instead of being a redeclaration).
|
compiler/checker/tests/checker/question_tests.rs
CHANGED
|
@@ -23,7 +23,7 @@ enum ErrB =
|
|
|
23
23
|
fn run(body: &str) -> Result<(), Vec<String>> {
|
|
24
24
|
let src = format!("{DEFS}\n{body}\n");
|
|
25
25
|
let mut source = plum_test_support::parse(&src);
|
|
26
|
-
plum_core::lower::frontEndDiag(&mut source).
|
|
26
|
+
plum_core::lower::frontEndDiag(&mut source).map_err(|e| e.into_iter().map(|x| x.message).collect::<Vec<_>>())?;
|
|
27
27
|
checkSource(&source).map_err(|e| e.into_iter().map(|x| x.message).collect())
|
|
28
28
|
}
|
|
29
29
|
|
|
@@ -56,10 +56,10 @@ fn question_result_same_error_ok() {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
#[test]
|
|
59
|
-
fn
|
|
59
|
+
fn question_result_error_mismatch_names_both_types() {
|
|
60
60
|
rejected(
|
|
61
61
|
"fun g() -> Result[Int, ErrA] = Ok(1)\nfun f() -> Result[Int, ErrB] =\n x := g()?\n Ok(x)",
|
|
62
|
-
"
|
|
62
|
+
"expected ErrB, found ErrA",
|
|
63
63
|
);
|
|
64
64
|
}
|
|
65
65
|
|
|
@@ -221,3 +221,17 @@ fn removed_forms_fail_to_compile() {
|
|
|
221
221
|
assert!(failed, "should fail to compile: {body}");
|
|
222
222
|
}
|
|
223
223
|
}
|
|
224
|
+
|
|
225
|
+
#[test]
|
|
226
|
+
fn question_rejected_forms() {
|
|
227
|
+
let g = "fun g() -> Option[Int] = Some(1)\n";
|
|
228
|
+
for (body, needle) in [
|
|
229
|
+
("fun f() -> Int =\n x := g()?\n x", "enclosing fn returning"),
|
|
230
|
+
("fun f() -> Option[Int] =\n b := true && g()? > 0\n Some(1)", "conditionally"),
|
|
231
|
+
("fun f() -> Option[Int] =\n b := if true then g()? else 1\n Some(b)", "conditionally"),
|
|
232
|
+
("fun f() -> Option[Int] =\n h := || g()?\n Some(1)", "closure"),
|
|
233
|
+
("fun f() -> Option[Int] =\n while g()? > 0\n return None\n Some(1)", "conditionally"),
|
|
234
|
+
] {
|
|
235
|
+
rejected(&format!("{g}{body}"), needle);
|
|
236
|
+
}
|
|
237
|
+
}
|
compiler/core/src/closure_spec.rs
CHANGED
|
@@ -360,7 +360,6 @@ impl<'h> Ctx<'h> {
|
|
|
360
360
|
let mut bad = false;
|
|
361
361
|
let mut usesSelf = false;
|
|
362
362
|
visitBlock(&mut c.body, &mut |e| match &mut e.kind {
|
|
363
|
-
ExprKind::Question(_) => bad = true,
|
|
364
363
|
ExprKind::Self_ => usesSelf = true,
|
|
365
364
|
ExprKind::FnCall(call) => {
|
|
366
365
|
// a closure call, also when a free fn has that name: the local shadows it
|
compiler/core/src/drive.rs
CHANGED
|
@@ -867,7 +867,7 @@ impl Driver {
|
|
|
867
867
|
fn argPure(&self, e: &Expr) -> bool {
|
|
868
868
|
match &e.kind {
|
|
869
869
|
ExprKind::Closure(_) => return true,
|
|
870
|
-
ExprKind::
|
|
870
|
+
ExprKind::Bang(_) | ExprKind::Bind(_) => return false,
|
|
871
871
|
ExprKind::FnCall(c) => {
|
|
872
872
|
let ok = !self.bound.contains(&c.name)
|
|
873
873
|
&& (self.pure.contains(&c.name) || self.ctors.contains(&c.name) || CASTS.contains(&c.name.as_str()));
|
|
@@ -2073,7 +2073,7 @@ impl Driver {
|
|
|
2073
2073
|
}
|
|
2074
2074
|
}
|
|
2075
2075
|
}
|
|
2076
|
-
ExprKind::Bang(_)
|
|
2076
|
+
ExprKind::Bang(_) => ok = false,
|
|
2077
2077
|
_ => {}
|
|
2078
2078
|
});
|
|
2079
2079
|
ok
|
compiler/core/src/lib.rs
CHANGED
|
@@ -22,6 +22,7 @@ pub mod main_result;
|
|
|
22
22
|
pub mod modules;
|
|
23
23
|
pub mod parser;
|
|
24
24
|
pub mod purity;
|
|
25
|
+
pub mod question;
|
|
25
26
|
pub mod rename;
|
|
26
27
|
pub mod reuse;
|
|
27
28
|
pub mod session;
|
compiler/core/src/lower.rs
CHANGED
|
@@ -25,6 +25,10 @@ pub fn perFileDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
|
25
25
|
/// errors.
|
|
26
26
|
pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
27
27
|
crate::session::begin();
|
|
28
|
+
let questionErrors = crate::question::lowerQuestions(source);
|
|
29
|
+
if !questionErrors.is_empty() {
|
|
30
|
+
return Err(questionErrors);
|
|
31
|
+
}
|
|
28
32
|
let ctorErrors = crate::ctors::lowerCtors(source);
|
|
29
33
|
if !ctorErrors.is_empty() {
|
|
30
34
|
return Err(diags(DiagKind::Type, ctorErrors));
|
compiler/core/src/question.rs
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
//! Lowers postfix `?` before checking. `x := e?` followed by the rest of the block becomes
|
|
2
|
+
//! `match e` with `Ok(x) => rest` and `Err(q) => Err(error: q)` (`Some` / `None` for an Option),
|
|
3
|
+
//! so no `Expr::Question` is left for the checker, the fusion passes or codegen.
|
|
4
|
+
//!
|
|
5
|
+
//! The kind (Result or Option) comes from the enclosing fn's declared return type: the checker
|
|
6
|
+
//! always required the operand to be the same kind as the return type, so no operand type is
|
|
7
|
+
//! needed and the rewrite can run in the front end.
|
|
8
|
+
//!
|
|
9
|
+
//! * A `?` nested in a larger expression is lifted to a temporary: the unwrapped value is bound
|
|
10
|
+
//! first, and every earlier sibling that is not trivial is bound to a temporary before it, so
|
|
11
|
+
//! evaluation order is kept.
|
|
12
|
+
//! * `?` is allowed at block level, including in the branches of a tail `if` / `match`, which
|
|
13
|
+
//! recurse (the branch's value is the block's value).
|
|
14
|
+
//! * Rejected: `?` in a closure, in a conditionally evaluated expression (`&&` / `||` right
|
|
15
|
+
//! side, an inline `if` branch, an `else if` condition, a `when` guard, a loop condition), and
|
|
16
|
+
//! in a fn or test that does not return an Option or a Result.
|
|
17
|
+
//! * Inside a loop body or a non-tail `if` / `match` branch the failure arm is
|
|
18
|
+
//! `return Err(error: q)` instead of a value (the rest of the body stays in the success arm, so
|
|
19
|
+
//! the code after the match runs as before). std uses `?` there next to `return` today. This
|
|
20
|
+
//! route must go (and those two forms become errors) when `return` is removed.
|
|
21
|
+
use crate::ast::*;
|
|
22
|
+
use crate::diag::{DiagKind, Diagnostic};
|
|
23
|
+
use crate::visit::*;
|
|
24
|
+
|
|
25
|
+
#[derive(Clone, Copy, PartialEq)]
|
|
26
|
+
enum Kind {
|
|
27
|
+
Option,
|
|
28
|
+
Result,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
#[derive(Clone, Copy, PartialEq)]
|
|
32
|
+
enum Mode {
|
|
33
|
+
/// The rest of the block is the rest of the fn: the failure arm is the block's value.
|
|
34
|
+
Tail,
|
|
35
|
+
/// Inside a loop body or a non-tail branch: the failure arm returns.
|
|
36
|
+
Early,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
enum Pre {
|
|
40
|
+
Bind(String, Expr),
|
|
41
|
+
Unwrap { pat: CasePattern, operand: Expr, span: Span },
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
struct Pass {
|
|
45
|
+
file: String,
|
|
46
|
+
kind: Kind,
|
|
47
|
+
fresh: usize,
|
|
48
|
+
errors: Vec<Diagnostic>,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const MOVE: &str = "move it into a function";
|
|
52
|
+
|
|
53
|
+
fn hasQ(e: &Expr) -> bool {
|
|
54
|
+
matches!(e.kind, ExprKind::Question(_)) || childRefs(e).into_iter().any(hasQ)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
fn blockHasQ(b: &Block) -> bool {
|
|
58
|
+
b.stmts.iter().any(stmtHasQ)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
fn stmtHasQ(s: &Stmt) -> bool {
|
|
62
|
+
stmtExprRefs(s).into_iter().any(hasQ) || stmtBlockRefs(s).into_iter().any(blockHasQ)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// Span of the first `?` under `e`, closures included.
|
|
66
|
+
fn firstQ(e: &Expr) -> Option<Span> {
|
|
67
|
+
let mut found = None;
|
|
68
|
+
walkRef(e, &mut |x| {
|
|
69
|
+
if found.is_none() && matches!(x.kind, ExprKind::Question(_)) {
|
|
70
|
+
found = Some(x.span);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
found
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fn firstQBlock(b: &Block) -> Option<Span> {
|
|
77
|
+
let mut found = None;
|
|
78
|
+
walkBlockRef(b, &mut |x| {
|
|
79
|
+
if found.is_none() && matches!(x.kind, ExprKind::Question(_)) {
|
|
80
|
+
found = Some(x.span);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
found
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Needs no temporary to keep its place in the evaluation order.
|
|
87
|
+
fn isTrivial(e: &Expr) -> bool {
|
|
88
|
+
match &e.kind {
|
|
89
|
+
ExprKind::Int(_)
|
|
90
|
+
| ExprKind::Float(_)
|
|
91
|
+
| ExprKind::BoolLit(_)
|
|
92
|
+
| ExprKind::Self_
|
|
93
|
+
| ExprKind::Var(_)
|
|
94
|
+
| ExprKind::TypeName(_)
|
|
95
|
+
| ExprKind::Closure(_) => true,
|
|
96
|
+
ExprKind::String(s) => s.parts.iter().all(|p| matches!(p, StringPart::Text(_))),
|
|
97
|
+
_ => false,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
fn stmt(kind: StmtKind, span: Span) -> Stmt {
|
|
102
|
+
Stmt { id: NodeId(0), span, kind }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
impl Pass {
|
|
106
|
+
fn error(&mut self, span: Span, msg: String) {
|
|
107
|
+
self.errors.push(Diagnostic::new(DiagKind::Type, self.file.clone(), span.startLine, span.startColumn, msg));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fn freshName(&mut self, base: &str) -> String {
|
|
111
|
+
self.fresh += 1;
|
|
112
|
+
format!("__{}{}", base, self.fresh)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---------- expressions ----------
|
|
116
|
+
|
|
117
|
+
/// Pulls every `?` out of `e` into `pre`, in evaluation order.
|
|
118
|
+
fn extract(&mut self, e: &mut Expr, pre: &mut Vec<Pre>) {
|
|
119
|
+
if !hasQ(e) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if matches!(e.kind, ExprKind::Question(_)) {
|
|
123
|
+
let span = e.span;
|
|
124
|
+
let ExprKind::Question(mut inner) = std::mem::replace(&mut e.kind, ExprKind::Self_) else { unreachable!() };
|
|
125
|
+
self.extract(&mut inner, pre);
|
|
126
|
+
let tmp = self.freshName("q");
|
|
127
|
+
pre.push(Pre::Unwrap { pat: CasePattern::Name(tmp.clone()), operand: *inner, span });
|
|
128
|
+
e.kind = ExprKind::Var(tmp);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
let condFrom = match &e.kind {
|
|
132
|
+
ExprKind::Bool(_) | ExprKind::InlineIf(_) | ExprKind::Bind(_) => 1,
|
|
133
|
+
_ => usize::MAX,
|
|
134
|
+
};
|
|
135
|
+
self.extractSeq(childExprs(e), condFrom, pre);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// `items` are evaluated in order; those from `condFrom` on only conditionally.
|
|
139
|
+
fn extractSeq(&mut self, items: Vec<&mut Expr>, condFrom: usize, pre: &mut Vec<Pre>) {
|
|
140
|
+
let mut last = None;
|
|
141
|
+
for (j, it) in items.iter().enumerate() {
|
|
142
|
+
if hasQ(it) {
|
|
143
|
+
if j >= condFrom {
|
|
144
|
+
let span = firstQ(it).unwrap_or(it.span);
|
|
145
|
+
self.error(span, format!("'?' in a conditionally evaluated expression is not allowed: {MOVE}"));
|
|
146
|
+
} else {
|
|
147
|
+
last = Some(j);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
let Some(last) = last else { return };
|
|
152
|
+
for (j, it) in items.into_iter().enumerate() {
|
|
153
|
+
if j > last {
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
self.extract(it, pre);
|
|
157
|
+
if j < last && !isTrivial(it) {
|
|
158
|
+
let tmp = self.freshName("t");
|
|
159
|
+
let span = it.span;
|
|
160
|
+
let taken = std::mem::replace(it, Expr::Var(tmp.clone()));
|
|
161
|
+
it.span = span;
|
|
162
|
+
pre.push(Pre::Bind(tmp, taken));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------- statements ----------
|
|
168
|
+
|
|
169
|
+
fn lowerBlock(&mut self, b: Block, mode: Mode) -> Block {
|
|
170
|
+
if !blockHasQ(&b) {
|
|
171
|
+
return b;
|
|
172
|
+
}
|
|
173
|
+
let n = b.stmts.len();
|
|
174
|
+
let mut acc: Vec<Stmt> = Vec::new();
|
|
175
|
+
for (i, s) in b.stmts.into_iter().enumerate().rev() {
|
|
176
|
+
let (pre, keep) = self.lowerStmt(s, i + 1 == n, mode);
|
|
177
|
+
let mut tail: Vec<Stmt> = keep.into_iter().collect();
|
|
178
|
+
tail.extend(acc);
|
|
179
|
+
acc = self.wrap(pre, tail, mode);
|
|
180
|
+
}
|
|
181
|
+
Block { stmts: acc }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
fn lowerStmt(&mut self, mut s: Stmt, isLast: bool, mode: Mode) -> (Vec<Pre>, Option<Stmt>) {
|
|
185
|
+
let mut pre = Vec::new();
|
|
186
|
+
if !stmtHasQ(&s) {
|
|
187
|
+
return (pre, Some(s));
|
|
188
|
+
}
|
|
189
|
+
// `x := e?` and a discarded `e?` bind the success pattern directly.
|
|
190
|
+
if !isLast {
|
|
191
|
+
match &mut s.kind {
|
|
192
|
+
StmtKind::Assign(a)
|
|
193
|
+
if a.declare
|
|
194
|
+
&& a.ty.is_none()
|
|
195
|
+
&& a.values.len() == 1
|
|
196
|
+
&& matches!(a.values[0].kind, ExprKind::Question(_))
|
|
197
|
+
&& matches!(a.targets.as_slice(), [AssignTarget::Var(_)]) =>
|
|
198
|
+
{
|
|
199
|
+
let AssignTarget::Var(name) = a.targets[0].clone() else { unreachable!() };
|
|
200
|
+
let span = a.values[0].span;
|
|
201
|
+
let ExprKind::Question(mut inner) = std::mem::replace(&mut a.values[0].kind, ExprKind::Self_) else { unreachable!() };
|
|
202
|
+
self.extract(&mut inner, &mut pre);
|
|
203
|
+
let pat = if name == "_" { CasePattern::Wildcard } else { CasePattern::Name(name) };
|
|
204
|
+
pre.push(Pre::Unwrap { pat, operand: *inner, span });
|
|
205
|
+
return (pre, None);
|
|
206
|
+
}
|
|
207
|
+
StmtKind::Expr(e, ..) if matches!(e.kind, ExprKind::Question(_)) => {
|
|
208
|
+
let span = e.span;
|
|
209
|
+
let ExprKind::Question(mut inner) = std::mem::replace(&mut e.kind, ExprKind::Self_) else { unreachable!() };
|
|
210
|
+
self.extract(&mut inner, &mut pre);
|
|
211
|
+
pre.push(Pre::Unwrap { pat: CasePattern::Wildcard, operand: *inner, span });
|
|
212
|
+
return (pre, None);
|
|
213
|
+
}
|
|
214
|
+
_ => {}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
// Expressions evaluated before any branch is chosen.
|
|
218
|
+
let condFrom = match &s.kind {
|
|
219
|
+
StmtKind::While(_) => 0,
|
|
220
|
+
StmtKind::If(_) => 1,
|
|
221
|
+
StmtKind::Match(m) => m.subjects.len(),
|
|
222
|
+
_ => usize::MAX,
|
|
223
|
+
};
|
|
224
|
+
self.extractSeq(stmtExprs(&mut s), condFrom, &mut pre);
|
|
225
|
+
// Nested blocks.
|
|
226
|
+
let kind = std::mem::replace(&mut s.kind, StmtKind::Todo);
|
|
227
|
+
s.kind = match kind {
|
|
228
|
+
StmtKind::If(mut i) => {
|
|
229
|
+
self.branches(isLast, mode, vec![&mut i.body]);
|
|
230
|
+
for e in &mut i.else_ifs {
|
|
231
|
+
self.branches(isLast, mode, vec![&mut e.body]);
|
|
232
|
+
}
|
|
233
|
+
if let Some(b) = &mut i.else_ {
|
|
234
|
+
self.branches(isLast, mode, vec![b]);
|
|
235
|
+
}
|
|
236
|
+
StmtKind::If(i)
|
|
237
|
+
}
|
|
238
|
+
StmtKind::Match(mut m) => {
|
|
239
|
+
for c in &mut m.cases {
|
|
240
|
+
self.branches(isLast, mode, vec![&mut c.body]);
|
|
241
|
+
}
|
|
242
|
+
StmtKind::Match(m)
|
|
243
|
+
}
|
|
244
|
+
StmtKind::While(mut w) => {
|
|
245
|
+
let body = std::mem::replace(&mut w.body, Block { stmts: vec![] });
|
|
246
|
+
w.body = self.lowerBlock(body, Mode::Early);
|
|
247
|
+
StmtKind::While(w)
|
|
248
|
+
}
|
|
249
|
+
StmtKind::ForLoop(mut f) => {
|
|
250
|
+
let body = std::mem::replace(&mut f.body, Block { stmts: vec![] });
|
|
251
|
+
f.body = self.lowerBlock(body, Mode::Early);
|
|
252
|
+
StmtKind::ForLoop(f)
|
|
253
|
+
}
|
|
254
|
+
other => other,
|
|
255
|
+
};
|
|
256
|
+
(pre, Some(s))
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/// One branch block of an `if` / `match`.
|
|
260
|
+
fn branches(&mut self, isLast: bool, mode: Mode, blocks: Vec<&mut Block>) {
|
|
261
|
+
for b in blocks {
|
|
262
|
+
if !blockHasQ(b) {
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
// A tail branch's value is the block's value. Otherwise control continues after
|
|
266
|
+
// the branch, so the failure arm has to return.
|
|
267
|
+
let inner = if isLast { mode } else { Mode::Early };
|
|
268
|
+
let body = std::mem::replace(b, Block { stmts: vec![] });
|
|
269
|
+
*b = self.lowerBlock(body, inner);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/// `pre` in front of `tail`: binds as `x := e`, unwraps as a `match` whose success arm is the rest.
|
|
274
|
+
fn wrap(&mut self, pre: Vec<Pre>, tail: Vec<Stmt>, mode: Mode) -> Vec<Stmt> {
|
|
275
|
+
let mut acc = tail;
|
|
276
|
+
for p in pre.into_iter().rev() {
|
|
277
|
+
match p {
|
|
278
|
+
Pre::Bind(name, value) => {
|
|
279
|
+
let span = value.span;
|
|
280
|
+
let a = Assign {
|
|
281
|
+
targets: vec![AssignTarget::Var(name)],
|
|
282
|
+
values: vec![value],
|
|
283
|
+
declare: true,
|
|
284
|
+
ty: None,
|
|
285
|
+
isSynthetic: false,
|
|
286
|
+
};
|
|
287
|
+
acc.insert(0, stmt(StmtKind::Assign(a), span));
|
|
288
|
+
}
|
|
289
|
+
Pre::Unwrap { pat, operand, span } => {
|
|
290
|
+
acc = vec![self.unwrapMatch(pat, operand, span, acc, mode)];
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
acc
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
fn unwrapMatch(&mut self, pat: CasePattern, operand: Expr, span: Span, rest: Vec<Stmt>, mode: Mode) -> Stmt {
|
|
298
|
+
let (good, failPat, failure) = match self.kind {
|
|
299
|
+
Kind::Result => {
|
|
300
|
+
let q = self.freshName("e");
|
|
301
|
+
let err = Expr::ClassCall(ClassCall {
|
|
302
|
+
type_name: "Err".to_string(),
|
|
303
|
+
fields: vec![FieldArg { name: "error".to_string(), value: Expr::Var(q.clone()).at_span(span) }],
|
|
304
|
+
generics: vec![],
|
|
305
|
+
spread: None,
|
|
306
|
+
unique: false,
|
|
307
|
+
reuse: None,
|
|
308
|
+
})
|
|
309
|
+
.at_span(span);
|
|
310
|
+
("Ok", CasePattern::class("Err".to_string(), vec![CasePattern::Name(q)]), err)
|
|
311
|
+
}
|
|
312
|
+
Kind::Option => ("Some", CasePattern::Name("None".to_string()), Expr::TypeName("None".to_string()).at_span(span)),
|
|
313
|
+
};
|
|
314
|
+
let failBody = match mode {
|
|
315
|
+
Mode::Tail => stmt(StmtKind::Expr(failure, span.startLine, span.startColumn), span),
|
|
316
|
+
Mode::Early => stmt(StmtKind::Return(Some(failure)), span),
|
|
317
|
+
};
|
|
318
|
+
let cases = vec![
|
|
319
|
+
Case { patterns: vec![CasePattern::class(good.to_string(), vec![pat])], guard: None, body: Block { stmts: rest } },
|
|
320
|
+
Case { patterns: vec![failPat], guard: None, body: Block { stmts: vec![failBody] } },
|
|
321
|
+
];
|
|
322
|
+
stmt(StmtKind::Match(Match { subjects: vec![operand], cases }), span)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
trait AtSpan {
|
|
327
|
+
fn at_span(self, span: Span) -> Self;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
impl AtSpan for Expr {
|
|
331
|
+
fn at_span(mut self, span: Span) -> Expr {
|
|
332
|
+
self.span = span;
|
|
333
|
+
self
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
fn returnKind(f: &Fn) -> Option<Kind> {
|
|
338
|
+
match f.returns.as_ref().map(|t| t.name.as_str()) {
|
|
339
|
+
Some("Option") => Some(Kind::Option),
|
|
340
|
+
Some("Result") => Some(Kind::Result),
|
|
341
|
+
_ => None,
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/// Rejects every `?` in `b`'s closures; returns whether any was found.
|
|
346
|
+
fn closureErrors(pass: &mut Pass, b: &Block) -> bool {
|
|
347
|
+
let mut spans = Vec::new();
|
|
348
|
+
walkBlockRef(b, &mut |x| {
|
|
349
|
+
if let ExprKind::Closure(c) = &x.kind {
|
|
350
|
+
if let Some(span) = firstQBlock(&c.body) {
|
|
351
|
+
spans.push(span);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
let any = !spans.is_empty();
|
|
356
|
+
for span in spans {
|
|
357
|
+
pass.error(span, format!("'?' in a closure is not allowed: {MOVE}"));
|
|
358
|
+
}
|
|
359
|
+
any
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
fn lowerFn(f: &mut Fn, fresh: &mut usize, errors: &mut Vec<Diagnostic>) {
|
|
363
|
+
let block = match &mut f.body {
|
|
364
|
+
FnBody::Block(b) => std::mem::replace(b, Block { stmts: vec![] }),
|
|
365
|
+
FnBody::Expr(e) => {
|
|
366
|
+
let (line, column) = (e.span.startLine, e.span.startColumn);
|
|
367
|
+
let span = e.span;
|
|
368
|
+
let e = std::mem::replace(e, Expr::Self_);
|
|
369
|
+
Block { stmts: vec![stmt(StmtKind::Expr(e, line, column), span)] }
|
|
370
|
+
}
|
|
371
|
+
FnBody::Extern => return,
|
|
372
|
+
};
|
|
373
|
+
let kind = returnKind(f);
|
|
374
|
+
let mut pass = Pass { file: f.file.clone(), kind: kind.unwrap_or(Kind::Result), fresh: *fresh, errors: vec![] };
|
|
375
|
+
let mut out = block;
|
|
376
|
+
if blockHasQ(&out) || closureHasQ(&out) {
|
|
377
|
+
if closureErrors(&mut pass, &out) {
|
|
378
|
+
// reported
|
|
379
|
+
}
|
|
380
|
+
if blockHasQ(&out) {
|
|
381
|
+
if kind.is_none() {
|
|
382
|
+
let ret = f.returns.as_ref().map(|t| t.name.clone()).unwrap_or_else(|| "Unit".to_string());
|
|
383
|
+
let mut spans = Vec::new();
|
|
384
|
+
walkBlockRefTop(&out, &mut spans);
|
|
385
|
+
for span in spans {
|
|
386
|
+
pass.error(span, format!("'?' needs an enclosing fn returning Option[..] or Result[..], found {ret}"));
|
|
387
|
+
}
|
|
388
|
+
} else {
|
|
389
|
+
out = pass.lowerBlock(out, Mode::Tail);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
*fresh = pass.fresh;
|
|
394
|
+
errors.append(&mut pass.errors);
|
|
395
|
+
f.body = FnBody::Block(out);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
fn closureHasQ(b: &Block) -> bool {
|
|
399
|
+
let mut any = false;
|
|
400
|
+
walkBlockRef(b, &mut |x| {
|
|
401
|
+
if let ExprKind::Closure(c) = &x.kind {
|
|
402
|
+
any |= firstQBlock(&c.body).is_some();
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
any
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/// Spans of the `?`s outside closures.
|
|
409
|
+
fn walkBlockRefTop(b: &Block, out: &mut Vec<Span>) {
|
|
410
|
+
for s in &b.stmts {
|
|
411
|
+
for e in stmtExprRefs(s) {
|
|
412
|
+
topQs(e, out);
|
|
413
|
+
}
|
|
414
|
+
for blk in stmtBlockRefs(s) {
|
|
415
|
+
walkBlockRefTop(blk, out);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
fn topQs(e: &Expr, out: &mut Vec<Span>) {
|
|
421
|
+
if matches!(e.kind, ExprKind::Question(_)) {
|
|
422
|
+
out.push(e.span);
|
|
423
|
+
}
|
|
424
|
+
for c in childRefs(e) {
|
|
425
|
+
topQs(c, out);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/// Lowers every `?` in the program. Returns the errors; a fn with an error keeps its `?`.
|
|
430
|
+
pub fn lowerQuestions(source: &mut Source) -> Vec<Diagnostic> {
|
|
431
|
+
let mut errors = Vec::new();
|
|
432
|
+
let mut fresh = 0;
|
|
433
|
+
for item in source.items.iter_mut() {
|
|
434
|
+
match item {
|
|
435
|
+
Item::Fn(f) => {
|
|
436
|
+
let probe = match &f.body {
|
|
437
|
+
FnBody::Block(b) => blockHasQ(b) || closureHasQ(b),
|
|
438
|
+
FnBody::Expr(e) => {
|
|
439
|
+
let b = Block { stmts: vec![stmt(StmtKind::Expr(e.clone(), 0, 0), e.span)] };
|
|
440
|
+
blockHasQ(&b) || closureHasQ(&b)
|
|
441
|
+
}
|
|
442
|
+
FnBody::Extern => false,
|
|
443
|
+
};
|
|
444
|
+
if probe {
|
|
445
|
+
let before = errors.len();
|
|
446
|
+
let saved = f.clone();
|
|
447
|
+
lowerFn(f, &mut fresh, &mut errors);
|
|
448
|
+
if errors.len() > before {
|
|
449
|
+
*f = saved;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
Item::Const(c) => {
|
|
454
|
+
if let Some(span) = firstQ(&c.value) {
|
|
455
|
+
errors.push(Diagnostic::new(
|
|
456
|
+
DiagKind::Type,
|
|
457
|
+
source.file.clone(),
|
|
458
|
+
span.startLine,
|
|
459
|
+
span.startColumn,
|
|
460
|
+
"'?' needs an enclosing fn returning Option[..] or Result[..], found a constant",
|
|
461
|
+
));
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
Item::Test(t) => {
|
|
465
|
+
if let Some(span) = firstQBlock(&t.body) {
|
|
466
|
+
errors.push(Diagnostic::new(
|
|
467
|
+
DiagKind::Type,
|
|
468
|
+
t.file.clone(),
|
|
469
|
+
span.startLine,
|
|
470
|
+
span.startColumn,
|
|
471
|
+
"'?' is not allowed in a closure or test: only in a fn returning Option[..] or Result[..]",
|
|
472
|
+
));
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
Item::Enum(_) => {}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
errors
|
|
479
|
+
}
|
tests/syntax/question.plum
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import std/Option
|
|
2
|
+
import std/Result
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Str
|
|
5
|
+
import std/List
|
|
6
|
+
|
|
7
|
+
enum Oops =
|
|
8
|
+
| Bad
|
|
9
|
+
| Worse
|
|
10
|
+
|
|
11
|
+
fun half(n: Int) -> Result[Int, Oops] =
|
|
12
|
+
if n % 2 == 0 then Ok(n / 2) else Err(Bad)
|
|
13
|
+
|
|
14
|
+
fun quarter(n: Int) -> Result[Int, Oops] =
|
|
15
|
+
a := half(n)?
|
|
16
|
+
b := half(a)?
|
|
17
|
+
Ok(b)
|
|
18
|
+
|
|
19
|
+
fun firstPositive(a: Int, b: Int) -> Option[Int] =
|
|
20
|
+
if a > 0 then Some(a) else if b > 0 then Some(b) else None
|
|
21
|
+
|
|
22
|
+
fun both(a: Int, b: Int) -> Option[Int] =
|
|
23
|
+
x := firstPositive(a, 0)?
|
|
24
|
+
y := firstPositive(0, b)?
|
|
25
|
+
Some(x + y)
|
|
26
|
+
|
|
27
|
+
fun val(r: Result[Int, Oops]) -> Int = match r
|
|
28
|
+
Ok(v) => v
|
|
29
|
+
Err(_) => 0 - 1
|
|
30
|
+
|
|
31
|
+
fun valOpt(o: Option[Int]) -> Int = match o
|
|
32
|
+
Some(v) => v
|
|
33
|
+
None => 0 - 1
|
|
34
|
+
|
|
35
|
+
fun valStr(r: Result[Str, Oops]) -> Str = match r
|
|
36
|
+
Ok(v) => v
|
|
37
|
+
Err(_) => "bad"
|
|
38
|
+
|
|
39
|
+
fun add(a: Int, b: Int) -> Int = a + b
|
|
40
|
+
|
|
41
|
+
struct Log(mut trace: Int)
|
|
42
|
+
|
|
43
|
+
fun tick(log: Log, tag: Int, n: Int) -> Result[Int, Oops] =
|
|
44
|
+
log.trace = log.trace * 10 + tag
|
|
45
|
+
half(n)
|
|
46
|
+
|
|
47
|
+
fun note(log: Log, tag: Int) -> Int =
|
|
48
|
+
log.trace = log.trace * 10 + tag
|
|
49
|
+
tag
|
|
50
|
+
|
|
51
|
+
# `?` nested in arguments: each call runs once, left to right, and a failure skips the rest.
|
|
52
|
+
fun nested(a: Int, b: Int) -> Result[Int, Oops] =
|
|
53
|
+
Ok(add(half(a)?, half(b)?))
|
|
54
|
+
|
|
55
|
+
fun order(log: Log, a: Int, b: Int) -> Result[Int, Oops] =
|
|
56
|
+
Ok(add(tick(log, 1, a)?, tick(log, 2, b)?))
|
|
57
|
+
|
|
58
|
+
fun orderMixed(log: Log, a: Int) -> Result[Int, Oops] =
|
|
59
|
+
Ok(add(note(log, 1), add(note(log, 2), tick(log, 3, a)?)))
|
|
60
|
+
|
|
61
|
+
fun inTailIf(n: Int) -> Result[Int, Oops] =
|
|
62
|
+
if n > 10
|
|
63
|
+
x := half(n)?
|
|
64
|
+
Ok(x + 1)
|
|
65
|
+
else
|
|
66
|
+
Ok(n)
|
|
67
|
+
|
|
68
|
+
fun inTailMatch(n: Int) -> Result[Int, Oops] = match n
|
|
69
|
+
0 => Ok(0)
|
|
70
|
+
_ =>
|
|
71
|
+
x := half(n)?
|
|
72
|
+
Ok(x)
|
|
73
|
+
|
|
74
|
+
fun interp(n: Int) -> Result[Str, Oops] =
|
|
75
|
+
Ok("half is {half(n)?}")
|
|
76
|
+
|
|
77
|
+
fun checkEven(n: Int) -> Result[Unit, Oops] =
|
|
78
|
+
_ := half(n)?
|
|
79
|
+
Ok(Unit)
|
|
80
|
+
|
|
81
|
+
fun discarded(n: Int) -> Result[Int, Oops] =
|
|
82
|
+
checkEven(n)?
|
|
83
|
+
_ := half(n)?
|
|
84
|
+
Ok(n)
|
|
85
|
+
|
|
86
|
+
fun inLoop(n: Int) -> Result[Int, Oops] =
|
|
87
|
+
total := 0
|
|
88
|
+
for i := range n
|
|
89
|
+
h := half(i * 2)?
|
|
90
|
+
total = total + h
|
|
91
|
+
Ok(total)
|
|
92
|
+
|
|
93
|
+
test "chains"
|
|
94
|
+
assert val(quarter(8)) == 2
|
|
95
|
+
assert val(quarter(6)) == 0 - 1
|
|
96
|
+
assert val(quarter(3)) == 0 - 1
|
|
97
|
+
|
|
98
|
+
test "option"
|
|
99
|
+
assert valOpt(both(3, 4)) == 7
|
|
100
|
+
assert valOpt(both(0, 4)) == 0 - 1
|
|
101
|
+
|
|
102
|
+
test "nested in arguments"
|
|
103
|
+
assert val(nested(4, 6)) == 5
|
|
104
|
+
assert val(nested(4, 7)) == 0 - 1
|
|
105
|
+
assert val(nested(3, 6)) == 0 - 1
|
|
106
|
+
|
|
107
|
+
test "evaluation order"
|
|
108
|
+
log := Log(trace: 0)
|
|
109
|
+
assert val(order(log, 2, 4)) == 3
|
|
110
|
+
assert log.trace == 12
|
|
111
|
+
log2 := Log(trace: 0)
|
|
112
|
+
assert val(order(log2, 3, 4)) == 0 - 1
|
|
113
|
+
assert log2.trace == 1
|
|
114
|
+
log3 := Log(trace: 0)
|
|
115
|
+
assert val(orderMixed(log3, 6)) == 6
|
|
116
|
+
assert log3.trace == 123
|
|
117
|
+
log4 := Log(trace: 0)
|
|
118
|
+
assert val(orderMixed(log4, 5)) == 0 - 1
|
|
119
|
+
assert log4.trace == 123
|
|
120
|
+
|
|
121
|
+
test "tail branches"
|
|
122
|
+
assert val(inTailIf(20)) == 11
|
|
123
|
+
assert val(inTailIf(5)) == 5
|
|
124
|
+
assert val(inTailIf(11)) == 0 - 1
|
|
125
|
+
assert val(inTailMatch(0)) == 0
|
|
126
|
+
assert val(inTailMatch(8)) == 4
|
|
127
|
+
assert val(inTailMatch(7)) == 0 - 1
|
|
128
|
+
|
|
129
|
+
test "other positions"
|
|
130
|
+
assert valStr(interp(6)) == "half is 3"
|
|
131
|
+
assert valStr(interp(5)) == "bad"
|
|
132
|
+
assert val(discarded(4)) == 4
|
|
133
|
+
assert val(discarded(5)) == 0 - 1
|
|
134
|
+
assert val(inLoop(4)) == 6
|