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