Find Swift mutation sites and join them to crapper's functions.

Swift needs the same operator decisions as Java, plus the ?? fallback
TypeScript already flips, and a negation of boolean conditions so guard
is covered. A logical ! and a unary - are deleted; a force-unwrap is not.
Statements and returns are not removed, because the other languages do
not remove them either. private and fileprivate declarations use defn-/.

A closure crapper does not report stays on the enclosing function, and a
stored closure is its own entry, so the snapshot namespace matches
.metrics/crap.edn.

Proved by tests/test_swift.py. Those tests failed first: only true/false
and 0/1 were sites, private funcs were defn/, and a run exited 0 because
the comparison and the guard negation were missing. They pass, and the
existing suite still passes (101 tests).

Co-authored-by: Robert C. Martin <[email protected]>
This commit is contained in:
Cursor Agent
2026-11-25 23:58:11 +00:00
co-authored by Robert C. Martin
parent 0136cf5557
commit b52159454d
3 changed files with 261 additions and 6 deletions
+6
View File
@@ -46,6 +46,10 @@ def _typescript_private(name: str, header: str) -> bool:
return name.startswith("#") or bool(re.search(r"\bprivate\b", header))
def _swift_private(header: str) -> bool:
return re.search(r"\b(?:fileprivate|private)\b", header) is not None
def is_private(language: str, name: str, source: str, start: int, end: int) -> bool:
"""True when uml-viewer should treat the operation as private."""
@@ -62,6 +66,8 @@ def is_private(language: str, name: str, source: str, start: int, end: int) -> b
return re.match(r"pub\s", header) is None
if language == "typescript":
return _typescript_private(name, header)
if language == "swift":
return _swift_private(header)
return False
+79 -6
View File
@@ -1,10 +1,11 @@
"""Find mutation sites.
Clojure follows clj-mutate's symbol rules. Go follows mutate4go, including
one-way `*` to `/`. Java follows mutate4java. TypeScript, Rust, and Python
use the same decisions as Java, spelled in that language. TypeScript also
mutates `??` to `||` and `?.` to `.` (removed on a call or index). JavaScript
files use the TypeScript rules.
one-way `*` to `/`. Java follows mutate4java. TypeScript, Rust, Python, and
Swift use the same decisions as Java, spelled in that language. TypeScript
also mutates `??` to `||` and `?.` to `.` (removed on a call or index).
Swift mutates `??` to `||` and wraps a boolean condition of `if`, `guard`,
`while`, or `repeat-while` in `!()`. JavaScript files use the TypeScript rules.
"""
from __future__ import annotations
@@ -36,9 +37,39 @@ _BINARY_PARENTS = {
"binary_operator",
"comparison_operator",
"boolean_operator",
"additive_expression",
"multiplicative_expression",
"comparison_expression",
"equality_expression",
"infix_expression",
"conjunction_expression",
"disjunction_expression",
"nil_coalescing_expression",
}
_UNARY_PARENTS = {"unary_expression", "unary_operator", "not_operator"}
_UNARY_PARENTS = {"unary_expression", "unary_operator", "not_operator", "prefix_expression"}
# Boolean conditions. A `let` binding is not one of them. `repeat-while` puts
# the condition after the body; the others put it before.
_SWIFT_CONDITIONS = {
"if_statement",
"guard_statement",
"while_statement",
"repeat_while_statement",
}
_SWIFT_SKIP = {
"if",
"else",
"guard",
"while",
"repeat",
"{",
"}",
",",
"statements",
"if_statement",
"comment",
}
_BOOLEANS = {"true": "false", "false": "true", "True": "False", "False": "True"}
@@ -137,7 +168,7 @@ def _category(token: str) -> str:
def _binary_mutant(language: str, token: str) -> str | None:
if language == "go" and token == "/":
return None
if token == "??" and language != "typescript":
if token == "??" and language not in {"typescript", "swift"}:
return None
return _BINARY.get(token)
@@ -336,9 +367,51 @@ def _visit_leaf(node, data: bytes, language: str, found: list[RawSite]) -> None:
_visit_constant(node, token, found)
def _ends_swift_conditions(node, child) -> bool:
if child.type == "else":
return True
if node.type == "repeat_while_statement":
return False
return child.type in {"{", "statements"}
def _swift_conditions(node):
if node.type not in _SWIFT_CONDITIONS:
return []
found = []
binding = False
for child in node.children:
if _ends_swift_conditions(node, child):
break
if child.type in _SWIFT_SKIP:
binding = False
continue
if child.type == "value_binding_pattern":
binding = True
continue
if binding:
continue
found.append(child)
return found
def _negate_condition(node, data: bytes, found: list[RawSite]) -> None:
original = _text(data, node)
if not original.strip():
return
_add(found, node, original, f"!({original})", "conditional")
def _visit_swift_conditions(node, data: bytes, found: list[RawSite]) -> None:
for condition in _swift_conditions(node):
_negate_condition(condition, data, found)
def _visit_node(node, data: bytes, language: str, found: list[RawSite]) -> None:
if language == "typescript" and _in_type(node):
return
if language == "swift":
_visit_swift_conditions(node, data, found)
if node.child_count == 0:
_visit_leaf(node, data, language, found)
else:
+176
View File
@@ -0,0 +1,176 @@
"""Swift mutation sites join the functions crapper reports."""
import sys
from pathlib import Path
from mutator.cli import run
from mutator.functions import sites_in_file
SOURCE = """func place(x: Int, ready: Bool, name: String?) -> Int {
guard x > 0, ready else { return 0 }
if x >= 1 && ready || !ready {
return x + 1
} else if x != 0 {
return x - 1
}
while x < 2 {
x = x * 2 / 1
}
let value = name ?? "guest"
let flag = true
let n = -x
let forced = name!
let same = name === nil
let other = name !== nil
return value.count
}
struct Box {
private func hide() -> Bool { false }
fileprivate func seal() -> Bool { true }
func open() -> Int { 1 }
}
let stored = { (n: Int) -> Int in n + 1 }
func mount() -> Int {
let handler = { (n: Int) -> Int in
n > 0 ? n : 0
}
return handler(1)
}
func quote() -> String {
// x > 0 && true ?? name!
return "x > 0 && true ?? name!"
}
func bind(name: String?) -> Int {
if let name, name.count > 1 {
return name.count
}
repeat {
return 0
} while name == nil
}
"""
def _sites(tmp_path: Path, source: str = SOURCE, relative: str = "Sources/Demo/Box.swift"):
path = tmp_path / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(source, encoding="utf-8")
return sites_in_file(source, path, tmp_path, relative)
def _pairs(sites):
return {(site.original, site.mutant) for site in sites}
def test_swift_operators_match_the_other_languages_and_negate_conditions(tmp_path):
sites = _sites(tmp_path)
pairs = _pairs(sites)
assert ("+", "-") in pairs
assert ("-", "+") in pairs
assert ("-", "") in pairs
assert ("*", "/") in pairs
assert ("/", "*") in pairs
assert (">", ">=") in pairs
assert (">=", ">") in pairs
assert ("<", "<=") in pairs
assert ("!=", "==") in pairs
assert ("==", "!=") in pairs
assert ("===", "!==") in pairs
assert ("!==", "===") in pairs
assert ("&&", "||") in pairs
assert ("||", "&&") in pairs
assert ("??", "||") in pairs
assert ("true", "false") in pairs
assert ("false", "true") in pairs
assert ("0", "1") in pairs
assert ("1", "0") in pairs
assert ("!", "") in pairs
negated = {site.original for site in sites if site.mutant == f"!({site.original})"}
assert negated == {
"x > 0",
"ready",
"x >= 1 && ready || !ready",
"x != 0",
"x < 2",
"name.count > 1",
"name == nil",
}
assert all(site.original != "?" for site in sites)
assert all(site.original != "?." for site in sites)
assert all(site.original != "%" for site in sites)
def test_a_nested_closure_stays_on_the_parent_and_a_stored_closure_is_its_own(tmp_path):
sites = _sites(tmp_path)
mount = [site for site in sites if site.name == "mount"]
assert (">", ">=") in _pairs(mount)
assert ("0", "1") in _pairs(mount)
assert {site.namespace for site in mount} == {"Demo"}
assert all(site.name != "handler" for site in sites)
stored = [site for site in sites if site.name == "stored"]
assert _pairs(stored) == {("+", "-"), ("1", "0")}
assert {site.namespace for site in stored} == {"Demo"}
def test_strings_comments_and_force_unwrap_are_left_alone(tmp_path):
sites = _sites(tmp_path)
assert all(site.name != "quote" for site in sites)
deleted = [site for site in sites if site.original == "!" and site.mutant == ""]
assert len(deleted) == 1
assert deleted[0].name == "place"
def test_private_and_fileprivate_join_the_type_namespace(tmp_path):
sites = _sites(tmp_path)
by_name = {site.name: site for site in sites if site.name in {"hide", "seal", "open"}}
assert by_name["hide"].form_id == "defn-/hide"
assert by_name["seal"].form_id == "defn-/seal"
assert by_name["open"].form_id == "defn/open"
assert {site.namespace for site in by_name.values()} == {"Demo.Box"}
assert by_name["hide"].mutant == "true"
assert by_name["seal"].mutant == "false"
assert (by_name["open"].original, by_name["open"].mutant) == ("1", "0")
def test_a_swift_run_records_killed_and_survived_on_the_crapper_namespace(tmp_path, capsys):
relative = "Sources/Demo/Place.swift"
path = tmp_path / relative
path.parent.mkdir(parents=True)
path.write_text(
"func place(x: Int) -> Int {\n guard x > 0 else { return x }\n return x\n}\n",
encoding="utf-8",
)
command = (
f"{sys.executable} -c \"from pathlib import Path; "
"text = Path('Sources/Demo/Place.swift').read_text(); "
"raise SystemExit(0 if 'x > 0' in text else 1)\""
)
code = run(
[
"--no-coverage",
"--mutate-all",
"--root",
str(tmp_path),
"--test-command",
command,
relative,
]
)
captured = capsys.readouterr()
assert code == 3
assert "KILLED" in captured.out
assert "SURVIVED" in captured.out
assert "Uncovered" in captured.out
snapshot = tmp_path / ".metrics" / "mutate" / "Demo.edn"
text = snapshot.read_text(encoding="utf-8")
assert ':namespace "Demo"' in text
assert ':source "Sources/Demo/Place.swift"' in text
assert ':id "defn/place"' in text
assert ":killed" in text
assert ":survived" in text
assert path.read_text(encoding="utf-8").startswith("func place")