Skip to main content

rustc_borrowck/polonius/
dump.rs

1use std::io;
2
3use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
4use rustc_index::IndexVec;
5use rustc_middle::mir::pretty::{MirDumper, PassWhere, PrettyPrintMirOptions};
6use rustc_middle::mir::{Body, Location};
7use rustc_middle::ty::{RegionVid, TyCtxt};
8use rustc_mir_dataflow::points::PointIndex;
9use rustc_session::config::MirIncludeSpans;
10
11use crate::borrow_set::BorrowSet;
12use crate::constraints::OutlivesConstraint;
13use crate::dataflow::BorrowIndex;
14use crate::polonius::liveness::RegionLiveness;
15use crate::polonius::{
16    LiveRegionVariances, LivenessSource, LocalizedConstraintGraphVisitor, LocalizedNode,
17    PoloniusContext,
18};
19use crate::region_infer::values::LivenessValues;
20use crate::type_check::Locations;
21use crate::universal_regions::UniversalRegions;
22use crate::{BorrowckInferCtxt, ClosureRegionRequirements, RegionInferenceContext};
23
24/// The polonius MIR dump template: a regular HTML file for easy editing, with special dummy
25/// sections to be replaced by real contents.
26const TEMPLATE: &str = "<!DOCTYPE html>\n<html>\n<head>\n<title>Polonius MIR dump</title>\n<style>\npre {\n    margin-top: 0;\n    white-space: pre-wrap;\n}\n\n.section + .section {\n    margin-top: 20px;\n    border-top: 1px solid #aaa;\n    padding-top: 10px;\n}\n\n.section-header {\n    margin-bottom: 6px;\n}\n\n.trace + .trace {\n    margin-top: 15px;\n}\n\n.trace ul {\n    margin: 5px 0px;\n    padding-left: 15px;\n}\n\n.trace-suffix {\n    opacity: 0.8;\n    margin-left: 10px;\n}\n\n.hidden {\n    display: none;\n}\n</style>\n</head>\n\n<body>\n\n<!-- Links to the other sections -->\n<div class=\"section\">\n    <div class=\"section-header\">Quick links</div>\n    <a href=\"#mir\">Polonius MIR</a>\n    <a href=\"#polonius-region-graph\">Polonius constraint graph</a>\n    <a href=\"#loan-traces\">Loan traces</a>\n    <a href=\"#cfg-graph\">Control-flow graph</a>\n    <a href=\"#nll-region-graph\">NLL region graph</a>\n    <a href=\"#nll-scc-graph\">NLL SCC graph</a>\n</div>\n\n<!-- The NLL + Polonius MIR -->\n<div class=\"section\" id=\"mir\">\n    <div class=\"section-header\">Raw MIR dump</div>\n    <pre><code>$SECTION_MIR</code></pre>\n</div>\n\n<!-- Mermaid visualization of the polonius constraint graph -->\n<div class=\"section\" id=\"polonius-region-graph\">\n    <div class=\"section-header\">Polonius constraint graph</div>\n    <pre class=\'mermaid\'>$SECTION_POLONIUS_CONSTRAINTS</pre>\n</div>\n\n<!-- The reachability of loans while traversing the polonius constraint graph -->\n<div class=\"section traces\" id=\"loan-traces\">\n    <div class=\"section-header\">Loan Traces</div>\n    $SECTION_POLONIUS_REACHABILITY\n</div>\n\n<!-- Mermaid visualization of the CFG -->\n<div class=\"section\" id=\"cfg-graph\">\n    <div class=\"section-header\">Control-flow graph</div>\n    <pre class=\'mermaid\'>$SECTION_CFG</pre>\n</div>\n\n<!-- Mermaid visualization of the NLL region graph -->\n<div class=\"section\" id=\"nll-region-graph\">\n    <div class=\"section-header\">NLL regions</div>\n    <pre class=\'mermaid\'>$SECTION_NLL_CONSTRAINTS</pre>\n</div>\n\n<!-- Mermaid visualization of the NLL SCC graph -->\n<div class=\"section\" id=\"nll-scc-graph\">\n    <div class=\"section-header\">NLL SCCs</div>\n    <pre class=\'mermaid\'>$SECTION_NLL_SCCS</pre>\n</div>\n\n<script src=\'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js\'></script>\n$SECTION_INITIALIZATION\n<script>\n// Set up the loan traces buttons.\ndocument.querySelectorAll(\".traces button\").forEach(button => {\n    button.addEventListener(\"click\", e => {\n        // We remove the class hiding the trace by default.\n        let loan = button.getAttribute(\"data-loan\");\n        let trace = document.getElementById(`trace-${loan}`);\n        trace.classList.remove(\"hidden\");\n\n        // And we also remove the button\'s container.\n        button.parentElement.remove();\n    });\n});\n</script>\n</body>\n</html>\n"include_str!("./dump/polonius-mir-dump.template.html");
27
28/// A `LivenessSource` for already-existing liveness and variance data.
29struct CachedLivenessSource<'a, 'tcx> {
30    live_region_variances: &'a LiveRegionVariances,
31    universal_regions: &'a UniversalRegions<'tcx>,
32    liveness: &'a LivenessValues,
33}
34
35impl<'a, 'tcx> LivenessSource for CachedLivenessSource<'a, 'tcx> {
36    fn liveness_for_region(&mut self, region: RegionVid) -> RegionLiveness<'_> {
37        RegionLiveness::new(
38            region,
39            self.live_region_variances,
40            self.universal_regions,
41            self.liveness.points(),
42        )
43    }
44}
45
46/// `-Zdump-mir=polonius` dumps MIR annotated with NLL and polonius specific information.
47pub(crate) fn dump_polonius_mir<'tcx>(
48    infcx: &BorrowckInferCtxt<'tcx>,
49    body: &Body<'tcx>,
50    regioncx: &RegionInferenceContext<'tcx>,
51    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
52    borrow_set: &BorrowSet<'tcx>,
53    polonius_context: Option<&PoloniusContext<'tcx>>,
54) {
55    let tcx = infcx.tcx;
56    if !tcx.sess.opts.unstable_opts.polonius.is_next_enabled() {
57        return;
58    }
59
60    let Some(dumper) = MirDumper::new(tcx, "polonius", body) else { return };
61
62    let polonius_context =
63        polonius_context.expect("missing polonius context with `-Zpolonius=next`");
64
65    // If we have a polonius graph to dump along the rest of the MIR and NLL info, we extract its
66    // constraints here.
67    let mut liveness_source = CachedLivenessSource {
68        live_region_variances: &polonius_context.live_region_variances,
69        universal_regions: regioncx.universal_regions(),
70        liveness: regioncx.liveness_constraints(),
71    };
72    let mut collector = MirDumpCollector::default();
73    if let Some(graph) = &polonius_context.graph {
74        graph.traverse(body, borrow_set, &mut liveness_source, &mut collector);
75    }
76
77    let extra_data = &|pass_where, out: &mut dyn io::Write| {
78        emit_polonius_mir(
79            tcx,
80            regioncx,
81            closure_region_requirements,
82            borrow_set,
83            &collector.constraints,
84            pass_where,
85            out,
86        )
87    };
88    // We want the NLL extra comments printed by default in NLL MIR dumps. Specifying `-Z
89    // mir-include-spans` on the CLI still has priority.
90    let options = PrettyPrintMirOptions {
91        include_extra_comments: #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.opts.unstable_opts.mir_include_spans
    {
    MirIncludeSpans::On | MirIncludeSpans::Nll => true,
    _ => false,
}matches!(
92            tcx.sess.opts.unstable_opts.mir_include_spans,
93            MirIncludeSpans::On | MirIncludeSpans::Nll
94        ),
95    };
96
97    let dumper = dumper.set_extra_data(extra_data).set_options(options);
98
99    let _ = try {
100        let mut file = dumper.create_dump_file("html", body)?;
101        emit_polonius_dump(&dumper, body, regioncx, borrow_set, &collector, &mut file)?;
102    };
103}
104
105/// The constraints we'll dump as text or a mermaid graph.
106struct LocalizedOutlivesConstraint {
107    source: RegionVid,
108    from: PointIndex,
109    target: RegionVid,
110    to: PointIndex,
111}
112
113/// Visitor to record constraints encountered when traversing the localized constraint graph, as
114/// well as the reachability of each loan.
115#[derive(#[automatically_derived]
impl ::core::default::Default for MirDumpCollector {
    #[inline]
    fn default() -> Self {
        Self {
            constraints: ::core::default::Default::default(),
            reachability: ::core::default::Default::default(),
        }
    }
}Default)]
116struct MirDumpCollector {
117    constraints: Vec<LocalizedOutlivesConstraint>,
118    reachability: FxIndexMap<BorrowIndex, Vec<LocalizedNode>>,
119}
120
121impl LocalizedConstraintGraphVisitor for MirDumpCollector {
122    fn on_node_traversed(&mut self, loan: BorrowIndex, node: LocalizedNode, _is_live: bool) {
123        self.reachability.entry(loan).or_default().push(node);
124    }
125
126    fn on_successor_discovered(&mut self, current_node: LocalizedNode, successor: LocalizedNode) {
127        self.constraints.push(LocalizedOutlivesConstraint {
128            source: current_node.region,
129            from: current_node.point,
130            target: successor.region,
131            to: successor.point,
132        });
133    }
134}
135
136/// The polonius dump consists of:
137/// - the NLL MIR
138/// - the list of polonius localized constraints
139/// - a mermaid graph of the CFG
140/// - a mermaid graph of the NLL regions and the constraints between them
141/// - a mermaid graph of the NLL SCCs and the constraints between them
142fn emit_polonius_dump<'tcx>(
143    dumper: &MirDumper<'_, 'tcx>,
144    body: &Body<'tcx>,
145    regioncx: &RegionInferenceContext<'tcx>,
146    borrow_set: &BorrowSet<'tcx>,
147    collector: &MirDumpCollector,
148    out: &mut dyn io::Write,
149) -> io::Result<()> {
150    let mut edge_count = 0;
151
152    // We replace the dummy $SECTION tokens from the HTML polonius dump template, and emit the
153    // result into the given writer.
154    for chunk in TEMPLATE.split("$SECTION") {
155        match chunk.strip_prefix("_") {
156            None => {
157                // We're at the beginning of the template: this is the prologue to emit as-is.
158                out.write_fmt(format_args!("{0}\n", chunk))writeln!(out, "{}", chunk)?;
159            }
160            Some(section) => {
161                // This is the start of a prefixed section, we look for its identifier.
162                let dummy_section_end = section
163                    .find("<")
164                    .expect("the template section end boundary needs to be present");
165                let section_identifier = section[..dummy_section_end].trim();
166
167                // Emit the real section instead of the dummy token.
168                match section_identifier {
169                    "MIR" => {
170                        emit_html_mir(dumper, body, out)?;
171                    }
172                    "POLONIUS_CONSTRAINTS" => {
173                        edge_count = emit_mermaid_constraint_graph(
174                            borrow_set,
175                            regioncx.liveness_constraints(),
176                            &collector.constraints,
177                            out,
178                        )?;
179                    }
180                    "POLONIUS_REACHABILITY" => {
181                        emit_loan_reachability(
182                            borrow_set,
183                            regioncx.liveness_constraints(),
184                            &collector.reachability,
185                            out,
186                        )?;
187                    }
188                    "CFG" => {
189                        emit_mermaid_cfg(body, out)?;
190                    }
191                    "NLL_CONSTRAINTS" => {
192                        emit_mermaid_nll_regions(dumper.tcx(), regioncx, out)?;
193                    }
194                    "NLL_SCCS" => {
195                        emit_mermaid_nll_sccs(dumper.tcx(), regioncx, out)?;
196                    }
197                    "INITIALIZATION" => {
198                        out.write_fmt(format_args!("<script>\n"))writeln!(out, "<script>")?;
199                        out.write_fmt(format_args!("mermaid.initialize({{ startOnLoad: false, maxEdges: {0} }});\n",
        edge_count.max(100)))writeln!(
200                            out,
201                            "mermaid.initialize({{ startOnLoad: false, maxEdges: {} }});",
202                            edge_count.max(100),
203                        )?;
204                        out.write_fmt(format_args!("mermaid.run({{ querySelector: \'.mermaid\' }})\n"))writeln!(out, "mermaid.run({{ querySelector: '.mermaid' }})")?;
205                        out.write_fmt(format_args!("</script>\n"))writeln!(out, "</script>")?;
206                    }
207
208                    _ => {
209                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected dummy section identifier {0:?}",
                section_identifier)));
}unreachable!("unexpected dummy section identifier {:?}", section_identifier)
210                    }
211                }
212
213                // And finally, emit the contents that followed the dummy token.
214                out.write_fmt(format_args!("{0}\n", &section[dummy_section_end..]))writeln!(out, "{}", &section[dummy_section_end..])?;
215            }
216        }
217    }
218
219    Ok(())
220}
221
222/// Emits the polonius MIR, as escaped HTML.
223fn emit_html_mir<'tcx>(
224    dumper: &MirDumper<'_, 'tcx>,
225    body: &Body<'tcx>,
226    out: &mut dyn io::Write,
227) -> io::Result<()> {
228    // Buffer the regular MIR dump to be able to escape it.
229    let mut buffer = Vec::new();
230
231    dumper.dump_mir_to_writer(body, &mut buffer)?;
232
233    // Escape the handful of characters that need it. We don't need to be particularly efficient:
234    // we're actually writing into a buffered writer already. Note that MIR dumps are valid UTF-8.
235    let buffer = String::from_utf8_lossy(&buffer);
236    for ch in buffer.chars() {
237        let escaped = match ch {
238            '>' => "&gt;",
239            '<' => "&lt;",
240            '&' => "&amp;",
241            '\'' => "&#39;",
242            '"' => "&quot;",
243            _ => {
244                // The common case, no escaping needed.
245                out.write_fmt(format_args!("{0}", ch))write!(out, "{}", ch)?;
246                continue;
247            }
248        };
249        out.write_fmt(format_args!("{0}", escaped))write!(out, "{}", escaped)?;
250    }
251    Ok(())
252}
253
254/// Produces the actual NLL + Polonius MIR sections to emit during the dumping process.
255fn emit_polonius_mir<'tcx>(
256    tcx: TyCtxt<'tcx>,
257    regioncx: &RegionInferenceContext<'tcx>,
258    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
259    borrow_set: &BorrowSet<'tcx>,
260    localized_outlives_constraints: &[LocalizedOutlivesConstraint],
261    pass_where: PassWhere,
262    out: &mut dyn io::Write,
263) -> io::Result<()> {
264    // Emit the regular NLL front-matter
265    crate::nll::emit_nll_mir(
266        tcx,
267        regioncx,
268        closure_region_requirements,
269        borrow_set,
270        pass_where,
271        out,
272    )?;
273
274    let liveness = regioncx.liveness_constraints();
275
276    // Add localized outlives constraints
277    match pass_where {
278        PassWhere::BeforeCFG => {
279            if localized_outlives_constraints.len() > 0 {
280                out.write_fmt(format_args!("| Localized constraints\n"))writeln!(out, "| Localized constraints")?;
281
282                for constraint in localized_outlives_constraints {
283                    let LocalizedOutlivesConstraint { source, from, target, to } = constraint;
284                    let from = liveness.location_from_point(*from);
285                    let to = liveness.location_from_point(*to);
286                    out.write_fmt(format_args!("| {0:?} at {1:?} -> {2:?} at {3:?}\n", source,
        from, target, to))writeln!(out, "| {source:?} at {from:?} -> {target:?} at {to:?}")?;
287                }
288                out.write_fmt(format_args!("|\n"))writeln!(out, "|")?;
289            }
290        }
291        _ => {}
292    }
293
294    Ok(())
295}
296
297/// Emits a mermaid flowchart of the CFG blocks and edges, similar to the graphviz version.
298fn emit_mermaid_cfg(body: &Body<'_>, out: &mut dyn io::Write) -> io::Result<()> {
299    use rustc_middle::mir::{TerminatorEdges, TerminatorKind};
300
301    // The mermaid chart type: a top-down flowchart.
302    out.write_fmt(format_args!("flowchart TD\n"))writeln!(out, "flowchart TD")?;
303
304    // Emit the block nodes.
305    for (block_idx, block) in body.basic_blocks.iter_enumerated() {
306        let block_idx = block_idx.as_usize();
307        let cleanup = if block.is_cleanup { " (cleanup)" } else { "" };
308        out.write_fmt(format_args!("{0}[\"bb{0}{1}\"]\n", block_idx, cleanup))writeln!(out, "{block_idx}[\"bb{block_idx}{cleanup}\"]")?;
309    }
310
311    // Emit the edges between blocks, from the terminator edges.
312    for (block_idx, block) in body.basic_blocks.iter_enumerated() {
313        let block_idx = block_idx.as_usize();
314        let terminator = block.terminator();
315        match terminator.edges() {
316            TerminatorEdges::None => {}
317            TerminatorEdges::Single(bb) => {
318                out.write_fmt(format_args!("{1} --> {0}\n", bb.as_usize(), block_idx))writeln!(out, "{block_idx} --> {}", bb.as_usize())?;
319            }
320            TerminatorEdges::Double(bb1, bb2) => {
321                if #[allow(non_exhaustive_omitted_patterns)] match terminator.kind {
    TerminatorKind::FalseEdge { .. } => true,
    _ => false,
}matches!(terminator.kind, TerminatorKind::FalseEdge { .. }) {
322                    out.write_fmt(format_args!("{1} --> {0}\n", bb1.as_usize(), block_idx))writeln!(out, "{block_idx} --> {}", bb1.as_usize())?;
323                    out.write_fmt(format_args!("{1} -- imaginary --> {0}\n", bb2.as_usize(),
        block_idx))writeln!(out, "{block_idx} -- imaginary --> {}", bb2.as_usize())?;
324                } else {
325                    out.write_fmt(format_args!("{1} --> {0}\n", bb1.as_usize(), block_idx))writeln!(out, "{block_idx} --> {}", bb1.as_usize())?;
326                    out.write_fmt(format_args!("{1} -- unwind --> {0}\n", bb2.as_usize(),
        block_idx))writeln!(out, "{block_idx} -- unwind --> {}", bb2.as_usize())?;
327                }
328            }
329            TerminatorEdges::AssignOnReturn { return_, cleanup, .. } => {
330                for to_idx in return_ {
331                    out.write_fmt(format_args!("{1} --> {0}\n", to_idx.as_usize(), block_idx))writeln!(out, "{block_idx} --> {}", to_idx.as_usize())?;
332                }
333
334                if let Some(to_idx) = cleanup {
335                    out.write_fmt(format_args!("{1} -- unwind --> {0}\n", to_idx.as_usize(),
        block_idx))writeln!(out, "{block_idx} -- unwind --> {}", to_idx.as_usize())?;
336                }
337            }
338            TerminatorEdges::SwitchInt { targets, .. } => {
339                for to_idx in targets.all_targets() {
340                    out.write_fmt(format_args!("{1} --> {0}\n", to_idx.as_usize(), block_idx))writeln!(out, "{block_idx} --> {}", to_idx.as_usize())?;
341                }
342            }
343        }
344    }
345
346    Ok(())
347}
348
349/// Emits a region's label: index, universe, external name.
350fn render_region<'tcx>(
351    tcx: TyCtxt<'tcx>,
352    region: RegionVid,
353    regioncx: &RegionInferenceContext<'tcx>,
354    out: &mut dyn io::Write,
355) -> io::Result<()> {
356    let def = regioncx.region_definition(region);
357    let universe = def.universe;
358
359    out.write_fmt(format_args!("\'{0}", region.as_usize()))write!(out, "'{}", region.as_usize())?;
360    if !universe.is_root() {
361        out.write_fmt(format_args!("/{0:?}", universe))write!(out, "/{universe:?}")?;
362    }
363    if let Some(name) = def.external_name.and_then(|e| e.get_name(tcx)) {
364        out.write_fmt(format_args!(" ({0})", name))write!(out, " ({name})")?;
365    }
366    Ok(())
367}
368
369/// Emits a mermaid flowchart of the NLL regions and the outlives constraints between them, similar
370/// to the graphviz version.
371fn emit_mermaid_nll_regions<'tcx>(
372    tcx: TyCtxt<'tcx>,
373    regioncx: &RegionInferenceContext<'tcx>,
374    out: &mut dyn io::Write,
375) -> io::Result<()> {
376    // The mermaid chart type: a top-down flowchart.
377    out.write_fmt(format_args!("flowchart TD\n"))writeln!(out, "flowchart TD")?;
378
379    // Emit the region nodes.
380    for region in regioncx.definitions.indices() {
381        out.write_fmt(format_args!("{0}[\"", region.as_usize()))write!(out, "{}[\"", region.as_usize())?;
382        render_region(tcx, region, regioncx, out)?;
383        out.write_fmt(format_args!("\"]\n"))writeln!(out, "\"]")?;
384    }
385
386    // Get a set of edges to check for the reverse edge being present.
387    let edges: FxHashSet<_> = regioncx.outlives_constraints().map(|c| (c.sup, c.sub)).collect();
388
389    // Order (and deduplicate) edges for traversal, to display them in a generally increasing order.
390    let constraint_key = |c: &OutlivesConstraint<'_>| {
391        let min = c.sup.min(c.sub);
392        let max = c.sup.max(c.sub);
393        (min, max)
394    };
395    let mut ordered_edges: Vec<_> = regioncx.outlives_constraints().collect();
396    ordered_edges.sort_by_key(|c| constraint_key(c));
397    ordered_edges.dedup_by_key(|c| constraint_key(c));
398
399    for outlives in ordered_edges {
400        // Source node.
401        out.write_fmt(format_args!("{0} ", outlives.sup.as_usize()))write!(out, "{} ", outlives.sup.as_usize())?;
402
403        // The kind of arrow: bidirectional if the opposite edge exists in the set.
404        if edges.contains(&(outlives.sub, outlives.sup)) {
405            out.write_fmt(format_args!("&lt;"))write!(out, "&lt;")?;
406        }
407        out.write_fmt(format_args!("-- "))write!(out, "-- ")?;
408
409        // Edge label from its `Locations`.
410        match outlives.locations {
411            Locations::All(_) => out.write_fmt(format_args!("All"))write!(out, "All")?,
412            Locations::Single(location) => out.write_fmt(format_args!("{0:?}", location))write!(out, "{:?}", location)?,
413        }
414
415        // Target node.
416        out.write_fmt(format_args!(" --> {0}\n", outlives.sub.as_usize()))writeln!(out, " --> {}", outlives.sub.as_usize())?;
417    }
418    Ok(())
419}
420
421/// Emits a mermaid flowchart of the NLL SCCs and the outlives constraints between them, similar
422/// to the graphviz version.
423fn emit_mermaid_nll_sccs<'tcx>(
424    tcx: TyCtxt<'tcx>,
425    regioncx: &RegionInferenceContext<'tcx>,
426    out: &mut dyn io::Write,
427) -> io::Result<()> {
428    // The mermaid chart type: a top-down flowchart.
429    out.write_fmt(format_args!("flowchart TD\n"))writeln!(out, "flowchart TD")?;
430
431    // Gather and emit the SCC nodes.
432    let mut nodes_per_scc: IndexVec<_, _> =
433        regioncx.constraint_sccs().all_sccs().map(|_| Vec::new()).collect();
434    for region in regioncx.definitions.indices() {
435        let scc = regioncx.constraint_sccs().scc(region);
436        nodes_per_scc[scc].push(region);
437    }
438    for (scc, regions) in nodes_per_scc.iter_enumerated() {
439        // The node label: the regions contained in the SCC.
440        out.write_fmt(format_args!("{0}[\"SCC({0}) = {{", scc.as_usize()))write!(out, "{scc}[\"SCC({scc}) = {{", scc = scc.as_usize())?;
441        for (idx, &region) in regions.iter().enumerate() {
442            render_region(tcx, region, regioncx, out)?;
443            if idx < regions.len() - 1 {
444                out.write_fmt(format_args!(","))write!(out, ",")?;
445            }
446        }
447        out.write_fmt(format_args!("}}\"]\n"))writeln!(out, "}}\"]")?;
448    }
449
450    // Emit the edges between SCCs.
451    let edges = regioncx.constraint_sccs().all_sccs().flat_map(|source| {
452        regioncx.constraint_sccs().successors(source).iter().map(move |&target| (source, target))
453    });
454    for (source, target) in edges {
455        out.write_fmt(format_args!("{0} --> {1}\n", source.as_usize(),
        target.as_usize()))writeln!(out, "{} --> {}", source.as_usize(), target.as_usize())?;
456    }
457
458    Ok(())
459}
460
461/// Emits a mermaid flowchart of the polonius localized outlives constraints, with subgraphs per
462/// region, and loan introductions.
463fn emit_mermaid_constraint_graph<'tcx>(
464    borrow_set: &BorrowSet<'tcx>,
465    liveness: &LivenessValues,
466    localized_outlives_constraints: &[LocalizedOutlivesConstraint],
467    out: &mut dyn io::Write,
468) -> io::Result<usize> {
469    let node_label = |region: RegionVid, point: PointIndex| {
470        let location = liveness.location_from_point(point);
471        node_name(region, location)
472    };
473
474    // The mermaid chart type: a top-down flowchart, which supports subgraphs.
475    out.write_fmt(format_args!("flowchart TD\n"))writeln!(out, "flowchart TD")?;
476
477    // The loans subgraph: a node per loan.
478    out.write_fmt(format_args!("    subgraph \"Loans\"\n"))writeln!(out, "    subgraph \"Loans\"")?;
479    for loan_idx in 0..borrow_set.len() {
480        out.write_fmt(format_args!("        L{0}\n", loan_idx))writeln!(out, "        L{loan_idx}")?;
481    }
482    out.write_fmt(format_args!("    end\n\n"))writeln!(out, "    end\n")?;
483
484    // And an edge from that loan node to where it enters the constraint graph.
485    for (loan_idx, loan) in borrow_set.iter_enumerated() {
486        out.write_fmt(format_args!("    L{0} --> {1}_{2}\n", loan_idx.index(),
        region_name(loan.region), location_name(loan.reserve_location)))writeln!(
487            out,
488            "    L{} --> {}_{}",
489            loan_idx.index(),
490            region_name(loan.region),
491            location_name(loan.reserve_location),
492        )?;
493    }
494    out.write_fmt(format_args!("\n"))writeln!(out, "")?;
495
496    // The regions subgraphs containing the region/point nodes.
497    let mut points_per_region: FxIndexMap<RegionVid, FxIndexSet<PointIndex>> =
498        FxIndexMap::default();
499    for constraint in localized_outlives_constraints {
500        points_per_region.entry(constraint.source).or_default().insert(constraint.from);
501        points_per_region.entry(constraint.target).or_default().insert(constraint.to);
502    }
503    for (region, points) in points_per_region {
504        out.write_fmt(format_args!("    subgraph \"{0}\"\n", region_name(region)))writeln!(out, "    subgraph \"{}\"", region_name(region))?;
505        for point in points {
506            out.write_fmt(format_args!("        {0}\n", node_label(region, point)))writeln!(out, "        {}", node_label(region, point))?;
507        }
508        out.write_fmt(format_args!("    end\n\n"))writeln!(out, "    end\n")?;
509    }
510
511    // The constraint graph edges.
512    for constraint in localized_outlives_constraints {
513        // FIXME: add killed loans and constraint kind as edge labels.
514        out.write_fmt(format_args!("    {0} --> {1}\n",
        node_label(constraint.source, constraint.from),
        node_label(constraint.target, constraint.to)))writeln!(
515            out,
516            "    {} --> {}",
517            node_label(constraint.source, constraint.from),
518            node_label(constraint.target, constraint.to),
519        )?;
520    }
521
522    // Return the number of edges: this is the biggest graph in the dump and its edge count will be
523    // mermaid's max edge count to support.
524    let edge_count = borrow_set.len() + localized_outlives_constraints.len();
525    Ok(edge_count)
526}
527
528/// Emits the reachability of loans: a list of all nodes reached while traversing the polonius
529/// constraint graph.
530fn emit_loan_reachability(
531    borrow_set: &BorrowSet<'_>,
532    liveness: &LivenessValues,
533    reachability: &FxIndexMap<BorrowIndex, Vec<LocalizedNode>>,
534    out: &mut dyn io::Write,
535) -> io::Result<()> {
536    for (loan, _) in borrow_set.iter_enumerated() {
537        let Some(reachability) = reachability.get(&loan) else {
538            continue;
539        };
540        let loan = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("L{0}", loan.index()))
    })format!("L{}", loan.index());
541
542        // The button to display the loan trace. The javascript event listener is hooked up in the
543        // template itself.
544        out.write_fmt(format_args!("<div class=\'trace\'><button data-loan=\'{0}\'>Trace for loan {0}</button></div>\n",
        loan))writeln!(
545            out,
546            "<div class='trace'><button data-loan='{loan}'>Trace for loan {loan}</button></div>"
547        )?;
548
549        // The actual trace contents, hidden by default.
550        out.write_fmt(format_args!("<div id=\'trace-{0}\' class=\'trace hidden\'>\n",
        loan))writeln!(out, "<div id='trace-{loan}' class='trace hidden'>")?;
551        out.write_fmt(format_args!("<div>Trace for loan {0}</div>\n", loan))writeln!(out, "<div>Trace for loan {loan}</div>")?;
552        out.write_fmt(format_args!("<ul>\n"))writeln!(out, "<ul>")?;
553        for (idx, node) in reachability.iter().enumerate() {
554            out.write_fmt(format_args!("<li>\n"))writeln!(out, "<li>")?;
555
556            let location = liveness.location_from_point(node.point);
557            let kind = if idx == 0 { "starts in" } else { "reaches" };
558            out.write_fmt(format_args!("<code>{1}</code> {2} <code>{0}</code>\n",
        node_name(node.region, location), loan, kind))writeln!(
559                out,
560                "<code>{loan}</code> {kind} <code>{}</code>",
561                node_name(node.region, location),
562            )?;
563
564            // It's useful to know whether the region we're reaching is live at this point.
565            let node_liveness =
566                if liveness.is_live_at(node.region, location) { "live" } else { "not live" };
567            out.write_fmt(format_args!("<span class=\'trace-suffix\'>\n"))writeln!(out, "<span class='trace-suffix'>")?;
568            out.write_fmt(format_args!("/ at <code>{0:?}</code>: <code>\'{1}</code> is {2}\n",
        location, node.region.index(), node_liveness))writeln!(
569                out,
570                "/ at <code>{:?}</code>: <code>'{}</code> is {}",
571                location,
572                node.region.index(),
573                node_liveness,
574            )?;
575            out.write_fmt(format_args!("</span>\n"))writeln!(out, "</span>")?;
576            out.write_fmt(format_args!("</li>\n"))writeln!(out, "</li>")?;
577        }
578        out.write_fmt(format_args!("</ul>\n"))writeln!(out, "</ul>")?;
579        out.write_fmt(format_args!("</div>\n"))writeln!(out, "</div>")?;
580    }
581
582    Ok(())
583}
584
585fn region_name(region: RegionVid) -> String {
586    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", region.index()))
    })format!("'{}", region.index())
587}
588/// A MIR location looks like `bb5[2]`. As that is not a syntactically valid mermaid node id,
589/// transform it into `BB5_2`.
590fn location_name(location: Location) -> String {
591    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("BB{0}_{1}", location.block.index(),
                location.statement_index))
    })format!("BB{}_{}", location.block.index(), location.statement_index)
592}
593fn node_name(region: RegionVid, location: Location) -> String {
594    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", region_name(region),
                location_name(location)))
    })format!("{}_{}", region_name(region), location_name(location))
595}