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