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