Skip to main content

annotate_snippets/
snippet.rs

1//! Structures used as an input for the library.
2
3use alloc::borrow::Cow;
4use alloc::string::String;
5use alloc::{vec, vec::Vec};
6use core::ops::Range;
7
8use crate::Level;
9
10pub(crate) const ERROR_TXT: &str = "error";
11pub(crate) const HELP_TXT: &str = "help";
12pub(crate) const INFO_TXT: &str = "info";
13pub(crate) const NOTE_TXT: &str = "note";
14pub(crate) const WARNING_TXT: &str = "warning";
15
16/// A [diagnostic message][Title] and any associated [context][Element] to help users
17/// understand it
18///
19/// The first [`Group`] is the ["primary" group][Level::primary_title], ie it contains the diagnostic
20/// message.
21///
22/// All subsequent [`Group`]s are for distinct pieces of [context][Level::secondary_title].
23/// The primary group will be visually distinguished to help tell them apart.
24pub type Report<'a> = &'a [Group<'a>];
25
26#[derive(Clone, Debug, Default)]
27pub(crate) struct Id<'a> {
28    pub(crate) id: Option<Cow<'a, str>>,
29    pub(crate) url: Option<Cow<'a, str>>,
30}
31
32/// A [`Title`] with supporting [context][Element] within a [`Report`]
33///
34/// [Decor][crate::renderer::DecorStyle] is used to visually connect [`Element`]s of a `Group`.
35///
36/// Generally, you will create separate group's for:
37/// - New [`Snippet`]s, especially if they need their own [`AnnotationKind::Primary`]
38/// - Each logically distinct set of [suggestions][Patch`]
39///
40/// # Example
41///
42/// ```rust
43/// # #[allow(clippy::needless_doctest_main)]
44#[doc = include_str!("../examples/highlight_message.rs")]
45/// ```
46#[doc = include_str!("../examples/highlight_message.svg")]
47#[derive(Clone, Debug)]
48pub struct Group<'a> {
49    pub(crate) primary_level: Level<'a>,
50    pub(crate) title: Option<Title<'a>>,
51    pub(crate) elements: Vec<Element<'a>>,
52}
53
54impl<'a> Group<'a> {
55    /// Create group with a [`Title`], deriving [`AnnotationKind::Primary`] from its [`Level`]
56    pub fn with_title(title: Title<'a>) -> Self {
57        let level = title.level.clone();
58        let mut x = Self::with_level(level);
59        x.title = Some(title);
60        x
61    }
62
63    /// Create a title-less group with a primary [`Level`] for [`AnnotationKind::Primary`]
64    ///
65    /// # Example
66    ///
67    /// ```rust
68    /// # #[allow(clippy::needless_doctest_main)]
69    #[doc = include_str!("../examples/elide_header.rs")]
70    /// ```
71    #[doc = include_str!("../examples/elide_header.svg")]
72    pub fn with_level(level: Level<'a>) -> Self {
73        Self {
74            primary_level: level,
75            title: None,
76            elements: vec![],
77        }
78    }
79
80    /// Append an [`Element`] that adds context to the [`Title`]
81    pub fn element(mut self, section: impl Into<Element<'a>>) -> Self {
82        self.elements.push(section.into());
83        self
84    }
85
86    /// Append [`Element`]s that adds context to the [`Title`]
87    pub fn elements(mut self, sections: impl IntoIterator<Item = impl Into<Element<'a>>>) -> Self {
88        self.elements.extend(sections.into_iter().map(Into::into));
89        self
90    }
91
92    pub fn is_empty(&self) -> bool {
93        self.elements.is_empty() && self.title.is_none()
94    }
95}
96
97/// A section of content within a [`Group`]
98#[derive(Clone, Debug)]
99#[non_exhaustive]
100pub enum Element<'a> {
101    Message(Message<'a>),
102    Cause(Snippet<'a, Annotation<'a>>),
103    Suggestion(Snippet<'a, Patch<'a>>),
104    Origin(Origin<'a>),
105    Padding(Padding),
106}
107
108impl<'a> From<Message<'a>> for Element<'a> {
109    fn from(value: Message<'a>) -> Self {
110        Element::Message(value)
111    }
112}
113
114impl<'a> From<Snippet<'a, Annotation<'a>>> for Element<'a> {
115    fn from(value: Snippet<'a, Annotation<'a>>) -> Self {
116        Element::Cause(value)
117    }
118}
119
120impl<'a> From<Snippet<'a, Patch<'a>>> for Element<'a> {
121    fn from(value: Snippet<'a, Patch<'a>>) -> Self {
122        Element::Suggestion(value)
123    }
124}
125
126impl<'a> From<Origin<'a>> for Element<'a> {
127    fn from(value: Origin<'a>) -> Self {
128        Element::Origin(value)
129    }
130}
131
132impl From<Padding> for Element<'_> {
133    fn from(value: Padding) -> Self {
134        Self::Padding(value)
135    }
136}
137
138/// A whitespace [`Element`] in a [`Group`]
139#[derive(Clone, Debug)]
140pub struct Padding;
141
142/// A title that introduces a [`Group`], describing the main point
143///
144/// To create a `Title`, see [`Level::primary_title`] or [`Level::secondary_title`].
145///
146/// # Example
147///
148/// ```rust
149/// # use annotate_snippets::*;
150/// let report = &[
151///     Group::with_title(
152///         Level::ERROR.primary_title("mismatched types").id("E0308")
153///     ),
154///     Group::with_title(
155///         Level::HELP.secondary_title("function defined here")
156///     ),
157/// ];
158/// ```
159#[derive(Clone, Debug)]
160pub struct Title<'a> {
161    pub(crate) level: Level<'a>,
162    pub(crate) id: Option<Id<'a>>,
163    pub(crate) footnote_marker: Option<Cow<'a, str>>,
164    pub(crate) text: Cow<'a, str>,
165    pub(crate) allows_styling: bool,
166}
167
168impl<'a> Title<'a> {
169    /// The category for this [`Report`]
170    ///
171    /// Useful for looking searching for more information to resolve the diagnostic.
172    ///
173    /// <div class="warning">
174    ///
175    /// Text passed to this function is considered "untrusted input", as such
176    /// all text is passed through a normalization function. Styled text is
177    /// not allowed to be passed to this function.
178    ///
179    /// </div>
180    pub fn id(mut self, id: impl Into<Cow<'a, str>>) -> Self {
181        self.id.get_or_insert(Id::default()).id = Some(id.into());
182        self
183    }
184
185    /// Provide a URL for [`Title::id`] for more information on this diagnostic
186    ///
187    /// <div class="warning">
188    ///
189    /// This is only relevant if `id` is present
190    ///
191    /// </div>
192    pub fn id_url(mut self, url: impl Into<Cow<'a, str>>) -> Self {
193        self.id.get_or_insert(Id::default()).url = Some(url.into());
194        self
195    }
196
197    /// Append a footnote marker to the title
198    ///
199    /// The caller is responsible for rendering the footnote.
200    ///
201    /// <div class="warning">
202    ///
203    /// Text passed to this function is considered "untrusted input", as such
204    /// all text is passed through a normalization function. Styled text is
205    /// not allowed to be passed to this function.
206    ///
207    /// </div>
208    pub fn footnote(mut self, marker: impl Into<OptionCow<'a>>) -> Self {
209        self.footnote_marker = marker.into().0;
210        self
211    }
212
213    /// Append an [`Element`] that adds context to the [`Title`]
214    pub fn element(self, section: impl Into<Element<'a>>) -> Group<'a> {
215        Group::with_title(self).element(section)
216    }
217
218    /// Append [`Element`]s that adds context to the [`Title`]
219    pub fn elements(self, sections: impl IntoIterator<Item = impl Into<Element<'a>>>) -> Group<'a> {
220        Group::with_title(self).elements(sections)
221    }
222}
223
224/// A text [`Element`] in a [`Group`]
225///
226/// See [`Level::message`] to create this.
227#[derive(Clone, Debug)]
228pub struct Message<'a> {
229    pub(crate) level: Level<'a>,
230    pub(crate) text: Cow<'a, str>,
231}
232
233/// A source view [`Element`] in a [`Group`]
234///
235/// If you do not have [source][Snippet::source] available, see instead [`Origin`]
236///
237/// `Snippet`s come in the following styles (`T`):
238/// - With [`Annotation`]s, see [`Snippet::annotation`]
239/// - With [`Patch`]s, see [`Snippet::patch`]
240#[derive(Clone, Debug)]
241pub struct Snippet<'a, T> {
242    pub(crate) path: Option<Cow<'a, str>>,
243    pub(crate) section: Option<Cow<'a, str>>,
244    pub(crate) line_start: usize,
245    pub(crate) source: Cow<'a, str>,
246    pub(crate) markers: Vec<T>,
247    pub(crate) line_numbering: bool,
248    pub(crate) fold: bool,
249}
250
251impl<'a, T: Clone> Snippet<'a, T> {
252    /// The source code to be rendered
253    ///
254    /// <div class="warning">
255    ///
256    /// Text passed to this function is considered "untrusted input", as such
257    /// all text is passed through a normalization function. Pre-styled text is
258    /// not allowed to be passed to this function.
259    ///
260    /// </div>
261    pub fn source(source: impl Into<Cow<'a, str>>) -> Self {
262        Self {
263            path: None,
264            section: None,
265            line_start: 1,
266            source: source.into(),
267            markers: vec![],
268            line_numbering: true,
269            fold: true,
270        }
271    }
272
273    /// Whether to show the line number for each line (default: `true`)
274    ///
275    /// The default is `line_numbering(true)`, showing line numbers
276    pub fn line_numbering(mut self, yes: bool) -> Self {
277        self.line_numbering = yes;
278        self
279    }
280
281    /// When manually [`fold`][Self::fold]ing,
282    /// the [`source`][Self::source]s line offset from the original start
283    pub fn line_start(mut self, line_start: usize) -> Self {
284        self.line_start = line_start;
285        self
286    }
287
288    /// The location of the [`source`][Self::source] (e.g. a path)
289    ///
290    /// <div class="warning">
291    ///
292    /// Text passed to this function is considered "untrusted input", as such
293    /// all text is passed through a normalization function. Pre-styled text is
294    /// not allowed to be passed to this function.
295    ///
296    /// </div>
297    pub fn path(mut self, path: impl Into<OptionCow<'a>>) -> Self {
298        self.path = path.into().0;
299        self
300    }
301
302    /// A named section that [`Origin::line`] is relative to within a container format
303    ///
304    /// e.g. Jupyter cells can be `"cell 1"`
305    pub fn section(mut self, section: impl Into<OptionCow<'a>>) -> Self {
306        self.section = section.into().0;
307        self
308    }
309
310    /// Control whether lines without [`Annotation`]s are shown
311    ///
312    /// The default is `fold(true)`, collapsing uninteresting lines.
313    ///
314    /// See [`AnnotationKind::Visible`] to force specific spans to be shown.
315    pub fn fold(mut self, fold: bool) -> Self {
316        self.fold = fold;
317        self
318    }
319
320    pub(crate) fn to_origin(&self) -> Option<Origin<'_>> {
321        if self.path.is_none() && self.section.is_none() {
322            return None;
323        }
324        Some(Origin {
325            path: self.path.clone(),
326            section: self.section.clone(),
327            line: None,
328            char_column: None,
329        })
330    }
331}
332
333impl<'a> Snippet<'a, Annotation<'a>> {
334    /// Highlight and describe a span of text within the [`source`][Self::source]
335    pub fn annotation(mut self, annotation: Annotation<'a>) -> Self {
336        self.markers.push(annotation);
337        self
338    }
339
340    /// Highlight and describe spans of text within the [`source`][Self::source]
341    pub fn annotations(mut self, annotation: impl IntoIterator<Item = Annotation<'a>>) -> Self {
342        self.markers.extend(annotation);
343        self
344    }
345}
346
347impl<'a> Snippet<'a, Patch<'a>> {
348    /// Suggest to the user an edit to the [`source`][Self::source]
349    pub fn patch(mut self, patch: Patch<'a>) -> Self {
350        self.markers.push(patch);
351        self
352    }
353
354    /// Suggest to the user edits to the [`source`][Self::source]
355    pub fn patches(mut self, patches: impl IntoIterator<Item = Patch<'a>>) -> Self {
356        self.markers.extend(patches);
357        self
358    }
359}
360
361/// Highlight and describe a span of text within a [`Snippet`]
362///
363/// See [`AnnotationKind`] to create an annotation.
364///
365/// # Example
366///
367/// ```rust
368/// # #[allow(clippy::needless_doctest_main)]
369#[doc = include_str!("../examples/expected_type.rs")]
370/// ```
371///
372#[doc = include_str!("../examples/expected_type.svg")]
373#[derive(Clone, Debug)]
374pub struct Annotation<'a> {
375    pub(crate) span: Range<usize>,
376    pub(crate) label: Option<Cow<'a, str>>,
377    pub(crate) kind: AnnotationKind,
378    pub(crate) highlight_source: bool,
379}
380
381impl<'a> Annotation<'a> {
382    /// Describe the reason the span is highlighted
383    ///
384    /// This will be styled according to the [`AnnotationKind`]
385    ///
386    /// <div class="warning">
387    ///
388    /// Text passed to this function is considered "untrusted input", as such
389    /// all text is passed through a normalization function. Pre-styled text is
390    /// not allowed to be passed to this function.
391    ///
392    /// </div>
393    pub fn label(mut self, label: impl Into<OptionCow<'a>>) -> Self {
394        self.label = label.into().0;
395        self
396    }
397
398    /// Style the source according to the [`AnnotationKind`]
399    ///
400    /// This gives extra emphasis to this annotation
401    pub fn highlight_source(mut self, highlight_source: bool) -> Self {
402        self.highlight_source = highlight_source;
403        self
404    }
405}
406
407/// The type of [`Annotation`] being applied to a [`Snippet`]
408#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
409#[non_exhaustive]
410pub enum AnnotationKind {
411    /// For showing the source that the [Group's Title][Group::with_title] references
412    ///
413    /// For [`Title`]-less groups, see [`Group::with_level`]
414    Primary,
415    /// Additional context to better understand the [`Primary`][Self::Primary]
416    /// [`Annotation`]
417    ///
418    /// See also [`Renderer::context`].
419    ///
420    /// [`Renderer::context`]: crate::renderer::Renderer
421    Context,
422    /// Prevents the annotated text from getting [folded][Snippet::fold]
423    ///
424    /// By default, [`Snippet`]s will [fold][`Snippet::fold`] (remove) lines
425    /// that do not contain any annotations. [`Visible`][Self::Visible] makes
426    /// it possible to selectively prevent this behavior for specific text,
427    /// allowing context to be preserved without adding any annotation
428    /// characters.
429    ///
430    /// # Example
431    ///
432    /// ```rust
433    /// # #[allow(clippy::needless_doctest_main)]
434    #[doc = include_str!("../examples/struct_name_as_context.rs")]
435    /// ```
436    ///
437    #[doc = include_str!("../examples/struct_name_as_context.svg")]
438    ///
439    Visible,
440}
441
442impl AnnotationKind {
443    /// Annotate a byte span within [`Snippet`]
444    pub fn span<'a>(self, span: Range<usize>) -> Annotation<'a> {
445        Annotation {
446            span,
447            label: None,
448            kind: self,
449            highlight_source: false,
450        }
451    }
452
453    pub(crate) fn is_primary(&self) -> bool {
454        matches!(self, Self::Primary)
455    }
456}
457
458/// Suggested edit to the [`Snippet`]
459///
460/// See [`Snippet::patch`]
461///
462/// # Example
463///
464/// ```rust
465/// # #[allow(clippy::needless_doctest_main)]
466#[doc = include_str!("../examples/multi_suggestion.rs")]
467/// ```
468///
469#[doc = include_str!("../examples/multi_suggestion.svg")]
470#[derive(Clone, Debug)]
471pub struct Patch<'a> {
472    pub(crate) span: Range<usize>,
473    pub(crate) replacement: Cow<'a, str>,
474}
475
476impl<'a> Patch<'a> {
477    /// Splice `replacement` into the [`Snippet`] at the specified byte span
478    ///
479    /// <div class="warning">
480    ///
481    /// Text passed to this function is considered "untrusted input", as such
482    /// all text is passed through a normalization function. Pre-styled text is
483    /// not allowed to be passed to this function.
484    ///
485    /// </div>
486    pub fn new(span: Range<usize>, replacement: impl Into<Cow<'a, str>>) -> Self {
487        Self {
488            span,
489            replacement: replacement.into(),
490        }
491    }
492}
493
494/// A source location [`Element`] in a [`Group`]
495///
496/// If you have source available, see instead [`Snippet`]
497///
498/// # Example
499///
500/// ```rust
501/// # use annotate_snippets::{Group, Snippet, AnnotationKind, Level, Origin};
502/// let report = &[
503///     Level::ERROR.primary_title("mismatched types").id("E0308")
504///         .element(
505///             Origin::path("$DIR/mismatched-types.rs")
506///         )
507/// ];
508/// ```
509#[derive(Clone, Debug)]
510pub struct Origin<'a> {
511    pub(crate) path: Option<Cow<'a, str>>,
512    pub(crate) section: Option<Cow<'a, str>>,
513    pub(crate) line: Option<usize>,
514    pub(crate) char_column: Option<usize>,
515}
516
517impl<'a> Origin<'a> {
518    /// <div class="warning">
519    ///
520    /// Text passed to this function is considered "untrusted input", as such
521    /// all text is passed through a normalization function. Pre-styled text is
522    /// not allowed to be passed to this function.
523    ///
524    /// </div>
525    pub fn path(path: impl Into<Cow<'a, str>>) -> Self {
526        Self {
527            path: Some(path.into()),
528            section: None,
529            line: None,
530            char_column: None,
531        }
532    }
533
534    /// A named section that [`Origin::line`] is relative to within a container format
535    ///
536    /// e.g. Jupyter cells can be `"cell 1"`
537    pub fn section(mut self, section: impl Into<OptionCow<'a>>) -> Self {
538        self.section = section.into().0;
539        self
540    }
541
542    /// Set the default line number to display
543    pub fn line(mut self, line: usize) -> Self {
544        self.line = Some(line);
545        self
546    }
547
548    /// Set the default column to display
549    ///
550    /// <div class="warning">
551    ///
552    /// `char_column` is only be respected if [`Origin::line`] is also set.
553    ///
554    /// </div>
555    pub fn char_column(mut self, char_column: usize) -> Self {
556        self.char_column = Some(char_column);
557        self
558    }
559}
560
561impl<'a> From<Cow<'a, str>> for Origin<'a> {
562    fn from(origin: Cow<'a, str>) -> Self {
563        Self::path(origin)
564    }
565}
566
567#[derive(Debug)]
568pub struct OptionCow<'a>(pub(crate) Option<Cow<'a, str>>);
569
570impl<'a, T: Into<Cow<'a, str>>> From<Option<T>> for OptionCow<'a> {
571    fn from(value: Option<T>) -> Self {
572        Self(value.map(Into::into))
573    }
574}
575
576impl<'a> From<&'a Cow<'a, str>> for OptionCow<'a> {
577    fn from(value: &'a Cow<'a, str>) -> Self {
578        Self(Some(Cow::Borrowed(value)))
579    }
580}
581
582impl<'a> From<Cow<'a, str>> for OptionCow<'a> {
583    fn from(value: Cow<'a, str>) -> Self {
584        Self(Some(value))
585    }
586}
587
588impl<'a> From<&'a str> for OptionCow<'a> {
589    fn from(value: &'a str) -> Self {
590        Self(Some(Cow::Borrowed(value)))
591    }
592}
593impl<'a> From<String> for OptionCow<'a> {
594    fn from(value: String) -> Self {
595        Self(Some(Cow::Owned(value)))
596    }
597}
598
599impl<'a> From<&'a String> for OptionCow<'a> {
600    fn from(value: &'a String) -> Self {
601        Self(Some(Cow::Borrowed(value.as_str())))
602    }
603}