Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(parser): TypeScript methods keep their params, regex and ternary consts are symbols (#2680)
Swati Ahuja671e3e703a64
diff --git a/packages/core/src/repowise/core/ingestion/extractors/helpers.py b/packages/core/src/repowise/core/ingestion/extractors/helpers.pyindex d0c588256..fed9b4525 100644--- a/packages/core/src/repowise/core/ingestion/extractors/helpers.py+++ b/packages/core/src/repowise/core/ingestion/extractors/helpers.py@@ -197,20 +197,52 @@ def clean_string_literal(text: str) -> str:return text+# Statements a declaration sits inside when its JSDoc is written above the+# whole statement: ``/** doc */ export const f = () => {}`` puts the comment+# beside the export_statement, not beside the declarator. ``declare`` wraps a+# declaration in an ambient_declaration the same way.+_JSDOC_WRAPPER_TYPES = frozenset(+ {+ "export_statement",+ "ambient_declaration",+ "lexical_declaration",+ "variable_declaration",+ "variable_declarator",+ }+)+++def _leads_statement(node: Node, parent: Node) -> bool:+ """Whether *node* is *parent*'s first named child other than comments and decorators."""+ first = next((c for c in parent.named_children if c.type not in ("comment", "decorator")), None)+ return first is not None and first.id == node.id++def find_preceding_jsdoc(node: Node, src: str) -> str | None:- """Return the JSDoc comment immediately before *node*, if any."""+ """Return the JSDoc comment written directly above *node*, if any.++ Climbs out of the export / declaration wrappers *node* leads (never past+ them, so never past ``program``), steps over the node's own decorators,+ and requires the comment to touch the declaration with no blank line, so a+ file-header comment never documents the first export.+ """parent = node.parent- if parent is None:+ while (+ parent is not None+ and parent.type in _JSDOC_WRAPPER_TYPES+ and _leads_statement(node, parent)+ ):+ node, parent = parent, parent.parent+ prev = node.prev_sibling+ while prev is not None and prev.type == "decorator":+ node, prev = prev, prev.prev_sibling+ if prev is None or prev.type != "comment":return None- siblings = list(parent.children)- idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)- if idx <= 0:+ if node.start_point[0] - prev.end_point[0] > 1:return None- prev = siblings[idx - 1]- if prev.type == "comment":- text = node_text(prev, src).strip()- if text.startswith("/**"):- return clean_jsdoc(text)+ text = node_text(prev, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)return None@@ -237,6 +269,8 @@ def clean_jsdoc(text: str) -> str:cleaned: list[str] = []for line in lines:line = line.strip().lstrip("/*").lstrip()+ # A one-line ``/** doc */`` ends on the closing delimiter too.+ line = line.removesuffix("*/").rstrip()if line:cleaned.append(line)return "\n".join(cleaned).strip()diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pyindex 8817fa075..4d769f8f2 100644--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -31,9 +31,10 @@ def py_visibility(name: str, _mods: list[str]) -> str:return "public"-def ts_visibility(_name: str, mods: list[str]) -> str:+def ts_visibility(name: str, mods: list[str]) -> str:mods_lower = [m.lower() for m in mods]- if "private" in mods_lower:+ # ``#x`` is an ECMAScript private member: private without any modifier.+ if "private" in mods_lower or name.startswith("#"):return "private"if "protected" in mods_lower:return "protected"diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scmindex f07592eef..fe2a0c4bf 100644--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm@@ -22,7 +22,7 @@) @symbol.def(method_definition- name: (property_identifier) @symbol.name+ name: [(property_identifier) (private_property_identifier)] @symbol.nameparameters: (formal_parameters) @symbol.params) @symbol.def@@ -68,6 +68,7 @@(new_expression) (member_expression)(call_expression) (function_expression) (class)(await_expression) (parenthesized_expression)+ (regex) (ternary_expression)]) @symbol.def)@@ -84,6 +85,7 @@(new_expression) (member_expression)(call_expression) (function_expression) (class)(await_expression) (parenthesized_expression)+ (regex) (ternary_expression)]) @symbol.def)diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex 43b5a9efa..50fe47749 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -44,15 +44,13 @@name: (identifier) @symbol.name) @symbol.def-; Method inside class body+; Method inside class body, including ECMAScript #private members. One+; pattern carries both the accessibility modifier and the parameters: the+; parser keeps the first match per (line, name), so a second pattern for+; ``private foo(...)`` used to win the dedup with no @symbol.params.(method_definition- name: (property_identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Private method inside class body (ECMAScript #private members)-(method_definition- name: (private_property_identifier) @symbol.name+ (accessibility_modifier)? @symbol.modifiers+ name: [(property_identifier) (private_property_identifier)] @symbol.nameparameters: (formal_parameters) @symbol.params) @symbol.def@@ -76,12 +74,6 @@)) @symbol.def-; Public method accessor modifier capture-(method_definition- (accessibility_modifier) @symbol.modifiers- name: (property_identifier) @symbol.name-) @symbol.def-; Class property holding a function: ``static create = (...) => {}`` and; ``handler = function () {}``.;@@ -93,7 +85,7 @@; static-factory idiom was absent from every symbol table.;; The optional accessibility_modifier capture keeps ``private handler =-; () => {}`` from reading as public, matching the method patterns above.+; () => {}`` from reading as public, matching the method pattern above.(public_field_definition(accessibility_modifier)? @symbol.modifiersname: [(property_identifier) (private_property_identifier)] @symbol.name@@ -130,6 +122,7 @@(new_expression) (member_expression) (as_expression) (satisfies_expression)(call_expression) (function_expression) (class)(await_expression) (parenthesized_expression) (non_null_expression)+ (regex) (ternary_expression)]) @symbol.def)@@ -146,6 +139,7 @@(new_expression) (member_expression) (as_expression) (satisfies_expression)(call_expression) (function_expression) (class)(await_expression) (parenthesized_expression) (non_null_expression)+ (regex) (ternary_expression)]) @symbol.def)diff --git a/tests/fixtures/lang_samples/typescript/ts_class_modifiers.ts b/tests/fixtures/lang_samples/typescript/ts_class_modifiers.tsnew file mode 100644index 000000000..e9aa6bc36--- /dev/null+++ b/tests/fixtures/lang_samples/typescript/ts_class_modifiers.ts@@ -0,0 +1,41 @@+export class Service {+ public open(path: string, mode = "r"): number {+ return 0;+ }++ private close(fd: number): void {}++ protected flush(fd: number, ...chunks: Uint8Array[]): void {}++ #reset(hard?: boolean) {}++ static create(options: object): Service {+ return new Service();+ }++ async fetch(url: string): Promise<string> {+ return url;+ }++ private static async retry<T>(fn: () => Promise<T>, attempts: number): Promise<T> {+ return fn();+ }++ public override toString(): string {+ return "Service";+ }++ convert(value: string): number;+ convert(value: number): string;+ convert(value: string | number): string | number {+ return value;+ }++ constructor(private readonly root: string) {}+}++export abstract class Repository<T> {+ protected abstract load(id: string): T;++ protected cache(id: string, entity: T): void {}+}diff --git a/tests/fixtures/lang_samples/typescript/ts_module_consts.ts b/tests/fixtures/lang_samples/typescript/ts_module_consts.tsnew file mode 100644index 000000000..aff66343f--- /dev/null+++ b/tests/fixtures/lang_samples/typescript/ts_module_consts.ts@@ -0,0 +1,11 @@+export const SLUG_PATTERN = /^[a-z0-9-]+$/i;+const whitespace = /\s+/g;+export const mode = process.env.NODE_ENV === "production" ? "prod" : "dev";+const retries = isCi ? 5 : 1;+export const limit = 10;++function helper(input: string) {+ const inner = /x/;+ const pick = input ? 1 : 2;+ return inner.test(input) ? pick : 0;+}diff --git a/tests/unit/ingestion/parser/test_jsdoc_attachment.py b/tests/unit/ingestion/parser/test_jsdoc_attachment.pynew file mode 100644index 000000000..8329a911e--- /dev/null+++ b/tests/unit/ingestion/parser/test_jsdoc_attachment.py@@ -0,0 +1,125 @@+"""JSDoc reaches the declaration it is written above, through export wrappers.++``/** doc */ export function f() {}`` puts the comment beside the+export_statement, not beside the function, so reading only the node's own+previous sibling left most exported TS/JS symbols with no docstring. The+comment must touch the declaration: a file header separated by a blank line+documents nothing.+"""++from __future__ import annotations++import pytest++from repowise.core.ingestion.parser import ASTParser+from tests.unit.ingestion.parser._helpers import _make_file_info++# (shape id, source, symbol name, expected docstring or None)+_COMMON_SHAPES = [+ ("plain", "/** Adds. */\nfunction add(a, b) { return a + b; }\n", "add", "Adds."),+ ("exported", "/** Adds. */\nexport function add(a, b) { return a + b; }\n", "add", "Adds."),+ (+ "default_export",+ "/** Main entry. */\nexport default function main() {}\n",+ "main",+ "Main entry.",+ ),+ (+ "const_arrow",+ "/**\n * Doubles a value.\n */\nexport const double = (x) => x * 2;\n",+ "double",+ "Doubles a value.",+ ),+ ("const_value", "/** Slug shape. */\nexport const SLUG = /^[a-z]+$/;\n", "SLUG", "Slug shape."),+ ("class", "/** A shape. */\nexport class Shape {}\n", "Shape", "A shape."),+ (+ "method",+ "export class Shape {\n /** The area. */\n area() { return 0; }\n}\n",+ "area",+ "The area.",+ ),+ (+ "file_header_negative",+ "/**\n * @file Geometry helpers.\n */\n\nexport function area() {}\n",+ "area",+ None,+ ),+ (+ "blank_line_negative",+ "/** Stale note. */\n\nexport const limit = 10;\n",+ "limit",+ None,+ ),+ (+ "second_declarator_negative",+ "/** Only the first. */\nexport const first = 1, second = 2;\n",+ "second",+ None,+ ),+ (+ "line_comment_negative",+ "// Not JSDoc.\nexport function area() {}\n",+ "area",+ None,+ ),+]++_TS_ONLY_SHAPES = [+ (+ "overloads",+ "export function parse(v: string): number;\nexport function parse(v: number): number;\n"+ "/** Parses a value. */\nexport function parse(v: string | number): number { return 0; }\n",+ "parse",+ "Parses a value.",+ ),+ (+ "decorated_class",+ "/** A component. */\n@Component({})\nclass Widget {}\n",+ "Widget",+ "A component.",+ ),+ (+ "decorated_export",+ "/** A component. */\n@Component({})\nexport class Widget {}\n",+ "Widget",+ "A component.",+ ),+ (+ "decorated_method",+ "export class Api {\n /** Lists items. */\n @Get()\n list(): void {}\n}\n",+ "list",+ "Lists items.",+ ),+ (+ "declare",+ "/** Internal shape. */\nexport declare type Shape = { a: number };\n",+ "Shape",+ "Internal shape.",+ ),+ (+ "private_method",+ "export class Api {\n /** Resets state. */\n private reset(hard: boolean): void {}\n}\n",+ "reset",+ "Resets state.",+ ),+]++_CASES = [+ pytest.param(path, lang, src, name, doc, id=f"{path}-{shape}")+ for path, lang, shapes in (+ ("mod.ts", "typescript", _COMMON_SHAPES + _TS_ONLY_SHAPES),+ ("mod.tsx", "typescript", _COMMON_SHAPES + _TS_ONLY_SHAPES),+ ("mod.js", "javascript", _COMMON_SHAPES),+ )+ for shape, src, name, doc in shapes+]++[email protected](("path", "language", "src", "name", "expected"), _CASES)+def test_jsdoc_attachment(+ parser: ASTParser, path: str, language: str, src: str, name: str, expected: str | None+) -> None:+ parsed = parser.parse_file(_make_file_info(path, language), src.encode())+ matches = [s for s in parsed.symbols if s.name == name and not s.is_declaration]+ assert len(matches) == 1, [s.id for s in parsed.symbols]+ assert matches[0].docstring == expecteddiff --git a/tests/unit/ingestion/parser/test_ts_class_members.py b/tests/unit/ingestion/parser/test_ts_class_members.pynew file mode 100644index 000000000..2c236a7b9--- /dev/null+++ b/tests/unit/ingestion/parser/test_ts_class_members.py@@ -0,0 +1,108 @@+"""TypeScript class members keep their parameters, and regex / ternary module+constants are symbols.++A second ``method_definition`` pattern that captured only the accessibility+modifier used to win the parser's per-(line, name) dedup for every+``private`` / ``protected`` / ``public`` method, so those methods lost their+parameter list. Module constants initialised with a regex literal or a+ternary matched no value alternative and minted no symbol at all.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion.parser import ASTParser+from tests.unit.ingestion.parser._helpers import _make_file_info++FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "lang_samples" / "typescript"+++def _symbols(parser: ASTParser, fixture: str) -> dict[str, object]:+ path = FIXTURES / fixture+ parsed = parser.parse_file(_make_file_info(fixture, "typescript"), path.read_bytes())+ # Overload signatures may surface as declarations; the implementation is+ # the one member row per name that carries the body.+ return {s.name: s for s in parsed.symbols if not s.is_declaration}+++ ("name", "signature", "visibility"),+ [+ ("open", 'open(path: string, mode = "r") -> number', "public"),+ ("close", "close(fd: number) -> void", "private"),+ ("flush", "flush(fd: number, ...chunks: Uint8Array[]) -> void", "protected"),+ ("#reset", "#reset(hard?: boolean)", "private"),+ ("create", "create(options: object) -> Service", "public"),+ ("fetch", "fetch(url: string) -> Promise<string>", "public"),+ (+ "retry",+ "retry(fn: () => Promise<T>, attempts: number) -> Promise<T>",+ "private",+ ),+ ("toString", "toString() -> string", "public"),+ ("convert", "convert(value: string | number) -> string | number", "public"),+ ("constructor", "constructor(private readonly root: string)", "public"),+ ("cache", "cache(id: string, entity: T) -> void", "protected"),+ ],+)+def test_member_signature_and_visibility(+ parser: ASTParser, name: str, signature: str, visibility: str+) -> None:+ sym = _symbols(parser, "ts_class_modifiers.ts")[name]+ assert sym.kind == "method"+ assert sym.signature == signature+ assert sym.visibility == visibility+++def test_async_member_flags(parser: ASTParser) -> None:+ syms = _symbols(parser, "ts_class_modifiers.ts")+ assert syms["fetch"].is_async+ assert syms["retry"].is_async+ assert not syms["create"].is_async+++def test_members_parented_to_their_class(parser: ASTParser) -> None:+ syms = _symbols(parser, "ts_class_modifiers.ts")+ assert syms["close"].parent_name == "Service"+ assert syms["cache"].parent_name == "Repository"+ assert syms["Repository"].kind == "class"+++def test_one_row_per_accessibility_modified_method(parser: ASTParser) -> None:+ parsed = parser.parse_file(+ _make_file_info("ts_class_modifiers.ts", "typescript"),+ (FIXTURES / "ts_class_modifiers.ts").read_bytes(),+ )+ ids = [s.id for s in parsed.symbols if s.name in ("open", "close", "flush", "retry")]+ assert len(ids) == len(set(ids)) == 4+++def test_regex_and_ternary_module_constants(parser: ASTParser) -> None:+ syms = _symbols(parser, "ts_module_consts.ts")+ assert syms["SLUG_PATTERN"].kind == "constant"+ assert syms["SLUG_PATTERN"].visibility == "public"+ assert syms["whitespace"].kind == "variable"+ assert syms["whitespace"].visibility == "private"+ assert syms["mode"].visibility == "public"+ assert syms["retries"].visibility == "private"+ assert syms["limit"].kind == "variable"+++def test_function_local_regex_and_ternary_stay_unindexed(parser: ASTParser) -> None:+ syms = _symbols(parser, "ts_module_consts.ts")+ assert "helper" in syms+ assert "inner" not in syms+ assert "pick" not in syms+++def test_javascript_private_method_and_regex_constant(parser: ASTParser) -> None:+ src = b"export const RE = /a+/g;\nconst flag = a ? 1 : 2;\nclass C {\n #step(n) {}\n}\n"+ parsed = parser.parse_file(_make_file_info("mod.js", "javascript"), src)+ syms = {s.name: s for s in parsed.symbols}+ assert syms["RE"].kind == "constant"+ assert "flag" in syms+ assert syms["#step"].signature == "#step(n)"+ assert syms["#step"].parent_name == "C"