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-23-field-assignment.md
# Field/Attribute Assignment Target 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:** Make `obj.field = value` a valid assignment target end-to-end (grammar → parser → checker → codegen), so methods like `libs/std/list.plum`'s can mutate `self`'s fields.

**Architecture:** Add a `field_target` grammar rule (an "attribute with no call args", used only on the assignment LHS) and a new `AssignTarget` AST enum (`Var(String)` / `Field(Box<Expr>, String)`). Thread the new variant through the checker's single `Stmt::Assign` arm and codegen's five `Stmt::Assign` match arms (a sixth site, `scan_stmt_for_param_types`, only reads `a.values` and needs no change). The field-write itself reuses the exact offset arithmetic already used for field reads (`Expr::Attribute`/`AttrKind::Field`) and class-literal field init in `plum-wasm-codegen/src/lib.rs`.

**Tech Stack:** Rust, tree-sitter (grammar.js + generated C parser), wasm-encoder/wasmparser, wasmtime (test execution).

## Global Constraints

- Spec: `docs/superpowers/specs/2026-07-23-field-assignment-design.md`
- Scope is exactly: `<object-expr>.<field> = <value>` as an assignment target (including chains like `self.head.value = x`, which fall out for free). Comma-separated multi-assign continues to work, mixing var and field targets.
- Out of scope: variadic parameters, `List`'s other `todo` methods, index/array assignment, enum-payload mutation — do not touch these.
- Every new/changed error message must follow the existing message shape used in the touched function (e.g. checker: `"fn '{}': assign '{}': {}"`; codegen: `"codegen: ..."`).
- Run the full workspace test suite (`cargo test --workspace`) after every task that touches Rust code — all pre-existing tests must keep passing throughout, not just the new ones.

---

### Task 1: Grammar — `field_target` rule and updated `assign` rule

**Files:**
- Modify: `tooling/tree-sitter-plum/grammar.js` (the `assign` rule, ~line 202)
- Test: `tooling/tree-sitter-plum/test/corpus/assign.txt` (append new corpus cases)

**Interfaces:**
- Produces: a new named grammar node `field_target` with fields `object` (a `primary_expression`) and `member` (an `fn_identifier`), and an `assign` rule whose LHS is `commaSep1(choice($.var_identifier, $.field_target))`. Task 2's parser code matches on these two node kinds by name (`"var_identifier"` / `"field_target"`).

- [ ] **Step 1: Add the failing corpus test**

Append to `tooling/tree-sitter-plum/test/corpus/assign.txt`:

```
================================================================================
field assignment target
================================================================================

main() =
  self.head = value
  self.head.value = x
  a, self.field = 1, 2

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

(source
  (fn
    (fn_identifier)
    (body
      (assign
        (field_target
          (primary_expression
            (self))
          (fn_identifier))
        (expression
          (primary_expression
            (var_identifier))))
      (assign
        (field_target
          (primary_expression
            (attribute
              (primary_expression
                (self))
              (fn_identifier)))
          (fn_identifier))
        (expression
          (primary_expression
            (var_identifier))))
      (assign
        (var_identifier)
        (field_target
          (primary_expression
            (var_identifier))
          (fn_identifier))
        (expression
          (primary_expression
            (integer)))
        (expression
          (primary_expression
            (integer)))))))
```

- [ ] **Step 2: Run the corpus test to verify it fails**

Run: `cd tooling/tree-sitter-plum && make corpus_test`
Expected: FAIL — `assign` doesn't yet parse `field_target` (either a parse error on `self.head = value`, or a mismatched-tree failure against the expected output above).

- [ ] **Step 3: Add the grammar rule**

In `tooling/tree-sitter-plum/grammar.js`, replace the `assign` rule (~line 202) with:

```js
    field_target: ($) =>
      seq(
        field("object", $.primary_expression),
        ".",
        field("member", $.fn_identifier),
      ),

    assign: ($) =>
      seq(
        commaSep1(choice($.var_identifier, $.field_target)),
        "=",
        commaSep1($.expression),
      ),
```

- [ ] **Step 4: Regenerate and run the corpus test**

Run: `cd tooling/tree-sitter-plum && make corpus_test`
Expected: PASS. If the actual tree shape printed by the failure differs from Step 1's expected output (e.g. field ordering), update the corpus file's expected tree to match tree-sitter's actual canonical output rather than fighting the generator — the goal is a parse for `self.head.value = x` where the outer `field_target`'s `object` is an `attribute` node wrapping the inner `self.head`.

- [ ] **Step 5: Run the full existing corpus suite**

Run: `cd tooling/tree-sitter-plum && make corpus_test`
Expected: PASS — all pre-existing `.txt` corpus files (assert, const, enum, for, function, if, literals, match, trait, type, while) still pass unchanged.

- [ ] **Step 6: Commit**

```bash
git add tooling/tree-sitter-plum/grammar.js tooling/tree-sitter-plum/test/corpus/assign.txt tooling/tree-sitter-plum/src tooling/tree-sitter-plum/bindings
git commit -m "feat(tree-sitter-plum): add field_target rule for obj.field = value assignment"
```

(`tree-sitter generate` regenerates `src/parser.c`/`src/grammar.json`/`src/node-types.json` — stage whatever files it changed under `src/` and `bindings/`.)

---

### Task 2: AST — `AssignTarget` enum

**Files:**
- Modify: `plum-core/src/ast.rs` (the `Assign` struct, ~line 155)
- Modify: `plum-core/src/parser.rs` (`parse_assign`, ~line 351)
- Test: `plum-core` has no dedicated parser unit tests today — verification for this task is via the downstream checker/codegen tests in Tasks 3–4, which exercise `parse_assign` transitively. Do not add a `plum-core`-only test; go straight to compiling and running `cargo build --workspace` to confirm the new enum compiles and every existing match on `Assign.targets`/`AssignTarget` (there are none yet outside this crate) still type-checks after this task alone (it won't — Tasks 3/4 fix the call sites; that's expected and is why Task 2 ends with a build-only check, not a full test run).

**Interfaces:**
- Consumes: nothing new.
- Produces: `pub enum AssignTarget { Var(String), Field(Box<Expr>, String) }` and `pub struct Assign { pub targets: Vec<AssignTarget>, pub values: Vec<Expr> }` (replacing `pub targets: Vec<String>`). Every downstream task matches on `AssignTarget::Var(name)` / `AssignTarget::Field(object, field_name)`.

- [ ] **Step 1: Change the AST types**

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

```rust
#[derive(Debug, Clone, PartialEq)]
pub struct Assign {
    pub targets: Vec<String>,
    pub values: Vec<Expr>,
}
```

with:

```rust
#[derive(Debug, Clone, PartialEq)]
pub enum AssignTarget {
    Var(String),
    /// `object.field = value` — `object`'s evaluated type must be a class; `field`
    /// is that class's field name being written.
    Field(Box<Expr>, String),
}

#[derive(Debug, Clone, PartialEq)]
pub struct Assign {
    pub targets: Vec<AssignTarget>,
    pub values: Vec<Expr>,
}
```

- [ ] **Step 2: Update `parse_assign`**

In `plum-core/src/parser.rs`, replace `parse_assign` (~line 351):

```rust
    fn parse_assign(&self, node: Node) -> Assign {
        // assign: commaSep1(choice(var_identifier, field_target)) "=" commaSep1(expression)
        // Named children are all targets (var_identifier | field_target) then all
        // expressions. We split at the first child that is neither.
        let mut cursor = node.walk();
        let named: Vec<Node> = node.named_children(&mut cursor).collect();
        let split = named
            .iter()
            .position(|n| n.kind() != "var_identifier" && n.kind() != "field_target")
            .unwrap_or(named.len());
        let targets = named[..split]
            .iter()
            .map(|n| self.parse_assign_target(*n))
            .collect();
        let values = named[split..]
            .iter()
            .map(|n| { let u = self.unwrap_expr_node(*n); self.parse_expression(u) })
            .collect();
        Assign { targets, values }
    }

    fn parse_assign_target(&self, node: Node) -> AssignTarget {
        match node.kind() {
            "field_target" => {
                // field_target: object: primary_expression "." member: fn_identifier
                let object_node = node.child_by_field_name("object").expect("field_target has an object");
                let member = node
                    .child_by_field_name("member")
                    .map(|n| self.text(n))
                    .unwrap_or_default();
                let object = self.parse_primary_expression(self.unwrap_expr_node(object_node));
                AssignTarget::Field(Box::new(object), member)
            }
            _ => AssignTarget::Var(self.text(node)),
        }
    }
```

- [ ] **Step 3: Build the workspace**

Run: `cargo build --workspace 2>&1 | tail -60`
Expected: `plum-core` builds. `plum-checker` and `plum-wasm-codegen` fail to build with errors about `a.targets` no longer being `Vec<String>` (e.g. `expected String, found AssignTarget` / no method `.clone()` producing a `String`) — this is expected; Tasks 3 and 4 fix those crates. Confirm the *only* new errors are in `plum-checker/src/lib.rs`, `plum-checker/src/monomorphize.rs`, and `plum-wasm-codegen/src/lib.rs`.

- [ ] **Step 4: Commit**

```bash
git add plum-core/src/ast.rs plum-core/src/parser.rs
git commit -m "feat(plum-core): parse obj.field assignment targets into AssignTarget::Field"
```

---

### Task 3: Checker — type-check field assignment targets

**Files:**
- Modify: `plum-checker/src/lib.rs` (`check_stmt`'s `Stmt::Assign` arm, ~line 246)
- Modify: `plum-checker/src/monomorphize.rs` (the `Stmt::Assign` arm at ~line 380 — see Step 1 below for what it needs)
- Test: `plum-checker/tests/checker_tests.rs`

**Interfaces:**
- Consumes: `ast::AssignTarget::{Var, Field}` from Task 2; `plum_checker::{infer_expr, unify, CheckCtx, ClassEnv}` (already defined in `plum-checker/src/lib.rs`).
- Produces: `check_stmt` correctly type-checks both target kinds; no new public functions.

- [ ] **Step 1: Fix `monomorphize.rs`'s `Stmt::Assign` arm**

`plum-checker/src/monomorphize.rs`'s `rewrite_stmt` (~line 378-386) currently reads:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter().zip(a.values.iter_mut()) {
                    self.rewrite_expr(value, env)?;
                    let ty = self.infer(value, env);
                    env.insert(target.clone(), TypeScheme::mono(ty));
                }
            }
```

`rewrite_expr` mutably rewrites generic-call mangling (e.g. `List(Int)` specialization) inside an expression, and `target.clone()` is used as the new binding's env key — both assume `target: &String`. Replace with:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter_mut().zip(a.values.iter_mut()) {
                    self.rewrite_expr(value, env)?;
                    let ty = self.infer(value, env);
                    match target {
                        ast::AssignTarget::Var(name) => {
                            env.insert(name.clone(), TypeScheme::mono(ty));
                        }
                        ast::AssignTarget::Field(object, _) => {
                            self.rewrite_expr(object, env)?;
                        }
                    }
                }
            }
```

(`a.targets.iter_mut()` instead of `.iter()`, since `AssignTarget::Field`'s boxed object expression needs the same mutable generic-mangling rewrite as any other expression — a plain `Var` target has no expression to rewrite, so its arm ignores the `&mut` and just reads the name.)

- [ ] **Step 2: Write the failing checker tests**

Add to `plum-checker/tests/checker_tests.rs`:

```rust
#[test]
fn field_assignment_target_with_matching_type_passes() {
    let src = "\
type Cat =
  name: Str
  age: Int

haveBirthday<Cat>() =
  self.age = self.age + 1
";
    let source = parse(src);
    assert!(check_source(&source).is_ok(), "expected Ok");
}

#[test]
fn field_assignment_target_with_mismatched_type_is_error() {
    let src = "\
type Cat =
  name: Str
  age: Int

breakCat<Cat>() =
  self.age = \"oops\"
";
    let source = parse(src);
    let result = check_source(&source);
    assert!(result.is_err());
}

#[test]
fn field_assignment_target_unknown_field_is_error() {
    let src = "\
type Cat =
  name: Str
  age: Int

breakCat<Cat>() =
  self.nope = 1
";
    let source = parse(src);
    let result = check_source(&source);
    assert!(result.is_err());
}
```

- [ ] **Step 3: Run the tests to verify they fail (or fail to compile)**

Run: `cargo test -p plum-checker field_assignment 2>&1 | tail -60`
Expected: compile error (the crate doesn't build yet from Task 2's fallout) or, once you provisionally stub `check_stmt`'s new arm just enough to compile, a test failure because field targets aren't actually validated yet.

- [ ] **Step 4: Fix `check_stmt`'s `Stmt::Assign` arm**

In `plum-checker/src/lib.rs`, replace the arm (~line 246):

```rust
        ast::Stmt::Assign(a) => {
            for (target, value) in a.targets.iter().zip(a.values.iter()) {
                match target {
                    ast::AssignTarget::Var(name) => {
                        match infer_expr(value, env, ctx) {
                            Ok(t) => { env.insert(name.clone(), TypeScheme::mono(t)); }
                            Err(msg) => errors.push(CheckError { message: format!("fn '{}': assign '{}': {}", fn_name, name, msg) }),
                        }
                    }
                    ast::AssignTarget::Field(object, field_name) => {
                        let label = format!("{}.{}", describe_target_object(object), field_name);
                        match (infer_expr(object, env, ctx), infer_expr(value, env, ctx)) {
                            (Ok(PlumType::TNamed(class_name)), Ok(value_ty)) => {
                                match ctx.classes.get(&class_name).and_then(|fields| {
                                    fields.iter().find(|(n, _)| n == field_name).map(|(_, ty)| ty.clone())
                                }) {
                                    Some(field_ty) => {
                                        if let Err(msg) = unify(&field_ty, &value_ty) {
                                            errors.push(CheckError { message: format!("fn '{}': assign '{}': {}", fn_name, label, msg) });
                                        }
                                    }
                                    None => errors.push(CheckError { message: format!("fn '{}': assign '{}': no field '{}' on class '{}'", fn_name, label, field_name, class_name) }),
                                }
                            }
                            (Ok(other), Ok(_)) => errors.push(CheckError { message: format!("fn '{}': assign '{}': cannot access field on non-class type {}", fn_name, label, other) }),
                            (Err(msg), _) => errors.push(CheckError { message: format!("fn '{}': assign '{}': {}", fn_name, label, msg) }),
                            (_, Err(msg)) => errors.push(CheckError { message: format!("fn '{}': assign '{}': {}", fn_name, label, msg) }),
                        }
                    }
                }
            }
        }
```

Add this small helper near `check_stmt` (used only for the error-message label above — it does not need to handle every `Expr` variant, only the ones that can appear as a `field_target`'s object per the grammar: `self`, a variable, or a nested attribute):

```rust
fn describe_target_object(expr: &ast::Expr) -> String {
    match expr {
        ast::Expr::Self_ => "self".to_string(),
        ast::Expr::Var(n) => n.clone(),
        ast::Expr::Attribute(a) => {
            if let ast::AttrKind::Field(f) = &a.attr {
                format!("{}.{}", describe_target_object(&a.object), f)
            } else {
                "<expr>".to_string()
            }
        }
        _ => "<expr>".to_string(),
    }
}
```

- [ ] **Step 5: Run the new tests**

Run: `cargo test -p plum-checker field_assignment 2>&1 | tail -40`
Expected: PASS (3 tests).

- [ ] **Step 6: Run the full checker test suite**

Run: `cargo test -p plum-checker 2>&1 | tail -60`
Expected: all tests PASS (pre-existing tests unaffected).

- [ ] **Step 7: Commit**

```bash
git add plum-checker/src/lib.rs plum-checker/src/monomorphize.rs plum-checker/tests/checker_tests.rs
git commit -m "feat(plum-checker): type-check obj.field assignment targets"
```

---

### Task 4: Codegen — compile field assignment targets

**Files:**
- Modify: `plum-wasm-codegen/src/lib.rs` — five `Stmt::Assign` sites:
  - `ClosureWalker::walk_stmt` (~line 940)
  - `fv_collect_bound_block` (~line 1336)
  - `fv_collect_refs_block` (~line 1392)
  - `Collector::walk_stmt` (~line 1573)
  - `compile_stmt` (~line 1982, the emission pass)
- Test: `plum-wasm-codegen/tests/codegen_tests.rs`

**Interfaces:**
- Consumes: `ast::AssignTarget::{Var, Field}`; the existing field-offset lookup pattern already used at `Expr::Attribute`/`AttrKind::Field` (~line 2772-2796) and class-literal field init (~line 2760-2768) — reuse it verbatim, don't invent new offset math.
- Produces: `compile_stmt` correctly emits a field store for `AssignTarget::Field`; no new public functions.

- [ ] **Step 1: Write the failing codegen tests**

Add to `plum-wasm-codegen/tests/codegen_tests.rs`:

```rust
#[test]
fn field_assignment_target_runs_correctly() {
    let src = "\
type Counter =
  value: Int

bump<Counter>() =
  self.value = self.value + 1

main() -> Int =
  c = Counter(value: 41)
  c.bump()
  c.value
";
    let source = parse(src);
    let bytes = compile_source(&source).expect("compile failed");
    assert_eq!(run_main(&bytes), 42);
}

#[test]
fn chained_field_assignment_target_runs_correctly() {
    let src = "\
type Inner =
  value: Int

type Outer =
  inner: Inner

bump<Outer>() =
  self.inner.value = self.inner.value + 1

main() -> Int =
  o = Outer(inner: Inner(value: 9))
  o.bump()
  o.inner.value
";
    let source = parse(src);
    let bytes = compile_source(&source).expect("compile failed");
    assert_eq!(run_main(&bytes), 10);
}

#[test]
fn mixed_multi_assign_with_field_target_runs_correctly() {
    let src = "\
type Counter =
  value: Int

main() -> Int =
  c = Counter(value: 5)
  a, c.value = 100, 7
  a + c.value
";
    let source = parse(src);
    let bytes = compile_source(&source).expect("compile failed");
    assert_eq!(run_main(&bytes), 107);
}
```

- [ ] **Step 2: Run the tests to verify they fail**

Run: `cargo test -p plum-wasm-codegen field_assignment chained_field mixed_multi_assign 2>&1 | tail -60`
Expected: compile error (crate doesn't build yet per Task 2's fallout).

- [ ] **Step 3: Fix `ClosureWalker::walk_stmt`**

In `plum-wasm-codegen/src/lib.rs` (~line 940), replace:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter().zip(a.values.iter()) {
                    self.walk_expr(value, None);
                    let ty = plum_checker::infer_expr(value, &self.env, &self.cctx).unwrap_or(PlumType::TInt);
                    self.env.insert(target.clone(), TypeScheme::mono(ty));
                    self.locals.insert(target.clone());
                }
            }
```

with:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter().zip(a.values.iter()) {
                    self.walk_expr(value, None);
                    match target {
                        ast::AssignTarget::Var(name) => {
                            let ty = plum_checker::infer_expr(value, &self.env, &self.cctx).unwrap_or(PlumType::TInt);
                            self.env.insert(name.clone(), TypeScheme::mono(ty));
                            self.locals.insert(name.clone());
                        }
                        ast::AssignTarget::Field(object, _) => {
                            self.walk_expr(object, None);
                        }
                    }
                }
            }
```

- [ ] **Step 4: Fix `fv_collect_bound_block`**

(~line 1336), replace:

```rust
            ast::Stmt::Assign(a) => {
                for t in &a.targets {
                    bound.insert(t.clone());
                }
            }
```

with:

```rust
            ast::Stmt::Assign(a) => {
                for t in &a.targets {
                    if let ast::AssignTarget::Var(name) = t {
                        bound.insert(name.clone());
                    }
                }
            }
```

(A `Field` target introduces no new bound name — the object expression's own variable references are handled by `fv_collect_refs_block` in Step 5, which runs as a separate pass over the same block.)

- [ ] **Step 5: Fix `fv_collect_refs_block`**

(~line 1392), replace:

```rust
            ast::Stmt::Assign(a) => {
                for v in &a.values {
                    fv_collect_refs_expr(v, bound, seen, free, env, fn_decls);
                }
            }
```

with:

```rust
            ast::Stmt::Assign(a) => {
                for v in &a.values {
                    fv_collect_refs_expr(v, bound, seen, free, env, fn_decls);
                }
                for t in &a.targets {
                    if let ast::AssignTarget::Field(object, _) = t {
                        fv_collect_refs_expr(object, bound, seen, free, env, fn_decls);
                    }
                }
            }
```

- [ ] **Step 6: Fix `Collector::walk_stmt`**

(~line 1573), replace:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter().zip(a.values.iter()) {
                    self.walk_expr(value);
                    let ty = if matches!(value, ast::Expr::Closure(_)) {
                        // ... (existing comment) ...
                        PlumType::TFun(Vec::new(), Box::new(PlumType::TUnit))
                    } else {
                        plum_checker::infer_expr(value, &self.env, &self.cctx).unwrap_or(PlumType::TInt)
                    };
                    self.bind(target, ty);
                }
            }
```

with:

```rust
            ast::Stmt::Assign(a) => {
                for (target, value) in a.targets.iter().zip(a.values.iter()) {
                    self.walk_expr(value);
                    match target {
                        ast::AssignTarget::Var(name) => {
                            let ty = if matches!(value, ast::Expr::Closure(_)) {
                                // The checker's own closure inference (`infer_expr` on
                                // `Expr::Closure`) infers the return type by recursively
                                // inferring the body's tail expression with each param bound
                                // to a fresh, unconstrained `TVar` — e.g. a captured/param
                                // attribute access (`c.age`) on a `TVar`-typed object isn't a
                                // known class, so it errors out entirely, and this call site
                                // then silently defaults to `TInt` — the *wrong* wasm local
                                // width for what's actually always an `i32` pointer. All that
                                // actually matters here is the local's wasm width, and every
                                // closure value is an i32 pointer regardless of its
                                // parameter/return types, so skip inference entirely.
                                PlumType::TFun(Vec::new(), Box::new(PlumType::TUnit))
                            } else {
                                plum_checker::infer_expr(value, &self.env, &self.cctx).unwrap_or(PlumType::TInt)
                            };
                            self.bind(name, ty);
                        }
                        ast::AssignTarget::Field(object, _) => {
                            self.walk_expr(object);
                        }
                    }
                }
            }
```

(Keep the existing explanatory comment verbatim inside the `Var` arm — it's shown abbreviated above only for brevity in this plan.)

- [ ] **Step 7: Fix `compile_stmt` (the emission pass)**

(~line 1982), replace:

```rust
        ast::Stmt::Assign(a) => {
            for (target, value) in a.targets.iter().zip(a.values.iter()) {
                // See the matching comment in `Collector::walk_stmt`: ...
                let vty = if matches!(value, ast::Expr::Closure(_)) {
                    PlumType::TFun(Vec::new(), Box::new(PlumType::TUnit))
                } else {
                    infer_local_type(value, ctx)
                };
                compile_expr(value, body, ctx, state)?;
                let idx = ctx
                    .locals
                    .get(target)
                    .copied()
                    .ok_or_else(|| format!("undeclared local '{}'", target))?;
                Instruction::LocalSet(idx).encode(body);
                ctx.type_env.borrow_mut().insert(target.clone(), TypeScheme::mono(vty));
                if let ast::Expr::Closure(cl) = value {
                    let key = cl.as_ref() as *const ast::Closure as usize;
                    if let Some(info) = ctx.closures.get(&key) {
                        let mut sig_params = vec![ValType::I32];
                        sig_params.extend(info.param_vts.iter().copied());
                        ctx.closure_local_sigs.borrow_mut().insert(target.clone(), (sig_params, info.ret_vt));
                    }
                }
            }
        }
```

with:

```rust
        ast::Stmt::Assign(a) => {
            for (target, value) in a.targets.iter().zip(a.values.iter()) {
                match target {
                    ast::AssignTarget::Var(name) => {
                        // See the matching comment in `Collector::walk_stmt`: the checker's
                        // closure inference is unreliable (can error out entirely depending
                        // on the body), but every closure value is an i32 pointer regardless
                        // of its real signature, so don't bother inferring it at all here.
                        let vty = if matches!(value, ast::Expr::Closure(_)) {
                            PlumType::TFun(Vec::new(), Box::new(PlumType::TUnit))
                        } else {
                            infer_local_type(value, ctx)
                        };
                        compile_expr(value, body, ctx, state)?;
                        let idx = ctx
                            .locals
                            .get(name)
                            .copied()
                            .ok_or_else(|| format!("undeclared local '{}'", name))?;
                        Instruction::LocalSet(idx).encode(body);
                        ctx.type_env.borrow_mut().insert(name.clone(), TypeScheme::mono(vty));
                        if let ast::Expr::Closure(cl) = value {
                            let key = cl.as_ref() as *const ast::Closure as usize;
                            if let Some(info) = ctx.closures.get(&key) {
                                let mut sig_params = vec![ValType::I32];
                                sig_params.extend(info.param_vts.iter().copied());
                                ctx.closure_local_sigs.borrow_mut().insert(name.clone(), (sig_params, info.ret_vt));
                            }
                        }
                    }
                    ast::AssignTarget::Field(object, field_name) => {
                        let obj_ty = infer_local_type(object, ctx);
                        let class_name = match &obj_ty {
                            PlumType::TNamed(n) => n.clone(),
                            other => return Err(format!("codegen: cannot assign field '{}' on non-class type {}", field_name, other)),
                        };
                        let fields = ctx
                            .classes
                            .get(&class_name)
                            .ok_or_else(|| format!("codegen: unknown class '{}'", class_name))?;
                        let (field_idx, field_ty) = fields
                            .iter()
                            .position(|(n, _)| n == field_name)
                            .map(|i| (i, fields[i].1.clone()))
                            .ok_or_else(|| format!("codegen: no field '{}' on class '{}'", field_name, class_name))?;
                        compile_expr(object, body, ctx, state)?;
                        compile_expr(value, body, ctx, state)?;
                        let offset = (field_idx as u64) * 8;
                        match plum_type_to_valtype(&field_ty) {
                            ValType::I64 => Instruction::I64Store(MemArg { offset, align: 3, memory_index: 0 }).encode(body),
                            ValType::F64 => Instruction::F64Store(MemArg { offset, align: 3, memory_index: 0 }).encode(body),
                            _ => Instruction::I32Store(MemArg { offset, align: 2, memory_index: 0 }).encode(body),
                        };
                    }
                }
            }
        }
```

- [ ] **Step 8: Build and run the new tests**

Run: `cargo test -p plum-wasm-codegen field_assignment chained_field mixed_multi_assign 2>&1 | tail -60`
Expected: PASS (3 tests). If `field_assignment_target_runs_correctly` traps or returns the wrong value, check the field store pushes the *object pointer* before the *value* (wasm stack order for a store is `[address, value]``I32Store`/`I64Store`/`F64Store` pop value then address, so `compile_expr(object)` must run first, matching the existing class-literal field-init code this was modeled on).

- [ ] **Step 9: Run the full workspace test suite**

Run: `cargo test --workspace 2>&1 | tail -100`
Expected: all tests PASS, including every pre-existing `plum-wasm-codegen`, `plum-checker`, and `tree-sitter-plum` test.

- [ ] **Step 10: 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 obj.field = value assignment targets"
```

---

### Task 5: README — close the gap

**Files:**
- Modify: `README.md` (the "Known gaps" section, ~line 345-350)

**Interfaces:**
- Consumes: nothing.
- Produces: nothing (docs only).

- [ ] **Step 1: Update the Known gaps bullet**

In `README.md`, the current bullet reads:

```
- `libs/std`'s actual `List`/`Map` still don't fully compile — mutating a field or attribute (`self.head = ...`) isn't a supported assignment target yet (only a plain local variable is), and there's no cross-file import resolution yet either, so a file that references a type/enum declared in a different `libs/std` file won't type-check standalone
```

Replace it with:

```
- `libs/std`'s actual `List`/`Map` still don't fully compile — there's no cross-file import resolution yet, so a file that references a type/enum declared in a different `libs/std` file won't type-check standalone; separately, `List`'s methods beyond `get`/`length` are still `todo` pending variadic-parameter support (`values: ...a`), a distinct follow-up gap
```

Also check whether any earlier section of the README (e.g. wherever assignment / `self.field` is first documented, likely near "Naming conventions" or a "Statements"/"Classes" section) currently says a field/attribute can't be an assignment target, and update it to state that `obj.field = value` is now supported. Search first:

Run: `grep -n "assignment target\|self\\.field\|field or attribute" README.md`

- [ ] **Step 2: Commit**

```bash
git add README.md
git commit -m "docs: field/attribute assignment is no longer a known gap"
```