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