]> git.proxmox.com Git - rustc.git/blame - src/librustc_driver/pretty.rs
New upstream version 1.12.0+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
a7813a04
XL
18use abort_on_err;
19use driver::{self, Resolutions};
1a4d82fc 20
54a0048b
SL
21use rustc::ty::{self, TyCtxt};
22use rustc::cfg;
23use rustc::cfg::graphviz::LabelledCFG;
a7813a04 24use rustc::dep_graph::DepGraph;
1a4d82fc
JJ
25use rustc::session::Session;
26use rustc::session::config::Input;
1a4d82fc
JJ
27use rustc_borrowck as borrowck;
28use rustc_borrowck::graphviz as borrowck_dot;
29
7453a54e 30use rustc_mir::pretty::write_mir_pretty;
54a0048b 31use rustc_mir::graphviz::write_mir_graphviz;
7453a54e
SL
32
33use syntax::ast::{self, BlockCheckMode};
1a4d82fc
JJ
34use syntax::fold::{self, Folder};
35use syntax::print::{pp, pprust};
b039eaaf 36use syntax::print::pprust::PrintState;
1a4d82fc 37use syntax::ptr::P;
d9579d0f 38use syntax::util::small_vector::SmallVector;
3157f602 39use syntax_pos;
1a4d82fc
JJ
40
41use graphviz as dot;
42
c34b1796
AL
43use std::fs::File;
44use std::io::{self, Write};
54a0048b 45use std::iter;
1a4d82fc 46use std::option;
a7813a04 47use std::path::Path;
1a4d82fc
JJ
48use std::str::FromStr;
49
54a0048b
SL
50use rustc::hir::map as hir_map;
51use rustc::hir::map::{blocks, NodePrinter};
52use rustc::hir;
54a0048b
SL
53use rustc::hir::print as pprust_hir;
54
55use rustc::mir::mir_map::MirMap;
e9174d1e 56
c34b1796 57#[derive(Copy, Clone, PartialEq, Debug)]
1a4d82fc
JJ
58pub enum PpSourceMode {
59 PpmNormal,
60 PpmEveryBodyLoops,
61 PpmExpanded,
1a4d82fc
JJ
62 PpmIdentified,
63 PpmExpandedIdentified,
64 PpmExpandedHygiene,
e9174d1e 65 PpmTyped,
1a4d82fc
JJ
66}
67
c34b1796 68#[derive(Copy, Clone, PartialEq, Debug)]
85aaf69f
SL
69pub enum PpFlowGraphMode {
70 Default,
71 /// Drops the labels from the edges in the flowgraph output. This
c1a9b12d 72 /// is mostly for use in the --unpretty flowgraph run-make tests,
85aaf69f
SL
73 /// since the labels are largely uninteresting in those cases and
74 /// have become a pain to maintain.
75 UnlabelledEdges,
76}
c34b1796 77#[derive(Copy, Clone, PartialEq, Debug)]
1a4d82fc
JJ
78pub enum PpMode {
79 PpmSource(PpSourceMode),
e9174d1e 80 PpmHir(PpSourceMode),
85aaf69f 81 PpmFlowGraph(PpFlowGraphMode),
7453a54e 82 PpmMir,
54a0048b 83 PpmMirCFG,
1a4d82fc
JJ
84}
85
a7813a04
XL
86impl PpMode {
87 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
88 match *self {
89 PpmSource(PpmNormal) |
90 PpmSource(PpmEveryBodyLoops) |
91 PpmSource(PpmIdentified) => opt_uii.is_some(),
92
93 PpmSource(PpmExpanded) |
94 PpmSource(PpmExpandedIdentified) |
95 PpmSource(PpmExpandedHygiene) |
96 PpmHir(_) |
97 PpmMir |
98 PpmMirCFG |
99 PpmFlowGraph(_) => true,
100 PpmSource(PpmTyped) => panic!("invalid state"),
101 }
102 }
103
104 pub fn needs_analysis(&self) -> bool {
105 match *self {
106 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
107 _ => false,
108 }
109 }
110}
111
1a4d82fc
JJ
112pub fn parse_pretty(sess: &Session,
113 name: &str,
92a42be0
SL
114 extended: bool)
115 -> (PpMode, Option<UserIdentifiedItem>) {
c34b1796 116 let mut split = name.splitn(2, '=');
1a4d82fc
JJ
117 let first = split.next().unwrap();
118 let opt_second = split.next();
119 let first = match (first, extended) {
92a42be0
SL
120 ("normal", _) => PpmSource(PpmNormal),
121 ("identified", _) => PpmSource(PpmIdentified),
1a4d82fc 122 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
92a42be0 123 ("expanded", _) => PpmSource(PpmExpanded),
1a4d82fc
JJ
124 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
125 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
92a42be0 126 ("hir", true) => PpmHir(PpmNormal),
e9174d1e 127 ("hir,identified", true) => PpmHir(PpmIdentified),
92a42be0 128 ("hir,typed", true) => PpmHir(PpmTyped),
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`.
168 fn call_with_pp_support<'tcx, A, B, F>(&self,
b039eaaf 169 sess: &'tcx Session,
a7813a04 170 ast_map: Option<&hir_map::Map<'tcx>>,
1a4d82fc 171 payload: B,
92a42be0
SL
172 f: F)
173 -> A
174 where F: FnOnce(&PrinterSupport, B) -> A
1a4d82fc
JJ
175 {
176 match *self {
177 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
92a42be0
SL
178 let annotation = NoAnn {
179 sess: sess,
a7813a04 180 ast_map: ast_map.map(|m| m.clone()),
92a42be0 181 };
1a4d82fc
JJ
182 f(&annotation, payload)
183 }
184
185 PpmIdentified | PpmExpandedIdentified => {
92a42be0
SL
186 let annotation = IdentifiedAnnotation {
187 sess: sess,
a7813a04 188 ast_map: ast_map.map(|m| m.clone()),
92a42be0 189 };
1a4d82fc
JJ
190 f(&annotation, payload)
191 }
192 PpmExpandedHygiene => {
92a42be0
SL
193 let annotation = HygieneAnnotation {
194 sess: sess,
a7813a04 195 ast_map: ast_map.map(|m| m.clone()),
92a42be0 196 };
1a4d82fc
JJ
197 f(&annotation, payload)
198 }
e9174d1e
SL
199 _ => panic!("Should use call_with_pp_support_hir"),
200 }
201 }
202 fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
b039eaaf 203 sess: &'tcx Session,
e9174d1e 204 ast_map: &hir_map::Map<'tcx>,
a7813a04
XL
205 analysis: &ty::CrateAnalysis,
206 resolutions: &Resolutions,
e9174d1e 207 arenas: &'tcx ty::CtxtArenas<'tcx>,
b039eaaf 208 id: &str,
e9174d1e 209 payload: B,
92a42be0
SL
210 f: F)
211 -> A
212 where F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A
e9174d1e
SL
213 {
214 match *self {
215 PpmNormal => {
92a42be0
SL
216 let annotation = NoAnn {
217 sess: sess,
218 ast_map: Some(ast_map.clone()),
219 };
7453a54e 220 f(&annotation, payload, ast_map.forest.krate())
e9174d1e
SL
221 }
222
223 PpmIdentified => {
224 let annotation = IdentifiedAnnotation {
225 sess: sess,
92a42be0 226 ast_map: Some(ast_map.clone()),
e9174d1e 227 };
7453a54e 228 f(&annotation, payload, ast_map.forest.krate())
e9174d1e 229 }
1a4d82fc 230 PpmTyped => {
7453a54e 231 abort_on_err(driver::phase_3_run_analysis_passes(sess,
7453a54e 232 ast_map.clone(),
a7813a04
XL
233 analysis.clone(),
234 resolutions.clone(),
7453a54e
SL
235 arenas,
236 id,
7453a54e
SL
237 |tcx, _, _, _| {
238 let annotation = TypedAnnotation {
239 tcx: tcx,
240 };
241 let _ignore = tcx.dep_graph.in_ignore();
242 f(&annotation,
243 payload,
244 ast_map.forest.krate())
245 }), sess)
1a4d82fc 246 }
e9174d1e 247 _ => panic!("Should use call_with_pp_support"),
1a4d82fc
JJ
248 }
249 }
250}
251
252trait PrinterSupport<'ast>: pprust::PpAnn {
253 /// Provides a uniform interface for re-extracting a reference to a
254 /// `Session` from a value that now owns it.
255 fn sess<'a>(&'a self) -> &'a Session;
256
257 /// Provides a uniform interface for re-extracting a reference to an
e9174d1e
SL
258 /// `hir_map::Map` from a value that now owns it.
259 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
1a4d82fc
JJ
260
261 /// Produces the pretty-print annotation object.
262 ///
263 /// (Rust does not yet support upcasting from a trait object to
264 /// an object for one of its super-traits.)
265 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
266}
267
e9174d1e
SL
268trait HirPrinterSupport<'ast>: pprust_hir::PpAnn {
269 /// Provides a uniform interface for re-extracting a reference to a
270 /// `Session` from a value that now owns it.
271 fn sess<'a>(&'a self) -> &'a Session;
272
273 /// Provides a uniform interface for re-extracting a reference to an
274 /// `hir_map::Map` from a value that now owns it.
275 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
276
277 /// Produces the pretty-print annotation object.
278 ///
279 /// (Rust does not yet support upcasting from a trait object to
280 /// an object for one of its super-traits.)
281 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
54a0048b
SL
282
283 /// Computes an user-readable representation of a path, if possible.
284 fn node_path(&self, id: ast::NodeId) -> Option<String> {
285 self.ast_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
286 path.data.into_iter().map(|elem| {
287 elem.data.to_string()
288 }).collect::<Vec<_>>().join("::")
289 })
290 }
e9174d1e
SL
291}
292
1a4d82fc 293struct NoAnn<'ast> {
b039eaaf 294 sess: &'ast Session,
92a42be0 295 ast_map: Option<hir_map::Map<'ast>>,
1a4d82fc
JJ
296}
297
298impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
92a42be0
SL
299 fn sess<'a>(&'a self) -> &'a Session {
300 self.sess
301 }
1a4d82fc 302
e9174d1e 303 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
1a4d82fc
JJ
304 self.ast_map.as_ref()
305 }
306
92a42be0
SL
307 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
308 self
309 }
1a4d82fc
JJ
310}
311
e9174d1e 312impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> {
92a42be0
SL
313 fn sess<'a>(&'a self) -> &'a Session {
314 self.sess
315 }
e9174d1e
SL
316
317 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
318 self.ast_map.as_ref()
319 }
320
92a42be0
SL
321 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
322 self
323 }
e9174d1e
SL
324}
325
1a4d82fc 326impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
e9174d1e 327impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
1a4d82fc
JJ
328
329struct IdentifiedAnnotation<'ast> {
b039eaaf 330 sess: &'ast Session,
e9174d1e 331 ast_map: Option<hir_map::Map<'ast>>,
1a4d82fc
JJ
332}
333
334impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
92a42be0
SL
335 fn sess<'a>(&'a self) -> &'a Session {
336 self.sess
337 }
1a4d82fc 338
e9174d1e 339 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
1a4d82fc
JJ
340 self.ast_map.as_ref()
341 }
342
92a42be0
SL
343 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
344 self
345 }
1a4d82fc
JJ
346}
347
348impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
92a42be0 349 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc
JJ
350 match node {
351 pprust::NodeExpr(_) => s.popen(),
92a42be0 352 _ => Ok(()),
1a4d82fc
JJ
353 }
354 }
92a42be0 355 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc
JJ
356 match node {
357 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
358
359 pprust::NodeItem(item) => {
54a0048b 360 pp::space(&mut s.s)?;
1a4d82fc
JJ
361 s.synth_comment(item.id.to_string())
362 }
c34b1796 363 pprust::NodeSubItem(id) => {
54a0048b 364 pp::space(&mut s.s)?;
c34b1796
AL
365 s.synth_comment(id.to_string())
366 }
1a4d82fc 367 pprust::NodeBlock(blk) => {
54a0048b 368 pp::space(&mut s.s)?;
1a4d82fc
JJ
369 s.synth_comment(format!("block {}", blk.id))
370 }
371 pprust::NodeExpr(expr) => {
54a0048b
SL
372 pp::space(&mut s.s)?;
373 s.synth_comment(expr.id.to_string())?;
1a4d82fc
JJ
374 s.pclose()
375 }
376 pprust::NodePat(pat) => {
54a0048b 377 pp::space(&mut s.s)?;
1a4d82fc
JJ
378 s.synth_comment(format!("pat {}", pat.id))
379 }
380 }
381 }
382}
383
e9174d1e 384impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
92a42be0
SL
385 fn sess<'a>(&'a self) -> &'a Session {
386 self.sess
387 }
e9174d1e
SL
388
389 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
390 self.ast_map.as_ref()
391 }
392
92a42be0
SL
393 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
394 self
395 }
e9174d1e
SL
396}
397
398impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
92a42be0 399 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
e9174d1e
SL
400 match node {
401 pprust_hir::NodeExpr(_) => s.popen(),
92a42be0 402 _ => Ok(()),
e9174d1e
SL
403 }
404 }
92a42be0 405 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
e9174d1e 406 match node {
b039eaaf 407 pprust_hir::NodeName(_) => Ok(()),
e9174d1e 408 pprust_hir::NodeItem(item) => {
54a0048b 409 pp::space(&mut s.s)?;
e9174d1e
SL
410 s.synth_comment(item.id.to_string())
411 }
412 pprust_hir::NodeSubItem(id) => {
54a0048b 413 pp::space(&mut s.s)?;
e9174d1e
SL
414 s.synth_comment(id.to_string())
415 }
416 pprust_hir::NodeBlock(blk) => {
54a0048b 417 pp::space(&mut s.s)?;
e9174d1e
SL
418 s.synth_comment(format!("block {}", blk.id))
419 }
420 pprust_hir::NodeExpr(expr) => {
54a0048b
SL
421 pp::space(&mut s.s)?;
422 s.synth_comment(expr.id.to_string())?;
e9174d1e
SL
423 s.pclose()
424 }
425 pprust_hir::NodePat(pat) => {
54a0048b 426 pp::space(&mut s.s)?;
e9174d1e
SL
427 s.synth_comment(format!("pat {}", pat.id))
428 }
429 }
430 }
431}
432
1a4d82fc 433struct HygieneAnnotation<'ast> {
b039eaaf 434 sess: &'ast Session,
e9174d1e 435 ast_map: Option<hir_map::Map<'ast>>,
1a4d82fc
JJ
436}
437
438impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
92a42be0
SL
439 fn sess<'a>(&'a self) -> &'a Session {
440 self.sess
441 }
1a4d82fc 442
e9174d1e 443 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
1a4d82fc
JJ
444 self.ast_map.as_ref()
445 }
446
92a42be0
SL
447 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
448 self
449 }
1a4d82fc
JJ
450}
451
452impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
92a42be0 453 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
1a4d82fc
JJ
454 match node {
455 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
54a0048b 456 pp::space(&mut s.s)?;
1a4d82fc
JJ
457 // FIXME #16420: this doesn't display the connections
458 // between syntax contexts
5bcae85e 459 s.synth_comment(format!("{}{:?}", nm, ctxt))
1a4d82fc
JJ
460 }
461 pprust::NodeName(&ast::Name(nm)) => {
54a0048b 462 pp::space(&mut s.s)?;
1a4d82fc
JJ
463 s.synth_comment(nm.to_string())
464 }
92a42be0 465 _ => Ok(()),
1a4d82fc
JJ
466 }
467 }
468}
469
470
62682a34 471struct TypedAnnotation<'a, 'tcx: 'a> {
a7813a04 472 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1a4d82fc
JJ
473}
474
e9174d1e 475impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
92a42be0
SL
476 fn sess<'a>(&'a self) -> &'a Session {
477 &self.tcx.sess
478 }
1a4d82fc 479
e9174d1e 480 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
62682a34 481 Some(&self.tcx.map)
1a4d82fc
JJ
482 }
483
92a42be0
SL
484 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
485 self
486 }
54a0048b
SL
487
488 fn node_path(&self, id: ast::NodeId) -> Option<String> {
489 Some(self.tcx.node_path_str(id))
490 }
1a4d82fc
JJ
491}
492
e9174d1e 493impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
92a42be0 494 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
1a4d82fc 495 match node {
e9174d1e 496 pprust_hir::NodeExpr(_) => s.popen(),
92a42be0 497 _ => Ok(()),
1a4d82fc
JJ
498 }
499 }
92a42be0 500 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
1a4d82fc 501 match node {
e9174d1e 502 pprust_hir::NodeExpr(expr) => {
54a0048b
SL
503 pp::space(&mut s.s)?;
504 pp::word(&mut s.s, "as")?;
505 pp::space(&mut s.s)?;
506 pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())?;
1a4d82fc
JJ
507 s.pclose()
508 }
92a42be0 509 _ => Ok(()),
1a4d82fc
JJ
510 }
511 }
512}
513
514fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
515 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
516 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
517 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
518 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
519 let mut variants = Vec::new();
520 if print_all || print_loans {
521 variants.push(borrowck_dot::Loans);
522 }
523 if print_all || print_moves {
524 variants.push(borrowck_dot::Moves);
525 }
526 if print_all || print_assigns {
527 variants.push(borrowck_dot::Assigns);
528 }
529 variants
530}
531
85aaf69f 532#[derive(Clone, Debug)]
1a4d82fc
JJ
533pub enum UserIdentifiedItem {
534 ItemViaNode(ast::NodeId),
535 ItemViaPath(Vec<String>),
536}
537
538impl FromStr for UserIdentifiedItem {
85aaf69f
SL
539 type Err = ();
540 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
92a42be0
SL
541 Ok(s.parse()
542 .map(ItemViaNode)
543 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
1a4d82fc
JJ
544 }
545}
546
547enum NodesMatchingUII<'a, 'ast: 'a> {
548 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
e9174d1e 549 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'ast>),
1a4d82fc
JJ
550}
551
552impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
553 type Item = ast::NodeId;
554
555 fn next(&mut self) -> Option<ast::NodeId> {
556 match self {
557 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
558 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
559 }
560 }
561}
562
563impl UserIdentifiedItem {
564 fn reconstructed_input(&self) -> String {
565 match *self {
566 ItemViaNode(node_id) => node_id.to_string(),
c1a9b12d 567 ItemViaPath(ref parts) => parts.join("::"),
1a4d82fc
JJ
568 }
569 }
570
92a42be0
SL
571 fn all_matching_node_ids<'a, 'ast>(&'a self,
572 map: &'a hir_map::Map<'ast>)
1a4d82fc
JJ
573 -> NodesMatchingUII<'a, 'ast> {
574 match *self {
92a42be0
SL
575 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
576 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
1a4d82fc
JJ
577 }
578 }
579
e9174d1e 580 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
85aaf69f 581 let fail_because = |is_wrong_because| -> ast::NodeId {
92a42be0
SL
582 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
583 {}, which {}",
584 user_option,
585 self.reconstructed_input(),
586 is_wrong_because);
85aaf69f 587 sess.fatal(&message[..])
1a4d82fc
JJ
588 };
589
590 let mut saw_node = ast::DUMMY_NODE_ID;
85aaf69f 591 let mut seen = 0;
1a4d82fc
JJ
592 for node in self.all_matching_node_ids(map) {
593 saw_node = node;
594 seen += 1;
595 if seen > 1 {
596 fail_because("does not resolve uniquely");
597 }
598 }
599 if seen == 0 {
600 fail_because("does not resolve to any item");
601 }
602
603 assert!(seen == 1);
604 return saw_node;
605 }
606}
607
1a4d82fc
JJ
608struct ReplaceBodyWithLoop {
609 within_static_or_const: bool,
610}
611
612impl ReplaceBodyWithLoop {
613 fn new() -> ReplaceBodyWithLoop {
614 ReplaceBodyWithLoop { within_static_or_const: false }
615 }
616}
617
618impl fold::Folder for ReplaceBodyWithLoop {
7453a54e 619 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
1a4d82fc 620 match i {
7453a54e 621 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
1a4d82fc 622 self.within_static_or_const = true;
7453a54e 623 let ret = fold::noop_fold_item_kind(i, self);
1a4d82fc
JJ
624 self.within_static_or_const = false;
625 return ret;
626 }
627 _ => {
7453a54e 628 fold::noop_fold_item_kind(i, self)
1a4d82fc
JJ
629 }
630 }
631 }
632
7453a54e 633 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
d9579d0f 634 match i.node {
7453a54e 635 ast::TraitItemKind::Const(..) => {
d9579d0f
AL
636 self.within_static_or_const = true;
637 let ret = fold::noop_fold_trait_item(i, self);
638 self.within_static_or_const = false;
639 return ret;
640 }
641 _ => fold::noop_fold_trait_item(i, self),
642 }
643 }
644
7453a54e 645 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
d9579d0f 646 match i.node {
92a42be0 647 ast::ImplItemKind::Const(..) => {
d9579d0f
AL
648 self.within_static_or_const = true;
649 let ret = fold::noop_fold_impl_item(i, self);
650 self.within_static_or_const = false;
651 return ret;
652 }
653 _ => fold::noop_fold_impl_item(i, self),
654 }
655 }
1a4d82fc
JJ
656
657 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
92a42be0 658 fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
1a4d82fc 659 P(ast::Block {
3157f602
XL
660 stmts: e.map(|e| ast::Stmt {
661 id: ast::DUMMY_NODE_ID,
662 span: e.span,
663 node: ast::StmtKind::Expr(e),
664 }).into_iter().collect(),
92a42be0
SL
665 rules: rules,
666 id: ast::DUMMY_NODE_ID,
3157f602 667 span: syntax_pos::DUMMY_SP,
1a4d82fc
JJ
668 })
669 }
670
671 if !self.within_static_or_const {
672
7453a54e 673 let empty_block = expr_to_block(BlockCheckMode::Default, None);
1a4d82fc 674 let loop_expr = P(ast::Expr {
7453a54e 675 node: ast::ExprKind::Loop(empty_block, None),
92a42be0 676 id: ast::DUMMY_NODE_ID,
3157f602
XL
677 span: syntax_pos::DUMMY_SP,
678 attrs: ast::ThinVec::new(),
1a4d82fc
JJ
679 });
680
681 expr_to_block(b.rules, Some(loop_expr))
682
683 } else {
684 fold::noop_fold_block(b, self)
685 }
686 }
687
688 // in general the pretty printer processes unexpanded code, so
689 // we override the default `fold_mac` method which panics.
690 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
691 fold::noop_fold_mac(mac, self)
692 }
693}
694
a7813a04
XL
695fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
696 tcx: TyCtxt<'a, 'tcx, 'tcx>,
697 mir_map: Option<&MirMap<'tcx>>,
698 code: blocks::Code,
699 mode: PpFlowGraphMode,
700 mut out: W)
701 -> io::Result<()> {
702 let cfg = match code {
703 blocks::BlockCode(block) => cfg::CFG::new(tcx, &block),
704 blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &fn_like.body()),
705 };
706 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
707 let lcfg = LabelledCFG {
708 ast_map: &tcx.map,
709 cfg: &cfg,
710 name: format!("node_{}", code.id()),
711 labelled_edges: labelled_edges,
1a4d82fc
JJ
712 };
713
a7813a04
XL
714 match code {
715 _ if variants.is_empty() => {
716 let r = dot::render(&lcfg, &mut out);
717 return expand_err_details(r);
718 }
719 blocks::BlockCode(_) => {
720 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
721 fn-like node id.");
722 return Ok(());
723 }
724 blocks::FnLikeCode(fn_like) => {
725 let (bccx, analysis_data) =
726 borrowck::build_borrowck_dataflow_data_for_fn(tcx,
727 mir_map,
728 fn_like.to_fn_parts(),
729 &cfg);
1a4d82fc 730
a7813a04
XL
731 let lcfg = borrowck_dot::DataflowLabeller {
732 inner: lcfg,
733 variants: variants,
734 borrowck_ctxt: &bccx,
735 analysis_data: &analysis_data,
736 };
737 let r = dot::render(&lcfg, &mut out);
738 return expand_err_details(r);
1a4d82fc 739 }
a7813a04 740 }
1a4d82fc 741
a7813a04
XL
742 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
743 r.map_err(|ioerr| {
744 io::Error::new(io::ErrorKind::Other,
745 &format!("graphviz::render failed: {}", ioerr)[..])
746 })
747 }
748}
749
750pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate {
751 if let PpmSource(PpmEveryBodyLoops) = ppm {
752 let mut fold = ReplaceBodyWithLoop::new();
753 fold.fold_crate(krate)
1a4d82fc 754 } else {
a7813a04
XL
755 krate
756 }
757}
1a4d82fc 758
a7813a04 759fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) {
1a4d82fc 760 let src_name = driver::source_name(input);
92a42be0 761 let src = sess.codemap()
a7813a04 762 .get_filemap(&src_name)
3157f602 763 .unwrap()
92a42be0
SL
764 .src
765 .as_ref()
766 .unwrap()
767 .as_bytes()
768 .to_vec();
a7813a04
XL
769 (src, src_name)
770}
771
772fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
773 match ofile {
774 None => print!("{}", String::from_utf8(out).unwrap()),
775 Some(p) => {
776 match File::create(p) {
777 Ok(mut w) => w.write_all(&out).unwrap(),
778 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
779 }
780 }
781 }
782}
1a4d82fc 783
a7813a04
XL
784pub fn print_after_parsing(sess: &Session,
785 input: &Input,
786 krate: &ast::Crate,
787 ppm: PpMode,
788 ofile: Option<&Path>) {
789 let dep_graph = DepGraph::new(false);
790 let _ignore = dep_graph.in_ignore();
791
792 let (src, src_name) = get_source(input, sess);
793
794 let mut rdr = &*src;
795 let mut out = Vec::new();
796
797 if let PpmSource(s) = ppm {
798 // Silently ignores an identified node.
799 let out: &mut Write = &mut out;
800 s.call_with_pp_support(sess, None, box out, |annotation, out| {
801 debug!("pretty printing source code {:?}", s);
802 let sess = annotation.sess();
803 pprust::print_crate(sess.codemap(),
804 sess.diagnostic(),
805 krate,
806 src_name.to_string(),
807 &mut rdr,
808 out,
809 annotation.pp_ann(),
810 false)
811 }).unwrap()
812 } else {
813 unreachable!();
814 };
815
816 write_output(out, ofile);
817}
818
819pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
820 ast_map: &hir_map::Map<'tcx>,
821 analysis: &ty::CrateAnalysis,
822 resolutions: &Resolutions,
823 input: &Input,
824 krate: &ast::Crate,
825 crate_name: &str,
826 ppm: PpMode,
827 arenas: &'tcx ty::CtxtArenas<'tcx>,
828 opt_uii: Option<UserIdentifiedItem>,
829 ofile: Option<&Path>) {
830 let dep_graph = DepGraph::new(false);
831 let _ignore = dep_graph.in_ignore();
832
833 if ppm.needs_analysis() {
834 print_with_analysis(sess, ast_map, analysis, resolutions,
835 crate_name, arenas, ppm, opt_uii, ofile);
836 return;
837 }
838
839 let (src, src_name) = get_source(input, sess);
840
841 let mut rdr = &src[..];
c34b1796 842 let mut out = Vec::new();
1a4d82fc
JJ
843
844 match (ppm, opt_uii) {
e9174d1e
SL
845 (PpmSource(s), _) => {
846 // Silently ignores an identified node.
c34b1796 847 let out: &mut Write = &mut out;
a7813a04 848 s.call_with_pp_support(sess, Some(ast_map), box out, |annotation, out| {
92a42be0
SL
849 debug!("pretty printing source code {:?}", s);
850 let sess = annotation.sess();
851 pprust::print_crate(sess.codemap(),
852 sess.diagnostic(),
a7813a04 853 krate,
92a42be0
SL
854 src_name.to_string(),
855 &mut rdr,
856 out,
857 annotation.pp_ann(),
a7813a04 858 true)
c34b1796
AL
859 })
860 }
1a4d82fc 861
e9174d1e 862 (PpmHir(s), None) => {
c34b1796 863 let out: &mut Write = &mut out;
a7813a04
XL
864 s.call_with_pp_support_hir(sess,
865 ast_map,
866 analysis,
867 resolutions,
868 arenas,
869 crate_name,
92a42be0
SL
870 box out,
871 |annotation, out, krate| {
872 debug!("pretty printing source code {:?}", s);
873 let sess = annotation.sess();
874 pprust_hir::print_crate(sess.codemap(),
875 sess.diagnostic(),
876 krate,
877 src_name.to_string(),
878 &mut rdr,
879 out,
880 annotation.pp_ann(),
a7813a04 881 true)
92a42be0 882 })
e9174d1e
SL
883 }
884
885 (PpmHir(s), Some(uii)) => {
886 let out: &mut Write = &mut out;
a7813a04
XL
887 s.call_with_pp_support_hir(sess,
888 ast_map,
889 analysis,
890 resolutions,
891 arenas,
892 crate_name,
e9174d1e
SL
893 (out,uii),
894 |annotation, (out,uii), _| {
895 debug!("pretty printing source code {:?}", s);
896 let sess = annotation.sess();
54a0048b 897 let ast_map = annotation.ast_map().expect("--unpretty missing HIR map");
e9174d1e
SL
898 let mut pp_state =
899 pprust_hir::State::new_from_input(sess.codemap(),
1a4d82fc
JJ
900 sess.diagnostic(),
901 src_name.to_string(),
902 &mut rdr,
c34b1796 903 box out,
1a4d82fc 904 annotation.pp_ann(),
92a42be0
SL
905 true,
906 Some(ast_map.krate()));
e9174d1e
SL
907 for node_id in uii.all_matching_node_ids(ast_map) {
908 let node = ast_map.get(node_id);
54a0048b
SL
909 pp_state.print_node(&node)?;
910 pp::space(&mut pp_state.s)?;
911 let path = annotation.node_path(node_id)
912 .expect("--unpretty missing node paths");
913 pp_state.synth_comment(path)?;
914 pp::hardbreak(&mut pp_state.s)?;
e9174d1e
SL
915 }
916 pp::eof(&mut pp_state.s)
917 })
a7813a04
XL
918 }
919 _ => unreachable!(),
920 }.unwrap();
921
922 write_output(out, ofile);
923}
924
925// In an ideal world, this would be a public function called by the driver after
926// analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
927// with a different callback than the standard driver, so that isn't easy.
928// Instead, we call that function ourselves.
929fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
930 ast_map: &hir_map::Map<'tcx>,
931 analysis: &ty::CrateAnalysis,
932 resolutions: &Resolutions,
933 crate_name: &str,
934 arenas: &'tcx ty::CtxtArenas<'tcx>,
935 ppm: PpMode,
936 uii: Option<UserIdentifiedItem>,
937 ofile: Option<&Path>) {
938 let nodeid = if let Some(uii) = uii {
939 debug!("pretty printing for {:?}", uii);
940 Some(uii.to_one_node_id("--unpretty", sess, &ast_map))
941 } else {
942 debug!("pretty printing for whole crate");
943 None
944 };
1a4d82fc 945
a7813a04
XL
946 let mut out = Vec::new();
947
948 abort_on_err(driver::phase_3_run_analysis_passes(sess,
949 ast_map.clone(),
950 analysis.clone(),
951 resolutions.clone(),
952 arenas,
953 crate_name,
954 |tcx, mir_map, _, _| {
955 match ppm {
956 PpmMir | PpmMirCFG => {
7453a54e 957 if let Some(mir_map) = mir_map {
54a0048b 958 if let Some(nodeid) = nodeid {
5bcae85e 959 let def_id = tcx.map.local_def_id(nodeid);
a7813a04 960 match ppm {
5bcae85e 961 PpmMir => write_mir_pretty(tcx, iter::once(def_id), &mir_map, &mut out),
a7813a04 962 PpmMirCFG => {
5bcae85e 963 write_mir_graphviz(tcx, iter::once(def_id), &mir_map, &mut out)
a7813a04
XL
964 }
965 _ => unreachable!(),
54a0048b
SL
966 }?;
967 } else {
a7813a04 968 match ppm {
5bcae85e
SL
969 PpmMir => write_mir_pretty(tcx,
970 mir_map.map.keys().into_iter(),
971 &mir_map,
972 &mut out),
973 PpmMirCFG => write_mir_graphviz(tcx,
974 mir_map.map.keys().into_iter(),
975 &mir_map,
976 &mut out),
a7813a04 977 _ => unreachable!(),
54a0048b 978 }?;
7453a54e
SL
979 }
980 }
981 Ok(())
a7813a04
XL
982 }
983 PpmFlowGraph(mode) => {
984 let nodeid = nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or \
985 unique path suffix (b::c::d)");
986 let node = tcx.map.find(nodeid).unwrap_or_else(|| {
987 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
988 });
1a4d82fc 989
a7813a04
XL
990 let code = blocks::Code::from_node(node);
991 match code {
992 Some(code) => {
993 let variants = gather_flowgraph_variants(tcx.sess);
1a4d82fc 994
a7813a04 995 let out: &mut Write = &mut out;
1a4d82fc 996
7453a54e
SL
997 print_flowgraph(variants,
998 tcx,
54a0048b 999 mir_map.as_ref(),
7453a54e
SL
1000 code,
1001 mode,
1002 out)
a7813a04
XL
1003 }
1004 None => {
1005 let message = format!("--pretty=flowgraph needs block, fn, or method; got \
1006 {:?}",
1007 node);
1008
1009 // Point to what was found, if there's an accessible span.
1010 match tcx.map.opt_span(nodeid) {
1011 Some(sp) => tcx.sess.span_fatal(sp, &message),
1012 None => tcx.sess.fatal(&message),
1013 }
1a4d82fc
JJ
1014 }
1015 }
1016 }
a7813a04 1017 _ => unreachable!(),
1a4d82fc 1018 }
a7813a04 1019 }), sess).unwrap();
c34b1796 1020
a7813a04 1021 write_output(out, ofile);
1a4d82fc 1022}