From 780f7d0071072bf47ba59b7212d4d2e26d2657e9 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Fri, 27 Nov 2026 23:46:24 -0500 Subject: [PATCH 01/13] docs: plan a checker-bound TypeScript symbol index Co-Authored-By: Claude Opus 5.5 --- docs/intent/checker-symbol-index/README.md | 160 +++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 docs/intent/checker-symbol-index/README.md diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md new file mode 100644 index 00000000..3d7987bd --- /dev/null +++ b/docs/intent/checker-symbol-index/README.md @@ -0,0 +1,160 @@ +# Checker-bound symbol index (plan) + +Status: proposed, not built. Retire this folder when the last milestone lands. + +## Problem + +The TypeScript symbol index (`server/app/services/symbols/typescript.py`) binds each name with tree-sitter and its own scope rules. #486 fixed three gaps after three Codex rounds and left five open. All five are binding questions that the TypeScript checker already answers: + +| #486 finding | Why tree-sitter misses it | Closed by this plan | +| --- | --- | --- | +| P1 `typescript.py:786`: `pick()`, a type named `then`, JSX type arguments | The parse loses the type position | Yes. The checker gives the meaning at the location | +| P1 `CodeModal.tsx:225`: Show references on a use of a split name opens the value | The client looks the name up by text | Yes. Lookup by source position (M3) | +| P2 `typescript_deps.py:399`: a barrel imports interface `T`, declares value `T`, exports `{ T }` | One target per export hop | Yes for refs and the Symbols view. The Imports graph keeps tree-sitter (see "Imports graph") | +| P2 `typescript.py:795`: forward reference to a block-local alias | Block-local types are not predeclared | Yes | +| P2 `typescript.py:79`: `export default function A` plus `export type A` | No visibility check per public name | Yes | + +The larger gain is member references. Today the index guesses a member's target from a declared type (`typed`) or a unique member name (`name`), and leaves the rest unresolved. Measured 2026-11-27 on this branch's base (`54bf3bba`); the snippet below the table recomputes it: + +| Repo | TS references | `exact` | `typed` | `name` | Unresolved members | +| --- | ---: | ---: | ---: | ---: | ---: | +| srcly | 40,261 | 32,132 | 7,728 | 401 | 40,529 | +| explorEDA | 49,069 | 42,468 | 6,263 | 338 | 9,986 | + +The unresolved count includes library members (`arr.map`), so it is an upper bound. The checker binds `props.store.bump()` to `Store.bump` where tree-sitter can not. `srcly refs` exists so an agent can find every caller before it deletes code. A member call through a parameter is the caller it misses most. + +```python +# Recompute (from server/): +from pathlib import Path; from collections import Counter +from app.services.symbols.index import build_symbol_index +ix = build_symbol_index(Path("")) +refs = [r for r in ix.references if ix.symbols[r.source].language == "ts"] +print(len(refs), Counter(r.resolution for r in refs), ix.unresolved_members) +``` + +## Design + +### Who owns what + +- **Tree-sitter keeps the declarations and the ids.** `file#Name`, `file#Class.member`, `file#Name@type` stay as #486 made them. The Imports graph, `at` links and saved URLs do not change. The engine never builds an id. +- **The checker owns binding.** For each identifier, it says which declaration TypeScript binds, or that nothing is bound. +- **The join key is `(file, line, name, meaning)`** for a declaration's name, where `meaning` is `value` or `type`. Both sides know all four. No column conversion is needed, so engine UTF-16 spans and tree-sitter bytes stay apart (`docs/dataflow-engine.md`, "Outcomes and positions"). `meaning` separates `A` from `A@type` when both sit on one line. + +This follows "derive one from the other": one naming rule (tree-sitter), one binding rule (checker). A key that matches no tree-sitter symbol is a counted mismatch, never a guessed id. + +### Engine op: `symbolRefs` + +Tier 1, on the primary Program. The steps follow AGENTS.md "To add an op". + +Params: `files` (optional; absent means every source file the Program owns under the root), `expectedGeneration`. + +Result per file: + +```ts +{ + file: string, + refs: Array<{ + span: Span, // the identifier, 1-based UTF-16, like every contract + kind: "call" | "instantiate" | "read" | "write" | "type" | "extends" | "implements", + source: DeclKey | null, // nearest enclosing named declaration; null = module code + target: DeclKey | null, + unbound: "any" | "unresolved-module" | "external" | "library" | null, + }>, +} +// DeclKey = { file, line, name, meaning: "value" | "type" } +``` + +How the op binds a reference: + +- It walks every `Identifier` and `PrivateIdentifier` that is not a declaration name. +- It calls `getSymbolAtLocation` and follows aliases to the declaration with `getAliasedSymbol`. That covers imports, re-exports, barrels and `import("…").T`. +- The checker already filters by meaning at the location. For a merged symbol (class plus interface), the op picks the declaration whose flags match the location, else the first one. Tree-sitter keeps those as one symbol, so either key matches. +- A target outside the root, or in `node_modules` or a `.d.ts`, is `external` and is dropped by Python, as today. + +`kind` comes from the parent node (call callee, `new`, assignment target, heritage clause, type node). It is the same syntax rule as `RefKind` today, now on the TypeScript AST. + +The op leaves out HTTP references. `fetch("/api/x")` matching stays in Python, which already does it per symbol. + +### Python merge + +`build_symbol_index` takes declarations from tree-sitter as today. When the checker is available, it uses the engine's refs instead of the tree-sitter refs for TS files: + +1. It maps each `DeclKey` to a tree-sitter symbol id. A miss on `target` drops the ref and adds to `mismatched_keys`. A miss on `source` attaches the ref to the module node. +2. A bound ref is `exact`. The `typed` and `name` resolutions do not happen for TS refs. An `unbound` ref stays out of the graph and is counted by reason in `SymbolIndexInfo`. +3. Each ref keeps its span (`line`, `column`, `end_column`, UTF-16). `Reference` gains `column` and `end_column`, `None` for tree-sitter refs. +4. `SymbolIndexInfo` gains `binder: "checker" | "tree-sitter"` and, for tree-sitter, the reason (`no-node`, `no-tsconfig`, `memory-limit`, `timeout`, …). The Symbols view and `srcly refs` print it, so an answer names its binder. + +Files that the Program does not own (outside every tsconfig) keep tree-sitter refs inside a checker index. They are counted as `outside_program` and named in the info. This is the only place the two binders mix, and it is per file, never per reference. + +### When the engine runs + +Invariant 1 says the base scan never waits. The symbol index is not the base scan: + +- `srcly refs` and `srcly symbols` start the engine, like `--dataflow`. They wait for it, and fall back with a printed reason. +- The Symbols view and Show references start it on first open. That adds them to invariant 1's explicit-use list. While the engine builds, the view shows "binding with the checker" and the tree-sitter answer greyed. It does not draw that answer as final. +- The cache key becomes `(source_signature, programHash)` in checker mode. The generation goes into the response, and a stale query is `stale`, as for every engine op. + +### Imports graph + +`build_ts_edges` stays tree-sitter. It is part of the base scan and must draw without Node. Its P2 (`typescript_deps.py:399`) stays open there. After M2, the proof script also compares the Imports graph's symbol edges with the checker index's cross-file refs, rolled up to top-level symbols. Disagreements become fixes in the tree-sitter export walk, or named limits. A checker-drawn Imports graph is out of scope until the engine is warm at scan time, which `docs/dataflow-engine.md` dropped on purpose. + +### Show references by position (client) + +`CodeModal`'s `onReferences` sends `{file, line, column}` (UTF-16, as the editor reports it) to a new `GET /api/symbols/at`. The server answers in this order: + +1. A ref whose span covers the position: its target. +2. A declaration whose name is at that line and name: that symbol. +3. Nothing: "No symbol bound here". It never falls back to a name search. + +In tree-sitter mode, refs have no columns. Step 1 matches the line and the identifier text, and when two targets tie, the answer says so instead of picking the first. The treemap tile already has the symbol id, so it passes the id with `@type` and never searches. + +## Cost + +Measured numbers for tier 1 (`docs/dataflow-engine.md`): visual-notes `app/` 13.9 s and 2.0 GB, srcly `client/` 3.0 s and 2.4 GB. The walk adds `getSymbolAtLocation` on every identifier. On a property access, that forces the checker to type the receiver expression, which is close to a full type check. It is not measured yet. M0 measures it before anything is built. + +M0 gate, on `~/Projects/visual-notes`, under `node --max-old-space-size=4096`, one process at a time across sessions: + +- The walk takes 20 s or less on top of the Program build. +- Peak heap after a full GC stays under `SRCLY_DATAFLOW_MEMORY_MB` (2,560 MB). If it passes, the memory guard can drop the session and the op answers `memory-limit`, which falls back to tree-sitter with that reason. +- The result for every file is 40 MB of JSON or less. If it is larger, the op streams per file or Python asks per folder. + +If M0 fails, stop and record the numbers here. The five findings then stay as named limits. + +## Fallback + +No Node, no engine, no tsconfig, crash, timeout or `memory-limit`: the index is tree-sitter only, exactly as today, with `binder: "tree-sitter"` and the reason. The fallback does not try to approximate the checker. That keeps one binder per answer, and the tree-sitter code stays as it is and gets no new rules. + +## Proof at product scope + +`server/scripts/compare_binders.py ` builds both indexes and compares every TS reference by `(source file, line, identifier, target)`: + +- `agree`: same target. +- `checker-only`: the checker binds it, tree-sitter has no ref (expected: members, the #486 cases). +- `tree-sitter-only`: tree-sitter binds it, the checker says `unbound` or something else (every one is a tree-sitter false positive or a mapping bug). +- `differ`: both bind, to different symbols. +- `mismatched_keys`: checker declarations with no tree-sitter symbol, listed by declaration kind. + +Run it on srcly and explorEDA (`f44a5c63` or newer). Done when: + +- `mismatched_keys` is 0 for exported and top-level declarations. Any key on locals is listed and explained. +- Every `differ` and `tree-sitter-only` row is in a named bucket. Check a sample of 20 per bucket by hand. Each bucket is a checker-correct case, or a bug fixed before merge. +- The five #486 cases have fixtures in `server/tests/test_symbol_index_ts.py`. They pass in checker mode, and the tree-sitter mode answers still pass. +- `srcly refs` on the #486 proof symbols (`AnalysisSourceRow`, `SavedDataStructure`, `EvidenceCollector`) lists at least the same callers as #486. +- The PR states how many references each repo compared, for example "47,524 of 47,524 explorEDA references compared". + +## Milestones + +| | Milestone | Done when | +| --- | --- | --- | +| M0 | Spike: a throwaway walk script on visual-notes and srcly | The cost gate above has numbers. Go or stop is recorded here | +| M1 | `symbolRefs` op, contract, Pydantic mirror, route | Engine tests pass on `examples/value-flow-basics`, plus a fixture per #486 case | +| M2 | Python merge, `binder` info, `compare_binders.py` | The proof above passes on srcly and explorEDA | +| M3 | `/api/symbols/at` and Show references by position | A Playwright test clicks a use of a split name and lands on `@type` | + +M1 to M3 change core logic (two binders that must agree). Each one gets the Codex review loop. + +## Recommendation + +Build it, but only after the M0 gate passes. The five #486 findings are rare: 23 of 47,524 explorEDA references moved in #486. They alone would not pay for an engine op. What pays is member binding: about 8,100 srcly references are guessed today (`typed` plus `name`), and the unresolved pool is much larger. Those are the callers `srcly refs` misses before a delete. The design adds no new id scheme and keeps tree-sitter unchanged as the fallback. So a failed M0 costs one spike and nothing else. + +Do not move the Imports graph to the checker. It must draw without Node, and its one open finding is cheaper to fix in the tree-sitter export walk. From f273c05e589723b5b29a6431f7412e7a81f6f946 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Fri, 27 Nov 2026 23:51:20 -0500 Subject: [PATCH 02/13] docs: add Draftably diagrams for the checker symbol index plan Co-Authored-By: Claude Opus 5.5 --- docs/intent/checker-symbol-index/README.md | 8 ++++ .../intent/checker-symbol-index/binding.draft | 34 +++++++++++++++ .../checker-symbol-index/delivery.draft | 33 +++++++++++++++ docs/intent/checker-symbol-index/goals.draft | 42 +++++++++++++++++++ 4 files changed, 117 insertions(+) create mode 100644 docs/intent/checker-symbol-index/binding.draft create mode 100644 docs/intent/checker-symbol-index/delivery.draft create mode 100644 docs/intent/checker-symbol-index/goals.draft diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md index 3d7987bd..b4fb1925 100644 --- a/docs/intent/checker-symbol-index/README.md +++ b/docs/intent/checker-symbol-index/README.md @@ -2,6 +2,14 @@ Status: proposed, not built. Retire this folder when the last milestone lands. +## Diagrams + +Draftably sources in this folder. Open them with `draftably open docs/intent/checker-symbol-index`. + +- [goals.draft](goals.draft): the goals, the design choices and the proof, on one map. +- [binding.draft](binding.draft): how one request is bound, with the tree-sitter fallback. +- [delivery.draft](delivery.draft): the milestones, the M0 gate and the compare loop. + ## Problem The TypeScript symbol index (`server/app/services/symbols/typescript.py`) binds each name with tree-sitter and its own scope rules. #486 fixed three gaps after three Codex rounds and left five open. All five are binding questions that the TypeScript checker already answers: diff --git a/docs/intent/checker-symbol-index/binding.draft b/docs/intent/checker-symbol-index/binding.draft new file mode 100644 index 00000000..ba3a4cd6 --- /dev/null +++ b/docs/intent/checker-symbol-index/binding.draft @@ -0,0 +1,34 @@ +diagram "How a reference is bound" version=1 +subtitle "Checker when the engine is up; today's index when it is not" + +node ask "srcly refs, Symbols view,\nShow references" + +group engine "Data-flow engine (Node)" color=blue +node start "Start engine\nexplicit use only" in=engine +node walk "symbolRefs walk\ngetSymbolAtLocation + aliases" in=engine + +group server "srcly server (Python)" color=mint +node decls "Tree-sitter declarations\nthe only source of ids" in=server +node join "Join keys to ids\nfile, line, name, meaning" in=server +node cindex "Checker index\nbound = exact, unbound counted" in=server +node tsbind "Tree-sitter binding\ntoday's index, unchanged" in=server +node lookup "Resolve position\n/api/symbols/at" in=server + +node answer "Refs answer\nlabelled with its binder" color=violet + +legend blue "Engine" +legend mint "Server" +legend violet "What the reader gets" +legend line dashed "Fallback" + +edge e_ask ask -> start "request" +edge e_up start -> walk "engine up" +edge e_keys walk -> join "decl keys" +edge e_ids decls -> join "ids" +edge e_build join -> cindex "builds" +edge e_down start -> tsbind "no Node, crash,\nmemory-limit" kind=async +edge e_c cindex -> lookup +edge e_t tsbind -> lookup "line + text" kind=async +edge e_answer lookup -> answer "never a name search" + +layout root engine=compound-spring fit=slide aspect=1.6 diff --git a/docs/intent/checker-symbol-index/delivery.draft b/docs/intent/checker-symbol-index/delivery.draft new file mode 100644 index 00000000..b42249b9 --- /dev/null +++ b/docs/intent/checker-symbol-index/delivery.draft @@ -0,0 +1,33 @@ +diagram "How the plan is delivered" version=1 +subtitle "M0 decides go or stop; each later milestone gets Codex review" + +node approve "Byron approves\nPR 487" +node m0 "M0 cost spike\nvisual-notes + srcly" color=amber +node stop "Stop\nrecord numbers, keep limits" color=red +node m1 "M1 symbolRefs op\ncontract, mirror, route, fixtures" color=blue +node m2 "M2 Python merge\nbinder info, programHash cache" color=blue +node compare "compare_binders.py\nsrcly + explorEDA" color=amber +node fix "Fix mapping bugs" color=red +node m3 "M3 position lookup\nPlaywright lands on @type" color=blue +node review "Codex review loop\nup to 3 rounds, no P0 or P1" color=blue +node ship "Checker-bound refs\nretire the plan folder" color=green + +legend amber "Gate" +legend blue "Build step" +legend green "Outcome" +legend red "Stop or fix" +legend line dashed "Failure path" +legend line solid "Happy path" + +edge a approve -> m0 +edge pass m0 -> m1 "gate passes" +edge fail m0 -> stop "gate fails" kind=async +edge b m1 -> m2 +edge c m2 -> compare "proves" +edge ok compare -> m3 "0 mismatched keys" +edge bad compare -> fix "unexplained rows" kind=async +edge rerun fix -> compare "re-run" kind=async +edge d m3 -> review +edge e review -> ship "clean" + +layout root engine=layered fit=slide diff --git a/docs/intent/checker-symbol-index/goals.draft b/docs/intent/checker-symbol-index/goals.draft new file mode 100644 index 00000000..ddd27de9 --- /dev/null +++ b/docs/intent/checker-symbol-index/goals.draft @@ -0,0 +1,42 @@ +diagram "Checker-bound symbol index" version=1 +subtitle "The checker binds names; tree-sitter keeps the ids" + +node plan "Checker-bound\nsymbol index" + +node goals "Goals" +node g_members "Bind member calls\n~8,100 guessed refs in srcly" +node g_486 "Close #486 findings\n4 of 5 fully" +node g_ids "Keep every id\nfile#Name, file#Name@type" +node g_unbound "Unbound stays unresolved\ncounted by reason" + +node design "Design" +node d_op "symbolRefs engine op\nspan, kind, source, target" +node d_key "Join key\nfile, line, name, meaning" +node d_pos "Show references by position\n/api/symbols/at" +node d_fallback "Tree-sitter fallback\nno Node, crash, memory-limit" +node d_imports "Imports graph stays tree-sitter\nbase scan never waits" + +node proof "Proof" +node p_gate "M0 cost gate\nvisual-notes: at most 20 s, under 2,560 MB" +node p_compare "compare_binders.py\nevery TS ref, srcly + explorEDA" +node p_keys "0 mismatched keys\nexported and top-level" +node p_fixtures "#486 fixtures pass\nin both modes" + +edge e1 plan -> goals +edge e2 goals -> g_members +edge e3 goals -> g_486 +edge e4 goals -> g_ids +edge e5 goals -> g_unbound +edge e6 plan -> design +edge e7 design -> d_op +edge e8 design -> d_key +edge e9 design -> d_pos +edge e10 design -> d_fallback +edge e11 design -> d_imports +edge e12 plan -> proof +edge e13 proof -> p_gate +edge e14 proof -> p_compare +edge e15 proof -> p_keys +edge e16 proof -> p_fixtures + +layout root mindmap root=plan From e7f7a21be52096b5e15b472e3651116e67116bb3 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Fri, 27 Nov 2026 23:55:46 -0500 Subject: [PATCH 03/13] docs(symbols): record the M0 cost spike for checker-bound refs Co-Authored-By: Claude Opus 5.5 --- docs/intent/checker-symbol-index/README.md | 13 ++++ engine/scripts/symbol-refs-spike.ts | 70 ++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 engine/scripts/symbol-refs-spike.ts diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md index b4fb1925..255c2568 100644 --- a/docs/intent/checker-symbol-index/README.md +++ b/docs/intent/checker-symbol-index/README.md @@ -128,6 +128,19 @@ M0 gate, on `~/Projects/visual-notes`, under `node --max-old-space-size=4096`, o If M0 fails, stop and record the numbers here. The five findings then stay as named limits. +### M0 result (2026-11-27): go + +`engine/scripts/symbol-refs-spike.ts` binds every identifier with `getSymbolAtLocation` and alias resolution, one run per root, `node --expose-gc --max-old-space-size=4096`. Heap is after a full GC. + +| Root | Files | Build | Walk | Heap built → walked | RSS | JSON | Bound | Unbound | External | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| srcly `client/` | 196 | 1.4 s | 1.6 s | 319 → 396 MB | 664 MB | 2.8 MB | 41,467 | 821 | 14,152 | +| visual-notes | 691 | 3.1 s | 4.5 s | 555 → 885 MB | 1,157 MB | 3.7 MB | 44,571 | 4,141 | 21,694 | +| srcly (whole repo) | 707 | 2.4 s | 4.7 s | 542 → 771 MB | 1,050 MB | 12.7 MB | 151,560 | 2,476 | 55,922 | +| explorEDA | 819 | 3.2 s | 6.8 s | 604 → 886 MB | 1,187 MB | 15.9 MB | 163,849 | 6,096 | 49,865 | + +Every root is well inside the gate: a walk of 7 s at most, heap under 900 MB, JSON under 16 MB. + ## Fallback No Node, no engine, no tsconfig, crash, timeout or `memory-limit`: the index is tree-sitter only, exactly as today, with `binder: "tree-sitter"` and the reason. The fallback does not try to approximate the checker. That keeps one binder per answer, and the tree-sitter code stays as it is and gets no new rules. diff --git a/engine/scripts/symbol-refs-spike.ts b/engine/scripts/symbol-refs-spike.ts new file mode 100644 index 00000000..e111fe23 --- /dev/null +++ b/engine/scripts/symbol-refs-spike.ts @@ -0,0 +1,70 @@ +import path from "node:path"; +import { createEngineSession, requireTypescript } from "../src/srcly/session"; + +// M0 spike (docs/intent/checker-symbol-index): bind every identifier with the +// checker and measure time, heap and result size. +// node --expose-gc --max-old-space-size=4096 --import tsx scripts/symbol-refs-spike.ts --root +const args = new Map(); +for (let i = 2; i < process.argv.length; i += 2) args.set(process.argv[i].replace(/^--/, ""), process.argv[i + 1]); +const root = path.resolve(args.get("root") ?? "."); +const gc = (globalThis as { gc?: () => void }).gc!; +const mb = (n: number) => Math.round(n / 1024 / 1024); +const heap = () => { + gc(); + return mb(process.memoryUsage().heapUsed); +}; + +const t0 = Date.now(); +const session = createEngineSession({ root, source: ".", tsconfig: null, typescriptFrom: root }); +const tier1 = requireTypescript(session.tier1(), "spike"); +const built = Date.now() - t0; +const heapBuilt = heap(); +const { ts, program } = tier1; +const checker = program.getTypeChecker(); +const rel = (f: string) => path.relative(root, f).split(path.sep).join("/"); +const files = program.getSourceFiles().filter((f) => !f.isDeclarationFile && !f.fileName.includes("/node_modules/") && !rel(f.fileName).startsWith("..")); + +const counts = { identifiers: 0, declNames: 0, bound: 0, unbound: 0, external: 0 }; +const out: unknown[] = []; +const t1 = Date.now(); +for (const file of files) { + const refs: unknown[] = []; + const visit = (node: import("typescript").Node) => { + if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { + counts.identifiers += 1; + const parent = node.parent as import("typescript").Node & { name?: import("typescript").Node }; + if (parent && parent.name === node && ts.isDeclaration(parent as import("typescript").Node)) { + counts.declNames += 1; + return; + } + let sym = checker.getSymbolAtLocation(node); + if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym); + const decl = sym?.declarations?.[0]; + const start = file.getLineAndCharacterOfPosition(node.getStart(file)); + if (!decl) { + counts.unbound += 1; + refs.push({ l: start.line + 1, c: start.character + 1, u: 1 }); + return; + } + const target = decl.getSourceFile(); + const tr = rel(target.fileName); + if (target.isDeclarationFile || tr.startsWith("..") || target.fileName.includes("/node_modules/")) { + counts.external += 1; + return; + } + counts.bound += 1; + const at = target.getLineAndCharacterOfPosition(decl.getStart(target)); + refs.push({ l: start.line + 1, c: start.character + 1, t: [tr, at.line + 1, node.text] }); + return; + } + ts.forEachChild(node, visit); + }; + visit(file); + out.push({ file: rel(file.fileName), refs }); +} +const walked = Date.now() - t1; +const heapWalked = heap(); +const json = JSON.stringify(out).length; +console.log( + JSON.stringify({ root, files: files.length, buildMs: built, walkMs: walked, heapBuiltMB: heapBuilt, heapWalkedMB: heapWalked, rssMB: mb(process.memoryUsage().rss), jsonMB: +(json / 1e6).toFixed(1), ...counts }), +); From 6da5c223fc92a8d60f3fcee8d9b2e366717d371c Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:00:13 -0500 Subject: [PATCH 04/13] feat(engine): symbolRefs binds every identifier with the checker Co-Authored-By: Claude Opus 5.5 --- client/src/dataflow/contract.generated.ts | 35 +++ docs/intent/checker-symbol-index/README.md | 2 +- engine/bin/srcly-engine.ts | 1 + engine/eslint.config.js | 2 +- engine/scripts/symbol-refs-probe.ts | 30 +++ engine/scripts/symbol-refs-spike.ts | 70 ------ engine/src/service/analysis-service.ts | 2 + engine/src/service/analysis-worker.ts | 2 + engine/src/srcly/contracts/registry.ts | 2 + engine/src/srcly/contracts/symbol-refs.ts | 54 +++++ engine/src/srcly/ops/symbol-refs.ts | 183 +++++++++++++++ .../srcly/__fixtures__/symbol-refs/src/m.ts | 14 ++ .../__fixtures__/symbol-refs/src/use.tsx | 25 ++ .../__fixtures__/symbol-refs/tsconfig.json | 1 + engine/test/srcly/symbol-refs.test.ts | 75 ++++++ .../dataflow/contracts/symbolRefs.schema.json | 216 ++++++++++++++++++ 16 files changed, 642 insertions(+), 72 deletions(-) create mode 100644 engine/scripts/symbol-refs-probe.ts delete mode 100644 engine/scripts/symbol-refs-spike.ts create mode 100644 engine/src/srcly/contracts/symbol-refs.ts create mode 100644 engine/src/srcly/ops/symbol-refs.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs/src/m.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx create mode 100644 engine/test/srcly/__fixtures__/symbol-refs/tsconfig.json create mode 100644 engine/test/srcly/symbol-refs.test.ts create mode 100644 server/app/services/dataflow/contracts/symbolRefs.schema.json diff --git a/client/src/dataflow/contract.generated.ts b/client/src/dataflow/contract.generated.ts index 44466426..39e87137 100644 --- a/client/src/dataflow/contract.generated.ts +++ b/client/src/dataflow/contract.generated.ts @@ -724,3 +724,38 @@ export type FlowSignatureResult = { }[]; skippedScopes: number; }; + +/** Result of the `symbolRefs` op. */ +export type SymbolRefsResult = { + outcome: "ok" | "assumed" | "partial" | "not-analyzed" | "unsupported" | "stale" | "cancelled" | "budget"; + generation: number; + programHash: string; + tsconfig: string; + typescript: string; + nullProof: boolean; + reason: string | null; + targets: { + file: string; + name: string; + line: number; + meaning: "value" | "type"; + scope: "module" | "member" | "local"; + }[]; + files: { + file: string; + refs: { + line: number; + column: number; + endColumn: number; + kind: "call" | "instantiate" | "read" | "write" | "type" | "extends" | "implements"; + target: number | null; + unbound: "unresolved" | "any" | null; + }[]; + }[]; + counts: { + files: number; + bound: number; + unbound: number; + external: number; + }; +}; diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md index 255c2568..4341c18f 100644 --- a/docs/intent/checker-symbol-index/README.md +++ b/docs/intent/checker-symbol-index/README.md @@ -130,7 +130,7 @@ If M0 fails, stop and record the numbers here. The five findings then stay as na ### M0 result (2026-11-27): go -`engine/scripts/symbol-refs-spike.ts` binds every identifier with `getSymbolAtLocation` and alias resolution, one run per root, `node --expose-gc --max-old-space-size=4096`. Heap is after a full GC. +A throwaway spike bound every identifier with `getSymbolAtLocation` and alias resolution, one run per root (the op's cost is now `cd engine && node --expose-gc --max-old-space-size=4096 --import tsx scripts/symbol-refs-probe.ts --root `), `node --expose-gc --max-old-space-size=4096`. Heap is after a full GC. | Root | Files | Build | Walk | Heap built → walked | RSS | JSON | Bound | Unbound | External | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | diff --git a/engine/bin/srcly-engine.ts b/engine/bin/srcly-engine.ts index 9c8f2155..3f039478 100644 --- a/engine/bin/srcly-engine.ts +++ b/engine/bin/srcly-engine.ts @@ -106,6 +106,7 @@ function workerOperation(frame: RequestFrame): AnalysisOperation | null { if (frame.op === "anchorGraph") return { kind: "anchor-graph", params }; if (frame.op === "functionEffects") return { kind: "function-effects", params }; if (frame.op === "fileExports") return { kind: "file-exports", params }; + if (frame.op === "symbolRefs") return { kind: "symbol-refs", params }; if (frame.op === "routePath") return { kind: "route-path", params }; if (frame.op === "fileSignals") return { kind: "file-signals", params }; if (frame.op === "flowSignature") return { kind: "flow-signature", params }; diff --git a/engine/eslint.config.js b/engine/eslint.config.js index 6ba34839..313e2613 100644 --- a/engine/eslint.config.js +++ b/engine/eslint.config.js @@ -5,7 +5,7 @@ import tseslint from "typescript-eslint"; export default tseslint.config( { - ignores: ["dist/**", "node_modules/**", "tmp/**", "examples/bad-ish-solid/**", "examples/pattern-catalog/**", "examples/value-flow-js/**"], + ignores: ["dist/**", "node_modules/**", "tmp/**", "examples/bad-ish-solid/**", "examples/pattern-catalog/**", "examples/value-flow-js/**", "test/srcly/__fixtures__/symbol-refs/**"], }, eslint.configs.recommended, ...tseslint.configs.recommended, diff --git a/engine/scripts/symbol-refs-probe.ts b/engine/scripts/symbol-refs-probe.ts new file mode 100644 index 00000000..8daf6dec --- /dev/null +++ b/engine/scripts/symbol-refs-probe.ts @@ -0,0 +1,30 @@ +import fs from "node:fs"; +import path from "node:path"; +import { symbolRefsOp } from "../src/srcly/ops/symbol-refs"; +import { createEngineSession } from "../src/srcly/session"; + +// The cost of `symbolRefs` on one root: Program build, walk, heap after a full GC +// and result size (docs/intent/checker-symbol-index, M0). +// node --expose-gc --max-old-space-size=4096 --import tsx scripts/symbol-refs-probe.ts --root [--json out.json] +const args = new Map(); +for (let i = 2; i < process.argv.length; i += 2) args.set(process.argv[i].replace(/^--/, ""), process.argv[i + 1]); +const root = path.resolve(args.get("root") ?? "."); +const gc = (globalThis as { gc?: () => void }).gc; +if (!gc) throw new Error("run with --expose-gc"); +const mb = (n: number) => Math.round(n / 1024 / 1024); +const heap = () => { + gc(); + return mb(process.memoryUsage().heapUsed); +}; + +const t0 = Date.now(); +const session = createEngineSession({ root, source: ".", tsconfig: null, typescriptFrom: root }); +session.tier1(); +const buildMs = Date.now() - t0; +const heapBuilt = heap(); +const t1 = Date.now(); +const result = symbolRefsOp(session, {}); +const walkMs = Date.now() - t1; +const text = JSON.stringify(result); +if (args.has("json")) fs.writeFileSync(args.get("json")!, text); +console.log(JSON.stringify({ root, buildMs, walkMs, heapBuiltMB: heapBuilt, heapWalkedMB: heap(), rssMB: mb(process.memoryUsage().rss), jsonMB: +(text.length / 1e6).toFixed(1), ...result.counts })); diff --git a/engine/scripts/symbol-refs-spike.ts b/engine/scripts/symbol-refs-spike.ts deleted file mode 100644 index e111fe23..00000000 --- a/engine/scripts/symbol-refs-spike.ts +++ /dev/null @@ -1,70 +0,0 @@ -import path from "node:path"; -import { createEngineSession, requireTypescript } from "../src/srcly/session"; - -// M0 spike (docs/intent/checker-symbol-index): bind every identifier with the -// checker and measure time, heap and result size. -// node --expose-gc --max-old-space-size=4096 --import tsx scripts/symbol-refs-spike.ts --root -const args = new Map(); -for (let i = 2; i < process.argv.length; i += 2) args.set(process.argv[i].replace(/^--/, ""), process.argv[i + 1]); -const root = path.resolve(args.get("root") ?? "."); -const gc = (globalThis as { gc?: () => void }).gc!; -const mb = (n: number) => Math.round(n / 1024 / 1024); -const heap = () => { - gc(); - return mb(process.memoryUsage().heapUsed); -}; - -const t0 = Date.now(); -const session = createEngineSession({ root, source: ".", tsconfig: null, typescriptFrom: root }); -const tier1 = requireTypescript(session.tier1(), "spike"); -const built = Date.now() - t0; -const heapBuilt = heap(); -const { ts, program } = tier1; -const checker = program.getTypeChecker(); -const rel = (f: string) => path.relative(root, f).split(path.sep).join("/"); -const files = program.getSourceFiles().filter((f) => !f.isDeclarationFile && !f.fileName.includes("/node_modules/") && !rel(f.fileName).startsWith("..")); - -const counts = { identifiers: 0, declNames: 0, bound: 0, unbound: 0, external: 0 }; -const out: unknown[] = []; -const t1 = Date.now(); -for (const file of files) { - const refs: unknown[] = []; - const visit = (node: import("typescript").Node) => { - if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { - counts.identifiers += 1; - const parent = node.parent as import("typescript").Node & { name?: import("typescript").Node }; - if (parent && parent.name === node && ts.isDeclaration(parent as import("typescript").Node)) { - counts.declNames += 1; - return; - } - let sym = checker.getSymbolAtLocation(node); - if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym); - const decl = sym?.declarations?.[0]; - const start = file.getLineAndCharacterOfPosition(node.getStart(file)); - if (!decl) { - counts.unbound += 1; - refs.push({ l: start.line + 1, c: start.character + 1, u: 1 }); - return; - } - const target = decl.getSourceFile(); - const tr = rel(target.fileName); - if (target.isDeclarationFile || tr.startsWith("..") || target.fileName.includes("/node_modules/")) { - counts.external += 1; - return; - } - counts.bound += 1; - const at = target.getLineAndCharacterOfPosition(decl.getStart(target)); - refs.push({ l: start.line + 1, c: start.character + 1, t: [tr, at.line + 1, node.text] }); - return; - } - ts.forEachChild(node, visit); - }; - visit(file); - out.push({ file: rel(file.fileName), refs }); -} -const walked = Date.now() - t1; -const heapWalked = heap(); -const json = JSON.stringify(out).length; -console.log( - JSON.stringify({ root, files: files.length, buildMs: built, walkMs: walked, heapBuiltMB: heapBuilt, heapWalkedMB: heapWalked, rssMB: mb(process.memoryUsage().rss), jsonMB: +(json / 1e6).toFixed(1), ...counts }), -); diff --git a/engine/src/service/analysis-service.ts b/engine/src/service/analysis-service.ts index 5504db32..4a5516ef 100644 --- a/engine/src/service/analysis-service.ts +++ b/engine/src/service/analysis-service.ts @@ -79,6 +79,8 @@ export type AnalysisOperation = | { kind: "function-effects"; params: Record } | { kind: "route-path"; params: Record } | { kind: "file-exports"; params: Record } + /** Every identifier bound by the checker, for srcly's symbol index. */ + | { kind: "symbol-refs"; params: Record } /** Tier 2: the legacy report as per-file metrics, findings and `dataflow.md`. */ | { kind: "file-signals"; params: Record } /** A file's functions as flow signatures, for the compare report's data-flow changes. */ diff --git a/engine/src/service/analysis-worker.ts b/engine/src/service/analysis-worker.ts index 4cded6ce..ef959566 100644 --- a/engine/src/service/analysis-worker.ts +++ b/engine/src/service/analysis-worker.ts @@ -13,6 +13,7 @@ import type { AnalysisOperation, AnalysisProgress, AnalysisWorkerData, AnalysisW import { errorPayload } from "../srcly/protocol"; import { anchorGraphOp } from "../srcly/ops/anchor-graph"; import { fileExportsOp } from "../srcly/ops/file-exports"; +import { symbolRefsOp } from "../srcly/ops/symbol-refs"; import { fileSignalsOp } from "../srcly/ops/file-signals"; import { flowSignatureOp } from "../srcly/ops/flow-signature"; import { functionEffectsOp } from "../srcly/ops/function-effects"; @@ -92,6 +93,7 @@ function perform(operation: AnalysisOperation, requestId: number, cancellation: if (operation.kind === "anchor-graph") return announce(anchorGraphOp(requireSession(), operation.params, cancellation)); if (operation.kind === "function-effects") return announce(functionEffectsOp(requireSession(), operation.params, cancellation)); if (operation.kind === "file-exports") return announce(fileExportsOp(requireSession(), operation.params, cancellation)); + if (operation.kind === "symbol-refs") return announce(symbolRefsOp(requireSession(), operation.params, cancellation)); if (operation.kind === "file-signals") return announce(fileSignalsOp(requireSession(), operation.params)); if (operation.kind === "flow-signature") return announce(flowSignatureOp(requireSession(), operation.params, cancellation)); if (operation.kind === "route-path") return announce(routePathOp(requireSession(), operation.params, cancellation)); diff --git a/engine/src/srcly/contracts/registry.ts b/engine/src/srcly/contracts/registry.ts index de193e2a..59362ed5 100644 --- a/engine/src/srcly/contracts/registry.ts +++ b/engine/src/srcly/contracts/registry.ts @@ -10,6 +10,7 @@ import { routePathResultSchema } from "./route-path"; import { routesResultSchema } from "./routes"; import { selectExpressionResultSchema, valueFlowResultSchema } from "./value-flow"; import { statusResultSchema } from "./status"; +import { symbolRefsResultSchema } from "./symbol-refs"; /** * Every op result the server and client read, by op name. `pnpm @@ -29,4 +30,5 @@ export const CONTRACTS: { op: string; typeName: string; schema: z.ZodType }[] = { op: "routePath", typeName: "RoutePathResult", schema: routePathResultSchema }, { op: "fileSignals", typeName: "FileSignalsResult", schema: fileSignalsResultSchema }, { op: "flowSignature", typeName: "FlowSignatureResult", schema: flowSignatureResultSchema }, + { op: "symbolRefs", typeName: "SymbolRefsResult", schema: symbolRefsResultSchema }, ]; diff --git a/engine/src/srcly/contracts/symbol-refs.ts b/engine/src/srcly/contracts/symbol-refs.ts new file mode 100644 index 00000000..102e0285 --- /dev/null +++ b/engine/src/srcly/contracts/symbol-refs.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; +import { generationFields, outcomeSchema } from "./primitives"; + +/** + * Every identifier of the Program's own files, bound by the checker + * (docs/intent/checker-symbol-index). srcly's symbol index keeps its own ids + * and joins each target to one of them by file, name, line and meaning, so + * no id is built here. Positions are 1-based lines and 1-based UTF-16 + * columns with an exclusive end, like every contract. + */ +export const symbolRefKindSchema = z.enum(["call", "instantiate", "read", "write", "type", "extends", "implements"]); + +export const symbolRefTargetSchema = z.strictObject({ + /** Relative to the engine root. */ + file: z.string(), + /** The declaration's own name: `A` for `import { A as B }`, `default` for an anonymous default export. */ + name: z.string(), + /** The line of the declaration's name. */ + line: z.number().int().positive(), + /** `type` for an interface or type alias; everything else is `value`. */ + meaning: z.enum(["value", "type"]), + /** `module`: declared at the top of its file; `member`: a class, interface or object member; `local`: inside a body. */ + scope: z.enum(["module", "member", "local"]), +}); + +export const symbolRefSchema = z.strictObject({ + line: z.number().int().positive(), + column: z.number().int().positive(), + endColumn: z.number().int().positive(), + kind: symbolRefKindSchema, + /** An index into `targets`; null when the checker binds nothing here (`unbound` says why). */ + target: z.number().int().nonnegative().nullable(), + unbound: z.enum(["unresolved", "any"]).nullable(), +}); + +export const symbolRefsResultSchema = z.strictObject({ + outcome: outcomeSchema, + ...generationFields, + reason: z.string().nullable(), + /** Each declaration that some ref binds to, once. */ + targets: z.array(symbolRefTargetSchema), + files: z.array(z.strictObject({ file: z.string(), refs: z.array(symbolRefSchema) })), + counts: z.strictObject({ + files: z.number().int().nonnegative(), + bound: z.number().int().nonnegative(), + unbound: z.number().int().nonnegative(), + /** Bound to a declaration outside the root, in `node_modules` or in a `.d.ts`: left out of `files`. */ + external: z.number().int().nonnegative(), + }), +}); + +export type SymbolRef = z.infer; +export type SymbolRefTarget = z.infer; +export type SymbolRefsResult = z.infer; diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts new file mode 100644 index 00000000..0f98ea7f --- /dev/null +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -0,0 +1,183 @@ +import path from "node:path"; +import type * as TypeScript from "typescript"; +import type { AnalysisCancellationToken } from "../../analysis/cancellation"; +import { symbolRefsResultSchema, type SymbolRef, type SymbolRefTarget, type SymbolRefsResult } from "../contracts/symbol-refs"; +import { EngineError } from "../protocol"; +import { checkGeneration, requireTypescript, type EngineSession } from "../session"; + +type Ts = typeof TypeScript; +type Kind = SymbolRef["kind"]; + +/** + * Every identifier of the Program's own files under the root, with the + * declaration the checker binds it to (docs/intent/checker-symbol-index). + * srcly's symbol index joins each target to its own ids, so this op answers + * binding only: no ids, no source symbol. `params.files` narrows it to some + * files (relative to the root); absent means all of them. + */ +export function symbolRefsOp(session: EngineSession, params: { files?: unknown; expectedGeneration?: unknown }, cancellation?: AnalysisCancellationToken): SymbolRefsResult { + const tier1 = requireTypescript(session.tier1(), "symbolRefs"); + checkGeneration(tier1, params.expectedGeneration); + if (params.files !== undefined && !(Array.isArray(params.files) && params.files.every((f) => typeof f === "string"))) { + throw new EngineError("invalid-request", "symbolRefs params.files must be a list of paths"); + } + const { ts, program } = tier1; + const checker = program.getTypeChecker(); + const root = path.resolve(tier1.root); + const rel = (file: string) => path.relative(root, file).split(path.sep).join("/"); + const own = (source: TypeScript.SourceFile) => source.fileName.startsWith(root + path.sep) && !source.fileName.includes(`${path.sep}node_modules${path.sep}`) && !source.isDeclarationFile; + const wanted = params.files ? new Set((params.files as string[]).map((f) => f.split(path.sep).join("/"))) : null; + const sources = program + .getSourceFiles() + .filter((source) => own(source) && (!wanted || wanted.has(rel(source.fileName)))) + .sort((a, b) => (a.fileName < b.fileName ? -1 : a.fileName > b.fileName ? 1 : 0)); + + const counts = { files: sources.length, bound: 0, unbound: 0, external: 0 }; + const targets: SymbolRefTarget[] = []; + const indexOf = new Map(); + const intern = (decl: TypeScript.Declaration, home: TypeScript.SourceFile) => { + let index = indexOf.get(decl); + if (index === undefined) { + index = targets.push(targetOf(ts, decl, home, rel)) - 1; + indexOf.set(decl, index); + } + return index; + }; + const files = sources.map((source) => { + cancellation?.throwIfCancelled(); + const refs: SymbolRef[] = []; + const visit = (node: TypeScript.Node) => { + if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { + const ref = bind(ts, checker, source, node, own, intern); + if (ref === "skip") return; + if (ref === "external") counts.external += 1; + else { + if (ref.target) counts.bound += 1; + else counts.unbound += 1; + refs.push(ref); + } + return; + } + ts.forEachChild(node, visit); + }; + visit(source); + return { file: rel(source.fileName), refs }; + }); + + return symbolRefsResultSchema.parse({ + outcome: "ok", + generation: tier1.generation.id, + programHash: tier1.generation.programHash, + tsconfig: tier1.generation.tsconfig, + typescript: tier1.generation.typescript, + nullProof: tier1.generation.nullProof, + reason: null, + targets, + files, + counts, + }); +} + +function bind( + ts: Ts, + checker: TypeScript.TypeChecker, + source: TypeScript.SourceFile, + node: TypeScript.Identifier | TypeScript.PrivateIdentifier, + own: (source: TypeScript.SourceFile) => boolean, + intern: (decl: TypeScript.Declaration, home: TypeScript.SourceFile) => number, +): SymbolRef | "external" | "skip" { + const parent = node.parent; + if (!parent || skipped(ts, node, parent)) return "skip"; + const shorthand = ts.isShorthandPropertyAssignment(parent) && parent.name === node; + // A declaration's own name is not a reference; `{ action }` is the one name that is both. + if (!shorthand && (parent as { name?: TypeScript.Node }).name === node && isDeclaration(ts, parent)) return "skip"; + const position = typePosition(ts, node); + const inType = position !== "code"; + let symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(parent) : checker.getSymbolAtLocation(node); + if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); + const start = source.getLineAndCharacterOfPosition(node.getStart(source)); + const ref = { line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind: inType ? ("type" as Kind) : kindOf(ts, node) }; + // `typeof x` in a type names the value x. + const decl = symbol ? pick(ts, symbol, position === "type") : undefined; + if (!decl) { + const receiver = ts.isPropertyAccessExpression(parent) && parent.name === node ? parent.expression : null; + const any = receiver ? (checker.getTypeAtLocation(receiver).flags & ts.TypeFlags.Any) !== 0 : false; + return { ...ref, target: null, unbound: any ? "any" : "unresolved" }; + } + const home = decl.getSourceFile(); + if (!own(home)) return "external"; + return { ...ref, target: intern(decl, home), unbound: null }; +} + +/** Identifiers that are syntax, not a use: import and export clauses, labels, a JSX closing tag. */ +function skipped(ts: Ts, node: TypeScript.Node, parent: TypeScript.Node): boolean { + if (ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent)) return true; + if (ts.isLabeledStatement(parent) || ts.isBreakOrContinueStatement(parent)) return true; + if (ts.isJsxClosingElement(parent)) return true; + if (ts.isMetaProperty(parent)) return true; + // The tag name's right side in `` is still a use; a JSX attribute name is a prop declaration. + return ts.isJsxAttribute(parent) && parent.name === node; +} + +/** + * Where the identifier sits: in code, in a type (an annotation, a type argument, `import("…").T`), + * or in `typeof x` inside a type, which names a value. + */ +function typePosition(ts: Ts, node: TypeScript.Node): "code" | "type" | "typeof" { + let typeofSeen = false; + for (let at = node.parent; at && !ts.isSourceFile(at); at = at.parent) { + // `class A extends B`: B is code; T was a type node on the way up. + if (ts.isExpressionWithTypeArguments(at) && !ts.isTypeNode(at.parent)) return "code"; + if (ts.isTypeQueryNode(at) || (ts.isImportTypeNode(at) && at.isTypeOf)) typeofSeen = true; + if (ts.isTypeNode(at) && !ts.isExpressionWithTypeArguments(at)) return typeofSeen ? "typeof" : "type"; + if (ts.isStatement(at) || ts.isBlock(at) || ts.isPropertyAccessExpression(at) || ts.isCallExpression(at) || ts.isNewExpression(at) || ts.isBinaryExpression(at)) return "code"; + } + return "code"; +} + +function kindOf(ts: Ts, node: TypeScript.Node): Kind { + let expr: TypeScript.Node = node; + const parent = node.parent; + // `a.b`: the member name stands for the whole access; the receiver `a` is a read. + if ((ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isQualifiedName(parent) && parent.right === node)) expr = parent; + while (ts.isParenthesizedExpression(expr.parent) || ts.isNonNullExpression(expr.parent) || ts.isAsExpression(expr.parent)) expr = expr.parent; + const up = expr.parent; + if (ts.isExpressionWithTypeArguments(up) && ts.isHeritageClause(up.parent)) return up.parent.token === ts.SyntaxKind.ImplementsKeyword ? "implements" : "extends"; + if ((ts.isCallExpression(up) || ts.isDecorator(up) || ts.isTaggedTemplateExpression(up)) && (up as { expression?: TypeScript.Node; tag?: TypeScript.Node }).expression === expr) return "call"; + if (ts.isTaggedTemplateExpression(up) && up.tag === expr) return "call"; + if (ts.isNewExpression(up) && up.expression === expr) return "instantiate"; + if ((ts.isJsxOpeningElement(up) || ts.isJsxSelfClosingElement(up)) && up.tagName === expr) return "call"; + if (ts.isBinaryExpression(up) && up.left === expr && up.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && up.operatorToken.kind <= ts.SyntaxKind.LastAssignment) return "write"; + if ((ts.isPrefixUnaryExpression(up) || ts.isPostfixUnaryExpression(up)) && (up.operator === ts.SyntaxKind.PlusPlusToken || up.operator === ts.SyntaxKind.MinusMinusToken)) return "write"; + return "read"; +} + +/** `ts.isDeclaration` is internal to TypeScript; it is on the runtime object of every supported version. */ +const isDeclaration = (ts: Ts, node: TypeScript.Node) => (ts as unknown as { isDeclaration(n: TypeScript.Node): boolean }).isDeclaration(node); + +const isTypeDecl = (ts: Ts, d: TypeScript.Declaration) => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d); + +/** The declaration the location means: in a type, a type-side one; in code, a value-side one. */ +function pick(ts: Ts, symbol: TypeScript.Symbol, inType: boolean): TypeScript.Declaration | undefined { + const decls = symbol.declarations ?? []; + if (decls.length < 2) return decls[0]; + const typeSide = decls.find((d) => isTypeDecl(ts, d) || ts.isClassDeclaration(d) || ts.isEnumDeclaration(d)); + const valueSide = decls.find((d) => !isTypeDecl(ts, d)); + return (inType ? typeSide : valueSide) ?? decls[0]; +} + +function targetOf(ts: Ts, decl: TypeScript.Declaration, home: TypeScript.SourceFile, rel: (file: string) => string): SymbolRefTarget { + const file = rel(home.fileName); + if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, meaning: "value", scope: "module" }; + const name = ts.getNameOfDeclaration(decl); + const text = name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; + const at = home.getLineAndCharacterOfPosition((name ?? decl).getStart(home)); + return { file, name: text, line: at.line + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; +} + +function scopeOf(ts: Ts, decl: TypeScript.Node): SymbolRefTarget["scope"] { + if (ts.isClassElement(decl) || ts.isTypeElement(decl) || ts.isEnumMember(decl) || ts.isObjectLiteralElementLike(decl)) return "member"; + let at = decl.parent; + while (at && (ts.isVariableDeclaration(at) || ts.isVariableDeclarationList(at) || ts.isVariableStatement(at) || ts.isBindingElement(at) || ts.isObjectBindingPattern(at) || ts.isArrayBindingPattern(at))) at = at.parent; + return at && ts.isSourceFile(at) ? "module" : "local"; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts new file mode 100644 index 00000000..2e8f152a --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts @@ -0,0 +1,14 @@ +export type Row = { id: number }; +export const Row = { id: 1 }; + +export class Store { + count = 0; + bump() { + this.count += 1; + } +} + +export default function A() { + return 1; +} +export type A = number; diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx new file mode 100644 index 00000000..663390ce --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx @@ -0,0 +1,25 @@ +import A, { Store } from "./m"; +import * as m from "./m"; + +declare function pick(): T; +declare function C(props: { row?: T }): null; + +export const value = pick(); +export let typed: import("./m").Row | undefined; +export const tag = />; + +export function run(store: Store, loose: any) { + store.bump(); + loose.bump(); + const made = new m.Store(); + const n: A = A(); + return { made, n }; +} + +export function outer() { + function inner(): Local { + return { ok: true }; + } + type Local = { ok: boolean }; + return inner; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs/tsconfig.json b/engine/test/srcly/__fixtures__/symbol-refs/tsconfig.json new file mode 100644 index 00000000..ad6d0027 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "jsx": "preserve", "module": "esnext", "moduleResolution": "bundler", "target": "es2022", "noEmit": true }, "include": ["src"] } diff --git a/engine/test/srcly/symbol-refs.test.ts b/engine/test/srcly/symbol-refs.test.ts new file mode 100644 index 00000000..20406950 --- /dev/null +++ b/engine/test/srcly/symbol-refs.test.ts @@ -0,0 +1,75 @@ +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { symbolRefsOp } from "../../src/srcly/ops/symbol-refs"; +import { createEngineSession } from "../../src/srcly/session"; + +const root = path.join(__dirname, "__fixtures__", "symbol-refs"); + +describe("symbolRefs binds every identifier with the checker", () => { + const result = symbolRefsOp(createEngineSession({ root, source: ".", tsconfig: null, typescriptFrom: root }), { files: ["src/use.tsx"] }); + const use = result.files[0]; + const lines = use.refs.map((ref) => ({ ...ref, to: ref.target === null ? null : result.targets[ref.target] })); + const at = (line: number, text: string) => { + const column = (source[line - 1].indexOf(text) ?? -1) + 1; + const hit = lines.find((ref) => ref.line === line && ref.column === column); + if (!hit) throw new Error(`no ref at ${line}:${column} (${text})`); + return hit; + }; + const source = [ + `import A, { Store } from "./m";`, + `import * as m from "./m";`, + ``, + `declare function pick(): T;`, + `declare function C(props: { row?: T }): null;`, + ``, + `export const value = pick();`, + `export let typed: import("./m").Row | undefined;`, + `export const tag = />;`, + ``, + `export function run(store: Store, loose: any) {`, + ` store.bump();`, + ` loose.bump();`, + ` const made = new m.Store();`, + ` const n: A = A();`, + ` return { made, n };`, + `}`, + ``, + `export function outer() {`, + ` function inner(): Local {`, + ` return { ok: true };`, + ` }`, + ` type Local = { ok: boolean };`, + ` return inner;`, + `}`, + ]; + + it("answers ok for the files asked, with no import clause as a reference", () => { + expect(result.outcome).toBe("ok"); + expect(result.files.map((f) => f.file)).toEqual(["src/use.tsx"]); + expect(lines.filter((ref) => ref.line <= 2)).toEqual([]); + }); + + it("splits a name's type and value by position, typeof included", () => { + expect(at(7, "Row").to).toMatchObject({ file: "src/m.ts", name: "Row", line: 2, meaning: "value", scope: "module" }); + expect(at(7, "Row").kind).toBe("type"); + expect(at(8, "Row").to).toMatchObject({ name: "Row", line: 1, meaning: "type" }); + expect(at(9, "Row").to).toMatchObject({ name: "Row", line: 1, meaning: "type" }); + }); + + it("binds a member call through a parameter's type, and leaves an any receiver unbound", () => { + expect(at(12, "bump")).toMatchObject({ kind: "call", to: { name: "bump", line: 6, meaning: "value", scope: "member" } }); + expect(at(13, "bump")).toMatchObject({ kind: "call", target: null, unbound: "any" }); + expect(at(14, "Store")).toMatchObject({ kind: "instantiate", to: { name: "Store", line: 4 } }); + expect(at(14, "m.Store").to).toMatchObject({ file: "src/m.ts", name: "*" }); + }); + + it("follows a default import to the function by its own name, and never to the type of the same name", () => { + expect(at(15, "A()")).toMatchObject({ kind: "call", to: { name: "A", line: 11, meaning: "value" } }); + // `import A` imports the default export, a function: as a type it binds nothing (#486 bound it to `A@type`). + expect(at(15, "A =")).toMatchObject({ kind: "type", target: null, unbound: "unresolved" }); + }); + + it("binds a forward reference to a block-local alias", () => { + expect(at(20, "Local").to).toMatchObject({ file: "src/use.tsx", name: "Local", line: 23, meaning: "type", scope: "local" }); + }); +}); diff --git a/server/app/services/dataflow/contracts/symbolRefs.schema.json b/server/app/services/dataflow/contracts/symbolRefs.schema.json new file mode 100644 index 00000000..6e0871aa --- /dev/null +++ b/server/app/services/dataflow/contracts/symbolRefs.schema.json @@ -0,0 +1,216 @@ +{ + "title": "SymbolRefsResult", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "outcome": { + "type": "string", + "enum": [ + "ok", + "assumed", + "partial", + "not-analyzed", + "unsupported", + "stale", + "cancelled", + "budget" + ] + }, + "generation": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "programHash": { + "type": "string" + }, + "tsconfig": { + "type": "string" + }, + "typescript": { + "type": "string" + }, + "nullProof": { + "type": "boolean" + }, + "reason": { + "type": [ + "string", + "null" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "name": { + "type": "string" + }, + "line": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "meaning": { + "type": "string", + "enum": [ + "value", + "type" + ] + }, + "scope": { + "type": "string", + "enum": [ + "module", + "member", + "local" + ] + } + }, + "required": [ + "file", + "name", + "line", + "meaning", + "scope" + ], + "additionalProperties": false + } + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "refs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "line": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "column": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "endColumn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "kind": { + "type": "string", + "enum": [ + "call", + "instantiate", + "read", + "write", + "type", + "extends", + "implements" + ] + }, + "target": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "unbound": { + "anyOf": [ + { + "type": "string", + "enum": [ + "unresolved", + "any" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "line", + "column", + "endColumn", + "kind", + "target", + "unbound" + ], + "additionalProperties": false + } + } + }, + "required": [ + "file", + "refs" + ], + "additionalProperties": false + } + }, + "counts": { + "type": "object", + "properties": { + "files": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "bound": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "unbound": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "external": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "files", + "bound", + "unbound", + "external" + ], + "additionalProperties": false + } + }, + "required": [ + "outcome", + "generation", + "programHash", + "tsconfig", + "typescript", + "nullProof", + "reason", + "targets", + "files", + "counts" + ], + "additionalProperties": false +} From 097c23c262113349763f678f84cd89e5d7bb1df1 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:13:58 -0500 Subject: [PATCH 05/13] feat(symbols): bind TypeScript refs with the engine's checker, joined to tree-sitter ids Co-Authored-By: Claude Opus 5.5 --- client/src/dataflow/contract.generated.ts | 1 + engine/src/core.ts | 2 + engine/src/srcly/contracts/symbol-refs.ts | 4 +- engine/src/srcly/ops/symbol-refs.ts | 166 +++++++++++++++++- engine/src/srcly/session.ts | 4 + server/app/models.py | 9 +- server/app/routers/symbols.py | 8 +- .../dataflow/contracts/symbolRefs.schema.json | 13 ++ server/app/services/dataflow/models.py | 46 +++++ server/app/services/symbols/checker.py | 126 +++++++++++++ server/app/services/symbols/index.py | 63 ++++++- server/app/services/symbols/model.py | 3 + server/app/services/symbols/refs.py | 17 +- server/scripts/compare_binders.py | 116 ++++++++++++ server/tests/test_dataflow_models.py | 1 + server/tests/test_symbol_checker_join.py | 80 +++++++++ 16 files changed, 633 insertions(+), 26 deletions(-) create mode 100644 server/app/services/symbols/checker.py create mode 100644 server/scripts/compare_binders.py create mode 100644 server/tests/test_symbol_checker_join.py diff --git a/client/src/dataflow/contract.generated.ts b/client/src/dataflow/contract.generated.ts index 39e87137..9da51c3e 100644 --- a/client/src/dataflow/contract.generated.ts +++ b/client/src/dataflow/contract.generated.ts @@ -748,6 +748,7 @@ export type SymbolRefsResult = { column: number; endColumn: number; kind: "call" | "instantiate" | "read" | "write" | "type" | "extends" | "implements"; + source: number | null; target: number | null; unbound: "unresolved" | "any" | null; }[]; diff --git a/engine/src/core.ts b/engine/src/core.ts index cda5c808..8c41e8e6 100644 --- a/engine/src/core.ts +++ b/engine/src/core.ts @@ -49,6 +49,8 @@ export function createAnalyzer(args: AnalyzerArgs, reportProgress?: AnalyzerProg ts, program, args, + /** The tsconfigs found and the primary one, whose options the Program uses. */ + resolution, identitiesForFile: (file: string) => prepare().identityIndex.evidenceForFile(file), report: (overrides: Partial = {}) => { const { routing, identityIndex } = prepare(); diff --git a/engine/src/srcly/contracts/symbol-refs.ts b/engine/src/srcly/contracts/symbol-refs.ts index 102e0285..9d3b5a3c 100644 --- a/engine/src/srcly/contracts/symbol-refs.ts +++ b/engine/src/srcly/contracts/symbol-refs.ts @@ -28,6 +28,8 @@ export const symbolRefSchema = z.strictObject({ column: z.number().int().positive(), endColumn: z.number().int().positive(), kind: symbolRefKindSchema, + /** The nearest named declaration around the ref, an index into `targets`; null for module code. */ + source: z.number().int().nonnegative().nullable(), /** An index into `targets`; null when the checker binds nothing here (`unbound` says why). */ target: z.number().int().nonnegative().nullable(), unbound: z.enum(["unresolved", "any"]).nullable(), @@ -37,7 +39,7 @@ export const symbolRefsResultSchema = z.strictObject({ outcome: outcomeSchema, ...generationFields, reason: z.string().nullable(), - /** Each declaration that some ref binds to, once. */ + /** Each declaration that some ref binds to or sits in, once. */ targets: z.array(symbolRefTargetSchema), files: z.array(z.strictObject({ file: z.string(), refs: z.array(symbolRefSchema) })), counts: z.strictObject({ diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts index 0f98ea7f..3c0927d6 100644 --- a/engine/src/srcly/ops/symbol-refs.ts +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -1,9 +1,10 @@ +import fs from "node:fs"; import path from "node:path"; import type * as TypeScript from "typescript"; import type { AnalysisCancellationToken } from "../../analysis/cancellation"; import { symbolRefsResultSchema, type SymbolRef, type SymbolRefTarget, type SymbolRefsResult } from "../contracts/symbol-refs"; import { EngineError } from "../protocol"; -import { checkGeneration, requireTypescript, type EngineSession } from "../session"; +import { checkGeneration, requireTypescript, type EngineSession, type TsTier1 } from "../session"; type Ts = typeof TypeScript; type Kind = SymbolRef["kind"]; @@ -22,7 +23,7 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; throw new EngineError("invalid-request", "symbolRefs params.files must be a list of paths"); } const { ts, program } = tier1; - const checker = program.getTypeChecker(); + const primaryChecker = program.getTypeChecker(); const root = path.resolve(tier1.root); const rel = (file: string) => path.relative(root, file).split(path.sep).join("/"); const own = (source: TypeScript.SourceFile) => source.fileName.startsWith(root + path.sep) && !source.fileName.includes(`${path.sep}node_modules${path.sep}`) && !source.isDeclarationFile; @@ -43,13 +44,20 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; } return index; }; - const files = sources.map((source) => { + const ownerOf = owners(tier1); + const toSource = workspaceSources(tier1, root); + const files = sources.map((primary) => { cancellation?.throwIfCancelled(); + // A file whose own tsconfig resolves imports differently binds in that config's Program. + const routed = ownerOf(primary.fileName); + const source: TypeScript.SourceFile = routed?.program.getSourceFile(primary.fileName) ?? primary; + const checker: TypeScript.TypeChecker = routed?.checker ?? primaryChecker; const refs: SymbolRef[] = []; const visit = (node: TypeScript.Node) => { if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { - const ref = bind(ts, checker, source, node, own, intern); + const ref = bind(ts, checker, source, node, own, intern, toSource); if (ref === "skip") return; + if (ref !== "external") ref.source = enclosing(ts, node, source, intern); if (ref === "external") counts.external += 1; else { if (ref.target) counts.bound += 1; @@ -61,7 +69,7 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; ts.forEachChild(node, visit); }; visit(source); - return { file: rel(source.fileName), refs }; + return { file: rel(primary.fileName), refs }; }); return symbolRefsResultSchema.parse({ @@ -78,6 +86,109 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; }); } +type Routed = { program: TypeScript.Program; checker: TypeScript.TypeChecker }; +const routedByTier = new WeakMap>(); + +/** + * The Program a file binds in, when it is not the primary. The primary Program uses one + * config's options, so a file whose nearest config declares other `paths` or `baseUrl` + * (a monorepo app beside the package) would resolve `@/x` against the wrong folder. + * Such a config gets its own Program, built on first use and kept with the tier. + */ +function owners(tier1: TsTier1): (file: string) => Routed | undefined { + const { ts, resolution } = tier1; + const primary = resolution.primary; + const resolves = (o: TypeScript.CompilerOptions) => JSON.stringify([o.paths ?? null, o.paths ? (o.pathsBasePath ?? o.baseUrl ?? null) : (o.baseUrl ?? null)]); + const differs = resolution.configs.filter((c) => c.file !== primary.file && c.fileNames.length > 0 && resolves(c.options) !== resolves(primary.options)); + if (!differs.length) return () => undefined; + const nearest = new Map(); + for (const config of [primary, ...differs]) { + const dir = path.dirname(config.file); + for (const file of config.fileNames) { + const seen = nearest.get(file); + if (!seen || dir.length > path.dirname(seen.file).length) nearest.set(file, config); + } + } + let built = routedByTier.get(tier1); + if (!built) routedByTier.set(tier1, (built = new Map())); + const cache = built; + return (file) => { + const config = nearest.get(file); + if (!config || config.file === primary.file) return undefined; + let routed = cache.get(config.file); + if (!routed) { + const program = ts.createProgram(config.fileNames, config.options); + routed = { program, checker: program.getTypeChecker() }; + cache.set(config.file, routed); + } + return routed; + }; +} + +/** + * A workspace package's import, followed to the package's source the way srcly's import + * graph does (`typescript_deps.py`): `pkg/sub` is `/sub` or `/src/sub`, and `pkg` + * alone is its `source` or `src/index`. The export is then looked up in that module by the + * checker. Only a package under the root that is not in `node_modules` counts. + */ +function workspaceSources(tier1: TsTier1, root: string) { + const { ts, program } = tier1; + let packages: Map | null = null; + const known = () => { + if (packages) return packages; + packages = new Map(); + const seen = new Set(); + for (const source of program.getSourceFiles()) { + if (source.isDeclarationFile || !source.fileName.startsWith(root + path.sep) || source.fileName.includes("/node_modules/")) continue; + for (let dir = path.dirname(source.fileName); dir.startsWith(root) && !seen.has(dir); dir = path.dirname(dir)) { + seen.add(dir); + const manifest = path.join(dir, "package.json"); + if (!fs.existsSync(manifest)) continue; + try { + const name = (JSON.parse(fs.readFileSync(manifest, "utf8")) as { name?: unknown }).name; + if (typeof name === "string" && !packages.has(name)) packages.set(name, dir); + } catch { + // An unreadable manifest names no package. + } + } + } + return packages; + }; + const extensions = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"]; + const moduleOf = (spec: string): TypeScript.SourceFile | undefined => { + const names = [...known().keys()].filter((name) => spec === name || spec.startsWith(name + "/")).sort((a, b) => b.length - a.length); + for (const name of names) { + const dir = known().get(name)!; + const rest = spec.slice(name.length + 1); + const bases = rest ? [path.join(dir, rest), path.join(dir, "src", rest)] : [path.join(dir, "src", "index"), dir]; + for (const base of bases) { + for (const ext of ["", ...extensions]) { + const hit = program.getSourceFile(base + ext); + if (hit && !hit.isDeclarationFile) return hit; + } + } + } + return undefined; + }; + // The package's source is in the primary Program, whichever Program bound the import. + const checker = program.getTypeChecker(); + return (alias: TypeScript.Symbol): TypeScript.Symbol | undefined => { + const declaration = alias.declarations?.[0]; + if (!declaration) return undefined; + let at: TypeScript.Node | undefined = declaration; + while (at && !ts.isImportDeclaration(at) && !ts.isExportDeclaration(at)) at = at.parent; + const specifier = at && (at as TypeScript.ImportDeclaration | TypeScript.ExportDeclaration).moduleSpecifier; + if (!specifier || !ts.isStringLiteral(specifier) || specifier.text.startsWith(".")) return undefined; + const module = moduleOf(specifier.text); + const moduleSymbol = module && checker.getSymbolAtLocation(module); + if (!moduleSymbol) return undefined; + if (ts.isNamespaceImport(declaration)) return moduleSymbol; + const exported = ts.isImportClause(declaration) ? "default" : ((declaration as TypeScript.ImportSpecifier).propertyName ?? (declaration as TypeScript.ImportSpecifier).name).text; + const member = checker.tryGetMemberInModuleExports(exported, moduleSymbol); + return member && member.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(member) : member; + }; +} + function bind( ts: Ts, checker: TypeScript.TypeChecker, @@ -85,6 +196,7 @@ function bind( node: TypeScript.Identifier | TypeScript.PrivateIdentifier, own: (source: TypeScript.SourceFile) => boolean, intern: (decl: TypeScript.Declaration, home: TypeScript.SourceFile) => number, + toSource: (alias: TypeScript.Symbol) => TypeScript.Symbol | undefined, ): SymbolRef | "external" | "skip" { const parent = node.parent; if (!parent || skipped(ts, node, parent)) return "skip"; @@ -94,11 +206,18 @@ function bind( const position = typePosition(ts, node); const inType = position !== "code"; let symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(parent) : checker.getSymbolAtLocation(node); - if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); + const alias = symbol && symbol.flags & ts.SymbolFlags.Alias ? symbol : undefined; + if (alias) symbol = checker.getAliasedSymbol(alias); const start = source.getLineAndCharacterOfPosition(node.getStart(source)); - const ref = { line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind: inType ? ("type" as Kind) : kindOf(ts, node) }; + const ref = { source: null as number | null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind: inType ? ("type" as Kind) : kindOf(ts, node) }; // `typeof x` in a type names the value x. - const decl = symbol ? pick(ts, symbol, position === "type") : undefined; + let decl = symbol ? pick(ts, symbol, position === "type") : undefined; + // An import of a workspace package lands in its built `.d.ts`: bind the same export in its source. + if (alias && decl?.getSourceFile().isDeclarationFile) { + const fromSource = toSource(alias); + const sourceDecl = fromSource ? pick(ts, fromSource, position === "type") : undefined; + if (sourceDecl) decl = sourceDecl; + } if (!decl) { const receiver = ts.isPropertyAccessExpression(parent) && parent.name === node ? parent.expression : null; const any = receiver ? (checker.getTypeAtLocation(receiver).flags & ts.TypeFlags.Any) !== 0 : false; @@ -115,6 +234,9 @@ function skipped(ts: Ts, node: TypeScript.Node, parent: TypeScript.Node): boolea if (ts.isLabeledStatement(parent) || ts.isBreakOrContinueStatement(parent)) return true; if (ts.isJsxClosingElement(parent)) return true; if (ts.isMetaProperty(parent)) return true; + // `as const` is a keyword written as a type name; `undefined` is a value with no declaration. + if (ts.isTypeReferenceNode(parent) && ts.isConstTypeReference(parent)) return true; + if (ts.isIdentifier(node) && node.text === "undefined" && !ts.isPropertyAccessExpression(parent)) return true; // The tag name's right side in `` is still a use; a JSX attribute name is a prop declaration. return ts.isJsxAttribute(parent) && parent.name === node; } @@ -155,12 +277,38 @@ function kindOf(ts: Ts, node: TypeScript.Node): Kind { /** `ts.isDeclaration` is internal to TypeScript; it is on the runtime object of every supported version. */ const isDeclaration = (ts: Ts, node: TypeScript.Node) => (ts as unknown as { isDeclaration(n: TypeScript.Node): boolean }).isDeclaration(node); +/** The nearest named declaration a node sits in: a function, class, member, variable or type. */ +function enclosing(ts: Ts, node: TypeScript.Node, home: TypeScript.SourceFile, intern: (decl: TypeScript.Declaration, home: TypeScript.SourceFile) => number): number | null { + for (let at = node.parent; at && !ts.isSourceFile(at); at = at.parent) { + const named = + // An overload signature has no body; the implementation is the declaration. + (ts.isFunctionDeclaration(at) && at.body !== undefined) || + ts.isClassDeclaration(at) || + ts.isMethodDeclaration(at) || + ts.isGetAccessorDeclaration(at) || + ts.isSetAccessorDeclaration(at) || + ts.isPropertyDeclaration(at) || + ts.isPropertyAssignment(at) || + ts.isInterfaceDeclaration(at) || + ts.isTypeAliasDeclaration(at) || + ts.isEnumDeclaration(at) || + (ts.isVariableDeclaration(at) && ts.isIdentifier(at.name)); + // `node` itself may be the declaration's name (`{ action }`); the name is in its declaration. + if (named && (at as TypeScript.NamedDeclaration).name) return intern(at as TypeScript.Declaration, home); + if (ts.isConstructorDeclaration(at)) return intern(at, home); + } + return null; +} + const isTypeDecl = (ts: Ts, d: TypeScript.Declaration) => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d); /** The declaration the location means: in a type, a type-side one; in code, a value-side one. */ function pick(ts: Ts, symbol: TypeScript.Symbol, inType: boolean): TypeScript.Declaration | undefined { const decls = symbol.declarations ?? []; if (decls.length < 2) return decls[0]; + // Overload signatures, then the body: the body is the declaration. + const body = decls.find((d) => ts.isFunctionLike(d) && (d as { body?: TypeScript.Node }).body !== undefined); + if (body && decls.every((d) => ts.isFunctionLike(d))) return body; const typeSide = decls.find((d) => isTypeDecl(ts, d) || ts.isClassDeclaration(d) || ts.isEnumDeclaration(d)); const valueSide = decls.find((d) => !isTypeDecl(ts, d)); return (inType ? typeSide : valueSide) ?? decls[0]; @@ -170,7 +318,7 @@ function targetOf(ts: Ts, decl: TypeScript.Declaration, home: TypeScript.SourceF const file = rel(home.fileName); if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, meaning: "value", scope: "module" }; const name = ts.getNameOfDeclaration(decl); - const text = name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; + const text = ts.isConstructorDeclaration(decl) ? "constructor" : name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; const at = home.getLineAndCharacterOfPosition((name ?? decl).getStart(home)); return { file, name: text, line: at.line + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; } diff --git a/engine/src/srcly/session.ts b/engine/src/srcly/session.ts index 3752d156..f0d2fcd5 100644 --- a/engine/src/srcly/session.ts +++ b/engine/src/srcly/session.ts @@ -2,6 +2,7 @@ import path from "node:path"; import type * as TypeScript from "typescript"; import { parseArgs } from "../cli/args"; import { createAnalyzer } from "../core"; +import type { ProgramResolution } from "../project/typescript"; import { createCompleteProgramEvidenceProvider, createLazyProgramEvidenceProvider, type EvidenceRelationProvider } from "../analysis/evidence-relation-provider"; import type { AnalysisCancellationToken } from "../analysis/cancellation"; import { ProgramEvidenceCollector } from "../analysis/program-evidence-collector"; @@ -86,6 +87,8 @@ export type TsTier1 = BaseTier1 & { surface: (routeKey: string, cancellation?: AnalysisCancellationToken) => RouteSurfaceRecord | null; /** Tier 2: the full legacy report. Slow; only batch signals call it. */ fullReport: () => AnalysisReport; + /** The tsconfigs found and the primary one, whose options the Program uses. */ + resolution: ProgramResolution; }; export type Tier1 = TsTier1 | PythonTier1; @@ -220,6 +223,7 @@ export function createEngineSession(config: EngineConfig, progress?: AnalyzerPro return totality; }, fullReport: () => (report ??= analyzer.report()), + resolution: analyzer.resolution, }; built.host = createTypescriptHost(built); return built; diff --git a/server/app/models.py b/server/app/models.py index 4a3b8e0e..9b338439 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -1,4 +1,4 @@ -from typing import Any, List +from typing import Any, Dict, List from pydantic import BaseModel, Field, PrivateAttr class Witness(BaseModel): @@ -291,6 +291,13 @@ class SymbolIndexInfo(BaseModel): # Client requests joined to a handler of the index, and ones nothing answers. http_links: int = Field(0, alias="httpLinks") http_unmatched: int = Field(0, alias="httpUnmatched") + # Who bound the TypeScript references, "checker" or "tree-sitter", and why not the checker. + binder: str = "tree-sitter" + binder_reason: str | None = Field(None, alias="binderReason") + # Checker mode: unbound references by reason, module declarations that joined no symbol, TS files outside the Program. + unbound: Dict[str, int] = Field(default_factory=dict) + mismatched: int = 0 + outside_program: int = Field(0, alias="outsideProgram") class SymbolGraph(BaseModel): diff --git a/server/app/routers/symbols.py b/server/app/routers/symbols.py index c04fe8c6..16433a2e 100644 --- a/server/app/routers/symbols.py +++ b/server/app/routers/symbols.py @@ -41,7 +41,7 @@ def get_symbol_graph( chosen = [k for k in kinds.split(",") if k in REF_KINDS] if not chosen: raise HTTPException(status_code=400, detail=f"kinds must be some of {', '.join(REF_KINDS)}") - index = build_symbol_index(_root(path)) + index = build_symbol_index(_root(path), binder="checker") opened = [m for m in (more or "").split(",") if m] graph = index.neighbourhood(at, hops=hops, kinds=chosen, include_tests=tests, direction=direction, members=members, more=opened) if graph is None: @@ -52,7 +52,7 @@ def get_symbol_graph( @router.get("/search", response_model=SymbolSearch, response_model_exclude_none=True, response_model_by_alias=True) def search_symbols(path: str | None = None, q: str = Query("", max_length=200), limit: int = Query(30, ge=1, le=200), tests: bool = True): """Symbols whose name, qualified name or file contains `q`, best match first, with their reference counts.""" - index = build_symbol_index(_root(path)) + index = build_symbol_index(_root(path), binder="checker") return SymbolSearch(hits=index.search(q, limit=limit, include_tests=tests), index=index.info()) @@ -70,7 +70,7 @@ def get_symbol_path( chosen = [k for k in kinds.split(",") if k in REF_KINDS] if not chosen: raise HTTPException(status_code=400, detail=f"kinds must be some of {', '.join(REF_KINDS)}") - index = build_symbol_index(_root(path)) + index = build_symbol_index(_root(path), binder="checker") result = index.path(start, end, kinds=chosen, include_tests=tests) if result is None: missing = start if start not in index.symbols else end @@ -81,4 +81,4 @@ def get_symbol_path( @router.get("/stats", response_model=SymbolStats, response_model_exclude_none=True, response_model_by_alias=True) def get_symbol_stats(path: str | None = None, limit: int = Query(50, ge=1, le=500), hubs: int = Query(30, ge=1, le=200)): """Symbols nothing references (private first, then largest), the ones only test files reference, and the top hubs.""" - return build_symbol_index(_root(path)).stats(limit=limit, hubs=hubs) + return build_symbol_index(_root(path), binder="checker").stats(limit=limit, hubs=hubs) diff --git a/server/app/services/dataflow/contracts/symbolRefs.schema.json b/server/app/services/dataflow/contracts/symbolRefs.schema.json index 6e0871aa..941f1df1 100644 --- a/server/app/services/dataflow/contracts/symbolRefs.schema.json +++ b/server/app/services/dataflow/contracts/symbolRefs.schema.json @@ -121,6 +121,18 @@ "implements" ] }, + "source": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, "target": { "anyOf": [ { @@ -153,6 +165,7 @@ "column", "endColumn", "kind", + "source", "target", "unbound" ], diff --git a/server/app/services/dataflow/models.py b/server/app/services/dataflow/models.py index b3416e48..e99b2c8b 100644 --- a/server/app/services/dataflow/models.py +++ b/server/app/services/dataflow/models.py @@ -524,6 +524,52 @@ class FileExportsResponse(BaseModel): exports: FileExportsResult | None = None +# ---- symbol refs (contracts/symbolRefs.schema.json) --------------------------- + + +class SymbolRefTarget(BaseModel): + file: str + name: str + line: int + meaning: Literal["value", "type"] + scope: Literal["module", "member", "local"] + + +class SymbolRef(BaseModel): + line: int + column: int + endColumn: int + kind: Literal["call", "instantiate", "read", "write", "type", "extends", "implements"] + source: int | None + target: int | None + unbound: Literal["unresolved", "any"] | None + + +class SymbolRefsFile(BaseModel): + file: str + refs: list[SymbolRef] + + +class SymbolRefsCounts(BaseModel): + files: int + bound: int + unbound: int + external: int + + +class SymbolRefsResult(BaseModel): + outcome: Outcome + generation: int + programHash: str + tsconfig: str + typescript: str + nullProof: bool + reason: str | None + targets: list[SymbolRefTarget] + files: list[SymbolRefsFile] + counts: SymbolRefsCounts + + # ---- function effects (contracts/functionEffects.schema.json) ---------------- diff --git a/server/app/services/symbols/checker.py b/server/app/services/symbols/checker.py new file mode 100644 index 00000000..449ae727 --- /dev/null +++ b/server/app/services/symbols/checker.py @@ -0,0 +1,126 @@ +""" +TypeScript references bound by the data-flow engine's checker (``symbolRefs``), +joined to the tree-sitter index's own ids (docs/intent/checker-symbol-index). + +Tree-sitter keeps every declaration and id. The checker says, for each +identifier, which declaration TypeScript binds: a file, a name, the line of +the name and a meaning (``value`` or ``type``). The join picks the innermost +tree-sitter symbol of that file and name whose lines hold that line, on the +side the meaning asks for (``file#A`` or ``file#A@type``). A reference's source +is the declaration the checker says it sits in, joined the same way; failing +that, the innermost symbol whose lines hold the reference. An unbound reference +stays out of the graph and is counted by reason. +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Optional, Set, Tuple + +from app.services.dataflow.models import SymbolRefsResult, SymbolRefTarget +from app.services.symbols.model import Reference, Symbol +from app.services.symbols.typescript import TYPE_ID_SUFFIX + + +@dataclass +class CheckerRefs: + """What the checker bound, joined to tree-sitter ids, and how much of it did not join.""" + + files: Set[str] + references: List[Reference] + unbound: Counter = field(default_factory=Counter) # reason → count + # A module-scope declaration the checker binds that no tree-sitter symbol holds: a mapping bug, listed. + mismatched: List[str] = field(default_factory=list) + generation: Optional[int] = None + program_hash: Optional[str] = None + + +def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Optional[str]]: + """The engine's ``symbolRefs`` for the root, or None and the reason it has none.""" + from app.services.dataflow.engine import EngineError + from app.services.dataflow.engine import registry as shared + + reg = registry if registry is not None else shared + found = reg.probe(root) + if not found.available: + return None, found.reason or "not-analyzed" + if found.language != "typescript": + return None, "python-root" + known = reg.failure(root) + if known is not None: + return None, known.code + try: + # A walk of the whole program: allow more than one ordinary query. + raw = reg.query(root, "symbolRefs", {}, timeout=180.0) + except EngineError as exc: + return None, exc.code + return SymbolRefsResult.model_validate(raw), None + + +_HOLDERS = frozenset({"type", "class", "enum", "variable"}) + + +class _Files: + """Each file's symbols, by name and by line span, for the join.""" + + def __init__(self, symbols: Dict[str, Symbol]): + self.by_name: Dict[Tuple[str, str], List[Symbol]] = defaultdict(list) + self.by_file: Dict[str, List[Symbol]] = defaultdict(list) + for s in symbols.values(): + if s.language != "ts" or s.kind == "module": + continue + self.by_name[(s.file, s.name)].append(s) + self.by_file[s.file].append(s) + self._sources: Dict[Tuple[str, int], str] = {} + self.modules = {s.file for s in symbols.values() if s.kind == "module"} | {s.id for s in symbols.values() if s.kind == "module"} + + def target(self, t: SymbolRefTarget) -> Optional[str]: + if t.name == "*": + return t.file if t.file in self.modules else None + want_type = t.meaning == "type" + held = [s for s in self.by_name.get((t.file, t.name), ()) if s.line <= t.line <= s.end_line] + if not held and t.scope == "member": + # A member the index keeps no symbol for (an interface's field, an object type's member): + # the type, class or variable that declares it, as a typed receiver gives today. + held = [s for s in self.by_file.get(t.file, ()) if s.kind in _HOLDERS and s.line <= t.line <= s.end_line] + if not held: + return None + # The side the meaning asks for first, then the innermost span. + best = min(held, key=lambda s: (s.id.endswith(TYPE_ID_SUFFIX) != want_type, s.end_line - s.line, -s.line)) + return best.id + + def source(self, file: str, line: int) -> str: + key = (file, line) + hit = self._sources.get(key) + if hit is None: + hit = self._sources[key] = self._innermost(file, line) + return hit + + def _innermost(self, file: str, line: int) -> str: + held = [s for s in self.by_file.get(file, ()) if s.line <= line <= s.end_line] + if not held: + return file + return min(held, key=lambda s: (s.end_line - s.line, -s.line)).id + + +def join(result: SymbolRefsResult, symbols: Dict[str, Symbol]) -> CheckerRefs: + files = _Files(symbols) + targets = [files.target(t) for t in result.targets] + mismatched = sorted({f"{t.file}:{t.line} {t.name} ({t.meaning})" for t, sid in zip(result.targets, targets) if sid is None and t.scope == "module" and t.name != "*"}) + out = CheckerRefs(files={f.file for f in result.files}, references=[], mismatched=mismatched, generation=result.generation, program_hash=result.programHash) + for f in result.files: + for r in f.refs: + if r.target is None: + out.unbound[r.unbound or "unresolved"] += 1 + continue + target = targets[r.target] + if target is None: + continue + # The enclosing declaration's symbol, else the innermost symbol holding the line. + source = (targets[r.source] if r.source is not None else None) or files.source(f.file, r.line) + if source == target: + continue + out.references.append(Reference(source=source, target=target, kind=r.kind, line=r.line, column=r.column, end_column=r.endColumn)) + return out diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 13c9db13..324d6f84 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -16,6 +16,9 @@ from app.models import SymbolGraph, SymbolGraphEdge, SymbolGraphNode, SymbolIndexInfo, SymbolPath, SymbolSearchHit, SymbolStats from app.services.deps.common import SourceSignature, is_test_path, source_signature, walk_source_files from app.services.deps.typescript_deps import TS_EXTENSIONS +from app.services.dataflow.models import SymbolRefsResult as CheckerResult +from app.services.symbols.checker import join +from app.services.symbols.checker import query as query_checker from app.services.symbols.model import BUILTIN_MEMBERS, REF_KINDS, FileSymbols, PendingMember, RefKind, Reference, Symbol # Lines kept per merged edge in a response. @@ -41,6 +44,13 @@ class SymbolIndex: http_unmatched: int = 0 # member name → ids of every method / field with that name, for name-only resolution members_by_name: Dict[str, List[str]] = field(default_factory=lambda: defaultdict(list)) + # Who bound the TypeScript references: "checker" (the data-flow engine) or "tree-sitter", and why not the checker. + binder: str = "tree-sitter" + binder_reason: Optional[str] = None + # Checker mode: unbound references by reason, module declarations no symbol holds, TS files outside the Program. + unbound: Dict[str, int] = field(default_factory=dict) + mismatched: List[str] = field(default_factory=list) + outside_program: int = 0 def __post_init__(self) -> None: for i, r in enumerate(self.references): @@ -340,6 +350,11 @@ def info(self) -> SymbolIndexInfo: built_ms=self.built_ms, http_links=self.http_links, http_unmatched=self.http_unmatched, + binder=self.binder, + binder_reason=self.binder_reason, + unbound=dict(self.unbound), + mismatched=len(self.mismatched), + outside_program=self.outside_program, ) @@ -353,8 +368,12 @@ def _weaker(a: str, b: str) -> str: # ---- building ---- -def assemble(root: Path, parts: List[FileSymbols]) -> SymbolIndex: - """Merge every file's symbols, settle member references, drop references to nothing.""" +def assemble(root: Path, parts: List[FileSymbols], checker: Optional[CheckerResult] = None) -> SymbolIndex: + """ + Merge every file's symbols, settle member references, drop references to nothing. + With a checker result, the TypeScript files it covers take their references from it + (no member guesses); the rest keep tree-sitter's. + """ started = time.monotonic() symbols: Dict[str, Symbol] = {} for part in parts: @@ -369,8 +388,18 @@ def assemble(root: Path, parts: List[FileSymbols]) -> SymbolIndex: if sym.kind in ("method", "field"): members_by_name[sym.name].append(sym.id) + bound = join(checker, symbols) if checker is not None else None + checked = bound.files if bound is not None else set() + bound_parts = [p for p in parts if p.file in checked] + parts = [p for p in parts if p.file not in checked] + references: List[Reference] = [] unresolved = 0 + if bound is not None: + for r in bound.references: + if r.target in symbols and r.source in symbols: + references.append(r) + _note_base(r, symbols) for part in parts: for r in part.references: if r.target in symbols and r.source in symbols: @@ -395,8 +424,13 @@ def assemble(root: Path, parts: List[FileSymbols]) -> SymbolIndex: elif settled.source in symbols and settled.source != settled.target: references.append(settled) - http_links, http_unmatched = _link_http(parts, symbols, references) - index = SymbolIndex(root=root, symbols=symbols, references=references, files=len(parts), unresolved_members=unresolved) + http_links, http_unmatched = _link_http(parts + bound_parts, symbols, references) + index = SymbolIndex(root=root, symbols=symbols, references=references, files=len(parts) + len(bound_parts), unresolved_members=unresolved) + if bound is not None: + index.binder = "checker" + index.unbound = dict(bound.unbound) + index.mismatched = bound.mismatched + index.outside_program = sum(1 for p in parts if Path(p.file).suffix in TS_EXTENSIONS) index.members_by_name = members_by_name index.http_links, index.http_unmatched = http_links, http_unmatched index.built_ms = int((time.monotonic() - started) * 1000) @@ -558,19 +592,24 @@ def _demote(kind: RefKind) -> RefKind: return "write" if kind == "write" else "read" -_cache: Dict[Path, Tuple[SourceSignature, SymbolIndex]] = {} +_cache: Dict[Tuple[Path, str], Tuple[SourceSignature, SymbolIndex]] = {} _lock = threading.Lock() SOURCE_EXTENSIONS = TS_EXTENSIONS | {".py"} -def build_symbol_index(root: Path, use_cache: bool = True) -> SymbolIndex: +def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-sitter", registry=None) -> SymbolIndex: + """ + The index of a root. ``binder="checker"`` binds TypeScript references with the data-flow + engine when it can, and falls back to tree-sitter with the reason; ``"tree-sitter"`` never + starts the engine. ``registry`` is the engine registry to use (the server's by default). + """ root = root.resolve() files = walk_source_files(root, SOURCE_EXTENSIONS) if use_cache: sig = source_signature(files) with _lock: - hit = _cache.get(root) + hit = _cache.get((root, binder)) if hit is not None and hit[0] == sig: return hit[1] parts: List[FileSymbols] = [] @@ -586,8 +625,14 @@ def build_symbol_index(root: Path, use_cache: bool = True) -> SymbolIndex: py_parts, _py_program = extract_py(root, py_files) parts.extend(py_parts) - index = assemble(root, parts) + checked: Optional[CheckerResult] = None + reason: Optional[str] = None + if ts_files and binder == "checker": + checked, reason = query_checker(root, registry) + index = assemble(root, parts, checked) + if index.binder != "checker": + index.binder_reason = reason if binder == "checker" else "asked" if use_cache: with _lock: - _cache[root] = (sig, index) + _cache[(root, binder)] = (sig, index) return index diff --git a/server/app/services/symbols/model.py b/server/app/services/symbols/model.py index e46a2d07..f04e152c 100644 --- a/server/app/services/symbols/model.py +++ b/server/app/services/symbols/model.py @@ -105,6 +105,9 @@ class Reference: resolution: Resolution = "exact" # An HTTP reference: the request as matched, `GET /api/items/{id}`. via: Optional[str] = None + # A checker-bound reference: the identifier's 1-based UTF-16 columns, end exclusive. None from tree-sitter. + column: Optional[int] = None + end_column: Optional[int] = None @dataclass diff --git a/server/app/services/symbols/refs.py b/server/app/services/symbols/refs.py index e7bfe95a..ffe02bbf 100644 --- a/server/app/services/symbols/refs.py +++ b/server/app/services/symbols/refs.py @@ -54,6 +54,9 @@ def build(idx: SymbolIndex, query: str, tests: bool = True) -> dict: return { "query": query, "root": str(idx.root), + # Who bound the TypeScript names: the engine's checker, or tree-sitter with the reason. + "binder": idx.binder, + "binderReason": idx.binder_reason, "declarations": [ { "id": s.id, @@ -82,7 +85,9 @@ def render(payload: dict, limit: int) -> str: if payload["suggestions"]: lines.append("Did you mean: " + ", ".join(payload["suggestions"])) return "\n".join(lines) - out = [f"{payload['query']}: {_count(len(decls), 'declaration')}"] + binder = payload.get("binder", "tree-sitter") + how = "bound by the TypeScript checker" if binder == "checker" else f"bound by tree-sitter names ({payload.get('binderReason') or 'no checker'})" + out = [f"{payload['query']}: {_count(len(decls), 'declaration')} · {how}"] for d in decls: flag = "exported" if d["exported"] else "not exported" out.append("") @@ -109,5 +114,13 @@ def render(payload: dict, limit: int) -> str: def run(root: Path, query: str, fmt: str = "md", limit: int = 20, tests: bool = True) -> str: - payload = build(build_symbol_index(root, use_cache=False), query, tests=tests) + from app.services.dataflow.engine import EngineRegistry + + # The checker binds TypeScript names when Node and the engine are there; this run's engine closes with it. + registry = EngineRegistry() + try: + idx = build_symbol_index(root, use_cache=False, binder="checker", registry=registry) + finally: + registry.close_all() + payload = build(idx, query, tests=tests) return json.dumps(payload, indent=2) if fmt == "json" else render(payload, limit) diff --git a/server/scripts/compare_binders.py b/server/scripts/compare_binders.py new file mode 100644 index 00000000..107bd207 --- /dev/null +++ b/server/scripts/compare_binders.py @@ -0,0 +1,116 @@ +"""Compare the checker-bound and the tree-sitter symbol index on every TypeScript reference of a root. + + cd server && uv run python scripts/compare_binders.py [--samples 20] [--json out.json] + +A reference is keyed by (source file, line, target id), counted as a multiset. A key in +both indexes agrees; the rest are bucketed by how tree-sitter resolved it (``exact``, +``typed``, ``name``) or by the checker reference's kind and target kind. See +docs/intent/checker-symbol-index ("Proof at product scope"). +""" + +from __future__ import annotations + +import argparse +import json +import random +import sys +import time +from collections import Counter, defaultdict +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.services.dataflow.engine import EngineRegistry # noqa: E402 +from app.services.symbols.index import SymbolIndex, build_symbol_index # noqa: E402 + + +def _ts_refs(idx: SymbolIndex): + for r in idx.references: + src = idx.symbols.get(r.source) + if src is None or src.language != "ts" or r.kind == "http": + continue + yield (src.file, r.line, r.target), r + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("root") + ap.add_argument("--samples", type=int, default=20) + ap.add_argument("--json") + args = ap.parse_args() + root = Path(args.root).resolve() + + t = time.monotonic() + tree = build_symbol_index(root, use_cache=False, binder="tree-sitter") + tree_s = time.monotonic() - t + registry = EngineRegistry() + try: + t = time.monotonic() + checked = build_symbol_index(root, use_cache=False, binder="checker", registry=registry) + checked_s = time.monotonic() - t + finally: + registry.close_all() + if checked.binder != "checker": + print(f"checker unavailable: {checked.binder_reason}", file=sys.stderr) + return 2 + + tree_refs = defaultdict(list) + for key, r in _ts_refs(tree): + tree_refs[key].append(r) + checked_refs = defaultdict(list) + for key, r in _ts_refs(checked): + checked_refs[key].append(r) + + agree = 0 + kind_differs = Counter() + buckets = defaultdict(list) + for key in set(tree_refs) | set(checked_refs): + a, b = tree_refs.get(key, []), checked_refs.get(key, []) + both = min(len(a), len(b)) + agree += both + for ra, rb in zip(a, b): + if ra.kind != rb.kind: + kind_differs[f"{ra.kind} -> {rb.kind}"] += 1 + target = checked.symbols.get(key[2]) or tree.symbols.get(key[2]) + tkind = target.kind if target else "?" + for r in a[both:]: + buckets[f"tree-sitter-only · {r.resolution} · {r.kind} -> {tkind}"].append((key, r)) + for r in b[both:]: + buckets[f"checker-only · {r.kind} -> {tkind}"].append((key, r)) + + total_tree = sum(len(v) for v in tree_refs.values()) + total_checked = sum(len(v) for v in checked_refs.values()) + rng = random.Random(0) + report = { + "root": str(root), + "seconds": {"tree-sitter": round(tree_s, 1), "checker": round(checked_s, 1)}, + "references": {"tree-sitter": total_tree, "checker": total_checked, "agree": agree}, + "symbols": len([s for s in tree.symbols.values() if s.language == "ts" and s.kind != "module"]), + "unbound": checked.unbound, + "mismatched": len(checked.mismatched), + "mismatchedSample": checked.mismatched[: args.samples], + "outsideProgram": checked.outside_program, + "kindDiffers": dict(kind_differs.most_common()), + "buckets": { + name: { + "count": len(rows), + "sample": [f"{k[0]}:{k[1]} {r.source} -> {k[2]}" for k, r in rng.sample(rows, min(args.samples, len(rows)))], + } + for name, rows in sorted(buckets.items(), key=lambda kv: -len(kv[1])) + }, + } + text = json.dumps(report, indent=2) + if args.json: + Path(args.json).write_text(text) + else: + print(text) + print( + f"{root.name}: tree-sitter {total_tree}, checker {total_checked}, agree {agree}, " + f"mismatched {len(checked.mismatched)}, outside program {checked.outside_program}, unbound {dict(checked.unbound)}", + file=sys.stderr, + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/server/tests/test_dataflow_models.py b/server/tests/test_dataflow_models.py index 35e61bb2..4affc41e 100644 --- a/server/tests/test_dataflow_models.py +++ b/server/tests/test_dataflow_models.py @@ -23,6 +23,7 @@ ("functionEffects", models.FunctionEffectsResult), ("routePath", models.RoutePathResult), ("fileExports", models.FileExportsResult), + ("symbolRefs", models.SymbolRefsResult), ("fileSignals", models.FileSignalsResult), ("flowSignature", models.FlowSignatureResult), ], diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py new file mode 100644 index 00000000..4038353b --- /dev/null +++ b/server/tests/test_symbol_checker_join.py @@ -0,0 +1,80 @@ +"""The checker's references joined to tree-sitter's ids (docs/intent/checker-symbol-index).""" + +from pathlib import Path + +from app.services.dataflow.models import SymbolRefsResult +from app.services.symbols.index import assemble +from app.services.symbols.typescript import extract_ts + +M = "\n".join( + [ + "export type Row = { id: number };", # 1 + "export const Row = { id: 1 };", # 2 + "export interface Shape {", # 3 + " width: number;", # 4 + "}", # 5 + "export class Store {", # 6 + " bump() {", # 7 + " return 1;", # 8 + " }", # 9 + "}", # 10 + "export function use(s: Store, shape: Shape) {", # 11 + " s.bump();", # 12 + " const r: Row = Row;", # 13 + " return shape.width;", # 14 + "}", # 15 + "declare function ambient(): void;", # 16 + ] +) + + +def _result(targets, refs, file="src/m.ts"): + return SymbolRefsResult.model_validate( + { + "outcome": "ok", + "generation": 1, + "programHash": "h", + "tsconfig": "", + "typescript": "5", + "nullProof": True, + "reason": None, + "targets": [dict(zip(("file", "name", "line", "meaning", "scope"), t)) for t in targets], + "files": [{"file": file, "refs": [dict(zip(("line", "column", "endColumn", "kind", "source", "target", "unbound"), r)) for r in refs]}], + "counts": {"files": 1, "bound": 0, "unbound": 0, "external": 0}, + } + ) + + +def test_checker_refs_join_to_tree_sitter_ids(tmp_path: Path): + (tmp_path / "src").mkdir() + (tmp_path / "src" / "m.ts").write_text(M, encoding="utf-8") + parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "m.ts"]) + targets = [ + ("src/m.ts", "use", 11, "value", "module"), # 0 + ("src/m.ts", "bump", 7, "value", "member"), # 1 + ("src/m.ts", "Row", 1, "type", "module"), # 2 + ("src/m.ts", "Row", 2, "value", "module"), # 3 + ("src/m.ts", "width", 4, "value", "member"), # 4: an interface field: no symbol of its own + ("src/m.ts", "ambient", 16, "value", "module"), # 5: a `declare function` the index keeps no symbol for + ] + refs = [ + (12, 5, 9, "call", 0, 1, None), + (13, 12, 15, "type", 0, 2, None), + (13, 18, 21, "read", 0, 3, None), + (14, 16, 21, "read", 0, 4, None), + (14, 3, 9, "read", 0, None, "any"), + (16, 1, 8, "call", None, 5, None), + ] + idx = assemble(tmp_path, parts, _result(targets, refs)) + got = {(r.source, r.kind, r.target, r.line, r.column) for r in idx.references} + use = "src/m.ts#use" + assert (use, "call", "src/m.ts#Store.bump", 12, 5) in got + # One name, two symbols: the position's meaning picks the side. + assert (use, "type", "src/m.ts#Row@type", 13, 12) in got + assert (use, "read", "src/m.ts#Row", 13, 18) in got + # A member with no symbol joins the type that declares it. + assert (use, "read", "src/m.ts#Shape", 14, 16) in got + # Nothing is guessed: no tree-sitter `typed` or `name` reference is left for the file. + assert {r.resolution for r in idx.references} == {"exact"} + assert idx.binder == "checker" and idx.unbound == {"any": 1} + assert idx.mismatched == ["src/m.ts:16 ambient (value)"] From 38dd19948430adfc979c8bfc1c15caf644b0b142 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:19:22 -0500 Subject: [PATCH 06/13] feat(symbols): Show references resolves the symbol by source position Co-Authored-By: Claude Opus 5.5 --- client/e2e/symbols.spec.ts | 47 +++++++++++++++++++ client/src/components/CodeModal/CodeModal.tsx | 21 ++++----- .../src/investigation/valueFlowInspector.ts | 11 +++-- client/src/symbols/api.ts | 7 ++- client/src/symbols/contract.ts | 14 ++++++ client/src/viz/deps/symbols/SymbolsView.tsx | 2 + server/app/models.py | 8 ++++ server/app/routers/symbols.py | 22 +++++++-- server/app/services/symbols/index.py | 34 ++++++++++++++ server/tests/test_symbol_checker_join.py | 14 ++++++ 10 files changed, 161 insertions(+), 19 deletions(-) diff --git a/client/e2e/symbols.spec.ts b/client/e2e/symbols.spec.ts index 1b5fdfa1..8d1ae188 100644 --- a/client/e2e/symbols.spec.ts +++ b/client/e2e/symbols.spec.ts @@ -136,3 +136,50 @@ test.describe("Symbols mode paths on solid-route", () => { await expect(stats(page)).toContainText("no chain of references", { timeout: 90_000 }); }); }); + +// Show references in the code viewer resolves the name by its position, through the checker: +// `Row` is both a type and a value in src/m.ts, and each use opens its own side. +test.describe("Show references by position", () => { + const fixture = path.resolve(here, "../../engine/test/srcly/__fixtures__/symbol-refs"); + + /** Right-click the `nth` occurrence of `text` on the code line that contains `context`, then Show references. */ + async function showReferences(page: Page, context: string, text: string) { + const line = page.getByRole("dialog").locator("span.line").filter({ hasText: context }); + await line.scrollIntoViewIfNeeded(); + const point = await line.evaluate((el, word) => { + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + let all = ""; + const nodes: Text[] = []; + while (walker.nextNode()) nodes.push(walker.currentNode as Text); + for (const node of nodes) all += node.textContent; + let offset = all.indexOf(word) + 1; + for (const node of nodes) { + if (offset < node.textContent!.length) { + const range = document.createRange(); + range.setStart(node, offset); + range.setEnd(node, offset + 1); + const { x, y, width, height } = range.getBoundingClientRect(); + return { x: x + width / 2, y: y + height / 2 }; + } + offset -= node.textContent!.length; + } + throw new Error(`${word} is not rendered`); + }, text); + await page.mouse.click(point.x, point.y, { button: "right" }); + await page.locator("[data-inspect-menu][role=menu]").getByRole("menuitem", { name: /Show references/ }).click(); + } + + for (const [context, focus] of [ + ['typed: import("./m").Row', "src/m.ts#Row@type"], + ['typeof import("./m").Row', "src/m.ts#Row"], + ] as const) { + test(`a use of a split name opens ${focus}`, async ({ page }) => { + await page.goto(`/?${new URLSearchParams({ repo: fixture, view: "treemap", at: "src" })}`); + await page.getByRole("treeitem", { name: /use\.tsx/ }).click(); + await showReferences(page, context, "Row"); + await expect.poll(() => new URL(page.url()).searchParams.get("symbols"), { timeout: 90_000 }).toBe(focus); + await expect(stats(page)).toHaveAttribute("data-symbol-stats", "ready", { timeout: 90_000 }); + if (focus.endsWith("@type")) await shot(page, "symbols-show-references-by-position"); + }); + } +}); diff --git a/client/src/components/CodeModal/CodeModal.tsx b/client/src/components/CodeModal/CodeModal.tsx index 1d858e59..04e77cc8 100644 --- a/client/src/components/CodeModal/CodeModal.tsx +++ b/client/src/components/CodeModal/CodeModal.tsx @@ -13,7 +13,7 @@ import { DialogShell } from "../dialog/DialogShell"; import { MarkdownPane } from "./MarkdownPane"; import { MetricsSidebar } from "./MetricsSidebar"; import { InspectMenu } from "./InspectMenu"; -import { searchSymbols } from "../../symbols/api"; +import { fetchSymbolAt } from "../../symbols/api"; import { identifierAt } from "../../symbols/identifier"; import { refsPatch, traceAnchorPatch } from "../../navigation/nodeActions"; import { ValueFlowLedger } from "./ValueFlowLedger"; @@ -213,20 +213,17 @@ export default function CodeModal(props: CodeModalProps) { props.onClose(); go(traceAnchorPatch({ file: at, span: candidate.span }, direction)); }, - // Show references: the identifier under the caret, looked up in the symbol index (this file's symbol first). - onReferences: ({ line, column }) => { + // Show references: the symbol the index binds at the caret's position, never a search by name. + onReferences: async ({ line, column }) => { const at = props.rootPath && props.filePath ? atFromTreePath(props.filePath, props.rootPath) : null; const text = (rawCode() ?? "").split("\n")[line - 1] ?? ""; const name = identifierAt(text, column); - if (at === null || !name || !props.rootPath) return; - void searchSymbols({ path: props.rootPath, q: name, limit: 50 }).then((res) => { - const exact = res.hits.filter((h) => h.name === name); - // On a declaration, that declaration: a type and a value of one name are two symbols. - const hit = exact.find((h) => h.file === at && h.line === line) ?? exact.find((h) => h.file === at) ?? exact[0] ?? res.hits[0]; - if (!hit) return; - props.onClose(); - go(refsPatch({ at: hit.id })); - }); + if (at === null || !name || !props.rootPath) return "No name here"; + const res = await fetchSymbolAt({ path: props.rootPath, file: at, line, column, name }); + if (!res.id) return res.candidates.length ? `"${name}" could be ${res.candidates.length} symbols here` : `No symbol is bound to "${name}" here`; + props.onClose(); + go(refsPatch({ at: res.id })); + return null; }, }); /** The ledger's rows are marked through the metric overlay while this is on. */ diff --git a/client/src/investigation/valueFlowInspector.ts b/client/src/investigation/valueFlowInspector.ts index fe9b565f..ff197bb4 100644 --- a/client/src/investigation/valueFlowInspector.ts +++ b/client/src/investigation/valueFlowInspector.ts @@ -23,8 +23,8 @@ export function createValueFlowInspector(opts: { file: () => string | null; /** "Trace where it goes / comes from": open the graph anchored at the candidate. */ onTrace?: (candidate: Candidate, direction: "forward" | "backward") => void; - /** "Show references": Symbols mode centred on the name at the caret (no engine needed). */ - onReferences?: (at: { line: number; column: number }) => void; + /** "Show references": Symbols mode centred on the symbol bound at the caret; a message when there is none. */ + onReferences?: (at: { line: number; column: number }) => Promise; }) { const [menu, setMenu] = createSignal(null); const [picker, setPicker] = createSignal(null); @@ -45,7 +45,12 @@ export function createValueFlowInspector(opts: { setMenu(null); if (!at || !req) return; if (action === "references") { - opts.onReferences?.({ line: at.line, column: at.column }); + if (!opts.onReferences) return; + const mine = ++token; + setPicker({ x: at.x, y: at.y, loading: true, candidates: [], message: null, action }); + const message = await opts.onReferences({ line: at.line, column: at.column }).catch((e: unknown) => String((e as Error)?.message ?? e)); + if (mine !== token) return; + setPicker(message ? { x: at.x, y: at.y, loading: false, candidates: [], message, action } : null); return; } pending = action; diff --git a/client/src/symbols/api.ts b/client/src/symbols/api.ts index a1579a8f..fdb68d9d 100644 --- a/client/src/symbols/api.ts +++ b/client/src/symbols/api.ts @@ -1,4 +1,4 @@ -import type { SymbolGraph, SymbolPath, SymbolSearch, SymbolStats } from "./contract"; +import type { SymbolAt, SymbolGraph, SymbolPath, SymbolSearch, SymbolStats } from "./contract"; export class SymbolApiError extends Error { status: number; @@ -39,6 +39,11 @@ export function fetchSymbolStats(req: { path: string; limit?: number; hubs?: num return get("/api/symbols/stats", { path: req.path, limit: req.limit, hubs: req.hubs }); } +/** The symbol bound at a source position (1-based line, 1-based UTF-16 column): Show references. Never a name search. */ +export function fetchSymbolAt(req: { path: string; file: string; line: number; column: number; name: string }): Promise { + return get("/api/symbols/at", { path: req.path, file: req.file, line: req.line, column: req.column, name: req.name }); +} + export function searchSymbols(req: { path: string; q: string; limit?: number; tests?: boolean }): Promise { return get("/api/symbols/search", { path: req.path, q: req.q, limit: req.limit, tests: req.tests }); } diff --git a/client/src/symbols/contract.ts b/client/src/symbols/contract.ts index 83e06c23..b21d149e 100644 --- a/client/src/symbols/contract.ts +++ b/client/src/symbols/contract.ts @@ -48,6 +48,20 @@ export interface SymbolIndexInfo { /** Client requests joined to a handler of the index, and ones nothing answers. */ httpLinks?: number; httpUnmatched?: number; + /** Who bound the TypeScript references: the engine's checker, or tree-sitter names with the reason. */ + binder?: "checker" | "tree-sitter"; + binderReason?: string; + /** Checker mode: unbound references by reason, module declarations that joined no symbol, TS files outside the Program. */ + unbound?: Record; + mismatched?: number; + outsideProgram?: number; +} + +/** The symbol bound at a source position, or the candidates when the index cannot tell. */ +export interface SymbolAt { + id?: string; + candidates: string[]; + index: SymbolIndexInfo; } export interface SymbolGraph { diff --git a/client/src/viz/deps/symbols/SymbolsView.tsx b/client/src/viz/deps/symbols/SymbolsView.tsx index 991c8a7e..0fe46774 100644 --- a/client/src/viz/deps/symbols/SymbolsView.tsx +++ b/client/src/viz/deps/symbols/SymbolsView.tsx @@ -315,6 +315,8 @@ export default function SymbolsView(props: { rootPath: string; onOpen: (at: stri if (m.hiddenByKind) parts.push(`${m.hiddenByKind} hidden by the kind filters`); if (g.truncated) parts.push("cut at the neighbourhood limit: hide kinds or tests"); parts.push(`index: ${g.index.symbols.toLocaleString("en-US")} symbols, ${g.index.references.toLocaleString("en-US")} references in ${g.index.files} files`); + // Who bound the TypeScript names: the checker, or tree-sitter names and why. + if (g.index.binder) parts.push(g.index.binder === "checker" ? "TypeScript bound by the checker" : `TypeScript bound by name (${g.index.binderReason ?? "no checker"})`); if (g.index.httpLinks) parts.push(`${g.index.httpLinks} HTTP link${g.index.httpLinks === 1 ? "" : "s"} client → server${g.index.httpUnmatched ? `, ${g.index.httpUnmatched} unanswered` : ""}`); return parts.join(" · "); }; diff --git a/server/app/models.py b/server/app/models.py index 9b338439..6de31fbb 100644 --- a/server/app/models.py +++ b/server/app/models.py @@ -300,6 +300,14 @@ class SymbolIndexInfo(BaseModel): outside_program: int = Field(0, alias="outsideProgram") +class SymbolAt(BaseModel): + """The symbol bound at a source position, or the candidates when the index cannot tell.""" + + id: str | None = None + candidates: List[str] = Field(default_factory=list) + index: SymbolIndexInfo + + class SymbolGraph(BaseModel): root: str focus: str diff --git a/server/app/routers/symbols.py b/server/app/routers/symbols.py index 16433a2e..74e8894b 100644 --- a/server/app/routers/symbols.py +++ b/server/app/routers/symbols.py @@ -1,7 +1,9 @@ """ The symbol reference graph: who calls, instantiates, reads, writes, extends or -names whom, inside and across files. Built once per root by name (tree-sitter) -and cached by file mtimes; served as neighbourhoods, never whole. +names whom, inside and across files. Declarations come from tree-sitter; TypeScript +references are bound by the data-flow engine's checker when it can run, else by +name (tree-sitter). Built once per root, cached by file mtimes, and served as +neighbourhoods, never whole. """ from __future__ import annotations @@ -10,7 +12,7 @@ from fastapi import APIRouter, HTTPException, Query -from app.models import SymbolGraph, SymbolPath, SymbolSearch, SymbolStats +from app.models import SymbolAt, SymbolGraph, SymbolPath, SymbolSearch, SymbolStats from app.services.symbols.index import build_symbol_index from app.services.symbols.model import REF_KINDS @@ -56,6 +58,20 @@ def search_symbols(path: str | None = None, q: str = Query("", max_length=200), return SymbolSearch(hits=index.search(q, limit=limit, include_tests=tests), index=index.info()) +@router.get("/at", response_model=SymbolAt, response_model_exclude_none=True, response_model_by_alias=True) +def get_symbol_at( + path: str | None = None, + file: str = Query(..., description="Relative to the root"), + line: int = Query(..., ge=1), + column: int = Query(..., ge=1, description="1-based UTF-16 column"), + name: str = Query(..., max_length=200, description="The identifier at the position"), +): + """The symbol bound at a source position: Show references in the code viewer. No symbol is an answer, not a search.""" + index = build_symbol_index(_root(path), binder="checker") + found, candidates = index.at(file, line, column, name) + return SymbolAt(id=found, candidates=candidates, index=index.info()) + + @router.get("/path", response_model=SymbolPath, response_model_exclude_none=True, response_model_by_alias=True) def get_symbol_path( path: str | None = None, diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 324d6f84..63a41d7e 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -51,6 +51,7 @@ class SymbolIndex: unbound: Dict[str, int] = field(default_factory=dict) mismatched: List[str] = field(default_factory=list) outside_program: int = 0 + _by_line: Optional[Dict[Tuple[str, int], List[int]]] = None def __post_init__(self) -> None: for i, r in enumerate(self.references): @@ -341,6 +342,39 @@ def search(self, query: str, limit: int = 30, include_tests: bool = True) -> Lis scored.sort() return [self._hit(s) for _r, _n, _i, s in scored[:limit]] + def at(self, file: str, line: int, column: int, name: str) -> Tuple[Optional[str], List[str]]: + """ + The symbol bound at a source position (1-based line, 1-based UTF-16 column), and the + candidates when the index cannot tell. A reference whose span holds the column wins; + then a declaration of that name whose lines hold the line. A tree-sitter reference has + no columns, so it matches by line and target name, and several targets stay candidates. + Never a search by name alone. + """ + here = [self.references[i] for i in self._refs_on_line().get((file, line), [])] + spanned = [r for r in here if r.column is not None and r.end_column is not None and r.column <= column < r.end_column] + if spanned: + return spanned[0].target, [] + if not any(r.column is not None for r in here): + named = sorted({r.target for r in here if self.symbols[r.target].name == name}) + if len(named) == 1: + return named[0], [] + if named: + return None, named + declared = [s for s in self.symbols.values() if s.file == file and s.name == name and s.kind != "module" and s.line <= line <= s.end_line] + if declared: + return min(declared, key=lambda s: (s.end_line - s.line, -s.line)).id, [] + return None, [] + + def _refs_on_line(self) -> Dict[Tuple[str, int], List[int]]: + if self._by_line is None: + by_line: Dict[Tuple[str, int], List[int]] = defaultdict(list) + for i, r in enumerate(self.references): + src = self.symbols.get(r.source) + if src is not None: + by_line[(src.file, r.line)].append(i) + self._by_line = by_line + return self._by_line + def info(self) -> SymbolIndexInfo: return SymbolIndexInfo( symbols=sum(1 for s in self.symbols.values() if s.kind != "module"), diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py index 4038353b..18b2c6a9 100644 --- a/server/tests/test_symbol_checker_join.py +++ b/server/tests/test_symbol_checker_join.py @@ -78,3 +78,17 @@ def test_checker_refs_join_to_tree_sitter_ids(tmp_path: Path): assert {r.resolution for r in idx.references} == {"exact"} assert idx.binder == "checker" and idx.unbound == {"any": 1} assert idx.mismatched == ["src/m.ts:16 ambient (value)"] + + +def test_a_position_resolves_to_the_reference_there_never_a_name_search(tmp_path: Path): + (tmp_path / "src").mkdir() + (tmp_path / "src" / "m.ts").write_text(M, encoding="utf-8") + parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "m.ts"]) + targets = [("src/m.ts", "use", 11, "value", "module"), ("src/m.ts", "Row", 1, "type", "module"), ("src/m.ts", "Row", 2, "value", "module")] + refs = [(13, 12, 15, "type", 0, 1, None), (13, 18, 21, "read", 0, 2, None)] + idx = assemble(tmp_path, parts, _result(targets, refs)) + assert idx.at("src/m.ts", 13, 13, "Row") == ("src/m.ts#Row@type", []) + assert idx.at("src/m.ts", 13, 18, "Row") == ("src/m.ts#Row", []) + # A declaration's own name is the declaration; an unbound name is nothing, not the first search hit. + assert idx.at("src/m.ts", 1, 13, "Row") == ("src/m.ts#Row@type", []) + assert idx.at("src/m.ts", 14, 3, "shape") == (None, []) From fd20d2eee9e79bc0c441cee9f7c081aca16f33bb Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:20:04 -0500 Subject: [PATCH 07/13] docs(symbols): record the checker binder's proof and where it lives Co-Authored-By: Claude Opus 5.5 --- docs/CODE_MAP.md | 7 +++-- docs/dataflow-engine.md | 4 +-- docs/intent/checker-symbol-index/README.md | 31 ++++++++++++++++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index 4f83bcaf..ada40e68 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -338,7 +338,8 @@ Graph-to-code rule: there is one `CodeModal`. Opening from the graph resolves th Design rules: -- Matching is name-based first, and every edge says how sure it is: `resolution` is `exact`, `typed` or `name`. The client draws `name` edges as partial proof. The intended upgrade is to re-resolve a neighbourhood with the data-flow engine's checker. +- Tree-sitter makes every declaration and id. TypeScript references come from the data-flow engine's checker (`symbolRefs`) when Node and a tsconfig are there: each identifier's declaration is joined to a tree-sitter id by file, name, line and meaning (`value` or `type`), and an unbound name stays out of the graph. Without the checker, and for Python and files outside the Program (tests), references are matched by name, and every edge says how sure it is: `resolution` is `exact`, `typed` or `name`. The index says which binder ran (`binder`, `binderReason`). +- The Symbols routes and `srcly refs` start the engine (explicit use); other callers of `build_symbol_index` get tree-sitter only. - The server holds the index. The client asks only for a neighbourhood (up to 4 hops). Past 400 symbols the answer says `truncated`, and the client offers filters. - Symbol ids are `file#Qualified.name`. A top-level symbol's id equals the import graph's id, so `at`, Open code and Trace work on it. Members add `.member`. - Symbols is a third mode of the graph view. It reuses the dependency canvas, layout, palette, node menus and rail through an adapter. Nothing new is drawn by hand. @@ -350,9 +351,11 @@ Open work: backlog area `area-symbol-graph` in `pgm/data`. | Symbol and reference model: ids `file#Qualified.name`, kinds (function, class, method, field, variable, type, enum, module), reference kinds (call, instantiate, read, write, type, extends, implements), resolution (`exact`, `typed`, `name`), the builtin member stop list | `server/app/services/symbols/model.py` | | TypeScript extractor: scope stack (enclosing symbol, class for `this`, shadowing locals, nested symbols), members and object-literal methods as nodes, typed receivers from annotations and `new`, pending member references; reuses `TsProgram` for parsing, module resolution and barrels | `server/app/services/symbols/typescript.py`, `server/app/services/deps/typescript_deps.py` (`TsProgram`) | | Python extractor: the same contract; class scopes seen only from the class body, `self`/`cls` (the first parameter of a method) and `super()` as the class receiver, fields from class-body and `self.x = …` assignments, `global`, function-local imports, module attribute chains descended to the deepest known module; `PyProgram` reuses `PyModuleIndex` and `parse_py_file` with `__init__` re-exports passed through | `server/app/services/symbols/python.py` | +| Checker binding: the `symbolRefs` op (every identifier, its kind, enclosing declaration and target; a tsconfig whose `paths` differ from the primary's gets its own Program; a workspace package's built `.d.ts` is followed to its source), the join to tree-sitter ids, and the comparison of both binders on a whole repo | `engine/src/srcly/ops/symbol-refs.ts`, `engine/src/srcly/contracts/symbol-refs.ts`, `server/app/services/symbols/checker.py`, `server/scripts/compare_binders.py`, `engine/scripts/symbol-refs-probe.ts` (cost) | +| Show references by position: the reference whose span holds the caret, else the declaration of that name, never a name search | `server/app/services/symbols/index.py` (`SymbolIndex.at`), `GET /api/symbols/at` in `server/app/routers/symbols.py`, `client/src/components/CodeModal/CodeModal.tsx` (`onReferences`) | | Index: merge files, settle member references (`this`/`super`, class-qualified, module attribute, typed receiver, else a unique non-builtin member name for calls), mtime cache, neighbourhood BFS with hop and direction, merged edges, search | `server/app/services/symbols/index.py` | | Response models | `server/app/models.py` (`SymbolGraph`, `SymbolGraphNode`, `SymbolGraphEdge`, `SymbolSearch`) | -| Tests: extractor rules and queries; router | `server/tests/test_symbol_index_ts.py`, `server/tests/test_symbol_index_py.py`, `server/tests/test_symbols_router.py` | +| Tests: extractor rules and queries; router; the checker join and position lookup | `server/tests/test_symbol_index_ts.py`, `server/tests/test_symbol_index_py.py`, `server/tests/test_symbols_router.py`, `server/tests/test_symbol_checker_join.py`, `engine/test/srcly/symbol-refs.test.ts` | ### Client: Symbols mode diff --git a/docs/dataflow-engine.md b/docs/dataflow-engine.md index 584d065d..1fffe565 100644 --- a/docs/dataflow-engine.md +++ b/docs/dataflow-engine.md @@ -19,7 +19,7 @@ Three surfaces read the engine: the route graph in the dependency view, the valu ## Invariants -1. **The base scan never waits.** The engine starts on first explicit use: Data flow mode, Inspect value flow, the effects panel, or a `--dataflow` CLI flag. The treemap, explorer and import graph are the same with or without Node. +1. **The base scan never waits.** The engine starts on first explicit use: Data flow mode, Inspect value flow, the effects panel, Symbols mode and Show references, `srcly refs`, or a `--dataflow` CLI flag. The treemap, explorer and import graph are the same with or without Node. 2. **Evidence is bound to a generation.** Every result carries `generation` and `programHash`. A query with an older `expectedGeneration` gets `stale`, and the client does not draw stale rows over current source. 3. **Not analyzed is never 0.** Each surface shows the query outcome by name. A metric the engine did not measure is `None` with an `na_reason`. 4. **One answer per expression.** The anchor graph decides where a value goes, ends and stops. The value-flow ledger is that graph laid out as rows; it never walks a slice of its own or copies a stop rule (ESLint refuses both imports in `value-flow.ts`). A new end or stop rule goes in `anchor-graph.ts` only, and both views get it. `pnpm parity-probe` compares the two on every selectable expression in a fixture root; run it after any change to either op. Before this rule, the ledger's copied rules passed every fixture test and still differed on 145 of 6,032 selections. @@ -28,7 +28,7 @@ Three surfaces read the engine: the route graph in the dependency view, the valu The legacy entry point built the full legacy report before it answered anything: 130 s on srcly's `client/`. So the session has two tiers that share one Program. -- **Tier 1** builds the primary Program and a lazy evidence provider, and finds routes. It answers `routes`, `routeGraph`, `routePath`, `selectExpression`, `valueFlow`, `functionEffects`, `flowSignature` and the anchor ops. `routes` never calls `buildRouteDataInventory`, which alone costs 17.5 s on visual-notes. +- **Tier 1** builds the primary Program and a lazy evidence provider, and finds routes. It answers `routes`, `routeGraph`, `routePath`, `selectExpression`, `valueFlow`, `functionEffects`, `flowSignature`, `symbolRefs` and the anchor ops. `routes` never calls `buildRouteDataInventory`, which alone costs 17.5 s on visual-notes. - **Tier 2** is the legacy report (`fullReport()`), built only by `fileSignals`. It is slow, so only a batch caller asks for it: `srcly report --dataflow` and `srcly compare --dataflow`. - `programHash` hashes the sorted `(file, size, mtime)` of the Program's source files, every governing tsconfig, the TypeScript version and the engine version. `status` recomputes it with `stat` calls only. A rebuild bumps `generation`. - Refresh drops both tiers. There is no incremental invalidation. diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md index 4341c18f..060cd4ca 100644 --- a/docs/intent/checker-symbol-index/README.md +++ b/docs/intent/checker-symbol-index/README.md @@ -1,6 +1,6 @@ # Checker-bound symbol index (plan) -Status: proposed, not built. Retire this folder when the last milestone lands. +Status: M0 to M3 built (2026-11-28). Retire this folder once the PR merges: the lasting facts are in `docs/CODE_MAP.md` (Symbol graph) and `docs/dataflow-engine.md`. ## Diagrams @@ -163,14 +163,35 @@ Run it on srcly and explorEDA (`f44a5c63` or newer). Done when: - `srcly refs` on the #486 proof symbols (`AnalysisSourceRow`, `SavedDataStructure`, `EvidenceCollector`) lists at least the same callers as #486. - The PR states how many references each repo compared, for example "47,524 of 47,524 explorEDA references compared". +## Proof result (2026-11-28) + +`cd server && SRCLY_ENGINE_DEV=1 uv run python scripts/compare_binders.py --json out.json`. A reference is (source file, line, target id), counted as a multiset. + +| Root | Tree-sitter refs | Checker refs | Agree | Mismatched ids | TS files outside the Program | Unbound | +| --- | ---: | ---: | ---: | ---: | ---: | --- | +| srcly (this branch) | 40,464 | 61,113 | 38,879 (96.1%) | 5 | 176 | 615 unresolved, 815 `any` | +| explorEDA `f44a5c63` | 49,092 | 74,720 | 47,445 (96.6%) | 3 | 452 | 1,657 unresolved, 40 `any` | + +The buckets, by size (explorEDA; srcly has the same shape): + +- Checker only, `read → type` (24,861): a member read through a receiver whose type tree-sitter cannot see (inferred, returned, destructured, a union). The member has no symbol, so it joins the type that declares it, as tree-sitter's `typed` rule does for an annotated receiver. +- Checker only, `call → function` (622), `call → type` (410), `read → variable` (1,113): calls through re-exports and closures, interface method calls, fields of object constants (zod schemas). +- Tree-sitter only, `typed · read → type` (1,412): the checker binds the member somewhere more exact (a union member's own interface, a base interface, the TypeScript library behind `type Ts = typeof TypeScript`), or the type is mapped and has no declaration. +- Tree-sitter only, `name · call → method/field` (111): name guesses the checker refuses, such as a TypeScript call bound to the Python method `BodyWalker.literal`. +- Tree-sitter only, `exact · call → function/variable` (74): mostly JSX intrinsic tags (``, ``) that tree-sitter bound to a local of the same name. +- Mismatched ids: srcly's 5 are `declare function` declarations, which the index keeps no symbol for. explorEDA's 3 are in `FieldListRow.tsx`, where tree-sitter makes no symbol after ``. +- Outside the Program: test files (the engine's Program leaves them out), configs and docs scripts. They keep tree-sitter references. + +Spot checks by hand: the `Legend.span`, `BoxCell.line` and `RowChart.span` rows (JSX tags), `PlotManager.onKeyDown` (four locals that tree-sitter merges into one symbol), `CoverageMatrix.tsx:103` (a `@/` path in `apps/demo`, which needed its own tsconfig's Program), and `PageFileDrop.tsx` (a workspace package's `.d.ts`, followed to source). + ## Milestones | | Milestone | Done when | | --- | --- | --- | -| M0 | Spike: a throwaway walk script on visual-notes and srcly | The cost gate above has numbers. Go or stop is recorded here | -| M1 | `symbolRefs` op, contract, Pydantic mirror, route | Engine tests pass on `examples/value-flow-basics`, plus a fixture per #486 case | -| M2 | Python merge, `binder` info, `compare_binders.py` | The proof above passes on srcly and explorEDA | -| M3 | `/api/symbols/at` and Show references by position | A Playwright test clicks a use of a split name and lands on `@type` | +| M0 ✅ | Spike: a throwaway walk script on visual-notes and srcly | The cost gate above has numbers. Go or stop is recorded here | +| M1 ✅ | `symbolRefs` op, contract, Pydantic mirror | `engine/test/srcly/symbol-refs.test.ts` on its own fixture, one case per #486 finding. The op is not an HTTP route: only the symbol index reads it | +| M2 ✅ | Python merge, `binder` info, `compare_binders.py` | The proof above passes on srcly and explorEDA (results below) | +| M3 ✅ | `/api/symbols/at` and Show references by position | `client/e2e/symbols.spec.ts` (Show references by position) clicks each side of a split name | M1 to M3 change core logic (two binders that must agree). Each one gets the Codex review loop. From 0dfc8a4d94ba1dc239a0e1036b195bd8aea7f485 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:23:44 -0500 Subject: [PATCH 08/13] fix(symbols): refresh a stale engine before binding, and retry the checker after a passing failure Co-Authored-By: Claude Opus 5.5 --- server/app/services/symbols/checker.py | 13 ++++++++++++- server/app/services/symbols/index.py | 4 +++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/server/app/services/symbols/checker.py b/server/app/services/symbols/checker.py index 449ae727..7d4499bd 100644 --- a/server/app/services/symbols/checker.py +++ b/server/app/services/symbols/checker.py @@ -37,8 +37,16 @@ class CheckerRefs: program_hash: Optional[str] = None +# Reasons the checker will still be missing on the next request: the index may cache its fallback. +LASTING = frozenset({"python-root", "node-not-found", "engine-missing", "no-tsconfig", "no-ts-files", "typescript-not-found", "engine-protocol-mismatch"}) + + def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Optional[str]]: - """The engine's ``symbolRefs`` for the root, or None and the reason it has none.""" + """ + The engine's ``symbolRefs`` for the root, from the sources as they are now, or None and + the reason it has none. The engine keeps its Program until asked to refresh, so a stale + one is rebuilt first. + """ from app.services.dataflow.engine import EngineError from app.services.dataflow.engine import registry as shared @@ -52,6 +60,9 @@ def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Option if known is not None: return None, known.code try: + status = reg.query(root, "status", {}) + if status.get("stale"): + reg.query(root, "refresh", {}, timeout=180.0) # A walk of the whole program: allow more than one ordinary query. raw = reg.query(root, "symbolRefs", {}, timeout=180.0) except EngineError as exc: diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 63a41d7e..27d71047 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -17,6 +17,7 @@ from app.services.deps.common import SourceSignature, is_test_path, source_signature, walk_source_files from app.services.deps.typescript_deps import TS_EXTENSIONS from app.services.dataflow.models import SymbolRefsResult as CheckerResult +from app.services.symbols.checker import LASTING as LASTING_REASONS from app.services.symbols.checker import join from app.services.symbols.checker import query as query_checker from app.services.symbols.model import BUILTIN_MEMBERS, REF_KINDS, FileSymbols, PendingMember, RefKind, Reference, Symbol @@ -666,7 +667,8 @@ def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-s index = assemble(root, parts, checked) if index.binder != "checker": index.binder_reason = reason if binder == "checker" else "asked" - if use_cache: + # A fallback for a passing cause (a crash, a timeout, the memory limit) is not kept: the next request tries the checker again. + if use_cache and (index.binder == binder or reason in LASTING_REASONS): with _lock: _cache[(root, binder)] = (sig, index) return index From 07ed8b2432697257ea375fd7e56e8cef2b696b8f Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:38:23 -0500 Subject: [PATCH 09/13] fix(symbols): join by name position, follow built .d.ts by path, route every resolution option Codex round 1: join a declaration by the line of its name, not its body; Show references sends the identifier's first column and matches a declaration at its name; a workspace package's built .d.ts follows its own path to src and the export path there (namespace and member uses too); a config that resolves modules differently binds in its own Program; implements and an interface's extends bind the type side; x["run"]() is a reference; a cached checker index holds only while the engine's program hash matches; an anonymous export default function is file#default; a member id passes through Show references. Co-Authored-By: Claude Opus 5.5 --- client/src/components/CodeModal/CodeModal.tsx | 12 +- client/src/navigation/nodeActions.test.ts | 2 + client/src/navigation/nodeActions.ts | 7 +- client/src/symbols/identifier.ts | 7 +- engine/src/srcly/ops/symbol-refs.ts | 176 +++++++++++------- .../symbol-refs-workspace/app/src/use.ts | 10 + .../symbol-refs-workspace/app/tsconfig.json | 1 + .../srcly/__fixtures__/symbol-refs/src/m.ts | 5 + .../__fixtures__/symbol-refs/src/use.tsx | 8 + engine/test/srcly/symbol-refs.test.ts | 56 +++--- server/app/services/symbols/checker.py | 19 +- server/app/services/symbols/index.py | 18 +- server/app/services/symbols/model.py | 3 + server/app/services/symbols/typescript.py | 44 ++++- server/tests/test_symbol_checker_join.py | 22 +++ 15 files changed, 279 insertions(+), 111 deletions(-) create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json diff --git a/client/src/components/CodeModal/CodeModal.tsx b/client/src/components/CodeModal/CodeModal.tsx index 04e77cc8..d0e9a224 100644 --- a/client/src/components/CodeModal/CodeModal.tsx +++ b/client/src/components/CodeModal/CodeModal.tsx @@ -14,7 +14,7 @@ import { MarkdownPane } from "./MarkdownPane"; import { MetricsSidebar } from "./MetricsSidebar"; import { InspectMenu } from "./InspectMenu"; import { fetchSymbolAt } from "../../symbols/api"; -import { identifierAt } from "../../symbols/identifier"; +import { identifierRangeAt } from "../../symbols/identifier"; import { refsPatch, traceAnchorPatch } from "../../navigation/nodeActions"; import { ValueFlowLedger } from "./ValueFlowLedger"; import { createEffectsQuery, EffectsPanel } from "../../dataflow/EffectsPanel"; @@ -217,12 +217,14 @@ export default function CodeModal(props: CodeModalProps) { onReferences: async ({ line, column }) => { const at = props.rootPath && props.filePath ? atFromTreePath(props.filePath, props.rootPath) : null; const text = (rawCode() ?? "").split("\n")[line - 1] ?? ""; - const name = identifierAt(text, column); - if (at === null || !name || !props.rootPath) return "No name here"; - const res = await fetchSymbolAt({ path: props.rootPath, file: at, line, column, name }); + // The identifier's first column: a caret just past its last letter still names it. + const word = identifierRangeAt(text, column); + if (at === null || !word || !props.rootPath) return "No name here"; + const name = word.name; + const res = await fetchSymbolAt({ path: props.rootPath, file: at, line, column: word.column, name }); if (!res.id) return res.candidates.length ? `"${name}" could be ${res.candidates.length} symbols here` : `No symbol is bound to "${name}" here`; props.onClose(); - go(refsPatch({ at: res.id })); + go(refsPatch({ symbol: res.id })); return null; }, }); diff --git a/client/src/navigation/nodeActions.test.ts b/client/src/navigation/nodeActions.test.ts index 88760919..3ade26ae 100644 --- a/client/src/navigation/nodeActions.test.ts +++ b/client/src/navigation/nodeActions.test.ts @@ -51,6 +51,8 @@ describe("Show references", () => { expect(refsPatch({ at: "a/b.ts#X" })).toMatchObject({ view: "graph", symbols: "a/b.ts#X", flow: undefined, anchor: undefined, open: undefined }); expect(refsPatch({ at: "a.py#Foo (class)::run" }).symbols).toBe("a.py#Foo.run"); expect(refsPatch({ at: "a/b.ts" }).symbols).toBe("a/b.ts"); + // An id from the symbol index is the focus as it is, a member's dot included. + expect(refsPatch({ symbol: "a/model.ts#Runner.run" }).symbols).toBe("a/model.ts#Runner.run"); const reason = (target: Parameters[0]) => nodeActions(target).find((a) => a.id === "refs")?.disabledReason; expect(reason({ at: "a", kind: "folder", currentAt: "" })).toBe("Pick a file or symbol"); expect(reason({ at: "ext:react", kind: "external", currentAt: "" })).toBe("Outside this repo"); diff --git a/client/src/navigation/nodeActions.ts b/client/src/navigation/nodeActions.ts index b8e8469a..9f4ef166 100644 --- a/client/src/navigation/nodeActions.ts +++ b/client/src/navigation/nodeActions.ts @@ -62,9 +62,10 @@ export function addAnchorPatch(target: { at: string; line?: number }, current: L /** * Where "Show references" takes the view: Symbols mode centred on the - * symbol `at` names (a file shows its module and top-level symbols). + * symbol `at` names (a file shows its module and top-level symbols), or on + * `symbol`, an id the symbol index gave, which passes through unchanged. */ -export function refsPatch(target: { at: string }): Partial { +export function refsPatch(target: { at: string } | { symbol: string }): Partial { return { view: "graph", flow: undefined, @@ -74,7 +75,7 @@ export function refsPatch(target: { at: string }): Partial { dest: undefined, lens: undefined, open: undefined, - symbols: symbolIdOf(target.at) ?? "", + symbols: "symbol" in target ? target.symbol : (symbolIdOf(target.at) ?? ""), to: undefined, }; } diff --git a/client/src/symbols/identifier.ts b/client/src/symbols/identifier.ts index 93b66461..30bca299 100644 --- a/client/src/symbols/identifier.ts +++ b/client/src/symbols/identifier.ts @@ -1,5 +1,10 @@ /** The identifier under a 1-based column of a source line, or null when the caret is not on one. */ export function identifierAt(line: string, column: number): string | null { + return identifierRangeAt(line, column)?.name ?? null; +} + +/** The identifier at a 1-based column and the 1-based column of its first character: a caret on either side of a letter finds it. */ +export function identifierRangeAt(line: string, column: number): { name: string; column: number } | null { const i = Math.min(Math.max(column - 1, 0), line.length); const word = /[A-Za-z0-9_$#]/; if (!word.test(line[i] ?? "") && !word.test(line[i - 1] ?? "")) return null; @@ -8,5 +13,5 @@ export function identifierAt(line: string, column: number): string | null { let end = start; while (end < line.length && word.test(line[end])) end += 1; const name = line.slice(start, end); - return /^[A-Za-z_$#]/.test(name) ? name : null; + return /^[A-Za-z_$#]/.test(name) ? { name, column: start + 1 } : null; } diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts index 3c0927d6..12da77bb 100644 --- a/engine/src/srcly/ops/symbol-refs.ts +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -1,4 +1,3 @@ -import fs from "node:fs"; import path from "node:path"; import type * as TypeScript from "typescript"; import type { AnalysisCancellationToken } from "../../analysis/cancellation"; @@ -45,7 +44,7 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; return index; }; const ownerOf = owners(tier1); - const toSource = workspaceSources(tier1, root); + const toSource = builtSources(tier1, root); const files = sources.map((primary) => { cancellation?.throwIfCancelled(); // A file whose own tsconfig resolves imports differently binds in that config's Program. @@ -54,7 +53,9 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; const checker: TypeScript.TypeChecker = routed?.checker ?? primaryChecker; const refs: SymbolRef[] = []; const visit = (node: TypeScript.Node) => { - if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) { + // `x["run"]()` names a member as a string: the same reference as `x.run()`. + const keyed = ts.isStringLiteralLike(node) && ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; + if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node) || keyed) { const ref = bind(ts, checker, source, node, own, intern, toSource); if (ref === "skip") return; if (ref !== "external") ref.source = enclosing(ts, node, source, intern); @@ -91,14 +92,30 @@ const routedByTier = new WeakMap>(); /** * The Program a file binds in, when it is not the primary. The primary Program uses one - * config's options, so a file whose nearest config declares other `paths` or `baseUrl` - * (a monorepo app beside the package) would resolve `@/x` against the wrong folder. + * config's options, so a file whose nearest config resolves modules differently (other + * `paths`, `baseUrl`, `moduleResolution`, conditions; a monorepo app beside the package) + * would resolve `@/x` or `pkg` against the wrong target. * Such a config gets its own Program, built on first use and kept with the tier. */ function owners(tier1: TsTier1): (file: string) => Routed | undefined { const { ts, resolution } = tier1; const primary = resolution.primary; - const resolves = (o: TypeScript.CompilerOptions) => JSON.stringify([o.paths ?? null, o.paths ? (o.pathsBasePath ?? o.baseUrl ?? null) : (o.baseUrl ?? null)]); + // Every option that changes where an import resolves, or which JSX runtime a tag binds to. + const resolves = (o: TypeScript.CompilerOptions) => + JSON.stringify([ + o.paths ?? null, + o.paths ? (o.pathsBasePath ?? o.baseUrl ?? null) : (o.baseUrl ?? null), + o.moduleResolution ?? null, + o.module ?? null, + o.customConditions ?? null, + o.resolvePackageJsonExports ?? null, + o.resolvePackageJsonImports ?? null, + o.rootDirs ?? null, + o.allowJs ?? null, + o.jsx ?? null, + o.jsxImportSource ?? null, + o.types ?? null, + ]); const differs = resolution.configs.filter((c) => c.file !== primary.file && c.fileNames.length > 0 && resolves(c.options) !== resolves(primary.options)); if (!differs.length) return () => undefined; const nearest = new Map(); @@ -126,66 +143,82 @@ function owners(tier1: TsTier1): (file: string) => Routed | undefined { } /** - * A workspace package's import, followed to the package's source the way srcly's import - * graph does (`typescript_deps.py`): `pkg/sub` is `/sub` or `/src/sub`, and `pkg` - * alone is its `source` or `src/index`. The export is then looked up in that module by the - * checker. Only a package under the root that is not in `node_modules` counts. + * A declaration in a built `.d.ts` under the root (a workspace package another project imports + * through its `dist`), followed to its source: the declaration file the checker resolved, with + * its output folder swapped for `src` (`dist/readers.d.ts` → `src/readers.ts`), and the same + * export path looked up there by the checker (`tick`, `Runner.run`, `default`). Each alias hop + * is tried first, so a named import reaches the module it was imported from, not a bundle chunk. + * Nothing found means the reference stays external: no guessed module. */ -function workspaceSources(tier1: TsTier1, root: string) { +const OUTPUT_FOLDERS = new Set(["dist", "build", "lib", "out", "types"]); + +function builtSources(tier1: TsTier1, root: string) { const { ts, program } = tier1; - let packages: Map | null = null; - const known = () => { - if (packages) return packages; - packages = new Map(); - const seen = new Set(); - for (const source of program.getSourceFiles()) { - if (source.isDeclarationFile || !source.fileName.startsWith(root + path.sep) || source.fileName.includes("/node_modules/")) continue; - for (let dir = path.dirname(source.fileName); dir.startsWith(root) && !seen.has(dir); dir = path.dirname(dir)) { - seen.add(dir); - const manifest = path.join(dir, "package.json"); - if (!fs.existsSync(manifest)) continue; - try { - const name = (JSON.parse(fs.readFileSync(manifest, "utf8")) as { name?: unknown }).name; - if (typeof name === "string" && !packages.has(name)) packages.set(name, dir); - } catch { - // An unreadable manifest names no package. - } - } + // The package's source is in the primary Program, whichever Program bound the reference. + const checker = program.getTypeChecker(); + const built = (file: TypeScript.SourceFile) => file.isDeclarationFile && file.fileName.startsWith(root + path.sep) && !file.fileName.includes(`${path.sep}node_modules${path.sep}`); + const sourceOf = (file: TypeScript.SourceFile): TypeScript.SourceFile | undefined => { + const stem = file.fileName.replace(/\.d\.[mc]?ts$/, ""); + // The last output folder in the path is the one the build wrote (`packages/lib/dist/x`: `dist`). + const parts = stem.split("/"); + let out = parts.length - 2; + while (out >= 0 && !OUTPUT_FOLDERS.has(parts[out])) out -= 1; + if (out < 0) return undefined; + const swapped = [...parts.slice(0, out), "src", ...parts.slice(out + 1)].join("/"); + for (const ext of [".ts", ".tsx", ".mts", "/index.ts", "/index.tsx"]) { + const hit = program.getSourceFile(swapped + ext); + if (hit && !hit.isDeclarationFile) return hit; } - return packages; + return undefined; }; - const extensions = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"]; - const moduleOf = (spec: string): TypeScript.SourceFile | undefined => { - const names = [...known().keys()].filter((name) => spec === name || spec.startsWith(name + "/")).sort((a, b) => b.length - a.length); - for (const name of names) { - const dir = known().get(name)!; - const rest = spec.slice(name.length + 1); - const bases = rest ? [path.join(dir, rest), path.join(dir, "src", rest)] : [path.join(dir, "src", "index"), dir]; - for (const base of bases) { - for (const ext of ["", ...extensions]) { - const hit = program.getSourceFile(base + ext); - if (hit && !hit.isDeclarationFile) return hit; - } + /** The names from the module down to the declaration: `["Runner", "run"]`; undefined inside a body. */ + const pathOf = (decl: TypeScript.Declaration): string[] | undefined => { + const own = ts.isExportAssignment(decl) ? "default" : ts.isExportSpecifier(decl) ? decl.name.text : (() => { + const name = ts.getNameOfDeclaration(decl); + return name && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? name.text : undefined; + })(); + if (!own) return undefined; + const names = [own]; + for (let at = decl.parent; at && !ts.isSourceFile(at); at = at.parent) { + if (ts.isClassDeclaration(at) || ts.isInterfaceDeclaration(at) || ts.isEnumDeclaration(at) || ts.isModuleDeclaration(at)) { + if (!at.name || !ts.isIdentifier(at.name)) return undefined; + names.unshift(at.name.text); + } else if (ts.isModuleBlock(at) || ts.isVariableDeclaration(at) || ts.isVariableDeclarationList(at) || ts.isVariableStatement(at) || ts.isExportDeclaration(at) || ts.isNamedExports(at)) { + continue; + } else if (!ts.isClassElement(decl) && !ts.isTypeElement(decl) && !ts.isEnumMember(decl)) { + return undefined; } } - return undefined; + return names; }; - // The package's source is in the primary Program, whichever Program bound the import. - const checker = program.getTypeChecker(); - return (alias: TypeScript.Symbol): TypeScript.Symbol | undefined => { - const declaration = alias.declarations?.[0]; - if (!declaration) return undefined; - let at: TypeScript.Node | undefined = declaration; - while (at && !ts.isImportDeclaration(at) && !ts.isExportDeclaration(at)) at = at.parent; - const specifier = at && (at as TypeScript.ImportDeclaration | TypeScript.ExportDeclaration).moduleSpecifier; - if (!specifier || !ts.isStringLiteral(specifier) || specifier.text.startsWith(".")) return undefined; - const module = moduleOf(specifier.text); - const moduleSymbol = module && checker.getSymbolAtLocation(module); + const follow = (symbol: TypeScript.Symbol | undefined) => (symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol); + const lookup = (module: TypeScript.SourceFile, names: string[]): TypeScript.Symbol | undefined => { + const moduleSymbol = checker.getSymbolAtLocation(module); if (!moduleSymbol) return undefined; - if (ts.isNamespaceImport(declaration)) return moduleSymbol; - const exported = ts.isImportClause(declaration) ? "default" : ((declaration as TypeScript.ImportSpecifier).propertyName ?? (declaration as TypeScript.ImportSpecifier).name).text; - const member = checker.tryGetMemberInModuleExports(exported, moduleSymbol); - return member && member.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(member) : member; + let found = follow(checker.tryGetMemberInModuleExports(names[0], moduleSymbol)); + for (const name of names.slice(1)) { + const key = ts.escapeLeadingUnderscores(name); + found = found && (found.members?.get(key) ?? found.exports?.get(key)); + } + return found; + }; + return (bound: TypeScript.TypeChecker, symbol: TypeScript.Symbol, alias: TypeScript.Symbol | undefined): TypeScript.Symbol | undefined => { + const hops: TypeScript.Declaration[] = []; + for (let at: TypeScript.Symbol | undefined = alias; at && at.flags & ts.SymbolFlags.Alias; ) { + const next = bound.getImmediateAliasedSymbol(at); + if (next?.declarations?.[0]) hops.push(next.declarations[0]); + at = next; + } + hops.push(...(symbol.declarations ?? [])); + for (const decl of hops) { + const file = decl.getSourceFile(); + if (!built(file)) continue; + const module = sourceOf(file); + const names = module && pathOf(decl); + const found = module && names ? lookup(module, names) : undefined; + if (found?.declarations?.length) return found; + } + return undefined; }; } @@ -193,10 +226,10 @@ function bind( ts: Ts, checker: TypeScript.TypeChecker, source: TypeScript.SourceFile, - node: TypeScript.Identifier | TypeScript.PrivateIdentifier, + node: TypeScript.Identifier | TypeScript.PrivateIdentifier | TypeScript.StringLiteralLike, own: (source: TypeScript.SourceFile) => boolean, intern: (decl: TypeScript.Declaration, home: TypeScript.SourceFile) => number, - toSource: (alias: TypeScript.Symbol) => TypeScript.Symbol | undefined, + toSource: (bound: TypeScript.TypeChecker, symbol: TypeScript.Symbol, alias: TypeScript.Symbol | undefined) => TypeScript.Symbol | undefined, ): SymbolRef | "external" | "skip" { const parent = node.parent; if (!parent || skipped(ts, node, parent)) return "skip"; @@ -209,17 +242,20 @@ function bind( const alias = symbol && symbol.flags & ts.SymbolFlags.Alias ? symbol : undefined; if (alias) symbol = checker.getAliasedSymbol(alias); const start = source.getLineAndCharacterOfPosition(node.getStart(source)); - const ref = { source: null as number | null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind: inType ? ("type" as Kind) : kindOf(ts, node) }; + const syntactic = kindOf(ts, node); + // A heritage clause keeps its own kind, whichever side of a name it binds. + const kind: Kind = syntactic === "extends" || syntactic === "implements" ? syntactic : inType ? "type" : syntactic; + const ref = { source: null as number | null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind }; // `typeof x` in a type names the value x. let decl = symbol ? pick(ts, symbol, position === "type") : undefined; - // An import of a workspace package lands in its built `.d.ts`: bind the same export in its source. - if (alias && decl?.getSourceFile().isDeclarationFile) { - const fromSource = toSource(alias); + // A workspace package imported through its built `.d.ts`: the same declaration in its source. + if (symbol && decl?.getSourceFile().isDeclarationFile) { + const fromSource = toSource(checker, symbol, alias); const sourceDecl = fromSource ? pick(ts, fromSource, position === "type") : undefined; if (sourceDecl) decl = sourceDecl; } if (!decl) { - const receiver = ts.isPropertyAccessExpression(parent) && parent.name === node ? parent.expression : null; + const receiver = (ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isElementAccessExpression(parent) && parent.argumentExpression === node) ? parent.expression : null; const any = receiver ? (checker.getTypeAtLocation(receiver).flags & ts.TypeFlags.Any) !== 0 : false; return { ...ref, target: null, unbound: any ? "any" : "unresolved" }; } @@ -248,7 +284,11 @@ function skipped(ts: Ts, node: TypeScript.Node, parent: TypeScript.Node): boolea function typePosition(ts: Ts, node: TypeScript.Node): "code" | "type" | "typeof" { let typeofSeen = false; for (let at = node.parent; at && !ts.isSourceFile(at); at = at.parent) { - // `class A extends B`: B is code; T was a type node on the way up. + // `class A extends B`: B is a value; `implements B` and an interface's `extends B` name a type. + // T was a type node on the way up. + if (ts.isExpressionWithTypeArguments(at) && ts.isHeritageClause(at.parent)) { + return at.parent.token === ts.SyntaxKind.ImplementsKeyword || ts.isInterfaceDeclaration(at.parent.parent) ? "type" : "code"; + } if (ts.isExpressionWithTypeArguments(at) && !ts.isTypeNode(at.parent)) return "code"; if (ts.isTypeQueryNode(at) || (ts.isImportTypeNode(at) && at.isTypeOf)) typeofSeen = true; if (ts.isTypeNode(at) && !ts.isExpressionWithTypeArguments(at)) return typeofSeen ? "typeof" : "type"; @@ -261,7 +301,7 @@ function kindOf(ts: Ts, node: TypeScript.Node): Kind { let expr: TypeScript.Node = node; const parent = node.parent; // `a.b`: the member name stands for the whole access; the receiver `a` is a read. - if ((ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isQualifiedName(parent) && parent.right === node)) expr = parent; + if ((ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isQualifiedName(parent) && parent.right === node) || (ts.isElementAccessExpression(parent) && parent.argumentExpression === node)) expr = parent; while (ts.isParenthesizedExpression(expr.parent) || ts.isNonNullExpression(expr.parent) || ts.isAsExpression(expr.parent)) expr = expr.parent; const up = expr.parent; if (ts.isExpressionWithTypeArguments(up) && ts.isHeritageClause(up.parent)) return up.parent.token === ts.SyntaxKind.ImplementsKeyword ? "implements" : "extends"; @@ -318,7 +358,7 @@ function targetOf(ts: Ts, decl: TypeScript.Declaration, home: TypeScript.SourceF const file = rel(home.fileName); if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, meaning: "value", scope: "module" }; const name = ts.getNameOfDeclaration(decl); - const text = ts.isConstructorDeclaration(decl) ? "constructor" : name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; + const text = ts.isConstructorDeclaration(decl) ? "constructor" : ts.isExportAssignment(decl) && !decl.isExportEquals ? "default" : name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; const at = home.getLineAndCharacterOfPosition((name ?? decl).getStart(home)); return { file, name: text, line: at.line + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; } diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts new file mode 100644 index 00000000..e96f4c36 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts @@ -0,0 +1,10 @@ +import main, { tick, Runner } from "lib"; +import * as lib from "lib"; + +export function app() { + tick(); + lib.tick(); + new Runner().run(); + new lib.Runner()["run"](); + return main(); +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json new file mode 100644 index 00000000..525df808 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "module": "esnext", "moduleResolution": "bundler", "target": "es2022", "noEmit": true, "paths": { "lib": ["../packages/lib/dist/index.d.ts"] } }, "include": ["src"] } diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts index 2e8f152a..50e103f7 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts @@ -12,3 +12,8 @@ export default function A() { return 1; } export type A = number; + +export interface Model { + id: number; +} +export const Model = { id: 1 }; diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx index 663390ce..f3b3fcaa 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx @@ -23,3 +23,11 @@ export function outer() { type Local = { ok: boolean }; return inner; } + +export class Impl implements Model { + id = 1; +} +export interface Wider extends Model { + extra: boolean; +} +import { Model } from "./m"; diff --git a/engine/test/srcly/symbol-refs.test.ts b/engine/test/srcly/symbol-refs.test.ts index 20406950..8cb40a01 100644 --- a/engine/test/srcly/symbol-refs.test.ts +++ b/engine/test/srcly/symbol-refs.test.ts @@ -1,3 +1,4 @@ +import fs from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { symbolRefsOp } from "../../src/srcly/ops/symbol-refs"; @@ -15,33 +16,7 @@ describe("symbolRefs binds every identifier with the checker", () => { if (!hit) throw new Error(`no ref at ${line}:${column} (${text})`); return hit; }; - const source = [ - `import A, { Store } from "./m";`, - `import * as m from "./m";`, - ``, - `declare function pick(): T;`, - `declare function C(props: { row?: T }): null;`, - ``, - `export const value = pick();`, - `export let typed: import("./m").Row | undefined;`, - `export const tag = />;`, - ``, - `export function run(store: Store, loose: any) {`, - ` store.bump();`, - ` loose.bump();`, - ` const made = new m.Store();`, - ` const n: A = A();`, - ` return { made, n };`, - `}`, - ``, - `export function outer() {`, - ` function inner(): Local {`, - ` return { ok: true };`, - ` }`, - ` type Local = { ok: boolean };`, - ` return inner;`, - `}`, - ]; + const source = fs.readFileSync(path.join(root, "src/use.tsx"), "utf8").split("\n"); it("answers ok for the files asked, with no import clause as a reference", () => { expect(result.outcome).toBe("ok"); @@ -69,7 +44,34 @@ describe("symbolRefs binds every identifier with the checker", () => { expect(at(15, "A =")).toMatchObject({ kind: "type", target: null, unbound: "unresolved" }); }); + it("binds `implements` and an interface's `extends` to the type side of a split name", () => { + expect(at(27, "Model")).toMatchObject({ kind: "implements", to: { name: "Model", line: 16, meaning: "type" } }); + expect(at(30, "Model")).toMatchObject({ kind: "extends", to: { name: "Model", line: 16, meaning: "type" } }); + }); + it("binds a forward reference to a block-local alias", () => { expect(at(20, "Local").to).toMatchObject({ file: "src/use.tsx", name: "Local", line: 23, meaning: "type", scope: "local" }); }); }); + +describe("symbolRefs follows a workspace package's built .d.ts to its source", () => { + const workspace = path.join(__dirname, "__fixtures__", "symbol-refs-workspace"); + const result = symbolRefsOp(createEngineSession({ root: workspace, source: ".", tsconfig: null, typescriptFrom: workspace }), { files: ["app/src/use.ts"] }); + const text = fs.readFileSync(path.join(workspace, "app/src/use.ts"), "utf8").split("\n"); + const at = (line: number, needle: string, offset = 0) => { + const column = text[line - 1].indexOf(needle) + 1 + offset; + const ref = result.files[0]?.refs.find((r) => r.line === line && r.column === column); + if (!ref) throw new Error(`no ref at ${line}:${column} (${needle})`); + return { ...ref, to: ref.target === null ? null : result.targets[ref.target] }; + }; + const lib = "packages/lib/src/index.ts"; + + it("binds named, namespace, class-member, bracket and default uses to the source", () => { + expect(at(5, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); + expect(at(6, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); + expect(at(7, "Runner")).toMatchObject({ kind: "instantiate", to: { file: lib, name: "Runner", line: 5 } }); + expect(at(7, "run")).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6, scope: "member" } }); + expect(at(8, '"run"')).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6 } }); + expect(at(9, "main")).toMatchObject({ kind: "call", to: { file: lib, name: "main", line: 11 } }); + }); +}); diff --git a/server/app/services/symbols/checker.py b/server/app/services/symbols/checker.py index 7d4499bd..8400028d 100644 --- a/server/app/services/symbols/checker.py +++ b/server/app/services/symbols/checker.py @@ -73,6 +73,21 @@ def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Option _HOLDERS = frozenset({"type", "class", "enum", "variable"}) +def current_hash(root: Path, registry=None) -> Optional[str]: + """The program hash of the sources and tsconfigs as they are now (stat calls only), or None when the engine cannot say.""" + from app.services.dataflow.engine import EngineError + from app.services.dataflow.engine import registry as shared + + reg = registry if registry is not None else shared + if not reg.probe(root).available or reg.failure(root) is not None: + return None + try: + status = reg.query(root, "status", {}) + except EngineError: + return None + return status.get("currentHash") or (status.get("programHash") if status.get("built") and not status.get("stale") else None) + + class _Files: """Each file's symbols, by name and by line span, for the join.""" @@ -91,7 +106,9 @@ def target(self, t: SymbolRefTarget) -> Optional[str]: if t.name == "*": return t.file if t.file in self.modules else None want_type = t.meaning == "type" - held = [s for s in self.by_name.get((t.file, t.name), ()) if s.line <= t.line <= s.end_line] + # The declaration whose name is on that line: a shadowing parameter or an unindexed local + # inside a same-named symbol's body never joins it. + held = [s for s in self.by_name.get((t.file, t.name), ()) if any(line == t.line for line, _ in s.names)] if not held and t.scope == "member": # A member the index keeps no symbol for (an interface's field, an object type's member): # the type, class or variable that declares it, as a typed receiver gives today. diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 27d71047..f3265c5a 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -18,7 +18,7 @@ from app.services.deps.typescript_deps import TS_EXTENSIONS from app.services.dataflow.models import SymbolRefsResult as CheckerResult from app.services.symbols.checker import LASTING as LASTING_REASONS -from app.services.symbols.checker import join +from app.services.symbols.checker import current_hash, join from app.services.symbols.checker import query as query_checker from app.services.symbols.model import BUILTIN_MEMBERS, REF_KINDS, FileSymbols, PendingMember, RefKind, Reference, Symbol @@ -52,6 +52,7 @@ class SymbolIndex: unbound: Dict[str, int] = field(default_factory=dict) mismatched: List[str] = field(default_factory=list) outside_program: int = 0 + program_hash: Optional[str] = None _by_line: Optional[Dict[Tuple[str, int], List[int]]] = None def __post_init__(self) -> None: @@ -345,7 +346,8 @@ def search(self, query: str, limit: int = 30, include_tests: bool = True) -> Lis def at(self, file: str, line: int, column: int, name: str) -> Tuple[Optional[str], List[str]]: """ - The symbol bound at a source position (1-based line, 1-based UTF-16 column), and the + The symbol bound at a source position (1-based line, 1-based UTF-16 column of the + identifier's first character), and the candidates when the index cannot tell. A reference whose span holds the column wins; then a declaration of that name whose lines hold the line. A tree-sitter reference has no columns, so it matches by line and target name, and several targets stay candidates. @@ -361,7 +363,12 @@ def at(self, file: str, line: int, column: int, name: str) -> Tuple[Optional[str return named[0], [] if named: return None, named - declared = [s for s in self.symbols.values() if s.file == file and s.name == name and s.kind != "module" and s.line <= line <= s.end_line] + # A declaration's own name, at its column when the index knows it (TypeScript), else on its line. + declared = [ + s + for s in self.symbols.values() + if s.file == file and s.name == name and s.kind != "module" and ((line, column) in s.names if s.names else s.line == line) + ] if declared: return min(declared, key=lambda s: (s.end_line - s.line, -s.line)).id, [] return None, [] @@ -465,6 +472,7 @@ def assemble(root: Path, parts: List[FileSymbols], checker: Optional[CheckerResu index.binder = "checker" index.unbound = dict(bound.unbound) index.mismatched = bound.mismatched + index.program_hash = bound.program_hash index.outside_program = sum(1 for p in parts if Path(p.file).suffix in TS_EXTENSIONS) index.members_by_name = members_by_name index.http_links, index.http_unmatched = http_links, http_unmatched @@ -645,7 +653,9 @@ def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-s sig = source_signature(files) with _lock: hit = _cache.get((root, binder)) - if hit is not None and hit[0] == sig: + # A checker index also holds while the Program it came from is current: a tsconfig edit + # or a source the walk did not see changes the engine's hash. + if hit is not None and hit[0] == sig and (hit[1].binder != "checker" or current_hash(root, registry) == hit[1].program_hash): return hit[1] parts: List[FileSymbols] = [] ts_files = [f for f in files if f.suffix in TS_EXTENSIONS] diff --git a/server/app/services/symbols/model.py b/server/app/services/symbols/model.py index f04e152c..cdad20b9 100644 --- a/server/app/services/symbols/model.py +++ b/server/app/services/symbols/model.py @@ -90,6 +90,9 @@ class Symbol: http_methods: List[str] = field(default_factory=list) http_path: Optional[str] = None http_router: Optional[str] = None + # Where the declaration's name is: (line, 1-based UTF-16 column), several when one id holds + # same-named locals. TypeScript only; empty for Python. + names: List[Tuple[int, int]] = field(default_factory=list) @property def qualified(self) -> str: diff --git a/server/app/services/symbols/typescript.py b/server/app/services/symbols/typescript.py index 3294feae..3dbe55d4 100644 --- a/server/app/services/symbols/typescript.py +++ b/server/app/services/symbols/typescript.py @@ -25,6 +25,8 @@ from app.services.deps.typescript_deps import TsFileInfo, TsProgram, _string_value, _text, pattern_names from app.services.symbols.model import HTTP_METHODS, FileSymbols, HttpRequest, PendingMember, RefKind, Reference, Symbol, SymbolKind +# An anonymous function value: under `export default`, it is the declaration `default`. +_FUNCTION_EXPRESSIONS = frozenset({"arrow_function", "function_expression", "function", "generator_function"}) _FUNCTION_LIKE = {"function_declaration", "generator_function_declaration", "arrow_function", "function_expression", "function", "generator_function"} _CLASS_LIKE = {"class_declaration", "abstract_class_declaration"} _TYPE_DECLS: Dict[str, SymbolKind] = {"interface_declaration": "type", "type_alias_declaration": "type", "enum_declaration": "enum"} @@ -61,6 +63,7 @@ def __init__(self, program: TsProgram, path: Path, rel: str, info: TsFileInfo, r self.split = program.type_split.get(path, set()) self.by_id: Dict[str, Symbol] = {} self.scopes: List[_Scope] = [_Scope(symbol=rel, class_id=None)] + self._lines: Optional[List[bytes]] = None # ---- scopes and names ---- @@ -132,8 +135,11 @@ def resolve_declared(self, declared: str) -> Optional[str]: def _add(self, name: str, kind: SymbolKind, node: Node, container: Optional[str], exported: bool, suffix: str = "") -> Symbol: sid = f"{self.rel}#{name}{suffix}" if container is None or container == self.rel else f"{container}.{name}" existing = self.by_id.get(sid) + at = self._position(_name_node(node, name)) if existing is not None: existing.end_line = max(existing.end_line, node.end_point[0] + 1) + if at not in existing.names: + existing.names.append(at) return existing sym = Symbol( id=sid, @@ -144,6 +150,7 @@ def _add(self, name: str, kind: SymbolKind, node: Node, container: Optional[str] end_line=node.end_point[0] + 1, container=None if container == self.rel else container, exported=exported, + names=[at], ) self.by_id[sid] = sym self.out.symbols.append(sym) @@ -151,6 +158,14 @@ def _add(self, name: str, kind: SymbolKind, node: Node, container: Optional[str] self.by_id[container].members[name] = sid return sym + def _position(self, node: Node) -> Tuple[int, int]: + """A node's start as a 1-based line and 1-based UTF-16 column, the engine's and the client's unit.""" + if self._lines is None: + self._lines = self.path.read_bytes().split(b"\n") + row, byte_col = node.start_point + prefix = self._lines[row][:byte_col] if row < len(self._lines) else b"" + return row + 1, len(prefix.decode("utf-8", errors="replace").encode("utf-16-le")) // 2 + 1 + def _declare(self, name: str, kind: SymbolKind, node: Node) -> Symbol: """A symbol in the current scope: top-level, or nested in the scope's symbol.""" at_top = len(self.scopes) == 1 @@ -276,7 +291,10 @@ def _predeclare(self, stmt: Node) -> None: if decl is None: if any(c.type == "default" for c in stmt.children): value = stmt.child_by_field_name("value") - if value is not None and value.type not in _FUNCTION_LIKE and value.type not in _CLASS_LIKE and value.type != "class": + if value is not None and value.type in _FUNCTION_EXPRESSIONS: + # `export default () => 1`: the function is `file#default`. + self._declare("default", "function", value) + elif value is not None and value.type not in _FUNCTION_LIKE and value.type not in _CLASS_LIKE and value.type != "class": self._declare("default", "variable", value) return for name, kind, node in self._declared_names(decl): @@ -424,7 +442,11 @@ def _visit_export(self, n: Node) -> None: return value = n.child_by_field_name("value") if value is not None: - if value.type in _FUNCTION_LIKE or value.type in _CLASS_LIKE or value.type == "class": + if value.type in _FUNCTION_EXPRESSIONS: + self._push(self.top.get("default")) + self.visit(value) + self._pop() + elif value.type in _FUNCTION_LIKE or value.type in _CLASS_LIKE or value.type == "class": self.visit(value) else: self._push(self.top.get("default")) @@ -810,6 +832,24 @@ def _type_parameter_bound(n: Node) -> bool: return False +_NAME_NODES = frozenset({"identifier", "property_identifier", "type_identifier", "private_property_identifier", "shorthand_property_identifier_pattern"}) + + +def _name_node(node: Node, name: str) -> Node: + """A declaration's name: its `name` or `key` field, else the first identifier spelled `name` in it, else the declaration.""" + for field_name in ("name", "key"): + named = node.child_by_field_name(field_name) + if named is not None and _text(named) == name: + return named + stack = [node] + while stack: + n = stack.pop(0) + if n.type in _NAME_NODES and _text(n) == name: + return n + stack.extend(n.named_children) + return node + + def _same(a: Optional[Node], b: Optional[Node]) -> bool: """tree-sitter hands out a new Node object on every access, so identity is by node id.""" return a is not None and b is not None and a.id == b.id diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py index 18b2c6a9..73ce0251 100644 --- a/server/tests/test_symbol_checker_join.py +++ b/server/tests/test_symbol_checker_join.py @@ -92,3 +92,25 @@ def test_a_position_resolves_to_the_reference_there_never_a_name_search(tmp_path # A declaration's own name is the declaration; an unbound name is nothing, not the first search hit. assert idx.at("src/m.ts", 1, 13, "Row") == ("src/m.ts#Row@type", []) assert idx.at("src/m.ts", 14, 3, "shape") == (None, []) + + +def test_a_name_joins_only_the_declaration_on_its_own_line(tmp_path: Path): + src = "\n".join( + [ + "export function handler() {", # 1 + " function wrapper(handler: () => void) { handler(); }", # 2 + " return wrapper;", # 3 + "}", # 4 + "export function getSelection() { return document.getSelection(); }", # 5 + ] + ) + (tmp_path / "src").mkdir() + (tmp_path / "src" / "h.ts").write_text(src, encoding="utf-8") + parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "h.ts"]) + targets = [("src/h.ts", "wrapper", 2, "value", "local"), ("src/h.ts", "handler", 2, "value", "local")] + # `handler()` on line 2 calls the parameter, declared on line 2: not the function on line 1. + idx = assemble(tmp_path, parts, _result(targets, [(2, 43, 50, "call", 0, 1, None)], file="src/h.ts")) + assert [r for r in idx.references if r.target == "src/h.ts#handler"] == [] + # The DOM method inside the one-line wrapper is not the wrapper; its own name is. + assert idx.at("src/h.ts", 5, 50, "getSelection") == (None, []) + assert idx.at("src/h.ts", 5, 17, "getSelection") == ("src/h.ts#getSelection", []) From 8f70e6c5d866ffb0a9822d878fad47a34820e50b Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 00:52:09 -0500 Subject: [PATCH 10/13] fix(symbols): join at the name's column, keep union members, locate clause names, track configs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex round 2: the checker sends each target's name column and the join matches it exactly; a union's member binds every class's own member; import and export clause names and recursive calls are positions for Show references, not edges; a checked class takes its bases from checker extends edges only; config edits join the cache key and refresh the engine, and a cached fallback holds only while the engine is still missing; baseUrl wins over an inherited paths base; a declaration map beats the dist→src convention; satisfies keeps a callee a call; the workspace fixture is tracked. Co-Authored-By: Claude Opus 5.5 --- client/src/dataflow/contract.generated.ts | 3 + engine/src/srcly/contracts/symbol-refs.ts | 7 +- engine/src/srcly/ops/symbol-refs.ts | 77 +++++++++++++++---- .../symbol-refs-workspace/app/src/use.ts | 2 + .../symbol-refs-workspace/app/tsconfig.json | 21 ++++- .../packages/kit/dist/entry.d.ts | 2 + .../packages/kit/dist/entry.d.ts.map | 1 + .../packages/kit/dist/index.d.ts | 6 ++ .../packages/kit/package.json | 1 + .../packages/kit/src/entry.ts | 3 + .../packages/kit/src/index.ts | 13 ++++ .../packages/kit/src/real.ts | 3 + .../packages/kit/tsconfig.json | 1 + .../srcly/__fixtures__/symbol-refs/src/m.ts | 5 ++ .../__fixtures__/symbol-refs/src/use.tsx | 4 + engine/test/srcly/symbol-refs.test.ts | 23 +++++- .../dataflow/contracts/symbolRefs.schema.json | 18 +++++ server/app/services/dataflow/models.py | 3 + server/app/services/symbols/checker.py | 34 +++++--- server/app/services/symbols/index.py | 51 +++++++++--- server/tests/test_symbol_checker_join.py | 36 ++++++++- 21 files changed, 272 insertions(+), 42 deletions(-) create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts.map create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/index.d.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/package.json create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/entry.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/index.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/real.ts create mode 100644 engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/tsconfig.json diff --git a/client/src/dataflow/contract.generated.ts b/client/src/dataflow/contract.generated.ts index 9da51c3e..7135b1b5 100644 --- a/client/src/dataflow/contract.generated.ts +++ b/client/src/dataflow/contract.generated.ts @@ -738,6 +738,7 @@ export type SymbolRefsResult = { file: string; name: string; line: number; + column: number; meaning: "value" | "type"; scope: "module" | "member" | "local"; }[]; @@ -750,6 +751,8 @@ export type SymbolRefsResult = { kind: "call" | "instantiate" | "read" | "write" | "type" | "extends" | "implements"; source: number | null; target: number | null; + also?: number[]; + clause?: true; unbound: "unresolved" | "any" | null; }[]; }[]; diff --git a/engine/src/srcly/contracts/symbol-refs.ts b/engine/src/srcly/contracts/symbol-refs.ts index 9d3b5a3c..4ede8946 100644 --- a/engine/src/srcly/contracts/symbol-refs.ts +++ b/engine/src/srcly/contracts/symbol-refs.ts @@ -15,8 +15,9 @@ export const symbolRefTargetSchema = z.strictObject({ file: z.string(), /** The declaration's own name: `A` for `import { A as B }`, `default` for an anonymous default export. */ name: z.string(), - /** The line of the declaration's name. */ + /** The line and 1-based UTF-16 column of the declaration's name (of the expression, for `export default `). */ line: z.number().int().positive(), + column: z.number().int().positive(), /** `type` for an interface or type alias; everything else is `value`. */ meaning: z.enum(["value", "type"]), /** `module`: declared at the top of its file; `member`: a class, interface or object member; `local`: inside a body. */ @@ -32,6 +33,10 @@ export const symbolRefSchema = z.strictObject({ source: z.number().int().nonnegative().nullable(), /** An index into `targets`; null when the checker binds nothing here (`unbound` says why). */ target: z.number().int().nonnegative().nullable(), + /** More targets, when the name means several members at once (a method of a union's every class). */ + also: z.array(z.number().int().nonnegative()).optional(), + /** A name that binds but is not a use: an import or export clause's name. It locates the symbol; it makes no edge. */ + clause: z.literal(true).optional(), unbound: z.enum(["unresolved", "any"]).nullable(), }); diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts index 12da77bb..4ccb1f51 100644 --- a/engine/src/srcly/ops/symbol-refs.ts +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -1,3 +1,4 @@ +import fs from "node:fs"; import path from "node:path"; import type * as TypeScript from "typescript"; import type { AnalysisCancellationToken } from "../../analysis/cancellation"; @@ -61,7 +62,7 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; if (ref !== "external") ref.source = enclosing(ts, node, source, intern); if (ref === "external") counts.external += 1; else { - if (ref.target) counts.bound += 1; + if (ref.target !== null) counts.bound += 1; else counts.unbound += 1; refs.push(ref); } @@ -104,7 +105,8 @@ function owners(tier1: TsTier1): (file: string) => Routed | undefined { const resolves = (o: TypeScript.CompilerOptions) => JSON.stringify([ o.paths ?? null, - o.paths ? (o.pathsBasePath ?? o.baseUrl ?? null) : (o.baseUrl ?? null), + // TypeScript resolves `paths` against `baseUrl` when one is set, else against the config that declared them. + o.baseUrl ?? (o.paths ? (o.pathsBasePath ?? null) : null), o.moduleResolution ?? null, o.module ?? null, o.customConditions ?? null, @@ -144,8 +146,9 @@ function owners(tier1: TsTier1): (file: string) => Routed | undefined { /** * A declaration in a built `.d.ts` under the root (a workspace package another project imports - * through its `dist`), followed to its source: the declaration file the checker resolved, with - * its output folder swapped for `src` (`dist/readers.d.ts` → `src/readers.ts`), and the same + * through its `dist`), followed to its source: the file its declaration map names, else the + * declaration file the checker resolved with its output folder swapped for `src` + * (`dist/readers.d.ts` → `src/readers.ts`, the convention a bundled build without maps leaves), and the same * export path looked up there by the checker (`tick`, `Runner.run`, `default`). Each alias hop * is tried first, so a named import reaches the module it was imported from, not a bundle chunk. * Nothing found means the reference stays external: no guessed module. @@ -158,6 +161,19 @@ function builtSources(tier1: TsTier1, root: string) { const checker = program.getTypeChecker(); const built = (file: TypeScript.SourceFile) => file.isDeclarationFile && file.fileName.startsWith(root + path.sep) && !file.fileName.includes(`${path.sep}node_modules${path.sep}`); const sourceOf = (file: TypeScript.SourceFile): TypeScript.SourceFile | undefined => { + // A declaration map names the source the build read: that, when there is one. + const map = `${file.fileName}.map`; + if (fs.existsSync(map)) { + try { + const sources = (JSON.parse(fs.readFileSync(map, "utf8")) as { sources?: unknown; sourceRoot?: unknown }).sources; + const first = Array.isArray(sources) && typeof sources[0] === "string" ? path.resolve(path.dirname(map), sources[0]) : undefined; + const hit = first ? program.getSourceFile(first.split(path.sep).join("/")) : undefined; + return hit && !hit.isDeclarationFile ? hit : undefined; + } catch { + return undefined; + } + } + // Else the build's convention: the output folder swapped for `src`. const stem = file.fileName.replace(/\.d\.[mc]?ts$/, ""); // The last output folder in the path is the one the build wrote (`packages/lib/dist/x`: `dist`). const parts = stem.split("/"); @@ -233,19 +249,25 @@ function bind( ): SymbolRef | "external" | "skip" { const parent = node.parent; if (!parent || skipped(ts, node, parent)) return "skip"; + // An import or export clause's name locates the symbol it binds, but is not a use. + const clause = ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent); const shorthand = ts.isShorthandPropertyAssignment(parent) && parent.name === node; // A declaration's own name is not a reference; `{ action }` is the one name that is both. - if (!shorthand && (parent as { name?: TypeScript.Node }).name === node && isDeclaration(ts, parent)) return "skip"; + if (!clause && !shorthand && (parent as { name?: TypeScript.Node }).name === node && isDeclaration(ts, parent)) return "skip"; const position = typePosition(ts, node); const inType = position !== "code"; - let symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(parent) : checker.getSymbolAtLocation(node); + let symbol = shorthand + ? checker.getShorthandAssignmentValueSymbol(parent) + : ts.isExportSpecifier(parent) && ts.isIdentifier(node) + ? (checker.getExportSpecifierLocalTargetSymbol(parent) ?? checker.getSymbolAtLocation(node)) + : checker.getSymbolAtLocation(node); const alias = symbol && symbol.flags & ts.SymbolFlags.Alias ? symbol : undefined; if (alias) symbol = checker.getAliasedSymbol(alias); const start = source.getLineAndCharacterOfPosition(node.getStart(source)); const syntactic = kindOf(ts, node); // A heritage clause keeps its own kind, whichever side of a name it binds. const kind: Kind = syntactic === "extends" || syntactic === "implements" ? syntactic : inType ? "type" : syntactic; - const ref = { source: null as number | null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind }; + const ref: SymbolRef = { source: null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind, target: null, unbound: null, ...(clause ? { clause: true as const } : {}) }; // `typeof x` in a type names the value x. let decl = symbol ? pick(ts, symbol, position === "type") : undefined; // A workspace package imported through its built `.d.ts`: the same declaration in its source. @@ -261,12 +283,13 @@ function bind( } const home = decl.getSourceFile(); if (!own(home)) return "external"; - return { ...ref, target: intern(decl, home), unbound: null }; + // A member of a union means each class's own member: every one is a target. + const also = symbol && !alias ? siblings(ts, symbol, decl).filter((d) => own(d.getSourceFile())).map((d) => intern(d, d.getSourceFile())) : []; + return { ...ref, target: intern(decl, home), unbound: null, ...(also.length ? { also } : {}) }; } /** Identifiers that are syntax, not a use: import and export clauses, labels, a JSX closing tag. */ function skipped(ts: Ts, node: TypeScript.Node, parent: TypeScript.Node): boolean { - if (ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent)) return true; if (ts.isLabeledStatement(parent) || ts.isBreakOrContinueStatement(parent)) return true; if (ts.isJsxClosingElement(parent)) return true; if (ts.isMetaProperty(parent)) return true; @@ -302,7 +325,7 @@ function kindOf(ts: Ts, node: TypeScript.Node): Kind { const parent = node.parent; // `a.b`: the member name stands for the whole access; the receiver `a` is a read. if ((ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isQualifiedName(parent) && parent.right === node) || (ts.isElementAccessExpression(parent) && parent.argumentExpression === node)) expr = parent; - while (ts.isParenthesizedExpression(expr.parent) || ts.isNonNullExpression(expr.parent) || ts.isAsExpression(expr.parent)) expr = expr.parent; + while (ts.isParenthesizedExpression(expr.parent) || ts.isNonNullExpression(expr.parent) || ts.isAsExpression(expr.parent) || ts.isSatisfiesExpression(expr.parent)) expr = expr.parent; const up = expr.parent; if (ts.isExpressionWithTypeArguments(up) && ts.isHeritageClause(up.parent)) return up.parent.token === ts.SyntaxKind.ImplementsKeyword ? "implements" : "extends"; if ((ts.isCallExpression(up) || ts.isDecorator(up) || ts.isTaggedTemplateExpression(up)) && (up as { expression?: TypeScript.Node; tag?: TypeScript.Node }).expression === expr) return "call"; @@ -340,6 +363,33 @@ function enclosing(ts: Ts, node: TypeScript.Node, home: TypeScript.SourceFile, i return null; } +/** + * The other declarations a name means at once: a member of a union, declared once per class or + * interface. Overloads, a class merged with its interface and one owner's accessors are one member. + */ +function siblings(ts: Ts, symbol: TypeScript.Symbol, chosen: TypeScript.Declaration): TypeScript.Declaration[] { + const decls = symbol.declarations ?? []; + if (decls.length < 2) return []; + const member = (d: TypeScript.Declaration) => ts.isClassElement(d) || ts.isTypeElement(d) || ts.isObjectLiteralElementLike(d); + if (!decls.every(member)) return []; + const ownerOf = (d: TypeScript.Declaration) => (d.parent && (ts.isClassLike(d.parent) || ts.isInterfaceDeclaration(d.parent) || ts.isTypeLiteralNode(d.parent) || ts.isObjectLiteralExpression(d.parent)) ? d.parent : undefined); + const owner = (d: TypeScript.Declaration) => { + const at = ownerOf(d); + const name = at && (at as { name?: TypeScript.Node }).name; + // A class and an interface of one name are one owner (declaration merging). + return name && ts.isIdentifier(name) ? `${at.getSourceFile().fileName}#${name.text}` : at; + }; + const seen = new Set([owner(chosen)]); + const out: TypeScript.Declaration[] = []; + for (const d of decls) { + const key = owner(d); + if (key === undefined || seen.has(key)) continue; + seen.add(key); + out.push(d); + } + return out; +} + const isTypeDecl = (ts: Ts, d: TypeScript.Declaration) => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d); /** The declaration the location means: in a type, a type-side one; in code, a value-side one. */ @@ -356,11 +406,12 @@ function pick(ts: Ts, symbol: TypeScript.Symbol, inType: boolean): TypeScript.De function targetOf(ts: Ts, decl: TypeScript.Declaration, home: TypeScript.SourceFile, rel: (file: string) => string): SymbolRefTarget { const file = rel(home.fileName); - if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, meaning: "value", scope: "module" }; + if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, column: 1, meaning: "value", scope: "module" }; const name = ts.getNameOfDeclaration(decl); const text = ts.isConstructorDeclaration(decl) ? "constructor" : ts.isExportAssignment(decl) && !decl.isExportEquals ? "default" : name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; - const at = home.getLineAndCharacterOfPosition((name ?? decl).getStart(home)); - return { file, name: text, line: at.line + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; + const anchor = ts.isExportAssignment(decl) ? decl.expression : (name ?? decl); + const at = home.getLineAndCharacterOfPosition(anchor.getStart(home)); + return { file, name: text, line: at.line + 1, column: at.character + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; } function scopeOf(ts: Ts, decl: TypeScript.Node): SymbolRefTarget["scope"] { diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts index e96f4c36..60a88a47 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts @@ -8,3 +8,5 @@ export function app() { new lib.Runner()["run"](); return main(); } +import { run } from "kit/entry"; +export const mapped = run(); diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json index 525df808..5a5d256e 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/tsconfig.json @@ -1 +1,20 @@ -{ "compilerOptions": { "strict": true, "module": "esnext", "moduleResolution": "bundler", "target": "es2022", "noEmit": true, "paths": { "lib": ["../packages/lib/dist/index.d.ts"] } }, "include": ["src"] } +{ + "compilerOptions": { + "strict": true, + "module": "esnext", + "moduleResolution": "bundler", + "target": "es2022", + "noEmit": true, + "paths": { + "lib": [ + "../packages/kit/dist/index.d.ts" + ], + "kit/entry": [ + "../packages/kit/dist/entry.d.ts" + ] + } + }, + "include": [ + "src" + ] +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts new file mode 100644 index 00000000..f6a73111 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts @@ -0,0 +1,2 @@ +export declare function run(): string; +//# sourceMappingURL=entry.d.ts.map diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts.map b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts.map new file mode 100644 index 00000000..97267784 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/entry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"entry.d.ts","sourceRoot":"","sources":["../src/real.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,WAElB"} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/index.d.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/index.d.ts new file mode 100644 index 00000000..439f2915 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/dist/index.d.ts @@ -0,0 +1,6 @@ +export declare function tick(): number; +export declare class Runner { + run(): number; +} +declare function main(): number; +export default main; diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/package.json b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/package.json new file mode 100644 index 00000000..4878d30e --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/package.json @@ -0,0 +1 @@ +{ "name": "lib", "types": "./dist/index.d.ts" } diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/entry.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/entry.ts new file mode 100644 index 00000000..cc71d845 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/entry.ts @@ -0,0 +1,3 @@ +export function run() { + return "decoy"; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/index.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/index.ts new file mode 100644 index 00000000..657675aa --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/index.ts @@ -0,0 +1,13 @@ +export function tick() { + return 1; +} + +export class Runner { + run() { + return 2; + } +} + +export default function main() { + return 3; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/real.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/real.ts new file mode 100644 index 00000000..ff8845b8 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/src/real.ts @@ -0,0 +1,3 @@ +export function run() { + return "real"; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/tsconfig.json b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/tsconfig.json new file mode 100644 index 00000000..743457f9 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/packages/kit/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "strict": true, "module": "esnext", "moduleResolution": "bundler", "target": "es2022", "noEmit": true }, "include": ["src"] } diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts index 50e103f7..ac085634 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/m.ts @@ -17,3 +17,8 @@ export interface Model { id: number; } export const Model = { id: 1 }; +export class Other { + bump() { + return 2; + } +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx index f3b3fcaa..33e02b20 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx @@ -31,3 +31,7 @@ export interface Wider extends Model { extra: boolean; } import { Model } from "./m"; +import { Other } from "./m"; +export function either(x: Store | Other) { + return (x.bump satisfies () => number)() + x.bump(); +} diff --git a/engine/test/srcly/symbol-refs.test.ts b/engine/test/srcly/symbol-refs.test.ts index 8cb40a01..43999edb 100644 --- a/engine/test/srcly/symbol-refs.test.ts +++ b/engine/test/srcly/symbol-refs.test.ts @@ -18,10 +18,11 @@ describe("symbolRefs binds every identifier with the checker", () => { }; const source = fs.readFileSync(path.join(root, "src/use.tsx"), "utf8").split("\n"); - it("answers ok for the files asked, with no import clause as a reference", () => { + it("answers ok for the files asked, with import clauses marked as names, not uses", () => { expect(result.outcome).toBe("ok"); expect(result.files.map((f) => f.file)).toEqual(["src/use.tsx"]); - expect(lines.filter((ref) => ref.line <= 2)).toEqual([]); + // Import clause names only locate a symbol: each is marked, none is a use. + expect(lines.filter((ref) => ref.line <= 2).every((ref) => ref.clause)).toBe(true); }); it("splits a name's type and value by position, typeof included", () => { @@ -49,6 +50,18 @@ describe("symbolRefs binds every identifier with the checker", () => { expect(at(30, "Model")).toMatchObject({ kind: "extends", to: { name: "Model", line: 16, meaning: "type" } }); }); + it("binds a union member to every class's own member, and a call through `satisfies` stays a call", () => { + const union = at(36, "bump"); + expect(union).toMatchObject({ kind: "call", to: { name: "bump", line: 6 } }); + expect((union.also ?? []).map((i) => result.targets[i])).toMatchObject([{ name: "bump", line: 21 }]); + expect(at(36, "bump()")).toMatchObject({ kind: "call" }); + }); + + it("locates an import clause's name without making it a use", () => { + expect(at(34, "Other")).toMatchObject({ clause: true, to: { name: "Other", line: 20, column: 14 } }); + expect(at(36, "bump()").clause).toBeUndefined(); + }); + it("binds a forward reference to a block-local alias", () => { expect(at(20, "Local").to).toMatchObject({ file: "src/use.tsx", name: "Local", line: 23, meaning: "type", scope: "local" }); }); @@ -64,7 +77,7 @@ describe("symbolRefs follows a workspace package's built .d.ts to its source", ( if (!ref) throw new Error(`no ref at ${line}:${column} (${needle})`); return { ...ref, to: ref.target === null ? null : result.targets[ref.target] }; }; - const lib = "packages/lib/src/index.ts"; + const lib = "packages/kit/src/index.ts"; it("binds named, namespace, class-member, bracket and default uses to the source", () => { expect(at(5, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); @@ -74,4 +87,8 @@ describe("symbolRefs follows a workspace package's built .d.ts to its source", ( expect(at(8, '"run"')).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6 } }); expect(at(9, "main")).toMatchObject({ kind: "call", to: { file: lib, name: "main", line: 11 } }); }); + + it("follows a declaration map over the conventional path", () => { + expect(at(12, "run")).toMatchObject({ kind: "call", to: { file: "packages/kit/src/real.ts", name: "run", line: 1 } }); + }); }); diff --git a/server/app/services/dataflow/contracts/symbolRefs.schema.json b/server/app/services/dataflow/contracts/symbolRefs.schema.json index 941f1df1..f1879b10 100644 --- a/server/app/services/dataflow/contracts/symbolRefs.schema.json +++ b/server/app/services/dataflow/contracts/symbolRefs.schema.json @@ -55,6 +55,11 @@ "exclusiveMinimum": 0, "maximum": 9007199254740991 }, + "column": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, "meaning": { "type": "string", "enum": [ @@ -75,6 +80,7 @@ "file", "name", "line", + "column", "meaning", "scope" ], @@ -145,6 +151,18 @@ } ] }, + "also": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "clause": { + "type": "boolean", + "const": true + }, "unbound": { "anyOf": [ { diff --git a/server/app/services/dataflow/models.py b/server/app/services/dataflow/models.py index e99b2c8b..65d87989 100644 --- a/server/app/services/dataflow/models.py +++ b/server/app/services/dataflow/models.py @@ -531,6 +531,7 @@ class SymbolRefTarget(BaseModel): file: str name: str line: int + column: int meaning: Literal["value", "type"] scope: Literal["module", "member", "local"] @@ -542,6 +543,8 @@ class SymbolRef(BaseModel): kind: Literal["call", "instantiate", "read", "write", "type", "extends", "implements"] source: int | None target: int | None + also: list[int] | None = None + clause: Literal[True] | None = None unbound: Literal["unresolved", "any"] | None diff --git a/server/app/services/symbols/checker.py b/server/app/services/symbols/checker.py index 8400028d..e3717512 100644 --- a/server/app/services/symbols/checker.py +++ b/server/app/services/symbols/checker.py @@ -33,6 +33,9 @@ class CheckerRefs: unbound: Counter = field(default_factory=Counter) # reason → count # A module-scope declaration the checker binds that no tree-sitter symbol holds: a mapping bug, listed. mismatched: List[str] = field(default_factory=list) + # Every bound name's position, edges or not (an import clause's name, a recursive call): + # (file, line) → [(column, end column, symbol id)], for Show references. + positions: Dict[Tuple[str, int], List[Tuple[int, int, str]]] = field(default_factory=lambda: defaultdict(list)) generation: Optional[int] = None program_hash: Optional[str] = None @@ -41,7 +44,15 @@ class CheckerRefs: LASTING = frozenset({"python-root", "node-not-found", "engine-missing", "no-tsconfig", "no-ts-files", "typescript-not-found", "engine-protocol-mismatch"}) -def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Optional[str]]: +def still_missing(root: Path, registry=None) -> bool: + """Whether the engine still cannot run for the root: no Node or engine, or a failure on record.""" + from app.services.dataflow.engine import registry as shared + + reg = registry if registry is not None else shared + return not reg.probe(root).available or reg.failure(root) is not None + + +def query(root: Path, registry=None, refresh: bool = False) -> Tuple[Optional[SymbolRefsResult], Optional[str]]: """ The engine's ``symbolRefs`` for the root, from the sources as they are now, or None and the reason it has none. The engine keeps its Program until asked to refresh, so a stale @@ -61,7 +72,7 @@ def query(root: Path, registry=None) -> Tuple[Optional[SymbolRefsResult], Option return None, known.code try: status = reg.query(root, "status", {}) - if status.get("stale"): + if refresh or status.get("stale"): reg.query(root, "refresh", {}, timeout=180.0) # A walk of the whole program: allow more than one ordinary query. raw = reg.query(root, "symbolRefs", {}, timeout=180.0) @@ -106,9 +117,9 @@ def target(self, t: SymbolRefTarget) -> Optional[str]: if t.name == "*": return t.file if t.file in self.modules else None want_type = t.meaning == "type" - # The declaration whose name is on that line: a shadowing parameter or an unindexed local - # inside a same-named symbol's body never joins it. - held = [s for s in self.by_name.get((t.file, t.name), ()) if any(line == t.line for line, _ in s.names)] + # The declaration whose name is at that very position: a shadowing parameter or an unindexed + # local inside a same-named symbol's body never joins it, on any line. + held = [s for s in self.by_name.get((t.file, t.name), ()) if (t.line, t.column) in s.names] if not held and t.scope == "member": # A member the index keeps no symbol for (an interface's field, an object type's member): # the type, class or variable that declares it, as a typed receiver gives today. @@ -143,12 +154,15 @@ def join(result: SymbolRefsResult, symbols: Dict[str, Symbol]) -> CheckerRefs: if r.target is None: out.unbound[r.unbound or "unresolved"] += 1 continue - target = targets[r.target] - if target is None: + # A union's member means each class's own member: one reference to each. + bound = [t for t in dict.fromkeys(targets[i] for i in [r.target, *(r.also or [])]) if t is not None] + for target in bound: + out.positions[(f.file, r.line)].append((r.column, r.endColumn, target)) + if r.clause: continue # The enclosing declaration's symbol, else the innermost symbol holding the line. source = (targets[r.source] if r.source is not None else None) or files.source(f.file, r.line) - if source == target: - continue - out.references.append(Reference(source=source, target=target, kind=r.kind, line=r.line, column=r.column, end_column=r.endColumn)) + for target in bound: + if source != target: + out.references.append(Reference(source=source, target=target, kind=r.kind, line=r.line, column=r.column, end_column=r.endColumn)) return out diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index f3265c5a..1dc14958 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -18,7 +18,7 @@ from app.services.deps.typescript_deps import TS_EXTENSIONS from app.services.dataflow.models import SymbolRefsResult as CheckerResult from app.services.symbols.checker import LASTING as LASTING_REASONS -from app.services.symbols.checker import current_hash, join +from app.services.symbols.checker import current_hash, join, still_missing from app.services.symbols.checker import query as query_checker from app.services.symbols.model import BUILTIN_MEMBERS, REF_KINDS, FileSymbols, PendingMember, RefKind, Reference, Symbol @@ -53,6 +53,9 @@ class SymbolIndex: mismatched: List[str] = field(default_factory=list) outside_program: int = 0 program_hash: Optional[str] = None + # Checker mode: each bound name's span by (file, line), and the TS files tree-sitter bound instead. + positions: Dict[Tuple[str, int], List[Tuple[int, int, str]]] = field(default_factory=dict) + unchecked_files: Set[str] = field(default_factory=set) _by_line: Optional[Dict[Tuple[str, int], List[int]]] = None def __post_init__(self) -> None: @@ -354,10 +357,14 @@ def at(self, file: str, line: int, column: int, name: str) -> Tuple[Optional[str Never a search by name alone. """ here = [self.references[i] for i in self._refs_on_line().get((file, line), [])] - spanned = [r for r in here if r.column is not None and r.end_column is not None and r.column <= column < r.end_column] - if spanned: - return spanned[0].target, [] - if not any(r.column is not None for r in here): + if self.binder == "checker" and file not in self.unchecked_files: + # Every bound name the checker saw, edges or not: an import's name, a recursive call. + bound = sorted({target for start, end, target in self.positions.get((file, line), ()) if start <= column < end}) + if len(bound) == 1: + return bound[0], [] + if bound: + return None, bound # a union's member: one per class + elif not any(r.column is not None for r in here): named = sorted({r.target for r in here if self.symbols[r.target].name == name}) if len(named) == 1: return named[0], [] @@ -421,7 +428,11 @@ def assemble(root: Path, parts: List[FileSymbols], checker: Optional[CheckerResu for part in parts: for sym in part.symbols: symbols.setdefault(sym.id, sym) + # A class the checker covers takes its bases from the checker's `extends` edges only (below). + covered = {f.file for f in checker.files} if checker is not None else set() for part in parts: + if part.file in covered: + continue for cls, bases in part.bases.items(): if cls in symbols: symbols[cls].bases = [b for b in bases if b in symbols] @@ -473,6 +484,8 @@ def assemble(root: Path, parts: List[FileSymbols], checker: Optional[CheckerResu index.unbound = dict(bound.unbound) index.mismatched = bound.mismatched index.program_hash = bound.program_hash + index.positions = dict(bound.positions) + index.unchecked_files = {p.file for p in parts if Path(p.file).suffix in TS_EXTENSIONS} index.outside_program = sum(1 for p in parts if Path(p.file).suffix in TS_EXTENSIONS) index.members_by_name = members_by_name index.http_links, index.http_unmatched = http_links, http_unmatched @@ -635,12 +648,25 @@ def _demote(kind: RefKind) -> RefKind: return "write" if kind == "write" else "read" -_cache: Dict[Tuple[Path, str], Tuple[SourceSignature, SymbolIndex]] = {} +_cache: Dict[Tuple[Path, str], Tuple[Tuple[SourceSignature, Optional[SourceSignature]], SymbolIndex]] = {} _lock = threading.Lock() SOURCE_EXTENSIONS = TS_EXTENSIONS | {".py"} +def _config_files(root: Path) -> List[Path]: + return [p for p in walk_source_files(root, {".json"}) if p.name.startswith(("tsconfig", "jsconfig"))] + + +def _still_current(root: Path, index: SymbolIndex, registry) -> bool: + """A cached checker index while its Program is the engine's current one; a cached fallback while the checker is still missing.""" + if index.binder == "checker": + return current_hash(root, registry) == index.program_hash + if index.binder_reason in ("python-root", "asked"): + return True + return still_missing(root, registry) + + def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-sitter", registry=None) -> SymbolIndex: """ The index of a root. ``binder="checker"`` binds TypeScript references with the data-flow @@ -649,14 +675,17 @@ def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-s """ root = root.resolve() files = walk_source_files(root, SOURCE_EXTENSIONS) + # The checker's answer also depends on every tsconfig, an extended base included. + configs = source_signature(_config_files(root)) if binder == "checker" else None + refresh = False if use_cache: - sig = source_signature(files) + sig = (source_signature(files), configs) with _lock: hit = _cache.get((root, binder)) - # A checker index also holds while the Program it came from is current: a tsconfig edit - # or a source the walk did not see changes the engine's hash. - if hit is not None and hit[0] == sig and (hit[1].binder != "checker" or current_hash(root, registry) == hit[1].program_hash): + if hit is not None and hit[0] == sig and _still_current(root, hit[1], registry): return hit[1] + # A config the engine's own hash may not cover changed: rebuild its Program. + refresh = hit is not None and hit[0][1] != configs parts: List[FileSymbols] = [] ts_files = [f for f in files if f.suffix in TS_EXTENSIONS] if ts_files: @@ -673,7 +702,7 @@ def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-s checked: Optional[CheckerResult] = None reason: Optional[str] = None if ts_files and binder == "checker": - checked, reason = query_checker(root, registry) + checked, reason = query_checker(root, registry, refresh=refresh) index = assemble(root, parts, checked) if index.binder != "checker": index.binder_reason = reason if binder == "checker" else "asked" diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py index 73ce0251..1c73c3fc 100644 --- a/server/tests/test_symbol_checker_join.py +++ b/server/tests/test_symbol_checker_join.py @@ -28,7 +28,10 @@ ) -def _result(targets, refs, file="src/m.ts"): +def _result(targets, refs, file="src/m.ts", text=None): + """Targets are (file, name, line, meaning, scope); the name's column is its first spelling on that line.""" + lines = (text or M).split("\n") + targets = [(f, n, line, lines[line - 1].index(n) + 1, meaning, scope) for f, n, line, meaning, scope in targets] return SymbolRefsResult.model_validate( { "outcome": "ok", @@ -38,7 +41,7 @@ def _result(targets, refs, file="src/m.ts"): "typescript": "5", "nullProof": True, "reason": None, - "targets": [dict(zip(("file", "name", "line", "meaning", "scope"), t)) for t in targets], + "targets": [dict(zip(("file", "name", "line", "column", "meaning", "scope"), t)) for t in targets], "files": [{"file": file, "refs": [dict(zip(("line", "column", "endColumn", "kind", "source", "target", "unbound"), r)) for r in refs]}], "counts": {"files": 1, "bound": 0, "unbound": 0, "external": 0}, } @@ -109,8 +112,35 @@ def test_a_name_joins_only_the_declaration_on_its_own_line(tmp_path: Path): parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "h.ts"]) targets = [("src/h.ts", "wrapper", 2, "value", "local"), ("src/h.ts", "handler", 2, "value", "local")] # `handler()` on line 2 calls the parameter, declared on line 2: not the function on line 1. - idx = assemble(tmp_path, parts, _result(targets, [(2, 43, 50, "call", 0, 1, None)], file="src/h.ts")) + idx = assemble(tmp_path, parts, _result([("src/h.ts", "wrapper", 2, "value", "local"), ("src/h.ts", "handler", 2, "value", "local")], [(2, 43, 50, "call", 0, 1, None)], file="src/h.ts", text=src)) assert [r for r in idx.references if r.target == "src/h.ts#handler"] == [] # The DOM method inside the one-line wrapper is not the wrapper; its own name is. assert idx.at("src/h.ts", 5, 50, "getSelection") == (None, []) assert idx.at("src/h.ts", 5, 17, "getSelection") == ("src/h.ts#getSelection", []) + + +def test_one_line_shadowing_and_positions_without_edges(tmp_path: Path): + src = "export function handler() { function wrapper(handler: () => void) { handler(); } return handler(); }" + (tmp_path / "src").mkdir() + (tmp_path / "src" / "h.ts").write_text(src, encoding="utf-8") + parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "h.ts"]) + param = src.index("handler:") + 1 + targets = [("src/h.ts", "handler", 1, param, "value", "local"), ("src/h.ts", "handler", 1, 17, "value", "module")] + result = SymbolRefsResult.model_validate( + { + "outcome": "ok", "generation": 1, "programHash": "h", "tsconfig": "", "typescript": "5", "nullProof": True, "reason": None, + "targets": [dict(zip(("file", "name", "line", "column", "meaning", "scope"), t)) for t in targets], + "files": [{"file": "src/h.ts", "refs": [ + # the parameter's call, then the recursive call to the function itself + {"line": 1, "column": src.index("handler();") + 1, "endColumn": src.index("handler();") + 8, "kind": "call", "source": None, "target": 0, "unbound": None}, + {"line": 1, "column": src.rindex("handler()") + 1, "endColumn": src.rindex("handler()") + 8, "kind": "call", "source": 1, "target": 1, "unbound": None}, + ]}], + "counts": {"files": 1, "bound": 2, "unbound": 0, "external": 0}, + } + ) + idx = assemble(tmp_path, parts, result) + # On one line, the parameter still never joins the outer function, and a recursive call makes no edge. + assert idx.references == [] + # Show references still finds the function at its recursive call. + assert idx.at("src/h.ts", 1, src.rindex("handler()") + 1, "handler") == ("src/h.ts#handler", []) + assert idx.at("src/h.ts", 1, src.index("handler();") + 1, "handler") == (None, []) From ffdf235fef744f0a79192541c50a1829fa6521ac Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 01:03:41 -0500 Subject: [PATCH 11/13] fix(symbols): type-only clauses, module-level sources, union order, default anchors, Python lookups Codex round 3: a type-only import or export clause names the type side; a reference with no enclosing declaration is module code; a union keeps its local members when an external one comes first; an anonymous default function anchors after 'default' in both binders; Python files keep tree-sitter's position lookup in a checker index; file names compare in TypeScript's '/' spelling; the workspace fixture's imports come first. Co-Authored-By: Claude Opus 5.5 --- docs/intent/checker-symbol-index/README.md | 14 ++++--- engine/src/srcly/ops/symbol-refs.ts | 41 ++++++++++++++----- .../symbol-refs-workspace/app/src/use.ts | 2 +- .../__fixtures__/symbol-refs/src/anon.ts | 3 ++ .../__fixtures__/symbol-refs/src/use.tsx | 8 ++-- engine/test/srcly/symbol-refs.test.ts | 25 +++++++---- server/app/services/symbols/checker.py | 5 ++- server/app/services/symbols/index.py | 9 ++-- server/tests/test_symbol_checker_join.py | 25 +++++++++++ 9 files changed, 96 insertions(+), 36 deletions(-) create mode 100644 engine/test/srcly/__fixtures__/symbol-refs/src/anon.ts diff --git a/docs/intent/checker-symbol-index/README.md b/docs/intent/checker-symbol-index/README.md index 060cd4ca..339f5f9c 100644 --- a/docs/intent/checker-symbol-index/README.md +++ b/docs/intent/checker-symbol-index/README.md @@ -169,17 +169,19 @@ Run it on srcly and explorEDA (`f44a5c63` or newer). Done when: | Root | Tree-sitter refs | Checker refs | Agree | Mismatched ids | TS files outside the Program | Unbound | | --- | ---: | ---: | ---: | ---: | ---: | --- | -| srcly (this branch) | 40,464 | 61,113 | 38,879 (96.1%) | 5 | 176 | 615 unresolved, 815 `any` | -| explorEDA `f44a5c63` | 49,092 | 74,720 | 47,445 (96.6%) | 3 | 452 | 1,657 unresolved, 40 `any` | +| srcly (this branch) | 40,736 | 61,653 | 39,141 (96.1%) | 11 | 179 | 1,175 unresolved, 811 `any` | +| explorEDA `f44a5c63` | 49,092 | 85,223 | 47,451 (96.7%) | 3 | 452 | 1,676 unresolved, 40 `any` | + +The join is exact: a target joins the tree-sitter symbol whose name is at the same line and UTF-16 column. A member with no symbol joins the type, class, enum or variable that holds it. A union's member counts once for each member type that declares it. The buckets, by size (explorEDA; srcly has the same shape): -- Checker only, `read → type` (24,861): a member read through a receiver whose type tree-sitter cannot see (inferred, returned, destructured, a union). The member has no symbol, so it joins the type that declares it, as tree-sitter's `typed` rule does for an annotated receiver. -- Checker only, `call → function` (622), `call → type` (410), `read → variable` (1,113): calls through re-exports and closures, interface method calls, fields of object constants (zod schemas). -- Tree-sitter only, `typed · read → type` (1,412): the checker binds the member somewhere more exact (a union member's own interface, a base interface, the TypeScript library behind `type Ts = typeof TypeScript`), or the type is mapped and has no declaration. +- Checker only, `read → type` (35,343): a member read through a receiver whose type tree-sitter cannot see (inferred, returned, destructured, a union). The member has no symbol, so it joins the type that declares it, as tree-sitter's `typed` rule does for an annotated receiver. +- Checker only, `call → function` (622), `call → type` (413), `read → variable` (1,117): calls through re-exports and closures, interface method calls, fields of object constants (zod schemas). +- Tree-sitter only, `typed · read → type` (1,406): the checker binds the member somewhere more exact (a union member's own interface, a base interface, the TypeScript library behind `type Ts = typeof TypeScript`), or the type is mapped and has no declaration. - Tree-sitter only, `name · call → method/field` (111): name guesses the checker refuses, such as a TypeScript call bound to the Python method `BodyWalker.literal`. - Tree-sitter only, `exact · call → function/variable` (74): mostly JSX intrinsic tags (``, ``) that tree-sitter bound to a local of the same name. -- Mismatched ids: srcly's 5 are `declare function` declarations, which the index keeps no symbol for. explorEDA's 3 are in `FieldListRow.tsx`, where tree-sitter makes no symbol after ``. +- Mismatched ids: srcly's 11 are `declare function` declarations (7), which the index keeps no symbol for, and files the index does not walk (4, untracked `engine/tmp` output). explorEDA's 3 are in `FieldListRow.tsx`, where tree-sitter makes no symbol after ``. - Outside the Program: test files (the engine's Program leaves them out), configs and docs scripts. They keep tree-sitter references. Spot checks by hand: the `Legend.span`, `BoxCell.line` and `RowChart.span` rows (JSX tags), `PlotManager.onKeyDown` (four locals that tree-sitter merges into one symbol), `CoverageMatrix.tsx:103` (a `@/` path in `apps/demo`, which needed its own tsconfig's Program), and `PageFileDrop.tsx` (a workspace package's `.d.ts`, followed to source). diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts index 4ccb1f51..52dffcf3 100644 --- a/engine/src/srcly/ops/symbol-refs.ts +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -24,9 +24,10 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; } const { ts, program } = tier1; const primaryChecker = program.getTypeChecker(); - const root = path.resolve(tier1.root); - const rel = (file: string) => path.relative(root, file).split(path.sep).join("/"); - const own = (source: TypeScript.SourceFile) => source.fileName.startsWith(root + path.sep) && !source.fileName.includes(`${path.sep}node_modules${path.sep}`) && !source.isDeclarationFile; + // TypeScript spells every file name with "/", on Windows too: compare in that spelling. + const root = slash(path.resolve(tier1.root)); + const rel = (file: string) => path.posix.relative(root, slash(file)); + const own = (source: TypeScript.SourceFile) => slash(source.fileName).startsWith(`${root}/`) && !source.fileName.includes("/node_modules/") && !source.isDeclarationFile; const wanted = params.files ? new Set((params.files as string[]).map((f) => f.split(path.sep).join("/"))) : null; const sources = program .getSourceFiles() @@ -88,6 +89,8 @@ export function symbolRefsOp(session: EngineSession, params: { files?: unknown; }); } +const slash = (file: string) => file.split(path.sep).join("/"); + type Routed = { program: TypeScript.Program; checker: TypeScript.TypeChecker }; const routedByTier = new WeakMap>(); @@ -159,7 +162,7 @@ function builtSources(tier1: TsTier1, root: string) { const { ts, program } = tier1; // The package's source is in the primary Program, whichever Program bound the reference. const checker = program.getTypeChecker(); - const built = (file: TypeScript.SourceFile) => file.isDeclarationFile && file.fileName.startsWith(root + path.sep) && !file.fileName.includes(`${path.sep}node_modules${path.sep}`); + const built = (file: TypeScript.SourceFile) => file.isDeclarationFile && slash(file.fileName).startsWith(`${root}/`) && !file.fileName.includes("/node_modules/"); const sourceOf = (file: TypeScript.SourceFile): TypeScript.SourceFile | undefined => { // A declaration map names the source the build read: that, when there is one. const map = `${file.fileName}.map`; @@ -251,6 +254,8 @@ function bind( if (!parent || skipped(ts, node, parent)) return "skip"; // An import or export clause's name locates the symbol it binds, but is not a use. const clause = ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent); + // `import type { A }` and `export type { A }` name the type side of a split name. + const typeOnly = clause && typeOnlyClause(ts, parent); const shorthand = ts.isShorthandPropertyAssignment(parent) && parent.name === node; // A declaration's own name is not a reference; `{ action }` is the one name that is both. if (!clause && !shorthand && (parent as { name?: TypeScript.Node }).name === node && isDeclaration(ts, parent)) return "skip"; @@ -269,7 +274,7 @@ function bind( const kind: Kind = syntactic === "extends" || syntactic === "implements" ? syntactic : inType ? "type" : syntactic; const ref: SymbolRef = { source: null, line: start.line + 1, column: start.character + 1, endColumn: start.character + 1 + node.getWidth(source), kind, target: null, unbound: null, ...(clause ? { clause: true as const } : {}) }; // `typeof x` in a type names the value x. - let decl = symbol ? pick(ts, symbol, position === "type") : undefined; + let decl = symbol ? pick(ts, symbol, position === "type" || typeOnly) : undefined; // A workspace package imported through its built `.d.ts`: the same declaration in its source. if (symbol && decl?.getSourceFile().isDeclarationFile) { const fromSource = toSource(checker, symbol, alias); @@ -281,11 +286,11 @@ function bind( const any = receiver ? (checker.getTypeAtLocation(receiver).flags & ts.TypeFlags.Any) !== 0 : false; return { ...ref, target: null, unbound: any ? "any" : "unresolved" }; } - const home = decl.getSourceFile(); - if (!own(home)) return "external"; - // A member of a union means each class's own member: every one is a target. - const also = symbol && !alias ? siblings(ts, symbol, decl).filter((d) => own(d.getSourceFile())).map((d) => intern(d, d.getSourceFile())) : []; - return { ...ref, target: intern(decl, home), unbound: null, ...(also.length ? { also } : {}) }; + // A member of a union means each class's own member: every one is a target, the program's own only. + const all = [decl, ...(symbol && !alias ? siblings(ts, symbol, decl) : [])].filter((d) => own(d.getSourceFile())); + if (!all.length) return "external"; + const [first, ...rest] = all.map((d) => intern(d, d.getSourceFile())); + return { ...ref, target: first, unbound: null, ...(rest.length ? { also: rest } : {}) }; } /** Identifiers that are syntax, not a use: import and export clauses, labels, a JSX closing tag. */ @@ -390,6 +395,16 @@ function siblings(ts: Ts, symbol: TypeScript.Symbol, chosen: TypeScript.Declarat return out; } +function typeOnlyClause(ts: Ts, clause: TypeScript.Node): boolean { + if ((ts.isImportSpecifier(clause) || ts.isExportSpecifier(clause)) && clause.isTypeOnly) return true; + for (let at: TypeScript.Node | undefined = clause; at; at = at.parent) { + if (ts.isImportClause(at)) return at.isTypeOnly; + if (ts.isExportDeclaration(at)) return at.isTypeOnly; + if (ts.isImportDeclaration(at)) return false; + } + return false; +} + const isTypeDecl = (ts: Ts, d: TypeScript.Declaration) => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d); /** The declaration the location means: in a type, a type-side one; in code, a value-side one. */ @@ -409,8 +424,12 @@ function targetOf(ts: Ts, decl: TypeScript.Declaration, home: TypeScript.SourceF if (ts.isSourceFile(decl)) return { file, name: "*", line: 1, column: 1, meaning: "value", scope: "module" }; const name = ts.getNameOfDeclaration(decl); const text = ts.isConstructorDeclaration(decl) ? "constructor" : ts.isExportAssignment(decl) && !decl.isExportEquals ? "default" : name && (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : "default"; + // `export default ` and an anonymous `export default function` anchor at what follows + // `default`, where srcly's tree-sitter index puts `file#default`. + const after = !name && ts.canHaveModifiers(decl) ? ts.getModifiers(decl)?.find((m) => m.kind === ts.SyntaxKind.DefaultKeyword) : undefined; const anchor = ts.isExportAssignment(decl) ? decl.expression : (name ?? decl); - const at = home.getLineAndCharacterOfPosition(anchor.getStart(home)); + const start = after ? after.end + (home.text.slice(after.end).match(/^\s*/)?.[0].length ?? 0) : anchor.getStart(home); + const at = home.getLineAndCharacterOfPosition(start); return { file, name: text, line: at.line + 1, column: at.character + 1, meaning: ts.isTypeParameterDeclaration(decl) || isTypeDecl(ts, decl) ? "type" : "value", scope: scopeOf(ts, decl) }; } diff --git a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts index 60a88a47..1d9e87a0 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts +++ b/engine/test/srcly/__fixtures__/symbol-refs-workspace/app/src/use.ts @@ -1,5 +1,6 @@ import main, { tick, Runner } from "lib"; import * as lib from "lib"; +import { run } from "kit/entry"; export function app() { tick(); @@ -8,5 +9,4 @@ export function app() { new lib.Runner()["run"](); return main(); } -import { run } from "kit/entry"; export const mapped = run(); diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/anon.ts b/engine/test/srcly/__fixtures__/symbol-refs/src/anon.ts new file mode 100644 index 00000000..1e2ce7e1 --- /dev/null +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/anon.ts @@ -0,0 +1,3 @@ +export default function () { + return 1; +} diff --git a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx index 33e02b20..54f87324 100644 --- a/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx +++ b/engine/test/srcly/__fixtures__/symbol-refs/src/use.tsx @@ -1,4 +1,4 @@ -import A, { Store } from "./m"; +import A, { Store, Model, Other } from "./m"; import * as m from "./m"; declare function pick(): T; @@ -30,8 +30,10 @@ export class Impl implements Model { export interface Wider extends Model { extra: boolean; } -import { Model } from "./m"; -import { Other } from "./m"; export function either(x: Store | Other) { return (x.bump satisfies () => number)() + x.bump(); } +import type { Row as Imported } from "./m"; +export let imported: Imported | undefined; +import anon from "./anon"; +export const anonValue = anon(); diff --git a/engine/test/srcly/symbol-refs.test.ts b/engine/test/srcly/symbol-refs.test.ts index 43999edb..4a5bb9b9 100644 --- a/engine/test/srcly/symbol-refs.test.ts +++ b/engine/test/srcly/symbol-refs.test.ts @@ -51,15 +51,22 @@ describe("symbolRefs binds every identifier with the checker", () => { }); it("binds a union member to every class's own member, and a call through `satisfies` stays a call", () => { - const union = at(36, "bump"); + const union = at(34, "bump"); expect(union).toMatchObject({ kind: "call", to: { name: "bump", line: 6 } }); expect((union.also ?? []).map((i) => result.targets[i])).toMatchObject([{ name: "bump", line: 21 }]); - expect(at(36, "bump()")).toMatchObject({ kind: "call" }); + expect(at(34, "bump()")).toMatchObject({ kind: "call" }); }); it("locates an import clause's name without making it a use", () => { - expect(at(34, "Other")).toMatchObject({ clause: true, to: { name: "Other", line: 20, column: 14 } }); - expect(at(36, "bump()").clause).toBeUndefined(); + expect(at(1, "Other")).toMatchObject({ clause: true, to: { name: "Other", line: 20, column: 14 } }); + expect(at(34, "bump()").clause).toBeUndefined(); + // A type-only clause names the type side of a split name, like its uses. + expect(at(36, "Row")).toMatchObject({ clause: true, to: { name: "Row", line: 1, meaning: "type" } }); + expect(at(36, "Imported")).toMatchObject({ clause: true, to: { name: "Row", line: 1, meaning: "type" } }); + }); + + it("anchors an anonymous default function where tree-sitter names it, after `default`", () => { + expect(at(39, "anon()")).toMatchObject({ kind: "call", to: { file: "src/anon.ts", name: "default", line: 1, column: 16 } }); }); it("binds a forward reference to a block-local alias", () => { @@ -80,12 +87,12 @@ describe("symbolRefs follows a workspace package's built .d.ts to its source", ( const lib = "packages/kit/src/index.ts"; it("binds named, namespace, class-member, bracket and default uses to the source", () => { - expect(at(5, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); expect(at(6, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); - expect(at(7, "Runner")).toMatchObject({ kind: "instantiate", to: { file: lib, name: "Runner", line: 5 } }); - expect(at(7, "run")).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6, scope: "member" } }); - expect(at(8, '"run"')).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6 } }); - expect(at(9, "main")).toMatchObject({ kind: "call", to: { file: lib, name: "main", line: 11 } }); + expect(at(7, "tick")).toMatchObject({ kind: "call", to: { file: lib, name: "tick", line: 1 } }); + expect(at(8, "Runner")).toMatchObject({ kind: "instantiate", to: { file: lib, name: "Runner", line: 5 } }); + expect(at(8, "run")).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6, scope: "member" } }); + expect(at(9, '"run"')).toMatchObject({ kind: "call", to: { file: lib, name: "run", line: 6 } }); + expect(at(10, "main")).toMatchObject({ kind: "call", to: { file: lib, name: "main", line: 11 } }); }); it("follows a declaration map over the conventional path", () => { diff --git a/server/app/services/symbols/checker.py b/server/app/services/symbols/checker.py index e3717512..5f2bd0d4 100644 --- a/server/app/services/symbols/checker.py +++ b/server/app/services/symbols/checker.py @@ -160,8 +160,9 @@ def join(result: SymbolRefsResult, symbols: Dict[str, Symbol]) -> CheckerRefs: out.positions[(f.file, r.line)].append((r.column, r.endColumn, target)) if r.clause: continue - # The enclosing declaration's symbol, else the innermost symbol holding the line. - source = (targets[r.source] if r.source is not None else None) or files.source(f.file, r.line) + # The enclosing declaration's symbol; module code when the checker names none; the + # innermost symbol holding the line only when the enclosing one has no symbol. + source = f.file if r.source is None else (targets[r.source] or files.source(f.file, r.line)) for target in bound: if source != target: out.references.append(Reference(source=source, target=target, kind=r.kind, line=r.line, column=r.column, end_column=r.endColumn)) diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 1dc14958..75cd555f 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -53,9 +53,10 @@ class SymbolIndex: mismatched: List[str] = field(default_factory=list) outside_program: int = 0 program_hash: Optional[str] = None - # Checker mode: each bound name's span by (file, line), and the TS files tree-sitter bound instead. + # Checker mode: each bound name's span by (file, line), and the files the checker bound + # (every other file, Python included, keeps tree-sitter's references and lookup). positions: Dict[Tuple[str, int], List[Tuple[int, int, str]]] = field(default_factory=dict) - unchecked_files: Set[str] = field(default_factory=set) + checked_files: Set[str] = field(default_factory=set) _by_line: Optional[Dict[Tuple[str, int], List[int]]] = None def __post_init__(self) -> None: @@ -357,7 +358,7 @@ def at(self, file: str, line: int, column: int, name: str) -> Tuple[Optional[str Never a search by name alone. """ here = [self.references[i] for i in self._refs_on_line().get((file, line), [])] - if self.binder == "checker" and file not in self.unchecked_files: + if file in self.checked_files: # Every bound name the checker saw, edges or not: an import's name, a recursive call. bound = sorted({target for start, end, target in self.positions.get((file, line), ()) if start <= column < end}) if len(bound) == 1: @@ -485,7 +486,7 @@ def assemble(root: Path, parts: List[FileSymbols], checker: Optional[CheckerResu index.mismatched = bound.mismatched index.program_hash = bound.program_hash index.positions = dict(bound.positions) - index.unchecked_files = {p.file for p in parts if Path(p.file).suffix in TS_EXTENSIONS} + index.checked_files = set(bound.files) index.outside_program = sum(1 for p in parts if Path(p.file).suffix in TS_EXTENSIONS) index.members_by_name = members_by_name index.http_links, index.http_unmatched = http_links, http_unmatched diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py index 1c73c3fc..dc9072a5 100644 --- a/server/tests/test_symbol_checker_join.py +++ b/server/tests/test_symbol_checker_join.py @@ -144,3 +144,28 @@ def test_one_line_shadowing_and_positions_without_edges(tmp_path: Path): # Show references still finds the function at its recursive call. assert idx.at("src/h.ts", 1, src.rindex("handler()") + 1, "handler") == ("src/h.ts#handler", []) assert idx.at("src/h.ts", 1, src.index("handler();") + 1, "handler") == (None, []) + + +def test_module_code_on_a_declaration_line_and_python_lookups_keep_their_binder(tmp_path: Path): + from app.services.symbols.python import extract_py + + src = "export function run() {}; run();" + (tmp_path / "src").mkdir() + (tmp_path / "src" / "r.ts").write_text(src, encoding="utf-8") + (tmp_path / "src" / "p.py").write_text("def go():\n return 1\n\n\ndef main():\n return go()\n", encoding="utf-8") + ts_parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "r.ts"]) + py_parts, _ = extract_py(tmp_path, [tmp_path / "src" / "p.py"]) + call = src.rindex("run") + 1 + result = SymbolRefsResult.model_validate( + { + "outcome": "ok", "generation": 1, "programHash": "h", "tsconfig": "", "typescript": "5", "nullProof": True, "reason": None, + "targets": [{"file": "src/r.ts", "name": "run", "line": 1, "column": 17, "meaning": "value", "scope": "module"}], + "files": [{"file": "src/r.ts", "refs": [{"line": 1, "column": call, "endColumn": call + 3, "kind": "call", "source": None, "target": 0, "unbound": None}]}], + "counts": {"files": 1, "bound": 1, "unbound": 0, "external": 0}, + } + ) + idx = assemble(tmp_path, ts_parts + py_parts, result) + # No enclosing declaration is module code, even on the declaration's own line. + assert ("src/r.ts", "src/r.ts#run") in {(r.source, r.target) for r in idx.references} + # A Python file keeps tree-sitter's lookup in a checker index. + assert idx.at("src/p.py", 6, 12, "go") == ("src/p.py#go", []) From a0e4c6dc69f5f0c6a96c81ad29447ae351af42ff Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 01:04:54 -0500 Subject: [PATCH 12/13] test(symbols): use the shadowing test's targets Co-Authored-By: Claude Opus 5.5 --- server/tests/test_symbol_checker_join.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/tests/test_symbol_checker_join.py b/server/tests/test_symbol_checker_join.py index dc9072a5..e5ad00ae 100644 --- a/server/tests/test_symbol_checker_join.py +++ b/server/tests/test_symbol_checker_join.py @@ -112,7 +112,7 @@ def test_a_name_joins_only_the_declaration_on_its_own_line(tmp_path: Path): parts, _ = extract_ts(tmp_path, [tmp_path / "src" / "h.ts"]) targets = [("src/h.ts", "wrapper", 2, "value", "local"), ("src/h.ts", "handler", 2, "value", "local")] # `handler()` on line 2 calls the parameter, declared on line 2: not the function on line 1. - idx = assemble(tmp_path, parts, _result([("src/h.ts", "wrapper", 2, "value", "local"), ("src/h.ts", "handler", 2, "value", "local")], [(2, 43, 50, "call", 0, 1, None)], file="src/h.ts", text=src)) + idx = assemble(tmp_path, parts, _result(targets, [(2, 43, 50, "call", 0, 1, None)], file="src/h.ts", text=src)) assert [r for r in idx.references if r.target == "src/h.ts#handler"] == [] # The DOM method inside the one-line wrapper is not the wrapper; its own name is. assert idx.at("src/h.ts", 5, 50, "getSelection") == (None, []) From d07f3c3bc0a168a1b6d969daef8787e8d880fd95 Mon Sep 17 00:00:00 2001 From: Byron Wall Date: Sat, 28 Nov 2026 01:09:43 -0500 Subject: [PATCH 13/13] fix(symbols): refresh the engine on any source change; honour a declaration map's sourceRoot Co-Authored-By: Claude Opus 5.5 --- engine/src/srcly/ops/symbol-refs.ts | 5 +++-- server/app/services/symbols/index.py | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/engine/src/srcly/ops/symbol-refs.ts b/engine/src/srcly/ops/symbol-refs.ts index 52dffcf3..78a496d8 100644 --- a/engine/src/srcly/ops/symbol-refs.ts +++ b/engine/src/srcly/ops/symbol-refs.ts @@ -168,8 +168,9 @@ function builtSources(tier1: TsTier1, root: string) { const map = `${file.fileName}.map`; if (fs.existsSync(map)) { try { - const sources = (JSON.parse(fs.readFileSync(map, "utf8")) as { sources?: unknown; sourceRoot?: unknown }).sources; - const first = Array.isArray(sources) && typeof sources[0] === "string" ? path.resolve(path.dirname(map), sources[0]) : undefined; + const parsed = JSON.parse(fs.readFileSync(map, "utf8")) as { sources?: unknown; sourceRoot?: unknown }; + const base = typeof parsed.sourceRoot === "string" ? path.resolve(path.dirname(map), parsed.sourceRoot) : path.dirname(map); + const first = Array.isArray(parsed.sources) && typeof parsed.sources[0] === "string" ? path.resolve(base, parsed.sources[0]) : undefined; const hit = first ? program.getSourceFile(first.split(path.sep).join("/")) : undefined; return hit && !hit.isDeclarationFile ? hit : undefined; } catch { diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 75cd555f..ec8ad1c5 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -685,8 +685,10 @@ def build_symbol_index(root: Path, use_cache: bool = True, binder: str = "tree-s hit = _cache.get((root, binder)) if hit is not None and hit[0] == sig and _still_current(root, hit[1], registry): return hit[1] - # A config the engine's own hash may not cover changed: rebuild its Program. - refresh = hit is not None and hit[0][1] != configs + # A source or config changed since the cached index: rebuild the engine's Program too. + # Its own hash covers only the files it holds, so a new file that changes where an + # import resolves, or an extended config, would not mark it stale. + refresh = hit is not None and hit[0] != sig parts: List[FileSymbols] = [] ts_files = [f for f in files if f.suffix in TS_EXTENSIONS] if ts_files: