plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
1bc8c44
— Peter John
2026-07-24T12:26:46+05:30
docs: add implementation plan for guard-clause match arms
docs/superpowers/plans/2026-07-24-guard-clause-match.md
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
# Guard-Clause Match Arms Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** Add a subject-less `match` form whose arms are boolean guard conditions (`| cond => body`) instead of value patterns, with `_` as a catch-all, per `docs/superpowers/specs/2026-07-24-guard-clause-match-design.md`.
|
|
6
|
+
|
|
7
|
+
**Architecture:** Bottom-up: grammar (new `guard_case` rule, `match` becomes a `choice` of subject-ful/subject-less) → AST (one new `CasePattern::Guard(Expr)` variant, no new top-level struct) → parser (new `guard_case`-parsing branch reusing `parse_match`'s existing subject-splitting logic, which already tolerates zero subjects) → checker (`check_match` branches on `m.subjects.is_empty()`) → codegen (new dedicated `compile_guard_match`, reusing `compile_if`'s if/else-if/else chain shape, bypassing the subject-scratch/pattern-fallthrough machinery entirely — the existing Collector pass needs no changes, since it already produces an empty scratch-type list and a no-op pattern-zip for a subject-less match, verified during design).
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** tree-sitter (JS grammar), Rust (`plum-core`, `plum-checker`, `plum-wasm-codegen`).
|
|
10
|
+
|
|
11
|
+
## Global Constraints
|
|
12
|
+
|
|
13
|
+
- Spec: `docs/superpowers/specs/2026-07-24-guard-clause-match-design.md`
|
|
14
|
+
- Guard arm syntax: `"|" (expression | "_") "=>" (expression | body)` — leading `|` required, `=>` unchanged, no new punctuation elsewhere.
|
|
15
|
+
- `_` in guard position parses to the EXISTING `CasePattern::Wildcard` (not a new "always-true" node) — every downstream consumer that already understands `Wildcard` needs no new knowledge.
|
|
16
|
+
- Subject-ful `match` (today's form) is completely unchanged — this is purely additive, disambiguated by presence/absence of a subject expression before the indent.
|
|
17
|
+
- No stdlib `Ordering` type is added — out of scope.
|
|
18
|
+
- Run `cargo test --workspace` and (from `tooling/tree-sitter-plum/`) `npx --yes tree-sitter-cli test` after every task — all pre-existing tests must keep passing throughout.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
### Task 1: Grammar — new `guard_case` rule and subject-less `match`
|
|
23
|
+
|
|
24
|
+
**Files:**
|
|
25
|
+
- Modify: `tooling/tree-sitter-plum/grammar.js`
|
|
26
|
+
- Modify: `tooling/tree-sitter-plum/test/corpus/match.txt`
|
|
27
|
+
|
|
28
|
+
**Interfaces:**
|
|
29
|
+
- Consumes: nothing (bottom of the pipeline).
|
|
30
|
+
- Produces: a regenerated parser where `match` accepts EITHER today's subject-ful form OR a new subject-less form whose body is `repeat(field("case", $.guard_case))`; `guard_case` is a new node kind `"guard_case"` with fields `"guard"` (an `expression` or the literal `"_"`) and `"body"`.
|
|
31
|
+
|
|
32
|
+
- [ ] **Step 1: Edit the `match` rule to add the subject-less alternative**
|
|
33
|
+
|
|
34
|
+
In `tooling/tree-sitter-plum/grammar.js`, find the current `match` rule:
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
match: ($) =>
|
|
38
|
+
prec.left(
|
|
39
|
+
seq(
|
|
40
|
+
"match",
|
|
41
|
+
commaSep1(field("subject", $.expression)), // remove comma use tuples (a, b) and match against tuples
|
|
42
|
+
$._indent,
|
|
43
|
+
repeat(field("case", $.case)),
|
|
44
|
+
$._dedent,
|
|
45
|
+
),
|
|
46
|
+
),
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Replace it with:
|
|
50
|
+
|
|
51
|
+
```js
|
|
52
|
+
match: ($) =>
|
|
53
|
+
prec.left(
|
|
54
|
+
choice(
|
|
55
|
+
seq(
|
|
56
|
+
"match",
|
|
57
|
+
commaSep1(field("subject", $.expression)), // remove comma use tuples (a, b) and match against tuples
|
|
58
|
+
$._indent,
|
|
59
|
+
repeat(field("case", $.case)),
|
|
60
|
+
$._dedent,
|
|
61
|
+
),
|
|
62
|
+
seq(
|
|
63
|
+
"match",
|
|
64
|
+
$._indent,
|
|
65
|
+
repeat(field("case", $.guard_case)),
|
|
66
|
+
$._dedent,
|
|
67
|
+
),
|
|
68
|
+
),
|
|
69
|
+
),
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
- [ ] **Step 2: Add the `guard_case` rule**
|
|
73
|
+
|
|
74
|
+
Add a new rule near `case`/`case_pattern` (find the existing `case`/`case_pattern`/`class_pattern` rules and add `guard_case` right after `case_pattern`):
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
guard_case: ($) =>
|
|
78
|
+
seq(
|
|
79
|
+
"|",
|
|
80
|
+
field("guard", choice($.expression, "_")),
|
|
81
|
+
"=>",
|
|
82
|
+
field("body", choice($.expression, $.body)),
|
|
83
|
+
),
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- [ ] **Step 3: Regenerate the parser**
|
|
87
|
+
|
|
88
|
+
Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli generate`
|
|
89
|
+
Expected: succeeds with no conflicts. If tree-sitter reports a conflict (e.g. between the two `match` alternatives, or between `guard_case`'s `"_"` and `case_pattern`'s `"_"`), stop and report BLOCKED — that would mean the two forms aren't as structurally distinguishable as this plan assumes.
|
|
90
|
+
|
|
91
|
+
- [ ] **Step 4: Add corpus tests**
|
|
92
|
+
|
|
93
|
+
In `tooling/tree-sitter-plum/test/corpus/match.txt`, add a new test block (matching the file's existing format — a `====` header, source, a `----` divider, then the expected S-expression tree). Read the existing file first to match its exact section-separator style, then add:
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
================================================================================
|
|
97
|
+
match - guard-clause arms, no subject
|
|
98
|
+
================================================================================
|
|
99
|
+
|
|
100
|
+
compare(x: Int, y: Int) -> Int =
|
|
101
|
+
match
|
|
102
|
+
| x > y => 1
|
|
103
|
+
| x == y => 0
|
|
104
|
+
| _ => -1
|
|
105
|
+
|
|
106
|
+
--------------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
(source
|
|
109
|
+
(fn
|
|
110
|
+
(fn_identifier)
|
|
111
|
+
(param
|
|
112
|
+
(var_identifier)
|
|
113
|
+
(type
|
|
114
|
+
(type_identifier)))
|
|
115
|
+
(param
|
|
116
|
+
(var_identifier)
|
|
117
|
+
(type
|
|
118
|
+
(type_identifier)))
|
|
119
|
+
(type
|
|
120
|
+
(type_identifier))
|
|
121
|
+
(body
|
|
122
|
+
(match
|
|
123
|
+
(guard_case
|
|
124
|
+
(expression
|
|
125
|
+
(comparison_operator
|
|
126
|
+
(primary_expression
|
|
127
|
+
(var_identifier))
|
|
128
|
+
(primary_expression
|
|
129
|
+
(var_identifier))))
|
|
130
|
+
(expression
|
|
131
|
+
(primary_expression
|
|
132
|
+
(integer))))
|
|
133
|
+
(guard_case
|
|
134
|
+
(expression
|
|
135
|
+
(comparison_operator
|
|
136
|
+
(primary_expression
|
|
137
|
+
(var_identifier))
|
|
138
|
+
(primary_expression
|
|
139
|
+
(var_identifier))))
|
|
140
|
+
(expression
|
|
141
|
+
(primary_expression
|
|
142
|
+
(integer))))
|
|
143
|
+
(guard_case
|
|
144
|
+
(expression
|
|
145
|
+
(primary_expression
|
|
146
|
+
(unary_operator
|
|
147
|
+
(primary_expression
|
|
148
|
+
(integer)))))))))))
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Note: the exact tree shape for the `_` arm's body (`-1`, a unary-minus integer) and the precise nesting of `comparison_operator`/`expression` wrappers may not match this sketch exactly — **you must run Step 5 first, look at the ACTUAL generated tree via `tree-sitter parse`, and paste the real output into the corpus file rather than trusting this sketch verbatim.** This is standard practice for corpus tests (they encode ground truth from the real parser, not a hand-guess) and mirrors how earlier corpus updates in this codebase were done.
|
|
152
|
+
|
|
153
|
+
- [ ] **Step 5: Run the corpus tests, fix the expected tree from real output, iterate to green**
|
|
154
|
+
|
|
155
|
+
Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli test 2>&1 | tail -100`
|
|
156
|
+
|
|
157
|
+
If the new test fails, run `echo '<the exact source from Step 4>' | npx --yes tree-sitter-cli parse -` (or write it to a temp `.plum` file and parse that) to see the actual tree, then correct the corpus file's expected S-expression to match reality. Repeat until `tree-sitter-cli test` reports 100% success including your new test.
|
|
158
|
+
|
|
159
|
+
- [ ] **Step 6: Commit**
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
git add tooling/tree-sitter-plum/grammar.js tooling/tree-sitter-plum/src tooling/tree-sitter-plum/test/corpus/match.txt
|
|
163
|
+
git commit -m "feat(grammar): add subject-less guard-clause match arms"
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
### Task 2: `plum-core` — AST and parser support for guard arms
|
|
169
|
+
|
|
170
|
+
**Files:**
|
|
171
|
+
- Modify: `plum-core/src/ast.rs`
|
|
172
|
+
- Modify: `plum-core/src/parser.rs`
|
|
173
|
+
- Modify: `plum-core/tests/parser_test.rs`
|
|
174
|
+
|
|
175
|
+
**Interfaces:**
|
|
176
|
+
- Consumes: the regenerated grammar from Task 1 (node kind `"guard_case"` with fields `"guard"`/`"body"`; a `match` node with zero `"subject"` children and `"guard_case"`-kind case children instead of `"case"`-kind ones).
|
|
177
|
+
- Produces: `CasePattern::Guard(ast::Expr)` (new variant); `Match { subjects: vec![], cases }` for a guard-form match, where each `Case.patterns` has exactly one element (`Guard(expr)` or `Wildcard`).
|
|
178
|
+
|
|
179
|
+
- [ ] **Step 1: Add the `Guard` variant to `CasePattern`**
|
|
180
|
+
|
|
181
|
+
In `plum-core/src/ast.rs`, find:
|
|
182
|
+
|
|
183
|
+
```rust
|
|
184
|
+
#[derive(Debug, Clone, PartialEq)]
|
|
185
|
+
pub enum CasePattern {
|
|
186
|
+
Class { name: String, fields: Vec<CasePattern> },
|
|
187
|
+
String(String),
|
|
188
|
+
Int(i64),
|
|
189
|
+
Float(f64),
|
|
190
|
+
Name(String),
|
|
191
|
+
Wildcard,
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Add a `Guard` variant:
|
|
196
|
+
|
|
197
|
+
```rust
|
|
198
|
+
#[derive(Debug, Clone, PartialEq)]
|
|
199
|
+
pub enum CasePattern {
|
|
200
|
+
Class { name: String, fields: Vec<CasePattern> },
|
|
201
|
+
String(String),
|
|
202
|
+
Int(i64),
|
|
203
|
+
Float(f64),
|
|
204
|
+
Name(String),
|
|
205
|
+
Wildcard,
|
|
206
|
+
/// A boolean guard-clause arm in a subject-less `match` (`| x > y => ...`).
|
|
207
|
+
Guard(Expr),
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
- [ ] **Step 2: Parse `guard_case` nodes**
|
|
212
|
+
|
|
213
|
+
In `plum-core/src/parser.rs`, `parse_match` currently reads:
|
|
214
|
+
|
|
215
|
+
```rust
|
|
216
|
+
fn parse_match(&self, node: Node) -> Match {
|
|
217
|
+
// match: "match" commaSep1(expression) "is" case+
|
|
218
|
+
let mut cursor = node.walk();
|
|
219
|
+
let named: Vec<Node> = node.named_children(&mut cursor).collect();
|
|
220
|
+
let split = named.iter().position(|n| n.kind() == "case").unwrap_or(named.len());
|
|
221
|
+
let subjects = named[..split]
|
|
222
|
+
.iter()
|
|
223
|
+
.map(|n| { let u = self.unwrap_expr_node(*n); self.parse_expression(u) })
|
|
224
|
+
.collect();
|
|
225
|
+
let cases = named[split..]
|
|
226
|
+
.iter()
|
|
227
|
+
.filter(|n| n.kind() == "case")
|
|
228
|
+
.map(|n| self.parse_case(*n))
|
|
229
|
+
.collect();
|
|
230
|
+
Match { subjects, cases }
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Replace it so it also recognizes `guard_case` children (a guard-form match has NO `"case"`-kind children at all — only `"guard_case"`-kind ones — so `split` naturally lands at `named.len()` for a guard match, giving an empty `subjects` slice, which is exactly the desired `Match.subjects: vec![]`; you just need the `cases` collection to also parse `guard_case` nodes):
|
|
235
|
+
|
|
236
|
+
```rust
|
|
237
|
+
fn parse_match(&self, node: Node) -> Match {
|
|
238
|
+
// match: "match" commaSep1(expression) case+ | "match" guard_case+
|
|
239
|
+
let mut cursor = node.walk();
|
|
240
|
+
let named: Vec<Node> = node.named_children(&mut cursor).collect();
|
|
241
|
+
let split = named.iter()
|
|
242
|
+
.position(|n| n.kind() == "case" || n.kind() == "guard_case")
|
|
243
|
+
.unwrap_or(named.len());
|
|
244
|
+
let subjects = named[..split]
|
|
245
|
+
.iter()
|
|
246
|
+
.map(|n| { let u = self.unwrap_expr_node(*n); self.parse_expression(u) })
|
|
247
|
+
.collect();
|
|
248
|
+
let cases = named[split..]
|
|
249
|
+
.iter()
|
|
250
|
+
.map(|n| match n.kind() {
|
|
251
|
+
"case" => self.parse_case(*n),
|
|
252
|
+
"guard_case" => self.parse_guard_case(*n),
|
|
253
|
+
_ => Case { patterns: vec![], body: Block { stmts: vec![] } },
|
|
254
|
+
})
|
|
255
|
+
.collect();
|
|
256
|
+
Match { subjects, cases }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
fn parse_guard_case(&self, node: Node) -> Case {
|
|
260
|
+
// guard_case: "|" field("guard", expression | "_") "=>" field("body", expression | body)
|
|
261
|
+
let guard_node = node.child_by_field_name("guard");
|
|
262
|
+
let pattern = match guard_node {
|
|
263
|
+
Some(n) if self.text(n) == "_" => CasePattern::Wildcard,
|
|
264
|
+
Some(n) => {
|
|
265
|
+
let unwrapped = self.unwrap_expr_node(n);
|
|
266
|
+
CasePattern::Guard(self.parse_expression(unwrapped))
|
|
267
|
+
}
|
|
268
|
+
None => CasePattern::Wildcard,
|
|
269
|
+
};
|
|
270
|
+
let body = node.child_by_field_name("body").map(|n| {
|
|
271
|
+
if n.kind() == "body" {
|
|
272
|
+
self.parse_block(n)
|
|
273
|
+
} else {
|
|
274
|
+
let unwrapped = self.unwrap_expr_node(n);
|
|
275
|
+
Block { stmts: vec![Stmt::Expr(self.parse_expression(unwrapped))] }
|
|
276
|
+
}
|
|
277
|
+
}).unwrap_or(Block { stmts: vec![] });
|
|
278
|
+
Case { patterns: vec![pattern], body }
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
Read the current `parse_match`/`parse_case` in the actual file first — the surrounding code may have shifted slightly since this plan was written; match the existing style (e.g. whether `child_by_field_name` or positional `named_child` indexing is idiomatic here — `parse_case` uses positional filtering because `case`'s patterns and body aren't field-tagged the same way, but `guard_case`'s fields ARE explicitly named in the grammar, so `child_by_field_name` is the more direct and correct choice for it specifically).
|
|
283
|
+
|
|
284
|
+
- [ ] **Step 3: Add a parser test for guard-clause matches**
|
|
285
|
+
|
|
286
|
+
In `plum-core/tests/parser_test.rs`, add a test that parses a small guard-match function (e.g. the `compare` example from the spec) and asserts on the resulting `ast::Match`: `subjects` is empty, `cases.len() == 3`, the first two cases' single pattern is `CasePattern::Guard(_)` (match on the variant, don't need to assert the exact `Expr` shape), and the last case's pattern is `CasePattern::Wildcard`. Follow this file's existing test style/helpers (e.g. however it currently parses a source string into an `ast::Source` and drills into a specific `Fn`'s body).
|
|
287
|
+
|
|
288
|
+
- [ ] **Step 4: Run `plum-core`'s tests**
|
|
289
|
+
|
|
290
|
+
Run: `cargo test -p plum-core 2>&1 | tail -60`
|
|
291
|
+
Expected: PASS, including your new test.
|
|
292
|
+
|
|
293
|
+
- [ ] **Step 5: Commit**
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
git add plum-core/src/ast.rs plum-core/src/parser.rs plum-core/tests/parser_test.rs
|
|
297
|
+
git commit -m "feat(plum-core): parse guard-clause match arms into CasePattern::Guard"
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
### Task 3: `plum-checker` — type-check guard-clause matches
|
|
303
|
+
|
|
304
|
+
**Files:**
|
|
305
|
+
- Modify: `plum-checker/src/lib.rs`
|
|
306
|
+
- Modify: `plum-checker/tests/checker_tests.rs`
|
|
307
|
+
|
|
308
|
+
**Interfaces:**
|
|
309
|
+
- Consumes: `Match.subjects: Vec<Expr>` possibly empty, `CasePattern::Guard(Expr)` from Task 2.
|
|
310
|
+
- Produces: a guard's condition must type as `Bool`; a `Wildcard` guard arm needs no check; every arm's body still checks against `declared_ret` exactly as today.
|
|
311
|
+
|
|
312
|
+
- [ ] **Step 1: Branch `check_match` on empty subjects**
|
|
313
|
+
|
|
314
|
+
In `plum-checker/src/lib.rs`, `check_match` currently starts:
|
|
315
|
+
|
|
316
|
+
```rust
|
|
317
|
+
fn check_match(m: &ast::Match, env: &TypeEnv, declared_ret: &PlumType, fn_name: &str, ctx: &CheckCtx) -> Vec<CheckError> {
|
|
318
|
+
let mut errors = Vec::new();
|
|
319
|
+
|
|
320
|
+
let mut subject_types: Vec<PlumType> = Vec::new();
|
|
321
|
+
for s in &m.subjects {
|
|
322
|
+
match infer_expr(s, env, ctx) {
|
|
323
|
+
Ok(t) => subject_types.push(t),
|
|
324
|
+
Err(msg) => errors.push(CheckError { message: format!("fn '{}': match subject: {}", fn_name, msg) }),
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if subject_types.len() != m.subjects.len() {
|
|
328
|
+
return errors; // a subject failed to type — cases can't be checked meaningfully
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
for case in &m.cases {
|
|
332
|
+
// ... existing subject-ful pattern-zip logic ...
|
|
333
|
+
}
|
|
334
|
+
errors
|
|
335
|
+
}
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
Add a guard-clause branch at the very top, before any of the existing subject-inference logic:
|
|
339
|
+
|
|
340
|
+
```rust
|
|
341
|
+
fn check_match(m: &ast::Match, env: &TypeEnv, declared_ret: &PlumType, fn_name: &str, ctx: &CheckCtx) -> Vec<CheckError> {
|
|
342
|
+
let mut errors = Vec::new();
|
|
343
|
+
|
|
344
|
+
if m.subjects.is_empty() {
|
|
345
|
+
for case in &m.cases {
|
|
346
|
+
let mut case_env = env.clone();
|
|
347
|
+
match case.patterns.first() {
|
|
348
|
+
Some(ast::CasePattern::Guard(e)) => match infer_expr(e, &case_env, ctx) {
|
|
349
|
+
Ok(ty) => {
|
|
350
|
+
if let Err(msg) = unify(&ty, &PlumType::TBool) {
|
|
351
|
+
errors.push(CheckError {
|
|
352
|
+
message: format!("fn '{}': guard clause must be Bool: {}", fn_name, msg),
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
Err(msg) => errors.push(CheckError {
|
|
357
|
+
message: format!("fn '{}': guard clause: {}", fn_name, msg),
|
|
358
|
+
}),
|
|
359
|
+
},
|
|
360
|
+
Some(ast::CasePattern::Wildcard) => {}
|
|
361
|
+
_ => errors.push(CheckError {
|
|
362
|
+
message: format!(
|
|
363
|
+
"fn '{}': guard-clause match arm must be a boolean condition or '_'",
|
|
364
|
+
fn_name
|
|
365
|
+
),
|
|
366
|
+
}),
|
|
367
|
+
}
|
|
368
|
+
errors.append(&mut check_block(&case.body, &mut case_env, declared_ret, fn_name, ctx));
|
|
369
|
+
}
|
|
370
|
+
return errors;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
let mut subject_types: Vec<PlumType> = Vec::new();
|
|
374
|
+
for s in &m.subjects {
|
|
375
|
+
match infer_expr(s, env, ctx) {
|
|
376
|
+
Ok(t) => subject_types.push(t),
|
|
377
|
+
Err(msg) => errors.push(CheckError { message: format!("fn '{}': match subject: {}", fn_name, msg) }),
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if subject_types.len() != m.subjects.len() {
|
|
381
|
+
return errors; // a subject failed to type — cases can't be checked meaningfully
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
for case in &m.cases {
|
|
385
|
+
// ... existing subject-ful pattern-zip logic, UNCHANGED ...
|
|
386
|
+
}
|
|
387
|
+
errors
|
|
388
|
+
}
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Read the current file first to get the exact unchanged middle section right — copy it verbatim from the current source, don't retype it from this plan's earlier excerpt (this plan's excerpt may be stale relative to the actual file).
|
|
392
|
+
|
|
393
|
+
- [ ] **Step 2: `check_pattern` also needs a `Guard` arm (for completeness / future callers)**
|
|
394
|
+
|
|
395
|
+
`check_pattern` is a `match` over `CasePattern` with no `Guard` variant yet — since Rust match exhaustiveness will now fail to compile once `CasePattern::Guard` exists, add an arm (even though `check_match`'s new guard branch above doesn't call `check_pattern` for guard cases — some other code path might, and the compiler needs it regardless):
|
|
396
|
+
|
|
397
|
+
```rust
|
|
398
|
+
ast::CasePattern::Guard(e) => {
|
|
399
|
+
// Guard clauses are only meaningful inside a subject-less match, which
|
|
400
|
+
// check_match's dedicated branch already type-checks directly against
|
|
401
|
+
// Bool — check_pattern is only reached for subject-ful matches, where a
|
|
402
|
+
// bare Guard pattern shouldn't structurally occur. Treat it permissively
|
|
403
|
+
// (no subject to unify against) rather than panicking.
|
|
404
|
+
let _ = e;
|
|
405
|
+
Ok(())
|
|
406
|
+
}
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
Add this arm to `check_pattern`'s `match pat { ... }` (exact insertion point: wherever the current arms are — read the file first).
|
|
410
|
+
|
|
411
|
+
- [ ] **Step 3: Add checker tests**
|
|
412
|
+
|
|
413
|
+
In `plum-checker/tests/checker_tests.rs`, add tests for:
|
|
414
|
+
1. A guard match with all-`Bool` guards and a `_` fallback type-checks with no errors (e.g. the `compare` example).
|
|
415
|
+
2. A guard match with a non-`Bool` guard (e.g. `| x + 1 => 0`) produces an error.
|
|
416
|
+
3. A guard match with arms returning inconsistent types (e.g. one arm returns `Int`, another returns `Str`) produces an error, the same way today's subject-ful match already does for that case — find and mirror whatever existing test covers that for subject-ful match.
|
|
417
|
+
|
|
418
|
+
Follow this file's existing test conventions (however it currently asserts on `Vec<CheckError>` — count, message substring, etc.).
|
|
419
|
+
|
|
420
|
+
- [ ] **Step 4: Run `plum-checker`'s tests**
|
|
421
|
+
|
|
422
|
+
Run: `cargo test -p plum-checker 2>&1 | tail -100`
|
|
423
|
+
Expected: PASS, including your new tests.
|
|
424
|
+
|
|
425
|
+
- [ ] **Step 5: Commit**
|
|
426
|
+
|
|
427
|
+
```bash
|
|
428
|
+
git add plum-checker/src/lib.rs plum-checker/tests/checker_tests.rs
|
|
429
|
+
git commit -m "feat(plum-checker): type-check guard-clause match arms"
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
---
|
|
433
|
+
|
|
434
|
+
### Task 4: `plum-wasm-codegen` — compile guard-clause matches
|
|
435
|
+
|
|
436
|
+
**Files:**
|
|
437
|
+
- Modify: `plum-wasm-codegen/src/lib.rs`
|
|
438
|
+
- Modify: `plum-wasm-codegen/tests/codegen_tests.rs`
|
|
439
|
+
|
|
440
|
+
**Interfaces:**
|
|
441
|
+
- Consumes: `Match.subjects.is_empty()` + `CasePattern::Guard(Expr)`/`Wildcard` cases from Task 2/3.
|
|
442
|
+
- Produces: a guard match compiles as an if/else-if/else chain (mirroring `compile_if`), trapping (`Unreachable`) if no guard is true and no `Wildcard` arm is present.
|
|
443
|
+
|
|
444
|
+
- [ ] **Step 1: Add a dedicated `compile_guard_match` function**
|
|
445
|
+
|
|
446
|
+
In `plum-wasm-codegen/src/lib.rs`, `compile_match` currently starts by looking up a match-scratch slot and evaluating subjects — none of that applies to a guard match. Add a branch at the very top of `compile_match` (read the current function first to get its exact current signature/body verbatim, this plan's earlier excerpt may be stale):
|
|
447
|
+
|
|
448
|
+
```rust
|
|
449
|
+
fn compile_match(
|
|
450
|
+
m: &ast::Match,
|
|
451
|
+
body: &mut Vec<u8>,
|
|
452
|
+
ctx: &LocalCtx,
|
|
453
|
+
state: &mut ModuleState,
|
|
454
|
+
result_vt: Option<ValType>,
|
|
455
|
+
) -> Result<(), String> {
|
|
456
|
+
if m.subjects.is_empty() {
|
|
457
|
+
return compile_guard_match(m, result_vt, body, ctx, state);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ... existing subject-ful body, UNCHANGED ...
|
|
461
|
+
}
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
Add the new function near `compile_if` (they share the same if/else-if/else shape and `compile_case_body` helper):
|
|
465
|
+
|
|
466
|
+
```rust
|
|
467
|
+
/// Compiles a subject-less guard-clause match (`match \n | cond => body ...`) as an
|
|
468
|
+
/// if/else-if/else chain — structurally identical to `compile_if`, since a guard
|
|
469
|
+
/// arm's condition is an ordinary boolean expression with no subject to evaluate or
|
|
470
|
+
/// destructure. A `CasePattern::Wildcard` arm (bare `_`) becomes the chain's
|
|
471
|
+
/// trailing `else`; if none is present and every guard is false at runtime, the
|
|
472
|
+
/// chain falls through to `Unreachable` — the same "non-exhaustive match traps"
|
|
473
|
+
/// behavior today's pattern-match codegen already has for enums, just checked at
|
|
474
|
+
/// runtime instead of compile time (guard conditions aren't statically enumerable).
|
|
475
|
+
fn compile_guard_match(
|
|
476
|
+
m: &ast::Match,
|
|
477
|
+
result_vt: Option<ValType>,
|
|
478
|
+
body: &mut Vec<u8>,
|
|
479
|
+
ctx: &LocalCtx,
|
|
480
|
+
state: &mut ModuleState,
|
|
481
|
+
) -> Result<(), String> {
|
|
482
|
+
let bt = block_type_for(result_vt);
|
|
483
|
+
let mut open_blocks = 0usize;
|
|
484
|
+
let mut wildcard_case: Option<&ast::Case> = None;
|
|
485
|
+
|
|
486
|
+
for case in &m.cases {
|
|
487
|
+
match case.patterns.first() {
|
|
488
|
+
Some(ast::CasePattern::Wildcard) => {
|
|
489
|
+
wildcard_case = Some(case);
|
|
490
|
+
break; // any arm after a `_` is unreachable; stop compiling arms here
|
|
491
|
+
}
|
|
492
|
+
Some(ast::CasePattern::Guard(cond)) => {
|
|
493
|
+
compile_expr(cond, body, ctx, state)?;
|
|
494
|
+
Instruction::If(bt).encode(body);
|
|
495
|
+
compile_case_body(&case.body, result_vt, body, ctx, state)?;
|
|
496
|
+
Instruction::Else.encode(body);
|
|
497
|
+
open_blocks += 1;
|
|
498
|
+
}
|
|
499
|
+
_ => return Err("codegen: guard-clause match arm must be a guard or '_'".to_string()),
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
match wildcard_case {
|
|
504
|
+
Some(case) => compile_case_body(&case.body, result_vt, body, ctx, state)?,
|
|
505
|
+
None => {
|
|
506
|
+
if result_vt.is_some() {
|
|
507
|
+
Instruction::Unreachable.encode(body);
|
|
508
|
+
}
|
|
509
|
+
// A guard match with no `_` in a non-value (statement) position and no
|
|
510
|
+
// guard true at runtime simply falls through to nothing further to do —
|
|
511
|
+
// still needs the trap so execution doesn't silently continue with a
|
|
512
|
+
// dangling value-stack expectation when result_vt IS Some.
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
for _ in 0..open_blocks {
|
|
517
|
+
Instruction::End.encode(body);
|
|
518
|
+
}
|
|
519
|
+
Ok(())
|
|
520
|
+
}
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Read `compile_if`'s exact current body first and cross-check this sketch against it — in particular confirm the exact `Instruction::If`/`Else`/`End` encoding calls and `compile_case_body`'s exact signature match what's actually in the file (this plan's earlier research excerpt of `compile_if` may have drifted).
|
|
524
|
+
|
|
525
|
+
- [ ] **Step 2: Confirm the Collector pass needs no changes (verification step, not necessarily a code change)**
|
|
526
|
+
|
|
527
|
+
Read the `Collector` struct's `walk_stmt` handling of `ast::Stmt::Match(m)` (search for `match_scratch.insert` in `plum-wasm-codegen/src/lib.rs`). For a guard match, `m.subjects` is empty, so `subject_types` collects to `vec![]`, and the `case.patterns.iter().zip(subject_types.iter())` loop naturally produces zero iterations for every case (since `subject_types` is empty) — meaning `collect_pattern` is never called for `Guard`/`Wildcard` patterns, which is correct (they need no scratch-slot or env-binding registration). Confirm this by reading the actual code; if the Collector's `walk_stmt`/`walk_expr` for `Match` does anything ELSE that assumes `subjects.len() > 0` (e.g. panics on an empty subject list, or skips walking case bodies for empty-subject matches), that would be a real gap — fix it if found, and note the fix in your report. If it's exactly as described (a no-op for guard cases, but still walks `case.body` for nested match/expression discovery), no code change is needed here, just note that you verified it.
|
|
528
|
+
|
|
529
|
+
- [ ] **Step 3: Add codegen tests**
|
|
530
|
+
|
|
531
|
+
In `plum-wasm-codegen/tests/codegen_tests.rs`, add tests:
|
|
532
|
+
1. A guard match with a `_` fallback (the `compare` example) compiles and runs correctly for at least 3 different input pairs (one hitting each arm), via `run_main`.
|
|
533
|
+
2. A guard match with NO `_` fallback traps at runtime when no guard is true — mirror whatever existing test pattern this file already uses for "non-exhaustive match traps" (search for an existing trap/`Unreachable`-related test, e.g. around `todo_traps_at_runtime` or a non-exhaustive-enum-match test, and follow its assertion style for "the wasm call traps/errors").
|
|
534
|
+
|
|
535
|
+
- [ ] **Step 4: Run the codegen tests**
|
|
536
|
+
|
|
537
|
+
Run: `cargo test -p plum-wasm-codegen 2>&1 | tail -100`
|
|
538
|
+
Expected: PASS, including your new tests.
|
|
539
|
+
|
|
540
|
+
- [ ] **Step 5: Run the full workspace suite**
|
|
541
|
+
|
|
542
|
+
Run: `cargo test --workspace 2>&1 | tail -100`
|
|
543
|
+
Expected: all PASS.
|
|
544
|
+
|
|
545
|
+
- [ ] **Step 6: Commit**
|
|
546
|
+
|
|
547
|
+
```bash
|
|
548
|
+
git add plum-wasm-codegen/src/lib.rs plum-wasm-codegen/tests/codegen_tests.rs
|
|
549
|
+
git commit -m "feat(plum-wasm-codegen): compile guard-clause match arms as if/else-if chains"
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
---
|
|
553
|
+
|
|
554
|
+
### Task 5: Final verification
|
|
555
|
+
|
|
556
|
+
**Files:** none (verification only).
|
|
557
|
+
|
|
558
|
+
- [ ] **Step 1: Full workspace test suite**
|
|
559
|
+
|
|
560
|
+
Run: `cargo test --workspace 2>&1 | tail -100`
|
|
561
|
+
Expected: all PASS.
|
|
562
|
+
|
|
563
|
+
- [ ] **Step 2: Tree-sitter corpus suite**
|
|
564
|
+
|
|
565
|
+
Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli test 2>&1 | tail -60`
|
|
566
|
+
Expected: all PASS.
|
|
567
|
+
|
|
568
|
+
- [ ] **Step 3: No commit needed** — verification only.
|