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