compiletest/directives/
line.rs1use std::fmt;
2
3use camino::Utf8Path;
4
5use crate::directives::LineNumber;
6use crate::{error, help};
7
8pub(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 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#[cfg_attr(test, derive(Debug))]
77pub(crate) struct DirectiveLine<'a> {
78 pub(crate) file_path: &'a Utf8Path,
83 pub(crate) line_number: LineNumber,
84
85 pub(crate) revision: Option<&'a str>,
89
90 #[cfg(not(test))]
96 raw_directive: &'a str,
97 #[cfg(test)]
98 pub(crate) raw_directive: &'a str,
99
100 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 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 pub(crate) fn value_after_colon(&self) -> Option<&'ln str> {
125 self.rest_after_separator(b':')
126 }
127
128 pub(crate) fn remark_after_space(&self) -> Option<&'ln str> {
131 self.rest_after_separator(b' ')
132 }
133
134 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 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}