rustc_middle/mir/
pretty.rs

1use std::collections::BTreeSet;
2use std::fmt::{Display, Write as _};
3use std::path::{Path, PathBuf};
4use std::{fs, io};
5
6use rustc_abi::Size;
7use rustc_ast::InlineAsmTemplatePiece;
8use tracing::trace;
9use ty::print::PrettyPrinter;
10
11use super::graphviz::write_mir_fn_graphviz;
12use crate::mir::interpret::{
13    AllocBytes, AllocId, Allocation, ConstAllocation, GlobalAlloc, Pointer, Provenance,
14    alloc_range, read_target_uint,
15};
16use crate::mir::visit::Visitor;
17use crate::mir::*;
18
19const INDENT: &str = "    ";
20/// Alignment for lining up comments following MIR statements
21pub(crate) const ALIGN: usize = 40;
22
23/// An indication of where we are in the control flow graph. Used for printing
24/// extra information in `dump_mir`
25#[derive(Clone, Copy)]
26pub enum PassWhere {
27    /// We have not started dumping the control flow graph, but we are about to.
28    BeforeCFG,
29
30    /// We just finished dumping the control flow graph. This is right before EOF
31    AfterCFG,
32
33    /// We are about to start dumping the given basic block.
34    BeforeBlock(BasicBlock),
35
36    /// We are just about to dump the given statement or terminator.
37    BeforeLocation(Location),
38
39    /// We just dumped the given statement or terminator.
40    AfterLocation(Location),
41
42    /// We just dumped the terminator for a block but not the closing `}`.
43    AfterTerminator(BasicBlock),
44}
45
46/// Cosmetic options for pretty-printing the MIR contents, gathered from the CLI. Each pass can
47/// override these when dumping its own specific MIR information with `dump_mir`.
48#[derive(Copy, Clone)]
49pub struct PrettyPrintMirOptions {
50    /// Whether to include extra comments, like span info. From `-Z mir-include-spans`.
51    pub include_extra_comments: bool,
52}
53
54impl PrettyPrintMirOptions {
55    /// Create the default set of MIR pretty-printing options from the CLI flags.
56    pub fn from_cli(tcx: TyCtxt<'_>) -> Self {
57        Self { include_extra_comments: tcx.sess.opts.unstable_opts.mir_include_spans.is_enabled() }
58    }
59}
60
61/// Manages MIR dumping, which is MIR writing done to a file with a specific name. In particular,
62/// it makes it impossible to dump MIR to one of these files when it hasn't been requested from the
63/// command line. Layered on top of `MirWriter`, which does the actual writing.
64pub struct MirDumper<'dis, 'de, 'tcx> {
65    show_pass_num: bool,
66    pass_name: &'static str,
67    disambiguator: &'dis dyn Display,
68    writer: MirWriter<'de, 'tcx>,
69}
70
71impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
72    // If dumping should be performed (e.g. because it was requested on the
73    // CLI), returns a `MirDumper` with default values for the following fields:
74    // - `show_pass_num`: `false`
75    // - `disambiguator`: `&0`
76    // - `writer.extra_data`: a no-op
77    // - `writer.options`: default options derived from CLI flags
78    pub fn new(tcx: TyCtxt<'tcx>, pass_name: &'static str, body: &Body<'tcx>) -> Option<Self> {
79        let dump_enabled = if let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir {
80            // see notes on #41697 below
81            let node_path = ty::print::with_no_trimmed_paths!(
82                ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()))
83            );
84            filters.split('|').any(|or_filter| {
85                or_filter.split('&').all(|and_filter| {
86                    let and_filter_trimmed = and_filter.trim();
87                    and_filter_trimmed == "all"
88                        || pass_name.contains(and_filter_trimmed)
89                        || node_path.contains(and_filter_trimmed)
90                })
91            })
92        } else {
93            false
94        };
95
96        dump_enabled.then_some(MirDumper {
97            show_pass_num: false,
98            pass_name,
99            disambiguator: &0,
100            writer: MirWriter::new(tcx),
101        })
102    }
103
104    pub fn tcx(&self) -> TyCtxt<'tcx> {
105        self.writer.tcx
106    }
107
108    #[must_use]
109    pub fn set_show_pass_num(mut self) -> Self {
110        self.show_pass_num = true;
111        self
112    }
113
114    #[must_use]
115    pub fn set_disambiguator(mut self, disambiguator: &'dis dyn Display) -> Self {
116        self.disambiguator = disambiguator;
117        self
118    }
119
120    #[must_use]
121    pub fn set_extra_data(
122        mut self,
123        extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
124    ) -> Self {
125        self.writer.extra_data = extra_data;
126        self
127    }
128
129    #[must_use]
130    pub fn set_options(mut self, options: PrettyPrintMirOptions) -> Self {
131        self.writer.options = options;
132        self
133    }
134
135    /// If the session is properly configured, dumps a human-readable representation of the MIR
136    /// (with default pretty-printing options) into:
137    ///
138    /// ```text
139    /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
140    /// ```
141    ///
142    /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
143    /// where `<filter>` takes the following forms:
144    ///
145    /// - `all` -- dump MIR for all fns, all passes, all everything
146    /// - a filter defined by a set of substrings combined with `&` and `|`
147    ///   (`&` has higher precedence). At least one of the `|`-separated groups
148    ///   must match; an `|`-separated group matches if all of its `&`-separated
149    ///   substrings are matched.
150    ///
151    /// Example:
152    ///
153    /// - `nll` == match if `nll` appears in the name
154    /// - `foo & nll` == match if `foo` and `nll` both appear in the name
155    /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
156    ///   or `typeck` appears in the name.
157    /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
158    ///   or `typeck` and `bar` both appear in the name.
159    pub fn dump_mir(&self, body: &Body<'tcx>) {
160        let _: io::Result<()> = try {
161            let mut file = self.create_dump_file("mir", body)?;
162            self.dump_mir_to_writer(body, &mut file)?;
163        };
164
165        if self.tcx().sess.opts.unstable_opts.dump_mir_graphviz {
166            let _: io::Result<()> = try {
167                let mut file = self.create_dump_file("dot", body)?;
168                write_mir_fn_graphviz(self.tcx(), body, false, &mut file)?;
169            };
170        }
171    }
172
173    // #41697 -- we use `with_forced_impl_filename_line()` because `def_path_str()` would otherwise
174    // trigger `type_of`, and this can run while we are already attempting to evaluate `type_of`.
175    pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
176        // see notes on #41697 above
177        let def_path =
178            ty::print::with_no_trimmed_paths!(ty::print::with_forced_impl_filename_line!(
179                self.tcx().def_path_str(body.source.def_id())
180            ));
181        // ignore-tidy-odd-backticks the literal below is fine
182        write!(w, "// MIR for `{def_path}")?;
183        match body.source.promoted {
184            None => write!(w, "`")?,
185            Some(promoted) => write!(w, "::{promoted:?}`")?,
186        }
187        writeln!(w, " {} {}", self.disambiguator, self.pass_name)?;
188        if let Some(ref layout) = body.coroutine_layout_raw() {
189            writeln!(w, "/* coroutine_layout = {layout:#?} */")?;
190        }
191        writeln!(w)?;
192        (self.writer.extra_data)(PassWhere::BeforeCFG, w)?;
193        write_user_type_annotations(self.tcx(), body, w)?;
194        self.writer.write_mir_fn(body, w)?;
195        (self.writer.extra_data)(PassWhere::AfterCFG, w)
196    }
197
198    /// Returns the path to the filename where we should dump a given MIR.
199    /// Also used by other bits of code (e.g., NLL inference) that dump
200    /// graphviz data or other things.
201    fn dump_path(&self, extension: &str, body: &Body<'tcx>) -> PathBuf {
202        let tcx = self.tcx();
203        let source = body.source;
204        let promotion_id = match source.promoted {
205            Some(id) => format!("-{id:?}"),
206            None => String::new(),
207        };
208
209        let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
210            String::new()
211        } else if self.show_pass_num {
212            let (dialect_index, phase_index) = body.phase.index();
213            format!(".{}-{}-{:03}", dialect_index, phase_index, body.pass_count)
214        } else {
215            ".-------".to_string()
216        };
217
218        let crate_name = tcx.crate_name(source.def_id().krate);
219        let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
220        // All drop shims have the same DefId, so we have to add the type
221        // to get unique file names.
222        let shim_disambiguator = match source.instance {
223            ty::InstanceKind::DropGlue(_, Some(ty)) => {
224                // Unfortunately, pretty-printed types are not very filename-friendly.
225                // We do some filtering.
226                let mut s = ".".to_owned();
227                s.extend(ty.to_string().chars().filter_map(|c| match c {
228                    ' ' => None,
229                    ':' | '<' | '>' => Some('_'),
230                    c => Some(c),
231                }));
232                s
233            }
234            ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
235                let mut s = ".".to_owned();
236                s.extend(ty.to_string().chars().filter_map(|c| match c {
237                    ' ' => None,
238                    ':' | '<' | '>' => Some('_'),
239                    c => Some(c),
240                }));
241                s
242            }
243            ty::InstanceKind::AsyncDropGlue(_, ty) => {
244                let ty::Coroutine(_, args) = ty.kind() else {
245                    bug!();
246                };
247                let ty = args.first().unwrap().expect_ty();
248                let mut s = ".".to_owned();
249                s.extend(ty.to_string().chars().filter_map(|c| match c {
250                    ' ' => None,
251                    ':' | '<' | '>' => Some('_'),
252                    c => Some(c),
253                }));
254                s
255            }
256            ty::InstanceKind::FutureDropPollShim(_, proxy_cor, impl_cor) => {
257                let mut s = ".".to_owned();
258                s.extend(proxy_cor.to_string().chars().filter_map(|c| match c {
259                    ' ' => None,
260                    ':' | '<' | '>' => Some('_'),
261                    c => Some(c),
262                }));
263                s.push('.');
264                s.extend(impl_cor.to_string().chars().filter_map(|c| match c {
265                    ' ' => None,
266                    ':' | '<' | '>' => Some('_'),
267                    c => Some(c),
268                }));
269                s
270            }
271            _ => String::new(),
272        };
273
274        let mut file_path = PathBuf::new();
275        file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
276
277        let pass_name = self.pass_name;
278        let disambiguator = self.disambiguator;
279        let file_name = format!(
280            "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}.{extension}",
281        );
282
283        file_path.push(&file_name);
284
285        file_path
286    }
287
288    /// Attempts to open a file where we should dump a given MIR or other
289    /// bit of MIR-related data. Used by `mir-dump`, but also by other
290    /// bits of code (e.g., NLL inference) that dump graphviz data or
291    /// other things, and hence takes the extension as an argument.
292    pub fn create_dump_file(
293        &self,
294        extension: &str,
295        body: &Body<'tcx>,
296    ) -> io::Result<io::BufWriter<fs::File>> {
297        let file_path = self.dump_path(extension, body);
298        if let Some(parent) = file_path.parent() {
299            fs::create_dir_all(parent).map_err(|e| {
300                io::Error::new(
301                    e.kind(),
302                    format!("IO error creating MIR dump directory: {parent:?}; {e}"),
303                )
304            })?;
305        }
306        fs::File::create_buffered(&file_path).map_err(|e| {
307            io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}"))
308        })
309    }
310}
311
312///////////////////////////////////////////////////////////////////////////
313// Whole MIR bodies
314
315/// Write out a human-readable textual representation for the given MIR, with the default
316/// [PrettyPrintMirOptions].
317pub fn write_mir_pretty<'tcx>(
318    tcx: TyCtxt<'tcx>,
319    single: Option<DefId>,
320    w: &mut dyn io::Write,
321) -> io::Result<()> {
322    let writer = MirWriter::new(tcx);
323
324    writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
325    writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
326    writeln!(w, "// HINT: See also -Z dump-mir for MIR at specific points during compilation.")?;
327
328    let mut first = true;
329    for def_id in dump_mir_def_ids(tcx, single) {
330        if first {
331            first = false;
332        } else {
333            // Put empty lines between all items
334            writeln!(w)?;
335        }
336
337        let render_body = |w: &mut dyn io::Write, body| -> io::Result<()> {
338            writer.write_mir_fn(body, w)?;
339
340            for body in tcx.promoted_mir(def_id) {
341                writeln!(w)?;
342                writer.write_mir_fn(body, w)?;
343            }
344            Ok(())
345        };
346
347        // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
348        if tcx.is_const_fn(def_id) {
349            render_body(w, tcx.optimized_mir(def_id))?;
350            writeln!(w)?;
351            writeln!(w, "// MIR FOR CTFE")?;
352            // Do not use `render_body`, as that would render the promoteds again, but these
353            // are shared between mir_for_ctfe and optimized_mir
354            writer.write_mir_fn(tcx.mir_for_ctfe(def_id), w)?;
355        } else {
356            let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id));
357            render_body(w, instance_mir)?;
358        }
359    }
360    Ok(())
361}
362
363/// Does the writing of MIR to output, e.g. a file.
364pub struct MirWriter<'de, 'tcx> {
365    tcx: TyCtxt<'tcx>,
366    extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
367    options: PrettyPrintMirOptions,
368}
369
370impl<'de, 'tcx> MirWriter<'de, 'tcx> {
371    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
372        MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
373    }
374
375    /// Write out a human-readable textual representation for the given function.
376    pub fn write_mir_fn(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
377        write_mir_intro(self.tcx, body, w, self.options)?;
378        for block in body.basic_blocks.indices() {
379            (self.extra_data)(PassWhere::BeforeBlock(block), w)?;
380            self.write_basic_block(block, body, w)?;
381            if block.index() + 1 != body.basic_blocks.len() {
382                writeln!(w)?;
383            }
384        }
385
386        writeln!(w, "}}")?;
387
388        write_allocations(self.tcx, body, w)?;
389
390        Ok(())
391    }
392}
393
394/// Prints local variables in a scope tree.
395fn write_scope_tree(
396    tcx: TyCtxt<'_>,
397    body: &Body<'_>,
398    scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
399    w: &mut dyn io::Write,
400    parent: SourceScope,
401    depth: usize,
402    options: PrettyPrintMirOptions,
403) -> io::Result<()> {
404    let indent = depth * INDENT.len();
405
406    // Local variable debuginfo.
407    for var_debug_info in &body.var_debug_info {
408        if var_debug_info.source_info.scope != parent {
409            // Not declared in this scope.
410            continue;
411        }
412
413        let indented_debug_info = format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
414
415        if options.include_extra_comments {
416            writeln!(
417                w,
418                "{0:1$} // in {2}",
419                indented_debug_info,
420                ALIGN,
421                comment(tcx, var_debug_info.source_info),
422            )?;
423        } else {
424            writeln!(w, "{indented_debug_info}")?;
425        }
426    }
427
428    // Local variable types.
429    for (local, local_decl) in body.local_decls.iter_enumerated() {
430        if (1..body.arg_count + 1).contains(&local.index()) {
431            // Skip over argument locals, they're printed in the signature.
432            continue;
433        }
434
435        if local_decl.source_info.scope != parent {
436            // Not declared in this scope.
437            continue;
438        }
439
440        let mut_str = local_decl.mutability.prefix_str();
441
442        let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
443            "{0:1$}let {2}{3:?}: {4}",
444            INDENT, indent, mut_str, local, local_decl.ty
445        ));
446        if let Some(user_ty) = &local_decl.user_ty {
447            for user_ty in user_ty.projections() {
448                write!(indented_decl, " as {user_ty:?}").unwrap();
449            }
450        }
451        indented_decl.push(';');
452
453        let local_name = if local == RETURN_PLACE { " return place" } else { "" };
454
455        if options.include_extra_comments {
456            writeln!(
457                w,
458                "{0:1$} //{2} in {3}",
459                indented_decl,
460                ALIGN,
461                local_name,
462                comment(tcx, local_decl.source_info),
463            )?;
464        } else {
465            writeln!(w, "{indented_decl}",)?;
466        }
467    }
468
469    let Some(children) = scope_tree.get(&parent) else {
470        return Ok(());
471    };
472
473    for &child in children {
474        let child_data = &body.source_scopes[child];
475        assert_eq!(child_data.parent_scope, Some(parent));
476
477        let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
478            (
479                format!(
480                    " (inlined {}{})",
481                    if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
482                    callee
483                ),
484                Some(callsite_span),
485            )
486        } else {
487            (String::new(), None)
488        };
489
490        let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
491
492        if options.include_extra_comments {
493            if let Some(span) = span {
494                writeln!(
495                    w,
496                    "{0:1$} // at {2}",
497                    indented_header,
498                    ALIGN,
499                    tcx.sess.source_map().span_to_embeddable_string(span),
500                )?;
501            } else {
502                writeln!(w, "{indented_header}")?;
503            }
504        } else {
505            writeln!(w, "{indented_header}")?;
506        }
507
508        write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
509        writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
510    }
511
512    Ok(())
513}
514
515impl Debug for VarDebugInfo<'_> {
516    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
517        if let Some(box VarDebugInfoFragment { ty, ref projection }) = self.composite {
518            pre_fmt_projection(&projection[..], fmt)?;
519            write!(fmt, "({}: {})", self.name, ty)?;
520            post_fmt_projection(&projection[..], fmt)?;
521        } else {
522            write!(fmt, "{}", self.name)?;
523        }
524
525        write!(fmt, " => {:?}", self.value)
526    }
527}
528
529/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
530/// local variables (both user-defined bindings and compiler temporaries).
531fn write_mir_intro<'tcx>(
532    tcx: TyCtxt<'tcx>,
533    body: &Body<'_>,
534    w: &mut dyn io::Write,
535    options: PrettyPrintMirOptions,
536) -> io::Result<()> {
537    write_mir_sig(tcx, body, w)?;
538    writeln!(w, "{{")?;
539
540    // construct a scope tree and write it out
541    let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
542    for (index, scope_data) in body.source_scopes.iter_enumerated() {
543        if let Some(parent) = scope_data.parent_scope {
544            scope_tree.entry(parent).or_default().push(index);
545        } else {
546            // Only the argument scope has no parent, because it's the root.
547            assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
548        }
549    }
550
551    write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
552
553    // Add an empty line before the first block is printed.
554    writeln!(w)?;
555
556    if let Some(coverage_info_hi) = &body.coverage_info_hi {
557        write_coverage_info_hi(coverage_info_hi, w)?;
558    }
559    if let Some(function_coverage_info) = &body.function_coverage_info {
560        write_function_coverage_info(function_coverage_info, w)?;
561    }
562
563    Ok(())
564}
565
566fn write_coverage_info_hi(
567    coverage_info_hi: &coverage::CoverageInfoHi,
568    w: &mut dyn io::Write,
569) -> io::Result<()> {
570    let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
571
572    // Only add an extra trailing newline if we printed at least one thing.
573    let mut did_print = false;
574
575    for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
576        writeln!(
577            w,
578            "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
579        )?;
580        did_print = true;
581    }
582
583    if did_print {
584        writeln!(w)?;
585    }
586
587    Ok(())
588}
589
590fn write_function_coverage_info(
591    function_coverage_info: &coverage::FunctionCoverageInfo,
592    w: &mut dyn io::Write,
593) -> io::Result<()> {
594    let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
595
596    for coverage::Mapping { kind, span } in mappings {
597        writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
598    }
599    writeln!(w)?;
600
601    Ok(())
602}
603
604fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
605    use rustc_hir::def::DefKind;
606
607    trace!("write_mir_sig: {:?}", body.source.instance);
608    let def_id = body.source.def_id();
609    let kind = tcx.def_kind(def_id);
610    let is_function = match kind {
611        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
612            true
613        }
614        _ => tcx.is_closure_like(def_id),
615    };
616    match (kind, body.source.promoted) {
617        (_, Some(_)) => write!(w, "const ")?, // promoteds are the closest to consts
618        (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
619        (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
620            write!(w, "static ")?
621        }
622        (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
623            write!(w, "static mut ")?
624        }
625        (_, _) if is_function => write!(w, "fn ")?,
626        // things like anon const, not an item
627        (DefKind::AnonConst | DefKind::InlineConst, _) => {}
628        // `global_asm!` have fake bodies, which we may dump after mir-build
629        (DefKind::GlobalAsm, _) => {}
630        _ => bug!("Unexpected def kind {:?}", kind),
631    }
632
633    ty::print::with_forced_impl_filename_line! {
634        // see notes on #41697 elsewhere
635        write!(w, "{}", tcx.def_path_str(def_id))?
636    }
637    if let Some(p) = body.source.promoted {
638        write!(w, "::{p:?}")?;
639    }
640
641    if body.source.promoted.is_none() && is_function {
642        write!(w, "(")?;
643
644        // fn argument types.
645        for (i, arg) in body.args_iter().enumerate() {
646            if i != 0 {
647                write!(w, ", ")?;
648            }
649            write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
650        }
651
652        write!(w, ") -> {}", body.return_ty())?;
653    } else {
654        assert_eq!(body.arg_count, 0);
655        write!(w, ": {} =", body.return_ty())?;
656    }
657
658    if let Some(yield_ty) = body.yield_ty() {
659        writeln!(w)?;
660        writeln!(w, "yields {yield_ty}")?;
661    }
662
663    write!(w, " ")?;
664    // Next thing that gets printed is the opening {
665
666    Ok(())
667}
668
669fn write_user_type_annotations(
670    tcx: TyCtxt<'_>,
671    body: &Body<'_>,
672    w: &mut dyn io::Write,
673) -> io::Result<()> {
674    if !body.user_type_annotations.is_empty() {
675        writeln!(w, "| User Type Annotations")?;
676    }
677    for (index, annotation) in body.user_type_annotations.iter_enumerated() {
678        writeln!(
679            w,
680            "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
681            index.index(),
682            annotation.user_ty,
683            tcx.sess.source_map().span_to_embeddable_string(annotation.span),
684            with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
685        )?;
686    }
687    if !body.user_type_annotations.is_empty() {
688        writeln!(w, "|")?;
689    }
690    Ok(())
691}
692
693pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
694    if let Some(i) = single {
695        vec![i]
696    } else {
697        tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
698    }
699}
700
701///////////////////////////////////////////////////////////////////////////
702// Basic blocks and their parts (statements, terminators, ...)
703
704impl<'de, 'tcx> MirWriter<'de, 'tcx> {
705    /// Write out a human-readable textual representation for the given basic block.
706    fn write_basic_block(
707        &self,
708        block: BasicBlock,
709        body: &Body<'tcx>,
710        w: &mut dyn io::Write,
711    ) -> io::Result<()> {
712        let data = &body[block];
713
714        // Basic block label at the top.
715        let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
716        writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
717
718        // List of statements in the middle.
719        let mut current_location = Location { block, statement_index: 0 };
720        for statement in &data.statements {
721            (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
722
723            for debuginfo in statement.debuginfos.iter() {
724                writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
725            }
726
727            let indented_body = format!("{INDENT}{INDENT}{statement:?};");
728            if self.options.include_extra_comments {
729                writeln!(
730                    w,
731                    "{:A$} // {}{}",
732                    indented_body,
733                    if self.tcx.sess.verbose_internals() {
734                        format!("{current_location:?}: ")
735                    } else {
736                        String::new()
737                    },
738                    comment(self.tcx, statement.source_info),
739                    A = ALIGN,
740                )?;
741            } else {
742                writeln!(w, "{indented_body}")?;
743            }
744
745            write_extra(
746                self.tcx,
747                w,
748                &|visitor| visitor.visit_statement(statement, current_location),
749                self.options,
750            )?;
751
752            (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
753
754            current_location.statement_index += 1;
755        }
756
757        for debuginfo in data.after_last_stmt_debuginfos.iter() {
758            writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
759        }
760
761        // Terminator at the bottom.
762        (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
763        if data.terminator.is_some() {
764            let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
765            if self.options.include_extra_comments {
766                writeln!(
767                    w,
768                    "{:A$} // {}{}",
769                    indented_terminator,
770                    if self.tcx.sess.verbose_internals() {
771                        format!("{current_location:?}: ")
772                    } else {
773                        String::new()
774                    },
775                    comment(self.tcx, data.terminator().source_info),
776                    A = ALIGN,
777                )?;
778            } else {
779                writeln!(w, "{indented_terminator}")?;
780            }
781
782            write_extra(
783                self.tcx,
784                w,
785                &|visitor| visitor.visit_terminator(data.terminator(), current_location),
786                self.options,
787            )?;
788        }
789
790        (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
791        (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
792
793        writeln!(w, "{INDENT}}}")
794    }
795}
796
797impl Debug for Statement<'_> {
798    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
799        use self::StatementKind::*;
800        match self.kind {
801            Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
802            FakeRead(box (ref cause, ref place)) => {
803                write!(fmt, "FakeRead({cause:?}, {place:?})")
804            }
805            Retag(ref kind, ref place) => write!(
806                fmt,
807                "Retag({}{:?})",
808                match kind {
809                    RetagKind::FnEntry => "[fn entry] ",
810                    RetagKind::TwoPhase => "[2phase] ",
811                    RetagKind::Raw => "[raw] ",
812                    RetagKind::Default => "",
813                },
814                place,
815            ),
816            StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
817            StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
818            SetDiscriminant { ref place, variant_index } => {
819                write!(fmt, "discriminant({place:?}) = {variant_index:?}")
820            }
821            PlaceMention(ref place) => {
822                write!(fmt, "PlaceMention({place:?})")
823            }
824            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
825                write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
826            }
827            Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
828            Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
829            ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
830            Nop => write!(fmt, "nop"),
831            BackwardIncompatibleDropHint { ref place, reason: _ } => {
832                // For now, we don't record the reason because there is only one use case,
833                // which is to report breaking change in drop order by Edition 2024
834                write!(fmt, "BackwardIncompatibleDropHint({place:?})")
835            }
836        }
837    }
838}
839
840impl Debug for StmtDebugInfo<'_> {
841    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
842        match self {
843            StmtDebugInfo::AssignRef(local, place) => {
844                write!(fmt, "{local:?} = &{place:?}")
845            }
846            StmtDebugInfo::InvalidAssign(local) => {
847                write!(fmt, "{local:?} = &?")
848            }
849        }
850    }
851}
852
853impl Display for NonDivergingIntrinsic<'_> {
854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855        match self {
856            Self::Assume(op) => write!(f, "assume({op:?})"),
857            Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
858                write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
859            }
860        }
861    }
862}
863
864impl<'tcx> Debug for TerminatorKind<'tcx> {
865    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
866        self.fmt_head(fmt)?;
867        let successor_count = self.successors().count();
868        let labels = self.fmt_successor_labels();
869        assert_eq!(successor_count, labels.len());
870
871        // `Cleanup` is already included in successors
872        let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
873        let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
874            write!(fmt, "unwind ")?;
875            match self.unwind() {
876                // Not needed or included in successors
877                None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
878                Some(UnwindAction::Continue) => write!(fmt, "continue"),
879                Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
880                Some(UnwindAction::Terminate(reason)) => {
881                    write!(fmt, "terminate({})", reason.as_short_str())
882                }
883            }
884        };
885
886        match (successor_count, show_unwind) {
887            (0, false) => Ok(()),
888            (0, true) => {
889                write!(fmt, " -> ")?;
890                fmt_unwind(fmt)
891            }
892            (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
893            _ => {
894                write!(fmt, " -> [")?;
895                for (i, target) in self.successors().enumerate() {
896                    if i > 0 {
897                        write!(fmt, ", ")?;
898                    }
899                    write!(fmt, "{}: {:?}", labels[i], target)?;
900                }
901                if show_unwind {
902                    write!(fmt, ", ")?;
903                    fmt_unwind(fmt)?;
904                }
905                write!(fmt, "]")
906            }
907        }
908    }
909}
910
911impl<'tcx> TerminatorKind<'tcx> {
912    /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
913    /// successor basic block, if any. The only information not included is the list of possible
914    /// successors, which may be rendered differently between the text and the graphviz format.
915    pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
916        use self::TerminatorKind::*;
917        match self {
918            Goto { .. } => write!(fmt, "goto"),
919            SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
920            Return => write!(fmt, "return"),
921            CoroutineDrop => write!(fmt, "coroutine_drop"),
922            UnwindResume => write!(fmt, "resume"),
923            UnwindTerminate(reason) => {
924                write!(fmt, "terminate({})", reason.as_short_str())
925            }
926            Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
927            Unreachable => write!(fmt, "unreachable"),
928            Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
929            Drop { place, async_fut: Some(async_fut), .. } => {
930                write!(fmt, "async drop({place:?}; poll={async_fut:?})")
931            }
932            Call { func, args, destination, .. } => {
933                write!(fmt, "{destination:?} = ")?;
934                write!(fmt, "{func:?}(")?;
935                for (index, arg) in args.iter().enumerate() {
936                    if index > 0 {
937                        write!(fmt, ", ")?;
938                    }
939                    write!(fmt, "{:?}", arg.node)?;
940                }
941                write!(fmt, ")")
942            }
943            TailCall { func, args, .. } => {
944                write!(fmt, "tailcall {func:?}(")?;
945                for (index, arg) in args.iter().enumerate() {
946                    if index > 0 {
947                        write!(fmt, ", ")?;
948                    }
949                    write!(fmt, "{:?}", arg.node)?;
950                }
951                write!(fmt, ")")
952            }
953            Assert { cond, expected, msg, .. } => {
954                write!(fmt, "assert(")?;
955                if !expected {
956                    write!(fmt, "!")?;
957                }
958                write!(fmt, "{cond:?}, ")?;
959                msg.fmt_assert_args(fmt)?;
960                write!(fmt, ")")
961            }
962            FalseEdge { .. } => write!(fmt, "falseEdge"),
963            FalseUnwind { .. } => write!(fmt, "falseUnwind"),
964            InlineAsm { template, operands, options, .. } => {
965                write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
966                for op in operands {
967                    write!(fmt, ", ")?;
968                    let print_late = |&late| if late { "late" } else { "" };
969                    match op {
970                        InlineAsmOperand::In { reg, value } => {
971                            write!(fmt, "in({reg}) {value:?}")?;
972                        }
973                        InlineAsmOperand::Out { reg, late, place: Some(place) } => {
974                            write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
975                        }
976                        InlineAsmOperand::Out { reg, late, place: None } => {
977                            write!(fmt, "{}out({}) _", print_late(late), reg)?;
978                        }
979                        InlineAsmOperand::InOut {
980                            reg,
981                            late,
982                            in_value,
983                            out_place: Some(out_place),
984                        } => {
985                            write!(
986                                fmt,
987                                "in{}out({}) {:?} => {:?}",
988                                print_late(late),
989                                reg,
990                                in_value,
991                                out_place
992                            )?;
993                        }
994                        InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
995                            write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
996                        }
997                        InlineAsmOperand::Const { value } => {
998                            write!(fmt, "const {value:?}")?;
999                        }
1000                        InlineAsmOperand::SymFn { value } => {
1001                            write!(fmt, "sym_fn {value:?}")?;
1002                        }
1003                        InlineAsmOperand::SymStatic { def_id } => {
1004                            write!(fmt, "sym_static {def_id:?}")?;
1005                        }
1006                        InlineAsmOperand::Label { target_index } => {
1007                            write!(fmt, "label {target_index}")?;
1008                        }
1009                    }
1010                }
1011                write!(fmt, ", options({options:?}))")
1012            }
1013        }
1014    }
1015
1016    /// Returns the list of labels for the edges to the successor basic blocks.
1017    pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1018        use self::TerminatorKind::*;
1019        match *self {
1020            Return
1021            | TailCall { .. }
1022            | UnwindResume
1023            | UnwindTerminate(_)
1024            | Unreachable
1025            | CoroutineDrop => vec![],
1026            Goto { .. } => vec!["".into()],
1027            SwitchInt { ref targets, .. } => targets
1028                .values
1029                .iter()
1030                .map(|&u| Cow::Owned(u.to_string()))
1031                .chain(iter::once("otherwise".into()))
1032                .collect(),
1033            Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1034                vec!["return".into(), "unwind".into()]
1035            }
1036            Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1037            Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1038            Call { target: None, unwind: _, .. } => vec![],
1039            Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1040            Yield { drop: None, .. } => vec!["resume".into()],
1041            Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1042                vec!["return".into(), "unwind".into(), "drop".into()]
1043            }
1044            Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1045                vec!["return".into(), "unwind".into()]
1046            }
1047            Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1048            Drop { unwind: _, .. } => vec!["return".into()],
1049            Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1050                vec!["success".into(), "unwind".into()]
1051            }
1052            Assert { unwind: _, .. } => vec!["success".into()],
1053            FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1054            FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1055                vec!["real".into(), "unwind".into()]
1056            }
1057            FalseUnwind { unwind: _, .. } => vec!["real".into()],
1058            InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1059                let mut vec = Vec::with_capacity(targets.len() + 1);
1060                if !asm_macro.diverges(options) {
1061                    vec.push("return".into());
1062                }
1063                vec.resize(targets.len(), "label".into());
1064
1065                if let UnwindAction::Cleanup(_) = unwind {
1066                    vec.push("unwind".into());
1067                }
1068
1069                vec
1070            }
1071        }
1072    }
1073}
1074
1075impl<'tcx> Debug for Rvalue<'tcx> {
1076    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1077        use self::Rvalue::*;
1078
1079        match *self {
1080            Use(ref place) => write!(fmt, "{place:?}"),
1081            Repeat(ref a, b) => {
1082                write!(fmt, "[{a:?}; ")?;
1083                pretty_print_const(b, fmt, false)?;
1084                write!(fmt, "]")
1085            }
1086            Cast(ref kind, ref place, ref ty) => {
1087                with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1088            }
1089            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1090            UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1091            Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1092            NullaryOp(ref op, ref t) => {
1093                let t = with_no_trimmed_paths!(format!("{}", t));
1094                match op {
1095                    NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
1096                    NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
1097                    NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1098                    NullOp::UbChecks => write!(fmt, "UbChecks()"),
1099                    NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1100                }
1101            }
1102            ThreadLocalRef(did) => ty::tls::with(|tcx| {
1103                let muta = tcx.static_mutability(did).unwrap().prefix_str();
1104                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1105            }),
1106            Ref(region, borrow_kind, ref place) => {
1107                let kind_str = match borrow_kind {
1108                    BorrowKind::Shared => "",
1109                    BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1110                    BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1111                    BorrowKind::Mut { .. } => "mut ",
1112                };
1113
1114                // When printing regions, add trailing space if necessary.
1115                let print_region = ty::tls::with(|tcx| {
1116                    tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1117                });
1118                let region = if print_region {
1119                    let mut region = region.to_string();
1120                    if !region.is_empty() {
1121                        region.push(' ');
1122                    }
1123                    region
1124                } else {
1125                    // Do not even print 'static
1126                    String::new()
1127                };
1128                write!(fmt, "&{region}{kind_str}{place:?}")
1129            }
1130
1131            CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1132
1133            RawPtr(mutability, ref place) => {
1134                write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1135            }
1136
1137            Aggregate(ref kind, ref places) => {
1138                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1139                    let mut tuple_fmt = fmt.debug_tuple(name);
1140                    for place in places {
1141                        tuple_fmt.field(place);
1142                    }
1143                    tuple_fmt.finish()
1144                };
1145
1146                match **kind {
1147                    AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1148
1149                    AggregateKind::Tuple => {
1150                        if places.is_empty() {
1151                            write!(fmt, "()")
1152                        } else {
1153                            fmt_tuple(fmt, "")
1154                        }
1155                    }
1156
1157                    AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1158                        ty::tls::with(|tcx| {
1159                            let variant_def = &tcx.adt_def(adt_did).variant(variant);
1160                            let args = tcx.lift(args).expect("could not lift for printing");
1161                            let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1162                                p.print_def_path(variant_def.def_id, args)
1163                            })?;
1164
1165                            match variant_def.ctor_kind() {
1166                                Some(CtorKind::Const) => fmt.write_str(&name),
1167                                Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1168                                None => {
1169                                    let mut struct_fmt = fmt.debug_struct(&name);
1170                                    for (field, place) in iter::zip(&variant_def.fields, places) {
1171                                        struct_fmt.field(field.name.as_str(), place);
1172                                    }
1173                                    struct_fmt.finish()
1174                                }
1175                            }
1176                        })
1177                    }
1178
1179                    AggregateKind::Closure(def_id, args)
1180                    | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1181                        let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1182                            let args = tcx.lift(args).unwrap();
1183                            format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1184                        } else {
1185                            let span = tcx.def_span(def_id);
1186                            format!(
1187                                "{{closure@{}}}",
1188                                tcx.sess.source_map().span_to_diagnostic_string(span)
1189                            )
1190                        };
1191                        let mut struct_fmt = fmt.debug_struct(&name);
1192
1193                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1194                        if let Some(def_id) = def_id.as_local()
1195                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1196                        {
1197                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1198                                let var_name = tcx.hir_name(var_id);
1199                                struct_fmt.field(var_name.as_str(), place);
1200                            }
1201                        } else {
1202                            for (index, place) in places.iter().enumerate() {
1203                                struct_fmt.field(&format!("{index}"), place);
1204                            }
1205                        }
1206
1207                        struct_fmt.finish()
1208                    }),
1209
1210                    AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1211                        let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1212                        let mut struct_fmt = fmt.debug_struct(&name);
1213
1214                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1215                        if let Some(def_id) = def_id.as_local()
1216                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1217                        {
1218                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1219                                let var_name = tcx.hir_name(var_id);
1220                                struct_fmt.field(var_name.as_str(), place);
1221                            }
1222                        } else {
1223                            for (index, place) in places.iter().enumerate() {
1224                                struct_fmt.field(&format!("{index}"), place);
1225                            }
1226                        }
1227
1228                        struct_fmt.finish()
1229                    }),
1230
1231                    AggregateKind::RawPtr(pointee_ty, mutability) => {
1232                        let kind_str = match mutability {
1233                            Mutability::Mut => "mut",
1234                            Mutability::Not => "const",
1235                        };
1236                        with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1237                        fmt_tuple(fmt, "")
1238                    }
1239                }
1240            }
1241
1242            ShallowInitBox(ref place, ref ty) => {
1243                with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1244            }
1245
1246            WrapUnsafeBinder(ref op, ty) => {
1247                with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1248            }
1249        }
1250    }
1251}
1252
1253impl<'tcx> Debug for Operand<'tcx> {
1254    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1255        use self::Operand::*;
1256        match *self {
1257            Constant(ref a) => write!(fmt, "{a:?}"),
1258            Copy(ref place) => write!(fmt, "copy {place:?}"),
1259            Move(ref place) => write!(fmt, "move {place:?}"),
1260        }
1261    }
1262}
1263
1264impl<'tcx> Debug for ConstOperand<'tcx> {
1265    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1266        write!(fmt, "{self}")
1267    }
1268}
1269
1270impl<'tcx> Display for ConstOperand<'tcx> {
1271    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1272        match self.ty().kind() {
1273            ty::FnDef(..) => {}
1274            _ => write!(fmt, "const ")?,
1275        }
1276        Display::fmt(&self.const_, fmt)
1277    }
1278}
1279
1280impl Debug for Place<'_> {
1281    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1282        self.as_ref().fmt(fmt)
1283    }
1284}
1285
1286impl Debug for PlaceRef<'_> {
1287    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1288        pre_fmt_projection(self.projection, fmt)?;
1289        write!(fmt, "{:?}", self.local)?;
1290        post_fmt_projection(self.projection, fmt)
1291    }
1292}
1293
1294fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1295    for &elem in projection.iter().rev() {
1296        match elem {
1297            ProjectionElem::OpaqueCast(_)
1298            | ProjectionElem::Downcast(_, _)
1299            | ProjectionElem::Field(_, _) => {
1300                write!(fmt, "(")?;
1301            }
1302            ProjectionElem::Deref => {
1303                write!(fmt, "(*")?;
1304            }
1305            ProjectionElem::Index(_)
1306            | ProjectionElem::ConstantIndex { .. }
1307            | ProjectionElem::Subslice { .. } => {}
1308            ProjectionElem::UnwrapUnsafeBinder(_) => {
1309                write!(fmt, "unwrap_binder!(")?;
1310            }
1311        }
1312    }
1313
1314    Ok(())
1315}
1316
1317fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1318    for &elem in projection.iter() {
1319        match elem {
1320            ProjectionElem::OpaqueCast(ty) => {
1321                write!(fmt, " as {ty})")?;
1322            }
1323            ProjectionElem::Downcast(Some(name), _index) => {
1324                write!(fmt, " as {name})")?;
1325            }
1326            ProjectionElem::Downcast(None, index) => {
1327                write!(fmt, " as variant#{index:?})")?;
1328            }
1329            ProjectionElem::Deref => {
1330                write!(fmt, ")")?;
1331            }
1332            ProjectionElem::Field(field, ty) => {
1333                with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1334            }
1335            ProjectionElem::Index(ref index) => {
1336                write!(fmt, "[{index:?}]")?;
1337            }
1338            ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1339                write!(fmt, "[{offset:?} of {min_length:?}]")?;
1340            }
1341            ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1342                write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1343            }
1344            ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1345                write!(fmt, "[{from:?}:]")?;
1346            }
1347            ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1348                write!(fmt, "[:-{to:?}]")?;
1349            }
1350            ProjectionElem::Subslice { from, to, from_end: true } => {
1351                write!(fmt, "[{from:?}:-{to:?}]")?;
1352            }
1353            ProjectionElem::Subslice { from, to, from_end: false } => {
1354                write!(fmt, "[{from:?}..{to:?}]")?;
1355            }
1356            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1357                write!(fmt, "; {ty})")?;
1358            }
1359        }
1360    }
1361
1362    Ok(())
1363}
1364
1365/// After we print the main statement, we sometimes dump extra
1366/// information. There's often a lot of little things "nuzzled up" in
1367/// a statement.
1368fn write_extra<'tcx>(
1369    tcx: TyCtxt<'tcx>,
1370    write: &mut dyn io::Write,
1371    visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1372    options: PrettyPrintMirOptions,
1373) -> io::Result<()> {
1374    if options.include_extra_comments {
1375        let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1376        visit_op(&mut extra_comments);
1377        for comment in extra_comments.comments {
1378            writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1379        }
1380    }
1381    Ok(())
1382}
1383
1384struct ExtraComments<'tcx> {
1385    tcx: TyCtxt<'tcx>,
1386    comments: Vec<String>,
1387}
1388
1389impl<'tcx> ExtraComments<'tcx> {
1390    fn push(&mut self, lines: &str) {
1391        for line in lines.split('\n') {
1392            self.comments.push(line.to_string());
1393        }
1394    }
1395}
1396
1397fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1398    match *ty.kind() {
1399        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1400        // Unit type
1401        ty::Tuple(g_args) if g_args.is_empty() => false,
1402        ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1403        ty::Array(ty, _) => use_verbose(ty, fn_def),
1404        ty::FnDef(..) => fn_def,
1405        _ => true,
1406    }
1407}
1408
1409impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1410    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1411        let ConstOperand { span, user_ty, const_ } = constant;
1412        if use_verbose(const_.ty(), true) {
1413            self.push("mir::ConstOperand");
1414            self.push(&format!(
1415                "+ span: {}",
1416                self.tcx.sess.source_map().span_to_embeddable_string(*span)
1417            ));
1418            if let Some(user_ty) = user_ty {
1419                self.push(&format!("+ user_ty: {user_ty:?}"));
1420            }
1421
1422            let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1423                let tcx = self.tcx;
1424                rustc_data_structures::make_display(move |fmt| {
1425                    pretty_print_const_value_tcx(tcx, val, ty, fmt)
1426                })
1427            };
1428
1429            let fmt_valtree = |cv: &ty::Value<'tcx>| {
1430                let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1431                p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1432                p.into_buffer()
1433            };
1434
1435            let val = match const_ {
1436                Const::Ty(_, ct) => match ct.kind() {
1437                    ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1438                    ty::ConstKind::Unevaluated(uv) => {
1439                        format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1440                    }
1441                    ty::ConstKind::Value(cv) => {
1442                        format!("ty::Valtree({})", fmt_valtree(&cv))
1443                    }
1444                    // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
1445                    ty::ConstKind::Error(_) => "Error".to_string(),
1446                    // These variants shouldn't exist in the MIR.
1447                    ty::ConstKind::Placeholder(_)
1448                    | ty::ConstKind::Infer(_)
1449                    | ty::ConstKind::Expr(_)
1450                    | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1451                },
1452                Const::Unevaluated(uv, _) => {
1453                    format!(
1454                        "Unevaluated({}, {:?}, {:?})",
1455                        self.tcx.def_path_str(uv.def),
1456                        uv.args,
1457                        uv.promoted,
1458                    )
1459                }
1460                Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1461            };
1462
1463            // This reflects what `Const` looked liked before `val` was renamed
1464            // as `kind`. We print it like this to avoid having to update
1465            // expected output in a lot of tests.
1466            self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1467        }
1468    }
1469
1470    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1471        self.super_rvalue(rvalue, location);
1472        if let Rvalue::Aggregate(kind, _) = rvalue {
1473            match **kind {
1474                AggregateKind::Closure(def_id, args) => {
1475                    self.push("closure");
1476                    self.push(&format!("+ def_id: {def_id:?}"));
1477                    self.push(&format!("+ args: {args:#?}"));
1478                }
1479
1480                AggregateKind::Coroutine(def_id, args) => {
1481                    self.push("coroutine");
1482                    self.push(&format!("+ def_id: {def_id:?}"));
1483                    self.push(&format!("+ args: {args:#?}"));
1484                    self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1485                }
1486
1487                AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1488                    self.push("adt");
1489                    self.push(&format!("+ user_ty: {user_ty:?}"));
1490                }
1491
1492                _ => {}
1493            }
1494        }
1495    }
1496}
1497
1498fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1499    let location = tcx.sess.source_map().span_to_embeddable_string(span);
1500    format!("scope {} at {}", scope.index(), location,)
1501}
1502
1503///////////////////////////////////////////////////////////////////////////
1504// Allocations
1505
1506/// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
1507/// allocations.
1508pub fn write_allocations<'tcx>(
1509    tcx: TyCtxt<'tcx>,
1510    body: &Body<'_>,
1511    w: &mut dyn io::Write,
1512) -> io::Result<()> {
1513    fn alloc_ids_from_alloc(
1514        alloc: ConstAllocation<'_>,
1515    ) -> impl DoubleEndedIterator<Item = AllocId> {
1516        alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1517    }
1518
1519    fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1520        match val {
1521            ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1522            ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1523            ConstValue::ZeroSized => None,
1524            ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1525                // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
1526                // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
1527                Some(alloc_id)
1528            }
1529        }
1530    }
1531    struct CollectAllocIds(BTreeSet<AllocId>);
1532
1533    impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1534        fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1535            match c.const_ {
1536                Const::Ty(_, _) | Const::Unevaluated(..) => {}
1537                Const::Val(val, _) => {
1538                    if let Some(id) = alloc_id_from_const_val(val) {
1539                        self.0.insert(id);
1540                    }
1541                }
1542            }
1543        }
1544    }
1545
1546    let mut visitor = CollectAllocIds(Default::default());
1547    visitor.visit_body(body);
1548
1549    // `seen` contains all seen allocations, including the ones we have *not* printed yet.
1550    // The protocol is to first `insert` into `seen`, and only if that returns `true`
1551    // then push to `todo`.
1552    let mut seen = visitor.0;
1553    let mut todo: Vec<_> = seen.iter().copied().collect();
1554    while let Some(id) = todo.pop() {
1555        let mut write_allocation_track_relocs =
1556            |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1557                // `.rev()` because we are popping them from the back of the `todo` vector.
1558                for id in alloc_ids_from_alloc(alloc).rev() {
1559                    if seen.insert(id) {
1560                        todo.push(id);
1561                    }
1562                }
1563                write!(w, "{}", display_allocation(tcx, alloc.inner()))
1564            };
1565        write!(w, "\n{id:?}")?;
1566        match tcx.try_get_global_alloc(id) {
1567            // This can't really happen unless there are bugs, but it doesn't cost us anything to
1568            // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
1569            None => write!(w, " (deallocated)")?,
1570            Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1571            Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1572                write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1573            }
1574            Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1575            Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1576                write!(w, " (static: {}", tcx.def_path_str(did))?;
1577                if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1578                    && body
1579                        .source
1580                        .def_id()
1581                        .as_local()
1582                        .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1583                {
1584                    // Statics may be cyclic and evaluating them too early
1585                    // in the MIR pipeline may cause cycle errors even though
1586                    // normal compilation is fine.
1587                    write!(w, ")")?;
1588                } else {
1589                    match tcx.eval_static_initializer(did) {
1590                        Ok(alloc) => {
1591                            write!(w, ", ")?;
1592                            write_allocation_track_relocs(w, alloc)?;
1593                        }
1594                        Err(_) => write!(w, ", error during initializer evaluation)")?,
1595                    }
1596                }
1597            }
1598            Some(GlobalAlloc::Static(did)) => {
1599                write!(w, " (extern static: {})", tcx.def_path_str(did))?
1600            }
1601            Some(GlobalAlloc::Memory(alloc)) => {
1602                write!(w, " (")?;
1603                write_allocation_track_relocs(w, alloc)?
1604            }
1605        }
1606        writeln!(w)?;
1607    }
1608    Ok(())
1609}
1610
1611/// Dumps the size and metadata and content of an allocation to the given writer.
1612/// The expectation is that the caller first prints other relevant metadata, so the exact
1613/// format of this function is (*without* leading or trailing newline):
1614///
1615/// ```text
1616/// size: {}, align: {}) {
1617///     <bytes>
1618/// }
1619/// ```
1620///
1621/// The byte format is similar to how hex editors print bytes. Each line starts with the address of
1622/// the start of the line, followed by all bytes in hex format (space separated).
1623/// If the allocation is small enough to fit into a single line, no start address is given.
1624/// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
1625/// characters or characters whose value is larger than 127) with a `.`
1626/// This also prints provenance adequately.
1627pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1628    tcx: TyCtxt<'tcx>,
1629    alloc: &'a Allocation<Prov, Extra, Bytes>,
1630) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1631    RenderAllocation { tcx, alloc }
1632}
1633
1634#[doc(hidden)]
1635pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1636    tcx: TyCtxt<'tcx>,
1637    alloc: &'a Allocation<Prov, Extra, Bytes>,
1638}
1639
1640impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1641    for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1642{
1643    fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1644        let RenderAllocation { tcx, alloc } = *self;
1645        write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1646        if alloc.size() == Size::ZERO {
1647            // We are done.
1648            return write!(w, " {{}}");
1649        }
1650        if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1651            return write!(w, " {{ .. }}");
1652        }
1653        // Write allocation bytes.
1654        writeln!(w, " {{")?;
1655        write_allocation_bytes(tcx, alloc, w, "    ")?;
1656        write!(w, "}}")?;
1657        Ok(())
1658    }
1659}
1660
1661fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1662    for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1663        write!(w, "   ")?;
1664    }
1665    writeln!(w, " │ {ascii}")
1666}
1667
1668/// Number of bytes to print per allocation hex dump line.
1669const BYTES_PER_LINE: usize = 16;
1670
1671/// Prints the line start address and returns the new line start address.
1672fn write_allocation_newline(
1673    w: &mut dyn std::fmt::Write,
1674    mut line_start: Size,
1675    ascii: &str,
1676    pos_width: usize,
1677    prefix: &str,
1678) -> Result<Size, std::fmt::Error> {
1679    write_allocation_endline(w, ascii)?;
1680    line_start += Size::from_bytes(BYTES_PER_LINE);
1681    write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1682    Ok(line_start)
1683}
1684
1685/// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
1686/// is only one line). Note that your prefix should contain a trailing space as the lines are
1687/// printed directly after it.
1688pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1689    tcx: TyCtxt<'tcx>,
1690    alloc: &Allocation<Prov, Extra, Bytes>,
1691    w: &mut dyn std::fmt::Write,
1692    prefix: &str,
1693) -> std::fmt::Result {
1694    let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1695    // Number of chars needed to represent all line numbers.
1696    let pos_width = hex_number_length(alloc.size().bytes());
1697
1698    if num_lines > 0 {
1699        write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1700    } else {
1701        write!(w, "{prefix}")?;
1702    }
1703
1704    let mut i = Size::ZERO;
1705    let mut line_start = Size::ZERO;
1706
1707    let ptr_size = tcx.data_layout.pointer_size();
1708
1709    let mut ascii = String::new();
1710
1711    let oversized_ptr = |target: &mut String, width| {
1712        if target.len() > width {
1713            write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1714        }
1715    };
1716
1717    while i < alloc.size() {
1718        // The line start already has a space. While we could remove that space from the line start
1719        // printing and unconditionally print a space here, that would cause the single-line case
1720        // to have a single space before it, which looks weird.
1721        if i != line_start {
1722            write!(w, " ")?;
1723        }
1724        if let Some(prov) = alloc.provenance().get_ptr(i) {
1725            // Memory with provenance must be defined
1726            assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1727            let j = i.bytes_usize();
1728            let offset = alloc
1729                .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1730            let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1731            let offset = Size::from_bytes(offset);
1732            let provenance_width = |bytes| bytes * 3;
1733            let ptr = Pointer::new(prov, offset);
1734            let mut target = format!("{ptr:?}");
1735            if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1736                // This is too long, try to save some space.
1737                target = format!("{ptr:#?}");
1738            }
1739            if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1740                // This branch handles the situation where a provenance starts in the current line
1741                // but ends in the next one.
1742                let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1743                let overflow = ptr_size - remainder;
1744                let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1745                let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1746                ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
1747                for _ in 1..remainder.bytes() {
1748                    ascii.push('─'); // LIGHT HORIZONTAL
1749                }
1750                if overflow_width > remainder_width && overflow_width >= target.len() {
1751                    // The case where the provenance fits into the part in the next line
1752                    write!(w, "╾{0:─^1$}", "", remainder_width)?;
1753                    line_start =
1754                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1755                    ascii.clear();
1756                    write!(w, "{target:─^overflow_width$}╼")?;
1757                } else {
1758                    oversized_ptr(&mut target, remainder_width);
1759                    write!(w, "╾{target:─^remainder_width$}")?;
1760                    line_start =
1761                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1762                    write!(w, "{0:─^1$}╼", "", overflow_width)?;
1763                    ascii.clear();
1764                }
1765                for _ in 0..overflow.bytes() - 1 {
1766                    ascii.push('─');
1767                }
1768                ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
1769                i += ptr_size;
1770                continue;
1771            } else {
1772                // This branch handles a provenance that starts and ends in the current line.
1773                let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1774                oversized_ptr(&mut target, provenance_width);
1775                ascii.push('╾');
1776                write!(w, "╾{target:─^provenance_width$}╼")?;
1777                for _ in 0..ptr_size.bytes() - 2 {
1778                    ascii.push('─');
1779                }
1780                ascii.push('╼');
1781                i += ptr_size;
1782            }
1783        } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) {
1784            // Memory with provenance must be defined
1785            assert!(
1786                alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1787            );
1788            ascii.push('━'); // HEAVY HORIZONTAL
1789            // We have two characters to display this, which is obviously not enough.
1790            // Format is similar to "oversized" above.
1791            let j = i.bytes_usize();
1792            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1793            write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?;
1794            i += Size::from_bytes(1);
1795        } else if alloc
1796            .init_mask()
1797            .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1798            .is_ok()
1799        {
1800            let j = i.bytes_usize();
1801
1802            // Checked definedness (and thus range) and provenance. This access also doesn't
1803            // influence interpreter execution but is only for debugging.
1804            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1805            write!(w, "{c:02x}")?;
1806            if c.is_ascii_control() || c >= 0x80 {
1807                ascii.push('.');
1808            } else {
1809                ascii.push(char::from(c));
1810            }
1811            i += Size::from_bytes(1);
1812        } else {
1813            write!(w, "__")?;
1814            ascii.push('░');
1815            i += Size::from_bytes(1);
1816        }
1817        // Print a new line header if the next line still has some bytes to print.
1818        if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1819            line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1820            ascii.clear();
1821        }
1822    }
1823    write_allocation_endline(w, &ascii)?;
1824
1825    Ok(())
1826}
1827
1828///////////////////////////////////////////////////////////////////////////
1829// Constants
1830
1831fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1832    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1833}
1834
1835fn comma_sep<'tcx>(
1836    tcx: TyCtxt<'tcx>,
1837    fmt: &mut Formatter<'_>,
1838    elems: Vec<(ConstValue, Ty<'tcx>)>,
1839) -> fmt::Result {
1840    let mut first = true;
1841    for (ct, ty) in elems {
1842        if !first {
1843            fmt.write_str(", ")?;
1844        }
1845        pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1846        first = false;
1847    }
1848    Ok(())
1849}
1850
1851fn pretty_print_const_value_tcx<'tcx>(
1852    tcx: TyCtxt<'tcx>,
1853    ct: ConstValue,
1854    ty: Ty<'tcx>,
1855    fmt: &mut Formatter<'_>,
1856) -> fmt::Result {
1857    use crate::ty::print::PrettyPrinter;
1858
1859    if tcx.sess.verbose_internals() {
1860        fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1861        return Ok(());
1862    }
1863
1864    let u8_type = tcx.types.u8;
1865    match (ct, ty.kind()) {
1866        // Byte/string slices, printed as (byte) string literals.
1867        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1868            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1869                fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1870                return Ok(());
1871            }
1872        }
1873        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1874            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1875                pretty_print_byte_str(fmt, data)?;
1876                return Ok(());
1877            }
1878        }
1879        (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1880            let n = n.try_to_target_usize(tcx).unwrap();
1881            let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1882            // cast is ok because we already checked for pointer size (32 or 64 bit) above
1883            let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1884            let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1885            fmt.write_str("*")?;
1886            pretty_print_byte_str(fmt, byte_str)?;
1887            return Ok(());
1888        }
1889        // Aggregates, printed as array/tuple/struct/variant construction syntax.
1890        //
1891        // NB: the `has_non_region_param` check ensures that we can use
1892        // the `destructure_const` query with an empty `ty::ParamEnv` without
1893        // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1894        // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1895        // to be able to destructure the tuple into `(0u8, *mut T)`
1896        (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1897            let ct = tcx.lift(ct).unwrap();
1898            let ty = tcx.lift(ty).unwrap();
1899            if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1900                let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1901                match *ty.kind() {
1902                    ty::Array(..) => {
1903                        fmt.write_str("[")?;
1904                        comma_sep(tcx, fmt, fields)?;
1905                        fmt.write_str("]")?;
1906                    }
1907                    ty::Tuple(..) => {
1908                        fmt.write_str("(")?;
1909                        comma_sep(tcx, fmt, fields)?;
1910                        if contents.fields.len() == 1 {
1911                            fmt.write_str(",")?;
1912                        }
1913                        fmt.write_str(")")?;
1914                    }
1915                    ty::Adt(def, _) if def.variants().is_empty() => {
1916                        fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1917                    }
1918                    ty::Adt(def, args) => {
1919                        let variant_idx = contents
1920                            .variant
1921                            .expect("destructed mir constant of adt without variant idx");
1922                        let variant_def = &def.variant(variant_idx);
1923                        let args = tcx.lift(args).unwrap();
1924                        let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1925                        p.print_alloc_ids = true;
1926                        p.pretty_print_value_path(variant_def.def_id, args)?;
1927                        fmt.write_str(&p.into_buffer())?;
1928
1929                        match variant_def.ctor_kind() {
1930                            Some(CtorKind::Const) => {}
1931                            Some(CtorKind::Fn) => {
1932                                fmt.write_str("(")?;
1933                                comma_sep(tcx, fmt, fields)?;
1934                                fmt.write_str(")")?;
1935                            }
1936                            None => {
1937                                fmt.write_str(" {{ ")?;
1938                                let mut first = true;
1939                                for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1940                                {
1941                                    if !first {
1942                                        fmt.write_str(", ")?;
1943                                    }
1944                                    write!(fmt, "{}: ", field_def.name)?;
1945                                    pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1946                                    first = false;
1947                                }
1948                                fmt.write_str(" }}")?;
1949                            }
1950                        }
1951                    }
1952                    _ => unreachable!(),
1953                }
1954                return Ok(());
1955            }
1956        }
1957        (ConstValue::Scalar(scalar), _) => {
1958            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1959            p.print_alloc_ids = true;
1960            let ty = tcx.lift(ty).unwrap();
1961            p.pretty_print_const_scalar(scalar, ty)?;
1962            fmt.write_str(&p.into_buffer())?;
1963            return Ok(());
1964        }
1965        (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1966            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1967            p.print_alloc_ids = true;
1968            p.pretty_print_value_path(*d, s)?;
1969            fmt.write_str(&p.into_buffer())?;
1970            return Ok(());
1971        }
1972        // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1973        // their fields instead of just dumping the memory.
1974        _ => {}
1975    }
1976    // Fall back to debug pretty printing for invalid constants.
1977    write!(fmt, "{ct:?}: {ty}")
1978}
1979
1980pub(crate) fn pretty_print_const_value<'tcx>(
1981    ct: ConstValue,
1982    ty: Ty<'tcx>,
1983    fmt: &mut Formatter<'_>,
1984) -> fmt::Result {
1985    ty::tls::with(|tcx| {
1986        let ct = tcx.lift(ct).unwrap();
1987        let ty = tcx.lift(ty).unwrap();
1988        pretty_print_const_value_tcx(tcx, ct, ty, fmt)
1989    })
1990}
1991
1992///////////////////////////////////////////////////////////////////////////
1993// Miscellaneous
1994
1995/// Calc converted u64 decimal into hex and return its length in chars.
1996///
1997/// ```ignore (cannot-test-private-function)
1998/// assert_eq!(1, hex_number_length(0));
1999/// assert_eq!(1, hex_number_length(1));
2000/// assert_eq!(2, hex_number_length(16));
2001/// ```
2002fn hex_number_length(x: u64) -> usize {
2003    if x == 0 {
2004        return 1;
2005    }
2006    let mut length = 0;
2007    let mut x_left = x;
2008    while x_left > 0 {
2009        x_left /= 16;
2010        length += 1;
2011    }
2012    length
2013}