]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/assert_dep_graph.rs
Auto merge of #67312 - cuviper:clone-box-slice, r=SimonSapin
[rust.git] / src / librustc_incremental / assert_dep_graph.rs
1 //! This pass is only used for the UNIT TESTS and DEBUGGING NEEDS
2 //! around dependency graph construction. It serves two purposes; it
3 //! will dump graphs in graphviz form to disk, and it searches for
4 //! `#[rustc_if_this_changed]` and `#[rustc_then_this_would_need]`
5 //! annotations. These annotations can be used to test whether paths
6 //! exist in the graph. These checks run after codegen, so they view the
7 //! the final state of the dependency graph. Note that there are
8 //! similar assertions found in `persist::dirty_clean` which check the
9 //! **initial** state of the dependency graph, just after it has been
10 //! loaded from disk.
11 //!
12 //! In this code, we report errors on each `rustc_if_this_changed`
13 //! annotation. If a path exists in all cases, then we would report
14 //! "all path(s) exist". Otherwise, we report: "no path to `foo`" for
15 //! each case where no path exists. `compile-fail` tests can then be
16 //! used to check when paths exist or do not.
17 //!
18 //! The full form of the `rustc_if_this_changed` annotation is
19 //! `#[rustc_if_this_changed("foo")]`, which will report a
20 //! source node of `foo(def_id)`. The `"foo"` is optional and
21 //! defaults to `"Hir"` if omitted.
22 //!
23 //! Example:
24 //!
25 //! ```
26 //! #[rustc_if_this_changed(Hir)]
27 //! fn foo() { }
28 //!
29 //! #[rustc_then_this_would_need(codegen)] //~ ERROR no path from `foo`
30 //! fn bar() { }
31 //!
32 //! #[rustc_then_this_would_need(codegen)] //~ ERROR OK
33 //! fn baz() { foo(); }
34 //! ```
35
36 use graphviz as dot;
37 use rustc::dep_graph::debug::{DepNodeFilter, EdgeFilter};
38 use rustc::dep_graph::{DepGraphQuery, DepKind, DepNode};
39 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
40 use rustc::ty::TyCtxt;
41 use rustc_data_structures::fx::FxHashSet;
42 use rustc_data_structures::graph::implementation::{Direction, NodeIndex, INCOMING, OUTGOING};
43 use rustc_hir as hir;
44 use rustc_hir::def_id::DefId;
45 use rustc_span::symbol::sym;
46 use rustc_span::Span;
47 use syntax::ast;
48
49 use std::env;
50 use std::fs::{self, File};
51 use std::io::Write;
52
53 pub fn assert_dep_graph(tcx: TyCtxt<'_>) {
54     tcx.dep_graph.with_ignore(|| {
55         if tcx.sess.opts.debugging_opts.dump_dep_graph {
56             dump_graph(tcx);
57         }
58
59         // if the `rustc_attrs` feature is not enabled, then the
60         // attributes we are interested in cannot be present anyway, so
61         // skip the walk.
62         if !tcx.features().rustc_attrs {
63             return;
64         }
65
66         // Find annotations supplied by user (if any).
67         let (if_this_changed, then_this_would_need) = {
68             let mut visitor =
69                 IfThisChanged { tcx, if_this_changed: vec![], then_this_would_need: vec![] };
70             visitor.process_attrs(hir::CRATE_HIR_ID, &tcx.hir().krate().attrs);
71             tcx.hir().krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
72             (visitor.if_this_changed, visitor.then_this_would_need)
73         };
74
75         if !if_this_changed.is_empty() || !then_this_would_need.is_empty() {
76             assert!(
77                 tcx.sess.opts.debugging_opts.query_dep_graph,
78                 "cannot use the `#[{}]` or `#[{}]` annotations \
79                     without supplying `-Z query-dep-graph`",
80                 sym::rustc_if_this_changed,
81                 sym::rustc_then_this_would_need
82             );
83         }
84
85         // Check paths.
86         check_paths(tcx, &if_this_changed, &then_this_would_need);
87     })
88 }
89
90 type Sources = Vec<(Span, DefId, DepNode)>;
91 type Targets = Vec<(Span, ast::Name, hir::HirId, DepNode)>;
92
93 struct IfThisChanged<'tcx> {
94     tcx: TyCtxt<'tcx>,
95     if_this_changed: Sources,
96     then_this_would_need: Targets,
97 }
98
99 impl IfThisChanged<'tcx> {
100     fn argument(&self, attr: &ast::Attribute) -> Option<ast::Name> {
101         let mut value = None;
102         for list_item in attr.meta_item_list().unwrap_or_default() {
103             match list_item.ident() {
104                 Some(ident) if list_item.is_word() && value.is_none() => value = Some(ident.name),
105                 _ =>
106                 // FIXME better-encapsulate meta_item (don't directly access `node`)
107                 {
108                     span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item)
109                 }
110             }
111         }
112         value
113     }
114
115     fn process_attrs(&mut self, hir_id: hir::HirId, attrs: &[ast::Attribute]) {
116         let def_id = self.tcx.hir().local_def_id(hir_id);
117         let def_path_hash = self.tcx.def_path_hash(def_id);
118         for attr in attrs {
119             if attr.check_name(sym::rustc_if_this_changed) {
120                 let dep_node_interned = self.argument(attr);
121                 let dep_node = match dep_node_interned {
122                     None => def_path_hash.to_dep_node(DepKind::Hir),
123                     Some(n) => match DepNode::from_label_string(&n.as_str(), def_path_hash) {
124                         Ok(n) => n,
125                         Err(()) => {
126                             self.tcx.sess.span_fatal(
127                                 attr.span,
128                                 &format!("unrecognized DepNode variant {:?}", n),
129                             );
130                         }
131                     },
132                 };
133                 self.if_this_changed.push((attr.span, def_id, dep_node));
134             } else if attr.check_name(sym::rustc_then_this_would_need) {
135                 let dep_node_interned = self.argument(attr);
136                 let dep_node = match dep_node_interned {
137                     Some(n) => match DepNode::from_label_string(&n.as_str(), def_path_hash) {
138                         Ok(n) => n,
139                         Err(()) => {
140                             self.tcx.sess.span_fatal(
141                                 attr.span,
142                                 &format!("unrecognized DepNode variant {:?}", n),
143                             );
144                         }
145                     },
146                     None => {
147                         self.tcx.sess.span_fatal(attr.span, "missing DepNode variant");
148                     }
149                 };
150                 self.then_this_would_need.push((
151                     attr.span,
152                     dep_node_interned.unwrap(),
153                     hir_id,
154                     dep_node,
155                 ));
156             }
157         }
158     }
159 }
160
161 impl Visitor<'tcx> for IfThisChanged<'tcx> {
162     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
163         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
164     }
165
166     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
167         self.process_attrs(item.hir_id, &item.attrs);
168         intravisit::walk_item(self, item);
169     }
170
171     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
172         self.process_attrs(trait_item.hir_id, &trait_item.attrs);
173         intravisit::walk_trait_item(self, trait_item);
174     }
175
176     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
177         self.process_attrs(impl_item.hir_id, &impl_item.attrs);
178         intravisit::walk_impl_item(self, impl_item);
179     }
180
181     fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
182         self.process_attrs(s.hir_id, &s.attrs);
183         intravisit::walk_struct_field(self, s);
184     }
185 }
186
187 fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_would_need: &Targets) {
188     // Return early here so as not to construct the query, which is not cheap.
189     if if_this_changed.is_empty() {
190         for &(target_span, _, _, _) in then_this_would_need {
191             tcx.sess.span_err(target_span, "no `#[rustc_if_this_changed]` annotation detected");
192         }
193         return;
194     }
195     let query = tcx.dep_graph.query();
196     for &(_, source_def_id, ref source_dep_node) in if_this_changed {
197         let dependents = query.transitive_predecessors(source_dep_node);
198         for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
199             if !dependents.contains(&target_dep_node) {
200                 tcx.sess.span_err(
201                     target_span,
202                     &format!(
203                         "no path from `{}` to `{}`",
204                         tcx.def_path_str(source_def_id),
205                         target_pass
206                     ),
207                 );
208             } else {
209                 tcx.sess.span_err(target_span, "OK");
210             }
211         }
212     }
213 }
214
215 fn dump_graph(tcx: TyCtxt<'_>) {
216     let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
217     let query = tcx.dep_graph.query();
218
219     let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
220         Ok(string) => {
221             // Expect one of: "-> target", "source -> target", or "source ->".
222             let edge_filter =
223                 EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e));
224             let sources = node_set(&query, &edge_filter.source);
225             let targets = node_set(&query, &edge_filter.target);
226             filter_nodes(&query, &sources, &targets)
227         }
228         Err(_) => query.nodes().into_iter().collect(),
229     };
230     let edges = filter_edges(&query, &nodes);
231
232     {
233         // dump a .txt file with just the edges:
234         let txt_path = format!("{}.txt", path);
235         let mut file = File::create(&txt_path).unwrap();
236         for &(ref source, ref target) in &edges {
237             write!(file, "{:?} -> {:?}\n", source, target).unwrap();
238         }
239     }
240
241     {
242         // dump a .dot file in graphviz format:
243         let dot_path = format!("{}.dot", path);
244         let mut v = Vec::new();
245         dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
246         fs::write(dot_path, v).unwrap();
247     }
248 }
249
250 pub struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode>, Vec<(&'q DepNode, &'q DepNode)>);
251
252 impl<'a, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> {
253     type Node = &'q DepNode;
254     type Edge = (&'q DepNode, &'q DepNode);
255     fn nodes(&self) -> dot::Nodes<'_, &'q DepNode> {
256         let nodes: Vec<_> = self.0.iter().cloned().collect();
257         nodes.into()
258     }
259     fn edges(&self) -> dot::Edges<'_, (&'q DepNode, &'q DepNode)> {
260         self.1[..].into()
261     }
262     fn source(&self, edge: &(&'q DepNode, &'q DepNode)) -> &'q DepNode {
263         edge.0
264     }
265     fn target(&self, edge: &(&'q DepNode, &'q DepNode)) -> &'q DepNode {
266         edge.1
267     }
268 }
269
270 impl<'a, 'q> dot::Labeller<'a> for GraphvizDepGraph<'q> {
271     type Node = &'q DepNode;
272     type Edge = (&'q DepNode, &'q DepNode);
273     fn graph_id(&self) -> dot::Id<'_> {
274         dot::Id::new("DependencyGraph").unwrap()
275     }
276     fn node_id(&self, n: &&'q DepNode) -> dot::Id<'_> {
277         let s: String = format!("{:?}", n)
278             .chars()
279             .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
280             .collect();
281         debug!("n={:?} s={:?}", n, s);
282         dot::Id::new(s).unwrap()
283     }
284     fn node_label(&self, n: &&'q DepNode) -> dot::LabelText<'_> {
285         dot::LabelText::label(format!("{:?}", n))
286     }
287 }
288
289 // Given an optional filter like `"x,y,z"`, returns either `None` (no
290 // filter) or the set of nodes whose labels contain all of those
291 // substrings.
292 fn node_set<'q>(
293     query: &'q DepGraphQuery,
294     filter: &DepNodeFilter,
295 ) -> Option<FxHashSet<&'q DepNode>> {
296     debug!("node_set(filter={:?})", filter);
297
298     if filter.accepts_all() {
299         return None;
300     }
301
302     Some(query.nodes().into_iter().filter(|n| filter.test(n)).collect())
303 }
304
305 fn filter_nodes<'q>(
306     query: &'q DepGraphQuery,
307     sources: &Option<FxHashSet<&'q DepNode>>,
308     targets: &Option<FxHashSet<&'q DepNode>>,
309 ) -> FxHashSet<&'q DepNode> {
310     if let &Some(ref sources) = sources {
311         if let &Some(ref targets) = targets {
312             walk_between(query, sources, targets)
313         } else {
314             walk_nodes(query, sources, OUTGOING)
315         }
316     } else if let &Some(ref targets) = targets {
317         walk_nodes(query, targets, INCOMING)
318     } else {
319         query.nodes().into_iter().collect()
320     }
321 }
322
323 fn walk_nodes<'q>(
324     query: &'q DepGraphQuery,
325     starts: &FxHashSet<&'q DepNode>,
326     direction: Direction,
327 ) -> FxHashSet<&'q DepNode> {
328     let mut set = FxHashSet::default();
329     for &start in starts {
330         debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
331         if set.insert(start) {
332             let mut stack = vec![query.indices[start]];
333             while let Some(index) = stack.pop() {
334                 for (_, edge) in query.graph.adjacent_edges(index, direction) {
335                     let neighbor_index = edge.source_or_target(direction);
336                     let neighbor = query.graph.node_data(neighbor_index);
337                     if set.insert(neighbor) {
338                         stack.push(neighbor_index);
339                     }
340                 }
341             }
342         }
343     }
344     set
345 }
346
347 fn walk_between<'q>(
348     query: &'q DepGraphQuery,
349     sources: &FxHashSet<&'q DepNode>,
350     targets: &FxHashSet<&'q DepNode>,
351 ) -> FxHashSet<&'q DepNode> {
352     // This is a bit tricky. We want to include a node only if it is:
353     // (a) reachable from a source and (b) will reach a target. And we
354     // have to be careful about cycles etc.  Luckily efficiency is not
355     // a big concern!
356
357     #[derive(Copy, Clone, PartialEq)]
358     enum State {
359         Undecided,
360         Deciding,
361         Included,
362         Excluded,
363     }
364
365     let mut node_states = vec![State::Undecided; query.graph.len_nodes()];
366
367     for &target in targets {
368         node_states[query.indices[target].0] = State::Included;
369     }
370
371     for source in sources.iter().map(|&n| query.indices[n]) {
372         recurse(query, &mut node_states, source);
373     }
374
375     return query
376         .nodes()
377         .into_iter()
378         .filter(|&n| {
379             let index = query.indices[n];
380             node_states[index.0] == State::Included
381         })
382         .collect();
383
384     fn recurse(query: &DepGraphQuery, node_states: &mut [State], node: NodeIndex) -> bool {
385         match node_states[node.0] {
386             // known to reach a target
387             State::Included => return true,
388
389             // known not to reach a target
390             State::Excluded => return false,
391
392             // backedge, not yet known, say false
393             State::Deciding => return false,
394
395             State::Undecided => {}
396         }
397
398         node_states[node.0] = State::Deciding;
399
400         for neighbor_index in query.graph.successor_nodes(node) {
401             if recurse(query, node_states, neighbor_index) {
402                 node_states[node.0] = State::Included;
403             }
404         }
405
406         // if we didn't find a path to target, then set to excluded
407         if node_states[node.0] == State::Deciding {
408             node_states[node.0] = State::Excluded;
409             false
410         } else {
411             assert!(node_states[node.0] == State::Included);
412             true
413         }
414     }
415 }
416
417 fn filter_edges<'q>(
418     query: &'q DepGraphQuery,
419     nodes: &FxHashSet<&'q DepNode>,
420 ) -> Vec<(&'q DepNode, &'q DepNode)> {
421     query
422         .edges()
423         .into_iter()
424         .filter(|&(source, target)| nodes.contains(source) && nodes.contains(target))
425         .collect()
426 }