diff --git a/client/src/App.tsx b/client/src/App.tsx index 58776613..33492441 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -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); diff --git a/client/src/components/CodeModal/CodeModal.tsx b/client/src/components/CodeModal/CodeModal.tsx index 0efdc504..1d858e59 100644 --- a/client/src/components/CodeModal/CodeModal.tsx +++ b/client/src/components/CodeModal/CodeModal.tsx @@ -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 })); diff --git a/client/src/navigation/location.test.ts b/client/src/navigation/location.test.ts index 64afa74c..0d191e26 100644 --- a/client/src/navigation/location.test.ts +++ b/client/src/navigation/location.test.ts @@ -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#")).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(); }); diff --git a/client/src/navigation/location.ts b/client/src/navigation/location.ts index 6fd8b193..b7b8f0a1 100644 --- a/client/src/navigation/location.ts +++ b/client/src/navigation/location.ts @@ -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. */ @@ -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); diff --git a/client/src/symbols/contract.ts b/client/src/symbols/contract.ts index 342072fb..83e06c23 100644 --- a/client/src/symbols/contract.ts +++ b/client/src/symbols/contract.ts @@ -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); diff --git a/server/app/services/deps/typescript_deps.py b/server/app/services/deps/typescript_deps.py index e7f72401..59596d1a 100644 --- a/server/app/services/deps/typescript_deps.py +++ b/server/app/services/deps/typescript_deps.py @@ -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 @@ -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) @@ -131,10 +135,12 @@ 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": @@ -142,6 +148,7 @@ def _parse_import(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 imp.names.append(ImportedName(name, alias, type_only or _has_type_keyword(s))) + info.import_locals[alias] = (spec, name) info.imports.append(imp) @@ -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) @@ -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)) @@ -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" @@ -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.""" @@ -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.""" @@ -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) @@ -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) diff --git a/server/app/services/symbols/index.py b/server/app/services/symbols/index.py index 895b9071..13c9db13 100644 --- a/server/app/services/symbols/index.py +++ b/server/app/services/symbols/index.py @@ -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 @@ -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`: 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 diff --git a/server/app/services/symbols/model.py b/server/app/services/symbols/model.py index 9fdaccca..e46a2d07 100644 --- a/server/app/services/symbols/model.py +++ b/server/app/services/symbols/model.py @@ -10,7 +10,10 @@ Ids are ``#``: ``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 -```` of kind ``module``. +```` 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: diff --git a/server/app/services/symbols/typescript.py b/server/app/services/symbols/typescript.py index 7a1d709c..3294feae 100644 --- a/server/app/services/symbols/typescript.py +++ b/server/app/services/symbols/typescript.py @@ -22,20 +22,25 @@ from tree_sitter import Node from app.services.deps.common import ImportBinding -from app.services.deps.typescript_deps import TsFileInfo, TsProgram, _text +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 _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"} _NAMED_CLASS_MEMBERS = {"method_definition", "abstract_method_signature", "method_signature", "public_field_definition", "property_signature"} +# The id suffix of a type-only declaration that shares its name with a value-only one in the same file +# (`export const A = B; export type A = B`). The value keeps `file#A`; the type is `file#A@type`. +TYPE_ID_SUFFIX = "@type" +# The members of the promise `import("./m")` is in code; any other `import("./m").X` is the type X. +_PROMISE_MEMBERS = {"then", "catch", "finally"} @dataclass class _Scope: symbol: Optional[str] class_id: Optional[str] - # local name → the type name it was declared with (`x: Store`, `new Store()`), or None + # local name → the type name it was declared with (`x: Store`, or `new Store` for `new Store()`), or None locals: Dict[str, Optional[str]] = field(default_factory=dict) # nested symbols declared directly in this scope, by name named: Dict[str, str] = field(default_factory=dict) @@ -52,6 +57,8 @@ def __init__(self, program: TsProgram, path: Path, rel: str, info: TsFileInfo, r self.bindings: Dict[str, ImportBinding] = program.bindings_for(path) self.exported = set(info.local_exports.values()) self.top: Dict[str, str] = {} # top-level declaration name → id + self.top_types: Dict[str, str] = {} # the split type-only declarations (TYPE_ID_SUFFIX), by name + self.split = program.type_split.get(path, set()) self.by_id: Dict[str, Symbol] = {} self.scopes: List[_Scope] = [_Scope(symbol=rel, class_id=None)] @@ -69,11 +76,22 @@ def _push(self, symbol: Optional[str], class_id: Optional[str] = None) -> _Scope def _pop(self) -> None: self.scopes.pop() - def _binding_id(self, b: ImportBinding) -> Optional[str]: - target = self.rel_of.get(b.target_file) + def _export_id(self, file: Path, name: Optional[str], type_ns: bool) -> Optional[str]: + """The id of the top-level `name` of `file` (the module when None), in the type or the value namespace.""" + target = self.rel_of.get(file) if target is None: return None - return target if b.target_symbol is None or b.namespace else f"{target}#{b.target_symbol}" + if name is None: + return target + if name in self.program.type_split.get(file, set()): + # One side of a split name can be private: `export default function A` beside a `type A`. + if not self.program.exported_as(file, name, type_ns): + return None + return f"{target}#{name}{TYPE_ID_SUFFIX if type_ns else ''}" + return f"{target}#{name}" + + def _binding_id(self, b: ImportBinding, type_ns: bool = False) -> Optional[str]: + return self._export_id(b.target_file, None if b.namespace else b.target_symbol, type_ns) def resolve_name(self, name: str) -> Tuple[Optional[str], Optional[str]]: """(symbol id, declared type name) for a bare name: the id when it names a symbol, the type when it is a typed local.""" @@ -90,13 +108,29 @@ def resolve_name(self, name: str) -> Tuple[Optional[str], Optional[str]]: return None, None def resolve_type_name(self, name: str) -> Optional[str]: - sid, _ = self.resolve_name(name) - return sid + """The symbol a name in a type position names: a local variable never does, a split type does first.""" + for s in reversed(self.scopes): + if name in s.named and self.by_id[s.named[name]].kind not in ("function", "variable"): + return s.named[name] + if name in self.top_types: + return self.top_types[name] + if name in self.top: + return self.top[name] + b = self.bindings.get(name) + if b is not None: + return self._binding_id(b, type_ns=True) + return None + + def resolve_declared(self, declared: str) -> Optional[str]: + """The class a `_declared_type` names: `new A` is the value A (the constructor), `A` the type A.""" + if declared.startswith(_NEW): + return self.resolve_name(declared[len(_NEW) :])[0] + return self.resolve_type_name(declared) # ---- symbols ---- - def _add(self, name: str, kind: SymbolKind, node: Node, container: Optional[str], exported: bool) -> Symbol: - sid = f"{self.rel}#{name}" if container is None or container == self.rel else f"{container}.{name}" + 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) if existing is not None: existing.end_line = max(existing.end_line, node.end_point[0] + 1) @@ -121,8 +155,15 @@ 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 container = None if at_top else self.scope.symbol - sym = self._add(name, kind, node, container, exported=(name in self.exported) if at_top else self._container_exported()) - if at_top: + split = at_top and kind == "type" and name in self.split + if at_top and name in self.split and kind in ("type", "variable", "function"): + exported = self.program.exported_as(self.path, name, kind == "type") + else: + exported = (name in self.exported) if at_top else self._container_exported() + sym = self._add(name, kind, node, container, exported, TYPE_ID_SUFFIX if split else "") + if split: + self.top_types[name] = sym.id + elif at_top: self.top[name] = sym.id else: self.scope.named[name] = sym.id @@ -165,7 +206,7 @@ def _receiver(self, obj: Node) -> Tuple[Optional[str], str]: if sid is not None: return sid, "" if type_name: - return self.resolve_type_name(type_name), "typed" + return self.resolve_declared(type_name), "typed" return None, "local" return None, "expression" @@ -175,6 +216,11 @@ def _on_member(self, node: Node, kind: RefKind) -> None: prop = node.child_by_field_name("property") if obj is None: return + if obj.type == "call_expression" and _import_spec(obj) is not None and _text(prop) not in _PROMISE_MEMBERS: + # `import("./m").Row`: the export Row of ./m, as a static `import type` would bind it. Only a type + # can say this (tree-sitter often parses it as code or an error), and `typeof` makes it the value. + self._ref(self._inline_import(obj, _text(prop), not _in_typeof(node)), "type", node) + return if obj.type in ("identifier", "this", "super"): receiver, note = self._receiver(obj) if receiver is not None and note == "typed": @@ -193,6 +239,18 @@ def _on_member(self, node: Node, kind: RefKind) -> None: self.visit(obj) self._member(None, _text(prop), kind, node, "expression") + def _inline_import(self, call: Node, name: str, type_ns: bool) -> Optional[str]: + spec = _import_spec(call) + target = self.program.resolve(spec, self.path) if spec else None + if target is None or not name: + return None + d_file, d_name = self.program.find_definer(target, name) + exports = self.program.infos[d_file].local_exports if d_file in self.program.infos else {} + # Only a public name: `import("./m").A` of a file whose A is private (or only its default) names nothing. + if (name not in exports) if d_file == target else (d_name not in exports.values()): + return None + return self._export_id(d_file, d_name, type_ns) + # ---- the walk ---- def run(self) -> FileSymbols: @@ -318,7 +376,8 @@ def visit(self, n: Node) -> None: self.visit(inner) return if t == "type_identifier": - self._ref(self.resolve_type_name(_text(n)), self._type_ref_kind(n), n) + if not _type_parameter_bound(n): + self._ref(self.resolve_type_name(_text(n)), self._type_ref_kind(n), n) return if t in ("identifier", "shorthand_property_identifier"): self._ref(self.resolve_name(_text(n))[0], "read", n) @@ -327,7 +386,7 @@ def visit(self, n: Node) -> None: param = n.child_by_field_name("parameter") self._push(None) if param is not None: - for name in _pattern_names(param): + for name in pattern_names(param): self.scope.locals[name] = None body = n.child_by_field_name("body") if body is not None: @@ -411,7 +470,7 @@ def _bind_parameters(self, fn: Node, scope: _Scope) -> None: elif pattern.type == "this": continue else: - for name in _pattern_names(pattern): + for name in pattern_names(pattern): scope.locals[name] = None def _visit_parameter_types(self, params: Node) -> None: @@ -458,7 +517,7 @@ def _collect_locals(self, body: Optional[Node], scope: _Scope) -> None: if value is None or value.type not in _FUNCTION_LIKE: scope.locals.setdefault(_text(name_node), _declared_type(node)) else: - for name in _pattern_names(name_node): + for name in pattern_names(name_node): scope.locals.setdefault(name, None) elif t == "function_declaration": continue @@ -483,11 +542,11 @@ def _visit_variables(self, n: Node) -> None: if not is_fn: type_name = _declared_type(d) if type_name: - sym.typed_as = self.resolve_type_name(type_name) + sym.typed_as = self.resolve_declared(type_name) else: self.scope.locals[name] = _declared_type(d) else: - for name in _pattern_names(name_node): + for name in pattern_names(name_node): if not at_top: self.scope.locals[name] = None else: @@ -636,12 +695,28 @@ def _visit_method(self, m: Node, owner: str, class_id: Optional[str]) -> None: def _visit_type_decl(self, n: Node) -> None: name_node = n.child_by_field_name("name") sym = self._declare(_text(name_node), _TYPE_DECLS[n.type], n) + if n.type == "type_alias_declaration": + sym.typed_as = self._instance_of(n.child_by_field_name("value")) self._push(sym.id) for c in n.named_children: if not _same(c, name_node): self.visit(c) self._pop() + def _instance_of(self, value: Optional[Node]) -> Optional[str]: + """The class an alias's instances are: `type A = B` is B, `type A = InstanceType` the value A.""" + if value is None: + return None + if value.type == "type_identifier": + return self.resolve_type_name(_text(value)) + if value.type == "generic_type" and _text(value.child_by_field_name("name")) == "InstanceType": + args = next((c for c in value.named_children if c.type == "type_arguments"), None) + query = next((c for c in args.named_children), None) if args is not None else None + target = next((c for c in query.named_children), None) if query is not None and query.type == "type_query" else None + if target is not None and target.type == "identifier": + return self.resolve_name(_text(target))[0] + return None + def _note_request(self, n: Node, kind: RefKind) -> None: """`fetch("/api/x", {method})`, `x.fetch(...)`, `new URL("/api/x", base)`, `api.post("/x")`: a same-origin request.""" fn = n.child_by_field_name("function") if kind == "call" else n.child_by_field_name("constructor") @@ -699,6 +774,42 @@ def _visit_write(self, left: Node) -> None: self.visit(left) +def _import_spec(call: Node) -> Optional[str]: + """The module of `import("./m")`; None for any other call.""" + fn = call.child_by_field_name("function") + args = call.child_by_field_name("arguments") + if fn is None or fn.type != "import" or args is None: + return None + return _string_value(next((a for a in args.named_children), None)) + + +def _in_typeof(n: Node) -> bool: + p = n.parent + while p is not None and p.type not in ("program", "statement_block", "type_annotation", "type_arguments"): + if p.type == "type_query": + return True + p = p.parent + return False + + +def _type_parameter_bound(n: Node) -> bool: + """A type name that a generic parameter (``) declares or binds: not a reference to an outer type.""" + name = _text(n) + if n.parent is not None and n.parent.type == "type_parameter" and _same(n.parent.child_by_field_name("name"), n): + return True + p = n.parent + while p is not None: + params = p.child_by_field_name("type_parameters") + if params is not None and any(_text(tp.child_by_field_name("name")) == name for tp in params.named_children): + return True + if p.type == "statement_block" and any( + c.type in _TYPE_DECLS and _text(c.child_by_field_name("name")) == name for c in p.named_children + ): + return False # a nearer `type A` in this block binds the name before any outer generic + p = p.parent + return False + + 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 @@ -739,26 +850,6 @@ def _literal_method(options: Optional[Node]) -> Optional[str]: return None -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) - - def _annotation_name(type_node: Optional[Node]) -> Optional[str]: """`: Store` → "Store"; anything else (unions, generics, object types) is not an instance type.""" if type_node is None: @@ -769,6 +860,9 @@ def _annotation_name(type_node: Optional[Node]) -> Optional[str]: return None +_NEW = "new " # a `_declared_type` from a `new` initializer: the constructor, a value + + def _declared_type(declarator: Node) -> Optional[str]: """A variable's class, from `x: Store` or `x = new Store()`.""" name = _annotation_name(declarator.child_by_field_name("type")) @@ -778,7 +872,7 @@ def _declared_type(declarator: Node) -> Optional[str]: if value is not None and value.type == "new_expression": ctor = value.child_by_field_name("constructor") if ctor is not None and ctor.type == "identifier": - return _text(ctor) + return _NEW + _text(ctor) return None diff --git a/server/tests/test_symbol_index_ts.py b/server/tests/test_symbol_index_ts.py index c229340d..bd8f0f80 100644 --- a/server/tests/test_symbol_index_ts.py +++ b/server/tests/test_symbol_index_ts.py @@ -203,3 +203,101 @@ def test_refs_flags_and_stats(tmp_path: Path): assert stats.hubs[0].id == "s.ts#hub" and stats.hubs[0].in_count == 3 assert "s.ts#big" not in {h.id for h in stats.hubs} assert stats.unreferenced[0].lines == 1 and stats.unreferenced[0].exported is False + + +def test_inline_type_import_names_the_export(tmp_path: Path): + write(tmp_path, "src/types.ts", "export type Row = { id: string };\nexport const LIMIT = 3;\n") + write(tmp_path, "src/index.ts", 'export * from "./types";\n') + write(tmp_path, "src/private.ts", "export default function Secret() {}\ntype Secret = number;\nfunction Hidden() {}\n") + write( + tmp_path, + "src/worker.ts", + "\n".join( + [ + 'const tables: Record = {};', + 'export function first(r: import("./index").Row): typeof import("./types").LIMIT { return 3; }', + 'export const later = import("./types").then((m) => m.LIMIT);', + 'export const cast = {} as import("./types").Row;', + 'export const checked = { id: "a" } satisfies import("./types").Row;', + 'export const hidden: import("./private").Secret = 1;', + 'export function pick() { return pick(); }', + 'export type Keys = keyof import("./types").Row;', + ] + ), + ) + r = refs(build_symbol_index(tmp_path, use_cache=False)) + assert ("src/worker.ts#tables", "type", "src/types.ts#Row", "exact") in r + assert ("src/worker.ts#first", "type", "src/types.ts#Row", "exact") in r # through the barrel + assert ("src/worker.ts#first", "type", "src/types.ts#LIMIT", "exact") in r # `typeof` names the value + assert ("src/worker.ts#cast", "type", "src/types.ts#Row", "exact") in r # `x as T`, `x satisfies T` + assert ("src/worker.ts#checked", "type", "src/types.ts#Row", "exact") in r + assert ("src/worker.ts#pick", "type", "src/types.ts#Row", "exact") in r # a call's type argument + # tree-sitter cannot parse `keyof import(…)` as an alias, so the module is the source; the caller still shows. + assert ("src/worker.ts", "type", "src/types.ts#Row", "exact") in r + assert not any(s == "src/worker.ts#hidden" and t.startswith("src/private.ts#") for s, _k, t, _r in r) # not a public name + # A dynamic import in code is a promise, not a reference to the module's exports. + assert not any(s == "src/worker.ts#later" and t.startswith("src/types.ts#") for s, _k, t, _r in r) + + +def test_import_then_reexport_follows_to_the_definer(tmp_path: Path): + write(tmp_path, "src/types.ts", "export interface Saved { id: string }\nexport default function make() {}\n") + write(tmp_path, "src/Widget.tsx", 'import { type Saved } from "./types";\nimport make from "./types";\nexport type { Saved };\nexport { make as build };\n') + write(tmp_path, "src/App.tsx", 'import { type Saved, build } from "./Widget";\nexport function App(s: Saved) { return build(); }\n') + # A destructured local of the re-exported name is the module's own value: it wins over the import. + write(tmp_path, "src/Both.ts", 'import { type Saved } from "./types";\nconst { Saved } = { Saved: 1 };\nexport { Saved };\n') + write(tmp_path, "src/use.ts", 'import { Saved } from "./Both";\nexport const v = Saved;\n') + r = refs(build_symbol_index(tmp_path, use_cache=False)) + assert ("src/use.ts#v", "read", "src/Both.ts#Saved", "exact") in r + assert ("src/App.tsx#App", "type", "src/types.ts#Saved", "exact") in r + assert ("src/App.tsx#App", "call", "src/types.ts#make", "exact") in r + + +def test_type_and_value_of_one_name_are_two_symbols(tmp_path: Path): + write( + tmp_path, + "src/collector.ts", + "\n".join( + [ + "export const Collector = class { run() {} };", + "export type Collector = InstanceType;", + "export interface Store { n: number }", + "export class Store {}", + "export function use(c: Collector) { const x = new Collector(); x.run(); return c; }", + "export function adapt(Collector: number, input: Collector): Collector { return input; }", + "export function outer() { function inner() { type Store = number; let hit: Store = 2; } }", + "export function annotated(c: Collector) { c.run(); }", + "class Other { run() {} }", + "export const Alias = class { run() {} };", + "export type Alias = Other;", + "export function aliased(a: Alias) { a.run(); }", + "export default function Pub() {}", + "type Pub = number;", + ] + ), + ) + write( + tmp_path, + "src/app.ts", + 'import { Collector } from "./collector";\nimport * as col from "./collector";\nexport const c: Collector = new Collector();\nexport let d: col.Collector;\n' + "export class Sub extends col.Collector {}\n", + ) + idx = build_symbol_index(tmp_path, use_cache=False) + s = idx.symbols + value, typ = s["src/collector.ts#Collector"], s["src/collector.ts#Collector@type"] + assert (value.kind, value.line, typ.kind, typ.line, typ.name) == ("variable", 1, "type", 2, "Collector") + assert s["src/collector.ts#Pub"].exported and not s["src/collector.ts#Pub@type"].exported + assert "src/collector.ts#Store@type" not in s # an interface merges into its class + r = refs(idx) + assert ("src/collector.ts#use", "type", "src/collector.ts#Collector@type", "exact") in r + assert ("src/collector.ts#use", "instantiate", "src/collector.ts#Collector", "exact") in r + assert ("src/app.ts#c", "type", "src/collector.ts#Collector@type", "exact") in r + assert ("src/app.ts#c", "instantiate", "src/collector.ts#Collector", "exact") in r + assert ("src/app.ts#d", "type", "src/collector.ts#Collector@type", "exact") in r + assert ("src/collector.ts#use", "call", "src/collector.ts#Collector.run", "typed") in r # `new` names the constructor + assert ("src/collector.ts#annotated", "call", "src/collector.ts#Collector.run", "typed") in r # `x: A` of an instance type + assert ("src/collector.ts#aliased", "call", "src/collector.ts#Other.run", "typed") in r # the alias's class, not the value's + assert ("src/collector.ts#outer.inner", "type", "src/collector.ts#outer.inner.Store", "exact") in r # nearest binding wins + assert ("src/app.ts#Sub", "extends", "src/collector.ts#Collector", "exact") in r # a class base is a value + assert not any(t == "src/collector.ts#Collector" and k == "type" for _s, k, t, _r in r) + # `` declares a generic parameter: neither it nor its uses name the module's type. + assert not any(s == "src/collector.ts#adapt" and t.startswith("src/collector.ts#Collector") for s, _k, t, _r in r)