Native.php 15 KB

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