]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/print.rs
Rollup merge of #35618 - jseyfried:ast_view_path_refactor, r=eddyb
[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::TyNever => {
508                 word(&mut self.s, "!")?;
509             },
510             hir::TyTup(ref elts) => {
511                 self.popen()?;
512                 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
513                 if elts.len() == 1 {
514                     word(&mut self.s, ",")?;
515                 }
516                 self.pclose()?;
517             }
518             hir::TyBareFn(ref f) => {
519                 let generics = hir::Generics {
520                     lifetimes: f.lifetimes.clone(),
521                     ty_params: hir::HirVec::new(),
522                     where_clause: hir::WhereClause {
523                         id: ast::DUMMY_NODE_ID,
524                         predicates: hir::HirVec::new(),
525                     },
526                     span: syntax_pos::DUMMY_SP,
527                 };
528                 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
529             }
530             hir::TyPath(None, ref path) => {
531                 self.print_path(path, false, 0)?;
532             }
533             hir::TyPath(Some(ref qself), ref path) => {
534                 self.print_qpath(path, qself, false)?
535             }
536             hir::TyObjectSum(ref ty, ref bounds) => {
537                 self.print_type(&ty)?;
538                 self.print_bounds("+", &bounds[..])?;
539             }
540             hir::TyPolyTraitRef(ref bounds) => {
541                 self.print_bounds("", &bounds[..])?;
542             }
543             hir::TyImplTrait(ref bounds) => {
544                 self.print_bounds("impl ", &bounds[..])?;
545             }
546             hir::TyFixedLengthVec(ref ty, ref v) => {
547                 word(&mut self.s, "[")?;
548                 self.print_type(&ty)?;
549                 word(&mut self.s, "; ")?;
550                 self.print_expr(&v)?;
551                 word(&mut self.s, "]")?;
552             }
553             hir::TyTypeof(ref e) => {
554                 word(&mut self.s, "typeof(")?;
555                 self.print_expr(&e)?;
556                 word(&mut self.s, ")")?;
557             }
558             hir::TyInfer => {
559                 word(&mut self.s, "_")?;
560             }
561         }
562         self.end()
563     }
564
565     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
566         self.hardbreak_if_not_bol()?;
567         self.maybe_print_comment(item.span.lo)?;
568         self.print_outer_attributes(&item.attrs)?;
569         match item.node {
570             hir::ForeignItemFn(ref decl, ref generics) => {
571                 self.head("")?;
572                 self.print_fn(decl,
573                               hir::Unsafety::Normal,
574                               hir::Constness::NotConst,
575                               Abi::Rust,
576                               Some(item.name),
577                               generics,
578                               &item.vis)?;
579                 self.end()?; // end head-ibox
580                 word(&mut self.s, ";")?;
581                 self.end() // end the outer fn box
582             }
583             hir::ForeignItemStatic(ref t, m) => {
584                 self.head(&visibility_qualified(&item.vis, "static"))?;
585                 if m {
586                     self.word_space("mut")?;
587                 }
588                 self.print_name(item.name)?;
589                 self.word_space(":")?;
590                 self.print_type(&t)?;
591                 word(&mut self.s, ";")?;
592                 self.end()?; // end the head-ibox
593                 self.end() // end the outer cbox
594             }
595         }
596     }
597
598     fn print_associated_const(&mut self,
599                               name: ast::Name,
600                               ty: &hir::Ty,
601                               default: Option<&hir::Expr>,
602                               vis: &hir::Visibility)
603                               -> io::Result<()> {
604         word(&mut self.s, &visibility_qualified(vis, ""))?;
605         self.word_space("const")?;
606         self.print_name(name)?;
607         self.word_space(":")?;
608         self.print_type(ty)?;
609         if let Some(expr) = default {
610             space(&mut self.s)?;
611             self.word_space("=")?;
612             self.print_expr(expr)?;
613         }
614         word(&mut self.s, ";")
615     }
616
617     fn print_associated_type(&mut self,
618                              name: ast::Name,
619                              bounds: Option<&hir::TyParamBounds>,
620                              ty: Option<&hir::Ty>)
621                              -> io::Result<()> {
622         self.word_space("type")?;
623         self.print_name(name)?;
624         if let Some(bounds) = bounds {
625             self.print_bounds(":", bounds)?;
626         }
627         if let Some(ty) = ty {
628             space(&mut self.s)?;
629             self.word_space("=")?;
630             self.print_type(ty)?;
631         }
632         word(&mut self.s, ";")
633     }
634
635     pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
636         if let Some(krate) = self.krate {
637             // skip nested items if krate context was not provided
638             let item = &krate.items[&item_id.id];
639             self.print_item(item)
640         } else {
641             Ok(())
642         }
643     }
644
645     /// Pretty-print an item
646     pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
647         self.hardbreak_if_not_bol()?;
648         self.maybe_print_comment(item.span.lo)?;
649         self.print_outer_attributes(&item.attrs)?;
650         self.ann.pre(self, NodeItem(item))?;
651         match item.node {
652             hir::ItemExternCrate(ref optional_path) => {
653                 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
654                 if let Some(p) = *optional_path {
655                     let val = p.as_str();
656                     if val.contains("-") {
657                         self.print_string(&val, ast::StrStyle::Cooked)?;
658                     } else {
659                         self.print_name(p)?;
660                     }
661                     space(&mut self.s)?;
662                     word(&mut self.s, "as")?;
663                     space(&mut self.s)?;
664                 }
665                 self.print_name(item.name)?;
666                 word(&mut self.s, ";")?;
667                 self.end()?; // end inner head-block
668                 self.end()?; // end outer head-block
669             }
670             hir::ItemUse(ref vp) => {
671                 self.head(&visibility_qualified(&item.vis, "use"))?;
672                 self.print_view_path(&vp)?;
673                 word(&mut self.s, ";")?;
674                 self.end()?; // end inner head-block
675                 self.end()?; // end outer head-block
676             }
677             hir::ItemStatic(ref ty, m, ref expr) => {
678                 self.head(&visibility_qualified(&item.vis, "static"))?;
679                 if m == hir::MutMutable {
680                     self.word_space("mut")?;
681                 }
682                 self.print_name(item.name)?;
683                 self.word_space(":")?;
684                 self.print_type(&ty)?;
685                 space(&mut self.s)?;
686                 self.end()?; // end the head-ibox
687
688                 self.word_space("=")?;
689                 self.print_expr(&expr)?;
690                 word(&mut self.s, ";")?;
691                 self.end()?; // end the outer cbox
692             }
693             hir::ItemConst(ref ty, ref expr) => {
694                 self.head(&visibility_qualified(&item.vis, "const"))?;
695                 self.print_name(item.name)?;
696                 self.word_space(":")?;
697                 self.print_type(&ty)?;
698                 space(&mut self.s)?;
699                 self.end()?; // end the head-ibox
700
701                 self.word_space("=")?;
702                 self.print_expr(&expr)?;
703                 word(&mut self.s, ";")?;
704                 self.end()?; // end the outer cbox
705             }
706             hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
707                 self.head("")?;
708                 self.print_fn(decl,
709                               unsafety,
710                               constness,
711                               abi,
712                               Some(item.name),
713                               typarams,
714                               &item.vis)?;
715                 word(&mut self.s, " ")?;
716                 self.print_block_with_attrs(&body, &item.attrs)?;
717             }
718             hir::ItemMod(ref _mod) => {
719                 self.head(&visibility_qualified(&item.vis, "mod"))?;
720                 self.print_name(item.name)?;
721                 self.nbsp()?;
722                 self.bopen()?;
723                 self.print_mod(_mod, &item.attrs)?;
724                 self.bclose(item.span)?;
725             }
726             hir::ItemForeignMod(ref nmod) => {
727                 self.head("extern")?;
728                 self.word_nbsp(&nmod.abi.to_string())?;
729                 self.bopen()?;
730                 self.print_foreign_mod(nmod, &item.attrs)?;
731                 self.bclose(item.span)?;
732             }
733             hir::ItemTy(ref ty, ref params) => {
734                 self.ibox(indent_unit)?;
735                 self.ibox(0)?;
736                 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
737                 self.print_name(item.name)?;
738                 self.print_generics(params)?;
739                 self.end()?; // end the inner ibox
740
741                 self.print_where_clause(&params.where_clause)?;
742                 space(&mut self.s)?;
743                 self.word_space("=")?;
744                 self.print_type(&ty)?;
745                 word(&mut self.s, ";")?;
746                 self.end()?; // end the outer ibox
747             }
748             hir::ItemEnum(ref enum_definition, ref params) => {
749                 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
750             }
751             hir::ItemStruct(ref struct_def, ref generics) => {
752                 self.head(&visibility_qualified(&item.vis, "struct"))?;
753                 self.print_struct(struct_def, generics, item.name, item.span, true)?;
754             }
755
756             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
757                 self.head("")?;
758                 self.print_visibility(&item.vis)?;
759                 self.print_unsafety(unsafety)?;
760                 self.word_nbsp("impl")?;
761                 self.print_trait_ref(trait_ref)?;
762                 space(&mut self.s)?;
763                 self.word_space("for")?;
764                 self.word_space("..")?;
765                 self.bopen()?;
766                 self.bclose(item.span)?;
767             }
768             hir::ItemImpl(unsafety,
769                           polarity,
770                           ref generics,
771                           ref opt_trait,
772                           ref ty,
773                           ref impl_items) => {
774                 self.head("")?;
775                 self.print_visibility(&item.vis)?;
776                 self.print_unsafety(unsafety)?;
777                 self.word_nbsp("impl")?;
778
779                 if generics.is_parameterized() {
780                     self.print_generics(generics)?;
781                     space(&mut self.s)?;
782                 }
783
784                 match polarity {
785                     hir::ImplPolarity::Negative => {
786                         word(&mut self.s, "!")?;
787                     }
788                     _ => {}
789                 }
790
791                 match opt_trait {
792                     &Some(ref t) => {
793                         self.print_trait_ref(t)?;
794                         space(&mut self.s)?;
795                         self.word_space("for")?;
796                     }
797                     &None => {}
798                 }
799
800                 self.print_type(&ty)?;
801                 self.print_where_clause(&generics.where_clause)?;
802
803                 space(&mut self.s)?;
804                 self.bopen()?;
805                 self.print_inner_attributes(&item.attrs)?;
806                 for impl_item in impl_items {
807                     self.print_impl_item(impl_item)?;
808                 }
809                 self.bclose(item.span)?;
810             }
811             hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
812                 self.head("")?;
813                 self.print_visibility(&item.vis)?;
814                 self.print_unsafety(unsafety)?;
815                 self.word_nbsp("trait")?;
816                 self.print_name(item.name)?;
817                 self.print_generics(generics)?;
818                 let mut real_bounds = Vec::with_capacity(bounds.len());
819                 for b in bounds.iter() {
820                     if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
821                         space(&mut self.s)?;
822                         self.word_space("for ?")?;
823                         self.print_trait_ref(&ptr.trait_ref)?;
824                     } else {
825                         real_bounds.push(b.clone());
826                     }
827                 }
828                 self.print_bounds(":", &real_bounds[..])?;
829                 self.print_where_clause(&generics.where_clause)?;
830                 word(&mut self.s, " ")?;
831                 self.bopen()?;
832                 for trait_item in trait_items {
833                     self.print_trait_item(trait_item)?;
834                 }
835                 self.bclose(item.span)?;
836             }
837         }
838         self.ann.post(self, NodeItem(item))
839     }
840
841     fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
842         self.print_path(&t.path, false, 0)
843     }
844
845     fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
846         if !lifetimes.is_empty() {
847             word(&mut self.s, "for<")?;
848             let mut comma = false;
849             for lifetime_def in lifetimes {
850                 if comma {
851                     self.word_space(",")?
852                 }
853                 self.print_lifetime_def(lifetime_def)?;
854                 comma = true;
855             }
856             word(&mut self.s, ">")?;
857         }
858         Ok(())
859     }
860
861     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
862         self.print_formal_lifetime_list(&t.bound_lifetimes)?;
863         self.print_trait_ref(&t.trait_ref)
864     }
865
866     pub fn print_enum_def(&mut self,
867                           enum_definition: &hir::EnumDef,
868                           generics: &hir::Generics,
869                           name: ast::Name,
870                           span: syntax_pos::Span,
871                           visibility: &hir::Visibility)
872                           -> io::Result<()> {
873         self.head(&visibility_qualified(visibility, "enum"))?;
874         self.print_name(name)?;
875         self.print_generics(generics)?;
876         self.print_where_clause(&generics.where_clause)?;
877         space(&mut self.s)?;
878         self.print_variants(&enum_definition.variants, span)
879     }
880
881     pub fn print_variants(&mut self,
882                           variants: &[hir::Variant],
883                           span: syntax_pos::Span)
884                           -> io::Result<()> {
885         self.bopen()?;
886         for v in variants {
887             self.space_if_not_bol()?;
888             self.maybe_print_comment(v.span.lo)?;
889             self.print_outer_attributes(&v.node.attrs)?;
890             self.ibox(indent_unit)?;
891             self.print_variant(v)?;
892             word(&mut self.s, ",")?;
893             self.end()?;
894             self.maybe_print_trailing_comment(v.span, None)?;
895         }
896         self.bclose(span)
897     }
898
899     pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
900         match *vis {
901             hir::Public => self.word_nbsp("pub"),
902             hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
903             hir::Visibility::Restricted { ref path, .. } =>
904                 self.word_nbsp(&format!("pub({})", path)),
905             hir::Inherited => Ok(()),
906         }
907     }
908
909     pub fn print_struct(&mut self,
910                         struct_def: &hir::VariantData,
911                         generics: &hir::Generics,
912                         name: ast::Name,
913                         span: syntax_pos::Span,
914                         print_finalizer: bool)
915                         -> io::Result<()> {
916         self.print_name(name)?;
917         self.print_generics(generics)?;
918         if !struct_def.is_struct() {
919             if struct_def.is_tuple() {
920                 self.popen()?;
921                 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
922                     s.maybe_print_comment(field.span.lo)?;
923                     s.print_outer_attributes(&field.attrs)?;
924                     s.print_visibility(&field.vis)?;
925                     s.print_type(&field.ty)
926                 })?;
927                 self.pclose()?;
928             }
929             self.print_where_clause(&generics.where_clause)?;
930             if print_finalizer {
931                 word(&mut self.s, ";")?;
932             }
933             self.end()?;
934             self.end() // close the outer-box
935         } else {
936             self.print_where_clause(&generics.where_clause)?;
937             self.nbsp()?;
938             self.bopen()?;
939             self.hardbreak_if_not_bol()?;
940
941             for field in struct_def.fields() {
942                 self.hardbreak_if_not_bol()?;
943                 self.maybe_print_comment(field.span.lo)?;
944                 self.print_outer_attributes(&field.attrs)?;
945                 self.print_visibility(&field.vis)?;
946                 self.print_name(field.name)?;
947                 self.word_nbsp(":")?;
948                 self.print_type(&field.ty)?;
949                 word(&mut self.s, ",")?;
950             }
951
952             self.bclose(span)
953         }
954     }
955
956     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
957         self.head("")?;
958         let generics = hir::Generics::empty();
959         self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
960         match v.node.disr_expr {
961             Some(ref d) => {
962                 space(&mut self.s)?;
963                 self.word_space("=")?;
964                 self.print_expr(&d)
965             }
966             _ => Ok(()),
967         }
968     }
969     pub fn print_method_sig(&mut self,
970                             name: ast::Name,
971                             m: &hir::MethodSig,
972                             vis: &hir::Visibility)
973                             -> io::Result<()> {
974         self.print_fn(&m.decl,
975                       m.unsafety,
976                       m.constness,
977                       m.abi,
978                       Some(name),
979                       &m.generics,
980                       vis)
981     }
982
983     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
984         self.ann.pre(self, NodeSubItem(ti.id))?;
985         self.hardbreak_if_not_bol()?;
986         self.maybe_print_comment(ti.span.lo)?;
987         self.print_outer_attributes(&ti.attrs)?;
988         match ti.node {
989             hir::ConstTraitItem(ref ty, ref default) => {
990                 self.print_associated_const(ti.name,
991                                             &ty,
992                                             default.as_ref().map(|expr| &**expr),
993                                             &hir::Inherited)?;
994             }
995             hir::MethodTraitItem(ref sig, ref body) => {
996                 if body.is_some() {
997                     self.head("")?;
998                 }
999                 self.print_method_sig(ti.name, sig, &hir::Inherited)?;
1000                 if let Some(ref body) = *body {
1001                     self.nbsp()?;
1002                     self.print_block_with_attrs(body, &ti.attrs)?;
1003                 } else {
1004                     word(&mut self.s, ";")?;
1005                 }
1006             }
1007             hir::TypeTraitItem(ref bounds, ref default) => {
1008                 self.print_associated_type(ti.name,
1009                                            Some(bounds),
1010                                            default.as_ref().map(|ty| &**ty))?;
1011             }
1012         }
1013         self.ann.post(self, NodeSubItem(ti.id))
1014     }
1015
1016     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1017         self.ann.pre(self, NodeSubItem(ii.id))?;
1018         self.hardbreak_if_not_bol()?;
1019         self.maybe_print_comment(ii.span.lo)?;
1020         self.print_outer_attributes(&ii.attrs)?;
1021
1022         if let hir::Defaultness::Default = ii.defaultness {
1023             self.word_nbsp("default")?;
1024         }
1025
1026         match ii.node {
1027             hir::ImplItemKind::Const(ref ty, ref expr) => {
1028                 self.print_associated_const(ii.name, &ty, Some(&expr), &ii.vis)?;
1029             }
1030             hir::ImplItemKind::Method(ref sig, ref body) => {
1031                 self.head("")?;
1032                 self.print_method_sig(ii.name, sig, &ii.vis)?;
1033                 self.nbsp()?;
1034                 self.print_block_with_attrs(body, &ii.attrs)?;
1035             }
1036             hir::ImplItemKind::Type(ref ty) => {
1037                 self.print_associated_type(ii.name, None, Some(ty))?;
1038             }
1039         }
1040         self.ann.post(self, NodeSubItem(ii.id))
1041     }
1042
1043     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1044         self.maybe_print_comment(st.span.lo)?;
1045         match st.node {
1046             hir::StmtDecl(ref decl, _) => {
1047                 self.print_decl(&decl)?;
1048             }
1049             hir::StmtExpr(ref expr, _) => {
1050                 self.space_if_not_bol()?;
1051                 self.print_expr(&expr)?;
1052             }
1053             hir::StmtSemi(ref expr, _) => {
1054                 self.space_if_not_bol()?;
1055                 self.print_expr(&expr)?;
1056                 word(&mut self.s, ";")?;
1057             }
1058         }
1059         if stmt_ends_with_semi(&st.node) {
1060             word(&mut self.s, ";")?;
1061         }
1062         self.maybe_print_trailing_comment(st.span, None)
1063     }
1064
1065     pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1066         self.print_block_with_attrs(blk, &[])
1067     }
1068
1069     pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1070         self.print_block_unclosed_indent(blk, indent_unit)
1071     }
1072
1073     pub fn print_block_unclosed_indent(&mut self,
1074                                        blk: &hir::Block,
1075                                        indented: usize)
1076                                        -> io::Result<()> {
1077         self.print_block_maybe_unclosed(blk, indented, &[], false)
1078     }
1079
1080     pub fn print_block_with_attrs(&mut self,
1081                                   blk: &hir::Block,
1082                                   attrs: &[ast::Attribute])
1083                                   -> io::Result<()> {
1084         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1085     }
1086
1087     pub fn print_block_maybe_unclosed(&mut self,
1088                                       blk: &hir::Block,
1089                                       indented: usize,
1090                                       attrs: &[ast::Attribute],
1091                                       close_box: bool)
1092                                       -> io::Result<()> {
1093         match blk.rules {
1094             hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1095             hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1096             hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1097             hir::PushUnstableBlock => self.word_space("push_unstable")?,
1098             hir::PopUnstableBlock => self.word_space("pop_unstable")?,
1099             hir::DefaultBlock => (),
1100         }
1101         self.maybe_print_comment(blk.span.lo)?;
1102         self.ann.pre(self, NodeBlock(blk))?;
1103         self.bopen()?;
1104
1105         self.print_inner_attributes(attrs)?;
1106
1107         for st in &blk.stmts {
1108             self.print_stmt(st)?;
1109         }
1110         match blk.expr {
1111             Some(ref expr) => {
1112                 self.space_if_not_bol()?;
1113                 self.print_expr(&expr)?;
1114                 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1115             }
1116             _ => (),
1117         }
1118         self.bclose_maybe_open(blk.span, indented, close_box)?;
1119         self.ann.post(self, NodeBlock(blk))
1120     }
1121
1122     fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1123         match els {
1124             Some(_else) => {
1125                 match _else.node {
1126                     // "another else-if"
1127                     hir::ExprIf(ref i, ref then, ref e) => {
1128                         self.cbox(indent_unit - 1)?;
1129                         self.ibox(0)?;
1130                         word(&mut self.s, " else if ")?;
1131                         self.print_expr(&i)?;
1132                         space(&mut self.s)?;
1133                         self.print_block(&then)?;
1134                         self.print_else(e.as_ref().map(|e| &**e))
1135                     }
1136                     // "final else"
1137                     hir::ExprBlock(ref b) => {
1138                         self.cbox(indent_unit - 1)?;
1139                         self.ibox(0)?;
1140                         word(&mut self.s, " else ")?;
1141                         self.print_block(&b)
1142                     }
1143                     // BLEAH, constraints would be great here
1144                     _ => {
1145                         panic!("print_if saw if with weird alternative");
1146                     }
1147                 }
1148             }
1149             _ => Ok(()),
1150         }
1151     }
1152
1153     pub fn print_if(&mut self,
1154                     test: &hir::Expr,
1155                     blk: &hir::Block,
1156                     elseopt: Option<&hir::Expr>)
1157                     -> io::Result<()> {
1158         self.head("if")?;
1159         self.print_expr(test)?;
1160         space(&mut self.s)?;
1161         self.print_block(blk)?;
1162         self.print_else(elseopt)
1163     }
1164
1165     pub fn print_if_let(&mut self,
1166                         pat: &hir::Pat,
1167                         expr: &hir::Expr,
1168                         blk: &hir::Block,
1169                         elseopt: Option<&hir::Expr>)
1170                         -> io::Result<()> {
1171         self.head("if let")?;
1172         self.print_pat(pat)?;
1173         space(&mut self.s)?;
1174         self.word_space("=")?;
1175         self.print_expr(expr)?;
1176         space(&mut self.s)?;
1177         self.print_block(blk)?;
1178         self.print_else(elseopt)
1179     }
1180
1181
1182     fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1183         self.popen()?;
1184         self.commasep_exprs(Inconsistent, args)?;
1185         self.pclose()
1186     }
1187
1188     pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1189         let needs_par = needs_parentheses(expr);
1190         if needs_par {
1191             self.popen()?;
1192         }
1193         self.print_expr(expr)?;
1194         if needs_par {
1195             self.pclose()?;
1196         }
1197         Ok(())
1198     }
1199
1200     fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1201         self.ibox(indent_unit)?;
1202         word(&mut self.s, "[")?;
1203         self.commasep_exprs(Inconsistent, &exprs[..])?;
1204         word(&mut self.s, "]")?;
1205         self.end()
1206     }
1207
1208     fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1209         self.ibox(indent_unit)?;
1210         word(&mut self.s, "[")?;
1211         self.print_expr(element)?;
1212         self.word_space(";")?;
1213         self.print_expr(count)?;
1214         word(&mut self.s, "]")?;
1215         self.end()
1216     }
1217
1218     fn print_expr_struct(&mut self,
1219                          path: &hir::Path,
1220                          fields: &[hir::Field],
1221                          wth: &Option<P<hir::Expr>>)
1222                          -> io::Result<()> {
1223         self.print_path(path, true, 0)?;
1224         word(&mut self.s, "{")?;
1225         self.commasep_cmnt(Consistent,
1226                            &fields[..],
1227                            |s, field| {
1228                                s.ibox(indent_unit)?;
1229                                s.print_name(field.name.node)?;
1230                                s.word_space(":")?;
1231                                s.print_expr(&field.expr)?;
1232                                s.end()
1233                            },
1234                            |f| f.span)?;
1235         match *wth {
1236             Some(ref expr) => {
1237                 self.ibox(indent_unit)?;
1238                 if !fields.is_empty() {
1239                     word(&mut self.s, ",")?;
1240                     space(&mut self.s)?;
1241                 }
1242                 word(&mut self.s, "..")?;
1243                 self.print_expr(&expr)?;
1244                 self.end()?;
1245             }
1246             _ => if !fields.is_empty() {
1247                 word(&mut self.s, ",")?
1248             },
1249         }
1250         word(&mut self.s, "}")?;
1251         Ok(())
1252     }
1253
1254     fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1255         self.popen()?;
1256         self.commasep_exprs(Inconsistent, &exprs[..])?;
1257         if exprs.len() == 1 {
1258             word(&mut self.s, ",")?;
1259         }
1260         self.pclose()
1261     }
1262
1263     fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1264         self.print_expr_maybe_paren(func)?;
1265         self.print_call_post(args)
1266     }
1267
1268     fn print_expr_method_call(&mut self,
1269                               name: Spanned<ast::Name>,
1270                               tys: &[P<hir::Ty>],
1271                               args: &[P<hir::Expr>])
1272                               -> io::Result<()> {
1273         let base_args = &args[1..];
1274         self.print_expr(&args[0])?;
1275         word(&mut self.s, ".")?;
1276         self.print_name(name.node)?;
1277         if !tys.is_empty() {
1278             word(&mut self.s, "::<")?;
1279             self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1280             word(&mut self.s, ">")?;
1281         }
1282         self.print_call_post(base_args)
1283     }
1284
1285     fn print_expr_binary(&mut self,
1286                          op: hir::BinOp,
1287                          lhs: &hir::Expr,
1288                          rhs: &hir::Expr)
1289                          -> io::Result<()> {
1290         self.print_expr(lhs)?;
1291         space(&mut self.s)?;
1292         self.word_space(op.node.as_str())?;
1293         self.print_expr(rhs)
1294     }
1295
1296     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1297         word(&mut self.s, op.as_str())?;
1298         self.print_expr_maybe_paren(expr)
1299     }
1300
1301     fn print_expr_addr_of(&mut self,
1302                           mutability: hir::Mutability,
1303                           expr: &hir::Expr)
1304                           -> io::Result<()> {
1305         word(&mut self.s, "&")?;
1306         self.print_mutability(mutability)?;
1307         self.print_expr_maybe_paren(expr)
1308     }
1309
1310     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1311         self.maybe_print_comment(expr.span.lo)?;
1312         self.ibox(indent_unit)?;
1313         self.ann.pre(self, NodeExpr(expr))?;
1314         match expr.node {
1315             hir::ExprBox(ref expr) => {
1316                 self.word_space("box")?;
1317                 self.print_expr(expr)?;
1318             }
1319             hir::ExprVec(ref exprs) => {
1320                 self.print_expr_vec(&exprs[..])?;
1321             }
1322             hir::ExprRepeat(ref element, ref count) => {
1323                 self.print_expr_repeat(&element, &count)?;
1324             }
1325             hir::ExprStruct(ref path, ref fields, ref wth) => {
1326                 self.print_expr_struct(path, &fields[..], wth)?;
1327             }
1328             hir::ExprTup(ref exprs) => {
1329                 self.print_expr_tup(&exprs[..])?;
1330             }
1331             hir::ExprCall(ref func, ref args) => {
1332                 self.print_expr_call(&func, &args[..])?;
1333             }
1334             hir::ExprMethodCall(name, ref tys, ref args) => {
1335                 self.print_expr_method_call(name, &tys[..], &args[..])?;
1336             }
1337             hir::ExprBinary(op, ref lhs, ref rhs) => {
1338                 self.print_expr_binary(op, &lhs, &rhs)?;
1339             }
1340             hir::ExprUnary(op, ref expr) => {
1341                 self.print_expr_unary(op, &expr)?;
1342             }
1343             hir::ExprAddrOf(m, ref expr) => {
1344                 self.print_expr_addr_of(m, &expr)?;
1345             }
1346             hir::ExprLit(ref lit) => {
1347                 self.print_literal(&lit)?;
1348             }
1349             hir::ExprCast(ref expr, ref ty) => {
1350                 self.print_expr(&expr)?;
1351                 space(&mut self.s)?;
1352                 self.word_space("as")?;
1353                 self.print_type(&ty)?;
1354             }
1355             hir::ExprType(ref expr, ref ty) => {
1356                 self.print_expr(&expr)?;
1357                 self.word_space(":")?;
1358                 self.print_type(&ty)?;
1359             }
1360             hir::ExprIf(ref test, ref blk, ref elseopt) => {
1361                 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1362             }
1363             hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1364                 if let Some(sp_name) = opt_sp_name {
1365                     self.print_name(sp_name.node)?;
1366                     self.word_space(":")?;
1367                 }
1368                 self.head("while")?;
1369                 self.print_expr(&test)?;
1370                 space(&mut self.s)?;
1371                 self.print_block(&blk)?;
1372             }
1373             hir::ExprLoop(ref blk, opt_sp_name) => {
1374                 if let Some(sp_name) = opt_sp_name {
1375                     self.print_name(sp_name.node)?;
1376                     self.word_space(":")?;
1377                 }
1378                 self.head("loop")?;
1379                 space(&mut self.s)?;
1380                 self.print_block(&blk)?;
1381             }
1382             hir::ExprMatch(ref expr, ref arms, _) => {
1383                 self.cbox(indent_unit)?;
1384                 self.ibox(4)?;
1385                 self.word_nbsp("match")?;
1386                 self.print_expr(&expr)?;
1387                 space(&mut self.s)?;
1388                 self.bopen()?;
1389                 for arm in arms {
1390                     self.print_arm(arm)?;
1391                 }
1392                 self.bclose_(expr.span, indent_unit)?;
1393             }
1394             hir::ExprClosure(capture_clause, ref decl, ref body, _fn_decl_span) => {
1395                 self.print_capture_clause(capture_clause)?;
1396
1397                 self.print_fn_block_args(&decl)?;
1398                 space(&mut self.s)?;
1399
1400                 let default_return = match decl.output {
1401                     hir::DefaultReturn(..) => true,
1402                     _ => false,
1403                 };
1404
1405                 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1406                     self.print_block_unclosed(&body)?;
1407                 } else {
1408                     // we extract the block, so as not to create another set of boxes
1409                     match body.expr.as_ref().unwrap().node {
1410                         hir::ExprBlock(ref blk) => {
1411                             self.print_block_unclosed(&blk)?;
1412                         }
1413                         _ => {
1414                             // this is a bare expression
1415                             self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap())?;
1416                             self.end()?; // need to close a box
1417                         }
1418                     }
1419                 }
1420                 // a box will be closed by print_expr, but we didn't want an overall
1421                 // wrapper so we closed the corresponding opening. so create an
1422                 // empty box to satisfy the close.
1423                 self.ibox(0)?;
1424             }
1425             hir::ExprBlock(ref blk) => {
1426                 // containing cbox, will be closed by print-block at }
1427                 self.cbox(indent_unit)?;
1428                 // head-box, will be closed by print-block after {
1429                 self.ibox(0)?;
1430                 self.print_block(&blk)?;
1431             }
1432             hir::ExprAssign(ref lhs, ref rhs) => {
1433                 self.print_expr(&lhs)?;
1434                 space(&mut self.s)?;
1435                 self.word_space("=")?;
1436                 self.print_expr(&rhs)?;
1437             }
1438             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1439                 self.print_expr(&lhs)?;
1440                 space(&mut self.s)?;
1441                 word(&mut self.s, op.node.as_str())?;
1442                 self.word_space("=")?;
1443                 self.print_expr(&rhs)?;
1444             }
1445             hir::ExprField(ref expr, name) => {
1446                 self.print_expr(&expr)?;
1447                 word(&mut self.s, ".")?;
1448                 self.print_name(name.node)?;
1449             }
1450             hir::ExprTupField(ref expr, id) => {
1451                 self.print_expr(&expr)?;
1452                 word(&mut self.s, ".")?;
1453                 self.print_usize(id.node)?;
1454             }
1455             hir::ExprIndex(ref expr, ref index) => {
1456                 self.print_expr(&expr)?;
1457                 word(&mut self.s, "[")?;
1458                 self.print_expr(&index)?;
1459                 word(&mut self.s, "]")?;
1460             }
1461             hir::ExprPath(None, ref path) => {
1462                 self.print_path(path, true, 0)?
1463             }
1464             hir::ExprPath(Some(ref qself), ref path) => {
1465                 self.print_qpath(path, qself, true)?
1466             }
1467             hir::ExprBreak(opt_name) => {
1468                 word(&mut self.s, "break")?;
1469                 space(&mut self.s)?;
1470                 if let Some(name) = opt_name {
1471                     self.print_name(name.node)?;
1472                     space(&mut self.s)?;
1473                 }
1474             }
1475             hir::ExprAgain(opt_name) => {
1476                 word(&mut self.s, "continue")?;
1477                 space(&mut self.s)?;
1478                 if let Some(name) = opt_name {
1479                     self.print_name(name.node)?;
1480                     space(&mut self.s)?
1481                 }
1482             }
1483             hir::ExprRet(ref result) => {
1484                 word(&mut self.s, "return")?;
1485                 match *result {
1486                     Some(ref expr) => {
1487                         word(&mut self.s, " ")?;
1488                         self.print_expr(&expr)?;
1489                     }
1490                     _ => (),
1491                 }
1492             }
1493             hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1494                 word(&mut self.s, "asm!")?;
1495                 self.popen()?;
1496                 self.print_string(&a.asm, a.asm_str_style)?;
1497                 self.word_space(":")?;
1498
1499                 let mut out_idx = 0;
1500                 self.commasep(Inconsistent, &a.outputs, |s, out| {
1501                     let mut ch = out.constraint.chars();
1502                     match ch.next() {
1503                         Some('=') if out.is_rw => {
1504                             s.print_string(&format!("+{}", ch.as_str()),
1505                                            ast::StrStyle::Cooked)?
1506                         }
1507                         _ => s.print_string(&out.constraint,
1508                                             ast::StrStyle::Cooked)?,
1509                     }
1510                     s.popen()?;
1511                     s.print_expr(&outputs[out_idx])?;
1512                     s.pclose()?;
1513                     out_idx += 1;
1514                     Ok(())
1515                 })?;
1516                 space(&mut self.s)?;
1517                 self.word_space(":")?;
1518
1519                 let mut in_idx = 0;
1520                 self.commasep(Inconsistent, &a.inputs, |s, co| {
1521                     s.print_string(&co, ast::StrStyle::Cooked)?;
1522                     s.popen()?;
1523                     s.print_expr(&inputs[in_idx])?;
1524                     s.pclose()?;
1525                     in_idx += 1;
1526                     Ok(())
1527                 })?;
1528                 space(&mut self.s)?;
1529                 self.word_space(":")?;
1530
1531                 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1532                     s.print_string(&co, ast::StrStyle::Cooked)?;
1533                     Ok(())
1534                 })?;
1535
1536                 let mut options = vec![];
1537                 if a.volatile {
1538                     options.push("volatile");
1539                 }
1540                 if a.alignstack {
1541                     options.push("alignstack");
1542                 }
1543                 if a.dialect == ast::AsmDialect::Intel {
1544                     options.push("intel");
1545                 }
1546
1547                 if !options.is_empty() {
1548                     space(&mut self.s)?;
1549                     self.word_space(":")?;
1550                     self.commasep(Inconsistent, &options, |s, &co| {
1551                         s.print_string(co, ast::StrStyle::Cooked)?;
1552                         Ok(())
1553                     })?;
1554                 }
1555
1556                 self.pclose()?;
1557             }
1558         }
1559         self.ann.post(self, NodeExpr(expr))?;
1560         self.end()
1561     }
1562
1563     pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1564         self.print_pat(&loc.pat)?;
1565         if let Some(ref ty) = loc.ty {
1566             self.word_space(":")?;
1567             self.print_type(&ty)?;
1568         }
1569         Ok(())
1570     }
1571
1572     pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1573         self.maybe_print_comment(decl.span.lo)?;
1574         match decl.node {
1575             hir::DeclLocal(ref loc) => {
1576                 self.space_if_not_bol()?;
1577                 self.ibox(indent_unit)?;
1578                 self.word_nbsp("let")?;
1579
1580                 self.ibox(indent_unit)?;
1581                 self.print_local_decl(&loc)?;
1582                 self.end()?;
1583                 if let Some(ref init) = loc.init {
1584                     self.nbsp()?;
1585                     self.word_space("=")?;
1586                     self.print_expr(&init)?;
1587                 }
1588                 self.end()
1589             }
1590             hir::DeclItem(ref item) => {
1591                 self.print_item_id(item)
1592             }
1593         }
1594     }
1595
1596     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1597         word(&mut self.s, &i.to_string())
1598     }
1599
1600     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1601         word(&mut self.s, &name.as_str())?;
1602         self.ann.post(self, NodeName(&name))
1603     }
1604
1605     pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1606         self.print_local_decl(loc)?;
1607         space(&mut self.s)?;
1608         self.word_space("in")?;
1609         self.print_expr(coll)
1610     }
1611
1612     fn print_path(&mut self,
1613                   path: &hir::Path,
1614                   colons_before_params: bool,
1615                   depth: usize)
1616                   -> io::Result<()> {
1617         self.maybe_print_comment(path.span.lo)?;
1618
1619         let mut first = !path.global;
1620         for segment in &path.segments[..path.segments.len() - depth] {
1621             if first {
1622                 first = false
1623             } else {
1624                 word(&mut self.s, "::")?
1625             }
1626
1627             self.print_name(segment.name)?;
1628
1629             self.print_path_parameters(&segment.parameters, colons_before_params)?;
1630         }
1631
1632         Ok(())
1633     }
1634
1635     fn print_qpath(&mut self,
1636                    path: &hir::Path,
1637                    qself: &hir::QSelf,
1638                    colons_before_params: bool)
1639                    -> io::Result<()> {
1640         word(&mut self.s, "<")?;
1641         self.print_type(&qself.ty)?;
1642         if qself.position > 0 {
1643             space(&mut self.s)?;
1644             self.word_space("as")?;
1645             let depth = path.segments.len() - qself.position;
1646             self.print_path(&path, false, depth)?;
1647         }
1648         word(&mut self.s, ">")?;
1649         word(&mut self.s, "::")?;
1650         let item_segment = path.segments.last().unwrap();
1651         self.print_name(item_segment.name)?;
1652         self.print_path_parameters(&item_segment.parameters, colons_before_params)
1653     }
1654
1655     fn print_path_parameters(&mut self,
1656                              parameters: &hir::PathParameters,
1657                              colons_before_params: bool)
1658                              -> io::Result<()> {
1659         if parameters.is_empty() {
1660             return Ok(());
1661         }
1662
1663         if colons_before_params {
1664             word(&mut self.s, "::")?
1665         }
1666
1667         match *parameters {
1668             hir::AngleBracketedParameters(ref data) => {
1669                 word(&mut self.s, "<")?;
1670
1671                 let mut comma = false;
1672                 for lifetime in &data.lifetimes {
1673                     if comma {
1674                         self.word_space(",")?
1675                     }
1676                     self.print_lifetime(lifetime)?;
1677                     comma = true;
1678                 }
1679
1680                 if !data.types.is_empty() {
1681                     if comma {
1682                         self.word_space(",")?
1683                     }
1684                     self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1685                     comma = true;
1686                 }
1687
1688                 for binding in data.bindings.iter() {
1689                     if comma {
1690                         self.word_space(",")?
1691                     }
1692                     self.print_name(binding.name)?;
1693                     space(&mut self.s)?;
1694                     self.word_space("=")?;
1695                     self.print_type(&binding.ty)?;
1696                     comma = true;
1697                 }
1698
1699                 word(&mut self.s, ">")?
1700             }
1701
1702             hir::ParenthesizedParameters(ref data) => {
1703                 word(&mut self.s, "(")?;
1704                 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1705                 word(&mut self.s, ")")?;
1706
1707                 if let Some(ref ty) = data.output {
1708                     self.space_if_not_bol()?;
1709                     self.word_space("->")?;
1710                     self.print_type(&ty)?;
1711                 }
1712             }
1713         }
1714
1715         Ok(())
1716     }
1717
1718     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1719         self.maybe_print_comment(pat.span.lo)?;
1720         self.ann.pre(self, NodePat(pat))?;
1721         // Pat isn't normalized, but the beauty of it
1722         // is that it doesn't matter
1723         match pat.node {
1724             PatKind::Wild => word(&mut self.s, "_")?,
1725             PatKind::Binding(binding_mode, ref path1, ref sub) => {
1726                 match binding_mode {
1727                     hir::BindByRef(mutbl) => {
1728                         self.word_nbsp("ref")?;
1729                         self.print_mutability(mutbl)?;
1730                     }
1731                     hir::BindByValue(hir::MutImmutable) => {}
1732                     hir::BindByValue(hir::MutMutable) => {
1733                         self.word_nbsp("mut")?;
1734                     }
1735                 }
1736                 self.print_name(path1.node)?;
1737                 if let Some(ref p) = *sub {
1738                     word(&mut self.s, "@")?;
1739                     self.print_pat(&p)?;
1740                 }
1741             }
1742             PatKind::TupleStruct(ref path, ref elts, ddpos) => {
1743                 self.print_path(path, true, 0)?;
1744                 self.popen()?;
1745                 if let Some(ddpos) = ddpos {
1746                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1747                     if ddpos != 0 {
1748                         self.word_space(",")?;
1749                     }
1750                     word(&mut self.s, "..")?;
1751                     if ddpos != elts.len() {
1752                         word(&mut self.s, ",")?;
1753                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1754                     }
1755                 } else {
1756                     try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
1757                 }
1758                 try!(self.pclose());
1759             }
1760             PatKind::Path(None, ref path) => {
1761                 self.print_path(path, true, 0)?;
1762             }
1763             PatKind::Path(Some(ref qself), ref path) => {
1764                 self.print_qpath(path, qself, false)?;
1765             }
1766             PatKind::Struct(ref path, ref fields, etc) => {
1767                 self.print_path(path, true, 0)?;
1768                 self.nbsp()?;
1769                 self.word_space("{")?;
1770                 self.commasep_cmnt(Consistent,
1771                                    &fields[..],
1772                                    |s, f| {
1773                                        s.cbox(indent_unit)?;
1774                                        if !f.node.is_shorthand {
1775                                            s.print_name(f.node.name)?;
1776                                            s.word_nbsp(":")?;
1777                                        }
1778                                        s.print_pat(&f.node.pat)?;
1779                                        s.end()
1780                                    },
1781                                    |f| f.node.pat.span)?;
1782                 if etc {
1783                     if !fields.is_empty() {
1784                         self.word_space(",")?;
1785                     }
1786                     word(&mut self.s, "..")?;
1787                 }
1788                 space(&mut self.s)?;
1789                 word(&mut self.s, "}")?;
1790             }
1791             PatKind::Tuple(ref elts, ddpos) => {
1792                 self.popen()?;
1793                 if let Some(ddpos) = ddpos {
1794                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1795                     if ddpos != 0 {
1796                         self.word_space(",")?;
1797                     }
1798                     word(&mut self.s, "..")?;
1799                     if ddpos != elts.len() {
1800                         word(&mut self.s, ",")?;
1801                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1802                     }
1803                 } else {
1804                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1805                     if elts.len() == 1 {
1806                         word(&mut self.s, ",")?;
1807                     }
1808                 }
1809                 self.pclose()?;
1810             }
1811             PatKind::Box(ref inner) => {
1812                 word(&mut self.s, "box ")?;
1813                 self.print_pat(&inner)?;
1814             }
1815             PatKind::Ref(ref inner, mutbl) => {
1816                 word(&mut self.s, "&")?;
1817                 if mutbl == hir::MutMutable {
1818                     word(&mut self.s, "mut ")?;
1819                 }
1820                 self.print_pat(&inner)?;
1821             }
1822             PatKind::Lit(ref e) => self.print_expr(&e)?,
1823             PatKind::Range(ref begin, ref end) => {
1824                 self.print_expr(&begin)?;
1825                 space(&mut self.s)?;
1826                 word(&mut self.s, "...")?;
1827                 self.print_expr(&end)?;
1828             }
1829             PatKind::Vec(ref before, ref slice, ref after) => {
1830                 word(&mut self.s, "[")?;
1831                 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1832                 if let Some(ref p) = *slice {
1833                     if !before.is_empty() {
1834                         self.word_space(",")?;
1835                     }
1836                     if p.node != PatKind::Wild {
1837                         self.print_pat(&p)?;
1838                     }
1839                     word(&mut self.s, "..")?;
1840                     if !after.is_empty() {
1841                         self.word_space(",")?;
1842                     }
1843                 }
1844                 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1845                 word(&mut self.s, "]")?;
1846             }
1847         }
1848         self.ann.post(self, NodePat(pat))
1849     }
1850
1851     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1852         // I have no idea why this check is necessary, but here it
1853         // is :(
1854         if arm.attrs.is_empty() {
1855             space(&mut self.s)?;
1856         }
1857         self.cbox(indent_unit)?;
1858         self.ibox(0)?;
1859         self.print_outer_attributes(&arm.attrs)?;
1860         let mut first = true;
1861         for p in &arm.pats {
1862             if first {
1863                 first = false;
1864             } else {
1865                 space(&mut self.s)?;
1866                 self.word_space("|")?;
1867             }
1868             self.print_pat(&p)?;
1869         }
1870         space(&mut self.s)?;
1871         if let Some(ref e) = arm.guard {
1872             self.word_space("if")?;
1873             self.print_expr(&e)?;
1874             space(&mut self.s)?;
1875         }
1876         self.word_space("=>")?;
1877
1878         match arm.body.node {
1879             hir::ExprBlock(ref blk) => {
1880                 // the block will close the pattern's ibox
1881                 self.print_block_unclosed_indent(&blk, indent_unit)?;
1882
1883                 // If it is a user-provided unsafe block, print a comma after it
1884                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1885                     word(&mut self.s, ",")?;
1886                 }
1887             }
1888             _ => {
1889                 self.end()?; // close the ibox for the pattern
1890                 self.print_expr(&arm.body)?;
1891                 word(&mut self.s, ",")?;
1892             }
1893         }
1894         self.end() // close enclosing cbox
1895     }
1896
1897     fn print_explicit_self(&mut self, explicit_self: &hir::ExplicitSelf) -> io::Result<()> {
1898         match explicit_self.node {
1899             SelfKind::Value(m) => {
1900                 self.print_mutability(m)?;
1901                 word(&mut self.s, "self")
1902             }
1903             SelfKind::Region(ref lt, m) => {
1904                 word(&mut self.s, "&")?;
1905                 self.print_opt_lifetime(lt)?;
1906                 self.print_mutability(m)?;
1907                 word(&mut self.s, "self")
1908             }
1909             SelfKind::Explicit(ref typ, m) => {
1910                 self.print_mutability(m)?;
1911                 word(&mut self.s, "self")?;
1912                 self.word_space(":")?;
1913                 self.print_type(&typ)
1914             }
1915         }
1916     }
1917
1918     pub fn print_fn(&mut self,
1919                     decl: &hir::FnDecl,
1920                     unsafety: hir::Unsafety,
1921                     constness: hir::Constness,
1922                     abi: Abi,
1923                     name: Option<ast::Name>,
1924                     generics: &hir::Generics,
1925                     vis: &hir::Visibility)
1926                     -> io::Result<()> {
1927         self.print_fn_header_info(unsafety, constness, abi, vis)?;
1928
1929         if let Some(name) = name {
1930             self.nbsp()?;
1931             self.print_name(name)?;
1932         }
1933         self.print_generics(generics)?;
1934         self.print_fn_args_and_ret(decl)?;
1935         self.print_where_clause(&generics.where_clause)
1936     }
1937
1938     pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1939         self.popen()?;
1940         self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
1941         if decl.variadic {
1942             word(&mut self.s, ", ...")?;
1943         }
1944         self.pclose()?;
1945
1946         self.print_fn_output(decl)
1947     }
1948
1949     pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1950         word(&mut self.s, "|")?;
1951         self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
1952         word(&mut self.s, "|")?;
1953
1954         if let hir::DefaultReturn(..) = decl.output {
1955             return Ok(());
1956         }
1957
1958         self.space_if_not_bol()?;
1959         self.word_space("->")?;
1960         match decl.output {
1961             hir::Return(ref ty) => {
1962                 self.print_type(&ty)?;
1963                 self.maybe_print_comment(ty.span.lo)
1964             }
1965             hir::DefaultReturn(..) => unreachable!(),
1966         }
1967     }
1968
1969     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1970         match capture_clause {
1971             hir::CaptureByValue => self.word_space("move"),
1972             hir::CaptureByRef => Ok(()),
1973         }
1974     }
1975
1976     pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1977         if !bounds.is_empty() {
1978             word(&mut self.s, prefix)?;
1979             let mut first = true;
1980             for bound in bounds {
1981                 self.nbsp()?;
1982                 if first {
1983                     first = false;
1984                 } else {
1985                     self.word_space("+")?;
1986                 }
1987
1988                 match *bound {
1989                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1990                         self.print_poly_trait_ref(tref)
1991                     }
1992                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1993                         word(&mut self.s, "?")?;
1994                         self.print_poly_trait_ref(tref)
1995                     }
1996                     RegionTyParamBound(ref lt) => {
1997                         self.print_lifetime(lt)
1998                     }
1999                 }?
2000             }
2001             Ok(())
2002         } else {
2003             Ok(())
2004         }
2005     }
2006
2007     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2008         self.print_name(lifetime.name)
2009     }
2010
2011     pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2012         self.print_lifetime(&lifetime.lifetime)?;
2013         let mut sep = ":";
2014         for v in &lifetime.bounds {
2015             word(&mut self.s, sep)?;
2016             self.print_lifetime(v)?;
2017             sep = "+";
2018         }
2019         Ok(())
2020     }
2021
2022     pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2023         let total = generics.lifetimes.len() + generics.ty_params.len();
2024         if total == 0 {
2025             return Ok(());
2026         }
2027
2028         word(&mut self.s, "<")?;
2029
2030         let mut ints = Vec::new();
2031         for i in 0..total {
2032             ints.push(i);
2033         }
2034
2035         self.commasep(Inconsistent, &ints[..], |s, &idx| {
2036             if idx < generics.lifetimes.len() {
2037                 let lifetime = &generics.lifetimes[idx];
2038                 s.print_lifetime_def(lifetime)
2039             } else {
2040                 let idx = idx - generics.lifetimes.len();
2041                 let param = &generics.ty_params[idx];
2042                 s.print_ty_param(param)
2043             }
2044         })?;
2045
2046         word(&mut self.s, ">")?;
2047         Ok(())
2048     }
2049
2050     pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2051         self.print_name(param.name)?;
2052         self.print_bounds(":", &param.bounds)?;
2053         match param.default {
2054             Some(ref default) => {
2055                 space(&mut self.s)?;
2056                 self.word_space("=")?;
2057                 self.print_type(&default)
2058             }
2059             _ => Ok(()),
2060         }
2061     }
2062
2063     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2064         if where_clause.predicates.is_empty() {
2065             return Ok(());
2066         }
2067
2068         space(&mut self.s)?;
2069         self.word_space("where")?;
2070
2071         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2072             if i != 0 {
2073                 self.word_space(",")?;
2074             }
2075
2076             match predicate {
2077                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2078                                                                               ref bounded_ty,
2079                                                                               ref bounds,
2080                                                                               ..}) => {
2081                     self.print_formal_lifetime_list(bound_lifetimes)?;
2082                     self.print_type(&bounded_ty)?;
2083                     self.print_bounds(":", bounds)?;
2084                 }
2085                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2086                                                                                 ref bounds,
2087                                                                                 ..}) => {
2088                     self.print_lifetime(lifetime)?;
2089                     word(&mut self.s, ":")?;
2090
2091                     for (i, bound) in bounds.iter().enumerate() {
2092                         self.print_lifetime(bound)?;
2093
2094                         if i != 0 {
2095                             word(&mut self.s, ":")?;
2096                         }
2097                     }
2098                 }
2099                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2100                     self.print_path(path, false, 0)?;
2101                     space(&mut self.s)?;
2102                     self.word_space("=")?;
2103                     self.print_type(&ty)?;
2104                 }
2105             }
2106         }
2107
2108         Ok(())
2109     }
2110
2111     pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2112         match vp.node {
2113             hir::ViewPathSimple(name, ref path) => {
2114                 self.print_path(path, false, 0)?;
2115
2116                 if path.segments.last().unwrap().name != name {
2117                     space(&mut self.s)?;
2118                     self.word_space("as")?;
2119                     self.print_name(name)?;
2120                 }
2121
2122                 Ok(())
2123             }
2124
2125             hir::ViewPathGlob(ref path) => {
2126                 self.print_path(path, false, 0)?;
2127                 word(&mut self.s, "::*")
2128             }
2129
2130             hir::ViewPathList(ref path, ref segments) => {
2131                 if path.segments.is_empty() {
2132                     word(&mut self.s, "{")?;
2133                 } else {
2134                     self.print_path(path, false, 0)?;
2135                     word(&mut self.s, "::{")?;
2136                 }
2137                 self.commasep(Inconsistent, &segments[..], |s, w| s.print_name(w.node.name))?;
2138                 word(&mut self.s, "}")
2139             }
2140         }
2141     }
2142
2143     pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2144         match mutbl {
2145             hir::MutMutable => self.word_nbsp("mut"),
2146             hir::MutImmutable => Ok(()),
2147         }
2148     }
2149
2150     pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2151         self.print_mutability(mt.mutbl)?;
2152         self.print_type(&mt.ty)
2153     }
2154
2155     pub fn print_arg(&mut self, input: &hir::Arg, is_closure: bool) -> io::Result<()> {
2156         self.ibox(indent_unit)?;
2157         match input.ty.node {
2158             hir::TyInfer if is_closure => self.print_pat(&input.pat)?,
2159             _ => {
2160                 if let Some(eself) = input.to_self() {
2161                     self.print_explicit_self(&eself)?;
2162                 } else {
2163                     let invalid = if let PatKind::Binding(_, name, _) = input.pat.node {
2164                         name.node == keywords::Invalid.name()
2165                     } else {
2166                         false
2167                     };
2168                     if !invalid {
2169                         self.print_pat(&input.pat)?;
2170                         word(&mut self.s, ":")?;
2171                         space(&mut self.s)?;
2172                     }
2173                     self.print_type(&input.ty)?;
2174                 }
2175             }
2176         }
2177         self.end()
2178     }
2179
2180     pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2181         if let hir::DefaultReturn(..) = decl.output {
2182             return Ok(());
2183         }
2184
2185         self.space_if_not_bol()?;
2186         self.ibox(indent_unit)?;
2187         self.word_space("->")?;
2188         match decl.output {
2189             hir::DefaultReturn(..) => unreachable!(),
2190             hir::Return(ref ty) => self.print_type(&ty)?,
2191         }
2192         self.end()?;
2193
2194         match decl.output {
2195             hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2196             _ => Ok(()),
2197         }
2198     }
2199
2200     pub fn print_ty_fn(&mut self,
2201                        abi: Abi,
2202                        unsafety: hir::Unsafety,
2203                        decl: &hir::FnDecl,
2204                        name: Option<ast::Name>,
2205                        generics: &hir::Generics)
2206                        -> io::Result<()> {
2207         self.ibox(indent_unit)?;
2208         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2209             word(&mut self.s, "for")?;
2210             self.print_generics(generics)?;
2211         }
2212         let generics = hir::Generics {
2213             lifetimes: hir::HirVec::new(),
2214             ty_params: hir::HirVec::new(),
2215             where_clause: hir::WhereClause {
2216                 id: ast::DUMMY_NODE_ID,
2217                 predicates: hir::HirVec::new(),
2218             },
2219             span: syntax_pos::DUMMY_SP,
2220         };
2221         self.print_fn(decl,
2222                       unsafety,
2223                       hir::Constness::NotConst,
2224                       abi,
2225                       name,
2226                       &generics,
2227                       &hir::Inherited)?;
2228         self.end()
2229     }
2230
2231     pub fn maybe_print_trailing_comment(&mut self,
2232                                         span: syntax_pos::Span,
2233                                         next_pos: Option<BytePos>)
2234                                         -> io::Result<()> {
2235         let cm = match self.cm {
2236             Some(cm) => cm,
2237             _ => return Ok(()),
2238         };
2239         if let Some(ref cmnt) = self.next_comment() {
2240             if (*cmnt).style != comments::Trailing {
2241                 return Ok(());
2242             }
2243             let span_line = cm.lookup_char_pos(span.hi);
2244             let comment_line = cm.lookup_char_pos((*cmnt).pos);
2245             let mut next = (*cmnt).pos + BytePos(1);
2246             if let Some(p) = next_pos {
2247                 next = p;
2248             }
2249             if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2250                span_line.line == comment_line.line {
2251                 self.print_comment(cmnt)?;
2252                 self.cur_cmnt_and_lit.cur_cmnt += 1;
2253             }
2254         }
2255         Ok(())
2256     }
2257
2258     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2259         // If there aren't any remaining comments, then we need to manually
2260         // make sure there is a line break at the end.
2261         if self.next_comment().is_none() {
2262             hardbreak(&mut self.s)?;
2263         }
2264         loop {
2265             match self.next_comment() {
2266                 Some(ref cmnt) => {
2267                     self.print_comment(cmnt)?;
2268                     self.cur_cmnt_and_lit.cur_cmnt += 1;
2269                 }
2270                 _ => break,
2271             }
2272         }
2273         Ok(())
2274     }
2275
2276     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2277                                                   opt_abi: Option<Abi>)
2278                                                   -> io::Result<()> {
2279         match opt_abi {
2280             Some(Abi::Rust) => Ok(()),
2281             Some(abi) => {
2282                 self.word_nbsp("extern")?;
2283                 self.word_nbsp(&abi.to_string())
2284             }
2285             None => Ok(()),
2286         }
2287     }
2288
2289     pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2290         match opt_abi {
2291             Some(abi) => {
2292                 self.word_nbsp("extern")?;
2293                 self.word_nbsp(&abi.to_string())
2294             }
2295             None => Ok(()),
2296         }
2297     }
2298
2299     pub fn print_fn_header_info(&mut self,
2300                                 unsafety: hir::Unsafety,
2301                                 constness: hir::Constness,
2302                                 abi: Abi,
2303                                 vis: &hir::Visibility)
2304                                 -> io::Result<()> {
2305         word(&mut self.s, &visibility_qualified(vis, ""))?;
2306         self.print_unsafety(unsafety)?;
2307
2308         match constness {
2309             hir::Constness::NotConst => {}
2310             hir::Constness::Const => self.word_nbsp("const")?,
2311         }
2312
2313         if abi != Abi::Rust {
2314             self.word_nbsp("extern")?;
2315             self.word_nbsp(&abi.to_string())?;
2316         }
2317
2318         word(&mut self.s, "fn")
2319     }
2320
2321     pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2322         match s {
2323             hir::Unsafety::Normal => Ok(()),
2324             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2325         }
2326     }
2327 }
2328
2329 // Dup'ed from parse::classify, but adapted for the HIR.
2330 /// Does this expression require a semicolon to be treated
2331 /// as a statement? The negation of this: 'can this expression
2332 /// be used as a statement without a semicolon' -- is used
2333 /// as an early-bail-out in the parser so that, for instance,
2334 ///     if true {...} else {...}
2335 ///      |x| 5
2336 /// isn't parsed as (if true {...} else {...} | x) | 5
2337 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2338     match e.node {
2339         hir::ExprIf(..) |
2340         hir::ExprMatch(..) |
2341         hir::ExprBlock(_) |
2342         hir::ExprWhile(..) |
2343         hir::ExprLoop(..) => false,
2344         _ => true,
2345     }
2346 }
2347
2348 /// this statement requires a semicolon after it.
2349 /// note that in one case (stmt_semi), we've already
2350 /// seen the semicolon, and thus don't need another.
2351 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2352     match *stmt {
2353         hir::StmtDecl(ref d, _) => {
2354             match d.node {
2355                 hir::DeclLocal(_) => true,
2356                 hir::DeclItem(_) => false,
2357             }
2358         }
2359         hir::StmtExpr(ref e, _) => {
2360             expr_requires_semi_to_be_stmt(&e)
2361         }
2362         hir::StmtSemi(..) => {
2363             false
2364         }
2365     }
2366 }