]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/pretty.rs
Rollup merge of #65763 - ObsidianMinor:diag/65642, r=varkor
[rust.git] / src / librustc_mir / util / pretty.rs
1 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
2 use rustc::mir::*;
3 use rustc::mir::visit::Visitor;
4 use rustc::ty::{self, TyCtxt};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_index::vec::Idx;
7 use std::fmt::Display;
8 use std::fmt::Write as _;
9 use std::fs;
10 use std::io::{self, Write};
11 use std::path::{Path, PathBuf};
12 use super::graphviz::write_mir_fn_graphviz;
13 use crate::transform::MirSource;
14
15 const INDENT: &str = "    ";
16 /// Alignment for lining up comments following MIR statements
17 pub(crate) const ALIGN: usize = 40;
18
19 /// An indication of where we are in the control flow graph. Used for printing
20 /// extra information in `dump_mir`
21 pub enum PassWhere {
22     /// We have not started dumping the control flow graph, but we are about to.
23     BeforeCFG,
24
25     /// We just finished dumping the control flow graph. This is right before EOF
26     AfterCFG,
27
28     /// We are about to start dumping the given basic block.
29     BeforeBlock(BasicBlock),
30
31     /// We are just about to dump the given statement or terminator.
32     BeforeLocation(Location),
33
34     /// We just dumped the given statement or terminator.
35     AfterLocation(Location),
36
37     /// We just dumped the terminator for a block but not the closing `}`.
38     AfterTerminator(BasicBlock),
39 }
40
41 /// If the session is properly configured, dumps a human-readable
42 /// representation of the mir into:
43 ///
44 /// ```text
45 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
46 /// ```
47 ///
48 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
49 /// where `<filter>` takes the following forms:
50 ///
51 /// - `all` -- dump MIR for all fns, all passes, all everything
52 /// - a filter defined by a set of substrings combined with `&` and `|`
53 ///   (`&` has higher precedence). At least one of the `|`-separated groups
54 ///   must match; an `|`-separated group matches if all of its `&`-separated
55 ///   substrings are matched.
56 ///
57 /// Example:
58 ///
59 /// - `nll` == match if `nll` appears in the name
60 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
61 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
62 ///   or `typeck` appears in the name.
63 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
64 ///   or `typeck` and `bar` both appear in the name.
65 pub fn dump_mir<'tcx, F>(
66     tcx: TyCtxt<'tcx>,
67     pass_num: Option<&dyn Display>,
68     pass_name: &str,
69     disambiguator: &dyn Display,
70     source: MirSource<'tcx>,
71     body: &Body<'tcx>,
72     extra_data: F,
73 ) where
74     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
75 {
76     if !dump_enabled(tcx, pass_name, source) {
77         return;
78     }
79
80     let node_path = ty::print::with_forced_impl_filename_line(|| {
81         // see notes on #41697 below
82         tcx.def_path_str(source.def_id())
83     });
84     dump_matched_mir_node(
85         tcx,
86         pass_num,
87         pass_name,
88         &node_path,
89         disambiguator,
90         source,
91         body,
92         extra_data,
93     );
94 }
95
96 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, source: MirSource<'tcx>) -> bool {
97     let filters = match tcx.sess.opts.debugging_opts.dump_mir {
98         None => return false,
99         Some(ref filters) => filters,
100     };
101     let node_path = ty::print::with_forced_impl_filename_line(|| {
102         // see notes on #41697 below
103         tcx.def_path_str(source.def_id())
104     });
105     filters.split('|').any(|or_filter| {
106         or_filter.split('&').all(|and_filter| {
107             and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
108         })
109     })
110 }
111
112 // #41697 -- we use `with_forced_impl_filename_line()` because
113 // `def_path_str()` would otherwise trigger `type_of`, and this can
114 // run while we are already attempting to evaluate `type_of`.
115
116 fn dump_matched_mir_node<'tcx, F>(
117     tcx: TyCtxt<'tcx>,
118     pass_num: Option<&dyn Display>,
119     pass_name: &str,
120     node_path: &str,
121     disambiguator: &dyn Display,
122     source: MirSource<'tcx>,
123     body: &Body<'tcx>,
124     mut extra_data: F,
125 ) where
126     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
127 {
128     let _: io::Result<()> = try {
129         let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
130         writeln!(file, "// MIR for `{}`", node_path)?;
131         writeln!(file, "// source = {:?}", source)?;
132         writeln!(file, "// pass_name = {}", pass_name)?;
133         writeln!(file, "// disambiguator = {}", disambiguator)?;
134         if let Some(ref layout) = body.generator_layout {
135             writeln!(file, "// generator_layout = {:?}", layout)?;
136         }
137         writeln!(file, "")?;
138         extra_data(PassWhere::BeforeCFG, &mut file)?;
139         write_user_type_annotations(body, &mut file)?;
140         write_mir_fn(tcx, source, body, &mut extra_data, &mut file)?;
141         extra_data(PassWhere::AfterCFG, &mut file)?;
142     };
143
144     if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
145         let _: io::Result<()> = try {
146             let mut file =
147                 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
148             write_mir_fn_graphviz(tcx, source.def_id(), body, &mut file)?;
149         };
150     }
151 }
152
153 /// Returns the path to the filename where we should dump a given MIR.
154 /// Also used by other bits of code (e.g., NLL inference) that dump
155 /// graphviz data or other things.
156 fn dump_path(
157     tcx: TyCtxt<'_>,
158     extension: &str,
159     pass_num: Option<&dyn Display>,
160     pass_name: &str,
161     disambiguator: &dyn Display,
162     source: MirSource<'tcx>,
163 ) -> PathBuf {
164     let promotion_id = match source.promoted {
165         Some(id) => format!("-{:?}", id),
166         None => String::new(),
167     };
168
169     let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
170         String::new()
171     } else {
172         match pass_num {
173             None => ".-------".to_string(),
174             Some(pass_num) => format!(".{}", pass_num),
175         }
176     };
177
178     let mut file_path = PathBuf::new();
179     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
180
181     let item_name = tcx
182         .def_path(source.def_id())
183         .to_filename_friendly_no_crate();
184     // All drop shims have the same DefId, so we have to add the type
185     // to get unique file names.
186     let shim_disambiguator = match source.instance {
187         ty::InstanceDef::DropGlue(_, Some(ty)) => {
188             // Unfortunately, pretty-printed typed are not very filename-friendly.
189             // We dome some filtering.
190             let mut s = ".".to_owned();
191             s.extend(ty.to_string()
192                 .chars()
193                 .filter_map(|c| match c {
194                     ' ' => None,
195                     ':' | '<' | '>' => Some('_'),
196                     c => Some(c)
197                 }));
198             s
199         }
200         _ => String::new(),
201     };
202
203     let file_name = format!(
204         "rustc.{}{}{}{}.{}.{}.{}",
205         item_name,
206         shim_disambiguator,
207         promotion_id,
208         pass_num,
209         pass_name,
210         disambiguator,
211         extension,
212     );
213
214     file_path.push(&file_name);
215
216     file_path
217 }
218
219 /// Attempts to open a file where we should dump a given MIR or other
220 /// bit of MIR-related data. Used by `mir-dump`, but also by other
221 /// bits of code (e.g., NLL inference) that dump graphviz data or
222 /// other things, and hence takes the extension as an argument.
223 pub(crate) fn create_dump_file(
224     tcx: TyCtxt<'_>,
225     extension: &str,
226     pass_num: Option<&dyn Display>,
227     pass_name: &str,
228     disambiguator: &dyn Display,
229     source: MirSource<'tcx>,
230 ) -> io::Result<io::BufWriter<fs::File>> {
231     let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
232     if let Some(parent) = file_path.parent() {
233         fs::create_dir_all(parent)?;
234     }
235     Ok(io::BufWriter::new(fs::File::create(&file_path)?))
236 }
237
238 /// Write out a human-readable textual representation for the given MIR.
239 pub fn write_mir_pretty<'tcx>(
240     tcx: TyCtxt<'tcx>,
241     single: Option<DefId>,
242     w: &mut dyn Write,
243 ) -> io::Result<()> {
244     writeln!(
245         w,
246         "// WARNING: This output format is intended for human consumers only"
247     )?;
248     writeln!(
249         w,
250         "// and is subject to change without notice. Knock yourself out."
251     )?;
252
253     let mut first = true;
254     for def_id in dump_mir_def_ids(tcx, single) {
255         let body = &tcx.optimized_mir(def_id);
256
257         if first {
258             first = false;
259         } else {
260             // Put empty lines between all items
261             writeln!(w, "")?;
262         }
263
264         write_mir_fn(tcx, MirSource::item(def_id), body, &mut |_, _| Ok(()), w)?;
265
266         for (i, body) in tcx.promoted_mir(def_id).iter_enumerated() {
267             writeln!(w, "")?;
268             let src = MirSource {
269                 instance: ty::InstanceDef::Item(def_id),
270                 promoted: Some(i),
271             };
272             write_mir_fn(tcx, src, body, &mut |_, _| Ok(()), w)?;
273         }
274     }
275     Ok(())
276 }
277
278 pub fn write_mir_fn<'tcx, F>(
279     tcx: TyCtxt<'tcx>,
280     src: MirSource<'tcx>,
281     body: &Body<'tcx>,
282     extra_data: &mut F,
283     w: &mut dyn Write,
284 ) -> io::Result<()>
285 where
286     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
287 {
288     write_mir_intro(tcx, src, body, w)?;
289     for block in body.basic_blocks().indices() {
290         extra_data(PassWhere::BeforeBlock(block), w)?;
291         write_basic_block(tcx, block, body, extra_data, w)?;
292         if block.index() + 1 != body.basic_blocks().len() {
293             writeln!(w, "")?;
294         }
295     }
296
297     writeln!(w, "}}")?;
298     Ok(())
299 }
300
301 /// Write out a human-readable textual representation for the given basic block.
302 pub fn write_basic_block<'tcx, F>(
303     tcx: TyCtxt<'tcx>,
304     block: BasicBlock,
305     body: &Body<'tcx>,
306     extra_data: &mut F,
307     w: &mut dyn Write,
308 ) -> io::Result<()>
309 where
310     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
311 {
312     let data = &body[block];
313
314     // Basic block label at the top.
315     let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
316     writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
317
318     // List of statements in the middle.
319     let mut current_location = Location {
320         block: block,
321         statement_index: 0,
322     };
323     for statement in &data.statements {
324         extra_data(PassWhere::BeforeLocation(current_location), w)?;
325         let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
326         writeln!(
327             w,
328             "{:A$} // {:?}: {}",
329             indented_body,
330             current_location,
331             comment(tcx, statement.source_info),
332             A = ALIGN,
333         )?;
334
335         write_extra(tcx, w, |visitor| {
336             visitor.visit_statement(statement, current_location);
337         })?;
338
339         extra_data(PassWhere::AfterLocation(current_location), w)?;
340
341         current_location.statement_index += 1;
342     }
343
344     // Terminator at the bottom.
345     extra_data(PassWhere::BeforeLocation(current_location), w)?;
346     let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
347     writeln!(
348         w,
349         "{:A$} // {:?}: {}",
350         indented_terminator,
351         current_location,
352         comment(tcx, data.terminator().source_info),
353         A = ALIGN,
354     )?;
355
356     write_extra(tcx, w, |visitor| {
357         visitor.visit_terminator(data.terminator(), current_location);
358     })?;
359
360     extra_data(PassWhere::AfterLocation(current_location), w)?;
361     extra_data(PassWhere::AfterTerminator(block), w)?;
362
363     writeln!(w, "{}}}", INDENT)
364 }
365
366 /// After we print the main statement, we sometimes dump extra
367 /// information. There's often a lot of little things "nuzzled up" in
368 /// a statement.
369 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
370 where
371     F: FnMut(&mut ExtraComments<'tcx>),
372 {
373     let mut extra_comments = ExtraComments {
374         _tcx: tcx,
375         comments: vec![],
376     };
377     visit_op(&mut extra_comments);
378     for comment in extra_comments.comments {
379         writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
380     }
381     Ok(())
382 }
383
384 struct ExtraComments<'tcx> {
385     _tcx: TyCtxt<'tcx>, // don't need it now, but bet we will soon
386     comments: Vec<String>,
387 }
388
389 impl ExtraComments<'tcx> {
390     fn push(&mut self, lines: &str) {
391         for line in lines.split('\n') {
392             self.comments.push(line.to_string());
393         }
394     }
395 }
396
397 impl Visitor<'tcx> for ExtraComments<'tcx> {
398     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
399         self.super_constant(constant, location);
400         let Constant { span, user_ty, literal } = constant;
401         self.push("mir::Constant");
402         self.push(&format!("+ span: {:?}", span));
403         if let Some(user_ty) = user_ty {
404             self.push(&format!("+ user_ty: {:?}", user_ty));
405         }
406         self.push(&format!("+ literal: {:?}", literal));
407     }
408
409     fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
410         self.super_const(constant);
411         let ty::Const { ty, val, .. } = constant;
412         self.push("ty::Const");
413         self.push(&format!("+ ty: {:?}", ty));
414         self.push(&format!("+ val: {:?}", val));
415     }
416
417     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
418         self.super_rvalue(rvalue, location);
419         match rvalue {
420             Rvalue::Aggregate(kind, _) => match **kind {
421                 AggregateKind::Closure(def_id, substs) => {
422                     self.push("closure");
423                     self.push(&format!("+ def_id: {:?}", def_id));
424                     self.push(&format!("+ substs: {:#?}", substs));
425                 }
426
427                 AggregateKind::Generator(def_id, substs, movability) => {
428                     self.push("generator");
429                     self.push(&format!("+ def_id: {:?}", def_id));
430                     self.push(&format!("+ substs: {:#?}", substs));
431                     self.push(&format!("+ movability: {:?}", movability));
432                 }
433
434                 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
435                     self.push("adt");
436                     self.push(&format!("+ user_ty: {:?}", user_ty));
437                 }
438
439                 _ => {}
440             },
441
442             _ => {}
443         }
444     }
445 }
446
447 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
448     format!(
449         "scope {} at {}",
450         scope.index(),
451         tcx.sess.source_map().span_to_string(span)
452     )
453 }
454
455 /// Prints local variables in a scope tree.
456 fn write_scope_tree(
457     tcx: TyCtxt<'_>,
458     body: &Body<'_>,
459     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
460     w: &mut dyn Write,
461     parent: SourceScope,
462     depth: usize,
463 ) -> io::Result<()> {
464     let indent = depth * INDENT.len();
465
466     // Local variable types (including the user's name in a comment).
467     for (local, local_decl) in body.local_decls.iter_enumerated() {
468         if (1..body.arg_count+1).contains(&local.index()) {
469             // Skip over argument locals, they're printed in the signature.
470             continue;
471         }
472
473         if local_decl.source_info.scope != parent {
474             // Not declared in this scope.
475             continue;
476         }
477
478         let mut_str = if local_decl.mutability == Mutability::Mut {
479             "mut "
480         } else {
481             ""
482         };
483
484         let mut indented_decl = format!(
485             "{0:1$}let {2}{3:?}: {4:?}",
486             INDENT,
487             indent,
488             mut_str,
489             local,
490             local_decl.ty
491         );
492         for user_ty in local_decl.user_ty.projections() {
493             write!(indented_decl, " as {:?}", user_ty).unwrap();
494         }
495         indented_decl.push_str(";");
496
497         let local_name = if local == RETURN_PLACE {
498             format!(" return place")
499         } else if let Some(name) = local_decl.name {
500             format!(" \"{}\"", name)
501         } else {
502             String::new()
503         };
504
505         writeln!(
506             w,
507             "{0:1$} //{2} in {3}",
508             indented_decl,
509             ALIGN,
510             local_name,
511             comment(tcx, local_decl.source_info),
512         )?;
513     }
514
515     let children = match scope_tree.get(&parent) {
516         Some(childs) => childs,
517         None => return Ok(()),
518     };
519
520     for &child in children {
521         assert_eq!(body.source_scopes[child].parent_scope, Some(parent));
522         writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
523         write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
524         writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
525     }
526
527     Ok(())
528 }
529
530 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
531 /// local variables (both user-defined bindings and compiler temporaries).
532 pub fn write_mir_intro<'tcx>(
533     tcx: TyCtxt<'tcx>,
534     src: MirSource<'tcx>,
535     body: &Body<'_>,
536     w: &mut dyn Write,
537 ) -> io::Result<()> {
538     write_mir_sig(tcx, src, body, w)?;
539     writeln!(w, "{{")?;
540
541     // construct a scope tree and write it out
542     let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
543     for (index, scope_data) in body.source_scopes.iter().enumerate() {
544         if let Some(parent) = scope_data.parent_scope {
545             scope_tree
546                 .entry(parent)
547                 .or_default()
548                 .push(SourceScope::new(index));
549         } else {
550             // Only the argument scope has no parent, because it's the root.
551             assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
552         }
553     }
554
555     write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
556
557     // Add an empty line before the first block is printed.
558     writeln!(w, "")?;
559
560     Ok(())
561 }
562
563 fn write_mir_sig(
564     tcx: TyCtxt<'_>,
565     src: MirSource<'tcx>,
566     body: &Body<'_>,
567     w: &mut dyn Write,
568 ) -> io::Result<()> {
569     use rustc::hir::def::DefKind;
570
571     trace!("write_mir_sig: {:?}", src.instance);
572     let kind = tcx.def_kind(src.def_id());
573     let is_function = match kind {
574         Some(DefKind::Fn)
575         | Some(DefKind::Method)
576         | Some(DefKind::Ctor(..)) => true,
577         _ => tcx.is_closure(src.def_id()),
578     };
579     match (kind, src.promoted) {
580         (_, Some(i)) => write!(w, "{:?} in ", i)?,
581         (Some(DefKind::Const), _)
582         | (Some(DefKind::AssocConst), _) => write!(w, "const ")?,
583         (Some(DefKind::Static), _) =>
584             write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?,
585         (_, _) if is_function => write!(w, "fn ")?,
586         (None, _) => {}, // things like anon const, not an item
587         _ => bug!("Unexpected def kind {:?}", kind),
588     }
589
590     ty::print::with_forced_impl_filename_line(|| {
591         // see notes on #41697 elsewhere
592         write!(w, " {}", tcx.def_path_str(src.def_id()))
593     })?;
594
595     if src.promoted.is_none() && is_function {
596         write!(w, "(")?;
597
598         // fn argument types.
599         for (i, arg) in body.args_iter().enumerate() {
600             if i != 0 {
601                 write!(w, ", ")?;
602             }
603             write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
604         }
605
606         write!(w, ") -> {}", body.return_ty())?;
607     } else {
608         assert_eq!(body.arg_count, 0);
609         write!(w, ": {} =", body.return_ty())?;
610     }
611
612     if let Some(yield_ty) = body.yield_ty {
613         writeln!(w)?;
614         writeln!(w, "yields {}", yield_ty)?;
615     }
616
617     write!(w, " ")?;
618     // Next thing that gets printed is the opening {
619
620     Ok(())
621 }
622
623 fn write_user_type_annotations(body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
624     if !body.user_type_annotations.is_empty() {
625         writeln!(w, "| User Type Annotations")?;
626     }
627     for (index, annotation) in body.user_type_annotations.iter_enumerated() {
628         writeln!(w, "| {:?}: {:?} at {:?}", index.index(), annotation.user_ty, annotation.span)?;
629     }
630     if !body.user_type_annotations.is_empty() {
631         writeln!(w, "|")?;
632     }
633     Ok(())
634 }
635
636 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
637     if let Some(i) = single {
638         vec![i]
639     } else {
640         tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()
641     }
642 }