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::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::AsyncDropGlueCtorShim(_, 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::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::FutureDropPollShim(_, 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, name) in layout.field_names.iter_enumerated() {
433 let source_info = layout.field_tys[field].source_info;
434 if let Some(name) = 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 {
563 field_tys,
564 field_names: _, variant_fields,
566 variant_source_info,
567 storage_conflicts,
568 } = layout;
569
570 w.write_fmt(format_args!("{0}coroutine layout {{\n", INDENT))writeln!(w, "{INDENT}coroutine layout {{")?;
571
572 for (field, CoroutineSavedTy { ty, source_info, ignore_for_traits }) in
573 field_tys.iter_enumerated()
574 {
575 let ignore_for_traits = if *ignore_for_traits { " (ignored for traits)" } else { "" };
576 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};",);
577 if options.include_extra_comments {
578 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))?;
579 } else {
580 w.write_fmt(format_args!("{0}\n", indented_body))writeln!(w, "{}", indented_body)?;
581 }
582 }
583
584 w.write_fmt(format_args!("{0}{0}variant_fields = {{\n", INDENT))writeln!(w, "{INDENT}{INDENT}variant_fields = {{")?;
585 for (variant, fields) in variant_fields.iter_enumerated() {
586 let variant_name = ty::CoroutineArgs::variant_name(variant);
587 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:?},");
588 if options.include_extra_comments {
589 let source_info = variant_source_info[variant];
590 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))?;
591 } else {
592 w.write_fmt(format_args!("{0}\n", header))writeln!(w, "{}", header)?;
593 }
594 }
595 w.write_fmt(format_args!("{0}{0}}}\n", INDENT))writeln!(w, "{INDENT}{INDENT}}}")?;
596 w.write_fmt(format_args!("{0}{0}storage_conflicts = {1:?}\n", INDENT,
storage_conflicts))writeln!(w, "{INDENT}{INDENT}storage_conflicts = {storage_conflicts:?}")?;
597 w.write_fmt(format_args!("{0}}}\n", INDENT))writeln!(w, "{INDENT}}}")
598}
599
600fn write_mir_intro<'tcx>(
603 tcx: TyCtxt<'tcx>,
604 body: &Body<'_>,
605 w: &mut dyn io::Write,
606 options: PrettyPrintMirOptions,
607) -> io::Result<()> {
608 write_mir_sig(tcx, body, w)?;
609 w.write_fmt(format_args!("{{\n"))writeln!(w, "{{")?;
610
611 if let Some(ref layout) = body.coroutine_layout_raw() {
612 write_coroutine_layout(tcx, layout, w, options)?;
613 }
614
615 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
617 for (index, scope_data) in body.source_scopes.iter_enumerated() {
618 if let Some(parent) = scope_data.parent_scope {
619 scope_tree.entry(parent).or_default().push(index);
620 } else {
621 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);
623 }
624 }
625
626 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
627
628 w.write_fmt(format_args!("\n"))writeln!(w)?;
630
631 if let Some(coverage_info_hi) = &body.coverage_info_hi {
632 write_coverage_info_hi(coverage_info_hi, w)?;
633 }
634 if let Some(function_coverage_info) = &body.function_coverage_info {
635 write_function_coverage_info(function_coverage_info, w)?;
636 }
637
638 Ok(())
639}
640
641fn write_coverage_info_hi(
642 coverage_info_hi: &coverage::CoverageInfoHi,
643 w: &mut dyn io::Write,
644) -> io::Result<()> {
645 let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
646
647 let mut did_print = false;
649
650 for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
651 w.write_fmt(format_args!("{0}coverage branch {{ true: {1:?}, false: {2:?} }} => {3:?}\n",
INDENT, true_marker, false_marker, span))writeln!(
652 w,
653 "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
654 )?;
655 did_print = true;
656 }
657
658 if did_print {
659 w.write_fmt(format_args!("\n"))writeln!(w)?;
660 }
661
662 Ok(())
663}
664
665fn write_function_coverage_info(
666 function_coverage_info: &coverage::FunctionCoverageInfo,
667 w: &mut dyn io::Write,
668) -> io::Result<()> {
669 let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
670
671 for coverage::Mapping { kind, span } in mappings {
672 w.write_fmt(format_args!("{0}coverage {1:?} => {2:?};\n", INDENT, kind, span))writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
673 }
674 w.write_fmt(format_args!("\n"))writeln!(w)?;
675
676 Ok(())
677}
678
679fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
680 use rustc_hir::def::DefKind;
681
682 {
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:682",
"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(682u32),
::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);
683 let def_id = body.source.def_id();
684 let kind = tcx.def_kind(def_id);
685 let is_function = match kind {
686 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
687 true
688 }
689 _ => tcx.is_closure_like(def_id),
690 };
691 match (kind, body.source.promoted) {
692 (_, Some(_)) => w.write_fmt(format_args!("const "))write!(w, "const ")?, (DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => w.write_fmt(format_args!("const "))write!(w, "const ")?,
694 (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
695 w.write_fmt(format_args!("static "))write!(w, "static ")?
696 }
697 (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
698 w.write_fmt(format_args!("static mut "))write!(w, "static mut ")?
699 }
700 (_, _) if is_function => w.write_fmt(format_args!("fn "))write!(w, "fn ")?,
701 (DefKind::AnonConst | DefKind::InlineConst, _) => {}
703 (DefKind::GlobalAsm, _) => {}
705 _ => crate::util::bug::bug_fmt(format_args!("Unexpected def kind {0:?}", kind))bug!("Unexpected def kind {:?}", kind),
706 }
707
708 {
let _guard = ForcedImplGuard::new();
w.write_fmt(format_args!("{0}", tcx.def_path_str(def_id)))?
}ty::print::with_forced_impl_filename_line! {
709 write!(w, "{}", tcx.def_path_str(def_id))?
711 }
712 if let Some(p) = body.source.promoted {
713 w.write_fmt(format_args!("::{0:?}", p))write!(w, "::{p:?}")?;
714 }
715
716 if body.source.promoted.is_none() && is_function {
717 w.write_fmt(format_args!("("))write!(w, "(")?;
718
719 for (i, arg) in body.args_iter().enumerate() {
721 if i != 0 {
722 w.write_fmt(format_args!(", "))write!(w, ", ")?;
723 }
724 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)?;
725 }
726
727 w.write_fmt(format_args!(") -> {0}", body.return_ty()))write!(w, ") -> {}", body.return_ty())?;
728 } else {
729 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);
730 w.write_fmt(format_args!(": {0} =", body.return_ty()))write!(w, ": {} =", body.return_ty())?;
731 }
732
733 if let Some(yield_ty) = body.yield_ty() {
734 w.write_fmt(format_args!("\n"))writeln!(w)?;
735 w.write_fmt(format_args!("yields {0}\n", yield_ty))writeln!(w, "yields {yield_ty}")?;
736 }
737
738 w.write_fmt(format_args!(" "))write!(w, " ")?;
739 Ok(())
742}
743
744fn write_user_type_annotations(
745 tcx: TyCtxt<'_>,
746 body: &Body<'_>,
747 w: &mut dyn io::Write,
748) -> io::Result<()> {
749 if !body.user_type_annotations.is_empty() {
750 w.write_fmt(format_args!("| User Type Annotations\n"))writeln!(w, "| User Type Annotations")?;
751 }
752 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
753 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!(
754 w,
755 "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
756 index.index(),
757 annotation.user_ty,
758 tcx.sess.source_map().span_to_diagnostic_string(annotation.span),
759 with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
760 )?;
761 }
762 if !body.user_type_annotations.is_empty() {
763 w.write_fmt(format_args!("|\n"))writeln!(w, "|")?;
764 }
765 Ok(())
766}
767
768impl<'a, 'tcx> MirWriter<'a, 'tcx> {
772 fn write_basic_block(
774 &self,
775 block: BasicBlock,
776 body: &Body<'tcx>,
777 w: &mut dyn io::Write,
778 ) -> io::Result<()> {
779 let data = &body[block];
780
781 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
783 w.write_fmt(format_args!("{0}{1:?}{2}: {{\n", INDENT, block, cleanup_text))writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
784
785 let mut current_location = Location { block, statement_index: 0 };
787 for statement in &data.statements {
788 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
789
790 for debuginfo in statement.debuginfos.iter() {
791 w.write_fmt(format_args!("{0}{0}// DBG: {1:?};\n", INDENT, debuginfo))writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
792 }
793
794 let indented_body = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{0}{1:?};", INDENT, statement))
})format!("{INDENT}{INDENT}{statement:?};");
795 if self.options.include_extra_comments {
796 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!(
797 w,
798 "{:A$} // {}{}",
799 indented_body,
800 if self.tcx.sess.verbose_internals() {
801 format!("{current_location:?}: ")
802 } else {
803 String::new()
804 },
805 comment(self.tcx, statement.source_info),
806 A = ALIGN,
807 )?;
808 } else {
809 w.write_fmt(format_args!("{0}\n", indented_body))writeln!(w, "{indented_body}")?;
810 }
811
812 write_extra(
813 self.tcx,
814 w,
815 &|visitor| visitor.visit_statement(statement, current_location),
816 self.options,
817 )?;
818
819 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
820
821 current_location.statement_index += 1;
822 }
823
824 for debuginfo in data.after_last_stmt_debuginfos.iter() {
825 w.write_fmt(format_args!("{0}{0}// DBG: {1:?};\n", INDENT, debuginfo))writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
826 }
827
828 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
830 if data.terminator.is_some() {
831 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);
832 if self.options.include_extra_comments {
833 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!(
834 w,
835 "{:A$} // {}{}",
836 indented_terminator,
837 if self.tcx.sess.verbose_internals() {
838 format!("{current_location:?}: ")
839 } else {
840 String::new()
841 },
842 comment(self.tcx, data.terminator().source_info),
843 A = ALIGN,
844 )?;
845 } else {
846 w.write_fmt(format_args!("{0}\n", indented_terminator))writeln!(w, "{indented_terminator}")?;
847 }
848
849 write_extra(
850 self.tcx,
851 w,
852 &|visitor| visitor.visit_terminator(data.terminator(), current_location),
853 self.options,
854 )?;
855 }
856
857 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
858 (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
859
860 w.write_fmt(format_args!("{0}}}\n", INDENT))writeln!(w, "{INDENT}}}")
861 }
862}
863
864impl Debug for StatementKind<'_> {
865 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
866 use self::StatementKind::*;
867 match *self {
868 Assign((ref place, ref rv)) => fmt.write_fmt(format_args!("{0:?} = {1:?}", place, rv))write!(fmt, "{place:?} = {rv:?}"),
869 FakeRead((ref cause, ref place)) => {
870 fmt.write_fmt(format_args!("FakeRead({0:?}, {1:?})", cause, place))write!(fmt, "FakeRead({cause:?}, {place:?})")
871 }
872 StorageLive(ref place) => fmt.write_fmt(format_args!("StorageLive({0:?})", place))write!(fmt, "StorageLive({place:?})"),
873 StorageDead(ref place) => fmt.write_fmt(format_args!("StorageDead({0:?})", place))write!(fmt, "StorageDead({place:?})"),
874 SetDiscriminant { ref place, variant_index } => {
875 fmt.write_fmt(format_args!("discriminant({0:?}) = {1:?}", place,
variant_index))write!(fmt, "discriminant({place:?}) = {variant_index:?}")
876 }
877 PlaceMention(ref place) => {
878 fmt.write_fmt(format_args!("PlaceMention({0:?})", place))write!(fmt, "PlaceMention({place:?})")
879 }
880 AscribeUserType((ref place, ref c_ty), ref variance) => {
881 fmt.write_fmt(format_args!("AscribeUserType({0:?}, {1:?}, {2:?})", place,
variance, c_ty))write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
882 }
883 Coverage(ref kind) => fmt.write_fmt(format_args!("Coverage::{0:?}", kind))write!(fmt, "Coverage::{kind:?}"),
884 Intrinsic(ref intrinsic) => fmt.write_fmt(format_args!("{0}", intrinsic))write!(fmt, "{intrinsic}"),
885 ConstEvalCounter => fmt.write_fmt(format_args!("ConstEvalCounter"))write!(fmt, "ConstEvalCounter"),
886 Nop => fmt.write_fmt(format_args!("nop"))write!(fmt, "nop"),
887 BackwardIncompatibleDropHint { ref place, reason: _ } => {
888 fmt.write_fmt(format_args!("BackwardIncompatibleDropHint({0:?})", place))write!(fmt, "BackwardIncompatibleDropHint({place:?})")
891 }
892 }
893 }
894}
895impl Debug for Statement<'_> {
896 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
897 self.kind.fmt(fmt)
898 }
899}
900
901impl Debug for StmtDebugInfo<'_> {
902 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
903 match self {
904 StmtDebugInfo::AssignRef(local, place) => {
905 fmt.write_fmt(format_args!("{0:?} = &{1:?}", local, place))write!(fmt, "{local:?} = &{place:?}")
906 }
907 StmtDebugInfo::InvalidAssign(local) => {
908 fmt.write_fmt(format_args!("{0:?} = &?", local))write!(fmt, "{local:?} = &?")
909 }
910 }
911 }
912}
913
914impl Display for NonDivergingIntrinsic<'_> {
915 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
916 match self {
917 Self::Assume(op) => f.write_fmt(format_args!("assume({0:?})", op))write!(f, "assume({op:?})"),
918 Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
919 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:?})")
920 }
921 }
922 }
923}
924
925impl<'tcx> Debug for TerminatorKind<'tcx> {
926 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
927 self.fmt_head(fmt)?;
928 let successor_count = self.successors().count();
929 let labels = self.fmt_successor_labels();
930 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());
931
932 let show_unwind = !#[allow(non_exhaustive_omitted_patterns)] match self.unwind() {
None | Some(UnwindAction::Cleanup(_)) => true,
_ => false,
}matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
934 let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
935 fmt.write_fmt(format_args!("unwind "))write!(fmt, "unwind ")?;
936 match self.unwind() {
937 None | Some(UnwindAction::Cleanup(_)) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
939 Some(UnwindAction::Continue) => fmt.write_fmt(format_args!("continue"))write!(fmt, "continue"),
940 Some(UnwindAction::Unreachable) => fmt.write_fmt(format_args!("unreachable"))write!(fmt, "unreachable"),
941 Some(UnwindAction::Terminate(reason)) => {
942 fmt.write_fmt(format_args!("terminate({0})", reason.as_short_str()))write!(fmt, "terminate({})", reason.as_short_str())
943 }
944 }
945 };
946
947 match (successor_count, show_unwind) {
948 (0, false) => Ok(()),
949 (0, true) => {
950 fmt.write_fmt(format_args!(" -> "))write!(fmt, " -> ")?;
951 fmt_unwind(fmt)
952 }
953 (1, false) => fmt.write_fmt(format_args!(" -> {0:?}", self.successors().next().unwrap()))write!(fmt, " -> {:?}", self.successors().next().unwrap()),
954 _ => {
955 fmt.write_fmt(format_args!(" -> ["))write!(fmt, " -> [")?;
956 for (i, target) in self.successors().enumerate() {
957 if i > 0 {
958 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
959 }
960 fmt.write_fmt(format_args!("{0}: {1:?}", labels[i], target))write!(fmt, "{}: {:?}", labels[i], target)?;
961 }
962 if show_unwind {
963 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
964 fmt_unwind(fmt)?;
965 }
966 fmt.write_fmt(format_args!("]"))write!(fmt, "]")
967 }
968 }
969 }
970}
971impl Debug for Terminator<'_> {
972 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
973 self.kind.fmt(fmt)
974 }
975}
976
977impl<'tcx> TerminatorKind<'tcx> {
978 pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
982 use self::TerminatorKind::*;
983 match self {
984 Goto { .. } => fmt.write_fmt(format_args!("goto"))write!(fmt, "goto"),
985 SwitchInt { discr, .. } => fmt.write_fmt(format_args!("switchInt({0:?})", discr))write!(fmt, "switchInt({discr:?})"),
986 Return => fmt.write_fmt(format_args!("return"))write!(fmt, "return"),
987 CoroutineDrop => fmt.write_fmt(format_args!("coroutine_drop"))write!(fmt, "coroutine_drop"),
988 UnwindResume => fmt.write_fmt(format_args!("resume"))write!(fmt, "resume"),
989 UnwindTerminate(reason) => {
990 fmt.write_fmt(format_args!("terminate({0})", reason.as_short_str()))write!(fmt, "terminate({})", reason.as_short_str())
991 }
992 Yield { value, resume_arg, .. } => fmt.write_fmt(format_args!("{0:?} = yield({1:?})", resume_arg, value))write!(fmt, "{resume_arg:?} = yield({value:?})"),
993 Unreachable => fmt.write_fmt(format_args!("unreachable"))write!(fmt, "unreachable"),
994 Drop { place, async_fut: None, .. } => fmt.write_fmt(format_args!("drop({0:?})", place))write!(fmt, "drop({place:?})"),
995 Drop { place, async_fut: Some(async_fut), .. } => {
996 fmt.write_fmt(format_args!("async drop({0:?}; poll={1:?})", place, async_fut))write!(fmt, "async drop({place:?}; poll={async_fut:?})")
997 }
998 Call { func, args, destination, .. } => {
999 fmt.write_fmt(format_args!("{0:?} = ", destination))write!(fmt, "{destination:?} = ")?;
1000 fmt.write_fmt(format_args!("{0:?}(", func))write!(fmt, "{func:?}(")?;
1001 for (index, arg) in args.iter().enumerate() {
1002 if index > 0 {
1003 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
1004 }
1005 fmt.write_fmt(format_args!("{0:?}", arg.node))write!(fmt, "{:?}", arg.node)?;
1006 }
1007 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1008 }
1009 TailCall { func, args, .. } => {
1010 fmt.write_fmt(format_args!("tailcall {0:?}(", func))write!(fmt, "tailcall {func:?}(")?;
1011 for (index, arg) in args.iter().enumerate() {
1012 if index > 0 {
1013 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
1014 }
1015 fmt.write_fmt(format_args!("{0:?}", arg.node))write!(fmt, "{:?}", arg.node)?;
1016 }
1017 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1018 }
1019 Assert { cond, expected, msg, .. } => {
1020 fmt.write_fmt(format_args!("assert("))write!(fmt, "assert(")?;
1021 if !expected {
1022 fmt.write_fmt(format_args!("!"))write!(fmt, "!")?;
1023 }
1024 fmt.write_fmt(format_args!("{0:?}, ", cond))write!(fmt, "{cond:?}, ")?;
1025 msg.fmt_assert_args(fmt)?;
1026 fmt.write_fmt(format_args!(")"))write!(fmt, ")")
1027 }
1028 FalseEdge { .. } => fmt.write_fmt(format_args!("falseEdge"))write!(fmt, "falseEdge"),
1029 FalseUnwind { .. } => fmt.write_fmt(format_args!("falseUnwind"))write!(fmt, "falseUnwind"),
1030 InlineAsm { template, operands, options, .. } => {
1031 fmt.write_fmt(format_args!("asm!(\"{0}\"",
InlineAsmTemplatePiece::to_string(template)))write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
1032 for op in operands {
1033 fmt.write_fmt(format_args!(", "))write!(fmt, ", ")?;
1034 let print_late = |&late| if late { "late" } else { "" };
1035 match op {
1036 InlineAsmOperand::In { reg, value } => {
1037 fmt.write_fmt(format_args!("in({0}) {1:?}", reg, value))write!(fmt, "in({reg}) {value:?}")?;
1038 }
1039 InlineAsmOperand::Out { reg, late, place: Some(place) } => {
1040 fmt.write_fmt(format_args!("{0}out({1}) {2:?}", print_late(late), reg, place))write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
1041 }
1042 InlineAsmOperand::Out { reg, late, place: None } => {
1043 fmt.write_fmt(format_args!("{0}out({1}) _", print_late(late), reg))write!(fmt, "{}out({}) _", print_late(late), reg)?;
1044 }
1045 InlineAsmOperand::InOut {
1046 reg,
1047 late,
1048 in_value,
1049 out_place: Some(out_place),
1050 } => {
1051 fmt.write_fmt(format_args!("in{0}out({1}) {2:?} => {3:?}", print_late(late),
reg, in_value, out_place))write!(
1052 fmt,
1053 "in{}out({}) {:?} => {:?}",
1054 print_late(late),
1055 reg,
1056 in_value,
1057 out_place
1058 )?;
1059 }
1060 InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
1061 fmt.write_fmt(format_args!("in{0}out({1}) {2:?} => _", print_late(late), reg,
in_value))write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
1062 }
1063 InlineAsmOperand::Const { value } => {
1064 fmt.write_fmt(format_args!("const {0:?}", value))write!(fmt, "const {value:?}")?;
1065 }
1066 InlineAsmOperand::SymFn { value } => {
1067 fmt.write_fmt(format_args!("sym_fn {0:?}", value))write!(fmt, "sym_fn {value:?}")?;
1068 }
1069 InlineAsmOperand::SymStatic { def_id } => {
1070 fmt.write_fmt(format_args!("sym_static {0:?}", def_id))write!(fmt, "sym_static {def_id:?}")?;
1071 }
1072 InlineAsmOperand::Label { target_index } => {
1073 fmt.write_fmt(format_args!("label {0}", target_index))write!(fmt, "label {target_index}")?;
1074 }
1075 }
1076 }
1077 fmt.write_fmt(format_args!(", options({0:?}))", options))write!(fmt, ", options({options:?}))")
1078 }
1079 }
1080 }
1081
1082 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1084 use self::TerminatorKind::*;
1085 match *self {
1086 Return
1087 | TailCall { .. }
1088 | UnwindResume
1089 | UnwindTerminate(_)
1090 | Unreachable
1091 | CoroutineDrop => ::alloc::vec::Vec::new()vec![],
1092 Goto { .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["".into()]))vec!["".into()],
1093 SwitchInt { ref targets, .. } => targets
1094 .values
1095 .iter()
1096 .map(|&u| Cow::Owned(u.to_string()))
1097 .chain(iter::once("otherwise".into()))
1098 .collect(),
1099 Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1100 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into()]))vec!["return".into(), "unwind".into()]
1101 }
1102 Call { target: Some(_), unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into()]))vec!["return".into()],
1103 Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["unwind".into()]))vec!["unwind".into()],
1104 Call { target: None, unwind: _, .. } => ::alloc::vec::Vec::new()vec![],
1105 Yield { drop: Some(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["resume".into(), "drop".into()]))vec!["resume".into(), "drop".into()],
1106 Yield { drop: None, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["resume".into()]))vec!["resume".into()],
1107 Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1108 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into(), "drop".into()]))vec!["return".into(), "unwind".into(), "drop".into()]
1109 }
1110 Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1111 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "unwind".into()]))vec!["return".into(), "unwind".into()]
1112 }
1113 Drop { unwind: _, drop: Some(_), .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into(), "drop".into()]))vec!["return".into(), "drop".into()],
1114 Drop { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["return".into()]))vec!["return".into()],
1115 Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1116 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["success".into(), "unwind".into()]))vec!["success".into(), "unwind".into()]
1117 }
1118 Assert { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["success".into()]))vec!["success".into()],
1119 FalseEdge { .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into(), "imaginary".into()]))vec!["real".into(), "imaginary".into()],
1120 FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1121 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into(), "unwind".into()]))vec!["real".into(), "unwind".into()]
1122 }
1123 FalseUnwind { unwind: _, .. } => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["real".into()]))vec!["real".into()],
1124 InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1125 let mut vec = Vec::with_capacity(targets.len() + 1);
1126 if !asm_macro.diverges(options) {
1127 vec.push("return".into());
1128 }
1129 vec.resize(targets.len(), "label".into());
1130
1131 if let UnwindAction::Cleanup(_) = unwind {
1132 vec.push("unwind".into());
1133 }
1134
1135 vec
1136 }
1137 }
1138 }
1139}
1140
1141impl<'tcx> Debug for Rvalue<'tcx> {
1142 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1143 use self::Rvalue::*;
1144
1145 match *self {
1146 Use(ref operand, with_retag) => {
1147 fmt.write_fmt(format_args!("{0}{1:?}",
if with_retag.no() { "no_retag " } else { "" }, operand))write!(fmt, "{}{operand:?}", if with_retag.no() { "no_retag " } else { "" })
1149 }
1150 Repeat(ref a, b) => {
1151 fmt.write_fmt(format_args!("[{0:?}; ", a))write!(fmt, "[{a:?}; ")?;
1152 pretty_print_const(b, fmt, false)?;
1153 fmt.write_fmt(format_args!("]"))write!(fmt, "]")
1154 }
1155 Cast(ref kind, ref place, ref ty) => {
1156 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!("{0:?} as {1} ({2:?})", place, ty, kind))
}with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1157 }
1158 BinaryOp(ref op, (ref a, ref b)) => fmt.write_fmt(format_args!("{0:?}({1:?}, {2:?})", op, a, b))write!(fmt, "{op:?}({a:?}, {b:?})"),
1159 UnaryOp(ref op, ref a) => fmt.write_fmt(format_args!("{0:?}({1:?})", op, a))write!(fmt, "{op:?}({a:?})"),
1160 Discriminant(ref place) => fmt.write_fmt(format_args!("discriminant({0:?})", place))write!(fmt, "discriminant({place:?})"),
1161 ThreadLocalRef(did) => ty::tls::with(|tcx| {
1162 let muta = tcx.static_mutability(did).unwrap().prefix_str();
1163 fmt.write_fmt(format_args!("&/*tls*/ {0}{1}", muta, tcx.def_path_str(did)))write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1164 }),
1165 Ref(region, borrow_kind, ref place) => {
1166 let kind_str = match borrow_kind {
1167 BorrowKind::Shared => "",
1168 BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1169 BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1170 BorrowKind::Mut { .. } => "mut ",
1171 };
1172
1173 let print_region = ty::tls::with(|tcx| {
1175 tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1176 });
1177 let region = if print_region {
1178 let mut region = region.to_string();
1179 if !region.is_empty() {
1180 region.push(' ');
1181 }
1182 region
1183 } else {
1184 String::new()
1186 };
1187 fmt.write_fmt(format_args!("&{0}{1}{2:?}", region, kind_str, place))write!(fmt, "&{region}{kind_str}{place:?}")
1188 }
1189
1190 Reborrow(target, mutability, ref place) => {
1191 fmt.write_fmt(format_args!("{1:?}({0} {2:?})",
if mutability.is_mut() { "reborrow" } else { "coerce shared" },
target, place))write!(
1192 fmt,
1193 "{target:?}({} {place:?})",
1194 if mutability.is_mut() { "reborrow" } else { "coerce shared" }
1195 )
1196 }
1197
1198 CopyForDeref(ref place) => fmt.write_fmt(format_args!("deref_copy {0:#?}", place))write!(fmt, "deref_copy {place:#?}"),
1199
1200 RawPtr(mutability, ref place) => {
1201 fmt.write_fmt(format_args!("&raw {0} {1:?}", mutability.ptr_str(), place))write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1202 }
1203
1204 Aggregate(ref kind, ref places) => {
1205 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1206 let mut tuple_fmt = fmt.debug_tuple(name);
1207 for place in places {
1208 tuple_fmt.field(place);
1209 }
1210 tuple_fmt.finish()
1211 };
1212
1213 match **kind {
1214 AggregateKind::Array(_) => fmt.write_fmt(format_args!("{0:?}", places))write!(fmt, "{places:?}"),
1215
1216 AggregateKind::Tuple => {
1217 if places.is_empty() {
1218 fmt.write_fmt(format_args!("()"))write!(fmt, "()")
1219 } else {
1220 fmt_tuple(fmt, "")
1221 }
1222 }
1223
1224 AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1225 ty::tls::with(|tcx| {
1226 let variant_def = &tcx.adt_def(adt_did).variant(variant);
1227 let args = tcx.lift(args);
1228 let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1229 p.print_def_path(variant_def.def_id, args)
1230 })?;
1231
1232 match variant_def.ctor_kind() {
1233 Some(CtorKind::Const) => fmt.write_str(&name),
1234 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1235 None => {
1236 let mut struct_fmt = fmt.debug_struct(&name);
1237 for (field, place) in iter::zip(&variant_def.fields, places) {
1238 struct_fmt.field(field.name.as_str(), place);
1239 }
1240 struct_fmt.finish()
1241 }
1242 }
1243 })
1244 }
1245
1246 AggregateKind::Closure(def_id, args)
1247 | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1248 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1249 let args = tcx.lift(args);
1250 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{closure@{0}}}",
tcx.def_path_str_with_args(def_id, args)))
})format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1251 } else {
1252 let span = tcx.def_span(def_id);
1253 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{closure@{0}}}",
tcx.sess.source_map().span_to_diagnostic_string(span)))
})format!(
1254 "{{closure@{}}}",
1255 tcx.sess.source_map().span_to_diagnostic_string(span)
1256 )
1257 };
1258 let mut struct_fmt = fmt.debug_struct(&name);
1259
1260 if let Some(def_id) = def_id.as_local()
1262 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1263 {
1264 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1265 let var_name = tcx.hir_name(var_id);
1266 struct_fmt.field(var_name.as_str(), place);
1267 }
1268 } else {
1269 for (index, place) in places.iter().enumerate() {
1270 struct_fmt.field(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", index))
})format!("{index}"), place);
1271 }
1272 }
1273
1274 struct_fmt.finish()
1275 }),
1276
1277 AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1278 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));
1279 let mut struct_fmt = fmt.debug_struct(&name);
1280
1281 if let Some(def_id) = def_id.as_local()
1283 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1284 {
1285 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1286 let var_name = tcx.hir_name(var_id);
1287 struct_fmt.field(var_name.as_str(), place);
1288 }
1289 } else {
1290 for (index, place) in places.iter().enumerate() {
1291 struct_fmt.field(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", index))
})format!("{index}"), place);
1292 }
1293 }
1294
1295 struct_fmt.finish()
1296 }),
1297
1298 AggregateKind::RawPtr(pointee_ty, mutability) => {
1299 let kind_str = match mutability {
1300 Mutability::Mut => "mut",
1301 Mutability::Not => "const",
1302 };
1303 {
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 "))?;
1304 fmt_tuple(fmt, "")
1305 }
1306 }
1307 }
1308
1309 WrapUnsafeBinder(ref op, ty) => {
1310 {
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})"))
1311 }
1312 }
1313 }
1314}
1315
1316impl<'tcx> Debug for Operand<'tcx> {
1317 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1318 use self::Operand::*;
1319 match *self {
1320 Constant(ref a) => fmt.write_fmt(format_args!("{0:?}", a))write!(fmt, "{a:?}"),
1321 Copy(ref place) => fmt.write_fmt(format_args!("copy {0:?}", place))write!(fmt, "copy {place:?}"),
1322 Move(ref place) => fmt.write_fmt(format_args!("move {0:?}", place))write!(fmt, "move {place:?}"),
1323 RuntimeChecks(checks) => fmt.write_fmt(format_args!("{0:?}", checks))write!(fmt, "{checks:?}"),
1324 }
1325 }
1326}
1327
1328impl<'tcx> Debug for ConstOperand<'tcx> {
1329 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1330 fmt.write_fmt(format_args!("{0}", self))write!(fmt, "{self}")
1331 }
1332}
1333
1334impl<'tcx> Display for ConstOperand<'tcx> {
1335 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1336 match self.ty().kind() {
1337 ty::FnDef(..) => {}
1338 _ => fmt.write_fmt(format_args!("const "))write!(fmt, "const ")?,
1339 }
1340 Display::fmt(&self.const_, fmt)
1341 }
1342}
1343
1344impl Debug for Place<'_> {
1345 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1346 self.as_ref().fmt(fmt)
1347 }
1348}
1349
1350impl Debug for PlaceRef<'_> {
1351 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1352 pre_fmt_projection(self.projection, fmt)?;
1353 fmt.write_fmt(format_args!("{0:?}", self.local))write!(fmt, "{:?}", self.local)?;
1354 post_fmt_projection(self.projection, fmt)
1355 }
1356}
1357
1358fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1359 for &elem in projection.iter().rev() {
1360 match elem {
1361 ProjectionElem::OpaqueCast(_)
1362 | ProjectionElem::Downcast(_, _)
1363 | ProjectionElem::Field(_, _) => {
1364 fmt.write_fmt(format_args!("("))write!(fmt, "(")?;
1365 }
1366 ProjectionElem::Deref => {
1367 fmt.write_fmt(format_args!("(*"))write!(fmt, "(*")?;
1368 }
1369 ProjectionElem::Index(_)
1370 | ProjectionElem::ConstantIndex { .. }
1371 | ProjectionElem::Subslice { .. } => {}
1372 ProjectionElem::UnwrapUnsafeBinder(_) => {
1373 fmt.write_fmt(format_args!("unwrap_binder!("))write!(fmt, "unwrap_binder!(")?;
1374 }
1375 }
1376 }
1377
1378 Ok(())
1379}
1380
1381fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1382 for &elem in projection.iter() {
1383 match elem {
1384 ProjectionElem::OpaqueCast(ty) => {
1385 fmt.write_fmt(format_args!(" as {0})", ty))write!(fmt, " as {ty})")?;
1386 }
1387 ProjectionElem::Downcast(Some(name), _index) => {
1388 fmt.write_fmt(format_args!(" as {0})", name))write!(fmt, " as {name})")?;
1389 }
1390 ProjectionElem::Downcast(None, index) => {
1391 fmt.write_fmt(format_args!(" as variant#{0:?})", index))write!(fmt, " as variant#{index:?})")?;
1392 }
1393 ProjectionElem::Deref => {
1394 fmt.write_fmt(format_args!(")"))write!(fmt, ")")?;
1395 }
1396 ProjectionElem::Field(field, ty) => {
1397 {
let _guard = NoTrimmedGuard::new();
fmt.write_fmt(format_args!(".{0:?}: {1})", field.index(), ty))?
};with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1398 }
1399 ProjectionElem::Index(ref index) => {
1400 fmt.write_fmt(format_args!("[{0:?}]", index))write!(fmt, "[{index:?}]")?;
1401 }
1402 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1403 fmt.write_fmt(format_args!("[{0:?} of {1:?}]", offset, min_length))write!(fmt, "[{offset:?} of {min_length:?}]")?;
1404 }
1405 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1406 fmt.write_fmt(format_args!("[-{0:?} of {1:?}]", offset, min_length))write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1407 }
1408 ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1409 fmt.write_fmt(format_args!("[{0:?}:]", from))write!(fmt, "[{from:?}:]")?;
1410 }
1411 ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1412 fmt.write_fmt(format_args!("[:-{0:?}]", to))write!(fmt, "[:-{to:?}]")?;
1413 }
1414 ProjectionElem::Subslice { from, to, from_end: true } => {
1415 fmt.write_fmt(format_args!("[{0:?}:-{1:?}]", from, to))write!(fmt, "[{from:?}:-{to:?}]")?;
1416 }
1417 ProjectionElem::Subslice { from, to, from_end: false } => {
1418 fmt.write_fmt(format_args!("[{0:?}..{1:?}]", from, to))write!(fmt, "[{from:?}..{to:?}]")?;
1419 }
1420 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1421 fmt.write_fmt(format_args!("; {0})", ty))write!(fmt, "; {ty})")?;
1422 }
1423 }
1424 }
1425
1426 Ok(())
1427}
1428
1429fn write_extra<'tcx>(
1433 tcx: TyCtxt<'tcx>,
1434 write: &mut dyn io::Write,
1435 visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1436 options: PrettyPrintMirOptions,
1437) -> io::Result<()> {
1438 if options.include_extra_comments {
1439 let mut extra_comments = ExtraComments { tcx, comments: ::alloc::vec::Vec::new()vec![] };
1440 visit_op(&mut extra_comments);
1441 for comment in extra_comments.comments {
1442 write.write_fmt(format_args!("{0:2$} // {1}\n", "", comment, ALIGN))writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1443 }
1444 }
1445 Ok(())
1446}
1447
1448struct ExtraComments<'tcx> {
1449 tcx: TyCtxt<'tcx>,
1450 comments: Vec<String>,
1451}
1452
1453impl<'tcx> ExtraComments<'tcx> {
1454 fn push(&mut self, lines: &str) {
1455 for line in lines.split('\n') {
1456 self.comments.push(line.to_string());
1457 }
1458 }
1459}
1460
1461fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1462 match *ty.kind() {
1463 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1464 ty::Tuple(g_args) if g_args.is_empty() => false,
1466 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1467 ty::Array(ty, _) => use_verbose(ty, fn_def),
1468 ty::FnDef(..) => fn_def,
1469 _ => true,
1470 }
1471}
1472
1473impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1474 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1475 let ConstOperand { span, user_ty, const_ } = constant;
1476 if use_verbose(const_.ty(), true) {
1477 self.push("mir::ConstOperand");
1478 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ span: {0}",
self.tcx.sess.source_map().span_to_diagnostic_string(*span)))
})format!(
1479 "+ span: {}",
1480 self.tcx.sess.source_map().span_to_diagnostic_string(*span)
1481 ));
1482 if let Some(user_ty) = user_ty {
1483 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ user_ty: {0:?}", user_ty))
})format!("+ user_ty: {user_ty:?}"));
1484 }
1485
1486 let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1487 let tcx = self.tcx;
1488 rustc_data_structures::make_display(move |fmt| {
1489 pretty_print_const_value_tcx(tcx, val, ty, fmt)
1490 })
1491 };
1492
1493 let fmt_valtree = |cv: &ty::Value<'tcx>| {
1494 let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1495 p.pretty_print_const_valtree(*cv, true).unwrap();
1496 p.into_buffer()
1497 };
1498
1499 let val = match const_ {
1500 Const::Ty(_, ct) => match ct.kind() {
1501 ty::ConstKind::Param(p) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::Param({0})", p))
})format!("ty::Param({p})"),
1502 ty::ConstKind::Unevaluated(uv) => {
1503 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::Unevaluated({0}, {1:?})",
self.tcx.def_path_str(uv.def), uv.args))
})format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1504 }
1505 ty::ConstKind::Value(cv) => {
1506 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ty::Valtree({0})",
fmt_valtree(&cv)))
})format!("ty::Valtree({})", fmt_valtree(&cv))
1507 }
1508 ty::ConstKind::Error(_) => "Error".to_string(),
1510 ty::ConstKind::Placeholder(_)
1512 | ty::ConstKind::Infer(_)
1513 | ty::ConstKind::Expr(_)
1514 | ty::ConstKind::Bound(..) => crate::util::bug::bug_fmt(format_args!("unexpected MIR constant: {0:?}",
const_))bug!("unexpected MIR constant: {:?}", const_),
1515 },
1516 Const::Unevaluated(uv, _) => {
1517 ::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!(
1518 "Unevaluated({}, {:?}, {:?})",
1519 self.tcx.def_path_str(uv.def),
1520 uv.args,
1521 uv.promoted,
1522 )
1523 }
1524 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)),
1525 };
1526
1527 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));
1531 }
1532 }
1533
1534 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1535 self.super_rvalue(rvalue, location);
1536 if let Rvalue::Aggregate(kind, _) = rvalue {
1537 match **kind {
1538 AggregateKind::Closure(def_id, args) => {
1539 self.push("closure");
1540 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ def_id: {0:?}", def_id))
})format!("+ def_id: {def_id:?}"));
1541 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ args: {0:#?}", args))
})format!("+ args: {args:#?}"));
1542 }
1543
1544 AggregateKind::Coroutine(def_id, args) => {
1545 self.push("coroutine");
1546 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ def_id: {0:?}", def_id))
})format!("+ def_id: {def_id:?}"));
1547 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ args: {0:#?}", args))
})format!("+ args: {args:#?}"));
1548 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)));
1549 }
1550
1551 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1552 self.push("adt");
1553 self.push(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("+ user_ty: {0:?}", user_ty))
})format!("+ user_ty: {user_ty:?}"));
1554 }
1555
1556 _ => {}
1557 }
1558 }
1559 }
1560}
1561
1562fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1563 let location = tcx.sess.source_map().span_to_diagnostic_string(span);
1564 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scope {0} at {1}", scope.index(),
location))
})format!("scope {} at {}", scope.index(), location,)
1565}
1566
1567pub fn write_allocations<'tcx>(
1573 tcx: TyCtxt<'tcx>,
1574 body: &Body<'_>,
1575 w: &mut dyn io::Write,
1576) -> io::Result<()> {
1577 fn alloc_ids_from_alloc(
1578 alloc: ConstAllocation<'_>,
1579 ) -> impl DoubleEndedIterator<Item = AllocId> {
1580 alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1581 }
1582
1583 fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1584 match val {
1585 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1586 ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1587 ConstValue::ZeroSized => None,
1588 ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1589 Some(alloc_id)
1592 }
1593 }
1594 }
1595 struct CollectAllocIds(BTreeSet<AllocId>);
1596
1597 impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1598 fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1599 match c.const_ {
1600 Const::Ty(_, _) | Const::Unevaluated(..) => {}
1601 Const::Val(val, _) => {
1602 if let Some(id) = alloc_id_from_const_val(val) {
1603 self.0.insert(id);
1604 }
1605 }
1606 }
1607 }
1608 }
1609
1610 let mut visitor = CollectAllocIds(Default::default());
1611 visitor.visit_body(body);
1612
1613 let mut seen = visitor.0;
1617 let mut todo: Vec<_> = seen.iter().copied().collect();
1618 while let Some(id) = todo.pop() {
1619 let mut write_allocation_track_relocs =
1620 |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1621 for id in alloc_ids_from_alloc(alloc).rev() {
1623 if seen.insert(id) {
1624 todo.push(id);
1625 }
1626 }
1627 w.write_fmt(format_args!("{0}", display_allocation(tcx, alloc.inner())))write!(w, "{}", display_allocation(tcx, alloc.inner()))
1628 };
1629 w.write_fmt(format_args!("\n{0:?}", id))write!(w, "\n{id:?}")?;
1630 match tcx.try_get_global_alloc(id) {
1631 None => w.write_fmt(format_args!(" (deallocated)"))write!(w, " (deallocated)")?,
1634 Some(GlobalAlloc::Function { instance, .. }) => w.write_fmt(format_args!(" (fn: {0})", instance))write!(w, " (fn: {instance})")?,
1635 Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1636 w.write_fmt(format_args!(" (vtable: impl {0} for {1})", dyn_ty, ty))write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1637 }
1638 Some(GlobalAlloc::TypeId { ty }) => w.write_fmt(format_args!(" (typeid for {0})", ty))write!(w, " (typeid for {ty})")?,
1639 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1640 w.write_fmt(format_args!(" (static: {0}", tcx.def_path_str(did)))write!(w, " (static: {}", tcx.def_path_str(did))?;
1641 if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1642 && body
1643 .source
1644 .def_id()
1645 .as_local()
1646 .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1647 {
1648 w.write_fmt(format_args!(")"))write!(w, ")")?;
1652 } else {
1653 match tcx.eval_static_initializer(did) {
1654 Ok(alloc) => {
1655 w.write_fmt(format_args!(", "))write!(w, ", ")?;
1656 write_allocation_track_relocs(w, alloc)?;
1657 }
1658 Err(_) => w.write_fmt(format_args!(", error during initializer evaluation)"))write!(w, ", error during initializer evaluation)")?,
1659 }
1660 }
1661 }
1662 Some(GlobalAlloc::Static(did)) => {
1663 w.write_fmt(format_args!(" (extern static: {0})", tcx.def_path_str(did)))write!(w, " (extern static: {})", tcx.def_path_str(did))?
1664 }
1665 Some(GlobalAlloc::Memory(alloc)) => {
1666 w.write_fmt(format_args!(" ("))write!(w, " (")?;
1667 write_allocation_track_relocs(w, alloc)?
1668 }
1669 }
1670 w.write_fmt(format_args!("\n"))writeln!(w)?;
1671 }
1672 Ok(())
1673}
1674
1675pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1692 tcx: TyCtxt<'tcx>,
1693 alloc: &'a Allocation<Prov, Extra, Bytes>,
1694) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1695 RenderAllocation { tcx, alloc }
1696}
1697
1698#[doc(hidden)]
1699pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1700 tcx: TyCtxt<'tcx>,
1701 alloc: &'a Allocation<Prov, Extra, Bytes>,
1702}
1703
1704impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1705 for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1706{
1707 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1708 let RenderAllocation { tcx, alloc } = *self;
1709 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())?;
1710 if alloc.size() == Size::ZERO {
1711 return w.write_fmt(format_args!(" {{}}"))write!(w, " {{}}");
1713 }
1714 if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1715 return w.write_fmt(format_args!(" {{ .. }}"))write!(w, " {{ .. }}");
1716 }
1717 w.write_fmt(format_args!(" {{\n"))writeln!(w, " {{")?;
1719 write_allocation_bytes(tcx, alloc, w, " ")?;
1720 w.write_fmt(format_args!("}}"))write!(w, "}}")?;
1721 Ok(())
1722 }
1723}
1724
1725fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1726 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1727 w.write_fmt(format_args!(" "))write!(w, " ")?;
1728 }
1729 w.write_fmt(format_args!(" │ {0}\n", ascii))writeln!(w, " │ {ascii}")
1730}
1731
1732const BYTES_PER_LINE: usize = 16;
1734
1735fn write_allocation_newline(
1737 w: &mut dyn std::fmt::Write,
1738 mut line_start: Size,
1739 ascii: &str,
1740 pos_width: usize,
1741 prefix: &str,
1742) -> Result<Size, std::fmt::Error> {
1743 write_allocation_endline(w, ascii)?;
1744 line_start += Size::from_bytes(BYTES_PER_LINE);
1745 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)?;
1746 Ok(line_start)
1747}
1748
1749pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1753 tcx: TyCtxt<'tcx>,
1754 alloc: &Allocation<Prov, Extra, Bytes>,
1755 w: &mut dyn std::fmt::Write,
1756 prefix: &str,
1757) -> std::fmt::Result {
1758 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1759 let pos_width = hex_number_length(alloc.size().bytes());
1761
1762 if num_lines > 0 {
1763 w.write_fmt(format_args!("{0}0x{1:02$x} │ ", prefix, 0, pos_width))write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1764 } else {
1765 w.write_fmt(format_args!("{0}", prefix))write!(w, "{prefix}")?;
1766 }
1767
1768 let mut i = Size::ZERO;
1769 let mut line_start = Size::ZERO;
1770
1771 let ptr_size = tcx.data_layout.pointer_size();
1772
1773 let mut ascii = String::new();
1774
1775 let oversized_ptr = |target: &mut String, width| {
1776 if target.len() > width {
1777 target.write_fmt(format_args!(" ({0} ptr bytes)", ptr_size.bytes()))write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1778 }
1779 };
1780
1781 while i < alloc.size() {
1782 if i != line_start {
1786 w.write_fmt(format_args!(" "))write!(w, " ")?;
1787 }
1788 if let Some(prov) = alloc.provenance().get_ptr(i) {
1789 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());
1791 let j = i.bytes_usize();
1792 let offset = alloc
1793 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1794 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1795 let offset = Size::from_bytes(offset);
1796 let provenance_width = |bytes| bytes * 3;
1797 let ptr = Pointer::new(prov, offset);
1798 let mut target = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ptr))
})format!("{ptr:?}");
1799 if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1800 target = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:#?}", ptr))
})format!("{ptr:#?}");
1802 }
1803 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1804 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1807 let overflow = ptr_size - remainder;
1808 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1809 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1810 ascii.push('╾'); for _ in 1..remainder.bytes() {
1812 ascii.push('─'); }
1814 if overflow_width > remainder_width && overflow_width >= target.len() {
1815 w.write_fmt(format_args!("╾{0:─^1$}", "", remainder_width))write!(w, "╾{0:─^1$}", "", remainder_width)?;
1817 line_start =
1818 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1819 ascii.clear();
1820 w.write_fmt(format_args!("{0:─^1$}╼", target, overflow_width))write!(w, "{target:─^overflow_width$}╼")?;
1821 } else {
1822 oversized_ptr(&mut target, remainder_width);
1823 w.write_fmt(format_args!("╾{0:─^1$}", target, remainder_width))write!(w, "╾{target:─^remainder_width$}")?;
1824 line_start =
1825 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1826 w.write_fmt(format_args!("{0:─^1$}╼", "", overflow_width))write!(w, "{0:─^1$}╼", "", overflow_width)?;
1827 ascii.clear();
1828 }
1829 for _ in 0..overflow.bytes() - 1 {
1830 ascii.push('─');
1831 }
1832 ascii.push('╼'); i += ptr_size;
1834 continue;
1835 } else {
1836 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1838 oversized_ptr(&mut target, provenance_width);
1839 ascii.push('╾');
1840 w.write_fmt(format_args!("╾{0:─^1$}╼", target, provenance_width))write!(w, "╾{target:─^provenance_width$}╼")?;
1841 for _ in 0..ptr_size.bytes() - 2 {
1842 ascii.push('─');
1843 }
1844 ascii.push('╼');
1845 i += ptr_size;
1846 }
1847 } else if let Some(frag) = alloc.provenance().get_byte(i, &tcx) {
1848 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!(
1850 alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1851 );
1852 ascii.push('━'); let j = i.bytes_usize();
1856 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1857 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)?;
1859 i += Size::from_bytes(1);
1860 } else if alloc
1861 .init_mask()
1862 .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1863 .is_ok()
1864 {
1865 let j = i.bytes_usize();
1866
1867 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1870 w.write_fmt(format_args!("{0:02x}", c))write!(w, "{c:02x}")?;
1871 if c.is_ascii_control() || c >= 0x80 {
1872 ascii.push('.');
1873 } else {
1874 ascii.push(char::from(c));
1875 }
1876 i += Size::from_bytes(1);
1877 } else {
1878 w.write_fmt(format_args!("__"))write!(w, "__")?;
1879 ascii.push('░');
1880 i += Size::from_bytes(1);
1881 }
1882 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1884 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1885 ascii.clear();
1886 }
1887 }
1888 write_allocation_endline(w, &ascii)?;
1889
1890 Ok(())
1891}
1892
1893fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1897 fmt.write_fmt(format_args!("b\"{0}\"", byte_str.escape_ascii()))write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1898}
1899
1900fn comma_sep<'tcx>(
1901 tcx: TyCtxt<'tcx>,
1902 fmt: &mut Formatter<'_>,
1903 elems: Vec<(ConstValue, Ty<'tcx>)>,
1904) -> fmt::Result {
1905 let mut first = true;
1906 for (ct, ty) in elems {
1907 if !first {
1908 fmt.write_str(", ")?;
1909 }
1910 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1911 first = false;
1912 }
1913 Ok(())
1914}
1915
1916fn pretty_print_const_value_tcx<'tcx>(
1917 tcx: TyCtxt<'tcx>,
1918 ct: ConstValue,
1919 ty: Ty<'tcx>,
1920 fmt: &mut Formatter<'_>,
1921) -> fmt::Result {
1922 use crate::ty::print::PrettyPrinter;
1923
1924 if tcx.sess.verbose_internals() {
1925 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("ConstValue({0:?}: {1})", ct, ty))
})format!("ConstValue({ct:?}: {ty})"))?;
1926 return Ok(());
1927 }
1928
1929 if ct.all_bytes_uninit(tcx) {
1932 fmt.write_str("<uninit>")?;
1933 return Ok(());
1934 }
1935
1936 let u8_type = tcx.types.u8;
1937 match (ct, ty.kind()) {
1938 (_, ty::Ref(_, inner_ty, _)) if let ty::Str = inner_ty.kind() => {
1940 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1941 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}",
String::from_utf8_lossy(data)))
})format!("{:?}", String::from_utf8_lossy(data)))?;
1942 return Ok(());
1943 }
1944 }
1945 (_, ty::Ref(_, inner_ty, _))
1946 if let ty::Slice(t) = inner_ty.kind()
1947 && *t == u8_type =>
1948 {
1949 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1950 pretty_print_byte_str(fmt, data)?;
1951 return Ok(());
1952 }
1953 }
1954 (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1955 let n = n.try_to_target_usize(tcx).unwrap();
1956 let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1957 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1959 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1960 fmt.write_str("*")?;
1961 pretty_print_byte_str(fmt, byte_str)?;
1962 return Ok(());
1963 }
1964 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1973 if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1974 let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1975 match *ty.kind() {
1976 ty::Array(..) => {
1977 fmt.write_str("[")?;
1978 comma_sep(tcx, fmt, fields)?;
1979 fmt.write_str("]")?;
1980 }
1981 ty::Tuple(..) => {
1982 fmt.write_str("(")?;
1983 comma_sep(tcx, fmt, fields)?;
1984 if contents.fields.len() == 1 {
1985 fmt.write_str(",")?;
1986 }
1987 fmt.write_str(")")?;
1988 }
1989 ty::Adt(def, _) if def.variants().is_empty() => {
1990 fmt.write_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{unreachable(): {0}}}", ty))
})format!("{{unreachable(): {ty}}}"))?;
1991 }
1992 ty::Adt(def, args) => {
1993 let variant_idx = contents
1994 .variant
1995 .expect("destructed mir constant of adt without variant idx");
1996 let variant_def = &def.variant(variant_idx);
1997 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1998 p.print_alloc_ids = true;
1999 p.pretty_print_value_path(variant_def.def_id, args)?;
2000 fmt.write_str(&p.into_buffer())?;
2001
2002 match variant_def.ctor_kind() {
2003 Some(CtorKind::Const) => {}
2004 Some(CtorKind::Fn) => {
2005 fmt.write_str("(")?;
2006 comma_sep(tcx, fmt, fields)?;
2007 fmt.write_str(")")?;
2008 }
2009 None => {
2010 fmt.write_str(" {{ ")?;
2011 let mut first = true;
2012 for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
2013 {
2014 if !first {
2015 fmt.write_str(", ")?;
2016 }
2017 fmt.write_fmt(format_args!("{0}: ", field_def.name))write!(fmt, "{}: ", field_def.name)?;
2018 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
2019 first = false;
2020 }
2021 fmt.write_str(" }}")?;
2022 }
2023 }
2024 }
2025 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2026 }
2027 return Ok(());
2028 }
2029 }
2030 (ConstValue::Scalar(scalar), _) => {
2031 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2032 p.print_alloc_ids = true;
2033 p.pretty_print_const_scalar(scalar, ty)?;
2034 fmt.write_str(&p.into_buffer())?;
2035 return Ok(());
2036 }
2037 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
2038 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
2039 p.print_alloc_ids = true;
2040 p.pretty_print_value_path(*d, s)?;
2041 fmt.write_str(&p.into_buffer())?;
2042 return Ok(());
2043 }
2044 _ => {}
2047 }
2048 fmt.write_fmt(format_args!("{0:?}: {1}", ct, ty))write!(fmt, "{ct:?}: {ty}")
2050}
2051
2052pub(crate) fn pretty_print_const_value<'tcx>(
2053 ct: ConstValue,
2054 ty: Ty<'tcx>,
2055 fmt: &mut Formatter<'_>,
2056) -> fmt::Result {
2057 ty::tls::with(|tcx| {
2058 let ty = tcx.lift(ty);
2059 pretty_print_const_value_tcx(tcx, ct, ty, fmt)
2060 })
2061}
2062
2063fn hex_number_length(x: u64) -> usize {
2074 if x == 0 {
2075 return 1;
2076 }
2077 let mut length = 0;
2078 let mut x_left = x;
2079 while x_left > 0 {
2080 x_left /= 16;
2081 length += 1;
2082 }
2083 length
2084}