rustc_middle/mir/
pretty.rs

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