1 use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
6 use rustc_macros::HashStable_Generic;
7 use rustc_span::hygiene::MacroKind;
8 use rustc_span::Symbol;
10 use std::array::IntoIter;
13 /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
14 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
15 #[derive(HashStable_Generic)]
17 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
19 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
23 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
24 #[derive(HashStable_Generic)]
26 /// Constructor function automatically created by a tuple struct/variant.
28 /// Constructor constant automatically created by a unit struct/variant.
30 /// Unusable name in value namespace created by a struct variant.
34 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
35 #[derive(HashStable_Generic)]
36 pub enum NonMacroAttrKind {
37 /// Single-segment attribute defined by the language (`#[inline]`)
39 /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
41 /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
43 /// Single-segment custom attribute registered by a derive macro
44 /// but used before that derive macro was expanded (deprecated).
46 /// Single-segment custom attribute registered with `#[register_attr]`.
50 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
51 #[derive(HashStable_Generic)]
55 /// Refers to the struct itself, `DefKind::Ctor` refers to its constructor if it exists.
59 /// Refers to the variant itself, `DefKind::Ctor` refers to its constructor if it exists.
74 /// Refers to the struct or enum variant's constructor.
75 Ctor(CtorOf, CtorKind),
82 // Not namespaced (or they are, but we don't treat them so)
97 pub fn descr(self, def_id: DefId) -> &'static str {
99 DefKind::Fn => "function",
100 DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => {
103 DefKind::Mod => "module",
104 DefKind::Static => "static",
105 DefKind::Enum => "enum",
106 DefKind::Variant => "variant",
107 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
108 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
109 DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
110 DefKind::Struct => "struct",
111 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
112 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
113 DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
114 panic!("impossible struct constructor")
116 DefKind::OpaqueTy => "opaque type",
117 DefKind::TyAlias => "type alias",
118 DefKind::TraitAlias => "trait alias",
119 DefKind::AssocTy => "associated type",
120 DefKind::Union => "union",
121 DefKind::Trait => "trait",
122 DefKind::ForeignTy => "foreign type",
123 DefKind::AssocFn => "associated function",
124 DefKind::Const => "constant",
125 DefKind::AssocConst => "associated constant",
126 DefKind::TyParam => "type parameter",
127 DefKind::ConstParam => "const parameter",
128 DefKind::Macro(macro_kind) => macro_kind.descr(),
129 DefKind::LifetimeParam => "lifetime parameter",
130 DefKind::Use => "import",
131 DefKind::ForeignMod => "foreign module",
132 DefKind::AnonConst => "constant expression",
133 DefKind::Field => "field",
134 DefKind::Impl => "implementation",
135 DefKind::Closure => "closure",
136 DefKind::Generator => "generator",
137 DefKind::ExternCrate => "extern crate",
138 DefKind::GlobalAsm => "global assembly block",
142 /// Gets an English article for the definition.
143 pub fn article(&self) -> &'static str {
146 | DefKind::AssocConst
152 | DefKind::ExternCrate => "an",
153 DefKind::Macro(macro_kind) => macro_kind.article(),
158 pub fn ns(&self) -> Option<Namespace> {
169 | DefKind::TraitAlias
171 | DefKind::TyParam => Some(Namespace::TypeNS),
175 | DefKind::ConstParam
179 | DefKind::AssocConst => Some(Namespace::ValueNS),
181 DefKind::Macro(..) => Some(Namespace::MacroNS),
186 | DefKind::LifetimeParam
187 | DefKind::ExternCrate
191 | DefKind::ForeignMod
193 | DefKind::Impl => None,
198 /// The resolution of a path or export.
199 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
200 #[derive(HashStable_Generic)]
201 pub enum Res<Id = hir::HirId> {
206 /// `Self`, with both an optional trait and impl `DefId`.
208 /// HACK(min_const_generics): impl self types also have an optional requirement to not mention
209 /// any generic parameters to allow the following with `min_const_generics`:
211 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] {} }
213 /// We do however allow `Self` in repeat expression even if it is generic to not break code
214 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint.
216 /// FIXME(lazy_normalization_consts): Remove this bodge once that feature is stable.
217 SelfTy(Option<DefId> /* trait */, Option<(DefId, bool)> /* impl */),
218 ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
221 SelfCtor(DefId /* impl */), // `DefId` refers to the impl
225 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
231 /// The result of resolving a path before lowering to HIR,
232 /// with "module" segments resolved and associated item
233 /// segments deferred to type checking.
234 /// `base_res` is the resolution of the resolved part of the
235 /// path, `unresolved_segments` is the number of unresolved
239 /// module::Type::AssocX::AssocY::MethodOrAssocType
240 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
241 /// base_res unresolved_segments = 3
243 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
244 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
245 /// base_res unresolved_segments = 2
247 #[derive(Copy, Clone, Debug)]
248 pub struct PartialRes {
249 base_res: Res<NodeId>,
250 unresolved_segments: usize,
255 pub fn new(base_res: Res<NodeId>) -> Self {
256 PartialRes { base_res, unresolved_segments: 0 }
260 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
261 if base_res == Res::Err {
262 unresolved_segments = 0
264 PartialRes { base_res, unresolved_segments }
268 pub fn base_res(&self) -> Res<NodeId> {
273 pub fn unresolved_segments(&self) -> usize {
274 self.unresolved_segments
278 /// Different kinds of symbols don't influence each other.
280 /// Therefore, they have a separate universe (namespace).
281 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
289 pub fn descr(self) -> &'static str {
291 Self::TypeNS => "type",
292 Self::ValueNS => "value",
293 Self::MacroNS => "macro",
298 /// Just a helper ‒ separate structure for each namespace.
299 #[derive(Copy, Clone, Default, Debug)]
300 pub struct PerNS<T> {
307 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
308 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
311 pub fn into_iter(self) -> IntoIter<T, 3> {
312 IntoIter::new([self.value_ns, self.type_ns, self.macro_ns])
315 pub fn iter(&self) -> IntoIter<&T, 3> {
316 IntoIter::new([&self.value_ns, &self.type_ns, &self.macro_ns])
320 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
323 fn index(&self, ns: Namespace) -> &T {
325 Namespace::ValueNS => &self.value_ns,
326 Namespace::TypeNS => &self.type_ns,
327 Namespace::MacroNS => &self.macro_ns,
332 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
333 fn index_mut(&mut self, ns: Namespace) -> &mut T {
335 Namespace::ValueNS => &mut self.value_ns,
336 Namespace::TypeNS => &mut self.type_ns,
337 Namespace::MacroNS => &mut self.macro_ns,
342 impl<T> PerNS<Option<T>> {
343 /// Returns `true` if all the items in this collection are `None`.
344 pub fn is_empty(&self) -> bool {
345 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
348 /// Returns an iterator over the items which are `Some`.
349 pub fn present_items(self) -> impl Iterator<Item = T> {
350 IntoIter::new([self.type_ns, self.value_ns, self.macro_ns]).filter_map(|it| it)
355 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
357 ast::VariantData::Tuple(..) => CtorKind::Fn,
358 ast::VariantData::Unit(..) => CtorKind::Const,
359 ast::VariantData::Struct(..) => CtorKind::Fictive,
363 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
365 hir::VariantData::Tuple(..) => CtorKind::Fn,
366 hir::VariantData::Unit(..) => CtorKind::Const,
367 hir::VariantData::Struct(..) => CtorKind::Fictive,
372 impl NonMacroAttrKind {
373 pub fn descr(self) -> &'static str {
375 NonMacroAttrKind::Builtin(..) => "built-in attribute",
376 NonMacroAttrKind::Tool => "tool attribute",
377 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
378 "derive helper attribute"
380 NonMacroAttrKind::Registered => "explicitly registered attribute",
384 pub fn article(self) -> &'static str {
386 NonMacroAttrKind::Registered => "an",
391 /// Users of some attributes cannot mark them as used, so they are considered always used.
392 pub fn is_used(self) -> bool {
394 NonMacroAttrKind::Tool
395 | NonMacroAttrKind::DeriveHelper
396 | NonMacroAttrKind::DeriveHelperCompat => true,
397 NonMacroAttrKind::Builtin(..) | NonMacroAttrKind::Registered => false,
403 /// Return the `DefId` of this `Def` if it has an ID, else panic.
404 pub fn def_id(&self) -> DefId
409 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
412 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
413 pub fn opt_def_id(&self) -> Option<DefId> {
415 Res::Def(_, id) => Some(id),
422 | Res::NonMacroAttr(..)
427 /// Return the `DefId` of this `Res` if it represents a module.
428 pub fn mod_def_id(&self) -> Option<DefId> {
430 Res::Def(DefKind::Mod, id) => Some(id),
435 /// A human readable name for the res kind ("function", "module", etc.).
436 pub fn descr(&self) -> &'static str {
438 Res::Def(kind, def_id) => kind.descr(def_id),
439 Res::SelfCtor(..) => "self constructor",
440 Res::PrimTy(..) => "builtin type",
441 Res::Local(..) => "local variable",
442 Res::SelfTy(..) => "self type",
443 Res::ToolMod => "tool module",
444 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
445 Res::Err => "unresolved item",
449 /// Gets an English article for the `Res`.
450 pub fn article(&self) -> &'static str {
452 Res::Def(kind, _) => kind.article(),
453 Res::NonMacroAttr(kind) => kind.article(),
459 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
461 Res::Def(kind, id) => Res::Def(kind, id),
462 Res::SelfCtor(id) => Res::SelfCtor(id),
463 Res::PrimTy(id) => Res::PrimTy(id),
464 Res::Local(id) => Res::Local(map(id)),
465 Res::SelfTy(a, b) => Res::SelfTy(a, b),
466 Res::ToolMod => Res::ToolMod,
467 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
468 Res::Err => Res::Err,
472 pub fn macro_kind(self) -> Option<MacroKind> {
474 Res::Def(DefKind::Macro(kind), _) => Some(kind),
475 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
480 /// Returns `None` if this is `Res::Err`
481 pub fn ns(&self) -> Option<Namespace> {
483 Res::Def(kind, ..) => kind.ns(),
484 Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => Some(Namespace::TypeNS),
485 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
486 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
491 /// Always returns `true` if `self` is `Res::Err`
492 pub fn matches_ns(&self, ns: Namespace) -> bool {
493 self.ns().map_or(true, |actual_ns| actual_ns == ns)
496 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
497 pub fn expected_in_tuple_struct_pat(&self) -> bool {
498 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))