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