Algorithm Search⌘K

Algorithmcore

diff3 algorithm

Also called diff3 merge.

Merge by diffing the ancestor with each version, splitting the files into stable and unstable chunks, and taking the side that changed in each chunk.

Time
O(n^2) worst
Space
O(n^2) extra
Where
n = the total number of lines of the three files
Properties
deterministicofflineiterative

diff3 is the standard method for a three-way merge of text files. It compares the common ancestor OO with each of the two versions AA and BB, using a line diff such as Myers' algorithm, and gets two matchings of equal lines. A line of OO that is matched in both versions is stable. One pass over the three files cuts them into stable chunks, where all three agree, and unstable chunks between them. In each unstable chunk the merge takes the side that changed, or the common change if both changed it in the same way, and it marks a conflict where the two sides changed it in different ways. It is the method of the GNU diff3 program, and version control systems such as CVS and Subversion use it to merge files. Khanna, Kunal and Pierce wrote it as a precise algorithm in 2007 and showed that it has fewer of the expected properties than its users believe.

In plain words

Two people edit copies of the same file. To merge their work, compare the original with each copy, line by line.

Some lines are still in both copies, in their places. They are anchors. Between two anchors there is a gap, and in each gap you look at three small pieces: the original, the first copy and the second copy.

If the piece of one copy is the same as the original, only the other person changed this part, so you take their version. If both copies have the same new text, you take it. If all three pieces are different, both people changed the same part in different ways. That is a conflict, and the merge writes both versions, with the original, between marker lines, so that a person can choose.

The problem

The input is a base OO and two versions AA and BB, each a sequence of lines, and two matchings: MAM_A pairs lines of OO with equal lines of AA, and MBM_B pairs lines of OO with equal lines of BB, each strictly increasing in both files. Usually each matching is a longest common subsequence, from a shortest edit script. For a line xx of OO that has a partner in both, let a(x)a(x) and b(x)b(x) be its partners; the triple (x,a(x),b(x))(x, a(x), b(x)) is then a stable point. The output is the merged file, with the stable lines, the changes of each side, and a marked region for each conflict.

The algorithm

The indices lOl_O, lAl_A and lBl_B are the first lines of the three files that no chunk has taken yet.

  1. DIFF3(A, O, B, M_A, M_B)
  2. 1l_O ← 0; l_A ← 0; l_B ← 0; P ← an empty list of chunks
  3. 2loop: i ← 1; while (l_O + i - 1, l_A + i - 1, l_B + i - 1) is a stable point do i ← i + 1
  4. 3if i = 1 then x ← the least line x ≥ l_O of O with partners in both; if there is none, leave the loop
  5. 4append the unstable chunk (A[l_A .. a(x) - 1], O[l_O .. x - 1], B[l_B .. b(x) - 1]) to P; (l_O, l_A, l_B) ← (x, a(x), b(x))
  6. 5else append the stable chunk of the next i - 1 lines of each file to P; add i - 1 to l_O, l_A and l_B
  7. 6if some lines are left, append the rest of the three files to P as an unstable chunk
  8. 7for each chunk (A_i, O_i, B_i) of P: if it is stable, or O_i = B_i, or A_i = B_i, output A_i; else if O_i = A_i, output B_i; else output a conflict region
  9. 8return the output and the number of conflicts

Lines L1 to L6 are Figure 2 of Khanna, Kunal and Pierce, with indices from 0. Line L7 is the merge rule. Khanna, Kunal and Pierce name the classes of an unstable chunk: changed in A if Oi=Bi≠AiO_i = B_i \ne A_i, changed in B if Oi=Ai≠BiO_i = A_i \ne B_i, falsely conflicting if Ai=Bi≠OiA_i = B_i \ne O_i, and truly conflicting if the three pieces are all different. A conflict region is written in the diff3 style of Git:

<<<<<<< A
the lines of A_i
||||||| O
the lines of O_i
=======
the lines of B_i
>>>>>>> B

The implementation takes both matchings from the shared helper, a longest common subsequence by dynamic programming, or from the caller. It also returns the three new versions A′A', O′O' and B′B' of the paper, in which a chunk that changed on one side is copied to all three.

Example

This is Figure 1 of Khanna, Kunal and Pierce. Let A=[1,4,5,2,3,6]A = [1, 4, 5, 2, 3, 6], O=[1,2,3,4,5,6]O = [1, 2, 3, 4, 5, 6] and B=[1,2,4,5,3,6]B = [1, 2, 4, 5, 3, 6]. GNU diff3 matches the lines 1, 2, 3, 6 of OO with AA, and the lines 1, 2, 4, 5, 6 of OO with BB. The stable points are the lines 1, 2 and 6 of OO.

chunk AiA_i OiO_i BiB_i class merge
1 1 1 1 stable 1
2 4, 5 changed in A 4, 5
3 2 2 2 stable 2
4 3 3, 4, 5 4, 5, 3 truly conflicting conflict region
5 6 6 6 stable 6

So the merge is 1, 4, 5, 2, then a conflict that shows [3][3], [3,4,5][3, 4, 5] and [4,5,3][4, 5, 3], then 6. In the form of the paper the output is A′=[1,4,5,2,3,6]A' = [1, 4, 5, 2, 3, 6], O′=[1,4,5,2,3,4,5,6]O' = [1, 4, 5, 2, 3, 4, 5, 6] and B′=[1,4,5,2,4,5,3,6]B' = [1, 4, 5, 2, 4, 5, 3, 6].

The matching of OO with AA is not unique: 1, 4, 5, 6 is also a longest common subsequence, and the helper of this page picks it. Then the stable points are 1, 4, 5 and 6, and the merge has two conflicts, ([ ],[2,3],[2])([\,], [2, 3], [2]) and ([2,3],[ ],[3])([2, 3], [\,], [3]). The same three files give a different merge with a different diff.

Correctness

The proof file shows that lines L1 to L6 return a diff3 parse, the definition of Khanna, Kunal and Pierce: the chunks cut the three files into consecutive pieces, every stable point lies in a stable chunk at the same place in its three pieces, and each stable chunk is as large as possible. The key fact is an invariant: every stable point that is not yet in a stable chunk lies after lOl_O, lAl_A and lBl_B in the three files, because the matchings increase. Line L3 takes the least such point, so no stable point falls inside an unstable chunk. Each round takes at least one line, so the loop ends. The proof then shows that the merge rule does what it should when only one side changed the file: if A=OA = O, the merge is BB, and if B=OB = O, the merge is AA, both without a conflict.

Proof: The chunk pass gives a diff3 parse, and the merge keeps the change of a side that alone changed the filefull

We use the pseudocode of the page, with indices from 0. The inputs are the base OO, the versions AA and BB, and two matchings: MAM_A, a set of pairs (x,y)(x, y) with O[x]=A[y]O[x] = A[y], and MBM_B, a set of pairs (x,z)(x, z) with O[x]=B[z]O[x] = B[z], each strictly increasing in both coordinates. Since MAM_A is increasing, a line xx of OO has at most one partner a(x)a(x) in AA, and in the same way at most one partner b(x)b(x) in BB. A triple is (x,a(x),b(x))(x, a(x), b(x)) for a line xx of OO that is matched in both. A stable chunk with starts (o,p,q)(o, p, q) and length k≥1k \ge 1 is one where (o+t,p+t,q+t)(o + t, p + t, q + t) is a triple for each t<kt < k.

Khanna, Kunal and Pierce call a list of chunks a diff3 parse if the chunks cut AA, OO and BB into consecutive pieces, (I) every triple lies in some stable chunk, at the same offset in its three pieces, and (II) each stable chunk is as large as possible.

Lemma 1 (invariant). At line L2, the chunks emitted so far cut A[0…lA−1]A[0 \ldots l_A - 1], O[0…lO−1]O[0 \ldots l_O - 1] and B[0…lB−1]B[0 \ldots l_B - 1] into consecutive pieces, and every triple (x,y,z)(x, y, z) has one of two forms: x<lOx < l_O and the triple lies in an emitted stable chunk, or x≥lOx \ge l_O, y≥lAy \ge l_A and z≥lBz \ge l_B.

Proof. At line L1 nothing is emitted and lO=lA=lB=0l_O = l_A = l_B = 0, so every triple has the second form. Assume the invariant at line L2.

A stable chunk. Lines L2 and L5 find the largest k=i−1≥1k = i - 1 \ge 1 such that (lO+t,lA+t,lB+t)(l_O + t, l_A + t, l_B + t) is a triple for each t<kt < k, and emit these lines as a stable chunk. A triple with lO≤x<lO+kl_O \le x < l_O + k is the one of the line xx, because each line has at most one partner on each side, so it lies in this chunk. A triple with x≥lO+kx \ge l_O + k comes after the triple of lO+k−1l_O + k - 1 in both increasing matchings, so y≥lA+ky \ge l_A + k and z≥lB+kz \ge l_B + k. The new values of lOl_O, lAl_A, lBl_B are these sums, so the invariant holds.

An unstable chunk. If i=1i = 1, line L3 takes the least line x≥lOx \ge l_O of OO that is matched in both. Its triple has the second form, so a(x)≥lAa(x) \ge l_A and b(x)≥lBb(x) \ge l_B, and line L4 emits the pieces A[lA…a(x)−1]A[l_A \ldots a(x) - 1], O[lO…x−1]O[l_O \ldots x - 1] and B[lB…b(x)−1]B[l_B \ldots b(x) - 1], which follow the earlier pieces. No triple has its first index in [lO,x)[l_O, x), by the choice of xx, and the triples at xx and after keep the second form for the new values xx, a(x)a(x), b(x)b(x). So the invariant holds. □\square

Lemma 2 (progress). Each round of the loop emits a nonempty chunk and increases lO+lA+lBl_O + l_A + l_B. So the loop ends.

Proof. A stable chunk has k≥1k \ge 1 lines in each piece. For an unstable chunk, all three pieces are empty only if x=lOx = l_O, a(x)=lAa(x) = l_A and b(x)=lBb(x) = l_B, but then (lO,lA,lB)(l_O, l_A, l_B) is a triple, and line L2 would have found i>1i > 1. The sum is at most ∣A∣+∣O∣+∣B∣|A| + |O| + |B|. □\square

Theorem 1 (a diff3 parse). The chunks returned by the parse form a diff3 parse of AA, OO and BB with respect to MAM_A and MBM_B.

Proof. The loop stops at line L3 when no line x≥lOx \ge l_O is matched in both. Line L6 then emits the rest of the three files as one chunk if it is not empty, so by Lemma 1 the chunks cut the three files into consecutive pieces. When the loop stops, no triple has the second form of Lemma 1, so every triple lies in a stable chunk, at the same offset in its three pieces: this is (I).

For (II), take a stable chunk with starts (o,p,q)(o, p, q) and length kk. It cannot grow at the end: line L2 stopped because (o+k,p+k,q+k)(o + k, p + k, q + k) is not a triple, so a chunk that follows starts with an unstable chunk or nothing. It cannot grow at the start either. If it is the first chunk, then o=p=q=0o = p = q = 0. Otherwise the chunk before it is unstable, because a stable chunk is never followed by another one, and it was made at line L4 with the least line x=o≥lOx = o \ge l_O that is matched in both. If (o−1,p−1,q−1)(o - 1, p - 1, q - 1) were a triple, then o−1<lOo - 1 < l_O by the choice of xx, so o=lO≥1o = l_O \ge 1. An unstable chunk ends at a triple, so the next round emits a stable chunk; so the chunk before this unstable chunk is stable, and the triple of lO−1l_O - 1 is its last one, (lO−1,lA−1,lB−1)(l_O - 1, l_A - 1, l_B - 1). Then p=lAp = l_A and q=lBq = l_B, and the unstable chunk would be empty, against Lemma 2. □\square

Classes. Each unstable chunk gets one class from its three pieces (Ai,Oi,Bi)(A_i, O_i, B_i): changed in AA if Oi=Bi≠AiO_i = B_i \ne A_i, changed in BB if Oi=Ai≠BiO_i = A_i \ne B_i, falsely conflicting if Ai=Bi≠OiA_i = B_i \ne O_i, and truly conflicting if all three differ. The code adds one more class, unchanged, for Ai=Oi=BiA_i = O_i = B_i. This class is empty when MAM_A and MBM_B are maximum: the pairs of MAM_A that start in OiO_i end in AiA_i, because the chunk borders are triples, so the part of MAM_A in the chunk is a maximum matching of OiO_i and Ai=OiA_i = O_i, and so it is the identity. The same holds for MBM_B, so the first line of the chunk would start a triple at the start of the three pieces, and the chunk would be stable.

Theorem 2 (the merge rule). The merge takes the stable chunks, AiA_i for a chunk that is changed in AA, falsely conflicting or unchanged, and BiB_i for a chunk that is changed in BB; it marks the truly conflicting chunks. As a result:

  1. If A=OA = O and MAM_A is a maximum matching, the merge is BB, with no conflict, for any MBM_B.
  2. If B=OB = O and MBM_B is a maximum matching, the merge is AA, with no conflict, for any MAM_A.
  3. If A=BA = B and MA=MBM_A = M_B, the merge is AA, with no conflict.

Proof. The first sentence is lines L7 and L8. For part 1, a maximum matching of OO with itself has ∣O∣|O| increasing pairs, so it is the identity. Then lA=lOl_A = l_O at each round: a stable chunk adds the same length to both, and an unstable chunk sets lA=a(x)=x=lOl_A = a(x) = x = l_O. So Ai=OiA_i = O_i in every chunk, and each chunk is stable, unchanged or changed in BB. In each case the merge takes a piece equal to BiB_i, and by Theorem 1 the pieces BiB_i, in order, make BB. Part 2 is the same with the two sides swapped. For part 3, MA=MBM_A = M_B gives a(x)=b(x)a(x) = b(x) for each xx, so lA=lBl_A = l_B at each round and Ai=BiA_i = B_i in every chunk. Each chunk is then stable, unchanged or falsely conflicting, and the merge takes AiA_i. □\square

Output triples. The function for the outputs (A′,O′,B′)(A', O', B') of the paper writes (Ai,Ai,Ai)(A_i, A_i, A_i) for a chunk that is changed in AA, (Bi,Bi,Bi)(B_i, B_i, B_i) for a chunk that is changed in BB, and (Ai,Oi,Bi)(A_i, O_i, B_i) for the other chunks, which is the definition of the output of a chunk.

Cost. By Lemma 2 there are at most ∣A∣+∣O∣+∣B∣|A| + |O| + |B| rounds. Line L2 tests ii triples and the round moves lOl_O by i−1i - 1. Line L3 scans the lines lOl_O to xx and the round moves lOl_O to xx, so each line of OO is scanned at most twice over all rounds. With hash sets for the matchings, each test takes expected O(1)O(1) time, and the copies of the pieces take O(∣A∣+∣O∣+∣B∣)O(|A| + |O| + |B|) in total. So the chunk pass is expected linear. The two matchings of the shared helper cost O(∣O∣ ∣A∣+∣O∣ ∣B∣)O(|O| \, |A| + |O| \, |B|).

Complexity

Let nn be the total number of lines of the three files, and count in the word-RAM with lines compared in O(1)O(1), for example by a hash of each line.

  • The chunk pass. Each line of OO is tested at most twice in lines L2 and L3, and each line of each file is copied once, so lines L1 to L8 take O(n)O(n) expected time with hash sets for the matchings.
  • The matchings. Two line diffs dominate. With the dynamic program of the helper they cost O(n2)O(n^2) time and space. With Myers' algorithm they cost O(nD)O(n D) time, where DD is the size of the larger edit script, and O(n)O(n) space in the linear space version.

Properties

  • One side unchanged. If A=OA = O, the merge is BB, and if B=OB = O, it is AA, for any maximum matchings. If A=BA = B and both use the same matching, the merge is AA.
  • Depends on the matchings. Two longest matchings can give different chunks and different conflicts, as in the example.
  • Not idempotent. Figure 4 of Khanna, Kunal and Pierce: for A=[1,2,4,6,8]A = [1, 2, 4, 6, 8], O=[1,2,3,4,5,5,5,6,7,8]O = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8] and B=[1,4,5,5,5,6,2,3,4,8]B = [1, 4, 5, 5, 5, 6, 2, 3, 4, 8], where each pair has one maximum matching, a run gives A′=[1,2,4,6,8]A' = [1, 2, 4, 6, 8], O′=[1,2,3,4,6,7,8]O' = [1, 2, 3, 4, 6, 7, 8] and B′=[1,4,6,2,3,4,8]B' = [1, 4, 6, 2, 3, 4, 8], and a second run on these changes them again, to [1,4,6,2,4,6,8][1, 4, 6, 2, 4, 6, 8], [1,4,6,2,4,6,7,8][1, 4, 6, 2, 4, 6, 7, 8] and [1,4,6,2,4,8][1, 4, 6, 2, 4, 8].
  • Not local. Figure 3: let O=(1,2)n 1,2O = (1, 2)^n\, 1, 2, let AA add 1,21, 2 at the start and BB replace the last 1,21, 2 by 33. The two edits are far apart for large nn, yet with a maximum matching that shifts AA by one period the last chunk is a conflict, for every nn.
  • Safe inputs. Theorem 4.1.1: cut OO into a start, a middle and an end. If at most one side changes the start, at most one side changes the end, no side changes the middle, and the middle has a line that occurs exactly once in each of the three files, the merge is unique and has no conflict. A unique line such as a function header often plays this role in source code.
  • Not stable. Khanna, Kunal and Pierce also show that similar inputs can give very different outputs, even without conflicts.

Variants and improvements

  • Conflict styles. The RCS merge style, the default of Git, shows only AiA_i and BiB_i. The diff3 style adds OiO_i after a ||||||| marker. The zdiff3 style of Git also moves the equal lines at the start and end of a conflict out of the region.
  • The diff used. The matchings can come from any line diff, such as patience diff or histogram diff, which match unique or rare lines first and so often give anchors that people expect.
  • Structure. Semistructured merge parses the files into declarations and runs a diff3 merge only inside method bodies, and tree merges use a tree diff such as Chawathe's change detection.
  • Operations instead of states. Editors for live collaboration merge each edit as it happens, with operational transformation or a CRDT, and never show a conflict.

When to use it

Use diff3 to merge two versions of a text file that have a known common ancestor, as version control systems do. It is simple, fast and easy to explain, and its conflict regions are what most programmers know. When the files have structure that a line merge does not respect, such as declarations whose order does not matter, use a structured or semistructured merge. For edits that arrive one at a time from many users, use operational transformation.

Pitfalls

  • Adjacent edits conflict. If AA changes one line and BB changes the next line, no stable point lies between them, and the chunk is a conflict: O=[a,b]O = [a, b], A=[x,b]A = [x, b] and B=[a,y]B = [a, y] give one conflict. With one stable line between the edits there is no conflict.
  • False conflicts are taken without a note. If both sides made the same change, the merge takes it once. This is right in most cases, but if both sides added the same line for different reasons, one copy is lost.
  • The matchings are part of the input. A different diff, or another version of the same diff, can give different conflicts. Tests must fix the matchings or the diff.
  • A clean merge is not a correct program. diff3 sees lines, not meaning. Two changes without a conflict can still break the program together, for example when one side renames a function and the other side adds a call to its old name.
  • Marker lines in the data. A file that already has lines such as ======= makes the conflict regions hard to read and to parse again.

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.

diff3.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diff3/. The authors are listed in prov/8YT0S8.jsonl.
"""The diff3 merge, after the algorithm of Khanna, Kunal and Pierce (FSTTCS 2007, Figure 2).

The inputs are the base o and the two versions a and b. The matchings ma (pairs
(i, j) with o[i] == a[j]) and mb (pairs (i, j) with o[i] == b[j]) are increasing
lists; by default each one is a longest matching from the shared helper. The
parse cuts the three files into stable chunks, where all three agree line by
line, and unstable chunks between them. Indices are 0-based; the paper counts
from 1.
"""

from collections.abc import Hashable, Sequence
from typing import NamedTuple

from txdiff import is_matching, lcs_matching

STABLE = "stable"
CHANGED_A = "changed in A"
CHANGED_B = "changed in B"
FALSE_CONFLICT = "falsely conflicting"
CONFLICT = "truly conflicting"
UNCHANGED = "unchanged"  # an unstable chunk with three equal pieces; only matchings that are not maximum give it


class Chunk(NamedTuple):
    kind: str
    a: list
    o: list
    b: list


def _classify(a: list, o: list, b: list) -> str:
    if a == o == b:
        return UNCHANGED
    if o == b and o != a:
        return CHANGED_A
    if o == a and o != b:
        return CHANGED_B
    if a == b and a != o:
        return FALSE_CONFLICT
    return CONFLICT


def diff3_parse(a: Sequence[Hashable], o: Sequence[Hashable], b: Sequence[Hashable],
                ma: Sequence[tuple[int, int]] | None = None,
                mb: Sequence[tuple[int, int]] | None = None) -> list[Chunk]:
    """Return the chunks of the diff3 parse of (a, o, b) for the matchings ma and mb."""
    ma = list(ma) if ma is not None else lcs_matching(o, a)
    mb = list(mb) if mb is not None else lcs_matching(o, b)
    if not is_matching(o, a, ma) or not is_matching(o, b, mb):
        raise ValueError("ma and mb must be increasing matchings of equal lines")
    in_a, in_b = set(ma), set(mb)
    a_of = dict(ma)  # line of o -> its partner in a
    b_of = dict(mb)
    chunks: list[Chunk] = []

    def emit(kind: str | None, la: int, ha: int, lo: int, ho: int, lb: int, hb: int) -> None:
        pa, po, pb = list(a[la:ha]), list(o[lo:ho]), list(b[lb:hb])
        chunks.append(Chunk(kind or _classify(pa, po, pb), pa, po, pb))

    lo = la = lb = 0  # @line L1
    while True:
        i = 1  # @line L2
        while (lo + i - 1, la + i - 1) in in_a and (lo + i - 1, lb + i - 1) in in_b:
            i += 1
        if i == 1:  # @line L3
            o_next = next((x for x in range(lo, len(o)) if x in a_of and x in b_of), None)
            if o_next is None:
                break
            ja, jb = a_of[o_next], b_of[o_next]
            emit(None, la, ja, lo, o_next, lb, jb)  # @line L4
            lo, la, lb = o_next, ja, jb
        else:
            emit(STABLE, la, la + i - 1, lo, lo + i - 1, lb, lb + i - 1)  # @line L5
            lo, la, lb = lo + i - 1, la + i - 1, lb + i - 1
    if lo < len(o) or la < len(a) or lb < len(b):  # @line L6
        emit(None, la, len(a), lo, len(o), lb, len(b))
    return chunks


def diff3_output(chunks: Sequence[Chunk]) -> tuple[list, list, list]:
    """Return the three new versions (A', O', B') of the paper: a chunk changed on one side is taken on all three."""
    out_a: list = []
    out_o: list = []
    out_b: list = []
    for c in chunks:
        if c.kind == CHANGED_A:
            parts = (c.a, c.a, c.a)
        elif c.kind == CHANGED_B:
            parts = (c.b, c.b, c.b)
        else:
            parts = (c.a, c.o, c.b)
        out_a += parts[0]
        out_o += parts[1]
        out_b += parts[2]
    return out_a, out_o, out_b


def diff3_merge(a: Sequence[Hashable], o: Sequence[Hashable], b: Sequence[Hashable],
                ma: Sequence[tuple[int, int]] | None = None, mb: Sequence[tuple[int, int]] | None = None,
                names: tuple[str, str, str] = ("A", "O", "B")) -> tuple[list, int]:
    """Return the merged lines, with a marked region for each true conflict, and the number of conflicts."""
    merged: list = []
    conflicts = 0
    for c in diff3_parse(a, o, b, ma, mb):  # @line L7
        if c.kind in (STABLE, UNCHANGED, CHANGED_A, FALSE_CONFLICT):
            merged += c.a
        elif c.kind == CHANGED_B:
            merged += c.b
        else:
            conflicts += 1
            merged += [f"<<<<<<< {names[0]}", *c.a, f"||||||| {names[1]}", *c.o, "=======", *c.b,
                       f">>>>>>> {names[2]}"]
    return merged, conflicts  # @line L8
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_diff3.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diff3/. The authors are listed in prov/8YT0S8.jsonl.

import random

from diff3 import (CHANGED_A, CHANGED_B, CONFLICT, FALSE_CONFLICT, STABLE, UNCHANGED, diff3_merge, diff3_output,
                   diff3_parse)
from txdiff import lcs_matching

# Figure 1 of Khanna, Kunal and Pierce, with the matchings of GNU diff3.
A1, O1, B1 = [1, 4, 5, 2, 3, 6], [1, 2, 3, 4, 5, 6], [1, 2, 4, 5, 3, 6]
MA1 = [(0, 0), (1, 3), (2, 4), (5, 5)]
MB1 = [(0, 0), (1, 1), (3, 2), (4, 3), (5, 5)]


def test_figure_1() -> None:
    chunks = diff3_parse(A1, O1, B1, MA1, MB1)
    assert [(c.kind, c.a, c.o, c.b) for c in chunks] == [
        (STABLE, [1], [1], [1]),
        (CHANGED_A, [4, 5], [], []),
        (STABLE, [2], [2], [2]),
        (CONFLICT, [3], [3, 4, 5], [4, 5, 3]),
        (STABLE, [6], [6], [6]),
    ]
    assert diff3_output(chunks) == ([1, 4, 5, 2, 3, 6], [1, 4, 5, 2, 3, 4, 5, 6], [1, 4, 5, 2, 4, 5, 3, 6])
    merged, conflicts = diff3_merge(A1, O1, B1, MA1, MB1)
    assert conflicts == 1
    assert merged == [1, 4, 5, 2, "<<<<<<< A", 3, "||||||| O", 3, 4, 5, "=======", 4, 5, 3, ">>>>>>> B", 6]


def test_the_matching_changes_the_result() -> None:
    # The helper takes another longest matching of O and A: 1, 4, 5, 6 instead of 1, 2, 3, 6.
    ma = lcs_matching(O1, A1)
    assert ma == [(0, 0), (3, 1), (4, 2), (5, 5)] and len(ma) == len(MA1)
    chunks = diff3_parse(A1, O1, B1, ma, MB1)
    assert [c.kind for c in chunks] == [STABLE, CONFLICT, STABLE, CONFLICT, STABLE]
    assert chunks[2].o == [4, 5]
    assert diff3_merge(A1, O1, B1, ma, MB1)[1] == 2


def test_not_idempotent() -> None:
    # Figure 4: each pair of files has one maximum matching, and a second run changes the result.
    a, o, b = [1, 2, 4, 6, 8], [1, 2, 3, 4, 5, 5, 5, 6, 7, 8], [1, 4, 5, 5, 5, 6, 2, 3, 4, 8]
    first = diff3_output(diff3_parse(a, o, b))
    assert first == ([1, 2, 4, 6, 8], [1, 2, 3, 4, 6, 7, 8], [1, 4, 6, 2, 3, 4, 8])
    second = diff3_output(diff3_parse(*first))
    assert second == ([1, 4, 6, 2, 4, 6, 8], [1, 4, 6, 2, 4, 6, 7, 8], [1, 4, 6, 2, 4, 8])


def test_locality() -> None:
    # Figure 3: A edits the start and B edits the end, yet there is a conflict for every n.
    for n in (1, 3, 6):
        o2 = [1, 2] * n
        a, o, b = [1, 2] + o2 + [1, 2], o2 + [1, 2], o2 + [3]
        assert lcs_matching(o, a) == [(k, k) for k in range(2 * n + 2)]  # the matching of the paper
        chunks = diff3_parse(a, o, b)
        assert [(c.kind, c.a, c.o, c.b) for c in chunks] == [(STABLE, o2, o2, o2), (CONFLICT, [1, 2, 1, 2], [1, 2], [3])]
        # Theorem 4.1.1: a line that occurs once in each file, in the middle part, removes the conflict.
        o2 = [1, 2] * n + [9] + [1, 2] * n
        a, o, b = [1, 2] + o2 + [1, 2], o2 + [1, 2], o2 + [3]
        assert diff3_merge(a, o, b) == ([1, 2] + o2 + [3], 0)


def test_page_examples() -> None:
    o = ["a", "b", "c"]
    assert diff3_merge(["a", "x", "b", "c"], o, ["a", "b", "c", "y"]) == (["a", "x", "b", "c", "y"], 0)
    merged, conflicts = diff3_merge(["a", "p", "c"], o, ["a", "q", "c"])
    assert conflicts == 1
    assert merged == ["a", "<<<<<<< A", "p", "||||||| O", "b", "=======", "q", ">>>>>>> B", "c"]
    # The same change on both sides is a false conflict, and the merge takes it.
    chunks = diff3_parse(["a", "z", "c"], o, ["a", "z", "c"])
    assert [c.kind for c in chunks] == [STABLE, FALSE_CONFLICT, STABLE]
    assert diff3_merge(["a", "z", "c"], o, ["a", "z", "c"]) == (["a", "z", "c"], 0)
    # A deletion on one side and no change on the other.
    assert diff3_merge(["a", "c"], o, o) == (["a", "c"], 0)
    assert [c.kind for c in diff3_parse(o, o, ["a", "c"])] == [STABLE, CHANGED_B, STABLE]
    assert diff3_merge([], [], []) == ([], 0)


def test_bad_matching() -> None:
    for ma in ([(1, 0)], [(0, 0), (0, 1)], [(3, 3)]):
        try:
            diff3_parse(["x", "y"], ["x", "y"], ["x", "y"], ma, None)
        except ValueError:
            continue
        raise AssertionError(f"{ma} was accepted")


def _edit(rng: random.Random, s: list[str]) -> list[str]:
    t = list(s)
    for _ in range(rng.randint(0, 3)):
        k = rng.randint(0, len(t))
        if t and rng.random() < 0.5:
            del t[min(k, len(t) - 1)]
        else:
            t.insert(k, rng.choice("abcxy"))
    return t


def _check_parse(a: list[str], o: list[str], b: list[str], ma: list[tuple[int, int]],
                 mb: list[tuple[int, int]]) -> None:
    chunks = diff3_parse(a, o, b, ma, mb)
    assert sum((c.a for c in chunks), []) == a
    assert sum((c.o for c in chunks), []) == o
    assert sum((c.b for c in chunks), []) == b
    triples = set()
    pa = po = pb = 0
    for k, c in enumerate(chunks):
        assert c.a or c.o or c.b
        if c.kind == STABLE:
            assert c.a == c.o == c.b
            triples |= {(po + t, pa + t, pb + t) for t in range(len(c.o))}
            # Each stable chunk is as large as possible: the next chunk is not stable.
            assert k + 1 == len(chunks) or chunks[k + 1].kind != STABLE
        pa, po, pb = pa + len(c.a), po + len(c.o), pb + len(c.b)
    a_of, b_of = dict(ma), dict(mb)
    both = {(x, a_of[x], b_of[x]) for x in a_of if x in b_of}
    assert both <= triples  # property (I) of a diff3 parse


def test_random_parses() -> None:
    rng = random.Random(8)
    for _ in range(400):
        o = [rng.choice("abc") for _ in range(rng.randint(0, 7))]
        a, b = _edit(rng, o), _edit(rng, o)
        ma, mb = lcs_matching(o, a), lcs_matching(o, b)
        _check_parse(a, o, b, ma, mb)
        assert UNCHANGED not in [c.kind for c in diff3_parse(a, o, b, ma, mb)]
        # Any increasing matchings give a parse, also ones that are not maximum.
        sub_a = [p for p in ma if rng.random() < 0.6]
        sub_b = [p for p in mb if rng.random() < 0.6]
        _check_parse(a, o, b, sub_a, sub_b)
        for x, y in ((sub_a, sub_b), (ma, mb)):
            # One side unchanged: the merge is the other side.
            assert diff3_merge(o, o, b, None, y) == (b, 0)
            assert diff3_merge(a, o, o, x, None) == (a, 0)
            # The same change on both sides with the same matching: the merge is that change.
            assert diff3_merge(a, o, a, x, x) == (a, 0)

History

Khanna, Kunal and Pierce write that diff3 was developed by Randy Smith in 1988, as the GNU diff3 program, and that version control systems such as CVS and Subversion made it popular. The default conflict style of Git is the one of the merge program of RCS, and Git's merge-file command is a minimal clone of that program. In 2007 Khanna, Kunal and Pierce gave a formal account of diff3, with its chunk algorithm, the counterexamples to idempotence, stability and locality, and the condition on a unique line under which a merge is safe.

References

  1. Sanjeev Khanna, Keshav Kunal and Benjamin C. Pierce, A formal investigation of Diff3, FSTTCS 2007, LNCS 4855, 485-496, Section 2, the stable and unstable chunks, their four classes and the output of a chunk; Figure 2, the algorithm of the parse, with Lemma 3.1; Figure 1, the example with the matchings of GNU diff3; Figures 3 and 4 and Theorem 4.1.1 on locality and idempotence; the history in Section 1
  2. Git, git-merge, how conflicts are presented, the conflict markers of the default style, the diff3 style with the base after the ||||||| marker, and the zdiff3 style
  3. Git, git-merge-file, the three-way merge of three files, the conflict markers, the labels of the -L option, the number of conflicts as exit value, and the note that it is a minimal clone of RCS merge

Where this leads

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.worst
  • 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