]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/print.rs
Add transpose conversions for Option and Result
[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, FileName};
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: FileName,
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: FileName,
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                 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
394                                  &f.arg_names[..])?;
395             }
396             hir::TyPath(ref qpath) => {
397                 self.print_qpath(qpath, false)?
398             }
399             hir::TyTraitObject(ref bounds, ref lifetime) => {
400                 let mut first = true;
401                 for bound in bounds {
402                     if first {
403                         first = false;
404                     } else {
405                         self.nbsp()?;
406                         self.word_space("+")?;
407                     }
408                     self.print_poly_trait_ref(bound)?;
409                 }
410                 if !lifetime.is_elided() {
411                     self.nbsp()?;
412                     self.word_space("+")?;
413                     self.print_lifetime(lifetime)?;
414                 }
415             }
416             hir::TyImplTraitExistential(ref existty, ref _lifetimes) => {
417                 self.print_bounds("impl", &existty.bounds[..])?;
418             }
419             hir::TyArray(ref ty, v) => {
420                 self.s.word("[")?;
421                 self.print_type(&ty)?;
422                 self.s.word("; ")?;
423                 self.ann.nested(self, Nested::Body(v))?;
424                 self.s.word("]")?;
425             }
426             hir::TyTypeof(e) => {
427                 self.s.word("typeof(")?;
428                 self.ann.nested(self, Nested::Body(e))?;
429                 self.s.word(")")?;
430             }
431             hir::TyInfer => {
432                 self.s.word("_")?;
433             }
434             hir::TyErr => {
435                 self.s.word("?")?;
436             }
437         }
438         self.end()
439     }
440
441     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
442         self.hardbreak_if_not_bol()?;
443         self.maybe_print_comment(item.span.lo())?;
444         self.print_outer_attributes(&item.attrs)?;
445         match item.node {
446             hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
447                 self.head("")?;
448                 self.print_fn(decl,
449                               hir::Unsafety::Normal,
450                               hir::Constness::NotConst,
451                               Abi::Rust,
452                               Some(item.name),
453                               generics,
454                               &item.vis,
455                               arg_names,
456                               None)?;
457                 self.end()?; // end head-ibox
458                 self.s.word(";")?;
459                 self.end() // end the outer fn box
460             }
461             hir::ForeignItemStatic(ref t, m) => {
462                 self.head(&visibility_qualified(&item.vis, "static"))?;
463                 if m {
464                     self.word_space("mut")?;
465                 }
466                 self.print_name(item.name)?;
467                 self.word_space(":")?;
468                 self.print_type(&t)?;
469                 self.s.word(";")?;
470                 self.end()?; // end the head-ibox
471                 self.end() // end the outer cbox
472             }
473             hir::ForeignItemType => {
474                 self.head(&visibility_qualified(&item.vis, "type"))?;
475                 self.print_name(item.name)?;
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 generics) => {
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_generic_params(&generics.params)?;
635                 self.end()?; // end the inner ibox
636
637                 self.print_where_clause(&generics.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::ItemAutoImpl(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.params.is_empty() {
681                     self.print_generic_params(&generics.params)?;
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(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
713                 self.head("")?;
714                 self.print_visibility(&item.vis)?;
715                 self.print_is_auto(is_auto)?;
716                 self.print_unsafety(unsafety)?;
717                 self.word_nbsp("trait")?;
718                 self.print_name(item.name)?;
719                 self.print_generic_params(&generics.params)?;
720                 let mut real_bounds = Vec::with_capacity(bounds.len());
721                 for b in bounds.iter() {
722                     if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
723                         self.s.space()?;
724                         self.word_space("for ?")?;
725                         self.print_trait_ref(&ptr.trait_ref)?;
726                     } else {
727                         real_bounds.push(b.clone());
728                     }
729                 }
730                 self.print_bounds(":", &real_bounds[..])?;
731                 self.print_where_clause(&generics.where_clause)?;
732                 self.s.word(" ")?;
733                 self.bopen()?;
734                 for trait_item in trait_items {
735                     self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
736                 }
737                 self.bclose(item.span)?;
738             }
739             hir::ItemTraitAlias(ref generics, ref bounds) => {
740                 self.head("")?;
741                 self.print_visibility(&item.vis)?;
742                 self.word_nbsp("trait")?;
743                 self.print_name(item.name)?;
744                 self.print_generic_params(&generics.params)?;
745                 let mut real_bounds = Vec::with_capacity(bounds.len());
746                 // FIXME(durka) this seems to be some quite outdated syntax
747                 for b in bounds.iter() {
748                     if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
749                         self.s.space()?;
750                         self.word_space("for ?")?;
751                         self.print_trait_ref(&ptr.trait_ref)?;
752                     } else {
753                         real_bounds.push(b.clone());
754                     }
755                 }
756                 self.nbsp()?;
757                 self.print_bounds("=", &real_bounds[..])?;
758                 self.print_where_clause(&generics.where_clause)?;
759                 self.s.word(";")?;
760             }
761         }
762         self.ann.post(self, NodeItem(item))
763     }
764
765     pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
766         self.print_path(&t.path, false)
767     }
768
769     fn print_formal_generic_params(
770         &mut self,
771         generic_params: &[hir::GenericParam]
772     ) -> io::Result<()> {
773         if !generic_params.is_empty() {
774             self.s.word("for")?;
775             self.print_generic_params(generic_params)?;
776             self.nbsp()?;
777         }
778         Ok(())
779     }
780
781     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
782         self.print_formal_generic_params(&t.bound_generic_params)?;
783         self.print_trait_ref(&t.trait_ref)
784     }
785
786     pub fn print_enum_def(&mut self,
787                           enum_definition: &hir::EnumDef,
788                           generics: &hir::Generics,
789                           name: ast::Name,
790                           span: syntax_pos::Span,
791                           visibility: &hir::Visibility)
792                           -> io::Result<()> {
793         self.head(&visibility_qualified(visibility, "enum"))?;
794         self.print_name(name)?;
795         self.print_generic_params(&generics.params)?;
796         self.print_where_clause(&generics.where_clause)?;
797         self.s.space()?;
798         self.print_variants(&enum_definition.variants, span)
799     }
800
801     pub fn print_variants(&mut self,
802                           variants: &[hir::Variant],
803                           span: syntax_pos::Span)
804                           -> io::Result<()> {
805         self.bopen()?;
806         for v in variants {
807             self.space_if_not_bol()?;
808             self.maybe_print_comment(v.span.lo())?;
809             self.print_outer_attributes(&v.node.attrs)?;
810             self.ibox(indent_unit)?;
811             self.print_variant(v)?;
812             self.s.word(",")?;
813             self.end()?;
814             self.maybe_print_trailing_comment(v.span, None)?;
815         }
816         self.bclose(span)
817     }
818
819     pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
820         match *vis {
821             hir::Public => self.word_nbsp("pub"),
822             hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
823             hir::Visibility::Restricted { ref path, .. } => {
824                 self.s.word("pub(")?;
825                 self.print_path(path, false)?;
826                 self.word_nbsp(")")
827             }
828             hir::Inherited => Ok(()),
829         }
830     }
831
832     pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
833         match defaultness {
834             hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
835             hir::Defaultness::Final => (),
836         }
837         Ok(())
838     }
839
840     pub fn print_struct(&mut self,
841                         struct_def: &hir::VariantData,
842                         generics: &hir::Generics,
843                         name: ast::Name,
844                         span: syntax_pos::Span,
845                         print_finalizer: bool)
846                         -> io::Result<()> {
847         self.print_name(name)?;
848         self.print_generic_params(&generics.params)?;
849         if !struct_def.is_struct() {
850             if struct_def.is_tuple() {
851                 self.popen()?;
852                 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
853                     s.maybe_print_comment(field.span.lo())?;
854                     s.print_outer_attributes(&field.attrs)?;
855                     s.print_visibility(&field.vis)?;
856                     s.print_type(&field.ty)
857                 })?;
858                 self.pclose()?;
859             }
860             self.print_where_clause(&generics.where_clause)?;
861             if print_finalizer {
862                 self.s.word(";")?;
863             }
864             self.end()?;
865             self.end() // close the outer-box
866         } else {
867             self.print_where_clause(&generics.where_clause)?;
868             self.nbsp()?;
869             self.bopen()?;
870             self.hardbreak_if_not_bol()?;
871
872             for field in struct_def.fields() {
873                 self.hardbreak_if_not_bol()?;
874                 self.maybe_print_comment(field.span.lo())?;
875                 self.print_outer_attributes(&field.attrs)?;
876                 self.print_visibility(&field.vis)?;
877                 self.print_name(field.name)?;
878                 self.word_nbsp(":")?;
879                 self.print_type(&field.ty)?;
880                 self.s.word(",")?;
881             }
882
883             self.bclose(span)
884         }
885     }
886
887     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
888         self.head("")?;
889         let generics = hir::Generics::empty();
890         self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
891         if let Some(d) = v.node.disr_expr {
892             self.s.space()?;
893             self.word_space("=")?;
894             self.ann.nested(self, Nested::Body(d))?;
895         }
896         Ok(())
897     }
898     pub fn print_method_sig(&mut self,
899                             name: ast::Name,
900                             m: &hir::MethodSig,
901                             generics: &hir::Generics,
902                             vis: &hir::Visibility,
903                             arg_names: &[Spanned<ast::Name>],
904                             body_id: Option<hir::BodyId>)
905                             -> io::Result<()> {
906         self.print_fn(&m.decl,
907                       m.unsafety,
908                       m.constness,
909                       m.abi,
910                       Some(name),
911                       generics,
912                       vis,
913                       arg_names,
914                       body_id)
915     }
916
917     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
918         self.ann.pre(self, NodeSubItem(ti.id))?;
919         self.hardbreak_if_not_bol()?;
920         self.maybe_print_comment(ti.span.lo())?;
921         self.print_outer_attributes(&ti.attrs)?;
922         match ti.node {
923             hir::TraitItemKind::Const(ref ty, default) => {
924                 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
925             }
926             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
927                 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, arg_names,
928                     None)?;
929                 self.s.word(";")?;
930             }
931             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
932                 self.head("")?;
933                 self.print_method_sig(ti.name, sig, &ti.generics, &hir::Inherited, &[],
934                     Some(body))?;
935                 self.nbsp()?;
936                 self.end()?; // need to close a box
937                 self.end()?; // need to close a box
938                 self.ann.nested(self, Nested::Body(body))?;
939             }
940             hir::TraitItemKind::Type(ref bounds, ref default) => {
941                 self.print_associated_type(ti.name,
942                                            Some(bounds),
943                                            default.as_ref().map(|ty| &**ty))?;
944             }
945         }
946         self.ann.post(self, NodeSubItem(ti.id))
947     }
948
949     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
950         self.ann.pre(self, NodeSubItem(ii.id))?;
951         self.hardbreak_if_not_bol()?;
952         self.maybe_print_comment(ii.span.lo())?;
953         self.print_outer_attributes(&ii.attrs)?;
954         self.print_defaultness(ii.defaultness)?;
955
956         match ii.node {
957             hir::ImplItemKind::Const(ref ty, expr) => {
958                 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
959             }
960             hir::ImplItemKind::Method(ref sig, body) => {
961                 self.head("")?;
962                 self.print_method_sig(ii.name, sig, &ii.generics, &ii.vis, &[], Some(body))?;
963                 self.nbsp()?;
964                 self.end()?; // need to close a box
965                 self.end()?; // need to close a box
966                 self.ann.nested(self, Nested::Body(body))?;
967             }
968             hir::ImplItemKind::Type(ref ty) => {
969                 self.print_associated_type(ii.name, None, Some(ty))?;
970             }
971         }
972         self.ann.post(self, NodeSubItem(ii.id))
973     }
974
975     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
976         self.maybe_print_comment(st.span.lo())?;
977         match st.node {
978             hir::StmtDecl(ref decl, _) => {
979                 self.print_decl(&decl)?;
980             }
981             hir::StmtExpr(ref expr, _) => {
982                 self.space_if_not_bol()?;
983                 self.print_expr(&expr)?;
984             }
985             hir::StmtSemi(ref expr, _) => {
986                 self.space_if_not_bol()?;
987                 self.print_expr(&expr)?;
988                 self.s.word(";")?;
989             }
990         }
991         if stmt_ends_with_semi(&st.node) {
992             self.s.word(";")?;
993         }
994         self.maybe_print_trailing_comment(st.span, None)
995     }
996
997     pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
998         self.print_block_with_attrs(blk, &[])
999     }
1000
1001     pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1002         self.print_block_unclosed_indent(blk, indent_unit)
1003     }
1004
1005     pub fn print_block_unclosed_indent(&mut self,
1006                                        blk: &hir::Block,
1007                                        indented: usize)
1008                                        -> io::Result<()> {
1009         self.print_block_maybe_unclosed(blk, indented, &[], false)
1010     }
1011
1012     pub fn print_block_with_attrs(&mut self,
1013                                   blk: &hir::Block,
1014                                   attrs: &[ast::Attribute])
1015                                   -> io::Result<()> {
1016         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1017     }
1018
1019     pub fn print_block_maybe_unclosed(&mut self,
1020                                       blk: &hir::Block,
1021                                       indented: usize,
1022                                       attrs: &[ast::Attribute],
1023                                       close_box: bool)
1024                                       -> io::Result<()> {
1025         match blk.rules {
1026             hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1027             hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1028             hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1029             hir::DefaultBlock => (),
1030         }
1031         self.maybe_print_comment(blk.span.lo())?;
1032         self.ann.pre(self, NodeBlock(blk))?;
1033         self.bopen()?;
1034
1035         self.print_inner_attributes(attrs)?;
1036
1037         for st in &blk.stmts {
1038             self.print_stmt(st)?;
1039         }
1040         match blk.expr {
1041             Some(ref expr) => {
1042                 self.space_if_not_bol()?;
1043                 self.print_expr(&expr)?;
1044                 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1045             }
1046             _ => (),
1047         }
1048         self.bclose_maybe_open(blk.span, indented, close_box)?;
1049         self.ann.post(self, NodeBlock(blk))
1050     }
1051
1052     fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1053         match els {
1054             Some(_else) => {
1055                 match _else.node {
1056                     // "another else-if"
1057                     hir::ExprIf(ref i, ref then, ref e) => {
1058                         self.cbox(indent_unit - 1)?;
1059                         self.ibox(0)?;
1060                         self.s.word(" else if ")?;
1061                         self.print_expr_as_cond(&i)?;
1062                         self.s.space()?;
1063                         self.print_expr(&then)?;
1064                         self.print_else(e.as_ref().map(|e| &**e))
1065                     }
1066                     // "final else"
1067                     hir::ExprBlock(ref b) => {
1068                         self.cbox(indent_unit - 1)?;
1069                         self.ibox(0)?;
1070                         self.s.word(" else ")?;
1071                         self.print_block(&b)
1072                     }
1073                     // BLEAH, constraints would be great here
1074                     _ => {
1075                         panic!("print_if saw if with weird alternative");
1076                     }
1077                 }
1078             }
1079             _ => Ok(()),
1080         }
1081     }
1082
1083     pub fn print_if(&mut self,
1084                     test: &hir::Expr,
1085                     blk: &hir::Expr,
1086                     elseopt: Option<&hir::Expr>)
1087                     -> io::Result<()> {
1088         self.head("if")?;
1089         self.print_expr_as_cond(test)?;
1090         self.s.space()?;
1091         self.print_expr(blk)?;
1092         self.print_else(elseopt)
1093     }
1094
1095     pub fn print_if_let(&mut self,
1096                         pat: &hir::Pat,
1097                         expr: &hir::Expr,
1098                         blk: &hir::Block,
1099                         elseopt: Option<&hir::Expr>)
1100                         -> io::Result<()> {
1101         self.head("if let")?;
1102         self.print_pat(pat)?;
1103         self.s.space()?;
1104         self.word_space("=")?;
1105         self.print_expr_as_cond(expr)?;
1106         self.s.space()?;
1107         self.print_block(blk)?;
1108         self.print_else(elseopt)
1109     }
1110
1111
1112     fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1113         self.popen()?;
1114         self.commasep_exprs(Inconsistent, args)?;
1115         self.pclose()
1116     }
1117
1118     pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1119         let needs_par = expr_precedence(expr) < prec;
1120         if needs_par {
1121             self.popen()?;
1122         }
1123         self.print_expr(expr)?;
1124         if needs_par {
1125             self.pclose()?;
1126         }
1127         Ok(())
1128     }
1129
1130     /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1131     /// `if cond { ... }`.
1132     pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1133         let needs_par = match expr.node {
1134             // These cases need parens due to the parse error observed in #26461: `if return {}`
1135             // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1136             hir::ExprClosure(..) |
1137             hir::ExprRet(..) |
1138             hir::ExprBreak(..) => true,
1139
1140             _ => contains_exterior_struct_lit(expr),
1141         };
1142
1143         if needs_par {
1144             self.popen()?;
1145         }
1146         self.print_expr(expr)?;
1147         if needs_par {
1148             self.pclose()?;
1149         }
1150         Ok(())
1151     }
1152
1153     fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1154         self.ibox(indent_unit)?;
1155         self.s.word("[")?;
1156         self.commasep_exprs(Inconsistent, exprs)?;
1157         self.s.word("]")?;
1158         self.end()
1159     }
1160
1161     fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1162         self.ibox(indent_unit)?;
1163         self.s.word("[")?;
1164         self.print_expr(element)?;
1165         self.word_space(";")?;
1166         self.ann.nested(self, Nested::Body(count))?;
1167         self.s.word("]")?;
1168         self.end()
1169     }
1170
1171     fn print_expr_struct(&mut self,
1172                          qpath: &hir::QPath,
1173                          fields: &[hir::Field],
1174                          wth: &Option<P<hir::Expr>>)
1175                          -> io::Result<()> {
1176         self.print_qpath(qpath, true)?;
1177         self.s.word("{")?;
1178         self.commasep_cmnt(Consistent,
1179                            &fields[..],
1180                            |s, field| {
1181                                s.ibox(indent_unit)?;
1182                                if !field.is_shorthand {
1183                                     s.print_name(field.name.node)?;
1184                                     s.word_space(":")?;
1185                                }
1186                                s.print_expr(&field.expr)?;
1187                                s.end()
1188                            },
1189                            |f| f.span)?;
1190         match *wth {
1191             Some(ref expr) => {
1192                 self.ibox(indent_unit)?;
1193                 if !fields.is_empty() {
1194                     self.s.word(",")?;
1195                     self.s.space()?;
1196                 }
1197                 self.s.word("..")?;
1198                 self.print_expr(&expr)?;
1199                 self.end()?;
1200             }
1201             _ => if !fields.is_empty() {
1202                 self.s.word(",")?
1203             },
1204         }
1205         self.s.word("}")?;
1206         Ok(())
1207     }
1208
1209     fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1210         self.popen()?;
1211         self.commasep_exprs(Inconsistent, exprs)?;
1212         if exprs.len() == 1 {
1213             self.s.word(",")?;
1214         }
1215         self.pclose()
1216     }
1217
1218     fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1219         let prec =
1220             match func.node {
1221                 hir::ExprField(..) |
1222                 hir::ExprTupField(..) => parser::PREC_FORCE_PAREN,
1223                 _ => parser::PREC_POSTFIX,
1224             };
1225
1226         self.print_expr_maybe_paren(func, prec)?;
1227         self.print_call_post(args)
1228     }
1229
1230     fn print_expr_method_call(&mut self,
1231                               segment: &hir::PathSegment,
1232                               args: &[hir::Expr])
1233                               -> io::Result<()> {
1234         let base_args = &args[1..];
1235         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1236         self.s.word(".")?;
1237         self.print_name(segment.name)?;
1238
1239         segment.with_parameters(|parameters| {
1240             if !parameters.lifetimes.is_empty() ||
1241                 !parameters.types.is_empty() ||
1242                 !parameters.bindings.is_empty()
1243             {
1244                 self.print_path_parameters(&parameters, segment.infer_types, true)
1245             } else {
1246                 Ok(())
1247             }
1248         })?;
1249         self.print_call_post(base_args)
1250     }
1251
1252     fn print_expr_binary(&mut self,
1253                          op: hir::BinOp,
1254                          lhs: &hir::Expr,
1255                          rhs: &hir::Expr)
1256                          -> io::Result<()> {
1257         let assoc_op = bin_op_to_assoc_op(op.node);
1258         let prec = assoc_op.precedence() as i8;
1259         let fixity = assoc_op.fixity();
1260
1261         let (left_prec, right_prec) = match fixity {
1262             Fixity::Left => (prec, prec + 1),
1263             Fixity::Right => (prec + 1, prec),
1264             Fixity::None => (prec + 1, prec + 1),
1265         };
1266
1267         let left_prec = match (&lhs.node, op.node) {
1268             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1269             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1270             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1271             (&hir::ExprCast { .. }, hir::BinOp_::BiLt) |
1272             (&hir::ExprCast { .. }, hir::BinOp_::BiShl) => parser::PREC_FORCE_PAREN,
1273             _ => left_prec,
1274         };
1275
1276         self.print_expr_maybe_paren(lhs, left_prec)?;
1277         self.s.space()?;
1278         self.word_space(op.node.as_str())?;
1279         self.print_expr_maybe_paren(rhs, right_prec)
1280     }
1281
1282     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1283         self.s.word(op.as_str())?;
1284         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1285     }
1286
1287     fn print_expr_addr_of(&mut self,
1288                           mutability: hir::Mutability,
1289                           expr: &hir::Expr)
1290                           -> io::Result<()> {
1291         self.s.word("&")?;
1292         self.print_mutability(mutability)?;
1293         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1294     }
1295
1296     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1297         self.maybe_print_comment(expr.span.lo())?;
1298         self.print_outer_attributes(&expr.attrs)?;
1299         self.ibox(indent_unit)?;
1300         self.ann.pre(self, NodeExpr(expr))?;
1301         match expr.node {
1302             hir::ExprBox(ref expr) => {
1303                 self.word_space("box")?;
1304                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1305             }
1306             hir::ExprArray(ref exprs) => {
1307                 self.print_expr_vec(exprs)?;
1308             }
1309             hir::ExprRepeat(ref element, count) => {
1310                 self.print_expr_repeat(&element, count)?;
1311             }
1312             hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1313                 self.print_expr_struct(qpath, &fields[..], wth)?;
1314             }
1315             hir::ExprTup(ref exprs) => {
1316                 self.print_expr_tup(exprs)?;
1317             }
1318             hir::ExprCall(ref func, ref args) => {
1319                 self.print_expr_call(&func, args)?;
1320             }
1321             hir::ExprMethodCall(ref segment, _, ref args) => {
1322                 self.print_expr_method_call(segment, args)?;
1323             }
1324             hir::ExprBinary(op, ref lhs, ref rhs) => {
1325                 self.print_expr_binary(op, &lhs, &rhs)?;
1326             }
1327             hir::ExprUnary(op, ref expr) => {
1328                 self.print_expr_unary(op, &expr)?;
1329             }
1330             hir::ExprAddrOf(m, ref expr) => {
1331                 self.print_expr_addr_of(m, &expr)?;
1332             }
1333             hir::ExprLit(ref lit) => {
1334                 self.print_literal(&lit)?;
1335             }
1336             hir::ExprCast(ref expr, ref ty) => {
1337                 let prec = AssocOp::As.precedence() as i8;
1338                 self.print_expr_maybe_paren(&expr, prec)?;
1339                 self.s.space()?;
1340                 self.word_space("as")?;
1341                 self.print_type(&ty)?;
1342             }
1343             hir::ExprType(ref expr, ref ty) => {
1344                 let prec = AssocOp::Colon.precedence() as i8;
1345                 self.print_expr_maybe_paren(&expr, prec)?;
1346                 self.word_space(":")?;
1347                 self.print_type(&ty)?;
1348             }
1349             hir::ExprIf(ref test, ref blk, ref elseopt) => {
1350                 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1351             }
1352             hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1353                 if let Some(sp_name) = opt_sp_name {
1354                     self.print_name(sp_name.node)?;
1355                     self.word_space(":")?;
1356                 }
1357                 self.head("while")?;
1358                 self.print_expr_as_cond(&test)?;
1359                 self.s.space()?;
1360                 self.print_block(&blk)?;
1361             }
1362             hir::ExprLoop(ref blk, opt_sp_name, _) => {
1363                 if let Some(sp_name) = opt_sp_name {
1364                     self.print_name(sp_name.node)?;
1365                     self.word_space(":")?;
1366                 }
1367                 self.head("loop")?;
1368                 self.s.space()?;
1369                 self.print_block(&blk)?;
1370             }
1371             hir::ExprMatch(ref expr, ref arms, _) => {
1372                 self.cbox(indent_unit)?;
1373                 self.ibox(4)?;
1374                 self.word_nbsp("match")?;
1375                 self.print_expr_as_cond(&expr)?;
1376                 self.s.space()?;
1377                 self.bopen()?;
1378                 for arm in arms {
1379                     self.print_arm(arm)?;
1380                 }
1381                 self.bclose_(expr.span, indent_unit)?;
1382             }
1383             hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1384                 self.print_capture_clause(capture_clause)?;
1385
1386                 self.print_closure_args(&decl, body)?;
1387                 self.s.space()?;
1388
1389                 // this is a bare expression
1390                 self.ann.nested(self, Nested::Body(body))?;
1391                 self.end()?; // need to close a box
1392
1393                 // a box will be closed by print_expr, but we didn't want an overall
1394                 // wrapper so we closed the corresponding opening. so create an
1395                 // empty box to satisfy the close.
1396                 self.ibox(0)?;
1397             }
1398             hir::ExprBlock(ref blk) => {
1399                 // containing cbox, will be closed by print-block at }
1400                 self.cbox(indent_unit)?;
1401                 // head-box, will be closed by print-block after {
1402                 self.ibox(0)?;
1403                 self.print_block(&blk)?;
1404             }
1405             hir::ExprAssign(ref lhs, ref rhs) => {
1406                 let prec = AssocOp::Assign.precedence() as i8;
1407                 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1408                 self.s.space()?;
1409                 self.word_space("=")?;
1410                 self.print_expr_maybe_paren(&rhs, prec)?;
1411             }
1412             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1413                 let prec = AssocOp::Assign.precedence() as i8;
1414                 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1415                 self.s.space()?;
1416                 self.s.word(op.node.as_str())?;
1417                 self.word_space("=")?;
1418                 self.print_expr_maybe_paren(&rhs, prec)?;
1419             }
1420             hir::ExprField(ref expr, name) => {
1421                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1422                 self.s.word(".")?;
1423                 self.print_name(name.node)?;
1424             }
1425             hir::ExprTupField(ref expr, id) => {
1426                 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1427                 self.s.word(".")?;
1428                 self.print_usize(id.node)?;
1429             }
1430             hir::ExprIndex(ref expr, ref index) => {
1431                 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1432                 self.s.word("[")?;
1433                 self.print_expr(&index)?;
1434                 self.s.word("]")?;
1435             }
1436             hir::ExprPath(ref qpath) => {
1437                 self.print_qpath(qpath, true)?
1438             }
1439             hir::ExprBreak(label, ref opt_expr) => {
1440                 self.s.word("break")?;
1441                 self.s.space()?;
1442                 if let Some(label_ident) = label.ident {
1443                     self.print_name(label_ident.node.name)?;
1444                     self.s.space()?;
1445                 }
1446                 if let Some(ref expr) = *opt_expr {
1447                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1448                     self.s.space()?;
1449                 }
1450             }
1451             hir::ExprAgain(label) => {
1452                 self.s.word("continue")?;
1453                 self.s.space()?;
1454                 if let Some(label_ident) = label.ident {
1455                     self.print_name(label_ident.node.name)?;
1456                     self.s.space()?
1457                 }
1458             }
1459             hir::ExprRet(ref result) => {
1460                 self.s.word("return")?;
1461                 match *result {
1462                     Some(ref expr) => {
1463                         self.s.word(" ")?;
1464                         self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1465                     }
1466                     _ => (),
1467                 }
1468             }
1469             hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1470                 self.s.word("asm!")?;
1471                 self.popen()?;
1472                 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1473                 self.word_space(":")?;
1474
1475                 let mut out_idx = 0;
1476                 self.commasep(Inconsistent, &a.outputs, |s, out| {
1477                     let constraint = out.constraint.as_str();
1478                     let mut ch = constraint.chars();
1479                     match ch.next() {
1480                         Some('=') if out.is_rw => {
1481                             s.print_string(&format!("+{}", ch.as_str()),
1482                                            ast::StrStyle::Cooked)?
1483                         }
1484                         _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1485                     }
1486                     s.popen()?;
1487                     s.print_expr(&outputs[out_idx])?;
1488                     s.pclose()?;
1489                     out_idx += 1;
1490                     Ok(())
1491                 })?;
1492                 self.s.space()?;
1493                 self.word_space(":")?;
1494
1495                 let mut in_idx = 0;
1496                 self.commasep(Inconsistent, &a.inputs, |s, co| {
1497                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1498                     s.popen()?;
1499                     s.print_expr(&inputs[in_idx])?;
1500                     s.pclose()?;
1501                     in_idx += 1;
1502                     Ok(())
1503                 })?;
1504                 self.s.space()?;
1505                 self.word_space(":")?;
1506
1507                 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1508                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1509                     Ok(())
1510                 })?;
1511
1512                 let mut options = vec![];
1513                 if a.volatile {
1514                     options.push("volatile");
1515                 }
1516                 if a.alignstack {
1517                     options.push("alignstack");
1518                 }
1519                 if a.dialect == ast::AsmDialect::Intel {
1520                     options.push("intel");
1521                 }
1522
1523                 if !options.is_empty() {
1524                     self.s.space()?;
1525                     self.word_space(":")?;
1526                     self.commasep(Inconsistent, &options, |s, &co| {
1527                         s.print_string(co, ast::StrStyle::Cooked)?;
1528                         Ok(())
1529                     })?;
1530                 }
1531
1532                 self.pclose()?;
1533             }
1534             hir::ExprYield(ref expr) => {
1535                 self.word_space("yield")?;
1536                 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1537             }
1538         }
1539         self.ann.post(self, NodeExpr(expr))?;
1540         self.end()
1541     }
1542
1543     pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1544         self.print_pat(&loc.pat)?;
1545         if let Some(ref ty) = loc.ty {
1546             self.word_space(":")?;
1547             self.print_type(&ty)?;
1548         }
1549         Ok(())
1550     }
1551
1552     pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1553         self.maybe_print_comment(decl.span.lo())?;
1554         match decl.node {
1555             hir::DeclLocal(ref loc) => {
1556                 self.space_if_not_bol()?;
1557                 self.ibox(indent_unit)?;
1558                 self.word_nbsp("let")?;
1559
1560                 self.ibox(indent_unit)?;
1561                 self.print_local_decl(&loc)?;
1562                 self.end()?;
1563                 if let Some(ref init) = loc.init {
1564                     self.nbsp()?;
1565                     self.word_space("=")?;
1566                     self.print_expr(&init)?;
1567                 }
1568                 self.end()
1569             }
1570             hir::DeclItem(item) => {
1571                 self.ann.nested(self, Nested::Item(item))
1572             }
1573         }
1574     }
1575
1576     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1577         self.s.word(&i.to_string())
1578     }
1579
1580     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1581         self.s.word(&name.as_str())?;
1582         self.ann.post(self, NodeName(&name))
1583     }
1584
1585     pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1586         self.print_local_decl(loc)?;
1587         self.s.space()?;
1588         self.word_space("in")?;
1589         self.print_expr(coll)
1590     }
1591
1592     pub fn print_path(&mut self,
1593                       path: &hir::Path,
1594                       colons_before_params: bool)
1595                       -> io::Result<()> {
1596         self.maybe_print_comment(path.span.lo())?;
1597
1598         for (i, segment) in path.segments.iter().enumerate() {
1599             if i > 0 {
1600                 self.s.word("::")?
1601             }
1602             if segment.name != keywords::CrateRoot.name() &&
1603                segment.name != keywords::DollarCrate.name() {
1604                self.print_name(segment.name)?;
1605                segment.with_parameters(|parameters| {
1606                    self.print_path_parameters(parameters,
1607                                               segment.infer_types,
1608                                               colons_before_params)
1609                })?;
1610             }
1611         }
1612
1613         Ok(())
1614     }
1615
1616     pub fn print_qpath(&mut self,
1617                        qpath: &hir::QPath,
1618                        colons_before_params: bool)
1619                        -> io::Result<()> {
1620         match *qpath {
1621             hir::QPath::Resolved(None, ref path) => {
1622                 self.print_path(path, colons_before_params)
1623             }
1624             hir::QPath::Resolved(Some(ref qself), ref path) => {
1625                 self.s.word("<")?;
1626                 self.print_type(qself)?;
1627                 self.s.space()?;
1628                 self.word_space("as")?;
1629
1630                 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1631                     if i > 0 {
1632                         self.s.word("::")?
1633                     }
1634                     if segment.name != keywords::CrateRoot.name() &&
1635                        segment.name != keywords::DollarCrate.name() {
1636                         self.print_name(segment.name)?;
1637                         segment.with_parameters(|parameters| {
1638                             self.print_path_parameters(parameters,
1639                                                        segment.infer_types,
1640                                                        colons_before_params)
1641                         })?;
1642                     }
1643                 }
1644
1645                 self.s.word(">")?;
1646                 self.s.word("::")?;
1647                 let item_segment = path.segments.last().unwrap();
1648                 self.print_name(item_segment.name)?;
1649                 item_segment.with_parameters(|parameters| {
1650                     self.print_path_parameters(parameters,
1651                                                item_segment.infer_types,
1652                                                colons_before_params)
1653                 })
1654             }
1655             hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1656                 self.s.word("<")?;
1657                 self.print_type(qself)?;
1658                 self.s.word(">")?;
1659                 self.s.word("::")?;
1660                 self.print_name(item_segment.name)?;
1661                 item_segment.with_parameters(|parameters| {
1662                     self.print_path_parameters(parameters,
1663                                                item_segment.infer_types,
1664                                                colons_before_params)
1665                 })
1666             }
1667         }
1668     }
1669
1670     fn print_path_parameters(&mut self,
1671                              parameters: &hir::PathParameters,
1672                              infer_types: bool,
1673                              colons_before_params: bool)
1674                              -> io::Result<()> {
1675         if parameters.parenthesized {
1676             self.s.word("(")?;
1677             self.commasep(Inconsistent, parameters.inputs(), |s, ty| s.print_type(&ty))?;
1678             self.s.word(")")?;
1679
1680             self.space_if_not_bol()?;
1681             self.word_space("->")?;
1682             self.print_type(&parameters.bindings[0].ty)?;
1683         } else {
1684             let start = if colons_before_params { "::<" } else { "<" };
1685             let empty = Cell::new(true);
1686             let start_or_comma = |this: &mut Self| {
1687                 if empty.get() {
1688                     empty.set(false);
1689                     this.s.word(start)
1690                 } else {
1691                     this.word_space(",")
1692                 }
1693             };
1694
1695             if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) {
1696                 for lifetime in &parameters.lifetimes {
1697                     start_or_comma(self)?;
1698                     self.print_lifetime(lifetime)?;
1699                 }
1700             }
1701
1702             if !parameters.types.is_empty() {
1703                 start_or_comma(self)?;
1704                 self.commasep(Inconsistent, &parameters.types, |s, ty| s.print_type(&ty))?;
1705             }
1706
1707             // FIXME(eddyb) This would leak into error messages, e.g.:
1708             // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1709             if infer_types && false {
1710                 start_or_comma(self)?;
1711                 self.s.word("..")?;
1712             }
1713
1714             for binding in parameters.bindings.iter() {
1715                 start_or_comma(self)?;
1716                 self.print_name(binding.name)?;
1717                 self.s.space()?;
1718                 self.word_space("=")?;
1719                 self.print_type(&binding.ty)?;
1720             }
1721
1722             if !empty.get() {
1723                 self.s.word(">")?
1724             }
1725         }
1726
1727         Ok(())
1728     }
1729
1730     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1731         self.maybe_print_comment(pat.span.lo())?;
1732         self.ann.pre(self, NodePat(pat))?;
1733         // Pat isn't normalized, but the beauty of it
1734         // is that it doesn't matter
1735         match pat.node {
1736             PatKind::Wild => self.s.word("_")?,
1737             PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1738                 match binding_mode {
1739                     hir::BindingAnnotation::Ref => {
1740                         self.word_nbsp("ref")?;
1741                         self.print_mutability(hir::MutImmutable)?;
1742                     }
1743                     hir::BindingAnnotation::RefMut => {
1744                         self.word_nbsp("ref")?;
1745                         self.print_mutability(hir::MutMutable)?;
1746                     }
1747                     hir::BindingAnnotation::Unannotated => {}
1748                     hir::BindingAnnotation::Mutable => {
1749                         self.word_nbsp("mut")?;
1750                     }
1751                 }
1752                 self.print_name(path1.node)?;
1753                 if let Some(ref p) = *sub {
1754                     self.s.word("@")?;
1755                     self.print_pat(&p)?;
1756                 }
1757             }
1758             PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1759                 self.print_qpath(qpath, true)?;
1760                 self.popen()?;
1761                 if let Some(ddpos) = ddpos {
1762                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1763                     if ddpos != 0 {
1764                         self.word_space(",")?;
1765                     }
1766                     self.s.word("..")?;
1767                     if ddpos != elts.len() {
1768                         self.s.word(",")?;
1769                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1770                     }
1771                 } else {
1772                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1773                 }
1774                 self.pclose()?;
1775             }
1776             PatKind::Path(ref qpath) => {
1777                 self.print_qpath(qpath, true)?;
1778             }
1779             PatKind::Struct(ref qpath, ref fields, etc) => {
1780                 self.print_qpath(qpath, true)?;
1781                 self.nbsp()?;
1782                 self.word_space("{")?;
1783                 self.commasep_cmnt(Consistent,
1784                                    &fields[..],
1785                                    |s, f| {
1786                                        s.cbox(indent_unit)?;
1787                                        if !f.node.is_shorthand {
1788                                            s.print_name(f.node.name)?;
1789                                            s.word_nbsp(":")?;
1790                                        }
1791                                        s.print_pat(&f.node.pat)?;
1792                                        s.end()
1793                                    },
1794                                    |f| f.node.pat.span)?;
1795                 if etc {
1796                     if !fields.is_empty() {
1797                         self.word_space(",")?;
1798                     }
1799                     self.s.word("..")?;
1800                 }
1801                 self.s.space()?;
1802                 self.s.word("}")?;
1803             }
1804             PatKind::Tuple(ref elts, ddpos) => {
1805                 self.popen()?;
1806                 if let Some(ddpos) = ddpos {
1807                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1808                     if ddpos != 0 {
1809                         self.word_space(",")?;
1810                     }
1811                     self.s.word("..")?;
1812                     if ddpos != elts.len() {
1813                         self.s.word(",")?;
1814                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1815                     }
1816                 } else {
1817                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1818                     if elts.len() == 1 {
1819                         self.s.word(",")?;
1820                     }
1821                 }
1822                 self.pclose()?;
1823             }
1824             PatKind::Box(ref inner) => {
1825                 self.s.word("box ")?;
1826                 self.print_pat(&inner)?;
1827             }
1828             PatKind::Ref(ref inner, mutbl) => {
1829                 self.s.word("&")?;
1830                 if mutbl == hir::MutMutable {
1831                     self.s.word("mut ")?;
1832                 }
1833                 self.print_pat(&inner)?;
1834             }
1835             PatKind::Lit(ref e) => self.print_expr(&e)?,
1836             PatKind::Range(ref begin, ref end, ref end_kind) => {
1837                 self.print_expr(&begin)?;
1838                 self.s.space()?;
1839                 match *end_kind {
1840                     RangeEnd::Included => self.s.word("...")?,
1841                     RangeEnd::Excluded => self.s.word("..")?,
1842                 }
1843                 self.print_expr(&end)?;
1844             }
1845             PatKind::Slice(ref before, ref slice, ref after) => {
1846                 self.s.word("[")?;
1847                 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1848                 if let Some(ref p) = *slice {
1849                     if !before.is_empty() {
1850                         self.word_space(",")?;
1851                     }
1852                     if p.node != PatKind::Wild {
1853                         self.print_pat(&p)?;
1854                     }
1855                     self.s.word("..")?;
1856                     if !after.is_empty() {
1857                         self.word_space(",")?;
1858                     }
1859                 }
1860                 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1861                 self.s.word("]")?;
1862             }
1863         }
1864         self.ann.post(self, NodePat(pat))
1865     }
1866
1867     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1868         // I have no idea why this check is necessary, but here it
1869         // is :(
1870         if arm.attrs.is_empty() {
1871             self.s.space()?;
1872         }
1873         self.cbox(indent_unit)?;
1874         self.ibox(0)?;
1875         self.print_outer_attributes(&arm.attrs)?;
1876         let mut first = true;
1877         for p in &arm.pats {
1878             if first {
1879                 first = false;
1880             } else {
1881                 self.s.space()?;
1882                 self.word_space("|")?;
1883             }
1884             self.print_pat(&p)?;
1885         }
1886         self.s.space()?;
1887         if let Some(ref e) = arm.guard {
1888             self.word_space("if")?;
1889             self.print_expr(&e)?;
1890             self.s.space()?;
1891         }
1892         self.word_space("=>")?;
1893
1894         match arm.body.node {
1895             hir::ExprBlock(ref blk) => {
1896                 // the block will close the pattern's ibox
1897                 self.print_block_unclosed_indent(&blk, indent_unit)?;
1898
1899                 // If it is a user-provided unsafe block, print a comma after it
1900                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1901                     self.s.word(",")?;
1902                 }
1903             }
1904             _ => {
1905                 self.end()?; // close the ibox for the pattern
1906                 self.print_expr(&arm.body)?;
1907                 self.s.word(",")?;
1908             }
1909         }
1910         self.end() // close enclosing cbox
1911     }
1912
1913     pub fn print_fn(&mut self,
1914                     decl: &hir::FnDecl,
1915                     unsafety: hir::Unsafety,
1916                     constness: hir::Constness,
1917                     abi: Abi,
1918                     name: Option<ast::Name>,
1919                     generics: &hir::Generics,
1920                     vis: &hir::Visibility,
1921                     arg_names: &[Spanned<ast::Name>],
1922                     body_id: Option<hir::BodyId>)
1923                     -> io::Result<()> {
1924         self.print_fn_header_info(unsafety, constness, abi, vis)?;
1925
1926         if let Some(name) = name {
1927             self.nbsp()?;
1928             self.print_name(name)?;
1929         }
1930         self.print_generic_params(&generics.params)?;
1931
1932         self.popen()?;
1933         let mut i = 0;
1934         // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1935         assert!(arg_names.is_empty() || body_id.is_none());
1936         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1937             s.ibox(indent_unit)?;
1938             if let Some(name) = arg_names.get(i) {
1939                 s.s.word(&name.node.as_str())?;
1940                 s.s.word(":")?;
1941                 s.s.space()?;
1942             } else if let Some(body_id) = body_id {
1943                 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1944                 s.s.word(":")?;
1945                 s.s.space()?;
1946             }
1947             i += 1;
1948             s.print_type(ty)?;
1949             s.end()
1950         })?;
1951         if decl.variadic {
1952             self.s.word(", ...")?;
1953         }
1954         self.pclose()?;
1955
1956         self.print_fn_output(decl)?;
1957         self.print_where_clause(&generics.where_clause)
1958     }
1959
1960     fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1961         self.s.word("|")?;
1962         let mut i = 0;
1963         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1964             s.ibox(indent_unit)?;
1965
1966             s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1967             i += 1;
1968
1969             if ty.node != hir::TyInfer {
1970                 s.s.word(":")?;
1971                 s.s.space()?;
1972                 s.print_type(ty)?;
1973             }
1974             s.end()
1975         })?;
1976         self.s.word("|")?;
1977
1978         if let hir::DefaultReturn(..) = decl.output {
1979             return Ok(());
1980         }
1981
1982         self.space_if_not_bol()?;
1983         self.word_space("->")?;
1984         match decl.output {
1985             hir::Return(ref ty) => {
1986                 self.print_type(&ty)?;
1987                 self.maybe_print_comment(ty.span.lo())
1988             }
1989             hir::DefaultReturn(..) => unreachable!(),
1990         }
1991     }
1992
1993     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1994         match capture_clause {
1995             hir::CaptureByValue => self.word_space("move"),
1996             hir::CaptureByRef => Ok(()),
1997         }
1998     }
1999
2000     pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
2001         if !bounds.is_empty() {
2002             self.s.word(prefix)?;
2003             let mut first = true;
2004             for bound in bounds {
2005                 if !(first && prefix.is_empty()) {
2006                     self.nbsp()?;
2007                 }
2008                 if first {
2009                     first = false;
2010                 } else {
2011                     self.word_space("+")?;
2012                 }
2013
2014                 match bound {
2015                     TraitTyParamBound(tref, modifier) => {
2016                         if modifier == &TraitBoundModifier::Maybe {
2017                             self.s.word("?")?;
2018                         }
2019                         self.print_poly_trait_ref(tref)?;
2020                     }
2021                     RegionTyParamBound(lt) => {
2022                         self.print_lifetime(lt)?;
2023                     }
2024                 }
2025             }
2026         }
2027         Ok(())
2028     }
2029
2030     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2031         self.print_name(lifetime.name.name())
2032     }
2033
2034     pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2035         self.print_lifetime(&lifetime.lifetime)?;
2036         let mut sep = ":";
2037         for v in &lifetime.bounds {
2038             self.s.word(sep)?;
2039             self.print_lifetime(v)?;
2040             sep = "+";
2041         }
2042         Ok(())
2043     }
2044
2045     pub fn print_generic_params(&mut self, generic_params: &[hir::GenericParam]) -> io::Result<()> {
2046         if !generic_params.is_empty() {
2047             self.s.word("<")?;
2048
2049             self.commasep(Inconsistent, generic_params, |s, param| {
2050                 match *param {
2051                     hir::GenericParam::Lifetime(ref ld) => s.print_lifetime_def(ld),
2052                     hir::GenericParam::Type(ref tp) => s.print_ty_param(tp),
2053                 }
2054             })?;
2055
2056             self.s.word(">")?;
2057         }
2058         Ok(())
2059     }
2060
2061     pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2062         self.print_name(param.name)?;
2063         self.print_bounds(":", &param.bounds)?;
2064         match param.default {
2065             Some(ref default) => {
2066                 self.s.space()?;
2067                 self.word_space("=")?;
2068                 self.print_type(&default)
2069             }
2070             _ => Ok(()),
2071         }
2072     }
2073
2074     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2075         if where_clause.predicates.is_empty() {
2076             return Ok(());
2077         }
2078
2079         self.s.space()?;
2080         self.word_space("where")?;
2081
2082         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2083             if i != 0 {
2084                 self.word_space(",")?;
2085             }
2086
2087             match predicate {
2088                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2089                     ref bound_generic_params,
2090                     ref bounded_ty,
2091                     ref bounds,
2092                     ..
2093                 }) => {
2094                     self.print_formal_generic_params(bound_generic_params)?;
2095                     self.print_type(&bounded_ty)?;
2096                     self.print_bounds(":", bounds)?;
2097                 }
2098                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2099                                                                                 ref bounds,
2100                                                                                 ..}) => {
2101                     self.print_lifetime(lifetime)?;
2102                     self.s.word(":")?;
2103
2104                     for (i, bound) in bounds.iter().enumerate() {
2105                         self.print_lifetime(bound)?;
2106
2107                         if i != 0 {
2108                             self.s.word(":")?;
2109                         }
2110                     }
2111                 }
2112                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2113                                                                         ref rhs_ty,
2114                                                                         ..}) => {
2115                     self.print_type(lhs_ty)?;
2116                     self.s.space()?;
2117                     self.word_space("=")?;
2118                     self.print_type(rhs_ty)?;
2119                 }
2120             }
2121         }
2122
2123         Ok(())
2124     }
2125
2126     pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2127         match mutbl {
2128             hir::MutMutable => self.word_nbsp("mut"),
2129             hir::MutImmutable => Ok(()),
2130         }
2131     }
2132
2133     pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2134         self.print_mutability(mt.mutbl)?;
2135         self.print_type(&mt.ty)
2136     }
2137
2138     pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2139         if let hir::DefaultReturn(..) = decl.output {
2140             return Ok(());
2141         }
2142
2143         self.space_if_not_bol()?;
2144         self.ibox(indent_unit)?;
2145         self.word_space("->")?;
2146         match decl.output {
2147             hir::DefaultReturn(..) => unreachable!(),
2148             hir::Return(ref ty) => self.print_type(&ty)?,
2149         }
2150         self.end()?;
2151
2152         match decl.output {
2153             hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2154             _ => Ok(()),
2155         }
2156     }
2157
2158     pub fn print_ty_fn(&mut self,
2159                        abi: Abi,
2160                        unsafety: hir::Unsafety,
2161                        decl: &hir::FnDecl,
2162                        name: Option<ast::Name>,
2163                        generic_params: &[hir::GenericParam],
2164                        arg_names: &[Spanned<ast::Name>])
2165                        -> io::Result<()> {
2166         self.ibox(indent_unit)?;
2167         if !generic_params.is_empty() {
2168             self.s.word("for")?;
2169             self.print_generic_params(generic_params)?;
2170         }
2171         let generics = hir::Generics {
2172             params: hir::HirVec::new(),
2173             where_clause: hir::WhereClause {
2174                 id: ast::DUMMY_NODE_ID,
2175                 predicates: hir::HirVec::new(),
2176             },
2177             span: syntax_pos::DUMMY_SP,
2178         };
2179         self.print_fn(decl,
2180                       unsafety,
2181                       hir::Constness::NotConst,
2182                       abi,
2183                       name,
2184                       &generics,
2185                       &hir::Inherited,
2186                       arg_names,
2187                       None)?;
2188         self.end()
2189     }
2190
2191     pub fn maybe_print_trailing_comment(&mut self,
2192                                         span: syntax_pos::Span,
2193                                         next_pos: Option<BytePos>)
2194                                         -> io::Result<()> {
2195         let cm = match self.cm {
2196             Some(cm) => cm,
2197             _ => return Ok(()),
2198         };
2199         if let Some(ref cmnt) = self.next_comment() {
2200             if (*cmnt).style != comments::Trailing {
2201                 return Ok(());
2202             }
2203             let span_line = cm.lookup_char_pos(span.hi());
2204             let comment_line = cm.lookup_char_pos((*cmnt).pos);
2205             let mut next = (*cmnt).pos + BytePos(1);
2206             if let Some(p) = next_pos {
2207                 next = p;
2208             }
2209             if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2210                span_line.line == comment_line.line {
2211                 self.print_comment(cmnt)?;
2212             }
2213         }
2214         Ok(())
2215     }
2216
2217     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2218         // If there aren't any remaining comments, then we need to manually
2219         // make sure there is a line break at the end.
2220         if self.next_comment().is_none() {
2221             self.s.hardbreak()?;
2222         }
2223         loop {
2224             match self.next_comment() {
2225                 Some(ref cmnt) => {
2226                     self.print_comment(cmnt)?;
2227                 }
2228                 _ => break,
2229             }
2230         }
2231         Ok(())
2232     }
2233
2234     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2235                                                   opt_abi: Option<Abi>)
2236                                                   -> io::Result<()> {
2237         match opt_abi {
2238             Some(Abi::Rust) => Ok(()),
2239             Some(abi) => {
2240                 self.word_nbsp("extern")?;
2241                 self.word_nbsp(&abi.to_string())
2242             }
2243             None => Ok(()),
2244         }
2245     }
2246
2247     pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2248         match opt_abi {
2249             Some(abi) => {
2250                 self.word_nbsp("extern")?;
2251                 self.word_nbsp(&abi.to_string())
2252             }
2253             None => Ok(()),
2254         }
2255     }
2256
2257     pub fn print_fn_header_info(&mut self,
2258                                 unsafety: hir::Unsafety,
2259                                 constness: hir::Constness,
2260                                 abi: Abi,
2261                                 vis: &hir::Visibility)
2262                                 -> io::Result<()> {
2263         self.s.word(&visibility_qualified(vis, ""))?;
2264         self.print_unsafety(unsafety)?;
2265
2266         match constness {
2267             hir::Constness::NotConst => {}
2268             hir::Constness::Const => self.word_nbsp("const")?,
2269         }
2270
2271         if abi != Abi::Rust {
2272             self.word_nbsp("extern")?;
2273             self.word_nbsp(&abi.to_string())?;
2274         }
2275
2276         self.s.word("fn")
2277     }
2278
2279     pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2280         match s {
2281             hir::Unsafety::Normal => Ok(()),
2282             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2283         }
2284     }
2285
2286     pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2287         match s {
2288             hir::IsAuto::Yes => self.word_nbsp("auto"),
2289             hir::IsAuto::No => Ok(()),
2290         }
2291     }
2292 }
2293
2294 // Dup'ed from parse::classify, but adapted for the HIR.
2295 /// Does this expression require a semicolon to be treated
2296 /// as a statement? The negation of this: 'can this expression
2297 /// be used as a statement without a semicolon' -- is used
2298 /// as an early-bail-out in the parser so that, for instance,
2299 ///     if true {...} else {...}
2300 ///      |x| 5
2301 /// isn't parsed as (if true {...} else {...} | x) | 5
2302 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2303     match e.node {
2304         hir::ExprIf(..) |
2305         hir::ExprMatch(..) |
2306         hir::ExprBlock(_) |
2307         hir::ExprWhile(..) |
2308         hir::ExprLoop(..) => false,
2309         _ => true,
2310     }
2311 }
2312
2313 /// this statement requires a semicolon after it.
2314 /// note that in one case (stmt_semi), we've already
2315 /// seen the semicolon, and thus don't need another.
2316 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2317     match *stmt {
2318         hir::StmtDecl(ref d, _) => {
2319             match d.node {
2320                 hir::DeclLocal(_) => true,
2321                 hir::DeclItem(_) => false,
2322             }
2323         }
2324         hir::StmtExpr(ref e, _) => {
2325             expr_requires_semi_to_be_stmt(&e)
2326         }
2327         hir::StmtSemi(..) => {
2328             false
2329         }
2330     }
2331 }
2332
2333
2334 fn expr_precedence(expr: &hir::Expr) -> i8 {
2335     use syntax::util::parser::*;
2336
2337     match expr.node {
2338         hir::ExprClosure(..) => PREC_CLOSURE,
2339
2340         hir::ExprBreak(..) |
2341         hir::ExprAgain(..) |
2342         hir::ExprRet(..) |
2343         hir::ExprYield(..) => PREC_JUMP,
2344
2345         // Binop-like expr kinds, handled by `AssocOp`.
2346         hir::ExprBinary(op, _, _) => bin_op_to_assoc_op(op.node).precedence() as i8,
2347
2348         hir::ExprCast(..) => AssocOp::As.precedence() as i8,
2349         hir::ExprType(..) => AssocOp::Colon.precedence() as i8,
2350
2351         hir::ExprAssign(..) |
2352         hir::ExprAssignOp(..) => AssocOp::Assign.precedence() as i8,
2353
2354         // Unary, prefix
2355         hir::ExprBox(..) |
2356         hir::ExprAddrOf(..) |
2357         hir::ExprUnary(..) => PREC_PREFIX,
2358
2359         // Unary, postfix
2360         hir::ExprCall(..) |
2361         hir::ExprMethodCall(..) |
2362         hir::ExprField(..) |
2363         hir::ExprTupField(..) |
2364         hir::ExprIndex(..) |
2365         hir::ExprInlineAsm(..) => PREC_POSTFIX,
2366
2367         // Never need parens
2368         hir::ExprArray(..) |
2369         hir::ExprRepeat(..) |
2370         hir::ExprTup(..) |
2371         hir::ExprLit(..) |
2372         hir::ExprPath(..) |
2373         hir::ExprIf(..) |
2374         hir::ExprWhile(..) |
2375         hir::ExprLoop(..) |
2376         hir::ExprMatch(..) |
2377         hir::ExprBlock(..) |
2378         hir::ExprStruct(..) => PREC_PAREN,
2379     }
2380 }
2381
2382 fn bin_op_to_assoc_op(op: hir::BinOp_) -> AssocOp {
2383     use hir::BinOp_::*;
2384     match op {
2385         BiAdd => AssocOp::Add,
2386         BiSub => AssocOp::Subtract,
2387         BiMul => AssocOp::Multiply,
2388         BiDiv => AssocOp::Divide,
2389         BiRem => AssocOp::Modulus,
2390
2391         BiAnd => AssocOp::LAnd,
2392         BiOr => AssocOp::LOr,
2393
2394         BiBitXor => AssocOp::BitXor,
2395         BiBitAnd => AssocOp::BitAnd,
2396         BiBitOr => AssocOp::BitOr,
2397         BiShl => AssocOp::ShiftLeft,
2398         BiShr => AssocOp::ShiftRight,
2399
2400         BiEq => AssocOp::Equal,
2401         BiLt => AssocOp::Less,
2402         BiLe => AssocOp::LessEqual,
2403         BiNe => AssocOp::NotEqual,
2404         BiGe => AssocOp::GreaterEqual,
2405         BiGt => AssocOp::Greater,
2406     }
2407 }
2408
2409 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2410 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2411 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2412 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2413     match value.node {
2414         hir::ExprStruct(..) => true,
2415
2416         hir::ExprAssign(ref lhs, ref rhs) |
2417         hir::ExprAssignOp(_, ref lhs, ref rhs) |
2418         hir::ExprBinary(_, ref lhs, ref rhs) => {
2419             // X { y: 1 } + X { y: 2 }
2420             contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2421         }
2422         hir::ExprUnary(_, ref x) |
2423         hir::ExprCast(ref x, _) |
2424         hir::ExprType(ref x, _) |
2425         hir::ExprField(ref x, _) |
2426         hir::ExprTupField(ref x, _) |
2427         hir::ExprIndex(ref x, _) => {
2428             // &X { y: 1 }, X { y: 1 }.y
2429             contains_exterior_struct_lit(&x)
2430         }
2431
2432         hir::ExprMethodCall(.., ref exprs) => {
2433             // X { y: 1 }.bar(...)
2434             contains_exterior_struct_lit(&exprs[0])
2435         }
2436
2437         _ => false,
2438     }
2439 }