1 use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
6 use rustc_macros::HashStable_Generic;
7 use rustc_span::hygiene::MacroKind;
9 use std::array::IntoIter;
12 /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
13 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
14 #[derive(HashStable_Generic)]
16 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
18 /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
22 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
23 #[derive(HashStable_Generic)]
25 /// Constructor function automatically created by a tuple struct/variant.
27 /// Constructor constant automatically created by a unit struct/variant.
29 /// Unusable name in value namespace created by a struct variant.
33 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
34 #[derive(HashStable_Generic)]
35 pub enum NonMacroAttrKind {
36 /// Single-segment attribute defined by the language (`#[inline]`)
38 /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
40 /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
42 /// Single-segment custom attribute registered by a derive macro
43 /// but used before that derive macro was expanded (deprecated).
45 /// Single-segment custom attribute registered with `#[register_attr]`.
49 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
50 #[derive(HashStable_Generic)]
54 /// Refers to the struct itself, `DefKind::Ctor` refers to its constructor if it exists.
58 /// Refers to the variant itself, `DefKind::Ctor` refers to its constructor if it exists.
73 /// Refers to the struct or enum variant's constructor.
74 Ctor(CtorOf, CtorKind),
81 // Not namespaced (or they are, but we don't treat them so)
96 pub fn descr(self, def_id: DefId) -> &'static str {
98 DefKind::Fn => "function",
99 DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => {
102 DefKind::Mod => "module",
103 DefKind::Static => "static",
104 DefKind::Enum => "enum",
105 DefKind::Variant => "variant",
106 DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
107 DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
108 DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
109 DefKind::Struct => "struct",
110 DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
111 DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
112 DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
113 panic!("impossible struct constructor")
115 DefKind::OpaqueTy => "opaque type",
116 DefKind::TyAlias => "type alias",
117 DefKind::TraitAlias => "trait alias",
118 DefKind::AssocTy => "associated type",
119 DefKind::Union => "union",
120 DefKind::Trait => "trait",
121 DefKind::ForeignTy => "foreign type",
122 DefKind::AssocFn => "associated function",
123 DefKind::Const => "constant",
124 DefKind::AssocConst => "associated constant",
125 DefKind::TyParam => "type parameter",
126 DefKind::ConstParam => "const parameter",
127 DefKind::Macro(macro_kind) => macro_kind.descr(),
128 DefKind::LifetimeParam => "lifetime parameter",
129 DefKind::Use => "import",
130 DefKind::ForeignMod => "foreign module",
131 DefKind::AnonConst => "constant expression",
132 DefKind::Field => "field",
133 DefKind::Impl => "implementation",
134 DefKind::Closure => "closure",
135 DefKind::Generator => "generator",
136 DefKind::ExternCrate => "extern crate",
137 DefKind::GlobalAsm => "global assembly block",
141 /// Gets an English article for the definition.
142 pub fn article(&self) -> &'static str {
145 | DefKind::AssocConst
151 | DefKind::ExternCrate => "an",
152 DefKind::Macro(macro_kind) => macro_kind.article(),
157 pub fn ns(&self) -> Option<Namespace> {
168 | DefKind::TraitAlias
170 | DefKind::TyParam => Some(Namespace::TypeNS),
174 | DefKind::ConstParam
178 | DefKind::AssocConst => Some(Namespace::ValueNS),
180 DefKind::Macro(..) => Some(Namespace::MacroNS),
185 | DefKind::LifetimeParam
186 | DefKind::ExternCrate
190 | DefKind::ForeignMod
192 | DefKind::Impl => None,
197 /// The resolution of a path or export.
198 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
199 #[derive(HashStable_Generic)]
200 pub enum Res<Id = hir::HirId> {
205 /// `Self`, with both an optional trait and impl `DefId`.
207 /// HACK(min_const_generics): impl self types also have an optional requirement to not mention
208 /// any generic parameters to allow the following with `min_const_generics`:
210 /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] {} }
212 /// We do however allow `Self` in repeat expression even if it is generic to not break code
213 /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint.
215 /// FIXME(lazy_normalization_consts): Remove this bodge once that feature is stable.
216 SelfTy(Option<DefId> /* trait */, Option<(DefId, bool)> /* impl */),
217 ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
220 SelfCtor(DefId /* impl */), // `DefId` refers to the impl
224 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
230 /// The result of resolving a path before lowering to HIR,
231 /// with "module" segments resolved and associated item
232 /// segments deferred to type checking.
233 /// `base_res` is the resolution of the resolved part of the
234 /// path, `unresolved_segments` is the number of unresolved
238 /// module::Type::AssocX::AssocY::MethodOrAssocType
239 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
240 /// base_res unresolved_segments = 3
242 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
243 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
244 /// base_res unresolved_segments = 2
246 #[derive(Copy, Clone, Debug)]
247 pub struct PartialRes {
248 base_res: Res<NodeId>,
249 unresolved_segments: usize,
254 pub fn new(base_res: Res<NodeId>) -> Self {
255 PartialRes { base_res, unresolved_segments: 0 }
259 pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
260 if base_res == Res::Err {
261 unresolved_segments = 0
263 PartialRes { base_res, unresolved_segments }
267 pub fn base_res(&self) -> Res<NodeId> {
272 pub fn unresolved_segments(&self) -> usize {
273 self.unresolved_segments
277 /// Different kinds of symbols don't influence each other.
279 /// Therefore, they have a separate universe (namespace).
280 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
288 pub fn descr(self) -> &'static str {
290 Self::TypeNS => "type",
291 Self::ValueNS => "value",
292 Self::MacroNS => "macro",
297 /// Just a helper ‒ separate structure for each namespace.
298 #[derive(Copy, Clone, Default, Debug)]
299 pub struct PerNS<T> {
306 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
307 PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
310 pub fn into_iter(self) -> IntoIter<T, 3> {
311 IntoIter::new([self.value_ns, self.type_ns, self.macro_ns])
314 pub fn iter(&self) -> IntoIter<&T, 3> {
315 IntoIter::new([&self.value_ns, &self.type_ns, &self.macro_ns])
319 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
322 fn index(&self, ns: Namespace) -> &T {
324 Namespace::ValueNS => &self.value_ns,
325 Namespace::TypeNS => &self.type_ns,
326 Namespace::MacroNS => &self.macro_ns,
331 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
332 fn index_mut(&mut self, ns: Namespace) -> &mut T {
334 Namespace::ValueNS => &mut self.value_ns,
335 Namespace::TypeNS => &mut self.type_ns,
336 Namespace::MacroNS => &mut self.macro_ns,
341 impl<T> PerNS<Option<T>> {
342 /// Returns `true` if all the items in this collection are `None`.
343 pub fn is_empty(&self) -> bool {
344 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
347 /// Returns an iterator over the items which are `Some`.
348 pub fn present_items(self) -> impl Iterator<Item = T> {
349 IntoIter::new([self.type_ns, self.value_ns, self.macro_ns]).filter_map(|it| it)
354 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
356 ast::VariantData::Tuple(..) => CtorKind::Fn,
357 ast::VariantData::Unit(..) => CtorKind::Const,
358 ast::VariantData::Struct(..) => CtorKind::Fictive,
362 pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
364 hir::VariantData::Tuple(..) => CtorKind::Fn,
365 hir::VariantData::Unit(..) => CtorKind::Const,
366 hir::VariantData::Struct(..) => CtorKind::Fictive,
371 impl NonMacroAttrKind {
372 pub fn descr(self) -> &'static str {
374 NonMacroAttrKind::Builtin => "built-in attribute",
375 NonMacroAttrKind::Tool => "tool attribute",
376 NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
377 "derive helper attribute"
379 NonMacroAttrKind::Registered => "explicitly registered attribute",
383 pub fn article(self) -> &'static str {
385 NonMacroAttrKind::Registered => "an",
390 /// Users of some attributes cannot mark them as used, so they are considered always used.
391 pub fn is_used(self) -> bool {
393 NonMacroAttrKind::Tool
394 | NonMacroAttrKind::DeriveHelper
395 | NonMacroAttrKind::DeriveHelperCompat => true,
396 NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false,
402 /// Return the `DefId` of this `Def` if it has an ID, else panic.
403 pub fn def_id(&self) -> DefId
408 .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
411 /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
412 pub fn opt_def_id(&self) -> Option<DefId> {
414 Res::Def(_, id) => Some(id),
421 | Res::NonMacroAttr(..)
426 /// Return the `DefId` of this `Res` if it represents a module.
427 pub fn mod_def_id(&self) -> Option<DefId> {
429 Res::Def(DefKind::Mod, id) => Some(id),
434 /// A human readable name for the res kind ("function", "module", etc.).
435 pub fn descr(&self) -> &'static str {
437 Res::Def(kind, def_id) => kind.descr(def_id),
438 Res::SelfCtor(..) => "self constructor",
439 Res::PrimTy(..) => "builtin type",
440 Res::Local(..) => "local variable",
441 Res::SelfTy(..) => "self type",
442 Res::ToolMod => "tool module",
443 Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
444 Res::Err => "unresolved item",
448 /// Gets an English article for the `Res`.
449 pub fn article(&self) -> &'static str {
451 Res::Def(kind, _) => kind.article(),
452 Res::NonMacroAttr(kind) => kind.article(),
458 pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
460 Res::Def(kind, id) => Res::Def(kind, id),
461 Res::SelfCtor(id) => Res::SelfCtor(id),
462 Res::PrimTy(id) => Res::PrimTy(id),
463 Res::Local(id) => Res::Local(map(id)),
464 Res::SelfTy(a, b) => Res::SelfTy(a, b),
465 Res::ToolMod => Res::ToolMod,
466 Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
467 Res::Err => Res::Err,
471 pub fn macro_kind(self) -> Option<MacroKind> {
473 Res::Def(DefKind::Macro(kind), _) => Some(kind),
474 Res::NonMacroAttr(..) => Some(MacroKind::Attr),
479 /// Returns `None` if this is `Res::Err`
480 pub fn ns(&self) -> Option<Namespace> {
482 Res::Def(kind, ..) => kind.ns(),
483 Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => Some(Namespace::TypeNS),
484 Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
485 Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
490 /// Always returns `true` if `self` is `Res::Err`
491 pub fn matches_ns(&self, ns: Namespace) -> bool {
492 self.ns().map_or(true, |actual_ns| actual_ns == ns)
495 /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
496 pub fn expected_in_tuple_struct_pat(&self) -> bool {
497 matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))