annotate-snippets 0.12.15

Format diagnostic reports, including highlighting snippets of text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Structures used as an input for the library.

use alloc::borrow::{Cow, ToOwned};
use alloc::string::String;
use alloc::{vec, vec::Vec};
use core::ops::Range;

use crate::Level;
use crate::renderer::source_map::{TrimmedPatch, as_substr};

pub(crate) const ERROR_TXT: &str = "error";
pub(crate) const HELP_TXT: &str = "help";
pub(crate) const INFO_TXT: &str = "info";
pub(crate) const NOTE_TXT: &str = "note";
pub(crate) const WARNING_TXT: &str = "warning";

/// A [diagnostic message][Title] and any associated [context][Element] to help users
/// understand it
///
/// The first [`Group`] is the ["primary" group][Level::primary_title], ie it contains the diagnostic
/// message.
///
/// All subsequent [`Group`]s are for distinct pieces of [context][Level::secondary_title].
/// The primary group will be visually distinguished to help tell them apart.
pub type Report<'a> = &'a [Group<'a>];

#[derive(Clone, Debug, Default)]
pub(crate) struct Id<'a> {
    pub(crate) id: Option<Cow<'a, str>>,
    pub(crate) url: Option<Cow<'a, str>>,
}

/// A [`Title`] with supporting [context][Element] within a [`Report`]
///
/// [Decor][crate::renderer::DecorStyle] is used to visually connect [`Element`]s of a `Group`.
///
/// Generally, you will create separate group's for:
/// - New [`Snippet`]s, especially if they need their own [`AnnotationKind::Primary`]
/// - Each logically distinct set of [suggestions][Patch`]
///
/// # Example
///
/// ```rust
/// # #[allow(clippy::needless_doctest_main)]
#[doc = include_str!("../examples/highlight_message.rs")]
/// ```
#[doc = include_str!("../examples/highlight_message.svg")]
#[derive(Clone, Debug)]
pub struct Group<'a> {
    pub(crate) primary_level: Level<'a>,
    pub(crate) title: Option<Title<'a>>,
    pub(crate) elements: Vec<Element<'a>>,
}

impl<'a> Group<'a> {
    /// Create group with a [`Title`], deriving [`AnnotationKind::Primary`] from its [`Level`]
    pub fn with_title(title: Title<'a>) -> Self {
        let level = title.level.clone();
        let mut x = Self::with_level(level);
        x.title = Some(title);
        x
    }

    /// Create a title-less group with a primary [`Level`] for [`AnnotationKind::Primary`]
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[allow(clippy::needless_doctest_main)]
    #[doc = include_str!("../examples/elide_header.rs")]
    /// ```
    #[doc = include_str!("../examples/elide_header.svg")]
    pub fn with_level(level: Level<'a>) -> Self {
        Self {
            primary_level: level,
            title: None,
            elements: vec![],
        }
    }

    /// Append an [`Element`] that adds context to the [`Title`]
    pub fn element(mut self, section: impl Into<Element<'a>>) -> Self {
        self.elements.push(section.into());
        self
    }

    /// Append [`Element`]s that adds context to the [`Title`]
    pub fn elements(mut self, sections: impl IntoIterator<Item = impl Into<Element<'a>>>) -> Self {
        self.elements.extend(sections.into_iter().map(Into::into));
        self
    }

    pub fn is_empty(&self) -> bool {
        self.elements.is_empty() && self.title.is_none()
    }
}

/// A section of content within a [`Group`]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Element<'a> {
    Message(Message<'a>),
    Cause(Snippet<'a, Annotation<'a>>),
    Suggestion(Snippet<'a, Patch<'a>>),
    Origin(Origin<'a>),
    Padding(Padding),
}

impl<'a> From<Message<'a>> for Element<'a> {
    fn from(value: Message<'a>) -> Self {
        Element::Message(value)
    }
}

impl<'a> From<Snippet<'a, Annotation<'a>>> for Element<'a> {
    fn from(value: Snippet<'a, Annotation<'a>>) -> Self {
        Element::Cause(value)
    }
}

impl<'a> From<Snippet<'a, Patch<'a>>> for Element<'a> {
    fn from(value: Snippet<'a, Patch<'a>>) -> Self {
        Element::Suggestion(value)
    }
}

impl<'a> From<Origin<'a>> for Element<'a> {
    fn from(value: Origin<'a>) -> Self {
        Element::Origin(value)
    }
}

impl From<Padding> for Element<'_> {
    fn from(value: Padding) -> Self {
        Self::Padding(value)
    }
}

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

/// A title that introduces a [`Group`], describing the main point
///
/// To create a `Title`, see [`Level::primary_title`] or [`Level::secondary_title`].
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::*;
/// let report = &[
///     Group::with_title(
///         Level::ERROR.primary_title("mismatched types").id("E0308")
///     ),
///     Group::with_title(
///         Level::HELP.secondary_title("function defined here")
///     ),
/// ];
/// ```
#[derive(Clone, Debug)]
pub struct Title<'a> {
    pub(crate) level: Level<'a>,
    pub(crate) id: Option<Id<'a>>,
    pub(crate) text: Cow<'a, str>,
    pub(crate) allows_styling: bool,
}

impl<'a> Title<'a> {
    /// The category for this [`Report`]
    ///
    /// Useful for looking searching for more information to resolve the diagnostic.
    ///
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn id(mut self, id: impl Into<Cow<'a, str>>) -> Self {
        self.id.get_or_insert(Id::default()).id = Some(id.into());
        self
    }

    /// Provide a URL for [`Title::id`] for more information on this diagnostic
    ///
    /// <div class="warning">
    ///
    /// This is only relevant if `id` is present
    ///
    /// </div>
    pub fn id_url(mut self, url: impl Into<Cow<'a, str>>) -> Self {
        self.id.get_or_insert(Id::default()).url = Some(url.into());
        self
    }

    /// Append an [`Element`] that adds context to the [`Title`]
    pub fn element(self, section: impl Into<Element<'a>>) -> Group<'a> {
        Group::with_title(self).element(section)
    }

    /// Append [`Element`]s that adds context to the [`Title`]
    pub fn elements(self, sections: impl IntoIterator<Item = impl Into<Element<'a>>>) -> Group<'a> {
        Group::with_title(self).elements(sections)
    }
}

/// A text [`Element`] in a [`Group`]
///
/// See [`Level::message`] to create this.
#[derive(Clone, Debug)]
pub struct Message<'a> {
    pub(crate) level: Level<'a>,
    pub(crate) text: Cow<'a, str>,
}

/// A source view [`Element`] in a [`Group`]
///
/// If you do not have [source][Snippet::source] available, see instead [`Origin`]
///
/// `Snippet`s come in the following styles (`T`):
/// - With [`Annotation`]s, see [`Snippet::annotation`]
/// - With [`Patch`]s, see [`Snippet::patch`]
#[derive(Clone, Debug)]
pub struct Snippet<'a, T> {
    pub(crate) path: Option<Cow<'a, str>>,
    pub(crate) line_start: usize,
    pub(crate) source: Cow<'a, str>,
    pub(crate) markers: Vec<T>,
    pub(crate) fold: bool,
}

impl<'a, T: Clone> Snippet<'a, T> {
    /// The source code to be rendered
    ///
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Pre-styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn source(source: impl Into<Cow<'a, str>>) -> Self {
        Self {
            path: None,
            line_start: 1,
            source: source.into(),
            markers: vec![],
            fold: true,
        }
    }

    /// When manually [`fold`][Self::fold]ing,
    /// the [`source`][Self::source]s line offset from the original start
    pub fn line_start(mut self, line_start: usize) -> Self {
        self.line_start = line_start;
        self
    }

    /// The location of the [`source`][Self::source] (e.g. a path)
    ///
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Pre-styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn path(mut self, path: impl Into<OptionCow<'a>>) -> Self {
        self.path = path.into().0;
        self
    }

    /// Control whether lines without [`Annotation`]s are shown
    ///
    /// The default is `fold(true)`, collapsing uninteresting lines.
    ///
    /// See [`AnnotationKind::Visible`] to force specific spans to be shown.
    pub fn fold(mut self, fold: bool) -> Self {
        self.fold = fold;
        self
    }
}

impl<'a> Snippet<'a, Annotation<'a>> {
    /// Highlight and describe a span of text within the [`source`][Self::source]
    pub fn annotation(mut self, annotation: Annotation<'a>) -> Snippet<'a, Annotation<'a>> {
        self.markers.push(annotation);
        self
    }

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

impl<'a> Snippet<'a, Patch<'a>> {
    /// Suggest to the user an edit to the [`source`][Self::source]
    pub fn patch(mut self, patch: Patch<'a>) -> Snippet<'a, Patch<'a>> {
        self.markers.push(patch);
        self
    }

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

/// Highlight and describe a span of text within a [`Snippet`]
///
/// See [`AnnotationKind`] to create an annotation.
///
/// # Example
///
/// ```rust
/// # #[allow(clippy::needless_doctest_main)]
#[doc = include_str!("../examples/expected_type.rs")]
/// ```
///
#[doc = include_str!("../examples/expected_type.svg")]
#[derive(Clone, Debug)]
pub struct Annotation<'a> {
    pub(crate) span: Range<usize>,
    pub(crate) label: Option<Cow<'a, str>>,
    pub(crate) kind: AnnotationKind,
    pub(crate) highlight_source: bool,
}

impl<'a> Annotation<'a> {
    /// Describe the reason the span is highlighted
    ///
    /// This will be styled according to the [`AnnotationKind`]
    ///
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Pre-styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn label(mut self, label: impl Into<OptionCow<'a>>) -> Self {
        self.label = label.into().0;
        self
    }

    /// Style the source according to the [`AnnotationKind`]
    ///
    /// This gives extra emphasis to this annotation
    pub fn highlight_source(mut self, highlight_source: bool) -> Self {
        self.highlight_source = highlight_source;
        self
    }
}

/// The type of [`Annotation`] being applied to a [`Snippet`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum AnnotationKind {
    /// For showing the source that the [Group's Title][Group::with_title] references
    ///
    /// For [`Title`]-less groups, see [`Group::with_level`]
    Primary,
    /// Additional context to better understand the [`Primary`][Self::Primary]
    /// [`Annotation`]
    ///
    /// See also [`Renderer::context`].
    ///
    /// [`Renderer::context`]: crate::renderer::Renderer
    Context,
    /// Prevents the annotated text from getting [folded][Snippet::fold]
    ///
    /// By default, [`Snippet`]s will [fold][`Snippet::fold`] (remove) lines
    /// that do not contain any annotations. [`Visible`][Self::Visible] makes
    /// it possible to selectively prevent this behavior for specific text,
    /// allowing context to be preserved without adding any annotation
    /// characters.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[allow(clippy::needless_doctest_main)]
    #[doc = include_str!("../examples/struct_name_as_context.rs")]
    /// ```
    ///
    #[doc = include_str!("../examples/struct_name_as_context.svg")]
    ///
    Visible,
}

impl AnnotationKind {
    /// Annotate a byte span within [`Snippet`]
    pub fn span<'a>(self, span: Range<usize>) -> Annotation<'a> {
        Annotation {
            span,
            label: None,
            kind: self,
            highlight_source: false,
        }
    }

    pub(crate) fn is_primary(&self) -> bool {
        matches!(self, AnnotationKind::Primary)
    }
}

/// Suggested edit to the [`Snippet`]
///
/// See [`Snippet::patch`]
///
/// # Example
///
/// ```rust
/// # #[allow(clippy::needless_doctest_main)]
#[doc = include_str!("../examples/multi_suggestion.rs")]
/// ```
///
#[doc = include_str!("../examples/multi_suggestion.svg")]
#[derive(Clone, Debug)]
pub struct Patch<'a> {
    pub(crate) span: Range<usize>,
    pub(crate) replacement: Cow<'a, str>,
}

impl<'a> Patch<'a> {
    /// Splice `replacement` into the [`Snippet`] at the specified byte span
    ///
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Pre-styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn new(span: Range<usize>, replacement: impl Into<Cow<'a, str>>) -> Self {
        Self {
            span,
            replacement: replacement.into(),
        }
    }

    /// Try to turn a replacement into an addition when the span that is being
    /// overwritten matches either the prefix or suffix of the replacement.
    pub(crate) fn trim_trivial_replacements(self, source: &str) -> TrimmedPatch<'a> {
        let mut trimmed = TrimmedPatch {
            original_span: self.span.clone(),
            span: self.span,
            replacement: self.replacement,
        };

        if trimmed.replacement.is_empty() {
            return trimmed;
        }
        let Some(snippet) = source.get(trimmed.original_span.clone()) else {
            return trimmed;
        };

        if let Some((prefix, substr, suffix)) = as_substr(snippet, &trimmed.replacement) {
            trimmed.span = trimmed.original_span.start + prefix
                ..trimmed.original_span.end.saturating_sub(suffix);
            trimmed.replacement = Cow::Owned(substr.to_owned());
        }
        trimmed
    }
}

/// A source location [`Element`] in a [`Group`]
///
/// If you have source available, see instead [`Snippet`]
///
/// # Example
///
/// ```rust
/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level, Origin};
/// let report = &[
///     Level::ERROR.primary_title("mismatched types").id("E0308")
///         .element(
///             Origin::path("$DIR/mismatched-types.rs")
///         )
/// ];
/// ```
#[derive(Clone, Debug)]
pub struct Origin<'a> {
    pub(crate) path: Cow<'a, str>,
    pub(crate) line: Option<usize>,
    pub(crate) char_column: Option<usize>,
}

impl<'a> Origin<'a> {
    /// <div class="warning">
    ///
    /// Text passed to this function is considered "untrusted input", as such
    /// all text is passed through a normalization function. Pre-styled text is
    /// not allowed to be passed to this function.
    ///
    /// </div>
    pub fn path(path: impl Into<Cow<'a, str>>) -> Self {
        Self {
            path: path.into(),
            line: None,
            char_column: None,
        }
    }

    /// Set the default line number to display
    pub fn line(mut self, line: usize) -> Self {
        self.line = Some(line);
        self
    }

    /// Set the default column to display
    ///
    /// <div class="warning">
    ///
    /// `char_column` is only be respected if [`Origin::line`] is also set.
    ///
    /// </div>
    pub fn char_column(mut self, char_column: usize) -> Self {
        self.char_column = Some(char_column);
        self
    }
}

impl<'a> From<Cow<'a, str>> for Origin<'a> {
    fn from(origin: Cow<'a, str>) -> Self {
        Self::path(origin)
    }
}

#[derive(Debug)]
pub struct OptionCow<'a>(pub(crate) Option<Cow<'a, str>>);

impl<'a, T: Into<Cow<'a, str>>> From<Option<T>> for OptionCow<'a> {
    fn from(value: Option<T>) -> Self {
        Self(value.map(Into::into))
    }
}

impl<'a> From<&'a Cow<'a, str>> for OptionCow<'a> {
    fn from(value: &'a Cow<'a, str>) -> Self {
        Self(Some(Cow::Borrowed(value)))
    }
}

impl<'a> From<Cow<'a, str>> for OptionCow<'a> {
    fn from(value: Cow<'a, str>) -> Self {
        Self(Some(value))
    }
}

impl<'a> From<&'a str> for OptionCow<'a> {
    fn from(value: &'a str) -> Self {
        Self(Some(Cow::Borrowed(value)))
    }
}
impl<'a> From<String> for OptionCow<'a> {
    fn from(value: String) -> Self {
        Self(Some(Cow::Owned(value)))
    }
}

impl<'a> From<&'a String> for OptionCow<'a> {
    fn from(value: &'a String) -> Self {
        Self(Some(Cow::Borrowed(value.as_str())))
    }
}