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