rustc_hir/
def.rs

1use std::array::IntoIter;
2use std::fmt::Debug;
3
4use rustc_ast as ast;
5use rustc_ast::NodeId;
6use rustc_data_structures::stable_hasher::ToStableHashKey;
7use rustc_data_structures::unord::UnordMap;
8use rustc_macros::{Decodable, Encodable, HashStable_Generic};
9use rustc_span::Symbol;
10use rustc_span::def_id::{DefId, LocalDefId};
11use rustc_span::hygiene::MacroKind;
12
13use crate::definitions::DefPathData;
14use crate::hir;
15
16/// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
17#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
18pub enum CtorOf {
19    /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
20    Struct,
21    /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
22    Variant,
23}
24
25/// What kind of constructor something is.
26#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
27pub enum CtorKind {
28    /// Constructor function automatically created by a tuple struct/variant.
29    Fn,
30    /// Constructor constant automatically created by a unit struct/variant.
31    Const,
32}
33
34/// An attribute that is not a macro; e.g., `#[inline]` or `#[rustfmt::skip]`.
35#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
36pub enum NonMacroAttrKind {
37    /// Single-segment attribute defined by the language (`#[inline]`)
38    Builtin(Symbol),
39    /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
40    Tool,
41    /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
42    DeriveHelper,
43    /// Single-segment custom attribute registered by a derive macro
44    /// but used before that derive macro was expanded (deprecated).
45    DeriveHelperCompat,
46}
47
48/// What kind of definition something is; e.g., `mod` vs `struct`.
49/// `enum DefPathData` may need to be updated if a new variant is added here.
50#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
51pub enum DefKind {
52    // Type namespace
53    Mod,
54    /// Refers to the struct itself, [`DefKind::Ctor`] refers to its constructor if it exists.
55    Struct,
56    Union,
57    Enum,
58    /// Refers to the variant itself, [`DefKind::Ctor`] refers to its constructor if it exists.
59    Variant,
60    Trait,
61    /// Type alias: `type Foo = Bar;`
62    TyAlias,
63    /// Type from an `extern` block.
64    ForeignTy,
65    /// Trait alias: `trait IntIterator = Iterator<Item = i32>;`
66    TraitAlias,
67    /// Associated type: `trait MyTrait { type Assoc; }`
68    AssocTy,
69    /// Type parameter: the `T` in `struct Vec<T> { ... }`
70    TyParam,
71
72    // Value namespace
73    Fn,
74    Const,
75    /// Constant generic parameter: `struct Foo<const N: usize> { ... }`
76    ConstParam,
77    Static {
78        /// Whether it's a `unsafe static`, `safe static` (inside extern only) or just a `static`.
79        safety: hir::Safety,
80        /// Whether it's a `static mut` or just a `static`.
81        mutability: ast::Mutability,
82        /// Whether it's an anonymous static generated for nested allocations.
83        nested: bool,
84    },
85    /// Refers to the struct or enum variant's constructor.
86    ///
87    /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
88    /// [`DefKind::Variant`] is because structs and enum variants exist
89    /// in the *type* namespace, whereas struct and enum variant *constructors*
90    /// exist in the *value* namespace.
91    ///
92    /// You may wonder why enum variants exist in the type namespace as opposed
93    /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
94    ///
95    /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
96    Ctor(CtorOf, CtorKind),
97    /// Associated function: `impl MyStruct { fn associated() {} }`
98    /// or `trait Foo { fn associated() {} }`
99    AssocFn,
100    /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
101    AssocConst,
102
103    // Macro namespace
104    Macro(MacroKind),
105
106    // Not namespaced (or they are, but we don't treat them so)
107    ExternCrate,
108    Use,
109    /// An `extern` block.
110    ForeignMod,
111    /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`.
112    ///
113    /// Not all anon-consts are actually still relevant in the HIR. We lower
114    /// trivial const-arguments directly to `hir::ConstArgKind::Path`, at which
115    /// point the definition for the anon-const ends up unused and incomplete.
116    ///
117    /// We do not provide any a `Span` for the definition and pretty much all other
118    /// queries also ICE when using this `DefId`. Given that the `DefId` of such
119    /// constants should only be reachable by iterating all definitions of a
120    /// given crate, you should not have to worry about this.
121    AnonConst,
122    /// An inline constant, e.g. `const { 1 + 2 }`
123    InlineConst,
124    /// Opaque type, aka `impl Trait`.
125    OpaqueTy,
126    /// A field in a struct, enum or union. e.g.
127    /// - `bar` in `struct Foo { bar: u8 }`
128    /// - `Foo::Bar::0` in `enum Foo { Bar(u8) }`
129    Field,
130    /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
131    LifetimeParam,
132    /// A use of `global_asm!`.
133    GlobalAsm,
134    Impl {
135        of_trait: bool,
136    },
137    /// A closure, coroutine, or coroutine-closure.
138    ///
139    /// These are all represented with the same `ExprKind::Closure` in the AST and HIR,
140    /// which makes it difficult to distinguish these during def collection. Therefore,
141    /// we treat them all the same, and code which needs to distinguish them can match
142    /// or `hir::ClosureKind` or `type_of`.
143    Closure,
144    /// The definition of a synthetic coroutine body created by the lowering of a
145    /// coroutine-closure, such as an async closure.
146    SyntheticCoroutineBody,
147}
148
149impl DefKind {
150    /// Get an English description for the item's kind.
151    ///
152    /// If you have access to `TyCtxt`, use `TyCtxt::def_descr` or
153    /// `TyCtxt::def_kind_descr` instead, because they give better
154    /// information for coroutines and associated functions.
155    pub fn descr(self, def_id: DefId) -> &'static str {
156        match self {
157            DefKind::Fn => "function",
158            DefKind::Mod if def_id.is_crate_root() && !def_id.is_local() => "crate",
159            DefKind::Mod => "module",
160            DefKind::Static { .. } => "static",
161            DefKind::Enum => "enum",
162            DefKind::Variant => "variant",
163            DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
164            DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
165            DefKind::Struct => "struct",
166            DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
167            DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
168            DefKind::OpaqueTy => "opaque type",
169            DefKind::TyAlias => "type alias",
170            DefKind::TraitAlias => "trait alias",
171            DefKind::AssocTy => "associated type",
172            DefKind::Union => "union",
173            DefKind::Trait => "trait",
174            DefKind::ForeignTy => "foreign type",
175            DefKind::AssocFn => "associated function",
176            DefKind::Const => "constant",
177            DefKind::AssocConst => "associated constant",
178            DefKind::TyParam => "type parameter",
179            DefKind::ConstParam => "const parameter",
180            DefKind::Macro(macro_kind) => macro_kind.descr(),
181            DefKind::LifetimeParam => "lifetime parameter",
182            DefKind::Use => "import",
183            DefKind::ForeignMod => "foreign module",
184            DefKind::AnonConst => "constant expression",
185            DefKind::InlineConst => "inline constant",
186            DefKind::Field => "field",
187            DefKind::Impl { .. } => "implementation",
188            DefKind::Closure => "closure",
189            DefKind::ExternCrate => "extern crate",
190            DefKind::GlobalAsm => "global assembly block",
191            DefKind::SyntheticCoroutineBody => "synthetic mir body",
192        }
193    }
194
195    /// Gets an English article for the definition.
196    ///
197    /// If you have access to `TyCtxt`, use `TyCtxt::def_descr_article` or
198    /// `TyCtxt::def_kind_descr_article` instead, because they give better
199    /// information for coroutines and associated functions.
200    pub fn article(&self) -> &'static str {
201        match *self {
202            DefKind::AssocTy
203            | DefKind::AssocConst
204            | DefKind::AssocFn
205            | DefKind::Enum
206            | DefKind::OpaqueTy
207            | DefKind::Impl { .. }
208            | DefKind::Use
209            | DefKind::InlineConst
210            | DefKind::ExternCrate => "an",
211            DefKind::Macro(macro_kind) => macro_kind.article(),
212            _ => "a",
213        }
214    }
215
216    pub fn ns(&self) -> Option<Namespace> {
217        match self {
218            DefKind::Mod
219            | DefKind::Struct
220            | DefKind::Union
221            | DefKind::Enum
222            | DefKind::Variant
223            | DefKind::Trait
224            | DefKind::TyAlias
225            | DefKind::ForeignTy
226            | DefKind::TraitAlias
227            | DefKind::AssocTy
228            | DefKind::TyParam => Some(Namespace::TypeNS),
229
230            DefKind::Fn
231            | DefKind::Const
232            | DefKind::ConstParam
233            | DefKind::Static { .. }
234            | DefKind::Ctor(..)
235            | DefKind::AssocFn
236            | DefKind::AssocConst => Some(Namespace::ValueNS),
237
238            DefKind::Macro(..) => Some(Namespace::MacroNS),
239
240            // Not namespaced.
241            DefKind::AnonConst
242            | DefKind::InlineConst
243            | DefKind::Field
244            | DefKind::LifetimeParam
245            | DefKind::ExternCrate
246            | DefKind::Closure
247            | DefKind::Use
248            | DefKind::ForeignMod
249            | DefKind::GlobalAsm
250            | DefKind::Impl { .. }
251            | DefKind::OpaqueTy
252            | DefKind::SyntheticCoroutineBody => None,
253        }
254    }
255
256    // Some `DefKind`s require a name, some don't. Panics if one is needed but
257    // not provided. (`AssocTy` is an exception, see below.)
258    pub fn def_path_data(self, name: Option<Symbol>) -> DefPathData {
259        match self {
260            DefKind::Mod
261            | DefKind::Struct
262            | DefKind::Union
263            | DefKind::Enum
264            | DefKind::Variant
265            | DefKind::Trait
266            | DefKind::TyAlias
267            | DefKind::ForeignTy
268            | DefKind::TraitAlias
269            | DefKind::TyParam
270            | DefKind::ExternCrate => DefPathData::TypeNs(name.unwrap()),
271
272            // An associated type name will be missing for an RPITIT.
273            DefKind::AssocTy => {
274                if let Some(name) = name {
275                    DefPathData::TypeNs(name)
276                } else {
277                    DefPathData::AnonAssocTy
278                }
279            }
280
281            // It's not exactly an anon const, but wrt DefPathData, there
282            // is no difference.
283            DefKind::Static { nested: true, .. } => DefPathData::AnonConst,
284            DefKind::Fn
285            | DefKind::Const
286            | DefKind::ConstParam
287            | DefKind::Static { .. }
288            | DefKind::AssocFn
289            | DefKind::AssocConst
290            | DefKind::Field => DefPathData::ValueNs(name.unwrap()),
291            DefKind::Macro(..) => DefPathData::MacroNs(name.unwrap()),
292            DefKind::LifetimeParam => DefPathData::LifetimeNs(name.unwrap()),
293            DefKind::Ctor(..) => DefPathData::Ctor,
294            DefKind::Use => DefPathData::Use,
295            DefKind::ForeignMod => DefPathData::ForeignMod,
296            DefKind::AnonConst => DefPathData::AnonConst,
297            DefKind::InlineConst => DefPathData::AnonConst,
298            DefKind::OpaqueTy => DefPathData::OpaqueTy,
299            DefKind::GlobalAsm => DefPathData::GlobalAsm,
300            DefKind::Impl { .. } => DefPathData::Impl,
301            DefKind::Closure => DefPathData::Closure,
302            DefKind::SyntheticCoroutineBody => DefPathData::SyntheticCoroutineBody,
303        }
304    }
305
306    #[inline]
307    pub fn is_fn_like(self) -> bool {
308        matches!(
309            self,
310            DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::SyntheticCoroutineBody
311        )
312    }
313
314    /// Whether `query get_codegen_attrs` should be used with this definition.
315    pub fn has_codegen_attrs(self) -> bool {
316        match self {
317            DefKind::Fn
318            | DefKind::AssocFn
319            | DefKind::Ctor(..)
320            | DefKind::Closure
321            | DefKind::Static { .. }
322            | DefKind::SyntheticCoroutineBody => true,
323            DefKind::Mod
324            | DefKind::Struct
325            | DefKind::Union
326            | DefKind::Enum
327            | DefKind::Variant
328            | DefKind::Trait
329            | DefKind::TyAlias
330            | DefKind::ForeignTy
331            | DefKind::TraitAlias
332            | DefKind::AssocTy
333            | DefKind::Const
334            | DefKind::AssocConst
335            | DefKind::Macro(..)
336            | DefKind::Use
337            | DefKind::ForeignMod
338            | DefKind::OpaqueTy
339            | DefKind::Impl { .. }
340            | DefKind::Field
341            | DefKind::TyParam
342            | DefKind::ConstParam
343            | DefKind::LifetimeParam
344            | DefKind::AnonConst
345            | DefKind::InlineConst
346            | DefKind::GlobalAsm
347            | DefKind::ExternCrate => false,
348        }
349    }
350}
351
352/// The resolution of a path or export.
353///
354/// For every path or identifier in Rust, the compiler must determine
355/// what the path refers to. This process is called name resolution,
356/// and `Res` is the primary result of name resolution.
357///
358/// For example, everything prefixed with `/* Res */` in this example has
359/// an associated `Res`:
360///
361/// ```
362/// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
363///     /* Res */ String::from(/* Res */ s)
364/// }
365///
366/// /* Res */ str_to_string("hello");
367/// ```
368///
369/// The associated `Res`s will be:
370///
371/// - `str` will resolve to [`Res::PrimTy`];
372/// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
373///   for `String` as defined in the standard library;
374/// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
375///   pointing to `String::from`;
376/// - `s` will resolve to [`Res::Local`];
377/// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
378///   pointing to the definition of `str_to_string` in the current crate.
379//
380#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
381pub enum Res<Id = hir::HirId> {
382    /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
383    ///
384    /// **Not bound to a specific namespace.**
385    Def(DefKind, DefId),
386
387    // Type namespace
388    /// A primitive type such as `i32` or `str`.
389    ///
390    /// **Belongs to the type namespace.**
391    PrimTy(hir::PrimTy),
392
393    /// The `Self` type, as used within a trait.
394    ///
395    /// **Belongs to the type namespace.**
396    ///
397    /// See the examples on [`Res::SelfTyAlias`] for details.
398    SelfTyParam {
399        /// The trait this `Self` is a generic parameter for.
400        trait_: DefId,
401    },
402
403    /// The `Self` type, as used somewhere other than within a trait.
404    ///
405    /// **Belongs to the type namespace.**
406    ///
407    /// Examples:
408    /// ```
409    /// struct Bar(Box<Self>); // SelfTyAlias
410    ///
411    /// trait Foo {
412    ///     fn foo() -> Box<Self>; // SelfTyParam
413    /// }
414    ///
415    /// impl Bar {
416    ///     fn blah() {
417    ///         let _: Self; // SelfTyAlias
418    ///     }
419    /// }
420    ///
421    /// impl Foo for Bar {
422    ///     fn foo() -> Box<Self> { // SelfTyAlias
423    ///         let _: Self;        // SelfTyAlias
424    ///
425    ///         todo!()
426    ///     }
427    /// }
428    /// ```
429    /// *See also [`Res::SelfCtor`].*
430    ///
431    SelfTyAlias {
432        /// The item introducing the `Self` type alias. Can be used in the `type_of` query
433        /// to get the underlying type.
434        alias_to: DefId,
435
436        /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
437        /// anonymous constant).
438        ///
439        /// HACK(min_const_generics): self types also have an optional requirement to **not**
440        /// mention any generic parameters to allow the following with `min_const_generics`:
441        /// ```
442        /// # struct Foo;
443        /// impl Foo { fn test() -> [u8; size_of::<Self>()] { todo!() } }
444        ///
445        /// struct Bar([u8; baz::<Self>()]);
446        /// const fn baz<T>() -> usize { 10 }
447        /// ```
448        /// We do however allow `Self` in repeat expression even if it is generic to not break code
449        /// which already works on stable while causing the `const_evaluatable_unchecked` future
450        /// compat lint:
451        /// ```
452        /// fn foo<T>() {
453        ///     let _bar = [1_u8; size_of::<*mut T>()];
454        /// }
455        /// ```
456        // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
457        forbid_generic: bool,
458
459        /// Is this within an `impl Foo for bar`?
460        is_trait_impl: bool,
461    },
462
463    // Value namespace
464    /// The `Self` constructor, along with the [`DefId`]
465    /// of the impl it is associated with.
466    ///
467    /// **Belongs to the value namespace.**
468    ///
469    /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
470    SelfCtor(DefId),
471
472    /// A local variable or function parameter.
473    ///
474    /// **Belongs to the value namespace.**
475    Local(Id),
476
477    /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
478    ///
479    /// **Belongs to the type namespace.**
480    ToolMod,
481
482    // Macro namespace
483    /// An attribute that is *not* implemented via macro.
484    /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
485    /// as opposed to `#[test]`, which is a builtin macro.
486    ///
487    /// **Belongs to the macro namespace.**
488    NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
489
490    // All namespaces
491    /// Name resolution failed. We use a dummy `Res` variant so later phases
492    /// of the compiler won't crash and can instead report more errors.
493    ///
494    /// **Not bound to a specific namespace.**
495    Err,
496}
497
498/// The result of resolving a path before lowering to HIR,
499/// with "module" segments resolved and associated item
500/// segments deferred to type checking.
501/// `base_res` is the resolution of the resolved part of the
502/// path, `unresolved_segments` is the number of unresolved
503/// segments.
504///
505/// ```text
506/// module::Type::AssocX::AssocY::MethodOrAssocType
507/// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
508/// base_res      unresolved_segments = 3
509///
510/// <T as Trait>::AssocX::AssocY::MethodOrAssocType
511///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
512///       base_res        unresolved_segments = 2
513/// ```
514#[derive(Copy, Clone, Debug)]
515pub struct PartialRes {
516    base_res: Res<NodeId>,
517    unresolved_segments: usize,
518}
519
520impl PartialRes {
521    #[inline]
522    pub fn new(base_res: Res<NodeId>) -> Self {
523        PartialRes { base_res, unresolved_segments: 0 }
524    }
525
526    #[inline]
527    pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
528        if base_res == Res::Err {
529            unresolved_segments = 0
530        }
531        PartialRes { base_res, unresolved_segments }
532    }
533
534    #[inline]
535    pub fn base_res(&self) -> Res<NodeId> {
536        self.base_res
537    }
538
539    #[inline]
540    pub fn unresolved_segments(&self) -> usize {
541        self.unresolved_segments
542    }
543
544    #[inline]
545    pub fn full_res(&self) -> Option<Res<NodeId>> {
546        (self.unresolved_segments == 0).then_some(self.base_res)
547    }
548
549    #[inline]
550    pub fn expect_full_res(&self) -> Res<NodeId> {
551        self.full_res().expect("unexpected unresolved segments")
552    }
553}
554
555/// Different kinds of symbols can coexist even if they share the same textual name.
556/// Therefore, they each have a separate universe (known as a "namespace").
557#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
558#[derive(HashStable_Generic)]
559pub enum Namespace {
560    /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
561    /// (and, by extension, crates).
562    ///
563    /// Note that the type namespace includes other items; this is not an
564    /// exhaustive list.
565    TypeNS,
566    /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
567    ValueNS,
568    /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
569    /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
570    /// like `#[inline]` and `#[rustfmt::skip]`.
571    MacroNS,
572}
573
574impl Namespace {
575    /// The English description of the namespace.
576    pub fn descr(self) -> &'static str {
577        match self {
578            Self::TypeNS => "type",
579            Self::ValueNS => "value",
580            Self::MacroNS => "macro",
581        }
582    }
583}
584
585impl<CTX: crate::HashStableContext> ToStableHashKey<CTX> for Namespace {
586    type KeyType = Namespace;
587
588    #[inline]
589    fn to_stable_hash_key(&self, _: &CTX) -> Namespace {
590        *self
591    }
592}
593
594/// Just a helper ‒ separate structure for each namespace.
595#[derive(Copy, Clone, Default, Debug)]
596pub struct PerNS<T> {
597    pub value_ns: T,
598    pub type_ns: T,
599    pub macro_ns: T,
600}
601
602impl<T> PerNS<T> {
603    pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
604        PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
605    }
606
607    pub fn into_iter(self) -> IntoIter<T, 3> {
608        [self.value_ns, self.type_ns, self.macro_ns].into_iter()
609    }
610
611    pub fn iter(&self) -> IntoIter<&T, 3> {
612        [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
613    }
614}
615
616impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
617    type Output = T;
618
619    fn index(&self, ns: Namespace) -> &T {
620        match ns {
621            Namespace::ValueNS => &self.value_ns,
622            Namespace::TypeNS => &self.type_ns,
623            Namespace::MacroNS => &self.macro_ns,
624        }
625    }
626}
627
628impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
629    fn index_mut(&mut self, ns: Namespace) -> &mut T {
630        match ns {
631            Namespace::ValueNS => &mut self.value_ns,
632            Namespace::TypeNS => &mut self.type_ns,
633            Namespace::MacroNS => &mut self.macro_ns,
634        }
635    }
636}
637
638impl<T> PerNS<Option<T>> {
639    /// Returns `true` if all the items in this collection are `None`.
640    pub fn is_empty(&self) -> bool {
641        self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
642    }
643
644    /// Returns an iterator over the items which are `Some`.
645    pub fn present_items(self) -> impl Iterator<Item = T> {
646        [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
647    }
648}
649
650impl CtorKind {
651    pub fn from_ast(vdata: &ast::VariantData) -> Option<(CtorKind, NodeId)> {
652        match *vdata {
653            ast::VariantData::Tuple(_, node_id) => Some((CtorKind::Fn, node_id)),
654            ast::VariantData::Unit(node_id) => Some((CtorKind::Const, node_id)),
655            ast::VariantData::Struct { .. } => None,
656        }
657    }
658}
659
660impl NonMacroAttrKind {
661    pub fn descr(self) -> &'static str {
662        match self {
663            NonMacroAttrKind::Builtin(..) => "built-in attribute",
664            NonMacroAttrKind::Tool => "tool attribute",
665            NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
666                "derive helper attribute"
667            }
668        }
669    }
670
671    // Currently trivial, but exists in case a new kind is added in the future whose name starts
672    // with a vowel.
673    pub fn article(self) -> &'static str {
674        "a"
675    }
676
677    /// Users of some attributes cannot mark them as used, so they are considered always used.
678    pub fn is_used(self) -> bool {
679        match self {
680            NonMacroAttrKind::Tool
681            | NonMacroAttrKind::DeriveHelper
682            | NonMacroAttrKind::DeriveHelperCompat => true,
683            NonMacroAttrKind::Builtin(..) => false,
684        }
685    }
686}
687
688impl<Id> Res<Id> {
689    /// Return the `DefId` of this `Def` if it has an ID, else panic.
690    pub fn def_id(&self) -> DefId
691    where
692        Id: Debug,
693    {
694        self.opt_def_id().unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}"))
695    }
696
697    /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
698    pub fn opt_def_id(&self) -> Option<DefId> {
699        match *self {
700            Res::Def(_, id) => Some(id),
701
702            Res::Local(..)
703            | Res::PrimTy(..)
704            | Res::SelfTyParam { .. }
705            | Res::SelfTyAlias { .. }
706            | Res::SelfCtor(..)
707            | Res::ToolMod
708            | Res::NonMacroAttr(..)
709            | Res::Err => None,
710        }
711    }
712
713    /// Return the `DefId` of this `Res` if it represents a module.
714    pub fn mod_def_id(&self) -> Option<DefId> {
715        match *self {
716            Res::Def(DefKind::Mod, id) => Some(id),
717            _ => None,
718        }
719    }
720
721    /// A human readable name for the res kind ("function", "module", etc.).
722    pub fn descr(&self) -> &'static str {
723        match *self {
724            Res::Def(kind, def_id) => kind.descr(def_id),
725            Res::SelfCtor(..) => "self constructor",
726            Res::PrimTy(..) => "builtin type",
727            Res::Local(..) => "local variable",
728            Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
729            Res::ToolMod => "tool module",
730            Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
731            Res::Err => "unresolved item",
732        }
733    }
734
735    /// Gets an English article for the `Res`.
736    pub fn article(&self) -> &'static str {
737        match *self {
738            Res::Def(kind, _) => kind.article(),
739            Res::NonMacroAttr(kind) => kind.article(),
740            Res::Err => "an",
741            _ => "a",
742        }
743    }
744
745    pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
746        match self {
747            Res::Def(kind, id) => Res::Def(kind, id),
748            Res::SelfCtor(id) => Res::SelfCtor(id),
749            Res::PrimTy(id) => Res::PrimTy(id),
750            Res::Local(id) => Res::Local(map(id)),
751            Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
752            Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
753                Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
754            }
755            Res::ToolMod => Res::ToolMod,
756            Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
757            Res::Err => Res::Err,
758        }
759    }
760
761    pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
762        Ok(match self {
763            Res::Def(kind, id) => Res::Def(kind, id),
764            Res::SelfCtor(id) => Res::SelfCtor(id),
765            Res::PrimTy(id) => Res::PrimTy(id),
766            Res::Local(id) => Res::Local(map(id)?),
767            Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
768            Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
769                Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
770            }
771            Res::ToolMod => Res::ToolMod,
772            Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
773            Res::Err => Res::Err,
774        })
775    }
776
777    #[track_caller]
778    pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
779        self.map_id(
780            #[track_caller]
781            |_| panic!("unexpected `Res::Local`"),
782        )
783    }
784
785    pub fn macro_kind(self) -> Option<MacroKind> {
786        match self {
787            Res::Def(DefKind::Macro(kind), _) => Some(kind),
788            Res::NonMacroAttr(..) => Some(MacroKind::Attr),
789            _ => None,
790        }
791    }
792
793    /// Returns `None` if this is `Res::Err`
794    pub fn ns(&self) -> Option<Namespace> {
795        match self {
796            Res::Def(kind, ..) => kind.ns(),
797            Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
798                Some(Namespace::TypeNS)
799            }
800            Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
801            Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
802            Res::Err => None,
803        }
804    }
805
806    /// Always returns `true` if `self` is `Res::Err`
807    pub fn matches_ns(&self, ns: Namespace) -> bool {
808        self.ns().is_none_or(|actual_ns| actual_ns == ns)
809    }
810
811    /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
812    pub fn expected_in_tuple_struct_pat(&self) -> bool {
813        matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
814    }
815
816    /// Returns whether such a resolved path can occur in a unit struct/variant pattern
817    pub fn expected_in_unit_struct_pat(&self) -> bool {
818        matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
819    }
820}
821
822/// Resolution for a lifetime appearing in a type.
823#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
824pub enum LifetimeRes {
825    /// Successfully linked the lifetime to a generic parameter.
826    Param {
827        /// Id of the generic parameter that introduced it.
828        param: LocalDefId,
829        /// Id of the introducing place. That can be:
830        /// - an item's id, for the item's generic parameters;
831        /// - a TraitRef's ref_id, identifying the `for<...>` binder;
832        /// - a BareFn type's id.
833        ///
834        /// This information is used for impl-trait lifetime captures, to know when to or not to
835        /// capture any given lifetime.
836        binder: NodeId,
837    },
838    /// Created a generic parameter for an anonymous lifetime.
839    Fresh {
840        /// Id of the generic parameter that introduced it.
841        ///
842        /// Creating the associated `LocalDefId` is the responsibility of lowering.
843        param: NodeId,
844        /// Id of the introducing place. See `Param`.
845        binder: NodeId,
846        /// Kind of elided lifetime
847        kind: hir::MissingLifetimeKind,
848    },
849    /// This variant is used for anonymous lifetimes that we did not resolve during
850    /// late resolution. Those lifetimes will be inferred by typechecking.
851    Infer,
852    /// `'static` lifetime.
853    Static {
854        /// We do not want to emit `elided_named_lifetimes`
855        /// when we are inside of a const item or a static,
856        /// because it would get too annoying.
857        suppress_elision_warning: bool,
858    },
859    /// Resolution failure.
860    Error,
861    /// HACK: This is used to recover the NodeId of an elided lifetime.
862    ElidedAnchor { start: NodeId, end: NodeId },
863}
864
865pub type DocLinkResMap = UnordMap<(Symbol, Namespace), Option<Res<NodeId>>>;