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