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)?;
507 hir::TyTup(ref elts) => {
509 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
511 word(&mut self.s, ",")?;
515 hir::TyBareFn(ref f) => {
516 let generics = hir::Generics {
517 lifetimes: f.lifetimes.clone(),
518 ty_params: hir::HirVec::new(),
519 where_clause: hir::WhereClause {
520 id: ast::DUMMY_NODE_ID,
521 predicates: hir::HirVec::new(),
524 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
526 hir::TyPath(None, ref path) => {
527 self.print_path(path, false, 0)?;
529 hir::TyPath(Some(ref qself), ref path) => {
530 self.print_qpath(path, qself, false)?
532 hir::TyObjectSum(ref ty, ref bounds) => {
533 self.print_type(&ty)?;
534 self.print_bounds("+", &bounds[..])?;
536 hir::TyPolyTraitRef(ref bounds) => {
537 self.print_bounds("", &bounds[..])?;
539 hir::TyFixedLengthVec(ref ty, ref v) => {
540 word(&mut self.s, "[")?;
541 self.print_type(&ty)?;
542 word(&mut self.s, "; ")?;
543 self.print_expr(&v)?;
544 word(&mut self.s, "]")?;
546 hir::TyTypeof(ref e) => {
547 word(&mut self.s, "typeof(")?;
548 self.print_expr(&e)?;
549 word(&mut self.s, ")")?;
552 word(&mut self.s, "_")?;
558 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
559 self.hardbreak_if_not_bol()?;
560 self.maybe_print_comment(item.span.lo)?;
561 self.print_outer_attributes(&item.attrs)?;
563 hir::ForeignItemFn(ref decl, ref generics) => {
566 hir::Unsafety::Normal,
567 hir::Constness::NotConst,
572 self.end()?; // end head-ibox
573 word(&mut self.s, ";")?;
574 self.end() // end the outer fn box
576 hir::ForeignItemStatic(ref t, m) => {
577 self.head(&visibility_qualified(&item.vis, "static"))?;
579 self.word_space("mut")?;
581 self.print_name(item.name)?;
582 self.word_space(":")?;
583 self.print_type(&t)?;
584 word(&mut self.s, ";")?;
585 self.end()?; // end the head-ibox
586 self.end() // end the outer cbox
591 fn print_associated_const(&mut self,
594 default: Option<&hir::Expr>,
595 vis: &hir::Visibility)
597 word(&mut self.s, &visibility_qualified(vis, ""))?;
598 self.word_space("const")?;
599 self.print_name(name)?;
600 self.word_space(":")?;
601 self.print_type(ty)?;
602 if let Some(expr) = default {
604 self.word_space("=")?;
605 self.print_expr(expr)?;
607 word(&mut self.s, ";")
610 fn print_associated_type(&mut self,
612 bounds: Option<&hir::TyParamBounds>,
613 ty: Option<&hir::Ty>)
615 self.word_space("type")?;
616 self.print_name(name)?;
617 if let Some(bounds) = bounds {
618 self.print_bounds(":", bounds)?;
620 if let Some(ty) = ty {
622 self.word_space("=")?;
623 self.print_type(ty)?;
625 word(&mut self.s, ";")
628 pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
629 if let Some(krate) = self.krate {
630 // skip nested items if krate context was not provided
631 let item = &krate.items[&item_id.id];
632 self.print_item(item)
638 /// Pretty-print an item
639 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
640 self.hardbreak_if_not_bol()?;
641 self.maybe_print_comment(item.span.lo)?;
642 self.print_outer_attributes(&item.attrs)?;
643 self.ann.pre(self, NodeItem(item))?;
645 hir::ItemExternCrate(ref optional_path) => {
646 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
647 if let Some(p) = *optional_path {
648 let val = p.as_str();
649 if val.contains("-") {
650 self.print_string(&val, ast::StrStyle::Cooked)?;
655 word(&mut self.s, "as")?;
658 self.print_name(item.name)?;
659 word(&mut self.s, ";")?;
660 self.end()?; // end inner head-block
661 self.end()?; // end outer head-block
663 hir::ItemUse(ref vp) => {
664 self.head(&visibility_qualified(&item.vis, "use"))?;
665 self.print_view_path(&vp)?;
666 word(&mut self.s, ";")?;
667 self.end()?; // end inner head-block
668 self.end()?; // end outer head-block
670 hir::ItemStatic(ref ty, m, ref expr) => {
671 self.head(&visibility_qualified(&item.vis, "static"))?;
672 if m == hir::MutMutable {
673 self.word_space("mut")?;
675 self.print_name(item.name)?;
676 self.word_space(":")?;
677 self.print_type(&ty)?;
679 self.end()?; // end the head-ibox
681 self.word_space("=")?;
682 self.print_expr(&expr)?;
683 word(&mut self.s, ";")?;
684 self.end()?; // end the outer cbox
686 hir::ItemConst(ref ty, ref expr) => {
687 self.head(&visibility_qualified(&item.vis, "const"))?;
688 self.print_name(item.name)?;
689 self.word_space(":")?;
690 self.print_type(&ty)?;
692 self.end()?; // end the head-ibox
694 self.word_space("=")?;
695 self.print_expr(&expr)?;
696 word(&mut self.s, ";")?;
697 self.end()?; // end the outer cbox
699 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
708 word(&mut self.s, " ")?;
709 self.print_block_with_attrs(&body, &item.attrs)?;
711 hir::ItemMod(ref _mod) => {
712 self.head(&visibility_qualified(&item.vis, "mod"))?;
713 self.print_name(item.name)?;
716 self.print_mod(_mod, &item.attrs)?;
717 self.bclose(item.span)?;
719 hir::ItemForeignMod(ref nmod) => {
720 self.head("extern")?;
721 self.word_nbsp(&nmod.abi.to_string())?;
723 self.print_foreign_mod(nmod, &item.attrs)?;
724 self.bclose(item.span)?;
726 hir::ItemTy(ref ty, ref params) => {
727 self.ibox(indent_unit)?;
729 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
730 self.print_name(item.name)?;
731 self.print_generics(params)?;
732 self.end()?; // end the inner ibox
734 self.print_where_clause(¶ms.where_clause)?;
736 self.word_space("=")?;
737 self.print_type(&ty)?;
738 word(&mut self.s, ";")?;
739 self.end()?; // end the outer ibox
741 hir::ItemEnum(ref enum_definition, ref params) => {
742 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
744 hir::ItemStruct(ref struct_def, ref generics) => {
745 self.head(&visibility_qualified(&item.vis, "struct"))?;
746 self.print_struct(struct_def, generics, item.name, item.span, true)?;
749 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
751 self.print_visibility(&item.vis)?;
752 self.print_unsafety(unsafety)?;
753 self.word_nbsp("impl")?;
754 self.print_trait_ref(trait_ref)?;
756 self.word_space("for")?;
757 self.word_space("..")?;
759 self.bclose(item.span)?;
761 hir::ItemImpl(unsafety,
768 self.print_visibility(&item.vis)?;
769 self.print_unsafety(unsafety)?;
770 self.word_nbsp("impl")?;
772 if generics.is_parameterized() {
773 self.print_generics(generics)?;
778 hir::ImplPolarity::Negative => {
779 word(&mut self.s, "!")?;
786 self.print_trait_ref(t)?;
788 self.word_space("for")?;
793 self.print_type(&ty)?;
794 self.print_where_clause(&generics.where_clause)?;
798 self.print_inner_attributes(&item.attrs)?;
799 for impl_item in impl_items {
800 self.print_impl_item(impl_item)?;
802 self.bclose(item.span)?;
804 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
806 self.print_visibility(&item.vis)?;
807 self.print_unsafety(unsafety)?;
808 self.word_nbsp("trait")?;
809 self.print_name(item.name)?;
810 self.print_generics(generics)?;
811 let mut real_bounds = Vec::with_capacity(bounds.len());
812 for b in bounds.iter() {
813 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
815 self.word_space("for ?")?;
816 self.print_trait_ref(&ptr.trait_ref)?;
818 real_bounds.push(b.clone());
821 self.print_bounds(":", &real_bounds[..])?;
822 self.print_where_clause(&generics.where_clause)?;
823 word(&mut self.s, " ")?;
825 for trait_item in trait_items {
826 self.print_trait_item(trait_item)?;
828 self.bclose(item.span)?;
831 self.ann.post(self, NodeItem(item))
834 fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
835 self.print_path(&t.path, false, 0)
838 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
839 if !lifetimes.is_empty() {
840 word(&mut self.s, "for<")?;
841 let mut comma = false;
842 for lifetime_def in lifetimes {
844 self.word_space(",")?
846 self.print_lifetime_def(lifetime_def)?;
849 word(&mut self.s, ">")?;
854 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
855 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
856 self.print_trait_ref(&t.trait_ref)
859 pub fn print_enum_def(&mut self,
860 enum_definition: &hir::EnumDef,
861 generics: &hir::Generics,
863 span: syntax_pos::Span,
864 visibility: &hir::Visibility)
866 self.head(&visibility_qualified(visibility, "enum"))?;
867 self.print_name(name)?;
868 self.print_generics(generics)?;
869 self.print_where_clause(&generics.where_clause)?;
871 self.print_variants(&enum_definition.variants, span)
874 pub fn print_variants(&mut self,
875 variants: &[hir::Variant],
876 span: syntax_pos::Span)
880 self.space_if_not_bol()?;
881 self.maybe_print_comment(v.span.lo)?;
882 self.print_outer_attributes(&v.node.attrs)?;
883 self.ibox(indent_unit)?;
884 self.print_variant(v)?;
885 word(&mut self.s, ",")?;
887 self.maybe_print_trailing_comment(v.span, None)?;
892 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
894 hir::Public => self.word_nbsp("pub"),
895 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
896 hir::Visibility::Restricted { ref path, .. } =>
897 self.word_nbsp(&format!("pub({})", path)),
898 hir::Inherited => Ok(()),
902 pub fn print_struct(&mut self,
903 struct_def: &hir::VariantData,
904 generics: &hir::Generics,
906 span: syntax_pos::Span,
907 print_finalizer: bool)
909 self.print_name(name)?;
910 self.print_generics(generics)?;
911 if !struct_def.is_struct() {
912 if struct_def.is_tuple() {
914 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
915 s.maybe_print_comment(field.span.lo)?;
916 s.print_outer_attributes(&field.attrs)?;
917 s.print_visibility(&field.vis)?;
918 s.print_type(&field.ty)
922 self.print_where_clause(&generics.where_clause)?;
924 word(&mut self.s, ";")?;
927 self.end() // close the outer-box
929 self.print_where_clause(&generics.where_clause)?;
932 self.hardbreak_if_not_bol()?;
934 for field in struct_def.fields() {
935 self.hardbreak_if_not_bol()?;
936 self.maybe_print_comment(field.span.lo)?;
937 self.print_outer_attributes(&field.attrs)?;
938 self.print_visibility(&field.vis)?;
939 self.print_name(field.name)?;
940 self.word_nbsp(":")?;
941 self.print_type(&field.ty)?;
942 word(&mut self.s, ",")?;
949 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
951 let generics = hir::Generics::empty();
952 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
953 match v.node.disr_expr {
956 self.word_space("=")?;
962 pub fn print_method_sig(&mut self,
965 vis: &hir::Visibility)
967 self.print_fn(&m.decl,
976 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
977 self.ann.pre(self, NodeSubItem(ti.id))?;
978 self.hardbreak_if_not_bol()?;
979 self.maybe_print_comment(ti.span.lo)?;
980 self.print_outer_attributes(&ti.attrs)?;
982 hir::ConstTraitItem(ref ty, ref default) => {
983 self.print_associated_const(ti.name,
985 default.as_ref().map(|expr| &**expr),
988 hir::MethodTraitItem(ref sig, ref body) => {
992 self.print_method_sig(ti.name, sig, &hir::Inherited)?;
993 if let Some(ref body) = *body {
995 self.print_block_with_attrs(body, &ti.attrs)?;
997 word(&mut self.s, ";")?;
1000 hir::TypeTraitItem(ref bounds, ref default) => {
1001 self.print_associated_type(ti.name,
1003 default.as_ref().map(|ty| &**ty))?;
1006 self.ann.post(self, NodeSubItem(ti.id))
1009 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1010 self.ann.pre(self, NodeSubItem(ii.id))?;
1011 self.hardbreak_if_not_bol()?;
1012 self.maybe_print_comment(ii.span.lo)?;
1013 self.print_outer_attributes(&ii.attrs)?;
1015 if let hir::Defaultness::Default = ii.defaultness {
1016 self.word_nbsp("default")?;
1020 hir::ImplItemKind::Const(ref ty, ref expr) => {
1021 self.print_associated_const(ii.name, &ty, Some(&expr), &ii.vis)?;
1023 hir::ImplItemKind::Method(ref sig, ref body) => {
1025 self.print_method_sig(ii.name, sig, &ii.vis)?;
1027 self.print_block_with_attrs(body, &ii.attrs)?;
1029 hir::ImplItemKind::Type(ref ty) => {
1030 self.print_associated_type(ii.name, None, Some(ty))?;
1033 self.ann.post(self, NodeSubItem(ii.id))
1036 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1037 self.maybe_print_comment(st.span.lo)?;
1039 hir::StmtDecl(ref decl, _) => {
1040 self.print_decl(&decl)?;
1042 hir::StmtExpr(ref expr, _) => {
1043 self.space_if_not_bol()?;
1044 self.print_expr(&expr)?;
1046 hir::StmtSemi(ref expr, _) => {
1047 self.space_if_not_bol()?;
1048 self.print_expr(&expr)?;
1049 word(&mut self.s, ";")?;
1052 if stmt_ends_with_semi(&st.node) {
1053 word(&mut self.s, ";")?;
1055 self.maybe_print_trailing_comment(st.span, None)
1058 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1059 self.print_block_with_attrs(blk, &[])
1062 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1063 self.print_block_unclosed_indent(blk, indent_unit)
1066 pub fn print_block_unclosed_indent(&mut self,
1070 self.print_block_maybe_unclosed(blk, indented, &[], false)
1073 pub fn print_block_with_attrs(&mut self,
1075 attrs: &[ast::Attribute])
1077 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1080 pub fn print_block_maybe_unclosed(&mut self,
1083 attrs: &[ast::Attribute],
1087 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1088 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1089 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1090 hir::PushUnstableBlock => self.word_space("push_unstable")?,
1091 hir::PopUnstableBlock => self.word_space("pop_unstable")?,
1092 hir::DefaultBlock => (),
1094 self.maybe_print_comment(blk.span.lo)?;
1095 self.ann.pre(self, NodeBlock(blk))?;
1098 self.print_inner_attributes(attrs)?;
1100 for st in &blk.stmts {
1101 self.print_stmt(st)?;
1105 self.space_if_not_bol()?;
1106 self.print_expr(&expr)?;
1107 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1111 self.bclose_maybe_open(blk.span, indented, close_box)?;
1112 self.ann.post(self, NodeBlock(blk))
1115 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1119 // "another else-if"
1120 hir::ExprIf(ref i, ref then, ref e) => {
1121 self.cbox(indent_unit - 1)?;
1123 word(&mut self.s, " else if ")?;
1124 self.print_expr(&i)?;
1125 space(&mut self.s)?;
1126 self.print_block(&then)?;
1127 self.print_else(e.as_ref().map(|e| &**e))
1130 hir::ExprBlock(ref b) => {
1131 self.cbox(indent_unit - 1)?;
1133 word(&mut self.s, " else ")?;
1134 self.print_block(&b)
1136 // BLEAH, constraints would be great here
1138 panic!("print_if saw if with weird alternative");
1146 pub fn print_if(&mut self,
1149 elseopt: Option<&hir::Expr>)
1152 self.print_expr(test)?;
1153 space(&mut self.s)?;
1154 self.print_block(blk)?;
1155 self.print_else(elseopt)
1158 pub fn print_if_let(&mut self,
1162 elseopt: Option<&hir::Expr>)
1164 self.head("if let")?;
1165 self.print_pat(pat)?;
1166 space(&mut self.s)?;
1167 self.word_space("=")?;
1168 self.print_expr(expr)?;
1169 space(&mut self.s)?;
1170 self.print_block(blk)?;
1171 self.print_else(elseopt)
1175 fn print_call_post(&mut self, args: &[P<hir::Expr>]) -> io::Result<()> {
1177 self.commasep_exprs(Inconsistent, args)?;
1181 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1182 let needs_par = needs_parentheses(expr);
1186 self.print_expr(expr)?;
1193 fn print_expr_vec(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1194 self.ibox(indent_unit)?;
1195 word(&mut self.s, "[")?;
1196 self.commasep_exprs(Inconsistent, &exprs[..])?;
1197 word(&mut self.s, "]")?;
1201 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1202 self.ibox(indent_unit)?;
1203 word(&mut self.s, "[")?;
1204 self.print_expr(element)?;
1205 self.word_space(";")?;
1206 self.print_expr(count)?;
1207 word(&mut self.s, "]")?;
1211 fn print_expr_struct(&mut self,
1213 fields: &[hir::Field],
1214 wth: &Option<P<hir::Expr>>)
1216 self.print_path(path, true, 0)?;
1217 word(&mut self.s, "{")?;
1218 self.commasep_cmnt(Consistent,
1221 s.ibox(indent_unit)?;
1222 s.print_name(field.name.node)?;
1224 s.print_expr(&field.expr)?;
1230 self.ibox(indent_unit)?;
1231 if !fields.is_empty() {
1232 word(&mut self.s, ",")?;
1233 space(&mut self.s)?;
1235 word(&mut self.s, "..")?;
1236 self.print_expr(&expr)?;
1239 _ => if !fields.is_empty() {
1240 word(&mut self.s, ",")?
1243 word(&mut self.s, "}")?;
1247 fn print_expr_tup(&mut self, exprs: &[P<hir::Expr>]) -> io::Result<()> {
1249 self.commasep_exprs(Inconsistent, &exprs[..])?;
1250 if exprs.len() == 1 {
1251 word(&mut self.s, ",")?;
1256 fn print_expr_call(&mut self, func: &hir::Expr, args: &[P<hir::Expr>]) -> io::Result<()> {
1257 self.print_expr_maybe_paren(func)?;
1258 self.print_call_post(args)
1261 fn print_expr_method_call(&mut self,
1262 name: Spanned<ast::Name>,
1264 args: &[P<hir::Expr>])
1266 let base_args = &args[1..];
1267 self.print_expr(&args[0])?;
1268 word(&mut self.s, ".")?;
1269 self.print_name(name.node)?;
1270 if !tys.is_empty() {
1271 word(&mut self.s, "::<")?;
1272 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1273 word(&mut self.s, ">")?;
1275 self.print_call_post(base_args)
1278 fn print_expr_binary(&mut self,
1283 self.print_expr(lhs)?;
1284 space(&mut self.s)?;
1285 self.word_space(op.node.as_str())?;
1286 self.print_expr(rhs)
1289 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1290 word(&mut self.s, op.as_str())?;
1291 self.print_expr_maybe_paren(expr)
1294 fn print_expr_addr_of(&mut self,
1295 mutability: hir::Mutability,
1298 word(&mut self.s, "&")?;
1299 self.print_mutability(mutability)?;
1300 self.print_expr_maybe_paren(expr)
1303 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1304 self.maybe_print_comment(expr.span.lo)?;
1305 self.ibox(indent_unit)?;
1306 self.ann.pre(self, NodeExpr(expr))?;
1308 hir::ExprBox(ref expr) => {
1309 self.word_space("box")?;
1310 self.print_expr(expr)?;
1312 hir::ExprVec(ref exprs) => {
1313 self.print_expr_vec(&exprs[..])?;
1315 hir::ExprRepeat(ref element, ref count) => {
1316 self.print_expr_repeat(&element, &count)?;
1318 hir::ExprStruct(ref path, ref fields, ref wth) => {
1319 self.print_expr_struct(path, &fields[..], wth)?;
1321 hir::ExprTup(ref exprs) => {
1322 self.print_expr_tup(&exprs[..])?;
1324 hir::ExprCall(ref func, ref args) => {
1325 self.print_expr_call(&func, &args[..])?;
1327 hir::ExprMethodCall(name, ref tys, ref args) => {
1328 self.print_expr_method_call(name, &tys[..], &args[..])?;
1330 hir::ExprBinary(op, ref lhs, ref rhs) => {
1331 self.print_expr_binary(op, &lhs, &rhs)?;
1333 hir::ExprUnary(op, ref expr) => {
1334 self.print_expr_unary(op, &expr)?;
1336 hir::ExprAddrOf(m, ref expr) => {
1337 self.print_expr_addr_of(m, &expr)?;
1339 hir::ExprLit(ref lit) => {
1340 self.print_literal(&lit)?;
1342 hir::ExprCast(ref expr, ref ty) => {
1343 self.print_expr(&expr)?;
1344 space(&mut self.s)?;
1345 self.word_space("as")?;
1346 self.print_type(&ty)?;
1348 hir::ExprType(ref expr, ref ty) => {
1349 self.print_expr(&expr)?;
1350 self.word_space(":")?;
1351 self.print_type(&ty)?;
1353 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1354 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1356 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1357 if let Some(sp_name) = opt_sp_name {
1358 self.print_name(sp_name.node)?;
1359 self.word_space(":")?;
1361 self.head("while")?;
1362 self.print_expr(&test)?;
1363 space(&mut self.s)?;
1364 self.print_block(&blk)?;
1366 hir::ExprLoop(ref blk, opt_sp_name) => {
1367 if let Some(sp_name) = opt_sp_name {
1368 self.print_name(sp_name.node)?;
1369 self.word_space(":")?;
1372 space(&mut self.s)?;
1373 self.print_block(&blk)?;
1375 hir::ExprMatch(ref expr, ref arms, _) => {
1376 self.cbox(indent_unit)?;
1378 self.word_nbsp("match")?;
1379 self.print_expr(&expr)?;
1380 space(&mut self.s)?;
1383 self.print_arm(arm)?;
1385 self.bclose_(expr.span, indent_unit)?;
1387 hir::ExprClosure(capture_clause, ref decl, ref body, _fn_decl_span) => {
1388 self.print_capture_clause(capture_clause)?;
1390 self.print_fn_block_args(&decl)?;
1391 space(&mut self.s)?;
1393 let default_return = match decl.output {
1394 hir::DefaultReturn(..) => true,
1398 if !default_return || !body.stmts.is_empty() || body.expr.is_none() {
1399 self.print_block_unclosed(&body)?;
1401 // we extract the block, so as not to create another set of boxes
1402 match body.expr.as_ref().unwrap().node {
1403 hir::ExprBlock(ref blk) => {
1404 self.print_block_unclosed(&blk)?;
1407 // this is a bare expression
1408 self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap())?;
1409 self.end()?; // need to close a box
1413 // a box will be closed by print_expr, but we didn't want an overall
1414 // wrapper so we closed the corresponding opening. so create an
1415 // empty box to satisfy the close.
1418 hir::ExprBlock(ref blk) => {
1419 // containing cbox, will be closed by print-block at }
1420 self.cbox(indent_unit)?;
1421 // head-box, will be closed by print-block after {
1423 self.print_block(&blk)?;
1425 hir::ExprAssign(ref lhs, ref rhs) => {
1426 self.print_expr(&lhs)?;
1427 space(&mut self.s)?;
1428 self.word_space("=")?;
1429 self.print_expr(&rhs)?;
1431 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1432 self.print_expr(&lhs)?;
1433 space(&mut self.s)?;
1434 word(&mut self.s, op.node.as_str())?;
1435 self.word_space("=")?;
1436 self.print_expr(&rhs)?;
1438 hir::ExprField(ref expr, name) => {
1439 self.print_expr(&expr)?;
1440 word(&mut self.s, ".")?;
1441 self.print_name(name.node)?;
1443 hir::ExprTupField(ref expr, id) => {
1444 self.print_expr(&expr)?;
1445 word(&mut self.s, ".")?;
1446 self.print_usize(id.node)?;
1448 hir::ExprIndex(ref expr, ref index) => {
1449 self.print_expr(&expr)?;
1450 word(&mut self.s, "[")?;
1451 self.print_expr(&index)?;
1452 word(&mut self.s, "]")?;
1454 hir::ExprPath(None, ref path) => {
1455 self.print_path(path, true, 0)?
1457 hir::ExprPath(Some(ref qself), ref path) => {
1458 self.print_qpath(path, qself, true)?
1460 hir::ExprBreak(opt_name) => {
1461 word(&mut self.s, "break")?;
1462 space(&mut self.s)?;
1463 if let Some(name) = opt_name {
1464 self.print_name(name.node)?;
1465 space(&mut self.s)?;
1468 hir::ExprAgain(opt_name) => {
1469 word(&mut self.s, "continue")?;
1470 space(&mut self.s)?;
1471 if let Some(name) = opt_name {
1472 self.print_name(name.node)?;
1476 hir::ExprRet(ref result) => {
1477 word(&mut self.s, "return")?;
1480 word(&mut self.s, " ")?;
1481 self.print_expr(&expr)?;
1486 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1487 word(&mut self.s, "asm!")?;
1489 self.print_string(&a.asm, a.asm_str_style)?;
1490 self.word_space(":")?;
1492 let mut out_idx = 0;
1493 self.commasep(Inconsistent, &a.outputs, |s, out| {
1494 let mut ch = out.constraint.chars();
1496 Some('=') if out.is_rw => {
1497 s.print_string(&format!("+{}", ch.as_str()),
1498 ast::StrStyle::Cooked)?
1500 _ => s.print_string(&out.constraint,
1501 ast::StrStyle::Cooked)?,
1504 s.print_expr(&outputs[out_idx])?;
1509 space(&mut self.s)?;
1510 self.word_space(":")?;
1513 self.commasep(Inconsistent, &a.inputs, |s, co| {
1514 s.print_string(&co, ast::StrStyle::Cooked)?;
1516 s.print_expr(&inputs[in_idx])?;
1521 space(&mut self.s)?;
1522 self.word_space(":")?;
1524 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1525 s.print_string(&co, ast::StrStyle::Cooked)?;
1529 let mut options = vec![];
1531 options.push("volatile");
1534 options.push("alignstack");
1536 if a.dialect == ast::AsmDialect::Intel {
1537 options.push("intel");
1540 if !options.is_empty() {
1541 space(&mut self.s)?;
1542 self.word_space(":")?;
1543 self.commasep(Inconsistent, &options, |s, &co| {
1544 s.print_string(co, ast::StrStyle::Cooked)?;
1552 self.ann.post(self, NodeExpr(expr))?;
1556 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1557 self.print_pat(&loc.pat)?;
1558 if let Some(ref ty) = loc.ty {
1559 self.word_space(":")?;
1560 self.print_type(&ty)?;
1565 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1566 self.maybe_print_comment(decl.span.lo)?;
1568 hir::DeclLocal(ref loc) => {
1569 self.space_if_not_bol()?;
1570 self.ibox(indent_unit)?;
1571 self.word_nbsp("let")?;
1573 self.ibox(indent_unit)?;
1574 self.print_local_decl(&loc)?;
1576 if let Some(ref init) = loc.init {
1578 self.word_space("=")?;
1579 self.print_expr(&init)?;
1583 hir::DeclItem(ref item) => {
1584 self.print_item_id(item)
1589 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1590 word(&mut self.s, &i.to_string())
1593 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1594 word(&mut self.s, &name.as_str())?;
1595 self.ann.post(self, NodeName(&name))
1598 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1599 self.print_local_decl(loc)?;
1600 space(&mut self.s)?;
1601 self.word_space("in")?;
1602 self.print_expr(coll)
1605 fn print_path(&mut self,
1607 colons_before_params: bool,
1610 self.maybe_print_comment(path.span.lo)?;
1612 let mut first = !path.global;
1613 for segment in &path.segments[..path.segments.len() - depth] {
1617 word(&mut self.s, "::")?
1620 self.print_name(segment.name)?;
1622 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1628 fn print_qpath(&mut self,
1631 colons_before_params: bool)
1633 word(&mut self.s, "<")?;
1634 self.print_type(&qself.ty)?;
1635 if qself.position > 0 {
1636 space(&mut self.s)?;
1637 self.word_space("as")?;
1638 let depth = path.segments.len() - qself.position;
1639 self.print_path(&path, false, depth)?;
1641 word(&mut self.s, ">")?;
1642 word(&mut self.s, "::")?;
1643 let item_segment = path.segments.last().unwrap();
1644 self.print_name(item_segment.name)?;
1645 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1648 fn print_path_parameters(&mut self,
1649 parameters: &hir::PathParameters,
1650 colons_before_params: bool)
1652 if parameters.is_empty() {
1656 if colons_before_params {
1657 word(&mut self.s, "::")?
1661 hir::AngleBracketedParameters(ref data) => {
1662 word(&mut self.s, "<")?;
1664 let mut comma = false;
1665 for lifetime in &data.lifetimes {
1667 self.word_space(",")?
1669 self.print_lifetime(lifetime)?;
1673 if !data.types.is_empty() {
1675 self.word_space(",")?
1677 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1681 for binding in data.bindings.iter() {
1683 self.word_space(",")?
1685 self.print_name(binding.name)?;
1686 space(&mut self.s)?;
1687 self.word_space("=")?;
1688 self.print_type(&binding.ty)?;
1692 word(&mut self.s, ">")?
1695 hir::ParenthesizedParameters(ref data) => {
1696 word(&mut self.s, "(")?;
1697 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1698 word(&mut self.s, ")")?;
1700 if let Some(ref ty) = data.output {
1701 self.space_if_not_bol()?;
1702 self.word_space("->")?;
1703 self.print_type(&ty)?;
1711 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1712 self.maybe_print_comment(pat.span.lo)?;
1713 self.ann.pre(self, NodePat(pat))?;
1714 // Pat isn't normalized, but the beauty of it
1715 // is that it doesn't matter
1717 PatKind::Wild => word(&mut self.s, "_")?,
1718 PatKind::Binding(binding_mode, ref path1, ref sub) => {
1719 match binding_mode {
1720 hir::BindByRef(mutbl) => {
1721 self.word_nbsp("ref")?;
1722 self.print_mutability(mutbl)?;
1724 hir::BindByValue(hir::MutImmutable) => {}
1725 hir::BindByValue(hir::MutMutable) => {
1726 self.word_nbsp("mut")?;
1729 self.print_name(path1.node)?;
1730 if let Some(ref p) = *sub {
1731 word(&mut self.s, "@")?;
1732 self.print_pat(&p)?;
1735 PatKind::TupleStruct(ref path, ref elts, ddpos) => {
1736 self.print_path(path, true, 0)?;
1738 if let Some(ddpos) = ddpos {
1739 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1741 self.word_space(",")?;
1743 word(&mut self.s, "..")?;
1744 if ddpos != elts.len() {
1745 word(&mut self.s, ",")?;
1746 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1749 try!(self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p)));
1751 try!(self.pclose());
1753 PatKind::Path(None, ref path) => {
1754 self.print_path(path, true, 0)?;
1756 PatKind::Path(Some(ref qself), ref path) => {
1757 self.print_qpath(path, qself, false)?;
1759 PatKind::Struct(ref path, ref fields, etc) => {
1760 self.print_path(path, true, 0)?;
1762 self.word_space("{")?;
1763 self.commasep_cmnt(Consistent,
1766 s.cbox(indent_unit)?;
1767 if !f.node.is_shorthand {
1768 s.print_name(f.node.name)?;
1771 s.print_pat(&f.node.pat)?;
1774 |f| f.node.pat.span)?;
1776 if !fields.is_empty() {
1777 self.word_space(",")?;
1779 word(&mut self.s, "..")?;
1781 space(&mut self.s)?;
1782 word(&mut self.s, "}")?;
1784 PatKind::Tuple(ref elts, ddpos) => {
1786 if let Some(ddpos) = ddpos {
1787 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1789 self.word_space(",")?;
1791 word(&mut self.s, "..")?;
1792 if ddpos != elts.len() {
1793 word(&mut self.s, ",")?;
1794 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1797 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1798 if elts.len() == 1 {
1799 word(&mut self.s, ",")?;
1804 PatKind::Box(ref inner) => {
1805 word(&mut self.s, "box ")?;
1806 self.print_pat(&inner)?;
1808 PatKind::Ref(ref inner, mutbl) => {
1809 word(&mut self.s, "&")?;
1810 if mutbl == hir::MutMutable {
1811 word(&mut self.s, "mut ")?;
1813 self.print_pat(&inner)?;
1815 PatKind::Lit(ref e) => self.print_expr(&e)?,
1816 PatKind::Range(ref begin, ref end) => {
1817 self.print_expr(&begin)?;
1818 space(&mut self.s)?;
1819 word(&mut self.s, "...")?;
1820 self.print_expr(&end)?;
1822 PatKind::Vec(ref before, ref slice, ref after) => {
1823 word(&mut self.s, "[")?;
1824 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1825 if let Some(ref p) = *slice {
1826 if !before.is_empty() {
1827 self.word_space(",")?;
1829 if p.node != PatKind::Wild {
1830 self.print_pat(&p)?;
1832 word(&mut self.s, "..")?;
1833 if !after.is_empty() {
1834 self.word_space(",")?;
1837 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1838 word(&mut self.s, "]")?;
1841 self.ann.post(self, NodePat(pat))
1844 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1845 // I have no idea why this check is necessary, but here it
1847 if arm.attrs.is_empty() {
1848 space(&mut self.s)?;
1850 self.cbox(indent_unit)?;
1852 self.print_outer_attributes(&arm.attrs)?;
1853 let mut first = true;
1854 for p in &arm.pats {
1858 space(&mut self.s)?;
1859 self.word_space("|")?;
1861 self.print_pat(&p)?;
1863 space(&mut self.s)?;
1864 if let Some(ref e) = arm.guard {
1865 self.word_space("if")?;
1866 self.print_expr(&e)?;
1867 space(&mut self.s)?;
1869 self.word_space("=>")?;
1871 match arm.body.node {
1872 hir::ExprBlock(ref blk) => {
1873 // the block will close the pattern's ibox
1874 self.print_block_unclosed_indent(&blk, indent_unit)?;
1876 // If it is a user-provided unsafe block, print a comma after it
1877 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1878 word(&mut self.s, ",")?;
1882 self.end()?; // close the ibox for the pattern
1883 self.print_expr(&arm.body)?;
1884 word(&mut self.s, ",")?;
1887 self.end() // close enclosing cbox
1890 fn print_explicit_self(&mut self, explicit_self: &hir::ExplicitSelf) -> io::Result<()> {
1891 match explicit_self.node {
1892 SelfKind::Value(m) => {
1893 self.print_mutability(m)?;
1894 word(&mut self.s, "self")
1896 SelfKind::Region(ref lt, m) => {
1897 word(&mut self.s, "&")?;
1898 self.print_opt_lifetime(lt)?;
1899 self.print_mutability(m)?;
1900 word(&mut self.s, "self")
1902 SelfKind::Explicit(ref typ, m) => {
1903 self.print_mutability(m)?;
1904 word(&mut self.s, "self")?;
1905 self.word_space(":")?;
1906 self.print_type(&typ)
1911 pub fn print_fn(&mut self,
1913 unsafety: hir::Unsafety,
1914 constness: hir::Constness,
1916 name: Option<ast::Name>,
1917 generics: &hir::Generics,
1918 vis: &hir::Visibility)
1920 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1922 if let Some(name) = name {
1924 self.print_name(name)?;
1926 self.print_generics(generics)?;
1927 self.print_fn_args_and_ret(decl)?;
1928 self.print_where_clause(&generics.where_clause)
1931 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1933 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
1935 word(&mut self.s, ", ...")?;
1939 self.print_fn_output(decl)
1942 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1943 word(&mut self.s, "|")?;
1944 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
1945 word(&mut self.s, "|")?;
1947 if let hir::DefaultReturn(..) = decl.output {
1951 self.space_if_not_bol()?;
1952 self.word_space("->")?;
1954 hir::Return(ref ty) => {
1955 self.print_type(&ty)?;
1956 self.maybe_print_comment(ty.span.lo)
1958 hir::DefaultReturn(..) => unreachable!(),
1959 hir::NoReturn(span) => {
1960 self.word_nbsp("!")?;
1961 self.maybe_print_comment(span.lo)
1966 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
1967 match capture_clause {
1968 hir::CaptureByValue => self.word_space("move"),
1969 hir::CaptureByRef => Ok(()),
1973 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
1974 if !bounds.is_empty() {
1975 word(&mut self.s, prefix)?;
1976 let mut first = true;
1977 for bound in bounds {
1982 self.word_space("+")?;
1986 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
1987 self.print_poly_trait_ref(tref)
1989 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
1990 word(&mut self.s, "?")?;
1991 self.print_poly_trait_ref(tref)
1993 RegionTyParamBound(ref lt) => {
1994 self.print_lifetime(lt)
2004 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2005 self.print_name(lifetime.name)
2008 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2009 self.print_lifetime(&lifetime.lifetime)?;
2011 for v in &lifetime.bounds {
2012 word(&mut self.s, sep)?;
2013 self.print_lifetime(v)?;
2019 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2020 let total = generics.lifetimes.len() + generics.ty_params.len();
2025 word(&mut self.s, "<")?;
2027 let mut ints = Vec::new();
2032 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2033 if idx < generics.lifetimes.len() {
2034 let lifetime = &generics.lifetimes[idx];
2035 s.print_lifetime_def(lifetime)
2037 let idx = idx - generics.lifetimes.len();
2038 let param = &generics.ty_params[idx];
2039 s.print_ty_param(param)
2043 word(&mut self.s, ">")?;
2047 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2048 self.print_name(param.name)?;
2049 self.print_bounds(":", ¶m.bounds)?;
2050 match param.default {
2051 Some(ref default) => {
2052 space(&mut self.s)?;
2053 self.word_space("=")?;
2054 self.print_type(&default)
2060 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2061 if where_clause.predicates.is_empty() {
2065 space(&mut self.s)?;
2066 self.word_space("where")?;
2068 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2070 self.word_space(",")?;
2074 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2078 self.print_formal_lifetime_list(bound_lifetimes)?;
2079 self.print_type(&bounded_ty)?;
2080 self.print_bounds(":", bounds)?;
2082 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2085 self.print_lifetime(lifetime)?;
2086 word(&mut self.s, ":")?;
2088 for (i, bound) in bounds.iter().enumerate() {
2089 self.print_lifetime(bound)?;
2092 word(&mut self.s, ":")?;
2096 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2097 self.print_path(path, false, 0)?;
2098 space(&mut self.s)?;
2099 self.word_space("=")?;
2100 self.print_type(&ty)?;
2108 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2110 hir::ViewPathSimple(name, ref path) => {
2111 self.print_path(path, false, 0)?;
2113 if path.segments.last().unwrap().name != name {
2114 space(&mut self.s)?;
2115 self.word_space("as")?;
2116 self.print_name(name)?;
2122 hir::ViewPathGlob(ref path) => {
2123 self.print_path(path, false, 0)?;
2124 word(&mut self.s, "::*")
2127 hir::ViewPathList(ref path, ref segments) => {
2128 if path.segments.is_empty() {
2129 word(&mut self.s, "{")?;
2131 self.print_path(path, false, 0)?;
2132 word(&mut self.s, "::{")?;
2134 self.commasep(Inconsistent, &segments[..], |s, w| {
2136 hir::PathListIdent { name, .. } => {
2139 hir::PathListMod { .. } => {
2140 word(&mut s.s, "self")
2144 word(&mut self.s, "}")
2149 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2151 hir::MutMutable => self.word_nbsp("mut"),
2152 hir::MutImmutable => Ok(()),
2156 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2157 self.print_mutability(mt.mutbl)?;
2158 self.print_type(&mt.ty)
2161 pub fn print_arg(&mut self, input: &hir::Arg, is_closure: bool) -> io::Result<()> {
2162 self.ibox(indent_unit)?;
2163 match input.ty.node {
2164 hir::TyInfer if is_closure => self.print_pat(&input.pat)?,
2166 if let Some(eself) = input.to_self() {
2167 self.print_explicit_self(&eself)?;
2169 let invalid = if let PatKind::Binding(_, name, _) = input.pat.node {
2170 name.node == keywords::Invalid.name()
2175 self.print_pat(&input.pat)?;
2176 word(&mut self.s, ":")?;
2177 space(&mut self.s)?;
2179 self.print_type(&input.ty)?;
2186 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2187 if let hir::DefaultReturn(..) = decl.output {
2191 self.space_if_not_bol()?;
2192 self.ibox(indent_unit)?;
2193 self.word_space("->")?;
2195 hir::NoReturn(_) => self.word_nbsp("!")?,
2196 hir::DefaultReturn(..) => unreachable!(),
2197 hir::Return(ref ty) => self.print_type(&ty)?,
2202 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2207 pub fn print_ty_fn(&mut self,
2209 unsafety: hir::Unsafety,
2211 name: Option<ast::Name>,
2212 generics: &hir::Generics)
2214 self.ibox(indent_unit)?;
2215 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2216 word(&mut self.s, "for")?;
2217 self.print_generics(generics)?;
2219 let generics = hir::Generics {
2220 lifetimes: hir::HirVec::new(),
2221 ty_params: hir::HirVec::new(),
2222 where_clause: hir::WhereClause {
2223 id: ast::DUMMY_NODE_ID,
2224 predicates: hir::HirVec::new(),
2229 hir::Constness::NotConst,
2237 pub fn maybe_print_trailing_comment(&mut self,
2238 span: syntax_pos::Span,
2239 next_pos: Option<BytePos>)
2241 let cm = match self.cm {
2245 if let Some(ref cmnt) = self.next_comment() {
2246 if (*cmnt).style != comments::Trailing {
2249 let span_line = cm.lookup_char_pos(span.hi);
2250 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2251 let mut next = (*cmnt).pos + BytePos(1);
2252 if let Some(p) = next_pos {
2255 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2256 span_line.line == comment_line.line {
2257 self.print_comment(cmnt)?;
2258 self.cur_cmnt_and_lit.cur_cmnt += 1;
2264 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2265 // If there aren't any remaining comments, then we need to manually
2266 // make sure there is a line break at the end.
2267 if self.next_comment().is_none() {
2268 hardbreak(&mut self.s)?;
2271 match self.next_comment() {
2273 self.print_comment(cmnt)?;
2274 self.cur_cmnt_and_lit.cur_cmnt += 1;
2282 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2283 opt_abi: Option<Abi>)
2286 Some(Abi::Rust) => Ok(()),
2288 self.word_nbsp("extern")?;
2289 self.word_nbsp(&abi.to_string())
2295 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2298 self.word_nbsp("extern")?;
2299 self.word_nbsp(&abi.to_string())
2305 pub fn print_fn_header_info(&mut self,
2306 unsafety: hir::Unsafety,
2307 constness: hir::Constness,
2309 vis: &hir::Visibility)
2311 word(&mut self.s, &visibility_qualified(vis, ""))?;
2312 self.print_unsafety(unsafety)?;
2315 hir::Constness::NotConst => {}
2316 hir::Constness::Const => self.word_nbsp("const")?,
2319 if abi != Abi::Rust {
2320 self.word_nbsp("extern")?;
2321 self.word_nbsp(&abi.to_string())?;
2324 word(&mut self.s, "fn")
2327 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2329 hir::Unsafety::Normal => Ok(()),
2330 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2335 // Dup'ed from parse::classify, but adapted for the HIR.
2336 /// Does this expression require a semicolon to be treated
2337 /// as a statement? The negation of this: 'can this expression
2338 /// be used as a statement without a semicolon' -- is used
2339 /// as an early-bail-out in the parser so that, for instance,
2340 /// if true {...} else {...}
2342 /// isn't parsed as (if true {...} else {...} | x) | 5
2343 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2346 hir::ExprMatch(..) |
2348 hir::ExprWhile(..) |
2349 hir::ExprLoop(..) => false,
2354 /// this statement requires a semicolon after it.
2355 /// note that in one case (stmt_semi), we've already
2356 /// seen the semicolon, and thus don't need another.
2357 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2359 hir::StmtDecl(ref d, _) => {
2361 hir::DeclLocal(_) => true,
2362 hir::DeclItem(_) => false,
2365 hir::StmtExpr(ref e, _) => {
2366 expr_requires_semi_to_be_stmt(&e)
2368 hir::StmtSemi(..) => {