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