You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MyersDiff.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. * Copyright (C) 2008-2009, Johannes E. Schindelin <johannes.schindelin@gmx.de>
  3. * Copyright (C) 2009, Johannes Schindelin <johannes.schindelin@gmx.de>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.diff;
  45. import org.eclipse.jgit.util.IntList;
  46. import org.eclipse.jgit.util.LongList;
  47. /**
  48. * Diff algorithm, based on "An O(ND) Difference Algorithm and its
  49. * Variations", by Eugene Myers.
  50. *
  51. * The basic idea is to put the line numbers of text A as columns ("x") and the
  52. * lines of text B as rows ("y"). Now you try to find the shortest "edit path"
  53. * from the upper left corner to the lower right corner, where you can
  54. * always go horizontally or vertically, but diagonally from (x,y) to
  55. * (x+1,y+1) only if line x in text A is identical to line y in text B.
  56. *
  57. * Myers' fundamental concept is the "furthest reaching D-path on diagonal k":
  58. * a D-path is an edit path starting at the upper left corner and containing
  59. * exactly D non-diagonal elements ("differences"). The furthest reaching
  60. * D-path on diagonal k is the one that contains the most (diagonal) elements
  61. * which ends on diagonal k (where k = y - x).
  62. *
  63. * Example:
  64. *
  65. * H E L L O W O R L D
  66. * ____
  67. * L \___
  68. * O \___
  69. * W \________
  70. *
  71. * Since every D-path has exactly D horizontal or vertical elements, it can
  72. * only end on the diagonals -D, -D+2, ..., D-2, D.
  73. *
  74. * Since every furthest reaching D-path contains at least one furthest
  75. * reaching (D-1)-path (except for D=0), we can construct them recursively.
  76. *
  77. * Since we are really interested in the shortest edit path, we can start
  78. * looking for a 0-path, then a 1-path, and so on, until we find a path that
  79. * ends in the lower right corner.
  80. *
  81. * To save space, we do not need to store all paths (which has quadratic space
  82. * requirements), but generate the D-paths simultaneously from both sides.
  83. * When the ends meet, we will have found "the middle" of the path. From the
  84. * end points of that diagonal part, we can generate the rest recursively.
  85. *
  86. * This only requires linear space.
  87. *
  88. * The overall (runtime) complexity is
  89. *
  90. * O(N * D^2 + 2 * N/2 * (D/2)^2 + 4 * N/4 * (D/4)^2 + ...)
  91. * = O(N * D^2 * 5 / 4) = O(N * D^2),
  92. *
  93. * (With each step, we have to find the middle parts of twice as many regions
  94. * as before, but the regions (as well as the D) are halved.)
  95. *
  96. * So the overall runtime complexity stays the same with linear space,
  97. * albeit with a larger constant factor.
  98. */
  99. public class MyersDiff {
  100. /**
  101. * The list of edits found during the last call to {@link #calculateEdits()}
  102. */
  103. protected EditList edits;
  104. /**
  105. * The first text to be compared. Referred to as "Text A" in the comments
  106. */
  107. protected Sequence a;
  108. /**
  109. * The second text to be compared. Referred to as "Text B" in the comments
  110. */
  111. protected Sequence b;
  112. /**
  113. * The only constructor
  114. *
  115. * @param a the text A which should be compared
  116. * @param b the text B which should be compared
  117. */
  118. public MyersDiff(Sequence a, Sequence b) {
  119. this.a = a;
  120. this.b = b;
  121. calculateEdits();
  122. }
  123. /**
  124. * @return the list of edits found during the last call to {@link #calculateEdits()}
  125. */
  126. public EditList getEdits() {
  127. return edits;
  128. }
  129. // TODO: use ThreadLocal for future multi-threaded operations
  130. MiddleEdit middle = new MiddleEdit();
  131. /**
  132. * Entrypoint into the algorithm this class is all about. This method triggers that the
  133. * differences between A and B are calculated in form of a list of edits.
  134. */
  135. protected void calculateEdits() {
  136. edits = new EditList();
  137. middle.initialize(0, a.size(), 0, b.size());
  138. if (middle.beginA >= middle.endA &&
  139. middle.beginB >= middle.endB)
  140. return;
  141. calculateEdits(middle.beginA, middle.endA,
  142. middle.beginB, middle.endB);
  143. }
  144. /**
  145. * Calculates the differences between a given part of A against another given part of B
  146. * @param beginA start of the part of A which should be compared (0<=beginA<sizeof(A))
  147. * @param endA end of the part of A which should be compared (beginA<=endA<sizeof(A))
  148. * @param beginB start of the part of B which should be compared (0<=beginB<sizeof(B))
  149. * @param endB end of the part of B which should be compared (beginB<=endB<sizeof(B))
  150. */
  151. protected void calculateEdits(int beginA, int endA,
  152. int beginB, int endB) {
  153. Edit edit = middle.calculate(beginA, endA, beginB, endB);
  154. if (beginA < edit.beginA || beginB < edit.beginB) {
  155. int k = edit.beginB - edit.beginA;
  156. int x = middle.backward.snake(k, edit.beginA);
  157. calculateEdits(beginA, x, beginB, k + x);
  158. }
  159. if (edit.getType() != Edit.Type.EMPTY)
  160. edits.add(edits.size(), edit);
  161. // after middle
  162. if (endA > edit.endA || endB > edit.endB) {
  163. int k = edit.endB - edit.endA;
  164. int x = middle.forward.snake(k, edit.endA);
  165. calculateEdits(x, endA, k + x, endB);
  166. }
  167. }
  168. /**
  169. * A class to help bisecting the sequences a and b to find minimal
  170. * edit paths.
  171. *
  172. * As the arrays are reused for space efficiency, you will need one
  173. * instance per thread.
  174. *
  175. * The entry function is the calculate() method.
  176. */
  177. class MiddleEdit {
  178. void initialize(int beginA, int endA, int beginB, int endB) {
  179. this.beginA = beginA; this.endA = endA;
  180. this.beginB = beginB; this.endB = endB;
  181. // strip common parts on either end
  182. int k = beginB - beginA;
  183. this.beginA = forward.snake(k, beginA);
  184. this.beginB = k + this.beginA;
  185. k = endB - endA;
  186. this.endA = backward.snake(k, endA);
  187. this.endB = k + this.endA;
  188. }
  189. /*
  190. * This function calculates the "middle" Edit of the shortest
  191. * edit path between the given subsequences of a and b.
  192. *
  193. * Once a forward path and a backward path meet, we found the
  194. * middle part. From the last snake end point on both of them,
  195. * we construct the Edit.
  196. *
  197. * It is assumed that there is at least one edit in the range.
  198. */
  199. // TODO: measure speed impact when this is synchronized
  200. Edit calculate(int beginA, int endA, int beginB, int endB) {
  201. if (beginA == endA || beginB == endB)
  202. return new Edit(beginA, endA, beginB, endB);
  203. this.beginA = beginA; this.endA = endA;
  204. this.beginB = beginB; this.endB = endB;
  205. /*
  206. * Following the conventions in Myers' paper, "k" is
  207. * the difference between the index into "b" and the
  208. * index into "a".
  209. */
  210. int minK = beginB - endA;
  211. int maxK = endB - beginA;
  212. forward.initialize(beginB - beginA, beginA, minK, maxK);
  213. backward.initialize(endB - endA, endA, minK, maxK);
  214. for (int d = 1; ; d++)
  215. if (forward.calculate(d) ||
  216. backward.calculate(d))
  217. return edit;
  218. }
  219. /*
  220. * For each d, we need to hold the d-paths for the diagonals
  221. * k = -d, -d + 2, ..., d - 2, d. These are stored in the
  222. * forward (and backward) array.
  223. *
  224. * As we allow subsequences, too, this needs some refinement:
  225. * the forward paths start on the diagonal forwardK =
  226. * beginB - beginA, and backward paths start on the diagonal
  227. * backwardK = endB - endA.
  228. *
  229. * So, we need to hold the forward d-paths for the diagonals
  230. * k = forwardK - d, forwardK - d + 2, ..., forwardK + d and
  231. * the analogue for the backward d-paths. This means that
  232. * we can turn (k, d) into the forward array index using this
  233. * formula:
  234. *
  235. * i = (d + k - forwardK) / 2
  236. *
  237. * There is a further complication: the edit paths should not
  238. * leave the specified subsequences, so k is bounded by
  239. * minK = beginB - endA and maxK = endB - beginA. However,
  240. * (k - forwardK) _must_ be odd whenever d is odd, and it
  241. * _must_ be even when d is even.
  242. *
  243. * The values in the "forward" and "backward" arrays are
  244. * positions ("x") in the sequence a, to get the corresponding
  245. * positions ("y") in the sequence b, you have to calculate
  246. * the appropriate k and then y:
  247. *
  248. * k = forwardK - d + i * 2
  249. * y = k + x
  250. *
  251. * (substitute backwardK for forwardK if you want to get the
  252. * y position for an entry in the "backward" array.
  253. */
  254. EditPaths forward = new ForwardEditPaths();
  255. EditPaths backward = new BackwardEditPaths();
  256. /* Some variables which are shared between methods */
  257. protected int beginA, endA, beginB, endB;
  258. protected Edit edit;
  259. abstract class EditPaths {
  260. private IntList x = new IntList();
  261. private LongList snake = new LongList();
  262. int beginK, endK, middleK;
  263. int prevBeginK, prevEndK;
  264. /* if we hit one end early, no need to look further */
  265. int minK, maxK; // TODO: better explanation
  266. final int getIndex(int d, int k) {
  267. // TODO: remove
  268. if (((d + k - middleK) % 2) == 1)
  269. throw new RuntimeException("odd: " + d + " + " + k + " - " + middleK);
  270. return (d + k - middleK) / 2;
  271. }
  272. final int getX(int d, int k) {
  273. // TODO: remove
  274. if (k < beginK || k > endK)
  275. throw new RuntimeException("k " + k + " not in " + beginK + " - " + endK);
  276. return x.get(getIndex(d, k));
  277. }
  278. final long getSnake(int d, int k) {
  279. // TODO: remove
  280. if (k < beginK || k > endK)
  281. throw new RuntimeException("k " + k + " not in " + beginK + " - " + endK);
  282. return snake.get(getIndex(d, k));
  283. }
  284. private int forceKIntoRange(int k) {
  285. /* if k is odd, so must be the result */
  286. if (k < minK)
  287. return minK + ((k ^ minK) & 1);
  288. else if (k > maxK)
  289. return maxK - ((k ^ maxK) & 1);
  290. return k;
  291. }
  292. void initialize(int k, int x, int minK, int maxK) {
  293. this.minK = minK;
  294. this.maxK = maxK;
  295. beginK = endK = middleK = k;
  296. this.x.clear();
  297. this.x.add(x);
  298. snake.clear();
  299. snake.add(newSnake(k, x));
  300. }
  301. abstract int snake(int k, int x);
  302. abstract int getLeft(int x);
  303. abstract int getRight(int x);
  304. abstract boolean isBetter(int left, int right);
  305. abstract void adjustMinMaxK(final int k, final int x);
  306. abstract boolean meets(int d, int k, int x, long snake);
  307. final long newSnake(int k, int x) {
  308. long y = k + x;
  309. long ret = ((long) x) << 32;
  310. return ret | y;
  311. }
  312. final int snake2x(long snake) {
  313. return (int) (snake >>> 32);
  314. }
  315. final int snake2y(long snake) {
  316. return (int) snake;
  317. }
  318. final boolean makeEdit(long snake1, long snake2) {
  319. int x1 = snake2x(snake1), x2 = snake2x(snake2);
  320. int y1 = snake2y(snake1), y2 = snake2y(snake2);
  321. /*
  322. * Check for incompatible partial edit paths:
  323. * when there are ambiguities, we might have
  324. * hit incompatible (i.e. non-overlapping)
  325. * forward/backward paths.
  326. *
  327. * In that case, just pretend that we have
  328. * an empty edit at the end of one snake; this
  329. * will force a decision which path to take
  330. * in the next recursion step.
  331. */
  332. if (x1 > x2 || y1 > y2) {
  333. x1 = x2;
  334. y1 = y2;
  335. }
  336. edit = new Edit(x1, x2, y1, y2);
  337. return true;
  338. }
  339. boolean calculate(int d) {
  340. prevBeginK = beginK;
  341. prevEndK = endK;
  342. beginK = forceKIntoRange(middleK - d);
  343. endK = forceKIntoRange(middleK + d);
  344. // TODO: handle i more efficiently
  345. // TODO: walk snake(k, getX(d, k)) only once per (d, k)
  346. // TODO: move end points out of the loop to avoid conditionals inside the loop
  347. // go backwards so that we can avoid temp vars
  348. for (int k = endK; k >= beginK; k -= 2) {
  349. int left = -1, right = -1;
  350. long leftSnake = -1L, rightSnake = -1L;
  351. // TODO: refactor into its own function
  352. if (k > prevBeginK) {
  353. int i = getIndex(d - 1, k - 1);
  354. left = x.get(i);
  355. int end = snake(k - 1, left);
  356. leftSnake = left != end ?
  357. newSnake(k - 1, end) :
  358. snake.get(i);
  359. if (meets(d, k - 1, end, leftSnake))
  360. return true;
  361. left = getLeft(end);
  362. }
  363. if (k < prevEndK) {
  364. int i = getIndex(d - 1, k + 1);
  365. right = x.get(i);
  366. int end = snake(k + 1, right);
  367. rightSnake = right != end ?
  368. newSnake(k + 1, end) :
  369. snake.get(i);
  370. if (meets(d, k + 1, end, rightSnake))
  371. return true;
  372. right = getRight(end);
  373. }
  374. int newX;
  375. long newSnake;
  376. if (k >= prevEndK ||
  377. (k > prevBeginK &&
  378. isBetter(left, right))) {
  379. newX = left;
  380. newSnake = leftSnake;
  381. }
  382. else {
  383. newX = right;
  384. newSnake = rightSnake;
  385. }
  386. if (meets(d, k, newX, newSnake))
  387. return true;
  388. adjustMinMaxK(k, newX);
  389. int i = getIndex(d, k);
  390. x.set(i, newX);
  391. snake.set(i, newSnake);
  392. }
  393. return false;
  394. }
  395. }
  396. class ForwardEditPaths extends EditPaths {
  397. final int snake(int k, int x) {
  398. for (; x < endA && k + x < endB; x++)
  399. if (!a.equals(x, b, k + x))
  400. break;
  401. return x;
  402. }
  403. final int getLeft(final int x) {
  404. return x;
  405. }
  406. final int getRight(final int x) {
  407. return x + 1;
  408. }
  409. final boolean isBetter(final int left, final int right) {
  410. return left > right;
  411. }
  412. final void adjustMinMaxK(final int k, final int x) {
  413. if (x >= endA || k + x >= endB) {
  414. if (k > backward.middleK)
  415. maxK = k;
  416. else
  417. minK = k;
  418. }
  419. }
  420. final boolean meets(int d, int k, int x, long snake) {
  421. if (k < backward.beginK || k > backward.endK)
  422. return false;
  423. // TODO: move out of loop
  424. if (((d - 1 + k - backward.middleK) % 2) == 1)
  425. return false;
  426. if (x < backward.getX(d - 1, k))
  427. return false;
  428. makeEdit(snake, backward.getSnake(d - 1, k));
  429. return true;
  430. }
  431. }
  432. class BackwardEditPaths extends EditPaths {
  433. final int snake(int k, int x) {
  434. for (; x > beginA && k + x > beginB; x--)
  435. if (!a.equals(x - 1, b, k + x - 1))
  436. break;
  437. return x;
  438. }
  439. final int getLeft(final int x) {
  440. return x - 1;
  441. }
  442. final int getRight(final int x) {
  443. return x;
  444. }
  445. final boolean isBetter(final int left, final int right) {
  446. return left < right;
  447. }
  448. final void adjustMinMaxK(final int k, final int x) {
  449. if (x <= beginA || k + x <= beginB) {
  450. if (k > forward.middleK)
  451. maxK = k;
  452. else
  453. minK = k;
  454. }
  455. }
  456. final boolean meets(int d, int k, int x, long snake) {
  457. if (k < forward.beginK || k > forward.endK)
  458. return false;
  459. // TODO: move out of loop
  460. if (((d + k - forward.middleK) % 2) == 1)
  461. return false;
  462. if (x > forward.getX(d, k))
  463. return false;
  464. makeEdit(forward.getSnake(d, k), snake);
  465. return true;
  466. }
  467. }
  468. }
  469. /**
  470. * @param args two filenames specifying the contents to be diffed
  471. */
  472. public static void main(String[] args) {
  473. if (args.length != 2) {
  474. System.err.println("Need 2 arguments");
  475. System.exit(1);
  476. }
  477. try {
  478. RawText a = new RawText(new java.io.File(args[0]));
  479. RawText b = new RawText(new java.io.File(args[1]));
  480. MyersDiff diff = new MyersDiff(a, b);
  481. System.out.println(diff.getEdits().toString());
  482. } catch (Exception e) {
  483. e.printStackTrace();
  484. }
  485. }
  486. }