Algorithmresearch
Semistructured merge
Also called structured merge.
Merge program versions on their trees of declarations, matching elements by name so that reordered members do not conflict, with line merge inside bodies.
- Time
- O(n^2) worst
- Space
- O(n^2) extra
- Where
- n = the total number of nodes and body lines of the three versions
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Semistructured merge is a three-way merge for program files that uses part of the structure of the language. Each version is parsed into a tree of its declarations, such as classes, fields and methods. Declarations whose order does not matter, such as the methods of a Java class, are matched by kind and name, not by place, and merged again inside. Declarations whose text order matters, such as method bodies, are kept as plain text and merged line by line with diff3. So two new methods that two developers add at the same place, which a line merge reports as a conflict, are both kept without one. Sven Apel, Jörg Liebig, Benjamin Brandl, Christian Lengauer and Christian Kästner described the method in 2011, built it into the tool FSTMerge, and found in 24 projects that it reduces the number of conflicts in most merges, but that renaming makes it worse.
In plain words
Two people change the same class. One adds a method at the end, the other adds a different method at the end. A normal merge only sees lines, so it finds two new pieces of text at the same place, and it cannot know which one comes first. It gives up and reports a conflict.
But in many languages the order of the methods in a class does not matter. So read each version as a list of named parts, and match the parts by their names. A part that only one person added is simply kept. A part that both people have is merged again, and inside a method body, where the order of the lines matters, use the normal line merge.
Conflicts then only appear where both people changed the same method in different ways.
The problem
The input is a base program and two revisions and , each parsed into a program structure tree. A grammar of the language marks which constructs become nonterminal nodes, whose children may be in any order and have distinct keys (kind and name), and which become terminal nodes, whose content is kept as text. The output is a merged tree, printed back as a program, and a list of conflicts.
The algorithm
The merge starts at the three roots and goes down the trees. For a node, , and denote the children of , and with a given key; any of them may be absent.
MERGE(a, o, b) ▷ a and b have the same key; o is their base, absent if both sides added the node- 1
if a is a terminal then return LINE-MERGE(a.body, o.body or nothing, b.body) - 2
K ← the keys of the children of a in their order, then the keys of the children of b that a does not have - 3
for each key k in K, with children x of a, y of o and z of b: - 4
if x and z are both present then append MERGE(x, y, z) - 5
else if y is absent then append the one of x and z that is present ▷ added on one side - 6
else if the present one differs from y then append it and report a conflict ▷ deleted on one side, changed on the other ▷ else the node was deleted on one side and not changed on the other: drop it- 7
return a with the appended children
LINE-MERGE is the merge rule of diff3: match the base with each side by a longest common subsequence, take the side that changed between two lines that all three keep, and mark a conflict where both changed in different ways. Lines L2 to L6 are superimposition, the composition of trees by name that the FeatureHouse tools of Apel and his colleagues use for software composition, plus the rules for deletions. Apel et al. handle deletions "following RCS's merge" and do not give the rules; lines L5 and L6 are the rules of this page. A grammar can also attach a conflict handler to a kind of terminal, which merges it in a special way: their example is the list of interfaces in an implements clause, which is merged as a set.
Example
This is the stack example of Apel et al. The base class has the methods push and pop. Revision TOP adds a method top, and revision SIZE adds a method size, both after pop.
class Stack {
void push(T item) { ... }
T pop() { ... }
}
A line merge sees two blocks of new lines before the same closing brace. It cannot choose an order, so it reports one conflict:
<<<<<<< A
T top() { ... }
||||||| O
=======
int size() { ... }
>>>>>>> B
}
The semistructured merge parses the three versions into trees. Each root is a class node named Stack, with the method nodes as children. Line L2 lists the keys push, pop and top of revision TOP, then size from revision SIZE. The methods push and pop are in all three versions and unchanged, so line L4 merges them to themselves. The methods top and size have no base, and each is in one revision only, so line L5 keeps both. The result has push, pop, top and size, and no conflict.
Now let revision TOP rename pop to remove, and let revision SIZE add a line to the body of pop. The key of remove is new, so line L5 keeps it. The key of pop is in the base and in SIZE only, with a changed body, so line L6 keeps SIZE's pop and reports a conflict. The merge cannot see that the two are the same method.
Correctness
The proof file shows three facts. If one revision equals the base, the merge returns the other revision, with no conflict, up to the order of the members. Members with different keys never conflict with each other, wherever the two sides put them, because line L4 matches children by key and not by place. And a merge without conflicts gives the same result when the two revisions are swapped, up to order. The line merge inside bodies has the same properties for lines, which the proof also shows, so the facts carry over to the whole tree by induction on its height.
Proof: Semistructured merge keeps the work of a side that alone changed the program, and orders no members by placefull
We use the pseudocode of the page. A tree is a node with a kind and a name; its key is the pair of the two. A nonterminal node has a list of children with distinct keys, and a terminal node has a body, a list of lines. Two trees are equal up to order if they become equal when the children of every nonterminal node are sorted by key. MERGE takes two nodes and with the same key and their base , which is absent when both sides added the node. LINE-MERGE is the chunk rule of diff3 on two longest matchings, with and with : between two lines of that are matched on both sides, it takes the piece of if the pieces of and are equal or the pieces of and are equal, else the piece of if the pieces of and are equal, else it writes a conflict.
Lemma 1 (the line merge with one side unchanged). LINE-MERGE is and LINE-MERGE is , both without a conflict.
Proof. A longest matching of with itself has pairs and is increasing, so it is the identity. Take LINE-MERGE. The partner of each line of in the copy is itself, so at each step the start in the copy is the start in , and the pieces of and of the copy are equal. The first case of the rule applies at every step, and the output is the pieces of , joined by the lines between them, which is . For LINE-MERGE the pieces of and are equal at every step. If the piece of is equal to them too, the rule takes the piece of , which is the same; otherwise it takes the piece of . So the output is .
Lemma 2 (the line merge is symmetric without conflicts). If LINE-MERGE has no conflict, then LINE-MERGE has the same lines.
Proof. The lines of that are matched on both sides are the same for the two calls, and the pieces of each step are the same with and swapped. Write , and for the pieces of one step. If , both calls take that piece. If , the first call takes ; in the second call and , so it reaches the case and takes too. If , both calls take in the same way. These are all the steps without a conflict.
Lemma 3 (the members of a merged node). Let and be nonterminal nodes with base . For each key of a child, the merged node has a child with key exactly in these cases, and the conflicts of line L6 are the only ones made at this level:
- is in and in : the child is the merge of the two children and the child of (line L4);
- is in exactly one of and , and not in : the child is that one (line L5);
- is in exactly one of and , and in , and that child differs from the child of : the child is kept, and a conflict is reported (line L6).
If is in exactly one of and , in , and unchanged there, or in neither nor , the merged node has no child with key . The children with a key in come first, in the order of , and then the others, in the order of .
Proof. Line L2 lists each key of or once, the keys of in their order and then the new keys of in theirs, so a key that is in neither does not appear. Line L3 takes the children , and of , and with the key; a key has at most one child in each node. The three branches of lines L4 to L6 are the cases of the lemma.
Theorem 1 (one side unchanged). MERGE is , and MERGE is equal to up to order, both without a conflict.
Proof. By induction on the height of the trees. If the nodes are terminal, line L1 returns LINE-MERGE of the bodies, which is the body of or of without a conflict by Lemma 1. Otherwise use Lemma 3. In MERGE, a key of that is in is in both sides, and its child is MERGE by induction. A key of that is not in is not in the copy of either, so its child is by case 2. A key of that is not in is in the copy of unchanged, so it is dropped. So the merged children are those of , in the order of , and the node is . In MERGE, in the same way, a key in and gives a child equal to that of up to order, a key only in gives the child of , and a key of that is not in is dropped, because the first side has it unchanged. So the merged node has the children of , up to order. No case is case 3, so there is no conflict.
Theorem 2 (no ordering conflicts). Two members that the two sides add to the same node with different keys never conflict, wherever they are placed, and a member that one side moves among its siblings and the other side changes is merged as if it had not moved.
Proof. Lemma 3 matches children by key only, never by place. Two added members with different keys fall under case 2 each, without a conflict. A moved member is in , and with the same key, so case 1 merges it with its base like any other member; the move changes only the order of the children, which no case of Lemma 3 tests.
Theorem 3 (symmetric without conflicts). If MERGE has no conflict, then MERGE has no conflict either, and the two results are equal up to order.
Proof. By induction on the height. For terminal nodes, Lemma 2 applies to the bodies, with an empty base if is absent, and a conflict of one call is a conflict of the other because the pieces are only swapped. For nonterminal nodes, the set of keys at line L2 is the union of the keys of and in both calls, and each case of Lemma 3 is symmetric in and : case 1 by induction, case 2 takes the same child, and in the last case the child is dropped in both calls. Case 3 is excluded, since it reports a conflict. Only the order of the children can differ.
Renaming. A member that one side renames has a new key. By Lemma 3 the old key is in and on one side only, and the new key is on one side only and not in . If the other side changed the member, the result keeps both versions and reports a conflict of case 3; if not, the old member is dropped and the renamed one is kept. This is the weakness that Apel et al. found in their study.
Termination and cost. Each call of MERGE recurses only on children, so the calls follow the nodes of the trees, and each node of or is in at most one call. With hash maps for the children, one nonterminal costs expected time linear in its number of children, so the tree part is expected linear in the size of the trees. A terminal costs the two longest matchings of its bodies, with the dynamic program, so the total time is for versions with lines and nodes in total.
Complexity
Let be the total number of nodes and body lines of the three versions. With hash maps for the children, each nonterminal node takes expected time linear in its number of children, so the tree part of the merge is expected ; Apel et al. note that the merge is done in linear time. The line merge of each terminal costs two longest matchings of its bodies, with the dynamic program of this page, so the total is in the worst case, with space for the table. A diff such as Myers' algorithm makes the body merges faster when the changes are small. Parsing and printing the programs are linear for the usual grammars.
Properties
- No ordering conflicts. Two revisions that add different members to the same node never conflict, wherever they place them.
- One side unchanged. If one revision equals the base, the merge is the other revision, up to order.
- Conflicts follow the structure. A conflict is always inside one method or about one declaration, never across the borders of classes or methods, which makes it easier to read.
- Order of the result. The members of a node come in the order of one revision, followed by the members that only the other revision added. Where the order matters, the grammar must make the construct a terminal, so that the line merge keeps its order.
- Renaming hurts. A renamed member is a deleted member plus a new one, so changes to it on the other side lead to a conflict, or to two copies.
- Needs a parser. Each version must parse. A revision with a syntax error cannot be merged this way.
Variants and improvements
- Granularity. The grammar decides how deep the tree goes. Apel et al. stop at methods and fields, and keep statements as text; deeper trees give a merge of full syntax trees, which needs matching of ordered nodes, such as a tree diff like Chawathe's change detection.
- Conflict handlers. Special merges for some kinds of terminals, such as lists of interfaces or modifiers, remove more conflicts.
- A mix with line merge. Apel et al. found that a tool that merges each file both ways and keeps the result with fewer conflicts reduces the conflicts by 35% compared with a line merge alone, because it avoids the cases with renaming.
- Tracking renames. If the editor or the version control system records renames, renamed members can be matched to their old keys.
- Operation-based merge. Recording the edit operations, as in operational transformation or a CRDT, avoids the question of matching altogether.
When to use it
Use it to merge source files in languages where many declarations can be in any order, such as Java, C# or Python classes, when branches often add members at the same places. It needs a grammar of the language with the right marks, and the versions must parse. Keep a line merge for files that do not parse and for other files, and prefer it when a revision renames many elements.
Pitfalls
- Keys must be unique. Overloaded methods in Java have the same name, so the key of a method must include its parameter types, or two methods are merged as one.
- Deleted versus changed. If one side deletes a member and the other side changes it, there is no safe choice; the merge must report it, not drop the change silently.
- Added on both sides. Two revisions that add members with the same key and different bodies give a line merge with an empty base, which is one large conflict.
- Order that matters. Some members do depend on their order, such as field initializers that refer to each other. If the grammar marks them as unordered, the merge may move them and change the program.
- Comments and layout. A printer that writes the merged tree may lose comments or change the layout of code that neither side touched.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semistructured-merge/. The authors are listed in prov/30FJFE.jsonl.
"""Semistructured merge, after Apel, Liebig, Brandl, Lengauer and Kästner (ESEC/FSE 2011).
A program is a tree of nodes. A node has a kind and a name. A nonterminal node,
such as a class, has children whose order does not matter; a terminal node, such
as a method, has a body of text lines. The merge matches children by (kind, name),
merges matched nonterminals again, and merges the bodies of matched terminals
with a line-based three-way merge. The tree part is superimposition; deletions are
handled by the rules of merge_node.
"""
from collections.abc import Sequence
from typing import NamedTuple, Optional
from txdiff import lcs_matching
class Node(NamedTuple):
kind: str
name: str
children: tuple["Node", ...] = ()
body: Optional[tuple[str, ...]] = None # None for a nonterminal node
@property
def key(self) -> tuple[str, str]:
return (self.kind, self.name)
@property
def terminal(self) -> bool:
return self.body is not None
class Conflict(NamedTuple):
path: tuple[str, ...] # the names from the root to the node
reason: str # "lines", "added on both sides", "deleted in A, changed in B" or "deleted in B, changed in A"
def line_merge(a: Sequence[str], o: Sequence[str], b: Sequence[str],
names: tuple[str, str, str] = ("A", "O", "B")) -> tuple[list[str], int]:
"""Return the line-based three-way merge of a and b with base o, and its number of conflicts.
This is the chunk rule of diff3, with longest matchings of o with a and of o with b.
"""
a_of, b_of = dict(lcs_matching(o, a)), dict(lcs_matching(o, b))
out: list[str] = []
conflicts = 0
lo = la = lb = 0
for x in [x for x in range(len(o)) if x in a_of and x in b_of] + [len(o)]:
ja, jb = (a_of[x], b_of[x]) if x < len(o) else (len(a), len(b))
pa, po, pb = list(a[la:ja]), list(o[lo:x]), list(b[lb:jb])
if po == pb or pa == pb:
out += pa # changed in A only, or the same change on both sides, or no change
elif po == pa:
out += pb # changed in B only
else:
conflicts += 1
out += [f"<<<<<<< {names[0]}", *pa, f"||||||| {names[1]}", *po, "=======", *pb, f">>>>>>> {names[2]}"]
if x < len(o):
out.append(o[x]) # a line that all three files keep
lo, la, lb = x + 1, ja + 1, jb + 1
return out, conflicts
def merge_node(a: Node, o: Optional[Node], b: Node,
path: tuple[str, ...] = ()) -> tuple[Node, list[Conflict]]:
"""Merge two nodes with the same key, given their base o, which is None if both sides added the node."""
if a.key != b.key or (o is not None and o.key != a.key) or a.terminal != b.terminal:
raise ValueError("the nodes do not match")
path = path + (a.name,)
if a.terminal: # @line L1
body, k = line_merge(a.body, o.body if o is not None and o.terminal else (), b.body)
reason = "lines" if o is not None else "added on both sides"
return a._replace(body=tuple(body)), [Conflict(path, reason)] * k
in_a = {c.key: c for c in a.children}
in_o = {c.key: c for c in o.children} if o is not None else {}
in_b = {c.key: c for c in b.children}
keys = [c.key for c in a.children] + [c.key for c in b.children if c.key not in in_a] # @line L2
children: list[Node] = []
conflicts: list[Conflict] = []
for key in keys: # @line L3
x, y, z = in_a.get(key), in_o.get(key), in_b.get(key)
if x is not None and z is not None: # @line L4
child, more = merge_node(x, y, z, path)
children.append(child)
conflicts += more
elif y is None: # @line L5
children.append(x if x is not None else z) # added on one side
else:
kept, side = (x, "B") if x is not None else (z, "A")
if kept != y: # @line L6
children.append(kept) # deleted on one side, changed on the other: keep it and report
other = "A" if side == "B" else "B"
conflicts.append(Conflict(path + (kept.name,), f"deleted in {side}, changed in {other}"))
# Otherwise the node is unchanged on one side and deleted on the other, so it is dropped.
return a._replace(children=tuple(children)), conflicts # @line L7
def semistructured_merge(a: Node, o: Node, b: Node) -> tuple[Node, list[Conflict]]:
"""Merge the trees a and b of two revisions with the tree o of their base; return the tree and the conflicts."""
return merge_node(a, o, b)
def to_lines(node: Node, depth: int = 0) -> list[str]:
"""Print a tree as lines: a nonterminal as "kind name {", its children and "}", a terminal as its body."""
pad = " " * depth
if node.terminal:
return [pad + line if line else line for line in node.body]
out = [f"{pad}{node.kind} {node.name} {{"]
for child in node.children:
out += to_lines(child, depth + 1)
return out + [pad + "}"]
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_semistructured_merge.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semistructured-merge/. The authors are listed in prov/30FJFE.jsonl.
import random
from semistructured_merge import Conflict, Node, line_merge, semistructured_merge, to_lines
def method(name: str, *lines: str) -> Node:
return Node("method", name, body=tuple(lines))
def stack(*members: Node, name: str = "Stack") -> Node:
return Node("class", name, tuple(members))
PUSH = method("push", "void push(T item) {", " items.addFirst(item);", "}")
POP = method("pop", "T pop() {", " return items.removeFirst();", "}")
TOP = method("top", "T top() {", " return items.getFirst();", "}")
SIZE = method("size", "int size() {", " return items.size();", "}")
def test_two_new_methods() -> None:
o, a, b = stack(PUSH, POP), stack(PUSH, POP, TOP), stack(PUSH, POP, SIZE)
merged, conflicts = semistructured_merge(a, o, b)
assert conflicts == [] and merged == stack(PUSH, POP, TOP, SIZE)
# A line merge of the same three files cannot order the two new methods.
lines, k = line_merge(to_lines(a), to_lines(o), to_lines(b))
assert k == 1
assert lines[7:] == ["<<<<<<< A", *to_lines(TOP, 1), "||||||| O", "=======", *to_lines(SIZE, 1), ">>>>>>> B", "}"]
def test_order_does_not_matter() -> None:
push2 = method("push", "void push(T item) {", " items.addFirst(item);", " count++;", "}")
merged, conflicts = semistructured_merge(stack(POP, PUSH), stack(PUSH, POP), stack(push2, POP))
assert conflicts == [] and merged == stack(POP, push2)
def test_deletions() -> None:
o = stack(PUSH, POP)
assert semistructured_merge(stack(PUSH), o, o) == (stack(PUSH), [])
assert semistructured_merge(stack(PUSH), o, stack(PUSH)) == (stack(PUSH), [])
pop2 = method("pop", "T pop() {", " check();", " return items.removeFirst();", "}")
merged, conflicts = semistructured_merge(stack(PUSH), o, stack(PUSH, pop2))
assert merged == stack(PUSH, pop2)
assert conflicts == [Conflict(("Stack", "pop"), "deleted in A, changed in B")]
merged, conflicts = semistructured_merge(stack(PUSH, pop2), o, stack(PUSH))
assert conflicts == [Conflict(("Stack", "pop"), "deleted in B, changed in A")]
def test_renaming_is_a_delete_and_an_add() -> None:
o = stack(PUSH, POP)
remove = POP._replace(name="remove", body=("T remove() {",) + POP.body[1:])
pop2 = method("pop", "T pop() {", " check();", " return items.removeFirst();", "}")
merged, conflicts = semistructured_merge(stack(PUSH, remove), o, stack(PUSH, pop2))
assert merged == stack(PUSH, remove, pop2)
assert conflicts == [Conflict(("Stack", "pop"), "deleted in A, changed in B")]
def test_bodies_are_merged_by_lines() -> None:
body = ("int f() {", " int x = 1;", " int y = 2;", " int z = 3;", " return x + y + z;", "}")
o = stack(method("f", *body))
a = stack(method("f", *body[:1], " int x = 10;", *body[2:]))
b = stack(method("f", *body[:4], " return x * y * z;", *body[5:]))
merged, conflicts = semistructured_merge(a, o, b)
assert conflicts == []
assert merged.children[0].body == (body[0], " int x = 10;", body[2], body[3], " return x * y * z;", body[5])
c = stack(method("f", *body[:1], " int x = 20;", *body[2:]))
merged, conflicts = semistructured_merge(a, o, c)
assert conflicts == [Conflict(("Stack", "f"), "lines")]
assert merged.children[0].body[1:6] == ("<<<<<<< A", " int x = 10;", "||||||| O", " int x = 1;", "=======")
# The same method added on both sides has no base: equal bodies merge, different ones conflict.
assert semistructured_merge(stack(TOP), stack(), stack(TOP)) == (stack(TOP), [])
top2 = method("top", "T top() {", " return items.peek();", "}")
merged, conflicts = semistructured_merge(stack(TOP), stack(), stack(top2))
assert conflicts == [Conflict(("Stack", "top"), "added on both sides")]
def test_nested_and_bad_input() -> None:
o = Node("package", "util", (stack(PUSH, POP),))
a = Node("package", "util", (stack(PUSH, POP, TOP), stack(PUSH, name="Queue")))
b = Node("package", "util", (stack(PUSH, POP, SIZE),))
merged, conflicts = semistructured_merge(a, o, b)
assert conflicts == []
assert merged == Node("package", "util", (stack(PUSH, POP, TOP, SIZE), stack(PUSH, name="Queue")))
try:
semistructured_merge(stack(PUSH), stack(PUSH), stack(PUSH, name="Queue"))
except ValueError:
return
raise AssertionError("different roots were accepted")
def _canonical(node: Node) -> Node:
if node.terminal:
return node
return node._replace(children=tuple(sorted((_canonical(c) for c in node.children), key=lambda c: c.key)))
def _random_class(rng: random.Random) -> Node:
names = rng.sample("fghijk", rng.randint(0, 4))
return stack(*(method(n, *(rng.choice("pqr") for _ in range(rng.randint(1, 4)))) for n in names))
def _edit(rng: random.Random, node: Node) -> Node:
members = list(node.children)
for _ in range(rng.randint(0, 3)):
r = rng.random()
if members and r < 0.25:
del members[rng.randrange(len(members))]
elif r < 0.5:
name = rng.choice("fghijk")
if all(m.name != name for m in members):
members.insert(rng.randint(0, len(members)), method(name, rng.choice("pqr")))
elif members and r < 0.75:
k = rng.randrange(len(members))
body = list(members[k].body)
body.insert(rng.randint(0, len(body)), rng.choice("pqrs"))
members[k] = members[k]._replace(body=tuple(body))
else:
rng.shuffle(members)
return node._replace(children=tuple(members))
def test_random_merges() -> None:
rng = random.Random(30)
for _ in range(300):
o = _random_class(rng)
a, b = _edit(rng, o), _edit(rng, o)
assert semistructured_merge(a, o, o) == (a, [])
merged, conflicts = semistructured_merge(o, o, b)
assert conflicts == [] and _canonical(merged) == _canonical(b)
merged, conflicts = semistructured_merge(a, o, b)
# The members of A that stay come first, in the order of A; then the members that only B has.
got = [c.name for c in merged.children]
from_a = [c.name for c in a.children if c.name in got]
assert got == from_a + [c.name for c in b.children if c.name in got and c.name not in from_a]
# A member that one side deleted and the other did not change is gone.
names_a, names_b = {x.name for x in a.children}, {x.name for x in b.children}
for c in o.children:
if (c in a.children and c.name not in names_b) or (c in b.children and c.name not in names_a):
assert c.name not in got
if not conflicts:
back, more = semistructured_merge(b, o, a)
assert more == [] and _canonical(back) == _canonical(merged)
History
Version control systems have merged files as lines since the early tools, and merges of full syntax trees were studied in research for a long time, as Mens surveys in 2002, but they need a full grammar and a merge for each language. Apel and his colleagues proposed the middle way in an earlier workshop paper, and described it in full at ESEC/FSE 2011. They built FSTMerge as an extension of FeatureHouse, their tool infrastructure for software composition, in which a generator makes almost all the code for a new language from an annotated grammar. In their study of 24 projects in Java, C# and Python, with 180 merge scenarios, semistructured merge reduced the number of conflicts in 60% of the scenarios, by 34 ± 21%. In 26% of the scenarios, it increased the number of conflicts, by 109 ± 170%, and they traced these cases to renaming.
References
- Sven Apel, Jörg Liebig, Benjamin Brandl, Christian Lengauer and Christian Kästner, Semistructured merge, rethinking merge in revision control systems, ESEC/FSE 2011, 190-200, Section 2, the stack example with the methods top and size; Section 3, program structure trees, superimposition, the annotated grammar with FSTNonTerminal and FSTTerminal, line-based merge of terminals, deletions and conflict handlers; Section 4, the tool FSTMerge; Section 5, the study of 24 projects and 180 merge scenarios and the effect of renaming
- Tom Mens, A state-of-the-art survey on software merging, IEEE Transactions on Software Engineering 28(5), 2002, 449-462, textual, syntactic, semantic and structural merging, and the merge of trees and graphs
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 30FJFE Edit this page History Report an error Markdown