blob: c1463fdf186472fb4fe3c55de417c757746839c0 [file] [log] [blame]
Jonathon7c7a4e62025-01-12 09:58:00 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10#include "vim.h"
11
12#define LN_MAX_BUFS 8
13#define LN_DECISION_MAX 255 // pow(2, LN_MAX_BUFS(8)) - 1 = 255
14
15// struct for running the diff linematch algorithm
16typedef struct diffcmppath_S diffcmppath_T;
17struct diffcmppath_S
18{
19 // to keep track of the total score of this path
20 int df_lev_score;
21 size_t df_path_n; // current index of this path
22 int df_choice_mem[LN_DECISION_MAX + 1];
23 int df_choice[LN_DECISION_MAX];
24 // to keep track of this path traveled
25 diffcmppath_T *df_decision[LN_DECISION_MAX];
26 size_t df_optimal_choice;
27};
28
29static int matching_chars(const mmfile_t *m1, const mmfile_t *m2);
30static size_t unwrap_indexes(const int *values, const int *diff_len, const size_t ndiffs);
31static size_t test_charmatch_paths(diffcmppath_T *node, int lastdecision);
32
33 static size_t
34line_len(const mmfile_t *m)
35{
36 char *s = m->ptr;
37 size_t n = (size_t)m->size;
38 char *end;
39
40 end = vim_strnchr(s, &n, '\n');
41 if (end)
42 return (size_t)(end - s);
43
44 return (size_t)m->size;
45}
46
47#define MATCH_CHAR_MAX_LEN 800
48
49/// Same as matching_chars but ignore whitespace
50///
51/// @param s1
52/// @param s2
53 static int
54matching_chars_iwhite(const mmfile_t *s1, const mmfile_t *s2)
55{
56 // the newly processed strings that will be compared
57 // delete the white space characters
58 mmfile_t sp[2];
59 char p[2][MATCH_CHAR_MAX_LEN];
60
61 for (int k = 0; k < 2; k++)
62 {
63 const mmfile_t *s = k == 0 ? s1 : s2;
64 size_t pi = 0;
65 size_t slen = MIN(MATCH_CHAR_MAX_LEN - 1, line_len(s));
66
67 for (size_t i = 0; i <= slen; i++)
68 {
69 char e = s->ptr[i];
70
71 if (e != ' ' && e != '\t')
72 {
73 p[k][pi] = e;
74 pi++;
75 }
76 }
77
78 sp[k].ptr = p[k];
79 sp[k].size = (int)pi;
80 }
81
82 return matching_chars(&sp[0], &sp[1]);
83}
84
85/// Return matching characters between "s1" and "s2" whilst respecting sequence
86/// order.
87/// Consider the case of two strings 'AAACCC' and 'CCCAAA', the
88/// return value from this function will be 3, either to match
89/// the 3 C's, or the 3 A's.
90///
91/// Examples:
92/// matching_chars("aabc", "acba") -> 2 // 'a' and 'b' in common
93/// matching_chars("123hello567", "he123ll567o") -> 8 // '123', 'll' and '567' in common
94/// matching_chars("abcdefg", "gfedcba") -> 1 // all characters in common,
95/// // but only at most 1 in sequence
96///
97/// @param m1
98/// @param m2
99 static int
100matching_chars(const mmfile_t *m1, const mmfile_t *m2)
101{
102 size_t s1len = MIN(MATCH_CHAR_MAX_LEN - 1, line_len(m1));
103 size_t s2len = MIN(MATCH_CHAR_MAX_LEN - 1, line_len(m2));
104 char *s1 = m1->ptr;
105 char *s2 = m2->ptr;
106 int matrix[2][MATCH_CHAR_MAX_LEN] = { 0 };
107 int icur = 1; // save space by storing only two rows for i axis
108
109 for (size_t i = 0; i < s1len; i++)
110 {
111 icur = (icur == 1 ? 0 : 1);
112 int *e1 = matrix[icur];
113 int *e2 = matrix[!icur];
114
115 for (size_t j = 0; j < s2len; j++)
116 {
117 // skip char in s1
118 if (e2[j + 1] > e1[j + 1])
119 e1[j + 1] = e2[j + 1];
120 // skip char in s2
121 if (e1[j] > e1[j + 1])
122 e1[j + 1] = e1[j];
123 // compare char in s1 and s2
124 if ((s1[i] == s2[j]) && (e2[j] + 1) > e1[j + 1])
125 e1[j + 1] = e2[j] + 1;
126 }
127 }
128
129 return matrix[icur][s2len];
130}
131
132/// count the matching characters between a variable number of strings "sp"
133/// mark the strings that have already been compared to extract them later
134/// without re-running the character match counting.
135/// @param sp
136/// @param fomvals
137/// @param n
138 static int
139count_n_matched_chars(mmfile_t **sp, const size_t n, int iwhite)
140{
141 int matched_chars = 0;
142 int matched = 0;
143
144 for (size_t i = 0; i < n; i++)
145 {
146 for (size_t j = i + 1; j < n; j++)
147 {
148 if (sp[i]->ptr != NULL && sp[j]->ptr != NULL)
149 {
150 matched++;
151 // TODO(lewis6991): handle whitespace ignoring higher up in the
152 // stack
153 matched_chars += iwhite ? matching_chars_iwhite(sp[i], sp[j])
154 : matching_chars(sp[i], sp[j]);
155 }
156 }
157 }
158
159 // prioritize a match of 3 (or more lines) equally to a match of 2 lines
160 if (matched >= 2)
161 {
162 matched_chars *= 2;
163 matched_chars /= matched;
164 }
165
166 return matched_chars;
167}
168
169 static mmfile_t
170fastforward_buf_to_lnum(mmfile_t s, linenr_T lnum)
171{
172 for (int i = 0; i < lnum - 1; i++)
173 {
174 size_t n = (size_t)s.size;
175
176 s.ptr = vim_strnchr(s.ptr, &n, '\n');
177 s.size = (int)n;
178 if (!s.ptr)
179 break;
180 s.ptr++;
181 s.size--;
182 }
183
184 return s;
185}
186
187/// try all the different ways to compare these lines and use the one that
188/// results in the most matching characters
189/// @param df_iters
190/// @param paths
191/// @param npaths
192/// @param path_idx
193/// @param choice
194/// @param diffcmppath
195/// @param diff_len
196/// @param ndiffs
197/// @param diff_blk
198 static void
199try_possible_paths(
200 const int *df_iters,
201 const size_t *paths,
202 const int npaths,
203 const int path_idx,
204 int *choice,
205 diffcmppath_T *diffcmppath,
206 const int *diff_len,
207 const size_t ndiffs,
208 const mmfile_t **diff_blk,
209 int iwhite)
210{
211 if (path_idx == npaths)
212 {
213 if ((*choice) > 0)
214 {
215 int from_vals[LN_MAX_BUFS] = { 0 };
216 const int *to_vals = df_iters;
217
218 mmfile_t mm[LN_MAX_BUFS]; // stack memory for current_lines
219 mmfile_t *current_lines[LN_MAX_BUFS];
220 for (size_t k = 0; k < ndiffs; k++)
221 {
222 from_vals[k] = df_iters[k];
223 // get the index at all of the places
224 if ((*choice) & (1 << k))
225 {
226 from_vals[k]--;
227 mm[k] = fastforward_buf_to_lnum(*diff_blk[k], df_iters[k]);
228 }
229 else
230 CLEAR_FIELD(mm[k]);
231 current_lines[k] = &mm[k];
232 }
233 size_t unwrapped_idx_from = unwrap_indexes(from_vals, diff_len, ndiffs);
234 size_t unwrapped_idx_to = unwrap_indexes(to_vals, diff_len, ndiffs);
235 int matched_chars = count_n_matched_chars(current_lines, ndiffs, iwhite);
236 int score = diffcmppath[unwrapped_idx_from].df_lev_score + matched_chars;
237
238 if (score > diffcmppath[unwrapped_idx_to].df_lev_score)
239 {
240 diffcmppath[unwrapped_idx_to].df_path_n = 1;
241 diffcmppath[unwrapped_idx_to].df_decision[0] =
242 &diffcmppath[unwrapped_idx_from];
243 diffcmppath[unwrapped_idx_to].df_choice[0] = *choice;
244 diffcmppath[unwrapped_idx_to].df_lev_score = score;
245 }
246 else if (score == diffcmppath[unwrapped_idx_to].df_lev_score)
247 {
248 size_t k = diffcmppath[unwrapped_idx_to].df_path_n++;
249 diffcmppath[unwrapped_idx_to].df_decision[k] =
250 &diffcmppath[unwrapped_idx_from];
251 diffcmppath[unwrapped_idx_to].df_choice[k] = *choice;
252 }
253 }
254 return;
255 }
256
257 size_t bit_place = paths[path_idx];
258 *(choice) |= (1 << bit_place); // set it to 1
259 try_possible_paths(df_iters, paths, npaths, path_idx + 1, choice,
260 diffcmppath, diff_len, ndiffs, diff_blk, iwhite);
261 *(choice) &= ~(1 << bit_place); // set it to 0
262 try_possible_paths(df_iters, paths, npaths, path_idx + 1, choice,
263 diffcmppath, diff_len, ndiffs, diff_blk, iwhite);
264}
265
266/// unwrap indexes to access n dimensional tensor
267/// @param values
268/// @param diff_len
269/// @param ndiffs
270 static size_t
271unwrap_indexes(const int *values, const int *diff_len, const size_t ndiffs)
272{
273 size_t num_unwrap_scalar = 1;
274
275 for (size_t k = 0; k < ndiffs; k++)
276 num_unwrap_scalar *= (size_t)diff_len[k] + 1;
277
278 size_t path_idx = 0;
279 for (size_t k = 0; k < ndiffs; k++)
280 {
281 num_unwrap_scalar /= (size_t)diff_len[k] + 1;
282
283 int n = values[k];
284 path_idx += num_unwrap_scalar * (size_t)n;
285 }
286
287 return path_idx;
288}
289
290/// populate the values of the linematch algorithm tensor, and find the best
291/// decision for how to compare the relevant lines from each of the buffers at
292/// each point in the tensor
293/// @param df_iters
294/// @param ch_dim
295/// @param diffcmppath
296/// @param diff_len
297/// @param ndiffs
298/// @param diff_blk
299 static void
300populate_tensor(
301 int *df_iters,
302 const size_t ch_dim,
303 diffcmppath_T *diffcmppath,
304 const int *diff_len,
305 const size_t ndiffs,
306 const mmfile_t **diff_blk,
307 int iwhite)
308{
309 if (ch_dim == ndiffs)
310 {
311 int npaths = 0;
312 size_t paths[LN_MAX_BUFS];
313
314 for (size_t j = 0; j < ndiffs; j++)
315 {
316 if (df_iters[j] > 0)
317 {
318 paths[npaths] = j;
319 npaths++;
320 }
321 }
322
323 int choice = 0;
324 size_t unwrapper_idx_to = unwrap_indexes(df_iters, diff_len, ndiffs);
325
326 diffcmppath[unwrapper_idx_to].df_lev_score = -1;
327 try_possible_paths(df_iters, paths, npaths, 0, &choice, diffcmppath,
328 diff_len, ndiffs, diff_blk, iwhite);
329 return;
330 }
331
332 for (int i = 0; i <= diff_len[ch_dim]; i++)
333 {
334 df_iters[ch_dim] = i;
335 populate_tensor(df_iters, ch_dim + 1, diffcmppath, diff_len,
336 ndiffs, diff_blk, iwhite);
337 }
338}
339
340/// algorithm to find an optimal alignment of lines of a diff block with 2 or
341/// more files. The algorithm is generalized to work for any number of files
342/// which corresponds to another dimension added to the tensor used in the
343/// algorithm
344///
345/// for questions and information about the linematch algorithm please contact
346/// Jonathon White (jonathonwhite@protonmail.com)
347///
348/// for explanation, a summary of the algorithm in 3 dimensions (3 files
349/// compared) follows
350///
351/// The 3d case (for 3 buffers) of the algorithm implemented when diffopt
352/// 'linematch' is enabled. The algorithm constructs a 3d tensor to
353/// compare a diff between 3 buffers. The dimensions of the tensor are
354/// the length of the diff in each buffer plus 1 A path is constructed by
355/// moving from one edge of the cube/3d tensor to the opposite edge.
356/// Motions from one cell of the cube to the next represent decisions. In
357/// a 3d cube, there are a total of 7 decisions that can be made,
358/// represented by the enum df_path3_choice which is defined in
359/// buffer_defs.h a comparison of buffer 0 and 1 represents a motion
360/// toward the opposite edge of the cube with components along the 0 and
361/// 1 axes. a comparison of buffer 0, 1, and 2 represents a motion
362/// toward the opposite edge of the cube with components along the 0, 1,
363/// and 2 axes. A skip of buffer 0 represents a motion along only the 0
364/// axis. For each action, a point value is awarded, and the path is
365/// saved for reference later, if it is found to have been the optimal
366/// path. The optimal path has the highest score. The score is
367/// calculated as the summation of the total characters matching between
368/// all of the lines which were compared. The structure of the algorithm
369/// is that of a dynamic programming problem. We can calculate a point
370/// i,j,k in the cube as a function of i-1, j-1, and k-1. To find the
371/// score and path at point i,j,k, we must determine which path we want
372/// to use, this is done by looking at the possibilities and choosing
373/// the one which results in the local highest score. The total highest
374/// scored path is, then in the end represented by the cell in the
375/// opposite corner from the start location. The entire algorithm
376/// consists of populating the 3d cube with the optimal paths from which
377/// it may have came.
378///
379/// Optimizations:
380/// As the function to calculate the cell of a tensor at point i,j,k is a
381/// function of the cells at i-1, j-1, k-1, the whole tensor doesn't need
382/// to be stored in memory at once. In the case of the 3d cube, only two
383/// slices (along k and j axis) are stored in memory. For the 2d matrix
384/// (for 2 files), only two rows are stored at a time. The next/previous
385/// slice (or row) is always calculated from the other, and they alternate
386/// at each iteration.
387/// In the 3d case, 3 arrays are populated to memorize the score (matched
388/// characters) of the 3 buffers, so a redundant calculation of the
389/// scores does not occur
390/// @param diff_blk
391/// @param diff_len
392/// @param ndiffs
393/// @param [out] [allocated] decisions
394/// @return the length of decisions
395 size_t
396linematch_nbuffers(
397 const mmfile_t **diff_blk,
398 const int *diff_len,
399 const size_t ndiffs,
400 int **decisions,
401 int iwhite)
402{
403 assert(ndiffs <= LN_MAX_BUFS);
404
405 size_t memsize = 1;
406 size_t memsize_decisions = 0;
407 for (size_t i = 0; i < ndiffs; i++)
408 {
409 assert(diff_len[i] >= 0);
410 memsize *= (size_t)(diff_len[i] + 1);
411 memsize_decisions += (size_t)diff_len[i];
412 }
413
414 // create the flattened path matrix
415 diffcmppath_T *diffcmppath = lalloc(sizeof(diffcmppath_T) * memsize, TRUE);
416 // allocate memory here
417 for (size_t i = 0; i < memsize; i++)
418 {
419 diffcmppath[i].df_lev_score = 0;
420 diffcmppath[i].df_path_n = 0;
421 for (size_t j = 0; j < (size_t)pow(2, (double)ndiffs); j++)
422 diffcmppath[i].df_choice_mem[j] = -1;
423 }
424
425 // memory for avoiding repetitive calculations of score
426 int df_iters[LN_MAX_BUFS];
427 populate_tensor(df_iters, 0, diffcmppath, diff_len, ndiffs, diff_blk,
428 iwhite);
429
430 const size_t u = unwrap_indexes(diff_len, diff_len, ndiffs);
431 diffcmppath_T *startNode = &diffcmppath[u];
432
433 *decisions = lalloc(sizeof(int) * memsize_decisions, TRUE);
434 size_t n_optimal = 0;
435 test_charmatch_paths(startNode, 0);
436 while (startNode->df_path_n > 0)
437 {
438 size_t j = startNode->df_optimal_choice;
439 (*decisions)[n_optimal++] = startNode->df_choice[j];
440 startNode = startNode->df_decision[j];
441 }
442 // reverse array
443 for (size_t i = 0; i < (n_optimal / 2); i++)
444 {
445 int tmp = (*decisions)[i];
446 (*decisions)[i] = (*decisions)[n_optimal - 1 - i];
447 (*decisions)[n_optimal - 1 - i] = tmp;
448 }
449
450 vim_free(diffcmppath);
451
452 return n_optimal;
453}
454
455// returns the minimum amount of path changes from start to end
456 static size_t
457test_charmatch_paths(diffcmppath_T *node, int lastdecision)
458{
459 // memoization
460 if (node->df_choice_mem[lastdecision] == -1)
461 {
462 if (node->df_path_n == 0)
463 // we have reached the end of the tree
464 node->df_choice_mem[lastdecision] = 0;
465 else
466 {
467 // the minimum amount of turns required to reach the end
468 size_t minimum_turns = SIZE_MAX;
469 for (size_t i = 0; i < node->df_path_n; i++)
470 {
471 // recurse
472 size_t t = test_charmatch_paths(node->df_decision[i],
473 node->df_choice[i]) +
474 (lastdecision != node->df_choice[i] ? 1 : 0);
475 if (t < minimum_turns)
476 {
477 node->df_optimal_choice = i;
478 minimum_turns = t;
479 }
480 }
481 node->df_choice_mem[lastdecision] = (int)minimum_turns;
482 }
483 }
484
485 return (size_t)node->df_choice_mem[lastdecision];
486}