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(health): a complexity map for Swift (#3450)
Yang Bai08b6e738a7a2
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex bf804e0a5..f1d56d486 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -967,9 +967,13 @@ cognitive complexity and per-function markers. Optional additions widen it:metrics (LCOM4, god-class); `assert_kinds` / `assert_call_kinds` addassertion-block smells. See `complexity/README.md`.-C, F# and Objective-C have maps of their own (C separate from C++ despite the-shared grammar), so they get complexity markers, but none of the three has a perf-or dataflow dialect yet.+C, Swift, F# and Objective-C have maps of their own (C separate from C++ despite+the shared grammar), so they get complexity markers, but none of the four has a+perf or dataflow dialect yet. Swift's map counts `guard` as a decision, a `for` /+`catch` `where` filter as one more, and a computed property (also a subscript's+body, and a `willSet` / `didSet` block) as a function unit named for the property;+a struct, an enum, an extension and an actor are classes, since the grammar gives+them all `class_declaration`.### 2. Performance: `analysis/health/perf/dialects/` (`PERF_DIALECTS`)diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 93996cc87..00aeb6c9a 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -57,7 +57,7 @@ resolution and health markers are all static.| Tier | Languages | What you get ||------|-----------|--------------|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges and code-health markers |-| **Good** (11) | C · Swift · PHP · Dart · Object Pascal · COBOL · GDScript · VB.NET · Elixir · F# · Objective-C | Everything above except the full health suite. Dart, Object Pascal and PHP get health markers; C, F# and Objective-C get the complexity-derived ones; the rest get none yet |+| **Good** (11) | C · Swift · PHP · Dart · Object Pascal · COBOL · GDScript · VB.NET · Elixir · F# · Objective-C | Everything above except the full health suite. Dart, Object Pascal and PHP get health markers; C, Swift, F# and Objective-C get the complexity-derived ones; the rest get none yet || **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo and `.luaurc` aware), no health markers. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers, no import edges yet || **Lightweight** (6) | Clojure · Haskell · Lean 4 · Erlang · HTML · QML | A real file-to-file import graph, no symbol-level claims || **Structural** (8) | R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only: blame, hotspots, co-change. No AST parsing |diff --git a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.pyindex ecdc23547..dba482f7b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py@@ -59,6 +59,11 @@ def member_name(node: Node) -> Node | None:prop = node.child_by_field_name(field_name)if prop is not None:return prop+ # Swift wraps the member in a ``navigation_suffix`` (``.name``), with the+ # name as that node's own ``suffix``.+ suffix = node.child_by_field_name("suffix")+ if suffix is not None and (inner := suffix.child_by_field_name("suffix")) is not None:+ return innernamed = [c for c in node.children if c.is_named]return next((c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)), None)@@ -143,6 +148,13 @@ def _find_name(node: Node) -> str:names = [c for c in grandchild.children if c.type == "identifier" and c.text]if names:return names[-1].text.decode("utf-8", errors="replace")+ # Swift: a computed property and a ``willSet`` / ``didSet`` block are named+ # for the property that holds them, a subscript's body ``subscript``, and+ # ``deinit`` has no name node at all.+ if node.type in _SWIFT_PROPERTY_UNITS:+ return _swift_property_name(node)+ if node.type == "deinit_declaration":+ return "deinit"# C / C++: the function name is not a direct child but nested inside a# ``declarator`` chain (``function_definition → function_declarator →# field_identifier``). Languages with a ``name`` field never reach here.@@ -162,6 +174,20 @@ def _find_name(node: Node) -> str:return "<anonymous>"+_SWIFT_PROPERTY_UNITS = frozenset({"computed_property", "willset_didset_block"})+++def _swift_property_name(unit: Node) -> str:+ holder = unit.parent+ if holder is None:+ return "<anonymous>"+ if holder.type == "subscript_declaration":+ return "subscript"+ name = holder.child_by_field_name("name")+ text = "".join((name.text or b"").decode("utf-8", errors="replace").split()) if name else ""+ return text or "<anonymous>"++def _node_text(node: Node) -> str:return (node.text or b"").decode("utf-8", errors="replace")@@ -394,7 +420,12 @@ def _count_parameters(fn_node: Node) -> int:"""params = _parameter_list(fn_node)if params is None:- return 0+ # Swift has no list node: each ``parameter`` is a child of the function,+ # and a subscript's are on the ``subscript_declaration`` around its body.+ holder = fn_node+ if fn_node.type == "computed_property" and fn_node.parent is not None:+ holder = fn_node.parent+ return sum(1 for child in holder.children if child.type == "parameter")count = 0receiver = _receiver_parameter(params)for child in params.children:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.pyindex 991b2da39..1f9d15b77 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py@@ -130,6 +130,12 @@ def _collect_class_body(body.methods.append(node)elif node.type in lmap.field_decl_kinds:body.field_decls.append(node)+ # A Swift property holds its own function units: a computed+ # property's body, a ``willSet`` / ``didSet`` block. They are+ # members like any method. The unit carries the property's name, so+ # a reference to it is a reference to a method, not to a field.+ units = [child for child in node.children if is_function_node(child, lmap)]+ body.methods.extend(u for u in units if _is_own_method(u, lmap, language, source))elif node.type not in lmap.nested_type_kinds:stack.extend(node.children)return body@@ -293,6 +299,10 @@ def _foreign_member_id(node: Node, lmap: LanguageNodeMap) -> int | None:obj, prop = member_object(node), member_name(node)if obj is None or prop is None or obj.id == prop.id:return None # a bare call (``id()``) has no receiver+ # The child of *node* that holds the name: the name itself, or the+ # wrapper around it (Swift's ``navigation_suffix``).+ while prop.parent is not None and prop.parent.id != node.id:+ prop = prop.parentreturn prop.iddiff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex ae55ee9f3..ebb2c1c1f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -78,6 +78,8 @@ _FLAT_BRANCH_KINDS = frozenset({"if_clause","guard",+ # Swift ``for x in xs where c`` / ``catch E where c``.+ "where_clause","if_modifier","unless_modifier","while_modifier",diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 4344c1d8b..444e34971 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -699,6 +699,59 @@ _KOTLIN = LanguageNodeMap(call_kinds=frozenset({"call_expression"}),)+# tree-sitter-swift names a struct, an enum, an extension and an actor+# ``class_declaration`` like a class, so one class kind covers them all; a+# ``protocol_declaration`` holds requirements with no bodies and is left out.+#+# A computed property is a function unit: ``computed_property`` holds either+# the bare getter's statements or its ``get`` / ``set`` accessors, and is also+# the body of a ``subscript``, which is why ``subscript_declaration`` is not a+# kind itself (the walk would stop at the nested one and count nothing).+# ``willSet`` / ``didSet`` are one unit the same way.+_SWIFT = LanguageNodeMap(+ function_kinds=frozenset(+ {+ "function_declaration",+ "init_declaration",+ "deinit_declaration",+ "computed_property",+ "willset_didset_block",+ }+ ),+ lambda_kinds=frozenset({"lambda_literal"}),+ # ``guard`` is a decision like ``if``: it has a condition and a path that+ # leaves. ``if let`` / ``guard let`` are the same nodes with a binding.+ # ``for x in xs where c`` and ``catch E where c`` filter with a+ # ``where_clause``: one more decision, no deeper nesting (a generic+ # constraint is a ``type_constraints`` node and is not one). A ``case ...+ # where c`` guard has no node of its own in this grammar and is not counted.+ branch_kinds=frozenset(+ {"if_statement", "guard_statement", "ternary_expression", "where_clause"}+ ),+ loop_kinds=frozenset({"for_statement", "while_statement", "repeat_while_statement"}),+ # ``do`` opens the guarded region and each ``catch`` is a path out of it.+ # ``try`` / ``try?`` / ``try!`` mark a call that can throw and ``defer``+ # schedules cleanup: neither is a decision.+ try_kinds=frozenset({"do_statement"}),+ catch_kinds=frozenset({"catch_block"}),+ switch_kinds=frozenset({"switch_statement"}),+ case_kinds=frozenset({"switch_entry"}),+ boolean_operator_kinds=frozenset({"conjunction_expression", "disjunction_expression"}),+ class_kinds=frozenset({"class_declaration"}),+ self_identifiers=frozenset({"self"}),+ member_access_kinds=frozenset({"navigation_expression"}),+ field_decl_kinds=frozenset({"property_declaration"}),+ identifier_kinds=frozenset({"simple_identifier"}),+ ctor_kinds=frozenset({"init_declaration"}),+ fixed_signature_markers=frozenset({"override"}),+ # No ``scalar_type_names``: a Swift ``parameter`` is a child of the function+ # with no list node around it, which ``typed_param_counts`` does not read+ # yet, so ``primitive_obsession`` has nothing to count here. No assertion+ # kinds either: XCTest has no vocabulary row, so the test-quality markers+ # do not read Swift.+ call_kinds=frozenset({"call_expression"}),+)+_DART = LanguageNodeMap(scalar_type_names=frozenset({"int", "double", "num", "bool", "String"}),# Dart splits a function into a ``function_signature`` node whose body is@@ -1319,6 +1372,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {"fsharp": _FSHARP,"objectivec": _OBJC,"php": _PHP,+ "swift": _SWIFT,}diff --git a/tests/fixtures/lang_samples/swift/classes.swift b/tests/fixtures/lang_samples/swift/classes.swiftnew file mode 100644index 000000000..af0994afd--- /dev/null+++ b/tests/fixtures/lang_samples/swift/classes.swift@@ -0,0 +1,52 @@+// Fixtures for class-level (LCOM4 / god-class) walker tests.+//+// Swift reaches instance members without a receiver idiomatically; these+// fixtures write `self.` so the member-access node type is exercised.++class Cohesive {+ var total = 0+ var count = 0++ func add(_ n: Int) {+ self.total += n+ self.count += 1+ }++ func average() -> Int {+ return self.count != 0 ? self.total / self.count : 0+ }++ func reset() {+ self.total = 0+ self.count = 0+ }++ func describe() -> Int {+ return self.count+ }+}++struct Splintered {+ var a = 0+ var b = 0++ mutating func setA(_ v: Int) {+ self.a = v+ }++ func getA() -> Int {+ return self.a+ }++ mutating func setB(_ v: Int) {+ self.b = v+ }++ func getB() -> Int {+ return self.b+ }++ func loner() -> Int {+ return 42+ }+}diff --git a/tests/fixtures/lang_samples/swift/nested.swift b/tests/fixtures/lang_samples/swift/nested.swiftnew file mode 100644index 000000000..29f0ef64a--- /dev/null+++ b/tests/fixtures/lang_samples/swift/nested.swift@@ -0,0 +1,28 @@+// Fixtures for nesting / cyclomatic-complexity walker tests.++func deeplyNested(_ x: Int) -> Int {+ if x > 0 {+ for i in 0..<x {+ while i > 0 {+ if i == 5 {+ return i+ }+ }+ }+ }+ return x+}++func shallow(_ x: Int) -> Int {+ return x + 1+}++func manyBranches(_ x: Int) -> Int {+ if x == 1 { return 1 }+ if x == 2 && x > 0 { return 2 }+ if x == 3 || x < 0 { return 3 }+ if x == 4 { return 4 }+ if x == 5 { return 5 }+ if x == 6 { return 6 }+ return x+}diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex 1291b6209..50f6b0fe0 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -552,6 +552,44 @@ def test_kotlin_assertion_blocks():assert few is not None and few.assertion_blocks == []+def test_swift_nesting_and_ccn():+ results = _walk("swift/nested.swift", "swift")+ deep = _find(results, "deeplyNested")+ assert deep is not None+ assert deep.max_nesting >= 4, f"expected ≥4 nesting, got {deep.max_nesting}"+ many = _find(results, "manyBranches")+ assert many is not None+ # 6 ifs + 2 boolean operators over the base path.+ assert many.ccn >= 9, f"expected CCN ≥ 9, got {many.ccn}"+ shallow = _find(results, "shallow")+ assert shallow is not None and shallow.max_nesting == 0+++def test_swift_scores_the_kotlin_fixture_s_twin_the_same():+ """``swift/nested.swift`` is ``kotlin/nested.kt`` line for line: the two+ maps must agree on every number the control flow gives."""+ swift = {r.name: (r.ccn, r.max_nesting, r.cognitive) for r in _walk("swift/nested.swift", "swift")}+ kotlin = {r.name: (r.ccn, r.max_nesting, r.cognitive) for r in _walk("kotlin/nested.kt", "kotlin")}+ assert swift == kotlin+ assert swift["deeplyNested"] == (5, 4, 10)+++def test_swift_class_cohesion():+ classes = _walk_classes("swift/classes.swift", "swift")+ cohesive = classes.get("Cohesive")+ splintered = classes.get("Splintered")+ assert cohesive is not None and splintered is not None+ assert (cohesive.lcom4, cohesive.method_count, cohesive.field_count) == (1, 4, 2)+ # A struct is a class kind too. Each cluster is an accessor pair over one+ # field and the loner touches none, as in the Kotlin fixture.+ assert (splintered.lcom4, splintered.method_count, splintered.field_count) == (1, 5, 2)+ # ``self.total`` is read as a use of the field: every pair of Cohesive's+ # methods shares one, and few of Splintered's do. Kotlin's twin agrees.+ kotlin = _walk_classes("kotlin/classes.kt", "kotlin")+ assert cohesive.tcc == kotlin["Cohesive"].tcc == 1.0+ assert splintered.tcc == kotlin["Splintered"].tcc < 0.5++def test_cpp_nesting_and_ccn():results = _walk("cpp/nested.cpp", "cpp")deep = _find(results, "deeplyNested")diff --git a/tests/unit/health/test_swift_complexity.py b/tests/unit/health/test_swift_complexity.pynew file mode 100644index 000000000..994d11a7f--- /dev/null+++ b/tests/unit/health/test_swift_complexity.py@@ -0,0 +1,470 @@+"""The Swift complexity map, one decision at a time (#3437).++Swift had no ``LanguageNodeMap``: ``walk_file`` returned no functions for a+Swift file and health could not score it. Each test here pins one counting+choice of the map. Where Kotlin has the same construct, the Kotlin twin is+walked beside it, so a difference between the two languages is a choice made+here and not an accident.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.complexity.languages import get_language_map, has_health_dialect+++def _walk(source: str, language: str = "swift"):+ try:+ from repowise.core.ingestion.parser import _get_language+ except Exception:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ if _get_language(language) is None:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ extension = {"swift": "swift", "kotlin": "kt"}[language]+ return walk_file(f"a.{extension}", language, source.encode())+++def _shape(source: str, language: str = "swift") -> dict[str, tuple[int, int]]:+ """``name -> (ccn, max_nesting)``."""+ return {f.name: (f.ccn, f.max_nesting) for f in _walk(source, language).functions}+++def _f(body: str, language: str = "swift") -> tuple[int, int]:+ """``(ccn, max_nesting)`` of a function ``f`` with *body*."""+ source = {+ "swift": f"func f(a: Int, b: Int, xs: [Int]) -> Int {{\n{body}\n return 0\n}}\n",+ "kotlin": f"fun f(a: Int, b: Int, xs: List<Int>): Int {{\n{body}\n return 0\n}}\n",+ }[language]+ return _shape(source, language)["f"]+++def test_swift_has_a_map():+ assert has_health_dialect("swift")+ assert get_language_map("swift") is not None+++def test_a_function_with_no_decisions():+ assert _f(" let c = a + b") == (1, 0)+++# -- branches -------------------------------------------------------------------+++ ("swift", "kotlin", "expected"),+ [+ pytest.param(" if a > 0 { return 1 }", " if (a > 0) { return 1 }", (2, 1), id="if"),+ pytest.param(+ " if a > 0 { return 1 } else { return 2 }",+ " if (a > 0) { return 1 } else { return 2 }",+ (2, 1),+ id="if-else",+ ),+ pytest.param(+ " if a > 0 { return 1 } else if a < 0 { return 2 } else { return 3 }",+ " if (a > 0) { return 1 } else if (a < 0) { return 2 } else { return 3 }",+ (3, 1),+ id="else-if-is-flat",+ ),+ pytest.param(+ " if a > 0 { if b > 0 { return 1 } }",+ " if (a > 0) { if (b > 0) { return 1 } }",+ (3, 2),+ id="nested-if",+ ),+ pytest.param(+ " if a > 0 && b > 0 || a < -1 { return 1 }",+ " if (a > 0 && b > 0 || a < -1) { return 1 }",+ (4, 1),+ id="and-or",+ ),+ pytest.param(+ " for x in xs { if x > 0 { return x } }",+ " for (x in xs) { if (x > 0) { return x } }",+ (3, 2),+ id="for",+ ),+ pytest.param(+ " while a > 0 { if b > 0 { return 1 } }",+ " while (a > 0) { if (b > 0) { return 1 } }",+ (3, 2),+ id="while",+ ),+ pytest.param(+ " repeat { if b > 0 { return 1 } } while a > 0",+ " do { if (b > 0) { return 1 } } while (a > 0)",+ (3, 2),+ id="repeat-while",+ ),+ ],+)+def test_swift_and_kotlin_agree(swift, kotlin, expected):+ assert _f(swift) == expected+ assert _f(kotlin, "kotlin") == expected+++def test_guard_is_a_decision():+ """It has a condition and a path that leaves, like an ``if``."""+ assert _f(" guard a > 0 else { return 1 }") == (2, 1)+ assert _f(" guard a > 0, b > 0 else { return 1 }") == (2, 1)+++def test_if_let_and_guard_let_are_the_same_decisions_with_a_binding():+ source = (+ "func f(a: Int?) -> Int {\n"+ " guard let x = a else { return 0 }\n"+ " if let y = a, y > x { return y }\n"+ " return x\n"+ "}\n"+ )++ assert _shape(source) == {"f": (3, 1)}+++def test_the_ternary_is_a_branch():+ assert _f(" let c = a > 0 ? 1 : 2") == (2, 1)+ # Each arm of a chain is a decision. How deep a chain nests is #3285's+ # question for every language outside TypeScript, so it is not pinned here.+ assert _f(" let c = a > 0 ? 1 : a < 0 ? -1 : 0")[0] == 3+++def test_nil_coalescing_is_not_a_decision():+ """As Kotlin's ``?:`` is not."""+ source = "func f(a: Int?, b: Int?) -> Int {\n let c = a ?? b ?? 0\n return c\n}\n"+ kotlin = "fun f(a: Int?, b: Int?): Int {\n val c = a ?: b ?: 0\n return c\n}\n"++ assert _shape(source) == {"f": (1, 0)}+ assert _shape(kotlin, "kotlin") == {"f": (1, 0)}+++# -- loops with a filter ----------------------------------------------------------+++def test_a_for_where_filter_is_one_more_decision_and_no_deeper():+ plain = _f(" for x in xs { if x > 0 { return x } }")+ filtered = _f(" for x in xs where x > 1 { if x > 0 { return x } }")++ assert plain == (3, 2)+ assert filtered == (4, 2)+ # The filter is beside the body, not around it: on its own it is level 1.+ assert _f(" for x in xs where x > 1 { use(x) }") == (3, 1)+++def test_a_generic_where_is_a_constraint_and_not_a_decision():+ source = (+ "func f<T>(x: T) -> Int where T: Equatable {\n return 0\n}\n"+ "extension Array where Element == Int {\n func g() -> Int { return 0 }\n}\n"+ )++ assert _shape(source) == {"f": (1, 0), "g": (1, 0)}+++# -- switch -----------------------------------------------------------------------+++def test_a_switch_with_simple_arms_is_one_decision():+ """The rule Kotlin's ``when`` follows: a flat dispatch counts once."""+ swift = (+ "func f(k: Int) -> Int {\n switch k {\n case 1: return 1\n case 2, 3: return 2\n"+ " default: return 0\n }\n}\n"+ )+ kotlin = (+ "fun f(k: Int): Int {\n when (k) {\n 1 -> return 1\n 2, 3 -> return 2\n"+ " else -> return 0\n }\n}\n"+ )++ assert _shape(swift) == {"f": (2, 1)}+ assert _shape(kotlin, "kotlin") == {"f": (2, 1)}+++def test_a_switch_whose_arms_branch_counts_each_arm():+ swift = (+ "func f(k: Int, a: Int) -> Int {\n switch k {\n"+ " case 1:\n if a > 0 { return 1 }\n return 2\n"+ " case 2:\n return 3\n"+ " default:\n return 0\n }\n}\n"+ )+ kotlin = (+ "fun f(k: Int, a: Int): Int {\n when (k) {\n"+ " 1 -> {\n if (a > 0) { return 1 }\n return 2\n }\n"+ " 2 -> return 3\n"+ " else -> return 0\n }\n}\n"+ )++ assert _shape(swift) == _shape(kotlin, "kotlin")+ assert _shape(swift)["f"][0] > 2+++def test_a_case_where_guard_is_not_counted():+ """This grammar gives the guard no node of its own."""+ plain = (+ "func f(k: K) -> Int {\n switch k {\n case .b(let n): return n\n default: return 0\n }\n}\n"+ )+ guarded = plain.replace("case .b(let n):", "case .b(let n) where n > 2:")++ assert _shape(guarded) == _shape(plain) == {"f": (2, 1)}+++# -- errors -----------------------------------------------------------------------+++def test_do_catch_counts_each_catch_and_do_opens_a_level():+ source = (+ "func f() -> Int {\n do {\n try g()\n } catch let e as NSError {\n return 1\n"+ " } catch {\n return 2\n }\n return 0\n}\n"+ )+ kotlin = (+ "fun f(): Int {\n try {\n g()\n } catch (e: IllegalStateException) {\n return 1\n"+ " } catch (e: Exception) {\n return 2\n }\n return 0\n}\n"+ )++ assert _shape(source) == {"f": (3, 2)}+ assert _shape(kotlin, "kotlin") == {"f": (3, 2)}+++def test_a_catch_where_filter_is_one_more_decision():+ plain = "func f() -> Int {\n do { try g() } catch E.x { return 1 }\n return 0\n}\n"+ filtered = plain.replace("catch E.x {", "catch E.x where c {")++ assert _shape(plain)["f"][0] + 1 == _shape(filtered)["f"][0]+++def test_try_marks_and_defer_are_not_decisions():+ source = (+ "func f() throws -> Int {\n defer { cleanup() }\n let a = try g()\n let b = try? g()\n"+ " let c = try! g()\n return a\n}\n"+ )++ assert _shape(source) == {"f": (1, 0)}+++def test_a_do_block_with_no_catch_opens_a_level_and_adds_no_path():+ assert _f(" do { if a > 0 { return 1 } }") == (2, 2)+++# -- what is a function -------------------------------------------------------------+++def test_init_deinit_subscript_and_properties_are_units():+ source = (+ "class C {\n"+ " var items: [Int] = []\n"+ " init(x: Int, y: Int) { if x > 0 { items = [y] } }\n"+ " deinit { if items.isEmpty { log() } }\n"+ " subscript(i: Int) -> Int { if i > 0 { return 1 }; return items[i] }\n"+ " var first: Int { get { if items.isEmpty { return 0 }; return items[0] } set { if newValue > 0 { items = [newValue] } } }\n"+ " var count: Int { return items.isEmpty ? 0 : items.count }\n"+ " var watched: Int = 0 { willSet { if newValue > 0 { log() } } didSet { log() } }\n"+ " func plain(a: Int, b: String) -> Int { return a }\n"+ "}\n"+ )++ functions = {f.name: f for f in _walk(source).functions}++ assert {name: (f.ccn, f.param_count) for name, f in functions.items()} == {+ "init": (2, 2),+ "deinit": (2, 0),+ "subscript": (2, 1),+ # ``get`` and ``set`` are one unit, the property's.+ "first": (3, 0),+ "count": (2, 0),+ "watched": (2, 0),+ "plain": (1, 2),+ }+ assert functions["init"].is_constructor+ assert not functions["plain"].is_constructor+ assert (functions["subscript"].start_line, functions["first"].start_line) == (5, 6)+++def test_a_stored_property_and_a_protocol_requirement_are_not_units():+ source = (+ "protocol Shape {\n func area() -> Double\n var name: String { get }\n}\n"+ "struct P {\n var x: Int = 0\n let y = 1\n}\n"+ )++ assert _walk(source).functions == []+++def test_a_closure_counts_toward_the_function_that_holds_it():+ """Like a Kotlin lambda."""+ source = (+ "func f(xs: [Int]) -> [Int] {\n"+ " let g = { (a: Int) -> Int in if a > 0 { return a }; return 0 }\n"+ " return xs.map { $0 > 1 ? $0 : 0 }\n"+ "}\n"+ )+ kotlin = (+ "fun f(xs: List<Int>): List<Int> {\n"+ " val g = { a: Int -> if (a > 0) a else 0 }\n"+ " return xs.map { if (it > 1) it else 0 }\n"+ "}\n"+ )++ assert _shape(source) == {"f": (3, 1)}+ assert _shape(kotlin, "kotlin") == {"f": (3, 1)}+++def test_a_nested_func_is_a_unit_of_its_own_and_a_closure_inside_it_is_its():+ """A function inside a function has its own row (#3281); the closure in+ ``inner`` counts toward ``inner``, not toward ``outer``."""+ source = (+ "func outer(xs: [Int]) -> Int {\n"+ " if xs.isEmpty { return 0 }\n"+ " func inner(q: Int) -> Int {\n"+ " let pick = { (a: Int) -> Int in a > 0 ? a : 0 }\n"+ " if q > 0 { return pick(q) }\n"+ " return 0\n"+ " }\n"+ " return inner(q: xs[0])\n"+ "}\n"+ )++ functions = {f.name: (f.ccn, f.max_nesting, f.param_count) for f in _walk(source).functions}++ assert functions == {"outer": (2, 1, 1), "inner": (3, 1, 1)}+++def test_a_local_type_s_members_are_units():+ source = (+ "func make() -> Int {\n"+ " struct Local {\n"+ " var n = 0\n"+ " var doubled: Int { return n > 0 ? n * 2 : 0 }\n"+ " func get() -> Int { if n > 0 { return n }; return 0 }\n"+ " }\n"+ " return Local().get()\n"+ "}\n"+ )++ walked = _walk(source)++ assert {f.name: f.ccn for f in walked.functions} == {"make": 1, "doubled": 2, "get": 2}+ assert [(c.name, c.method_count) for c in walked.classes] == [("Local", 2)]+++def test_a_closure_at_file_level_is_a_unit_of_its_own():+ """Nothing holds it, so it gets a row, as a Kotlin file-level lambda does."""+ source = "let handler = { (a: Int) -> Int in\n if a > 0 { return 1 }\n return 0\n}\n"+ kotlin = "val handler = { a: Int ->\n if (a > 0) 1 else 0\n}\n"++ assert _shape(source) == {"<anonymous@1>": (2, 1)}+ assert _shape(kotlin, "kotlin") == {"<anonymous@1>": (2, 1)}+++def test_an_override_has_a_fixed_signature():+ source = "class C: B {\n override func m(a: Int) -> Int { return a }\n func n(a: Int) -> Int { return a }\n}\n"++ fixed = {f.name: f.signature_fixed for f in _walk(source).functions}++ assert fixed == {"m": True, "n": False}+++# -- classes ------------------------------------------------------------------------+++def test_struct_enum_extension_and_actor_are_classes_and_a_protocol_is_not():+ source = (+ "class A {\n var n = 0\n func a() -> Int { return self.n }\n}\n"+ "struct S {\n var n = 0\n func s() -> Int { return self.n }\n}\n"+ "enum E {\n case one\n func e() -> Int { return 1 }\n}\n"+ "extension S {\n func x() -> Int { return self.n }\n}\n"+ "actor R {\n var n = 0\n func r() -> Int { return self.n }\n}\n"+ "protocol P {\n func p() -> Int\n}\n"+ )++ classes = sorted((c.name, c.start_line, c.method_count) for c in _walk(source).classes)++ assert classes == [("A", 1, 1), ("E", 9, 1), ("R", 16, 1), ("S", 5, 1), ("S", 13, 1)]+++def test_class_metrics_count_methods_and_stored_properties():+ source = (+ "class C {\n"+ " var items: [Int] = []\n"+ " let k = 1\n"+ " init(x: Int) { self.items = [x] }\n"+ " func a() -> Int { return self.items.count + self.k }\n"+ " func b() -> Int { return self.k }\n"+ "}\n"+ )++ (cls,) = _walk(source).classes++ assert (cls.name, cls.method_count, cls.field_count, cls.lcom4) == ("C", 3, 2, 1)+++def test_another_object_s_member_is_not_this_class_s_field():+ """``o.a`` names a member of ``o``. Read as the class's own ``a`` it would+ tie ``m2`` to ``m1``; the Kotlin twin keeps them apart the same way."""+ swift = (+ "class C {\n var a = 0\n var b = 0\n"+ " func m1() -> Int { return self.a }\n"+ " func m2(o: C) -> Int {\n let x = o.a\n return x + self.b\n }\n}\n"+ )+ kotlin = (+ "class C {\n var a = 0\n var b = 0\n"+ " fun m1(): Int { return this.a }\n"+ " fun m2(o: C): Int {\n val x = o.a\n return x + this.b\n }\n}\n"+ )++ (swift_class,) = _walk(swift).classes+ (kotlin_class,) = _walk(kotlin, "kotlin").classes++ assert swift_class.tcc == kotlin_class.tcc == 0.0+++def test_self_dot_member_and_a_bare_member_both_reach_the_field():+ source = (+ "class C {\n var a = 0\n"+ " func explicit() -> Int { return self.a }\n"+ " func implicit() -> Int { return a + 1 }\n}\n"+ )++ (cls,) = _walk(source).classes++ assert (cls.method_count, cls.field_count, cls.tcc) == (2, 1, 1.0)+++def test_a_property_s_units_are_members_of_its_class():+ """Every function row inside the class is one of its methods: a computed+ property, a ``get`` / ``set`` pair, a ``willSet`` / ``didSet`` block and a+ subscript beside ``init`` and the ``func``."""+ source = (+ "class C {\n"+ " var items: [Int] = []\n"+ " var watched: Int = 0 { willSet { if newValue > 0 { log() } } didSet { log() } }\n"+ " var total: Int { return items.count > 0 ? items[0] : 0 }\n"+ " var first: Int { get { return items[0] } set { items = [newValue] } }\n"+ " init(x: Int) { self.items = [x] }\n"+ " subscript(i: Int) -> Int { return items[i] }\n"+ " func a() -> Int { return total + watched }\n"+ "}\n"+ )++ walked = _walk(source)+ (cls,) = walked.classes++ rows = sorted(f.name for f in walked.functions)+ assert rows == ["a", "first", "init", "subscript", "total", "watched"]+ assert sorted(m.name for m in cls.methods) == rows+ assert cls.method_count == 6+ assert cls.max_method_ccn == 2+++def test_a_computed_property_is_not_counted_as_a_field():+ """It stores nothing. ``doubled`` reads the one stored property and ``m``+ calls ``doubled``: one field, and the two members are one component."""+ source = (+ "struct S {\n"+ " var n = 0\n"+ " var doubled: Int { return n * 2 }\n"+ " func m() -> Int { return doubled + 1 }\n"+ "}\n"+ )++ (cls,) = _walk(source).classes++ assert (cls.method_count, cls.field_count, cls.lcom4) == (2, 1, 1)+diff --git a/tests/unit/health/test_unanalysed_languages.py b/tests/unit/health/test_unanalysed_languages.pyindex b1390ea05..1fcea8a9b 100644--- a/tests/unit/health/test_unanalysed_languages.py+++ b/tests/unit/health/test_unanalysed_languages.py@@ -27,12 +27,14 @@ from repowise.core.analysis.health.trends import snapshot_fieldsfrom repowise.core.pipeline.incremental import _numbers_moved[email protected]("language", ["python", "typescript", "csharp", "razor", "sql", "php"])+ "language", ["python", "typescript", "csharp", "razor", "sql", "php", "swift"]+)def test_languages_health_walks_have_a_dialect(language: str) -> None:assert has_health_dialect(language)[email protected]("language", ["swift", "elixir", "markdown", "", None])[email protected]("language", ["lua", "elixir", "markdown", "", None])def test_languages_nothing_walks_have_none(language: str | None) -> None:assert not has_health_dialect(language)