1use proc_macro::*;
11use std::path::Path;
12use std::process::Command;
13use std::sync::LazyLock;
14
15#[proc_macro_attribute]
64pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
65 let mut ignore = false;
78 let mut requires_reason = false;
79 let mut explicit_reason = None;
80 let mut implicit_reasons = Vec::new();
81 macro_rules! set_ignore {
82 ($predicate:expr, $($arg:tt)*) => {
83 let p = $predicate;
84 ignore |= p;
85 if p {
86 implicit_reasons.push(std::fmt::format(format_args!($($arg)*)));
87 }
88 };
89 }
90 let is_not_nightly = !version().1;
91 for rule in split_rules(attr) {
92 match rule.as_str() {
93 "build_std_real" => {
94 set_ignore!(is_not_nightly, "requires nightly");
99 set_ignore!(
100 option_env!("CARGO_RUN_BUILD_STD_TESTS").is_none(),
101 "CARGO_RUN_BUILD_STD_TESTS must be set"
102 );
103 }
104 "build_std_mock" => {
105 set_ignore!(is_not_nightly, "requires nightly");
109 set_ignore!(
110 cfg!(all(target_os = "windows", target_env = "gnu")),
111 "does not work on windows-gnu"
112 );
113 }
114 "container_test" => {
115 set_ignore!(
117 option_env!("CARGO_CONTAINER_TESTS").is_none(),
118 "CARGO_CONTAINER_TESTS must be set"
119 );
120 }
121 "public_network_test" => {
122 set_ignore!(
127 option_env!("CARGO_PUBLIC_NETWORK_TESTS").is_none(),
128 "CARGO_PUBLIC_NETWORK_TESTS must be set"
129 );
130 }
131 "nightly" => {
132 requires_reason = true;
133 set_ignore!(is_not_nightly, "requires nightly");
134 }
135 "requires_rustup_stable" => {
136 set_ignore!(
137 !has_rustup_stable(),
138 "rustup or stable toolchain not installed"
139 );
140 }
141 s if s.starts_with("requires=") => {
142 let command = &s[9..];
143 let Ok(literal) = command.parse::<Literal>() else {
144 panic!("expect a string literal, found: {command}");
145 };
146 let literal = literal.to_string();
147 let Some(command) = literal
148 .strip_prefix('"')
149 .and_then(|lit| lit.strip_suffix('"'))
150 else {
151 panic!("expect a quoted string literal, found: {literal}");
152 };
153 set_ignore!(!has_command(command), "{command} not installed");
154 }
155 s if s.starts_with("requires_host_split_debuginfo=") => {
156 let split_debuginfo = &s[30..];
157 let Ok(literal) = split_debuginfo.parse::<Literal>() else {
158 panic!("expect a string literal, found: {split_debuginfo}");
159 };
160 let literal = literal.to_string();
161 let Some(split_debuginfo) = literal
162 .strip_prefix('"')
163 .and_then(|lit| lit.strip_suffix('"'))
164 else {
165 panic!("expect a quoted string literal, found: {literal}");
166 };
167 set_ignore!(
168 !host_supports_split_debuginfo(split_debuginfo),
169 "host rustc does not support -Csplit-debuginfo={split_debuginfo}"
170 );
171 }
172 s if s.starts_with(">=1.") => {
173 requires_reason = true;
174 let min_minor = s[4..].parse().unwrap();
175 let minor = version().0;
176 set_ignore!(minor < min_minor, "requires rustc 1.{minor} or newer");
177 }
178 s if s.starts_with("reason=") => {
179 explicit_reason = Some(s[7..].parse().unwrap());
180 }
181 s if s.starts_with("ignore_windows=") => {
182 set_ignore!(cfg!(windows), "{}", &s[16..s.len() - 1]);
183 }
184 _ => panic!("unknown rule {:?}", rule),
185 }
186 }
187 if requires_reason && explicit_reason.is_none() {
188 panic!(
189 "#[cargo_test] with a rule also requires a reason, \
190 such as #[cargo_test(nightly, reason = \"needs -Z unstable-thing\")]"
191 );
192 }
193
194 let span = Span::call_site();
196 let mut ret = TokenStream::new();
197 let add_attr = |ret: &mut TokenStream, attr_name, attr_input| {
198 ret.extend(Some(TokenTree::from(Punct::new('#', Spacing::Alone))));
199 let attr = TokenTree::from(Ident::new(attr_name, span));
200 let mut attr_stream: TokenStream = attr.into();
201 if let Some(input) = attr_input {
202 attr_stream.extend(input);
203 }
204 ret.extend(Some(TokenTree::from(Group::new(
205 Delimiter::Bracket,
206 attr_stream,
207 ))));
208 };
209 add_attr(&mut ret, "test", None);
210 if ignore {
211 let reason = explicit_reason
212 .or_else(|| {
213 (!implicit_reasons.is_empty())
214 .then(|| TokenTree::from(Literal::string(&implicit_reasons.join(", "))).into())
215 })
216 .map(|reason: TokenStream| {
217 let mut stream = TokenStream::new();
218 stream.extend(Some(TokenTree::from(Punct::new('=', Spacing::Alone))));
219 stream.extend(Some(reason));
220 stream
221 });
222 add_attr(&mut ret, "ignore", reason);
223 }
224
225 let mut test_name = None;
226 let mut num = 0;
227
228 for token in item {
230 let group = match token {
231 TokenTree::Group(g) => {
232 if g.delimiter() == Delimiter::Brace {
233 g
234 } else {
235 ret.extend(Some(TokenTree::Group(g)));
236 continue;
237 }
238 }
239 TokenTree::Ident(i) => {
240 if test_name.is_none() && num == 1 {
243 test_name = Some(i.to_string())
244 } else {
245 num += 1;
246 }
247 ret.extend(Some(TokenTree::Ident(i)));
248 continue;
249 }
250 other => {
251 ret.extend(Some(other));
252 continue;
253 }
254 };
255
256 let name = &test_name
257 .clone()
258 .map(|n| n.split("::").next().unwrap().to_string())
259 .unwrap();
260
261 let mut new_body = to_token_stream(&format!(
262 r#"let _test_guard = {{
263 let tmp_dir = env!("CARGO_TARGET_TMPDIR");
264 let test_dir = cargo_test_support::paths::test_dir(std::file!(), "{name}");
265 cargo_test_support::paths::init_root(tmp_dir, test_dir)
266 }};"#
267 ));
268
269 new_body.extend(group.stream());
270 ret.extend(Some(TokenTree::from(Group::new(
271 group.delimiter(),
272 new_body,
273 ))));
274 }
275
276 ret
277}
278
279fn split_rules(t: TokenStream) -> Vec<String> {
280 let tts: Vec<_> = t.into_iter().collect();
281 tts.split(|tt| match tt {
282 TokenTree::Punct(p) => p.as_char() == ',',
283 _ => false,
284 })
285 .filter(|parts| !parts.is_empty())
286 .map(|parts| {
287 parts
288 .into_iter()
289 .map(|part| part.to_string())
290 .collect::<String>()
291 })
292 .collect()
293}
294
295fn to_token_stream(code: &str) -> TokenStream {
296 code.parse().unwrap()
297}
298
299static VERSION: std::sync::LazyLock<(u32, bool)> = LazyLock::new(|| {
300 let output = Command::new("rustc")
301 .arg("-V")
302 .output()
303 .expect("rustc should run");
304
305 let exit_code = output.status.code();
306
307 if exit_code != Some(0) {
308 let stdout = std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>");
309 let stderr = std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>");
310 let extra = if exit_code.map(|c| c as u32) == Some(0xC0000017) {
315 "This likely indicates that PATH is too large for Windows.\n"
316 } else {
317 ""
318 };
319 panic!(
320 "'rustc -V' exited with non-zero exit code: {exit_code:?}\n{extra}stdout: {stdout}\nstderr: {stderr}",
321 );
322 }
323
324 let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
325 let vers = stdout
326 .split_whitespace()
327 .skip(1)
328 .next()
329 .expect("version should have contain at least one space");
330 let is_nightly = option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_none()
331 && (vers.contains("-nightly") || vers.contains("-dev"));
332 let minor = vers
333 .split('.')
334 .skip(1)
335 .next()
336 .expect("malformed rustc version (not semver)")
337 .parse()
338 .expect("malformed rustc version (minor version was not u32)");
339 (minor, is_nightly)
340});
341
342fn version() -> (u32, bool) {
343 LazyLock::force(&VERSION).clone()
344}
345
346fn host_supports_split_debuginfo(split_debuginfo: &str) -> bool {
347 static SPLIT_DEBUGINFO: LazyLock<Vec<String>> = LazyLock::new(|| {
348 let output = Command::new("rustc")
349 .arg("--print=split-debuginfo")
350 .output()
351 .expect("rustc should run");
352
353 let exit_code = output.status.code();
354 if exit_code != Some(0) {
355 let stdout = std::str::from_utf8(&output.stdout).unwrap_or("<invalid utf8>");
356 let stderr = std::str::from_utf8(&output.stderr).unwrap_or("<invalid utf8>");
357 panic!(
358 "'rustc --print=split-debuginfo' exited with non-zero exit code: {exit_code:?}\n\
359 stdout: {stdout}\n\
360 stderr: {stderr}",
361 );
362 }
363
364 let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
365 stdout.lines().map(str::to_owned).collect()
366 });
367
368 SPLIT_DEBUGINFO
369 .iter()
370 .any(|supported| supported == split_debuginfo)
371}
372
373fn check_command(command_path: &Path, args: &[&str]) -> bool {
374 let mut command = Command::new(command_path);
375 let command_name = command.get_program().to_str().unwrap().to_owned();
376 command.args(args);
377 let output = match command.output() {
378 Ok(output) => output,
379 Err(e) => {
380 if is_ci() {
381 panic!("expected command `{command_name}` to be somewhere in PATH: {e}",);
382 }
383 return false;
384 }
385 };
386 if !output.status.success() {
387 panic!(
388 "expected command `{command_name}` to be runnable, got error {}:\n\
389 stderr:{}\n\
390 stdout:{}\n",
391 output.status,
392 String::from_utf8_lossy(&output.stderr),
393 String::from_utf8_lossy(&output.stdout)
394 );
395 }
396 true
397}
398
399fn has_command(command: &str) -> bool {
400 use std::env::consts::EXE_EXTENSION;
401 #[allow(clippy::disallowed_methods)]
403 let Some(paths) = std::env::var_os("PATH") else {
404 return false;
405 };
406 let found = std::env::split_paths(&paths)
407 .flat_map(|path| {
408 let candidate = path.join(&command);
409 let with_exe = if EXE_EXTENSION.is_empty() {
410 None
411 } else {
412 Some(candidate.with_extension(EXE_EXTENSION))
413 };
414 std::iter::once(candidate).chain(with_exe)
415 })
416 .find(|p| is_executable(p))
417 .is_some();
418 if !found && requires_external_tools() && command != "hg" {
422 panic!("expected command `{command}` to be somewhere in PATH");
423 }
424 found
425}
426
427#[cfg(unix)]
428fn is_executable<P: AsRef<Path>>(path: P) -> bool {
429 use std::os::unix::prelude::*;
430 std::fs::metadata(path)
431 .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
432 .unwrap_or(false)
433}
434
435#[cfg(windows)]
436fn is_executable<P: AsRef<Path>>(path: P) -> bool {
437 path.as_ref().is_file()
438}
439
440fn has_rustup_stable() -> bool {
441 if option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_some() {
442 return false;
444 }
445 check_command(
446 Path::new("rustup"),
447 &["run", "stable", "cargo", "--version"],
448 )
449}
450
451fn is_ci() -> bool {
453 option_env!("CI").is_some() || option_env!("TF_BUILD").is_some()
457}
458
459fn requires_external_tools() -> bool {
461 option_env!("CARGO_TEST_REQUIRE_EXTERNAL_TOOLS").is_some()
462}