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.
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.
11 pub use self::AnnNode::*;
15 use syntax::codemap::{CodeMap, Spanned};
16 use syntax::parse::ParseSess;
17 use syntax::parse::lexer::comments;
18 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
19 use syntax::print::pp::{Breaks, eof};
20 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
21 use syntax::print::pprust::{self as ast_pp, PrintState};
23 use syntax::symbol::keywords;
24 use syntax_pos::{self, BytePos};
27 use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
29 use std::io::{self, Write, Read};
31 pub enum AnnNode<'a> {
32 NodeName(&'a ast::Name),
33 NodeBlock(&'a hir::Block),
34 NodeItem(&'a hir::Item),
35 NodeSubItem(ast::NodeId),
36 NodeExpr(&'a hir::Expr),
37 NodePat(&'a hir::Pat),
42 TraitItem(hir::TraitItemId),
43 ImplItem(hir::ImplItemId),
45 BodyArgPat(hir::BodyId, usize)
49 fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
52 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
55 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
61 impl PpAnn for NoAnn {}
62 pub const NO_ANN: &'static PpAnn = &NoAnn;
64 impl PpAnn for hir::Crate {
65 fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
67 Nested::Item(id) => state.print_item(self.item(id.id)),
68 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
69 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
70 Nested::Body(id) => state.print_expr(&self.body(id).value),
71 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
76 pub struct State<'a> {
77 pub s: pp::Printer<'a>,
78 cm: Option<&'a CodeMap>,
79 comments: Option<Vec<comments::Comment>>,
80 literals: Option<Vec<comments::Literal>>,
81 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
82 boxes: Vec<pp::Breaks>,
83 ann: &'a (PpAnn + 'a),
86 impl<'a> PrintState<'a> for State<'a> {
87 fn writer(&mut self) -> &mut pp::Printer<'a> {
91 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
95 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
99 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
100 &mut self.cur_cmnt_and_lit
103 fn literals(&self) -> &Option<Vec<comments::Literal>> {
108 #[allow(non_upper_case_globals)]
109 pub const indent_unit: usize = 4;
111 #[allow(non_upper_case_globals)]
112 pub const default_columns: usize = 78;
115 /// Requires you to pass an input filename and reader so that
116 /// it can scan the input text for comments and literals to
118 pub fn print_crate<'a>(cm: &'a CodeMap,
123 out: Box<Write + 'a>,
127 let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
129 // When printing the AST, we sometimes need to inject `#[no_std]` here.
130 // Since you can't compile the HIR, it's not necessary.
132 s.print_mod(&krate.module, &krate.attrs)?;
133 s.print_remaining_comments()?;
138 pub fn new_from_input(cm: &'a CodeMap,
142 out: Box<Write + 'a>,
146 let (cmnts, lits) = comments::gather_comments_and_literals(sess, filename, input);
152 // If the code is post expansion, don't use the table of
153 // literals, since it doesn't correspond with the literals
154 // in the AST anymore.
162 pub fn new(cm: &'a CodeMap,
163 out: Box<Write + 'a>,
165 comments: Option<Vec<comments::Comment>>,
166 literals: Option<Vec<comments::Literal>>)
169 s: pp::mk_printer(out, default_columns),
171 comments: comments.clone(),
172 literals: literals.clone(),
173 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
183 pub fn to_string<F>(ann: &PpAnn, f: F) -> String
184 where F: FnOnce(&mut State) -> io::Result<()>
186 let mut wr = Vec::new();
188 let mut printer = State {
189 s: pp::mk_printer(Box::new(&mut wr), default_columns),
193 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
200 f(&mut printer).unwrap();
201 eof(&mut printer.s).unwrap();
203 String::from_utf8(wr).unwrap()
206 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
207 to_string(NO_ANN, |s| {
208 s.print_visibility(vis)?;
213 fn needs_parentheses(expr: &hir::Expr) -> bool {
215 hir::ExprAssign(..) |
216 hir::ExprBinary(..) |
217 hir::ExprClosure(..) |
218 hir::ExprAssignOp(..) |
220 hir::ExprType(..) => true,
226 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
227 self.boxes.push(pp::Breaks::Consistent);
228 pp::cbox(&mut self.s, u)
231 pub fn nbsp(&mut self) -> io::Result<()> {
232 word(&mut self.s, " ")
235 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
236 word(&mut self.s, w)?;
240 pub fn head(&mut self, w: &str) -> io::Result<()> {
241 // outer-box is consistent
242 self.cbox(indent_unit)?;
243 // head-box is inconsistent
244 self.ibox(w.len() + 1)?;
245 // keyword that starts the head
252 pub fn bopen(&mut self) -> io::Result<()> {
253 word(&mut self.s, "{")?;
254 self.end() // close the head-box
257 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
258 self.bclose_maybe_open(span, indented, true)
260 pub fn bclose_maybe_open(&mut self,
261 span: syntax_pos::Span,
265 self.maybe_print_comment(span.hi)?;
266 self.break_offset_if_not_bol(1, -(indented as isize))?;
267 word(&mut self.s, "}")?;
269 self.end()?; // close the outer-box
273 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
274 self.bclose_(span, indent_unit)
277 pub fn in_cbox(&self) -> bool {
278 match self.boxes.last() {
279 Some(&last_box) => last_box == pp::Breaks::Consistent,
283 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
289 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
291 break_offset(&mut self.s, n, off)
293 if off != 0 && self.s.last_token().is_hardbreak_tok() {
294 // We do something pretty sketchy here: tuck the nonzero
295 // offset-adjustment we were going to deposit along with the
296 // break into the previous hardbreak.
297 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
303 // Synthesizes a comment that was not textually present in the original source
305 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
306 word(&mut self.s, "/*")?;
308 word(&mut self.s, &text[..])?;
310 word(&mut self.s, "*/")
314 pub fn commasep_cmnt<T, F, G>(&mut self,
320 where F: FnMut(&mut State, &T) -> io::Result<()>,
321 G: FnMut(&T) -> syntax_pos::Span
324 let len = elts.len();
327 self.maybe_print_comment(get_span(elt).hi)?;
331 word(&mut self.s, ",")?;
332 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
333 self.space_if_not_bol()?;
339 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
340 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
343 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
344 self.print_inner_attributes(attrs)?;
345 for &item_id in &_mod.item_ids {
346 self.ann.nested(self, Nested::Item(item_id))?;
351 pub fn print_foreign_mod(&mut self,
352 nmod: &hir::ForeignMod,
353 attrs: &[ast::Attribute])
355 self.print_inner_attributes(attrs)?;
356 for item in &nmod.items {
357 self.print_foreign_item(item)?;
362 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
363 if let Some(l) = *lifetime {
364 self.print_lifetime(&l)?;
370 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
371 self.maybe_print_comment(ty.span.lo)?;
374 hir::TySlice(ref ty) => {
375 word(&mut self.s, "[")?;
376 self.print_type(&ty)?;
377 word(&mut self.s, "]")?;
379 hir::TyPtr(ref mt) => {
380 word(&mut self.s, "*")?;
382 hir::MutMutable => self.word_nbsp("mut")?,
383 hir::MutImmutable => self.word_nbsp("const")?,
385 self.print_type(&mt.ty)?;
387 hir::TyRptr(ref lifetime, ref mt) => {
388 word(&mut self.s, "&")?;
389 self.print_opt_lifetime(lifetime)?;
393 word(&mut self.s, "!")?;
395 hir::TyTup(ref elts) => {
397 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
399 word(&mut self.s, ",")?;
403 hir::TyBareFn(ref f) => {
404 let generics = hir::Generics {
405 lifetimes: f.lifetimes.clone(),
406 ty_params: hir::HirVec::new(),
407 where_clause: hir::WhereClause {
408 id: ast::DUMMY_NODE_ID,
409 predicates: hir::HirVec::new(),
411 span: syntax_pos::DUMMY_SP,
413 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
415 hir::TyPath(ref qpath) => {
416 self.print_qpath(qpath, false)?
418 hir::TyTraitObject(ref bounds) => {
419 self.print_bounds("", &bounds[..])?;
421 hir::TyImplTrait(ref bounds) => {
422 self.print_bounds("impl ", &bounds[..])?;
424 hir::TyArray(ref ty, v) => {
425 word(&mut self.s, "[")?;
426 self.print_type(&ty)?;
427 word(&mut self.s, "; ")?;
428 self.ann.nested(self, Nested::Body(v))?;
429 word(&mut self.s, "]")?;
431 hir::TyTypeof(e) => {
432 word(&mut self.s, "typeof(")?;
433 self.ann.nested(self, Nested::Body(e))?;
434 word(&mut self.s, ")")?;
437 word(&mut self.s, "_")?;
443 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
444 self.hardbreak_if_not_bol()?;
445 self.maybe_print_comment(item.span.lo)?;
446 self.print_outer_attributes(&item.attrs)?;
448 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
451 hir::Unsafety::Normal,
452 hir::Constness::NotConst,
459 self.end()?; // end head-ibox
460 word(&mut self.s, ";")?;
461 self.end() // end the outer fn box
463 hir::ForeignItemStatic(ref t, m) => {
464 self.head(&visibility_qualified(&item.vis, "static"))?;
466 self.word_space("mut")?;
468 self.print_name(item.name)?;
469 self.word_space(":")?;
470 self.print_type(&t)?;
471 word(&mut self.s, ";")?;
472 self.end()?; // end the head-ibox
473 self.end() // end the outer cbox
478 fn print_associated_const(&mut self,
481 default: Option<hir::BodyId>,
482 vis: &hir::Visibility)
484 word(&mut self.s, &visibility_qualified(vis, ""))?;
485 self.word_space("const")?;
486 self.print_name(name)?;
487 self.word_space(":")?;
488 self.print_type(ty)?;
489 if let Some(expr) = default {
491 self.word_space("=")?;
492 self.ann.nested(self, Nested::Body(expr))?;
494 word(&mut self.s, ";")
497 fn print_associated_type(&mut self,
499 bounds: Option<&hir::TyParamBounds>,
500 ty: Option<&hir::Ty>)
502 self.word_space("type")?;
503 self.print_name(name)?;
504 if let Some(bounds) = bounds {
505 self.print_bounds(":", bounds)?;
507 if let Some(ty) = ty {
509 self.word_space("=")?;
510 self.print_type(ty)?;
512 word(&mut self.s, ";")
515 /// Pretty-print an item
516 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
517 self.hardbreak_if_not_bol()?;
518 self.maybe_print_comment(item.span.lo)?;
519 self.print_outer_attributes(&item.attrs)?;
520 self.ann.pre(self, NodeItem(item))?;
522 hir::ItemExternCrate(ref optional_path) => {
523 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
524 if let Some(p) = *optional_path {
525 let val = p.as_str();
526 if val.contains("-") {
527 self.print_string(&val, ast::StrStyle::Cooked)?;
532 word(&mut self.s, "as")?;
535 self.print_name(item.name)?;
536 word(&mut self.s, ";")?;
537 self.end()?; // end inner head-block
538 self.end()?; // end outer head-block
540 hir::ItemUse(ref path, kind) => {
541 self.head(&visibility_qualified(&item.vis, "use"))?;
542 self.print_path(path, false)?;
545 hir::UseKind::Single => {
546 if path.segments.last().unwrap().name != item.name {
548 self.word_space("as")?;
549 self.print_name(item.name)?;
551 word(&mut self.s, ";")?;
553 hir::UseKind::Glob => word(&mut self.s, "::*;")?,
554 hir::UseKind::ListStem => word(&mut self.s, "::{};")?
556 self.end()?; // end inner head-block
557 self.end()?; // end outer head-block
559 hir::ItemStatic(ref ty, m, expr) => {
560 self.head(&visibility_qualified(&item.vis, "static"))?;
561 if m == hir::MutMutable {
562 self.word_space("mut")?;
564 self.print_name(item.name)?;
565 self.word_space(":")?;
566 self.print_type(&ty)?;
568 self.end()?; // end the head-ibox
570 self.word_space("=")?;
571 self.ann.nested(self, Nested::Body(expr))?;
572 word(&mut self.s, ";")?;
573 self.end()?; // end the outer cbox
575 hir::ItemConst(ref ty, expr) => {
576 self.head(&visibility_qualified(&item.vis, "const"))?;
577 self.print_name(item.name)?;
578 self.word_space(":")?;
579 self.print_type(&ty)?;
581 self.end()?; // end the head-ibox
583 self.word_space("=")?;
584 self.ann.nested(self, Nested::Body(expr))?;
585 word(&mut self.s, ";")?;
586 self.end()?; // end the outer cbox
588 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, body) => {
599 word(&mut self.s, " ")?;
600 self.end()?; // need to close a box
601 self.end()?; // need to close a box
602 self.ann.nested(self, Nested::Body(body))?;
604 hir::ItemMod(ref _mod) => {
605 self.head(&visibility_qualified(&item.vis, "mod"))?;
606 self.print_name(item.name)?;
609 self.print_mod(_mod, &item.attrs)?;
610 self.bclose(item.span)?;
612 hir::ItemForeignMod(ref nmod) => {
613 self.head("extern")?;
614 self.word_nbsp(&nmod.abi.to_string())?;
616 self.print_foreign_mod(nmod, &item.attrs)?;
617 self.bclose(item.span)?;
619 hir::ItemTy(ref ty, ref params) => {
620 self.ibox(indent_unit)?;
622 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
623 self.print_name(item.name)?;
624 self.print_generics(params)?;
625 self.end()?; // end the inner ibox
627 self.print_where_clause(¶ms.where_clause)?;
629 self.word_space("=")?;
630 self.print_type(&ty)?;
631 word(&mut self.s, ";")?;
632 self.end()?; // end the outer ibox
634 hir::ItemEnum(ref enum_definition, ref params) => {
635 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
637 hir::ItemStruct(ref struct_def, ref generics) => {
638 self.head(&visibility_qualified(&item.vis, "struct"))?;
639 self.print_struct(struct_def, generics, item.name, item.span, true)?;
641 hir::ItemUnion(ref struct_def, ref generics) => {
642 self.head(&visibility_qualified(&item.vis, "union"))?;
643 self.print_struct(struct_def, generics, item.name, item.span, true)?;
645 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
647 self.print_visibility(&item.vis)?;
648 self.print_unsafety(unsafety)?;
649 self.word_nbsp("impl")?;
650 self.print_trait_ref(trait_ref)?;
652 self.word_space("for")?;
653 self.word_space("..")?;
655 self.bclose(item.span)?;
657 hir::ItemImpl(unsafety,
664 self.print_visibility(&item.vis)?;
665 self.print_unsafety(unsafety)?;
666 self.word_nbsp("impl")?;
668 if generics.is_parameterized() {
669 self.print_generics(generics)?;
674 hir::ImplPolarity::Negative => {
675 word(&mut self.s, "!")?;
682 self.print_trait_ref(t)?;
684 self.word_space("for")?;
689 self.print_type(&ty)?;
690 self.print_where_clause(&generics.where_clause)?;
694 self.print_inner_attributes(&item.attrs)?;
695 for impl_item in impl_items {
696 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
698 self.bclose(item.span)?;
700 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
702 self.print_visibility(&item.vis)?;
703 self.print_unsafety(unsafety)?;
704 self.word_nbsp("trait")?;
705 self.print_name(item.name)?;
706 self.print_generics(generics)?;
707 let mut real_bounds = Vec::with_capacity(bounds.len());
708 for b in bounds.iter() {
709 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
711 self.word_space("for ?")?;
712 self.print_trait_ref(&ptr.trait_ref)?;
714 real_bounds.push(b.clone());
717 self.print_bounds(":", &real_bounds[..])?;
718 self.print_where_clause(&generics.where_clause)?;
719 word(&mut self.s, " ")?;
721 for trait_item in trait_items {
722 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
724 self.bclose(item.span)?;
727 self.ann.post(self, NodeItem(item))
730 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
731 self.print_path(&t.path, false)
734 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
735 if !lifetimes.is_empty() {
736 word(&mut self.s, "for<")?;
737 let mut comma = false;
738 for lifetime_def in lifetimes {
740 self.word_space(",")?
742 self.print_lifetime_def(lifetime_def)?;
745 word(&mut self.s, ">")?;
750 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
751 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
752 self.print_trait_ref(&t.trait_ref)
755 pub fn print_enum_def(&mut self,
756 enum_definition: &hir::EnumDef,
757 generics: &hir::Generics,
759 span: syntax_pos::Span,
760 visibility: &hir::Visibility)
762 self.head(&visibility_qualified(visibility, "enum"))?;
763 self.print_name(name)?;
764 self.print_generics(generics)?;
765 self.print_where_clause(&generics.where_clause)?;
767 self.print_variants(&enum_definition.variants, span)
770 pub fn print_variants(&mut self,
771 variants: &[hir::Variant],
772 span: syntax_pos::Span)
776 self.space_if_not_bol()?;
777 self.maybe_print_comment(v.span.lo)?;
778 self.print_outer_attributes(&v.node.attrs)?;
779 self.ibox(indent_unit)?;
780 self.print_variant(v)?;
781 word(&mut self.s, ",")?;
783 self.maybe_print_trailing_comment(v.span, None)?;
788 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
790 hir::Public => self.word_nbsp("pub"),
791 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
792 hir::Visibility::Restricted { ref path, .. } => {
793 word(&mut self.s, "pub(")?;
794 self.print_path(path, false)?;
797 hir::Inherited => Ok(()),
801 pub fn print_struct(&mut self,
802 struct_def: &hir::VariantData,
803 generics: &hir::Generics,
805 span: syntax_pos::Span,
806 print_finalizer: bool)
808 self.print_name(name)?;
809 self.print_generics(generics)?;
810 if !struct_def.is_struct() {
811 if struct_def.is_tuple() {
813 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
814 s.maybe_print_comment(field.span.lo)?;
815 s.print_outer_attributes(&field.attrs)?;
816 s.print_visibility(&field.vis)?;
817 s.print_type(&field.ty)
821 self.print_where_clause(&generics.where_clause)?;
823 word(&mut self.s, ";")?;
826 self.end() // close the outer-box
828 self.print_where_clause(&generics.where_clause)?;
831 self.hardbreak_if_not_bol()?;
833 for field in struct_def.fields() {
834 self.hardbreak_if_not_bol()?;
835 self.maybe_print_comment(field.span.lo)?;
836 self.print_outer_attributes(&field.attrs)?;
837 self.print_visibility(&field.vis)?;
838 self.print_name(field.name)?;
839 self.word_nbsp(":")?;
840 self.print_type(&field.ty)?;
841 word(&mut self.s, ",")?;
848 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
850 let generics = hir::Generics::empty();
851 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
852 if let Some(d) = v.node.disr_expr {
854 self.word_space("=")?;
855 self.ann.nested(self, Nested::Body(d))?;
859 pub fn print_method_sig(&mut self,
862 vis: &hir::Visibility,
863 arg_names: &[Spanned<ast::Name>],
864 body_id: Option<hir::BodyId>)
866 self.print_fn(&m.decl,
877 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
878 self.ann.pre(self, NodeSubItem(ti.id))?;
879 self.hardbreak_if_not_bol()?;
880 self.maybe_print_comment(ti.span.lo)?;
881 self.print_outer_attributes(&ti.attrs)?;
883 hir::TraitItemKind::Const(ref ty, default) => {
884 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
886 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
887 self.print_method_sig(ti.name, sig, &hir::Inherited, arg_names, None)?;
888 word(&mut self.s, ";")?;
890 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
892 self.print_method_sig(ti.name, sig, &hir::Inherited, &[], Some(body))?;
894 self.end()?; // need to close a box
895 self.end()?; // need to close a box
896 self.ann.nested(self, Nested::Body(body))?;
898 hir::TraitItemKind::Type(ref bounds, ref default) => {
899 self.print_associated_type(ti.name,
901 default.as_ref().map(|ty| &**ty))?;
904 self.ann.post(self, NodeSubItem(ti.id))
907 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
908 self.ann.pre(self, NodeSubItem(ii.id))?;
909 self.hardbreak_if_not_bol()?;
910 self.maybe_print_comment(ii.span.lo)?;
911 self.print_outer_attributes(&ii.attrs)?;
913 match ii.defaultness {
914 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
915 hir::Defaultness::Final => (),
919 hir::ImplItemKind::Const(ref ty, expr) => {
920 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
922 hir::ImplItemKind::Method(ref sig, body) => {
924 self.print_method_sig(ii.name, sig, &ii.vis, &[], Some(body))?;
926 self.end()?; // need to close a box
927 self.end()?; // need to close a box
928 self.ann.nested(self, Nested::Body(body))?;
930 hir::ImplItemKind::Type(ref ty) => {
931 self.print_associated_type(ii.name, None, Some(ty))?;
934 self.ann.post(self, NodeSubItem(ii.id))
937 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
938 self.maybe_print_comment(st.span.lo)?;
940 hir::StmtDecl(ref decl, _) => {
941 self.print_decl(&decl)?;
943 hir::StmtExpr(ref expr, _) => {
944 self.space_if_not_bol()?;
945 self.print_expr(&expr)?;
947 hir::StmtSemi(ref expr, _) => {
948 self.space_if_not_bol()?;
949 self.print_expr(&expr)?;
950 word(&mut self.s, ";")?;
953 if stmt_ends_with_semi(&st.node) {
954 word(&mut self.s, ";")?;
956 self.maybe_print_trailing_comment(st.span, None)
959 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
960 self.print_block_with_attrs(blk, &[])
963 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
964 self.print_block_unclosed_indent(blk, indent_unit)
967 pub fn print_block_unclosed_indent(&mut self,
971 self.print_block_maybe_unclosed(blk, indented, &[], false)
974 pub fn print_block_with_attrs(&mut self,
976 attrs: &[ast::Attribute])
978 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
981 pub fn print_block_maybe_unclosed(&mut self,
984 attrs: &[ast::Attribute],
988 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
989 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
990 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
991 hir::DefaultBlock => (),
993 self.maybe_print_comment(blk.span.lo)?;
994 self.ann.pre(self, NodeBlock(blk))?;
997 self.print_inner_attributes(attrs)?;
999 for st in &blk.stmts {
1000 self.print_stmt(st)?;
1004 self.space_if_not_bol()?;
1005 self.print_expr(&expr)?;
1006 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1010 self.bclose_maybe_open(blk.span, indented, close_box)?;
1011 self.ann.post(self, NodeBlock(blk))
1014 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1018 // "another else-if"
1019 hir::ExprIf(ref i, ref then, ref e) => {
1020 self.cbox(indent_unit - 1)?;
1022 word(&mut self.s, " else if ")?;
1023 self.print_expr(&i)?;
1024 space(&mut self.s)?;
1025 self.print_block(&then)?;
1026 self.print_else(e.as_ref().map(|e| &**e))
1029 hir::ExprBlock(ref b) => {
1030 self.cbox(indent_unit - 1)?;
1032 word(&mut self.s, " else ")?;
1033 self.print_block(&b)
1035 // BLEAH, constraints would be great here
1037 panic!("print_if saw if with weird alternative");
1045 pub fn print_if(&mut self,
1048 elseopt: Option<&hir::Expr>)
1051 self.print_expr(test)?;
1052 space(&mut self.s)?;
1053 self.print_block(blk)?;
1054 self.print_else(elseopt)
1057 pub fn print_if_let(&mut self,
1061 elseopt: Option<&hir::Expr>)
1063 self.head("if let")?;
1064 self.print_pat(pat)?;
1065 space(&mut self.s)?;
1066 self.word_space("=")?;
1067 self.print_expr(expr)?;
1068 space(&mut self.s)?;
1069 self.print_block(blk)?;
1070 self.print_else(elseopt)
1074 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1076 self.commasep_exprs(Inconsistent, args)?;
1080 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1081 let needs_par = needs_parentheses(expr);
1085 self.print_expr(expr)?;
1092 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1093 self.ibox(indent_unit)?;
1094 word(&mut self.s, "[")?;
1095 self.commasep_exprs(Inconsistent, exprs)?;
1096 word(&mut self.s, "]")?;
1100 fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1101 self.ibox(indent_unit)?;
1102 word(&mut self.s, "[")?;
1103 self.print_expr(element)?;
1104 self.word_space(";")?;
1105 self.ann.nested(self, Nested::Body(count))?;
1106 word(&mut self.s, "]")?;
1110 fn print_expr_struct(&mut self,
1112 fields: &[hir::Field],
1113 wth: &Option<P<hir::Expr>>)
1115 self.print_qpath(qpath, true)?;
1116 word(&mut self.s, "{")?;
1117 self.commasep_cmnt(Consistent,
1120 s.ibox(indent_unit)?;
1121 if !field.is_shorthand {
1122 s.print_name(field.name.node)?;
1125 s.print_expr(&field.expr)?;
1131 self.ibox(indent_unit)?;
1132 if !fields.is_empty() {
1133 word(&mut self.s, ",")?;
1134 space(&mut self.s)?;
1136 word(&mut self.s, "..")?;
1137 self.print_expr(&expr)?;
1140 _ => if !fields.is_empty() {
1141 word(&mut self.s, ",")?
1144 word(&mut self.s, "}")?;
1148 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1150 self.commasep_exprs(Inconsistent, exprs)?;
1151 if exprs.len() == 1 {
1152 word(&mut self.s, ",")?;
1157 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1158 self.print_expr_maybe_paren(func)?;
1159 self.print_call_post(args)
1162 fn print_expr_method_call(&mut self,
1163 name: Spanned<ast::Name>,
1167 let base_args = &args[1..];
1168 self.print_expr(&args[0])?;
1169 word(&mut self.s, ".")?;
1170 self.print_name(name.node)?;
1171 if !tys.is_empty() {
1172 word(&mut self.s, "::<")?;
1173 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1174 word(&mut self.s, ">")?;
1176 self.print_call_post(base_args)
1179 fn print_expr_binary(&mut self,
1184 self.print_expr(lhs)?;
1185 space(&mut self.s)?;
1186 self.word_space(op.node.as_str())?;
1187 self.print_expr(rhs)
1190 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1191 word(&mut self.s, op.as_str())?;
1192 self.print_expr_maybe_paren(expr)
1195 fn print_expr_addr_of(&mut self,
1196 mutability: hir::Mutability,
1199 word(&mut self.s, "&")?;
1200 self.print_mutability(mutability)?;
1201 self.print_expr_maybe_paren(expr)
1204 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1205 self.maybe_print_comment(expr.span.lo)?;
1206 self.print_outer_attributes(&expr.attrs)?;
1207 self.ibox(indent_unit)?;
1208 self.ann.pre(self, NodeExpr(expr))?;
1210 hir::ExprBox(ref expr) => {
1211 self.word_space("box")?;
1212 self.print_expr(expr)?;
1214 hir::ExprArray(ref exprs) => {
1215 self.print_expr_vec(exprs)?;
1217 hir::ExprRepeat(ref element, count) => {
1218 self.print_expr_repeat(&element, count)?;
1220 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1221 self.print_expr_struct(qpath, &fields[..], wth)?;
1223 hir::ExprTup(ref exprs) => {
1224 self.print_expr_tup(exprs)?;
1226 hir::ExprCall(ref func, ref args) => {
1227 self.print_expr_call(&func, args)?;
1229 hir::ExprMethodCall(name, ref tys, ref args) => {
1230 self.print_expr_method_call(name, &tys[..], args)?;
1232 hir::ExprBinary(op, ref lhs, ref rhs) => {
1233 self.print_expr_binary(op, &lhs, &rhs)?;
1235 hir::ExprUnary(op, ref expr) => {
1236 self.print_expr_unary(op, &expr)?;
1238 hir::ExprAddrOf(m, ref expr) => {
1239 self.print_expr_addr_of(m, &expr)?;
1241 hir::ExprLit(ref lit) => {
1242 self.print_literal(&lit)?;
1244 hir::ExprCast(ref expr, ref ty) => {
1245 self.print_expr(&expr)?;
1246 space(&mut self.s)?;
1247 self.word_space("as")?;
1248 self.print_type(&ty)?;
1250 hir::ExprType(ref expr, ref ty) => {
1251 self.print_expr(&expr)?;
1252 self.word_space(":")?;
1253 self.print_type(&ty)?;
1255 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1256 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1258 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1259 if let Some(sp_name) = opt_sp_name {
1260 self.print_name(sp_name.node)?;
1261 self.word_space(":")?;
1263 self.head("while")?;
1264 self.print_expr(&test)?;
1265 space(&mut self.s)?;
1266 self.print_block(&blk)?;
1268 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1269 if let Some(sp_name) = opt_sp_name {
1270 self.print_name(sp_name.node)?;
1271 self.word_space(":")?;
1274 space(&mut self.s)?;
1275 self.print_block(&blk)?;
1277 hir::ExprMatch(ref expr, ref arms, _) => {
1278 self.cbox(indent_unit)?;
1280 self.word_nbsp("match")?;
1281 self.print_expr(&expr)?;
1282 space(&mut self.s)?;
1285 self.print_arm(arm)?;
1287 self.bclose_(expr.span, indent_unit)?;
1289 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span) => {
1290 self.print_capture_clause(capture_clause)?;
1292 self.print_closure_args(&decl, body)?;
1293 space(&mut self.s)?;
1295 // this is a bare expression
1296 self.ann.nested(self, Nested::Body(body))?;
1297 self.end()?; // need to close a box
1299 // a box will be closed by print_expr, but we didn't want an overall
1300 // wrapper so we closed the corresponding opening. so create an
1301 // empty box to satisfy the close.
1304 hir::ExprBlock(ref blk) => {
1305 // containing cbox, will be closed by print-block at }
1306 self.cbox(indent_unit)?;
1307 // head-box, will be closed by print-block after {
1309 self.print_block(&blk)?;
1311 hir::ExprAssign(ref lhs, ref rhs) => {
1312 self.print_expr(&lhs)?;
1313 space(&mut self.s)?;
1314 self.word_space("=")?;
1315 self.print_expr(&rhs)?;
1317 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1318 self.print_expr(&lhs)?;
1319 space(&mut self.s)?;
1320 word(&mut self.s, op.node.as_str())?;
1321 self.word_space("=")?;
1322 self.print_expr(&rhs)?;
1324 hir::ExprField(ref expr, name) => {
1325 self.print_expr(&expr)?;
1326 word(&mut self.s, ".")?;
1327 self.print_name(name.node)?;
1329 hir::ExprTupField(ref expr, id) => {
1330 self.print_expr(&expr)?;
1331 word(&mut self.s, ".")?;
1332 self.print_usize(id.node)?;
1334 hir::ExprIndex(ref expr, ref index) => {
1335 self.print_expr(&expr)?;
1336 word(&mut self.s, "[")?;
1337 self.print_expr(&index)?;
1338 word(&mut self.s, "]")?;
1340 hir::ExprPath(ref qpath) => {
1341 self.print_qpath(qpath, true)?
1343 hir::ExprBreak(opt_label, ref opt_expr) => {
1344 word(&mut self.s, "break")?;
1345 space(&mut self.s)?;
1346 if let Some(label) = opt_label {
1347 self.print_name(label.name)?;
1348 space(&mut self.s)?;
1350 if let Some(ref expr) = *opt_expr {
1351 self.print_expr(expr)?;
1352 space(&mut self.s)?;
1355 hir::ExprAgain(opt_label) => {
1356 word(&mut self.s, "continue")?;
1357 space(&mut self.s)?;
1358 if let Some(label) = opt_label {
1359 self.print_name(label.name)?;
1363 hir::ExprRet(ref result) => {
1364 word(&mut self.s, "return")?;
1367 word(&mut self.s, " ")?;
1368 self.print_expr(&expr)?;
1373 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1374 word(&mut self.s, "asm!")?;
1376 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1377 self.word_space(":")?;
1379 let mut out_idx = 0;
1380 self.commasep(Inconsistent, &a.outputs, |s, out| {
1381 let constraint = out.constraint.as_str();
1382 let mut ch = constraint.chars();
1384 Some('=') if out.is_rw => {
1385 s.print_string(&format!("+{}", ch.as_str()),
1386 ast::StrStyle::Cooked)?
1388 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1391 s.print_expr(&outputs[out_idx])?;
1396 space(&mut self.s)?;
1397 self.word_space(":")?;
1400 self.commasep(Inconsistent, &a.inputs, |s, co| {
1401 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1403 s.print_expr(&inputs[in_idx])?;
1408 space(&mut self.s)?;
1409 self.word_space(":")?;
1411 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1412 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1416 let mut options = vec![];
1418 options.push("volatile");
1421 options.push("alignstack");
1423 if a.dialect == ast::AsmDialect::Intel {
1424 options.push("intel");
1427 if !options.is_empty() {
1428 space(&mut self.s)?;
1429 self.word_space(":")?;
1430 self.commasep(Inconsistent, &options, |s, &co| {
1431 s.print_string(co, ast::StrStyle::Cooked)?;
1439 self.ann.post(self, NodeExpr(expr))?;
1443 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1444 self.print_pat(&loc.pat)?;
1445 if let Some(ref ty) = loc.ty {
1446 self.word_space(":")?;
1447 self.print_type(&ty)?;
1452 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1453 self.maybe_print_comment(decl.span.lo)?;
1455 hir::DeclLocal(ref loc) => {
1456 self.space_if_not_bol()?;
1457 self.ibox(indent_unit)?;
1458 self.word_nbsp("let")?;
1460 self.ibox(indent_unit)?;
1461 self.print_local_decl(&loc)?;
1463 if let Some(ref init) = loc.init {
1465 self.word_space("=")?;
1466 self.print_expr(&init)?;
1470 hir::DeclItem(item) => {
1471 self.ann.nested(self, Nested::Item(item))
1476 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1477 word(&mut self.s, &i.to_string())
1480 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1481 word(&mut self.s, &name.as_str())?;
1482 self.ann.post(self, NodeName(&name))
1485 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1486 self.print_local_decl(loc)?;
1487 space(&mut self.s)?;
1488 self.word_space("in")?;
1489 self.print_expr(coll)
1492 pub fn print_path(&mut self,
1494 colons_before_params: bool)
1496 self.maybe_print_comment(path.span.lo)?;
1498 for (i, segment) in path.segments.iter().enumerate() {
1500 word(&mut self.s, "::")?
1502 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1503 self.print_name(segment.name)?;
1504 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1511 pub fn print_qpath(&mut self,
1513 colons_before_params: bool)
1516 hir::QPath::Resolved(None, ref path) => {
1517 self.print_path(path, colons_before_params)
1519 hir::QPath::Resolved(Some(ref qself), ref path) => {
1520 word(&mut self.s, "<")?;
1521 self.print_type(qself)?;
1522 space(&mut self.s)?;
1523 self.word_space("as")?;
1525 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1527 word(&mut self.s, "::")?
1529 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1530 self.print_name(segment.name)?;
1531 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1535 word(&mut self.s, ">")?;
1536 word(&mut self.s, "::")?;
1537 let item_segment = path.segments.last().unwrap();
1538 self.print_name(item_segment.name)?;
1539 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1541 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1542 word(&mut self.s, "<")?;
1543 self.print_type(qself)?;
1544 word(&mut self.s, ">")?;
1545 word(&mut self.s, "::")?;
1546 self.print_name(item_segment.name)?;
1547 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1552 fn print_path_parameters(&mut self,
1553 parameters: &hir::PathParameters,
1554 colons_before_params: bool)
1556 if parameters.is_empty() {
1557 let infer_types = match *parameters {
1558 hir::AngleBracketedParameters(ref data) => data.infer_types,
1559 hir::ParenthesizedParameters(_) => false
1562 // FIXME(eddyb) See the comment below about infer_types.
1563 if !(infer_types && false) {
1568 if colons_before_params {
1569 word(&mut self.s, "::")?
1573 hir::AngleBracketedParameters(ref data) => {
1574 word(&mut self.s, "<")?;
1576 let mut comma = false;
1577 for lifetime in &data.lifetimes {
1579 self.word_space(",")?
1581 self.print_lifetime(lifetime)?;
1585 if !data.types.is_empty() {
1587 self.word_space(",")?
1589 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1593 // FIXME(eddyb) This would leak into error messages, e.g.:
1594 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1595 if data.infer_types && false {
1597 self.word_space(",")?
1599 word(&mut self.s, "..")?;
1603 for binding in data.bindings.iter() {
1605 self.word_space(",")?
1607 self.print_name(binding.name)?;
1608 space(&mut self.s)?;
1609 self.word_space("=")?;
1610 self.print_type(&binding.ty)?;
1614 word(&mut self.s, ">")?
1617 hir::ParenthesizedParameters(ref data) => {
1618 word(&mut self.s, "(")?;
1619 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1620 word(&mut self.s, ")")?;
1622 if let Some(ref ty) = data.output {
1623 self.space_if_not_bol()?;
1624 self.word_space("->")?;
1625 self.print_type(&ty)?;
1633 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1634 self.maybe_print_comment(pat.span.lo)?;
1635 self.ann.pre(self, NodePat(pat))?;
1636 // Pat isn't normalized, but the beauty of it
1637 // is that it doesn't matter
1639 PatKind::Wild => word(&mut self.s, "_")?,
1640 PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1641 match binding_mode {
1642 hir::BindByRef(mutbl) => {
1643 self.word_nbsp("ref")?;
1644 self.print_mutability(mutbl)?;
1646 hir::BindByValue(hir::MutImmutable) => {}
1647 hir::BindByValue(hir::MutMutable) => {
1648 self.word_nbsp("mut")?;
1651 self.print_name(path1.node)?;
1652 if let Some(ref p) = *sub {
1653 word(&mut self.s, "@")?;
1654 self.print_pat(&p)?;
1657 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1658 self.print_qpath(qpath, true)?;
1660 if let Some(ddpos) = ddpos {
1661 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1663 self.word_space(",")?;
1665 word(&mut self.s, "..")?;
1666 if ddpos != elts.len() {
1667 word(&mut self.s, ",")?;
1668 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1671 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1675 PatKind::Path(ref qpath) => {
1676 self.print_qpath(qpath, true)?;
1678 PatKind::Struct(ref qpath, ref fields, etc) => {
1679 self.print_qpath(qpath, true)?;
1681 self.word_space("{")?;
1682 self.commasep_cmnt(Consistent,
1685 s.cbox(indent_unit)?;
1686 if !f.node.is_shorthand {
1687 s.print_name(f.node.name)?;
1690 s.print_pat(&f.node.pat)?;
1693 |f| f.node.pat.span)?;
1695 if !fields.is_empty() {
1696 self.word_space(",")?;
1698 word(&mut self.s, "..")?;
1700 space(&mut self.s)?;
1701 word(&mut self.s, "}")?;
1703 PatKind::Tuple(ref elts, ddpos) => {
1705 if let Some(ddpos) = ddpos {
1706 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1708 self.word_space(",")?;
1710 word(&mut self.s, "..")?;
1711 if ddpos != elts.len() {
1712 word(&mut self.s, ",")?;
1713 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1716 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1717 if elts.len() == 1 {
1718 word(&mut self.s, ",")?;
1723 PatKind::Box(ref inner) => {
1724 word(&mut self.s, "box ")?;
1725 self.print_pat(&inner)?;
1727 PatKind::Ref(ref inner, mutbl) => {
1728 word(&mut self.s, "&")?;
1729 if mutbl == hir::MutMutable {
1730 word(&mut self.s, "mut ")?;
1732 self.print_pat(&inner)?;
1734 PatKind::Lit(ref e) => self.print_expr(&e)?,
1735 PatKind::Range(ref begin, ref end) => {
1736 self.print_expr(&begin)?;
1737 space(&mut self.s)?;
1738 word(&mut self.s, "...")?;
1739 self.print_expr(&end)?;
1741 PatKind::Slice(ref before, ref slice, ref after) => {
1742 word(&mut self.s, "[")?;
1743 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1744 if let Some(ref p) = *slice {
1745 if !before.is_empty() {
1746 self.word_space(",")?;
1748 if p.node != PatKind::Wild {
1749 self.print_pat(&p)?;
1751 word(&mut self.s, "..")?;
1752 if !after.is_empty() {
1753 self.word_space(",")?;
1756 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1757 word(&mut self.s, "]")?;
1760 self.ann.post(self, NodePat(pat))
1763 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1764 // I have no idea why this check is necessary, but here it
1766 if arm.attrs.is_empty() {
1767 space(&mut self.s)?;
1769 self.cbox(indent_unit)?;
1771 self.print_outer_attributes(&arm.attrs)?;
1772 let mut first = true;
1773 for p in &arm.pats {
1777 space(&mut self.s)?;
1778 self.word_space("|")?;
1780 self.print_pat(&p)?;
1782 space(&mut self.s)?;
1783 if let Some(ref e) = arm.guard {
1784 self.word_space("if")?;
1785 self.print_expr(&e)?;
1786 space(&mut self.s)?;
1788 self.word_space("=>")?;
1790 match arm.body.node {
1791 hir::ExprBlock(ref blk) => {
1792 // the block will close the pattern's ibox
1793 self.print_block_unclosed_indent(&blk, indent_unit)?;
1795 // If it is a user-provided unsafe block, print a comma after it
1796 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1797 word(&mut self.s, ",")?;
1801 self.end()?; // close the ibox for the pattern
1802 self.print_expr(&arm.body)?;
1803 word(&mut self.s, ",")?;
1806 self.end() // close enclosing cbox
1809 pub fn print_fn(&mut self,
1811 unsafety: hir::Unsafety,
1812 constness: hir::Constness,
1814 name: Option<ast::Name>,
1815 generics: &hir::Generics,
1816 vis: &hir::Visibility,
1817 arg_names: &[Spanned<ast::Name>],
1818 body_id: Option<hir::BodyId>)
1820 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1822 if let Some(name) = name {
1824 self.print_name(name)?;
1826 self.print_generics(generics)?;
1830 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1831 assert!(arg_names.is_empty() || body_id.is_none());
1832 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1833 s.ibox(indent_unit)?;
1834 if let Some(name) = arg_names.get(i) {
1835 word(&mut s.s, &name.node.as_str())?;
1836 word(&mut s.s, ":")?;
1838 } else if let Some(body_id) = body_id {
1839 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1840 word(&mut s.s, ":")?;
1848 word(&mut self.s, ", ...")?;
1852 self.print_fn_output(decl)?;
1853 self.print_where_clause(&generics.where_clause)
1856 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1857 word(&mut self.s, "|")?;
1859 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1860 s.ibox(indent_unit)?;
1862 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1865 if ty.node != hir::TyInfer {
1866 word(&mut s.s, ":")?;
1872 word(&mut self.s, "|")?;
1874 if let hir::DefaultReturn(..) = decl.output {
1878 self.space_if_not_bol()?;
1879 self.word_space("->")?;
1881 hir::Return(ref ty) => {
1882 self.print_type(&ty)?;
1883 self.maybe_print_comment(ty.span.lo)
1885 hir::DefaultReturn(..) => unreachable!(),
1889 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1890 match capture_clause {
1891 hir::CaptureByValue => self.word_space("move"),
1892 hir::CaptureByRef => Ok(()),
1896 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1897 if !bounds.is_empty() {
1898 word(&mut self.s, prefix)?;
1899 let mut first = true;
1900 for bound in bounds {
1905 self.word_space("+")?;
1909 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1910 self.print_poly_trait_ref(tref)
1912 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1913 word(&mut self.s, "?")?;
1914 self.print_poly_trait_ref(tref)
1916 RegionTyParamBound(ref lt) => {
1917 self.print_lifetime(lt)
1927 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
1928 self.print_name(lifetime.name)
1931 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
1932 self.print_lifetime(&lifetime.lifetime)?;
1934 for v in &lifetime.bounds {
1935 word(&mut self.s, sep)?;
1936 self.print_lifetime(v)?;
1942 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
1943 let total = generics.lifetimes.len() + generics.ty_params.len();
1948 word(&mut self.s, "<")?;
1950 let mut ints = Vec::new();
1955 self.commasep(Inconsistent, &ints[..], |s, &idx| {
1956 if idx < generics.lifetimes.len() {
1957 let lifetime = &generics.lifetimes[idx];
1958 s.print_lifetime_def(lifetime)
1960 let idx = idx - generics.lifetimes.len();
1961 let param = &generics.ty_params[idx];
1962 s.print_ty_param(param)
1966 word(&mut self.s, ">")?;
1970 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
1971 self.print_name(param.name)?;
1972 self.print_bounds(":", ¶m.bounds)?;
1973 match param.default {
1974 Some(ref default) => {
1975 space(&mut self.s)?;
1976 self.word_space("=")?;
1977 self.print_type(&default)
1983 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
1984 if where_clause.predicates.is_empty() {
1988 space(&mut self.s)?;
1989 self.word_space("where")?;
1991 for (i, predicate) in where_clause.predicates.iter().enumerate() {
1993 self.word_space(",")?;
1997 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2001 self.print_formal_lifetime_list(bound_lifetimes)?;
2002 self.print_type(&bounded_ty)?;
2003 self.print_bounds(":", bounds)?;
2005 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2008 self.print_lifetime(lifetime)?;
2009 word(&mut self.s, ":")?;
2011 for (i, bound) in bounds.iter().enumerate() {
2012 self.print_lifetime(bound)?;
2015 word(&mut self.s, ":")?;
2019 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2022 self.print_type(lhs_ty)?;
2023 space(&mut self.s)?;
2024 self.word_space("=")?;
2025 self.print_type(rhs_ty)?;
2033 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2035 hir::MutMutable => self.word_nbsp("mut"),
2036 hir::MutImmutable => Ok(()),
2040 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2041 self.print_mutability(mt.mutbl)?;
2042 self.print_type(&mt.ty)
2045 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2046 if let hir::DefaultReturn(..) = decl.output {
2050 self.space_if_not_bol()?;
2051 self.ibox(indent_unit)?;
2052 self.word_space("->")?;
2054 hir::DefaultReturn(..) => unreachable!(),
2055 hir::Return(ref ty) => self.print_type(&ty)?,
2060 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2065 pub fn print_ty_fn(&mut self,
2067 unsafety: hir::Unsafety,
2069 name: Option<ast::Name>,
2070 generics: &hir::Generics)
2072 self.ibox(indent_unit)?;
2073 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2074 word(&mut self.s, "for")?;
2075 self.print_generics(generics)?;
2077 let generics = hir::Generics {
2078 lifetimes: hir::HirVec::new(),
2079 ty_params: hir::HirVec::new(),
2080 where_clause: hir::WhereClause {
2081 id: ast::DUMMY_NODE_ID,
2082 predicates: hir::HirVec::new(),
2084 span: syntax_pos::DUMMY_SP,
2088 hir::Constness::NotConst,
2098 pub fn maybe_print_trailing_comment(&mut self,
2099 span: syntax_pos::Span,
2100 next_pos: Option<BytePos>)
2102 let cm = match self.cm {
2106 if let Some(ref cmnt) = self.next_comment() {
2107 if (*cmnt).style != comments::Trailing {
2110 let span_line = cm.lookup_char_pos(span.hi);
2111 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2112 let mut next = (*cmnt).pos + BytePos(1);
2113 if let Some(p) = next_pos {
2116 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2117 span_line.line == comment_line.line {
2118 self.print_comment(cmnt)?;
2119 self.cur_cmnt_and_lit.cur_cmnt += 1;
2125 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2126 // If there aren't any remaining comments, then we need to manually
2127 // make sure there is a line break at the end.
2128 if self.next_comment().is_none() {
2129 hardbreak(&mut self.s)?;
2132 match self.next_comment() {
2134 self.print_comment(cmnt)?;
2135 self.cur_cmnt_and_lit.cur_cmnt += 1;
2143 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2144 opt_abi: Option<Abi>)
2147 Some(Abi::Rust) => Ok(()),
2149 self.word_nbsp("extern")?;
2150 self.word_nbsp(&abi.to_string())
2156 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2159 self.word_nbsp("extern")?;
2160 self.word_nbsp(&abi.to_string())
2166 pub fn print_fn_header_info(&mut self,
2167 unsafety: hir::Unsafety,
2168 constness: hir::Constness,
2170 vis: &hir::Visibility)
2172 word(&mut self.s, &visibility_qualified(vis, ""))?;
2173 self.print_unsafety(unsafety)?;
2176 hir::Constness::NotConst => {}
2177 hir::Constness::Const => self.word_nbsp("const")?,
2180 if abi != Abi::Rust {
2181 self.word_nbsp("extern")?;
2182 self.word_nbsp(&abi.to_string())?;
2185 word(&mut self.s, "fn")
2188 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2190 hir::Unsafety::Normal => Ok(()),
2191 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2196 // Dup'ed from parse::classify, but adapted for the HIR.
2197 /// Does this expression require a semicolon to be treated
2198 /// as a statement? The negation of this: 'can this expression
2199 /// be used as a statement without a semicolon' -- is used
2200 /// as an early-bail-out in the parser so that, for instance,
2201 /// if true {...} else {...}
2203 /// isn't parsed as (if true {...} else {...} | x) | 5
2204 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2207 hir::ExprMatch(..) |
2209 hir::ExprWhile(..) |
2210 hir::ExprLoop(..) => false,
2215 /// this statement requires a semicolon after it.
2216 /// note that in one case (stmt_semi), we've already
2217 /// seen the semicolon, and thus don't need another.
2218 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2220 hir::StmtDecl(ref d, _) => {
2222 hir::DeclLocal(_) => true,
2223 hir::DeclItem(_) => false,
2226 hir::StmtExpr(ref e, _) => {
2227 expr_requires_semi_to_be_stmt(&e)
2229 hir::StmtSemi(..) => {