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