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.**
312 /// The `Self` type, optionally with the [`DefId`] of the trait it belongs to and
313 /// optionally with the [`DefId`] of the item introducing the `Self` type alias.
315 /// **Belongs to the type namespace.**
319 /// struct Bar(Box<Self>);
320 /// // `Res::SelfTy { trait_: None, alias_of: Some(Bar) }`
323 /// fn foo() -> Box<Self>;
324 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: None }`
330 /// // `Res::SelfTy { trait_: None, alias_of: Some(::{impl#0}) }`
334 /// impl Foo for Bar {
335 /// fn foo() -> Box<Self> {
336 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
338 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
345 /// *See also [`Res::SelfCtor`].*
349 /// HACK(min_const_generics): self types also have an optional requirement to **not** mention
350 /// any generic parameters to allow the following with `min_const_generics`:
353 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
355 /// struct Bar([u8; baz::<Self>()]);
356 /// const fn baz<T>() -> usize { 10 }
358 /// We do however allow `Self` in repeat expression even if it is generic to not break code
359 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat
363 /// let _bar = [1_u8; std::mem::size_of::<*mut T>()];
366 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
368 /// The trait this `Self` is a generic arg for.
369 trait_: Option<DefId>,
370 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
371 /// to get the underlying type. Additionally whether the `Self` type is disallowed
372 /// from mentioning generics (i.e. when used in an anonymous constant).
373 alias_to: Option<(DefId, bool)>,
376 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
378 /// **Belongs to the type namespace.**
382 /// The `Self` constructor, along with the [`DefId`]
383 /// of the impl it is associated with.
385 /// **Belongs to the value namespace.**
387 /// *See also [`Res::SelfTy`].*
390 /// A local variable or function parameter.
392 /// **Belongs to the value namespace.**
396 /// An attribute that is *not* implemented via macro.
397 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
398 /// as opposed to `#[test]`, which is a builtin macro.
400 /// **Belongs to the macro namespace.**
401 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
404 /// Name resolution failed. We use a dummy `Res` variant so later phases
405 /// of the compiler won't crash and can instead report more errors.
407 /// **Not bound to a specific namespace.**
411 /// The result of resolving a path before lowering to HIR,
412 /// with "module" segments resolved and associated item
413 /// segments deferred to type checking.
414 /// `base_res` is the resolution of the resolved part of the
415 /// path, `unresolved_segments` is the number of unresolved
419 /// module::Type::AssocX::AssocY::MethodOrAssocType
420 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
421 /// base_res unresolved_segments = 3
423 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
424 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
425 /// base_res unresolved_segments = 2
427 #[derive(Copy, Clone, Debug)]
428 pub struct PartialRes {
429 base_res: Res<NodeId>,
430 unresolved_segments: usize,
435 pub fn new(base_res: Res<NodeId>) -> Self {
436 PartialRes { base_res, unresolved_segments: 0 }
440 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
441 if base_res == Res::Err {
442 unresolved_segments = 0
444 PartialRes { base_res, unresolved_segments }
448 pub fn base_res(&self) -> Res<NodeId> {
453 pub fn unresolved_segments(&self) -> usize {
454 self.unresolved_segments
458 /// Different kinds of symbols can coexist even if they share the same textual name.
459 /// Therefore, they each have a separate universe (known as a "namespace").
460 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
462 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
463 /// (and, by extension, crates).
465 /// Note that the type namespace includes other items; this is not an
468 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
470 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
471 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
472 /// like `#[inline]` and `#[rustfmt::skip]`.
477 /// The English description of the namespace.
478 pub fn descr(self) -> &'static str {
480 Self::TypeNS => "type",
481 Self::ValueNS => "value",
482 Self::MacroNS => "macro",
487 /// Just a helper ‒ separate structure for each namespace.
488 #[derive(Copy, Clone, Default, Debug)]
489 pub struct PerNS<T> {
496 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
497 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
500 pub fn into_iter(self) -> IntoIter<T, 3> {
501 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
504 pub fn iter(&self) -> IntoIter<&T, 3> {
505 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
509 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
512 fn index(&self, ns: Namespace) -> &T {
514 Namespace::ValueNS => &self.value_ns,
515 Namespace::TypeNS => &self.type_ns,
516 Namespace::MacroNS => &self.macro_ns,
521 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
522 fn index_mut(&mut self, ns: Namespace) -> &mut T {
524 Namespace::ValueNS => &mut self.value_ns,
525 Namespace::TypeNS => &mut self.type_ns,
526 Namespace::MacroNS => &mut self.macro_ns,
531 impl<T> PerNS<Option<T>> {
532 /// Returns `true` if all the items in this collection are `None`.
533 pub fn is_empty(&self) -> bool {
534 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
537 /// Returns an iterator over the items which are `Some`.
538 pub fn present_items(self) -> impl Iterator<Item = T> {
539 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
544 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
546 ast::VariantData::Tuple(..) => CtorKind::Fn,
547 ast::VariantData::Unit(..) => CtorKind::Const,
548 ast::VariantData::Struct(..) => CtorKind::Fictive,
552 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
554 hir::VariantData::Tuple(..) => CtorKind::Fn,
555 hir::VariantData::Unit(..) => CtorKind::Const,
556 hir::VariantData::Struct(..) => CtorKind::Fictive,
561 impl NonMacroAttrKind {
562 pub fn descr(self) -> &'static str {
564 NonMacroAttrKind::Builtin(..) => "built-in attribute",
565 NonMacroAttrKind::Tool => "tool attribute",
566 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
567 "derive helper attribute"
572 pub fn article(self) -> &'static str {
576 /// Users of some attributes cannot mark them as used, so they are considered always used.
577 pub fn is_used(self) -> bool {
579 NonMacroAttrKind::Tool
580 | NonMacroAttrKind::DeriveHelper
581 | NonMacroAttrKind::DeriveHelperCompat => true,
582 NonMacroAttrKind::Builtin(..) => false,
588 /// Return the `DefId` of this `Def` if it has an ID, else panic.
589 pub fn def_id(&self) -> DefId
594 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
597 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
598 pub fn opt_def_id(&self) -> Option<DefId> {
600 Res::Def(_, id) => Some(id),
607 | Res::NonMacroAttr(..)
612 /// Return the `DefId` of this `Res` if it represents a module.
613 pub fn mod_def_id(&self) -> Option<DefId> {
615 Res::Def(DefKind::Mod, id) => Some(id),
620 /// A human readable name for the res kind ("function", "module", etc.).
621 pub fn descr(&self) -> &'static str {
623 Res::Def(kind, def_id) => kind.descr(def_id),
624 Res::SelfCtor(..) => "self constructor",
625 Res::PrimTy(..) => "builtin type",
626 Res::Local(..) => "local variable",
627 Res::SelfTy { .. } => "self type",
628 Res::ToolMod => "tool module",
629 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
630 Res::Err => "unresolved item",
634 /// Gets an English article for the `Res`.
635 pub fn article(&self) -> &'static str {
637 Res::Def(kind, _) => kind.article(),
638 Res::NonMacroAttr(kind) => kind.article(),
644 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
646 Res::Def(kind, id) => Res::Def(kind, id),
647 Res::SelfCtor(id) => Res::SelfCtor(id),
648 Res::PrimTy(id) => Res::PrimTy(id),
649 Res::Local(id) => Res::Local(map(id)),
650 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
651 Res::ToolMod => Res::ToolMod,
652 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
653 Res::Err => Res::Err,
657 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
659 Res::Def(kind, id) => Res::Def(kind, id),
660 Res::SelfCtor(id) => Res::SelfCtor(id),
661 Res::PrimTy(id) => Res::PrimTy(id),
662 Res::Local(id) => Res::Local(map(id)?),
663 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
664 Res::ToolMod => Res::ToolMod,
665 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
666 Res::Err => Res::Err,
671 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
674 |_| panic!("unexpected `Res::Local`"),
678 pub fn macro_kind(self) -> Option<MacroKind> {
680 Res::Def(DefKind::Macro(kind), _) => Some(kind),
681 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
686 /// Returns `None` if this is `Res::Err`
687 pub fn ns(&self) -> Option<Namespace> {
689 Res::Def(kind, ..) => kind.ns(),
690 Res::PrimTy(..) | Res::SelfTy { .. } | Res::ToolMod => Some(Namespace::TypeNS),
691 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
692 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
697 /// Always returns `true` if `self` is `Res::Err`
698 pub fn matches_ns(&self, ns: Namespace) -> bool {
699 self.ns().map_or(true, |actual_ns| actual_ns == ns)
702 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
703 pub fn expected_in_tuple_struct_pat(&self) -> bool {
704 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
707 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
708 pub fn expected_in_unit_struct_pat(&self) -> bool {
709 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
713 /// Resolution for a lifetime appearing in a type.
714 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
715 pub enum LifetimeRes {
716 /// Successfully linked the lifetime to a generic parameter.
718 /// Id of the generic parameter that introduced it.
720 /// Id of the introducing place. That can be:
721 /// - an item's id, for the item's generic parameters;
722 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
723 /// - a BareFn type's id.
725 /// This information is used for impl-trait lifetime captures, to know when to or not to
726 /// capture any given lifetime.
729 /// Created a generic parameter for an anonymous lifetime.
731 /// Id of the generic parameter that introduced it.
733 /// Creating the associated `LocalDefId` is the responsibility of lowering.
735 /// Id of the introducing place. See `Param`.
738 /// This variant is used for anonymous lifetimes that we did not resolve during
739 /// late resolution. Those lifetimes will be inferred by typechecking.
741 /// Explicit `'static` lifetime.
743 /// Resolution failure.
745 /// HACK: This is used to recover the NodeId of an elided lifetime.
746 ElidedAnchor { start: NodeId, end: NodeId },