DiffEngine.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. namespace Drupal\Component\Diff\Engine;
  3. use Drupal\Component\Utility\Unicode;
  4. /**
  5. * Class used internally by Diff to actually compute the diffs.
  6. *
  7. * The algorithm used here is mostly lifted from the perl module
  8. * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
  9. * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
  10. *
  11. * More ideas are taken from:
  12. * http://www.ics.uci.edu/~eppstein/161/960229.html
  13. *
  14. * Some ideas (and a bit of code) are from analyze.c, from GNU
  15. * diffutils-2.7, which can be found at:
  16. * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
  17. *
  18. * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
  19. * are my own.
  20. *
  21. * Line length limits for robustness added by Tim Starling, 2005-08-31
  22. *
  23. * @author Geoffrey T. Dairiki, Tim Starling
  24. * @private
  25. * @subpackage DifferenceEngine
  26. */
  27. class DiffEngine {
  28. const USE_ASSERTS = FALSE;
  29. const MAX_XREF_LENGTH = 10000;
  30. public function diff($from_lines, $to_lines) {
  31. $n_from = sizeof($from_lines);
  32. $n_to = sizeof($to_lines);
  33. $this->xchanged = $this->ychanged = [];
  34. $this->xv = $this->yv = [];
  35. $this->xind = $this->yind = [];
  36. unset($this->seq);
  37. unset($this->in_seq);
  38. unset($this->lcs);
  39. // Skip leading common lines.
  40. for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
  41. if ($from_lines[$skip] !== $to_lines[$skip]) {
  42. break;
  43. }
  44. $this->xchanged[$skip] = $this->ychanged[$skip] = FALSE;
  45. }
  46. // Skip trailing common lines.
  47. $xi = $n_from;
  48. $yi = $n_to;
  49. for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
  50. if ($from_lines[$xi] !== $to_lines[$yi]) {
  51. break;
  52. }
  53. $this->xchanged[$xi] = $this->ychanged[$yi] = FALSE;
  54. }
  55. // Ignore lines which do not exist in both files.
  56. for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
  57. $xhash[$this->_line_hash($from_lines[$xi])] = 1;
  58. }
  59. for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
  60. $line = $to_lines[$yi];
  61. if ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) {
  62. continue;
  63. }
  64. $yhash[$this->_line_hash($line)] = 1;
  65. $this->yv[] = $line;
  66. $this->yind[] = $yi;
  67. }
  68. for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
  69. $line = $from_lines[$xi];
  70. if ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) {
  71. continue;
  72. }
  73. $this->xv[] = $line;
  74. $this->xind[] = $xi;
  75. }
  76. // Find the LCS.
  77. $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
  78. // Merge edits when possible
  79. $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
  80. $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
  81. // Compute the edit operations.
  82. $edits = [];
  83. $xi = $yi = 0;
  84. while ($xi < $n_from || $yi < $n_to) {
  85. $this::USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
  86. $this::USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
  87. // Skip matching "snake".
  88. $copy = [];
  89. while ( $xi < $n_from && $yi < $n_to && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
  90. $copy[] = $from_lines[$xi++];
  91. ++$yi;
  92. }
  93. if ($copy) {
  94. $edits[] = new DiffOpCopy($copy);
  95. }
  96. // Find deletes & adds.
  97. $delete = [];
  98. while ($xi < $n_from && $this->xchanged[$xi]) {
  99. $delete[] = $from_lines[$xi++];
  100. }
  101. $add = [];
  102. while ($yi < $n_to && $this->ychanged[$yi]) {
  103. $add[] = $to_lines[$yi++];
  104. }
  105. if ($delete && $add) {
  106. $edits[] = new DiffOpChange($delete, $add);
  107. }
  108. elseif ($delete) {
  109. $edits[] = new DiffOpDelete($delete);
  110. }
  111. elseif ($add) {
  112. $edits[] = new DiffOpAdd($add);
  113. }
  114. }
  115. return $edits;
  116. }
  117. /**
  118. * Returns the whole line if it's small enough, or the MD5 hash otherwise.
  119. */
  120. protected function _line_hash($line) {
  121. if (Unicode::strlen($line) > $this::MAX_XREF_LENGTH) {
  122. return md5($line);
  123. }
  124. else {
  125. return $line;
  126. }
  127. }
  128. /**
  129. * Divide the Largest Common Subsequence (LCS) of the sequences
  130. * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
  131. * sized segments.
  132. *
  133. * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
  134. * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
  135. * sub sequences. The first sub-sequence is contained in [X0, X1),
  136. * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
  137. * that (X0, Y0) == (XOFF, YOFF) and
  138. * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
  139. *
  140. * This function assumes that the first lines of the specified portions
  141. * of the two files do not match, and likewise that the last lines do not
  142. * match. The caller must trim matching lines from the beginning and end
  143. * of the portions it is going to specify.
  144. */
  145. protected function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) {
  146. $flip = FALSE;
  147. if ($xlim - $xoff > $ylim - $yoff) {
  148. // Things seems faster (I'm not sure I understand why)
  149. // when the shortest sequence in X.
  150. $flip = TRUE;
  151. list($xoff, $xlim, $yoff, $ylim) = [$yoff, $ylim, $xoff, $xlim];
  152. }
  153. if ($flip) {
  154. for ($i = $ylim - 1; $i >= $yoff; $i--) {
  155. $ymatches[$this->xv[$i]][] = $i;
  156. }
  157. }
  158. else {
  159. for ($i = $ylim - 1; $i >= $yoff; $i--) {
  160. $ymatches[$this->yv[$i]][] = $i;
  161. }
  162. }
  163. $this->lcs = 0;
  164. $this->seq[0] = $yoff - 1;
  165. $this->in_seq = [];
  166. $ymids[0] = [];
  167. $numer = $xlim - $xoff + $nchunks - 1;
  168. $x = $xoff;
  169. for ($chunk = 0; $chunk < $nchunks; $chunk++) {
  170. if ($chunk > 0) {
  171. for ($i = 0; $i <= $this->lcs; $i++) {
  172. $ymids[$i][$chunk - 1] = $this->seq[$i];
  173. }
  174. }
  175. $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks);
  176. for (; $x < $x1; $x++) {
  177. $line = $flip ? $this->yv[$x] : $this->xv[$x];
  178. if (empty($ymatches[$line])) {
  179. continue;
  180. }
  181. $matches = $ymatches[$line];
  182. reset($matches);
  183. while (list ($junk, $y) = each($matches)) {
  184. if (empty($this->in_seq[$y])) {
  185. $k = $this->_lcs_pos($y);
  186. $this::USE_ASSERTS && assert($k > 0);
  187. $ymids[$k] = $ymids[$k - 1];
  188. break;
  189. }
  190. }
  191. while (list ($junk, $y) = each($matches)) {
  192. if ($y > $this->seq[$k - 1]) {
  193. $this::USE_ASSERTS && assert($y < $this->seq[$k]);
  194. // Optimization: this is a common case:
  195. // next match is just replacing previous match.
  196. $this->in_seq[$this->seq[$k]] = FALSE;
  197. $this->seq[$k] = $y;
  198. $this->in_seq[$y] = 1;
  199. }
  200. elseif (empty($this->in_seq[$y])) {
  201. $k = $this->_lcs_pos($y);
  202. $this::USE_ASSERTS && assert($k > 0);
  203. $ymids[$k] = $ymids[$k - 1];
  204. }
  205. }
  206. }
  207. }
  208. $seps[] = $flip ? [$yoff, $xoff] : [$xoff, $yoff];
  209. $ymid = $ymids[$this->lcs];
  210. for ($n = 0; $n < $nchunks - 1; $n++) {
  211. $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
  212. $y1 = $ymid[$n] + 1;
  213. $seps[] = $flip ? [$y1, $x1] : [$x1, $y1];
  214. }
  215. $seps[] = $flip ? [$ylim, $xlim] : [$xlim, $ylim];
  216. return [$this->lcs, $seps];
  217. }
  218. protected function _lcs_pos($ypos) {
  219. $end = $this->lcs;
  220. if ($end == 0 || $ypos > $this->seq[$end]) {
  221. $this->seq[++$this->lcs] = $ypos;
  222. $this->in_seq[$ypos] = 1;
  223. return $this->lcs;
  224. }
  225. $beg = 1;
  226. while ($beg < $end) {
  227. $mid = (int)(($beg + $end) / 2);
  228. if ($ypos > $this->seq[$mid]) {
  229. $beg = $mid + 1;
  230. }
  231. else {
  232. $end = $mid;
  233. }
  234. }
  235. $this::USE_ASSERTS && assert($ypos != $this->seq[$end]);
  236. $this->in_seq[$this->seq[$end]] = FALSE;
  237. $this->seq[$end] = $ypos;
  238. $this->in_seq[$ypos] = 1;
  239. return $end;
  240. }
  241. /**
  242. * Find LCS of two sequences.
  243. *
  244. * The results are recorded in the vectors $this->{x,y}changed[], by
  245. * storing a 1 in the element for each line that is an insertion
  246. * or deletion (ie. is not in the LCS).
  247. *
  248. * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  249. *
  250. * Note that XLIM, YLIM are exclusive bounds.
  251. * All line numbers are origin-0 and discarded lines are not counted.
  252. */
  253. protected function _compareseq($xoff, $xlim, $yoff, $ylim) {
  254. // Slide down the bottom initial diagonal.
  255. while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) {
  256. ++$xoff;
  257. ++$yoff;
  258. }
  259. // Slide up the top initial diagonal.
  260. while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
  261. --$xlim;
  262. --$ylim;
  263. }
  264. if ($xoff == $xlim || $yoff == $ylim) {
  265. $lcs = 0;
  266. }
  267. else {
  268. // This is ad hoc but seems to work well.
  269. //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
  270. //$nchunks = max(2, min(8, (int)$nchunks));
  271. $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
  272. list($lcs, $seps) = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
  273. }
  274. if ($lcs == 0) {
  275. // X and Y sequences have no common subsequence:
  276. // mark all changed.
  277. while ($yoff < $ylim) {
  278. $this->ychanged[$this->yind[$yoff++]] = 1;
  279. }
  280. while ($xoff < $xlim) {
  281. $this->xchanged[$this->xind[$xoff++]] = 1;
  282. }
  283. }
  284. else {
  285. // Use the partitions to split this problem into subproblems.
  286. reset($seps);
  287. $pt1 = $seps[0];
  288. while ($pt2 = next($seps)) {
  289. $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
  290. $pt1 = $pt2;
  291. }
  292. }
  293. }
  294. /**
  295. * Adjust inserts/deletes of identical lines to join changes
  296. * as much as possible.
  297. *
  298. * We do something when a run of changed lines include a
  299. * line at one end and has an excluded, identical line at the other.
  300. * We are free to choose which identical line is included.
  301. * `compareseq' usually chooses the one at the beginning,
  302. * but usually it is cleaner to consider the following identical line
  303. * to be the "change".
  304. *
  305. * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
  306. */
  307. protected function _shift_boundaries($lines, &$changed, $other_changed) {
  308. $i = 0;
  309. $j = 0;
  310. $this::USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
  311. $len = sizeof($lines);
  312. $other_len = sizeof($other_changed);
  313. while (1) {
  314. /*
  315. * Scan forwards to find beginning of another run of changes.
  316. * Also keep track of the corresponding point in the other file.
  317. *
  318. * Throughout this code, $i and $j are adjusted together so that
  319. * the first $i elements of $changed and the first $j elements
  320. * of $other_changed both contain the same number of zeros
  321. * (unchanged lines).
  322. * Furthermore, $j is always kept so that $j == $other_len or
  323. * $other_changed[$j] == FALSE.
  324. */
  325. while ($j < $other_len && $other_changed[$j]) {
  326. $j++;
  327. }
  328. while ($i < $len && !$changed[$i]) {
  329. $this::USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
  330. $i++;
  331. $j++;
  332. while ($j < $other_len && $other_changed[$j]) {
  333. $j++;
  334. }
  335. }
  336. if ($i == $len) {
  337. break;
  338. }
  339. $start = $i;
  340. // Find the end of this run of changes.
  341. while (++$i < $len && $changed[$i]) {
  342. continue;
  343. }
  344. do {
  345. /*
  346. * Record the length of this run of changes, so that
  347. * we can later determine whether the run has grown.
  348. */
  349. $runlength = $i - $start;
  350. /*
  351. * Move the changed region back, so long as the
  352. * previous unchanged line matches the last changed one.
  353. * This merges with previous changed regions.
  354. */
  355. while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
  356. $changed[--$start] = 1;
  357. $changed[--$i] = FALSE;
  358. while ($start > 0 && $changed[$start - 1]) {
  359. $start--;
  360. }
  361. $this::USE_ASSERTS && assert('$j > 0');
  362. while ($other_changed[--$j]) {
  363. continue;
  364. }
  365. $this::USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
  366. }
  367. /*
  368. * Set CORRESPONDING to the end of the changed run, at the last
  369. * point where it corresponds to a changed run in the other file.
  370. * CORRESPONDING == LEN means no such point has been found.
  371. */
  372. $corresponding = $j < $other_len ? $i : $len;
  373. /*
  374. * Move the changed region forward, so long as the
  375. * first changed line matches the following unchanged one.
  376. * This merges with following changed regions.
  377. * Do this second, so that if there are no merges,
  378. * the changed region is moved forward as far as possible.
  379. */
  380. while ($i < $len && $lines[$start] == $lines[$i]) {
  381. $changed[$start++] = FALSE;
  382. $changed[$i++] = 1;
  383. while ($i < $len && $changed[$i]) {
  384. $i++;
  385. }
  386. $this::USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
  387. $j++;
  388. if ($j < $other_len && $other_changed[$j]) {
  389. $corresponding = $i;
  390. while ($j < $other_len && $other_changed[$j]) {
  391. $j++;
  392. }
  393. }
  394. }
  395. } while ($runlength != $i - $start);
  396. /*
  397. * If possible, move the fully-merged run of changes
  398. * back to a corresponding run in the other file.
  399. */
  400. while ($corresponding < $i) {
  401. $changed[--$start] = 1;
  402. $changed[--$i] = 0;
  403. $this::USE_ASSERTS && assert('$j > 0');
  404. while ($other_changed[--$j]) {
  405. continue;
  406. }
  407. $this::USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
  408. }
  409. }
  410. }
  411. }