Skip to main content

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