Skip to main content

cargo/util/
frontmatter.rs

1type Span = std::ops::Range<usize>;
2
3#[derive(Debug)]
4pub struct ScriptSource<'s> {
5    /// The full file
6    raw: &'s str,
7    /// The `#!/usr/bin/env cargo` line, if present
8    shebang: Option<Span>,
9    /// The code fence opener (`---`)
10    open: Option<Span>,
11    /// Trailing text after `ScriptSource::open` that identifies the meaning of
12    /// `ScriptSource::frontmatter`
13    info: Option<Span>,
14    /// The lines between `ScriptSource::open` and `ScriptSource::close`
15    frontmatter: Option<Span>,
16    /// The code fence closer (`---`)
17    close: Option<Span>,
18    /// All content after the frontmatter and shebang
19    content: Span,
20}
21
22impl<'s> ScriptSource<'s> {
23    pub fn parse(raw: &'s str) -> Result<Self, FrontmatterError> {
24        use winnow::stream::FindSlice as _;
25        use winnow::stream::Location as _;
26        use winnow::stream::Stream as _;
27
28        let content_end = raw.len();
29        let mut source = Self {
30            raw,
31            shebang: None,
32            open: None,
33            info: None,
34            frontmatter: None,
35            close: None,
36            content: 0..content_end,
37        };
38
39        let mut input = winnow::stream::LocatingSlice::new(raw);
40
41        // rustc strips a byte order mark before looking for a shebang or frontmatter
42        const BOM: &str = "\u{feff}";
43        if input.as_ref().starts_with(BOM) {
44            let _ = input.next_slice(BOM.len());
45            source.content = input.current_token_start()..content_end;
46        }
47
48        if let Some(shebang_end) = strip_shebang(input.as_ref()) {
49            let shebang_start = input.current_token_start();
50            let _ = input.next_slice(shebang_end);
51            let shebang_end = input.current_token_start();
52            source.shebang = Some(shebang_start..shebang_end);
53            source.content = shebang_end..content_end;
54        }
55
56        // Whitespace may precede a frontmatter but must end with a newline
57        if let Some(nl_end) = strip_ws_lines(input.as_ref()) {
58            let _ = input.next_slice(nl_end);
59        }
60
61        // Opens with a line that starts with 3 or more `-` followed by an optional identifier
62        const FENCE_CHAR: char = '-';
63        let fence_length = input
64            .as_ref()
65            .char_indices()
66            .find_map(|(i, c)| (c != FENCE_CHAR).then_some(i))
67            .unwrap_or_else(|| input.eof_offset());
68        let open_start = input.current_token_start();
69        let fence_pattern = input.next_slice(fence_length);
70        let open_end = input.current_token_start();
71        match fence_length {
72            0 => {
73                return Ok(source);
74            }
75            1 | 2 => {
76                // either not a frontmatter or invalid frontmatter opening
77                return Err(FrontmatterError::new(
78                    format!(
79                        "found {fence_length} `{FENCE_CHAR}` in rust frontmatter, expected at least 3"
80                    ),
81                    raw.len()..raw.len(),
82                ).push_visible_span(open_start..open_end));
83            }
84            _ if u8::try_from(fence_length).is_err() => {
85                return Err(FrontmatterError::new(
86                    format!(
87                        "too many `-` symbols: frontmatter openings may be delimited by up to 255 `-` symbols, but found {fence_length}"
88                    ),
89                    open_start..open_end,
90                ));
91            }
92            _ => {}
93        }
94        source.open = Some(open_start..open_end);
95        let Some(info_nl) = input.find_slice("\n") else {
96            return Err(FrontmatterError::new(
97                format!("unclosed frontmatter; expected `{fence_pattern}`"),
98                raw.len()..raw.len(),
99            )
100            .push_visible_span(open_start..open_end));
101        };
102        let info = input.next_slice(info_nl.start);
103        let info = info.trim_suffix('\r'); // already excludes `\n`
104        let info = info.trim_matches(is_horizontal_whitespace);
105        if !info.is_empty() {
106            source.info = Some(raw.substr_range(info).unwrap().into());
107        }
108
109        // Ends with a line that starts with a matching number of `-` only followed by whitespace
110        let nl_fence_pattern = format!("\n{fence_pattern}");
111        let Some(frontmatter_nl) = input.find_slice(nl_fence_pattern.as_str()) else {
112            for prefix_len in (2..=(nl_fence_pattern.len() - 1)).rev() {
113                let Some(frontmatter_nl) = input.find_slice(&nl_fence_pattern[0..prefix_len])
114                else {
115                    continue;
116                };
117                let nl_len = "\n".len();
118                let close_len = prefix_len - nl_len;
119
120                let _ = input.next_slice(frontmatter_nl.start + nl_len);
121                let close_start = input.current_token_start();
122                let _ = input.next_slice(close_len);
123                let close_end = input.current_token_start();
124                let fewer_dashes = fence_length - close_len;
125                return Err(FrontmatterError::new(
126                    format!(
127                        "closing code fence has {fewer_dashes} less `-` than the opening fence"
128                    ),
129                    close_start..close_end,
130                )
131                .push_visible_span(open_start..open_end));
132            }
133            return Err(FrontmatterError::new(
134                format!("unclosed frontmatter; expected `{fence_pattern}`"),
135                raw.len()..raw.len(),
136            )
137            .push_visible_span(open_start..open_end));
138        };
139        let frontmatter_start = input.current_token_start() + 1; // skip nl from infostring
140        let _ = input.next_slice(frontmatter_nl.start + 1);
141        let frontmatter_end = input.current_token_start();
142        source.frontmatter = Some(frontmatter_start..frontmatter_end);
143        let close_start = input.current_token_start();
144        let _ = input.next_slice(fence_length);
145        let close_end = input.current_token_start();
146        source.close = Some(close_start..close_end);
147
148        let nl = input.find_slice("\n");
149        let after_closing_fence = input.next_slice(
150            nl.map(|span| span.end)
151                .unwrap_or_else(|| input.eof_offset()),
152        );
153        let content_start = input.current_token_start();
154        let extra_dashes = after_closing_fence
155            .chars()
156            .take_while(|b| *b == FENCE_CHAR)
157            .count();
158        if 0 < extra_dashes {
159            let extra_start = close_end;
160            let extra_end = extra_start + extra_dashes;
161            return Err(FrontmatterError::new(
162                format!("closing code fence has {extra_dashes} more `-` than the opening fence"),
163                extra_start..extra_end,
164            )
165            .push_visible_span(open_start..open_end));
166        } else {
167            let after_closing_fence = strip_newline(after_closing_fence);
168            let after_closing_fence = after_closing_fence.trim_matches(is_horizontal_whitespace);
169            if !after_closing_fence.is_empty() {
170                // extra characters beyond the original fence pattern
171                return Err(FrontmatterError::new(
172                    format!("unexpected characters after frontmatter close"),
173                    raw.substr_range(after_closing_fence).unwrap().into(),
174                )
175                .push_visible_span(open_start..open_end));
176            }
177        }
178
179        source.content = content_start..content_end;
180
181        if let Some(nl_end) = strip_ws_lines(input.as_ref()) {
182            let _ = input.next_slice(nl_end);
183        }
184        let fence_length = input
185            .as_ref()
186            .char_indices()
187            .find_map(|(i, c)| (c != FENCE_CHAR).then_some(i))
188            .unwrap_or_else(|| input.eof_offset());
189        if 0 < fence_length {
190            let fence_start = input.current_token_start();
191            let fence_end = fence_start + fence_length;
192            return Err(FrontmatterError::new(
193                format!("only one frontmatter is supported"),
194                fence_start..fence_end,
195            )
196            .push_visible_span(open_start..open_end)
197            .push_visible_span(close_start..close_end));
198        }
199
200        Ok(source)
201    }
202
203    pub fn shebang(&self) -> Option<&'s str> {
204        self.shebang.clone().map(|span| &self.raw[span])
205    }
206
207    pub fn shebang_span(&self) -> Option<Span> {
208        self.shebang.clone()
209    }
210
211    pub fn open_span(&self) -> Option<Span> {
212        self.open.clone()
213    }
214
215    pub fn info(&self) -> Option<&'s str> {
216        self.info.clone().map(|span| &self.raw[span])
217    }
218
219    pub fn info_span(&self) -> Option<Span> {
220        self.info.clone()
221    }
222
223    pub fn frontmatter(&self) -> Option<&'s str> {
224        self.frontmatter.clone().map(|span| &self.raw[span])
225    }
226
227    pub fn frontmatter_span(&self) -> Option<Span> {
228        self.frontmatter.clone()
229    }
230
231    pub fn close_span(&self) -> Option<Span> {
232        self.close.clone()
233    }
234
235    pub fn content(&self) -> &'s str {
236        &self.raw[self.content.clone()]
237    }
238
239    pub fn content_span(&self) -> Span {
240        self.content.clone()
241    }
242}
243
244/// Returns the index after the shebang line, if present
245pub fn strip_shebang(input: &str) -> Option<usize> {
246    // See rust-lang/rust's compiler/rustc_lexer/src/lib.rs's `strip_shebang`
247    // Shebang must start with `#!` literally, without any preceding whitespace.
248    // For simplicity we consider any line starting with `#!` a shebang,
249    // regardless of restrictions put on shebangs by specific platforms.
250    if let Some(rest) = input.strip_prefix("#!") {
251        // Ok, this is a shebang but if the next non-whitespace token is `[`,
252        // then it may be valid Rust code, so consider it Rust code.
253        //
254        // NOTE: rustc considers line and block comments to be whitespace but to avoid
255        // any more awareness of Rust grammar, we are excluding it.
256        if !rest.trim_start().starts_with('[') {
257            // No other choice than to consider this a shebang.
258            let newline_end = input.find('\n').map(|pos| pos + 1).unwrap_or(input.len());
259            return Some(newline_end);
260        }
261    }
262    None
263}
264
265/// Returns the index after any lines with only whitespace, if present
266pub fn strip_ws_lines(input: &str) -> Option<usize> {
267    let ws_end = input.find(|c| !is_whitespace(c)).unwrap_or(input.len());
268    if ws_end == 0 {
269        return None;
270    }
271
272    let nl_start = input[0..ws_end].rfind('\n')?;
273    let nl_end = nl_start + 1;
274    Some(nl_end)
275}
276
277/// True if `c` is considered a whitespace according to Rust language definition.
278/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
279/// for definitions of these classes.
280fn is_whitespace(c: char) -> bool {
281    // This is Pattern_White_Space.
282    //
283    // Note that this set is stable (ie, it doesn't change with different
284    // Unicode versions), so it's ok to just hard-code the values.
285
286    matches!(
287        c,
288        // End-of-line characters
289        | '\u{000A}' // line feed (\n)
290        | '\u{000B}' // vertical tab
291        | '\u{000C}' // form feed
292        | '\u{000D}' // carriage return (\r)
293        | '\u{0085}' // next line (from latin1)
294        | '\u{2028}' // LINE SEPARATOR
295        | '\u{2029}' // PARAGRAPH SEPARATOR
296
297        // `Default_Ignorable_Code_Point` characters
298        | '\u{200E}' // LEFT-TO-RIGHT MARK
299        | '\u{200F}' // RIGHT-TO-LEFT MARK
300
301        // Horizontal space characters
302        | '\u{0009}'   // tab (\t)
303        | '\u{0020}' // space
304    )
305}
306
307/// True if `c` is considered horizontal whitespace according to Rust language definition.
308fn is_horizontal_whitespace(c: char) -> bool {
309    // This is Pattern_White_Space.
310    //
311    // Note that this set is stable (ie, it doesn't change with different
312    // Unicode versions), so it's ok to just hard-code the values.
313
314    matches!(
315        c,
316        // Horizontal space characters
317        '\u{0009}'   // tab (\t)
318        | '\u{0020}' // space
319    )
320}
321
322fn strip_newline(text: &str) -> &str {
323    text.strip_suffix("\r\n")
324        .or_else(|| text.strip_suffix('\n'))
325        .unwrap_or(text)
326}
327
328#[derive(Debug)]
329pub struct FrontmatterError {
330    message: String,
331    primary_span: Span,
332    visible_spans: Vec<Span>,
333}
334
335impl FrontmatterError {
336    pub fn new(message: impl Into<String>, span: Span) -> Self {
337        Self {
338            message: message.into(),
339            primary_span: span,
340            visible_spans: Vec::new(),
341        }
342    }
343
344    pub fn push_visible_span(mut self, span: Span) -> Self {
345        self.visible_spans.push(span);
346        self
347    }
348
349    pub fn message(&self) -> &str {
350        self.message.as_str()
351    }
352
353    pub fn primary_span(&self) -> Span {
354        self.primary_span.clone()
355    }
356
357    pub fn visible_spans(&self) -> &[Span] {
358        &self.visible_spans
359    }
360}
361
362impl std::fmt::Display for FrontmatterError {
363    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364        self.message.fmt(fmt)
365    }
366}
367
368impl std::error::Error for FrontmatterError {}
369
370#[cfg(test)]
371mod test {
372    use snapbox::assert_data_eq;
373    use snapbox::prelude::*;
374    use snapbox::str;
375
376    use super::*;
377
378    #[track_caller]
379    fn assert_source(source: &str, expected: impl IntoData) {
380        use std::fmt::Write as _;
381
382        let actual = match ScriptSource::parse(source) {
383            Ok(actual) => actual,
384            Err(err) => panic!("unexpected err: {err}"),
385        };
386
387        let mut rendered = String::new();
388        write_optional_field(&mut rendered, "shebang", actual.shebang());
389        write_optional_field(&mut rendered, "info", actual.info());
390        write_optional_field(&mut rendered, "frontmatter", actual.frontmatter());
391        writeln!(&mut rendered, "content: {:?}", actual.content()).unwrap();
392        assert_data_eq!(rendered, expected.raw());
393    }
394
395    fn write_optional_field(writer: &mut dyn std::fmt::Write, field: &str, value: Option<&str>) {
396        if let Some(value) = value {
397            writeln!(writer, "{field}: {value:?}").unwrap();
398        } else {
399            writeln!(writer, "{field}: None").unwrap();
400        }
401    }
402
403    #[track_caller]
404    fn assert_source_err(source: &str, expected: impl IntoData) {
405        match ScriptSource::parse(source) {
406            Ok(d) => panic!("unexpected Ok({d:#?})"),
407            Err(err) => {
408                let report = &[annotate_snippets::Level::ERROR
409                    .primary_title(err.to_string())
410                    .element(
411                        annotate_snippets::Snippet::source(source)
412                            .annotation(
413                                annotate_snippets::AnnotationKind::Primary.span(err.primary_span()),
414                            )
415                            .annotations(err.visible_spans().iter().map(|s| {
416                                annotate_snippets::AnnotationKind::Context.span(s.clone())
417                            })),
418                    )];
419                let renderer = annotate_snippets::Renderer::plain();
420                let actual = renderer.render(report);
421                snapbox::assert_data_eq!(actual, expected.raw())
422            }
423        }
424    }
425
426    #[test]
427    fn split_default() {
428        assert_source(
429            r#"fn main() {}
430"#,
431            str![[r#"
432shebang: None
433info: None
434frontmatter: None
435content: "fn main() {}\n"
436
437"#]],
438        );
439    }
440
441    #[test]
442    fn split_bom() {
443        assert_source(
444            "\u{feff}---
445[dependencies]
446time=\"0.1.25\"
447---
448fn main() {}
449",
450            str![[r#"
451shebang: None
452info: None
453frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
454content: "fn main() {}\n"
455
456"#]],
457        );
458    }
459
460    #[test]
461    fn split_bom_shebang() {
462        assert_source(
463            "\u{feff}#!/usr/bin/env cargo
464---
465[dependencies]
466time=\"0.1.25\"
467---
468fn main() {}
469",
470            str![[r##"
471shebang: "#!/usr/bin/env cargo\n"
472info: None
473frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
474content: "fn main() {}\n"
475
476"##]],
477        );
478    }
479
480    #[test]
481    fn split_dependencies() {
482        assert_source(
483            r#"---
484[dependencies]
485time="0.1.25"
486---
487fn main() {}
488"#,
489            str![[r#"
490shebang: None
491info: None
492frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
493content: "fn main() {}\n"
494
495"#]],
496        );
497    }
498
499    #[test]
500    fn split_infostring() {
501        assert_source(
502            r#"---cargo
503[dependencies]
504time="0.1.25"
505---
506fn main() {}
507"#,
508            str![[r#"
509shebang: None
510info: "cargo"
511frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
512content: "fn main() {}\n"
513
514"#]],
515        );
516    }
517
518    #[test]
519    fn split_infostring_whitespace() {
520        assert_source(
521            "--- cargo \n\
522[dependencies]\n\
523time=\"0.1.25\"\n\
524---\n\
525fn main() {}\n\
526",
527            str![[r#"
528shebang: None
529info: "cargo"
530frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
531content: "fn main() {}\n"
532
533"#]],
534        );
535    }
536
537    #[test]
538    fn split_shebang() {
539        assert_source(
540            r#"#!/usr/bin/env cargo
541---
542[dependencies]
543time="0.1.25"
544---
545fn main() {}
546"#,
547            str![[r##"
548shebang: "#!/usr/bin/env cargo\n"
549info: None
550frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
551content: "fn main() {}\n"
552
553"##]],
554        );
555    }
556
557    #[test]
558    fn split_crlf() {
559        assert_source(
560            "#!/usr/bin/env cargo\r\n---\r\n[dependencies]\r\ntime=\"0.1.25\"\r\n---\r\nfn main() {}",
561            str![[r##"
562shebang: "#!/usr/bin/env cargo\r\n"
563info: None
564frontmatter: "[dependencies]\r\ntime=\"0.1.25\"\r\n"
565content: "fn main() {}"
566
567"##]],
568        );
569    }
570
571    #[test]
572    fn split_leading_newlines() {
573        assert_source(
574            "#!/usr/bin/env cargo\n\
575    \n\
576\n\
577\n\
578---\n\
579[dependencies]\n\
580time=\"0.1.25\"\n\
581---\n\
582\n\
583\n\
584fn main() {}\n\
585",
586            str![[r##"
587shebang: "#!/usr/bin/env cargo\n"
588info: None
589frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
590content: "\n\nfn main() {}\n"
591
592"##]],
593        );
594    }
595
596    #[test]
597    fn split_attribute() {
598        assert_source(
599            r#"#[allow(dead_code)]
600---
601[dependencies]
602time="0.1.25"
603---
604fn main() {}
605"#,
606            str![[r##"
607shebang: None
608info: None
609frontmatter: None
610content: "#[allow(dead_code)]\n---\n[dependencies]\ntime=\"0.1.25\"\n---\nfn main() {}\n"
611
612"##]],
613        );
614    }
615
616    #[test]
617    fn split_extra_dash() {
618        assert_source(
619            r#"#!/usr/bin/env cargo
620----------
621[dependencies]
622time="0.1.25"
623----------
624
625fn main() {}"#,
626            str![[r##"
627shebang: "#!/usr/bin/env cargo\n"
628info: None
629frontmatter: "[dependencies]\ntime=\"0.1.25\"\n"
630content: "\nfn main() {}"
631
632"##]],
633        );
634    }
635
636    #[test]
637    fn split_too_few_dashes() {
638        assert_source_err(
639            r#"#!/usr/bin/env cargo
640--
641[dependencies]
642time="0.1.25"
643--
644fn main() {}
645"#,
646            str![[r#"
647error: found 2 `-` in rust frontmatter, expected at least 3
648  |
6492 | --
650  | --
651...
6526 | fn main() {}
653  |             ^
654"#]],
655        );
656    }
657
658    #[test]
659    fn split_indent() {
660        assert_source(
661            r#"#!/usr/bin/env cargo
662    ---
663    [dependencies]
664    time="0.1.25"
665    ----
666
667fn main() {}
668"#,
669            str![[r##"
670shebang: "#!/usr/bin/env cargo\n"
671info: None
672frontmatter: None
673content: "    ---\n    [dependencies]\n    time=\"0.1.25\"\n    ----\n\nfn main() {}\n"
674
675"##]],
676        );
677    }
678
679    #[test]
680    fn split_escaped() {
681        assert_source(
682            r#"#!/usr/bin/env cargo
683-----
684---
685---
686-----
687
688fn main() {}
689"#,
690            str![[r##"
691shebang: "#!/usr/bin/env cargo\n"
692info: None
693frontmatter: "---\n---\n"
694content: "\nfn main() {}\n"
695
696"##]],
697        );
698    }
699
700    #[test]
701    fn split_invalid_escaped() {
702        assert_source_err(
703            r#"#!/usr/bin/env cargo
704---
705-----
706-----
707---
708
709fn main() {}
710"#,
711            str![[r#"
712error: closing code fence has 2 more `-` than the opening fence
713  |
7142 | ---
715  | ---
7163 | -----
717  |    ^^
718"#]],
719        );
720    }
721
722    #[test]
723    fn split_dashes_in_body() {
724        assert_source(
725            r#"#!/usr/bin/env cargo
726---
727Hello---
728World
729---
730
731fn main() {}
732"#,
733            str![[r##"
734shebang: "#!/usr/bin/env cargo\n"
735info: None
736frontmatter: "Hello---\nWorld\n"
737content: "\nfn main() {}\n"
738
739"##]],
740        );
741    }
742
743    #[test]
744    fn split_mismatched_dashes() {
745        assert_source_err(
746            r#"#!/usr/bin/env cargo
747---
748[dependencies]
749time="0.1.25"
750----
751fn main() {}
752"#,
753            str![[r#"
754error: closing code fence has 1 more `-` than the opening fence
755  |
7562 | ---
757  | ---
758...
7595 | ----
760  |    ^
761"#]],
762        );
763    }
764
765    #[test]
766    fn split_missing_close() {
767        assert_source_err(
768            r#"#!/usr/bin/env cargo
769---
770[dependencies]
771time="0.1.25"
772fn main() {}
773"#,
774            str![[r#"
775error: unclosed frontmatter; expected `---`
776  |
7772 | ---
778  | ---
779...
7805 | fn main() {}
781  |             ^
782"#]],
783        );
784    }
785
786    #[test]
787    fn split_fewer_dashes() {
788        assert_source_err(
789            r#"----
790[dependencies]
791--
792fn main() {}
793"#,
794            str![[r#"
795error: closing code fence has 2 less `-` than the opening fence
796  |
7971 | ----
798  | ----
7992 | [dependencies]
8003 | --
801  | ^^
802"#]],
803        );
804    }
805
806    #[test]
807    fn split_fewer_dashes_by_one() {
808        assert_source_err(
809            r#"----
810[dependencies]
811---
812fn main() {}
813"#,
814            str![[r#"
815error: closing code fence has 1 less `-` than the opening fence
816  |
8171 | ----
818  | ----
8192 | [dependencies]
8203 | ---
821  | ^^^
822"#]],
823        );
824    }
825
826    #[test]
827    fn split_fewer_dashes_before_non_ascii() {
828        // The byte after the short closing fence starts a multi-byte char.
829        assert_source_err(
830            "---
831-\u{2502}
832",
833            str![[r#"
834error: closing code fence has 2 less `-` than the opening fence
835  |
8361 | ---
837  | ---
8382 | -│
839  | ^
840"#]],
841        );
842    }
843}