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`.
112 /// A return-position `impl Trait` in a trait definition
113 ImplTraitPlaceholder,
115 /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
117 /// A use of `global_asm!`.
125 pub fn descr(self, def_id: DefId) -> &'static str {
127 DefKind::Fn => "function",
128 DefKind::Mod if def_id.is_crate_root() && !def_id.is_local() => "crate",
129 DefKind::Mod => "module",
130 DefKind::Static(..) => "static",
131 DefKind::Enum => "enum",
132 DefKind::Variant => "variant",
133 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
134 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
135 DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
136 DefKind::Struct => "struct",
137 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
138 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
139 DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
140 panic!("impossible struct constructor")
142 DefKind::OpaqueTy => "opaque type",
143 DefKind::ImplTraitPlaceholder => "opaque type in trait",
144 DefKind::TyAlias => "type alias",
145 DefKind::TraitAlias => "trait alias",
146 DefKind::AssocTy => "associated type",
147 DefKind::Union => "union",
148 DefKind::Trait => "trait",
149 DefKind::ForeignTy => "foreign type",
150 DefKind::AssocFn => "associated function",
151 DefKind::Const => "constant",
152 DefKind::AssocConst => "associated constant",
153 DefKind::TyParam => "type parameter",
154 DefKind::ConstParam => "const parameter",
155 DefKind::Macro(macro_kind) => macro_kind.descr(),
156 DefKind::LifetimeParam => "lifetime parameter",
157 DefKind::Use => "import",
158 DefKind::ForeignMod => "foreign module",
159 DefKind::AnonConst => "constant expression",
160 DefKind::InlineConst => "inline constant",
161 DefKind::Field => "field",
162 DefKind::Impl => "implementation",
163 DefKind::Closure => "closure",
164 DefKind::Generator => "generator",
165 DefKind::ExternCrate => "extern crate",
166 DefKind::GlobalAsm => "global assembly block",
170 /// Gets an English article for the definition.
171 pub fn article(&self) -> &'static str {
174 | DefKind::AssocConst
180 | DefKind::InlineConst
181 | DefKind::ExternCrate => "an",
182 DefKind::Macro(macro_kind) => macro_kind.article(),
187 pub fn ns(&self) -> Option<Namespace> {
198 | DefKind::TraitAlias
200 | DefKind::TyParam => Some(Namespace::TypeNS),
204 | DefKind::ConstParam
205 | DefKind::Static(..)
208 | DefKind::AssocConst => Some(Namespace::ValueNS),
210 DefKind::Macro(..) => Some(Namespace::MacroNS),
214 | DefKind::InlineConst
216 | DefKind::LifetimeParam
217 | DefKind::ExternCrate
221 | DefKind::ForeignMod
224 | DefKind::ImplTraitPlaceholder => None,
229 pub fn is_fn_like(self) -> bool {
231 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true,
236 /// Whether `query get_codegen_attrs` should be used with this definition.
237 pub fn has_codegen_attrs(self) -> bool {
244 | DefKind::Static(_) => true,
253 | DefKind::TraitAlias
256 | DefKind::AssocConst
259 | DefKind::ForeignMod
261 | DefKind::ImplTraitPlaceholder
265 | DefKind::ConstParam
266 | DefKind::LifetimeParam
268 | DefKind::InlineConst
270 | DefKind::ExternCrate => false,
275 /// The resolution of a path or export.
277 /// For every path or identifier in Rust, the compiler must determine
278 /// what the path refers to. This process is called name resolution,
279 /// and `Res` is the primary result of name resolution.
281 /// For example, everything prefixed with `/* Res */` in this example has
282 /// an associated `Res`:
285 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
286 /// /* Res */ String::from(/* Res */ s)
289 /// /* Res */ str_to_string("hello");
292 /// The associated `Res`s will be:
294 /// - `str` will resolve to [`Res::PrimTy`];
295 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
296 /// for `String` as defined in the standard library;
297 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
298 /// pointing to `String::from`;
299 /// - `s` will resolve to [`Res::Local`];
300 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
301 /// pointing to the definition of `str_to_string` in the current crate.
303 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
304 #[derive(HashStable_Generic)]
305 pub enum Res<Id = hir::HirId> {
306 /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
308 /// **Not bound to a specific namespace.**
312 /// A primitive type such as `i32` or `str`.
314 /// **Belongs to the type namespace.**
317 /// The `Self` type, as used within a trait.
319 /// **Belongs to the type namespace.**
321 /// See the examples on [`Res::SelfTyAlias`] for details.
323 /// The trait this `Self` is a generic parameter for.
327 /// The `Self` type, as used somewhere other than within a trait.
329 /// **Belongs to the type namespace.**
333 /// struct Bar(Box<Self>); // SelfTyAlias
336 /// fn foo() -> Box<Self>; // SelfTyParam
341 /// let _: Self; // SelfTyAlias
345 /// impl Foo for Bar {
346 /// fn foo() -> Box<Self> { // SelfTyAlias
347 /// let _: Self; // SelfTyAlias
353 /// *See also [`Res::SelfCtor`].*
356 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
357 /// to get the underlying type.
360 /// Whether the `Self` type is disallowed from mentioning generics (i.e. when used in an
361 /// anonymous constant).
363 /// HACK(min_const_generics): self types also have an optional requirement to **not**
364 /// mention any generic parameters to allow the following with `min_const_generics`:
367 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
369 /// struct Bar([u8; baz::<Self>()]);
370 /// const fn baz<T>() -> usize { 10 }
372 /// We do however allow `Self` in repeat expression even if it is generic to not break code
373 /// which already works on stable while causing the `const_evaluatable_unchecked` future
377 /// let _bar = [1_u8; std::mem::size_of::<*mut T>()];
380 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
381 forbid_generic: bool,
383 /// Is this within an `impl Foo for bar`?
388 /// The `Self` constructor, along with the [`DefId`]
389 /// of the impl it is associated with.
391 /// **Belongs to the value namespace.**
393 /// *See also [`Res::SelfTyParam`] and [`Res::SelfTyAlias`].*
396 /// A local variable or function parameter.
398 /// **Belongs to the value namespace.**
401 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
403 /// **Belongs to the type namespace.**
407 /// An attribute that is *not* implemented via macro.
408 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
409 /// as opposed to `#[test]`, which is a builtin macro.
411 /// **Belongs to the macro namespace.**
412 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
415 /// Name resolution failed. We use a dummy `Res` variant so later phases
416 /// of the compiler won't crash and can instead report more errors.
418 /// **Not bound to a specific namespace.**
422 /// The result of resolving a path before lowering to HIR,
423 /// with "module" segments resolved and associated item
424 /// segments deferred to type checking.
425 /// `base_res` is the resolution of the resolved part of the
426 /// path, `unresolved_segments` is the number of unresolved
430 /// module::Type::AssocX::AssocY::MethodOrAssocType
431 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
432 /// base_res unresolved_segments = 3
434 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
435 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
436 /// base_res unresolved_segments = 2
438 #[derive(Copy, Clone, Debug)]
439 pub struct PartialRes {
440 base_res: Res<NodeId>,
441 unresolved_segments: usize,
446 pub fn new(base_res: Res<NodeId>) -> Self {
447 PartialRes { base_res, unresolved_segments: 0 }
451 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
452 if base_res == Res::Err {
453 unresolved_segments = 0
455 PartialRes { base_res, unresolved_segments }
459 pub fn base_res(&self) -> Res<NodeId> {
464 pub fn unresolved_segments(&self) -> usize {
465 self.unresolved_segments
469 /// Different kinds of symbols can coexist even if they share the same textual name.
470 /// Therefore, they each have a separate universe (known as a "namespace").
471 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
473 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
474 /// (and, by extension, crates).
476 /// Note that the type namespace includes other items; this is not an
479 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
481 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
482 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
483 /// like `#[inline]` and `#[rustfmt::skip]`.
488 /// The English description of the namespace.
489 pub fn descr(self) -> &'static str {
491 Self::TypeNS => "type",
492 Self::ValueNS => "value",
493 Self::MacroNS => "macro",
498 /// Just a helper ‒ separate structure for each namespace.
499 #[derive(Copy, Clone, Default, Debug)]
500 pub struct PerNS<T> {
507 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
508 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
511 pub fn into_iter(self) -> IntoIter<T, 3> {
512 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
515 pub fn iter(&self) -> IntoIter<&T, 3> {
516 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
520 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
523 fn index(&self, ns: Namespace) -> &T {
525 Namespace::ValueNS => &self.value_ns,
526 Namespace::TypeNS => &self.type_ns,
527 Namespace::MacroNS => &self.macro_ns,
532 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
533 fn index_mut(&mut self, ns: Namespace) -> &mut T {
535 Namespace::ValueNS => &mut self.value_ns,
536 Namespace::TypeNS => &mut self.type_ns,
537 Namespace::MacroNS => &mut self.macro_ns,
542 impl<T> PerNS<Option<T>> {
543 /// Returns `true` if all the items in this collection are `None`.
544 pub fn is_empty(&self) -> bool {
545 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
548 /// Returns an iterator over the items which are `Some`.
549 pub fn present_items(self) -> impl Iterator<Item = T> {
550 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
555 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
557 ast::VariantData::Tuple(..) => CtorKind::Fn,
558 ast::VariantData::Unit(..) => CtorKind::Const,
559 ast::VariantData::Struct(..) => CtorKind::Fictive,
563 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
565 hir::VariantData::Tuple(..) => CtorKind::Fn,
566 hir::VariantData::Unit(..) => CtorKind::Const,
567 hir::VariantData::Struct(..) => CtorKind::Fictive,
572 impl NonMacroAttrKind {
573 pub fn descr(self) -> &'static str {
575 NonMacroAttrKind::Builtin(..) => "built-in attribute",
576 NonMacroAttrKind::Tool => "tool attribute",
577 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
578 "derive helper attribute"
583 pub fn article(self) -> &'static str {
587 /// Users of some attributes cannot mark them as used, so they are considered always used.
588 pub fn is_used(self) -> bool {
590 NonMacroAttrKind::Tool
591 | NonMacroAttrKind::DeriveHelper
592 | NonMacroAttrKind::DeriveHelperCompat => true,
593 NonMacroAttrKind::Builtin(..) => false,
599 /// Return the `DefId` of this `Def` if it has an ID, else panic.
600 pub fn def_id(&self) -> DefId
605 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
608 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
609 pub fn opt_def_id(&self) -> Option<DefId> {
611 Res::Def(_, id) => Some(id),
615 | Res::SelfTyParam { .. }
616 | Res::SelfTyAlias { .. }
619 | Res::NonMacroAttr(..)
624 /// Return the `DefId` of this `Res` if it represents a module.
625 pub fn mod_def_id(&self) -> Option<DefId> {
627 Res::Def(DefKind::Mod, id) => Some(id),
632 /// A human readable name for the res kind ("function", "module", etc.).
633 pub fn descr(&self) -> &'static str {
635 Res::Def(kind, def_id) => kind.descr(def_id),
636 Res::SelfCtor(..) => "self constructor",
637 Res::PrimTy(..) => "builtin type",
638 Res::Local(..) => "local variable",
639 Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
640 Res::ToolMod => "tool module",
641 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
642 Res::Err => "unresolved item",
646 /// Gets an English article for the `Res`.
647 pub fn article(&self) -> &'static str {
649 Res::Def(kind, _) => kind.article(),
650 Res::NonMacroAttr(kind) => kind.article(),
656 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
658 Res::Def(kind, id) => Res::Def(kind, id),
659 Res::SelfCtor(id) => Res::SelfCtor(id),
660 Res::PrimTy(id) => Res::PrimTy(id),
661 Res::Local(id) => Res::Local(map(id)),
662 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
663 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
664 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
666 Res::ToolMod => Res::ToolMod,
667 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
668 Res::Err => Res::Err,
672 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
674 Res::Def(kind, id) => Res::Def(kind, id),
675 Res::SelfCtor(id) => Res::SelfCtor(id),
676 Res::PrimTy(id) => Res::PrimTy(id),
677 Res::Local(id) => Res::Local(map(id)?),
678 Res::SelfTyParam { trait_ } => Res::SelfTyParam { trait_ },
679 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl } => {
680 Res::SelfTyAlias { alias_to, forbid_generic, is_trait_impl }
682 Res::ToolMod => Res::ToolMod,
683 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
684 Res::Err => Res::Err,
689 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
692 |_| panic!("unexpected `Res::Local`"),
696 pub fn macro_kind(self) -> Option<MacroKind> {
698 Res::Def(DefKind::Macro(kind), _) => Some(kind),
699 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
704 /// Returns `None` if this is `Res::Err`
705 pub fn ns(&self) -> Option<Namespace> {
707 Res::Def(kind, ..) => kind.ns(),
708 Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
709 Some(Namespace::TypeNS)
711 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
712 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
717 /// Always returns `true` if `self` is `Res::Err`
718 pub fn matches_ns(&self, ns: Namespace) -> bool {
719 self.ns().map_or(true, |actual_ns| actual_ns == ns)
722 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
723 pub fn expected_in_tuple_struct_pat(&self) -> bool {
724 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
727 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
728 pub fn expected_in_unit_struct_pat(&self) -> bool {
729 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
733 /// Resolution for a lifetime appearing in a type.
734 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
735 pub enum LifetimeRes {
736 /// Successfully linked the lifetime to a generic parameter.
738 /// Id of the generic parameter that introduced it.
740 /// Id of the introducing place. That can be:
741 /// - an item's id, for the item's generic parameters;
742 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
743 /// - a BareFn type's id.
745 /// This information is used for impl-trait lifetime captures, to know when to or not to
746 /// capture any given lifetime.
749 /// Created a generic parameter for an anonymous lifetime.
751 /// Id of the generic parameter that introduced it.
753 /// Creating the associated `LocalDefId` is the responsibility of lowering.
755 /// Id of the introducing place. See `Param`.
758 /// This variant is used for anonymous lifetimes that we did not resolve during
759 /// late resolution. Those lifetimes will be inferred by typechecking.
761 /// Explicit `'static` lifetime.
763 /// Resolution failure.
765 /// HACK: This is used to recover the NodeId of an elided lifetime.
766 ElidedAnchor { start: NodeId, end: NodeId },