]> git.proxmox.com Git - rustc.git/blame - src/librustc_driver/pretty.rs
New upstream version 1.27.1+dfsg1
[rustc.git] / src / librustc_driver / pretty.rs
CommitLineData
1a4d82fc
JJ
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//! The various pretty print routines.
12
13pub use self::UserIdentifiedItem::*;
14pub use self::PpSourceMode::*;
15pub use self::PpMode::*;
16use self::NodesMatchingUII::*;
17
32a655c1 18use {abort_on_err, driver};
1a4d82fc 19
ff7c6d11 20use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
54a0048b
SL
21use rustc::cfg;
22use rustc::cfg::graphviz::LabelledCFG;
ea8adc8c 23use rustc::middle::cstore::CrateStore;
1a4d82fc 24use rustc::session::Session;
ea8adc8c 25use rustc::session::config::{Input, OutputFilenames};
1a4d82fc
JJ
26use rustc_borrowck as borrowck;
27use rustc_borrowck::graphviz as borrowck_dot;
28
cc61c64b 29use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
7453a54e
SL
30
31use syntax::ast::{self, BlockCheckMode};
1a4d82fc 32use syntax::fold::{self, Folder};
041b39d2 33use syntax::print::{pprust};
b039eaaf 34use syntax::print::pprust::PrintState;
1a4d82fc 35use syntax::ptr::P;
d9579d0f 36use syntax::util::small_vector::SmallVector;
ff7c6d11 37use syntax_pos::{self, FileName};
1a4d82fc
JJ
38
39use graphviz as dot;
40
32a655c1 41use std::cell::Cell;
c34b1796
AL
42use std::fs::File;
43use std::io::{self, Write};
1a4d82fc 44use std::option;
a7813a04 45use std::path::Path;
1a4d82fc 46use std::str::FromStr;
3b2f2976 47use std::mem;
1a4d82fc 48
54a0048b 49use rustc::hir::map as hir_map;
32a655c1 50use rustc::hir::map::blocks;
54a0048b 51use rustc::hir;
54a0048b
SL
52use rustc::hir::print as pprust_hir;
53
c34b1796 54#[derive(Copy, Clone, PartialEq, Debug)]
1a4d82fc
JJ
55pub enum PpSourceMode {
56 PpmNormal,
57 PpmEveryBodyLoops,
58 PpmExpanded,
1a4d82fc
JJ
59 PpmIdentified,
60 PpmExpandedIdentified,
61 PpmExpandedHygiene,
e9174d1e 62 PpmTyped,
1a4d82fc
JJ
63}
64
c34b1796 65#[derive(Copy, Clone, PartialEq, Debug)]
85aaf69f
SL
66pub enum PpFlowGraphMode {
67 Default,
68 /// Drops the labels from the edges in the flowgraph output. This
2c00a5a8 69 /// is mostly for use in the -Z unpretty flowgraph run-make tests,
85aaf69f
SL
70 /// since the labels are largely uninteresting in those cases and
71 /// have become a pain to maintain.
72 UnlabelledEdges,
73}
c34b1796 74#[derive(Copy, Clone, PartialEq, Debug)]
1a4d82fc
JJ
75pub enum PpMode {
76 PpmSource(PpSourceMode),
e9174d1e 77 PpmHir(PpSourceMode),
ff7c6d11 78 PpmHirTree(PpSourceMode),
85aaf69f 79 PpmFlowGraph(PpFlowGraphMode),
7453a54e 80 PpmMir,
54a0048b 81 PpmMirCFG,
1a4d82fc
JJ
82}
83
a7813a04
XL
84impl PpMode {
85 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
86 match *self {
87 PpmSource(PpmNormal) |
88 PpmSource(PpmEveryBodyLoops) |
89 PpmSource(PpmIdentified) => opt_uii.is_some(),
90
91 PpmSource(PpmExpanded) |
92 PpmSource(PpmExpandedIdentified) |
93 PpmSource(PpmExpandedHygiene) |
94 PpmHir(_) |
ff7c6d11 95 PpmHirTree(_) |
a7813a04
XL
96 PpmMir |
97 PpmMirCFG |
98 PpmFlowGraph(_) => true,
99 PpmSource(PpmTyped) => panic!("invalid state"),
100 }
101 }
102
103 pub fn needs_analysis(&self) -> bool {
104 match *self {
c30ab7b3
SL
105 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
106 _ => false,
a7813a04
XL
107 }
108 }
109}
110
1a4d82fc
JJ
111pub fn parse_pretty(sess: &Session,
112 name: &str,
92a42be0
SL
113 extended: bool)
114 -> (PpMode, Option<UserIdentifiedItem>) {
c34b1796 115 let mut split = name.splitn(2, '=');
1a4d82fc
JJ
116 let first = split.next().unwrap();
117 let opt_second = split.next();
118 let first = match (first, extended) {
92a42be0
SL
119 ("normal", _) => PpmSource(PpmNormal),
120 ("identified", _) => PpmSource(PpmIdentified),
1a4d82fc 121 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
92a42be0 122 ("expanded", _) => PpmSource(PpmExpanded),
1a4d82fc
JJ
123 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
124 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
92a42be0 125 ("hir", true) => PpmHir(PpmNormal),
e9174d1e 126 ("hir,identified", true) => PpmHir(PpmIdentified),
92a42be0 127 ("hir,typed", true) => PpmHir(PpmTyped),
ff7c6d11 128 ("hir-tree", true) => PpmHirTree(PpmNormal),
7453a54e 129 ("mir", true) => PpmMir,
54a0048b 130 ("mir-cfg", true) => PpmMirCFG,
92a42be0
SL
131 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
132 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
1a4d82fc
JJ
133 _ => {
134 if extended {
92a42be0
SL
135 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
136 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
137 `identified`, `expanded,identified`, `everybody_loops`, \
7453a54e 138 `hir`, `hir,identified`, `hir,typed`, or `mir`; got {}",
92a42be0 139 name));
1a4d82fc 140 } else {
92a42be0
SL
141 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
142 `identified`, or `expanded,identified`; got {}",
143 name));
1a4d82fc
JJ
144 }
145 }
146 };
85aaf69f 147 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
1a4d82fc
JJ
148 (first, opt_second)
149}
150
151
152
153// This slightly awkward construction is to allow for each PpMode to
154// choose whether it needs to do analyses (which can consume the
155// Session) and then pass through the session (now attached to the
156// analysis results) on to the chosen pretty-printer, along with the
157// `&PpAnn` object.
158//
159// Note that since the `&PrinterSupport` is freshly constructed on each
160// call, it would not make sense to try to attach the lifetime of `self`
161// to the lifetime of the `&PrinterObject`.
162//
163// (The `use_once_payload` is working around the current lack of once
164// functions in the compiler.)
165
166impl PpSourceMode {
167 /// Constructs a `PrinterSupport` object and passes it to `f`.
041b39d2 168 fn call_with_pp_support<'tcx, A, F>(&self,
b039eaaf 169 sess: &'tcx Session,
32a655c1 170 hir_map: Option<&hir_map::Map<'tcx>>,
92a42be0
SL
171 f: F)
172 -> A
041b39d2 173 where F: FnOnce(&PrinterSupport) -> A
1a4d82fc
JJ
174 {
175 match *self {
176 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
92a42be0 177 let annotation = NoAnn {
3b2f2976 178 sess,
32a655c1 179 hir_map: hir_map.map(|m| m.clone()),
92a42be0 180 };
041b39d2 181 f(&annotation)
1a4d82fc
JJ
182 }
183
184 PpmIdentified | PpmExpandedIdentified => {
92a42be0 185 let annotation = IdentifiedAnnotation {
3b2f2976 186 sess,
32a655c1 187 hir_map: hir_map.map(|m| m.clone()),
92a42be0 188 };
041b39d2 189 f(&annotation)
1a4d82fc
JJ
190 }
191 PpmExpandedHygiene => {
92a42be0 192 let annotation = HygieneAnnotation {
3b2f2976 193 sess,
92a42be0 194 };
041b39d2 195 f(&annotation)
1a4d82fc 196 }
e9174d1e
SL
197 _ => panic!("Should use call_with_pp_support_hir"),
198 }
199 }
041b39d2 200 fn call_with_pp_support_hir<'tcx, A, F>(&self,
b039eaaf 201 sess: &'tcx Session,
ea8adc8c 202 cstore: &'tcx CrateStore,
32a655c1 203 hir_map: &hir_map::Map<'tcx>,
8bb4bdeb 204 analysis: &ty::CrateAnalysis,
a7813a04 205 resolutions: &Resolutions,
ff7c6d11 206 arenas: &'tcx AllArenas<'tcx>,
ea8adc8c 207 output_filenames: &OutputFilenames,
b039eaaf 208 id: &str,
92a42be0
SL
209 f: F)
210 -> A
041b39d2 211 where F: FnOnce(&HirPrinterSupport, &hir::Crate) -> A
e9174d1e
SL
212 {
213 match *self {
214 PpmNormal => {
92a42be0 215 let annotation = NoAnn {
3b2f2976 216 sess,
32a655c1 217 hir_map: Some(hir_map.clone()),
92a42be0 218 };
041b39d2 219 f(&annotation, hir_map.forest.krate())
e9174d1e
SL
220 }
221
222 PpmIdentified => {
223 let annotation = IdentifiedAnnotation {
3b2f2976 224 sess,
32a655c1 225 hir_map: Some(hir_map.clone()),
e9174d1e 226 };
041b39d2 227 f(&annotation, hir_map.forest.krate())
e9174d1e 228 }
1a4d82fc 229 PpmTyped => {
abe05a73 230 let control = &driver::CompileController::basic();
2c00a5a8
XL
231 let trans = ::get_trans(sess);
232 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
233 control,
abe05a73 234 sess,
ea8adc8c 235 cstore,
32a655c1 236 hir_map.clone(),
a7813a04
XL
237 analysis.clone(),
238 resolutions.clone(),
7453a54e
SL
239 arenas,
240 id,
ea8adc8c 241 output_filenames,
c30ab7b3 242 |tcx, _, _, _| {
3b2f2976 243 let empty_tables = ty::TypeckTables::empty(None);
32a655c1 244 let annotation = TypedAnnotation {
3b2f2976 245 tcx,
32a655c1
SL
246 tables: Cell::new(&empty_tables)
247 };
2c00a5a8
XL
248 tcx.dep_graph.with_ignore(|| {
249 f(&annotation, hir_map.forest.krate())
250 })
c30ab7b3
SL
251 }),
252 sess)
1a4d82fc 253 }
e9174d1e 254 _ => panic!("Should use call_with_pp_support"),
1a4d82fc
JJ
255 }
256 }
257}
258
32a655c1 259trait PrinterSupport: pprust::PpAnn {
1a4d82fc
JJ
260 /// Provides a uniform interface for re-extracting a reference to a
261 /// `Session` from a value that now owns it.
262 fn sess<'a>(&'a self) -> &'a Session;
263
1a4d82fc
JJ
264 /// Produces the pretty-print annotation object.
265 ///
266 /// (Rust does not yet support upcasting from a trait object to
267 /// an object for one of its super-traits.)
268 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
269}
270
32a655c1 271trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
e9174d1e
SL
272 /// Provides a uniform interface for re-extracting a reference to a
273 /// `Session` from a value that now owns it.
274 fn sess<'a>(&'a self) -> &'a Session;
275
276 /// Provides a uniform interface for re-extracting a reference to an
277 /// `hir_map::Map` from a value that now owns it.
32a655c1 278 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
e9174d1e
SL
279
280 /// Produces the pretty-print annotation object.
281 ///
282 /// (Rust does not yet support upcasting from a trait object to
283 /// an object for one of its super-traits.)
284 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
54a0048b
SL
285
286 /// Computes an user-readable representation of a path, if possible.
287 fn node_path(&self, id: ast::NodeId) -> Option<String> {
32a655c1 288 self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
c30ab7b3
SL
289 path.data
290 .into_iter()
291 .map(|elem| elem.data.to_string())
292 .collect::<Vec<_>>()
293 .join("::")
54a0048b
SL
294 })
295 }
e9174d1e
SL
296}
297
32a655c1
SL
298struct NoAnn<'hir> {
299 sess: &'hir Session,
300 hir_map: Option<hir_map::Map<'hir>>,
1a4d82fc
JJ
301}
302
32a655c1 303impl<'hir> PrinterSupport for NoAnn<'hir> {
92a42be0
SL
304 fn sess<'a>(&'a self) -> &'a Session {
305 self.sess
306 }
1a4d82fc 307
92a42be0
SL
308 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
309 self
310 }
1a4d82fc
JJ
311}
312
32a655c1 313impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
92a42be0
SL
314 fn sess<'a>(&'a self) -> &'a Session {
315 self.sess
316 }
e9174d1e 317
32a655c1
SL
318 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
319 self.hir_map.as_ref()
e9174d1e
SL
320 }
321
92a42be0
SL
322 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
323 self
324 }
e9174d1e
SL
325}
326
32a655c1
SL
327impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
328impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
329 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
330 -> io::Result<()> {
331 if let Some(ref map) = self.hir_map {
332 pprust_hir::PpAnn::nested(map, state, nested)
333 } else {
334 Ok(())
335 }
336 }
337}
1a4d82fc 338
32a655c1
SL
339struct IdentifiedAnnotation<'hir> {
340 sess: &'hir Session,
341 hir_map: Option<hir_map::Map<'hir>>,
1a4d82fc
JJ
342}
343
32a655c1 344impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
92a42be0
SL
345 fn sess<'a>(&'a self) -> &'a Session {
346 self.sess
347 }
1a4d82fc 348
92a42be0
SL
349 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
350 self
351 }
1a4d82fc
JJ
352}
353
32a655c1 354impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
92a42be0 355 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc
JJ
356 match node {
357 pprust::NodeExpr(_) => s.popen(),
92a42be0 358 _ => Ok(()),
1a4d82fc
JJ
359 }
360 }
92a42be0 361 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc 362 match node {
c30ab7b3
SL
363 pprust::NodeIdent(_) |
364 pprust::NodeName(_) => Ok(()),
1a4d82fc
JJ
365
366 pprust::NodeItem(item) => {
041b39d2 367 s.s.space()?;
1a4d82fc
JJ
368 s.synth_comment(item.id.to_string())
369 }
c34b1796 370 pprust::NodeSubItem(id) => {
041b39d2 371 s.s.space()?;
c34b1796
AL
372 s.synth_comment(id.to_string())
373 }
1a4d82fc 374 pprust::NodeBlock(blk) => {
041b39d2 375 s.s.space()?;
1a4d82fc
JJ
376 s.synth_comment(format!("block {}", blk.id))
377 }
378 pprust::NodeExpr(expr) => {
041b39d2 379 s.s.space()?;
54a0048b 380 s.synth_comment(expr.id.to_string())?;
1a4d82fc
JJ
381 s.pclose()
382 }
383 pprust::NodePat(pat) => {
041b39d2 384 s.s.space()?;
1a4d82fc
JJ
385 s.synth_comment(format!("pat {}", pat.id))
386 }
387 }
388 }
389}
390
32a655c1 391impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
92a42be0
SL
392 fn sess<'a>(&'a self) -> &'a Session {
393 self.sess
394 }
e9174d1e 395
32a655c1
SL
396 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
397 self.hir_map.as_ref()
e9174d1e
SL
398 }
399
92a42be0
SL
400 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
401 self
402 }
e9174d1e
SL
403}
404
32a655c1
SL
405impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
406 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
407 -> io::Result<()> {
408 if let Some(ref map) = self.hir_map {
409 pprust_hir::PpAnn::nested(map, state, nested)
410 } else {
411 Ok(())
412 }
413 }
92a42be0 414 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
e9174d1e
SL
415 match node {
416 pprust_hir::NodeExpr(_) => s.popen(),
92a42be0 417 _ => Ok(()),
e9174d1e
SL
418 }
419 }
92a42be0 420 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
e9174d1e 421 match node {
b039eaaf 422 pprust_hir::NodeName(_) => Ok(()),
e9174d1e 423 pprust_hir::NodeItem(item) => {
041b39d2 424 s.s.space()?;
ff7c6d11
XL
425 s.synth_comment(format!("node_id: {} hir local_id: {}",
426 item.id, item.hir_id.local_id.0))
e9174d1e
SL
427 }
428 pprust_hir::NodeSubItem(id) => {
041b39d2 429 s.s.space()?;
e9174d1e
SL
430 s.synth_comment(id.to_string())
431 }
432 pprust_hir::NodeBlock(blk) => {
041b39d2 433 s.s.space()?;
ff7c6d11
XL
434 s.synth_comment(format!("block node_id: {} hir local_id: {}",
435 blk.id, blk.hir_id.local_id.0))
e9174d1e
SL
436 }
437 pprust_hir::NodeExpr(expr) => {
041b39d2 438 s.s.space()?;
ff7c6d11
XL
439 s.synth_comment(format!("node_id: {} hir local_id: {}",
440 expr.id, expr.hir_id.local_id.0))?;
e9174d1e
SL
441 s.pclose()
442 }
443 pprust_hir::NodePat(pat) => {
041b39d2 444 s.s.space()?;
ff7c6d11
XL
445 s.synth_comment(format!("pat node_id: {} hir local_id: {}",
446 pat.id, pat.hir_id.local_id.0))
e9174d1e
SL
447 }
448 }
449 }
450}
451
32a655c1
SL
452struct HygieneAnnotation<'a> {
453 sess: &'a Session
1a4d82fc
JJ
454}
455
32a655c1
SL
456impl<'a> PrinterSupport for HygieneAnnotation<'a> {
457 fn sess(&self) -> &Session {
92a42be0
SL
458 self.sess
459 }
1a4d82fc 460
32a655c1 461 fn pp_ann(&self) -> &pprust::PpAnn {
92a42be0
SL
462 self
463 }
1a4d82fc
JJ
464}
465
32a655c1 466impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
92a42be0 467 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc 468 match node {
83c7162d 469 pprust::NodeIdent(&ast::Ident { name, span }) => {
041b39d2 470 s.s.space()?;
1a4d82fc
JJ
471 // FIXME #16420: this doesn't display the connections
472 // between syntax contexts
83c7162d 473 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
1a4d82fc 474 }
476ff2be 475 pprust::NodeName(&name) => {
041b39d2 476 s.s.space()?;
476ff2be 477 s.synth_comment(name.as_u32().to_string())
1a4d82fc 478 }
92a42be0 479 _ => Ok(()),
1a4d82fc
JJ
480 }
481 }
482}
483
484
62682a34 485struct TypedAnnotation<'a, 'tcx: 'a> {
a7813a04 486 tcx: TyCtxt<'a, 'tcx, 'tcx>,
32a655c1 487 tables: Cell<&'a ty::TypeckTables<'tcx>>,
1a4d82fc
JJ
488}
489
e9174d1e 490impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
92a42be0
SL
491 fn sess<'a>(&'a self) -> &'a Session {
492 &self.tcx.sess
493 }
1a4d82fc 494
32a655c1
SL
495 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
496 Some(&self.tcx.hir)
1a4d82fc
JJ
497 }
498
92a42be0
SL
499 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
500 self
501 }
54a0048b
SL
502
503 fn node_path(&self, id: ast::NodeId) -> Option<String> {
504 Some(self.tcx.node_path_str(id))
505 }
1a4d82fc
JJ
506}
507
e9174d1e 508impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
32a655c1
SL
509 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
510 -> io::Result<()> {
511 let old_tables = self.tables.get();
512 if let pprust_hir::Nested::Body(id) = nested {
513 self.tables.set(self.tcx.body_tables(id));
514 }
515 pprust_hir::PpAnn::nested(&self.tcx.hir, state, nested)?;
516 self.tables.set(old_tables);
517 Ok(())
518 }
92a42be0 519 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
1a4d82fc 520 match node {
e9174d1e 521 pprust_hir::NodeExpr(_) => s.popen(),
92a42be0 522 _ => Ok(()),
1a4d82fc
JJ
523 }
524 }
92a42be0 525 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
1a4d82fc 526 match node {
e9174d1e 527 pprust_hir::NodeExpr(expr) => {
041b39d2
XL
528 s.s.space()?;
529 s.s.word("as")?;
530 s.s.space()?;
531 s.s.word(&self.tables.get().expr_ty(expr).to_string())?;
1a4d82fc
JJ
532 s.pclose()
533 }
92a42be0 534 _ => Ok(()),
1a4d82fc
JJ
535 }
536 }
537}
538
539fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
540 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
541 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
542 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
543 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
544 let mut variants = Vec::new();
545 if print_all || print_loans {
546 variants.push(borrowck_dot::Loans);
547 }
548 if print_all || print_moves {
549 variants.push(borrowck_dot::Moves);
550 }
551 if print_all || print_assigns {
552 variants.push(borrowck_dot::Assigns);
553 }
554 variants
555}
556
85aaf69f 557#[derive(Clone, Debug)]
1a4d82fc
JJ
558pub enum UserIdentifiedItem {
559 ItemViaNode(ast::NodeId),
560 ItemViaPath(Vec<String>),
561}
562
563impl FromStr for UserIdentifiedItem {
85aaf69f
SL
564 type Err = ();
565 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
92a42be0 566 Ok(s.parse()
9e0c209e 567 .map(ast::NodeId::new)
92a42be0
SL
568 .map(ItemViaNode)
569 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
1a4d82fc
JJ
570 }
571}
572
32a655c1 573enum NodesMatchingUII<'a, 'hir: 'a> {
1a4d82fc 574 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
32a655c1 575 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
1a4d82fc
JJ
576}
577
32a655c1 578impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
1a4d82fc
JJ
579 type Item = ast::NodeId;
580
581 fn next(&mut self) -> Option<ast::NodeId> {
582 match self {
583 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
584 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
585 }
586 }
0531ce1d
XL
587
588 fn size_hint(&self) -> (usize, Option<usize>) {
589 match self {
590 &NodesMatchingDirect(ref iter) => iter.size_hint(),
591 &NodesMatchingSuffix(ref iter) => iter.size_hint(),
592 }
593 }
1a4d82fc
JJ
594}
595
596impl UserIdentifiedItem {
597 fn reconstructed_input(&self) -> String {
598 match *self {
599 ItemViaNode(node_id) => node_id.to_string(),
c1a9b12d 600 ItemViaPath(ref parts) => parts.join("::"),
1a4d82fc
JJ
601 }
602 }
603
32a655c1
SL
604 fn all_matching_node_ids<'a, 'hir>(&'a self,
605 map: &'a hir_map::Map<'hir>)
606 -> NodesMatchingUII<'a, 'hir> {
1a4d82fc 607 match *self {
92a42be0 608 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
cc61c64b 609 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
1a4d82fc
JJ
610 }
611 }
612
e9174d1e 613 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
85aaf69f 614 let fail_because = |is_wrong_because| -> ast::NodeId {
92a42be0
SL
615 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
616 {}, which {}",
617 user_option,
618 self.reconstructed_input(),
619 is_wrong_because);
cc61c64b 620 sess.fatal(&message)
1a4d82fc
JJ
621 };
622
623 let mut saw_node = ast::DUMMY_NODE_ID;
85aaf69f 624 let mut seen = 0;
1a4d82fc
JJ
625 for node in self.all_matching_node_ids(map) {
626 saw_node = node;
627 seen += 1;
628 if seen > 1 {
629 fail_because("does not resolve uniquely");
630 }
631 }
632 if seen == 0 {
633 fail_because("does not resolve to any item");
634 }
635
636 assert!(seen == 1);
637 return saw_node;
638 }
639}
640
3b2f2976
XL
641// Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
642//
643// FIXME: Currently the `everybody_loops` transformation is not applied to:
644// * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
645// waiting for miri to fix that.
646// * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
647// Solving this may require `!` to implement every trait, which relies on the an even more
648// ambitious form of the closed RFC #1637. See also [#34511].
649//
650// [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
ff7c6d11 651pub struct ReplaceBodyWithLoop<'a> {
1a4d82fc 652 within_static_or_const: bool,
ff7c6d11 653 sess: &'a Session,
1a4d82fc
JJ
654}
655
ff7c6d11
XL
656impl<'a> ReplaceBodyWithLoop<'a> {
657 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
658 ReplaceBodyWithLoop { within_static_or_const: false, sess }
1a4d82fc 659 }
3b2f2976
XL
660
661 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
662 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
663 let ret = action(self);
664 self.within_static_or_const = old_const;
665 ret
666 }
667
668 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
669 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
670 fn involves_impl_trait(ty: &ast::Ty) -> bool {
671 match ty.node {
672 ast::TyKind::ImplTrait(_) => true,
673 ast::TyKind::Slice(ref subty) |
674 ast::TyKind::Array(ref subty, _) |
675 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
676 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
677 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
ea8adc8c
XL
678 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
679 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
680 match seg.parameters.as_ref().map(|p| &**p) {
681 None => false,
682 Some(&ast::PathParameters::AngleBracketed(ref data)) =>
683 any_involves_impl_trait(data.types.iter()) ||
684 any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)),
685 Some(&ast::PathParameters::Parenthesized(ref data)) =>
686 any_involves_impl_trait(data.inputs.iter()) ||
687 any_involves_impl_trait(data.output.iter()),
688 }
689 }),
3b2f2976
XL
690 _ => false,
691 }
692 }
ea8adc8c
XL
693
694 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
695 it.any(|subty| involves_impl_trait(subty))
696 }
697
3b2f2976
XL
698 involves_impl_trait(ty)
699 } else {
700 false
701 }
702 }
1a4d82fc
JJ
703}
704
ff7c6d11 705impl<'a> fold::Folder for ReplaceBodyWithLoop<'a> {
7453a54e 706 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
3b2f2976
XL
707 let is_const = match i {
708 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
709 ast::ItemKind::Fn(ref decl, _, ref constness, _, _, _) =>
710 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
711 _ => false,
712 };
713 self.run(is_const, |s| fold::noop_fold_item_kind(i, s))
1a4d82fc
JJ
714 }
715
7453a54e 716 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
3b2f2976
XL
717 let is_const = match i.node {
718 ast::TraitItemKind::Const(..) => true,
719 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
720 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
721 _ => false,
722 };
723 self.run(is_const, |s| fold::noop_fold_trait_item(i, s))
d9579d0f
AL
724 }
725
7453a54e 726 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
3b2f2976
XL
727 let is_const = match i.node {
728 ast::ImplItemKind::Const(..) => true,
729 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
730 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
731 _ => false,
732 };
733 self.run(is_const, |s| fold::noop_fold_impl_item(i, s))
d9579d0f 734 }
1a4d82fc
JJ
735
736 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
ff7c6d11
XL
737 fn expr_to_block(rules: ast::BlockCheckMode,
738 recovered: bool,
739 e: Option<P<ast::Expr>>,
740 sess: &Session) -> P<ast::Block> {
1a4d82fc 741 P(ast::Block {
c30ab7b3
SL
742 stmts: e.map(|e| {
743 ast::Stmt {
ff7c6d11 744 id: sess.next_node_id(),
c30ab7b3
SL
745 span: e.span,
746 node: ast::StmtKind::Expr(e),
747 }
748 })
749 .into_iter()
750 .collect(),
3b2f2976 751 rules,
ff7c6d11 752 id: sess.next_node_id(),
3157f602 753 span: syntax_pos::DUMMY_SP,
ff7c6d11 754 recovered,
1a4d82fc
JJ
755 })
756 }
757
758 if !self.within_static_or_const {
759
ff7c6d11 760 let empty_block = expr_to_block(BlockCheckMode::Default, false, None, self.sess);
1a4d82fc 761 let loop_expr = P(ast::Expr {
7453a54e 762 node: ast::ExprKind::Loop(empty_block, None),
ff7c6d11 763 id: self.sess.next_node_id(),
3157f602
XL
764 span: syntax_pos::DUMMY_SP,
765 attrs: ast::ThinVec::new(),
1a4d82fc
JJ
766 });
767
ff7c6d11 768 expr_to_block(b.rules, b.recovered, Some(loop_expr), self.sess)
1a4d82fc
JJ
769
770 } else {
771 fold::noop_fold_block(b, self)
772 }
773 }
774
775 // in general the pretty printer processes unexpanded code, so
776 // we override the default `fold_mac` method which panics.
777 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
778 fold::noop_fold_mac(mac, self)
779 }
780}
781
a7813a04
XL
782fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
783 tcx: TyCtxt<'a, 'tcx, 'tcx>,
476ff2be 784 code: blocks::Code<'tcx>,
a7813a04
XL
785 mode: PpFlowGraphMode,
786 mut out: W)
787 -> io::Result<()> {
8bb4bdeb
XL
788 let body_id = match code {
789 blocks::Code::Expr(expr) => {
790 // Find the function this expression is from.
791 let mut node_id = expr.id;
792 loop {
793 let node = tcx.hir.get(node_id);
794 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
795 break n.body();
796 }
797 let parent = tcx.hir.get_parent_node(node_id);
798 assert!(node_id != parent);
799 node_id = parent;
800 }
801 }
802 blocks::Code::FnLike(fn_like) => fn_like.body(),
a7813a04 803 };
8bb4bdeb
XL
804 let body = tcx.hir.body(body_id);
805 let cfg = cfg::CFG::new(tcx, &body);
a7813a04
XL
806 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
807 let lcfg = LabelledCFG {
ea8adc8c 808 tcx,
a7813a04
XL
809 cfg: &cfg,
810 name: format!("node_{}", code.id()),
3b2f2976 811 labelled_edges,
1a4d82fc
JJ
812 };
813
a7813a04
XL
814 match code {
815 _ if variants.is_empty() => {
816 let r = dot::render(&lcfg, &mut out);
817 return expand_err_details(r);
818 }
476ff2be 819 blocks::Code::Expr(_) => {
a7813a04
XL
820 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
821 fn-like node id.");
822 return Ok(());
823 }
476ff2be 824 blocks::Code::FnLike(fn_like) => {
a7813a04 825 let (bccx, analysis_data) =
32a655c1 826 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
1a4d82fc 827
a7813a04
XL
828 let lcfg = borrowck_dot::DataflowLabeller {
829 inner: lcfg,
3b2f2976 830 variants,
a7813a04
XL
831 borrowck_ctxt: &bccx,
832 analysis_data: &analysis_data,
833 };
834 let r = dot::render(&lcfg, &mut out);
835 return expand_err_details(r);
1a4d82fc 836 }
a7813a04 837 }
1a4d82fc 838
a7813a04
XL
839 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
840 r.map_err(|ioerr| {
841 io::Error::new(io::ErrorKind::Other,
cc61c64b 842 format!("graphviz::render failed: {}", ioerr))
a7813a04
XL
843 })
844 }
845}
846
ff7c6d11 847pub fn fold_crate(sess: &Session, krate: ast::Crate, ppm: PpMode) -> ast::Crate {
a7813a04 848 if let PpmSource(PpmEveryBodyLoops) = ppm {
ff7c6d11 849 let mut fold = ReplaceBodyWithLoop::new(sess);
a7813a04 850 fold.fold_crate(krate)
1a4d82fc 851 } else {
a7813a04
XL
852 krate
853 }
854}
1a4d82fc 855
ff7c6d11 856fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, FileName) {
1a4d82fc 857 let src_name = driver::source_name(input);
92a42be0 858 let src = sess.codemap()
c30ab7b3
SL
859 .get_filemap(&src_name)
860 .unwrap()
861 .src
862 .as_ref()
863 .unwrap()
864 .as_bytes()
865 .to_vec();
a7813a04
XL
866 (src, src_name)
867}
868
869fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
870 match ofile {
871 None => print!("{}", String::from_utf8(out).unwrap()),
872 Some(p) => {
873 match File::create(p) {
874 Ok(mut w) => w.write_all(&out).unwrap(),
875 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
876 }
877 }
878 }
879}
1a4d82fc 880
a7813a04
XL
881pub fn print_after_parsing(sess: &Session,
882 input: &Input,
883 krate: &ast::Crate,
884 ppm: PpMode,
885 ofile: Option<&Path>) {
a7813a04
XL
886 let (src, src_name) = get_source(input, sess);
887
888 let mut rdr = &*src;
889 let mut out = Vec::new();
890
891 if let PpmSource(s) = ppm {
892 // Silently ignores an identified node.
893 let out: &mut Write = &mut out;
041b39d2 894 s.call_with_pp_support(sess, None, move |annotation| {
c30ab7b3
SL
895 debug!("pretty printing source code {:?}", s);
896 let sess = annotation.sess();
897 pprust::print_crate(sess.codemap(),
32a655c1 898 &sess.parse_sess,
c30ab7b3 899 krate,
ff7c6d11 900 src_name,
c30ab7b3 901 &mut rdr,
041b39d2 902 box out,
c30ab7b3
SL
903 annotation.pp_ann(),
904 false)
905 })
906 .unwrap()
a7813a04
XL
907 } else {
908 unreachable!();
909 };
910
911 write_output(out, ofile);
912}
913
914pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
ea8adc8c 915 cstore: &'tcx CrateStore,
32a655c1 916 hir_map: &hir_map::Map<'tcx>,
8bb4bdeb 917 analysis: &ty::CrateAnalysis,
a7813a04
XL
918 resolutions: &Resolutions,
919 input: &Input,
920 krate: &ast::Crate,
921 crate_name: &str,
922 ppm: PpMode,
ff7c6d11 923 arenas: &'tcx AllArenas<'tcx>,
ea8adc8c 924 output_filenames: &OutputFilenames,
a7813a04
XL
925 opt_uii: Option<UserIdentifiedItem>,
926 ofile: Option<&Path>) {
a7813a04 927 if ppm.needs_analysis() {
c30ab7b3 928 print_with_analysis(sess,
ea8adc8c 929 cstore,
32a655c1 930 hir_map,
c30ab7b3
SL
931 analysis,
932 resolutions,
933 crate_name,
934 arenas,
ea8adc8c 935 output_filenames,
c30ab7b3
SL
936 ppm,
937 opt_uii,
938 ofile);
a7813a04
XL
939 return;
940 }
941
942 let (src, src_name) = get_source(input, sess);
943
944 let mut rdr = &src[..];
c34b1796 945 let mut out = Vec::new();
1a4d82fc
JJ
946
947 match (ppm, opt_uii) {
c30ab7b3
SL
948 (PpmSource(s), _) => {
949 // Silently ignores an identified node.
950 let out: &mut Write = &mut out;
041b39d2 951 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
c30ab7b3
SL
952 debug!("pretty printing source code {:?}", s);
953 let sess = annotation.sess();
954 pprust::print_crate(sess.codemap(),
32a655c1 955 &sess.parse_sess,
c30ab7b3 956 krate,
ff7c6d11 957 src_name,
c30ab7b3 958 &mut rdr,
041b39d2 959 box out,
c30ab7b3
SL
960 annotation.pp_ann(),
961 true)
962 })
963 }
1a4d82fc 964
c30ab7b3
SL
965 (PpmHir(s), None) => {
966 let out: &mut Write = &mut out;
967 s.call_with_pp_support_hir(sess,
ea8adc8c 968 cstore,
32a655c1 969 hir_map,
c30ab7b3
SL
970 analysis,
971 resolutions,
972 arenas,
ea8adc8c 973 output_filenames,
c30ab7b3 974 crate_name,
041b39d2 975 move |annotation, krate| {
c30ab7b3
SL
976 debug!("pretty printing source code {:?}", s);
977 let sess = annotation.sess();
978 pprust_hir::print_crate(sess.codemap(),
32a655c1 979 &sess.parse_sess,
c30ab7b3 980 krate,
ff7c6d11 981 src_name,
c30ab7b3 982 &mut rdr,
041b39d2 983 box out,
c30ab7b3
SL
984 annotation.pp_ann(),
985 true)
986 })
987 }
e9174d1e 988
ff7c6d11
XL
989 (PpmHirTree(s), None) => {
990 let out: &mut Write = &mut out;
991 s.call_with_pp_support_hir(sess,
992 cstore,
993 hir_map,
994 analysis,
995 resolutions,
996 arenas,
997 output_filenames,
998 crate_name,
999 move |_annotation, krate| {
1000 debug!("pretty printing source code {:?}", s);
1001 write!(out, "{:#?}", krate)
1002 })
1003 }
1004
c30ab7b3
SL
1005 (PpmHir(s), Some(uii)) => {
1006 let out: &mut Write = &mut out;
1007 s.call_with_pp_support_hir(sess,
ea8adc8c 1008 cstore,
32a655c1 1009 hir_map,
c30ab7b3
SL
1010 analysis,
1011 resolutions,
1012 arenas,
ea8adc8c 1013 output_filenames,
c30ab7b3 1014 crate_name,
041b39d2 1015 move |annotation, _| {
c30ab7b3
SL
1016 debug!("pretty printing source code {:?}", s);
1017 let sess = annotation.sess();
2c00a5a8 1018 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
c30ab7b3 1019 let mut pp_state = pprust_hir::State::new_from_input(sess.codemap(),
32a655c1 1020 &sess.parse_sess,
ff7c6d11 1021 src_name,
c30ab7b3
SL
1022 &mut rdr,
1023 box out,
1024 annotation.pp_ann(),
32a655c1
SL
1025 true);
1026 for node_id in uii.all_matching_node_ids(hir_map) {
1027 let node = hir_map.get(node_id);
1028 pp_state.print_node(node)?;
041b39d2 1029 pp_state.s.space()?;
c30ab7b3 1030 let path = annotation.node_path(node_id)
2c00a5a8 1031 .expect("-Z unpretty missing node paths");
c30ab7b3 1032 pp_state.synth_comment(path)?;
041b39d2 1033 pp_state.s.hardbreak()?;
c30ab7b3 1034 }
041b39d2 1035 pp_state.s.eof()
c30ab7b3
SL
1036 })
1037 }
ff7c6d11
XL
1038
1039 (PpmHirTree(s), Some(uii)) => {
1040 let out: &mut Write = &mut out;
1041 s.call_with_pp_support_hir(sess,
1042 cstore,
1043 hir_map,
1044 analysis,
1045 resolutions,
1046 arenas,
1047 output_filenames,
1048 crate_name,
1049 move |_annotation, _krate| {
1050 debug!("pretty printing source code {:?}", s);
1051 for node_id in uii.all_matching_node_ids(hir_map) {
1052 let node = hir_map.get(node_id);
1053 write!(out, "{:#?}", node)?;
1054 }
1055 Ok(())
1056 })
1057 }
1058
c30ab7b3
SL
1059 _ => unreachable!(),
1060 }
1061 .unwrap();
a7813a04
XL
1062
1063 write_output(out, ofile);
1064}
1065
1066// In an ideal world, this would be a public function called by the driver after
1067// analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
1068// with a different callback than the standard driver, so that isn't easy.
1069// Instead, we call that function ourselves.
1070fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
ea8adc8c 1071 cstore: &'a CrateStore,
32a655c1 1072 hir_map: &hir_map::Map<'tcx>,
8bb4bdeb 1073 analysis: &ty::CrateAnalysis,
a7813a04
XL
1074 resolutions: &Resolutions,
1075 crate_name: &str,
ff7c6d11 1076 arenas: &'tcx AllArenas<'tcx>,
ea8adc8c 1077 output_filenames: &OutputFilenames,
a7813a04
XL
1078 ppm: PpMode,
1079 uii: Option<UserIdentifiedItem>,
1080 ofile: Option<&Path>) {
1081 let nodeid = if let Some(uii) = uii {
1082 debug!("pretty printing for {:?}", uii);
2c00a5a8 1083 Some(uii.to_one_node_id("-Z unpretty", sess, &hir_map))
a7813a04
XL
1084 } else {
1085 debug!("pretty printing for whole crate");
1086 None
1087 };
1a4d82fc 1088
a7813a04
XL
1089 let mut out = Vec::new();
1090
abe05a73 1091 let control = &driver::CompileController::basic();
2c00a5a8
XL
1092 let trans = ::get_trans(sess);
1093 abort_on_err(driver::phase_3_run_analysis_passes(&*trans,
1094 control,
abe05a73 1095 sess,
ea8adc8c 1096 cstore,
32a655c1 1097 hir_map.clone(),
a7813a04
XL
1098 analysis.clone(),
1099 resolutions.clone(),
1100 arenas,
1101 crate_name,
ea8adc8c 1102 output_filenames,
c30ab7b3 1103 |tcx, _, _, _| {
a7813a04
XL
1104 match ppm {
1105 PpmMir | PpmMirCFG => {
c30ab7b3 1106 if let Some(nodeid) = nodeid {
32a655c1 1107 let def_id = tcx.hir.local_def_id(nodeid);
c30ab7b3 1108 match ppm {
7cac9316
XL
1109 PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1110 PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
c30ab7b3
SL
1111 _ => unreachable!(),
1112 }?;
1113 } else {
1114 match ppm {
7cac9316
XL
1115 PpmMir => write_mir_pretty(tcx, None, &mut out),
1116 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
c30ab7b3
SL
1117 _ => unreachable!(),
1118 }?;
7453a54e
SL
1119 }
1120 Ok(())
a7813a04
XL
1121 }
1122 PpmFlowGraph(mode) => {
c30ab7b3
SL
1123 let nodeid =
1124 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1125 suffix (b::c::d)");
32a655c1 1126 let node = tcx.hir.find(nodeid).unwrap_or_else(|| {
a7813a04
XL
1127 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1128 });
1a4d82fc 1129
32a655c1 1130 match blocks::Code::from_node(&tcx.hir, nodeid) {
a7813a04
XL
1131 Some(code) => {
1132 let variants = gather_flowgraph_variants(tcx.sess);
1a4d82fc 1133
a7813a04 1134 let out: &mut Write = &mut out;
1a4d82fc 1135
c30ab7b3 1136 print_flowgraph(variants, tcx, code, mode, out)
a7813a04
XL
1137 }
1138 None => {
c30ab7b3
SL
1139 let message = format!("--pretty=flowgraph needs block, fn, or method; \
1140 got {:?}",
a7813a04
XL
1141 node);
1142
32a655c1 1143 tcx.sess.span_fatal(tcx.hir.span(nodeid), &message)
1a4d82fc
JJ
1144 }
1145 }
1146 }
a7813a04 1147 _ => unreachable!(),
1a4d82fc 1148 }
c30ab7b3
SL
1149 }),
1150 sess)
1151 .unwrap();
c34b1796 1152
a7813a04 1153 write_output(out, ofile);
1a4d82fc 1154}