]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/hir_id_validator.rs
Rollup merge of #89138 - newpavlov:patch-2, r=dtolnay
[rust.git] / compiler / rustc_passes / src / hir_id_validator.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::sync::Lock;
3 use rustc_hir as hir;
4 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_INDEX};
5 use rustc_hir::intravisit;
6 use rustc_hir::itemlikevisit::ItemLikeVisitor;
7 use rustc_hir::{HirId, ItemLocalId};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::ty::TyCtxt;
10
11 pub fn check_crate(tcx: TyCtxt<'_>) {
12     tcx.dep_graph.assert_ignored();
13
14     if tcx.sess.opts.debugging_opts.hir_stats {
15         crate::hir_stats::print_hir_stats(tcx);
16     }
17
18     let errors = Lock::new(Vec::new());
19     let hir_map = tcx.hir();
20
21     hir_map.par_for_each_module(|module_id| {
22         hir_map
23             .visit_item_likes_in_module(module_id, &mut OuterVisitor { hir_map, errors: &errors })
24     });
25
26     let errors = errors.into_inner();
27
28     if !errors.is_empty() {
29         let message = errors.iter().fold(String::new(), |s1, s2| s1 + "\n" + s2);
30         tcx.sess.delay_span_bug(rustc_span::DUMMY_SP, &message);
31     }
32 }
33
34 struct HirIdValidator<'a, 'hir> {
35     hir_map: Map<'hir>,
36     owner: Option<LocalDefId>,
37     hir_ids_seen: FxHashSet<ItemLocalId>,
38     errors: &'a Lock<Vec<String>>,
39 }
40
41 struct OuterVisitor<'a, 'hir> {
42     hir_map: Map<'hir>,
43     errors: &'a Lock<Vec<String>>,
44 }
45
46 impl<'a, 'hir> OuterVisitor<'a, 'hir> {
47     fn new_inner_visitor(&self, hir_map: Map<'hir>) -> HirIdValidator<'a, 'hir> {
48         HirIdValidator {
49             hir_map,
50             owner: None,
51             hir_ids_seen: Default::default(),
52             errors: self.errors,
53         }
54     }
55 }
56
57 impl<'a, 'hir> ItemLikeVisitor<'hir> for OuterVisitor<'a, 'hir> {
58     fn visit_item(&mut self, i: &'hir hir::Item<'hir>) {
59         let mut inner_visitor = self.new_inner_visitor(self.hir_map);
60         inner_visitor.check(i.hir_id(), |this| intravisit::walk_item(this, i));
61     }
62
63     fn visit_trait_item(&mut self, i: &'hir hir::TraitItem<'hir>) {
64         let mut inner_visitor = self.new_inner_visitor(self.hir_map);
65         inner_visitor.check(i.hir_id(), |this| intravisit::walk_trait_item(this, i));
66     }
67
68     fn visit_impl_item(&mut self, i: &'hir hir::ImplItem<'hir>) {
69         let mut inner_visitor = self.new_inner_visitor(self.hir_map);
70         inner_visitor.check(i.hir_id(), |this| intravisit::walk_impl_item(this, i));
71     }
72
73     fn visit_foreign_item(&mut self, i: &'hir hir::ForeignItem<'hir>) {
74         let mut inner_visitor = self.new_inner_visitor(self.hir_map);
75         inner_visitor.check(i.hir_id(), |this| intravisit::walk_foreign_item(this, i));
76     }
77 }
78
79 impl<'a, 'hir> HirIdValidator<'a, 'hir> {
80     #[cold]
81     #[inline(never)]
82     fn error(&self, f: impl FnOnce() -> String) {
83         self.errors.lock().push(f());
84     }
85
86     fn check<F: FnOnce(&mut HirIdValidator<'a, 'hir>)>(&mut self, hir_id: HirId, walk: F) {
87         assert!(self.owner.is_none());
88         let owner = self.hir_map.local_def_id(hir_id);
89         self.owner = Some(owner);
90         walk(self);
91
92         if owner.local_def_index == CRATE_DEF_INDEX {
93             return;
94         }
95
96         // There's always at least one entry for the owning item itself
97         let max = self
98             .hir_ids_seen
99             .iter()
100             .map(|local_id| local_id.as_usize())
101             .max()
102             .expect("owning item has no entry");
103
104         if max != self.hir_ids_seen.len() - 1 {
105             // Collect the missing ItemLocalIds
106             let missing: Vec<_> = (0..=max as u32)
107                 .filter(|&i| !self.hir_ids_seen.contains(&ItemLocalId::from_u32(i)))
108                 .collect();
109
110             // Try to map those to something more useful
111             let mut missing_items = Vec::with_capacity(missing.len());
112
113             for local_id in missing {
114                 let hir_id = HirId { owner, local_id: ItemLocalId::from_u32(local_id) };
115
116                 trace!("missing hir id {:#?}", hir_id);
117
118                 missing_items.push(format!(
119                     "[local_id: {}, owner: {}]",
120                     local_id,
121                     self.hir_map.def_path(owner).to_string_no_crate_verbose()
122                 ));
123             }
124             self.error(|| {
125                 format!(
126                     "ItemLocalIds not assigned densely in {}. \
127                 Max ItemLocalId = {}, missing IDs = {:?}; seens IDs = {:?}",
128                     self.hir_map.def_path(owner).to_string_no_crate_verbose(),
129                     max,
130                     missing_items,
131                     self.hir_ids_seen
132                         .iter()
133                         .map(|&local_id| HirId { owner, local_id })
134                         .map(|h| format!("({:?} {})", h, self.hir_map.node_to_string(h)))
135                         .collect::<Vec<_>>()
136                 )
137             });
138         }
139     }
140 }
141
142 impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
143     type Map = Map<'hir>;
144
145     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
146         intravisit::NestedVisitorMap::OnlyBodies(self.hir_map)
147     }
148
149     fn visit_id(&mut self, hir_id: HirId) {
150         let owner = self.owner.expect("no owner");
151
152         if owner != hir_id.owner {
153             self.error(|| {
154                 format!(
155                     "HirIdValidator: The recorded owner of {} is {} instead of {}",
156                     self.hir_map.node_to_string(hir_id),
157                     self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(),
158                     self.hir_map.def_path(owner).to_string_no_crate_verbose()
159                 )
160             });
161         }
162
163         self.hir_ids_seen.insert(hir_id.local_id);
164     }
165
166     fn visit_impl_item_ref(&mut self, _: &'hir hir::ImplItemRef) {
167         // Explicitly do nothing here. ImplItemRefs contain hir::Visibility
168         // values that actually belong to an ImplItem instead of the ItemKind::Impl
169         // we are currently in. So for those it's correct that they have a
170         // different owner.
171     }
172
173     fn visit_foreign_item_ref(&mut self, _: &'hir hir::ForeignItemRef) {
174         // Explicitly do nothing here. ForeignItemRefs contain hir::Visibility
175         // values that actually belong to an ForeignItem instead of the ItemKind::ForeignMod
176         // we are currently in. So for those it's correct that they have a
177         // different owner.
178     }
179 }