From 84687a6924ed298e5bd3eb5bf5540e5831fe021c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sat, 22 May 2021 20:20:46 +0200 Subject: [PATCH 1/8] =?UTF-8?q?=EF=BB=BFSeperate=20HIR=20owner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compiler/rustc_ast_lowering/src/expr.rs | 2 +- compiler/rustc_ast_lowering/src/item.rs | 20 +++--- compiler/rustc_ast_lowering/src/lib.rs | 49 ++++++++++----- compiler/rustc_hir/src/hir.rs | 23 ++++--- compiler/rustc_hir/src/hir_id.rs | 62 ++++++++++++++++--- compiler/rustc_hir/src/stable_hash_impls.rs | 6 +- .../src/persist/dirty_clean.rs | 18 +++--- .../src/infer/error_reporting/mod.rs | 4 +- compiler/rustc_infer/src/infer/mod.rs | 5 +- compiler/rustc_lint/src/builtin.rs | 6 +- compiler/rustc_lint/src/context.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 21 ++++--- .../rustc_middle/src/dep_graph/dep_node.rs | 2 +- .../rustc_middle/src/hir/map/collector.rs | 23 ++++--- compiler/rustc_middle/src/hir/map/mod.rs | 8 +-- compiler/rustc_middle/src/hir/mod.rs | 25 +++++--- compiler/rustc_middle/src/ich/impls_hir.rs | 24 ++++++- compiler/rustc_middle/src/query/mod.rs | 12 ++-- compiler/rustc_middle/src/ty/context.rs | 33 +++++----- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/query/mod.rs | 11 +++- .../diagnostics/mutability_errors.rs | 2 +- .../src/borrow_check/universal_regions.rs | 4 +- .../rustc_mir/src/monomorphize/collector.rs | 4 +- compiler/rustc_passes/src/diagnostic_items.rs | 13 ++-- compiler/rustc_passes/src/entry.rs | 2 +- compiler/rustc_passes/src/hir_id_validator.rs | 19 +++--- compiler/rustc_passes/src/layout_test.rs | 2 +- compiler/rustc_passes/src/reachable.rs | 4 +- compiler/rustc_passes/src/stability.rs | 2 +- compiler/rustc_plugin_impl/src/build.rs | 2 +- compiler/rustc_privacy/src/lib.rs | 2 +- compiler/rustc_query_impl/src/keys.rs | 10 +++ compiler/rustc_query_impl/src/plumbing.rs | 2 +- compiler/rustc_resolve/src/late/lifetimes.rs | 43 ++++++++----- .../rustc_save_analysis/src/dump_visitor.rs | 12 ++-- compiler/rustc_save_analysis/src/lib.rs | 4 +- compiler/rustc_symbol_mangling/src/test.rs | 6 +- compiler/rustc_typeck/src/check/_match.rs | 9 ++- compiler/rustc_typeck/src/check/check.rs | 20 +++--- .../rustc_typeck/src/check/compare_method.rs | 14 +++-- compiler/rustc_typeck/src/check/wfcheck.rs | 12 ++-- compiler/rustc_typeck/src/check_unused.rs | 4 +- .../src/coherence/inherent_impls.rs | 48 +++++++------- compiler/rustc_typeck/src/collect/type_of.rs | 6 +- compiler/rustc_typeck/src/impl_wf_check.rs | 4 +- src/librustdoc/clean/mod.rs | 2 +- 47 files changed, 376 insertions(+), 234 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 866f2180bb6e3..5e8315bcc43a9 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -341,7 +341,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // Add a definition for the in-band const def. self.resolver.create_def( - parent_def_id, + parent_def_id.def_id, node_id, DefPathData::AnonConst, ExpnId::root(), diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 292643d6d7510..6d83f1353057c 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -53,7 +53,7 @@ impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> { ItemKind::Mod(..) => { let def_id = this.lctx.lower_node_id(item.id).expect_owner(); let old_current_module = - mem::replace(&mut this.lctx.current_module, def_id); + mem::replace(&mut this.lctx.current_module, def_id.def_id); visit::walk_item(this, item); this.lctx.current_module = old_current_module; } @@ -404,7 +404,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let lowered_trait_def_id = self.lower_node_id(id).expect_owner(); let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( ast_generics, - lowered_trait_def_id, + lowered_trait_def_id.def_id, AnonymousLifetimeMode::CreateParameter, |this, _| { let trait_ref = trait_ref.as_ref().map(|trait_ref| { @@ -416,7 +416,7 @@ impl<'hir> LoweringContext<'_, 'hir> { this.trait_impls .entry(def_id) .or_default() - .push(lowered_trait_def_id); + .push(lowered_trait_def_id.def_id); } } @@ -714,7 +714,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let fdec = &sig.decl; let (generics, (fn_dec, fn_args)) = self.add_in_band_defs( generics, - def_id, + def_id.def_id, AnonymousLifetimeMode::PassThrough, |this, _| { ( @@ -832,8 +832,14 @@ impl<'hir> LoweringContext<'_, 'hir> { } AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, None)) => { let names = self.lower_fn_params_to_names(&sig.decl); - let (generics, sig) = - self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id); + let (generics, sig) = self.lower_method_sig( + generics, + sig, + trait_item_def_id.def_id, + false, + None, + i.id, + ); (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names))) } AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, Some(ref body))) => { @@ -843,7 +849,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let (generics, sig) = self.lower_method_sig( generics, sig, - trait_item_def_id, + trait_item_def_id.def_id, false, asyncness.opt_return_id(), i.id, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 6f1772ff8188d..2214174345904 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -51,7 +51,7 @@ use rustc_hir::def::{DefKind, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, CRATE_DEF_ID}; use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; use rustc_hir::intravisit; -use rustc_hir::{ConstArg, GenericArg, ParamName}; +use rustc_hir::{ConstArg, GenericArg, HirOwner, ParamName}; use rustc_index::vec::{Idx, IndexVec}; use rustc_session::lint::builtin::{BARE_TRAIT_OBJECTS, MISSING_ABI}; use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer}; @@ -166,7 +166,7 @@ struct LoweringContext<'a, 'hir: 'a> { type_def_lifetime_params: DefIdMap, - current_hir_id_owner: (LocalDefId, u32), + current_hir_id_owner: (HirOwner, u32), item_local_id_counters: NodeMap, node_id_to_hir_id: IndexVec>, @@ -223,7 +223,7 @@ enum ImplTraitContext<'b, 'a> { /// equivalent to a fresh universal parameter like `fn foo(x: T)`. /// /// Newly generated parameters should be inserted into the given `Vec`. - Universal(&'b mut Vec>, LocalDefId), + Universal(&'b mut Vec>, HirOwner), /// Treat `impl Trait` as shorthand for a new opaque type. /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually @@ -322,7 +322,7 @@ pub fn lower_crate<'a, 'hir>( anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough, type_def_lifetime_params: Default::default(), current_module: CRATE_DEF_ID, - current_hir_id_owner: (CRATE_DEF_ID, 0), + current_hir_id_owner: (HirOwner { def_id: CRATE_DEF_ID }, 0), item_local_id_counters: Default::default(), node_id_to_hir_id: IndexVec::new(), generator_kind: None, @@ -594,7 +594,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { .item_local_id_counters .insert(owner, HIR_ID_COUNTER_LOCKED) .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner)); - let def_id = self.resolver.local_def_id(owner); + let def_id = HirOwner { def_id: self.resolver.local_def_id(owner) }; let old_owner = std::mem::replace(&mut self.current_hir_id_owner, (def_id, counter)); let ret = f(self); let (new_def_id, new_counter) = @@ -637,10 +637,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert!(local_id != HIR_ID_COUNTER_LOCKED); *local_id_counter += 1; - let owner = this.resolver.opt_local_def_id(owner).expect( - "you forgot to call `create_def` or are lowering node-IDs \ + let owner = HirOwner { + def_id: this.resolver.opt_local_def_id(owner).expect( + "you forgot to call `create_def` or are lowering node-IDs \ that do not belong to the current owner", - ); + ), + }; hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) } }) @@ -1133,7 +1135,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let impl_trait_node_id = self.resolver.next_node_id(); self.resolver.create_def( - parent_def_id, + parent_def_id.def_id, impl_trait_node_id, DefPathData::ImplTrait, ExpnId::root(), @@ -1201,7 +1203,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Add a definition for the in-band const def. self.resolver.create_def( - parent_def_id, + parent_def_id.def_id, node_id, DefPathData::AnonConst, ExpnId::root(), @@ -1512,10 +1514,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id); - lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span); + lctx.generate_opaque_type( + HirOwner { def_id: opaque_ty_def_id }, + opaque_ty_item, + span, + opaque_ty_span, + ); // `impl Trait` now just becomes `Foo<'a, 'b, ..>`. - hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, lifetimes) + hir::TyKind::OpaqueDef( + hir::ItemId { def_id: HirOwner { def_id: opaque_ty_def_id } }, + lifetimes, + ) }) } @@ -1523,7 +1533,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// returns the lowered node-ID for the opaque type. fn generate_opaque_type( &mut self, - opaque_ty_id: LocalDefId, + opaque_ty_id: HirOwner, opaque_ty_item: hir::OpaqueTy<'hir>, span: Span, opaque_ty_span: Span, @@ -2015,7 +2025,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id); - this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span); + this.generate_opaque_type( + HirOwner { def_id: opaque_ty_def_id }, + opaque_ty_item, + span, + opaque_ty_span, + ); lifetime_params }); @@ -2060,8 +2075,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Foo = impl Trait` is, internally, created as a child of the // async fn, so the *type parameters* are inherited. It's // only the lifetime parameters that we must supply. - let opaque_ty_ref = - hir::TyKind::OpaqueDef(hir::ItemId { def_id: opaque_ty_def_id }, generic_args); + let opaque_ty_ref = hir::TyKind::OpaqueDef( + hir::ItemId { def_id: HirOwner { def_id: opaque_ty_def_id } }, + generic_args, + ); let opaque_ty = self.ty(opaque_ty_span, opaque_ty_ref); hir::FnRetTy::Return(self.arena.alloc(opaque_ty)) } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 91fd97a0d4020..8a40aec3ae10d 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1,7 +1,7 @@ // ignore-tidy-filelength use crate::def::{CtorKind, DefKind, Res}; use crate::def_id::DefId; -crate use crate::hir_id::HirId; +crate use crate::hir_id::{HirId, HirOwner}; use crate::{itemlikevisit, LangItem}; use rustc_ast::util::parser::ExprPrecedence; @@ -753,7 +753,7 @@ impl Crate<'_> { pub struct MacroDef<'hir> { pub ident: Ident, pub vis: Visibility<'hir>, - pub def_id: LocalDefId, + pub def_id: HirOwner, pub span: Span, pub ast: ast::MacroDef, } @@ -1994,7 +1994,7 @@ pub struct FnSig<'hir> { // so it can fetched later. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] pub struct TraitItemId { - pub def_id: LocalDefId, + pub def_id: HirOwner, } impl TraitItemId { @@ -2012,7 +2012,7 @@ impl TraitItemId { #[derive(Debug)] pub struct TraitItem<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: HirOwner, pub generics: Generics<'hir>, pub kind: TraitItemKind<'hir>, pub span: Span, @@ -2055,9 +2055,10 @@ pub enum TraitItemKind<'hir> { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. +/// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] pub struct ImplItemId { - pub def_id: LocalDefId, + pub def_id: HirOwner, } impl ImplItemId { @@ -2072,7 +2073,7 @@ impl ImplItemId { #[derive(Debug)] pub struct ImplItem<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: HirOwner, pub vis: Visibility<'hir>, pub defaultness: Defaultness, pub generics: Generics<'hir>, @@ -2653,9 +2654,10 @@ impl VariantData<'hir> { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. +/// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)] pub struct ItemId { - pub def_id: LocalDefId, + pub def_id: HirOwner, } impl ItemId { @@ -2672,7 +2674,7 @@ impl ItemId { #[derive(Debug)] pub struct Item<'hir> { pub ident: Ident, - pub def_id: LocalDefId, + pub def_id: HirOwner, pub kind: ItemKind<'hir>, pub vis: Visibility<'hir>, pub span: Span, @@ -2858,9 +2860,10 @@ pub enum AssocItemKind { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. +// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] pub struct ForeignItemId { - pub def_id: LocalDefId, + pub def_id: HirOwner, } impl ForeignItemId { @@ -2890,7 +2893,7 @@ pub struct ForeignItemRef<'hir> { pub struct ForeignItem<'hir> { pub ident: Ident, pub kind: ForeignItemKind<'hir>, - pub def_id: LocalDefId, + pub def_id: HirOwner, pub span: Span, pub vis: Visibility<'hir>, } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index 0b25ebc27bd3f..d13efe7cd9b28 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -1,7 +1,51 @@ -use crate::def_id::{LocalDefId, CRATE_DEF_INDEX}; +use crate::def_id::{DefId, LocalDefId, CRATE_DEF_INDEX}; use rustc_index::vec::IndexVec; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fmt; +/// TODO +#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)] +pub struct HirOwner { + pub def_id: LocalDefId, +} + +impl HirOwner { + pub fn def_id(&self) -> LocalDefId { + self.def_id + } + + pub fn to_def_id(&self) -> DefId { + self.def_id.to_def_id() + } +} + +impl rustc_index::vec::Idx for HirOwner { + fn new(idx: usize) -> Self { + Self { def_id: LocalDefId::new(idx) } + } + fn index(self) -> usize { + self.def_id.index() + } +} + +impl Encodable for HirOwner { + fn encode(&self, s: &mut E) -> Result<(), E::Error> { + self.def_id.to_def_id().encode(s) + } +} + +impl Decodable for HirOwner { + fn decode(d: &mut D) -> Result { + LocalDefId::decode(d).map(|d| Self { def_id: d }) + } +} + +impl From for LocalDefId { + fn from(f: HirOwner) -> Self { + f.def_id + } +} + /// Uniquely identifies a node in the HIR of the current crate. It is /// composed of the `owner`, which is the `LocalDefId` of the directly enclosing /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"), @@ -15,22 +59,22 @@ use std::fmt; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] #[derive(Encodable, Decodable)] pub struct HirId { - pub owner: LocalDefId, + pub owner: HirOwner, pub local_id: ItemLocalId, } impl HirId { - pub fn expect_owner(self) -> LocalDefId { + pub fn expect_owner(self) -> HirOwner { assert_eq!(self.local_id.index(), 0); self.owner } - pub fn as_owner(self) -> Option { + pub fn as_owner(self) -> Option { if self.local_id.index() == 0 { Some(self.owner) } else { None } } #[inline] - pub fn make_owner(owner: LocalDefId) -> Self { + pub fn make_owner(owner: HirOwner) -> Self { Self { owner, local_id: ItemLocalId::from_u32(0) } } } @@ -59,18 +103,18 @@ rustc_data_structures::impl_stable_hash_via_hash!(ItemLocalId); /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`. pub const CRATE_HIR_ID: HirId = HirId { - owner: LocalDefId { local_def_index: CRATE_DEF_INDEX }, + owner: HirOwner { def_id: LocalDefId { local_def_index: CRATE_DEF_INDEX } }, local_id: ItemLocalId::from_u32(0), }; /// N.B. This collection is currently unused, but will be used by #72015 and future PRs. #[derive(Clone, Default, Debug, Encodable, Decodable)] pub struct HirIdVec { - map: IndexVec>, + map: IndexVec>, } impl HirIdVec { - pub fn push_owner(&mut self, id: LocalDefId) { + pub fn push_owner(&mut self, id: HirOwner) { self.map.ensure_contains_elem(id, IndexVec::new); } @@ -101,7 +145,7 @@ impl HirIdVec { self.map.get(id.owner)?.get(id.local_id) } - pub fn get_owner(&self, id: LocalDefId) -> &IndexVec { + pub fn get_owner(&self, id: HirOwner) -> &IndexVec { &self.map[id] } diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index 0232654aaa524..fd7e358a1dfe1 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -4,8 +4,8 @@ use crate::hir::{ BodyId, Expr, ForeignItem, ForeignItemId, ImplItem, ImplItemId, Item, ItemId, MacroDef, Mod, TraitItem, TraitItemId, Ty, VisibilityKind, }; -use crate::hir_id::{HirId, ItemLocalId}; -use rustc_span::def_id::{DefPathHash, LocalDefId}; +use crate::hir_id::{HirId, HirOwner, ItemLocalId}; +use rustc_span::def_id::DefPathHash; /// Requirements for a `StableHashingContext` to be used in this crate. /// This is a hack to allow using the `HashStable_Generic` derive macro @@ -21,7 +21,7 @@ pub trait HashStableContext: fn hash_hir_ty(&mut self, _: &Ty<'_>, hasher: &mut StableHasher); fn hash_hir_visibility_kind(&mut self, _: &VisibilityKind<'_>, hasher: &mut StableHasher); fn hash_hir_item_like(&mut self, f: F); - fn local_def_path_hash(&self, def_id: LocalDefId) -> DefPathHash; + fn local_def_path_hash(&self, def_id: HirOwner) -> DefPathHash; } impl ToStableHashKey for HirId { diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index e7bd488af8ebf..51c16fe307c36 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -16,7 +16,8 @@ use rustc_ast::{self as ast, Attribute, NestedMetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; -use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::def_id::DefId; +use rustc_hir::hir_id::HirOwner; use rustc_hir::intravisit; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_hir::Node as HirNode; @@ -168,7 +169,7 @@ pub struct DirtyCleanVisitor<'tcx> { impl DirtyCleanVisitor<'tcx> { /// Possibly "deserialize" the attribute into a clean/dirty assertion - fn assertion_maybe(&mut self, item_id: LocalDefId, attr: &Attribute) -> Option { + fn assertion_maybe(&mut self, item_id: HirOwner, attr: &Attribute) -> Option { let is_clean = if self.tcx.sess.check_name(attr, sym::rustc_dirty) { false } else if self.tcx.sess.check_name(attr, sym::rustc_clean) { @@ -194,12 +195,7 @@ impl DirtyCleanVisitor<'tcx> { } /// Gets the "auto" assertion on pre-validated attr, along with the `except` labels. - fn assertion_auto( - &mut self, - item_id: LocalDefId, - attr: &Attribute, - is_clean: bool, - ) -> Assertion { + fn assertion_auto(&mut self, item_id: HirOwner, attr: &Attribute, is_clean: bool) -> Assertion { let (name, mut auto) = self.auto_labels(item_id, attr); let except = self.except(attr); for e in except.iter() { @@ -242,8 +238,8 @@ impl DirtyCleanVisitor<'tcx> { /// Return all DepNode labels that should be asserted for this item. /// index=0 is the "name" used for error messages - fn auto_labels(&mut self, item_id: LocalDefId, attr: &Attribute) -> (&'static str, Labels) { - let hir_id = self.tcx.hir().local_def_id_to_hir_id(item_id); + fn auto_labels(&mut self, item_id: HirOwner, attr: &Attribute) -> (&'static str, Labels) { + let hir_id = self.tcx.hir().local_def_id_to_hir_id(item_id.def_id); let node = self.tcx.hir().get(hir_id); let (name, labels) = match node { HirNode::Item(item) => { @@ -399,7 +395,7 @@ impl DirtyCleanVisitor<'tcx> { } } - fn check_item(&mut self, item_id: LocalDefId, item_span: Span) { + fn check_item(&mut self, item_id: HirOwner, item_span: Span) { for attr in self.tcx.get_attrs(item_id.to_def_id()).iter() { let assertion = match self.assertion_maybe(item_id, attr) { Some(a) => a, diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 680f6af63f26c..46e976fc039ca 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2052,7 +2052,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { .in_progress_typeck_results .map(|typeck_results| typeck_results.borrow().hir_owner) .map(|owner| { - let hir_id = hir.local_def_id_to_hir_id(owner); + let hir_id = hir.local_def_id_to_hir_id(owner.def_id); let parent_id = hir.get_parent_item(hir_id); ( // Parent item could be a `mod`, so we check the HIR before calling: @@ -2267,7 +2267,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let return_impl_trait = self .in_progress_typeck_results .map(|typeck_results| typeck_results.borrow().hir_owner) - .and_then(|owner| self.tcx.return_type_impl_trait(owner)) + .and_then(|owner| self.tcx.return_type_impl_trait(owner.def_id)) .is_some(); let t = self.resolve_vars_if_possible(t); match t.kind() { diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index f39431f2494b1..61878491c2392 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -14,7 +14,8 @@ use rustc_data_structures::undo_log::Rollback; use rustc_data_structures::unify as ut; use rustc_errors::DiagnosticBuilder; use rustc_hir as hir; -use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::def_id::DefId; +use rustc_hir::hir_id::HirOwner; use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue}; use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType}; @@ -546,7 +547,7 @@ impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { impl<'tcx> InferCtxtBuilder<'tcx> { /// Used only by `rustc_typeck` during body type-checking/inference, /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. - pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { + pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: HirOwner) -> Self { self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); self } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index e7275374b8915..61e46164f3502 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -817,7 +817,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { debug!("{:?}", self.impling_types); } - if !self.impling_types.as_ref().unwrap().contains(&item.def_id) { + if !self.impling_types.as_ref().unwrap().contains(&item.def_id.def_id) { cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { lint.build(&format!( "type does not implement `{}`; consider adding `#[derive(Debug)]` \ @@ -1830,7 +1830,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems { if let hir::ItemKind::Mod(..) = it.kind { } else { self.items_nameable = false; - self.boundary = Some(it.def_id); + self.boundary = Some(it.def_id.def_id); } return; } @@ -1844,7 +1844,7 @@ impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems { } fn check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>) { - if !self.items_nameable && self.boundary == Some(it.def_id) { + if !self.items_nameable && self.boundary == Some(it.def_id.def_id) { self.items_nameable = true; } } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index c1d6a4f1de1ff..5d271224f8d38 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -840,7 +840,7 @@ impl<'tcx> LateContext<'tcx> { .filter(|typeck_results| typeck_results.hir_owner == id.owner) .or_else(|| { if self.tcx.has_typeck_results(id.owner.to_def_id()) { - Some(self.tcx.typeck(id.owner)) + Some(self.tcx.typeck(id.owner.def_id)) } else { None } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 0c31430598a98..a6f820a6b80da 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -447,9 +447,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_def_path_table(&mut self) { let table = self.tcx.hir().definitions().def_path_table(); if self.is_proc_macro { - for def_index in std::iter::once(CRATE_DEF_INDEX) - .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)) - { + for def_index in std::iter::once(CRATE_DEF_INDEX).chain( + self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.def_id.local_def_index), + ) { let def_key = self.lazy(table.def_key(def_index)); let def_path_hash = self.lazy(table.def_path_hash(def_index)); self.tables.def_keys.set(def_index, def_key); @@ -1071,7 +1071,7 @@ impl EncodeContext<'a, 'tcx> { record!(self.tables.children[def_id] <- &[]); } else { record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| { - item_id.def_id.local_def_index + item_id.def_id.def_id.local_def_index })); } } @@ -1363,7 +1363,7 @@ impl EncodeContext<'a, 'tcx> { EntryKind::Fn(self.lazy(data)) } hir::ItemKind::Mod(ref m) => { - return self.encode_info_for_mod(item.def_id, m); + return self.encode_info_for_mod(item.def_id.def_id, m); } hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, @@ -1462,7 +1462,7 @@ impl EncodeContext<'a, 'tcx> { hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <- items .iter() - .map(|foreign_item| foreign_item.id.def_id.local_def_index) + .map(|foreign_item| foreign_item.id.def_id.def_id.local_def_index) ), hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- self.tcx.adt_def(def_id).variants.iter().map(|v| { @@ -1601,7 +1601,8 @@ impl EncodeContext<'a, 'tcx> { let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); - let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index)); + let macros = + self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.def_id.local_def_index)); let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans(); for (i, span) in spans.into_iter().enumerate() { let span = self.lazy(span); @@ -1621,7 +1622,7 @@ impl EncodeContext<'a, 'tcx> { // defined in this crate. However, we skip doing that for proc-macro crates, // so we manually encode just the information that we need for proc_macro in &hir.krate().proc_macros { - let id = proc_macro.owner.local_def_index; + let id = proc_macro.owner.def_id.local_def_index; let mut name = hir.name(*proc_macro); let span = hir.span(*proc_macro); // Proc-macros may have attributes like `#[allow_internal_unstable]`, @@ -1644,7 +1645,7 @@ impl EncodeContext<'a, 'tcx> { bug!("Unknown proc-macro type for item {:?}", id); }; - let mut def_key = self.tcx.hir().def_key(proc_macro.owner); + let mut def_key = self.tcx.hir().def_key(proc_macro.owner.def_id); def_key.disambiguated_data.data = DefPathData::MacroNs(name); let def_id = DefId::local(id); @@ -2004,7 +2005,7 @@ impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> { self.impls .entry(trait_ref.def_id) .or_default() - .push((item.def_id.local_def_index, simplified_self_ty)); + .push((item.def_id.def_id.local_def_index, simplified_self_ty)); } } } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 8476929eaeced..adf92c7f3d80a 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -483,7 +483,7 @@ impl<'tcx> DepNodeParams> for HirId { fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { let HirId { owner, local_id } = *self; - let def_path_hash = tcx.def_path_hash(owner.to_def_id()); + let def_path_hash = tcx.def_path_hash(owner.def_id.to_def_id()); let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into()); def_path_hash.0.combine(local_id) diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 342cc9a7397b7..9ba0d30a25ff7 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -9,6 +9,7 @@ use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::CRATE_DEF_INDEX; use rustc_hir::definitions; +use rustc_hir::hir_id::HirOwner; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::*; use rustc_index::vec::{Idx, IndexVec}; @@ -28,13 +29,13 @@ pub(super) struct NodeCollector<'a, 'hir> { /// Source map source_map: &'a SourceMap, - map: IndexVec>, - parenting: FxHashMap, + map: IndexVec>, + parenting: FxHashMap, /// The parent of this node parent_node: hir::HirId, - current_dep_node_owner: LocalDefId, + current_dep_node_owner: HirOwner, definitions: &'a definitions::Definitions, @@ -104,7 +105,9 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { krate, source_map: sess.source_map(), parent_node: hir::CRATE_HIR_ID, - current_dep_node_owner: LocalDefId { local_def_index: CRATE_DEF_INDEX }, + current_dep_node_owner: HirOwner { + def_id: LocalDefId { local_def_index: CRATE_DEF_INDEX }, + }, definitions, hcx, map: (0..definitions.def_index_count()) @@ -154,7 +157,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { debug_assert!(data.signature.is_none()); data.signature = Some(self.arena.alloc(Owner { node: entry.node })); - let dk_parent = self.definitions.def_key(id.owner).parent; + let dk_parent = self.definitions.def_key(id.owner.def_id).parent; if let Some(dk_parent) = dk_parent { let dk_parent = LocalDefId { local_def_index: dk_parent }; let dk_parent = self.definitions.local_def_id_to_hir_id(dk_parent); @@ -200,10 +203,10 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { self.source_map.span_to_diagnostic_string(span), node_str, self.definitions - .def_path(self.current_dep_node_owner) + .def_path(self.current_dep_node_owner.def_id) .to_string_no_crate_verbose(), self.current_dep_node_owner, - self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(), + self.definitions.def_path(hir_id.owner.def_id).to_string_no_crate_verbose(), hir_id.owner, ) } @@ -224,7 +227,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { F: FnOnce(&mut Self, Fingerprint), >( &mut self, - dep_node_owner: LocalDefId, + dep_node_owner: HirOwner, item_like: &T, f: F, ) { @@ -236,7 +239,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { self.current_dep_node_owner = prev_owner; } - fn insert_nested(&mut self, item: LocalDefId) { + fn insert_nested(&mut self, item: HirOwner) { #[cfg(debug_assertions)] { let dk_parent = self.definitions.def_key(item).parent.unwrap(); @@ -464,7 +467,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { // Exported macros are visited directly from the crate root, // so they do not have `parent_node` set. // Find the correct enclosing module from their DefKey. - let def_key = self.definitions.def_key(macro_def.def_id); + let def_key = self.definitions.def_key(macro_def.def_id.def_id); let parent = def_key.parent.map_or(hir::CRATE_HIR_ID, |local_def_index| { self.definitions.local_def_id_to_hir_id(LocalDefId { local_def_index }) }); diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index d154b7804f052..dad2f153d4717 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -132,7 +132,7 @@ impl<'hir> Iterator for ParentOwnerIterator<'_, 'hir> { } loop { // There are nodes that do not have entries, so we need to skip them. - let parent_id = self.map.def_key(self.current_id.owner).parent; + let parent_id = self.map.def_key(self.current_id.owner.def_id).parent; let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| { let def_id = LocalDefId { local_def_index }; @@ -814,7 +814,7 @@ impl<'hir> Map<'hir> { /// Given a node ID, gets a list of attributes associated with the AST /// corresponding to the node-ID. pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { - self.tcx.hir_attrs(id.owner).get(id.local_id) + self.tcx.hir_attrs(id.owner.def_id).get(id.local_id) } /// Gets the span of the definition of the specified HIR node. @@ -950,10 +950,10 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { .map .iter_enumerated() .filter_map(|(def_id, hod)| { - let def_path_hash = tcx.definitions.def_path_hash(def_id); + let def_path_hash = tcx.definitions.def_path_hash(def_id.def_id); let mut hasher = StableHasher::new(); hod.with_bodies.as_ref()?.hash_stable(&mut hcx, &mut hasher); - AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id } + AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id.def_id } .hash_stable(&mut hcx, &mut hasher); Some((def_path_hash, hasher.finish())) }) diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 879372c65eaa1..8264a67995157 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -13,7 +13,8 @@ use rustc_ast::Attribute; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_hir::def_id::LocalDefId; +use rustc_hir::def_id::{LocalDefId}; +use rustc_hir::hir_id::HirOwner; use rustc_hir::*; use rustc_index::vec::IndexVec; use rustc_span::DUMMY_SP; @@ -27,8 +28,8 @@ struct HirOwnerData<'hir> { #[derive(Debug)] pub struct IndexedHir<'hir> { - map: IndexVec>, - parenting: FxHashMap, + map: IndexVec>, + parenting: FxHashMap, } #[derive(Debug)] @@ -94,15 +95,21 @@ impl<'tcx> std::fmt::Debug for AttributeMap<'tcx> { impl<'tcx> AttributeMap<'tcx> { fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] { - self.map.get(&HirId { owner: self.prefix, local_id: id }).copied().unwrap_or(&[]) + self.map + .get(&HirId { owner: HirOwner { def_id: self.prefix }, local_id: id }) + .copied() + .unwrap_or(&[]) } fn range(&self) -> std::collections::btree_map::Range<'_, rustc_hir::HirId, &[Attribute]> { let local_zero = ItemLocalId::from_u32(0); - let range = HirId { owner: self.prefix, local_id: local_zero }..HirId { - owner: LocalDefId { local_def_index: self.prefix.local_def_index + 1 }, - local_id: local_zero, - }; + let range = HirId { owner: HirOwner { def_id: self.prefix }, local_id: local_zero } + ..HirId { + owner: HirOwner { + def_id: LocalDefId { local_def_index: self.prefix.local_def_index + 1 }, + }, + local_id: local_zero, + }; self.map.range(range) } } @@ -114,7 +121,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn parent_module(self, id: HirId) -> LocalDefId { - self.parent_module_from_def_id(id.owner) + self.parent_module_from_def_id(id.owner.def_id) } } diff --git a/compiler/rustc_middle/src/ich/impls_hir.rs b/compiler/rustc_middle/src/ich/impls_hir.rs index abf56832329b2..532b6563a7d0c 100644 --- a/compiler/rustc_middle/src/ich/impls_hir.rs +++ b/compiler/rustc_middle/src/ich/impls_hir.rs @@ -8,6 +8,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHas use rustc_hir as hir; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX}; use rustc_hir::definitions::DefPathHash; +use rustc_hir::hir_id::HirOwner; use smallvec::SmallVec; use std::mem; @@ -22,7 +23,7 @@ impl<'ctx> rustc_hir::HashStableContext for StableHashingContext<'ctx> { NodeIdHashingMode::HashDefPath => { let hir::HirId { owner, local_id } = hir_id; - hcx.local_def_path_hash(owner).hash_stable(hcx, hasher); + hcx.local_def_path_hash(owner.def_id).hash_stable(hcx, hasher); local_id.hash_stable(hcx, hasher); } } @@ -115,8 +116,8 @@ impl<'ctx> rustc_hir::HashStableContext for StableHashingContext<'ctx> { } #[inline] - fn local_def_path_hash(&self, def_id: LocalDefId) -> DefPathHash { - self.local_def_path_hash(def_id) + fn local_def_path_hash(&self, def_id: HirOwner) -> DefPathHash { + self.local_def_path_hash(def_id.def_id) } } @@ -136,6 +137,13 @@ impl<'a> HashStable> for LocalDefId { } } +impl<'a> HashStable> for HirOwner { + #[inline] + fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { + self.def_id.hash_stable(hcx, hasher); + } +} + impl<'a> ToStableHashKey> for LocalDefId { type KeyType = DefPathHash; @@ -145,6 +153,16 @@ impl<'a> ToStableHashKey> for LocalDefId { } } +impl<'a> ToStableHashKey> for HirOwner { + type KeyType = + >>::KeyType; + + #[inline] + fn to_stable_hash_key(&self, hcx: &StableHashingContext<'a>) -> DefPathHash { + self.def_id.to_stable_hash_key(hcx) + } +} + impl<'a> ToStableHashKey> for CrateNum { type KeyType = DefPathHash; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 9125be33c93da..7e16d41516489 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -47,27 +47,27 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner(key: LocalDefId) -> Option<&'tcx crate::hir::Owner<'tcx>> { + query hir_owner(key: HirOwner ) -> Option<&'tcx crate::hir::Owner<'tcx>> { eval_always - desc { |tcx| "HIR owner of `{}`", tcx.def_path_str(key.to_def_id()) } + desc { |tcx| "HIR owner of `{}`", tcx.def_path_str(key.def_id.to_def_id()) } } /// Gives access to the HIR node's parent for the HIR owner `key`. /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner_parent(key: LocalDefId) -> hir::HirId { + query hir_owner_parent(key: HirOwner ) -> hir::HirId { eval_always - desc { |tcx| "HIR parent of `{}`", tcx.def_path_str(key.to_def_id()) } + desc { |tcx| "HIR parent of `{}`", tcx.def_path_str(key.def_id.to_def_id()) } } /// Gives access to the HIR nodes and bodies inside the HIR owner `key`. /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_owner_nodes(key: LocalDefId) -> Option<&'tcx crate::hir::OwnerNodes<'tcx>> { + query hir_owner_nodes(key: HirOwner) -> Option<&'tcx crate::hir::OwnerNodes<'tcx>> { eval_always - desc { |tcx| "HIR owner items in `{}`", tcx.def_path_str(key.to_def_id()) } + desc { |tcx| "HIR owner items in `{}`", tcx.def_path_str(key.def_id.to_def_id()) } } /// Gives access to the HIR attributes inside the HIR owner `key`. diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index cb08d7671bd29..ed44167c2bdff 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -39,6 +39,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE}; use rustc_hir::definitions::Definitions; +use rustc_hir::hir_id::HirOwner; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ @@ -204,7 +205,7 @@ pub struct CommonConsts<'tcx> { } pub struct LocalTableInContext<'a, V> { - hir_owner: LocalDefId, + hir_owner: HirOwner, data: &'a ItemLocalMap, } @@ -216,7 +217,7 @@ pub struct LocalTableInContext<'a, V> { /// would result in lookup errors, or worse, in silently wrong data being /// stored/returned. #[inline] -fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { +fn validate_hir_id_for_typeck_results(hir_owner: HirOwner, hir_id: hir::HirId) { if hir_id.owner != hir_owner { invalid_hir_id_for_typeck_results(hir_owner, hir_id); } @@ -224,7 +225,7 @@ fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) #[cold] #[inline(never)] -fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { +fn invalid_hir_id_for_typeck_results(hir_owner: HirOwner, hir_id: hir::HirId) { ty::tls::with(|tcx| { bug!( "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}", @@ -260,7 +261,7 @@ impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { } pub struct LocalTableInContextMut<'a, V> { - hir_owner: LocalDefId, + hir_owner: HirOwner, data: &'a mut ItemLocalMap, } @@ -333,7 +334,7 @@ pub struct GeneratorInteriorTypeCause<'tcx> { #[derive(TyEncodable, TyDecodable, Debug)] pub struct TypeckResults<'tcx> { /// The `HirId::owner` all `ItemLocalId`s in this table are relative to. - pub hir_owner: LocalDefId, + pub hir_owner: HirOwner, /// Resolved definitions for `::X` associated paths and /// method calls, including those of overloaded operators. @@ -466,7 +467,7 @@ pub struct TypeckResults<'tcx> { } impl<'tcx> TypeckResults<'tcx> { - pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { + pub fn new(hir_owner: HirOwner) -> TypeckResults<'tcx> { TypeckResults { hir_owner, type_dependent_defs: Default::default(), @@ -736,7 +737,7 @@ impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { } = *self; hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { - hcx.local_def_path_hash(hir_owner); + hcx.local_def_path_hash(hir_owner.def_id); type_dependent_defs.hash_stable(hcx, hasher); field_indices.hash_stable(hcx, hasher); @@ -968,7 +969,7 @@ pub struct GlobalCtxt<'tcx> { /// Map indicating what traits are in scope for places where this /// is relevant; generated by resolve. - trait_map: FxHashMap>>, + trait_map: FxHashMap>>, /// Export map produced by name resolution. export_map: ExportMap, @@ -2663,26 +2664,26 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec> { - self.in_scope_traits_map(id.owner).and_then(|map| map.get(&id.local_id)) + self.in_scope_traits_map(id.owner.def_id).and_then(|map| map.get(&id.local_id)) } pub fn named_region(self, id: HirId) -> Option { debug!(?id, "named_region"); - self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) + self.named_region_map(id.owner.def_id).and_then(|map| map.get(&id.local_id).cloned()) } pub fn is_late_bound(self, id: HirId) -> bool { - self.is_late_bound_map(id.owner) - .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) + self.is_late_bound_map(id.owner.def_id) + .map_or(false, |(owner, set)| owner == id.owner.def_id && set.contains(&id.local_id)) } pub fn object_lifetime_defaults(self, id: HirId) -> Option> { - self.object_lifetime_defaults_map(id.owner) + self.object_lifetime_defaults_map(id.owner.def_id) } pub fn late_bound_vars(self, id: HirId) -> &'tcx List { self.mk_bound_variable_kinds( - self.late_bound_vars_map(id.owner) + self.late_bound_vars_map(id.owner.def_id) .and_then(|map| map.get(&id.local_id).cloned()) .unwrap_or_else(|| { bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) @@ -2692,7 +2693,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn lifetime_scope(self, id: HirId) -> Option { - self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) + self.lifetime_scope_map(id.owner.def_id).and_then(|mut map| map.remove(&id.local_id)) } } @@ -2793,7 +2794,7 @@ fn ptr_eq(t: *const T, u: *const U) -> bool { } pub fn provide(providers: &mut ty::query::Providers) { - providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id); + providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&HirOwner { def_id: id }); providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]); providers.crate_name = |tcx, id| { assert_eq!(id, LOCAL_CRATE); diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index f514278a11c93..4c39b131eec5d 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2239,7 +2239,7 @@ fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, N continue; } - let def_id = item.def_id.to_def_id(); + let def_id = item.def_id.def_id.to_def_id(); let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS); collect_fn(&item.ident, ns, def_id); } diff --git a/compiler/rustc_middle/src/ty/query/mod.rs b/compiler/rustc_middle/src/ty/query/mod.rs index 3bdb438896bf2..02e3ea4d8d99f 100644 --- a/compiler/rustc_middle/src/ty/query/mod.rs +++ b/compiler/rustc_middle/src/ty/query/mod.rs @@ -43,7 +43,7 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId}; use rustc_hir::lang_items::{LangItem, LanguageItems}; -use rustc_hir::{Crate, ItemLocalId, TraitCandidate}; +use rustc_hir::{Crate, HirOwner, ItemLocalId, TraitCandidate}; use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec}; use rustc_serialize::opaque; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; @@ -285,7 +285,7 @@ macro_rules! define_callbacks { rustc_query_append! { [define_callbacks!][<'tcx>] } mod sealed { - use super::{DefId, LocalDefId}; + use super::{DefId, HirOwner, LocalDefId}; /// An analogue of the `Into` trait that's intended only for query paramaters. /// @@ -308,6 +308,13 @@ mod sealed { self.to_def_id() } } + + impl IntoQueryParam for HirOwner { + #[inline(always)] + fn into_query_param(self) -> DefId { + self.def_id.into_query_param() + } + } } use sealed::IntoQueryParam; diff --git a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs index d2b156610476c..7e271c22b443a 100644 --- a/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs +++ b/compiler/rustc_mir/src/borrow_check/diagnostics/mutability_errors.rs @@ -698,7 +698,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { { let opt_suggestions = path_segment .hir_id - .map(|path_hir_id| self.infcx.tcx.typeck(path_hir_id.owner)) + .map(|path_hir_id| self.infcx.tcx.typeck(path_hir_id.owner.def_id)) .and_then(|typeck| typeck.type_dependent_def_id(*hir_id)) .and_then(|def_id| self.infcx.tcx.impl_of_method(def_id)) .map(|def_id| self.infcx.tcx.associated_items(def_id)) diff --git a/compiler/rustc_mir/src/borrow_check/universal_regions.rs b/compiler/rustc_mir/src/borrow_check/universal_regions.rs index c2ac1e289ce4e..584e3ee397ea6 100644 --- a/compiler/rustc_mir/src/borrow_check/universal_regions.rs +++ b/compiler/rustc_mir/src/borrow_check/universal_regions.rs @@ -18,7 +18,7 @@ use rustc_errors::DiagnosticBuilder; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::{BodyOwnerKind, HirId}; +use rustc_hir::{BodyOwnerKind, HirId, HirOwner}; use rustc_index::vec::{Idx, IndexVec}; use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin}; use rustc_middle::ty::fold::TypeFoldable; @@ -804,7 +804,7 @@ fn for_each_late_bound_region_defined_on<'tcx>( ) { if let Some((owner, late_bounds)) = tcx.is_late_bound_map(fn_def_id.expect_local()) { for &late_bound in late_bounds.iter() { - let hir_id = HirId { owner, local_id: late_bound }; + let hir_id = HirId { owner: HirOwner { def_id: owner }, local_id: late_bound }; let name = tcx.hir().name(hir_id); let region_def_id = tcx.hir().local_def_id(hir_id); let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion { diff --git a/compiler/rustc_mir/src/monomorphize/collector.rs b/compiler/rustc_mir/src/monomorphize/collector.rs index ef79f36b3b5aa..cfffaebade932 100644 --- a/compiler/rustc_mir/src/monomorphize/collector.rs +++ b/compiler/rustc_mir/src/monomorphize/collector.rs @@ -1145,7 +1145,7 @@ impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { } } hir::ItemKind::Fn(..) => { - self.push_if_root(item.def_id); + self.push_if_root(item.def_id.def_id); } } } @@ -1157,7 +1157,7 @@ impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { if let hir::ImplItemKind::Fn(hir::FnSig { .. }, _) = ii.kind { - self.push_if_root(ii.def_id); + self.push_if_root(ii.def_id.def_id); } } diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index f345d45d17808..35cff88db1041 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -13,10 +13,11 @@ use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_hir::itemlikevisit::ItemLikeVisitor; +use rustc_hir::HirOwner; use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::Session; -use rustc_span::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_span::symbol::{sym, Symbol}; struct DiagnosticItemCollector<'tcx> { @@ -48,8 +49,8 @@ impl<'tcx> DiagnosticItemCollector<'tcx> { DiagnosticItemCollector { tcx, items: Default::default() } } - fn observe_item(&mut self, def_id: LocalDefId) { - let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); + fn observe_item(&mut self, def_id: HirOwner) { + let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.def_id); let attrs = self.tcx.hir().attrs(hir_id); if let Some(name) = extract(&self.tcx.sess, attrs) { // insert into our table @@ -94,7 +95,11 @@ fn collect_item( /// Extract the first `rustc_diagnostic_item = "$name"` out of a list of attributes. fn extract(sess: &Session, attrs: &[ast::Attribute]) -> Option { attrs.iter().find_map(|attr| { - if sess.check_name(attr, sym::rustc_diagnostic_item) { attr.value_str() } else { None } + if sess.check_name(attr, sym::rustc_diagnostic_item) { + attr.value_str() + } else { + None + } }) } diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index ca6a7561f3e77..130b6c54cd031 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -30,7 +30,7 @@ struct EntryContext<'a, 'tcx> { impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> { fn visit_item(&mut self, item: &'tcx Item<'tcx>) { - let def_key = self.map.def_key(item.def_id); + let def_key = self.map.def_key(item.def_id.def_id); let at_root = def_key.parent == Some(CRATE_DEF_INDEX); find_item(item, self, at_root); } diff --git a/compiler/rustc_passes/src/hir_id_validator.rs b/compiler/rustc_passes/src/hir_id_validator.rs index 944a3097a61c3..e38fb95aa42e2 100644 --- a/compiler/rustc_passes/src/hir_id_validator.rs +++ b/compiler/rustc_passes/src/hir_id_validator.rs @@ -1,10 +1,10 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator}; use rustc_hir as hir; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX}; +use rustc_hir::def_id::CRATE_DEF_INDEX; use rustc_hir::intravisit; use rustc_hir::itemlikevisit::ItemLikeVisitor; -use rustc_hir::{HirId, ItemLocalId}; +use rustc_hir::{HirId, HirOwner, ItemLocalId}; use rustc_middle::hir::map::Map; use rustc_middle::ty::TyCtxt; @@ -29,7 +29,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) { struct HirIdValidator<'a, 'hir> { hir_map: Map<'hir>, - owner: Option, + owner: Option, hir_ids_seen: FxHashSet, errors: &'a Lock>, } @@ -82,7 +82,7 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { fn check)>(&mut self, hir_id: HirId, walk: F) { assert!(self.owner.is_none()); let owner = self.hir_map.local_def_id(hir_id); - self.owner = Some(owner); + self.owner = Some(HirOwner { def_id: owner }); walk(self); if owner.local_def_index == CRATE_DEF_INDEX { @@ -107,7 +107,10 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { let mut missing_items = Vec::with_capacity(missing.len()); for local_id in missing { - let hir_id = HirId { owner, local_id: ItemLocalId::from_u32(local_id) }; + let hir_id = HirId { + owner: HirOwner { def_id: owner }, + local_id: ItemLocalId::from_u32(local_id), + }; trace!("missing hir id {:#?}", hir_id); @@ -126,7 +129,7 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> { missing_items, self.hir_ids_seen .iter() - .map(|&local_id| HirId { owner, local_id }) + .map(|&local_id| HirId { owner: HirOwner { def_id: owner }, local_id }) .map(|h| format!("({:?} {})", h, self.hir_map.node_to_string(h))) .collect::>() ) @@ -150,8 +153,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> { format!( "HirIdValidator: The recorded owner of {} is {} instead of {}", self.hir_map.node_to_string(hir_id), - self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(), - self.hir_map.def_path(owner).to_string_no_crate_verbose() + self.hir_map.def_path(hir_id.owner.def_id).to_string_no_crate_verbose(), + self.hir_map.def_path(owner.def_id).to_string_no_crate_verbose() ) }); } diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 18c1d647060b1..0c30fa32be42c 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -28,7 +28,7 @@ impl ItemLikeVisitor<'tcx> for LayoutTest<'tcx> { | ItemKind::Union(..) => { for attr in self.tcx.get_attrs(item.def_id.to_def_id()).iter() { if self.tcx.sess.check_name(attr, sym::rustc_layout) { - self.dump_layout_of(item.def_id, item, attr); + self.dump_layout_of(item.def_id.def_id, item, attr); } } } diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index 0b3227abb5f8b..847e2a941265e 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -344,7 +344,7 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx if codegen_attrs.contains_extern_indicator() || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) { - self.worklist.push(item.def_id); + self.worklist.push(item.def_id.def_id); } // We need only trait impls here, not inherent impls, and only non-exported ones @@ -354,7 +354,7 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx if !self.access_levels.is_reachable(item.hir_id()) { // FIXME(#53488) remove `let` let tcx = self.tcx; - self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id)); + self.worklist.extend(items.iter().map(|ii_ref| ii_ref.id.def_id.def_id)); let trait_def_id = match trait_ref.path.res { Res::Def(DefKind::Trait, def_id) => def_id, diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index f41e0e0370680..f04291b381dc8 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -730,7 +730,7 @@ impl Visitor<'tcx> for Checker<'tcx> { return; } - let cnum = match self.tcx.extern_mod_stmt_cnum(item.def_id) { + let cnum = match self.tcx.extern_mod_stmt_cnum(item.def_id.def_id) { Some(cnum) => cnum, None => return, }; diff --git a/compiler/rustc_plugin_impl/src/build.rs b/compiler/rustc_plugin_impl/src/build.rs index b95c4a720195a..eddcf52b61896 100644 --- a/compiler/rustc_plugin_impl/src/build.rs +++ b/compiler/rustc_plugin_impl/src/build.rs @@ -18,7 +18,7 @@ impl<'v, 'tcx> ItemLikeVisitor<'v> for RegistrarFinder<'tcx> { if let hir::ItemKind::Fn(..) = item.kind { let attrs = self.tcx.hir().attrs(item.hir_id()); if self.tcx.sess.contains_name(attrs, sym::plugin_registrar) { - self.registrars.push((item.def_id, item.span)); + self.registrars.push((item.def_id.def_id, item.span)); } } } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index e64f12ef48f22..fb3959e4e19c7 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1343,7 +1343,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // Check types in item interfaces. fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - let orig_current_item = mem::replace(&mut self.current_item, item.def_id); + let orig_current_item = mem::replace(&mut self.current_item, item.def_id.def_id); let old_maybe_typeck_results = self.maybe_typeck_results.take(); intravisit::walk_item(self, item); self.maybe_typeck_results = old_maybe_typeck_results; diff --git a/compiler/rustc_query_impl/src/keys.rs b/compiler/rustc_query_impl/src/keys.rs index 27a0dc47682a5..31149fb5ad2aa 100644 --- a/compiler/rustc_query_impl/src/keys.rs +++ b/compiler/rustc_query_impl/src/keys.rs @@ -1,6 +1,7 @@ //! Defines the set of legal keys that can be used in queries. use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::hir_id::HirOwner; use rustc_middle::infer::canonical::Canonical; use rustc_middle::mir; use rustc_middle::ty::fast_reject::SimplifiedType; @@ -89,6 +90,15 @@ impl Key for LocalDefId { } } +impl Key for HirOwner { + fn query_crate(&self) -> CrateNum { + self.def_id.to_def_id().query_crate() + } + fn default_span(&self, tcx: TyCtxt<'_>) -> Span { + self.def_id.to_def_id().default_span(tcx) + } +} + impl Key for DefId { fn query_crate(&self) -> CrateNum { self.krate diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index c789aa2fa596e..01e54283c9735 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -68,7 +68,7 @@ impl QueryContext for QueryCtxt<'tcx> { if let Some(def_id) = dep_node.extract_def_id(**self) { let def_id = def_id.expect_local(); let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); - if def_id != hir_id.owner { + if def_id != hir_id.owner.def_id { // This `DefPath` does not have a // corresponding `DepNode` (e.g. a // struct field), and the ` DefPath` diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index efa5d7e7b1139..b9eee5b1bf3dd 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -13,7 +13,7 @@ use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefIdMap, LocalDefId}; -use rustc_hir::hir_id::ItemLocalId; +use rustc_hir::hir_id::{HirOwner, ItemLocalId}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{GenericArg, GenericParam, LifetimeName, Node, ParamName, QPath}; use rustc_hir::{GenericParamKind, HirIdMap, HirIdSet, LifetimeParamKind}; @@ -473,15 +473,15 @@ fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetime let mut rl = ResolveLifetimes::default(); for (hir_id, v) in named_region_map.defs { - let map = rl.defs.entry(hir_id.owner).or_default(); + let map = rl.defs.entry(hir_id.owner.def_id).or_default(); map.insert(hir_id.local_id, v); } for hir_id in named_region_map.late_bound { - let map = rl.late_bound.entry(hir_id.owner).or_default(); + let map = rl.late_bound.entry(hir_id.owner.def_id).or_default(); map.insert(hir_id.local_id); } for (hir_id, v) in named_region_map.late_bound_vars { - let map = rl.late_bound_vars.entry(hir_id.owner).or_default(); + let map = rl.late_bound_vars.entry(hir_id.owner.def_id).or_default(); map.insert(hir_id.local_id, v); } @@ -502,7 +502,7 @@ fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetime fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes { let item_id = item_for(tcx, def_id); if item_id == def_id { - let item = tcx.hir().item(hir::ItemId { def_id: item_id }); + let item = tcx.hir().item(hir::ItemId { def_id: HirOwner { def_id: item_id } }); match item.kind { hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id), _ => tcx.resolve_lifetimes(item_id), @@ -517,7 +517,7 @@ fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId { let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id); match tcx.hir().find(hir_id) { Some(Node::Item(item)) => { - return item.def_id; + return item.def_id.def_id; } _ => {} } @@ -533,7 +533,7 @@ fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId { } } }; - item + item.def_id } fn is_late_bound_map<'tcx>( @@ -760,22 +760,31 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // their owner, we can keep going until we find the Item that owns that. We then // conservatively add all resolved lifetimes. Otherwise we run into problems in // cases like `type Foo<'a> = impl Bar`. - for (_hir_id, node) in - self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id)) + for (_hir_id, node) in self + .tcx + .hir() + .parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id.def_id)) { match node { hir::Node::Item(parent_item) => { - let resolved_lifetimes: &ResolveLifetimes = - self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id)); + let resolved_lifetimes: &ResolveLifetimes = self + .tcx + .resolve_lifetimes(item_for(self.tcx, parent_item.def_id.def_id)); // We need to add *all* deps, since opaque tys may want them from *us* for (&owner, defs) in resolved_lifetimes.defs.iter() { defs.iter().for_each(|(&local_id, region)| { - self.map.defs.insert(hir::HirId { owner, local_id }, *region); + self.map.defs.insert( + hir::HirId { owner: HirOwner { def_id: owner }, local_id }, + *region, + ); }); } for (&owner, late_bound) in resolved_lifetimes.late_bound.iter() { late_bound.iter().for_each(|&local_id| { - self.map.late_bound.insert(hir::HirId { owner, local_id }); + self.map.late_bound.insert(hir::HirId { + owner: HirOwner { def_id: owner }, + local_id, + }); }); } for (&owner, late_bound_vars) in @@ -783,7 +792,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { { late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| { self.map.late_bound_vars.insert( - hir::HirId { owner, local_id }, + hir::HirId { owner: HirOwner { def_id: owner }, local_id }, late_bound_vars.clone(), ); }); @@ -1295,7 +1304,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // We add lifetime scope information for `Ident`s in associated type bindings and use // the `HirId` of the type binding as the key in `LifetimeMap` let lifetime_scope = get_lifetime_scopes_for_path(scope); - let map = scope_for_path.entry(type_binding.hir_id.owner).or_default(); + let map = scope_for_path.entry(type_binding.hir_id.owner.def_id).or_default(); map.insert(type_binding.hir_id.local_id, lifetime_scope); } hir::intravisit::walk_assoc_type_binding(self, type_binding); @@ -1316,7 +1325,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // processed using `visit_segment_args`. let lifetime_scope = get_lifetime_scopes_for_path(scope); if let Some(hir_id) = segment.hir_id { - let map = scope_for_path.entry(hir_id.owner).or_default(); + let map = scope_for_path.entry(hir_id.owner.def_id).or_default(); map.insert(hir_id.local_id, lifetime_scope); } } @@ -1328,7 +1337,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { if let Some(scope_for_path) = self.map.scope_for_path.as_mut() { let lifetime_scope = get_lifetime_scopes_for_path(scope); if let Some(hir_id) = path_segment.hir_id { - let map = scope_for_path.entry(hir_id.owner).or_default(); + let map = scope_for_path.entry(hir_id.owner.def_id).or_default(); map.insert(hir_id.local_id, lifetime_scope); } } diff --git a/compiler/rustc_save_analysis/src/dump_visitor.rs b/compiler/rustc_save_analysis/src/dump_visitor.rs index 54b6a12158581..0127a96c4f9d1 100644 --- a/compiler/rustc_save_analysis/src/dump_visitor.rs +++ b/compiler/rustc_save_analysis/src/dump_visitor.rs @@ -364,7 +364,7 @@ impl<'tcx> DumpVisitor<'tcx> { body: hir::BodyId, ) { let map = &self.tcx.hir(); - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { let body = map.body(body); if let Some(fn_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(fn_data, DefData, item.span); @@ -392,7 +392,7 @@ impl<'tcx> DumpVisitor<'tcx> { typ: &'tcx hir::Ty<'tcx>, expr: &'tcx hir::Expr<'tcx>, ) { - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { if let Some(var_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(var_data, DefData, item.span); v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id()), var_data); @@ -507,7 +507,7 @@ impl<'tcx> DumpVisitor<'tcx> { ); } - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { for field in def.fields() { v.process_struct_field_def(field, item.hir_id()); v.visit_ty(&field.ty); @@ -629,7 +629,7 @@ impl<'tcx> DumpVisitor<'tcx> { } let map = &self.tcx.hir(); - self.nest_typeck_results(item.def_id, |v| { + self.nest_typeck_results(item.def_id.def_id, |v| { v.visit_ty(&impl_.self_ty); if let Some(trait_ref) = &impl_.of_trait { v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path)); @@ -1171,7 +1171,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::ItemKind::Use(path, hir::UseKind::Glob) => { // Make a comma-separated list of names of imported modules. - let names = self.tcx.names_imported_by_glob_use(item.def_id); + let names = self.tcx.names_imported_by_glob_use(item.def_id.def_id); let names: Vec<_> = names.iter().map(|n| n.to_string()).collect(); // Otherwise it's a span with wrong macro expansion info, which @@ -1335,7 +1335,7 @@ impl<'tcx> Visitor<'tcx> for DumpVisitor<'tcx> { } hir::TyKind::OpaqueDef(item_id, _) => { let item = self.tcx.hir().item(item_id); - self.nest_typeck_results(item_id.def_id, |v| v.visit_item(item)); + self.nest_typeck_results(item_id.def_id.def_id, |v| v.visit_item(item)); } _ => intravisit::walk_ty(self, t), } diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index 2bba6500d89cb..994f4a71d6126 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -626,7 +626,7 @@ impl<'tcx> SaveContext<'tcx> { hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => { // #75962: `self.typeck_results` may be different from the `hir_id`'s result. if self.tcx.has_typeck_results(hir_id.owner.to_def_id()) { - self.tcx.typeck(hir_id.owner).qpath_res(qpath, hir_id) + self.tcx.typeck(hir_id.owner.def_id).qpath_res(qpath, hir_id) } else { Res::Err } @@ -1070,7 +1070,7 @@ fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_>) -> rls_data::Id { // crate (very unlikely to actually happen). rls_data::Id { krate: LOCAL_CRATE.as_u32(), - index: id.owner.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(), + index: id.owner.def_id.local_def_index.as_u32() | id.local_id.as_u32().reverse_bits(), } }) } diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index bfe9c4d6de3de..339c400cfcb21 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -5,7 +5,7 @@ //! paths etc in all kinds of annoying scenarios. use rustc_hir as hir; -use rustc_hir::def_id::LocalDefId; +use rustc_hir::hir_id::HirOwner; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{subst::InternalSubsts, Instance, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; @@ -32,11 +32,11 @@ struct SymbolNamesTest<'tcx> { } impl SymbolNamesTest<'tcx> { - fn process_attrs(&mut self, def_id: LocalDefId) { + fn process_attrs(&mut self, def_id: HirOwner) { let tcx = self.tcx; for attr in tcx.get_attrs(def_id.to_def_id()).iter() { if tcx.sess.check_name(attr, SYMBOL_NAME) { - let def_id = def_id.to_def_id(); + let def_id = def_id.def_id.to_def_id(); let instance = Instance::new( def_id, tcx.erase_regions(InternalSubsts::identity_for_item(tcx, def_id)), diff --git a/compiler/rustc_typeck/src/check/_match.rs b/compiler/rustc_typeck/src/check/_match.rs index d056f2c90f988..23f9d80a944d6 100644 --- a/compiler/rustc_typeck/src/check/_match.rs +++ b/compiler/rustc_typeck/src/check/_match.rs @@ -598,8 +598,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (Expectation::ExpectHasType(expected), Some((id, ty))) if self.in_tail_expr && self.can_coerce(outer_ty, expected) => { - let impl_trait_ret_ty = - self.infcx.instantiate_opaque_types(id, self.body_id, self.param_env, ty, span); + let impl_trait_ret_ty = self.infcx.instantiate_opaque_types( + id.def_id, + self.body_id, + self.param_env, + ty, + span, + ); let mut suggest_box = !impl_trait_ret_ty.obligations.is_empty(); for o in impl_trait_ret_ty.obligations { match o.predicate.kind().skip_binder() { diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index 92d7ea2600300..a4a70716d7043 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -755,15 +755,15 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { match it.kind { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { - tcx.ensure().typeck(it.def_id); - maybe_check_static_with_link_section(tcx, it.def_id, it.span); - check_static_inhabited(tcx, it.def_id, it.span); + tcx.ensure().typeck(it.def_id.def_id); + maybe_check_static_with_link_section(tcx, it.def_id.def_id, it.span); + check_static_inhabited(tcx, it.def_id.def_id, it.span); } hir::ItemKind::Const(..) => { - tcx.ensure().typeck(it.def_id); + tcx.ensure().typeck(it.def_id.def_id); } hir::ItemKind::Enum(ref enum_definition, _) => { - check_enum(tcx, it.span, &enum_definition.variants, it.def_id); + check_enum(tcx, it.span, &enum_definition.variants, it.def_id.def_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl(ref impl_) => { @@ -772,7 +772,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { check_impl_items_against_trait( tcx, it.span, - it.def_id, + it.def_id.def_id, impl_trait_ref, &impl_.items, ); @@ -807,10 +807,10 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { } } hir::ItemKind::Struct(..) => { - check_struct(tcx, it.def_id, it.span); + check_struct(tcx, it.def_id.def_id, it.span); } hir::ItemKind::Union(..) => { - check_union(tcx, it.def_id, it.span); + check_union(tcx, it.def_id.def_id, it.span); } hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting @@ -819,7 +819,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { // See https://github.com/rust-lang/rust/issues/75100 if !tcx.sess.opts.actually_rustdoc { let substs = InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id()); - check_opaque(tcx, it.def_id, substs, it.span, &origin); + check_opaque(tcx, it.def_id.def_id, substs, it.span, &origin); } } hir::ItemKind::TyAlias(..) => { @@ -880,7 +880,7 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { require_c_abi_if_c_variadic(tcx, fn_decl, abi, item.span); } hir::ForeignItemKind::Static(..) => { - check_static_inhabited(tcx, def_id, item.span); + check_static_inhabited(tcx, def_id.def_id, item.span); } _ => {} } diff --git a/compiler/rustc_typeck/src/check/compare_method.rs b/compiler/rustc_typeck/src/check/compare_method.rs index 60ca562f99200..337aceea448aa 100644 --- a/compiler/rustc_typeck/src/check/compare_method.rs +++ b/compiler/rustc_typeck/src/check/compare_method.rs @@ -2,7 +2,7 @@ use crate::errors::LifetimesOrBoundsMismatchOnTrait; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit; +use rustc_hir::{intravisit, HirOwner}; use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind}; use rustc_infer::infer::{self, InferOk, TyCtxtInferExt}; use rustc_infer::traits::util; @@ -828,10 +828,14 @@ fn compare_synthetic_generics<'tcx>( // as another generic argument let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?; let trait_m = trait_m.def_id.as_local()?; - let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m }); + let trait_m = tcx + .hir() + .trait_item(hir::TraitItemId { def_id: HirOwner { def_id: trait_m } }); let impl_m = impl_m.def_id.as_local()?; - let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m }); + let impl_m = tcx + .hir() + .impl_item(hir::ImplItemId { def_id: HirOwner { def_id: impl_m } }); // in case there are no generics, take the spot between the function name // and the opening paren of the argument list @@ -865,7 +869,9 @@ fn compare_synthetic_generics<'tcx>( err.span_label(impl_span, "expected `impl Trait`, found generic parameter"); (|| { let impl_m = impl_m.def_id.as_local()?; - let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m }); + let impl_m = tcx + .hir() + .impl_item(hir::ImplItemId { def_id: HirOwner { def_id: impl_m } }); let input_tys = match impl_m.kind { hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs, _ => unreachable!(), diff --git a/compiler/rustc_typeck/src/check/wfcheck.rs b/compiler/rustc_typeck/src/check/wfcheck.rs index 7436edccf84bb..733094b69b075 100644 --- a/compiler/rustc_typeck/src/check/wfcheck.rs +++ b/compiler/rustc_typeck/src/check/wfcheck.rs @@ -224,18 +224,18 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem let mut trait_should_be_self = vec![]; match &item.kind { hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty)) - if could_be_self(trait_def_id, ty) => + if could_be_self(trait_def_id.def_id, ty) => { trait_should_be_self.push(ty.span) } hir::TraitItemKind::Fn(sig, _) => { for ty in sig.decl.inputs { - if could_be_self(trait_def_id, ty) { + if could_be_self(trait_def_id.def_id, ty) { trait_should_be_self.push(ty.span); } } match sig.decl.output { - hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => { + hir::FnRetTy::Return(ty) if could_be_self(trait_def_id.def_id, ty) => { trait_should_be_self.push(ty.span); } _ => {} @@ -1385,19 +1385,19 @@ impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> { fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) { debug!("visit_item: {:?}", i); - self.tcx.ensure().check_item_well_formed(i.def_id); + self.tcx.ensure().check_item_well_formed(i.def_id.def_id); hir_visit::walk_item(self, i); } fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { debug!("visit_trait_item: {:?}", trait_item); - self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id); + self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id.def_id); hir_visit::walk_trait_item(self, trait_item); } fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { debug!("visit_impl_item: {:?}", impl_item); - self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id); + self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id.def_id); hir_visit::walk_impl_item(self, impl_item); } diff --git a/compiler/rustc_typeck/src/check_unused.rs b/compiler/rustc_typeck/src/check_unused.rs index 836bed2a15635..e4282da25b271 100644 --- a/compiler/rustc_typeck/src/check_unused.rs +++ b/compiler/rustc_typeck/src/check_unused.rs @@ -46,11 +46,11 @@ struct CheckVisitor<'tcx> { impl CheckVisitor<'tcx> { fn check_import(&self, item_id: hir::ItemId, span: Span) { - if !self.tcx.maybe_unused_trait_import(item_id.def_id) { + if !self.tcx.maybe_unused_trait_import(item_id.def_id.def_id) { return; } - if self.used_trait_imports.contains(&item_id.def_id) { + if self.used_trait_imports.contains(&item_id.def_id.def_id) { return; } diff --git a/compiler/rustc_typeck/src/coherence/inherent_impls.rs b/compiler/rustc_typeck/src/coherence/inherent_impls.rs index 51698437a305b..ef192197562b7 100644 --- a/compiler/rustc_typeck/src/coherence/inherent_impls.rs +++ b/compiler/rustc_typeck/src/coherence/inherent_impls.rs @@ -62,7 +62,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Bool => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.bool_impl(), None, "bool", @@ -73,7 +73,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Char => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.char_impl(), None, "char", @@ -84,7 +84,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Str => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.str_impl(), lang_items.str_alloc_impl(), "str", @@ -95,7 +95,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Slice(slice_item) if slice_item == self.tcx.types.u8 => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.slice_u8_impl(), lang_items.slice_u8_alloc_impl(), "slice_u8", @@ -106,7 +106,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Slice(_) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.slice_impl(), lang_items.slice_alloc_impl(), "slice", @@ -117,7 +117,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Array(_, _) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.array_impl(), None, "array", @@ -130,7 +130,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { if matches!(inner.kind(), ty::Slice(_)) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.const_slice_ptr_impl(), None, "const_slice_ptr", @@ -143,7 +143,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { if matches!(inner.kind(), ty::Slice(_)) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.mut_slice_ptr_impl(), None, "mut_slice_ptr", @@ -154,7 +154,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::Mutability::Not }) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.const_ptr_impl(), None, "const_ptr", @@ -165,7 +165,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::Mutability::Mut }) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.mut_ptr_impl(), None, "mut_ptr", @@ -176,7 +176,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::I8) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.i8_impl(), None, "i8", @@ -187,7 +187,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::I16) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.i16_impl(), None, "i16", @@ -198,7 +198,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::I32) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.i32_impl(), None, "i32", @@ -209,7 +209,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::I64) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.i64_impl(), None, "i64", @@ -220,7 +220,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::I128) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.i128_impl(), None, "i128", @@ -231,7 +231,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Int(ty::IntTy::Isize) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.isize_impl(), None, "isize", @@ -242,7 +242,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::U8) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.u8_impl(), None, "u8", @@ -253,7 +253,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::U16) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.u16_impl(), None, "u16", @@ -264,7 +264,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::U32) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.u32_impl(), None, "u32", @@ -275,7 +275,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::U64) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.u64_impl(), None, "u64", @@ -286,7 +286,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::U128) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.u128_impl(), None, "u128", @@ -297,7 +297,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Uint(ty::UintTy::Usize) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.usize_impl(), None, "usize", @@ -308,7 +308,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Float(ty::FloatTy::F32) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.f32_impl(), lang_items.f32_runtime_impl(), "f32", @@ -319,7 +319,7 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> { } ty::Float(ty::FloatTy::F64) => { self.check_primitive_impl( - item.def_id, + item.def_id.def_id, lang_items.f64_impl(), lang_items.f64_runtime_impl(), "f64", diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index 5197b620f90ba..ca4091c8f943a 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -619,7 +619,7 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> { debug!("find_existential_constraints: visiting {:?}", it); // The opaque type itself or its children are not within its reveal scope. if it.def_id.to_def_id() != self.def_id { - self.check(it.def_id); + self.check(it.def_id.def_id); intravisit::walk_item(self, it); } } @@ -627,13 +627,13 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> { debug!("find_existential_constraints: visiting {:?}", it); // The opaque type itself or its children are not within its reveal scope. if it.def_id.to_def_id() != self.def_id { - self.check(it.def_id); + self.check(it.def_id.def_id); intravisit::walk_impl_item(self, it); } } fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) { debug!("find_existential_constraints: visiting {:?}", it); - self.check(it.def_id); + self.check(it.def_id.def_id); intravisit::walk_trait_item(self, it); } } diff --git a/compiler/rustc_typeck/src/impl_wf_check.rs b/compiler/rustc_typeck/src/impl_wf_check.rs index 1240946860573..770ae5a5ba7d7 100644 --- a/compiler/rustc_typeck/src/impl_wf_check.rs +++ b/compiler/rustc_typeck/src/impl_wf_check.rs @@ -81,10 +81,10 @@ struct ImplWfCheck<'tcx> { impl ItemLikeVisitor<'tcx> for ImplWfCheck<'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { if let hir::ItemKind::Impl(ref impl_) = item.kind { - enforce_impl_params_are_constrained(self.tcx, item.def_id, impl_.items); + enforce_impl_params_are_constrained(self.tcx, item.def_id.def_id, impl_.items); enforce_impl_items_are_distinct(self.tcx, impl_.items); if self.min_specialization { - check_min_specialization(self.tcx, item.def_id.to_def_id(), item.span); + check_min_specialization(self.tcx, item.def_id.def_id.to_def_id(), item.span); } } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 231f13adeb68c..4d638ffcbd859 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1975,7 +1975,7 @@ fn clean_extern_crate( cx: &mut DocContext<'_>, ) -> Vec { // this is the ID of the `extern crate` statement - let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE); + let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id.def_id).unwrap_or(LOCAL_CRATE); // this is the ID of the crate itself let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX }; let attrs = cx.tcx.hir().attrs(krate.hir_id()); From b976ad0969bcb795f7322f62f159a46215dd72c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sun, 23 May 2021 12:50:01 +0200 Subject: [PATCH 2/8] hir atribute map to HirOwner --- compiler/rustc_hir/src/hir.rs | 3 --- compiler/rustc_hir/src/hir_id.rs | 1 - compiler/rustc_middle/src/hir/map/mod.rs | 4 ++-- compiler/rustc_middle/src/hir/mod.rs | 20 ++++++++------------ compiler/rustc_middle/src/query/mod.rs | 2 +- 5 files changed, 11 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 8a40aec3ae10d..5107f17ccd544 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2055,7 +2055,6 @@ pub enum TraitItemKind<'hir> { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. -/// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] pub struct ImplItemId { pub def_id: HirOwner, @@ -2654,7 +2653,6 @@ impl VariantData<'hir> { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. -/// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)] pub struct ItemId { pub def_id: HirOwner, @@ -2860,7 +2858,6 @@ pub enum AssocItemKind { // The bodies for items are stored "out of line", in a separate // hashmap in the `Crate`. Here we just record the hir-id of the item // so it can fetched later. -// TODO review #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)] pub struct ForeignItemId { pub def_id: HirOwner, diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index d13efe7cd9b28..c138238655a10 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -3,7 +3,6 @@ use rustc_index::vec::IndexVec; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fmt; -/// TODO #[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)] pub struct HirOwner { pub def_id: LocalDefId, diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index dad2f153d4717..a2edace2877a0 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -814,7 +814,7 @@ impl<'hir> Map<'hir> { /// Given a node ID, gets a list of attributes associated with the AST /// corresponding to the node-ID. pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { - self.tcx.hir_attrs(id.owner.def_id).get(id.local_id) + self.tcx.hir_attrs(id.owner).get(id.local_id) } /// Gets the span of the definition of the specified HIR node. @@ -953,7 +953,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { let def_path_hash = tcx.definitions.def_path_hash(def_id.def_id); let mut hasher = StableHasher::new(); hod.with_bodies.as_ref()?.hash_stable(&mut hcx, &mut hasher); - AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id.def_id } + AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id } .hash_stable(&mut hcx, &mut hasher); Some((def_path_hash, hasher.finish())) }) diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 8264a67995157..5a704d7ebae67 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -69,7 +69,7 @@ impl<'a, 'tcx> HashStable> for OwnerNodes<'tcx> { #[derive(Copy, Clone)] pub struct AttributeMap<'tcx> { map: &'tcx BTreeMap, - prefix: LocalDefId, + prefix: HirOwner, } impl<'a, 'tcx> HashStable> for AttributeMap<'tcx> { @@ -95,21 +95,17 @@ impl<'tcx> std::fmt::Debug for AttributeMap<'tcx> { impl<'tcx> AttributeMap<'tcx> { fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] { - self.map - .get(&HirId { owner: HirOwner { def_id: self.prefix }, local_id: id }) - .copied() - .unwrap_or(&[]) + self.map.get(&HirId { owner: self.prefix, local_id: id }).copied().unwrap_or(&[]) } fn range(&self) -> std::collections::btree_map::Range<'_, rustc_hir::HirId, &[Attribute]> { let local_zero = ItemLocalId::from_u32(0); - let range = HirId { owner: HirOwner { def_id: self.prefix }, local_id: local_zero } - ..HirId { - owner: HirOwner { - def_id: LocalDefId { local_def_index: self.prefix.local_def_index + 1 }, - }, - local_id: local_zero, - }; + let range = HirId { owner: self.prefix, local_id: local_zero }..HirId { + owner: HirOwner { + def_id: LocalDefId { local_def_index: self.prefix.def_id.local_def_index + 1 }, + }, + local_id: local_zero, + }; self.map.range(range) } } diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 7e16d41516489..7c5e7a2c68ccf 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -74,7 +74,7 @@ rustc_queries! { /// /// This can be conveniently accessed by methods on `tcx.hir()`. /// Avoid calling this query directly. - query hir_attrs(key: LocalDefId) -> rustc_middle::hir::AttributeMap<'tcx> { + query hir_attrs(key: HirOwner) -> rustc_middle::hir::AttributeMap<'tcx> { eval_always desc { |tcx| "HIR owner attributes in `{}`", tcx.def_path_str(key.to_def_id()) } } From 8ea87bd57817d398f1ddb6d8a57170135cc00678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sun, 23 May 2021 12:52:35 +0200 Subject: [PATCH 3/8] simplyfiy local_def_id_to_hir_id --- compiler/rustc_hir/src/hir_id.rs | 4 ++++ compiler/rustc_incremental/src/persist/dirty_clean.rs | 2 +- compiler/rustc_infer/src/infer/error_reporting/mod.rs | 2 +- compiler/rustc_passes/src/diagnostic_items.rs | 2 +- compiler/rustc_resolve/src/late/lifetimes.rs | 8 ++------ 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index c138238655a10..84e202a24a2db 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -16,6 +16,10 @@ impl HirOwner { pub fn to_def_id(&self) -> DefId { self.def_id.to_def_id() } + + pub fn to_hir_id(self) -> HirId { + HirId { owner: self, local_id: ItemLocalId::from_u32(0) } + } } impl rustc_index::vec::Idx for HirOwner { diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 51c16fe307c36..dc5604a7370fa 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -239,7 +239,7 @@ impl DirtyCleanVisitor<'tcx> { /// Return all DepNode labels that should be asserted for this item. /// index=0 is the "name" used for error messages fn auto_labels(&mut self, item_id: HirOwner, attr: &Attribute) -> (&'static str, Labels) { - let hir_id = self.tcx.hir().local_def_id_to_hir_id(item_id.def_id); + let hir_id = item_id.to_hir_id(); let node = self.tcx.hir().get(hir_id); let (name, labels) = match node { HirNode::Item(item) => { diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 46e976fc039ca..5a1581bb89bbb 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2052,7 +2052,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { .in_progress_typeck_results .map(|typeck_results| typeck_results.borrow().hir_owner) .map(|owner| { - let hir_id = hir.local_def_id_to_hir_id(owner.def_id); + let hir_id = owner.to_hir_id(); let parent_id = hir.get_parent_item(hir_id); ( // Parent item could be a `mod`, so we check the HIR before calling: diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index 35cff88db1041..d72c28f32a694 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -50,7 +50,7 @@ impl<'tcx> DiagnosticItemCollector<'tcx> { } fn observe_item(&mut self, def_id: HirOwner) { - let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.def_id); + let hir_id = def_id.to_hir_id(); let attrs = self.tcx.hir().attrs(hir_id); if let Some(name) = extract(&self.tcx.sess, attrs) { // insert into our table diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index b9eee5b1bf3dd..05c248a77ef08 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -502,7 +502,7 @@ fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetime fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes { let item_id = item_for(tcx, def_id); if item_id == def_id { - let item = tcx.hir().item(hir::ItemId { def_id: HirOwner { def_id: item_id } }); + let item = tcx.hir().item(hir::ItemId { def_id: HirOwner { def_id } }); match item.kind { hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id), _ => tcx.resolve_lifetimes(item_id), @@ -760,11 +760,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // their owner, we can keep going until we find the Item that owns that. We then // conservatively add all resolved lifetimes. Otherwise we run into problems in // cases like `type Foo<'a> = impl Bar`. - for (_hir_id, node) in self - .tcx - .hir() - .parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id.def_id)) - { + for (_hir_id, node) in self.tcx.hir().parent_iter(item.def_id.to_hir_id()) { match node { hir::Node::Item(parent_item) => { let resolved_lifetimes: &ResolveLifetimes = self From 9f45b24344ad1e36cae263c902ed1bb3c1732f17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sun, 23 May 2021 16:47:11 +0200 Subject: [PATCH 4/8] fix clippy --- src/tools/clippy/clippy_lints/src/doc.rs | 105 ++++++------ .../clippy_lints/src/fallible_impl_from.rs | 8 +- .../clippy_lints/src/functions/must_use.rs | 40 +++-- .../clippy_lints/src/loops/mut_range_bound.rs | 21 +-- .../clippy/clippy_lints/src/missing_doc.rs | 17 +- .../clippy_lints/src/needless_borrow.rs | 14 +- .../clippy_lints/src/transmute/utils.rs | 34 ++-- .../clippy_lints/src/unwrap_in_result.rs | 8 +- src/tools/clippy/clippy_lints/src/use_self.rs | 118 +++++++------- .../clippy_lints/src/utils/inspector.rs | 150 +++++++++--------- .../clippy_lints/src/wildcard_imports.rs | 7 +- src/tools/clippy/clippy_utils/src/usage.rs | 43 ++--- 12 files changed, 293 insertions(+), 272 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index e67ec4e06c547..32af87e7b3492 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -1,6 +1,8 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_note}; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; -use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty}; +use clippy_utils::{ + is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty, +}; use if_chain::if_chain; use itertools::Itertools; use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind}; @@ -195,10 +197,7 @@ pub struct DocMarkdown { impl DocMarkdown { pub fn new(valid_idents: FxHashSet) -> Self { - Self { - valid_idents, - in_trait_impl: false, - } + Self { valid_idents, in_trait_impl: false } } } @@ -217,11 +216,13 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, attrs); match item.kind { hir::ItemKind::Fn(ref sig, _, body_id) => { - if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) { + if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) + || in_external_macro(cx.tcx.sess, item.span)) + { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(&body.value); @@ -235,11 +236,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { fpu.panic_span, ); } - }, + } hir::ItemKind::Impl(ref impl_) => { self.in_trait_impl = impl_.of_trait.is_some(); - }, - _ => {}, + } + _ => {} } } @@ -269,7 +270,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, - typeck_results: cx.tcx.typeck(item.def_id), + typeck_results: cx.tcx.typeck(item.def_id.def_id), panic_span: None, }; fpu.visit_expr(&body.value); @@ -299,12 +300,7 @@ fn lint_for_missing_headers<'tcx>( return; // Private functions do not require doc comments } if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe { - span_lint( - cx, - MISSING_SAFETY_DOC, - span, - "unsafe function's docs miss `# Safety` section", - ); + span_lint(cx, MISSING_SAFETY_DOC, span, "unsafe function's docs miss `# Safety` section"); } if !headers.panics && panic_span.is_some() { span_lint_and_note( @@ -357,7 +353,11 @@ fn lint_for_missing_headers<'tcx>( /// the spans but this function is inspired from the later. #[allow(clippy::cast_possible_truncation)] #[must_use] -pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) { +pub fn strip_doc_comment_decoration( + doc: &str, + comment_kind: CommentKind, + span: Span, +) -> (String, Vec<(usize, Span)>) { // one-line comments lose their prefix if comment_kind == CommentKind::Line { let mut doc = doc.to_owned(); @@ -405,23 +405,24 @@ struct DocHeaders { panics: bool, } -fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet, attrs: &'a [Attribute]) -> DocHeaders { +fn check_attrs<'a>( + cx: &LateContext<'_>, + valid_idents: &FxHashSet, + attrs: &'a [Attribute], +) -> DocHeaders { let mut doc = String::new(); let mut spans = vec![]; for attr in attrs { if let AttrKind::DocComment(comment_kind, comment) = attr.kind { - let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span); + let (comment, current_spans) = + strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span); spans.extend_from_slice(¤t_spans); doc.push_str(&comment); } else if attr.has_name(sym::doc) { // ignore mix of sugared and non-sugared doc // don't trigger the safety or errors check - return DocHeaders { - safety: true, - errors: true, - panics: true, - }; + return DocHeaders { safety: true, errors: true, panics: true }; } } @@ -433,11 +434,7 @@ fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet, attrs } if doc.is_empty() { - return DocHeaders { - safety: false, - errors: false, - panics: false, - }; + return DocHeaders { safety: false, errors: false, panics: false }; } let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter(); @@ -453,7 +450,7 @@ fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet, attrs let mut previous = previous.to_string(); previous.push_str(¤t); Ok((Text(previous.into()), previous_range)) - }, + } (previous, current) => Err(((previous, previous_range), (current, current_range))), } }); @@ -475,11 +472,7 @@ fn check_doc<'a, Events: Iterator, Range, Range { in_code = false; is_rust = false; - }, + } Start(Link(_, url, _)) => in_link = Some(url), End(Link(..)) => in_link = None, Start(Heading(_)) => in_heading = true, @@ -541,7 +534,7 @@ fn check_doc<'a, Events: Iterator, Range, text: &str, edition: Edition, span: Span) { let filename = FileName::anon_source_code(code); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false); + let emitter = + EmitterWriter::new(box io::sink(), None, false, false, false, None, false); let handler = Handler::with_emitter(false, None, box emitter); let sess = ParseSess::with_span_handler(handler, sm); - let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) { - Ok(p) => p, - Err(errs) => { - for mut err in errs { - err.cancel(); + let mut parser = + match maybe_new_parser_from_source_str(&sess, filename, code.into()) { + Ok(p) => p, + Err(errs) => { + for mut err in errs { + err.cancel(); + } + return false; } - return false; - }, - }; + }; let mut relevant_main_found = false; loop { @@ -578,7 +573,9 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) { | ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) => return false, // We found a main function ... - ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => { + ItemKind::Fn(box FnKind(_, sig, _, Some(block))) + if item.ident.name == sym::main => + { let is_async = matches!(sig.header.asyncness, Async::Yes { .. }); let returns_nothing = match &sig.decl.output { FnRetTy::Default(..) => true, @@ -593,16 +590,16 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) { // This main function should not be linted, we're done return false; } - }, + } // Another function was found; this case is ignored too ItemKind::Fn(..) => return false, - _ => {}, + _ => {} }, Ok(None) => break, Err(mut e) => { e.cancel(); return false; - }, + } } } @@ -722,7 +719,9 @@ impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { } // check for `assert_eq` or `assert_ne` - if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() { + if is_expn_of(expr.span, "assert_eq").is_some() + || is_expn_of(expr.span, "assert_ne").is_some() + { self.panic_span = Some(expr.span); } diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 2937fcb9ca0f3..99d2fbe0ff5cf 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -65,7 +65,11 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { } } -fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) { +fn lint_impl_body<'tcx>( + cx: &LateContext<'tcx>, + impl_span: Span, + impl_items: &[hir::ImplItemRef<'_>], +) { use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath}; @@ -120,7 +124,7 @@ fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[h let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.id.def_id), + typeck_results: cx.tcx.typeck(impl_item.id.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(&body.value); diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index 20288427b4a74..a5168436be7e5 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -27,7 +27,10 @@ pub(super) fn check_item(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); return; - } else if is_public && !is_proc_macro(cx.sess(), attrs) && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) { + } else if is_public + && !is_proc_macro(cx.sess(), attrs) + && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) + { check_must_use_candidate( cx, sig.decl, @@ -49,7 +52,10 @@ pub(super) fn check_impl_item(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem< let attr = must_use_attr(attrs); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); - } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.hir_id()).is_none() { + } else if is_public + && !is_proc_macro(cx.sess(), attrs) + && trait_ref_of_method(cx, item.hir_id()).is_none() + { check_must_use_candidate( cx, sig.decl, @@ -178,7 +184,7 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) return false; // ignore `_` patterns } if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) { - is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys) + is_mutable_ty(cx, cx.tcx.typeck(pat.hir_id.owner.def_id).pat_ty(pat), pat.span, tys) } else { false } @@ -186,7 +192,12 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]]; -fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut DefIdSet) -> bool { +fn is_mutable_ty<'tcx>( + cx: &LateContext<'tcx>, + ty: Ty<'tcx>, + span: Span, + tys: &mut DefIdSet, +) -> bool { match *ty.kind() { // primitive types are never mutable ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false, @@ -194,12 +205,12 @@ fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &m tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env) || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path)) && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)) - }, + } ty::Tuple(substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)), ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys), ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => { mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys) - }, + } // calling something constitutes a side effect, so return true on all callables // also never calls need not be used, so return true for them, too _ => true, @@ -227,7 +238,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id()) && is_mutable_ty( self.cx, - self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg), + self.cx.tcx.typeck(arg.hir_id.owner.def_id).expr_ty(arg), arg.span, &mut tys, ) @@ -238,11 +249,13 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { } tys.clear(); } - }, - Assign(target, ..) | AssignOp(_, target, _) | AddrOf(_, hir::Mutability::Mut, target) => { + } + Assign(target, ..) + | AssignOp(_, target, _) + | AddrOf(_, hir::Mutability::Mut, target) => { self.mutates_static |= is_mutated_static(target) - }, - _ => {}, + } + _ => {} } } @@ -263,10 +276,7 @@ fn is_mutated_static(e: &hir::Expr<'_>) -> bool { } fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool { - let mut v = StaticMutVisitor { - cx, - mutates_static: false, - }; + let mut v = StaticMutVisitor { cx, mutates_static: false }; intravisit::walk_expr(&mut v, &body.value); v.mutates_static } diff --git a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs index 1425d50f56046..4bdcffa10111e 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs @@ -7,15 +7,12 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::{mir::FakeReadCause, ty}; use rustc_span::source_map::Span; -use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_typeck::expr_use_visitor::{ + ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId, +}; pub(super) fn check(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) { - if let Some(higher::Range { - start: Some(start), - end: Some(end), - .. - }) = higher::range(arg) - { + if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(arg) { let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)]; if mut_ids[0].is_some() || mut_ids[1].is_some() { let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids); @@ -64,7 +61,7 @@ fn check_for_mutation<'tcx>( ExprUseVisitor::new( &mut delegate, &infcx, - body.hir_id.owner, + body.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) @@ -108,7 +105,13 @@ impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> { } } - fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read( + &mut self, + _: rustc_typeck::expr_use_visitor::Place<'tcx>, + _: FakeReadCause, + _: HirId, + ) { + } } impl MutatePairDelegate<'_, '_> { diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index dfab3e8a93112..8677bba5323de 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -47,9 +47,7 @@ impl Default for MissingDoc { impl MissingDoc { #[must_use] pub fn new() -> Self { - Self { - doc_hidden_stack: vec![false], - } + Self { doc_hidden_stack: vec![false] } } fn doc_hidden(&self) -> bool { @@ -94,7 +92,10 @@ impl MissingDoc { } let has_doc = attrs.iter().any(|a| { - a.is_doc_comment() || a.doc_str().is_some() || a.value_str().is_some() || Self::has_include(a.meta()) + a.is_doc_comment() + || a.doc_str().is_some() + || a.value_str().is_some() + || Self::has_include(a.meta()) }); if !has_doc { span_lint( @@ -129,12 +130,12 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { hir::ItemKind::Fn(..) => { // ignore main() if it.ident.name == sym::main { - let def_key = cx.tcx.hir().def_key(it.def_id); + let def_key = cx.tcx.hir().def_key(it.def_id.def_id); if def_key.parent == Some(hir::def_id::CRATE_DEF_INDEX) { return; } } - }, + } hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Mod(..) @@ -144,7 +145,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { | hir::ItemKind::TraitAlias(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) - | hir::ItemKind::OpaqueTy(..) => {}, + | hir::ItemKind::OpaqueTy(..) => {} hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::GlobalAsm(..) @@ -173,7 +174,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { if cx.tcx.impl_trait_ref(cid).is_some() { return; } - }, + } } let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index eef3c16730b13..6acb8aec82dbf 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -51,14 +51,8 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = e.kind { if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(inner).kind() { for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) { - if let [Adjustment { - kind: Adjust::Deref(_), .. - }, Adjustment { - kind: Adjust::Deref(_), .. - }, Adjustment { - kind: Adjust::Borrow(_), - .. - }] = *adj3 + if let [Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(_), .. }] = + *adj3 { span_lint_and_then( cx, @@ -121,13 +115,13 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { let attrs = cx.tcx.hir().attrs(item.hir_id()); if is_automatically_derived(attrs) { debug_assert!(self.derived_item.is_none()); - self.derived_item = Some(item.def_id); + self.derived_item = Some(item.def_id.def_id); } } fn check_item_post(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'_>) { if let Some(id) = self.derived_item { - if item.def_id == id { + if item.def_id.def_id == id { self.derived_item = None; } } diff --git a/src/tools/clippy/clippy_lints/src/transmute/utils.rs b/src/tools/clippy/clippy_lints/src/transmute/utils.rs index f359b606e4548..84333f10e396e 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/utils.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/utils.rs @@ -13,7 +13,11 @@ use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited}; /// the type's `ToString` implementation. In weird cases it could lead to types /// with invalid `'_` /// lifetime, but it should be rare. -pub(super) fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String { +pub(super) fn get_type_snippet( + cx: &LateContext<'_>, + path: &QPath<'_>, + to_ref_ty: Ty<'_>, +) -> String { let seg = last_path_segment(path); if_chain! { if let Some(params) = seg.args; @@ -33,7 +37,11 @@ pub(super) fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty // check if the component types of the transmuted collection and the result have different ABI, // size or alignment -pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool { +pub(super) fn is_layout_incompatible<'tcx>( + cx: &LateContext<'tcx>, + from: Ty<'tcx>, + to: Ty<'tcx>, +) -> bool { let empty_param_env = ty::ParamEnv::empty(); // check if `from` and `to` are normalizable to avoid ICE (#4968) if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) { @@ -42,7 +50,9 @@ pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from)); let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to)); if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) { - from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi + from_layout.size != to_layout.size + || from_layout.align != to_layout.align + || from_layout.abi != to_layout.abi } else { // no idea about layout, so don't lint false @@ -59,7 +69,9 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, ) -> bool { - use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; + use CastKind::{ + AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast, + }; matches!( check_cast(cx, e, from_ty, to_ty), Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) @@ -70,18 +82,20 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// the cast. In certain cases, including some invalid casts from array references /// to pointers, this may cause additional errors to be emitted and/or ICE error /// messages. This function will panic if that occurs. -fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { +fn check_cast<'tcx>( + cx: &LateContext<'tcx>, + e: &'tcx Expr<'_>, + from_ty: Ty<'tcx>, + to_ty: Ty<'tcx>, +) -> Option { let hir_id = e.hir_id; - let local_def_id = hir_id.owner; + let local_def_id = hir_id.owner.def_id; Inherited::build(cx.tcx, local_def_id).enter(|inherited| { let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); // If we already have errors, we can't be sure we can pointer cast. - assert!( - !fn_ctxt.errors_reported_since_creation(), - "Newly created FnCtxt contained errors" - ); + assert!(!fn_ctxt.errors_reported_since_creation(), "Newly created FnCtxt contained errors"); if let Ok(check) = CastCheck::new( &fn_ctxt, e, from_ty, to_ty, diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index d17aa6d842411..db5262766c1db 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -109,12 +109,16 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { } } -fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tcx hir::ImplItem<'_>) { +fn lint_impl_body<'tcx>( + cx: &LateContext<'tcx>, + impl_span: Span, + impl_item: &'tcx hir::ImplItem<'_>, +) { if let ImplItemKind::Fn(_, body_id) = impl_item.kind { let body = cx.tcx.hir().body(body_id); let mut fpu = FindExpectUnwrap { lcx: cx, - typeck_results: cx.tcx.typeck(impl_item.def_id), + typeck_results: cx.tcx.typeck(impl_item.def_id.def_id), result: Vec::new(), }; fpu.visit_expr(&body.value); diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 2ad6fa77f4818..19daba2af0089 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -9,8 +9,8 @@ use rustc_hir::{ def::{self, DefKind}, def_id::LocalDefId, intravisit::{walk_ty, NestedVisitorMap, Visitor}, - Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, Path, PathSegment, - QPath, TyKind, + Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, + Path, PathSegment, QPath, TyKind, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; @@ -65,10 +65,7 @@ pub struct UseSelf { impl UseSelf { #[must_use] pub fn new(msrv: Option) -> Self { - Self { - msrv, - ..Self::default() - } + Self { msrv, ..Self::default() } } } @@ -97,20 +94,20 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { // NB: If you push something on the stack in this method, remember to also pop it in the // `check_item_post` method. match &item.kind { - ItemKind::Impl(Impl { - self_ty: hir_self_ty, - of_trait, - .. - }) => { - let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = hir_self_ty.kind { + ItemKind::Impl(Impl { self_ty: hir_self_ty, of_trait, .. }) => { + let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = + hir_self_ty.kind + { let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args; parameters.as_ref().map_or(true, |params| { - !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) + !params.parenthesized + && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) }) } else { false }; - let impl_trait_ref_def_id = of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id())); + let impl_trait_ref_def_id = + of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id())); if should_check { self.stack.push(StackItem::Check { hir_id: hir_self_ty.hir_id, @@ -121,7 +118,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } else { self.stack.push(StackItem::NoCheck); } - }, + } ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) @@ -130,7 +127,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { | ItemKind::Union(..) | ItemKind::Trait(..) => { self.stack.push(StackItem::NoCheck); - }, + } _ => (), } } @@ -138,9 +135,16 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) { use ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union}; match item.kind { - Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..) => { + Impl { .. } + | Static(..) + | Const(..) + | Fn(..) + | Enum(..) + | Struct(..) + | Union(..) + | Trait(..) => { self.stack.pop(); - }, + } _ => (), } } @@ -212,21 +216,13 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { // which shouldn't, with a visitor. We could directly lint in the visitor, but then we // could only allow this lint on item scope. And we would have to check if those types are // already dealt with in `check_ty` anyway. - if let Some(StackItem::Check { - hir_id, - types_to_lint, - types_to_skip, - .. - }) = self.stack.last_mut() + if let Some(StackItem::Check { hir_id, types_to_lint, types_to_skip, .. }) = + self.stack.last_mut() { let self_ty = ty_from_hir_id(cx, *hir_id); - let mut visitor = LintTyCollector { - cx, - self_ty, - types_to_lint: vec![], - types_to_skip: vec![], - }; + let mut visitor = + LintTyCollector { cx, self_ty, types_to_lint: vec![], types_to_skip: vec![] }; visitor.visit_expr(&body.value); types_to_lint.extend(visitor.types_to_lint); types_to_skip.extend(visitor.types_to_skip); @@ -241,24 +237,21 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { return; } - let lint_dependend_on_expr_kind = if let Some(StackItem::Check { - hir_id, - types_to_lint, - types_to_skip, - .. - }) = self.stack.last() - { - if types_to_skip.contains(&hir_ty.hir_id) { - false - } else if types_to_lint.contains(&hir_ty.hir_id) { - true + let lint_dependend_on_expr_kind = + if let Some(StackItem::Check { hir_id, types_to_lint, types_to_skip, .. }) = + self.stack.last() + { + if types_to_skip.contains(&hir_ty.hir_id) { + false + } else if types_to_lint.contains(&hir_ty.hir_id) { + true + } else { + let self_ty = ty_from_hir_id(cx, *hir_id); + should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty) + } } else { - let self_ty = ty_from_hir_id(cx, *hir_id); - should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty) - } - } else { - false - }; + false + }; if lint_dependend_on_expr_kind { // FIXME: this span manipulation should not be necessary @@ -281,7 +274,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { fn expr_ty_matches(cx: &LateContext<'_>, expr: &Expr<'_>, self_ty: Ty<'_>) -> bool { - let def_id = expr.hir_id.owner; + let def_id = expr.hir_id.owner.def_id; if cx.tcx.has_typeck_results(def_id) { cx.tcx.typeck(def_id).expr_ty_opt(expr) == Some(self_ty) } else { @@ -289,7 +282,8 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } } - if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) { + if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) + { return; } @@ -301,20 +295,18 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if expr_ty_matches(cx, expr, self_ty) { match path.res { def::Res::SelfTy(..) => (), - def::Res::Def(DefKind::Variant, _) => span_lint_on_path_until_last_segment(cx, path), + def::Res::Def(DefKind::Variant, _) => { + span_lint_on_path_until_last_segment(cx, path) + } _ => { span_lint(cx, path.span); - }, + } } } - }, + } // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`) ExprKind::Call(fun, _) => { - if let Expr { - kind: ExprKind::Path(ref qpath), - .. - } = fun - { + if let Expr { kind: ExprKind::Path(ref qpath), .. } = fun { if expr_ty_matches(cx, expr, self_ty) { let res = cx.qpath_res(qpath, fun.hir_id); @@ -322,21 +314,21 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { match ctor_of { def::CtorOf::Variant => { span_lint_on_qpath_resolved(cx, qpath, true); - }, + } def::CtorOf::Struct => { span_lint_on_qpath_resolved(cx, qpath, false); - }, + } } } } } - }, + } // unit enum variants (`Enum::A`) ExprKind::Path(qpath) => { if expr_ty_matches(cx, expr, self_ty) { span_lint_on_qpath_resolved(cx, qpath, true); } - }, + } _ => (), } } @@ -439,7 +431,9 @@ fn ty_from_hir_id<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Ty<'tcx> { if let Some(Node::Ty(hir_ty)) = cx.tcx.hir().find(hir_id) { hir_ty_to_ty(cx.tcx, hir_ty) } else { - unreachable!("This function should only be called with `HirId`s that are for sure `Node::Ty`") + unreachable!( + "This function should only be called with `HirId`s that are for sure `Node::Ty`" + ) } } diff --git a/src/tools/clippy/clippy_lints/src/utils/inspector.rs b/src/tools/clippy/clippy_lints/src/utils/inspector.rs index 4665eeeff7b21..4dbbde5f611fd 100644 --- a/src/tools/clippy/clippy_lints/src/utils/inspector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/inspector.rs @@ -49,7 +49,8 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { hir::VisibilityKind::Crate(_) => println!("visible crate wide"), hir::VisibilityKind::Restricted { path, .. } => println!( "visible in module `{}`", - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s + .print_path(path, false)) ), hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"), } @@ -60,7 +61,7 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { hir::ImplItemKind::Const(_, body_id) => { println!("associated constant"); print_expr(cx, &cx.tcx.hir().body(body_id).value, 1); - }, + } hir::ImplItemKind::Fn(..) => println!("method"), hir::ImplItemKind::TyAlias(_) => println!("associated type"), } @@ -121,7 +122,7 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { println!("init expression:"); print_expr(cx, e, 0); } - }, + } hir::StmtKind::Item(_) => println!("item decl"), hir::StmtKind::Expr(e) | hir::StmtKind::Semi(e) => print_expr(cx, e, 0), } @@ -145,22 +146,18 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { let ind = " ".repeat(indent); println!("{}+", ind); println!("{}ty: {}", ind, cx.typeck_results().expr_ty(expr)); - println!( - "{}adjustments: {:?}", - ind, - cx.typeck_results().adjustments().get(expr.hir_id) - ); + println!("{}adjustments: {:?}", ind, cx.typeck_results().adjustments().get(expr.hir_id)); match expr.kind { hir::ExprKind::Box(e) => { println!("{}Box", ind); print_expr(cx, e, indent + 1); - }, + } hir::ExprKind::Array(v) => { println!("{}Array", ind); for e in v { print_expr(cx, e, indent + 1); } - }, + } hir::ExprKind::Call(func, args) => { println!("{}Call", ind); println!("{}function:", ind); @@ -169,20 +166,20 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { for arg in args { print_expr(cx, arg, indent + 1); } - }, + } hir::ExprKind::MethodCall(path, _, args, _) => { println!("{}MethodCall", ind); println!("{}method name: {}", ind, path.ident.name); for arg in args { print_expr(cx, arg, indent + 1); } - }, + } hir::ExprKind::Tup(v) => { println!("{}Tup", ind); for e in v { print_expr(cx, e, indent + 1); } - }, + } hir::ExprKind::Binary(op, lhs, rhs) => { println!("{}Binary", ind); println!("{}op: {:?}", ind, op.node); @@ -190,29 +187,29 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - }, + } hir::ExprKind::Unary(op, inner) => { println!("{}Unary", ind); println!("{}op: {:?}", ind, op); print_expr(cx, inner, indent + 1); - }, + } hir::ExprKind::Lit(ref lit) => { println!("{}Lit", ind); println!("{}{:?}", ind, lit); - }, + } hir::ExprKind::Cast(e, target) => { println!("{}Cast", ind); print_expr(cx, e, indent + 1); println!("{}target type: {:?}", ind, target); - }, + } hir::ExprKind::Type(e, target) => { println!("{}Type", ind); print_expr(cx, e, indent + 1); println!("{}target type: {:?}", ind, target); - }, + } hir::ExprKind::Loop(..) => { println!("{}Loop", ind); - }, + } hir::ExprKind::If(cond, _, ref else_opt) => { println!("{}If", ind); println!("{}condition:", ind); @@ -221,31 +218,31 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { println!("{}else:", ind); print_expr(cx, els, indent + 1); } - }, + } hir::ExprKind::Match(cond, _, ref source) => { println!("{}Match", ind); println!("{}condition:", ind); print_expr(cx, cond, indent + 1); println!("{}source: {:?}", ind, source); - }, + } hir::ExprKind::Closure(ref clause, _, _, _, _) => { println!("{}Closure", ind); println!("{}clause: {:?}", ind, clause); - }, + } hir::ExprKind::Yield(sub, _) => { println!("{}Yield", ind); print_expr(cx, sub, indent + 1); - }, + } hir::ExprKind::Block(_, _) => { println!("{}Block", ind); - }, + } hir::ExprKind::Assign(lhs, rhs, _) => { println!("{}Assign", ind); println!("{}lhs:", ind); print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - }, + } hir::ExprKind::AssignOp(ref binop, lhs, rhs) => { println!("{}AssignOp", ind); println!("{}op: {:?}", ind, binop.node); @@ -253,50 +250,50 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - }, + } hir::ExprKind::Field(e, ident) => { println!("{}Field", ind); println!("{}field name: {}", ind, ident.name); println!("{}struct expr:", ind); print_expr(cx, e, indent + 1); - }, + } hir::ExprKind::Index(arr, idx) => { println!("{}Index", ind); println!("{}array expr:", ind); print_expr(cx, arr, indent + 1); println!("{}index expr:", ind); print_expr(cx, idx, indent + 1); - }, + } hir::ExprKind::Path(hir::QPath::Resolved(ref ty, path)) => { println!("{}Resolved Path, {:?}", ind, ty); println!("{}path: {:?}", ind, path); - }, + } hir::ExprKind::Path(hir::QPath::TypeRelative(ty, seg)) => { println!("{}Relative Path, {:?}", ind, ty); println!("{}seg: {:?}", ind, seg); - }, + } hir::ExprKind::Path(hir::QPath::LangItem(lang_item, ..)) => { println!("{}Lang Item Path, {:?}", ind, lang_item.name()); - }, + } hir::ExprKind::AddrOf(kind, ref muta, e) => { println!("{}AddrOf", ind); println!("kind: {:?}", kind); println!("mutability: {:?}", muta); print_expr(cx, e, indent + 1); - }, + } hir::ExprKind::Break(_, ref e) => { println!("{}Break", ind); if let Some(e) = *e { print_expr(cx, e, indent + 1); } - }, + } hir::ExprKind::Continue(_) => println!("{}Again", ind), hir::ExprKind::Ret(ref e) => { println!("{}Ret", ind); if let Some(e) = *e { print_expr(cx, e, indent + 1); } - }, + } hir::ExprKind::InlineAsm(asm) => { println!("{}InlineAsm", ind); println!("{}template: {}", ind, InlineAsmTemplatePiece::to_string(asm.template)); @@ -311,20 +308,20 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { if let Some(expr) = expr { print_expr(cx, expr, indent + 1); } - }, + } hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => { print_expr(cx, in_expr, indent + 1); if let Some(out_expr) = out_expr { print_expr(cx, out_expr, indent + 1); } - }, + } hir::InlineAsmOperand::Const { anon_const } => { println!("{}anon_const:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - }, + } } } - }, + } hir::ExprKind::LlvmInlineAsm(asm) => { let inputs = &asm.inputs_exprs; let outputs = &asm.outputs_exprs; @@ -337,7 +334,7 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { for e in outputs.iter() { print_expr(cx, e, indent + 1); } - }, + } hir::ExprKind::Struct(path, fields, ref base) => { println!("{}Struct", ind); println!("{}path: {:?}", ind, path); @@ -349,26 +346,26 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { println!("{}base:", ind); print_expr(cx, base, indent + 1); } - }, + } hir::ExprKind::ConstBlock(ref anon_const) => { println!("{}ConstBlock", ind); println!("{}anon_const:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - }, + } hir::ExprKind::Repeat(val, ref anon_const) => { println!("{}Repeat", ind); println!("{}value:", ind); print_expr(cx, val, indent + 1); println!("{}repeat count:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - }, + } hir::ExprKind::Err => { println!("{}Err", ind); - }, + } hir::ExprKind::DropTemps(e) => { println!("{}DropTemps", ind); print_expr(cx, e, indent + 1); - }, + } } } @@ -386,7 +383,7 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { } match item.kind { hir::ItemKind::ExternCrate(ref _renamed_from) => { - if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(did) { + if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(did.def_id) { let source = cx.tcx.used_crate_source(crate_id); if let Some(ref src) = source.dylib { println!("extern crate dylib source: {:?}", src.0); @@ -397,32 +394,32 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { } else { println!("weird extern crate without a crate id"); } - }, + } hir::ItemKind::Use(path, ref kind) => println!("{:?}, {:?}", path, kind), hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)), hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)), hir::ItemKind::Fn(..) => { let item_ty = cx.tcx.type_of(did); println!("function of type {:#?}", item_ty); - }, + } hir::ItemKind::Mod(..) => println!("module"), hir::ItemKind::ForeignMod { abi, .. } => println!("foreign module with abi: {}", abi), hir::ItemKind::GlobalAsm(asm) => println!("global asm: {:?}", asm), hir::ItemKind::TyAlias(..) => { println!("type alias for {:?}", cx.tcx.type_of(did)); - }, + } hir::ItemKind::OpaqueTy(..) => { println!("existential type with real type {:?}", cx.tcx.type_of(did)); - }, + } hir::ItemKind::Enum(..) => { println!("enum definition of type {:?}", cx.tcx.type_of(did)); - }, + } hir::ItemKind::Struct(..) => { println!("struct definition of type {:?}", cx.tcx.type_of(did)); - }, + } hir::ItemKind::Union(..) => { println!("union definition of type {:?}", cx.tcx.type_of(did)); - }, + } hir::ItemKind::Trait(..) => { println!("trait decl"); if cx.tcx.trait_is_auto(did.to_def_id()) { @@ -430,19 +427,16 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { } else { println!("trait is not auto"); } - }, + } hir::ItemKind::TraitAlias(..) => { println!("trait alias"); - }, - hir::ItemKind::Impl(hir::Impl { - of_trait: Some(ref _trait_ref), - .. - }) => { + } + hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref _trait_ref), .. }) => { println!("trait impl"); - }, + } hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) => { println!("impl"); - }, + } } } @@ -461,19 +455,20 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { println!("{}inner:", ind); print_pat(cx, inner, indent + 1); } - }, + } hir::PatKind::Or(fields) => { println!("{}Or", ind); for field in fields { print_pat(cx, field, indent + 1); } - }, + } hir::PatKind::Struct(ref path, fields, ignore) => { println!("{}Struct", ind); println!( "{}name: {}", ind, - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s + .print_qpath(path, false)) ); println!("{}ignore leftover fields: {}", ind, ignore); println!("{}fields:", ind); @@ -484,13 +479,14 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { } print_pat(cx, field.pat, indent + 1); } - }, + } hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => { println!("{}TupleStruct", ind); println!( "{}path: {}", ind, - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s + .print_qpath(path, false)) ); if let Some(dot_position) = opt_dots_position { println!("{}dot position: {}", ind, dot_position); @@ -498,18 +494,18 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for field in fields { print_pat(cx, field, indent + 1); } - }, + } hir::PatKind::Path(hir::QPath::Resolved(ref ty, path)) => { println!("{}Resolved Path, {:?}", ind, ty); println!("{}path: {:?}", ind, path); - }, + } hir::PatKind::Path(hir::QPath::TypeRelative(ty, seg)) => { println!("{}Relative Path, {:?}", ind, ty); println!("{}seg: {:?}", ind, seg); - }, + } hir::PatKind::Path(hir::QPath::LangItem(lang_item, ..)) => { println!("{}Lang Item Path, {:?}", ind, lang_item.name()); - }, + } hir::PatKind::Tuple(pats, opt_dots_position) => { println!("{}Tuple", ind); if let Some(dot_position) = opt_dots_position { @@ -518,20 +514,20 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for field in pats { print_pat(cx, field, indent + 1); } - }, + } hir::PatKind::Box(inner) => { println!("{}Box", ind); print_pat(cx, inner, indent + 1); - }, + } hir::PatKind::Ref(inner, ref muta) => { println!("{}Ref", ind); println!("{}mutability: {:?}", ind, muta); print_pat(cx, inner, indent + 1); - }, + } hir::PatKind::Lit(e) => { println!("{}Lit", ind); print_expr(cx, e, indent + 1); - }, + } hir::PatKind::Range(ref l, ref r, ref range_end) => { println!("{}Range", ind); if let Some(expr) = l { @@ -544,7 +540,7 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { hir::RangeEnd::Included => println!("{} end included", ind), hir::RangeEnd::Excluded => println!("{} end excluded", ind), } - }, + } hir::PatKind::Slice(first_pats, ref range, last_pats) => { println!("{}Slice [a, b, ..i, y, z]", ind); println!("[a, b]:"); @@ -559,7 +555,7 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for pat in last_pats { print_pat(cx, pat, indent + 1); } - }, + } } } @@ -570,11 +566,11 @@ fn print_guard(cx: &LateContext<'_>, guard: &hir::Guard<'_>, indent: usize) { hir::Guard::If(expr) => { println!("{}If", ind); print_expr(cx, expr, indent + 1); - }, + } hir::Guard::IfLet(pat, expr) => { println!("{}IfLet", ind); print_pat(cx, pat, indent + 1); print_expr(cx, expr, indent + 1); - }, + } } } diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index 51c1117d20641..c0f90ef42e4d1 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -95,10 +95,7 @@ pub struct WildcardImports { impl WildcardImports { pub fn new(warn_on_all: bool) -> Self { - Self { - warn_on_all, - test_modules_deep: 0, - } + Self { warn_on_all, test_modules_deep: 0 } } } @@ -115,7 +112,7 @@ impl LateLintPass<'_> for WildcardImports { if_chain! { if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind; if self.warn_on_all || !self.check_exceptions(item, use_path.segments); - let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id); + let used_imports = cx.tcx.names_imported_by_glob_use(item.def_id.def_id); if !used_imports.is_empty(); // Already handled by `unused_imports` then { let mut applicability = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_utils/src/usage.rs b/src/tools/clippy/clippy_utils/src/usage.rs index 650b70c63af95..0224ae310f6b6 100644 --- a/src/tools/clippy/clippy_utils/src/usage.rs +++ b/src/tools/clippy/clippy_utils/src/usage.rs @@ -10,19 +10,18 @@ use rustc_lint::LateContext; use rustc_middle::hir::map::Map; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty; -use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; +use rustc_typeck::expr_use_visitor::{ + ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId, +}; /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined. pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option { - let mut delegate = MutVarsDelegate { - used_mutably: HirIdSet::default(), - skip: false, - }; + let mut delegate = MutVarsDelegate { used_mutably: HirIdSet::default(), skip: false }; cx.tcx.infer_ctxt().enter(|infcx| { ExprUseVisitor::new( &mut delegate, &infcx, - expr.hir_id.owner, + expr.hir_id.owner.def_id, cx.param_env, cx.typeck_results(), ) @@ -35,7 +34,11 @@ pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Some(delegate.used_mutably) } -pub fn is_potentially_mutated<'tcx>(variable: &'tcx Path<'_>, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool { +pub fn is_potentially_mutated<'tcx>( + variable: &'tcx Path<'_>, + expr: &'tcx Expr<'_>, + cx: &LateContext<'tcx>, +) -> bool { if let Res::Local(id) = variable.res { mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id)) } else { @@ -54,14 +57,14 @@ impl<'tcx> MutVarsDelegate { match cat.place.base { PlaceBase::Local(id) => { self.used_mutably.insert(id); - }, + } PlaceBase::Upvar(_) => { //FIXME: This causes false negatives. We can't get the `NodeId` from //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the //`while`-body, not just the ones in the condition. self.skip = true - }, - _ => {}, + } + _ => {} } } } @@ -79,7 +82,13 @@ impl<'tcx> Delegate<'tcx> for MutVarsDelegate { self.update(&cmt) } - fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} + fn fake_read( + &mut self, + _: rustc_typeck::expr_use_visitor::Place<'tcx>, + _: FakeReadCause, + _: HirId, + ) { + } } pub struct ParamBindingIdCollector { @@ -89,9 +98,7 @@ impl<'tcx> ParamBindingIdCollector { fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec { let mut hir_ids: Vec = Vec::new(); for param in body.params.iter() { - let mut finder = ParamBindingIdCollector { - binding_hir_ids: Vec::new(), - }; + let mut finder = ParamBindingIdCollector { binding_hir_ids: Vec::new() }; finder.visit_param(param); for hir_id in &finder.binding_hir_ids { hir_ids.push(*hir_id); @@ -159,9 +166,7 @@ struct ReturnBreakContinueMacroVisitor { impl ReturnBreakContinueMacroVisitor { fn new() -> ReturnBreakContinueMacroVisitor { - ReturnBreakContinueMacroVisitor { - seen_return_break_continue: false, - } + ReturnBreakContinueMacroVisitor { seen_return_break_continue: false } } } @@ -179,7 +184,7 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { match &ex.kind { ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => { self.seen_return_break_continue = true; - }, + } // Something special could be done here to handle while or for loop // desugaring, as this will detect a break if there's a while loop // or a for loop inside the expression. @@ -189,7 +194,7 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { } else { rustc_hir::intravisit::walk_expr(self, ex); } - }, + } } } } From b072a4a68c299bdde57f99547d9431b18350e351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sun, 23 May 2021 17:18:54 +0200 Subject: [PATCH 5/8] fix issue introduced that affected dep_graph by implementing traits --- .../rustc_middle/src/dep_graph/dep_node.rs | 21 ++++++++++++++++++- .../rustc_query_impl/src/profiling_support.rs | 10 +++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index adf92c7f3d80a..63879ad2abf2a 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -62,7 +62,7 @@ use crate::ty::TyCtxt; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX}; use rustc_hir::definitions::DefPathHash; -use rustc_hir::HirId; +use rustc_hir::{HirId, HirOwner}; use rustc_span::symbol::Symbol; use std::hash::Hash; @@ -426,6 +426,25 @@ impl<'tcx> DepNodeParams> for LocalDefId { } } +impl<'tcx> DepNodeParams> for HirOwner { + #[inline(always)] + fn can_reconstruct_query_key() -> bool { + LocalDefId::can_reconstruct_query_key() + } + + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.def_id.to_fingerprint(tcx) + } + + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.def_id.to_debug_str(tcx) + } + + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + LocalDefId::recover(tcx, dep_node).map(|def_id| HirOwner { def_id }) + } +} + impl<'tcx> DepNodeParams> for CrateNum { #[inline(always)] fn can_reconstruct_query_key() -> bool { diff --git a/compiler/rustc_query_impl/src/profiling_support.rs b/compiler/rustc_query_impl/src/profiling_support.rs index 2517793ecea70..64832ac4fc01d 100644 --- a/compiler/rustc_query_impl/src/profiling_support.rs +++ b/compiler/rustc_query_impl/src/profiling_support.rs @@ -3,6 +3,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::profiling::SelfProfiler; use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::DefPathData; +use rustc_hir::HirOwner; use rustc_middle::ty::{TyCtxt, WithOptConstParam}; use rustc_query_system::query::{QueryCache, QueryCacheStore}; use std::fmt::Debug; @@ -165,6 +166,15 @@ impl SpecIntoSelfProfilingString for LocalDefId { } } +impl SpecIntoSelfProfilingString for HirOwner { + fn spec_to_self_profile_string( + &self, + builder: &mut QueryKeyStringBuilder<'_, '_, '_>, + ) -> StringId { + self.def_id.spec_to_self_profile_string(builder) + } +} + impl SpecIntoSelfProfilingString for WithOptConstParam { fn spec_to_self_profile_string( &self, From b93ed5fec5e8c3ed4df25cd7c28088f84606c223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Sun, 23 May 2021 18:13:44 +0200 Subject: [PATCH 6/8] fix --- compiler/rustc_middle/src/hir/map/collector.rs | 2 +- compiler/rustc_middle/src/hir/mod.rs | 2 +- compiler/rustc_passes/src/diagnostic_items.rs | 6 +----- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_middle/src/hir/map/collector.rs b/compiler/rustc_middle/src/hir/map/collector.rs index 9ba0d30a25ff7..e20001d3c89b7 100644 --- a/compiler/rustc_middle/src/hir/map/collector.rs +++ b/compiler/rustc_middle/src/hir/map/collector.rs @@ -242,7 +242,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> { fn insert_nested(&mut self, item: HirOwner) { #[cfg(debug_assertions)] { - let dk_parent = self.definitions.def_key(item).parent.unwrap(); + let dk_parent = self.definitions.def_key(item.def_id).parent.unwrap(); let dk_parent = LocalDefId { local_def_index: dk_parent }; let dk_parent = self.definitions.local_def_id_to_hir_id(dk_parent); debug_assert_eq!( diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 5a704d7ebae67..d887d8fdd11ec 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -13,7 +13,7 @@ use rustc_ast::Attribute; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_hir::def_id::{LocalDefId}; +use rustc_hir::def_id::LocalDefId; use rustc_hir::hir_id::HirOwner; use rustc_hir::*; use rustc_index::vec::IndexVec; diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index d72c28f32a694..b78be198094f2 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -95,11 +95,7 @@ fn collect_item( /// Extract the first `rustc_diagnostic_item = "$name"` out of a list of attributes. fn extract(sess: &Session, attrs: &[ast::Attribute]) -> Option { attrs.iter().find_map(|attr| { - if sess.check_name(attr, sym::rustc_diagnostic_item) { - attr.value_str() - } else { - None - } + if sess.check_name(attr, sym::rustc_diagnostic_item) { attr.value_str() } else { None } }) } From 3a162b0d00b0f38fbead63b64197b898dda69abf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Mon, 24 May 2021 21:34:52 +0200 Subject: [PATCH 7/8] revert clippy formating --- src/tools/clippy/clippy_lints/src/doc.rs | 101 ++++++------ .../clippy_lints/src/fallible_impl_from.rs | 6 +- .../clippy_lints/src/functions/must_use.rs | 36 ++--- .../clippy_lints/src/loops/mut_range_bound.rs | 19 +-- .../clippy/clippy_lints/src/missing_doc.rs | 15 +- .../clippy_lints/src/needless_borrow.rs | 10 +- .../clippy_lints/src/transmute/utils.rs | 32 ++-- .../clippy_lints/src/unwrap_in_result.rs | 6 +- src/tools/clippy/clippy_lints/src/use_self.rs | 116 +++++++------- .../clippy_lints/src/utils/inspector.rs | 148 +++++++++--------- .../clippy_lints/src/wildcard_imports.rs | 5 +- src/tools/clippy/clippy_utils/src/usage.rs | 41 +++-- 12 files changed, 257 insertions(+), 278 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/doc.rs b/src/tools/clippy/clippy_lints/src/doc.rs index 32af87e7b3492..7dc376dad09a1 100644 --- a/src/tools/clippy/clippy_lints/src/doc.rs +++ b/src/tools/clippy/clippy_lints/src/doc.rs @@ -1,8 +1,6 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_note}; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; -use clippy_utils::{ - is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty, -}; +use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty}; use if_chain::if_chain; use itertools::Itertools; use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind}; @@ -197,7 +195,10 @@ pub struct DocMarkdown { impl DocMarkdown { pub fn new(valid_idents: FxHashSet) -> Self { - Self { valid_idents, in_trait_impl: false } + Self { + valid_idents, + in_trait_impl: false, + } } } @@ -216,9 +217,7 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { let headers = check_attrs(cx, &self.valid_idents, attrs); match item.kind { hir::ItemKind::Fn(ref sig, _, body_id) => { - if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) - || in_external_macro(cx.tcx.sess, item.span)) - { + if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) { let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { cx, @@ -236,11 +235,11 @@ impl<'tcx> LateLintPass<'tcx> for DocMarkdown { fpu.panic_span, ); } - } + }, hir::ItemKind::Impl(ref impl_) => { self.in_trait_impl = impl_.of_trait.is_some(); - } - _ => {} + }, + _ => {}, } } @@ -300,7 +299,12 @@ fn lint_for_missing_headers<'tcx>( return; // Private functions do not require doc comments } if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe { - span_lint(cx, MISSING_SAFETY_DOC, span, "unsafe function's docs miss `# Safety` section"); + span_lint( + cx, + MISSING_SAFETY_DOC, + span, + "unsafe function's docs miss `# Safety` section", + ); } if !headers.panics && panic_span.is_some() { span_lint_and_note( @@ -353,11 +357,7 @@ fn lint_for_missing_headers<'tcx>( /// the spans but this function is inspired from the later. #[allow(clippy::cast_possible_truncation)] #[must_use] -pub fn strip_doc_comment_decoration( - doc: &str, - comment_kind: CommentKind, - span: Span, -) -> (String, Vec<(usize, Span)>) { +pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) { // one-line comments lose their prefix if comment_kind == CommentKind::Line { let mut doc = doc.to_owned(); @@ -405,24 +405,23 @@ struct DocHeaders { panics: bool, } -fn check_attrs<'a>( - cx: &LateContext<'_>, - valid_idents: &FxHashSet, - attrs: &'a [Attribute], -) -> DocHeaders { +fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet, attrs: &'a [Attribute]) -> DocHeaders { let mut doc = String::new(); let mut spans = vec![]; for attr in attrs { if let AttrKind::DocComment(comment_kind, comment) = attr.kind { - let (comment, current_spans) = - strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span); + let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span); spans.extend_from_slice(¤t_spans); doc.push_str(&comment); } else if attr.has_name(sym::doc) { // ignore mix of sugared and non-sugared doc // don't trigger the safety or errors check - return DocHeaders { safety: true, errors: true, panics: true }; + return DocHeaders { + safety: true, + errors: true, + panics: true, + }; } } @@ -434,7 +433,11 @@ fn check_attrs<'a>( } if doc.is_empty() { - return DocHeaders { safety: false, errors: false, panics: false }; + return DocHeaders { + safety: false, + errors: false, + panics: false, + }; } let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter(); @@ -450,7 +453,7 @@ fn check_attrs<'a>( let mut previous = previous.to_string(); previous.push_str(¤t); Ok((Text(previous.into()), previous_range)) - } + }, (previous, current) => Err(((previous, previous_range), (current, current_range))), } }); @@ -472,7 +475,11 @@ fn check_doc<'a, Events: Iterator, Range, Range { in_code = false; is_rust = false; - } + }, Start(Link(_, url, _)) => in_link = Some(url), End(Link(..)) => in_link = None, Start(Heading(_)) => in_heading = true, @@ -534,7 +541,7 @@ fn check_doc<'a, Events: Iterator, Range, text: &str, edition: Edition, span: Span) { let filename = FileName::anon_source_code(code); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let emitter = - EmitterWriter::new(box io::sink(), None, false, false, false, None, false); + let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false); let handler = Handler::with_emitter(false, None, box emitter); let sess = ParseSess::with_span_handler(handler, sm); - let mut parser = - match maybe_new_parser_from_source_str(&sess, filename, code.into()) { - Ok(p) => p, - Err(errs) => { - for mut err in errs { - err.cancel(); - } - return false; + let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) { + Ok(p) => p, + Err(errs) => { + for mut err in errs { + err.cancel(); } - }; + return false; + }, + }; let mut relevant_main_found = false; loop { @@ -573,9 +578,7 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) { | ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) => return false, // We found a main function ... - ItemKind::Fn(box FnKind(_, sig, _, Some(block))) - if item.ident.name == sym::main => - { + ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => { let is_async = matches!(sig.header.asyncness, Async::Yes { .. }); let returns_nothing = match &sig.decl.output { FnRetTy::Default(..) => true, @@ -590,16 +593,16 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) { // This main function should not be linted, we're done return false; } - } + }, // Another function was found; this case is ignored too ItemKind::Fn(..) => return false, - _ => {} + _ => {}, }, Ok(None) => break, Err(mut e) => { e.cancel(); return false; - } + }, } } @@ -719,9 +722,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { } // check for `assert_eq` or `assert_ne` - if is_expn_of(expr.span, "assert_eq").is_some() - || is_expn_of(expr.span, "assert_ne").is_some() - { + if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() { self.panic_span = Some(expr.span); } diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 99d2fbe0ff5cf..cd2202a2991b1 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -65,11 +65,7 @@ impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { } } -fn lint_impl_body<'tcx>( - cx: &LateContext<'tcx>, - impl_span: Span, - impl_items: &[hir::ImplItemRef<'_>], -) { +fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) { use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath}; diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index a5168436be7e5..2ac5e92dedec3 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -27,10 +27,7 @@ pub(super) fn check_item(cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); return; - } else if is_public - && !is_proc_macro(cx.sess(), attrs) - && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) - { + } else if is_public && !is_proc_macro(cx.sess(), attrs) && !attrs.iter().any(|a| a.has_name(sym::no_mangle)) { check_must_use_candidate( cx, sig.decl, @@ -52,10 +49,7 @@ pub(super) fn check_impl_item(cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem< let attr = must_use_attr(attrs); if let Some(attr) = attr { check_needless_must_use(cx, sig.decl, item.hir_id(), item.span, fn_header_span, attr); - } else if is_public - && !is_proc_macro(cx.sess(), attrs) - && trait_ref_of_method(cx, item.hir_id()).is_none() - { + } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.hir_id()).is_none() { check_must_use_candidate( cx, sig.decl, @@ -192,12 +186,7 @@ fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut DefIdSet) static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]]; -fn is_mutable_ty<'tcx>( - cx: &LateContext<'tcx>, - ty: Ty<'tcx>, - span: Span, - tys: &mut DefIdSet, -) -> bool { +fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut DefIdSet) -> bool { match *ty.kind() { // primitive types are never mutable ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false, @@ -205,12 +194,12 @@ fn is_mutable_ty<'tcx>( tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env) || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path)) && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)) - } + }, ty::Tuple(substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)), ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys), ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => { mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys) - } + }, // calling something constitutes a side effect, so return true on all callables // also never calls need not be used, so return true for them, too _ => true, @@ -249,13 +238,11 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { } tys.clear(); } - } - Assign(target, ..) - | AssignOp(_, target, _) - | AddrOf(_, hir::Mutability::Mut, target) => { + }, + Assign(target, ..) | AssignOp(_, target, _) | AddrOf(_, hir::Mutability::Mut, target) => { self.mutates_static |= is_mutated_static(target) - } - _ => {} + }, + _ => {}, } } @@ -276,7 +263,10 @@ fn is_mutated_static(e: &hir::Expr<'_>) -> bool { } fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool { - let mut v = StaticMutVisitor { cx, mutates_static: false }; + let mut v = StaticMutVisitor { + cx, + mutates_static: false, + }; intravisit::walk_expr(&mut v, &body.value); v.mutates_static } diff --git a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs index 4bdcffa10111e..1ba5c2d54b31f 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs @@ -7,12 +7,15 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::{mir::FakeReadCause, ty}; use rustc_span::source_map::Span; -use rustc_typeck::expr_use_visitor::{ - ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId, -}; +use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; pub(super) fn check(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) { - if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::range(arg) { + if let Some(higher::Range { + start: Some(start), + end: Some(end), + .. + }) = higher::range(arg) + { let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)]; if mut_ids[0].is_some() || mut_ids[1].is_some() { let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids); @@ -105,13 +108,7 @@ impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> { } } - fn fake_read( - &mut self, - _: rustc_typeck::expr_use_visitor::Place<'tcx>, - _: FakeReadCause, - _: HirId, - ) { - } + fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} } impl MutatePairDelegate<'_, '_> { diff --git a/src/tools/clippy/clippy_lints/src/missing_doc.rs b/src/tools/clippy/clippy_lints/src/missing_doc.rs index 8677bba5323de..563bc888e463c 100644 --- a/src/tools/clippy/clippy_lints/src/missing_doc.rs +++ b/src/tools/clippy/clippy_lints/src/missing_doc.rs @@ -47,7 +47,9 @@ impl Default for MissingDoc { impl MissingDoc { #[must_use] pub fn new() -> Self { - Self { doc_hidden_stack: vec![false] } + Self { + doc_hidden_stack: vec![false], + } } fn doc_hidden(&self) -> bool { @@ -92,10 +94,7 @@ impl MissingDoc { } let has_doc = attrs.iter().any(|a| { - a.is_doc_comment() - || a.doc_str().is_some() - || a.value_str().is_some() - || Self::has_include(a.meta()) + a.is_doc_comment() || a.doc_str().is_some() || a.value_str().is_some() || Self::has_include(a.meta()) }); if !has_doc { span_lint( @@ -135,7 +134,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { return; } } - } + }, hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Mod(..) @@ -145,7 +144,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { | hir::ItemKind::TraitAlias(..) | hir::ItemKind::TyAlias(..) | hir::ItemKind::Union(..) - | hir::ItemKind::OpaqueTy(..) => {} + | hir::ItemKind::OpaqueTy(..) => {}, hir::ItemKind::ExternCrate(..) | hir::ItemKind::ForeignMod { .. } | hir::ItemKind::GlobalAsm(..) @@ -174,7 +173,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { if cx.tcx.impl_trait_ref(cid).is_some() { return; } - } + }, } let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index 6acb8aec82dbf..eba8f3b419ce9 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -51,8 +51,14 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessBorrow { if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = e.kind { if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty(inner).kind() { for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) { - if let [Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(_), .. }] = - *adj3 + if let [Adjustment { + kind: Adjust::Deref(_), .. + }, Adjustment { + kind: Adjust::Deref(_), .. + }, Adjustment { + kind: Adjust::Borrow(_), + .. + }] = *adj3 { span_lint_and_then( cx, diff --git a/src/tools/clippy/clippy_lints/src/transmute/utils.rs b/src/tools/clippy/clippy_lints/src/transmute/utils.rs index 84333f10e396e..6ac21efff9f91 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/utils.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/utils.rs @@ -13,11 +13,7 @@ use rustc_typeck::check::{cast::CastCheck, FnCtxt, Inherited}; /// the type's `ToString` implementation. In weird cases it could lead to types /// with invalid `'_` /// lifetime, but it should be rare. -pub(super) fn get_type_snippet( - cx: &LateContext<'_>, - path: &QPath<'_>, - to_ref_ty: Ty<'_>, -) -> String { +pub(super) fn get_type_snippet(cx: &LateContext<'_>, path: &QPath<'_>, to_ref_ty: Ty<'_>) -> String { let seg = last_path_segment(path); if_chain! { if let Some(params) = seg.args; @@ -37,11 +33,7 @@ pub(super) fn get_type_snippet( // check if the component types of the transmuted collection and the result have different ABI, // size or alignment -pub(super) fn is_layout_incompatible<'tcx>( - cx: &LateContext<'tcx>, - from: Ty<'tcx>, - to: Ty<'tcx>, -) -> bool { +pub(super) fn is_layout_incompatible<'tcx>(cx: &LateContext<'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool { let empty_param_env = ty::ParamEnv::empty(); // check if `from` and `to` are normalizable to avoid ICE (#4968) if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) { @@ -50,9 +42,7 @@ pub(super) fn is_layout_incompatible<'tcx>( let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from)); let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to)); if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) { - from_layout.size != to_layout.size - || from_layout.align != to_layout.align - || from_layout.abi != to_layout.abi + from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi } else { // no idea about layout, so don't lint false @@ -69,9 +59,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( from_ty: Ty<'tcx>, to_ty: Ty<'tcx>, ) -> bool { - use CastKind::{ - AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast, - }; + use CastKind::{AddrPtrCast, ArrayPtrCast, FnPtrAddrCast, FnPtrPtrCast, PtrAddrCast, PtrPtrCast}; matches!( check_cast(cx, e, from_ty, to_ty), Some(PtrPtrCast | PtrAddrCast | AddrPtrCast | ArrayPtrCast | FnPtrPtrCast | FnPtrAddrCast) @@ -82,12 +70,7 @@ pub(super) fn can_be_expressed_as_pointer_cast<'tcx>( /// the cast. In certain cases, including some invalid casts from array references /// to pointers, this may cause additional errors to be emitted and/or ICE error /// messages. This function will panic if that occurs. -fn check_cast<'tcx>( - cx: &LateContext<'tcx>, - e: &'tcx Expr<'_>, - from_ty: Ty<'tcx>, - to_ty: Ty<'tcx>, -) -> Option { +fn check_cast<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> Option { let hir_id = e.hir_id; let local_def_id = hir_id.owner.def_id; @@ -95,7 +78,10 @@ fn check_cast<'tcx>( let fn_ctxt = FnCtxt::new(&inherited, cx.param_env, hir_id); // If we already have errors, we can't be sure we can pointer cast. - assert!(!fn_ctxt.errors_reported_since_creation(), "Newly created FnCtxt contained errors"); + assert!( + !fn_ctxt.errors_reported_since_creation(), + "Newly created FnCtxt contained errors" + ); if let Ok(check) = CastCheck::new( &fn_ctxt, e, from_ty, to_ty, diff --git a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs index db5262766c1db..95ebbbe577bf6 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap_in_result.rs @@ -109,11 +109,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindExpectUnwrap<'a, 'tcx> { } } -fn lint_impl_body<'tcx>( - cx: &LateContext<'tcx>, - impl_span: Span, - impl_item: &'tcx hir::ImplItem<'_>, -) { +fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_item: &'tcx hir::ImplItem<'_>) { if let ImplItemKind::Fn(_, body_id) = impl_item.kind { let body = cx.tcx.hir().body(body_id); let mut fpu = FindExpectUnwrap { diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 19daba2af0089..8fee01f0e58c7 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -9,8 +9,8 @@ use rustc_hir::{ def::{self, DefKind}, def_id::LocalDefId, intravisit::{walk_ty, NestedVisitorMap, Visitor}, - Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, - Path, PathSegment, QPath, TyKind, + Expr, ExprKind, FnRetTy, FnSig, GenericArg, HirId, Impl, ImplItemKind, Item, ItemKind, Node, Path, PathSegment, + QPath, TyKind, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; @@ -65,7 +65,10 @@ pub struct UseSelf { impl UseSelf { #[must_use] pub fn new(msrv: Option) -> Self { - Self { msrv, ..Self::default() } + Self { + msrv, + ..Self::default() + } } } @@ -94,20 +97,20 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { // NB: If you push something on the stack in this method, remember to also pop it in the // `check_item_post` method. match &item.kind { - ItemKind::Impl(Impl { self_ty: hir_self_ty, of_trait, .. }) => { - let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = - hir_self_ty.kind - { + ItemKind::Impl(Impl { + self_ty: hir_self_ty, + of_trait, + .. + }) => { + let should_check = if let TyKind::Path(QPath::Resolved(_, item_path)) = hir_self_ty.kind { let parameters = &item_path.segments.last().expect(SEGMENTS_MSG).args; parameters.as_ref().map_or(true, |params| { - !params.parenthesized - && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) + !params.parenthesized && !params.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))) }) } else { false }; - let impl_trait_ref_def_id = - of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id())); + let impl_trait_ref_def_id = of_trait.as_ref().map(|_| cx.tcx.hir().local_def_id(item.hir_id())); if should_check { self.stack.push(StackItem::Check { hir_id: hir_self_ty.hir_id, @@ -118,7 +121,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } else { self.stack.push(StackItem::NoCheck); } - } + }, ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) @@ -127,7 +130,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { | ItemKind::Union(..) | ItemKind::Trait(..) => { self.stack.push(StackItem::NoCheck); - } + }, _ => (), } } @@ -135,16 +138,9 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { fn check_item_post(&mut self, _: &LateContext<'_>, item: &Item<'_>) { use ItemKind::{Const, Enum, Fn, Impl, Static, Struct, Trait, Union}; match item.kind { - Impl { .. } - | Static(..) - | Const(..) - | Fn(..) - | Enum(..) - | Struct(..) - | Union(..) - | Trait(..) => { + Impl { .. } | Static(..) | Const(..) | Fn(..) | Enum(..) | Struct(..) | Union(..) | Trait(..) => { self.stack.pop(); - } + }, _ => (), } } @@ -216,13 +212,21 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { // which shouldn't, with a visitor. We could directly lint in the visitor, but then we // could only allow this lint on item scope. And we would have to check if those types are // already dealt with in `check_ty` anyway. - if let Some(StackItem::Check { hir_id, types_to_lint, types_to_skip, .. }) = - self.stack.last_mut() + if let Some(StackItem::Check { + hir_id, + types_to_lint, + types_to_skip, + .. + }) = self.stack.last_mut() { let self_ty = ty_from_hir_id(cx, *hir_id); - let mut visitor = - LintTyCollector { cx, self_ty, types_to_lint: vec![], types_to_skip: vec![] }; + let mut visitor = LintTyCollector { + cx, + self_ty, + types_to_lint: vec![], + types_to_skip: vec![], + }; visitor.visit_expr(&body.value); types_to_lint.extend(visitor.types_to_lint); types_to_skip.extend(visitor.types_to_skip); @@ -237,21 +241,24 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { return; } - let lint_dependend_on_expr_kind = - if let Some(StackItem::Check { hir_id, types_to_lint, types_to_skip, .. }) = - self.stack.last() - { - if types_to_skip.contains(&hir_ty.hir_id) { - false - } else if types_to_lint.contains(&hir_ty.hir_id) { - true - } else { - let self_ty = ty_from_hir_id(cx, *hir_id); - should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty) - } - } else { + let lint_dependend_on_expr_kind = if let Some(StackItem::Check { + hir_id, + types_to_lint, + types_to_skip, + .. + }) = self.stack.last() + { + if types_to_skip.contains(&hir_ty.hir_id) { false - }; + } else if types_to_lint.contains(&hir_ty.hir_id) { + true + } else { + let self_ty = ty_from_hir_id(cx, *hir_id); + should_lint_ty(hir_ty, hir_ty_to_ty(cx.tcx, hir_ty), self_ty) + } + } else { + false + }; if lint_dependend_on_expr_kind { // FIXME: this span manipulation should not be necessary @@ -282,8 +289,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } } - if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) - { + if in_macro(expr.span) || !meets_msrv(self.msrv.as_ref(), &msrvs::TYPE_ALIAS_ENUM_VARIANTS) { return; } @@ -295,18 +301,20 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if expr_ty_matches(cx, expr, self_ty) { match path.res { def::Res::SelfTy(..) => (), - def::Res::Def(DefKind::Variant, _) => { - span_lint_on_path_until_last_segment(cx, path) - } + def::Res::Def(DefKind::Variant, _) => span_lint_on_path_until_last_segment(cx, path), _ => { span_lint(cx, path.span); - } + }, } } - } + }, // tuple struct instantiation (`Foo(arg)` or `Enum::Foo(arg)`) ExprKind::Call(fun, _) => { - if let Expr { kind: ExprKind::Path(ref qpath), .. } = fun { + if let Expr { + kind: ExprKind::Path(ref qpath), + .. + } = fun + { if expr_ty_matches(cx, expr, self_ty) { let res = cx.qpath_res(qpath, fun.hir_id); @@ -314,21 +322,21 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { match ctor_of { def::CtorOf::Variant => { span_lint_on_qpath_resolved(cx, qpath, true); - } + }, def::CtorOf::Struct => { span_lint_on_qpath_resolved(cx, qpath, false); - } + }, } } } } - } + }, // unit enum variants (`Enum::A`) ExprKind::Path(qpath) => { if expr_ty_matches(cx, expr, self_ty) { span_lint_on_qpath_resolved(cx, qpath, true); } - } + }, _ => (), } } @@ -431,9 +439,7 @@ fn ty_from_hir_id<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Ty<'tcx> { if let Some(Node::Ty(hir_ty)) = cx.tcx.hir().find(hir_id) { hir_ty_to_ty(cx.tcx, hir_ty) } else { - unreachable!( - "This function should only be called with `HirId`s that are for sure `Node::Ty`" - ) + unreachable!("This function should only be called with `HirId`s that are for sure `Node::Ty`") } } diff --git a/src/tools/clippy/clippy_lints/src/utils/inspector.rs b/src/tools/clippy/clippy_lints/src/utils/inspector.rs index 4dbbde5f611fd..be9dd848e0140 100644 --- a/src/tools/clippy/clippy_lints/src/utils/inspector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/inspector.rs @@ -49,8 +49,7 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { hir::VisibilityKind::Crate(_) => println!("visible crate wide"), hir::VisibilityKind::Restricted { path, .. } => println!( "visible in module `{}`", - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s - .print_path(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false)) ), hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"), } @@ -61,7 +60,7 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { hir::ImplItemKind::Const(_, body_id) => { println!("associated constant"); print_expr(cx, &cx.tcx.hir().body(body_id).value, 1); - } + }, hir::ImplItemKind::Fn(..) => println!("method"), hir::ImplItemKind::TyAlias(_) => println!("associated type"), } @@ -122,7 +121,7 @@ impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector { println!("init expression:"); print_expr(cx, e, 0); } - } + }, hir::StmtKind::Item(_) => println!("item decl"), hir::StmtKind::Expr(e) | hir::StmtKind::Semi(e) => print_expr(cx, e, 0), } @@ -146,18 +145,22 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { let ind = " ".repeat(indent); println!("{}+", ind); println!("{}ty: {}", ind, cx.typeck_results().expr_ty(expr)); - println!("{}adjustments: {:?}", ind, cx.typeck_results().adjustments().get(expr.hir_id)); + println!( + "{}adjustments: {:?}", + ind, + cx.typeck_results().adjustments().get(expr.hir_id) + ); match expr.kind { hir::ExprKind::Box(e) => { println!("{}Box", ind); print_expr(cx, e, indent + 1); - } + }, hir::ExprKind::Array(v) => { println!("{}Array", ind); for e in v { print_expr(cx, e, indent + 1); } - } + }, hir::ExprKind::Call(func, args) => { println!("{}Call", ind); println!("{}function:", ind); @@ -166,20 +169,20 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { for arg in args { print_expr(cx, arg, indent + 1); } - } + }, hir::ExprKind::MethodCall(path, _, args, _) => { println!("{}MethodCall", ind); println!("{}method name: {}", ind, path.ident.name); for arg in args { print_expr(cx, arg, indent + 1); } - } + }, hir::ExprKind::Tup(v) => { println!("{}Tup", ind); for e in v { print_expr(cx, e, indent + 1); } - } + }, hir::ExprKind::Binary(op, lhs, rhs) => { println!("{}Binary", ind); println!("{}op: {:?}", ind, op.node); @@ -187,29 +190,29 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - } + }, hir::ExprKind::Unary(op, inner) => { println!("{}Unary", ind); println!("{}op: {:?}", ind, op); print_expr(cx, inner, indent + 1); - } + }, hir::ExprKind::Lit(ref lit) => { println!("{}Lit", ind); println!("{}{:?}", ind, lit); - } + }, hir::ExprKind::Cast(e, target) => { println!("{}Cast", ind); print_expr(cx, e, indent + 1); println!("{}target type: {:?}", ind, target); - } + }, hir::ExprKind::Type(e, target) => { println!("{}Type", ind); print_expr(cx, e, indent + 1); println!("{}target type: {:?}", ind, target); - } + }, hir::ExprKind::Loop(..) => { println!("{}Loop", ind); - } + }, hir::ExprKind::If(cond, _, ref else_opt) => { println!("{}If", ind); println!("{}condition:", ind); @@ -218,31 +221,31 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { println!("{}else:", ind); print_expr(cx, els, indent + 1); } - } + }, hir::ExprKind::Match(cond, _, ref source) => { println!("{}Match", ind); println!("{}condition:", ind); print_expr(cx, cond, indent + 1); println!("{}source: {:?}", ind, source); - } + }, hir::ExprKind::Closure(ref clause, _, _, _, _) => { println!("{}Closure", ind); println!("{}clause: {:?}", ind, clause); - } + }, hir::ExprKind::Yield(sub, _) => { println!("{}Yield", ind); print_expr(cx, sub, indent + 1); - } + }, hir::ExprKind::Block(_, _) => { println!("{}Block", ind); - } + }, hir::ExprKind::Assign(lhs, rhs, _) => { println!("{}Assign", ind); println!("{}lhs:", ind); print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - } + }, hir::ExprKind::AssignOp(ref binop, lhs, rhs) => { println!("{}AssignOp", ind); println!("{}op: {:?}", ind, binop.node); @@ -250,50 +253,50 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { print_expr(cx, lhs, indent + 1); println!("{}rhs:", ind); print_expr(cx, rhs, indent + 1); - } + }, hir::ExprKind::Field(e, ident) => { println!("{}Field", ind); println!("{}field name: {}", ind, ident.name); println!("{}struct expr:", ind); print_expr(cx, e, indent + 1); - } + }, hir::ExprKind::Index(arr, idx) => { println!("{}Index", ind); println!("{}array expr:", ind); print_expr(cx, arr, indent + 1); println!("{}index expr:", ind); print_expr(cx, idx, indent + 1); - } + }, hir::ExprKind::Path(hir::QPath::Resolved(ref ty, path)) => { println!("{}Resolved Path, {:?}", ind, ty); println!("{}path: {:?}", ind, path); - } + }, hir::ExprKind::Path(hir::QPath::TypeRelative(ty, seg)) => { println!("{}Relative Path, {:?}", ind, ty); println!("{}seg: {:?}", ind, seg); - } + }, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, ..)) => { println!("{}Lang Item Path, {:?}", ind, lang_item.name()); - } + }, hir::ExprKind::AddrOf(kind, ref muta, e) => { println!("{}AddrOf", ind); println!("kind: {:?}", kind); println!("mutability: {:?}", muta); print_expr(cx, e, indent + 1); - } + }, hir::ExprKind::Break(_, ref e) => { println!("{}Break", ind); if let Some(e) = *e { print_expr(cx, e, indent + 1); } - } + }, hir::ExprKind::Continue(_) => println!("{}Again", ind), hir::ExprKind::Ret(ref e) => { println!("{}Ret", ind); if let Some(e) = *e { print_expr(cx, e, indent + 1); } - } + }, hir::ExprKind::InlineAsm(asm) => { println!("{}InlineAsm", ind); println!("{}template: {}", ind, InlineAsmTemplatePiece::to_string(asm.template)); @@ -308,20 +311,20 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { if let Some(expr) = expr { print_expr(cx, expr, indent + 1); } - } + }, hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => { print_expr(cx, in_expr, indent + 1); if let Some(out_expr) = out_expr { print_expr(cx, out_expr, indent + 1); } - } + }, hir::InlineAsmOperand::Const { anon_const } => { println!("{}anon_const:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - } + }, } } - } + }, hir::ExprKind::LlvmInlineAsm(asm) => { let inputs = &asm.inputs_exprs; let outputs = &asm.outputs_exprs; @@ -334,7 +337,7 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { for e in outputs.iter() { print_expr(cx, e, indent + 1); } - } + }, hir::ExprKind::Struct(path, fields, ref base) => { println!("{}Struct", ind); println!("{}path: {:?}", ind, path); @@ -346,26 +349,26 @@ fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) { println!("{}base:", ind); print_expr(cx, base, indent + 1); } - } + }, hir::ExprKind::ConstBlock(ref anon_const) => { println!("{}ConstBlock", ind); println!("{}anon_const:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - } + }, hir::ExprKind::Repeat(val, ref anon_const) => { println!("{}Repeat", ind); println!("{}value:", ind); print_expr(cx, val, indent + 1); println!("{}repeat count:", ind); print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1); - } + }, hir::ExprKind::Err => { println!("{}Err", ind); - } + }, hir::ExprKind::DropTemps(e) => { println!("{}DropTemps", ind); print_expr(cx, e, indent + 1); - } + }, } } @@ -394,32 +397,32 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { } else { println!("weird extern crate without a crate id"); } - } + }, hir::ItemKind::Use(path, ref kind) => println!("{:?}, {:?}", path, kind), hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)), hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)), hir::ItemKind::Fn(..) => { let item_ty = cx.tcx.type_of(did); println!("function of type {:#?}", item_ty); - } + }, hir::ItemKind::Mod(..) => println!("module"), hir::ItemKind::ForeignMod { abi, .. } => println!("foreign module with abi: {}", abi), hir::ItemKind::GlobalAsm(asm) => println!("global asm: {:?}", asm), hir::ItemKind::TyAlias(..) => { println!("type alias for {:?}", cx.tcx.type_of(did)); - } + }, hir::ItemKind::OpaqueTy(..) => { println!("existential type with real type {:?}", cx.tcx.type_of(did)); - } + }, hir::ItemKind::Enum(..) => { println!("enum definition of type {:?}", cx.tcx.type_of(did)); - } + }, hir::ItemKind::Struct(..) => { println!("struct definition of type {:?}", cx.tcx.type_of(did)); - } + }, hir::ItemKind::Union(..) => { println!("union definition of type {:?}", cx.tcx.type_of(did)); - } + }, hir::ItemKind::Trait(..) => { println!("trait decl"); if cx.tcx.trait_is_auto(did.to_def_id()) { @@ -427,16 +430,19 @@ fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) { } else { println!("trait is not auto"); } - } + }, hir::ItemKind::TraitAlias(..) => { println!("trait alias"); - } - hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref _trait_ref), .. }) => { + }, + hir::ItemKind::Impl(hir::Impl { + of_trait: Some(ref _trait_ref), + .. + }) => { println!("trait impl"); - } + }, hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) => { println!("impl"); - } + }, } } @@ -455,20 +461,19 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { println!("{}inner:", ind); print_pat(cx, inner, indent + 1); } - } + }, hir::PatKind::Or(fields) => { println!("{}Or", ind); for field in fields { print_pat(cx, field, indent + 1); } - } + }, hir::PatKind::Struct(ref path, fields, ignore) => { println!("{}Struct", ind); println!( "{}name: {}", ind, - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s - .print_qpath(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) ); println!("{}ignore leftover fields: {}", ind, ignore); println!("{}fields:", ind); @@ -479,14 +484,13 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { } print_pat(cx, field.pat, indent + 1); } - } + }, hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => { println!("{}TupleStruct", ind); println!( "{}path: {}", ind, - rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s - .print_qpath(path, false)) + rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)) ); if let Some(dot_position) = opt_dots_position { println!("{}dot position: {}", ind, dot_position); @@ -494,18 +498,18 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for field in fields { print_pat(cx, field, indent + 1); } - } + }, hir::PatKind::Path(hir::QPath::Resolved(ref ty, path)) => { println!("{}Resolved Path, {:?}", ind, ty); println!("{}path: {:?}", ind, path); - } + }, hir::PatKind::Path(hir::QPath::TypeRelative(ty, seg)) => { println!("{}Relative Path, {:?}", ind, ty); println!("{}seg: {:?}", ind, seg); - } + }, hir::PatKind::Path(hir::QPath::LangItem(lang_item, ..)) => { println!("{}Lang Item Path, {:?}", ind, lang_item.name()); - } + }, hir::PatKind::Tuple(pats, opt_dots_position) => { println!("{}Tuple", ind); if let Some(dot_position) = opt_dots_position { @@ -514,20 +518,20 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for field in pats { print_pat(cx, field, indent + 1); } - } + }, hir::PatKind::Box(inner) => { println!("{}Box", ind); print_pat(cx, inner, indent + 1); - } + }, hir::PatKind::Ref(inner, ref muta) => { println!("{}Ref", ind); println!("{}mutability: {:?}", ind, muta); print_pat(cx, inner, indent + 1); - } + }, hir::PatKind::Lit(e) => { println!("{}Lit", ind); print_expr(cx, e, indent + 1); - } + }, hir::PatKind::Range(ref l, ref r, ref range_end) => { println!("{}Range", ind); if let Some(expr) = l { @@ -540,7 +544,7 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { hir::RangeEnd::Included => println!("{} end included", ind), hir::RangeEnd::Excluded => println!("{} end excluded", ind), } - } + }, hir::PatKind::Slice(first_pats, ref range, last_pats) => { println!("{}Slice [a, b, ..i, y, z]", ind); println!("[a, b]:"); @@ -555,7 +559,7 @@ fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) { for pat in last_pats { print_pat(cx, pat, indent + 1); } - } + }, } } @@ -566,11 +570,11 @@ fn print_guard(cx: &LateContext<'_>, guard: &hir::Guard<'_>, indent: usize) { hir::Guard::If(expr) => { println!("{}If", ind); print_expr(cx, expr, indent + 1); - } + }, hir::Guard::IfLet(pat, expr) => { println!("{}IfLet", ind); print_pat(cx, pat, indent + 1); print_expr(cx, expr, indent + 1); - } + }, } } diff --git a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs index c0f90ef42e4d1..cbf0cbd9b7ead 100644 --- a/src/tools/clippy/clippy_lints/src/wildcard_imports.rs +++ b/src/tools/clippy/clippy_lints/src/wildcard_imports.rs @@ -95,7 +95,10 @@ pub struct WildcardImports { impl WildcardImports { pub fn new(warn_on_all: bool) -> Self { - Self { warn_on_all, test_modules_deep: 0 } + Self { + warn_on_all, + test_modules_deep: 0, + } } } diff --git a/src/tools/clippy/clippy_utils/src/usage.rs b/src/tools/clippy/clippy_utils/src/usage.rs index 0224ae310f6b6..871bb9d1edadf 100644 --- a/src/tools/clippy/clippy_utils/src/usage.rs +++ b/src/tools/clippy/clippy_utils/src/usage.rs @@ -10,13 +10,14 @@ use rustc_lint::LateContext; use rustc_middle::hir::map::Map; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty; -use rustc_typeck::expr_use_visitor::{ - ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId, -}; +use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined. pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option { - let mut delegate = MutVarsDelegate { used_mutably: HirIdSet::default(), skip: false }; + let mut delegate = MutVarsDelegate { + used_mutably: HirIdSet::default(), + skip: false, + }; cx.tcx.infer_ctxt().enter(|infcx| { ExprUseVisitor::new( &mut delegate, @@ -34,11 +35,7 @@ pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Some(delegate.used_mutably) } -pub fn is_potentially_mutated<'tcx>( - variable: &'tcx Path<'_>, - expr: &'tcx Expr<'_>, - cx: &LateContext<'tcx>, -) -> bool { +pub fn is_potentially_mutated<'tcx>(variable: &'tcx Path<'_>, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool { if let Res::Local(id) = variable.res { mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id)) } else { @@ -57,14 +54,14 @@ impl<'tcx> MutVarsDelegate { match cat.place.base { PlaceBase::Local(id) => { self.used_mutably.insert(id); - } + }, PlaceBase::Upvar(_) => { //FIXME: This causes false negatives. We can't get the `NodeId` from //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the //`while`-body, not just the ones in the condition. self.skip = true - } - _ => {} + }, + _ => {}, } } } @@ -82,13 +79,7 @@ impl<'tcx> Delegate<'tcx> for MutVarsDelegate { self.update(&cmt) } - fn fake_read( - &mut self, - _: rustc_typeck::expr_use_visitor::Place<'tcx>, - _: FakeReadCause, - _: HirId, - ) { - } + fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {} } pub struct ParamBindingIdCollector { @@ -98,7 +89,9 @@ impl<'tcx> ParamBindingIdCollector { fn collect_binding_hir_ids(body: &'tcx hir::Body<'tcx>) -> Vec { let mut hir_ids: Vec = Vec::new(); for param in body.params.iter() { - let mut finder = ParamBindingIdCollector { binding_hir_ids: Vec::new() }; + let mut finder = ParamBindingIdCollector { + binding_hir_ids: Vec::new(), + }; finder.visit_param(param); for hir_id in &finder.binding_hir_ids { hir_ids.push(*hir_id); @@ -166,7 +159,9 @@ struct ReturnBreakContinueMacroVisitor { impl ReturnBreakContinueMacroVisitor { fn new() -> ReturnBreakContinueMacroVisitor { - ReturnBreakContinueMacroVisitor { seen_return_break_continue: false } + ReturnBreakContinueMacroVisitor { + seen_return_break_continue: false, + } } } @@ -184,7 +179,7 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { match &ex.kind { ExprKind::Ret(..) | ExprKind::Break(..) | ExprKind::Continue(..) => { self.seen_return_break_continue = true; - } + }, // Something special could be done here to handle while or for loop // desugaring, as this will detect a break if there's a while loop // or a for loop inside the expression. @@ -194,7 +189,7 @@ impl<'tcx> Visitor<'tcx> for ReturnBreakContinueMacroVisitor { } else { rustc_hir::intravisit::walk_expr(self, ex); } - } + }, } } } From 70920c6ef2bf10703e463c9822be85df7d0cbea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ali=C3=A9nore=20Bouttefeux?= Date: Tue, 25 May 2021 17:25:23 +0200 Subject: [PATCH 8/8] fix --- src/librustdoc/clean/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 4d638ffcbd859..21c6d2b643900 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1292,7 +1292,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { }; Type::QPath { name: p.segments.last().expect("segments were empty").ident.name, - self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)), + self_def_id: Some(DefId::local(qself.hir_id.owner.def_id.local_def_index)), self_type: box qself.clean(cx), trait_: box resolve_type(cx, trait_path, hir_id), }