Duplicate code detection for OCaml
README.md

dupfind #

Duplicate code detection for OCaml.

Overview #

Copied code in a large OCaml tree rarely stays identical: one copy renames a variable, another reorders a match, and a textual clone detector stops seeing them as the same function. dupfind compares the structure of the code instead. It parses every binding, normalises the expression and hashes it, so bindings that differ only in local names hash the same. A second pass, anti-unification, finds bindings that are similar without being equal. Anti-unification (Plotkin, 1970) is the dual of unification: given two trees, it computes the most specific pattern that matches both, a tree with a variable (a hole) at each position where they disagree, and the same variable wherever the same pair of subtrees disagrees again. The skeleton of two bindings is that pattern, and its size is its count of nodes that are not holes. Parallel implementations of one idea have a large skeleton and few holes.

The exact-clone pass works in four steps:

  1. Parse. Source files are parsed into the compiler's Parsetree.
  2. Normalise. Each binding's expression becomes a simplified AST with locations erased and local variables renamed to canonical names (_0, _1 and so on), so fun x -> x + 1 and fun y -> y + 1 become the same tree.
  3. Hash. The normalised AST is written as a tag-length-value encoding and hashed with MD5.
  4. Cluster. Bindings with the same hash are grouped. A group is reported once the mass it duplicates reaches --min-mass.

What gets reported #

Every binding is hashed, however small. The cost of a duplicate depends on how many copies there are as much as on its size: a 40-node body copied twice is 40 nodes to delete and two places to fix, and a 4-node body copied eleven times is 40 nodes and eleven places to fix. The threshold therefore reads one number for both, the mass a finding duplicates:

  • an exact cluster of n copies duplicates ast_size * (n - 1), the nodes that factoring it out would delete;
  • a drift pair is two bindings that are not equal after normalisation but whose skeleton covers at least --threshold of the larger one (the overlap, skeleton nodes over the larger binding's nodes, default 0.6); it duplicates the skeleton's nodes.

The two agree when n is 2. Findings are ranked by the same mass, so the threshold, the ranking and the Mass column all read one quantity. Raise --min-mass to report less.

Anti-unification compares bindings in pairs, and n bindings that all match each other give n(n-1)/2 pairs. Those pairs describe one fact about the code, so dupfind groups them back into the family they come from and reports it once, with every member listed and the closest pair named as the one to read first. Grouping changes the shape of the report and drops nothing: on a CSS library whose eighteen prop_*.ml files each hold about forty printers, 7,740 drift pairs become 78 families, the largest with 159 members.

Anti-unifying every pair of the N bindings in a tree would cost N(N-1)/2 runs, 5 x 10^9 for N = 100,000, so dupfind first selects candidates. Each binding is summarised by its structural bigrams, the (parent constructor, child position, child constructor) triples of its tree. A skeleton of m nodes is one connected tree, so it shares at least m - 1 bigrams with each binding, and a pair whose bigram intersection is below threshold x larger size - 1 cannot reach the threshold. An inverted index over each binding's rarest bigrams (a prefix-filter set-similarity join) proposes every pair that can pass that bound, and only among bindings whose sizes are within a factor 1 / threshold of each other, since the skeleton is no larger than the smaller binding. Each candidate is checked against the exact bounds before the anti-unification, which is linear in the size of the two trees, runs. The filter drops no pair that could reach the threshold.

--min-drift-size bounds the anti-unification pass alone, which compares whole bindings and needs a skeleton large enough to mean something. It does not bound exact clones: a body smaller than --min-drift-size is still reported once it repeats enough to reach --min-mass. It counts normalised nodes, the same unit as the Mass column and the ast_size field of the JSON output.

Anti-unification also uses types. When the .cmt files of a dune build are present under _build/default/, a pair is kept only if the two bindings have compatible inferred types; when they are absent, every pair is kept.

Installation #

Install with opam:

$ opam install dupfind

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install dupfind

Usage #

Finding duplicates #

dupfind scan [--no-intra] [--min-mass N] [--min-drift-size N] [--top N] [--format cli|json] [--exclude PATTERN] DIR...

dupfind scan reads every .ml file under the given directories and reports duplicates both across packages and within one package. --no-intra keeps only the duplicates that cross packages.

$ dupfind scan src/lib-a src/lib-b
╭───┬──────────┬──────┬──────────────────┬─────────╮
│ # │ Kind     │ Mass │ Locations        │ Binding │
├───┼──────────┼──────┼──────────────────┼─────────┤
│ 1 │ Exact x2 │   21 │ src/lib-b/b.ml:1 │ encode  │
│   │          │      │ src/lib-a/a.ml:1 │ encode  │
╰───┴──────────┴──────┴──────────────────┴─────────╯

Found 1 exact clone clusters and 0 drift families.

Inspecting the normalised AST #

dupfind hash EXPR

dupfind hash prints the normalised AST and the hash of an OCaml expression given on the command line, which shows what normalisation keeps and what it erases:

$ dupfind hash "let f x = x + 1"
AST:  fun _0 -> + _0 1
Hash: db4909941d07713e84ced7187adab6c8

$ dupfind hash "let g y = y + 1"
AST:  fun _0 -> + _0 1
Hash: db4909941d07713e84ced7187adab6c8

The two bindings produce the same AST because normalisation erases local variable names.

Configuration #

dupfind config init writes a .dupfind.toml holding the defaults in the current directory, and dupfind config show prints the configuration in effect. dupfind scan reads the first .dupfind.toml it finds walking up from the current directory, and a flag on the command line overrides the file.

Options #

Flag Description
--min-mass N Smallest duplicated mass a finding must carry (default: 15)
--min-drift-size N Smallest binding the anti-unification pass compares, in normalised nodes (default: 30); no bound on exact clones
--min-nested-size N Smallest binding nested inside an expression that is indexed at all (default: 6)
--threshold FLOAT Smallest structural overlap of a drift pair, from 0.0 to 1.0 (default: 0.6)
--no-intra Only show cross-package duplicates
--no-exact Skip exact-clone detection
--no-fuzzy Skip anti-unification and report exact clones only
--no-backbone Do not require a shared control-flow node in a drift pair
--no-type-filter Do not require the two bindings of a pair to share a type
--top N Show only the top N findings
--format cli|json Output format
--exclude PATTERN Exclude paths matching a glob