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            let indented_body = format!("{INDENT}{INDENT}{statement:?};");
723            if self.options.include_extra_comments {
724                writeln!(
725                    w,
726                    "{:A$} // {}{}",
727                    indented_body,
728                    if self.tcx.sess.verbose_internals() {
729                        format!("{current_location:?}: ")
730                    } else {
731                        String::new()
732                    },
733                    comment(self.tcx, statement.source_info),
734                    A = ALIGN,
735                )?;
736            } else {
737                writeln!(w, "{indented_body}")?;
738            }
739
740            write_extra(
741                self.tcx,
742                w,
743                &|visitor| visitor.visit_statement(statement, current_location),
744                self.options,
745            )?;
746
747            (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
748
749            current_location.statement_index += 1;
750        }
751
752        // Terminator at the bottom.
753        (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
754        if data.terminator.is_some() {
755            let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
756            if self.options.include_extra_comments {
757                writeln!(
758                    w,
759                    "{:A$} // {}{}",
760                    indented_terminator,
761                    if self.tcx.sess.verbose_internals() {
762                        format!("{current_location:?}: ")
763                    } else {
764                        String::new()
765                    },
766                    comment(self.tcx, data.terminator().source_info),
767                    A = ALIGN,
768                )?;
769            } else {
770                writeln!(w, "{indented_terminator}")?;
771            }
772
773            write_extra(
774                self.tcx,
775                w,
776                &|visitor| visitor.visit_terminator(data.terminator(), current_location),
777                self.options,
778            )?;
779        }
780
781        (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
782        (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
783
784        writeln!(w, "{INDENT}}}")
785    }
786}
787
788impl Debug for Statement<'_> {
789    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
790        use self::StatementKind::*;
791        match self.kind {
792            Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
793            FakeRead(box (ref cause, ref place)) => {
794                write!(fmt, "FakeRead({cause:?}, {place:?})")
795            }
796            Retag(ref kind, ref place) => write!(
797                fmt,
798                "Retag({}{:?})",
799                match kind {
800                    RetagKind::FnEntry => "[fn entry] ",
801                    RetagKind::TwoPhase => "[2phase] ",
802                    RetagKind::Raw => "[raw] ",
803                    RetagKind::Default => "",
804                },
805                place,
806            ),
807            StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
808            StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
809            SetDiscriminant { ref place, variant_index } => {
810                write!(fmt, "discriminant({place:?}) = {variant_index:?}")
811            }
812            Deinit(ref place) => write!(fmt, "Deinit({place:?})"),
813            PlaceMention(ref place) => {
814                write!(fmt, "PlaceMention({place:?})")
815            }
816            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
817                write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
818            }
819            Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
820            Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
821            ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
822            Nop => write!(fmt, "nop"),
823            BackwardIncompatibleDropHint { ref place, reason: _ } => {
824                // For now, we don't record the reason because there is only one use case,
825                // which is to report breaking change in drop order by Edition 2024
826                write!(fmt, "BackwardIncompatibleDropHint({place:?})")
827            }
828        }
829    }
830}
831
832impl Display for NonDivergingIntrinsic<'_> {
833    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834        match self {
835            Self::Assume(op) => write!(f, "assume({op:?})"),
836            Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
837                write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
838            }
839        }
840    }
841}
842
843impl<'tcx> Debug for TerminatorKind<'tcx> {
844    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
845        self.fmt_head(fmt)?;
846        let successor_count = self.successors().count();
847        let labels = self.fmt_successor_labels();
848        assert_eq!(successor_count, labels.len());
849
850        // `Cleanup` is already included in successors
851        let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
852        let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
853            write!(fmt, "unwind ")?;
854            match self.unwind() {
855                // Not needed or included in successors
856                None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
857                Some(UnwindAction::Continue) => write!(fmt, "continue"),
858                Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
859                Some(UnwindAction::Terminate(reason)) => {
860                    write!(fmt, "terminate({})", reason.as_short_str())
861                }
862            }
863        };
864
865        match (successor_count, show_unwind) {
866            (0, false) => Ok(()),
867            (0, true) => {
868                write!(fmt, " -> ")?;
869                fmt_unwind(fmt)
870            }
871            (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
872            _ => {
873                write!(fmt, " -> [")?;
874                for (i, target) in self.successors().enumerate() {
875                    if i > 0 {
876                        write!(fmt, ", ")?;
877                    }
878                    write!(fmt, "{}: {:?}", labels[i], target)?;
879                }
880                if show_unwind {
881                    write!(fmt, ", ")?;
882                    fmt_unwind(fmt)?;
883                }
884                write!(fmt, "]")
885            }
886        }
887    }
888}
889
890impl<'tcx> TerminatorKind<'tcx> {
891    /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
892    /// successor basic block, if any. The only information not included is the list of possible
893    /// successors, which may be rendered differently between the text and the graphviz format.
894    pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
895        use self::TerminatorKind::*;
896        match self {
897            Goto { .. } => write!(fmt, "goto"),
898            SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
899            Return => write!(fmt, "return"),
900            CoroutineDrop => write!(fmt, "coroutine_drop"),
901            UnwindResume => write!(fmt, "resume"),
902            UnwindTerminate(reason) => {
903                write!(fmt, "terminate({})", reason.as_short_str())
904            }
905            Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
906            Unreachable => write!(fmt, "unreachable"),
907            Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
908            Drop { place, async_fut: Some(async_fut), .. } => {
909                write!(fmt, "async drop({place:?}; poll={async_fut:?})")
910            }
911            Call { func, args, destination, .. } => {
912                write!(fmt, "{destination:?} = ")?;
913                write!(fmt, "{func:?}(")?;
914                for (index, arg) in args.iter().enumerate() {
915                    if index > 0 {
916                        write!(fmt, ", ")?;
917                    }
918                    write!(fmt, "{:?}", arg.node)?;
919                }
920                write!(fmt, ")")
921            }
922            TailCall { func, args, .. } => {
923                write!(fmt, "tailcall {func:?}(")?;
924                for (index, arg) in args.iter().enumerate() {
925                    if index > 0 {
926                        write!(fmt, ", ")?;
927                    }
928                    write!(fmt, "{:?}", arg.node)?;
929                }
930                write!(fmt, ")")
931            }
932            Assert { cond, expected, msg, .. } => {
933                write!(fmt, "assert(")?;
934                if !expected {
935                    write!(fmt, "!")?;
936                }
937                write!(fmt, "{cond:?}, ")?;
938                msg.fmt_assert_args(fmt)?;
939                write!(fmt, ")")
940            }
941            FalseEdge { .. } => write!(fmt, "falseEdge"),
942            FalseUnwind { .. } => write!(fmt, "falseUnwind"),
943            InlineAsm { template, operands, options, .. } => {
944                write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
945                for op in operands {
946                    write!(fmt, ", ")?;
947                    let print_late = |&late| if late { "late" } else { "" };
948                    match op {
949                        InlineAsmOperand::In { reg, value } => {
950                            write!(fmt, "in({reg}) {value:?}")?;
951                        }
952                        InlineAsmOperand::Out { reg, late, place: Some(place) } => {
953                            write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
954                        }
955                        InlineAsmOperand::Out { reg, late, place: None } => {
956                            write!(fmt, "{}out({}) _", print_late(late), reg)?;
957                        }
958                        InlineAsmOperand::InOut {
959                            reg,
960                            late,
961                            in_value,
962                            out_place: Some(out_place),
963                        } => {
964                            write!(
965                                fmt,
966                                "in{}out({}) {:?} => {:?}",
967                                print_late(late),
968                                reg,
969                                in_value,
970                                out_place
971                            )?;
972                        }
973                        InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
974                            write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
975                        }
976                        InlineAsmOperand::Const { value } => {
977                            write!(fmt, "const {value:?}")?;
978                        }
979                        InlineAsmOperand::SymFn { value } => {
980                            write!(fmt, "sym_fn {value:?}")?;
981                        }
982                        InlineAsmOperand::SymStatic { def_id } => {
983                            write!(fmt, "sym_static {def_id:?}")?;
984                        }
985                        InlineAsmOperand::Label { target_index } => {
986                            write!(fmt, "label {target_index}")?;
987                        }
988                    }
989                }
990                write!(fmt, ", options({options:?}))")
991            }
992        }
993    }
994
995    /// Returns the list of labels for the edges to the successor basic blocks.
996    pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
997        use self::TerminatorKind::*;
998        match *self {
999            Return
1000            | TailCall { .. }
1001            | UnwindResume
1002            | UnwindTerminate(_)
1003            | Unreachable
1004            | CoroutineDrop => vec![],
1005            Goto { .. } => vec!["".into()],
1006            SwitchInt { ref targets, .. } => targets
1007                .values
1008                .iter()
1009                .map(|&u| Cow::Owned(u.to_string()))
1010                .chain(iter::once("otherwise".into()))
1011                .collect(),
1012            Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1013                vec!["return".into(), "unwind".into()]
1014            }
1015            Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1016            Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1017            Call { target: None, unwind: _, .. } => vec![],
1018            Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1019            Yield { drop: None, .. } => vec!["resume".into()],
1020            Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1021                vec!["return".into(), "unwind".into(), "drop".into()]
1022            }
1023            Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1024                vec!["return".into(), "unwind".into()]
1025            }
1026            Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1027            Drop { unwind: _, .. } => vec!["return".into()],
1028            Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1029                vec!["success".into(), "unwind".into()]
1030            }
1031            Assert { unwind: _, .. } => vec!["success".into()],
1032            FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1033            FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1034                vec!["real".into(), "unwind".into()]
1035            }
1036            FalseUnwind { unwind: _, .. } => vec!["real".into()],
1037            InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1038                let mut vec = Vec::with_capacity(targets.len() + 1);
1039                if !asm_macro.diverges(options) {
1040                    vec.push("return".into());
1041                }
1042                vec.resize(targets.len(), "label".into());
1043
1044                if let UnwindAction::Cleanup(_) = unwind {
1045                    vec.push("unwind".into());
1046                }
1047
1048                vec
1049            }
1050        }
1051    }
1052}
1053
1054impl<'tcx> Debug for Rvalue<'tcx> {
1055    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1056        use self::Rvalue::*;
1057
1058        match *self {
1059            Use(ref place) => write!(fmt, "{place:?}"),
1060            Repeat(ref a, b) => {
1061                write!(fmt, "[{a:?}; ")?;
1062                pretty_print_const(b, fmt, false)?;
1063                write!(fmt, "]")
1064            }
1065            Len(ref a) => write!(fmt, "Len({a:?})"),
1066            Cast(ref kind, ref place, ref ty) => {
1067                with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1068            }
1069            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1070            UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1071            Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1072            NullaryOp(ref op, ref t) => {
1073                let t = with_no_trimmed_paths!(format!("{}", t));
1074                match op {
1075                    NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
1076                    NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
1077                    NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1078                    NullOp::UbChecks => write!(fmt, "UbChecks()"),
1079                    NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1080                }
1081            }
1082            ThreadLocalRef(did) => ty::tls::with(|tcx| {
1083                let muta = tcx.static_mutability(did).unwrap().prefix_str();
1084                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1085            }),
1086            Ref(region, borrow_kind, ref place) => {
1087                let kind_str = match borrow_kind {
1088                    BorrowKind::Shared => "",
1089                    BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1090                    BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1091                    BorrowKind::Mut { .. } => "mut ",
1092                };
1093
1094                // When printing regions, add trailing space if necessary.
1095                let print_region = ty::tls::with(|tcx| {
1096                    tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1097                });
1098                let region = if print_region {
1099                    let mut region = region.to_string();
1100                    if !region.is_empty() {
1101                        region.push(' ');
1102                    }
1103                    region
1104                } else {
1105                    // Do not even print 'static
1106                    String::new()
1107                };
1108                write!(fmt, "&{region}{kind_str}{place:?}")
1109            }
1110
1111            CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1112
1113            RawPtr(mutability, ref place) => {
1114                write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1115            }
1116
1117            Aggregate(ref kind, ref places) => {
1118                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1119                    let mut tuple_fmt = fmt.debug_tuple(name);
1120                    for place in places {
1121                        tuple_fmt.field(place);
1122                    }
1123                    tuple_fmt.finish()
1124                };
1125
1126                match **kind {
1127                    AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1128
1129                    AggregateKind::Tuple => {
1130                        if places.is_empty() {
1131                            write!(fmt, "()")
1132                        } else {
1133                            fmt_tuple(fmt, "")
1134                        }
1135                    }
1136
1137                    AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1138                        ty::tls::with(|tcx| {
1139                            let variant_def = &tcx.adt_def(adt_did).variant(variant);
1140                            let args = tcx.lift(args).expect("could not lift for printing");
1141                            let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1142                                p.print_def_path(variant_def.def_id, args)
1143                            })?;
1144
1145                            match variant_def.ctor_kind() {
1146                                Some(CtorKind::Const) => fmt.write_str(&name),
1147                                Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1148                                None => {
1149                                    let mut struct_fmt = fmt.debug_struct(&name);
1150                                    for (field, place) in iter::zip(&variant_def.fields, places) {
1151                                        struct_fmt.field(field.name.as_str(), place);
1152                                    }
1153                                    struct_fmt.finish()
1154                                }
1155                            }
1156                        })
1157                    }
1158
1159                    AggregateKind::Closure(def_id, args)
1160                    | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1161                        let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1162                            let args = tcx.lift(args).unwrap();
1163                            format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1164                        } else {
1165                            let span = tcx.def_span(def_id);
1166                            format!(
1167                                "{{closure@{}}}",
1168                                tcx.sess.source_map().span_to_diagnostic_string(span)
1169                            )
1170                        };
1171                        let mut struct_fmt = fmt.debug_struct(&name);
1172
1173                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1174                        if let Some(def_id) = def_id.as_local()
1175                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1176                        {
1177                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1178                                let var_name = tcx.hir_name(var_id);
1179                                struct_fmt.field(var_name.as_str(), place);
1180                            }
1181                        } else {
1182                            for (index, place) in places.iter().enumerate() {
1183                                struct_fmt.field(&format!("{index}"), place);
1184                            }
1185                        }
1186
1187                        struct_fmt.finish()
1188                    }),
1189
1190                    AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1191                        let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1192                        let mut struct_fmt = fmt.debug_struct(&name);
1193
1194                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1195                        if let Some(def_id) = def_id.as_local()
1196                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1197                        {
1198                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1199                                let var_name = tcx.hir_name(var_id);
1200                                struct_fmt.field(var_name.as_str(), place);
1201                            }
1202                        } else {
1203                            for (index, place) in places.iter().enumerate() {
1204                                struct_fmt.field(&format!("{index}"), place);
1205                            }
1206                        }
1207
1208                        struct_fmt.finish()
1209                    }),
1210
1211                    AggregateKind::RawPtr(pointee_ty, mutability) => {
1212                        let kind_str = match mutability {
1213                            Mutability::Mut => "mut",
1214                            Mutability::Not => "const",
1215                        };
1216                        with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1217                        fmt_tuple(fmt, "")
1218                    }
1219                }
1220            }
1221
1222            ShallowInitBox(ref place, ref ty) => {
1223                with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1224            }
1225
1226            WrapUnsafeBinder(ref op, ty) => {
1227                with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1228            }
1229        }
1230    }
1231}
1232
1233impl<'tcx> Debug for Operand<'tcx> {
1234    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1235        use self::Operand::*;
1236        match *self {
1237            Constant(ref a) => write!(fmt, "{a:?}"),
1238            Copy(ref place) => write!(fmt, "copy {place:?}"),
1239            Move(ref place) => write!(fmt, "move {place:?}"),
1240        }
1241    }
1242}
1243
1244impl<'tcx> Debug for ConstOperand<'tcx> {
1245    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1246        write!(fmt, "{self}")
1247    }
1248}
1249
1250impl<'tcx> Display for ConstOperand<'tcx> {
1251    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1252        match self.ty().kind() {
1253            ty::FnDef(..) => {}
1254            _ => write!(fmt, "const ")?,
1255        }
1256        Display::fmt(&self.const_, fmt)
1257    }
1258}
1259
1260impl Debug for Place<'_> {
1261    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1262        self.as_ref().fmt(fmt)
1263    }
1264}
1265
1266impl Debug for PlaceRef<'_> {
1267    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1268        pre_fmt_projection(self.projection, fmt)?;
1269        write!(fmt, "{:?}", self.local)?;
1270        post_fmt_projection(self.projection, fmt)
1271    }
1272}
1273
1274fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1275    for &elem in projection.iter().rev() {
1276        match elem {
1277            ProjectionElem::OpaqueCast(_)
1278            | ProjectionElem::Subtype(_)
1279            | ProjectionElem::Downcast(_, _)
1280            | ProjectionElem::Field(_, _) => {
1281                write!(fmt, "(")?;
1282            }
1283            ProjectionElem::Deref => {
1284                write!(fmt, "(*")?;
1285            }
1286            ProjectionElem::Index(_)
1287            | ProjectionElem::ConstantIndex { .. }
1288            | ProjectionElem::Subslice { .. } => {}
1289            ProjectionElem::UnwrapUnsafeBinder(_) => {
1290                write!(fmt, "unwrap_binder!(")?;
1291            }
1292        }
1293    }
1294
1295    Ok(())
1296}
1297
1298fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1299    for &elem in projection.iter() {
1300        match elem {
1301            ProjectionElem::OpaqueCast(ty) => {
1302                write!(fmt, " as {ty})")?;
1303            }
1304            ProjectionElem::Subtype(ty) => {
1305                write!(fmt, " as subtype {ty})")?;
1306            }
1307            ProjectionElem::Downcast(Some(name), _index) => {
1308                write!(fmt, " as {name})")?;
1309            }
1310            ProjectionElem::Downcast(None, index) => {
1311                write!(fmt, " as variant#{index:?})")?;
1312            }
1313            ProjectionElem::Deref => {
1314                write!(fmt, ")")?;
1315            }
1316            ProjectionElem::Field(field, ty) => {
1317                with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1318            }
1319            ProjectionElem::Index(ref index) => {
1320                write!(fmt, "[{index:?}]")?;
1321            }
1322            ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1323                write!(fmt, "[{offset:?} of {min_length:?}]")?;
1324            }
1325            ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1326                write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1327            }
1328            ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1329                write!(fmt, "[{from:?}:]")?;
1330            }
1331            ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1332                write!(fmt, "[:-{to:?}]")?;
1333            }
1334            ProjectionElem::Subslice { from, to, from_end: true } => {
1335                write!(fmt, "[{from:?}:-{to:?}]")?;
1336            }
1337            ProjectionElem::Subslice { from, to, from_end: false } => {
1338                write!(fmt, "[{from:?}..{to:?}]")?;
1339            }
1340            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1341                write!(fmt, "; {ty})")?;
1342            }
1343        }
1344    }
1345
1346    Ok(())
1347}
1348
1349/// After we print the main statement, we sometimes dump extra
1350/// information. There's often a lot of little things "nuzzled up" in
1351/// a statement.
1352fn write_extra<'tcx>(
1353    tcx: TyCtxt<'tcx>,
1354    write: &mut dyn io::Write,
1355    visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1356    options: PrettyPrintMirOptions,
1357) -> io::Result<()> {
1358    if options.include_extra_comments {
1359        let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1360        visit_op(&mut extra_comments);
1361        for comment in extra_comments.comments {
1362            writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1363        }
1364    }
1365    Ok(())
1366}
1367
1368struct ExtraComments<'tcx> {
1369    tcx: TyCtxt<'tcx>,
1370    comments: Vec<String>,
1371}
1372
1373impl<'tcx> ExtraComments<'tcx> {
1374    fn push(&mut self, lines: &str) {
1375        for line in lines.split('\n') {
1376            self.comments.push(line.to_string());
1377        }
1378    }
1379}
1380
1381fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1382    match *ty.kind() {
1383        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1384        // Unit type
1385        ty::Tuple(g_args) if g_args.is_empty() => false,
1386        ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1387        ty::Array(ty, _) => use_verbose(ty, fn_def),
1388        ty::FnDef(..) => fn_def,
1389        _ => true,
1390    }
1391}
1392
1393impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1394    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1395        let ConstOperand { span, user_ty, const_ } = constant;
1396        if use_verbose(const_.ty(), true) {
1397            self.push("mir::ConstOperand");
1398            self.push(&format!(
1399                "+ span: {}",
1400                self.tcx.sess.source_map().span_to_embeddable_string(*span)
1401            ));
1402            if let Some(user_ty) = user_ty {
1403                self.push(&format!("+ user_ty: {user_ty:?}"));
1404            }
1405
1406            let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1407                let tcx = self.tcx;
1408                rustc_data_structures::make_display(move |fmt| {
1409                    pretty_print_const_value_tcx(tcx, val, ty, fmt)
1410                })
1411            };
1412
1413            let fmt_valtree = |cv: &ty::Value<'tcx>| {
1414                let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1415                p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1416                p.into_buffer()
1417            };
1418
1419            let val = match const_ {
1420                Const::Ty(_, ct) => match ct.kind() {
1421                    ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1422                    ty::ConstKind::Unevaluated(uv) => {
1423                        format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1424                    }
1425                    ty::ConstKind::Value(cv) => {
1426                        format!("ty::Valtree({})", fmt_valtree(&cv))
1427                    }
1428                    // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
1429                    ty::ConstKind::Error(_) => "Error".to_string(),
1430                    // These variants shouldn't exist in the MIR.
1431                    ty::ConstKind::Placeholder(_)
1432                    | ty::ConstKind::Infer(_)
1433                    | ty::ConstKind::Expr(_)
1434                    | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1435                },
1436                Const::Unevaluated(uv, _) => {
1437                    format!(
1438                        "Unevaluated({}, {:?}, {:?})",
1439                        self.tcx.def_path_str(uv.def),
1440                        uv.args,
1441                        uv.promoted,
1442                    )
1443                }
1444                Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1445            };
1446
1447            // This reflects what `Const` looked liked before `val` was renamed
1448            // as `kind`. We print it like this to avoid having to update
1449            // expected output in a lot of tests.
1450            self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1451        }
1452    }
1453
1454    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1455        self.super_rvalue(rvalue, location);
1456        if let Rvalue::Aggregate(kind, _) = rvalue {
1457            match **kind {
1458                AggregateKind::Closure(def_id, args) => {
1459                    self.push("closure");
1460                    self.push(&format!("+ def_id: {def_id:?}"));
1461                    self.push(&format!("+ args: {args:#?}"));
1462                }
1463
1464                AggregateKind::Coroutine(def_id, args) => {
1465                    self.push("coroutine");
1466                    self.push(&format!("+ def_id: {def_id:?}"));
1467                    self.push(&format!("+ args: {args:#?}"));
1468                    self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1469                }
1470
1471                AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1472                    self.push("adt");
1473                    self.push(&format!("+ user_ty: {user_ty:?}"));
1474                }
1475
1476                _ => {}
1477            }
1478        }
1479    }
1480}
1481
1482fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1483    let location = tcx.sess.source_map().span_to_embeddable_string(span);
1484    format!("scope {} at {}", scope.index(), location,)
1485}
1486
1487///////////////////////////////////////////////////////////////////////////
1488// Allocations
1489
1490/// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
1491/// allocations.
1492pub fn write_allocations<'tcx>(
1493    tcx: TyCtxt<'tcx>,
1494    body: &Body<'_>,
1495    w: &mut dyn io::Write,
1496) -> io::Result<()> {
1497    fn alloc_ids_from_alloc(
1498        alloc: ConstAllocation<'_>,
1499    ) -> impl DoubleEndedIterator<Item = AllocId> {
1500        alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1501    }
1502
1503    fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1504        match val {
1505            ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1506            ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1507            ConstValue::ZeroSized => None,
1508            ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1509                // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
1510                // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
1511                Some(alloc_id)
1512            }
1513        }
1514    }
1515    struct CollectAllocIds(BTreeSet<AllocId>);
1516
1517    impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1518        fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1519            match c.const_ {
1520                Const::Ty(_, _) | Const::Unevaluated(..) => {}
1521                Const::Val(val, _) => {
1522                    if let Some(id) = alloc_id_from_const_val(val) {
1523                        self.0.insert(id);
1524                    }
1525                }
1526            }
1527        }
1528    }
1529
1530    let mut visitor = CollectAllocIds(Default::default());
1531    visitor.visit_body(body);
1532
1533    // `seen` contains all seen allocations, including the ones we have *not* printed yet.
1534    // The protocol is to first `insert` into `seen`, and only if that returns `true`
1535    // then push to `todo`.
1536    let mut seen = visitor.0;
1537    let mut todo: Vec<_> = seen.iter().copied().collect();
1538    while let Some(id) = todo.pop() {
1539        let mut write_allocation_track_relocs =
1540            |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1541                // `.rev()` because we are popping them from the back of the `todo` vector.
1542                for id in alloc_ids_from_alloc(alloc).rev() {
1543                    if seen.insert(id) {
1544                        todo.push(id);
1545                    }
1546                }
1547                write!(w, "{}", display_allocation(tcx, alloc.inner()))
1548            };
1549        write!(w, "\n{id:?}")?;
1550        match tcx.try_get_global_alloc(id) {
1551            // This can't really happen unless there are bugs, but it doesn't cost us anything to
1552            // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
1553            None => write!(w, " (deallocated)")?,
1554            Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1555            Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1556                write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1557            }
1558            Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1559            Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1560                write!(w, " (static: {}", tcx.def_path_str(did))?;
1561                if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1562                    && body
1563                        .source
1564                        .def_id()
1565                        .as_local()
1566                        .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1567                {
1568                    // Statics may be cyclic and evaluating them too early
1569                    // in the MIR pipeline may cause cycle errors even though
1570                    // normal compilation is fine.
1571                    write!(w, ")")?;
1572                } else {
1573                    match tcx.eval_static_initializer(did) {
1574                        Ok(alloc) => {
1575                            write!(w, ", ")?;
1576                            write_allocation_track_relocs(w, alloc)?;
1577                        }
1578                        Err(_) => write!(w, ", error during initializer evaluation)")?,
1579                    }
1580                }
1581            }
1582            Some(GlobalAlloc::Static(did)) => {
1583                write!(w, " (extern static: {})", tcx.def_path_str(did))?
1584            }
1585            Some(GlobalAlloc::Memory(alloc)) => {
1586                write!(w, " (")?;
1587                write_allocation_track_relocs(w, alloc)?
1588            }
1589        }
1590        writeln!(w)?;
1591    }
1592    Ok(())
1593}
1594
1595/// Dumps the size and metadata and content of an allocation to the given writer.
1596/// The expectation is that the caller first prints other relevant metadata, so the exact
1597/// format of this function is (*without* leading or trailing newline):
1598///
1599/// ```text
1600/// size: {}, align: {}) {
1601///     <bytes>
1602/// }
1603/// ```
1604///
1605/// The byte format is similar to how hex editors print bytes. Each line starts with the address of
1606/// the start of the line, followed by all bytes in hex format (space separated).
1607/// If the allocation is small enough to fit into a single line, no start address is given.
1608/// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
1609/// characters or characters whose value is larger than 127) with a `.`
1610/// This also prints provenance adequately.
1611pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1612    tcx: TyCtxt<'tcx>,
1613    alloc: &'a Allocation<Prov, Extra, Bytes>,
1614) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1615    RenderAllocation { tcx, alloc }
1616}
1617
1618#[doc(hidden)]
1619pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1620    tcx: TyCtxt<'tcx>,
1621    alloc: &'a Allocation<Prov, Extra, Bytes>,
1622}
1623
1624impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1625    for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1626{
1627    fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1628        let RenderAllocation { tcx, alloc } = *self;
1629        write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1630        if alloc.size() == Size::ZERO {
1631            // We are done.
1632            return write!(w, " {{}}");
1633        }
1634        if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1635            return write!(w, " {{ .. }}");
1636        }
1637        // Write allocation bytes.
1638        writeln!(w, " {{")?;
1639        write_allocation_bytes(tcx, alloc, w, "    ")?;
1640        write!(w, "}}")?;
1641        Ok(())
1642    }
1643}
1644
1645fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1646    for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1647        write!(w, "   ")?;
1648    }
1649    writeln!(w, " │ {ascii}")
1650}
1651
1652/// Number of bytes to print per allocation hex dump line.
1653const BYTES_PER_LINE: usize = 16;
1654
1655/// Prints the line start address and returns the new line start address.
1656fn write_allocation_newline(
1657    w: &mut dyn std::fmt::Write,
1658    mut line_start: Size,
1659    ascii: &str,
1660    pos_width: usize,
1661    prefix: &str,
1662) -> Result<Size, std::fmt::Error> {
1663    write_allocation_endline(w, ascii)?;
1664    line_start += Size::from_bytes(BYTES_PER_LINE);
1665    write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1666    Ok(line_start)
1667}
1668
1669/// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
1670/// is only one line). Note that your prefix should contain a trailing space as the lines are
1671/// printed directly after it.
1672pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1673    tcx: TyCtxt<'tcx>,
1674    alloc: &Allocation<Prov, Extra, Bytes>,
1675    w: &mut dyn std::fmt::Write,
1676    prefix: &str,
1677) -> std::fmt::Result {
1678    let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1679    // Number of chars needed to represent all line numbers.
1680    let pos_width = hex_number_length(alloc.size().bytes());
1681
1682    if num_lines > 0 {
1683        write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1684    } else {
1685        write!(w, "{prefix}")?;
1686    }
1687
1688    let mut i = Size::ZERO;
1689    let mut line_start = Size::ZERO;
1690
1691    let ptr_size = tcx.data_layout.pointer_size();
1692
1693    let mut ascii = String::new();
1694
1695    let oversized_ptr = |target: &mut String, width| {
1696        if target.len() > width {
1697            write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1698        }
1699    };
1700
1701    while i < alloc.size() {
1702        // The line start already has a space. While we could remove that space from the line start
1703        // printing and unconditionally print a space here, that would cause the single-line case
1704        // to have a single space before it, which looks weird.
1705        if i != line_start {
1706            write!(w, " ")?;
1707        }
1708        if let Some(prov) = alloc.provenance().get_ptr(i) {
1709            // Memory with provenance must be defined
1710            assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1711            let j = i.bytes_usize();
1712            let offset = alloc
1713                .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1714            let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1715            let offset = Size::from_bytes(offset);
1716            let provenance_width = |bytes| bytes * 3;
1717            let ptr = Pointer::new(prov, offset);
1718            let mut target = format!("{ptr:?}");
1719            if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1720                // This is too long, try to save some space.
1721                target = format!("{ptr:#?}");
1722            }
1723            if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1724                // This branch handles the situation where a provenance starts in the current line
1725                // but ends in the next one.
1726                let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1727                let overflow = ptr_size - remainder;
1728                let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1729                let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1730                ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
1731                for _ in 1..remainder.bytes() {
1732                    ascii.push('─'); // LIGHT HORIZONTAL
1733                }
1734                if overflow_width > remainder_width && overflow_width >= target.len() {
1735                    // The case where the provenance fits into the part in the next line
1736                    write!(w, "╾{0:─^1$}", "", remainder_width)?;
1737                    line_start =
1738                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1739                    ascii.clear();
1740                    write!(w, "{target:─^overflow_width$}╼")?;
1741                } else {
1742                    oversized_ptr(&mut target, remainder_width);
1743                    write!(w, "╾{target:─^remainder_width$}")?;
1744                    line_start =
1745                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1746                    write!(w, "{0:─^1$}╼", "", overflow_width)?;
1747                    ascii.clear();
1748                }
1749                for _ in 0..overflow.bytes() - 1 {
1750                    ascii.push('─');
1751                }
1752                ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
1753                i += ptr_size;
1754                continue;
1755            } else {
1756                // This branch handles a provenance that starts and ends in the current line.
1757                let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1758                oversized_ptr(&mut target, provenance_width);
1759                ascii.push('╾');
1760                write!(w, "╾{target:─^provenance_width$}╼")?;
1761                for _ in 0..ptr_size.bytes() - 2 {
1762                    ascii.push('─');
1763                }
1764                ascii.push('╼');
1765                i += ptr_size;
1766            }
1767        } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) {
1768            // Memory with provenance must be defined
1769            assert!(
1770                alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1771            );
1772            ascii.push('━'); // HEAVY HORIZONTAL
1773            // We have two characters to display this, which is obviously not enough.
1774            // Format is similar to "oversized" above.
1775            let j = i.bytes_usize();
1776            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1777            write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?;
1778            i += Size::from_bytes(1);
1779        } else if alloc
1780            .init_mask()
1781            .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1782            .is_ok()
1783        {
1784            let j = i.bytes_usize();
1785
1786            // Checked definedness (and thus range) and provenance. This access also doesn't
1787            // influence interpreter execution but is only for debugging.
1788            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1789            write!(w, "{c:02x}")?;
1790            if c.is_ascii_control() || c >= 0x80 {
1791                ascii.push('.');
1792            } else {
1793                ascii.push(char::from(c));
1794            }
1795            i += Size::from_bytes(1);
1796        } else {
1797            write!(w, "__")?;
1798            ascii.push('░');
1799            i += Size::from_bytes(1);
1800        }
1801        // Print a new line header if the next line still has some bytes to print.
1802        if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1803            line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1804            ascii.clear();
1805        }
1806    }
1807    write_allocation_endline(w, &ascii)?;
1808
1809    Ok(())
1810}
1811
1812///////////////////////////////////////////////////////////////////////////
1813// Constants
1814
1815fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1816    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1817}
1818
1819fn comma_sep<'tcx>(
1820    tcx: TyCtxt<'tcx>,
1821    fmt: &mut Formatter<'_>,
1822    elems: Vec<(ConstValue, Ty<'tcx>)>,
1823) -> fmt::Result {
1824    let mut first = true;
1825    for (ct, ty) in elems {
1826        if !first {
1827            fmt.write_str(", ")?;
1828        }
1829        pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1830        first = false;
1831    }
1832    Ok(())
1833}
1834
1835fn pretty_print_const_value_tcx<'tcx>(
1836    tcx: TyCtxt<'tcx>,
1837    ct: ConstValue,
1838    ty: Ty<'tcx>,
1839    fmt: &mut Formatter<'_>,
1840) -> fmt::Result {
1841    use crate::ty::print::PrettyPrinter;
1842
1843    if tcx.sess.verbose_internals() {
1844        fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1845        return Ok(());
1846    }
1847
1848    let u8_type = tcx.types.u8;
1849    match (ct, ty.kind()) {
1850        // Byte/string slices, printed as (byte) string literals.
1851        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1852            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1853                fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1854                return Ok(());
1855            }
1856        }
1857        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1858            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1859                pretty_print_byte_str(fmt, data)?;
1860                return Ok(());
1861            }
1862        }
1863        (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1864            let n = n.try_to_target_usize(tcx).unwrap();
1865            let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1866            // cast is ok because we already checked for pointer size (32 or 64 bit) above
1867            let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1868            let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1869            fmt.write_str("*")?;
1870            pretty_print_byte_str(fmt, byte_str)?;
1871            return Ok(());
1872        }
1873        // Aggregates, printed as array/tuple/struct/variant construction syntax.
1874        //
1875        // NB: the `has_non_region_param` check ensures that we can use
1876        // the `destructure_const` query with an empty `ty::ParamEnv` without
1877        // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1878        // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1879        // to be able to destructure the tuple into `(0u8, *mut T)`
1880        (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1881            let ct = tcx.lift(ct).unwrap();
1882            let ty = tcx.lift(ty).unwrap();
1883            if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1884                let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1885                match *ty.kind() {
1886                    ty::Array(..) => {
1887                        fmt.write_str("[")?;
1888                        comma_sep(tcx, fmt, fields)?;
1889                        fmt.write_str("]")?;
1890                    }
1891                    ty::Tuple(..) => {
1892                        fmt.write_str("(")?;
1893                        comma_sep(tcx, fmt, fields)?;
1894                        if contents.fields.len() == 1 {
1895                            fmt.write_str(",")?;
1896                        }
1897                        fmt.write_str(")")?;
1898                    }
1899                    ty::Adt(def, _) if def.variants().is_empty() => {
1900                        fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1901                    }
1902                    ty::Adt(def, args) => {
1903                        let variant_idx = contents
1904                            .variant
1905                            .expect("destructed mir constant of adt without variant idx");
1906                        let variant_def = &def.variant(variant_idx);
1907                        let args = tcx.lift(args).unwrap();
1908                        let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1909                        p.print_alloc_ids = true;
1910                        p.pretty_print_value_path(variant_def.def_id, args)?;
1911                        fmt.write_str(&p.into_buffer())?;
1912
1913                        match variant_def.ctor_kind() {
1914                            Some(CtorKind::Const) => {}
1915                            Some(CtorKind::Fn) => {
1916                                fmt.write_str("(")?;
1917                                comma_sep(tcx, fmt, fields)?;
1918                                fmt.write_str(")")?;
1919                            }
1920                            None => {
1921                                fmt.write_str(" {{ ")?;
1922                                let mut first = true;
1923                                for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1924                                {
1925                                    if !first {
1926                                        fmt.write_str(", ")?;
1927                                    }
1928                                    write!(fmt, "{}: ", field_def.name)?;
1929                                    pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1930                                    first = false;
1931                                }
1932                                fmt.write_str(" }}")?;
1933                            }
1934                        }
1935                    }
1936                    _ => unreachable!(),
1937                }
1938                return Ok(());
1939            }
1940        }
1941        (ConstValue::Scalar(scalar), _) => {
1942            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1943            p.print_alloc_ids = true;
1944            let ty = tcx.lift(ty).unwrap();
1945            p.pretty_print_const_scalar(scalar, ty)?;
1946            fmt.write_str(&p.into_buffer())?;
1947            return Ok(());
1948        }
1949        (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1950            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1951            p.print_alloc_ids = true;
1952            p.pretty_print_value_path(*d, s)?;
1953            fmt.write_str(&p.into_buffer())?;
1954            return Ok(());
1955        }
1956        // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1957        // their fields instead of just dumping the memory.
1958        _ => {}
1959    }
1960    // Fall back to debug pretty printing for invalid constants.
1961    write!(fmt, "{ct:?}: {ty}")
1962}
1963
1964pub(crate) fn pretty_print_const_value<'tcx>(
1965    ct: ConstValue,
1966    ty: Ty<'tcx>,
1967    fmt: &mut Formatter<'_>,
1968) -> fmt::Result {
1969    ty::tls::with(|tcx| {
1970        let ct = tcx.lift(ct).unwrap();
1971        let ty = tcx.lift(ty).unwrap();
1972        pretty_print_const_value_tcx(tcx, ct, ty, fmt)
1973    })
1974}
1975
1976///////////////////////////////////////////////////////////////////////////
1977// Miscellaneous
1978
1979/// Calc converted u64 decimal into hex and return its length in chars.
1980///
1981/// ```ignore (cannot-test-private-function)
1982/// assert_eq!(1, hex_number_length(0));
1983/// assert_eq!(1, hex_number_length(1));
1984/// assert_eq!(2, hex_number_length(16));
1985/// ```
1986fn hex_number_length(x: u64) -> usize {
1987    if x == 0 {
1988        return 1;
1989    }
1990    let mut length = 0;
1991    let mut x_left = x;
1992    while x_left > 0 {
1993        x_left /= 16;
1994        length += 1;
1995    }
1996    length
1997}