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