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