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