Test whether the rustc at `var("RUSTC")` can compile the given code.
(test: T)
| 42 | |
| 43 | /// Test whether the rustc at `var("RUSTC")` can compile the given code. |
| 44 | fn can_compile<T: AsRef<str>>(test: T) -> bool { |
| 45 | use std::process::Stdio; |
| 46 | |
| 47 | let rustc = var("RUSTC").unwrap(); |
| 48 | let target = var("TARGET").unwrap(); |
| 49 | |
| 50 | // Use `RUSTC_WRAPPER` if it's set, unless it's set to an empty string, as |
| 51 | // documented [here]. |
| 52 | // [here]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-reads |
| 53 | let wrapper = var("RUSTC_WRAPPER") |
| 54 | .ok() |
| 55 | .and_then(|w| if w.is_empty() { None } else { Some(w) }); |
| 56 | |
| 57 | let mut cmd = if let Some(wrapper) = wrapper { |
| 58 | let mut cmd = std::process::Command::new(wrapper); |
| 59 | // The wrapper's first argument is supposed to be the path to rustc. |
| 60 | cmd.arg(rustc); |
| 61 | cmd |
| 62 | } else { |
| 63 | std::process::Command::new(rustc) |
| 64 | }; |
| 65 | |
| 66 | cmd.arg("--crate-type=rlib") // Don't require `main`. |
| 67 | .arg("--emit=metadata") // Do as little as possible but still parse. |
| 68 | .arg("--target") |
| 69 | .arg(target) |
| 70 | .arg("-o") |
| 71 | .arg("-") |
| 72 | .stdout(Stdio::null()); // We don't care about the output (only whether it builds or not) |
| 73 | |
| 74 | // If Cargo wants to set RUSTFLAGS, use that. |
| 75 | if let Ok(rustflags) = var("CARGO_ENCODED_RUSTFLAGS") { |
| 76 | if !rustflags.is_empty() { |
| 77 | for arg in rustflags.split('\x1f') { |
| 78 | cmd.arg(arg); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | let mut child = cmd |
| 84 | .arg("-") // Read from stdin. |
| 85 | .stdin(Stdio::piped()) // Stdin is a pipe. |
| 86 | .stderr(Stdio::null()) // Errors from feature detection aren't interesting and can be confusing. |
| 87 | .spawn() |
| 88 | .unwrap(); |
| 89 | |
| 90 | writeln!(child.stdin.take().unwrap(), "{}", test.as_ref()).unwrap(); |
| 91 | |
| 92 | child.wait().unwrap().success() |
| 93 | } |