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