Skip to main content

annotate_snippets/renderer/
preprocess.rs

1use alloc::borrow::Cow;
2use alloc::vec::Vec;
3use core::cmp::max;
4
5use super::source_map::{AnnotatedLineInfo, PatchKind, SourceMap, SplicedLines, TrimmedPatch};
6use crate::{Annotation, Element, Group, Message, Origin, Padding, Patch, Snippet};
7
8pub(crate) struct Preprocessed<'a> {
9    pub(crate) max_line_num: Option<usize>,
10    pub(crate) report_primary_path: Option<&'a Cow<'a, str>>,
11    pub(crate) groups: Vec<PreprocessedGroup<'a>>,
12}
13
14impl Preprocessed<'_> {
15    pub(crate) fn preprocess<'a>(groups: &'a [Group<'a>]) -> Preprocessed<'a> {
16        preprocess(groups)
17    }
18}
19
20pub(crate) struct PreprocessedGroup<'a> {
21    pub(crate) group: &'a Group<'a>,
22    pub(crate) elements: Vec<PreprocessedElement<'a>>,
23    pub(crate) primary_path: Option<&'a Cow<'a, str>>,
24    pub(crate) max_depth: usize,
25}
26
27pub(crate) enum PreprocessedElement<'a> {
28    Message(&'a Message<'a>),
29    Cause(
30        (
31            &'a Snippet<'a, Annotation<'a>>,
32            SourceMap<'a>,
33            Vec<AnnotatedLineInfo<'a>>,
34        ),
35    ),
36    Suggestion(
37        (
38            &'a Snippet<'a, Patch<'a>>,
39            SourceMap<'a>,
40            SplicedLines<'a>,
41            DisplaySuggestion,
42        ),
43    ),
44    Origin(&'a Origin<'a>),
45    Padding(Padding),
46}
47
48fn preprocess<'a>(groups: &'a [Group<'a>]) -> Preprocessed<'a> {
49    let mut max_line_num = None;
50    let mut report_primary_path = None;
51    let mut out = Vec::with_capacity(groups.len());
52    for group in groups {
53        let mut elements = Vec::with_capacity(group.elements.len());
54        let mut primary_path = None;
55        let mut max_depth = 0;
56        for element in &group.elements {
57            match element {
58                Element::Message(message) => {
59                    elements.push(PreprocessedElement::Message(message));
60                }
61                Element::Cause(cause) => {
62                    let sm = SourceMap::new(&cause.source, cause.line_start);
63                    let (depth, annotated_lines) =
64                        sm.annotated_lines(cause.markers.clone(), cause.fold);
65
66                    if cause.fold {
67                        let end = cause
68                            .markers
69                            .iter()
70                            .map(|a| a.span.end)
71                            .max()
72                            .unwrap_or(cause.source.len())
73                            .min(cause.source.len());
74
75                        if cause.line_numbering {
76                            max_line_num = Some(max(
77                                cause.line_start + newline_count(&cause.source[..end]),
78                                max_line_num.unwrap_or(0),
79                            ));
80                        }
81                    } else {
82                        if cause.line_numbering {
83                            max_line_num = Some(max(
84                                cause.line_start + newline_count(&cause.source),
85                                max_line_num.unwrap_or(0),
86                            ));
87                        }
88                    }
89
90                    if primary_path.is_none() {
91                        primary_path = Some(cause.path.as_ref());
92                    }
93                    max_depth = max(depth, max_depth);
94                    elements.push(PreprocessedElement::Cause((cause, sm, annotated_lines)));
95                }
96                Element::Suggestion(suggestion) => {
97                    let sm = SourceMap::new(&suggestion.source, suggestion.line_start);
98                    if let Some(spliced_lines) =
99                        sm.splice_lines(suggestion.markers.clone(), suggestion.fold)
100                    {
101                        let display_suggestion = DisplaySuggestion::new(
102                            &spliced_lines.complete,
103                            &spliced_lines.patches,
104                            &sm,
105                        );
106
107                        if suggestion.line_numbering {
108                            if suggestion.fold {
109                                if let Some(first) = spliced_lines.patches.first() {
110                                    let (l_start, _) = sm.span_to_locations(first.original_span());
111                                    let nc = newline_count(&spliced_lines.complete);
112                                    let sugg_max_line_num = match display_suggestion {
113                                        DisplaySuggestion::Underline => l_start.line,
114                                        DisplaySuggestion::Diff => {
115                                            let file_lines = sm.span_to_lines(first.span());
116                                            file_lines
117                                                .last()
118                                                .map_or(l_start.line + nc, |line| line.line_index)
119                                        }
120                                        DisplaySuggestion::None => l_start.line + nc,
121                                        DisplaySuggestion::Add => l_start.line + nc,
122                                    };
123                                    max_line_num =
124                                        Some(max(sugg_max_line_num, max_line_num.unwrap_or(0)));
125                                }
126                            } else {
127                                max_line_num = Some(max(
128                                    suggestion.line_start + newline_count(&spliced_lines.complete),
129                                    max_line_num.unwrap_or(0),
130                                ));
131                            }
132                        }
133
134                        elements.push(PreprocessedElement::Suggestion((
135                            suggestion,
136                            sm,
137                            spliced_lines,
138                            display_suggestion,
139                        )));
140                    }
141                }
142                Element::Origin(origin) => {
143                    if primary_path.is_none() {
144                        primary_path = Some(origin.path.as_ref());
145                    }
146                    elements.push(PreprocessedElement::Origin(origin));
147                }
148                Element::Padding(padding) => {
149                    elements.push(PreprocessedElement::Padding(padding.clone()));
150                }
151            }
152        }
153        let group = PreprocessedGroup {
154            group,
155            elements,
156            primary_path: primary_path.unwrap_or_default(),
157            max_depth,
158        };
159        if report_primary_path.is_none() && group.primary_path.is_some() {
160            report_primary_path = group.primary_path;
161        }
162        out.push(group);
163    }
164
165    Preprocessed {
166        max_line_num,
167        report_primary_path,
168        groups: out,
169    }
170}
171
172fn newline_count(body: &str) -> usize {
173    #[cfg(feature = "simd")]
174    {
175        // Trailing newlines do not count towards the number of lines
176        // (this is based into `str::lines`)
177        let trailing_newline = body.ends_with('\n');
178        memchr::memchr_iter(b'\n', body.as_bytes()).count() - usize::from(trailing_newline)
179    }
180    #[cfg(not(feature = "simd"))]
181    {
182        body.lines().count().saturating_sub(1)
183    }
184}
185
186#[derive(Clone, Copy, Debug)]
187pub(crate) enum DisplaySuggestion {
188    Underline,
189    Diff,
190    None,
191    Add,
192}
193
194impl DisplaySuggestion {
195    fn new(complete: &str, patches: &[TrimmedPatch<'_>], sm: &SourceMap<'_>) -> Self {
196        let has_deletion = patches.iter().any(|p| {
197            matches!(p.kind(), Some(PatchKind::Deletion)) || p.is_destructive_replacement(sm)
198        });
199        let is_multiline = complete.lines().count() > 1;
200        if has_deletion && !is_multiline {
201            Self::Diff
202        } else if patches.len() == 1
203            && patches.first().is_some_and(|p| {
204                p.replacement().ends_with('\n') && p.replacement().trim() == complete.trim()
205            })
206        {
207            // We are adding a line(s) of code before code that was already there.
208            Self::Add
209        } else if (patches.len() != 1 || patches[0].replacement().trim() != complete.trim())
210            && !is_multiline
211        {
212            Self::Underline
213        } else {
214            Self::None
215        }
216    }
217}
218
219#[cfg(test)]
220mod test {
221    use super::newline_count;
222
223    #[test]
224    fn ensure_newline_count_correct() {
225        let source = r#"
226                cargo-features = ["path-bases"]
227
228                [package]
229                name = "foo"
230                version = "0.5.0"
231                authors = ["wycats@example.com"]
232
233                [dependencies]
234                bar = { base = '^^not-valid^^', path = 'bar' }
235            "#;
236        assert_eq!(newline_count(source), 10);
237
238        assert_eq!(newline_count(""), 0);
239
240        assert_eq!(newline_count("one"), 0);
241
242        assert_eq!(newline_count("one\n"), 0);
243
244        assert_eq!(newline_count("one\ntwo"), 1);
245
246        assert_eq!(newline_count("one\ntwo\n"), 1);
247
248        assert_eq!(newline_count("one\n\n"), 1);
249
250        assert_eq!(newline_count("one\r\ntwo\r\n"), 1);
251    }
252}