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::lexer::comments;
17 use syntax::print::pp::{self, break_offset, word, space, hardbreak};
18 use syntax::print::pp::{Breaks, eof};
19 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
20 use syntax::print::pprust::{self as ast_pp, PrintState};
22 use syntax::symbol::keywords;
23 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,
119 span_diagnostic: &errors::Handler,
123 out: Box<Write + 'a>,
127 let mut s = State::new_from_input(cm, span_diagnostic, filename, input,
128 out, ann, is_expanded);
130 // When printing the AST, we sometimes need to inject `#[no_std]` here.
131 // Since you can't compile the HIR, it's not necessary.
133 s.print_mod(&krate.module, &krate.attrs)?;
134 s.print_remaining_comments()?;
139 pub fn new_from_input(cm: &'a CodeMap,
140 span_diagnostic: &errors::Handler,
143 out: Box<Write + 'a>,
147 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
155 // If the code is post expansion, don't use the table of
156 // literals, since it doesn't correspond with the literals
157 // in the AST anymore.
165 pub fn new(cm: &'a CodeMap,
166 out: Box<Write + 'a>,
168 comments: Option<Vec<comments::Comment>>,
169 literals: Option<Vec<comments::Literal>>)
172 s: pp::mk_printer(out, default_columns),
174 comments: comments.clone(),
175 literals: literals.clone(),
176 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
186 pub fn to_string<F>(ann: &PpAnn, f: F) -> String
187 where F: FnOnce(&mut State) -> io::Result<()>
189 let mut wr = Vec::new();
191 let mut printer = State {
192 s: pp::mk_printer(Box::new(&mut wr), default_columns),
196 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
203 f(&mut printer).unwrap();
204 eof(&mut printer.s).unwrap();
206 String::from_utf8(wr).unwrap()
209 pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
210 to_string(NO_ANN, |s| {
211 s.print_visibility(vis)?;
216 fn needs_parentheses(expr: &hir::Expr) -> bool {
218 hir::ExprAssign(..) |
219 hir::ExprBinary(..) |
220 hir::ExprClosure(..) |
221 hir::ExprAssignOp(..) |
223 hir::ExprType(..) => true,
229 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
230 self.boxes.push(pp::Breaks::Consistent);
231 pp::cbox(&mut self.s, u)
234 pub fn nbsp(&mut self) -> io::Result<()> {
235 word(&mut self.s, " ")
238 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
239 word(&mut self.s, w)?;
243 pub fn head(&mut self, w: &str) -> io::Result<()> {
244 // outer-box is consistent
245 self.cbox(indent_unit)?;
246 // head-box is inconsistent
247 self.ibox(w.len() + 1)?;
248 // keyword that starts the head
255 pub fn bopen(&mut self) -> io::Result<()> {
256 word(&mut self.s, "{")?;
257 self.end() // close the head-box
260 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
261 self.bclose_maybe_open(span, indented, true)
263 pub fn bclose_maybe_open(&mut self,
264 span: syntax_pos::Span,
268 self.maybe_print_comment(span.hi)?;
269 self.break_offset_if_not_bol(1, -(indented as isize))?;
270 word(&mut self.s, "}")?;
272 self.end()?; // close the outer-box
276 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
277 self.bclose_(span, indent_unit)
280 pub fn in_cbox(&self) -> bool {
281 match self.boxes.last() {
282 Some(&last_box) => last_box == pp::Breaks::Consistent,
286 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
292 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
294 break_offset(&mut self.s, n, off)
296 if off != 0 && self.s.last_token().is_hardbreak_tok() {
297 // We do something pretty sketchy here: tuck the nonzero
298 // offset-adjustment we were going to deposit along with the
299 // break into the previous hardbreak.
300 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
306 // Synthesizes a comment that was not textually present in the original source
308 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
309 word(&mut self.s, "/*")?;
311 word(&mut self.s, &text[..])?;
313 word(&mut self.s, "*/")
317 pub fn commasep_cmnt<T, F, G>(&mut self,
323 where F: FnMut(&mut State, &T) -> io::Result<()>,
324 G: FnMut(&T) -> syntax_pos::Span
327 let len = elts.len();
330 self.maybe_print_comment(get_span(elt).hi)?;
334 word(&mut self.s, ",")?;
335 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
336 self.space_if_not_bol()?;
342 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
343 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
346 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
347 self.print_inner_attributes(attrs)?;
348 for &item_id in &_mod.item_ids {
349 self.ann.nested(self, Nested::Item(item_id))?;
354 pub fn print_foreign_mod(&mut self,
355 nmod: &hir::ForeignMod,
356 attrs: &[ast::Attribute])
358 self.print_inner_attributes(attrs)?;
359 for item in &nmod.items {
360 self.print_foreign_item(item)?;
365 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
366 if let Some(l) = *lifetime {
367 self.print_lifetime(&l)?;
373 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
374 self.maybe_print_comment(ty.span.lo)?;
377 hir::TySlice(ref ty) => {
378 word(&mut self.s, "[")?;
379 self.print_type(&ty)?;
380 word(&mut self.s, "]")?;
382 hir::TyPtr(ref mt) => {
383 word(&mut self.s, "*")?;
385 hir::MutMutable => self.word_nbsp("mut")?,
386 hir::MutImmutable => self.word_nbsp("const")?,
388 self.print_type(&mt.ty)?;
390 hir::TyRptr(ref lifetime, ref mt) => {
391 word(&mut self.s, "&")?;
392 self.print_opt_lifetime(lifetime)?;
396 word(&mut self.s, "!")?;
398 hir::TyTup(ref elts) => {
400 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
402 word(&mut self.s, ",")?;
406 hir::TyBareFn(ref f) => {
407 let generics = hir::Generics {
408 lifetimes: f.lifetimes.clone(),
409 ty_params: hir::HirVec::new(),
410 where_clause: hir::WhereClause {
411 id: ast::DUMMY_NODE_ID,
412 predicates: hir::HirVec::new(),
414 span: syntax_pos::DUMMY_SP,
416 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
418 hir::TyPath(ref qpath) => {
419 self.print_qpath(qpath, false)?
421 hir::TyObjectSum(ref ty, ref bounds) => {
422 self.print_type(&ty)?;
423 self.print_bounds("+", &bounds[..])?;
425 hir::TyPolyTraitRef(ref bounds) => {
426 self.print_bounds("", &bounds[..])?;
428 hir::TyImplTrait(ref bounds) => {
429 self.print_bounds("impl ", &bounds[..])?;
431 hir::TyArray(ref ty, v) => {
432 word(&mut self.s, "[")?;
433 self.print_type(&ty)?;
434 word(&mut self.s, "; ")?;
435 self.ann.nested(self, Nested::Body(v))?;
436 word(&mut self.s, "]")?;
438 hir::TyTypeof(e) => {
439 word(&mut self.s, "typeof(")?;
440 self.ann.nested(self, Nested::Body(e))?;
441 word(&mut self.s, ")")?;
444 word(&mut self.s, "_")?;
450 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
451 self.hardbreak_if_not_bol()?;
452 self.maybe_print_comment(item.span.lo)?;
453 self.print_outer_attributes(&item.attrs)?;
455 hir::ForeignItemFn(ref decl, ref arg_names, ref generics) => {
458 hir::Unsafety::Normal,
459 hir::Constness::NotConst,
466 self.end()?; // end head-ibox
467 word(&mut self.s, ";")?;
468 self.end() // end the outer fn box
470 hir::ForeignItemStatic(ref t, m) => {
471 self.head(&visibility_qualified(&item.vis, "static"))?;
473 self.word_space("mut")?;
475 self.print_name(item.name)?;
476 self.word_space(":")?;
477 self.print_type(&t)?;
478 word(&mut self.s, ";")?;
479 self.end()?; // end the head-ibox
480 self.end() // end the outer cbox
485 fn print_associated_const(&mut self,
488 default: Option<hir::BodyId>,
489 vis: &hir::Visibility)
491 word(&mut self.s, &visibility_qualified(vis, ""))?;
492 self.word_space("const")?;
493 self.print_name(name)?;
494 self.word_space(":")?;
495 self.print_type(ty)?;
496 if let Some(expr) = default {
498 self.word_space("=")?;
499 self.ann.nested(self, Nested::Body(expr))?;
501 word(&mut self.s, ";")
504 fn print_associated_type(&mut self,
506 bounds: Option<&hir::TyParamBounds>,
507 ty: Option<&hir::Ty>)
509 self.word_space("type")?;
510 self.print_name(name)?;
511 if let Some(bounds) = bounds {
512 self.print_bounds(":", bounds)?;
514 if let Some(ty) = ty {
516 self.word_space("=")?;
517 self.print_type(ty)?;
519 word(&mut self.s, ";")
522 /// Pretty-print an item
523 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
524 self.hardbreak_if_not_bol()?;
525 self.maybe_print_comment(item.span.lo)?;
526 self.print_outer_attributes(&item.attrs)?;
527 self.ann.pre(self, NodeItem(item))?;
529 hir::ItemExternCrate(ref optional_path) => {
530 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
531 if let Some(p) = *optional_path {
532 let val = p.as_str();
533 if val.contains("-") {
534 self.print_string(&val, ast::StrStyle::Cooked)?;
539 word(&mut self.s, "as")?;
542 self.print_name(item.name)?;
543 word(&mut self.s, ";")?;
544 self.end()?; // end inner head-block
545 self.end()?; // end outer head-block
547 hir::ItemUse(ref path, kind) => {
548 self.head(&visibility_qualified(&item.vis, "use"))?;
549 self.print_path(path, false)?;
552 hir::UseKind::Single => {
553 if path.segments.last().unwrap().name != item.name {
555 self.word_space("as")?;
556 self.print_name(item.name)?;
558 word(&mut self.s, ";")?;
560 hir::UseKind::Glob => word(&mut self.s, "::*;")?,
561 hir::UseKind::ListStem => word(&mut self.s, "::{};")?
563 self.end()?; // end inner head-block
564 self.end()?; // end outer head-block
566 hir::ItemStatic(ref ty, m, expr) => {
567 self.head(&visibility_qualified(&item.vis, "static"))?;
568 if m == hir::MutMutable {
569 self.word_space("mut")?;
571 self.print_name(item.name)?;
572 self.word_space(":")?;
573 self.print_type(&ty)?;
575 self.end()?; // end the head-ibox
577 self.word_space("=")?;
578 self.ann.nested(self, Nested::Body(expr))?;
579 word(&mut self.s, ";")?;
580 self.end()?; // end the outer cbox
582 hir::ItemConst(ref ty, expr) => {
583 self.head(&visibility_qualified(&item.vis, "const"))?;
584 self.print_name(item.name)?;
585 self.word_space(":")?;
586 self.print_type(&ty)?;
588 self.end()?; // end the head-ibox
590 self.word_space("=")?;
591 self.ann.nested(self, Nested::Body(expr))?;
592 word(&mut self.s, ";")?;
593 self.end()?; // end the outer cbox
595 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, body) => {
606 word(&mut self.s, " ")?;
607 self.end()?; // need to close a box
608 self.end()?; // need to close a box
609 self.ann.nested(self, Nested::Body(body))?;
611 hir::ItemMod(ref _mod) => {
612 self.head(&visibility_qualified(&item.vis, "mod"))?;
613 self.print_name(item.name)?;
616 self.print_mod(_mod, &item.attrs)?;
617 self.bclose(item.span)?;
619 hir::ItemForeignMod(ref nmod) => {
620 self.head("extern")?;
621 self.word_nbsp(&nmod.abi.to_string())?;
623 self.print_foreign_mod(nmod, &item.attrs)?;
624 self.bclose(item.span)?;
626 hir::ItemTy(ref ty, ref params) => {
627 self.ibox(indent_unit)?;
629 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
630 self.print_name(item.name)?;
631 self.print_generics(params)?;
632 self.end()?; // end the inner ibox
634 self.print_where_clause(¶ms.where_clause)?;
636 self.word_space("=")?;
637 self.print_type(&ty)?;
638 word(&mut self.s, ";")?;
639 self.end()?; // end the outer ibox
641 hir::ItemEnum(ref enum_definition, ref params) => {
642 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
644 hir::ItemStruct(ref struct_def, ref generics) => {
645 self.head(&visibility_qualified(&item.vis, "struct"))?;
646 self.print_struct(struct_def, generics, item.name, item.span, true)?;
648 hir::ItemUnion(ref struct_def, ref generics) => {
649 self.head(&visibility_qualified(&item.vis, "union"))?;
650 self.print_struct(struct_def, generics, item.name, item.span, true)?;
652 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
654 self.print_visibility(&item.vis)?;
655 self.print_unsafety(unsafety)?;
656 self.word_nbsp("impl")?;
657 self.print_trait_ref(trait_ref)?;
659 self.word_space("for")?;
660 self.word_space("..")?;
662 self.bclose(item.span)?;
664 hir::ItemImpl(unsafety,
671 self.print_visibility(&item.vis)?;
672 self.print_unsafety(unsafety)?;
673 self.word_nbsp("impl")?;
675 if generics.is_parameterized() {
676 self.print_generics(generics)?;
681 hir::ImplPolarity::Negative => {
682 word(&mut self.s, "!")?;
689 self.print_trait_ref(t)?;
691 self.word_space("for")?;
696 self.print_type(&ty)?;
697 self.print_where_clause(&generics.where_clause)?;
701 self.print_inner_attributes(&item.attrs)?;
702 for impl_item in impl_items {
703 self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
705 self.bclose(item.span)?;
707 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
709 self.print_visibility(&item.vis)?;
710 self.print_unsafety(unsafety)?;
711 self.word_nbsp("trait")?;
712 self.print_name(item.name)?;
713 self.print_generics(generics)?;
714 let mut real_bounds = Vec::with_capacity(bounds.len());
715 for b in bounds.iter() {
716 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
718 self.word_space("for ?")?;
719 self.print_trait_ref(&ptr.trait_ref)?;
721 real_bounds.push(b.clone());
724 self.print_bounds(":", &real_bounds[..])?;
725 self.print_where_clause(&generics.where_clause)?;
726 word(&mut self.s, " ")?;
728 for trait_item in trait_items {
729 self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
731 self.bclose(item.span)?;
734 self.ann.post(self, NodeItem(item))
737 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
738 self.print_path(&t.path, false)
741 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
742 if !lifetimes.is_empty() {
743 word(&mut self.s, "for<")?;
744 let mut comma = false;
745 for lifetime_def in lifetimes {
747 self.word_space(",")?
749 self.print_lifetime_def(lifetime_def)?;
752 word(&mut self.s, ">")?;
757 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
758 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
759 self.print_trait_ref(&t.trait_ref)
762 pub fn print_enum_def(&mut self,
763 enum_definition: &hir::EnumDef,
764 generics: &hir::Generics,
766 span: syntax_pos::Span,
767 visibility: &hir::Visibility)
769 self.head(&visibility_qualified(visibility, "enum"))?;
770 self.print_name(name)?;
771 self.print_generics(generics)?;
772 self.print_where_clause(&generics.where_clause)?;
774 self.print_variants(&enum_definition.variants, span)
777 pub fn print_variants(&mut self,
778 variants: &[hir::Variant],
779 span: syntax_pos::Span)
783 self.space_if_not_bol()?;
784 self.maybe_print_comment(v.span.lo)?;
785 self.print_outer_attributes(&v.node.attrs)?;
786 self.ibox(indent_unit)?;
787 self.print_variant(v)?;
788 word(&mut self.s, ",")?;
790 self.maybe_print_trailing_comment(v.span, None)?;
795 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
797 hir::Public => self.word_nbsp("pub"),
798 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
799 hir::Visibility::Restricted { ref path, .. } => {
800 word(&mut self.s, "pub(")?;
801 self.print_path(path, false)?;
804 hir::Inherited => Ok(()),
808 pub fn print_struct(&mut self,
809 struct_def: &hir::VariantData,
810 generics: &hir::Generics,
812 span: syntax_pos::Span,
813 print_finalizer: bool)
815 self.print_name(name)?;
816 self.print_generics(generics)?;
817 if !struct_def.is_struct() {
818 if struct_def.is_tuple() {
820 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
821 s.maybe_print_comment(field.span.lo)?;
822 s.print_outer_attributes(&field.attrs)?;
823 s.print_visibility(&field.vis)?;
824 s.print_type(&field.ty)
828 self.print_where_clause(&generics.where_clause)?;
830 word(&mut self.s, ";")?;
833 self.end() // close the outer-box
835 self.print_where_clause(&generics.where_clause)?;
838 self.hardbreak_if_not_bol()?;
840 for field in struct_def.fields() {
841 self.hardbreak_if_not_bol()?;
842 self.maybe_print_comment(field.span.lo)?;
843 self.print_outer_attributes(&field.attrs)?;
844 self.print_visibility(&field.vis)?;
845 self.print_name(field.name)?;
846 self.word_nbsp(":")?;
847 self.print_type(&field.ty)?;
848 word(&mut self.s, ",")?;
855 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
857 let generics = hir::Generics::empty();
858 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
859 if let Some(d) = v.node.disr_expr {
861 self.word_space("=")?;
862 self.ann.nested(self, Nested::Body(d))?;
866 pub fn print_method_sig(&mut self,
869 vis: &hir::Visibility,
870 arg_names: &[Spanned<ast::Name>],
871 body_id: Option<hir::BodyId>)
873 self.print_fn(&m.decl,
884 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
885 self.ann.pre(self, NodeSubItem(ti.id))?;
886 self.hardbreak_if_not_bol()?;
887 self.maybe_print_comment(ti.span.lo)?;
888 self.print_outer_attributes(&ti.attrs)?;
890 hir::TraitItemKind::Const(ref ty, default) => {
891 self.print_associated_const(ti.name, &ty, default, &hir::Inherited)?;
893 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
894 self.print_method_sig(ti.name, sig, &hir::Inherited, arg_names, None)?;
895 word(&mut self.s, ";")?;
897 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
899 self.print_method_sig(ti.name, sig, &hir::Inherited, &[], Some(body))?;
901 self.end()?; // need to close a box
902 self.end()?; // need to close a box
903 self.ann.nested(self, Nested::Body(body))?;
905 hir::TraitItemKind::Type(ref bounds, ref default) => {
906 self.print_associated_type(ti.name,
908 default.as_ref().map(|ty| &**ty))?;
911 self.ann.post(self, NodeSubItem(ti.id))
914 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
915 self.ann.pre(self, NodeSubItem(ii.id))?;
916 self.hardbreak_if_not_bol()?;
917 self.maybe_print_comment(ii.span.lo)?;
918 self.print_outer_attributes(&ii.attrs)?;
920 match ii.defaultness {
921 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
922 hir::Defaultness::Final => (),
926 hir::ImplItemKind::Const(ref ty, expr) => {
927 self.print_associated_const(ii.name, &ty, Some(expr), &ii.vis)?;
929 hir::ImplItemKind::Method(ref sig, body) => {
931 self.print_method_sig(ii.name, sig, &ii.vis, &[], Some(body))?;
933 self.end()?; // need to close a box
934 self.end()?; // need to close a box
935 self.ann.nested(self, Nested::Body(body))?;
937 hir::ImplItemKind::Type(ref ty) => {
938 self.print_associated_type(ii.name, None, Some(ty))?;
941 self.ann.post(self, NodeSubItem(ii.id))
944 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
945 self.maybe_print_comment(st.span.lo)?;
947 hir::StmtDecl(ref decl, _) => {
948 self.print_decl(&decl)?;
950 hir::StmtExpr(ref expr, _) => {
951 self.space_if_not_bol()?;
952 self.print_expr(&expr)?;
954 hir::StmtSemi(ref expr, _) => {
955 self.space_if_not_bol()?;
956 self.print_expr(&expr)?;
957 word(&mut self.s, ";")?;
960 if stmt_ends_with_semi(&st.node) {
961 word(&mut self.s, ";")?;
963 self.maybe_print_trailing_comment(st.span, None)
966 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
967 self.print_block_with_attrs(blk, &[])
970 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
971 self.print_block_unclosed_indent(blk, indent_unit)
974 pub fn print_block_unclosed_indent(&mut self,
978 self.print_block_maybe_unclosed(blk, indented, &[], false)
981 pub fn print_block_with_attrs(&mut self,
983 attrs: &[ast::Attribute])
985 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
988 pub fn print_block_maybe_unclosed(&mut self,
991 attrs: &[ast::Attribute],
995 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
996 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
997 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
998 hir::DefaultBlock => (),
1000 self.maybe_print_comment(blk.span.lo)?;
1001 self.ann.pre(self, NodeBlock(blk))?;
1004 self.print_inner_attributes(attrs)?;
1006 for st in &blk.stmts {
1007 self.print_stmt(st)?;
1011 self.space_if_not_bol()?;
1012 self.print_expr(&expr)?;
1013 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1017 self.bclose_maybe_open(blk.span, indented, close_box)?;
1018 self.ann.post(self, NodeBlock(blk))
1021 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1025 // "another else-if"
1026 hir::ExprIf(ref i, ref then, ref e) => {
1027 self.cbox(indent_unit - 1)?;
1029 word(&mut self.s, " else if ")?;
1030 self.print_expr(&i)?;
1031 space(&mut self.s)?;
1032 self.print_block(&then)?;
1033 self.print_else(e.as_ref().map(|e| &**e))
1036 hir::ExprBlock(ref b) => {
1037 self.cbox(indent_unit - 1)?;
1039 word(&mut self.s, " else ")?;
1040 self.print_block(&b)
1042 // BLEAH, constraints would be great here
1044 panic!("print_if saw if with weird alternative");
1052 pub fn print_if(&mut self,
1055 elseopt: Option<&hir::Expr>)
1058 self.print_expr(test)?;
1059 space(&mut self.s)?;
1060 self.print_block(blk)?;
1061 self.print_else(elseopt)
1064 pub fn print_if_let(&mut self,
1068 elseopt: Option<&hir::Expr>)
1070 self.head("if let")?;
1071 self.print_pat(pat)?;
1072 space(&mut self.s)?;
1073 self.word_space("=")?;
1074 self.print_expr(expr)?;
1075 space(&mut self.s)?;
1076 self.print_block(blk)?;
1077 self.print_else(elseopt)
1081 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1083 self.commasep_exprs(Inconsistent, args)?;
1087 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1088 let needs_par = needs_parentheses(expr);
1092 self.print_expr(expr)?;
1099 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1100 self.ibox(indent_unit)?;
1101 word(&mut self.s, "[")?;
1102 self.commasep_exprs(Inconsistent, exprs)?;
1103 word(&mut self.s, "]")?;
1107 fn print_expr_repeat(&mut self, element: &hir::Expr, count: hir::BodyId) -> io::Result<()> {
1108 self.ibox(indent_unit)?;
1109 word(&mut self.s, "[")?;
1110 self.print_expr(element)?;
1111 self.word_space(";")?;
1112 self.ann.nested(self, Nested::Body(count))?;
1113 word(&mut self.s, "]")?;
1117 fn print_expr_struct(&mut self,
1119 fields: &[hir::Field],
1120 wth: &Option<P<hir::Expr>>)
1122 self.print_qpath(qpath, true)?;
1123 word(&mut self.s, "{")?;
1124 self.commasep_cmnt(Consistent,
1127 s.ibox(indent_unit)?;
1128 if !field.is_shorthand {
1129 s.print_name(field.name.node)?;
1132 s.print_expr(&field.expr)?;
1138 self.ibox(indent_unit)?;
1139 if !fields.is_empty() {
1140 word(&mut self.s, ",")?;
1141 space(&mut self.s)?;
1143 word(&mut self.s, "..")?;
1144 self.print_expr(&expr)?;
1147 _ => if !fields.is_empty() {
1148 word(&mut self.s, ",")?
1151 word(&mut self.s, "}")?;
1155 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1157 self.commasep_exprs(Inconsistent, exprs)?;
1158 if exprs.len() == 1 {
1159 word(&mut self.s, ",")?;
1164 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1165 self.print_expr_maybe_paren(func)?;
1166 self.print_call_post(args)
1169 fn print_expr_method_call(&mut self,
1170 name: Spanned<ast::Name>,
1174 let base_args = &args[1..];
1175 self.print_expr(&args[0])?;
1176 word(&mut self.s, ".")?;
1177 self.print_name(name.node)?;
1178 if !tys.is_empty() {
1179 word(&mut self.s, "::<")?;
1180 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1181 word(&mut self.s, ">")?;
1183 self.print_call_post(base_args)
1186 fn print_expr_binary(&mut self,
1191 self.print_expr(lhs)?;
1192 space(&mut self.s)?;
1193 self.word_space(op.node.as_str())?;
1194 self.print_expr(rhs)
1197 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1198 word(&mut self.s, op.as_str())?;
1199 self.print_expr_maybe_paren(expr)
1202 fn print_expr_addr_of(&mut self,
1203 mutability: hir::Mutability,
1206 word(&mut self.s, "&")?;
1207 self.print_mutability(mutability)?;
1208 self.print_expr_maybe_paren(expr)
1211 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1212 self.maybe_print_comment(expr.span.lo)?;
1213 self.print_outer_attributes(&expr.attrs)?;
1214 self.ibox(indent_unit)?;
1215 self.ann.pre(self, NodeExpr(expr))?;
1217 hir::ExprBox(ref expr) => {
1218 self.word_space("box")?;
1219 self.print_expr(expr)?;
1221 hir::ExprArray(ref exprs) => {
1222 self.print_expr_vec(exprs)?;
1224 hir::ExprRepeat(ref element, count) => {
1225 self.print_expr_repeat(&element, count)?;
1227 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1228 self.print_expr_struct(qpath, &fields[..], wth)?;
1230 hir::ExprTup(ref exprs) => {
1231 self.print_expr_tup(exprs)?;
1233 hir::ExprCall(ref func, ref args) => {
1234 self.print_expr_call(&func, args)?;
1236 hir::ExprMethodCall(name, ref tys, ref args) => {
1237 self.print_expr_method_call(name, &tys[..], args)?;
1239 hir::ExprBinary(op, ref lhs, ref rhs) => {
1240 self.print_expr_binary(op, &lhs, &rhs)?;
1242 hir::ExprUnary(op, ref expr) => {
1243 self.print_expr_unary(op, &expr)?;
1245 hir::ExprAddrOf(m, ref expr) => {
1246 self.print_expr_addr_of(m, &expr)?;
1248 hir::ExprLit(ref lit) => {
1249 self.print_literal(&lit)?;
1251 hir::ExprCast(ref expr, ref ty) => {
1252 self.print_expr(&expr)?;
1253 space(&mut self.s)?;
1254 self.word_space("as")?;
1255 self.print_type(&ty)?;
1257 hir::ExprType(ref expr, ref ty) => {
1258 self.print_expr(&expr)?;
1259 self.word_space(":")?;
1260 self.print_type(&ty)?;
1262 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1263 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1265 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1266 if let Some(sp_name) = opt_sp_name {
1267 self.print_name(sp_name.node)?;
1268 self.word_space(":")?;
1270 self.head("while")?;
1271 self.print_expr(&test)?;
1272 space(&mut self.s)?;
1273 self.print_block(&blk)?;
1275 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1276 if let Some(sp_name) = opt_sp_name {
1277 self.print_name(sp_name.node)?;
1278 self.word_space(":")?;
1281 space(&mut self.s)?;
1282 self.print_block(&blk)?;
1284 hir::ExprMatch(ref expr, ref arms, _) => {
1285 self.cbox(indent_unit)?;
1287 self.word_nbsp("match")?;
1288 self.print_expr(&expr)?;
1289 space(&mut self.s)?;
1292 self.print_arm(arm)?;
1294 self.bclose_(expr.span, indent_unit)?;
1296 hir::ExprClosure(capture_clause, ref decl, body, _fn_decl_span) => {
1297 self.print_capture_clause(capture_clause)?;
1299 self.print_closure_args(&decl, body)?;
1300 space(&mut self.s)?;
1302 // this is a bare expression
1303 self.ann.nested(self, Nested::Body(body))?;
1304 self.end()?; // need to close a box
1306 // a box will be closed by print_expr, but we didn't want an overall
1307 // wrapper so we closed the corresponding opening. so create an
1308 // empty box to satisfy the close.
1311 hir::ExprBlock(ref blk) => {
1312 // containing cbox, will be closed by print-block at }
1313 self.cbox(indent_unit)?;
1314 // head-box, will be closed by print-block after {
1316 self.print_block(&blk)?;
1318 hir::ExprAssign(ref lhs, ref rhs) => {
1319 self.print_expr(&lhs)?;
1320 space(&mut self.s)?;
1321 self.word_space("=")?;
1322 self.print_expr(&rhs)?;
1324 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1325 self.print_expr(&lhs)?;
1326 space(&mut self.s)?;
1327 word(&mut self.s, op.node.as_str())?;
1328 self.word_space("=")?;
1329 self.print_expr(&rhs)?;
1331 hir::ExprField(ref expr, name) => {
1332 self.print_expr(&expr)?;
1333 word(&mut self.s, ".")?;
1334 self.print_name(name.node)?;
1336 hir::ExprTupField(ref expr, id) => {
1337 self.print_expr(&expr)?;
1338 word(&mut self.s, ".")?;
1339 self.print_usize(id.node)?;
1341 hir::ExprIndex(ref expr, ref index) => {
1342 self.print_expr(&expr)?;
1343 word(&mut self.s, "[")?;
1344 self.print_expr(&index)?;
1345 word(&mut self.s, "]")?;
1347 hir::ExprPath(ref qpath) => {
1348 self.print_qpath(qpath, true)?
1350 hir::ExprBreak(opt_label, ref opt_expr) => {
1351 word(&mut self.s, "break")?;
1352 space(&mut self.s)?;
1353 if let Some(label) = opt_label {
1354 self.print_name(label.name)?;
1355 space(&mut self.s)?;
1357 if let Some(ref expr) = *opt_expr {
1358 self.print_expr(expr)?;
1359 space(&mut self.s)?;
1362 hir::ExprAgain(opt_label) => {
1363 word(&mut self.s, "continue")?;
1364 space(&mut self.s)?;
1365 if let Some(label) = opt_label {
1366 self.print_name(label.name)?;
1370 hir::ExprRet(ref result) => {
1371 word(&mut self.s, "return")?;
1374 word(&mut self.s, " ")?;
1375 self.print_expr(&expr)?;
1380 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1381 word(&mut self.s, "asm!")?;
1383 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1384 self.word_space(":")?;
1386 let mut out_idx = 0;
1387 self.commasep(Inconsistent, &a.outputs, |s, out| {
1388 let constraint = out.constraint.as_str();
1389 let mut ch = constraint.chars();
1391 Some('=') if out.is_rw => {
1392 s.print_string(&format!("+{}", ch.as_str()),
1393 ast::StrStyle::Cooked)?
1395 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1398 s.print_expr(&outputs[out_idx])?;
1403 space(&mut self.s)?;
1404 self.word_space(":")?;
1407 self.commasep(Inconsistent, &a.inputs, |s, co| {
1408 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1410 s.print_expr(&inputs[in_idx])?;
1415 space(&mut self.s)?;
1416 self.word_space(":")?;
1418 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1419 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1423 let mut options = vec![];
1425 options.push("volatile");
1428 options.push("alignstack");
1430 if a.dialect == ast::AsmDialect::Intel {
1431 options.push("intel");
1434 if !options.is_empty() {
1435 space(&mut self.s)?;
1436 self.word_space(":")?;
1437 self.commasep(Inconsistent, &options, |s, &co| {
1438 s.print_string(co, ast::StrStyle::Cooked)?;
1446 self.ann.post(self, NodeExpr(expr))?;
1450 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1451 self.print_pat(&loc.pat)?;
1452 if let Some(ref ty) = loc.ty {
1453 self.word_space(":")?;
1454 self.print_type(&ty)?;
1459 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1460 self.maybe_print_comment(decl.span.lo)?;
1462 hir::DeclLocal(ref loc) => {
1463 self.space_if_not_bol()?;
1464 self.ibox(indent_unit)?;
1465 self.word_nbsp("let")?;
1467 self.ibox(indent_unit)?;
1468 self.print_local_decl(&loc)?;
1470 if let Some(ref init) = loc.init {
1472 self.word_space("=")?;
1473 self.print_expr(&init)?;
1477 hir::DeclItem(item) => {
1478 self.ann.nested(self, Nested::Item(item))
1483 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1484 word(&mut self.s, &i.to_string())
1487 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1488 word(&mut self.s, &name.as_str())?;
1489 self.ann.post(self, NodeName(&name))
1492 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1493 self.print_local_decl(loc)?;
1494 space(&mut self.s)?;
1495 self.word_space("in")?;
1496 self.print_expr(coll)
1499 pub fn print_path(&mut self,
1501 colons_before_params: bool)
1503 self.maybe_print_comment(path.span.lo)?;
1505 for (i, segment) in path.segments.iter().enumerate() {
1507 word(&mut self.s, "::")?
1509 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1510 self.print_name(segment.name)?;
1511 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1518 pub fn print_qpath(&mut self,
1520 colons_before_params: bool)
1523 hir::QPath::Resolved(None, ref path) => {
1524 self.print_path(path, colons_before_params)
1526 hir::QPath::Resolved(Some(ref qself), ref path) => {
1527 word(&mut self.s, "<")?;
1528 self.print_type(qself)?;
1529 space(&mut self.s)?;
1530 self.word_space("as")?;
1532 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1534 word(&mut self.s, "::")?
1536 if segment.name != keywords::CrateRoot.name() && segment.name != "$crate" {
1537 self.print_name(segment.name)?;
1538 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1542 word(&mut self.s, ">")?;
1543 word(&mut self.s, "::")?;
1544 let item_segment = path.segments.last().unwrap();
1545 self.print_name(item_segment.name)?;
1546 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1548 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1549 word(&mut self.s, "<")?;
1550 self.print_type(qself)?;
1551 word(&mut self.s, ">")?;
1552 word(&mut self.s, "::")?;
1553 self.print_name(item_segment.name)?;
1554 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1559 fn print_path_parameters(&mut self,
1560 parameters: &hir::PathParameters,
1561 colons_before_params: bool)
1563 if parameters.is_empty() {
1564 let infer_types = match *parameters {
1565 hir::AngleBracketedParameters(ref data) => data.infer_types,
1566 hir::ParenthesizedParameters(_) => false
1569 // FIXME(eddyb) See the comment below about infer_types.
1570 if !(infer_types && false) {
1575 if colons_before_params {
1576 word(&mut self.s, "::")?
1580 hir::AngleBracketedParameters(ref data) => {
1581 word(&mut self.s, "<")?;
1583 let mut comma = false;
1584 for lifetime in &data.lifetimes {
1586 self.word_space(",")?
1588 self.print_lifetime(lifetime)?;
1592 if !data.types.is_empty() {
1594 self.word_space(",")?
1596 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1600 // FIXME(eddyb) This would leak into error messages, e.g.:
1601 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1602 if data.infer_types && false {
1604 self.word_space(",")?
1606 word(&mut self.s, "..")?;
1610 for binding in data.bindings.iter() {
1612 self.word_space(",")?
1614 self.print_name(binding.name)?;
1615 space(&mut self.s)?;
1616 self.word_space("=")?;
1617 self.print_type(&binding.ty)?;
1621 word(&mut self.s, ">")?
1624 hir::ParenthesizedParameters(ref data) => {
1625 word(&mut self.s, "(")?;
1626 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1627 word(&mut self.s, ")")?;
1629 if let Some(ref ty) = data.output {
1630 self.space_if_not_bol()?;
1631 self.word_space("->")?;
1632 self.print_type(&ty)?;
1640 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1641 self.maybe_print_comment(pat.span.lo)?;
1642 self.ann.pre(self, NodePat(pat))?;
1643 // Pat isn't normalized, but the beauty of it
1644 // is that it doesn't matter
1646 PatKind::Wild => word(&mut self.s, "_")?,
1647 PatKind::Binding(binding_mode, _, ref path1, ref sub) => {
1648 match binding_mode {
1649 hir::BindByRef(mutbl) => {
1650 self.word_nbsp("ref")?;
1651 self.print_mutability(mutbl)?;
1653 hir::BindByValue(hir::MutImmutable) => {}
1654 hir::BindByValue(hir::MutMutable) => {
1655 self.word_nbsp("mut")?;
1658 self.print_name(path1.node)?;
1659 if let Some(ref p) = *sub {
1660 word(&mut self.s, "@")?;
1661 self.print_pat(&p)?;
1664 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1665 self.print_qpath(qpath, true)?;
1667 if let Some(ddpos) = ddpos {
1668 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1670 self.word_space(",")?;
1672 word(&mut self.s, "..")?;
1673 if ddpos != elts.len() {
1674 word(&mut self.s, ",")?;
1675 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1678 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1682 PatKind::Path(ref qpath) => {
1683 self.print_qpath(qpath, true)?;
1685 PatKind::Struct(ref qpath, ref fields, etc) => {
1686 self.print_qpath(qpath, true)?;
1688 self.word_space("{")?;
1689 self.commasep_cmnt(Consistent,
1692 s.cbox(indent_unit)?;
1693 if !f.node.is_shorthand {
1694 s.print_name(f.node.name)?;
1697 s.print_pat(&f.node.pat)?;
1700 |f| f.node.pat.span)?;
1702 if !fields.is_empty() {
1703 self.word_space(",")?;
1705 word(&mut self.s, "..")?;
1707 space(&mut self.s)?;
1708 word(&mut self.s, "}")?;
1710 PatKind::Tuple(ref elts, ddpos) => {
1712 if let Some(ddpos) = ddpos {
1713 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1715 self.word_space(",")?;
1717 word(&mut self.s, "..")?;
1718 if ddpos != elts.len() {
1719 word(&mut self.s, ",")?;
1720 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1723 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1724 if elts.len() == 1 {
1725 word(&mut self.s, ",")?;
1730 PatKind::Box(ref inner) => {
1731 word(&mut self.s, "box ")?;
1732 self.print_pat(&inner)?;
1734 PatKind::Ref(ref inner, mutbl) => {
1735 word(&mut self.s, "&")?;
1736 if mutbl == hir::MutMutable {
1737 word(&mut self.s, "mut ")?;
1739 self.print_pat(&inner)?;
1741 PatKind::Lit(ref e) => self.print_expr(&e)?,
1742 PatKind::Range(ref begin, ref end) => {
1743 self.print_expr(&begin)?;
1744 space(&mut self.s)?;
1745 word(&mut self.s, "...")?;
1746 self.print_expr(&end)?;
1748 PatKind::Slice(ref before, ref slice, ref after) => {
1749 word(&mut self.s, "[")?;
1750 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1751 if let Some(ref p) = *slice {
1752 if !before.is_empty() {
1753 self.word_space(",")?;
1755 if p.node != PatKind::Wild {
1756 self.print_pat(&p)?;
1758 word(&mut self.s, "..")?;
1759 if !after.is_empty() {
1760 self.word_space(",")?;
1763 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1764 word(&mut self.s, "]")?;
1767 self.ann.post(self, NodePat(pat))
1770 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1771 // I have no idea why this check is necessary, but here it
1773 if arm.attrs.is_empty() {
1774 space(&mut self.s)?;
1776 self.cbox(indent_unit)?;
1778 self.print_outer_attributes(&arm.attrs)?;
1779 let mut first = true;
1780 for p in &arm.pats {
1784 space(&mut self.s)?;
1785 self.word_space("|")?;
1787 self.print_pat(&p)?;
1789 space(&mut self.s)?;
1790 if let Some(ref e) = arm.guard {
1791 self.word_space("if")?;
1792 self.print_expr(&e)?;
1793 space(&mut self.s)?;
1795 self.word_space("=>")?;
1797 match arm.body.node {
1798 hir::ExprBlock(ref blk) => {
1799 // the block will close the pattern's ibox
1800 self.print_block_unclosed_indent(&blk, indent_unit)?;
1802 // If it is a user-provided unsafe block, print a comma after it
1803 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1804 word(&mut self.s, ",")?;
1808 self.end()?; // close the ibox for the pattern
1809 self.print_expr(&arm.body)?;
1810 word(&mut self.s, ",")?;
1813 self.end() // close enclosing cbox
1816 pub fn print_fn(&mut self,
1818 unsafety: hir::Unsafety,
1819 constness: hir::Constness,
1821 name: Option<ast::Name>,
1822 generics: &hir::Generics,
1823 vis: &hir::Visibility,
1824 arg_names: &[Spanned<ast::Name>],
1825 body_id: Option<hir::BodyId>)
1827 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1829 if let Some(name) = name {
1831 self.print_name(name)?;
1833 self.print_generics(generics)?;
1837 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1838 assert!(arg_names.is_empty() || body_id.is_none());
1839 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1840 s.ibox(indent_unit)?;
1841 if let Some(name) = arg_names.get(i) {
1842 word(&mut s.s, &name.node.as_str())?;
1843 word(&mut s.s, ":")?;
1845 } else if let Some(body_id) = body_id {
1846 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1847 word(&mut s.s, ":")?;
1855 word(&mut self.s, ", ...")?;
1859 self.print_fn_output(decl)?;
1860 self.print_where_clause(&generics.where_clause)
1863 fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
1864 word(&mut self.s, "|")?;
1866 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1867 s.ibox(indent_unit)?;
1869 s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
1872 if ty.node != hir::TyInfer {
1873 word(&mut s.s, ":")?;
1879 word(&mut self.s, "|")?;
1881 if let hir::DefaultReturn(..) = decl.output {
1885 self.space_if_not_bol()?;
1886 self.word_space("->")?;
1888 hir::Return(ref ty) => {
1889 self.print_type(&ty)?;
1890 self.maybe_print_comment(ty.span.lo)
1892 hir::DefaultReturn(..) => unreachable!(),
1896 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1897 match capture_clause {
1898 hir::CaptureByValue => self.word_space("move"),
1899 hir::CaptureByRef => Ok(()),
1903 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1904 if !bounds.is_empty() {
1905 word(&mut self.s, prefix)?;
1906 let mut first = true;
1907 for bound in bounds {
1912 self.word_space("+")?;
1916 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1917 self.print_poly_trait_ref(tref)
1919 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1920 word(&mut self.s, "?")?;
1921 self.print_poly_trait_ref(tref)
1923 RegionTyParamBound(ref lt) => {
1924 self.print_lifetime(lt)
1934 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
1935 self.print_name(lifetime.name)
1938 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
1939 self.print_lifetime(&lifetime.lifetime)?;
1941 for v in &lifetime.bounds {
1942 word(&mut self.s, sep)?;
1943 self.print_lifetime(v)?;
1949 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
1950 let total = generics.lifetimes.len() + generics.ty_params.len();
1955 word(&mut self.s, "<")?;
1957 let mut ints = Vec::new();
1962 self.commasep(Inconsistent, &ints[..], |s, &idx| {
1963 if idx < generics.lifetimes.len() {
1964 let lifetime = &generics.lifetimes[idx];
1965 s.print_lifetime_def(lifetime)
1967 let idx = idx - generics.lifetimes.len();
1968 let param = &generics.ty_params[idx];
1969 s.print_ty_param(param)
1973 word(&mut self.s, ">")?;
1977 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
1978 self.print_name(param.name)?;
1979 self.print_bounds(":", ¶m.bounds)?;
1980 match param.default {
1981 Some(ref default) => {
1982 space(&mut self.s)?;
1983 self.word_space("=")?;
1984 self.print_type(&default)
1990 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
1991 if where_clause.predicates.is_empty() {
1995 space(&mut self.s)?;
1996 self.word_space("where")?;
1998 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2000 self.word_space(",")?;
2004 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2008 self.print_formal_lifetime_list(bound_lifetimes)?;
2009 self.print_type(&bounded_ty)?;
2010 self.print_bounds(":", bounds)?;
2012 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2015 self.print_lifetime(lifetime)?;
2016 word(&mut self.s, ":")?;
2018 for (i, bound) in bounds.iter().enumerate() {
2019 self.print_lifetime(bound)?;
2022 word(&mut self.s, ":")?;
2026 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2029 self.print_type(lhs_ty)?;
2030 space(&mut self.s)?;
2031 self.word_space("=")?;
2032 self.print_type(rhs_ty)?;
2040 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2042 hir::MutMutable => self.word_nbsp("mut"),
2043 hir::MutImmutable => Ok(()),
2047 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2048 self.print_mutability(mt.mutbl)?;
2049 self.print_type(&mt.ty)
2052 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2053 if let hir::DefaultReturn(..) = decl.output {
2057 self.space_if_not_bol()?;
2058 self.ibox(indent_unit)?;
2059 self.word_space("->")?;
2061 hir::DefaultReturn(..) => unreachable!(),
2062 hir::Return(ref ty) => self.print_type(&ty)?,
2067 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2072 pub fn print_ty_fn(&mut self,
2074 unsafety: hir::Unsafety,
2076 name: Option<ast::Name>,
2077 generics: &hir::Generics)
2079 self.ibox(indent_unit)?;
2080 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2081 word(&mut self.s, "for")?;
2082 self.print_generics(generics)?;
2084 let generics = hir::Generics {
2085 lifetimes: hir::HirVec::new(),
2086 ty_params: hir::HirVec::new(),
2087 where_clause: hir::WhereClause {
2088 id: ast::DUMMY_NODE_ID,
2089 predicates: hir::HirVec::new(),
2091 span: syntax_pos::DUMMY_SP,
2095 hir::Constness::NotConst,
2105 pub fn maybe_print_trailing_comment(&mut self,
2106 span: syntax_pos::Span,
2107 next_pos: Option<BytePos>)
2109 let cm = match self.cm {
2113 if let Some(ref cmnt) = self.next_comment() {
2114 if (*cmnt).style != comments::Trailing {
2117 let span_line = cm.lookup_char_pos(span.hi);
2118 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2119 let mut next = (*cmnt).pos + BytePos(1);
2120 if let Some(p) = next_pos {
2123 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2124 span_line.line == comment_line.line {
2125 self.print_comment(cmnt)?;
2126 self.cur_cmnt_and_lit.cur_cmnt += 1;
2132 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2133 // If there aren't any remaining comments, then we need to manually
2134 // make sure there is a line break at the end.
2135 if self.next_comment().is_none() {
2136 hardbreak(&mut self.s)?;
2139 match self.next_comment() {
2141 self.print_comment(cmnt)?;
2142 self.cur_cmnt_and_lit.cur_cmnt += 1;
2150 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2151 opt_abi: Option<Abi>)
2154 Some(Abi::Rust) => Ok(()),
2156 self.word_nbsp("extern")?;
2157 self.word_nbsp(&abi.to_string())
2163 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2166 self.word_nbsp("extern")?;
2167 self.word_nbsp(&abi.to_string())
2173 pub fn print_fn_header_info(&mut self,
2174 unsafety: hir::Unsafety,
2175 constness: hir::Constness,
2177 vis: &hir::Visibility)
2179 word(&mut self.s, &visibility_qualified(vis, ""))?;
2180 self.print_unsafety(unsafety)?;
2183 hir::Constness::NotConst => {}
2184 hir::Constness::Const => self.word_nbsp("const")?,
2187 if abi != Abi::Rust {
2188 self.word_nbsp("extern")?;
2189 self.word_nbsp(&abi.to_string())?;
2192 word(&mut self.s, "fn")
2195 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2197 hir::Unsafety::Normal => Ok(()),
2198 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2203 // Dup'ed from parse::classify, but adapted for the HIR.
2204 /// Does this expression require a semicolon to be treated
2205 /// as a statement? The negation of this: 'can this expression
2206 /// be used as a statement without a semicolon' -- is used
2207 /// as an early-bail-out in the parser so that, for instance,
2208 /// if true {...} else {...}
2210 /// isn't parsed as (if true {...} else {...} | x) | 5
2211 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2214 hir::ExprMatch(..) |
2216 hir::ExprWhile(..) |
2217 hir::ExprLoop(..) => false,
2222 /// this statement requires a semicolon after it.
2223 /// note that in one case (stmt_semi), we've already
2224 /// seen the semicolon, and thus don't need another.
2225 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2227 hir::StmtDecl(ref d, _) => {
2229 hir::DeclLocal(_) => true,
2230 hir::DeclItem(_) => false,
2233 hir::StmtExpr(ref e, _) => {
2234 expr_requires_semi_to_be_stmt(&e)
2236 hir::StmtSemi(..) => {