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