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(ingestion): resolve Pascal dead-code false positives and disambiguate type kinds (#1675)
Laentir Valetovb9c852c4f130
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 61fd34466..008ddf8c6 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -362,10 +362,12 @@ cannot check.parse that succeeds with the wrong meaning is worse than a skip. Componentprops are set by the parent as markup attributes and never imported by name, sothe unused-export pass is suppressed for both.-- **Object Pascal type kinds collapse.** `record` / `interface` / class-helper /- enum / type alias all report as `kind="class"`, and its `extends` vs- `implements` split is inferred from the `I`-prefix naming convention rather- than guaranteed by the language.+- **Object Pascal's `extends`/`implements` split is a naming heuristic.**+ `class(TBase, IFoo, IBar)` doesn't itself distinguish a base class from an+ implemented interface; the heritage extractor infers it from the `I`-prefix+ convention rather than a language guarantee. (`record` / `interface` /+ class-helper / enum / type alias each report their own `SymbolKind` via+ `refine_pascal_type_kind` — they no longer collapse to `kind="class"`.)- **C has no health dialect.** It shares the C++ grammar for parsing but reachesno health walker map, so it gets graph coverage without markers.- **Scala import resolution is partial**, and ScalaTest's infix DSLdiff --git a/packages/core/src/repowise/core/ingestion/extractors/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/__init__.pyindex 0026ed9a8..823d93a8b 100644--- a/packages/core/src/repowise/core/ingestion/extractors/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/__init__.py@@ -7,6 +7,7 @@ from .helpers import (node_text,refine_go_type_kind,refine_kotlin_class_kind,+ refine_pascal_type_kind,)from .heritage import HERITAGE_EXTRACTORS, extract_heritagefrom .signatures import build_signature@@ -24,4 +25,5 @@ __all__ = ["node_text","refine_go_type_kind","refine_kotlin_class_kind",+ "refine_pascal_type_kind",]diff --git a/packages/core/src/repowise/core/ingestion/extractors/helpers.py b/packages/core/src/repowise/core/ingestion/extractors/helpers.pyindex 9db170956..cd585d35f 100644--- a/packages/core/src/repowise/core/ingestion/extractors/helpers.py+++ b/packages/core/src/repowise/core/ingestion/extractors/helpers.py@@ -59,6 +59,51 @@ def refine_kotlin_class_kind(class_node: Node) -> str:return "class"+def refine_pascal_type_kind(decl_type_node: Node) -> str:+ """Refine the generic ``class`` kind for Pascal ``declType`` nodes.++ ``declType`` wraps class / record / object / interface / class-helper+ / enum / set / array / plain-alias in one node shape (see+ ``languages/specs/pascal.py``'s spec docstring). Its ``type`` field is+ one of two shapes:++ * a class-like node directly -- ``declClass`` (covers *both* the+ ``class`` and ``record``/``object`` keyword forms; the grammar has+ no separate "record" node, so the first child's keyword token+ (``kRecord`` vs. ``kClass``/``kObject``) is what actually+ distinguishes them), ``declIntf``, or ``declHelper``;+ * a generic ``type`` wrapper around ``declEnum``, ``declSet``,+ ``declArray``, or a bare ``typeref`` (a plain alias, e.g.+ ``TMyInt = Integer;``).++ ``object`` and class-helper both collapse to ``"class"`` -- Pascal's+ pre-OOP ``object`` type and a class helper both declare members the+ same shape a class does, and neither has a closer match in+ :data:`~repowise.core.ingestion.models.SymbolKind`. ``set``/``array``/+ plain-alias all collapse to ``"type_alias"`` for the same reason:+ none of them declare members of their own, so ``"class"`` would be+ actively misleading.+ """+ type_node = decl_type_node.child_by_field_name("type")+ if type_node is None:+ return "class"+ if type_node.type == "declClass":+ first_child = type_node.children[0] if type_node.children else None+ if first_child is not None and first_child.type == "kRecord":+ return "struct"+ return "class"+ if type_node.type == "declIntf":+ return "interface"+ if type_node.type == "declHelper":+ return "class"+ if type_node.type == "type":+ inner = next(iter(type_node.named_children), None)+ if inner is not None and inner.type == "declEnum":+ return "enum"+ return "type_alias"+ return "class"++def clean_string_literal(text: str) -> str:"""Strip quote characters from a Python string literal."""text = text.strip()diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/pascal.py b/packages/core/src/repowise/core/ingestion/languages/specs/pascal.pyindex 24ceef2b5..55f65ad75 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/pascal.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/pascal.py@@ -69,6 +69,22 @@ SPEC = LanguageSpec("TObject", "TInterfacedObject", "TPersistent", "TComponent","IUnknown", "IInterface", "IDispatch",}),+ # Ordinal/scalar built-ins plus the universal VCL/RTL root types (the+ # latter overlap with builtin_parents above) -- none of these ever have+ # an in-repo declaration, so resolving them as a type reference is a+ # guaranteed miss. Read back via get_builtin_types("pascal") in+ # parser_helpers.py's head-identifier extractor.+ builtin_types=frozenset({+ "Integer", "Cardinal", "Boolean", "ByteBool", "WordBool", "LongBool",+ "String", "AnsiString", "WideString", "UnicodeString", "ShortString",+ "Char", "AnsiChar", "WideChar", "Byte", "ShortInt", "SmallInt", "Word",+ "LongWord", "LongInt", "Int64", "UInt64", "NativeInt", "NativeUInt",+ "Single", "Double", "Extended", "Real", "Real48", "Currency", "Comp",+ "Variant", "OleVariant", "Pointer", "PChar", "PAnsiChar", "PWideChar",+ "TDateTime", "TDate", "TTime", "TGUID", "TClass", "HRESULT", "TBytes",+ "TObject", "TInterfacedObject", "TPersistent", "TComponent",+ "IUnknown", "IInterface", "IDispatch",+ }),# Delphi/FPC has no same-directory same-stem test-file convention (no# ``uFoo.pas`` <-> ``uFoo_test.pas``): a unit is exercised by a# standalone console test *program* named ``Test<Unit>.dpr`` -- onediff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex bfbde4b27..a38e9dac2 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -42,6 +42,7 @@ from .extractors import (node_text,refine_go_type_kind,refine_kotlin_class_kind,+ refine_pascal_type_kind,)from .extractors.bindings.python import expand_bare_relative_importsfrom .extractors.bindings.ts_js import (@@ -721,6 +722,13 @@ class ASTParser:):kind = refine_kotlin_class_kind(def_node)+ # Refine "class" kind for Pascal (declType wraps class / record /+ # object / interface / class-helper / enum / set / array / alias+ # in one node shape -- see the spec docstring and+ # refine_pascal_type_kind's own docstring for the disambiguation).+ if kind == "class" and file_info.language == "pascal" and def_node.type == "declType":+ kind = refine_pascal_type_kind(def_node)+# Dart: a function is a ``function_signature`` whose BODY is a# sibling ``function_body`` node (members wrap the signature in# ``method_signature``). Two consequences the generic path can't@@ -1043,7 +1051,25 @@ class ASTParser:Import(raw_statement=raw,module_path=unit_name,- imported_names=[],+ # ``uses UnitA;`` exposes UnitA's ENTIRE public+ # interface section, unlike Python/JS's+ # name-scoped `from x import y` -- Pascal has no+ # per-symbol import syntax to name a specific+ # one. ``imported_names=[]`` (empty, not+ # wildcard) meant dead_code/analyzer.py's+ # `sym_name in imported_names` / `"*" in+ # imported_names` file-level unused-export+ # rescue could structurally never fire for+ # Pascal -- every public symbol fell straight+ # through to the (now Phase-1-fixed, but still+ # best-effort) symbol-level call/type_use+ # rescue instead. ``["*"]`` is this codebase's+ # existing wildcard-import sentinel (see the+ # Python `import *` and CJS re-export branches+ # of this function) and is the semantically+ # correct value here, not a workaround: it says+ # exactly what a Pascal `uses` clause does.+ imported_names=["*"],is_relative=False,resolved_file=None,bindings=[],diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.pyindex 1df8e1b1a..e6f515ba5 100644--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py@@ -18,6 +18,7 @@ import structlogfrom tree_sitter import Nodefrom .extractors import node_text+from .language_data import get_builtin_typesfrom .type_names import is_resolvable_type_nameif TYPE_CHECKING:@@ -378,6 +379,12 @@ _PARAM_ORIGIN_BY_ANCESTOR: dict[str, str] = {"class_parameter": "ctor_param", # Kotlin primary-ctor parameter"variable_declaration": "field_type", # Kotlin property declaration"delegation_specifier": "extends", # Kotlin class : Bar()+ # Pascal type positions — node types are Pascal-only, no collision risk.+ "declField": "field_type",+ "declArg": "param_type",+ "declVar": "local_var_type",+ "declProc": "return_type",+ "exprArgs": "framework_ctor", # Application.CreateForm(TClass, Var)}@@ -889,6 +896,56 @@ def _rust_head_type_identifier(type_node: Node, src: str) -> str | None:return text if is_resolvable_type_name(text, "rust") else None+def _pascal_head_type_identifier(type_node: Node, src: str) -> str | None:+ """Return the head identifier of a Pascal ``typeref`` type expression.++ Examples:+ ``TFoo`` → "TFoo"+ ``TList<TBar>`` → "TList" (generic head only; the arg+ isn't captured separately -- no+ ``typerefArgs``-scoped query pattern+ exists yet)+ ``Ns.TQualified`` → "TQualified" (rightmost segment;+ Pascal's unit-qualification puts the+ type name last, same convention as+ C#'s ``qualified_name`` handling)+ ``Integer`` / ``TObject`` → None (builtin / VCL root type, never+ has an in-repo declaration)++ ``type_node`` is the ``typeref`` node pascal.scm captures directly (a+ ``declProc`` return type) or via the intermediate ``type`` wrapper+ (field/parameter/local-variable positions) -- the wrapper itself is+ never captured, only the ``typeref`` inside it, so this always starts+ from ``typeref`` regardless of which position it came from. A+ ``typeref`` wraps exactly one of: a bare ``identifier``, a generic+ ``typerefTpl`` (``entity`` field holds the head), or a qualified+ ``typerefDot`` (``rhs`` field holds the type name -- ``lhs`` is the+ unit qualifier).+ """+ head = type_node+ if head.type == "typeref":+ head = next(iter(head.named_children), None)+ if head is None:+ return None+ if head.type == "typerefTpl":+ entity = head.child_by_field_name("entity")+ if entity is None:+ return None+ head = entity+ elif head.type == "typerefDot":+ rhs = head.child_by_field_name("rhs")+ if rhs is None:+ return None+ head = rhs++ if head.type != "identifier":+ return None+ text = node_text(head, src).strip()+ if not text or text in get_builtin_types("pascal"):+ return None+ return text++# Per-language head-identifier extractor for ``@param.type`` captures.# Defaults to the C#-shaped extractor; languages with a differently-shaped# type grammar register their own here.@@ -901,6 +958,7 @@ TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {"java": _java_head_type_identifier,"kotlin": _kotlin_head_type_identifier,"rust": _rust_head_type_identifier,+ "pascal": _pascal_head_type_identifier,}diff --git a/packages/core/src/repowise/core/ingestion/queries/pascal.scm b/packages/core/src/repowise/core/ingestion/queries/pascal.scmindex 8b8991d64..433aeb348 100644--- a/packages/core/src/repowise/core/ingestion/queries/pascal.scm+++ b/packages/core/src/repowise/core/ingestion/queries/pascal.scm@@ -171,6 +171,39 @@lhs: (_) @call.receiverrhs: (exprTpl entity: (identifier) @call.target))) @call.site+; A parenless call is just as idiomatic on an assignment's RHS as it is+; bare-statement -- `Result := GetDefaultNDNProfile;` is the standard shape+; for a niladic Delphi function, arguably *more* common than the bare-+; statement form above (a niladic function is normally called for its+; result, which means an assignment). Verified against MTN2: every call+; site of a real niladic function (GetDefaultNDNProfile, 8 call sites) was+; this shape, and none were captured before this pattern -- the function+; read as having zero callers even from within its own file. `assignment`+; is a distinct node from `statement` (not nested in it), so the earlier+; `statement`-anchored patterns never fire here regardless of order.+;+; Unlike the bare-statement form, this is genuinely ambiguous at the+; grammar level: `X := Y;` fires this pattern whether `Y` is a niladic+; function call or a plain variable read -- Pascal's grammar doesn't (and+; can't, without a symbol table) distinguish them. Left deliberately+; over-eager rather than trying to disambiguate: a stray edge to an+; unrelated same-named local only ever ADDS usage evidence somewhere in+; the graph, which can suppress a real dead-code finding (a false+; negative) but can never manufacture a "confidently dead" false+; positive -- the failure direction this whole pass exists to avoid.+(assignment+ rhs: (identifier) @call.target) @call.site++(assignment+ rhs: (exprDot+ lhs: (_) @call.receiver+ rhs: (identifier) @call.target)) @call.site++(assignment+ rhs: (exprDot+ lhs: (_) @call.receiver+ rhs: (exprTpl entity: (identifier) @call.target))) @call.site+; ---------------------------------------------------------------; `inherited Foo;` / `inherited Foo(...)` -- calls the base class's; same-named method. The bare `inherited;` form (no explicit name) is@@ -188,3 +221,61 @@entity: (inherited(identifier) @call.target)args: (exprArgs)? @call.arguments) @call.site++; ---------------------------------------------------------------+; Type references -- a class/interface/record named only in a field,+; parameter, local-variable, or return-type position (never called,+; never subclassed) previously minted no usage edge at all, since+; pascal.scm had no `@param.type` captures (unlike C#/Go/Java/Kotlin/TS).+; ``parser.py:_extract_type_refs`` collects these into TypeReference+; records generically; ``_pascal_head_type_identifier`` in+; parser_helpers.py unwraps the `typeref` shape (plain / generic+; `typerefTpl` / qualified `typerefDot`) down to the head identifier.+; Verified against MTN2: TConsoleBuffer / TDialogHost read as having zero+; importers despite being referenced in 10-18 files, exclusively through+; declarations of this shape (`FBuf: TConsoleBuffer;`), never through a+; call or heritage edge.+;+; `declField`/`declArg`/`declVar` wrap their type in an intermediate+; `type` node (which can also hold array/set/generic-class-body shapes+; the `typeref` case doesn't cover); `declProc`'s return-type field holds+; a bare `typeref` directly -- see the grammar note at the top of this+; file. Both shapes are captured; anything under `type` that isn't a+; `typeref` (e.g. an inline `array of X`) is simply not matched, same+; "no rule, no capture" degradation as everywhere else in this file.+; ---------------------------------------------------------------++(declField+ type: (type (typeref) @param.type))++(declArg+ type: (type (typeref) @param.type))++(declVar+ type: (type (typeref) @param.type))++(declProc+ type: (typeref) @param.type)++; ---------------------------------------------------------------+; `Application.CreateForm(TMainForm, MainForm);` -- the classic VCL/FMX/+; LCL entry-point idiom, universal across Delphi and Lazarus project+; (.dpr/.lpr) files. The class argument is a bare identifier passed by+; value, not a receiver or a type-position declaration -- no other+; pattern in this file captures it, so a form class referenced ONLY this+; way (never a `var x: TMainForm` elsewhere, which is otherwise the norm+; for every other class) still read as having zero importers even after+; the type-reference captures above. Scoped tightly to the literal+; `CreateForm` call target (case-insensitive -- Pascal identifiers are)+; specifically to avoid the much broader, much noisier alternative of+; treating every bare-identifier call argument as a possible type+; reference. Only the first argument is captured (`.` anchors it) --+; `CreateForm`'s second parameter is a `var` reference, not a class.+; ---------------------------------------------------------------++(exprCall+ entity: (exprDot+ rhs: (identifier) @_pascal_create_form_check)+ args: (exprArgs+ . (identifier) @param.type)+ (#match? @_pascal_create_form_check "(?i)^CreateForm$"))diff --git a/tests/unit/dead_code/test_interfaces.py b/tests/unit/dead_code/test_interfaces.pyindex 652ea8c55..b07712aff 100644--- a/tests/unit/dead_code/test_interfaces.py+++ b/tests/unit/dead_code/test_interfaces.py@@ -121,6 +121,132 @@ def test_com_contract_method_demoted_below_safe_threshold():assert f.safe_to_delete is False+def test_pascal_unused_export_is_not_blanket_capped():+ """Object Pascal is no longer capped as a whole language.++ A blanket confidence cap on every Pascal unused-export finding was a+ temporary mitigation (PR #1353 follow-up) for real query gaps —+ assignment-RHS parenless calls and missing var/field/parameter/+ return-type/framework-ctor type-reference captures, all now fixed in+ pascal.scm and parser.py — plus a structural gap where ``uses``+ carried no per-symbol ``imported_names`` for the file-level rescue to+ match against (also fixed: Pascal imports now carry the wildcard+ sentinel ``["*"]``, since ``uses`` exposes a whole unit's public+ interface). Re-validated against the real ~150-file Delphi codebase+ that surfaced the original false positives: 603 findings dropped to+ 1, and that one was already a known, correctly-low-confidence+ candidate, not a Pascal false positive. A genuinely unimported,+ uncalled, untyped-as symbol should flag at full confidence like any+ other language now — no language-wide cap left to interfere.+ """+ g = _build_graph(+ nodes={+ "src/uConsole.pas": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "TConsoleBuffer",+ "kind": "class",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 20,+ "complexity_estimate": 1,+ "language": "pascal",+ },+ ],+ },+ },+ edges=[],+ )+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ }+ )+ pascal_findings = [+ f+ for f in report.findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "TConsoleBuffer"+ ]+ assert pascal_findings, "expected a finding for TConsoleBuffer"+ assert any(f.confidence >= 0.7 and f.safe_to_delete for f in pascal_findings), (+ "a genuinely-unused Pascal symbol with no risk factors should still be able to "+ f"reach safe-to-delete confidence, got {[(f.confidence, f.safe_to_delete) for f in pascal_findings]}"+ )+++def test_pascal_uses_clause_rescues_every_public_symbol_in_the_unit():+ """A ``uses UnitA;`` clause exposes UnitA's entire public interface+ section, unlike Python/JS's name-scoped ``from x import y`` -- Pascal+ has no per-symbol import syntax. ``parser.py`` emits+ ``imported_names=["*"]`` for every Pascal import edge for exactly this+ reason, which should rescue every public symbol in a unit that's+ named in another file's ``uses`` clause, not just capped confidence.+ """+ g = _build_graph(+ nodes={+ "src/uConsole.pas": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "TConsoleBuffer",+ "kind": "class",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 20,+ "complexity_estimate": 1,+ "language": "pascal",+ },+ ],+ },+ "src/uMain.pas": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 0,+ "symbols": [],+ },+ },+ # uMain.pas has `uses uConsole;` -- Pascal's parser.py emits this+ # as a wildcard import (no per-symbol names in the uses syntax).+ edges=[+ (+ "src/uMain.pas",+ "src/uConsole.pas",+ {"edge_type": "imports", "imported_names": ["*"]},+ )+ ],+ )+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})+ report = analyzer.analyze(+ {+ "detect_unreachable_files": False,+ "detect_zombie_packages": False,+ "min_confidence": 0.0,+ }+ )+ pascal_findings = [+ f+ for f in report.findings+ if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "TConsoleBuffer"+ ]+ assert not pascal_findings, (+ "TConsoleBuffer should be rescued entirely by the uses-clause wildcard import, "+ f"got {pascal_findings}"+ )++def test_release_in_non_com_language_not_clamped():"""A free function named ``Release`` in TypeScript/Python is *not* aCOM contract method — the contract-method clamp must not apply.diff --git a/tests/unit/ingestion/parser/test_pascal.py b/tests/unit/ingestion/parser/test_pascal.pyindex aeeb82ae5..5d736dbe7 100644--- a/tests/unit/ingestion/parser/test_pascal.py+++ b/tests/unit/ingestion/parser/test_pascal.py@@ -57,7 +57,10 @@ class TestPascalSymbols:result = parser.parse_file(_pas(), UNIT_SOURCE)kinds = {(s.name, s.kind) for s in result.symbols}assert ("TCalculator", "class") in kinds- assert ("ICalcTarget", "class") in kinds+ # Review follow-up on PR #1353: declType used to collapse every+ # type form to "class" -- refine_pascal_type_kind now+ # disambiguates via the declType's `type` field shape.+ assert ("ICalcTarget", "interface") in kindsdef test_interface_and_implementation_method_collapse_to_one_symbol(self, parser: ASTParser@@ -272,6 +275,17 @@ class TestPascalImports:modules = {i.module_path for i in result.imports}assert modules == {"SysUtils", "Classes", "Ns.UnitC"}+ def test_uses_clause_carries_wildcard_imported_names(self, parser: ASTParser) -> None:+ # `uses UnitA;` exposes UnitA's entire public interface section --+ # there's no Pascal syntax to name a specific imported symbol the+ # way Python's `from x import y` does. `imported_names=["*"]`+ # (this codebase's existing wildcard-import sentinel) lets+ # dead_code/analyzer.py's file-level unused-export rescue work for+ # Pascal; `imported_names=[]` meant it could never fire.+ result = parser.parse_file(_pas(), UNIT_SOURCE)+ assert result.imports+ assert all(i.imported_names == ["*"] for i in result.imports)+def test_single_unit_uses_clause(self, parser: ASTParser) -> None:src = b"""\unit Only;@@ -384,6 +398,92 @@ end.assert [i.module_path for i in result.imports] == ["SysUtils"]+class TestPascalTypeKinds:+ """``declType`` wraps class / record / object / interface / class-helper+ / enum / set / array / plain-alias in one node shape. Review follow-up+ on PR #1353: all eight forms used to collapse to ``kind="class"``;+ ``refine_pascal_type_kind`` now disambiguates via the declType's+ ``type`` field shape.+ """++ SRC = b"""\+unit Foo;+interface+type+ TColor = (Red, Green, Blue);+ TColorSet = set of TColor;+ TIntArray = array[0..9] of Integer;+ TMyInt = Integer;+ TRec = record+ X: Integer;+ end;+ TCls = class+ Y: Integer;+ end;+ TIntf = interface+ procedure DoFoo;+ end;+ THelper = class helper for TObject+ procedure Bar;+ end;+implementation+end.+"""++ def test_class_stays_class(self, parser: ASTParser) -> None:+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TCls"] == "class"++ def test_record_becomes_struct(self, parser: ASTParser) -> None:+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TRec"] == "struct"++ def test_interface_becomes_interface(self, parser: ASTParser) -> None:+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TIntf"] == "interface"++ def test_class_helper_stays_class(self, parser: ASTParser) -> None:+ # A helper declares members the same shape a class does, and has+ # no closer match in SymbolKind.+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["THelper"] == "class"++ def test_enum_becomes_enum(self, parser: ASTParser) -> None:+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TColor"] == "enum"++ def test_set_and_array_and_plain_alias_become_type_alias(+ self, parser: ASTParser+ ) -> None:+ result = parser.parse_file(_pas(), self.SRC)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TColorSet"] == "type_alias"+ assert kinds["TIntArray"] == "type_alias"+ assert kinds["TMyInt"] == "type_alias"++ def test_object_form_becomes_class(self, parser: ASTParser) -> None:+ # Pascal's pre-OOP `object` type declares members the same shape+ # a class does -- no closer SymbolKind match, same as helper.+ src = b"""\+unit Foo;+interface+type+ TObj = object+ Z: Integer;+ end;+implementation+end.+"""+ result = parser.parse_file(_pas(), src)+ kinds = {s.name: s.kind for s in result.symbols}+ assert kinds["TObj"] == "class"++class TestPascalHeritage:def test_extends_and_implements(self, parser: ASTParser) -> None:result = parser.parse_file(_pas(), UNIT_SOURCE)@@ -633,3 +733,266 @@ end.# emitted for it (and nothing should crash trying).assert None not in namesassert "Сложить" not in names++ def test_niladic_call_as_assignment_rhs_is_a_call_site(self, parser: ASTParser) -> None:+ # Review follow-up on PR #1353 (real-world MTN2 validation): a+ # niladic function's result assigned to a variable --+ # `Profile := GetDefaultNDNProfile;` -- is the dominant Delphi+ # idiom for calling one, arguably more common than the bare+ # call-statement form covered above. Missing this meant a+ # function called exclusively this way (even from within its own+ # file) read as having zero callers.+ src = b"""\+unit Foo;+interface+implementation+function GetProfile: Integer;+begin+ Result := 1;+end;+procedure P;+var+ Profile: Integer;+begin+ Profile := GetProfile;+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ calls = {(c.target_name, c.receiver_name) for c in result.calls}+ assert ("GetProfile", None) in calls++ def test_niladic_method_call_as_assignment_rhs_is_a_call_site(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+implementation+procedure P;+var+ Obj: TFoo;+ Value: Integer;+begin+ Value := Obj.GetValue;+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ calls = {(c.target_name, c.receiver_name) for c in result.calls}+ assert ("GetValue", "Obj") in calls++ def test_plain_variable_assignment_still_mints_a_call_edge(self, parser: ASTParser) -> None:+ # Documents a known, deliberate imprecision: Pascal's grammar+ # can't distinguish `X := SomeFunc;` (niladic call) from+ # `X := SomeVar;` (plain read) without a symbol table, so the+ # assignment-RHS pattern fires on both. Accepted because it is+ # directionally safe for dead-code purposes -- a stray edge only+ # ever adds usage evidence (a possible false negative), never+ # manufactures a "confidently dead" false positive.+ src = b"""\+unit Foo;+interface+implementation+procedure P;+var+ A, B: Integer;+begin+ A := B;+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ calls = {(c.target_name, c.receiver_name) for c in result.calls}+ assert ("B", None) in calls+++class TestPascalTypeReferences:+ """Type-reference coverage — a class named only in a field, parameter,+ local-variable, or return-type position previously minted no usage+ edge at all (pascal.scm had no ``@param.type`` captures, unlike+ C#/Go/Java/Kotlin/TS). Review follow-up on PR #1353: verified against+ MTN2 that classes referenced exclusively this way (never called,+ never subclassed) read as having zero importers.+ """++ def test_field_type_reference(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TBuffer = class+ end;++ TOwner = class+ FBuf: TBuffer;+ end;+implementation+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {(t.type_name, t.origin) for t in result.type_refs}+ assert ("TBuffer", "field_type") in refs++ def test_parameter_type_reference(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TBuffer = class+ end;+procedure DoWork(Buf: TBuffer);+implementation+procedure DoWork(Buf: TBuffer);+begin+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {(t.type_name, t.origin) for t in result.type_refs}+ assert ("TBuffer", "param_type") in refs++ def test_local_variable_type_reference(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TBuffer = class+ end;+implementation+procedure DoWork;+var+ Local: TBuffer;+begin+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {(t.type_name, t.origin) for t in result.type_refs}+ assert ("TBuffer", "local_var_type") in refs++ def test_return_type_reference(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TBuffer = class+ end;+function MakeBuffer: TBuffer;+implementation+function MakeBuffer: TBuffer;+begin+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {(t.type_name, t.origin) for t in result.type_refs}+ assert ("TBuffer", "return_type") in refs++ def test_qualified_type_reference_takes_the_rightmost_segment(+ self, parser: ASTParser+ ) -> None:+ src = b"""\+unit Foo;+interface+type+ TOwner = class+ FBuf: Ns.TQualifiedBuffer;+ end;+implementation+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {t.type_name for t in result.type_refs}+ assert "TQualifiedBuffer" in refs+ assert "Ns" not in refs++ def test_generic_type_reference_takes_the_head(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TOwner = class+ FList: TList<TItem>;+ end;+implementation+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {t.type_name for t in result.type_refs}+ assert "TList" in refs++ def test_builtin_scalar_types_are_not_captured(self, parser: ASTParser) -> None:+ src = b"""\+unit Foo;+interface+type+ TOwner = class+ FCount: Integer;+ FName: String;+ FBase: TObject;+ end;+implementation+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {t.type_name for t in result.type_refs}+ assert refs.isdisjoint({"Integer", "String", "TObject"})++ def test_application_create_form_first_argument_is_a_type_reference(+ self, parser: ASTParser+ ) -> None:+ # Review follow-up on PR #1353 (real-world MTN2 validation):+ # `Application.CreateForm(TMainForm, MainForm);` is the classic+ # VCL/FMX/LCL entry-point idiom -- the class argument is a bare+ # call argument, not a var/field/param declaration, so none of+ # the type-reference patterns above capture it. A form class+ # referenced only this way (never `var x: TMainForm` elsewhere)+ # still read as having zero importers.+ src = b"""\+program MTN2;+uses uMainForm;+begin+ Application.Initialize;+ Application.CreateForm(TMainForm, MainForm);+ Application.Run;+end.+"""+ result = parser.parse_file(_make_file_info("MTN2.dpr", "pascal"), src)+ refs = {(t.type_name, t.origin) for t in result.type_refs}+ assert ("TMainForm", "framework_ctor") in refs+ # The second (var-reference) argument must not be captured.+ assert "MainForm" not in {t.type_name for t in result.type_refs}++ def test_create_form_case_insensitive_and_second_arg_not_captured(+ self, parser: ASTParser+ ) -> None:+ # Pascal identifiers are case-insensitive; the query must match+ # `createform` / `CREATEFORM` the same as `CreateForm`.+ src = b"""\+program Foo;+begin+ Application.createform(TSplash, Splash);+end.+"""+ result = parser.parse_file(_make_file_info("Foo.dpr", "pascal"), src)+ refs = {t.type_name for t in result.type_refs}+ assert "TSplash" in refs+ assert "Splash" not in refs++ def test_ordinary_call_arguments_are_not_type_references(+ self, parser: ASTParser+ ) -> None:+ # The CreateForm pattern must not fire for an unrelated call whose+ # first argument happens to look like a type name.+ src = b"""\+unit Foo;+interface+implementation+procedure P;+begin+ DoSomething(TFoo, TBar);+end;+end.+"""+ result = parser.parse_file(_pas(), src)+ refs = {t.type_name for t in result.type_refs}+ assert refs.isdisjoint({"TFoo", "TBar"})