]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/definitions.rs
Rollup merge of #69033 - jonas-schievink:resume-with-context, r=tmandry
[rust.git] / src / librustc / hir / map / definitions.rs
1 //! For each definition, we track the following data. A definition
2 //! here is defined somewhat circularly as "something with a `DefId`",
3 //! but it generally corresponds to things like structs, enums, etc.
4 //! There are also some rather random cases (like const initializer
5 //! expressions) that are mostly just leftovers.
6
7 use rustc_ast::ast;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::stable_hasher::StableHasher;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_index::vec::IndexVec;
13 use rustc_session::CrateDisambiguator;
14 use rustc_span::hygiene::ExpnId;
15 use rustc_span::symbol::{sym, Symbol};
16 use rustc_span::Span;
17
18 use std::fmt::Write;
19 use std::hash::Hash;
20
21 pub use rustc_hir::def_id::DefPathHash;
22
23 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
24 /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
25 /// stores the `DefIndex` of its parent.
26 /// There is one `DefPathTable` for each crate.
27 #[derive(Clone, Default, RustcDecodable, RustcEncodable)]
28 pub struct DefPathTable {
29     index_to_key: IndexVec<DefIndex, DefKey>,
30     def_path_hashes: IndexVec<DefIndex, DefPathHash>,
31 }
32
33 impl DefPathTable {
34     fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
35         let index = {
36             let index = DefIndex::from(self.index_to_key.len());
37             debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
38             self.index_to_key.push(key);
39             index
40         };
41         self.def_path_hashes.push(def_path_hash);
42         debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
43         index
44     }
45
46     pub fn next_id(&self) -> DefIndex {
47         DefIndex::from(self.index_to_key.len())
48     }
49
50     #[inline(always)]
51     pub fn def_key(&self, index: DefIndex) -> DefKey {
52         self.index_to_key[index]
53     }
54
55     #[inline(always)]
56     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
57         let hash = self.def_path_hashes[index];
58         debug!("def_path_hash({:?}) = {:?}", index, hash);
59         hash
60     }
61
62     pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
63         out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
64             let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
65             (hash, def_id)
66         }));
67     }
68
69     pub fn size(&self) -> usize {
70         self.index_to_key.len()
71     }
72 }
73
74 /// The definition table containing node definitions.
75 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
76 /// mapping from `NodeId`s to local `DefId`s.
77 #[derive(Clone, Default)]
78 pub struct Definitions {
79     table: DefPathTable,
80
81     def_id_to_span: IndexVec<LocalDefId, Span>,
82
83     // FIXME(eddyb) don't go through `ast::NodeId` to convert between `HirId`
84     // and `LocalDefId` - ideally all `LocalDefId`s would be HIR owners.
85     node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
86     def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
87
88     pub(super) node_id_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
89     /// The reverse mapping of `node_id_to_hir_id`.
90     pub(super) hir_id_to_node_id: FxHashMap<hir::HirId, ast::NodeId>,
91
92     /// If `ExpnId` is an ID of some macro expansion,
93     /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
94     parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
95     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
96     expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
97     next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
98     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
99     /// we know what parent node that fragment should be attached to thanks to this table.
100     invocation_parents: FxHashMap<ExpnId, LocalDefId>,
101     /// Indices of unnamed struct or variant fields with unresolved attributes.
102     placeholder_field_indices: FxHashMap<ast::NodeId, usize>,
103 }
104
105 /// A unique identifier that we can use to lookup a definition
106 /// precisely. It combines the index of the definition's parent (if
107 /// any) with a `DisambiguatedDefPathData`.
108 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
109 pub struct DefKey {
110     /// The parent path.
111     pub parent: Option<DefIndex>,
112
113     /// The identifier of this node.
114     pub disambiguated_data: DisambiguatedDefPathData,
115 }
116
117 impl DefKey {
118     fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
119         let mut hasher = StableHasher::new();
120
121         // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
122         // and the special "root_parent" below.
123         0u8.hash(&mut hasher);
124         parent_hash.hash(&mut hasher);
125
126         let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
127
128         ::std::mem::discriminant(data).hash(&mut hasher);
129         if let Some(name) = data.get_opt_name() {
130             // Get a stable hash by considering the symbol chars rather than
131             // the symbol index.
132             name.as_str().hash(&mut hasher);
133         }
134
135         disambiguator.hash(&mut hasher);
136
137         DefPathHash(hasher.finish())
138     }
139
140     fn root_parent_stable_hash(
141         crate_name: &str,
142         crate_disambiguator: CrateDisambiguator,
143     ) -> DefPathHash {
144         let mut hasher = StableHasher::new();
145         // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
146         1u8.hash(&mut hasher);
147         crate_name.hash(&mut hasher);
148         crate_disambiguator.hash(&mut hasher);
149         DefPathHash(hasher.finish())
150     }
151 }
152
153 /// A pair of `DefPathData` and an integer disambiguator. The integer is
154 /// normally `0`, but in the event that there are multiple defs with the
155 /// same `parent` and `data`, we use this field to disambiguate
156 /// between them. This introduces some artificial ordering dependency
157 /// but means that if you have, e.g., two impls for the same type in
158 /// the same module, they do get distinct `DefId`s.
159 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
160 pub struct DisambiguatedDefPathData {
161     pub data: DefPathData,
162     pub disambiguator: u32,
163 }
164
165 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
166 pub struct DefPath {
167     /// The path leading from the crate root to the item.
168     pub data: Vec<DisambiguatedDefPathData>,
169
170     /// The crate root this path is relative to.
171     pub krate: CrateNum,
172 }
173
174 impl DefPath {
175     pub fn is_local(&self) -> bool {
176         self.krate == LOCAL_CRATE
177     }
178
179     pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
180     where
181         FN: FnMut(DefIndex) -> DefKey,
182     {
183         let mut data = vec![];
184         let mut index = Some(start_index);
185         loop {
186             debug!("DefPath::make: krate={:?} index={:?}", krate, index);
187             let p = index.unwrap();
188             let key = get_key(p);
189             debug!("DefPath::make: key={:?}", key);
190             match key.disambiguated_data.data {
191                 DefPathData::CrateRoot => {
192                     assert!(key.parent.is_none());
193                     break;
194                 }
195                 _ => {
196                     data.push(key.disambiguated_data);
197                     index = key.parent;
198                 }
199             }
200         }
201         data.reverse();
202         DefPath { data, krate }
203     }
204
205     /// Returns a string representation of the `DefPath` without
206     /// the crate-prefix. This method is useful if you don't have
207     /// a `TyCtxt` available.
208     pub fn to_string_no_crate(&self) -> String {
209         let mut s = String::with_capacity(self.data.len() * 16);
210
211         for component in &self.data {
212             write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
213         }
214
215         s
216     }
217
218     /// Returns a filename-friendly string for the `DefPath`, with the
219     /// crate-prefix.
220     pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
221     where
222         F: FnOnce(CrateNum) -> Symbol,
223     {
224         let crate_name_str = crate_imported_name(self.krate).as_str();
225         let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
226
227         write!(s, "::{}", crate_name_str).unwrap();
228
229         for component in &self.data {
230             if component.disambiguator == 0 {
231                 write!(s, "::{}", component.data.as_symbol()).unwrap();
232             } else {
233                 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
234             }
235         }
236
237         s
238     }
239
240     /// Returns a filename-friendly string of the `DefPath`, without
241     /// the crate-prefix. This method is useful if you don't have
242     /// a `TyCtxt` available.
243     pub fn to_filename_friendly_no_crate(&self) -> String {
244         let mut s = String::with_capacity(self.data.len() * 16);
245
246         let mut opt_delimiter = None;
247         for component in &self.data {
248             opt_delimiter.map(|d| s.push(d));
249             opt_delimiter = Some('-');
250             if component.disambiguator == 0 {
251                 write!(s, "{}", component.data.as_symbol()).unwrap();
252             } else {
253                 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
254             }
255         }
256         s
257     }
258 }
259
260 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
261 pub enum DefPathData {
262     // Root: these should only be used for the root nodes, because
263     // they are treated specially by the `def_path` function.
264     /// The crate root (marker).
265     CrateRoot,
266     // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
267     Misc,
268
269     // Different kinds of items and item-like things:
270     /// An impl.
271     Impl,
272     /// Something in the type namespace.
273     TypeNs(Symbol),
274     /// Something in the value namespace.
275     ValueNs(Symbol),
276     /// Something in the macro namespace.
277     MacroNs(Symbol),
278     /// Something in the lifetime namespace.
279     LifetimeNs(Symbol),
280     /// A closure expression.
281     ClosureExpr,
282
283     // Subportions of items:
284     /// Implicit constructor for a unit or tuple-like struct or enum variant.
285     Ctor,
286     /// A constant expression (see `{ast,hir}::AnonConst`).
287     AnonConst,
288     /// An `impl Trait` type node.
289     ImplTrait,
290 }
291
292 impl Definitions {
293     pub fn def_path_table(&self) -> &DefPathTable {
294         &self.table
295     }
296
297     /// Gets the number of definitions.
298     pub fn def_index_count(&self) -> usize {
299         self.table.index_to_key.len()
300     }
301
302     pub fn def_key(&self, id: LocalDefId) -> DefKey {
303         self.table.def_key(id.local_def_index)
304     }
305
306     #[inline(always)]
307     pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
308         self.table.def_path_hash(id.local_def_index)
309     }
310
311     /// Returns the path from the crate root to `index`. The root
312     /// nodes are not included in the path (i.e., this will be an
313     /// empty vector for the crate root). For an inlined item, this
314     /// will be the path of the item in the external crate (but the
315     /// path will begin with the path to the external crate).
316     pub fn def_path(&self, id: LocalDefId) -> DefPath {
317         DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
318             self.def_key(LocalDefId { local_def_index: index })
319         })
320     }
321
322     #[inline]
323     pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<LocalDefId> {
324         self.node_id_to_def_id.get(&node).copied()
325     }
326
327     // FIXME(eddyb) this function can and should return `LocalDefId`.
328     #[inline]
329     pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
330         self.opt_local_def_id(node).unwrap().to_def_id()
331     }
332
333     #[inline]
334     pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
335         if let Some(def_id) = def_id.as_local() {
336             let node_id = self.def_id_to_node_id[def_id];
337             if node_id != ast::DUMMY_NODE_ID {
338                 return Some(node_id);
339             }
340         }
341         None
342     }
343
344     #[inline]
345     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
346         if let Some(def_id) = def_id.as_local() {
347             let hir_id = self.local_def_id_to_hir_id(def_id);
348             if hir_id != hir::DUMMY_HIR_ID { Some(hir_id) } else { None }
349         } else {
350             None
351         }
352     }
353
354     // FIXME(eddyb) rename to `hir_id_to_node_id`.
355     #[inline]
356     pub fn hir_to_node_id(&self, hir_id: hir::HirId) -> ast::NodeId {
357         self.hir_id_to_node_id[&hir_id]
358     }
359
360     // FIXME(eddyb) rename to `node_id_to_hir_id`.
361     #[inline]
362     pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
363         self.node_id_to_hir_id[node_id]
364     }
365
366     #[inline]
367     pub fn local_def_id_to_hir_id(&self, id: LocalDefId) -> hir::HirId {
368         let node_id = self.def_id_to_node_id[id];
369         self.node_id_to_hir_id[node_id]
370     }
371
372     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
373     #[inline]
374     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
375         if let Some(def_id) = def_id.as_local() { Some(self.def_id_to_span[def_id]) } else { None }
376     }
377
378     /// Adds a root definition (no parent) and a few other reserved definitions.
379     pub fn create_root_def(
380         &mut self,
381         crate_name: &str,
382         crate_disambiguator: CrateDisambiguator,
383     ) -> LocalDefId {
384         let key = DefKey {
385             parent: None,
386             disambiguated_data: DisambiguatedDefPathData {
387                 data: DefPathData::CrateRoot,
388                 disambiguator: 0,
389             },
390         };
391
392         let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
393         let def_path_hash = key.compute_stable_hash(parent_hash);
394
395         // Create the definition.
396         let root = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
397         assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
398
399         assert_eq!(self.def_id_to_node_id.push(ast::CRATE_NODE_ID), root);
400         assert_eq!(self.def_id_to_span.push(rustc_span::DUMMY_SP), root);
401
402         self.node_id_to_def_id.insert(ast::CRATE_NODE_ID, root);
403         self.set_invocation_parent(ExpnId::root(), root);
404
405         root
406     }
407
408     /// Adds a definition with a parent definition.
409     pub fn create_def_with_parent(
410         &mut self,
411         parent: LocalDefId,
412         node_id: ast::NodeId,
413         data: DefPathData,
414         expn_id: ExpnId,
415         span: Span,
416     ) -> LocalDefId {
417         debug!(
418             "create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
419             parent, node_id, data
420         );
421
422         assert!(
423             !self.node_id_to_def_id.contains_key(&node_id),
424             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
425             node_id,
426             data,
427             self.table.def_key(self.node_id_to_def_id[&node_id].local_def_index),
428         );
429
430         // The root node must be created with `create_root_def()`.
431         assert!(data != DefPathData::CrateRoot);
432
433         // Find the next free disambiguator for this key.
434         let disambiguator = {
435             let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
436             let disambiguator = *next_disamb;
437             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
438             disambiguator
439         };
440
441         let key = DefKey {
442             parent: Some(parent.local_def_index),
443             disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
444         };
445
446         let parent_hash = self.table.def_path_hash(parent.local_def_index);
447         let def_path_hash = key.compute_stable_hash(parent_hash);
448
449         debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
450
451         // Create the definition.
452         let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
453
454         assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
455         assert_eq!(self.def_id_to_span.push(span), def_id);
456
457         // Some things for which we allocate `LocalDefId`s don't correspond to
458         // anything in the AST, so they don't have a `NodeId`. For these cases
459         // we don't need a mapping from `NodeId` to `LocalDefId`.
460         if node_id != ast::DUMMY_NODE_ID {
461             debug!("create_def_with_parent: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
462             self.node_id_to_def_id.insert(node_id, def_id);
463         }
464
465         if expn_id != ExpnId::root() {
466             self.expansions_that_defined.insert(def_id, expn_id);
467         }
468
469         def_id
470     }
471
472     /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
473     /// AST to HIR lowering.
474     pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
475         assert!(
476             self.node_id_to_hir_id.is_empty(),
477             "trying to initialize `NodeId` -> `HirId` mapping twice"
478         );
479         self.node_id_to_hir_id = mapping;
480
481         // Build the reverse mapping of `node_id_to_hir_id`.
482         self.hir_id_to_node_id = self
483             .node_id_to_hir_id
484             .iter_enumerated()
485             .map(|(node_id, &hir_id)| (hir_id, node_id))
486             .collect();
487     }
488
489     pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
490         self.expansions_that_defined.get(&id).copied().unwrap_or(ExpnId::root())
491     }
492
493     pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
494         self.parent_modules_of_macro_defs[&expn_id]
495     }
496
497     pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
498         self.parent_modules_of_macro_defs.insert(expn_id, module);
499     }
500
501     pub fn invocation_parent(&self, invoc_id: ExpnId) -> LocalDefId {
502         self.invocation_parents[&invoc_id]
503     }
504
505     pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: LocalDefId) {
506         let old_parent = self.invocation_parents.insert(invoc_id, parent);
507         assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
508     }
509
510     pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
511         self.placeholder_field_indices[&node_id]
512     }
513
514     pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
515         let old_index = self.placeholder_field_indices.insert(node_id, index);
516         assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
517     }
518 }
519
520 impl DefPathData {
521     pub fn get_opt_name(&self) -> Option<Symbol> {
522         use self::DefPathData::*;
523         match *self {
524             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
525
526             Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
527         }
528     }
529
530     pub fn as_symbol(&self) -> Symbol {
531         use self::DefPathData::*;
532         match *self {
533             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
534             // Note that this does not show up in user print-outs.
535             CrateRoot => sym::double_braced_crate,
536             Impl => sym::double_braced_impl,
537             Misc => sym::double_braced_misc,
538             ClosureExpr => sym::double_braced_closure,
539             Ctor => sym::double_braced_constructor,
540             AnonConst => sym::double_braced_constant,
541             ImplTrait => sym::double_braced_opaque,
542         }
543     }
544
545     pub fn to_string(&self) -> String {
546         self.as_symbol().to_string()
547     }
548 }