1use std::{fmt, fs, io, path::Path};
9
10use flux_common::dbg::SpanTrace;
11use rustc_data_structures::{
12 fx::{FxIndexMap, FxIndexSet},
13 unord::UnordMap,
14};
15use rustc_hir::{def::DefKind, def_id::DefId};
16use rustc_macros::{TyDecodable, TyEncodable};
17use rustc_middle::{
18 mir::Location,
19 ty::{GenericArgs, Instance, InstanceKind, TyCtxt, TypeVisitableExt},
20};
21use rustc_serialize::ContextOrd;
22use serde::Serialize;
23use toposort_scc::IndexGraph;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)]
28pub enum NodeKey<'tcx> {
29 Item(DefId),
31 Mono(Instance<'tcx>),
37}
38
39impl<'tcx, E> ContextOrd<E> for NodeKey<'tcx> {}
41
42impl<'tcx> NodeKey<'tcx> {
43 pub fn from_instance(instance: Instance<'tcx>) -> Self {
45 if let InstanceKind::Item(def_id) = instance.def
46 && (instance.args.has_param() || instance.args.is_empty())
49 {
50 NodeKey::Item(def_id)
51 } else {
52 NodeKey::Mono(instance)
53 }
54 }
55
56 pub fn def_id(self) -> DefId {
57 match self {
58 NodeKey::Item(def_id) => def_id,
59 NodeKey::Mono(instance) => instance.def_id(),
60 }
61 }
62
63 pub fn instance(self, tcx: TyCtxt<'tcx>) -> Instance<'tcx> {
66 match self {
67 NodeKey::Item(def_id) => {
68 Instance::new_raw(def_id, GenericArgs::identity_for_item(tcx, def_id))
69 }
70 NodeKey::Mono(instance) => instance,
71 }
72 }
73
74 #[allow(
79 clippy::disallowed_methods,
80 reason = "is responsibility of who builds the graph to filter out dummy extern spec items."
81 )]
82 pub fn is_local_item(self) -> bool {
83 self.def_id().is_local()
84 && match self {
85 NodeKey::Item(_) => true,
86 NodeKey::Mono(instance) => matches!(instance.def, InstanceKind::Item(_)),
87 }
88 }
89}
90
91#[derive(Debug, Clone)]
93pub struct CallSite<'tcx> {
94 pub location: Location,
95 pub kind: CallSiteKind<'tcx>,
96}
97
98#[derive(Debug, Clone)]
99pub enum CallSiteKind<'tcx> {
100 Resolved { callee: NodeKey<'tcx> },
103 SynthesizedPanic,
106 Unresolved { def_id: DefId },
108 DynamicDispatch,
110}
111
112#[derive(Debug, Clone)]
116pub enum Node<'tcx> {
117 Analyzed { call_sites: Vec<CallSite<'tcx>> },
119 ExternalCrate,
121 Leaf(DefKind),
125}
126
127impl<'tcx> Node<'tcx> {
128 fn call_sites(&self) -> &[CallSite<'tcx>] {
130 match self {
131 Node::Analyzed { call_sites } => call_sites,
132 Node::ExternalCrate | Node::Leaf(_) => &[],
133 }
134 }
135
136 pub fn resolved_callees(&self) -> impl Iterator<Item = NodeKey<'tcx>> {
138 self.call_sites().iter().filter_map(|site| {
139 match site.kind {
140 CallSiteKind::Resolved { callee } => Some(callee),
141 _ => None,
142 }
143 })
144 }
145}
146
147pub struct CallGraph<'tcx> {
148 pub nodes: FxIndexMap<NodeKey<'tcx>, Node<'tcx>>,
149 pub callers: UnordMap<NodeKey<'tcx>, Vec<NodeKey<'tcx>>>,
150}
151
152impl<'tcx> CallGraph<'tcx> {
153 pub fn new(nodes: FxIndexMap<NodeKey<'tcx>, Node<'tcx>>) -> Self {
154 let mut callers: UnordMap<_, Vec<_>> = UnordMap::default();
155 for (&caller, node) in &nodes {
156 for callee in node.resolved_callees() {
157 callers.entry(callee).or_default().push(caller);
158 }
159 }
160 CallGraph { nodes, callers }
161 }
162
163 pub fn resolved_callee(&self, caller: DefId, location: Location) -> Option<NodeKey<'tcx>> {
167 let node = self.nodes.get(&NodeKey::Item(caller))?;
168 node.call_sites().iter().find_map(|site| {
169 match site.kind {
170 CallSiteKind::Resolved { callee } if site.location == location => Some(callee),
171 _ => None,
172 }
173 })
174 }
175}
176
177impl<'tcx> fmt::Display for NodeKey<'tcx> {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 match self {
180 NodeKey::Item(def_id) => write!(f, "{def_id:?}"),
181 NodeKey::Mono(instance) => write!(f, "{instance}"),
182 }
183 }
184}
185
186impl<'tcx> fmt::Display for Node<'tcx> {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 match self {
189 Node::Analyzed { .. } => write!(f, "Analyzed"),
190 Node::ExternalCrate => write!(f, "ExternalCrate"),
191 Node::Leaf(kind) => write!(f, "Leaf({kind:?})"),
192 }
193 }
194}
195
196impl<'tcx> fmt::Display for CallSiteKind<'tcx> {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 match self {
199 CallSiteKind::Resolved { callee } => write!(f, "-> {callee}"),
200 CallSiteKind::SynthesizedPanic => write!(f, "-> panic"),
201 CallSiteKind::Unresolved { def_id: method } => write!(f, "-> trait {method:?}"),
202 CallSiteKind::DynamicDispatch => write!(f, "-> <dynamic>"),
203 }
204 }
205}
206
207impl<'tcx> fmt::Display for CallGraph<'tcx> {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 writeln!(f, "call graph ({} nodes):", self.nodes.len())?;
210 let mut nodes: Vec<_> = self.nodes.iter().collect();
211 nodes.sort_by_key(|(key, _)| format!("{key}"));
212 for (key, node) in nodes {
213 writeln!(f, " {key} [{node}]:")?;
214 for site in node.call_sites() {
215 writeln!(f, " {} at {:?}", site.kind, site.location)?;
216 }
217 }
218 Ok(())
219 }
220}
221
222#[derive(Serialize)]
223pub struct JsonNode {
224 pub uid: usize,
225 pub path: String,
226 pub span: SpanTrace,
227 pub deps: Vec<usize>,
228}
229
230pub fn dump_dep_graph_json(
233 tcx: TyCtxt<'_>,
234 dir: &Path,
235 file_name: &str,
236 def_ids: &[DefId],
237 adj: &[Vec<usize>],
238) -> io::Result<()> {
239 let mut graph = IndexGraph::from_adjacency_list(adj);
240 graph.transpose();
241 let topo_order = graph
242 .toposort_or_scc()
243 .unwrap_or_else(|sccs| sccs.into_iter().flatten().collect());
244
245 let mut uid_of: Vec<usize> = vec![0; def_ids.len()];
246 for (uid, &orig_idx) in topo_order.iter().enumerate() {
247 uid_of[orig_idx] = uid;
248 }
249
250 let json_nodes: Vec<JsonNode> = topo_order
251 .iter()
252 .enumerate()
253 .map(|(uid, &orig_idx)| {
254 let def_id = def_ids[orig_idx];
255 let dep_uids: Vec<usize> = adj[orig_idx].iter().map(|&j| uid_of[j]).collect();
256 JsonNode {
257 uid,
258 path: tcx.def_path_str(def_id),
259 span: SpanTrace::new(tcx, tcx.def_span(def_id)),
260 deps: dep_uids,
261 }
262 })
263 .collect();
264
265 fs::create_dir_all(dir)?;
266 let path = dir.join(file_name);
267 let file = fs::File::create(path)?;
268 serde_json::to_writer_pretty(file, &json_nodes)
269 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
270}
271
272impl<'tcx> CallGraph<'tcx> {
273 pub fn dump_dep_graph_json(&self, tcx: TyCtxt<'tcx>, dir: &Path) -> io::Result<()> {
276 let def_ids: FxIndexSet<DefId> = self
280 .nodes
281 .keys()
282 .filter(|key| key.is_local_item())
283 .map(|key| key.def_id())
284 .collect();
285 let idx_of = |key: &NodeKey<'tcx>| {
286 if key.is_local_item() { def_ids.get_index_of(&key.def_id()) } else { None }
287 };
288
289 let mut adj: Vec<Vec<usize>> = vec![vec![]; def_ids.len()];
292 for (key, node) in &self.nodes {
293 let Some(caller_idx) = idx_of(key) else { continue };
294 adj[caller_idx].extend(node.resolved_callees().filter_map(|callee| idx_of(&callee)));
295 }
296 for deps in &mut adj {
297 deps.sort_unstable();
298 deps.dedup();
299 }
300 let def_ids: Vec<DefId> = def_ids.into_iter().collect();
301
302 dump_dep_graph_json(tcx, dir, "call_graph.json", &def_ids, &adj)
303 }
304}