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