|
44 | 44 | # --- acquire catalog: how each React acquire maps onto a core resource kind ----- |
45 | 45 | # |
46 | 46 | # Each acquire has (a) a regex that spots the acquire call, (b) the OwnIR `resource` |
47 | | -# discriminator the core understands, (c) the cleanup verb that releases it, and |
48 | | -# (d) the EFF id + tag for provenance. The `resource` value is the *only* field the |
49 | | -# core acts on; `eff`/`profile` ride along as additive provenance the core ignores. |
| 47 | +# discriminator the core understands, and (c) the EFF id + tag for provenance. The |
| 48 | +# `resource` value is the *only* field the core acts on; `eff`/`profile` ride along |
| 49 | +# as additive provenance the core ignores. Whether a *specific* acquire is released |
| 50 | +# is decided per-resource by `_is_released` (matched to its own token/handler — not |
| 51 | +# a kind-level "is there any cleanup verb", which would mark every same-kind acquire |
| 52 | +# released as soon as one is cleaned up). |
50 | 53 | @dataclass(frozen=True) |
51 | 54 | class Acquire: |
52 | 55 | name: str # human label, e.g. "setInterval" |
53 | 56 | pattern: re.Pattern # spots the acquire call |
54 | 57 | resource: str # OwnIR resource kind: timer / subscribe / subscription |
55 | | - release: re.Pattern # the cleanup verb that releases it |
56 | 58 | eff: str # Own.React catalog id |
57 | 59 |
|
58 | 60 | ACQUIRES: list[Acquire] = [ |
59 | | - Acquire("setInterval", re.compile(r"\bsetInterval\s*\("), |
60 | | - "timer", re.compile(r"\bclearInterval\s*\("), "EFF004"), |
61 | | - Acquire("setTimeout", re.compile(r"\bsetTimeout\s*\("), |
62 | | - "timer", re.compile(r"\bclearTimeout\s*\("), "EFF004"), |
63 | | - Acquire(".subscribe", re.compile(r"\.subscribe\s*\("), |
64 | | - "subscribe", re.compile(r"\.unsubscribe\s*\(|\.remove\s*\("), "EFF003"), |
| 61 | + Acquire("setInterval", re.compile(r"\bsetInterval\s*\("), "timer", "EFF004"), |
| 62 | + Acquire("setTimeout", re.compile(r"\bsetTimeout\s*\("), "timer", "EFF004"), |
| 63 | + Acquire(".subscribe", re.compile(r"\.subscribe\s*\("), "subscribe", "EFF003"), |
65 | 64 | Acquire("addEventListener", re.compile(r"\.addEventListener\s*\("), |
66 | | - "subscription", re.compile(r"\.removeEventListener\s*\("), "EFF003"), |
| 65 | + "subscription", "EFF003"), |
67 | 66 | ] |
68 | 67 |
|
| 68 | + |
| 69 | +def _lhs_token(setup: str, pos: int) -> str | None: |
| 70 | + """The variable an acquire's result is bound to, e.g. `id` in |
| 71 | + `const id = setInterval(...)` or `sub` in `const sub = obs.subscribe(...)`. |
| 72 | + Scoped to the current statement so an earlier `const` does not bleed in.""" |
| 73 | + head = re.split(r"[;\n{}]", setup[:pos])[-1] |
| 74 | + m = re.search(r"(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=", head) |
| 75 | + return m.group(1) if m else None |
| 76 | + |
| 77 | + |
| 78 | +def _is_released(acq: Acquire, setup: str, pos: int, cleanup: str) -> bool: |
| 79 | + """Whether THIS acquire (at `pos` in `setup`) is released by the effect's cleanup |
| 80 | + — matched to its own handle, so two `setInterval`s with one `clearInterval` leave |
| 81 | + the other a leak. A resource with no capturable handle (a bare `setInterval(...)` |
| 82 | + or an ignored `.subscribe(...)` result) can never be released → False.""" |
| 83 | + if acq.resource == "timer": |
| 84 | + tok = _lhs_token(setup, pos) |
| 85 | + return bool(tok and re.search( |
| 86 | + rf"\bclear(?:Interval|Timeout)\s*\(\s*{re.escape(tok)}\b", cleanup)) |
| 87 | + if acq.resource == "subscribe": |
| 88 | + tok = _lhs_token(setup, pos) |
| 89 | + return bool(tok and re.search( |
| 90 | + rf"\b{re.escape(tok)}\s*\.\s*(?:unsubscribe|remove)\s*\(", cleanup)) |
| 91 | + if acq.resource == "subscription": # addEventListener(event, handler) |
| 92 | + hm = re.search(r"addEventListener\s*\(\s*[^,]+,\s*([A-Za-z_$][\w$.]*)", |
| 93 | + setup[pos:]) |
| 94 | + handler = hm.group(1) if hm else None |
| 95 | + return bool(handler and re.search( |
| 96 | + rf"removeEventListener\s*\(\s*[^,]+,\s*{re.escape(handler)}\b", cleanup)) |
| 97 | + return False |
| 98 | + |
69 | 99 | # A React component is a function whose name is Capitalized (the JSX convention). |
70 | 100 | _COMPONENT = re.compile( |
71 | | - r"(?:function\s+([A-Z]\w*)\s*\(|" |
| 101 | + r"(?:function\s+([A-Z]\w*)\b|" |
72 | 102 | r"(?:const|let|var)\s+([A-Z]\w*)\s*=\s*(?:\([^)]*\)|\w+)\s*(?::[^=]+)?=>)" |
73 | 103 | ) |
| 104 | + |
| 105 | + |
| 106 | +def _body_brace(text: str, start: int) -> int: |
| 107 | + """Index of a component's body `{`, scanning from `start` (just past the name or |
| 108 | + `=>`). Skips the parameter list by paren depth, so a destructured param |
| 109 | + `({ x }: { x: T })` is not mistaken for the body block.""" |
| 110 | + depth = 0 |
| 111 | + for i in range(start, len(text)): |
| 112 | + c = text[i] |
| 113 | + if c == "(": |
| 114 | + depth += 1 |
| 115 | + elif c == ")": |
| 116 | + depth -= 1 |
| 117 | + elif c == "{" and depth == 0: |
| 118 | + return i |
| 119 | + return -1 |
74 | 120 | _USE_EFFECT = re.compile(r"\buseEffect\s*\(") |
75 | 121 |
|
76 | 122 |
|
@@ -169,35 +215,77 @@ def _component_at(text: str, idx: int) -> str: |
169 | 215 | return name or "AnonymousComponent" |
170 | 216 |
|
171 | 217 |
|
| 218 | +def _expr_end(text: str, i: int) -> int: |
| 219 | + """End index of an expression body — the first top-level `,` or `)` from `i` |
| 220 | + (so the `, [deps])` tail and the `useEffect(` close are not swallowed).""" |
| 221 | + depth = 0 |
| 222 | + while i < len(text): |
| 223 | + c = text[i] |
| 224 | + if c in "([{": |
| 225 | + depth += 1 |
| 226 | + elif c in ")]}": |
| 227 | + if depth == 0: |
| 228 | + return i |
| 229 | + depth -= 1 |
| 230 | + elif c == "," and depth == 0: |
| 231 | + return i |
| 232 | + i += 1 |
| 233 | + return i |
| 234 | + |
| 235 | + |
| 236 | +def _effect_callback(text: str, after_open: int) -> tuple[str, int, list[str] | None, int]: |
| 237 | + """Parse `useEffect(<cb>, [deps])` from just past the `(`. Returns |
| 238 | + (body, body_start, deps, end). Handles BOTH a block `() => { ... }` and an |
| 239 | + expression `() => fetch(url)` callback — calling `_match_block` blindly on the |
| 240 | + latter would jump to an unrelated `{` or run off the end. `deps` is None when no |
| 241 | + dependency array is present; `body` includes the braces for a block callback.""" |
| 242 | + arrow = text.find("=>", after_open) |
| 243 | + i = (arrow + 2) if arrow != -1 else after_open |
| 244 | + while i < len(text) and text[i] in " \t\r\n": |
| 245 | + i += 1 |
| 246 | + if i < len(text) and text[i] == "{": |
| 247 | + end = _match_block(text, i) |
| 248 | + else: |
| 249 | + end = _expr_end(text, i) |
| 250 | + body = text[i:end] |
| 251 | + deps_m = re.search(r"\s*,\s*\[([^\]]*)\]", text[end:end + 200]) |
| 252 | + deps = ([d.strip() for d in deps_m.group(1).split(",") if d.strip()] |
| 253 | + if deps_m else None) |
| 254 | + return body, i, deps, end |
| 255 | + |
| 256 | + |
172 | 257 | def _split_cleanup(body: str) -> tuple[str, str]: |
173 | | - """Split an effect body into (setup, cleanup). Cleanup is the block of the |
174 | | - `return () => { ... }` the effect hands back to React; setup is the rest.""" |
175 | | - m = re.search(r"return\s*(?:\(\s*\)|\w+)\s*=>", body) |
176 | | - if not m: |
177 | | - return body, "" |
178 | | - brace = body.find("{", m.end()) |
179 | | - if brace == -1: |
180 | | - # `return () => clearInterval(id)` — single-expression cleanup, no block. |
181 | | - nl = body.find("\n", m.end()) |
182 | | - tail = body[m.end(): nl if nl != -1 else len(body)] |
183 | | - return body[: m.start()], tail |
184 | | - end = _match_block(body, brace) |
185 | | - return body[: m.start()] + body[end:], body[brace:end] |
| 258 | + """Split an effect block body into (setup, cleanup). Cleanup is the block of the |
| 259 | + effect's OWN top-level `return () => { ... }` — a `return ... =>` nested inside a |
| 260 | + callback (brace-depth > 1) is NOT the effect cleanup and must not suppress a |
| 261 | + leak. For an expression-bodied effect there is no cleanup.""" |
| 262 | + for m in re.finditer(r"return\s*(?:\(\s*\)|\w+)\s*=>", body): |
| 263 | + prefix = body[:m.start()] |
| 264 | + if prefix.count("{") - prefix.count("}") != 1: # 1 == the effect body's own brace |
| 265 | + continue |
| 266 | + brace = body.find("{", m.end()) |
| 267 | + if brace == -1: |
| 268 | + # `return () => clearInterval(id)` — single-expression cleanup, no block. |
| 269 | + nl = body.find("\n", m.end()) |
| 270 | + tail = body[m.end(): nl if nl != -1 else len(body)] |
| 271 | + return body[: m.start()], tail |
| 272 | + end = _match_block(body, brace) |
| 273 | + return body[: m.start()] + body[end:], body[brace:end] |
| 274 | + return body, "" |
186 | 275 |
|
187 | 276 |
|
188 | 277 | def extract(path: str) -> list[Component]: |
189 | 278 | text = _strip_comments(open(path, encoding="utf-8").read()) |
190 | 279 | comps: dict[str, Component] = {} |
191 | 280 | for eff in _USE_EFFECT.finditer(text): |
192 | | - end = _match_block(text, eff.end()) |
193 | | - body = text[eff.end():end] |
| 281 | + body, body_start, _deps, _end = _effect_callback(text, eff.end()) |
194 | 282 | setup, cleanup = _split_cleanup(body) |
195 | 283 | cname = _component_at(text, eff.start()) |
196 | 284 | comp = comps.setdefault(cname, Component(cname, path)) |
197 | 285 | for acq in ACQUIRES: |
198 | 286 | for hit in acq.pattern.finditer(setup): |
199 | | - line = text.count("\n", 0, eff.end() + hit.start()) + 1 |
200 | | - released = bool(acq.release.search(cleanup)) |
| 287 | + line = text.count("\n", 0, body_start + hit.start()) + 1 |
| 288 | + released = _is_released(acq, setup, hit.start(), cleanup) |
201 | 289 | # the acquire expression, trimmed to the call head for a readable tag |
202 | 290 | snippet = setup[hit.start():].splitlines()[0].strip().rstrip("{").strip() |
203 | 291 | comp.resources.append( |
@@ -272,27 +360,45 @@ def _classify_rhs(rhs: str) -> tuple[str, list[str]]: |
272 | 360 | return "unknown", [] |
273 | 361 |
|
274 | 362 |
|
| 363 | +def _render_bindings(text: str) -> dict[str, list[dict]]: |
| 364 | + """The render-scope binding table per component: only bindings declared DIRECTLY |
| 365 | + in the component body (brace-depth 1). A `const filters = {...}` inside a |
| 366 | + `useEffect` callback, an event handler, or any nested block is NOT render scope — |
| 367 | + it must not shadow the real outer dependency of the same name and mint a false |
| 368 | + EFF001. Excluding a render-level `if`/`try` binding only costs a missed finding |
| 369 | + (the dep reads as stable), never a false one — the safe direction.""" |
| 370 | + out: dict[str, list[dict]] = {} |
| 371 | + for cm in _COMPONENT.finditer(text): |
| 372 | + name = cm.group(1) or cm.group(2) |
| 373 | + brace = _body_brace(text, cm.end()) # skips a destructured param list |
| 374 | + if brace == -1: |
| 375 | + continue |
| 376 | + body_end = _match_block(text, brace) |
| 377 | + body = text[brace + 1:body_end] |
| 378 | + base = text.count("\n", 0, brace + 1) # 0-based line index of the body start |
| 379 | + binds: list[dict] = [] |
| 380 | + for m in _BINDING.finditer(body): |
| 381 | + prefix = body[:m.start()] |
| 382 | + if prefix.count("{") != prefix.count("}"): |
| 383 | + continue # inside a nested block -> not the component's render scope |
| 384 | + kind, refs = _classify_rhs(m.group(2)) |
| 385 | + binds.append({"name": m.group(1), "init": kind, "refs": refs, |
| 386 | + "line": base + prefix.count("\n") + 1}) |
| 387 | + out[name] = binds |
| 388 | + return out |
| 389 | + |
| 390 | + |
275 | 391 | def extract_effects(path: str) -> list[dict]: |
276 | 392 | """Extract the EFF001 stability facts: for each `useEffect`, its dependency list, |
277 | 393 | whether its body does network IO, and the render-scope binding table of the |
278 | 394 | component it lives in. The core's effects analysis turns these into a verdict.""" |
279 | 395 | text = _strip_comments(open(path, encoding="utf-8").read()) |
280 | | - # render-scope bindings, attributed to their enclosing component. |
281 | | - binds_by_comp: dict[str, list[dict]] = {} |
282 | | - for m in _BINDING.finditer(text): |
283 | | - kind, refs = _classify_rhs(m.group(2)) |
284 | | - binds_by_comp.setdefault(_component_at(text, m.start()), []).append({ |
285 | | - "name": m.group(1), "init": kind, "refs": refs, |
286 | | - "line": text.count("\n", 0, m.start()) + 1, |
287 | | - }) |
| 396 | + binds_by_comp = _render_bindings(text) |
288 | 397 | effects: list[dict] = [] |
289 | 398 | for eff in _USE_EFFECT.finditer(text): |
290 | | - end = _match_block(text, eff.end()) |
291 | | - body = text[eff.end():end] |
292 | | - deps_m = re.search(r",\s*\[([^\]]*)\]\s*\)", text[end - 1:end + 200]) |
293 | | - if not deps_m: # no dep array -> not an EFF001 candidate (by-design re-run cadence) |
| 399 | + body, _start, deps, _end = _effect_callback(text, eff.end()) |
| 400 | + if deps is None: # no dep array -> not an EFF001 candidate (by-design re-run cadence) |
294 | 401 | continue |
295 | | - deps = [d.strip() for d in deps_m.group(1).split(",") if d.strip()] |
296 | 402 | cname = _component_at(text, eff.start()) |
297 | 403 | effects.append({ |
298 | 404 | "component": cname, "file": path, |
|
0 commit comments