]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/def.rs
Auto merge of #82958 - camelid:res-docs, r=petrochenkov
[rust.git] / compiler / rustc_hir / src / def.rs
1 use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
2 use crate::hir;
3
4 use rustc_ast as ast;
5 use rustc_ast::NodeId;
6 use rustc_macros::HashStable_Generic;
7 use rustc_span::hygiene::MacroKind;
8 use rustc_span::Symbol;
9
10 use std::array::IntoIter;
11 use std::fmt::Debug;
12
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)]
16 pub enum CtorOf {
17     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
18     Struct,
19     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
20     Variant,
21 }
22
23 /// What kind of constructor something is.
24 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
25 #[derive(HashStable_Generic)]
26 pub enum CtorKind {
27     /// Constructor function automatically created by a tuple struct/variant.
28     Fn,
29     /// Constructor constant automatically created by a unit struct/variant.
30     Const,
31     /// Unusable name in value namespace created by a struct variant.
32     Fictive,
33 }
34
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]`)
40     Builtin(Symbol),
41     /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
42     Tool,
43     /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
44     DeriveHelper,
45     /// Single-segment custom attribute registered by a derive macro
46     /// but used before that derive macro was expanded (deprecated).
47     DeriveHelperCompat,
48     /// Single-segment custom attribute registered with `#[register_attr]`.
49     Registered,
50 }
51
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)]
55 pub enum DefKind {
56     // Type namespace
57     Mod,
58     /// Refers to the struct itself, [`DefKind::Ctor`] refers to its constructor if it exists.
59     Struct,
60     Union,
61     Enum,
62     /// Refers to the variant itself, [`DefKind::Ctor`] refers to its constructor if it exists.
63     Variant,
64     Trait,
65     /// Type alias: `type Foo = Bar;`
66     TyAlias,
67     /// Type from an `extern` block.
68     ForeignTy,
69     /// Trait alias: `trait IntIterator = Iterator<Item = i32>;`
70     TraitAlias,
71     /// Associated type: `trait MyTrait { type Assoc; }`
72     AssocTy,
73     /// Type parameter: the `T` in `struct Vec<T> { ... }`
74     TyParam,
75
76     // Value namespace
77     Fn,
78     Const,
79     /// Constant generic parameter: `struct Foo<const N: usize> { ... }`
80     ConstParam,
81     Static,
82     /// Refers to the struct or enum variant's constructor.
83     ///
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.
88     ///
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.
91     ///
92     /// [RFC 2593]: https://github.com/rust-lang/rfcs/pull/2593
93     Ctor(CtorOf, CtorKind),
94     /// Associated function: `impl MyStruct { fn associated() {} }`
95     AssocFn,
96     /// Associated constant: `trait MyTrait { const ASSOC: usize; }`
97     AssocConst,
98
99     // Macro namespace
100     Macro(MacroKind),
101
102     // Not namespaced (or they are, but we don't treat them so)
103     ExternCrate,
104     Use,
105     /// An `extern` block.
106     ForeignMod,
107     /// Anonymous constant, e.g. the `1 + 2` in `[u8; 1 + 2]`, or `const { 1 + 2}`
108     AnonConst,
109     /// Opaque type, aka `impl Trait`.
110     OpaqueTy,
111     Field,
112     /// Lifetime parameter: the `'a` in `struct Foo<'a> { ... }`
113     LifetimeParam,
114     /// A use of [`global_asm!`].
115     GlobalAsm,
116     Impl,
117     Closure,
118     Generator,
119 }
120
121 impl DefKind {
122     pub fn descr(self, def_id: DefId) -> &'static str {
123         match self {
124             DefKind::Fn => "function",
125             DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => {
126                 "crate"
127             }
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")
140             }
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::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",
164         }
165     }
166
167     /// Gets an English article for the definition.
168     pub fn article(&self) -> &'static str {
169         match *self {
170             DefKind::AssocTy
171             | DefKind::AssocConst
172             | DefKind::AssocFn
173             | DefKind::Enum
174             | DefKind::OpaqueTy
175             | DefKind::Impl
176             | DefKind::Use
177             | DefKind::ExternCrate => "an",
178             DefKind::Macro(macro_kind) => macro_kind.article(),
179             _ => "a",
180         }
181     }
182
183     pub fn ns(&self) -> Option<Namespace> {
184         match self {
185             DefKind::Mod
186             | DefKind::Struct
187             | DefKind::Union
188             | DefKind::Enum
189             | DefKind::Variant
190             | DefKind::Trait
191             | DefKind::OpaqueTy
192             | DefKind::TyAlias
193             | DefKind::ForeignTy
194             | DefKind::TraitAlias
195             | DefKind::AssocTy
196             | DefKind::TyParam => Some(Namespace::TypeNS),
197
198             DefKind::Fn
199             | DefKind::Const
200             | DefKind::ConstParam
201             | DefKind::Static
202             | DefKind::Ctor(..)
203             | DefKind::AssocFn
204             | DefKind::AssocConst => Some(Namespace::ValueNS),
205
206             DefKind::Macro(..) => Some(Namespace::MacroNS),
207
208             // Not namespaced.
209             DefKind::AnonConst
210             | DefKind::Field
211             | DefKind::LifetimeParam
212             | DefKind::ExternCrate
213             | DefKind::Closure
214             | DefKind::Generator
215             | DefKind::Use
216             | DefKind::ForeignMod
217             | DefKind::GlobalAsm
218             | DefKind::Impl => None,
219         }
220     }
221 }
222
223 /// The resolution of a path or export.
224 ///
225 /// For every path or identifier in Rust, the compiler must determine
226 /// what the path refers to. This process is called name resolution,
227 /// and `Res` is the primary result of name resolution.
228 ///
229 /// For example, everything prefixed with `/* Res */` in this example has
230 /// an associated `Res`:
231 ///
232 /// ```
233 /// fn str_to_string(s: & /* Res */ str) -> /* Res */ String {
234 ///     /* Res */ String::from(/* Res */ s)
235 /// }
236 ///
237 /// /* Res */ str_to_string("hello");
238 /// ```
239 ///
240 /// The associated `Res`s will be:
241 ///
242 /// - `str` will resolve to [`Res::PrimTy`];
243 /// - `String` will resolve to [`Res::Def`], and the `Res` will include the [`DefId`]
244 ///   for `String` as defined in the standard library;
245 /// - `String::from` will also resolve to [`Res::Def`], with the [`DefId`]
246 ///   pointing to `String::from`;
247 /// - `s` will resolve to [`Res::Local`];
248 /// - the call to `str_to_string` will resolve to [`Res::Def`], with the [`DefId`]
249 ///   pointing to the definition of `str_to_string` in the current crate.
250 //
251 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
252 #[derive(HashStable_Generic)]
253 pub enum Res<Id = hir::HirId> {
254     /// Definition having a unique ID (`DefId`), corresponds to something defined in user code.
255     ///
256     /// **Not bound to a specific namespace.**
257     Def(DefKind, DefId),
258
259     // Type namespace
260     /// A primitive type such as `i32` or `str`.
261     ///
262     /// **Belongs to the type namespace.**
263     PrimTy(hir::PrimTy),
264     /// The `Self` type, optionally with the trait it is associated with
265     /// and optionally with the [`DefId`] of the impl it is associated with.
266     ///
267     /// **Belongs to the type namespace.**
268     ///
269     /// For example, the `Self` in
270     ///
271     /// ```
272     /// trait Foo {
273     ///     fn foo() -> Box<Self>;
274     /// }
275     /// ```
276     ///
277     /// would have the [`DefId`] of `Foo` associated with it. The `Self` in
278     ///
279     /// ```
280     /// struct Bar;
281     ///
282     /// impl Bar {
283     ///     fn new() -> Self { Bar }
284     /// }
285     /// ```
286     ///
287     /// would have the [`DefId`] of the impl associated with it. Finally, the `Self` in
288     ///
289     /// ```
290     /// impl Foo for Bar {
291     ///     fn foo() -> Box<Self> { Box::new(Bar) }
292     /// }
293     /// ```
294     ///
295     /// would have both the [`DefId`] of `Foo` and the [`DefId`] of the impl
296     /// associated with it.
297     ///
298     /// *See also [`Res::SelfCtor`].*
299     ///
300     /// -----
301     ///
302     /// HACK(min_const_generics): impl self types also have an optional requirement to **not** mention
303     /// any generic parameters to allow the following with `min_const_generics`:
304     /// ```
305     /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] { todo!() } }
306     /// ```
307     /// We do however allow `Self` in repeat expression even if it is generic to not break code
308     /// which already works on stable while causing the `const_evaluatable_unchecked` future compat lint.
309     ///
310     /// FIXME(lazy_normalization_consts): Remove this bodge once that feature is stable.
311     SelfTy(
312         /// Optionally, the trait associated with this `Self` type.
313         Option<DefId>,
314         /// Optionally, the impl associated with this `Self` type.
315         Option<(DefId, bool)>,
316     ),
317     /// A tool attribute module; e.g., the `rustfmt` in `#[rustfmt::skip]`.
318     ///
319     /// **Belongs to the type namespace.**
320     ToolMod,
321
322     // Value namespace
323     /// The `Self` constructor, along with the [`DefId`]
324     /// of the impl it is associated with.
325     ///
326     /// **Belongs to the value namespace.**
327     ///
328     /// *See also [`Res::SelfTy`].*
329     SelfCtor(DefId),
330     /// A local variable or function parameter.
331     ///
332     /// **Belongs to the value namespace.**
333     Local(Id),
334
335     // Macro namespace
336     /// An attribute that is *not* implemented via macro.
337     /// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
338     /// as opposed to `#[test]`, which is a builtin macro.
339     ///
340     /// **Belongs to the macro namespace.**
341     NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
342
343     // All namespaces
344     /// Name resolution failed. We use a dummy `Res` variant so later phases
345     /// of the compiler won't crash and can instead report more errors.
346     ///
347     /// **Not bound to a specific namespace.**
348     Err,
349 }
350
351 /// The result of resolving a path before lowering to HIR,
352 /// with "module" segments resolved and associated item
353 /// segments deferred to type checking.
354 /// `base_res` is the resolution of the resolved part of the
355 /// path, `unresolved_segments` is the number of unresolved
356 /// segments.
357 ///
358 /// ```text
359 /// module::Type::AssocX::AssocY::MethodOrAssocType
360 /// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361 /// base_res      unresolved_segments = 3
362 ///
363 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
364 ///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
365 ///       base_res        unresolved_segments = 2
366 /// ```
367 #[derive(Copy, Clone, Debug)]
368 pub struct PartialRes {
369     base_res: Res<NodeId>,
370     unresolved_segments: usize,
371 }
372
373 impl PartialRes {
374     #[inline]
375     pub fn new(base_res: Res<NodeId>) -> Self {
376         PartialRes { base_res, unresolved_segments: 0 }
377     }
378
379     #[inline]
380     pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
381         if base_res == Res::Err {
382             unresolved_segments = 0
383         }
384         PartialRes { base_res, unresolved_segments }
385     }
386
387     #[inline]
388     pub fn base_res(&self) -> Res<NodeId> {
389         self.base_res
390     }
391
392     #[inline]
393     pub fn unresolved_segments(&self) -> usize {
394         self.unresolved_segments
395     }
396 }
397
398 /// Different kinds of symbols can coexist even if they share the same textual name.
399 /// Therefore, they each have a separate universe (known as a "namespace").
400 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
401 pub enum Namespace {
402     /// The type namespace includes `struct`s, `enum`s, `union`s, `trait`s, and `mod`s
403     /// (and, by extension, crates).
404     ///
405     /// Note that the type namespace includes other items; this is not an
406     /// exhaustive list.
407     TypeNS,
408     /// The value namespace includes `fn`s, `const`s, `static`s, and local variables (including function arguments).
409     ValueNS,
410     /// The macro namespace includes `macro_rules!` macros, declarative `macro`s,
411     /// procedural macros, attribute macros, `derive` macros, and non-macro attributes
412     /// like `#[inline]` and `#[rustfmt::skip]`.
413     MacroNS,
414 }
415
416 impl Namespace {
417     /// The English description of the namespace.
418     pub fn descr(self) -> &'static str {
419         match self {
420             Self::TypeNS => "type",
421             Self::ValueNS => "value",
422             Self::MacroNS => "macro",
423         }
424     }
425 }
426
427 /// Just a helper ‒ separate structure for each namespace.
428 #[derive(Copy, Clone, Default, Debug)]
429 pub struct PerNS<T> {
430     pub value_ns: T,
431     pub type_ns: T,
432     pub macro_ns: T,
433 }
434
435 impl<T> PerNS<T> {
436     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
437         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
438     }
439
440     pub fn into_iter(self) -> IntoIter<T, 3> {
441         IntoIter::new([self.value_ns, self.type_ns, self.macro_ns])
442     }
443
444     pub fn iter(&self) -> IntoIter<&T, 3> {
445         IntoIter::new([&self.value_ns, &self.type_ns, &self.macro_ns])
446     }
447 }
448
449 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
450     type Output = T;
451
452     fn index(&self, ns: Namespace) -> &T {
453         match ns {
454             Namespace::ValueNS => &self.value_ns,
455             Namespace::TypeNS => &self.type_ns,
456             Namespace::MacroNS => &self.macro_ns,
457         }
458     }
459 }
460
461 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
462     fn index_mut(&mut self, ns: Namespace) -> &mut T {
463         match ns {
464             Namespace::ValueNS => &mut self.value_ns,
465             Namespace::TypeNS => &mut self.type_ns,
466             Namespace::MacroNS => &mut self.macro_ns,
467         }
468     }
469 }
470
471 impl<T> PerNS<Option<T>> {
472     /// Returns `true` if all the items in this collection are `None`.
473     pub fn is_empty(&self) -> bool {
474         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
475     }
476
477     /// Returns an iterator over the items which are `Some`.
478     pub fn present_items(self) -> impl Iterator<Item = T> {
479         IntoIter::new([self.type_ns, self.value_ns, self.macro_ns]).filter_map(|it| it)
480     }
481 }
482
483 impl CtorKind {
484     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
485         match *vdata {
486             ast::VariantData::Tuple(..) => CtorKind::Fn,
487             ast::VariantData::Unit(..) => CtorKind::Const,
488             ast::VariantData::Struct(..) => CtorKind::Fictive,
489         }
490     }
491
492     pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
493         match *vdata {
494             hir::VariantData::Tuple(..) => CtorKind::Fn,
495             hir::VariantData::Unit(..) => CtorKind::Const,
496             hir::VariantData::Struct(..) => CtorKind::Fictive,
497         }
498     }
499 }
500
501 impl NonMacroAttrKind {
502     pub fn descr(self) -> &'static str {
503         match self {
504             NonMacroAttrKind::Builtin(..) => "built-in attribute",
505             NonMacroAttrKind::Tool => "tool attribute",
506             NonMacroAttrKind::DeriveHelper | NonMacroAttrKind::DeriveHelperCompat => {
507                 "derive helper attribute"
508             }
509             NonMacroAttrKind::Registered => "explicitly registered attribute",
510         }
511     }
512
513     pub fn article(self) -> &'static str {
514         match self {
515             NonMacroAttrKind::Registered => "an",
516             _ => "a",
517         }
518     }
519
520     /// Users of some attributes cannot mark them as used, so they are considered always used.
521     pub fn is_used(self) -> bool {
522         match self {
523             NonMacroAttrKind::Tool
524             | NonMacroAttrKind::DeriveHelper
525             | NonMacroAttrKind::DeriveHelperCompat => true,
526             NonMacroAttrKind::Builtin(..) | NonMacroAttrKind::Registered => false,
527         }
528     }
529 }
530
531 impl<Id> Res<Id> {
532     /// Return the `DefId` of this `Def` if it has an ID, else panic.
533     pub fn def_id(&self) -> DefId
534     where
535         Id: Debug,
536     {
537         self.opt_def_id()
538             .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
539     }
540
541     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
542     pub fn opt_def_id(&self) -> Option<DefId> {
543         match *self {
544             Res::Def(_, id) => Some(id),
545
546             Res::Local(..)
547             | Res::PrimTy(..)
548             | Res::SelfTy(..)
549             | Res::SelfCtor(..)
550             | Res::ToolMod
551             | Res::NonMacroAttr(..)
552             | Res::Err => None,
553         }
554     }
555
556     /// Return the `DefId` of this `Res` if it represents a module.
557     pub fn mod_def_id(&self) -> Option<DefId> {
558         match *self {
559             Res::Def(DefKind::Mod, id) => Some(id),
560             _ => None,
561         }
562     }
563
564     /// A human readable name for the res kind ("function", "module", etc.).
565     pub fn descr(&self) -> &'static str {
566         match *self {
567             Res::Def(kind, def_id) => kind.descr(def_id),
568             Res::SelfCtor(..) => "self constructor",
569             Res::PrimTy(..) => "builtin type",
570             Res::Local(..) => "local variable",
571             Res::SelfTy(..) => "self type",
572             Res::ToolMod => "tool module",
573             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
574             Res::Err => "unresolved item",
575         }
576     }
577
578     /// Gets an English article for the `Res`.
579     pub fn article(&self) -> &'static str {
580         match *self {
581             Res::Def(kind, _) => kind.article(),
582             Res::NonMacroAttr(kind) => kind.article(),
583             Res::Err => "an",
584             _ => "a",
585         }
586     }
587
588     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
589         match self {
590             Res::Def(kind, id) => Res::Def(kind, id),
591             Res::SelfCtor(id) => Res::SelfCtor(id),
592             Res::PrimTy(id) => Res::PrimTy(id),
593             Res::Local(id) => Res::Local(map(id)),
594             Res::SelfTy(a, b) => Res::SelfTy(a, b),
595             Res::ToolMod => Res::ToolMod,
596             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
597             Res::Err => Res::Err,
598         }
599     }
600
601     pub fn macro_kind(self) -> Option<MacroKind> {
602         match self {
603             Res::Def(DefKind::Macro(kind), _) => Some(kind),
604             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
605             _ => None,
606         }
607     }
608
609     /// Returns `None` if this is `Res::Err`
610     pub fn ns(&self) -> Option<Namespace> {
611         match self {
612             Res::Def(kind, ..) => kind.ns(),
613             Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => Some(Namespace::TypeNS),
614             Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
615             Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
616             Res::Err => None,
617         }
618     }
619
620     /// Always returns `true` if `self` is `Res::Err`
621     pub fn matches_ns(&self, ns: Namespace) -> bool {
622         self.ns().map_or(true, |actual_ns| actual_ns == ns)
623     }
624
625     /// Returns whether such a resolved path can occur in a tuple struct/variant pattern
626     pub fn expected_in_tuple_struct_pat(&self) -> bool {
627         matches!(self, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
628     }
629 }