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