Skip to main content

rustc_middle/mir/
pretty.rs

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