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