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