]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/print.rs
Implement existential types
[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::TyKind::Slice(ref ty) => {
371                 self.s.word("[")?;
372                 self.print_type(&ty)?;
373                 self.s.word("]")?;
374             }
375             hir::TyKind::Ptr(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::TyKind::Rptr(ref lifetime, ref mt) => {
384                 self.s.word("&")?;
385                 self.print_opt_lifetime(lifetime)?;
386                 self.print_mt(mt)?;
387             }
388             hir::TyKind::Never => {
389                 self.s.word("!")?;
390             },
391             hir::TyKind::Tup(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::TyKind::BareFn(ref f) => {
400                 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
401                                  &f.arg_names[..])?;
402             }
403             hir::TyKind::Path(ref qpath) => {
404                 self.print_qpath(qpath, false)?
405             }
406             hir::TyKind::TraitObject(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::TyKind::Array(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::TyKind::Typeof(ref e) => {
431                 self.s.word("typeof(")?;
432                 self.print_anon_const(e)?;
433                 self.s.word(")")?;
434             }
435             hir::TyKind::Infer => {
436                 self.s.word("_")?;
437             }
438             hir::TyKind::Err => {
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::ForeignItemKind::Fn(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::ForeignItemKind::Static(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::ForeignItemKind::Type => {
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::ItemKind::ExternCrate(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::ItemKind::Use(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::ItemKind::Static(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::ItemKind::Const(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::ItemKind::Fn(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::ItemKind::Mod(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::ItemKind::ForeignMod(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::ItemKind::GlobalAsm(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::ItemKind::Ty(ref ty, ref generics) => {
630                 self.head(&visibility_qualified(&item.vis, "type"))?;
631                 self.print_name(item.name)?;
632                 self.print_generic_params(&generics.params)?;
633                 self.end()?; // end the inner ibox
634
635                 self.print_where_clause(&generics.where_clause)?;
636                 self.s.space()?;
637                 self.word_space("=")?;
638                 self.print_type(&ty)?;
639                 self.s.word(";")?;
640                 self.end()?; // end the outer ibox
641             }
642             hir::ItemKind::Existential(ref exist) => {
643                 self.head(&visibility_qualified(&item.vis, "existential type"))?;
644                 self.print_name(item.name)?;
645                 self.print_generic_params(&exist.generics.params)?;
646                 self.end()?; // end the inner ibox
647
648                 self.print_where_clause(&exist.generics.where_clause)?;
649                 self.s.space()?;
650                 self.word_space(":")?;
651                 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
652                 for b in exist.bounds.iter() {
653                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
654                         self.s.space()?;
655                         self.word_space("for ?")?;
656                         self.print_trait_ref(&ptr.trait_ref)?;
657                     } else {
658                         real_bounds.push(b.clone());
659                     }
660                 }
661                 self.print_bounds(":", &real_bounds[..])?;
662                 self.s.word(";")?;
663                 self.end()?; // end the outer ibox
664             }
665             hir::ItemKind::Enum(ref enum_definition, ref params) => {
666                 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
667             }
668             hir::ItemKind::Struct(ref struct_def, ref generics) => {
669                 self.head(&visibility_qualified(&item.vis, "struct"))?;
670                 self.print_struct(struct_def, generics, item.name, item.span, true)?;
671             }
672             hir::ItemKind::Union(ref struct_def, ref generics) => {
673                 self.head(&visibility_qualified(&item.vis, "union"))?;
674                 self.print_struct(struct_def, generics, item.name, item.span, true)?;
675             }
676             hir::ItemKind::Impl(unsafety,
677                           polarity,
678                           defaultness,
679                           ref generics,
680                           ref opt_trait,
681                           ref ty,
682                           ref impl_items) => {
683                 self.head("")?;
684                 self.print_visibility(&item.vis)?;
685                 self.print_defaultness(defaultness)?;
686                 self.print_unsafety(unsafety)?;
687                 self.word_nbsp("impl")?;
688
689                 if !generics.params.is_empty() {
690                     self.print_generic_params(&generics.params)?;
691                     self.s.space()?;
692                 }
693
694                 match polarity {
695                     hir::ImplPolarity::Negative => {
696                         self.s.word("!")?;
697                     }
698                     _ => {}
699                 }
700
701                 match opt_trait {
702                     &Some(ref t) => {
703                         self.print_trait_ref(t)?;
704                         self.s.space()?;
705                         self.word_space("for")?;
706                     }
707                     &None => {}
708                 }
709
710                 self.print_type(&ty)?;
711                 self.print_where_clause(&generics.where_clause)?;
712
713                 self.s.space()?;
714                 self.bopen()?;
715                 self.print_inner_attributes(&item.attrs)?;
716                 for impl_item in impl_items {
717                     self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
718                 }
719                 self.bclose(item.span)?;
720             }
721             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
722                 self.head("")?;
723                 self.print_visibility(&item.vis)?;
724                 self.print_is_auto(is_auto)?;
725                 self.print_unsafety(unsafety)?;
726                 self.word_nbsp("trait")?;
727                 self.print_name(item.name)?;
728                 self.print_generic_params(&generics.params)?;
729                 let mut real_bounds = Vec::with_capacity(bounds.len());
730                 for b in bounds.iter() {
731                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
732                         self.s.space()?;
733                         self.word_space("for ?")?;
734                         self.print_trait_ref(&ptr.trait_ref)?;
735                     } else {
736                         real_bounds.push(b.clone());
737                     }
738                 }
739                 self.print_bounds(":", &real_bounds[..])?;
740                 self.print_where_clause(&generics.where_clause)?;
741                 self.s.word(" ")?;
742                 self.bopen()?;
743                 for trait_item in trait_items {
744                     self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
745                 }
746                 self.bclose(item.span)?;
747             }
748             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
749                 self.head("")?;
750                 self.print_visibility(&item.vis)?;
751                 self.word_nbsp("trait")?;
752                 self.print_name(item.name)?;
753                 self.print_generic_params(&generics.params)?;
754                 let mut real_bounds = Vec::with_capacity(bounds.len());
755                 // FIXME(durka) this seems to be some quite outdated syntax
756                 for b in bounds.iter() {
757                     if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
758                         self.s.space()?;
759                         self.word_space("for ?")?;
760                         self.print_trait_ref(&ptr.trait_ref)?;
761                     } else {
762                         real_bounds.push(b.clone());
763                     }
764                 }
765                 self.nbsp()?;
766                 self.print_bounds("=", &real_bounds[..])?;
767                 self.print_where_clause(&generics.where_clause)?;
768                 self.s.word(";")?;
769             }
770         }
771         self.ann.post(self, NodeItem(item))
772     }
773
774     pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
775         self.print_path(&t.path, false)
776     }
777
778     fn print_formal_generic_params(
779         &mut self,
780         generic_params: &[hir::GenericParam]
781     ) -> io::Result<()> {
782         if !generic_params.is_empty() {
783             self.s.word("for")?;
784             self.print_generic_params(generic_params)?;
785             self.nbsp()?;
786         }
787         Ok(())
788     }
789
790     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
791         self.print_formal_generic_params(&t.bound_generic_params)?;
792         self.print_trait_ref(&t.trait_ref)
793     }
794
795     pub fn print_enum_def(&mut self,
796                           enum_definition: &hir::EnumDef,
797                           generics: &hir::Generics,
798                           name: ast::Name,
799                           span: syntax_pos::Span,
800                           visibility: &hir::Visibility)
801                           -> io::Result<()> {
802         self.head(&visibility_qualified(visibility, "enum"))?;
803         self.print_name(name)?;
804         self.print_generic_params(&generics.params)?;
805         self.print_where_clause(&generics.where_clause)?;
806         self.s.space()?;
807         self.print_variants(&enum_definition.variants, span)
808     }
809
810     pub fn print_variants(&mut self,
811                           variants: &[hir::Variant],
812                           span: syntax_pos::Span)
813                           -> io::Result<()> {
814         self.bopen()?;
815         for v in variants {
816             self.space_if_not_bol()?;
817             self.maybe_print_comment(v.span.lo())?;
818             self.print_outer_attributes(&v.node.attrs)?;
819             self.ibox(indent_unit)?;
820             self.print_variant(v)?;
821             self.s.word(",")?;
822             self.end()?;
823             self.maybe_print_trailing_comment(v.span, None)?;
824         }
825         self.bclose(span)
826     }
827
828     pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
829         match vis.node {
830             hir::VisibilityKind::Public => self.word_nbsp("pub")?,
831             hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate")?,
832             hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)")?,
833             hir::VisibilityKind::Restricted { ref path, .. } => {
834                 self.s.word("pub(")?;
835                 if path.segments.len() == 1 &&
836                    path.segments[0].ident.name == keywords::Super.name() {
837                     // Special case: `super` can print like `pub(super)`.
838                     self.s.word("super")?;
839                 } else {
840                     // Everything else requires `in` at present.
841                     self.word_nbsp("in")?;
842                     self.print_path(path, false)?;
843                 }
844                 self.word_nbsp(")")?;
845             }
846             hir::VisibilityKind::Inherited => ()
847         }
848
849         Ok(())
850     }
851
852     pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) -> io::Result<()> {
853         match defaultness {
854             hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
855             hir::Defaultness::Final => (),
856         }
857         Ok(())
858     }
859
860     pub fn print_struct(&mut self,
861                         struct_def: &hir::VariantData,
862                         generics: &hir::Generics,
863                         name: ast::Name,
864                         span: syntax_pos::Span,
865                         print_finalizer: bool)
866                         -> io::Result<()> {
867         self.print_name(name)?;
868         self.print_generic_params(&generics.params)?;
869         if !struct_def.is_struct() {
870             if struct_def.is_tuple() {
871                 self.popen()?;
872                 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
873                     s.maybe_print_comment(field.span.lo())?;
874                     s.print_outer_attributes(&field.attrs)?;
875                     s.print_visibility(&field.vis)?;
876                     s.print_type(&field.ty)
877                 })?;
878                 self.pclose()?;
879             }
880             self.print_where_clause(&generics.where_clause)?;
881             if print_finalizer {
882                 self.s.word(";")?;
883             }
884             self.end()?;
885             self.end() // close the outer-box
886         } else {
887             self.print_where_clause(&generics.where_clause)?;
888             self.nbsp()?;
889             self.bopen()?;
890             self.hardbreak_if_not_bol()?;
891
892             for field in struct_def.fields() {
893                 self.hardbreak_if_not_bol()?;
894                 self.maybe_print_comment(field.span.lo())?;
895                 self.print_outer_attributes(&field.attrs)?;
896                 self.print_visibility(&field.vis)?;
897                 self.print_ident(field.ident)?;
898                 self.word_nbsp(":")?;
899                 self.print_type(&field.ty)?;
900                 self.s.word(",")?;
901             }
902
903             self.bclose(span)
904         }
905     }
906
907     pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
908         self.head("")?;
909         let generics = hir::Generics::empty();
910         self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
911         if let Some(ref d) = v.node.disr_expr {
912             self.s.space()?;
913             self.word_space("=")?;
914             self.print_anon_const(d)?;
915         }
916         Ok(())
917     }
918     pub fn print_method_sig(&mut self,
919                             ident: ast::Ident,
920                             m: &hir::MethodSig,
921                             generics: &hir::Generics,
922                             vis: &hir::Visibility,
923                             arg_names: &[ast::Ident],
924                             body_id: Option<hir::BodyId>)
925                             -> io::Result<()> {
926         self.print_fn(&m.decl,
927                       m.header,
928                       Some(ident.name),
929                       generics,
930                       vis,
931                       arg_names,
932                       body_id)
933     }
934
935     pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
936         self.ann.pre(self, NodeSubItem(ti.id))?;
937         self.hardbreak_if_not_bol()?;
938         self.maybe_print_comment(ti.span.lo())?;
939         self.print_outer_attributes(&ti.attrs)?;
940         match ti.node {
941             hir::TraitItemKind::Const(ref ty, default) => {
942                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
943                                     node: hir::VisibilityKind::Inherited };
944                 self.print_associated_const(ti.ident, &ty, default, &vis)?;
945             }
946             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
947                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
948                                     node: hir::VisibilityKind::Inherited };
949                 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None)?;
950                 self.s.word(";")?;
951             }
952             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
953                 let vis = Spanned { span: syntax_pos::DUMMY_SP,
954                                     node: hir::VisibilityKind::Inherited };
955                 self.head("")?;
956                 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body))?;
957                 self.nbsp()?;
958                 self.end()?; // need to close a box
959                 self.end()?; // need to close a box
960                 self.ann.nested(self, Nested::Body(body))?;
961             }
962             hir::TraitItemKind::Type(ref bounds, ref default) => {
963                 self.print_associated_type(ti.ident,
964                                            Some(bounds),
965                                            default.as_ref().map(|ty| &**ty))?;
966             }
967         }
968         self.ann.post(self, NodeSubItem(ti.id))
969     }
970
971     pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
972         self.ann.pre(self, NodeSubItem(ii.id))?;
973         self.hardbreak_if_not_bol()?;
974         self.maybe_print_comment(ii.span.lo())?;
975         self.print_outer_attributes(&ii.attrs)?;
976         self.print_defaultness(ii.defaultness)?;
977
978         match ii.node {
979             hir::ImplItemKind::Const(ref ty, expr) => {
980                 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis)?;
981             }
982             hir::ImplItemKind::Method(ref sig, body) => {
983                 self.head("")?;
984                 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body))?;
985                 self.nbsp()?;
986                 self.end()?; // need to close a box
987                 self.end()?; // need to close a box
988                 self.ann.nested(self, Nested::Body(body))?;
989             }
990             hir::ImplItemKind::Type(ref ty) => {
991                 self.print_associated_type(ii.ident, None, Some(ty))?;
992             }
993             hir::ImplItemKind::Existential(ref bounds) => {
994                 self.word_space("existential")?;
995                 self.print_associated_type(ii.ident, Some(bounds), None)?;
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::StmtKind::Decl(ref decl, _) => {
1005                 self.print_decl(&decl)?;
1006             }
1007             hir::StmtKind::Expr(ref expr, _) => {
1008                 self.space_if_not_bol()?;
1009                 self.print_expr(&expr)?;
1010             }
1011             hir::StmtKind::Semi(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::ExprKind::If(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::ExprKind::Block(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::ExprKind::Closure(..) |
1166             hir::ExprKind::Ret(..) |
1167             hir::ExprKind::Break(..) => 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::ExprKind::Field(..) => 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::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1296             (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => 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::ExprKind::Box(ref expr) => {
1327                 self.word_space("box")?;
1328                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)?;
1329             }
1330             hir::ExprKind::Array(ref exprs) => {
1331                 self.print_expr_vec(exprs)?;
1332             }
1333             hir::ExprKind::Repeat(ref element, ref count) => {
1334                 self.print_expr_repeat(&element, count)?;
1335             }
1336             hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1337                 self.print_expr_struct(qpath, &fields[..], wth)?;
1338             }
1339             hir::ExprKind::Tup(ref exprs) => {
1340                 self.print_expr_tup(exprs)?;
1341             }
1342             hir::ExprKind::Call(ref func, ref args) => {
1343                 self.print_expr_call(&func, args)?;
1344             }
1345             hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1346                 self.print_expr_method_call(segment, args)?;
1347             }
1348             hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1349                 self.print_expr_binary(op, &lhs, &rhs)?;
1350             }
1351             hir::ExprKind::Unary(op, ref expr) => {
1352                 self.print_expr_unary(op, &expr)?;
1353             }
1354             hir::ExprKind::AddrOf(m, ref expr) => {
1355                 self.print_expr_addr_of(m, &expr)?;
1356             }
1357             hir::ExprKind::Lit(ref lit) => {
1358                 self.print_literal(&lit)?;
1359             }
1360             hir::ExprKind::Cast(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::ExprKind::Type(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::ExprKind::If(ref test, ref blk, ref elseopt) => {
1374                 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1375             }
1376             hir::ExprKind::While(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::ExprKind::Loop(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::ExprKind::Match(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::ExprKind::Closure(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::ExprKind::Block(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::ExprKind::Assign(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::ExprKind::AssignOp(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::ExprKind::Field(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::ExprKind::Index(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::ExprKind::Path(ref qpath) => {
1460                 self.print_qpath(qpath, true)?
1461             }
1462             hir::ExprKind::Break(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::ExprKind::Continue(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::ExprKind::Ret(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::ExprKind::InlineAsm(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::ExprKind::Yield(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::DeclKind::Local(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::DeclKind::Item(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 let PatKind::Wild = p.node {
1918                         // Print nothing
1919                     } else {
1920                         self.print_pat(&p)?;
1921                     }
1922                     self.s.word("..")?;
1923                     if !after.is_empty() {
1924                         self.word_space(",")?;
1925                     }
1926                 }
1927                 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1928                 self.s.word("]")?;
1929             }
1930         }
1931         self.ann.post(self, NodePat(pat))
1932     }
1933
1934     fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1935         // I have no idea why this check is necessary, but here it
1936         // is :(
1937         if arm.attrs.is_empty() {
1938             self.s.space()?;
1939         }
1940         self.cbox(indent_unit)?;
1941         self.ibox(0)?;
1942         self.print_outer_attributes(&arm.attrs)?;
1943         let mut first = true;
1944         for p in &arm.pats {
1945             if first {
1946                 first = false;
1947             } else {
1948                 self.s.space()?;
1949                 self.word_space("|")?;
1950             }
1951             self.print_pat(&p)?;
1952         }
1953         self.s.space()?;
1954         if let Some(ref e) = arm.guard {
1955             self.word_space("if")?;
1956             self.print_expr(&e)?;
1957             self.s.space()?;
1958         }
1959         self.word_space("=>")?;
1960
1961         match arm.body.node {
1962             hir::ExprKind::Block(ref blk, opt_label) => {
1963                 if let Some(label) = opt_label {
1964                     self.print_ident(label.ident)?;
1965                     self.word_space(":")?;
1966                 }
1967                 // the block will close the pattern's ibox
1968                 self.print_block_unclosed_indent(&blk, indent_unit)?;
1969
1970                 // If it is a user-provided unsafe block, print a comma after it
1971                 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1972                     self.s.word(",")?;
1973                 }
1974             }
1975             _ => {
1976                 self.end()?; // close the ibox for the pattern
1977                 self.print_expr(&arm.body)?;
1978                 self.s.word(",")?;
1979             }
1980         }
1981         self.end() // close enclosing cbox
1982     }
1983
1984     pub fn print_fn(&mut self,
1985                     decl: &hir::FnDecl,
1986                     header: hir::FnHeader,
1987                     name: Option<ast::Name>,
1988                     generics: &hir::Generics,
1989                     vis: &hir::Visibility,
1990                     arg_names: &[ast::Ident],
1991                     body_id: Option<hir::BodyId>)
1992                     -> io::Result<()> {
1993         self.print_fn_header_info(header, vis)?;
1994
1995         if let Some(name) = name {
1996             self.nbsp()?;
1997             self.print_name(name)?;
1998         }
1999         self.print_generic_params(&generics.params)?;
2000
2001         self.popen()?;
2002         let mut i = 0;
2003         // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2004         assert!(arg_names.is_empty() || body_id.is_none());
2005         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2006             s.ibox(indent_unit)?;
2007             if let Some(arg_name) = arg_names.get(i) {
2008                 s.s.word(&arg_name.as_str())?;
2009                 s.s.word(":")?;
2010                 s.s.space()?;
2011             } else if let Some(body_id) = body_id {
2012                 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2013                 s.s.word(":")?;
2014                 s.s.space()?;
2015             }
2016             i += 1;
2017             s.print_type(ty)?;
2018             s.end()
2019         })?;
2020         if decl.variadic {
2021             self.s.word(", ...")?;
2022         }
2023         self.pclose()?;
2024
2025         self.print_fn_output(decl)?;
2026         self.print_where_clause(&generics.where_clause)
2027     }
2028
2029     fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
2030         self.s.word("|")?;
2031         let mut i = 0;
2032         self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2033             s.ibox(indent_unit)?;
2034
2035             s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
2036             i += 1;
2037
2038             if let hir::TyKind::Infer = ty.node {
2039                 // Print nothing
2040             } else {
2041                 s.s.word(":")?;
2042                 s.s.space()?;
2043                 s.print_type(ty)?;
2044             }
2045             s.end()
2046         })?;
2047         self.s.word("|")?;
2048
2049         if let hir::DefaultReturn(..) = decl.output {
2050             return Ok(());
2051         }
2052
2053         self.space_if_not_bol()?;
2054         self.word_space("->")?;
2055         match decl.output {
2056             hir::Return(ref ty) => {
2057                 self.print_type(&ty)?;
2058                 self.maybe_print_comment(ty.span.lo())
2059             }
2060             hir::DefaultReturn(..) => unreachable!(),
2061         }
2062     }
2063
2064     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2065         match capture_clause {
2066             hir::CaptureByValue => self.word_space("move"),
2067             hir::CaptureByRef => Ok(()),
2068         }
2069     }
2070
2071     pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
2072         if !bounds.is_empty() {
2073             self.s.word(prefix)?;
2074             let mut first = true;
2075             for bound in bounds {
2076                 if !(first && prefix.is_empty()) {
2077                     self.nbsp()?;
2078                 }
2079                 if first {
2080                     first = false;
2081                 } else {
2082                     self.word_space("+")?;
2083                 }
2084
2085                 match bound {
2086                     GenericBound::Trait(tref, modifier) => {
2087                         if modifier == &TraitBoundModifier::Maybe {
2088                             self.s.word("?")?;
2089                         }
2090                         self.print_poly_trait_ref(tref)?;
2091                     }
2092                     GenericBound::Outlives(lt) => {
2093                         self.print_lifetime(lt)?;
2094                     }
2095                 }
2096             }
2097         }
2098         Ok(())
2099     }
2100
2101     pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
2102         if !generic_params.is_empty() {
2103             self.s.word("<")?;
2104
2105             self.commasep(Inconsistent, generic_params, |s, param| {
2106                 s.print_generic_param(param)
2107             })?;
2108
2109             self.s.word(">")?;
2110         }
2111         Ok(())
2112     }
2113
2114     pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
2115         self.print_ident(param.name.ident())?;
2116         match param.kind {
2117             GenericParamKind::Lifetime { .. } => {
2118                 let mut sep = ":";
2119                 for bound in &param.bounds {
2120                     match bound {
2121                         GenericBound::Outlives(lt) => {
2122                             self.s.word(sep)?;
2123                             self.print_lifetime(lt)?;
2124                             sep = "+";
2125                         }
2126                         _ => bug!(),
2127                     }
2128                 }
2129                 Ok(())
2130             }
2131             GenericParamKind::Type { ref default, .. } => {
2132                 self.print_bounds(":", &param.bounds)?;
2133                 match default {
2134                     Some(default) => {
2135                         self.s.space()?;
2136                         self.word_space("=")?;
2137                         self.print_type(&default)
2138                     }
2139                     _ => Ok(()),
2140                 }
2141             }
2142         }
2143     }
2144
2145     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2146         self.print_ident(lifetime.name.ident())
2147     }
2148
2149     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2150         if where_clause.predicates.is_empty() {
2151             return Ok(());
2152         }
2153
2154         self.s.space()?;
2155         self.word_space("where")?;
2156
2157         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2158             if i != 0 {
2159                 self.word_space(",")?;
2160             }
2161
2162             match predicate {
2163                 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2164                     ref bound_generic_params,
2165                     ref bounded_ty,
2166                     ref bounds,
2167                     ..
2168                 }) => {
2169                     self.print_formal_generic_params(bound_generic_params)?;
2170                     self.print_type(&bounded_ty)?;
2171                     self.print_bounds(":", bounds)?;
2172                 }
2173                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2174                                                                                 ref bounds,
2175                                                                                 ..}) => {
2176                     self.print_lifetime(lifetime)?;
2177                     self.s.word(":")?;
2178
2179                     for (i, bound) in bounds.iter().enumerate() {
2180                         match bound {
2181                             GenericBound::Outlives(lt) => {
2182                                 self.print_lifetime(lt)?;
2183                             }
2184                             _ => bug!(),
2185                         }
2186
2187                         if i != 0 {
2188                             self.s.word(":")?;
2189                         }
2190                     }
2191                 }
2192                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2193                                                                         ref rhs_ty,
2194                                                                         ..}) => {
2195                     self.print_type(lhs_ty)?;
2196                     self.s.space()?;
2197                     self.word_space("=")?;
2198                     self.print_type(rhs_ty)?;
2199                 }
2200             }
2201         }
2202
2203         Ok(())
2204     }
2205
2206     pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2207         match mutbl {
2208             hir::MutMutable => self.word_nbsp("mut"),
2209             hir::MutImmutable => Ok(()),
2210         }
2211     }
2212
2213     pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2214         self.print_mutability(mt.mutbl)?;
2215         self.print_type(&mt.ty)
2216     }
2217
2218     pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2219         if let hir::DefaultReturn(..) = decl.output {
2220             return Ok(());
2221         }
2222
2223         self.space_if_not_bol()?;
2224         self.ibox(indent_unit)?;
2225         self.word_space("->")?;
2226         match decl.output {
2227             hir::DefaultReturn(..) => unreachable!(),
2228             hir::Return(ref ty) => self.print_type(&ty)?,
2229         }
2230         self.end()?;
2231
2232         match decl.output {
2233             hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2234             _ => Ok(()),
2235         }
2236     }
2237
2238     pub fn print_ty_fn(&mut self,
2239                        abi: Abi,
2240                        unsafety: hir::Unsafety,
2241                        decl: &hir::FnDecl,
2242                        name: Option<ast::Name>,
2243                        generic_params: &[hir::GenericParam],
2244                        arg_names: &[ast::Ident])
2245                        -> io::Result<()> {
2246         self.ibox(indent_unit)?;
2247         if !generic_params.is_empty() {
2248             self.s.word("for")?;
2249             self.print_generic_params(generic_params)?;
2250         }
2251         let generics = hir::Generics {
2252             params: hir::HirVec::new(),
2253             where_clause: hir::WhereClause {
2254                 id: ast::DUMMY_NODE_ID,
2255                 predicates: hir::HirVec::new(),
2256             },
2257             span: syntax_pos::DUMMY_SP,
2258         };
2259         self.print_fn(decl,
2260                       hir::FnHeader {
2261                           unsafety,
2262                           abi,
2263                           constness: hir::Constness::NotConst,
2264                           asyncness: hir::IsAsync::NotAsync,
2265                       },
2266                       name,
2267                       &generics,
2268                       &Spanned { span: syntax_pos::DUMMY_SP,
2269                                  node: hir::VisibilityKind::Inherited },
2270                       arg_names,
2271                       None)?;
2272         self.end()
2273     }
2274
2275     pub fn maybe_print_trailing_comment(&mut self,
2276                                         span: syntax_pos::Span,
2277                                         next_pos: Option<BytePos>)
2278                                         -> io::Result<()> {
2279         let cm = match self.cm {
2280             Some(cm) => cm,
2281             _ => return Ok(()),
2282         };
2283         if let Some(ref cmnt) = self.next_comment() {
2284             if (*cmnt).style != comments::Trailing {
2285                 return Ok(());
2286             }
2287             let span_line = cm.lookup_char_pos(span.hi());
2288             let comment_line = cm.lookup_char_pos((*cmnt).pos);
2289             let mut next = (*cmnt).pos + BytePos(1);
2290             if let Some(p) = next_pos {
2291                 next = p;
2292             }
2293             if span.hi() < (*cmnt).pos && (*cmnt).pos < next &&
2294                span_line.line == comment_line.line {
2295                 self.print_comment(cmnt)?;
2296             }
2297         }
2298         Ok(())
2299     }
2300
2301     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2302         // If there aren't any remaining comments, then we need to manually
2303         // make sure there is a line break at the end.
2304         if self.next_comment().is_none() {
2305             self.s.hardbreak()?;
2306         }
2307         while let Some(ref cmnt) = self.next_comment() {
2308             self.print_comment(cmnt)?
2309         }
2310         Ok(())
2311     }
2312
2313     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2314                                                   opt_abi: Option<Abi>)
2315                                                   -> io::Result<()> {
2316         match opt_abi {
2317             Some(Abi::Rust) => Ok(()),
2318             Some(abi) => {
2319                 self.word_nbsp("extern")?;
2320                 self.word_nbsp(&abi.to_string())
2321             }
2322             None => Ok(()),
2323         }
2324     }
2325
2326     pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2327         match opt_abi {
2328             Some(abi) => {
2329                 self.word_nbsp("extern")?;
2330                 self.word_nbsp(&abi.to_string())
2331             }
2332             None => Ok(()),
2333         }
2334     }
2335
2336     pub fn print_fn_header_info(&mut self,
2337                                 header: hir::FnHeader,
2338                                 vis: &hir::Visibility)
2339                                 -> io::Result<()> {
2340         self.s.word(&visibility_qualified(vis, ""))?;
2341
2342         match header.constness {
2343             hir::Constness::NotConst => {}
2344             hir::Constness::Const => self.word_nbsp("const")?,
2345         }
2346
2347         match header.asyncness {
2348             hir::IsAsync::NotAsync => {}
2349             hir::IsAsync::Async => self.word_nbsp("async")?,
2350         }
2351
2352         self.print_unsafety(header.unsafety)?;
2353
2354         if header.abi != Abi::Rust {
2355             self.word_nbsp("extern")?;
2356             self.word_nbsp(&header.abi.to_string())?;
2357         }
2358
2359         self.s.word("fn")
2360     }
2361
2362     pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2363         match s {
2364             hir::Unsafety::Normal => Ok(()),
2365             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2366         }
2367     }
2368
2369     pub fn print_is_auto(&mut self, s: hir::IsAuto) -> io::Result<()> {
2370         match s {
2371             hir::IsAuto::Yes => self.word_nbsp("auto"),
2372             hir::IsAuto::No => Ok(()),
2373         }
2374     }
2375 }
2376
2377 // Dup'ed from parse::classify, but adapted for the HIR.
2378 /// Does this expression require a semicolon to be treated
2379 /// as a statement? The negation of this: 'can this expression
2380 /// be used as a statement without a semicolon' -- is used
2381 /// as an early-bail-out in the parser so that, for instance,
2382 ///     if true {...} else {...}
2383 ///      |x| 5
2384 /// isn't parsed as (if true {...} else {...} | x) | 5
2385 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2386     match e.node {
2387         hir::ExprKind::If(..) |
2388         hir::ExprKind::Match(..) |
2389         hir::ExprKind::Block(..) |
2390         hir::ExprKind::While(..) |
2391         hir::ExprKind::Loop(..) => false,
2392         _ => true,
2393     }
2394 }
2395
2396 /// this statement requires a semicolon after it.
2397 /// note that in one case (stmt_semi), we've already
2398 /// seen the semicolon, and thus don't need another.
2399 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2400     match *stmt {
2401         hir::StmtKind::Decl(ref d, _) => {
2402             match d.node {
2403                 hir::DeclKind::Local(_) => true,
2404                 hir::DeclKind::Item(_) => false,
2405             }
2406         }
2407         hir::StmtKind::Expr(ref e, _) => {
2408             expr_requires_semi_to_be_stmt(&e)
2409         }
2410         hir::StmtKind::Semi(..) => {
2411             false
2412         }
2413     }
2414 }
2415
2416 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2417     use hir::BinOpKind::*;
2418     match op {
2419         Add => AssocOp::Add,
2420         Sub => AssocOp::Subtract,
2421         Mul => AssocOp::Multiply,
2422         Div => AssocOp::Divide,
2423         Rem => AssocOp::Modulus,
2424
2425         And => AssocOp::LAnd,
2426         Or => AssocOp::LOr,
2427
2428         BitXor => AssocOp::BitXor,
2429         BitAnd => AssocOp::BitAnd,
2430         BitOr => AssocOp::BitOr,
2431         Shl => AssocOp::ShiftLeft,
2432         Shr => AssocOp::ShiftRight,
2433
2434         Eq => AssocOp::Equal,
2435         Lt => AssocOp::Less,
2436         Le => AssocOp::LessEqual,
2437         Ne => AssocOp::NotEqual,
2438         Ge => AssocOp::GreaterEqual,
2439         Gt => AssocOp::Greater,
2440     }
2441 }
2442
2443 /// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any
2444 /// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2445 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2446 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2447     match value.node {
2448         hir::ExprKind::Struct(..) => true,
2449
2450         hir::ExprKind::Assign(ref lhs, ref rhs) |
2451         hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2452         hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2453             // X { y: 1 } + X { y: 2 }
2454             contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2455         }
2456         hir::ExprKind::Unary(_, ref x) |
2457         hir::ExprKind::Cast(ref x, _) |
2458         hir::ExprKind::Type(ref x, _) |
2459         hir::ExprKind::Field(ref x, _) |
2460         hir::ExprKind::Index(ref x, _) => {
2461             // &X { y: 1 }, X { y: 1 }.y
2462             contains_exterior_struct_lit(&x)
2463         }
2464
2465         hir::ExprKind::MethodCall(.., ref exprs) => {
2466             // X { y: 1 }.bar(...)
2467             contains_exterior_struct_lit(&exprs[0])
2468         }
2469
2470         _ => false,
2471     }
2472 }