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