Debian Codegraph @

lib/diffseq.h

raw
1 /* Analyze differences between two vectors.
2
3 Copyright (C) 1988-1989, 1992-1995, 2001-2004, 2006-2025 Free Software
4 Foundation, Inc.
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18
19
20 /* The basic idea is to consider two vectors as similar if, when
21 transforming the first vector into the second vector through a
22 sequence of edits (inserts and deletes of one element each),
23 this sequence is short - or equivalently, if the ordered list
24 of elements that are untouched by these edits is long. For a
25 good introduction to the subject, read about the "Levenshtein
26 distance" in Wikipedia.
27
28 The basic algorithm is described in:
29 "An O(ND) Difference Algorithm and its Variations", Eugene W. Myers,
30 Algorithmica Vol. 1, 1986, pp. 251-266,
31 <https://doi.org/10.1007/BF01840446>.
32 See especially section 4.2, which describes the variation used below.
33
34 The basic algorithm was independently discovered as described in:
35 "Algorithms for Approximate String Matching", Esko Ukkonen,
36 Information and Control Vol. 64, 1985, pp. 100-118,
37 <https://doi.org/10.1016/S0019-9958(85)80046-2>.
38
39 Unless the 'find_minimal' flag is set, this code uses the TOO_EXPENSIVE
40 heuristic, by Paul Eggert, to limit the cost to O(N**1.5 log N)
41 at the price of producing suboptimal output for large inputs with
42 many differences. */
43
44 /* Before including this file, you need to define:
45 ELEMENT The element type of the vectors being compared.
46 EQUAL A two-argument macro that tests two elements for
47 equality.
48 OFFSET A signed integer type sufficient to hold the
49 difference between two indices. Usually
50 something like ptrdiff_t.
51 OFFSET_MAX (Optional) The maximum value of OFFSET (e.g.,
52 PTRDIFF_MAX). If omitted, it is inferred in a
53 way portable to the vast majority of C platforms,
54 as they lack padding bits.
55 EXTRA_CONTEXT_FIELDS Declarations of fields for 'struct context'.
56 NOTE_DELETE(ctxt, xoff) Record the removal of the object xvec[xoff].
57 NOTE_INSERT(ctxt, yoff) Record the insertion of the object yvec[yoff].
58 NOTE_ORDERED (Optional) A boolean expression saying that
59 NOTE_DELETE and NOTE_INSERT calls must be
60 issued in offset order.
61 EARLY_ABORT(ctxt) (Optional) A boolean expression that triggers an
62 early abort of the computation.
63 USE_HEURISTIC (Optional) Define if you want to support the
64 heuristic for large vectors.
65
66 It is also possible to use this file with abstract arrays. In this case,
67 xvec and yvec are not represented in memory. They only exist conceptually.
68 In this case, the list of defines above is amended as follows:
69 ELEMENT Undefined.
70 EQUAL Undefined.
71 XVECREF_YVECREF_EQUAL(ctxt, xoff, yoff)
72 A three-argument macro: References xvec[xoff] and
73 yvec[yoff] and tests these elements for equality.
74
75 Before including this file, you also need to include:
76 #include <limits.h>
77 #include "minmax.h"
78 */
79
80 /* Maximum value of type OFFSET. */
81 #ifndef OFFSET_MAX
82 # define OFFSET_MAX \
83 ((((OFFSET) 1 << (sizeof (OFFSET) * CHAR_BIT - 2)) - 1) * 2 + 1)
84 #endif
85
86 /* Default to no early abort. */
87 #ifndef EARLY_ABORT
88 # define EARLY_ABORT(ctxt) false
89 #endif
90
91 #ifndef NOTE_ORDERED
92 # define NOTE_ORDERED false
93 #endif
94
95 /* Suppress gcc's "...may be used before initialized" warnings,
96 generated by GCC versions up to at least GCC 14.2.
97 Likewise for gcc -fanalyzer's "use of uninitialized value" warnings. */
98 #if _GL_GNUC_PREREQ (4, 7)
99 # pragma GCC diagnostic push
100 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
101 # if _GL_GNUC_PREREQ (13, 0)
102 # pragma GCC diagnostic ignored "-Wanalyzer-use-of-uninitialized-value"
103 # endif
104 #endif
105
106 /*
107 * Context of comparison operation.
108 */
109 struct context
110 {
111 #ifdef ELEMENT
112 /* Vectors being compared. */
113 ELEMENT const *xvec;
114 ELEMENT const *yvec;
115 #endif
116
117 /* Extra fields. */
118 EXTRA_CONTEXT_FIELDS
119
120 /* Vector, indexed by diagonal, containing 1 + the X coordinate of the point
121 furthest along the given diagonal in the forward search of the edit
122 matrix. */
123 OFFSET *fdiag;
124
125 /* Vector, indexed by diagonal, containing the X coordinate of the point
126 furthest along the given diagonal in the backward search of the edit
127 matrix. */
128 OFFSET *bdiag;
129
130 #ifdef USE_HEURISTIC
131 /* This corresponds to the diff --speed-large-files flag. With this
132 heuristic, for vectors with a constant small density of changes,
133 the algorithm is linear in the vector size. */
134 bool heuristic;
135 #endif
136
137 /* Edit scripts longer than this are too expensive to compute. */
138 OFFSET too_expensive;
139
140 /* Snakes bigger than this are considered "big". */
141 #define SNAKE_LIMIT 20
142 };
143
144 struct partition
145 {
146 /* Midpoints of this partition. */
147 OFFSET xmid;
148 OFFSET ymid;
149
150 /* True if low half will be analyzed minimally. */
151 bool lo_minimal;
152
153 /* Likewise for high half. */
154 bool hi_minimal;
155 };
156
157
158 /* Find the midpoint of the shortest edit script for a specified portion
159 of the two vectors.
160
161 Scan from the beginnings of the vectors, and simultaneously from the ends,
162 doing a breadth-first search through the space of edit-sequence.
163 When the two searches meet, we have found the midpoint of the shortest
164 edit sequence.
165
166 If FIND_MINIMAL is true, find the minimal edit script regardless of
167 expense. Otherwise, if the search is too expensive, use heuristics to
168 stop the search and report a suboptimal answer.
169
170 Set PART->(xmid,ymid) to the midpoint (XMID,YMID). The diagonal number
171 XMID - YMID equals the number of inserted elements minus the number
172 of deleted elements (counting only elements before the midpoint).
173
174 Set PART->lo_minimal to true iff the minimal edit script for the
175 left half of the partition is known; similarly for PART->hi_minimal.
176
177 This function assumes that the first elements of the specified portions
178 of the two vectors do not match, and likewise that the last elements do not
179 match. The caller must trim matching elements from the beginning and end
180 of the portions it is going to specify.
181
182 If we return the "wrong" partitions, the worst this can do is cause
183 suboptimal diff output. It cannot cause incorrect diff output. */
184
185 static void
186 diag (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim, bool find_minimal,
187 struct partition *part, struct context *ctxt)
188 {
189 OFFSET *const fd = ctxt->fdiag; /* Give the compiler a chance. */
190 OFFSET *const bd = ctxt->bdiag; /* Additional help for the compiler. */
191 #ifdef ELEMENT
192 ELEMENT const *const xv = ctxt->xvec; /* Still more help for the compiler. */
193 ELEMENT const *const yv = ctxt->yvec; /* And more and more . . . */
194 #define XREF_YREF_EQUAL(x,y) EQUAL (xv[x], yv[y])
195 #else
196 #define XREF_YREF_EQUAL(x,y) XVECREF_YVECREF_EQUAL (ctxt, x, y)
197 #endif
198 const OFFSET dmin = xoff - ylim; /* Minimum valid diagonal. */
199 const OFFSET dmax = xlim - yoff; /* Maximum valid diagonal. */
200 const OFFSET fmid = xoff - yoff; /* Center diagonal of top-down search. */
201 const OFFSET bmid = xlim - ylim; /* Center diagonal of bottom-up search. */
202 OFFSET fmin = fmid;
203 OFFSET fmax = fmid; /* Limits of top-down search. */
204 OFFSET bmin = bmid;
205 OFFSET bmax = bmid; /* Limits of bottom-up search. */
206 OFFSET c; /* Cost. */
207 bool odd = (fmid - bmid) & 1; /* True if southeast corner is on an odd
208 diagonal with respect to the northwest. */
209
210 fd[fmid] = xoff;
211 bd[bmid] = xlim;
212
213 for (c = 1;; ++c)
214 {
215 OFFSET d; /* Active diagonal. */
216 bool big_snake = false;
217
218 /* Extend the top-down search by an edit step in each diagonal. */
219 if (fmin > dmin)
220 fd[--fmin - 1] = -1;
221 else
222 ++fmin;
223 if (fmax < dmax)
224 fd[++fmax + 1] = -1;
225 else
226 --fmax;
227 for (d = fmax; d >= fmin; d -= 2)
228 {
229 OFFSET x;
230 OFFSET y;
231 OFFSET tlo = fd[d - 1];
232 OFFSET thi = fd[d + 1];
233 OFFSET x0 = tlo < thi ? thi : tlo + 1;
234
235 for (x = x0, y = x0 - d;
236 x < xlim && y < ylim && XREF_YREF_EQUAL (x, y);
237 x++, y++)
238 continue;
239 if (x - x0 > SNAKE_LIMIT)
240 big_snake = true;
241 fd[d] = x;
242 if (odd && bmin <= d && d <= bmax && bd[d] <= x)
243 {
244 part->xmid = x;
245 part->ymid = y;
246 part->lo_minimal = part->hi_minimal = true;
247 return;
248 }
249 }
250
251 /* Similarly extend the bottom-up search. */
252 if (bmin > dmin)
253 bd[--bmin - 1] = OFFSET_MAX;
254 else
255 ++bmin;
256 if (bmax < dmax)
257 bd[++bmax + 1] = OFFSET_MAX;
258 else
259 --bmax;
260 for (d = bmax; d >= bmin; d -= 2)
261 {
262 OFFSET x;
263 OFFSET y;
264 OFFSET tlo = bd[d - 1];
265 OFFSET thi = bd[d + 1];
266 OFFSET x0 = tlo < thi ? tlo : thi - 1;
267
268 for (x = x0, y = x0 - d;
269 xoff < x && yoff < y && XREF_YREF_EQUAL (x - 1, y - 1);
270 x--, y--)
271 continue;
272 if (x0 - x > SNAKE_LIMIT)
273 big_snake = true;
274 bd[d] = x;
275 if (!odd && fmin <= d && d <= fmax && x <= fd[d])
276 {
277 part->xmid = x;
278 part->ymid = y;
279 part->lo_minimal = part->hi_minimal = true;
280 return;
281 }
282 }
283
284 if (find_minimal)
285 continue;
286
287 #ifdef USE_HEURISTIC
288 bool heuristic = ctxt->heuristic;
289 #else
290 bool heuristic = false;
291 #endif
292
293 /* Heuristic: check occasionally for a diagonal that has made lots
294 of progress compared with the edit distance. If we have any
295 such, find the one that has made the most progress and return it
296 as if it had succeeded.
297
298 With this heuristic, for vectors with a constant small density
299 of changes, the algorithm is linear in the vector size. */
300
301 if (200 < c && big_snake && heuristic)
302 {
303 {
304 OFFSET best = 0;
305
306 for (d = fmax; d >= fmin; d -= 2)
307 {
308 OFFSET dd = d - fmid;
309 OFFSET x = fd[d];
310 OFFSET y = x - d;
311 OFFSET v = (x - xoff) * 2 - dd;
312
313 if (v > 12 * (c + (dd < 0 ? -dd : dd)))
314 {
315 if (v > best
316 && xoff + SNAKE_LIMIT <= x && x < xlim
317 && yoff + SNAKE_LIMIT <= y && y < ylim)
318 {
319 /* We have a good enough best diagonal; now insist
320 that it end with a significant snake. */
321 int k;
322
323 for (k = 1; XREF_YREF_EQUAL (x - k, y - k); k++)
324 if (k == SNAKE_LIMIT)
325 {
326 best = v;
327 part->xmid = x;
328 part->ymid = y;
329 break;
330 }
331 }
332 }
333 }
334 if (best > 0)
335 {
336 part->lo_minimal = true;
337 part->hi_minimal = false;
338 return;
339 }
340 }
341
342 {
343 OFFSET best = 0;
344
345 for (d = bmax; d >= bmin; d -= 2)
346 {
347 OFFSET dd = d - bmid;
348 OFFSET x = bd[d];
349 OFFSET y = x - d;
350 OFFSET v = (xlim - x) * 2 + dd;
351
352 if (v > 12 * (c + (dd < 0 ? -dd : dd)))
353 {
354 if (v > best
355 && xoff < x && x <= xlim - SNAKE_LIMIT
356 && yoff < y && y <= ylim - SNAKE_LIMIT)
357 {
358 /* We have a good enough best diagonal; now insist
359 that it end with a significant snake. */
360 int k;
361
362 for (k = 0; XREF_YREF_EQUAL (x + k, y + k); k++)
363 if (k == SNAKE_LIMIT - 1)
364 {
365 best = v;
366 part->xmid = x;
367 part->ymid = y;
368 break;
369 }
370 }
371 }
372 }
373 if (best > 0)
374 {
375 part->lo_minimal = false;
376 part->hi_minimal = true;
377 return;
378 }
379 }
380 }
381
382 /* Heuristic: if we've gone well beyond the call of duty, give up
383 and report halfway between our best results so far. */
384 if (c >= ctxt->too_expensive)
385 {
386 /* Find forward diagonal that maximizes X + Y. */
387 OFFSET fxybest = -1, fxbest;
388 for (d = fmax; d >= fmin; d -= 2)
389 {
390 OFFSET x = MIN (fd[d], xlim);
391 OFFSET y = x - d;
392 if (ylim < y)
393 {
394 x = ylim + d;
395 y = ylim;
396 }
397 if (fxybest < x + y)
398 {
399 fxybest = x + y;
400 fxbest = x;
401 }
402 }
403
404 /* Find backward diagonal that minimizes X + Y. */
405 OFFSET bxybest = OFFSET_MAX, bxbest;
406 for (d = bmax; d >= bmin; d -= 2)
407 {
408 OFFSET x = MAX (xoff, bd[d]);
409 OFFSET y = x - d;
410 if (y < yoff)
411 {
412 x = yoff + d;
413 y = yoff;
414 }
415 if (x + y < bxybest)
416 {
417 bxybest = x + y;
418 bxbest = x;
419 }
420 }
421
422 /* Use the better of the two diagonals. */
423 if ((xlim + ylim) - bxybest < fxybest - (xoff + yoff))
424 {
425 part->xmid = fxbest;
426 part->ymid = fxybest - fxbest;
427 part->lo_minimal = true;
428 part->hi_minimal = false;
429 }
430 else
431 {
432 part->xmid = bxbest;
433 part->ymid = bxybest - bxbest;
434 part->lo_minimal = false;
435 part->hi_minimal = true;
436 }
437 return;
438 }
439 }
440 #undef XREF_YREF_EQUAL
441 }
442
443
444 /* Compare in detail contiguous subsequences of the two vectors
445 which are known, as a whole, to match each other.
446
447 The subsequence of vector 0 is [XOFF, XLIM) and likewise for vector 1.
448
449 Note that XLIM, YLIM are exclusive bounds. All indices into the vectors
450 are origin-0.
451
452 If FIND_MINIMAL, find a minimal difference no matter how
453 expensive it is.
454
455 The results are recorded by invoking NOTE_DELETE and NOTE_INSERT.
456
457 Return false if terminated normally, or true if terminated through early
458 abort. */
459
460 static bool
461 compareseq (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim,
462 bool find_minimal, struct context *ctxt)
463 {
464 #ifdef ELEMENT
465 ELEMENT const *xv = ctxt->xvec; /* Help the compiler. */
466 ELEMENT const *yv = ctxt->yvec;
467 #define XREF_YREF_EQUAL(x,y) EQUAL (xv[x], yv[y])
468 #else
469 #define XREF_YREF_EQUAL(x,y) XVECREF_YVECREF_EQUAL (ctxt, x, y)
470 #endif
471
472 while (true)
473 {
474 /* Slide down the bottom initial diagonal. */
475 while (xoff < xlim && yoff < ylim && XREF_YREF_EQUAL (xoff, yoff))
476 {
477 xoff++;
478 yoff++;
479 }
480
481 /* Slide up the top initial diagonal. */
482 while (xoff < xlim && yoff < ylim && XREF_YREF_EQUAL (xlim - 1, ylim - 1))
483 {
484 xlim--;
485 ylim--;
486 }
487
488 /* Handle simple cases. */
489 if (xoff == xlim)
490 {
491 while (yoff < ylim)
492 {
493 NOTE_INSERT (ctxt, yoff);
494 if (EARLY_ABORT (ctxt))
495 return true;
496 yoff++;
497 }
498 break;
499 }
500 if (yoff == ylim)
501 {
502 while (xoff < xlim)
503 {
504 NOTE_DELETE (ctxt, xoff);
505 if (EARLY_ABORT (ctxt))
506 return true;
507 xoff++;
508 }
509 break;
510 }
511
512 struct partition part;
513
514 /* Find a point of correspondence in the middle of the vectors. */
515 diag (xoff, xlim, yoff, ylim, find_minimal, &part, ctxt);
516
517 /* Use the partitions to split this problem into subproblems. */
518 OFFSET xoff1, xlim1, yoff1, ylim1, xoff2, xlim2, yoff2, ylim2;
519 bool find_minimal1, find_minimal2;
520 if (!NOTE_ORDERED
521 && ((xlim + ylim) - (part.xmid + part.ymid)
522 < (part.xmid + part.ymid) - (xoff + yoff)))
523 {
524 /* The second problem is smaller and the caller doesn't
525 care about order, so do the second problem first to
526 lessen recursion. */
527 xoff1 = part.xmid; xlim1 = xlim;
528 yoff1 = part.ymid; ylim1 = ylim;
529 find_minimal1 = part.hi_minimal;
530
531 xoff2 = xoff; xlim2 = part.xmid;
532 yoff2 = yoff; ylim2 = part.ymid;
533 find_minimal2 = part.lo_minimal;
534 }
535 else
536 {
537 xoff1 = xoff; xlim1 = part.xmid;
538 yoff1 = yoff; ylim1 = part.ymid;
539 find_minimal1 = part.lo_minimal;
540
541 xoff2 = part.xmid; xlim2 = xlim;
542 yoff2 = part.ymid; ylim2 = ylim;
543 find_minimal2 = part.hi_minimal;
544 }
545
546 /* Recurse to do one subproblem. */
547 bool early = compareseq (xoff1, xlim1, yoff1, ylim1, find_minimal1, ctxt);
548 if (early)
549 return early;
550
551 /* Iterate to do the other subproblem. */
552 xoff = xoff2; xlim = xlim2;
553 yoff = yoff2; ylim = ylim2;
554 find_minimal = find_minimal2;
555 }
556
557 return false;
558 #undef XREF_YREF_EQUAL
559 }
560
561 #if _GL_GNUC_PREREQ (4, 7)
562 # pragma GCC diagnostic pop
563 #endif
564
565 #undef ELEMENT
566 #undef EQUAL
567 #undef OFFSET
568 #undef EXTRA_CONTEXT_FIELDS
569 #undef NOTE_DELETE
570 #undef NOTE_INSERT
571 #undef EARLY_ABORT
572 #undef USE_HEURISTIC
573 #undef XVECREF_YVECREF_EQUAL
574 #undef OFFSET_MAX