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