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