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
2 changes: 1 addition & 1 deletion client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ function AppContent(props: { active: boolean }) {
if (node && scopes.length === 1 && typeof line === "number") {
const fileNode = node.type === "file" ? node : findTreeNodeByPath(data, treePathFromAt(symbolFile, rootPath()));
const byLine = findScopeForSymbol(fileNode, scopes[0], line);
if (byLine && (node.type === "file" || normalizeScopeName(String(byLine.name ?? "")) === scopes[0])) {
if (byLine && (node.type === "file" || normalizeScopeName(String(byLine.name ?? "")) === normalizeScopeName(scopes[0]))) {
node = byLine;
} else if (node.type === "file") {
const path = extractFilePath(node.path, node.type);
Expand Down
3 changes: 2 additions & 1 deletion client/src/components/CodeModal/CodeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ export default function CodeModal(props: CodeModalProps) {
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);
const hit = exact.find((h) => h.file === at) ?? exact[0] ?? res.hits[0];
// 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 }));
Expand Down
2 changes: 2 additions & 0 deletions client/src/navigation/location.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,8 @@ describe("Symbols mode (`symbols`)", () => {
expect(symbolIdOf("src/store.ts#Store")).toBe("src/store.ts#Store");
expect(symbolIdOf("a.py#Foo (class)::run")).toBe("a.py#Foo.run");
expect(symbolIdOf("src/a.tsx#<Panel>")).toBeNull();
expect(symbolIdOf("src/a.ts#A@type")).toBe("src/a.ts#A@type");
expect(normalizeScopeName("A@type")).toBe("A");
expect(symbolIdOf("")).toBeNull();
expect(symbolIdOf("ext:react")).toBeNull();
});
Expand Down
10 changes: 8 additions & 2 deletions client/src/navigation/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,9 @@ export function symbolIdOf(at: string): string | null {
if (!scopes.length) return file;
const names = scopes.map((s) => normalizeScopeName(s));
if (names.some((n) => !/^[A-Za-z_$#][\w$#]*$/.test(n))) return null;
return `${file}#${names.join(".")}`;
// A type that shares its name with a value keeps its own id (`src/a.ts#A@type`).
const suffix = scopes[scopes.length - 1].endsWith(TYPE_ID_SUFFIX) ? TYPE_ID_SUFFIX : "";
return `${file}#${names.join(".")}${suffix}`;
}

/** Data flow mode: a route, or an anchor. */
Expand Down Expand Up @@ -352,9 +354,13 @@ export function treePathFromAt(at: string, root: string): string {
* "(class) Foo", "run (async)"); graph symbols are bare. Compare them bare.
*/
export function normalizeScopeName(name: string): string {
return name.replace(/\([^)]*\)/g, "").trim();
const bare = name.replace(/\([^)]*\)/g, "").trim();
return bare.endsWith(TYPE_ID_SUFFIX) ? bare.slice(0, -TYPE_ID_SUFFIX.length) : bare;
}

/** The symbol index's id suffix for a type-only declaration named like a value of its file. */
export const TYPE_ID_SUFFIX = "@type";

/** Last path segment ("/a/b/" → "b"). */
export function baseName(path: string): string {
const parts = path.split(/[\\/]/).filter(Boolean);
Expand Down
2 changes: 2 additions & 0 deletions client/src/symbols/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ export function baseName(file: string): string {
/**
* The code-viewer location for a symbol: its file, and its top-level
* declaration's name (a member opens through its class; the line lands it).
* A type that shares its name with a value keeps its suffix (`src/a.ts#A@type`), so
* "Show references" stays on the type; the code viewer drops it to find the name.
*/
export function atOf(id: string): string {
const qualified = qualifiedOf(id);
Expand Down
69 changes: 66 additions & 3 deletions server/app/services/deps/typescript_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
from typing import Dict, Iterator, List, Optional, Set, Tuple

import tree_sitter_typescript as tstypescript
from tree_sitter import Language, Node, Parser
Expand Down Expand Up @@ -62,6 +62,10 @@ class TsFileInfo:
reexports: Dict[str, Tuple[str, str]] = field(default_factory=dict)
# `export * from "x"`
star_reexports: List[str] = field(default_factory=list)
# local name → (source spec, imported name) of each static import binding ("*" for a namespace)
import_locals: Dict[str, Tuple[str, str]] = field(default_factory=dict)
# local names `export { a }` or `export default a` exports, in every namespace they have
clause_exports: Set[str] = field(default_factory=set)
declarations: List[SymbolDef] = field(default_factory=list)
# Top-level declaration nodes, kept for symbol-usage analysis.
decl_nodes: Dict[str, Node] = field(default_factory=dict)
Expand Down Expand Up @@ -131,17 +135,20 @@ def _parse_import(stmt: Node, info: TsFileInfo, line: int) -> None:
for c in clause.children:
if c.type == "identifier":
imp.names.append(ImportedName("default", _text(c), type_only))
info.import_locals[_text(c)] = (spec, "default")
elif c.type == "namespace_import":
ident = next((x for x in c.children if x.type == "identifier"), None)
imp.kind = "namespace"
imp.names.append(ImportedName("*", _text(ident), type_only))
info.import_locals[_text(ident)] = (spec, "*")
elif c.type == "named_imports":
for s in c.children:
if s.type != "import_specifier":
continue
name = _text(s.child_by_field_name("name"))
alias = _text(s.child_by_field_name("alias")) or name
imp.names.append(ImportedName(name, alias, type_only or _has_type_keyword(s)))
info.import_locals[alias] = (spec, name)
info.imports.append(imp)


Expand Down Expand Up @@ -177,6 +184,7 @@ def _parse_export(stmt: Node, info: TsFileInfo, line: int) -> None:
name = _text(s.child_by_field_name("name"))
alias = _text(s.child_by_field_name("alias")) or name
info.local_exports[alias] = name
info.clause_exports.add(name)
return

is_default = any(c.type == "default" for c in stmt.children)
Expand All @@ -191,6 +199,8 @@ def _parse_export(stmt: Node, info: TsFileInfo, line: int) -> None:
value = stmt.child_by_field_name("value")
local = _text(value) if value is not None and value.type == "identifier" else "default"
info.local_exports["default"] = local
if local != "default":
info.clause_exports.add(local)
if local == "default":
info.declarations.append(SymbolDef("default", "value", line, exported=True))

Expand All @@ -209,7 +219,13 @@ def _record_declaration(node: Node, info: TsFileInfo, exported: bool) -> List[st
if d.type != "variable_declarator":
continue
name_node = d.child_by_field_name("name")
if name_node is None or name_node.type != "identifier":
if name_node is None:
continue
if name_node.type != "identifier":
# `const { a, b } = x`: each bound name is a top-level variable.
for name in pattern_names(name_node):
names.append(name)
info.declarations.append(SymbolDef(name, "variable", d.start_point[0] + 1, exported))
continue
value = d.child_by_field_name("value")
kind = "function" if value is not None and value.type in ("arrow_function", "function_expression", "function") else "variable"
Expand All @@ -220,6 +236,26 @@ def _record_declaration(node: Node, info: TsFileInfo, exported: bool) -> List[st
return names


def pattern_names(pattern: Node) -> Iterator[str]:
"""Every bound identifier in a destructuring pattern."""
stack = [pattern]
while stack:
node = stack.pop()
t = node.type
if t in ("identifier", "shorthand_property_identifier_pattern"):
yield _text(node)
elif t == "pair_pattern":
v = node.child_by_field_name("value")
if v is not None:
stack.append(v)
elif t in ("object_assignment_pattern", "assignment_pattern"):
left = node.child_by_field_name("left")
if left is not None:
stack.append(left)
elif t in ("object_pattern", "array_pattern", "rest_pattern"):
stack.extend(node.named_children)


class TsModuleResolver:
"""Resolve module specifiers to files inside the analysed root."""

Expand Down Expand Up @@ -318,6 +354,14 @@ def _is_external_spec(spec: str) -> bool:
return not (spec.startswith(".") or spec.startswith("/"))


def _type_split(decls: List[SymbolDef]) -> Set[str]:
kinds: Dict[str, Set[str]] = {}
for d in decls:
kinds.setdefault(d.name, set()).add(d.kind)
# A class or an enum is a type and a value at once: an interface of its name merges into it.
return {n for n, k in kinds.items() if "type" in k and k & {"variable", "function", "value"} and not k & {"class", "enum"}}


class TsProgram:
"""Every TS/JS file of a root parsed once, with module resolution and re-export passing."""

Expand All @@ -333,6 +377,18 @@ def __init__(self, root: Path, files: List[Path]):
self.resolver = TsModuleResolver(root, self.files)
self._resolved: Dict[Tuple[Path, str], Optional[Path]] = {}
self.declared: Dict[Path, Set[str]] = {f: {d.name for d in i.declarations} for f, i in self.infos.items()}
# Names a file declares twice, once as a type only (interface, type alias) and once as a value only
# (variable, function): `export const A = B; export type A = B`. They are two symbols; see type_split.
self.type_split: Dict[Path, Set[str]] = {f: _type_split(i.declarations) for f, i in self.infos.items()}

def exported_as(self, file: Path, name: str, type_ns: bool) -> bool:
"""Whether a split name (see type_split) is public in the type or the value namespace."""
info = self.infos.get(file)
if info is None:
return False
if name in info.clause_exports:
return True
return any(d.name == name and d.exported and (d.kind == "type") == type_ns for d in info.declarations)

def resolve(self, spec: str, from_file: Path) -> Optional[Path]:
key = (from_file.parent, spec) if not spec.startswith(".") else (from_file, spec)
Expand All @@ -350,7 +406,14 @@ def find_definer(self, file: Path, name: str, depth: int = 0, seen: Optional[Set
if info is None:
return file, name
if name in info.local_exports:
return file, info.local_exports[name]
local = info.local_exports[name]
# `import { A } from "./a"; export { A }`: the export names an import, so A lives in ./a.
src = info.import_locals.get(local)
if src is not None and local not in self.declared.get(file, set()) and src[1] != "*":
target = self.resolve(src[0], file)
if target is not None and target != file:
return self.find_definer(target, src[1], depth + 1, seen)
return file, local
if name in info.reexports:
spec, imported = info.reexports[name]
target = self.resolve(spec, file)
Expand Down
12 changes: 10 additions & 2 deletions server/app/services/symbols/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import threading
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set, Tuple

Expand Down Expand Up @@ -508,10 +508,18 @@ def _member_of(cls: Symbol, name: str, symbols: Dict[str, Symbol], skip_self: bo

def _settle(p: PendingMember, symbols: Dict[str, Symbol], members_by_name: Dict[str, List[str]]) -> Optional[Reference]:
receiver = symbols.get(p.receiver) if p.receiver else None
split = receiver is not None and receiver.kind == "type" and receiver.id.endswith("@type")
if split and receiver.typed_as in symbols and p.kind != "type":
# `x: A` where the split `type A = B` or `type A = InstanceType<typeof A>`: the members are B's, or the value A's.
return _settle(replace(p, receiver=receiver.typed_as, receiver_note="typed"), symbols, members_by_name)
if receiver is not None:
resolution = "typed" if p.receiver_note == "typed" else "exact"
if receiver.kind == "module":
hit = symbols.get(f"{receiver.id}#{p.member}")
# `ns.A` in a type names the type A of a file that also has a value A (`file#A@type`);
# a class's `extends ns.A` is code, so it names the value.
hit = (symbols.get(f"{receiver.id}#{p.member}@type") if p.kind == "type" else None) or symbols.get(
f"{receiver.id}#{p.member}"
)
if hit is not None:
return Reference(p.source, hit.id, p.kind, p.line, resolution)
return None
Expand Down
5 changes: 4 additions & 1 deletion server/app/services/symbols/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
Ids are ``<file>#<qualified>``: ``src/store.ts#Store`` for a top-level
declaration (the same id the dependency graph gives it), ``src/store.ts#Store.bump``
for a member or a nested function. A file's module-level code is the node
``<file>`` of kind ``module``.
``<file>`` of kind ``module``. TypeScript keeps types and values apart: when a
file declares a type-only ``A`` (interface, type alias) and a value-only ``A``
(variable, function), the value is ``src/a.ts#A`` and the type is
``src/a.ts#A@type``, and each reference names the one its position uses.

Every reference says how it was resolved, because a name-based extractor
cannot always be sure:
Expand Down
Loading
Loading