plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
docs/superpowers/plans/2026-07-24-nested-method-declarations.md
# Nested Method Declarations 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:** Let methods be declared indented directly inside a `type`/`enum` body, implicitly bound to that type as their receiver, per `docs/superpowers/specs/2026-07-24-nested-method-declarations-design.md`.
**Architecture:** This is a `plum-core`-only, parser-level desugaring — no grammar ambiguity risk (fields and `fn`s are already structurally distinguishable at the same position), and no `plum-checker`/`plum-wasm-codegen` changes at all, since a nested method desugars to EXACTLY the same `ast::Fn { type_param: Some(receiver), ... }` shape a top-level `<Receiver>`-annotated method already produces.
**Tech Stack:** tree-sitter (JS grammar), Rust (`plum-core`).
## Global Constraints
- Spec: `docs/superpowers/specs/2026-07-24-nested-method-declarations-design.md`
- Purely additive: today's top-level `methodName<Receiver>(...) = ...` form is completely unchanged and may be freely mixed with nested declarations for the same type.
- `trait` bodies are explicitly out of scope — no `fn` nesting added there.
- A nested method's `type_param` is forced to the enclosing type's name, regardless of whatever its own (redundant, optional) `<Receiver>` annotation parsed to, if one was written.
- `plum-checker`/`plum-wasm-codegen` need NO changes — verify this remains true as you implement; if it turns out not to be true, stop and report BLOCKED rather than silently expanding scope.
- Run `cargo test --workspace` and (from `tooling/tree-sitter-plum/`) `npx --yes tree-sitter-cli test` after every task.
---
### Task 1: Grammar — allow `fn` nested inside `class`/`enum` bodies
**Files:**
- Modify: `tooling/tree-sitter-plum/grammar.js`
- Modify: `tooling/tree-sitter-plum/test/corpus/type.txt`
- Modify: `tooling/tree-sitter-plum/test/corpus/enum.txt`
**Interfaces:**
- Consumes: nothing (bottom of the pipeline). Note: if the enum-discriminant-values plan is implemented before this one, `enum`'s rule will already have gained a `params` field — read the CURRENT `enum`/`class` rules before editing, don't assume this plan's excerpt below is the exact current text.
- Produces: `class` and `enum` each gain an optional trailing `field("methods", optional(repeat($.fn)))` after their existing fields, reusing the `fn` rule unmodified.
- [ ] **Step 1: Read the current `class` and `enum` rules first**
Read them directly in `tooling/tree-sitter-plum/grammar.js` — this plan's excerpts below reflect their state as of the bracket-generics-migration plan's completion, but may have since changed (e.g. if enum discriminant values landed first, `enum` will already have a `params` field).
- [ ] **Step 2: Add `field("methods", optional(repeat($.fn)))` to `class`**
Current shape (verify against the actual file):
```js
class: ($) =>
seq(
"type",
field("name", $.type_identifier),
field("generics", optional($.generics)),
field("implements", optional(seq("(", commaSep1($.type_identifier), ")"))),
"=",
$._indent,
field("fields", optional(repeat(alias($.class_field, $.field)))),
$._dedent,
),
```
Add the new field right before `$._dedent`:
```js
class: ($) =>
seq(
"type",
field("name", $.type_identifier),
field("generics", optional($.generics)),
field("implements", optional(seq("(", commaSep1($.type_identifier), ")"))),
"=",
$._indent,
field("fields", optional(repeat(alias($.class_field, $.field)))),
field("methods", optional(repeat($.fn))),
$._dedent,
),
```
- [ ] **Step 3: Add the same field to `enum`**
Current shape (verify against the actual file — this may already include a `params` field if the enum-discriminant-values plan landed first):
```js
enum: ($) =>
seq(
"enum",
field("name", $.type_identifier),
"=",
$._indent,
optional(repeat(alias($.enum_field, $.field))),
$._dedent,
),
```
Add the new field before `$._dedent`, preserving whatever else is already there:
```js
enum: ($) =>
seq(
"enum",
field("name", $.type_identifier),
"=",
$._indent,
optional(repeat(alias($.enum_field, $.field))),
field("methods", optional(repeat($.fn))),
$._dedent,
),
```
- [ ] **Step 4: Regenerate the parser**
Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli generate`
Expected: succeeds with no conflicts. `class_field`/`enum_field` and `fn` start with different tokens after their leading identifier (`:` vs. `<`/`(`), so this should be conflict-free — if tree-sitter reports one anyway, stop and report BLOCKED.
- [ ] **Step 5: Add corpus tests**
Add a new test block to `tooling/tree-sitter-plum/test/corpus/type.txt` (a class with one nested method) and one to `enum.txt` (the `Step`/`toNumber` example from the spec's Goal section, or a smaller equivalent) — match each file's existing header/divider format exactly. Don't hand-guess the expected S-expression tree: run Step 6 first to get the real parser output, then paste that into the corpus files.
- [ ] **Step 6: Run the corpus tests, fix expected trees from real output, iterate to green**
Run: `cd tooling/tree-sitter-plum && npx --yes tree-sitter-cli test 2>&1 | tail -100`. Use `npx --yes tree-sitter-cli parse -` on the new sources to get ground truth. Iterate until 100% pass, including every pre-existing test (confirm a `class`/`enum` with NO nested methods, and a `trait`, are unaffected).
- [ ] **Step 7: Commit**
```bash
git add tooling/tree-sitter-plum/grammar.js tooling/tree-sitter-plum/src tooling/tree-sitter-plum/test/corpus/type.txt tooling/tree-sitter-plum/test/corpus/enum.txt
git commit -m "feat(grammar): allow methods nested inside type/enum bodies"
```
---
### Task 2: `plum-core` — lift nested methods into top-level `Item::Fn`s
**Files:**
- Modify: `plum-core/src/parser.rs`
- Modify: `plum-core/tests/parser_test.rs`
**Interfaces:**
- Consumes: the regenerated grammar from Task 1 (`class`/`enum` nodes may now have `"fn"`-kind named children after their fields).
- Produces: each nested `fn` becomes an `Item::Fn` in `Source.items`, immediately after the owning `Item::Class`/`Item::Enum`, in the order written, with `type_param` forced to the enclosing type's name.
- [ ] **Step 1: Read the current `parse_source`, `parse_class`, `parse_enum` first**
Read their current exact bodies in `plum-core/src/parser.rs` — reproduced below as they stood when this plan was written, but re-verify, especially if the enum-discriminant-values plan already changed `parse_enum`'s signature/body:
```rust
pub fn parse_source(&self, node: Node) -> Source {
assert_eq!(node.kind(), "source");
let mut module = None;
let mut imports = Vec::new();
let mut items = Vec::new();
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
match child.kind() {
"module" => module = Some(self.parse_module(child)),
"import" => imports.push(self.parse_import(child)),
"class" => items.push(Item::Class(self.parse_class(child))),
"trait" => items.push(Item::Trait(self.parse_trait(child))),
"enum" => items.push(Item::Enum(self.parse_enum(child))),
"fn" => items.push(Item::Fn(self.parse_fn(child))),
"const" => items.push(Item::Const(self.parse_const(child))),
_ => {}
}
}
Source { module, imports, items }
}
```
- [ ] **Step 2: Add `collect_nested_fns` and wire it into `parse_source`**
Add a new helper method (place it near `parse_class`/`parse_enum`):
```rust
/// Collects any `fn` named children nested directly inside a class/enum body and
/// parses each as an ordinary top-level `Fn`, with `type_param` forced to `owner`
/// regardless of whatever the nested `fn` itself parsed (a nested method's receiver
/// is implicit from its enclosing declaration; if it also carries its own explicit,
/// redundant `<Receiver>` annotation, that's simply overridden, not treated as a
/// conflict/error).
fn collect_nested_fns(&self, node: Node, owner: &str) -> Vec<Fn> {
self.children_of_kind(node, "fn")
.into_iter()
.map(|n| {
let mut f = self.parse_fn(n);
f.type_param = Some(owner.to_string());
f
})
.collect()
}
```
Update `parse_source`'s loop so `"class"` and `"enum"` children also push their nested methods immediately after the owning item:
```rust
"class" => {
let c = self.parse_class(child);
let nested = self.collect_nested_fns(child, &c.name);
items.push(Item::Class(c));
items.extend(nested.into_iter().map(Item::Fn));
}
"enum" => {
let e = self.parse_enum(child);
let nested = self.collect_nested_fns(child, &e.name);
items.push(Item::Enum(e));
items.extend(nested.into_iter().map(Item::Fn));
}
```
(`"trait"` stays exactly as it is today, untouched — no nesting added there.)
- [ ] **Step 3: Confirm `parse_class`/`parse_enum` themselves need no changes**
`parse_class`'s field-collection (`named.iter().filter(|n| n.kind() == "field")`) and `parse_enum`'s variant-collection (via `self.children_of_kind(node, "field")`) already filter specifically for `"field"`-kind children — a nested `"fn"`-kind child is a different `kind()` and is simply skipped by these existing filters, requiring no change to either function. Verify this by reading their current bodies (Task 1 of this plan didn't touch `parse_class`/`parse_enum`, only `parse_source` and the new helper) — if you find either function DOES need a change (e.g. because it walks ALL named children rather than filtering by kind), report what you found and fix it, noting the deviation from this plan's assumption in your report.
- [ ] **Step 4: Add a parser test**
In `plum-core/tests/parser_test.rs`, parse a `type`/`enum` with one or more nested methods (e.g. the `Step`/`toNumber` example, or a smaller `type`-based equivalent) and assert:
1. `Source.items` contains the owning `Item::Class`/`Item::Enum` immediately followed by one `Item::Fn` per nested method, in the order they were written.
2. Each nested method's `Fn.type_param == Some("<EnclosingTypeName>")`.
3. A type/enum with NO nested methods still parses with no extra `Item::Fn`s (regression coverage for the common/existing case).
- [ ] **Step 5: Run `plum-core`'s tests**
Run: `cargo test -p plum-core 2>&1 | tail -60`
Expected: PASS, including your new tests and every pre-existing one (in particular, re-confirm the `Fn.type_param`/`TraitMethod.returns` regression tests added during the bracket-generics migration's Task 2 still pass — this task touches the same `parse_source`/`Fn` machinery).
- [ ] **Step 6: Commit**
```bash
git add plum-core/src/parser.rs plum-core/tests/parser_test.rs
git commit -m "feat(plum-core): lift nested type/enum methods into top-level Fn items"
```
---
### Task 3: End-to-end verification that nested methods behave identically to top-level ones
**Files:**
- Modify: `plum-checker/tests/checker_tests.rs`
- Modify: `plum-wasm-codegen/tests/codegen_tests.rs`
**Interfaces:**
- Consumes: `Item::Fn` entries produced by Task 2's desugaring.
- Produces: proof (not just assertion) that `plum-checker`/`plum-wasm-codegen` need no changes — a nested method type-checks, dispatches, and runs identically to the same method written in today's top-level `<Receiver>` form.
- [ ] **Step 1: Add a checker test**
In `plum-checker/tests/checker_tests.rs`, add a test that type-checks a small `type`/`enum` with one nested method and confirms it produces the same result (no errors, or the same errors) as an equivalent top-level `<Receiver>`-annotated version — e.g. two near-identical test sources, one nested one not, both compiled through `check_source`, asserting both succeed (or both fail identically, if you also want a negative-case pair).
- [ ] **Step 2: Add a codegen test**
In `plum-wasm-codegen/tests/codegen_tests.rs`, add a test that compiles and runs (`run_main`) a program using a nested method (e.g. the `Step`/`toNumber` example, or a smaller equivalent using a `type` instead of the enum-discriminant feature if that plan hasn't landed yet — a nested method on an ordinary `type`/`enum` is sufficient to prove this feature works standalone) and confirms the expected result.
- [ ] **Step 3: Run both crates' test suites**
Run: `cargo test -p plum-checker 2>&1 | tail -60` and `cargo test -p plum-wasm-codegen 2>&1 | tail -100`
Expected: both PASS, including your new tests.
- [ ] **Step 4: Run the full workspace suite**
Run: `cargo test --workspace 2>&1 | tail -100`
Expected: all PASS.
- [ ] **Step 5: Commit**
```bash
git add plum-checker/tests/checker_tests.rs plum-wasm-codegen/tests/codegen_tests.rs
git commit -m "test: confirm nested type/enum methods behave identically to top-level ones"
```
---
### Task 4: 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.