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

rust-lang / annotate-snippets-rs / 15913305121

26 Jun 2025 09:55PM UTC coverage: 87.892%. Remained the same
15913305121

Pull #227

github

web-flow
Merge 8df4d37c1 into 119854678
Pull Request #227: Improve clarity arount Origin and Snippet

22 of 25 new or added lines in 2 files covered. (88.0%)

1 existing line in 1 file now uncovered.

1430 of 1627 relevant lines covered (87.89%)

4.63 hits per line

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

79.85
/src/snippet.rs
1
//! Structures used as an input for the library.
2

3
use crate::renderer::source_map::SourceMap;
4
use crate::Level;
5
use std::ops::Range;
6

7
pub(crate) const ERROR_TXT: &str = "error";
8
pub(crate) const HELP_TXT: &str = "help";
9
pub(crate) const INFO_TXT: &str = "info";
10
pub(crate) const NOTE_TXT: &str = "note";
11
pub(crate) const WARNING_TXT: &str = "warning";
12

13
/// Top-level user message
14
#[derive(Clone, Debug)]
15
pub struct Message<'a> {
16
    pub(crate) id: Option<&'a str>, // for "correctness", could be sloppy and be on Title
17
    pub(crate) groups: Vec<Group<'a>>,
18
}
19

20
impl<'a> Message<'a> {
21
    /// <div class="warning">
22
    ///
23
    /// Text passed to this function is considered "untrusted input", as such
24
    /// all text is passed through a normalization function. Pre-styled text is
25
    /// not allowed to be passed to this function.
26
    ///
27
    /// </div>
28
    pub fn id(mut self, id: &'a str) -> Self {
4✔
29
        self.id = Some(id);
6✔
30
        self
6✔
31
    }
32

33
    /// Add an [`Element`] container
34
    pub fn group(mut self, group: Group<'a>) -> Self {
6✔
35
        self.groups.push(group);
9✔
36
        self
6✔
37
    }
38

39
    pub(crate) fn max_line_number(&self) -> usize {
8✔
40
        self.groups
6✔
41
            .iter()
42
            .map(|v| {
8✔
43
                v.elements
6✔
44
                    .iter()
×
45
                    .map(|s| match s {
14✔
46
                        Element::Title(_) | Element::Origin(_) | Element::Padding(_) => 0,
8✔
47
                        Element::Cause(cause) => {
7✔
48
                            let end = cause
24✔
49
                                .markers
×
50
                                .iter()
×
51
                                .map(|a| a.span.end)
14✔
52
                                .max()
×
53
                                .unwrap_or(cause.source.len())
6✔
54
                                .min(cause.source.len());
6✔
55

56
                            cause.line_start + newline_count(&cause.source[..end])
15✔
57
                        }
58
                        Element::Suggestion(suggestion) => {
3✔
59
                            let end = suggestion
9✔
60
                                .markers
×
61
                                .iter()
×
62
                                .map(|a| a.span.end)
6✔
63
                                .max()
×
64
                                .unwrap_or(suggestion.source.len())
3✔
65
                                .min(suggestion.source.len());
3✔
66

67
                            suggestion.line_start + newline_count(&suggestion.source[..end])
6✔
68
                        }
69
                    })
70
                    .max()
×
71
                    .unwrap_or(1)
×
72
            })
73
            .max()
74
            .unwrap_or(1)
75
    }
76
}
77

78
/// An [`Element`] container
79
#[derive(Clone, Debug)]
80
pub struct Group<'a> {
81
    pub(crate) elements: Vec<Element<'a>>,
82
}
83

84
impl Default for Group<'_> {
85
    fn default() -> Self {
×
86
        Self::new()
×
87
    }
88
}
89

90
impl<'a> Group<'a> {
91
    pub fn new() -> Self {
12✔
92
        Self { elements: vec![] }
12✔
93
    }
94

95
    pub fn element(mut self, section: impl Into<Element<'a>>) -> Self {
31✔
96
        self.elements.push(section.into());
64✔
97
        self
32✔
98
    }
99

100
    pub fn elements(mut self, sections: impl IntoIterator<Item = impl Into<Element<'a>>>) -> Self {
×
101
        self.elements.extend(sections.into_iter().map(Into::into));
×
102
        self
×
103
    }
104

105
    pub fn is_empty(&self) -> bool {
×
106
        self.elements.is_empty()
×
107
    }
108
}
109

110
/// A section of content within a [`Group`]
111
#[derive(Clone, Debug)]
112
#[non_exhaustive]
113
pub enum Element<'a> {
114
    Title(Title<'a>),
115
    Cause(Snippet<'a, Annotation<'a>>),
116
    Suggestion(Snippet<'a, Patch<'a>>),
117
    Origin(Origin<'a>),
118
    Padding(Padding),
119
}
120

121
impl<'a> From<Title<'a>> for Element<'a> {
122
    fn from(value: Title<'a>) -> Self {
5✔
123
        Element::Title(value)
4✔
124
    }
125
}
126

127
impl<'a> From<Snippet<'a, Annotation<'a>>> for Element<'a> {
128
    fn from(value: Snippet<'a, Annotation<'a>>) -> Self {
7✔
129
        Element::Cause(value)
9✔
130
    }
131
}
132

133
impl<'a> From<Snippet<'a, Patch<'a>>> for Element<'a> {
134
    fn from(value: Snippet<'a, Patch<'a>>) -> Self {
4✔
135
        Element::Suggestion(value)
4✔
136
    }
137
}
138

139
impl<'a> From<Origin<'a>> for Element<'a> {
140
    fn from(value: Origin<'a>) -> Self {
2✔
141
        Element::Origin(value)
2✔
142
    }
143
}
144

145
impl From<Padding> for Element<'_> {
146
    fn from(value: Padding) -> Self {
1✔
147
        Self::Padding(value)
1✔
148
    }
149
}
150

151
/// A whitespace [`Element`] in a [`Group`]
152
#[derive(Clone, Debug)]
153
pub struct Padding;
154

155
/// A text [`Element`] in a [`Group`]
156
///
157
/// See [`Level::title`] to create this.
158
#[derive(Clone, Debug)]
159
pub struct Title<'a> {
160
    pub(crate) level: Level<'a>,
161
    pub(crate) title: &'a str,
162
}
163

164
/// A source view [`Element`] in a [`Group`]
165
///
166
/// If you do not have [source][Snippet::source] available, see instead [`Origin`]
167
#[derive(Clone, Debug)]
168
pub struct Snippet<'a, T> {
169
    pub(crate) path: Option<&'a str>,
170
    pub(crate) line_start: usize,
171
    pub(crate) source: &'a str,
172
    pub(crate) markers: Vec<T>,
173
    pub(crate) fold: bool,
174
}
175

176
impl<'a, T: Clone> Snippet<'a, T> {
177
    /// The source code to be rendered
178
    ///
179
    /// <div class="warning">
180
    ///
181
    /// Text passed to this function is considered "untrusted input", as such
182
    /// all text is passed through a normalization function. Pre-styled text is
183
    /// not allowed to be passed to this function.
184
    ///
185
    /// </div>
186
    pub fn source(source: &'a str) -> Self {
14✔
187
        Self {
188
            path: None,
189
            line_start: 1,
190
            source,
191
            markers: vec![],
12✔
192
            fold: false,
193
        }
194
    }
195

196
    /// When manually [`fold`][Self::fold]ing,
197
    /// the [`source`][Self::source]s line offset from the original start
198
    pub fn line_start(mut self, line_start: usize) -> Self {
12✔
199
        self.line_start = line_start;
13✔
200
        self
13✔
201
    }
202

203
    /// The location of the [`source`][Self::source] (e.g. a path)
204
    ///
205
    /// <div class="warning">
206
    ///
207
    /// Text passed to this function is considered "untrusted input", as such
208
    /// all text is passed through a normalization function. Pre-styled text is
209
    /// not allowed to be passed to this function.
210
    ///
211
    /// </div>
212
    pub fn path(mut self, path: &'a str) -> Self {
12✔
213
        self.path = Some(path);
14✔
214
        self
14✔
215
    }
216

217
    /// Hide lines without [`Annotation`]s
218
    pub fn fold(mut self, fold: bool) -> Self {
9✔
219
        self.fold = fold;
11✔
220
        self
9✔
221
    }
222
}
223

224
impl<'a> Snippet<'a, Annotation<'a>> {
225
    /// Highlight and describe a span of text within the [`source`][Self::source]
226
    pub fn annotation(mut self, annotation: Annotation<'a>) -> Snippet<'a, Annotation<'a>> {
9✔
227
        self.markers.push(annotation);
7✔
228
        self
9✔
229
    }
230

231
    /// Highlight and describe spans of text within the [`source`][Self::source]
232
    pub fn annotations(mut self, annotation: impl IntoIterator<Item = Annotation<'a>>) -> Self {
×
233
        self.markers.extend(annotation);
×
234
        self
×
235
    }
236
}
237

238
impl<'a> Snippet<'a, Patch<'a>> {
239
    /// Suggest to the user an edit to the [`source`][Self::source]
240
    pub fn patch(mut self, patch: Patch<'a>) -> Snippet<'a, Patch<'a>> {
5✔
241
        self.markers.push(patch);
5✔
242
        self
5✔
243
    }
244

245
    /// Suggest to the user edits to the [`source`][Self::source]
246
    pub fn patches(mut self, patches: impl IntoIterator<Item = Patch<'a>>) -> Self {
×
247
        self.markers.extend(patches);
×
248
        self
×
249
    }
250
}
251

252
/// Highlighted and describe a span of text within a [`Snippet`]
253
///
254
/// See [`AnnotationKind`] to create an annotation.
255
#[derive(Clone, Debug)]
256
pub struct Annotation<'a> {
257
    pub(crate) span: Range<usize>,
258
    pub(crate) label: Option<&'a str>,
259
    pub(crate) kind: AnnotationKind,
260
    pub(crate) highlight_source: bool,
261
}
262

263
impl<'a> Annotation<'a> {
264
    /// Describe the reason the span is highlighted
265
    ///
266
    /// This will be styled according to the [`AnnotationKind`]
267
    ///
268
    /// <div class="warning">
269
    ///
270
    /// Text passed to this function is considered "untrusted input", as such
271
    /// all text is passed through a normalization function. Pre-styled text is
272
    /// not allowed to be passed to this function.
273
    ///
274
    /// </div>
275
    pub fn label(mut self, label: &'a str) -> Self {
7✔
276
        self.label = Some(label);
5✔
277
        self
9✔
278
    }
279

280
    /// Style the source according to the [`AnnotationKind`]
281
    pub fn highlight_source(mut self, highlight_source: bool) -> Self {
×
282
        self.highlight_source = highlight_source;
×
283
        self
×
284
    }
285
}
286

287
/// The category of the [`Annotation`]
288
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
289
pub enum AnnotationKind {
290
    /// Color to [`Message`]'s [`Level`]
291
    Primary,
292
    /// "secondary"; fixed color
293
    Context,
294
}
295

296
impl AnnotationKind {
297
    pub fn span<'a>(self, span: Range<usize>) -> Annotation<'a> {
8✔
298
        Annotation {
299
            span,
300
            label: None,
301
            kind: self,
302
            highlight_source: false,
303
        }
304
    }
305

306
    pub(crate) fn is_primary(&self) -> bool {
7✔
307
        matches!(self, AnnotationKind::Primary)
3✔
308
    }
309
}
310

311
/// Suggested edit to the [`Snippet`]
312
#[derive(Clone, Debug)]
313
pub struct Patch<'a> {
314
    pub(crate) span: Range<usize>,
315
    pub(crate) replacement: &'a str,
316
}
317

318
impl<'a> Patch<'a> {
319
    /// Splice `replacement` into the [`Snippet`] at the `span`
320
    ///
321
    /// <div class="warning">
322
    ///
323
    /// Text passed to this function is considered "untrusted input", as such
324
    /// all text is passed through a normalization function. Pre-styled text is
325
    /// not allowed to be passed to this function.
326
    ///
327
    /// </div>
328
    pub fn new(span: Range<usize>, replacement: &'a str) -> Self {
5✔
329
        Self { span, replacement }
330
    }
331

332
    pub(crate) fn is_addition(&self, sm: &SourceMap<'_>) -> bool {
2✔
333
        !self.replacement.is_empty() && !self.replaces_meaningful_content(sm)
2✔
334
    }
335

336
    pub(crate) fn is_deletion(&self, sm: &SourceMap<'_>) -> bool {
3✔
337
        self.replacement.trim().is_empty() && self.replaces_meaningful_content(sm)
4✔
338
    }
339

340
    pub(crate) fn is_replacement(&self, sm: &SourceMap<'_>) -> bool {
2✔
341
        !self.replacement.is_empty() && self.replaces_meaningful_content(sm)
3✔
342
    }
343

344
    /// Whether this is a replacement that overwrites source with a snippet
345
    /// in a way that isn't a superset of the original string. For example,
346
    /// replacing "abc" with "abcde" is not destructive, but replacing it
347
    /// it with "abx" is, since the "c" character is lost.
348
    pub(crate) fn is_destructive_replacement(&self, sm: &SourceMap<'_>) -> bool {
2✔
349
        self.is_replacement(sm)
3✔
350
            && !sm
6✔
351
                .span_to_snippet(self.span.clone())
3✔
352
                // This should use `is_some_and` when our MSRV is >= 1.70
353
                .map_or(false, |s| {
6✔
354
                    as_substr(s.trim(), self.replacement.trim()).is_some()
3✔
355
                })
356
    }
357

358
    fn replaces_meaningful_content(&self, sm: &SourceMap<'_>) -> bool {
3✔
359
        sm.span_to_snippet(self.span.clone())
8✔
360
            .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
14✔
361
    }
362

363
    /// Try to turn a replacement into an addition when the span that is being
364
    /// overwritten matches either the prefix or suffix of the replacement.
365
    pub(crate) fn trim_trivial_replacements(&mut self, sm: &'a SourceMap<'a>) {
4✔
366
        if self.replacement.is_empty() {
4✔
367
            return;
×
368
        }
369
        let Some(snippet) = sm.span_to_snippet(self.span.clone()) else {
8✔
370
            return;
×
371
        };
372

373
        if let Some((prefix, substr, suffix)) = as_substr(snippet, self.replacement) {
7✔
374
            self.span = self.span.start + prefix..self.span.end.saturating_sub(suffix);
3✔
375
            self.replacement = substr;
3✔
376
        }
377
    }
378
}
379

380
/// The referenced location (e.g. a path)
381
///
382
/// If you have source available, see instead [`Snippet`]
383
#[derive(Clone, Debug)]
384
pub struct Origin<'a> {
385
    pub(crate) path: &'a str,
386
    pub(crate) line: Option<usize>,
387
    pub(crate) char_column: Option<usize>,
388
    pub(crate) primary: bool,
389
}
390

391
impl<'a> Origin<'a> {
392
    /// <div class="warning">
393
    ///
394
    /// Text passed to this function is considered "untrusted input", as such
395
    /// all text is passed through a normalization function. Pre-styled text is
396
    /// not allowed to be passed to this function.
397
    ///
398
    /// </div>
399
    pub fn new(path: &'a str) -> Self {
6✔
400
        Self {
401
            path,
402
            line: None,
403
            char_column: None,
404
            primary: false,
405
        }
406
    }
407

408
    /// Set the default line number to display
409
    ///
410
    /// Otherwise this will be inferred from the primary [`Annotation`]
411
    pub fn line(mut self, line: usize) -> Self {
2✔
412
        self.line = Some(line);
2✔
413
        self
2✔
414
    }
415

416
    /// Set the default column to display
417
    ///
418
    /// Otherwise this will be inferred from the primary [`Annotation`]
419
    ///
420
    /// <div class="warning">
421
    ///
422
    /// `char_column` is only be respected if [`Origin::line`] is also set.
423
    ///
424
    /// </div>
425
    pub fn char_column(mut self, char_column: usize) -> Self {
2✔
426
        self.char_column = Some(char_column);
2✔
427
        self
2✔
428
    }
429

430
    pub fn primary(mut self, primary: bool) -> Self {
1✔
431
        self.primary = primary;
1✔
432
        self
1✔
433
    }
434
}
435

436
fn newline_count(body: &str) -> usize {
8✔
437
    #[cfg(feature = "simd")]
438
    {
439
        memchr::memchr_iter(b'\n', body.as_bytes())
440
            .count()
441
            .saturating_sub(1)
442
    }
443
    #[cfg(not(feature = "simd"))]
444
    {
445
        body.lines().count().saturating_sub(1)
6✔
446
    }
447
}
448

449
/// Given an original string like `AACC`, and a suggestion like `AABBCC`, try to detect
450
/// the case where a substring of the suggestion is "sandwiched" in the original, like
451
/// `BB` is. Return the length of the prefix, the "trimmed" suggestion, and the length
452
/// of the suffix.
453
fn as_substr<'a>(original: &'a str, suggestion: &'a str) -> Option<(usize, &'a str, usize)> {
4✔
454
    let common_prefix = original
7✔
455
        .chars()
456
        .zip(suggestion.chars())
3✔
457
        .take_while(|(c1, c2)| c1 == c2)
4✔
458
        .map(|(c, _)| c.len_utf8())
4✔
459
        .sum();
460
    let original = &original[common_prefix..];
2✔
461
    let suggestion = &suggestion[common_prefix..];
2✔
462
    if let Some(stripped) = suggestion.strip_suffix(original) {
5✔
463
        let common_suffix = original.len();
2✔
464
        Some((common_prefix, stripped, common_suffix))
3✔
465
    } else {
466
        None
2✔
467
    }
468
}
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

© 2025 Coveralls, Inc