]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/assert_dep_graph.rs
Remove need for &format!(...) or &&"" dances in `span_label` calls
[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 trans, 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(trans)] //~ ERROR no path from `foo`
40 //! fn bar() { }
41 //!
42 //! #[rustc_then_this_would_need(trans)] //~ ERROR OK
43 //! fn baz() { foo(); }
44 //! ```
45
46 use graphviz as dot;
47 use rustc::dep_graph::{DepGraphQuery, DepNode};
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::{Direction, INCOMING, OUTGOING, NodeIndex};
53 use rustc::hir;
54 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
55 use rustc::ich::{ATTR_IF_THIS_CHANGED, ATTR_THEN_THIS_WOULD_NEED};
56 use graphviz::IntoCow;
57 use std::env;
58 use std::fs::File;
59 use std::io::Write;
60 use syntax::ast;
61 use syntax_pos::Span;
62
63 pub fn assert_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
64     let _ignore = tcx.dep_graph.in_ignore();
65
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.sess.features.borrow().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: 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 type Sources = Vec<(Span, DefId, DepNode<DefId>)>;
99 type Targets = Vec<(Span, ast::Name, ast::NodeId, DepNode<DefId>)>;
100
101 struct IfThisChanged<'a, 'tcx:'a> {
102     tcx: TyCtxt<'a, 'tcx, 'tcx>,
103     if_this_changed: Sources,
104     then_this_would_need: Targets,
105 }
106
107 impl<'a, 'tcx> IfThisChanged<'a, 'tcx> {
108     fn argument(&self, attr: &ast::Attribute) -> Option<ast::Name> {
109         let mut value = None;
110         for list_item in attr.meta_item_list().unwrap_or_default() {
111             match list_item.word() {
112                 Some(word) if value.is_none() =>
113                     value = Some(word.name().clone()),
114                 _ =>
115                     // FIXME better-encapsulate meta_item (don't directly access `node`)
116                     span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item.node),
117             }
118         }
119         value
120     }
121
122     fn process_attrs(&mut self, node_id: ast::NodeId, attrs: &[ast::Attribute]) {
123         let def_id = self.tcx.hir.local_def_id(node_id);
124         for attr in attrs {
125             if attr.check_name(ATTR_IF_THIS_CHANGED) {
126                 let dep_node_interned = self.argument(attr);
127                 let dep_node = match dep_node_interned {
128                     None => DepNode::Hir(def_id),
129                     Some(n) => {
130                         match DepNode::from_label_string(&n.as_str(), def_id) {
131                             Ok(n) => n,
132                             Err(()) => {
133                                 self.tcx.sess.span_fatal(
134                                     attr.span,
135                                     &format!("unrecognized DepNode variant {:?}", n));
136                             }
137                         }
138                     }
139                 };
140                 self.if_this_changed.push((attr.span, def_id, dep_node));
141             } else if attr.check_name(ATTR_THEN_THIS_WOULD_NEED) {
142                 let dep_node_interned = self.argument(attr);
143                 let dep_node = match dep_node_interned {
144                     Some(n) => {
145                         match DepNode::from_label_string(&n.as_str(), def_id) {
146                             Ok(n) => n,
147                             Err(()) => {
148                                 self.tcx.sess.span_fatal(
149                                     attr.span,
150                                     &format!("unrecognized DepNode variant {:?}", n));
151                             }
152                         }
153                     }
154                     None => {
155                         self.tcx.sess.span_fatal(
156                             attr.span,
157                             "missing DepNode variant");
158                     }
159                 };
160                 self.then_this_would_need.push((attr.span,
161                                                 dep_node_interned.unwrap(),
162                                                 node_id,
163                                                 dep_node));
164             }
165         }
166     }
167 }
168
169 impl<'a, 'tcx> Visitor<'tcx> for IfThisChanged<'a, 'tcx> {
170     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
171         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
172     }
173
174     fn visit_item(&mut self, item: &'tcx hir::Item) {
175         self.process_attrs(item.id, &item.attrs);
176         intravisit::walk_item(self, item);
177     }
178
179     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
180         self.process_attrs(trait_item.id, &trait_item.attrs);
181         intravisit::walk_trait_item(self, trait_item);
182     }
183
184     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
185         self.process_attrs(impl_item.id, &impl_item.attrs);
186         intravisit::walk_impl_item(self, impl_item);
187     }
188
189     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
190         self.process_attrs(s.id, &s.attrs);
191         intravisit::walk_struct_field(self, s);
192     }
193 }
194
195 fn check_paths<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
196                          if_this_changed: &Sources,
197                          then_this_would_need: &Targets)
198 {
199     // Return early here so as not to construct the query, which is not cheap.
200     if if_this_changed.is_empty() {
201         for &(target_span, _, _, _) in then_this_would_need {
202             tcx.sess.span_err(
203                 target_span,
204                 "no #[rustc_if_this_changed] annotation detected");
205
206         }
207         return;
208     }
209     let query = tcx.dep_graph.query();
210     for &(_, source_def_id, ref source_dep_node) in if_this_changed {
211         let dependents = query.transitive_successors(source_dep_node);
212         for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
213             if !dependents.contains(&target_dep_node) {
214                 tcx.sess.span_err(
215                     target_span,
216                     &format!("no path from `{}` to `{}`",
217                              tcx.item_path_str(source_def_id),
218                              target_pass));
219             } else {
220                 tcx.sess.span_err(
221                     target_span,
222                     "OK");
223             }
224         }
225     }
226 }
227
228 fn dump_graph(tcx: TyCtxt) {
229     let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| format!("dep_graph"));
230     let query = tcx.dep_graph.query();
231
232     let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
233         Ok(string) => {
234             // Expect one of: "-> target", "source -> target", or "source ->".
235             let edge_filter = EdgeFilter::new(&string).unwrap_or_else(|e| {
236                 bug!("invalid filter: {}", e)
237             });
238             let sources = node_set(&query, &edge_filter.source);
239             let targets = node_set(&query, &edge_filter.target);
240             filter_nodes(&query, &sources, &targets)
241         }
242         Err(_) => {
243             query.nodes()
244                  .into_iter()
245                  .collect()
246         }
247     };
248     let edges = filter_edges(&query, &nodes);
249
250     { // dump a .txt file with just the edges:
251         let txt_path = format!("{}.txt", path);
252         let mut file = File::create(&txt_path).unwrap();
253         for &(ref source, ref target) in &edges {
254             write!(file, "{:?} -> {:?}\n", source, target).unwrap();
255         }
256     }
257
258     { // dump a .dot file in graphviz format:
259         let dot_path = format!("{}.dot", path);
260         let mut v = Vec::new();
261         dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
262         File::create(&dot_path).and_then(|mut f| f.write_all(&v)).unwrap();
263     }
264 }
265
266 pub struct GraphvizDepGraph<'q>(FxHashSet<&'q DepNode<DefId>>,
267                                 Vec<(&'q DepNode<DefId>, &'q DepNode<DefId>)>);
268
269 impl<'a, 'tcx, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> {
270     type Node = &'q DepNode<DefId>;
271     type Edge = (&'q DepNode<DefId>, &'q DepNode<DefId>);
272     fn nodes(&self) -> dot::Nodes<&'q DepNode<DefId>> {
273         let nodes: Vec<_> = self.0.iter().cloned().collect();
274         nodes.into_cow()
275     }
276     fn edges(&self) -> dot::Edges<(&'q DepNode<DefId>, &'q DepNode<DefId>)> {
277         self.1[..].into_cow()
278     }
279     fn source(&self, edge: &(&'q DepNode<DefId>, &'q DepNode<DefId>)) -> &'q DepNode<DefId> {
280         edge.0
281     }
282     fn target(&self, edge: &(&'q DepNode<DefId>, &'q DepNode<DefId>)) -> &'q DepNode<DefId> {
283         edge.1
284     }
285 }
286
287 impl<'a, 'tcx, 'q> dot::Labeller<'a> for GraphvizDepGraph<'q> {
288     type Node = &'q DepNode<DefId>;
289     type Edge = (&'q DepNode<DefId>, &'q DepNode<DefId>);
290     fn graph_id(&self) -> dot::Id {
291         dot::Id::new("DependencyGraph").unwrap()
292     }
293     fn node_id(&self, n: &&'q DepNode<DefId>) -> dot::Id {
294         let s: String =
295             format!("{:?}", n).chars()
296                               .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
297                               .collect();
298         debug!("n={:?} s={:?}", n, s);
299         dot::Id::new(s).unwrap()
300     }
301     fn node_label(&self, n: &&'q DepNode<DefId>) -> dot::LabelText {
302         dot::LabelText::label(format!("{:?}", n))
303     }
304 }
305
306 // Given an optional filter like `"x,y,z"`, returns either `None` (no
307 // filter) or the set of nodes whose labels contain all of those
308 // substrings.
309 fn node_set<'q>(query: &'q DepGraphQuery<DefId>, filter: &DepNodeFilter)
310                 -> Option<FxHashSet<&'q DepNode<DefId>>>
311 {
312     debug!("node_set(filter={:?})", filter);
313
314     if filter.accepts_all() {
315         return None;
316     }
317
318     Some(query.nodes().into_iter().filter(|n| filter.test(n)).collect())
319 }
320
321 fn filter_nodes<'q>(query: &'q DepGraphQuery<DefId>,
322                     sources: &Option<FxHashSet<&'q DepNode<DefId>>>,
323                     targets: &Option<FxHashSet<&'q DepNode<DefId>>>)
324                     -> FxHashSet<&'q DepNode<DefId>>
325 {
326     if let &Some(ref sources) = sources {
327         if let &Some(ref targets) = targets {
328             walk_between(query, sources, targets)
329         } else {
330             walk_nodes(query, sources, OUTGOING)
331         }
332     } else if let &Some(ref targets) = targets {
333         walk_nodes(query, targets, INCOMING)
334     } else {
335         query.nodes().into_iter().collect()
336     }
337 }
338
339 fn walk_nodes<'q>(query: &'q DepGraphQuery<DefId>,
340                   starts: &FxHashSet<&'q DepNode<DefId>>,
341                   direction: Direction)
342                   -> FxHashSet<&'q DepNode<DefId>>
343 {
344     let mut set = FxHashSet();
345     for &start in starts {
346         debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
347         if set.insert(start) {
348             let mut stack = vec![query.indices[start]];
349             while let Some(index) = stack.pop() {
350                 for (_, edge) in query.graph.adjacent_edges(index, direction) {
351                     let neighbor_index = edge.source_or_target(direction);
352                     let neighbor = query.graph.node_data(neighbor_index);
353                     if set.insert(neighbor) {
354                         stack.push(neighbor_index);
355                     }
356                 }
357             }
358         }
359     }
360     set
361 }
362
363 fn walk_between<'q>(query: &'q DepGraphQuery<DefId>,
364                     sources: &FxHashSet<&'q DepNode<DefId>>,
365                     targets: &FxHashSet<&'q DepNode<DefId>>)
366                     -> FxHashSet<&'q DepNode<DefId>>
367 {
368     // This is a bit tricky. We want to include a node only if it is:
369     // (a) reachable from a source and (b) will reach a target. And we
370     // have to be careful about cycles etc.  Luckily efficiency is not
371     // a big concern!
372
373     #[derive(Copy, Clone, PartialEq)]
374     enum State { Undecided, Deciding, Included, Excluded }
375
376     let mut node_states = vec![State::Undecided; query.graph.len_nodes()];
377
378     for &target in targets {
379         node_states[query.indices[target].0] = State::Included;
380     }
381
382     for source in sources.iter().map(|&n| query.indices[n]) {
383         recurse(query, &mut node_states, source);
384     }
385
386     return query.nodes()
387                 .into_iter()
388                 .filter(|&n| {
389                     let index = query.indices[n];
390                     node_states[index.0] == State::Included
391                 })
392                 .collect();
393
394     fn recurse(query: &DepGraphQuery<DefId>,
395                node_states: &mut [State],
396                node: NodeIndex)
397                -> bool
398     {
399         match node_states[node.0] {
400             // known to reach a target
401             State::Included => return true,
402
403             // known not to reach a target
404             State::Excluded => return false,
405
406             // backedge, not yet known, say false
407             State::Deciding => return false,
408
409             State::Undecided => { }
410         }
411
412         node_states[node.0] = State::Deciding;
413
414         for neighbor_index in query.graph.successor_nodes(node) {
415             if recurse(query, node_states, neighbor_index) {
416                 node_states[node.0] = State::Included;
417             }
418         }
419
420         // if we didn't find a path to target, then set to excluded
421         if node_states[node.0] == State::Deciding {
422             node_states[node.0] = State::Excluded;
423             false
424         } else {
425             assert!(node_states[node.0] == State::Included);
426             true
427         }
428     }
429 }
430
431 fn filter_edges<'q>(query: &'q DepGraphQuery<DefId>,
432                     nodes: &FxHashSet<&'q DepNode<DefId>>)
433                     -> Vec<(&'q DepNode<DefId>, &'q DepNode<DefId>)>
434 {
435     query.edges()
436          .into_iter()
437          .filter(|&(source, target)| nodes.contains(source) && nodes.contains(target))
438          .collect()
439 }