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