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