diff.go 13 KB

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