]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/print.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[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 crate::hir;
15 use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
16 use crate::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(hir::HirId),
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             hir::TyKind::CVarArgs(_) => {
438                 self.s.word("...")?;
439             }
440         }
441         self.end()
442     }
443
444     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
445         self.hardbreak_if_not_bol()?;
446         self.maybe_print_comment(item.span.lo())?;
447         self.print_outer_attributes(&item.attrs)?;
448         match item.node {
449             hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
450                 self.head("")?;
451                 self.print_fn(decl,
452                               hir::FnHeader {
453                                   unsafety: hir::Unsafety::Normal,
454                                   constness: hir::Constness::NotConst,
455                                   abi: Abi::Rust,
456                                   asyncness: hir::IsAsync::NotAsync,
457                               },
458                               Some(item.ident.name),
459                               generics,
460                               &item.vis,
461                               arg_names,
462                               None)?;
463                 self.end()?; // end head-ibox
464                 self.s.word(";")?;
465                 self.end() // end the outer fn box
466             }
467             hir::ForeignItemKind::Static(ref t, m) => {
468                 self.head(visibility_qualified(&item.vis, "static"))?;
469                 if m {
470                     self.word_space("mut")?;
471                 }
472                 self.print_ident(item.ident)?;
473                 self.word_space(":")?;
474                 self.print_type(&t)?;
475                 self.s.word(";")?;
476                 self.end()?; // end the head-ibox
477                 self.end() // end the outer cbox
478             }
479             hir::ForeignItemKind::Type => {
480                 self.head(visibility_qualified(&item.vis, "type"))?;
481                 self.print_ident(item.ident)?;
482                 self.s.word(";")?;
483                 self.end()?; // end the head-ibox
484                 self.end() // end the outer cbox
485             }
486         }
487     }
488
489     fn print_associated_const(&mut self,
490                               ident: ast::Ident,
491                               ty: &hir::Ty,
492                               default: Option<hir::BodyId>,
493                               vis: &hir::Visibility)
494                               -> io::Result<()> {
495         self.s.word(visibility_qualified(vis, ""))?;
496         self.word_space("const")?;
497         self.print_ident(ident)?;
498         self.word_space(":")?;
499         self.print_type(ty)?;
500         if let Some(expr) = default {
501             self.s.space()?;
502             self.word_space("=")?;
503             self.ann.nested(self, Nested::Body(expr))?;
504         }
505         self.s.word(";")
506     }
507
508     fn print_associated_type(&mut self,
509                              ident: ast::Ident,
510                              bounds: Option<&hir::GenericBounds>,
511                              ty: Option<&hir::Ty>)
512                              -> io::Result<()> {
513         self.word_space("type")?;
514         self.print_ident(ident)?;
515         if let Some(bounds) = bounds {
516             self.print_bounds(":", bounds)?;
517         }
518         if let Some(ty) = ty {
519             self.s.space()?;
520             self.word_space("=")?;
521             self.print_type(ty)?;
522         }
523         self.s.word(";")
524     }
525
526     /// Pretty-print an item
527     pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
528         self.hardbreak_if_not_bol()?;
529         self.maybe_print_comment(item.span.lo())?;
530         self.print_outer_attributes(&item.attrs)?;
531         self.ann.pre(self, AnnNode::Item(item))?;
532         match item.node {
533             hir::ItemKind::ExternCrate(orig_name) => {
534                 self.head(visibility_qualified(&item.vis, "extern crate"))?;
535                 if let Some(orig_name) = orig_name {
536                     self.print_name(orig_name)?;
537                     self.s.space()?;
538                     self.s.word("as")?;
539                     self.s.space()?;
540                 }
541                 self.print_ident(item.ident)?;
542                 self.s.word(";")?;
543                 self.end()?; // end inner head-block
544                 self.end()?; // end outer head-block
545             }
546             hir::ItemKind::Use(ref path, kind) => {
547                 self.head(visibility_qualified(&item.vis, "use"))?;
548                 self.print_path(path, false)?;
549
550                 match kind {
551                     hir::UseKind::Single => {
552                         if path.segments.last().unwrap().ident != item.ident {
553                             self.s.space()?;
554                             self.word_space("as")?;
555                             self.print_ident(item.ident)?;
556                         }
557                         self.s.word(";")?;
558                     }
559                     hir::UseKind::Glob => self.s.word("::*;")?,
560                     hir::UseKind::ListStem => self.s.word("::{};")?
561                 }
562                 self.end()?; // end inner head-block
563                 self.end()?; // end outer head-block
564             }
565             hir::ItemKind::Static(ref ty, m, expr) => {
566                 self.head(visibility_qualified(&item.vis, "static"))?;
567                 if m == hir::MutMutable {
568                     self.word_space("mut")?;
569                 }
570                 self.print_ident(item.ident)?;
571                 self.word_space(":")?;
572                 self.print_type(&ty)?;
573                 self.s.space()?;
574                 self.end()?; // end the head-ibox
575
576                 self.word_space("=")?;
577                 self.ann.nested(self, Nested::Body(expr))?;
578                 self.s.word(";")?;
579                 self.end()?; // end the outer cbox
580             }
581             hir::ItemKind::Const(ref ty, expr) => {
582                 self.head(visibility_qualified(&item.vis, "const"))?;
583                 self.print_ident(item.ident)?;
584                 self.word_space(":")?;
585                 self.print_type(&ty)?;
586                 self.s.space()?;
587                 self.end()?; // end the head-ibox
588
589                 self.word_space("=")?;
590                 self.ann.nested(self, Nested::Body(expr))?;
591                 self.s.word(";")?;
592                 self.end()?; // end the outer cbox
593             }
594             hir::ItemKind::Fn(ref decl, header, ref param_names, body) => {
595                 self.head("")?;
596                 self.print_fn(decl,
597                               header,
598                               Some(item.ident.name),
599                               param_names,
600                               &item.vis,
601                               &[],
602                               Some(body))?;
603                 self.s.word(" ")?;
604                 self.end()?; // need to close a box
605                 self.end()?; // need to close a box
606                 self.ann.nested(self, Nested::Body(body))?;
607             }
608             hir::ItemKind::Mod(ref _mod) => {
609                 self.head(visibility_qualified(&item.vis, "mod"))?;
610                 self.print_ident(item.ident)?;
611                 self.nbsp()?;
612                 self.bopen()?;
613                 self.print_mod(_mod, &item.attrs)?;
614                 self.bclose(item.span)?;
615             }
616             hir::ItemKind::ForeignMod(ref nmod) => {
617                 self.head("extern")?;
618                 self.word_nbsp(nmod.abi.to_string())?;
619                 self.bopen()?;
620                 self.print_foreign_mod(nmod, &item.attrs)?;
621                 self.bclose(item.span)?;
622             }
623             hir::ItemKind::GlobalAsm(ref ga) => {
624                 self.head(visibility_qualified(&item.vis, "global asm"))?;
625                 self.s.word(ga.asm.as_str().get())?;
626                 self.end()?
627             }
628             hir::ItemKind::Ty(ref ty, ref generics) => {
629                 self.head(visibility_qualified(&item.vis, "type"))?;
630                 self.print_ident(item.ident)?;
631                 self.print_generic_params(&generics.params)?;
632                 self.end()?; // end the inner ibox
633
634                 self.print_where_clause(&generics.where_clause)?;
635                 self.s.space()?;
636                 self.word_space("=")?;
637                 self.print_type(&ty)?;
638                 self.s.word(";")?;
639                 self.end()?; // end the outer ibox
640             }
641             hir::ItemKind::Existential(ref exist) => {
642                 self.head(visibility_qualified(&item.vis, "existential type"))?;
643                 self.print_ident(item.ident)?;
644                 self.print_generic_params(&exist.generics.params)?;
645                 self.end()?; // end the inner ibox
646
647                 self.print_where_clause(&exist.generics.where_clause)?;
648                 self.s.space()?;
649                 self.word_space(":")?;
650                 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
651                 for b in exist.bounds.iter() {
652                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
653                         self.s.space()?;
654                         self.word_space("for ?")?;
655                         self.print_trait_ref(&ptr.trait_ref)?;
656                     } else {
657                         real_bounds.push(b.clone());
658                     }
659                 }
660                 self.print_bounds(":", &real_bounds[..])?;
661                 self.s.word(";")?;
662                 self.end()?; // end the outer ibox
663             }
664             hir::ItemKind::Enum(ref enum_definition, ref params) => {
665                 self.print_enum_def(enum_definition, params, item.ident.name, item.span,
666                                     &item.vis)?;
667             }
668             hir::ItemKind::Struct(ref struct_def, ref generics) => {
669                 self.head(visibility_qualified(&item.vis, "struct"))?;
670                 self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
671             }
672             hir::ItemKind::Union(ref struct_def, ref generics) => {
673                 self.head(visibility_qualified(&item.vis, "union"))?;
674                 self.print_struct(struct_def, generics, item.ident.name, item.span, true)?;
675             }
676             hir::ItemKind::Impl(unsafety,
677                           polarity,
678                           defaultness,
679                           ref generics,
680                           ref opt_trait,
681                           ref ty,
682                           ref impl_items) => {
683                 self.head("")?;
684                 self.print_visibility(&item.vis)?;
685                 self.print_defaultness(defaultness)?;
686                 self.print_unsafety(unsafety)?;
687                 self.word_nbsp("impl")?;
688
689                 if !generics.params.is_empty() {
690                     self.print_generic_params(&generics.params)?;
691                     self.s.space()?;
692                 }
693
694                 if let hir::ImplPolarity::Negative = polarity {
695                     self.s.word("!")?;
696                 }
697
698                 if let Some(ref t) = opt_trait {
699                     self.print_trait_ref(t)?;
700                     self.s.space()?;
701                     self.word_space("for")?;
702                 }
703
704                 self.print_type(&ty)?;
705                 self.print_where_clause(&generics.where_clause)?;
706
707                 self.s.space()?;
708                 self.bopen()?;
709                 self.print_inner_attributes(&item.attrs)?;
710                 for impl_item in impl_items {
711                     self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
712                 }
713                 self.bclose(item.span)?;
714             }
715             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
716                 self.head("")?;
717                 self.print_visibility(&item.vis)?;
718                 self.print_is_auto(is_auto)?;
719                 self.print_unsafety(unsafety)?;
720                 self.word_nbsp("trait")?;
721                 self.print_ident(item.ident)?;
722                 self.print_generic_params(&generics.params)?;
723                 let mut real_bounds = Vec::with_capacity(bounds.len());
724                 for b in bounds.iter() {
725                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
726                         self.s.space()?;
727                         self.word_space("for ?")?;
728                         self.print_trait_ref(&ptr.trait_ref)?;
729                     } else {
730                         real_bounds.push(b.clone());
731                     }
732                 }
733                 self.print_bounds(":", &real_bounds[..])?;
734                 self.print_where_clause(&generics.where_clause)?;
735                 self.s.word(" ")?;
736                 self.bopen()?;
737                 for trait_item in trait_items {
738                     self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
739                 }
740                 self.bclose(item.span)?;
741             }
742             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
743                 self.head("")?;
744                 self.print_visibility(&item.vis)?;
745                 self.word_nbsp("trait")?;
746                 self.print_ident(item.ident)?;
747                 self.print_generic_params(&generics.params)?;
748                 let mut real_bounds = Vec::with_capacity(bounds.len());
749                 // FIXME(durka) this seems to be some quite outdated syntax
750                 for b in bounds.iter() {
751                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
752                         self.s.space()?;
753                         self.word_space("for ?")?;
754                         self.print_trait_ref(&ptr.trait_ref)?;
755                     } else {
756                         real_bounds.push(b.clone());
757                     }
758                 }
759                 self.nbsp()?;
760                 self.print_bounds("=", &real_bounds[..])?;
761                 self.print_where_clause(&generics.where_clause)?;
762                 self.s.word(";")?;
763             }
764         }
765         self.ann.post(self, AnnNode::Item(item))
766     }
767
768     pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
769         self.print_path(&t.path, false)
770     }
771
772     fn print_formal_generic_params(
773         &mut self,
774         generic_params: &[hir::GenericParam]
775     ) -> io::Result<()> {
776         if !generic_params.is_empty() {
777             self.s.word("for")?;
778             self.print_generic_params(generic_params)?;
779             self.nbsp()?;
780         }
781         Ok(())
782     }
783
784     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
785         self.print_formal_generic_params(&t.bound_generic_params)?;
786         self.print_trait_ref(&t.trait_ref)
787     }
788
789     pub fn print_enum_def(&mut self,
790                           enum_definition: &hir::EnumDef,
791                           generics: &hir::Generics,
792                           name: ast::Name,
793                           span: syntax_pos::Span,
794                           visibility: &hir::Visibility)
795                           -> io::Result<()> {
796         self.head(visibility_qualified(visibility, "enum"))?;
797         self.print_name(name)?;
798         self.print_generic_params(&generics.params)?;
799         self.print_where_clause(&generics.where_clause)?;
800         self.s.space()?;
801         self.print_variants(&enum_definition.variants, span)
802     }
803
804     pub fn print_variants(&mut self,
805                           variants: &[hir::Variant],
806                           span: syntax_pos::Span)
807                           -> io::Result<()> {
808         self.bopen()?;
809         for v in variants {
810             self.space_if_not_bol()?;
811             self.maybe_print_comment(v.span.lo())?;
812             self.print_outer_attributes(&v.node.attrs)?;
813             self.ibox(indent_unit)?;
814             self.print_variant(v)?;
815             self.s.word(",")?;
816             self.end()?;
817             self.maybe_print_trailing_comment(v.span, None)?;
818         }
819         self.bclose(span)
820     }
821
822     pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
823         match vis.node {
824             hir::VisibilityKind::Public => self.word_nbsp("pub")?,
825             hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
826             hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
827             hir::VisibilityKind::Restricted { ref path, .. } => {
828                 self.s.word("pub(")?;
829                 if path.segments.len() == 1 &&
830                    path.segments[0].ident.name == keywords::Super.name() {
831                     // Special case: `super` can print like `pub(super)`.
832                     self.s.word("super")?;
833                 } else {
834                     // Everything else requires `in` at present.
835                     self.word_nbsp("in")?;
836                     self.print_path(path, false)?;
837                 }
838                 self.word_nbsp(")")?;
839             }
840             hir::VisibilityKind::Inherited => ()
841         }
842
843         Ok(())
844     }
845
846     pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
847         match defaultness {
848             hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
849             hir::Defaultness::Final => (),
850         }
851         Ok(())
852     }
853
854     pub fn print_struct(&mut self,
855                         struct_def: &hir::VariantData,
856                         generics: &hir::Generics,
857                         name: ast::Name,
858                         span: syntax_pos::Span,
859                         print_finalizer: bool)
860                         -> io::Result<()> {
861         self.print_name(name)?;
862         self.print_generic_params(&generics.params)?;
863         match struct_def {
864             hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
865                 if let hir::VariantData::Tuple(..) = struct_def {
866                     self.popen()?;
867                     self.commasep(Inconsistent, struct_def.fields(), |s, field| {
868                         s.maybe_print_comment(field.span.lo())?;
869                         s.print_outer_attributes(&field.attrs)?;
870                         s.print_visibility(&field.vis)?;
871                         s.print_type(&field.ty)
872                     })?;
873                     self.pclose()?;
874                 }
875                 self.print_where_clause(&generics.where_clause)?;
876                 if print_finalizer {
877                     self.s.word(";")?;
878                 }
879                 self.end()?;
880                 self.end() // close the outer-box
881             }
882             hir::VariantData::Struct(..) => {
883                 self.print_where_clause(&generics.where_clause)?;
884                 self.nbsp()?;
885                 self.bopen()?;
886                 self.hardbreak_if_not_bol()?;
887
888                 for field in struct_def.fields() {
889                     self.hardbreak_if_not_bol()?;
890                     self.maybe_print_comment(field.span.lo())?;
891                     self.print_outer_attributes(&field.attrs)?;
892                     self.print_visibility(&field.vis)?;
893                     self.print_ident(field.ident)?;
894                     self.word_nbsp(":")?;
895                     self.print_type(&field.ty)?;
896                     self.s.word(",")?;
897                 }
898
899                 self.bclose(span)
900             }
901         }
902     }
903
904     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
905         self.head("")?;
906         let generics = hir::Generics::empty();
907         self.print_struct(&v.node.data, &generics, v.node.ident.name, v.span, false)?;
908         if let Some(ref d) = v.node.disr_expr {
909             self.s.space()?;
910             self.word_space("=")?;
911             self.print_anon_const(d)?;
912         }
913         Ok(())
914     }
915     pub fn print_method_sig(&mut self,
916                             ident: ast::Ident,
917                             m: &hir::MethodSig,
918                             generics: &hir::Generics,
919                             vis: &hir::Visibility,
920                             arg_names: &[ast::Ident],
921                             body_id: Option<hir::BodyId>)
922                             -> io::Result<()> {
923         self.print_fn(&m.decl,
924                       m.header,
925                       Some(ident.name),
926                       generics,
927                       vis,
928                       arg_names,
929                       body_id)
930     }
931
932     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
933         self.ann.pre(self, AnnNode::SubItem(ti.hir_id))?;
934         self.hardbreak_if_not_bol()?;
935         self.maybe_print_comment(ti.span.lo())?;
936         self.print_outer_attributes(&ti.attrs)?;
937         match ti.node {
938             hir::TraitItemKind::Const(ref ty, default) => {
939                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
940                                     node: hir::VisibilityKind::Inherited };
941                 self.print_associated_const(ti.ident, &ty, default, &vis)?;
942             }
943             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
944                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
945                                     node: hir::VisibilityKind::Inherited };
946                 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
947                 self.s.word(";")?;
948             }
949             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
950                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
951                                     node: hir::VisibilityKind::Inherited };
952                 self.head("")?;
953                 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
954                 self.nbsp()?;
955                 self.end()?; // need to close a box
956                 self.end()?; // need to close a box
957                 self.ann.nested(self, Nested::Body(body))?;
958             }
959             hir::TraitItemKind::Type(ref bounds, ref default) => {
960                 self.print_associated_type(ti.ident,
961                                            Some(bounds),
962                                            default.as_ref().map(|ty| &**ty))?;
963             }
964         }
965         self.ann.post(self, AnnNode::SubItem(ti.hir_id))
966     }
967
968     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
969         self.ann.pre(self, AnnNode::SubItem(ii.hir_id))?;
970         self.hardbreak_if_not_bol()?;
971         self.maybe_print_comment(ii.span.lo())?;
972         self.print_outer_attributes(&ii.attrs)?;
973         self.print_defaultness(ii.defaultness)?;
974
975         match ii.node {
976             hir::ImplItemKind::Const(ref ty, expr) => {
977                 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
978             }
979             hir::ImplItemKind::Method(ref sig, body) => {
980                 self.head("")?;
981                 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
982                 self.nbsp()?;
983                 self.end()?; // need to close a box
984                 self.end()?; // need to close a box
985                 self.ann.nested(self, Nested::Body(body))?;
986             }
987             hir::ImplItemKind::Type(ref ty) => {
988                 self.print_associated_type(ii.ident, None, Some(ty))?;
989             }
990             hir::ImplItemKind::Existential(ref bounds) => {
991                 self.word_space("existential")?;
992                 self.print_associated_type(ii.ident, Some(bounds), None)?;
993             }
994         }
995         self.ann.post(self, AnnNode::SubItem(ii.hir_id))
996     }
997
998     pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
999         self.maybe_print_comment(st.span.lo())?;
1000         match st.node {
1001             hir::StmtKind::Local(ref loc) => {
1002                 self.space_if_not_bol()?;
1003                 self.ibox(indent_unit)?;
1004                 self.word_nbsp("let")?;
1005
1006                 self.ibox(indent_unit)?;
1007                 self.print_local_decl(&loc)?;
1008                 self.end()?;
1009                 if let Some(ref init) = loc.init {
1010                     self.nbsp()?;
1011                     self.word_space("=")?;
1012                     self.print_expr(&init)?;
1013                 }
1014                 self.end()?
1015             }
1016             hir::StmtKind::Item(item) => {
1017                 self.ann.nested(self, Nested::Item(item))?
1018             }
1019             hir::StmtKind::Expr(ref expr) => {
1020                 self.space_if_not_bol()?;
1021                 self.print_expr(&expr)?;
1022             }
1023             hir::StmtKind::Semi(ref expr) => {
1024                 self.space_if_not_bol()?;
1025                 self.print_expr(&expr)?;
1026                 self.s.word(";")?;
1027             }
1028         }
1029         if stmt_ends_with_semi(&st.node) {
1030             self.s.word(";")?;
1031         }
1032         self.maybe_print_trailing_comment(st.span, None)
1033     }
1034
1035     pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1036         self.print_block_with_attrs(blk, &[])
1037     }
1038
1039     pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1040         self.print_block_unclosed_indent(blk, indent_unit)
1041     }
1042
1043     pub fn print_block_unclosed_indent(&mut self,
1044                                        blk: &hir::Block,
1045                                        indented: usize)
1046                                        -> io::Result<()> {
1047         self.print_block_maybe_unclosed(blk, indented, &[], false)
1048     }
1049
1050     pub fn print_block_with_attrs(&mut self,
1051                                   blk: &hir::Block,
1052                                   attrs: &[ast::Attribute])
1053                                   -> io::Result<()> {
1054         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1055     }
1056
1057     pub fn print_block_maybe_unclosed(&mut self,
1058                                       blk: &hir::Block,
1059                                       indented: usize,
1060                                       attrs: &[ast::Attribute],
1061                                       close_box: bool)
1062                                       -> io::Result<()> {
1063         match blk.rules {
1064             hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1065             hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1066             hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1067             hir::DefaultBlock => (),
1068         }
1069         self.maybe_print_comment(blk.span.lo())?;
1070         self.ann.pre(self, AnnNode::Block(blk))?;
1071         self.bopen()?;
1072
1073         self.print_inner_attributes(attrs)?;
1074
1075         for st in &blk.stmts {
1076             self.print_stmt(st)?;
1077         }
1078         if let Some(ref expr) = blk.expr {
1079             self.space_if_not_bol()?;
1080             self.print_expr(&expr)?;
1081             self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
1082         }
1083         self.bclose_maybe_open(blk.span, indented, close_box)?;
1084         self.ann.post(self, AnnNode::Block(blk))
1085     }
1086
1087     fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1088         match els {
1089             Some(_else) => {
1090                 match _else.node {
1091                     // "another else-if"
1092                     hir::ExprKind::If(ref i, ref then, ref e) => {
1093                         self.cbox(indent_unit - 1)?;
1094                         self.ibox(0)?;
1095                         self.s.word(" else if ")?;
1096                         self.print_expr_as_cond(&i)?;
1097                         self.s.space()?;
1098                         self.print_expr(&then)?;
1099                         self.print_else(e.as_ref().map(|e| &**e))
1100                     }
1101                     // "final else"
1102                     hir::ExprKind::Block(ref b, _) => {
1103                         self.cbox(indent_unit - 1)?;
1104                         self.ibox(0)?;
1105                         self.s.word(" else ")?;
1106                         self.print_block(&b)
1107                     }
1108                     // BLEAH, constraints would be great here
1109                     _ => {
1110                         panic!("print_if saw if with weird alternative");
1111                     }
1112                 }
1113             }
1114             _ => Ok(()),
1115         }
1116     }
1117
1118     pub fn print_if(&mut self,
1119                     test: &hir::Expr,
1120                     blk: &hir::Expr,
1121                     elseopt: Option<&hir::Expr>)
1122                     -> io::Result<()> {
1123         self.head("if")?;
1124         self.print_expr_as_cond(test)?;
1125         self.s.space()?;
1126         self.print_expr(blk)?;
1127         self.print_else(elseopt)
1128     }
1129
1130     pub fn print_if_let(&mut self,
1131                         pat: &hir::Pat,
1132                         expr: &hir::Expr,
1133                         blk: &hir::Block,
1134                         elseopt: Option<&hir::Expr>)
1135                         -> io::Result<()> {
1136         self.head("if let")?;
1137         self.print_pat(pat)?;
1138         self.s.space()?;
1139         self.word_space("=")?;
1140         self.print_expr_as_cond(expr)?;
1141         self.s.space()?;
1142         self.print_block(blk)?;
1143         self.print_else(elseopt)
1144     }
1145
1146     pub fn print_anon_const(&mut self, constant: &hir::AnonConst) -> io::Result<()> {
1147         self.ann.nested(self, Nested::Body(constant.body))
1148     }
1149
1150     fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1151         self.popen()?;
1152         self.commasep_exprs(Inconsistent, args)?;
1153         self.pclose()
1154     }
1155
1156     pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) -> io::Result<()> {
1157         let needs_par = expr.precedence().order() < prec;
1158         if needs_par {
1159             self.popen()?;
1160         }
1161         self.print_expr(expr)?;
1162         if needs_par {
1163             self.pclose()?;
1164         }
1165         Ok(())
1166     }
1167
1168     /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1169     /// `if cond { ... }`.
1170     pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) -> io::Result<()> {
1171         let needs_par = match expr.node {
1172             // These cases need parens due to the parse error observed in #26461: `if return {}`
1173             // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1174             hir::ExprKind::Closure(..) |
1175             hir::ExprKind::Ret(..) |
1176             hir::ExprKind::Break(..) => true,
1177
1178             _ => contains_exterior_struct_lit(expr),
1179         };
1180
1181         if needs_par {
1182             self.popen()?;
1183         }
1184         self.print_expr(expr)?;
1185         if needs_par {
1186             self.pclose()?;
1187         }
1188         Ok(())
1189     }
1190
1191     fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1192         self.ibox(indent_unit)?;
1193         self.s.word("[")?;
1194         self.commasep_exprs(Inconsistent, exprs)?;
1195         self.s.word("]")?;
1196         self.end()
1197     }
1198
1199     fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) -> io::Result<()> {
1200         self.ibox(indent_unit)?;
1201         self.s.word("[")?;
1202         self.print_expr(element)?;
1203         self.word_space(";")?;
1204         self.print_anon_const(count)?;
1205         self.s.word("]")?;
1206         self.end()
1207     }
1208
1209     fn print_expr_struct(&mut self,
1210                          qpath: &hir::QPath,
1211                          fields: &[hir::Field],
1212                          wth: &Option<P<hir::Expr>>)
1213                          -> io::Result<()> {
1214         self.print_qpath(qpath, true)?;
1215         self.s.word("{")?;
1216         self.commasep_cmnt(Consistent,
1217                            &fields[..],
1218                            |s, field| {
1219                                s.ibox(indent_unit)?;
1220                                if !field.is_shorthand {
1221                                     s.print_ident(field.ident)?;
1222                                     s.word_space(":")?;
1223                                }
1224                                s.print_expr(&field.expr)?;
1225                                s.end()
1226                            },
1227                            |f| f.span)?;
1228         match *wth {
1229             Some(ref expr) => {
1230                 self.ibox(indent_unit)?;
1231                 if !fields.is_empty() {
1232                     self.s.word(",")?;
1233                     self.s.space()?;
1234                 }
1235                 self.s.word("..")?;
1236                 self.print_expr(&expr)?;
1237                 self.end()?;
1238             }
1239             _ => if !fields.is_empty() {
1240                 self.s.word(",")?
1241             },
1242         }
1243         self.s.word("}")?;
1244         Ok(())
1245     }
1246
1247     fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1248         self.popen()?;
1249         self.commasep_exprs(Inconsistent, exprs)?;
1250         if exprs.len() == 1 {
1251             self.s.word(",")?;
1252         }
1253         self.pclose()
1254     }
1255
1256     fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1257         let prec =
1258             match func.node {
1259                 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1260                 _ => parser::PREC_POSTFIX,
1261             };
1262
1263         self.print_expr_maybe_paren(func, prec)?;
1264         self.print_call_post(args)
1265     }
1266
1267     fn print_expr_method_call(&mut self,
1268                               segment: &hir::PathSegment,
1269                               args: &[hir::Expr])
1270                               -> io::Result<()> {
1271         let base_args = &args[1..];
1272         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
1273         self.s.word(".")?;
1274         self.print_ident(segment.ident)?;
1275
1276         segment.with_generic_args(|generic_args| {
1277             if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1278                 return self.print_generic_args(&generic_args, segment.infer_types, true);
1279             }
1280             Ok(())
1281         })?;
1282         self.print_call_post(base_args)
1283     }
1284
1285     fn print_expr_binary(&mut self,
1286                          op: hir::BinOp,
1287                          lhs: &hir::Expr,
1288                          rhs: &hir::Expr)
1289                          -> io::Result<()> {
1290         let assoc_op = bin_op_to_assoc_op(op.node);
1291         let prec = assoc_op.precedence() as i8;
1292         let fixity = assoc_op.fixity();
1293
1294         let (left_prec, right_prec) = match fixity {
1295             Fixity::Left => (prec, prec + 1),
1296             Fixity::Right => (prec + 1, prec),
1297             Fixity::None => (prec + 1, prec + 1),
1298         };
1299
1300         let left_prec = match (&lhs.node, op.node) {
1301             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1302             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1303             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1304             (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1305             (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1306             _ => left_prec,
1307         };
1308
1309         self.print_expr_maybe_paren(lhs, left_prec)?;
1310         self.s.space()?;
1311         self.word_space(op.node.as_str())?;
1312         self.print_expr_maybe_paren(rhs, right_prec)
1313     }
1314
1315     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1316         self.s.word(op.as_str())?;
1317         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1318     }
1319
1320     fn print_expr_addr_of(&mut self,
1321                           mutability: hir::Mutability,
1322                           expr: &hir::Expr)
1323                           -> io::Result<()> {
1324         self.s.word("&")?;
1325         self.print_mutability(mutability)?;
1326         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1327     }
1328
1329     pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1330         self.maybe_print_comment(expr.span.lo())?;
1331         self.print_outer_attributes(&expr.attrs)?;
1332         self.ibox(indent_unit)?;
1333         self.ann.pre(self, AnnNode::Expr(expr))?;
1334         match expr.node {
1335             hir::ExprKind::Box(ref expr) => {
1336                 self.word_space("box")?;
1337                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1338             }
1339             hir::ExprKind::Array(ref exprs) => {
1340                 self.print_expr_vec(exprs)?;
1341             }
1342             hir::ExprKind::Repeat(ref element, ref count) => {
1343                 self.print_expr_repeat(&element, count)?;
1344             }
1345             hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1346                 self.print_expr_struct(qpath, &fields[..], wth)?;
1347             }
1348             hir::ExprKind::Tup(ref exprs) => {
1349                 self.print_expr_tup(exprs)?;
1350             }
1351             hir::ExprKind::Call(ref func, ref args) => {
1352                 self.print_expr_call(&func, args)?;
1353             }
1354             hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1355                 self.print_expr_method_call(segment, args)?;
1356             }
1357             hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1358                 self.print_expr_binary(op, &lhs, &rhs)?;
1359             }
1360             hir::ExprKind::Unary(op, ref expr) => {
1361                 self.print_expr_unary(op, &expr)?;
1362             }
1363             hir::ExprKind::AddrOf(m, ref expr) => {
1364                 self.print_expr_addr_of(m, &expr)?;
1365             }
1366             hir::ExprKind::Lit(ref lit) => {
1367                 self.print_literal(&lit)?;
1368             }
1369             hir::ExprKind::Cast(ref expr, ref ty) => {
1370                 let prec = AssocOp::As.precedence() as i8;
1371                 self.print_expr_maybe_paren(&expr, prec)?;
1372                 self.s.space()?;
1373                 self.word_space("as")?;
1374                 self.print_type(&ty)?;
1375             }
1376             hir::ExprKind::Type(ref expr, ref ty) => {
1377                 let prec = AssocOp::Colon.precedence() as i8;
1378                 self.print_expr_maybe_paren(&expr, prec)?;
1379                 self.word_space(":")?;
1380                 self.print_type(&ty)?;
1381             }
1382             hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1383                 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1384             }
1385             hir::ExprKind::While(ref test, ref blk, opt_label) => {
1386                 if let Some(label) = opt_label {
1387                     self.print_ident(label.ident)?;
1388                     self.word_space(":")?;
1389                 }
1390                 self.head("while")?;
1391                 self.print_expr_as_cond(&test)?;
1392                 self.s.space()?;
1393                 self.print_block(&blk)?;
1394             }
1395             hir::ExprKind::Loop(ref blk, opt_label, _) => {
1396                 if let Some(label) = opt_label {
1397                     self.print_ident(label.ident)?;
1398                     self.word_space(":")?;
1399                 }
1400                 self.head("loop")?;
1401                 self.s.space()?;
1402                 self.print_block(&blk)?;
1403             }
1404             hir::ExprKind::Match(ref expr, ref arms, _) => {
1405                 self.cbox(indent_unit)?;
1406                 self.ibox(4)?;
1407                 self.word_nbsp("match")?;
1408                 self.print_expr_as_cond(&expr)?;
1409                 self.s.space()?;
1410                 self.bopen()?;
1411                 for arm in arms {
1412                     self.print_arm(arm)?;
1413                 }
1414                 self.bclose_(expr.span, indent_unit)?;
1415             }
1416             hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1417                 self.print_capture_clause(capture_clause)?;
1418
1419                 self.print_closure_args(&decl, body)?;
1420                 self.s.space()?;
1421
1422                 // this is a bare expression
1423                 self.ann.nested(self, Nested::Body(body))?;
1424                 self.end()?; // need to close a box
1425
1426                 // a box will be closed by print_expr, but we didn't want an overall
1427                 // wrapper so we closed the corresponding opening. so create an
1428                 // empty box to satisfy the close.
1429                 self.ibox(0)?;
1430             }
1431             hir::ExprKind::Block(ref blk, opt_label) => {
1432                 if let Some(label) = opt_label {
1433                     self.print_ident(label.ident)?;
1434                     self.word_space(":")?;
1435                 }
1436                 // containing cbox, will be closed by print-block at }
1437                 self.cbox(indent_unit)?;
1438                 // head-box, will be closed by print-block after {
1439                 self.ibox(0)?;
1440                 self.print_block(&blk)?;
1441             }
1442             hir::ExprKind::Assign(ref lhs, ref rhs) => {
1443                 let prec = AssocOp::Assign.precedence() as i8;
1444                 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1445                 self.s.space()?;
1446                 self.word_space("=")?;
1447                 self.print_expr_maybe_paren(&rhs, prec)?;
1448             }
1449             hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1450                 let prec = AssocOp::Assign.precedence() as i8;
1451                 self.print_expr_maybe_paren(&lhs, prec + 1)?;
1452                 self.s.space()?;
1453                 self.s.word(op.node.as_str())?;
1454                 self.word_space("=")?;
1455                 self.print_expr_maybe_paren(&rhs, prec)?;
1456             }
1457             hir::ExprKind::Field(ref expr, ident) => {
1458                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX)?;
1459                 self.s.word(".")?;
1460                 self.print_ident(ident)?;
1461             }
1462             hir::ExprKind::Index(ref expr, ref index) => {
1463                 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX)?;
1464                 self.s.word("[")?;
1465                 self.print_expr(&index)?;
1466                 self.s.word("]")?;
1467             }
1468             hir::ExprKind::Path(ref qpath) => {
1469                 self.print_qpath(qpath, true)?
1470             }
1471             hir::ExprKind::Break(destination, ref opt_expr) => {
1472                 self.s.word("break")?;
1473                 self.s.space()?;
1474                 if let Some(label) = destination.label {
1475                     self.print_ident(label.ident)?;
1476                     self.s.space()?;
1477                 }
1478                 if let Some(ref expr) = *opt_expr {
1479                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP)?;
1480                     self.s.space()?;
1481                 }
1482             }
1483             hir::ExprKind::Continue(destination) => {
1484                 self.s.word("continue")?;
1485                 self.s.space()?;
1486                 if let Some(label) = destination.label {
1487                     self.print_ident(label.ident)?;
1488                     self.s.space()?
1489                 }
1490             }
1491             hir::ExprKind::Ret(ref result) => {
1492                 self.s.word("return")?;
1493                 if let Some(ref expr) = *result {
1494                     self.s.word(" ")?;
1495                     self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1496                 }
1497             }
1498             hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1499                 self.s.word("asm!")?;
1500                 self.popen()?;
1501                 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1502                 self.word_space(":")?;
1503
1504                 let mut out_idx = 0;
1505                 self.commasep(Inconsistent, &a.outputs, |s, out| {
1506                     let constraint = out.constraint.as_str();
1507                     let mut ch = constraint.chars();
1508                     match ch.next() {
1509                         Some('=') if out.is_rw => {
1510                             s.print_string(&format!("+{}", ch.as_str()),
1511                                            ast::StrStyle::Cooked)?
1512                         }
1513                         _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1514                     }
1515                     s.popen()?;
1516                     s.print_expr(&outputs[out_idx])?;
1517                     s.pclose()?;
1518                     out_idx += 1;
1519                     Ok(())
1520                 })?;
1521                 self.s.space()?;
1522                 self.word_space(":")?;
1523
1524                 let mut in_idx = 0;
1525                 self.commasep(Inconsistent, &a.inputs, |s, co| {
1526                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1527                     s.popen()?;
1528                     s.print_expr(&inputs[in_idx])?;
1529                     s.pclose()?;
1530                     in_idx += 1;
1531                     Ok(())
1532                 })?;
1533                 self.s.space()?;
1534                 self.word_space(":")?;
1535
1536                 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1537                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1538                     Ok(())
1539                 })?;
1540
1541                 let mut options = vec![];
1542                 if a.volatile {
1543                     options.push("volatile");
1544                 }
1545                 if a.alignstack {
1546                     options.push("alignstack");
1547                 }
1548                 if a.dialect == ast::AsmDialect::Intel {
1549                     options.push("intel");
1550                 }
1551
1552                 if !options.is_empty() {
1553                     self.s.space()?;
1554                     self.word_space(":")?;
1555                     self.commasep(Inconsistent, &options, |s, &co| {
1556                         s.print_string(co, ast::StrStyle::Cooked)?;
1557                         Ok(())
1558                     })?;
1559                 }
1560
1561                 self.pclose()?;
1562             }
1563             hir::ExprKind::Yield(ref expr) => {
1564                 self.word_space("yield")?;
1565                 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
1566             }
1567             hir::ExprKind::Err => {
1568                 self.popen()?;
1569                 self.s.word("/*ERROR*/")?;
1570                 self.pclose()?;
1571             }
1572         }
1573         self.ann.post(self, AnnNode::Expr(expr))?;
1574         self.end()
1575     }
1576
1577     pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1578         self.print_pat(&loc.pat)?;
1579         if let Some(ref ty) = loc.ty {
1580             self.word_space(":")?;
1581             self.print_type(&ty)?;
1582         }
1583         Ok(())
1584     }
1585
1586     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1587         self.s.word(i.to_string())
1588     }
1589
1590     pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
1591         if ident.is_raw_guess() {
1592             self.s.word(format!("r#{}", ident.name))?;
1593         } else {
1594             self.s.word(ident.as_str().get())?;
1595         }
1596         self.ann.post(self, AnnNode::Name(&ident.name))
1597     }
1598
1599     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1600         self.print_ident(ast::Ident::with_empty_ctxt(name))
1601     }
1602
1603     pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1604         self.print_local_decl(loc)?;
1605         self.s.space()?;
1606         self.word_space("in")?;
1607         self.print_expr(coll)
1608     }
1609
1610     pub fn print_path(&mut self,
1611                       path: &hir::Path,
1612                       colons_before_params: bool)
1613                       -> io::Result<()> {
1614         self.maybe_print_comment(path.span.lo())?;
1615
1616         for (i, segment) in path.segments.iter().enumerate() {
1617             if i > 0 {
1618                 self.s.word("::")?
1619             }
1620             if segment.ident.name != keywords::PathRoot.name() {
1621                self.print_ident(segment.ident)?;
1622                segment.with_generic_args(|generic_args| {
1623                    self.print_generic_args(generic_args, segment.infer_types,
1624                                            colons_before_params)
1625                })?;
1626             }
1627         }
1628
1629         Ok(())
1630     }
1631
1632     pub fn print_path_segment(&mut self, segment: &hir::PathSegment) -> io::Result<()> {
1633         if segment.ident.name != keywords::PathRoot.name() {
1634            self.print_ident(segment.ident)?;
1635            segment.with_generic_args(|generic_args| {
1636                self.print_generic_args(generic_args, segment.infer_types, false)
1637            })?;
1638         }
1639         Ok(())
1640     }
1641
1642     pub fn print_qpath(&mut self,
1643                        qpath: &hir::QPath,
1644                        colons_before_params: bool)
1645                        -> io::Result<()> {
1646         match *qpath {
1647             hir::QPath::Resolved(None, ref path) => {
1648                 self.print_path(path, colons_before_params)
1649             }
1650             hir::QPath::Resolved(Some(ref qself), ref path) => {
1651                 self.s.word("<")?;
1652                 self.print_type(qself)?;
1653                 self.s.space()?;
1654                 self.word_space("as")?;
1655
1656                 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1657                     if i > 0 {
1658                         self.s.word("::")?
1659                     }
1660                     if segment.ident.name != keywords::PathRoot.name() {
1661                         self.print_ident(segment.ident)?;
1662                         segment.with_generic_args(|generic_args| {
1663                             self.print_generic_args(generic_args,
1664                                                     segment.infer_types,
1665                                                     colons_before_params)
1666                         })?;
1667                     }
1668                 }
1669
1670                 self.s.word(">")?;
1671                 self.s.word("::")?;
1672                 let item_segment = path.segments.last().unwrap();
1673                 self.print_ident(item_segment.ident)?;
1674                 item_segment.with_generic_args(|generic_args| {
1675                     self.print_generic_args(generic_args,
1676                                             item_segment.infer_types,
1677                                             colons_before_params)
1678                 })
1679             }
1680             hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1681                 self.s.word("<")?;
1682                 self.print_type(qself)?;
1683                 self.s.word(">")?;
1684                 self.s.word("::")?;
1685                 self.print_ident(item_segment.ident)?;
1686                 item_segment.with_generic_args(|generic_args| {
1687                     self.print_generic_args(generic_args,
1688                                             item_segment.infer_types,
1689                                             colons_before_params)
1690                 })
1691             }
1692         }
1693     }
1694
1695     fn print_generic_args(&mut self,
1696                              generic_args: &hir::GenericArgs,
1697                              infer_types: bool,
1698                              colons_before_params: bool)
1699                              -> io::Result<()> {
1700         if generic_args.parenthesized {
1701             self.s.word("(")?;
1702             self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
1703             self.s.word(")")?;
1704
1705             self.space_if_not_bol()?;
1706             self.word_space("->")?;
1707             self.print_type(&generic_args.bindings[0].ty)?;
1708         } else {
1709             let start = if colons_before_params { "::<" } else { "<" };
1710             let empty = Cell::new(true);
1711             let start_or_comma = |this: &mut Self| {
1712                 if empty.get() {
1713                     empty.set(false);
1714                     this.s.word(start)
1715                 } else {
1716                     this.word_space(",")
1717                 }
1718             };
1719
1720             let mut nonelided_generic_args: bool = false;
1721             let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1722                 GenericArg::Lifetime(lt) => lt.is_elided(),
1723                 _ => {
1724                     nonelided_generic_args = true;
1725                     true
1726                 }
1727             });
1728
1729             if nonelided_generic_args {
1730                 start_or_comma(self)?;
1731                 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1732                     match generic_arg {
1733                         GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1734                         GenericArg::Lifetime(_) => Ok(()),
1735                         GenericArg::Type(ty) => s.print_type(ty),
1736                         GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1737                     }
1738                 })?;
1739             }
1740
1741             // FIXME(eddyb) This would leak into error messages, e.g.:
1742             // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1743             if infer_types && false {
1744                 start_or_comma(self)?;
1745                 self.s.word("..")?;
1746             }
1747
1748             for binding in generic_args.bindings.iter() {
1749                 start_or_comma(self)?;
1750                 self.print_ident(binding.ident)?;
1751                 self.s.space()?;
1752                 self.word_space("=")?;
1753                 self.print_type(&binding.ty)?;
1754             }
1755
1756             if !empty.get() {
1757                 self.s.word(">")?
1758             }
1759         }
1760
1761         Ok(())
1762     }
1763
1764     pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1765         self.maybe_print_comment(pat.span.lo())?;
1766         self.ann.pre(self, AnnNode::Pat(pat))?;
1767         // Pat isn't normalized, but the beauty of it
1768         // is that it doesn't matter
1769         match pat.node {
1770             PatKind::Wild => self.s.word("_")?,
1771             PatKind::Binding(binding_mode, _, ident, ref sub) => {
1772                 match binding_mode {
1773                     hir::BindingAnnotation::Ref => {
1774                         self.word_nbsp("ref")?;
1775                         self.print_mutability(hir::MutImmutable)?;
1776                     }
1777                     hir::BindingAnnotation::RefMut => {
1778                         self.word_nbsp("ref")?;
1779                         self.print_mutability(hir::MutMutable)?;
1780                     }
1781                     hir::BindingAnnotation::Unannotated => {}
1782                     hir::BindingAnnotation::Mutable => {
1783                         self.word_nbsp("mut")?;
1784                     }
1785                 }
1786                 self.print_ident(ident)?;
1787                 if let Some(ref p) = *sub {
1788                     self.s.word("@")?;
1789                     self.print_pat(&p)?;
1790                 }
1791             }
1792             PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1793                 self.print_qpath(qpath, true)?;
1794                 self.popen()?;
1795                 if let Some(ddpos) = ddpos {
1796                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1797                     if ddpos != 0 {
1798                         self.word_space(",")?;
1799                     }
1800                     self.s.word("..")?;
1801                     if ddpos != elts.len() {
1802                         self.s.word(",")?;
1803                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1804                     }
1805                 } else {
1806                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1807                 }
1808                 self.pclose()?;
1809             }
1810             PatKind::Path(ref qpath) => {
1811                 self.print_qpath(qpath, true)?;
1812             }
1813             PatKind::Struct(ref qpath, ref fields, etc) => {
1814                 self.print_qpath(qpath, true)?;
1815                 self.nbsp()?;
1816                 self.word_space("{")?;
1817                 self.commasep_cmnt(Consistent,
1818                                    &fields[..],
1819                                    |s, f| {
1820                                        s.cbox(indent_unit)?;
1821                                        if !f.node.is_shorthand {
1822                                            s.print_ident(f.node.ident)?;
1823                                            s.word_nbsp(":")?;
1824                                        }
1825                                        s.print_pat(&f.node.pat)?;
1826                                        s.end()
1827                                    },
1828                                    |f| f.node.pat.span)?;
1829                 if etc {
1830                     if !fields.is_empty() {
1831                         self.word_space(",")?;
1832                     }
1833                     self.s.word("..")?;
1834                 }
1835                 self.s.space()?;
1836                 self.s.word("}")?;
1837             }
1838             PatKind::Tuple(ref elts, ddpos) => {
1839                 self.popen()?;
1840                 if let Some(ddpos) = ddpos {
1841                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1842                     if ddpos != 0 {
1843                         self.word_space(",")?;
1844                     }
1845                     self.s.word("..")?;
1846                     if ddpos != elts.len() {
1847                         self.s.word(",")?;
1848                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1849                     }
1850                 } else {
1851                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1852                     if elts.len() == 1 {
1853                         self.s.word(",")?;
1854                     }
1855                 }
1856                 self.pclose()?;
1857             }
1858             PatKind::Box(ref inner) => {
1859                 let is_range_inner = match inner.node {
1860                     PatKind::Range(..) => true,
1861                     _ => false,
1862                 };
1863                 self.s.word("box ")?;
1864                 if is_range_inner {
1865                     self.popen()?;
1866                 }
1867                 self.print_pat(&inner)?;
1868                 if is_range_inner {
1869                     self.pclose()?;
1870                 }
1871             }
1872             PatKind::Ref(ref inner, mutbl) => {
1873                 let is_range_inner = match inner.node {
1874                     PatKind::Range(..) => true,
1875                     _ => false,
1876                 };
1877                 self.s.word("&")?;
1878                 if mutbl == hir::MutMutable {
1879                     self.s.word("mut ")?;
1880                 }
1881                 if is_range_inner {
1882                     self.popen()?;
1883                 }
1884                 self.print_pat(&inner)?;
1885                 if is_range_inner {
1886                     self.pclose()?;
1887                 }
1888             }
1889             PatKind::Lit(ref e) => self.print_expr(&e)?,
1890             PatKind::Range(ref begin, ref end, ref end_kind) => {
1891                 self.print_expr(&begin)?;
1892                 self.s.space()?;
1893                 match *end_kind {
1894                     RangeEnd::Included => self.s.word("...")?,
1895                     RangeEnd::Excluded => self.s.word("..")?,
1896                 }
1897                 self.print_expr(&end)?;
1898             }
1899             PatKind::Slice(ref before, ref slice, ref after) => {
1900                 self.s.word("[")?;
1901                 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1902                 if let Some(ref p) = *slice {
1903                     if !before.is_empty() {
1904                         self.word_space(",")?;
1905                     }
1906                     if let PatKind::Wild = p.node {
1907                         // Print nothing
1908                     } else {
1909                         self.print_pat(&p)?;
1910                     }
1911                     self.s.word("..")?;
1912                     if !after.is_empty() {
1913                         self.word_space(",")?;
1914                     }
1915                 }
1916                 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1917                 self.s.word("]")?;
1918             }
1919         }
1920         self.ann.post(self, AnnNode::Pat(pat))
1921     }
1922
1923     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1924         // I have no idea why this check is necessary, but here it
1925         // is :(
1926         if arm.attrs.is_empty() {
1927             self.s.space()?;
1928         }
1929         self.cbox(indent_unit)?;
1930         self.ibox(0)?;
1931         self.print_outer_attributes(&arm.attrs)?;
1932         let mut first = true;
1933         for p in &arm.pats {
1934             if first {
1935                 first = false;
1936             } else {
1937                 self.s.space()?;
1938                 self.word_space("|")?;
1939             }
1940             self.print_pat(&p)?;
1941         }
1942         self.s.space()?;
1943         if let Some(ref g) = arm.guard {
1944             match g {
1945                 hir::Guard::If(e) => {
1946                     self.word_space("if")?;
1947                     self.print_expr(&e)?;
1948                     self.s.space()?;
1949                 }
1950             }
1951         }
1952         self.word_space("=>")?;
1953
1954         match arm.body.node {
1955             hir::ExprKind::Block(ref blk, opt_label) => {
1956                 if let Some(label) = opt_label {
1957                     self.print_ident(label.ident)?;
1958                     self.word_space(":")?;
1959                 }
1960                 // the block will close the pattern's ibox
1961                 self.print_block_unclosed_indent(&blk, indent_unit)?;
1962
1963                 // If it is a user-provided unsafe block, print a comma after it
1964                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1965                     self.s.word(",")?;
1966                 }
1967             }
1968             _ => {
1969                 self.end()?; // close the ibox for the pattern
1970                 self.print_expr(&arm.body)?;
1971                 self.s.word(",")?;
1972             }
1973         }
1974         self.end() // close enclosing cbox
1975     }
1976
1977     pub fn print_fn(&mut self,
1978                     decl: &hir::FnDecl,
1979                     header: hir::FnHeader,
1980                     name: Option<ast::Name>,
1981                     generics: &hir::Generics,
1982                     vis: &hir::Visibility,
1983                     arg_names: &[ast::Ident],
1984                     body_id: Option<hir::BodyId>)
1985                     -> io::Result<()> {
1986         self.print_fn_header_info(header, vis)?;
1987
1988         if let Some(name) = name {
1989             self.nbsp()?;
1990             self.print_name(name)?;
1991         }
1992         self.print_generic_params(&generics.params)?;
1993
1994         self.popen()?;
1995         let mut i = 0;
1996         // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1997         assert!(arg_names.is_empty() || body_id.is_none());
1998         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1999             s.ibox(indent_unit)?;
2000             if let Some(arg_name) = arg_names.get(i) {
2001                 s.s.word(arg_name.as_str().get())?;
2002                 s.s.word(":")?;
2003                 s.s.space()?;
2004             } else if let Some(body_id) = body_id {
2005                 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2006                 s.s.word(":")?;
2007                 s.s.space()?;
2008             }
2009             i += 1;
2010             s.print_type(ty)?;
2011             s.end()
2012         })?;
2013         if decl.c_variadic {
2014             self.s.word(", ...")?;
2015         }
2016         self.pclose()?;
2017
2018         self.print_fn_output(decl)?;
2019         self.print_where_clause(&generics.where_clause)
2020     }
2021
2022     fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2023         self.s.word("|")?;
2024         let mut i = 0;
2025         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2026             s.ibox(indent_unit)?;
2027
2028             s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2029             i += 1;
2030
2031             if let hir::TyKind::Infer = ty.node {
2032                 // Print nothing
2033             } else {
2034                 s.s.word(":")?;
2035                 s.s.space()?;
2036                 s.print_type(ty)?;
2037             }
2038             s.end()
2039         })?;
2040         self.s.word("|")?;
2041
2042         if let hir::DefaultReturn(..) = decl.output {
2043             return Ok(());
2044         }
2045
2046         self.space_if_not_bol()?;
2047         self.word_space("->")?;
2048         match decl.output {
2049             hir::Return(ref ty) => {
2050                 self.print_type(&ty)?;
2051                 self.maybe_print_comment(ty.span.lo())
2052             }
2053             hir::DefaultReturn(..) => unreachable!(),
2054         }
2055     }
2056
2057     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2058         match capture_clause {
2059             hir::CaptureByValue => self.word_space("move"),
2060             hir::CaptureByRef => Ok(()),
2061         }
2062     }
2063
2064     pub fn print_bounds(&mut self, prefix: &'static str, bounds: &[hir::GenericBound])
2065                         -> io::Result<()> {
2066         if !bounds.is_empty() {
2067             self.s.word(prefix)?;
2068             let mut first = true;
2069             for bound in bounds {
2070                 if !(first && prefix.is_empty()) {
2071                     self.nbsp()?;
2072                 }
2073                 if first {
2074                     first = false;
2075                 } else {
2076                     self.word_space("+")?;
2077                 }
2078
2079                 match bound {
2080                     GenericBound::Trait(tref, modifier) => {
2081                         if modifier == &TraitBoundModifier::Maybe {
2082                             self.s.word("?")?;
2083                         }
2084                         self.print_poly_trait_ref(tref)?;
2085                     }
2086                     GenericBound::Outlives(lt) => {
2087                         self.print_lifetime(lt)?;
2088                     }
2089                 }
2090             }
2091         }
2092         Ok(())
2093     }
2094
2095     pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2096         if !generic_params.is_empty() {
2097             self.s.word("<")?;
2098
2099             self.commasep(Inconsistent, generic_params, |s, param| {
2100                 s.print_generic_param(param)
2101             })?;
2102
2103             self.s.word(">")?;
2104         }
2105         Ok(())
2106     }
2107
2108     pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2109         if let GenericParamKind::Const { .. } = param.kind {
2110             self.word_space("const")?;
2111         }
2112
2113         self.print_ident(param.name.ident())?;
2114
2115         match param.kind {
2116             GenericParamKind::Lifetime { .. } => {
2117                 let mut sep = ":";
2118                 for bound in &param.bounds {
2119                     match bound {
2120                         GenericBound::Outlives(lt) => {
2121                             self.s.word(sep)?;
2122                             self.print_lifetime(lt)?;
2123                             sep = "+";
2124                         }
2125                         _ => bug!(),
2126                     }
2127                 }
2128                 Ok(())
2129             }
2130             GenericParamKind::Type { ref default, .. } => {
2131                 self.print_bounds(":", &param.bounds)?;
2132                 match default {
2133                     Some(default) => {
2134                         self.s.space()?;
2135                         self.word_space("=")?;
2136                         self.print_type(&default)
2137                     }
2138                     _ => Ok(()),
2139                 }
2140             }
2141             GenericParamKind::Const { ref ty } => {
2142                 self.word_space(":")?;
2143                 self.print_type(ty)
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                 hir_id: hir::DUMMY_HIR_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::Local(_) => true,
2405         hir::StmtKind::Item(_) => false,
2406         hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2407         hir::StmtKind::Semi(..) => false,
2408     }
2409 }
2410
2411 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2412     use crate::hir::BinOpKind::*;
2413     match op {
2414         Add => AssocOp::Add,
2415         Sub => AssocOp::Subtract,
2416         Mul => AssocOp::Multiply,
2417         Div => AssocOp::Divide,
2418         Rem => AssocOp::Modulus,
2419
2420         And => AssocOp::LAnd,
2421         Or => AssocOp::LOr,
2422
2423         BitXor => AssocOp::BitXor,
2424         BitAnd => AssocOp::BitAnd,
2425         BitOr => AssocOp::BitOr,
2426         Shl => AssocOp::ShiftLeft,
2427         Shr => AssocOp::ShiftRight,
2428
2429         Eq => AssocOp::Equal,
2430         Lt => AssocOp::Less,
2431         Le => AssocOp::LessEqual,
2432         Ne => AssocOp::NotEqual,
2433         Ge => AssocOp::GreaterEqual,
2434         Gt => AssocOp::Greater,
2435     }
2436 }
2437
2438 /// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any
2439 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2440 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2441 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2442     match value.node {
2443         hir::ExprKind::Struct(..) => true,
2444
2445         hir::ExprKind::Assign(ref lhs, ref rhs) |
2446         hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2447         hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2448             // X { y: 1 } + X { y: 2 }
2449             contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2450         }
2451         hir::ExprKind::Unary(_, ref x) |
2452         hir::ExprKind::Cast(ref x, _) |
2453         hir::ExprKind::Type(ref x, _) |
2454         hir::ExprKind::Field(ref x, _) |
2455         hir::ExprKind::Index(ref x, _) => {
2456             // &X { y: 1 }, X { y: 1 }.y
2457             contains_exterior_struct_lit(&x)
2458         }
2459
2460         hir::ExprKind::MethodCall(.., ref exprs) => {
2461             // X { y: 1 }.bar(...)
2462             contains_exterior_struct_lit(&exprs[0])
2463         }
2464
2465         _ => false,
2466     }
2467 }