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