Blob


1 /* Myers diff algorithm implementation, invented by Eugene W. Myers [1].
2 * Implementations of both the Myers Divide Et Impera (using linear space)
3 * and the canonical Myers algorithm (using quadratic space). */
4 /*
5 * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
20 #include <diff/diff_main.h>
22 #include "debug.h"
24 /* Myers' diff algorithm [1] is nicely explained in [2].
25 * [1] http://www.xmailserver.org/diff2.pdf
26 * [2] https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ ff.
27 *
28 * Myers approaches finding the smallest diff as a graph problem.
29 * The crux is that the original algorithm requires quadratic amount of memory:
30 * both sides' lengths added, and that squared. So if we're diffing lines of text, two files with 1000 lines each would
31 * blow up to a matrix of about 2000 * 2000 ints of state, about 16 Mb of RAM to figure out 2 kb of text.
32 * The solution is using Myers' "divide and conquer" extension algorithm, which does the original traversal from both
33 * ends of the files to reach a middle where these "snakes" touch, hence does not need to backtrace the traversal, and
34 * so gets away with only keeping a single column of that huge state matrix in memory.
35 *
36 * Todo: the divide and conquer requires linear *space*, not necessarily linear *time*. It recurses, apparently doing
37 * multiple Myers passes, and also it apparently favors fragmented diffs in cases where chunks of text were moved to a
38 * different place. Up to a given count of diff atoms (text lines), it might be desirable to accept the quadratic memory
39 * usage, get nicer diffs and less re-iteration of the same data?
40 */
42 struct diff_box {
43 unsigned int left_start;
44 unsigned int left_end;
45 unsigned int right_start;
46 unsigned int right_end;
47 };
49 #define diff_box_empty(DIFF_SNAKE) ((DIFF_SNAKE)->left_end == 0)
52 /* If the two contents of a file are A B C D E and X B C Y,
53 * the Myers diff graph looks like:
54 *
55 * k0 k1
56 * \ \
57 * k-1 0 1 2 3 4 5
58 * \ A B C D E
59 * 0 o-o-o-o-o-o
60 * X | | | | | |
61 * 1 o-o-o-o-o-o
62 * B | |\| | | |
63 * 2 o-o-o-o-o-o
64 * C | | |\| | |
65 * 3 o-o-o-o-o-o
66 * Y | | | | | |\
67 * 4 o-o-o-o-o-o c1
68 * \ \
69 * c-1 c0
70 *
71 * Moving right means delete an atom from the left-hand-side,
72 * Moving down means add an atom from the right-hand-side.
73 * Diagonals indicate identical atoms on both sides, the challenge is to use as many diagonals as possible.
74 *
75 * The original Myers algorithm walks all the way from the top left to the bottom right, remembers all steps, and then
76 * backtraces to find the shortest path. However, that requires keeping the entire graph in memory, which needs
77 * quadratic space.
78 *
79 * Myers adds a variant that uses linear space -- note, not linear time, only linear space: walk forward and backward,
80 * find a meeting point in the middle, and recurse on the two separate sections. This is called "divide and conquer".
81 *
82 * d: the step number, starting with 0, a.k.a. the distance from the starting point.
83 * k: relative index in the state array for the forward scan, indicating on which diagonal through the diff graph we
84 * currently are.
85 * c: relative index in the state array for the backward scan, indicating the diagonal number from the bottom up.
86 *
87 * The "divide and conquer" traversal through the Myers graph looks like this:
88 *
89 * | d= 0 1 2 3 2 1 0
90 * ----+--------------------------------------------
91 * k= | c=
92 * 4 | 3
93 * |
94 * 3 | 3,0 5,2 2
95 * | / \
96 * 2 | 2,0 5,3 1
97 * | / \
98 * 1 | 1,0 4,3 >= 4,3 5,4<-- 0
99 * | / / \ /
100 * 0 | -->0,0 3,3 4,4 -1
101 * | \ / /
102 * -1 | 0,1 1,2 3,4 -2
103 * | \ /
104 * -2 | 0,2 -3
105 * | \
106 * | 0,3
107 * | forward-> <-backward
109 * x,y pairs here are the coordinates in the Myers graph:
110 * x = atom index in left-side source, y = atom index in the right-side source.
112 * Only one forward column and one backward column are kept in mem, each need at most left.len + 1 + right.len items.
113 * Note that each d step occupies either the even or the odd items of a column: if e.g. the previous column is in the
114 * odd items, the next column is formed in the even items, without overwriting the previous column's results.
116 * Also note that from the diagonal index k and the x coordinate, the y coordinate can be derived:
117 * y = x - k
118 * Hence the state array only needs to keep the x coordinate, i.e. the position in the left-hand file, and the y
119 * coordinate, i.e. position in the right-hand file, is derived from the index in the state array.
121 * The two traces meet at 4,3, the first step (here found in the forward traversal) where a forward position is on or
122 * past a backward traced position on the same diagonal.
124 * This divides the problem space into:
126 * 0 1 2 3 4 5
127 * A B C D E
128 * 0 o-o-o-o-o
129 * X | | | | |
130 * 1 o-o-o-o-o
131 * B | |\| | |
132 * 2 o-o-o-o-o
133 * C | | |\| |
134 * 3 o-o-o-o-*-o *: forward and backward meet here
135 * Y | |
136 * 4 o-o
138 * Doing the same on each section lead to:
140 * 0 1 2 3 4 5
141 * A B C D E
142 * 0 o-o
143 * X | |
144 * 1 o-b b: backward d=1 first reaches here (sliding up the snake)
145 * B \ f: then forward d=2 reaches here (sliding down the snake)
146 * 2 o As result, the box from b to f is found to be identical;
147 * C \ leaving a top box from 0,0 to 1,1 and a bottom trivial tail 3,3 to 4,3.
148 * 3 f-o
150 * 3 o-*
151 * Y |
152 * 4 o *: forward and backward meet here
154 * and solving the last top left box gives:
156 * 0 1 2 3 4 5
157 * A B C D E -A
158 * 0 o-o +X
159 * X | B
160 * 1 o C
161 * B \ -D
162 * 2 o -E
163 * C \ +Y
164 * 3 o-o-o
165 * Y |
166 * 4 o
168 */
170 #define xk_to_y(X, K) ((X) - (K))
171 #define xc_to_y(X, C, DELTA) ((X) - (C) + (DELTA))
172 #define k_to_c(K, DELTA) ((K) + (DELTA))
173 #define c_to_k(C, DELTA) ((C) - (DELTA))
175 /* Do one forwards step in the "divide and conquer" graph traversal.
176 * left: the left side to diff.
177 * right: the right side to diff against.
178 * kd_forward: the traversal state for forwards traversal, modified by this function.
179 * This is carried over between invocations with increasing d.
180 * kd_forward points at the center of the state array, allowing negative indexes.
181 * kd_backward: the traversal state for backwards traversal, to find a meeting point.
182 * Since forwards is done first, kd_backward will be valid for d - 1, not d.
183 * kd_backward points at the center of the state array, allowing negative indexes.
184 * d: Step or distance counter, indicating for what value of d the kd_forward should be populated.
185 * For d == 0, kd_forward[0] is initialized, i.e. the first invocation should be for d == 0.
186 * meeting_snake: resulting meeting point, if any.
187 */
188 static void diff_divide_myers_forward(struct diff_data *left, struct diff_data *right,
189 int *kd_forward, int *kd_backward, int d,
190 struct diff_box *meeting_snake)
192 int delta = (int)right->atoms.len - (int)left->atoms.len;
193 int prev_x;
194 int prev_y;
195 int k;
196 int x;
198 debug("-- %s d=%d\n", __func__, d);
199 debug_dump_myers_graph(left, right, NULL);
201 for (k = d; k >= -d; k -= 2) {
202 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
203 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
204 if (k < -(int)right->atoms.len)
205 debug(" %d k < -(int)right->atoms.len %d\n", k, -(int)right->atoms.len);
206 else
207 debug(" %d k > left->atoms.len %d\n", k, left->atoms.len);
208 if (k < 0) {
209 /* We are traversing negatively, and already below the entire graph, nothing will come
210 * of this. */
211 debug(" break");
212 break;
214 debug(" continue");
215 continue;
217 debug("- k = %d\n", k);
218 if (d == 0) {
219 /* This is the initializing step. There is no prev_k yet, get the initial x from the top left of
220 * the Myers graph. */
221 x = 0;
223 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
224 * For this, all k should derive from k - 1, only the bottom most k derive from k + 1:
226 * | d= 0 1 2
227 * ----+----------------
228 * k= |
229 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
230 * | /
231 * 1 | 1,0
232 * | /
233 * 0 | -->0,0 3,3
234 * | \\ /
235 * -1 | 0,1 <-- bottom most for d=1 from prev_k = -1 + 1 = 0
236 * | \\
237 * -2 | 0,2 <-- bottom most for d=2 from prev_k = -2 + 1 = -1
239 * Except when a k + 1 from a previous run already means a further advancement in the graph.
240 * If k == d, there is no k + 1 and k - 1 is the only option.
241 * If k < d, use k + 1 in case that yields a larger x. Also use k + 1 if k - 1 is outside the graph.
242 */
243 else if (k > -d && (k == d
244 || (k - 1 >= -(int)right->atoms.len
245 && kd_forward[k - 1] >= kd_forward[k + 1]))) {
246 /* Advance from k - 1.
247 * From position prev_k, step to the right in the Myers graph: x += 1.
248 */
249 int prev_k = k - 1;
250 prev_x = kd_forward[prev_k];
251 prev_y = xk_to_y(prev_x, prev_k);
252 x = prev_x + 1;
253 } else {
254 /* The bottom most one.
255 * From position prev_k, step to the bottom in the Myers graph: y += 1.
256 * Incrementing y is achieved by decrementing k while keeping the same x.
257 * (since we're deriving y from y = x - k).
258 */
259 int prev_k = k + 1;
260 prev_x = kd_forward[prev_k];
261 prev_y = xk_to_y(prev_x, prev_k);
262 x = prev_x;
265 /* Slide down any snake that we might find here. */
266 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len
267 && diff_atom_same(&left->atoms.head[x], &right->atoms.head[xk_to_y(x, k)]))
268 x++;
269 kd_forward[k] = x;
271 if (DEBUG) {
272 int fi;
273 for (fi = d; fi >= k; fi--) {
274 debug("kd_forward[%d] = (%d, %d)\n", fi, kd_forward[fi], kd_forward[fi] - fi);
275 /*
276 if (kd_forward[fi] >= 0 && kd_forward[fi] < left->atoms.len)
277 debug_dump_atom(left, right, &left->atoms.head[kd_forward[fi]]);
278 else
279 debug("\n");
280 if (kd_forward[fi]-fi >= 0 && kd_forward[fi]-fi < right->atoms.len)
281 debug_dump_atom(right, left, &right->atoms.head[kd_forward[fi]-fi]);
282 else
283 debug("\n");
284 */
288 if (x < 0 || x > left->atoms.len
289 || xk_to_y(x, k) < 0 || xk_to_y(x, k) > right->atoms.len)
290 continue;
292 /* Figured out a new forwards traversal, see if this has gone onto or even past a preceding backwards
293 * traversal.
295 * If the delta in length is odd, then d and backwards_d hit the same state indexes:
296 * | d= 0 1 2 1 0
297 * ----+---------------- ----------------
298 * k= | c=
299 * 4 | 3
300 * |
301 * 3 | 2
302 * | same
303 * 2 | 2,0====5,3 1
304 * | / \
305 * 1 | 1,0 5,4<-- 0
306 * | / /
307 * 0 | -->0,0 3,3====4,4 -1
308 * | \ /
309 * -1 | 0,1 -2
310 * | \
311 * -2 | 0,2 -3
312 * |
314 * If the delta is even, they end up off-by-one, i.e. on different diagonals:
316 * | d= 0 1 2 1 0
317 * ----+---------------- ----------------
318 * | c=
319 * 3 | 3
320 * |
321 * 2 | 2,0 off 2
322 * | / \\
323 * 1 | 1,0 4,3 1
324 * | / // \
325 * 0 | -->0,0 3,3 4,4<-- 0
326 * | \ / /
327 * -1 | 0,1 3,4 -1
328 * | \ //
329 * -2 | 0,2 -2
330 * |
332 * So in the forward path, we can only match up diagonals when the delta is odd.
333 */
334 /* Forwards is done first, so the backwards one was still at d - 1. Can't do this for d == 0. */
335 int backwards_d = d - 1;
336 if ((delta & 1) && (backwards_d >= 0)) {
337 debug("backwards_d = %d\n", backwards_d);
339 /* If both sides have the same length, forward and backward start on the same diagonal, meaning the
340 * backwards state index c == k.
341 * As soon as the lengths are not the same, the backwards traversal starts on a different diagonal, and
342 * c = k shifted by the difference in length.
343 */
344 int c = k_to_c(k, delta);
346 /* When the file sizes are very different, the traversal trees start on far distant diagonals.
347 * They don't necessarily meet straight on. See whether this forward value is on a diagonal that
348 * is also valid in kd_backward[], and match them if so. */
349 if (c >= -backwards_d && c <= backwards_d) {
350 /* Current k is on a diagonal that exists in kd_backward[]. If the two x positions have
351 * met or passed (forward walked onto or past backward), then we've found a midpoint / a
352 * mid-box.
354 * But we need to avoid matching a situation like this:
355 * 0 1
356 * x y
357 * 0 o-o-o
358 * x |\| |
359 * 1 o-o-o
360 * y | |\|
361 * 2 (B)o-o <--(B) backwards traversal reached here
362 * a | | |
363 * 3 o-o-o<-- prev_x, prev_y
364 * b | | |
365 * 4 o-o(F) <--(F) forwards traversal reached here
366 * x |\| | Now both are on the same diagonal and look like they passed,
367 * 5 o-o-o but actually they have sneaked past each other and have not met.
368 * y | |\|
369 * 6 o-o-o
371 * The solution is to notice that prev_x,prev_y were also already past (B).
372 */
373 int backward_x = kd_backward[c];
374 int backward_y = xc_to_y(backward_x, c, delta);
375 debug(" prev_x,y = (%d,%d) c%d:backward_x,y = (%d,%d) k%d:x,y = (%d,%d)\n",
376 prev_x, prev_y, c, backward_x, backward_y, k, x, xk_to_y(x, k));
377 if (prev_x <= backward_x && prev_y <= backward_y
378 && x >= backward_x) {
379 *meeting_snake = (struct diff_box){
380 .left_start = backward_x,
381 .left_end = x,
382 .right_start = xc_to_y(backward_x, c, delta),
383 .right_end = xk_to_y(x, k),
384 };
385 debug("HIT x=(%u,%u) - y=(%u,%u)\n",
386 meeting_snake->left_start,
387 meeting_snake->right_start,
388 meeting_snake->left_end,
389 meeting_snake->right_end);
390 return;
397 /* Do one backwards step in the "divide and conquer" graph traversal.
398 * left: the left side to diff.
399 * right: the right side to diff against.
400 * kd_forward: the traversal state for forwards traversal, to find a meeting point.
401 * Since forwards is done first, after this, both kd_forward and kd_backward will be valid for d.
402 * kd_forward points at the center of the state array, allowing negative indexes.
403 * kd_backward: the traversal state for backwards traversal, to find a meeting point.
404 * This is carried over between invocations with increasing d.
405 * kd_backward points at the center of the state array, allowing negative indexes.
406 * d: Step or distance counter, indicating for what value of d the kd_backward should be populated.
407 * Before the first invocation, kd_backward[0] shall point at the bottom right of the Myers graph
408 * (left.len, right.len).
409 * The first invocation will be for d == 1.
410 * meeting_snake: resulting meeting point, if any.
411 */
412 static void diff_divide_myers_backward(struct diff_data *left, struct diff_data *right,
413 int *kd_forward, int *kd_backward, int d,
414 struct diff_box *meeting_snake)
416 int delta = (int)right->atoms.len - (int)left->atoms.len;
417 int prev_x;
418 int prev_y;
419 int c;
420 int x;
422 debug("-- %s d=%d\n", __func__, d);
423 debug_dump_myers_graph(left, right, NULL);
425 for (c = d; c >= -d; c -= 2) {
426 if (c < -(int)left->atoms.len || c > (int)right->atoms.len) {
427 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
428 if (c < -(int)left->atoms.len)
429 debug(" %d c < -(int)left->atoms.len %d\n", c, -(int)left->atoms.len);
430 else
431 debug(" %d c > right->atoms.len %d\n", c, right->atoms.len);
432 if (c < 0) {
433 /* We are traversing negatively, and already below the entire graph, nothing will come
434 * of this. */
435 debug(" break");
436 break;
438 debug(" continue");
439 continue;
441 debug("- c = %d\n", c);
442 if (d == 0) {
443 /* This is the initializing step. There is no prev_c yet, get the initial x from the bottom
444 * right of the Myers graph. */
445 x = left->atoms.len;
447 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
448 * For this, all c should derive from c - 1, only the bottom most c derive from c + 1:
450 * 2 1 0
451 * ---------------------------------------------------
452 * c=
453 * 3
455 * from prev_c = c - 1 --> 5,2 2
456 * \
457 * 5,3 1
458 * \
459 * 4,3 5,4<-- 0
460 * \ /
461 * bottom most for d=1 from c + 1 --> 4,4 -1
462 * /
463 * bottom most for d=2 --> 3,4 -2
465 * Except when a c + 1 from a previous run already means a further advancement in the graph.
466 * If c == d, there is no c + 1 and c - 1 is the only option.
467 * If c < d, use c + 1 in case that yields a larger x. Also use c + 1 if c - 1 is outside the graph.
468 */
469 else if (c > -d && (c == d
470 || (c - 1 >= -(int)right->atoms.len
471 && kd_backward[c - 1] <= kd_backward[c + 1]))) {
472 /* A top one.
473 * From position prev_c, step upwards in the Myers graph: y -= 1.
474 * Decrementing y is achieved by incrementing c while keeping the same x.
475 * (since we're deriving y from y = x - c + delta).
476 */
477 int prev_c = c - 1;
478 prev_x = kd_backward[prev_c];
479 prev_y = xc_to_y(prev_x, prev_c, delta);
480 x = prev_x;
481 } else {
482 /* The bottom most one.
483 * From position prev_c, step to the left in the Myers graph: x -= 1.
484 */
485 int prev_c = c + 1;
486 prev_x = kd_backward[prev_c];
487 prev_y = xc_to_y(prev_x, prev_c, delta);
488 x = prev_x - 1;
491 /* Slide up any snake that we might find here. */
492 debug("c=%d x-1=%d Yb-1=%d-1=%d\n", c, x-1, xc_to_y(x, c, delta), xc_to_y(x, c, delta)-1);
493 if (x > 0) {
494 debug(" l="); debug_dump_atom(left, right, &left->atoms.head[x-1]);
496 if (xc_to_y(x, c, delta) > 0) {
497 debug(" r="); debug_dump_atom(right, left, &right->atoms.head[xc_to_y(x, c, delta)-1]);
499 while (x > 0 && xc_to_y(x, c, delta) > 0
500 && diff_atom_same(&left->atoms.head[x-1], &right->atoms.head[xc_to_y(x, c, delta)-1]))
501 x--;
502 kd_backward[c] = x;
504 if (DEBUG) {
505 int fi;
506 for (fi = d; fi >= c; fi--) {
507 debug("kd_backward[%d] = (%d, %d)\n", fi, kd_backward[fi],
508 kd_backward[fi] - fi + delta);
509 /*
510 if (kd_backward[fi] >= 0 && kd_backward[fi] < left->atoms.len)
511 debug_dump_atom(left, right, &left->atoms.head[kd_backward[fi]]);
512 else
513 debug("\n");
514 if (kd_backward[fi]-fi+delta >= 0 && kd_backward[fi]-fi+delta < right->atoms.len)
515 debug_dump_atom(right, left, &right->atoms.head[kd_backward[fi]-fi+delta]);
516 else
517 debug("\n");
518 */
522 if (x < 0 || x > left->atoms.len
523 || xc_to_y(x, c, delta) < 0 || xc_to_y(x, c, delta) > right->atoms.len)
524 continue;
526 /* Figured out a new backwards traversal, see if this has gone onto or even past a preceding forwards
527 * traversal.
529 * If the delta in length is even, then d and backwards_d hit the same state indexes -- note how this is
530 * different from in the forwards traversal, because now both d are the same:
532 * | d= 0 1 2 2 1 0
533 * ----+---------------- --------------------
534 * k= | c=
535 * 4 |
536 * |
537 * 3 | 3
538 * | same
539 * 2 | 2,0====5,2 2
540 * | / \
541 * 1 | 1,0 5,3 1
542 * | / / \
543 * 0 | -->0,0 3,3====4,3 5,4<-- 0
544 * | \ / /
545 * -1 | 0,1 4,4 -1
546 * | \
547 * -2 | 0,2 -2
548 * |
549 * -3
550 * If the delta is odd, they end up off-by-one, i.e. on different diagonals.
551 * So in the backward path, we can only match up diagonals when the delta is even.
552 */
553 if ((delta & 1) == 0) {
554 /* Forwards was done first, now both d are the same. */
555 int forwards_d = d;
557 /* As soon as the lengths are not the same, the backwards traversal starts on a different diagonal, and
558 * c = k shifted by the difference in length.
559 */
560 int k = c_to_k(c, delta);
562 /* When the file sizes are very different, the traversal trees start on far distant diagonals.
563 * They don't necessarily meet straight on. See whether this backward value is also on a valid
564 * diagonal in kd_forward[], and match them if so. */
565 if (k >= -forwards_d && k <= forwards_d) {
566 /* Current c is on a diagonal that exists in kd_forward[]. If the two x positions have
567 * met or passed (backward walked onto or past forward), then we've found a midpoint / a
568 * mid-box. */
569 int forward_x = kd_forward[k];
570 int forward_y = xk_to_y(forward_x, k);
571 debug("Compare %d to %d k=%d (x=%d,y=%d) to (x=%d,y=%d)\n",
572 forward_x, x, k,
573 forward_x, xk_to_y(forward_x, k), x, xc_to_y(x, c, delta));
574 if (forward_x <= prev_x && forward_y <= prev_y
575 && forward_x >= x) {
576 *meeting_snake = (struct diff_box){
577 .left_start = x,
578 .left_end = forward_x,
579 .right_start = xc_to_y(x, c, delta),
580 .right_end = xk_to_y(forward_x, k),
581 };
582 debug("HIT x=%u,%u - y=%u,%u\n",
583 meeting_snake->left_start,
584 meeting_snake->right_start,
585 meeting_snake->left_end,
586 meeting_snake->right_end);
587 return;
594 /* Myers "Divide et Impera": tracing forwards from the start and backwards from the end to find a midpoint that divides
595 * the problem into smaller chunks. Requires only linear amounts of memory. */
596 enum diff_rc diff_algo_myers_divide(const struct diff_algo_config *algo_config, struct diff_state *state)
598 enum diff_rc rc = DIFF_RC_ENOMEM;
599 struct diff_data *left = &state->left;
600 struct diff_data *right = &state->right;
602 debug("\n** %s\n", __func__);
603 debug("left:\n");
604 debug_dump(left);
605 debug("right:\n");
606 debug_dump(right);
607 debug_dump_myers_graph(left, right, NULL);
609 /* Allocate two columns of a Myers graph, one for the forward and one for the backward traversal. */
610 unsigned int max = left->atoms.len + right->atoms.len;
611 size_t kd_len = max + 1;
612 size_t kd_buf_size = kd_len << 1;
613 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
614 if (!kd_buf)
615 return DIFF_RC_ENOMEM;
616 int i;
617 for (i = 0; i < kd_buf_size; i++)
618 kd_buf[i] = -1;
619 int *kd_forward = kd_buf;
620 int *kd_backward = kd_buf + kd_len;
622 /* The 'k' axis in Myers spans positive and negative indexes, so point the kd to the middle.
623 * It is then possible to index from -max/2 .. max/2. */
624 kd_forward += max/2;
625 kd_backward += max/2;
627 int d;
628 struct diff_box mid_snake = {};
629 for (d = 0; d <= (max/2); d++) {
630 debug("-- d=%d\n", d);
631 diff_divide_myers_forward(left, right, kd_forward, kd_backward, d, &mid_snake);
632 if (!diff_box_empty(&mid_snake))
633 break;
634 diff_divide_myers_backward(left, right, kd_forward, kd_backward, d, &mid_snake);
635 if (!diff_box_empty(&mid_snake))
636 break;
639 if (diff_box_empty(&mid_snake)) {
640 /* Divide and conquer failed to find a meeting point. Use the fallback_algo defined in the algo_config
641 * (leave this to the caller). This is just paranoia/sanity, we normally should always find a midpoint.
642 */
643 debug(" no midpoint \n");
644 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
645 goto return_rc;
646 } else {
647 debug(" mid snake L: %u to %u of %u R: %u to %u of %u\n",
648 mid_snake.left_start, mid_snake.left_end, left->atoms.len,
649 mid_snake.right_start, mid_snake.right_end, right->atoms.len);
651 /* Section before the mid-snake. */
652 debug("Section before the mid-snake\n");
654 struct diff_atom *left_atom = &left->atoms.head[0];
655 unsigned int left_section_len = mid_snake.left_start;
656 struct diff_atom *right_atom = &right->atoms.head[0];
657 unsigned int right_section_len = mid_snake.right_start;
659 if (left_section_len && right_section_len) {
660 /* Record an unsolved chunk, the caller will apply inner_algo() on this chunk. */
661 if (!diff_state_add_chunk(state, false,
662 left_atom, left_section_len,
663 right_atom, right_section_len))
664 goto return_rc;
665 } else if (left_section_len && !right_section_len) {
666 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
667 if (!diff_state_add_chunk(state, true,
668 left_atom, left_section_len,
669 right_atom, 0))
670 goto return_rc;
671 } else if (!left_section_len && right_section_len) {
672 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
673 if (!diff_state_add_chunk(state, true,
674 left_atom, 0,
675 right_atom, right_section_len))
676 goto return_rc;
678 /* else: left_section_len == 0 and right_section_len == 0, i.e. nothing before the mid-snake. */
680 /* the mid-snake, identical data on both sides: */
681 debug("the mid-snake\n");
682 if (!diff_state_add_chunk(state, true,
683 &left->atoms.head[mid_snake.left_start],
684 mid_snake.left_end - mid_snake.left_start,
685 &right->atoms.head[mid_snake.right_start],
686 mid_snake.right_end - mid_snake.right_start))
687 goto return_rc;
689 /* Section after the mid-snake. */
690 debug("Section after the mid-snake\n");
691 debug(" left_end %u right_end %u\n", mid_snake.left_end, mid_snake.right_end);
692 debug(" left_count %u right_count %u\n", left->atoms.len, right->atoms.len);
693 left_atom = &left->atoms.head[mid_snake.left_end];
694 left_section_len = left->atoms.len - mid_snake.left_end;
695 right_atom = &right->atoms.head[mid_snake.right_end];
696 right_section_len = right->atoms.len - mid_snake.right_end;
698 if (left_section_len && right_section_len) {
699 /* Record an unsolved chunk, the caller will apply inner_algo() on this chunk. */
700 if (!diff_state_add_chunk(state, false,
701 left_atom, left_section_len,
702 right_atom, right_section_len))
703 goto return_rc;
704 } else if (left_section_len && !right_section_len) {
705 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
706 if (!diff_state_add_chunk(state, true,
707 left_atom, left_section_len,
708 right_atom, 0))
709 goto return_rc;
710 } else if (!left_section_len && right_section_len) {
711 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
712 if (!diff_state_add_chunk(state, true,
713 left_atom, 0,
714 right_atom, right_section_len))
715 goto return_rc;
717 /* else: left_section_len == 0 and right_section_len == 0, i.e. nothing after the mid-snake. */
720 rc = DIFF_RC_OK;
722 return_rc:
723 free(kd_buf);
724 debug("** END %s\n", __func__);
725 return rc;
728 /* Myers Diff tracing from the start all the way through to the end, requiring quadratic amounts of memory. This can
729 * fail if the required space surpasses algo_config->permitted_state_size. */
730 enum diff_rc diff_algo_myers(const struct diff_algo_config *algo_config, struct diff_state *state)
732 /* do a diff_divide_myers_forward() without a _backward(), so that it walks forward across the entire
733 * files to reach the end. Keep each run's state, and do a final backtrace. */
734 enum diff_rc rc = DIFF_RC_ENOMEM;
735 struct diff_data *left = &state->left;
736 struct diff_data *right = &state->right;
738 debug("\n** %s\n", __func__);
739 debug("left:\n");
740 debug_dump(left);
741 debug("right:\n");
742 debug_dump(right);
743 debug_dump_myers_graph(left, right, NULL);
745 /* Allocate two columns of a Myers graph, one for the forward and one for the backward traversal. */
746 unsigned int max = left->atoms.len + right->atoms.len;
747 size_t kd_len = max + 1 + max;
748 size_t kd_buf_size = kd_len * kd_len;
749 debug("state size: %zu\n", kd_buf_size);
750 if (kd_buf_size < kd_len /* overflow? */
751 || kd_buf_size * sizeof(int) > algo_config->permitted_state_size) {
752 debug("state size %zu > permitted_state_size %zu, use fallback_algo\n",
753 kd_buf_size, algo_config->permitted_state_size);
754 return DIFF_RC_USE_DIFF_ALGO_FALLBACK;
757 int *kd_buf = reallocarray(NULL, kd_buf_size, sizeof(int));
758 if (!kd_buf)
759 return DIFF_RC_ENOMEM;
760 int i;
761 for (i = 0; i < kd_buf_size; i++)
762 kd_buf[i] = -1;
764 /* The 'k' axis in Myers spans positive and negative indexes, so point the kd to the middle.
765 * It is then possible to index from -max .. max. */
766 int *kd_origin = kd_buf + max;
767 int *kd_column = kd_origin;
769 int d;
770 int backtrack_d = -1;
771 int backtrack_k = 0;
772 int k;
773 int x, y;
774 for (d = 0; d <= max; d++, kd_column += kd_len) {
775 debug("-- d=%d\n", d);
777 debug("-- %s d=%d\n", __func__, d);
779 for (k = d; k >= -d; k -= 2) {
780 if (k < -(int)right->atoms.len || k > (int)left->atoms.len) {
781 /* This diagonal is completely outside of the Myers graph, don't calculate it. */
782 if (k < -(int)right->atoms.len)
783 debug(" %d k < -(int)right->atoms.len %d\n", k, -(int)right->atoms.len);
784 else
785 debug(" %d k > left->atoms.len %d\n", k, left->atoms.len);
786 if (k < 0) {
787 /* We are traversing negatively, and already below the entire graph, nothing will come
788 * of this. */
789 debug(" break");
790 break;
792 debug(" continue");
793 continue;
796 debug("- k = %d\n", k);
797 if (d == 0) {
798 /* This is the initializing step. There is no prev_k yet, get the initial x from the top left of
799 * the Myers graph. */
800 x = 0;
801 } else {
802 int *kd_prev_column = kd_column - kd_len;
804 /* Favoring "-" lines first means favoring moving rightwards in the Myers graph.
805 * For this, all k should derive from k - 1, only the bottom most k derive from k + 1:
807 * | d= 0 1 2
808 * ----+----------------
809 * k= |
810 * 2 | 2,0 <-- from prev_k = 2 - 1 = 1
811 * | /
812 * 1 | 1,0
813 * | /
814 * 0 | -->0,0 3,3
815 * | \\ /
816 * -1 | 0,1 <-- bottom most for d=1 from prev_k = -1 + 1 = 0
817 * | \\
818 * -2 | 0,2 <-- bottom most for d=2 from prev_k = -2 + 1 = -1
820 * Except when a k + 1 from a previous run already means a further advancement in the graph.
821 * If k == d, there is no k + 1 and k - 1 is the only option.
822 * If k < d, use k + 1 in case that yields a larger x. Also use k + 1 if k - 1 is outside the graph.
823 */
824 if (k > -d && (k == d
825 || (k - 1 >= -(int)right->atoms.len
826 && kd_prev_column[k - 1] >= kd_prev_column[k + 1]))) {
827 /* Advance from k - 1.
828 * From position prev_k, step to the right in the Myers graph: x += 1.
829 */
830 int prev_k = k - 1;
831 int prev_x = kd_prev_column[prev_k];
832 x = prev_x + 1;
833 } else {
834 /* The bottom most one.
835 * From position prev_k, step to the bottom in the Myers graph: y += 1.
836 * Incrementing y is achieved by decrementing k while keeping the same x.
837 * (since we're deriving y from y = x - k).
838 */
839 int prev_k = k + 1;
840 int prev_x = kd_prev_column[prev_k];
841 x = prev_x;
845 /* Slide down any snake that we might find here. */
846 while (x < left->atoms.len && xk_to_y(x, k) < right->atoms.len
847 && diff_atom_same(&left->atoms.head[x], &right->atoms.head[xk_to_y(x, k)]))
848 x++;
849 kd_column[k] = x;
851 if (DEBUG) {
852 int fi;
853 for (fi = d; fi >= k; fi-=2) {
854 debug("kd_column[%d] = (%d, %d)\n", fi, kd_column[fi], kd_column[fi] - fi);
855 #if 0
856 if (kd_column[fi] >= 0 && kd_column[fi] < left->atoms.len)
857 debug_dump_atom(left, right, &left->atoms.head[kd_column[fi]]);
858 else
859 debug("\n");
860 if (kd_column[fi]-fi >= 0 && kd_column[fi]-fi < right->atoms.len)
861 debug_dump_atom(right, left, &right->atoms.head[kd_column[fi]-fi]);
862 else
863 debug("\n");
864 #endif
868 if (x == left->atoms.len && xk_to_y(x, k) == right->atoms.len) {
869 /* Found a path */
870 backtrack_d = d;
871 backtrack_k = k;
872 debug("Reached the end at d = %d, k = %d\n",
873 backtrack_d, backtrack_k);
874 break;
878 if (backtrack_d >= 0)
879 break;
882 debug_dump_myers_graph(left, right, kd_origin);
884 /* backtrack. A matrix spanning from start to end of the file is ready:
886 * | d= 0 1 2 3 4
887 * ----+---------------------------------
888 * k= |
889 * 3 |
890 * |
891 * 2 | 2,0
892 * | /
893 * 1 | 1,0 4,3
894 * | / / \
895 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
896 * | \ / \
897 * -1 | 0,1 3,4
898 * | \
899 * -2 | 0,2
900 * |
902 * From (4,4) backwards, find the previous position that is the largest, and remember it.
904 */
905 for (d = backtrack_d, k = backtrack_k; d >= 0; d--) {
906 x = kd_column[k];
907 y = xk_to_y(x, k);
909 /* When the best position is identified, remember it for that kd_column.
910 * That kd_column is no longer needed otherwise, so just re-purpose kd_column[0] = x and kd_column[1] = y,
911 * so that there is no need to allocate more memory.
912 */
913 kd_column[0] = x;
914 kd_column[1] = y;
915 debug("Backtrack d=%d: xy=(%d, %d)\n",
916 d, kd_column[0], kd_column[1]);
918 /* Don't access memory before kd_buf */
919 if (d == 0)
920 break;
921 int *kd_prev_column = kd_column - kd_len;
923 /* When y == 0, backtracking downwards (k-1) is the only way.
924 * When x == 0, backtracking upwards (k+1) is the only way.
926 * | d= 0 1 2 3 4
927 * ----+---------------------------------
928 * k= |
929 * 3 |
930 * | ..y == 0
931 * 2 | 2,0
932 * | /
933 * 1 | 1,0 4,3
934 * | / / \
935 * 0 | -->0,0 3,3 4,4 --> backtrack_d = 4, backtrack_k = 0
936 * | \ / \
937 * -1 | 0,1 3,4
938 * | \
939 * -2 | 0,2__
940 * | x == 0
941 */
942 debug("prev[k-1] = %d,%d prev[k+1] = %d,%d\n",
943 kd_prev_column[k-1], xk_to_y(kd_prev_column[k-1],k-1),
944 kd_prev_column[k+1], xk_to_y(kd_prev_column[k+1],k+1));
945 if (y == 0
946 || (x > 0 && kd_prev_column[k - 1] >= kd_prev_column[k + 1])) {
947 k = k - 1;
948 debug("prev k=k-1=%d x=%d y=%d\n",
949 k, kd_prev_column[k], xk_to_y(kd_prev_column[k], k));
950 } else {
951 k = k + 1;
952 debug("prev k=k+1=%d x=%d y=%d\n",
953 k, kd_prev_column[k], xk_to_y(kd_prev_column[k], k));
955 kd_column = kd_prev_column;
958 /* Forwards again, this time recording the diff chunks.
959 * Definitely start from 0,0. kd_column[0] may actually point to the bottom of a snake starting at 0,0 */
960 x = 0;
961 y = 0;
963 kd_column = kd_origin;
964 for (d = 0; d <= backtrack_d; d++, kd_column += kd_len) {
965 int next_x = kd_column[0];
966 int next_y = kd_column[1];
967 debug("Forward track from xy(%d,%d) to xy(%d,%d)\n",
968 x, y, next_x, next_y);
970 struct diff_atom *left_atom = &left->atoms.head[x];
971 int left_section_len = next_x - x;
972 struct diff_atom *right_atom = &right->atoms.head[y];
973 int right_section_len = next_y - y;
975 rc = DIFF_RC_ENOMEM;
976 if (left_section_len && right_section_len) {
977 /* This must be a snake slide.
978 * Snake slides have a straight line leading into them (except when starting at (0,0)). Find
979 * out whether the lead-in is horizontal or vertical:
981 * left
982 * ---------->
983 * |
984 * r| o-o o
985 * i| \ |
986 * g| o o
987 * h| \ \
988 * t| o o
989 * v
991 * If left_section_len > right_section_len, the lead-in is horizontal, meaning first
992 * remove one atom from the left before sliding down the snake.
993 * If right_section_len > left_section_len, the lead-in is vetical, so add one atom from
994 * the right before sliding down the snake. */
995 if (left_section_len == right_section_len + 1) {
996 if (!diff_state_add_chunk(state, true,
997 left_atom, 1,
998 right_atom, 0))
999 goto return_rc;
1000 left_atom++;
1001 left_section_len--;
1002 } else if (right_section_len == left_section_len + 1) {
1003 if (!diff_state_add_chunk(state, true,
1004 left_atom, 0,
1005 right_atom, 1))
1006 goto return_rc;
1007 right_atom++;
1008 right_section_len--;
1009 } else if (left_section_len != right_section_len) {
1010 /* The numbers are making no sense. Should never happen. */
1011 rc = DIFF_RC_USE_DIFF_ALGO_FALLBACK;
1012 goto return_rc;
1015 if (!diff_state_add_chunk(state, true,
1016 left_atom, left_section_len,
1017 right_atom, right_section_len))
1018 goto return_rc;
1019 } else if (left_section_len && !right_section_len) {
1020 /* Only left atoms and none on the right, they form a "minus" chunk, then. */
1021 if (!diff_state_add_chunk(state, true,
1022 left_atom, left_section_len,
1023 right_atom, 0))
1024 goto return_rc;
1025 } else if (!left_section_len && right_section_len) {
1026 /* No left atoms, only atoms on the right, they form a "plus" chunk, then. */
1027 if (!diff_state_add_chunk(state, true,
1028 left_atom, 0,
1029 right_atom, right_section_len))
1030 goto return_rc;
1033 x = next_x;
1034 y = next_y;
1037 rc = DIFF_RC_OK;
1039 return_rc:
1040 free(kd_buf);
1041 debug("** END %s rc=%d\n", __func__, rc);
1042 return rc;