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

rust-lang / annotate-snippets-rs / 15862044996

24 Jun 2025 09:37PM UTC coverage: 86.621%. Remained the same
15862044996

Pull #222

github

web-flow
Merge a0d26c6aa into a81dc31d2
Pull Request #222: test: Ensure all examples have a test

1392 of 1607 relevant lines covered (86.62%)

4.5 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);
5✔
30
        self
5✔
31
    }
32

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

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

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

67
                            suggestion.line_start + newline_count(&suggestion.source[..end])
2✔
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 {
28✔
96
        self.elements.push(section.into());
56✔
97
        self
28✔
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 {
2✔
123
        Element::Title(value)
2✔
124
    }
125
}
126

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

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

139
impl<'a> From<Origin<'a>> for Element<'a> {
140
    fn from(value: Origin<'a>) -> Self {
1✔
141
        Element::Origin(value)
1✔
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
#[derive(Clone, Debug)]
166
pub struct Snippet<'a, T> {
167
    pub(crate) origin: Option<&'a str>,
168
    pub(crate) line_start: usize,
169
    pub(crate) source: &'a str,
170
    pub(crate) markers: Vec<T>,
171
    pub(crate) fold: bool,
172
}
173

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

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

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

215
    /// Hide lines without [`Annotation`]s
216
    pub fn fold(mut self, fold: bool) -> Self {
6✔
217
        self.fold = fold;
8✔
218
        self
7✔
219
    }
220
}
221

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

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

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

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

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

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

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

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

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

304
    pub(crate) fn is_primary(&self) -> bool {
6✔
305
        matches!(self, AnnotationKind::Primary)
4✔
306
    }
307
}
308

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

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

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

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

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

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

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

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

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

378
/// The location of the [`Snippet`] (e.g. a path)
379
#[derive(Clone, Debug)]
380
pub struct Origin<'a> {
381
    pub(crate) origin: &'a str,
382
    pub(crate) line: Option<usize>,
383
    pub(crate) char_column: Option<usize>,
384
    pub(crate) primary: bool,
385
}
386

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

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

412
    /// Set the default column to display
413
    ///
414
    /// Otherwise this will be inferred from the primary [`Annotation`]
415
    pub fn char_column(mut self, char_column: usize) -> Self {
1✔
416
        self.char_column = Some(char_column);
1✔
417
        self
1✔
418
    }
419

420
    pub fn primary(mut self, primary: bool) -> Self {
1✔
421
        self.primary = primary;
1✔
422
        self
1✔
423
    }
424
}
425

426
fn newline_count(body: &str) -> usize {
7✔
427
    #[cfg(feature = "simd")]
428
    {
429
        memchr::memchr_iter(b'\n', body.as_bytes())
430
            .count()
431
            .saturating_sub(1)
432
    }
433
    #[cfg(not(feature = "simd"))]
434
    {
435
        body.lines().count().saturating_sub(1)
5✔
436
    }
437
}
438

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