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