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