1 // Copyright 2012-2014 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.
12 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
13 use ast::{FnOnceUnboxedClosureKind};
14 use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound};
15 use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
16 use ast::{UnboxedClosureKind, UnboxedFnTyParamBound};
19 use owned_slice::OwnedSlice;
20 use attr::{AttrMetaMethods, AttributeMethods};
21 use codemap::{CodeMap, BytePos};
25 use parse::lexer::comments;
27 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
28 use print::pp::{Breaks, Consistent, Inconsistent, eof};
32 use std::io::{IoResult, MemWriter};
36 pub enum AnnNode<'a> {
37 NodeIdent(&'a ast::Ident),
38 NodeName(&'a ast::Name),
39 NodeBlock(&'a ast::Block),
40 NodeItem(&'a ast::Item),
41 NodeExpr(&'a ast::Expr),
42 NodePat(&'a ast::Pat),
46 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
47 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
52 impl PpAnn for NoAnn {}
54 pub struct CurrentCommentAndLiteral {
59 pub struct State<'a> {
61 cm: Option<&'a CodeMap>,
62 comments: Option<Vec<comments::Comment> >,
63 literals: Option<Vec<comments::Literal> >,
64 cur_cmnt_and_lit: CurrentCommentAndLiteral,
65 boxes: Vec<pp::Breaks>,
67 encode_idents_with_hygiene: bool,
70 pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> {
71 static NO_ANN: NoAnn = NoAnn;
72 rust_printer_annotated(writer, &NO_ANN)
75 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>,
76 ann: &'a PpAnn) -> State<'a> {
78 s: pp::mk_printer(writer, default_columns),
82 cur_cmnt_and_lit: CurrentCommentAndLiteral {
88 encode_idents_with_hygiene: false,
92 pub static indent_unit: uint = 4u;
94 pub static default_columns: uint = 78u;
96 /// Requires you to pass an input filename and reader so that
97 /// it can scan the input text for comments and literals to
99 pub fn print_crate<'a>(cm: &'a CodeMap,
100 span_diagnostic: &diagnostic::SpanHandler,
103 input: &mut io::Reader,
104 out: Box<io::Writer+'static>,
106 is_expanded: bool) -> IoResult<()> {
107 let mut s = State::new_from_input(cm,
114 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
115 try!(s.print_remaining_comments());
120 pub fn new_from_input(cm: &'a CodeMap,
121 span_diagnostic: &diagnostic::SpanHandler,
123 input: &mut io::Reader,
124 out: Box<io::Writer+'static>,
126 is_expanded: bool) -> State<'a> {
127 let (cmnts, lits) = comments::gather_comments_and_literals(
137 // If the code is post expansion, don't use the table of
138 // literals, since it doesn't correspond with the literals
139 // in the AST anymore.
140 if is_expanded { None } else { Some(lits) })
143 pub fn new(cm: &'a CodeMap,
144 out: Box<io::Writer+'static>,
146 comments: Option<Vec<comments::Comment>>,
147 literals: Option<Vec<comments::Literal>>) -> State<'a> {
149 s: pp::mk_printer(out, default_columns),
153 cur_cmnt_and_lit: CurrentCommentAndLiteral {
159 encode_idents_with_hygiene: false,
164 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
165 use std::raw::TraitObject;
166 let mut s = rust_printer(box MemWriter::new());
168 eof(&mut s.s).unwrap();
170 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
171 // that we "know" to be a `MemWriter` that works around the lack of checked
173 let obj: TraitObject = mem::transmute_copy(&s.s.out);
174 let wr: Box<MemWriter> = mem::transmute(obj.data);
176 String::from_utf8(Vec::from_slice(wr.get_ref().as_slice())).unwrap();
182 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
183 // after we revise the syntax::ext::quote::ToToken impls to go directly
184 // to token-trees instead of thing -> string -> token-trees.
186 macro_rules! thing_to_string_impls {
187 ($to_string:ident) => {
189 pub fn ty_to_string(ty: &ast::Ty) -> String {
190 $to_string(|s| s.print_type(ty))
193 pub fn pat_to_string(pat: &ast::Pat) -> String {
194 $to_string(|s| s.print_pat(pat))
197 pub fn arm_to_string(arm: &ast::Arm) -> String {
198 $to_string(|s| s.print_arm(arm))
201 pub fn expr_to_string(e: &ast::Expr) -> String {
202 $to_string(|s| s.print_expr(e))
205 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
206 $to_string(|s| s.print_lifetime(e))
209 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
210 $to_string(|s| s.print_tt(tt))
213 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
214 $to_string(|s| s.print_tts(tts))
217 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
218 $to_string(|s| s.print_stmt(stmt))
221 pub fn item_to_string(i: &ast::Item) -> String {
222 $to_string(|s| s.print_item(i))
225 pub fn generics_to_string(generics: &ast::Generics) -> String {
226 $to_string(|s| s.print_generics(generics))
229 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
230 $to_string(|s| s.print_ty_method(p))
233 pub fn method_to_string(p: &ast::Method) -> String {
234 $to_string(|s| s.print_method(p))
237 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
238 $to_string(|s| s.print_fn_block_args(p, None))
241 pub fn path_to_string(p: &ast::Path) -> String {
242 $to_string(|s| s.print_path(p, false))
245 pub fn ident_to_string(id: &ast::Ident) -> String {
246 $to_string(|s| s.print_ident(*id))
249 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
250 opt_explicit_self: Option<&ast::ExplicitSelf_>,
251 generics: &ast::Generics) -> String {
253 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
254 name, generics, opt_explicit_self, ast::Inherited));
255 try!(s.end()); // Close the head box
256 s.end() // Close the outer box
260 pub fn block_to_string(blk: &ast::Block) -> String {
262 // containing cbox, will be closed by print-block at }
263 try!(s.cbox(indent_unit));
264 // head-ibox, will be closed by print-block after {
270 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
271 $to_string(|s| s.print_meta_item(mi))
274 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
275 $to_string(|s| s.print_attribute(attr))
278 pub fn lit_to_string(l: &ast::Lit) -> String {
279 $to_string(|s| s.print_literal(l))
282 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
283 $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
286 pub fn variant_to_string(var: &ast::Variant) -> String {
287 $to_string(|s| s.print_variant(var))
290 pub fn arg_to_string(arg: &ast::Arg) -> String {
291 $to_string(|s| s.print_arg(arg))
294 pub fn mac_to_string(arg: &ast::Mac) -> String {
295 $to_string(|s| s.print_mac(arg))
300 thing_to_string_impls!(to_string)
302 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
303 // after we revise the syntax::ext::quote::ToToken impls to go directly
304 // to token-trees instea of thing -> string -> token-trees.
306 pub mod with_hygiene {
309 use std::io::IoResult;
310 use super::indent_unit;
312 // This function is the trick that all the rest of the routines
314 pub fn to_string_hyg(f: |&mut super::State| -> IoResult<()>) -> String {
315 super::to_string(|s| {
316 s.encode_idents_with_hygiene = true;
321 thing_to_string_impls!(to_string_hyg)
324 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
326 ast::Public => format!("pub {}", s),
327 ast::Inherited => s.to_string()
331 fn needs_parentheses(expr: &ast::Expr) -> bool {
333 ast::ExprAssign(..) | ast::ExprBinary(..) |
334 ast::ExprFnBlock(..) | ast::ExprProc(..) |
335 ast::ExprUnboxedFn(..) | ast::ExprAssignOp(..) |
336 ast::ExprCast(..) => true,
342 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
343 self.boxes.push(pp::Inconsistent);
344 pp::ibox(&mut self.s, u)
347 pub fn end(&mut self) -> IoResult<()> {
348 self.boxes.pop().unwrap();
352 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
353 self.boxes.push(pp::Consistent);
354 pp::cbox(&mut self.s, u)
358 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
360 pp::rbox(&mut self.s, u, b)
363 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
365 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
366 try!(word(&mut self.s, w));
370 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
371 try!(word(&mut self.s, w));
375 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
377 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
379 pub fn head(&mut self, w: &str) -> IoResult<()> {
380 // outer-box is consistent
381 try!(self.cbox(indent_unit));
382 // head-box is inconsistent
383 try!(self.ibox(w.len() + 1));
384 // keyword that starts the head
386 try!(self.word_nbsp(w));
391 pub fn bopen(&mut self) -> IoResult<()> {
392 try!(word(&mut self.s, "{"));
393 self.end() // close the head-box
396 pub fn bclose_(&mut self, span: codemap::Span,
397 indented: uint) -> IoResult<()> {
398 self.bclose_maybe_open(span, indented, true)
400 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
401 indented: uint, close_box: bool) -> IoResult<()> {
402 try!(self.maybe_print_comment(span.hi));
403 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
404 try!(word(&mut self.s, "}"));
406 try!(self.end()); // close the outer-box
410 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
411 self.bclose_(span, indent_unit)
414 pub fn is_begin(&mut self) -> bool {
415 match self.s.last_token() { pp::Begin(_) => true, _ => false }
418 pub fn is_end(&mut self) -> bool {
419 match self.s.last_token() { pp::End => true, _ => false }
422 // is this the beginning of a line?
423 pub fn is_bol(&mut self) -> bool {
424 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
427 pub fn in_cbox(&self) -> bool {
428 match self.boxes.last() {
429 Some(&last_box) => last_box == pp::Consistent,
434 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
436 try!(hardbreak(&mut self.s))
440 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
441 if !self.is_bol() { try!(space(&mut self.s)); }
444 pub fn break_offset_if_not_bol(&mut self, n: uint,
445 off: int) -> IoResult<()> {
447 break_offset(&mut self.s, n, off)
449 if off != 0 && self.s.last_token().is_hardbreak_tok() {
450 // We do something pretty sketchy here: tuck the nonzero
451 // offset-adjustment we were going to deposit along with the
452 // break into the previous hardbreak.
453 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
459 // Synthesizes a comment that was not textually present in the original source
461 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
462 try!(word(&mut self.s, "/*"));
463 try!(space(&mut self.s));
464 try!(word(&mut self.s, text.as_slice()));
465 try!(space(&mut self.s));
466 word(&mut self.s, "*/")
469 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
470 op: |&mut State, &T| -> IoResult<()>)
472 try!(self.rbox(0u, b));
473 let mut first = true;
474 for elt in elts.iter() {
475 if first { first = false; } else { try!(self.word_space(",")); }
482 pub fn commasep_cmnt<T>(
486 op: |&mut State, &T| -> IoResult<()>,
487 get_span: |&T| -> codemap::Span) -> IoResult<()> {
488 try!(self.rbox(0u, b));
489 let len = elts.len();
491 for elt in elts.iter() {
492 try!(self.maybe_print_comment(get_span(elt).hi));
496 try!(word(&mut self.s, ","));
497 try!(self.maybe_print_trailing_comment(get_span(elt),
498 Some(get_span(&elts[i]).hi)));
499 try!(self.space_if_not_bol());
505 pub fn commasep_exprs(&mut self, b: Breaks,
506 exprs: &[P<ast::Expr>]) -> IoResult<()> {
507 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
510 pub fn print_mod(&mut self, _mod: &ast::Mod,
511 attrs: &[ast::Attribute]) -> IoResult<()> {
512 try!(self.print_inner_attributes(attrs));
513 for vitem in _mod.view_items.iter() {
514 try!(self.print_view_item(vitem));
516 for item in _mod.items.iter() {
517 try!(self.print_item(&**item));
522 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
523 attrs: &[ast::Attribute]) -> IoResult<()> {
524 try!(self.print_inner_attributes(attrs));
525 for vitem in nmod.view_items.iter() {
526 try!(self.print_view_item(vitem));
528 for item in nmod.items.iter() {
529 try!(self.print_foreign_item(&**item));
534 pub fn print_opt_lifetime(&mut self,
535 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
536 for l in lifetime.iter() {
537 try!(self.print_lifetime(l));
543 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
544 try!(self.maybe_print_comment(ty.span.lo));
547 ast::TyNil => try!(word(&mut self.s, "()")),
548 ast::TyBot => try!(word(&mut self.s, "!")),
549 ast::TyBox(ref ty) => {
550 try!(word(&mut self.s, "@"));
551 try!(self.print_type(&**ty));
553 ast::TyUniq(ref ty) => {
554 try!(word(&mut self.s, "~"));
555 try!(self.print_type(&**ty));
557 ast::TyVec(ref ty) => {
558 try!(word(&mut self.s, "["));
559 try!(self.print_type(&**ty));
560 try!(word(&mut self.s, "]"));
562 ast::TyPtr(ref mt) => {
563 try!(word(&mut self.s, "*"));
565 ast::MutMutable => try!(self.word_nbsp("mut")),
566 ast::MutImmutable => try!(self.word_nbsp("const")),
568 try!(self.print_type(&*mt.ty));
570 ast::TyRptr(ref lifetime, ref mt) => {
571 try!(word(&mut self.s, "&"));
572 try!(self.print_opt_lifetime(lifetime));
573 try!(self.print_mt(mt));
575 ast::TyTup(ref elts) => {
577 try!(self.commasep(Inconsistent, elts.as_slice(),
578 |s, ty| s.print_type(&**ty)));
580 try!(word(&mut self.s, ","));
584 ast::TyParen(ref typ) => {
586 try!(self.print_type(&**typ));
589 ast::TyBareFn(ref f) => {
590 let generics = ast::Generics {
591 lifetimes: f.lifetimes.clone(),
592 ty_params: OwnedSlice::empty(),
593 where_clause: ast::WhereClause {
594 id: ast::DUMMY_NODE_ID,
595 predicates: Vec::new(),
598 try!(self.print_ty_fn(Some(f.abi),
604 &OwnedSlice::empty(),
609 ast::TyClosure(ref f) => {
610 let generics = ast::Generics {
611 lifetimes: f.lifetimes.clone(),
612 ty_params: OwnedSlice::empty(),
613 where_clause: ast::WhereClause {
614 id: ast::DUMMY_NODE_ID,
615 predicates: Vec::new(),
618 try!(self.print_ty_fn(None,
629 ast::TyProc(ref f) => {
630 let generics = ast::Generics {
631 lifetimes: f.lifetimes.clone(),
632 ty_params: OwnedSlice::empty(),
633 where_clause: ast::WhereClause {
634 id: ast::DUMMY_NODE_ID,
635 predicates: Vec::new(),
638 try!(self.print_ty_fn(None,
649 ast::TyUnboxedFn(ref f) => {
650 try!(self.print_ty_fn(None,
656 &OwnedSlice::empty(),
661 ast::TyPath(ref path, ref bounds, _) => {
662 try!(self.print_bounded_path(path, bounds));
664 ast::TyQPath(ref qpath) => {
665 try!(word(&mut self.s, "<"));
666 try!(self.print_type(&*qpath.for_type));
667 try!(space(&mut self.s));
668 try!(self.word_space("as"));
669 try!(self.print_path(&qpath.trait_name, false));
670 try!(word(&mut self.s, ">"));
671 try!(word(&mut self.s, "::"));
672 try!(self.print_ident(qpath.item_name));
674 ast::TyFixedLengthVec(ref ty, ref v) => {
675 try!(word(&mut self.s, "["));
676 try!(self.print_type(&**ty));
677 try!(word(&mut self.s, ", .."));
678 try!(self.print_expr(&**v));
679 try!(word(&mut self.s, "]"));
681 ast::TyTypeof(ref e) => {
682 try!(word(&mut self.s, "typeof("));
683 try!(self.print_expr(&**e));
684 try!(word(&mut self.s, ")"));
687 try!(word(&mut self.s, "_"));
693 pub fn print_foreign_item(&mut self,
694 item: &ast::ForeignItem) -> IoResult<()> {
695 try!(self.hardbreak_if_not_bol());
696 try!(self.maybe_print_comment(item.span.lo));
697 try!(self.print_outer_attributes(item.attrs.as_slice()));
699 ast::ForeignItemFn(ref decl, ref generics) => {
700 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
702 try!(self.end()); // end head-ibox
703 try!(word(&mut self.s, ";"));
704 self.end() // end the outer fn box
706 ast::ForeignItemStatic(ref t, m) => {
707 try!(self.head(visibility_qualified(item.vis,
708 "static").as_slice()));
710 try!(self.word_space("mut"));
712 try!(self.print_ident(item.ident));
713 try!(self.word_space(":"));
714 try!(self.print_type(&**t));
715 try!(word(&mut self.s, ";"));
716 try!(self.end()); // end the head-ibox
717 self.end() // end the outer cbox
722 fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
724 try!(self.word_space("type"));
725 try!(self.print_ident(typedef.ident));
726 word(&mut self.s, ";")
729 fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
730 try!(self.word_space("type"));
731 try!(self.print_ident(typedef.ident));
732 try!(space(&mut self.s));
733 try!(self.word_space("="));
734 try!(self.print_type(&*typedef.typ));
735 word(&mut self.s, ";")
738 /// Pretty-print an item
739 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
740 try!(self.hardbreak_if_not_bol());
741 try!(self.maybe_print_comment(item.span.lo));
742 try!(self.print_outer_attributes(item.attrs.as_slice()));
743 try!(self.ann.pre(self, NodeItem(item)));
745 ast::ItemStatic(ref ty, m, ref expr) => {
746 try!(self.head(visibility_qualified(item.vis,
747 "static").as_slice()));
748 if m == ast::MutMutable {
749 try!(self.word_space("mut"));
751 try!(self.print_ident(item.ident));
752 try!(self.word_space(":"));
753 try!(self.print_type(&**ty));
754 try!(space(&mut self.s));
755 try!(self.end()); // end the head-ibox
757 try!(self.word_space("="));
758 try!(self.print_expr(&**expr));
759 try!(word(&mut self.s, ";"));
760 try!(self.end()); // end the outer cbox
762 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
772 try!(word(&mut self.s, " "));
773 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
775 ast::ItemMod(ref _mod) => {
776 try!(self.head(visibility_qualified(item.vis,
778 try!(self.print_ident(item.ident));
781 try!(self.print_mod(_mod, item.attrs.as_slice()));
782 try!(self.bclose(item.span));
784 ast::ItemForeignMod(ref nmod) => {
785 try!(self.head("extern"));
786 try!(self.word_nbsp(nmod.abi.to_string().as_slice()));
788 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
789 try!(self.bclose(item.span));
791 ast::ItemTy(ref ty, ref params) => {
792 try!(self.ibox(indent_unit));
794 try!(self.word_nbsp(visibility_qualified(item.vis,
795 "type").as_slice()));
796 try!(self.print_ident(item.ident));
797 try!(self.print_generics(params));
798 try!(self.end()); // end the inner ibox
800 try!(space(&mut self.s));
801 try!(self.word_space("="));
802 try!(self.print_type(&**ty));
803 try!(self.print_where_clause(params));
804 try!(word(&mut self.s, ";"));
805 try!(self.end()); // end the outer ibox
807 ast::ItemEnum(ref enum_definition, ref params) => {
808 try!(self.print_enum_def(
816 ast::ItemStruct(ref struct_def, ref generics) => {
817 if struct_def.is_virtual {
818 try!(self.word_space("virtual"));
820 try!(self.head(visibility_qualified(item.vis,"struct").as_slice()));
821 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
824 ast::ItemImpl(ref generics,
828 try!(self.head(visibility_qualified(item.vis,
829 "impl").as_slice()));
830 if generics.is_parameterized() {
831 try!(self.print_generics(generics));
832 try!(space(&mut self.s));
837 try!(self.print_trait_ref(t));
838 try!(space(&mut self.s));
839 try!(self.word_space("for"));
844 try!(self.print_type(&**ty));
845 try!(self.print_where_clause(generics));
847 try!(space(&mut self.s));
849 try!(self.print_inner_attributes(item.attrs.as_slice()));
850 for impl_item in impl_items.iter() {
852 ast::MethodImplItem(ref meth) => {
853 try!(self.print_method(&**meth));
855 ast::TypeImplItem(ref typ) => {
856 try!(self.print_typedef(&**typ));
860 try!(self.bclose(item.span));
862 ast::ItemTrait(ref generics, ref unbound, ref bounds, ref methods) => {
863 try!(self.head(visibility_qualified(item.vis,
864 "trait").as_slice()));
865 try!(self.print_ident(item.ident));
866 try!(self.print_generics(generics));
868 &Some(TraitTyParamBound(ref tref)) => {
869 try!(space(&mut self.s));
870 try!(self.word_space("for"));
871 try!(self.print_trait_ref(tref));
872 try!(word(&mut self.s, "?"));
876 try!(self.print_bounds(":", bounds));
877 try!(self.print_where_clause(generics));
878 try!(word(&mut self.s, " "));
880 for meth in methods.iter() {
881 try!(self.print_trait_method(meth));
883 try!(self.bclose(item.span));
885 // I think it's reasonable to hide the context here:
886 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
888 try!(self.print_visibility(item.vis));
889 try!(self.print_path(pth, false));
890 try!(word(&mut self.s, "! "));
891 try!(self.print_ident(item.ident));
892 try!(self.cbox(indent_unit));
894 try!(self.print_tts(tts.as_slice()));
899 self.ann.post(self, NodeItem(item))
902 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
903 if t.lifetimes.len() > 0 {
904 try!(self.print_generics(&ast::Generics {
905 lifetimes: t.lifetimes.clone(),
906 ty_params: OwnedSlice::empty(),
907 where_clause: ast::WhereClause {
908 id: ast::DUMMY_NODE_ID,
909 predicates: Vec::new(),
913 self.print_path(&t.path, false)
916 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
917 generics: &ast::Generics, ident: ast::Ident,
919 visibility: ast::Visibility) -> IoResult<()> {
920 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
921 try!(self.print_ident(ident));
922 try!(self.print_generics(generics));
923 try!(self.print_where_clause(generics));
924 try!(space(&mut self.s));
925 self.print_variants(enum_definition.variants.as_slice(), span)
928 pub fn print_variants(&mut self,
929 variants: &[P<ast::Variant>],
930 span: codemap::Span) -> IoResult<()> {
932 for v in variants.iter() {
933 try!(self.space_if_not_bol());
934 try!(self.maybe_print_comment(v.span.lo));
935 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
936 try!(self.ibox(indent_unit));
937 try!(self.print_variant(&**v));
938 try!(word(&mut self.s, ","));
940 try!(self.maybe_print_trailing_comment(v.span, None));
945 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
947 ast::Public => self.word_nbsp("pub"),
948 ast::Inherited => Ok(())
952 pub fn print_struct(&mut self,
953 struct_def: &ast::StructDef,
954 generics: &ast::Generics,
956 span: codemap::Span) -> IoResult<()> {
957 try!(self.print_ident(ident));
958 try!(self.print_generics(generics));
959 match struct_def.super_struct {
961 try!(self.word_space(":"));
962 try!(self.print_type(&**t));
966 if ast_util::struct_def_is_tuple_like(struct_def) {
967 if !struct_def.fields.is_empty() {
970 Inconsistent, struct_def.fields.as_slice(),
972 match field.node.kind {
973 ast::NamedField(..) => fail!("unexpected named field"),
974 ast::UnnamedField(vis) => {
975 try!(s.print_visibility(vis));
976 try!(s.maybe_print_comment(field.span.lo));
977 s.print_type(&*field.node.ty)
984 try!(word(&mut self.s, ";"));
986 self.end() // close the outer-box
990 try!(self.hardbreak_if_not_bol());
992 for field in struct_def.fields.iter() {
993 match field.node.kind {
994 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
995 ast::NamedField(ident, visibility) => {
996 try!(self.hardbreak_if_not_bol());
997 try!(self.maybe_print_comment(field.span.lo));
998 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
999 try!(self.print_visibility(visibility));
1000 try!(self.print_ident(ident));
1001 try!(self.word_nbsp(":"));
1002 try!(self.print_type(&*field.node.ty));
1003 try!(word(&mut self.s, ","));
1012 /// This doesn't deserve to be called "pretty" printing, but it should be
1013 /// meaning-preserving. A quick hack that might help would be to look at the
1014 /// spans embedded in the TTs to decide where to put spaces and newlines.
1015 /// But it'd be better to parse these according to the grammar of the
1016 /// appropriate macro, transcribe back into the grammar we just parsed from,
1017 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1018 /// expression arguments as expressions). It can be done! I think.
1019 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1021 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
1022 ast::TTTok(_, ref tk) => {
1023 try!(word(&mut self.s, parse::token::to_string(tk).as_slice()));
1025 parse::token::DOC_COMMENT(..) => {
1026 hardbreak(&mut self.s)
1031 ast::TTSeq(_, ref tts, ref sep, zerok) => {
1032 try!(word(&mut self.s, "$("));
1033 for tt_elt in (*tts).iter() {
1034 try!(self.print_tt(tt_elt));
1036 try!(word(&mut self.s, ")"));
1039 try!(word(&mut self.s,
1040 parse::token::to_string(tk).as_slice()));
1044 word(&mut self.s, if zerok { "*" } else { "+" })
1046 ast::TTNonterminal(_, name) => {
1047 try!(word(&mut self.s, "$"));
1048 self.print_ident(name)
1053 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1055 for (i, tt) in tts.iter().enumerate() {
1057 try!(space(&mut self.s));
1059 try!(self.print_tt(tt));
1064 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1065 try!(self.print_visibility(v.node.vis));
1067 ast::TupleVariantKind(ref args) => {
1068 try!(self.print_ident(v.node.name));
1069 if !args.is_empty() {
1071 try!(self.commasep(Consistent,
1073 |s, arg| s.print_type(&*arg.ty)));
1074 try!(self.pclose());
1077 ast::StructVariantKind(ref struct_def) => {
1078 try!(self.head(""));
1079 let generics = ast_util::empty_generics();
1080 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1083 match v.node.disr_expr {
1085 try!(space(&mut self.s));
1086 try!(self.word_space("="));
1087 self.print_expr(&**d)
1093 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1094 try!(self.hardbreak_if_not_bol());
1095 try!(self.maybe_print_comment(m.span.lo));
1096 try!(self.print_outer_attributes(m.attrs.as_slice()));
1097 try!(self.print_ty_fn(None,
1103 &OwnedSlice::empty(),
1105 Some(&m.explicit_self.node),
1107 word(&mut self.s, ";")
1110 pub fn print_trait_method(&mut self,
1111 m: &ast::TraitItem) -> IoResult<()> {
1113 RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1114 ProvidedMethod(ref m) => self.print_method(&**m),
1115 TypeTraitItem(ref t) => self.print_associated_type(&**t),
1119 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1121 MethodImplItem(ref m) => self.print_method(&**m),
1122 TypeImplItem(ref td) => self.print_typedef(&**td),
1126 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1127 try!(self.hardbreak_if_not_bol());
1128 try!(self.maybe_print_comment(meth.span.lo));
1129 try!(self.print_outer_attributes(meth.attrs.as_slice()));
1131 ast::MethDecl(ident,
1139 try!(self.print_fn(&**decl,
1144 Some(&explicit_self.node),
1146 try!(word(&mut self.s, " "));
1147 self.print_block_with_attrs(&**body, meth.attrs.as_slice())
1149 ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1151 // code copied from ItemMac:
1152 try!(self.print_path(pth, false));
1153 try!(word(&mut self.s, "! "));
1154 try!(self.cbox(indent_unit));
1156 try!(self.print_tts(tts.as_slice()));
1157 try!(self.pclose());
1163 pub fn print_outer_attributes(&mut self,
1164 attrs: &[ast::Attribute]) -> IoResult<()> {
1166 for attr in attrs.iter() {
1167 match attr.node.style {
1169 try!(self.print_attribute(attr));
1172 _ => {/* fallthrough */ }
1176 try!(self.hardbreak_if_not_bol());
1181 pub fn print_inner_attributes(&mut self,
1182 attrs: &[ast::Attribute]) -> IoResult<()> {
1184 for attr in attrs.iter() {
1185 match attr.node.style {
1187 try!(self.print_attribute(attr));
1190 _ => {/* fallthrough */ }
1194 try!(self.hardbreak_if_not_bol());
1199 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1200 try!(self.hardbreak_if_not_bol());
1201 try!(self.maybe_print_comment(attr.span.lo));
1202 if attr.node.is_sugared_doc {
1203 word(&mut self.s, attr.value_str().unwrap().get())
1205 match attr.node.style {
1206 ast::AttrInner => try!(word(&mut self.s, "#![")),
1207 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1209 try!(self.print_meta_item(&*attr.meta()));
1210 word(&mut self.s, "]")
1215 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1216 try!(self.maybe_print_comment(st.span.lo));
1218 ast::StmtDecl(ref decl, _) => {
1219 try!(self.print_decl(&**decl));
1221 ast::StmtExpr(ref expr, _) => {
1222 try!(self.space_if_not_bol());
1223 try!(self.print_expr(&**expr));
1225 ast::StmtSemi(ref expr, _) => {
1226 try!(self.space_if_not_bol());
1227 try!(self.print_expr(&**expr));
1228 try!(word(&mut self.s, ";"));
1230 ast::StmtMac(ref mac, semi) => {
1231 try!(self.space_if_not_bol());
1232 try!(self.print_mac(mac));
1234 try!(word(&mut self.s, ";"));
1238 if parse::classify::stmt_ends_with_semi(&st.node) {
1239 try!(word(&mut self.s, ";"));
1241 self.maybe_print_trailing_comment(st.span, None)
1244 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1245 self.print_block_with_attrs(blk, &[])
1248 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1249 self.print_block_unclosed_indent(blk, indent_unit)
1252 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1253 indented: uint) -> IoResult<()> {
1254 self.print_block_maybe_unclosed(blk, indented, &[], false)
1257 pub fn print_block_with_attrs(&mut self,
1259 attrs: &[ast::Attribute]) -> IoResult<()> {
1260 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1263 pub fn print_block_maybe_unclosed(&mut self,
1266 attrs: &[ast::Attribute],
1267 close_box: bool) -> IoResult<()> {
1269 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1270 ast::DefaultBlock => ()
1272 try!(self.maybe_print_comment(blk.span.lo));
1273 try!(self.ann.pre(self, NodeBlock(blk)));
1276 try!(self.print_inner_attributes(attrs));
1278 for vi in blk.view_items.iter() {
1279 try!(self.print_view_item(vi));
1281 for st in blk.stmts.iter() {
1282 try!(self.print_stmt(&**st));
1286 try!(self.space_if_not_bol());
1287 try!(self.print_expr(&**expr));
1288 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1292 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1293 self.ann.post(self, NodeBlock(blk))
1296 fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1300 // "another else-if"
1301 ast::ExprIf(ref i, ref then, ref e) => {
1302 try!(self.cbox(indent_unit - 1u));
1303 try!(self.ibox(0u));
1304 try!(word(&mut self.s, " else if "));
1305 try!(self.print_expr(&**i));
1306 try!(space(&mut self.s));
1307 try!(self.print_block(&**then));
1308 self.print_else(e.as_ref().map(|e| &**e))
1310 // "another else-if-let"
1311 ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1312 try!(self.cbox(indent_unit - 1u));
1313 try!(self.ibox(0u));
1314 try!(word(&mut self.s, " else if let "));
1315 try!(self.print_pat(&**pat));
1316 try!(space(&mut self.s));
1317 try!(self.word_space("="));
1318 try!(self.print_expr(&**expr));
1319 try!(space(&mut self.s));
1320 try!(self.print_block(&**then));
1321 self.print_else(e.as_ref().map(|e| &**e))
1324 ast::ExprBlock(ref b) => {
1325 try!(self.cbox(indent_unit - 1u));
1326 try!(self.ibox(0u));
1327 try!(word(&mut self.s, " else "));
1328 self.print_block(&**b)
1330 // BLEAH, constraints would be great here
1332 fail!("print_if saw if with weird alternative");
1340 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1341 elseopt: Option<&ast::Expr>) -> IoResult<()> {
1342 try!(self.head("if"));
1343 try!(self.print_expr(test));
1344 try!(space(&mut self.s));
1345 try!(self.print_block(blk));
1346 self.print_else(elseopt)
1349 pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1350 elseopt: Option<&ast::Expr>) -> IoResult<()> {
1351 try!(self.head("if let"));
1352 try!(self.print_pat(pat));
1353 try!(space(&mut self.s));
1354 try!(self.word_space("="));
1355 try!(self.print_expr(expr));
1356 try!(space(&mut self.s));
1357 try!(self.print_block(blk));
1358 self.print_else(elseopt)
1361 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1363 // I think it's reasonable to hide the ctxt here:
1364 ast::MacInvocTT(ref pth, ref tts, _) => {
1365 try!(self.print_path(pth, false));
1366 try!(word(&mut self.s, "!"));
1368 try!(self.print_tts(tts.as_slice()));
1375 fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1377 try!(self.commasep_exprs(Inconsistent, args));
1381 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1382 let needs_par = needs_parentheses(expr);
1386 try!(self.print_expr(expr));
1388 try!(self.pclose());
1393 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1394 try!(self.maybe_print_comment(expr.span.lo));
1395 try!(self.ibox(indent_unit));
1396 try!(self.ann.pre(self, NodeExpr(expr)));
1398 ast::ExprBox(ref p, ref e) => {
1399 try!(word(&mut self.s, "box"));
1400 try!(word(&mut self.s, "("));
1401 try!(self.print_expr(&**p));
1402 try!(self.word_space(")"));
1403 try!(self.print_expr(&**e));
1405 ast::ExprVec(ref exprs) => {
1406 try!(self.ibox(indent_unit));
1407 try!(word(&mut self.s, "["));
1408 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1409 try!(word(&mut self.s, "]"));
1413 ast::ExprRepeat(ref element, ref count) => {
1414 try!(self.ibox(indent_unit));
1415 try!(word(&mut self.s, "["));
1416 try!(self.print_expr(&**element));
1417 try!(word(&mut self.s, ","));
1418 try!(word(&mut self.s, ".."));
1419 try!(self.print_expr(&**count));
1420 try!(word(&mut self.s, "]"));
1424 ast::ExprStruct(ref path, ref fields, ref wth) => {
1425 try!(self.print_path(path, true));
1426 try!(word(&mut self.s, "{"));
1427 try!(self.commasep_cmnt(
1431 try!(s.ibox(indent_unit));
1432 try!(s.print_ident(field.ident.node));
1433 try!(s.word_space(":"));
1434 try!(s.print_expr(&*field.expr));
1440 try!(self.ibox(indent_unit));
1441 if !fields.is_empty() {
1442 try!(word(&mut self.s, ","));
1443 try!(space(&mut self.s));
1445 try!(word(&mut self.s, ".."));
1446 try!(self.print_expr(&**expr));
1449 _ => try!(word(&mut self.s, ","))
1451 try!(word(&mut self.s, "}"));
1453 ast::ExprTup(ref exprs) => {
1455 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1456 if exprs.len() == 1 {
1457 try!(word(&mut self.s, ","));
1459 try!(self.pclose());
1461 ast::ExprCall(ref func, ref args) => {
1462 try!(self.print_expr_maybe_paren(&**func));
1463 try!(self.print_call_post(args.as_slice()));
1465 ast::ExprMethodCall(ident, ref tys, ref args) => {
1466 let base_args = args.slice_from(1);
1467 try!(self.print_expr(&**args.get(0)));
1468 try!(word(&mut self.s, "."));
1469 try!(self.print_ident(ident.node));
1471 try!(word(&mut self.s, "::<"));
1472 try!(self.commasep(Inconsistent, tys.as_slice(),
1473 |s, ty| s.print_type(&**ty)));
1474 try!(word(&mut self.s, ">"));
1476 try!(self.print_call_post(base_args));
1478 ast::ExprBinary(op, ref lhs, ref rhs) => {
1479 try!(self.print_expr(&**lhs));
1480 try!(space(&mut self.s));
1481 try!(self.word_space(ast_util::binop_to_string(op)));
1482 try!(self.print_expr(&**rhs));
1484 ast::ExprUnary(op, ref expr) => {
1485 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1486 try!(self.print_expr_maybe_paren(&**expr));
1488 ast::ExprAddrOf(m, ref expr) => {
1489 try!(word(&mut self.s, "&"));
1490 try!(self.print_mutability(m));
1491 try!(self.print_expr_maybe_paren(&**expr));
1493 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1494 ast::ExprCast(ref expr, ref ty) => {
1495 try!(self.print_expr(&**expr));
1496 try!(space(&mut self.s));
1497 try!(self.word_space("as"));
1498 try!(self.print_type(&**ty));
1500 ast::ExprIf(ref test, ref blk, ref elseopt) => {
1501 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1503 ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1504 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1506 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1507 for ident in opt_ident.iter() {
1508 try!(self.print_ident(*ident));
1509 try!(self.word_space(":"));
1511 try!(self.head("while"));
1512 try!(self.print_expr(&**test));
1513 try!(space(&mut self.s));
1514 try!(self.print_block(&**blk));
1516 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1517 for ident in opt_ident.iter() {
1518 try!(self.print_ident(*ident));
1519 try!(self.word_space(":"));
1521 try!(self.head("for"));
1522 try!(self.print_pat(&**pat));
1523 try!(space(&mut self.s));
1524 try!(self.word_space("in"));
1525 try!(self.print_expr(&**iter));
1526 try!(space(&mut self.s));
1527 try!(self.print_block(&**blk));
1529 ast::ExprLoop(ref blk, opt_ident) => {
1530 for ident in opt_ident.iter() {
1531 try!(self.print_ident(*ident));
1532 try!(self.word_space(":"));
1534 try!(self.head("loop"));
1535 try!(space(&mut self.s));
1536 try!(self.print_block(&**blk));
1538 ast::ExprMatch(ref expr, ref arms, _) => {
1539 try!(self.cbox(indent_unit));
1541 try!(self.word_nbsp("match"));
1542 try!(self.print_expr(&**expr));
1543 try!(space(&mut self.s));
1545 for arm in arms.iter() {
1546 try!(self.print_arm(arm));
1548 try!(self.bclose_(expr.span, indent_unit));
1550 ast::ExprFnBlock(capture_clause, ref decl, ref body) => {
1551 try!(self.print_capture_clause(capture_clause));
1553 // in do/for blocks we don't want to show an empty
1554 // argument list, but at this point we don't know which
1557 // if !decl.inputs.is_empty() {
1558 try!(self.print_fn_block_args(&**decl, None));
1559 try!(space(&mut self.s));
1562 if !body.stmts.is_empty() || !body.expr.is_some() {
1563 try!(self.print_block_unclosed(&**body));
1565 // we extract the block, so as not to create another set of boxes
1566 match body.expr.as_ref().unwrap().node {
1567 ast::ExprBlock(ref blk) => {
1568 try!(self.print_block_unclosed(&**blk));
1571 // this is a bare expression
1572 try!(self.print_expr(&**body.expr.as_ref().unwrap()));
1573 try!(self.end()); // need to close a box
1577 // a box will be closed by print_expr, but we didn't want an overall
1578 // wrapper so we closed the corresponding opening. so create an
1579 // empty box to satisfy the close.
1582 ast::ExprUnboxedFn(capture_clause, kind, ref decl, ref body) => {
1583 try!(self.print_capture_clause(capture_clause));
1585 // in do/for blocks we don't want to show an empty
1586 // argument list, but at this point we don't know which
1589 // if !decl.inputs.is_empty() {
1590 try!(self.print_fn_block_args(&**decl, Some(kind)));
1591 try!(space(&mut self.s));
1594 if !body.stmts.is_empty() || !body.expr.is_some() {
1595 try!(self.print_block_unclosed(&**body));
1597 // we extract the block, so as not to create another set of boxes
1598 match body.expr.as_ref().unwrap().node {
1599 ast::ExprBlock(ref blk) => {
1600 try!(self.print_block_unclosed(&**blk));
1603 // this is a bare expression
1604 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1605 try!(self.end()); // need to close a box
1609 // a box will be closed by print_expr, but we didn't want an overall
1610 // wrapper so we closed the corresponding opening. so create an
1611 // empty box to satisfy the close.
1614 ast::ExprProc(ref decl, ref body) => {
1615 // in do/for blocks we don't want to show an empty
1616 // argument list, but at this point we don't know which
1619 // if !decl.inputs.is_empty() {
1620 try!(self.print_proc_args(&**decl));
1621 try!(space(&mut self.s));
1623 assert!(body.stmts.is_empty());
1624 assert!(body.expr.is_some());
1625 // we extract the block, so as not to create another set of boxes
1626 match body.expr.as_ref().unwrap().node {
1627 ast::ExprBlock(ref blk) => {
1628 try!(self.print_block_unclosed(&**blk));
1631 // this is a bare expression
1632 try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1633 try!(self.end()); // need to close a box
1636 // a box will be closed by print_expr, but we didn't want an overall
1637 // wrapper so we closed the corresponding opening. so create an
1638 // empty box to satisfy the close.
1641 ast::ExprBlock(ref blk) => {
1642 // containing cbox, will be closed by print-block at }
1643 try!(self.cbox(indent_unit));
1644 // head-box, will be closed by print-block after {
1645 try!(self.ibox(0u));
1646 try!(self.print_block(&**blk));
1648 ast::ExprAssign(ref lhs, ref rhs) => {
1649 try!(self.print_expr(&**lhs));
1650 try!(space(&mut self.s));
1651 try!(self.word_space("="));
1652 try!(self.print_expr(&**rhs));
1654 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1655 try!(self.print_expr(&**lhs));
1656 try!(space(&mut self.s));
1657 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1658 try!(self.word_space("="));
1659 try!(self.print_expr(&**rhs));
1661 ast::ExprField(ref expr, id, ref tys) => {
1662 try!(self.print_expr(&**expr));
1663 try!(word(&mut self.s, "."));
1664 try!(self.print_ident(id.node));
1666 try!(word(&mut self.s, "::<"));
1668 Inconsistent, tys.as_slice(),
1669 |s, ty| s.print_type(&**ty)));
1670 try!(word(&mut self.s, ">"));
1673 ast::ExprTupField(ref expr, id, ref tys) => {
1674 try!(self.print_expr(&**expr));
1675 try!(word(&mut self.s, "."));
1676 try!(self.print_uint(id.node));
1678 try!(word(&mut self.s, "::<"));
1680 Inconsistent, tys.as_slice(),
1681 |s, ty| s.print_type(&**ty)));
1682 try!(word(&mut self.s, ">"));
1685 ast::ExprIndex(ref expr, ref index) => {
1686 try!(self.print_expr(&**expr));
1687 try!(word(&mut self.s, "["));
1688 try!(self.print_expr(&**index));
1689 try!(word(&mut self.s, "]"));
1691 ast::ExprSlice(ref e, ref start, ref end, ref mutbl) => {
1692 try!(self.print_expr(&**e));
1693 try!(word(&mut self.s, "["));
1694 if mutbl == &ast::MutMutable {
1695 try!(word(&mut self.s, "mut"));
1696 if start.is_some() || end.is_some() {
1697 try!(space(&mut self.s));
1701 &Some(ref e) => try!(self.print_expr(&**e)),
1704 if start.is_some() || end.is_some() {
1705 try!(word(&mut self.s, ".."));
1708 &Some(ref e) => try!(self.print_expr(&**e)),
1711 try!(word(&mut self.s, "]"));
1713 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1714 ast::ExprBreak(opt_ident) => {
1715 try!(word(&mut self.s, "break"));
1716 try!(space(&mut self.s));
1717 for ident in opt_ident.iter() {
1718 try!(self.print_ident(*ident));
1719 try!(space(&mut self.s));
1722 ast::ExprAgain(opt_ident) => {
1723 try!(word(&mut self.s, "continue"));
1724 try!(space(&mut self.s));
1725 for ident in opt_ident.iter() {
1726 try!(self.print_ident(*ident));
1727 try!(space(&mut self.s))
1730 ast::ExprRet(ref result) => {
1731 try!(word(&mut self.s, "return"));
1734 try!(word(&mut self.s, " "));
1735 try!(self.print_expr(&**expr));
1740 ast::ExprInlineAsm(ref a) => {
1742 try!(word(&mut self.s, "__volatile__ asm!"));
1744 try!(word(&mut self.s, "asm!"));
1747 try!(self.print_string(a.asm.get(), a.asm_str_style));
1748 try!(self.word_space(":"));
1750 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1751 |s, &(ref co, ref o, is_rw)| {
1752 match co.get().slice_shift_char() {
1753 (Some('='), operand) if is_rw => {
1754 try!(s.print_string(format!("+{}", operand).as_slice(),
1757 _ => try!(s.print_string(co.get(), ast::CookedStr))
1760 try!(s.print_expr(&**o));
1764 try!(space(&mut self.s));
1765 try!(self.word_space(":"));
1767 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1768 |s, &(ref co, ref o)| {
1769 try!(s.print_string(co.get(), ast::CookedStr));
1771 try!(s.print_expr(&**o));
1775 try!(space(&mut self.s));
1776 try!(self.word_space(":"));
1778 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1779 try!(self.pclose());
1781 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1782 ast::ExprParen(ref e) => {
1784 try!(self.print_expr(&**e));
1785 try!(self.pclose());
1788 try!(self.ann.post(self, NodeExpr(expr)));
1792 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1793 try!(self.print_pat(&*loc.pat));
1795 ast::TyInfer => Ok(()),
1797 try!(self.word_space(":"));
1798 self.print_type(&*loc.ty)
1803 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1804 try!(self.maybe_print_comment(decl.span.lo));
1806 ast::DeclLocal(ref loc) => {
1807 try!(self.space_if_not_bol());
1808 try!(self.ibox(indent_unit));
1809 try!(self.word_nbsp("let"));
1811 try!(self.ibox(indent_unit));
1812 try!(self.print_local_decl(&**loc));
1817 try!(self.word_space("="));
1818 try!(self.print_expr(&**init));
1824 ast::DeclItem(ref item) => self.print_item(&**item)
1828 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1829 if self.encode_idents_with_hygiene {
1830 let encoded = ident.encode_with_hygiene();
1831 try!(word(&mut self.s, encoded.as_slice()))
1833 try!(word(&mut self.s, token::get_ident(ident).get()))
1835 self.ann.post(self, NodeIdent(&ident))
1838 pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1839 word(&mut self.s, i.to_string().as_slice())
1842 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1843 try!(word(&mut self.s, token::get_name(name).get()));
1844 self.ann.post(self, NodeName(&name))
1847 pub fn print_for_decl(&mut self, loc: &ast::Local,
1848 coll: &ast::Expr) -> IoResult<()> {
1849 try!(self.print_local_decl(loc));
1850 try!(space(&mut self.s));
1851 try!(self.word_space("in"));
1852 self.print_expr(coll)
1855 fn print_path_(&mut self,
1857 colons_before_params: bool,
1858 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1860 try!(self.maybe_print_comment(path.span.lo));
1862 try!(word(&mut self.s, "::"));
1865 let mut first = true;
1866 for segment in path.segments.iter() {
1870 try!(word(&mut self.s, "::"))
1873 try!(self.print_ident(segment.identifier));
1875 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1876 if colons_before_params {
1877 try!(word(&mut self.s, "::"))
1879 try!(word(&mut self.s, "<"));
1881 let mut comma = false;
1882 for lifetime in segment.lifetimes.iter() {
1884 try!(self.word_space(","))
1886 try!(self.print_lifetime(lifetime));
1890 if !segment.types.is_empty() {
1892 try!(self.word_space(","))
1896 segment.types.as_slice(),
1897 |s, ty| s.print_type(&**ty)));
1900 try!(word(&mut self.s, ">"))
1906 Some(ref bounds) => self.print_bounds("+", bounds)
1910 fn print_path(&mut self, path: &ast::Path,
1911 colons_before_params: bool) -> IoResult<()> {
1912 self.print_path_(path, colons_before_params, &None)
1915 fn print_bounded_path(&mut self, path: &ast::Path,
1916 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1918 self.print_path_(path, false, bounds)
1921 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1922 try!(self.maybe_print_comment(pat.span.lo));
1923 try!(self.ann.pre(self, NodePat(pat)));
1924 /* Pat isn't normalized, but the beauty of it
1925 is that it doesn't matter */
1927 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
1928 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
1929 ast::PatIdent(binding_mode, ref path1, ref sub) => {
1930 match binding_mode {
1931 ast::BindByRef(mutbl) => {
1932 try!(self.word_nbsp("ref"));
1933 try!(self.print_mutability(mutbl));
1935 ast::BindByValue(ast::MutImmutable) => {}
1936 ast::BindByValue(ast::MutMutable) => {
1937 try!(self.word_nbsp("mut"));
1940 try!(self.print_ident(path1.node));
1943 try!(word(&mut self.s, "@"));
1944 try!(self.print_pat(&**p));
1949 ast::PatEnum(ref path, ref args_) => {
1950 try!(self.print_path(path, true));
1952 None => try!(word(&mut self.s, "(..)")),
1954 if !args.is_empty() {
1956 try!(self.commasep(Inconsistent, args.as_slice(),
1957 |s, p| s.print_pat(&**p)));
1958 try!(self.pclose());
1963 ast::PatStruct(ref path, ref fields, etc) => {
1964 try!(self.print_path(path, true));
1966 try!(self.word_space("{"));
1967 try!(self.commasep_cmnt(
1968 Consistent, fields.as_slice(),
1970 try!(s.cbox(indent_unit));
1971 try!(s.print_ident(f.ident));
1972 try!(s.word_nbsp(":"));
1973 try!(s.print_pat(&*f.pat));
1978 if fields.len() != 0u { try!(self.word_space(",")); }
1979 try!(word(&mut self.s, ".."));
1981 try!(space(&mut self.s));
1982 try!(word(&mut self.s, "}"));
1984 ast::PatTup(ref elts) => {
1986 try!(self.commasep(Inconsistent,
1988 |s, p| s.print_pat(&**p)));
1989 if elts.len() == 1 {
1990 try!(word(&mut self.s, ","));
1992 try!(self.pclose());
1994 ast::PatBox(ref inner) => {
1995 try!(word(&mut self.s, "box "));
1996 try!(self.print_pat(&**inner));
1998 ast::PatRegion(ref inner) => {
1999 try!(word(&mut self.s, "&"));
2000 try!(self.print_pat(&**inner));
2002 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2003 ast::PatRange(ref begin, ref end) => {
2004 try!(self.print_expr(&**begin));
2005 try!(space(&mut self.s));
2006 try!(word(&mut self.s, "..."));
2007 try!(self.print_expr(&**end));
2009 ast::PatVec(ref before, ref slice, ref after) => {
2010 try!(word(&mut self.s, "["));
2011 try!(self.commasep(Inconsistent,
2013 |s, p| s.print_pat(&**p)));
2014 for p in slice.iter() {
2015 if !before.is_empty() { try!(self.word_space(",")); }
2016 try!(self.print_pat(&**p));
2018 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2019 // this case is handled by print_pat
2021 _ => try!(word(&mut self.s, "..")),
2023 if !after.is_empty() { try!(self.word_space(",")); }
2025 try!(self.commasep(Inconsistent,
2027 |s, p| s.print_pat(&**p)));
2028 try!(word(&mut self.s, "]"));
2030 ast::PatMac(ref m) => try!(self.print_mac(m)),
2032 self.ann.post(self, NodePat(pat))
2035 fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2036 // I have no idea why this check is necessary, but here it
2038 if arm.attrs.is_empty() {
2039 try!(space(&mut self.s));
2041 try!(self.cbox(indent_unit));
2042 try!(self.ibox(0u));
2043 try!(self.print_outer_attributes(arm.attrs.as_slice()));
2044 let mut first = true;
2045 for p in arm.pats.iter() {
2049 try!(space(&mut self.s));
2050 try!(self.word_space("|"));
2052 try!(self.print_pat(&**p));
2054 try!(space(&mut self.s));
2057 try!(self.word_space("if"));
2058 try!(self.print_expr(&**e));
2059 try!(space(&mut self.s));
2063 try!(self.word_space("=>"));
2065 match arm.body.node {
2066 ast::ExprBlock(ref blk) => {
2067 // the block will close the pattern's ibox
2068 try!(self.print_block_unclosed_indent(&**blk,
2072 try!(self.end()); // close the ibox for the pattern
2073 try!(self.print_expr(&*arm.body));
2074 try!(word(&mut self.s, ","));
2077 self.end() // close enclosing cbox
2080 // Returns whether it printed anything
2081 fn print_explicit_self(&mut self,
2082 explicit_self: &ast::ExplicitSelf_,
2083 mutbl: ast::Mutability) -> IoResult<bool> {
2084 try!(self.print_mutability(mutbl));
2085 match *explicit_self {
2086 ast::SelfStatic => { return Ok(false); }
2087 ast::SelfValue(_) => {
2088 try!(word(&mut self.s, "self"));
2090 ast::SelfRegion(ref lt, m, _) => {
2091 try!(word(&mut self.s, "&"));
2092 try!(self.print_opt_lifetime(lt));
2093 try!(self.print_mutability(m));
2094 try!(word(&mut self.s, "self"));
2096 ast::SelfExplicit(ref typ, _) => {
2097 try!(word(&mut self.s, "self"));
2098 try!(self.word_space(":"));
2099 try!(self.print_type(&**typ));
2105 pub fn print_fn(&mut self,
2107 fn_style: Option<ast::FnStyle>,
2110 generics: &ast::Generics,
2111 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2112 vis: ast::Visibility) -> IoResult<()> {
2113 try!(self.head(""));
2114 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
2116 try!(self.print_ident(name));
2117 try!(self.print_generics(generics));
2118 try!(self.print_fn_args_and_ret(decl, opt_explicit_self))
2119 self.print_where_clause(generics)
2122 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2123 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2125 // It is unfortunate to duplicate the commasep logic, but we want the
2126 // self type and the args all in the same box.
2127 try!(self.rbox(0u, Inconsistent));
2128 let mut first = true;
2129 for &explicit_self in opt_explicit_self.iter() {
2130 let m = match explicit_self {
2131 &ast::SelfStatic => ast::MutImmutable,
2132 _ => match decl.inputs.get(0).pat.node {
2133 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2134 _ => ast::MutImmutable
2137 first = !try!(self.print_explicit_self(explicit_self, m));
2140 // HACK(eddyb) ignore the separately printed self argument.
2141 let args = if first {
2142 decl.inputs.as_slice()
2144 decl.inputs.slice_from(1)
2147 for arg in args.iter() {
2148 if first { first = false; } else { try!(self.word_space(",")); }
2149 try!(self.print_arg(arg));
2155 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2156 opt_explicit_self: Option<&ast::ExplicitSelf_>)
2159 try!(self.print_fn_args(decl, opt_explicit_self));
2161 try!(word(&mut self.s, ", ..."));
2163 try!(self.pclose());
2165 try!(self.maybe_print_comment(decl.output.span.lo));
2166 match decl.output.node {
2167 ast::TyNil => Ok(()),
2169 try!(self.space_if_not_bol());
2170 try!(self.word_space("->"));
2171 self.print_type(&*decl.output)
2176 pub fn print_fn_block_args(
2179 unboxed_closure_kind: Option<UnboxedClosureKind>)
2181 try!(word(&mut self.s, "|"));
2182 match unboxed_closure_kind {
2184 Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2185 Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2186 Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2188 try!(self.print_fn_args(decl, None));
2189 try!(word(&mut self.s, "|"));
2191 match decl.output.node {
2194 try!(self.space_if_not_bol());
2195 try!(self.word_space("->"));
2196 try!(self.print_type(&*decl.output));
2200 self.maybe_print_comment(decl.output.span.lo)
2203 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2205 match capture_clause {
2206 ast::CaptureByValue => self.word_space("move"),
2207 ast::CaptureByRef => Ok(()),
2211 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2212 try!(word(&mut self.s, "proc"));
2213 try!(word(&mut self.s, "("));
2214 try!(self.print_fn_args(decl, None));
2215 try!(word(&mut self.s, ")"));
2217 match decl.output.node {
2220 try!(self.space_if_not_bol());
2221 try!(self.word_space("->"));
2222 try!(self.print_type(&*decl.output));
2226 self.maybe_print_comment(decl.output.span.lo)
2229 pub fn print_bounds(&mut self,
2231 bounds: &OwnedSlice<ast::TyParamBound>)
2233 if !bounds.is_empty() {
2234 try!(word(&mut self.s, prefix));
2235 let mut first = true;
2236 for bound in bounds.iter() {
2241 try!(self.word_space("+"));
2245 TraitTyParamBound(ref tref) => {
2246 self.print_trait_ref(tref)
2248 RegionTyParamBound(ref lt) => {
2249 self.print_lifetime(lt)
2251 UnboxedFnTyParamBound(ref unboxed_function_type) => {
2252 try!(self.print_path(&unboxed_function_type.path,
2255 try!(self.print_fn_args(&*unboxed_function_type.decl,
2257 try!(self.pclose());
2258 self.print_fn_output(&*unboxed_function_type.decl)
2268 pub fn print_lifetime(&mut self,
2269 lifetime: &ast::Lifetime)
2272 self.print_name(lifetime.name)
2275 pub fn print_lifetime_def(&mut self,
2276 lifetime: &ast::LifetimeDef)
2279 try!(self.print_lifetime(&lifetime.lifetime));
2281 for v in lifetime.bounds.iter() {
2282 try!(word(&mut self.s, sep));
2283 try!(self.print_lifetime(v));
2289 pub fn print_generics(&mut self,
2290 generics: &ast::Generics)
2293 let total = generics.lifetimes.len() + generics.ty_params.len();
2298 try!(word(&mut self.s, "<"));
2300 let mut ints = Vec::new();
2301 for i in range(0u, total) {
2305 try!(self.commasep(Inconsistent, ints.as_slice(), |s, &idx| {
2306 if idx < generics.lifetimes.len() {
2307 let lifetime = generics.lifetimes.get(idx);
2308 s.print_lifetime_def(lifetime)
2310 let idx = idx - generics.lifetimes.len();
2311 let param = generics.ty_params.get(idx);
2312 match param.unbound {
2313 Some(TraitTyParamBound(ref tref)) => {
2314 try!(s.print_trait_ref(tref));
2315 try!(s.word_space("?"));
2319 try!(s.print_ident(param.ident));
2320 try!(s.print_bounds(":", ¶m.bounds));
2321 match param.default {
2322 Some(ref default) => {
2323 try!(space(&mut s.s));
2324 try!(s.word_space("="));
2325 s.print_type(&**default)
2332 try!(word(&mut self.s, ">"));
2336 pub fn print_where_clause(&mut self, generics: &ast::Generics)
2338 if generics.where_clause.predicates.len() == 0 {
2342 try!(space(&mut self.s));
2343 try!(self.word_space("where"));
2345 for (i, predicate) in generics.where_clause
2350 try!(self.word_space(","));
2353 try!(self.print_ident(predicate.ident));
2354 try!(self.print_bounds(":", &predicate.bounds));
2360 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2361 try!(self.ibox(indent_unit));
2363 ast::MetaWord(ref name) => {
2364 try!(word(&mut self.s, name.get()));
2366 ast::MetaNameValue(ref name, ref value) => {
2367 try!(self.word_space(name.get()));
2368 try!(self.word_space("="));
2369 try!(self.print_literal(value));
2371 ast::MetaList(ref name, ref items) => {
2372 try!(word(&mut self.s, name.get()));
2374 try!(self.commasep(Consistent,
2376 |s, i| s.print_meta_item(&**i)));
2377 try!(self.pclose());
2383 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2385 ast::ViewPathSimple(ident, ref path, _) => {
2386 try!(self.print_path(path, false));
2388 // FIXME(#6993) can't compare identifiers directly here
2389 if path.segments.last().unwrap().identifier.name !=
2391 try!(space(&mut self.s));
2392 try!(self.word_space("as"));
2393 try!(self.print_ident(ident));
2399 ast::ViewPathGlob(ref path, _) => {
2400 try!(self.print_path(path, false));
2401 word(&mut self.s, "::*")
2404 ast::ViewPathList(ref path, ref idents, _) => {
2405 if path.segments.is_empty() {
2406 try!(word(&mut self.s, "{"));
2408 try!(self.print_path(path, false));
2409 try!(word(&mut self.s, "::{"));
2411 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2413 ast::PathListIdent { name, .. } => {
2416 ast::PathListMod { .. } => {
2417 word(&mut s.s, "mod")
2421 word(&mut self.s, "}")
2426 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2427 try!(self.hardbreak_if_not_bol());
2428 try!(self.maybe_print_comment(item.span.lo));
2429 try!(self.print_outer_attributes(item.attrs.as_slice()));
2430 try!(self.print_visibility(item.vis));
2432 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2433 try!(self.head("extern crate"));
2434 for &(ref p, style) in optional_path.iter() {
2435 try!(self.print_string(p.get(), style));
2436 try!(space(&mut self.s));
2437 try!(word(&mut self.s, "as"));
2438 try!(space(&mut self.s));
2440 try!(self.print_ident(id));
2443 ast::ViewItemUse(ref vp) => {
2444 try!(self.head("use"));
2445 try!(self.print_view_path(&**vp));
2448 try!(word(&mut self.s, ";"));
2449 try!(self.end()); // end inner head-block
2450 self.end() // end outer head-block
2453 pub fn print_mutability(&mut self,
2454 mutbl: ast::Mutability) -> IoResult<()> {
2456 ast::MutMutable => self.word_nbsp("mut"),
2457 ast::MutImmutable => Ok(()),
2461 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2462 try!(self.print_mutability(mt.mutbl));
2463 self.print_type(&*mt.ty)
2466 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2467 try!(self.ibox(indent_unit));
2468 match input.ty.node {
2469 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2471 match input.pat.node {
2472 ast::PatIdent(_, ref path1, _) if
2474 parse::token::special_idents::invalid.name => {
2478 try!(self.print_pat(&*input.pat));
2479 try!(word(&mut self.s, ":"));
2480 try!(space(&mut self.s));
2483 try!(self.print_type(&*input.ty));
2489 pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2490 match decl.output.node {
2491 ast::TyNil => Ok(()),
2493 try!(self.space_if_not_bol());
2494 try!(self.ibox(indent_unit));
2495 try!(self.word_space("->"));
2496 if decl.cf == ast::NoReturn {
2497 try!(self.word_nbsp("!"));
2499 try!(self.print_type(&*decl.output));
2506 pub fn print_ty_fn(&mut self,
2507 opt_abi: Option<abi::Abi>,
2508 opt_sigil: Option<char>,
2509 fn_style: ast::FnStyle,
2510 onceness: ast::Onceness,
2512 id: Option<ast::Ident>,
2513 bounds: &OwnedSlice<ast::TyParamBound>,
2514 generics: Option<&ast::Generics>,
2515 opt_explicit_self: Option<&ast::ExplicitSelf_>,
2516 opt_unboxed_closure_kind:
2517 Option<ast::UnboxedClosureKind>)
2519 try!(self.ibox(indent_unit));
2521 // Duplicates the logic in `print_fn_header_info()`. This is because that
2522 // function prints the sigil in the wrong place. That should be fixed.
2523 if opt_sigil == Some('~') && onceness == ast::Once {
2524 try!(word(&mut self.s, "proc"));
2525 } else if opt_sigil == Some('&') {
2526 try!(self.print_fn_style(fn_style));
2527 try!(self.print_extern_opt_abi(opt_abi));
2528 try!(self.print_onceness(onceness));
2530 assert!(opt_sigil.is_none());
2531 try!(self.print_fn_style(fn_style));
2532 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2533 try!(self.print_onceness(onceness));
2534 if opt_unboxed_closure_kind.is_none() {
2535 try!(word(&mut self.s, "fn"));
2541 try!(word(&mut self.s, " "));
2542 try!(self.print_ident(id));
2547 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2548 try!(zerobreak(&mut self.s));
2550 if opt_unboxed_closure_kind.is_some() || opt_sigil == Some('&') {
2551 try!(word(&mut self.s, "|"));
2556 match opt_unboxed_closure_kind {
2557 Some(ast::FnUnboxedClosureKind) => {
2558 try!(word(&mut self.s, "&"));
2559 try!(self.word_space(":"));
2561 Some(ast::FnMutUnboxedClosureKind) => {
2562 try!(word(&mut self.s, "&mut"));
2563 try!(self.word_space(":"));
2565 Some(ast::FnOnceUnboxedClosureKind) => {
2566 try!(self.word_space(":"));
2571 try!(self.print_fn_args(decl, opt_explicit_self));
2573 if opt_unboxed_closure_kind.is_some() || opt_sigil == Some('&') {
2574 try!(word(&mut self.s, "|"));
2577 try!(word(&mut self.s, ", ..."));
2579 try!(self.pclose());
2582 try!(self.print_bounds(":", bounds));
2584 try!(self.maybe_print_comment(decl.output.span.lo));
2586 try!(self.print_fn_output(decl));
2589 Some(generics) => try!(self.print_where_clause(generics)),
2596 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2597 next_pos: Option<BytePos>)
2599 let cm = match self.cm {
2603 match self.next_comment() {
2605 if (*cmnt).style != comments::Trailing { return Ok(()) }
2606 let span_line = cm.lookup_char_pos(span.hi);
2607 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2608 let mut next = (*cmnt).pos + BytePos(1);
2609 match next_pos { None => (), Some(p) => next = p }
2610 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2611 span_line.line == comment_line.line {
2612 try!(self.print_comment(cmnt));
2613 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2621 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2622 // If there aren't any remaining comments, then we need to manually
2623 // make sure there is a line break at the end.
2624 if self.next_comment().is_none() {
2625 try!(hardbreak(&mut self.s));
2628 match self.next_comment() {
2630 try!(self.print_comment(cmnt));
2631 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2639 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2640 try!(self.maybe_print_comment(lit.span.lo));
2641 match self.next_lit(lit.span.lo) {
2643 return word(&mut self.s, (*ltrl).lit.as_slice());
2648 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2649 ast::LitByte(byte) => {
2650 let mut res = String::from_str("b'");
2651 (byte as char).escape_default(|c| res.push_char(c));
2652 res.push_char('\'');
2653 word(&mut self.s, res.as_slice())
2655 ast::LitChar(ch) => {
2656 let mut res = String::from_str("'");
2657 ch.escape_default(|c| res.push_char(c));
2658 res.push_char('\'');
2659 word(&mut self.s, res.as_slice())
2661 ast::LitInt(i, t) => {
2663 ast::SignedIntLit(st, ast::Plus) => {
2665 ast_util::int_ty_to_string(st, Some(i as i64)).as_slice())
2667 ast::SignedIntLit(st, ast::Minus) => {
2669 ast_util::int_ty_to_string(st, Some(-(i as i64))).as_slice())
2671 ast::UnsignedIntLit(ut) => {
2672 word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
2674 ast::UnsuffixedIntLit(ast::Plus) => {
2675 word(&mut self.s, format!("{}", i).as_slice())
2677 ast::UnsuffixedIntLit(ast::Minus) => {
2678 word(&mut self.s, format!("-{}", i).as_slice())
2682 ast::LitFloat(ref f, t) => {
2687 ast_util::float_ty_to_string(t).as_slice()).as_slice())
2689 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2690 ast::LitNil => word(&mut self.s, "()"),
2691 ast::LitBool(val) => {
2692 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2694 ast::LitBinary(ref v) => {
2695 let escaped: String = v.iter().map(|&b| b as char).collect();
2696 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2701 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2702 match self.literals {
2704 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2705 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2706 if ltrl.pos > pos { return None; }
2707 self.cur_cmnt_and_lit.cur_lit += 1u;
2708 if ltrl.pos == pos { return Some(ltrl); }
2716 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2718 match self.next_comment() {
2720 if (*cmnt).pos < pos {
2721 try!(self.print_comment(cmnt));
2722 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2731 pub fn print_comment(&mut self,
2732 cmnt: &comments::Comment) -> IoResult<()> {
2734 comments::Mixed => {
2735 assert_eq!(cmnt.lines.len(), 1u);
2736 try!(zerobreak(&mut self.s));
2737 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2738 zerobreak(&mut self.s)
2740 comments::Isolated => {
2741 try!(self.hardbreak_if_not_bol());
2742 for line in cmnt.lines.iter() {
2743 // Don't print empty lines because they will end up as trailing
2745 if !line.is_empty() {
2746 try!(word(&mut self.s, line.as_slice()));
2748 try!(hardbreak(&mut self.s));
2752 comments::Trailing => {
2753 try!(word(&mut self.s, " "));
2754 if cmnt.lines.len() == 1u {
2755 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2756 hardbreak(&mut self.s)
2758 try!(self.ibox(0u));
2759 for line in cmnt.lines.iter() {
2760 if !line.is_empty() {
2761 try!(word(&mut self.s, line.as_slice()));
2763 try!(hardbreak(&mut self.s));
2768 comments::BlankLine => {
2769 // We need to do at least one, possibly two hardbreaks.
2770 let is_semi = match self.s.last_token() {
2771 pp::String(s, _) => ";" == s.as_slice(),
2774 if is_semi || self.is_begin() || self.is_end() {
2775 try!(hardbreak(&mut self.s));
2777 hardbreak(&mut self.s)
2782 pub fn print_string(&mut self, st: &str,
2783 style: ast::StrStyle) -> IoResult<()> {
2784 let st = match style {
2786 (format!("\"{}\"", st.escape_default()))
2789 (format!("r{delim}\"{string}\"{delim}",
2790 delim="#".repeat(n),
2794 word(&mut self.s, st.as_slice())
2797 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2798 match self.comments {
2799 Some(ref cmnts) => {
2800 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2801 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2810 pub fn print_opt_fn_style(&mut self,
2811 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2812 match opt_fn_style {
2813 Some(fn_style) => self.print_fn_style(fn_style),
2818 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2819 opt_abi: Option<abi::Abi>)
2822 Some(abi::Rust) => Ok(()),
2824 try!(self.word_nbsp("extern"));
2825 self.word_nbsp(abi.to_string().as_slice())
2831 pub fn print_extern_opt_abi(&mut self,
2832 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2835 try!(self.word_nbsp("extern"));
2836 self.word_nbsp(abi.to_string().as_slice())
2842 pub fn print_fn_header_info(&mut self,
2843 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2844 opt_fn_style: Option<ast::FnStyle>,
2846 vis: ast::Visibility) -> IoResult<()> {
2847 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2848 try!(self.print_opt_fn_style(opt_fn_style));
2850 if abi != abi::Rust {
2851 try!(self.word_nbsp("extern"));
2852 try!(self.word_nbsp(abi.to_string().as_slice()));
2855 word(&mut self.s, "fn")
2858 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2860 ast::NormalFn => Ok(()),
2861 ast::UnsafeFn => self.word_nbsp("unsafe"),
2865 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2867 ast::Once => self.word_nbsp("once"),
2884 fn test_fun_to_string() {
2885 let abba_ident = token::str_to_ident("abba");
2887 let decl = ast::FnDecl {
2889 output: P(ast::Ty {id: 0,
2891 span: codemap::DUMMY_SP}),
2895 let generics = ast_util::empty_generics();
2896 assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident,
2898 &"fn abba()".to_string());
2902 fn test_variant_to_string() {
2903 let ident = token::str_to_ident("principal_skinner");
2905 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2908 // making this up as I go.... ?
2909 kind: ast::TupleVariantKind(Vec::new()),
2915 let varstr = variant_to_string(&var);
2916 assert_eq!(&varstr,&"pub principal_skinner".to_string());