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