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