1 use crate::def_id::DefId;
6 use rustc_macros::HashStable_Generic;
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).
48 /// Single-segment custom attribute registered with `#[register_attr]`.
52 /// What kind of definition something is; e.g., `mod` vs `struct`.
53 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
54 #[derive(HashStable_Generic)]
58 /// Refers to the struct itself, [`DefKind::Ctor`] refers to its constructor if it exists.
62 /// Refers to the variant itself, [`DefKind::Ctor`] refers to its constructor if it exists.
65 /// Type alias: `type Foo = Bar;`
67 /// Type from an `extern` block.
69 /// Trait alias: `trait IntIterator = Iterator<Item = i32>;`
71 /// Associated type: `trait MyTrait { type Assoc; }`
73 /// Type parameter: the `T` in `struct Vec<T> { ... }`
79 /// Constant generic parameter: `struct Foo<const N: usize> { ... }`
81 Static(ast::Mutability),
82 /// Refers to the struct or enum variant's constructor.
84 /// The reason `Ctor` exists in addition to [`DefKind::Struct`] and
85 /// [`DefKind::Variant`] is because structs and enum variants exist
86 /// in the *type* namespace, whereas struct and enum variant *constructors*
87 /// exist in the *value* namespace.
89 /// You may wonder why enum variants exist in the type namespace as opposed
90 /// to the value namespace. Check out [RFC 2593] for intuition on why that is.
92 /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
93 Ctor(CtorOf, CtorKind),
94 /// Associated function: `impl MyStruct { fn associated() {} }`
96 /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
102 // Not namespaced (or they are, but we don't treat them so)
105 /// An `extern` block.
107 /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`
109 /// An inline constant, e.g. `const { 1 + 2 }`
111 /// Opaque type, aka `impl Trait`.
114 /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
116 /// A use of `global_asm!`.
124 pub fn descr(self, def_id: DefId) -> &'static str {
126 DefKind::Fn => "function",
127 DefKind::Mod if def_id.is_crate_root() && !def_id.is_local() => "crate",
128 DefKind::Mod => "module",
129 DefKind::Static(..) => "static",
130 DefKind::Enum => "enum",
131 DefKind::Variant => "variant",
132 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
133 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
134 DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
135 DefKind::Struct => "struct",
136 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
137 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
138 DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
139 panic!("impossible struct constructor")
141 DefKind::OpaqueTy => "opaque type",
142 DefKind::TyAlias => "type alias",
143 DefKind::TraitAlias => "trait alias",
144 DefKind::AssocTy => "associated type",
145 DefKind::Union => "union",
146 DefKind::Trait => "trait",
147 DefKind::ForeignTy => "foreign type",
148 DefKind::AssocFn => "associated function",
149 DefKind::Const => "constant",
150 DefKind::AssocConst => "associated constant",
151 DefKind::TyParam => "type parameter",
152 DefKind::ConstParam => "const parameter",
153 DefKind::Macro(macro_kind) => macro_kind.descr(),
154 DefKind::LifetimeParam => "lifetime parameter",
155 DefKind::Use => "import",
156 DefKind::ForeignMod => "foreign module",
157 DefKind::AnonConst => "constant expression",
158 DefKind::InlineConst => "inline constant",
159 DefKind::Field => "field",
160 DefKind::Impl => "implementation",
161 DefKind::Closure => "closure",
162 DefKind::Generator => "generator",
163 DefKind::ExternCrate => "extern crate",
164 DefKind::GlobalAsm => "global assembly block",
168 /// Gets an English article for the definition.
169 pub fn article(&self) -> &'static str {
172 | DefKind::AssocConst
178 | DefKind::InlineConst
179 | DefKind::ExternCrate => "an",
180 DefKind::Macro(macro_kind) => macro_kind.article(),
185 pub fn ns(&self) -> Option<Namespace> {
196 | DefKind::TraitAlias
198 | DefKind::TyParam => Some(Namespace::TypeNS),
202 | DefKind::ConstParam
203 | DefKind::Static(..)
206 | DefKind::AssocConst => Some(Namespace::ValueNS),
208 DefKind::Macro(..) => Some(Namespace::MacroNS),
212 | DefKind::InlineConst
214 | DefKind::LifetimeParam
215 | DefKind::ExternCrate
219 | DefKind::ForeignMod
221 | DefKind::Impl => None,
226 pub fn is_fn_like(self) -> bool {
228 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true,
234 /// The resolution of a path or export.
236 /// For every path or identifier in Rust, the compiler must determine
237 /// what the path refers to. This process is called name resolution,
238 /// and `Res` is the primary result of name resolution.
240 /// For example, everything prefixed with `/* Res */` in this example has
241 /// an associated `Res`:
244 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
245 /// /* Res */ String::from(/* Res */ s)
248 /// /* Res */ str_to_string("hello");
251 /// The associated `Res`s will be:
253 /// - `str` will resolve to [`Res::PrimTy`];
254 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
255 /// for `String` as defined in the standard library;
256 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
257 /// pointing to `String::from`;
258 /// - `s` will resolve to [`Res::Local`];
259 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
260 /// pointing to the definition of `str_to_string` in the current crate.
262 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
263 #[derive(HashStable_Generic)]
264 pub enum Res<Id = hir::HirId> {
265 /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
267 /// **Not bound to a specific namespace.**
271 /// A primitive type such as `i32` or `str`.
273 /// **Belongs to the type namespace.**
275 /// The `Self` type, optionally with the [`DefId`] of the trait it belongs to and
276 /// optionally with the [`DefId`] of the item introducing the `Self` type alias.
278 /// **Belongs to the type namespace.**
282 /// struct Bar(Box<Self>);
283 /// // `Res::SelfTy { trait_: None, alias_of: Some(Bar) }`
286 /// fn foo() -> Box<Self>;
287 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: None }`
293 /// // `Res::SelfTy { trait_: None, alias_of: Some(::{impl#0}) }`
297 /// impl Foo for Bar {
298 /// fn foo() -> Box<Self> {
299 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
301 /// // `Res::SelfTy { trait_: Some(Foo), alias_of: Some(::{impl#1}) }`
308 /// *See also [`Res::SelfCtor`].*
312 /// HACK(min_const_generics): self types also have an optional requirement to **not** mention
313 /// any generic parameters to allow the following with `min_const_generics`:
315 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
317 /// struct Bar([u8; baz::<Self>()]);
318 /// const fn baz<T>() -> usize { 10 }
320 /// We do however allow `Self` in repeat expression even if it is generic to not break code
321 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint:
324 /// let _bar = [1_u8; std::mem::size_of::<*mut T>()];
327 // FIXME(generic_const_exprs): Remove this bodge once that feature is stable.
329 /// The trait this `Self` is a generic arg for.
330 trait_: Option<DefId>,
331 /// The item introducing the `Self` type alias. Can be used in the `type_of` query
332 /// to get the underlying type. Additionally whether the `Self` type is disallowed
333 /// from mentioning generics (i.e. when used in an anonymous constant).
334 alias_to: Option<(DefId, bool)>,
336 /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
338 /// **Belongs to the type namespace.**
342 /// The `Self` constructor, along with the [`DefId`]
343 /// of the impl it is associated with.
345 /// **Belongs to the value namespace.**
347 /// *See also [`Res::SelfTy`].*
349 /// A local variable or function parameter.
351 /// **Belongs to the value namespace.**
355 /// An attribute that is *not* implemented via macro.
356 /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
357 /// as opposed to `#[test]`, which is a builtin macro.
359 /// **Belongs to the macro namespace.**
360 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
363 /// Name resolution failed. We use a dummy `Res` variant so later phases
364 /// of the compiler won't crash and can instead report more errors.
366 /// **Not bound to a specific namespace.**
370 /// The result of resolving a path before lowering to HIR,
371 /// with "module" segments resolved and associated item
372 /// segments deferred to type checking.
373 /// `base_res` is the resolution of the resolved part of the
374 /// path, `unresolved_segments` is the number of unresolved
378 /// module::Type::AssocX::AssocY::MethodOrAssocType
379 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
380 /// base_res unresolved_segments = 3
382 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
383 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
384 /// base_res unresolved_segments = 2
386 #[derive(Copy, Clone, Debug)]
387 pub struct PartialRes {
388 base_res: Res<NodeId>,
389 unresolved_segments: usize,
394 pub fn new(base_res: Res<NodeId>) -> Self {
395 PartialRes { base_res, unresolved_segments: 0 }
399 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
400 if base_res == Res::Err {
401 unresolved_segments = 0
403 PartialRes { base_res, unresolved_segments }
407 pub fn base_res(&self) -> Res<NodeId> {
412 pub fn unresolved_segments(&self) -> usize {
413 self.unresolved_segments
417 /// Different kinds of symbols can coexist even if they share the same textual name.
418 /// Therefore, they each have a separate universe (known as a "namespace").
419 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
421 /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
422 /// (and, by extension, crates).
424 /// Note that the type namespace includes other items; this is not an
427 /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
429 /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
430 /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
431 /// like `#[inline]` and `#[rustfmt::skip]`.
436 /// The English description of the namespace.
437 pub fn descr(self) -> &'static str {
439 Self::TypeNS => "type",
440 Self::ValueNS => "value",
441 Self::MacroNS => "macro",
446 /// Just a helper ‒ separate structure for each namespace.
447 #[derive(Copy, Clone, Default, Debug)]
448 pub struct PerNS<T> {
455 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
456 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
459 pub fn into_iter(self) -> IntoIter<T, 3> {
460 [self.value_ns, self.type_ns, self.macro_ns].into_iter()
463 pub fn iter(&self) -> IntoIter<&T, 3> {
464 [&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
468 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
471 fn index(&self, ns: Namespace) -> &T {
473 Namespace::ValueNS => &self.value_ns,
474 Namespace::TypeNS => &self.type_ns,
475 Namespace::MacroNS => &self.macro_ns,
480 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
481 fn index_mut(&mut self, ns: Namespace) -> &mut T {
483 Namespace::ValueNS => &mut self.value_ns,
484 Namespace::TypeNS => &mut self.type_ns,
485 Namespace::MacroNS => &mut self.macro_ns,
490 impl<T> PerNS<Option<T>> {
491 /// Returns `true` if all the items in this collection are `None`.
492 pub fn is_empty(&self) -> bool {
493 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
496 /// Returns an iterator over the items which are `Some`.
497 pub fn present_items(self) -> impl Iterator<Item = T> {
498 [self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
503 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
505 ast::VariantData::Tuple(..) => CtorKind::Fn,
506 ast::VariantData::Unit(..) => CtorKind::Const,
507 ast::VariantData::Struct(..) => CtorKind::Fictive,
511 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
513 hir::VariantData::Tuple(..) => CtorKind::Fn,
514 hir::VariantData::Unit(..) => CtorKind::Const,
515 hir::VariantData::Struct(..) => CtorKind::Fictive,
520 impl NonMacroAttrKind {
521 pub fn descr(self) -> &'static str {
523 NonMacroAttrKind::Builtin(..) => "built-in attribute",
524 NonMacroAttrKind::Tool => "tool attribute",
525 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
526 "derive helper attribute"
528 NonMacroAttrKind::Registered => "explicitly registered attribute",
532 pub fn article(self) -> &'static str {
534 NonMacroAttrKind::Registered => "an",
539 /// Users of some attributes cannot mark them as used, so they are considered always used.
540 pub fn is_used(self) -> bool {
542 NonMacroAttrKind::Tool
543 | NonMacroAttrKind::DeriveHelper
544 | NonMacroAttrKind::DeriveHelperCompat => true,
545 NonMacroAttrKind::Builtin(..) | NonMacroAttrKind::Registered => false,
551 /// Return the `DefId` of this `Def` if it has an ID, else panic.
552 pub fn def_id(&self) -> DefId
557 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
560 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
561 pub fn opt_def_id(&self) -> Option<DefId> {
563 Res::Def(_, id) => Some(id),
570 | Res::NonMacroAttr(..)
575 /// Return the `DefId` of this `Res` if it represents a module.
576 pub fn mod_def_id(&self) -> Option<DefId> {
578 Res::Def(DefKind::Mod, id) => Some(id),
583 /// A human readable name for the res kind ("function", "module", etc.).
584 pub fn descr(&self) -> &'static str {
586 Res::Def(kind, def_id) => kind.descr(def_id),
587 Res::SelfCtor(..) => "self constructor",
588 Res::PrimTy(..) => "builtin type",
589 Res::Local(..) => "local variable",
590 Res::SelfTy { .. } => "self type",
591 Res::ToolMod => "tool module",
592 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
593 Res::Err => "unresolved item",
597 /// Gets an English article for the `Res`.
598 pub fn article(&self) -> &'static str {
600 Res::Def(kind, _) => kind.article(),
601 Res::NonMacroAttr(kind) => kind.article(),
607 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
609 Res::Def(kind, id) => Res::Def(kind, id),
610 Res::SelfCtor(id) => Res::SelfCtor(id),
611 Res::PrimTy(id) => Res::PrimTy(id),
612 Res::Local(id) => Res::Local(map(id)),
613 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
614 Res::ToolMod => Res::ToolMod,
615 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
616 Res::Err => Res::Err,
620 pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
622 Res::Def(kind, id) => Res::Def(kind, id),
623 Res::SelfCtor(id) => Res::SelfCtor(id),
624 Res::PrimTy(id) => Res::PrimTy(id),
625 Res::Local(id) => Res::Local(map(id)?),
626 Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
627 Res::ToolMod => Res::ToolMod,
628 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
629 Res::Err => Res::Err,
634 pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
635 self.map_id(|_| panic!("unexpected `Res::Local`"))
638 pub fn macro_kind(self) -> Option<MacroKind> {
640 Res::Def(DefKind::Macro(kind), _) => Some(kind),
641 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
646 /// Returns `None` if this is `Res::Err`
647 pub fn ns(&self) -> Option<Namespace> {
649 Res::Def(kind, ..) => kind.ns(),
650 Res::PrimTy(..) | Res::SelfTy { .. } | Res::ToolMod => Some(Namespace::TypeNS),
651 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
652 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
657 /// Always returns `true` if `self` is `Res::Err`
658 pub fn matches_ns(&self, ns: Namespace) -> bool {
659 self.ns().map_or(true, |actual_ns| actual_ns == ns)
662 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
663 pub fn expected_in_tuple_struct_pat(&self) -> bool {
664 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))