Skip to content

Commit

Permalink
Fix various lints
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Dec 3, 2024
1 parent 8a0a9cc commit 7cf247b
Show file tree
Hide file tree
Showing 12 changed files with 113 additions and 154 deletions.
16 changes: 8 additions & 8 deletions crates/rustc_utils/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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));
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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<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 = 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")
}
}

Expand Down
27 changes: 9 additions & 18 deletions crates/rustc_utils/src/hir/ty.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -9,57 +8,49 @@ use rustc_type_ir::TypingMode;

/// Extension trait for [`Ty`].
pub trait TyExt<'tcx> {
type AllRegionsIter<'a>: Iterator<Item = Region<'tcx>>
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<Item = Region<'tcx>>;

/// 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<Item = Region<'tcx>> + Captures<'tcx> + 'a
where
Self: 'a;

fn inner_regions(&self) -> Self::AllRegionsIter<'_> {
fn inner_regions(self) -> impl Iterator<Item = Region<'tcx>> {
self.walk().filter_map(|part| match part.unpack() {
GenericArgKind::Lifetime(region) => Some(region),
_ => None,
})
}

fn does_implement_trait(
&self,
self,
tcx: TyCtxt<'tcx>,
param_env: ParamEnv<'tcx>,
trait_def_id: DefId,
) -> bool {
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,
EvaluationResult::EvaluatedToOk | EvaluationResult::EvaluatedToOkModuloRegions
)
}

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)
}
}
Expand Down
21 changes: 19 additions & 2 deletions crates/rustc_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)*) => (());
Expand Down
7 changes: 2 additions & 5 deletions crates/rustc_utils/src/mir/adt_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,21 @@ use rustc_middle::ty::{AdtDef, FieldDef, TyCtxt};

/// Extension trait for [`AdtDef`].
pub trait AdtDefExt<'tcx> {
type AllVisibleFieldsIter: Iterator<Item = &'tcx FieldDef>;

/// 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<Item = &'tcx FieldDef>;
}

impl<'tcx> AdtDefExt<'tcx> for AdtDef<'tcx> {
type AllVisibleFieldsIter = impl Iterator<Item = &'tcx FieldDef>;
fn all_visible_fields(
self,
module: DefId,
tcx: TyCtxt<'tcx>,
) -> Self::AllVisibleFieldsIter {
) -> impl Iterator<Item = &'tcx FieldDef> {
self
.all_fields()
.filter(move |field| field.vis.is_accessible_from(module, tcx))
Expand Down
86 changes: 28 additions & 58 deletions crates/rustc_utils/src/mir/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,24 +24,14 @@ use crate::{PlaceExt, TyExt};

/// Extension trait for [`Body`].
pub trait BodyExt<'tcx> {
type AllReturnsIter<'a>: Iterator<Item = Location>
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<Item = Location>
where
Self: 'a;
fn all_returns(&self) -> impl Iterator<Item = Location> + '_;

/// Returns an iterator over all the locations in a body.
fn all_locations(&self) -> Self::AllLocationsIter<'_>;

type LocationsIter: Iterator<Item = Location>;
fn all_locations(&self) -> impl Iterator<Item = Location> + '_;

/// 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<Item = Location>;

/// Returns a mapping from source-level variable names to [`Local`]s.
fn debug_info_name_map(&self) -> HashMap<String, Local>;
Expand All @@ -64,32 +57,22 @@ pub trait BodyExt<'tcx> {
/// locals across await calls.
fn async_context(&self, tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Ty<'tcx>>;

type PlacesIter<'a>: Iterator<Item = Place<'tcx>>
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<Item = Region<'tcx>>
where
Self: 'a;
fn all_places(
&self,
tcx: TyCtxt<'tcx>,
def_id: DefId,
) -> impl Iterator<Item = Place<'tcx>> + '_;

/// 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<Item = Region<'tcx>>;
fn regions_in_args(&self) -> impl Iterator<Item = Region<'tcx>> + '_;

/// 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<Item = Region<'tcx>> + '_;
}

impl<'tcx> BodyExt<'tcx> for Body<'tcx> {
type AllReturnsIter<'a>
= impl Iterator<Item = Location> + Captures<'tcx> + 'a
where
Self: 'a;
fn all_returns(&self) -> Self::AllReturnsIter<'_> {
fn all_returns(&self) -> impl Iterator<Item = Location> + '_ {
self
.basic_blocks
.iter_enumerated()
Expand All @@ -102,24 +85,19 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> {
})
}

type AllLocationsIter<'a>
= impl Iterator<Item = Location> + Captures<'tcx> + 'a
where
Self: 'a;
fn all_locations(&self) -> Self::AllLocationsIter<'_> {
fn all_locations(&self) -> impl Iterator<Item = Location> + '_ {
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<Item = Location>;
fn locations_in_block(&self, block: BasicBlock) -> Self::LocationsIter {
fn locations_in_block(&self, block: BasicBlock) -> impl Iterator<Item = Location> {
let num_stmts = self.basic_blocks[block].statements.len();
(0 ..= num_stmts).map(move |statement_index| Location {
block,
Expand Down Expand Up @@ -181,46 +159,38 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> {
}
}

type ArgRegionsIter<'a>
= impl Iterator<Item = Region<'tcx>> + Captures<'tcx> + 'a
where
Self: 'a;

type ReturnRegionsIter = impl Iterator<Item = Region<'tcx>>;

type PlacesIter<'a>
= impl Iterator<Item = Place<'tcx>> + Captures<'tcx> + 'a
where
Self: 'a;

fn regions_in_args(&self) -> Self::ArgRegionsIter<'_> {
fn regions_in_args(&self) -> impl Iterator<Item = Region<'tcx>> + '_ {
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<Item = Region<'tcx>> + '_ {
self
.return_ty()
.inner_regions()
.collect::<SmallVec<[Region<'tcx>; 8]>>()
.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<Item = Place<'tcx>> + '_ {
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<u8>) -> 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());
Expand Down
7 changes: 2 additions & 5 deletions crates/rustc_utils/src/mir/borrowck_facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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();
Expand All @@ -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>,
Expand Down
Loading

0 comments on commit 7cf247b

Please sign in to comment.