rustc_hir/def.rs
1use std::array::IntoIter;
2use std::fmt::Debug;
3
4use rustc_ast as ast;
5use rustc_ast::NodeId;
6use rustc_data_structures::stable_hasher::ToStableHashKey;
7use rustc_data_structures::unord::UnordMap;
8use rustc_macros::{Decodable, Encodable, HashStable_Generic};
9use rustc_span::Symbol;
10use rustc_span::def_id::{DefId, LocalDefId};
11use rustc_span::hygiene::MacroKind;
12
13use crate::definitions::DefPathData;
14use crate::hir;
15
16/// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
17#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
18pub 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, HashStable_Generic)]
27pub enum CtorKind {
28 /// Constructor function automatically created by a tuple struct/variant.
29 Fn,
30 /// Constructor constant automatically created by a unit struct/variant.
31 Const,
32}
33
34/// An attribute that is not a macro; e.g., `#[inline]` or `#[rustfmt::skip]`.
35#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
36pub 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/// `enum DefPathData` may need to be updated if a new variant is added here.
50#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
51pub 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 {
78 /// Whether it's a `unsafe static`, `safe static` (inside extern only) or just a `static`.
79 safety: hir::Safety,
80 /// Whether it's a `static mut` or just a `static`.
81 mutability: ast::Mutability,
82 /// Whether it's an anonymous static generated for nested allocations.
83 nested: bool,
84 },
85 /// Refers to the struct or enum variant's constructor.
86 ///
87 /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
88 /// [`DefKind::Variant`] is because structs and enum variants exist
89 /// in the *type* namespace, whereas struct and enum variant *constructors*
90 /// exist in the *value* namespace.
91 ///
92 /// You may wonder why enum variants exist in the type namespace as opposed
93 /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
94 ///
95 /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
96 Ctor(CtorOf, CtorKind),
97 /// Associated function: `impl MyStruct { fn associated() {} }`
98 /// or `trait Foo { fn associated() {} }`
99 AssocFn,
100 /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
101 AssocConst,
102
103 // Macro namespace
104 Macro(MacroKind),
105
106 // Not namespaced (or they are, but we don't treat them so)
107 ExternCrate,
108 Use,
109 /// An `extern` block.
110 ForeignMod,
111 /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`.
112 ///
113 /// Not all anon-consts are actually still relevant in the HIR. We lower
114 /// trivial const-arguments directly to `hir::ConstArgKind::Path`, at which
115 /// point the definition for the anon-const ends up unused and incomplete.
116 ///
117 /// We do not provide any a `Span` for the definition and pretty much all other
118 /// queries also ICE when using this `DefId`. Given that the `DefId` of such
119 /// constants should only be reachable by iterating all definitions of a
120 /// given crate, you should not have to worry about this.
121 AnonConst,
122 /// An inline constant, e.g. `const { 1 + 2 }`
123 InlineConst,
124 /// Opaque type, aka `impl Trait`.
125 OpaqueTy,
126 /// A field in a struct, enum or union. e.g.
127 /// - `bar` in `struct Foo { bar: u8 }`
128 /// - `Foo::Bar::0` in `enum Foo { Bar(u8) }`
129 Field,
130 /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
131 LifetimeParam,
132 /// A use of `global_asm!`.
133 GlobalAsm,
134 Impl {
135 of_trait: bool,
136 },
137 /// A closure, coroutine, or coroutine-closure.
138 ///
139 /// These are all represented with the same `ExprKind::Closure` in the AST and HIR,
140 /// which makes it difficult to distinguish these during def collection. Therefore,
141 /// we treat them all the same, and code which needs to distinguish them can match
142 /// or `hir::ClosureKind` or `type_of`.
143 Closure,
144 /// The definition of a synthetic coroutine body created by the lowering of a
145 /// coroutine-closure, such as an async closure.
146 SyntheticCoroutineBody,
147}
148
149impl DefKind {
150 /// Get an English description for the item's kind.
151 ///
152 /// If you have access to `TyCtxt`, use `TyCtxt::def_descr` or
153 /// `TyCtxt::def_kind_descr` instead, because they give better
154 /// information for coroutines and associated functions.
155 pub fn descr(self, def_id: DefId) -> &'static str {
156 match self {
157 DefKind::Fn => "function",
158 DefKind::Mod if def_id.is_crate_root() && !def_id.is_local() => "crate",
159 DefKind::Mod => "module",
160 DefKind::Static { .. } => "static",
161 DefKind::Enum => "enum",
162 DefKind::Variant => "variant",
163 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
164 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
165 DefKind::Struct => "struct",
166 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
167 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
168 DefKind::OpaqueTy => "opaque type",
169 DefKind::TyAlias => "type alias",
170 DefKind::TraitAlias => "trait alias",
171 DefKind::AssocTy => "associated type",
172 DefKind::Union => "union",
173 DefKind::Trait => "trait",
174 DefKind::ForeignTy => "foreign type",
175 DefKind::AssocFn => "associated function",
176 DefKind::Const => "constant",
177 DefKind::AssocConst => "associated constant",
178 DefKind::TyParam => "type parameter",
179 DefKind::ConstParam => "const parameter",
180 DefKind::Macro(macro_kind) => macro_kind.descr(),
181 DefKind::LifetimeParam => "lifetime parameter",
182 DefKind::Use => "import",
183 DefKind::ForeignMod => "foreign module",
184 DefKind::AnonConst => "constant expression",
185 DefKind::InlineConst => "inline constant",
186 DefKind::Field => "field",
187 DefKind::Impl { .. } => "implementation",
188 DefKind::Closure => "closure",
189 DefKind::ExternCrate => "extern crate",
190 DefKind::GlobalAsm => "global assembly block",
191 DefKind::SyntheticCoroutineBody => "synthetic mir body",
192 }
193 }
194
195 /// Gets an English article for the definition.
196 ///
197 /// If you have access to `TyCtxt`, use `TyCtxt::def_descr_article` or
198 /// `TyCtxt::def_kind_descr_article` instead, because they give better
199 /// information for coroutines and associated functions.
200 pub fn article(&self) -> &'static str {
201 match *self {
202 DefKind::AssocTy
203 | DefKind::AssocConst
204 | DefKind::AssocFn
205 | DefKind::Enum
206 | DefKind::OpaqueTy
207 | DefKind::Impl { .. }
208 | DefKind::Use
209 | DefKind::InlineConst
210 | DefKind::ExternCrate => "an",
211 DefKind::Macro(macro_kind) => macro_kind.article(),
212 _ => "a",
213 }
214 }
215
216 pub fn ns(&self) -> Option<Namespace> {
217 match self {
218 DefKind::Mod
219 | DefKind::Struct
220 | DefKind::Union
221 | DefKind::Enum
222 | DefKind::Variant
223 | DefKind::Trait
224 | DefKind::TyAlias
225 | DefKind::ForeignTy
226 | DefKind::TraitAlias
227 | DefKind::AssocTy
228 | DefKind::TyParam => Some(Namespace::TypeNS),
229
230 DefKind::Fn
231 | DefKind::Const
232 | DefKind::ConstParam
233 | DefKind::Static { .. }
234 | DefKind::Ctor(..)
235 | DefKind::AssocFn
236 | DefKind::AssocConst => Some(Namespace::ValueNS),
237
238 DefKind::Macro(..) => Some(Namespace::MacroNS),
239
240 // Not namespaced.
241 DefKind::AnonConst
242 | DefKind::InlineConst
243 | DefKind::Field
244 | DefKind::LifetimeParam
245 | DefKind::ExternCrate
246 | DefKind::Closure
247 | DefKind::Use
248 | DefKind::ForeignMod
249 | DefKind::GlobalAsm
250 | DefKind::Impl { .. }
251 | DefKind::OpaqueTy
252 | DefKind::SyntheticCoroutineBody => None,
253 }
254 }
255
256 // Some `DefKind`s require a name, some don't. Panics if one is needed but
257 // not provided. (`AssocTy` is an exception, see below.)
258 pub fn def_path_data(self, name: Option<Symbol>) -> DefPathData {
259 match self {
260 DefKind::Mod
261 | DefKind::Struct
262 | DefKind::Union
263 | DefKind::Enum
264 | DefKind::Variant
265 | DefKind::Trait
266 | DefKind::TyAlias
267 | DefKind::ForeignTy
268 | DefKind::TraitAlias
269 | DefKind::TyParam
270 | DefKind::ExternCrate => DefPathData::TypeNs(name.unwrap()),
271
272 // An associated type name will be missing for an RPITIT (DefPathData::AnonAssocTy),
273 // but those provide their own DefPathData.
274 DefKind::AssocTy => DefPathData::TypeNs(name.unwrap()),
275
276 DefKind::Fn
277 | DefKind::Const
278 | DefKind::ConstParam
279 | DefKind::Static { .. }
280 | DefKind::AssocFn
281 | DefKind::AssocConst
282 | DefKind::Field => DefPathData::ValueNs(name.unwrap()),
283 DefKind::Macro(..) => DefPathData::MacroNs(name.unwrap()),
284 DefKind::LifetimeParam => DefPathData::LifetimeNs(name.unwrap()),
285 DefKind::Ctor(..) => DefPathData::Ctor,
286 DefKind::Use => DefPathData::Use,
287 DefKind::ForeignMod => DefPathData::ForeignMod,
288 DefKind::AnonConst => DefPathData::AnonConst,
289 DefKind::InlineConst => DefPathData::AnonConst,
290 DefKind::OpaqueTy => DefPathData::OpaqueTy,
291 DefKind::GlobalAsm => DefPathData::GlobalAsm,
292 DefKind::Impl { .. } => DefPathData::Impl,
293 DefKind::Closure => DefPathData::Closure,
294 DefKind::SyntheticCoroutineBody => DefPathData::SyntheticCoroutineBody,
295 }
296 }
297
298 /// This is a "module" in name resolution sense.
299 #[inline]
300 pub fn is_module_like(self) -> bool {
301 matches!(self, DefKind::Mod | DefKind::Enum | DefKind::Trait)
302 }
303
304 #[inline]
305 pub fn is_fn_like(self) -> bool {
306 matches!(
307 self,
308 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::SyntheticCoroutineBody
309 )
310 }
311
312 /// Whether `query get_codegen_attrs` should be used with this definition.
313 pub fn has_codegen_attrs(self) -> bool {
314 match self {
315 DefKind::Fn
316 | DefKind::AssocFn
317 | DefKind::Ctor(..)
318 | DefKind::Closure
319 | DefKind::Static { .. }
320 | DefKind::SyntheticCoroutineBody => true,
321 DefKind::Mod
322 | DefKind::Struct
323 | DefKind::Union
324 | DefKind::Enum
325 | DefKind::Variant
326 | DefKind::Trait
327 | DefKind::TyAlias
328 | DefKind::ForeignTy
329 | DefKind::TraitAlias
330 | DefKind::AssocTy
331 | DefKind::Const
332 | DefKind::AssocConst
333 | DefKind::Macro(..)
334 | DefKind::Use
335 | DefKind::ForeignMod
336 | DefKind::OpaqueTy
337 | DefKind::Impl { .. }
338 | DefKind::Field
339 | DefKind::TyParam
340 | DefKind::ConstParam
341 | DefKind::LifetimeParam
342 | DefKind::AnonConst
343 | DefKind::InlineConst
344 | DefKind::GlobalAsm
345 | DefKind::ExternCrate => false,
346 }
347 }
348}
349
350/// The resolution of a path or export.
351///
352/// For every path or identifier in Rust, the compiler must determine
353/// what the path refers to. This process is called name resolution,
354/// and `Res` is the primary result of name resolution.
355///
356/// For example, everything prefixed with `/* Res */` in this example has
357/// an associated `Res`:
358///
359/// ```
360/// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
361/// /* Res */ String::from(/* Res */ s)
362/// }
363///
364/// /* Res */ str_to_string("hello");
365/// ```
366///
367/// The associated `Res`s will be:
368///
369/// - `str` will resolve to [`Res::PrimTy`];
370/// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
371/// for `String` as defined in the standard library;
372/// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
373/// pointing to `String::from`;
374/// - `s` will resolve to [`Res::Local`];
375/// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
376/// pointing to the definition of `str_to_string` in the current crate.
377//
378#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
379pub enum Res<Id = hir::HirId> {
380 /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
381 ///
382 /// **Not bound to a specific namespace.**
383 Def(DefKind, DefId),
384
385 // Type namespace
386 /// A primitive type such as `i32` or `str`.
387 ///
388 /// **Belongs to the type namespace.**
389 PrimTy(hir::PrimTy),
390
391 /// The `Self` type, as used within a trait.
392 ///
393 /// **Belongs to the type namespace.**
394 ///
395 /// See the examples on [`Res::SelfTyAlias`] for details.
396 SelfTyParam {
397 /// The trait this `Self` is a generic parameter for.
398 trait_: DefId,
399 },
400
401 /// The `Self` type, as used somewhere other than within a trait.
402 ///
403 /// **Belongs to the type namespace.**
404 ///
405 /// Examples:
406 /// ```
407 /// struct Bar(Box<Self>); // SelfTyAlias
408 ///
409 /// trait Foo {
410 /// fn foo() -> Box<Self>; // SelfTyParam
411 /// }
412 ///
413 /// impl Bar {
414 /// fn blah() {
415 /// let _: Self; // SelfTyAlias
416 /// }
417 /// }
418 ///
419 /// impl Foo for Bar {
420 /// fn foo() -> Box<Self> { // SelfTyAlias
421 /// let _: Self; // SelfTyAlias
422 ///
423 /// todo!()
424 /// }
425 /// }
426 /// ```
427 /// *See also [`Res::SelfCtor`].*
428 ///
429 SelfTyAlias {
430 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
431 /// to get the underlying type.
432 alias_to: DefId,
433
434 /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
435 /// anonymous constant).
436 ///
437 /// HACK(min_const_generics): self types also have an optional requirement to **not**
438 /// mention any generic parameters to allow the following with `min_const_generics`:
439 /// ```
440 /// # struct Foo;
441 /// impl Foo { fn test() -> [u8; size_of::<Self>()] { todo!() } }
442 ///
443 /// struct Bar([u8; baz::<Self>()]);
444 /// const fn baz<T>() -> usize { 10 }
445 /// ```
446 /// We do however allow `Self` in repeat expression even if it is generic to not break code
447 /// which already works on stable while causing the `const_evaluatable_unchecked` future
448 /// compat lint:
449 /// ```
450 /// fn foo<T>() {
451 /// let _bar = [1_u8; size_of::<*mut T>()];
452 /// }
453 /// ```
454 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
455 forbid_generic: bool,
456
457 /// Is this within an `impl Foo for bar`?
458 is_trait_impl: bool,
459 },
460
461 // Value namespace
462 /// The `Self` constructor, along with the [`DefId`]
463 /// of the impl it is associated with.
464 ///
465 /// **Belongs to the value namespace.**
466 ///
467 /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
468 SelfCtor(DefId),
469
470 /// A local variable or function parameter.
471 ///
472 /// **Belongs to the value namespace.**
473 Local(Id),
474
475 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
476 ///
477 /// **Belongs to the type namespace.**
478 ToolMod,
479
480 // Macro namespace
481 /// An attribute that is *not* implemented via macro.
482 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
483 /// as opposed to `#[test]`, which is a builtin macro.
484 ///
485 /// **Belongs to the macro namespace.**
486 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
487
488 // All namespaces
489 /// Name resolution failed. We use a dummy `Res` variant so later phases
490 /// of the compiler won't crash and can instead report more errors.
491 ///
492 /// **Not bound to a specific namespace.**
493 Err,
494}
495
496/// The result of resolving a path before lowering to HIR,
497/// with "module" segments resolved and associated item
498/// segments deferred to type checking.
499/// `base_res` is the resolution of the resolved part of the
500/// path, `unresolved_segments` is the number of unresolved
501/// segments.
502///
503/// ```text
504/// module::Type::AssocX::AssocY::MethodOrAssocType
505/// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
506/// base_res unresolved_segments = 3
507///
508/// <T as Trait>::AssocX::AssocY::MethodOrAssocType
509/// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
510/// base_res unresolved_segments = 2
511/// ```
512#[derive(Copy, Clone, Debug)]
513pub struct PartialRes {
514 base_res: Res<NodeId>,
515 unresolved_segments: usize,
516}
517
518impl PartialRes {
519 #[inline]
520 pub fn new(base_res: Res<NodeId>) -> Self {
521 PartialRes { base_res, unresolved_segments: 0 }
522 }
523
524 #[inline]
525 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
526 if base_res == Res::Err {
527 unresolved_segments = 0
528 }
529 PartialRes { base_res, unresolved_segments }
530 }
531
532 #[inline]
533 pub fn base_res(&self) -> Res<NodeId> {
534 self.base_res
535 }
536
537 #[inline]
538 pub fn unresolved_segments(&self) -> usize {
539 self.unresolved_segments
540 }
541
542 #[inline]
543 pub fn full_res(&self) -> Option<Res<NodeId>> {
544 (self.unresolved_segments == 0).then_some(self.base_res)
545 }
546
547 #[inline]
548 pub fn expect_full_res(&self) -> Res<NodeId> {
549 self.full_res().expect("unexpected unresolved segments")
550 }
551}
552
553/// Different kinds of symbols can coexist even if they share the same textual name.
554/// Therefore, they each have a separate universe (known as a "namespace").
555#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
556#[derive(HashStable_Generic)]
557pub enum Namespace {
558 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
559 /// (and, by extension, crates).
560 ///
561 /// Note that the type namespace includes other items; this is not an
562 /// exhaustive list.
563 TypeNS,
564 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
565 ValueNS,
566 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
567 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
568 /// like `#[inline]` and `#[rustfmt::skip]`.
569 MacroNS,
570}
571
572impl Namespace {
573 /// The English description of the namespace.
574 pub fn descr(self) -> &'static str {
575 match self {
576 Self::TypeNS => "type",
577 Self::ValueNS => "value",
578 Self::MacroNS => "macro",
579 }
580 }
581}
582
583impl<CTX: crate::HashStableContext> ToStableHashKey<CTX> for Namespace {
584 type KeyType = Namespace;
585
586 #[inline]
587 fn to_stable_hash_key(&self, _: &CTX) -> Namespace {
588 *self
589 }
590}
591
592/// Just a helper ‒ separate structure for each namespace.
593#[derive(Copy, Clone, Default, Debug, HashStable_Generic)]
594pub struct PerNS<T> {
595 pub value_ns: T,
596 pub type_ns: T,
597 pub macro_ns: T,
598}
599
600impl<T> PerNS<T> {
601 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
602 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
603 }
604
605 /// Note: Do you really want to use this? Often you know which namespace a
606 /// name will belong in, and you can consider just that namespace directly,
607 /// rather than iterating through all of them.
608 pub fn into_iter(self) -> IntoIter<T, 3> {
609 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
610 }
611
612 /// Note: Do you really want to use this? Often you know which namespace a
613 /// name will belong in, and you can consider just that namespace directly,
614 /// rather than iterating through all of them.
615 pub fn iter(&self) -> IntoIter<&T, 3> {
616 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
617 }
618}
619
620impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
621 type Output = T;
622
623 fn index(&self, ns: Namespace) -> &T {
624 match ns {
625 Namespace::ValueNS => &self.value_ns,
626 Namespace::TypeNS => &self.type_ns,
627 Namespace::MacroNS => &self.macro_ns,
628 }
629 }
630}
631
632impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
633 fn index_mut(&mut self, ns: Namespace) -> &mut T {
634 match ns {
635 Namespace::ValueNS => &mut self.value_ns,
636 Namespace::TypeNS => &mut self.type_ns,
637 Namespace::MacroNS => &mut self.macro_ns,
638 }
639 }
640}
641
642impl<T> PerNS<Option<T>> {
643 /// Returns `true` if all the items in this collection are `None`.
644 pub fn is_empty(&self) -> bool {
645 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
646 }
647
648 /// Returns an iterator over the items which are `Some`.
649 ///
650 /// Note: Do you really want to use this? Often you know which namespace a
651 /// name will belong in, and you can consider just that namespace directly,
652 /// rather than iterating through all of them.
653 pub fn present_items(self) -> impl Iterator<Item = T> {
654 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
655 }
656}
657
658impl CtorKind {
659 pub fn from_ast(vdata: &ast::VariantData) -> Option<(CtorKind, NodeId)> {
660 match *vdata {
661 ast::VariantData::Tuple(_, node_id) => Some((CtorKind::Fn, node_id)),
662 ast::VariantData::Unit(node_id) => Some((CtorKind::Const, node_id)),
663 ast::VariantData::Struct { .. } => None,
664 }
665 }
666}
667
668impl NonMacroAttrKind {
669 pub fn descr(self) -> &'static str {
670 match self {
671 NonMacroAttrKind::Builtin(..) => "built-in attribute",
672 NonMacroAttrKind::Tool => "tool attribute",
673 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
674 "derive helper attribute"
675 }
676 }
677 }
678
679 // Currently trivial, but exists in case a new kind is added in the future whose name starts
680 // with a vowel.
681 pub fn article(self) -> &'static str {
682 "a"
683 }
684
685 /// Users of some attributes cannot mark them as used, so they are considered always used.
686 pub fn is_used(self) -> bool {
687 match self {
688 NonMacroAttrKind::Tool
689 | NonMacroAttrKind::DeriveHelper
690 | NonMacroAttrKind::DeriveHelperCompat => true,
691 NonMacroAttrKind::Builtin(..) => false,
692 }
693 }
694}
695
696impl<Id> Res<Id> {
697 /// Return the `DefId` of this `Def` if it has an ID, else panic.
698 pub fn def_id(&self) -> DefId
699 where
700 Id: Debug,
701 {
702 self.opt_def_id().unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}"))
703 }
704
705 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
706 pub fn opt_def_id(&self) -> Option<DefId> {
707 match *self {
708 Res::Def(_, id) => Some(id),
709
710 Res::Local(..)
711 | Res::PrimTy(..)
712 | Res::SelfTyParam { .. }
713 | Res::SelfTyAlias { .. }
714 | Res::SelfCtor(..)
715 | Res::ToolMod
716 | Res::NonMacroAttr(..)
717 | Res::Err => None,
718 }
719 }
720
721 /// Return the `DefId` of this `Res` if it represents a module.
722 pub fn mod_def_id(&self) -> Option<DefId> {
723 match *self {
724 Res::Def(DefKind::Mod, id) => Some(id),
725 _ => None,
726 }
727 }
728
729 /// If this is a "module" in name resolution sense, return its `DefId`.
730 #[inline]
731 pub fn module_like_def_id(&self) -> Option<DefId> {
732 match self {
733 Res::Def(def_kind, def_id) if def_kind.is_module_like() => Some(*def_id),
734 _ => None,
735 }
736 }
737
738 /// A human readable name for the res kind ("function", "module", etc.).
739 pub fn descr(&self) -> &'static str {
740 match *self {
741 Res::Def(kind, def_id) => kind.descr(def_id),
742 Res::SelfCtor(..) => "self constructor",
743 Res::PrimTy(..) => "builtin type",
744 Res::Local(..) => "local variable",
745 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
746 Res::ToolMod => "tool module",
747 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
748 Res::Err => "unresolved item",
749 }
750 }
751
752 /// Gets an English article for the `Res`.
753 pub fn article(&self) -> &'static str {
754 match *self {
755 Res::Def(kind, _) => kind.article(),
756 Res::NonMacroAttr(kind) => kind.article(),
757 Res::Err => "an",
758 _ => "a",
759 }
760 }
761
762 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
763 match self {
764 Res::Def(kind, id) => Res::Def(kind, id),
765 Res::SelfCtor(id) => Res::SelfCtor(id),
766 Res::PrimTy(id) => Res::PrimTy(id),
767 Res::Local(id) => Res::Local(map(id)),
768 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
769 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
770 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
771 }
772 Res::ToolMod => Res::ToolMod,
773 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
774 Res::Err => Res::Err,
775 }
776 }
777
778 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
779 Ok(match self {
780 Res::Def(kind, id) => Res::Def(kind, id),
781 Res::SelfCtor(id) => Res::SelfCtor(id),
782 Res::PrimTy(id) => Res::PrimTy(id),
783 Res::Local(id) => Res::Local(map(id)?),
784 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
785 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
786 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
787 }
788 Res::ToolMod => Res::ToolMod,
789 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
790 Res::Err => Res::Err,
791 })
792 }
793
794 #[track_caller]
795 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
796 self.map_id(
797 #[track_caller]
798 |_| panic!("unexpected `Res::Local`"),
799 )
800 }
801
802 pub fn macro_kind(self) -> Option<MacroKind> {
803 match self {
804 Res::Def(DefKind::Macro(kind), _) => Some(kind),
805 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
806 _ => None,
807 }
808 }
809
810 /// Returns `None` if this is `Res::Err`
811 pub fn ns(&self) -> Option<Namespace> {
812 match self {
813 Res::Def(kind, ..) => kind.ns(),
814 Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
815 Some(Namespace::TypeNS)
816 }
817 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
818 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
819 Res::Err => None,
820 }
821 }
822
823 /// Always returns `true` if `self` is `Res::Err`
824 pub fn matches_ns(&self, ns: Namespace) -> bool {
825 self.ns().is_none_or(|actual_ns| actual_ns == ns)
826 }
827
828 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
829 pub fn expected_in_tuple_struct_pat(&self) -> bool {
830 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
831 }
832
833 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
834 pub fn expected_in_unit_struct_pat(&self) -> bool {
835 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
836 }
837}
838
839/// Resolution for a lifetime appearing in a type.
840#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
841pub enum LifetimeRes {
842 /// Successfully linked the lifetime to a generic parameter.
843 Param {
844 /// Id of the generic parameter that introduced it.
845 param: LocalDefId,
846 /// Id of the introducing place. That can be:
847 /// - an item's id, for the item's generic parameters;
848 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
849 /// - a FnPtr type's id.
850 ///
851 /// This information is used for impl-trait lifetime captures, to know when to or not to
852 /// capture any given lifetime.
853 binder: NodeId,
854 },
855 /// Created a generic parameter for an anonymous lifetime.
856 Fresh {
857 /// Id of the generic parameter that introduced it.
858 ///
859 /// Creating the associated `LocalDefId` is the responsibility of lowering.
860 param: NodeId,
861 /// Id of the introducing place. See `Param`.
862 binder: NodeId,
863 /// Kind of elided lifetime
864 kind: hir::MissingLifetimeKind,
865 },
866 /// This variant is used for anonymous lifetimes that we did not resolve during
867 /// late resolution. Those lifetimes will be inferred by typechecking.
868 Infer,
869 /// `'static` lifetime.
870 Static,
871 /// Resolution failure.
872 Error,
873 /// HACK: This is used to recover the NodeId of an elided lifetime.
874 ElidedAnchor { start: NodeId, end: NodeId },
875}
876
877pub type DocLinkResMap = UnordMap<(Symbol, Namespace), Option<Res<NodeId>>>;