]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/collector.rs
Rollup merge of #82260 - ojeda:rustc-argfile, r=jyn514
[rust.git] / compiler / rustc_middle / src / hir / map / collector.rs
1 use crate::arena::Arena;
2 use crate::hir::map::{Entry, HirOwnerData, Map};
3 use crate::hir::{Owner, OwnerNodes, ParentedNode};
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::{LocalDefId, LOCAL_CRATE};
13 use rustc_hir::definitions::{self, DefPathHash};
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::*;
16 use rustc_index::vec::{Idx, IndexVec};
17 use rustc_session::{CrateDisambiguator, Session};
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::{Span, Symbol, DUMMY_SP};
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     arena: &'hir Arena<'hir>,
26
27     /// The crate
28     krate: &'hir Crate<'hir>,
29
30     /// Source map
31     source_map: &'a SourceMap,
32
33     map: IndexVec<LocalDefId, HirOwnerData<'hir>>,
34
35     /// The parent of this node
36     parent_node: hir::HirId,
37
38     current_dep_node_owner: LocalDefId,
39
40     definitions: &'a definitions::Definitions,
41
42     hcx: StableHashingContext<'a>,
43
44     // We are collecting HIR hashes here so we can compute the
45     // crate hash from them later on.
46     hir_body_nodes: Vec<(DefPathHash, Fingerprint)>,
47 }
48
49 fn insert_vec_map<K: Idx, V: Clone>(map: &mut IndexVec<K, Option<V>>, k: K, v: V) {
50     let i = k.index();
51     let len = map.len();
52     if i >= len {
53         map.extend(repeat(None).take(i - len + 1));
54     }
55     map[k] = Some(v);
56 }
57
58 fn hash_body(
59     hcx: &mut StableHashingContext<'_>,
60     def_path_hash: DefPathHash,
61     item_like: impl for<'a> HashStable<StableHashingContext<'a>>,
62     hir_body_nodes: &mut Vec<(DefPathHash, Fingerprint)>,
63 ) -> Fingerprint {
64     let hash = {
65         let mut stable_hasher = StableHasher::new();
66         hcx.while_hashing_hir_bodies(true, |hcx| {
67             item_like.hash_stable(hcx, &mut stable_hasher);
68         });
69         stable_hasher.finish()
70     };
71     hir_body_nodes.push((def_path_hash, hash));
72     hash
73 }
74
75 fn upstream_crates(cstore: &dyn CrateStore) -> Vec<(Symbol, Fingerprint, Svh)> {
76     let mut upstream_crates: Vec<_> = cstore
77         .crates_untracked()
78         .iter()
79         .map(|&cnum| {
80             let name = cstore.crate_name_untracked(cnum);
81             let disambiguator = cstore.crate_disambiguator_untracked(cnum).to_fingerprint();
82             let hash = cstore.crate_hash_untracked(cnum);
83             (name, disambiguator, hash)
84         })
85         .collect();
86     upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name.as_str(), dis));
87     upstream_crates
88 }
89
90 impl<'a, 'hir> NodeCollector<'a, 'hir> {
91     pub(super) fn root(
92         sess: &'a Session,
93         arena: &'hir Arena<'hir>,
94         krate: &'hir Crate<'hir>,
95         definitions: &'a definitions::Definitions,
96         mut hcx: StableHashingContext<'a>,
97     ) -> NodeCollector<'a, 'hir> {
98         let root_mod_def_path_hash =
99             definitions.def_path_hash(LocalDefId { local_def_index: CRATE_DEF_INDEX });
100
101         let mut hir_body_nodes = Vec::new();
102
103         let hash = {
104             let Crate {
105                 ref item,
106                 // These fields are handled separately:
107                 exported_macros: _,
108                 non_exported_macro_attrs: _,
109                 items: _,
110                 trait_items: _,
111                 impl_items: _,
112                 foreign_items: _,
113                 bodies: _,
114                 trait_impls: _,
115                 body_ids: _,
116                 modules: _,
117                 proc_macros: _,
118                 trait_map: _,
119             } = *krate;
120
121             hash_body(&mut hcx, root_mod_def_path_hash, item, &mut hir_body_nodes)
122         };
123
124         let mut collector = NodeCollector {
125             arena,
126             krate,
127             source_map: sess.source_map(),
128             parent_node: hir::CRATE_HIR_ID,
129             current_dep_node_owner: LocalDefId { local_def_index: CRATE_DEF_INDEX },
130             definitions,
131             hcx,
132             hir_body_nodes,
133             map: (0..definitions.def_index_count())
134                 .map(|_| HirOwnerData { signature: None, with_bodies: None })
135                 .collect(),
136         };
137         collector.insert_entry(
138             hir::CRATE_HIR_ID,
139             Entry { parent: hir::CRATE_HIR_ID, node: Node::Crate(&krate.item) },
140             hash,
141         );
142
143         collector
144     }
145
146     pub(super) fn finalize_and_compute_crate_hash(
147         mut self,
148         crate_disambiguator: CrateDisambiguator,
149         cstore: &dyn CrateStore,
150         commandline_args_hash: u64,
151     ) -> (IndexVec<LocalDefId, HirOwnerData<'hir>>, Svh) {
152         // Insert bodies into the map
153         for (id, body) in self.krate.bodies.iter() {
154             let bodies = &mut self.map[id.hir_id.owner].with_bodies.as_mut().unwrap().bodies;
155             assert!(bodies.insert(id.hir_id.local_id, body).is_none());
156         }
157
158         self.hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
159
160         let node_hashes = self.hir_body_nodes.iter().fold(
161             Fingerprint::ZERO,
162             |combined_fingerprint, &(def_path_hash, fingerprint)| {
163                 combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
164             },
165         );
166
167         let upstream_crates = upstream_crates(cstore);
168
169         // We hash the final, remapped names of all local source files so we
170         // don't have to include the path prefix remapping commandline args.
171         // If we included the full mapping in the SVH, we could only have
172         // reproducible builds by compiling from the same directory. So we just
173         // hash the result of the mapping instead of the mapping itself.
174         let mut source_file_names: Vec<_> = self
175             .source_map
176             .files()
177             .iter()
178             .filter(|source_file| source_file.cnum == LOCAL_CRATE)
179             .map(|source_file| source_file.name_hash)
180             .collect();
181
182         source_file_names.sort_unstable();
183
184         let crate_hash_input = (
185             ((node_hashes, upstream_crates), source_file_names),
186             (commandline_args_hash, crate_disambiguator.to_fingerprint()),
187         );
188
189         let mut stable_hasher = StableHasher::new();
190         crate_hash_input.hash_stable(&mut self.hcx, &mut stable_hasher);
191         let crate_hash: Fingerprint = stable_hasher.finish();
192
193         let svh = Svh::new(crate_hash.to_smaller_hash());
194         (self.map, svh)
195     }
196
197     fn insert_entry(&mut self, id: HirId, entry: Entry<'hir>, hash: Fingerprint) {
198         let i = id.local_id.as_u32() as usize;
199
200         let arena = self.arena;
201
202         let data = &mut self.map[id.owner];
203
204         if data.with_bodies.is_none() {
205             data.with_bodies = Some(arena.alloc(OwnerNodes {
206                 hash,
207                 nodes: IndexVec::new(),
208                 bodies: FxHashMap::default(),
209             }));
210         }
211
212         let nodes = data.with_bodies.as_mut().unwrap();
213
214         if i == 0 {
215             // Overwrite the dummy hash with the real HIR owner hash.
216             nodes.hash = hash;
217
218             // FIXME: feature(impl_trait_in_bindings) broken and trigger this assert
219             //assert!(data.signature.is_none());
220
221             data.signature =
222                 Some(self.arena.alloc(Owner { parent: entry.parent, node: entry.node }));
223         } else {
224             assert_eq!(entry.parent.owner, id.owner);
225             insert_vec_map(
226                 &mut nodes.nodes,
227                 id.local_id,
228                 ParentedNode { parent: entry.parent.local_id, node: entry.node },
229             );
230         }
231     }
232
233     fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
234         self.insert_with_hash(span, hir_id, node, Fingerprint::ZERO)
235     }
236
237     fn insert_with_hash(&mut self, span: Span, hir_id: HirId, node: Node<'hir>, hash: Fingerprint) {
238         let entry = Entry { parent: self.parent_node, node };
239
240         // Make sure that the DepNode of some node coincides with the HirId
241         // owner of that node.
242         if cfg!(debug_assertions) {
243             if hir_id.owner != self.current_dep_node_owner {
244                 let node_str = match self.definitions.opt_hir_id_to_local_def_id(hir_id) {
245                     Some(def_id) => self.definitions.def_path(def_id).to_string_no_crate_verbose(),
246                     None => format!("{:?}", node),
247                 };
248
249                 span_bug!(
250                     span,
251                     "inconsistent DepNode at `{:?}` for `{}`: \
252                      current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
253                     self.source_map.span_to_string(span),
254                     node_str,
255                     self.definitions
256                         .def_path(self.current_dep_node_owner)
257                         .to_string_no_crate_verbose(),
258                     self.current_dep_node_owner,
259                     self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(),
260                     hir_id.owner,
261                 )
262             }
263         }
264
265         self.insert_entry(hir_id, entry, hash);
266     }
267
268     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_node_id: HirId, f: F) {
269         let parent_node = self.parent_node;
270         self.parent_node = parent_node_id;
271         f(self);
272         self.parent_node = parent_node;
273     }
274
275     fn with_dep_node_owner<
276         T: for<'b> HashStable<StableHashingContext<'b>>,
277         F: FnOnce(&mut Self, Fingerprint),
278     >(
279         &mut self,
280         dep_node_owner: LocalDefId,
281         item_like: &T,
282         f: F,
283     ) {
284         let prev_owner = self.current_dep_node_owner;
285
286         let def_path_hash = self.definitions.def_path_hash(dep_node_owner);
287
288         let hash = hash_body(&mut self.hcx, def_path_hash, item_like, &mut self.hir_body_nodes);
289
290         self.current_dep_node_owner = dep_node_owner;
291         f(self, hash);
292         self.current_dep_node_owner = prev_owner;
293     }
294 }
295
296 impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
297     type Map = Map<'hir>;
298
299     /// Because we want to track parent items and so forth, enable
300     /// deep walking so that we walk nested items in the context of
301     /// their outer items.
302
303     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
304         panic!("`visit_nested_xxx` must be manually implemented in this visitor");
305     }
306
307     fn visit_nested_item(&mut self, item: ItemId) {
308         debug!("visit_nested_item: {:?}", item);
309         self.visit_item(self.krate.item(item));
310     }
311
312     fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
313         self.visit_trait_item(self.krate.trait_item(item_id));
314     }
315
316     fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
317         self.visit_impl_item(self.krate.impl_item(item_id));
318     }
319
320     fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) {
321         self.visit_foreign_item(self.krate.foreign_item(foreign_id));
322     }
323
324     fn visit_nested_body(&mut self, id: BodyId) {
325         self.visit_body(self.krate.body(id));
326     }
327
328     fn visit_param(&mut self, param: &'hir Param<'hir>) {
329         let node = Node::Param(param);
330         self.insert(param.pat.span, param.hir_id, node);
331         self.with_parent(param.hir_id, |this| {
332             intravisit::walk_param(this, param);
333         });
334     }
335
336     fn visit_item(&mut self, i: &'hir Item<'hir>) {
337         debug!("visit_item: {:?}", i);
338         self.with_dep_node_owner(i.def_id, i, |this, hash| {
339             let hir_id = i.hir_id();
340             this.insert_with_hash(i.span, hir_id, Node::Item(i), hash);
341             this.with_parent(hir_id, |this| {
342                 if let ItemKind::Struct(ref struct_def, _) = i.kind {
343                     // If this is a tuple or unit-like struct, register the constructor.
344                     if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
345                         this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def));
346                     }
347                 }
348                 intravisit::walk_item(this, i);
349             });
350         });
351     }
352
353     fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) {
354         self.with_dep_node_owner(fi.def_id, fi, |this, hash| {
355             this.insert_with_hash(fi.span, fi.hir_id(), Node::ForeignItem(fi), hash);
356
357             this.with_parent(fi.hir_id(), |this| {
358                 intravisit::walk_foreign_item(this, fi);
359             });
360         });
361     }
362
363     fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) {
364         if let hir::GenericParamKind::Type {
365             synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
366             ..
367         } = param.kind
368         {
369             debug_assert_eq!(
370                 param.hir_id.owner,
371                 self.definitions.opt_hir_id_to_local_def_id(param.hir_id).unwrap()
372             );
373             self.with_dep_node_owner(param.hir_id.owner, param, |this, hash| {
374                 this.insert_with_hash(param.span, param.hir_id, Node::GenericParam(param), hash);
375
376                 this.with_parent(param.hir_id, |this| {
377                     intravisit::walk_generic_param(this, param);
378                 });
379             });
380         } else {
381             self.insert(param.span, param.hir_id, Node::GenericParam(param));
382             intravisit::walk_generic_param(self, param);
383         }
384     }
385
386     fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
387         self.with_dep_node_owner(ti.def_id, ti, |this, hash| {
388             this.insert_with_hash(ti.span, ti.hir_id(), Node::TraitItem(ti), hash);
389
390             this.with_parent(ti.hir_id(), |this| {
391                 intravisit::walk_trait_item(this, ti);
392             });
393         });
394     }
395
396     fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
397         self.with_dep_node_owner(ii.def_id, ii, |this, hash| {
398             this.insert_with_hash(ii.span, ii.hir_id(), Node::ImplItem(ii), hash);
399
400             this.with_parent(ii.hir_id(), |this| {
401                 intravisit::walk_impl_item(this, ii);
402             });
403         });
404     }
405
406     fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
407         let node =
408             if let PatKind::Binding(..) = pat.kind { Node::Binding(pat) } else { Node::Pat(pat) };
409         self.insert(pat.span, pat.hir_id, node);
410
411         self.with_parent(pat.hir_id, |this| {
412             intravisit::walk_pat(this, pat);
413         });
414     }
415
416     fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
417         let node = Node::Arm(arm);
418
419         self.insert(arm.span, arm.hir_id, node);
420
421         self.with_parent(arm.hir_id, |this| {
422             intravisit::walk_arm(this, arm);
423         });
424     }
425
426     fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
427         self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
428
429         self.with_parent(constant.hir_id, |this| {
430             intravisit::walk_anon_const(this, constant);
431         });
432     }
433
434     fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
435         self.insert(expr.span, expr.hir_id, Node::Expr(expr));
436
437         self.with_parent(expr.hir_id, |this| {
438             intravisit::walk_expr(this, expr);
439         });
440     }
441
442     fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
443         self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
444
445         self.with_parent(stmt.hir_id, |this| {
446             intravisit::walk_stmt(this, stmt);
447         });
448     }
449
450     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'hir PathSegment<'hir>) {
451         if let Some(hir_id) = path_segment.hir_id {
452             self.insert(path_span, hir_id, Node::PathSegment(path_segment));
453         }
454         intravisit::walk_path_segment(self, path_span, path_segment);
455     }
456
457     fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
458         self.insert(ty.span, ty.hir_id, Node::Ty(ty));
459
460         self.with_parent(ty.hir_id, |this| {
461             intravisit::walk_ty(this, ty);
462         });
463     }
464
465     fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
466         self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
467
468         self.with_parent(tr.hir_ref_id, |this| {
469             intravisit::walk_trait_ref(this, tr);
470         });
471     }
472
473     fn visit_fn(
474         &mut self,
475         fk: intravisit::FnKind<'hir>,
476         fd: &'hir FnDecl<'hir>,
477         b: BodyId,
478         s: Span,
479         id: HirId,
480     ) {
481         assert_eq!(self.parent_node, id);
482         intravisit::walk_fn(self, fk, fd, b, s, id);
483     }
484
485     fn visit_block(&mut self, block: &'hir Block<'hir>) {
486         self.insert(block.span, block.hir_id, Node::Block(block));
487         self.with_parent(block.hir_id, |this| {
488             intravisit::walk_block(this, block);
489         });
490     }
491
492     fn visit_local(&mut self, l: &'hir Local<'hir>) {
493         self.insert(l.span, l.hir_id, Node::Local(l));
494         self.with_parent(l.hir_id, |this| intravisit::walk_local(this, l))
495     }
496
497     fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
498         self.insert(lifetime.span, lifetime.hir_id, Node::Lifetime(lifetime));
499     }
500
501     fn visit_vis(&mut self, visibility: &'hir Visibility<'hir>) {
502         match visibility.node {
503             VisibilityKind::Public | VisibilityKind::Crate(_) | VisibilityKind::Inherited => {}
504             VisibilityKind::Restricted { hir_id, .. } => {
505                 self.insert(visibility.span, hir_id, Node::Visibility(visibility));
506                 self.with_parent(hir_id, |this| {
507                     intravisit::walk_vis(this, visibility);
508                 });
509             }
510         }
511     }
512
513     fn visit_macro_def(&mut self, macro_def: &'hir MacroDef<'hir>) {
514         // Exported macros are visited directly from the crate root,
515         // so they do not have `parent_node` set.
516         // Find the correct enclosing module from their DefKey.
517         let def_key = self.definitions.def_key(macro_def.def_id);
518         let parent = def_key.parent.map_or(hir::CRATE_HIR_ID, |local_def_index| {
519             self.definitions.local_def_id_to_hir_id(LocalDefId { local_def_index })
520         });
521         self.with_parent(parent, |this| {
522             this.with_dep_node_owner(macro_def.def_id, macro_def, |this, hash| {
523                 this.insert_with_hash(
524                     macro_def.span,
525                     macro_def.hir_id(),
526                     Node::MacroDef(macro_def),
527                     hash,
528                 );
529             })
530         });
531     }
532
533     fn visit_variant(&mut self, v: &'hir Variant<'hir>, g: &'hir Generics<'hir>, item_id: HirId) {
534         self.insert(v.span, v.id, Node::Variant(v));
535         self.with_parent(v.id, |this| {
536             // Register the constructor of this variant.
537             if let Some(ctor_hir_id) = v.data.ctor_hir_id() {
538                 this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data));
539             }
540             intravisit::walk_variant(this, v, g, item_id);
541         });
542     }
543
544     fn visit_struct_field(&mut self, field: &'hir StructField<'hir>) {
545         self.insert(field.span, field.hir_id, Node::Field(field));
546         self.with_parent(field.hir_id, |this| {
547             intravisit::walk_struct_field(this, field);
548         });
549     }
550
551     fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
552         // Do not visit the duplicate information in TraitItemRef. We want to
553         // map the actual nodes, not the duplicate ones in the *Ref.
554         let TraitItemRef { id, ident: _, kind: _, span: _, defaultness: _ } = *ii;
555
556         self.visit_nested_trait_item(id);
557     }
558
559     fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef<'hir>) {
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 { id, ident: _, kind: _, span: _, vis: _, defaultness: _ } = *ii;
563
564         self.visit_nested_impl_item(id);
565     }
566
567     fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef<'hir>) {
568         // Do not visit the duplicate information in ForeignItemRef. We want to
569         // map the actual nodes, not the duplicate ones in the *Ref.
570         let ForeignItemRef { id, ident: _, span: _, vis: _ } = *fi;
571
572         self.visit_nested_foreign_item(id);
573     }
574 }