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