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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 java.text.MessageFormat;
  46. import org.eclipse.jgit.errors.DiffInterruptedException;
  47. import org.eclipse.jgit.internal.JGitText;
  48. import org.eclipse.jgit.util.IntList;
  49. import org.eclipse.jgit.util.LongList;
  50. /**
  51. * Diff algorithm, based on "An O(ND) Difference Algorithm and its Variations",
  52. * by Eugene Myers.
  53. * <p>
  54. * The basic idea is to put the line numbers of text A as columns ("x") and the
  55. * lines of text B as rows ("y"). Now you try to find the shortest "edit path"
  56. * from the upper left corner to the lower right corner, where you can always go
  57. * horizontally or vertically, but diagonally from (x,y) to (x+1,y+1) only if
  58. * line x in text A is identical to line y in text B.
  59. * <p>
  60. * Myers' fundamental concept is the "furthest reaching D-path on diagonal k": a
  61. * D-path is an edit path starting at the upper left corner and containing
  62. * exactly D non-diagonal elements ("differences"). The furthest reaching D-path
  63. * on diagonal k is the one that contains the most (diagonal) elements which
  64. * ends on diagonal k (where k = y - x).
  65. * <p>
  66. * Example:
  67. *
  68. * <pre>
  69. * H E L L O W O R L D
  70. * ____
  71. * L \___
  72. * O \___
  73. * W \________
  74. * </pre>
  75. * <p>
  76. * Since every D-path has exactly D horizontal or vertical elements, it can only
  77. * end on the diagonals -D, -D+2, ..., D-2, D.
  78. * <p>
  79. * Since every furthest reaching D-path contains at least one furthest reaching
  80. * (D-1)-path (except for D=0), we can construct them recursively.
  81. * <p>
  82. * Since we are really interested in the shortest edit path, we can start
  83. * looking for a 0-path, then a 1-path, and so on, until we find a path that
  84. * ends in the lower right corner.
  85. * <p>
  86. * To save space, we do not need to store all paths (which has quadratic space
  87. * requirements), but generate the D-paths simultaneously from both sides. When
  88. * the ends meet, we will have found "the middle" of the path. From the end
  89. * points of that diagonal part, we can generate the rest recursively.
  90. * <p>
  91. * This only requires linear space.
  92. * <p>
  93. * The overall (runtime) complexity is:
  94. *
  95. * <pre>
  96. * O(N * D^2 + 2 * N/2 * (D/2)^2 + 4 * N/4 * (D/4)^2 + ...)
  97. * = O(N * D^2 * 5 / 4) = O(N * D^2),
  98. * </pre>
  99. * <p>
  100. * (With each step, we have to find the middle parts of twice as many regions as
  101. * before, but the regions (as well as the D) are halved.)
  102. * <p>
  103. * So the overall runtime complexity stays the same with linear space, albeit
  104. * with a larger constant factor.
  105. *
  106. * @param <S>
  107. * type of sequence.
  108. */
  109. @SuppressWarnings("hiding")
  110. public class MyersDiff<S extends Sequence> {
  111. /** Singleton instance of MyersDiff. */
  112. public static final DiffAlgorithm INSTANCE = new LowLevelDiffAlgorithm() {
  113. @Override
  114. public <S extends Sequence> void diffNonCommon(EditList edits,
  115. HashedSequenceComparator<S> cmp, HashedSequence<S> a,
  116. HashedSequence<S> b, Edit region) {
  117. new MyersDiff<S>(edits, cmp, a, b, region);
  118. }
  119. };
  120. /**
  121. * The list of edits found during the last call to
  122. * {@link #calculateEdits(Edit)}
  123. */
  124. protected EditList edits;
  125. /** Comparison function for sequences. */
  126. protected HashedSequenceComparator<S> cmp;
  127. /**
  128. * The first text to be compared. Referred to as "Text A" in the comments
  129. */
  130. protected HashedSequence<S> a;
  131. /**
  132. * The second text to be compared. Referred to as "Text B" in the comments
  133. */
  134. protected HashedSequence<S> b;
  135. private MyersDiff(EditList edits, HashedSequenceComparator<S> cmp,
  136. HashedSequence<S> a, HashedSequence<S> b, Edit region) {
  137. this.edits = edits;
  138. this.cmp = cmp;
  139. this.a = a;
  140. this.b = b;
  141. calculateEdits(region);
  142. }
  143. // TODO: use ThreadLocal for future multi-threaded operations
  144. MiddleEdit middle = new MiddleEdit();
  145. /**
  146. * Entrypoint into the algorithm this class is all about. This method triggers that the
  147. * differences between A and B are calculated in form of a list of edits.
  148. * @param r portion of the sequences to examine.
  149. */
  150. private void calculateEdits(Edit r) {
  151. middle.initialize(r.beginA, r.endA, r.beginB, r.endB);
  152. if (middle.beginA >= middle.endA &&
  153. middle.beginB >= middle.endB)
  154. return;
  155. calculateEdits(middle.beginA, middle.endA,
  156. middle.beginB, middle.endB);
  157. }
  158. /**
  159. * Calculates the differences between a given part of A against another
  160. * given part of B
  161. *
  162. * @param beginA
  163. * start of the part of A which should be compared
  164. * (0&lt;=beginA&lt;sizeof(A))
  165. * @param endA
  166. * end of the part of A which should be compared
  167. * (beginA&lt;=endA&lt;sizeof(A))
  168. * @param beginB
  169. * start of the part of B which should be compared
  170. * (0&lt;=beginB&lt;sizeof(B))
  171. * @param endB
  172. * end of the part of B which should be compared
  173. * (beginB&lt;=endB&lt;sizeof(B))
  174. */
  175. protected void calculateEdits(int beginA, int endA,
  176. int beginB, int endB) {
  177. Edit edit = middle.calculate(beginA, endA, beginB, endB);
  178. if (beginA < edit.beginA || beginB < edit.beginB) {
  179. int k = edit.beginB - edit.beginA;
  180. int x = middle.backward.snake(k, edit.beginA);
  181. calculateEdits(beginA, x, beginB, k + x);
  182. }
  183. if (edit.getType() != Edit.Type.EMPTY)
  184. edits.add(edits.size(), edit);
  185. // after middle
  186. if (endA > edit.endA || endB > edit.endB) {
  187. int k = edit.endB - edit.endA;
  188. int x = middle.forward.snake(k, edit.endA);
  189. calculateEdits(x, endA, k + x, endB);
  190. }
  191. }
  192. /**
  193. * A class to help bisecting the sequences a and b to find minimal
  194. * edit paths.
  195. *
  196. * As the arrays are reused for space efficiency, you will need one
  197. * instance per thread.
  198. *
  199. * The entry function is the calculate() method.
  200. */
  201. class MiddleEdit {
  202. void initialize(int beginA, int endA, int beginB, int endB) {
  203. this.beginA = beginA; this.endA = endA;
  204. this.beginB = beginB; this.endB = endB;
  205. // strip common parts on either end
  206. int k = beginB - beginA;
  207. this.beginA = forward.snake(k, beginA);
  208. this.beginB = k + this.beginA;
  209. k = endB - endA;
  210. this.endA = backward.snake(k, endA);
  211. this.endB = k + this.endA;
  212. }
  213. /*
  214. * This function calculates the "middle" Edit of the shortest
  215. * edit path between the given subsequences of a and b.
  216. *
  217. * Once a forward path and a backward path meet, we found the
  218. * middle part. From the last snake end point on both of them,
  219. * we construct the Edit.
  220. *
  221. * It is assumed that there is at least one edit in the range.
  222. */
  223. // TODO: measure speed impact when this is synchronized
  224. Edit calculate(int beginA, int endA, int beginB, int endB) {
  225. if (beginA == endA || beginB == endB)
  226. return new Edit(beginA, endA, beginB, endB);
  227. this.beginA = beginA; this.endA = endA;
  228. this.beginB = beginB; this.endB = endB;
  229. /*
  230. * Following the conventions in Myers' paper, "k" is
  231. * the difference between the index into "b" and the
  232. * index into "a".
  233. */
  234. int minK = beginB - endA;
  235. int maxK = endB - beginA;
  236. forward.initialize(beginB - beginA, beginA, minK, maxK);
  237. backward.initialize(endB - endA, endA, minK, maxK);
  238. for (int d = 1; ; d++)
  239. if (forward.calculate(d) ||
  240. backward.calculate(d))
  241. return edit;
  242. }
  243. /*
  244. * For each d, we need to hold the d-paths for the diagonals
  245. * k = -d, -d + 2, ..., d - 2, d. These are stored in the
  246. * forward (and backward) array.
  247. *
  248. * As we allow subsequences, too, this needs some refinement:
  249. * the forward paths start on the diagonal forwardK =
  250. * beginB - beginA, and backward paths start on the diagonal
  251. * backwardK = endB - endA.
  252. *
  253. * So, we need to hold the forward d-paths for the diagonals
  254. * k = forwardK - d, forwardK - d + 2, ..., forwardK + d and
  255. * the analogue for the backward d-paths. This means that
  256. * we can turn (k, d) into the forward array index using this
  257. * formula:
  258. *
  259. * i = (d + k - forwardK) / 2
  260. *
  261. * There is a further complication: the edit paths should not
  262. * leave the specified subsequences, so k is bounded by
  263. * minK = beginB - endA and maxK = endB - beginA. However,
  264. * (k - forwardK) _must_ be odd whenever d is odd, and it
  265. * _must_ be even when d is even.
  266. *
  267. * The values in the "forward" and "backward" arrays are
  268. * positions ("x") in the sequence a, to get the corresponding
  269. * positions ("y") in the sequence b, you have to calculate
  270. * the appropriate k and then y:
  271. *
  272. * k = forwardK - d + i * 2
  273. * y = k + x
  274. *
  275. * (substitute backwardK for forwardK if you want to get the
  276. * y position for an entry in the "backward" array.
  277. */
  278. EditPaths forward = new ForwardEditPaths();
  279. EditPaths backward = new BackwardEditPaths();
  280. /* Some variables which are shared between methods */
  281. protected int beginA, endA, beginB, endB;
  282. protected Edit edit;
  283. abstract class EditPaths {
  284. private IntList x = new IntList();
  285. private LongList snake = new LongList();
  286. int beginK, endK, middleK;
  287. int prevBeginK, prevEndK;
  288. /* if we hit one end early, no need to look further */
  289. int minK, maxK; // TODO: better explanation
  290. final int getIndex(int d, int k) {
  291. // TODO: remove
  292. if (((d + k - middleK) % 2) != 0)
  293. throw new RuntimeException(MessageFormat.format(JGitText.get().unexpectedOddResult, Integer.valueOf(d), Integer.valueOf(k), Integer.valueOf(middleK)));
  294. return (d + k - middleK) / 2;
  295. }
  296. final int getX(int d, int k) {
  297. // TODO: remove
  298. if (k < beginK || k > endK)
  299. throw new RuntimeException(MessageFormat.format(JGitText.get().kNotInRange, Integer.valueOf(k), Integer.valueOf(beginK), Integer.valueOf(endK)));
  300. return x.get(getIndex(d, k));
  301. }
  302. final long getSnake(int d, int k) {
  303. // TODO: remove
  304. if (k < beginK || k > endK)
  305. throw new RuntimeException(MessageFormat.format(JGitText.get().kNotInRange, Integer.valueOf(k), Integer.valueOf(beginK), Integer.valueOf(endK)));
  306. return snake.get(getIndex(d, k));
  307. }
  308. private int forceKIntoRange(int k) {
  309. /* if k is odd, so must be the result */
  310. if (k < minK)
  311. return minK + ((k ^ minK) & 1);
  312. else if (k > maxK)
  313. return maxK - ((k ^ maxK) & 1);
  314. return k;
  315. }
  316. void initialize(int k, int x, int minK, int maxK) {
  317. this.minK = minK;
  318. this.maxK = maxK;
  319. beginK = endK = middleK = k;
  320. this.x.clear();
  321. this.x.add(x);
  322. snake.clear();
  323. snake.add(newSnake(k, x));
  324. }
  325. abstract int snake(int k, int x);
  326. abstract int getLeft(int x);
  327. abstract int getRight(int x);
  328. abstract boolean isBetter(int left, int right);
  329. abstract void adjustMinMaxK(final int k, final int x);
  330. abstract boolean meets(int d, int k, int x, long snake);
  331. final long newSnake(int k, int x) {
  332. long y = k + x;
  333. long ret = ((long) x) << 32;
  334. return ret | y;
  335. }
  336. final int snake2x(long snake) {
  337. return (int) (snake >>> 32);
  338. }
  339. final int snake2y(long snake) {
  340. return (int) snake;
  341. }
  342. final boolean makeEdit(long snake1, long snake2) {
  343. int x1 = snake2x(snake1), x2 = snake2x(snake2);
  344. int y1 = snake2y(snake1), y2 = snake2y(snake2);
  345. /*
  346. * Check for incompatible partial edit paths:
  347. * when there are ambiguities, we might have
  348. * hit incompatible (i.e. non-overlapping)
  349. * forward/backward paths.
  350. *
  351. * In that case, just pretend that we have
  352. * an empty edit at the end of one snake; this
  353. * will force a decision which path to take
  354. * in the next recursion step.
  355. */
  356. if (x1 > x2 || y1 > y2) {
  357. x1 = x2;
  358. y1 = y2;
  359. }
  360. edit = new Edit(x1, x2, y1, y2);
  361. return true;
  362. }
  363. boolean calculate(int d) {
  364. prevBeginK = beginK;
  365. prevEndK = endK;
  366. beginK = forceKIntoRange(middleK - d);
  367. endK = forceKIntoRange(middleK + d);
  368. // TODO: handle i more efficiently
  369. // TODO: walk snake(k, getX(d, k)) only once per (d, k)
  370. // TODO: move end points out of the loop to avoid conditionals inside the loop
  371. // go backwards so that we can avoid temp vars
  372. for (int k = endK; k >= beginK; k -= 2) {
  373. if (Thread.interrupted()) {
  374. throw new DiffInterruptedException();
  375. }
  376. int left = -1, right = -1;
  377. long leftSnake = -1L, rightSnake = -1L;
  378. // TODO: refactor into its own function
  379. if (k > prevBeginK) {
  380. int i = getIndex(d - 1, k - 1);
  381. left = x.get(i);
  382. int end = snake(k - 1, left);
  383. leftSnake = left != end ?
  384. newSnake(k - 1, end) :
  385. snake.get(i);
  386. if (meets(d, k - 1, end, leftSnake))
  387. return true;
  388. left = getLeft(end);
  389. }
  390. if (k < prevEndK) {
  391. int i = getIndex(d - 1, k + 1);
  392. right = x.get(i);
  393. int end = snake(k + 1, right);
  394. rightSnake = right != end ?
  395. newSnake(k + 1, end) :
  396. snake.get(i);
  397. if (meets(d, k + 1, end, rightSnake))
  398. return true;
  399. right = getRight(end);
  400. }
  401. int newX;
  402. long newSnake;
  403. if (k >= prevEndK ||
  404. (k > prevBeginK &&
  405. isBetter(left, right))) {
  406. newX = left;
  407. newSnake = leftSnake;
  408. }
  409. else {
  410. newX = right;
  411. newSnake = rightSnake;
  412. }
  413. if (meets(d, k, newX, newSnake))
  414. return true;
  415. adjustMinMaxK(k, newX);
  416. int i = getIndex(d, k);
  417. x.set(i, newX);
  418. snake.set(i, newSnake);
  419. }
  420. return false;
  421. }
  422. }
  423. class ForwardEditPaths extends EditPaths {
  424. final int snake(int k, int x) {
  425. for (; x < endA && k + x < endB; x++)
  426. if (!cmp.equals(a, x, b, k + x))
  427. break;
  428. return x;
  429. }
  430. final int getLeft(final int x) {
  431. return x;
  432. }
  433. final int getRight(final int x) {
  434. return x + 1;
  435. }
  436. final boolean isBetter(final int left, final int right) {
  437. return left > right;
  438. }
  439. final void adjustMinMaxK(final int k, final int x) {
  440. if (x >= endA || k + x >= endB) {
  441. if (k > backward.middleK)
  442. maxK = k;
  443. else
  444. minK = k;
  445. }
  446. }
  447. final boolean meets(int d, int k, int x, long snake) {
  448. if (k < backward.beginK || k > backward.endK)
  449. return false;
  450. // TODO: move out of loop
  451. if (((d - 1 + k - backward.middleK) % 2) != 0)
  452. return false;
  453. if (x < backward.getX(d - 1, k))
  454. return false;
  455. makeEdit(snake, backward.getSnake(d - 1, k));
  456. return true;
  457. }
  458. }
  459. class BackwardEditPaths extends EditPaths {
  460. final int snake(int k, int x) {
  461. for (; x > beginA && k + x > beginB; x--)
  462. if (!cmp.equals(a, x - 1, b, k + x - 1))
  463. break;
  464. return x;
  465. }
  466. final int getLeft(final int x) {
  467. return x - 1;
  468. }
  469. final int getRight(final int x) {
  470. return x;
  471. }
  472. final boolean isBetter(final int left, final int right) {
  473. return left < right;
  474. }
  475. final void adjustMinMaxK(final int k, final int x) {
  476. if (x <= beginA || k + x <= beginB) {
  477. if (k > forward.middleK)
  478. maxK = k;
  479. else
  480. minK = k;
  481. }
  482. }
  483. final boolean meets(int d, int k, int x, long snake) {
  484. if (k < forward.beginK || k > forward.endK)
  485. return false;
  486. // TODO: move out of loop
  487. if (((d + k - forward.middleK) % 2) != 0)
  488. return false;
  489. if (x > forward.getX(d, k))
  490. return false;
  491. makeEdit(forward.getSnake(d, k), snake);
  492. return true;
  493. }
  494. }
  495. }
  496. /**
  497. * @param args two filenames specifying the contents to be diffed
  498. */
  499. public static void main(String[] args) {
  500. if (args.length != 2) {
  501. System.err.println(JGitText.get().need2Arguments);
  502. System.exit(1);
  503. }
  504. try {
  505. RawText a = new RawText(new java.io.File(args[0]));
  506. RawText b = new RawText(new java.io.File(args[1]));
  507. EditList r = INSTANCE.diff(RawTextComparator.DEFAULT, a, b);
  508. System.out.println(r.toString());
  509. } catch (Exception e) {
  510. e.printStackTrace();
  511. }
  512. }
  513. }