File Coverage

deps/libgit2/src/libgit2/xdiff/xdiffi.c
Criterion Covered Total %
statement 150 423 35.4
branch 76 312 24.3
condition n/a
subroutine n/a
pod n/a
total 226 735 30.7


line stmt bran cond sub pod time code
1             /*
2             * LibXDiff by Davide Libenzi ( File Differential Library )
3             * Copyright (C) 2003 Davide Libenzi
4             *
5             * This library is free software; you can redistribute it and/or
6             * modify it under the terms of the GNU Lesser General Public
7             * License as published by the Free Software Foundation; either
8             * version 2.1 of the License, or (at your option) any later version.
9             *
10             * This library is distributed in the hope that it will be useful,
11             * but WITHOUT ANY WARRANTY; without even the implied warranty of
12             * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13             * Lesser General Public License for more details.
14             *
15             * You should have received a copy of the GNU Lesser General Public
16             * License along with this library; if not, see
17             * .
18             *
19             * Davide Libenzi
20             *
21             */
22              
23             #include "xinclude.h"
24              
25             #define XDL_MAX_COST_MIN 256
26             #define XDL_HEUR_MIN_COST 256
27             #define XDL_LINE_MAX (long)((1UL << (CHAR_BIT * sizeof(long) - 1)) - 1)
28             #define XDL_SNAKE_CNT 20
29             #define XDL_K_HEUR 4
30              
31             typedef struct s_xdpsplit {
32             long i1, i2;
33             int min_lo, min_hi;
34             } xdpsplit_t;
35              
36             /*
37             * See "An O(ND) Difference Algorithm and its Variations", by Eugene Myers.
38             * Basically considers a "box" (off1, off2, lim1, lim2) and scan from both
39             * the forward diagonal starting from (off1, off2) and the backward diagonal
40             * starting from (lim1, lim2). If the K values on the same diagonal crosses
41             * returns the furthest point of reach. We might encounter expensive edge cases
42             * using this algorithm, so a little bit of heuristic is needed to cut the
43             * search and to return a suboptimal point.
44             */
45 0           static long xdl_split(unsigned long const *ha1, long off1, long lim1,
46             unsigned long const *ha2, long off2, long lim2,
47             long *kvdf, long *kvdb, int need_min, xdpsplit_t *spl,
48             xdalgoenv_t *xenv) {
49 0           long dmin = off1 - lim2, dmax = lim1 - off2;
50 0           long fmid = off1 - off2, bmid = lim1 - lim2;
51 0           long odd = (fmid - bmid) & 1;
52 0           long fmin = fmid, fmax = fmid;
53 0           long bmin = bmid, bmax = bmid;
54             long ec, d, i1, i2, prev1, best, dd, v, k;
55              
56             /*
57             * Set initial diagonal values for both forward and backward path.
58             */
59 0           kvdf[fmid] = off1;
60 0           kvdb[bmid] = lim1;
61              
62 0           for (ec = 1;; ec++) {
63 0           int got_snake = 0;
64              
65             /*
66             * We need to extend the diagonal "domain" by one. If the next
67             * values exits the box boundaries we need to change it in the
68             * opposite direction because (max - min) must be a power of
69             * two.
70             *
71             * Also we initialize the external K value to -1 so that we can
72             * avoid extra conditions in the check inside the core loop.
73             */
74 0 0         if (fmin > dmin)
75 0           kvdf[--fmin - 1] = -1;
76             else
77 0           ++fmin;
78 0 0         if (fmax < dmax)
79 0           kvdf[++fmax + 1] = -1;
80             else
81 0           --fmax;
82              
83 0 0         for (d = fmax; d >= fmin; d -= 2) {
84 0 0         if (kvdf[d - 1] >= kvdf[d + 1])
85 0           i1 = kvdf[d - 1] + 1;
86             else
87 0           i1 = kvdf[d + 1];
88 0           prev1 = i1;
89 0           i2 = i1 - d;
90 0 0         for (; i1 < lim1 && i2 < lim2 && ha1[i1] == ha2[i2]; i1++, i2++);
    0          
    0          
91 0 0         if (i1 - prev1 > xenv->snake_cnt)
92 0           got_snake = 1;
93 0           kvdf[d] = i1;
94 0 0         if (odd && bmin <= d && d <= bmax && kvdb[d] <= i1) {
    0          
    0          
    0          
95 0           spl->i1 = i1;
96 0           spl->i2 = i2;
97 0           spl->min_lo = spl->min_hi = 1;
98 0           return ec;
99             }
100             }
101              
102             /*
103             * We need to extend the diagonal "domain" by one. If the next
104             * values exits the box boundaries we need to change it in the
105             * opposite direction because (max - min) must be a power of
106             * two.
107             *
108             * Also we initialize the external K value to -1 so that we can
109             * avoid extra conditions in the check inside the core loop.
110             */
111 0 0         if (bmin > dmin)
112 0           kvdb[--bmin - 1] = XDL_LINE_MAX;
113             else
114 0           ++bmin;
115 0 0         if (bmax < dmax)
116 0           kvdb[++bmax + 1] = XDL_LINE_MAX;
117             else
118 0           --bmax;
119              
120 0 0         for (d = bmax; d >= bmin; d -= 2) {
121 0 0         if (kvdb[d - 1] < kvdb[d + 1])
122 0           i1 = kvdb[d - 1];
123             else
124 0           i1 = kvdb[d + 1] - 1;
125 0           prev1 = i1;
126 0           i2 = i1 - d;
127 0 0         for (; i1 > off1 && i2 > off2 && ha1[i1 - 1] == ha2[i2 - 1]; i1--, i2--);
    0          
    0          
128 0 0         if (prev1 - i1 > xenv->snake_cnt)
129 0           got_snake = 1;
130 0           kvdb[d] = i1;
131 0 0         if (!odd && fmin <= d && d <= fmax && i1 <= kvdf[d]) {
    0          
    0          
    0          
132 0           spl->i1 = i1;
133 0           spl->i2 = i2;
134 0           spl->min_lo = spl->min_hi = 1;
135 0           return ec;
136             }
137             }
138              
139 0 0         if (need_min)
140 0           continue;
141              
142             /*
143             * If the edit cost is above the heuristic trigger and if
144             * we got a good snake, we sample current diagonals to see
145             * if some of them have reached an "interesting" path. Our
146             * measure is a function of the distance from the diagonal
147             * corner (i1 + i2) penalized with the distance from the
148             * mid diagonal itself. If this value is above the current
149             * edit cost times a magic factor (XDL_K_HEUR) we consider
150             * it interesting.
151             */
152 0 0         if (got_snake && ec > xenv->heur_min) {
    0          
153 0 0         for (best = 0, d = fmax; d >= fmin; d -= 2) {
154 0 0         dd = d > fmid ? d - fmid: fmid - d;
155 0           i1 = kvdf[d];
156 0           i2 = i1 - d;
157 0           v = (i1 - off1) + (i2 - off2) - dd;
158              
159 0 0         if (v > XDL_K_HEUR * ec && v > best &&
    0          
    0          
160 0 0         off1 + xenv->snake_cnt <= i1 && i1 < lim1 &&
    0          
161 0 0         off2 + xenv->snake_cnt <= i2 && i2 < lim2) {
162 0 0         for (k = 1; ha1[i1 - k] == ha2[i2 - k]; k++)
163 0 0         if (k == xenv->snake_cnt) {
164 0           best = v;
165 0           spl->i1 = i1;
166 0           spl->i2 = i2;
167 0           break;
168             }
169             }
170             }
171 0 0         if (best > 0) {
172 0           spl->min_lo = 1;
173 0           spl->min_hi = 0;
174 0           return ec;
175             }
176              
177 0 0         for (best = 0, d = bmax; d >= bmin; d -= 2) {
178 0 0         dd = d > bmid ? d - bmid: bmid - d;
179 0           i1 = kvdb[d];
180 0           i2 = i1 - d;
181 0           v = (lim1 - i1) + (lim2 - i2) - dd;
182              
183 0 0         if (v > XDL_K_HEUR * ec && v > best &&
    0          
    0          
184 0 0         off1 < i1 && i1 <= lim1 - xenv->snake_cnt &&
    0          
185 0 0         off2 < i2 && i2 <= lim2 - xenv->snake_cnt) {
186 0 0         for (k = 0; ha1[i1 + k] == ha2[i2 + k]; k++)
187 0 0         if (k == xenv->snake_cnt - 1) {
188 0           best = v;
189 0           spl->i1 = i1;
190 0           spl->i2 = i2;
191 0           break;
192             }
193             }
194             }
195 0 0         if (best > 0) {
196 0           spl->min_lo = 0;
197 0           spl->min_hi = 1;
198 0           return ec;
199             }
200             }
201              
202             /*
203             * Enough is enough. We spent too much time here and now we
204             * collect the furthest reaching path using the (i1 + i2)
205             * measure.
206             */
207 0 0         if (ec >= xenv->mxcost) {
208             long fbest, fbest1, bbest, bbest1;
209              
210 0           fbest = fbest1 = -1;
211 0 0         for (d = fmax; d >= fmin; d -= 2) {
212 0           i1 = XDL_MIN(kvdf[d], lim1);
213 0           i2 = i1 - d;
214 0 0         if (lim2 < i2)
215 0           i1 = lim2 + d, i2 = lim2;
216 0 0         if (fbest < i1 + i2) {
217 0           fbest = i1 + i2;
218 0           fbest1 = i1;
219             }
220             }
221              
222 0           bbest = bbest1 = XDL_LINE_MAX;
223 0 0         for (d = bmax; d >= bmin; d -= 2) {
224 0           i1 = XDL_MAX(off1, kvdb[d]);
225 0           i2 = i1 - d;
226 0 0         if (i2 < off2)
227 0           i1 = off2 + d, i2 = off2;
228 0 0         if (i1 + i2 < bbest) {
229 0           bbest = i1 + i2;
230 0           bbest1 = i1;
231             }
232             }
233              
234 0 0         if ((lim1 + lim2) - bbest < fbest - (off1 + off2)) {
235 0           spl->i1 = fbest1;
236 0           spl->i2 = fbest - fbest1;
237 0           spl->min_lo = 1;
238 0           spl->min_hi = 0;
239             } else {
240 0           spl->i1 = bbest1;
241 0           spl->i2 = bbest - bbest1;
242 0           spl->min_lo = 0;
243 0           spl->min_hi = 1;
244             }
245 0           return ec;
246             }
247 0           }
248             }
249              
250              
251             /*
252             * Rule: "Divide et Impera" (divide & conquer). Recursively split the box in
253             * sub-boxes by calling the box splitting function. Note that the real job
254             * (marking changed lines) is done in the two boundary reaching checks.
255             */
256 73           int xdl_recs_cmp(diffdata_t *dd1, long off1, long lim1,
257             diffdata_t *dd2, long off2, long lim2,
258             long *kvdf, long *kvdb, int need_min, xdalgoenv_t *xenv) {
259 73           unsigned long const *ha1 = dd1->ha, *ha2 = dd2->ha;
260              
261             /*
262             * Shrink the box by walking through each diagonal snake (SW and NE).
263             */
264 75 100         for (; off1 < lim1 && off2 < lim2 && ha1[off1] == ha2[off2]; off1++, off2++);
    100          
    50          
265 73 100         for (; off1 < lim1 && off2 < lim2 && ha1[lim1 - 1] == ha2[lim2 - 1]; lim1--, lim2--);
    50          
    0          
266              
267             /*
268             * If one dimension is empty, then all records on the other one must
269             * be obviously changed.
270             */
271 73 100         if (off1 == lim1) {
272 71           char *rchg2 = dd2->rchg;
273 71           long *rindex2 = dd2->rindex;
274              
275 71 50         for (; off2 < lim2; off2++)
276 0           rchg2[rindex2[off2]] = 1;
277 2 50         } else if (off2 == lim2) {
278 2           char *rchg1 = dd1->rchg;
279 2           long *rindex1 = dd1->rindex;
280              
281 6 100         for (; off1 < lim1; off1++)
282 4           rchg1[rindex1[off1]] = 1;
283             } else {
284             xdpsplit_t spl;
285 0           spl.i1 = spl.i2 = 0;
286              
287             /*
288             * Divide ...
289             */
290 0 0         if (xdl_split(ha1, off1, lim1, ha2, off2, lim2, kvdf, kvdb,
291             need_min, &spl, xenv) < 0) {
292              
293 0           return -1;
294             }
295              
296             /*
297             * ... et Impera.
298             */
299 0 0         if (xdl_recs_cmp(dd1, off1, spl.i1, dd2, off2, spl.i2,
300 0 0         kvdf, kvdb, spl.min_lo, xenv) < 0 ||
301 0           xdl_recs_cmp(dd1, spl.i1, lim1, dd2, spl.i2, lim2,
302             kvdf, kvdb, spl.min_hi, xenv) < 0) {
303              
304 0           return -1;
305             }
306             }
307              
308 73           return 0;
309             }
310              
311              
312 73           int xdl_do_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp,
313             xdfenv_t *xe) {
314             long ndiags;
315             long *kvd, *kvdf, *kvdb;
316             xdalgoenv_t xenv;
317             diffdata_t dd1, dd2;
318              
319 73 50         if (XDF_DIFF_ALG(xpp->flags) == XDF_PATIENCE_DIFF)
320 0           return xdl_do_patience_diff(mf1, mf2, xpp, xe);
321              
322 73 50         if (XDF_DIFF_ALG(xpp->flags) == XDF_HISTOGRAM_DIFF)
323 0           return xdl_do_histogram_diff(mf1, mf2, xpp, xe);
324              
325 73 50         if (xdl_prepare_env(mf1, mf2, xpp, xe) < 0) {
326              
327 0           return -1;
328             }
329              
330             /*
331             * Allocate and setup K vectors to be used by the differential
332             * algorithm.
333             *
334             * One is to store the forward path and one to store the backward path.
335             */
336 73           ndiags = xe->xdf1.nreff + xe->xdf2.nreff + 3;
337 73 50         if (!(kvd = (long *) xdl_malloc((2 * ndiags + 2) * sizeof(long)))) {
338              
339 0           xdl_free_env(xe);
340 0           return -1;
341             }
342 73           kvdf = kvd;
343 73           kvdb = kvdf + ndiags;
344 73           kvdf += xe->xdf2.nreff + 1;
345 73           kvdb += xe->xdf2.nreff + 1;
346              
347 73           xenv.mxcost = xdl_bogosqrt(ndiags);
348 73 50         if (xenv.mxcost < XDL_MAX_COST_MIN)
349 73           xenv.mxcost = XDL_MAX_COST_MIN;
350 73           xenv.snake_cnt = XDL_SNAKE_CNT;
351 73           xenv.heur_min = XDL_HEUR_MIN_COST;
352              
353 73           dd1.nrec = xe->xdf1.nreff;
354 73           dd1.ha = xe->xdf1.ha;
355 73           dd1.rchg = xe->xdf1.rchg;
356 73           dd1.rindex = xe->xdf1.rindex;
357 73           dd2.nrec = xe->xdf2.nreff;
358 73           dd2.ha = xe->xdf2.ha;
359 73           dd2.rchg = xe->xdf2.rchg;
360 73           dd2.rindex = xe->xdf2.rindex;
361              
362 73 50         if (xdl_recs_cmp(&dd1, 0, dd1.nrec, &dd2, 0, dd2.nrec,
363 73           kvdf, kvdb, (xpp->flags & XDF_NEED_MINIMAL) != 0, &xenv) < 0) {
364              
365 0           xdl_free(kvd);
366 0           xdl_free_env(xe);
367 0           return -1;
368             }
369              
370 73           xdl_free(kvd);
371              
372 73           return 0;
373             }
374              
375              
376 75           static xdchange_t *xdl_add_change(xdchange_t *xscr, long i1, long i2, long chg1, long chg2) {
377             xdchange_t *xch;
378              
379 75 50         if (!(xch = (xdchange_t *) xdl_malloc(sizeof(xdchange_t))))
380 0           return NULL;
381              
382 75           xch->next = xscr;
383 75           xch->i1 = i1;
384 75           xch->i2 = i2;
385 75           xch->chg1 = chg1;
386 75           xch->chg2 = chg2;
387 75           xch->ignore = 0;
388              
389 75           return xch;
390             }
391              
392              
393 30           static int recs_match(xrecord_t *rec1, xrecord_t *rec2)
394             {
395 30           return (rec1->ha == rec2->ha);
396             }
397              
398             /*
399             * If a line is indented more than this, get_indent() just returns this value.
400             * This avoids having to do absurd amounts of work for data that are not
401             * human-readable text, and also ensures that the output of get_indent fits
402             * within an int.
403             */
404             #define MAX_INDENT 200
405              
406             /*
407             * Return the amount of indentation of the specified line, treating TAB as 8
408             * columns. Return -1 if line is empty or contains only whitespace. Clamp the
409             * output value at MAX_INDENT.
410             */
411 0           static int get_indent(xrecord_t *rec)
412             {
413             long i;
414 0           int ret = 0;
415              
416 0 0         for (i = 0; i < rec->size; i++) {
417 0           char c = rec->ptr[i];
418              
419 0 0         if (!XDL_ISSPACE(c))
420 0           return ret;
421 0 0         else if (c == ' ')
422 0           ret += 1;
423 0 0         else if (c == '\t')
424 0           ret += 8 - ret % 8;
425             /* ignore other whitespace characters */
426              
427 0 0         if (ret >= MAX_INDENT)
428 0           return MAX_INDENT;
429             }
430              
431             /* The line contains only whitespace. */
432 0           return -1;
433             }
434              
435             /*
436             * If more than this number of consecutive blank rows are found, just return
437             * this value. This avoids requiring O(N^2) work for pathological cases, and
438             * also ensures that the output of score_split fits in an int.
439             */
440             #define MAX_BLANKS 20
441              
442             /* Characteristics measured about a hypothetical split position. */
443             struct split_measurement {
444             /*
445             * Is the split at the end of the file (aside from any blank lines)?
446             */
447             int end_of_file;
448              
449             /*
450             * How much is the line immediately following the split indented (or -1
451             * if the line is blank):
452             */
453             int indent;
454              
455             /*
456             * How many consecutive lines above the split are blank?
457             */
458             int pre_blank;
459              
460             /*
461             * How much is the nearest non-blank line above the split indented (or
462             * -1 if there is no such line)?
463             */
464             int pre_indent;
465              
466             /*
467             * How many lines after the line following the split are blank?
468             */
469             int post_blank;
470              
471             /*
472             * How much is the nearest non-blank line after the line following the
473             * split indented (or -1 if there is no such line)?
474             */
475             int post_indent;
476             };
477              
478             struct split_score {
479             /* The effective indent of this split (smaller is preferred). */
480             int effective_indent;
481              
482             /* Penalty for this split (smaller is preferred). */
483             int penalty;
484             };
485              
486             /*
487             * Fill m with information about a hypothetical split of xdf above line split.
488             */
489 0           static void measure_split(const xdfile_t *xdf, long split,
490             struct split_measurement *m)
491             {
492             long i;
493              
494 0 0         if (split >= xdf->nrec) {
495 0           m->end_of_file = 1;
496 0           m->indent = -1;
497             } else {
498 0           m->end_of_file = 0;
499 0           m->indent = get_indent(xdf->recs[split]);
500             }
501              
502 0           m->pre_blank = 0;
503 0           m->pre_indent = -1;
504 0 0         for (i = split - 1; i >= 0; i--) {
505 0           m->pre_indent = get_indent(xdf->recs[i]);
506 0 0         if (m->pre_indent != -1)
507 0           break;
508 0           m->pre_blank += 1;
509 0 0         if (m->pre_blank == MAX_BLANKS) {
510 0           m->pre_indent = 0;
511 0           break;
512             }
513             }
514              
515 0           m->post_blank = 0;
516 0           m->post_indent = -1;
517 0 0         for (i = split + 1; i < xdf->nrec; i++) {
518 0           m->post_indent = get_indent(xdf->recs[i]);
519 0 0         if (m->post_indent != -1)
520 0           break;
521 0           m->post_blank += 1;
522 0 0         if (m->post_blank == MAX_BLANKS) {
523 0           m->post_indent = 0;
524 0           break;
525             }
526             }
527 0           }
528              
529             /*
530             * The empirically-determined weight factors used by score_split() below.
531             * Larger values means that the position is a less favorable place to split.
532             *
533             * Note that scores are only ever compared against each other, so multiplying
534             * all of these weight/penalty values by the same factor wouldn't change the
535             * heuristic's behavior. Still, we need to set that arbitrary scale *somehow*.
536             * In practice, these numbers are chosen to be large enough that they can be
537             * adjusted relative to each other with sufficient precision despite using
538             * integer math.
539             */
540              
541             /* Penalty if there are no non-blank lines before the split */
542             #define START_OF_FILE_PENALTY 1
543              
544             /* Penalty if there are no non-blank lines after the split */
545             #define END_OF_FILE_PENALTY 21
546              
547             /* Multiplier for the number of blank lines around the split */
548             #define TOTAL_BLANK_WEIGHT (-30)
549              
550             /* Multiplier for the number of blank lines after the split */
551             #define POST_BLANK_WEIGHT 6
552              
553             /*
554             * Penalties applied if the line is indented more than its predecessor
555             */
556             #define RELATIVE_INDENT_PENALTY (-4)
557             #define RELATIVE_INDENT_WITH_BLANK_PENALTY 10
558              
559             /*
560             * Penalties applied if the line is indented less than both its predecessor and
561             * its successor
562             */
563             #define RELATIVE_OUTDENT_PENALTY 24
564             #define RELATIVE_OUTDENT_WITH_BLANK_PENALTY 17
565              
566             /*
567             * Penalties applied if the line is indented less than its predecessor but not
568             * less than its successor
569             */
570             #define RELATIVE_DEDENT_PENALTY 23
571             #define RELATIVE_DEDENT_WITH_BLANK_PENALTY 17
572              
573             /*
574             * We only consider whether the sum of the effective indents for splits are
575             * less than (-1), equal to (0), or greater than (+1) each other. The resulting
576             * value is multiplied by the following weight and combined with the penalty to
577             * determine the better of two scores.
578             */
579             #define INDENT_WEIGHT 60
580              
581             /*
582             * How far do we slide a hunk at most?
583             */
584             #define INDENT_HEURISTIC_MAX_SLIDING 100
585              
586             /*
587             * Compute a badness score for the hypothetical split whose measurements are
588             * stored in m. The weight factors were determined empirically using the tools
589             * and corpus described in
590             *
591             * https://github.com/mhagger/diff-slider-tools
592             *
593             * Also see that project if you want to improve the weights based on, for
594             * example, a larger or more diverse corpus.
595             */
596 0           static void score_add_split(const struct split_measurement *m, struct split_score *s)
597             {
598             /*
599             * A place to accumulate penalty factors (positive makes this index more
600             * favored):
601             */
602             int post_blank, total_blank, indent, any_blanks;
603              
604 0 0         if (m->pre_indent == -1 && m->pre_blank == 0)
    0          
605 0           s->penalty += START_OF_FILE_PENALTY;
606              
607 0 0         if (m->end_of_file)
608 0           s->penalty += END_OF_FILE_PENALTY;
609              
610             /*
611             * Set post_blank to the number of blank lines following the split,
612             * including the line immediately after the split:
613             */
614 0 0         post_blank = (m->indent == -1) ? 1 + m->post_blank : 0;
615 0           total_blank = m->pre_blank + post_blank;
616              
617             /* Penalties based on nearby blank lines: */
618 0           s->penalty += TOTAL_BLANK_WEIGHT * total_blank;
619 0           s->penalty += POST_BLANK_WEIGHT * post_blank;
620              
621 0 0         if (m->indent != -1)
622 0           indent = m->indent;
623             else
624 0           indent = m->post_indent;
625              
626 0           any_blanks = (total_blank != 0);
627              
628             /* Note that the effective indent is -1 at the end of the file: */
629 0           s->effective_indent += indent;
630              
631 0 0         if (indent == -1) {
632             /* No additional adjustments needed. */
633 0 0         } else if (m->pre_indent == -1) {
634             /* No additional adjustments needed. */
635 0 0         } else if (indent > m->pre_indent) {
636             /*
637             * The line is indented more than its predecessor.
638             */
639 0           s->penalty += any_blanks ?
640 0 0         RELATIVE_INDENT_WITH_BLANK_PENALTY :
641             RELATIVE_INDENT_PENALTY;
642 0 0         } else if (indent == m->pre_indent) {
643             /*
644             * The line has the same indentation level as its predecessor.
645             * No additional adjustments needed.
646             */
647             } else {
648             /*
649             * The line is indented less than its predecessor. It could be
650             * the block terminator of the previous block, but it could
651             * also be the start of a new block (e.g., an "else" block, or
652             * maybe the previous block didn't have a block terminator).
653             * Try to distinguish those cases based on what comes next:
654             */
655 0 0         if (m->post_indent != -1 && m->post_indent > indent) {
    0          
656             /*
657             * The following line is indented more. So it is likely
658             * that this line is the start of a block.
659             */
660 0           s->penalty += any_blanks ?
661 0 0         RELATIVE_OUTDENT_WITH_BLANK_PENALTY :
662             RELATIVE_OUTDENT_PENALTY;
663             } else {
664             /*
665             * That was probably the end of a block.
666             */
667 0           s->penalty += any_blanks ?
668 0 0         RELATIVE_DEDENT_WITH_BLANK_PENALTY :
669             RELATIVE_DEDENT_PENALTY;
670             }
671             }
672 0           }
673              
674 0           static int score_cmp(struct split_score *s1, struct split_score *s2)
675             {
676             /* -1 if s1.effective_indent < s2->effective_indent, etc. */
677 0           int cmp_indents = ((s1->effective_indent > s2->effective_indent) -
678 0           (s1->effective_indent < s2->effective_indent));
679              
680 0           return INDENT_WEIGHT * cmp_indents + (s1->penalty - s2->penalty);
681             }
682              
683             /*
684             * Represent a group of changed lines in an xdfile_t (i.e., a contiguous group
685             * of lines that was inserted or deleted from the corresponding version of the
686             * file). We consider there to be such a group at the beginning of the file, at
687             * the end of the file, and between any two unchanged lines, though most such
688             * groups will usually be empty.
689             *
690             * If the first line in a group is equal to the line following the group, then
691             * the group can be slid down. Similarly, if the last line in a group is equal
692             * to the line preceding the group, then the group can be slid up. See
693             * group_slide_down() and group_slide_up().
694             *
695             * Note that loops that are testing for changed lines in xdf->rchg do not need
696             * index bounding since the array is prepared with a zero at position -1 and N.
697             */
698             struct xdlgroup {
699             /*
700             * The index of the first changed line in the group, or the index of
701             * the unchanged line above which the (empty) group is located.
702             */
703             long start;
704              
705             /*
706             * The index of the first unchanged line after the group. For an empty
707             * group, end is equal to start.
708             */
709             long end;
710             };
711              
712             /*
713             * Initialize g to point at the first group in xdf.
714             */
715 292           static void group_init(xdfile_t *xdf, struct xdlgroup *g)
716             {
717 292           g->start = g->end = 0;
718 516 100         while (xdf->rchg[g->end])
719 224           g->end++;
720 292           }
721              
722             /*
723             * Move g to describe the next (possibly empty) group in xdf and return 0. If g
724             * is already at the end of the file, do nothing and return -1.
725             */
726 366           static inline int group_next(xdfile_t *xdf, struct xdlgroup *g)
727             {
728 366 100         if (g->end == xdf->nrec)
729 292           return -1;
730              
731 74           g->start = g->end + 1;
732 111 100         for (g->end = g->start; xdf->rchg[g->end]; g->end++)
733             ;
734              
735 74           return 0;
736             }
737              
738             /*
739             * Move g to describe the previous (possibly empty) group in xdf and return 0.
740             * If g is already at the beginning of the file, do nothing and return -1.
741             */
742 6           static inline int group_previous(xdfile_t *xdf, struct xdlgroup *g)
743             {
744 6 50         if (g->start == 0)
745 0           return -1;
746              
747 6           g->end = g->start - 1;
748 9 100         for (g->start = g->end; xdf->rchg[g->start - 1]; g->start--)
749             ;
750              
751 6           return 0;
752             }
753              
754             /*
755             * If g can be slid toward the end of the file, do so, and if it bumps into a
756             * following group, expand this group to include it. Return 0 on success or -1
757             * if g cannot be slid down.
758             */
759 125           static int group_slide_down(xdfile_t *xdf, struct xdlgroup *g)
760             {
761 138           if (g->end < xdf->nrec &&
762 13           recs_match(xdf->recs[g->start], xdf->recs[g->end])) {
763 6           xdf->rchg[g->start++] = 0;
764 6           xdf->rchg[g->end++] = 1;
765              
766 6 50         while (xdf->rchg[g->end])
767 0           g->end++;
768              
769 6           return 0;
770             } else {
771 119           return -1;
772             }
773             }
774              
775             /*
776             * If g can be slid toward the beginning of the file, do so, and if it bumps
777             * into a previous group, expand this group to include it. Return 0 on success
778             * or -1 if g cannot be slid up.
779             */
780 125           static int group_slide_up(xdfile_t *xdf, struct xdlgroup *g)
781             {
782 142           if (g->start > 0 &&
783 17           recs_match(xdf->recs[g->start - 1], xdf->recs[g->end - 1])) {
784 6           xdf->rchg[--g->start] = 1;
785 6           xdf->rchg[--g->end] = 0;
786              
787 6 50         while (xdf->rchg[g->start - 1])
788 0           g->start--;
789              
790 6           return 0;
791             } else {
792 119           return -1;
793             }
794             }
795              
796             /*
797             * Move back and forward change groups for a consistent and pretty diff output.
798             * This also helps in finding joinable change groups and reducing the diff
799             * size.
800             */
801 146           int xdl_change_compact(xdfile_t *xdf, xdfile_t *xdfo, long flags) {
802             struct xdlgroup g, go;
803             long earliest_end, end_matching_other;
804             long groupsize;
805              
806 146           group_init(xdf, &g);
807 146           group_init(xdfo, &go);
808              
809             while (1) {
810             /*
811             * If the group is empty in the to-be-compacted file, skip it:
812             */
813 180 100         if (g.end == g.start)
814 61           goto next;
815              
816             /*
817             * Now shift the change up and then down as far as possible in
818             * each direction. If it bumps into any other changes, merge
819             * them.
820             */
821             do {
822 119           groupsize = g.end - g.start;
823              
824             /*
825             * Keep track of the last "end" index that causes this
826             * group to align with a group of changed lines in the
827             * other file. -1 indicates that we haven't found such
828             * a match yet:
829             */
830 119           end_matching_other = -1;
831              
832             /* Shift the group backward as much as possible: */
833 123 100         while (!group_slide_up(xdf, &g))
834 4           if (group_previous(xdfo, &go))
835             XDL_BUG("group sync broken sliding up");
836              
837             /*
838             * This is this highest that this group can be shifted.
839             * Record its end index:
840             */
841 119           earliest_end = g.end;
842              
843 119 100         if (go.end > go.start)
844 87           end_matching_other = g.end;
845              
846             /* Now shift the group forward as far as possible: */
847             while (1) {
848 125 100         if (group_slide_down(xdf, &g))
849 119           break;
850 6           if (group_next(xdfo, &go))
851             XDL_BUG("group sync broken sliding down");
852              
853 6 100         if (go.end > go.start)
854 3           end_matching_other = g.end;
855 6           }
856 119 50         } while (groupsize != g.end - g.start);
857              
858             /*
859             * If the group can be shifted, then we can possibly use this
860             * freedom to produce a more intuitive diff.
861             *
862             * The group is currently shifted as far down as possible, so
863             * the heuristics below only have to handle upwards shifts.
864             */
865              
866 119 100         if (g.end == earliest_end) {
867             /* no shifting was possible */
868 2 50         } else if (end_matching_other != -1) {
869             /*
870             * Move the possibly merged group of changes back to
871             * line up with the last group of changes from the
872             * other file that it can align with.
873             */
874 4 100         while (go.end == go.start) {
875 2           if (group_slide_up(xdf, &g))
876             XDL_BUG("match disappeared");
877 2           if (group_previous(xdfo, &go))
878             XDL_BUG("group sync broken sliding to match");
879             }
880 0 0         } else if (flags & XDF_INDENT_HEURISTIC) {
881             /*
882             * Indent heuristic: a group of pure add/delete lines
883             * implies two splits, one between the end of the
884             * "before" context and the start of the group, and
885             * another between the end of the group and the
886             * beginning of the "after" context. Some splits are
887             * aesthetically better and some are worse. We compute
888             * a badness "score" for each split, and add the scores
889             * for the two splits to define a "score" for each
890             * position that the group can be shifted to. Then we
891             * pick the shift with the lowest score.
892             */
893 0           long shift, best_shift = -1;
894             struct split_score best_score;
895              
896 0           shift = earliest_end;
897 0 0         if (g.end - groupsize - 1 > shift)
898 0           shift = g.end - groupsize - 1;
899 0 0         if (g.end - INDENT_HEURISTIC_MAX_SLIDING > shift)
900 0           shift = g.end - INDENT_HEURISTIC_MAX_SLIDING;
901 0 0         for (; shift <= g.end; shift++) {
902             struct split_measurement m;
903 0           struct split_score score = {0, 0};
904              
905 0           measure_split(xdf, shift, &m);
906 0           score_add_split(&m, &score);
907 0           measure_split(xdf, shift - groupsize, &m);
908 0           score_add_split(&m, &score);
909 0           if (best_shift == -1 ||
910 0           score_cmp(&score, &best_score) <= 0) {
911 0           best_score.effective_indent = score.effective_indent;
912 0           best_score.penalty = score.penalty;
913 0           best_shift = shift;
914             }
915             }
916              
917 0 0         while (g.end > best_shift) {
918 0           if (group_slide_up(xdf, &g))
919             XDL_BUG("best shift unreached");
920 0           if (group_previous(xdfo, &go))
921             XDL_BUG("group sync broken sliding to blank line");
922             }
923             }
924              
925             next:
926             /* Move past the just-processed group: */
927 180 100         if (group_next(xdf, &g))
928 146           break;
929 34           if (group_next(xdfo, &go))
930             XDL_BUG("group sync broken moving to next group");
931 34           }
932              
933 146           if (!group_next(xdfo, &go))
934             XDL_BUG("group sync broken at end of file");
935              
936 146           return 0;
937             }
938              
939              
940 73           int xdl_build_script(xdfenv_t *xe, xdchange_t **xscr) {
941 73           xdchange_t *cscr = NULL, *xch;
942 73           char *rchg1 = xe->xdf1.rchg, *rchg2 = xe->xdf2.rchg;
943             long i1, i2, l1, l2;
944              
945             /*
946             * Trivial. Collects "groups" of changes and creates an edit script.
947             */
948 163 100         for (i1 = xe->xdf1.nrec, i2 = xe->xdf2.nrec; i1 >= 0 || i2 >= 0; i1--, i2--)
    50          
949 90 100         if (rchg1[i1 - 1] || rchg2[i2 - 1]) {
    100          
950 124 100         for (l1 = i1; rchg1[i1 - 1]; i1--);
951 155 100         for (l2 = i2; rchg2[i2 - 1]; i2--);
952              
953 75 50         if (!(xch = xdl_add_change(cscr, i1, i2, l1 - i1, l2 - i2))) {
954 0           xdl_free_script(cscr);
955 0           return -1;
956             }
957 75           cscr = xch;
958             }
959              
960 73           *xscr = cscr;
961              
962 73           return 0;
963             }
964              
965              
966 73           void xdl_free_script(xdchange_t *xscr) {
967             xdchange_t *xch;
968              
969 148 100         while ((xch = xscr) != NULL) {
970 75           xscr = xscr->next;
971 75           xdl_free(xch);
972             }
973 73           }
974              
975 2           static int xdl_call_hunk_func(xdfenv_t *xe, xdchange_t *xscr, xdemitcb_t *ecb,
976             xdemitconf_t const *xecfg)
977             {
978             xdchange_t *xch, *xche;
979              
980 4 100         for (xch = xscr; xch; xch = xche->next) {
981 2           xche = xdl_get_hunk(&xch, xecfg);
982 2 50         if (!xch)
983 0           break;
984 2 50         if (xecfg->hunk_func(xch->i1, xche->i1 + xche->chg1 - xch->i1,
985 4           xch->i2, xche->i2 + xche->chg2 - xch->i2,
986             ecb->priv) < 0)
987 0           return -1;
988             }
989 2           return 0;
990             }
991              
992 0           static void xdl_mark_ignorable_lines(xdchange_t *xscr, xdfenv_t *xe, long flags)
993             {
994             xdchange_t *xch;
995              
996 0 0         for (xch = xscr; xch; xch = xch->next) {
997 0           int ignore = 1;
998             xrecord_t **rec;
999             long i;
1000              
1001 0           rec = &xe->xdf1.recs[xch->i1];
1002 0 0         for (i = 0; i < xch->chg1 && ignore; i++)
    0          
1003 0           ignore = xdl_blankline(rec[i]->ptr, rec[i]->size, flags);
1004              
1005 0           rec = &xe->xdf2.recs[xch->i2];
1006 0 0         for (i = 0; i < xch->chg2 && ignore; i++)
    0          
1007 0           ignore = xdl_blankline(rec[i]->ptr, rec[i]->size, flags);
1008              
1009 0           xch->ignore = ignore;
1010             }
1011 0           }
1012              
1013 0           static int record_matches_regex(xrecord_t *rec, xpparam_t const *xpp) {
1014             xdl_regmatch_t regmatch;
1015             int i;
1016              
1017 0 0         for (i = 0; i < xpp->ignore_regex_nr; i++)
1018 0 0         if (!xdl_regexec_buf(xpp->ignore_regex[i], rec->ptr, rec->size, 1,
1019             ®match, 0))
1020 0           return 1;
1021              
1022 0           return 0;
1023             }
1024              
1025 0           static void xdl_mark_ignorable_regex(xdchange_t *xscr, const xdfenv_t *xe,
1026             xpparam_t const *xpp)
1027             {
1028             xdchange_t *xch;
1029              
1030 0 0         for (xch = xscr; xch; xch = xch->next) {
1031             xrecord_t **rec;
1032 0           int ignore = 1;
1033             long i;
1034              
1035             /*
1036             * Do not override --ignore-blank-lines.
1037             */
1038 0 0         if (xch->ignore)
1039 0           continue;
1040              
1041 0           rec = &xe->xdf1.recs[xch->i1];
1042 0 0         for (i = 0; i < xch->chg1 && ignore; i++)
    0          
1043 0           ignore = record_matches_regex(rec[i], xpp);
1044              
1045 0           rec = &xe->xdf2.recs[xch->i2];
1046 0 0         for (i = 0; i < xch->chg2 && ignore; i++)
    0          
1047 0           ignore = record_matches_regex(rec[i], xpp);
1048              
1049 0           xch->ignore = ignore;
1050             }
1051 0           }
1052              
1053 40           int xdl_diff(mmfile_t *mf1, mmfile_t *mf2, xpparam_t const *xpp,
1054             xdemitconf_t const *xecfg, xdemitcb_t *ecb) {
1055             xdchange_t *xscr;
1056             xdfenv_t xe;
1057 40 100         emit_func_t ef = xecfg->hunk_func ? xdl_call_hunk_func : xdl_emit_diff;
1058              
1059 40 50         if (xdl_do_diff(mf1, mf2, xpp, &xe) < 0) {
1060              
1061 0           return -1;
1062             }
1063 80           if (xdl_change_compact(&xe.xdf1, &xe.xdf2, xpp->flags) < 0 ||
1064 80 50         xdl_change_compact(&xe.xdf2, &xe.xdf1, xpp->flags) < 0 ||
1065 40           xdl_build_script(&xe, &xscr) < 0) {
1066              
1067 0           xdl_free_env(&xe);
1068 0           return -1;
1069             }
1070 40 50         if (xscr) {
1071 40 50         if (xpp->flags & XDF_IGNORE_BLANK_LINES)
1072 0           xdl_mark_ignorable_lines(xscr, &xe, xpp->flags);
1073              
1074 40 50         if (xpp->ignore_regex)
1075 0           xdl_mark_ignorable_regex(xscr, &xe, xpp);
1076              
1077 40 50         if (ef(&xe, xscr, ecb, xecfg) < 0) {
1078              
1079 0           xdl_free_script(xscr);
1080 0           xdl_free_env(&xe);
1081 0           return -1;
1082             }
1083 40           xdl_free_script(xscr);
1084             }
1085 40           xdl_free_env(&xe);
1086              
1087 40           return 0;
1088             }