Skip to main content

rustc_middle/mir/
pretty.rs

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