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