Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions client/e2e/symbols.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
}
});
27 changes: 13 additions & 14 deletions client/src/components/CodeModal/CodeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import { DialogShell } from "../dialog/DialogShell";
import { MarkdownPane } from "./MarkdownPane";
import { MetricsSidebar } from "./MetricsSidebar";
import { InspectMenu } from "./InspectMenu";
import { searchSymbols } from "../../symbols/api";
import { identifierAt } from "../../symbols/identifier";
import { fetchSymbolAt } from "../../symbols/api";
import { identifierRangeAt } from "../../symbols/identifier";
import { refsPatch, traceAnchorPatch } from "../../navigation/nodeActions";
import { ValueFlowLedger } from "./ValueFlowLedger";
import { createEffectsQuery, EffectsPanel } from "../../dataflow/EffectsPanel";
Expand Down Expand Up @@ -213,20 +213,19 @@ 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 }));
});
// 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({ symbol: res.id }));
return null;
},
});
/** The ledger's rows are marked through the metric overlay while this is on. */
Expand Down
39 changes: 39 additions & 0 deletions client/src/dataflow/contract.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -724,3 +724,42 @@ 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;
column: 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";
source: number | null;
target: number | null;
also?: number[];
clause?: true;
unbound: "unresolved" | "any" | null;
}[];
}[];
counts: {
files: number;
bound: number;
unbound: number;
external: number;
};
};
11 changes: 8 additions & 3 deletions client/src/investigation/valueFlowInspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>;
}) {
const [menu, setMenu] = createSignal<MenuState | null>(null);
const [picker, setPicker] = createSignal<PickerState | null>(null);
Expand All @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions client/src/navigation/nodeActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof nodeActions>[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");
Expand Down
7 changes: 4 additions & 3 deletions client/src/navigation/nodeActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Location> {
export function refsPatch(target: { at: string } | { symbol: string }): Partial<Location> {
return {
view: "graph",
flow: undefined,
Expand All @@ -74,7 +75,7 @@ export function refsPatch(target: { at: string }): Partial<Location> {
dest: undefined,
lens: undefined,
open: undefined,
symbols: symbolIdOf(target.at) ?? "",
symbols: "symbol" in target ? target.symbol : (symbolIdOf(target.at) ?? ""),
to: undefined,
};
}
Expand Down
7 changes: 6 additions & 1 deletion client/src/symbols/api.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -39,6 +39,11 @@ export function fetchSymbolStats(req: { path: string; limit?: number; hubs?: num
return get<SymbolStats>("/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<SymbolAt> {
return get<SymbolAt>("/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<SymbolSearch> {
return get<SymbolSearch>("/api/symbols/search", { path: req.path, q: req.q, limit: req.limit, tests: req.tests });
}
14 changes: 14 additions & 0 deletions client/src/symbols/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number>;
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 {
Expand Down
7 changes: 6 additions & 1 deletion client/src/symbols/identifier.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
}
2 changes: 2 additions & 0 deletions client/src/viz/deps/symbols/SymbolsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(" · ");
};
Expand Down
7 changes: 5 additions & 2 deletions docs/CODE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
Loading
Loading