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