]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/collector.rs
Auto merge of #58065 - alexreg:refactor-smart_resolve_path_fragment, r=petrochenkov
[rust.git] / src / librustc / hir / map / collector.rs
1 use super::*;
2 use crate::dep_graph::{DepGraph, DepKind, DepNodeIndex};
3 use crate::hir;
4 use crate::hir::def_id::{LOCAL_CRATE, CrateNum};
5 use crate::hir::intravisit::{Visitor, NestedVisitorMap};
6 use rustc_data_structures::svh::Svh;
7 use crate::ich::Fingerprint;
8 use crate::middle::cstore::CrateStore;
9 use crate::session::CrateDisambiguator;
10 use crate::session::Session;
11 use std::iter::repeat;
12 use syntax::ast::{NodeId, CRATE_NODE_ID};
13 use syntax::source_map::SourceMap;
14 use syntax_pos::Span;
15
16 use crate::ich::StableHashingContext;
17 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
18
19 /// A Visitor that walks over the HIR and collects Nodes into a HIR map
20 pub(super) struct NodeCollector<'a, 'hir> {
21     /// The crate
22     krate: &'hir Crate,
23
24     /// Source map
25     source_map: &'a SourceMap,
26
27     /// The node map
28     map: Vec<Option<Entry<'hir>>>,
29     /// The parent of this node
30     parent_node: NodeId,
31
32     parent_hir: hir::HirId,
33
34     // These fields keep track of the currently relevant DepNodes during
35     // the visitor's traversal.
36     current_dep_node_owner: DefIndex,
37     current_signature_dep_index: DepNodeIndex,
38     current_full_dep_index: DepNodeIndex,
39     currently_in_body: bool,
40
41     dep_graph: &'a DepGraph,
42     definitions: &'a definitions::Definitions,
43
44     hcx: StableHashingContext<'a>,
45
46     // We are collecting DepNode::HirBody hashes here so we can compute the
47     // crate hash from then later on.
48     hir_body_nodes: Vec<(DefPathHash, Fingerprint)>,
49 }
50
51 fn input_dep_node_and_hash<'a, I>(
52     dep_graph: &DepGraph,
53     hcx: &mut StableHashingContext<'a>,
54     dep_node: DepNode,
55     input: I,
56 ) -> (DepNodeIndex, Fingerprint)
57 where
58     I: HashStable<StableHashingContext<'a>>,
59 {
60     let dep_node_index = dep_graph.input_task(dep_node, &mut *hcx, &input).1;
61
62     let hash = if dep_graph.is_fully_enabled() {
63         dep_graph.fingerprint_of(dep_node_index)
64     } else {
65         let mut stable_hasher = StableHasher::new();
66         input.hash_stable(hcx, &mut stable_hasher);
67         stable_hasher.finish()
68     };
69
70     (dep_node_index, hash)
71 }
72
73 fn alloc_hir_dep_nodes<'a, I>(
74     dep_graph: &DepGraph,
75     hcx: &mut StableHashingContext<'a>,
76     def_path_hash: DefPathHash,
77     item_like: I,
78     hir_body_nodes: &mut Vec<(DefPathHash, Fingerprint)>,
79 ) -> (DepNodeIndex, DepNodeIndex)
80 where
81     I: HashStable<StableHashingContext<'a>>,
82 {
83     let sig = dep_graph.input_task(
84         def_path_hash.to_dep_node(DepKind::Hir),
85         &mut *hcx,
86         HirItemLike { item_like: &item_like, hash_bodies: false },
87     ).1;
88     let (full, hash) = input_dep_node_and_hash(
89         dep_graph,
90         hcx,
91         def_path_hash.to_dep_node(DepKind::HirBody),
92         HirItemLike { item_like: &item_like, hash_bodies: true },
93     );
94     hir_body_nodes.push((def_path_hash, hash));
95     (sig, full)
96 }
97
98 impl<'a, 'hir> NodeCollector<'a, 'hir> {
99     pub(super) fn root(sess: &'a Session,
100                        krate: &'hir Crate,
101                        dep_graph: &'a DepGraph,
102                        definitions: &'a definitions::Definitions,
103                        mut hcx: StableHashingContext<'a>)
104                 -> NodeCollector<'a, 'hir> {
105         let root_mod_def_path_hash = definitions.def_path_hash(CRATE_DEF_INDEX);
106
107         let mut hir_body_nodes = Vec::new();
108
109         // Allocate DepNodes for the root module
110         let (root_mod_sig_dep_index, root_mod_full_dep_index) = {
111             let Crate {
112                 ref module,
113                 // Crate attributes are not copied over to the root `Mod`, so hash
114                 // them explicitly here.
115                 ref attrs,
116                 span,
117                 // These fields are handled separately:
118                 exported_macros: _,
119                 items: _,
120                 trait_items: _,
121                 impl_items: _,
122                 bodies: _,
123                 trait_impls: _,
124                 trait_auto_impl: _,
125                 body_ids: _,
126                 modules: _,
127             } = *krate;
128
129             alloc_hir_dep_nodes(
130                 dep_graph,
131                 &mut hcx,
132                 root_mod_def_path_hash,
133                 (module, attrs, span),
134                 &mut hir_body_nodes,
135             )
136         };
137
138         {
139             dep_graph.input_task(
140                 DepNode::new_no_params(DepKind::AllLocalTraitImpls),
141                 &mut hcx,
142                 &krate.trait_impls,
143             );
144         }
145
146         let mut collector = NodeCollector {
147             krate,
148             source_map: sess.source_map(),
149             map: repeat(None).take(sess.current_node_id_count()).collect(),
150             parent_node: CRATE_NODE_ID,
151             parent_hir: hir::CRATE_HIR_ID,
152             current_signature_dep_index: root_mod_sig_dep_index,
153             current_full_dep_index: root_mod_full_dep_index,
154             current_dep_node_owner: CRATE_DEF_INDEX,
155             currently_in_body: false,
156             dep_graph,
157             definitions,
158             hcx,
159             hir_body_nodes,
160         };
161         collector.insert_entry(CRATE_NODE_ID, Entry {
162             parent: CRATE_NODE_ID,
163             parent_hir: hir::CRATE_HIR_ID,
164             dep_node: root_mod_sig_dep_index,
165             node: Node::Crate,
166         });
167
168         collector
169     }
170
171     pub(super) fn finalize_and_compute_crate_hash(mut self,
172                                                   crate_disambiguator: CrateDisambiguator,
173                                                   cstore: &dyn CrateStore,
174                                                   commandline_args_hash: u64)
175                                                   -> (Vec<Option<Entry<'hir>>>, Svh)
176     {
177         self.hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
178
179         let node_hashes = self
180             .hir_body_nodes
181             .iter()
182             .fold(Fingerprint::ZERO, |combined_fingerprint, &(def_path_hash, fingerprint)| {
183                 combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
184             });
185
186         let mut upstream_crates: Vec<_> = cstore.crates_untracked().iter().map(|&cnum| {
187             let name = cstore.crate_name_untracked(cnum).as_str();
188             let disambiguator = cstore.crate_disambiguator_untracked(cnum).to_fingerprint();
189             let hash = cstore.crate_hash_untracked(cnum);
190             (name, disambiguator, hash)
191         }).collect();
192
193         upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name, dis));
194
195         // We hash the final, remapped names of all local source files so we
196         // don't have to include the path prefix remapping commandline args.
197         // If we included the full mapping in the SVH, we could only have
198         // reproducible builds by compiling from the same directory. So we just
199         // hash the result of the mapping instead of the mapping itself.
200         let mut source_file_names: Vec<_> = self
201             .source_map
202             .files()
203             .iter()
204             .filter(|source_file| CrateNum::from_u32(source_file.crate_of_origin) == LOCAL_CRATE)
205             .map(|source_file| source_file.name_hash)
206             .collect();
207
208         source_file_names.sort_unstable();
209
210         let crate_hash_input = (
211             ((node_hashes, upstream_crates), source_file_names),
212             (commandline_args_hash, crate_disambiguator.to_fingerprint())
213         );
214
215         let (_, crate_hash) = input_dep_node_and_hash(
216             self.dep_graph,
217             &mut self.hcx,
218             DepNode::new_no_params(DepKind::Krate),
219             crate_hash_input,
220         );
221
222         let svh = Svh::new(crate_hash.to_smaller_hash());
223         (self.map, svh)
224     }
225
226     fn insert_entry(&mut self, id: NodeId, entry: Entry<'hir>) {
227         debug!("hir_map: {:?} => {:?}", id, entry);
228         self.map[id.as_usize()] = Some(entry);
229     }
230
231     fn insert(&mut self, span: Span, id: NodeId, node: Node<'hir>) {
232         let entry = Entry {
233             parent: self.parent_node,
234             parent_hir: self.parent_hir,
235             dep_node: if self.currently_in_body {
236                 self.current_full_dep_index
237             } else {
238                 self.current_signature_dep_index
239             },
240             node,
241         };
242
243         // Make sure that the DepNode of some node coincides with the HirId
244         // owner of that node.
245         if cfg!(debug_assertions) {
246             let hir_id = self.definitions.node_to_hir_id(id);
247
248             if hir_id.owner != self.current_dep_node_owner {
249                 let node_str = match self.definitions.opt_def_index(id) {
250                     Some(def_index) => {
251                         self.definitions.def_path(def_index).to_string_no_crate()
252                     }
253                     None => format!("{:?}", node)
254                 };
255
256                 let forgot_str = if hir_id == crate::hir::DUMMY_HIR_ID {
257                     format!("\nMaybe you forgot to lower the node id {:?}?", id)
258                 } else {
259                     String::new()
260                 };
261
262                 span_bug!(
263                     span,
264                     "inconsistent DepNode at `{:?}` for `{}`: \
265                      current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?}){}",
266                     self.source_map.span_to_string(span),
267                     node_str,
268                     self.definitions
269                         .def_path(self.current_dep_node_owner)
270                         .to_string_no_crate(),
271                     self.current_dep_node_owner,
272                     self.definitions.def_path(hir_id.owner).to_string_no_crate(),
273                     hir_id.owner,
274                     forgot_str,
275                 )
276             }
277         }
278
279         self.insert_entry(id, entry);
280     }
281
282     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_id: NodeId, f: F) {
283         let parent_node = self.parent_node;
284         self.parent_node = parent_id;
285         f(self);
286         self.parent_node = parent_node;
287     }
288
289     fn with_dep_node_owner<T: HashStable<StableHashingContext<'a>>,
290                            F: FnOnce(&mut Self)>(&mut self,
291                                                  dep_node_owner: DefIndex,
292                                                  item_like: &T,
293                                                  f: F) {
294         let prev_owner = self.current_dep_node_owner;
295         let prev_signature_dep_index = self.current_signature_dep_index;
296         let prev_full_dep_index = self.current_full_dep_index;
297         let prev_in_body = self.currently_in_body;
298
299         let def_path_hash = self.definitions.def_path_hash(dep_node_owner);
300
301         let (signature_dep_index, full_dep_index) = alloc_hir_dep_nodes(
302             self.dep_graph,
303             &mut self.hcx,
304             def_path_hash,
305             item_like,
306             &mut self.hir_body_nodes,
307         );
308         self.current_signature_dep_index = signature_dep_index;
309         self.current_full_dep_index = full_dep_index;
310
311         self.current_dep_node_owner = dep_node_owner;
312         self.currently_in_body = false;
313         f(self);
314         self.currently_in_body = prev_in_body;
315         self.current_dep_node_owner = prev_owner;
316         self.current_full_dep_index = prev_full_dep_index;
317         self.current_signature_dep_index = prev_signature_dep_index;
318     }
319 }
320
321 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
322     /// Because we want to track parent items and so forth, enable
323     /// deep walking so that we walk nested items in the context of
324     /// their outer items.
325
326     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
327         panic!("visit_nested_xxx must be manually implemented in this visitor")
328     }
329
330     fn visit_nested_item(&mut self, item: ItemId) {
331         debug!("visit_nested_item: {:?}", item);
332         self.visit_item(self.krate.item(item.id));
333     }
334
335     fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
336         self.visit_trait_item(self.krate.trait_item(item_id));
337     }
338
339     fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
340         self.visit_impl_item(self.krate.impl_item(item_id));
341     }
342
343     fn visit_nested_body(&mut self, id: BodyId) {
344         let prev_in_body = self.currently_in_body;
345         self.currently_in_body = true;
346         self.visit_body(self.krate.body(id));
347         self.currently_in_body = prev_in_body;
348     }
349
350     fn visit_item(&mut self, i: &'hir Item) {
351         debug!("visit_item: {:?}", i);
352         debug_assert_eq!(i.hir_id.owner,
353                          self.definitions.opt_def_index(i.id).unwrap());
354         self.with_dep_node_owner(i.hir_id.owner, i, |this| {
355             this.insert(i.span, i.id, Node::Item(i));
356             this.with_parent(i.id, |this| {
357                 if let ItemKind::Struct(ref struct_def, _) = i.node {
358                     // If this is a tuple-like struct, register the constructor.
359                     if !struct_def.is_struct() {
360                         this.insert(i.span, struct_def.id(), Node::StructCtor(struct_def));
361                     }
362                 }
363                 intravisit::walk_item(this, i);
364             });
365         });
366     }
367
368     fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem) {
369         self.insert(foreign_item.span, foreign_item.id, Node::ForeignItem(foreign_item));
370
371         self.with_parent(foreign_item.id, |this| {
372             intravisit::walk_foreign_item(this, foreign_item);
373         });
374     }
375
376     fn visit_generic_param(&mut self, param: &'hir GenericParam) {
377         self.insert(param.span, param.id, Node::GenericParam(param));
378         intravisit::walk_generic_param(self, param);
379     }
380
381     fn visit_trait_item(&mut self, ti: &'hir TraitItem) {
382         debug_assert_eq!(ti.hir_id.owner,
383                          self.definitions.opt_def_index(ti.id).unwrap());
384         self.with_dep_node_owner(ti.hir_id.owner, ti, |this| {
385             this.insert(ti.span, ti.id, Node::TraitItem(ti));
386
387             this.with_parent(ti.id, |this| {
388                 intravisit::walk_trait_item(this, ti);
389             });
390         });
391     }
392
393     fn visit_impl_item(&mut self, ii: &'hir ImplItem) {
394         debug_assert_eq!(ii.hir_id.owner,
395                          self.definitions.opt_def_index(ii.id).unwrap());
396         self.with_dep_node_owner(ii.hir_id.owner, ii, |this| {
397             this.insert(ii.span, ii.id, Node::ImplItem(ii));
398
399             this.with_parent(ii.id, |this| {
400                 intravisit::walk_impl_item(this, ii);
401             });
402         });
403     }
404
405     fn visit_pat(&mut self, pat: &'hir Pat) {
406         let node = if let PatKind::Binding(..) = pat.node {
407             Node::Binding(pat)
408         } else {
409             Node::Pat(pat)
410         };
411         self.insert(pat.span, pat.id, node);
412
413         self.with_parent(pat.id, |this| {
414             intravisit::walk_pat(this, pat);
415         });
416     }
417
418     fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
419         self.insert(DUMMY_SP, constant.id, Node::AnonConst(constant));
420
421         self.with_parent(constant.id, |this| {
422             intravisit::walk_anon_const(this, constant);
423         });
424     }
425
426     fn visit_expr(&mut self, expr: &'hir Expr) {
427         self.insert(expr.span, expr.id, Node::Expr(expr));
428
429         self.with_parent(expr.id, |this| {
430             intravisit::walk_expr(this, expr);
431         });
432     }
433
434     fn visit_stmt(&mut self, stmt: &'hir Stmt) {
435         let id = stmt.id;
436         self.insert(stmt.span, id, Node::Stmt(stmt));
437
438         self.with_parent(id, |this| {
439             intravisit::walk_stmt(this, stmt);
440         });
441     }
442
443     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment) {
444         if let Some(id) = path_segment.id {
445             self.insert(path_span, id, Node::PathSegment(path_segment));
446         }
447         intravisit::walk_path_segment(self, path_span, path_segment);
448     }
449
450     fn visit_ty(&mut self, ty: &'hir Ty) {
451         self.insert(ty.span, ty.id, Node::Ty(ty));
452
453         self.with_parent(ty.id, |this| {
454             intravisit::walk_ty(this, ty);
455         });
456     }
457
458     fn visit_trait_ref(&mut self, tr: &'hir TraitRef) {
459         self.insert(tr.path.span, tr.ref_id, Node::TraitRef(tr));
460
461         self.with_parent(tr.ref_id, |this| {
462             intravisit::walk_trait_ref(this, tr);
463         });
464     }
465
466     fn visit_fn(&mut self, fk: intravisit::FnKind<'hir>, fd: &'hir FnDecl,
467                 b: BodyId, s: Span, id: NodeId) {
468         assert_eq!(self.parent_node, id);
469         intravisit::walk_fn(self, fk, fd, b, s, id);
470     }
471
472     fn visit_block(&mut self, block: &'hir Block) {
473         self.insert(block.span, block.id, Node::Block(block));
474         self.with_parent(block.id, |this| {
475             intravisit::walk_block(this, block);
476         });
477     }
478
479     fn visit_local(&mut self, l: &'hir Local) {
480         self.insert(l.span, l.id, Node::Local(l));
481         self.with_parent(l.id, |this| {
482             intravisit::walk_local(this, l)
483         })
484     }
485
486     fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
487         self.insert(lifetime.span, lifetime.id, Node::Lifetime(lifetime));
488     }
489
490     fn visit_vis(&mut self, visibility: &'hir Visibility) {
491         match visibility.node {
492             VisibilityKind::Public |
493             VisibilityKind::Crate(_) |
494             VisibilityKind::Inherited => {}
495             VisibilityKind::Restricted { id, .. } => {
496                 self.insert(visibility.span, id, Node::Visibility(visibility));
497                 self.with_parent(id, |this| {
498                     intravisit::walk_vis(this, visibility);
499                 });
500             }
501         }
502     }
503
504     fn visit_macro_def(&mut self, macro_def: &'hir MacroDef) {
505         let def_index = self.definitions.opt_def_index(macro_def.id).unwrap();
506
507         self.with_dep_node_owner(def_index, macro_def, |this| {
508             this.insert(macro_def.span, macro_def.id, Node::MacroDef(macro_def));
509         });
510     }
511
512     fn visit_variant(&mut self, v: &'hir Variant, g: &'hir Generics, item_id: NodeId) {
513         let id = v.node.data.id();
514         self.insert(v.span, id, Node::Variant(v));
515         self.with_parent(id, |this| {
516             intravisit::walk_variant(this, v, g, item_id);
517         });
518     }
519
520     fn visit_struct_field(&mut self, field: &'hir StructField) {
521         self.insert(field.span, field.id, Node::Field(field));
522         self.with_parent(field.id, |this| {
523             intravisit::walk_struct_field(this, field);
524         });
525     }
526
527     fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
528         // Do not visit the duplicate information in TraitItemRef. We want to
529         // map the actual nodes, not the duplicate ones in the *Ref.
530         let TraitItemRef {
531             id,
532             ident: _,
533             kind: _,
534             span: _,
535             defaultness: _,
536         } = *ii;
537
538         self.visit_nested_trait_item(id);
539     }
540
541     fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef) {
542         // Do not visit the duplicate information in ImplItemRef. We want to
543         // map the actual nodes, not the duplicate ones in the *Ref.
544         let ImplItemRef {
545             id,
546             ident: _,
547             kind: _,
548             span: _,
549             vis: _,
550             defaultness: _,
551         } = *ii;
552
553         self.visit_nested_impl_item(id);
554     }
555 }
556
557 // This is a wrapper structure that allows determining if span values within
558 // the wrapped item should be hashed or not.
559 struct HirItemLike<T> {
560     item_like: T,
561     hash_bodies: bool,
562 }
563
564 impl<'a, 'hir, T> HashStable<StableHashingContext<'hir>> for HirItemLike<T>
565     where T: HashStable<StableHashingContext<'hir>>
566 {
567     fn hash_stable<W: StableHasherResult>(&self,
568                                           hcx: &mut StableHashingContext<'hir>,
569                                           hasher: &mut StableHasher<W>) {
570         hcx.while_hashing_hir_bodies(self.hash_bodies, |hcx| {
571             self.item_like.hash_stable(hcx, hasher);
572         });
573     }
574 }