]> git.lizzy.rs Git - rust.git/blob - src/librustc_hir/def.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_hir / def.rs
1 use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
2 use crate::hir;
3
4 use rustc_ast::ast;
5 use rustc_ast::ast::NodeId;
6 use rustc_macros::HashStable_Generic;
7 use rustc_span::hygiene::MacroKind;
8
9 use std::fmt::Debug;
10
11 /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct.
12 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
13 #[derive(HashStable_Generic)]
14 pub enum CtorOf {
15     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct.
16     Struct,
17     /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant.
18     Variant,
19 }
20
21 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
22 #[derive(HashStable_Generic)]
23 pub enum CtorKind {
24     /// Constructor function automatically created by a tuple struct/variant.
25     Fn,
26     /// Constructor constant automatically created by a unit struct/variant.
27     Const,
28     /// Unusable name in value namespace created by a struct variant.
29     Fictive,
30 }
31
32 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
33 #[derive(HashStable_Generic)]
34 pub enum NonMacroAttrKind {
35     /// Single-segment attribute defined by the language (`#[inline]`)
36     Builtin,
37     /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
38     Tool,
39     /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
40     DeriveHelper,
41     /// Single-segment custom attribute registered with `#[register_attr]`.
42     Registered,
43 }
44
45 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
46 #[derive(HashStable_Generic)]
47 pub enum DefKind {
48     // Type namespace
49     Mod,
50     /// Refers to the struct itself, `DefKind::Ctor` refers to its constructor if it exists.
51     Struct,
52     Union,
53     Enum,
54     /// Refers to the variant itself, `DefKind::Ctor` refers to its constructor if it exists.
55     Variant,
56     Trait,
57     /// `type Foo = impl Bar;`
58     OpaqueTy,
59     /// `type Foo = Bar;`
60     TyAlias,
61     ForeignTy,
62     TraitAlias,
63     AssocTy,
64     /// `type Foo = impl Bar;`
65     AssocOpaqueTy,
66     TyParam,
67
68     // Value namespace
69     Fn,
70     Const,
71     ConstParam,
72     Static,
73     /// Refers to the struct or enum variant's constructor.
74     Ctor(CtorOf, CtorKind),
75     AssocFn,
76     AssocConst,
77
78     // Macro namespace
79     Macro(MacroKind),
80 }
81
82 impl DefKind {
83     pub fn descr(self, def_id: DefId) -> &'static str {
84         match self {
85             DefKind::Fn => "function",
86             DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => {
87                 "crate"
88             }
89             DefKind::Mod => "module",
90             DefKind::Static => "static",
91             DefKind::Enum => "enum",
92             DefKind::Variant => "variant",
93             DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant",
94             DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant",
95             DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant",
96             DefKind::Struct => "struct",
97             DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct",
98             DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct",
99             DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => {
100                 panic!("impossible struct constructor")
101             }
102             DefKind::OpaqueTy => "opaque type",
103             DefKind::TyAlias => "type alias",
104             DefKind::TraitAlias => "trait alias",
105             DefKind::AssocTy => "associated type",
106             DefKind::AssocOpaqueTy => "associated opaque type",
107             DefKind::Union => "union",
108             DefKind::Trait => "trait",
109             DefKind::ForeignTy => "foreign type",
110             DefKind::AssocFn => "associated function",
111             DefKind::Const => "constant",
112             DefKind::AssocConst => "associated constant",
113             DefKind::TyParam => "type parameter",
114             DefKind::ConstParam => "const parameter",
115             DefKind::Macro(macro_kind) => macro_kind.descr(),
116         }
117     }
118
119     /// Gets an English article for the definition.
120     pub fn article(&self) -> &'static str {
121         match *self {
122             DefKind::AssocTy
123             | DefKind::AssocConst
124             | DefKind::AssocOpaqueTy
125             | DefKind::AssocFn
126             | DefKind::Enum
127             | DefKind::OpaqueTy => "an",
128             DefKind::Macro(macro_kind) => macro_kind.article(),
129             _ => "a",
130         }
131     }
132
133     pub fn matches_ns(&self, ns: Namespace) -> bool {
134         match self {
135             DefKind::Mod
136             | DefKind::Struct
137             | DefKind::Union
138             | DefKind::Enum
139             | DefKind::Variant
140             | DefKind::Trait
141             | DefKind::OpaqueTy
142             | DefKind::TyAlias
143             | DefKind::ForeignTy
144             | DefKind::TraitAlias
145             | DefKind::AssocTy
146             | DefKind::AssocOpaqueTy
147             | DefKind::TyParam => ns == Namespace::TypeNS,
148
149             DefKind::Fn
150             | DefKind::Const
151             | DefKind::ConstParam
152             | DefKind::Static
153             | DefKind::Ctor(..)
154             | DefKind::AssocFn
155             | DefKind::AssocConst => ns == Namespace::ValueNS,
156
157             DefKind::Macro(..) => ns == Namespace::MacroNS,
158         }
159     }
160 }
161
162 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
163 #[derive(HashStable_Generic)]
164 pub enum Res<Id = hir::HirId> {
165     Def(DefKind, DefId),
166
167     // Type namespace
168     PrimTy(hir::PrimTy),
169     SelfTy(Option<DefId> /* trait */, Option<DefId> /* impl */),
170     ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
171
172     // Value namespace
173     SelfCtor(DefId /* impl */), // `DefId` refers to the impl
174     Local(Id),
175
176     // Macro namespace
177     NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
178
179     // All namespaces
180     Err,
181 }
182
183 /// The result of resolving a path before lowering to HIR,
184 /// with "module" segments resolved and associated item
185 /// segments deferred to type checking.
186 /// `base_res` is the resolution of the resolved part of the
187 /// path, `unresolved_segments` is the number of unresolved
188 /// segments.
189 ///
190 /// ```text
191 /// module::Type::AssocX::AssocY::MethodOrAssocType
192 /// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193 /// base_res      unresolved_segments = 3
194 ///
195 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
196 ///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
197 ///       base_res        unresolved_segments = 2
198 /// ```
199 #[derive(Copy, Clone, Debug)]
200 pub struct PartialRes {
201     base_res: Res<NodeId>,
202     unresolved_segments: usize,
203 }
204
205 impl PartialRes {
206     #[inline]
207     pub fn new(base_res: Res<NodeId>) -> Self {
208         PartialRes { base_res, unresolved_segments: 0 }
209     }
210
211     #[inline]
212     pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
213         if base_res == Res::Err {
214             unresolved_segments = 0
215         }
216         PartialRes { base_res, unresolved_segments }
217     }
218
219     #[inline]
220     pub fn base_res(&self) -> Res<NodeId> {
221         self.base_res
222     }
223
224     #[inline]
225     pub fn unresolved_segments(&self) -> usize {
226         self.unresolved_segments
227     }
228 }
229
230 /// Different kinds of symbols don't influence each other.
231 ///
232 /// Therefore, they have a separate universe (namespace).
233 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
234 pub enum Namespace {
235     TypeNS,
236     ValueNS,
237     MacroNS,
238 }
239
240 impl Namespace {
241     pub fn descr(self) -> &'static str {
242         match self {
243             Self::TypeNS => "type",
244             Self::ValueNS => "value",
245             Self::MacroNS => "macro",
246         }
247     }
248 }
249
250 /// Just a helper ‒ separate structure for each namespace.
251 #[derive(Copy, Clone, Default, Debug)]
252 pub struct PerNS<T> {
253     pub value_ns: T,
254     pub type_ns: T,
255     pub macro_ns: T,
256 }
257
258 impl<T> PerNS<T> {
259     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
260         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
261     }
262 }
263
264 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
265     type Output = T;
266
267     fn index(&self, ns: Namespace) -> &T {
268         match ns {
269             Namespace::ValueNS => &self.value_ns,
270             Namespace::TypeNS => &self.type_ns,
271             Namespace::MacroNS => &self.macro_ns,
272         }
273     }
274 }
275
276 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
277     fn index_mut(&mut self, ns: Namespace) -> &mut T {
278         match ns {
279             Namespace::ValueNS => &mut self.value_ns,
280             Namespace::TypeNS => &mut self.type_ns,
281             Namespace::MacroNS => &mut self.macro_ns,
282         }
283     }
284 }
285
286 impl<T> PerNS<Option<T>> {
287     /// Returns `true` if all the items in this collection are `None`.
288     pub fn is_empty(&self) -> bool {
289         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
290     }
291
292     /// Returns an iterator over the items which are `Some`.
293     pub fn present_items(self) -> impl Iterator<Item = T> {
294         use std::iter::once;
295
296         once(self.type_ns).chain(once(self.value_ns)).chain(once(self.macro_ns)).filter_map(|it| it)
297     }
298 }
299
300 impl CtorKind {
301     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
302         match *vdata {
303             ast::VariantData::Tuple(..) => CtorKind::Fn,
304             ast::VariantData::Unit(..) => CtorKind::Const,
305             ast::VariantData::Struct(..) => CtorKind::Fictive,
306         }
307     }
308
309     pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
310         match *vdata {
311             hir::VariantData::Tuple(..) => CtorKind::Fn,
312             hir::VariantData::Unit(..) => CtorKind::Const,
313             hir::VariantData::Struct(..) => CtorKind::Fictive,
314         }
315     }
316 }
317
318 impl NonMacroAttrKind {
319     pub fn descr(self) -> &'static str {
320         match self {
321             NonMacroAttrKind::Builtin => "built-in attribute",
322             NonMacroAttrKind::Tool => "tool attribute",
323             NonMacroAttrKind::DeriveHelper => "derive helper attribute",
324             NonMacroAttrKind::Registered => "explicitly registered attribute",
325         }
326     }
327
328     pub fn article(self) -> &'static str {
329         match self {
330             NonMacroAttrKind::Registered => "an",
331             _ => "a",
332         }
333     }
334
335     /// Users of some attributes cannot mark them as used, so they are considered always used.
336     pub fn is_used(self) -> bool {
337         match self {
338             NonMacroAttrKind::Tool | NonMacroAttrKind::DeriveHelper => true,
339             NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false,
340         }
341     }
342 }
343
344 impl<Id> Res<Id> {
345     /// Return the `DefId` of this `Def` if it has an ID, else panic.
346     pub fn def_id(&self) -> DefId
347     where
348         Id: Debug,
349     {
350         self.opt_def_id()
351             .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
352     }
353
354     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
355     pub fn opt_def_id(&self) -> Option<DefId> {
356         match *self {
357             Res::Def(_, id) => Some(id),
358
359             Res::Local(..)
360             | Res::PrimTy(..)
361             | Res::SelfTy(..)
362             | Res::SelfCtor(..)
363             | Res::ToolMod
364             | Res::NonMacroAttr(..)
365             | Res::Err => None,
366         }
367     }
368
369     /// Return the `DefId` of this `Res` if it represents a module.
370     pub fn mod_def_id(&self) -> Option<DefId> {
371         match *self {
372             Res::Def(DefKind::Mod, id) => Some(id),
373             _ => None,
374         }
375     }
376
377     /// A human readable name for the res kind ("function", "module", etc.).
378     pub fn descr(&self) -> &'static str {
379         match *self {
380             Res::Def(kind, def_id) => kind.descr(def_id),
381             Res::SelfCtor(..) => "self constructor",
382             Res::PrimTy(..) => "builtin type",
383             Res::Local(..) => "local variable",
384             Res::SelfTy(..) => "self type",
385             Res::ToolMod => "tool module",
386             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
387             Res::Err => "unresolved item",
388         }
389     }
390
391     /// Gets an English article for the `Res`.
392     pub fn article(&self) -> &'static str {
393         match *self {
394             Res::Def(kind, _) => kind.article(),
395             Res::NonMacroAttr(kind) => kind.article(),
396             Res::Err => "an",
397             _ => "a",
398         }
399     }
400
401     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
402         match self {
403             Res::Def(kind, id) => Res::Def(kind, id),
404             Res::SelfCtor(id) => Res::SelfCtor(id),
405             Res::PrimTy(id) => Res::PrimTy(id),
406             Res::Local(id) => Res::Local(map(id)),
407             Res::SelfTy(a, b) => Res::SelfTy(a, b),
408             Res::ToolMod => Res::ToolMod,
409             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
410             Res::Err => Res::Err,
411         }
412     }
413
414     pub fn macro_kind(self) -> Option<MacroKind> {
415         match self {
416             Res::Def(DefKind::Macro(kind), _) => Some(kind),
417             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
418             _ => None,
419         }
420     }
421
422     pub fn matches_ns(&self, ns: Namespace) -> bool {
423         match self {
424             Res::Def(kind, ..) => kind.matches_ns(ns),
425             Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => ns == Namespace::TypeNS,
426             Res::SelfCtor(..) | Res::Local(..) => ns == Namespace::ValueNS,
427             Res::NonMacroAttr(..) => ns == Namespace::MacroNS,
428             Res::Err => true,
429         }
430     }
431 }