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

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