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