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