diffseq.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /* Analyze differences between two vectors.
  2. Copyright (C) 1988-1989, 1992-1995, 2001-2004, 2006-2017 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 <http://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. <http://dx.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. <http://dx.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. EARLY_ABORT(ctxt) (Optional) A boolean expression that triggers an
  45. early abort of the computation.
  46. USE_HEURISTIC (Optional) Define if you want to support the
  47. heuristic for large vectors.
  48. It is also possible to use this file with abstract arrays. In this case,
  49. xvec and yvec are not represented in memory. They only exist conceptually.
  50. In this case, the list of defines above is amended as follows:
  51. ELEMENT Undefined.
  52. EQUAL Undefined.
  53. XVECREF_YVECREF_EQUAL(ctxt, xoff, yoff)
  54. A three-argument macro: References xvec[xoff] and
  55. yvec[yoff] and tests these elements for equality.
  56. Before including this file, you also need to include:
  57. #include <limits.h>
  58. #include <stdbool.h>
  59. #include "minmax.h"
  60. */
  61. /* Maximum value of type OFFSET. */
  62. #define OFFSET_MAX \
  63. ((((OFFSET)1 << (sizeof (OFFSET) * CHAR_BIT - 2)) - 1) * 2 + 1)
  64. /* Default to no early abort. */
  65. #ifndef EARLY_ABORT
  66. # define EARLY_ABORT(ctxt) false
  67. #endif
  68. /* Use this to suppress gcc's "...may be used before initialized" warnings.
  69. Beware: The Code argument must not contain commas. */
  70. #ifndef IF_LINT
  71. # if defined GCC_LINT || defined lint
  72. # define IF_LINT(Code) Code
  73. # else
  74. # define IF_LINT(Code) /* empty */
  75. # endif
  76. #endif
  77. /* As above, but when Code must contain one comma. */
  78. #ifndef IF_LINT2
  79. # if defined GCC_LINT || defined lint
  80. # define IF_LINT2(Code1, Code2) Code1, Code2
  81. # else
  82. # define IF_LINT2(Code1, Code2) /* empty */
  83. # endif
  84. #endif
  85. /*
  86. * Context of comparison operation.
  87. */
  88. struct context
  89. {
  90. #ifdef ELEMENT
  91. /* Vectors being compared. */
  92. ELEMENT const *xvec;
  93. ELEMENT const *yvec;
  94. #endif
  95. /* Extra fields. */
  96. EXTRA_CONTEXT_FIELDS
  97. /* Vector, indexed by diagonal, containing 1 + the X coordinate of the point
  98. furthest along the given diagonal in the forward search of the edit
  99. matrix. */
  100. OFFSET *fdiag;
  101. /* Vector, indexed by diagonal, containing the X coordinate of the point
  102. furthest along the given diagonal in the backward search of the edit
  103. matrix. */
  104. OFFSET *bdiag;
  105. #ifdef USE_HEURISTIC
  106. /* This corresponds to the diff --speed-large-files flag. With this
  107. heuristic, for vectors with a constant small density of changes,
  108. the algorithm is linear in the vector size. */
  109. bool heuristic;
  110. #endif
  111. /* Edit scripts longer than this are too expensive to compute. */
  112. OFFSET too_expensive;
  113. /* Snakes bigger than this are considered "big". */
  114. #define SNAKE_LIMIT 20
  115. };
  116. struct partition
  117. {
  118. /* Midpoints of this partition. */
  119. OFFSET xmid;
  120. OFFSET ymid;
  121. /* True if low half will be analyzed minimally. */
  122. bool lo_minimal;
  123. /* Likewise for high half. */
  124. bool hi_minimal;
  125. };
  126. /* Find the midpoint of the shortest edit script for a specified portion
  127. of the two vectors.
  128. Scan from the beginnings of the vectors, and simultaneously from the ends,
  129. doing a breadth-first search through the space of edit-sequence.
  130. When the two searches meet, we have found the midpoint of the shortest
  131. edit sequence.
  132. If FIND_MINIMAL is true, find the minimal edit script regardless of
  133. expense. Otherwise, if the search is too expensive, use heuristics to
  134. stop the search and report a suboptimal answer.
  135. Set PART->(xmid,ymid) to the midpoint (XMID,YMID). The diagonal number
  136. XMID - YMID equals the number of inserted elements minus the number
  137. of deleted elements (counting only elements before the midpoint).
  138. Set PART->lo_minimal to true iff the minimal edit script for the
  139. left half of the partition is known; similarly for PART->hi_minimal.
  140. This function assumes that the first elements of the specified portions
  141. of the two vectors do not match, and likewise that the last elements do not
  142. match. The caller must trim matching elements from the beginning and end
  143. of the portions it is going to specify.
  144. If we return the "wrong" partitions, the worst this can do is cause
  145. suboptimal diff output. It cannot cause incorrect diff output. */
  146. static void
  147. diag (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim, bool find_minimal,
  148. struct partition *part, struct context *ctxt)
  149. {
  150. OFFSET *const fd = ctxt->fdiag; /* Give the compiler a chance. */
  151. OFFSET *const bd = ctxt->bdiag; /* Additional help for the compiler. */
  152. #ifdef ELEMENT
  153. ELEMENT const *const xv = ctxt->xvec; /* Still more help for the compiler. */
  154. ELEMENT const *const yv = ctxt->yvec; /* And more and more . . . */
  155. #define XREF_YREF_EQUAL(x,y) EQUAL (xv[x], yv[y])
  156. #else
  157. #define XREF_YREF_EQUAL(x,y) XVECREF_YVECREF_EQUAL (ctxt, x, y)
  158. #endif
  159. const OFFSET dmin = xoff - ylim; /* Minimum valid diagonal. */
  160. const OFFSET dmax = xlim - yoff; /* Maximum valid diagonal. */
  161. const OFFSET fmid = xoff - yoff; /* Center diagonal of top-down search. */
  162. const OFFSET bmid = xlim - ylim; /* Center diagonal of bottom-up search. */
  163. OFFSET fmin = fmid;
  164. OFFSET fmax = fmid; /* Limits of top-down search. */
  165. OFFSET bmin = bmid;
  166. OFFSET bmax = bmid; /* Limits of bottom-up search. */
  167. OFFSET c; /* Cost. */
  168. bool odd = (fmid - bmid) & 1; /* True if southeast corner is on an odd
  169. diagonal with respect to the northwest. */
  170. fd[fmid] = xoff;
  171. bd[bmid] = xlim;
  172. for (c = 1;; ++c)
  173. {
  174. OFFSET d; /* Active diagonal. */
  175. bool big_snake = false;
  176. /* Extend the top-down search by an edit step in each diagonal. */
  177. if (fmin > dmin)
  178. fd[--fmin - 1] = -1;
  179. else
  180. ++fmin;
  181. if (fmax < dmax)
  182. fd[++fmax + 1] = -1;
  183. else
  184. --fmax;
  185. for (d = fmax; d >= fmin; d -= 2)
  186. {
  187. OFFSET x;
  188. OFFSET y;
  189. OFFSET tlo = fd[d - 1];
  190. OFFSET thi = fd[d + 1];
  191. OFFSET x0 = tlo < thi ? thi : tlo + 1;
  192. for (x = x0, y = x0 - d;
  193. x < xlim && y < ylim && XREF_YREF_EQUAL (x, y);
  194. x++, y++)
  195. continue;
  196. if (x - x0 > SNAKE_LIMIT)
  197. big_snake = true;
  198. fd[d] = x;
  199. if (odd && bmin <= d && d <= bmax && bd[d] <= x)
  200. {
  201. part->xmid = x;
  202. part->ymid = y;
  203. part->lo_minimal = part->hi_minimal = true;
  204. return;
  205. }
  206. }
  207. /* Similarly extend the bottom-up search. */
  208. if (bmin > dmin)
  209. bd[--bmin - 1] = OFFSET_MAX;
  210. else
  211. ++bmin;
  212. if (bmax < dmax)
  213. bd[++bmax + 1] = OFFSET_MAX;
  214. else
  215. --bmax;
  216. for (d = bmax; d >= bmin; d -= 2)
  217. {
  218. OFFSET x;
  219. OFFSET y;
  220. OFFSET tlo = bd[d - 1];
  221. OFFSET thi = bd[d + 1];
  222. OFFSET x0 = tlo < thi ? tlo : thi - 1;
  223. for (x = x0, y = x0 - d;
  224. xoff < x && yoff < y && XREF_YREF_EQUAL (x - 1, y - 1);
  225. x--, y--)
  226. continue;
  227. if (x0 - x > SNAKE_LIMIT)
  228. big_snake = true;
  229. bd[d] = x;
  230. if (!odd && fmin <= d && d <= fmax && x <= fd[d])
  231. {
  232. part->xmid = x;
  233. part->ymid = y;
  234. part->lo_minimal = part->hi_minimal = true;
  235. return;
  236. }
  237. }
  238. if (find_minimal)
  239. continue;
  240. #ifdef USE_HEURISTIC
  241. bool heuristic = ctxt->heuristic;
  242. #else
  243. bool heuristic = false;
  244. #endif
  245. /* Heuristic: check occasionally for a diagonal that has made lots
  246. of progress compared with the edit distance. If we have any
  247. such, find the one that has made the most progress and return it
  248. as if it had succeeded.
  249. With this heuristic, for vectors with a constant small density
  250. of changes, the algorithm is linear in the vector size. */
  251. if (200 < c && big_snake && heuristic)
  252. {
  253. {
  254. OFFSET best = 0;
  255. for (d = fmax; d >= fmin; d -= 2)
  256. {
  257. OFFSET dd = d - fmid;
  258. OFFSET x = fd[d];
  259. OFFSET y = x - d;
  260. OFFSET v = (x - xoff) * 2 - dd;
  261. if (v > 12 * (c + (dd < 0 ? -dd : dd)))
  262. {
  263. if (v > best
  264. && xoff + SNAKE_LIMIT <= x && x < xlim
  265. && yoff + SNAKE_LIMIT <= y && y < ylim)
  266. {
  267. /* We have a good enough best diagonal; now insist
  268. that it end with a significant snake. */
  269. int k;
  270. for (k = 1; XREF_YREF_EQUAL (x - k, y - k); k++)
  271. if (k == SNAKE_LIMIT)
  272. {
  273. best = v;
  274. part->xmid = x;
  275. part->ymid = y;
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. if (best > 0)
  282. {
  283. part->lo_minimal = true;
  284. part->hi_minimal = false;
  285. return;
  286. }
  287. }
  288. {
  289. OFFSET best = 0;
  290. for (d = bmax; d >= bmin; d -= 2)
  291. {
  292. OFFSET dd = d - bmid;
  293. OFFSET x = bd[d];
  294. OFFSET y = x - d;
  295. OFFSET v = (xlim - x) * 2 + dd;
  296. if (v > 12 * (c + (dd < 0 ? -dd : dd)))
  297. {
  298. if (v > best
  299. && xoff < x && x <= xlim - SNAKE_LIMIT
  300. && yoff < y && y <= ylim - SNAKE_LIMIT)
  301. {
  302. /* We have a good enough best diagonal; now insist
  303. that it end with a significant snake. */
  304. int k;
  305. for (k = 0; XREF_YREF_EQUAL (x + k, y + k); k++)
  306. if (k == SNAKE_LIMIT - 1)
  307. {
  308. best = v;
  309. part->xmid = x;
  310. part->ymid = y;
  311. break;
  312. }
  313. }
  314. }
  315. }
  316. if (best > 0)
  317. {
  318. part->lo_minimal = false;
  319. part->hi_minimal = true;
  320. return;
  321. }
  322. }
  323. }
  324. /* Heuristic: if we've gone well beyond the call of duty, give up
  325. and report halfway between our best results so far. */
  326. if (c >= ctxt->too_expensive)
  327. {
  328. OFFSET fxybest;
  329. OFFSET fxbest IF_LINT (= 0);
  330. OFFSET bxybest;
  331. OFFSET bxbest IF_LINT (= 0);
  332. /* Find forward diagonal that maximizes X + Y. */
  333. fxybest = -1;
  334. for (d = fmax; d >= fmin; d -= 2)
  335. {
  336. OFFSET x = MIN (fd[d], xlim);
  337. OFFSET y = x - d;
  338. if (ylim < y)
  339. {
  340. x = ylim + d;
  341. y = ylim;
  342. }
  343. if (fxybest < x + y)
  344. {
  345. fxybest = x + y;
  346. fxbest = x;
  347. }
  348. }
  349. /* Find backward diagonal that minimizes X + Y. */
  350. bxybest = OFFSET_MAX;
  351. for (d = bmax; d >= bmin; d -= 2)
  352. {
  353. OFFSET x = MAX (xoff, bd[d]);
  354. OFFSET y = x - d;
  355. if (y < yoff)
  356. {
  357. x = yoff + d;
  358. y = yoff;
  359. }
  360. if (x + y < bxybest)
  361. {
  362. bxybest = x + y;
  363. bxbest = x;
  364. }
  365. }
  366. /* Use the better of the two diagonals. */
  367. if ((xlim + ylim) - bxybest < fxybest - (xoff + yoff))
  368. {
  369. part->xmid = fxbest;
  370. part->ymid = fxybest - fxbest;
  371. part->lo_minimal = true;
  372. part->hi_minimal = false;
  373. }
  374. else
  375. {
  376. part->xmid = bxbest;
  377. part->ymid = bxybest - bxbest;
  378. part->lo_minimal = false;
  379. part->hi_minimal = true;
  380. }
  381. return;
  382. }
  383. }
  384. #undef XREF_YREF_EQUAL
  385. }
  386. /* Compare in detail contiguous subsequences of the two vectors
  387. which are known, as a whole, to match each other.
  388. The subsequence of vector 0 is [XOFF, XLIM) and likewise for vector 1.
  389. Note that XLIM, YLIM are exclusive bounds. All indices into the vectors
  390. are origin-0.
  391. If FIND_MINIMAL, find a minimal difference no matter how
  392. expensive it is.
  393. The results are recorded by invoking NOTE_DELETE and NOTE_INSERT.
  394. Return false if terminated normally, or true if terminated through early
  395. abort. */
  396. static bool
  397. compareseq (OFFSET xoff, OFFSET xlim, OFFSET yoff, OFFSET ylim,
  398. bool find_minimal, struct context *ctxt)
  399. {
  400. #ifdef ELEMENT
  401. ELEMENT const *xv = ctxt->xvec; /* Help the compiler. */
  402. ELEMENT const *yv = ctxt->yvec;
  403. #define XREF_YREF_EQUAL(x,y) EQUAL (xv[x], yv[y])
  404. #else
  405. #define XREF_YREF_EQUAL(x,y) XVECREF_YVECREF_EQUAL (ctxt, x, y)
  406. #endif
  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. while (yoff < ylim)
  422. {
  423. NOTE_INSERT (ctxt, yoff);
  424. if (EARLY_ABORT (ctxt))
  425. return true;
  426. yoff++;
  427. }
  428. else if (yoff == ylim)
  429. while (xoff < xlim)
  430. {
  431. NOTE_DELETE (ctxt, xoff);
  432. if (EARLY_ABORT (ctxt))
  433. return true;
  434. xoff++;
  435. }
  436. else
  437. {
  438. struct partition part IF_LINT2 (= { .xmid = 0, .ymid = 0 });
  439. /* Find a point of correspondence in the middle of the vectors. */
  440. diag (xoff, xlim, yoff, ylim, find_minimal, &part, ctxt);
  441. /* Use the partitions to split this problem into subproblems. */
  442. if (compareseq (xoff, part.xmid, yoff, part.ymid, part.lo_minimal, ctxt))
  443. return true;
  444. if (compareseq (part.xmid, xlim, part.ymid, ylim, part.hi_minimal, ctxt))
  445. return true;
  446. }
  447. return false;
  448. #undef XREF_YREF_EQUAL
  449. }
  450. #undef ELEMENT
  451. #undef EQUAL
  452. #undef OFFSET
  453. #undef EXTRA_CONTEXT_FIELDS
  454. #undef NOTE_DELETE
  455. #undef NOTE_INSERT
  456. #undef EARLY_ABORT
  457. #undef USE_HEURISTIC
  458. #undef XVECREF_YVECREF_EQUAL
  459. #undef OFFSET_MAX