]> git.lizzy.rs Git - rust.git/blob - src/librustc_hir/def.rs
Auto merge of #67076 - mbrubeck:condvar, r=dtolnay
[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_macros::HashStable_Generic;
5 use rustc_span::hygiene::MacroKind;
6 use syntax::ast;
7 use syntax::ast::NodeId;
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     Method,
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::Method => "method",
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::Enum
126             | DefKind::OpaqueTy => "an",
127             DefKind::Macro(macro_kind) => macro_kind.article(),
128             _ => "a",
129         }
130     }
131
132     pub fn matches_ns(&self, ns: Namespace) -> bool {
133         match self {
134             DefKind::Mod
135             | DefKind::Struct
136             | DefKind::Union
137             | DefKind::Enum
138             | DefKind::Variant
139             | DefKind::Trait
140             | DefKind::OpaqueTy
141             | DefKind::TyAlias
142             | DefKind::ForeignTy
143             | DefKind::TraitAlias
144             | DefKind::AssocTy
145             | DefKind::AssocOpaqueTy
146             | DefKind::TyParam => ns == Namespace::TypeNS,
147
148             DefKind::Fn
149             | DefKind::Const
150             | DefKind::ConstParam
151             | DefKind::Static
152             | DefKind::Ctor(..)
153             | DefKind::Method
154             | DefKind::AssocConst => ns == Namespace::ValueNS,
155
156             DefKind::Macro(..) => ns == Namespace::MacroNS,
157         }
158     }
159 }
160
161 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
162 #[derive(HashStable_Generic)]
163 pub enum Res<Id = hir::HirId> {
164     Def(DefKind, DefId),
165
166     // Type namespace
167     PrimTy(hir::PrimTy),
168     SelfTy(Option<DefId> /* trait */, Option<DefId> /* impl */),
169     ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
170
171     // Value namespace
172     SelfCtor(DefId /* impl */), // `DefId` refers to the impl
173     Local(Id),
174
175     // Macro namespace
176     NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
177
178     // All namespaces
179     Err,
180 }
181
182 /// The result of resolving a path before lowering to HIR,
183 /// with "module" segments resolved and associated item
184 /// segments deferred to type checking.
185 /// `base_res` is the resolution of the resolved part of the
186 /// path, `unresolved_segments` is the number of unresolved
187 /// segments.
188 ///
189 /// ```text
190 /// module::Type::AssocX::AssocY::MethodOrAssocType
191 /// ^~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
192 /// base_res      unresolved_segments = 3
193 ///
194 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
195 ///       ^~~~~~~~~~~~~~  ^~~~~~~~~~~~~~~~~~~~~~~~~
196 ///       base_res        unresolved_segments = 2
197 /// ```
198 #[derive(Copy, Clone, Debug)]
199 pub struct PartialRes {
200     base_res: Res<NodeId>,
201     unresolved_segments: usize,
202 }
203
204 impl PartialRes {
205     #[inline]
206     pub fn new(base_res: Res<NodeId>) -> Self {
207         PartialRes { base_res, unresolved_segments: 0 }
208     }
209
210     #[inline]
211     pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self {
212         if base_res == Res::Err {
213             unresolved_segments = 0
214         }
215         PartialRes { base_res, unresolved_segments }
216     }
217
218     #[inline]
219     pub fn base_res(&self) -> Res<NodeId> {
220         self.base_res
221     }
222
223     #[inline]
224     pub fn unresolved_segments(&self) -> usize {
225         self.unresolved_segments
226     }
227 }
228
229 /// Different kinds of symbols don't influence each other.
230 ///
231 /// Therefore, they have a separate universe (namespace).
232 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
233 pub enum Namespace {
234     TypeNS,
235     ValueNS,
236     MacroNS,
237 }
238
239 impl Namespace {
240     pub fn descr(self) -> &'static str {
241         match self {
242             Self::TypeNS => "type",
243             Self::ValueNS => "value",
244             Self::MacroNS => "macro",
245         }
246     }
247 }
248
249 /// Just a helper ‒ separate structure for each namespace.
250 #[derive(Copy, Clone, Default, Debug)]
251 pub struct PerNS<T> {
252     pub value_ns: T,
253     pub type_ns: T,
254     pub macro_ns: T,
255 }
256
257 impl<T> PerNS<T> {
258     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
259         PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) }
260     }
261 }
262
263 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
264     type Output = T;
265
266     fn index(&self, ns: Namespace) -> &T {
267         match ns {
268             Namespace::ValueNS => &self.value_ns,
269             Namespace::TypeNS => &self.type_ns,
270             Namespace::MacroNS => &self.macro_ns,
271         }
272     }
273 }
274
275 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
276     fn index_mut(&mut self, ns: Namespace) -> &mut T {
277         match ns {
278             Namespace::ValueNS => &mut self.value_ns,
279             Namespace::TypeNS => &mut self.type_ns,
280             Namespace::MacroNS => &mut self.macro_ns,
281         }
282     }
283 }
284
285 impl<T> PerNS<Option<T>> {
286     /// Returns `true` if all the items in this collection are `None`.
287     pub fn is_empty(&self) -> bool {
288         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
289     }
290
291     /// Returns an iterator over the items which are `Some`.
292     pub fn present_items(self) -> impl Iterator<Item = T> {
293         use std::iter::once;
294
295         once(self.type_ns).chain(once(self.value_ns)).chain(once(self.macro_ns)).filter_map(|it| it)
296     }
297 }
298
299 impl CtorKind {
300     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
301         match *vdata {
302             ast::VariantData::Tuple(..) => CtorKind::Fn,
303             ast::VariantData::Unit(..) => CtorKind::Const,
304             ast::VariantData::Struct(..) => CtorKind::Fictive,
305         }
306     }
307
308     pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind {
309         match *vdata {
310             hir::VariantData::Tuple(..) => CtorKind::Fn,
311             hir::VariantData::Unit(..) => CtorKind::Const,
312             hir::VariantData::Struct(..) => CtorKind::Fictive,
313         }
314     }
315 }
316
317 impl NonMacroAttrKind {
318     pub fn descr(self) -> &'static str {
319         match self {
320             NonMacroAttrKind::Builtin => "built-in attribute",
321             NonMacroAttrKind::Tool => "tool attribute",
322             NonMacroAttrKind::DeriveHelper => "derive helper attribute",
323             NonMacroAttrKind::Registered => "explicitly registered attribute",
324         }
325     }
326
327     pub fn article(self) -> &'static str {
328         match self {
329             NonMacroAttrKind::Registered => "an",
330             _ => "a",
331         }
332     }
333
334     /// Users of some attributes cannot mark them as used, so they are considered always used.
335     pub fn is_used(self) -> bool {
336         match self {
337             NonMacroAttrKind::Tool | NonMacroAttrKind::DeriveHelper => true,
338             NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false,
339         }
340     }
341 }
342
343 impl<Id> Res<Id> {
344     /// Return the `DefId` of this `Def` if it has an ID, else panic.
345     pub fn def_id(&self) -> DefId
346     where
347         Id: Debug,
348     {
349         self.opt_def_id()
350             .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self))
351     }
352
353     /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`.
354     pub fn opt_def_id(&self) -> Option<DefId> {
355         match *self {
356             Res::Def(_, id) => Some(id),
357
358             Res::Local(..)
359             | Res::PrimTy(..)
360             | Res::SelfTy(..)
361             | Res::SelfCtor(..)
362             | Res::ToolMod
363             | Res::NonMacroAttr(..)
364             | Res::Err => None,
365         }
366     }
367
368     /// Return the `DefId` of this `Res` if it represents a module.
369     pub fn mod_def_id(&self) -> Option<DefId> {
370         match *self {
371             Res::Def(DefKind::Mod, id) => Some(id),
372             _ => None,
373         }
374     }
375
376     /// A human readable name for the res kind ("function", "module", etc.).
377     pub fn descr(&self) -> &'static str {
378         match *self {
379             Res::Def(kind, def_id) => kind.descr(def_id),
380             Res::SelfCtor(..) => "self constructor",
381             Res::PrimTy(..) => "builtin type",
382             Res::Local(..) => "local variable",
383             Res::SelfTy(..) => "self type",
384             Res::ToolMod => "tool module",
385             Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
386             Res::Err => "unresolved item",
387         }
388     }
389
390     /// Gets an English article for the `Res`.
391     pub fn article(&self) -> &'static str {
392         match *self {
393             Res::Def(kind, _) => kind.article(),
394             Res::NonMacroAttr(kind) => kind.article(),
395             Res::Err => "an",
396             _ => "a",
397         }
398     }
399
400     pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> {
401         match self {
402             Res::Def(kind, id) => Res::Def(kind, id),
403             Res::SelfCtor(id) => Res::SelfCtor(id),
404             Res::PrimTy(id) => Res::PrimTy(id),
405             Res::Local(id) => Res::Local(map(id)),
406             Res::SelfTy(a, b) => Res::SelfTy(a, b),
407             Res::ToolMod => Res::ToolMod,
408             Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
409             Res::Err => Res::Err,
410         }
411     }
412
413     pub fn macro_kind(self) -> Option<MacroKind> {
414         match self {
415             Res::Def(DefKind::Macro(kind), _) => Some(kind),
416             Res::NonMacroAttr(..) => Some(MacroKind::Attr),
417             _ => None,
418         }
419     }
420
421     pub fn matches_ns(&self, ns: Namespace) -> bool {
422         match self {
423             Res::Def(kind, ..) => kind.matches_ns(ns),
424             Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => ns == Namespace::TypeNS,
425             Res::SelfCtor(..) | Res::Local(..) => ns == Namespace::ValueNS,
426             Res::NonMacroAttr(..) => ns == Namespace::MacroNS,
427             Res::Err => true,
428         }
429     }
430 }