1// Copyright 2017, The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE.md file.
4
5// Package diff implements an algorithm for producing edit-scripts.
6// The edit-script is a sequence of operations needed to transform one list
7// of symbols into another (or vice-versa). The edits allowed are insertions,
8// deletions, and modifications. The summation of all edits is called the
9// Levenshtein distance as this problem is well-known in computer science.
10//
11// This package prioritizes performance over accuracy. That is, the run time
12// is more important than obtaining a minimal Levenshtein distance.
13package diff
14
15// EditType represents a single operation within an edit-script.
16type EditType uint8
17
18const (
19	// Identity indicates that a symbol pair is identical in both list X and Y.
20	Identity EditType = iota
21	// UniqueX indicates that a symbol only exists in X and not Y.
22	UniqueX
23	// UniqueY indicates that a symbol only exists in Y and not X.
24	UniqueY
25	// Modified indicates that a symbol pair is a modification of each other.
26	Modified
27)
28
29// EditScript represents the series of differences between two lists.
30type EditScript []EditType
31
32// String returns a human-readable string representing the edit-script where
33// Identity, UniqueX, UniqueY, and Modified are represented by the
34// '.', 'X', 'Y', and 'M' characters, respectively.
35func (es EditScript) String() string {
36	b := make([]byte, len(es))
37	for i, e := range es {
38		switch e {
39		case Identity:
40			b[i] = '.'
41		case UniqueX:
42			b[i] = 'X'
43		case UniqueY:
44			b[i] = 'Y'
45		case Modified:
46			b[i] = 'M'
47		default:
48			panic("invalid edit-type")
49		}
50	}
51	return string(b)
52}
53
54// stats returns a histogram of the number of each type of edit operation.
55func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) {
56	for _, e := range es {
57		switch e {
58		case Identity:
59			s.NI++
60		case UniqueX:
61			s.NX++
62		case UniqueY:
63			s.NY++
64		case Modified:
65			s.NM++
66		default:
67			panic("invalid edit-type")
68		}
69	}
70	return
71}
72
73// Dist is the Levenshtein distance and is guaranteed to be 0 if and only if
74// lists X and Y are equal.
75func (es EditScript) Dist() int { return len(es) - es.stats().NI }
76
77// LenX is the length of the X list.
78func (es EditScript) LenX() int { return len(es) - es.stats().NY }
79
80// LenY is the length of the Y list.
81func (es EditScript) LenY() int { return len(es) - es.stats().NX }
82
83// EqualFunc reports whether the symbols at indexes ix and iy are equal.
84// When called by Difference, the index is guaranteed to be within nx and ny.
85type EqualFunc func(ix int, iy int) Result
86
87// Result is the result of comparison.
88// NSame is the number of sub-elements that are equal.
89// NDiff is the number of sub-elements that are not equal.
90type Result struct{ NSame, NDiff int }
91
92// Equal indicates whether the symbols are equal. Two symbols are equal
93// if and only if NDiff == 0. If Equal, then they are also Similar.
94func (r Result) Equal() bool { return r.NDiff == 0 }
95
96// Similar indicates whether two symbols are similar and may be represented
97// by using the Modified type. As a special case, we consider binary comparisons
98// (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar.
99//
100// The exact ratio of NSame to NDiff to determine similarity may change.
101func (r Result) Similar() bool {
102	// Use NSame+1 to offset NSame so that binary comparisons are similar.
103	return r.NSame+1 >= r.NDiff
104}
105
106// Difference reports whether two lists of lengths nx and ny are equal
107// given the definition of equality provided as f.
108//
109// This function may return a edit-script, which is a sequence of operations
110// needed to convert one list into the other. If non-nil, the following
111// invariants for the edit-script are maintained:
112//	• eq == (es.Dist()==0)
113//	• nx == es.LenX()
114//	• ny == es.LenY()
115//
116// This algorithm is not guaranteed to be an optimal solution (i.e., one that
117// produces an edit-script with a minimal Levenshtein distance). This algorithm
118// favors performance over optimality. The exact output is not guaranteed to
119// be stable and may change over time.
120func Difference(nx, ny int, f EqualFunc) (eq bool, es EditScript) {
121	es = searchGraph(nx, ny, f)
122	st := es.stats()
123	eq = len(es) == st.NI
124	if !eq && st.NI < (nx+ny)/4 {
125		return eq, nil // Edit-script more distracting than helpful
126	}
127	return eq, es
128}
129
130func searchGraph(nx, ny int, f EqualFunc) EditScript {
131	// This algorithm is based on traversing what is known as an "edit-graph".
132	// See Figure 1 from "An O(ND) Difference Algorithm and Its Variations"
133	// by Eugene W. Myers. Since D can be as large as N itself, this is
134	// effectively O(N^2). Unlike the algorithm from that paper, we are not
135	// interested in the optimal path, but at least some "decent" path.
136	//
137	// For example, let X and Y be lists of symbols:
138	//	X = [A B C A B B A]
139	//	Y = [C B A B A C]
140	//
141	// The edit-graph can be drawn as the following:
142	//	   A B C A B B A
143	//	  ┌─────────────┐
144	//	C │_|_|\|_|_|_|_│ 0
145	//	B │_|\|_|_|\|\|_│ 1
146	//	A │\|_|_|\|_|_|\│ 2
147	//	B │_|\|_|_|\|\|_│ 3
148	//	A │\|_|_|\|_|_|\│ 4
149	//	C │ | |\| | | | │ 5
150	//	  └─────────────┘ 6
151	//	   0 1 2 3 4 5 6 7
152	//
153	// List X is written along the horizontal axis, while list Y is written
154	// along the vertical axis. At any point on this grid, if the symbol in
155	// list X matches the corresponding symbol in list Y, then a '\' is drawn.
156	// The goal of any minimal edit-script algorithm is to find a path from the
157	// top-left corner to the bottom-right corner, while traveling through the
158	// fewest horizontal or vertical edges.
159	// A horizontal edge is equivalent to inserting a symbol from list X.
160	// A vertical edge is equivalent to inserting a symbol from list Y.
161	// A diagonal edge is equivalent to a matching symbol between both X and Y.
162
163	// Invariants:
164	//	• 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx
165	//	• 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny
166	//
167	// In general:
168	//	• fwdFrontier.X < revFrontier.X
169	//	• fwdFrontier.Y < revFrontier.Y
170	// Unless, it is time for the algorithm to terminate.
171	fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)}
172	revPath := path{-1, point{nx, ny}, make(EditScript, 0)}
173	fwdFrontier := fwdPath.point // Forward search frontier
174	revFrontier := revPath.point // Reverse search frontier
175
176	// Search budget bounds the cost of searching for better paths.
177	// The longest sequence of non-matching symbols that can be tolerated is
178	// approximately the square-root of the search budget.
179	searchBudget := 4 * (nx + ny) // O(n)
180
181	// The algorithm below is a greedy, meet-in-the-middle algorithm for
182	// computing sub-optimal edit-scripts between two lists.
183	//
184	// The algorithm is approximately as follows:
185	//	• Searching for differences switches back-and-forth between
186	//	a search that starts at the beginning (the top-left corner), and
187	//	a search that starts at the end (the bottom-right corner). The goal of
188	//	the search is connect with the search from the opposite corner.
189	//	• As we search, we build a path in a greedy manner, where the first
190	//	match seen is added to the path (this is sub-optimal, but provides a
191	//	decent result in practice). When matches are found, we try the next pair
192	//	of symbols in the lists and follow all matches as far as possible.
193	//	• When searching for matches, we search along a diagonal going through
194	//	through the "frontier" point. If no matches are found, we advance the
195	//	frontier towards the opposite corner.
196	//	• This algorithm terminates when either the X coordinates or the
197	//	Y coordinates of the forward and reverse frontier points ever intersect.
198	//
199	// This algorithm is correct even if searching only in the forward direction
200	// or in the reverse direction. We do both because it is commonly observed
201	// that two lists commonly differ because elements were added to the front
202	// or end of the other list.
203	//
204	// Running the tests with the "debug" build tag prints a visualization of
205	// the algorithm running in real-time. This is educational for understanding
206	// how the algorithm works. See debug_enable.go.
207	f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es)
208	for {
209		// Forward search from the beginning.
210		if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
211			break
212		}
213		for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
214			// Search in a diagonal pattern for a match.
215			z := zigzag(i)
216			p := point{fwdFrontier.X + z, fwdFrontier.Y - z}
217			switch {
218			case p.X >= revPath.X || p.Y < fwdPath.Y:
219				stop1 = true // Hit top-right corner
220			case p.Y >= revPath.Y || p.X < fwdPath.X:
221				stop2 = true // Hit bottom-left corner
222			case f(p.X, p.Y).Equal():
223				// Match found, so connect the path to this point.
224				fwdPath.connect(p, f)
225				fwdPath.append(Identity)
226				// Follow sequence of matches as far as possible.
227				for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
228					if !f(fwdPath.X, fwdPath.Y).Equal() {
229						break
230					}
231					fwdPath.append(Identity)
232				}
233				fwdFrontier = fwdPath.point
234				stop1, stop2 = true, true
235			default:
236				searchBudget-- // Match not found
237			}
238			debug.Update()
239		}
240		// Advance the frontier towards reverse point.
241		if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y {
242			fwdFrontier.X++
243		} else {
244			fwdFrontier.Y++
245		}
246
247		// Reverse search from the end.
248		if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 {
249			break
250		}
251		for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ {
252			// Search in a diagonal pattern for a match.
253			z := zigzag(i)
254			p := point{revFrontier.X - z, revFrontier.Y + z}
255			switch {
256			case fwdPath.X >= p.X || revPath.Y < p.Y:
257				stop1 = true // Hit bottom-left corner
258			case fwdPath.Y >= p.Y || revPath.X < p.X:
259				stop2 = true // Hit top-right corner
260			case f(p.X-1, p.Y-1).Equal():
261				// Match found, so connect the path to this point.
262				revPath.connect(p, f)
263				revPath.append(Identity)
264				// Follow sequence of matches as far as possible.
265				for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y {
266					if !f(revPath.X-1, revPath.Y-1).Equal() {
267						break
268					}
269					revPath.append(Identity)
270				}
271				revFrontier = revPath.point
272				stop1, stop2 = true, true
273			default:
274				searchBudget-- // Match not found
275			}
276			debug.Update()
277		}
278		// Advance the frontier towards forward point.
279		if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y {
280			revFrontier.X--
281		} else {
282			revFrontier.Y--
283		}
284	}
285
286	// Join the forward and reverse paths and then append the reverse path.
287	fwdPath.connect(revPath.point, f)
288	for i := len(revPath.es) - 1; i >= 0; i-- {
289		t := revPath.es[i]
290		revPath.es = revPath.es[:i]
291		fwdPath.append(t)
292	}
293	debug.Finish()
294	return fwdPath.es
295}
296
297type path struct {
298	dir   int // +1 if forward, -1 if reverse
299	point     // Leading point of the EditScript path
300	es    EditScript
301}
302
303// connect appends any necessary Identity, Modified, UniqueX, or UniqueY types
304// to the edit-script to connect p.point to dst.
305func (p *path) connect(dst point, f EqualFunc) {
306	if p.dir > 0 {
307		// Connect in forward direction.
308		for dst.X > p.X && dst.Y > p.Y {
309			switch r := f(p.X, p.Y); {
310			case r.Equal():
311				p.append(Identity)
312			case r.Similar():
313				p.append(Modified)
314			case dst.X-p.X >= dst.Y-p.Y:
315				p.append(UniqueX)
316			default:
317				p.append(UniqueY)
318			}
319		}
320		for dst.X > p.X {
321			p.append(UniqueX)
322		}
323		for dst.Y > p.Y {
324			p.append(UniqueY)
325		}
326	} else {
327		// Connect in reverse direction.
328		for p.X > dst.X && p.Y > dst.Y {
329			switch r := f(p.X-1, p.Y-1); {
330			case r.Equal():
331				p.append(Identity)
332			case r.Similar():
333				p.append(Modified)
334			case p.Y-dst.Y >= p.X-dst.X:
335				p.append(UniqueY)
336			default:
337				p.append(UniqueX)
338			}
339		}
340		for p.X > dst.X {
341			p.append(UniqueX)
342		}
343		for p.Y > dst.Y {
344			p.append(UniqueY)
345		}
346	}
347}
348
349func (p *path) append(t EditType) {
350	p.es = append(p.es, t)
351	switch t {
352	case Identity, Modified:
353		p.add(p.dir, p.dir)
354	case UniqueX:
355		p.add(p.dir, 0)
356	case UniqueY:
357		p.add(0, p.dir)
358	}
359	debug.Update()
360}
361
362type point struct{ X, Y int }
363
364func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy }
365
366// zigzag maps a consecutive sequence of integers to a zig-zag sequence.
367//	[0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...]
368func zigzag(x int) int {
369	if x&1 != 0 {
370		x = ^x
371	}
372	return x >> 1
373}
374