]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / librustc_driver / 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 //! The various pretty print routines.
12
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
17
18 use rustc_trans::back::link;
19
20 use driver;
21
22 use rustc::middle::ty;
23 use rustc::middle::borrowck::{mod, FnPartsWithCFG};
24 use rustc::middle::borrowck::graphviz as borrowck_dot;
25 use rustc::middle::cfg;
26 use rustc::middle::cfg::graphviz::LabelledCFG;
27 use rustc::session::Session;
28 use rustc::session::config::{mod, Input};
29 use rustc::util::ppaux;
30
31 use syntax::ast;
32 use syntax::ast_map::{mod, blocks, NodePrinter};
33 use syntax::print::{pp, pprust};
34
35 use graphviz as dot;
36
37 use std::io::{mod, MemReader};
38 use std::option;
39 use std::str::FromStr;
40 use arena::TypedArena;
41
42 #[deriving(PartialEq, Show)]
43 pub enum PpSourceMode {
44     PpmNormal,
45     PpmExpanded,
46     PpmTyped,
47     PpmIdentified,
48     PpmExpandedIdentified,
49     PpmExpandedHygiene,
50 }
51
52 #[deriving(PartialEq, Show)]
53 pub enum PpMode {
54     PpmSource(PpSourceMode),
55     PpmFlowGraph,
56 }
57
58 pub fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<UserIdentifiedItem>) {
59     let mut split = name.splitn(1, '=');
60     let first = split.next().unwrap();
61     let opt_second = split.next();
62     let first = match first {
63         "normal"       => PpmSource(PpmNormal),
64         "expanded"     => PpmSource(PpmExpanded),
65         "typed"        => PpmSource(PpmTyped),
66         "expanded,identified" => PpmSource(PpmExpandedIdentified),
67         "expanded,hygiene" => PpmSource(PpmExpandedHygiene),
68         "identified"   => PpmSource(PpmIdentified),
69         "flowgraph"    => PpmFlowGraph,
70         _ => {
71             sess.fatal(format!(
72                 "argument to `pretty` must be one of `normal`, \
73                  `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
74                  or `expanded,identified`; got {}", name).as_slice());
75         }
76     };
77     let opt_second = opt_second.and_then::<UserIdentifiedItem>(from_str);
78     (first, opt_second)
79 }
80
81
82
83 // This slightly awkward construction is to allow for each PpMode to
84 // choose whether it needs to do analyses (which can consume the
85 // Session) and then pass through the session (now attached to the
86 // analysis results) on to the chosen pretty-printer, along with the
87 // `&PpAnn` object.
88 //
89 // Note that since the `&PrinterSupport` is freshly constructed on each
90 // call, it would not make sense to try to attach the lifetime of `self`
91 // to the lifetime of the `&PrinterObject`.
92 //
93 // (The `use_once_payload` is working around the current lack of once
94 // functions in the compiler.)
95
96 impl PpSourceMode {
97     /// Constructs a `PrinterSupport` object and passes it to `f`.
98     fn call_with_pp_support<'tcx, A, B>(&self,
99                                         sess: Session,
100                                         ast_map: Option<ast_map::Map<'tcx>>,
101                                         type_arena: &'tcx TypedArena<ty::TyS<'tcx>>,
102                                         id: String,
103                                         payload: B,
104                                         f: |&PrinterSupport, B| -> A) -> A {
105         match *self {
106             PpmNormal | PpmExpanded => {
107                 let annotation = NoAnn { sess: sess, ast_map: ast_map };
108                 f(&annotation, payload)
109             }
110
111             PpmIdentified | PpmExpandedIdentified => {
112                 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
113                 f(&annotation, payload)
114             }
115             PpmExpandedHygiene => {
116                 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
117                 f(&annotation, payload)
118             }
119             PpmTyped => {
120                 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
121                 let analysis = driver::phase_3_run_analysis_passes(sess, ast_map,
122                                                                    type_arena, id);
123                 let annotation = TypedAnnotation { analysis: analysis };
124                 f(&annotation, payload)
125             }
126         }
127     }
128 }
129
130 trait PrinterSupport<'ast>: pprust::PpAnn {
131     /// Provides a uniform interface for re-extracting a reference to a
132     /// `Session` from a value that now owns it.
133     fn sess<'a>(&'a self) -> &'a Session;
134
135     /// Provides a uniform interface for re-extracting a reference to an
136     /// `ast_map::Map` from a value that now owns it.
137     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
138
139     /// Produces the pretty-print annotation object.
140     ///
141     /// (Rust does not yet support upcasting from a trait object to
142     /// an object for one of its super-traits.)
143     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn }
144 }
145
146 struct NoAnn<'ast> {
147     sess: Session,
148     ast_map: Option<ast_map::Map<'ast>>
149 }
150
151 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
152     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
153
154     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
155         self.ast_map.as_ref()
156     }
157 }
158
159 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
160
161 struct IdentifiedAnnotation<'ast> {
162     sess: Session,
163     ast_map: Option<ast_map::Map<'ast>>,
164 }
165
166 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
167     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
168
169     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
170         self.ast_map.as_ref()
171     }
172 }
173
174 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
175     fn pre(&self,
176            s: &mut pprust::State,
177            node: pprust::AnnNode) -> io::IoResult<()> {
178         match node {
179             pprust::NodeExpr(_) => s.popen(),
180             _ => Ok(())
181         }
182     }
183     fn post(&self,
184             s: &mut pprust::State,
185             node: pprust::AnnNode) -> io::IoResult<()> {
186         match node {
187             pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
188
189             pprust::NodeItem(item) => {
190                 try!(pp::space(&mut s.s));
191                 s.synth_comment(item.id.to_string())
192             }
193             pprust::NodeBlock(blk) => {
194                 try!(pp::space(&mut s.s));
195                 s.synth_comment(format!("block {}", blk.id))
196             }
197             pprust::NodeExpr(expr) => {
198                 try!(pp::space(&mut s.s));
199                 try!(s.synth_comment(expr.id.to_string()));
200                 s.pclose()
201             }
202             pprust::NodePat(pat) => {
203                 try!(pp::space(&mut s.s));
204                 s.synth_comment(format!("pat {}", pat.id))
205             }
206         }
207     }
208 }
209
210 struct HygieneAnnotation<'ast> {
211     sess: Session,
212     ast_map: Option<ast_map::Map<'ast>>,
213 }
214
215 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
216     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
217
218     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
219         self.ast_map.as_ref()
220     }
221 }
222
223 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
224     fn post(&self,
225             s: &mut pprust::State,
226             node: pprust::AnnNode) -> io::IoResult<()> {
227         match node {
228             pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
229                 try!(pp::space(&mut s.s));
230                 // FIXME #16420: this doesn't display the connections
231                 // between syntax contexts
232                 s.synth_comment(format!("{}#{}", nm, ctxt))
233             }
234             pprust::NodeName(&ast::Name(nm)) => {
235                 try!(pp::space(&mut s.s));
236                 s.synth_comment(nm.to_string())
237             }
238             _ => Ok(())
239         }
240     }
241 }
242
243
244 struct TypedAnnotation<'tcx> {
245     analysis: ty::CrateAnalysis<'tcx>,
246 }
247
248 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
249     fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
250
251     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
252         Some(&self.analysis.ty_cx.map)
253     }
254 }
255
256 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
257     fn pre(&self,
258            s: &mut pprust::State,
259            node: pprust::AnnNode) -> io::IoResult<()> {
260         match node {
261             pprust::NodeExpr(_) => s.popen(),
262             _ => Ok(())
263         }
264     }
265     fn post(&self,
266             s: &mut pprust::State,
267             node: pprust::AnnNode) -> io::IoResult<()> {
268         let tcx = &self.analysis.ty_cx;
269         match node {
270             pprust::NodeExpr(expr) => {
271                 try!(pp::space(&mut s.s));
272                 try!(pp::word(&mut s.s, "as"));
273                 try!(pp::space(&mut s.s));
274                 try!(pp::word(&mut s.s,
275                               ppaux::ty_to_string(
276                                   tcx,
277                                   ty::expr_ty(tcx, expr)).as_slice()));
278                 s.pclose()
279             }
280             _ => Ok(())
281         }
282     }
283 }
284
285 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
286     let print_loans   = config::FLOWGRAPH_PRINT_LOANS;
287     let print_moves   = config::FLOWGRAPH_PRINT_MOVES;
288     let print_assigns = config::FLOWGRAPH_PRINT_ASSIGNS;
289     let print_all     = config::FLOWGRAPH_PRINT_ALL;
290     let opt = |print_which| sess.debugging_opt(print_which);
291     let mut variants = Vec::new();
292     if opt(print_all) || opt(print_loans) {
293         variants.push(borrowck_dot::Loans);
294     }
295     if opt(print_all) || opt(print_moves) {
296         variants.push(borrowck_dot::Moves);
297     }
298     if opt(print_all) || opt(print_assigns) {
299         variants.push(borrowck_dot::Assigns);
300     }
301     variants
302 }
303
304 #[deriving(Clone, Show)]
305 pub enum UserIdentifiedItem {
306     ItemViaNode(ast::NodeId),
307     ItemViaPath(Vec<String>),
308 }
309
310 impl FromStr for UserIdentifiedItem {
311     fn from_str(s: &str) -> Option<UserIdentifiedItem> {
312         let extract_path_parts = || {
313             let v : Vec<_> = s.split_str("::")
314                 .map(|x|x.to_string())
315                 .collect();
316             Some(ItemViaPath(v))
317         };
318
319         from_str(s).map(ItemViaNode).or_else(extract_path_parts)
320     }
321 }
322
323 enum NodesMatchingUII<'a, 'ast: 'a> {
324     NodesMatchingDirect(option::Item<ast::NodeId>),
325     NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast, String>),
326 }
327
328 impl<'a, 'ast> Iterator<ast::NodeId> for NodesMatchingUII<'a, 'ast> {
329     fn next(&mut self) -> Option<ast::NodeId> {
330         match self {
331             &NodesMatchingDirect(ref mut iter) => iter.next(),
332             &NodesMatchingSuffix(ref mut iter) => iter.next(),
333         }
334     }
335 }
336
337 impl UserIdentifiedItem {
338     fn reconstructed_input(&self) -> String {
339         match *self {
340             ItemViaNode(node_id) => node_id.to_string(),
341             ItemViaPath(ref parts) => parts.connect("::"),
342         }
343     }
344
345     fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
346                                        -> NodesMatchingUII<'a, 'ast> {
347         match *self {
348             ItemViaNode(node_id) =>
349                 NodesMatchingDirect(Some(node_id).into_iter()),
350             ItemViaPath(ref parts) =>
351                 NodesMatchingSuffix(map.nodes_matching_suffix(parts.as_slice())),
352         }
353     }
354
355     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
356         let fail_because = |is_wrong_because| -> ast::NodeId {
357             let message =
358                 format!("{} needs NodeId (int) or unique \
359                          path suffix (b::c::d); got {}, which {}",
360                         user_option,
361                         self.reconstructed_input(),
362                         is_wrong_because);
363             sess.fatal(message.as_slice())
364         };
365
366         let mut saw_node = ast::DUMMY_NODE_ID;
367         let mut seen = 0u;
368         for node in self.all_matching_node_ids(map) {
369             saw_node = node;
370             seen += 1;
371             if seen > 1 {
372                 fail_because("does not resolve uniquely");
373             }
374         }
375         if seen == 0 {
376             fail_because("does not resolve to any item");
377         }
378
379         assert!(seen == 1);
380         return saw_node;
381     }
382 }
383
384 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
385     match *ppm {
386         PpmSource(PpmNormal) |
387         PpmSource(PpmIdentified) => opt_uii.is_some(),
388
389         PpmSource(PpmExpanded) |
390         PpmSource(PpmExpandedIdentified) |
391         PpmSource(PpmExpandedHygiene) |
392         PpmSource(PpmTyped) |
393         PpmFlowGraph => true
394     }
395 }
396
397 fn needs_expansion(ppm: &PpMode) -> bool {
398     match *ppm {
399         PpmSource(PpmNormal) |
400         PpmSource(PpmIdentified) => false,
401
402         PpmSource(PpmExpanded) |
403         PpmSource(PpmExpandedIdentified) |
404         PpmSource(PpmExpandedHygiene) |
405         PpmSource(PpmTyped) |
406         PpmFlowGraph => true
407     }
408 }
409
410 pub fn pretty_print_input(sess: Session,
411                           cfg: ast::CrateConfig,
412                           input: &Input,
413                           ppm: PpMode,
414                           opt_uii: Option<UserIdentifiedItem>,
415                           ofile: Option<Path>) {
416     let krate = driver::phase_1_parse_input(&sess, cfg, input);
417     let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
418
419     let is_expanded = needs_expansion(&ppm);
420     let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
421     let krate = if compute_ast_map {
422         match driver::phase_2_configure_and_expand(&sess, krate, id.as_slice(), None) {
423             None => return,
424             Some(k) => k
425         }
426     } else {
427         krate
428     };
429
430     let mut forest = ast_map::Forest::new(krate);
431     let type_arena = TypedArena::new();
432
433     let (krate, ast_map) = if compute_ast_map {
434         let map = driver::assign_node_ids_and_map(&sess, &mut forest);
435         (map.krate(), Some(map))
436     } else {
437         (forest.krate(), None)
438     };
439
440     let src_name = driver::source_name(input);
441     let src = sess.codemap().get_filemap(src_name.as_slice())
442                             .src.as_bytes().to_vec();
443     let mut rdr = MemReader::new(src);
444
445     let out = match ofile {
446         None => box io::stdout() as Box<Writer+'static>,
447         Some(p) => {
448             let r = io::File::create(&p);
449             match r {
450                 Ok(w) => box w as Box<Writer+'static>,
451                 Err(e) => panic!("print-print failed to open {} due to {}",
452                                 p.display(), e),
453             }
454         }
455     };
456
457     match (ppm, opt_uii) {
458         (PpmSource(s), None) =>
459             s.call_with_pp_support(
460                 sess, ast_map, &type_arena, id, out, |annotation, out| {
461                     debug!("pretty printing source code {}", s);
462                     let sess = annotation.sess();
463                     pprust::print_crate(sess.codemap(),
464                                         sess.diagnostic(),
465                                         krate,
466                                         src_name.to_string(),
467                                         &mut rdr,
468                                         out,
469                                         annotation.pp_ann(),
470                                         is_expanded)
471                 }),
472
473         (PpmSource(s), Some(uii)) =>
474             s.call_with_pp_support(
475                 sess, ast_map, &type_arena, id, (out,uii), |annotation, (out,uii)| {
476                     debug!("pretty printing source code {}", s);
477                     let sess = annotation.sess();
478                     let ast_map = annotation.ast_map()
479                         .expect("--pretty missing ast_map");
480                     let mut pp_state =
481                         pprust::State::new_from_input(sess.codemap(),
482                                                       sess.diagnostic(),
483                                                       src_name.to_string(),
484                                                       &mut rdr,
485                                                       out,
486                                                       annotation.pp_ann(),
487                                                       is_expanded);
488                     for node_id in uii.all_matching_node_ids(ast_map) {
489                         let node = ast_map.get(node_id);
490                         try!(pp_state.print_node(&node));
491                         try!(pp::space(&mut pp_state.s));
492                         try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
493                         try!(pp::hardbreak(&mut pp_state.s));
494                     }
495                     pp::eof(&mut pp_state.s)
496                 }),
497
498         (PpmFlowGraph, opt_uii) => {
499             debug!("pretty printing flow graph for {}", opt_uii);
500             let uii = opt_uii.unwrap_or_else(|| {
501                 sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or
502                                      unique path suffix (b::c::d)").as_slice())
503
504             });
505             let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
506             let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
507
508             let node = ast_map.find(nodeid).unwrap_or_else(|| {
509                 sess.fatal(format!("--pretty flowgraph couldn't find id: {}",
510                                    nodeid).as_slice())
511             });
512
513             let code = blocks::Code::from_node(node);
514             match code {
515                 Some(code) => {
516                     let variants = gather_flowgraph_variants(&sess);
517                     let analysis = driver::phase_3_run_analysis_passes(sess, ast_map,
518                                                                        &type_arena, id);
519                     print_flowgraph(variants, analysis, code, out)
520                 }
521                 None => {
522                     let message = format!("--pretty=flowgraph needs \
523                                            block, fn, or method; got {}",
524                                           node);
525
526                     // point to what was found, if there's an
527                     // accessible span.
528                     match ast_map.opt_span(nodeid) {
529                         Some(sp) => sess.span_fatal(sp, message.as_slice()),
530                         None => sess.fatal(message.as_slice())
531                     }
532                 }
533             }
534         }
535     }.unwrap()
536 }
537
538 fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,
539                                  analysis: ty::CrateAnalysis,
540                                  code: blocks::Code,
541                                  mut out: W) -> io::IoResult<()> {
542     let ty_cx = &analysis.ty_cx;
543     let cfg = match code {
544         blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
545         blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
546     };
547
548     match code {
549         _ if variants.len() == 0 => {
550             let lcfg = LabelledCFG {
551                 ast_map: &ty_cx.map,
552                 cfg: &cfg,
553                 name: format!("node_{}", code.id()),
554             };
555             let r = dot::render(&lcfg, &mut out);
556             return expand_err_details(r);
557         }
558         blocks::BlockCode(_) => {
559             ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
560                             annotations requires fn-like node id.");
561             return Ok(())
562         }
563         blocks::FnLikeCode(fn_like) => {
564             let fn_parts = FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
565             let (bccx, analysis_data) =
566                 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
567
568             let lcfg = LabelledCFG {
569                 ast_map: &ty_cx.map,
570                 cfg: &cfg,
571                 name: format!("node_{}", code.id()),
572             };
573             let lcfg = borrowck_dot::DataflowLabeller {
574                 inner: lcfg,
575                 variants: variants,
576                 borrowck_ctxt: &bccx,
577                 analysis_data: &analysis_data,
578             };
579             let r = dot::render(&lcfg, &mut out);
580             return expand_err_details(r);
581         }
582     }
583
584     fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
585         r.map_err(|ioerr| {
586             let orig_detail = ioerr.detail.clone();
587             let m = "graphviz::render failed";
588             io::IoError {
589                 detail: Some(match orig_detail {
590                     None => m.into_string(),
591                     Some(d) => format!("{}: {}", m, d)
592                 }),
593                 ..ioerr
594             }
595         })
596     }
597 }