From a37f7d1827f0f67eb397fc3935b511f8bb93f15d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:28:19 +0000 Subject: [PATCH 01/11] Compare Swift functions so renamed locals still match. A .swift file was not a source file, so a scan reported no candidates. .swift now selects the swift grammar, and a function with a body is a candidate form. Proved: test_renamed_locals_in_swift_functions_match failed with an empty report, then passed with one swift pair at score 1.0. The full suite passed, 81 tests. Co-authored-by: Robert C. Martin --- src/dryer/discover.py | 1 + src/dryer/extract.py | 9 +++++++++ tests/test_swift.py | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 tests/test_swift.py diff --git a/src/dryer/discover.py b/src/dryer/discover.py index 6feeaa7..b62cbfd 100644 --- a/src/dryer/discover.py +++ b/src/dryer/discover.py @@ -21,6 +21,7 @@ EXTENSIONS = { ".cts": "typescript", ".rs": "rust", ".py": "python", + ".swift": "swift", } SKIP_DIRS = { diff --git a/src/dryer/extract.py b/src/dryer/extract.py index 51f3160..b8a5a45 100644 --- a/src/dryer/extract.py +++ b/src/dryer/extract.py @@ -130,6 +130,14 @@ def _typescript_nodes(data: bytes, root) -> list: return found +def _swift_nodes(data: bytes, root) -> list: + found = [] + for node in descendants(root): + if node.type == "function_declaration" and _has(node, "function_body"): + found.append(node) + return found + + def _rust_nodes(data: bytes, root) -> list: found = [] for node in descendants(root): @@ -149,6 +157,7 @@ _PICKERS = { "python": ("python", _python_nodes), "typescript": (_grammar, _typescript_nodes), "rust": ("rust", _rust_nodes), + "swift": ("swift", _swift_nodes), } diff --git a/tests/test_swift.py b/tests/test_swift.py new file mode 100644 index 0000000..ceed466 --- /dev/null +++ b/tests/test_swift.py @@ -0,0 +1,40 @@ +from pathlib import Path + +from dryer.scan import find_duplicates, scan_files + + +def write_source(root: Path, name: str, text: str) -> None: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def pairs(root: Path): + files = sorted(path for path in root.rglob("*") if path.is_file()) + entries, warnings = scan_files(files, root, min_lines=1, min_nodes=1) + assert warnings == [] + return find_duplicates(entries, threshold=0.99) + + +SWIFT_LEFT = """\ +func alpha(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) +} +""" + +SWIFT_RIGHT = """\ +func beta(items: [Int]) -> [Int] { + let kept = filter(items, even) + return map(kept, dec) +} +""" + + +def test_renamed_locals_in_swift_functions_match(tmp_path): + write_source(tmp_path, "left.swift", SWIFT_LEFT) + write_source(tmp_path, "right.swift", SWIFT_RIGHT) + found = pairs(tmp_path) + assert [(item.language, item.left.file, item.right.file, item.score) for item in found] == [ + ("swift", "left.swift", "right.swift", 1.0) + ] From 16b5db55b2f79d08c83e917b5bf35e113fc2b392 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:28:45 +0000 Subject: [PATCH 02/11] Keep Swift call names so a different callee scores lower. Renamed locals already matched, and so did filter versus select, because a Swift call keeps its name in a call_suffix and the name is a simple_identifier. Both were treated as ordinary words, so the callee disappeared and the score stayed 1.0. simple_identifier is a name, and call_suffix is the argument list, the same two decisions the other languages already make. Proved: test_a_different_swift_callee_is_not_the_same_structure failed on a score of 1.0, then passed with the pair below 1.0. The renamed-local pair still scores 1.0. The full suite passed, 82 tests. Co-authored-by: Robert C. Martin --- src/dryer/astnorm.py | 3 ++- tests/test_swift.py | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/dryer/astnorm.py b/src/dryer/astnorm.py index 88f7582..b86d8c6 100644 --- a/src/dryer/astnorm.py +++ b/src/dryer/astnorm.py @@ -28,6 +28,7 @@ _IDENTIFIERS = { "shorthand_property_identifier", "shorthand_property_identifier_pattern", "package_identifier", + "simple_identifier", } _LITERALS = { @@ -134,7 +135,7 @@ _SCOPED = { "scoped_type_identifier", } -_ARG_LISTS = {"argument_list", "arguments"} +_ARG_LISTS = {"argument_list", "arguments", "call_suffix"} _TYPE_ARGS = {"type_arguments", "type_parameters"} _DATA: bytes = b"" diff --git a/tests/test_swift.py b/tests/test_swift.py index ceed466..51f006c 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -38,3 +38,23 @@ def test_renamed_locals_in_swift_functions_match(tmp_path): assert [(item.language, item.left.file, item.right.file, item.score) for item in found] == [ ("swift", "left.swift", "right.swift", 1.0) ] + + +def test_a_different_swift_callee_is_not_the_same_structure(tmp_path): + write_source(tmp_path, "left.swift", SWIFT_LEFT) + write_source( + tmp_path, + "right.swift", + """\ +func beta(items: [Int]) -> [Int] { + let kept = select(items, even) + return collect(kept, dec) +} +""", + ) + files = sorted(tmp_path.glob("*.swift")) + entries, warnings = scan_files(files, tmp_path, min_lines=1, min_nodes=1) + assert warnings == [] + found = find_duplicates(entries, threshold=0.0) + assert len(found) == 1 + assert found[0].score < 1.0 From 41384b723d86166847524e1ca3bcb2f8682eb90c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:35:30 +0000 Subject: [PATCH 03/11] Normalize Swift members, operators, labels, and literals. Call names were kept, and everything else in a Swift expression was still a generic word. filter matched select, >= matched !=, an argument label disappeared, and a string did not match a number. A navigation_expression is an attribute, so the called member stays and the field name does not. A custom operator and an argument label keep their spelling. Swift strings, nil, and real numbers are literals, an interpolation is not, and a block comment is skipped. Proved: the Swift tests for methods, operators, labels, literals, comments, and tuple indexes pass, and the other languages still pass. 92 tests. Co-authored-by: Robert C. Martin --- src/dryer/astnorm.py | 44 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/dryer/astnorm.py b/src/dryer/astnorm.py index b86d8c6..b5891c0 100644 --- a/src/dryer/astnorm.py +++ b/src/dryer/astnorm.py @@ -18,6 +18,7 @@ _SKIP = { "block_comment", "documentation_comment", "doc_comment", + "multiline_comment", } _IDENTIFIERS = { @@ -63,6 +64,10 @@ _LITERALS = { "template_string", "regex", "regex_literal", + "line_string_literal", + "multi_line_string_literal", + "nil_literal", + "real_literal", } _OPERATORS = { @@ -128,8 +133,14 @@ _ATTRIBUTES = { "selector_expression", "field_access", "field_expression", + "navigation_expression", } +# The spelling is the structure: Swift spells >= as custom_operator, and an +# argument label is part of the call name. +_TEXT_SYMBOLS = {"custom_operator", "value_argument_label"} +_INTERPOLATED = {"interpolation", "interpolated_expression"} + _SCOPED = { "scoped_identifier", "scoped_type_identifier", @@ -159,9 +170,7 @@ _PENDING = object() def _is_literal(node) -> bool: if node.type not in _LITERALS: return False - if node.type == "string" and any(child.type == "interpolation" for child in node.children): - return False - return True + return not any(child.type in _INTERPOLATED for child in node.children) def _named_before_args(node): @@ -204,6 +213,8 @@ def _try_leaf(node, mode: str, head: bool): return None if node.type in _OPERATORS: return [K("symbol"), node.type] + if node.type in _TEXT_SYMBOLS: + return [K("symbol"), _text(node)] if not node.is_named: return None return _named_leaf(node, head) @@ -223,11 +234,29 @@ def _call_jobs(node): return jobs -def _attr_jobs(node, head: bool): +def _member_name(node): + """Swift wraps the member in navigation_suffix. The name inside is the member.""" + + if node.type != "navigation_suffix": + return node + for child in node.named_children: + if child.type in _IDENTIFIERS: + return child + return node + + +def _attr_ends(node): named = list(node.named_children) if not named: - return [] + return [], None *objects, name = named + return objects, _member_name(name) + + +def _attr_jobs(node, head: bool): + objects, name = _attr_ends(node) + if name is None: + return [] jobs = [(obj, "norm", False) for obj in objects] if name.type in _IDENTIFIERS: return jobs @@ -307,10 +336,9 @@ def _assemble_call(node, cache): def _assemble_attr(node, head: bool, cache): - named = list(node.named_children) - if not named: + objects, name = _attr_ends(node) + if name is None: return [K(node.type)] - *objects, name = named parts = [K(node.type)] for obj in objects: norm = cache[(id(obj), "norm", False)] From ae380876446672d41a5212d473f307bbe1d9bb1b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:31:18 +0000 Subject: [PATCH 04/11] Select Swift methods, view bodies, and top-level closures. A SwiftUI body is a computed property, a protocol requirement has no body, and a closure or local function belongs to the form around it. The first picker kept every function, including the nested ones, and missed the body, the protocol default, and a file-level closure. Proved: test_swift_keeps_methods_bodies_and_top_level_closures_only failed by reporting the nested function at lines 7-9. The SwiftUI pair and the top-level closure pair were empty. All three pass, including a Text versus Label view that scores below 1.0. The full suite passed, 90 tests, and dryer reports no duplication at 0.8. Co-authored-by: Robert C. Martin --- src/dryer/extract.py | 24 ++++- tests/test_swift.py | 252 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 275 insertions(+), 1 deletion(-) diff --git a/src/dryer/extract.py b/src/dryer/extract.py index b8a5a45..5ba5a90 100644 --- a/src/dryer/extract.py +++ b/src/dryer/extract.py @@ -130,10 +130,32 @@ def _typescript_nodes(data: bytes, root) -> list: return found +# A closure, a local function, and a function written inside a view body stay +# inside the form that contains them. A protocol requirement has no body. +_SWIFT_NEST = { + "function_declaration", + "protocol_function_declaration", + "lambda_literal", + "computed_property", + "init_declaration", + "subscript_declaration", +} + + +def _swift_property(node) -> bool: + return node.type == "property_declaration" and _has(node, "computed_property", "lambda_literal") + + def _swift_nodes(data: bytes, root) -> list: found = [] for node in descendants(root): - if node.type == "function_declaration" and _has(node, "function_body"): + if _inside(node, _SWIFT_NEST): + continue + if node.type == "function_declaration": + found.append(node) + elif node.type == "protocol_function_declaration" and _has(node, "statements"): + found.append(node) + elif _swift_property(node): found.append(node) return found diff --git a/tests/test_swift.py b/tests/test_swift.py index 51f006c..16ad415 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -1,5 +1,6 @@ from pathlib import Path +from dryer.extract import entries_in_source from dryer.scan import find_duplicates, scan_files @@ -58,3 +59,254 @@ func beta(items: [Int]) -> [Int] { found = find_duplicates(entries, threshold=0.0) assert len(found) == 1 assert found[0].score < 1.0 + + +def _scored(tmp_path, left: str, right: str) -> float: + write_source(tmp_path, "left.swift", left) + write_source(tmp_path, "right.swift", right) + files = sorted(tmp_path.glob("*.swift")) + entries, warnings = scan_files(files, tmp_path, min_lines=1, min_nodes=1) + assert warnings == [] + found = find_duplicates(entries, threshold=0.0) + assert len(found) == 1 + return found[0].score + + +def test_a_swift_method_name_stays_and_the_field_name_does_not(tmp_path): + assert _scored( + tmp_path, + "func alpha(xs: Order) -> Int {\n return xs.total\n}\n", + "func beta(items: Order) -> Int {\n return items.count\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Order) -> [Int] {\n return xs.filter(odd)\n}\n", + "func beta(items: Order) -> [Int] {\n return items.select(even)\n}\n", + ) < 1.0 + assert _scored( + tmp_path, + "func alpha(pair: (Int, Int)) -> Int {\n return pair.0\n}\n", + "func beta(pair: (Int, Int)) -> Int {\n return pair.1\n}\n", + ) == 1.0 + + +def test_a_different_swift_operator_lowers_the_score(tmp_path): + assert _scored( + tmp_path, + "func alpha(xs: Int) -> Bool {\n return xs >= 1\n}\n", + "func beta(items: Int) -> Bool {\n return items >= 2\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Int) -> Bool {\n return xs >= 1\n}\n", + "func beta(items: Int) -> Bool {\n return items != 1\n}\n", + ) < 1.0 + + +def test_a_swift_argument_label_is_part_of_the_call(tmp_path): + assert _scored( + tmp_path, + "func alpha(xs: [Int]) -> [Int] {\n return move(from: xs, to: xs)\n}\n", + "func beta(items: [Int]) -> [Int] {\n return move(from: items, to: items)\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: [Int]) -> [Int] {\n return move(from: xs, to: xs)\n}\n", + "func beta(items: [Int]) -> [Int] {\n return move(start: items, end: items)\n}\n", + ) < 1.0 + + +def test_swift_literals_normalize_and_interpolation_does_not(tmp_path): + assert _scored( + tmp_path, + 'func alpha() -> String {\n return "Save"\n}\n', + "func beta() -> Int {\n return 1\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha() -> Int {\n return nil\n}\n", + "func beta() -> Double {\n return 1.5\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + 'func alpha() -> String {\n return """\n hello\n """\n}\n', + "func beta() -> Int {\n return 0\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + 'func alpha(name: String) -> String {\n return "Hello \\(name)"\n}\n', + 'func beta() -> String {\n return "Hello"\n}\n', + ) < 1.0 + + +def test_a_swift_comment_is_not_part_of_the_structure(tmp_path): + commented = """\ +func alpha(xs: [Int]) -> [Int] { + // keep the odds + /* and this */ + let ys = filter(xs, odd) + return map(ys, inc) +} +""" + assert _scored(tmp_path, commented, SWIFT_RIGHT) == 1.0 + + +APP = """\ +import SwiftUI + +struct InvoiceView: View { + var title: String + + var body: some View { + func hidden() -> Int { + return count() + } + VStack { + Text(title) + Button(action: { save() }) { + Text("Save") + } + } + } + + func refresh(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) + } +} + +class Panel { + init(xs: [Int]) { + self.items = filter(xs, odd) + self.kept = map(xs, inc) + } + + func beta(items: [Int]) -> [Int] { + let kept = filter(items, even) + return map(kept, dec) + } +} + +extension Board { + func gamma(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) + } +} + +enum Status { + case open + case closed + + func label(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) + } +} + +protocol Saving { + func save(order: Order) + + func load(id: Int) -> Order { + return cache(id) + } +} + +func outer(xs: [Int]) -> [Int] { + func inner(ys: [Int]) -> [Int] { + let kept = filter(ys, odd) + return map(kept, inc) + } + let closure = { (zs: [Int]) -> [Int] in + let kept = filter(zs, even) + return map(kept, dec) + } + return inner(xs) +} + +let alpha = { (xs: [Int]) -> [Int] in + func inner(ys: [Int]) -> [Int] { + let kept = filter(ys, odd) + return map(kept, inc) + } + return inner(xs) +} +""" + +INVOICE = """\ +struct InvoiceView: View { + var title: String + var body: some View { + VStack { + Text(title) + Button(action: { save() }) { + Text("Save") + } + } + } +} +""" + +RECEIPT = """\ +struct ReceiptView: View { + var heading: String + var body: some View { + VStack { + Text(heading) + Button(action: { save() }) { + Text("Done") + } + } + } +} +""" + +LABEL_VIEW = """\ +struct LabelView: View { + var heading: String + var body: some View { + VStack { + Label(heading) + Button(action: { save() }) { + Text("Done") + } + } + } +} +""" + + +def test_swift_keeps_methods_bodies_and_top_level_closures_only(): + entries, warning = entries_in_source("swift", APP, "App.swift", "App.swift") + assert warning is None + assert [(entry.start_line, entry.end_line) for entry in entries] == [ + (6, 16), + (18, 21), + (30, 33), + (37, 40), + (47, 50), + (56, 58), + (61, 71), + (73, 79), + ] + + +def test_swiftui_views_match_when_only_the_data_changes(tmp_path): + assert _scored(tmp_path, INVOICE, RECEIPT) == 1.0 + assert _scored(tmp_path, RECEIPT, LABEL_VIEW) < 1.0 + + +def test_a_top_level_swift_closure_matches_its_renamed_copy(tmp_path): + left = """\ +let alpha = { (xs: [Int]) -> [Int] in + let ys = filter(xs, odd) + return map(ys, inc) +} +""" + right = """\ +let beta = { (items: [Int]) -> [Int] in + let kept = filter(items, even) + return map(kept, dec) +} +""" + assert _scored(tmp_path, left, right) == 1.0 From f667ad03ba948871005112a7fe4262f80009a23f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:31:38 +0000 Subject: [PATCH 05/11] Skip Swift test files the way the other languages skip theirs. A Swift package keeps tests in Tests/ and names them *Tests.swift. Both were scanned as production code, so test helpers showed up as duplicate candidates. The suffix checks were one list already in spirit. Tests.swift joins that list, and Tests joins the skipped directories. Folding the old suffix branches into the list keeps the decision in one place. Proved: test_a_swift_package_skips_its_tests failed while reporting Sources/HiddenTests.swift and Tests/AppTests.swift, then passed with only Sources/App.swift. The existing test-name suite still passed. 91 tests. Co-authored-by: Robert C. Martin --- src/dryer/discover.py | 43 +++++++++++++++++++++++-------------------- tests/test_swift.py | 11 +++++++++++ 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/src/dryer/discover.py b/src/dryer/discover.py index b62cbfd..d2f0442 100644 --- a/src/dryer/discover.py +++ b/src/dryer/discover.py @@ -44,7 +44,27 @@ SKIP_DIRS = { ".clj-kondo", } -TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__"} +TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__", "Tests"} + +# One suffix list. Swift packages name XCTest files *Tests.swift. +_TEST_SUFFIXES = ( + "_test.go", + "_test.clj", + "_test.cljc", + "_test.cljs", + "_test.cljd", + "_test.bb", + ".test.ts", + ".spec.ts", + ".test.tsx", + ".spec.tsx", + ".test.mts", + ".spec.mts", + ".test.cts", + ".spec.cts", + "_test.py", + "Tests.swift", +) def language_of(path: str | Path) -> str | None: @@ -58,26 +78,9 @@ def language_of(path: str | Path) -> str | None: def is_test_file(path: str | Path) -> bool: file_path = Path(path) name = file_path.name - if name.endswith("_test.go"): + if name == "conftest.py" or name.endswith(_TEST_SUFFIXES): return True - if name.endswith(("_test.clj", "_test.cljc", "_test.cljs", "_test.cljd", "_test.bb")): - return True - if name.endswith( - ( - ".test.ts", - ".spec.ts", - ".test.tsx", - ".spec.tsx", - ".test.mts", - ".spec.mts", - ".test.cts", - ".spec.cts", - ) - ): - return True - if name == "conftest.py": - return True - if name.endswith("_test.py") or (name.startswith("test_") and name.endswith(".py")): + if name.startswith("test_") and name.endswith(".py"): return True return any(part in TEST_DIRS for part in file_path.parts) diff --git a/tests/test_swift.py b/tests/test_swift.py index 16ad415..d85aa4b 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -1,5 +1,6 @@ from pathlib import Path +from dryer.discover import iter_source_files, language_of from dryer.extract import entries_in_source from dryer.scan import find_duplicates, scan_files @@ -296,6 +297,16 @@ def test_swiftui_views_match_when_only_the_data_changes(tmp_path): assert _scored(tmp_path, RECEIPT, LABEL_VIEW) < 1.0 +def test_a_swift_package_skips_its_tests(tmp_path): + body = "func alpha() -> Int {\n return 1\n}\n" + write_source(tmp_path, "Sources/App.swift", body) + write_source(tmp_path, "Tests/AppTests.swift", body) + write_source(tmp_path, "Sources/HiddenTests.swift", body) + relative = [path.relative_to(tmp_path).as_posix() for path in iter_source_files([tmp_path])] + assert language_of("Sources/App.swift") == "swift" + assert relative == ["Sources/App.swift"] + + def test_a_top_level_swift_closure_matches_its_renamed_copy(tmp_path): left = """\ let alpha = { (xs: [Int]) -> [Int] in From 1bb1936ad54e3cc7c3cff90c2c22bceb101a2a7d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:32:22 +0000 Subject: [PATCH 06/11] Document Swift as a supported language. The scan already reports Swift pairs in the text report and in .metrics/dry.edn. The help text, the language table, and the project description still listed the previous six languages. Proved: test_help_does_not_scan failed until the help named Swift (.swift) and *Tests.swift, then passed. test_swift_report_writes_the_same_snapshot checks the text lines and :language \"swift\" in dry.edn. The shared language tests now include Swift. 92 tests passed. Co-authored-by: Robert C. Martin --- README.md | 14 ++++++++++++-- pyproject.toml | 2 +- src/dryer/__init__.py | 2 +- src/dryer/cli.py | 18 ++++++++++-------- src/dryer/discover.py | 2 +- src/dryer/extract.py | 3 ++- tests/test_cli.py | 2 ++ tests/test_languages.py | 37 ++++++++++++++++++++++++++++++++++--- tests/test_swift.py | 15 +++++++++++++++ 9 files changed, 78 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index fae6e64..12de678 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # dryer -dryer finds candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, and Python. One run detects the language of each source file, normalizes that language's forms, and reports pairs whose structure is close enough to review. +dryer finds candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, Python, and Swift. One run detects the language of each source file, normalizes that language's forms, and reports pairs whose structure is close enough to review. -Clojure follows [dry4clj](https://github.com/unclebob/dry4clj). The other languages use the same idea on the functions and methods [crapper](https://github.com/unclebob/crapper) and [mutator](https://github.com/unclebob/mutator) already treat as one unit. A form is only compared with forms written in the same language. +Clojure follows [dry4clj](https://github.com/unclebob/dry4clj). Java, Go, TypeScript, Rust, and Python use the same idea on the functions and methods [crapper](https://github.com/unclebob/crapper) and [mutator](https://github.com/unclebob/mutator) already treat as one unit. Swift uses that same unit. A form is only compared with forms written in the same language. The score is Jaccard similarity of structural fingerprints: @@ -39,6 +39,13 @@ def beta(items): return map(kept, dec) ``` +```swift +func alpha(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) +} +``` + What stays is the call or method name, the operator, and the shape of the tree. What drops out is the local name, the field name, the literal, and the keyword. A Clojure keyword call `(:kind m)` and `(:id row)` is the same shape. So is `order.total` and `row.amount`. ## Run @@ -101,6 +108,9 @@ DUPLICATE score=0.89 | TypeScript | functions, methods, and top-level arrow functions | callbacks nested inside another function | | Rust | functions and methods with a body | functions inside `mod tests`, and closures | | Python | functions and methods | functions nested inside another function | +| Swift | functions and methods with a body, computed properties, and file-level closures | initializers, subscripts, protocol requirements, and closures or functions nested inside another form | + +A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, because in Swift they are part of the call. `>=` and `!=` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. Clojure reader conditionals keep the `:clj` branch, as dry4clj does. Syntax-quote is kept as a `syntax-quote` form rather than expanded. diff --git a/pyproject.toml b/pyproject.toml index 645115a..829119b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "dryer" version = "0.1.0" -description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, and Python." +description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, Python, and Swift." readme = "README.md" license = { file = "LICENSE" } classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"] diff --git a/src/dryer/__init__.py b/src/dryer/__init__.py index 3591c90..5c72edf 100644 --- a/src/dryer/__init__.py +++ b/src/dryer/__init__.py @@ -1,3 +1,3 @@ -"""Find structural duplicates in Clojure, Java, Go, TypeScript, Rust, and Python.""" +"""Find structural duplicates in Clojure, Java, Go, TypeScript, Rust, Python, and Swift.""" __version__ = "0.1.0" diff --git a/src/dryer/cli.py b/src/dryer/cli.py index 288754d..c98438b 100644 --- a/src/dryer/cli.py +++ b/src/dryer/cli.py @@ -21,16 +21,16 @@ def _skipped_directory_text() -> str: HELP = f"""\ Usage: dryer [options] [path-or-filter ...] -Find candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, and -Python. Each form is normalized — call and method names, operators, and -tree shape stay; local names, field names, and literals do not — and compared -with the other forms of the same language. The score is Jaccard similarity of -those structural fingerprints, the same score as dry4clj. +Find candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, +Python, and Swift. Each form is normalized — call and method names, operators, +and tree shape stay; local names, field names, and literals do not — and +compared with the other forms of the same language. The score is Jaccard +similarity of those structural fingerprints, the same score as dry4clj. Prints a report and writes .metrics/dry.edn. Languages: Clojure (.clj .cljc .cljs .cljd .bb), Java (.java), Go (.go), -TypeScript (.ts .tsx .mts .cts), Rust (.rs), Python (.py). +TypeScript (.ts .tsx .mts .cts), Rust (.rs), Python (.py), Swift (.swift). Options: -h, --help Print this help and exit. @@ -56,10 +56,12 @@ Arguments: With no paths, source files under the project root are compared. Directories named {_skipped_directory_text()} are skipped, as are *_test.go, *.test.cts, -*.spec.cts, *.spec.ts, test_*.py, and *_test.py files. +*.spec.cts, *.spec.ts, test_*.py, *_test.py, and *Tests.swift files. Clojure compares every top-level form except ns. The other languages compare -functions and methods. A form is only compared with forms in the same language. +functions and methods. Swift also compares computed properties, including a +SwiftUI view body, and a closure bound at file scope. A form is only compared +with forms in the same language. Exit codes: 0 the report was written diff --git a/src/dryer/discover.py b/src/dryer/discover.py index d2f0442..a1ef4c3 100644 --- a/src/dryer/discover.py +++ b/src/dryer/discover.py @@ -1,7 +1,7 @@ """Find source files and decide which language each one is written in. The extensions and the skipped directories match crapper and mutator, with -`.cljd` added because dry4clj reads it. +`.cljd` added because dry4clj reads it and `.swift` added for Swift. """ import os diff --git a/src/dryer/extract.py b/src/dryer/extract.py index 5ba5a90..0357638 100644 --- a/src/dryer/extract.py +++ b/src/dryer/extract.py @@ -3,7 +3,8 @@ Clojure compares every top-level list except `ns`, matching dry4clj. The other languages compare the functions and methods crapper scores: bodies, not signatures alone, and not callbacks nested inside another function. Rust -functions inside `mod tests` are test code and are skipped. +functions inside `mod tests` are test code and are skipped. Swift also +compares computed properties and a closure bound at file scope. """ from __future__ import annotations diff --git a/tests/test_cli.py b/tests/test_cli.py index 7a6875d..a17e20f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -40,6 +40,8 @@ def test_help_does_not_scan(capsys): assert "Usage: dryer" in out assert "__pycache__" in out assert ".test.cts" in out + assert "Swift (.swift)" in out + assert "*Tests.swift" in out assert "--threshold" in out diff --git a/tests/test_languages.py b/tests/test_languages.py index 1710cf8..18be0a1 100644 --- a/tests/test_languages.py +++ b/tests/test_languages.py @@ -126,6 +126,18 @@ def test_each_language_matches_renamed_locals(tmp_path): "right.tsx": TSX_RIGHT, "left.rs": RUST_LEFT, "right.rs": RUST_RIGHT, + "left.swift": """\ +func alpha(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) +} +""", + "right.swift": """\ +func beta(items: [Int]) -> [Int] { + let kept = filter(items, even) + return map(kept, dec) +} +""", } for name, source in samples.items(): write_source(tmp_path, name, source) @@ -133,7 +145,7 @@ def test_each_language_matches_renamed_locals(tmp_path): by_language = {} for item in found: by_language.setdefault(item.language, []).append(item) - assert set(by_language) == {"java", "go", "python", "typescript", "rust"} + assert set(by_language) == {"java", "go", "python", "typescript", "rust", "swift"} assert [(item.left.file, item.right.file) for item in by_language["typescript"]] == [ ("left.ts", "right.ts"), ("left.tsx", "right.tsx"), @@ -237,7 +249,14 @@ class Right { def _suffix(language: str) -> str: - return {"python": "py", "go": "go", "rust": "rs", "java": "java", "typescript": "ts"}[language] + return { + "python": "py", + "go": "go", + "rust": "rs", + "java": "java", + "typescript": "ts", + "swift": "swift", + }[language] def test_callee_names_stay_and_member_names_do_not(tmp_path): @@ -307,6 +326,18 @@ export function alpha(xs: number[]): number { export function beta(items: number[]): number { return foo(items.baz); } +""", + "left.swift": """\ +func alpha(xs: Order) -> Int { + let ys = xs.filter(odd) + return xs.total +} +""", + "right.swift": """\ +func beta(items: Order) -> Int { + let kept = items.filter(even) + return items.count +} """, } for name, source in samples.items(): @@ -315,7 +346,7 @@ export function beta(items: number[]): number { by_language = {} for item in found: by_language.setdefault(item.language, []).append(item) - assert set(by_language) == {"python", "go", "rust", "java", "typescript"} + assert set(by_language) == {"python", "go", "rust", "java", "typescript", "swift"} for language, group in by_language.items(): assert [(item.left.file, item.right.file, item.score) for item in group] == [ (f"left.{_suffix(language)}", f"right.{_suffix(language)}", 1.0) diff --git a/tests/test_swift.py b/tests/test_swift.py index d85aa4b..8e97692 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -1,5 +1,6 @@ from pathlib import Path +from dryer.cli import run from dryer.discover import iter_source_files, language_of from dryer.extract import entries_in_source from dryer.scan import find_duplicates, scan_files @@ -297,6 +298,20 @@ def test_swiftui_views_match_when_only_the_data_changes(tmp_path): assert _scored(tmp_path, RECEIPT, LABEL_VIEW) < 1.0 +def test_swift_report_writes_the_same_snapshot(tmp_path, capsys): + write_source(tmp_path, "left.swift", SWIFT_LEFT) + write_source(tmp_path, "right.swift", SWIFT_RIGHT) + assert run(["--root", str(tmp_path)]) == 0 + captured = capsys.readouterr() + assert "DUPLICATE score=1.00" in captured.out + assert "left.swift:1-4" in captured.out + assert "right.swift:1-4" in captured.out + text = (tmp_path / ".metrics" / "dry.edn").read_text(encoding="utf-8") + assert ':language "swift"' in text + assert ':file "left.swift"' in text + assert "Wrote" in captured.err + + def test_a_swift_package_skips_its_tests(tmp_path): body = "func alpha() -> Int {\n return 1\n}\n" write_source(tmp_path, "Sources/App.swift", body) From 121fb2f4ba60db3db671612f05cad2aa63165745 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:49:25 +0000 Subject: [PATCH 07/11] Keep Swift range operators in the fingerprint. ..< and ... were dropped as punctuation, so a half-open range and a closed range scored 1.0. They now stay, as >= and != do. Proved by test_a_different_swift_range_lowers_the_score. The suite is 93 passed. Co-authored-by: Robert C. Martin --- README.md | 2 +- src/dryer/astnorm.py | 2 ++ tests/test_swift.py | 13 +++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 12de678..26e7901 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ DUPLICATE score=0.89 | Python | functions and methods | functions nested inside another function | | Swift | functions and methods with a body, computed properties, and file-level closures | initializers, subscripts, protocol requirements, and closures or functions nested inside another form | -A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, because in Swift they are part of the call. `>=` and `!=` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. +A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. Clojure reader conditionals keep the `:clj` branch, as dry4clj does. Syntax-quote is kept as a `syntax-quote` form rather than expanded. diff --git a/src/dryer/astnorm.py b/src/dryer/astnorm.py index b5891c0..d7b863f 100644 --- a/src/dryer/astnorm.py +++ b/src/dryer/astnorm.py @@ -117,6 +117,8 @@ _OPERATORS = { ":=", "=>", "?", + "...", + "..<", } _CALLS = { diff --git a/tests/test_swift.py b/tests/test_swift.py index 8e97692..9dd633b 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -105,6 +105,19 @@ def test_a_different_swift_operator_lowers_the_score(tmp_path): ) < 1.0 +def test_a_different_swift_range_lowers_the_score(tmp_path): + assert _scored( + tmp_path, + "func alpha(xs: Int) -> Bool {\n return xs..<1\n}\n", + "func beta(items: Int) -> Bool {\n return items..<2\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Int) -> Bool {\n return xs..<1\n}\n", + "func beta(items: Int) -> Bool {\n return items...1\n}\n", + ) < 1.0 + + def test_a_swift_argument_label_is_part_of_the_call(tmp_path): assert _scored( tmp_path, From 105ff6f50ce276d10fdd69550c18cc0a3267f442 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:49:45 +0000 Subject: [PATCH 08/11] Keep the label on a Swift trailing closure. The grammar puts that label on the call as an identifier, so label: and action: scored 1.0. The spelling now stays, as a parenthesized argument label does. A closure body still drops its locals. Proved by test_a_trailing_closure_label_is_part_of_the_call. Co-authored-by: Robert C. Martin --- README.md | 2 +- src/dryer/astnorm.py | 12 ++++++++++-- tests/test_swift.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 26e7901..feedb47 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ DUPLICATE score=0.89 | Python | functions and methods | functions nested inside another function | | Swift | functions and methods with a body, computed properties, and file-level closures | initializers, subscripts, protocol requirements, and closures or functions nested inside another form | -A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. +A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, including the label of a trailing closure, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. Clojure reader conditionals keep the `:clj` branch, as dry4clj does. Syntax-quote is kept as a `syntax-quote` form rather than expanded. diff --git a/src/dryer/astnorm.py b/src/dryer/astnorm.py index d7b863f..50311df 100644 --- a/src/dryer/astnorm.py +++ b/src/dryer/astnorm.py @@ -139,7 +139,8 @@ _ATTRIBUTES = { } # The spelling is the structure: Swift spells >= as custom_operator, and an -# argument label is part of the call name. +# argument label is part of the call name. A trailing closure's label is an +# identifier placed directly on the call_suffix, not a value_argument_label. _TEXT_SYMBOLS = {"custom_operator", "value_argument_label"} _INTERPOLATED = {"interpolation", "interpolated_expression"} @@ -206,6 +207,13 @@ def _named_leaf(node, head: bool): return _PENDING +def _trailing_label(node) -> bool: + """A trailing-closure label sits on the call, so its spelling stays.""" + + parent = node.parent + return parent is not None and parent.type == "call_suffix" and node.type in _IDENTIFIERS + + def _try_leaf(node, mode: str, head: bool): if mode == "callee": return _callee_leaf(node) @@ -215,7 +223,7 @@ def _try_leaf(node, mode: str, head: bool): return None if node.type in _OPERATORS: return [K("symbol"), node.type] - if node.type in _TEXT_SYMBOLS: + if node.type in _TEXT_SYMBOLS or _trailing_label(node): return [K("symbol"), _text(node)] if not node.is_named: return None diff --git a/tests/test_swift.py b/tests/test_swift.py index 9dd633b..700a1ca 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -131,6 +131,43 @@ def test_a_swift_argument_label_is_part_of_the_call(tmp_path): ) < 1.0 +def test_a_trailing_closure_label_is_part_of_the_call(tmp_path): + labeled = """\ +func alpha() -> Int { + return Button { + save() + } label: { + Text(title) + } +} +""" + renamed = """\ +func beta() -> Int { + return Button { + save() + } label: { + Text(heading) + } +} +""" + relabeled = """\ +func beta() -> Int { + return Button { + save() + } action: { + Text(title) + } +} +""" + assert _scored(tmp_path, labeled, renamed) == 1.0 + assert _scored(tmp_path, labeled, relabeled) < 1.0 + assert _scored( + tmp_path, + "func alpha(xs: [Int]) -> [Int] {\n return xs.filter { item in\n odd(item)\n }\n}\n", + "func beta(items: [Int]) -> [Int] {\n return items.filter { value in\n odd(value)\n }\n}\n", + ) == 1.0 + + def test_swift_literals_normalize_and_interpolation_does_not(tmp_path): assert _scored( tmp_path, From 2862b8428ef94f4d5cf9d0e3ec41da3071042253 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:51:01 +0000 Subject: [PATCH 09/11] Compare a deinit the way other Swift methods are compared. A deinit has a body, and a function nested inside it was being reported on its own. The deinit is now the candidate, and the nested function stays inside it. Actor methods are documented with the other type methods. Proved by test_a_deinit_is_compared_and_keeps_its_nested_function. Co-authored-by: Robert C. Martin --- README.md | 2 +- src/dryer/cli.py | 2 +- src/dryer/extract.py | 11 +++++++---- tests/test_swift.py | 30 ++++++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index feedb47..5ee1f50 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ DUPLICATE score=0.89 | Python | functions and methods | functions nested inside another function | | Swift | functions and methods with a body, computed properties, and file-level closures | initializers, subscripts, protocol requirements, and closures or functions nested inside another form | -A Swift computed property includes a SwiftUI `body`. A method on a struct, class, enum, or extension is a candidate, and so is a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, including the label of a trailing closure, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. +A Swift computed property includes a SwiftUI `body`. A method on a struct, class, actor, enum, or extension is a candidate, and so is a deinit and a protocol method that has a default body. A protocol requirement does not. A closure written inside a function stays in that function. A closure bound with `let` or `var` at file scope is its own candidate, as a top-level arrow function is in TypeScript. Argument labels stay, including the label of a trailing closure, because in Swift they are part of the call. `>=`, `!=`, `...`, and `..<` stay. Locals, field names, and literals, including `nil`, do not. An interpolated string keeps the interpolation. Clojure reader conditionals keep the `:clj` branch, as dry4clj does. Syntax-quote is kept as a `syntax-quote` form rather than expanded. diff --git a/src/dryer/cli.py b/src/dryer/cli.py index c98438b..df725ce 100644 --- a/src/dryer/cli.py +++ b/src/dryer/cli.py @@ -60,7 +60,7 @@ named {_skipped_directory_text()} are skipped, as are *_test.go, *.test.cts, Clojure compares every top-level form except ns. The other languages compare functions and methods. Swift also compares computed properties, including a -SwiftUI view body, and a closure bound at file scope. A form is only compared +SwiftUI view body, a closure bound at file scope, and deinit. A form is only compared with forms in the same language. Exit codes: diff --git a/src/dryer/extract.py b/src/dryer/extract.py index 0357638..7a00e06 100644 --- a/src/dryer/extract.py +++ b/src/dryer/extract.py @@ -4,7 +4,7 @@ Clojure compares every top-level list except `ns`, matching dry4clj. The other languages compare the functions and methods crapper scores: bodies, not signatures alone, and not callbacks nested inside another function. Rust functions inside `mod tests` are test code and are skipped. Swift also -compares computed properties and a closure bound at file scope. +compares computed properties, a closure bound at file scope, and deinit. """ from __future__ import annotations @@ -131,8 +131,9 @@ def _typescript_nodes(data: bytes, root) -> list: return found -# A closure, a local function, and a function written inside a view body stay -# inside the form that contains them. A protocol requirement has no body. +# A closure, a local function, and a function written inside a view body or a +# deinit stay inside the form that contains them. A protocol requirement has +# no body. deinit itself is a method with a body. _SWIFT_NEST = { "function_declaration", "protocol_function_declaration", @@ -140,7 +141,9 @@ _SWIFT_NEST = { "computed_property", "init_declaration", "subscript_declaration", + "deinit_declaration", } +_SWIFT_FUNCTION = {"function_declaration", "deinit_declaration"} def _swift_property(node) -> bool: @@ -152,7 +155,7 @@ def _swift_nodes(data: bytes, root) -> list: for node in descendants(root): if _inside(node, _SWIFT_NEST): continue - if node.type == "function_declaration": + if node.type in _SWIFT_FUNCTION: found.append(node) elif node.type == "protocol_function_declaration" and _has(node, "statements"): found.append(node) diff --git a/tests/test_swift.py b/tests/test_swift.py index 700a1ca..cbbfe6a 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -372,6 +372,36 @@ def test_a_swift_package_skips_its_tests(tmp_path): assert relative == ["Sources/App.swift"] +def test_a_deinit_is_compared_and_keeps_its_nested_function(tmp_path): + source = """\ +class Panel { + deinit { + func hidden() -> Int { + return cache() + } + close(handle) + } + + func stop() { + close(handle) + } +} +""" + entries, warning = entries_in_source("swift", source, "Panel.swift", "Panel.swift") + assert warning is None + assert [(entry.start_line, entry.end_line) for entry in entries] == [(2, 7), (9, 11)] + assert _scored( + tmp_path, + "class A {\n deinit {\n close(handle)\n release(buffer)\n }\n}\n", + "class B {\n deinit {\n close(other)\n release(kept)\n }\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "class A {\n deinit {\n close(handle)\n }\n}\n", + "class B {\n deinit {\n shutdown(other)\n }\n}\n", + ) < 1.0 + + def test_a_top_level_swift_closure_matches_its_renamed_copy(tmp_path): left = """\ let alpha = { (xs: [Int]) -> [Int] in From bc42b347c549d2489f0898c1c231c41469b97496 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:51:06 +0000 Subject: [PATCH 10/11] Lock Swift forms a real file uses. Generics, extension methods, async throws, @MainActor, nested block comments, multiline interpolation, computed getters and setters, and negation or force-unwrap still compare by structure. Constraint names, locals, and comments drop. A different try or a missing negation does not. Proved by the eight new tests in test_swift.py. The suite is 103 passed. Co-authored-by: Robert C. Martin --- tests/test_swift.py | 205 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) diff --git a/tests/test_swift.py b/tests/test_swift.py index cbbfe6a..3efca55 100644 --- a/tests/test_swift.py +++ b/tests/test_swift.py @@ -402,6 +402,211 @@ class Panel { ) < 1.0 +def test_a_generic_constraint_name_does_not_keep_the_functions_apart(tmp_path): + assert _scored( + tmp_path, + """\ +func alpha(xs: [T]) -> [T] { + let ys = filter(xs, odd) + return map(ys, inc) +} +""", + """\ +func beta(items: [U]) -> [U] { + let kept = filter(items, even) + return map(kept, dec) +} +""", + ) == 1.0 + assert _scored( + tmp_path, + """\ +func alpha(xs: [T]) -> [T] where T: Equatable { + let ys = filter(xs, odd) + return map(ys, inc) +} +""", + """\ +func beta(items: [U]) -> [U] where U: Hashable { + let kept = filter(items, even) + return map(kept, dec) +} +""", + ) == 1.0 + + +def test_an_extension_method_matches_its_renamed_copy(tmp_path): + assert _scored( + tmp_path, + """\ +extension Array where Element: Equatable { + func alpha(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) + } +} +""", + """\ +extension Array where Element: Hashable { + func beta(items: [Int]) -> [Int] { + let kept = filter(items, even) + return map(kept, dec) + } +} +""", + ) == 1.0 + + +def test_an_async_throws_function_matches_its_renamed_copy(tmp_path): + assert _scored( + tmp_path, + """\ +func alpha(xs: [Int]) async throws -> [Int] { + let ys = try await filter(xs, odd) + return map(ys, inc) +} +""", + """\ +func beta(items: [Int]) async throws -> [Int] { + let kept = try await filter(items, even) + return map(kept, dec) +} +""", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha() -> Int? {\n return try? cache()\n}\n", + "func beta() -> Int {\n return try load()\n}\n", + ) < 1.0 + + +def test_a_main_actor_function_matches_its_renamed_copy(tmp_path): + assert _scored( + tmp_path, + """\ +@MainActor +func alpha(xs: [Int]) -> [Int] { + let ys = filter(xs, odd) + return map(ys, inc) +} +""", + """\ +@MainActor +func beta(items: [Int]) -> [Int] { + let kept = filter(items, even) + return map(kept, dec) +} +""", + ) == 1.0 + assert _scored( + tmp_path, + """\ +struct InvoiceView { + @MainActor + var body: String { + return Text(title) + } +} +""", + """\ +struct ReceiptView { + @MainActor + var body: String { + return Text(heading) + } +} +""", + ) == 1.0 + + +def test_a_nested_block_comment_is_not_part_of_the_structure(tmp_path): + commented = """\ +func alpha(xs: [Int]) -> [Int] { + /* outer /* inner */ still comment */ + let ys = filter(xs, odd) + return map(ys, inc) +} +""" + assert _scored(tmp_path, commented, SWIFT_RIGHT) == 1.0 + + +def test_multiline_interpolation_keeps_the_expression_and_drops_the_name(tmp_path): + assert _scored( + tmp_path, + '''func alpha(order: Order) -> String {\n return """\n \\(order.total)\n """\n}\n''', + '''func beta(row: Row) -> String {\n return """\n \\(row.amount)\n """\n}\n''', + ) == 1.0 + assert _scored( + tmp_path, + '''func alpha(order: Order) -> String {\n return """\n \\(order.total)\n """\n}\n''', + 'func beta() -> String {\n return """\n hello\n """\n}\n', + ) < 1.0 + + +def test_a_getter_and_setter_match_when_only_the_names_change(tmp_path): + assert _scored( + tmp_path, + """\ +struct Left { + var value: Int { + get { return cache(stored) } + set { store(fresh) } + } +} +""", + """\ +struct Right { + var amount: Int { + get { return cache(kept) } + set { store(next) } + } +} +""", + ) == 1.0 + assert _scored( + tmp_path, + """\ +struct Left { + var value: Int { + get { return cache(stored) } + set { store(fresh) } + } +} +""", + """\ +struct Right { + var amount: Int { + get { return cache(kept) } + set { write(next) } + } +} +""", + ) < 1.0 + + +def test_negation_and_force_unwrap_stay_in_the_score(tmp_path): + assert _scored( + tmp_path, + "func alpha(xs: Bool) -> Bool {\n return !xs\n}\n", + "func beta(items: Bool) -> Bool {\n return !items\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Bool) -> Bool {\n return !xs\n}\n", + "func beta(items: Bool) -> Bool {\n return items\n}\n", + ) < 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Int?) -> Int {\n return xs!\n}\n", + "func beta(items: Int?) -> Int {\n return items!\n}\n", + ) == 1.0 + assert _scored( + tmp_path, + "func alpha(xs: Int?) -> Int {\n return xs!\n}\n", + "func beta(items: Int?) -> Int {\n return items\n}\n", + ) < 1.0 + + def test_a_top_level_swift_closure_matches_its_renamed_copy(tmp_path): left = """\ let alpha = { (xs: [Int]) -> [Int] in From 4cef42357f823854e74c49f44ef46ba46182e34c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 23:57:02 +0000 Subject: [PATCH 11/11] Cover the mutation sites the report left uncovered. A file outside the project root is not source. That branch returned false with no test, so the mutant was uncovered. check=False now sits on the git call coverage records, and a failing git is still reported as GitStatusError. Proved by test_a_file_outside_the_project_root_is_not_source. mutator on cli.py killed 64 of 64, with nothing survived and nothing uncovered. Co-authored-by: Robert C. Martin --- src/dryer/cli.py | 8 ++------ tests/test_cli.py | 8 ++++++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/dryer/cli.py b/src/dryer/cli.py index df725ce..275e16e 100644 --- a/src/dryer/cli.py +++ b/src/dryer/cli.py @@ -178,12 +178,8 @@ class GitStatusError(Exception): def _git(root: Path, *args: str) -> bytes: - result = subprocess.run( - ["git", "-C", os.fspath(root), *args], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - check=False, - ) + command = ["git", "-C", os.fspath(root), *args] + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if result.returncode != 0: message = os.fsdecode(result.stderr).strip() or "git status failed" raise GitStatusError(result.returncode, message) diff --git a/tests/test_cli.py b/tests/test_cli.py index a17e20f..8701f0c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -332,6 +332,14 @@ def test_changed_source_skips_unknown_and_test_files(tmp_path): assert _tracked_source(tmp_path / "target" / "app.py") is False +def test_a_file_outside_the_project_root_is_not_source(tmp_path): + outside = tmp_path / "outside.py" + outside.write_text("x = 1\n", encoding="utf-8") + root = tmp_path / "project" + root.mkdir() + assert _tracked_source(outside, root) is False + + def test_test_files_and_skipped_directories_are_left_out(tmp_path): write_source(tmp_path, "src/app.py", "x = 1\n") write_source(tmp_path, "src/foo_test.py", "x = 1\n")