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