1//! As part of generating the regions, if you enable `-Zdump-mir=nll`,
2//! we will generate an annotated copy of the MIR that includes the
3//! state of region inference. This code handles emitting the region
4//! context internal state.
56use std::io::{self, Write};
78use rustc_infer::infer::NllRegionVariableOrigin;
9use rustc_middle::ty::TyCtxt;
1011use super::{OutlivesConstraint, RegionInferenceContext};
12use crate::type_check::Locations;
1314// Room for "'_#NNNNr" before things get misaligned.
15// Easy enough to fix if this ever doesn't seem like
16// enough.
17const REGION_WIDTH: usize = 8;
1819impl<'tcx> RegionInferenceContext<'tcx> {
20/// Write out our state into the `.mir` files.
21pub(crate) fn dump_mir(&self, tcx: TyCtxt<'tcx>, out: &mut dyn Write) -> io::Result<()> {
22writeln!(out, "| Free Region Mapping")?;
2324for region in self.regions() {
25if let NllRegionVariableOrigin::FreeRegion = self.definitions[region].origin {
26let classification =
27self.universal_regions().region_classification(region).unwrap();
28let outlived_by = self.universal_region_relations.regions_outlived_by(region);
29writeln!(
30 out,
31"| {r:rw$?} | {c:cw$?} | {ob:?}",
32 r = region,
33 rw = REGION_WIDTH,
34 c = classification,
35 cw = 8, // "External" at most
36ob = outlived_by
37 )?;
38 }
39 }
4041writeln!(out, "|")?;
42writeln!(out, "| Inferred Region Values")?;
43for region in self.regions() {
44writeln!(
45 out,
46"| {r:rw$?} | {ui:4?} | {v}",
47 r = region,
48 rw = REGION_WIDTH,
49 ui = self.region_universe(region),
50 v = self.region_value_str(region),
51 )?;
52 }
5354writeln!(out, "|")?;
55writeln!(out, "| Inference Constraints")?;
56self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {msg}"))?;
5758Ok(())
59 }
6061/// Debugging aid: Invokes the `with_msg` callback repeatedly with
62 /// our internal region constraints. These are dumped into the
63 /// -Zdump-mir file so that we can figure out why the region
64 /// inference resulted in the values that it did when debugging.
65fn for_each_constraint(
66&self,
67 tcx: TyCtxt<'tcx>,
68 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
69 ) -> io::Result<()> {
70for region in self.definitions.indices() {
71let value = self.liveness_constraints.pretty_print_live_points(region);
72if value != "{}" {
73 with_msg(&format!("{region:?} live at {value}"))?;
74 }
75 }
7677let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
78constraints.sort_by_key(|c| (c.sup, c.sub));
79for constraint in &constraints {
80let OutlivesConstraint { sup, sub, locations, category, span, .. } = constraint;
81let (name, arg) = match locations {
82 Locations::All(span) => {
83 ("All", tcx.sess.source_map().span_to_embeddable_string(*span))
84 }
85 Locations::Single(loc) => ("Single", format!("{loc:?}")),
86 };
87 with_msg(&format!("{sup:?}: {sub:?} due to {category:?} at {name}({arg}) ({span:?}"))?;
88 }
8990Ok(())
91 }
92}