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