]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/pretty.rs
introduce `mir_keys()`
[rust.git] / src / librustc_mir / util / pretty.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::hir;
12 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
13 use rustc::mir::*;
14 use rustc::mir::transform::MirSource;
15 use rustc::ty::TyCtxt;
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::indexed_vec::{Idx};
18 use std::fmt::Display;
19 use std::fs;
20 use std::io::{self, Write};
21 use std::path::{PathBuf, Path};
22
23 const INDENT: &'static str = "    ";
24 /// Alignment for lining up comments following MIR statements
25 const ALIGN: usize = 40;
26
27 /// If the session is properly configured, dumps a human-readable
28 /// representation of the mir into:
29 ///
30 /// ```text
31 /// rustc.node<node_id>.<pass_name>.<disambiguator>
32 /// ```
33 ///
34 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
35 /// where `<filter>` takes the following forms:
36 ///
37 /// - `all` -- dump MIR for all fns, all passes, all everything
38 /// - `substring1&substring2,...` -- `&`-separated list of substrings
39 ///   that can appear in the pass-name or the `item_path_str` for the given
40 ///   node-id. If any one of the substrings match, the data is dumped out.
41 pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
42                           pass_name: &str,
43                           disambiguator: &Display,
44                           src: MirSource,
45                           mir: &Mir<'tcx>) {
46     let filters = match tcx.sess.opts.debugging_opts.dump_mir {
47         None => return,
48         Some(ref filters) => filters,
49     };
50     let node_id = src.item_id();
51     let node_path = tcx.item_path_str(tcx.hir.local_def_id(node_id));
52     let is_matched =
53         filters.split("&")
54                .any(|filter| {
55                    filter == "all" ||
56                        pass_name.contains(filter) ||
57                        node_path.contains(filter)
58                });
59     if !is_matched {
60         return;
61     }
62
63     let promotion_id = match src {
64         MirSource::Promoted(_, id) => format!("-{:?}", id),
65         _ => String::new()
66     };
67
68     let mut file_path = PathBuf::new();
69     if let Some(ref file_dir) = tcx.sess.opts.debugging_opts.dump_mir_dir {
70         let p = Path::new(file_dir);
71         file_path.push(p);
72     };
73     let file_name = format!("rustc.node{}{}.{}.{}.mir",
74                             node_id, promotion_id, pass_name, disambiguator);
75     file_path.push(&file_name);
76     let _ = fs::File::create(&file_path).and_then(|mut file| {
77         writeln!(file, "// MIR for `{}`", node_path)?;
78         writeln!(file, "// node_id = {}", node_id)?;
79         writeln!(file, "// pass_name = {}", pass_name)?;
80         writeln!(file, "// disambiguator = {}", disambiguator)?;
81         writeln!(file, "")?;
82         write_mir_fn(tcx, src, mir, &mut file)?;
83         Ok(())
84     });
85 }
86
87 /// Write out a human-readable textual representation for the given MIR.
88 pub fn write_mir_pretty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
89                                   single: Option<DefId>,
90                                   w: &mut Write)
91                                   -> io::Result<()>
92 {
93     writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
94     writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
95
96     let mut first = true;
97     for def_id in dump_mir_def_ids(tcx, single) {
98         let mir = &tcx.item_mir(def_id);
99
100         if first {
101             first = false;
102         } else {
103             // Put empty lines between all items
104             writeln!(w, "")?;
105         }
106
107         let id = tcx.hir.as_local_node_id(def_id).unwrap();
108         let src = MirSource::from_node(tcx, id);
109         write_mir_fn(tcx, src, mir, w)?;
110
111         for (i, mir) in mir.promoted.iter_enumerated() {
112             writeln!(w, "")?;
113             write_mir_fn(tcx, MirSource::Promoted(id, i), mir, w)?;
114         }
115     }
116     Ok(())
117 }
118
119 pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
120                               src: MirSource,
121                               mir: &Mir<'tcx>,
122                               w: &mut Write)
123                               -> io::Result<()> {
124     write_mir_intro(tcx, src, mir, w)?;
125     for block in mir.basic_blocks().indices() {
126         write_basic_block(tcx, block, mir, w)?;
127         if block.index() + 1 != mir.basic_blocks().len() {
128             writeln!(w, "")?;
129         }
130     }
131
132     writeln!(w, "}}")?;
133     Ok(())
134 }
135
136 /// Write out a human-readable textual representation for the given basic block.
137 fn write_basic_block(tcx: TyCtxt,
138                      block: BasicBlock,
139                      mir: &Mir,
140                      w: &mut Write)
141                      -> io::Result<()> {
142     let data = &mir[block];
143
144     // Basic block label at the top.
145     writeln!(w, "{}{:?}: {{", INDENT, block)?;
146
147     // List of statements in the middle.
148     let mut current_location = Location { block: block, statement_index: 0 };
149     for statement in &data.statements {
150         let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
151         writeln!(w, "{0:1$} // {2}",
152                  indented_mir,
153                  ALIGN,
154                  comment(tcx, statement.source_info))?;
155
156         current_location.statement_index += 1;
157     }
158
159     // Terminator at the bottom.
160     let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
161     writeln!(w, "{0:1$} // {2}",
162              indented_terminator,
163              ALIGN,
164              comment(tcx, data.terminator().source_info))?;
165
166     writeln!(w, "{}}}", INDENT)
167 }
168
169 fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
170     format!("scope {} at {}", scope.index(), tcx.sess.codemap().span_to_string(span))
171 }
172
173 /// Prints user-defined variables in a scope tree.
174 ///
175 /// Returns the total number of variables printed.
176 fn write_scope_tree(tcx: TyCtxt,
177                     mir: &Mir,
178                     scope_tree: &FxHashMap<VisibilityScope, Vec<VisibilityScope>>,
179                     w: &mut Write,
180                     parent: VisibilityScope,
181                     depth: usize)
182                     -> io::Result<()> {
183     let indent = depth * INDENT.len();
184
185     let children = match scope_tree.get(&parent) {
186         Some(childs) => childs,
187         None => return Ok(()),
188     };
189
190     for &child in children {
191         let data = &mir.visibility_scopes[child];
192         assert_eq!(data.parent_scope, Some(parent));
193         writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
194
195         // User variable types (including the user's name in a comment).
196         for local in mir.vars_iter() {
197             let var = &mir.local_decls[local];
198             let (name, source_info) = if var.source_info.scope == child {
199                 (var.name.unwrap(), var.source_info)
200             } else {
201                 // Not a variable or not declared in this scope.
202                 continue;
203             };
204
205             let mut_str = if var.mutability == Mutability::Mut {
206                 "mut "
207             } else {
208                 ""
209             };
210
211             let indent = indent + INDENT.len();
212             let indented_var = format!("{0:1$}let {2}{3:?}: {4};",
213                                        INDENT,
214                                        indent,
215                                        mut_str,
216                                        local,
217                                        var.ty);
218             writeln!(w, "{0:1$} // \"{2}\" in {3}",
219                      indented_var,
220                      ALIGN,
221                      name,
222                      comment(tcx, source_info))?;
223         }
224
225         write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;
226
227         writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
228     }
229
230     Ok(())
231 }
232
233 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
234 /// local variables (both user-defined bindings and compiler temporaries).
235 fn write_mir_intro<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
236                              src: MirSource,
237                              mir: &Mir,
238                              w: &mut Write)
239                              -> io::Result<()> {
240     write_mir_sig(tcx, src, mir, w)?;
241     writeln!(w, " {{")?;
242
243     // construct a scope tree and write it out
244     let mut scope_tree: FxHashMap<VisibilityScope, Vec<VisibilityScope>> = FxHashMap();
245     for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
246         if let Some(parent) = scope_data.parent_scope {
247             scope_tree.entry(parent)
248                       .or_insert(vec![])
249                       .push(VisibilityScope::new(index));
250         } else {
251             // Only the argument scope has no parent, because it's the root.
252             assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
253         }
254     }
255
256     // Print return pointer
257     let indented_retptr = format!("{}let mut {:?}: {};",
258                                   INDENT,
259                                   RETURN_POINTER,
260                                   mir.return_ty);
261     writeln!(w, "{0:1$} // return pointer",
262              indented_retptr,
263              ALIGN)?;
264
265     write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;
266
267     write_temp_decls(mir, w)?;
268
269     // Add an empty line before the first block is printed.
270     writeln!(w, "")?;
271
272     Ok(())
273 }
274
275 fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut Write)
276                  -> io::Result<()>
277 {
278     match src {
279         MirSource::Fn(_) => write!(w, "fn")?,
280         MirSource::Const(_) => write!(w, "const")?,
281         MirSource::Static(_, hir::MutImmutable) => write!(w, "static")?,
282         MirSource::Static(_, hir::MutMutable) => write!(w, "static mut")?,
283         MirSource::Promoted(_, i) => write!(w, "{:?} in", i)?
284     }
285
286     write!(w, " {}", tcx.node_path_str(src.item_id()))?;
287
288     if let MirSource::Fn(_) = src {
289         write!(w, "(")?;
290
291         // fn argument types.
292         for (i, arg) in mir.args_iter().enumerate() {
293             if i != 0 {
294                 write!(w, ", ")?;
295             }
296             write!(w, "{:?}: {}", Lvalue::Local(arg), mir.local_decls[arg].ty)?;
297         }
298
299         write!(w, ") -> {}", mir.return_ty)
300     } else {
301         assert_eq!(mir.arg_count, 0);
302         write!(w, ": {} =", mir.return_ty)
303     }
304 }
305
306 fn write_temp_decls(mir: &Mir, w: &mut Write) -> io::Result<()> {
307     // Compiler-introduced temporary types.
308     for temp in mir.temps_iter() {
309         writeln!(w, "{}let mut {:?}: {};", INDENT, temp, mir.local_decls[temp].ty)?;
310     }
311
312     Ok(())
313 }
314
315 pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option<DefId>) -> Vec<DefId> {
316     if let Some(i) = single {
317         vec![i]
318     } else {
319         tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()
320     }
321 }