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