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

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