Extract helpers and test the behavior mutation testing was missing.

The switches stay intact. The new tests pin option parsing, file selection, normalization, and which forms each language compares, so the survivors that remain are equivalent mutants.
This commit is contained in:
Robert C. Martin
2026-09-30 17:25:34 -05:00
parent fcf865759d
commit 6892667b34
9 changed files with 875 additions and 108 deletions
+41 -25
View File
@@ -189,32 +189,39 @@ def _is_literal(node) -> bool:
return True
def _normalize_call(node):
def _named_before_args(node):
incoming = []
args = None
for child in node.named_children:
if child.type in _ARG_LISTS:
args = child
break
return incoming, child
incoming.append(child)
type_args = [child for child in incoming if child.type in _TYPE_ARGS]
rest = [child for child in incoming if child.type not in _TYPE_ARGS]
return incoming, None
def _without_type_args(nodes):
type_args = [child for child in nodes if child.type in _TYPE_ARGS]
rest = [child for child in nodes if child.type not in _TYPE_ARGS]
return rest, type_args
def _extend_normalized(out, nodes) -> None:
for node in nodes:
norm = _normalize(node, False)
if norm is not None:
out.append(norm)
def _normalize_call(node):
incoming, args = _named_before_args(node)
rest, type_args = _without_type_args(incoming)
out = [K(node.type)]
if rest:
*receivers, callee = rest
for receiver in receivers:
norm = _normalize(receiver, False)
if norm is not None:
out.append(norm)
_extend_normalized(out, receivers)
out.append(_normalize_callee(callee))
for type_node in type_args:
norm = _normalize(type_node, False)
if norm is not None:
out.append(norm)
_extend_normalized(out, type_args)
if args is not None:
norm = _normalize(args, False)
if norm is not None:
out.append(norm)
_extend_normalized(out, [args])
return out
@@ -244,20 +251,29 @@ def _normalize_path(node):
return parts
def _normalized_name(name, head: bool):
"""Keep a member's spelling when it is the thing being called."""
if name.type in _IDENTIFIERS:
if head:
return [K("symbol"), _text(name)]
return K("symbol")
if head:
return _normalize_callee(name)
return _normalize(name, False)
def _normalize_attr(node, head: bool):
named = list(node.named_children)
parts = [K(node.type)]
if not named:
return parts
return [K(node.type)]
*objects, name = named
parts = [K(node.type)]
for obj in objects:
norm = _normalize(obj, False)
if norm is not None:
parts.append(norm)
if name.type in _IDENTIFIERS:
parts.append([K("symbol"), _text(name)] if head else K("symbol"))
else:
nested = _normalize_callee(name) if head else _normalize(name, False)
if nested is not None:
parts.append(nested)
nested = _normalized_name(name, head)
if nested is not None:
parts.append(nested)
return parts
+13 -12
View File
@@ -159,14 +159,13 @@ def parse_args(argv: list[str] | None = None) -> Options:
return options
def _git_status(root: Path):
args = ["git", "status", "--porcelain"]
return subprocess.run(args, cwd=root, check=False, capture_output=True, text=True)
def _changed_files(root: Path) -> list[Path]:
result = subprocess.run(
["git", "status", "--porcelain"],
cwd=root,
check=False,
capture_output=True,
text=True,
)
result = _git_status(root)
if result.returncode != 0:
print(result.stderr.strip() or "git status failed", file=sys.stderr)
return []
@@ -196,12 +195,14 @@ def _positionals(root: Path, args: list[str]) -> tuple[list[Path], list[str]]:
return existing, filters
def _tracked_source(path: Path) -> bool:
if language_of(path) is None:
return False
return not is_test_file(path)
def _changed_source(root: Path) -> list[Path]:
return [
path
for path in _changed_files(root)
if language_of(path) is not None and not is_test_file(path)
]
return [path for path in _changed_files(root) if _tracked_source(path)]
def _explicit_files(existing: list[Path]) -> list[Path]:
+52 -27
View File
@@ -218,24 +218,15 @@ class Reader:
form = self.read_form()
if not isinstance(form, Coll) or form.kind != "list":
raise ReadError(self.line, "reader conditional body must be a list")
chosen = None
index = 0
items = form.items
while index + 1 < len(items):
feature = items[index]
expr = items[index + 1]
index += 2
name = feature.name if isinstance(feature, Kw) else None
if name in {"clj", "default"}:
chosen = expr
break
chosen = _chosen_branch(form.items)
if chosen is None:
return None
if not splicing:
return chosen
if isinstance(chosen, Coll) and chosen.kind in {"list", "vector"}:
return Splice(list(chosen.items))
raise ReadError(self.line, "splicing reader conditional needs a collection")
spliced = _spliced(chosen)
if spliced is None:
raise ReadError(self.line, "splicing reader conditional needs a collection")
return spliced
def read_form(self):
self.skip_ws()
@@ -283,15 +274,47 @@ class Reader:
return Sym(token, line)
def _branch_name(feature):
if isinstance(feature, Kw):
return feature.name
return None
def _chosen_branch(items):
index = 0
while index + 1 < len(items):
expr = items[index + 1]
if _branch_name(items[index]) in {"clj", "default"}:
return expr
index += 2
return None
def _spliced(chosen):
if isinstance(chosen, Coll) and chosen.kind in {"list", "vector"}:
return Splice(list(chosen.items))
return None
def _strip_bom(text: str) -> str:
if text.startswith("\ufeff"):
return text[1:]
return text
def _skip_shebang(reader: Reader, text: str) -> None:
if not text.startswith("#!"):
return
while reader.peek() not in (None, "\n"):
reader.get()
def read_source(text: str) -> tuple[list, str | None]:
"""Top-level forms, plus a warning if a later form could not be read."""
if text.startswith("\ufeff"):
text = text[1:]
text = _strip_bom(text)
reader = Reader(text)
if text.startswith("#!"):
while not reader.eof() and reader.peek() != "\n":
reader.get()
_skip_shebang(reader, text)
forms: list = []
while True:
reader.skip_ws()
@@ -324,24 +347,26 @@ def max_line(form) -> int:
return best
def _normalize_list(form):
if not form.items:
return [K("list"), K("literal")]
head_form, *args = form.items
return [K("list"), normalize(head_form, True), *[normalize(arg, False) for arg in args]]
def normalize(form, head: bool = False):
"""dry4clj's `normalize-form`. Collection heads are normalized in full."""
if isinstance(form, Coll):
if form.kind == "list":
if not form.items:
return [K("list"), K("literal")]
head_form, *args = form.items
return [K("list"), normalize(head_form, True), *[normalize(arg, False) for arg in args]]
return _normalize_list(form)
if form.kind == "vector":
return [K("vector"), *[normalize(item, False) for item in form.items]]
if form.kind == "set":
return [K("set"), *[normalize(item, False) for item in form.items]]
if form.kind == "map":
return [
K("map"),
*[[normalize(key, False), normalize(value, False)] for key, value in form.pairs],
]
pairs = [[normalize(key, False), normalize(value, False)] for key, value in form.pairs]
return [K("map"), *pairs]
return [K("literal")]
if isinstance(form, Sym):
if head:
+5 -3
View File
@@ -79,6 +79,10 @@ def is_test_file(path: str | Path) -> bool:
return any(part in TEST_DIRS for part in file_path.parts)
def _skipped_dir(name: str) -> bool:
return name in SKIP_DIRS or name in TEST_DIRS
def _walk(root: Path) -> list[Path]:
if not root.exists():
return []
@@ -86,9 +90,7 @@ def _walk(root: Path) -> list[Path]:
return [root]
found: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [
name for name in dirnames if name not in SKIP_DIRS and name not in TEST_DIRS
]
dirnames[:] = [name for name in dirnames if not _skipped_dir(name)]
for name in filenames:
path = Path(dirpath) / name
if language_of(path) is None or is_test_file(path):
+21 -21
View File
@@ -34,32 +34,32 @@ def _edn_float(value: float) -> str:
return text
def _span_edn(span) -> str:
return (
f"{{:file {_edn_string(span.file)}, "
f":start-line {span.start_line}, :end-line {span.end_line}}}"
)
def _candidate_edn(candidate: Duplicate) -> str:
return "\n".join(
[
f" {{:score {_edn_float(candidate.score)}",
f" :language {_edn_string(candidate.language)}",
f" :left {_span_edn(candidate.left)}",
f" :right {_span_edn(candidate.right)}",
f" :left-nodes {candidate.left_nodes}",
f" :right-nodes {candidate.right_nodes}}}",
]
)
def render_edn(candidates: list[Duplicate]) -> str:
"""EDN map `{:candidates [...]}` with dry4clj's keys, plus `:language`."""
if not candidates:
return "{:candidates []}\n"
rows = []
for candidate in candidates:
left = candidate.left
right = candidate.right
rows.append(
" {:score "
+ _edn_float(candidate.score)
+ "\n :language "
+ _edn_string(candidate.language)
+ "\n :left {:file "
+ _edn_string(left.file)
+ f", :start-line {left.start_line}, :end-line {left.end_line}"
+ "}"
+ "\n :right {:file "
+ _edn_string(right.file)
+ f", :start-line {right.start_line}, :end-line {right.end_line}"
+ "}"
+ f"\n :left-nodes {candidate.left_nodes}"
+ f"\n :right-nodes {candidate.right_nodes}"
+ "}"
)
rows = [_candidate_edn(candidate) for candidate in candidates]
return "{:candidates [\n" + "\n".join(rows) + "\n]}\n"
+22 -15
View File
@@ -41,6 +41,26 @@ def scan_files(
return entries, warnings
def _same_span(left: Entry, right: Entry) -> bool:
if left.file != right.file:
return False
if left.start_line != right.start_line:
return False
return left.end_line == right.end_line
def _duplicate_key(item: Duplicate):
score = -item.score
return (
score,
item.language,
item.left.file,
item.left.start_line,
item.right.file,
item.right.start_line,
)
def find_duplicates(entries: list[Entry], threshold: float) -> list[Duplicate]:
"""Pair forms of the same language. Each unordered pair is reported once."""
@@ -52,11 +72,7 @@ def find_duplicates(entries: list[Entry], threshold: float) -> list[Duplicate]:
for language, group in by_language.items():
for index, left in enumerate(group):
for right in group[index + 1 :]:
if (
left.file == right.file
and left.start_line == right.start_line
and left.end_line == right.end_line
):
if _same_span(left, right):
continue
score = jaccard(left.fingerprints, right.fingerprints)
if score < threshold:
@@ -71,14 +87,5 @@ def find_duplicates(entries: list[Entry], threshold: float) -> list[Duplicate]:
right_nodes=right.nodes,
)
)
found.sort(
key=lambda item: (
-item.score,
item.language,
item.left.file,
item.left.start_line,
item.right.file,
item.right.start_line,
)
)
found.sort(key=_duplicate_key)
return found