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 pub fn is_assoc(self) -> bool {
299 matches!(self, DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy)
300 }
301
302 /// This is a "module" in name resolution sense.
303 #[inline]
304 pub fn is_module_like(self) -> bool {
305 matches!(self, DefKind::Mod | DefKind::Enum | DefKind::Trait)
306 }
307
308 #[inline]
309 pub fn is_fn_like(self) -> bool {
310 matches!(
311 self,
312 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::SyntheticCoroutineBody
313 )
314 }
315
316 /// Whether `query get_codegen_attrs` should be used with this definition.
317 pub fn has_codegen_attrs(self) -> bool {
318 match self {
319 DefKind::Fn
320 | DefKind::AssocFn
321 | DefKind::Ctor(..)
322 | DefKind::Closure
323 | DefKind::Static { .. }
324 | DefKind::SyntheticCoroutineBody => true,
325 DefKind::Mod
326 | DefKind::Struct
327 | DefKind::Union
328 | DefKind::Enum
329 | DefKind::Variant
330 | DefKind::Trait
331 | DefKind::TyAlias
332 | DefKind::ForeignTy
333 | DefKind::TraitAlias
334 | DefKind::AssocTy
335 | DefKind::Const
336 | DefKind::AssocConst
337 | DefKind::Macro(..)
338 | DefKind::Use
339 | DefKind::ForeignMod
340 | DefKind::OpaqueTy
341 | DefKind::Impl { .. }
342 | DefKind::Field
343 | DefKind::TyParam
344 | DefKind::ConstParam
345 | DefKind::LifetimeParam
346 | DefKind::AnonConst
347 | DefKind::InlineConst
348 | DefKind::GlobalAsm
349 | DefKind::ExternCrate => false,
350 }
351 }
352}
353
354/// The resolution of a path or export.
355///
356/// For every path or identifier in Rust, the compiler must determine
357/// what the path refers to. This process is called name resolution,
358/// and `Res` is the primary result of name resolution.
359///
360/// For example, everything prefixed with `/* Res */` in this example has
361/// an associated `Res`:
362///
363/// ```
364/// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
365/// /* Res */ String::from(/* Res */ s)
366/// }
367///
368/// /* Res */ str_to_string("hello");
369/// ```
370///
371/// The associated `Res`s will be:
372///
373/// - `str` will resolve to [`Res::PrimTy`];
374/// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
375/// for `String` as defined in the standard library;
376/// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
377/// pointing to `String::from`;
378/// - `s` will resolve to [`Res::Local`];
379/// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
380/// pointing to the definition of `str_to_string` in the current crate.
381//
382#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)]
383pub enum Res<Id = hir::HirId> {
384 /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
385 ///
386 /// **Not bound to a specific namespace.**
387 Def(DefKind, DefId),
388
389 // Type namespace
390 /// A primitive type such as `i32` or `str`.
391 ///
392 /// **Belongs to the type namespace.**
393 PrimTy(hir::PrimTy),
394
395 /// The `Self` type, as used within a trait.
396 ///
397 /// **Belongs to the type namespace.**
398 ///
399 /// See the examples on [`Res::SelfTyAlias`] for details.
400 SelfTyParam {
401 /// The trait this `Self` is a generic parameter for.
402 trait_: DefId,
403 },
404
405 /// The `Self` type, as used somewhere other than within a trait.
406 ///
407 /// **Belongs to the type namespace.**
408 ///
409 /// Examples:
410 /// ```
411 /// struct Bar(Box<Self>); // SelfTyAlias
412 ///
413 /// trait Foo {
414 /// fn foo() -> Box<Self>; // SelfTyParam
415 /// }
416 ///
417 /// impl Bar {
418 /// fn blah() {
419 /// let _: Self; // SelfTyAlias
420 /// }
421 /// }
422 ///
423 /// impl Foo for Bar {
424 /// fn foo() -> Box<Self> { // SelfTyAlias
425 /// let _: Self; // SelfTyAlias
426 ///
427 /// todo!()
428 /// }
429 /// }
430 /// ```
431 /// *See also [`Res::SelfCtor`].*
432 ///
433 SelfTyAlias {
434 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
435 /// to get the underlying type.
436 alias_to: DefId,
437
438 /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
439 /// anonymous constant).
440 ///
441 /// HACK(min_const_generics): self types also have an optional requirement to **not**
442 /// mention any generic parameters to allow the following with `min_const_generics`:
443 /// ```
444 /// # struct Foo;
445 /// impl Foo { fn test() -> [u8; size_of::<Self>()] { todo!() } }
446 ///
447 /// struct Bar([u8; baz::<Self>()]);
448 /// const fn baz<T>() -> usize { 10 }
449 /// ```
450 /// We do however allow `Self` in repeat expression even if it is generic to not break code
451 /// which already works on stable while causing the `const_evaluatable_unchecked` future
452 /// compat lint:
453 /// ```
454 /// fn foo<T>() {
455 /// let _bar = [1_u8; size_of::<*mut T>()];
456 /// }
457 /// ```
458 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
459 forbid_generic: bool,
460
461 /// Is this within an `impl Foo for bar`?
462 is_trait_impl: bool,
463 },
464
465 // Value namespace
466 /// The `Self` constructor, along with the [`DefId`]
467 /// of the impl it is associated with.
468 ///
469 /// **Belongs to the value namespace.**
470 ///
471 /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
472 SelfCtor(DefId),
473
474 /// A local variable or function parameter.
475 ///
476 /// **Belongs to the value namespace.**
477 Local(Id),
478
479 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
480 ///
481 /// **Belongs to the type namespace.**
482 ToolMod,
483
484 // Macro namespace
485 /// An attribute that is *not* implemented via macro.
486 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
487 /// as opposed to `#[test]`, which is a builtin macro.
488 ///
489 /// **Belongs to the macro namespace.**
490 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
491
492 // All namespaces
493 /// Name resolution failed. We use a dummy `Res` variant so later phases
494 /// of the compiler won't crash and can instead report more errors.
495 ///
496 /// **Not bound to a specific namespace.**
497 Err,
498}
499
500/// The result of resolving a path before lowering to HIR,
501/// with "module" segments resolved and associated item
502/// segments deferred to type checking.
503/// `base_res` is the resolution of the resolved part of the
504/// path, `unresolved_segments` is the number of unresolved
505/// segments.
506///
507/// ```text
508/// module::Type::AssocX::AssocY::MethodOrAssocType
509/// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
510/// base_res unresolved_segments = 3
511///
512/// <T as Trait>::AssocX::AssocY::MethodOrAssocType
513/// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
514/// base_res unresolved_segments = 2
515/// ```
516#[derive(Copy, Clone, Debug)]
517pub struct PartialRes {
518 base_res: Res<NodeId>,
519 unresolved_segments: usize,
520}
521
522impl PartialRes {
523 #[inline]
524 pub fn new(base_res: Res<NodeId>) -> Self {
525 PartialRes { base_res, unresolved_segments: 0 }
526 }
527
528 #[inline]
529 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
530 if base_res == Res::Err {
531 unresolved_segments = 0
532 }
533 PartialRes { base_res, unresolved_segments }
534 }
535
536 #[inline]
537 pub fn base_res(&self) -> Res<NodeId> {
538 self.base_res
539 }
540
541 #[inline]
542 pub fn unresolved_segments(&self) -> usize {
543 self.unresolved_segments
544 }
545
546 #[inline]
547 pub fn full_res(&self) -> Option<Res<NodeId>> {
548 (self.unresolved_segments == 0).then_some(self.base_res)
549 }
550
551 #[inline]
552 pub fn expect_full_res(&self) -> Res<NodeId> {
553 self.full_res().expect("unexpected unresolved segments")
554 }
555}
556
557/// Different kinds of symbols can coexist even if they share the same textual name.
558/// Therefore, they each have a separate universe (known as a "namespace").
559#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)]
560#[derive(HashStable_Generic)]
561pub enum Namespace {
562 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
563 /// (and, by extension, crates).
564 ///
565 /// Note that the type namespace includes other items; this is not an
566 /// exhaustive list.
567 TypeNS,
568 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
569 ValueNS,
570 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
571 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
572 /// like `#[inline]` and `#[rustfmt::skip]`.
573 MacroNS,
574}
575
576impl Namespace {
577 /// The English description of the namespace.
578 pub fn descr(self) -> &'static str {
579 match self {
580 Self::TypeNS => "type",
581 Self::ValueNS => "value",
582 Self::MacroNS => "macro",
583 }
584 }
585}
586
587impl<CTX: crate::HashStableContext> ToStableHashKey<CTX> for Namespace {
588 type KeyType = Namespace;
589
590 #[inline]
591 fn to_stable_hash_key(&self, _: &CTX) -> Namespace {
592 *self
593 }
594}
595
596/// Just a helper ‒ separate structure for each namespace.
597#[derive(Copy, Clone, Default, Debug, HashStable_Generic)]
598pub struct PerNS<T> {
599 pub value_ns: T,
600 pub type_ns: T,
601 pub macro_ns: T,
602}
603
604impl<T> PerNS<T> {
605 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
606 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
607 }
608
609 /// Note: Do you really want to use this? Often you know which namespace a
610 /// name will belong in, and you can consider just that namespace directly,
611 /// rather than iterating through all of them.
612 pub fn into_iter(self) -> IntoIter<T, 3> {
613 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
614 }
615
616 /// Note: Do you really want to use this? Often you know which namespace a
617 /// name will belong in, and you can consider just that namespace directly,
618 /// rather than iterating through all of them.
619 pub fn iter(&self) -> IntoIter<&T, 3> {
620 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
621 }
622}
623
624impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
625 type Output = T;
626
627 fn index(&self, ns: Namespace) -> &T {
628 match ns {
629 Namespace::ValueNS => &self.value_ns,
630 Namespace::TypeNS => &self.type_ns,
631 Namespace::MacroNS => &self.macro_ns,
632 }
633 }
634}
635
636impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
637 fn index_mut(&mut self, ns: Namespace) -> &mut T {
638 match ns {
639 Namespace::ValueNS => &mut self.value_ns,
640 Namespace::TypeNS => &mut self.type_ns,
641 Namespace::MacroNS => &mut self.macro_ns,
642 }
643 }
644}
645
646impl<T> PerNS<Option<T>> {
647 /// Returns `true` if all the items in this collection are `None`.
648 pub fn is_empty(&self) -> bool {
649 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
650 }
651
652 /// Returns an iterator over the items which are `Some`.
653 ///
654 /// Note: Do you really want to use this? Often you know which namespace a
655 /// name will belong in, and you can consider just that namespace directly,
656 /// rather than iterating through all of them.
657 pub fn present_items(self) -> impl Iterator<Item = T> {
658 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
659 }
660}
661
662impl CtorKind {
663 pub fn from_ast(vdata: &ast::VariantData) -> Option<(CtorKind, NodeId)> {
664 match *vdata {
665 ast::VariantData::Tuple(_, node_id) => Some((CtorKind::Fn, node_id)),
666 ast::VariantData::Unit(node_id) => Some((CtorKind::Const, node_id)),
667 ast::VariantData::Struct { .. } => None,
668 }
669 }
670}
671
672impl NonMacroAttrKind {
673 pub fn descr(self) -> &'static str {
674 match self {
675 NonMacroAttrKind::Builtin(..) => "built-in attribute",
676 NonMacroAttrKind::Tool => "tool attribute",
677 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
678 "derive helper attribute"
679 }
680 }
681 }
682
683 // Currently trivial, but exists in case a new kind is added in the future whose name starts
684 // with a vowel.
685 pub fn article(self) -> &'static str {
686 "a"
687 }
688
689 /// Users of some attributes cannot mark them as used, so they are considered always used.
690 pub fn is_used(self) -> bool {
691 match self {
692 NonMacroAttrKind::Tool
693 | NonMacroAttrKind::DeriveHelper
694 | NonMacroAttrKind::DeriveHelperCompat => true,
695 NonMacroAttrKind::Builtin(..) => false,
696 }
697 }
698}
699
700impl<Id> Res<Id> {
701 /// Return the `DefId` of this `Def` if it has an ID, else panic.
702 pub fn def_id(&self) -> DefId
703 where
704 Id: Debug,
705 {
706 self.opt_def_id().unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}"))
707 }
708
709 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
710 pub fn opt_def_id(&self) -> Option<DefId> {
711 match *self {
712 Res::Def(_, id) => Some(id),
713
714 Res::Local(..)
715 | Res::PrimTy(..)
716 | Res::SelfTyParam { .. }
717 | Res::SelfTyAlias { .. }
718 | Res::SelfCtor(..)
719 | Res::ToolMod
720 | Res::NonMacroAttr(..)
721 | Res::Err => None,
722 }
723 }
724
725 /// Return the `DefId` of this `Res` if it represents a module.
726 pub fn mod_def_id(&self) -> Option<DefId> {
727 match *self {
728 Res::Def(DefKind::Mod, id) => Some(id),
729 _ => None,
730 }
731 }
732
733 /// If this is a "module" in name resolution sense, return its `DefId`.
734 #[inline]
735 pub fn module_like_def_id(&self) -> Option<DefId> {
736 match self {
737 Res::Def(def_kind, def_id) if def_kind.is_module_like() => Some(*def_id),
738 _ => None,
739 }
740 }
741
742 /// A human readable name for the res kind ("function", "module", etc.).
743 pub fn descr(&self) -> &'static str {
744 match *self {
745 Res::Def(kind, def_id) => kind.descr(def_id),
746 Res::SelfCtor(..) => "self constructor",
747 Res::PrimTy(..) => "builtin type",
748 Res::Local(..) => "local variable",
749 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
750 Res::ToolMod => "tool module",
751 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
752 Res::Err => "unresolved item",
753 }
754 }
755
756 /// Gets an English article for the `Res`.
757 pub fn article(&self) -> &'static str {
758 match *self {
759 Res::Def(kind, _) => kind.article(),
760 Res::NonMacroAttr(kind) => kind.article(),
761 Res::Err => "an",
762 _ => "a",
763 }
764 }
765
766 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
767 match self {
768 Res::Def(kind, id) => Res::Def(kind, id),
769 Res::SelfCtor(id) => Res::SelfCtor(id),
770 Res::PrimTy(id) => Res::PrimTy(id),
771 Res::Local(id) => Res::Local(map(id)),
772 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
773 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
774 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
775 }
776 Res::ToolMod => Res::ToolMod,
777 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
778 Res::Err => Res::Err,
779 }
780 }
781
782 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
783 Ok(match self {
784 Res::Def(kind, id) => Res::Def(kind, id),
785 Res::SelfCtor(id) => Res::SelfCtor(id),
786 Res::PrimTy(id) => Res::PrimTy(id),
787 Res::Local(id) => Res::Local(map(id)?),
788 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
789 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
790 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
791 }
792 Res::ToolMod => Res::ToolMod,
793 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
794 Res::Err => Res::Err,
795 })
796 }
797
798 #[track_caller]
799 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
800 self.map_id(
801 #[track_caller]
802 |_| panic!("unexpected `Res::Local`"),
803 )
804 }
805
806 pub fn macro_kind(self) -> Option<MacroKind> {
807 match self {
808 Res::Def(DefKind::Macro(kind), _) => Some(kind),
809 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
810 _ => None,
811 }
812 }
813
814 /// Returns `None` if this is `Res::Err`
815 pub fn ns(&self) -> Option<Namespace> {
816 match self {
817 Res::Def(kind, ..) => kind.ns(),
818 Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
819 Some(Namespace::TypeNS)
820 }
821 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
822 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
823 Res::Err => None,
824 }
825 }
826
827 /// Always returns `true` if `self` is `Res::Err`
828 pub fn matches_ns(&self, ns: Namespace) -> bool {
829 self.ns().is_none_or(|actual_ns| actual_ns == ns)
830 }
831
832 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
833 pub fn expected_in_tuple_struct_pat(&self) -> bool {
834 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
835 }
836
837 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
838 pub fn expected_in_unit_struct_pat(&self) -> bool {
839 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
840 }
841}
842
843/// Resolution for a lifetime appearing in a type.
844#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
845pub enum LifetimeRes {
846 /// Successfully linked the lifetime to a generic parameter.
847 Param {
848 /// Id of the generic parameter that introduced it.
849 param: LocalDefId,
850 /// Id of the introducing place. That can be:
851 /// - an item's id, for the item's generic parameters;
852 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
853 /// - a FnPtr type's id.
854 ///
855 /// This information is used for impl-trait lifetime captures, to know when to or not to
856 /// capture any given lifetime.
857 binder: NodeId,
858 },
859 /// Created a generic parameter for an anonymous lifetime.
860 Fresh {
861 /// Id of the generic parameter that introduced it.
862 ///
863 /// Creating the associated `LocalDefId` is the responsibility of lowering.
864 param: NodeId,
865 /// Id of the introducing place. See `Param`.
866 binder: NodeId,
867 /// Kind of elided lifetime
868 kind: hir::MissingLifetimeKind,
869 },
870 /// This variant is used for anonymous lifetimes that we did not resolve during
871 /// late resolution. Those lifetimes will be inferred by typechecking.
872 Infer,
873 /// `'static` lifetime.
874 Static,
875 /// Resolution failure.
876 Error,
877 /// HACK: This is used to recover the NodeId of an elided lifetime.
878 ElidedAnchor { start: NodeId, end: NodeId },
879}
880
881pub type DocLinkResMap = UnordMap<(Symbol, Namespace), Option<Res<NodeId>>>;