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