Skip to main content

compiletest/directives/
line.rs

1use std::fmt;
2
3use camino::Utf8Path;
4
5use crate::directives::LineNumber;
6use crate::{error, help};
7
8/// If the given line begins with the appropriate comment prefix for a directive,
9/// returns a struct containing various parts of the directive.
10pub(crate) fn line_directive<'a>(
11    file_path: &'a Utf8Path,
12    line_number: LineNumber,
13    line: &'a str,
14) -> Option<Result<DirectiveLine<'a>, Error<'a>>> {
15    let error = |kind| Some(Err(Error { kind, file_path, line_number }));
16
17    let comment = line.trim_start().strip_prefix("//")?;
18    let trimmed_comment = comment.trim_start();
19
20    let (leading_revision, trimmed_comment) = trimmed_comment
21        .strip_prefix('[')
22        .and_then(|after_open_bracket| after_open_bracket.split_once(']'))
23        .map(|(revision, after_close_bracket)| (Some(revision), after_close_bracket.trim_start()))
24        .unwrap_or((None, trimmed_comment));
25
26    let mut raw_directive = trimmed_comment.strip_prefix("@")?.trim_start();
27
28    if let Some(revision) = leading_revision {
29        let context = &line[..line.substr_range(raw_directive).unwrap().start];
30        return error(ErrorKind::LeadingRevisionCondition { revision, context });
31    }
32
33    if trimmed_comment.len() != comment.len() {
34        return error(ErrorKind::WhitespaceBeforeAtSign);
35    }
36
37    let mut revision = None;
38
39    if let Some(after_open_bracket) = raw_directive.strip_prefix('[') {
40        let Some((line_revision, after_close_bracket)) = after_open_bracket.split_once(']') else {
41            return error(ErrorKind::UnclosedRevisionCondition);
42        };
43
44        revision = Some(line_revision);
45        raw_directive = after_close_bracket.trim_start();
46
47        if line_revision.contains(",") {
48            return error(ErrorKind::CommaInRevisionCondition {
49                revision: line_revision,
50                directive: raw_directive,
51            });
52        }
53    }
54
55    // The directive name ends at the first occurrence of colon, space, or end-of-string.
56    let name = raw_directive.split([':', ' ']).next().expect("split is never empty");
57
58    Some(Ok(DirectiveLine { file_path, line_number, revision, raw_directive, name }))
59}
60
61/// The (partly) broken-down contents of a line containing a test directive,
62/// which `iter_directives` passes to its callback function.
63///
64/// For example:
65///
66/// ```text
67/// //@ compile-flags: -O
68///     ^^^^^^^^^^^^^^^^^ raw_directive
69///     ^^^^^^^^^^^^^     name
70///
71/// //@ [foo] compile-flags: -O
72///      ^^^                    revision
73///           ^^^^^^^^^^^^^^^^^ raw_directive
74///           ^^^^^^^^^^^^^     name
75/// ```
76#[cfg_attr(test, derive(Debug))]
77pub(crate) struct DirectiveLine<'a> {
78    /// Path of the file containing this line.
79    ///
80    /// Mostly used for diagnostics, but some directives (e.g. `//@ pp-exact`)
81    /// also use it to compute a value based on the filename.
82    pub(crate) file_path: &'a Utf8Path,
83    pub(crate) line_number: LineNumber,
84
85    /// Some test directives start with a revision name in square brackets
86    /// (e.g. `[foo]`), and only apply to that revision of the test.
87    /// If present, this field contains the revision name (e.g. `foo`).
88    pub(crate) revision: Option<&'a str>,
89
90    /// The main part of the directive, after removing the comment prefix
91    /// and the optional revision specifier.
92    ///
93    /// This is "raw" because the directive's name and colon-separated value
94    /// (if present) have not yet been extracted or checked.
95    #[cfg(not(test))]
96    raw_directive: &'a str,
97    #[cfg(test)]
98    pub(crate) raw_directive: &'a str,
99
100    /// Name of the directive.
101    ///
102    /// Invariant: `self.raw_directive.starts_with(self.name)`
103    pub(crate) name: &'a str,
104}
105
106impl<'ln> DirectiveLine<'ln> {
107    pub(crate) fn applies_to_test_revision(&self, test_revision: Option<&str>) -> bool {
108        self.revision.is_none() || self.revision == test_revision
109    }
110
111    /// Helper method used by `value_after_colon` and `remark_after_space`.
112    /// Don't call this directly.
113    fn rest_after_separator(&self, separator: u8) -> Option<&'ln str> {
114        let n = self.name.len();
115        if self.raw_directive.as_bytes().get(n) != Some(&separator) {
116            return None;
117        }
118
119        Some(&self.raw_directive[n + 1..])
120    }
121
122    /// If this directive uses `name: value` syntax, returns the part after
123    /// the colon character.
124    pub(crate) fn value_after_colon(&self) -> Option<&'ln str> {
125        self.rest_after_separator(b':')
126    }
127
128    /// If this directive uses `name remark` syntax, returns the part after
129    /// the separating space.
130    pub(crate) fn remark_after_space(&self) -> Option<&'ln str> {
131        self.rest_after_separator(b' ')
132    }
133
134    /// Allows callers to print `raw_directive` if necessary,
135    /// without accessing the field directly.
136    pub(crate) fn display(&self) -> impl fmt::Display {
137        self.raw_directive
138    }
139}
140
141#[cfg_attr(test, derive(Debug))]
142pub(crate) struct Error<'a> {
143    pub(crate) kind: ErrorKind<'a>,
144    pub(crate) file_path: &'a Utf8Path,
145    pub(crate) line_number: LineNumber,
146}
147
148#[cfg_attr(test, derive(Debug))]
149pub(crate) enum ErrorKind<'a> {
150    LeadingRevisionCondition { revision: &'a str, context: &'a str },
151    WhitespaceBeforeAtSign,
152    UnclosedRevisionCondition,
153    CommaInRevisionCondition { revision: &'a str, directive: &'a str },
154}
155
156impl Error<'_> {
157    // FIXME: Just report the error, poison the context and keep going.
158    pub(crate) fn raise_fatal(self) -> ! {
159        let Self { kind, file_path, line_number } = self;
160
161        let error = |message| error!("malformed directive: {message} at {file_path}:{line_number}");
162
163        match kind {
164            ErrorKind::LeadingRevisionCondition { revision, context } => {
165                error("found revision condition before `@` instead of after");
166                help!("rewrite the start of the line to `//@[{revision}] ` (from `{context}`)");
167            }
168            ErrorKind::WhitespaceBeforeAtSign => {
169                error("found whitespace between `//` and `@`");
170                help!("if you meant to write a directive remove the whitespace to form `//@`");
171                help!(
172                    "if you meant to literally write `@` in a code comment add `\\` before `@` or \
173                    rewrap the contents of the comment so `@` doesn't come first"
174                );
175            }
176            ErrorKind::UnclosedRevisionCondition => {
177                error("revision condition is missing a closing bracket `]`");
178            }
179            ErrorKind::CommaInRevisionCondition { revision, directive } => {
180                error(
181                    "found commas in revision condition but multiple revisions aren't supported yet",
182                );
183
184                let suggestion = revision
185                    .split(",")
186                    .map(|revision| format!("//@[{revision}]: {directive}"))
187                    .collect::<Vec<_>>()
188                    .join("\n");
189
190                help!("consider splitting the directive like\n{suggestion}");
191            }
192        }
193
194        panic!("fatal error")
195    }
196}