5 use rustc_macros::HashStable_Generic;
6 use rustc_span::def_id::{DefId, LocalDefId};
7 use rustc_span::hygiene::MacroKind;
8 use rustc_span::Symbol;
10 use std::array::IntoIter;
13 /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
14 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
15 #[derive(HashStable_Generic)]
17 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
19 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
23 /// What kind of constructor something is.
24 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
25 #[derive(HashStable_Generic)]
27 /// Constructor function automatically created by a tuple struct/variant.
29 /// Constructor constant automatically created by a unit struct/variant.
31 /// Unusable name in value namespace created by a struct variant.
35 /// An attribute that is not a macro; e.g., `#[inline]` or `#[rustfmt::skip]`.
36 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
37 #[derive(HashStable_Generic)]
38 pub enum NonMacroAttrKind {
39 /// Single-segment attribute defined by the language (`#[inline]`)
41 /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
43 /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
45 /// Single-segment custom attribute registered by a derive macro
46 /// but used before that derive macro was expanded (deprecated).
50 /// What kind of definition something is; e.g., `mod` vs `struct`.
51 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
52 #[derive(HashStable_Generic)]
56 /// Refers to the struct itself, [`DefKind::Ctor`] refers to its constructor if it exists.
60 /// Refers to the variant itself, [`DefKind::Ctor`] refers to its constructor if it exists.
63 /// Type alias: `type Foo = Bar;`
65 /// Type from an `extern` block.
67 /// Trait alias: `trait IntIterator = Iterator<Item = i32>;`
69 /// Associated type: `trait MyTrait { type Assoc; }`
71 /// Type parameter: the `T` in `struct Vec<T> { ... }`
77 /// Constant generic parameter: `struct Foo<const N: usize> { ... }`
79 Static(ast::Mutability),
80 /// Refers to the struct or enum variant's constructor.
82 /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
83 /// [`DefKind::Variant`] is because structs and enum variants exist
84 /// in the *type* namespace, whereas struct and enum variant *constructors*
85 /// exist in the *value* namespace.
87 /// You may wonder why enum variants exist in the type namespace as opposed
88 /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
90 /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
91 Ctor(CtorOf, CtorKind),
92 /// Associated function: `impl MyStruct { fn associated() {} }`
93 /// or `trait Foo { fn associated() {} }`
95 /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
101 // Not namespaced (or they are, but we don't treat them so)
104 /// An `extern` block.
106 /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`
108 /// An inline constant, e.g. `const { 1 + 2 }`
110 /// Opaque type, aka `impl Trait`.
113 /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
115 /// A use of `global_asm!`.
123 pub fn descr(self, def_id: DefId) -> &'static str {
125 DefKind::Fn => "function",
126 DefKind::Mod if def_id.is_crate_root() && !def_id.is_local() => "crate",
127 DefKind::Mod => "module",
128 DefKind::Static(..) => "static",
129 DefKind::Enum => "enum",
130 DefKind::Variant => "variant",
131 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
132 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
133 DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
134 DefKind::Struct => "struct",
135 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
136 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
137 DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
138 panic!("impossible struct constructor")
140 DefKind::OpaqueTy => "opaque type",
141 DefKind::TyAlias => "type alias",
142 DefKind::TraitAlias => "trait alias",
143 DefKind::AssocTy => "associated type",
144 DefKind::Union => "union",
145 DefKind::Trait => "trait",
146 DefKind::ForeignTy => "foreign type",
147 DefKind::AssocFn => "associated function",
148 DefKind::Const => "constant",
149 DefKind::AssocConst => "associated constant",
150 DefKind::TyParam => "type parameter",
151 DefKind::ConstParam => "const parameter",
152 DefKind::Macro(macro_kind) => macro_kind.descr(),
153 DefKind::LifetimeParam => "lifetime parameter",
154 DefKind::Use => "import",
155 DefKind::ForeignMod => "foreign module",
156 DefKind::AnonConst => "constant expression",
157 DefKind::InlineConst => "inline constant",
158 DefKind::Field => "field",
159 DefKind::Impl => "implementation",
160 DefKind::Closure => "closure",
161 DefKind::Generator => "generator",
162 DefKind::ExternCrate => "extern crate",
163 DefKind::GlobalAsm => "global assembly block",
167 /// Gets an English article for the definition.
168 pub fn article(&self) -> &'static str {
171 | DefKind::AssocConst
177 | DefKind::InlineConst
178 | DefKind::ExternCrate => "an",
179 DefKind::Macro(macro_kind) => macro_kind.article(),
184 pub fn ns(&self) -> Option<Namespace> {
195 | DefKind::TraitAlias
197 | DefKind::TyParam => Some(Namespace::TypeNS),
201 | DefKind::ConstParam
202 | DefKind::Static(..)
205 | DefKind::AssocConst => Some(Namespace::ValueNS),
207 DefKind::Macro(..) => Some(Namespace::MacroNS),
211 | DefKind::InlineConst
213 | DefKind::LifetimeParam
214 | DefKind::ExternCrate
218 | DefKind::ForeignMod
220 | DefKind::Impl => None,
225 pub fn is_fn_like(self) -> bool {
227 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true,
232 /// Whether `query get_codegen_attrs` should be used with this definition.
233 pub fn has_codegen_attrs(self) -> bool {
240 | DefKind::Static(_) => true,
249 | DefKind::TraitAlias
252 | DefKind::AssocConst
255 | DefKind::ForeignMod
260 | DefKind::ConstParam
261 | DefKind::LifetimeParam
263 | DefKind::InlineConst
265 | DefKind::ExternCrate => false,
270 /// The resolution of a path or export.
272 /// For every path or identifier in Rust, the compiler must determine
273 /// what the path refers to. This process is called name resolution,
274 /// and `Res` is the primary result of name resolution.
276 /// For example, everything prefixed with `/* Res */` in this example has
277 /// an associated `Res`:
280 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
281 /// /* Res */ String::from(/* Res */ s)
284 /// /* Res */ str_to_string("hello");
287 /// The associated `Res`s will be:
289 /// - `str` will resolve to [`Res::PrimTy`];
290 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
291 /// for `String` as defined in the standard library;
292 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
293 /// pointing to `String::from`;
294 /// - `s` will resolve to [`Res::Local`];
295 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
296 /// pointing to the definition of `str_to_string` in the current crate.
298 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
299 #[derive(HashStable_Generic)]
300 pub enum Res<Id = hir::HirId> {
301 /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
303 /// **Not bound to a specific namespace.**
307 /// A primitive type such as `i32` or `str`.
309 /// **Belongs to the type namespace.**
311 /// The `Self` type, optionally with the [`DefId`] of the trait it belongs to and
312 /// optionally with the [`DefId`] of the item introducing the `Self` type alias.
314 /// **Belongs to the type namespace.**
318 /// struct Bar(Box<Self>);
319 /// // `Res::SelfTy { trait_: None, alias_of: Some(Bar) }`
322 /// fn foo() -> Box<Self>;
323 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: None }`
329 /// // `Res::SelfTy { trait_: None, alias_of: Some(::{impl#0}) }`
333 /// impl Foo for Bar {
334 /// fn foo() -> Box<Self> {
335 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
337 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
344 /// *See also [`Res::SelfCtor`].*
348 /// HACK(min_const_generics): self types also have an optional requirement to **not** mention
349 /// any generic parameters to allow the following with `min_const_generics`:
352 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
354 /// struct Bar([u8; baz::<Self>()]);
355 /// const fn baz<T>() -> usize { 10 }
357 /// We do however allow `Self` in repeat expression even if it is generic to not break code
358 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint:
361 /// let _bar = [1_u8; std::mem::size_of::<*mut T>()];
364 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
366 /// The trait this `Self` is a generic arg for.
367 trait_: Option<DefId>,
368 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
369 /// to get the underlying type. Additionally whether the `Self` type is disallowed
370 /// from mentioning generics (i.e. when used in an anonymous constant).
371 alias_to: Option<(DefId, bool)>,
373 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
375 /// **Belongs to the type namespace.**
379 /// The `Self` constructor, along with the [`DefId`]
380 /// of the impl it is associated with.
382 /// **Belongs to the value namespace.**
384 /// *See also [`Res::SelfTy`].*
386 /// A local variable or function parameter.
388 /// **Belongs to the value namespace.**
392 /// An attribute that is *not* implemented via macro.
393 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
394 /// as opposed to `#[test]`, which is a builtin macro.
396 /// **Belongs to the macro namespace.**
397 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
400 /// Name resolution failed. We use a dummy `Res` variant so later phases
401 /// of the compiler won't crash and can instead report more errors.
403 /// **Not bound to a specific namespace.**
407 /// The result of resolving a path before lowering to HIR,
408 /// with "module" segments resolved and associated item
409 /// segments deferred to type checking.
410 /// `base_res` is the resolution of the resolved part of the
411 /// path, `unresolved_segments` is the number of unresolved
415 /// module::Type::AssocX::AssocY::MethodOrAssocType
416 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
417 /// base_res unresolved_segments = 3
419 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
420 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
421 /// base_res unresolved_segments = 2
423 #[derive(Copy, Clone, Debug)]
424 pub struct PartialRes {
425 base_res: Res<NodeId>,
426 unresolved_segments: usize,
431 pub fn new(base_res: Res<NodeId>) -> Self {
432 PartialRes { base_res, unresolved_segments: 0 }
436 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
437 if base_res == Res::Err {
438 unresolved_segments = 0
440 PartialRes { base_res, unresolved_segments }
444 pub fn base_res(&self) -> Res<NodeId> {
449 pub fn unresolved_segments(&self) -> usize {
450 self.unresolved_segments
454 /// Different kinds of symbols can coexist even if they share the same textual name.
455 /// Therefore, they each have a separate universe (known as a "namespace").
456 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
458 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
459 /// (and, by extension, crates).
461 /// Note that the type namespace includes other items; this is not an
464 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
466 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
467 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
468 /// like `#[inline]` and `#[rustfmt::skip]`.
473 /// The English description of the namespace.
474 pub fn descr(self) -> &'static str {
476 Self::TypeNS => "type",
477 Self::ValueNS => "value",
478 Self::MacroNS => "macro",
483 /// Just a helper ‒ separate structure for each namespace.
484 #[derive(Copy, Clone, Default, Debug)]
485 pub struct PerNS<T> {
492 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
493 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
496 pub fn into_iter(self) -> IntoIter<T, 3> {
497 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
500 pub fn iter(&self) -> IntoIter<&T, 3> {
501 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
505 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
508 fn index(&self, ns: Namespace) -> &T {
510 Namespace::ValueNS => &self.value_ns,
511 Namespace::TypeNS => &self.type_ns,
512 Namespace::MacroNS => &self.macro_ns,
517 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
518 fn index_mut(&mut self, ns: Namespace) -> &mut T {
520 Namespace::ValueNS => &mut self.value_ns,
521 Namespace::TypeNS => &mut self.type_ns,
522 Namespace::MacroNS => &mut self.macro_ns,
527 impl<T> PerNS<Option<T>> {
528 /// Returns `true` if all the items in this collection are `None`.
529 pub fn is_empty(&self) -> bool {
530 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
533 /// Returns an iterator over the items which are `Some`.
534 pub fn present_items(self) -> impl Iterator<Item = T> {
535 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
540 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
542 ast::VariantData::Tuple(..) => CtorKind::Fn,
543 ast::VariantData::Unit(..) => CtorKind::Const,
544 ast::VariantData::Struct(..) => CtorKind::Fictive,
548 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
550 hir::VariantData::Tuple(..) => CtorKind::Fn,
551 hir::VariantData::Unit(..) => CtorKind::Const,
552 hir::VariantData::Struct(..) => CtorKind::Fictive,
557 impl NonMacroAttrKind {
558 pub fn descr(self) -> &'static str {
560 NonMacroAttrKind::Builtin(..) => "built-in attribute",
561 NonMacroAttrKind::Tool => "tool attribute",
562 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
563 "derive helper attribute"
568 pub fn article(self) -> &'static str {
572 /// Users of some attributes cannot mark them as used, so they are considered always used.
573 pub fn is_used(self) -> bool {
575 NonMacroAttrKind::Tool
576 | NonMacroAttrKind::DeriveHelper
577 | NonMacroAttrKind::DeriveHelperCompat => true,
578 NonMacroAttrKind::Builtin(..) => false,
584 /// Return the `DefId` of this `Def` if it has an ID, else panic.
585 pub fn def_id(&self) -> DefId
590 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
593 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
594 pub fn opt_def_id(&self) -> Option<DefId> {
596 Res::Def(_, id) => Some(id),
603 | Res::NonMacroAttr(..)
608 /// Return the `DefId` of this `Res` if it represents a module.
609 pub fn mod_def_id(&self) -> Option<DefId> {
611 Res::Def(DefKind::Mod, id) => Some(id),
616 /// A human readable name for the res kind ("function", "module", etc.).
617 pub fn descr(&self) -> &'static str {
619 Res::Def(kind, def_id) => kind.descr(def_id),
620 Res::SelfCtor(..) => "self constructor",
621 Res::PrimTy(..) => "builtin type",
622 Res::Local(..) => "local variable",
623 Res::SelfTy { .. } => "self type",
624 Res::ToolMod => "tool module",
625 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
626 Res::Err => "unresolved item",
630 /// Gets an English article for the `Res`.
631 pub fn article(&self) -> &'static str {
633 Res::Def(kind, _) => kind.article(),
634 Res::NonMacroAttr(kind) => kind.article(),
640 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
642 Res::Def(kind, id) => Res::Def(kind, id),
643 Res::SelfCtor(id) => Res::SelfCtor(id),
644 Res::PrimTy(id) => Res::PrimTy(id),
645 Res::Local(id) => Res::Local(map(id)),
646 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
647 Res::ToolMod => Res::ToolMod,
648 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
649 Res::Err => Res::Err,
653 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
655 Res::Def(kind, id) => Res::Def(kind, id),
656 Res::SelfCtor(id) => Res::SelfCtor(id),
657 Res::PrimTy(id) => Res::PrimTy(id),
658 Res::Local(id) => Res::Local(map(id)?),
659 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
660 Res::ToolMod => Res::ToolMod,
661 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
662 Res::Err => Res::Err,
667 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
670 |_| panic!("unexpected `Res::Local`"),
674 pub fn macro_kind(self) -> Option<MacroKind> {
676 Res::Def(DefKind::Macro(kind), _) => Some(kind),
677 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
682 /// Returns `None` if this is `Res::Err`
683 pub fn ns(&self) -> Option<Namespace> {
685 Res::Def(kind, ..) => kind.ns(),
686 Res::PrimTy(..) | Res::SelfTy { .. } | Res::ToolMod => Some(Namespace::TypeNS),
687 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
688 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
693 /// Always returns `true` if `self` is `Res::Err`
694 pub fn matches_ns(&self, ns: Namespace) -> bool {
695 self.ns().map_or(true, |actual_ns| actual_ns == ns)
698 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
699 pub fn expected_in_tuple_struct_pat(&self) -> bool {
700 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
703 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
704 pub fn expected_in_unit_struct_pat(&self) -> bool {
705 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
709 /// Resolution for a lifetime appearing in a type.
710 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
711 pub enum LifetimeRes {
712 /// Successfully linked the lifetime to a generic parameter.
714 /// Id of the generic parameter that introduced it.
716 /// Id of the introducing place. That can be:
717 /// - an item's id, for the item's generic parameters;
718 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
719 /// - a BareFn type's id.
721 /// This information is used for impl-trait lifetime captures, to know when to or not to
722 /// capture any given lifetime.
725 /// Created a generic parameter for an anonymous lifetime.
727 /// Id of the generic parameter that introduced it.
729 /// Creating the associated `LocalDefId` is the responsibility of lowering.
731 /// Id of the introducing place. See `Param`.
734 /// This variant is used for anonymous lifetimes that we did not resolve during
735 /// late resolution. Those lifetimes will be inferred by typechecking.
737 /// Explicit `'static` lifetime.
739 /// Resolution failure.
741 /// HACK: This is used to recover the NodeId of an elided lifetime.
742 ElidedAnchor { start: NodeId, end: NodeId },