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::token::{self, keywords, BinOpToken};
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_pos::{self, BytePos};
27 use hir::{Crate, PatKind, RegionTyParamBound, SelfKind, 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),
41 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
44 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
49 #[derive(Copy, Clone)]
52 impl PpAnn for NoAnn {}
55 pub struct State<'a> {
56 krate: Option<&'a Crate>,
57 pub s: pp::Printer<'a>,
58 cm: Option<&'a CodeMap>,
59 comments: Option<Vec<comments::Comment>>,
60 literals: Option<Vec<comments::Literal>>,
61 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
62 boxes: Vec<pp::Breaks>,
63 ann: &'a (PpAnn + 'a),
66 impl<'a> PrintState<'a> for State<'a> {
67 fn writer(&mut self) -> &mut pp::Printer<'a> {
71 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
75 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
79 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
80 &mut self.cur_cmnt_and_lit
83 fn literals(&self) -> &Option<Vec<comments::Literal>> {
88 pub fn rust_printer<'a>(writer: Box<Write + 'a>, krate: Option<&'a Crate>) -> State<'a> {
89 static NO_ANN: NoAnn = NoAnn;
90 rust_printer_annotated(writer, &NO_ANN, krate)
93 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>,
95 krate: Option<&'a Crate>)
99 s: pp::mk_printer(writer, default_columns),
103 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
112 #[allow(non_upper_case_globals)]
113 pub const indent_unit: usize = 4;
115 #[allow(non_upper_case_globals)]
116 pub const default_columns: usize = 78;
119 /// Requires you to pass an input filename and reader so that
120 /// it can scan the input text for comments and literals to
122 pub fn print_crate<'a>(cm: &'a CodeMap,
123 span_diagnostic: &errors::Handler,
127 out: Box<Write + 'a>,
131 let mut s = State::new_from_input(cm, span_diagnostic, filename, input,
132 out, ann, is_expanded, Some(krate));
134 // When printing the AST, we sometimes need to inject `#[no_std]` here.
135 // Since you can't compile the HIR, it's not necessary.
137 s.print_mod(&krate.module, &krate.attrs)?;
138 s.print_remaining_comments()?;
143 pub fn new_from_input(cm: &'a CodeMap,
144 span_diagnostic: &errors::Handler,
147 out: Box<Write + 'a>,
150 krate: Option<&'a Crate>)
152 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
160 // If the code is post expansion, don't use the table of
161 // literals, since it doesn't correspond with the literals
162 // in the AST anymore.
171 pub fn new(cm: &'a CodeMap,
172 out: Box<Write + 'a>,
174 comments: Option<Vec<comments::Comment>>,
175 literals: Option<Vec<comments::Literal>>,
176 krate: Option<&'a Crate>)
180 s: pp::mk_printer(out, default_columns),
182 comments: comments.clone(),
183 literals: literals.clone(),
184 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
194 pub fn to_string<F>(f: F) -> String
195 where F: FnOnce(&mut State) -> io::Result<()>
197 let mut wr = Vec::new();
199 let mut printer = rust_printer(Box::new(&mut wr), None);
200 f(&mut printer).unwrap();
201 eof(&mut printer.s).unwrap();
203 String::from_utf8(wr).unwrap()
206 pub fn binop_to_string(op: BinOpToken) -> &'static str {
212 token::Percent => "%",
221 pub fn ty_to_string(ty: &hir::Ty) -> String {
222 to_string(|s| s.print_type(ty))
225 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
226 to_string(|s| s.print_bounds("", bounds))
229 pub fn pat_to_string(pat: &hir::Pat) -> String {
230 to_string(|s| s.print_pat(pat))
233 pub fn arm_to_string(arm: &hir::Arm) -> String {
234 to_string(|s| s.print_arm(arm))
237 pub fn expr_to_string(e: &hir::Expr) -> String {
238 to_string(|s| s.print_expr(e))
241 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
242 to_string(|s| s.print_lifetime(e))
245 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
246 to_string(|s| s.print_stmt(stmt))
249 pub fn item_to_string(i: &hir::Item) -> String {
250 to_string(|s| s.print_item(i))
253 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
254 to_string(|s| s.print_impl_item(i))
257 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
258 to_string(|s| s.print_trait_item(i))
261 pub fn generics_to_string(generics: &hir::Generics) -> String {
262 to_string(|s| s.print_generics(generics))
265 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
266 to_string(|s| s.print_where_clause(i))
269 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
270 to_string(|s| s.print_fn_block_args(p))
273 pub fn path_to_string(p: &hir::Path) -> String {
274 to_string(|s| s.print_path(p, false, 0))
277 pub fn name_to_string(name: ast::Name) -> String {
278 to_string(|s| s.print_name(name))
281 pub fn fun_to_string(decl: &hir::FnDecl,
282 unsafety: hir::Unsafety,
283 constness: hir::Constness,
285 generics: &hir::Generics)
296 s.end()?; // Close the head box
297 s.end() // Close the outer box
301 pub fn block_to_string(blk: &hir::Block) -> String {
303 // containing cbox, will be closed by print-block at }
304 s.cbox(indent_unit)?;
305 // head-ibox, will be closed by print-block after {
311 pub fn variant_to_string(var: &hir::Variant) -> String {
312 to_string(|s| s.print_variant(var))
315 pub fn arg_to_string(arg: &hir::Arg) -> String {
316 to_string(|s| s.print_arg(arg, false))
319 pub fn visibility_qualified(vis: &hir::Visibility, s: &str) -> String {
321 hir::Public => format!("pub {}", s),
322 hir::Visibility::Crate => format!("pub(crate) {}", s),
323 hir::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
324 hir::Inherited => s.to_string(),
328 fn needs_parentheses(expr: &hir::Expr) -> bool {
330 hir::ExprAssign(..) |
331 hir::ExprBinary(..) |
332 hir::ExprClosure(..) |
333 hir::ExprAssignOp(..) |
335 hir::ExprType(..) => true,
341 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
342 self.boxes.push(pp::Breaks::Consistent);
343 pp::cbox(&mut self.s, u)
346 pub fn nbsp(&mut self) -> io::Result<()> {
347 word(&mut self.s, " ")
350 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
351 word(&mut self.s, w)?;
355 pub fn head(&mut self, w: &str) -> io::Result<()> {
356 // outer-box is consistent
357 self.cbox(indent_unit)?;
358 // head-box is inconsistent
359 self.ibox(w.len() + 1)?;
360 // keyword that starts the head
367 pub fn bopen(&mut self) -> io::Result<()> {
368 word(&mut self.s, "{")?;
369 self.end() // close the head-box
372 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
373 self.bclose_maybe_open(span, indented, true)
375 pub fn bclose_maybe_open(&mut self,
376 span: syntax_pos::Span,
380 self.maybe_print_comment(span.hi)?;
381 self.break_offset_if_not_bol(1, -(indented as isize))?;
382 word(&mut self.s, "}")?;
384 self.end()?; // close the outer-box
388 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
389 self.bclose_(span, indent_unit)
392 pub fn in_cbox(&self) -> bool {
393 match self.boxes.last() {
394 Some(&last_box) => last_box == pp::Breaks::Consistent,
398 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
404 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
406 break_offset(&mut self.s, n, off)
408 if off != 0 && self.s.last_token().is_hardbreak_tok() {
409 // We do something pretty sketchy here: tuck the nonzero
410 // offset-adjustment we were going to deposit along with the
411 // break into the previous hardbreak.
412 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
418 // Synthesizes a comment that was not textually present in the original source
420 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
421 word(&mut self.s, "/*")?;
423 word(&mut self.s, &text[..])?;
425 word(&mut self.s, "*/")
429 pub fn commasep_cmnt<T, F, G>(&mut self,
435 where F: FnMut(&mut State, &T) -> io::Result<()>,
436 G: FnMut(&T) -> syntax_pos::Span
439 let len = elts.len();
442 self.maybe_print_comment(get_span(elt).hi)?;
446 word(&mut self.s, ",")?;
447 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
448 self.space_if_not_bol()?;
454 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<hir::Expr>]) -> io::Result<()> {
455 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
458 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
459 self.print_inner_attributes(attrs)?;
460 for item_id in &_mod.item_ids {
461 self.print_item_id(item_id)?;
466 pub fn print_foreign_mod(&mut self,
467 nmod: &hir::ForeignMod,
468 attrs: &[ast::Attribute])
470 self.print_inner_attributes(attrs)?;
471 for item in &nmod.items {
472 self.print_foreign_item(item)?;
477 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
478 if let Some(l) = *lifetime {
479 self.print_lifetime(&l)?;
485 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
486 self.maybe_print_comment(ty.span.lo)?;
489 hir::TyVec(ref ty) => {
490 word(&mut self.s, "[")?;
491 self.print_type(&ty)?;
492 word(&mut self.s, "]")?;
494 hir::TyPtr(ref mt) => {
495 word(&mut self.s, "*")?;
497 hir::MutMutable => self.word_nbsp("mut")?,
498 hir::MutImmutable => self.word_nbsp("const")?,
500 self.print_type(&mt.ty)?;
502 hir::TyRptr(ref lifetime, ref mt) => {
503 word(&mut self.s, "&")?;
504 self.print_opt_lifetime(lifetime)?;
508 word(&mut self.s, "!")?;
510 hir::TyTup(ref elts) => {
512 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
514 word(&mut self.s, ",")?;
518 hir::TyBareFn(ref f) => {
519 let generics = hir::Generics {
520 lifetimes: f.lifetimes.clone(),
521 ty_params: hir::HirVec::new(),
522 where_clause: hir::WhereClause {
523 id: ast::DUMMY_NODE_ID,
524 predicates: hir::HirVec::new(),
526 span: syntax_pos::DUMMY_SP,
528 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
530 hir::TyPath(None, ref path) => {
531 self.print_path(path, false, 0)?;
533 hir::TyPath(Some(ref qself), ref path) => {
534 self.print_qpath(path, qself, false)?
536 hir::TyObjectSum(ref ty, ref bounds) => {
537 self.print_type(&ty)?;
538 self.print_bounds("+", &bounds[..])?;
540 hir::TyPolyTraitRef(ref bounds) => {
541 self.print_bounds("", &bounds[..])?;
543 hir::TyImplTrait(ref bounds) => {
544 self.print_bounds("impl ", &bounds[..])?;
546 hir::TyFixedLengthVec(ref ty, ref v) => {
547 word(&mut self.s, "[")?;
548 self.print_type(&ty)?;
549 word(&mut self.s, "; ")?;
550 self.print_expr(&v)?;
551 word(&mut self.s, "]")?;
553 hir::TyTypeof(ref e) => {
554 word(&mut self.s, "typeof(")?;
555 self.print_expr(&e)?;
556 word(&mut self.s, ")")?;
559 word(&mut self.s, "_")?;
565 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
566 self.hardbreak_if_not_bol()?;
567 self.maybe_print_comment(item.span.lo)?;
568 self.print_outer_attributes(&item.attrs)?;
570 hir::ForeignItemFn(ref decl, ref generics) => {
573 hir::Unsafety::Normal,
574 hir::Constness::NotConst,
579 self.end()?; // end head-ibox
580 word(&mut self.s, ";")?;
581 self.end() // end the outer fn box
583 hir::ForeignItemStatic(ref t, m) => {
584 self.head(&visibility_qualified(&item.vis, "static"))?;
586 self.word_space("mut")?;
588 self.print_name(item.name)?;
589 self.word_space(":")?;
590 self.print_type(&t)?;
591 word(&mut self.s, ";")?;
592 self.end()?; // end the head-ibox
593 self.end() // end the outer cbox
598 fn print_associated_const(&mut self,
601 default: Option<&hir::Expr>,
602 vis: &hir::Visibility)
604 word(&mut self.s, &visibility_qualified(vis, ""))?;
605 self.word_space("const")?;
606 self.print_name(name)?;
607 self.word_space(":")?;
608 self.print_type(ty)?;
609 if let Some(expr) = default {
611 self.word_space("=")?;
612 self.print_expr(expr)?;
614 word(&mut self.s, ";")
617 fn print_associated_type(&mut self,
619 bounds: Option<&hir::TyParamBounds>,
620 ty: Option<&hir::Ty>)
622 self.word_space("type")?;
623 self.print_name(name)?;
624 if let Some(bounds) = bounds {
625 self.print_bounds(":", bounds)?;
627 if let Some(ty) = ty {
629 self.word_space("=")?;
630 self.print_type(ty)?;
632 word(&mut self.s, ";")
635 pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
636 if let Some(krate) = self.krate {
637 // skip nested items if krate context was not provided
638 let item = &krate.items[&item_id.id];
639 self.print_item(item)
645 /// Pretty-print an item
646 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
647 self.hardbreak_if_not_bol()?;
648 self.maybe_print_comment(item.span.lo)?;
649 self.print_outer_attributes(&item.attrs)?;
650 self.ann.pre(self, NodeItem(item))?;
652 hir::ItemExternCrate(ref optional_path) => {
653 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
654 if let Some(p) = *optional_path {
655 let val = p.as_str();
656 if val.contains("-") {
657 self.print_string(&val, ast::StrStyle::Cooked)?;
662 word(&mut self.s, "as")?;
665 self.print_name(item.name)?;
666 word(&mut self.s, ";")?;
667 self.end()?; // end inner head-block
668 self.end()?; // end outer head-block
670 hir::ItemUse(ref vp) => {
671 self.head(&visibility_qualified(&item.vis, "use"))?;
672 self.print_view_path(&vp)?;
673 word(&mut self.s, ";")?;
674 self.end()?; // end inner head-block
675 self.end()?; // end outer head-block
677 hir::ItemStatic(ref ty, m, ref expr) => {
678 self.head(&visibility_qualified(&item.vis, "static"))?;
679 if m == hir::MutMutable {
680 self.word_space("mut")?;
682 self.print_name(item.name)?;
683 self.word_space(":")?;
684 self.print_type(&ty)?;
686 self.end()?; // end the head-ibox
688 self.word_space("=")?;
689 self.print_expr(&expr)?;
690 word(&mut self.s, ";")?;
691 self.end()?; // end the outer cbox
693 hir::ItemConst(ref ty, ref expr) => {
694 self.head(&visibility_qualified(&item.vis, "const"))?;
695 self.print_name(item.name)?;
696 self.word_space(":")?;
697 self.print_type(&ty)?;
699 self.end()?; // end the head-ibox
701 self.word_space("=")?;
702 self.print_expr(&expr)?;
703 word(&mut self.s, ";")?;
704 self.end()?; // end the outer cbox
706 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
715 word(&mut self.s, " ")?;
716 self.print_block_with_attrs(&body, &item.attrs)?;
718 hir::ItemMod(ref _mod) => {
719 self.head(&visibility_qualified(&item.vis, "mod"))?;
720 self.print_name(item.name)?;
723 self.print_mod(_mod, &item.attrs)?;
724 self.bclose(item.span)?;
726 hir::ItemForeignMod(ref nmod) => {
727 self.head("extern")?;
728 self.word_nbsp(&nmod.abi.to_string())?;
730 self.print_foreign_mod(nmod, &item.attrs)?;
731 self.bclose(item.span)?;
733 hir::ItemTy(ref ty, ref params) => {
734 self.ibox(indent_unit)?;
736 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
737 self.print_name(item.name)?;
738 self.print_generics(params)?;
739 self.end()?; // end the inner ibox
741 self.print_where_clause(¶ms.where_clause)?;
743 self.word_space("=")?;
744 self.print_type(&ty)?;
745 word(&mut self.s, ";")?;
746 self.end()?; // end the outer ibox
748 hir::ItemEnum(ref enum_definition, ref params) => {
749 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
751 hir::ItemStruct(ref struct_def, ref generics) => {
752 self.head(&visibility_qualified(&item.vis, "struct"))?;
753 self.print_struct(struct_def, generics, item.name, item.span, true)?;
756 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
758 self.print_visibility(&item.vis)?;
759 self.print_unsafety(unsafety)?;
760 self.word_nbsp("impl")?;
761 self.print_trait_ref(trait_ref)?;
763 self.word_space("for")?;
764 self.word_space("..")?;
766 self.bclose(item.span)?;
768 hir::ItemImpl(unsafety,
775 self.print_visibility(&item.vis)?;
776 self.print_unsafety(unsafety)?;
777 self.word_nbsp("impl")?;
779 if generics.is_parameterized() {
780 self.print_generics(generics)?;
785 hir::ImplPolarity::Negative => {
786 word(&mut self.s, "!")?;
793 self.print_trait_ref(t)?;
795 self.word_space("for")?;
800 self.print_type(&ty)?;
801 self.print_where_clause(&generics.where_clause)?;
805 self.print_inner_attributes(&item.attrs)?;
806 for impl_item in impl_items {
807 self.print_impl_item(impl_item)?;
809 self.bclose(item.span)?;
811 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
813 self.print_visibility(&item.vis)?;
814 self.print_unsafety(unsafety)?;
815 self.word_nbsp("trait")?;
816 self.print_name(item.name)?;
817 self.print_generics(generics)?;
818 let mut real_bounds = Vec::with_capacity(bounds.len());
819 for b in bounds.iter() {
820 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
822 self.word_space("for ?")?;
823 self.print_trait_ref(&ptr.trait_ref)?;
825 real_bounds.push(b.clone());
828 self.print_bounds(":", &real_bounds[..])?;
829 self.print_where_clause(&generics.where_clause)?;
830 word(&mut self.s, " ")?;
832 for trait_item in trait_items {
833 self.print_trait_item(trait_item)?;
835 self.bclose(item.span)?;
838 self.ann.post(self, NodeItem(item))
841 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
842 self.print_path(&t.path, false, 0)
845 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
846 if !lifetimes.is_empty() {
847 word(&mut self.s, "for<")?;
848 let mut comma = false;
849 for lifetime_def in lifetimes {
851 self.word_space(",")?
853 self.print_lifetime_def(lifetime_def)?;
856 word(&mut self.s, ">")?;
861 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
862 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
863 self.print_trait_ref(&t.trait_ref)
866 pub fn print_enum_def(&mut self,
867 enum_definition: &hir::EnumDef,
868 generics: &hir::Generics,
870 span: syntax_pos::Span,
871 visibility: &hir::Visibility)
873 self.head(&visibility_qualified(visibility, "enum"))?;
874 self.print_name(name)?;
875 self.print_generics(generics)?;
876 self.print_where_clause(&generics.where_clause)?;
878 self.print_variants(&enum_definition.variants, span)
881 pub fn print_variants(&mut self,
882 variants: &[hir::Variant],
883 span: syntax_pos::Span)
887 self.space_if_not_bol()?;
888 self.maybe_print_comment(v.span.lo)?;
889 self.print_outer_attributes(&v.node.attrs)?;
890 self.ibox(indent_unit)?;
891 self.print_variant(v)?;
892 word(&mut self.s, ",")?;
894 self.maybe_print_trailing_comment(v.span, None)?;
899 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
901 hir::Public => self.word_nbsp("pub"),
902 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
903 hir::Visibility::Restricted { ref path, .. } =>
904 self.word_nbsp(&format!("pub({})", path)),
905 hir::Inherited => Ok(()),
909 pub fn print_struct(&mut self,
910 struct_def: &hir::VariantData,
911 generics: &hir::Generics,
913 span: syntax_pos::Span,
914 print_finalizer: bool)
916 self.print_name(name)?;
917 self.print_generics(generics)?;
918 if !struct_def.is_struct() {
919 if struct_def.is_tuple() {
921 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
922 s.maybe_print_comment(field.span.lo)?;
923 s.print_outer_attributes(&field.attrs)?;
924 s.print_visibility(&field.vis)?;
925 s.print_type(&field.ty)
929 self.print_where_clause(&generics.where_clause)?;
931 word(&mut self.s, ";")?;
934 self.end() // close the outer-box
936 self.print_where_clause(&generics.where_clause)?;
939 self.hardbreak_if_not_bol()?;
941 for field in struct_def.fields() {
942 self.hardbreak_if_not_bol()?;
943 self.maybe_print_comment(field.span.lo)?;
944 self.print_outer_attributes(&field.attrs)?;
945 self.print_visibility(&field.vis)?;
946 self.print_name(field.name)?;
947 self.word_nbsp(":")?;
948 self.print_type(&field.ty)?;
949 word(&mut self.s, ",")?;
956 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
958 let generics = hir::Generics::empty();
959 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
960 match v.node.disr_expr {
963 self.word_space("=")?;
969 pub fn print_method_sig(&mut self,
972 vis: &hir::Visibility)
974 self.print_fn(&m.decl,
983 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
984 self.ann.pre(self, NodeSubItem(ti.id))?;
985 self.hardbreak_if_not_bol()?;
986 self.maybe_print_comment(ti.span.lo)?;
987 self.print_outer_attributes(&ti.attrs)?;
989 hir::ConstTraitItem(ref ty, ref default) => {
990 self.print_associated_const(ti.name,
992 default.as_ref().map(|expr| &**expr),
995 hir::MethodTraitItem(ref sig, ref body) => {
999 self.print_method_sig(ti.name, sig, &hir::Inherited)?;
1000 if let Some(ref body) = *body {
1002 self.print_block_with_attrs(body, &ti.attrs)?;
1004 word(&mut self.s, ";")?;
1007 hir::TypeTraitItem(ref bounds, ref default) => {
1008 self.print_associated_type(ti.name,
1010 default.as_ref().map(|ty| &**ty))?;
1013 self.ann.post(self, NodeSubItem(ti.id))
1016 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1017 self.ann.pre(self, NodeSubItem(ii.id))?;
1018 self.hardbreak_if_not_bol()?;
1019 self.maybe_print_comment(ii.span.lo)?;
1020 self.print_outer_attributes(&ii.attrs)?;
1022 if let hir::Defaultness::Default = ii.defaultness {
1023 self.word_nbsp("default")?;
1027 hir::ImplItemKind::Const(ref ty, ref expr) => {
1028 self.print_associated_const(ii.name, &ty, Some(&expr), &ii.vis)?;
1030 hir::ImplItemKind::Method(ref sig, ref body) => {
1032 self.print_method_sig(ii.name, sig, &ii.vis)?;
1034 self.print_block_with_attrs(body, &ii.attrs)?;
1036 hir::ImplItemKind::Type(ref ty) => {
1037 self.print_associated_type(ii.name, None, Some(ty))?;
1040 self.ann.post(self, NodeSubItem(ii.id))
1043 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1044 self.maybe_print_comment(st.span.lo)?;
1046 hir::StmtDecl(ref decl, _) => {
1047 self.print_decl(&decl)?;
1049 hir::StmtExpr(ref expr, _) => {
1050 self.space_if_not_bol()?;
1051 self.print_expr(&expr)?;
1053 hir::StmtSemi(ref expr, _) => {
1054 self.space_if_not_bol()?;
1055 self.print_expr(&expr)?;
1056 word(&mut self.s, ";")?;
1059 if stmt_ends_with_semi(&st.node) {
1060 word(&mut self.s, ";")?;
1062 self.maybe_print_trailing_comment(st.span, None)
1065 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1066 self.print_block_with_attrs(blk, &[])
1069 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1070 self.print_block_unclosed_indent(blk, indent_unit)
1073 pub fn print_block_unclosed_indent(&mut self,
1077 self.print_block_maybe_unclosed(blk, indented, &[], false)
1080 pub fn print_block_with_attrs(&mut self,
1082 attrs: &[ast::Attribute])
1084 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1087 pub fn print_block_maybe_unclosed(&mut self,
1090 attrs: &[ast::Attribute],
1094 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1095 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1096 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1097 hir::PushUnstableBlock => self.word_space("push_unstable")?,
1098 hir::PopUnstableBlock => self.word_space("pop_unstable")?,
1099 hir::DefaultBlock => (),
1101 self.maybe_print_comment(blk.span.lo)?;
1102 self.ann.pre(self, NodeBlock(blk))?;
1105 self.print_inner_attributes(attrs)?;
1107 for st in &blk.stmts {
1108 self.print_stmt(st)?;
1112 self.space_if_not_bol()?;
1113 self.print_expr(&expr)?;
1114 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1118 self.bclose_maybe_open(blk.span, indented, close_box)?;
1119 self.ann.post(self, NodeBlock(blk))
1122 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1126 // "another else-if"
1127 hir::ExprIf(ref i, ref then, ref e) => {
1128 self.cbox(indent_unit - 1)?;
1130 word(&mut self.s, " else if ")?;
1131 self.print_expr(&i)?;
1132 space(&mut self.s)?;
1133 self.print_block(&then)?;
1134 self.print_else(e.as_ref().map(|e| &**e))
1137 hir::ExprBlock(ref b) => {
1138 self.cbox(indent_unit - 1)?;
1140 word(&mut self.s, " else ")?;
1141 self.print_block(&b)
1143 // BLEAH, constraints would be great here
1145 panic!("print_if saw if with weird alternative");
1153 pub fn print_if(&mut self,
1156 elseopt: Option<&hir::Expr>)
1159 self.print_expr(test)?;
1160 space(&mut self.s)?;
1161 self.print_block(blk)?;
1162 self.print_else(elseopt)
1165 pub fn print_if_let(&mut self,
1169 elseopt: Option<&hir::Expr>)
1171 self.head("if let")?;
1172 self.print_pat(pat)?;
1173 space(&mut self.s)?;
1174 self.word_space("=")?;
1175 self.print_expr(expr)?;
1176 space(&mut self.s)?;
1177 self.print_block(blk)?;
1178 self.print_else(elseopt)
1182 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1184 self.commasep_exprs(Inconsistent, args)?;
1188 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1189 let needs_par = needs_parentheses(expr);
1193 self.print_expr(expr)?;
1200 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1201 self.ibox(indent_unit)?;
1202 word(&mut self.s, "[")?;
1203 self.commasep_exprs(Inconsistent, &exprs[..])?;
1204 word(&mut self.s, "]")?;
1208 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1209 self.ibox(indent_unit)?;
1210 word(&mut self.s, "[")?;
1211 self.print_expr(element)?;
1212 self.word_space(";")?;
1213 self.print_expr(count)?;
1214 word(&mut self.s, "]")?;
1218 fn print_expr_struct(&mut self,
1220 fields: &[hir::Field],
1221 wth: &Option<P<hir::Expr>>)
1223 self.print_path(path, true, 0)?;
1224 word(&mut self.s, "{")?;
1225 self.commasep_cmnt(Consistent,
1228 s.ibox(indent_unit)?;
1229 s.print_name(field.name.node)?;
1231 s.print_expr(&field.expr)?;
1237 self.ibox(indent_unit)?;
1238 if !fields.is_empty() {
1239 word(&mut self.s, ",")?;
1240 space(&mut self.s)?;
1242 word(&mut self.s, "..")?;
1243 self.print_expr(&expr)?;
1246 _ => if !fields.is_empty() {
1247 word(&mut self.s, ",")?
1250 word(&mut self.s, "}")?;
1254 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1256 self.commasep_exprs(Inconsistent, &exprs[..])?;
1257 if exprs.len() == 1 {
1258 word(&mut self.s, ",")?;
1263 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1264 self.print_expr_maybe_paren(func)?;
1265 self.print_call_post(args)
1268 fn print_expr_method_call(&mut self,
1269 name: Spanned<ast::Name>,
1271 args: &[P<hir::Expr>])
1273 let base_args = &args[1..];
1274 self.print_expr(&args[0])?;
1275 word(&mut self.s, ".")?;
1276 self.print_name(name.node)?;
1277 if !tys.is_empty() {
1278 word(&mut self.s, "::<")?;
1279 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1280 word(&mut self.s, ">")?;
1282 self.print_call_post(base_args)
1285 fn print_expr_binary(&mut self,
1290 self.print_expr(lhs)?;
1291 space(&mut self.s)?;
1292 self.word_space(op.node.as_str())?;
1293 self.print_expr(rhs)
1296 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1297 word(&mut self.s, op.as_str())?;
1298 self.print_expr_maybe_paren(expr)
1301 fn print_expr_addr_of(&mut self,
1302 mutability: hir::Mutability,
1305 word(&mut self.s, "&")?;
1306 self.print_mutability(mutability)?;
1307 self.print_expr_maybe_paren(expr)
1310 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1311 self.maybe_print_comment(expr.span.lo)?;
1312 self.ibox(indent_unit)?;
1313 self.ann.pre(self, NodeExpr(expr))?;
1315 hir::ExprBox(ref expr) => {
1316 self.word_space("box")?;
1317 self.print_expr(expr)?;
1319 hir::ExprVec(ref exprs) => {
1320 self.print_expr_vec(&exprs[..])?;
1322 hir::ExprRepeat(ref element, ref count) => {
1323 self.print_expr_repeat(&element, &count)?;
1325 hir::ExprStruct(ref path, ref fields, ref wth) => {
1326 self.print_expr_struct(path, &fields[..], wth)?;
1328 hir::ExprTup(ref exprs) => {
1329 self.print_expr_tup(&exprs[..])?;
1331 hir::ExprCall(ref func, ref args) => {
1332 self.print_expr_call(&func, &args[..])?;
1334 hir::ExprMethodCall(name, ref tys, ref args) => {
1335 self.print_expr_method_call(name, &tys[..], &args[..])?;
1337 hir::ExprBinary(op, ref lhs, ref rhs) => {
1338 self.print_expr_binary(op, &lhs, &rhs)?;
1340 hir::ExprUnary(op, ref expr) => {
1341 self.print_expr_unary(op, &expr)?;
1343 hir::ExprAddrOf(m, ref expr) => {
1344 self.print_expr_addr_of(m, &expr)?;
1346 hir::ExprLit(ref lit) => {
1347 self.print_literal(&lit)?;
1349 hir::ExprCast(ref expr, ref ty) => {
1350 self.print_expr(&expr)?;
1351 space(&mut self.s)?;
1352 self.word_space("as")?;
1353 self.print_type(&ty)?;
1355 hir::ExprType(ref expr, ref ty) => {
1356 self.print_expr(&expr)?;
1357 self.word_space(":")?;
1358 self.print_type(&ty)?;
1360 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1361 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1363 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1364 if let Some(sp_name) = opt_sp_name {
1365 self.print_name(sp_name.node)?;
1366 self.word_space(":")?;
1368 self.head("while")?;
1369 self.print_expr(&test)?;
1370 space(&mut self.s)?;
1371 self.print_block(&blk)?;
1373 hir::ExprLoop(ref blk, opt_sp_name) => {
1374 if let Some(sp_name) = opt_sp_name {
1375 self.print_name(sp_name.node)?;
1376 self.word_space(":")?;
1379 space(&mut self.s)?;
1380 self.print_block(&blk)?;
1382 hir::ExprMatch(ref expr, ref arms, _) => {
1383 self.cbox(indent_unit)?;
1385 self.word_nbsp("match")?;
1386 self.print_expr(&expr)?;
1387 space(&mut self.s)?;
1390 self.print_arm(arm)?;
1392 self.bclose_(expr.span, indent_unit)?;
1394 hir::ExprClosure(capture_clause, ref decl, ref body, _fn_decl_span) => {
1395 self.print_capture_clause(capture_clause)?;
1397 self.print_fn_block_args(&decl)?;
1398 space(&mut self.s)?;
1400 let default_return = match decl.output {
1401 hir::DefaultReturn(..) => true,
1405 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1406 self.print_block_unclosed(&body)?;
1408 // we extract the block, so as not to create another set of boxes
1409 match body.expr.as_ref().unwrap().node {
1410 hir::ExprBlock(ref blk) => {
1411 self.print_block_unclosed(&blk)?;
1414 // this is a bare expression
1415 self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap())?;
1416 self.end()?; // need to close a box
1420 // a box will be closed by print_expr, but we didn't want an overall
1421 // wrapper so we closed the corresponding opening. so create an
1422 // empty box to satisfy the close.
1425 hir::ExprBlock(ref blk) => {
1426 // containing cbox, will be closed by print-block at }
1427 self.cbox(indent_unit)?;
1428 // head-box, will be closed by print-block after {
1430 self.print_block(&blk)?;
1432 hir::ExprAssign(ref lhs, ref rhs) => {
1433 self.print_expr(&lhs)?;
1434 space(&mut self.s)?;
1435 self.word_space("=")?;
1436 self.print_expr(&rhs)?;
1438 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1439 self.print_expr(&lhs)?;
1440 space(&mut self.s)?;
1441 word(&mut self.s, op.node.as_str())?;
1442 self.word_space("=")?;
1443 self.print_expr(&rhs)?;
1445 hir::ExprField(ref expr, name) => {
1446 self.print_expr(&expr)?;
1447 word(&mut self.s, ".")?;
1448 self.print_name(name.node)?;
1450 hir::ExprTupField(ref expr, id) => {
1451 self.print_expr(&expr)?;
1452 word(&mut self.s, ".")?;
1453 self.print_usize(id.node)?;
1455 hir::ExprIndex(ref expr, ref index) => {
1456 self.print_expr(&expr)?;
1457 word(&mut self.s, "[")?;
1458 self.print_expr(&index)?;
1459 word(&mut self.s, "]")?;
1461 hir::ExprPath(None, ref path) => {
1462 self.print_path(path, true, 0)?
1464 hir::ExprPath(Some(ref qself), ref path) => {
1465 self.print_qpath(path, qself, true)?
1467 hir::ExprBreak(opt_name) => {
1468 word(&mut self.s, "break")?;
1469 space(&mut self.s)?;
1470 if let Some(name) = opt_name {
1471 self.print_name(name.node)?;
1472 space(&mut self.s)?;
1475 hir::ExprAgain(opt_name) => {
1476 word(&mut self.s, "continue")?;
1477 space(&mut self.s)?;
1478 if let Some(name) = opt_name {
1479 self.print_name(name.node)?;
1483 hir::ExprRet(ref result) => {
1484 word(&mut self.s, "return")?;
1487 word(&mut self.s, " ")?;
1488 self.print_expr(&expr)?;
1493 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1494 word(&mut self.s, "asm!")?;
1496 self.print_string(&a.asm, a.asm_str_style)?;
1497 self.word_space(":")?;
1499 let mut out_idx = 0;
1500 self.commasep(Inconsistent, &a.outputs, |s, out| {
1501 let mut ch = out.constraint.chars();
1503 Some('=') if out.is_rw => {
1504 s.print_string(&format!("+{}", ch.as_str()),
1505 ast::StrStyle::Cooked)?
1507 _ => s.print_string(&out.constraint,
1508 ast::StrStyle::Cooked)?,
1511 s.print_expr(&outputs[out_idx])?;
1516 space(&mut self.s)?;
1517 self.word_space(":")?;
1520 self.commasep(Inconsistent, &a.inputs, |s, co| {
1521 s.print_string(&co, ast::StrStyle::Cooked)?;
1523 s.print_expr(&inputs[in_idx])?;
1528 space(&mut self.s)?;
1529 self.word_space(":")?;
1531 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1532 s.print_string(&co, ast::StrStyle::Cooked)?;
1536 let mut options = vec![];
1538 options.push("volatile");
1541 options.push("alignstack");
1543 if a.dialect == ast::AsmDialect::Intel {
1544 options.push("intel");
1547 if !options.is_empty() {
1548 space(&mut self.s)?;
1549 self.word_space(":")?;
1550 self.commasep(Inconsistent, &options, |s, &co| {
1551 s.print_string(co, ast::StrStyle::Cooked)?;
1559 self.ann.post(self, NodeExpr(expr))?;
1563 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1564 self.print_pat(&loc.pat)?;
1565 if let Some(ref ty) = loc.ty {
1566 self.word_space(":")?;
1567 self.print_type(&ty)?;
1572 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1573 self.maybe_print_comment(decl.span.lo)?;
1575 hir::DeclLocal(ref loc) => {
1576 self.space_if_not_bol()?;
1577 self.ibox(indent_unit)?;
1578 self.word_nbsp("let")?;
1580 self.ibox(indent_unit)?;
1581 self.print_local_decl(&loc)?;
1583 if let Some(ref init) = loc.init {
1585 self.word_space("=")?;
1586 self.print_expr(&init)?;
1590 hir::DeclItem(ref item) => {
1591 self.print_item_id(item)
1596 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1597 word(&mut self.s, &i.to_string())
1600 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1601 word(&mut self.s, &name.as_str())?;
1602 self.ann.post(self, NodeName(&name))
1605 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1606 self.print_local_decl(loc)?;
1607 space(&mut self.s)?;
1608 self.word_space("in")?;
1609 self.print_expr(coll)
1612 fn print_path(&mut self,
1614 colons_before_params: bool,
1617 self.maybe_print_comment(path.span.lo)?;
1619 let mut first = !path.global;
1620 for segment in &path.segments[..path.segments.len() - depth] {
1624 word(&mut self.s, "::")?
1627 self.print_name(segment.name)?;
1629 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1635 fn print_qpath(&mut self,
1638 colons_before_params: bool)
1640 word(&mut self.s, "<")?;
1641 self.print_type(&qself.ty)?;
1642 if qself.position > 0 {
1643 space(&mut self.s)?;
1644 self.word_space("as")?;
1645 let depth = path.segments.len() - qself.position;
1646 self.print_path(&path, false, depth)?;
1648 word(&mut self.s, ">")?;
1649 word(&mut self.s, "::")?;
1650 let item_segment = path.segments.last().unwrap();
1651 self.print_name(item_segment.name)?;
1652 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1655 fn print_path_parameters(&mut self,
1656 parameters: &hir::PathParameters,
1657 colons_before_params: bool)
1659 if parameters.is_empty() {
1663 if colons_before_params {
1664 word(&mut self.s, "::")?
1668 hir::AngleBracketedParameters(ref data) => {
1669 word(&mut self.s, "<")?;
1671 let mut comma = false;
1672 for lifetime in &data.lifetimes {
1674 self.word_space(",")?
1676 self.print_lifetime(lifetime)?;
1680 if !data.types.is_empty() {
1682 self.word_space(",")?
1684 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1688 for binding in data.bindings.iter() {
1690 self.word_space(",")?
1692 self.print_name(binding.name)?;
1693 space(&mut self.s)?;
1694 self.word_space("=")?;
1695 self.print_type(&binding.ty)?;
1699 word(&mut self.s, ">")?
1702 hir::ParenthesizedParameters(ref data) => {
1703 word(&mut self.s, "(")?;
1704 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1705 word(&mut self.s, ")")?;
1707 if let Some(ref ty) = data.output {
1708 self.space_if_not_bol()?;
1709 self.word_space("->")?;
1710 self.print_type(&ty)?;
1718 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1719 self.maybe_print_comment(pat.span.lo)?;
1720 self.ann.pre(self, NodePat(pat))?;
1721 // Pat isn't normalized, but the beauty of it
1722 // is that it doesn't matter
1724 PatKind::Wild => word(&mut self.s, "_")?,
1725 PatKind::Binding(binding_mode, ref path1, ref sub) => {
1726 match binding_mode {
1727 hir::BindByRef(mutbl) => {
1728 self.word_nbsp("ref")?;
1729 self.print_mutability(mutbl)?;
1731 hir::BindByValue(hir::MutImmutable) => {}
1732 hir::BindByValue(hir::MutMutable) => {
1733 self.word_nbsp("mut")?;
1736 self.print_name(path1.node)?;
1737 if let Some(ref p) = *sub {
1738 word(&mut self.s, "@")?;
1739 self.print_pat(&p)?;
1742 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
1743 self.print_path(path, true, 0)?;
1745 if let Some(ddpos) = ddpos {
1746 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1748 self.word_space(",")?;
1750 word(&mut self.s, "..")?;
1751 if ddpos != elts.len() {
1752 word(&mut self.s, ",")?;
1753 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1756 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
1758 try!(self.pclose());
1760 PatKind::Path(None, ref path) => {
1761 self.print_path(path, true, 0)?;
1763 PatKind::Path(Some(ref qself), ref path) => {
1764 self.print_qpath(path, qself, false)?;
1766 PatKind::Struct(ref path, ref fields, etc) => {
1767 self.print_path(path, true, 0)?;
1769 self.word_space("{")?;
1770 self.commasep_cmnt(Consistent,
1773 s.cbox(indent_unit)?;
1774 if !f.node.is_shorthand {
1775 s.print_name(f.node.name)?;
1778 s.print_pat(&f.node.pat)?;
1781 |f| f.node.pat.span)?;
1783 if !fields.is_empty() {
1784 self.word_space(",")?;
1786 word(&mut self.s, "..")?;
1788 space(&mut self.s)?;
1789 word(&mut self.s, "}")?;
1791 PatKind::Tuple(ref elts, ddpos) => {
1793 if let Some(ddpos) = ddpos {
1794 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1796 self.word_space(",")?;
1798 word(&mut self.s, "..")?;
1799 if ddpos != elts.len() {
1800 word(&mut self.s, ",")?;
1801 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1804 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1805 if elts.len() == 1 {
1806 word(&mut self.s, ",")?;
1811 PatKind::Box(ref inner) => {
1812 word(&mut self.s, "box ")?;
1813 self.print_pat(&inner)?;
1815 PatKind::Ref(ref inner, mutbl) => {
1816 word(&mut self.s, "&")?;
1817 if mutbl == hir::MutMutable {
1818 word(&mut self.s, "mut ")?;
1820 self.print_pat(&inner)?;
1822 PatKind::Lit(ref e) => self.print_expr(&e)?,
1823 PatKind::Range(ref begin, ref end) => {
1824 self.print_expr(&begin)?;
1825 space(&mut self.s)?;
1826 word(&mut self.s, "...")?;
1827 self.print_expr(&end)?;
1829 PatKind::Vec(ref before, ref slice, ref after) => {
1830 word(&mut self.s, "[")?;
1831 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1832 if let Some(ref p) = *slice {
1833 if !before.is_empty() {
1834 self.word_space(",")?;
1836 if p.node != PatKind::Wild {
1837 self.print_pat(&p)?;
1839 word(&mut self.s, "..")?;
1840 if !after.is_empty() {
1841 self.word_space(",")?;
1844 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1845 word(&mut self.s, "]")?;
1848 self.ann.post(self, NodePat(pat))
1851 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1852 // I have no idea why this check is necessary, but here it
1854 if arm.attrs.is_empty() {
1855 space(&mut self.s)?;
1857 self.cbox(indent_unit)?;
1859 self.print_outer_attributes(&arm.attrs)?;
1860 let mut first = true;
1861 for p in &arm.pats {
1865 space(&mut self.s)?;
1866 self.word_space("|")?;
1868 self.print_pat(&p)?;
1870 space(&mut self.s)?;
1871 if let Some(ref e) = arm.guard {
1872 self.word_space("if")?;
1873 self.print_expr(&e)?;
1874 space(&mut self.s)?;
1876 self.word_space("=>")?;
1878 match arm.body.node {
1879 hir::ExprBlock(ref blk) => {
1880 // the block will close the pattern's ibox
1881 self.print_block_unclosed_indent(&blk, indent_unit)?;
1883 // If it is a user-provided unsafe block, print a comma after it
1884 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1885 word(&mut self.s, ",")?;
1889 self.end()?; // close the ibox for the pattern
1890 self.print_expr(&arm.body)?;
1891 word(&mut self.s, ",")?;
1894 self.end() // close enclosing cbox
1897 fn print_explicit_self(&mut self, explicit_self: &hir::ExplicitSelf) -> io::Result<()> {
1898 match explicit_self.node {
1899 SelfKind::Value(m) => {
1900 self.print_mutability(m)?;
1901 word(&mut self.s, "self")
1903 SelfKind::Region(ref lt, m) => {
1904 word(&mut self.s, "&")?;
1905 self.print_opt_lifetime(lt)?;
1906 self.print_mutability(m)?;
1907 word(&mut self.s, "self")
1909 SelfKind::Explicit(ref typ, m) => {
1910 self.print_mutability(m)?;
1911 word(&mut self.s, "self")?;
1912 self.word_space(":")?;
1913 self.print_type(&typ)
1918 pub fn print_fn(&mut self,
1920 unsafety: hir::Unsafety,
1921 constness: hir::Constness,
1923 name: Option<ast::Name>,
1924 generics: &hir::Generics,
1925 vis: &hir::Visibility)
1927 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1929 if let Some(name) = name {
1931 self.print_name(name)?;
1933 self.print_generics(generics)?;
1934 self.print_fn_args_and_ret(decl)?;
1935 self.print_where_clause(&generics.where_clause)
1938 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1940 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
1942 word(&mut self.s, ", ...")?;
1946 self.print_fn_output(decl)
1949 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1950 word(&mut self.s, "|")?;
1951 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
1952 word(&mut self.s, "|")?;
1954 if let hir::DefaultReturn(..) = decl.output {
1958 self.space_if_not_bol()?;
1959 self.word_space("->")?;
1961 hir::Return(ref ty) => {
1962 self.print_type(&ty)?;
1963 self.maybe_print_comment(ty.span.lo)
1965 hir::DefaultReturn(..) => unreachable!(),
1969 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1970 match capture_clause {
1971 hir::CaptureByValue => self.word_space("move"),
1972 hir::CaptureByRef => Ok(()),
1976 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1977 if !bounds.is_empty() {
1978 word(&mut self.s, prefix)?;
1979 let mut first = true;
1980 for bound in bounds {
1985 self.word_space("+")?;
1989 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1990 self.print_poly_trait_ref(tref)
1992 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1993 word(&mut self.s, "?")?;
1994 self.print_poly_trait_ref(tref)
1996 RegionTyParamBound(ref lt) => {
1997 self.print_lifetime(lt)
2007 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2008 self.print_name(lifetime.name)
2011 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2012 self.print_lifetime(&lifetime.lifetime)?;
2014 for v in &lifetime.bounds {
2015 word(&mut self.s, sep)?;
2016 self.print_lifetime(v)?;
2022 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2023 let total = generics.lifetimes.len() + generics.ty_params.len();
2028 word(&mut self.s, "<")?;
2030 let mut ints = Vec::new();
2035 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2036 if idx < generics.lifetimes.len() {
2037 let lifetime = &generics.lifetimes[idx];
2038 s.print_lifetime_def(lifetime)
2040 let idx = idx - generics.lifetimes.len();
2041 let param = &generics.ty_params[idx];
2042 s.print_ty_param(param)
2046 word(&mut self.s, ">")?;
2050 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2051 self.print_name(param.name)?;
2052 self.print_bounds(":", ¶m.bounds)?;
2053 match param.default {
2054 Some(ref default) => {
2055 space(&mut self.s)?;
2056 self.word_space("=")?;
2057 self.print_type(&default)
2063 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2064 if where_clause.predicates.is_empty() {
2068 space(&mut self.s)?;
2069 self.word_space("where")?;
2071 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2073 self.word_space(",")?;
2077 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2081 self.print_formal_lifetime_list(bound_lifetimes)?;
2082 self.print_type(&bounded_ty)?;
2083 self.print_bounds(":", bounds)?;
2085 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2088 self.print_lifetime(lifetime)?;
2089 word(&mut self.s, ":")?;
2091 for (i, bound) in bounds.iter().enumerate() {
2092 self.print_lifetime(bound)?;
2095 word(&mut self.s, ":")?;
2099 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2100 self.print_path(path, false, 0)?;
2101 space(&mut self.s)?;
2102 self.word_space("=")?;
2103 self.print_type(&ty)?;
2111 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2113 hir::ViewPathSimple(name, ref path) => {
2114 self.print_path(path, false, 0)?;
2116 if path.segments.last().unwrap().name != name {
2117 space(&mut self.s)?;
2118 self.word_space("as")?;
2119 self.print_name(name)?;
2125 hir::ViewPathGlob(ref path) => {
2126 self.print_path(path, false, 0)?;
2127 word(&mut self.s, "::*")
2130 hir::ViewPathList(ref path, ref segments) => {
2131 if path.segments.is_empty() {
2132 word(&mut self.s, "{")?;
2134 self.print_path(path, false, 0)?;
2135 word(&mut self.s, "::{")?;
2137 self.commasep(Inconsistent, &segments[..], |s, w| s.print_name(w.node.name))?;
2138 word(&mut self.s, "}")
2143 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2145 hir::MutMutable => self.word_nbsp("mut"),
2146 hir::MutImmutable => Ok(()),
2150 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2151 self.print_mutability(mt.mutbl)?;
2152 self.print_type(&mt.ty)
2155 pub fn print_arg(&mut self, input: &hir::Arg, is_closure: bool) -> io::Result<()> {
2156 self.ibox(indent_unit)?;
2157 match input.ty.node {
2158 hir::TyInfer if is_closure => self.print_pat(&input.pat)?,
2160 if let Some(eself) = input.to_self() {
2161 self.print_explicit_self(&eself)?;
2163 let invalid = if let PatKind::Binding(_, name, _) = input.pat.node {
2164 name.node == keywords::Invalid.name()
2169 self.print_pat(&input.pat)?;
2170 word(&mut self.s, ":")?;
2171 space(&mut self.s)?;
2173 self.print_type(&input.ty)?;
2180 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2181 if let hir::DefaultReturn(..) = decl.output {
2185 self.space_if_not_bol()?;
2186 self.ibox(indent_unit)?;
2187 self.word_space("->")?;
2189 hir::DefaultReturn(..) => unreachable!(),
2190 hir::Return(ref ty) => self.print_type(&ty)?,
2195 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2200 pub fn print_ty_fn(&mut self,
2202 unsafety: hir::Unsafety,
2204 name: Option<ast::Name>,
2205 generics: &hir::Generics)
2207 self.ibox(indent_unit)?;
2208 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2209 word(&mut self.s, "for")?;
2210 self.print_generics(generics)?;
2212 let generics = hir::Generics {
2213 lifetimes: hir::HirVec::new(),
2214 ty_params: hir::HirVec::new(),
2215 where_clause: hir::WhereClause {
2216 id: ast::DUMMY_NODE_ID,
2217 predicates: hir::HirVec::new(),
2219 span: syntax_pos::DUMMY_SP,
2223 hir::Constness::NotConst,
2231 pub fn maybe_print_trailing_comment(&mut self,
2232 span: syntax_pos::Span,
2233 next_pos: Option<BytePos>)
2235 let cm = match self.cm {
2239 if let Some(ref cmnt) = self.next_comment() {
2240 if (*cmnt).style != comments::Trailing {
2243 let span_line = cm.lookup_char_pos(span.hi);
2244 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2245 let mut next = (*cmnt).pos + BytePos(1);
2246 if let Some(p) = next_pos {
2249 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2250 span_line.line == comment_line.line {
2251 self.print_comment(cmnt)?;
2252 self.cur_cmnt_and_lit.cur_cmnt += 1;
2258 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2259 // If there aren't any remaining comments, then we need to manually
2260 // make sure there is a line break at the end.
2261 if self.next_comment().is_none() {
2262 hardbreak(&mut self.s)?;
2265 match self.next_comment() {
2267 self.print_comment(cmnt)?;
2268 self.cur_cmnt_and_lit.cur_cmnt += 1;
2276 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2277 opt_abi: Option<Abi>)
2280 Some(Abi::Rust) => Ok(()),
2282 self.word_nbsp("extern")?;
2283 self.word_nbsp(&abi.to_string())
2289 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2292 self.word_nbsp("extern")?;
2293 self.word_nbsp(&abi.to_string())
2299 pub fn print_fn_header_info(&mut self,
2300 unsafety: hir::Unsafety,
2301 constness: hir::Constness,
2303 vis: &hir::Visibility)
2305 word(&mut self.s, &visibility_qualified(vis, ""))?;
2306 self.print_unsafety(unsafety)?;
2309 hir::Constness::NotConst => {}
2310 hir::Constness::Const => self.word_nbsp("const")?,
2313 if abi != Abi::Rust {
2314 self.word_nbsp("extern")?;
2315 self.word_nbsp(&abi.to_string())?;
2318 word(&mut self.s, "fn")
2321 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2323 hir::Unsafety::Normal => Ok(()),
2324 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2329 // Dup'ed from parse::classify, but adapted for the HIR.
2330 /// Does this expression require a semicolon to be treated
2331 /// as a statement? The negation of this: 'can this expression
2332 /// be used as a statement without a semicolon' -- is used
2333 /// as an early-bail-out in the parser so that, for instance,
2334 /// if true {...} else {...}
2336 /// isn't parsed as (if true {...} else {...} | x) | 5
2337 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2340 hir::ExprMatch(..) |
2342 hir::ExprWhile(..) |
2343 hir::ExprLoop(..) => false,
2348 /// this statement requires a semicolon after it.
2349 /// note that in one case (stmt_semi), we've already
2350 /// seen the semicolon, and thus don't need another.
2351 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2353 hir::StmtDecl(ref d, _) => {
2355 hir::DeclLocal(_) => true,
2356 hir::DeclItem(_) => false,
2359 hir::StmtExpr(ref e, _) => {
2360 expr_requires_semi_to_be_stmt(&e)
2362 hir::StmtSemi(..) => {