plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


docs/superpowers/plans/2026-07-24-guard-clause-match.md
# Guard-Clause Match Arms Implementation Plan

> **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.

**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`.

**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).

**Tech Stack:** tree-sitter (JS grammar), Rust (`plum-core`, `plum-checker`, `plum-wasm-codegen`).

## Global Constraints

- Spec: `docs/superpowers/specs/2026-07-24-guard-clause-match-design.md`
- Guard arm syntax: `"|" (expression | "_") "=>" (expression | body)` — leading `|` required, `=>` unchanged, no new punctuation elsewhere.
- `_` 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.
- Subject-ful `match` (today's form) is completely unchanged — this is purely additive, disambiguated by presence/absence of a subject expression before the indent.
- No stdlib `Ordering` type is added — out of scope.
- 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.

---

### Task 1: Grammar — new `guard_case` rule and subject-less `match`

**Files:**
- Modify: `tooling/tree-sitter-plum/grammar.js`
- Modify: `tooling/tree-sitter-plum/test/corpus/match.txt`

**Interfaces:**
- Consumes: nothing (bottom of the pipeline).
- 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"`.

- [ ] **Step 1: Edit the `match` rule to add the subject-less alternative**

In `tooling/tree-sitter-plum/grammar.js`, find the current `match` rule:

```js
    match: ($) =>
      prec.left(
        seq(
          "match",
          commaSep1(field("subject", $.expression)), // remove comma use tuples (a, b) and match against tuples
          $._indent,
          repeat(field("case", $.case)),
          $._dedent,
        ),
      ),
```

Replace it with:

```js
    match: ($) =>
      prec.left(
        choice(
          seq(
            "match",
            commaSep1(field("subject", $.expression)), // remove comma use tuples (a, b) and match against tuples
            $._indent,
            repeat(field("case", $.case)),
            $._dedent,
          ),
          seq(
            "match",
            $._indent,
            repeat(field("case", $.guard_case)),
            $._dedent,
          ),
        ),
      ),
```

- [ ] **Step 2: Add the `guard_case` rule**

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`):

```js
    guard_case: ($) =>
      seq(
        "|",
        field("guard", choice($.expression, "_")),
        "=>",
        field("body", choice($.expression, $.body)),
      ),
```

- [ ] **Step 3: Regenerate the parser**

Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli generate`
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.

- [ ] **Step 4: Add corpus tests**

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:

```
================================================================================
match - guard-clause arms, no subject
================================================================================

compare(x: Int, y: Int) -> Int =
  match
    | x > y => 1
    | x == y => 0
    | _ => -1

--------------------------------------------------------------------------------

(source
  (fn
    (fn_identifier)
    (param
      (var_identifier)
      (type
        (type_identifier)))
    (param
      (var_identifier)
      (type
        (type_identifier)))
    (type
      (type_identifier))
    (body
      (match
        (guard_case
          (expression
            (comparison_operator
              (primary_expression
                (var_identifier))
              (primary_expression
                (var_identifier))))
          (expression
            (primary_expression
              (integer))))
        (guard_case
          (expression
            (comparison_operator
              (primary_expression
                (var_identifier))
              (primary_expression
                (var_identifier))))
          (expression
            (primary_expression
              (integer))))
        (guard_case
          (expression
            (primary_expression
              (unary_operator
                (primary_expression
                  (integer)))))))))))
```

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.

- [ ] **Step 5: Run the corpus tests, fix the expected tree from real output, iterate to green**

Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli test 2>&1 | tail -100`

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.

- [ ] **Step 6: Commit**

```bash
git add tooling/tree-sitter-plum/grammar.js tooling/tree-sitter-plum/src tooling/tree-sitter-plum/test/corpus/match.txt
git commit -m "feat(grammar): add subject-less guard-clause match arms"
```

---

### Task 2: `plum-core` — AST and parser support for guard arms

**Files:**
- Modify: `plum-core/src/ast.rs`
- Modify: `plum-core/src/parser.rs`
- Modify: `plum-core/tests/parser_test.rs`

**Interfaces:**
- 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).
- 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`).

- [ ] **Step 1: Add the `Guard` variant to `CasePattern`**

In `plum-core/src/ast.rs`, find:

```rust
#[derive(Debug, Clone, PartialEq)]
pub enum CasePattern {
    Class { name: String, fields: Vec<CasePattern> },
    String(String),
    Int(i64),
    Float(f64),
    Name(String),
    Wildcard,
}
```

Add a `Guard` variant:

```rust
#[derive(Debug, Clone, PartialEq)]
pub enum CasePattern {
    Class { name: String, fields: Vec<CasePattern> },
    String(String),
    Int(i64),
    Float(f64),
    Name(String),
    Wildcard,
    /// A boolean guard-clause arm in a subject-less `match` (`| x > y => ...`).
    Guard(Expr),
}
```

- [ ] **Step 2: Parse `guard_case` nodes**

In `plum-core/src/parser.rs`, `parse_match` currently reads:

```rust
    fn parse_match(&self, node: Node) -> Match {
        // match: "match" commaSep1(expression) "is" case+
        let mut cursor = node.walk();
        let named: Vec<Node> = node.named_children(&mut cursor).collect();
        let split = named.iter().position(|n| n.kind() == "case").unwrap_or(named.len());
        let subjects = named[..split]
            .iter()
            .map(|n| { let u = self.unwrap_expr_node(*n); self.parse_expression(u) })
            .collect();
        let cases = named[split..]
            .iter()
            .filter(|n| n.kind() == "case")
            .map(|n| self.parse_case(*n))
            .collect();
        Match { subjects, cases }
    }
```

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):

```rust
    fn parse_match(&self, node: Node) -> Match {
        // match: "match" commaSep1(expression) case+  |  "match" guard_case+
        let mut cursor = node.walk();
        let named: Vec<Node> = node.named_children(&mut cursor).collect();
        let split = named.iter()
            .position(|n| n.kind() == "case" || n.kind() == "guard_case")
            .unwrap_or(named.len());
        let subjects = named[..split]
            .iter()
            .map(|n| { let u = self.unwrap_expr_node(*n); self.parse_expression(u) })
            .collect();
        let cases = named[split..]
            .iter()
            .map(|n| match n.kind() {
                "case" => self.parse_case(*n),
                "guard_case" => self.parse_guard_case(*n),
                _ => Case { patterns: vec![], body: Block { stmts: vec![] } },
            })
            .collect();
        Match { subjects, cases }
    }

    fn parse_guard_case(&self, node: Node) -> Case {
        // guard_case: "|" field("guard", expression | "_") "=>" field("body", expression | body)
        let guard_node = node.child_by_field_name("guard");
        let pattern = match guard_node {
            Some(n) if self.text(n) == "_" => CasePattern::Wildcard,
            Some(n) => {
                let unwrapped = self.unwrap_expr_node(n);
                CasePattern::Guard(self.parse_expression(unwrapped))
            }
            None => CasePattern::Wildcard,
        };
        let body = node.child_by_field_name("body").map(|n| {
            if n.kind() == "body" {
                self.parse_block(n)
            } else {
                let unwrapped = self.unwrap_expr_node(n);
                Block { stmts: vec![Stmt::Expr(self.parse_expression(unwrapped))] }
            }
        }).unwrap_or(Block { stmts: vec![] });
        Case { patterns: vec![pattern], body }
    }
```

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).

- [ ] **Step 3: Add a parser test for guard-clause matches**

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).

- [ ] **Step 4: Run `plum-core`'s tests**

Run: `cargo test -p plum-core 2>&1 | tail -60`
Expected: PASS, including your new test.

- [ ] **Step 5: Commit**

```bash
git add plum-core/src/ast.rs plum-core/src/parser.rs plum-core/tests/parser_test.rs
git commit -m "feat(plum-core): parse guard-clause match arms into CasePattern::Guard"
```

---

### Task 3: `plum-checker` — type-check guard-clause matches

**Files:**
- Modify: `plum-checker/src/lib.rs`
- Modify: `plum-checker/tests/checker_tests.rs`

**Interfaces:**
- Consumes: `Match.subjects: Vec<Expr>` possibly empty, `CasePattern::Guard(Expr)` from Task 2.
- 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.

- [ ] **Step 1: Branch `check_match` on empty subjects**

In `plum-checker/src/lib.rs`, `check_match` currently starts:

```rust
fn check_match(m: &ast::Match, env: &TypeEnv, declared_ret: &PlumType, fn_name: &str, ctx: &CheckCtx) -> Vec<CheckError> {
    let mut errors = Vec::new();

    let mut subject_types: Vec<PlumType> = Vec::new();
    for s in &m.subjects {
        match infer_expr(s, env, ctx) {
            Ok(t) => subject_types.push(t),
            Err(msg) => errors.push(CheckError { message: format!("fn '{}': match subject: {}", fn_name, msg) }),
        }
    }
    if subject_types.len() != m.subjects.len() {
        return errors; // a subject failed to type — cases can't be checked meaningfully
    }

    for case in &m.cases {
        // ... existing subject-ful pattern-zip logic ...
    }
    errors
}
```

Add a guard-clause branch at the very top, before any of the existing subject-inference logic:

```rust
fn check_match(m: &ast::Match, env: &TypeEnv, declared_ret: &PlumType, fn_name: &str, ctx: &CheckCtx) -> Vec<CheckError> {
    let mut errors = Vec::new();

    if m.subjects.is_empty() {
        for case in &m.cases {
            let mut case_env = env.clone();
            match case.patterns.first() {
                Some(ast::CasePattern::Guard(e)) => match infer_expr(e, &case_env, ctx) {
                    Ok(ty) => {
                        if let Err(msg) = unify(&ty, &PlumType::TBool) {
                            errors.push(CheckError {
                                message: format!("fn '{}': guard clause must be Bool: {}", fn_name, msg),
                            });
                        }
                    }
                    Err(msg) => errors.push(CheckError {
                        message: format!("fn '{}': guard clause: {}", fn_name, msg),
                    }),
                },
                Some(ast::CasePattern::Wildcard) => {}
                _ => errors.push(CheckError {
                    message: format!(
                        "fn '{}': guard-clause match arm must be a boolean condition or '_'",
                        fn_name
                    ),
                }),
            }
            errors.append(&mut check_block(&case.body, &mut case_env, declared_ret, fn_name, ctx));
        }
        return errors;
    }

    let mut subject_types: Vec<PlumType> = Vec::new();
    for s in &m.subjects {
        match infer_expr(s, env, ctx) {
            Ok(t) => subject_types.push(t),
            Err(msg) => errors.push(CheckError { message: format!("fn '{}': match subject: {}", fn_name, msg) }),
        }
    }
    if subject_types.len() != m.subjects.len() {
        return errors; // a subject failed to type — cases can't be checked meaningfully
    }

    for case in &m.cases {
        // ... existing subject-ful pattern-zip logic, UNCHANGED ...
    }
    errors
}
```

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).

- [ ] **Step 2: `check_pattern` also needs a `Guard` arm (for completeness / future callers)**

`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):

```rust
        ast::CasePattern::Guard(e) => {
            // Guard clauses are only meaningful inside a subject-less match, which
            // check_match's dedicated branch already type-checks directly against
            // Bool — check_pattern is only reached for subject-ful matches, where a
            // bare Guard pattern shouldn't structurally occur. Treat it permissively
            // (no subject to unify against) rather than panicking.
            let _ = e;
            Ok(())
        }
```

Add this arm to `check_pattern`'s `match pat { ... }` (exact insertion point: wherever the current arms are — read the file first).

- [ ] **Step 3: Add checker tests**

In `plum-checker/tests/checker_tests.rs`, add tests for:
1. A guard match with all-`Bool` guards and a `_` fallback type-checks with no errors (e.g. the `compare` example).
2. A guard match with a non-`Bool` guard (e.g. `| x + 1 => 0`) produces an error.
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.

Follow this file's existing test conventions (however it currently asserts on `Vec<CheckError>` — count, message substring, etc.).

- [ ] **Step 4: Run `plum-checker`'s tests**

Run: `cargo test -p plum-checker 2>&1 | tail -100`
Expected: PASS, including your new tests.

- [ ] **Step 5: Commit**

```bash
git add plum-checker/src/lib.rs plum-checker/tests/checker_tests.rs
git commit -m "feat(plum-checker): type-check guard-clause match arms"
```

---

### Task 4: `plum-wasm-codegen` — compile guard-clause matches

**Files:**
- Modify: `plum-wasm-codegen/src/lib.rs`
- Modify: `plum-wasm-codegen/tests/codegen_tests.rs`

**Interfaces:**
- Consumes: `Match.subjects.is_empty()` + `CasePattern::Guard(Expr)`/`Wildcard` cases from Task 2/3.
- 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.

- [ ] **Step 1: Add a dedicated `compile_guard_match` function**

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):

```rust
fn compile_match(
    m: &ast::Match,
    body: &mut Vec<u8>,
    ctx: &LocalCtx,
    state: &mut ModuleState,
    result_vt: Option<ValType>,
) -> Result<(), String> {
    if m.subjects.is_empty() {
        return compile_guard_match(m, result_vt, body, ctx, state);
    }

    // ... existing subject-ful body, UNCHANGED ...
}
```

Add the new function near `compile_if` (they share the same if/else-if/else shape and `compile_case_body` helper):

```rust
/// Compiles a subject-less guard-clause match (`match \n | cond => body ...`) as an
/// if/else-if/else chain — structurally identical to `compile_if`, since a guard
/// arm's condition is an ordinary boolean expression with no subject to evaluate or
/// destructure. A `CasePattern::Wildcard` arm (bare `_`) becomes the chain's
/// trailing `else`; if none is present and every guard is false at runtime, the
/// chain falls through to `Unreachable` — the same "non-exhaustive match traps"
/// behavior today's pattern-match codegen already has for enums, just checked at
/// runtime instead of compile time (guard conditions aren't statically enumerable).
fn compile_guard_match(
    m: &ast::Match,
    result_vt: Option<ValType>,
    body: &mut Vec<u8>,
    ctx: &LocalCtx,
    state: &mut ModuleState,
) -> Result<(), String> {
    let bt = block_type_for(result_vt);
    let mut open_blocks = 0usize;
    let mut wildcard_case: Option<&ast::Case> = None;

    for case in &m.cases {
        match case.patterns.first() {
            Some(ast::CasePattern::Wildcard) => {
                wildcard_case = Some(case);
                break; // any arm after a `_` is unreachable; stop compiling arms here
            }
            Some(ast::CasePattern::Guard(cond)) => {
                compile_expr(cond, body, ctx, state)?;
                Instruction::If(bt).encode(body);
                compile_case_body(&case.body, result_vt, body, ctx, state)?;
                Instruction::Else.encode(body);
                open_blocks += 1;
            }
            _ => return Err("codegen: guard-clause match arm must be a guard or '_'".to_string()),
        }
    }

    match wildcard_case {
        Some(case) => compile_case_body(&case.body, result_vt, body, ctx, state)?,
        None => {
            if result_vt.is_some() {
                Instruction::Unreachable.encode(body);
            }
            // A guard match with no `_` in a non-value (statement) position and no
            // guard true at runtime simply falls through to nothing further to do —
            // still needs the trap so execution doesn't silently continue with a
            // dangling value-stack expectation when result_vt IS Some.
        }
    }

    for _ in 0..open_blocks {
        Instruction::End.encode(body);
    }
    Ok(())
}
```

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).

- [ ] **Step 2: Confirm the Collector pass needs no changes (verification step, not necessarily a code change)**

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.

- [ ] **Step 3: Add codegen tests**

In `plum-wasm-codegen/tests/codegen_tests.rs`, add tests:
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`.
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").

- [ ] **Step 4: Run the codegen tests**

Run: `cargo test -p plum-wasm-codegen 2>&1 | tail -100`
Expected: PASS, including your new tests.

- [ ] **Step 5: Run the full workspace suite**

Run: `cargo test --workspace 2>&1 | tail -100`
Expected: all PASS.

- [ ] **Step 6: Commit**

```bash
git add plum-wasm-codegen/src/lib.rs plum-wasm-codegen/tests/codegen_tests.rs
git commit -m "feat(plum-wasm-codegen): compile guard-clause match arms as if/else-if chains"
```

---

### Task 5: Final verification

**Files:** none (verification only).

- [ ] **Step 1: Full workspace test suite**

Run: `cargo test --workspace 2>&1 | tail -100`
Expected: all PASS.

- [ ] **Step 2: Tree-sitter corpus suite**

Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli test 2>&1 | tail -60`
Expected: all PASS.

- [ ] **Step 3: No commit needed** — verification only.