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