Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# dryer

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.
dryer finds candidate duplicate code in Clojure, Java, Go, TypeScript, Rust, Python, Dart, 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). 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.
Clojure follows [dry4clj](https://github.com/unclebob/dry4clj). Java, Go, TypeScript, Rust, Python, and Dart 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:

Expand Down Expand Up @@ -108,6 +108,7 @@ 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 |
| Dart | functions, methods, getters, setters, operators, factory constructors | generative constructors, abstract and external members, local functions, closures, generated files |
| 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, 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.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "dryer"
version = "0.1.0"
description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, Python, and Swift."
description = "Structural duplicate finder for Clojure, Java, Go, TypeScript, Rust, Python, Dart, and Swift."
readme = "README.md"
license = { file = "LICENSE" }
classifiers = ["License :: OSI Approved :: Zero-Clause BSD (0BSD)"]
Expand Down
49 changes: 47 additions & 2 deletions src/dryer/astnorm.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from __future__ import annotations

from dryer.shape import K
from dryer.treesitter import node_text
from dryer.treesitter import child_of_type, node_text

_SKIP = {
"comment",
Expand Down Expand Up @@ -143,13 +143,18 @@
# identifier placed directly on the call_suffix, not a value_argument_label.
_TEXT_SYMBOLS = {"custom_operator", "value_argument_label"}
_INTERPOLATED = {"interpolation", "interpolated_expression"}
# Dart spells interpolation as `template_substitution` inside a `string`. Kept
# scoped to that node so a template string in another language stays a literal.
_DART_INTERPOLATED = {"template_substitution"}

_SCOPED = {
"scoped_identifier",
"scoped_type_identifier",
}

_ARG_LISTS = {"argument_list", "arguments", "call_suffix"}
# Dart spells some operators as named leaves, which carry no token child.
_OPERATOR_LEAVES = {"additive_operator", "equality_operator", "minus_operator"}
_TYPE_ARGS = {"type_arguments", "type_parameters"}

_DATA: bytes = b""
Expand All @@ -173,6 +178,10 @@ def _text(node) -> str:
def _is_literal(node) -> bool:
if node.type not in _LITERALS:
return False
if node.type in {"string", "string_literal"} and any(
child.type in _DART_INTERPOLATED for child in node.children
):
return False
return not any(child.type in _INTERPOLATED for child in node.children)


Expand All @@ -197,9 +206,43 @@ def _callee_leaf(node):
return _PENDING


_DART_MEMBERS = {
"unconditional_assignable_selector",
"conditional_assignable_selector",
"cascade_selector",
}


def _dart_holder(node):
"""The node whose next sibling holds the arguments: `.name` sits in a
`selector`, except after `super` and in a cascade."""

parent = node.parent
if parent is None or parent.type not in _DART_MEMBERS:
return node
if parent.parent is not None and parent.parent.type == "selector":
return parent.parent
return parent


def _has_arguments(node) -> bool:
if node is None:
return False
return node.type == "argument_part" or child_of_type(node, "argument_part") is not None


def _dart_called(node) -> bool:
"""Dart calls are flat: the name, then a `selector` holding the arguments.
`const A.b(...)` keeps both names."""

if node.parent is not None and node.parent.type == "const_object_expression":
return True
return _has_arguments(_dart_holder(node).next_named_sibling)


def _named_leaf(node, head: bool):
if node.type in _IDENTIFIERS:
if head:
if head or _dart_called(node):
return [K("symbol"), _text(node)]
return K("symbol")
if _is_literal(node):
Expand Down Expand Up @@ -227,6 +270,8 @@ def _try_leaf(node, mode: str, head: bool):
return [K("symbol"), _text(node)]
if not node.is_named:
return None
if node.type in _OPERATOR_LEAVES:
return [K("symbol"), _text(node)]
return _named_leaf(node, head)


Expand Down
10 changes: 6 additions & 4 deletions src/dryer/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ def _skipped_directory_text() -> str:
Usage: dryer [options] [path-or-filter ...]

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
Python, Dart, 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), Swift (.swift).
TypeScript (.ts .tsx .mts .cts), Rust (.rs), Python (.py), Dart (.dart),
Swift (.swift).
Generated Dart files (*.g.dart, *.freezed.dart and similar) are skipped.

Options:
-h, --help Print this help and exit.
Expand Down
28 changes: 26 additions & 2 deletions src/dryer/discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
".cts": "typescript",
".rs": "rust",
".py": "python",
".dart": "dart",
".swift": "swift",
}

Expand All @@ -42,13 +43,17 @@
"testdata",
"__pycache__",
".clj-kondo",
".dart_tool",
}

TEST_DIRS = {"test", "tests", "spec", "specs", "__tests__", "Tests"}
# Dart tests only: a Go or Python folder with these names is still source.
DART_TEST_DIRS = {"integration_test", "test_driver"}

# One suffix list. Swift packages name XCTest files *Tests.swift.
_TEST_SUFFIXES = (
"_test.go",
"_test.dart",
"_test.clj",
"_test.cljc",
"_test.cljs",
Expand All @@ -66,23 +71,42 @@
"Tests.swift",
)

# Dart code generators write files that are still sources to the analyzer.
DART_GENERATED_SUFFIXES = (
".g.dart",
".freezed.dart",
".mocks.dart",
".gr.dart",
".config.dart",
".pb.dart",
".pbenum.dart",
".pbjson.dart",
".pbserver.dart",
)


def language_of(path: str | Path) -> str | None:
file_path = Path(path)
name = file_path.name
if name.endswith(".d.ts"):
if name.endswith(".d.ts") or name.endswith(DART_GENERATED_SUFFIXES):
return None
return EXTENSIONS.get(file_path.suffix)


def _test_dirs(file_path: Path) -> set[str]:
if file_path.suffix == ".dart":
return TEST_DIRS | DART_TEST_DIRS
return TEST_DIRS


def is_test_file(path: str | Path) -> bool:
file_path = Path(path)
name = file_path.name
if name == "conftest.py" or name.endswith(_TEST_SUFFIXES):
return True
if name.startswith("test_") and name.endswith(".py"):
return True
return any(part in TEST_DIRS for part in file_path.parts)
return any(part in _test_dirs(file_path) for part in file_path.parts)


def _skipped_dir(name: str) -> bool:
Expand Down
45 changes: 43 additions & 2 deletions src/dryer/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,52 @@ def _rust_nodes(data: bytes, root) -> list:
return found


_DART_SIGNATURES = {"function_signature", "getter_signature", "setter_signature"}
_DART_BETWEEN = {"comment", "documentation_comment", "annotation"}
_DART_GENERATIVE = {
"constructor_signature",
"constant_constructor_signature",
"redirecting_factory_constructor_signature",
}


def _dart_signature(node) -> bool:
if node.type == "method_signature":
first = next((child for child in node.named_children), None)
return first is not None and first.type not in _DART_GENERATIVE
return node.type in _DART_SIGNATURES and node.parent.type != "method_signature"


def _dart_body(signature):
current = signature.next_sibling
while current is not None and current.type in _DART_BETWEEN:
current = current.next_sibling
if current is not None and current.type == "function_body":
return current
return None


def _dart_nodes(data: bytes, root) -> list:
"""The functions crapper scores, as (body, signature): Dart keeps them as
siblings. Generative constructors, locals, and closures are not entries."""

found = []
for node in descendants(root):
if not _dart_signature(node) or _inside(node, {"function_body", "function_expression"}):
continue
body = _dart_body(node)
if body is not None:
found.append((body, node))
return found


_PICKERS = {
"java": ("java", _java_nodes),
"go": ("go", _go_nodes),
"python": ("python", _python_nodes),
"typescript": (_grammar, _typescript_nodes),
"rust": ("rust", _rust_nodes),
"dart": ("dart", _dart_nodes),
"swift": ("swift", _swift_nodes),
}

Expand All @@ -192,15 +232,16 @@ def _tree_entries(language: str, source: str, path: str, file: str) -> list[Entr
grammar = grammar_or_name(path) if callable(grammar_or_name) else grammar_or_name
data, tree = parse(source, grammar)
entries = []
for node in pick(data, tree.root_node):
for picked in pick(data, tree.root_node):
node, first = picked if isinstance(picked, tuple) else (picked, picked)
normalized = normalize(node, data)
if normalized is None:
continue
entries.append(
Entry(
language=language,
file=file,
start_line=start_line(node),
start_line=start_line(first),
end_line=end_line(node),
nodes=node_count(normalized),
fingerprints=fingerprints(normalized),
Expand Down
Loading