]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/def.rs
Rollup merge of #101655 - dns2utf8:box_docs, r=dtolnay
[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, as used within a trait.
318     ///
319     /// **Belongs to the type namespace.**
320     ///
321     /// See the examples on [`Res::SelfTyAlias`] for details.
322     SelfTyParam {
323         /// The trait this `Self` is a generic parameter for.
324         trait_: DefId,
325     },
326
327     /// The `Self` type, as used somewhere other than within a trait.
328     ///
329     /// **Belongs to the type namespace.**
330     ///
331     /// Examples:
332     /// ```
333     /// struct Bar(Box<Self>); // SelfTyAlias
334     ///
335     /// trait Foo {
336     ///     fn foo() -> Box<Self>; // SelfTyParam
337     /// }
338     ///
339     /// impl Bar {
340     ///     fn blah() {
341     ///         let _: Self; // SelfTyAlias
342     ///     }
343     /// }
344     ///
345     /// impl Foo for Bar {
346     ///     fn foo() -> Box<Self> { // SelfTyAlias
347     ///         let _: Self;        // SelfTyAlias
348     ///
349     ///         todo!()
350     ///     }
351     /// }
352     /// ```
353     /// *See also [`Res::SelfCtor`].*
354     ///
355     SelfTyAlias {
356         /// The item introducing the `Self` type alias. Can be used in the `type_of` query
357         /// to get the underlying type.
358         alias_to: DefId,
359
360         /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
361         /// anonymous constant).
362         ///
363         /// HACK(min_const_generics): self types also have an optional requirement to **not**
364         /// mention any generic parameters to allow the following with `min_const_generics`:
365         /// ```
366         /// # struct Foo;
367         /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
368         ///
369         /// struct Bar([u8; baz::<Self>()]);
370         /// const fn baz<T>() -> usize { 10 }
371         /// ```
372         /// We do however allow `Self` in repeat expression even if it is generic to not break code
373         /// which already works on stable while causing the `const_evaluatable_unchecked` future
374         /// compat lint:
375         /// ```
376         /// fn foo<T>() {
377         ///     let _bar = [1_u8; std::mem::size_of::<*mut T>()];
378         /// }
379         /// ```
380         // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
381         forbid_generic: bool,
382
383         /// Is this within an `impl Foo for bar`?
384         is_trait_impl: bool,
385     },
386
387     // Value namespace
388     /// The `Self` constructor, along with the [`DefId`]
389     /// of the impl it is associated with.
390     ///
391     /// **Belongs to the value namespace.**
392     ///
393     /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
394     SelfCtor(DefId),
395
396     /// A local variable or function parameter.
397     ///
398     /// **Belongs to the value namespace.**
399     Local(Id),
400
401     /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
402     ///
403     /// **Belongs to the type namespace.**
404     ToolMod,
405
406     // Macro namespace
407     /// An attribute that is *not* implemented via macro.
408     /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
409     /// as opposed to `#[test]`, which is a builtin macro.
410     ///
411     /// **Belongs to the macro namespace.**
412     NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
413
414     // All namespaces
415     /// Name resolution failed. We use a dummy `Res` variant so later phases
416     /// of the compiler won't crash and can instead report more errors.
417     ///
418     /// **Not bound to a specific namespace.**
419     Err,
420 }
421
422 /// The result of resolving a path before lowering to HIR,
423 /// with "module" segments resolved and associated item
424 /// segments deferred to type checking.
425 /// `base_res` is the resolution of the resolved part of the
426 /// path, `unresolved_segments` is the number of unresolved
427 /// segments.
428 ///
429 /// ```text
430 /// module::Type::AssocX::AssocY::MethodOrAssocType
431 /// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
432 /// base_res      unresolved_segments = 3
433 ///
434 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
435 ///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
436 ///       base_res        unresolved_segments = 2
437 /// ```
438 #[derive(Copy, Clone, Debug)]
439 pub struct PartialRes {
440     base_res: Res<NodeId>,
441     unresolved_segments: usize,
442 }
443
444 impl PartialRes {
445     #[inline]
446     pub fn new(base_res: Res<NodeId>) -> Self {
447         PartialRes { base_res, unresolved_segments: 0 }
448     }
449
450     #[inline]
451     pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
452         if base_res == Res::Err {
453             unresolved_segments = 0
454         }
455         PartialRes { base_res, unresolved_segments }
456     }
457
458     #[inline]
459     pub fn base_res(&self) -> Res<NodeId> {
460         self.base_res
461     }
462
463     #[inline]
464     pub fn unresolved_segments(&self) -> usize {
465         self.unresolved_segments
466     }
467
468     #[inline]
469     pub fn full_res(&self) -> Option<Res<NodeId>> {
470         (self.unresolved_segments == 0).then_some(self.base_res)
471     }
472
473     #[inline]
474     pub fn expect_full_res(&self) -> Res<NodeId> {
475         self.full_res().expect("unexpected unresolved segments")
476     }
477 }
478
479 /// Different kinds of symbols can coexist even if they share the same textual name.
480 /// Therefore, they each have a separate universe (known as a "namespace").
481 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
482 pub enum Namespace {
483     /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
484     /// (and, by extension, crates).
485     ///
486     /// Note that the type namespace includes other items; this is not an
487     /// exhaustive list.
488     TypeNS,
489     /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
490     ValueNS,
491     /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
492     /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
493     /// like `#[inline]` and `#[rustfmt::skip]`.
494     MacroNS,
495 }
496
497 impl Namespace {
498     /// The English description of the namespace.
499     pub fn descr(self) -> &'static str {
500         match self {
501             Self::TypeNS => "type",
502             Self::ValueNS => "value",
503             Self::MacroNS => "macro",
504         }
505     }
506 }
507
508 /// Just a helper â€’ separate structure for each namespace.
509 #[derive(Copy, Clone, Default, Debug)]
510 pub struct PerNS<T> {
511     pub value_ns: T,
512     pub type_ns: T,
513     pub macro_ns: T,
514 }
515
516 impl<T> PerNS<T> {
517     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
518         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
519     }
520
521     pub fn into_iter(self) -> IntoIter<T, 3> {
522         [self.value_ns, self.type_ns, self.macro_ns].into_iter()
523     }
524
525     pub fn iter(&self) -> IntoIter<&T, 3> {
526         [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
527     }
528 }
529
530 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
531     type Output = T;
532
533     fn index(&self, ns: Namespace) -> &T {
534         match ns {
535             Namespace::ValueNS => &self.value_ns,
536             Namespace::TypeNS => &self.type_ns,
537             Namespace::MacroNS => &self.macro_ns,
538         }
539     }
540 }
541
542 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
543     fn index_mut(&mut self, ns: Namespace) -> &mut T {
544         match ns {
545             Namespace::ValueNS => &mut self.value_ns,
546             Namespace::TypeNS => &mut self.type_ns,
547             Namespace::MacroNS => &mut self.macro_ns,
548         }
549     }
550 }
551
552 impl<T> PerNS<Option<T>> {
553     /// Returns `true` if all the items in this collection are `None`.
554     pub fn is_empty(&self) -> bool {
555         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
556     }
557
558     /// Returns an iterator over the items which are `Some`.
559     pub fn present_items(self) -> impl Iterator<Item = T> {
560         [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
561     }
562 }
563
564 impl CtorKind {
565     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
566         match *vdata {
567             ast::VariantData::Tuple(..) => CtorKind::Fn,
568             ast::VariantData::Unit(..) => CtorKind::Const,
569             ast::VariantData::Struct(..) => CtorKind::Fictive,
570         }
571     }
572
573     pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
574         match *vdata {
575             hir::VariantData::Tuple(..) => CtorKind::Fn,
576             hir::VariantData::Unit(..) => CtorKind::Const,
577             hir::VariantData::Struct(..) => CtorKind::Fictive,
578         }
579     }
580 }
581
582 impl NonMacroAttrKind {
583     pub fn descr(self) -> &'static str {
584         match self {
585             NonMacroAttrKind::Builtin(..) => "built-in attribute",
586             NonMacroAttrKind::Tool => "tool attribute",
587             NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
588                 "derive helper attribute"
589             }
590         }
591     }
592
593     pub fn article(self) -> &'static str {
594         "a"
595     }
596
597     /// Users of some attributes cannot mark them as used, so they are considered always used.
598     pub fn is_used(self) -> bool {
599         match self {
600             NonMacroAttrKind::Tool
601             | NonMacroAttrKind::DeriveHelper
602             | NonMacroAttrKind::DeriveHelperCompat => true,
603             NonMacroAttrKind::Builtin(..) => false,
604         }
605     }
606 }
607
608 impl<Id> Res<Id> {
609     /// Return the `DefId` of this `Def` if it has an ID, else panic.
610     pub fn def_id(&self) -> DefId
611     where
612         Id: Debug,
613     {
614         self.opt_def_id()
615             .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
616     }
617
618     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
619     pub fn opt_def_id(&self) -> Option<DefId> {
620         match *self {
621             Res::Def(_, id) => Some(id),
622
623             Res::Local(..)
624             | Res::PrimTy(..)
625             | Res::SelfTyParam { .. }
626             | Res::SelfTyAlias { .. }
627             | Res::SelfCtor(..)
628             | Res::ToolMod
629             | Res::NonMacroAttr(..)
630             | Res::Err => None,
631         }
632     }
633
634     /// Return the `DefId` of this `Res` if it represents a module.
635     pub fn mod_def_id(&self) -> Option<DefId> {
636         match *self {
637             Res::Def(DefKind::Mod, id) => Some(id),
638             _ => None,
639         }
640     }
641
642     /// A human readable name for the res kind ("function", "module", etc.).
643     pub fn descr(&self) -> &'static str {
644         match *self {
645             Res::Def(kind, def_id) => kind.descr(def_id),
646             Res::SelfCtor(..) => "self constructor",
647             Res::PrimTy(..) => "builtin type",
648             Res::Local(..) => "local variable",
649             Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
650             Res::ToolMod => "tool module",
651             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
652             Res::Err => "unresolved item",
653         }
654     }
655
656     /// Gets an English article for the `Res`.
657     pub fn article(&self) -> &'static str {
658         match *self {
659             Res::Def(kind, _) => kind.article(),
660             Res::NonMacroAttr(kind) => kind.article(),
661             Res::Err => "an",
662             _ => "a",
663         }
664     }
665
666     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
667         match self {
668             Res::Def(kind, id) => Res::Def(kind, id),
669             Res::SelfCtor(id) => Res::SelfCtor(id),
670             Res::PrimTy(id) => Res::PrimTy(id),
671             Res::Local(id) => Res::Local(map(id)),
672             Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
673             Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
674                 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
675             }
676             Res::ToolMod => Res::ToolMod,
677             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
678             Res::Err => Res::Err,
679         }
680     }
681
682     pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
683         Ok(match self {
684             Res::Def(kind, id) => Res::Def(kind, id),
685             Res::SelfCtor(id) => Res::SelfCtor(id),
686             Res::PrimTy(id) => Res::PrimTy(id),
687             Res::Local(id) => Res::Local(map(id)?),
688             Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
689             Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
690                 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
691             }
692             Res::ToolMod => Res::ToolMod,
693             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
694             Res::Err => Res::Err,
695         })
696     }
697
698     #[track_caller]
699     pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
700         self.map_id(
701             #[track_caller]
702             |_| panic!("unexpected `Res::Local`"),
703         )
704     }
705
706     pub fn macro_kind(self) -> Option<MacroKind> {
707         match self {
708             Res::Def(DefKind::Macro(kind), _) => Some(kind),
709             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
710             _ => None,
711         }
712     }
713
714     /// Returns `None` if this is `Res::Err`
715     pub fn ns(&self) -> Option<Namespace> {
716         match self {
717             Res::Def(kind, ..) => kind.ns(),
718             Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
719                 Some(Namespace::TypeNS)
720             }
721             Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
722             Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
723             Res::Err => None,
724         }
725     }
726
727     /// Always returns `true` if `self` is `Res::Err`
728     pub fn matches_ns(&self, ns: Namespace) -> bool {
729         self.ns().map_or(true, |actual_ns| actual_ns == ns)
730     }
731
732     /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
733     pub fn expected_in_tuple_struct_pat(&self) -> bool {
734         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
735     }
736
737     /// Returns whether such a resolved path can occur in a unit struct/variant pattern
738     pub fn expected_in_unit_struct_pat(&self) -> bool {
739         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
740     }
741 }
742
743 /// Resolution for a lifetime appearing in a type.
744 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
745 pub enum LifetimeRes {
746     /// Successfully linked the lifetime to a generic parameter.
747     Param {
748         /// Id of the generic parameter that introduced it.
749         param: LocalDefId,
750         /// Id of the introducing place. That can be:
751         /// - an item's id, for the item's generic parameters;
752         /// - a TraitRef's ref_id, identifying the `for<...>` binder;
753         /// - a BareFn type's id.
754         ///
755         /// This information is used for impl-trait lifetime captures, to know when to or not to
756         /// capture any given lifetime.
757         binder: NodeId,
758     },
759     /// Created a generic parameter for an anonymous lifetime.
760     Fresh {
761         /// Id of the generic parameter that introduced it.
762         ///
763         /// Creating the associated `LocalDefId` is the responsibility of lowering.
764         param: NodeId,
765         /// Id of the introducing place. See `Param`.
766         binder: NodeId,
767     },
768     /// This variant is used for anonymous lifetimes that we did not resolve during
769     /// late resolution.  Those lifetimes will be inferred by typechecking.
770     Infer,
771     /// Explicit `'static` lifetime.
772     Static,
773     /// Resolution failure.
774     Error,
775     /// HACK: This is used to recover the NodeId of an elided lifetime.
776     ElidedAnchor { start: NodeId, end: NodeId },
777 }