difflib.go

  1/* Package difflib is a partial port of Python difflib module.
  2
  3Original source: https://github.com/pmezard/go-difflib
  4
  5This file is trimmed to only the parts used by this repository.
  6*/
  7package difflib // import "gotest.tools/internal/difflib"
  8
  9func min(a, b int) int {
 10	if a < b {
 11		return a
 12	}
 13	return b
 14}
 15
 16func max(a, b int) int {
 17	if a > b {
 18		return a
 19	}
 20	return b
 21}
 22
 23type Match struct {
 24	A    int
 25	B    int
 26	Size int
 27}
 28
 29type OpCode struct {
 30	Tag byte
 31	I1  int
 32	I2  int
 33	J1  int
 34	J2  int
 35}
 36
 37// SequenceMatcher compares sequence of strings. The basic
 38// algorithm predates, and is a little fancier than, an algorithm
 39// published in the late 1980's by Ratcliff and Obershelp under the
 40// hyperbolic name "gestalt pattern matching".  The basic idea is to find
 41// the longest contiguous matching subsequence that contains no "junk"
 42// elements (R-O doesn't address junk).  The same idea is then applied
 43// recursively to the pieces of the sequences to the left and to the right
 44// of the matching subsequence.  This does not yield minimal edit
 45// sequences, but does tend to yield matches that "look right" to people.
 46//
 47// SequenceMatcher tries to compute a "human-friendly diff" between two
 48// sequences.  Unlike e.g. UNIX(tm) diff, the fundamental notion is the
 49// longest *contiguous* & junk-free matching subsequence.  That's what
 50// catches peoples' eyes.  The Windows(tm) windiff has another interesting
 51// notion, pairing up elements that appear uniquely in each sequence.
 52// That, and the method here, appear to yield more intuitive difference
 53// reports than does diff.  This method appears to be the least vulnerable
 54// to synching up on blocks of "junk lines", though (like blank lines in
 55// ordinary text files, or maybe "<P>" lines in HTML files).  That may be
 56// because this is the only method of the 3 that has a *concept* of
 57// "junk" <wink>.
 58//
 59// Timing:  Basic R-O is cubic time worst case and quadratic time expected
 60// case.  SequenceMatcher is quadratic time for the worst case and has
 61// expected-case behavior dependent in a complicated way on how many
 62// elements the sequences have in common; best case time is linear.
 63type SequenceMatcher struct {
 64	a              []string
 65	b              []string
 66	b2j            map[string][]int
 67	IsJunk         func(string) bool
 68	autoJunk       bool
 69	bJunk          map[string]struct{}
 70	matchingBlocks []Match
 71	fullBCount     map[string]int
 72	bPopular       map[string]struct{}
 73	opCodes        []OpCode
 74}
 75
 76func NewMatcher(a, b []string) *SequenceMatcher {
 77	m := SequenceMatcher{autoJunk: true}
 78	m.SetSeqs(a, b)
 79	return &m
 80}
 81
 82// Set two sequences to be compared.
 83func (m *SequenceMatcher) SetSeqs(a, b []string) {
 84	m.SetSeq1(a)
 85	m.SetSeq2(b)
 86}
 87
 88// Set the first sequence to be compared. The second sequence to be compared is
 89// not changed.
 90//
 91// SequenceMatcher computes and caches detailed information about the second
 92// sequence, so if you want to compare one sequence S against many sequences,
 93// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
 94// sequences.
 95//
 96// See also SetSeqs() and SetSeq2().
 97func (m *SequenceMatcher) SetSeq1(a []string) {
 98	if &a == &m.a {
 99		return
100	}
101	m.a = a
102	m.matchingBlocks = nil
103	m.opCodes = nil
104}
105
106// Set the second sequence to be compared. The first sequence to be compared is
107// not changed.
108func (m *SequenceMatcher) SetSeq2(b []string) {
109	if &b == &m.b {
110		return
111	}
112	m.b = b
113	m.matchingBlocks = nil
114	m.opCodes = nil
115	m.fullBCount = nil
116	m.chainB()
117}
118
119func (m *SequenceMatcher) chainB() {
120	// Populate line -> index mapping
121	b2j := map[string][]int{}
122	for i, s := range m.b {
123		indices := b2j[s]
124		indices = append(indices, i)
125		b2j[s] = indices
126	}
127
128	// Purge junk elements
129	m.bJunk = map[string]struct{}{}
130	if m.IsJunk != nil {
131		junk := m.bJunk
132		for s, _ := range b2j {
133			if m.IsJunk(s) {
134				junk[s] = struct{}{}
135			}
136		}
137		for s, _ := range junk {
138			delete(b2j, s)
139		}
140	}
141
142	// Purge remaining popular elements
143	popular := map[string]struct{}{}
144	n := len(m.b)
145	if m.autoJunk && n >= 200 {
146		ntest := n/100 + 1
147		for s, indices := range b2j {
148			if len(indices) > ntest {
149				popular[s] = struct{}{}
150			}
151		}
152		for s, _ := range popular {
153			delete(b2j, s)
154		}
155	}
156	m.bPopular = popular
157	m.b2j = b2j
158}
159
160func (m *SequenceMatcher) isBJunk(s string) bool {
161	_, ok := m.bJunk[s]
162	return ok
163}
164
165// Find longest matching block in a[alo:ahi] and b[blo:bhi].
166//
167// If IsJunk is not defined:
168//
169// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
170//     alo <= i <= i+k <= ahi
171//     blo <= j <= j+k <= bhi
172// and for all (i',j',k') meeting those conditions,
173//     k >= k'
174//     i <= i'
175//     and if i == i', j <= j'
176//
177// In other words, of all maximal matching blocks, return one that
178// starts earliest in a, and of all those maximal matching blocks that
179// start earliest in a, return the one that starts earliest in b.
180//
181// If IsJunk is defined, first the longest matching block is
182// determined as above, but with the additional restriction that no
183// junk element appears in the block.  Then that block is extended as
184// far as possible by matching (only) junk elements on both sides.  So
185// the resulting block never matches on junk except as identical junk
186// happens to be adjacent to an "interesting" match.
187//
188// If no blocks match, return (alo, blo, 0).
189func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
190	// CAUTION:  stripping common prefix or suffix would be incorrect.
191	// E.g.,
192	//    ab
193	//    acab
194	// Longest matching block is "ab", but if common prefix is
195	// stripped, it's "a" (tied with "b").  UNIX(tm) diff does so
196	// strip, so ends up claiming that ab is changed to acab by
197	// inserting "ca" in the middle.  That's minimal but unintuitive:
198	// "it's obvious" that someone inserted "ac" at the front.
199	// Windiff ends up at the same place as diff, but by pairing up
200	// the unique 'b's and then matching the first two 'a's.
201	besti, bestj, bestsize := alo, blo, 0
202
203	// find longest junk-free match
204	// during an iteration of the loop, j2len[j] = length of longest
205	// junk-free match ending with a[i-1] and b[j]
206	j2len := map[int]int{}
207	for i := alo; i != ahi; i++ {
208		// look at all instances of a[i] in b; note that because
209		// b2j has no junk keys, the loop is skipped if a[i] is junk
210		newj2len := map[int]int{}
211		for _, j := range m.b2j[m.a[i]] {
212			// a[i] matches b[j]
213			if j < blo {
214				continue
215			}
216			if j >= bhi {
217				break
218			}
219			k := j2len[j-1] + 1
220			newj2len[j] = k
221			if k > bestsize {
222				besti, bestj, bestsize = i-k+1, j-k+1, k
223			}
224		}
225		j2len = newj2len
226	}
227
228	// Extend the best by non-junk elements on each end.  In particular,
229	// "popular" non-junk elements aren't in b2j, which greatly speeds
230	// the inner loop above, but also means "the best" match so far
231	// doesn't contain any junk *or* popular non-junk elements.
232	for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
233		m.a[besti-1] == m.b[bestj-1] {
234		besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
235	}
236	for besti+bestsize < ahi && bestj+bestsize < bhi &&
237		!m.isBJunk(m.b[bestj+bestsize]) &&
238		m.a[besti+bestsize] == m.b[bestj+bestsize] {
239		bestsize += 1
240	}
241
242	// Now that we have a wholly interesting match (albeit possibly
243	// empty!), we may as well suck up the matching junk on each
244	// side of it too.  Can't think of a good reason not to, and it
245	// saves post-processing the (possibly considerable) expense of
246	// figuring out what to do with it.  In the case of an empty
247	// interesting match, this is clearly the right thing to do,
248	// because no other kind of match is possible in the regions.
249	for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
250		m.a[besti-1] == m.b[bestj-1] {
251		besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
252	}
253	for besti+bestsize < ahi && bestj+bestsize < bhi &&
254		m.isBJunk(m.b[bestj+bestsize]) &&
255		m.a[besti+bestsize] == m.b[bestj+bestsize] {
256		bestsize += 1
257	}
258
259	return Match{A: besti, B: bestj, Size: bestsize}
260}
261
262// Return list of triples describing matching subsequences.
263//
264// Each triple is of the form (i, j, n), and means that
265// a[i:i+n] == b[j:j+n].  The triples are monotonically increasing in
266// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
267// adjacent triples in the list, and the second is not the last triple in the
268// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
269// adjacent equal blocks.
270//
271// The last triple is a dummy, (len(a), len(b), 0), and is the only
272// triple with n==0.
273func (m *SequenceMatcher) GetMatchingBlocks() []Match {
274	if m.matchingBlocks != nil {
275		return m.matchingBlocks
276	}
277
278	var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
279	matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
280		match := m.findLongestMatch(alo, ahi, blo, bhi)
281		i, j, k := match.A, match.B, match.Size
282		if match.Size > 0 {
283			if alo < i && blo < j {
284				matched = matchBlocks(alo, i, blo, j, matched)
285			}
286			matched = append(matched, match)
287			if i+k < ahi && j+k < bhi {
288				matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
289			}
290		}
291		return matched
292	}
293	matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
294
295	// It's possible that we have adjacent equal blocks in the
296	// matching_blocks list now.
297	nonAdjacent := []Match{}
298	i1, j1, k1 := 0, 0, 0
299	for _, b := range matched {
300		// Is this block adjacent to i1, j1, k1?
301		i2, j2, k2 := b.A, b.B, b.Size
302		if i1+k1 == i2 && j1+k1 == j2 {
303			// Yes, so collapse them -- this just increases the length of
304			// the first block by the length of the second, and the first
305			// block so lengthened remains the block to compare against.
306			k1 += k2
307		} else {
308			// Not adjacent.  Remember the first block (k1==0 means it's
309			// the dummy we started with), and make the second block the
310			// new block to compare against.
311			if k1 > 0 {
312				nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
313			}
314			i1, j1, k1 = i2, j2, k2
315		}
316	}
317	if k1 > 0 {
318		nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
319	}
320
321	nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
322	m.matchingBlocks = nonAdjacent
323	return m.matchingBlocks
324}
325
326// Return list of 5-tuples describing how to turn a into b.
327//
328// Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple
329// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
330// tuple preceding it, and likewise for j1 == the previous j2.
331//
332// The tags are characters, with these meanings:
333//
334// 'r' (replace):  a[i1:i2] should be replaced by b[j1:j2]
335//
336// 'd' (delete):   a[i1:i2] should be deleted, j1==j2 in this case.
337//
338// 'i' (insert):   b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
339//
340// 'e' (equal):    a[i1:i2] == b[j1:j2]
341func (m *SequenceMatcher) GetOpCodes() []OpCode {
342	if m.opCodes != nil {
343		return m.opCodes
344	}
345	i, j := 0, 0
346	matching := m.GetMatchingBlocks()
347	opCodes := make([]OpCode, 0, len(matching))
348	for _, m := range matching {
349		//  invariant:  we've pumped out correct diffs to change
350		//  a[:i] into b[:j], and the next matching block is
351		//  a[ai:ai+size] == b[bj:bj+size]. So we need to pump
352		//  out a diff to change a[i:ai] into b[j:bj], pump out
353		//  the matching block, and move (i,j) beyond the match
354		ai, bj, size := m.A, m.B, m.Size
355		tag := byte(0)
356		if i < ai && j < bj {
357			tag = 'r'
358		} else if i < ai {
359			tag = 'd'
360		} else if j < bj {
361			tag = 'i'
362		}
363		if tag > 0 {
364			opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
365		}
366		i, j = ai+size, bj+size
367		// the list of matching blocks is terminated by a
368		// sentinel with size 0
369		if size > 0 {
370			opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
371		}
372	}
373	m.opCodes = opCodes
374	return m.opCodes
375}
376
377// Isolate change clusters by eliminating ranges with no changes.
378//
379// Return a generator of groups with up to n lines of context.
380// Each group is in the same format as returned by GetOpCodes().
381func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
382	if n < 0 {
383		n = 3
384	}
385	codes := m.GetOpCodes()
386	if len(codes) == 0 {
387		codes = []OpCode{OpCode{'e', 0, 1, 0, 1}}
388	}
389	// Fixup leading and trailing groups if they show no changes.
390	if codes[0].Tag == 'e' {
391		c := codes[0]
392		i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
393		codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
394	}
395	if codes[len(codes)-1].Tag == 'e' {
396		c := codes[len(codes)-1]
397		i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
398		codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
399	}
400	nn := n + n
401	groups := [][]OpCode{}
402	group := []OpCode{}
403	for _, c := range codes {
404		i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
405		// End the current group and start a new one whenever
406		// there is a large range with no changes.
407		if c.Tag == 'e' && i2-i1 > nn {
408			group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
409				j1, min(j2, j1+n)})
410			groups = append(groups, group)
411			group = []OpCode{}
412			i1, j1 = max(i1, i2-n), max(j1, j2-n)
413		}
414		group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
415	}
416	if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
417		groups = append(groups, group)
418	}
419	return groups
420}