Algorithm Search⌘K

Algorithmcore

Heckel's diff algorithm

Also called Heckel's algorithm.

Link the lines that occur once in each file, then extend the links to equal neighbors. Expected linear time with hashing; it finds moved blocks, but the diff is not minimal.

Time
O(n + r log r) expected
Space
O(n) extra
Where
n = the total number of lines in both files; r = the number of linked line pairs
Properties
not adaptivedeterministicofflineiterative

Heckel's diff algorithm compares two files line by line in six passes over the lines and a hash table of line counts. A line that occurs exactly once in the old file and exactly once in the new file is taken as the same line in both, and each such pair is then extended to the equal lines just before and just after it. The method runs in expected linear time, and because the pairs may cross, it can report a block of lines that moved. It is a heuristic: unlike Myers' algorithm, it does not always find a shortest edit script. Paul Heckel published it in 1978.

In plain words

Compare two versions of a file. First count how often each line occurs in each version. A line that occurs once in the old version and once in the new version is almost surely the same line in both, so tie the two copies together.

A line next to a tied line often belongs with it, even when it is a common line such as a closing brace. So walk down the new file, and when the line after a tied line equals the line after its partner, tie those too. Then do the same walk upward.

The tied lines tell you what stayed. Lines that are not tied were removed or added. Tied lines whose order changed show a block that moved.

The problem

The input is an old file O=⟨O1,…,Om⟩O = \langle O_1, \ldots, O_m \rangle and a new file N=⟨N1,…,Nn⟩N = \langle N_1, \ldots, N_n \rangle, as sequences of lines, where only an equality test and a hash of a line are available. The output is a set of links, pairs (j,i)(j, i) with Oj=NiO_j = N_i where each line is in at most one pair, and from them an edit script of keeps, deletes and inserts that turns OO into NN, plus the blocks of linked lines that moved. The page writes nn for the total number of lines of both files in the cost bounds. The goal is a readable diff in linear time, not a minimum one: Myers' algorithm and the Hunt-Szymanski algorithm solve the minimum problem, the shortest edit script.

The algorithm

Heckel keeps one symbol table entry per distinct line, with a count OCOC of its copies in OO, a count NCNC of its copies in NN, and OLNOOLNO, the number of an old line that holds it. The array NA[0…n+1]NA[0 \ldots n + 1] holds for each new line either its entry (the line is free) or the number of the old line it is linked to; OA[0…m+1]OA[0 \ldots m + 1] is the same for the old file. Index 0 and the last index are a begin line and an end line that Heckel adds to both files.

  1. HECKEL(O[1 .. m], N[1 .. n])
  2. 1T ← an empty hash table of entries (OC, NC, OLNO)
  3. 2for i ← 1 to n do e ← T[N[i]], made if missing; e.NC ← e.NC + 1; NA[i] ← e ▷ pass 1
  4. 3for j ← 1 to m do e ← T[O[j]], made if missing; e.OC ← e.OC + 1; e.OLNO ← j; OA[j] ← e ▷ pass 2
  5. 4NA[0] ← 0; OA[0] ← 0; NA[n + 1] ← m + 1; OA[m + 1] ← n + 1 ▷ link the begin and end lines
  6. 5for i ← 1 to n do ▷ pass 3: lines unique in both
  7. if NA[i] is an entry e with e.NC = 1 and e.OC = 1 then j ← e.OLNO; NA[i] ← j; OA[j] ← i
  8. 6for i ← 0 to n do ▷ pass 4: extend downward
  9. if NA[i] is a line j and NA[i + 1], OA[j + 1] are the same entry then NA[i + 1] ← j + 1; OA[j + 1] ← i + 1
  10. 7for i ← n + 1 downto 1 do ▷ pass 5: extend upward
  11. if NA[i] is a line j and NA[i - 1], OA[j - 1] are the same entry then NA[i - 1] ← j - 1; OA[j - 1] ← i - 1
  12. 8L ← the pairs (NA[i], i) for 1 ≤ i ≤ n where NA[i] is a line ▷ pass 6 starts here
  13. 9K ← a longest subset of L that increases in both coordinates
  14. 10return the script that keeps K, deletes and inserts the rest, and the pairs of L - K grouped into moved blocks

Lines L2 and L3 are Heckel's passes 1 and 2. Line L5 is pass 3: it links the lines that are unique in both files. Lines L6 and L7 are passes 4 and 5: a link from line ii to line jj pulls along the next pair (i+1,j+1)(i + 1, j + 1) if both are still free and equal, and the loop of line L6 runs upward in ii, so a run of equal lines is linked in one sweep. The begin and end lines make the equal first and last lines of the two files act as if they were next to a link. Heckel's pass 6 prints the result from the arrays. Lines L8 to L10 are the version of pass 6 that this page uses to get an edit script: the links may cross, and a script can keep only pairs that do not cross, so line L9 keeps a longest increasing subsequence of them, by patience sorting. This choice of the kept pairs is a design choice of the page, not a step of the paper.

Example

The old file has two functions, f and g, and the new file has the same functions in the other order.

line old OO new NN
1 int f() int g()
2 { {
3 return 1; return 2;
4 } }
5 int g() int f()
6 { {
7 return 2; return 1;
8 } }

The table has six entries. The four lines int f(), return 1;, int g() and return 2; have OC=NC=1OC = NC = 1. The lines { and } have OC=NC=2OC = NC = 2.

step new links (i,j)(i, j), new line ii with old line jj
pass 3 (L5) (1,5)(1, 5) int g(); (3,7)(3, 7) return 2;; (5,1)(5, 1) int f(); (7,3)(7, 3) return 1;
pass 4 (L6), i=1i = 1 NA[2]NA[2] and OA[6]OA[6] both hold the entry of {: link (2,6)(2, 6)
pass 4, i=3i = 3 NA[4]NA[4] and OA[8]OA[8] both hold }: link (4,8)(4, 8)
pass 4, i=5i = 5 link (6,2)(6, 2)
pass 4, i=7i = 7 link (8,4)(8, 4)
pass 5 (L7) no free pairs are left

All 8 lines are linked. In order of the new lines, the old line numbers are 5, 6, 7, 8, 1, 2, 3, 4. A longest increasing subsequence has length 4, and line L9 keeps the f block (1, 2, 3, 4). The result is a script that inserts the four lines of g at the top and deletes the four old lines of g at the bottom, and one moved block: old lines 5 to 8 went to new lines 1 to 4. The script has 8 operations, the minimum here, since a longest common subsequence has 4 lines. A tool that knows the moved block can print "lines 5 to 8 moved to the top" instead of a delete and an insert.

The standard example that the method is not minimal is O=[u,a,a,a,v]O = [u, a, a, a, v] and N=[a,a,a,u,v]N = [a, a, a, u, v]. Pass 3 links uu and vv. The lines next to them are linked already, or they are the begin line, so passes 4 and 5 link no aa. The script keeps uu and vv, inserts three aa lines and deletes three aa lines: 6 operations. The common subsequence a,a,a,va, a, a, v gives 2 operations.

Correctness

The proof file shows an invariant of the arrays: NA[i]=jNA[i] = j exactly when OA[j]=iOA[j] = i, a linked pair has equal lines, and a free cell holds the entry of its own line. Passes 3 to 5 link only two free cells with the same entry, so the invariant holds after each step. From it follow three results. First, the links pair equal lines, each line is in at most one link, and every line that occurs exactly once in each file is linked to its copy. Second, the kept pairs of line L9 increase in both coordinates, so the script of line L10 is valid: applied to OO, it gives NN. Third, when neither file has a repeated line, all common lines are linked and line L9 keeps a longest common subsequence, so the script is a shortest edit script. With repeated lines the third result fails, as the second example shows.

Proof: Heckel's links pair equal lines, and the script built from them turns the old file into the new filefull

We use the pseudocode of the page. The old file is O[1…m]O[1 \ldots m] and the new file is N[1…n]N[1 \ldots n]. Line L4 adds the begin line at index 0 and the end line at index m+1m + 1 of OO and n+1n + 1 of NN. We say that NA[i]NA[i] is linked when it holds a line number, and free when it holds a symbol table entry. The same words apply to OA[j]OA[j].

Invariant (I). After line L4 and after each later step of lines L5 to L7, for all 0≤i≤n+10 \le i \le n + 1 and 0≤j≤m+10 \le j \le m + 1:

  1. NA[i]=jNA[i] = j if and only if OA[j]=iOA[j] = i;
  2. if NA[i]=jNA[i] = j with 1≤i≤n1 \le i \le n, then 1≤j≤m1 \le j \le m and N[i]=O[j]N[i] = O[j];
  3. a free NA[i]NA[i] holds the entry of the text N[i]N[i], and a free OA[j]OA[j] holds the entry of the text O[j]O[j].

Proof. After lines L2 and L3, every NA[i]NA[i] and OA[j]OA[j] with 1≤i≤n1 \le i \le n, 1≤j≤m1 \le j \le m is free and holds the entry of its own text, because the table has one entry for each distinct text. Line L4 links the begin lines to each other and the end lines to each other, so part 1 holds. Parts 2 and 3 hold, since no real line is linked.

Line L5 links NA[i]NA[i] to OA[j]OA[j] only when NA[i]NA[i] is free with an entry ee such that e.NC=e.OC=1e.NC = e.OC = 1, and j=e.OLNOj = e.OLNO. Since e.OC=1e.OC = 1, line L3 met the text of ee at exactly one old line, and e.OLNOe.OLNO is that line, so O[j]=N[i]O[j] = N[i]. Since e.NC=1e.NC = 1, no other new line holds ee, so no other step of line L5 writes OA[j]OA[j]. Lines L2 to L4 link no real line, so OA[j]OA[j] was free before this step. So the step links two free cells with the same text, and keeps (I).

Line L6 links NA[i+1]NA[i + 1] to OA[j+1]OA[j + 1] only when NA[i]=jNA[i] = j and both NA[i+1]NA[i + 1] and OA[j+1]OA[j + 1] are free and hold the same entry. By part 3, N[i+1]=O[j+1]N[i + 1] = O[j + 1]. A free cell is never one of the begin or end lines, so 1≤i+1≤n1 \le i + 1 \le n and 1≤j+1≤m1 \le j + 1 \le m. Both cells were free, so no other link uses them, and part 1 still holds. Line L7 is the same with i−1i - 1 and j−1j - 1. □\square

Theorem 1 (the links). The list LL of line L8 is a set of pairs (j,i)(j, i) with O[j]=N[i]O[j] = N[i], such that each old line and each new line occurs in at most one pair. Each line whose text occurs exactly once in OO and exactly once in NN is in a pair, with its copy in the other file.

Proof. The first sentence is (I), parts 1 and 2. For the second, let the text tt occur once in each file, at O[j]O[j] and N[i]N[i]. Its entry has OC=NC=1OC = NC = 1 and OLNO=jOLNO = j. Before line L5 reaches ii, NA[i]NA[i] is still free: lines L2 to L4 link no real line, and an earlier step of line L5 links only cells that hold another entry. So line L5 links ii and jj, and later steps never unlink a cell. □\square

Theorem 2 (the script). The pairs KK of line L9 are increasing in both coordinates, and the script of line L10 turns OO into NN.

Proof. The pairs of LL come in increasing order of the new line ii, and their old lines jj are distinct by Theorem 1. Line L9 takes a longest strictly increasing subsequence of the old lines, so the chosen pairs increase in both coordinates. Each chosen pair has equal lines by Theorem 1. So KK is a common subsequence of OO and NN, given by its positions. The helper matching_to_script keeps exactly the pairs of KK, deletes every other old line and inserts every other new line, in order. Applying the result to OO gives the kept lines of KK with the new lines between them in their order, which is NN. □\square

Theorem 3 (files without repeated lines). If no text occurs twice in OO and no text occurs twice in NN, the script of line L10 is a shortest edit script.

Proof. Each common text occurs once in each file, so Theorem 1 links all common lines in line L5. No other pair of equal lines exists, so LL is the set of all pairs of equal lines. A common subsequence of OO and NN uses only pairs of equal lines, increasing in both coordinates, so it is an increasing subsequence of LL. Line L9 takes a longest one, so ∣K∣|K| is the length of a longest common subsequence, and the script has the least number of operations, m+n−2∣K∣m + n - 2|K|. □\square

The script is not minimal in general. Take O=[u,a,a,a,v]O = [u, a, a, a, v] and N=[a,a,a,u,v]N = [a, a, a, u, v]. Line L5 links uu and vv. Line L6 at i=0i = 0 compares NA[1]NA[1], the entry of aa, with OA[1]OA[1], which is linked to uu, so it does nothing; at i=4i = 4 and i=5i = 5 the next new cell is linked. Line L7 at i=4i = 4 compares NA[3]NA[3], the entry of aa, with OA[0]OA[0], the begin line, which is linked. So no aa is linked, K={(1,4),(5,5)}K = \{(1, 4), (5, 5)\}, and the script has 10−4=610 - 4 = 6 operations. The common subsequence a,a,a,va, a, a, v gives a script of 2 operations.

Termination and cost. Each of the lines L2, L3, L5, L6 and L7 is one loop over at most n+2n + 2 or m+2m + 2 cells, with a constant number of table operations and cell reads per step. Line L9 runs a patience-pile longest increasing subsequence on r=∣L∣r = |L| pairs, with one binary search per pair. Line L10 is one pass over both files.

Complexity

Count in the word-RAM, with nn the total number of lines of both files and rr the number of links, r≤n/2r \le n / 2.

  • Time. Lines L2 and L3 do one table lookup per line. With a hash table, a lookup costs O(1)O(1) expected time plus the time to hash the line, which is linear in its length, so the passes over the text take expected time linear in the size of the input. Lines L4 to L8 do O(1)O(1) work per line, without hashing, since they compare entries by identity. Line L9 does one binary search per link, O(rlog⁡r)O(r \log r), and line L10 is one pass. In total, O(n+rlog⁡r)O(n + r \log r) expected table operations and steps. Heckel's own pass 6, which prints the links without choosing an increasing subset, keeps the whole method O(n)O(n) expected.
  • Worst case of the table. The linear bound is an expected bound over the hash function. With a balanced search tree in place of the hash table, each lookup costs O(log⁡n)O(\log n) comparisons, and the passes cost O(nlog⁡n)O(n \log n) comparisons of lines.
  • Space. The table has at most nn entries, and the arrays have n+4n + 4 cells in total: O(n)O(n).

Properties

  • Not minimal. The script can be much longer than a shortest one, as the second example shows. The method trusts unique lines and never searches.
  • Finds moves. Links may cross, and the crossing links are blocks that moved. A diff based on a longest common subsequence cannot show a move; it shows a delete and an insert.
  • Linear and simple. Six passes, no dynamic program and no recursion.
  • Greedy extension. Passes 4 and 5 take the first equal neighbor that they meet, in a fixed order, and never undo a link.
  • Symmetric counts. Only the counts OCOC and NCNC decide which lines are unique; the line contents are compared only through the table.

Variants and improvements

  • Patience diff. Patience diff also starts from the lines that are unique in both files, but it keeps only an increasing subset of them, by a longest increasing subsequence, and then recurses into the gaps, so lines between two anchors are matched again with new counts.
  • Histogram diff. Histogram diff uses lines with few copies when no unique line exists, and recurses as patience diff does.
  • Move detection by copies. Tichy's block move method builds the new file from copied blocks of the old file, so it can also express moves and repeated copies, with a different measure of cost.
  • List diffs in user interfaces. Libraries that update a displayed list after a change in the data use Heckel's passes on item identifiers, because they need the moves, and the lists are often free of repeats. DeepDiff for Swift is one such library.

When to use it

Use it when the diff must be fast and must show moved blocks, and when most lines are distinct, for example source files with many distinct statements, or lists of items with unique keys. Do not use it when a minimum diff is required, or when the files have long runs of repeated lines (blank lines, braces, table rows), since such lines can stay unlinked. For a minimum diff use Myers' algorithm.

Pitfalls

  • Begin and end lines. Without the extra links of line L4, equal first lines and equal last lines that are not unique stay unlinked, because passes 4 and 5 need a linked neighbor to start from.
  • The order of pass 4 matters. With O=[{,x,},{,y,}]O = [\{, x, \}, \{, y, \}] and N=[{,y,},{,x,}]N = [\{, y, \}, \{, x, \}], pass 4 links the first braces of both files from the begin line, and links each closing brace from the unique line before it. The second opening brace of each file is then left free, because its neighbors are already linked. The two blocks of three lines are not both found.
  • Crossing links are not a script. An edit script can keep only pairs that increase in both files. Treating all links as kept lines gives an invalid script when a block moved. Choose an increasing subset, as line L9 does, and report the rest as moves.
  • Hash collisions. If the table compares only hash values, two different lines with the same hash are taken as equal. Keep the full line in the entry and compare it.
  • The cost of hashing. The linear time counts a line hash as one step. For very long lines, the time is linear in the total length of the text, not in the number of lines.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

heckel_diff.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heckel-diff/. The authors are listed in prov/T7BYC1.jsonl.
"""Heckel's six-pass difference method (CACM 21(4), 1978).

The old file is a, the new file is b. Heckel calls them O and N. The arrays OA
and NA hold, for each line, either a symbol table entry or the number of the
line that it is linked to in the other file. Index 0 and the index after the
last line are the begin and end lines that the paper adds to both files.
Lines are numbered from 1 inside heckel_links, as in the paper, and the
results use 0-based indices.
"""

from bisect import bisect_left
from collections.abc import Hashable, Sequence

from txdiff import Op, matching_to_script


class _Entry:
    """A symbol table entry: the counts OC and NC and the old line number OLNO."""

    __slots__ = ("oc", "nc", "olno")

    def __init__(self) -> None:
        self.oc = 0
        self.nc = 0
        self.olno = 0


def _same_entry(x: object, y: object) -> bool:
    return isinstance(x, _Entry) and x is y


def heckel_links(a: Sequence[Hashable], b: Sequence[Hashable]) -> list[tuple[int, int]]:
    """Return the linked pairs (i, j) with a[i] == b[j], 0-based, sorted by j. The pairs may cross."""
    m, n = len(a), len(b)
    table: dict[Hashable, _Entry] = {}  # @line L1
    na: list[object] = [None] * (n + 2)
    oa: list[object] = [None] * (m + 2)
    for i in range(1, n + 1):  # @line L2
        entry = table.setdefault(b[i - 1], _Entry())
        entry.nc += 1
        na[i] = entry
    for j in range(1, m + 1):  # @line L3
        entry = table.setdefault(a[j - 1], _Entry())
        entry.oc += 1
        entry.olno = j
        oa[j] = entry
    na[0], oa[0], na[n + 1], oa[m + 1] = 0, 0, m + 1, n + 1  # @line L4
    for i in range(1, n + 1):  # @line L5
        entry = na[i]
        if isinstance(entry, _Entry) and entry.nc == 1 and entry.oc == 1:
            j = entry.olno
            na[i], oa[j] = j, i
    for i in range(0, n + 1):  # @line L6
        j = na[i]
        if isinstance(j, int) and _same_entry(na[i + 1], oa[j + 1]):
            na[i + 1], oa[j + 1] = j + 1, i + 1
    for i in range(n + 1, 0, -1):  # @line L7
        j = na[i]
        if isinstance(j, int) and j >= 1 and _same_entry(na[i - 1], oa[j - 1]):
            na[i - 1], oa[j - 1] = j - 1, i - 1
    links: list[tuple[int, int]] = []
    for i in range(1, n + 1):  # @line L8
        j = na[i]
        if isinstance(j, int):
            links.append((j - 1, i - 1))
    return links


def increasing_pairs(links: Sequence[tuple[int, int]]) -> list[tuple[int, int]]:
    """Return a longest subset of the links that is increasing in both coordinates.

    The links are sorted by their second coordinate, and their first coordinates are
    distinct, so this is a longest increasing subsequence of the first coordinates,
    found with patience piles in O(r log r) time.
    """
    tops: list[int] = []  # the first coordinate on top of each pile
    top_index: list[int] = []  # the index in links of that top
    back: list[int] = [-1] * len(links)
    for t, (i, _) in enumerate(links):
        p = bisect_left(tops, i)
        back[t] = top_index[p - 1] if p > 0 else -1
        if p == len(tops):
            tops.append(i)
            top_index.append(t)
        else:
            tops[p] = i
            top_index[p] = t
    out: list[tuple[int, int]] = []
    t = top_index[-1] if top_index else -1
    while t >= 0:
        out.append(links[t])
        t = back[t]
    out.reverse()
    return out


def moved_blocks(links: Sequence[tuple[int, int]],
                 kept: Sequence[tuple[int, int]]) -> list[tuple[int, int, int]]:
    """Group the links that are not kept into blocks (i, j, length) of consecutive lines."""
    keep = set(kept)
    blocks: list[tuple[int, int, int]] = []
    for i, j in links:
        if (i, j) in keep:
            continue
        if blocks:
            bi, bj, length = blocks[-1]
            if bi + length == i and bj + length == j:
                blocks[-1] = (bi, bj, length + 1)
                continue
        blocks.append((i, j, 1))
    return blocks


def heckel_diff(a: Sequence[Hashable], b: Sequence[Hashable]) -> tuple[list[Op], list[tuple[int, int, int]]]:
    """Return an edit script from a to b and the moved blocks (i, j, length) that it shows as delete and insert."""
    links = heckel_links(a, b)
    kept = increasing_pairs(links)  # @line L9
    return matching_to_script(a, b, kept), moved_blocks(links, kept)  # @line L10
txdiff.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Common parts of the diff and merge pages: lines, edit scripts, the LCS matcher and a unified diff printer.

An edit script turns a sequence a into a sequence b. It is a list of Op values in
order. Each Op has a kind, an index i into a, an index j into b, and the item:

- Op(KEEP, i, j, a[i]): a[i] is kept, and it is b[j];
- Op(DELETE, i, j, a[i]): a[i] is deleted; j is the number of items of b made so far;
- Op(INSERT, i, j, b[j]): b[j] is inserted; i is the number of items of a used so far.

A matching is a list of pairs (i, j), increasing in both coordinates, of items
that the script keeps. The named algorithms of the pages are not in this file.
"""

from collections.abc import Callable, Sequence
from typing import Any, NamedTuple

KEEP = "="
DELETE = "-"
INSERT = "+"


class Op(NamedTuple):
    kind: str
    i: int
    j: int
    item: Any


def split_lines(text: str) -> list[str]:
    """Split text at each "\\n" into lines without the line feed; a final line feed adds no empty line."""
    if text == "":
        return []
    lines = text.split("\n")
    if lines[-1] == "":
        lines.pop()
    return lines


def is_matching(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]],
                eq: Callable[[Any, Any], bool] | None = None) -> bool:
    """Return True if pairs is strictly increasing in both coordinates and each pair is equal by eq."""
    eq = eq if eq is not None else (lambda x, y: x == y)
    pi, pj = -1, -1
    for i, j in pairs:
        if not (pi < i < len(a) and pj < j < len(b)) or not eq(a[i], b[j]):
            return False
        pi, pj = i, j
    return True


def lcs_matching(a: Sequence[Any], b: Sequence[Any],
                 eq: Callable[[Any, Any], bool] | None = None) -> list[tuple[int, int]]:
    """Return a longest matching of a and b by the O(n m) dynamic program.

    eq(x, y) decides whether x and y may be matched; the default is ==. Ties go to
    the earliest pair, so the result is fixed for given inputs.
    """
    eq = eq if eq is not None else (lambda x, y: x == y)
    n, m = len(a), len(b)
    # length[i][j] is the length of a longest matching of a[i:] and b[j:].
    length = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n - 1, -1, -1):
        row, below = length[i], length[i + 1]
        ai = a[i]
        for j in range(m - 1, -1, -1):
            if eq(ai, b[j]):
                row[j] = below[j + 1] + 1
            else:
                row[j] = below[j] if below[j] >= row[j + 1] else row[j + 1]
    pairs: list[tuple[int, int]] = []
    i = j = 0
    while i < n and j < m:
        if eq(a[i], b[j]):
            pairs.append((i, j))
            i += 1
            j += 1
        elif length[i + 1][j] >= length[i][j + 1]:
            i += 1
        else:
            j += 1
    return pairs


def matching_to_script(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]]) -> list[Op]:
    """Return the edit script that keeps the pairs; in each gap the deletes come before the inserts."""
    script: list[Op] = []
    i = j = 0
    for pi, pj in list(pairs) + [(len(a), len(b))]:
        if pi < i or pj < j:
            raise ValueError("the pairs are not increasing")
        while i < pi:
            script.append(Op(DELETE, i, j, a[i]))
            i += 1
        while j < pj:
            script.append(Op(INSERT, i, j, b[j]))
            j += 1
        if pi < len(a) and pj < len(b):
            script.append(Op(KEEP, i, j, a[i]))
            i += 1
            j += 1
    return script


def script_matching(script: Sequence[Op]) -> list[tuple[int, int]]:
    """Return the pairs (i, j) that the script keeps."""
    return [(op.i, op.j) for op in script if op.kind == KEEP]


def apply_script(a: Sequence[Any], script: Sequence[Op]) -> list[Any]:
    """Apply the script to a and return the new sequence; raise ValueError if the script does not fit a."""
    out: list[Any] = []
    i = 0
    for op in script:
        if op.kind == INSERT:
            if op.i != i or op.j != len(out):
                raise ValueError(f"bad insert {op}")
            out.append(op.item)
        elif op.kind in (KEEP, DELETE):
            if op.i != i or i >= len(a) or op.item != a[i] or op.j != len(out):
                raise ValueError(f"bad {op.kind} {op}")
            if op.kind == KEEP:
                out.append(a[i])
            i += 1
        else:
            raise ValueError(f"unknown kind {op.kind!r}")
    if i != len(a):
        raise ValueError("the script does not use all of a")
    return out


def is_valid_script(a: Sequence[Any], b: Sequence[Any], script: Sequence[Op]) -> bool:
    """Return True if the script fits a and turns a into b."""
    try:
        return apply_script(a, script) == list(b)
    except ValueError:
        return False


def script_cost(script: Sequence[Op]) -> int:
    """Return the number of deletes and inserts of the script."""
    return sum(1 for op in script if op.kind != KEEP)


def _opcodes(script: Sequence[Op]) -> list[tuple[str, int, int, int, int]]:
    """Group the script into runs in the format of difflib: equal, delete, insert or replace."""
    codes: list[tuple[str, int, int, int, int]] = []
    i = j = 0
    k = 0
    while k < len(script):
        i1, j1 = i, j
        if script[k].kind == KEEP:
            while k < len(script) and script[k].kind == KEEP:
                i, j, k = i + 1, j + 1, k + 1
            codes.append(("equal", i1, i, j1, j))
        else:
            while k < len(script) and script[k].kind != KEEP:
                if script[k].kind == DELETE:
                    i += 1
                else:
                    j += 1
                k += 1
            tag = "replace" if i > i1 and j > j1 else ("delete" if i > i1 else "insert")
            codes.append((tag, i1, i, j1, j))
    return codes


def _range(start: int, stop: int) -> str:
    length = stop - start
    first = start + 1
    if length == 1:
        return f"{first}"
    if length == 0:
        first -= 1
    return f"{first},{length}"


def unified_diff(a: Sequence[str], b: Sequence[str], script: Sequence[Op], context: int = 3,
                 from_name: str = "a", to_name: str = "b") -> list[str]:
    """Return the lines of a unified diff of the script, without line feeds, in the layout of GNU diff -u.

    The hunks are grouped as difflib.unified_diff groups them, so for the same
    matching the output is the same. If the script changes nothing, the result is [].
    """
    codes = _opcodes(script)
    if not codes:
        codes = [("equal", 0, 1, 0, 1)]
    n = context
    if codes[0][0] == "equal":
        tag, i1, i2, j1, j2 = codes[0]
        codes[0] = (tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2)
    if codes[-1][0] == "equal":
        tag, i1, i2, j1, j2 = codes[-1]
        codes[-1] = (tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))
    groups: list[list[tuple[str, int, int, int, int]]] = []
    group: list[tuple[str, int, int, int, int]] = []
    for tag, i1, i2, j1, j2 in codes:
        if tag == "equal" and i2 - i1 > 2 * n:
            group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)))
            groups.append(group)
            group = []
            i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
        group.append((tag, i1, i2, j1, j2))
    if group and not (len(group) == 1 and group[0][0] == "equal"):
        groups.append(group)
    out: list[str] = []
    for group in groups:
        if not out:
            out += [f"--- {from_name}", f"+++ {to_name}"]
        first, last = group[0], group[-1]
        out.append(f"@@ -{_range(first[1], last[2])} +{_range(first[3], last[4])} @@")
        for tag, i1, i2, j1, j2 in group:
            if tag == "equal":
                out += [" " + line for line in a[i1:i2]]
                continue
            if tag in ("replace", "delete"):
                out += ["-" + line for line in a[i1:i2]]
            if tag in ("replace", "insert"):
                out += ["+" + line for line in b[j1:j2]]
    return out
test_heckel_diff.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heckel-diff/. The authors are listed in prov/T7BYC1.jsonl.
# This file also tests the shared helper txdiff.py, whose reference copy is in this folder.

import difflib
import itertools
import random
from collections import Counter

from heckel_diff import heckel_diff, heckel_links, increasing_pairs
from txdiff import (DELETE, INSERT, KEEP, Op, apply_script, is_matching, is_valid_script, lcs_matching,
                    matching_to_script, script_cost, script_matching, split_lines, unified_diff)


def lcs_brute(a, b):
    for r in range(min(len(a), len(b)), -1, -1):
        for ia in itertools.combinations(range(len(a)), r):
            sub = [a[i] for i in ia]
            for jb in itertools.combinations(range(len(b)), r):
                if sub == [b[j] for j in jb]:
                    return r
    return 0


def test_helper_split_and_apply() -> None:
    assert split_lines("") == []
    assert split_lines("x\n") == ["x"]
    assert split_lines("x\ny") == ["x", "y"]
    assert split_lines("\n\n") == ["", ""]
    assert unified_diff([], [], []) == []
    assert not is_valid_script("ab", "b", [Op(KEEP, 0, 0, "a"), Op(DELETE, 1, 1, "b")])
    assert apply_script("ab", [Op(DELETE, 0, 0, "a"), Op(KEEP, 1, 0, "b"), Op(INSERT, 2, 1, "c")]) == ["b", "c"]


def test_helper_against_brute_force_and_difflib() -> None:
    rng = random.Random(5)
    for _ in range(300):
        a = [rng.choice("abc") for _ in range(rng.randint(0, 6))]
        b = [rng.choice("abc") for _ in range(rng.randint(0, 6))]
        pairs = lcs_matching(a, b)
        assert is_matching(a, b, pairs)
        assert len(pairs) == lcs_brute(a, b)
        s = matching_to_script(a, b, pairs)
        assert is_valid_script(a, b, s)
        assert script_matching(s) == pairs
        assert script_cost(s) == len(a) + len(b) - 2 * len(pairs)
        sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
        dp = [(blk.a + t, blk.b + t) for blk in sm.get_matching_blocks() for t in range(blk.size)]
        for n in (0, 1, 3):
            assert unified_diff(a, b, matching_to_script(a, b, dp), n) == list(
                difflib.unified_diff(a, b, "a", "b", lineterm="", n=n))


def test_check_value_is_not_minimal() -> None:
    a, b = list("uaaav"), list("aaauv")
    assert heckel_links(a, b) == [(0, 3), (4, 4)]
    script, moved = heckel_diff(a, b)
    assert is_valid_script(a, b, script)
    assert script_cost(script) == 6
    assert moved == []
    assert len(a) + len(b) - 2 * len(lcs_matching(a, b)) == 2


def test_moved_function() -> None:
    old = ["int f()", "{", "return 1;", "}", "int g()", "{", "return 2;", "}"]
    new = old[4:] + old[:4]
    assert heckel_links(old, new) == [(4, 0), (5, 1), (6, 2), (7, 3), (0, 4), (1, 5), (2, 6), (3, 7)]
    script, moved = heckel_diff(old, new)
    assert is_valid_script(old, new, script)
    assert moved == [(4, 0, 4)]
    assert script_cost(script) == 8


def test_passes_four_and_five_extend_runs() -> None:
    # The braces are not unique. Pass 4 links the first braces from the begin line, then
    # each closing brace from the unique line before it. The second opening braces stay unlinked.
    old = ["{", "x", "}", "{", "y", "}"]
    new = ["{", "y", "}", "{", "x", "}"]
    assert heckel_links(old, new) == [(0, 0), (4, 1), (5, 2), (1, 4), (2, 5)]
    script, moved = heckel_diff(old, new)
    assert script_cost(script) == 6 and moved == [(4, 1, 2)]
    # Equal first and last lines are linked from the begin and end lines.
    assert heckel_links(list("aab"), list("aac")) == [(0, 0), (1, 1)]
    assert heckel_links(list("baa"), list("caa")) == [(1, 1), (2, 2)]


def test_random_properties() -> None:
    rng = random.Random(7)
    for _ in range(400):
        alpha = "abcdefgh"[: rng.randint(1, 8)]
        a = [rng.choice(alpha) for _ in range(rng.randint(0, 9))]
        b = [rng.choice(alpha) for _ in range(rng.randint(0, 9))]
        links = heckel_links(a, b)
        assert all(a[i] == b[j] for i, j in links)
        assert len({i for i, _ in links}) == len(links) == len({j for _, j in links})
        ca, cb = Counter(a), Counter(b)
        for j, x in enumerate(b):
            if ca[x] == 1 and cb[x] == 1:
                assert (a.index(x), j) in links
        kept = increasing_pairs(links)
        assert is_matching(a, b, kept)
        script, _ = heckel_diff(a, b)
        assert is_valid_script(a, b, script)
        assert script_cost(script) >= len(a) + len(b) - 2 * len(lcs_matching(a, b))


def test_permutations_are_minimal() -> None:
    # When every line occurs once in each file, all lines are linked and the kept pairs are an LCS.
    rng = random.Random(11)
    for n in range(0, 9):
        for _ in range(20):
            a = list(range(n))
            b = a[:]
            rng.shuffle(b)
            script, _ = heckel_diff(a, b)
            assert script_cost(script) == 2 * n - 2 * len(lcs_matching(a, b))

History

Paul Heckel, then at Interactive Systems Consultants, published the method in Communications of the ACM in 1978. He presented it as a fast and simple alternative to the method of the Unix diff program of Hunt and McIlroy (1976), which computes a longest common subsequence of the lines. The same idea of unique lines as anchors came back in Bram Cohen's patience diff, and the passes are used today in list diff libraries.

References

  1. Paul Heckel, A technique for isolating differences between files, Communications of the ACM 21(4), 1978, 264-268, the six passes, the symbol table entries with the counters OC and NC and the old line number OLNO, the arrays OA and NA, and the begin and end lines of Fig. 1
  2. J. W. Hunt and M. D. McIlroy, An algorithm for differential file comparison, Computing Science Technical Report 41, Bell Laboratories, 1976, the diff program based on a longest common subsequence of lines, the method that Heckel compares with
  3. Eugene W. Myers, An O(ND) difference algorithm and its variations, Algorithmica 1, 1986, 251-266, the shortest edit script, the minimum that Heckel's method does not always reach
  4. DeepDiff, a Swift library for collection diffs, Sources/Shared/Algorithms/Heckel.swift

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example