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;
7 use middle::cstore::CrateStore;
8 use session::CrateDisambiguator;
10 use syntax::ast::{NodeId, CRATE_NODE_ID};
11 use syntax::source_map::SourceMap;
14 use ich::StableHashingContext;
15 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
17 /// A Visitor that walks over the HIR and collects Nodes into a HIR map
18 pub(super) struct NodeCollector<'a, 'hir> {
23 source_map: &'a SourceMap,
26 map: Vec<Option<Entry<'hir>>>,
27 /// The parent of this node
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,
37 dep_graph: &'a DepGraph,
38 definitions: &'a definitions::Definitions,
40 hcx: StableHashingContext<'a>,
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)>,
47 fn input_dep_node_and_hash<'a, I>(
49 hcx: &mut StableHashingContext<'a>,
52 ) -> (DepNodeIndex, Fingerprint)
54 I: HashStable<StableHashingContext<'a>>,
56 let dep_node_index = dep_graph.input_task(def_node, &mut *hcx, &input).1;
58 let hash = if dep_graph.is_fully_enabled() {
59 dep_graph.fingerprint_of(dep_node_index)
61 let mut stable_hasher = StableHasher::new();
62 input.hash_stable(hcx, &mut stable_hasher);
63 stable_hasher.finish()
66 (dep_node_index, hash)
69 fn hir_dep_nodes<'a, I>(
71 hcx: &mut StableHashingContext<'a>,
72 def_path_hash: DefPathHash,
74 hir_body_nodes: &mut Vec<(DefPathHash, Fingerprint)>,
75 ) -> (DepNodeIndex, DepNodeIndex)
77 I: HashStable<StableHashingContext<'a>>,
79 let sig = dep_graph.input_task(
80 def_path_hash.to_dep_node(DepKind::Hir),
82 HirItemLike { item_like: &item_like, hash_bodies: false },
84 let (full, hash) = input_dep_node_and_hash(
87 def_path_hash.to_dep_node(DepKind::HirBody),
88 HirItemLike { item_like: &item_like, hash_bodies: true },
90 hir_body_nodes.push((def_path_hash, hash));
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);
103 let mut hir_body_nodes = Vec::new();
105 // Allocate DepNodes for the root module
106 let (root_mod_sig_dep_index, root_mod_full_dep_index) = {
109 // Crate attributes are not copied over to the root `Mod`, so hash
110 // them explicitly here.
113 // These fields are handled separately:
127 root_mod_def_path_hash,
128 (module, attrs, span),
134 dep_graph.input_task(
135 DepNode::new_no_params(DepKind::AllLocalTraitImpls),
141 let mut collector = NodeCollector {
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,
155 collector.insert_entry(CRATE_NODE_ID, Entry {
156 parent: CRATE_NODE_ID,
157 dep_node: root_mod_sig_dep_index,
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)
170 self.hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
172 let node_hashes = self
175 .fold(Fingerprint::ZERO, |fingerprint, &(def_path_hash, hash)| {
177 def_path_hash.0.combine(hash)
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)
188 upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name, dis));
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
199 .filter(|source_file| CrateNum::from_u32(source_file.crate_of_origin) == LOCAL_CRATE)
200 .map(|source_file| source_file.name_hash)
203 source_file_names.sort_unstable();
205 let crate_hash_input = (
206 ((node_hashes, upstream_crates), source_file_names),
207 (commandline_args_hash, crate_disambiguator.to_fingerprint())
210 let (_, crate_hash) = input_dep_node_and_hash(
213 DepNode::new_no_params(DepKind::Krate),
217 let svh = Svh::new(crate_hash.to_smaller_hash());
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));
227 self.map[id.as_usize()] = Some(entry);
230 fn insert(&mut self, span: Span, id: NodeId, node: Node<'hir>) {
232 parent: self.parent_node,
233 dep_node: if self.currently_in_body {
234 self.current_full_dep_index
236 self.current_signature_dep_index
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);
246 if hir_id.owner != self.current_dep_node_owner {
247 let node_str = match self.definitions.opt_def_index(id) {
249 self.definitions.def_path(def_index).to_string_no_crate()
251 None => format!("{:?}", node)
254 let forgot_str = if hir_id == ::hir::DUMMY_HIR_ID {
255 format!("\nMaybe you forgot to lower the node id {:?}?", id)
262 "inconsistent DepNode at `{:?}` for `{}`: \
263 current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?}){}",
264 self.source_map.span_to_string(span),
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(),
277 self.insert_entry(id, entry);
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;
284 self.parent_node = parent_node;
287 fn with_dep_node_owner<T: HashStable<StableHashingContext<'a>>,
288 F: FnOnce(&mut Self)>(&mut self,
289 dep_node_owner: DefIndex,
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;
297 let def_path_hash = self.definitions.def_path_hash(dep_node_owner);
299 let (signature_dep_index, full_dep_index) = hir_dep_nodes(
304 &mut self.hir_body_nodes,
306 self.current_signature_dep_index = signature_dep_index;
307 self.current_full_dep_index = full_dep_index;
309 self.current_dep_node_owner = dep_node_owner;
310 self.currently_in_body = false;
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;
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.
324 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
325 panic!("visit_nested_xxx must be manually implemented in this visitor")
328 fn visit_nested_item(&mut self, item: ItemId) {
329 debug!("visit_nested_item: {:?}", item);
330 self.visit_item(self.krate.item(item.id));
333 fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
334 self.visit_trait_item(self.krate.trait_item(item_id));
337 fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
338 self.visit_impl_item(self.krate.impl_item(item_id));
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;
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));
361 intravisit::walk_item(this, i);
366 fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem) {
367 self.insert(foreign_item.span, foreign_item.id, Node::ForeignItem(foreign_item));
369 self.with_parent(foreign_item.id, |this| {
370 intravisit::walk_foreign_item(this, foreign_item);
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);
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));
385 this.with_parent(ti.id, |this| {
386 intravisit::walk_trait_item(this, ti);
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));
397 this.with_parent(ii.id, |this| {
398 intravisit::walk_impl_item(this, ii);
403 fn visit_pat(&mut self, pat: &'hir Pat) {
404 let node = if let PatKind::Binding(..) = pat.node {
409 self.insert(pat.span, pat.id, node);
411 self.with_parent(pat.id, |this| {
412 intravisit::walk_pat(this, pat);
416 fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
417 self.insert(DUMMY_SP, constant.id, Node::AnonConst(constant));
419 self.with_parent(constant.id, |this| {
420 intravisit::walk_anon_const(this, constant);
424 fn visit_expr(&mut self, expr: &'hir Expr) {
425 self.insert(expr.span, expr.id, Node::Expr(expr));
427 self.with_parent(expr.id, |this| {
428 intravisit::walk_expr(this, expr);
432 fn visit_stmt(&mut self, stmt: &'hir Stmt) {
433 let id = stmt.node.id();
434 self.insert(stmt.span, id, Node::Stmt(stmt));
436 self.with_parent(id, |this| {
437 intravisit::walk_stmt(this, stmt);
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));
445 intravisit::walk_path_segment(self, path_span, path_segment);
448 fn visit_ty(&mut self, ty: &'hir Ty) {
449 self.insert(ty.span, ty.id, Node::Ty(ty));
451 self.with_parent(ty.id, |this| {
452 intravisit::walk_ty(this, ty);
456 fn visit_trait_ref(&mut self, tr: &'hir TraitRef) {
457 self.insert(tr.path.span, tr.ref_id, Node::TraitRef(tr));
459 self.with_parent(tr.ref_id, |this| {
460 intravisit::walk_trait_ref(this, tr);
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);
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);
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)
484 fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
485 self.insert(lifetime.span, lifetime.id, Node::Lifetime(lifetime));
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);
502 fn visit_macro_def(&mut self, macro_def: &'hir MacroDef) {
503 let def_index = self.definitions.opt_def_index(macro_def.id).unwrap();
505 self.with_dep_node_owner(def_index, macro_def, |this| {
506 this.insert(macro_def.span, macro_def.id, Node::MacroDef(macro_def));
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);
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);
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.
536 self.visit_nested_trait_item(id);
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.
551 self.visit_nested_impl_item(id);
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> {
562 impl<'a, 'hir, T> HashStable<StableHashingContext<'hir>> for HirItemLike<T>
563 where T: HashStable<StableHashingContext<'hir>>
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);