]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/def.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[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 }
32
33 /// An attribute that is not a macro; e.g., `#[inline]` or `#[rustfmt::skip]`.
34 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
35 #[derive(HashStable_Generic)]
36 pub 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 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
50 #[derive(HashStable_Generic)]
51 pub 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(ast::Mutability),
78     /// Refers to the struct or enum variant's constructor.
79     ///
80     /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
81     /// [`DefKind::Variant`] is because structs and enum variants exist
82     /// in the *type* namespace, whereas struct and enum variant *constructors*
83     /// exist in the *value* namespace.
84     ///
85     /// You may wonder why enum variants exist in the type namespace as opposed
86     /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
87     ///
88     /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
89     Ctor(CtorOf, CtorKind),
90     /// Associated function: `impl MyStruct { fn associated() {} }`
91     /// or `trait Foo { fn associated() {} }`
92     AssocFn,
93     /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
94     AssocConst,
95
96     // Macro namespace
97     Macro(MacroKind),
98
99     // Not namespaced (or they are, but we don't treat them so)
100     ExternCrate,
101     Use,
102     /// An `extern` block.
103     ForeignMod,
104     /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`
105     AnonConst,
106     /// An inline constant, e.g. `const { 1 + 2 }`
107     InlineConst,
108     /// Opaque type, aka `impl Trait`.
109     OpaqueTy,
110     /// A return-position `impl Trait` in a trait definition
111     ImplTraitPlaceholder,
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::Struct => "struct",
134             DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
135             DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
136             DefKind::OpaqueTy => "opaque type",
137             DefKind::ImplTraitPlaceholder => "opaque type in trait",
138             DefKind::TyAlias => "type alias",
139             DefKind::TraitAlias => "trait alias",
140             DefKind::AssocTy => "associated type",
141             DefKind::Union => "union",
142             DefKind::Trait => "trait",
143             DefKind::ForeignTy => "foreign type",
144             DefKind::AssocFn => "associated function",
145             DefKind::Const => "constant",
146             DefKind::AssocConst => "associated constant",
147             DefKind::TyParam => "type parameter",
148             DefKind::ConstParam => "const parameter",
149             DefKind::Macro(macro_kind) => macro_kind.descr(),
150             DefKind::LifetimeParam => "lifetime parameter",
151             DefKind::Use => "import",
152             DefKind::ForeignMod => "foreign module",
153             DefKind::AnonConst => "constant expression",
154             DefKind::InlineConst => "inline constant",
155             DefKind::Field => "field",
156             DefKind::Impl => "implementation",
157             DefKind::Closure => "closure",
158             DefKind::Generator => "generator",
159             DefKind::ExternCrate => "extern crate",
160             DefKind::GlobalAsm => "global assembly block",
161         }
162     }
163
164     /// Gets an English article for the definition.
165     pub fn article(&self) -> &'static str {
166         match *self {
167             DefKind::AssocTy
168             | DefKind::AssocConst
169             | DefKind::AssocFn
170             | DefKind::Enum
171             | DefKind::OpaqueTy
172             | DefKind::Impl
173             | DefKind::Use
174             | DefKind::InlineConst
175             | DefKind::ExternCrate => "an",
176             DefKind::Macro(macro_kind) => macro_kind.article(),
177             _ => "a",
178         }
179     }
180
181     pub fn ns(&self) -> Option<Namespace> {
182         match self {
183             DefKind::Mod
184             | DefKind::Struct
185             | DefKind::Union
186             | DefKind::Enum
187             | DefKind::Variant
188             | DefKind::Trait
189             | DefKind::OpaqueTy
190             | DefKind::TyAlias
191             | DefKind::ForeignTy
192             | DefKind::TraitAlias
193             | DefKind::AssocTy
194             | DefKind::TyParam => Some(Namespace::TypeNS),
195
196             DefKind::Fn
197             | DefKind::Const
198             | DefKind::ConstParam
199             | DefKind::Static(..)
200             | DefKind::Ctor(..)
201             | DefKind::AssocFn
202             | DefKind::AssocConst => Some(Namespace::ValueNS),
203
204             DefKind::Macro(..) => Some(Namespace::MacroNS),
205
206             // Not namespaced.
207             DefKind::AnonConst
208             | DefKind::InlineConst
209             | DefKind::Field
210             | DefKind::LifetimeParam
211             | DefKind::ExternCrate
212             | DefKind::Closure
213             | DefKind::Generator
214             | DefKind::Use
215             | DefKind::ForeignMod
216             | DefKind::GlobalAsm
217             | DefKind::Impl
218             | DefKind::ImplTraitPlaceholder => None,
219         }
220     }
221
222     #[inline]
223     pub fn is_fn_like(self) -> bool {
224         match self {
225             DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true,
226             _ => false,
227         }
228     }
229
230     /// Whether `query get_codegen_attrs` should be used with this definition.
231     pub fn has_codegen_attrs(self) -> bool {
232         match self {
233             DefKind::Fn
234             | DefKind::AssocFn
235             | DefKind::Ctor(..)
236             | DefKind::Closure
237             | DefKind::Generator
238             | DefKind::Static(_) => true,
239             DefKind::Mod
240             | DefKind::Struct
241             | DefKind::Union
242             | DefKind::Enum
243             | DefKind::Variant
244             | DefKind::Trait
245             | DefKind::TyAlias
246             | DefKind::ForeignTy
247             | DefKind::TraitAlias
248             | DefKind::AssocTy
249             | DefKind::Const
250             | DefKind::AssocConst
251             | DefKind::Macro(..)
252             | DefKind::Use
253             | DefKind::ForeignMod
254             | DefKind::OpaqueTy
255             | DefKind::ImplTraitPlaceholder
256             | DefKind::Impl
257             | DefKind::Field
258             | DefKind::TyParam
259             | DefKind::ConstParam
260             | DefKind::LifetimeParam
261             | DefKind::AnonConst
262             | DefKind::InlineConst
263             | DefKind::GlobalAsm
264             | DefKind::ExternCrate => false,
265         }
266     }
267 }
268
269 /// The resolution of a path or export.
270 ///
271 /// For every path or identifier in Rust, the compiler must determine
272 /// what the path refers to. This process is called name resolution,
273 /// and `Res` is the primary result of name resolution.
274 ///
275 /// For example, everything prefixed with `/* Res */` in this example has
276 /// an associated `Res`:
277 ///
278 /// ```
279 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
280 ///     /* Res */ String::from(/* Res */ s)
281 /// }
282 ///
283 /// /* Res */ str_to_string("hello");
284 /// ```
285 ///
286 /// The associated `Res`s will be:
287 ///
288 /// - `str` will resolve to [`Res::PrimTy`];
289 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
290 ///   for `String` as defined in the standard library;
291 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
292 ///   pointing to `String::from`;
293 /// - `s` will resolve to [`Res::Local`];
294 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
295 ///   pointing to the definition of `str_to_string` in the current crate.
296 //
297 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
298 #[derive(HashStable_Generic)]
299 pub enum Res<Id = hir::HirId> {
300     /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
301     ///
302     /// **Not bound to a specific namespace.**
303     Def(DefKind, DefId),
304
305     // Type namespace
306     /// A primitive type such as `i32` or `str`.
307     ///
308     /// **Belongs to the type namespace.**
309     PrimTy(hir::PrimTy),
310
311     /// The `Self` type, as used within a trait.
312     ///
313     /// **Belongs to the type namespace.**
314     ///
315     /// See the examples on [`Res::SelfTyAlias`] for details.
316     SelfTyParam {
317         /// The trait this `Self` is a generic parameter for.
318         trait_: DefId,
319     },
320
321     /// The `Self` type, as used somewhere other than within a trait.
322     ///
323     /// **Belongs to the type namespace.**
324     ///
325     /// Examples:
326     /// ```
327     /// struct Bar(Box<Self>); // SelfTyAlias
328     ///
329     /// trait Foo {
330     ///     fn foo() -> Box<Self>; // SelfTyParam
331     /// }
332     ///
333     /// impl Bar {
334     ///     fn blah() {
335     ///         let _: Self; // SelfTyAlias
336     ///     }
337     /// }
338     ///
339     /// impl Foo for Bar {
340     ///     fn foo() -> Box<Self> { // SelfTyAlias
341     ///         let _: Self;        // SelfTyAlias
342     ///
343     ///         todo!()
344     ///     }
345     /// }
346     /// ```
347     /// *See also [`Res::SelfCtor`].*
348     ///
349     SelfTyAlias {
350         /// The item introducing the `Self` type alias. Can be used in the `type_of` query
351         /// to get the underlying type.
352         alias_to: DefId,
353
354         /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
355         /// anonymous constant).
356         ///
357         /// HACK(min_const_generics): self types also have an optional requirement to **not**
358         /// mention any generic parameters to allow the following with `min_const_generics`:
359         /// ```
360         /// # struct Foo;
361         /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
362         ///
363         /// struct Bar([u8; baz::<Self>()]);
364         /// const fn baz<T>() -> usize { 10 }
365         /// ```
366         /// We do however allow `Self` in repeat expression even if it is generic to not break code
367         /// which already works on stable while causing the `const_evaluatable_unchecked` future
368         /// compat lint:
369         /// ```
370         /// fn foo<T>() {
371         ///     let _bar = [1_u8; std::mem::size_of::<*mut T>()];
372         /// }
373         /// ```
374         // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
375         forbid_generic: bool,
376
377         /// Is this within an `impl Foo for bar`?
378         is_trait_impl: bool,
379     },
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::SelfTyParam`] and [`Res::SelfTyAlias`].*
388     SelfCtor(DefId),
389
390     /// A local variable or function parameter.
391     ///
392     /// **Belongs to the value namespace.**
393     Local(Id),
394
395     /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
396     ///
397     /// **Belongs to the type namespace.**
398     ToolMod,
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     #[inline]
463     pub fn full_res(&self) -> Option<Res<NodeId>> {
464         (self.unresolved_segments == 0).then_some(self.base_res)
465     }
466
467     #[inline]
468     pub fn expect_full_res(&self) -> Res<NodeId> {
469         self.full_res().expect("unexpected unresolved segments")
470     }
471 }
472
473 /// Different kinds of symbols can coexist even if they share the same textual name.
474 /// Therefore, they each have a separate universe (known as a "namespace").
475 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
476 pub enum Namespace {
477     /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
478     /// (and, by extension, crates).
479     ///
480     /// Note that the type namespace includes other items; this is not an
481     /// exhaustive list.
482     TypeNS,
483     /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
484     ValueNS,
485     /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
486     /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
487     /// like `#[inline]` and `#[rustfmt::skip]`.
488     MacroNS,
489 }
490
491 impl Namespace {
492     /// The English description of the namespace.
493     pub fn descr(self) -> &'static str {
494         match self {
495             Self::TypeNS => "type",
496             Self::ValueNS => "value",
497             Self::MacroNS => "macro",
498         }
499     }
500 }
501
502 /// Just a helper ‒ separate structure for each namespace.
503 #[derive(Copy, Clone, Default, Debug)]
504 pub struct PerNS<T> {
505     pub value_ns: T,
506     pub type_ns: T,
507     pub macro_ns: T,
508 }
509
510 impl<T> PerNS<T> {
511     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
512         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
513     }
514
515     pub fn into_iter(self) -> IntoIter<T, 3> {
516         [self.value_ns, self.type_ns, self.macro_ns].into_iter()
517     }
518
519     pub fn iter(&self) -> IntoIter<&T, 3> {
520         [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
521     }
522 }
523
524 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
525     type Output = T;
526
527     fn index(&self, ns: Namespace) -> &T {
528         match ns {
529             Namespace::ValueNS => &self.value_ns,
530             Namespace::TypeNS => &self.type_ns,
531             Namespace::MacroNS => &self.macro_ns,
532         }
533     }
534 }
535
536 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
537     fn index_mut(&mut self, ns: Namespace) -> &mut T {
538         match ns {
539             Namespace::ValueNS => &mut self.value_ns,
540             Namespace::TypeNS => &mut self.type_ns,
541             Namespace::MacroNS => &mut self.macro_ns,
542         }
543     }
544 }
545
546 impl<T> PerNS<Option<T>> {
547     /// Returns `true` if all the items in this collection are `None`.
548     pub fn is_empty(&self) -> bool {
549         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
550     }
551
552     /// Returns an iterator over the items which are `Some`.
553     pub fn present_items(self) -> impl Iterator<Item = T> {
554         [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
555     }
556 }
557
558 impl CtorKind {
559     pub fn from_ast(vdata: &ast::VariantData) -> Option<(CtorKind, NodeId)> {
560         match *vdata {
561             ast::VariantData::Tuple(_, node_id) => Some((CtorKind::Fn, node_id)),
562             ast::VariantData::Unit(node_id) => Some((CtorKind::Const, node_id)),
563             ast::VariantData::Struct(..) => None,
564         }
565     }
566 }
567
568 impl NonMacroAttrKind {
569     pub fn descr(self) -> &'static str {
570         match self {
571             NonMacroAttrKind::Builtin(..) => "built-in attribute",
572             NonMacroAttrKind::Tool => "tool attribute",
573             NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
574                 "derive helper attribute"
575             }
576         }
577     }
578
579     pub fn article(self) -> &'static str {
580         "a"
581     }
582
583     /// Users of some attributes cannot mark them as used, so they are considered always used.
584     pub fn is_used(self) -> bool {
585         match self {
586             NonMacroAttrKind::Tool
587             | NonMacroAttrKind::DeriveHelper
588             | NonMacroAttrKind::DeriveHelperCompat => true,
589             NonMacroAttrKind::Builtin(..) => false,
590         }
591     }
592 }
593
594 impl<Id> Res<Id> {
595     /// Return the `DefId` of this `Def` if it has an ID, else panic.
596     pub fn def_id(&self) -> DefId
597     where
598         Id: Debug,
599     {
600         self.opt_def_id().unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}"))
601     }
602
603     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
604     pub fn opt_def_id(&self) -> Option<DefId> {
605         match *self {
606             Res::Def(_, id) => Some(id),
607
608             Res::Local(..)
609             | Res::PrimTy(..)
610             | Res::SelfTyParam { .. }
611             | Res::SelfTyAlias { .. }
612             | Res::SelfCtor(..)
613             | Res::ToolMod
614             | Res::NonMacroAttr(..)
615             | Res::Err => None,
616         }
617     }
618
619     /// Return the `DefId` of this `Res` if it represents a module.
620     pub fn mod_def_id(&self) -> Option<DefId> {
621         match *self {
622             Res::Def(DefKind::Mod, id) => Some(id),
623             _ => None,
624         }
625     }
626
627     /// A human readable name for the res kind ("function", "module", etc.).
628     pub fn descr(&self) -> &'static str {
629         match *self {
630             Res::Def(kind, def_id) => kind.descr(def_id),
631             Res::SelfCtor(..) => "self constructor",
632             Res::PrimTy(..) => "builtin type",
633             Res::Local(..) => "local variable",
634             Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
635             Res::ToolMod => "tool module",
636             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
637             Res::Err => "unresolved item",
638         }
639     }
640
641     /// Gets an English article for the `Res`.
642     pub fn article(&self) -> &'static str {
643         match *self {
644             Res::Def(kind, _) => kind.article(),
645             Res::NonMacroAttr(kind) => kind.article(),
646             Res::Err => "an",
647             _ => "a",
648         }
649     }
650
651     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
652         match self {
653             Res::Def(kind, id) => Res::Def(kind, id),
654             Res::SelfCtor(id) => Res::SelfCtor(id),
655             Res::PrimTy(id) => Res::PrimTy(id),
656             Res::Local(id) => Res::Local(map(id)),
657             Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
658             Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
659                 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
660             }
661             Res::ToolMod => Res::ToolMod,
662             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
663             Res::Err => Res::Err,
664         }
665     }
666
667     pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
668         Ok(match self {
669             Res::Def(kind, id) => Res::Def(kind, id),
670             Res::SelfCtor(id) => Res::SelfCtor(id),
671             Res::PrimTy(id) => Res::PrimTy(id),
672             Res::Local(id) => Res::Local(map(id)?),
673             Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
674             Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
675                 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
676             }
677             Res::ToolMod => Res::ToolMod,
678             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
679             Res::Err => Res::Err,
680         })
681     }
682
683     #[track_caller]
684     pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
685         self.map_id(
686             #[track_caller]
687             |_| panic!("unexpected `Res::Local`"),
688         )
689     }
690
691     pub fn macro_kind(self) -> Option<MacroKind> {
692         match self {
693             Res::Def(DefKind::Macro(kind), _) => Some(kind),
694             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
695             _ => None,
696         }
697     }
698
699     /// Returns `None` if this is `Res::Err`
700     pub fn ns(&self) -> Option<Namespace> {
701         match self {
702             Res::Def(kind, ..) => kind.ns(),
703             Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
704                 Some(Namespace::TypeNS)
705             }
706             Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
707             Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
708             Res::Err => None,
709         }
710     }
711
712     /// Always returns `true` if `self` is `Res::Err`
713     pub fn matches_ns(&self, ns: Namespace) -> bool {
714         self.ns().map_or(true, |actual_ns| actual_ns == ns)
715     }
716
717     /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
718     pub fn expected_in_tuple_struct_pat(&self) -> bool {
719         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
720     }
721
722     /// Returns whether such a resolved path can occur in a unit struct/variant pattern
723     pub fn expected_in_unit_struct_pat(&self) -> bool {
724         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
725     }
726 }
727
728 /// Resolution for a lifetime appearing in a type.
729 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
730 pub enum LifetimeRes {
731     /// Successfully linked the lifetime to a generic parameter.
732     Param {
733         /// Id of the generic parameter that introduced it.
734         param: LocalDefId,
735         /// Id of the introducing place. That can be:
736         /// - an item's id, for the item's generic parameters;
737         /// - a TraitRef's ref_id, identifying the `for<...>` binder;
738         /// - a BareFn type's id.
739         ///
740         /// This information is used for impl-trait lifetime captures, to know when to or not to
741         /// capture any given lifetime.
742         binder: NodeId,
743     },
744     /// Created a generic parameter for an anonymous lifetime.
745     Fresh {
746         /// Id of the generic parameter that introduced it.
747         ///
748         /// Creating the associated `LocalDefId` is the responsibility of lowering.
749         param: NodeId,
750         /// Id of the introducing place. See `Param`.
751         binder: NodeId,
752     },
753     /// This variant is used for anonymous lifetimes that we did not resolve during
754     /// late resolution. Those lifetimes will be inferred by typechecking.
755     Infer,
756     /// Explicit `'static` lifetime.
757     Static,
758     /// Resolution failure.
759     Error,
760     /// HACK: This is used to recover the NodeId of an elided lifetime.
761     ElidedAnchor { start: NodeId, end: NodeId },
762 }