• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rust-lang / annotate-snippets-rs / 18656330633

20 Oct 2025 03:06PM UTC coverage: 89.848% (-0.1%) from 89.951%
18656330633

push

github

web-flow
Merge pull request #323 from Muscraft/fix-suggestion-max-line-num

fix: Properly calculate the max line num for suggestions

237 of 271 new or added lines in 3 files covered. (87.45%)

1 existing line in 1 file now uncovered.

1478 of 1645 relevant lines covered (89.85%)

4.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.48
/src/renderer/source_map.rs
1
use crate::renderer::{char_width, num_overlap, LineAnnotation, LineAnnotationType};
2
use crate::{Annotation, AnnotationKind, Patch};
3
use std::borrow::Cow;
4
use std::cmp::{max, min};
5
use std::ops::Range;
6

7
#[derive(Debug)]
8
pub(crate) struct SourceMap<'a> {
9
    lines: Vec<LineInfo<'a>>,
10
    pub(crate) source: &'a str,
11
}
12

13
impl<'a> SourceMap<'a> {
14
    pub(crate) fn new(source: &'a str, line_start: usize) -> Self {
8✔
15
        // Empty sources do have a "line", but it is empty, so we need to add
16
        // a line with an empty string to the source map.
17
        if source.is_empty() {
5✔
18
            return Self {
2✔
19
                lines: vec![LineInfo {
4✔
20
                    line: "",
×
21
                    line_index: line_start,
×
22
                    start_byte: 0,
×
23
                    end_byte: 0,
×
24
                    end_line_size: 0,
×
25
                }],
26
                source,
×
27
            };
28
        }
29

30
        let mut current_index = 0;
6✔
31

32
        let mut mapping = vec![];
6✔
33
        for (idx, (line, end_line)) in CursorLines::new(source).enumerate() {
16✔
34
            let line_length = line.len();
7✔
35
            let line_range = current_index..current_index + line_length;
4✔
36
            let end_line_size = end_line.len();
12✔
37

38
            mapping.push(LineInfo {
4✔
39
                line,
×
40
                line_index: line_start + idx,
4✔
41
                start_byte: line_range.start,
×
42
                end_byte: line_range.end + end_line_size,
8✔
43
                end_line_size,
×
44
            });
45

46
            current_index += line_length + end_line_size;
8✔
47
        }
48
        Self {
49
            lines: mapping,
50
            source,
51
        }
52
    }
53

54
    pub(crate) fn get_line(&self, idx: usize) -> Option<&'a str> {
4✔
55
        self.lines
4✔
56
            .iter()
57
            .find(|l| l.line_index == idx)
12✔
58
            .map(|info| info.line)
12✔
59
    }
60

61
    pub(crate) fn span_to_locations(&self, span: Range<usize>) -> (Loc, Loc) {
5✔
62
        let start_info = self
7✔
63
            .lines
×
64
            .iter()
65
            .find(|info| span.start >= info.start_byte && span.start < info.end_byte)
17✔
66
            .unwrap_or(self.lines.last().unwrap());
6✔
67
        let (mut start_char_pos, start_display_pos) = start_info.line
10✔
68
            [0..(span.start - start_info.start_byte).min(start_info.line.len())]
5✔
69
            .chars()
70
            .fold((0, 0), |(char_pos, byte_pos), c| {
18✔
71
                let display = char_width(c);
5✔
72
                (char_pos + 1, byte_pos + display)
6✔
73
            });
74
        // correct the char pos if we are highlighting the end of a line
75
        if (span.start - start_info.start_byte).saturating_sub(start_info.line.len()) > 0 {
12✔
76
            start_char_pos += 1;
2✔
77
        }
78
        let start = Loc {
79
            line: start_info.line_index,
7✔
80
            char: start_char_pos,
81
            display: start_display_pos,
82
            byte: span.start,
4✔
83
        };
84

85
        if span.start == span.end {
8✔
86
            return (start, start);
3✔
87
        }
88

89
        let end_info = self
5✔
90
            .lines
×
91
            .iter()
92
            .find(|info| span.end >= info.start_byte && span.end < info.end_byte)
18✔
93
            .unwrap_or(self.lines.last().unwrap());
3✔
94
        let (end_char_pos, end_display_pos) = end_info.line
12✔
95
            [0..(span.end - end_info.start_byte).min(end_info.line.len())]
10✔
96
            .chars()
97
            .fold((0, 0), |(char_pos, byte_pos), c| {
11✔
98
                let display = char_width(c);
4✔
99
                (char_pos + 1, byte_pos + display)
4✔
100
            });
101

102
        let mut end = Loc {
103
            line: end_info.line_index,
5✔
104
            char: end_char_pos,
105
            display: end_display_pos,
106
            byte: span.end,
6✔
107
        };
108
        if start.line != end.line && end.byte > end_info.end_byte - end_info.end_line_size {
10✔
109
            end.char += 1;
2✔
110
            end.display += 1;
4✔
111
        }
112

113
        (start, end)
4✔
114
    }
115

116
    pub(crate) fn span_to_snippet(&self, span: Range<usize>) -> Option<&str> {
4✔
117
        self.source.get(span)
6✔
118
    }
119

120
    pub(crate) fn span_to_lines(&self, span: Range<usize>) -> Vec<&LineInfo<'a>> {
4✔
121
        let mut lines = vec![];
4✔
122
        let start = span.start;
4✔
123
        let end = span.end;
4✔
124
        for line_info in &self.lines {
8✔
125
            if start >= line_info.end_byte {
4✔
126
                continue;
×
127
            }
128
            if end < line_info.start_byte {
4✔
129
                break;
×
130
            }
131
            lines.push(line_info);
4✔
132
        }
133
        lines
4✔
134
    }
135

136
    pub(crate) fn annotated_lines(
4✔
137
        &self,
138
        annotations: Vec<Annotation<'a>>,
139
        fold: bool,
140
    ) -> (usize, Vec<AnnotatedLineInfo<'a>>) {
141
        let source_len = self.source.len();
13✔
142
        if let Some(bigger) = annotations.iter().find_map(|x| {
12✔
143
            // Allow highlighting one past the last character in the source.
144
            if source_len + 1 < x.span.end {
13✔
145
                Some(&x.span)
1✔
146
            } else {
147
                None
5✔
148
            }
149
        }) {
150
            panic!("Annotation range `{bigger:?}` is beyond the end of buffer `{source_len}`")
2✔
151
        }
152

153
        let mut annotated_line_infos = self
5✔
154
            .lines
×
155
            .iter()
156
            .map(|info| AnnotatedLineInfo {
15✔
157
                line: info.line,
8✔
158
                line_index: info.line_index,
4✔
159
                annotations: vec![],
8✔
160
                keep: false,
×
161
            })
162
            .collect::<Vec<_>>();
163
        let mut multiline_annotations = vec![];
8✔
164

165
        for Annotation {
9✔
166
            span,
4✔
167
            label,
8✔
168
            kind,
4✔
169
            highlight_source,
8✔
170
        } in annotations
23✔
171
        {
172
            let (lo, mut hi) = self.span_to_locations(span.clone());
11✔
173
            if kind == AnnotationKind::Visible {
3✔
174
                for line_idx in lo.line..=hi.line {
4✔
175
                    self.keep_line(&mut annotated_line_infos, line_idx);
4✔
176
                }
177
                continue;
×
178
            }
179
            // Watch out for "empty spans". If we get a span like 6..6, we
180
            // want to just display a `^` at 6, so convert that to
181
            // 6..7. This is degenerate input, but it's best to degrade
182
            // gracefully -- and the parser likes to supply a span like
183
            // that for EOF, in particular.
184

185
            if lo.display == hi.display && lo.line == hi.line {
12✔
186
                hi.display += 1;
3✔
187
            }
188

189
            if lo.line == hi.line {
4✔
190
                let line_ann = LineAnnotation {
191
                    start: lo,
192
                    end: hi,
193
                    kind,
194
                    label,
195
                    annotation_type: LineAnnotationType::Singleline,
196
                    highlight_source,
197
                };
198
                self.add_annotation_to_file(&mut annotated_line_infos, lo.line, line_ann);
8✔
199
            } else {
200
                multiline_annotations.push(MultilineAnnotation {
8✔
201
                    depth: 1,
×
202
                    start: lo,
×
203
                    end: hi,
4✔
204
                    kind,
×
205
                    label,
4✔
206
                    overlaps_exactly: false,
×
207
                    highlight_source,
×
208
                });
209
            }
210
        }
211

212
        let mut primary_spans = vec![];
5✔
213

214
        // Find overlapping multiline annotations, put them at different depths
215
        multiline_annotations.sort_by_key(|ml| (ml.start.line, usize::MAX - ml.end.line));
14✔
216
        for (outer_i, ann) in multiline_annotations.clone().into_iter().enumerate() {
9✔
217
            if ann.kind.is_primary() {
6✔
218
                primary_spans.push((ann.start, ann.end));
3✔
219
            }
220
            for (inner_i, a) in &mut multiline_annotations.iter_mut().enumerate() {
6✔
221
                // Move all other multiline annotations overlapping with this one
222
                // one level to the right.
223
                if !ann.same_span(a)
8✔
224
                    && num_overlap(ann.start.line, ann.end.line, a.start.line, a.end.line, true)
4✔
225
                {
226
                    a.increase_depth();
2✔
227
                } else if ann.same_span(a) && outer_i != inner_i {
9✔
228
                    a.overlaps_exactly = true;
2✔
229
                } else {
230
                    if primary_spans
12✔
231
                        .iter()
232
                        .any(|(s, e)| a.start == *s && a.end == *e)
9✔
233
                    {
234
                        a.kind = AnnotationKind::Primary;
3✔
235
                    }
236
                    break;
×
237
                }
238
            }
239
        }
240

241
        let mut max_depth = 0; // max overlapping multiline spans
3✔
242
        for ann in &multiline_annotations {
7✔
243
            max_depth = max(max_depth, ann.depth);
6✔
244
        }
245
        // Change order of multispan depth to minimize the number of overlaps in the ASCII art.
246
        for a in &mut multiline_annotations {
6✔
247
            a.depth = max_depth - a.depth + 1;
6✔
248
        }
249
        for ann in multiline_annotations {
7✔
250
            let mut end_ann = ann.as_end();
6✔
251
            if ann.overlaps_exactly {
5✔
252
                end_ann.annotation_type = LineAnnotationType::Singleline;
2✔
253
            } else {
254
                // avoid output like
255
                //
256
                //  |        foo(
257
                //  |   _____^
258
                //  |  |_____|
259
                //  | ||         bar,
260
                //  | ||     );
261
                //  | ||      ^
262
                //  | ||______|
263
                //  |  |______foo
264
                //  |         baz
265
                //
266
                // and instead get
267
                //
268
                //  |       foo(
269
                //  |  _____^
270
                //  | |         bar,
271
                //  | |     );
272
                //  | |      ^
273
                //  | |      |
274
                //  | |______foo
275
                //  |        baz
276
                self.add_annotation_to_file(
3✔
277
                    &mut annotated_line_infos,
×
278
                    ann.start.line,
3✔
279
                    ann.as_start(),
3✔
280
                );
281
                // 4 is the minimum vertical length of a multiline span when presented: two lines
282
                // of code and two lines of underline. This is not true for the special case where
283
                // the beginning doesn't have an underline, but the current logic seems to be
284
                // working correctly.
285
                let middle = min(ann.start.line + 4, ann.end.line);
3✔
286
                // We'll show up to 4 lines past the beginning of the multispan start.
287
                // We will *not* include the tail of lines that are only whitespace, a comment or
288
                // a bare delimiter.
289
                let filter = |s: &str| {
4✔
290
                    let s = s.trim();
3✔
291
                    // Consider comments as empty, but don't consider docstrings to be empty.
292
                    !(s.starts_with("//") && !(s.starts_with("///") || s.starts_with("//!")))
6✔
293
                        // Consider lines with nothing but whitespace, a single delimiter as empty.
294
                        && !["", "{", "}", "(", ")", "[", "]"].contains(&s)
3✔
295
                };
296
                let until = (ann.start.line..middle)
6✔
297
                    .rev()
298
                    .filter_map(|line| self.get_line(line).map(|s| (line + 1, s)))
18✔
299
                    .find(|(_, s)| filter(s))
11✔
300
                    .map_or(ann.start.line, |(line, _)| line);
6✔
301
                for line in ann.start.line + 1..until {
4✔
302
                    // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
303
                    self.add_annotation_to_file(&mut annotated_line_infos, line, ann.as_line());
6✔
304
                }
305
                let line_end = ann.end.line - 1;
4✔
306
                let end_is_empty = self.get_line(line_end).map_or(false, |s| !filter(s));
16✔
307
                if middle < line_end && !end_is_empty {
7✔
308
                    self.add_annotation_to_file(&mut annotated_line_infos, line_end, ann.as_line());
2✔
309
                }
310
            }
311
            self.add_annotation_to_file(&mut annotated_line_infos, end_ann.end.line, end_ann);
4✔
312
        }
313

314
        if fold {
4✔
315
            annotated_line_infos.retain(|l| !l.annotations.is_empty() || l.keep);
10✔
316
        }
317

318
        (max_depth, annotated_line_infos)
4✔
319
    }
320

321
    fn add_annotation_to_file(
3✔
322
        &self,
323
        annotated_line_infos: &mut Vec<AnnotatedLineInfo<'a>>,
324
        line_index: usize,
325
        line_ann: LineAnnotation<'a>,
326
    ) {
327
        if let Some(line_info) = annotated_line_infos
12✔
328
            .iter_mut()
329
            .find(|line_info| line_info.line_index == line_index)
12✔
330
        {
331
            line_info.annotations.push(line_ann);
9✔
332
        } else {
333
            let info = self
×
334
                .lines
×
335
                .iter()
336
                .find(|l| l.line_index == line_index)
×
337
                .unwrap();
338
            annotated_line_infos.push(AnnotatedLineInfo {
×
339
                line: info.line,
×
340
                line_index,
×
341
                annotations: vec![line_ann],
×
342
                keep: false,
×
343
            });
344
            annotated_line_infos.sort_by_key(|l| l.line_index);
×
345
        }
346
    }
347

348
    fn keep_line(&self, annotated_line_infos: &mut Vec<AnnotatedLineInfo<'a>>, line_index: usize) {
2✔
349
        if let Some(line_info) = annotated_line_infos
6✔
350
            .iter_mut()
351
            .find(|line_info| line_info.line_index == line_index)
6✔
352
        {
353
            line_info.keep = true;
2✔
354
        } else {
355
            let info = self
×
356
                .lines
×
357
                .iter()
358
                .find(|l| l.line_index == line_index)
×
359
                .unwrap();
360
            annotated_line_infos.push(AnnotatedLineInfo {
×
361
                line: info.line,
×
362
                line_index,
×
363
                annotations: vec![],
×
364
                keep: true,
×
365
            });
366
            annotated_line_infos.sort_by_key(|l| l.line_index);
×
367
        }
368
    }
369

370
    pub(crate) fn splice_lines<'b>(
5✔
371
        &'a self,
372
        mut patches: Vec<Patch<'b>>,
373
        fold: bool,
374
    ) -> Option<SplicedLines<'b>> {
375
        fn push_trailing(
4✔
376
            buf: &mut String,
377
            line_opt: Option<&str>,
378
            lo: &Loc,
379
            hi_opt: Option<&Loc>,
380
        ) -> usize {
381
            let mut line_count = 0;
5✔
382
            // Convert CharPos to Usize, as CharPose is character offset
383
            // Extract low index and high index
384
            let (lo, hi_opt) = (lo.char, hi_opt.map(|hi| hi.char));
13✔
385
            if let Some(line) = line_opt {
5✔
386
                if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
18✔
387
                    // Get high index while account for rare unicode and emoji with char_indices
388
                    let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
22✔
389
                    match hi_opt {
5✔
390
                        // If high index exist, take string from low to high index
391
                        Some(hi) if hi > lo => {
8✔
392
                            // count how many '\n' exist
393
                            line_count = line[lo..hi].matches('\n').count();
4✔
394
                            buf.push_str(&line[lo..hi]);
3✔
395
                        }
396
                        Some(_) => (),
×
397
                        // If high index absence, take string from low index till end string.len
398
                        None => {
×
399
                            // count how many '\n' exist
400
                            line_count = line[lo..].matches('\n').count();
4✔
401
                            buf.push_str(&line[lo..]);
4✔
402
                        }
403
                    }
404
                }
405
                // If high index is None
406
                if hi_opt.is_none() {
3✔
407
                    buf.push('\n');
5✔
408
                }
409
            }
410
            line_count
4✔
411
        }
412

413
        let source_len = self.source.len();
8✔
414
        if let Some(bigger) = patches.iter().find_map(|x| {
8✔
415
            // Allow patching one past the last character in the source.
416
            if source_len + 1 < x.span.end {
8✔
417
                Some(&x.span)
1✔
418
            } else {
419
                None
4✔
420
            }
421
        }) {
422
            panic!("Patch span `{bigger:?}` is beyond the end of buffer `{source_len}`")
2✔
423
        }
424

425
        // Assumption: all spans are in the same file, and all spans
426
        // are disjoint. Sort in ascending order.
427
        patches.sort_by_key(|p| p.span.start);
15✔
428

429
        // Find the bounding span.
430
        let (lo, hi) = if fold {
13✔
431
            let lo = patches.iter().map(|p| p.span.start).min()?;
16✔
432
            let hi = patches.iter().map(|p| p.span.end).max()?;
12✔
433
            (lo, hi)
4✔
434
        } else {
435
            (0, source_len)
1✔
436
        };
437

438
        let lines = self.span_to_lines(lo..hi);
4✔
439

440
        let mut highlights = vec![];
4✔
441
        // To build up the result, we do this for each span:
442
        // - push the line segment trailing the previous span
443
        //   (at the beginning a "phantom" span pointing at the start of the line)
444
        // - push lines between the previous and current span (if any)
445
        // - if the previous and current span are not on the same line
446
        //   push the line segment leading up to the current span
447
        // - splice in the span substitution
448
        //
449
        // Finally push the trailing line segment of the last span
450
        let (mut prev_hi, _) = self.span_to_locations(lo..hi);
9✔
451
        prev_hi.char = 0;
4✔
452
        let mut prev_line = lines.first().map(|line| line.line);
14✔
453
        let mut buf = String::new();
4✔
454

455
        let trimmed_patches = patches
5✔
456
            .into_iter()
457
            // If this is a replacement of, e.g. `"a"` into `"ab"`, adjust the
458
            // suggestion and snippet to look as if we just suggested to add
459
            // `"b"`, which is typically much easier for the user to understand.
460
            .map(|part| part.trim_trivial_replacements(self.source))
13✔
461
            .collect::<Vec<_>>();
462
        let mut line_highlight = vec![];
4✔
463
        // We need to keep track of the difference between the existing code and the added
464
        // or deleted code in order to point at the correct column *after* substitution.
465
        let mut acc = 0;
5✔
466
        for part in &trimmed_patches {
9✔
467
            let (cur_lo, cur_hi) = self.span_to_locations(part.span.clone());
9✔
468
            if prev_hi.line == cur_lo.line {
4✔
469
                let mut count = push_trailing(&mut buf, prev_line, &prev_hi, Some(&cur_lo));
8✔
470
                while count > 0 {
4✔
471
                    highlights.push(std::mem::take(&mut line_highlight));
×
472
                    acc = 0;
×
473
                    count -= 1;
×
474
                }
475
            } else {
476
                acc = 0;
1✔
477
                highlights.push(std::mem::take(&mut line_highlight));
2✔
478
                let mut count = push_trailing(&mut buf, prev_line, &prev_hi, None);
1✔
479
                while count > 0 {
1✔
480
                    highlights.push(std::mem::take(&mut line_highlight));
×
481
                    count -= 1;
×
482
                }
483
                // push lines between the previous and current span (if any)
484
                for idx in prev_hi.line + 1..(cur_lo.line) {
2✔
485
                    if let Some(line) = self.get_line(idx) {
2✔
486
                        buf.push_str(line.as_ref());
1✔
487
                        buf.push('\n');
1✔
488
                        highlights.push(std::mem::take(&mut line_highlight));
1✔
489
                    }
490
                }
491
                if let Some(cur_line) = self.get_line(cur_lo.line) {
1✔
492
                    let end = match cur_line.char_indices().nth(cur_lo.char) {
3✔
493
                        Some((i, _)) => i,
2✔
494
                        None => cur_line.len(),
1✔
495
                    };
496
                    buf.push_str(&cur_line[..end]);
2✔
497
                }
498
            }
499
            // Add a whole line highlight per line in the snippet.
500
            let len: isize = part
7✔
501
                .replacement
×
502
                .split('\n')
503
                .next()
504
                .unwrap_or(&part.replacement)
4✔
505
                .chars()
506
                .map(|c| match c {
9✔
507
                    '\t' => 4,
×
508
                    _ => 1,
3✔
509
                })
510
                .sum();
511
            line_highlight.push(SubstitutionHighlight {
5✔
512
                start: (cur_lo.char as isize + acc) as usize,
3✔
513
                end: (cur_lo.char as isize + acc + len) as usize,
8✔
514
            });
515
            buf.push_str(&part.replacement);
4✔
516
            // Account for the difference between the width of the current code and the
517
            // snippet being suggested, so that the *later* suggestions are correctly
518
            // aligned on the screen. Note that cur_hi and cur_lo can be on different
519
            // lines, so cur_hi.col can be smaller than cur_lo.col
520
            acc += len - (cur_hi.char as isize - cur_lo.char as isize);
5✔
521
            prev_hi = cur_hi;
4✔
522
            prev_line = self.get_line(prev_hi.line);
8✔
523
            for line in part.replacement.split('\n').skip(1) {
5✔
524
                acc = 0;
2✔
525
                highlights.push(std::mem::take(&mut line_highlight));
2✔
526
                let end: usize = line
2✔
527
                    .chars()
528
                    .map(|c| match c {
6✔
529
                        '\t' => 4,
×
530
                        _ => 1,
2✔
531
                    })
532
                    .sum();
533
                line_highlight.push(SubstitutionHighlight { start: 0, end });
2✔
534
            }
535
        }
536
        highlights.push(std::mem::take(&mut line_highlight));
4✔
537
        if fold {
5✔
538
            // if the replacement already ends with a newline, don't print the next line
539
            if !buf.ends_with('\n') {
9✔
540
                push_trailing(&mut buf, prev_line, &prev_hi, None);
4✔
541
            }
542
        } else {
543
            // Add the trailing part of the source after the last patch
544
            if let Some(snippet) = self.span_to_snippet(prev_hi.byte..source_len) {
3✔
545
                buf.push_str(snippet);
2✔
546
                for _ in snippet.matches('\n') {
2✔
547
                    highlights.push(std::mem::take(&mut line_highlight));
2✔
548
                }
549
            }
550
        }
551
        // remove trailing newlines
552
        while buf.ends_with('\n') {
9✔
553
            buf.pop();
10✔
554
        }
555
        if highlights.iter().all(|parts| parts.is_empty()) {
28✔
NEW
556
            None
×
557
        } else {
558
            Some((buf, trimmed_patches, highlights))
5✔
559
        }
560
    }
561
}
562

563
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
564
pub(crate) struct MultilineAnnotation<'a> {
565
    pub depth: usize,
566
    pub start: Loc,
567
    pub end: Loc,
568
    pub kind: AnnotationKind,
569
    pub label: Option<Cow<'a, str>>,
570
    pub overlaps_exactly: bool,
571
    pub highlight_source: bool,
572
}
573

574
impl<'a> MultilineAnnotation<'a> {
575
    pub(crate) fn increase_depth(&mut self) {
2✔
576
        self.depth += 1;
2✔
577
    }
578

579
    /// Compare two `MultilineAnnotation`s considering only the `Span` they cover.
580
    pub(crate) fn same_span(&self, other: &MultilineAnnotation<'_>) -> bool {
3✔
581
        self.start == other.start && self.end == other.end
3✔
582
    }
583

584
    pub(crate) fn as_start(&self) -> LineAnnotation<'a> {
3✔
585
        LineAnnotation {
586
            start: self.start,
3✔
587
            end: Loc {
3✔
588
                line: self.start.line,
589
                char: self.start.char + 1,
590
                display: self.start.display + 1,
591
                byte: self.start.byte + 1,
592
            },
593
            kind: self.kind,
3✔
594
            label: None,
595
            annotation_type: LineAnnotationType::MultilineStart(self.depth),
3✔
596
            highlight_source: self.highlight_source,
3✔
597
        }
598
    }
599

600
    pub(crate) fn as_end(&self) -> LineAnnotation<'a> {
3✔
601
        LineAnnotation {
602
            start: Loc {
3✔
603
                line: self.end.line,
604
                char: self.end.char.saturating_sub(1),
605
                display: self.end.display.saturating_sub(1),
606
                byte: self.end.byte.saturating_sub(1),
607
            },
608
            end: self.end,
3✔
609
            kind: self.kind,
3✔
610
            label: self.label.clone(),
3✔
611
            annotation_type: LineAnnotationType::MultilineEnd(self.depth),
3✔
612
            highlight_source: self.highlight_source,
3✔
613
        }
614
    }
615

616
    pub(crate) fn as_line(&self) -> LineAnnotation<'a> {
3✔
617
        LineAnnotation {
618
            start: Loc::default(),
3✔
619
            end: Loc::default(),
3✔
620
            kind: self.kind,
3✔
621
            label: None,
622
            annotation_type: LineAnnotationType::MultilineLine(self.depth),
3✔
623
            highlight_source: self.highlight_source,
3✔
624
        }
625
    }
626
}
627

628
#[derive(Debug)]
629
pub(crate) struct LineInfo<'a> {
630
    pub(crate) line: &'a str,
631
    pub(crate) line_index: usize,
632
    pub(crate) start_byte: usize,
633
    pub(crate) end_byte: usize,
634
    end_line_size: usize,
635
}
636

637
#[derive(Debug)]
638
pub(crate) struct AnnotatedLineInfo<'a> {
639
    pub(crate) line: &'a str,
640
    pub(crate) line_index: usize,
641
    pub(crate) annotations: Vec<LineAnnotation<'a>>,
642
    pub(crate) keep: bool,
643
}
644

645
/// A source code location used for error reporting.
646
#[derive(Clone, Copy, Debug, Default, PartialOrd, Ord, PartialEq, Eq)]
647
pub(crate) struct Loc {
648
    /// The (1-based) line number.
649
    pub(crate) line: usize,
650
    /// The (0-based) column offset.
651
    pub(crate) char: usize,
652
    /// The (0-based) column offset when displayed.
653
    pub(crate) display: usize,
654
    /// The (0-based) byte offset.
655
    pub(crate) byte: usize,
656
}
657

658
struct CursorLines<'a>(&'a str);
659

660
impl CursorLines<'_> {
661
    fn new(src: &str) -> CursorLines<'_> {
6✔
662
        CursorLines(src)
663
    }
664
}
665

666
#[derive(Copy, Clone, Debug, PartialEq)]
667
enum EndLine {
668
    Eof,
669
    Lf,
670
    Crlf,
671
}
672

673
impl EndLine {
674
    /// The number of characters this line ending occupies in bytes.
675
    pub(crate) fn len(self) -> usize {
4✔
676
        match self {
4✔
677
            EndLine::Eof => 0,
678
            EndLine::Lf => 1,
679
            EndLine::Crlf => 2,
680
        }
681
    }
682
}
683

684
impl<'a> Iterator for CursorLines<'a> {
685
    type Item = (&'a str, EndLine);
686

687
    fn next(&mut self) -> Option<Self::Item> {
6✔
688
        if self.0.is_empty() {
4✔
689
            None
9✔
690
        } else {
691
            self.0
8✔
692
                .find('\n')
693
                .map(|x| {
11✔
694
                    let ret = if 0 < x {
8✔
695
                        if self.0.as_bytes()[x - 1] == b'\r' {
20✔
696
                            (&self.0[..x - 1], EndLine::Crlf)
6✔
697
                        } else {
698
                            (&self.0[..x], EndLine::Lf)
3✔
699
                        }
700
                    } else {
701
                        ("", EndLine::Lf)
3✔
702
                    };
703
                    self.0 = &self.0[x + 1..];
12✔
704
                    ret
5✔
705
                })
706
                .or_else(|| {
8✔
707
                    let ret = Some((self.0, EndLine::Eof));
3✔
708
                    self.0 = "";
3✔
709
                    ret
×
710
                })
711
        }
712
    }
713
}
714

715
pub(crate) type SplicedLines<'a> = (
716
    String,
717
    Vec<TrimmedPatch<'a>>,
718
    Vec<Vec<SubstitutionHighlight>>,
719
);
720

721
/// Used to translate between `Span`s and byte positions within a single output line in highlighted
722
/// code of structured suggestions.
723
#[derive(Debug, Clone, Copy)]
724
pub(crate) struct SubstitutionHighlight {
725
    pub(crate) start: usize,
726
    pub(crate) end: usize,
727
}
728

729
#[derive(Clone, Debug)]
730
pub(crate) struct TrimmedPatch<'a> {
731
    pub(crate) original_span: Range<usize>,
732
    pub(crate) span: Range<usize>,
733
    pub(crate) replacement: Cow<'a, str>,
734
}
735

736
impl<'a> TrimmedPatch<'a> {
737
    pub(crate) fn is_addition(&self, sm: &SourceMap<'_>) -> bool {
3✔
738
        !self.replacement.is_empty() && !self.replaces_meaningful_content(sm)
2✔
739
    }
740

741
    pub(crate) fn is_deletion(&self, sm: &SourceMap<'_>) -> bool {
5✔
742
        self.replacement.trim().is_empty() && self.replaces_meaningful_content(sm)
6✔
743
    }
744

745
    pub(crate) fn is_replacement(&self, sm: &SourceMap<'_>) -> bool {
5✔
746
        !self.replacement.is_empty() && self.replaces_meaningful_content(sm)
5✔
747
    }
748

749
    /// Whether this is a replacement that overwrites source with a snippet
750
    /// in a way that isn't a superset of the original string. For example,
751
    /// replacing "abc" with "abcde" is not destructive, but replacing it
752
    /// it with "abx" is, since the "c" character is lost.
753
    pub(crate) fn is_destructive_replacement(&self, sm: &SourceMap<'_>) -> bool {
5✔
754
        self.is_replacement(sm)
5✔
755
            && !sm
3✔
756
                .span_to_snippet(self.span.clone())
3✔
757
                // This should use `is_some_and` when our MSRV is >= 1.70
758
                .map_or(false, |s| {
6✔
759
                    as_substr(s.trim(), self.replacement.trim()).is_some()
3✔
760
                })
761
    }
762

763
    fn replaces_meaningful_content(&self, sm: &SourceMap<'_>) -> bool {
5✔
764
        sm.span_to_snippet(self.span.clone())
6✔
765
            .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
13✔
766
    }
767
}
768

769
/// Given an original string like `AACC`, and a suggestion like `AABBCC`, try to detect
770
/// the case where a substring of the suggestion is "sandwiched" in the original, like
771
/// `BB` is. Return the length of the prefix, the "trimmed" suggestion, and the length
772
/// of the suffix.
773
pub(crate) fn as_substr<'a>(
4✔
774
    original: &'a str,
775
    suggestion: &'a str,
776
) -> Option<(usize, &'a str, usize)> {
777
    let common_prefix = original
×
778
        .chars()
779
        .zip(suggestion.chars())
4✔
780
        .take_while(|(c1, c2)| c1 == c2)
10✔
781
        .map(|(c, _)| c.len_utf8())
8✔
782
        .sum();
783
    let original = &original[common_prefix..];
3✔
784
    let suggestion = &suggestion[common_prefix..];
3✔
785
    if let Some(stripped) = suggestion.strip_suffix(original) {
7✔
786
        let common_suffix = original.len();
3✔
787
        Some((common_prefix, stripped, common_suffix))
4✔
788
    } else {
789
        None
3✔
790
    }
791
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc