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