diff --git a/crates/rustc_utils/src/cache.rs b/crates/rustc_utils/src/cache.rs index f8a8d8bf..47d9918f 100644 --- a/crates/rustc_utils/src/cache.rs +++ b/crates/rustc_utils/src/cache.rs @@ -79,7 +79,7 @@ where /// # Panics /// /// If this is a recursive invocation for this key. - pub fn get(&self, key: In, compute: impl FnOnce(In) -> Out) -> &Out { + pub fn get(&self, key: &In, compute: impl FnOnce(In) -> Out) -> &Out { self .get_maybe_recursive(key, compute) .unwrap_or_else(recursion_panic) @@ -90,10 +90,10 @@ where /// Returns `None` if this is a recursive invocation of `get` for key `key`. pub fn get_maybe_recursive<'a>( &'a self, - key: In, + key: &In, compute: impl FnOnce(In) -> Out, ) -> Option<&'a Out> { - if !self.0.borrow().contains_key(&key) { + if !self.0.borrow().contains_key(key) { self.0.borrow_mut().insert(key.clone(), None); let out = Box::pin(compute(key.clone())); self.0.borrow_mut().insert(key.clone(), Some(out)); @@ -102,7 +102,7 @@ where let cache = self.0.borrow(); // Important here to first `unwrap` the `Option` created by `get`, then // propagate the potential option stored in the map. - let entry = cache.get(&key).expect("invariant broken").as_ref()?; + let entry = cache.get(key).expect("invariant broken").as_ref()?; // SAFETY: because the entry is pinned, it cannot move and this pointer will // only be invalidated if Cache is dropped. The returned reference has a lifetime @@ -139,7 +139,7 @@ where /// # Panics /// /// If this is a recursive invocation for this key. - pub fn get(&self, key: In, compute: impl FnOnce(In) -> Out) -> Out { + pub fn get(&self, key: &In, compute: impl FnOnce(In) -> Out) -> Out { self .get_maybe_recursive(key, compute) .unwrap_or_else(recursion_panic) @@ -151,16 +151,16 @@ where /// Returns `None` if this is a recursive invocation of `get` for key `key`. pub fn get_maybe_recursive( &self, - key: In, + key: &In, compute: impl FnOnce(In) -> Out, ) -> Option { - if !self.0.borrow().contains_key(&key) { + if !self.0.borrow().contains_key(key) { self.0.borrow_mut().insert(key.clone(), None); let out = compute(key.clone()); self.0.borrow_mut().insert(key.clone(), Some(out)); } - *self.0.borrow_mut().get(&key).expect("invariant broken") + *self.0.borrow_mut().get(key).expect("invariant broken") } } @@ -177,9 +177,9 @@ mod test { #[test] fn test_cached() { let cache: Cache = Cache::default(); - let x = cache.get(0, |_| 0); - let y = cache.get(1, |_| 1); - let z = cache.get(0, |_| 2); + let x = cache.get(&0, |_| 0); + let y = cache.get(&1, |_| 1); + let z = cache.get(&0, |_| 2); assert_eq!(*x, 0); assert_eq!(*y, 1); assert_eq!(*z, 0); @@ -193,12 +193,12 @@ mod test { fn get_infinite_recursion(&self, i: i32) -> i32 { self .0 - .get_maybe_recursive(i, |_| i + self.get_infinite_recursion(i)) + .get_maybe_recursive(&i, |_| i + self.get_infinite_recursion(i)) .copied() .unwrap_or(-18) } fn get_safe_recursion(&self, i: i32) -> i32 { - *self.0.get(i, |_| { + *self.0.get(&i, |_| { if i == 0 { 0 } else { diff --git a/crates/rustc_utils/src/hir/ty.rs b/crates/rustc_utils/src/hir/ty.rs index 22bb4515..b778f948 100644 --- a/crates/rustc_utils/src/hir/ty.rs +++ b/crates/rustc_utils/src/hir/ty.rs @@ -1,6 +1,5 @@ //! Utilities for [`Ty`]. -use rustc_data_structures::captures::Captures; use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::ty::{GenericArgKind, ParamEnv, Region, Ty, TyCtxt, TypingEnv}; @@ -9,32 +8,24 @@ use rustc_type_ir::TypingMode; /// Extension trait for [`Ty`]. pub trait TyExt<'tcx> { - type AllRegionsIter<'a>: Iterator> - where - Self: 'a; - /// Returns an iterator over the regions appearing within a type. - fn inner_regions(&self) -> Self::AllRegionsIter<'_>; + fn inner_regions(self) -> impl Iterator>; /// Returns true if a type implements a given trait. fn does_implement_trait( - &self, + self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, trait_def_id: DefId, ) -> bool; + #[allow(clippy::wrong_self_convention)] /// Returns true if a type implements `Copy`. - fn is_copyable(&self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool; + fn is_copyable(self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool; } impl<'tcx> TyExt<'tcx> for Ty<'tcx> { - type AllRegionsIter<'a> - = impl Iterator> + Captures<'tcx> + 'a - where - Self: 'a; - - fn inner_regions(&self) -> Self::AllRegionsIter<'_> { + fn inner_regions(self) -> impl Iterator> { self.walk().filter_map(|part| match part.unpack() { GenericArgKind::Lifetime(region) => Some(region), _ => None, @@ -42,7 +33,7 @@ impl<'tcx> TyExt<'tcx> for Ty<'tcx> { } fn does_implement_trait( - &self, + self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, trait_def_id: DefId, @@ -50,7 +41,7 @@ impl<'tcx> TyExt<'tcx> for Ty<'tcx> { use rustc_infer::traits::EvaluationResult; let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis()); - let ty = tcx.erase_regions(*self); + let ty = tcx.erase_regions(self); let result = infcx.type_implements_trait(trait_def_id, [ty], param_env); matches!( result, @@ -58,8 +49,8 @@ impl<'tcx> TyExt<'tcx> for Ty<'tcx> { ) } - fn is_copyable(&self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool { - let ty = tcx.erase_regions(*self); + fn is_copyable(self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool { + let ty = tcx.erase_regions(self); ty.is_copy_modulo_regions(tcx, typing_env) } } diff --git a/crates/rustc_utils/src/lib.rs b/crates/rustc_utils/src/lib.rs index f89961d5..c97b50d6 100644 --- a/crates/rustc_utils/src/lib.rs +++ b/crates/rustc_utils/src/lib.rs @@ -21,7 +21,24 @@ impl_trait_in_assoc_type, doc_auto_cfg, // for feature gates in documentation )] -#![allow(clippy::len_zero, clippy::len_without_is_empty)] +#![warn(clippy::pedantic)] +#![allow( + clippy::len_zero, + clippy::len_without_is_empty, + clippy::must_use_candidate, + clippy::return_self_not_must_use, + clippy::missing_panics_doc, + clippy::missing_errors_doc, + clippy::doc_markdown, + clippy::single_match_else, + clippy::if_not_else, + clippy::match_on_vec_items, + clippy::map_unwrap_or, + clippy::match_wildcard_for_single_variants, + clippy::items_after_statements, + clippy::implicit_hasher, + clippy::wildcard_imports +)] extern crate either; extern crate rustc_borrowck; @@ -62,7 +79,7 @@ pub use crate::{ source_map::span::{SpanDataExt, SpanExt}, }; -/// Utility for hashset literals. Same as maplit::hashset but works with FxHasher. +/// Utility for hashset literals. Same as [`maplit::hashset`] but works with [`FxHasher`]. #[macro_export] macro_rules! hashset { (@single $($x:tt)*) => (()); diff --git a/crates/rustc_utils/src/mir/adt_def.rs b/crates/rustc_utils/src/mir/adt_def.rs index 8f83907a..93ecc74b 100644 --- a/crates/rustc_utils/src/mir/adt_def.rs +++ b/crates/rustc_utils/src/mir/adt_def.rs @@ -5,24 +5,21 @@ use rustc_middle::ty::{AdtDef, FieldDef, TyCtxt}; /// Extension trait for [`AdtDef`]. pub trait AdtDefExt<'tcx> { - type AllVisibleFieldsIter: Iterator; - /// Returns an iterator over all the fields of the ADT that are visible /// from `module`. fn all_visible_fields( self, module: DefId, tcx: TyCtxt<'tcx>, - ) -> Self::AllVisibleFieldsIter; + ) -> impl Iterator; } impl<'tcx> AdtDefExt<'tcx> for AdtDef<'tcx> { - type AllVisibleFieldsIter = impl Iterator; fn all_visible_fields( self, module: DefId, tcx: TyCtxt<'tcx>, - ) -> Self::AllVisibleFieldsIter { + ) -> impl Iterator { self .all_fields() .filter(move |field| field.vis.is_accessible_from(module, tcx)) diff --git a/crates/rustc_utils/src/mir/body.rs b/crates/rustc_utils/src/mir/body.rs index 8e1326f1..75d0eb3c 100644 --- a/crates/rustc_utils/src/mir/body.rs +++ b/crates/rustc_utils/src/mir/body.rs @@ -8,10 +8,13 @@ use std::{ use anyhow::{ensure, Result}; use pretty::PrettyPrintMirOptions; -use rustc_data_structures::{captures::Captures, fx::FxHashMap as HashMap}; +use rustc_data_structures::fx::FxHashMap as HashMap; use rustc_hir::{def_id::DefId, CoroutineDesugaring, CoroutineKind, HirId}; use rustc_middle::{ - mir::{pretty::write_mir_fn, *}, + mir::{ + pretty, pretty::write_mir_fn, BasicBlock, Body, Local, Location, Place, SourceInfo, + TerminatorKind, VarDebugInfoContents, + }, ty::{Region, Ty, TyCtxt}, }; use smallvec::SmallVec; @@ -21,24 +24,14 @@ use crate::{PlaceExt, TyExt}; /// Extension trait for [`Body`]. pub trait BodyExt<'tcx> { - type AllReturnsIter<'a>: Iterator - where - Self: 'a; - /// Returns an iterator over the locations of [`TerminatorKind::Return`] instructions in a body. - fn all_returns(&self) -> Self::AllReturnsIter<'_>; - - type AllLocationsIter<'a>: Iterator - where - Self: 'a; + fn all_returns(&self) -> impl Iterator + '_; /// Returns an iterator over all the locations in a body. - fn all_locations(&self) -> Self::AllLocationsIter<'_>; - - type LocationsIter: Iterator; + fn all_locations(&self) -> impl Iterator + '_; /// Returns all the locations in a [`BasicBlock`]. - fn locations_in_block(&self, block: BasicBlock) -> Self::LocationsIter; + fn locations_in_block(&self, block: BasicBlock) -> impl Iterator; /// Returns a mapping from source-level variable names to [`Local`]s. fn debug_info_name_map(&self) -> HashMap; @@ -64,32 +57,22 @@ pub trait BodyExt<'tcx> { /// locals across await calls. fn async_context(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Option>; - type PlacesIter<'a>: Iterator> - where - Self: 'a; - /// Returns an iterator over all projections of all local variables in the body. - fn all_places(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Self::PlacesIter<'_>; - - type ArgRegionsIter<'a>: Iterator> - where - Self: 'a; + fn all_places( + &self, + tcx: TyCtxt<'tcx>, + def_id: DefId, + ) -> impl Iterator> + '_; /// Returns an iterator over all the regions that appear in argument types to the body. - fn regions_in_args(&self) -> Self::ArgRegionsIter<'_>; - - type ReturnRegionsIter: Iterator>; + fn regions_in_args(&self) -> impl Iterator> + '_; /// Returns an iterator over all the regions that appear in the body's return type. - fn regions_in_return(&self) -> Self::ReturnRegionsIter; + fn regions_in_return(&self) -> impl Iterator> + '_; } impl<'tcx> BodyExt<'tcx> for Body<'tcx> { - type AllReturnsIter<'a> - = impl Iterator + Captures<'tcx> + 'a - where - Self: 'a; - fn all_returns(&self) -> Self::AllReturnsIter<'_> { + fn all_returns(&self) -> impl Iterator + '_ { self .basic_blocks .iter_enumerated() @@ -102,24 +85,19 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> { }) } - type AllLocationsIter<'a> - = impl Iterator + Captures<'tcx> + 'a - where - Self: 'a; - fn all_locations(&self) -> Self::AllLocationsIter<'_> { + fn all_locations(&self) -> impl Iterator + '_ { self .basic_blocks .iter_enumerated() .flat_map(|(block, data)| { - (0 .. data.statements.len() + 1).map(move |statement_index| Location { + (0 ..= data.statements.len()).map(move |statement_index| Location { block, statement_index, }) }) } - type LocationsIter = impl Iterator; - fn locations_in_block(&self, block: BasicBlock) -> Self::LocationsIter { + fn locations_in_block(&self, block: BasicBlock) -> impl Iterator { let num_stmts = self.basic_blocks[block].statements.len(); (0 ..= num_stmts).map(move |statement_index| Location { block, @@ -181,25 +159,13 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> { } } - type ArgRegionsIter<'a> - = impl Iterator> + Captures<'tcx> + 'a - where - Self: 'a; - - type ReturnRegionsIter = impl Iterator>; - - type PlacesIter<'a> - = impl Iterator> + Captures<'tcx> + 'a - where - Self: 'a; - - fn regions_in_args(&self) -> Self::ArgRegionsIter<'_> { + fn regions_in_args(&self) -> impl Iterator> + '_ { self .args_iter() .flat_map(|arg_local| self.local_decls[arg_local].ty.inner_regions()) } - fn regions_in_return(&self) -> Self::ReturnRegionsIter { + fn regions_in_return(&self) -> impl Iterator> + '_ { self .return_ty() .inner_regions() @@ -207,20 +173,24 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> { .into_iter() } - fn all_places(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Self::PlacesIter<'_> { + fn all_places( + &self, + tcx: TyCtxt<'tcx>, + def_id: DefId, + ) -> impl Iterator> + '_ { self.local_decls.indices().flat_map(move |local| { Place::from_local(local, tcx).interior_paths(tcx, self, def_id) }) } } -pub fn run_dot(path: &Path, buf: Vec) -> Result<()> { +pub fn run_dot(path: &Path, buf: &[u8]) -> Result<()> { let mut p = Command::new("dot") .args(["-Tpdf", "-o", &path.display().to_string()]) .stdin(Stdio::piped()) .spawn()?; - p.stdin.as_mut().unwrap().write_all(&buf)?; + p.stdin.as_mut().unwrap().write_all(buf)?; let status = p.wait()?; ensure!(status.success(), "dot for {} failed", path.display()); diff --git a/crates/rustc_utils/src/mir/borrowck_facts.rs b/crates/rustc_utils/src/mir/borrowck_facts.rs index 8a7a7cb4..bc1517af 100644 --- a/crates/rustc_utils/src/mir/borrowck_facts.rs +++ b/crates/rustc_utils/src/mir/borrowck_facts.rs @@ -39,9 +39,6 @@ pub fn simplify_mir(body: &mut Body<'_>) { TerminatorKind::FalseEdge { real_target, .. } => TerminatorKind::Goto { target: real_target, }, - TerminatorKind::FalseUnwind { real_target, .. } => TerminatorKind::Goto { - target: real_target, - }, // Ensures that control dependencies can determine the independence of differnet // return paths TerminatorKind::Goto { target } if return_blocks.contains(&target) => { @@ -90,7 +87,7 @@ fn mir_borrowck(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &BorrowCheckResult<'_> { let body_with_facts: BodyWithBorrowckFacts<'static> = unsafe { std::mem::transmute(body_with_facts) }; MIR_BODIES.with(|cache| { - cache.get(def_id, |_| body_with_facts); + cache.get(&def_id, |_| body_with_facts); }); let mut providers = Providers::default(); @@ -117,7 +114,7 @@ pub fn get_body_with_borrowck_facts<'tcx>( ) -> &'tcx BodyWithBorrowckFacts<'tcx> { let _ = tcx.mir_borrowck(def_id); MIR_BODIES.with(|cache| { - let body = cache.get(def_id, |_| panic!("mir_borrowck override should have stored body for item: {def_id:?}. Are you sure you registered borrowck_facts::override_queries?")); + let body = cache.get(&def_id, |_| panic!("mir_borrowck override should have stored body for item: {def_id:?}. Are you sure you registered borrowck_facts::override_queries?")); unsafe { std::mem::transmute::< &BodyWithBorrowckFacts<'static>, diff --git a/crates/rustc_utils/src/mir/control_dependencies.rs b/crates/rustc_utils/src/mir/control_dependencies.rs index e7e0aaa4..b154a4bf 100644 --- a/crates/rustc_utils/src/mir/control_dependencies.rs +++ b/crates/rustc_utils/src/mir/control_dependencies.rs @@ -8,7 +8,10 @@ use std::fmt; -use rustc_data_structures::graph::{dominators::Dominators, vec_graph::VecGraph, *}; +use rustc_data_structures::graph::{ + dominators, dominators::Dominators, iterate, vec_graph::VecGraph, ControlFlowGraph, + DirectedGraph, Predecessors, StartNode, Successors, +}; use rustc_index::{ bit_set::{BitSet, ChunkedBitSet, SparseBitMatrix}, Idx, diff --git a/crates/rustc_utils/src/mir/place.rs b/crates/rustc_utils/src/mir/place.rs index 513020c7..e48b631b 100644 --- a/crates/rustc_utils/src/mir/place.rs +++ b/crates/rustc_utils/src/mir/place.rs @@ -58,19 +58,13 @@ pub trait PlaceExt<'tcx> { /// - all dereferences in `self` are dereferences of a `Box` fn is_direct(&self, body: &Body<'tcx>, tcx: TyCtxt<'tcx>) -> bool; - type RefsInProjectionIter<'a>: Iterator< - Item = (PlaceRef<'tcx>, &'tcx [PlaceElem<'tcx>]), - > - where - Self: 'a; - /// Returns an iterator over all prefixes of `self`'s projection that are references, /// along with the suffix of the remaining projection. fn refs_in_projection( - &self, + self, body: &Body<'tcx>, tcx: TyCtxt<'tcx>, - ) -> Self::RefsInProjectionIter<'_>; + ) -> impl Iterator, &'tcx [PlaceElem<'tcx>])>; /// Returns all possible projections of `self` that are references. /// @@ -142,35 +136,22 @@ impl<'tcx> PlaceExt<'tcx> for Place<'tcx> { || self.refs_in_projection(body, tcx).next().is_none() } - type RefsInProjectionIter<'a> - = impl Iterator, &'tcx [PlaceElem<'tcx>])> + 'a - where - Self: 'a; fn refs_in_projection( - &self, + self, body: &Body<'tcx>, tcx: TyCtxt<'tcx>, - ) -> Self::RefsInProjectionIter<'_> { + ) -> impl Iterator, &'tcx [PlaceElem<'tcx>])> { self - .projection - .iter() + .iter_projections() .enumerate() - .scan( - Place::from(self.local).ty(body, tcx), - move |ty, (i, elem)| { - let old_ty = *ty; - *ty = ty.projection_ty(tcx, elem); - Some((i, elem, old_ty)) - }, - ) - .filter_map(|(i, elem, ty)| match elem { + .filter_map(move |(i, (place_ref, elem))| match elem { ProjectionElem::Deref => { let ptr = PlaceRef { local: self.local, projection: &self.projection[.. i], }; let after = &self.projection[i + 1 ..]; - (!ty.ty.is_box()).then_some((ptr, after)) + (!place_ref.ty(body.local_decls(), tcx).ty.is_box()).then_some((ptr, after)) } _ => None, }) diff --git a/crates/rustc_utils/src/source_map/range.rs b/crates/rustc_utils/src/source_map/range.rs index 9ff96d2b..dd3695e1 100644 --- a/crates/rustc_utils/src/source_map/range.rs +++ b/crates/rustc_utils/src/source_map/range.rs @@ -134,7 +134,7 @@ impl FilenameIndex { let filename = &ctx.filenames[self]; let filename = filename.0 .canonicalize() - .unwrap_or_else(|_| filename.0.to_path_buf()); + .unwrap_or_else(|_| filename.0.clone()); let rustc_filename = files .iter() .map(|file| &file.name) @@ -226,7 +226,7 @@ impl ByteRange { let ctx = ctx.borrow(); let mapping: &CharByteMapping = ctx .char_byte_mapping - .get(self.filename, |_| CharByteMapping::build(&file)); + .get(&self.filename, |_| CharByteMapping::build(&file)); let char_start = mapping.byte_to_char(self.start); let char_end = mapping.byte_to_char(self.end); @@ -251,7 +251,7 @@ impl ByteRange { let ctx = ctx.borrow(); let mapping = ctx .char_byte_mapping - .get(filename, |_| CharByteMapping::build(&file)); + .get(&filename, |_| CharByteMapping::build(&file)); let byte_start = mapping.char_to_byte(char_start); let byte_end = mapping.char_to_byte(char_end); Ok(ByteRange { @@ -284,7 +284,7 @@ impl ByteRange { let _src = file .src .as_deref() - .map(|s| s.as_str()) + .map(String::as_str) .unwrap_or_else(|| external.get_source().as_ref().unwrap()); let byte_start = BytePos(span.lo().0 as usize); @@ -318,8 +318,8 @@ pub trait ToSpan { impl ToSpan for ByteRange { fn to_span(&self, _tcx: TyCtxt) -> Result { Ok(Span::with_root_ctxt( - rustc_span::BytePos(self.start.0 as u32), - rustc_span::BytePos(self.end.0 as u32), + rustc_span::BytePos(u32::try_from(self.start.0).unwrap()), + rustc_span::BytePos(u32::try_from(self.end.0).unwrap()), )) } } diff --git a/crates/rustc_utils/src/source_map/span.rs b/crates/rustc_utils/src/source_map/span.rs index ebf6845a..b2fe0cf6 100644 --- a/crates/rustc_utils/src/source_map/span.rs +++ b/crates/rustc_utils/src/source_map/span.rs @@ -87,11 +87,11 @@ impl SpanExt for Span { // of that span is the entire macro. if outer_span.contains(*self) { return Some(*self); - } else { - let sp = self.source_callsite(); - if outer_span.contains(sp) { - return Some(sp); - } + } + + let sp = self.source_callsite(); + if outer_span.contains(sp) { + return Some(sp); } None @@ -107,7 +107,7 @@ impl SpanExt for Span { spans.sort_by_key(|s| (s.lo(), s.hi())); // See note in Span::subtract - for span in spans.iter_mut() { + for span in &mut spans { *span = span.with_ctxt(SyntaxContext::root()); } @@ -154,10 +154,14 @@ impl SpanExt for Span { let offset = line .chars() .take_while(|c| c.is_whitespace()) - .map(|c| c.len_utf8()) + .map(char::len_utf8) .sum::(); - let end = (start + BytePos(line.len() as u32)).min(self.hi()); - spans.push(self.with_lo(start + BytePos(offset as u32)).with_hi(end)); + let end = (start + BytePos(u32::try_from(line.len()).unwrap())).min(self.hi()); + spans.push( + self + .with_lo(start + BytePos(u32::try_from(offset).unwrap())) + .with_hi(end), + ); start = end + BytePos(1); } Some(spans) diff --git a/crates/rustc_utils/src/source_map/spanner/mir_span.rs b/crates/rustc_utils/src/source_map/spanner/mir_span.rs index 2546fb8b..58383874 100644 --- a/crates/rustc_utils/src/source_map/spanner/mir_span.rs +++ b/crates/rustc_utils/src/source_map/spanner/mir_span.rs @@ -50,7 +50,7 @@ impl<'tcx> MirVisitor<'tcx> for MirSpanCollector<'_, 'tcx> { span: span.data(), locations, place: Place::from_local(RETURN_PLACE, self.0.tcx), - }) + }); } fn visit_place( diff --git a/crates/rustc_utils/src/test_utils.rs b/crates/rustc_utils/src/test_utils.rs index 74d53c9f..83c24a4d 100644 --- a/crates/rustc_utils/src/test_utils.rs +++ b/crates/rustc_utils/src/test_utils.rs @@ -111,7 +111,7 @@ impl CompileBuilder { &*SYSROOT, ] .into_iter() - .map(|s| s.to_owned()) + .map(str::to_owned) .chain(self.arguments.iter().cloned()) .collect::>(); @@ -134,8 +134,8 @@ pub fn compile_body( ) { CompileBuilder::new(input).compile(|result| { let (body_id, body_with_facts) = result.as_body(); - callback(result.tcx, body_id, body_with_facts) - }) + callback(result.tcx, body_id, body_with_facts); + }); } /// State during the rust compilation. Most of the time you only care about @@ -152,11 +152,10 @@ impl<'tcx> CompileResult<'tcx> { let hir = tcx.hir(); let body_id = hir .items() - .filter_map(|id| match hir.item(id).kind { + .find_map(|id| match hir.item(id).kind { ItemKind::Fn(_, _, body) => Some(body), _ => None, }) - .next() .unwrap(); let def_id = tcx.hir().body_owner_def_id(body_id); @@ -169,7 +168,7 @@ impl<'tcx> CompileResult<'tcx> { pub fn as_body_with_range( &self, target: ByteRange, - ) -> (BodyId, &'tcx BodyWithBorrowckFacts) { + ) -> (BodyId, &'tcx BodyWithBorrowckFacts<'tcx>) { let tcx = self.tcx; let body_id = find_enclosing_bodies(tcx, target.to_span(tcx).unwrap()) .next() @@ -269,7 +268,7 @@ pub fn parse_ranges( Ok((prog_clean, ranges)) } -pub fn color_ranges(prog: &str, all_ranges: Vec<(&str, &HashSet)>) -> String { +pub fn color_ranges(prog: &str, all_ranges: &[(&str, &HashSet)]) -> String { let mut new_tokens = all_ranges .iter() .flat_map(|(_, ranges)| { @@ -284,7 +283,7 @@ pub fn color_ranges(prog: &str, all_ranges: Vec<(&str, &HashSet)>) -> }) }) .collect::>(); - new_tokens.sort_by_key(|(_, i)| -(i.0 as isize)); + new_tokens.sort_by_key(|(_, i)| -(isize::try_from(i.0).unwrap())); let mut output = prog.to_owned(); for (s, i) in new_tokens { @@ -295,21 +294,21 @@ pub fn color_ranges(prog: &str, all_ranges: Vec<(&str, &HashSet)>) -> } pub fn fmt_ranges(prog: &str, s: &HashSet) -> String { - textwrap::indent(&color_ranges(prog, vec![("", s)]), " ") + textwrap::indent(&color_ranges(prog, &[("", s)]), " ") } pub fn compare_ranges( - expected: HashSet, - actual: HashSet, + expected: &HashSet, + actual: &HashSet, prog: &str, ) { - let missing = &expected - &actual; - let extra = &actual - &expected; + let missing = expected - actual; + let extra = actual - expected; let check = |s: HashSet, message: &str| { if s.len() > 0 { - println!("Expected ranges:\n{}", fmt_ranges(prog, &expected)); - println!("Actual ranges:\n{}", fmt_ranges(prog, &actual)); + println!("Expected ranges:\n{}", fmt_ranges(prog, expected)); + println!("Actual ranges:\n{}", fmt_ranges(prog, actual)); panic!("{message} ranges:\n{}", fmt_ranges(prog, &s)); } };