]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/print/pprust.rs
Auto merge of #29580 - alexbool:smart-pointer-conversion, r=alexcrichton
[rust.git] / src / librustc_front / print / pprust.rs
1 // Copyright 2015 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 pub use self::AnnNode::*;
12
13 use syntax::abi;
14 use syntax::ast;
15 use syntax::owned_slice::OwnedSlice;
16 use syntax::codemap::{self, CodeMap, BytePos, Spanned};
17 use syntax::diagnostic;
18 use syntax::parse::token::{self, BinOpToken};
19 use syntax::parse::lexer::comments;
20 use syntax::parse;
21 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
22 use syntax::print::pp::{Breaks, eof};
23 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
24 use syntax::print::pprust::{self as ast_pp, PrintState};
25 use syntax::ptr::P;
26
27 use hir;
28 use hir::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
29
30 use std::io::{self, Write, Read};
31
32 pub enum AnnNode<'a> {
33     NodeName(&'a ast::Name),
34     NodeBlock(&'a hir::Block),
35     NodeItem(&'a hir::Item),
36     NodeSubItem(ast::NodeId),
37     NodeExpr(&'a hir::Expr),
38     NodePat(&'a hir::Pat),
39 }
40
41 pub trait PpAnn {
42     fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
43         Ok(())
44     }
45     fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
46         Ok(())
47     }
48 }
49
50 #[derive(Copy, Clone)]
51 pub struct NoAnn;
52
53 impl PpAnn for NoAnn {}
54
55
56 pub struct State<'a> {
57     pub s: pp::Printer<'a>,
58     cm: Option<&'a CodeMap>,
59     comments: Option<Vec<comments::Comment>>,
60     literals: Option<Vec<comments::Literal>>,
61     cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
62     boxes: Vec<pp::Breaks>,
63     ann: &'a (PpAnn + 'a),
64 }
65
66 impl<'a> PrintState<'a> for State<'a> {
67     fn writer(&mut self) -> &mut pp::Printer<'a> {
68         &mut self.s
69     }
70
71     fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
72         &mut self.boxes
73     }
74
75     fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
76         &mut self.comments
77     }
78
79     fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
80         &mut self.cur_cmnt_and_lit
81     }
82
83     fn literals(&self) -> &Option<Vec<comments::Literal>> {
84         &self.literals
85     }
86 }
87
88 pub fn rust_printer<'a>(writer: Box<Write + 'a>) -> State<'a> {
89     static NO_ANN: NoAnn = NoAnn;
90     rust_printer_annotated(writer, &NO_ANN)
91 }
92
93 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>, ann: &'a PpAnn) -> State<'a> {
94     State {
95         s: pp::mk_printer(writer, default_columns),
96         cm: None,
97         comments: None,
98         literals: None,
99         cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
100             cur_cmnt: 0,
101             cur_lit: 0,
102         },
103         boxes: Vec::new(),
104         ann: ann,
105     }
106 }
107
108 #[allow(non_upper_case_globals)]
109 pub const indent_unit: usize = 4;
110
111 #[allow(non_upper_case_globals)]
112 pub const default_columns: usize = 78;
113
114
115 /// Requires you to pass an input filename and reader so that
116 /// it can scan the input text for comments and literals to
117 /// copy forward.
118 pub fn print_crate<'a>(cm: &'a CodeMap,
119                        span_diagnostic: &diagnostic::SpanHandler,
120                        krate: &hir::Crate,
121                        filename: String,
122                        input: &mut Read,
123                        out: Box<Write + 'a>,
124                        ann: &'a PpAnn,
125                        is_expanded: bool)
126                        -> io::Result<()> {
127     let mut s = State::new_from_input(cm, span_diagnostic, filename, input, out, ann, is_expanded);
128
129     // When printing the AST, we sometimes need to inject `#[no_std]` here.
130     // Since you can't compile the HIR, it's not necessary.
131
132     try!(s.print_mod(&krate.module, &krate.attrs));
133     try!(s.print_remaining_comments());
134     eof(&mut s.s)
135 }
136
137 impl<'a> State<'a> {
138     pub fn new_from_input(cm: &'a CodeMap,
139                           span_diagnostic: &diagnostic::SpanHandler,
140                           filename: String,
141                           input: &mut Read,
142                           out: Box<Write + 'a>,
143                           ann: &'a PpAnn,
144                           is_expanded: bool)
145                           -> State<'a> {
146         let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
147                                                                    filename,
148                                                                    input);
149
150         State::new(cm,
151                    out,
152                    ann,
153                    Some(cmnts),
154                    // If the code is post expansion, don't use the table of
155                    // literals, since it doesn't correspond with the literals
156                    // in the AST anymore.
157                    if is_expanded {
158                        None
159                    } else {
160                        Some(lits)
161                    })
162     }
163
164     pub fn new(cm: &'a CodeMap,
165                out: Box<Write + 'a>,
166                ann: &'a PpAnn,
167                comments: Option<Vec<comments::Comment>>,
168                literals: Option<Vec<comments::Literal>>)
169                -> State<'a> {
170         State {
171             s: pp::mk_printer(out, default_columns),
172             cm: Some(cm),
173             comments: comments.clone(),
174             literals: literals.clone(),
175             cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
176                 cur_cmnt: 0,
177                 cur_lit: 0,
178             },
179             boxes: Vec::new(),
180             ann: ann,
181         }
182     }
183 }
184
185 pub fn to_string<F>(f: F) -> String
186     where F: FnOnce(&mut State) -> io::Result<()>
187 {
188     let mut wr = Vec::new();
189     {
190         let mut printer = rust_printer(Box::new(&mut wr));
191         f(&mut printer).unwrap();
192         eof(&mut printer.s).unwrap();
193     }
194     String::from_utf8(wr).unwrap()
195 }
196
197 pub fn binop_to_string(op: BinOpToken) -> &'static str {
198     match op {
199         token::Plus => "+",
200         token::Minus => "-",
201         token::Star => "*",
202         token::Slash => "/",
203         token::Percent => "%",
204         token::Caret => "^",
205         token::And => "&",
206         token::Or => "|",
207         token::Shl => "<<",
208         token::Shr => ">>",
209     }
210 }
211
212 pub fn ty_to_string(ty: &hir::Ty) -> String {
213     to_string(|s| s.print_type(ty))
214 }
215
216 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
217     to_string(|s| s.print_bounds("", bounds))
218 }
219
220 pub fn pat_to_string(pat: &hir::Pat) -> String {
221     to_string(|s| s.print_pat(pat))
222 }
223
224 pub fn arm_to_string(arm: &hir::Arm) -> String {
225     to_string(|s| s.print_arm(arm))
226 }
227
228 pub fn expr_to_string(e: &hir::Expr) -> String {
229     to_string(|s| s.print_expr(e))
230 }
231
232 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
233     to_string(|s| s.print_lifetime(e))
234 }
235
236 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
237     to_string(|s| s.print_stmt(stmt))
238 }
239
240 pub fn item_to_string(i: &hir::Item) -> String {
241     to_string(|s| s.print_item(i))
242 }
243
244 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
245     to_string(|s| s.print_impl_item(i))
246 }
247
248 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
249     to_string(|s| s.print_trait_item(i))
250 }
251
252 pub fn generics_to_string(generics: &hir::Generics) -> String {
253     to_string(|s| s.print_generics(generics))
254 }
255
256 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
257     to_string(|s| s.print_where_clause(i))
258 }
259
260 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
261     to_string(|s| s.print_fn_block_args(p))
262 }
263
264 pub fn path_to_string(p: &hir::Path) -> String {
265     to_string(|s| s.print_path(p, false, 0))
266 }
267
268 pub fn name_to_string(name: ast::Name) -> String {
269     to_string(|s| s.print_name(name))
270 }
271
272 pub fn fun_to_string(decl: &hir::FnDecl,
273                      unsafety: hir::Unsafety,
274                      constness: hir::Constness,
275                      name: ast::Name,
276                      opt_explicit_self: Option<&hir::ExplicitSelf_>,
277                      generics: &hir::Generics)
278                      -> String {
279     to_string(|s| {
280         try!(s.head(""));
281         try!(s.print_fn(decl,
282                         unsafety,
283                         constness,
284                         abi::Rust,
285                         Some(name),
286                         generics,
287                         opt_explicit_self,
288                         hir::Inherited));
289         try!(s.end()); // Close the head box
290         s.end() // Close the outer box
291     })
292 }
293
294 pub fn block_to_string(blk: &hir::Block) -> String {
295     to_string(|s| {
296         // containing cbox, will be closed by print-block at }
297         try!(s.cbox(indent_unit));
298         // head-ibox, will be closed by print-block after {
299         try!(s.ibox(0));
300         s.print_block(blk)
301     })
302 }
303
304 pub fn explicit_self_to_string(explicit_self: &hir::ExplicitSelf_) -> String {
305     to_string(|s| s.print_explicit_self(explicit_self, hir::MutImmutable).map(|_| {}))
306 }
307
308 pub fn variant_to_string(var: &hir::Variant) -> String {
309     to_string(|s| s.print_variant(var))
310 }
311
312 pub fn arg_to_string(arg: &hir::Arg) -> String {
313     to_string(|s| s.print_arg(arg))
314 }
315
316 pub fn visibility_qualified(vis: hir::Visibility, s: &str) -> String {
317     match vis {
318         hir::Public => format!("pub {}", s),
319         hir::Inherited => s.to_string(),
320     }
321 }
322
323 fn needs_parentheses(expr: &hir::Expr) -> bool {
324     match expr.node {
325         hir::ExprAssign(..) |
326         hir::ExprBinary(..) |
327         hir::ExprClosure(..) |
328         hir::ExprAssignOp(..) |
329         hir::ExprCast(..) => true,
330         _ => false,
331     }
332 }
333
334 impl<'a> State<'a> {
335     pub fn cbox(&mut self, u: usize) -> io::Result<()> {
336         self.boxes.push(pp::Breaks::Consistent);
337         pp::cbox(&mut self.s, u)
338     }
339
340     pub fn nbsp(&mut self) -> io::Result<()> {
341         word(&mut self.s, " ")
342     }
343
344     pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
345         try!(word(&mut self.s, w));
346         self.nbsp()
347     }
348
349     pub fn head(&mut self, w: &str) -> io::Result<()> {
350         // outer-box is consistent
351         try!(self.cbox(indent_unit));
352         // head-box is inconsistent
353         try!(self.ibox(w.len() + 1));
354         // keyword that starts the head
355         if !w.is_empty() {
356             try!(self.word_nbsp(w));
357         }
358         Ok(())
359     }
360
361     pub fn bopen(&mut self) -> io::Result<()> {
362         try!(word(&mut self.s, "{"));
363         self.end() // close the head-box
364     }
365
366     pub fn bclose_(&mut self, span: codemap::Span, indented: usize) -> io::Result<()> {
367         self.bclose_maybe_open(span, indented, true)
368     }
369     pub fn bclose_maybe_open(&mut self,
370                              span: codemap::Span,
371                              indented: usize,
372                              close_box: bool)
373                              -> io::Result<()> {
374         try!(self.maybe_print_comment(span.hi));
375         try!(self.break_offset_if_not_bol(1, -(indented as isize)));
376         try!(word(&mut self.s, "}"));
377         if close_box {
378             try!(self.end()); // close the outer-box
379         }
380         Ok(())
381     }
382     pub fn bclose(&mut self, span: codemap::Span) -> io::Result<()> {
383         self.bclose_(span, indent_unit)
384     }
385
386     pub fn in_cbox(&self) -> bool {
387         match self.boxes.last() {
388             Some(&last_box) => last_box == pp::Breaks::Consistent,
389             None => false,
390         }
391     }
392     pub fn space_if_not_bol(&mut self) -> io::Result<()> {
393         if !self.is_bol() {
394             try!(space(&mut self.s));
395         }
396         Ok(())
397     }
398     pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
399         if !self.is_bol() {
400             break_offset(&mut self.s, n, off)
401         } else {
402             if off != 0 && self.s.last_token().is_hardbreak_tok() {
403                 // We do something pretty sketchy here: tuck the nonzero
404                 // offset-adjustment we were going to deposit along with the
405                 // break into the previous hardbreak.
406                 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
407             }
408             Ok(())
409         }
410     }
411
412     // Synthesizes a comment that was not textually present in the original source
413     // file.
414     pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
415         try!(word(&mut self.s, "/*"));
416         try!(space(&mut self.s));
417         try!(word(&mut self.s, &text[..]));
418         try!(space(&mut self.s));
419         word(&mut self.s, "*/")
420     }
421
422
423     pub fn commasep_cmnt<T, F, G>(&mut self,
424                                   b: Breaks,
425                                   elts: &[T],
426                                   mut op: F,
427                                   mut get_span: G)
428                                   -> io::Result<()>
429         where F: FnMut(&mut State, &T) -> io::Result<()>,
430               G: FnMut(&T) -> codemap::Span
431     {
432         try!(self.rbox(0, b));
433         let len = elts.len();
434         let mut i = 0;
435         for elt in elts {
436             try!(self.maybe_print_comment(get_span(elt).hi));
437             try!(op(self, elt));
438             i += 1;
439             if i < len {
440                 try!(word(&mut self.s, ","));
441                 try!(self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi)));
442                 try!(self.space_if_not_bol());
443             }
444         }
445         self.end()
446     }
447
448     pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<hir::Expr>]) -> io::Result<()> {
449         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
450     }
451
452     pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
453         try!(self.print_inner_attributes(attrs));
454         for item in &_mod.items {
455             try!(self.print_item(&**item));
456         }
457         Ok(())
458     }
459
460     pub fn print_foreign_mod(&mut self,
461                              nmod: &hir::ForeignMod,
462                              attrs: &[ast::Attribute])
463                              -> io::Result<()> {
464         try!(self.print_inner_attributes(attrs));
465         for item in &nmod.items {
466             try!(self.print_foreign_item(&**item));
467         }
468         Ok(())
469     }
470
471     pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
472         if let Some(l) = *lifetime {
473             try!(self.print_lifetime(&l));
474             try!(self.nbsp());
475         }
476         Ok(())
477     }
478
479     pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
480         try!(self.maybe_print_comment(ty.span.lo));
481         try!(self.ibox(0));
482         match ty.node {
483             hir::TyVec(ref ty) => {
484                 try!(word(&mut self.s, "["));
485                 try!(self.print_type(&**ty));
486                 try!(word(&mut self.s, "]"));
487             }
488             hir::TyPtr(ref mt) => {
489                 try!(word(&mut self.s, "*"));
490                 match mt.mutbl {
491                     hir::MutMutable => try!(self.word_nbsp("mut")),
492                     hir::MutImmutable => try!(self.word_nbsp("const")),
493                 }
494                 try!(self.print_type(&*mt.ty));
495             }
496             hir::TyRptr(ref lifetime, ref mt) => {
497                 try!(word(&mut self.s, "&"));
498                 try!(self.print_opt_lifetime(lifetime));
499                 try!(self.print_mt(mt));
500             }
501             hir::TyTup(ref elts) => {
502                 try!(self.popen());
503                 try!(self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&**ty)));
504                 if elts.len() == 1 {
505                     try!(word(&mut self.s, ","));
506                 }
507                 try!(self.pclose());
508             }
509             hir::TyParen(ref typ) => {
510                 try!(self.popen());
511                 try!(self.print_type(&**typ));
512                 try!(self.pclose());
513             }
514             hir::TyBareFn(ref f) => {
515                 let generics = hir::Generics {
516                     lifetimes: f.lifetimes.clone(),
517                     ty_params: OwnedSlice::empty(),
518                     where_clause: hir::WhereClause {
519                         id: ast::DUMMY_NODE_ID,
520                         predicates: Vec::new(),
521                     },
522                 };
523                 try!(self.print_ty_fn(f.abi, f.unsafety, &*f.decl, None, &generics, None));
524             }
525             hir::TyPath(None, ref path) => {
526                 try!(self.print_path(path, false, 0));
527             }
528             hir::TyPath(Some(ref qself), ref path) => {
529                 try!(self.print_qpath(path, qself, false))
530             }
531             hir::TyObjectSum(ref ty, ref bounds) => {
532                 try!(self.print_type(&**ty));
533                 try!(self.print_bounds("+", &bounds[..]));
534             }
535             hir::TyPolyTraitRef(ref bounds) => {
536                 try!(self.print_bounds("", &bounds[..]));
537             }
538             hir::TyFixedLengthVec(ref ty, ref v) => {
539                 try!(word(&mut self.s, "["));
540                 try!(self.print_type(&**ty));
541                 try!(word(&mut self.s, "; "));
542                 try!(self.print_expr(&**v));
543                 try!(word(&mut self.s, "]"));
544             }
545             hir::TyTypeof(ref e) => {
546                 try!(word(&mut self.s, "typeof("));
547                 try!(self.print_expr(&**e));
548                 try!(word(&mut self.s, ")"));
549             }
550             hir::TyInfer => {
551                 try!(word(&mut self.s, "_"));
552             }
553         }
554         self.end()
555     }
556
557     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
558         try!(self.hardbreak_if_not_bol());
559         try!(self.maybe_print_comment(item.span.lo));
560         try!(self.print_outer_attributes(&item.attrs));
561         match item.node {
562             hir::ForeignItemFn(ref decl, ref generics) => {
563                 try!(self.head(""));
564                 try!(self.print_fn(decl,
565                                    hir::Unsafety::Normal,
566                                    hir::Constness::NotConst,
567                                    abi::Rust,
568                                    Some(item.name),
569                                    generics,
570                                    None,
571                                    item.vis));
572                 try!(self.end()); // end head-ibox
573                 try!(word(&mut self.s, ";"));
574                 self.end() // end the outer fn box
575             }
576             hir::ForeignItemStatic(ref t, m) => {
577                 try!(self.head(&visibility_qualified(item.vis, "static")));
578                 if m {
579                     try!(self.word_space("mut"));
580                 }
581                 try!(self.print_name(item.name));
582                 try!(self.word_space(":"));
583                 try!(self.print_type(&**t));
584                 try!(word(&mut self.s, ";"));
585                 try!(self.end()); // end the head-ibox
586                 self.end() // end the outer cbox
587             }
588         }
589     }
590
591     fn print_associated_const(&mut self,
592                               name: ast::Name,
593                               ty: &hir::Ty,
594                               default: Option<&hir::Expr>,
595                               vis: hir::Visibility)
596                               -> io::Result<()> {
597         try!(word(&mut self.s, &visibility_qualified(vis, "")));
598         try!(self.word_space("const"));
599         try!(self.print_name(name));
600         try!(self.word_space(":"));
601         try!(self.print_type(ty));
602         if let Some(expr) = default {
603             try!(space(&mut self.s));
604             try!(self.word_space("="));
605             try!(self.print_expr(expr));
606         }
607         word(&mut self.s, ";")
608     }
609
610     fn print_associated_type(&mut self,
611                              name: ast::Name,
612                              bounds: Option<&hir::TyParamBounds>,
613                              ty: Option<&hir::Ty>)
614                              -> io::Result<()> {
615         try!(self.word_space("type"));
616         try!(self.print_name(name));
617         if let Some(bounds) = bounds {
618             try!(self.print_bounds(":", bounds));
619         }
620         if let Some(ty) = ty {
621             try!(space(&mut self.s));
622             try!(self.word_space("="));
623             try!(self.print_type(ty));
624         }
625         word(&mut self.s, ";")
626     }
627
628     /// Pretty-print an item
629     pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
630         try!(self.hardbreak_if_not_bol());
631         try!(self.maybe_print_comment(item.span.lo));
632         try!(self.print_outer_attributes(&item.attrs));
633         try!(self.ann.pre(self, NodeItem(item)));
634         match item.node {
635             hir::ItemExternCrate(ref optional_path) => {
636                 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
637                 if let Some(p) = *optional_path {
638                     let val = p.as_str();
639                     if val.contains("-") {
640                         try!(self.print_string(&val, ast::CookedStr));
641                     } else {
642                         try!(self.print_name(p));
643                     }
644                     try!(space(&mut self.s));
645                     try!(word(&mut self.s, "as"));
646                     try!(space(&mut self.s));
647                 }
648                 try!(self.print_name(item.name));
649                 try!(word(&mut self.s, ";"));
650                 try!(self.end()); // end inner head-block
651                 try!(self.end()); // end outer head-block
652             }
653             hir::ItemUse(ref vp) => {
654                 try!(self.head(&visibility_qualified(item.vis, "use")));
655                 try!(self.print_view_path(&**vp));
656                 try!(word(&mut self.s, ";"));
657                 try!(self.end()); // end inner head-block
658                 try!(self.end()); // end outer head-block
659             }
660             hir::ItemStatic(ref ty, m, ref expr) => {
661                 try!(self.head(&visibility_qualified(item.vis, "static")));
662                 if m == hir::MutMutable {
663                     try!(self.word_space("mut"));
664                 }
665                 try!(self.print_name(item.name));
666                 try!(self.word_space(":"));
667                 try!(self.print_type(&**ty));
668                 try!(space(&mut self.s));
669                 try!(self.end()); // end the head-ibox
670
671                 try!(self.word_space("="));
672                 try!(self.print_expr(&**expr));
673                 try!(word(&mut self.s, ";"));
674                 try!(self.end()); // end the outer cbox
675             }
676             hir::ItemConst(ref ty, ref expr) => {
677                 try!(self.head(&visibility_qualified(item.vis, "const")));
678                 try!(self.print_name(item.name));
679                 try!(self.word_space(":"));
680                 try!(self.print_type(&**ty));
681                 try!(space(&mut self.s));
682                 try!(self.end()); // end the head-ibox
683
684                 try!(self.word_space("="));
685                 try!(self.print_expr(&**expr));
686                 try!(word(&mut self.s, ";"));
687                 try!(self.end()); // end the outer cbox
688             }
689             hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
690                 try!(self.head(""));
691                 try!(self.print_fn(decl,
692                                    unsafety,
693                                    constness,
694                                    abi,
695                                    Some(item.name),
696                                    typarams,
697                                    None,
698                                    item.vis));
699                 try!(word(&mut self.s, " "));
700                 try!(self.print_block_with_attrs(&**body, &item.attrs));
701             }
702             hir::ItemMod(ref _mod) => {
703                 try!(self.head(&visibility_qualified(item.vis, "mod")));
704                 try!(self.print_name(item.name));
705                 try!(self.nbsp());
706                 try!(self.bopen());
707                 try!(self.print_mod(_mod, &item.attrs));
708                 try!(self.bclose(item.span));
709             }
710             hir::ItemForeignMod(ref nmod) => {
711                 try!(self.head("extern"));
712                 try!(self.word_nbsp(&nmod.abi.to_string()));
713                 try!(self.bopen());
714                 try!(self.print_foreign_mod(nmod, &item.attrs));
715                 try!(self.bclose(item.span));
716             }
717             hir::ItemTy(ref ty, ref params) => {
718                 try!(self.ibox(indent_unit));
719                 try!(self.ibox(0));
720                 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
721                 try!(self.print_name(item.name));
722                 try!(self.print_generics(params));
723                 try!(self.end()); // end the inner ibox
724
725                 try!(self.print_where_clause(&params.where_clause));
726                 try!(space(&mut self.s));
727                 try!(self.word_space("="));
728                 try!(self.print_type(&**ty));
729                 try!(word(&mut self.s, ";"));
730                 try!(self.end()); // end the outer ibox
731             }
732             hir::ItemEnum(ref enum_definition, ref params) => {
733                 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
734             }
735             hir::ItemStruct(ref struct_def, ref generics) => {
736                 try!(self.head(&visibility_qualified(item.vis, "struct")));
737                 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
738             }
739
740             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
741                 try!(self.head(""));
742                 try!(self.print_visibility(item.vis));
743                 try!(self.print_unsafety(unsafety));
744                 try!(self.word_nbsp("impl"));
745                 try!(self.print_trait_ref(trait_ref));
746                 try!(space(&mut self.s));
747                 try!(self.word_space("for"));
748                 try!(self.word_space(".."));
749                 try!(self.bopen());
750                 try!(self.bclose(item.span));
751             }
752             hir::ItemImpl(unsafety,
753                           polarity,
754                           ref generics,
755                           ref opt_trait,
756                           ref ty,
757                           ref impl_items) => {
758                 try!(self.head(""));
759                 try!(self.print_visibility(item.vis));
760                 try!(self.print_unsafety(unsafety));
761                 try!(self.word_nbsp("impl"));
762
763                 if generics.is_parameterized() {
764                     try!(self.print_generics(generics));
765                     try!(space(&mut self.s));
766                 }
767
768                 match polarity {
769                     hir::ImplPolarity::Negative => {
770                         try!(word(&mut self.s, "!"));
771                     }
772                     _ => {}
773                 }
774
775                 match opt_trait {
776                     &Some(ref t) => {
777                         try!(self.print_trait_ref(t));
778                         try!(space(&mut self.s));
779                         try!(self.word_space("for"));
780                     }
781                     &None => {}
782                 }
783
784                 try!(self.print_type(&**ty));
785                 try!(self.print_where_clause(&generics.where_clause));
786
787                 try!(space(&mut self.s));
788                 try!(self.bopen());
789                 try!(self.print_inner_attributes(&item.attrs));
790                 for impl_item in impl_items {
791                     try!(self.print_impl_item(impl_item));
792                 }
793                 try!(self.bclose(item.span));
794             }
795             hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
796                 try!(self.head(""));
797                 try!(self.print_visibility(item.vis));
798                 try!(self.print_unsafety(unsafety));
799                 try!(self.word_nbsp("trait"));
800                 try!(self.print_name(item.name));
801                 try!(self.print_generics(generics));
802                 let mut real_bounds = Vec::with_capacity(bounds.len());
803                 for b in bounds.iter() {
804                     if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
805                         try!(space(&mut self.s));
806                         try!(self.word_space("for ?"));
807                         try!(self.print_trait_ref(&ptr.trait_ref));
808                     } else {
809                         real_bounds.push(b.clone());
810                     }
811                 }
812                 try!(self.print_bounds(":", &real_bounds[..]));
813                 try!(self.print_where_clause(&generics.where_clause));
814                 try!(word(&mut self.s, " "));
815                 try!(self.bopen());
816                 for trait_item in trait_items {
817                     try!(self.print_trait_item(trait_item));
818                 }
819                 try!(self.bclose(item.span));
820             }
821         }
822         self.ann.post(self, NodeItem(item))
823     }
824
825     fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
826         self.print_path(&t.path, false, 0)
827     }
828
829     fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
830         if !lifetimes.is_empty() {
831             try!(word(&mut self.s, "for<"));
832             let mut comma = false;
833             for lifetime_def in lifetimes {
834                 if comma {
835                     try!(self.word_space(","))
836                 }
837                 try!(self.print_lifetime_def(lifetime_def));
838                 comma = true;
839             }
840             try!(word(&mut self.s, ">"));
841         }
842         Ok(())
843     }
844
845     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
846         try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
847         self.print_trait_ref(&t.trait_ref)
848     }
849
850     pub fn print_enum_def(&mut self,
851                           enum_definition: &hir::EnumDef,
852                           generics: &hir::Generics,
853                           name: ast::Name,
854                           span: codemap::Span,
855                           visibility: hir::Visibility)
856                           -> io::Result<()> {
857         try!(self.head(&visibility_qualified(visibility, "enum")));
858         try!(self.print_name(name));
859         try!(self.print_generics(generics));
860         try!(self.print_where_clause(&generics.where_clause));
861         try!(space(&mut self.s));
862         self.print_variants(&enum_definition.variants, span)
863     }
864
865     pub fn print_variants(&mut self,
866                           variants: &[P<hir::Variant>],
867                           span: codemap::Span)
868                           -> io::Result<()> {
869         try!(self.bopen());
870         for v in variants {
871             try!(self.space_if_not_bol());
872             try!(self.maybe_print_comment(v.span.lo));
873             try!(self.print_outer_attributes(&v.node.attrs));
874             try!(self.ibox(indent_unit));
875             try!(self.print_variant(&**v));
876             try!(word(&mut self.s, ","));
877             try!(self.end());
878             try!(self.maybe_print_trailing_comment(v.span, None));
879         }
880         self.bclose(span)
881     }
882
883     pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
884         match vis {
885             hir::Public => self.word_nbsp("pub"),
886             hir::Inherited => Ok(()),
887         }
888     }
889
890     pub fn print_struct(&mut self,
891                         struct_def: &hir::VariantData,
892                         generics: &hir::Generics,
893                         name: ast::Name,
894                         span: codemap::Span,
895                         print_finalizer: bool)
896                         -> io::Result<()> {
897         try!(self.print_name(name));
898         try!(self.print_generics(generics));
899         if !struct_def.is_struct() {
900             if struct_def.is_tuple() {
901                 try!(self.popen());
902                 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
903                     match field.node.kind {
904                         hir::NamedField(..) => panic!("unexpected named field"),
905                         hir::UnnamedField(vis) => {
906                             try!(s.print_visibility(vis));
907                             try!(s.maybe_print_comment(field.span.lo));
908                             s.print_type(&*field.node.ty)
909                         }
910                     }
911                 }));
912                 try!(self.pclose());
913             }
914             try!(self.print_where_clause(&generics.where_clause));
915             if print_finalizer {
916                 try!(word(&mut self.s, ";"));
917             }
918             try!(self.end());
919             self.end() // close the outer-box
920         } else {
921             try!(self.print_where_clause(&generics.where_clause));
922             try!(self.nbsp());
923             try!(self.bopen());
924             try!(self.hardbreak_if_not_bol());
925
926             for field in struct_def.fields() {
927                 match field.node.kind {
928                     hir::UnnamedField(..) => panic!("unexpected unnamed field"),
929                     hir::NamedField(name, visibility) => {
930                         try!(self.hardbreak_if_not_bol());
931                         try!(self.maybe_print_comment(field.span.lo));
932                         try!(self.print_outer_attributes(&field.node.attrs));
933                         try!(self.print_visibility(visibility));
934                         try!(self.print_name(name));
935                         try!(self.word_nbsp(":"));
936                         try!(self.print_type(&*field.node.ty));
937                         try!(word(&mut self.s, ","));
938                     }
939                 }
940             }
941
942             self.bclose(span)
943         }
944     }
945
946     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
947         try!(self.head(""));
948         let generics = ::util::empty_generics();
949         try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
950         match v.node.disr_expr {
951             Some(ref d) => {
952                 try!(space(&mut self.s));
953                 try!(self.word_space("="));
954                 self.print_expr(&**d)
955             }
956             _ => Ok(()),
957         }
958     }
959
960     pub fn print_method_sig(&mut self,
961                             name: ast::Name,
962                             m: &hir::MethodSig,
963                             vis: hir::Visibility)
964                             -> io::Result<()> {
965         self.print_fn(&m.decl,
966                       m.unsafety,
967                       m.constness,
968                       m.abi,
969                       Some(name),
970                       &m.generics,
971                       Some(&m.explicit_self.node),
972                       vis)
973     }
974
975     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
976         try!(self.ann.pre(self, NodeSubItem(ti.id)));
977         try!(self.hardbreak_if_not_bol());
978         try!(self.maybe_print_comment(ti.span.lo));
979         try!(self.print_outer_attributes(&ti.attrs));
980         match ti.node {
981             hir::ConstTraitItem(ref ty, ref default) => {
982                 try!(self.print_associated_const(ti.name,
983                                                  &ty,
984                                                  default.as_ref().map(|expr| &**expr),
985                                                  hir::Inherited));
986             }
987             hir::MethodTraitItem(ref sig, ref body) => {
988                 if body.is_some() {
989                     try!(self.head(""));
990                 }
991                 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
992                 if let Some(ref body) = *body {
993                     try!(self.nbsp());
994                     try!(self.print_block_with_attrs(body, &ti.attrs));
995                 } else {
996                     try!(word(&mut self.s, ";"));
997                 }
998             }
999             hir::TypeTraitItem(ref bounds, ref default) => {
1000                 try!(self.print_associated_type(ti.name,
1001                                                 Some(bounds),
1002                                                 default.as_ref().map(|ty| &**ty)));
1003             }
1004         }
1005         self.ann.post(self, NodeSubItem(ti.id))
1006     }
1007
1008     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1009         try!(self.ann.pre(self, NodeSubItem(ii.id)));
1010         try!(self.hardbreak_if_not_bol());
1011         try!(self.maybe_print_comment(ii.span.lo));
1012         try!(self.print_outer_attributes(&ii.attrs));
1013         match ii.node {
1014             hir::ConstImplItem(ref ty, ref expr) => {
1015                 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1016             }
1017             hir::MethodImplItem(ref sig, ref body) => {
1018                 try!(self.head(""));
1019                 try!(self.print_method_sig(ii.name, sig, ii.vis));
1020                 try!(self.nbsp());
1021                 try!(self.print_block_with_attrs(body, &ii.attrs));
1022             }
1023             hir::TypeImplItem(ref ty) => {
1024                 try!(self.print_associated_type(ii.name, None, Some(ty)));
1025             }
1026         }
1027         self.ann.post(self, NodeSubItem(ii.id))
1028     }
1029
1030     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1031         try!(self.maybe_print_comment(st.span.lo));
1032         match st.node {
1033             hir::StmtDecl(ref decl, _) => {
1034                 try!(self.print_decl(&**decl));
1035             }
1036             hir::StmtExpr(ref expr, _) => {
1037                 try!(self.space_if_not_bol());
1038                 try!(self.print_expr(&**expr));
1039             }
1040             hir::StmtSemi(ref expr, _) => {
1041                 try!(self.space_if_not_bol());
1042                 try!(self.print_expr(&**expr));
1043                 try!(word(&mut self.s, ";"));
1044             }
1045         }
1046         if stmt_ends_with_semi(&st.node) {
1047             try!(word(&mut self.s, ";"));
1048         }
1049         self.maybe_print_trailing_comment(st.span, None)
1050     }
1051
1052     pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1053         self.print_block_with_attrs(blk, &[])
1054     }
1055
1056     pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1057         self.print_block_unclosed_indent(blk, indent_unit)
1058     }
1059
1060     pub fn print_block_unclosed_indent(&mut self,
1061                                        blk: &hir::Block,
1062                                        indented: usize)
1063                                        -> io::Result<()> {
1064         self.print_block_maybe_unclosed(blk, indented, &[], false)
1065     }
1066
1067     pub fn print_block_with_attrs(&mut self,
1068                                   blk: &hir::Block,
1069                                   attrs: &[ast::Attribute])
1070                                   -> io::Result<()> {
1071         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1072     }
1073
1074     pub fn print_block_maybe_unclosed(&mut self,
1075                                       blk: &hir::Block,
1076                                       indented: usize,
1077                                       attrs: &[ast::Attribute],
1078                                       close_box: bool)
1079                                       -> io::Result<()> {
1080         match blk.rules {
1081             hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1082             hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1083             hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1084             hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1085             hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1086             hir::DefaultBlock => (),
1087         }
1088         try!(self.maybe_print_comment(blk.span.lo));
1089         try!(self.ann.pre(self, NodeBlock(blk)));
1090         try!(self.bopen());
1091
1092         try!(self.print_inner_attributes(attrs));
1093
1094         for st in &blk.stmts {
1095             try!(self.print_stmt(&**st));
1096         }
1097         match blk.expr {
1098             Some(ref expr) => {
1099                 try!(self.space_if_not_bol());
1100                 try!(self.print_expr(&**expr));
1101                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1102             }
1103             _ => (),
1104         }
1105         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1106         self.ann.post(self, NodeBlock(blk))
1107     }
1108
1109     fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1110         match els {
1111             Some(_else) => {
1112                 match _else.node {
1113                     // "another else-if"
1114                     hir::ExprIf(ref i, ref then, ref e) => {
1115                         try!(self.cbox(indent_unit - 1));
1116                         try!(self.ibox(0));
1117                         try!(word(&mut self.s, " else if "));
1118                         try!(self.print_expr(&**i));
1119                         try!(space(&mut self.s));
1120                         try!(self.print_block(&**then));
1121                         self.print_else(e.as_ref().map(|e| &**e))
1122                     }
1123                     // "final else"
1124                     hir::ExprBlock(ref b) => {
1125                         try!(self.cbox(indent_unit - 1));
1126                         try!(self.ibox(0));
1127                         try!(word(&mut self.s, " else "));
1128                         self.print_block(&**b)
1129                     }
1130                     // BLEAH, constraints would be great here
1131                     _ => {
1132                         panic!("print_if saw if with weird alternative");
1133                     }
1134                 }
1135             }
1136             _ => Ok(()),
1137         }
1138     }
1139
1140     pub fn print_if(&mut self,
1141                     test: &hir::Expr,
1142                     blk: &hir::Block,
1143                     elseopt: Option<&hir::Expr>)
1144                     -> io::Result<()> {
1145         try!(self.head("if"));
1146         try!(self.print_expr(test));
1147         try!(space(&mut self.s));
1148         try!(self.print_block(blk));
1149         self.print_else(elseopt)
1150     }
1151
1152     pub fn print_if_let(&mut self,
1153                         pat: &hir::Pat,
1154                         expr: &hir::Expr,
1155                         blk: &hir::Block,
1156                         elseopt: Option<&hir::Expr>)
1157                         -> io::Result<()> {
1158         try!(self.head("if let"));
1159         try!(self.print_pat(pat));
1160         try!(space(&mut self.s));
1161         try!(self.word_space("="));
1162         try!(self.print_expr(expr));
1163         try!(space(&mut self.s));
1164         try!(self.print_block(blk));
1165         self.print_else(elseopt)
1166     }
1167
1168
1169     fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1170         try!(self.popen());
1171         try!(self.commasep_exprs(Inconsistent, args));
1172         self.pclose()
1173     }
1174
1175     pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1176         let needs_par = needs_parentheses(expr);
1177         if needs_par {
1178             try!(self.popen());
1179         }
1180         try!(self.print_expr(expr));
1181         if needs_par {
1182             try!(self.pclose());
1183         }
1184         Ok(())
1185     }
1186
1187     fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1188         try!(self.ibox(indent_unit));
1189         try!(word(&mut self.s, "["));
1190         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1191         try!(word(&mut self.s, "]"));
1192         self.end()
1193     }
1194
1195     fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1196         try!(self.ibox(indent_unit));
1197         try!(word(&mut self.s, "["));
1198         try!(self.print_expr(element));
1199         try!(self.word_space(";"));
1200         try!(self.print_expr(count));
1201         try!(word(&mut self.s, "]"));
1202         self.end()
1203     }
1204
1205     fn print_expr_struct(&mut self,
1206                          path: &hir::Path,
1207                          fields: &[hir::Field],
1208                          wth: &Option<P<hir::Expr>>)
1209                          -> io::Result<()> {
1210         try!(self.print_path(path, true, 0));
1211         try!(word(&mut self.s, "{"));
1212         try!(self.commasep_cmnt(Consistent,
1213                                 &fields[..],
1214                                 |s, field| {
1215                                     try!(s.ibox(indent_unit));
1216                                     try!(s.print_name(field.name.node));
1217                                     try!(s.word_space(":"));
1218                                     try!(s.print_expr(&*field.expr));
1219                                     s.end()
1220                                 },
1221                                 |f| f.span));
1222         match *wth {
1223             Some(ref expr) => {
1224                 try!(self.ibox(indent_unit));
1225                 if !fields.is_empty() {
1226                     try!(word(&mut self.s, ","));
1227                     try!(space(&mut self.s));
1228                 }
1229                 try!(word(&mut self.s, ".."));
1230                 try!(self.print_expr(&**expr));
1231                 try!(self.end());
1232             }
1233             _ => if !fields.is_empty() {
1234                 try!(word(&mut self.s, ","))
1235             },
1236         }
1237         try!(word(&mut self.s, "}"));
1238         Ok(())
1239     }
1240
1241     fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1242         try!(self.popen());
1243         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1244         if exprs.len() == 1 {
1245             try!(word(&mut self.s, ","));
1246         }
1247         self.pclose()
1248     }
1249
1250     fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1251         try!(self.print_expr_maybe_paren(func));
1252         self.print_call_post(args)
1253     }
1254
1255     fn print_expr_method_call(&mut self,
1256                               name: Spanned<ast::Name>,
1257                               tys: &[P<hir::Ty>],
1258                               args: &[P<hir::Expr>])
1259                               -> io::Result<()> {
1260         let base_args = &args[1..];
1261         try!(self.print_expr(&*args[0]));
1262         try!(word(&mut self.s, "."));
1263         try!(self.print_name(name.node));
1264         if !tys.is_empty() {
1265             try!(word(&mut self.s, "::<"));
1266             try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty)));
1267             try!(word(&mut self.s, ">"));
1268         }
1269         self.print_call_post(base_args)
1270     }
1271
1272     fn print_expr_binary(&mut self,
1273                          op: hir::BinOp,
1274                          lhs: &hir::Expr,
1275                          rhs: &hir::Expr)
1276                          -> io::Result<()> {
1277         try!(self.print_expr(lhs));
1278         try!(space(&mut self.s));
1279         try!(self.word_space(::util::binop_to_string(op.node)));
1280         self.print_expr(rhs)
1281     }
1282
1283     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1284         try!(word(&mut self.s, ::util::unop_to_string(op)));
1285         self.print_expr_maybe_paren(expr)
1286     }
1287
1288     fn print_expr_addr_of(&mut self,
1289                           mutability: hir::Mutability,
1290                           expr: &hir::Expr)
1291                           -> io::Result<()> {
1292         try!(word(&mut self.s, "&"));
1293         try!(self.print_mutability(mutability));
1294         self.print_expr_maybe_paren(expr)
1295     }
1296
1297     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1298         try!(self.maybe_print_comment(expr.span.lo));
1299         try!(self.ibox(indent_unit));
1300         try!(self.ann.pre(self, NodeExpr(expr)));
1301         match expr.node {
1302             hir::ExprBox(ref expr) => {
1303                 try!(self.word_space("box"));
1304                 try!(self.print_expr(expr));
1305             }
1306             hir::ExprVec(ref exprs) => {
1307                 try!(self.print_expr_vec(&exprs[..]));
1308             }
1309             hir::ExprRepeat(ref element, ref count) => {
1310                 try!(self.print_expr_repeat(&**element, &**count));
1311             }
1312             hir::ExprStruct(ref path, ref fields, ref wth) => {
1313                 try!(self.print_expr_struct(path, &fields[..], wth));
1314             }
1315             hir::ExprTup(ref exprs) => {
1316                 try!(self.print_expr_tup(&exprs[..]));
1317             }
1318             hir::ExprCall(ref func, ref args) => {
1319                 try!(self.print_expr_call(&**func, &args[..]));
1320             }
1321             hir::ExprMethodCall(name, ref tys, ref args) => {
1322                 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1323             }
1324             hir::ExprBinary(op, ref lhs, ref rhs) => {
1325                 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1326             }
1327             hir::ExprUnary(op, ref expr) => {
1328                 try!(self.print_expr_unary(op, &**expr));
1329             }
1330             hir::ExprAddrOf(m, ref expr) => {
1331                 try!(self.print_expr_addr_of(m, &**expr));
1332             }
1333             hir::ExprLit(ref lit) => {
1334                 try!(self.print_literal(&**lit));
1335             }
1336             hir::ExprCast(ref expr, ref ty) => {
1337                 try!(self.print_expr(&**expr));
1338                 try!(space(&mut self.s));
1339                 try!(self.word_space("as"));
1340                 try!(self.print_type(&**ty));
1341             }
1342             hir::ExprIf(ref test, ref blk, ref elseopt) => {
1343                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1344             }
1345             hir::ExprWhile(ref test, ref blk, opt_ident) => {
1346                 if let Some(ident) = opt_ident {
1347                     try!(self.print_name(ident.name));
1348                     try!(self.word_space(":"));
1349                 }
1350                 try!(self.head("while"));
1351                 try!(self.print_expr(&**test));
1352                 try!(space(&mut self.s));
1353                 try!(self.print_block(&**blk));
1354             }
1355             hir::ExprLoop(ref blk, opt_ident) => {
1356                 if let Some(ident) = opt_ident {
1357                     try!(self.print_name(ident.name));
1358                     try!(self.word_space(":"));
1359                 }
1360                 try!(self.head("loop"));
1361                 try!(space(&mut self.s));
1362                 try!(self.print_block(&**blk));
1363             }
1364             hir::ExprMatch(ref expr, ref arms, _) => {
1365                 try!(self.cbox(indent_unit));
1366                 try!(self.ibox(4));
1367                 try!(self.word_nbsp("match"));
1368                 try!(self.print_expr(&**expr));
1369                 try!(space(&mut self.s));
1370                 try!(self.bopen());
1371                 for arm in arms {
1372                     try!(self.print_arm(arm));
1373                 }
1374                 try!(self.bclose_(expr.span, indent_unit));
1375             }
1376             hir::ExprClosure(capture_clause, ref decl, ref body) => {
1377                 try!(self.print_capture_clause(capture_clause));
1378
1379                 try!(self.print_fn_block_args(&**decl));
1380                 try!(space(&mut self.s));
1381
1382                 let default_return = match decl.output {
1383                     hir::DefaultReturn(..) => true,
1384                     _ => false,
1385                 };
1386
1387                 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1388                     try!(self.print_block_unclosed(&**body));
1389                 } else {
1390                     // we extract the block, so as not to create another set of boxes
1391                     match body.expr.as_ref().unwrap().node {
1392                         hir::ExprBlock(ref blk) => {
1393                             try!(self.print_block_unclosed(&**blk));
1394                         }
1395                         _ => {
1396                             // this is a bare expression
1397                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1398                             try!(self.end()); // need to close a box
1399                         }
1400                     }
1401                 }
1402                 // a box will be closed by print_expr, but we didn't want an overall
1403                 // wrapper so we closed the corresponding opening. so create an
1404                 // empty box to satisfy the close.
1405                 try!(self.ibox(0));
1406             }
1407             hir::ExprBlock(ref blk) => {
1408                 // containing cbox, will be closed by print-block at }
1409                 try!(self.cbox(indent_unit));
1410                 // head-box, will be closed by print-block after {
1411                 try!(self.ibox(0));
1412                 try!(self.print_block(&**blk));
1413             }
1414             hir::ExprAssign(ref lhs, ref rhs) => {
1415                 try!(self.print_expr(&**lhs));
1416                 try!(space(&mut self.s));
1417                 try!(self.word_space("="));
1418                 try!(self.print_expr(&**rhs));
1419             }
1420             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1421                 try!(self.print_expr(&**lhs));
1422                 try!(space(&mut self.s));
1423                 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1424                 try!(self.word_space("="));
1425                 try!(self.print_expr(&**rhs));
1426             }
1427             hir::ExprField(ref expr, name) => {
1428                 try!(self.print_expr(&**expr));
1429                 try!(word(&mut self.s, "."));
1430                 try!(self.print_name(name.node));
1431             }
1432             hir::ExprTupField(ref expr, id) => {
1433                 try!(self.print_expr(&**expr));
1434                 try!(word(&mut self.s, "."));
1435                 try!(self.print_usize(id.node));
1436             }
1437             hir::ExprIndex(ref expr, ref index) => {
1438                 try!(self.print_expr(&**expr));
1439                 try!(word(&mut self.s, "["));
1440                 try!(self.print_expr(&**index));
1441                 try!(word(&mut self.s, "]"));
1442             }
1443             hir::ExprRange(ref start, ref end) => {
1444                 if let &Some(ref e) = start {
1445                     try!(self.print_expr(&**e));
1446                 }
1447                 try!(word(&mut self.s, ".."));
1448                 if let &Some(ref e) = end {
1449                     try!(self.print_expr(&**e));
1450                 }
1451             }
1452             hir::ExprPath(None, ref path) => {
1453                 try!(self.print_path(path, true, 0))
1454             }
1455             hir::ExprPath(Some(ref qself), ref path) => {
1456                 try!(self.print_qpath(path, qself, true))
1457             }
1458             hir::ExprBreak(opt_ident) => {
1459                 try!(word(&mut self.s, "break"));
1460                 try!(space(&mut self.s));
1461                 if let Some(ident) = opt_ident {
1462                     try!(self.print_name(ident.node.name));
1463                     try!(space(&mut self.s));
1464                 }
1465             }
1466             hir::ExprAgain(opt_ident) => {
1467                 try!(word(&mut self.s, "continue"));
1468                 try!(space(&mut self.s));
1469                 if let Some(ident) = opt_ident {
1470                     try!(self.print_name(ident.node.name));
1471                     try!(space(&mut self.s))
1472                 }
1473             }
1474             hir::ExprRet(ref result) => {
1475                 try!(word(&mut self.s, "return"));
1476                 match *result {
1477                     Some(ref expr) => {
1478                         try!(word(&mut self.s, " "));
1479                         try!(self.print_expr(&**expr));
1480                     }
1481                     _ => (),
1482                 }
1483             }
1484             hir::ExprInlineAsm(ref a) => {
1485                 try!(word(&mut self.s, "asm!"));
1486                 try!(self.popen());
1487                 try!(self.print_string(&a.asm, a.asm_str_style));
1488                 try!(self.word_space(":"));
1489
1490                 try!(self.commasep(Inconsistent, &a.outputs, |s, &(ref co, ref o, is_rw)| {
1491                     match co.slice_shift_char() {
1492                         Some(('=', operand)) if is_rw => {
1493                             try!(s.print_string(&format!("+{}", operand), ast::CookedStr))
1494                         }
1495                         _ => try!(s.print_string(&co, ast::CookedStr)),
1496                     }
1497                     try!(s.popen());
1498                     try!(s.print_expr(&**o));
1499                     try!(s.pclose());
1500                     Ok(())
1501                 }));
1502                 try!(space(&mut self.s));
1503                 try!(self.word_space(":"));
1504
1505                 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1506                     try!(s.print_string(&co, ast::CookedStr));
1507                     try!(s.popen());
1508                     try!(s.print_expr(&**o));
1509                     try!(s.pclose());
1510                     Ok(())
1511                 }));
1512                 try!(space(&mut self.s));
1513                 try!(self.word_space(":"));
1514
1515                 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1516                     try!(s.print_string(&co, ast::CookedStr));
1517                     Ok(())
1518                 }));
1519
1520                 let mut options = vec![];
1521                 if a.volatile {
1522                     options.push("volatile");
1523                 }
1524                 if a.alignstack {
1525                     options.push("alignstack");
1526                 }
1527                 if a.dialect == ast::AsmDialect::Intel {
1528                     options.push("intel");
1529                 }
1530
1531                 if !options.is_empty() {
1532                     try!(space(&mut self.s));
1533                     try!(self.word_space(":"));
1534                     try!(self.commasep(Inconsistent, &*options, |s, &co| {
1535                         try!(s.print_string(co, ast::CookedStr));
1536                         Ok(())
1537                     }));
1538                 }
1539
1540                 try!(self.pclose());
1541             }
1542         }
1543         try!(self.ann.post(self, NodeExpr(expr)));
1544         self.end()
1545     }
1546
1547     pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1548         try!(self.print_pat(&*loc.pat));
1549         if let Some(ref ty) = loc.ty {
1550             try!(self.word_space(":"));
1551             try!(self.print_type(&**ty));
1552         }
1553         Ok(())
1554     }
1555
1556     pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1557         try!(self.maybe_print_comment(decl.span.lo));
1558         match decl.node {
1559             hir::DeclLocal(ref loc) => {
1560                 try!(self.space_if_not_bol());
1561                 try!(self.ibox(indent_unit));
1562                 try!(self.word_nbsp("let"));
1563
1564                 try!(self.ibox(indent_unit));
1565                 try!(self.print_local_decl(&**loc));
1566                 try!(self.end());
1567                 if let Some(ref init) = loc.init {
1568                     try!(self.nbsp());
1569                     try!(self.word_space("="));
1570                     try!(self.print_expr(&**init));
1571                 }
1572                 self.end()
1573             }
1574             hir::DeclItem(ref item) => self.print_item(&**item),
1575         }
1576     }
1577
1578     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1579         word(&mut self.s, &i.to_string())
1580     }
1581
1582     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1583         try!(word(&mut self.s, &name.as_str()));
1584         self.ann.post(self, NodeName(&name))
1585     }
1586
1587     pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1588         try!(self.print_local_decl(loc));
1589         try!(space(&mut self.s));
1590         try!(self.word_space("in"));
1591         self.print_expr(coll)
1592     }
1593
1594     fn print_path(&mut self,
1595                   path: &hir::Path,
1596                   colons_before_params: bool,
1597                   depth: usize)
1598                   -> io::Result<()> {
1599         try!(self.maybe_print_comment(path.span.lo));
1600
1601         let mut first = !path.global;
1602         for segment in &path.segments[..path.segments.len() - depth] {
1603             if first {
1604                 first = false
1605             } else {
1606                 try!(word(&mut self.s, "::"))
1607             }
1608
1609             try!(self.print_name(segment.identifier.name));
1610
1611             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1612         }
1613
1614         Ok(())
1615     }
1616
1617     fn print_qpath(&mut self,
1618                    path: &hir::Path,
1619                    qself: &hir::QSelf,
1620                    colons_before_params: bool)
1621                    -> io::Result<()> {
1622         try!(word(&mut self.s, "<"));
1623         try!(self.print_type(&qself.ty));
1624         if qself.position > 0 {
1625             try!(space(&mut self.s));
1626             try!(self.word_space("as"));
1627             let depth = path.segments.len() - qself.position;
1628             try!(self.print_path(&path, false, depth));
1629         }
1630         try!(word(&mut self.s, ">"));
1631         try!(word(&mut self.s, "::"));
1632         let item_segment = path.segments.last().unwrap();
1633         try!(self.print_name(item_segment.identifier.name));
1634         self.print_path_parameters(&item_segment.parameters, colons_before_params)
1635     }
1636
1637     fn print_path_parameters(&mut self,
1638                              parameters: &hir::PathParameters,
1639                              colons_before_params: bool)
1640                              -> io::Result<()> {
1641         if parameters.is_empty() {
1642             return Ok(());
1643         }
1644
1645         if colons_before_params {
1646             try!(word(&mut self.s, "::"))
1647         }
1648
1649         match *parameters {
1650             hir::AngleBracketedParameters(ref data) => {
1651                 try!(word(&mut self.s, "<"));
1652
1653                 let mut comma = false;
1654                 for lifetime in &data.lifetimes {
1655                     if comma {
1656                         try!(self.word_space(","))
1657                     }
1658                     try!(self.print_lifetime(lifetime));
1659                     comma = true;
1660                 }
1661
1662                 if !data.types.is_empty() {
1663                     if comma {
1664                         try!(self.word_space(","))
1665                     }
1666                     try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&**ty)));
1667                     comma = true;
1668                 }
1669
1670                 for binding in data.bindings.iter() {
1671                     if comma {
1672                         try!(self.word_space(","))
1673                     }
1674                     try!(self.print_name(binding.name));
1675                     try!(space(&mut self.s));
1676                     try!(self.word_space("="));
1677                     try!(self.print_type(&*binding.ty));
1678                     comma = true;
1679                 }
1680
1681                 try!(word(&mut self.s, ">"))
1682             }
1683
1684             hir::ParenthesizedParameters(ref data) => {
1685                 try!(word(&mut self.s, "("));
1686                 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&**ty)));
1687                 try!(word(&mut self.s, ")"));
1688
1689                 match data.output {
1690                     None => {}
1691                     Some(ref ty) => {
1692                         try!(self.space_if_not_bol());
1693                         try!(self.word_space("->"));
1694                         try!(self.print_type(&**ty));
1695                     }
1696                 }
1697             }
1698         }
1699
1700         Ok(())
1701     }
1702
1703     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1704         try!(self.maybe_print_comment(pat.span.lo));
1705         try!(self.ann.pre(self, NodePat(pat)));
1706         // Pat isn't normalized, but the beauty of it
1707         // is that it doesn't matter
1708         match pat.node {
1709             hir::PatWild => try!(word(&mut self.s, "_")),
1710             hir::PatIdent(binding_mode, ref path1, ref sub) => {
1711                 match binding_mode {
1712                     hir::BindByRef(mutbl) => {
1713                         try!(self.word_nbsp("ref"));
1714                         try!(self.print_mutability(mutbl));
1715                     }
1716                     hir::BindByValue(hir::MutImmutable) => {}
1717                     hir::BindByValue(hir::MutMutable) => {
1718                         try!(self.word_nbsp("mut"));
1719                     }
1720                 }
1721                 try!(self.print_name(path1.node.name));
1722                 match *sub {
1723                     Some(ref p) => {
1724                         try!(word(&mut self.s, "@"));
1725                         try!(self.print_pat(&**p));
1726                     }
1727                     None => (),
1728                 }
1729             }
1730             hir::PatEnum(ref path, ref args_) => {
1731                 try!(self.print_path(path, true, 0));
1732                 match *args_ {
1733                     None => try!(word(&mut self.s, "(..)")),
1734                     Some(ref args) => {
1735                         if !args.is_empty() {
1736                             try!(self.popen());
1737                             try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&**p)));
1738                             try!(self.pclose());
1739                         }
1740                     }
1741                 }
1742             }
1743             hir::PatQPath(ref qself, ref path) => {
1744                 try!(self.print_qpath(path, qself, false));
1745             }
1746             hir::PatStruct(ref path, ref fields, etc) => {
1747                 try!(self.print_path(path, true, 0));
1748                 try!(self.nbsp());
1749                 try!(self.word_space("{"));
1750                 try!(self.commasep_cmnt(Consistent,
1751                                         &fields[..],
1752                                         |s, f| {
1753                                             try!(s.cbox(indent_unit));
1754                                             if !f.node.is_shorthand {
1755                                                 try!(s.print_name(f.node.name));
1756                                                 try!(s.word_nbsp(":"));
1757                                             }
1758                                             try!(s.print_pat(&*f.node.pat));
1759                                             s.end()
1760                                         },
1761                                         |f| f.node.pat.span));
1762                 if etc {
1763                     if !fields.is_empty() {
1764                         try!(self.word_space(","));
1765                     }
1766                     try!(word(&mut self.s, ".."));
1767                 }
1768                 try!(space(&mut self.s));
1769                 try!(word(&mut self.s, "}"));
1770             }
1771             hir::PatTup(ref elts) => {
1772                 try!(self.popen());
1773                 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&**p)));
1774                 if elts.len() == 1 {
1775                     try!(word(&mut self.s, ","));
1776                 }
1777                 try!(self.pclose());
1778             }
1779             hir::PatBox(ref inner) => {
1780                 try!(word(&mut self.s, "box "));
1781                 try!(self.print_pat(&**inner));
1782             }
1783             hir::PatRegion(ref inner, mutbl) => {
1784                 try!(word(&mut self.s, "&"));
1785                 if mutbl == hir::MutMutable {
1786                     try!(word(&mut self.s, "mut "));
1787                 }
1788                 try!(self.print_pat(&**inner));
1789             }
1790             hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1791             hir::PatRange(ref begin, ref end) => {
1792                 try!(self.print_expr(&**begin));
1793                 try!(space(&mut self.s));
1794                 try!(word(&mut self.s, "..."));
1795                 try!(self.print_expr(&**end));
1796             }
1797             hir::PatVec(ref before, ref slice, ref after) => {
1798                 try!(word(&mut self.s, "["));
1799                 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&**p)));
1800                 if let Some(ref p) = *slice {
1801                     if !before.is_empty() {
1802                         try!(self.word_space(","));
1803                     }
1804                     if p.node != hir::PatWild {
1805                         try!(self.print_pat(&**p));
1806                     }
1807                     try!(word(&mut self.s, ".."));
1808                     if !after.is_empty() {
1809                         try!(self.word_space(","));
1810                     }
1811                 }
1812                 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&**p)));
1813                 try!(word(&mut self.s, "]"));
1814             }
1815         }
1816         self.ann.post(self, NodePat(pat))
1817     }
1818
1819     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1820         // I have no idea why this check is necessary, but here it
1821         // is :(
1822         if arm.attrs.is_empty() {
1823             try!(space(&mut self.s));
1824         }
1825         try!(self.cbox(indent_unit));
1826         try!(self.ibox(0));
1827         try!(self.print_outer_attributes(&arm.attrs));
1828         let mut first = true;
1829         for p in &arm.pats {
1830             if first {
1831                 first = false;
1832             } else {
1833                 try!(space(&mut self.s));
1834                 try!(self.word_space("|"));
1835             }
1836             try!(self.print_pat(&**p));
1837         }
1838         try!(space(&mut self.s));
1839         if let Some(ref e) = arm.guard {
1840             try!(self.word_space("if"));
1841             try!(self.print_expr(&**e));
1842             try!(space(&mut self.s));
1843         }
1844         try!(self.word_space("=>"));
1845
1846         match arm.body.node {
1847             hir::ExprBlock(ref blk) => {
1848                 // the block will close the pattern's ibox
1849                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1850
1851                 // If it is a user-provided unsafe block, print a comma after it
1852                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1853                     try!(word(&mut self.s, ","));
1854                 }
1855             }
1856             _ => {
1857                 try!(self.end()); // close the ibox for the pattern
1858                 try!(self.print_expr(&*arm.body));
1859                 try!(word(&mut self.s, ","));
1860             }
1861         }
1862         self.end() // close enclosing cbox
1863     }
1864
1865     // Returns whether it printed anything
1866     fn print_explicit_self(&mut self,
1867                            explicit_self: &hir::ExplicitSelf_,
1868                            mutbl: hir::Mutability)
1869                            -> io::Result<bool> {
1870         try!(self.print_mutability(mutbl));
1871         match *explicit_self {
1872             hir::SelfStatic => {
1873                 return Ok(false);
1874             }
1875             hir::SelfValue(_) => {
1876                 try!(word(&mut self.s, "self"));
1877             }
1878             hir::SelfRegion(ref lt, m, _) => {
1879                 try!(word(&mut self.s, "&"));
1880                 try!(self.print_opt_lifetime(lt));
1881                 try!(self.print_mutability(m));
1882                 try!(word(&mut self.s, "self"));
1883             }
1884             hir::SelfExplicit(ref typ, _) => {
1885                 try!(word(&mut self.s, "self"));
1886                 try!(self.word_space(":"));
1887                 try!(self.print_type(&**typ));
1888             }
1889         }
1890         return Ok(true);
1891     }
1892
1893     pub fn print_fn(&mut self,
1894                     decl: &hir::FnDecl,
1895                     unsafety: hir::Unsafety,
1896                     constness: hir::Constness,
1897                     abi: abi::Abi,
1898                     name: Option<ast::Name>,
1899                     generics: &hir::Generics,
1900                     opt_explicit_self: Option<&hir::ExplicitSelf_>,
1901                     vis: hir::Visibility)
1902                     -> io::Result<()> {
1903         try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1904
1905         if let Some(name) = name {
1906             try!(self.nbsp());
1907             try!(self.print_name(name));
1908         }
1909         try!(self.print_generics(generics));
1910         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1911         self.print_where_clause(&generics.where_clause)
1912     }
1913
1914     pub fn print_fn_args(&mut self,
1915                          decl: &hir::FnDecl,
1916                          opt_explicit_self: Option<&hir::ExplicitSelf_>)
1917                          -> io::Result<()> {
1918         // It is unfortunate to duplicate the commasep logic, but we want the
1919         // self type and the args all in the same box.
1920         try!(self.rbox(0, Inconsistent));
1921         let mut first = true;
1922         if let Some(explicit_self) = opt_explicit_self {
1923             let m = match explicit_self {
1924                 &hir::SelfStatic => hir::MutImmutable,
1925                 _ => match decl.inputs[0].pat.node {
1926                     hir::PatIdent(hir::BindByValue(m), _, _) => m,
1927                     _ => hir::MutImmutable,
1928                 },
1929             };
1930             first = !try!(self.print_explicit_self(explicit_self, m));
1931         }
1932
1933         // HACK(eddyb) ignore the separately printed self argument.
1934         let args = if first {
1935             &decl.inputs[..]
1936         } else {
1937             &decl.inputs[1..]
1938         };
1939
1940         for arg in args {
1941             if first {
1942                 first = false;
1943             } else {
1944                 try!(self.word_space(","));
1945             }
1946             try!(self.print_arg(arg));
1947         }
1948
1949         self.end()
1950     }
1951
1952     pub fn print_fn_args_and_ret(&mut self,
1953                                  decl: &hir::FnDecl,
1954                                  opt_explicit_self: Option<&hir::ExplicitSelf_>)
1955                                  -> io::Result<()> {
1956         try!(self.popen());
1957         try!(self.print_fn_args(decl, opt_explicit_self));
1958         if decl.variadic {
1959             try!(word(&mut self.s, ", ..."));
1960         }
1961         try!(self.pclose());
1962
1963         self.print_fn_output(decl)
1964     }
1965
1966     pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1967         try!(word(&mut self.s, "|"));
1968         try!(self.print_fn_args(decl, None));
1969         try!(word(&mut self.s, "|"));
1970
1971         if let hir::DefaultReturn(..) = decl.output {
1972             return Ok(());
1973         }
1974
1975         try!(self.space_if_not_bol());
1976         try!(self.word_space("->"));
1977         match decl.output {
1978             hir::Return(ref ty) => {
1979                 try!(self.print_type(&**ty));
1980                 self.maybe_print_comment(ty.span.lo)
1981             }
1982             hir::DefaultReturn(..) => unreachable!(),
1983             hir::NoReturn(span) => {
1984                 try!(self.word_nbsp("!"));
1985                 self.maybe_print_comment(span.lo)
1986             }
1987         }
1988     }
1989
1990     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1991         match capture_clause {
1992             hir::CaptureByValue => self.word_space("move"),
1993             hir::CaptureByRef => Ok(()),
1994         }
1995     }
1996
1997     pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1998         if !bounds.is_empty() {
1999             try!(word(&mut self.s, prefix));
2000             let mut first = true;
2001             for bound in bounds {
2002                 try!(self.nbsp());
2003                 if first {
2004                     first = false;
2005                 } else {
2006                     try!(self.word_space("+"));
2007                 }
2008
2009                 try!(match *bound {
2010                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2011                         self.print_poly_trait_ref(tref)
2012                     }
2013                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2014                         try!(word(&mut self.s, "?"));
2015                         self.print_poly_trait_ref(tref)
2016                     }
2017                     RegionTyParamBound(ref lt) => {
2018                         self.print_lifetime(lt)
2019                     }
2020                 })
2021             }
2022             Ok(())
2023         } else {
2024             Ok(())
2025         }
2026     }
2027
2028     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2029         self.print_name(lifetime.name)
2030     }
2031
2032     pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2033         try!(self.print_lifetime(&lifetime.lifetime));
2034         let mut sep = ":";
2035         for v in &lifetime.bounds {
2036             try!(word(&mut self.s, sep));
2037             try!(self.print_lifetime(v));
2038             sep = "+";
2039         }
2040         Ok(())
2041     }
2042
2043     pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2044         let total = generics.lifetimes.len() + generics.ty_params.len();
2045         if total == 0 {
2046             return Ok(());
2047         }
2048
2049         try!(word(&mut self.s, "<"));
2050
2051         let mut ints = Vec::new();
2052         for i in 0..total {
2053             ints.push(i);
2054         }
2055
2056         try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2057             if idx < generics.lifetimes.len() {
2058                 let lifetime = &generics.lifetimes[idx];
2059                 s.print_lifetime_def(lifetime)
2060             } else {
2061                 let idx = idx - generics.lifetimes.len();
2062                 let param = &generics.ty_params[idx];
2063                 s.print_ty_param(param)
2064             }
2065         }));
2066
2067         try!(word(&mut self.s, ">"));
2068         Ok(())
2069     }
2070
2071     pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2072         try!(self.print_name(param.name));
2073         try!(self.print_bounds(":", &param.bounds));
2074         match param.default {
2075             Some(ref default) => {
2076                 try!(space(&mut self.s));
2077                 try!(self.word_space("="));
2078                 self.print_type(&**default)
2079             }
2080             _ => Ok(()),
2081         }
2082     }
2083
2084     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2085         if where_clause.predicates.is_empty() {
2086             return Ok(());
2087         }
2088
2089         try!(space(&mut self.s));
2090         try!(self.word_space("where"));
2091
2092         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2093             if i != 0 {
2094                 try!(self.word_space(","));
2095             }
2096
2097             match predicate {
2098                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2099                                                                               ref bounded_ty,
2100                                                                               ref bounds,
2101                                                                               ..}) => {
2102                     try!(self.print_formal_lifetime_list(bound_lifetimes));
2103                     try!(self.print_type(&**bounded_ty));
2104                     try!(self.print_bounds(":", bounds));
2105                 }
2106                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2107                                                                                 ref bounds,
2108                                                                                 ..}) => {
2109                     try!(self.print_lifetime(lifetime));
2110                     try!(word(&mut self.s, ":"));
2111
2112                     for (i, bound) in bounds.iter().enumerate() {
2113                         try!(self.print_lifetime(bound));
2114
2115                         if i != 0 {
2116                             try!(word(&mut self.s, ":"));
2117                         }
2118                     }
2119                 }
2120                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2121                     try!(self.print_path(path, false, 0));
2122                     try!(space(&mut self.s));
2123                     try!(self.word_space("="));
2124                     try!(self.print_type(&**ty));
2125                 }
2126             }
2127         }
2128
2129         Ok(())
2130     }
2131
2132     pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2133         match vp.node {
2134             hir::ViewPathSimple(name, ref path) => {
2135                 try!(self.print_path(path, false, 0));
2136
2137                 if path.segments.last().unwrap().identifier.name != name {
2138                     try!(space(&mut self.s));
2139                     try!(self.word_space("as"));
2140                     try!(self.print_name(name));
2141                 }
2142
2143                 Ok(())
2144             }
2145
2146             hir::ViewPathGlob(ref path) => {
2147                 try!(self.print_path(path, false, 0));
2148                 word(&mut self.s, "::*")
2149             }
2150
2151             hir::ViewPathList(ref path, ref segments) => {
2152                 if path.segments.is_empty() {
2153                     try!(word(&mut self.s, "{"));
2154                 } else {
2155                     try!(self.print_path(path, false, 0));
2156                     try!(word(&mut self.s, "::{"));
2157                 }
2158                 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2159                     match w.node {
2160                         hir::PathListIdent { name, .. } => {
2161                             s.print_name(name)
2162                         }
2163                         hir::PathListMod { .. } => {
2164                             word(&mut s.s, "self")
2165                         }
2166                     }
2167                 }));
2168                 word(&mut self.s, "}")
2169             }
2170         }
2171     }
2172
2173     pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2174         match mutbl {
2175             hir::MutMutable => self.word_nbsp("mut"),
2176             hir::MutImmutable => Ok(()),
2177         }
2178     }
2179
2180     pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2181         try!(self.print_mutability(mt.mutbl));
2182         self.print_type(&*mt.ty)
2183     }
2184
2185     pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2186         try!(self.ibox(indent_unit));
2187         match input.ty.node {
2188             hir::TyInfer => try!(self.print_pat(&*input.pat)),
2189             _ => {
2190                 match input.pat.node {
2191                     hir::PatIdent(_, ref path1, _) if
2192                         path1.node.name ==
2193                             parse::token::special_idents::invalid.name => {
2194                         // Do nothing.
2195                     }
2196                     _ => {
2197                         try!(self.print_pat(&*input.pat));
2198                         try!(word(&mut self.s, ":"));
2199                         try!(space(&mut self.s));
2200                     }
2201                 }
2202                 try!(self.print_type(&*input.ty));
2203             }
2204         }
2205         self.end()
2206     }
2207
2208     pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2209         if let hir::DefaultReturn(..) = decl.output {
2210             return Ok(());
2211         }
2212
2213         try!(self.space_if_not_bol());
2214         try!(self.ibox(indent_unit));
2215         try!(self.word_space("->"));
2216         match decl.output {
2217             hir::NoReturn(_) => try!(self.word_nbsp("!")),
2218             hir::DefaultReturn(..) => unreachable!(),
2219             hir::Return(ref ty) => try!(self.print_type(&**ty)),
2220         }
2221         try!(self.end());
2222
2223         match decl.output {
2224             hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2225             _ => Ok(()),
2226         }
2227     }
2228
2229     pub fn print_ty_fn(&mut self,
2230                        abi: abi::Abi,
2231                        unsafety: hir::Unsafety,
2232                        decl: &hir::FnDecl,
2233                        name: Option<ast::Name>,
2234                        generics: &hir::Generics,
2235                        opt_explicit_self: Option<&hir::ExplicitSelf_>)
2236                        -> io::Result<()> {
2237         try!(self.ibox(indent_unit));
2238         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2239             try!(word(&mut self.s, "for"));
2240             try!(self.print_generics(generics));
2241         }
2242         let generics = hir::Generics {
2243             lifetimes: Vec::new(),
2244             ty_params: OwnedSlice::empty(),
2245             where_clause: hir::WhereClause {
2246                 id: ast::DUMMY_NODE_ID,
2247                 predicates: Vec::new(),
2248             },
2249         };
2250         try!(self.print_fn(decl,
2251                            unsafety,
2252                            hir::Constness::NotConst,
2253                            abi,
2254                            name,
2255                            &generics,
2256                            opt_explicit_self,
2257                            hir::Inherited));
2258         self.end()
2259     }
2260
2261     pub fn maybe_print_trailing_comment(&mut self,
2262                                         span: codemap::Span,
2263                                         next_pos: Option<BytePos>)
2264                                         -> io::Result<()> {
2265         let cm = match self.cm {
2266             Some(cm) => cm,
2267             _ => return Ok(()),
2268         };
2269         match self.next_comment() {
2270             Some(ref cmnt) => {
2271                 if (*cmnt).style != comments::Trailing {
2272                     return Ok(());
2273                 }
2274                 let span_line = cm.lookup_char_pos(span.hi);
2275                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2276                 let mut next = (*cmnt).pos + BytePos(1);
2277                 match next_pos {
2278                     None => (),
2279                     Some(p) => next = p,
2280                 }
2281                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2282                    span_line.line == comment_line.line {
2283                     try!(self.print_comment(cmnt));
2284                     self.cur_cmnt_and_lit.cur_cmnt += 1;
2285                 }
2286             }
2287             _ => (),
2288         }
2289         Ok(())
2290     }
2291
2292     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2293         // If there aren't any remaining comments, then we need to manually
2294         // make sure there is a line break at the end.
2295         if self.next_comment().is_none() {
2296             try!(hardbreak(&mut self.s));
2297         }
2298         loop {
2299             match self.next_comment() {
2300                 Some(ref cmnt) => {
2301                     try!(self.print_comment(cmnt));
2302                     self.cur_cmnt_and_lit.cur_cmnt += 1;
2303                 }
2304                 _ => break,
2305             }
2306         }
2307         Ok(())
2308     }
2309
2310     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2311                                                   opt_abi: Option<abi::Abi>)
2312                                                   -> io::Result<()> {
2313         match opt_abi {
2314             Some(abi::Rust) => Ok(()),
2315             Some(abi) => {
2316                 try!(self.word_nbsp("extern"));
2317                 self.word_nbsp(&abi.to_string())
2318             }
2319             None => Ok(()),
2320         }
2321     }
2322
2323     pub fn print_extern_opt_abi(&mut self, opt_abi: Option<abi::Abi>) -> io::Result<()> {
2324         match opt_abi {
2325             Some(abi) => {
2326                 try!(self.word_nbsp("extern"));
2327                 self.word_nbsp(&abi.to_string())
2328             }
2329             None => Ok(()),
2330         }
2331     }
2332
2333     pub fn print_fn_header_info(&mut self,
2334                                 unsafety: hir::Unsafety,
2335                                 constness: hir::Constness,
2336                                 abi: abi::Abi,
2337                                 vis: hir::Visibility)
2338                                 -> io::Result<()> {
2339         try!(word(&mut self.s, &visibility_qualified(vis, "")));
2340         try!(self.print_unsafety(unsafety));
2341
2342         match constness {
2343             hir::Constness::NotConst => {}
2344             hir::Constness::Const => try!(self.word_nbsp("const")),
2345         }
2346
2347         if abi != abi::Rust {
2348             try!(self.word_nbsp("extern"));
2349             try!(self.word_nbsp(&abi.to_string()));
2350         }
2351
2352         word(&mut self.s, "fn")
2353     }
2354
2355     pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2356         match s {
2357             hir::Unsafety::Normal => Ok(()),
2358             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2359         }
2360     }
2361 }
2362
2363 // Dup'ed from parse::classify, but adapted for the HIR.
2364 /// Does this expression require a semicolon to be treated
2365 /// as a statement? The negation of this: 'can this expression
2366 /// be used as a statement without a semicolon' -- is used
2367 /// as an early-bail-out in the parser so that, for instance,
2368 ///     if true {...} else {...}
2369 ///      |x| 5
2370 /// isn't parsed as (if true {...} else {...} | x) | 5
2371 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2372     match e.node {
2373         hir::ExprIf(..) |
2374         hir::ExprMatch(..) |
2375         hir::ExprBlock(_) |
2376         hir::ExprWhile(..) |
2377         hir::ExprLoop(..) => false,
2378         _ => true,
2379     }
2380 }
2381
2382 /// this statement requires a semicolon after it.
2383 /// note that in one case (stmt_semi), we've already
2384 /// seen the semicolon, and thus don't need another.
2385 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2386     match *stmt {
2387         hir::StmtDecl(ref d, _) => {
2388             match d.node {
2389                 hir::DeclLocal(_) => true,
2390                 hir::DeclItem(_) => false,
2391             }
2392         }
2393         hir::StmtExpr(ref e, _) => {
2394             expr_requires_semi_to_be_stmt(&**e)
2395         }
2396         hir::StmtSemi(..) => {
2397             false
2398         }
2399     }
2400 }