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