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