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 (DefPathData::AnonAssocTy),
273            // but those provide their own DefPathData.
274            DefKind::AssocTy => DefPathData::TypeNs(name.unwrap()),
275
276            DefKind::Fn
277            | DefKind::Const
278            | DefKind::ConstParam
279            | DefKind::Static { .. }
280            | DefKind::AssocFn
281            | DefKind::AssocConst
282            | DefKind::Field => DefPathData::ValueNs(name.unwrap()),
283            DefKind::Macro(..) => DefPathData::MacroNs(name.unwrap()),
284            DefKind::LifetimeParam => DefPathData::LifetimeNs(name.unwrap()),
285            DefKind::Ctor(..) => DefPathData::Ctor,
286            DefKind::Use => DefPathData::Use,
287            DefKind::ForeignMod => DefPathData::ForeignMod,
288            DefKind::AnonConst => DefPathData::AnonConst,
289            DefKind::InlineConst => DefPathData::AnonConst,
290            DefKind::OpaqueTy => DefPathData::OpaqueTy,
291            DefKind::GlobalAsm => DefPathData::GlobalAsm,
292            DefKind::Impl { .. } => DefPathData::Impl,
293            DefKind::Closure => DefPathData::Closure,
294            DefKind::SyntheticCoroutineBody => DefPathData::SyntheticCoroutineBody,
295        }
296    }
297
298    #[inline]
299    pub fn is_fn_like(self) -> bool {
300        matches!(
301            self,
302            DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::SyntheticCoroutineBody
303        )
304    }
305
306    /// Whether `query get_codegen_attrs` should be used with this definition.
307    pub fn has_codegen_attrs(self) -> bool {
308        match self {
309            DefKind::Fn
310            | DefKind::AssocFn
311            | DefKind::Ctor(..)
312            | DefKind::Closure
313            | DefKind::Static { .. }
314            | DefKind::SyntheticCoroutineBody => true,
315            DefKind::Mod
316            | DefKind::Struct
317            | DefKind::Union
318            | DefKind::Enum
319            | DefKind::Variant
320            | DefKind::Trait
321            | DefKind::TyAlias
322            | DefKind::ForeignTy
323            | DefKind::TraitAlias
324            | DefKind::AssocTy
325            | DefKind::Const
326            | DefKind::AssocConst
327            | DefKind::Macro(..)
328            | DefKind::Use
329            | DefKind::ForeignMod
330            | DefKind::OpaqueTy
331            | DefKind::Impl { .. }
332            | DefKind::Field
333            | DefKind::TyParam
334            | DefKind::ConstParam
335            | DefKind::LifetimeParam
336            | DefKind::AnonConst
337            | DefKind::InlineConst
338            | DefKind::GlobalAsm
339            | DefKind::ExternCrate => false,
340        }
341    }
342}
343
344/// The resolution of a path or export.
345///
346/// For every path or identifier in Rust, the compiler must determine
347/// what the path refers to. This process is called name resolution,
348/// and `Res` is the primary result of name resolution.
349///
350/// For example, everything prefixed with `/* Res */` in this example has
351/// an associated `Res`:
352///
353/// ```
354/// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
355///     /* Res */ String::from(/* Res */ s)
356/// }
357///
358/// /* Res */ str_to_string("hello");
359/// ```
360///
361/// The associated `Res`s will be:
362///
363/// - `str` will resolve to [`Res::PrimTy`];
364/// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
365///   for `String` as defined in the standard library;
366/// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
367///   pointing to `String::from`;
368/// - `s` will resolve to [`Res::Local`];
369/// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
370///   pointing to the definition of `str_to_string` in the current crate.
371//
372#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
373pub enum Res<Id = hir::HirId> {
374    /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
375    ///
376    /// **Not bound to a specific namespace.**
377    Def(DefKind, DefId),
378
379    // Type namespace
380    /// A primitive type such as `i32` or `str`.
381    ///
382    /// **Belongs to the type namespace.**
383    PrimTy(hir::PrimTy),
384
385    /// The `Self` type, as used within a trait.
386    ///
387    /// **Belongs to the type namespace.**
388    ///
389    /// See the examples on [`Res::SelfTyAlias`] for details.
390    SelfTyParam {
391        /// The trait this `Self` is a generic parameter for.
392        trait_: DefId,
393    },
394
395    /// The `Self` type, as used somewhere other than within a trait.
396    ///
397    /// **Belongs to the type namespace.**
398    ///
399    /// Examples:
400    /// ```
401    /// struct Bar(Box<Self>); // SelfTyAlias
402    ///
403    /// trait Foo {
404    ///     fn foo() -> Box<Self>; // SelfTyParam
405    /// }
406    ///
407    /// impl Bar {
408    ///     fn blah() {
409    ///         let _: Self; // SelfTyAlias
410    ///     }
411    /// }
412    ///
413    /// impl Foo for Bar {
414    ///     fn foo() -> Box<Self> { // SelfTyAlias
415    ///         let _: Self;        // SelfTyAlias
416    ///
417    ///         todo!()
418    ///     }
419    /// }
420    /// ```
421    /// *See also [`Res::SelfCtor`].*
422    ///
423    SelfTyAlias {
424        /// The item introducing the `Self` type alias. Can be used in the `type_of` query
425        /// to get the underlying type.
426        alias_to: DefId,
427
428        /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
429        /// anonymous constant).
430        ///
431        /// HACK(min_const_generics): self types also have an optional requirement to **not**
432        /// mention any generic parameters to allow the following with `min_const_generics`:
433        /// ```
434        /// # struct Foo;
435        /// impl Foo { fn test() -> [u8; size_of::<Self>()] { todo!() } }
436        ///
437        /// struct Bar([u8; baz::<Self>()]);
438        /// const fn baz<T>() -> usize { 10 }
439        /// ```
440        /// We do however allow `Self` in repeat expression even if it is generic to not break code
441        /// which already works on stable while causing the `const_evaluatable_unchecked` future
442        /// compat lint:
443        /// ```
444        /// fn foo<T>() {
445        ///     let _bar = [1_u8; size_of::<*mut T>()];
446        /// }
447        /// ```
448        // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
449        forbid_generic: bool,
450
451        /// Is this within an `impl Foo for bar`?
452        is_trait_impl: bool,
453    },
454
455    // Value namespace
456    /// The `Self` constructor, along with the [`DefId`]
457    /// of the impl it is associated with.
458    ///
459    /// **Belongs to the value namespace.**
460    ///
461    /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
462    SelfCtor(DefId),
463
464    /// A local variable or function parameter.
465    ///
466    /// **Belongs to the value namespace.**
467    Local(Id),
468
469    /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
470    ///
471    /// **Belongs to the type namespace.**
472    ToolMod,
473
474    // Macro namespace
475    /// An attribute that is *not* implemented via macro.
476    /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
477    /// as opposed to `#[test]`, which is a builtin macro.
478    ///
479    /// **Belongs to the macro namespace.**
480    NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
481
482    // All namespaces
483    /// Name resolution failed. We use a dummy `Res` variant so later phases
484    /// of the compiler won't crash and can instead report more errors.
485    ///
486    /// **Not bound to a specific namespace.**
487    Err,
488}
489
490/// The result of resolving a path before lowering to HIR,
491/// with "module" segments resolved and associated item
492/// segments deferred to type checking.
493/// `base_res` is the resolution of the resolved part of the
494/// path, `unresolved_segments` is the number of unresolved
495/// segments.
496///
497/// ```text
498/// module::Type::AssocX::AssocY::MethodOrAssocType
499/// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
500/// base_res      unresolved_segments = 3
501///
502/// <T as Trait>::AssocX::AssocY::MethodOrAssocType
503///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
504///       base_res        unresolved_segments = 2
505/// ```
506#[derive(Copy, Clone, Debug)]
507pub struct PartialRes {
508    base_res: Res<NodeId>,
509    unresolved_segments: usize,
510}
511
512impl PartialRes {
513    #[inline]
514    pub fn new(base_res: Res<NodeId>) -> Self {
515        PartialRes { base_res, unresolved_segments: 0 }
516    }
517
518    #[inline]
519    pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
520        if base_res == Res::Err {
521            unresolved_segments = 0
522        }
523        PartialRes { base_res, unresolved_segments }
524    }
525
526    #[inline]
527    pub fn base_res(&self) -> Res<NodeId> {
528        self.base_res
529    }
530
531    #[inline]
532    pub fn unresolved_segments(&self) -> usize {
533        self.unresolved_segments
534    }
535
536    #[inline]
537    pub fn full_res(&self) -> Option<Res<NodeId>> {
538        (self.unresolved_segments == 0).then_some(self.base_res)
539    }
540
541    #[inline]
542    pub fn expect_full_res(&self) -> Res<NodeId> {
543        self.full_res().expect("unexpected unresolved segments")
544    }
545}
546
547/// Different kinds of symbols can coexist even if they share the same textual name.
548/// Therefore, they each have a separate universe (known as a "namespace").
549#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
550#[derive(HashStable_Generic)]
551pub enum Namespace {
552    /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
553    /// (and, by extension, crates).
554    ///
555    /// Note that the type namespace includes other items; this is not an
556    /// exhaustive list.
557    TypeNS,
558    /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
559    ValueNS,
560    /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
561    /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
562    /// like `#[inline]` and `#[rustfmt::skip]`.
563    MacroNS,
564}
565
566impl Namespace {
567    /// The English description of the namespace.
568    pub fn descr(self) -> &'static str {
569        match self {
570            Self::TypeNS => "type",
571            Self::ValueNS => "value",
572            Self::MacroNS => "macro",
573        }
574    }
575}
576
577impl<CTX: crate::HashStableContext> ToStableHashKey<CTX> for Namespace {
578    type KeyType = Namespace;
579
580    #[inline]
581    fn to_stable_hash_key(&self, _: &CTX) -> Namespace {
582        *self
583    }
584}
585
586/// Just a helper ‒ separate structure for each namespace.
587#[derive(Copy, Clone, Default, Debug)]
588pub struct PerNS<T> {
589    pub value_ns: T,
590    pub type_ns: T,
591    pub macro_ns: T,
592}
593
594impl<T> PerNS<T> {
595    pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
596        PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
597    }
598
599    pub fn into_iter(self) -> IntoIter<T, 3> {
600        [self.value_ns, self.type_ns, self.macro_ns].into_iter()
601    }
602
603    pub fn iter(&self) -> IntoIter<&T, 3> {
604        [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
605    }
606}
607
608impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
609    type Output = T;
610
611    fn index(&self, ns: Namespace) -> &T {
612        match ns {
613            Namespace::ValueNS => &self.value_ns,
614            Namespace::TypeNS => &self.type_ns,
615            Namespace::MacroNS => &self.macro_ns,
616        }
617    }
618}
619
620impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
621    fn index_mut(&mut self, ns: Namespace) -> &mut T {
622        match ns {
623            Namespace::ValueNS => &mut self.value_ns,
624            Namespace::TypeNS => &mut self.type_ns,
625            Namespace::MacroNS => &mut self.macro_ns,
626        }
627    }
628}
629
630impl<T> PerNS<Option<T>> {
631    /// Returns `true` if all the items in this collection are `None`.
632    pub fn is_empty(&self) -> bool {
633        self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
634    }
635
636    /// Returns an iterator over the items which are `Some`.
637    pub fn present_items(self) -> impl Iterator<Item = T> {
638        [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
639    }
640}
641
642impl CtorKind {
643    pub fn from_ast(vdata: &ast::VariantData) -> Option<(CtorKind, NodeId)> {
644        match *vdata {
645            ast::VariantData::Tuple(_, node_id) => Some((CtorKind::Fn, node_id)),
646            ast::VariantData::Unit(node_id) => Some((CtorKind::Const, node_id)),
647            ast::VariantData::Struct { .. } => None,
648        }
649    }
650}
651
652impl NonMacroAttrKind {
653    pub fn descr(self) -> &'static str {
654        match self {
655            NonMacroAttrKind::Builtin(..) => "built-in attribute",
656            NonMacroAttrKind::Tool => "tool attribute",
657            NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
658                "derive helper attribute"
659            }
660        }
661    }
662
663    // Currently trivial, but exists in case a new kind is added in the future whose name starts
664    // with a vowel.
665    pub fn article(self) -> &'static str {
666        "a"
667    }
668
669    /// Users of some attributes cannot mark them as used, so they are considered always used.
670    pub fn is_used(self) -> bool {
671        match self {
672            NonMacroAttrKind::Tool
673            | NonMacroAttrKind::DeriveHelper
674            | NonMacroAttrKind::DeriveHelperCompat => true,
675            NonMacroAttrKind::Builtin(..) => false,
676        }
677    }
678}
679
680impl<Id> Res<Id> {
681    /// Return the `DefId` of this `Def` if it has an ID, else panic.
682    pub fn def_id(&self) -> DefId
683    where
684        Id: Debug,
685    {
686        self.opt_def_id().unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}"))
687    }
688
689    /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
690    pub fn opt_def_id(&self) -> Option<DefId> {
691        match *self {
692            Res::Def(_, id) => Some(id),
693
694            Res::Local(..)
695            | Res::PrimTy(..)
696            | Res::SelfTyParam { .. }
697            | Res::SelfTyAlias { .. }
698            | Res::SelfCtor(..)
699            | Res::ToolMod
700            | Res::NonMacroAttr(..)
701            | Res::Err => None,
702        }
703    }
704
705    /// Return the `DefId` of this `Res` if it represents a module.
706    pub fn mod_def_id(&self) -> Option<DefId> {
707        match *self {
708            Res::Def(DefKind::Mod, id) => Some(id),
709            _ => None,
710        }
711    }
712
713    /// A human readable name for the res kind ("function", "module", etc.).
714    pub fn descr(&self) -> &'static str {
715        match *self {
716            Res::Def(kind, def_id) => kind.descr(def_id),
717            Res::SelfCtor(..) => "self constructor",
718            Res::PrimTy(..) => "builtin type",
719            Res::Local(..) => "local variable",
720            Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
721            Res::ToolMod => "tool module",
722            Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
723            Res::Err => "unresolved item",
724        }
725    }
726
727    /// Gets an English article for the `Res`.
728    pub fn article(&self) -> &'static str {
729        match *self {
730            Res::Def(kind, _) => kind.article(),
731            Res::NonMacroAttr(kind) => kind.article(),
732            Res::Err => "an",
733            _ => "a",
734        }
735    }
736
737    pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
738        match self {
739            Res::Def(kind, id) => Res::Def(kind, id),
740            Res::SelfCtor(id) => Res::SelfCtor(id),
741            Res::PrimTy(id) => Res::PrimTy(id),
742            Res::Local(id) => Res::Local(map(id)),
743            Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
744            Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
745                Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
746            }
747            Res::ToolMod => Res::ToolMod,
748            Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
749            Res::Err => Res::Err,
750        }
751    }
752
753    pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
754        Ok(match self {
755            Res::Def(kind, id) => Res::Def(kind, id),
756            Res::SelfCtor(id) => Res::SelfCtor(id),
757            Res::PrimTy(id) => Res::PrimTy(id),
758            Res::Local(id) => Res::Local(map(id)?),
759            Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
760            Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
761                Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
762            }
763            Res::ToolMod => Res::ToolMod,
764            Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
765            Res::Err => Res::Err,
766        })
767    }
768
769    #[track_caller]
770    pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
771        self.map_id(
772            #[track_caller]
773            |_| panic!("unexpected `Res::Local`"),
774        )
775    }
776
777    pub fn macro_kind(self) -> Option<MacroKind> {
778        match self {
779            Res::Def(DefKind::Macro(kind), _) => Some(kind),
780            Res::NonMacroAttr(..) => Some(MacroKind::Attr),
781            _ => None,
782        }
783    }
784
785    /// Returns `None` if this is `Res::Err`
786    pub fn ns(&self) -> Option<Namespace> {
787        match self {
788            Res::Def(kind, ..) => kind.ns(),
789            Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
790                Some(Namespace::TypeNS)
791            }
792            Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
793            Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
794            Res::Err => None,
795        }
796    }
797
798    /// Always returns `true` if `self` is `Res::Err`
799    pub fn matches_ns(&self, ns: Namespace) -> bool {
800        self.ns().is_none_or(|actual_ns| actual_ns == ns)
801    }
802
803    /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
804    pub fn expected_in_tuple_struct_pat(&self) -> bool {
805        matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
806    }
807
808    /// Returns whether such a resolved path can occur in a unit struct/variant pattern
809    pub fn expected_in_unit_struct_pat(&self) -> bool {
810        matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
811    }
812}
813
814/// Resolution for a lifetime appearing in a type.
815#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
816pub enum LifetimeRes {
817    /// Successfully linked the lifetime to a generic parameter.
818    Param {
819        /// Id of the generic parameter that introduced it.
820        param: LocalDefId,
821        /// Id of the introducing place. That can be:
822        /// - an item's id, for the item's generic parameters;
823        /// - a TraitRef's ref_id, identifying the `for<...>` binder;
824        /// - a BareFn type's id.
825        ///
826        /// This information is used for impl-trait lifetime captures, to know when to or not to
827        /// capture any given lifetime.
828        binder: NodeId,
829    },
830    /// Created a generic parameter for an anonymous lifetime.
831    Fresh {
832        /// Id of the generic parameter that introduced it.
833        ///
834        /// Creating the associated `LocalDefId` is the responsibility of lowering.
835        param: NodeId,
836        /// Id of the introducing place. See `Param`.
837        binder: NodeId,
838        /// Kind of elided lifetime
839        kind: hir::MissingLifetimeKind,
840    },
841    /// This variant is used for anonymous lifetimes that we did not resolve during
842    /// late resolution. Those lifetimes will be inferred by typechecking.
843    Infer,
844    /// `'static` lifetime.
845    Static {
846        /// We do not want to emit `elided_named_lifetimes`
847        /// when we are inside of a const item or a static,
848        /// because it would get too annoying.
849        suppress_elision_warning: bool,
850    },
851    /// Resolution failure.
852    Error,
853    /// HACK: This is used to recover the NodeId of an elided lifetime.
854    ElidedAnchor { start: NodeId, end: NodeId },
855}
856
857pub type DocLinkResMap = UnordMap<(Symbol, Namespace), Option<Res<NodeId>>>;