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