1 // Copyright 2012 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::{P, StaticRegionTyParamBound, OtherRegionTyParamBound};
13 use ast::{TraitTyParamBound, UnboxedFnTyParamBound, Required, Provided};
16 use owned_slice::OwnedSlice;
17 use attr::{AttrMetaMethods, AttributeMethods};
18 use codemap::{CodeMap, BytePos};
21 use parse::classify::expr_is_simple_block;
23 use parse::lexer::comments;
25 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, Consistent, Inconsistent, eof};
30 use std::io::{IoResult, MemWriter};
35 pub enum AnnNode<'a> {
36 NodeBlock(&'a ast::Block),
37 NodeItem(&'a ast::Item),
38 NodeExpr(&'a ast::Expr),
39 NodePat(&'a ast::Pat),
43 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
44 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
49 impl PpAnn for NoAnn {}
51 pub struct CurrentCommentAndLiteral {
56 pub struct State<'a> {
58 cm: Option<&'a CodeMap>,
59 comments: Option<Vec<comments::Comment> >,
60 literals: Option<Vec<comments::Literal> >,
61 cur_cmnt_and_lit: CurrentCommentAndLiteral,
62 boxes: Vec<pp::Breaks>,
66 pub fn rust_printer(writer: Box<io::Writer>) -> State<'static> {
67 static NO_ANN: NoAnn = NoAnn;
68 rust_printer_annotated(writer, &NO_ANN)
71 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer>,
72 ann: &'a PpAnn) -> State<'a> {
74 s: pp::mk_printer(writer, default_columns),
78 cur_cmnt_and_lit: CurrentCommentAndLiteral {
87 pub static indent_unit: uint = 4u;
89 pub static default_columns: uint = 78u;
91 /// Requires you to pass an input filename and reader so that
92 /// it can scan the input text for comments and literals to
94 pub fn print_crate<'a>(cm: &'a CodeMap,
95 span_diagnostic: &diagnostic::SpanHandler,
98 input: &mut io::Reader,
101 is_expanded: bool) -> IoResult<()> {
102 let (cmnts, lits) = comments::gather_comments_and_literals(
108 s: pp::mk_printer(out, default_columns),
110 comments: Some(cmnts),
111 // If the code is post expansion, don't use the table of
112 // literals, since it doesn't correspond with the literals
113 // in the AST anymore.
114 literals: if is_expanded {
119 cur_cmnt_and_lit: CurrentCommentAndLiteral {
126 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
127 try!(s.print_remaining_comments());
131 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
132 let mut s = rust_printer(box MemWriter::new());
134 eof(&mut s.s).unwrap();
136 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
137 // that we "know" to be a `MemWriter` that works around the lack of checked
139 let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);
141 str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();
147 pub fn ty_to_string(ty: &ast::Ty) -> String {
148 to_string(|s| s.print_type(ty))
151 pub fn pat_to_string(pat: &ast::Pat) -> String {
152 to_string(|s| s.print_pat(pat))
155 pub fn expr_to_string(e: &ast::Expr) -> String {
156 to_string(|s| s.print_expr(e))
159 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
160 to_string(|s| s.print_lifetime(e))
163 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
164 to_string(|s| s.print_tt(tt))
167 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
168 to_string(|s| s.print_tts(tts))
171 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
172 to_string(|s| s.print_stmt(stmt))
175 pub fn item_to_string(i: &ast::Item) -> String {
176 to_string(|s| s.print_item(i))
179 pub fn generics_to_string(generics: &ast::Generics) -> String {
180 to_string(|s| s.print_generics(generics))
183 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
184 to_string(|s| s.print_ty_method(p))
187 pub fn method_to_string(p: &ast::Method) -> String {
188 to_string(|s| s.print_method(p))
191 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
192 to_string(|s| s.print_fn_block_args(p))
195 pub fn path_to_string(p: &ast::Path) -> String {
196 to_string(|s| s.print_path(p, false))
199 pub fn ident_to_string(id: &ast::Ident) -> String {
200 to_string(|s| s.print_ident(*id))
203 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
204 opt_explicit_self: Option<ast::ExplicitSelf_>,
205 generics: &ast::Generics) -> String {
207 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
208 name, generics, opt_explicit_self, ast::Inherited));
209 try!(s.end()); // Close the head box
210 s.end() // Close the outer box
214 pub fn block_to_string(blk: &ast::Block) -> String {
216 // containing cbox, will be closed by print-block at }
217 try!(s.cbox(indent_unit));
218 // head-ibox, will be closed by print-block after {
224 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
225 to_string(|s| s.print_meta_item(mi))
228 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
229 to_string(|s| s.print_attribute(attr))
232 pub fn lit_to_string(l: &ast::Lit) -> String {
233 to_string(|s| s.print_literal(l))
236 pub fn explicit_self_to_string(explicit_self: ast::ExplicitSelf_) -> String {
237 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
240 pub fn variant_to_string(var: &ast::Variant) -> String {
241 to_string(|s| s.print_variant(var))
244 pub fn arg_to_string(arg: &ast::Arg) -> String {
245 to_string(|s| s.print_arg(arg))
251 pub fn to_str(f: |&mut State| -> IoResult<()>) -> String {
252 let mut s = rust_printer(box MemWriter::new());
254 eof(&mut s.s).unwrap();
256 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
257 // that we "know" to be a `MemWriter` that works around the lack of checked
259 let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);
261 str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();
268 pub fn ty_to_str(ty: &ast::Ty) -> String {
269 to_str(|s| s.print_type(ty))
273 pub fn pat_to_str(pat: &ast::Pat) -> String {
274 to_str(|s| s.print_pat(pat))
278 pub fn expr_to_str(e: &ast::Expr) -> String {
279 to_str(|s| s.print_expr(e))
283 pub fn lifetime_to_str(e: &ast::Lifetime) -> String {
284 to_str(|s| s.print_lifetime(e))
288 pub fn tt_to_str(tt: &ast::TokenTree) -> String {
289 to_str(|s| s.print_tt(tt))
293 pub fn tts_to_str(tts: &[ast::TokenTree]) -> String {
294 to_str(|s| s.print_tts(tts))
298 pub fn stmt_to_str(stmt: &ast::Stmt) -> String {
299 to_str(|s| s.print_stmt(stmt))
303 pub fn item_to_str(i: &ast::Item) -> String {
304 to_str(|s| s.print_item(i))
308 pub fn generics_to_str(generics: &ast::Generics) -> String {
309 to_str(|s| s.print_generics(generics))
313 pub fn ty_method_to_str(p: &ast::TypeMethod) -> String {
314 to_str(|s| s.print_ty_method(p))
318 pub fn method_to_str(p: &ast::Method) -> String {
319 to_str(|s| s.print_method(p))
323 pub fn fn_block_to_str(p: &ast::FnDecl) -> String {
324 to_str(|s| s.print_fn_block_args(p))
328 pub fn path_to_str(p: &ast::Path) -> String {
329 to_str(|s| s.print_path(p, false))
333 pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
334 opt_explicit_self: Option<ast::ExplicitSelf_>,
335 generics: &ast::Generics) -> String {
337 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
338 name, generics, opt_explicit_self, ast::Inherited));
339 try!(s.end()); // Close the head box
340 s.end() // Close the outer box
345 pub fn block_to_str(blk: &ast::Block) -> String {
347 // containing cbox, will be closed by print-block at }
348 try!(s.cbox(indent_unit));
349 // head-ibox, will be closed by print-block after {
356 pub fn meta_item_to_str(mi: &ast::MetaItem) -> String {
357 to_str(|s| s.print_meta_item(mi))
361 pub fn attribute_to_str(attr: &ast::Attribute) -> String {
362 to_str(|s| s.print_attribute(attr))
366 pub fn lit_to_str(l: &ast::Lit) -> String {
367 to_str(|s| s.print_literal(l))
371 pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> String {
372 to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
376 pub fn variant_to_str(var: &ast::Variant) -> String {
377 to_str(|s| s.print_variant(var))
381 pub fn arg_to_str(arg: &ast::Arg) -> String {
382 to_str(|s| s.print_arg(arg))
388 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
390 ast::Public => format!("pub {}", s),
391 ast::Inherited => s.to_string()
395 fn needs_parentheses(expr: &ast::Expr) -> bool {
397 ast::ExprAssign(..) | ast::ExprBinary(..) |
398 ast::ExprFnBlock(..) | ast::ExprProc(..) |
399 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
405 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
406 self.boxes.push(pp::Inconsistent);
407 pp::ibox(&mut self.s, u)
410 pub fn end(&mut self) -> IoResult<()> {
411 self.boxes.pop().unwrap();
415 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
416 self.boxes.push(pp::Consistent);
417 pp::cbox(&mut self.s, u)
421 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
423 pp::rbox(&mut self.s, u, b)
426 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
428 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
429 try!(word(&mut self.s, w));
433 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
434 try!(word(&mut self.s, w));
438 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
440 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
442 pub fn head(&mut self, w: &str) -> IoResult<()> {
443 // outer-box is consistent
444 try!(self.cbox(indent_unit));
445 // head-box is inconsistent
446 try!(self.ibox(w.len() + 1));
447 // keyword that starts the head
449 try!(self.word_nbsp(w));
454 pub fn bopen(&mut self) -> IoResult<()> {
455 try!(word(&mut self.s, "{"));
456 self.end() // close the head-box
459 pub fn bclose_(&mut self, span: codemap::Span,
460 indented: uint) -> IoResult<()> {
461 self.bclose_maybe_open(span, indented, true)
463 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
464 indented: uint, close_box: bool) -> IoResult<()> {
465 try!(self.maybe_print_comment(span.hi));
466 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
467 try!(word(&mut self.s, "}"));
469 try!(self.end()); // close the outer-box
473 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
474 self.bclose_(span, indent_unit)
477 pub fn is_begin(&mut self) -> bool {
478 match self.s.last_token() { pp::Begin(_) => true, _ => false }
481 pub fn is_end(&mut self) -> bool {
482 match self.s.last_token() { pp::End => true, _ => false }
485 pub fn is_bol(&mut self) -> bool {
486 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
489 pub fn in_cbox(&self) -> bool {
490 match self.boxes.last() {
491 Some(&last_box) => last_box == pp::Consistent,
496 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
498 try!(hardbreak(&mut self.s))
502 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
503 if !self.is_bol() { try!(space(&mut self.s)); }
506 pub fn break_offset_if_not_bol(&mut self, n: uint,
507 off: int) -> IoResult<()> {
509 break_offset(&mut self.s, n, off)
511 if off != 0 && self.s.last_token().is_hardbreak_tok() {
512 // We do something pretty sketchy here: tuck the nonzero
513 // offset-adjustment we were going to deposit along with the
514 // break into the previous hardbreak.
515 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
521 // Synthesizes a comment that was not textually present in the original source
523 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
524 try!(word(&mut self.s, "/*"));
525 try!(space(&mut self.s));
526 try!(word(&mut self.s, text.as_slice()));
527 try!(space(&mut self.s));
528 word(&mut self.s, "*/")
531 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
532 op: |&mut State, &T| -> IoResult<()>)
534 try!(self.rbox(0u, b));
535 let mut first = true;
536 for elt in elts.iter() {
537 if first { first = false; } else { try!(self.word_space(",")); }
544 pub fn commasep_cmnt<T>(
548 op: |&mut State, &T| -> IoResult<()>,
549 get_span: |&T| -> codemap::Span) -> IoResult<()> {
550 try!(self.rbox(0u, b));
551 let len = elts.len();
553 for elt in elts.iter() {
554 try!(self.maybe_print_comment(get_span(elt).hi));
558 try!(word(&mut self.s, ","));
559 try!(self.maybe_print_trailing_comment(get_span(elt),
560 Some(get_span(&elts[i]).hi)));
561 try!(self.space_if_not_bol());
567 pub fn commasep_exprs(&mut self, b: Breaks,
568 exprs: &[Gc<ast::Expr>]) -> IoResult<()> {
569 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
572 pub fn print_mod(&mut self, _mod: &ast::Mod,
573 attrs: &[ast::Attribute]) -> IoResult<()> {
574 try!(self.print_inner_attributes(attrs));
575 for vitem in _mod.view_items.iter() {
576 try!(self.print_view_item(vitem));
578 for item in _mod.items.iter() {
579 try!(self.print_item(&**item));
584 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
585 attrs: &[ast::Attribute]) -> IoResult<()> {
586 try!(self.print_inner_attributes(attrs));
587 for vitem in nmod.view_items.iter() {
588 try!(self.print_view_item(vitem));
590 for item in nmod.items.iter() {
591 try!(self.print_foreign_item(&**item));
596 pub fn print_opt_lifetime(&mut self,
597 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
598 for l in lifetime.iter() {
599 try!(self.print_lifetime(l));
605 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
606 try!(self.maybe_print_comment(ty.span.lo));
609 ast::TyNil => try!(word(&mut self.s, "()")),
610 ast::TyBot => try!(word(&mut self.s, "!")),
611 ast::TyBox(ref ty) => {
612 try!(word(&mut self.s, "@"));
613 try!(self.print_type(&**ty));
615 ast::TyUniq(ref ty) => {
616 try!(word(&mut self.s, "~"));
617 try!(self.print_type(&**ty));
619 ast::TyVec(ref ty) => {
620 try!(word(&mut self.s, "["));
621 try!(self.print_type(&**ty));
622 try!(word(&mut self.s, "]"));
624 ast::TyPtr(ref mt) => {
625 try!(word(&mut self.s, "*"));
627 ast::MutMutable => try!(self.word_nbsp("mut")),
628 ast::MutImmutable => try!(self.word_nbsp("const")),
630 try!(self.print_type(&*mt.ty));
632 ast::TyRptr(ref lifetime, ref mt) => {
633 try!(word(&mut self.s, "&"));
634 try!(self.print_opt_lifetime(lifetime));
635 try!(self.print_mt(mt));
637 ast::TyTup(ref elts) => {
639 try!(self.commasep(Inconsistent, elts.as_slice(),
640 |s, ty| s.print_type_ref(ty)));
642 try!(word(&mut self.s, ","));
646 ast::TyParen(ref typ) => {
648 try!(self.print_type(&**typ));
651 ast::TyBareFn(f) => {
652 let generics = ast::Generics {
653 lifetimes: f.lifetimes.clone(),
654 ty_params: OwnedSlice::empty()
656 try!(self.print_ty_fn(Some(f.abi),
668 ast::TyClosure(f, ref region) => {
669 let generics = ast::Generics {
670 lifetimes: f.lifetimes.clone(),
671 ty_params: OwnedSlice::empty()
673 try!(self.print_ty_fn(None,
685 ast::TyProc(ref f) => {
686 let generics = ast::Generics {
687 lifetimes: f.lifetimes.clone(),
688 ty_params: OwnedSlice::empty()
690 try!(self.print_ty_fn(None,
702 ast::TyUnboxedFn(f) => {
703 try!(self.print_ty_fn(None,
715 ast::TyPath(ref path, ref bounds, _) => {
716 try!(self.print_bounded_path(path, bounds));
718 ast::TyFixedLengthVec(ref ty, ref v) => {
719 try!(word(&mut self.s, "["));
720 try!(self.print_type(&**ty));
721 try!(word(&mut self.s, ", .."));
722 try!(self.print_expr(&**v));
723 try!(word(&mut self.s, "]"));
725 ast::TyTypeof(ref e) => {
726 try!(word(&mut self.s, "typeof("));
727 try!(self.print_expr(&**e));
728 try!(word(&mut self.s, ")"));
731 try!(word(&mut self.s, "_"));
737 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
738 self.print_type(&**ty)
741 pub fn print_foreign_item(&mut self,
742 item: &ast::ForeignItem) -> IoResult<()> {
743 try!(self.hardbreak_if_not_bol());
744 try!(self.maybe_print_comment(item.span.lo));
745 try!(self.print_outer_attributes(item.attrs.as_slice()));
747 ast::ForeignItemFn(ref decl, ref generics) => {
748 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
750 try!(self.end()); // end head-ibox
751 try!(word(&mut self.s, ";"));
752 self.end() // end the outer fn box
754 ast::ForeignItemStatic(ref t, m) => {
755 try!(self.head(visibility_qualified(item.vis,
756 "static").as_slice()));
758 try!(self.word_space("mut"));
760 try!(self.print_ident(item.ident));
761 try!(self.word_space(":"));
762 try!(self.print_type(&**t));
763 try!(word(&mut self.s, ";"));
764 try!(self.end()); // end the head-ibox
765 self.end() // end the outer cbox
770 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
771 try!(self.hardbreak_if_not_bol());
772 try!(self.maybe_print_comment(item.span.lo));
773 try!(self.print_outer_attributes(item.attrs.as_slice()));
774 try!(self.ann.pre(self, NodeItem(item)));
776 ast::ItemStatic(ref ty, m, ref expr) => {
777 try!(self.head(visibility_qualified(item.vis,
778 "static").as_slice()));
779 if m == ast::MutMutable {
780 try!(self.word_space("mut"));
782 try!(self.print_ident(item.ident));
783 try!(self.word_space(":"));
784 try!(self.print_type(&**ty));
785 try!(space(&mut self.s));
786 try!(self.end()); // end the head-ibox
788 try!(self.word_space("="));
789 try!(self.print_expr(&**expr));
790 try!(word(&mut self.s, ";"));
791 try!(self.end()); // end the outer cbox
793 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
803 try!(word(&mut self.s, " "));
804 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
806 ast::ItemMod(ref _mod) => {
807 try!(self.head(visibility_qualified(item.vis,
809 try!(self.print_ident(item.ident));
812 try!(self.print_mod(_mod, item.attrs.as_slice()));
813 try!(self.bclose(item.span));
815 ast::ItemForeignMod(ref nmod) => {
816 try!(self.head("extern"));
817 try!(self.word_nbsp(nmod.abi.to_string().as_slice()));
819 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
820 try!(self.bclose(item.span));
822 ast::ItemTy(ref ty, ref params) => {
823 try!(self.ibox(indent_unit));
825 try!(self.word_nbsp(visibility_qualified(item.vis,
826 "type").as_slice()));
827 try!(self.print_ident(item.ident));
828 try!(self.print_generics(params));
829 try!(self.end()); // end the inner ibox
831 try!(space(&mut self.s));
832 try!(self.word_space("="));
833 try!(self.print_type(&**ty));
834 try!(word(&mut self.s, ";"));
835 try!(self.end()); // end the outer ibox
837 ast::ItemEnum(ref enum_definition, ref params) => {
838 try!(self.print_enum_def(
846 ast::ItemStruct(ref struct_def, ref generics) => {
847 if struct_def.is_virtual {
848 try!(self.word_space("virtual"));
850 try!(self.head(visibility_qualified(item.vis,
851 "struct").as_slice()));
852 try!(self.print_struct(&**struct_def, generics, item.ident,
856 ast::ItemImpl(ref generics, ref opt_trait, ref ty, ref methods) => {
857 try!(self.head(visibility_qualified(item.vis,
858 "impl").as_slice()));
859 if generics.is_parameterized() {
860 try!(self.print_generics(generics));
861 try!(space(&mut self.s));
866 try!(self.print_trait_ref(t));
867 try!(space(&mut self.s));
868 try!(self.word_space("for"));
873 try!(self.print_type(&**ty));
875 try!(space(&mut self.s));
877 try!(self.print_inner_attributes(item.attrs.as_slice()));
878 for meth in methods.iter() {
879 try!(self.print_method(&**meth));
881 try!(self.bclose(item.span));
883 ast::ItemTrait(ref generics, ref unbound, ref traits, ref methods) => {
884 try!(self.head(visibility_qualified(item.vis,
885 "trait").as_slice()));
886 try!(self.print_ident(item.ident));
887 try!(self.print_generics(generics));
889 &Some(TraitTyParamBound(ref tref)) => {
890 try!(space(&mut self.s));
891 try!(self.word_space("for"));
892 try!(self.print_trait_ref(tref));
893 try!(word(&mut self.s, "?"));
897 if traits.len() != 0u {
898 try!(word(&mut self.s, ":"));
899 for (i, trait_) in traits.iter().enumerate() {
902 try!(self.word_space("+"));
904 try!(self.print_path(&trait_.path, false));
907 try!(word(&mut self.s, " "));
909 for meth in methods.iter() {
910 try!(self.print_trait_method(meth));
912 try!(self.bclose(item.span));
914 // I think it's reasonable to hide the context here:
915 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
917 try!(self.print_visibility(item.vis));
918 try!(self.print_path(pth, false));
919 try!(word(&mut self.s, "! "));
920 try!(self.print_ident(item.ident));
921 try!(self.cbox(indent_unit));
923 try!(self.print_tts(tts.as_slice()));
928 self.ann.post(self, NodeItem(item))
931 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
932 self.print_path(&t.path, false)
935 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
936 generics: &ast::Generics, ident: ast::Ident,
938 visibility: ast::Visibility) -> IoResult<()> {
939 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
940 try!(self.print_ident(ident));
941 try!(self.print_generics(generics));
942 try!(space(&mut self.s));
943 self.print_variants(enum_definition.variants.as_slice(), span)
946 pub fn print_variants(&mut self,
947 variants: &[P<ast::Variant>],
948 span: codemap::Span) -> IoResult<()> {
950 for v in variants.iter() {
951 try!(self.space_if_not_bol());
952 try!(self.maybe_print_comment(v.span.lo));
953 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
954 try!(self.ibox(indent_unit));
955 try!(self.print_variant(&**v));
956 try!(word(&mut self.s, ","));
958 try!(self.maybe_print_trailing_comment(v.span, None));
963 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
965 ast::Public => self.word_nbsp("pub"),
966 ast::Inherited => Ok(())
970 pub fn print_struct(&mut self,
971 struct_def: &ast::StructDef,
972 generics: &ast::Generics,
974 span: codemap::Span) -> IoResult<()> {
975 try!(self.print_ident(ident));
976 try!(self.print_generics(generics));
977 match struct_def.super_struct {
979 try!(self.word_space(":"));
980 try!(self.print_type(&**t));
984 if ast_util::struct_def_is_tuple_like(struct_def) {
985 if !struct_def.fields.is_empty() {
988 Inconsistent, struct_def.fields.as_slice(),
990 match field.node.kind {
991 ast::NamedField(..) => fail!("unexpected named field"),
992 ast::UnnamedField(vis) => {
993 try!(s.print_visibility(vis));
994 try!(s.maybe_print_comment(field.span.lo));
995 s.print_type(&*field.node.ty)
1000 try!(self.pclose());
1002 try!(word(&mut self.s, ";"));
1004 self.end() // close the outer-box
1008 try!(self.hardbreak_if_not_bol());
1010 for field in struct_def.fields.iter() {
1011 match field.node.kind {
1012 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
1013 ast::NamedField(ident, visibility) => {
1014 try!(self.hardbreak_if_not_bol());
1015 try!(self.maybe_print_comment(field.span.lo));
1016 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
1017 try!(self.print_visibility(visibility));
1018 try!(self.print_ident(ident));
1019 try!(self.word_nbsp(":"));
1020 try!(self.print_type(&*field.node.ty));
1021 try!(word(&mut self.s, ","));
1030 /// This doesn't deserve to be called "pretty" printing, but it should be
1031 /// meaning-preserving. A quick hack that might help would be to look at the
1032 /// spans embedded in the TTs to decide where to put spaces and newlines.
1033 /// But it'd be better to parse these according to the grammar of the
1034 /// appropriate macro, transcribe back into the grammar we just parsed from,
1035 /// and then pretty-print the resulting AST nodes (so, e.g., we print
1036 /// expression arguments as expressions). It can be done! I think.
1037 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1039 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
1040 ast::TTTok(_, ref tk) => {
1041 try!(word(&mut self.s, parse::token::to_string(tk).as_slice()));
1043 parse::token::DOC_COMMENT(..) => {
1044 hardbreak(&mut self.s)
1049 ast::TTSeq(_, ref tts, ref sep, zerok) => {
1050 try!(word(&mut self.s, "$("));
1051 for tt_elt in (*tts).iter() {
1052 try!(self.print_tt(tt_elt));
1054 try!(word(&mut self.s, ")"));
1057 try!(word(&mut self.s,
1058 parse::token::to_string(tk).as_slice()));
1062 word(&mut self.s, if zerok { "*" } else { "+" })
1064 ast::TTNonterminal(_, name) => {
1065 try!(word(&mut self.s, "$"));
1066 self.print_ident(name)
1071 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1073 for (i, tt) in tts.iter().enumerate() {
1075 try!(space(&mut self.s));
1077 try!(self.print_tt(tt));
1082 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1083 try!(self.print_visibility(v.node.vis));
1085 ast::TupleVariantKind(ref args) => {
1086 try!(self.print_ident(v.node.name));
1087 if !args.is_empty() {
1089 try!(self.commasep(Consistent,
1091 |s, arg| s.print_type(&*arg.ty)));
1092 try!(self.pclose());
1095 ast::StructVariantKind(ref struct_def) => {
1096 try!(self.head(""));
1097 let generics = ast_util::empty_generics();
1098 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1101 match v.node.disr_expr {
1103 try!(space(&mut self.s));
1104 try!(self.word_space("="));
1105 self.print_expr(&**d)
1111 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1112 try!(self.hardbreak_if_not_bol());
1113 try!(self.maybe_print_comment(m.span.lo));
1114 try!(self.print_outer_attributes(m.attrs.as_slice()));
1115 try!(self.print_ty_fn(None,
1124 Some(m.explicit_self.node),
1126 word(&mut self.s, ";")
1129 pub fn print_trait_method(&mut self,
1130 m: &ast::TraitMethod) -> IoResult<()> {
1132 Required(ref ty_m) => self.print_ty_method(ty_m),
1133 Provided(ref m) => self.print_method(&**m)
1137 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1138 try!(self.hardbreak_if_not_bol());
1139 try!(self.maybe_print_comment(meth.span.lo));
1140 try!(self.print_outer_attributes(meth.attrs.as_slice()));
1141 try!(self.print_fn(&*meth.decl, Some(meth.fn_style), abi::Rust,
1142 meth.ident, &meth.generics, Some(meth.explicit_self.node),
1144 try!(word(&mut self.s, " "));
1145 self.print_block_with_attrs(&*meth.body, meth.attrs.as_slice())
1148 pub fn print_outer_attributes(&mut self,
1149 attrs: &[ast::Attribute]) -> IoResult<()> {
1151 for attr in attrs.iter() {
1152 match attr.node.style {
1154 try!(self.print_attribute(attr));
1157 _ => {/* fallthrough */ }
1161 try!(self.hardbreak_if_not_bol());
1166 pub fn print_inner_attributes(&mut self,
1167 attrs: &[ast::Attribute]) -> IoResult<()> {
1169 for attr in attrs.iter() {
1170 match attr.node.style {
1172 try!(self.print_attribute(attr));
1175 _ => {/* fallthrough */ }
1179 try!(self.hardbreak_if_not_bol());
1184 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1185 try!(self.hardbreak_if_not_bol());
1186 try!(self.maybe_print_comment(attr.span.lo));
1187 if attr.node.is_sugared_doc {
1188 word(&mut self.s, attr.value_str().unwrap().get())
1190 match attr.node.style {
1191 ast::AttrInner => try!(word(&mut self.s, "#![")),
1192 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1194 try!(self.print_meta_item(&*attr.meta()));
1195 word(&mut self.s, "]")
1200 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1201 try!(self.maybe_print_comment(st.span.lo));
1203 ast::StmtDecl(ref decl, _) => {
1204 try!(self.print_decl(&**decl));
1206 ast::StmtExpr(ref expr, _) => {
1207 try!(self.space_if_not_bol());
1208 try!(self.print_expr(&**expr));
1210 ast::StmtSemi(ref expr, _) => {
1211 try!(self.space_if_not_bol());
1212 try!(self.print_expr(&**expr));
1213 try!(word(&mut self.s, ";"));
1215 ast::StmtMac(ref mac, semi) => {
1216 try!(self.space_if_not_bol());
1217 try!(self.print_mac(mac));
1219 try!(word(&mut self.s, ";"));
1223 if parse::classify::stmt_ends_with_semi(st) {
1224 try!(word(&mut self.s, ";"));
1226 self.maybe_print_trailing_comment(st.span, None)
1229 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1230 self.print_block_with_attrs(blk, &[])
1233 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1234 self.print_block_unclosed_indent(blk, indent_unit)
1237 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1238 indented: uint) -> IoResult<()> {
1239 self.print_block_maybe_unclosed(blk, indented, &[], false)
1242 pub fn print_block_with_attrs(&mut self,
1244 attrs: &[ast::Attribute]) -> IoResult<()> {
1245 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1248 pub fn print_block_maybe_unclosed(&mut self,
1251 attrs: &[ast::Attribute],
1252 close_box: bool) -> IoResult<()> {
1254 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1255 ast::DefaultBlock => ()
1257 try!(self.maybe_print_comment(blk.span.lo));
1258 try!(self.ann.pre(self, NodeBlock(blk)));
1261 try!(self.print_inner_attributes(attrs));
1263 for vi in blk.view_items.iter() {
1264 try!(self.print_view_item(vi));
1266 for st in blk.stmts.iter() {
1267 try!(self.print_stmt(&**st));
1271 try!(self.space_if_not_bol());
1272 try!(self.print_expr(&**expr));
1273 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1277 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1278 self.ann.post(self, NodeBlock(blk))
1281 fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1285 // "another else-if"
1286 ast::ExprIf(ref i, ref t, e) => {
1287 try!(self.cbox(indent_unit - 1u));
1288 try!(self.ibox(0u));
1289 try!(word(&mut self.s, " else if "));
1290 try!(self.print_expr(&**i));
1291 try!(space(&mut self.s));
1292 try!(self.print_block(&**t));
1296 ast::ExprBlock(ref b) => {
1297 try!(self.cbox(indent_unit - 1u));
1298 try!(self.ibox(0u));
1299 try!(word(&mut self.s, " else "));
1300 self.print_block(&**b)
1302 // BLEAH, constraints would be great here
1304 fail!("print_if saw if with weird alternative");
1312 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1313 elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1314 try!(self.head("if"));
1315 if chk { try!(self.word_nbsp("check")); }
1316 try!(self.print_expr(test));
1317 try!(space(&mut self.s));
1318 try!(self.print_block(blk));
1319 self.print_else(elseopt)
1322 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1324 // I think it's reasonable to hide the ctxt here:
1325 ast::MacInvocTT(ref pth, ref tts, _) => {
1326 try!(self.print_path(pth, false));
1327 try!(word(&mut self.s, "!"));
1329 try!(self.print_tts(tts.as_slice()));
1335 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1337 ast::ExprVstoreUniq => word(&mut self.s, "box "),
1338 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1339 ast::ExprVstoreMutSlice => {
1340 try!(word(&mut self.s, "&"));
1341 word(&mut self.s, "mut")
1346 fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1348 try!(self.commasep_exprs(Inconsistent, args));
1352 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1353 let needs_par = needs_parentheses(expr);
1357 try!(self.print_expr(expr));
1359 try!(self.pclose());
1364 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1365 try!(self.maybe_print_comment(expr.span.lo));
1366 try!(self.ibox(indent_unit));
1367 try!(self.ann.pre(self, NodeExpr(expr)));
1369 ast::ExprVstore(ref e, v) => {
1370 try!(self.print_expr_vstore(v));
1371 try!(self.print_expr(&**e));
1373 ast::ExprBox(ref p, ref e) => {
1374 try!(word(&mut self.s, "box"));
1375 try!(word(&mut self.s, "("));
1376 try!(self.print_expr(&**p));
1377 try!(self.word_space(")"));
1378 try!(self.print_expr(&**e));
1380 ast::ExprVec(ref exprs) => {
1381 try!(self.ibox(indent_unit));
1382 try!(word(&mut self.s, "["));
1383 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1384 try!(word(&mut self.s, "]"));
1388 ast::ExprRepeat(ref element, ref count) => {
1389 try!(self.ibox(indent_unit));
1390 try!(word(&mut self.s, "["));
1391 try!(self.print_expr(&**element));
1392 try!(word(&mut self.s, ","));
1393 try!(word(&mut self.s, ".."));
1394 try!(self.print_expr(&**count));
1395 try!(word(&mut self.s, "]"));
1399 ast::ExprStruct(ref path, ref fields, wth) => {
1400 try!(self.print_path(path, true));
1401 try!(word(&mut self.s, "{"));
1402 try!(self.commasep_cmnt(
1406 try!(s.ibox(indent_unit));
1407 try!(s.print_ident(field.ident.node));
1408 try!(s.word_space(":"));
1409 try!(s.print_expr(&*field.expr));
1415 try!(self.ibox(indent_unit));
1416 if !fields.is_empty() {
1417 try!(word(&mut self.s, ","));
1418 try!(space(&mut self.s));
1420 try!(word(&mut self.s, ".."));
1421 try!(self.print_expr(&**expr));
1424 _ => try!(word(&mut self.s, ","))
1426 try!(word(&mut self.s, "}"));
1428 ast::ExprTup(ref exprs) => {
1430 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1431 if exprs.len() == 1 {
1432 try!(word(&mut self.s, ","));
1434 try!(self.pclose());
1436 ast::ExprCall(ref func, ref args) => {
1437 try!(self.print_expr_maybe_paren(&**func));
1438 try!(self.print_call_post(args.as_slice()));
1440 ast::ExprMethodCall(ident, ref tys, ref args) => {
1441 let base_args = args.slice_from(1);
1442 try!(self.print_expr(&**args.get(0)));
1443 try!(word(&mut self.s, "."));
1444 try!(self.print_ident(ident.node));
1446 try!(word(&mut self.s, "::<"));
1447 try!(self.commasep(Inconsistent, tys.as_slice(),
1448 |s, ty| s.print_type_ref(ty)));
1449 try!(word(&mut self.s, ">"));
1451 try!(self.print_call_post(base_args));
1453 ast::ExprBinary(op, ref lhs, ref rhs) => {
1454 try!(self.print_expr(&**lhs));
1455 try!(space(&mut self.s));
1456 try!(self.word_space(ast_util::binop_to_string(op)));
1457 try!(self.print_expr(&**rhs));
1459 ast::ExprUnary(op, ref expr) => {
1460 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1461 try!(self.print_expr_maybe_paren(&**expr));
1463 ast::ExprAddrOf(m, ref expr) => {
1464 try!(word(&mut self.s, "&"));
1465 try!(self.print_mutability(m));
1466 try!(self.print_expr_maybe_paren(&**expr));
1468 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1469 ast::ExprCast(ref expr, ref ty) => {
1470 try!(self.print_expr(&**expr));
1471 try!(space(&mut self.s));
1472 try!(self.word_space("as"));
1473 try!(self.print_type(&**ty));
1475 ast::ExprIf(ref test, ref blk, elseopt) => {
1476 try!(self.print_if(&**test, &**blk, elseopt, false));
1478 ast::ExprWhile(ref test, ref blk) => {
1479 try!(self.head("while"));
1480 try!(self.print_expr(&**test));
1481 try!(space(&mut self.s));
1482 try!(self.print_block(&**blk));
1484 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1485 for ident in opt_ident.iter() {
1486 try!(self.print_ident(*ident));
1487 try!(self.word_space(":"));
1489 try!(self.head("for"));
1490 try!(self.print_pat(&**pat));
1491 try!(space(&mut self.s));
1492 try!(self.word_space("in"));
1493 try!(self.print_expr(&**iter));
1494 try!(space(&mut self.s));
1495 try!(self.print_block(&**blk));
1497 ast::ExprLoop(ref blk, opt_ident) => {
1498 for ident in opt_ident.iter() {
1499 try!(self.print_ident(*ident));
1500 try!(self.word_space(":"));
1502 try!(self.head("loop"));
1503 try!(space(&mut self.s));
1504 try!(self.print_block(&**blk));
1506 ast::ExprMatch(ref expr, ref arms) => {
1507 try!(self.cbox(indent_unit));
1509 try!(self.word_nbsp("match"));
1510 try!(self.print_expr(&**expr));
1511 try!(space(&mut self.s));
1513 let len = arms.len();
1514 for (i, arm) in arms.iter().enumerate() {
1515 // I have no idea why this check is necessary, but here it
1517 if arm.attrs.is_empty() {
1518 try!(space(&mut self.s));
1520 try!(self.cbox(indent_unit));
1521 try!(self.ibox(0u));
1522 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1523 let mut first = true;
1524 for p in arm.pats.iter() {
1528 try!(space(&mut self.s));
1529 try!(self.word_space("|"));
1531 try!(self.print_pat(&**p));
1533 try!(space(&mut self.s));
1536 try!(self.word_space("if"));
1537 try!(self.print_expr(&**e));
1538 try!(space(&mut self.s));
1542 try!(self.word_space("=>"));
1544 match arm.body.node {
1545 ast::ExprBlock(ref blk) => {
1546 // the block will close the pattern's ibox
1547 try!(self.print_block_unclosed_indent(&**blk,
1551 try!(self.end()); // close the ibox for the pattern
1552 try!(self.print_expr(&*arm.body));
1555 if !expr_is_simple_block(expr.clone())
1557 try!(word(&mut self.s, ","));
1559 try!(self.end()); // close enclosing cbox
1561 try!(self.bclose_(expr.span, indent_unit));
1563 ast::ExprFnBlock(ref decl, ref body) => {
1564 // in do/for blocks we don't want to show an empty
1565 // argument list, but at this point we don't know which
1568 // if !decl.inputs.is_empty() {
1569 try!(self.print_fn_block_args(&**decl));
1570 try!(space(&mut self.s));
1573 if !body.stmts.is_empty() || !body.expr.is_some() {
1574 try!(self.print_block_unclosed(&**body));
1576 // we extract the block, so as not to create another set of boxes
1577 match body.expr.unwrap().node {
1578 ast::ExprBlock(ref blk) => {
1579 try!(self.print_block_unclosed(&**blk));
1582 // this is a bare expression
1583 try!(self.print_expr(&*body.expr.unwrap()));
1584 try!(self.end()); // need to close a box
1588 // a box will be closed by print_expr, but we didn't want an overall
1589 // wrapper so we closed the corresponding opening. so create an
1590 // empty box to satisfy the close.
1593 ast::ExprProc(ref decl, ref body) => {
1594 // in do/for blocks we don't want to show an empty
1595 // argument list, but at this point we don't know which
1598 // if !decl.inputs.is_empty() {
1599 try!(self.print_proc_args(&**decl));
1600 try!(space(&mut self.s));
1602 assert!(body.stmts.is_empty());
1603 assert!(body.expr.is_some());
1604 // we extract the block, so as not to create another set of boxes
1605 match body.expr.unwrap().node {
1606 ast::ExprBlock(ref blk) => {
1607 try!(self.print_block_unclosed(&**blk));
1610 // this is a bare expression
1611 try!(self.print_expr(&*body.expr.unwrap()));
1612 try!(self.end()); // need to close a box
1615 // a box will be closed by print_expr, but we didn't want an overall
1616 // wrapper so we closed the corresponding opening. so create an
1617 // empty box to satisfy the close.
1620 ast::ExprBlock(ref blk) => {
1621 // containing cbox, will be closed by print-block at }
1622 try!(self.cbox(indent_unit));
1623 // head-box, will be closed by print-block after {
1624 try!(self.ibox(0u));
1625 try!(self.print_block(&**blk));
1627 ast::ExprAssign(ref lhs, ref rhs) => {
1628 try!(self.print_expr(&**lhs));
1629 try!(space(&mut self.s));
1630 try!(self.word_space("="));
1631 try!(self.print_expr(&**rhs));
1633 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1634 try!(self.print_expr(&**lhs));
1635 try!(space(&mut self.s));
1636 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1637 try!(self.word_space("="));
1638 try!(self.print_expr(&**rhs));
1640 ast::ExprField(ref expr, id, ref tys) => {
1641 try!(self.print_expr(&**expr));
1642 try!(word(&mut self.s, "."));
1643 try!(self.print_ident(id.node));
1645 try!(word(&mut self.s, "::<"));
1647 Inconsistent, tys.as_slice(),
1648 |s, ty| s.print_type_ref(ty)));
1649 try!(word(&mut self.s, ">"));
1652 ast::ExprIndex(ref expr, ref index) => {
1653 try!(self.print_expr(&**expr));
1654 try!(word(&mut self.s, "["));
1655 try!(self.print_expr(&**index));
1656 try!(word(&mut self.s, "]"));
1658 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1659 ast::ExprBreak(opt_ident) => {
1660 try!(word(&mut self.s, "break"));
1661 try!(space(&mut self.s));
1662 for ident in opt_ident.iter() {
1663 try!(self.print_ident(*ident));
1664 try!(space(&mut self.s));
1667 ast::ExprAgain(opt_ident) => {
1668 try!(word(&mut self.s, "continue"));
1669 try!(space(&mut self.s));
1670 for ident in opt_ident.iter() {
1671 try!(self.print_ident(*ident));
1672 try!(space(&mut self.s))
1675 ast::ExprRet(ref result) => {
1676 try!(word(&mut self.s, "return"));
1679 try!(word(&mut self.s, " "));
1680 try!(self.print_expr(&**expr));
1685 ast::ExprInlineAsm(ref a) => {
1687 try!(word(&mut self.s, "__volatile__ asm!"));
1689 try!(word(&mut self.s, "asm!"));
1692 try!(self.print_string(a.asm.get(), a.asm_str_style));
1693 try!(self.word_space(":"));
1695 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1696 |s, &(ref co, ref o)| {
1697 try!(s.print_string(co.get(), ast::CookedStr));
1699 try!(s.print_expr(&**o));
1703 try!(space(&mut self.s));
1704 try!(self.word_space(":"));
1706 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1707 |s, &(ref co, ref o)| {
1708 try!(s.print_string(co.get(), ast::CookedStr));
1710 try!(s.print_expr(&**o));
1714 try!(space(&mut self.s));
1715 try!(self.word_space(":"));
1717 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1718 try!(self.pclose());
1720 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1721 ast::ExprParen(ref e) => {
1723 try!(self.print_expr(&**e));
1724 try!(self.pclose());
1727 try!(self.ann.post(self, NodeExpr(expr)));
1731 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1732 try!(self.print_pat(&*loc.pat));
1734 ast::TyInfer => Ok(()),
1736 try!(self.word_space(":"));
1737 self.print_type(&*loc.ty)
1742 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1743 try!(self.maybe_print_comment(decl.span.lo));
1745 ast::DeclLocal(ref loc) => {
1746 try!(self.space_if_not_bol());
1747 try!(self.ibox(indent_unit));
1748 try!(self.word_nbsp("let"));
1750 try!(self.ibox(indent_unit));
1751 try!(self.print_local_decl(&**loc));
1756 try!(self.word_space("="));
1757 try!(self.print_expr(&**init));
1763 ast::DeclItem(ref item) => self.print_item(&**item)
1767 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1768 word(&mut self.s, token::get_ident(ident).get())
1771 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1772 word(&mut self.s, token::get_name(name).get())
1775 pub fn print_for_decl(&mut self, loc: &ast::Local,
1776 coll: &ast::Expr) -> IoResult<()> {
1777 try!(self.print_local_decl(loc));
1778 try!(space(&mut self.s));
1779 try!(self.word_space("in"));
1780 self.print_expr(coll)
1783 fn print_path_(&mut self,
1785 colons_before_params: bool,
1786 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1788 try!(self.maybe_print_comment(path.span.lo));
1790 try!(word(&mut self.s, "::"));
1793 let mut first = true;
1794 for segment in path.segments.iter() {
1798 try!(word(&mut self.s, "::"))
1801 try!(self.print_ident(segment.identifier));
1803 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1804 if colons_before_params {
1805 try!(word(&mut self.s, "::"))
1807 try!(word(&mut self.s, "<"));
1809 let mut comma = false;
1810 for lifetime in segment.lifetimes.iter() {
1812 try!(self.word_space(","))
1814 try!(self.print_lifetime(lifetime));
1818 if !segment.types.is_empty() {
1820 try!(self.word_space(","))
1824 segment.types.as_slice(),
1825 |s, ty| s.print_type_ref(ty)));
1828 try!(word(&mut self.s, ">"))
1834 Some(ref bounds) => self.print_bounds(&None, bounds, true, true),
1838 fn print_path(&mut self, path: &ast::Path,
1839 colons_before_params: bool) -> IoResult<()> {
1840 self.print_path_(path, colons_before_params, &None)
1843 fn print_bounded_path(&mut self, path: &ast::Path,
1844 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1846 self.print_path_(path, false, bounds)
1849 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1850 try!(self.maybe_print_comment(pat.span.lo));
1851 try!(self.ann.pre(self, NodePat(pat)));
1852 /* Pat isn't normalized, but the beauty of it
1853 is that it doesn't matter */
1855 ast::PatWild => try!(word(&mut self.s, "_")),
1856 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1857 ast::PatIdent(binding_mode, ref path1, sub) => {
1858 match binding_mode {
1859 ast::BindByRef(mutbl) => {
1860 try!(self.word_nbsp("ref"));
1861 try!(self.print_mutability(mutbl));
1863 ast::BindByValue(ast::MutImmutable) => {}
1864 ast::BindByValue(ast::MutMutable) => {
1865 try!(self.word_nbsp("mut"));
1868 try!(self.print_ident(path1.node));
1871 try!(word(&mut self.s, "@"));
1872 try!(self.print_pat(&**p));
1877 ast::PatEnum(ref path, ref args_) => {
1878 try!(self.print_path(path, true));
1880 None => try!(word(&mut self.s, "(..)")),
1882 if !args.is_empty() {
1884 try!(self.commasep(Inconsistent, args.as_slice(),
1885 |s, p| s.print_pat(&**p)));
1886 try!(self.pclose());
1891 ast::PatStruct(ref path, ref fields, etc) => {
1892 try!(self.print_path(path, true));
1894 try!(self.word_space("{"));
1895 try!(self.commasep_cmnt(
1896 Consistent, fields.as_slice(),
1898 try!(s.cbox(indent_unit));
1899 try!(s.print_ident(f.ident));
1900 try!(s.word_nbsp(":"));
1901 try!(s.print_pat(&*f.pat));
1906 if fields.len() != 0u { try!(self.word_space(",")); }
1907 try!(word(&mut self.s, ".."));
1909 try!(space(&mut self.s));
1910 try!(word(&mut self.s, "}"));
1912 ast::PatTup(ref elts) => {
1914 try!(self.commasep(Inconsistent,
1916 |s, p| s.print_pat(&**p)));
1917 if elts.len() == 1 {
1918 try!(word(&mut self.s, ","));
1920 try!(self.pclose());
1922 ast::PatBox(ref inner) => {
1923 try!(word(&mut self.s, "box "));
1924 try!(self.print_pat(&**inner));
1926 ast::PatRegion(ref inner) => {
1927 try!(word(&mut self.s, "&"));
1928 try!(self.print_pat(&**inner));
1930 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1931 ast::PatRange(ref begin, ref end) => {
1932 try!(self.print_expr(&**begin));
1933 try!(space(&mut self.s));
1934 try!(word(&mut self.s, ".."));
1935 try!(self.print_expr(&**end));
1937 ast::PatVec(ref before, slice, ref after) => {
1938 try!(word(&mut self.s, "["));
1939 try!(self.commasep(Inconsistent,
1941 |s, p| s.print_pat(&**p)));
1942 for p in slice.iter() {
1943 if !before.is_empty() { try!(self.word_space(",")); }
1945 ast::Pat { node: ast::PatWildMulti, .. } => {
1946 // this case is handled by print_pat
1948 _ => try!(word(&mut self.s, "..")),
1950 try!(self.print_pat(&**p));
1951 if !after.is_empty() { try!(self.word_space(",")); }
1953 try!(self.commasep(Inconsistent,
1955 |s, p| s.print_pat(&**p)));
1956 try!(word(&mut self.s, "]"));
1958 ast::PatMac(ref m) => try!(self.print_mac(m)),
1960 self.ann.post(self, NodePat(pat))
1963 // Returns whether it printed anything
1964 fn print_explicit_self(&mut self,
1965 explicit_self: ast::ExplicitSelf_,
1966 mutbl: ast::Mutability) -> IoResult<bool> {
1967 try!(self.print_mutability(mutbl));
1968 match explicit_self {
1969 ast::SelfStatic => { return Ok(false); }
1970 ast::SelfValue(_) => {
1971 try!(word(&mut self.s, "self"));
1973 ast::SelfUniq(_) => {
1974 try!(word(&mut self.s, "~self"));
1976 ast::SelfRegion(ref lt, m, _) => {
1977 try!(word(&mut self.s, "&"));
1978 try!(self.print_opt_lifetime(lt));
1979 try!(self.print_mutability(m));
1980 try!(word(&mut self.s, "self"));
1986 pub fn print_fn(&mut self,
1988 fn_style: Option<ast::FnStyle>,
1991 generics: &ast::Generics,
1992 opt_explicit_self: Option<ast::ExplicitSelf_>,
1993 vis: ast::Visibility) -> IoResult<()> {
1994 try!(self.head(""));
1995 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1997 try!(self.print_ident(name));
1998 try!(self.print_generics(generics));
1999 self.print_fn_args_and_ret(decl, opt_explicit_self)
2002 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2003 opt_explicit_self: Option<ast::ExplicitSelf_>)
2005 // It is unfortunate to duplicate the commasep logic, but we want the
2006 // self type and the args all in the same box.
2007 try!(self.rbox(0u, Inconsistent));
2008 let mut first = true;
2009 for &explicit_self in opt_explicit_self.iter() {
2010 let m = match explicit_self {
2011 ast::SelfStatic => ast::MutImmutable,
2012 _ => match decl.inputs.get(0).pat.node {
2013 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2014 _ => ast::MutImmutable
2017 first = !try!(self.print_explicit_self(explicit_self, m));
2020 // HACK(eddyb) ignore the separately printed self argument.
2021 let args = if first {
2022 decl.inputs.as_slice()
2024 decl.inputs.slice_from(1)
2027 for arg in args.iter() {
2028 if first { first = false; } else { try!(self.word_space(",")); }
2029 try!(self.print_arg(arg));
2035 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2036 opt_explicit_self: Option<ast::ExplicitSelf_>)
2039 try!(self.print_fn_args(decl, opt_explicit_self));
2041 try!(word(&mut self.s, ", ..."));
2043 try!(self.pclose());
2045 try!(self.maybe_print_comment(decl.output.span.lo));
2046 match decl.output.node {
2047 ast::TyNil => Ok(()),
2049 try!(self.space_if_not_bol());
2050 try!(self.word_space("->"));
2051 self.print_type(&*decl.output)
2056 pub fn print_fn_block_args(&mut self,
2057 decl: &ast::FnDecl) -> IoResult<()> {
2058 try!(word(&mut self.s, "|"));
2059 try!(self.print_fn_args(decl, None));
2060 try!(word(&mut self.s, "|"));
2062 match decl.output.node {
2065 try!(self.space_if_not_bol());
2066 try!(self.word_space("->"));
2067 try!(self.print_type(&*decl.output));
2071 self.maybe_print_comment(decl.output.span.lo)
2074 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2075 try!(word(&mut self.s, "proc"));
2076 try!(word(&mut self.s, "("));
2077 try!(self.print_fn_args(decl, None));
2078 try!(word(&mut self.s, ")"));
2080 match decl.output.node {
2083 try!(self.space_if_not_bol());
2084 try!(self.word_space("->"));
2085 try!(self.print_type(&*decl.output));
2089 self.maybe_print_comment(decl.output.span.lo)
2092 pub fn print_bounds(&mut self,
2093 region: &Option<ast::Lifetime>,
2094 bounds: &OwnedSlice<ast::TyParamBound>,
2095 print_colon_anyway: bool,
2096 print_plus_before_bounds: bool)
2098 let separator = if print_plus_before_bounds {
2103 if !bounds.is_empty() || region.is_some() {
2104 try!(word(&mut self.s, separator));
2105 let mut first = true;
2108 let token = token::get_name(lt.name);
2109 if token.get() != "'static" {
2112 try!(self.print_lifetime(lt));
2117 for bound in bounds.iter() {
2122 try!(self.word_space("+"));
2126 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
2127 StaticRegionTyParamBound => word(&mut self.s, "'static"),
2128 UnboxedFnTyParamBound(ref unboxed_function_type) => {
2129 self.print_ty_fn(None,
2134 &*unboxed_function_type.decl,
2141 OtherRegionTyParamBound(_) => Ok(())
2145 } else if print_colon_anyway {
2146 word(&mut self.s, separator)
2152 pub fn print_lifetime(&mut self,
2153 lifetime: &ast::Lifetime) -> IoResult<()> {
2154 self.print_name(lifetime.name)
2157 pub fn print_generics(&mut self,
2158 generics: &ast::Generics) -> IoResult<()> {
2159 let total = generics.lifetimes.len() + generics.ty_params.len();
2161 try!(word(&mut self.s, "<"));
2163 let mut ints = Vec::new();
2164 for i in range(0u, total) {
2169 Inconsistent, ints.as_slice(),
2171 if idx < generics.lifetimes.len() {
2172 let lifetime = generics.lifetimes.get(idx);
2173 s.print_lifetime(lifetime)
2175 let idx = idx - generics.lifetimes.len();
2176 let param = generics.ty_params.get(idx);
2177 match param.unbound {
2178 Some(TraitTyParamBound(ref tref)) => {
2179 try!(s.print_trait_ref(tref));
2180 try!(s.word_space("?"));
2184 try!(s.print_ident(param.ident));
2185 try!(s.print_bounds(&None,
2189 match param.default {
2190 Some(ref default) => {
2191 try!(space(&mut s.s));
2192 try!(s.word_space("="));
2193 s.print_type(&**default)
2199 word(&mut self.s, ">")
2205 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2206 try!(self.ibox(indent_unit));
2208 ast::MetaWord(ref name) => {
2209 try!(word(&mut self.s, name.get()));
2211 ast::MetaNameValue(ref name, ref value) => {
2212 try!(self.word_space(name.get()));
2213 try!(self.word_space("="));
2214 try!(self.print_literal(value));
2216 ast::MetaList(ref name, ref items) => {
2217 try!(word(&mut self.s, name.get()));
2219 try!(self.commasep(Consistent,
2221 |s, i| s.print_meta_item(&**i)));
2222 try!(self.pclose());
2228 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2230 ast::ViewPathSimple(ident, ref path, _) => {
2231 // FIXME(#6993) can't compare identifiers directly here
2232 if path.segments.last().unwrap().identifier.name != ident.name {
2233 try!(self.print_ident(ident));
2234 try!(space(&mut self.s));
2235 try!(self.word_space("="));
2237 self.print_path(path, false)
2240 ast::ViewPathGlob(ref path, _) => {
2241 try!(self.print_path(path, false));
2242 word(&mut self.s, "::*")
2245 ast::ViewPathList(ref path, ref idents, _) => {
2246 if path.segments.is_empty() {
2247 try!(word(&mut self.s, "{"));
2249 try!(self.print_path(path, false));
2250 try!(word(&mut self.s, "::{"));
2252 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2253 s.print_ident(w.node.name)
2255 word(&mut self.s, "}")
2260 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2261 try!(self.hardbreak_if_not_bol());
2262 try!(self.maybe_print_comment(item.span.lo));
2263 try!(self.print_outer_attributes(item.attrs.as_slice()));
2264 try!(self.print_visibility(item.vis));
2266 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2267 try!(self.head("extern crate"));
2268 try!(self.print_ident(id));
2269 for &(ref p, style) in optional_path.iter() {
2270 try!(space(&mut self.s));
2271 try!(word(&mut self.s, "="));
2272 try!(space(&mut self.s));
2273 try!(self.print_string(p.get(), style));
2277 ast::ViewItemUse(ref vp) => {
2278 try!(self.head("use"));
2279 try!(self.print_view_path(&**vp));
2282 try!(word(&mut self.s, ";"));
2283 try!(self.end()); // end inner head-block
2284 self.end() // end outer head-block
2287 pub fn print_mutability(&mut self,
2288 mutbl: ast::Mutability) -> IoResult<()> {
2290 ast::MutMutable => self.word_nbsp("mut"),
2291 ast::MutImmutable => Ok(()),
2295 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2296 try!(self.print_mutability(mt.mutbl));
2297 self.print_type(&*mt.ty)
2300 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2301 try!(self.ibox(indent_unit));
2302 match input.ty.node {
2303 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2305 match input.pat.node {
2306 ast::PatIdent(_, ref path1, _) if
2308 parse::token::special_idents::invalid.name => {
2312 try!(self.print_pat(&*input.pat));
2313 try!(word(&mut self.s, ":"));
2314 try!(space(&mut self.s));
2317 try!(self.print_type(&*input.ty));
2323 pub fn print_ty_fn(&mut self,
2324 opt_abi: Option<abi::Abi>,
2325 opt_sigil: Option<char>,
2326 opt_region: &Option<ast::Lifetime>,
2327 fn_style: ast::FnStyle,
2328 onceness: ast::Onceness,
2330 id: Option<ast::Ident>,
2331 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2332 generics: Option<&ast::Generics>,
2333 opt_explicit_self: Option<ast::ExplicitSelf_>,
2336 try!(self.ibox(indent_unit));
2338 // Duplicates the logic in `print_fn_header_info()`. This is because that
2339 // function prints the sigil in the wrong place. That should be fixed.
2340 if opt_sigil == Some('~') && onceness == ast::Once {
2341 try!(word(&mut self.s, "proc"));
2342 } else if opt_sigil == Some('&') {
2343 try!(self.print_fn_style(fn_style));
2344 try!(self.print_extern_opt_abi(opt_abi));
2345 try!(self.print_onceness(onceness));
2347 assert!(opt_sigil.is_none());
2348 try!(self.print_fn_style(fn_style));
2349 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2350 try!(self.print_onceness(onceness));
2352 try!(word(&mut self.s, "fn"));
2358 try!(word(&mut self.s, " "));
2359 try!(self.print_ident(id));
2364 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2365 try!(zerobreak(&mut self.s));
2367 if is_unboxed || opt_sigil == Some('&') {
2368 try!(word(&mut self.s, "|"));
2374 try!(word(&mut self.s, "&mut"));
2375 try!(self.word_space(":"));
2378 try!(self.print_fn_args(decl, opt_explicit_self));
2380 if is_unboxed || opt_sigil == Some('&') {
2381 try!(word(&mut self.s, "|"));
2384 try!(word(&mut self.s, ", ..."));
2386 try!(self.pclose());
2389 opt_bounds.as_ref().map(|bounds| {
2390 self.print_bounds(opt_region, bounds, true, false)
2393 try!(self.maybe_print_comment(decl.output.span.lo));
2395 match decl.output.node {
2398 try!(self.space_if_not_bol());
2399 try!(self.ibox(indent_unit));
2400 try!(self.word_space("->"));
2401 if decl.cf == ast::NoReturn {
2402 try!(self.word_nbsp("!"));
2404 try!(self.print_type(&*decl.output));
2413 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2414 next_pos: Option<BytePos>)
2416 let cm = match self.cm {
2420 match self.next_comment() {
2422 if (*cmnt).style != comments::Trailing { return Ok(()) }
2423 let span_line = cm.lookup_char_pos(span.hi);
2424 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2425 let mut next = (*cmnt).pos + BytePos(1);
2426 match next_pos { None => (), Some(p) => next = p }
2427 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2428 span_line.line == comment_line.line {
2429 try!(self.print_comment(cmnt));
2430 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2438 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2439 // If there aren't any remaining comments, then we need to manually
2440 // make sure there is a line break at the end.
2441 if self.next_comment().is_none() {
2442 try!(hardbreak(&mut self.s));
2445 match self.next_comment() {
2447 try!(self.print_comment(cmnt));
2448 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2456 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2457 try!(self.maybe_print_comment(lit.span.lo));
2458 match self.next_lit(lit.span.lo) {
2460 return word(&mut self.s, (*ltrl).lit.as_slice());
2465 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2466 ast::LitByte(byte) => {
2467 let mut res = String::from_str("b'");
2468 (byte as char).escape_default(|c| res.push_char(c));
2469 res.push_char('\'');
2470 word(&mut self.s, res.as_slice())
2472 ast::LitChar(ch) => {
2473 let mut res = String::from_str("'");
2474 ch.escape_default(|c| res.push_char(c));
2475 res.push_char('\'');
2476 word(&mut self.s, res.as_slice())
2478 ast::LitInt(i, t) => {
2480 ast_util::int_ty_to_string(t, Some(i)).as_slice())
2482 ast::LitUint(u, t) => {
2484 ast_util::uint_ty_to_string(t, Some(u)).as_slice())
2486 ast::LitIntUnsuffixed(i) => {
2487 word(&mut self.s, format!("{}", i).as_slice())
2489 ast::LitFloat(ref f, t) => {
2494 ast_util::float_ty_to_string(t).as_slice()).as_slice())
2496 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2497 ast::LitNil => word(&mut self.s, "()"),
2498 ast::LitBool(val) => {
2499 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2501 ast::LitBinary(ref v) => {
2502 let escaped: String = v.iter().map(|&b| b as char).collect();
2503 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2508 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2509 match self.literals {
2511 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2512 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2513 if ltrl.pos > pos { return None; }
2514 self.cur_cmnt_and_lit.cur_lit += 1u;
2515 if ltrl.pos == pos { return Some(ltrl); }
2523 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2525 match self.next_comment() {
2527 if (*cmnt).pos < pos {
2528 try!(self.print_comment(cmnt));
2529 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2538 pub fn print_comment(&mut self,
2539 cmnt: &comments::Comment) -> IoResult<()> {
2541 comments::Mixed => {
2542 assert_eq!(cmnt.lines.len(), 1u);
2543 try!(zerobreak(&mut self.s));
2544 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2545 zerobreak(&mut self.s)
2547 comments::Isolated => {
2548 try!(self.hardbreak_if_not_bol());
2549 for line in cmnt.lines.iter() {
2550 // Don't print empty lines because they will end up as trailing
2552 if !line.is_empty() {
2553 try!(word(&mut self.s, line.as_slice()));
2555 try!(hardbreak(&mut self.s));
2559 comments::Trailing => {
2560 try!(word(&mut self.s, " "));
2561 if cmnt.lines.len() == 1u {
2562 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2563 hardbreak(&mut self.s)
2565 try!(self.ibox(0u));
2566 for line in cmnt.lines.iter() {
2567 if !line.is_empty() {
2568 try!(word(&mut self.s, line.as_slice()));
2570 try!(hardbreak(&mut self.s));
2575 comments::BlankLine => {
2576 // We need to do at least one, possibly two hardbreaks.
2577 let is_semi = match self.s.last_token() {
2578 pp::String(s, _) => ";" == s.as_slice(),
2581 if is_semi || self.is_begin() || self.is_end() {
2582 try!(hardbreak(&mut self.s));
2584 hardbreak(&mut self.s)
2589 pub fn print_string(&mut self, st: &str,
2590 style: ast::StrStyle) -> IoResult<()> {
2591 let st = match style {
2593 (format!("\"{}\"", st.escape_default()))
2596 (format!("r{delim}\"{string}\"{delim}",
2597 delim="#".repeat(n),
2601 word(&mut self.s, st.as_slice())
2604 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2605 match self.comments {
2606 Some(ref cmnts) => {
2607 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2608 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2617 pub fn print_opt_fn_style(&mut self,
2618 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2619 match opt_fn_style {
2620 Some(fn_style) => self.print_fn_style(fn_style),
2625 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2626 opt_abi: Option<abi::Abi>)
2629 Some(abi::Rust) => Ok(()),
2631 try!(self.word_nbsp("extern"));
2632 self.word_nbsp(abi.to_string().as_slice())
2638 pub fn print_extern_opt_abi(&mut self,
2639 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2642 try!(self.word_nbsp("extern"));
2643 self.word_nbsp(abi.to_string().as_slice())
2649 pub fn print_fn_header_info(&mut self,
2650 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2651 opt_fn_style: Option<ast::FnStyle>,
2653 vis: ast::Visibility) -> IoResult<()> {
2654 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2655 try!(self.print_opt_fn_style(opt_fn_style));
2657 if abi != abi::Rust {
2658 try!(self.word_nbsp("extern"));
2659 try!(self.word_nbsp(abi.to_string().as_slice()));
2662 word(&mut self.s, "fn")
2665 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2667 ast::NormalFn => Ok(()),
2668 ast::UnsafeFn => self.word_nbsp("unsafe"),
2672 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2674 ast::Once => self.word_nbsp("once"),
2690 fn test_fun_to_string() {
2691 let abba_ident = token::str_to_ident("abba");
2693 let decl = ast::FnDecl {
2695 output: ast::P(ast::Ty {id: 0,
2697 span: codemap::DUMMY_SP}),
2701 let generics = ast_util::empty_generics();
2702 assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident,
2704 &"fn abba()".to_string());
2708 fn test_variant_to_string() {
2709 let ident = token::str_to_ident("principal_skinner");
2711 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2714 // making this up as I go.... ?
2715 kind: ast::TupleVariantKind(Vec::new()),
2721 let varstr = variant_to_string(&var);
2722 assert_eq!(&varstr,&"pub principal_skinner".to_string());