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, optionally with the [`DefId`] of the trait it belongs to and
318 /// optionally with the [`DefId`] of the item introducing the `Self` type alias.
320 /// **Belongs to the type namespace.**
324 /// struct Bar(Box<Self>);
325 /// // `Res::SelfTy { trait_: None, alias_of: Some(Bar) }`
328 /// fn foo() -> Box<Self>;
329 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: None }`
335 /// // `Res::SelfTy { trait_: None, alias_of: Some(::{impl#0}) }`
339 /// impl Foo for Bar {
340 /// fn foo() -> Box<Self> {
341 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
343 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
350 /// *See also [`Res::SelfCtor`].*
354 /// HACK(min_const_generics): self types also have an optional requirement to **not** mention
355 /// any generic parameters to allow the following with `min_const_generics`:
358 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
360 /// struct Bar([u8; baz::<Self>()]);
361 /// const fn baz<T>() -> usize { 10 }
363 /// We do however allow `Self` in repeat expression even if it is generic to not break code
364 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat
368 /// let _bar = [1_u8; std::mem::size_of::<*mut T>()];
371 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
373 /// The trait this `Self` is a generic arg for.
374 trait_: Option<DefId>,
375 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
376 /// to get the underlying type. Additionally whether the `Self` type is disallowed
377 /// from mentioning generics (i.e. when used in an anonymous constant).
378 alias_to: Option<(DefId, bool)>,
381 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
383 /// **Belongs to the type namespace.**
387 /// The `Self` constructor, along with the [`DefId`]
388 /// of the impl it is associated with.
390 /// **Belongs to the value namespace.**
392 /// *See also [`Res::SelfTy`].*
395 /// A local variable or function parameter.
397 /// **Belongs to the value namespace.**
401 /// An attribute that is *not* implemented via macro.
402 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
403 /// as opposed to `#[test]`, which is a builtin macro.
405 /// **Belongs to the macro namespace.**
406 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
409 /// Name resolution failed. We use a dummy `Res` variant so later phases
410 /// of the compiler won't crash and can instead report more errors.
412 /// **Not bound to a specific namespace.**
416 /// The result of resolving a path before lowering to HIR,
417 /// with "module" segments resolved and associated item
418 /// segments deferred to type checking.
419 /// `base_res` is the resolution of the resolved part of the
420 /// path, `unresolved_segments` is the number of unresolved
424 /// module::Type::AssocX::AssocY::MethodOrAssocType
425 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
426 /// base_res unresolved_segments = 3
428 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
429 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
430 /// base_res unresolved_segments = 2
432 #[derive(Copy, Clone, Debug)]
433 pub struct PartialRes {
434 base_res: Res<NodeId>,
435 unresolved_segments: usize,
440 pub fn new(base_res: Res<NodeId>) -> Self {
441 PartialRes { base_res, unresolved_segments: 0 }
445 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
446 if base_res == Res::Err {
447 unresolved_segments = 0
449 PartialRes { base_res, unresolved_segments }
453 pub fn base_res(&self) -> Res<NodeId> {
458 pub fn unresolved_segments(&self) -> usize {
459 self.unresolved_segments
463 /// Different kinds of symbols can coexist even if they share the same textual name.
464 /// Therefore, they each have a separate universe (known as a "namespace").
465 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
467 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
468 /// (and, by extension, crates).
470 /// Note that the type namespace includes other items; this is not an
473 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
475 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
476 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
477 /// like `#[inline]` and `#[rustfmt::skip]`.
482 /// The English description of the namespace.
483 pub fn descr(self) -> &'static str {
485 Self::TypeNS => "type",
486 Self::ValueNS => "value",
487 Self::MacroNS => "macro",
492 /// Just a helper ‒ separate structure for each namespace.
493 #[derive(Copy, Clone, Default, Debug)]
494 pub struct PerNS<T> {
501 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
502 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
505 pub fn into_iter(self) -> IntoIter<T, 3> {
506 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
509 pub fn iter(&self) -> IntoIter<&T, 3> {
510 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
514 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
517 fn index(&self, ns: Namespace) -> &T {
519 Namespace::ValueNS => &self.value_ns,
520 Namespace::TypeNS => &self.type_ns,
521 Namespace::MacroNS => &self.macro_ns,
526 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
527 fn index_mut(&mut self, ns: Namespace) -> &mut T {
529 Namespace::ValueNS => &mut self.value_ns,
530 Namespace::TypeNS => &mut self.type_ns,
531 Namespace::MacroNS => &mut self.macro_ns,
536 impl<T> PerNS<Option<T>> {
537 /// Returns `true` if all the items in this collection are `None`.
538 pub fn is_empty(&self) -> bool {
539 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
542 /// Returns an iterator over the items which are `Some`.
543 pub fn present_items(self) -> impl Iterator<Item = T> {
544 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
549 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
551 ast::VariantData::Tuple(..) => CtorKind::Fn,
552 ast::VariantData::Unit(..) => CtorKind::Const,
553 ast::VariantData::Struct(..) => CtorKind::Fictive,
557 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
559 hir::VariantData::Tuple(..) => CtorKind::Fn,
560 hir::VariantData::Unit(..) => CtorKind::Const,
561 hir::VariantData::Struct(..) => CtorKind::Fictive,
566 impl NonMacroAttrKind {
567 pub fn descr(self) -> &'static str {
569 NonMacroAttrKind::Builtin(..) => "built-in attribute",
570 NonMacroAttrKind::Tool => "tool attribute",
571 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
572 "derive helper attribute"
577 pub fn article(self) -> &'static str {
581 /// Users of some attributes cannot mark them as used, so they are considered always used.
582 pub fn is_used(self) -> bool {
584 NonMacroAttrKind::Tool
585 | NonMacroAttrKind::DeriveHelper
586 | NonMacroAttrKind::DeriveHelperCompat => true,
587 NonMacroAttrKind::Builtin(..) => false,
593 /// Return the `DefId` of this `Def` if it has an ID, else panic.
594 pub fn def_id(&self) -> DefId
599 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
602 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
603 pub fn opt_def_id(&self) -> Option<DefId> {
605 Res::Def(_, id) => Some(id),
612 | Res::NonMacroAttr(..)
617 /// Return the `DefId` of this `Res` if it represents a module.
618 pub fn mod_def_id(&self) -> Option<DefId> {
620 Res::Def(DefKind::Mod, id) => Some(id),
625 /// A human readable name for the res kind ("function", "module", etc.).
626 pub fn descr(&self) -> &'static str {
628 Res::Def(kind, def_id) => kind.descr(def_id),
629 Res::SelfCtor(..) => "self constructor",
630 Res::PrimTy(..) => "builtin type",
631 Res::Local(..) => "local variable",
632 Res::SelfTy { .. } => "self type",
633 Res::ToolMod => "tool module",
634 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
635 Res::Err => "unresolved item",
639 /// Gets an English article for the `Res`.
640 pub fn article(&self) -> &'static str {
642 Res::Def(kind, _) => kind.article(),
643 Res::NonMacroAttr(kind) => kind.article(),
649 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
651 Res::Def(kind, id) => Res::Def(kind, id),
652 Res::SelfCtor(id) => Res::SelfCtor(id),
653 Res::PrimTy(id) => Res::PrimTy(id),
654 Res::Local(id) => Res::Local(map(id)),
655 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
656 Res::ToolMod => Res::ToolMod,
657 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
658 Res::Err => Res::Err,
662 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
664 Res::Def(kind, id) => Res::Def(kind, id),
665 Res::SelfCtor(id) => Res::SelfCtor(id),
666 Res::PrimTy(id) => Res::PrimTy(id),
667 Res::Local(id) => Res::Local(map(id)?),
668 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
669 Res::ToolMod => Res::ToolMod,
670 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
671 Res::Err => Res::Err,
676 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
679 |_| panic!("unexpected `Res::Local`"),
683 pub fn macro_kind(self) -> Option<MacroKind> {
685 Res::Def(DefKind::Macro(kind), _) => Some(kind),
686 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
691 /// Returns `None` if this is `Res::Err`
692 pub fn ns(&self) -> Option<Namespace> {
694 Res::Def(kind, ..) => kind.ns(),
695 Res::PrimTy(..) | Res::SelfTy { .. } | Res::ToolMod => Some(Namespace::TypeNS),
696 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
697 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
702 /// Always returns `true` if `self` is `Res::Err`
703 pub fn matches_ns(&self, ns: Namespace) -> bool {
704 self.ns().map_or(true, |actual_ns| actual_ns == ns)
707 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
708 pub fn expected_in_tuple_struct_pat(&self) -> bool {
709 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
712 /// Returns whether such a resolved path can occur in a unit struct/variant pattern
713 pub fn expected_in_unit_struct_pat(&self) -> bool {
714 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..))
718 /// Resolution for a lifetime appearing in a type.
719 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
720 pub enum LifetimeRes {
721 /// Successfully linked the lifetime to a generic parameter.
723 /// Id of the generic parameter that introduced it.
725 /// Id of the introducing place. That can be:
726 /// - an item's id, for the item's generic parameters;
727 /// - a TraitRef's ref_id, identifying the `for<...>` binder;
728 /// - a BareFn type's id.
730 /// This information is used for impl-trait lifetime captures, to know when to or not to
731 /// capture any given lifetime.
734 /// Created a generic parameter for an anonymous lifetime.
736 /// Id of the generic parameter that introduced it.
738 /// Creating the associated `LocalDefId` is the responsibility of lowering.
740 /// Id of the introducing place. See `Param`.
743 /// This variant is used for anonymous lifetimes that we did not resolve during
744 /// late resolution. Those lifetimes will be inferred by typechecking.
746 /// Explicit `'static` lifetime.
748 /// Resolution failure.
750 /// HACK: This is used to recover the NodeId of an elided lifetime.
751 ElidedAnchor { start: NodeId, end: NodeId },