From 0102507108a663e67bf5ff53d01a27646c6ec850 Mon Sep 17 00:00:00 2001 From: asothii Date: Sat, 11 Oct 2025 15:27:55 +0100 Subject: [PATCH] Mostly told clippy to stfu --- compiler/rustc_arena/src/tests.rs | 6 +- compiler/rustc_fluent_macro/src/fluent.rs | 2 +- compiler/rustc_graphviz/src/lib.rs | 2 +- compiler/rustc_graphviz/src/tests.rs | 18 +- compiler/rustc_hashes/src/lib.rs | 2 +- compiler/rustc_llvm/build.rs | 2 +- compiler/rustc_log/src/lib.rs | 13 +- compiler/rustc_serialize/src/serialize.rs | 6 +- .../rustc_thread_pool/src/broadcast/mod.rs | 2 +- compiler/rustc_thread_pool/src/registry.rs | 4 +- compiler/rustc_thread_pool/src/scope/tests.rs | 2 +- .../src/thread_pool/tests.rs | 2 +- .../rustc_thread_pool/src/worker_local.rs | 4 +- compiler/rustc_type_ir_macros/src/lib.rs | 11 +- compiler/rustc_windows_rc/src/lib.rs | 2 +- library/proc_macro/src/bridge/symbol.rs | 5 +- library/proc_macro/src/diagnostic.rs | 2 +- library/proc_macro/src/escape.rs | 3 +- library/proc_macro/src/lib.rs | 2 +- library/proc_macro/src/quote.rs | 10 +- src/build_helper/src/npm.rs | 2 +- src/librustdoc/build.rs | 7 +- src/tools/build-manifest/src/main.rs | 8 +- src/tools/build-manifest/src/manifest.rs | 4 +- src/tools/build-manifest/src/versions.rs | 21 +- src/tools/cargotest/main.rs | 4 +- .../collect-license-metadata/src/path_tree.rs | 12 +- .../collect-license-metadata/src/reuse.rs | 4 +- src/tools/compiletest/src/common.rs | 2 +- src/tools/compiletest/src/debuggers.rs | 34 ++- src/tools/compiletest/src/directives.rs | 196 +++++++++--------- src/tools/compiletest/src/directives/needs.rs | 4 +- src/tools/compiletest/src/directives/tests.rs | 2 +- .../compiletest/src/executor/deadline.rs | 2 +- src/tools/compiletest/src/json.rs | 7 +- src/tools/compiletest/src/lib.rs | 16 +- src/tools/compiletest/src/panic_hook.rs | 3 +- src/tools/compiletest/src/read2.rs | 2 +- src/tools/compiletest/src/runtest.rs | 171 ++++++++------- .../compiletest/src/runtest/codegen_units.rs | 6 +- .../compiletest/src/runtest/compute_diff.rs | 10 +- src/tools/compiletest/src/runtest/coverage.rs | 16 +- src/tools/compiletest/src/runtest/crashes.rs | 6 +- src/tools/compiletest/src/runtest/debugger.rs | 6 +- .../compiletest/src/runtest/debuginfo.rs | 10 +- src/tools/compiletest/src/runtest/js_doc.rs | 4 +- src/tools/compiletest/src/runtest/mir_opt.rs | 2 +- src/tools/compiletest/src/runtest/run_make.rs | 8 +- src/tools/compiletest/src/runtest/rustdoc.rs | 2 +- .../compiletest/src/runtest/rustdoc_json.rs | 2 +- src/tools/compiletest/src/runtest/ui.rs | 2 +- src/tools/compiletest/src/util.rs | 2 +- src/tools/coverage-dump/src/covfun.rs | 4 +- src/tools/coverage-dump/src/main.rs | 2 +- src/tools/features-status-dump/src/main.rs | 2 +- .../generate-copyright/src/cargo_metadata.rs | 2 +- src/tools/generate-windows-sys/src/main.rs | 2 +- src/tools/html-checker/main.rs | 9 +- src/tools/jsondocck/src/cache.rs | 2 +- src/tools/jsondocck/src/directive.rs | 13 +- src/tools/jsondoclint/src/item_kind.rs | 6 +- src/tools/jsondoclint/src/main.rs | 4 +- src/tools/jsondoclint/src/validator.rs | 22 +- src/tools/jsondoclint/src/validator/tests.rs | 2 +- src/tools/linkchecker/main.rs | 54 +++-- src/tools/llvm-bitcode-linker/src/linker.rs | 4 +- src/tools/opt-dist/src/bolt.rs | 2 +- src/tools/opt-dist/src/exec.rs | 4 +- src/tools/opt-dist/src/tests.rs | 2 +- src/tools/remote-test-client/src/main.rs | 16 +- src/tools/remote-test-server/src/main.rs | 6 +- .../replace-version-placeholder/src/main.rs | 2 +- .../src/assertion_helpers/mod.rs | 4 +- src/tools/run-make-support/src/command.rs | 20 +- src/tools/run-make-support/src/env.rs | 5 +- .../src/external_deps/c_build.rs | 12 +- .../src/external_deps/rustc.rs | 12 +- .../src/external_deps/rustdoc.rs | 2 +- src/tools/run-make-support/src/fs.rs | 92 ++++---- src/tools/run-make-support/src/linker.rs | 2 +- src/tools/run-make-support/src/scoped_run.rs | 6 +- src/tools/run-make-support/src/string.rs | 2 +- src/tools/run-make-support/src/targets.rs | 2 +- src/tools/rustdoc-gui-test/src/main.rs | 54 +++-- src/tools/rustdoc-themes/main.rs | 13 +- .../rustfmt/config_proc_macro/src/attrs.rs | 10 +- .../config_proc_macro/src/item_enum.rs | 4 +- .../rustfmt/config_proc_macro/src/utils.rs | 5 +- src/tools/rustfmt/src/lists.rs | 2 +- src/tools/rustfmt/src/reorder.rs | 5 +- src/tools/rustfmt/src/rewrite.rs | 7 +- src/tools/rustfmt/src/sort.rs | 8 +- src/tools/rustfmt/src/types.rs | 2 +- .../test-float-parse/src/gen_/many_digits.rs | 8 +- src/tools/test-float-parse/src/lib.rs | 2 +- src/tools/test-float-parse/src/ui.rs | 2 +- src/tools/tidy/src/deps.rs | 2 +- src/tools/tidy/src/diagnostics.rs | 6 +- src/tools/tidy/src/error_codes.rs | 8 +- src/tools/tidy/src/extra_checks/mod.rs | 2 +- src/tools/tidy/src/extra_checks/rustdoc_js.rs | 2 +- src/tools/tidy/src/lib.rs | 2 +- .../tests_revision_unpaired_stdout_stderr.rs | 9 +- src/tools/tidy/src/unit_tests.rs | 6 +- src/tools/unstable-book-gen/src/main.rs | 27 +-- 105 files changed, 555 insertions(+), 627 deletions(-) diff --git a/compiler/rustc_arena/src/tests.rs b/compiler/rustc_arena/src/tests.rs index bfde8abd5893a..385de6359e04f 100644 --- a/compiler/rustc_arena/src/tests.rs +++ b/compiler/rustc_arena/src/tests.rs @@ -19,8 +19,8 @@ impl TypedArena { unsafe { // Clear the last chunk, which is partially filled. let mut chunks_borrow = self.chunks.borrow_mut(); - if let Some(mut last_chunk) = chunks_borrow.last_mut() { - self.clear_last_chunk(&mut last_chunk); + if let Some(last_chunk) = chunks_borrow.last_mut() { + self.clear_last_chunk(last_chunk); let len = chunks_borrow.len(); // If `T` is ZST, code below has no effect. for mut chunk in chunks_borrow.drain(..len - 1) { @@ -204,7 +204,7 @@ fn test_typed_arena_drop_on_clear() { } thread_local! { - static DROP_COUNTER: Cell = Cell::new(0) + static DROP_COUNTER: Cell = const { Cell::new(0) } } struct SmallDroppable; diff --git a/compiler/rustc_fluent_macro/src/fluent.rs b/compiler/rustc_fluent_macro/src/fluent.rs index d58c70674f6aa..e383d085bb3d3 100644 --- a/compiler/rustc_fluent_macro/src/fluent.rs +++ b/compiler/rustc_fluent_macro/src/fluent.rs @@ -265,7 +265,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok Level::Error, format!("referenced message `{mref}` does not exist (in message `{name}`)"), ) - .help(&format!("you may have meant to use a variable reference (`{{${mref}}}`)")) + .help(format!("you may have meant to use a variable reference (`{{${mref}}}`)")) .emit(); } } diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index c8f8fd5be0237..7fc7d10761bc3 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -422,7 +422,7 @@ impl<'a> Id<'a> { /// it in the generated .dot file. They can also provide more /// elaborate (and non-unique) label text that is used in the graphviz /// rendered output. - +/// /// The graph instance is responsible for providing the DOT compatible /// identifiers for the nodes and (optionally) rendered labels for the nodes and /// edges, as well as an identifier for the graph itself. diff --git a/compiler/rustc_graphviz/src/tests.rs b/compiler/rustc_graphviz/src/tests.rs index bf2f43fde2ee9..199c6e50284dd 100644 --- a/compiler/rustc_graphviz/src/tests.rs +++ b/compiler/rustc_graphviz/src/tests.rs @@ -63,10 +63,10 @@ impl NodeLabels<&'static str> { } fn len(&self) -> usize { - match self { - &UnlabelledNodes(len) => len, - &AllNodesLabelled(ref lbls) => lbls.len(), - &SomeNodesLabelled(ref lbls) => lbls.len(), + match *self { + UnlabelledNodes(len) => len, + AllNodesLabelled(ref lbls) => lbls.len(), + SomeNodesLabelled(ref lbls) => lbls.len(), } } } @@ -394,17 +394,15 @@ fn left_aligned_text() { #[test] fn simple_id_construction() { let id1 = Id::new("hello"); - match id1 { - Ok(_) => {} - Err(..) => panic!("'hello' is not a valid value for id anymore"), + if id1.is_err() { + panic!("'hello' is not a valid value for id anymore"); } } #[test] fn badly_formatted_id() { let id2 = Id::new("Weird { struct : ure } !!!"); - match id2 { - Ok(_) => panic!("graphviz id suddenly allows spaces, brackets and stuff"), - Err(..) => {} + if id2.is_ok() { + panic!("graphviz id suddenly allows spaces, brackets and stuff"); } } diff --git a/compiler/rustc_hashes/src/lib.rs b/compiler/rustc_hashes/src/lib.rs index 3755caaaa2963..c8f3057dac5fc 100644 --- a/compiler/rustc_hashes/src/lib.rs +++ b/compiler/rustc_hashes/src/lib.rs @@ -54,7 +54,7 @@ impl FromStableHash for Hash64 { type Hash = StableHasherHash; #[inline] - fn from(StableHasherHash([_0, __1]): Self::Hash) -> Self { + fn from(StableHasherHash([_0, _]): Self::Hash) -> Self { Self { inner: _0 } } } diff --git a/compiler/rustc_llvm/build.rs b/compiler/rustc_llvm/build.rs index 2cfda7a5fb4b2..d5c43c4fa0661 100644 --- a/compiler/rustc_llvm/build.rs +++ b/compiler/rustc_llvm/build.rs @@ -197,7 +197,7 @@ fn main() { // Include path contains host directory, replace it with target if is_crossed && flag.starts_with("-I") { - cfg.flag(&flag.replace(&host, &target)); + cfg.flag(flag.replace(&host, &target)); continue; } diff --git a/compiler/rustc_log/src/lib.rs b/compiler/rustc_log/src/lib.rs index 26475eec1c102..0643d5b23bc51 100644 --- a/compiler/rustc_log/src/lib.rs +++ b/compiler/rustc_log/src/lib.rs @@ -73,7 +73,7 @@ impl LoggerConfig { /// Initialize the logger with the given values for the filter, coloring, and other options env variables. pub fn init_logger(cfg: LoggerConfig) -> Result<(), Error> { - init_logger_with_additional_layer(cfg, || Registry::default()) + init_logger_with_additional_layer(cfg, Registry::default) } /// Trait alias for the complex return type of `build_subscriber` in @@ -145,14 +145,11 @@ where .with_thread_ids(verbose_thread_ids) .with_thread_names(verbose_thread_ids); - match cfg.wraptree { - Ok(v) => match v.parse::() { - Ok(v) => { - layer = layer.with_wraparound(v); - } + if let Ok(v) = cfg.wraptree { + match v.parse::() { + Ok(v) => layer = layer.with_wraparound(v), Err(_) => return Err(Error::InvalidWraptree(v)), - }, - Err(_) => {} // no wraptree + } } let subscriber = build_subscriber().with(layer.with_filter(filter)); diff --git a/compiler/rustc_serialize/src/serialize.rs b/compiler/rustc_serialize/src/serialize.rs index 1cb09e8a1ee2e..c07990e74a93a 100644 --- a/compiler/rustc_serialize/src/serialize.rs +++ b/compiler/rustc_serialize/src/serialize.rs @@ -261,7 +261,7 @@ impl Encodable for str { impl Encodable for String { fn encode(&self, s: &mut S) { - s.emit_str(&self); + s.emit_str(self); } } @@ -341,8 +341,8 @@ impl Decodable for [u8; N] { let len = d.read_usize(); assert!(len == N); let mut v = [0u8; N]; - for i in 0..len { - v[i] = Decodable::decode(d); + for i in v.iter_mut() { + *i = Decodable::decode(d); } v } diff --git a/compiler/rustc_thread_pool/src/broadcast/mod.rs b/compiler/rustc_thread_pool/src/broadcast/mod.rs index 1707ebb59883c..db784f903b83d 100644 --- a/compiler/rustc_thread_pool/src/broadcast/mod.rs +++ b/compiler/rustc_thread_pool/src/broadcast/mod.rs @@ -123,7 +123,7 @@ where registry.inject_broadcast(job_refs); let current_thread_job_id = current_thread - .and_then(|worker| (registry.id() == worker.registry.id()).then(|| worker)) + .and_then(|worker| (registry.id() == worker.registry.id()).then_some(worker)) .map(|worker| unsafe { jobs[worker.index()].as_job_ref() }.id()); // Wait for all jobs to complete, then collect the results, maybe propagating a panic. diff --git a/compiler/rustc_thread_pool/src/registry.rs b/compiler/rustc_thread_pool/src/registry.rs index 22d3a78604523..c6b4ddfbf2d9b 100644 --- a/compiler/rustc_thread_pool/src/registry.rs +++ b/compiler/rustc_thread_pool/src/registry.rs @@ -808,7 +808,7 @@ impl WorkerThread { latch: &L, mut all_jobs_started: impl FnMut() -> bool, mut is_job: impl FnMut(&JobRef) -> bool, - mut execute_job: impl FnMut(JobRef) -> (), + mut execute_job: impl FnMut(JobRef), ) { let mut jobs = SmallVec::<[JobRef; 8]>::new(); let mut broadcast_jobs = SmallVec::<[JobRef; 8]>::new(); @@ -897,7 +897,7 @@ impl WorkerThread { // The job might have injected local work, so go back to the outer loop. continue 'outer; } else { - self.registry.sleep.no_work_found(&mut idle_state, latch, &self, true) + self.registry.sleep.no_work_found(&mut idle_state, latch, self, true) } } diff --git a/compiler/rustc_thread_pool/src/scope/tests.rs b/compiler/rustc_thread_pool/src/scope/tests.rs index 9b9ac98d066c2..cdd378096c41d 100644 --- a/compiler/rustc_thread_pool/src/scope/tests.rs +++ b/compiler/rustc_thread_pool/src/scope/tests.rs @@ -168,7 +168,7 @@ fn the_final_countdown<'scope>( let top_of_stack = 0; let p = bottom_of_stack as *const i32 as usize; let q = &top_of_stack as *const i32 as usize; - let diff = if p > q { p - q } else { q - p }; + let diff = p.abs_diff(q); let mut data = max.lock().unwrap(); *data = Ord::max(diff, *data); diff --git a/compiler/rustc_thread_pool/src/thread_pool/tests.rs b/compiler/rustc_thread_pool/src/thread_pool/tests.rs index f2baab4c85986..a77af7b73e087 100644 --- a/compiler/rustc_thread_pool/src/thread_pool/tests.rs +++ b/compiler/rustc_thread_pool/src/thread_pool/tests.rs @@ -97,7 +97,7 @@ fn failed_thread_stack() { // macOS and Windows weren't fazed, or at least didn't fail the way we want. // They work with `isize::MAX`, but 32-bit platforms may feasibly allocate a // 2GB stack, so it might not fail until the second thread. - let stack_size = ::std::isize::MAX as usize; + let stack_size = isize::MAX as usize; let (start_count, start_handler) = count_handler(); let (exit_count, exit_handler) = count_handler(); diff --git a/compiler/rustc_thread_pool/src/worker_local.rs b/compiler/rustc_thread_pool/src/worker_local.rs index d108c91f9ee53..912001233bfea 100644 --- a/compiler/rustc_thread_pool/src/worker_local.rs +++ b/compiler/rustc_thread_pool/src/worker_local.rs @@ -43,7 +43,7 @@ impl WorkerLocal { unsafe { let worker_thread = WorkerThread::current(); if worker_thread.is_null() - || &*(*worker_thread).registry as *const _ != &*self.registry as *const _ + || !std::ptr::eq(&*(*worker_thread).registry, &*self.registry) { panic!("WorkerLocal can only be used on the thread pool it was created on") } @@ -55,7 +55,7 @@ impl WorkerLocal { impl WorkerLocal> { /// Joins the elements of all the worker locals into one Vec pub fn join(self) -> Vec { - self.into_inner().into_iter().flat_map(|v| v).collect() + self.into_inner().into_iter().flatten().collect() } } diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index 3a10d0d41ef32..eb2fa10158b2a 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -196,12 +196,11 @@ fn lift(mut ty: syn::Type) -> syn::Type { struct ItoJ; impl VisitMut for ItoJ { fn visit_type_path_mut(&mut self, i: &mut syn::TypePath) { - if i.qself.is_none() { - if let Some(first) = i.path.segments.first_mut() { - if first.ident == "I" { - *first = parse_quote! { J }; - } - } + if i.qself.is_none() + && let Some(first) = i.path.segments.first_mut() + && first.ident == "I" + { + *first = parse_quote! { J }; } syn::visit_mut::visit_type_path_mut(self, i); } diff --git a/compiler/rustc_windows_rc/src/lib.rs b/compiler/rustc_windows_rc/src/lib.rs index 15afaf7b94b8e..9b8bff14de5d6 100644 --- a/compiler/rustc_windows_rc/src/lib.rs +++ b/compiler/rustc_windows_rc/src/lib.rs @@ -94,7 +94,7 @@ fn write_resource_script_file( .replace("@RUSTC_PRODUCTVERSION_QUAD@", &version.to_quad_string()) .replace("@RUSTC_PRODUCTVERSION_STR@", &descriptive_version); - fs::write(&rc_path, resource_script) + fs::write(rc_path, resource_script) .unwrap_or_else(|_| panic!("failed to write resource file {}", rc_path.display())); } diff --git a/library/proc_macro/src/bridge/symbol.rs b/library/proc_macro/src/bridge/symbol.rs index eb7d30f9a6cc9..d97eb4a0bad7d 100644 --- a/library/proc_macro/src/bridge/symbol.rs +++ b/library/proc_macro/src/bridge/symbol.rs @@ -77,10 +77,7 @@ impl Symbol { // Mimics the behavior of `Symbol::can_be_raw` from `rustc_span` fn can_be_raw(string: &str) -> bool { - match string { - "_" | "super" | "self" | "Self" | "crate" | "$crate" => false, - _ => true, - } + !matches!(string, "_" | "super" | "self" | "Self" | "crate" | "$crate") } } diff --git a/library/proc_macro/src/diagnostic.rs b/library/proc_macro/src/diagnostic.rs index 5a209f7c7aa18..4fa2f039c0ac3 100644 --- a/library/proc_macro/src/diagnostic.rs +++ b/library/proc_macro/src/diagnostic.rs @@ -37,7 +37,7 @@ impl MultiSpan for Vec { } #[unstable(feature = "proc_macro_diagnostic", issue = "54140")] -impl<'a> MultiSpan for &'a [Span] { +impl MultiSpan for &[Span] { fn into_spans(self) -> Vec { self.to_vec() } diff --git a/library/proc_macro/src/escape.rs b/library/proc_macro/src/escape.rs index 87a4d1d50fd48..1f11a6633ff16 100644 --- a/library/proc_macro/src/escape.rs +++ b/library/proc_macro/src/escape.rs @@ -17,8 +17,7 @@ pub(crate) fn escape_bytes(bytes: &[u8], opt: EscapeOptions) -> String { escape_single_byte(byte, opt, &mut repr); } } else { - let mut chunks = bytes.utf8_chunks(); - while let Some(chunk) = chunks.next() { + for chunk in bytes.utf8_chunks() { for ch in chunk.valid().chars() { escape_single_char(ch, opt, &mut repr); } diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 613abd7024e3f..ca958b35a9a4a 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -557,7 +557,7 @@ impl Span { /// This path should not be embedded in the output of the macro; prefer `file()` instead. #[stable(feature = "proc_macro_span_file", since = "1.88.0")] pub fn local_file(&self) -> Option { - self.0.local_file().map(|s| PathBuf::from(s)) + self.0.local_file().map(PathBuf::from) } /// Creates a new span encompassing `self` and `other`. diff --git a/library/proc_macro/src/quote.rs b/library/proc_macro/src/quote.rs index dbb55cd9fb300..327e3bb189daa 100644 --- a/library/proc_macro/src/quote.rs +++ b/library/proc_macro/src/quote.rs @@ -378,11 +378,11 @@ pub fn quote(stream: TokenStream) -> TokenStream { "`$` must be followed by an ident or `$` or a repetition group in `quote!`" ), } - } else if let TokenTree::Punct(ref tt) = tree { - if tt.as_char() == '$' { - after_dollar = true; - continue; - } + } else if let TokenTree::Punct(ref tt) = tree + && tt.as_char() == '$' + { + after_dollar = true; + continue; } match tree { diff --git a/src/build_helper/src/npm.rs b/src/build_helper/src/npm.rs index 5a7df0999bd3d..42515b2700e42 100644 --- a/src/build_helper/src/npm.rs +++ b/src/build_helper/src/npm.rs @@ -28,7 +28,7 @@ pub fn install(src_root_path: &Path, out_dir: &Path, npm: &Path) -> Result bool { - match self { - PkgType::JsonDocs | PkgType::HtmlDocs => true, - _ => false, - } + matches!(self, PkgType::JsonDocs | PkgType::HtmlDocs) } } @@ -198,7 +195,7 @@ impl Versions { } fn load_version_from_tarball_inner(&mut self, tarball: &Path) -> Result { - let file = match File::open(&tarball) { + let file = match File::open(tarball) { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { // Missing tarballs do not return an error, but return empty data. @@ -208,9 +205,9 @@ impl Versions { Err(err) => return Err(err.into()), }; let mut tar: Archive> = - Archive::new(if tarball.extension().map_or(false, |e| e == "gz") { + Archive::new(if tarball.extension().is_some_and(|e| e == "gz") { Box::new(GzDecoder::new(file)) - } else if tarball.extension().map_or(false, |e| e == "xz") { + } else if tarball.extension().is_some_and(|e| e == "xz") { Box::new(XzDecoder::new(file)) } else { unimplemented!("tarball extension not recognized: {}", tarball.display()) @@ -221,12 +218,12 @@ impl Versions { for entry in tar.entries()? { let mut entry = entry?; - let dest; - match entry.path()?.components().nth(1).and_then(|c| c.as_os_str().to_str()) { - Some("version") => dest = &mut version, - Some("git-commit-hash") => dest = &mut git_commit, + let dest = match entry.path()?.components().nth(1).and_then(|c| c.as_os_str().to_str()) + { + Some("version") => &mut version, + Some("git-commit-hash") => &mut git_commit, _ => continue, - } + }; let mut buf = String::new(); entry.read_to_string(&mut buf)?; *dest = Some(buf); diff --git a/src/tools/cargotest/main.rs b/src/tools/cargotest/main.rs index 4c57683806e6a..4c168b69af88e 100644 --- a/src/tools/cargotest/main.rs +++ b/src/tools/cargotest/main.rs @@ -116,7 +116,7 @@ fn test_repo(cargo: &Path, out_dir: &Path, test: &Test) { println!("testing {}", test.repo); let dir = clone_repo(test, out_dir); if let Some(lockfile) = test.lock { - fs::write(&dir.join("Cargo.lock"), lockfile).unwrap(); + fs::write(dir.join("Cargo.lock"), lockfile).unwrap(); } if !run_cargo_test(cargo, &dir, test.packages, test.features, test.manifest_path, test.filters) { @@ -140,7 +140,7 @@ fn clone_repo(test: &Test, out_dir: &Path) -> PathBuf { .arg("fetch") .arg(test.repo) .arg(test.sha) - .arg(&format!("--depth={}", depth)) + .arg(format!("--depth={}", depth)) .current_dir(&out_dir) .status() .unwrap(); diff --git a/src/tools/collect-license-metadata/src/path_tree.rs b/src/tools/collect-license-metadata/src/path_tree.rs index 866a4e42aab0c..a530cbf688851 100644 --- a/src/tools/collect-license-metadata/src/path_tree.rs +++ b/src/tools/collect-license-metadata/src/path_tree.rs @@ -213,20 +213,12 @@ impl Node { match child { Node::Directory { name, children, license: Some(license) } => { if children.is_empty() { - grouped - .entry(*license) - .or_insert_with(Grouped::default) - .directories - .push(name.clone()); + grouped.entry(*license).or_default().directories.push(name.clone()); *child = Node::Empty; } } Node::File { name, license } => { - grouped - .entry(*license) - .or_insert_with(Grouped::default) - .files - .push(name.clone()); + grouped.entry(*license).or_default().files.push(name.clone()); *child = Node::Empty; } _ => {} diff --git a/src/tools/collect-license-metadata/src/reuse.rs b/src/tools/collect-license-metadata/src/reuse.rs index dbe46781b7c5b..b3deab137376c 100644 --- a/src/tools/collect-license-metadata/src/reuse.rs +++ b/src/tools/collect-license-metadata/src/reuse.rs @@ -15,7 +15,7 @@ pub(crate) fn collect( let raw = &obtain_spdx_document(reuse_exe)?; println!("finished gathering the license information from REUSE in {:.2?}", start.elapsed()); - let document = spdx_rs::parsers::spdx_from_tag_value(&raw)?; + let document = spdx_rs::parsers::spdx_from_tag_value(raw)?; let mut result = Vec::new(); for file in document.file_information { @@ -34,7 +34,7 @@ pub(crate) fn collect( fn obtain_spdx_document(reuse_exe: &Path) -> Result { let output = Command::new(reuse_exe) - .args(&["--include-submodules", "spdx", "--add-license-concluded", "--creator-person=bors"]) + .args(["--include-submodules", "spdx", "--add-license-concluded", "--creator-person=bors"]) .stdout(Stdio::piped()) .spawn()? .wait_with_output()?; diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index 58330ed20dc88..f728c76173c0b 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -729,7 +729,7 @@ impl Config { } pub fn get_pointer_width(&self) -> u32 { - *&self.target_cfg().pointer_width + self.target_cfg().pointer_width } pub fn can_unwind(&self) -> bool { diff --git a/src/tools/compiletest/src/debuggers.rs b/src/tools/compiletest/src/debuggers.rs index 8afe3289fa45a..2b1da00e65142 100644 --- a/src/tools/compiletest/src/debuggers.rs +++ b/src/tools/compiletest/src/debuggers.rs @@ -57,10 +57,7 @@ pub(crate) fn configure_lldb(config: &Config) -> Option> { /// Returns `true` if the given target is an Android target for the /// purposes of GDB testing. pub(crate) fn is_android_gdb_target(target: &str) -> bool { - matches!( - &target[..], - "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android" - ) + matches!(target, "arm-linux-androideabi" | "armv7-linux-androideabi" | "aarch64-linux-android") } /// Returns `true` if the given target is a MSVC target for the purposes of CDB testing. @@ -110,12 +107,11 @@ pub(crate) fn analyze_cdb( let cdb = cdb.map(Utf8PathBuf::from).or_else(|| find_cdb(target)); let mut version = None; - if let Some(cdb) = cdb.as_ref() { - if let Ok(output) = Command::new(cdb).arg("/version").output() { - if let Some(first_line) = String::from_utf8_lossy(&output.stdout).lines().next() { - version = extract_cdb_version(&first_line); - } - } + if let Some(cdb) = cdb.as_ref() + && let Ok(output) = Command::new(cdb).arg("/version").output() + && let Some(first_line) = String::from_utf8_lossy(&output.stdout).lines().next() + { + version = extract_cdb_version(first_line); } (cdb, version) @@ -160,10 +156,10 @@ pub(crate) fn analyze_gdb( }; let mut version_line = None; - if let Ok(output) = Command::new(&gdb).arg("--version").output() { - if let Some(first_line) = String::from_utf8_lossy(&output.stdout).lines().next() { - version_line = Some(first_line.to_string()); - } + if let Ok(output) = Command::new(&gdb).arg("--version").output() + && let Some(first_line) = String::from_utf8_lossy(&output.stdout).lines().next() + { + version_line = Some(first_line.to_string()); } let version = match version_line { @@ -250,11 +246,11 @@ pub(crate) fn extract_lldb_version(full_version_line: &str) -> Option { let version: u32 = apple_ver[..idx].parse().unwrap(); return Some(version); } - } else if let Some(lldb_ver) = full_version_line.strip_prefix("lldb version ") { - if let Some(idx) = lldb_ver.find(not_a_digit) { - let version: u32 = lldb_ver[..idx].parse().ok()?; - return Some(version * 100); - } + } else if let Some(lldb_ver) = full_version_line.strip_prefix("lldb version ") + && let Some(idx) = lldb_ver.find(not_a_digit) + { + let version: u32 = lldb_ver[..idx].parse().ok()?; + return Some(version * 100); } None } diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 34a9d77ce0dfa..fe7e79d580d4c 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -212,54 +212,54 @@ pub struct TestProps { } mod directives { - pub const ERROR_PATTERN: &'static str = "error-pattern"; - pub const REGEX_ERROR_PATTERN: &'static str = "regex-error-pattern"; - pub const COMPILE_FLAGS: &'static str = "compile-flags"; - pub const RUN_FLAGS: &'static str = "run-flags"; - pub const DOC_FLAGS: &'static str = "doc-flags"; - pub const SHOULD_ICE: &'static str = "should-ice"; - pub const BUILD_AUX_DOCS: &'static str = "build-aux-docs"; - pub const UNIQUE_DOC_OUT_DIR: &'static str = "unique-doc-out-dir"; - pub const FORCE_HOST: &'static str = "force-host"; - pub const CHECK_STDOUT: &'static str = "check-stdout"; - pub const CHECK_RUN_RESULTS: &'static str = "check-run-results"; - pub const DONT_CHECK_COMPILER_STDOUT: &'static str = "dont-check-compiler-stdout"; - pub const DONT_CHECK_COMPILER_STDERR: &'static str = "dont-check-compiler-stderr"; - pub const DONT_REQUIRE_ANNOTATIONS: &'static str = "dont-require-annotations"; - pub const NO_PREFER_DYNAMIC: &'static str = "no-prefer-dynamic"; - pub const PRETTY_MODE: &'static str = "pretty-mode"; - pub const PRETTY_COMPARE_ONLY: &'static str = "pretty-compare-only"; - pub const AUX_BIN: &'static str = "aux-bin"; - pub const AUX_BUILD: &'static str = "aux-build"; - pub const AUX_CRATE: &'static str = "aux-crate"; - pub const PROC_MACRO: &'static str = "proc-macro"; - pub const AUX_CODEGEN_BACKEND: &'static str = "aux-codegen-backend"; - pub const EXEC_ENV: &'static str = "exec-env"; - pub const RUSTC_ENV: &'static str = "rustc-env"; - pub const UNSET_EXEC_ENV: &'static str = "unset-exec-env"; - pub const UNSET_RUSTC_ENV: &'static str = "unset-rustc-env"; - pub const FORBID_OUTPUT: &'static str = "forbid-output"; - pub const CHECK_TEST_LINE_NUMBERS_MATCH: &'static str = "check-test-line-numbers-match"; - pub const IGNORE_PASS: &'static str = "ignore-pass"; - pub const FAILURE_STATUS: &'static str = "failure-status"; - pub const DONT_CHECK_FAILURE_STATUS: &'static str = "dont-check-failure-status"; - pub const RUN_RUSTFIX: &'static str = "run-rustfix"; - pub const RUSTFIX_ONLY_MACHINE_APPLICABLE: &'static str = "rustfix-only-machine-applicable"; - pub const ASSEMBLY_OUTPUT: &'static str = "assembly-output"; - pub const STDERR_PER_BITWIDTH: &'static str = "stderr-per-bitwidth"; - pub const INCREMENTAL: &'static str = "incremental"; - pub const KNOWN_BUG: &'static str = "known-bug"; - pub const TEST_MIR_PASS: &'static str = "test-mir-pass"; - pub const REMAP_SRC_BASE: &'static str = "remap-src-base"; - pub const LLVM_COV_FLAGS: &'static str = "llvm-cov-flags"; - pub const FILECHECK_FLAGS: &'static str = "filecheck-flags"; - pub const NO_AUTO_CHECK_CFG: &'static str = "no-auto-check-cfg"; - pub const ADD_CORE_STUBS: &'static str = "add-core-stubs"; - pub const CORE_STUBS_COMPILE_FLAGS: &'static str = "core-stubs-compile-flags"; + pub const ERROR_PATTERN: &str = "error-pattern"; + pub const REGEX_ERROR_PATTERN: &str = "regex-error-pattern"; + pub const COMPILE_FLAGS: &str = "compile-flags"; + pub const RUN_FLAGS: &str = "run-flags"; + pub const DOC_FLAGS: &str = "doc-flags"; + pub const SHOULD_ICE: &str = "should-ice"; + pub const BUILD_AUX_DOCS: &str = "build-aux-docs"; + pub const UNIQUE_DOC_OUT_DIR: &str = "unique-doc-out-dir"; + pub const FORCE_HOST: &str = "force-host"; + pub const CHECK_STDOUT: &str = "check-stdout"; + pub const CHECK_RUN_RESULTS: &str = "check-run-results"; + pub const DONT_CHECK_COMPILER_STDOUT: &str = "dont-check-compiler-stdout"; + pub const DONT_CHECK_COMPILER_STDERR: &str = "dont-check-compiler-stderr"; + pub const DONT_REQUIRE_ANNOTATIONS: &str = "dont-require-annotations"; + pub const NO_PREFER_DYNAMIC: &str = "no-prefer-dynamic"; + pub const PRETTY_MODE: &str = "pretty-mode"; + pub const PRETTY_COMPARE_ONLY: &str = "pretty-compare-only"; + pub const AUX_BIN: &str = "aux-bin"; + pub const AUX_BUILD: &str = "aux-build"; + pub const AUX_CRATE: &str = "aux-crate"; + pub const PROC_MACRO: &str = "proc-macro"; + pub const AUX_CODEGEN_BACKEND: &str = "aux-codegen-backend"; + pub const EXEC_ENV: &str = "exec-env"; + pub const RUSTC_ENV: &str = "rustc-env"; + pub const UNSET_EXEC_ENV: &str = "unset-exec-env"; + pub const UNSET_RUSTC_ENV: &str = "unset-rustc-env"; + pub const FORBID_OUTPUT: &str = "forbid-output"; + pub const CHECK_TEST_LINE_NUMBERS_MATCH: &str = "check-test-line-numbers-match"; + pub const IGNORE_PASS: &str = "ignore-pass"; + pub const FAILURE_STATUS: &str = "failure-status"; + pub const DONT_CHECK_FAILURE_STATUS: &str = "dont-check-failure-status"; + pub const RUN_RUSTFIX: &str = "run-rustfix"; + pub const RUSTFIX_ONLY_MACHINE_APPLICABLE: &str = "rustfix-only-machine-applicable"; + pub const ASSEMBLY_OUTPUT: &str = "assembly-output"; + pub const STDERR_PER_BITWIDTH: &str = "stderr-per-bitwidth"; + pub const INCREMENTAL: &str = "incremental"; + pub const KNOWN_BUG: &str = "known-bug"; + pub const TEST_MIR_PASS: &str = "test-mir-pass"; + pub const REMAP_SRC_BASE: &str = "remap-src-base"; + pub const LLVM_COV_FLAGS: &str = "llvm-cov-flags"; + pub const FILECHECK_FLAGS: &str = "filecheck-flags"; + pub const NO_AUTO_CHECK_CFG: &str = "no-auto-check-cfg"; + pub const ADD_CORE_STUBS: &str = "add-core-stubs"; + pub const CORE_STUBS_COMPILE_FLAGS: &str = "core-stubs-compile-flags"; // This isn't a real directive, just one that is probably mistyped often - pub const INCORRECT_COMPILER_FLAGS: &'static str = "compiler-flags"; - pub const DISABLE_GDB_PRETTY_PRINTERS: &'static str = "disable-gdb-pretty-printers"; - pub const COMPARE_OUTPUT_BY_LINES: &'static str = "compare-output-by-lines"; + pub const INCORRECT_COMPILER_FLAGS: &str = "compiler-flags"; + pub const DISABLE_GDB_PRETTY_PRINTERS: &str = "disable-gdb-pretty-printers"; + pub const COMPARE_OUTPUT_BY_LINES: &str = "compare-output-by-lines"; } impl TestProps { @@ -698,10 +698,10 @@ impl TestProps { } for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] { - if let Ok(val) = env::var(key) { - if !self.exec_env.iter().any(|&(ref x, _)| x == key) { - self.exec_env.push(((*key).to_owned(), val)) - } + if let Ok(val) = env::var(key) + && self.exec_env.iter().all(|(x, _)| x != key) + { + self.exec_env.push(((*key).to_owned(), val)) } } @@ -784,10 +784,11 @@ impl TestProps { } pub fn pass_mode(&self, config: &Config) -> Option { - if !self.ignore_pass && self.fail_mode.is_none() { - if let mode @ Some(_) = config.force_pass_mode { - return mode; - } + if !self.ignore_pass + && self.fail_mode.is_none() + && let mode @ Some(_) = config.force_pass_mode + { + return mode; } self.pass_mode } @@ -1090,19 +1091,19 @@ fn expand_variables(mut value: String, config: &Config) -> String { if value.contains(CWD) { let cwd = env::current_dir().unwrap(); - value = value.replace(CWD, &cwd.to_str().unwrap()); + value = value.replace(CWD, cwd.to_str().unwrap()); } if value.contains(SRC_BASE) { - value = value.replace(SRC_BASE, &config.src_test_suite_root.as_str()); + value = value.replace(SRC_BASE, config.src_test_suite_root.as_str()); } if value.contains(TEST_SUITE_BUILD_BASE) { - value = value.replace(TEST_SUITE_BUILD_BASE, &config.build_test_suite_root.as_str()); + value = value.replace(TEST_SUITE_BUILD_BASE, config.build_test_suite_root.as_str()); } if value.contains(SYSROOT_BASE) { - value = value.replace(SYSROOT_BASE, &config.sysroot_base.as_str()); + value = value.replace(SYSROOT_BASE, config.sysroot_base.as_str()); } if value.contains(TARGET_LINKER) { @@ -1115,9 +1116,9 @@ fn expand_variables(mut value: String, config: &Config) -> String { if value.contains(RUST_SRC_BASE) { let src_base = config.sysroot_base.join("lib/rustlib/src/rust"); - src_base.try_exists().expect(&*format!("{} should exists", src_base)); + src_base.try_exists().unwrap_or_else(|_| panic!("{} should exists", src_base)); let src_base = src_base.read_link_utf8().unwrap_or(src_base); - value = value.replace(RUST_SRC_BASE, &src_base.as_str()); + value = value.replace(RUST_SRC_BASE, src_base.as_str()); } value @@ -1437,21 +1438,20 @@ fn ignore_cdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { return IgnoreDecision::Continue; } - if let Some(actual_version) = config.cdb_version { - if line.name == "min-cdb-version" - && let Some(rest) = line.value_after_colon().map(str::trim) - { - let min_version = extract_cdb_version(rest).unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", rest); - }); + if let Some(actual_version) = config.cdb_version + && line.name == "min-cdb-version" + && let Some(rest) = line.value_after_colon().map(str::trim) + { + let min_version = extract_cdb_version(rest).unwrap_or_else(|| { + panic!("couldn't parse version range: {:?}", rest); + }); - // Ignore if actual version is smaller than the minimum - // required version - if actual_version < min_version { - return IgnoreDecision::Ignore { - reason: format!("ignored when the CDB version is lower than {rest}"), - }; - } + // Ignore if actual version is smaller than the minimum + // required version + if actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the CDB version is lower than {rest}"), + }; } } IgnoreDecision::Continue @@ -1514,20 +1514,19 @@ fn ignore_lldb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { return IgnoreDecision::Continue; } - if let Some(actual_version) = config.lldb_version { - if line.name == "min-lldb-version" - && let Some(rest) = line.value_after_colon().map(str::trim) - { - let min_version = rest.parse().unwrap_or_else(|e| { - panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e); - }); - // Ignore if actual version is smaller the minimum required - // version - if actual_version < min_version { - return IgnoreDecision::Ignore { - reason: format!("ignored when the LLDB version is {rest}"), - }; - } + if let Some(actual_version) = config.lldb_version + && line.name == "min-lldb-version" + && let Some(rest) = line.value_after_colon().map(str::trim) + { + let min_version = rest.parse().unwrap_or_else(|e| { + panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e); + }); + // Ignore if actual version is smaller the minimum required + // version + if actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the LLDB version is {rest}"), + }; } } IgnoreDecision::Continue @@ -1556,8 +1555,8 @@ fn ignore_backends(config: &Config, path: &Utf8Path, line: &DirectiveLine<'_>) - } fn needs_backends(config: &Config, path: &Utf8Path, line: &DirectiveLine<'_>) -> IgnoreDecision { - if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends", path) { - if !needed_backends + if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends", path) + && !needed_backends .split_whitespace() .map(|backend| match CodegenBackend::try_from(backend) { Ok(backend) => backend, @@ -1566,14 +1565,13 @@ fn needs_backends(config: &Config, path: &Utf8Path, line: &DirectiveLine<'_>) -> } }) .any(|backend| config.default_codegen_backend == backend) - { - return IgnoreDecision::Ignore { - reason: format!( - "{} backend is not part of required backends", - config.default_codegen_backend.as_str() - ), - }; - } + { + return IgnoreDecision::Ignore { + reason: format!( + "{} backend is not part of required backends", + config.default_codegen_backend.as_str() + ), + }; } IgnoreDecision::Continue } diff --git a/src/tools/compiletest/src/directives/needs.rs b/src/tools/compiletest/src/directives/needs.rs index 5e9fe59d8d1c3..1dcf967fc2167 100644 --- a/src/tools/compiletest/src/directives/needs.rs +++ b/src/tools/compiletest/src/directives/needs.rs @@ -370,8 +370,8 @@ impl CachedNeedsConditions { .join(if config.host.contains("windows") { "rust-lld.exe" } else { "rust-lld" }) .exists(), - llvm_zstd: llvm_has_libzstd(&config), - dlltool: find_dlltool(&config), + llvm_zstd: llvm_has_libzstd(config), + dlltool: find_dlltool(config), symlinks: has_symlinks(), } } diff --git a/src/tools/compiletest/src/directives/tests.rs b/src/tools/compiletest/src/directives/tests.rs index 77080c7469371..946e1cb22eabd 100644 --- a/src/tools/compiletest/src/directives/tests.rs +++ b/src/tools/compiletest/src/directives/tests.rs @@ -230,7 +230,7 @@ fn parse_rs(config: &Config, contents: &str) -> EarlyProps { fn check_ignore(config: &Config, contents: &str) -> bool { let tn = String::new(); let p = Utf8Path::new("a.rs"); - let d = make_test_description(&config, tn, p, p, contents, None); + let d = make_test_description(config, tn, p, p, contents, None); d.ignore } diff --git a/src/tools/compiletest/src/executor/deadline.rs b/src/tools/compiletest/src/executor/deadline.rs index 3536eff2fd80d..1b59571a1b84d 100644 --- a/src/tools/compiletest/src/executor/deadline.rs +++ b/src/tools/compiletest/src/executor/deadline.rs @@ -87,7 +87,7 @@ impl<'a> DeadlineQueue<'a> { // Also clear out any leading entries that are no longer running, even // if their deadline hasn't been reached. - while let Some(_) = pop_front_if(&mut self.queue, |entry| !is_running(entry.id)) {} + while pop_front_if(&mut self.queue, |entry| !is_running(entry.id)).is_some() {} if let Some(front) = self.queue.front() { assert!(now < front.deadline); diff --git a/src/tools/compiletest/src/json.rs b/src/tools/compiletest/src/json.rs index a8e6416e56c84..15b9624e7b1c8 100644 --- a/src/tools/compiletest/src/json.rs +++ b/src/tools/compiletest/src/json.rs @@ -117,10 +117,9 @@ pub fn extract_rendered(output: &str) -> String { .collect::() )) } - } else if serde_json::from_str::(line).is_ok() { - // Ignore the notification. - None - } else if serde_json::from_str::(line).is_ok() { + } else if serde_json::from_str::(line).is_ok() + || serde_json::from_str::(line).is_ok() + { // Ignore the notification. None } else { diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 48ae38b61b93d..a43fd3f2ac34d 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -299,7 +299,7 @@ fn parse_config(args: Vec) -> Config { .arg("--version") .stdout(Stdio::null()) .status() - .map_or(false, |status| status.success()) + .is_ok_and(|status| status.success()) } else { // Avoid spawning an external command when we know html-tidy won't be used. false @@ -338,7 +338,7 @@ fn parse_config(args: Vec) -> Config { }; let compare_mode = matches.opt_str("compare-mode").map(|s| { s.parse().unwrap_or_else(|_| { - let variants: Vec<_> = CompareMode::STR_VARIANTS.iter().copied().collect(); + let variants: Vec<_> = CompareMode::STR_VARIANTS.to_vec(); panic!( "`{s}` is not a valid value for `--compare-mode`, it should be one of: {}", variants.join(", ") @@ -506,10 +506,10 @@ fn run_tests(config: Arc) { if config.rustfix_coverage { let mut coverage_file_path = config.build_test_suite_root.clone(); coverage_file_path.push("rustfix_missing_coverage.txt"); - if coverage_file_path.exists() { - if let Err(e) = fs::remove_file(&coverage_file_path) { - panic!("Could not delete {} due to {}", coverage_file_path, e) - } + if coverage_file_path.exists() + && let Err(e) = fs::remove_file(&coverage_file_path) + { + panic!("Could not delete {} due to {}", coverage_file_path, e) } } @@ -692,7 +692,7 @@ fn common_inputs_stamp(config: &Config) -> Stamp { stamp.add_dir(&config.run_lib_path); if let Some(ref rustdoc_path) = config.rustdoc_path { - stamp.add_path(&rustdoc_path); + stamp.add_path(rustdoc_path); stamp.add_path(&src_root.join("src/etc/htmldocck.py")); } @@ -724,7 +724,7 @@ fn modified_tests(config: &Config, dir: &Utf8Path) -> Result, S let files = get_git_modified_files( &config.git_config(), Some(dir.as_std_path()), - &vec!["rs", "stderr", "fixed"], + &["rs", "stderr", "fixed"], )?; // Add new test cases to the list, it will be convenient in daily development. let untracked_files = get_git_untracked_files(Some(dir.as_std_path()))?.unwrap_or(vec![]); diff --git a/src/tools/compiletest/src/panic_hook.rs b/src/tools/compiletest/src/panic_hook.rs index 4f1e2547518f0..fa4413e093eb5 100644 --- a/src/tools/compiletest/src/panic_hook.rs +++ b/src/tools/compiletest/src/panic_hook.rs @@ -91,8 +91,7 @@ fn trim_backtrace(full_backtrace: String) -> String { // After the short-backtrace state is toggled, skip its associated "at" if present. let mut skip_next_at = false; - let mut lines = full_backtrace.lines(); - while let Some(line) = lines.next() { + for line in full_backtrace.lines() { if mem::replace(&mut skip_next_at, false) && line.trim_start().starts_with("at ") { continue; } diff --git a/src/tools/compiletest/src/read2.rs b/src/tools/compiletest/src/read2.rs index 2213dd07160a7..2c9aa405bedc0 100644 --- a/src/tools/compiletest/src/read2.rs +++ b/src/tools/compiletest/src/read2.rs @@ -84,7 +84,7 @@ impl ProcOutput { // We start matching `path_bytes - 1` into the previously loaded data, // to account for the fact a path_bytes might be included across multiple // `extend` calls. Starting from `- 1` avoids double-counting paths. - let matches = (&bytes[(old_len.saturating_sub(path_bytes.len() - 1))..]) + let matches = (bytes[(old_len.saturating_sub(path_bytes.len() - 1))..]) .windows(path_bytes.len()) .filter(|window| window == &path_bytes) .count(); diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index e9dea95cafbdc..b3f3cfb013aa8 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -152,7 +152,7 @@ pub fn run( let cx = TestCx { config: &config, stdout, stderr, props: &props, testpaths, revision }; - if let Err(e) = create_dir_all(&cx.output_base_dir()) { + if let Err(e) = create_dir_all(cx.output_base_dir()) { panic!("failed to create output base directory {}: {e}", cx.output_base_dir()); } @@ -442,8 +442,8 @@ impl<'test> TestCx<'test> { let mut rustc = Command::new(&self.config.rustc_path); rustc .arg(input) - .args(&["-Z", &format!("unpretty={}", pretty_type)]) - .args(&["--target", &self.config.target]) + .args(["-Z", &format!("unpretty={}", pretty_type)]) + .args(["--target", &self.config.target]) .arg("-L") .arg(&aux_dir) .arg("-A") @@ -530,7 +530,7 @@ impl<'test> TestCx<'test> { } check_cfg.push(')'); - cmd.args(&["--check-cfg", &check_cfg]); + cmd.args(["--check-cfg", &check_cfg]); } } @@ -551,7 +551,7 @@ impl<'test> TestCx<'test> { .arg("-Zno-codegen") .arg("--out-dir") .arg(&out_dir) - .arg(&format!("--target={}", target)) + .arg(format!("--target={}", target)) .arg("-L") // FIXME(jieyouxu): this search path seems questionable. Is this intended for // `rust_test_helpers` in ui tests? @@ -1018,7 +1018,7 @@ impl<'test> TestCx<'test> { create_dir_all(aux_cx.output_base_dir()).unwrap(); // use root_testpaths here, because aux-builds should have the // same --out-dir and auxiliary directory. - let auxres = aux_cx.document(&root_out_dir, root_testpaths); + let auxres = aux_cx.document(root_out_dir, root_testpaths); if !auxres.status.success() { return auxres; } @@ -1129,7 +1129,7 @@ impl<'test> TestCx<'test> { let mut test_client = Command::new(self.config.remote_test_client.as_ref().unwrap()); test_client - .args(&["run", &support_libs.len().to_string()]) + .args(["run", &support_libs.len().to_string()]) .arg(&prog) .args(support_libs) .args(args); @@ -1147,7 +1147,7 @@ impl<'test> TestCx<'test> { let aux_dir = self.aux_output_dir_name(); let ProcArgs { prog, args } = self.make_run_args(); let mut wr_run = Command::new("wr-run"); - wr_run.args(&[&prog]).args(args); + wr_run.args([&prog]).args(args); prepare_env(&mut wr_run); @@ -1162,7 +1162,7 @@ impl<'test> TestCx<'test> { let aux_dir = self.aux_output_dir_name(); let ProcArgs { prog, args } = self.make_run_args(); let mut program = Command::new(&prog); - program.args(args).current_dir(&self.output_base_dir()); + program.args(args).current_dir(self.output_base_dir()); prepare_env(&mut program); @@ -1251,11 +1251,11 @@ impl<'test> TestCx<'test> { fn build_all_auxiliary(&self, of: &TestPaths, aux_dir: &Utf8Path, rustc: &mut Command) { for rel_ab in &self.props.aux.builds { - self.build_auxiliary(of, rel_ab, &aux_dir, None); + self.build_auxiliary(of, rel_ab, aux_dir, None); } for rel_ab in &self.props.aux.bins { - self.build_auxiliary(of, rel_ab, &aux_dir, Some(AuxType::Bin)); + self.build_auxiliary(of, rel_ab, aux_dir, Some(AuxType::Bin)); } let path_to_crate_name = |path: &str| -> String { @@ -1274,12 +1274,12 @@ impl<'test> TestCx<'test> { }; for (aux_name, aux_path) in &self.props.aux.crates { - let aux_type = self.build_auxiliary(of, &aux_path, &aux_dir, None); + let aux_type = self.build_auxiliary(of, aux_path, aux_dir, None); add_extern(rustc, aux_name, aux_path, aux_type); } for proc_macro in &self.props.aux.proc_macros { - self.build_auxiliary(of, proc_macro, &aux_dir, Some(AuxType::ProcMacro)); + self.build_auxiliary(of, proc_macro, aux_dir, Some(AuxType::ProcMacro)); let crate_name = path_to_crate_name(proc_macro); add_extern(rustc, &crate_name, proc_macro, AuxType::ProcMacro); } @@ -1306,7 +1306,7 @@ impl<'test> TestCx<'test> { if self.props.add_core_stubs { let minicore_path = self.build_minicore(); rustc.arg("--extern"); - rustc.arg(&format!("minicore={}", minicore_path)); + rustc.arg(format!("minicore={}", minicore_path)); } let aux_dir = self.aux_output_dir(); @@ -1335,7 +1335,7 @@ impl<'test> TestCx<'test> { vec![], ); - rustc.args(&["--crate-type", "rlib"]); + rustc.args(["--crate-type", "rlib"]); rustc.arg("-Cpanic=abort"); rustc.args(self.props.core_stubs_compile_flags.clone()); @@ -1438,12 +1438,12 @@ impl<'test> TestCx<'test> { }; if let Some(crate_type) = crate_type { - aux_rustc.args(&["--crate-type", crate_type]); + aux_rustc.args(["--crate-type", crate_type]); } if aux_type == AuxType::ProcMacro { // For convenience, but this only works on 2018. - aux_rustc.args(&["--extern", "proc_macro"]); + aux_rustc.args(["--extern", "proc_macro"]); } aux_rustc.arg("-L").arg(&aux_dir); @@ -1451,7 +1451,7 @@ impl<'test> TestCx<'test> { if aux_props.add_core_stubs { let minicore_path = self.build_minicore(); aux_rustc.arg("--extern"); - aux_rustc.arg(&format!("minicore={}", minicore_path)); + aux_rustc.arg(format!("minicore={}", minicore_path)); } let auxres = aux_cx.compose_and_run( @@ -1557,7 +1557,7 @@ impl<'test> TestCx<'test> { let mut rustc = if !is_rustdoc { Command::new(&self.config.rustc_path) } else { - Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet")) + Command::new(self.config.rustdoc_path.clone().expect("no rustdoc built yet")) }; rustc.arg(input_file); @@ -1611,18 +1611,18 @@ impl<'test> TestCx<'test> { let target = if self.props.force_host { &*self.config.host } else { &*self.config.target }; - rustc.arg(&format!("--target={}", target)); + rustc.arg(format!("--target={}", target)); } self.set_revision_flags(&mut rustc); if !is_rustdoc { if let Some(ref incremental_dir) = self.props.incremental_dir { - rustc.args(&["-C", &format!("incremental={}", incremental_dir)]); - rustc.args(&["-Z", "incremental-verify-ich"]); + rustc.args(["-C", &format!("incremental={}", incremental_dir)]); + rustc.args(["-Z", "incremental-verify-ich"]); } if self.config.mode == TestMode::CodegenUnits { - rustc.args(&["-Z", "human_readable_cgu_names"]); + rustc.args(["-Z", "human_readable_cgu_names"]); } } @@ -1634,7 +1634,7 @@ impl<'test> TestCx<'test> { // Note: aux libs don't have a pass-mode, so they won't get optimized // unless compile-flags are set in the aux file. if self.config.optimize_tests - && self.props.pass_mode(&self.config) == Some(PassMode::Run) + && self.props.pass_mode(self.config) == Some(PassMode::Run) && !self .props .compile_flags @@ -1673,16 +1673,16 @@ impl<'test> TestCx<'test> { if self.props.error_patterns.is_empty() && self.props.regex_error_patterns.is_empty() { - rustc.args(&["--error-format", "json"]); - rustc.args(&["--json", "future-incompat"]); + rustc.args(["--error-format", "json"]); + rustc.args(["--json", "future-incompat"]); } rustc.arg("-Zui-testing"); rustc.arg("-Zdeduplicate-diagnostics=no"); } TestMode::Ui => { if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) { - rustc.args(&["--error-format", "json"]); - rustc.args(&["--json", "future-incompat"]); + rustc.args(["--error-format", "json"]); + rustc.args(["--json", "future-incompat"]); } rustc.arg("-Ccodegen-units=1"); // Hide line numbers to reduce churn @@ -1702,7 +1702,7 @@ impl<'test> TestCx<'test> { "-Zdump-mir=all".to_string() }; - rustc.args(&[ + rustc.args([ "-Copt-level=1", &zdump_arg, "-Zvalidate-mir", @@ -1712,9 +1712,9 @@ impl<'test> TestCx<'test> { "--crate-type=rlib", ]); if let Some(pass) = &self.props.mir_unit_test { - rustc.args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]); + rustc.args(["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]); } else { - rustc.args(&[ + rustc.args([ "-Zmir-opt-level=4", "-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals", ]); @@ -1773,19 +1773,19 @@ impl<'test> TestCx<'test> { Emit::None => {} Emit::Metadata if is_rustdoc => {} Emit::Metadata => { - rustc.args(&["--emit", "metadata"]); + rustc.args(["--emit", "metadata"]); } Emit::LlvmIr => { - rustc.args(&["--emit", "llvm-ir"]); + rustc.args(["--emit", "llvm-ir"]); } Emit::Mir => { - rustc.args(&["--emit", "mir"]); + rustc.args(["--emit", "mir"]); } Emit::Asm => { - rustc.args(&["--emit", "asm"]); + rustc.args(["--emit", "asm"]); } Emit::LinkArgsAsm => { - rustc.args(&["-Clink-args=--emit=asm"]); + rustc.args(["-Clink-args=--emit=asm"]); } } @@ -1793,7 +1793,7 @@ impl<'test> TestCx<'test> { if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() { // rustc.arg("-g"); // get any backtrace at all on errors } else if !self.props.no_prefer_dynamic { - rustc.args(&["-C", "prefer-dynamic"]); + rustc.args(["-C", "prefer-dynamic"]); } } @@ -1816,22 +1816,22 @@ impl<'test> TestCx<'test> { match self.config.compare_mode { Some(CompareMode::Polonius) => { - rustc.args(&["-Zpolonius=next"]); + rustc.args(["-Zpolonius=next"]); } Some(CompareMode::NextSolver) => { - rustc.args(&["-Znext-solver"]); + rustc.args(["-Znext-solver"]); } Some(CompareMode::NextSolverCoherence) => { - rustc.args(&["-Znext-solver=coherence"]); + rustc.args(["-Znext-solver=coherence"]); } Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => { - rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]); + rustc.args(["-Csplit-debuginfo=unpacked", "-Zunstable-options"]); } Some(CompareMode::SplitDwarf) => { - rustc.args(&["-Csplit-debuginfo=unpacked"]); + rustc.args(["-Csplit-debuginfo=unpacked"]); } Some(CompareMode::SplitDwarfSingle) => { - rustc.args(&["-Csplit-debuginfo=packed"]); + rustc.args(["-Csplit-debuginfo=packed"]); } None => {} } @@ -1839,31 +1839,27 @@ impl<'test> TestCx<'test> { // Add `-A unused` before `config` flags and in-test (`props`) flags, so that they can // overwrite this. if let AllowUnused::Yes = allow_unused { - rustc.args(&["-A", "unused"]); + rustc.args(["-A", "unused"]); } // Allow tests to use internal features. - rustc.args(&["-A", "internal_features"]); + rustc.args(["-A", "internal_features"]); // Allow tests to have unused parens and braces. // Add #![deny(unused_parens, unused_braces)] to the test file if you want to // test that these lints are working. - rustc.args(&["-A", "unused_parens"]); - rustc.args(&["-A", "unused_braces"]); + rustc.args(["-A", "unused_parens"]); + rustc.args(["-A", "unused_braces"]); if self.props.force_host { self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags); - if !is_rustdoc { - if let Some(ref linker) = self.config.host_linker { - rustc.arg(format!("-Clinker={}", linker)); - } + if !is_rustdoc && let Some(ref linker) = self.config.host_linker { + rustc.arg(format!("-Clinker={}", linker)); } } else { self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags); - if !is_rustdoc { - if let Some(ref linker) = self.config.target_linker { - rustc.arg(format!("-Clinker={}", linker)); - } + if !is_rustdoc && let Some(ref linker) = self.config.target_linker { + rustc.arg(format!("-Clinker={}", linker)); } } @@ -2066,7 +2062,7 @@ impl<'test> TestCx<'test> { fn error_prefix(&self) -> String { match self.revision { Some(rev) => format!("error in revision `{rev}`"), - None => format!("error"), + None => "error".to_string(), } } @@ -2150,7 +2146,7 @@ impl<'test> TestCx<'test> { filecheck.arg("--allow-unused-prefixes"); // Provide more context on failures. - filecheck.args(&["--dump-input-context", "100"]); + filecheck.args(["--dump-input-context", "100"]); // Add custom flags supplied by the `filecheck-flags:` test directive. filecheck.args(&self.props.filecheck_flags); @@ -2200,9 +2196,9 @@ impl<'test> TestCx<'test> { Vec::new(), ); let aux_dir = new_rustdoc.aux_output_dir(); - new_rustdoc.build_all_auxiliary(&new_rustdoc.testpaths, &aux_dir, &mut rustc); + new_rustdoc.build_all_auxiliary(new_rustdoc.testpaths, &aux_dir, &mut rustc); - let proc_res = new_rustdoc.document(&compare_dir, &new_rustdoc.testpaths); + let proc_res = new_rustdoc.document(&compare_dir, new_rustdoc.testpaths); if !proc_res.status.success() { writeln!(self.stderr, "failed to run nightly rustdoc"); return; @@ -2226,7 +2222,7 @@ impl<'test> TestCx<'test> { && entry.path().extension().and_then(|p| p.to_str()) == Some("html") { let status = - Command::new("tidy").args(&tidy_args).arg(entry.path()).status().unwrap(); + Command::new("tidy").args(tidy_args).arg(entry.path()).status().unwrap(); // `tidy` returns 1 if it modified the file. assert!(status.success() || status.code() == Some(1)); } @@ -2236,7 +2232,7 @@ impl<'test> TestCx<'test> { tidy_dir(&compare_dir); let pager = { - let output = Command::new("git").args(&["config", "--get", "core.pager"]).output().ok(); + let output = Command::new("git").args(["config", "--get", "core.pager"]).output().ok(); output.and_then(|out| { if out.status.success() { Some(String::from_utf8(out.stdout).expect("invalid UTF8 in git pager")) @@ -2365,7 +2361,7 @@ impl<'test> TestCx<'test> { files.insert(normalized, self.get_lines(&self.testpaths.file, Some(&mut other_files))); for other_file in other_files { let mut path = self.testpaths.file.clone(); - path.set_file_name(&format!("{}.rs", other_file)); + path.set_file_name(format!("{}.rs", other_file)); let path = path.canonicalize_utf8().expect("failed to canonicalize"); let normalized = path.as_str().replace('\\', "/"); files.insert(normalized, self.get_lines(&path, None)); @@ -2375,7 +2371,7 @@ impl<'test> TestCx<'test> { for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| { if let Some((left, right)) = s.split_once(" - ") { let path = left.rsplit("test ").next().unwrap(); - let path = fs::canonicalize(&path).expect("failed to canonicalize"); + let path = fs::canonicalize(path).expect("failed to canonicalize"); let path = path.to_str().unwrap().replace('\\', "/"); if let Some(ref mut v) = files.get_mut(&path) { tested += 1; @@ -2489,8 +2485,8 @@ impl<'test> TestCx<'test> { let mut errors = 0; match output_kind { TestOutput::Compile => { - if !self.props.dont_check_compiler_stdout { - if self + if !self.props.dont_check_compiler_stdout + && self .compare_output( stdout_kind, &normalized_stdout, @@ -2498,17 +2494,16 @@ impl<'test> TestCx<'test> { &expected_stdout, ) .should_error() - { - errors += 1; - } + { + errors += 1; } - if !self.props.dont_check_compiler_stderr { - if self + + if !self.props.dont_check_compiler_stderr + && self .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr) .should_error() - { - errors += 1; - } + { + errors += 1; } } TestOutput::Run => { @@ -2578,14 +2573,14 @@ impl<'test> TestCx<'test> { // Real paths into the libstd/libcore let rust_src_dir = &self.config.sysroot_base.join("lib/rustlib/src/rust"); - rust_src_dir.try_exists().expect(&*format!("{} should exists", rust_src_dir)); + rust_src_dir.try_exists().unwrap_or_else(|_| panic!("{} should exists", rust_src_dir)); let rust_src_dir = rust_src_dir.read_link_utf8().unwrap_or_else(|_| rust_src_dir.to_path_buf()); normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL"); // Real paths into the compiler let rustc_src_dir = &self.config.sysroot_base.join("lib/rustlib/rustc-src/rust"); - rustc_src_dir.try_exists().expect(&*format!("{} should exists", rustc_src_dir)); + rustc_src_dir.try_exists().unwrap_or_else(|_| panic!("{} should exists", rustc_src_dir)); let rustc_src_dir = rustc_src_dir.read_link_utf8().unwrap_or(rustc_src_dir.to_path_buf()); normalize_path(&rustc_src_dir.join("compiler"), "$COMPILER_DIR_REAL"); @@ -2737,16 +2732,16 @@ impl<'test> TestCx<'test> { fn expected_output_path(&self, kind: &str) -> Utf8PathBuf { let mut path = - expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind); + expected_output_path(self.testpaths, self.revision, &self.config.compare_mode, kind); - if !path.exists() { - if let Some(CompareMode::Polonius) = self.config.compare_mode { - path = expected_output_path(&self.testpaths, self.revision, &None, kind); - } + if !path.exists() + && let Some(CompareMode::Polonius) = self.config.compare_mode + { + path = expected_output_path(self.testpaths, self.revision, &None, kind); } if !path.exists() { - path = expected_output_path(&self.testpaths, self.revision, &None, kind); + path = expected_output_path(self.testpaths, self.revision, &None, kind); } path @@ -2842,7 +2837,7 @@ impl<'test> TestCx<'test> { ) .with_extra_extension(stream); - if let Err(err) = fs::write(&actual_path, &actual) { + if let Err(err) = fs::write(&actual_path, actual) { self.fatal(&format!("failed to write {stream} to `{actual_path}`: {err}",)); } writeln!(self.stdout, "Saved the actual {stream} to `{actual_path}`"); @@ -2870,7 +2865,7 @@ impl<'test> TestCx<'test> { } if !actual.is_empty() { - if let Err(err) = fs::write(&expected_path, &actual) { + if let Err(err) = fs::write(&expected_path, actual) { self.fatal(&format!("failed to write {stream} to `{expected_path}`: {err}")); } writeln!( @@ -2971,7 +2966,7 @@ impl<'test> TestCx<'test> { ) { for kind in UI_EXTENSIONS { let canon_comparison_path = - expected_output_path(&self.testpaths, self.revision, &None, kind); + expected_output_path(self.testpaths, self.revision, &None, kind); let canon = match self.load_expected_output_from_path(&canon_comparison_path) { Ok(canon) => canon, @@ -2980,7 +2975,7 @@ impl<'test> TestCx<'test> { let bless = self.config.bless; let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| { let examined_path = - expected_output_path(&self.testpaths, self.revision, &Some(mode.clone()), kind); + expected_output_path(self.testpaths, self.revision, &Some(mode.clone()), kind); // If there is no output, there is nothing to do let examined_content = match self.load_expected_output_from_path(&examined_path) { @@ -3016,8 +3011,8 @@ impl<'test> TestCx<'test> { } fn create_stamp(&self) { - let stamp_file_path = stamp_file_path(&self.config, self.testpaths, self.revision); - fs::write(&stamp_file_path, compute_stamp_hash(&self.config)).unwrap(); + let stamp_file_path = stamp_file_path(self.config, self.testpaths, self.revision); + fs::write(&stamp_file_path, compute_stamp_hash(self.config)).unwrap(); } fn init_incremental_test(&self) { @@ -3034,7 +3029,7 @@ impl<'test> TestCx<'test> { let canonicalized = incremental_dir.canonicalize().unwrap(); fs::remove_dir_all(canonicalized).unwrap(); } - fs::create_dir_all(&incremental_dir).unwrap(); + fs::create_dir_all(incremental_dir).unwrap(); if self.config.verbose { writeln!(self.stdout, "init_incremental_test: incremental_dir={incremental_dir}"); diff --git a/src/tools/compiletest/src/runtest/codegen_units.rs b/src/tools/compiletest/src/runtest/codegen_units.rs index 16c251c3c9e24..615de33b1b371 100644 --- a/src/tools/compiletest/src/runtest/codegen_units.rs +++ b/src/tools/compiletest/src/runtest/codegen_units.rs @@ -26,7 +26,7 @@ impl TestCx<'_> { .stdout .lines() .filter(|line| line.starts_with(PREFIX)) - .map(|line| line.replace(&self.testpaths.file.as_str(), "TEST_PATH").to_string()) + .map(|line| line.replace(self.testpaths.file.as_str(), "TEST_PATH").to_string()) .map(|line| str_to_mono_item(&line, true)) .collect(); @@ -91,7 +91,7 @@ impl TestCx<'_> { wrong_cgus.sort_by_key(|pair| pair.0.name.clone()); writeln!(self.stdout, "\nThe following items were assigned to wrong codegen units:\n"); - for &(ref expected_item, ref actual_item) in &wrong_cgus { + for (expected_item, actual_item) in &wrong_cgus { writeln!(self.stdout, "{}", expected_item.name); writeln!( self.stdout, @@ -120,7 +120,7 @@ impl TestCx<'_> { // [MONO_ITEM] name [@@ (cgu)+] fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem { - let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() }; + let s = s.strip_prefix(PREFIX).unwrap_or(s).trim(); let full_string = format!("{}{}", PREFIX, s); diff --git a/src/tools/compiletest/src/runtest/compute_diff.rs b/src/tools/compiletest/src/runtest/compute_diff.rs index 3363127b3ea37..7c58749b64512 100644 --- a/src/tools/compiletest/src/runtest/compute_diff.rs +++ b/src/tools/compiletest/src/runtest/compute_diff.rs @@ -133,15 +133,15 @@ where if filter(entry.file_type(), extension) { let expected_path = compare_dir .as_std_path() - .join(entry.path().strip_prefix(&out_dir.as_std_path()).unwrap()); + .join(entry.path().strip_prefix(out_dir.as_std_path()).unwrap()); let expected = if let Ok(s) = std::fs::read(&expected_path) { s } else { continue }; let actual_path = entry.path(); - let actual = std::fs::read(&actual_path).unwrap(); + let actual = std::fs::read(actual_path).unwrap(); let diff = unified_diff::diff( &expected, - &expected_path.to_str().unwrap(), + expected_path.to_str().unwrap(), &actual, - &actual_path.to_str().unwrap(), + actual_path.to_str().unwrap(), 3, ); wrote_data |= !diff.is_empty(); @@ -157,7 +157,7 @@ where writeln!(cx.stderr, "printing diff:"); let mut buf = Vec::new(); diff_output.read_to_end(&mut buf).unwrap(); - std::io::stderr().lock().write_all(&mut buf).unwrap(); + std::io::stderr().lock().write_all(&buf).unwrap(); } true } diff --git a/src/tools/compiletest/src/runtest/coverage.rs b/src/tools/compiletest/src/runtest/coverage.rs index d0a0c960b4512..548c4d95eb4ea 100644 --- a/src/tools/compiletest/src/runtest/coverage.rs +++ b/src/tools/compiletest/src/runtest/coverage.rs @@ -47,10 +47,7 @@ impl<'test> TestCx<'test> { ); if coverage_dump_compare_outcome.should_error() { - self.fatal_proc_rec( - &format!("an error occurred comparing coverage output."), - &proc_res, - ); + self.fatal_proc_rec("an error occurred comparing coverage output.", &proc_res); } } @@ -145,10 +142,7 @@ impl<'test> TestCx<'test> { ); if coverage_dump_compare_outcome.should_error() { - self.fatal_proc_rec( - &format!("an error occurred comparing coverage output."), - &proc_res, - ); + self.fatal_proc_rec("an error occurred comparing coverage output.", &proc_res); } } @@ -276,7 +270,7 @@ impl<'test> TestCx<'test> { // ` | 1000|` => ` | LL|` // ` | | 1000|` => ` | | LL|` let coverage = static_regex!(r"(?m:^)(?(?: \|)*) *[0-9]+\|") - .replace_all(&coverage, "${prefix} LL|"); + .replace_all(coverage, "${prefix} LL|"); // ` | Branch (1:` => ` | Branch (LL:` // ` | | Branch (10:` => ` | | Branch (LL:` @@ -311,7 +305,7 @@ impl<'test> TestCx<'test> { // Sort the file sections (not including the final empty "section"). let except_last = sections.len() - 1; - (&mut sections[..except_last]).sort(); + sections[..except_last].sort(); // Join the file sections back into a flat list of lines, with // sections separated by blank lines. @@ -340,7 +334,7 @@ impl<'test> TestCx<'test> { // The last "subview" should be just a boundary line on its own, // so exclude it when sorting the other subviews. let except_last = subviews.len() - 1; - (&mut subviews[..except_last]).sort(); + subviews[..except_last].sort(); for view in subviews { for line in view { diff --git a/src/tools/compiletest/src/runtest/crashes.rs b/src/tools/compiletest/src/runtest/crashes.rs index 0aae7eaa39cd5..dd9c2edb55a02 100644 --- a/src/tools/compiletest/src/runtest/crashes.rs +++ b/src/tools/compiletest/src/runtest/crashes.rs @@ -14,13 +14,13 @@ impl TestCx<'_> { // if a test does not crash, consider it an error if proc_res.status.success() || matches!(proc_res.status.code(), Some(1 | 0)) { - self.fatal(&format!( + self.fatal( "crashtest no longer crashes/triggers ICE, hooray! Please give it a meaningful \ name, add a doc-comment to the start of the test explaining why it exists and \ move it to tests/ui or wherever you see fit. Adding 'Fixes #' to your PR \ description ensures that the corresponding ticket is auto-closed upon merge. \ - If you want to see verbose output, set `COMPILETEST_VERBOSE_CRASHES=1`." - )); + If you want to see verbose output, set `COMPILETEST_VERBOSE_CRASHES=1`.", + ); } } } diff --git a/src/tools/compiletest/src/runtest/debugger.rs b/src/tools/compiletest/src/runtest/debugger.rs index 3d439e98eb7e1..986afefcc02b7 100644 --- a/src/tools/compiletest/src/runtest/debugger.rs +++ b/src/tools/compiletest/src/runtest/debugger.rs @@ -42,10 +42,10 @@ impl DebuggerCommands { continue; }; - if let Some(command) = parse_name_value(&line, &command_directive) { + if let Some(command) = parse_name_value(line, &command_directive) { commands.push(command); } - if let Some(pattern) = parse_name_value(&line, &check_directive) { + if let Some(pattern) = parse_name_value(line, &check_directive) { check_lines.push((line_no, pattern)); } } @@ -69,7 +69,7 @@ impl DebuggerCommands { if let Some(offset) = dbg_lines .iter() .skip(last_idx) - .position(|out_line| check_single_line(out_line, &ck_line)) + .position(|out_line| check_single_line(out_line, ck_line)) { last_idx += offset; found.push((src_lineno, dbg_lines[last_idx])); diff --git a/src/tools/compiletest/src/runtest/debuginfo.rs b/src/tools/compiletest/src/runtest/debuginfo.rs index 9175a38ffa5c9..2d8222bfbcad5 100644 --- a/src/tools/compiletest/src/runtest/debuginfo.rs +++ b/src/tools/compiletest/src/runtest/debuginfo.rs @@ -183,7 +183,7 @@ impl TestCx<'_> { .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}")); Command::new(adb_path) - .args(&["forward", "tcp:5039", "tcp:5039"]) + .args(["forward", "tcp:5039", "tcp:5039"]) .status() .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}")); @@ -198,7 +198,7 @@ impl TestCx<'_> { debug!("adb arg: {}", adb_arg); let mut adb = Command::new(adb_path) - .args(&["shell", &adb_arg]) + .args(["shell", &adb_arg]) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .spawn() @@ -224,12 +224,12 @@ impl TestCx<'_> { &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script]; let gdb_path = self.config.gdb.as_ref().unwrap(); - let Output { status, stdout, stderr } = Command::new(&gdb_path) + let Output { status, stdout, stderr } = Command::new(gdb_path) .args(debugger_opts) .output() .unwrap_or_else(|e| panic!("failed to exec `{gdb_path:?}`: {e:?}")); let cmdline = { - let mut gdb = Command::new(&format!("{}-gdb", self.config.target)); + let mut gdb = Command::new(format!("{}-gdb", self.config.target)); gdb.args(debugger_opts); // FIXME(jieyouxu): don't pass an empty Path let cmdline = self.make_cmdline(&gdb, Utf8Path::new("")); @@ -502,7 +502,7 @@ impl TestCx<'_> { ) } - fn cleanup_debug_info_options(&self, options: &Vec) -> Vec { + fn cleanup_debug_info_options(&self, options: &[String]) -> Vec { // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS. let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()]; diff --git a/src/tools/compiletest/src/runtest/js_doc.rs b/src/tools/compiletest/src/runtest/js_doc.rs index fd53f01ca1746..9b071be28345a 100644 --- a/src/tools/compiletest/src/runtest/js_doc.rs +++ b/src/tools/compiletest/src/runtest/js_doc.rs @@ -7,11 +7,11 @@ impl TestCx<'_> { if let Some(nodejs) = &self.config.nodejs { let out_dir = self.output_base_dir(); - self.document(&out_dir, &self.testpaths); + self.document(&out_dir, self.testpaths); let file_stem = self.testpaths.file.file_stem().expect("no file stem"); let res = self.run_command_to_procres( - Command::new(&nodejs) + Command::new(nodejs) .arg(self.config.src_root.join("src/tools/rustdoc-js/tester.js")) .arg("--doc-folder") .arg(out_dir) diff --git a/src/tools/compiletest/src/runtest/mir_opt.rs b/src/tools/compiletest/src/runtest/mir_opt.rs index 9448792638346..d772fa84dbad1 100644 --- a/src/tools/compiletest/src/runtest/mir_opt.rs +++ b/src/tools/compiletest/src/runtest/mir_opt.rs @@ -14,7 +14,7 @@ impl TestCx<'_> { let should_run = self.should_run(pm); let mut test_info = files_for_miropt_test( - &self.testpaths.file.as_std_path(), + self.testpaths.file.as_std_path(), self.config.get_pointer_width(), self.config.target_cfg().panic.for_miropt_test_tools(), ); diff --git a/src/tools/compiletest/src/runtest/run_make.rs b/src/tools/compiletest/src/runtest/run_make.rs index 738f504d5c1cf..472eb242452fe 100644 --- a/src/tools/compiletest/src/runtest/run_make.rs +++ b/src/tools/compiletest/src/runtest/run_make.rs @@ -47,7 +47,7 @@ impl TestCx<'_> { if path.file_name().is_some_and(|s| s != "rmake.rs") { let target = rmake_out_dir.join(path.strip_prefix(&self.testpaths.file).unwrap()); if path.is_dir() { - copy_dir_all(&path, &target).unwrap(); + copy_dir_all(path, &target).unwrap(); } else { fs::copy(path.as_std_path(), target).unwrap(); } @@ -108,7 +108,7 @@ impl TestCx<'_> { .stage0_rustc_path .as_ref() .expect("stage0 rustc is required to run run-make tests"); - let mut rustc = Command::new(&stage0_rustc); + let mut rustc = Command::new(stage0_rustc); rustc // `rmake.rs` **must** be buildable by a stable compiler, it may not use *any* unstable // library or compiler features. Here, we force the stage 0 rustc to consider itself as @@ -126,7 +126,7 @@ impl TestCx<'_> { .arg("--extern") .arg(format!("run_make_support={}", &support_lib_path)) .arg("--edition=2021") - .arg(&self.testpaths.file.join("rmake.rs")) + .arg(self.testpaths.file.join("rmake.rs")) .arg("-Cprefer-dynamic"); // In test code we want to be very pedantic about values being silently discarded that are @@ -169,7 +169,7 @@ impl TestCx<'_> { .env("LD_LIB_PATH_ENVVAR", dylib_env_var()) // Provide the dylib search paths. // This is required to run the **recipe** itself. - .env(dylib_env_var(), &env::join_paths(recipe_dylib_search_paths).unwrap()) + .env(dylib_env_var(), env::join_paths(recipe_dylib_search_paths).unwrap()) // Provide the directory to libraries that are needed to run the *compiler* invoked // by the recipe. .env("HOST_RUSTC_DYLIB_PATH", &self.config.compile_lib_path) diff --git a/src/tools/compiletest/src/runtest/rustdoc.rs b/src/tools/compiletest/src/runtest/rustdoc.rs index 4a143aa5824e7..aa130789982da 100644 --- a/src/tools/compiletest/src/runtest/rustdoc.rs +++ b/src/tools/compiletest/src/runtest/rustdoc.rs @@ -11,7 +11,7 @@ impl TestCx<'_> { panic!("failed to remove and recreate output directory `{out_dir}`: {e}") }); - let proc_res = self.document(&out_dir, &self.testpaths); + let proc_res = self.document(&out_dir, self.testpaths); if !proc_res.status.success() { self.fatal_proc_rec("rustdoc failed!", &proc_res); } diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs index b8da6e2ac5280..cc8b019064900 100644 --- a/src/tools/compiletest/src/runtest/rustdoc_json.rs +++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs @@ -13,7 +13,7 @@ impl TestCx<'_> { panic!("failed to remove and recreate output directory `{out_dir}`: {e}") }); - let proc_res = self.document(&out_dir, &self.testpaths); + let proc_res = self.document(&out_dir, self.testpaths); if !proc_res.status.success() { self.fatal_proc_rec("rustdoc failed!", &proc_res); } diff --git a/src/tools/compiletest/src/runtest/ui.rs b/src/tools/compiletest/src/runtest/ui.rs index d683a325c8666..44b188ca87f40 100644 --- a/src/tools/compiletest/src/runtest/ui.rs +++ b/src/tools/compiletest/src/runtest/ui.rs @@ -151,7 +151,7 @@ impl TestCx<'_> { let code = proc_res.status.code(); let run_result = if proc_res.status.success() { RunResult::Pass - } else if code.is_some_and(|c| c >= 1 && c <= 127) { + } else if code.is_some_and(|c| (1..=127).contains(&c)) { RunResult::Fail } else { RunResult::Crash diff --git a/src/tools/compiletest/src/util.rs b/src/tools/compiletest/src/util.rs index a189c1d1c2dfc..dc8a833cb339e 100644 --- a/src/tools/compiletest/src/util.rs +++ b/src/tools/compiletest/src/util.rs @@ -35,7 +35,7 @@ impl Utf8PathBufExt for Utf8PathBuf { } else { let mut fname = self.file_name().unwrap().to_string(); if !extension.starts_with('.') { - fname.push_str("."); + fname.push('.'); } fname.push_str(extension); self.with_file_name(fname) diff --git a/src/tools/coverage-dump/src/covfun.rs b/src/tools/coverage-dump/src/covfun.rs index 1cc9f4dc5d6a3..60b8c767f3787 100644 --- a/src/tools/coverage-dump/src/covfun.rs +++ b/src/tools/coverage-dump/src/covfun.rs @@ -160,8 +160,8 @@ fn parse_covfun_line(line: &str) -> anyhow::Result { let captures = RE.captures(line).with_context(|| format!("couldn't parse covfun line: {line:?}"))?; let is_used = captures.name("is_used").is_some(); - let name_hash = i64::from_str_radix(&captures["name_hash"], 10).unwrap() as u64; - let filenames_hash = i64::from_str_radix(&captures["filenames_hash"], 10).unwrap() as u64; + let name_hash = captures["name_hash"].parse::().unwrap() as u64; + let filenames_hash = captures["name_hash"].parse::().unwrap() as u64; let payload = unescape_llvm_string_contents(&captures["payload"]); Ok(CovfunLineData { is_used, name_hash, filenames_hash, payload }) diff --git a/src/tools/coverage-dump/src/main.rs b/src/tools/coverage-dump/src/main.rs index 2c76d2f246022..0bad442e640db 100644 --- a/src/tools/coverage-dump/src/main.rs +++ b/src/tools/coverage-dump/src/main.rs @@ -12,7 +12,7 @@ fn main() -> anyhow::Result<()> { // The coverage-dump tool already needs `rustc_demangle` in order to read // coverage metadata, so it's very easy to also have a separate mode that // turns it into a command-line demangler for use by coverage-run tests. - if &args[1..] == &["--demangle"] { + if args[1..] == ["--demangle"] { return demangle(); } diff --git a/src/tools/features-status-dump/src/main.rs b/src/tools/features-status-dump/src/main.rs index a4f88362ab816..cfdb31285625e 100644 --- a/src/tools/features-status-dump/src/main.rs +++ b/src/tools/features-status-dump/src/main.rs @@ -33,7 +33,7 @@ fn main() -> Result<()> { let lang_features_status = collect_lang_features(&compiler_path, &mut RunningCheck::new_noop()); let lib_features_status = collect_lib_features(&library_path) .into_iter() - .filter(|&(ref name, _)| !lang_features_status.contains_key(name)) + .filter(|(name, _)| !lang_features_status.contains_key(name)) .collect(); let features_status = FeaturesStatus { lang_features_status, lib_features_status }; diff --git a/src/tools/generate-copyright/src/cargo_metadata.rs b/src/tools/generate-copyright/src/cargo_metadata.rs index 87cd85c8def4e..adf6b20b9b53a 100644 --- a/src/tools/generate-copyright/src/cargo_metadata.rs +++ b/src/tools/generate-copyright/src/cargo_metadata.rs @@ -55,7 +55,7 @@ pub fn get_metadata_and_notices( // Now for each dependency we found, go and grab any important looking files for (package, metadata) in output.iter_mut() { - load_important_files(package, metadata, &vendor_path)?; + load_important_files(package, metadata, vendor_path)?; } Ok(output) diff --git a/src/tools/generate-windows-sys/src/main.rs b/src/tools/generate-windows-sys/src/main.rs index 6bf47e840627e..40998715f06f0 100644 --- a/src/tools/generate-windows-sys/src/main.rs +++ b/src/tools/generate-windows-sys/src/main.rs @@ -58,7 +58,7 @@ fn sort_bindings(file_name: &str) -> Result<(), Box> { bindings.push(line); } } - bindings.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase())); + bindings.sort_by_key(|a| a.to_lowercase()); for line in bindings { f.write(line.as_bytes())?; } diff --git a/src/tools/html-checker/main.rs b/src/tools/html-checker/main.rs index d5335d9e72e51..9ecf65e5f1ad6 100644 --- a/src/tools/html-checker/main.rs +++ b/src/tools/html-checker/main.rs @@ -64,10 +64,7 @@ fn find_all_html_files(dir: &Path) -> (usize, usize) { .into_iter() .filter_entry(|e| { e.depth() != 1 - || e.file_name() - .to_str() - .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) - .unwrap_or(false) + || e.file_name().to_str().map(|s| DOCS_TO_CHECK.contains(&s)).unwrap_or(false) }) .par_bridge() .map(|entry| { @@ -78,7 +75,7 @@ fn find_all_html_files(dir: &Path) -> (usize, usize) { let entry = entry.path(); // (Number of files processed, number of errors) if entry.extension().and_then(|s| s.to_str()) == Some("html") { - (1, check_html_file(&entry)) + (1, check_html_file(entry)) } else { (0, 0) } @@ -117,7 +114,7 @@ fn main() -> Result<(), String> { println!("Running HTML checker..."); - let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); + let (files_read, errors) = find_all_html_files(Path::new(&args[1])); println!("Done! Read {} files...", files_read); if errors > 0 { Err(format!("HTML check failed: {} errors", errors)) diff --git a/src/tools/jsondocck/src/cache.rs b/src/tools/jsondocck/src/cache.rs index 1369c8ded0070..f7b9a6171cdcf 100644 --- a/src/tools/jsondocck/src/cache.rs +++ b/src/tools/jsondocck/src/cache.rs @@ -19,7 +19,7 @@ impl Cache { // `filename` needs to replace `-` with `_` to be sure the JSON path will always be valid. let filename = Path::new(&config.template).file_stem().unwrap().to_str().unwrap().replace('-', "_"); - let file_path = root.join(&Path::with_extension(Path::new(&filename), "json")); + let file_path = root.join(Path::with_extension(Path::new(&filename), "json")); let content = fs::read_to_string(&file_path).expect("failed to read JSON file"); Cache { diff --git a/src/tools/jsondocck/src/directive.rs b/src/tools/jsondocck/src/directive.rs index c52c16866608d..9ba2ad0c85d41 100644 --- a/src/tools/jsondocck/src/directive.rs +++ b/src/tools/jsondocck/src/directive.rs @@ -214,12 +214,13 @@ fn get_one<'a>(matches: &[&'a Value]) -> Result<&'a Value, String> { } fn string_to_value<'a>(s: &str, cache: &'a Cache) -> Cow<'a, Value> { - if s.starts_with("$") { - Cow::Borrowed(&cache.variables.get(&s[1..]).unwrap_or_else(|| { + match s.strip_prefix("$") { + Some(s) => Cow::Borrowed(cache.variables.get(s).unwrap_or_else(|| { // FIXME(adotinthevoid): Show line number - panic!("No variable: `{}`. Current state: `{:?}`", &s[1..], cache.variables) - })) - } else { - Cow::Owned(serde_json::from_str(s).expect(&format!("Cannot convert `{}` to json", s))) + panic!("No variable: `{}`. Current state: `{:?}`", s, cache.variables) + })), + None => Cow::Owned( + serde_json::from_str(s).unwrap_or_else(|_| panic!("Cannot convert {} to json", s)), + ), } } diff --git a/src/tools/jsondoclint/src/item_kind.rs b/src/tools/jsondoclint/src/item_kind.rs index e2738636a1458..d2e08cd9e5853 100644 --- a/src/tools/jsondoclint/src/item_kind.rs +++ b/src/tools/jsondoclint/src/item_kind.rs @@ -77,11 +77,7 @@ impl Kind { } pub fn can_appear_in_glob_import(self) -> bool { - match self { - Kind::Module => true, - Kind::Enum => true, - _ => false, - } + matches!(self, Kind::Module | Kind::Enum) } pub fn can_appear_in_trait(self) -> bool { diff --git a/src/tools/jsondoclint/src/main.rs b/src/tools/jsondoclint/src/main.rs index 5cbf346086062..f4278658200f0 100644 --- a/src/tools/jsondoclint/src/main.rs +++ b/src/tools/jsondoclint/src/main.rs @@ -81,7 +81,7 @@ fn main() -> Result<()> { [sel] => eprintln!( "{} not in index or paths, but referred to at '{}'", err.id.0, - json_find::to_jsonpath(&sel) + json_find::to_jsonpath(sel) ), [sel, ..] => { if verbose { @@ -99,7 +99,7 @@ fn main() -> Result<()> { eprintln!( "{} not in index or paths, but referred to at '{}' and {} more", err.id.0, - json_find::to_jsonpath(&sel), + json_find::to_jsonpath(sel), sels.len() - 1, ) } diff --git a/src/tools/jsondoclint/src/validator.rs b/src/tools/jsondoclint/src/validator.rs index 0a4051fcbe8cd..181798afa2fe4 100644 --- a/src/tools/jsondoclint/src/validator.rs +++ b/src/tools/jsondoclint/src/validator.rs @@ -262,17 +262,17 @@ impl<'a> Validator<'a> { Type::Generic(_) => {} Type::Primitive(_) => {} Type::Pat { type_, __pat_unstable_do_not_use: _ } => self.check_type(type_), - Type::FunctionPointer(fp) => self.check_function_pointer(&**fp), + Type::FunctionPointer(fp) => self.check_function_pointer(fp), Type::Tuple(tys) => tys.iter().for_each(|ty| self.check_type(ty)), - Type::Slice(inner) => self.check_type(&**inner), - Type::Array { type_, len: _ } => self.check_type(&**type_), + Type::Slice(inner) => self.check_type(inner), + Type::Array { type_, len: _ } => self.check_type(type_), Type::ImplTrait(bounds) => bounds.iter().for_each(|b| self.check_generic_bound(b)), Type::Infer => {} - Type::RawPointer { is_mutable: _, type_ } => self.check_type(&**type_), - Type::BorrowedRef { lifetime: _, is_mutable: _, type_ } => self.check_type(&**type_), + Type::RawPointer { is_mutable: _, type_ } => self.check_type(type_), + Type::BorrowedRef { lifetime: _, is_mutable: _, type_ } => self.check_type(type_), Type::QualifiedPath { name: _, args, self_type, trait_ } => { - self.check_opt_generic_args(&args); - self.check_type(&**self_type); + self.check_opt_generic_args(args); + self.check_type(self_type); if let Some(trait_) = trait_ { self.check_path(trait_, PathKind::Trait); } @@ -404,7 +404,7 @@ impl<'a> Validator<'a> { // which encodes rustc implementation details. if item_info.crate_id == LOCAL_CRATE_ID && !self.krate.index.contains_key(id) { self.errs.push(Error { - id: id.clone(), + id: *id, kind: ErrorKind::Custom( "Id for local item in `paths` but not in `index`".to_owned(), ), @@ -483,16 +483,14 @@ impl<'a> Validator<'a> { } fn fail(&mut self, id: &Id, kind: ErrorKind) { - self.errs.push(Error { id: id.clone(), kind }); + self.errs.push(Error { id: *id, kind }); } fn kind_of(&mut self, id: &Id) -> Option { if let Some(item) = self.krate.index.get(id) { Some(Kind::from_item(item)) - } else if let Some(summary) = self.krate.paths.get(id) { - Some(Kind::from_summary(summary)) } else { - None + self.krate.paths.get(id).map(Kind::from_summary) } } } diff --git a/src/tools/jsondoclint/src/validator/tests.rs b/src/tools/jsondoclint/src/validator/tests.rs index dd0b4ac5601a7..74bf5b0595ad3 100644 --- a/src/tools/jsondoclint/src/validator/tests.rs +++ b/src/tools/jsondoclint/src/validator/tests.rs @@ -78,7 +78,7 @@ fn errors_on_local_in_paths_and_not_index() { span: None, visibility: Visibility::Public, docs: None, - links: FxHashMap::from_iter([(("prim@i32".to_owned(), Id(2)))]), + links: FxHashMap::from_iter([("prim@i32".to_owned(), Id(2))]), attrs: Vec::new(), deprecation: None, inner: ItemEnum::Module(Module { diff --git a/src/tools/linkchecker/main.rs b/src/tools/linkchecker/main.rs index e07a0784cdb3a..a259e5e1084da 100644 --- a/src/tools/linkchecker/main.rs +++ b/src/tools/linkchecker/main.rs @@ -306,7 +306,7 @@ impl Checker { Some((url, fragment)) => (url, Some(fragment)), }; // NB: the `splitn` always succeeds, even if the delimiter is not present. - let url = url.splitn(2, '?').next().unwrap(); + let url = url.split('?').next().unwrap(); // Once we've plucked out the URL, parse it using our base url and // then try to extract a file path. @@ -417,7 +417,7 @@ impl Checker { return; } - parse_ids(&mut target_ids.borrow_mut(), &pretty_path, target_source, report); + parse_ids(&mut target_ids.borrow_mut(), pretty_path, target_source, report); if target_ids.borrow().contains(*fragment) { return; @@ -585,11 +585,11 @@ fn maybe_redirect(source: &str) -> Option { fn parse_html(source: &str, sink: Sink) -> Sink { let tendril: ByteTendril = source.as_bytes().into(); - let mut input = BufferQueue::default(); + let input = BufferQueue::default(); input.push_back(tendril.try_reinterpret().unwrap()); let tok = Tokenizer::new(sink, TokenizerOpts::default()); - let _ = tok.feed(&mut input); + let _ = tok.feed(&input); assert!(input.is_empty()); tok.end(); tok.sink @@ -615,34 +615,32 @@ impl TokenSink for AttrCollector { type Handle = (); fn process_token(&self, token: Token, line_number: u64) -> TokenSinkResult<()> { - match token { - TagToken(tag) => { - let tag_name = tag.name.as_bytes(); - if tag_name == b"base" { - if let Some(href) = - tag.attrs.iter().find(|attr| attr.name.local.as_bytes() == b"href") - { - self.base.set(Some(href.value.to_string())); - } - return TokenSinkResult::Continue; - } else if tag_name == b"script" { - self.in_script.set(!self.in_script.get()); - } - if self.in_script.get() { - return TokenSinkResult::Continue; + if let TagToken(tag) = token { + let tag_name = tag.name.as_bytes(); + if tag_name == b"base" { + if let Some(href) = + tag.attrs.iter().find(|attr| attr.name.local.as_bytes() == b"href") + { + self.base.set(Some(href.value.to_string())); } - for attr in tag.attrs.iter() { - let name = attr.name.local.as_bytes(); - if name == self.attr_name { - let url = attr.value.to_string(); - self.found_attrs.borrow_mut().push((line_number, url)); - } + return TokenSinkResult::Continue; + } else if tag_name == b"script" { + self.in_script.set(!self.in_script.get()); + } + if self.in_script.get() { + return TokenSinkResult::Continue; + } + for attr in tag.attrs.iter() { + let name = attr.name.local.as_bytes(); + if name == self.attr_name { + let url = attr.value.to_string(); + self.found_attrs.borrow_mut().push((line_number, url)); } } - // Note: ParseError is pretty noisy. It seems html5ever does not - // particularly like some kinds of HTML comments. - _ => {} } + + // Note: ParseError is pretty noisy. It seems html5ever does not + // particularly like some kinds of HTML comments. TokenSinkResult::Continue } } diff --git a/src/tools/llvm-bitcode-linker/src/linker.rs b/src/tools/llvm-bitcode-linker/src/linker.rs index dafd847e76808..8250a196903d7 100644 --- a/src/tools/llvm-bitcode-linker/src/linker.rs +++ b/src/tools/llvm-bitcode-linker/src/linker.rs @@ -97,7 +97,7 @@ impl Session { // We add an internalize pass as the rust compiler as we require exported symbols to be explicitly marked passes.push_str(",internalize,globaldce"); - let symbol_file_content = self.symbols.iter().fold(String::new(), |s, x| s + &x + "\n"); + let symbol_file_content = self.symbols.iter().fold(String::new(), |s, x| s + x + "\n"); std::fs::write(&self.sym_path, symbol_file_content) .context(format!("Failed to write symbol file: {}", self.sym_path.display()))?; @@ -142,7 +142,7 @@ impl Session { } if let Some(mattr) = &self.feature { - lcc_command.arg(&format!("--mattr={}", mattr)); + lcc_command.arg(format!("--mattr={}", mattr)); } let lcc_output = lcc_command diff --git a/src/tools/opt-dist/src/bolt.rs b/src/tools/opt-dist/src/bolt.rs index 3ee9912b8c26d..a3e7d512626a5 100644 --- a/src/tools/opt-dist/src/bolt.rs +++ b/src/tools/opt-dist/src/bolt.rs @@ -30,7 +30,7 @@ pub fn with_bolt_instrumented anyhow::Result, R>( cmd(&[env.llvm_bolt().as_str()]) .arg("-instrument") .arg(path) - .arg(&format!("--instrumentation-file={profile_prefix}")) + .arg(format!("--instrumentation-file={profile_prefix}")) // Make sure that each process will write its profiles into a separate file .arg("--instrumentation-file-append-pid") .arg("-o") diff --git a/src/tools/opt-dist/src/exec.rs b/src/tools/opt-dist/src/exec.rs index a3935f9835956..fdb879945cfc2 100644 --- a/src/tools/opt-dist/src/exec.rs +++ b/src/tools/opt-dist/src/exec.rs @@ -105,9 +105,9 @@ impl Bootstrap { env.checkout_path().join("x.py").as_str(), "build", "--target", - &env.host_tuple(), + env.host_tuple(), "--host", - &env.host_tuple(), + env.host_tuple(), "--stage", "2", "library/std", diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs index fa55805bbf212..f432967cde341 100644 --- a/src/tools/opt-dist/src/tests.rs +++ b/src/tools/opt-dist/src/tests.rs @@ -37,7 +37,7 @@ pub fn run_tests(env: &Environment) -> anyhow::Result<()> { let extracted_src_dir = extract_dist_dir(&format!("rust-src-{version}"))?.join("rust-src"); // If we have a Cranelift archive, copy it to the rustc sysroot - if let Ok(_) = find_file_in_dir(&dist_dir, "rustc-codegen-cranelift-", ".tar.xz") { + if find_file_in_dir(&dist_dir, "rustc-codegen-cranelift-", ".tar.xz").is_ok() { let extracted_codegen_dir = extract_dist_dir(&format!("rustc-codegen-cranelift-{version}-{host_triple}"))? .join("rustc-codegen-cranelift-preview"); diff --git a/src/tools/remote-test-client/src/main.rs b/src/tools/remote-test-client/src/main.rs index b9741431b5034..24c47ea8ec0d3 100644 --- a/src/tools/remote-test-client/src/main.rs +++ b/src/tools/remote-test-client/src/main.rs @@ -132,7 +132,7 @@ fn prepare_rootfs_cpio(rootfs: &Path, rootfs_img: &Path) { let mut stdin = child.stdin.take().unwrap(); let rootfs = rootfs.to_path_buf(); thread::spawn(move || add_files(&mut stdin, &rootfs, &rootfs)); - t!(io::copy(&mut child.stdout.take().unwrap(), &mut t!(File::create(&rootfs_img)))); + t!(io::copy(&mut child.stdout.take().unwrap(), &mut t!(File::create(rootfs_img)))); assert!(t!(child.wait()).success()); fn add_files(w: &mut dyn Write, root: &Path, cur: &Path) { @@ -151,7 +151,7 @@ fn prepare_rootfs_cpio(rootfs: &Path, rootfs_img: &Path) { fn prepare_rootfs_ext4(rootfs: &Path, rootfs_img: &Path) { let mut dd = Command::new("dd"); dd.arg("if=/dev/zero") - .arg(&format!("of={}", rootfs_img.to_string_lossy())) + .arg(format!("of={}", rootfs_img.to_string_lossy())) .arg("bs=1M") .arg("count=1024"); let mut dd_child = t!(dd.spawn()); @@ -178,7 +178,7 @@ fn start_qemu_emulator(target: &str, rootfs: &Path, server: &Path, tmpdir: &Path .arg("-kernel") .arg("/tmp/zImage") .arg("-initrd") - .arg(&rootfs_img) + .arg(rootfs_img) .arg("-dtb") .arg("/tmp/vexpress-v2p-ca15-tc1.dtb") .arg("-append") @@ -201,7 +201,7 @@ fn start_qemu_emulator(target: &str, rootfs: &Path, server: &Path, tmpdir: &Path .arg("-kernel") .arg("/tmp/Image") .arg("-initrd") - .arg(&rootfs_img) + .arg(rootfs_img) .arg("-append") .arg("console=ttyAMA0 root=/dev/ram rdinit=/sbin/init init=/sbin/init") .arg("-nographic") @@ -231,7 +231,7 @@ fn start_qemu_emulator(target: &str, rootfs: &Path, server: &Path, tmpdir: &Path .arg("-device") .arg("virtio-blk-device,drive=hd0") .arg("-drive") - .arg(&format!("file={},format=raw,id=hd0", &rootfs_img.to_string_lossy())); + .arg(format!("file={},format=raw,id=hd0", &rootfs_img.to_string_lossy())); t!(cmd.spawn()); } _ => panic!("cannot start emulator for: {}", target), @@ -288,7 +288,7 @@ fn run(support_lib_count: usize, exe: String, all_args: Vec) { // Send over support libraries for file in support_libs.iter().map(Path::new) { - send(&file, &mut client); + send(file, &mut client); } t!(client.write_all(&[0])); @@ -330,7 +330,7 @@ fn run(support_lib_count: usize, exe: String, all_args: Vec) { let code = ((status[1] as i32) << 24) | ((status[2] as i32) << 16) | ((status[3] as i32) << 8) - | ((status[4] as i32) << 0); + | (status[4] as i32); if status[0] == 0 { std::process::exit(code); } else { @@ -344,7 +344,7 @@ fn run(support_lib_count: usize, exe: String, all_args: Vec) { fn send(path: &Path, dst: &mut dyn Write) { t!(dst.write_all(path.file_name().unwrap().to_str().unwrap().as_bytes())); t!(dst.write_all(&[0])); - let mut file = t!(File::open(&path)); + let mut file = t!(File::open(path)); let amt = t!(file.metadata()).len(); t!(dst.write_all(&amt.to_be_bytes())); diff --git a/src/tools/remote-test-server/src/main.rs b/src/tools/remote-test-server/src/main.rs index 5ec5e6e28982d..ec27860d7d0d8 100644 --- a/src/tools/remote-test-server/src/main.rs +++ b/src/tools/remote-test-server/src/main.rs @@ -176,7 +176,7 @@ fn bind_socket(addr: SocketAddr) -> TcpListener { fn handle_push(socket: TcpStream, work: &Path, config: Config) { let mut reader = BufReader::new(socket); - let dst = recv(&work, &mut reader); + let dst = recv(work, &mut reader); print_verbose(&format!("push {:#?}", dst), config); let mut socket = reader.into_inner(); @@ -321,7 +321,7 @@ fn handle_run(socket: TcpStream, work: &Path, tmp: &Path, lock: &Mutex<()>, conf (code >> 24) as u8, (code >> 16) as u8, (code >> 8) as u8, - (code >> 0) as u8, + code as u8, ])); } @@ -361,7 +361,7 @@ fn recv(dir: &Path, io: &mut B) -> PathBuf { #[cfg(not(windows))] fn set_permissions(path: &Path) { - t!(fs::set_permissions(&path, Permissions::from_mode(0o755))); + t!(fs::set_permissions(path, Permissions::from_mode(0o755))); } #[cfg(windows)] fn set_permissions(_path: &Path) {} diff --git a/src/tools/replace-version-placeholder/src/main.rs b/src/tools/replace-version-placeholder/src/main.rs index fb2838a4ea03b..c794897023577 100644 --- a/src/tools/replace-version-placeholder/src/main.rs +++ b/src/tools/replace-version-placeholder/src/main.rs @@ -23,7 +23,7 @@ fn main() { } let new_contents = contents.replace(VERSION_PLACEHOLDER, version_str); let path = entry.path(); - t!(std::fs::write(&path, new_contents), path); + t!(std::fs::write(path, new_contents), path); }, ); } diff --git a/src/tools/run-make-support/src/assertion_helpers/mod.rs b/src/tools/run-make-support/src/assertion_helpers/mod.rs index 9b666473b5b37..d8e7bc654cb20 100644 --- a/src/tools/run-make-support/src/assertion_helpers/mod.rs +++ b/src/tools/run-make-support/src/assertion_helpers/mod.rs @@ -115,10 +115,10 @@ pub fn assert_dirs_are_equal(dir1: impl AsRef, dir2: impl AsRef) { fs::read_dir_entries(dir1, |entry_path| { let entry_name = entry_path.file_name().unwrap(); if entry_path.is_dir() { - assert_dirs_are_equal(&entry_path, &dir2.join(entry_name)); + assert_dirs_are_equal(entry_path, dir2.join(entry_name)); } else { let path2 = dir2.join(entry_name); - let file1 = fs::read(&entry_path); + let file1 = fs::read(entry_path); let file2 = fs::read(&path2); // We don't use `assert_eq!` because they are `Vec`, so not great for display. diff --git a/src/tools/run-make-support/src/command.rs b/src/tools/run-make-support/src/command.rs index b46ddd1d3154b..a69731991109e 100644 --- a/src/tools/run-make-support/src/command.rs +++ b/src/tools/run-make-support/src/command.rs @@ -219,7 +219,7 @@ impl Command { pub fn run(&mut self) -> CompletedProcess { let output = self.command_output(); if !output.status().success() { - handle_failed_output(&self, output, panic::Location::caller().line()); + handle_failed_output(self, output, panic::Location::caller().line()); } output } @@ -231,7 +231,7 @@ impl Command { pub fn run_fail(&mut self) -> CompletedProcess { let output = self.command_output(); if output.status().success() { - handle_failed_output(&self, output, panic::Location::caller().line()); + handle_failed_output(self, output, panic::Location::caller().line()); } output } @@ -334,28 +334,28 @@ impl CompletedProcess { /// Checks that `stdout` does not contain `unexpected`. #[track_caller] pub fn assert_stdout_not_contains>(&self, unexpected: S) -> &Self { - assert_not_contains(&self.stdout_utf8(), unexpected); + assert_not_contains(self.stdout_utf8(), unexpected); self } /// Checks that `stdout` does not contain the regex pattern `unexpected`. #[track_caller] pub fn assert_stdout_not_contains_regex>(&self, unexpected: S) -> &Self { - assert_not_contains_regex(&self.stdout_utf8(), unexpected); + assert_not_contains_regex(self.stdout_utf8(), unexpected); self } /// Checks that `stdout` contains `expected`. #[track_caller] pub fn assert_stdout_contains>(&self, expected: S) -> &Self { - assert_contains(&self.stdout_utf8(), expected); + assert_contains(self.stdout_utf8(), expected); self } /// Checks that `stdout` contains the regex pattern `expected`. #[track_caller] pub fn assert_stdout_contains_regex>(&self, expected: S) -> &Self { - assert_contains_regex(&self.stdout_utf8(), expected); + assert_contains_regex(self.stdout_utf8(), expected); self } @@ -369,28 +369,28 @@ impl CompletedProcess { /// Checks that `stderr` contains `expected`. #[track_caller] pub fn assert_stderr_contains>(&self, expected: S) -> &Self { - assert_contains(&self.stderr_utf8(), expected); + assert_contains(self.stderr_utf8(), expected); self } /// Checks that `stderr` contains the regex pattern `expected`. #[track_caller] pub fn assert_stderr_contains_regex>(&self, expected: S) -> &Self { - assert_contains_regex(&self.stderr_utf8(), expected); + assert_contains_regex(self.stderr_utf8(), expected); self } /// Checks that `stderr` does not contain `unexpected`. #[track_caller] pub fn assert_stderr_not_contains>(&self, unexpected: S) -> &Self { - assert_not_contains(&self.stderr_utf8(), unexpected); + assert_not_contains(self.stderr_utf8(), unexpected); self } /// Checks that `stderr` does not contain the regex pattern `unexpected`. #[track_caller] pub fn assert_stderr_not_contains_regex>(&self, unexpected: S) -> &Self { - assert_not_contains_regex(&self.stderr_utf8(), unexpected); + assert_not_contains_regex(self.stderr_utf8(), unexpected); self } diff --git a/src/tools/run-make-support/src/env.rs b/src/tools/run-make-support/src/env.rs index cf1a6f7351a7f..eb3de6f93ba61 100644 --- a/src/tools/run-make-support/src/env.rs +++ b/src/tools/run-make-support/src/env.rs @@ -38,6 +38,7 @@ pub fn std_debug_assertions_enabled() -> bool { /// path in the panic message. #[track_caller] pub fn set_current_dir>(dir: P) { - std::env::set_current_dir(dir.as_ref()) - .expect(&format!("could not set current directory to \"{}\"", dir.as_ref().display())); + std::env::set_current_dir(dir.as_ref()).unwrap_or_else(|_| { + panic!("could not set current directory to \"{}\"", dir.as_ref().display()) + }); } diff --git a/src/tools/run-make-support/src/external_deps/c_build.rs b/src/tools/run-make-support/src/external_deps/c_build.rs index ecbf5ba8fe0d0..b2689295a2bf7 100644 --- a/src/tools/run-make-support/src/external_deps/c_build.rs +++ b/src/tools/run-make-support/src/external_deps/c_build.rs @@ -24,7 +24,7 @@ pub fn build_native_static_lib_optimized(lib_name: &str) -> PathBuf { #[track_caller] fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { - let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { lib_name.to_string() } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = static_lib_name(lib_name); @@ -50,7 +50,7 @@ fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { /// [`std::env::consts::DLL_PREFIX`] and [`std::env::consts::DLL_EXTENSION`]. #[track_caller] pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { - let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { lib_name.to_string() } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = dynamic_lib_name(lib_name); if is_windows_msvc() { @@ -62,13 +62,13 @@ pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { if is_windows_msvc() { format!("{lib_name}.obj") } else { format!("{lib_name}.o") }; if is_windows_msvc() { let out_arg = format!("-out:{lib_path}"); - cc().input(&obj_file).args(&["-link", "-dll", &out_arg]).run(); + cc().input(&obj_file).args(["-link", "-dll", &out_arg]).run(); } else if is_darwin() { - cc().out_exe(&lib_path).input(&obj_file).args(&["-dynamiclib", "-Wl,-dylib"]).run(); + cc().out_exe(&lib_path).input(&obj_file).args(["-dynamiclib", "-Wl,-dylib"]).run(); } else if is_windows() { cc().out_exe(&lib_path) .input(&obj_file) - .args(&["-shared", &format!("-Wl,--out-implib={lib_path}.a")]) + .args(["-shared", &format!("-Wl,--out-implib={lib_path}.a")]) .run(); } else { cc().out_exe(&lib_path).input(&obj_file).arg("-shared").run(); @@ -80,7 +80,7 @@ pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { /// Built from a C++ file. #[track_caller] pub fn build_native_static_lib_cxx(lib_name: &str) -> PathBuf { - let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { lib_name.to_string() } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.cpp"); let lib_path = static_lib_name(lib_name); if is_windows_msvc() { diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index b461a24a06168..3483481efa21a 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -33,7 +33,7 @@ pub struct Rustc { // Only fill in the target just before execution, so that it can be overridden. crate::macros::impl_common_helpers!(Rustc, |rustc: &mut Rustc| { if let Some(target) = &rustc.target { - rustc.cmd.arg(&format!("--target={target}")); + rustc.cmd.arg(format!("--target={target}")); } }); @@ -232,7 +232,7 @@ impl Rustc { /// Specify `-C prefer-dynamic`. pub fn prefer_dynamic(&mut self) -> &mut Self { - self.cmd.arg(format!("-Cprefer-dynamic")); + self.cmd.arg("-Cprefer-dynamic"); self } @@ -250,7 +250,7 @@ impl Rustc { /// Normalize the line number in the stderr output pub fn ui_testing(&mut self) -> &mut Self { - self.cmd.arg(format!("-Zui-testing")); + self.cmd.arg("-Zui-testing"); self } @@ -405,10 +405,8 @@ impl Rustc { } else if is_aix() { self.cmd.arg("-lc++"); self.cmd.arg("-lc++abi"); - } else { - if !matches!(&uname()[..], "FreeBSD" | "SunOS" | "OpenBSD") { - self.cmd.arg("-lstdc++"); - }; + } else if !matches!(&uname()[..], "FreeBSD" | "SunOS" | "OpenBSD") { + self.cmd.arg("-lstdc++"); }; self } diff --git a/src/tools/run-make-support/src/external_deps/rustdoc.rs b/src/tools/run-make-support/src/external_deps/rustdoc.rs index 33e5f04d3034d..2d66265542f7f 100644 --- a/src/tools/run-make-support/src/external_deps/rustdoc.rs +++ b/src/tools/run-make-support/src/external_deps/rustdoc.rs @@ -30,7 +30,7 @@ pub struct Rustdoc { // Only fill in the target just before execution, so that it can be overridden. crate::macros::impl_common_helpers!(Rustdoc, |rustdoc: &mut Rustdoc| { if let Some(target) = &rustdoc.target { - rustdoc.cmd.arg(&format!("--target={target}")); + rustdoc.cmd.arg(format!("--target={target}")); } }); diff --git a/src/tools/run-make-support/src/fs.rs b/src/tools/run-make-support/src/fs.rs index ceb4ebbaca55a..91f007fecba10 100644 --- a/src/tools/run-make-support/src/fs.rs +++ b/src/tools/run-make-support/src/fs.rs @@ -50,7 +50,7 @@ pub fn copy_dir_all(src: impl AsRef, dst: impl AsRef) { fn copy_dir_all_inner(src: impl AsRef, dst: impl AsRef) -> io::Result<()> { let dst = dst.as_ref(); if !dst.is_dir() { - std::fs::create_dir_all(&dst)?; + std::fs::create_dir_all(dst)?; } for entry in std::fs::read_dir(src)? { let entry = entry?; @@ -118,77 +118,83 @@ pub fn remove_dir>(path: P) { /// A wrapper around [`std::fs::copy`] which includes the file path in the panic message. #[track_caller] pub fn copy, Q: AsRef>(from: P, to: Q) { - std::fs::copy(from.as_ref(), to.as_ref()).expect(&format!( - "the file \"{}\" could not be copied over to \"{}\"", - from.as_ref().display(), - to.as_ref().display(), - )); + std::fs::copy(from.as_ref(), to.as_ref()).unwrap_or_else(|_| { + panic!( + "the file \"{}\" could not be copied over to \"{}\"", + from.as_ref().display(), + to.as_ref().display() + ) + }); } /// A wrapper around [`std::fs::File::create`] which includes the file path in the panic message. #[track_caller] pub fn create_file>(path: P) { - std::fs::File::create(path.as_ref()) - .expect(&format!("the file in path \"{}\" could not be created", path.as_ref().display())); + std::fs::File::create(path.as_ref()).unwrap_or_else(|_| { + panic!("the file in path \"{}\" could not be created", path.as_ref().display()) + }); } /// A wrapper around [`std::fs::read`] which includes the file path in the panic message. #[track_caller] pub fn read>(path: P) -> Vec { - std::fs::read(path.as_ref()) - .expect(&format!("the file in path \"{}\" could not be read", path.as_ref().display())) + std::fs::read(path.as_ref()).unwrap_or_else(|_| { + panic!("the file in path \"{}\" could not be read", path.as_ref().display()) + }) } /// A wrapper around [`std::fs::read_to_string`] which includes the file path in the panic message. #[track_caller] pub fn read_to_string>(path: P) -> String { - std::fs::read_to_string(path.as_ref()).expect(&format!( - "the file in path \"{}\" could not be read into a String", - path.as_ref().display() - )) + std::fs::read_to_string(path.as_ref()).unwrap_or_else(|_| { + panic!("the file in path \"{}\" could not be read into a String", path.as_ref().display()) + }) } /// A wrapper around [`std::fs::read_dir`] which includes the file path in the panic message. #[track_caller] pub fn read_dir>(path: P) -> std::fs::ReadDir { - std::fs::read_dir(path.as_ref()) - .expect(&format!("the directory in path \"{}\" could not be read", path.as_ref().display())) + std::fs::read_dir(path.as_ref()).unwrap_or_else(|_| { + panic!("the directory in path \"{}\" could not be read", path.as_ref().display()) + }) } /// A wrapper around [`std::fs::write`] which includes the file path in the panic message. #[track_caller] pub fn write, C: AsRef<[u8]>>(path: P, contents: C) { - std::fs::write(path.as_ref(), contents.as_ref()).expect(&format!( - "the file in path \"{}\" could not be written to", - path.as_ref().display() - )); + std::fs::write(path.as_ref(), contents.as_ref()).unwrap_or_else(|_| { + panic!("the file in path \"{}\" could not be written to", path.as_ref().display()) + }); } /// A wrapper around [`std::fs::remove_dir_all`] which includes the file path in the panic message. #[track_caller] pub fn remove_dir_all>(path: P) { - std::fs::remove_dir_all(path.as_ref()).expect(&format!( - "the directory in path \"{}\" could not be removed alongside all its contents", - path.as_ref().display(), - )); + std::fs::remove_dir_all(path.as_ref()).unwrap_or_else(|_| { + panic!( + "the directory in path \"{}\" could not be removed alongside all its contents", + path.as_ref().display() + ) + }); } /// A wrapper around [`std::fs::create_dir`] which includes the file path in the panic message. #[track_caller] pub fn create_dir>(path: P) { - std::fs::create_dir(path.as_ref()).expect(&format!( - "the directory in path \"{}\" could not be created", - path.as_ref().display() - )); + std::fs::create_dir(path.as_ref()).unwrap_or_else(|_| { + panic!("the directory in path \"{}\" could not be created", path.as_ref().display()) + }); } /// A wrapper around [`std::fs::create_dir_all`] which includes the file path in the panic message. #[track_caller] pub fn create_dir_all>(path: P) { - std::fs::create_dir_all(path.as_ref()).expect(&format!( - "the directory (and all its parents) in path \"{}\" could not be created", - path.as_ref().display() - )); + std::fs::create_dir_all(path.as_ref()).unwrap_or_else(|_| { + panic!( + "the directory (and all its parents) in path \"{}\" could not be created", + path.as_ref().display() + ) + }); } /// A wrapper around [`std::fs::metadata`] which includes the file path in the panic message. Note @@ -222,20 +228,24 @@ pub fn symlink_metadata>(path: P) -> std::fs::Metadata { /// A wrapper around [`std::fs::rename`] which includes the file path in the panic message. #[track_caller] pub fn rename, Q: AsRef>(from: P, to: Q) { - std::fs::rename(from.as_ref(), to.as_ref()).expect(&format!( - "the file \"{}\" could not be moved over to \"{}\"", - from.as_ref().display(), - to.as_ref().display(), - )); + std::fs::rename(from.as_ref(), to.as_ref()).unwrap_or_else(|_| { + panic!( + "the file \"{}\" could not be moved over to \"{}\"", + from.as_ref().display(), + to.as_ref().display() + ) + }); } /// A wrapper around [`std::fs::set_permissions`] which includes the file path in the panic message. #[track_caller] pub fn set_permissions>(path: P, perm: std::fs::Permissions) { - std::fs::set_permissions(path.as_ref(), perm).expect(&format!( - "the file's permissions in path \"{}\" could not be changed", - path.as_ref().display() - )); + std::fs::set_permissions(path.as_ref(), perm).unwrap_or_else(|_| { + panic!( + "the file’s permissions in path \"{}\" could not be changed", + path.as_ref().display() + ) + }); } /// List directory entries immediately under the given `dir`. diff --git a/src/tools/run-make-support/src/linker.rs b/src/tools/run-make-support/src/linker.rs index b2893ad88fe21..4309a3b6290e3 100644 --- a/src/tools/run-make-support/src/linker.rs +++ b/src/tools/run-make-support/src/linker.rs @@ -30,7 +30,7 @@ fn get_stderr_with_linker_messages(rustc: &mut Rustc) -> String { fn has_lld_version_in_logs(stderr: &str) -> bool { // Strip the `-Wlinker-messages` wrappers prefixing the linker output. - let stderr = Regex::new(r"warning: linker std(out|err):").unwrap().replace_all(&stderr, ""); + let stderr = Regex::new(r"warning: linker std(out|err):").unwrap().replace_all(stderr, ""); let lld_version_re = Regex::new(r"^LLD [0-9]+\.[0-9]+\.[0-9]+").unwrap(); stderr.lines().any(|line| lld_version_re.is_match(line.trim())) } diff --git a/src/tools/run-make-support/src/scoped_run.rs b/src/tools/run-make-support/src/scoped_run.rs index 074a83922c5b9..8ec78ded89f2f 100644 --- a/src/tools/run-make-support/src/scoped_run.rs +++ b/src/tools/run-make-support/src/scoped_run.rs @@ -34,16 +34,16 @@ where ); panic!("`test_while_readonly` on directory detected while on Windows."); } - let metadata = fs::metadata(&path); + let metadata = fs::metadata(path); let original_perms = metadata.permissions(); let mut new_perms = original_perms.clone(); new_perms.set_readonly(true); - fs::set_permissions(&path, new_perms); + fs::set_permissions(path, new_perms); let success = std::panic::catch_unwind(closure); - fs::set_permissions(&path, original_perms); + fs::set_permissions(path, original_perms); success.unwrap(); } diff --git a/src/tools/run-make-support/src/string.rs b/src/tools/run-make-support/src/string.rs index a79004b8ec6b0..bef3d89604033 100644 --- a/src/tools/run-make-support/src/string.rs +++ b/src/tools/run-make-support/src/string.rs @@ -11,7 +11,7 @@ pub fn count_regex_matches_in_files_with_extension(re: ®ex::Regex, ext: &str) let mut count = 0; for file in fetched_files { let content = fs::read_to_string(file); - count += content.lines().filter(|line| re.is_match(&line)).count(); + count += content.lines().filter(|line| re.is_match(line)).count(); } count diff --git a/src/tools/run-make-support/src/targets.rs b/src/tools/run-make-support/src/targets.rs index 6288f5f7c59da..52dbe39e62558 100644 --- a/src/tools/run-make-support/src/targets.rs +++ b/src/tools/run-make-support/src/targets.rs @@ -74,7 +74,7 @@ pub fn apple_os() -> &'static str { #[must_use] pub fn llvm_components_contain(component: &str) -> bool { // `LLVM_COMPONENTS` is a space-separated list of words - env_var("LLVM_COMPONENTS").split_whitespace().find(|s| s == &component).is_some() + env_var("LLVM_COMPONENTS").split_whitespace().any(|s| s == component) } /// Run `uname`. This assumes that `uname` is available on the platform! diff --git a/src/tools/rustdoc-gui-test/src/main.rs b/src/tools/rustdoc-gui-test/src/main.rs index cd10882fc2269..fd28c9bfb7a8a 100644 --- a/src/tools/rustdoc-gui-test/src/main.rs +++ b/src/tools/rustdoc-gui-test/src/main.rs @@ -24,38 +24,36 @@ fn main() -> Result<(), ()> { let config = Arc::new(Config::from_args(env::args().collect())); let src_path = config.rust_src.join("tests/rustdoc-gui/src"); - for entry in src_path.read_dir().expect("read_dir call failed") { - if let Ok(entry) = entry { - let path = entry.path(); + for entry in src_path.read_dir().expect("read_dir call failed").flatten() { + let path = entry.path(); - if !path.is_dir() { - continue; - } - - let mut cargo = Command::new(&config.initial_cargo); - cargo - .arg("doc") - .arg("--target-dir") - .arg(&config.out_dir) - .env("RUSTC_BOOTSTRAP", "1") - .env("RUSTDOC", &config.rustdoc) - .env("RUSTC", &config.rustc) - .current_dir(path); - - if let Some(librs) = find_librs(entry.path()) { - let test_props = RustdocGuiTestProps::from_file(&librs); - - if !test_props.compile_flags.is_empty() { - cargo.env("RUSTDOCFLAGS", test_props.compile_flags.join(" ")); - } + if !path.is_dir() { + continue; + } - cargo.args(&test_props.run_flags); + let mut cargo = Command::new(&config.initial_cargo); + cargo + .arg("doc") + .arg("--target-dir") + .arg(&config.out_dir) + .env("RUSTC_BOOTSTRAP", "1") + .env("RUSTDOC", &config.rustdoc) + .env("RUSTC", &config.rustc) + .current_dir(path); + + if let Some(librs) = find_librs(entry.path()) { + let test_props = RustdocGuiTestProps::from_file(&librs); + + if !test_props.compile_flags.is_empty() { + cargo.env("RUSTDOCFLAGS", test_props.compile_flags.join(" ")); } - if try_run(&mut cargo, config.verbose).is_err() { - eprintln!("failed to document `{}`", entry.path().display()); - panic!("Cannot run rustdoc-gui tests"); - } + cargo.args(&test_props.run_flags); + } + + if try_run(&mut cargo, config.verbose).is_err() { + eprintln!("failed to document `{}`", entry.path().display()); + panic!("Cannot run rustdoc-gui tests"); } } diff --git a/src/tools/rustdoc-themes/main.rs b/src/tools/rustdoc-themes/main.rs index 9f0663bd8ee01..f74fd84d8ad67 100644 --- a/src/tools/rustdoc-themes/main.rs +++ b/src/tools/rustdoc-themes/main.rs @@ -7,8 +7,8 @@ use std::process::{Command, exit}; fn get_themes>(style_path: P) -> Vec { let mut ret = Vec::with_capacity(10); - const BEGIN_THEME_MARKER: &'static str = "/* Begin theme: "; - const END_THEME_MARKER: &'static str = "/* End theme: "; + const BEGIN_THEME_MARKER: &str = "/* Begin theme: "; + const END_THEME_MARKER: &str = "/* End theme: "; let timestamp = std::time::SystemTime::UNIX_EPOCH.elapsed().expect("time is after UNIX epoch").as_millis(); @@ -18,14 +18,15 @@ fn get_themes>(style_path: P) -> Vec { for line in BufReader::new(File::open(style_path).expect("read rustdoc.css failed")).lines() { let line = line.expect("read line from rustdoc.css failed"); let line = line.trim(); - if line.starts_with(BEGIN_THEME_MARKER) { - let theme_name = &line[BEGIN_THEME_MARKER.len()..].trim().trim_end_matches("*/").trim(); + if let Some(line) = line.strip_prefix(BEGIN_THEME_MARKER) { + let theme_name = line.trim().trim_end_matches("*/").trim(); let filename = format!("build/tmp/rustdoc.bootstrap.{timestamp}.{theme_name}.css"); in_theme = Some(BufWriter::new( File::create(&filename).expect("failed to create temporary test css file"), )); ret.push(filename); } + if let Some(in_theme) = in_theme.as_mut() { in_theme.write_all(line.as_bytes()).expect("write to temporary test css file"); in_theme.write_all(b"\n").expect("write to temporary test css file"); @@ -46,14 +47,14 @@ fn main() { } let rustdoc_bin = &argv[1]; let style_path = &argv[2]; - let themes = get_themes(&style_path); + let themes = get_themes(style_path); if themes.is_empty() { eprintln!("No themes found in \"{}\"...", style_path); exit(1); } let arg_name = "--check-theme".to_owned(); let status = Command::new(rustdoc_bin) - .args(&themes.iter().flat_map(|t| vec![&arg_name, t].into_iter()).collect::>()) + .args(themes.iter().flat_map(|t| vec![&arg_name, t].into_iter()).collect::>()) .status() .expect("failed to execute child"); if !status.success() { diff --git a/src/tools/rustfmt/config_proc_macro/src/attrs.rs b/src/tools/rustfmt/config_proc_macro/src/attrs.rs index e7534b813d706..f6daf346bcf2b 100644 --- a/src/tools/rustfmt/config_proc_macro/src/attrs.rs +++ b/src/tools/rustfmt/config_proc_macro/src/attrs.rs @@ -51,17 +51,11 @@ pub fn is_unstable_variant(attr: &syn::Attribute) -> bool { } fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool { - match &attr.meta { - syn::Meta::NameValue(syn::MetaNameValue { path, .. }) if path.is_ident(name) => true, - _ => false, - } + matches!(&attr.meta, syn::Meta::NameValue(syn::MetaNameValue { path, .. }) if path.is_ident(name)) } fn is_attr_path(attr: &syn::Attribute, name: &str) -> bool { - match &attr.meta { - syn::Meta::Path(path) if path.is_ident(name) => true, - _ => false, - } + matches!(&attr.meta, syn::Meta::Path(path) if path.is_ident(name)) } fn get_name_value_str_lit(attr: &syn::Attribute, name: &str) -> Option { diff --git a/src/tools/rustfmt/config_proc_macro/src/item_enum.rs b/src/tools/rustfmt/config_proc_macro/src/item_enum.rs index 731a7ea06077b..069b2b53286ac 100644 --- a/src/tools/rustfmt/config_proc_macro/src/item_enum.rs +++ b/src/tools/rustfmt/config_proc_macro/src/item_enum.rs @@ -75,7 +75,7 @@ fn impl_doc_hint(ident: &syn::Ident, variants: &Variants) -> TokenStream { let variant_stables = variants .iter() - .map(|v| (&v.ident, fields_in_variant(&v), !unstable_of_variant(v))); + .map(|v| (&v.ident, fields_in_variant(v), !unstable_of_variant(v))); let match_patterns = fold_quote(variant_stables, |(v, fields, stable)| { quote! { #ident::#v #fields => #stable, @@ -150,7 +150,7 @@ fn impl_from_str(ident: &syn::Ident, variants: &Variants) -> TokenStream { fn doc_hint_of_variant(variant: &syn::Variant) -> String { let mut text = find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()); - if unstable_of_variant(&variant) { + if unstable_of_variant(variant) { text.push_str(" (unstable)") }; text diff --git a/src/tools/rustfmt/config_proc_macro/src/utils.rs b/src/tools/rustfmt/config_proc_macro/src/utils.rs index 1f5b5cdb604f0..ea23d7b3dbf04 100644 --- a/src/tools/rustfmt/config_proc_macro/src/utils.rs +++ b/src/tools/rustfmt/config_proc_macro/src/utils.rs @@ -13,10 +13,7 @@ where } pub fn is_unit(v: &syn::Variant) -> bool { - match v.fields { - syn::Fields::Unit => true, - _ => false, - } + matches!(v.fields, syn::Fields::Unit) } #[cfg(feature = "debug-with-rustfmt")] diff --git a/src/tools/rustfmt/src/lists.rs b/src/tools/rustfmt/src/lists.rs index 415144a8abc05..ea94d40ea186f 100644 --- a/src/tools/rustfmt/src/lists.rs +++ b/src/tools/rustfmt/src/lists.rs @@ -136,7 +136,7 @@ impl ListItem { ListItem { pre_comment: None, pre_comment_style: ListItemCommentStyle::None, - item: item, + item, post_comment: None, new_lines: false, } diff --git a/src/tools/rustfmt/src/reorder.rs b/src/tools/rustfmt/src/reorder.rs index 2460b61698ccf..8604ee266904a 100644 --- a/src/tools/rustfmt/src/reorder.rs +++ b/src/tools/rustfmt/src/reorder.rs @@ -137,10 +137,7 @@ fn rewrite_reorderable_or_regroupable_items( .map(|use_tree| { let item = use_tree.rewrite_top_level(context, nested_shape); if let Some(list_item) = use_tree.list_item { - ListItem { - item: item, - ..list_item - } + ListItem { item, ..list_item } } else { ListItem::from_item(item) } diff --git a/src/tools/rustfmt/src/rewrite.rs b/src/tools/rustfmt/src/rewrite.rs index f0accd62d1a93..1118264343ea7 100644 --- a/src/tools/rustfmt/src/rewrite.rs +++ b/src/tools/rustfmt/src/rewrite.rs @@ -73,15 +73,12 @@ impl RewriteErrorExt for Option { fn max_width_error(self, width: usize, span: Span) -> Result { self.ok_or_else(|| RewriteError::ExceedsMaxWidth { configured_width: width, - span: span, + span, }) } fn macro_error(self, kind: MacroErrorKind, span: Span) -> Result { - self.ok_or_else(|| RewriteError::MacroFailure { - kind: kind, - span: span, - }) + self.ok_or_else(|| RewriteError::MacroFailure { kind, span }) } fn unknown_error(self) -> Result { diff --git a/src/tools/rustfmt/src/sort.rs b/src/tools/rustfmt/src/sort.rs index 670f664a11949..b4baf73c0d7c5 100644 --- a/src/tools/rustfmt/src/sort.rs +++ b/src/tools/rustfmt/src/sort.rs @@ -152,10 +152,8 @@ pub(crate) fn version_sort(a: &str, b: &str) -> std::cmp::Ordering { | (VersionChunk::Str(ca), VersionChunk::Number { source: cb, .. }) | (VersionChunk::Number { source: ca, .. }, VersionChunk::Str(cb)) => { match ca.cmp(&cb) { - std::cmp::Ordering::Equal => { - continue; - } - order @ _ => return order, + std::cmp::Ordering::Equal => continue, + order => return order, } } ( @@ -182,7 +180,7 @@ pub(crate) fn version_sort(a: &str, b: &str) -> std::cmp::Ordering { } continue; } - order @ _ => return order, + order => return order, }, }, } diff --git a/src/tools/rustfmt/src/types.rs b/src/tools/rustfmt/src/types.rs index 5dce9a0c8d0f2..e1a8ef7e347cc 100644 --- a/src/tools/rustfmt/src/types.rs +++ b/src/tools/rustfmt/src/types.rs @@ -1321,7 +1321,7 @@ fn join_bounds_inner( // or the single item is of type `Trait`, // and any of the internal arrays contains more than one item; let retry_with_force_newline = match context.config.style_edition() { - style_edition @ _ if style_edition <= StyleEdition::Edition2021 => { + style_edition if style_edition <= StyleEdition::Edition2021 => { !force_newline && items.len() > 1 && (result.0.contains('\n') || result.0.len() > shape.width) diff --git a/src/tools/test-float-parse/src/gen_/many_digits.rs b/src/tools/test-float-parse/src/gen_/many_digits.rs index 741e11437fe29..38353d0f6d14f 100644 --- a/src/tools/test-float-parse/src/gen_/many_digits.rs +++ b/src/tools/test-float-parse/src/gen_/many_digits.rs @@ -67,10 +67,10 @@ impl Iterator for RandDigits { let digit = char::from_digit(self.uniform.sample(&mut self.rng), 10).unwrap(); s.push(digit); - if let Some(dec_pos) = dec_pos { - if pos == dec_pos { - s.push('.'); - } + if let Some(dec_pos) = dec_pos + && pos == dec_pos + { + s.push('.'); } } diff --git a/src/tools/test-float-parse/src/lib.rs b/src/tools/test-float-parse/src/lib.rs index 1321a3c335499..c72a38afa162a 100644 --- a/src/tools/test-float-parse/src/lib.rs +++ b/src/tools/test-float-parse/src/lib.rs @@ -381,7 +381,7 @@ fn test_runner>(test: &TestInfo, cfg: &Config) { }; // Send periodic updates - if executed % checks_per_update == 0 { + if executed.is_multiple_of(checks_per_update) { let failures = failures.load(Ordering::Relaxed); test.progress.as_ref().unwrap().update(executed, failures); if started.elapsed() > cfg.timeout { diff --git a/src/tools/test-float-parse/src/ui.rs b/src/tools/test-float-parse/src/ui.rs index 1a9ba0dc1d99c..d7806accd042d 100644 --- a/src/tools/test-float-parse/src/ui.rs +++ b/src/tools/test-float-parse/src/ui.rs @@ -48,7 +48,7 @@ impl Progress { /// Completed a out of b tests. pub fn update(&self, completed: u64, failures: u64) { // Infrequently update the progress bar. - if completed % 5_000 == 0 || failures > 0 { + if completed.is_multiple_of(5_000) || failures > 0 { self.pb.set_position(completed); } diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 3f40bef821c9d..a774a3cb7ae76 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -692,7 +692,7 @@ pub fn check(root: &Path, cargo: &Path, bless: bool, diag_ctx: DiagCtx) { check_license_exceptions(&metadata, path, exceptions, &mut check); if let Some((crates, permitted_deps, location)) = crates_and_deps { - let descr = crates.get(0).unwrap_or(&path); + let descr = crates.first().unwrap_or(&path); check_permitted_dependencies( &metadata, descr, diff --git a/src/tools/tidy/src/diagnostics.rs b/src/tools/tidy/src/diagnostics.rs index 6e95f97d0104f..6160ca3bc03a5 100644 --- a/src/tools/tidy/src/diagnostics.rs +++ b/src/tools/tidy/src/diagnostics.rs @@ -29,10 +29,8 @@ impl DiagCtx { let mut ctx = self.0.lock().unwrap(); // Shorten path for shorter diagnostics - id.path = match id.path { - Some(path) => Some(path.strip_prefix(&ctx.root_path).unwrap_or(&path).to_path_buf()), - None => None, - }; + id.path = + id.path.map(|path| path.strip_prefix(&ctx.root_path).unwrap_or(&path).to_path_buf()); ctx.start_check(id.clone()); RunningCheck { diff --git a/src/tools/tidy/src/error_codes.rs b/src/tools/tidy/src/error_codes.rs index 83fbefa43d975..6a2f9dd926256 100644 --- a/src/tools/tidy/src/error_codes.rs +++ b/src/tools/tidy/src/error_codes.rs @@ -63,16 +63,16 @@ fn check_removed_error_code_explanation(ci_info: &crate::CiInfo, check: &mut Run return; }; let Some(diff) = crate::git_diff(base_commit, "--name-status") else { - check.error(format!("removed error code explanation: Failed to run git diff")); + check.error("removed error code explanation: Failed to run git diff"); return; }; if diff.lines().any(|line| { line.starts_with('D') && line.contains("compiler/rustc_error_codes/src/error_codes/") }) { - check.error(format!( + check.error( r#"Error code explanations should never be removed! -Take a look at E0001 to see how to handle it."# - )); +Take a look at E0001 to see how to handle it."#, + ); return; } check.verbose_msg("No error code explanation was removed!"); diff --git a/src/tools/tidy/src/extra_checks/mod.rs b/src/tools/tidy/src/extra_checks/mod.rs index 9f2f2da2e86d7..9b8d5911d084d 100644 --- a/src/tools/tidy/src/extra_checks/mod.rs +++ b/src/tools/tidy/src/extra_checks/mod.rs @@ -316,7 +316,7 @@ fn check_impl( } else { eprintln!("spellchecking files"); } - let res = spellcheck_runner(root_path, &outdir, &cargo, &args); + let res = spellcheck_runner(root_path, outdir, cargo, &args); if res.is_err() { rerun_with_bless("spellcheck", "fix typos"); } diff --git a/src/tools/tidy/src/extra_checks/rustdoc_js.rs b/src/tools/tidy/src/extra_checks/rustdoc_js.rs index 5137e61836728..f97bea3f39451 100644 --- a/src/tools/tidy/src/extra_checks/rustdoc_js.rs +++ b/src/tools/tidy/src/extra_checks/rustdoc_js.rs @@ -37,7 +37,7 @@ fn rustdoc_js_files(librustdoc_path: &Path) -> Vec { files.push(path.path().into()); }, ); - return files; + files } fn run_eslint( diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 0acbcd64f067c..8790ef9c6da20 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -182,7 +182,7 @@ pub fn ensure_version_or_cargo_install( let Ok(s) = str::from_utf8(&output.stdout) else { break 'ck; }; - let Some(v) = s.trim().split_whitespace().last() else { + let Some(v) = s.split_whitespace().last() else { break 'ck; }; if v == version { diff --git a/src/tools/tidy/src/tests_revision_unpaired_stdout_stderr.rs b/src/tools/tidy/src/tests_revision_unpaired_stdout_stderr.rs index 1738088a3a0c0..3a140b976abe8 100644 --- a/src/tools/tidy/src/tests_revision_unpaired_stdout_stderr.rs +++ b/src/tools/tidy/src/tests_revision_unpaired_stdout_stderr.rs @@ -27,7 +27,7 @@ pub fn check(tests_path: &Path, diag_ctx: DiagCtx) { .start_check(CheckId::new("tests_revision_unpaired_stdout_stderr").path(tests_path)); // Recurse over subdirectories under `tests/` - walk_dir(tests_path.as_ref(), filter, &mut |entry| { + walk_dir(tests_path, filter, &mut |entry| { // We are inspecting a folder. Collect the paths to interesting files `.rs`, `.stderr`, // `.stdout` under the current folder (shallow). let mut files_under_inspection = BTreeSet::new(); @@ -134,10 +134,9 @@ pub fn check(tests_path: &Path, diag_ctx: DiagCtx) { } [_, _] => return, [_, found_revision, .., extension] => { - if !IGNORES.contains(found_revision) - && !expected_revisions.contains(*found_revision) - // This is from `//@ stderr-per-bitwidth` - && !(*extension == "stderr" && ["32bit", "64bit"].contains(found_revision)) + if !(IGNORES.contains(found_revision) + || expected_revisions.contains(*found_revision) + || *extension == "stderr" && ["32bit", "64bit"].contains(found_revision)) { // Found some unexpected revision-esque component that is not a known // compare-mode or expected revision. diff --git a/src/tools/tidy/src/unit_tests.rs b/src/tools/tidy/src/unit_tests.rs index cab445ac63a1b..c5c4063801baa 100644 --- a/src/tools/tidy/src/unit_tests.rs +++ b/src/tools/tidy/src/unit_tests.rs @@ -43,10 +43,8 @@ pub fn check(root_path: &Path, stdlib: bool, diag_ctx: DiagCtx) { if file_name == "tests" || file_name == "benches" { return true; } - } else { - if file_name == "tests.rs" || file_name == "benches.rs" { - return true; - } + } else if file_name == "tests.rs" || file_name == "benches.rs" { + return true; } } diff --git a/src/tools/unstable-book-gen/src/main.rs b/src/tools/unstable-book-gen/src/main.rs index 16550f83003dc..a1c1fb8a8c458 100644 --- a/src/tools/unstable-book-gen/src/main.rs +++ b/src/tools/unstable-book-gen/src/main.rs @@ -48,8 +48,8 @@ fn generate_summary(path: &Path, lang_features: &Features, lib_features: &Featur let compiler_env_vars_str = set_to_summary_str(&compiler_env_vars, "compiler-environment-variables"); - let unstable_lang_features = collect_unstable_feature_names(&lang_features); - let unstable_lib_features = collect_unstable_feature_names(&lib_features); + let unstable_lang_features = collect_unstable_feature_names(lang_features); + let unstable_lib_features = collect_unstable_feature_names(lib_features); let lang_features_str = set_to_summary_str(&unstable_lang_features, "language-features"); let lib_features_str = set_to_summary_str(&unstable_lib_features, "library-features"); @@ -68,7 +68,7 @@ fn generate_summary(path: &Path, lang_features: &Features, lib_features: &Featur fn generate_feature_files(src: &Path, out: &Path, features: &Features) { let unstable_features = collect_unstable_feature_names(features); let unstable_section_file_names = collect_unstable_book_section_file_names(src); - t!(fs::create_dir_all(&out)); + t!(fs::create_dir_all(out)); for feature_name in &unstable_features - &unstable_section_file_names { let feature_name_underscore = feature_name.replace('-', "_"); let file_name = format!("{feature_name}.md"); @@ -77,21 +77,16 @@ fn generate_feature_files(src: &Path, out: &Path, features: &Features) { let description = feature.description.as_deref().unwrap_or_default(); if let Some(issue) = feature.tracking_issue { - generate_stub_issue( - &out_file_path, - &feature_name_underscore, - issue.get(), - &description, - ); + generate_stub_issue(&out_file_path, &feature_name_underscore, issue.get(), description); } else { - generate_stub_no_issue(&out_file_path, &feature_name_underscore, &description); + generate_stub_no_issue(&out_file_path, &feature_name_underscore, description); } } } fn generate_env_files(src: &Path, out: &Path, env_vars: &BTreeSet) { let env_var_file_names = collect_unstable_book_section_file_names(src); - t!(fs::create_dir_all(&out)); + t!(fs::create_dir_all(out)); for env_var in env_vars - &env_var_file_names { let file_name = format!("{env_var}.md"); let out_file_path = out.join(&file_name); @@ -105,7 +100,7 @@ fn copy_recursive(from: &Path, to: &Path) { let t = t!(e.metadata()); let dest = &to.join(e.file_name()); if t.is_file() { - t!(fs::copy(&e.path(), dest)); + t!(fs::copy(e.path(), dest)); } else if t.is_dir() { t!(fs::create_dir_all(dest)); copy_recursive(&e.path(), dest); @@ -126,13 +121,13 @@ fn main() { let lang_features = collect_lang_features(compiler_path, &mut RunningCheck::new_noop()); let lib_features = collect_lib_features(library_path) .into_iter() - .filter(|&(ref name, _)| !lang_features.contains_key(name)) + .filter(|(name, _)| !lang_features.contains_key(name)) .collect(); let env_vars = collect_env_vars(compiler_path); let doc_src_path = src_path.join(PATH_STR); - t!(fs::create_dir_all(&dest_path)); + t!(fs::create_dir_all(dest_path)); generate_feature_files( &doc_src_path.join(LANG_FEATURES_DIR), @@ -146,7 +141,7 @@ fn main() { ); generate_env_files(&doc_src_path.join(ENV_VARS_DIR), &dest_path.join(ENV_VARS_DIR), &env_vars); - copy_recursive(&doc_src_path, &dest_path); + copy_recursive(&doc_src_path, dest_path); - generate_summary(&dest_path, &lang_features, &lib_features); + generate_summary(dest_path, &lang_features, &lib_features); }