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, 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::symbol::keywords;
24 use syntax_pos::{self, BytePos};
28 use hir::{Crate, PatKind, RegionTyParamBound, SelfKind, TraitTyParamBound, TraitBoundModifier};
30 use std::io::{self, Write, Read};
32 pub enum AnnNode<'a> {
33 NodeName(&'a ast::Name),
34 NodeBlock(&'a hir::Block),
35 NodeItem(&'a hir::Item),
36 NodeSubItem(ast::NodeId),
37 NodeExpr(&'a hir::Expr),
38 NodePat(&'a hir::Pat),
42 fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
45 fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
50 #[derive(Copy, Clone)]
53 impl PpAnn for NoAnn {}
56 pub struct State<'a> {
57 krate: Option<&'a Crate>,
58 pub s: pp::Printer<'a>,
59 cm: Option<&'a CodeMap>,
60 comments: Option<Vec<comments::Comment>>,
61 literals: Option<Vec<comments::Literal>>,
62 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral,
63 boxes: Vec<pp::Breaks>,
64 ann: &'a (PpAnn + 'a),
67 impl<'a> PrintState<'a> for State<'a> {
68 fn writer(&mut self) -> &mut pp::Printer<'a> {
72 fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
76 fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
80 fn cur_cmnt_and_lit(&mut self) -> &mut ast_pp::CurrentCommentAndLiteral {
81 &mut self.cur_cmnt_and_lit
84 fn literals(&self) -> &Option<Vec<comments::Literal>> {
89 pub fn rust_printer<'a>(writer: Box<Write + 'a>, krate: Option<&'a Crate>) -> State<'a> {
90 static NO_ANN: NoAnn = NoAnn;
91 rust_printer_annotated(writer, &NO_ANN, krate)
94 pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>,
96 krate: Option<&'a Crate>)
100 s: pp::mk_printer(writer, default_columns),
104 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
113 #[allow(non_upper_case_globals)]
114 pub const indent_unit: usize = 4;
116 #[allow(non_upper_case_globals)]
117 pub const default_columns: usize = 78;
120 /// Requires you to pass an input filename and reader so that
121 /// it can scan the input text for comments and literals to
123 pub fn print_crate<'a>(cm: &'a CodeMap,
124 span_diagnostic: &errors::Handler,
128 out: Box<Write + 'a>,
132 let mut s = State::new_from_input(cm, span_diagnostic, filename, input,
133 out, ann, is_expanded, Some(krate));
135 // When printing the AST, we sometimes need to inject `#[no_std]` here.
136 // Since you can't compile the HIR, it's not necessary.
138 s.print_mod(&krate.module, &krate.attrs)?;
139 s.print_remaining_comments()?;
144 pub fn new_from_input(cm: &'a CodeMap,
145 span_diagnostic: &errors::Handler,
148 out: Box<Write + 'a>,
151 krate: Option<&'a Crate>)
153 let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
161 // If the code is post expansion, don't use the table of
162 // literals, since it doesn't correspond with the literals
163 // in the AST anymore.
172 pub fn new(cm: &'a CodeMap,
173 out: Box<Write + 'a>,
175 comments: Option<Vec<comments::Comment>>,
176 literals: Option<Vec<comments::Literal>>,
177 krate: Option<&'a Crate>)
181 s: pp::mk_printer(out, default_columns),
183 comments: comments.clone(),
184 literals: literals.clone(),
185 cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
195 pub fn to_string<F>(f: F) -> String
196 where F: FnOnce(&mut State) -> io::Result<()>
198 let mut wr = Vec::new();
200 let mut printer = rust_printer(Box::new(&mut wr), None);
201 f(&mut printer).unwrap();
202 eof(&mut printer.s).unwrap();
204 String::from_utf8(wr).unwrap()
207 pub fn binop_to_string(op: BinOpToken) -> &'static str {
213 token::Percent => "%",
222 pub fn ty_to_string(ty: &hir::Ty) -> String {
223 to_string(|s| s.print_type(ty))
226 pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
227 to_string(|s| s.print_bounds("", bounds))
230 pub fn pat_to_string(pat: &hir::Pat) -> String {
231 to_string(|s| s.print_pat(pat))
234 pub fn arm_to_string(arm: &hir::Arm) -> String {
235 to_string(|s| s.print_arm(arm))
238 pub fn expr_to_string(e: &hir::Expr) -> String {
239 to_string(|s| s.print_expr(e))
242 pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
243 to_string(|s| s.print_lifetime(e))
246 pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
247 to_string(|s| s.print_stmt(stmt))
250 pub fn item_to_string(i: &hir::Item) -> String {
251 to_string(|s| s.print_item(i))
254 pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
255 to_string(|s| s.print_impl_item(i))
258 pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
259 to_string(|s| s.print_trait_item(i))
262 pub fn generics_to_string(generics: &hir::Generics) -> String {
263 to_string(|s| s.print_generics(generics))
266 pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
267 to_string(|s| s.print_where_clause(i))
270 pub fn fn_block_to_string(p: &hir::FnDecl) -> String {
271 to_string(|s| s.print_fn_block_args(p))
274 pub fn path_to_string(p: &hir::Path) -> String {
275 to_string(|s| s.print_path(p, false))
278 pub fn qpath_to_string(p: &hir::QPath) -> String {
279 to_string(|s| s.print_qpath(p, false))
282 pub fn name_to_string(name: ast::Name) -> String {
283 to_string(|s| s.print_name(name))
286 pub fn fun_to_string(decl: &hir::FnDecl,
287 unsafety: hir::Unsafety,
288 constness: hir::Constness,
290 generics: &hir::Generics)
301 s.end()?; // Close the head box
302 s.end() // Close the outer box
306 pub fn block_to_string(blk: &hir::Block) -> String {
308 // containing cbox, will be closed by print-block at }
309 s.cbox(indent_unit)?;
310 // head-ibox, will be closed by print-block after {
316 pub fn variant_to_string(var: &hir::Variant) -> String {
317 to_string(|s| s.print_variant(var))
320 pub fn arg_to_string(arg: &hir::Arg) -> String {
321 to_string(|s| s.print_arg(arg, false))
324 pub fn visibility_qualified(vis: &hir::Visibility, s: &str) -> String {
326 hir::Public => format!("pub {}", s),
327 hir::Visibility::Crate => format!("pub(crate) {}", s),
328 hir::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
329 hir::Inherited => s.to_string(),
333 fn needs_parentheses(expr: &hir::Expr) -> bool {
335 hir::ExprAssign(..) |
336 hir::ExprBinary(..) |
337 hir::ExprClosure(..) |
338 hir::ExprAssignOp(..) |
340 hir::ExprType(..) => true,
346 pub fn cbox(&mut self, u: usize) -> io::Result<()> {
347 self.boxes.push(pp::Breaks::Consistent);
348 pp::cbox(&mut self.s, u)
351 pub fn nbsp(&mut self) -> io::Result<()> {
352 word(&mut self.s, " ")
355 pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
356 word(&mut self.s, w)?;
360 pub fn head(&mut self, w: &str) -> io::Result<()> {
361 // outer-box is consistent
362 self.cbox(indent_unit)?;
363 // head-box is inconsistent
364 self.ibox(w.len() + 1)?;
365 // keyword that starts the head
372 pub fn bopen(&mut self) -> io::Result<()> {
373 word(&mut self.s, "{")?;
374 self.end() // close the head-box
377 pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
378 self.bclose_maybe_open(span, indented, true)
380 pub fn bclose_maybe_open(&mut self,
381 span: syntax_pos::Span,
385 self.maybe_print_comment(span.hi)?;
386 self.break_offset_if_not_bol(1, -(indented as isize))?;
387 word(&mut self.s, "}")?;
389 self.end()?; // close the outer-box
393 pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
394 self.bclose_(span, indent_unit)
397 pub fn in_cbox(&self) -> bool {
398 match self.boxes.last() {
399 Some(&last_box) => last_box == pp::Breaks::Consistent,
403 pub fn space_if_not_bol(&mut self) -> io::Result<()> {
409 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
411 break_offset(&mut self.s, n, off)
413 if off != 0 && self.s.last_token().is_hardbreak_tok() {
414 // We do something pretty sketchy here: tuck the nonzero
415 // offset-adjustment we were going to deposit along with the
416 // break into the previous hardbreak.
417 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
423 // Synthesizes a comment that was not textually present in the original source
425 pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
426 word(&mut self.s, "/*")?;
428 word(&mut self.s, &text[..])?;
430 word(&mut self.s, "*/")
434 pub fn commasep_cmnt<T, F, G>(&mut self,
440 where F: FnMut(&mut State, &T) -> io::Result<()>,
441 G: FnMut(&T) -> syntax_pos::Span
444 let len = elts.len();
447 self.maybe_print_comment(get_span(elt).hi)?;
451 word(&mut self.s, ",")?;
452 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi))?;
453 self.space_if_not_bol()?;
459 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) -> io::Result<()> {
460 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
463 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
464 self.print_inner_attributes(attrs)?;
465 for item_id in &_mod.item_ids {
466 self.print_item_id(item_id)?;
471 pub fn print_foreign_mod(&mut self,
472 nmod: &hir::ForeignMod,
473 attrs: &[ast::Attribute])
475 self.print_inner_attributes(attrs)?;
476 for item in &nmod.items {
477 self.print_foreign_item(item)?;
482 pub fn print_opt_lifetime(&mut self, lifetime: &Option<hir::Lifetime>) -> io::Result<()> {
483 if let Some(l) = *lifetime {
484 self.print_lifetime(&l)?;
490 pub fn print_type(&mut self, ty: &hir::Ty) -> io::Result<()> {
491 self.maybe_print_comment(ty.span.lo)?;
494 hir::TySlice(ref ty) => {
495 word(&mut self.s, "[")?;
496 self.print_type(&ty)?;
497 word(&mut self.s, "]")?;
499 hir::TyPtr(ref mt) => {
500 word(&mut self.s, "*")?;
502 hir::MutMutable => self.word_nbsp("mut")?,
503 hir::MutImmutable => self.word_nbsp("const")?,
505 self.print_type(&mt.ty)?;
507 hir::TyRptr(ref lifetime, ref mt) => {
508 word(&mut self.s, "&")?;
509 self.print_opt_lifetime(lifetime)?;
513 word(&mut self.s, "!")?;
515 hir::TyTup(ref elts) => {
517 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty))?;
519 word(&mut self.s, ",")?;
523 hir::TyBareFn(ref f) => {
524 let generics = hir::Generics {
525 lifetimes: f.lifetimes.clone(),
526 ty_params: hir::HirVec::new(),
527 where_clause: hir::WhereClause {
528 id: ast::DUMMY_NODE_ID,
529 predicates: hir::HirVec::new(),
531 span: syntax_pos::DUMMY_SP,
533 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &generics)?;
535 hir::TyPath(ref qpath) => {
536 self.print_qpath(qpath, false)?
538 hir::TyObjectSum(ref ty, ref bounds) => {
539 self.print_type(&ty)?;
540 self.print_bounds("+", &bounds[..])?;
542 hir::TyPolyTraitRef(ref bounds) => {
543 self.print_bounds("", &bounds[..])?;
545 hir::TyImplTrait(ref bounds) => {
546 self.print_bounds("impl ", &bounds[..])?;
548 hir::TyArray(ref ty, ref v) => {
549 word(&mut self.s, "[")?;
550 self.print_type(&ty)?;
551 word(&mut self.s, "; ")?;
552 self.print_expr(&v)?;
553 word(&mut self.s, "]")?;
555 hir::TyTypeof(ref e) => {
556 word(&mut self.s, "typeof(")?;
557 self.print_expr(&e)?;
558 word(&mut self.s, ")")?;
561 word(&mut self.s, "_")?;
567 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) -> io::Result<()> {
568 self.hardbreak_if_not_bol()?;
569 self.maybe_print_comment(item.span.lo)?;
570 self.print_outer_attributes(&item.attrs)?;
572 hir::ForeignItemFn(ref decl, ref generics) => {
575 hir::Unsafety::Normal,
576 hir::Constness::NotConst,
581 self.end()?; // end head-ibox
582 word(&mut self.s, ";")?;
583 self.end() // end the outer fn box
585 hir::ForeignItemStatic(ref t, m) => {
586 self.head(&visibility_qualified(&item.vis, "static"))?;
588 self.word_space("mut")?;
590 self.print_name(item.name)?;
591 self.word_space(":")?;
592 self.print_type(&t)?;
593 word(&mut self.s, ";")?;
594 self.end()?; // end the head-ibox
595 self.end() // end the outer cbox
600 fn print_associated_const(&mut self,
603 default: Option<&hir::Expr>,
604 vis: &hir::Visibility)
606 word(&mut self.s, &visibility_qualified(vis, ""))?;
607 self.word_space("const")?;
608 self.print_name(name)?;
609 self.word_space(":")?;
610 self.print_type(ty)?;
611 if let Some(expr) = default {
613 self.word_space("=")?;
614 self.print_expr(expr)?;
616 word(&mut self.s, ";")
619 fn print_associated_type(&mut self,
621 bounds: Option<&hir::TyParamBounds>,
622 ty: Option<&hir::Ty>)
624 self.word_space("type")?;
625 self.print_name(name)?;
626 if let Some(bounds) = bounds {
627 self.print_bounds(":", bounds)?;
629 if let Some(ty) = ty {
631 self.word_space("=")?;
632 self.print_type(ty)?;
634 word(&mut self.s, ";")
637 pub fn print_item_id(&mut self, item_id: &hir::ItemId) -> io::Result<()> {
638 if let Some(krate) = self.krate {
639 // skip nested items if krate context was not provided
640 let item = &krate.items[&item_id.id];
641 self.print_item(item)
647 /// Pretty-print an item
648 pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
649 self.hardbreak_if_not_bol()?;
650 self.maybe_print_comment(item.span.lo)?;
651 self.print_outer_attributes(&item.attrs)?;
652 self.ann.pre(self, NodeItem(item))?;
654 hir::ItemExternCrate(ref optional_path) => {
655 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
656 if let Some(p) = *optional_path {
657 let val = p.as_str();
658 if val.contains("-") {
659 self.print_string(&val, ast::StrStyle::Cooked)?;
664 word(&mut self.s, "as")?;
667 self.print_name(item.name)?;
668 word(&mut self.s, ";")?;
669 self.end()?; // end inner head-block
670 self.end()?; // end outer head-block
672 hir::ItemUse(ref vp) => {
673 self.head(&visibility_qualified(&item.vis, "use"))?;
674 self.print_view_path(&vp)?;
675 word(&mut self.s, ";")?;
676 self.end()?; // end inner head-block
677 self.end()?; // end outer head-block
679 hir::ItemStatic(ref ty, m, ref expr) => {
680 self.head(&visibility_qualified(&item.vis, "static"))?;
681 if m == hir::MutMutable {
682 self.word_space("mut")?;
684 self.print_name(item.name)?;
685 self.word_space(":")?;
686 self.print_type(&ty)?;
688 self.end()?; // end the head-ibox
690 self.word_space("=")?;
691 self.print_expr(&expr)?;
692 word(&mut self.s, ";")?;
693 self.end()?; // end the outer cbox
695 hir::ItemConst(ref ty, ref expr) => {
696 self.head(&visibility_qualified(&item.vis, "const"))?;
697 self.print_name(item.name)?;
698 self.word_space(":")?;
699 self.print_type(&ty)?;
701 self.end()?; // end the head-ibox
703 self.word_space("=")?;
704 self.print_expr(&expr)?;
705 word(&mut self.s, ";")?;
706 self.end()?; // end the outer cbox
708 hir::ItemFn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
717 word(&mut self.s, " ")?;
718 self.end()?; // need to close a box
719 self.end()?; // need to close a box
720 self.print_expr(&body)?;
722 hir::ItemMod(ref _mod) => {
723 self.head(&visibility_qualified(&item.vis, "mod"))?;
724 self.print_name(item.name)?;
727 self.print_mod(_mod, &item.attrs)?;
728 self.bclose(item.span)?;
730 hir::ItemForeignMod(ref nmod) => {
731 self.head("extern")?;
732 self.word_nbsp(&nmod.abi.to_string())?;
734 self.print_foreign_mod(nmod, &item.attrs)?;
735 self.bclose(item.span)?;
737 hir::ItemTy(ref ty, ref params) => {
738 self.ibox(indent_unit)?;
740 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
741 self.print_name(item.name)?;
742 self.print_generics(params)?;
743 self.end()?; // end the inner ibox
745 self.print_where_clause(¶ms.where_clause)?;
747 self.word_space("=")?;
748 self.print_type(&ty)?;
749 word(&mut self.s, ";")?;
750 self.end()?; // end the outer ibox
752 hir::ItemEnum(ref enum_definition, ref params) => {
753 self.print_enum_def(enum_definition, params, item.name, item.span, &item.vis)?;
755 hir::ItemStruct(ref struct_def, ref generics) => {
756 self.head(&visibility_qualified(&item.vis, "struct"))?;
757 self.print_struct(struct_def, generics, item.name, item.span, true)?;
759 hir::ItemUnion(ref struct_def, ref generics) => {
760 self.head(&visibility_qualified(&item.vis, "union"))?;
761 self.print_struct(struct_def, generics, item.name, item.span, true)?;
763 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
765 self.print_visibility(&item.vis)?;
766 self.print_unsafety(unsafety)?;
767 self.word_nbsp("impl")?;
768 self.print_trait_ref(trait_ref)?;
770 self.word_space("for")?;
771 self.word_space("..")?;
773 self.bclose(item.span)?;
775 hir::ItemImpl(unsafety,
782 self.print_visibility(&item.vis)?;
783 self.print_unsafety(unsafety)?;
784 self.word_nbsp("impl")?;
786 if generics.is_parameterized() {
787 self.print_generics(generics)?;
792 hir::ImplPolarity::Negative => {
793 word(&mut self.s, "!")?;
800 self.print_trait_ref(t)?;
802 self.word_space("for")?;
807 self.print_type(&ty)?;
808 self.print_where_clause(&generics.where_clause)?;
812 self.print_inner_attributes(&item.attrs)?;
813 for impl_item in impl_items {
814 self.print_impl_item_ref(impl_item)?;
816 self.bclose(item.span)?;
818 hir::ItemTrait(unsafety, ref generics, ref bounds, ref trait_items) => {
820 self.print_visibility(&item.vis)?;
821 self.print_unsafety(unsafety)?;
822 self.word_nbsp("trait")?;
823 self.print_name(item.name)?;
824 self.print_generics(generics)?;
825 let mut real_bounds = Vec::with_capacity(bounds.len());
826 for b in bounds.iter() {
827 if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
829 self.word_space("for ?")?;
830 self.print_trait_ref(&ptr.trait_ref)?;
832 real_bounds.push(b.clone());
835 self.print_bounds(":", &real_bounds[..])?;
836 self.print_where_clause(&generics.where_clause)?;
837 word(&mut self.s, " ")?;
839 for trait_item in trait_items {
840 self.print_trait_item(trait_item)?;
842 self.bclose(item.span)?;
845 self.ann.post(self, NodeItem(item))
848 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) -> io::Result<()> {
849 self.print_path(&t.path, false)
852 fn print_formal_lifetime_list(&mut self, lifetimes: &[hir::LifetimeDef]) -> io::Result<()> {
853 if !lifetimes.is_empty() {
854 word(&mut self.s, "for<")?;
855 let mut comma = false;
856 for lifetime_def in lifetimes {
858 self.word_space(",")?
860 self.print_lifetime_def(lifetime_def)?;
863 word(&mut self.s, ">")?;
868 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) -> io::Result<()> {
869 self.print_formal_lifetime_list(&t.bound_lifetimes)?;
870 self.print_trait_ref(&t.trait_ref)
873 pub fn print_enum_def(&mut self,
874 enum_definition: &hir::EnumDef,
875 generics: &hir::Generics,
877 span: syntax_pos::Span,
878 visibility: &hir::Visibility)
880 self.head(&visibility_qualified(visibility, "enum"))?;
881 self.print_name(name)?;
882 self.print_generics(generics)?;
883 self.print_where_clause(&generics.where_clause)?;
885 self.print_variants(&enum_definition.variants, span)
888 pub fn print_variants(&mut self,
889 variants: &[hir::Variant],
890 span: syntax_pos::Span)
894 self.space_if_not_bol()?;
895 self.maybe_print_comment(v.span.lo)?;
896 self.print_outer_attributes(&v.node.attrs)?;
897 self.ibox(indent_unit)?;
898 self.print_variant(v)?;
899 word(&mut self.s, ",")?;
901 self.maybe_print_trailing_comment(v.span, None)?;
906 pub fn print_visibility(&mut self, vis: &hir::Visibility) -> io::Result<()> {
908 hir::Public => self.word_nbsp("pub"),
909 hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
910 hir::Visibility::Restricted { ref path, .. } =>
911 self.word_nbsp(&format!("pub({})", path)),
912 hir::Inherited => Ok(()),
916 pub fn print_struct(&mut self,
917 struct_def: &hir::VariantData,
918 generics: &hir::Generics,
920 span: syntax_pos::Span,
921 print_finalizer: bool)
923 self.print_name(name)?;
924 self.print_generics(generics)?;
925 if !struct_def.is_struct() {
926 if struct_def.is_tuple() {
928 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
929 s.maybe_print_comment(field.span.lo)?;
930 s.print_outer_attributes(&field.attrs)?;
931 s.print_visibility(&field.vis)?;
932 s.print_type(&field.ty)
936 self.print_where_clause(&generics.where_clause)?;
938 word(&mut self.s, ";")?;
941 self.end() // close the outer-box
943 self.print_where_clause(&generics.where_clause)?;
946 self.hardbreak_if_not_bol()?;
948 for field in struct_def.fields() {
949 self.hardbreak_if_not_bol()?;
950 self.maybe_print_comment(field.span.lo)?;
951 self.print_outer_attributes(&field.attrs)?;
952 self.print_visibility(&field.vis)?;
953 self.print_name(field.name)?;
954 self.word_nbsp(":")?;
955 self.print_type(&field.ty)?;
956 word(&mut self.s, ",")?;
963 pub fn print_variant(&mut self, v: &hir::Variant) -> io::Result<()> {
965 let generics = hir::Generics::empty();
966 self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
967 match v.node.disr_expr {
970 self.word_space("=")?;
976 pub fn print_method_sig(&mut self,
979 vis: &hir::Visibility)
981 self.print_fn(&m.decl,
990 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
991 self.ann.pre(self, NodeSubItem(ti.id))?;
992 self.hardbreak_if_not_bol()?;
993 self.maybe_print_comment(ti.span.lo)?;
994 self.print_outer_attributes(&ti.attrs)?;
996 hir::ConstTraitItem(ref ty, ref default) => {
997 self.print_associated_const(ti.name,
999 default.as_ref().map(|expr| &**expr),
1002 hir::MethodTraitItem(ref sig, ref body) => {
1006 self.print_method_sig(ti.name, sig, &hir::Inherited)?;
1007 if let Some(ref body) = *body {
1009 self.end()?; // need to close a box
1010 self.end()?; // need to close a box
1011 self.print_expr(body)?;
1013 word(&mut self.s, ";")?;
1016 hir::TypeTraitItem(ref bounds, ref default) => {
1017 self.print_associated_type(ti.name,
1019 default.as_ref().map(|ty| &**ty))?;
1022 self.ann.post(self, NodeSubItem(ti.id))
1025 pub fn print_impl_item_ref(&mut self, item_ref: &hir::ImplItemRef) -> io::Result<()> {
1026 if let Some(krate) = self.krate {
1027 // skip nested items if krate context was not provided
1028 let item = &krate.impl_item(item_ref.id);
1029 self.print_impl_item(item)
1035 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
1036 self.ann.pre(self, NodeSubItem(ii.id))?;
1037 self.hardbreak_if_not_bol()?;
1038 self.maybe_print_comment(ii.span.lo)?;
1039 self.print_outer_attributes(&ii.attrs)?;
1041 match ii.defaultness {
1042 hir::Defaultness::Default { .. } => self.word_nbsp("default")?,
1043 hir::Defaultness::Final => (),
1047 hir::ImplItemKind::Const(ref ty, ref expr) => {
1048 self.print_associated_const(ii.name, &ty, Some(&expr), &ii.vis)?;
1050 hir::ImplItemKind::Method(ref sig, ref body) => {
1052 self.print_method_sig(ii.name, sig, &ii.vis)?;
1054 self.end()?; // need to close a box
1055 self.end()?; // need to close a box
1056 self.print_expr(body)?;
1058 hir::ImplItemKind::Type(ref ty) => {
1059 self.print_associated_type(ii.name, None, Some(ty))?;
1062 self.ann.post(self, NodeSubItem(ii.id))
1065 pub fn print_stmt(&mut self, st: &hir::Stmt) -> io::Result<()> {
1066 self.maybe_print_comment(st.span.lo)?;
1068 hir::StmtDecl(ref decl, _) => {
1069 self.print_decl(&decl)?;
1071 hir::StmtExpr(ref expr, _) => {
1072 self.space_if_not_bol()?;
1073 self.print_expr(&expr)?;
1075 hir::StmtSemi(ref expr, _) => {
1076 self.space_if_not_bol()?;
1077 self.print_expr(&expr)?;
1078 word(&mut self.s, ";")?;
1081 if stmt_ends_with_semi(&st.node) {
1082 word(&mut self.s, ";")?;
1084 self.maybe_print_trailing_comment(st.span, None)
1087 pub fn print_block(&mut self, blk: &hir::Block) -> io::Result<()> {
1088 self.print_block_with_attrs(blk, &[])
1091 pub fn print_block_unclosed(&mut self, blk: &hir::Block) -> io::Result<()> {
1092 self.print_block_unclosed_indent(blk, indent_unit)
1095 pub fn print_block_unclosed_indent(&mut self,
1099 self.print_block_maybe_unclosed(blk, indented, &[], false)
1102 pub fn print_block_with_attrs(&mut self,
1104 attrs: &[ast::Attribute])
1106 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1109 pub fn print_block_maybe_unclosed(&mut self,
1112 attrs: &[ast::Attribute],
1116 hir::UnsafeBlock(..) => self.word_space("unsafe")?,
1117 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe")?,
1118 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe")?,
1119 hir::PushUnstableBlock => self.word_space("push_unstable")?,
1120 hir::PopUnstableBlock => self.word_space("pop_unstable")?,
1121 hir::DefaultBlock => (),
1123 self.maybe_print_comment(blk.span.lo)?;
1124 self.ann.pre(self, NodeBlock(blk))?;
1127 self.print_inner_attributes(attrs)?;
1129 for st in &blk.stmts {
1130 self.print_stmt(st)?;
1134 self.space_if_not_bol()?;
1135 self.print_expr(&expr)?;
1136 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1140 self.bclose_maybe_open(blk.span, indented, close_box)?;
1141 self.ann.post(self, NodeBlock(blk))
1144 fn print_else(&mut self, els: Option<&hir::Expr>) -> io::Result<()> {
1148 // "another else-if"
1149 hir::ExprIf(ref i, ref then, ref e) => {
1150 self.cbox(indent_unit - 1)?;
1152 word(&mut self.s, " else if ")?;
1153 self.print_expr(&i)?;
1154 space(&mut self.s)?;
1155 self.print_block(&then)?;
1156 self.print_else(e.as_ref().map(|e| &**e))
1159 hir::ExprBlock(ref b) => {
1160 self.cbox(indent_unit - 1)?;
1162 word(&mut self.s, " else ")?;
1163 self.print_block(&b)
1165 // BLEAH, constraints would be great here
1167 panic!("print_if saw if with weird alternative");
1175 pub fn print_if(&mut self,
1178 elseopt: Option<&hir::Expr>)
1181 self.print_expr(test)?;
1182 space(&mut self.s)?;
1183 self.print_block(blk)?;
1184 self.print_else(elseopt)
1187 pub fn print_if_let(&mut self,
1191 elseopt: Option<&hir::Expr>)
1193 self.head("if let")?;
1194 self.print_pat(pat)?;
1195 space(&mut self.s)?;
1196 self.word_space("=")?;
1197 self.print_expr(expr)?;
1198 space(&mut self.s)?;
1199 self.print_block(blk)?;
1200 self.print_else(elseopt)
1204 fn print_call_post(&mut self, args: &[hir::Expr]) -> io::Result<()> {
1206 self.commasep_exprs(Inconsistent, args)?;
1210 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr) -> io::Result<()> {
1211 let needs_par = needs_parentheses(expr);
1215 self.print_expr(expr)?;
1222 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1223 self.ibox(indent_unit)?;
1224 word(&mut self.s, "[")?;
1225 self.commasep_exprs(Inconsistent, exprs)?;
1226 word(&mut self.s, "]")?;
1230 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::Expr) -> io::Result<()> {
1231 self.ibox(indent_unit)?;
1232 word(&mut self.s, "[")?;
1233 self.print_expr(element)?;
1234 self.word_space(";")?;
1235 self.print_expr(count)?;
1236 word(&mut self.s, "]")?;
1240 fn print_expr_struct(&mut self,
1242 fields: &[hir::Field],
1243 wth: &Option<P<hir::Expr>>)
1245 self.print_qpath(qpath, true)?;
1246 word(&mut self.s, "{")?;
1247 self.commasep_cmnt(Consistent,
1250 s.ibox(indent_unit)?;
1251 if !field.is_shorthand {
1252 s.print_name(field.name.node)?;
1255 s.print_expr(&field.expr)?;
1261 self.ibox(indent_unit)?;
1262 if !fields.is_empty() {
1263 word(&mut self.s, ",")?;
1264 space(&mut self.s)?;
1266 word(&mut self.s, "..")?;
1267 self.print_expr(&expr)?;
1270 _ => if !fields.is_empty() {
1271 word(&mut self.s, ",")?
1274 word(&mut self.s, "}")?;
1278 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) -> io::Result<()> {
1280 self.commasep_exprs(Inconsistent, exprs)?;
1281 if exprs.len() == 1 {
1282 word(&mut self.s, ",")?;
1287 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) -> io::Result<()> {
1288 self.print_expr_maybe_paren(func)?;
1289 self.print_call_post(args)
1292 fn print_expr_method_call(&mut self,
1293 name: Spanned<ast::Name>,
1297 let base_args = &args[1..];
1298 self.print_expr(&args[0])?;
1299 word(&mut self.s, ".")?;
1300 self.print_name(name.node)?;
1301 if !tys.is_empty() {
1302 word(&mut self.s, "::<")?;
1303 self.commasep(Inconsistent, tys, |s, ty| s.print_type(&ty))?;
1304 word(&mut self.s, ">")?;
1306 self.print_call_post(base_args)
1309 fn print_expr_binary(&mut self,
1314 self.print_expr(lhs)?;
1315 space(&mut self.s)?;
1316 self.word_space(op.node.as_str())?;
1317 self.print_expr(rhs)
1320 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) -> io::Result<()> {
1321 word(&mut self.s, op.as_str())?;
1322 self.print_expr_maybe_paren(expr)
1325 fn print_expr_addr_of(&mut self,
1326 mutability: hir::Mutability,
1329 word(&mut self.s, "&")?;
1330 self.print_mutability(mutability)?;
1331 self.print_expr_maybe_paren(expr)
1334 pub fn print_expr(&mut self, expr: &hir::Expr) -> io::Result<()> {
1335 self.maybe_print_comment(expr.span.lo)?;
1336 self.ibox(indent_unit)?;
1337 self.ann.pre(self, NodeExpr(expr))?;
1339 hir::ExprBox(ref expr) => {
1340 self.word_space("box")?;
1341 self.print_expr(expr)?;
1343 hir::ExprArray(ref exprs) => {
1344 self.print_expr_vec(exprs)?;
1346 hir::ExprRepeat(ref element, ref count) => {
1347 self.print_expr_repeat(&element, &count)?;
1349 hir::ExprStruct(ref qpath, ref fields, ref wth) => {
1350 self.print_expr_struct(qpath, &fields[..], wth)?;
1352 hir::ExprTup(ref exprs) => {
1353 self.print_expr_tup(exprs)?;
1355 hir::ExprCall(ref func, ref args) => {
1356 self.print_expr_call(&func, args)?;
1358 hir::ExprMethodCall(name, ref tys, ref args) => {
1359 self.print_expr_method_call(name, &tys[..], args)?;
1361 hir::ExprBinary(op, ref lhs, ref rhs) => {
1362 self.print_expr_binary(op, &lhs, &rhs)?;
1364 hir::ExprUnary(op, ref expr) => {
1365 self.print_expr_unary(op, &expr)?;
1367 hir::ExprAddrOf(m, ref expr) => {
1368 self.print_expr_addr_of(m, &expr)?;
1370 hir::ExprLit(ref lit) => {
1371 self.print_literal(&lit)?;
1373 hir::ExprCast(ref expr, ref ty) => {
1374 self.print_expr(&expr)?;
1375 space(&mut self.s)?;
1376 self.word_space("as")?;
1377 self.print_type(&ty)?;
1379 hir::ExprType(ref expr, ref ty) => {
1380 self.print_expr(&expr)?;
1381 self.word_space(":")?;
1382 self.print_type(&ty)?;
1384 hir::ExprIf(ref test, ref blk, ref elseopt) => {
1385 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
1387 hir::ExprWhile(ref test, ref blk, opt_sp_name) => {
1388 if let Some(sp_name) = opt_sp_name {
1389 self.print_name(sp_name.node)?;
1390 self.word_space(":")?;
1392 self.head("while")?;
1393 self.print_expr(&test)?;
1394 space(&mut self.s)?;
1395 self.print_block(&blk)?;
1397 hir::ExprLoop(ref blk, opt_sp_name, _) => {
1398 if let Some(sp_name) = opt_sp_name {
1399 self.print_name(sp_name.node)?;
1400 self.word_space(":")?;
1403 space(&mut self.s)?;
1404 self.print_block(&blk)?;
1406 hir::ExprMatch(ref expr, ref arms, _) => {
1407 self.cbox(indent_unit)?;
1409 self.word_nbsp("match")?;
1410 self.print_expr(&expr)?;
1411 space(&mut self.s)?;
1414 self.print_arm(arm)?;
1416 self.bclose_(expr.span, indent_unit)?;
1418 hir::ExprClosure(capture_clause, ref decl, ref body, _fn_decl_span) => {
1419 self.print_capture_clause(capture_clause)?;
1421 self.print_fn_block_args(&decl)?;
1422 space(&mut self.s)?;
1424 // this is a bare expression
1425 self.print_expr(body)?;
1426 self.end()?; // need to close a box
1428 // a box will be closed by print_expr, but we didn't want an overall
1429 // wrapper so we closed the corresponding opening. so create an
1430 // empty box to satisfy the close.
1433 hir::ExprBlock(ref blk) => {
1434 // containing cbox, will be closed by print-block at }
1435 self.cbox(indent_unit)?;
1436 // head-box, will be closed by print-block after {
1438 self.print_block(&blk)?;
1440 hir::ExprAssign(ref lhs, ref rhs) => {
1441 self.print_expr(&lhs)?;
1442 space(&mut self.s)?;
1443 self.word_space("=")?;
1444 self.print_expr(&rhs)?;
1446 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
1447 self.print_expr(&lhs)?;
1448 space(&mut self.s)?;
1449 word(&mut self.s, op.node.as_str())?;
1450 self.word_space("=")?;
1451 self.print_expr(&rhs)?;
1453 hir::ExprField(ref expr, name) => {
1454 self.print_expr(&expr)?;
1455 word(&mut self.s, ".")?;
1456 self.print_name(name.node)?;
1458 hir::ExprTupField(ref expr, id) => {
1459 self.print_expr(&expr)?;
1460 word(&mut self.s, ".")?;
1461 self.print_usize(id.node)?;
1463 hir::ExprIndex(ref expr, ref index) => {
1464 self.print_expr(&expr)?;
1465 word(&mut self.s, "[")?;
1466 self.print_expr(&index)?;
1467 word(&mut self.s, "]")?;
1469 hir::ExprPath(ref qpath) => {
1470 self.print_qpath(qpath, true)?
1472 hir::ExprBreak(opt_name, ref opt_expr) => {
1473 word(&mut self.s, "break")?;
1474 space(&mut self.s)?;
1475 if let Some(name) = opt_name {
1476 self.print_name(name.node)?;
1477 space(&mut self.s)?;
1479 if let Some(ref expr) = *opt_expr {
1480 self.print_expr(expr)?;
1481 space(&mut self.s)?;
1484 hir::ExprAgain(opt_name) => {
1485 word(&mut self.s, "continue")?;
1486 space(&mut self.s)?;
1487 if let Some(name) = opt_name {
1488 self.print_name(name.node)?;
1492 hir::ExprRet(ref result) => {
1493 word(&mut self.s, "return")?;
1496 word(&mut self.s, " ")?;
1497 self.print_expr(&expr)?;
1502 hir::ExprInlineAsm(ref a, ref outputs, ref inputs) => {
1503 word(&mut self.s, "asm!")?;
1505 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
1506 self.word_space(":")?;
1508 let mut out_idx = 0;
1509 self.commasep(Inconsistent, &a.outputs, |s, out| {
1510 let constraint = out.constraint.as_str();
1511 let mut ch = constraint.chars();
1513 Some('=') if out.is_rw => {
1514 s.print_string(&format!("+{}", ch.as_str()),
1515 ast::StrStyle::Cooked)?
1517 _ => s.print_string(&constraint, ast::StrStyle::Cooked)?,
1520 s.print_expr(&outputs[out_idx])?;
1525 space(&mut self.s)?;
1526 self.word_space(":")?;
1529 self.commasep(Inconsistent, &a.inputs, |s, co| {
1530 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1532 s.print_expr(&inputs[in_idx])?;
1537 space(&mut self.s)?;
1538 self.word_space(":")?;
1540 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1541 s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
1545 let mut options = vec![];
1547 options.push("volatile");
1550 options.push("alignstack");
1552 if a.dialect == ast::AsmDialect::Intel {
1553 options.push("intel");
1556 if !options.is_empty() {
1557 space(&mut self.s)?;
1558 self.word_space(":")?;
1559 self.commasep(Inconsistent, &options, |s, &co| {
1560 s.print_string(co, ast::StrStyle::Cooked)?;
1568 self.ann.post(self, NodeExpr(expr))?;
1572 pub fn print_local_decl(&mut self, loc: &hir::Local) -> io::Result<()> {
1573 self.print_pat(&loc.pat)?;
1574 if let Some(ref ty) = loc.ty {
1575 self.word_space(":")?;
1576 self.print_type(&ty)?;
1581 pub fn print_decl(&mut self, decl: &hir::Decl) -> io::Result<()> {
1582 self.maybe_print_comment(decl.span.lo)?;
1584 hir::DeclLocal(ref loc) => {
1585 self.space_if_not_bol()?;
1586 self.ibox(indent_unit)?;
1587 self.word_nbsp("let")?;
1589 self.ibox(indent_unit)?;
1590 self.print_local_decl(&loc)?;
1592 if let Some(ref init) = loc.init {
1594 self.word_space("=")?;
1595 self.print_expr(&init)?;
1599 hir::DeclItem(ref item) => {
1600 self.print_item_id(item)
1605 pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
1606 word(&mut self.s, &i.to_string())
1609 pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
1610 word(&mut self.s, &name.as_str())?;
1611 self.ann.post(self, NodeName(&name))
1614 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) -> io::Result<()> {
1615 self.print_local_decl(loc)?;
1616 space(&mut self.s)?;
1617 self.word_space("in")?;
1618 self.print_expr(coll)
1621 fn print_path(&mut self,
1623 colons_before_params: bool)
1625 self.maybe_print_comment(path.span.lo)?;
1627 let mut first = !path.global;
1628 for segment in &path.segments {
1632 word(&mut self.s, "::")?
1635 self.print_name(segment.name)?;
1637 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1643 fn print_qpath(&mut self,
1645 colons_before_params: bool)
1648 hir::QPath::Resolved(None, ref path) => {
1649 self.print_path(path, colons_before_params)
1651 hir::QPath::Resolved(Some(ref qself), ref path) => {
1652 word(&mut self.s, "<")?;
1653 self.print_type(qself)?;
1654 space(&mut self.s)?;
1655 self.word_space("as")?;
1657 let mut first = !path.global;
1658 for segment in &path.segments[..path.segments.len() - 1] {
1662 word(&mut self.s, "::")?
1664 self.print_name(segment.name)?;
1665 self.print_path_parameters(&segment.parameters, colons_before_params)?;
1668 word(&mut self.s, ">")?;
1669 word(&mut self.s, "::")?;
1670 let item_segment = path.segments.last().unwrap();
1671 self.print_name(item_segment.name)?;
1672 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1674 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1675 word(&mut self.s, "<")?;
1676 self.print_type(qself)?;
1677 word(&mut self.s, ">")?;
1678 word(&mut self.s, "::")?;
1679 self.print_name(item_segment.name)?;
1680 self.print_path_parameters(&item_segment.parameters, colons_before_params)
1685 fn print_path_parameters(&mut self,
1686 parameters: &hir::PathParameters,
1687 colons_before_params: bool)
1689 if parameters.is_empty() {
1690 let infer_types = match *parameters {
1691 hir::AngleBracketedParameters(ref data) => data.infer_types,
1692 hir::ParenthesizedParameters(_) => false
1695 // FIXME(eddyb) See the comment below about infer_types.
1696 if !(infer_types && false) {
1701 if colons_before_params {
1702 word(&mut self.s, "::")?
1706 hir::AngleBracketedParameters(ref data) => {
1707 word(&mut self.s, "<")?;
1709 let mut comma = false;
1710 for lifetime in &data.lifetimes {
1712 self.word_space(",")?
1714 self.print_lifetime(lifetime)?;
1718 if !data.types.is_empty() {
1720 self.word_space(",")?
1722 self.commasep(Inconsistent, &data.types, |s, ty| s.print_type(&ty))?;
1726 // FIXME(eddyb) This would leak into error messages, e.g.:
1727 // "non-exhaustive patterns: `Some::<..>(_)` not covered".
1728 if data.infer_types && false {
1730 self.word_space(",")?
1732 word(&mut self.s, "..")?;
1736 for binding in data.bindings.iter() {
1738 self.word_space(",")?
1740 self.print_name(binding.name)?;
1741 space(&mut self.s)?;
1742 self.word_space("=")?;
1743 self.print_type(&binding.ty)?;
1747 word(&mut self.s, ">")?
1750 hir::ParenthesizedParameters(ref data) => {
1751 word(&mut self.s, "(")?;
1752 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
1753 word(&mut self.s, ")")?;
1755 if let Some(ref ty) = data.output {
1756 self.space_if_not_bol()?;
1757 self.word_space("->")?;
1758 self.print_type(&ty)?;
1766 pub fn print_pat(&mut self, pat: &hir::Pat) -> io::Result<()> {
1767 self.maybe_print_comment(pat.span.lo)?;
1768 self.ann.pre(self, NodePat(pat))?;
1769 // Pat isn't normalized, but the beauty of it
1770 // is that it doesn't matter
1772 PatKind::Wild => word(&mut self.s, "_")?,
1773 PatKind::Binding(binding_mode, ref path1, ref sub) => {
1774 match binding_mode {
1775 hir::BindByRef(mutbl) => {
1776 self.word_nbsp("ref")?;
1777 self.print_mutability(mutbl)?;
1779 hir::BindByValue(hir::MutImmutable) => {}
1780 hir::BindByValue(hir::MutMutable) => {
1781 self.word_nbsp("mut")?;
1784 self.print_name(path1.node)?;
1785 if let Some(ref p) = *sub {
1786 word(&mut self.s, "@")?;
1787 self.print_pat(&p)?;
1790 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1791 self.print_qpath(qpath, true)?;
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))?;
1808 PatKind::Path(ref qpath) => {
1809 self.print_qpath(qpath, true)?;
1811 PatKind::Struct(ref qpath, ref fields, etc) => {
1812 self.print_qpath(qpath, true)?;
1814 self.word_space("{")?;
1815 self.commasep_cmnt(Consistent,
1818 s.cbox(indent_unit)?;
1819 if !f.node.is_shorthand {
1820 s.print_name(f.node.name)?;
1823 s.print_pat(&f.node.pat)?;
1826 |f| f.node.pat.span)?;
1828 if !fields.is_empty() {
1829 self.word_space(",")?;
1831 word(&mut self.s, "..")?;
1833 space(&mut self.s)?;
1834 word(&mut self.s, "}")?;
1836 PatKind::Tuple(ref elts, ddpos) => {
1838 if let Some(ddpos) = ddpos {
1839 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
1841 self.word_space(",")?;
1843 word(&mut self.s, "..")?;
1844 if ddpos != elts.len() {
1845 word(&mut self.s, ",")?;
1846 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
1849 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
1850 if elts.len() == 1 {
1851 word(&mut self.s, ",")?;
1856 PatKind::Box(ref inner) => {
1857 word(&mut self.s, "box ")?;
1858 self.print_pat(&inner)?;
1860 PatKind::Ref(ref inner, mutbl) => {
1861 word(&mut self.s, "&")?;
1862 if mutbl == hir::MutMutable {
1863 word(&mut self.s, "mut ")?;
1865 self.print_pat(&inner)?;
1867 PatKind::Lit(ref e) => self.print_expr(&e)?,
1868 PatKind::Range(ref begin, ref end) => {
1869 self.print_expr(&begin)?;
1870 space(&mut self.s)?;
1871 word(&mut self.s, "...")?;
1872 self.print_expr(&end)?;
1874 PatKind::Slice(ref before, ref slice, ref after) => {
1875 word(&mut self.s, "[")?;
1876 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p))?;
1877 if let Some(ref p) = *slice {
1878 if !before.is_empty() {
1879 self.word_space(",")?;
1881 if p.node != PatKind::Wild {
1882 self.print_pat(&p)?;
1884 word(&mut self.s, "..")?;
1885 if !after.is_empty() {
1886 self.word_space(",")?;
1889 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p))?;
1890 word(&mut self.s, "]")?;
1893 self.ann.post(self, NodePat(pat))
1896 fn print_arm(&mut self, arm: &hir::Arm) -> io::Result<()> {
1897 // I have no idea why this check is necessary, but here it
1899 if arm.attrs.is_empty() {
1900 space(&mut self.s)?;
1902 self.cbox(indent_unit)?;
1904 self.print_outer_attributes(&arm.attrs)?;
1905 let mut first = true;
1906 for p in &arm.pats {
1910 space(&mut self.s)?;
1911 self.word_space("|")?;
1913 self.print_pat(&p)?;
1915 space(&mut self.s)?;
1916 if let Some(ref e) = arm.guard {
1917 self.word_space("if")?;
1918 self.print_expr(&e)?;
1919 space(&mut self.s)?;
1921 self.word_space("=>")?;
1923 match arm.body.node {
1924 hir::ExprBlock(ref blk) => {
1925 // the block will close the pattern's ibox
1926 self.print_block_unclosed_indent(&blk, indent_unit)?;
1928 // If it is a user-provided unsafe block, print a comma after it
1929 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1930 word(&mut self.s, ",")?;
1934 self.end()?; // close the ibox for the pattern
1935 self.print_expr(&arm.body)?;
1936 word(&mut self.s, ",")?;
1939 self.end() // close enclosing cbox
1942 fn print_explicit_self(&mut self, explicit_self: &hir::ExplicitSelf) -> io::Result<()> {
1943 match explicit_self.node {
1944 SelfKind::Value(m) => {
1945 self.print_mutability(m)?;
1946 word(&mut self.s, "self")
1948 SelfKind::Region(ref lt, m) => {
1949 word(&mut self.s, "&")?;
1950 self.print_opt_lifetime(lt)?;
1951 self.print_mutability(m)?;
1952 word(&mut self.s, "self")
1954 SelfKind::Explicit(ref typ, m) => {
1955 self.print_mutability(m)?;
1956 word(&mut self.s, "self")?;
1957 self.word_space(":")?;
1958 self.print_type(&typ)
1963 pub fn print_fn(&mut self,
1965 unsafety: hir::Unsafety,
1966 constness: hir::Constness,
1968 name: Option<ast::Name>,
1969 generics: &hir::Generics,
1970 vis: &hir::Visibility)
1972 self.print_fn_header_info(unsafety, constness, abi, vis)?;
1974 if let Some(name) = name {
1976 self.print_name(name)?;
1978 self.print_generics(generics)?;
1979 self.print_fn_args_and_ret(decl)?;
1980 self.print_where_clause(&generics.where_clause)
1983 pub fn print_fn_args_and_ret(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1985 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
1987 word(&mut self.s, ", ...")?;
1991 self.print_fn_output(decl)
1994 pub fn print_fn_block_args(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
1995 word(&mut self.s, "|")?;
1996 self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
1997 word(&mut self.s, "|")?;
1999 if let hir::DefaultReturn(..) = decl.output {
2003 self.space_if_not_bol()?;
2004 self.word_space("->")?;
2006 hir::Return(ref ty) => {
2007 self.print_type(&ty)?;
2008 self.maybe_print_comment(ty.span.lo)
2010 hir::DefaultReturn(..) => unreachable!(),
2014 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io::Result<()> {
2015 match capture_clause {
2016 hir::CaptureByValue => self.word_space("move"),
2017 hir::CaptureByRef => Ok(()),
2021 pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
2022 if !bounds.is_empty() {
2023 word(&mut self.s, prefix)?;
2024 let mut first = true;
2025 for bound in bounds {
2030 self.word_space("+")?;
2034 TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2035 self.print_poly_trait_ref(tref)
2037 TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2038 word(&mut self.s, "?")?;
2039 self.print_poly_trait_ref(tref)
2041 RegionTyParamBound(ref lt) => {
2042 self.print_lifetime(lt)
2052 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
2053 self.print_name(lifetime.name)
2056 pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
2057 self.print_lifetime(&lifetime.lifetime)?;
2059 for v in &lifetime.bounds {
2060 word(&mut self.s, sep)?;
2061 self.print_lifetime(v)?;
2067 pub fn print_generics(&mut self, generics: &hir::Generics) -> io::Result<()> {
2068 let total = generics.lifetimes.len() + generics.ty_params.len();
2073 word(&mut self.s, "<")?;
2075 let mut ints = Vec::new();
2080 self.commasep(Inconsistent, &ints[..], |s, &idx| {
2081 if idx < generics.lifetimes.len() {
2082 let lifetime = &generics.lifetimes[idx];
2083 s.print_lifetime_def(lifetime)
2085 let idx = idx - generics.lifetimes.len();
2086 let param = &generics.ty_params[idx];
2087 s.print_ty_param(param)
2091 word(&mut self.s, ">")?;
2095 pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
2096 self.print_name(param.name)?;
2097 self.print_bounds(":", ¶m.bounds)?;
2098 match param.default {
2099 Some(ref default) => {
2100 space(&mut self.s)?;
2101 self.word_space("=")?;
2102 self.print_type(&default)
2108 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
2109 if where_clause.predicates.is_empty() {
2113 space(&mut self.s)?;
2114 self.word_space("where")?;
2116 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2118 self.word_space(",")?;
2122 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate{ref bound_lifetimes,
2126 self.print_formal_lifetime_list(bound_lifetimes)?;
2127 self.print_type(&bounded_ty)?;
2128 self.print_bounds(":", bounds)?;
2130 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2133 self.print_lifetime(lifetime)?;
2134 word(&mut self.s, ":")?;
2136 for (i, bound) in bounds.iter().enumerate() {
2137 self.print_lifetime(bound)?;
2140 word(&mut self.s, ":")?;
2144 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref path, ref ty, ..}) => {
2145 self.print_path(path, false)?;
2146 space(&mut self.s)?;
2147 self.word_space("=")?;
2148 self.print_type(&ty)?;
2156 pub fn print_view_path(&mut self, vp: &hir::ViewPath) -> io::Result<()> {
2158 hir::ViewPathSimple(name, ref path) => {
2159 self.print_path(path, false)?;
2161 if path.segments.last().unwrap().name != name {
2162 space(&mut self.s)?;
2163 self.word_space("as")?;
2164 self.print_name(name)?;
2170 hir::ViewPathGlob(ref path) => {
2171 self.print_path(path, false)?;
2172 word(&mut self.s, "::*")
2175 hir::ViewPathList(ref path, ref segments) => {
2176 if path.segments.is_empty() {
2177 word(&mut self.s, "{")?;
2179 self.print_path(path, false)?;
2180 word(&mut self.s, "::{")?;
2182 self.commasep(Inconsistent, &segments[..], |s, w| s.print_name(w.node.name))?;
2183 word(&mut self.s, "}")
2188 pub fn print_mutability(&mut self, mutbl: hir::Mutability) -> io::Result<()> {
2190 hir::MutMutable => self.word_nbsp("mut"),
2191 hir::MutImmutable => Ok(()),
2195 pub fn print_mt(&mut self, mt: &hir::MutTy) -> io::Result<()> {
2196 self.print_mutability(mt.mutbl)?;
2197 self.print_type(&mt.ty)
2200 pub fn print_arg(&mut self, input: &hir::Arg, is_closure: bool) -> io::Result<()> {
2201 self.ibox(indent_unit)?;
2202 match input.ty.node {
2203 hir::TyInfer if is_closure => self.print_pat(&input.pat)?,
2205 if let Some(eself) = input.to_self() {
2206 self.print_explicit_self(&eself)?;
2208 let invalid = if let PatKind::Binding(_, name, _) = input.pat.node {
2209 name.node == keywords::Invalid.name()
2214 self.print_pat(&input.pat)?;
2215 word(&mut self.s, ":")?;
2216 space(&mut self.s)?;
2218 self.print_type(&input.ty)?;
2225 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) -> io::Result<()> {
2226 if let hir::DefaultReturn(..) = decl.output {
2230 self.space_if_not_bol()?;
2231 self.ibox(indent_unit)?;
2232 self.word_space("->")?;
2234 hir::DefaultReturn(..) => unreachable!(),
2235 hir::Return(ref ty) => self.print_type(&ty)?,
2240 hir::Return(ref output) => self.maybe_print_comment(output.span.lo),
2245 pub fn print_ty_fn(&mut self,
2247 unsafety: hir::Unsafety,
2249 name: Option<ast::Name>,
2250 generics: &hir::Generics)
2252 self.ibox(indent_unit)?;
2253 if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2254 word(&mut self.s, "for")?;
2255 self.print_generics(generics)?;
2257 let generics = hir::Generics {
2258 lifetimes: hir::HirVec::new(),
2259 ty_params: hir::HirVec::new(),
2260 where_clause: hir::WhereClause {
2261 id: ast::DUMMY_NODE_ID,
2262 predicates: hir::HirVec::new(),
2264 span: syntax_pos::DUMMY_SP,
2268 hir::Constness::NotConst,
2276 pub fn maybe_print_trailing_comment(&mut self,
2277 span: syntax_pos::Span,
2278 next_pos: Option<BytePos>)
2280 let cm = match self.cm {
2284 if let Some(ref cmnt) = self.next_comment() {
2285 if (*cmnt).style != comments::Trailing {
2288 let span_line = cm.lookup_char_pos(span.hi);
2289 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2290 let mut next = (*cmnt).pos + BytePos(1);
2291 if let Some(p) = next_pos {
2294 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2295 span_line.line == comment_line.line {
2296 self.print_comment(cmnt)?;
2297 self.cur_cmnt_and_lit.cur_cmnt += 1;
2303 pub fn print_remaining_comments(&mut self) -> io::Result<()> {
2304 // If there aren't any remaining comments, then we need to manually
2305 // make sure there is a line break at the end.
2306 if self.next_comment().is_none() {
2307 hardbreak(&mut self.s)?;
2310 match self.next_comment() {
2312 self.print_comment(cmnt)?;
2313 self.cur_cmnt_and_lit.cur_cmnt += 1;
2321 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2322 opt_abi: Option<Abi>)
2325 Some(Abi::Rust) => Ok(()),
2327 self.word_nbsp("extern")?;
2328 self.word_nbsp(&abi.to_string())
2334 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) -> io::Result<()> {
2337 self.word_nbsp("extern")?;
2338 self.word_nbsp(&abi.to_string())
2344 pub fn print_fn_header_info(&mut self,
2345 unsafety: hir::Unsafety,
2346 constness: hir::Constness,
2348 vis: &hir::Visibility)
2350 word(&mut self.s, &visibility_qualified(vis, ""))?;
2351 self.print_unsafety(unsafety)?;
2354 hir::Constness::NotConst => {}
2355 hir::Constness::Const => self.word_nbsp("const")?,
2358 if abi != Abi::Rust {
2359 self.word_nbsp("extern")?;
2360 self.word_nbsp(&abi.to_string())?;
2363 word(&mut self.s, "fn")
2366 pub fn print_unsafety(&mut self, s: hir::Unsafety) -> io::Result<()> {
2368 hir::Unsafety::Normal => Ok(()),
2369 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2374 // Dup'ed from parse::classify, but adapted for the HIR.
2375 /// Does this expression require a semicolon to be treated
2376 /// as a statement? The negation of this: 'can this expression
2377 /// be used as a statement without a semicolon' -- is used
2378 /// as an early-bail-out in the parser so that, for instance,
2379 /// if true {...} else {...}
2381 /// isn't parsed as (if true {...} else {...} | x) | 5
2382 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2385 hir::ExprMatch(..) |
2387 hir::ExprWhile(..) |
2388 hir::ExprLoop(..) => false,
2393 /// this statement requires a semicolon after it.
2394 /// note that in one case (stmt_semi), we've already
2395 /// seen the semicolon, and thus don't need another.
2396 fn stmt_ends_with_semi(stmt: &hir::Stmt_) -> bool {
2398 hir::StmtDecl(ref d, _) => {
2400 hir::DeclLocal(_) => true,
2401 hir::DeclItem(_) => false,
2404 hir::StmtExpr(ref e, _) => {
2405 expr_requires_semi_to_be_stmt(&e)
2407 hir::StmtSemi(..) => {