From b92b1a76e175f396d7986177d0a2d5907bbba888 Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Sat, 20 Apr 2019 19:46:19 +0300 Subject: [PATCH] rustc: use DefKind instead of Def, where possible. --- src/librustc/hir/def.rs | 84 ++++++++------ src/librustc/hir/map/mod.rs | 27 ++--- src/librustc/hir/mod.rs | 2 +- src/librustc/middle/reachable.rs | 1 + src/librustc/middle/stability.rs | 8 +- src/librustc/query/mod.rs | 2 +- src/librustc/ty/context.rs | 25 +++-- src/librustc/ty/mod.rs | 20 ++-- src/librustc/ty/query/mod.rs | 2 +- src/librustc_lint/unused.rs | 10 +- src/librustc_metadata/cstore_impl.rs | 2 +- src/librustc_metadata/decoder.rs | 71 ++++++------ src/librustc_mir/const_eval.rs | 6 +- src/librustc_mir/hair/cx/expr.rs | 6 +- src/librustc_mir/interpret/eval_context.rs | 10 +- src/librustc_mir/transform/const_prop.rs | 6 +- src/librustc_mir/util/pretty.rs | 22 ++-- src/librustc_privacy/lib.rs | 30 ++--- src/librustc_resolve/build_reduced_graph.rs | 22 ++-- src/librustc_resolve/diagnostics.rs | 10 +- src/librustc_resolve/lib.rs | 56 +++++----- src/librustc_resolve/macros.rs | 2 +- src/librustc_resolve/resolve_imports.rs | 2 +- src/librustc_typeck/astconv.rs | 94 +++++++--------- src/librustc_typeck/check/demand.rs | 7 +- src/librustc_typeck/check/method/mod.rs | 23 ++-- src/librustc_typeck/check/method/probe.rs | 17 +-- src/librustc_typeck/check/method/suggest.rs | 10 +- src/librustc_typeck/check/mod.rs | 115 ++++++++++++-------- src/librustdoc/clean/mod.rs | 31 ++---- src/librustdoc/core.rs | 15 ++- 31 files changed, 381 insertions(+), 357 deletions(-) diff --git a/src/librustc/hir/def.rs b/src/librustc/hir/def.rs index d4ad4225b99..b9ba1aff8f4 100644 --- a/src/librustc/hir/def.rs +++ b/src/librustc/hir/def.rs @@ -80,6 +80,53 @@ pub enum DefKind { Macro(MacroKind), } +impl DefKind { + pub fn descr(self) -> &'static str { + match self { + DefKind::Fn => "function", + DefKind::Mod => "module", + DefKind::Static => "static", + DefKind::Enum => "enum", + DefKind::Variant => "variant", + DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant", + DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant", + DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant", + DefKind::Struct => "struct", + DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct", + DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct", + DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => + bug!("impossible struct constructor"), + DefKind::Existential => "existential type", + DefKind::TyAlias => "type alias", + DefKind::TraitAlias => "trait alias", + DefKind::AssociatedTy => "associated type", + DefKind::AssociatedExistential => "associated existential type", + DefKind::Union => "union", + DefKind::Trait => "trait", + DefKind::ForeignTy => "foreign type", + DefKind::Method => "method", + DefKind::Const => "constant", + DefKind::AssociatedConst => "associated constant", + DefKind::TyParam => "type parameter", + DefKind::ConstParam => "const parameter", + DefKind::Macro(macro_kind) => macro_kind.descr(), + } + } + + /// An English article for the def. + pub fn article(&self) -> &'static str { + match *self { + DefKind::AssociatedTy + | DefKind::AssociatedConst + | DefKind::AssociatedExistential + | DefKind::Enum + | DefKind::Existential => "an", + DefKind::Macro(macro_kind) => macro_kind.article(), + _ => "a", + } + } +} + #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)] pub enum Def { Def(DefKind, DefId), @@ -328,39 +375,13 @@ pub fn mod_def_id(&self) -> Option { /// A human readable name for the def kind ("function", "module", etc.). pub fn kind_name(&self) -> &'static str { match *self { - Def::Def(DefKind::Fn, _) => "function", - Def::Def(DefKind::Mod, _) => "module", - Def::Def(DefKind::Static, _) => "static", - Def::Def(DefKind::Enum, _) => "enum", - Def::Def(DefKind::Variant, _) => "variant", - Def::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), _) => "tuple variant", - Def::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Const), _) => "unit variant", - Def::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive), _) => "struct variant", - Def::Def(DefKind::Struct, _) => "struct", - Def::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => "tuple struct", - Def::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Const), _) => "unit struct", - Def::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive), _) => - bug!("impossible struct constructor"), - Def::Def(DefKind::Existential, _) => "existential type", - Def::Def(DefKind::TyAlias, _) => "type alias", - Def::Def(DefKind::TraitAlias, _) => "trait alias", - Def::Def(DefKind::AssociatedTy, _) => "associated type", - Def::Def(DefKind::AssociatedExistential, _) => "associated existential type", + Def::Def(kind, _) => kind.descr(), Def::SelfCtor(..) => "self constructor", - Def::Def(DefKind::Union, _) => "union", - Def::Def(DefKind::Trait, _) => "trait", - Def::Def(DefKind::ForeignTy, _) => "foreign type", - Def::Def(DefKind::Method, _) => "method", - Def::Def(DefKind::Const, _) => "constant", - Def::Def(DefKind::AssociatedConst, _) => "associated constant", - Def::Def(DefKind::TyParam, _) => "type parameter", - Def::Def(DefKind::ConstParam, _) => "const parameter", Def::PrimTy(..) => "builtin type", Def::Local(..) => "local variable", Def::Upvar(..) => "closure capture", Def::Label(..) => "label", Def::SelfTy(..) => "self type", - Def::Def(DefKind::Macro(macro_kind), _) => macro_kind.descr(), Def::ToolMod => "tool module", Def::NonMacroAttr(attr_kind) => attr_kind.descr(), Def::Err => "unresolved item", @@ -370,13 +391,8 @@ pub fn kind_name(&self) -> &'static str { /// An English article for the def. pub fn article(&self) -> &'static str { match *self { - Def::Def(DefKind::AssociatedTy, _) - | Def::Def(DefKind::AssociatedConst, _) - | Def::Def(DefKind::AssociatedExistential, _) - | Def::Def(DefKind::Enum, _) - | Def::Def(DefKind::Existential, _) - | Def::Err => "an", - Def::Def(DefKind::Macro(macro_kind), _) => macro_kind.article(), + Def::Def(kind, _) => kind.article(), + Def::Err => "an", _ => "a", } } diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 9251f8e797b..9c895198ddd 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -17,7 +17,7 @@ use syntax_pos::{Span, DUMMY_SP}; use crate::hir::*; -use crate::hir::{Def, DefKind}; +use crate::hir::DefKind; use crate::hir::itemlikevisit::ItemLikeVisitor; use crate::hir::print::Nested; use crate::util::nodemap::FxHashMap; @@ -310,14 +310,14 @@ pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId { self.definitions.as_local_node_id(def_id.to_def_id()).unwrap() } - pub fn describe_def(&self, node_id: NodeId) -> Option { + fn def_kind(&self, node_id: NodeId) -> Option { let node = if let Some(node) = self.find(node_id) { node } else { return None }; - let kind = match node { + Some(match node { Node::Item(item) => { match item.node { ItemKind::Static(..) => DefKind::Static, @@ -382,15 +382,11 @@ pub fn describe_def(&self, node_id: NodeId) -> Option { Node::TraitRef(_) | Node::Pat(_) | Node::Binding(_) | + Node::Local(_) | Node::Lifetime(_) | Node::Visibility(_) | Node::Block(_) | Node::Crate => return None, - // FIXME(eddyb) this is the only non-`DefKind` case here, - // investigate whether it's actually used, and ideally remove it. - Node::Local(local) => { - return Some(Def::Local(local.hir_id)); - } Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang), Node::GenericParam(param) => { match param.kind { @@ -399,14 +395,7 @@ pub fn describe_def(&self, node_id: NodeId) -> Option { GenericParamKind::Const { .. } => DefKind::ConstParam, } } - }; - Some(Def::Def(kind, self.local_def_id(node_id))) - } - - // FIXME(@ljedrz): replace the NodeId variant - pub fn describe_def_by_hir_id(&self, hir_id: HirId) -> Option { - let node_id = self.hir_to_node_id(hir_id); - self.describe_def(node_id) + }) } fn entry_count(&self) -> usize { @@ -1464,11 +1453,11 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String { node_id_to_string(map, node_id, include_id) } -pub fn describe_def(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option { +pub fn def_kind(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option { if let Some(node_id) = tcx.hir().as_local_node_id(def_id) { - tcx.hir().describe_def(node_id) + tcx.hir().def_kind(node_id) } else { - bug!("Calling local describe_def query provider for upstream DefId: {:?}", + bug!("Calling local def_kind query provider for upstream DefId: {:?}", def_id) } } diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index f474ab1a1a5..833983d3576 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -2521,7 +2521,7 @@ pub struct TraitCandidate { pub fn provide(providers: &mut Providers<'_>) { check_attr::provide(providers); - providers.describe_def = map::describe_def; + providers.def_kind = map::def_kind; } #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 8647820d574..a68be387d61 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -98,6 +98,7 @@ fn visit_expr(&mut self, expr: &'tcx hir::Expr) { } hir::ExprKind::MethodCall(..) => { self.tables.type_dependent_def(expr.hir_id) + .map(|(kind, def_id)| Def::Def(kind, def_id)) } _ => None }; diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index e651e82d304..c57b62f42d5 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -525,10 +525,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // See issue #38412. fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool { // Check if `def_id` is a trait method. - match self.describe_def(def_id) { - Some(Def::Def(DefKind::Method, _)) | - Some(Def::Def(DefKind::AssociatedTy, _)) | - Some(Def::Def(DefKind::AssociatedConst, _)) => { + match self.def_kind(def_id) { + Some(DefKind::Method) | + Some(DefKind::AssociatedTy) | + Some(DefKind::AssociatedConst) => { if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container { // Trait methods do not declare visibility (even // for visibility info in cstore). Use containing diff --git a/src/librustc/query/mod.rs b/src/librustc/query/mod.rs index b96ef1b7a86..e1e115cfe17 100644 --- a/src/librustc/query/mod.rs +++ b/src/librustc/query/mod.rs @@ -469,7 +469,7 @@ cache { true } } - query describe_def(_: DefId) -> Option {} + query def_kind(_: DefId) -> Option {} query def_span(_: DefId) -> Span { // FIXME(mw): DefSpans are not really inputs since they are derived from // HIR. But at the moment HIR hashing still contains some hacks that allow diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index 48c3400c597..dfc9e8140bb 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -44,6 +44,7 @@ use crate::ty::subst::{UserSubsts, UnpackedKind}; use crate::ty::{BoundVar, BindingMode}; use crate::ty::CanonicalPolyFnSig; +use crate::util::common::ErrorReported; use crate::util::nodemap::{DefIdMap, DefIdSet, ItemLocalMap, ItemLocalSet}; use crate::util::nodemap::{FxHashMap, FxHashSet}; use errors::DiagnosticBuilder; @@ -347,7 +348,7 @@ pub struct TypeckTables<'tcx> { /// Resolved definitions for `::X` associated paths and /// method calls, including those of overloaded operators. - type_dependent_defs: ItemLocalMap, + type_dependent_defs: ItemLocalMap>, /// Resolved field indices for field accesses in expressions (`S { field }`, `obj.field`) /// or patterns (`S { field }`). The index is often useful by itself, but to learn more @@ -481,30 +482,32 @@ pub fn empty(local_id_root: Option) -> TypeckTables<'tcx> { pub fn qpath_def(&self, qpath: &hir::QPath, id: hir::HirId) -> Def { match *qpath { hir::QPath::Resolved(_, ref path) => path.def, - hir::QPath::TypeRelative(..) => { - validate_hir_id_for_typeck_tables(self.local_id_root, id, false); - self.type_dependent_defs.get(&id.local_id).cloned().unwrap_or(Def::Err) - } + hir::QPath::TypeRelative(..) => self.type_dependent_def(id) + .map_or(Def::Err, |(kind, def_id)| Def::Def(kind, def_id)), } } - pub fn type_dependent_defs(&self) -> LocalTableInContext<'_, Def> { + pub fn type_dependent_defs( + &self, + ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { LocalTableInContext { local_id_root: self.local_id_root, data: &self.type_dependent_defs } } - pub fn type_dependent_def(&self, id: HirId) -> Option { + pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { validate_hir_id_for_typeck_tables(self.local_id_root, id, false); - self.type_dependent_defs.get(&id.local_id).cloned() + self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) } pub fn type_dependent_def_id(&self, id: HirId) -> Option { - self.type_dependent_def(id).map(|def| def.def_id()) + self.type_dependent_def(id).map(|(_, def_id)| def_id) } - pub fn type_dependent_defs_mut(&mut self) -> LocalTableInContextMut<'_, Def> { + pub fn type_dependent_defs_mut( + &mut self, + ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.type_dependent_defs @@ -658,7 +661,7 @@ pub fn is_method_call(&self, expr: &hir::Expr) -> bool { } match self.type_dependent_defs().get(expr.hir_id) { - Some(&Def::Def(DefKind::Method, _)) => true, + Some(Ok((DefKind::Method, _))) => true, _ => false } } diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 3871b465cab..3d08dc67005 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -191,12 +191,12 @@ pub enum AssociatedKind { } impl AssociatedItem { - pub fn def(&self) -> Def { + pub fn def_kind(&self) -> DefKind { match self.kind { - AssociatedKind::Const => Def::Def(DefKind::AssociatedConst, self.def_id), - AssociatedKind::Method => Def::Def(DefKind::Method, self.def_id), - AssociatedKind::Type => Def::Def(DefKind::AssociatedTy, self.def_id), - AssociatedKind::Existential => Def::Def(DefKind::AssociatedExistential, self.def_id), + AssociatedKind::Const => DefKind::AssociatedConst, + AssociatedKind::Method => DefKind::Method, + AssociatedKind::Type => DefKind::AssociatedTy, + AssociatedKind::Existential => DefKind::AssociatedExistential, } } @@ -2805,10 +2805,10 @@ pub fn opt_associated_item(self, def_id: DefId) -> Option { _ => false, } } else { - match self.describe_def(def_id).expect("no def for def-id") { - Def::Def(DefKind::AssociatedConst, _) - | Def::Def(DefKind::Method, _) - | Def::Def(DefKind::AssociatedTy, _) => true, + match self.def_kind(def_id).expect("no def for def-id") { + DefKind::AssociatedConst + | DefKind::Method + | DefKind::AssociatedTy => true, _ => false, } }; @@ -3046,7 +3046,7 @@ pub fn trait_id_of_impl(self, def_id: DefId) -> Option { /// `DefId` of the impl that the method belongs to; otherwise, returns `None`. pub fn impl_of_method(self, def_id: DefId) -> Option { let item = if def_id.krate != LOCAL_CRATE { - if let Some(Def::Def(DefKind::Method, _)) = self.describe_def(def_id) { + if let Some(DefKind::Method) = self.def_kind(def_id) { Some(self.associated_item(def_id)) } else { None diff --git a/src/librustc/ty/query/mod.rs b/src/librustc/ty/query/mod.rs index cd29ca81890..18d575f7364 100644 --- a/src/librustc/ty/query/mod.rs +++ b/src/librustc/ty/query/mod.rs @@ -1,6 +1,6 @@ use crate::dep_graph::{self, DepNode}; use crate::hir::def_id::{CrateNum, DefId, DefIndex}; -use crate::hir::def::{Def, Export}; +use crate::hir::def::{DefKind, Export}; use crate::hir::{self, TraitCandidate, ItemLocalId, CodegenFnAttrs}; use crate::infer::canonical::{self, Canonical}; use crate::lint; diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 9962caf0731..5155ac410aa 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -87,13 +87,14 @@ fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { let mut fn_warned = false; let mut op_warned = false; - let maybe_def = match expr.node { + let maybe_def_id = match expr.node { hir::ExprKind::Call(ref callee, _) => { match callee.node { hir::ExprKind::Path(ref qpath) => { let def = cx.tables.qpath_def(qpath, callee.hir_id); match def { - Def::Def(DefKind::Fn, _) | Def::Def(DefKind::Method, _) => Some(def), + Def::Def(DefKind::Fn, def_id) + | Def::Def(DefKind::Method, def_id) => Some(def_id), // `Def::Local` if it was a closure, for which we // do not currently support must-use linting _ => None @@ -103,12 +104,11 @@ fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { } }, hir::ExprKind::MethodCall(..) => { - cx.tables.type_dependent_def(expr.hir_id) + cx.tables.type_dependent_def_id(expr.hir_id) }, _ => None }; - if let Some(def) = maybe_def { - let def_id = def.def_id(); + if let Some(def_id) = maybe_def_id { fn_warned = check_must_use(cx, def_id, s.span, "return value of ", ""); } else if type_permits_lack_of_use { // We don't warn about unused unit or uninhabited types. diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index b3439e4c970..892a7a8355c 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -138,7 +138,7 @@ fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) } is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) } is_foreign_item => { cdata.is_foreign_item(def_id.index) } static_mutability => { cdata.static_mutability(def_id.index) } - describe_def => { cdata.get_def(def_id.index) } + def_kind => { cdata.def_kind(def_id.index) } def_span => { cdata.get_span(def_id.index, &tcx.sess) } lookup_stability => { cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s)) diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index cc7a72c7593..5e71a74c9bb 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -399,32 +399,32 @@ pub fn list_crate_metadata(&self, } impl<'tcx> EntryKind<'tcx> { - fn to_def(&self, did: DefId) -> Option { + fn def_kind(&self) -> Option { Some(match *self { - EntryKind::Const(..) => Def::Def(DefKind::Const, did), - EntryKind::AssociatedConst(..) => Def::Def(DefKind::AssociatedConst, did), + EntryKind::Const(..) => DefKind::Const, + EntryKind::AssociatedConst(..) => DefKind::AssociatedConst, EntryKind::ImmStatic | EntryKind::MutStatic | EntryKind::ForeignImmStatic | - EntryKind::ForeignMutStatic => Def::Def(DefKind::Static, did), - EntryKind::Struct(_, _) => Def::Def(DefKind::Struct, did), - EntryKind::Union(_, _) => Def::Def(DefKind::Union, did), + EntryKind::ForeignMutStatic => DefKind::Static, + EntryKind::Struct(_, _) => DefKind::Struct, + EntryKind::Union(_, _) => DefKind::Union, EntryKind::Fn(_) | - EntryKind::ForeignFn(_) => Def::Def(DefKind::Fn, did), - EntryKind::Method(_) => Def::Def(DefKind::Method, did), - EntryKind::Type => Def::Def(DefKind::TyAlias, did), - EntryKind::TypeParam => Def::Def(DefKind::TyParam, did), - EntryKind::ConstParam => Def::Def(DefKind::ConstParam, did), - EntryKind::Existential => Def::Def(DefKind::Existential, did), - EntryKind::AssociatedType(_) => Def::Def(DefKind::AssociatedTy, did), - EntryKind::AssociatedExistential(_) => Def::Def(DefKind::AssociatedExistential, did), - EntryKind::Mod(_) => Def::Def(DefKind::Mod, did), - EntryKind::Variant(_) => Def::Def(DefKind::Variant, did), - EntryKind::Trait(_) => Def::Def(DefKind::Trait, did), - EntryKind::TraitAlias(_) => Def::Def(DefKind::TraitAlias, did), - EntryKind::Enum(..) => Def::Def(DefKind::Enum, did), - EntryKind::MacroDef(_) => Def::Def(DefKind::Macro(MacroKind::Bang), did), - EntryKind::ForeignType => Def::Def(DefKind::ForeignTy, did), + EntryKind::ForeignFn(_) => DefKind::Fn, + EntryKind::Method(_) => DefKind::Method, + EntryKind::Type => DefKind::TyAlias, + EntryKind::TypeParam => DefKind::TyParam, + EntryKind::ConstParam => DefKind::ConstParam, + EntryKind::Existential => DefKind::Existential, + EntryKind::AssociatedType(_) => DefKind::AssociatedTy, + EntryKind::AssociatedExistential(_) => DefKind::AssociatedExistential, + EntryKind::Mod(_) => DefKind::Mod, + EntryKind::Variant(_) => DefKind::Variant, + EntryKind::Trait(_) => DefKind::Trait, + EntryKind::TraitAlias(_) => DefKind::TraitAlias, + EntryKind::Enum(..) => DefKind::Enum, + EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang), + EntryKind::ForeignType => DefKind::ForeignTy, EntryKind::ForeignMod | EntryKind::GlobalAsm | @@ -507,12 +507,12 @@ pub fn item_name(&self, item_index: DefIndex) -> InternedString { .expect("no name in item_name") } - pub fn get_def(&self, index: DefIndex) -> Option { + pub fn def_kind(&self, index: DefIndex) -> Option { if !self.is_proc_macro(index) { - self.entry(index).kind.to_def(self.local_def_id(index)) + self.entry(index).kind.def_kind() } else { let kind = self.proc_macros.as_ref().unwrap()[index.to_proc_macro_index()].1.kind(); - Some(Def::Def(DefKind::Macro(kind), self.local_def_id(index))) + Some(DefKind::Macro(kind)) } } @@ -745,10 +745,7 @@ pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Sessio for (id, &(name, ref ext)) in proc_macros.iter().enumerate() { let def = Def::Def( DefKind::Macro(ext.kind()), - DefId { - krate: self.cnum, - index: DefIndex::from_proc_macro_index(id), - }, + self.local_def_id(DefIndex::from_proc_macro_index(id)), ); let ident = Ident::with_empty_ctxt(name); callback(def::Export { @@ -789,9 +786,9 @@ pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Sessio // FIXME(eddyb) Don't encode these in children. EntryKind::ForeignMod => { for child_index in child.children.decode((self, sess)) { - if let Some(def) = self.get_def(child_index) { + if let Some(kind) = self.def_kind(child_index) { callback(def::Export { - def, + def: Def::Def(kind, self.local_def_id(child_index)), ident: Ident::from_interned_str(self.item_name(child_index)), vis: self.get_visibility(child_index), span: self.entry(child_index).span.decode((self, sess)), @@ -807,15 +804,17 @@ pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Sessio let def_key = self.def_key(child_index); let span = child.span.decode((self, sess)); - if let (Some(def), Some(name)) = - (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) { + if let (Some(kind), Some(name)) = + (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name()) { let ident = Ident::from_interned_str(name); let vis = self.get_visibility(child_index); + let def_id = self.local_def_id(child_index); + let def = Def::Def(kind, def_id); callback(def::Export { def, ident, vis, span }); // For non-re-export structs and variants add their constructors to children. // Re-export lists automatically contain constructors when necessary. - match def { - Def::Def(DefKind::Struct, _) => { + match kind { + DefKind::Struct => { if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) { let ctor_kind = self.get_ctor_kind(child_index); let ctor_def = Def::Def( @@ -826,7 +825,7 @@ pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Sessio callback(def::Export { def: ctor_def, vis, ident, span }); } } - Def::Def(DefKind::Variant, def_id) => { + DefKind::Variant => { // Braced variants, unlike structs, generate unusable names in // value namespace, they are reserved for possible future use. // It's ok to use the variant's id as a ctor id since an @@ -845,7 +844,7 @@ pub fn each_child_of_item(&self, id: DefIndex, mut callback: F, sess: &Sessio // were already encoded in metadata. let attrs = self.get_item_attrs(def_id.index, sess); if attr::contains_name(&attrs, "non_exhaustive") { - let crate_def_id = DefId { index: CRATE_DEF_INDEX, ..def_id }; + let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); vis = ty::Visibility::Restricted(crate_def_id); } } diff --git a/src/librustc_mir/const_eval.rs b/src/librustc_mir/const_eval.rs index f4c7b40647c..866b6492d10 100644 --- a/src/librustc_mir/const_eval.rs +++ b/src/librustc_mir/const_eval.rs @@ -6,7 +6,7 @@ use std::hash::Hash; use std::collections::hash_map::Entry; -use rustc::hir::def::{Def, DefKind}; +use rustc::hir::def::DefKind; use rustc::hir::def_id::DefId; use rustc::mir::interpret::{ConstEvalErr, ErrorHandled}; use rustc::mir; @@ -634,14 +634,14 @@ pub fn const_eval_raw_provider<'a, 'tcx>( } } else if def_id.is_local() { // constant defined in this crate, we can figure out a lint level! - match tcx.describe_def(def_id) { + match tcx.def_kind(def_id) { // constants never produce a hard error at the definition site. Anything else is // a backwards compatibility hazard (and will break old versions of winapi for sure) // // note that validation may still cause a hard error on this very same constant, // because any code that existed before validation could not have failed validation // thus preventing such a hard error from being a backwards compatibility hazard - Some(Def::Def(DefKind::Const, _)) | Some(Def::Def(DefKind::AssociatedConst, _)) => { + Some(DefKind::Const) | Some(DefKind::AssociatedConst) => { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); err.report_as_lint( tcx.at(tcx.def_span(def_id)), diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index b1c3cdc9dc8..51bb4134341 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -830,13 +830,13 @@ fn method_callee<'a, 'gcx, 'tcx>( let (def_id, substs, user_ty) = match overloaded_callee { Some((def_id, substs)) => (def_id, substs, None), None => { - let def = cx.tables().type_dependent_def(expr.hir_id) + let (kind, def_id) = cx.tables().type_dependent_def(expr.hir_id) .unwrap_or_else(|| { span_bug!(expr.span, "no type-dependent def for method callee") }); - let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def); + let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &Def::Def(kind, def_id)); debug!("method_callee: user_ty={:?}", user_ty); - (def.def_id(), cx.tables().node_substs(expr.hir_id), user_ty) + (def_id, cx.tables().node_substs(expr.hir_id), user_ty) } }; let ty = cx.tcx().mk_fn_def(def_id, substs); diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 7a8530b31ce..ad4bc6a91f5 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -4,7 +4,7 @@ use syntax::source_map::{self, Span, DUMMY_SP}; use rustc::hir::def_id::DefId; -use rustc::hir::def::{Def, DefKind}; +use rustc::hir::def::DefKind; use rustc::mir; use rustc::ty::layout::{ self, Size, Align, HasDataLayout, LayoutOf, TyLayout @@ -501,11 +501,11 @@ pub fn push_stack_frame( // entry in `locals` should never be used. Make it dead, to be sure. locals[mir::RETURN_PLACE].value = LocalValue::Dead; // Now mark those locals as dead that we do not want to initialize - match self.tcx.describe_def(instance.def_id()) { + match self.tcx.def_kind(instance.def_id()) { // statics and constants don't have `Storage*` statements, no need to look for them - Some(Def::Def(DefKind::Static, _)) - | Some(Def::Def(DefKind::Const, _)) - | Some(Def::Def(DefKind::AssociatedConst, _)) => {}, + Some(DefKind::Static) + | Some(DefKind::Const) + | Some(DefKind::AssociatedConst) => {}, _ => { trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len()); for block in mir.basic_blocks() { diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index a114c18ace8..72af0278201 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -1,7 +1,7 @@ //! Propagates constants for early reporting of statically known //! assertion failures -use rustc::hir::def::{Def, DefKind}; +use rustc::hir::def::DefKind; use rustc::mir::{ Constant, Location, Place, PlaceBase, Mir, Operand, Rvalue, Local, NullOp, UnOp, StatementKind, Statement, LocalKind, Static, StaticKind, @@ -42,8 +42,8 @@ fn run_pass<'a, 'tcx>(&self, .expect("Non-local call to local provider is_const_fn"); let is_fn_like = FnLikeNode::from_node(tcx.hir().get_by_hir_id(hir_id)).is_some(); - let is_assoc_const = match tcx.describe_def(source.def_id()) { - Some(Def::Def(DefKind::AssociatedConst, _)) => true, + let is_assoc_const = match tcx.def_kind(source.def_id()) { + Some(DefKind::AssociatedConst) => true, _ => false, }; diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index 790d3c6624a..94259fa523c 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -575,25 +575,25 @@ fn write_mir_sig( mir: &Mir<'_>, w: &mut dyn Write, ) -> io::Result<()> { - use rustc::hir::def::{Def, DefKind}; + use rustc::hir::def::DefKind; trace!("write_mir_sig: {:?}", src.instance); - let descr = tcx.describe_def(src.def_id()); - let is_function = match descr { - Some(Def::Def(DefKind::Fn, _)) - | Some(Def::Def(DefKind::Method, _)) - | Some(Def::Def(DefKind::Ctor(..), _)) => true, + let kind = tcx.def_kind(src.def_id()); + let is_function = match kind { + Some(DefKind::Fn) + | Some(DefKind::Method) + | Some(DefKind::Ctor(..)) => true, _ => tcx.is_closure(src.def_id()), }; - match (descr, src.promoted) { + match (kind, src.promoted) { (_, Some(i)) => write!(w, "{:?} in ", i)?, - (Some(Def::Def(DefKind::Const, _)), _) - | (Some(Def::Def(DefKind::AssociatedConst, _)), _) => write!(w, "const ")?, - (Some(Def::Def(DefKind::Static, _)), _) => + (Some(DefKind::Const), _) + | (Some(DefKind::AssociatedConst), _) => write!(w, "const ")?, + (Some(DefKind::Static), _) => write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?, (_, _) if is_function => write!(w, "fn ")?, (None, _) => {}, // things like anon const, not an item - _ => bug!("Unexpected def description {:?}", descr), + _ => bug!("Unexpected def kind {:?}", kind), } ty::print::with_forced_impl_filename_line(|| { diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index b971de06bbf..a7e59e8368f 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1105,20 +1105,22 @@ fn visit_expr(&mut self, expr: &'tcx hir::Expr) { // more code internal visibility at link time. (Access to private functions // is already prohibited by type privacy for function types.) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) { - let def = match *qpath { - hir::QPath::Resolved(_, ref path) => match path.def { - Def::Def(DefKind::Method, _) | Def::Def(DefKind::AssociatedConst, _) | - Def::Def(DefKind::AssociatedTy, _) | Def::Def(DefKind::AssociatedExistential, _) | - Def::Def(DefKind::Static, _) => Some(path.def), - _ => None, - } - hir::QPath::TypeRelative(..) => { - self.tables.type_dependent_def(id) - } + let def = match self.tables.qpath_def(qpath, id) { + Def::Def(kind, def_id) => Some((kind, def_id)), + _ => None, }; - if let Some(def) = def { - let def_id = def.def_id(); - let is_local_static = if let Def::Def(DefKind::Static, _) = def { + let def = def.filter(|(kind, _)| { + match kind { + DefKind::Method + | DefKind::AssociatedConst + | DefKind::AssociatedTy + | DefKind::AssociatedExistential + | DefKind::Static => true, + _ => false, + } + }); + if let Some((kind, def_id)) = def { + let is_local_static = if let DefKind::Static = kind { def_id.is_local() } else { false }; if !self.item_is_accessible(def_id) && !is_local_static { @@ -1126,7 +1128,7 @@ fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) { hir::QPath::Resolved(_, ref path) => path.to_string(), hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(), }; - let msg = format!("{} `{}` is private", def.kind_name(), name); + let msg = format!("{} `{}` is private", kind.descr(), name); self.tcx.sess.span_err(span, &msg); return; } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 5c7e51d4057..3be4ff77375 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -193,7 +193,7 @@ fn build_reduced_graph_for_use_tree( if source.ident.name == keywords::DollarCrate.name() && module_path.is_empty() { let crate_root = self.resolve_crate_root(source.ident); let crate_name = match crate_root.kind { - ModuleKind::Def(_, name) => name, + ModuleKind::Def(.., name) => name, ModuleKind::Block(..) => unreachable!(), }; // HACK(eddyb) unclear how good this is, but keeping `$crate` @@ -424,7 +424,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScop ItemKind::Mod(..) => { let def_id = self.definitions.local_def_id(item.id); - let module_kind = ModuleKind::Def(Def::Def(DefKind::Mod, def_id), ident.name); + let module_kind = ModuleKind::Def(DefKind::Mod, def_id, ident.name); let module = self.arenas.alloc_module(ModuleData { no_implicit_prelude: parent.no_implicit_prelude || { attr::contains_name(&item.attrs, "no_implicit_prelude") @@ -487,8 +487,11 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScop } ItemKind::Enum(ref enum_definition, _) => { - let def = Def::Def(DefKind::Enum, self.definitions.local_def_id(item.id)); - let module_kind = ModuleKind::Def(def, ident.name); + let module_kind = ModuleKind::Def( + DefKind::Enum, + self.definitions.local_def_id(item.id), + ident.name, + ); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id, @@ -565,7 +568,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScop let def_id = self.definitions.local_def_id(item.id); // Add all the items within to a new module. - let module_kind = ModuleKind::Def(Def::Def(DefKind::Trait, def_id), ident.name); + let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id, @@ -658,9 +661,10 @@ fn build_reduced_graph_for_external_crate_def( let ident = ident.gensym_if_underscore(); let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene match def { - Def::Def(DefKind::Mod, def_id) | Def::Def(DefKind::Enum, def_id) => { + Def::Def(kind @ DefKind::Mod, def_id) + | Def::Def(kind @ DefKind::Enum, def_id) => { let module = self.new_module(parent, - ModuleKind::Def(def, ident.name), + ModuleKind::Def(kind, def_id, ident.name), def_id, expansion, span); @@ -691,7 +695,7 @@ fn build_reduced_graph_for_external_crate_def( } } Def::Def(DefKind::Trait, def_id) => { - let module_kind = ModuleKind::Def(def, ident.name); + let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id, @@ -746,7 +750,7 @@ pub fn get_module(&mut self, def_id: DefId) -> Module<'a> { Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id }))) }; - let kind = ModuleKind::Def(Def::Def(DefKind::Mod, def_id), name.as_symbol()); + let kind = ModuleKind::Def(DefKind::Mod, def_id, name.as_symbol()); let module = self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP)); self.extern_module_map.insert((def_id, macros_only), module); diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index a86319801dc..0329c78bdf6 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -56,9 +56,9 @@ pub(crate) fn smart_resolve_report_errors( mod_path, Some(TypeNS), false, span, CrateLint::No ) { PathResult::Module(ModuleOrUniformRoot::Module(module)) => - module.def(), + module.def_kind(), _ => None, - }.map_or(String::new(), |def| format!("{} ", def.kind_name())); + }.map_or(String::new(), |kind| format!("{} ", kind.descr())); (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path))) }; (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), @@ -387,9 +387,9 @@ fn smart_resolve_context_dependent_help( return false; } } - (Def::Def(DefKind::Enum, _), PathSource::TupleStruct) - | (Def::Def(DefKind::Enum, _), PathSource::Expr(..)) => { - if let Some(variants) = self.collect_enum_variants(def) { + (Def::Def(DefKind::Enum, def_id), PathSource::TupleStruct) + | (Def::Def(DefKind::Enum, def_id), PathSource::Expr(..)) => { + if let Some(variants) = self.collect_enum_variants(def_id) { if !variants.is_empty() { let msg = if variants.len() == 1 { "try using the enum's variant" diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index f7b8103a521..ad8233fd554 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1133,7 +1133,7 @@ impl ModuleOrUniformRoot<'_> { fn same_def(lhs: Self, rhs: Self) -> bool { match (lhs, rhs) { (ModuleOrUniformRoot::Module(lhs), - ModuleOrUniformRoot::Module(rhs)) => lhs.def() == rhs.def(), + ModuleOrUniformRoot::Module(rhs)) => lhs.def_id() == rhs.def_id(), (ModuleOrUniformRoot::CrateRootAndExternPrelude, ModuleOrUniformRoot::CrateRootAndExternPrelude) | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) | @@ -1177,7 +1177,7 @@ enum ModuleKind { /// * A normal module ‒ either `mod from_file;` or `mod from_block { }`. /// * A trait or an enum (it implicitly contains associated types, methods and variant /// constructors). - Def(Def, Name), + Def(DefKind, DefId, Name), } impl ModuleKind { @@ -1185,7 +1185,7 @@ impl ModuleKind { pub fn name(&self) -> Option { match self { ModuleKind::Block(..) => None, - ModuleKind::Def(_, name) => Some(*name), + ModuleKind::Def(.., name) => Some(*name), } } } @@ -1271,26 +1271,36 @@ fn for_each_child_stable)>(&self, fn def(&self) -> Option { match self.kind { - ModuleKind::Def(def, _) => Some(def), + ModuleKind::Def(kind, def_id, _) => Some(Def::Def(kind, def_id)), + _ => None, + } + } + + fn def_kind(&self) -> Option { + match self.kind { + ModuleKind::Def(kind, ..) => Some(kind), _ => None, } } fn def_id(&self) -> Option { - self.def().as_ref().map(Def::def_id) + match self.kind { + ModuleKind::Def(_, def_id, _) => Some(def_id), + _ => None, + } } // `self` resolves to the first module ancestor that `is_normal`. fn is_normal(&self) -> bool { match self.kind { - ModuleKind::Def(Def::Def(DefKind::Mod, _), _) => true, + ModuleKind::Def(DefKind::Mod, _, _) => true, _ => false, } } fn is_trait(&self) -> bool { match self.kind { - ModuleKind::Def(Def::Def(DefKind::Trait, _), _) => true, + ModuleKind::Def(DefKind::Trait, _, _) => true, _ => false, } } @@ -1477,7 +1487,7 @@ fn is_extern_crate(&self) -> bool { }, .. } => true, NameBindingKind::Module( - &ModuleData { kind: ModuleKind::Def(Def::Def(DefKind::Mod, def_id), _), .. } + &ModuleData { kind: ModuleKind::Def(DefKind::Mod, def_id, _), .. } ) => def_id.index == CRATE_DEF_INDEX, _ => false, } @@ -1938,7 +1948,8 @@ pub fn new(session: &'a Session, -> Resolver<'a> { let root_def_id = DefId::local(CRATE_DEF_INDEX); let root_module_kind = ModuleKind::Def( - Def::Def(DefKind::Mod, root_def_id), + DefKind::Mod, + root_def_id, keywords::Invalid.name(), ); let graph_root = arenas.alloc_module(ModuleData { @@ -4788,10 +4799,7 @@ fn lookup_import_candidates(&mut self, suggestions } - fn find_module(&mut self, - module_def: Def) - -> Option<(Module<'a>, ImportSuggestion)> - { + fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> { let mut result = None; let mut seen_modules = FxHashSet::default(); let mut worklist = vec![(self.graph_root, Vec::new())]; @@ -4811,16 +4819,16 @@ fn find_module(&mut self, // form the path let mut path_segments = path_segments.clone(); path_segments.push(ast::PathSegment::from_ident(ident)); - if module.def() == Some(module_def) { + let module_def_id = module.def_id().unwrap(); + if module_def_id == def_id { let path = Path { span: name_binding.span, segments: path_segments, }; - let did = module.def().and_then(|def| def.opt_def_id()); - result = Some((module, ImportSuggestion { did, path })); + result = Some((module, ImportSuggestion { did: Some(def_id), path })); } else { // add the module to the lookup - if seen_modules.insert(module.def_id().unwrap()) { + if seen_modules.insert(module_def_id) { worklist.push((module, path_segments)); } } @@ -4831,12 +4839,8 @@ fn find_module(&mut self, result } - fn collect_enum_variants(&mut self, enum_def: Def) -> Option> { - if let Def::Def(DefKind::Enum, _) = enum_def {} else { - panic!("Non-enum def passed to collect_enum_variants: {:?}", enum_def) - } - - self.find_module(enum_def).map(|(enum_module, enum_import_suggestion)| { + fn collect_enum_variants(&mut self, def_id: DefId) -> Option> { + self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| { self.populate_module_if_necessary(enum_module); let mut variants = Vec::new(); @@ -5089,8 +5093,8 @@ fn report_conflict<'b>(&mut self, } let container = match parent.kind { - ModuleKind::Def(Def::Def(DefKind::Mod, _), _) => "module", - ModuleKind::Def(Def::Def(DefKind::Trait, _), _) => "trait", + ModuleKind::Def(DefKind::Mod, _, _) => "module", + ModuleKind::Def(DefKind::Trait, _, _) => "trait", ModuleKind::Block(..) => "block", _ => "enum", }; @@ -5458,7 +5462,7 @@ fn module_to_string(module: Module<'_>) -> Option { let mut names = Vec::new(); fn collect_mod(names: &mut Vec, module: Module<'_>) { - if let ModuleKind::Def(_, name) = module.kind { + if let ModuleKind::Def(.., name) = module.kind { if let Some(parent) = module.parent { names.push(Ident::with_empty_ctxt(name)); collect_mod(names, parent); diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index eea48f0711f..3df09369f89 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -140,7 +140,7 @@ impl<'a> Visitor<'a> for ResolveDollarCrates<'a, '_> { fn visit_ident(&mut self, ident: Ident) { if ident.name == keywords::DollarCrate.name() { let name = match self.resolver.resolve_crate_root(ident).kind { - ModuleKind::Def(_, name) if name != keywords::Invalid.name() => name, + ModuleKind::Def(.., name) if name != keywords::Invalid.name() => name, _ => keywords::Crate.name(), }; ident.span.ctxt().set_dollar_crate_name(name); diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 6ad09b2f7e7..7dbc7536440 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -1264,7 +1264,7 @@ fn check_for_redundant_imports( // Skip if we are inside a named module (in contrast to an anonymous // module defined by a block). - if let ModuleKind::Def(_, _) = directive.parent_scope.module.kind { + if let ModuleKind::Def(..) = directive.parent_scope.module.kind { return; } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 8807e1aa62a..241d77c2575 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1314,7 +1314,7 @@ pub fn associated_path_to_ty( qself_def: Def, assoc_segment: &hir::PathSegment, permit_variants: bool, - ) -> (Ty<'tcx>, Def) { + ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> { let tcx = self.tcx(); let assoc_ident = assoc_segment.ident; @@ -1330,13 +1330,12 @@ pub fn associated_path_to_ty( tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did) }); if let Some(variant_def) = variant_def { - let def = Def::Def(DefKind::Variant, variant_def.def_id); if permit_variants { check_type_alias_enum_variants_enabled(tcx, span); tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span); - return (qself_ty, def); + return Ok((qself_ty, DefKind::Variant, variant_def.def_id)); } else { - variant_resolution = Some(def); + variant_resolution = Some(variant_def.def_id); } } } @@ -1352,24 +1351,18 @@ pub fn associated_path_to_ty( Some(trait_ref) => trait_ref, None => { // A cycle error occurred, most likely. - return (tcx.types.err, Def::Err); + return Err(ErrorReported); } }; let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref)) .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident)); - match self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span) { - Ok(bound) => bound, - Err(ErrorReported) => return (tcx.types.err, Def::Err), - } + self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span)? } (&ty::Param(_), Def::SelfTy(Some(param_did), None)) | (&ty::Param(_), Def::Def(DefKind::TyParam, param_did)) => { - match self.find_bound_for_assoc_item(param_did, assoc_ident, span) { - Ok(bound) => bound, - Err(ErrorReported) => return (tcx.types.err, Def::Err), - } + self.find_bound_for_assoc_item(param_did, assoc_ident, span)? } _ => { if variant_resolution.is_some() { @@ -1413,7 +1406,7 @@ pub fn associated_path_to_ty( &assoc_ident.as_str(), ); } - return (tcx.types.err, Def::Err); + return Err(ErrorReported); } }; @@ -1427,14 +1420,14 @@ pub fn associated_path_to_ty( let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound); let ty = self.normalize_ty(span, ty); - let def = Def::Def(DefKind::AssociatedTy, item.def_id); + let kind = DefKind::AssociatedTy; if !item.vis.is_accessible_from(def_scope, tcx) { - let msg = format!("{} `{}` is private", def.kind_name(), assoc_ident); + let msg = format!("{} `{}` is private", kind.descr(), assoc_ident); tcx.sess.span_err(span, &msg); } tcx.check_stability(item.def_id, Some(hir_ref_id), span); - if let Some(variant_def) = variant_resolution { + if let Some(variant_def_id) = variant_resolution { let mut err = tcx.struct_span_lint_hir( AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, @@ -1442,13 +1435,13 @@ pub fn associated_path_to_ty( "ambiguous associated item", ); - let mut could_refer_to = |def: Def, also| { + let mut could_refer_to = |kind: DefKind, def_id, also| { let note_msg = format!("`{}` could{} refer to {} defined here", - assoc_ident, also, def.kind_name()); - err.span_note(tcx.def_span(def.def_id()), ¬e_msg); + assoc_ident, also, kind.descr()); + err.span_note(tcx.def_span(def_id), ¬e_msg); }; - could_refer_to(variant_def, ""); - could_refer_to(def, " also"); + could_refer_to(DefKind::Variant, variant_def_id, ""); + could_refer_to(kind, item.def_id, " also"); err.span_suggestion( span, @@ -1458,7 +1451,7 @@ pub fn associated_path_to_ty( ).emit(); } - (ty, def) + Ok((ty, kind, item.def_id)) } fn qpath_to_ty(&self, @@ -1554,11 +1547,14 @@ pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_, '_, '_>, span: Span) { err.span_label(span, "associated type not allowed here").emit(); } - pub fn def_ids_for_path_segments(&self, - segments: &[hir::PathSegment], - self_ty: Option>, - def: Def) - -> Vec { + // FIXME(eddyb, varkor) handle type paths here too, not just value ones. + pub fn def_ids_for_value_path_segments( + &self, + segments: &[hir::PathSegment], + self_ty: Option>, + kind: DefKind, + def_id: DefId, + ) -> Vec { // We need to extract the type parameters supplied by the user in // the path `path`. Due to the current setup, this is a bit of a // tricky-process; the problem is that resolve only tells us the @@ -1602,10 +1598,6 @@ pub fn def_ids_for_path_segments(&self, // `SomeStruct::`, contains parameters in TypeSpace, and the // final segment, `foo::` contains parameters in fn space. // - // 5. Reference to a local variable - // - // Local variables can't have any type parameters. - // // The first step then is to categorize the segments appropriately. let tcx = self.tcx(); @@ -1615,10 +1607,9 @@ pub fn def_ids_for_path_segments(&self, let mut path_segs = vec![]; - match def { + match kind { // Case 1. Reference to a struct constructor. - Def::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) | - Def::SelfCtor(.., def_id) => { + DefKind::Ctor(CtorOf::Struct, ..) => { // Everything but the final segment should have no // parameters at all. let generics = tcx.generics_of(def_id); @@ -1629,8 +1620,8 @@ pub fn def_ids_for_path_segments(&self, } // Case 2. Reference to a variant constructor. - Def::Def(DefKind::Ctor(CtorOf::Variant, ..), def_id) - | Def::Def(DefKind::Variant, def_id) => { + DefKind::Ctor(CtorOf::Variant, ..) + | DefKind::Variant => { let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap()); let (generics_def_id, index) = if let Some(adt_def) = adt_def { debug_assert!(adt_def.is_enum()); @@ -1641,11 +1632,11 @@ pub fn def_ids_for_path_segments(&self, let mut def_id = def_id; // `DefKind::Ctor` -> `DefKind::Variant` - if let Def::Def(DefKind::Ctor(..), _) = def { + if let DefKind::Ctor(..) = kind { def_id = tcx.parent(def_id).unwrap() } - // `DefKind::Variant` -> `DefKind::Item` (enum) + // `DefKind::Variant` -> `DefKind::Enum` let enum_def_id = tcx.parent(def_id).unwrap(); (enum_def_id, last - 1) } else { @@ -1663,16 +1654,16 @@ pub fn def_ids_for_path_segments(&self, } // Case 3. Reference to a top-level value. - Def::Def(DefKind::Fn, def_id) | - Def::Def(DefKind::Const, def_id) | - Def::Def(DefKind::ConstParam, def_id) | - Def::Def(DefKind::Static, def_id) => { + DefKind::Fn + | DefKind::Const + | DefKind::ConstParam + | DefKind::Static => { path_segs.push(PathSeg(def_id, last)); } // Case 4. Reference to a method or associated const. - Def::Def(DefKind::Method, def_id) | - Def::Def(DefKind::AssociatedConst, def_id) => { + DefKind::Method + | DefKind::AssociatedConst => { if segments.len() >= 2 { let generics = tcx.generics_of(def_id); path_segs.push(PathSeg(generics.parent.unwrap(), last - 1)); @@ -1680,10 +1671,7 @@ pub fn def_ids_for_path_segments(&self, path_segs.push(PathSeg(def_id, last)); } - // Case 5. Local variable, no generics. - Def::Local(..) | Def::Upvar(..) => {} - - _ => bug!("unexpected definition: {:?}", def), + kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), } debug!("path_segs = {:?}", path_segs); @@ -1724,12 +1712,13 @@ pub fn def_to_ty(&self, self.prohibit_generics(path.segments.split_last().unwrap().1); self.ast_path_to_ty(span, did, path.segments.last().unwrap()) } - Def::Def(DefKind::Variant, _) if permit_variants => { + Def::Def(kind @ DefKind::Variant, def_id) if permit_variants => { // Convert "variant type" as if it were a real type. // The resulting `Ty` is type of the variant's enum for now. assert_eq!(opt_self_ty, None); - let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def); + let path_segs = + self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id); let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect(); self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| { @@ -1854,7 +1843,8 @@ pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { } else { Def::Err }; - self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, def, segment, false).0 + self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, def, segment, false) + .map(|(ty, _, _)| ty).unwrap_or(tcx.types.err) } hir::TyKind::Array(ref ty, ref length) => { let length = self.ast_const_to_const(length, tcx.types.usize); diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index 537ea9a4b44..6fe7abda16d 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -5,7 +5,6 @@ use syntax::util::parser::PREC_POSTFIX; use syntax_pos::Span; use rustc::hir; -use rustc::hir::def::{Def, DefKind}; use rustc::hir::Node; use rustc::hir::{print, lowering::is_range_literal}; use rustc::ty::{self, Ty, AssociatedItem}; @@ -206,9 +205,9 @@ pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: // This function checks if the method isn't static and takes other arguments than `self`. fn has_no_input_arg(&self, method: &AssociatedItem) -> bool { - match method.def() { - Def::Def(DefKind::Method, def_id) => { - self.tcx.fn_sig(def_id).inputs().skip_binder().len() == 1 + match method.kind { + ty::AssociatedKind::Method => { + self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1 } _ => false, } diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index b0f0856615d..bbdc7df4441 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -15,7 +15,7 @@ use errors::{Applicability, DiagnosticBuilder}; use rustc_data_structures::sync::Lrc; use rustc::hir; -use rustc::hir::def::{CtorOf, Def, DefKind}; +use rustc::hir::def::{CtorOf, DefKind}; use rustc::hir::def_id::DefId; use rustc::traits; use rustc::ty::subst::{InternalSubsts, SubstsRef}; @@ -53,9 +53,9 @@ pub enum MethodError<'tcx> { // Multiple methods might apply. Ambiguity(Vec), - // Found an applicable method, but it is not visible. The second argument contains a list of + // Found an applicable method, but it is not visible. The third argument contains a list of // not-in-scope traits which may work. - PrivateMatch(Def, Vec), + PrivateMatch(DefKind, DefId, Vec), // Found a `Self: Sized` bound where `Self` is a trait object, also the caller may have // forgotten to import a trait. @@ -400,7 +400,7 @@ pub fn resolve_ufcs( method_name: ast::Ident, self_ty: Ty<'tcx>, expr_id: hir::HirId - ) -> Result> { + ) -> Result<(DefKind, DefId), MethodError<'tcx>> { debug!( "resolve_ufcs: method_name={:?} self_ty={:?} expr_id={:?}", method_name, self_ty, expr_id, @@ -422,12 +422,11 @@ pub fn resolve_ufcs( // them as well. It's ok to use the variant's id as a ctor id since an // error will be reported on any use of such resolution anyway. let ctor_def_id = variant_def.ctor_def_id.unwrap_or(variant_def.def_id); - let def = Def::Def( + tcx.check_stability(ctor_def_id, Some(expr_id), span); + return Ok(( DefKind::Ctor(CtorOf::Variant, variant_def.ctor_kind), ctor_def_id, - ); - tcx.check_stability(def.def_id(), Some(expr_id), span); - return Ok(def); + )); } } } @@ -442,10 +441,10 @@ pub fn resolve_ufcs( .unwrap().insert(import_def_id); } - let def = pick.item.def(); - debug!("resolve_ufcs: def={:?}", def); - tcx.check_stability(def.def_id(), Some(expr_id), span); - Ok(def) + let def_kind = pick.item.def_kind(); + debug!("resolve_ufcs: def_kind={:?}, def_id={:?}", def_kind, pick.item.def_id); + tcx.check_stability(pick.item.def_id, Some(expr_id), span); + Ok((def_kind, pick.item.def_id)) } /// Finds item with name `item_name` defined in impl/trait `def_id` diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 54260f196ce..8c61a127d10 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -6,7 +6,7 @@ use crate::check::autoderef::{self, Autoderef}; use crate::check::FnCtxt; use crate::hir::def_id::DefId; -use crate::hir::def::{Def, DefKind}; +use crate::hir::def::DefKind; use crate::namespace::Namespace; use rustc_data_structures::sync::Lrc; @@ -68,7 +68,7 @@ struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { allow_similar_names: bool, /// Some(candidate) if there is a private candidate - private_candidate: Option, + private_candidate: Option<(DefKind, DefId)>, /// Collects near misses when trait bounds for type parameters are unsatisfied and is only used /// for error reporting @@ -520,7 +520,8 @@ fn push_candidate(&mut self, self.extension_candidates.push(candidate); } } else if self.private_candidate.is_none() { - self.private_candidate = Some(candidate.item.def()); + self.private_candidate = + Some((candidate.item.def_kind(), candidate.item.def_id)); } } @@ -861,9 +862,9 @@ pub fn matches_return_type(&self, method: &ty::AssociatedItem, self_ty: Option>, expected: Ty<'tcx>) -> bool { - match method.def() { - Def::Def(DefKind::Method, def_id) => { - let fty = self.tcx.fn_sig(def_id); + match method.kind { + ty::AssociatedKind::Method => { + let fty = self.tcx.fn_sig(method.def_id); self.probe(|_| { let substs = self.fresh_substs_for_item(self.span, method.def_id); let fty = fty.subst(self.tcx, substs); @@ -1004,8 +1005,8 @@ fn pick(mut self) -> PickResult<'tcx> { _ => vec![], }; - if let Some(def) = private_candidate { - return Err(MethodError::PrivateMatch(def, out_of_scope_traits)); + if let Some((kind, def_id)) = private_candidate { + return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits)); } let lev_candidate = self.probe_for_lev_candidate()?; diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 2c567a86991..eef6627789d 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -483,13 +483,13 @@ macro_rules! report_function { } if let Some(lev_candidate) = lev_candidate { - let def = lev_candidate.def(); + let def_kind = lev_candidate.def_kind(); err.span_suggestion( span, &format!( "there is {} {} with a similar name", - def.article(), - def.kind_name(), + def_kind.article(), + def_kind.descr(), ), lev_candidate.ident.to_string(), Applicability::MaybeIncorrect, @@ -510,9 +510,9 @@ macro_rules! report_function { err.emit(); } - MethodError::PrivateMatch(def, out_of_scope_traits) => { + MethodError::PrivateMatch(kind, _, out_of_scope_traits) => { let mut err = struct_span_err!(self.tcx.sess, span, E0624, - "{} `{}` is private", def.kind_name(), item_name); + "{} `{}` is private", kind.descr(), item_name); self.suggest_valid_traits(&mut err, out_of_scope_traits); err.emit(); } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 47974bc5564..95e20e4e170 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -2149,7 +2149,7 @@ pub fn write_method_call(&self, self.tables .borrow_mut() .type_dependent_defs_mut() - .insert(hir_id, Def::Def(DefKind::Method, method.def_id)); + .insert(hir_id, Ok((DefKind::Method, method.def_id))); self.write_substs(hir_id, method.substs); @@ -4797,13 +4797,22 @@ fn finish_resolving_struct_path(&self, } else { Def::Err }; - let (ty, def) = AstConv::associated_path_to_ty(self, hir_id, path_span, - ty, def, segment, true); + let result = AstConv::associated_path_to_ty( + self, + hir_id, + path_span, + ty, + def, + segment, + true, + ); + let ty = result.map(|(ty, _, _)| ty).unwrap_or(self.tcx().types.err); + let result = result.map(|(_, kind, def_id)| (kind, def_id)); // Write back the new resolution. - self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def); + self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, result); - (def, ty) + (result.map(|(kind, def_id)| Def::Def(kind, def_id)).unwrap_or(Def::Err), ty) } } } @@ -4827,34 +4836,39 @@ pub fn resolve_ty_and_def_ufcs<'b>(&self, (self.to_ty(qself), qself, segment) } }; - if let Some(cached_def) = self.tables.borrow().type_dependent_def(hir_id) { + if let Some(&cached_result) = self.tables.borrow().type_dependent_defs().get(hir_id) { // Return directly on cache hit. This is useful to avoid doubly reporting // errors with default match binding modes. See #44614. - return (cached_def, Some(ty), slice::from_ref(&**item_segment)) + let def = cached_result.map(|(kind, def_id)| Def::Def(kind, def_id)) + .unwrap_or(Def::Err); + return (def, Some(ty), slice::from_ref(&**item_segment)); } let item_name = item_segment.ident; - let def = match self.resolve_ufcs(span, item_name, ty, hir_id) { - Ok(def) => def, - Err(error) => { - let def = match error { - method::MethodError::PrivateMatch(def, _) => def, - _ => Def::Err, - }; - if item_name.name != keywords::Invalid.name() { - self.report_method_error(span, - ty, - item_name, - SelfSource::QPath(qself), - error, - None); - } - def + let result = self.resolve_ufcs(span, item_name, ty, hir_id).or_else(|error| { + let result = match error { + method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)), + _ => Err(ErrorReported), + }; + if item_name.name != keywords::Invalid.name() { + self.report_method_error( + span, + ty, + item_name, + SelfSource::QPath(qself), + error, + None, + ); } - }; + result + }); // Write back the new resolution. - self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def); - (def, Some(ty), slice::from_ref(&**item_segment)) + self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, result); + ( + result.map(|(kind, def_id)| Def::Def(kind, def_id)).unwrap_or(Def::Err), + Some(ty), + slice::from_ref(&**item_segment), + ) } pub fn check_decl_initializer(&self, @@ -5355,7 +5369,11 @@ fn could_remove_semicolon( } // Rewrite `SelfCtor` to `Ctor` - pub fn rewrite_self_ctor(&self, def: Def, span: Span) -> (Def, DefId, Ty<'tcx>) { + pub fn rewrite_self_ctor( + &self, + def: Def, + span: Span, + ) -> Result<(DefKind, DefId, Ty<'tcx>), ErrorReported> { let tcx = self.tcx; if let Def::SelfCtor(impl_def_id) = def { let ty = self.impl_self_ty(span, impl_def_id).ty; @@ -5365,11 +5383,11 @@ pub fn rewrite_self_ctor(&self, def: Def, span: Span) -> (Def, DefId, Ty<'tcx>) Some(adt_def) if adt_def.has_ctor() => { let variant = adt_def.non_enum_variant(); let ctor_def_id = variant.ctor_def_id.unwrap(); - let def = Def::Def( + Ok(( DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id, - ); - (def, ctor_def_id, tcx.type_of(ctor_def_id)) + tcx.type_of(ctor_def_id), + )) } _ => { let mut err = tcx.sess.struct_span_err(span, @@ -5392,16 +5410,19 @@ pub fn rewrite_self_ctor(&self, def: Def, span: Span) -> (Def, DefId, Ty<'tcx>) } err.emit(); - (def, impl_def_id, tcx.types.err) + Err(ErrorReported) } } } else { - let def_id = def.def_id(); - - // The things we are substituting into the type should not contain - // escaping late-bound regions, and nor should the base type scheme. - let ty = tcx.type_of(def_id); - (def, def_id, ty) + match def { + Def::Def(kind, def_id) => { + // The things we are substituting into the type should not contain + // escaping late-bound regions, and nor should the base type scheme. + let ty = tcx.type_of(def_id); + Ok((kind, def_id, ty)) + } + _ => span_bug!(span, "unexpected def in rewrite_self_ctor: {:?}", def), + } } } @@ -5434,13 +5455,17 @@ pub fn instantiate_value_path(&self, _ => {} } - let (def, def_id, ty) = self.rewrite_self_ctor(def, span); - let path_segs = AstConv::def_ids_for_path_segments(self, segments, self_ty, def); + let (kind, def_id, ty) = match self.rewrite_self_ctor(def, span) { + Ok(result) => result, + Err(ErrorReported) => return (tcx.types.err, def), + }; + let path_segs = + AstConv::def_ids_for_value_path_segments(self, segments, self_ty, kind, def_id); let mut user_self_ty = None; let mut is_alias_variant_ctor = false; - match def { - Def::Def(DefKind::Ctor(CtorOf::Variant, _), _) => { + match kind { + DefKind::Ctor(CtorOf::Variant, _) => { if let Some(self_ty) = self_ty { let adt_def = self_ty.ty_adt_def().unwrap(); user_self_ty = Some(UserSelfTy { @@ -5450,10 +5475,10 @@ pub fn instantiate_value_path(&self, is_alias_variant_ctor = true; } } - Def::Def(DefKind::Method, def_id) | - Def::Def(DefKind::AssociatedConst, def_id) => { + DefKind::Method + | DefKind::AssociatedConst => { let container = tcx.associated_item(def_id).container; - debug!("instantiate_value_path: def={:?} container={:?}", def, container); + debug!("instantiate_value_path: def_id={:?} container={:?}", def_id, container); match container { ty::TraitContainer(trait_did) => { callee::check_legal_trait_for_method_call(tcx, span, trait_did) @@ -5643,7 +5668,7 @@ pub fn instantiate_value_path(&self, ty_substituted); self.write_substs(hir_id, substs); - (ty_substituted, def) + (ty_substituted, Def::Def(kind, def_id)) } fn check_rustc_args_require_const(&self, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 95a2664954d..d252a935e35 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2787,11 +2787,10 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { } } TyKind::Path(hir::QPath::Resolved(None, ref path)) => { - if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() { - return new_ty; - } - if let Def::Def(DefKind::TyParam, did) = path.def { + if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() { + return new_ty; + } if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did) { return ImplTrait(bounds); } @@ -2811,7 +2810,7 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { let provided_params = &path.segments.last().expect("segments were empty"); let mut ty_substs = FxHashMap::default(); let mut lt_substs = FxHashMap::default(); - let mut const_substs = FxHashMap::default(); + let mut ct_substs = FxHashMap::default(); provided_params.with_generic_args(|generic_args| { let mut indices: GenericParamCount = Default::default(); for param in generics.params.iter() { @@ -2840,11 +2839,8 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { indices.lifetimes += 1; } hir::GenericParamKind::Type { ref default, .. } => { - let ty_param_def = - Def::Def( - DefKind::TyParam, - cx.tcx.hir().local_def_id_from_hir_id(param.hir_id), - ); + let ty_param_def_id = + cx.tcx.hir().local_def_id_from_hir_id(param.hir_id); let mut j = 0; let type_ = generic_args.args.iter().find_map(|arg| { match arg { @@ -2859,19 +2855,16 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { } }); if let Some(ty) = type_.cloned() { - ty_substs.insert(ty_param_def, ty.clean(cx)); + ty_substs.insert(ty_param_def_id, ty.clean(cx)); } else if let Some(default) = default.clone() { - ty_substs.insert(ty_param_def, + ty_substs.insert(ty_param_def_id, default.into_inner().clean(cx)); } indices.types += 1; } hir::GenericParamKind::Const { .. } => { - let const_param_def = - Def::Def( - DefKind::ConstParam, - cx.tcx.hir().local_def_id_from_hir_id(param.hir_id), - ); + let const_param_def_id = + cx.tcx.hir().local_def_id_from_hir_id(param.hir_id); let mut j = 0; let const_ = generic_args.args.iter().find_map(|arg| { match arg { @@ -2886,7 +2879,7 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { } }); if let Some(ct) = const_.cloned() { - const_substs.insert(const_param_def, ct.clean(cx)); + ct_substs.insert(const_param_def_id, ct.clean(cx)); } // FIXME(const_generics:defaults) indices.consts += 1; @@ -2894,7 +2887,7 @@ fn clean(&self, cx: &DocContext<'_>) -> Type { } } }); - return cx.enter_alias(ty_substs, lt_substs, const_substs, || ty.clean(cx)); + return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx)); } resolve_type(cx, path.clean(cx), self.hir_id) } diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 831adb301ef..5555ea302c9 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -1,7 +1,6 @@ use rustc_lint; use rustc::session::{self, config}; use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CrateNum, LOCAL_CRATE}; -use rustc::hir::def::Def; use rustc::hir::HirId; use rustc::middle::cstore::CrateStore; use rustc::middle::privacy::AccessLevels; @@ -59,12 +58,12 @@ pub struct DocContext<'tcx> { // The current set of type and lifetime substitutions, // for expanding type aliases at the HIR level: - /// Table type parameter definition -> substituted type - pub ty_substs: RefCell>, - /// Table `NodeId` of lifetime parameter definition -> substituted lifetime + /// Table `DefId` of type parameter -> substituted type + pub ty_substs: RefCell>, + /// Table `DefId` of lifetime parameter -> substituted lifetime pub lt_substs: RefCell>, - /// Table node id of const parameter definition -> substituted const - pub ct_substs: RefCell>, + /// Table `DefId` of const parameter -> substituted const + pub ct_substs: RefCell>, /// Table DefId of `impl Trait` in argument position -> bounds pub impl_trait_bounds: RefCell>>, pub send_trait: Option, @@ -91,9 +90,9 @@ pub fn enter_resolver(&self, f: F) -> R /// Call the closure with the given parameters set as /// the substitutions for a type alias' RHS. pub fn enter_alias(&self, - ty_substs: FxHashMap, + ty_substs: FxHashMap, lt_substs: FxHashMap, - ct_substs: FxHashMap, + ct_substs: FxHashMap, f: F) -> R where F: FnOnce() -> R { let (old_tys, old_lts, old_cts) = ( -- 2.44.0