1 <?php declare(strict_types=1);
3 namespace PhpParser\Internal;
6 * Implements the Myers diff algorithm.
8 * Myers, Eugene W. "An O (ND) difference algorithm and its variations."
9 * Algorithmica 1.1 (1986): 251-266.
18 * Create differ over the given equality relation.
20 * @param callable $isEqual Equality relation with signature function($a, $b) : bool
22 public function __construct(callable $isEqual) {
23 $this->isEqual = $isEqual;
27 * Calculate diff (edit script) from $old to $new.
29 * @param array $old Original array
30 * @param array $new New array
32 * @return DiffElem[] Diff (edit script)
34 public function diff(array $old, array $new) {
35 list($trace, $x, $y) = $this->calculateTrace($old, $new);
36 return $this->extractDiff($trace, $x, $y, $old, $new);
40 * Calculate diff, including "replace" operations.
42 * If a sequence of remove operations is followed by the same number of add operations, these
43 * will be coalesced into replace operations.
45 * @param array $old Original array
46 * @param array $new New array
48 * @return DiffElem[] Diff (edit script), including replace operations
50 public function diffWithReplacements(array $old, array $new) {
51 return $this->coalesceReplacements($this->diff($old, $new));
54 private function calculateTrace(array $a, array $b) {
60 for ($d = 0; $d <= $max; $d++) {
62 for ($k = -$d; $k <= $d; $k += 2) {
63 if ($k === -$d || ($k !== $d && $v[$k-1] < $v[$k+1])) {
70 while ($x < $n && $y < $m && ($this->isEqual)($a[$x], $b[$y])) {
76 if ($x >= $n && $y >= $m) {
77 return [$trace, $x, $y];
81 throw new \Exception('Should not happen');
84 private function extractDiff(array $trace, int $x, int $y, array $a, array $b) {
86 for ($d = \count($trace) - 1; $d >= 0; $d--) {
90 if ($k === -$d || ($k !== $d && $v[$k-1] < $v[$k+1])) {
97 $prevY = $prevX - $prevK;
99 while ($x > $prevX && $y > $prevY) {
100 $result[] = new DiffElem(DiffElem::TYPE_KEEP, $a[$x-1], $b[$y-1]);
109 while ($x > $prevX) {
110 $result[] = new DiffElem(DiffElem::TYPE_REMOVE, $a[$x-1], null);
114 while ($y > $prevY) {
115 $result[] = new DiffElem(DiffElem::TYPE_ADD, null, $b[$y-1]);
119 return array_reverse($result);
123 * Coalesce equal-length sequences of remove+add into a replace operation.
125 * @param DiffElem[] $diff
128 private function coalesceReplacements(array $diff) {
131 for ($i = 0; $i < $c; $i++) {
132 $diffType = $diff[$i]->type;
133 if ($diffType !== DiffElem::TYPE_REMOVE) {
134 $newDiff[] = $diff[$i];
139 while ($j < $c && $diff[$j]->type === DiffElem::TYPE_REMOVE) {
144 while ($k < $c && $diff[$k]->type === DiffElem::TYPE_ADD) {
148 if ($j - $i === $k - $j) {
150 for ($n = 0; $n < $len; $n++) {
151 $newDiff[] = new DiffElem(
152 DiffElem::TYPE_REPLACE, $diff[$i + $n]->old, $diff[$j + $n]->new
156 for (; $i < $k; $i++) {
157 $newDiff[] = $diff[$i];