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::*;
18use crate::ty::CoroutineArgsExt;
19
20const INDENT: &str = " ";
21pub(crate) const ALIGN: usize = 40;
23
24#[derive(#[automatically_derived]
impl ::core::clone::Clone for PassWhere {
#[inline]
fn clone(&self) -> PassWhere {
let _: ::core::clone::AssertParamIsClone<BasicBlock>;
let _: ::core::clone::AssertParamIsClone<Location>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PassWhere { }Copy)]
27pub enum PassWhere {
28 BeforeCFG,
30
31 AfterCFG,
33
34 BeforeBlock(BasicBlock),
36
37 BeforeLocation(Location),
39
40 AfterLocation(Location),
42
43 AfterTerminator(BasicBlock),
45}
46
47#[derive(#[automatically_derived]
impl ::core::marker::Copy for PrettyPrintMirOptions { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PrettyPrintMirOptions {
#[inline]
fn clone(&self) -> PrettyPrintMirOptions {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone)]
50pub struct PrettyPrintMirOptions {
51 pub include_extra_comments: bool,
53}
54
55impl PrettyPrintMirOptions {
56 pub fn from_cli(tcx: TyCtxt<'_>) -> Self {
58 Self { include_extra_comments: tcx.sess.opts.unstable_opts.mir_include_spans.is_enabled() }
59 }
60}
61
62pub struct MirDumper<'a, 'tcx> {
66 show_pass_num: bool,
67 pass_name: &'static str,
68 disambiguator: &'a dyn Display,
69 writer: MirWriter<'a, 'tcx>,
70}
71
72impl<'a, 'tcx> MirDumper<'a, 'tcx> {
73 pub fn new(tcx: TyCtxt<'tcx>, pass_name: &'static str, body: &Body<'tcx>) -> Option<Self> {
80 let dump_enabled = if let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir {
81 let node_path = {
let _guard = NoTrimmedGuard::new();
{
let _guard = ForcedImplGuard::new();
tcx.def_path_str(body.source.def_id())
}
}ty::print::with_no_trimmed_paths!(
83 ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()))
84 );
85 filters.split('|').any(|or_filter| {
86 or_filter.split('&').all(|and_filter| {
87 let and_filter_trimmed = and_filter.trim();
88 and_filter_trimmed == "all"
89 || pass_name.contains(and_filter_trimmed)
90 || node_path.contains(and_filter_trimmed)
91 })
92 })
93 } else {
94 false
95 };
96
97 dump_enabled.then_some(MirDumper {
98 show_pass_num: false,
99 pass_name,
100 disambiguator: &0,
101 writer: MirWriter::new(tcx),
102 })
103 }
104
105 pub fn tcx(&self) -> TyCtxt<'tcx> {
106 self.writer.tcx
107 }
108
109 #[must_use]
110 pub fn set_show_pass_num(mut self) -> Self {
111 self.show_pass_num = true;
112 self
113 }
114
115 #[must_use]
116 pub fn set_disambiguator(mut self, disambiguator: &'a dyn Display) -> Self {
117 self.disambiguator = disambiguator;
118 self
119 }
120
121 #[must_use]
122 pub fn set_extra_data(
123 mut self,
124 extra_data: &'a dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
125 ) -> Self {
126 self.writer.extra_data = extra_data;
127 self
128 }
129
130 #[must_use]
131 pub fn set_options(mut self, options: PrettyPrintMirOptions) -> Self {
132 self.writer.options = options;
133 self
134 }
135
136 pub fn dump_mir(&self, body: &Body<'tcx>) {
161 let _ = try {
162 let mut file = self.create_dump_file("mir", body)?;
163 self.dump_mir_to_writer(body, &mut file)?;
164 };
165
166 if self.tcx().sess.opts.unstable_opts.dump_mir_graphviz {
167 let _ = try {
168 let mut file = self.create_dump_file("dot", body)?;
169 write_mir_fn_graphviz(self.tcx(), body, false, &mut file)?;
170 };
171 }
172 }
173
174 pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
177 let def_path =
179 {
let _guard = NoTrimmedGuard::new();
{
let _guard = ForcedImplGuard::new();
self.tcx().def_path_str(body.source.def_id())
}
}ty::print::with_no_trimmed_paths!(ty::print::with_forced_impl_filename_line!(
180 self.tcx().def_path_str(body.source.def_id())
181 ));
182 w.write_fmt(format_args!("// MIR for `{0}", def_path))write!(w, "// MIR for `{def_path}")?;
184 match body.source.promoted {
185 None => w.write_fmt(format_args!("`"))write!(w, "`")?,
186 Some(promoted) => w.write_fmt(format_args!("::{0:?}`", promoted))write!(w, "::{promoted:?}`")?,
187 }
188 w.write_fmt(format_args!(" {0} {1}\n", self.disambiguator, self.pass_name))writeln!(w, " {} {}", self.disambiguator, self.pass_name)?;
189 w.write_fmt(format_args!("\n"))writeln!(w)?;
190 (self.writer.extra_data)(PassWhere::BeforeCFG, w)?;
191 write_user_type_annotations(self.tcx(), body, w)?;
192 self.writer.write_mir_fn(body, w)?;
193 (self.writer.extra_data)(PassWhere::AfterCFG, w)
194 }
195
196 fn dump_path(&self, extension: &str, body: &Body<'tcx>) -> PathBuf {
200 let tcx = self.tcx();
201 let source = body.source;
202 let promotion_id = match source.promoted {
203 Some(id) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("-{0:?}", id))
})format!("-{id:?}"),
204 None => String::new(),
205 };
206
207 let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
208 String::new()
209 } else if self.show_pass_num {
210 let (dialect_index, phase_index) = body.phase.index();
211 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(".{0}-{1}-{2:03}", dialect_index,
phase_index, body.pass_count))
})format!(".{}-{}-{:03}", dialect_index, phase_index, body.pass_count)
212 } else {
213 ".-------".to_string()
214 };
215
216 let crate_name = tcx.crate_name(source.def_id().krate);
217 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
218 let shim_disambiguator = match source.instance {
221 ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(ty))) => {
222 let mut s = ".".to_owned();
225 s.extend(ty.to_string().chars().filter_map(|c| match c {
226 ' ' => None,
227 ':' | '<' | '>' => Some('_'),
228 c => Some(c),
229 }));
230 s
231 }
232 ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, ty)) => {
233 let mut s = ".".to_owned();
234 s.extend(ty.to_string().chars().filter_map(|c| match c {
235 ' ' => None,
236 ':' | '<' | '>' => Some('_'),
237 c => Some(c),
238 }));
239 s
240 }
241 ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, ty)) => {
242 let ty::Coroutine(_, args) = ty.kind() else {
243 crate::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
244 };
245 let ty = args.first().unwrap().expect_ty();
246 let mut s = ".".to_owned();
247 s.extend(ty.to_string().chars().filter_map(|c| match c {
248 ' ' => None,
249 ':' | '<' | '>' => Some('_'),
250 c => Some(c),
251 }));
252 s
253 }
254 ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(_, proxy_cor, impl_cor)) => {
255 let mut s = ".".to_owned();
256 s.extend(proxy_cor.to_string().chars().filter_map(|c| match c {
257 ' ' => None,
258 ':' | '<' | '>' => Some('_'),
259 c => Some(c),
260 }));
261 s.push('.');
262 s.extend(impl_cor.to_string().chars().filter_map(|c| match c {
263 ' ' => None,
264 ':' | '<' | '>' => Some('_'),
265 c => Some(c),
266 }));
267 s
268 }
269 _ => String::new(),
270 };
271
272 let mut file_path = PathBuf::new();
273 file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
274
275 let pass_name = self.pass_name;
276 let disambiguator = self.disambiguator;
277 let file_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}{2}{3}{4}.{5}.{6}.{7}",
crate_name, item_name, shim_disambiguator, promotion_id,
pass_num, pass_name, disambiguator, extension))
})format!(
278 "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}.{extension}",
279 );
280
281 file_path.push(&file_name);
282
283 file_path
284 }
285
286 pub fn create_dump_file(
291 &self,
292 extension: &str,
293 body: &Body<'tcx>,
294 ) -> io::Result<io::BufWriter<fs::File>> {
295 let file_path = self.dump_path(extension, body);
296 if let Some(parent) = file_path.parent() {
297 fs::create_dir_all(parent).map_err(|e| {
298 io::Error::new(
299 e.kind(),
300 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("IO error creating MIR dump directory: {0:?}; {1}",
parent, e))
})format!("IO error creating MIR dump directory: {parent:?}; {e}"),
301 )
302 })?;
303 }
304 fs::File::create_buffered(&file_path).map_err(|e| {
305 io::Error::new(e.kind(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("IO error creating MIR dump file: {0:?}; {1}",
file_path, e))
})format!("IO error creating MIR dump file: {file_path:?}; {e}"))
306 })
307 }
308}
309
310pub fn write_mir_pretty<'tcx>(tcx: TyCtxt<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
316 let writer = MirWriter::new(tcx);
317
318 w.write_fmt(format_args!("// WARNING: This output format is intended for human consumers only\n"))writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
319 w.write_fmt(format_args!("// and is subject to change without notice. Knock yourself out.\n"))writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
320 w.write_fmt(format_args!("// HINT: See also -Z dump-mir for MIR at specific points during compilation.\n"))writeln!(w, "// HINT: See also -Z dump-mir for MIR at specific points during compilation.")?;
321
322 let mut first = true;
323 for &def_id in tcx.mir_keys(()) {
324 if first {
325 first = false;
326 } else {
327 w.write_fmt(format_args!("\n"))writeln!(w)?;
329 }
330
331 let render_body = |w: &mut dyn io::Write, body| -> io::Result<()> {
332 writer.write_mir_fn(body, w)?;
333
334 for body in tcx.promoted_mir(def_id) {
335 w.write_fmt(format_args!("\n"))writeln!(w)?;
336 writer.write_mir_fn(body, w)?;
337 }
338 Ok(())
339 };
340
341 if tcx.is_const_fn(def_id) {
343 render_body(w, tcx.optimized_mir(def_id))?;
344 w.write_fmt(format_args!("\n"))writeln!(w)?;
345 w.write_fmt(format_args!("// MIR FOR CTFE\n"))writeln!(w, "// MIR FOR CTFE")?;
346 writer.write_mir_fn(tcx.mir_for_ctfe(def_id), w)?;
349 } else {
350 if let Some((val, ty)) = tcx.trivial_const(def_id) {
351 {
let _guard = ForcedImplGuard::new();
w.write_fmt(format_args!("const {0}", tcx.def_path_str(def_id)))?
}ty::print::with_forced_impl_filename_line! {
352 write!(w, "const {}", tcx.def_path_str(def_id))?
354 }
355 w.write_fmt(format_args!(": {0} = const {1};\n", ty, Const::Val(val, ty)))writeln!(w, ": {} = const {};", ty, Const::Val(val, ty))?;
356 } else {
357 let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id.to_def_id()));
358 render_body(w, instance_mir)?;
359 }
360 }
361 }
362 Ok(())
363}
364
365pub struct MirWriter<'a, 'tcx> {
367 tcx: TyCtxt<'tcx>,
368 extra_data: &'a dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
369 options: PrettyPrintMirOptions,
370}
371
372impl<'a, 'tcx> MirWriter<'a, 'tcx> {
373 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
374 MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
375 }
376
377 pub fn write_mir_fn(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
379 write_mir_intro(self.tcx, body, w, self.options)?;
380 for block in body.basic_blocks.indices() {
381 (self.extra_data)(PassWhere::BeforeBlock(block), w)?;
382 self.write_basic_block(block, body, w)?;
383 if block.index() + 1 != body.basic_blocks.len() {
384 w.write_fmt(format_args!("\n"))writeln!(w)?;
385 }
386 }
387
388 w.write_fmt(format_args!("}}\n"))writeln!(w, "}}")?;
389
390 write_allocations(self.tcx, body, w)?;
391
392 Ok(())
393 }
394}
395
396fn write_scope_tree(
398 tcx: TyCtxt<'_>,
399 body: &Body<'_>,
400 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
401 w: &mut dyn io::Write,
402 parent: SourceScope,
403 depth: usize,
404 options: PrettyPrintMirOptions,
405) -> io::Result<()> {
406 let indent = depth * INDENT.len();
407
408 for var_debug_info in &body.var_debug_info {
410 if var_debug_info.source_info.scope != parent {
411 continue;
413 }
414
415 let indented_debug_info = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:1$}debug {2:?};", INDENT,
indent, var_debug_info))
})format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
416
417 if options.include_extra_comments {
418 w.write_fmt(format_args!("{0:1$} // in {2}\n", indented_debug_info, ALIGN,
comment(tcx, var_debug_info.source_info)))writeln!(
419 w,
420 "{0:1$} // in {2}",
421 indented_debug_info,
422 ALIGN,
423 comment(tcx, var_debug_info.source_info),
424 )?;
425 } else {
426 w.write_fmt(format_args!("{0}\n", indented_debug_info))writeln!(w, "{indented_debug_info}")?;
427 }
428 }
429
430 if let Some(layout) = body.coroutine_layout_raw() {
432 for (field, field_decl) in layout.field_tys.iter_enumerated() {
433 let source_info = field_decl.source_info;
434 if let Some(name) = field_decl.debuginfo_name
435 && source_info.scope == parent
436 {
437 let indented_debug_info =
438 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:1$}coroutine debug {2} => {3:?};",
INDENT, indent, name, field))
})format!("{0:1$}coroutine debug {2} => {3:?};", INDENT, indent, name, field);
439
440 if options.include_extra_comments {
441 w.write_fmt(format_args!("{0:1$} // in {2}\n", indented_debug_info, ALIGN,
comment(tcx, source_info)))writeln!(
442 w,
443 "{0:1$} // in {2}",
444 indented_debug_info,
445 ALIGN,
446 comment(tcx, source_info),
447 )?;
448 } else {
449 w.write_fmt(format_args!("{0}\n", indented_debug_info))writeln!(w, "{indented_debug_info}")?;
450 }
451 }
452 }
453 }
454
455 for (local, local_decl) in body.local_decls.iter_enumerated() {
457 if (1..body.arg_count + 1).contains(&local.index()) {
458 continue;
460 }
461
462 if local_decl.source_info.scope != parent {
463 continue;
465 }
466
467 let mut_str = local_decl.mutability.prefix_str();
468
469 let mut indented_decl = {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:1$}let {2}{3:?}: {4}",
INDENT, indent, mut_str, local, local_decl.ty))
})
}ty::print::with_no_trimmed_paths!(format!(
470 "{0:1$}let {2}{3:?}: {4}",
471 INDENT, indent, mut_str, local, local_decl.ty
472 ));
473 if let Some(user_ty) = &local_decl.user_ty {
474 for user_ty in user_ty.projections() {
475 indented_decl.write_fmt(format_args!(" as {0:?}", user_ty))write!(indented_decl, " as {user_ty:?}").unwrap();
476 }
477 }
478 indented_decl.push(';');
479
480 let local_name = if local == RETURN_PLACE { " return place" } else { "" };
481
482 if options.include_extra_comments {
483 w.write_fmt(format_args!("{0:1$} //{2} in {3}\n", indented_decl, ALIGN,
local_name, comment(tcx, local_decl.source_info)))writeln!(
484 w,
485 "{0:1$} //{2} in {3}",
486 indented_decl,
487 ALIGN,
488 local_name,
489 comment(tcx, local_decl.source_info),
490 )?;
491 } else {
492 w.write_fmt(format_args!("{0}\n", indented_decl))writeln!(w, "{indented_decl}",)?;
493 }
494 }
495
496 let Some(children) = scope_tree.get(&parent) else {
497 return Ok(());
498 };
499
500 for &child in children {
501 let child_data = &body.source_scopes[child];
502 {
match (&child_data.parent_scope, &Some(parent)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(child_data.parent_scope, Some(parent));
503
504 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
505 (
506 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" (inlined {0}{1})",
if callee.def.requires_caller_location(tcx) {
"#[track_caller] "
} else { "" }, callee))
})format!(
507 " (inlined {}{})",
508 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
509 callee
510 ),
511 Some(callsite_span),
512 )
513 } else {
514 (String::new(), None)
515 };
516
517 let indented_header = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:1$}scope {2}{3} {{", "", indent,
child.index(), special))
})format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
518
519 if options.include_extra_comments {
520 if let Some(span) = span {
521 w.write_fmt(format_args!("{0:1$} // at {2}\n", indented_header, ALIGN,
tcx.sess.source_map().span_to_diagnostic_string(span)))writeln!(
522 w,
523 "{0:1$} // at {2}",
524 indented_header,
525 ALIGN,
526 tcx.sess.source_map().span_to_diagnostic_string(span),
527 )?;
528 } else {
529 w.write_fmt(format_args!("{0}\n", indented_header))writeln!(w, "{indented_header}")?;
530 }
531 } else {
532 w.write_fmt(format_args!("{0}\n", indented_header))writeln!(w, "{indented_header}")?;
533 }
534
535 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
536 w.write_fmt(format_args!("{0:1$}}}\n", "", depth * INDENT.len()))writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
537 }
538
539 Ok(())
540}
541
542impl Debug for VarDebugInfo<'_> {
543 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
544 if let Some(VarDebugInfoFragment { ty, ref projection }) = self.composite {
545 pre_fmt_projection(&projection[..], fmt)?;
546 fmt.write_fmt(format_args!("({0}: {1})", self.name, ty))write!(fmt, "({}: {})", self.name, ty)?;
547 post_fmt_projection(&projection[..], fmt)?;
548 } else {
549 fmt.write_fmt(format_args!("{0}", self.name))write!(fmt, "{}", self.name)?;
550 }
551
552 fmt.write_fmt(format_args!(" => {0:?}", self.value))write!(fmt, " => {:?}", self.value)
553 }
554}
555
556fn write_coroutine_layout<'tcx>(
557 tcx: TyCtxt<'tcx>,
558 layout: &CoroutineLayout<'_>,
559 w: &mut dyn io::Write,
560 options: PrettyPrintMirOptions,
561) -> io::Result<()> {
562 let CoroutineLayout { field_tys, variant_fields, variant_source_info, storage_conflicts } =
563 layout;
564
565 w.write_fmt(format_args!("{0}coroutine layout {{\n", INDENT))writeln!(w, "{INDENT}coroutine layout {{")?;
566
567 for (field, CoroutineSavedTy { ty, source_info, ignore_for_traits, debuginfo_name: _ }) in
568 field_tys.iter_enumerated()
569 {
570 let ignore_for_traits = if *ignore_for_traits { " (ignored for traits)" } else { "" };
571 let indented_body = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{0}field {1:?}: {2}{3};",
INDENT, field, ty, ignore_for_traits))
})format!("{INDENT}{INDENT}field {field:?}: {ty}{ignore_for_traits};",);
572 if options.include_extra_comments {
573 w.write_fmt(format_args!("{0:2$} // in {1}\n", indented_body,
comment(tcx, *source_info), ALIGN))writeln!(w, "{0:ALIGN$} // in {1}", indented_body, comment(tcx, *source_info))?;
574 } else {
575 w.write_fmt(format_args!("{0}\n", indented_body))writeln!(w, "{}", indented_body)?;
576 }
577 }
578
579 w.write_fmt(format_args!("{0}{0}variant_fields = {{\n", INDENT))writeln!(w, "{INDENT}{INDENT}variant_fields = {{")?;
580 for (variant, fields) in variant_fields.iter_enumerated() {
581 let variant_name = ty::CoroutineArgs::variant_name(variant);
582 let header = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{0}{0}{1:9}({2:?}): {3:?},",
INDENT, variant_name, variant, fields))
})format!("{INDENT}{INDENT}{INDENT}{variant_name:9}({variant:?}): {fields:?},");
583 if options.include_extra_comments {
584 let source_info = variant_source_info[variant];
585 w.write_fmt(format_args!("{0:2$} // in {1}\n", header,
comment(tcx, source_info), ALIGN))writeln!(w, "{0:ALIGN$} // in {1}", header, comment(tcx, source_info))?;
586 } else {
587 w.write_fmt(format_args!("{0}\n", header))writeln!(w, "{}", header)?;
588 }
589 }
590 w.write_fmt(format_args!("{0}{0}}}\n", INDENT))writeln!(w, "{INDENT}{INDENT}}}")?;
591 w.write_fmt(format_args!("{0}{0}storage_conflicts = {1:?}\n", INDENT,
storage_conflicts))writeln!(w, "{INDENT}{INDENT}storage_conflicts = {storage_conflicts:?}")?;
592 w.write_fmt(format_args!("{0}}}\n", INDENT))writeln!(w, "{INDENT}}}")
593}
594
595fn write_mir_intro<'tcx>(
598 tcx: TyCtxt<'tcx>,
599 body: &Body<'_>,
600 w: &mut dyn io::Write,
601 options: PrettyPrintMirOptions,
602) -> io::Result<()> {
603 write_mir_sig(tcx, body, w)?;
604 w.write_fmt(format_args!("{{\n"))writeln!(w, "{{")?;
605
606 if let Some(ref layout) = body.coroutine_layout_raw() {
607 write_coroutine_layout(tcx, layout, w, options)?;
608 }
609
610 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
612 for (index, scope_data) in body.source_scopes.iter_enumerated() {
613 if let Some(parent) = scope_data.parent_scope {
614 scope_tree.entry(parent).or_default().push(index);
615 } else {
616 {
match (&index, &OUTERMOST_SOURCE_SCOPE) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
618 }
619 }
620
621 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
622
623 w.write_fmt(format_args!("\n"))writeln!(w)?;
625
626 if let Some(coverage_info_hi) = &body.coverage_info_hi {
627 write_coverage_info_hi(coverage_info_hi, w)?;
628 }
629 if let Some(function_coverage_info) = &body.function_coverage_info {
630 write_function_coverage_info(function_coverage_info, w)?;
631 }
632
633 Ok(())
634}
635
636fn write_coverage_info_hi(
637 coverage_info_hi: &coverage::CoverageInfoHi,
638 w: &mut dyn io::Write,
639) -> io::Result<()> {
640 let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
641
642 let mut did_print = false;
644
645 for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
646 w.write_fmt(format_args!("{0}coverage branch {{ true: {1:?}, false: {2:?} }} => {3:?}\n",
INDENT, true_marker, false_marker, span))writeln!(
647 w,
648 "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
649 )?;
650 did_print = true;
651 }
652
653 if did_print {
654 w.write_fmt(format_args!("\n"))writeln!(w)?;
655 }
656
657 Ok(())
658}
659
660fn write_function_coverage_info(
661 function_coverage_info: &coverage::FunctionCoverageInfo,
662 w: &mut dyn io::Write,
663) -> io::Result<()> {
664 let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
665
666 for coverage::Mapping { kind, span } in mappings {
667 w.write_fmt(format_args!("{0}coverage {1:?} => {2:?};\n", INDENT, kind, span))writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
668 }
669 w.write_fmt(format_args!("\n"))writeln!(w)?;
670
671 Ok(())
672}
673
674fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
675 use rustc_hir::def::DefKind;
676
677 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/pretty.rs:677",
"rustc_middle::mir::pretty", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/pretty.rs"),
::tracing_core::__macro_support::Option::Some(677u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::mir::pretty"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("write_mir_sig: {0:?}",
body.source.instance) as &dyn Value))])
});
} else { ; }
};trace!("write_mir_sig: {:?}", body.source.instance);
678 let def_id = body.source.def_id();
679 let kind = tcx.def_kind(def_id);
680 let is_function = match kind {
681 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
682 true
683 }
684 _ => tcx.is_closure_like(def_id),
685 };
686 match (kind, body.source.promoted) {
687 (_, Some(_)) => w.write_fmt(format_args!("const "))write!(w, "const ")?, (DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => w.write_fmt(format_args!("const "))write!(w, "const ")?,
689 (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
690 w.write_fmt(format_args!("static "))write!(w, "static ")?
691 }
692 (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
693 w.write_fmt(format_args!("static mut "))write!(w, "static mut ")?
694 }
695 (_, _) if is_function => w.write_fmt(format_args!("fn "))write!(w, "fn ")?,
696 (DefKind::AnonConst, _) => {}
698 (DefKind::GlobalAsm, _) => {}
700 _ => crate::util::bug::bug_fmt(format_args!("Unexpected def kind {0:?}", kind))bug!("Unexpected def kind {:?}", kind),
701 }
702
703 {
let _guard = ForcedImplGuard::new();
w.write_fmt(format_args!("{0}", tcx.def_path_str(def_id)))?
}ty::print::with_forced_impl_filename_line! {
704 write!(w, "{}", tcx.def_path_str(def_id))?
706 }
707 if let Some(p) = body.source.promoted {
708 w.write_fmt(format_args!("::{0:?}", p))write!(w, "::{p:?}")?;
709 }
710
711 if body.source.promoted.is_none() && is_function {
712 w.write_fmt(format_args!("("))write!(w, "(")?;
713
714 for (i, arg) in body.args_iter().enumerate() {
716 if i != 0 {
717 w.write_fmt(format_args!(", "))write!(w, ", ")?;
718 }
719 w.write_fmt(format_args!("{0:?}: {1}", Place::from(arg),
body.local_decls[arg].ty))write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
720 }
721
722 w.write_fmt(format_args!(") -> {0}", body.return_ty()))write!(w, ") -> {}", body.return_ty())?;
723 } else {
724 {
match (&body.arg_count, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(body.arg_count, 0);
725 w.write_fmt(format_args!(": {0} =", body.return_ty()))write!(w, ": {} =", body.return_ty())?;
726 }
727
728 if let Some(yield_ty) = body.yield_ty() {
729 w.write_fmt(format_args!("\n"))writeln!(w)?;
730 w.write_fmt(format_args!("yields {0}\n", yield_ty))writeln!(w, "yields {yield_ty}")?;
731 }
732
733 w.write_fmt(format_args!(" "))write!(w, " ")?;
734 Ok(())
737}
738
739fn write_user_type_annotations(
740 tcx: TyCtxt<'_>,
741 body: &Body<'_>,
742 w: &mut dyn io::Write,
743) -> io::Result<()> {
744 if !body.user_type_annotations.is_empty() {
745 w.write_fmt(format_args!("| User Type Annotations\n"))writeln!(w, "| User Type Annotations")?;
746 }
747 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
748 w.write_fmt(format_args!("| {0:?}: user_ty: {1}, span: {2}, inferred_ty: {3}\n",
index.index(), annotation.user_ty,
tcx.sess.source_map().span_to_diagnostic_string(annotation.span),
{
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
annotation.inferred_ty))
})
}))writeln!(
749 w,
750 "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
751 index.index(),
752 annotation.user_ty,
753 tcx.sess.source_map().span_to_diagnostic_string(annotation.span),
754 with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
755 )?;
756 }
757 if !body.user_type_annotations.is_empty() {
758 w.write_fmt(format_args!("|\n"))writeln!(w, "|")?;
759 }
760 Ok(())
761}
762
763impl<'a, 'tcx> MirWriter<'a, 'tcx> {
767 fn write_basic_block(
769 &self,
770 block: BasicBlock,
771 body: &Body<'tcx>,
772 w: &mut dyn io::Write,
773 ) -> io::Result<()> {
774 let data = &body[block];
775
776 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
778 w.write_fmt(format_args!("{0}{1:?}{2}: {{\n", INDENT, block, cleanup_text))writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
779
780 let mut current_location = Location { block, statement_index: 0 };
782 for statement in &data.statements {
783 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
784
785 for debuginfo in statement.debuginfos.iter() {
786 w.write_fmt(format_args!("{0}{0}// DBG: {1:?};\n", INDENT, debuginfo))writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
787 }
788
789 let indented_body = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{0}{1:?};", INDENT, statement))
})format!("{INDENT}{INDENT}{statement:?};");
790 if self.options.include_extra_comments {
791 w.write_fmt(format_args!("{0:3$} // {1}{2}\n", indented_body,
if self.tcx.sess.verbose_internals() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: ",
current_location))
})
} else { String::new() }, comment(self.tcx, statement.source_info),
ALIGN))writeln!(
792 w,
793 "{:A$} // {}{}",
794 indented_body,
795 if self.tcx.sess.verbose_internals() {
796 format!("{current_location:?}: ")
797 } else {
798 String::new()
799 },
800 comment(self.tcx, statement.source_info),
801 A = ALIGN,
802 )?;
803 } else {
804 w.write_fmt(format_args!("{0}\n", indented_body))writeln!(w, "{indented_body}")?;
805 }
806
807 write_extra(
808 self.tcx,
809 w,
810 &|visitor| visitor.visit_statement(statement, current_location),
811 self.options,
812 )?;
813
814 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
815
816 current_location.statement_index += 1;
817 }
818
819 for debuginfo in data.after_last_stmt_debuginfos.iter() {
820 w.write_fmt(format_args!("{0}{0}// DBG: {1:?};\n", INDENT, debuginfo))writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
821 }
822
823 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
825 if data.terminator.is_some() {
826 let indented_terminator = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{0}{1:?};", INDENT,
data.terminator().kind))
})format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
827 if self.options.include_extra_comments {
828 w.write_fmt(format_args!("{0:3$} // {1}{2}\n", indented_terminator,
if self.tcx.sess.verbose_internals() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: ",
current_location))
})
} else { String::new() },
comment(self.tcx, data.terminator().source_info), ALIGN))writeln!(
829 w,
830 "{:A$} // {}{}",
831 indented_terminator,
832 if self.tcx.sess.verbose_internals() {
833 format!("{current_location:?}: ")
834 } else {
835 String::new()
836 },
837 comment(self.tcx, data.terminator().source_info),
838 A = ALIGN,
839 )?;
840 } else {
841 w.write_fmt(format_args!("{0}\n", indented_terminator))writeln!(w, "{indented_terminator}")?;
842 }
843
844 write_extra(
845 self.tcx,
846 w,
847 &|visitor| visitor.visit_terminator(data.terminator(), current_location),
848 self.options,
849 )?;
850 }
851
852 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
853 (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
854
855 w.write_fmt(format_args!("{0}}}\n", INDENT))writeln!(w, "{INDENT}}}")
856 }
857}
858
859impl Debug for StatementKind<'_> {
860 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
861 use self::StatementKind::*;
862 match *self {
863 Assign((ref place, ref rv)) => fmt.write_fmt(format_args!("{0:?} = {1:?}", place, rv))write!(fmt, "{place:?} = {rv:?}"),
864 FakeRead((ref cause, ref place)) => {
865 fmt.write_fmt(format_args!("FakeRead({0:?}, {1:?})", cause, place))write!(fmt, "FakeRead({cause:?}, {place:?})")
866 }
867 StorageLive(ref place) => fmt.write_fmt(format_args!("StorageLive({0:?})", place))write!(fmt, "StorageLive({place:?})"),
868 StorageDead(ref place) => fmt.write_fmt(format_args!("StorageDead({0:?})", place))write!(fmt, "StorageDead({place:?})"),
869 SetDiscriminant { ref place, variant_index } => {
870 fmt.write_fmt(format_args!("discriminant({0:?}) = {1:?}", place,
variant_index))write!(fmt, "discriminant({place:?}) = {variant_index:?}")
871 }
872 PlaceMention(ref place) => {
873 fmt.write_fmt(format_args!("PlaceMention({0:?})", place))write!(fmt, "PlaceMention({place:?})")
874 }
875 AscribeUserType((ref place, ref c_ty), ref variance) => {
876 fmt.write_fmt(format_args!("AscribeUserType({0:?}, {1:?}, {2:?})", place,
variance, c_ty))write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
877 }
878 Coverage(ref kind) => fmt.write_fmt(format_args!("Coverage::{0:?}", kind))write!(fmt, "Coverage::{kind:?}"),
879 Intrinsic(ref intrinsic) => fmt.write_fmt(format_args!("{0}", intrinsic))write!(fmt, "{intrinsic}"),
880 ConstEvalCounter => fmt.write_fmt(format_args!("ConstEvalCounter"))write!(fmt, "ConstEvalCounter"),
881 Nop => fmt.write_fmt(format_args!("nop"))write!(fmt, "nop"),
882 BackwardIncompatibleDropHint { ref place, reason: _ } => {
883 fmt.write_fmt(format_args!("BackwardIncompatibleDropHint({0:?})", place))write!(fmt, "BackwardIncompatibleDropHint({place:?})")
886 }
887 }
888 }
889}
890impl Debug for Statement<'_> {
891 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
892 self.kind.fmt(fmt)
893 }
894}
895
896impl Debug for StmtDebugInfo<'_> {
897 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
898 match self {
899 StmtDebugInfo::AssignRef(local, place) => {
900 fmt.write_fmt(format_args!("{0:?} = &{1:?}", local, place))write!(fmt, "{local:?} = &{place:?}")
901 }
902 StmtDebugInfo::InvalidAssign(local) => {
903 fmt.write_fmt(format_args!("{0:?} = &?", local))write!(fmt, "{local:?} = &?")
904 }
905 }
906 }
907}
908
909impl Display for NonDivergingIntrinsic<'_> {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 match self {
912 Self::Assume(op) => f.write_fmt(format_args!("assume({0:?})", op))write!(f, "assume({op:?})"),
913 Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
914 f.write_fmt(format_args!("copy_nonoverlapping(dst = {0:?}, src = {1:?}, count = {2:?})",
dst, src, count))write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
915 }
916 }
917 }
918}
919
920impl<'tcx> Debug for TerminatorKind<'tcx> {
921 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
922 self.fmt_head(fmt)?;
923 let successor_count = self.successors().count();
924 let labels = self.fmt_successor_labels();
925 {
match (&successor_count, &labels.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(successor_count, labels.len());
926
927 let show_unwind = !#[allow(non_exhaustive_omitted_patterns)] match self.unwind() {
None | Some(UnwindAction::Cleanup(_)) => true,
_ => false,
}matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
929 let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
930 fmt.write_fmt(format_args!("unwind "))write!(fmt, "unwind ")?;
931 match self.unwind() {
932 None | Some(UnwindAction::Cleanup(_)) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
934 Some(UnwindAction::Continue) => fmt.write_fmt(format_args!("continue"))write!(fmt, "continue"),
935 Some(UnwindAction::Unreachable) => fmt.write_fmt(format_args!("unreachable"))write!(fmt, "unreachable"),
936 Some(UnwindAction::Terminate(reason)) => {
937 fmt.write_fmt(format_args!("terminate({0})", reason.as_short_str()))write!(fmt, "terminate({})", reason.as_short_str())
938 }
939 }
940 };
941
942 match (successor_count, show_unwind) {
943 (0, false) => Ok(()),
944 (0, true) => {
945 fmt.write_fmt(format_args!(" -> "))write!(fmt, " -> ")?;
946 fmt_unwind(fmt)
947 }
948 (1, false) => fmt.write_fmt(format_args!(" -> {0:?}", self.successors().next().unwrap()))write!(fmt, " -> {:?}", self.successors().next().unwrap()),
949 _ => {
950 fmt.write_fmt(format_args!(" -> ["))write!(fmt, " -> [")?;
951 for (i, target) in self.successors().enumerate() {
952 if i > 0 {
953 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
954 }
955 fmt.write_fmt(format_args!("{0}: {1:?}", labels[i], target))write!(fmt, "{}: {:?}", labels[i], target)?;
956 }
957 if show_unwind {
958 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
959 fmt_unwind(fmt)?;
960 }
961 fmt.write_fmt(format_args!("]"))write!(fmt, "]")
962 }
963 }
964 }
965}
966impl Debug for Terminator<'_> {
967 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
968 self.kind.fmt(fmt)
969 }
970}
971
972impl<'tcx> TerminatorKind<'tcx> {
973 pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
977 use self::TerminatorKind::*;
978 match self {
979 Goto { .. } => fmt.write_fmt(format_args!("goto"))write!(fmt, "goto"),
980 SwitchInt { discr, .. } => fmt.write_fmt(format_args!("switchInt({0:?})", discr))write!(fmt, "switchInt({discr:?})"),
981 Return => fmt.write_fmt(format_args!("return"))write!(fmt, "return"),
982 CoroutineDrop => fmt.write_fmt(format_args!("coroutine_drop"))write!(fmt, "coroutine_drop"),
983 UnwindResume => fmt.write_fmt(format_args!("resume"))write!(fmt, "resume"),
984 UnwindTerminate(reason) => {
985 fmt.write_fmt(format_args!("terminate({0})", reason.as_short_str()))write!(fmt, "terminate({})", reason.as_short_str())
986 }
987 Yield { value, resume_arg, .. } => fmt.write_fmt(format_args!("{0:?} = yield({1:?})", resume_arg, value))write!(fmt, "{resume_arg:?} = yield({value:?})"),
988 Unreachable => fmt.write_fmt(format_args!("unreachable"))write!(fmt, "unreachable"),
989 Drop { place, .. } => fmt.write_fmt(format_args!("drop({0:?})", place))write!(fmt, "drop({place:?})"),
990 Call { func, args, destination, .. } => {
991 fmt.write_fmt(format_args!("{0:?} = ", destination))write!(fmt, "{destination:?} = ")?;
992 fmt.write_fmt(format_args!("{0:?}(", func))write!(fmt, "{func:?}(")?;
993 for (index, arg) in args.iter().enumerate() {
994 if index > 0 {
995 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
996 }
997 fmt.write_fmt(format_args!("{0:?}", arg.node))write!(fmt, "{:?}", arg.node)?;
998 }
999 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1000 }
1001 TailCall { func, args, .. } => {
1002 fmt.write_fmt(format_args!("tailcall {0:?}(", func))write!(fmt, "tailcall {func:?}(")?;
1003 for (index, arg) in args.iter().enumerate() {
1004 if index > 0 {
1005 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
1006 }
1007 fmt.write_fmt(format_args!("{0:?}", arg.node))write!(fmt, "{:?}", arg.node)?;
1008 }
1009 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1010 }
1011 Assert { cond, expected, msg, .. } => {
1012 fmt.write_fmt(format_args!("assert("))write!(fmt, "assert(")?;
1013 if !expected {
1014 fmt.write_fmt(format_args!("!"))write!(fmt, "!")?;
1015 }
1016 fmt.write_fmt(format_args!("{0:?}, ", cond))write!(fmt, "{cond:?}, ")?;
1017 msg.fmt_assert_args(fmt)?;
1018 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1019 }
1020 FalseEdge { .. } => fmt.write_fmt(format_args!("falseEdge"))write!(fmt, "falseEdge"),
1021 FalseUnwind { .. } => fmt.write_fmt(format_args!("falseUnwind"))write!(fmt, "falseUnwind"),
1022 InlineAsm { template, operands, options, .. } => {
1023 fmt.write_fmt(format_args!("asm!(\"{0}\"",
InlineAsmTemplatePiece::to_string(template)))write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
1024 for op in operands {
1025 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
1026 let print_late = |&late| if late { "late" } else { "" };
1027 match op {
1028 InlineAsmOperand::In { reg, value } => {
1029 fmt.write_fmt(format_args!("in({0}) {1:?}", reg, value))write!(fmt, "in({reg}) {value:?}")?;
1030 }
1031 InlineAsmOperand::Out { reg, late, place: Some(place) } => {
1032 fmt.write_fmt(format_args!("{0}out({1}) {2:?}", print_late(late), reg, place))write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
1033 }
1034 InlineAsmOperand::Out { reg, late, place: None } => {
1035 fmt.write_fmt(format_args!("{0}out({1}) _", print_late(late), reg))write!(fmt, "{}out({}) _", print_late(late), reg)?;
1036 }
1037 InlineAsmOperand::InOut {
1038 reg,
1039 late,
1040 in_value,
1041 out_place: Some(out_place),
1042 } => {
1043 fmt.write_fmt(format_args!("in{0}out({1}) {2:?} => {3:?}", print_late(late),
reg, in_value, out_place))write!(
1044 fmt,
1045 "in{}out({}) {:?} => {:?}",
1046 print_late(late),
1047 reg,
1048 in_value,
1049 out_place
1050 )?;
1051 }
1052 InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
1053 fmt.write_fmt(format_args!("in{0}out({1}) {2:?} => _", print_late(late), reg,
in_value))write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
1054 }
1055 InlineAsmOperand::Const { value } => {
1056 fmt.write_fmt(format_args!("const {0:?}", value))write!(fmt, "const {value:?}")?;
1057 }
1058 InlineAsmOperand::SymFn { value } => {
1059 fmt.write_fmt(format_args!("sym_fn {0:?}", value))write!(fmt, "sym_fn {value:?}")?;
1060 }
1061 InlineAsmOperand::SymStatic { def_id } => {
1062 fmt.write_fmt(format_args!("sym_static {0:?}", def_id))write!(fmt, "sym_static {def_id:?}")?;
1063 }
1064 InlineAsmOperand::Label { target_index } => {
1065 fmt.write_fmt(format_args!("label {0}", target_index))write!(fmt, "label {target_index}")?;
1066 }
1067 }
1068 }
1069 fmt.write_fmt(format_args!(", options({0:?}))", options))write!(fmt, ", options({options:?}))")
1070 }
1071 }
1072 }
1073
1074 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1076 use self::TerminatorKind::*;
1077 match *self {
1078 Return
1079 | TailCall { .. }
1080 | UnwindResume
1081 | UnwindTerminate(_)
1082 | Unreachable
1083 | CoroutineDrop => ::alloc::vec::Vec::new()vec![],
1084 Goto { .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["".into()]))vec!["".into()],
1085 SwitchInt { ref targets, .. } => targets
1086 .values
1087 .iter()
1088 .map(|&u| Cow::Owned(u.to_string()))
1089 .chain(iter::once("otherwise".into()))
1090 .collect(),
1091 Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1092 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into()]))vec!["return".into(), "unwind".into()]
1093 }
1094 Call { target: Some(_), unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into()]))vec!["return".into()],
1095 Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["unwind".into()]))vec!["unwind".into()],
1096 Call { target: None, unwind: _, .. } => ::alloc::vec::Vec::new()vec![],
1097 Yield { drop: Some(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["resume".into(), "drop".into()]))vec!["resume".into(), "drop".into()],
1098 Yield { drop: None, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["resume".into()]))vec!["resume".into()],
1099 Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1100 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into(), "drop".into()]))vec!["return".into(), "unwind".into(), "drop".into()]
1101 }
1102 Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1103 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into()]))vec!["return".into(), "unwind".into()]
1104 }
1105 Drop { unwind: _, drop: Some(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "drop".into()]))vec!["return".into(), "drop".into()],
1106 Drop { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into()]))vec!["return".into()],
1107 Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1108 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["success".into(), "unwind".into()]))vec!["success".into(), "unwind".into()]
1109 }
1110 Assert { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["success".into()]))vec!["success".into()],
1111 FalseEdge { .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into(), "imaginary".into()]))vec!["real".into(), "imaginary".into()],
1112 FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1113 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into(), "unwind".into()]))vec!["real".into(), "unwind".into()]
1114 }
1115 FalseUnwind { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into()]))vec!["real".into()],
1116 InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1117 let mut vec = Vec::with_capacity(targets.len() + 1);
1118 if !asm_macro.diverges(options) {
1119 vec.push("return".into());
1120 }
1121 vec.resize(targets.len(), "label".into());
1122
1123 if let UnwindAction::Cleanup(_) = unwind {
1124 vec.push("unwind".into());
1125 }
1126
1127 vec
1128 }
1129 }
1130 }
1131}
1132
1133impl<'tcx> Debug for Rvalue<'tcx> {
1134 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1135 use self::Rvalue::*;
1136
1137 match *self {
1138 Use(ref operand, with_retag) => {
1139 fmt.write_fmt(format_args!("{0}{1:?}",
if with_retag.no() { "no_retag " } else { "" }, operand))write!(fmt, "{}{operand:?}", if with_retag.no() { "no_retag " } else { "" })
1141 }
1142 Repeat(ref a, b) => {
1143 fmt.write_fmt(format_args!("[{0:?}; ", a))write!(fmt, "[{a:?}; ")?;
1144 pretty_print_const(b, fmt, false)?;
1145 fmt.write_fmt(format_args!("]"))write!(fmt, "]")
1146 }
1147 Cast(ref kind, ref place, ref ty) => {
1148 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!("{0:?} as {1} ({2:?})", place, ty, kind))
}with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1149 }
1150 BinaryOp(ref op, (ref a, ref b)) => fmt.write_fmt(format_args!("{0:?}({1:?}, {2:?})", op, a, b))write!(fmt, "{op:?}({a:?}, {b:?})"),
1151 UnaryOp(ref op, ref a) => fmt.write_fmt(format_args!("{0:?}({1:?})", op, a))write!(fmt, "{op:?}({a:?})"),
1152 Discriminant(ref place) => fmt.write_fmt(format_args!("discriminant({0:?})", place))write!(fmt, "discriminant({place:?})"),
1153 ThreadLocalRef(did) => ty::tls::with(|tcx| {
1154 let muta = tcx.static_mutability(did).unwrap().prefix_str();
1155 fmt.write_fmt(format_args!("&/*tls*/ {0}{1}", muta, tcx.def_path_str(did)))write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1156 }),
1157 Ref(region, borrow_kind, ref place) => {
1158 let kind_str = match borrow_kind {
1159 BorrowKind::Shared => "",
1160 BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1161 BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1162 BorrowKind::Mut { .. } => "mut ",
1163 };
1164
1165 let print_region = ty::tls::with(|tcx| {
1167 tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1168 });
1169 let region = if print_region {
1170 let mut region = region.to_string();
1171 if !region.is_empty() {
1172 region.push(' ');
1173 }
1174 region
1175 } else {
1176 String::new()
1178 };
1179 fmt.write_fmt(format_args!("&{0}{1}{2:?}", region, kind_str, place))write!(fmt, "&{region}{kind_str}{place:?}")
1180 }
1181
1182 Reborrow(target, mutability, ref place) => {
1183 fmt.write_fmt(format_args!("{1:?}({0} {2:?})",
if mutability.is_mut() { "reborrow" } else { "coerce shared" },
target, place))write!(
1184 fmt,
1185 "{target:?}({} {place:?})",
1186 if mutability.is_mut() { "reborrow" } else { "coerce shared" }
1187 )
1188 }
1189
1190 CopyForDeref(ref place) => fmt.write_fmt(format_args!("deref_copy {0:#?}", place))write!(fmt, "deref_copy {place:#?}"),
1191
1192 RawPtr(mutability, ref place) => {
1193 fmt.write_fmt(format_args!("&raw {0} {1:?}", mutability.ptr_str(), place))write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1194 }
1195
1196 Aggregate(ref kind, ref places) => {
1197 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1198 let mut tuple_fmt = fmt.debug_tuple(name);
1199 for place in places {
1200 tuple_fmt.field(place);
1201 }
1202 tuple_fmt.finish()
1203 };
1204
1205 match **kind {
1206 AggregateKind::Array(_) => fmt.write_fmt(format_args!("{0:?}", places))write!(fmt, "{places:?}"),
1207
1208 AggregateKind::Tuple => {
1209 if places.is_empty() {
1210 fmt.write_fmt(format_args!("()"))write!(fmt, "()")
1211 } else {
1212 fmt_tuple(fmt, "")
1213 }
1214 }
1215
1216 AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1217 ty::tls::with(|tcx| {
1218 let variant_def = &tcx.adt_def(adt_did).variant(variant);
1219 let args = tcx.lift(args);
1220 let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1221 p.print_def_path(variant_def.def_id, args)
1222 })?;
1223
1224 match variant_def.ctor_kind() {
1225 Some(CtorKind::Const) => fmt.write_str(&name),
1226 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1227 None => {
1228 let mut struct_fmt = fmt.debug_struct(&name);
1229 for (field, place) in iter::zip(&variant_def.fields, places) {
1230 struct_fmt.field(field.name.as_str(), place);
1231 }
1232 struct_fmt.finish()
1233 }
1234 }
1235 })
1236 }
1237
1238 AggregateKind::Closure(def_id, args)
1239 | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1240 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1241 let args = tcx.lift(args);
1242 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{closure@{0}}}",
tcx.def_path_str_with_args(def_id, args)))
})format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1243 } else {
1244 let span = tcx.def_span(def_id);
1245 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{closure@{0}}}",
tcx.sess.source_map().span_to_diagnostic_string(span)))
})format!(
1246 "{{closure@{}}}",
1247 tcx.sess.source_map().span_to_diagnostic_string(span)
1248 )
1249 };
1250 let mut struct_fmt = fmt.debug_struct(&name);
1251
1252 if let Some(def_id) = def_id.as_local()
1254 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1255 {
1256 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1257 let var_name = tcx.hir_name(var_id);
1258 struct_fmt.field(var_name.as_str(), place);
1259 }
1260 } else {
1261 for (index, place) in places.iter().enumerate() {
1262 struct_fmt.field(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", index))
})format!("{index}"), place);
1263 }
1264 }
1265
1266 struct_fmt.finish()
1267 }),
1268
1269 AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1270 let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{coroutine@{0:?}}}",
tcx.def_span(def_id)))
})format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1271 let mut struct_fmt = fmt.debug_struct(&name);
1272
1273 if let Some(def_id) = def_id.as_local()
1275 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1276 {
1277 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1278 let var_name = tcx.hir_name(var_id);
1279 struct_fmt.field(var_name.as_str(), place);
1280 }
1281 } else {
1282 for (index, place) in places.iter().enumerate() {
1283 struct_fmt.field(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", index))
})format!("{index}"), place);
1284 }
1285 }
1286
1287 struct_fmt.finish()
1288 }),
1289
1290 AggregateKind::RawPtr(pointee_ty, mutability) => {
1291 let kind_str = match mutability {
1292 Mutability::Mut => "mut",
1293 Mutability::Not => "const",
1294 };
1295 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!("*{0} {1} from ", kind_str, pointee_ty))
}with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1296 fmt_tuple(fmt, "")
1297 }
1298 }
1299 }
1300
1301 WrapUnsafeBinder(ref op, ty) => {
1302 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!("wrap_binder!({0:?}; {1})", op, ty))
}with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1303 }
1304 }
1305 }
1306}
1307
1308impl<'tcx> Debug for Operand<'tcx> {
1309 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1310 use self::Operand::*;
1311 match *self {
1312 Constant(ref a) => fmt.write_fmt(format_args!("{0:?}", a))write!(fmt, "{a:?}"),
1313 Copy(ref place) => fmt.write_fmt(format_args!("copy {0:?}", place))write!(fmt, "copy {place:?}"),
1314 Move(ref place) => fmt.write_fmt(format_args!("move {0:?}", place))write!(fmt, "move {place:?}"),
1315 RuntimeChecks(checks) => fmt.write_fmt(format_args!("{0:?}", checks))write!(fmt, "{checks:?}"),
1316 }
1317 }
1318}
1319
1320impl<'tcx> Debug for ConstOperand<'tcx> {
1321 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1322 fmt.write_fmt(format_args!("{0}", self))write!(fmt, "{self}")
1323 }
1324}
1325
1326impl<'tcx> Display for ConstOperand<'tcx> {
1327 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1328 match self.ty().kind() {
1329 ty::FnDef(..) => {}
1330 _ => fmt.write_fmt(format_args!("const "))write!(fmt, "const ")?,
1331 }
1332 Display::fmt(&self.const_, fmt)
1333 }
1334}
1335
1336impl Debug for Place<'_> {
1337 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1338 self.as_ref().fmt(fmt)
1339 }
1340}
1341
1342impl Debug for PlaceRef<'_> {
1343 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1344 pre_fmt_projection(self.projection, fmt)?;
1345 fmt.write_fmt(format_args!("{0:?}", self.local))write!(fmt, "{:?}", self.local)?;
1346 post_fmt_projection(self.projection, fmt)
1347 }
1348}
1349
1350fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1351 for &elem in projection.iter().rev() {
1352 match elem {
1353 ProjectionElem::OpaqueCast(_)
1354 | ProjectionElem::Downcast(_, _)
1355 | ProjectionElem::Field(_, _) => {
1356 fmt.write_fmt(format_args!("("))write!(fmt, "(")?;
1357 }
1358 ProjectionElem::Deref => {
1359 fmt.write_fmt(format_args!("(*"))write!(fmt, "(*")?;
1360 }
1361 ProjectionElem::Index(_)
1362 | ProjectionElem::ConstantIndex { .. }
1363 | ProjectionElem::Subslice { .. } => {}
1364 ProjectionElem::UnwrapUnsafeBinder(_) => {
1365 fmt.write_fmt(format_args!("unwrap_binder!("))write!(fmt, "unwrap_binder!(")?;
1366 }
1367 }
1368 }
1369
1370 Ok(())
1371}
1372
1373fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1374 for &elem in projection.iter() {
1375 match elem {
1376 ProjectionElem::OpaqueCast(ty) => {
1377 fmt.write_fmt(format_args!(" as {0})", ty))write!(fmt, " as {ty})")?;
1378 }
1379 ProjectionElem::Downcast(Some(name), _index) => {
1380 fmt.write_fmt(format_args!(" as {0})", name))write!(fmt, " as {name})")?;
1381 }
1382 ProjectionElem::Downcast(None, index) => {
1383 fmt.write_fmt(format_args!(" as variant#{0:?})", index))write!(fmt, " as variant#{index:?})")?;
1384 }
1385 ProjectionElem::Deref => {
1386 fmt.write_fmt(format_args!(")"))write!(fmt, ")")?;
1387 }
1388 ProjectionElem::Field(field, ty) => {
1389 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!(".{0:?}: {1})", field.index(), ty))?
};with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1390 }
1391 ProjectionElem::Index(ref index) => {
1392 fmt.write_fmt(format_args!("[{0:?}]", index))write!(fmt, "[{index:?}]")?;
1393 }
1394 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1395 fmt.write_fmt(format_args!("[{0:?} of {1:?}]", offset, min_length))write!(fmt, "[{offset:?} of {min_length:?}]")?;
1396 }
1397 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1398 fmt.write_fmt(format_args!("[-{0:?} of {1:?}]", offset, min_length))write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1399 }
1400 ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1401 fmt.write_fmt(format_args!("[{0:?}:]", from))write!(fmt, "[{from:?}:]")?;
1402 }
1403 ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1404 fmt.write_fmt(format_args!("[:-{0:?}]", to))write!(fmt, "[:-{to:?}]")?;
1405 }
1406 ProjectionElem::Subslice { from, to, from_end: true } => {
1407 fmt.write_fmt(format_args!("[{0:?}:-{1:?}]", from, to))write!(fmt, "[{from:?}:-{to:?}]")?;
1408 }
1409 ProjectionElem::Subslice { from, to, from_end: false } => {
1410 fmt.write_fmt(format_args!("[{0:?}..{1:?}]", from, to))write!(fmt, "[{from:?}..{to:?}]")?;
1411 }
1412 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1413 fmt.write_fmt(format_args!("; {0})", ty))write!(fmt, "; {ty})")?;
1414 }
1415 }
1416 }
1417
1418 Ok(())
1419}
1420
1421fn write_extra<'tcx>(
1425 tcx: TyCtxt<'tcx>,
1426 write: &mut dyn io::Write,
1427 visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1428 options: PrettyPrintMirOptions,
1429) -> io::Result<()> {
1430 if options.include_extra_comments {
1431 let mut extra_comments = ExtraComments { tcx, comments: ::alloc::vec::Vec::new()vec![] };
1432 visit_op(&mut extra_comments);
1433 for comment in extra_comments.comments {
1434 write.write_fmt(format_args!("{0:2$} // {1}\n", "", comment, ALIGN))writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1435 }
1436 }
1437 Ok(())
1438}
1439
1440struct ExtraComments<'tcx> {
1441 tcx: TyCtxt<'tcx>,
1442 comments: Vec<String>,
1443}
1444
1445impl<'tcx> ExtraComments<'tcx> {
1446 fn push(&mut self, lines: &str) {
1447 for line in lines.split('\n') {
1448 self.comments.push(line.to_string());
1449 }
1450 }
1451}
1452
1453fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1454 match *ty.kind() {
1455 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1456 ty::Tuple(g_args) if g_args.is_empty() => false,
1458 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1459 ty::Array(ty, _) => use_verbose(ty, fn_def),
1460 ty::FnDef(..) => fn_def,
1461 _ => true,
1462 }
1463}
1464
1465impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1466 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1467 let ConstOperand { span, user_ty, const_ } = constant;
1468 if use_verbose(const_.ty(), true) {
1469 self.push("mir::ConstOperand");
1470 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ span: {0}",
self.tcx.sess.source_map().span_to_diagnostic_string(*span)))
})format!(
1471 "+ span: {}",
1472 self.tcx.sess.source_map().span_to_diagnostic_string(*span)
1473 ));
1474 if let Some(user_ty) = user_ty {
1475 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ user_ty: {0:?}", user_ty))
})format!("+ user_ty: {user_ty:?}"));
1476 }
1477
1478 let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1479 let tcx = self.tcx;
1480 rustc_data_structures::make_display(move |fmt| {
1481 pretty_print_const_value_tcx(tcx, val, ty, fmt)
1482 })
1483 };
1484
1485 let fmt_valtree = |cv: &ty::Value<'tcx>| {
1486 let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1487 p.pretty_print_const_valtree(*cv, true).unwrap();
1488 p.into_buffer()
1489 };
1490
1491 let val = match const_ {
1492 Const::Ty(_, ct) => match ct.kind() {
1493 ty::ConstKind::Param(p) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::Param({0})", p))
})format!("ty::Param({p})"),
1494 ty::ConstKind::Alias(_, alias_const) => {
1495 let kind = match alias_const.kind {
1496 ty::AliasConstKind::Projection { def_id }
1497 | ty::AliasConstKind::Inherent { def_id }
1498 | ty::AliasConstKind::Free { def_id }
1499 | ty::AliasConstKind::Anon { def_id } => self.tcx.def_path_str(def_id),
1500 };
1501 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::AliasConst({0}, {1:?})", kind,
alias_const.args))
})format!("ty::AliasConst({}, {:?})", kind, alias_const.args)
1502 }
1503 ty::ConstKind::Value(cv) => {
1504 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::Valtree({0})",
fmt_valtree(&cv)))
})format!("ty::Valtree({})", fmt_valtree(&cv))
1505 }
1506 ty::ConstKind::Error(_) => "Error".to_string(),
1508 ty::ConstKind::Placeholder(_)
1510 | ty::ConstKind::Infer(_)
1511 | ty::ConstKind::Expr(_)
1512 | ty::ConstKind::Bound(..) => crate::util::bug::bug_fmt(format_args!("unexpected MIR constant: {0:?}",
const_))bug!("unexpected MIR constant: {:?}", const_),
1513 },
1514 Const::Unevaluated(uv, _) => {
1515 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Unevaluated({0}, {1:?}, {2:?})",
self.tcx.def_path_str(uv.def), uv.args, uv.promoted))
})format!(
1516 "Unevaluated({}, {:?}, {:?})",
1517 self.tcx.def_path_str(uv.def),
1518 uv.args,
1519 uv.promoted,
1520 )
1521 }
1522 Const::Val(val, ty) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Value({0})", fmt_val(*val, *ty)))
})format!("Value({})", fmt_val(*val, *ty)),
1523 };
1524
1525 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ const_: Const {{ ty: {0}, val: {1} }}",
const_.ty(), val))
})format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1529 }
1530 }
1531
1532 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1533 self.super_rvalue(rvalue, location);
1534 if let Rvalue::Aggregate(kind, _) = rvalue {
1535 match **kind {
1536 AggregateKind::Closure(def_id, args) => {
1537 self.push("closure");
1538 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ def_id: {0:?}", def_id))
})format!("+ def_id: {def_id:?}"));
1539 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ args: {0:#?}", args))
})format!("+ args: {args:#?}"));
1540 }
1541
1542 AggregateKind::Coroutine(def_id, args) => {
1543 self.push("coroutine");
1544 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ def_id: {0:?}", def_id))
})format!("+ def_id: {def_id:?}"));
1545 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ args: {0:#?}", args))
})format!("+ args: {args:#?}"));
1546 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ kind: {0:?}",
self.tcx.coroutine_kind(def_id)))
})format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1547 }
1548
1549 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1550 self.push("adt");
1551 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ user_ty: {0:?}", user_ty))
})format!("+ user_ty: {user_ty:?}"));
1552 }
1553
1554 _ => {}
1555 }
1556 }
1557 }
1558}
1559
1560fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1561 let location = tcx.sess.source_map().span_to_diagnostic_string(span);
1562 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scope {0} at {1}", scope.index(),
location))
})format!("scope {} at {}", scope.index(), location,)
1563}
1564
1565pub fn write_allocations<'tcx>(
1571 tcx: TyCtxt<'tcx>,
1572 body: &Body<'_>,
1573 w: &mut dyn io::Write,
1574) -> io::Result<()> {
1575 fn alloc_ids_from_alloc(
1576 alloc: ConstAllocation<'_>,
1577 ) -> impl DoubleEndedIterator<Item = AllocId> {
1578 alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1579 }
1580
1581 fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1582 match val {
1583 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1584 ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1585 ConstValue::ZeroSized => None,
1586 ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1587 Some(alloc_id)
1590 }
1591 }
1592 }
1593 struct CollectAllocIds(BTreeSet<AllocId>);
1594
1595 impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1596 fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1597 match c.const_ {
1598 Const::Ty(_, _) | Const::Unevaluated(..) => {}
1599 Const::Val(val, _) => {
1600 if let Some(id) = alloc_id_from_const_val(val) {
1601 self.0.insert(id);
1602 }
1603 }
1604 }
1605 }
1606 }
1607
1608 let mut visitor = CollectAllocIds(Default::default());
1609 visitor.visit_body(body);
1610
1611 let mut seen = visitor.0;
1615 let mut todo: Vec<_> = seen.iter().copied().collect();
1616 while let Some(id) = todo.pop() {
1617 let mut write_allocation_track_relocs =
1618 |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1619 for id in alloc_ids_from_alloc(alloc).rev() {
1621 if seen.insert(id) {
1622 todo.push(id);
1623 }
1624 }
1625 w.write_fmt(format_args!("{0}", display_allocation(tcx, alloc.inner())))write!(w, "{}", display_allocation(tcx, alloc.inner()))
1626 };
1627 w.write_fmt(format_args!("\n{0:?}", id))write!(w, "\n{id:?}")?;
1628 match tcx.try_get_global_alloc(id) {
1629 None => w.write_fmt(format_args!(" (deallocated)"))write!(w, " (deallocated)")?,
1632 Some(GlobalAlloc::Function { instance, .. }) => w.write_fmt(format_args!(" (fn: {0})", instance))write!(w, " (fn: {instance})")?,
1633 Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1634 w.write_fmt(format_args!(" (vtable: impl {0} for {1})", dyn_ty, ty))write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1635 }
1636 Some(GlobalAlloc::TypeId { ty }) => w.write_fmt(format_args!(" (typeid for {0})", ty))write!(w, " (typeid for {ty})")?,
1637 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1638 w.write_fmt(format_args!(" (static: {0}", tcx.def_path_str(did)))write!(w, " (static: {}", tcx.def_path_str(did))?;
1639 if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1640 && body
1641 .source
1642 .def_id()
1643 .as_local()
1644 .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1645 {
1646 w.write_fmt(format_args!(")"))write!(w, ")")?;
1650 } else {
1651 match tcx.eval_static_initializer(did) {
1652 Ok(alloc) => {
1653 w.write_fmt(format_args!(", "))write!(w, ", ")?;
1654 write_allocation_track_relocs(w, alloc)?;
1655 }
1656 Err(_) => w.write_fmt(format_args!(", error during initializer evaluation)"))write!(w, ", error during initializer evaluation)")?,
1657 }
1658 }
1659 }
1660 Some(GlobalAlloc::Static(did)) => {
1661 w.write_fmt(format_args!(" (extern static: {0})", tcx.def_path_str(did)))write!(w, " (extern static: {})", tcx.def_path_str(did))?
1662 }
1663 Some(GlobalAlloc::Memory(alloc)) => {
1664 w.write_fmt(format_args!(" ("))write!(w, " (")?;
1665 write_allocation_track_relocs(w, alloc)?
1666 }
1667 }
1668 w.write_fmt(format_args!("\n"))writeln!(w)?;
1669 }
1670 Ok(())
1671}
1672
1673pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1690 tcx: TyCtxt<'tcx>,
1691 alloc: &'a Allocation<Prov, Extra, Bytes>,
1692) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1693 RenderAllocation { tcx, alloc }
1694}
1695
1696#[doc(hidden)]
1697pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1698 tcx: TyCtxt<'tcx>,
1699 alloc: &'a Allocation<Prov, Extra, Bytes>,
1700}
1701
1702impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1703 for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1704{
1705 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1706 let RenderAllocation { tcx, alloc } = *self;
1707 w.write_fmt(format_args!("size: {0}, align: {1})", alloc.size().bytes(),
alloc.align.bytes()))write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1708 if alloc.size() == Size::ZERO {
1709 return w.write_fmt(format_args!(" {{}}"))write!(w, " {{}}");
1711 }
1712 if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1713 return w.write_fmt(format_args!(" {{ .. }}"))write!(w, " {{ .. }}");
1714 }
1715 w.write_fmt(format_args!(" {{\n"))writeln!(w, " {{")?;
1717 write_allocation_bytes(tcx, alloc, w, " ")?;
1718 w.write_fmt(format_args!("}}"))write!(w, "}}")?;
1719 Ok(())
1720 }
1721}
1722
1723fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1724 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1725 w.write_fmt(format_args!(" "))write!(w, " ")?;
1726 }
1727 w.write_fmt(format_args!(" │ {0}\n", ascii))writeln!(w, " │ {ascii}")
1728}
1729
1730const BYTES_PER_LINE: usize = 16;
1732
1733fn write_allocation_newline(
1735 w: &mut dyn std::fmt::Write,
1736 mut line_start: Size,
1737 ascii: &str,
1738 pos_width: usize,
1739 prefix: &str,
1740) -> Result<Size, std::fmt::Error> {
1741 write_allocation_endline(w, ascii)?;
1742 line_start += Size::from_bytes(BYTES_PER_LINE);
1743 w.write_fmt(format_args!("{0}0x{1:02$x} │ ", prefix, line_start.bytes(),
pos_width))write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1744 Ok(line_start)
1745}
1746
1747pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1751 tcx: TyCtxt<'tcx>,
1752 alloc: &Allocation<Prov, Extra, Bytes>,
1753 w: &mut dyn std::fmt::Write,
1754 prefix: &str,
1755) -> std::fmt::Result {
1756 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1757 let pos_width = hex_number_length(alloc.size().bytes());
1759
1760 if num_lines > 0 {
1761 w.write_fmt(format_args!("{0}0x{1:02$x} │ ", prefix, 0, pos_width))write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1762 } else {
1763 w.write_fmt(format_args!("{0}", prefix))write!(w, "{prefix}")?;
1764 }
1765
1766 let mut i = Size::ZERO;
1767 let mut line_start = Size::ZERO;
1768
1769 let ptr_size = tcx.data_layout.pointer_size();
1770
1771 let mut ascii = String::new();
1772
1773 let oversized_ptr = |target: &mut String, width| {
1774 if target.len() > width {
1775 target.write_fmt(format_args!(" ({0} ptr bytes)", ptr_size.bytes()))write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1776 }
1777 };
1778
1779 while i < alloc.size() {
1780 if i != line_start {
1784 w.write_fmt(format_args!(" "))write!(w, " ")?;
1785 }
1786 if let Some(prov) = alloc.provenance().get_ptr(i) {
1787 if !alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok() {
::core::panicking::panic("assertion failed: alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok()")
};assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1789 let j = i.bytes_usize();
1790 let offset = alloc
1791 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1792 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1793 let offset = Size::from_bytes(offset);
1794 let provenance_width = |bytes| bytes * 3;
1795 let ptr = Pointer::new(prov, offset);
1796 let mut target = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ptr))
})format!("{ptr:?}");
1797 if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1798 target = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:#?}", ptr))
})format!("{ptr:#?}");
1800 }
1801 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1802 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1805 let overflow = ptr_size - remainder;
1806 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1807 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1808 ascii.push('╾'); for _ in 1..remainder.bytes() {
1810 ascii.push('─'); }
1812 if overflow_width > remainder_width && overflow_width >= target.len() {
1813 w.write_fmt(format_args!("╾{0:─^1$}", "", remainder_width))write!(w, "╾{0:─^1$}", "", remainder_width)?;
1815 line_start =
1816 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1817 ascii.clear();
1818 w.write_fmt(format_args!("{0:─^1$}╼", target, overflow_width))write!(w, "{target:─^overflow_width$}╼")?;
1819 } else {
1820 oversized_ptr(&mut target, remainder_width);
1821 w.write_fmt(format_args!("╾{0:─^1$}", target, remainder_width))write!(w, "╾{target:─^remainder_width$}")?;
1822 line_start =
1823 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1824 w.write_fmt(format_args!("{0:─^1$}╼", "", overflow_width))write!(w, "{0:─^1$}╼", "", overflow_width)?;
1825 ascii.clear();
1826 }
1827 for _ in 0..overflow.bytes() - 1 {
1828 ascii.push('─');
1829 }
1830 ascii.push('╼'); i += ptr_size;
1832 continue;
1833 } else {
1834 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1836 oversized_ptr(&mut target, provenance_width);
1837 ascii.push('╾');
1838 w.write_fmt(format_args!("╾{0:─^1$}╼", target, provenance_width))write!(w, "╾{target:─^provenance_width$}╼")?;
1839 for _ in 0..ptr_size.bytes() - 2 {
1840 ascii.push('─');
1841 }
1842 ascii.push('╼');
1843 i += ptr_size;
1844 }
1845 } else if let Some(frag) = alloc.provenance().get_byte(i, &tcx) {
1846 if !alloc.init_mask().is_range_initialized(alloc_range(i,
Size::from_bytes(1))).is_ok() {
::core::panicking::panic("assertion failed: alloc.init_mask().is_range_initialized(alloc_range(i,\n Size::from_bytes(1))).is_ok()")
};assert!(
1848 alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1849 );
1850 ascii.push('━'); let j = i.bytes_usize();
1854 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1855 w.write_fmt(format_args!("╾{2:02x}{0:#?} (ptr fragment {1})╼", frag.prov,
frag.idx, c))write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼", prov = frag.prov, idx = frag.idx)?;
1857 i += Size::from_bytes(1);
1858 } else if alloc
1859 .init_mask()
1860 .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1861 .is_ok()
1862 {
1863 let j = i.bytes_usize();
1864
1865 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1868 w.write_fmt(format_args!("{0:02x}", c))write!(w, "{c:02x}")?;
1869 if c.is_ascii_control() || c >= 0x80 {
1870 ascii.push('.');
1871 } else {
1872 ascii.push(char::from(c));
1873 }
1874 i += Size::from_bytes(1);
1875 } else {
1876 w.write_fmt(format_args!("__"))write!(w, "__")?;
1877 ascii.push('░');
1878 i += Size::from_bytes(1);
1879 }
1880 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1882 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1883 ascii.clear();
1884 }
1885 }
1886 write_allocation_endline(w, &ascii)?;
1887
1888 Ok(())
1889}
1890
1891fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1895 fmt.write_fmt(format_args!("b\"{0}\"", byte_str.escape_ascii()))write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1896}
1897
1898fn comma_sep<'tcx>(
1899 tcx: TyCtxt<'tcx>,
1900 fmt: &mut Formatter<'_>,
1901 elems: Vec<(ConstValue, Ty<'tcx>)>,
1902) -> fmt::Result {
1903 let mut first = true;
1904 for (ct, ty) in elems {
1905 if !first {
1906 fmt.write_str(", ")?;
1907 }
1908 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1909 first = false;
1910 }
1911 Ok(())
1912}
1913
1914fn pretty_print_const_value_tcx<'tcx>(
1915 tcx: TyCtxt<'tcx>,
1916 ct: ConstValue,
1917 ty: Ty<'tcx>,
1918 fmt: &mut Formatter<'_>,
1919) -> fmt::Result {
1920 use crate::ty::print::PrettyPrinter;
1921
1922 if tcx.sess.verbose_internals() {
1923 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ConstValue({0:?}: {1})", ct, ty))
})format!("ConstValue({ct:?}: {ty})"))?;
1924 return Ok(());
1925 }
1926
1927 if ct.all_bytes_uninit(tcx) {
1930 fmt.write_str("<uninit>")?;
1931 return Ok(());
1932 }
1933
1934 let u8_type = tcx.types.u8;
1935 match (ct, ty.kind()) {
1936 (_, ty::Ref(_, inner_ty, _)) if let ty::Str = inner_ty.kind() => {
1938 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1939 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}",
String::from_utf8_lossy(data)))
})format!("{:?}", String::from_utf8_lossy(data)))?;
1940 return Ok(());
1941 }
1942 }
1943 (_, ty::Ref(_, inner_ty, _))
1944 if let ty::Slice(t) = inner_ty.kind()
1945 && *t == u8_type =>
1946 {
1947 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1948 pretty_print_byte_str(fmt, data)?;
1949 return Ok(());
1950 }
1951 }
1952 (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1953 let n = n.try_to_target_usize(tcx).unwrap();
1954 let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1955 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1957 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1958 fmt.write_str("*")?;
1959 pretty_print_byte_str(fmt, byte_str)?;
1960 return Ok(());
1961 }
1962 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1971 if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1972 let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1973 match *ty.kind() {
1974 ty::Array(..) => {
1975 fmt.write_str("[")?;
1976 comma_sep(tcx, fmt, fields)?;
1977 fmt.write_str("]")?;
1978 }
1979 ty::Tuple(..) => {
1980 fmt.write_str("(")?;
1981 comma_sep(tcx, fmt, fields)?;
1982 if contents.fields.len() == 1 {
1983 fmt.write_str(",")?;
1984 }
1985 fmt.write_str(")")?;
1986 }
1987 ty::Adt(def, _) if def.variants().is_empty() => {
1988 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{unreachable(): {0}}}", ty))
})format!("{{unreachable(): {ty}}}"))?;
1989 }
1990 ty::Adt(def, args) => {
1991 let variant_idx = contents
1992 .variant
1993 .expect("destructed mir constant of adt without variant idx");
1994 let variant_def = &def.variant(variant_idx);
1995 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1996 p.print_alloc_ids = true;
1997 p.pretty_print_value_path(variant_def.def_id, args)?;
1998 fmt.write_str(&p.into_buffer())?;
1999
2000 match variant_def.ctor_kind() {
2001 Some(CtorKind::Const) => {}
2002 Some(CtorKind::Fn) => {
2003 fmt.write_str("(")?;
2004 comma_sep(tcx, fmt, fields)?;
2005 fmt.write_str(")")?;
2006 }
2007 None => {
2008 fmt.write_str(" {{ ")?;
2009 let mut first = true;
2010 for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
2011 {
2012 if !first {
2013 fmt.write_str(", ")?;
2014 }
2015 fmt.write_fmt(format_args!("{0}: ", field_def.name))write!(fmt, "{}: ", field_def.name)?;
2016 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
2017 first = false;
2018 }
2019 fmt.write_str(" }}")?;
2020 }
2021 }
2022 }
2023 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2024 }
2025 return Ok(());
2026 }
2027 }
2028 (ConstValue::Scalar(scalar), _) => {
2029 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2030 p.print_alloc_ids = true;
2031 p.pretty_print_const_scalar(scalar, ty)?;
2032 fmt.write_str(&p.into_buffer())?;
2033 return Ok(());
2034 }
2035 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
2036 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2037 p.print_alloc_ids = true;
2038 p.pretty_print_value_path(*d, s.no_bound_vars().unwrap())?;
2039 fmt.write_str(&p.into_buffer())?;
2040 return Ok(());
2041 }
2042 _ => {}
2045 }
2046 fmt.write_fmt(format_args!("{0:?}: {1}", ct, ty))write!(fmt, "{ct:?}: {ty}")
2048}
2049
2050pub(crate) fn pretty_print_const_value<'tcx>(
2051 ct: ConstValue,
2052 ty: Ty<'tcx>,
2053 fmt: &mut Formatter<'_>,
2054) -> fmt::Result {
2055 ty::tls::with(|tcx| {
2056 let ty = tcx.lift(ty);
2057 pretty_print_const_value_tcx(tcx, ct, ty, fmt)
2058 })
2059}
2060
2061fn hex_number_length(x: u64) -> usize {
2072 if x == 0 {
2073 return 1;
2074 }
2075 let mut length = 0;
2076 let mut x_left = x;
2077 while x_left > 0 {
2078 x_left /= 16;
2079 length += 1;
2080 }
2081 length
2082}