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;
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};
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;
21 use std::iter::repeat;
23 /// A visitor that walks over the HIR and collects `Node`s into a HIR map.
24 pub(super) struct NodeCollector<'a, 'hir> {
26 krate: &'hir Crate<'hir>,
29 source_map: &'a SourceMap,
32 map: HirEntryMap<'hir>,
33 /// The parent of this node
34 parent_node: hir::HirId,
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,
43 dep_graph: &'a DepGraph,
44 definitions: &'a definitions::Definitions,
45 hir_to_node_id: &'a FxHashMap<HirId, NodeId>,
47 hcx: StableHashingContext<'a>,
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)>,
54 fn input_dep_node_and_hash(
56 hcx: &mut StableHashingContext<'_>,
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;
62 let hash = if dep_graph.is_fully_enabled() {
63 dep_graph.fingerprint_of(dep_node_index)
65 let mut stable_hasher = StableHasher::new();
66 input.hash_stable(hcx, &mut stable_hasher);
67 stable_hasher.finish()
70 (dep_node_index, hash)
73 fn alloc_hir_dep_nodes(
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) {
82 def_path_hash.to_dep_node(DepKind::Hir),
84 HirItemLike { item_like: &item_like, hash_bodies: false },
87 let (full, hash) = input_dep_node_and_hash(
90 def_path_hash.to_dep_node(DepKind::HirBody),
91 HirItemLike { item_like: &item_like, hash_bodies: true },
93 hir_body_nodes.push((def_path_hash, hash));
97 fn upstream_crates(cstore: &dyn CrateStore) -> Vec<(Symbol, Fingerprint, Svh)> {
98 let mut upstream_crates: Vec<_> = cstore
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)
108 upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name.as_str(), dis));
112 impl<'a, 'hir> NodeCollector<'a, 'hir> {
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);
123 let mut hir_body_nodes = Vec::new();
125 // Allocate `DepNode`s for the root module.
126 let (root_mod_sig_dep_index, root_mod_full_dep_index) = {
129 // Crate attributes are not copied over to the root `Mod`, so hash
130 // them explicitly here.
133 // These fields are handled separately:
135 non_exported_macro_attrs: _,
148 root_mod_def_path_hash,
149 (module, attrs, span),
155 dep_graph.input_task(
156 DepNode::new_no_params(DepKind::AllLocalTraitImpls),
162 let mut collector = NodeCollector {
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,
177 collector.insert_entry(
180 parent: hir::CRATE_HIR_ID,
181 dep_node: root_mod_sig_dep_index,
189 pub(super) fn finalize_and_compute_crate_hash(
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);
197 let node_hashes = self.hir_body_nodes.iter().fold(
199 |combined_fingerprint, &(def_path_hash, fingerprint)| {
200 combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
204 let upstream_crates = upstream_crates(cstore);
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
215 .filter(|source_file| CrateNum::from_u32(source_file.crate_of_origin) == LOCAL_CRATE)
216 .map(|source_file| source_file.name_hash)
219 source_file_names.sort_unstable();
221 let crate_hash_input = (
222 ((node_hashes, upstream_crates), source_file_names),
223 (commandline_args_hash, crate_disambiguator.to_fingerprint()),
226 let (_, crate_hash) = input_dep_node_and_hash(
229 DepNode::new_no_params(DepKind::Krate),
233 let svh = Svh::new(crate_hash.to_smaller_hash());
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();
243 local_map.extend(repeat(None).take(i - len + 1));
245 local_map[id.local_id] = Some(entry);
248 fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
250 parent: self.parent_node,
251 dep_node: if self.currently_in_body {
252 self.current_full_dep_index
254 self.current_signature_dep_index
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);
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),
271 let forgot_str = if hir_id == hir::DUMMY_HIR_ID {
272 format!("\nMaybe you forgot to lower the node id {:?}?", node_id)
279 "inconsistent DepNode at `{:?}` for `{}`: \
280 current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?}){}",
281 self.source_map.span_to_string(span),
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(),
292 self.insert_entry(hir_id, entry);
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;
299 self.parent_node = parent_node;
302 fn with_dep_node_owner<
303 T: for<'b> HashStable<StableHashingContext<'b>>,
304 F: FnOnce(&mut Self),
307 dep_node_owner: DefIndex,
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;
316 let def_path_hash = self.definitions.def_path_hash(dep_node_owner);
318 let (signature_dep_index, full_dep_index) = alloc_hir_dep_nodes(
323 &mut self.hir_body_nodes,
325 self.current_signature_dep_index = signature_dep_index;
326 self.current_full_dep_index = full_dep_index;
328 self.current_dep_node_owner = dep_node_owner;
329 self.currently_in_body = false;
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;
338 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
339 type Map = Map<'hir>;
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.
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");
349 fn visit_nested_item(&mut self, item: ItemId) {
350 debug!("visit_nested_item: {:?}", item);
351 self.visit_item(self.krate.item(item.id));
354 fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
355 self.visit_trait_item(self.krate.trait_item(item_id));
358 fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
359 self.visit_impl_item(self.krate.impl_item(item_id));
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;
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);
377 fn visit_item(&mut self, i: &'hir Item<'hir>) {
378 debug!("visit_item: {:?}", i);
381 self.definitions.opt_def_index(self.hir_to_node_id[&i.hir_id]).unwrap()
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));
392 intravisit::walk_item(this, i);
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));
400 self.with_parent(foreign_item.hir_id, |this| {
401 intravisit::walk_foreign_item(this, foreign_item);
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);
410 fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
413 self.definitions.opt_def_index(self.hir_to_node_id[&ti.hir_id]).unwrap()
415 self.with_dep_node_owner(ti.hir_id.owner, ti, |this| {
416 this.insert(ti.span, ti.hir_id, Node::TraitItem(ti));
418 this.with_parent(ti.hir_id, |this| {
419 intravisit::walk_trait_item(this, ti);
424 fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
427 self.definitions.opt_def_index(self.hir_to_node_id[&ii.hir_id]).unwrap()
429 self.with_dep_node_owner(ii.hir_id.owner, ii, |this| {
430 this.insert(ii.span, ii.hir_id, Node::ImplItem(ii));
432 this.with_parent(ii.hir_id, |this| {
433 intravisit::walk_impl_item(this, ii);
438 fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
440 if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) };
441 self.insert(pat.span, pat.hir_id, node);
443 self.with_parent(pat.hir_id, |this| {
444 intravisit::walk_pat(this, pat);
448 fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
449 let node = Node::Arm(arm);
451 self.insert(arm.span, arm.hir_id, node);
453 self.with_parent(arm.hir_id, |this| {
454 intravisit::walk_arm(this, arm);
458 fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
459 self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
461 self.with_parent(constant.hir_id, |this| {
462 intravisit::walk_anon_const(this, constant);
466 fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
467 self.insert(expr.span, expr.hir_id, Node::Expr(expr));
469 self.with_parent(expr.hir_id, |this| {
470 intravisit::walk_expr(this, expr);
474 fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
475 self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
477 self.with_parent(stmt.hir_id, |this| {
478 intravisit::walk_stmt(this, stmt);
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));
486 intravisit::walk_path_segment(self, path_span, path_segment);
489 fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
490 self.insert(ty.span, ty.hir_id, Node::Ty(ty));
492 self.with_parent(ty.hir_id, |this| {
493 intravisit::walk_ty(this, ty);
497 fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
498 self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
500 self.with_parent(tr.hir_ref_id, |this| {
501 intravisit::walk_trait_ref(this, tr);
507 fk: intravisit::FnKind<'hir>,
508 fd: &'hir FnDecl<'hir>,
513 assert_eq!(self.parent_node, id);
514 intravisit::walk_fn(self, fk, fd, b, s, id);
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);
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))
529 fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
530 self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime));
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);
545 fn visit_macro_def(&mut self, macro_def: &'hir MacroDef<'hir>) {
546 let node_id = self.hir_to_node_id[¯o_def.hir_id];
547 let def_index = self.definitions.opt_def_index(node_id).unwrap();
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));
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));
561 intravisit::walk_variant(this, v, g, item_id);
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);
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;
577 self.visit_nested_trait_item(id);
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;
585 self.visit_nested_impl_item(id);
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> {
596 impl<'hir, T> HashStable<StableHashingContext<'hir>> for HirItemLike<T>
598 T: HashStable<StableHashingContext<'hir>>,
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);