#!/usr/bin/env python3
"""Measure R4(b): the owned-payload double move in a positional container.

R4 makes a guarded cell in a `row`/`cells` body appear as an adjacent pair over
the same predicate, `when` then `unless`. R4(b) observes that such a pair
expands to two INDEPENDENT `if` statements rather than an `if`/`else`, so a pair
whose arms both consume the same owned value moves it twice and the generated
code does not compile. R9 is what makes that inevitable: a hole is one eager
evaluation whose owned result lands in a plain field.

The defect is real. Reproduced 2026-09-03 as E0382 against quasi-router, in a
throwaway crate holding exactly what the macro would emit:

    fn moved_twice(label: String, compact: bool) -> Cells {
        let mut cells = Vec::new();
        if compact { cells.push(Cell::new(label)); }
        if !compact { cells.push(Cell::new(label)); }   // E0382
        Cells::new(cells)
    }

What was unmeasured was its INCIDENCE, and the defect lives in code that does not
exist yet, so what is measurable is the antecedent: a positional-container shape
holding a two-armed conditional in emission position whose arms share a binding
that is not Copy. Every one of those is a site that, re-authored under R4's
pairing rule, becomes two independent `if`s.

Positional containers are the shapes R4 governs: Row, Cells, Cell, Column and
their plurals. A Slot and a Run accrete, so a lone guarded emission is safe there
and R4(b) cannot arise.

The answer is ZERO, with ten near-misses that each dissolve for a different
reason. Six are `match` arms, which R7 makes safe. Four are `if`/`else`: two
name the carried container or a Vec accumulator, which rebind rather than move,
and two are `Act::disabled`, where R5 guards the attribute and the emission stays
single. Full reading: wiki `quasi-declare-form` section 11.

    python3 scripts/r4b-incidence.py

Reuses population.py's blanking, `#[cfg(test)]` stripping and shape discovery, so
the denominator is the ratified 514. Re-run it after any change to the three
shape trees: zero is a fact about today's code, not a property of the form.
"""

from __future__ import annotations

import importlib.util
import re

from pathlib import Path

ROOT = Path.home() / "Code"
POP = ROOT / "quasi" / "scripts" / "population.py"

spec = importlib.util.spec_from_file_location("population", POP)
pop = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pop)

# The containers R4 governs. A Slot and a Run accrete and are out of scope.
POSITIONAL = {"Row", "Cells", "Cell", "Column"}

# Types whose values move. Deliberately conservative: a `&`-prefixed type, a
# primitive and a Copy vocabulary enum are excluded, so a hit is a real move
# candidate rather than a maybe.
COPY_ISH = re.compile(
    r"^(?:&|bool$|char$|u8$|u16$|u32$|u64$|usize$|i8$|i16$|i32$|i64$|isize$|f32$|f64$)"
)


def head(ret: str) -> str:
    """The vocabulary type inside Vec/Option/Result wrappers."""
    t = pop.head_type(ret)
    return t or ""


def body_of(src: str, line: int) -> str:
    """The blanked body of the fn starting at `line` (1-indexed)."""
    off = 0
    for _ in range(line - 1):
        off = src.index("\n", off) + 1
    brace = src.index("{", off)
    end = pop.match_brace(src, brace)
    return src[brace:end] if end > 0 else ""


def sig_at(src: str, line: int) -> str:
    """The signature text of the fn starting at `line`, up to its body brace."""
    off = 0
    for _ in range(line - 1):
        off = src.index("\n", off) + 1
    brace = src.index("{", off)
    return src[off:brace]


def owned_params(sig: str) -> set[str]:
    """Parameter names whose type is not a reference and not a primitive."""
    out = set()
    inner = sig[sig.index("(") + 1 : sig.rindex(")")] if "(" in sig else ""
    for part in pop.split_top(inner):
        part = part.strip()
        if not part or ":" not in part or part.startswith("&self") or part == "self":
            continue
        name, ty = part.split(":", 1)
        name, ty = name.strip(), ty.strip()
        if not name.isidentifier():
            continue
        if not COPY_ISH.match(ty):
            out.add(name)
    return out


def conditionals(body: str) -> list[tuple[str, str, str]]:
    """Every `if C { A } else { B }` in the body, as (cond, arm_a, arm_b)."""
    found = []
    for m in re.finditer(r"\bif\b", body):
        i = m.end()
        b1 = body.find("{", i)
        if b1 < 0:
            continue
        cond = body[i:b1].strip()
        if not cond or "{" in cond:
            continue
        e1 = pop.match_brace(body, b1)
        if e1 < 0:
            continue
        rest = body[e1:]
        me = re.match(r"\s*else\s*\{", rest)
        if not me:
            continue
        b2 = e1 + me.end() - 1
        e2 = pop.match_brace(body, b2)
        if e2 < 0:
            continue
        found.append((cond, body[b1:e1], body[b2:e2]))
    return found


def match_arms(body: str) -> list[tuple[str, list[str]]]:
    """Every `match S { .. }` in the body, as (scrutinee, [arm bodies]).

    R7 expands `given` to a real `match`, where arms are exclusive and a moved
    value is fine, so these are the SAFE form. Counted to show the pair rule is
    the only thing that produces the defect.
    """
    found = []
    for m in re.finditer(r"\bmatch\b", body):
        b = body.find("{", m.end())
        if b < 0:
            continue
        scrut = body[m.end() : b].strip()
        if not scrut or "{" in scrut:
            continue
        e = pop.match_brace(body, b)
        if e < 0:
            continue
        inner = body[b + 1 : e - 1]
        arms, depth, start = [], 0, 0
        for i, c in enumerate(inner):
            if c in "{([":
                depth += 1
            elif c in "})]":
                depth -= 1
            elif c == "," and depth == 0:
                arms.append(inner[start:i])
                start = i + 1
        arms.append(inner[start:])
        found.append((scrut, [a for a in arms if a.strip()]))
    return found


def adjacent_ifs(body: str) -> list[tuple[str, str, str]]:
    """A bare `if C {A}` immediately followed by `if !C {B}`, already split.

    This is what R4's pairing rule produces, written by hand. If any exist in
    the tree they are the defect's antecedent without any re-authoring at all.
    """
    found = []
    spans = []
    for m in re.finditer(r"\bif\b", body):
        b = body.find("{", m.end())
        if b < 0:
            continue
        cond = body[m.end() : b].strip()
        if not cond or "{" in cond:
            continue
        e = pop.match_brace(body, b)
        if e < 0:
            continue
        spans.append((cond, b, e))
    for (c1, _b1, e1), (c2, b2, e2) in zip(spans, spans[1:]):
        gap = body[e1:b2]
        if re.fullmatch(r"\s*(?:if\s*)?", gap.replace(c2, "", 1)) is None:
            continue
        norm = lambda c: c.strip().lstrip("!").strip()
        if norm(c1) == norm(c2) and (c1.strip().startswith("!") != c2.strip().startswith("!")):
            found.append((norm(c1), body[_b1:e1], body[b2:e2]))
    return found


IDENT = re.compile(r"\b([a-z_][a-z0-9_]*)\b")


def main() -> int:
    shapes = []
    for rel in pop.SHAPE_DIRS:
        d = ROOT / rel
        for f in sorted(d.rglob("*.rs")):
            parts = f.relative_to(ROOT).parts
            if f.name in ("tests.rs", "parity.rs") or "tests" in parts:
                continue
            raw = f.read_text(encoding="utf-8", errors="replace")
            blanked = pop.strip_cfg_test(pop.blank_noncode(raw))
            for h in pop.shapes_in(f):
                h["file"] = str(Path(h["file"]).relative_to(ROOT))
                h["_blanked"] = blanked
                shapes.append(h)

    total = len(shapes)
    positional = [s for s in shapes if head(s["returns"]) in POSITIONAL]

    hits = []
    for s in positional:
        body = body_of(s["_blanked"], s["line"])
        if not body:
            continue
        owned = owned_params(sig_at(s["_blanked"], s["line"]))
        # A `let` of a non-borrowed, non-literal source is an owned local too.
        for m in re.finditer(r"\blet\s+(?:mut\s+)?([a-z_][a-z0-9_]*)\s*=\s*([^;]*);", body):
            if not m.group(2).lstrip().startswith("&"):
                owned.add(m.group(1))
        pairs = [("if/else", c, a, b) for c, a, b in conditionals(body)]
        pairs += [("adjacent-if", c, a, b) for c, a, b in adjacent_ifs(body)]
        for scrut, arms in match_arms(body):
            for i in range(len(arms)):
                for j in range(i + 1, len(arms)):
                    pairs.append(("match", scrut, arms[i], arms[j]))
        for kind, cond, a, b in pairs:
            ia = set(IDENT.findall(a))
            ib = set(IDENT.findall(b))
            shared = (ia & ib) & owned
            if shared:
                hits.append({
                    "kind": kind,
                    "file": s["file"], "line": s["line"], "fn": s["fn"],
                    "returns": s["returns"], "cond": " ".join(cond.split())[:70],
                    "shared": sorted(shared),
                })

    print(f"population                     {total}")
    print(f"positional-container shapes    {len(positional)}  (Row/Cells/Cell/Column and plurals)")
    print(f"  with a two-armed conditional sharing an owned binding: {len(hits)}")
    print()
    for h in hits:
        print(f"  {h['file']}:{h['line']} {h['fn']} -> {h['returns']}")
        print(f"      [{h['kind']}] {h['cond']}")
        print(f"      shared owned: {', '.join(h['shared'])}")
    if not hits:
        print("  none")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
