Merge pull request #713 from GuillaumeGomez/fix-warnings

Fix fuzz warnings and deny warnings by default in build system
This commit is contained in:
antoyo 2025-06-16 11:55:20 -04:00 committed by GitHub
commit fda0bb9588
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 204 additions and 180 deletions

View file

@ -82,9 +82,20 @@ jobs:
#path: rust
#key: ${{ runner.os }}-packages-${{ hashFiles('rust/.git/HEAD') }}
- name: Prepare
run: ./y.sh prepare --only-libcore
- name: Check formatting
run: ./y.sh fmt --check
- name: clippy
run: |
cargo clippy --all-targets -- -D warnings
cargo clippy --all-targets --no-default-features -- -D warnings
cargo clippy --manifest-path build_system/Cargo.toml --all-targets -- -D warnings
- name: Build
run: |
./y.sh prepare --only-libcore
./y.sh build --sysroot
./y.sh test --cargo-tests
@ -106,14 +117,6 @@ jobs:
run: |
./y.sh test --release --clean --build-sysroot ${{ matrix.commands }}
- name: Check formatting
run: ./y.sh fmt --check
- name: clippy
run: |
cargo clippy --all-targets -- -D warnings
cargo clippy --all-targets --features master -- -D warnings
duplicates:
runs-on: ubuntu-24.04
steps:

View file

@ -81,6 +81,18 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "getrandom"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi",
]
[[package]]
name = "hermit-abi"
version = "0.3.1"
@ -111,9 +123,9 @@ checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d"
[[package]]
name = "linux-raw-sys"
version = "0.4.14"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
[[package]]
name = "memchr"
@ -137,6 +149,12 @@ version = "1.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
[[package]]
name = "r-efi"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
[[package]]
name = "regex"
version = "1.8.4"
@ -166,9 +184,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "0.38.42"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266"
dependencies = [
"bitflags",
"errno",
@ -188,12 +206,12 @@ dependencies = [
[[package]]
name = "tempfile"
version = "3.14.0"
version = "3.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c"
checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1"
dependencies = [
"cfg-if",
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
@ -242,6 +260,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "winapi"
version = "0.3.9"
@ -345,3 +372,12 @@ name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]

View file

@ -31,7 +31,7 @@ gccjit = "2.7"
[dev-dependencies]
boml = "0.3.1"
lang_tester = "0.8.0"
tempfile = "3.7.1"
tempfile = "3.20"
[profile.dev]
# By compiling dependencies with optimizations, performing tests gets much faster.

View file

@ -33,7 +33,7 @@ impl BuildArg {
}
arg => {
if !build_arg.config_info.parse_argument(arg, &mut args)? {
return Err(format!("Unknown argument `{}`", arg));
return Err(format!("Unknown argument `{arg}`"));
}
}
}
@ -105,14 +105,14 @@ pub fn create_build_sysroot_content(start_dir: &Path) -> Result<(), String> {
if !start_dir.is_dir() {
create_dir(start_dir)?;
}
copy_file("build_system/build_sysroot/Cargo.toml", &start_dir.join("Cargo.toml"))?;
copy_file("build_system/build_sysroot/Cargo.lock", &start_dir.join("Cargo.lock"))?;
copy_file("build_system/build_sysroot/Cargo.toml", start_dir.join("Cargo.toml"))?;
copy_file("build_system/build_sysroot/Cargo.lock", start_dir.join("Cargo.lock"))?;
let src_dir = start_dir.join("src");
if !src_dir.is_dir() {
create_dir(&src_dir)?;
}
copy_file("build_system/build_sysroot/lib.rs", &start_dir.join("src/lib.rs"))
copy_file("build_system/build_sysroot/lib.rs", start_dir.join("src/lib.rs"))
}
pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Result<(), String> {
@ -169,7 +169,7 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
run_command(&[&"cp", &"-r", &dir_to_copy, &sysroot_path], None).map(|_| ())
};
walk_dir(
start_dir.join(&format!("target/{}/{}/deps", config.target_triple, channel)),
start_dir.join(format!("target/{}/{}/deps", config.target_triple, channel)),
&mut copier.clone(),
&mut copier,
false,

View file

@ -17,12 +17,12 @@ enum CleanArg {
impl CleanArg {
fn new() -> Result<Self, String> {
// We skip the binary and the "clean" option.
for arg in std::env::args().skip(2) {
if let Some(arg) = std::env::args().nth(2) {
return match arg.as_str() {
"all" => Ok(Self::All),
"ui-tests" => Ok(Self::UiTests),
"--help" => Ok(Self::Help),
a => Err(format!("Unknown argument `{}`", a)),
a => Err(format!("Unknown argument `{a}`")),
};
}
Ok(Self::default())

View file

@ -43,7 +43,7 @@ impl Args {
}
arg => {
if !command_args.config_info.parse_argument(arg, &mut args)? {
return Err(format!("Unknown option {}", arg));
return Err(format!("Unknown option {arg}"));
}
}
}
@ -52,7 +52,7 @@ impl Args {
Some(p) => p.into(),
None => PathBuf::from("./gcc"),
};
return Ok(Some(command_args));
Ok(Some(command_args))
}
}
@ -64,7 +64,7 @@ pub fn run() -> Result<(), String> {
let result = git_clone("https://github.com/rust-lang/gcc", Some(&args.out_path), false)?;
if result.ran_clone {
let gcc_commit = args.config_info.get_gcc_commit()?;
println!("Checking out GCC commit `{}`...", gcc_commit);
println!("Checking out GCC commit `{gcc_commit}`...");
run_command_with_output(
&[&"git", &"checkout", &gcc_commit],
Some(Path::new(&result.repo_dir)),

View file

@ -66,7 +66,7 @@ impl ConfigFile {
"Expected a boolean for `download-gccjit`",
);
}
_ => return failed_config_parsing(config_file, &format!("Unknown key `{}`", key)),
_ => return failed_config_parsing(config_file, &format!("Unknown key `{key}`")),
}
}
match (config.gcc_path.as_mut(), config.download_gccjit) {
@ -86,9 +86,7 @@ impl ConfigFile {
let path = Path::new(gcc_path);
*gcc_path = path
.canonicalize()
.map_err(|err| {
format!("Failed to get absolute path of `{}`: {:?}", gcc_path, err)
})?
.map_err(|err| format!("Failed to get absolute path of `{gcc_path}`: {err:?}"))?
.display()
.to_string();
}
@ -175,7 +173,7 @@ impl ConfigInfo {
"--sysroot-panic-abort" => self.sysroot_panic_abort = true,
"--gcc-path" => match args.next() {
Some(arg) if !arg.is_empty() => {
self.gcc_path = Some(arg.into());
self.gcc_path = Some(arg);
}
_ => {
return Err("Expected a value after `--gcc-path`, found nothing".to_string());
@ -244,7 +242,7 @@ impl ConfigInfo {
let libgccjit_so = output_dir.join(libgccjit_so_name);
if !libgccjit_so.is_file() && !self.no_download {
// Download time!
let tempfile_name = format!("{}.download", libgccjit_so_name);
let tempfile_name = format!("{libgccjit_so_name}.download");
let tempfile = output_dir.join(&tempfile_name);
let is_in_ci = std::env::var("GITHUB_ACTIONS").is_ok();
@ -262,14 +260,14 @@ impl ConfigInfo {
)
})?;
println!("Downloaded libgccjit.so version {} successfully!", commit);
println!("Downloaded libgccjit.so version {commit} successfully!");
// We need to create a link named `libgccjit.so.0` because that's what the linker is
// looking for.
create_symlink(&libgccjit_so, output_dir.join(&format!("{}.0", libgccjit_so_name)))?;
create_symlink(&libgccjit_so, output_dir.join(format!("{libgccjit_so_name}.0")))?;
}
let gcc_path = output_dir.display().to_string();
println!("Using `{}` as path for libgccjit", gcc_path);
println!("Using `{gcc_path}` as path for libgccjit");
self.gcc_path = Some(gcc_path);
Ok(())
}
@ -286,8 +284,7 @@ impl ConfigInfo {
// since we already have everything we need.
if let Some(gcc_path) = &self.gcc_path {
println!(
"`--gcc-path` was provided, ignoring config file. Using `{}` as path for libgccjit",
gcc_path
"`--gcc-path` was provided, ignoring config file. Using `{gcc_path}` as path for libgccjit"
);
return Ok(());
}
@ -343,7 +340,7 @@ impl ConfigInfo {
self.dylib_ext = match os_name.as_str() {
"Linux" => "so",
"Darwin" => "dylib",
os => return Err(format!("unsupported OS `{}`", os)),
os => return Err(format!("unsupported OS `{os}`")),
}
.to_string();
let rustc = match env.get("RUSTC") {
@ -355,10 +352,10 @@ impl ConfigInfo {
None => return Err("no host found".to_string()),
};
if self.target_triple.is_empty() {
if let Some(overwrite) = env.get("OVERWRITE_TARGET_TRIPLE") {
self.target_triple = overwrite.clone();
}
if self.target_triple.is_empty()
&& let Some(overwrite) = env.get("OVERWRITE_TARGET_TRIPLE")
{
self.target_triple = overwrite.clone();
}
if self.target_triple.is_empty() {
self.target_triple = self.host_triple.clone();
@ -378,7 +375,7 @@ impl ConfigInfo {
}
let current_dir =
std_env::current_dir().map_err(|error| format!("`current_dir` failed: {:?}", error))?;
std_env::current_dir().map_err(|error| format!("`current_dir` failed: {error:?}"))?;
let channel = if self.channel == Channel::Release {
"release"
} else if let Some(channel) = env.get("CHANNEL") {
@ -391,15 +388,15 @@ impl ConfigInfo {
self.cg_backend_path = current_dir
.join("target")
.join(channel)
.join(&format!("librustc_codegen_gcc.{}", self.dylib_ext))
.join(format!("librustc_codegen_gcc.{}", self.dylib_ext))
.display()
.to_string();
self.sysroot_path =
current_dir.join(&get_sysroot_dir()).join("sysroot").display().to_string();
current_dir.join(get_sysroot_dir()).join("sysroot").display().to_string();
if let Some(backend) = &self.backend {
// This option is only used in the rust compiler testsuite. The sysroot is handled
// by its build system directly so no need to set it ourselves.
rustflags.push(format!("-Zcodegen-backend={}", backend));
rustflags.push(format!("-Zcodegen-backend={backend}"));
} else {
rustflags.extend_from_slice(&[
"--sysroot".to_string(),
@ -412,10 +409,10 @@ impl ConfigInfo {
// We have a different environment variable than RUSTFLAGS to make sure those flags are
// only sent to rustc_codegen_gcc and not the LLVM backend.
if let Some(cg_rustflags) = env.get("CG_RUSTFLAGS") {
rustflags.extend_from_slice(&split_args(&cg_rustflags)?);
rustflags.extend_from_slice(&split_args(cg_rustflags)?);
}
if let Some(test_flags) = env.get("TEST_FLAGS") {
rustflags.extend_from_slice(&split_args(&test_flags)?);
rustflags.extend_from_slice(&split_args(test_flags)?);
}
if let Some(linker) = linker {
@ -438,8 +435,8 @@ impl ConfigInfo {
env.insert("RUSTC_LOG".to_string(), "warn".to_string());
let sysroot = current_dir
.join(&get_sysroot_dir())
.join(&format!("sysroot/lib/rustlib/{}/lib", self.target_triple));
.join(get_sysroot_dir())
.join(format!("sysroot/lib/rustlib/{}/lib", self.target_triple));
let ld_library_path = format!(
"{target}:{sysroot}:{gcc_path}",
target = self.cargo_target_dir,
@ -505,7 +502,7 @@ fn download_gccjit(
with_progress_bar: bool,
) -> Result<(), String> {
let url = if std::env::consts::OS == "linux" && std::env::consts::ARCH == "x86_64" {
format!("https://github.com/rust-lang/gcc/releases/download/master-{}/libgccjit.so", commit)
format!("https://github.com/rust-lang/gcc/releases/download/master-{commit}/libgccjit.so")
} else {
eprintln!(
"\
@ -518,7 +515,7 @@ to `download-gccjit = false` and set `gcc-path` to the appropriate directory."
));
};
println!("Downloading `{}`...", url);
println!("Downloading `{url}`...");
// Try curl. If that fails and we are on windows, fallback to PowerShell.
let mut ret = run_command_with_output(
@ -538,7 +535,7 @@ to `download-gccjit = false` and set `gcc-path` to the appropriate directory."
if with_progress_bar { &"--progress-bar" } else { &"-s" },
&url.as_str(),
],
Some(&output_dir),
Some(output_dir),
);
if ret.is_err() && cfg!(windows) {
eprintln!("Fallback to PowerShell");
@ -549,12 +546,11 @@ to `download-gccjit = false` and set `gcc-path` to the appropriate directory."
&"-Command",
&"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;",
&format!(
"(New-Object System.Net.WebClient).DownloadFile('{}', '{}')",
url, tempfile_name,
"(New-Object System.Net.WebClient).DownloadFile('{url}', '{tempfile_name}')",
)
.as_str(),
],
Some(&output_dir),
Some(output_dir),
);
}
ret

View file

@ -16,21 +16,21 @@ fn show_usage() {
pub fn run() -> Result<(), String> {
let mut check = false;
// We skip binary name and the `info` command.
let mut args = std::env::args().skip(2);
while let Some(arg) = args.next() {
let args = std::env::args().skip(2);
for arg in args {
match arg.as_str() {
"--help" => {
show_usage();
return Ok(());
}
"--check" => check = true,
_ => return Err(format!("Unknown option {}", arg)),
_ => return Err(format!("Unknown option {arg}")),
}
}
let cmd: &[&dyn AsRef<OsStr>] =
if check { &[&"cargo", &"fmt", &"--check"] } else { &[&"cargo", &"fmt"] };
run_command_with_output(cmd, Some(&Path::new(".")))?;
run_command_with_output(cmd, Some(&Path::new("build_system")))
run_command_with_output(cmd, Some(Path::new(".")))?;
run_command_with_output(cmd, Some(Path::new("build_system")))
}

View file

@ -56,7 +56,7 @@ pub fn run() -> Result<(), String> {
)
.map_err(|err| (format!("Fuzz thread count not a number {err:?}!")))?;
}
_ => return Err(format!("Unknown option {}", arg)),
_ => return Err(format!("Unknown option {arg}")),
}
}
@ -70,11 +70,11 @@ pub fn run() -> Result<(), String> {
// Ensure that we are on the newest rustlantis commit.
let cmd: &[&dyn AsRef<OsStr>] = &[&"git", &"pull", &"origin"];
run_command_with_output(cmd, Some(&Path::new("clones/rustlantis")))?;
run_command_with_output(cmd, Some(Path::new("clones/rustlantis")))?;
// Build the release version of rustlantis
let cmd: &[&dyn AsRef<OsStr>] = &[&"cargo", &"build", &"--release"];
run_command_with_output(cmd, Some(&Path::new("clones/rustlantis")))?;
run_command_with_output(cmd, Some(Path::new("clones/rustlantis")))?;
// Fuzz a given range
fuzz_range(start, start + count, threads);
Ok(())
@ -104,13 +104,13 @@ fn fuzz_range(start: u64, end: u64, threads: usize) {
match test(next, false) {
Err(err) => {
// If the test failed at compile-time...
println!("test({}) failed because {err:?}", next);
println!("test({next}) failed because {err:?}");
// ... copy that file to the directory `target/fuzz/compiletime_error`...
let mut out_path: std::path::PathBuf =
"target/fuzz/compiletime_error".into();
std::fs::create_dir_all(&out_path).unwrap();
// .. into a file named `fuzz{seed}.rs`.
out_path.push(&format!("fuzz{next}.rs"));
out_path.push(format!("fuzz{next}.rs"));
std::fs::copy(err, out_path).unwrap();
}
Ok(Err(err)) => {
@ -122,12 +122,12 @@ fn fuzz_range(start: u64, end: u64, threads: usize) {
let Ok(Err(tmp_print_err)) = test(next, true) else {
// ... if that file does not reproduce the issue...
// ... save the original sample in a file named `fuzz{seed}.rs`...
out_path.push(&format!("fuzz{next}.rs"));
out_path.push(format!("fuzz{next}.rs"));
std::fs::copy(err, &out_path).unwrap();
continue;
};
// ... if that new file still produces the issue, copy it to `fuzz{seed}.rs`..
out_path.push(&format!("fuzz{next}.rs"));
out_path.push(format!("fuzz{next}.rs"));
std::fs::copy(tmp_print_err, &out_path).unwrap();
// ... and start reducing it, using some properties of `rustlantis` to speed up the process.
reduce::reduce(&out_path);
@ -240,10 +240,10 @@ fn test_cached(
cache: &mut ResultCache,
) -> Result<Result<(), std::path::PathBuf>, String> {
// Test `source_file` with release GCC ...
let gcc_res = release_gcc(&source_file)?;
let gcc_res = release_gcc(source_file)?;
if cache.is_none() {
// ...test `source_file` with debug LLVM ...
*cache = Some((debug_llvm(&source_file)?, gcc_res.clone()));
*cache = Some((debug_llvm(source_file)?, gcc_res.clone()));
}
let (llvm_res, old_gcc) = cache.as_ref().unwrap();
// ... compare the results ...
@ -269,12 +269,12 @@ fn test_file(
fn generate(seed: u64, print_tmp_vars: bool) -> Result<std::path::PathBuf, String> {
use std::io::Write;
let mut out_path = std::env::temp_dir();
out_path.push(&format!("fuzz{seed}.rs"));
out_path.push(format!("fuzz{seed}.rs"));
// We need to get the command output here.
let mut generate = std::process::Command::new("cargo");
generate
.args(["run", "--release", "--bin", "generate"])
.arg(&format!("{seed}"))
.arg(format!("{seed}"))
.current_dir("clones/rustlantis");
if print_tmp_vars {
generate.arg("--debug");

View file

@ -4,9 +4,9 @@ use std::path::{Path, PathBuf};
use super::ResultCache;
/// Saves a reduced file for a given `stage`
fn save_reduction(lines: &[String], path: &PathBuf, stage: &str) {
let mut path = path.clone();
path.set_extension(&format!("rs.{stage}"));
fn save_reduction(lines: &[String], path: &Path, stage: &str) {
let mut path = path.to_path_buf();
path.set_extension(format!("rs.{stage}"));
let mut file = std::fs::File::create(&path).expect("Could not create the reduced example file");
for line in lines {
file.write_all(line.as_bytes()).expect("Could not save the reduced example");
@ -14,8 +14,8 @@ fn save_reduction(lines: &[String], path: &PathBuf, stage: &str) {
}
/// Checks if a given reduction is valid.
fn test_reduction(lines: &[String], path: &PathBuf, cache: &mut ResultCache) -> bool {
let mut path = path.clone();
fn test_reduction(lines: &[String], path: &Path, cache: &mut ResultCache) -> bool {
let mut path = path.to_path_buf();
path.set_extension("rs_reduced");
let mut file = std::fs::File::create(&path).expect("Could not create the reduced example file");
for line in lines {
@ -25,7 +25,7 @@ fn test_reduction(lines: &[String], path: &PathBuf, cache: &mut ResultCache) ->
let Ok(Err(_)) = res else {
return false;
};
return true;
true
}
/// Removes duplicate assignments in bulk.
@ -39,7 +39,6 @@ fn remove_dup_assign(
ends: usize,
cache: &mut ResultCache,
) {
let mut curr = 0;
let mut file_copy = file.clone();
let mut reduction_count = 0;
// Not worth it.
@ -74,8 +73,8 @@ fn remove_dup_assign(
return;
}
// Check if the removed lines affected the execution result in any way, shape or form.
if test_reduction(&file_copy, &path, cache) {
println!("Reduced {path:?} by {} lines `remove_dup_assign`", reduction_count);
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by {reduction_count} lines `remove_dup_assign`");
*file = file_copy;
} else {
// The execution result changed.
@ -111,7 +110,7 @@ fn remove_dump_var(file: &mut Vec<String>, path: &PathBuf) {
// Not cached - the execution result can change.
let mut uncached = None;
// Check if this reduction is valid.
if test_reduction(&file_copy, &path, &mut uncached) {
if test_reduction(&file_copy, path, &mut uncached) {
println!("Reduced {path:?} by 3 lines `remove_dump_var`");
*file = file_copy;
curr = line;
@ -161,7 +160,7 @@ fn match_to_goto(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCache
file_copy.remove(match_starts);
}
file_copy.insert(match_starts, format!("Goto(bb{bb_ident})\n"));
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by {} lines `match_to_goto`", match_ends - match_starts);
*file = file_copy;
curr = match_starts;
@ -204,11 +203,12 @@ fn block_abort(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCache)
// ..and insert an unconditional call to abort.
file_copy.insert(
block_starts,
format!("Call(tmp = core::intrinsics::abort(), ReturnTo(bb1), UnwindUnreachable())\n"),
"Call(tmp = core::intrinsics::abort(), ReturnTo(bb1), UnwindUnreachable())\n"
.to_string(),
);
file_copy.insert(block_starts, format!("let tmp = ();\n"));
file_copy.insert(block_starts, "let tmp = ();\n".to_string());
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by {} lines `block_abort`", block_ends - block_starts - 2);
*file = file_copy;
curr = block_starts;
@ -249,7 +249,7 @@ fn remove_block(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCache)
}
let mut file_copy = file.clone();
file_copy.drain(block_starts..block_ends);
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by {} lines `remove_blocks`", block_ends - block_starts);
*file = file_copy;
curr = block_starts;
@ -296,7 +296,7 @@ fn linearize_cf(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCache)
file_copy.remove(block_starts - 2);
file_copy.remove(block_starts - 2);
// Check if this reduction is valid.
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by 3 lines `linearize_cf`");
*file = file_copy;
curr = block_starts;
@ -346,7 +346,7 @@ fn remove_fn_calls(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCac
file_copy.insert(fn_call, format!("Goto({block})\n"));
file_copy.insert(fn_call, format!("{place} = 0;\n"));
// Check if this reduction is valid.
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} using `remove_fn_calls` {cache:?}");
*file = file_copy;
curr = fn_call;
@ -383,7 +383,7 @@ fn remove_fns(file: &mut Vec<String>, path: &PathBuf, cache: &mut ResultCache) {
// Remove the function.\\
file_copy.drain(fn_start..fn_end);
// Check if this reduction is valid.
if test_reduction(&file_copy, &path, cache) {
if test_reduction(&file_copy, path, cache) {
println!("Reduced {path:?} by {} lines `remove_fns`", fn_end - fn_start);
*file = file_copy;
} else {
@ -427,7 +427,6 @@ pub(super) fn reduce(path: impl AsRef<Path>) {
println!("running `linearize_cf` on {path:?}.");
linearize_cf(&mut file, &path, &mut cache);
let mut out = std::fs::File::create(&path).expect("Could not save the reduction result.");
for line in file {
out.write_all(line.as_bytes());
}
let file = file.into_iter().collect::<String>();
out.write_all(file.as_bytes()).expect("failed to write into file");
}

View file

@ -15,7 +15,7 @@ pub fn run() -> Result<(), String> {
config.no_download = true;
config.setup_gcc_path()?;
if let Some(gcc_path) = config.gcc_path {
println!("{}", gcc_path);
println!("{gcc_path}");
}
Ok(())
}

View file

@ -18,9 +18,9 @@ fn prepare_libcore(
if let Some(path) = sysroot_source {
rustlib_dir = Path::new(&path)
.canonicalize()
.map_err(|error| format!("Failed to canonicalize path: {:?}", error))?;
.map_err(|error| format!("Failed to canonicalize path: {error:?}"))?;
if !rustlib_dir.is_dir() {
return Err(format!("Custom sysroot path {:?} not found", rustlib_dir));
return Err(format!("Custom sysroot path {rustlib_dir:?} not found"));
}
} else {
let rustc_path = match get_rustc_path() {
@ -36,17 +36,17 @@ fn prepare_libcore(
rustlib_dir = parent
.join("../lib/rustlib/src/rust")
.canonicalize()
.map_err(|error| format!("Failed to canonicalize path: {:?}", error))?;
.map_err(|error| format!("Failed to canonicalize path: {error:?}"))?;
if !rustlib_dir.is_dir() {
return Err("Please install `rust-src` component".to_string());
}
}
let sysroot_dir = sysroot_path.join("sysroot_src");
if sysroot_dir.is_dir() {
if let Err(error) = fs::remove_dir_all(&sysroot_dir) {
return Err(format!("Failed to remove `{}`: {:?}", sysroot_dir.display(), error,));
}
if sysroot_dir.is_dir()
&& let Err(error) = fs::remove_dir_all(&sysroot_dir)
{
return Err(format!("Failed to remove `{}`: {:?}", sysroot_dir.display(), error,));
}
let sysroot_library_dir = sysroot_dir.join("library");
@ -122,7 +122,7 @@ fn prepare_rand() -> Result<(), String> {
// Apply patch for the rand crate.
let file_path = "patches/crates/0001-Remove-deny-warnings.patch";
let rand_dir = Path::new("build/rand");
println!("[GIT] apply `{}`", file_path);
println!("[GIT] apply `{file_path}`");
let path = Path::new("../..").join(file_path);
run_command_with_output(&[&"git", &"apply", &path], Some(rand_dir))?;
run_command_with_output(&[&"git", &"add", &"-A"], Some(rand_dir))?;
@ -149,7 +149,7 @@ fn clone_and_setup<F>(repo_url: &str, checkout_commit: &str, extra: Option<F>) -
where
F: Fn(&Path) -> Result<(), String>,
{
let clone_result = git_clone_root_dir(repo_url, &Path::new(crate::BUILD_DIR), false)?;
let clone_result = git_clone_root_dir(repo_url, Path::new(crate::BUILD_DIR), false)?;
if !clone_result.ran_clone {
println!("`{}` has already been cloned", clone_result.repo_name);
}

View file

@ -9,15 +9,14 @@ use crate::utils::{get_toolchain, rustc_toolchain_version_info, rustc_version_in
fn args(command: &str) -> Result<Option<Vec<String>>, String> {
// We skip the binary and the "cargo"/"rustc" option.
if let Some("--help") = std::env::args().skip(2).next().as_deref() {
if let Some("--help") = std::env::args().nth(2).as_deref() {
usage(command);
return Ok(None);
}
let args = std::env::args().skip(2).collect::<Vec<_>>();
if args.is_empty() {
return Err(format!(
"Expected at least one argument for `{}` subcommand, found none",
command
"Expected at least one argument for `{command}` subcommand, found none"
));
}
Ok(Some(args))
@ -26,12 +25,11 @@ fn args(command: &str) -> Result<Option<Vec<String>>, String> {
fn usage(command: &str) {
println!(
r#"
`{}` command help:
`{command}` command help:
[args] : Arguments to be passed to the cargo command
--help : Show this help
"#,
command,
)
}
@ -50,10 +48,10 @@ impl RustcTools {
// expected.
let current_dir = std::env::current_dir()
.and_then(|path| path.canonicalize())
.map_err(|error| format!("Failed to get current directory path: {:?}", error))?;
.map_err(|error| format!("Failed to get current directory path: {error:?}"))?;
let current_exe = std::env::current_exe()
.and_then(|path| path.canonicalize())
.map_err(|error| format!("Failed to get current exe path: {:?}", error))?;
.map_err(|error| format!("Failed to get current exe path: {error:?}"))?;
let mut parent_dir =
current_exe.components().map(|comp| comp.as_os_str()).collect::<Vec<_>>();
// We run this script from "build_system/target/release/y", so we need to remove these elements.
@ -67,7 +65,7 @@ impl RustcTools {
));
}
}
let parent_dir = PathBuf::from(parent_dir.join(&OsStr::new("/")));
let parent_dir = PathBuf::from(parent_dir.join(OsStr::new("/")));
std::env::set_current_dir(&parent_dir).map_err(|error| {
format!("Failed to go to `{}` folder: {:?}", parent_dir.display(), error)
})?;
@ -91,7 +89,7 @@ impl RustcTools {
std::env::set_current_dir(&current_dir).map_err(|error| {
format!("Failed to go back to `{}` folder: {:?}", current_dir.display(), error)
})?;
let toolchain = format!("+{}", toolchain);
let toolchain = format!("+{toolchain}");
Ok(Some(Self { toolchain, args, env, config }))
}
}

View file

@ -53,9 +53,9 @@ fn get_number_after_arg(
match args.next() {
Some(nb) if !nb.is_empty() => match usize::from_str(&nb) {
Ok(nb) => Ok(nb),
Err(_) => Err(format!("Expected a number after `{}`, found `{}`", option, nb)),
Err(_) => Err(format!("Expected a number after `{option}`, found `{nb}`")),
},
_ => Err(format!("Expected a number after `{}`, found nothing", option)),
_ => Err(format!("Expected a number after `{option}`, found nothing")),
}
}
@ -76,8 +76,8 @@ fn show_usage() {
for (option, (doc, _)) in get_runners() {
// FIXME: Instead of using the hard-coded `23` value, better to compute it instead.
let needed_spaces = 23_usize.saturating_sub(option.len());
let spaces: String = std::iter::repeat(' ').take(needed_spaces).collect();
println!(" {}{}: {}", option, spaces, doc);
let spaces: String = std::iter::repeat_n(' ', needed_spaces).collect();
println!(" {option}{spaces}: {doc}");
}
println!(" --help : Show this help");
}
@ -139,7 +139,7 @@ impl TestArg {
test_arg.sysroot_features.push(feature);
}
_ => {
return Err(format!("Expected an argument after `{}`, found nothing", arg));
return Err(format!("Expected an argument after `{arg}`, found nothing"));
}
},
"--help" => {
@ -154,7 +154,7 @@ impl TestArg {
}
arg => {
if !test_arg.config_info.parse_argument(arg, &mut args)? {
return Err(format!("Unknown option {}", arg));
return Err(format!("Unknown option {arg}"));
}
}
}
@ -192,7 +192,7 @@ fn build_if_no_backend(env: &Env, args: &TestArg) -> Result<(), String> {
command.push(&"--release");
&tmp_env
} else {
&env
env
};
for flag in args.flags.iter() {
command.push(flag);
@ -252,7 +252,7 @@ fn mini_tests(env: &Env, args: &TestArg) -> Result<(), String> {
&"--target",
&args.config_info.target_triple,
]);
run_command_with_output_and_env(&command, None, Some(&env))?;
run_command_with_output_and_env(&command, None, Some(env))?;
// FIXME: create a function "display_if_not_quiet" or something along the line.
println!("[BUILD] example");
@ -264,7 +264,7 @@ fn mini_tests(env: &Env, args: &TestArg) -> Result<(), String> {
&"--target",
&args.config_info.target_triple,
]);
run_command_with_output_and_env(&command, None, Some(&env))?;
run_command_with_output_and_env(&command, None, Some(env))?;
// FIXME: create a function "display_if_not_quiet" or something along the line.
println!("[AOT] mini_core_hello_world");
@ -279,14 +279,14 @@ fn mini_tests(env: &Env, args: &TestArg) -> Result<(), String> {
&"--target",
&args.config_info.target_triple,
]);
run_command_with_output_and_env(&command, None, Some(&env))?;
run_command_with_output_and_env(&command, None, Some(env))?;
let command: &[&dyn AsRef<OsStr>] = &[
&Path::new(&args.config_info.cargo_target_dir).join("mini_core_hello_world"),
&"abc",
&"bcd",
];
maybe_run_command_in_vm(&command, env, args)?;
maybe_run_command_in_vm(command, env, args)?;
Ok(())
}
@ -512,19 +512,19 @@ fn setup_rustc(env: &mut Env, args: &TestArg) -> Result<PathBuf, String> {
let cargo = String::from_utf8(
run_command_with_env(&[&"rustup", &"which", &"cargo"], rust_dir, Some(env))?.stdout,
)
.map_err(|error| format!("Failed to retrieve cargo path: {:?}", error))
.map_err(|error| format!("Failed to retrieve cargo path: {error:?}"))
.and_then(|cargo| {
let cargo = cargo.trim().to_owned();
if cargo.is_empty() { Err(format!("`cargo` path is empty")) } else { Ok(cargo) }
if cargo.is_empty() { Err("`cargo` path is empty".to_string()) } else { Ok(cargo) }
})?;
let rustc = String::from_utf8(
run_command_with_env(&[&"rustup", &toolchain, &"which", &"rustc"], rust_dir, Some(env))?
.stdout,
)
.map_err(|error| format!("Failed to retrieve rustc path: {:?}", error))
.map_err(|error| format!("Failed to retrieve rustc path: {error:?}"))
.and_then(|rustc| {
let rustc = rustc.trim().to_owned();
if rustc.is_empty() { Err(format!("`rustc` path is empty")) } else { Ok(rustc) }
if rustc.is_empty() { Err("`rustc` path is empty".to_string()) } else { Ok(rustc) }
})?;
let llvm_filecheck = match run_command_with_env(
&[
@ -551,7 +551,7 @@ fn setup_rustc(env: &mut Env, args: &TestArg) -> Result<PathBuf, String> {
let file_path = rust_dir_path.join("config.toml");
std::fs::write(
&file_path,
&format!(
format!(
r#"change-id = 115898
[rust]
@ -590,7 +590,7 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> {
let codegen_backend_path = format!(
"{pwd}/target/{channel}/librustc_codegen_gcc.{dylib_ext}",
pwd = std::env::current_dir()
.map_err(|error| format!("`current_dir` failed: {:?}", error))?
.map_err(|error| format!("`current_dir` failed: {error:?}"))?
.display(),
channel = args.config_info.channel.as_str(),
dylib_ext = args.config_info.dylib_ext,
@ -645,11 +645,11 @@ where
F: Fn(&[&dyn AsRef<OsStr>], Option<&Path>, &Env) -> Result<(), String>,
{
let toolchain = get_toolchain()?;
let toolchain_arg = format!("+{}", toolchain);
let toolchain_arg = format!("+{toolchain}");
let rustc_version = String::from_utf8(
run_command_with_env(&[&args.config_info.rustc_command[0], &"-V"], cwd, Some(env))?.stdout,
)
.map_err(|error| format!("Failed to retrieve rustc version: {:?}", error))?;
.map_err(|error| format!("Failed to retrieve rustc version: {error:?}"))?;
let rustc_toolchain_version = String::from_utf8(
run_command_with_env(
&[&args.config_info.rustc_command[0], &toolchain_arg, &"-V"],
@ -658,20 +658,19 @@ where
)?
.stdout,
)
.map_err(|error| format!("Failed to retrieve rustc +toolchain version: {:?}", error))?;
.map_err(|error| format!("Failed to retrieve rustc +toolchain version: {error:?}"))?;
if rustc_version != rustc_toolchain_version {
eprintln!(
"rustc_codegen_gcc is built for `{}` but the default rustc version is `{}`.",
rustc_toolchain_version, rustc_version,
"rustc_codegen_gcc is built for `{rustc_toolchain_version}` but the default rustc version is `{rustc_version}`.",
);
eprintln!("Using `{}`.", rustc_toolchain_version);
eprintln!("Using `{rustc_toolchain_version}`.");
}
let mut env = env.clone();
let rustflags = env.get("RUSTFLAGS").cloned().unwrap_or_default();
env.insert("RUSTDOCFLAGS".to_string(), rustflags);
let mut cargo_command: Vec<&dyn AsRef<OsStr>> = vec![&"cargo", &toolchain_arg];
cargo_command.extend_from_slice(&command);
cargo_command.extend_from_slice(command);
callback(&cargo_command, cwd, &env)
}
@ -884,7 +883,7 @@ fn contains_ui_error_patterns(file_path: &Path, keep_lto_tests: bool) -> Result<
// Tests generating errors.
let file = File::open(file_path)
.map_err(|error| format!("Failed to read `{}`: {:?}", file_path.display(), error))?;
for line in BufReader::new(file).lines().filter_map(|line| line.ok()) {
for line in BufReader::new(file).lines().map_while(Result::ok) {
let line = line.trim();
if line.is_empty() {
continue;
@ -953,7 +952,7 @@ where
if !prepare_files_callback(&rust_path)? {
// FIXME: create a function "display_if_not_quiet" or something along the line.
println!("Keeping all {} tests", test_type);
println!("Keeping all {test_type} tests");
}
if test_type == "ui" {
@ -985,8 +984,7 @@ where
"borrowck",
"test-attrs",
]
.iter()
.any(|name| *name == dir_name)
.contains(&dir_name)
{
remove_dir_all(dir).map_err(|error| {
format!("Failed to remove folder `{}`: {:?}", dir.display(), error)
@ -1041,10 +1039,7 @@ where
if nb_parts > 0 {
let current_part = args.current_part.unwrap();
// FIXME: create a function "display_if_not_quiet" or something along the line.
println!(
"Splitting ui_test into {} parts (and running part {})",
nb_parts, current_part
);
println!("Splitting ui_test into {nb_parts} parts (and running part {current_part})");
let out = String::from_utf8(
run_command(
&[
@ -1062,7 +1057,7 @@ where
)?
.stdout,
)
.map_err(|error| format!("Failed to retrieve output of find command: {:?}", error))?;
.map_err(|error| format!("Failed to retrieve output of find command: {error:?}"))?;
let mut files = out
.split('\n')
.map(|line| line.trim())
@ -1082,7 +1077,7 @@ where
}
// FIXME: create a function "display_if_not_quiet" or something along the line.
println!("[TEST] rustc {} test suite", test_type);
println!("[TEST] rustc {test_type} test suite");
env.insert("COMPILETEST_FORCE_STAGE0".to_string(), "1".to_string());
let extra =
@ -1106,7 +1101,7 @@ where
&"always",
&"--stage",
&"0",
&format!("tests/{}", test_type),
&format!("tests/{test_type}"),
&"--compiletest-rustc-args",
&rustc_args,
],
@ -1182,7 +1177,7 @@ fn retain_files_callback<'a>(
run_command(
&[
&"find",
&format!("tests/{}", test_type),
&format!("tests/{test_type}"),
&"-mindepth",
&"1",
&"-type",
@ -1201,7 +1196,7 @@ fn retain_files_callback<'a>(
run_command(
&[
&"find",
&format!("tests/{}", test_type),
&format!("tests/{test_type}"),
&"-type",
&"f",
&"-name",
@ -1216,15 +1211,12 @@ fn retain_files_callback<'a>(
}
// Putting back only the failing ones.
if let Ok(files) = std::fs::read_to_string(&file_path) {
if let Ok(files) = std::fs::read_to_string(file_path) {
for file in files.split('\n').map(|line| line.trim()).filter(|line| !line.is_empty()) {
run_command(&[&"git", &"checkout", &"--", &file], Some(&rust_path))?;
run_command(&[&"git", &"checkout", &"--", &file], Some(rust_path))?;
}
} else {
println!(
"Failed to read `{}`, not putting back failing {} tests",
file_path, test_type
);
println!("Failed to read `{file_path}`, not putting back failing {test_type} tests");
}
Ok(true)
@ -1252,8 +1244,7 @@ fn remove_files_callback<'a>(
}
} else {
println!(
"Failed to read `{}`, not putting back failing {} tests",
file_path, test_type
"Failed to read `{file_path}`, not putting back failing {test_type} tests"
);
}
} else {
@ -1266,7 +1257,7 @@ fn remove_files_callback<'a>(
remove_file(&path)?;
}
} else {
println!("Failed to read `{}`, not putting back failing ui tests", file_path);
println!("Failed to read `{file_path}`, not putting back failing ui tests");
}
}
Ok(true)

View file

@ -21,7 +21,7 @@ fn exec_command(
{
if let Some(signal) = status.signal() {
// In case the signal didn't kill the current process.
return Err(command_error(input, &cwd, format!("Process received signal {}", signal)));
return Err(command_error(input, &cwd, format!("Process received signal {signal}")));
}
}
Ok(status)
@ -65,18 +65,18 @@ fn check_exit_status(
);
let input = input.iter().map(|i| i.as_ref()).collect::<Vec<&OsStr>>();
if show_err {
eprintln!("Command `{:?}` failed", input);
eprintln!("Command `{input:?}` failed");
}
if let Some(output) = output {
let stdout = String::from_utf8_lossy(&output.stdout);
if !stdout.is_empty() {
error.push_str("\n==== STDOUT ====\n");
error.push_str(&*stdout);
error.push_str(&stdout);
}
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.is_empty() {
error.push_str("\n==== STDERR ====\n");
error.push_str(&*stderr);
error.push_str(&stderr);
}
}
Err(error)
@ -233,7 +233,7 @@ pub fn get_toolchain() -> Result<String, String> {
if !line.starts_with("channel") {
return None;
}
line.split('"').skip(1).next()
line.split('"').nth(1)
})
.next()
{
@ -272,7 +272,7 @@ fn git_clone_inner(
}
fn get_repo_name(url: &str) -> String {
let repo_name = url.split('/').last().unwrap();
let repo_name = url.split('/').next_back().unwrap();
match repo_name.strip_suffix(".git") {
Some(n) => n.to_string(),
None => repo_name.to_string(),

View file

@ -4,8 +4,8 @@ use std::convert::TryFrom;
use std::ops::Deref;
use gccjit::{
BinaryOp, Block, ComparisonOp, Context, Function, FunctionType, LValue, Location, RValue,
ToRValue, Type, UnaryOp,
BinaryOp, Block, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, Type,
UnaryOp,
};
use rustc_abi as abi;
use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout, WrappingRange};
@ -785,7 +785,7 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
let f128_type = self.type_f128();
let fmodf128 = self.context.new_function(
None,
FunctionType::Extern,
gccjit::FunctionType::Extern,
f128_type,
&[
self.context.new_parameter(None, f128_type, "a"),

View file

@ -1012,7 +1012,7 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function
};
let func = cx.context.get_builtin_function(gcc_name);
cx.functions.borrow_mut().insert(gcc_name.to_string(), func);
return func;
func
}
#[cfg(feature = "master")]
@ -1556,4 +1556,5 @@ pub fn intrinsic<'gcc, 'tcx>(name: &str, cx: &CodegenCx<'gcc, 'tcx>) -> Function
func
}
#[cfg(feature = "master")]
include!("archs.rs");

View file

@ -302,13 +302,13 @@ impl<'gcc, 'tcx> BaseTypeCodegenMethods for CodegenCx<'gcc, 'tcx> {
#[cfg_attr(feature = "master", allow(unused_mut))]
fn type_array(&self, ty: Type<'gcc>, mut len: u64) -> Type<'gcc> {
#[cfg(not(feature = "master"))]
if let Some(struct_type) = ty.is_struct() {
if struct_type.get_field_count() == 0 {
// NOTE: since gccjit only supports i32 for the array size and libcore's tests uses a
// size of usize::MAX in test_binary_search, we workaround this by setting the size to
// zero for ZSTs.
len = 0;
}
if let Some(struct_type) = ty.is_struct()
&& struct_type.get_field_count() == 0
{
// NOTE: since gccjit only supports i32 for the array size and libcore's tests uses a
// size of usize::MAX in test_binary_search, we workaround this by setting the size to
// zero for ZSTs.
len = 0;
}
self.context.new_array_type(None, ty, len)

View file

@ -57,10 +57,10 @@ pub fn main_inner(profile: Profile) {
#[cfg(not(feature = "master"))]
fn filter(filename: &Path) -> bool {
if let Some(filename) = filename.to_str() {
if filename.ends_with("gep.rs") {
return false;
}
if let Some(filename) = filename.to_str()
&& filename.ends_with("gep.rs")
{
return false;
}
rust_filter(filename)
}