1use std::env;
37use std::fs::{self, File};
38use std::io::Write;
39
40use rustc_data_structures::fx::FxIndexSet;
41use rustc_data_structures::graph::implementation::{Direction, INCOMING, NodeIndex, OUTGOING};
42use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
43use rustc_hir::intravisit::{self, Visitor};
44use rustc_middle::dep_graph::{
45 DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter, dep_kinds,
46};
47use rustc_middle::hir::nested_filter;
48use rustc_middle::ty::TyCtxt;
49use rustc_middle::{bug, span_bug};
50use rustc_span::{Span, Symbol, sym};
51use tracing::debug;
52use {rustc_graphviz as dot, rustc_hir as hir};
53
54use crate::errors;
55
56#[allow(missing_docs)]
57pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) {
58 tcx.dep_graph.with_ignore(|| {
59 if tcx.sess.opts.unstable_opts.dump_dep_graph {
60 tcx.dep_graph.with_query(dump_graph);
61 }
62
63 if !tcx.sess.opts.unstable_opts.query_dep_graph {
64 return;
65 }
66
67 if !tcx.features().rustc_attrs() {
71 return;
72 }
73
74 let (if_this_changed, then_this_would_need) = {
76 let mut visitor =
77 IfThisChanged { tcx, if_this_changed: vec![], then_this_would_need: vec![] };
78 visitor.process_attrs(CRATE_DEF_ID);
79 tcx.hir().visit_all_item_likes_in_crate(&mut visitor);
80 (visitor.if_this_changed, visitor.then_this_would_need)
81 };
82
83 if !if_this_changed.is_empty() || !then_this_would_need.is_empty() {
84 assert!(
85 tcx.sess.opts.unstable_opts.query_dep_graph,
86 "cannot use the `#[{}]` or `#[{}]` annotations \
87 without supplying `-Z query-dep-graph`",
88 sym::rustc_if_this_changed,
89 sym::rustc_then_this_would_need
90 );
91 }
92
93 check_paths(tcx, &if_this_changed, &then_this_would_need);
95 })
96}
97
98type Sources = Vec<(Span, DefId, DepNode)>;
99type Targets = Vec<(Span, Symbol, hir::HirId, DepNode)>;
100
101struct IfThisChanged<'tcx> {
102 tcx: TyCtxt<'tcx>,
103 if_this_changed: Sources,
104 then_this_would_need: Targets,
105}
106
107impl<'tcx> IfThisChanged<'tcx> {
108 fn argument(&self, attr: &hir::Attribute) -> Option<Symbol> {
109 let mut value = None;
110 for list_item in attr.meta_item_list().unwrap_or_default() {
111 match list_item.ident() {
112 Some(ident) if list_item.is_word() && value.is_none() => value = Some(ident.name),
113 _ =>
114 {
116 span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item)
117 }
118 }
119 }
120 value
121 }
122
123 fn process_attrs(&mut self, def_id: LocalDefId) {
124 let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id());
125 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
126 let attrs = self.tcx.hir().attrs(hir_id);
127 for attr in attrs {
128 if attr.has_name(sym::rustc_if_this_changed) {
129 let dep_node_interned = self.argument(attr);
130 let dep_node = match dep_node_interned {
131 None => DepNode::from_def_path_hash(
132 self.tcx,
133 def_path_hash,
134 dep_kinds::opt_hir_owner_nodes,
135 ),
136 Some(n) => {
137 match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {
138 Ok(n) => n,
139 Err(()) => self.tcx.dcx().emit_fatal(errors::UnrecognizedDepNode {
140 span: attr.span,
141 name: n,
142 }),
143 }
144 }
145 };
146 self.if_this_changed.push((attr.span, def_id.to_def_id(), dep_node));
147 } else if attr.has_name(sym::rustc_then_this_would_need) {
148 let dep_node_interned = self.argument(attr);
149 let dep_node = match dep_node_interned {
150 Some(n) => {
151 match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {
152 Ok(n) => n,
153 Err(()) => self.tcx.dcx().emit_fatal(errors::UnrecognizedDepNode {
154 span: attr.span,
155 name: n,
156 }),
157 }
158 }
159 None => {
160 self.tcx.dcx().emit_fatal(errors::MissingDepNode { span: attr.span });
161 }
162 };
163 self.then_this_would_need.push((
164 attr.span,
165 dep_node_interned.unwrap(),
166 hir_id,
167 dep_node,
168 ));
169 }
170 }
171 }
172}
173
174impl<'tcx> Visitor<'tcx> for IfThisChanged<'tcx> {
175 type NestedFilter = nested_filter::OnlyBodies;
176
177 fn nested_visit_map(&mut self) -> Self::Map {
178 self.tcx.hir()
179 }
180
181 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
182 self.process_attrs(item.owner_id.def_id);
183 intravisit::walk_item(self, item);
184 }
185
186 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
187 self.process_attrs(trait_item.owner_id.def_id);
188 intravisit::walk_trait_item(self, trait_item);
189 }
190
191 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
192 self.process_attrs(impl_item.owner_id.def_id);
193 intravisit::walk_impl_item(self, impl_item);
194 }
195
196 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
197 self.process_attrs(s.def_id);
198 intravisit::walk_field_def(self, s);
199 }
200}
201
202fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_would_need: &Targets) {
203 if if_this_changed.is_empty() {
205 for &(target_span, _, _, _) in then_this_would_need {
206 tcx.dcx().emit_err(errors::MissingIfThisChanged { span: target_span });
207 }
208 return;
209 }
210 tcx.dep_graph.with_query(|query| {
211 for &(_, source_def_id, ref source_dep_node) in if_this_changed {
212 let dependents = query.transitive_predecessors(source_dep_node);
213 for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need {
214 if !dependents.contains(&target_dep_node) {
215 tcx.dcx().emit_err(errors::NoPath {
216 span: target_span,
217 source: tcx.def_path_str(source_def_id),
218 target: *target_pass,
219 });
220 } else {
221 tcx.dcx().emit_err(errors::Ok { span: target_span });
222 }
223 }
224 }
225 });
226}
227
228fn dump_graph(query: &DepGraphQuery) {
229 let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
230
231 let nodes = match env::var("RUST_DEP_GRAPH_FILTER") {
232 Ok(string) => {
233 let edge_filter =
235 EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e));
236 let sources = node_set(query, &edge_filter.source);
237 let targets = node_set(query, &edge_filter.target);
238 filter_nodes(query, &sources, &targets)
239 }
240 Err(_) => query.nodes().into_iter().map(|n| n.kind).collect(),
241 };
242 let edges = filter_edges(query, &nodes);
243
244 {
245 let txt_path = format!("{path}.txt");
247 let mut file = File::create_buffered(&txt_path).unwrap();
248 for (source, target) in &edges {
249 write!(file, "{source:?} -> {target:?}\n").unwrap();
250 }
251 }
252
253 {
254 let dot_path = format!("{path}.dot");
256 let mut v = Vec::new();
257 dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap();
258 fs::write(dot_path, v).unwrap();
259 }
260}
261
262#[allow(missing_docs)]
263struct GraphvizDepGraph(FxIndexSet<DepKind>, Vec<(DepKind, DepKind)>);
264
265impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph {
266 type Node = DepKind;
267 type Edge = (DepKind, DepKind);
268 fn nodes(&self) -> dot::Nodes<'_, DepKind> {
269 let nodes: Vec<_> = self.0.iter().cloned().collect();
270 nodes.into()
271 }
272 fn edges(&self) -> dot::Edges<'_, (DepKind, DepKind)> {
273 self.1[..].into()
274 }
275 fn source(&self, edge: &(DepKind, DepKind)) -> DepKind {
276 edge.0
277 }
278 fn target(&self, edge: &(DepKind, DepKind)) -> DepKind {
279 edge.1
280 }
281}
282
283impl<'a> dot::Labeller<'a> for GraphvizDepGraph {
284 type Node = DepKind;
285 type Edge = (DepKind, DepKind);
286 fn graph_id(&self) -> dot::Id<'_> {
287 dot::Id::new("DependencyGraph").unwrap()
288 }
289 fn node_id(&self, n: &DepKind) -> dot::Id<'_> {
290 let s: String = format!("{n:?}")
291 .chars()
292 .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
293 .collect();
294 debug!("n={:?} s={:?}", n, s);
295 dot::Id::new(s).unwrap()
296 }
297 fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> {
298 dot::LabelText::label(format!("{n:?}"))
299 }
300}
301
302fn node_set<'q>(
306 query: &'q DepGraphQuery,
307 filter: &DepNodeFilter,
308) -> Option<FxIndexSet<&'q DepNode>> {
309 debug!("node_set(filter={:?})", filter);
310
311 if filter.accepts_all() {
312 return None;
313 }
314
315 Some(query.nodes().into_iter().filter(|n| filter.test(n)).collect())
316}
317
318fn filter_nodes<'q>(
319 query: &'q DepGraphQuery,
320 sources: &Option<FxIndexSet<&'q DepNode>>,
321 targets: &Option<FxIndexSet<&'q DepNode>>,
322) -> FxIndexSet<DepKind> {
323 if let Some(sources) = sources {
324 if let Some(targets) = targets {
325 walk_between(query, sources, targets)
326 } else {
327 walk_nodes(query, sources, OUTGOING)
328 }
329 } else if let Some(targets) = targets {
330 walk_nodes(query, targets, INCOMING)
331 } else {
332 query.nodes().into_iter().map(|n| n.kind).collect()
333 }
334}
335
336fn walk_nodes<'q>(
337 query: &'q DepGraphQuery,
338 starts: &FxIndexSet<&'q DepNode>,
339 direction: Direction,
340) -> FxIndexSet<DepKind> {
341 let mut set = FxIndexSet::default();
342 for &start in starts {
343 debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING);
344 if set.insert(start.kind) {
345 let mut stack = vec![query.indices[start]];
346 while let Some(index) = stack.pop() {
347 for (_, edge) in query.graph.adjacent_edges(index, direction) {
348 let neighbor_index = edge.source_or_target(direction);
349 let neighbor = query.graph.node_data(neighbor_index);
350 if set.insert(neighbor.kind) {
351 stack.push(neighbor_index);
352 }
353 }
354 }
355 }
356 }
357 set
358}
359
360fn walk_between<'q>(
361 query: &'q DepGraphQuery,
362 sources: &FxIndexSet<&'q DepNode>,
363 targets: &FxIndexSet<&'q DepNode>,
364) -> FxIndexSet<DepKind> {
365 #[derive(Copy, Clone, PartialEq)]
371 enum State {
372 Undecided,
373 Deciding,
374 Included,
375 Excluded,
376 }
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
389 .nodes()
390 .into_iter()
391 .filter(|&n| {
392 let index = query.indices[n];
393 node_states[index.0] == State::Included
394 })
395 .map(|n| n.kind)
396 .collect();
397
398 fn recurse(query: &DepGraphQuery, node_states: &mut [State], node: NodeIndex) -> bool {
399 match node_states[node.0] {
400 State::Included => return true,
402
403 State::Excluded => return false,
405
406 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 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
431fn filter_edges(query: &DepGraphQuery, nodes: &FxIndexSet<DepKind>) -> Vec<(DepKind, DepKind)> {
432 let uniq: FxIndexSet<_> = query
433 .edges()
434 .into_iter()
435 .map(|(s, t)| (s.kind, t.kind))
436 .filter(|(source, target)| nodes.contains(source) && nodes.contains(target))
437 .collect();
438 uniq.into_iter().collect()
439}