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