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