diffseq.h 18 KB

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