]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/print/pprust.rs
Auto merge of #29531 - bltavares:issue-28586, r=sanxiyn
[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::TyBareFn(ref f) => {
510                 let generics = hir::Generics {
511                     lifetimes: f.lifetimes.clone(),
512                     ty_params: OwnedSlice::empty(),
513                     where_clause: hir::WhereClause {
514                         id: ast::DUMMY_NODE_ID,
515                         predicates: Vec::new(),
516                     },
517                 };
518                 try!(self.print_ty_fn(f.abi, f.unsafety, &*f.decl, None, &generics, None));
519             }
520             hir::TyPath(None, ref path) => {
521                 try!(self.print_path(path, false, 0));
522             }
523             hir::TyPath(Some(ref qself), ref path) => {
524                 try!(self.print_qpath(path, qself, false))
525             }
526             hir::TyObjectSum(ref ty, ref bounds) => {
527                 try!(self.print_type(&**ty));
528                 try!(self.print_bounds("+", &bounds[..]));
529             }
530             hir::TyPolyTraitRef(ref bounds) => {
531                 try!(self.print_bounds("", &bounds[..]));
532             }
533             hir::TyFixedLengthVec(ref ty, ref v) => {
534                 try!(word(&mut self.s, "["));
535                 try!(self.print_type(&**ty));
536                 try!(word(&mut self.s, "; "));
537                 try!(self.print_expr(&**v));
538                 try!(word(&mut self.s, "]"));
539             }
540             hir::TyTypeof(ref e) => {
541                 try!(word(&mut self.s, "typeof("));
542                 try!(self.print_expr(&**e));
543                 try!(word(&mut self.s, ")"));
544             }
545             hir::TyInfer => {
546                 try!(word(&mut self.s, "_"));
547             }
548         }
549         self.end()
550     }
551
552     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
553         try!(self.hardbreak_if_not_bol());
554         try!(self.maybe_print_comment(item.span.lo));
555         try!(self.print_outer_attributes(&item.attrs));
556         match item.node {
557             hir::ForeignItemFn(ref decl, ref generics) => {
558                 try!(self.head(""));
559                 try!(self.print_fn(decl,
560                                    hir::Unsafety::Normal,
561                                    hir::Constness::NotConst,
562                                    abi::Rust,
563                                    Some(item.name),
564                                    generics,
565                                    None,
566                                    item.vis));
567                 try!(self.end()); // end head-ibox
568                 try!(word(&mut self.s, ";"));
569                 self.end() // end the outer fn box
570             }
571             hir::ForeignItemStatic(ref t, m) => {
572                 try!(self.head(&visibility_qualified(item.vis, "static")));
573                 if m {
574                     try!(self.word_space("mut"));
575                 }
576                 try!(self.print_name(item.name));
577                 try!(self.word_space(":"));
578                 try!(self.print_type(&**t));
579                 try!(word(&mut self.s, ";"));
580                 try!(self.end()); // end the head-ibox
581                 self.end() // end the outer cbox
582             }
583         }
584     }
585
586     fn print_associated_const(&mut self,
587                               name: ast::Name,
588                               ty: &hir::Ty,
589                               default: Option<&hir::Expr>,
590                               vis: hir::Visibility)
591                               -> io::Result<()> {
592         try!(word(&mut self.s, &visibility_qualified(vis, "")));
593         try!(self.word_space("const"));
594         try!(self.print_name(name));
595         try!(self.word_space(":"));
596         try!(self.print_type(ty));
597         if let Some(expr) = default {
598             try!(space(&mut self.s));
599             try!(self.word_space("="));
600             try!(self.print_expr(expr));
601         }
602         word(&mut self.s, ";")
603     }
604
605     fn print_associated_type(&mut self,
606                              name: ast::Name,
607                              bounds: Option<&hir::TyParamBounds>,
608                              ty: Option<&hir::Ty>)
609                              -> io::Result<()> {
610         try!(self.word_space("type"));
611         try!(self.print_name(name));
612         if let Some(bounds) = bounds {
613             try!(self.print_bounds(":", bounds));
614         }
615         if let Some(ty) = ty {
616             try!(space(&mut self.s));
617             try!(self.word_space("="));
618             try!(self.print_type(ty));
619         }
620         word(&mut self.s, ";")
621     }
622
623     /// Pretty-print an item
624     pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
625         try!(self.hardbreak_if_not_bol());
626         try!(self.maybe_print_comment(item.span.lo));
627         try!(self.print_outer_attributes(&item.attrs));
628         try!(self.ann.pre(self, NodeItem(item)));
629         match item.node {
630             hir::ItemExternCrate(ref optional_path) => {
631                 try!(self.head(&visibility_qualified(item.vis, "extern crate")));
632                 if let Some(p) = *optional_path {
633                     let val = p.as_str();
634                     if val.contains("-") {
635                         try!(self.print_string(&val, ast::CookedStr));
636                     } else {
637                         try!(self.print_name(p));
638                     }
639                     try!(space(&mut self.s));
640                     try!(word(&mut self.s, "as"));
641                     try!(space(&mut self.s));
642                 }
643                 try!(self.print_name(item.name));
644                 try!(word(&mut self.s, ";"));
645                 try!(self.end()); // end inner head-block
646                 try!(self.end()); // end outer head-block
647             }
648             hir::ItemUse(ref vp) => {
649                 try!(self.head(&visibility_qualified(item.vis, "use")));
650                 try!(self.print_view_path(&**vp));
651                 try!(word(&mut self.s, ";"));
652                 try!(self.end()); // end inner head-block
653                 try!(self.end()); // end outer head-block
654             }
655             hir::ItemStatic(ref ty, m, ref expr) => {
656                 try!(self.head(&visibility_qualified(item.vis, "static")));
657                 if m == hir::MutMutable {
658                     try!(self.word_space("mut"));
659                 }
660                 try!(self.print_name(item.name));
661                 try!(self.word_space(":"));
662                 try!(self.print_type(&**ty));
663                 try!(space(&mut self.s));
664                 try!(self.end()); // end the head-ibox
665
666                 try!(self.word_space("="));
667                 try!(self.print_expr(&**expr));
668                 try!(word(&mut self.s, ";"));
669                 try!(self.end()); // end the outer cbox
670             }
671             hir::ItemConst(ref ty, ref expr) => {
672                 try!(self.head(&visibility_qualified(item.vis, "const")));
673                 try!(self.print_name(item.name));
674                 try!(self.word_space(":"));
675                 try!(self.print_type(&**ty));
676                 try!(space(&mut self.s));
677                 try!(self.end()); // end the head-ibox
678
679                 try!(self.word_space("="));
680                 try!(self.print_expr(&**expr));
681                 try!(word(&mut self.s, ";"));
682                 try!(self.end()); // end the outer cbox
683             }
684             hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
685                 try!(self.head(""));
686                 try!(self.print_fn(decl,
687                                    unsafety,
688                                    constness,
689                                    abi,
690                                    Some(item.name),
691                                    typarams,
692                                    None,
693                                    item.vis));
694                 try!(word(&mut self.s, " "));
695                 try!(self.print_block_with_attrs(&**body, &item.attrs));
696             }
697             hir::ItemMod(ref _mod) => {
698                 try!(self.head(&visibility_qualified(item.vis, "mod")));
699                 try!(self.print_name(item.name));
700                 try!(self.nbsp());
701                 try!(self.bopen());
702                 try!(self.print_mod(_mod, &item.attrs));
703                 try!(self.bclose(item.span));
704             }
705             hir::ItemForeignMod(ref nmod) => {
706                 try!(self.head("extern"));
707                 try!(self.word_nbsp(&nmod.abi.to_string()));
708                 try!(self.bopen());
709                 try!(self.print_foreign_mod(nmod, &item.attrs));
710                 try!(self.bclose(item.span));
711             }
712             hir::ItemTy(ref ty, ref params) => {
713                 try!(self.ibox(indent_unit));
714                 try!(self.ibox(0));
715                 try!(self.word_nbsp(&visibility_qualified(item.vis, "type")));
716                 try!(self.print_name(item.name));
717                 try!(self.print_generics(params));
718                 try!(self.end()); // end the inner ibox
719
720                 try!(self.print_where_clause(&params.where_clause));
721                 try!(space(&mut self.s));
722                 try!(self.word_space("="));
723                 try!(self.print_type(&**ty));
724                 try!(word(&mut self.s, ";"));
725                 try!(self.end()); // end the outer ibox
726             }
727             hir::ItemEnum(ref enum_definition, ref params) => {
728                 try!(self.print_enum_def(enum_definition, params, item.name, item.span, item.vis));
729             }
730             hir::ItemStruct(ref struct_def, ref generics) => {
731                 try!(self.head(&visibility_qualified(item.vis, "struct")));
732                 try!(self.print_struct(struct_def, generics, item.name, item.span, true));
733             }
734
735             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
736                 try!(self.head(""));
737                 try!(self.print_visibility(item.vis));
738                 try!(self.print_unsafety(unsafety));
739                 try!(self.word_nbsp("impl"));
740                 try!(self.print_trait_ref(trait_ref));
741                 try!(space(&mut self.s));
742                 try!(self.word_space("for"));
743                 try!(self.word_space(".."));
744                 try!(self.bopen());
745                 try!(self.bclose(item.span));
746             }
747             hir::ItemImpl(unsafety,
748                           polarity,
749                           ref generics,
750                           ref opt_trait,
751                           ref ty,
752                           ref impl_items) => {
753                 try!(self.head(""));
754                 try!(self.print_visibility(item.vis));
755                 try!(self.print_unsafety(unsafety));
756                 try!(self.word_nbsp("impl"));
757
758                 if generics.is_parameterized() {
759                     try!(self.print_generics(generics));
760                     try!(space(&mut self.s));
761                 }
762
763                 match polarity {
764                     hir::ImplPolarity::Negative => {
765                         try!(word(&mut self.s, "!"));
766                     }
767                     _ => {}
768                 }
769
770                 match opt_trait {
771                     &Some(ref t) => {
772                         try!(self.print_trait_ref(t));
773                         try!(space(&mut self.s));
774                         try!(self.word_space("for"));
775                     }
776                     &None => {}
777                 }
778
779                 try!(self.print_type(&**ty));
780                 try!(self.print_where_clause(&generics.where_clause));
781
782                 try!(space(&mut self.s));
783                 try!(self.bopen());
784                 try!(self.print_inner_attributes(&item.attrs));
785                 for impl_item in impl_items {
786                     try!(self.print_impl_item(impl_item));
787                 }
788                 try!(self.bclose(item.span));
789             }
790             hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
791                 try!(self.head(""));
792                 try!(self.print_visibility(item.vis));
793                 try!(self.print_unsafety(unsafety));
794                 try!(self.word_nbsp("trait"));
795                 try!(self.print_name(item.name));
796                 try!(self.print_generics(generics));
797                 let mut real_bounds = Vec::with_capacity(bounds.len());
798                 for b in bounds.iter() {
799                     if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
800                         try!(space(&mut self.s));
801                         try!(self.word_space("for ?"));
802                         try!(self.print_trait_ref(&ptr.trait_ref));
803                     } else {
804                         real_bounds.push(b.clone());
805                     }
806                 }
807                 try!(self.print_bounds(":", &real_bounds[..]));
808                 try!(self.print_where_clause(&generics.where_clause));
809                 try!(word(&mut self.s, " "));
810                 try!(self.bopen());
811                 for trait_item in trait_items {
812                     try!(self.print_trait_item(trait_item));
813                 }
814                 try!(self.bclose(item.span));
815             }
816         }
817         self.ann.post(self, NodeItem(item))
818     }
819
820     fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
821         self.print_path(&t.path, false, 0)
822     }
823
824     fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
825         if !lifetimes.is_empty() {
826             try!(word(&mut self.s, "for<"));
827             let mut comma = false;
828             for lifetime_def in lifetimes {
829                 if comma {
830                     try!(self.word_space(","))
831                 }
832                 try!(self.print_lifetime_def(lifetime_def));
833                 comma = true;
834             }
835             try!(word(&mut self.s, ">"));
836         }
837         Ok(())
838     }
839
840     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
841         try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
842         self.print_trait_ref(&t.trait_ref)
843     }
844
845     pub fn print_enum_def(&mut self,
846                           enum_definition: &hir::EnumDef,
847                           generics: &hir::Generics,
848                           name: ast::Name,
849                           span: codemap::Span,
850                           visibility: hir::Visibility)
851                           -> io::Result<()> {
852         try!(self.head(&visibility_qualified(visibility, "enum")));
853         try!(self.print_name(name));
854         try!(self.print_generics(generics));
855         try!(self.print_where_clause(&generics.where_clause));
856         try!(space(&mut self.s));
857         self.print_variants(&enum_definition.variants, span)
858     }
859
860     pub fn print_variants(&mut self,
861                           variants: &[P<hir::Variant>],
862                           span: codemap::Span)
863                           -> io::Result<()> {
864         try!(self.bopen());
865         for v in variants {
866             try!(self.space_if_not_bol());
867             try!(self.maybe_print_comment(v.span.lo));
868             try!(self.print_outer_attributes(&v.node.attrs));
869             try!(self.ibox(indent_unit));
870             try!(self.print_variant(&**v));
871             try!(word(&mut self.s, ","));
872             try!(self.end());
873             try!(self.maybe_print_trailing_comment(v.span, None));
874         }
875         self.bclose(span)
876     }
877
878     pub fn print_visibility(&mut self, vis: hir::Visibility) -> io::Result<()> {
879         match vis {
880             hir::Public => self.word_nbsp("pub"),
881             hir::Inherited => Ok(()),
882         }
883     }
884
885     pub fn print_struct(&mut self,
886                         struct_def: &hir::VariantData,
887                         generics: &hir::Generics,
888                         name: ast::Name,
889                         span: codemap::Span,
890                         print_finalizer: bool)
891                         -> io::Result<()> {
892         try!(self.print_name(name));
893         try!(self.print_generics(generics));
894         if !struct_def.is_struct() {
895             if struct_def.is_tuple() {
896                 try!(self.popen());
897                 try!(self.commasep(Inconsistent, struct_def.fields(), |s, field| {
898                     match field.node.kind {
899                         hir::NamedField(..) => panic!("unexpected named field"),
900                         hir::UnnamedField(vis) => {
901                             try!(s.print_visibility(vis));
902                             try!(s.maybe_print_comment(field.span.lo));
903                             s.print_type(&*field.node.ty)
904                         }
905                     }
906                 }));
907                 try!(self.pclose());
908             }
909             try!(self.print_where_clause(&generics.where_clause));
910             if print_finalizer {
911                 try!(word(&mut self.s, ";"));
912             }
913             try!(self.end());
914             self.end() // close the outer-box
915         } else {
916             try!(self.print_where_clause(&generics.where_clause));
917             try!(self.nbsp());
918             try!(self.bopen());
919             try!(self.hardbreak_if_not_bol());
920
921             for field in struct_def.fields() {
922                 match field.node.kind {
923                     hir::UnnamedField(..) => panic!("unexpected unnamed field"),
924                     hir::NamedField(name, visibility) => {
925                         try!(self.hardbreak_if_not_bol());
926                         try!(self.maybe_print_comment(field.span.lo));
927                         try!(self.print_outer_attributes(&field.node.attrs));
928                         try!(self.print_visibility(visibility));
929                         try!(self.print_name(name));
930                         try!(self.word_nbsp(":"));
931                         try!(self.print_type(&*field.node.ty));
932                         try!(word(&mut self.s, ","));
933                     }
934                 }
935             }
936
937             self.bclose(span)
938         }
939     }
940
941     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
942         try!(self.head(""));
943         let generics = ::util::empty_generics();
944         try!(self.print_struct(&v.node.data, &generics, v.node.name, v.span, false));
945         match v.node.disr_expr {
946             Some(ref d) => {
947                 try!(space(&mut self.s));
948                 try!(self.word_space("="));
949                 self.print_expr(&**d)
950             }
951             _ => Ok(()),
952         }
953     }
954
955     pub fn print_method_sig(&mut self,
956                             name: ast::Name,
957                             m: &hir::MethodSig,
958                             vis: hir::Visibility)
959                             -> io::Result<()> {
960         self.print_fn(&m.decl,
961                       m.unsafety,
962                       m.constness,
963                       m.abi,
964                       Some(name),
965                       &m.generics,
966                       Some(&m.explicit_self.node),
967                       vis)
968     }
969
970     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
971         try!(self.ann.pre(self, NodeSubItem(ti.id)));
972         try!(self.hardbreak_if_not_bol());
973         try!(self.maybe_print_comment(ti.span.lo));
974         try!(self.print_outer_attributes(&ti.attrs));
975         match ti.node {
976             hir::ConstTraitItem(ref ty, ref default) => {
977                 try!(self.print_associated_const(ti.name,
978                                                  &ty,
979                                                  default.as_ref().map(|expr| &**expr),
980                                                  hir::Inherited));
981             }
982             hir::MethodTraitItem(ref sig, ref body) => {
983                 if body.is_some() {
984                     try!(self.head(""));
985                 }
986                 try!(self.print_method_sig(ti.name, sig, hir::Inherited));
987                 if let Some(ref body) = *body {
988                     try!(self.nbsp());
989                     try!(self.print_block_with_attrs(body, &ti.attrs));
990                 } else {
991                     try!(word(&mut self.s, ";"));
992                 }
993             }
994             hir::TypeTraitItem(ref bounds, ref default) => {
995                 try!(self.print_associated_type(ti.name,
996                                                 Some(bounds),
997                                                 default.as_ref().map(|ty| &**ty)));
998             }
999         }
1000         self.ann.post(self, NodeSubItem(ti.id))
1001     }
1002
1003     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1004         try!(self.ann.pre(self, NodeSubItem(ii.id)));
1005         try!(self.hardbreak_if_not_bol());
1006         try!(self.maybe_print_comment(ii.span.lo));
1007         try!(self.print_outer_attributes(&ii.attrs));
1008         match ii.node {
1009             hir::ConstImplItem(ref ty, ref expr) => {
1010                 try!(self.print_associated_const(ii.name, &ty, Some(&expr), ii.vis));
1011             }
1012             hir::MethodImplItem(ref sig, ref body) => {
1013                 try!(self.head(""));
1014                 try!(self.print_method_sig(ii.name, sig, ii.vis));
1015                 try!(self.nbsp());
1016                 try!(self.print_block_with_attrs(body, &ii.attrs));
1017             }
1018             hir::TypeImplItem(ref ty) => {
1019                 try!(self.print_associated_type(ii.name, None, Some(ty)));
1020             }
1021         }
1022         self.ann.post(self, NodeSubItem(ii.id))
1023     }
1024
1025     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1026         try!(self.maybe_print_comment(st.span.lo));
1027         match st.node {
1028             hir::StmtDecl(ref decl, _) => {
1029                 try!(self.print_decl(&**decl));
1030             }
1031             hir::StmtExpr(ref expr, _) => {
1032                 try!(self.space_if_not_bol());
1033                 try!(self.print_expr(&**expr));
1034             }
1035             hir::StmtSemi(ref expr, _) => {
1036                 try!(self.space_if_not_bol());
1037                 try!(self.print_expr(&**expr));
1038                 try!(word(&mut self.s, ";"));
1039             }
1040         }
1041         if stmt_ends_with_semi(&st.node) {
1042             try!(word(&mut self.s, ";"));
1043         }
1044         self.maybe_print_trailing_comment(st.span, None)
1045     }
1046
1047     pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1048         self.print_block_with_attrs(blk, &[])
1049     }
1050
1051     pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1052         self.print_block_unclosed_indent(blk, indent_unit)
1053     }
1054
1055     pub fn print_block_unclosed_indent(&mut self,
1056                                        blk: &hir::Block,
1057                                        indented: usize)
1058                                        -> io::Result<()> {
1059         self.print_block_maybe_unclosed(blk, indented, &[], false)
1060     }
1061
1062     pub fn print_block_with_attrs(&mut self,
1063                                   blk: &hir::Block,
1064                                   attrs: &[ast::Attribute])
1065                                   -> io::Result<()> {
1066         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1067     }
1068
1069     pub fn print_block_maybe_unclosed(&mut self,
1070                                       blk: &hir::Block,
1071                                       indented: usize,
1072                                       attrs: &[ast::Attribute],
1073                                       close_box: bool)
1074                                       -> io::Result<()> {
1075         match blk.rules {
1076             hir::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1077             hir::PushUnsafeBlock(..) => try!(self.word_space("push_unsafe")),
1078             hir::PopUnsafeBlock(..) => try!(self.word_space("pop_unsafe")),
1079             hir::PushUnstableBlock => try!(self.word_space("push_unstable")),
1080             hir::PopUnstableBlock => try!(self.word_space("pop_unstable")),
1081             hir::DefaultBlock => (),
1082         }
1083         try!(self.maybe_print_comment(blk.span.lo));
1084         try!(self.ann.pre(self, NodeBlock(blk)));
1085         try!(self.bopen());
1086
1087         try!(self.print_inner_attributes(attrs));
1088
1089         for st in &blk.stmts {
1090             try!(self.print_stmt(&**st));
1091         }
1092         match blk.expr {
1093             Some(ref expr) => {
1094                 try!(self.space_if_not_bol());
1095                 try!(self.print_expr(&**expr));
1096                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1097             }
1098             _ => (),
1099         }
1100         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1101         self.ann.post(self, NodeBlock(blk))
1102     }
1103
1104     fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1105         match els {
1106             Some(_else) => {
1107                 match _else.node {
1108                     // "another else-if"
1109                     hir::ExprIf(ref i, ref then, ref e) => {
1110                         try!(self.cbox(indent_unit - 1));
1111                         try!(self.ibox(0));
1112                         try!(word(&mut self.s, " else if "));
1113                         try!(self.print_expr(&**i));
1114                         try!(space(&mut self.s));
1115                         try!(self.print_block(&**then));
1116                         self.print_else(e.as_ref().map(|e| &**e))
1117                     }
1118                     // "final else"
1119                     hir::ExprBlock(ref b) => {
1120                         try!(self.cbox(indent_unit - 1));
1121                         try!(self.ibox(0));
1122                         try!(word(&mut self.s, " else "));
1123                         self.print_block(&**b)
1124                     }
1125                     // BLEAH, constraints would be great here
1126                     _ => {
1127                         panic!("print_if saw if with weird alternative");
1128                     }
1129                 }
1130             }
1131             _ => Ok(()),
1132         }
1133     }
1134
1135     pub fn print_if(&mut self,
1136                     test: &hir::Expr,
1137                     blk: &hir::Block,
1138                     elseopt: Option<&hir::Expr>)
1139                     -> io::Result<()> {
1140         try!(self.head("if"));
1141         try!(self.print_expr(test));
1142         try!(space(&mut self.s));
1143         try!(self.print_block(blk));
1144         self.print_else(elseopt)
1145     }
1146
1147     pub fn print_if_let(&mut self,
1148                         pat: &hir::Pat,
1149                         expr: &hir::Expr,
1150                         blk: &hir::Block,
1151                         elseopt: Option<&hir::Expr>)
1152                         -> io::Result<()> {
1153         try!(self.head("if let"));
1154         try!(self.print_pat(pat));
1155         try!(space(&mut self.s));
1156         try!(self.word_space("="));
1157         try!(self.print_expr(expr));
1158         try!(space(&mut self.s));
1159         try!(self.print_block(blk));
1160         self.print_else(elseopt)
1161     }
1162
1163
1164     fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1165         try!(self.popen());
1166         try!(self.commasep_exprs(Inconsistent, args));
1167         self.pclose()
1168     }
1169
1170     pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1171         let needs_par = needs_parentheses(expr);
1172         if needs_par {
1173             try!(self.popen());
1174         }
1175         try!(self.print_expr(expr));
1176         if needs_par {
1177             try!(self.pclose());
1178         }
1179         Ok(())
1180     }
1181
1182     fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1183         try!(self.ibox(indent_unit));
1184         try!(word(&mut self.s, "["));
1185         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1186         try!(word(&mut self.s, "]"));
1187         self.end()
1188     }
1189
1190     fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1191         try!(self.ibox(indent_unit));
1192         try!(word(&mut self.s, "["));
1193         try!(self.print_expr(element));
1194         try!(self.word_space(";"));
1195         try!(self.print_expr(count));
1196         try!(word(&mut self.s, "]"));
1197         self.end()
1198     }
1199
1200     fn print_expr_struct(&mut self,
1201                          path: &hir::Path,
1202                          fields: &[hir::Field],
1203                          wth: &Option<P<hir::Expr>>)
1204                          -> io::Result<()> {
1205         try!(self.print_path(path, true, 0));
1206         try!(word(&mut self.s, "{"));
1207         try!(self.commasep_cmnt(Consistent,
1208                                 &fields[..],
1209                                 |s, field| {
1210                                     try!(s.ibox(indent_unit));
1211                                     try!(s.print_name(field.name.node));
1212                                     try!(s.word_space(":"));
1213                                     try!(s.print_expr(&*field.expr));
1214                                     s.end()
1215                                 },
1216                                 |f| f.span));
1217         match *wth {
1218             Some(ref expr) => {
1219                 try!(self.ibox(indent_unit));
1220                 if !fields.is_empty() {
1221                     try!(word(&mut self.s, ","));
1222                     try!(space(&mut self.s));
1223                 }
1224                 try!(word(&mut self.s, ".."));
1225                 try!(self.print_expr(&**expr));
1226                 try!(self.end());
1227             }
1228             _ => if !fields.is_empty() {
1229                 try!(word(&mut self.s, ","))
1230             },
1231         }
1232         try!(word(&mut self.s, "}"));
1233         Ok(())
1234     }
1235
1236     fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1237         try!(self.popen());
1238         try!(self.commasep_exprs(Inconsistent, &exprs[..]));
1239         if exprs.len() == 1 {
1240             try!(word(&mut self.s, ","));
1241         }
1242         self.pclose()
1243     }
1244
1245     fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1246         try!(self.print_expr_maybe_paren(func));
1247         self.print_call_post(args)
1248     }
1249
1250     fn print_expr_method_call(&mut self,
1251                               name: Spanned<ast::Name>,
1252                               tys: &[P<hir::Ty>],
1253                               args: &[P<hir::Expr>])
1254                               -> io::Result<()> {
1255         let base_args = &args[1..];
1256         try!(self.print_expr(&*args[0]));
1257         try!(word(&mut self.s, "."));
1258         try!(self.print_name(name.node));
1259         if !tys.is_empty() {
1260             try!(word(&mut self.s, "::<"));
1261             try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty)));
1262             try!(word(&mut self.s, ">"));
1263         }
1264         self.print_call_post(base_args)
1265     }
1266
1267     fn print_expr_binary(&mut self,
1268                          op: hir::BinOp,
1269                          lhs: &hir::Expr,
1270                          rhs: &hir::Expr)
1271                          -> io::Result<()> {
1272         try!(self.print_expr(lhs));
1273         try!(space(&mut self.s));
1274         try!(self.word_space(::util::binop_to_string(op.node)));
1275         self.print_expr(rhs)
1276     }
1277
1278     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1279         try!(word(&mut self.s, ::util::unop_to_string(op)));
1280         self.print_expr_maybe_paren(expr)
1281     }
1282
1283     fn print_expr_addr_of(&mut self,
1284                           mutability: hir::Mutability,
1285                           expr: &hir::Expr)
1286                           -> io::Result<()> {
1287         try!(word(&mut self.s, "&"));
1288         try!(self.print_mutability(mutability));
1289         self.print_expr_maybe_paren(expr)
1290     }
1291
1292     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1293         try!(self.maybe_print_comment(expr.span.lo));
1294         try!(self.ibox(indent_unit));
1295         try!(self.ann.pre(self, NodeExpr(expr)));
1296         match expr.node {
1297             hir::ExprBox(ref expr) => {
1298                 try!(self.word_space("box"));
1299                 try!(self.print_expr(expr));
1300             }
1301             hir::ExprVec(ref exprs) => {
1302                 try!(self.print_expr_vec(&exprs[..]));
1303             }
1304             hir::ExprRepeat(ref element, ref count) => {
1305                 try!(self.print_expr_repeat(&**element, &**count));
1306             }
1307             hir::ExprStruct(ref path, ref fields, ref wth) => {
1308                 try!(self.print_expr_struct(path, &fields[..], wth));
1309             }
1310             hir::ExprTup(ref exprs) => {
1311                 try!(self.print_expr_tup(&exprs[..]));
1312             }
1313             hir::ExprCall(ref func, ref args) => {
1314                 try!(self.print_expr_call(&**func, &args[..]));
1315             }
1316             hir::ExprMethodCall(name, ref tys, ref args) => {
1317                 try!(self.print_expr_method_call(name, &tys[..], &args[..]));
1318             }
1319             hir::ExprBinary(op, ref lhs, ref rhs) => {
1320                 try!(self.print_expr_binary(op, &**lhs, &**rhs));
1321             }
1322             hir::ExprUnary(op, ref expr) => {
1323                 try!(self.print_expr_unary(op, &**expr));
1324             }
1325             hir::ExprAddrOf(m, ref expr) => {
1326                 try!(self.print_expr_addr_of(m, &**expr));
1327             }
1328             hir::ExprLit(ref lit) => {
1329                 try!(self.print_literal(&**lit));
1330             }
1331             hir::ExprCast(ref expr, ref ty) => {
1332                 try!(self.print_expr(&**expr));
1333                 try!(space(&mut self.s));
1334                 try!(self.word_space("as"));
1335                 try!(self.print_type(&**ty));
1336             }
1337             hir::ExprIf(ref test, ref blk, ref elseopt) => {
1338                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1339             }
1340             hir::ExprWhile(ref test, ref blk, opt_ident) => {
1341                 if let Some(ident) = opt_ident {
1342                     try!(self.print_name(ident.name));
1343                     try!(self.word_space(":"));
1344                 }
1345                 try!(self.head("while"));
1346                 try!(self.print_expr(&**test));
1347                 try!(space(&mut self.s));
1348                 try!(self.print_block(&**blk));
1349             }
1350             hir::ExprLoop(ref blk, opt_ident) => {
1351                 if let Some(ident) = opt_ident {
1352                     try!(self.print_name(ident.name));
1353                     try!(self.word_space(":"));
1354                 }
1355                 try!(self.head("loop"));
1356                 try!(space(&mut self.s));
1357                 try!(self.print_block(&**blk));
1358             }
1359             hir::ExprMatch(ref expr, ref arms, _) => {
1360                 try!(self.cbox(indent_unit));
1361                 try!(self.ibox(4));
1362                 try!(self.word_nbsp("match"));
1363                 try!(self.print_expr(&**expr));
1364                 try!(space(&mut self.s));
1365                 try!(self.bopen());
1366                 for arm in arms {
1367                     try!(self.print_arm(arm));
1368                 }
1369                 try!(self.bclose_(expr.span, indent_unit));
1370             }
1371             hir::ExprClosure(capture_clause, ref decl, ref body) => {
1372                 try!(self.print_capture_clause(capture_clause));
1373
1374                 try!(self.print_fn_block_args(&**decl));
1375                 try!(space(&mut self.s));
1376
1377                 let default_return = match decl.output {
1378                     hir::DefaultReturn(..) => true,
1379                     _ => false,
1380                 };
1381
1382                 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1383                     try!(self.print_block_unclosed(&**body));
1384                 } else {
1385                     // we extract the block, so as not to create another set of boxes
1386                     match body.expr.as_ref().unwrap().node {
1387                         hir::ExprBlock(ref blk) => {
1388                             try!(self.print_block_unclosed(&**blk));
1389                         }
1390                         _ => {
1391                             // this is a bare expression
1392                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1393                             try!(self.end()); // need to close a box
1394                         }
1395                     }
1396                 }
1397                 // a box will be closed by print_expr, but we didn't want an overall
1398                 // wrapper so we closed the corresponding opening. so create an
1399                 // empty box to satisfy the close.
1400                 try!(self.ibox(0));
1401             }
1402             hir::ExprBlock(ref blk) => {
1403                 // containing cbox, will be closed by print-block at }
1404                 try!(self.cbox(indent_unit));
1405                 // head-box, will be closed by print-block after {
1406                 try!(self.ibox(0));
1407                 try!(self.print_block(&**blk));
1408             }
1409             hir::ExprAssign(ref lhs, ref rhs) => {
1410                 try!(self.print_expr(&**lhs));
1411                 try!(space(&mut self.s));
1412                 try!(self.word_space("="));
1413                 try!(self.print_expr(&**rhs));
1414             }
1415             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1416                 try!(self.print_expr(&**lhs));
1417                 try!(space(&mut self.s));
1418                 try!(word(&mut self.s, ::util::binop_to_string(op.node)));
1419                 try!(self.word_space("="));
1420                 try!(self.print_expr(&**rhs));
1421             }
1422             hir::ExprField(ref expr, name) => {
1423                 try!(self.print_expr(&**expr));
1424                 try!(word(&mut self.s, "."));
1425                 try!(self.print_name(name.node));
1426             }
1427             hir::ExprTupField(ref expr, id) => {
1428                 try!(self.print_expr(&**expr));
1429                 try!(word(&mut self.s, "."));
1430                 try!(self.print_usize(id.node));
1431             }
1432             hir::ExprIndex(ref expr, ref index) => {
1433                 try!(self.print_expr(&**expr));
1434                 try!(word(&mut self.s, "["));
1435                 try!(self.print_expr(&**index));
1436                 try!(word(&mut self.s, "]"));
1437             }
1438             hir::ExprRange(ref start, ref end) => {
1439                 if let &Some(ref e) = start {
1440                     try!(self.print_expr(&**e));
1441                 }
1442                 try!(word(&mut self.s, ".."));
1443                 if let &Some(ref e) = end {
1444                     try!(self.print_expr(&**e));
1445                 }
1446             }
1447             hir::ExprPath(None, ref path) => {
1448                 try!(self.print_path(path, true, 0))
1449             }
1450             hir::ExprPath(Some(ref qself), ref path) => {
1451                 try!(self.print_qpath(path, qself, true))
1452             }
1453             hir::ExprBreak(opt_ident) => {
1454                 try!(word(&mut self.s, "break"));
1455                 try!(space(&mut self.s));
1456                 if let Some(ident) = opt_ident {
1457                     try!(self.print_name(ident.node.name));
1458                     try!(space(&mut self.s));
1459                 }
1460             }
1461             hir::ExprAgain(opt_ident) => {
1462                 try!(word(&mut self.s, "continue"));
1463                 try!(space(&mut self.s));
1464                 if let Some(ident) = opt_ident {
1465                     try!(self.print_name(ident.node.name));
1466                     try!(space(&mut self.s))
1467                 }
1468             }
1469             hir::ExprRet(ref result) => {
1470                 try!(word(&mut self.s, "return"));
1471                 match *result {
1472                     Some(ref expr) => {
1473                         try!(word(&mut self.s, " "));
1474                         try!(self.print_expr(&**expr));
1475                     }
1476                     _ => (),
1477                 }
1478             }
1479             hir::ExprInlineAsm(ref a) => {
1480                 try!(word(&mut self.s, "asm!"));
1481                 try!(self.popen());
1482                 try!(self.print_string(&a.asm, a.asm_str_style));
1483                 try!(self.word_space(":"));
1484
1485                 try!(self.commasep(Inconsistent, &a.outputs, |s, &(ref co, ref o, is_rw)| {
1486                     match co.slice_shift_char() {
1487                         Some(('=', operand)) if is_rw => {
1488                             try!(s.print_string(&format!("+{}", operand), ast::CookedStr))
1489                         }
1490                         _ => try!(s.print_string(&co, ast::CookedStr)),
1491                     }
1492                     try!(s.popen());
1493                     try!(s.print_expr(&**o));
1494                     try!(s.pclose());
1495                     Ok(())
1496                 }));
1497                 try!(space(&mut self.s));
1498                 try!(self.word_space(":"));
1499
1500                 try!(self.commasep(Inconsistent, &a.inputs, |s, &(ref co, ref o)| {
1501                     try!(s.print_string(&co, ast::CookedStr));
1502                     try!(s.popen());
1503                     try!(s.print_expr(&**o));
1504                     try!(s.pclose());
1505                     Ok(())
1506                 }));
1507                 try!(space(&mut self.s));
1508                 try!(self.word_space(":"));
1509
1510                 try!(self.commasep(Inconsistent, &a.clobbers, |s, co| {
1511                     try!(s.print_string(&co, ast::CookedStr));
1512                     Ok(())
1513                 }));
1514
1515                 let mut options = vec![];
1516                 if a.volatile {
1517                     options.push("volatile");
1518                 }
1519                 if a.alignstack {
1520                     options.push("alignstack");
1521                 }
1522                 if a.dialect == ast::AsmDialect::Intel {
1523                     options.push("intel");
1524                 }
1525
1526                 if !options.is_empty() {
1527                     try!(space(&mut self.s));
1528                     try!(self.word_space(":"));
1529                     try!(self.commasep(Inconsistent, &*options, |s, &co| {
1530                         try!(s.print_string(co, ast::CookedStr));
1531                         Ok(())
1532                     }));
1533                 }
1534
1535                 try!(self.pclose());
1536             }
1537         }
1538         try!(self.ann.post(self, NodeExpr(expr)));
1539         self.end()
1540     }
1541
1542     pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1543         try!(self.print_pat(&*loc.pat));
1544         if let Some(ref ty) = loc.ty {
1545             try!(self.word_space(":"));
1546             try!(self.print_type(&**ty));
1547         }
1548         Ok(())
1549     }
1550
1551     pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1552         try!(self.maybe_print_comment(decl.span.lo));
1553         match decl.node {
1554             hir::DeclLocal(ref loc) => {
1555                 try!(self.space_if_not_bol());
1556                 try!(self.ibox(indent_unit));
1557                 try!(self.word_nbsp("let"));
1558
1559                 try!(self.ibox(indent_unit));
1560                 try!(self.print_local_decl(&**loc));
1561                 try!(self.end());
1562                 if let Some(ref init) = loc.init {
1563                     try!(self.nbsp());
1564                     try!(self.word_space("="));
1565                     try!(self.print_expr(&**init));
1566                 }
1567                 self.end()
1568             }
1569             hir::DeclItem(ref item) => self.print_item(&**item),
1570         }
1571     }
1572
1573     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1574         word(&mut self.s, &i.to_string())
1575     }
1576
1577     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1578         try!(word(&mut self.s, &name.as_str()));
1579         self.ann.post(self, NodeName(&name))
1580     }
1581
1582     pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1583         try!(self.print_local_decl(loc));
1584         try!(space(&mut self.s));
1585         try!(self.word_space("in"));
1586         self.print_expr(coll)
1587     }
1588
1589     fn print_path(&mut self,
1590                   path: &hir::Path,
1591                   colons_before_params: bool,
1592                   depth: usize)
1593                   -> io::Result<()> {
1594         try!(self.maybe_print_comment(path.span.lo));
1595
1596         let mut first = !path.global;
1597         for segment in &path.segments[..path.segments.len() - depth] {
1598             if first {
1599                 first = false
1600             } else {
1601                 try!(word(&mut self.s, "::"))
1602             }
1603
1604             try!(self.print_name(segment.identifier.name));
1605
1606             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1607         }
1608
1609         Ok(())
1610     }
1611
1612     fn print_qpath(&mut self,
1613                    path: &hir::Path,
1614                    qself: &hir::QSelf,
1615                    colons_before_params: bool)
1616                    -> io::Result<()> {
1617         try!(word(&mut self.s, "<"));
1618         try!(self.print_type(&qself.ty));
1619         if qself.position > 0 {
1620             try!(space(&mut self.s));
1621             try!(self.word_space("as"));
1622             let depth = path.segments.len() - qself.position;
1623             try!(self.print_path(&path, false, depth));
1624         }
1625         try!(word(&mut self.s, ">"));
1626         try!(word(&mut self.s, "::"));
1627         let item_segment = path.segments.last().unwrap();
1628         try!(self.print_name(item_segment.identifier.name));
1629         self.print_path_parameters(&item_segment.parameters, colons_before_params)
1630     }
1631
1632     fn print_path_parameters(&mut self,
1633                              parameters: &hir::PathParameters,
1634                              colons_before_params: bool)
1635                              -> io::Result<()> {
1636         if parameters.is_empty() {
1637             return Ok(());
1638         }
1639
1640         if colons_before_params {
1641             try!(word(&mut self.s, "::"))
1642         }
1643
1644         match *parameters {
1645             hir::AngleBracketedParameters(ref data) => {
1646                 try!(word(&mut self.s, "<"));
1647
1648                 let mut comma = false;
1649                 for lifetime in &data.lifetimes {
1650                     if comma {
1651                         try!(self.word_space(","))
1652                     }
1653                     try!(self.print_lifetime(lifetime));
1654                     comma = true;
1655                 }
1656
1657                 if !data.types.is_empty() {
1658                     if comma {
1659                         try!(self.word_space(","))
1660                     }
1661                     try!(self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&**ty)));
1662                     comma = true;
1663                 }
1664
1665                 for binding in data.bindings.iter() {
1666                     if comma {
1667                         try!(self.word_space(","))
1668                     }
1669                     try!(self.print_name(binding.name));
1670                     try!(space(&mut self.s));
1671                     try!(self.word_space("="));
1672                     try!(self.print_type(&*binding.ty));
1673                     comma = true;
1674                 }
1675
1676                 try!(word(&mut self.s, ">"))
1677             }
1678
1679             hir::ParenthesizedParameters(ref data) => {
1680                 try!(word(&mut self.s, "("));
1681                 try!(self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&**ty)));
1682                 try!(word(&mut self.s, ")"));
1683
1684                 match data.output {
1685                     None => {}
1686                     Some(ref ty) => {
1687                         try!(self.space_if_not_bol());
1688                         try!(self.word_space("->"));
1689                         try!(self.print_type(&**ty));
1690                     }
1691                 }
1692             }
1693         }
1694
1695         Ok(())
1696     }
1697
1698     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1699         try!(self.maybe_print_comment(pat.span.lo));
1700         try!(self.ann.pre(self, NodePat(pat)));
1701         // Pat isn't normalized, but the beauty of it
1702         // is that it doesn't matter
1703         match pat.node {
1704             hir::PatWild => try!(word(&mut self.s, "_")),
1705             hir::PatIdent(binding_mode, ref path1, ref sub) => {
1706                 match binding_mode {
1707                     hir::BindByRef(mutbl) => {
1708                         try!(self.word_nbsp("ref"));
1709                         try!(self.print_mutability(mutbl));
1710                     }
1711                     hir::BindByValue(hir::MutImmutable) => {}
1712                     hir::BindByValue(hir::MutMutable) => {
1713                         try!(self.word_nbsp("mut"));
1714                     }
1715                 }
1716                 try!(self.print_name(path1.node.name));
1717                 match *sub {
1718                     Some(ref p) => {
1719                         try!(word(&mut self.s, "@"));
1720                         try!(self.print_pat(&**p));
1721                     }
1722                     None => (),
1723                 }
1724             }
1725             hir::PatEnum(ref path, ref args_) => {
1726                 try!(self.print_path(path, true, 0));
1727                 match *args_ {
1728                     None => try!(word(&mut self.s, "(..)")),
1729                     Some(ref args) => {
1730                         if !args.is_empty() {
1731                             try!(self.popen());
1732                             try!(self.commasep(Inconsistent, &args[..], |s, p| s.print_pat(&**p)));
1733                             try!(self.pclose());
1734                         }
1735                     }
1736                 }
1737             }
1738             hir::PatQPath(ref qself, ref path) => {
1739                 try!(self.print_qpath(path, qself, false));
1740             }
1741             hir::PatStruct(ref path, ref fields, etc) => {
1742                 try!(self.print_path(path, true, 0));
1743                 try!(self.nbsp());
1744                 try!(self.word_space("{"));
1745                 try!(self.commasep_cmnt(Consistent,
1746                                         &fields[..],
1747                                         |s, f| {
1748                                             try!(s.cbox(indent_unit));
1749                                             if !f.node.is_shorthand {
1750                                                 try!(s.print_name(f.node.name));
1751                                                 try!(s.word_nbsp(":"));
1752                                             }
1753                                             try!(s.print_pat(&*f.node.pat));
1754                                             s.end()
1755                                         },
1756                                         |f| f.node.pat.span));
1757                 if etc {
1758                     if !fields.is_empty() {
1759                         try!(self.word_space(","));
1760                     }
1761                     try!(word(&mut self.s, ".."));
1762                 }
1763                 try!(space(&mut self.s));
1764                 try!(word(&mut self.s, "}"));
1765             }
1766             hir::PatTup(ref elts) => {
1767                 try!(self.popen());
1768                 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&**p)));
1769                 if elts.len() == 1 {
1770                     try!(word(&mut self.s, ","));
1771                 }
1772                 try!(self.pclose());
1773             }
1774             hir::PatBox(ref inner) => {
1775                 try!(word(&mut self.s, "box "));
1776                 try!(self.print_pat(&**inner));
1777             }
1778             hir::PatRegion(ref inner, mutbl) => {
1779                 try!(word(&mut self.s, "&"));
1780                 if mutbl == hir::MutMutable {
1781                     try!(word(&mut self.s, "mut "));
1782                 }
1783                 try!(self.print_pat(&**inner));
1784             }
1785             hir::PatLit(ref e) => try!(self.print_expr(&**e)),
1786             hir::PatRange(ref begin, ref end) => {
1787                 try!(self.print_expr(&**begin));
1788                 try!(space(&mut self.s));
1789                 try!(word(&mut self.s, "..."));
1790                 try!(self.print_expr(&**end));
1791             }
1792             hir::PatVec(ref before, ref slice, ref after) => {
1793                 try!(word(&mut self.s, "["));
1794                 try!(self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&**p)));
1795                 if let Some(ref p) = *slice {
1796                     if !before.is_empty() {
1797                         try!(self.word_space(","));
1798                     }
1799                     if p.node != hir::PatWild {
1800                         try!(self.print_pat(&**p));
1801                     }
1802                     try!(word(&mut self.s, ".."));
1803                     if !after.is_empty() {
1804                         try!(self.word_space(","));
1805                     }
1806                 }
1807                 try!(self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&**p)));
1808                 try!(word(&mut self.s, "]"));
1809             }
1810         }
1811         self.ann.post(self, NodePat(pat))
1812     }
1813
1814     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1815         // I have no idea why this check is necessary, but here it
1816         // is :(
1817         if arm.attrs.is_empty() {
1818             try!(space(&mut self.s));
1819         }
1820         try!(self.cbox(indent_unit));
1821         try!(self.ibox(0));
1822         try!(self.print_outer_attributes(&arm.attrs));
1823         let mut first = true;
1824         for p in &arm.pats {
1825             if first {
1826                 first = false;
1827             } else {
1828                 try!(space(&mut self.s));
1829                 try!(self.word_space("|"));
1830             }
1831             try!(self.print_pat(&**p));
1832         }
1833         try!(space(&mut self.s));
1834         if let Some(ref e) = arm.guard {
1835             try!(self.word_space("if"));
1836             try!(self.print_expr(&**e));
1837             try!(space(&mut self.s));
1838         }
1839         try!(self.word_space("=>"));
1840
1841         match arm.body.node {
1842             hir::ExprBlock(ref blk) => {
1843                 // the block will close the pattern's ibox
1844                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
1845
1846                 // If it is a user-provided unsafe block, print a comma after it
1847                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1848                     try!(word(&mut self.s, ","));
1849                 }
1850             }
1851             _ => {
1852                 try!(self.end()); // close the ibox for the pattern
1853                 try!(self.print_expr(&*arm.body));
1854                 try!(word(&mut self.s, ","));
1855             }
1856         }
1857         self.end() // close enclosing cbox
1858     }
1859
1860     // Returns whether it printed anything
1861     fn print_explicit_self(&mut self,
1862                            explicit_self: &hir::ExplicitSelf_,
1863                            mutbl: hir::Mutability)
1864                            -> io::Result<bool> {
1865         try!(self.print_mutability(mutbl));
1866         match *explicit_self {
1867             hir::SelfStatic => {
1868                 return Ok(false);
1869             }
1870             hir::SelfValue(_) => {
1871                 try!(word(&mut self.s, "self"));
1872             }
1873             hir::SelfRegion(ref lt, m, _) => {
1874                 try!(word(&mut self.s, "&"));
1875                 try!(self.print_opt_lifetime(lt));
1876                 try!(self.print_mutability(m));
1877                 try!(word(&mut self.s, "self"));
1878             }
1879             hir::SelfExplicit(ref typ, _) => {
1880                 try!(word(&mut self.s, "self"));
1881                 try!(self.word_space(":"));
1882                 try!(self.print_type(&**typ));
1883             }
1884         }
1885         return Ok(true);
1886     }
1887
1888     pub fn print_fn(&mut self,
1889                     decl: &hir::FnDecl,
1890                     unsafety: hir::Unsafety,
1891                     constness: hir::Constness,
1892                     abi: abi::Abi,
1893                     name: Option<ast::Name>,
1894                     generics: &hir::Generics,
1895                     opt_explicit_self: Option<&hir::ExplicitSelf_>,
1896                     vis: hir::Visibility)
1897                     -> io::Result<()> {
1898         try!(self.print_fn_header_info(unsafety, constness, abi, vis));
1899
1900         if let Some(name) = name {
1901             try!(self.nbsp());
1902             try!(self.print_name(name));
1903         }
1904         try!(self.print_generics(generics));
1905         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
1906         self.print_where_clause(&generics.where_clause)
1907     }
1908
1909     pub fn print_fn_args(&mut self,
1910                          decl: &hir::FnDecl,
1911                          opt_explicit_self: Option<&hir::ExplicitSelf_>)
1912                          -> io::Result<()> {
1913         // It is unfortunate to duplicate the commasep logic, but we want the
1914         // self type and the args all in the same box.
1915         try!(self.rbox(0, Inconsistent));
1916         let mut first = true;
1917         if let Some(explicit_self) = opt_explicit_self {
1918             let m = match explicit_self {
1919                 &hir::SelfStatic => hir::MutImmutable,
1920                 _ => match decl.inputs[0].pat.node {
1921                     hir::PatIdent(hir::BindByValue(m), _, _) => m,
1922                     _ => hir::MutImmutable,
1923                 },
1924             };
1925             first = !try!(self.print_explicit_self(explicit_self, m));
1926         }
1927
1928         // HACK(eddyb) ignore the separately printed self argument.
1929         let args = if first {
1930             &decl.inputs[..]
1931         } else {
1932             &decl.inputs[1..]
1933         };
1934
1935         for arg in args {
1936             if first {
1937                 first = false;
1938             } else {
1939                 try!(self.word_space(","));
1940             }
1941             try!(self.print_arg(arg));
1942         }
1943
1944         self.end()
1945     }
1946
1947     pub fn print_fn_args_and_ret(&mut self,
1948                                  decl: &hir::FnDecl,
1949                                  opt_explicit_self: Option<&hir::ExplicitSelf_>)
1950                                  -> io::Result<()> {
1951         try!(self.popen());
1952         try!(self.print_fn_args(decl, opt_explicit_self));
1953         if decl.variadic {
1954             try!(word(&mut self.s, ", ..."));
1955         }
1956         try!(self.pclose());
1957
1958         self.print_fn_output(decl)
1959     }
1960
1961     pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1962         try!(word(&mut self.s, "|"));
1963         try!(self.print_fn_args(decl, None));
1964         try!(word(&mut self.s, "|"));
1965
1966         if let hir::DefaultReturn(..) = decl.output {
1967             return Ok(());
1968         }
1969
1970         try!(self.space_if_not_bol());
1971         try!(self.word_space("->"));
1972         match decl.output {
1973             hir::Return(ref ty) => {
1974                 try!(self.print_type(&**ty));
1975                 self.maybe_print_comment(ty.span.lo)
1976             }
1977             hir::DefaultReturn(..) => unreachable!(),
1978             hir::NoReturn(span) => {
1979                 try!(self.word_nbsp("!"));
1980                 self.maybe_print_comment(span.lo)
1981             }
1982         }
1983     }
1984
1985     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1986         match capture_clause {
1987             hir::CaptureByValue => self.word_space("move"),
1988             hir::CaptureByRef => Ok(()),
1989         }
1990     }
1991
1992     pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1993         if !bounds.is_empty() {
1994             try!(word(&mut self.s, prefix));
1995             let mut first = true;
1996             for bound in bounds {
1997                 try!(self.nbsp());
1998                 if first {
1999                     first = false;
2000                 } else {
2001                     try!(self.word_space("+"));
2002                 }
2003
2004                 try!(match *bound {
2005                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2006                         self.print_poly_trait_ref(tref)
2007                     }
2008                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2009                         try!(word(&mut self.s, "?"));
2010                         self.print_poly_trait_ref(tref)
2011                     }
2012                     RegionTyParamBound(ref lt) => {
2013                         self.print_lifetime(lt)
2014                     }
2015                 })
2016             }
2017             Ok(())
2018         } else {
2019             Ok(())
2020         }
2021     }
2022
2023     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2024         self.print_name(lifetime.name)
2025     }
2026
2027     pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2028         try!(self.print_lifetime(&lifetime.lifetime));
2029         let mut sep = ":";
2030         for v in &lifetime.bounds {
2031             try!(word(&mut self.s, sep));
2032             try!(self.print_lifetime(v));
2033             sep = "+";
2034         }
2035         Ok(())
2036     }
2037
2038     pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2039         let total = generics.lifetimes.len() + generics.ty_params.len();
2040         if total == 0 {
2041             return Ok(());
2042         }
2043
2044         try!(word(&mut self.s, "<"));
2045
2046         let mut ints = Vec::new();
2047         for i in 0..total {
2048             ints.push(i);
2049         }
2050
2051         try!(self.commasep(Inconsistent, &ints[..], |s, &idx| {
2052             if idx < generics.lifetimes.len() {
2053                 let lifetime = &generics.lifetimes[idx];
2054                 s.print_lifetime_def(lifetime)
2055             } else {
2056                 let idx = idx - generics.lifetimes.len();
2057                 let param = &generics.ty_params[idx];
2058                 s.print_ty_param(param)
2059             }
2060         }));
2061
2062         try!(word(&mut self.s, ">"));
2063         Ok(())
2064     }
2065
2066     pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2067         try!(self.print_name(param.name));
2068         try!(self.print_bounds(":", &param.bounds));
2069         match param.default {
2070             Some(ref default) => {
2071                 try!(space(&mut self.s));
2072                 try!(self.word_space("="));
2073                 self.print_type(&**default)
2074             }
2075             _ => Ok(()),
2076         }
2077     }
2078
2079     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2080         if where_clause.predicates.is_empty() {
2081             return Ok(());
2082         }
2083
2084         try!(space(&mut self.s));
2085         try!(self.word_space("where"));
2086
2087         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2088             if i != 0 {
2089                 try!(self.word_space(","));
2090             }
2091
2092             match predicate {
2093                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2094                                                                               ref bounded_ty,
2095                                                                               ref bounds,
2096                                                                               ..}) => {
2097                     try!(self.print_formal_lifetime_list(bound_lifetimes));
2098                     try!(self.print_type(&**bounded_ty));
2099                     try!(self.print_bounds(":", bounds));
2100                 }
2101                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2102                                                                                 ref bounds,
2103                                                                                 ..}) => {
2104                     try!(self.print_lifetime(lifetime));
2105                     try!(word(&mut self.s, ":"));
2106
2107                     for (i, bound) in bounds.iter().enumerate() {
2108                         try!(self.print_lifetime(bound));
2109
2110                         if i != 0 {
2111                             try!(word(&mut self.s, ":"));
2112                         }
2113                     }
2114                 }
2115                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2116                     try!(self.print_path(path, false, 0));
2117                     try!(space(&mut self.s));
2118                     try!(self.word_space("="));
2119                     try!(self.print_type(&**ty));
2120                 }
2121             }
2122         }
2123
2124         Ok(())
2125     }
2126
2127     pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2128         match vp.node {
2129             hir::ViewPathSimple(name, ref path) => {
2130                 try!(self.print_path(path, false, 0));
2131
2132                 if path.segments.last().unwrap().identifier.name != name {
2133                     try!(space(&mut self.s));
2134                     try!(self.word_space("as"));
2135                     try!(self.print_name(name));
2136                 }
2137
2138                 Ok(())
2139             }
2140
2141             hir::ViewPathGlob(ref path) => {
2142                 try!(self.print_path(path, false, 0));
2143                 word(&mut self.s, "::*")
2144             }
2145
2146             hir::ViewPathList(ref path, ref segments) => {
2147                 if path.segments.is_empty() {
2148                     try!(word(&mut self.s, "{"));
2149                 } else {
2150                     try!(self.print_path(path, false, 0));
2151                     try!(word(&mut self.s, "::{"));
2152                 }
2153                 try!(self.commasep(Inconsistent, &segments[..], |s, w| {
2154                     match w.node {
2155                         hir::PathListIdent { name, .. } => {
2156                             s.print_name(name)
2157                         }
2158                         hir::PathListMod { .. } => {
2159                             word(&mut s.s, "self")
2160                         }
2161                     }
2162                 }));
2163                 word(&mut self.s, "}")
2164             }
2165         }
2166     }
2167
2168     pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2169         match mutbl {
2170             hir::MutMutable => self.word_nbsp("mut"),
2171             hir::MutImmutable => Ok(()),
2172         }
2173     }
2174
2175     pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2176         try!(self.print_mutability(mt.mutbl));
2177         self.print_type(&*mt.ty)
2178     }
2179
2180     pub fn print_arg(&mut self, input: &hir::Arg) -> io::Result<()> {
2181         try!(self.ibox(indent_unit));
2182         match input.ty.node {
2183             hir::TyInfer => try!(self.print_pat(&*input.pat)),
2184             _ => {
2185                 match input.pat.node {
2186                     hir::PatIdent(_, ref path1, _) if
2187                         path1.node.name ==
2188                             parse::token::special_idents::invalid.name => {
2189                         // Do nothing.
2190                     }
2191                     _ => {
2192                         try!(self.print_pat(&*input.pat));
2193                         try!(word(&mut self.s, ":"));
2194                         try!(space(&mut self.s));
2195                     }
2196                 }
2197                 try!(self.print_type(&*input.ty));
2198             }
2199         }
2200         self.end()
2201     }
2202
2203     pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2204         if let hir::DefaultReturn(..) = decl.output {
2205             return Ok(());
2206         }
2207
2208         try!(self.space_if_not_bol());
2209         try!(self.ibox(indent_unit));
2210         try!(self.word_space("->"));
2211         match decl.output {
2212             hir::NoReturn(_) => try!(self.word_nbsp("!")),
2213             hir::DefaultReturn(..) => unreachable!(),
2214             hir::Return(ref ty) => try!(self.print_type(&**ty)),
2215         }
2216         try!(self.end());
2217
2218         match decl.output {
2219             hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2220             _ => Ok(()),
2221         }
2222     }
2223
2224     pub fn print_ty_fn(&mut self,
2225                        abi: abi::Abi,
2226                        unsafety: hir::Unsafety,
2227                        decl: &hir::FnDecl,
2228                        name: Option<ast::Name>,
2229                        generics: &hir::Generics,
2230                        opt_explicit_self: Option<&hir::ExplicitSelf_>)
2231                        -> io::Result<()> {
2232         try!(self.ibox(indent_unit));
2233         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2234             try!(word(&mut self.s, "for"));
2235             try!(self.print_generics(generics));
2236         }
2237         let generics = hir::Generics {
2238             lifetimes: Vec::new(),
2239             ty_params: OwnedSlice::empty(),
2240             where_clause: hir::WhereClause {
2241                 id: ast::DUMMY_NODE_ID,
2242                 predicates: Vec::new(),
2243             },
2244         };
2245         try!(self.print_fn(decl,
2246                            unsafety,
2247                            hir::Constness::NotConst,
2248                            abi,
2249                            name,
2250                            &generics,
2251                            opt_explicit_self,
2252                            hir::Inherited));
2253         self.end()
2254     }
2255
2256     pub fn maybe_print_trailing_comment(&mut self,
2257                                         span: codemap::Span,
2258                                         next_pos: Option<BytePos>)
2259                                         -> io::Result<()> {
2260         let cm = match self.cm {
2261             Some(cm) => cm,
2262             _ => return Ok(()),
2263         };
2264         match self.next_comment() {
2265             Some(ref cmnt) => {
2266                 if (*cmnt).style != comments::Trailing {
2267                     return Ok(());
2268                 }
2269                 let span_line = cm.lookup_char_pos(span.hi);
2270                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2271                 let mut next = (*cmnt).pos + BytePos(1);
2272                 match next_pos {
2273                     None => (),
2274                     Some(p) => next = p,
2275                 }
2276                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2277                    span_line.line == comment_line.line {
2278                     try!(self.print_comment(cmnt));
2279                     self.cur_cmnt_and_lit.cur_cmnt += 1;
2280                 }
2281             }
2282             _ => (),
2283         }
2284         Ok(())
2285     }
2286
2287     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2288         // If there aren't any remaining comments, then we need to manually
2289         // make sure there is a line break at the end.
2290         if self.next_comment().is_none() {
2291             try!(hardbreak(&mut self.s));
2292         }
2293         loop {
2294             match self.next_comment() {
2295                 Some(ref cmnt) => {
2296                     try!(self.print_comment(cmnt));
2297                     self.cur_cmnt_and_lit.cur_cmnt += 1;
2298                 }
2299                 _ => break,
2300             }
2301         }
2302         Ok(())
2303     }
2304
2305     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2306                                                   opt_abi: Option<abi::Abi>)
2307                                                   -> io::Result<()> {
2308         match opt_abi {
2309             Some(abi::Rust) => Ok(()),
2310             Some(abi) => {
2311                 try!(self.word_nbsp("extern"));
2312                 self.word_nbsp(&abi.to_string())
2313             }
2314             None => Ok(()),
2315         }
2316     }
2317
2318     pub fn print_extern_opt_abi(&mut self, opt_abi: Option<abi::Abi>) -> io::Result<()> {
2319         match opt_abi {
2320             Some(abi) => {
2321                 try!(self.word_nbsp("extern"));
2322                 self.word_nbsp(&abi.to_string())
2323             }
2324             None => Ok(()),
2325         }
2326     }
2327
2328     pub fn print_fn_header_info(&mut self,
2329                                 unsafety: hir::Unsafety,
2330                                 constness: hir::Constness,
2331                                 abi: abi::Abi,
2332                                 vis: hir::Visibility)
2333                                 -> io::Result<()> {
2334         try!(word(&mut self.s, &visibility_qualified(vis, "")));
2335         try!(self.print_unsafety(unsafety));
2336
2337         match constness {
2338             hir::Constness::NotConst => {}
2339             hir::Constness::Const => try!(self.word_nbsp("const")),
2340         }
2341
2342         if abi != abi::Rust {
2343             try!(self.word_nbsp("extern"));
2344             try!(self.word_nbsp(&abi.to_string()));
2345         }
2346
2347         word(&mut self.s, "fn")
2348     }
2349
2350     pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2351         match s {
2352             hir::Unsafety::Normal => Ok(()),
2353             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2354         }
2355     }
2356 }
2357
2358 // Dup'ed from parse::classify, but adapted for the HIR.
2359 /// Does this expression require a semicolon to be treated
2360 /// as a statement? The negation of this: 'can this expression
2361 /// be used as a statement without a semicolon' -- is used
2362 /// as an early-bail-out in the parser so that, for instance,
2363 ///     if true {...} else {...}
2364 ///      |x| 5
2365 /// isn't parsed as (if true {...} else {...} | x) | 5
2366 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2367     match e.node {
2368         hir::ExprIf(..) |
2369         hir::ExprMatch(..) |
2370         hir::ExprBlock(_) |
2371         hir::ExprWhile(..) |
2372         hir::ExprLoop(..) => false,
2373         _ => true,
2374     }
2375 }
2376
2377 /// this statement requires a semicolon after it.
2378 /// note that in one case (stmt_semi), we've already
2379 /// seen the semicolon, and thus don't need another.
2380 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2381     match *stmt {
2382         hir::StmtDecl(ref d, _) => {
2383             match d.node {
2384                 hir::DeclLocal(_) => true,
2385                 hir::DeclItem(_) => false,
2386             }
2387         }
2388         hir::StmtExpr(ref e, _) => {
2389             expr_requires_semi_to_be_stmt(&**e)
2390         }
2391         hir::StmtSemi(..) => {
2392             false
2393         }
2394     }
2395 }