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