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