diff.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2018 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements an algorithm to compute the
  10. ## `diff`:idx: between two sequences of lines.
  11. ##
  12. ## - To learn more see `Diff on Wikipedia. <http://wikipedia.org/wiki/Diff>`_
  13. runnableExamples:
  14. assert diffInt(
  15. [0, 1, 2, 3, 4, 5, 6, 7, 8],
  16. [-1, 1, 2, 3, 4, 5, 666, 7, 42]) ==
  17. @[Item(startA: 0, startB: 0, deletedA: 1, insertedB: 1),
  18. Item(startA: 6, startB: 6, deletedA: 1, insertedB: 1),
  19. Item(startA: 8, startB: 8, deletedA: 1, insertedB: 1)]
  20. runnableExamples:
  21. # 2 samples of text (from "The Call of Cthulhu" by Lovecraft)
  22. let txt0 = """
  23. abc
  24. def ghi
  25. jkl2"""
  26. let txt1 = """
  27. bacx
  28. abc
  29. def ghi
  30. jkl"""
  31. assert diffText(txt0, txt1) ==
  32. @[Item(startA: 0, startB: 0, deletedA: 0, insertedB: 1),
  33. Item(startA: 2, startB: 3, deletedA: 1, insertedB: 1)]
  34. # code owner: Arne Döring
  35. #
  36. # This is based on C# code written by Matthias Hertel, http://www.mathertel.de
  37. #
  38. # This Class implements the Difference Algorithm published in
  39. # "An O(ND) Difference Algorithm and its Variations" by Eugene Myers
  40. # Algorithmica Vol. 1 No. 2, 1986, p 251.
  41. import tables, strutils
  42. type
  43. Item* = object ## An Item in the list of differences.
  44. startA*: int ## Start Line number in Data A.
  45. startB*: int ## Start Line number in Data B.
  46. deletedA*: int ## Number of changes in Data A.
  47. insertedB*: int ## Number of changes in Data B.
  48. DiffData = object ## Data on one input file being compared.
  49. data: seq[int] ## Buffer of numbers that will be compared.
  50. modified: seq[bool] ## Array of booleans that flag for modified
  51. ## data. This is the result of the diff.
  52. ## This means deletedA in the first Data or
  53. ## inserted in the second Data.
  54. Smsrd = object
  55. x, y: int
  56. # template to avoid a seq copy. Required until `sink` parameters are ready.
  57. template newDiffData(initData: seq[int]; L: int): DiffData =
  58. DiffData(
  59. data: initData,
  60. modified: newSeq[bool](L + 2)
  61. )
  62. proc len(d: DiffData): int {.inline.} = d.data.len
  63. proc diffCodes(aText: string; h: var Table[string, int]): DiffData =
  64. ## This function converts all textlines of the text into unique numbers for every unique textline
  65. ## so further work can work only with simple numbers.
  66. ## `aText` the input text
  67. ## `h` This extern initialized hashtable is used for storing all ever used textlines.
  68. ## `trimSpace` ignore leading and trailing space characters
  69. ## Returns a array of integers.
  70. var lastUsedCode = h.len
  71. result.data = newSeq[int]()
  72. for s in aText.splitLines:
  73. if h.contains s:
  74. result.data.add h[s]
  75. else:
  76. inc lastUsedCode
  77. h[s] = lastUsedCode
  78. result.data.add lastUsedCode
  79. result.modified = newSeq[bool](result.data.len + 2)
  80. proc optimize(data: var DiffData) =
  81. ## If a sequence of modified lines starts with a line that contains the same content
  82. ## as the line that appends the changes, the difference sequence is modified so that the
  83. ## appended line and not the starting line is marked as modified.
  84. ## This leads to more readable diff sequences when comparing text files.
  85. var startPos = 0
  86. while startPos < data.len:
  87. while startPos < data.len and not data.modified[startPos]:
  88. inc startPos
  89. var endPos = startPos
  90. while endPos < data.len and data.modified[endPos]:
  91. inc endPos
  92. if endPos < data.len and data.data[startPos] == data.data[endPos]:
  93. data.modified[startPos] = false
  94. data.modified[endPos] = true
  95. else:
  96. startPos = endPos
  97. proc sms(dataA: var DiffData; lowerA, upperA: int; dataB: DiffData; lowerB, upperB: int;
  98. downVector, upVector: var openArray[int]): Smsrd =
  99. ## This is the algorithm to find the Shortest Middle Snake (sms).
  100. ## `dataA` sequence A
  101. ## `lowerA` lower bound of the actual range in dataA
  102. ## `upperA` upper bound of the actual range in dataA (exclusive)
  103. ## `dataB` sequence B
  104. ## `lowerB` lower bound of the actual range in dataB
  105. ## `upperB` upper bound of the actual range in dataB (exclusive)
  106. ## `downVector` a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.
  107. ## `upVector` a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.
  108. ## Returns a MiddleSnakeData record containing x,y and u,v.
  109. let max = dataA.len + dataB.len + 1
  110. let downK = lowerA - lowerB # the k-line to start the forward search
  111. let upK = upperA - upperB # the k-line to start the reverse search
  112. let delta = (upperA - lowerA) - (upperB - lowerB)
  113. let oddDelta = (delta and 1) != 0
  114. # The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based
  115. # and are access using a specific offset: upOffset upVector and downOffset for downVector
  116. let downOffset = max - downK
  117. let upOffset = max - upK
  118. let maxD = ((upperA - lowerA + upperB - lowerB) div 2) + 1
  119. downVector[downOffset + downK + 1] = lowerA
  120. upVector[upOffset + upK - 1] = upperA
  121. for D in 0 .. maxD:
  122. # Extend the forward path.
  123. for k in countup(downK - D, downK + D, 2):
  124. # find the only or better starting point
  125. var x: int
  126. if k == downK - D:
  127. x = downVector[downOffset + k + 1] # down
  128. else:
  129. x = downVector[downOffset + k - 1] + 1 # a step to the right
  130. if k < downK + D and downVector[downOffset + k + 1] >= x:
  131. x = downVector[downOffset + k + 1] # down
  132. var y = x - k
  133. # find the end of the furthest reaching forward D-path in diagonal k.
  134. while x < upperA and y < upperB and dataA.data[x] == dataB.data[y]:
  135. inc x
  136. inc y
  137. downVector[downOffset + k] = x
  138. # overlap ?
  139. if oddDelta and upK - D < k and k < upK + D:
  140. if upVector[upOffset + k] <= downVector[downOffset + k]:
  141. return Smsrd(x: downVector[downOffset + k],
  142. y: downVector[downOffset + k] - k)
  143. # Extend the reverse path.
  144. for k in countup(upK - D, upK + D, 2):
  145. # find the only or better starting point
  146. var x: int
  147. if k == upK + D:
  148. x = upVector[upOffset + k - 1] # up
  149. else:
  150. x = upVector[upOffset + k + 1] - 1 # left
  151. if k > upK - D and upVector[upOffset + k - 1] < x:
  152. x = upVector[upOffset + k - 1] # up
  153. var y = x - k
  154. while x > lowerA and y > lowerB and dataA.data[x - 1] == dataB.data[y - 1]:
  155. dec x
  156. dec y
  157. upVector[upOffset + k] = x
  158. # overlap ?
  159. if not oddDelta and downK-D <= k and k <= downK+D:
  160. if upVector[upOffset + k] <= downVector[downOffset + k]:
  161. return Smsrd(x: downVector[downOffset + k],
  162. y: downVector[downOffset + k] - k)
  163. assert false, "the algorithm should never come here."
  164. proc lcs(dataA: var DiffData; lowerA, upperA: int; dataB: var DiffData; lowerB, upperB: int;
  165. downVector, upVector: var openArray[int]) =
  166. ## This is the divide-and-conquer implementation of the longes common-subsequence (lcs)
  167. ## algorithm.
  168. ## The published algorithm passes recursively parts of the A and B sequences.
  169. ## To avoid copying these arrays the lower and upper bounds are passed while the sequences stay constant.
  170. ## `dataA` sequence A
  171. ## `lowerA` lower bound of the actual range in dataA
  172. ## `upperA` upper bound of the actual range in dataA (exclusive)
  173. ## `dataB` sequence B
  174. ## `lowerB` lower bound of the actual range in dataB
  175. ## `upperB` upper bound of the actual range in dataB (exclusive)
  176. ## `downVector` a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.
  177. ## `upVector` a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.
  178. # make mutable copy:
  179. var lowerA = lowerA
  180. var lowerB = lowerB
  181. var upperA = upperA
  182. var upperB = upperB
  183. # Fast walkthrough equal lines at the start
  184. while lowerA < upperA and lowerB < upperB and dataA.data[lowerA] == dataB.data[lowerB]:
  185. inc lowerA
  186. inc lowerB
  187. # Fast walkthrough equal lines at the end
  188. while lowerA < upperA and lowerB < upperB and dataA.data[upperA - 1] == dataB.data[upperB - 1]:
  189. dec upperA
  190. dec upperB
  191. if lowerA == upperA:
  192. # mark as inserted lines.
  193. while lowerB < upperB:
  194. dataB.modified[lowerB] = true
  195. inc lowerB
  196. elif lowerB == upperB:
  197. # mark as deleted lines.
  198. while lowerA < upperA:
  199. dataA.modified[lowerA] = true
  200. inc lowerA
  201. else:
  202. # Find the middle snake and length of an optimal path for A and B
  203. let smsrd = sms(dataA, lowerA, upperA, dataB, lowerB, upperB, downVector, upVector)
  204. # Debug.Write(2, "MiddleSnakeData", String.Format("{0},{1}", smsrd.x, smsrd.y))
  205. # The path is from LowerX to (x,y) and (x,y) to UpperX
  206. lcs(dataA, lowerA, smsrd.x, dataB, lowerB, smsrd.y, downVector, upVector)
  207. lcs(dataA, smsrd.x, upperA, dataB, smsrd.y, upperB, downVector, upVector) # 2002.09.20: no need for 2 points
  208. proc createDiffs(dataA, dataB: DiffData): seq[Item] =
  209. ## Scan the tables of which lines are inserted and deleted,
  210. ## producing an edit script in forward order.
  211. var startA = 0
  212. var startB = 0
  213. var lineA = 0
  214. var lineB = 0
  215. while lineA < dataA.len or lineB < dataB.len:
  216. if lineA < dataA.len and not dataA.modified[lineA] and
  217. lineB < dataB.len and not dataB.modified[lineB]:
  218. # equal lines
  219. inc lineA
  220. inc lineB
  221. else:
  222. # maybe deleted and/or inserted lines
  223. startA = lineA
  224. startB = lineB
  225. while lineA < dataA.len and (lineB >= dataB.len or dataA.modified[lineA]):
  226. inc lineA
  227. while lineB < dataB.len and (lineA >= dataA.len or dataB.modified[lineB]):
  228. inc lineB
  229. if (startA < lineA) or (startB < lineB):
  230. result.add Item(startA: startA,
  231. startB: startB,
  232. deletedA: lineA - startA,
  233. insertedB: lineB - startB)
  234. proc diffInt*(arrayA, arrayB: openArray[int]): seq[Item] =
  235. ## Find the difference in 2 arrays of integers.
  236. ##
  237. ## `arrayA` A-version of the numbers (usually the old one)
  238. ##
  239. ## `arrayB` B-version of the numbers (usually the new one)
  240. ##
  241. ## Returns a sequence of Items that describe the differences.
  242. # The A-Version of the data (original data) to be compared.
  243. var dataA = newDiffData(@arrayA, arrayA.len)
  244. # The B-Version of the data (modified data) to be compared.
  245. var dataB = newDiffData(@arrayB, arrayB.len)
  246. let max = dataA.len + dataB.len + 1
  247. # vector for the (0,0) to (x,y) search
  248. var downVector = newSeq[int](2 * max + 2)
  249. # vector for the (u,v) to (N,M) search
  250. var upVector = newSeq[int](2 * max + 2)
  251. lcs(dataA, 0, dataA.len, dataB, 0, dataB.len, downVector, upVector)
  252. result = createDiffs(dataA, dataB)
  253. proc diffText*(textA, textB: string): seq[Item] =
  254. ## Find the difference in 2 text documents, comparing by textlines.
  255. ##
  256. ## The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents
  257. ## each line is converted into a (hash) number. This hash-value is computed by storing all
  258. ## textlines into a common hashtable so i can find duplicates in there, and generating a
  259. ## new number each time a new textline is inserted.
  260. ##
  261. ## `textA` A-version of the text (usually the old one)
  262. ##
  263. ## `textB` B-version of the text (usually the new one)
  264. ##
  265. ## Returns a seq of Items that describe the differences.
  266. # See also `gitutils.diffStrings`.
  267. # prepare the input-text and convert to comparable numbers.
  268. var h = initTable[string, int]() # TextA.len + TextB.len <- probably wrong initial size
  269. # The A-Version of the data (original data) to be compared.
  270. var dataA = diffCodes(textA, h)
  271. # The B-Version of the data (modified data) to be compared.
  272. var dataB = diffCodes(textB, h)
  273. h.clear # free up hashtable memory (maybe)
  274. let max = dataA.len + dataB.len + 1
  275. # vector for the (0,0) to (x,y) search
  276. var downVector = newSeq[int](2 * max + 2)
  277. # vector for the (u,v) to (N,M) search
  278. var upVector = newSeq[int](2 * max + 2)
  279. lcs(dataA, 0, dataA.len, dataB, 0, dataB.len, downVector, upVector)
  280. optimize(dataA)
  281. optimize(dataB)
  282. result = createDiffs(dataA, dataB)