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
feat(graph): type a Swift call receiver from its declaration (#1688)
Raghav Chamadiya6540c8b69219
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex ffb71ec0c..54ee6ed1b 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -134,6 +134,10 @@ _LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {"kotlin": replace(_JVM_STRATEGIES, member_fallback=_TYPED_RECEIVER),"csharp": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),"python": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),+ # Swift registers the fallback and nothing else: it has no package+ # tier of its own, so a typed receiver is looked for in the caller's+ # file, in what the file imports, and then in the global pair index.+ "swift": _LanguageCallStrategies(member_fallback=_TYPED_RECEIVER),"cpp": _CPP_STRATEGIES,"c": _CPP_STRATEGIES,}diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.pyindex fd9d0f6bd..79820808f 100644--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py@@ -223,12 +223,54 @@ _KT_CONSTRUCTED = re.compile(r"(?<![\w.])va[lr]\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)")+# Swift annotates after the name as Kotlin does, and the same one shape reaches+# more of the language than it does of Kotlin: `let x: Foo`, `var x: Foo` and+# all three parameter spellings are `name: Type`.+#+# The argument label is the reason to anchor on the colon rather than on the+# bracket that opens the list. Swift writes a parameter as `f(x: Foo)`,+# `f(_ x: Foo)` or `f(label x: Foo)`, and in the last of those the declared+# name is the *second* identifier. A pattern anchored at `(` or `,` takes the+# label instead and is wrong 736 times over swift-nio and Alamofire. The+# identifier adjacent to the colon is the declared name in all three+# spellings, with no branch on any of them.+#+# Measured over those two repos, this one shape is 88% of the declaration+# population: 4,001 single-name parameters, 2,876 stored properties, 2,104+# `var`s, 1,356 underscore-label parameters, 1,304 `let`s and 736 two-name+# parameters. The construction shape below is a further 6%.+#+# `some`/`any` is consumed rather than refused: an opaque or existential+# `some Foo` is a `Foo` at the call site, as a trailing `?` or `!` is.+#+# `[Foo]` and `[K: V]` match nothing on purpose — the value is an Array or a+# Dictionary, and typing the name as `Foo` would be wrong rather than merely+# unhelpful. `]` stays out of the closer set for the same reason: it is what a+# dictionary type's inner `k: V` would otherwise close on.+#+# The `let`/`var` keyword is captured for the reason Kotlin's is: an+# initialiser's `init(timeout: Duration = .seconds(5))` sits at type scope and+# closes on `=` exactly as a stored property does, and it is a parameter+# rather than a property. Only a keyword-bearing match may own a field.+_SWIFT_ANNOTATED = re.compile(+ rf"(?<![\w.])(?:(?P<keyword>let|var)\s+)?(?P<name>[a-z_]\w*)\s*:\s*"+ rf"(?:(?:some|any)\s+)?(?P<type>{_TYPE})[?!]?\s*(?=(?P<closer>[=,)\n{{]))"+)++# `let x = Foo(...)`. Bare-named, and refusing a chain, for the reasons+# `_KT_CONSTRUCTED` gives: `let x = Foo.bar()` is a call on a class, and+# `let x = Builder().build()` makes `x` whatever `build()` returns.+_SWIFT_CONSTRUCTED = re.compile(+ r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)"+)+_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)# No Go shape captures a closer, so every Go declaration carries ``""`` and# class scope would drop all of them. That is the intended reading: Go is not# in IMPLICIT_FIELD_LANGUAGES and must not be._GO_FAMILY = (_GO_PARAM, _GO_SHORT_DECL, _GO_VAR_DECL)_KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)+_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_CONSTRUCTED)_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {"csharp": _C_FAMILY,@@ -236,6 +278,7 @@ _LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {"java": _C_FAMILY,"kotlin": _KT_FAMILY,"python": (_PY_ANNOTATED, _PY_CONSTRUCTED),+ "swift": _SWIFT_FAMILY,}RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)@@ -256,7 +299,7 @@ RECEIVER_TYPE_LANGUAGES = frozenset(_LANGUAGE_PATTERNS)# Only a `val`/`var` reaches class scope. A primary-constructor parameter with# a default closes on `=` there too and is not a property at all, which is why# `_KT_ANNOTATED` captures the keyword.-IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "java", "kotlin"})+IMPLICIT_FIELD_LANGUAGES = frozenset({"csharp", "java", "kotlin", "swift"})# A decorator that changes what the symbol it wraps *is*: `@shared_task` leaves# no function behind, so `add.s(...)` is a method call and `(Task, s)` a@@ -365,6 +408,7 @@ _LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {"go": _LINE_COMMENT,"java": _LINE_COMMENT,"kotlin": _LINE_COMMENT,+ "swift": _LINE_COMMENT,"python": _HASH_COMMENT,}diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.pyindex e57aa2c5b..9ac56ac5b 100644--- a/tests/unit/ingestion/test_receiver_types.py+++ b/tests/unit/ingestion/test_receiver_types.py@@ -399,6 +399,105 @@ class TestKotlinFieldScope:assert fields(source, "kotlin", []) == {}++class TestSwiftShapes:+ """Swift annotates after the name, and one shape reaches 88% of it.++ Measured over swift-nio and Alamofire: 4,001 single-name parameters, 2,876+ stored properties, 2,104 `var`s, 1,356 underscore-label parameters, 1,304+ `let`s and 736 two-name-label parameters are all `name: Type`.+ """++ def test_a_typed_let(self) -> None:+ body = "func run() {\n let ctx: ChannelContext = loop.context\n}"+ assert declared_types(body, "swift")["ctx"] == "ChannelContext"++ def test_a_typed_var(self) -> None:+ body = "func run() {\n var channel: ServerChannel = make()\n}"+ assert declared_types(body, "swift")["channel"] == "ServerChannel"++ def test_a_plain_parameter(self) -> None:+ body = "func handle(request: HTTPRequest) { request.body() }"+ assert declared_types(body, "swift")["request"] == "HTTPRequest"++ def test_an_underscore_label_names_the_second_identifier(self) -> None:+ body = "func handle(_ request: HTTPRequest) { request.body() }"+ assert declared_types(body, "swift")["request"] == "HTTPRequest"++ def test_a_two_name_label_names_the_second_identifier(self) -> None:+ """The declared name is `loop`, not `on`. A pattern anchored at `(` or+ `,` takes the label and is wrong 736 times over the two repos; taking+ the identifier adjacent to the colon is right in all three spellings+ with no branch on any of them."""+ body = "func handle(on loop: EventLoop) { loop.execute() }"+ types = declared_types(body, "swift")+ assert types["loop"] == "EventLoop"+ assert "on" not in types++ def test_a_construction(self) -> None:+ body = "func run() {\n let body = ResponseBody(request)\n}"+ assert declared_types(body, "swift")["body"] == "ResponseBody"++ def test_an_opaque_type_keeps_its_type(self) -> None:+ """`some Foo` is a `Foo` at the call site, as `any Foo` is."""+ body = "func run() {\n let opaque: some Renderer = make()\n}"+ assert declared_types(body, "swift")["opaque"] == "Renderer"++ def test_an_optional_keeps_its_type(self) -> None:+ body = "func run() {\n var channel: ServerChannel? = nil\n}"+ assert declared_types(body, "swift")["channel"] == "ServerChannel"++ def test_an_implicitly_unwrapped_optional_keeps_its_type(self) -> None:+ body = "func run() {\n let session: Session! = current\n}"+ assert declared_types(body, "swift")["session"] == "Session"+++class TestSwiftRefusals:+ def test_an_array_types_nothing(self) -> None:+ """The value is an Array of Header, not a Header. The type token starts+ with `[`, so it matches nothing rather than matching wrongly."""+ body = "func run() {\n let items: [Header] = request.headers\n}"+ assert "items" not in declared_types(body, "swift")++ def test_a_dictionary_types_nothing(self) -> None:+ """`]` is kept out of the closer set precisely so the inner `k: V` of a+ dictionary type cannot close on it."""+ body = "func run() {\n let lookup: [String: Header] = request.map\n}"+ assert declared_types(body, "swift") == {}++ def test_a_factory_call_is_not_a_construction(self) -> None:+ body = "func run() {\n let cache = Store.shared(request)\n}"+ assert "cache" not in declared_types(body, "swift")++ def test_a_chained_construction_types_nothing(self) -> None:+ body = "func run() {\n let x = Builder().build()\n}"+ assert declared_types(body, "swift") == {}++ def test_a_doc_comment_parameter_is_not_a_declaration(self) -> None:+ """swift-nio carries 18,722 `///` lines and 331 `- Parameter Name:`+ ones, which read exactly like `name: Type`. `///` starts with `//`, so+ one line-comment pattern covers them; Swift needs no block strip, since+ genuine `/* */` runs are 15 in swift-nio and 2 in Alamofire."""+ body = "/// - Parameter Handler: the RequestHandler to use\nfunc run() { }"+ assert declared_types(body, "swift") == {}++ def test_an_initialiser_parameter_is_not_a_field(self) -> None:+ """It sits at type scope and closes on `=` exactly as a stored property+ does, and it is a parameter. The captured keyword is what refuses it."""+ source = (+ "class C {\n init(timeout: Duration = .seconds(5)) { }\n"+ " func run() { timeout.tick() }\n}"+ )+ assert "timeout" not in fields(source, "swift", [(2, 2), (3, 3)])++ def test_a_stored_property_is_a_field(self) -> None:+ source = (+ "class C {\n private let logger: Logger = Logger()\n"+ " func run() {\n logger.debug()\n }\n}"+ )+ assert fields(source, "swift", [(3, 5)])["logger"] == "Logger"++class TestGoShapes:"""Go writes ``name T``, which is the reverse of every other shape here.@@ -526,7 +625,7 @@ class TestClassScope:def test_the_language_set_is_what_the_patterns_declare() -> None:"""Excluding a language means removing its shapes, not gating a caller."""- assert set(RECEIVER_TYPE_LANGUAGES) == {"csharp", "go", "java", "kotlin", "python"}+ assert set(RECEIVER_TYPE_LANGUAGES) == {"csharp", "go", "java", "kotlin", "python", "swift"}def test_go_is_not_a_field_language() -> None: