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};
34 pub enum AnnNode<'a> {
35 NodeBlock(&'a ast::Block),
36 NodeItem(&'a ast::Item),
37 NodeExpr(&'a ast::Expr),
38 NodePat(&'a ast::Pat),
42 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
43 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
48 impl PpAnn for NoAnn {}
50 pub struct CurrentCommentAndLiteral {
55 pub struct State<'a> {
57 cm: Option<&'a CodeMap>,
58 comments: Option<Vec<comments::Comment> >,
59 literals: Option<Vec<comments::Literal> >,
60 cur_cmnt_and_lit: CurrentCommentAndLiteral,
61 boxes: Vec<pp::Breaks>,
65 pub fn rust_printer(writer: Box<io::Writer>) -> State<'static> {
66 static NO_ANN: NoAnn = NoAnn;
67 rust_printer_annotated(writer, &NO_ANN)
70 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer>,
71 ann: &'a PpAnn) -> State<'a> {
73 s: pp::mk_printer(writer, default_columns),
77 cur_cmnt_and_lit: CurrentCommentAndLiteral {
86 pub static indent_unit: uint = 4u;
88 pub static default_columns: uint = 78u;
90 /// Requires you to pass an input filename and reader so that
91 /// it can scan the input text for comments and literals to
93 pub fn print_crate<'a>(cm: &'a CodeMap,
94 span_diagnostic: &diagnostic::SpanHandler,
97 input: &mut io::Reader,
100 is_expanded: bool) -> IoResult<()> {
101 let (cmnts, lits) = comments::gather_comments_and_literals(
107 s: pp::mk_printer(out, default_columns),
109 comments: Some(cmnts),
110 // If the code is post expansion, don't use the table of
111 // literals, since it doesn't correspond with the literals
112 // in the AST anymore.
113 literals: if is_expanded {
118 cur_cmnt_and_lit: CurrentCommentAndLiteral {
125 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
126 try!(s.print_remaining_comments());
130 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
131 let mut s = rust_printer(box MemWriter::new());
133 eof(&mut s.s).unwrap();
135 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
136 // that we "know" to be a `MemWriter` that works around the lack of checked
138 let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);
140 String::from_utf8(Vec::from_slice(wr.get_ref())).unwrap();
146 pub fn ty_to_string(ty: &ast::Ty) -> String {
147 to_string(|s| s.print_type(ty))
150 pub fn pat_to_string(pat: &ast::Pat) -> String {
151 to_string(|s| s.print_pat(pat))
154 pub fn expr_to_string(e: &ast::Expr) -> String {
155 to_string(|s| s.print_expr(e))
158 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
159 to_string(|s| s.print_lifetime(e))
162 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
163 to_string(|s| s.print_tt(tt))
166 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
167 to_string(|s| s.print_tts(tts))
170 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
171 to_string(|s| s.print_stmt(stmt))
174 pub fn item_to_string(i: &ast::Item) -> String {
175 to_string(|s| s.print_item(i))
178 pub fn generics_to_string(generics: &ast::Generics) -> String {
179 to_string(|s| s.print_generics(generics))
182 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
183 to_string(|s| s.print_ty_method(p))
186 pub fn method_to_string(p: &ast::Method) -> String {
187 to_string(|s| s.print_method(p))
190 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
191 to_string(|s| s.print_fn_block_args(p, false))
194 pub fn path_to_string(p: &ast::Path) -> String {
195 to_string(|s| s.print_path(p, false))
198 pub fn ident_to_string(id: &ast::Ident) -> String {
199 to_string(|s| s.print_ident(*id))
202 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
203 opt_explicit_self: Option<ast::ExplicitSelf_>,
204 generics: &ast::Generics) -> String {
206 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
207 name, generics, opt_explicit_self, ast::Inherited));
208 try!(s.end()); // Close the head box
209 s.end() // Close the outer box
213 pub fn block_to_string(blk: &ast::Block) -> String {
215 // containing cbox, will be closed by print-block at }
216 try!(s.cbox(indent_unit));
217 // head-ibox, will be closed by print-block after {
223 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
224 to_string(|s| s.print_meta_item(mi))
227 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
228 to_string(|s| s.print_attribute(attr))
231 pub fn lit_to_string(l: &ast::Lit) -> String {
232 to_string(|s| s.print_literal(l))
235 pub fn explicit_self_to_string(explicit_self: ast::ExplicitSelf_) -> String {
236 to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
239 pub fn variant_to_string(var: &ast::Variant) -> String {
240 to_string(|s| s.print_variant(var))
243 pub fn arg_to_string(arg: &ast::Arg) -> String {
244 to_string(|s| s.print_arg(arg))
247 pub fn mac_to_string(arg: &ast::Mac) -> String {
248 to_string(|s| s.print_mac(arg))
251 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
253 ast::Public => format!("pub {}", s),
254 ast::Inherited => s.to_string()
258 fn needs_parentheses(expr: &ast::Expr) -> bool {
260 ast::ExprAssign(..) | ast::ExprBinary(..) |
261 ast::ExprFnBlock(..) | ast::ExprProc(..) |
262 ast::ExprUnboxedFn(..) | ast::ExprAssignOp(..) |
263 ast::ExprCast(..) => true,
269 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
270 self.boxes.push(pp::Inconsistent);
271 pp::ibox(&mut self.s, u)
274 pub fn end(&mut self) -> IoResult<()> {
275 self.boxes.pop().unwrap();
279 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
280 self.boxes.push(pp::Consistent);
281 pp::cbox(&mut self.s, u)
285 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
287 pp::rbox(&mut self.s, u, b)
290 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
292 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
293 try!(word(&mut self.s, w));
297 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
298 try!(word(&mut self.s, w));
302 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
304 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
306 pub fn head(&mut self, w: &str) -> IoResult<()> {
307 // outer-box is consistent
308 try!(self.cbox(indent_unit));
309 // head-box is inconsistent
310 try!(self.ibox(w.len() + 1));
311 // keyword that starts the head
313 try!(self.word_nbsp(w));
318 pub fn bopen(&mut self) -> IoResult<()> {
319 try!(word(&mut self.s, "{"));
320 self.end() // close the head-box
323 pub fn bclose_(&mut self, span: codemap::Span,
324 indented: uint) -> IoResult<()> {
325 self.bclose_maybe_open(span, indented, true)
327 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
328 indented: uint, close_box: bool) -> IoResult<()> {
329 try!(self.maybe_print_comment(span.hi));
330 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
331 try!(word(&mut self.s, "}"));
333 try!(self.end()); // close the outer-box
337 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
338 self.bclose_(span, indent_unit)
341 pub fn is_begin(&mut self) -> bool {
342 match self.s.last_token() { pp::Begin(_) => true, _ => false }
345 pub fn is_end(&mut self) -> bool {
346 match self.s.last_token() { pp::End => true, _ => false }
349 // is this the beginning of a line?
350 pub fn is_bol(&mut self) -> bool {
351 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
354 pub fn in_cbox(&self) -> bool {
355 match self.boxes.last() {
356 Some(&last_box) => last_box == pp::Consistent,
361 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
363 try!(hardbreak(&mut self.s))
367 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
368 if !self.is_bol() { try!(space(&mut self.s)); }
371 pub fn break_offset_if_not_bol(&mut self, n: uint,
372 off: int) -> IoResult<()> {
374 break_offset(&mut self.s, n, off)
376 if off != 0 && self.s.last_token().is_hardbreak_tok() {
377 // We do something pretty sketchy here: tuck the nonzero
378 // offset-adjustment we were going to deposit along with the
379 // break into the previous hardbreak.
380 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
386 // Synthesizes a comment that was not textually present in the original source
388 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
389 try!(word(&mut self.s, "/*"));
390 try!(space(&mut self.s));
391 try!(word(&mut self.s, text.as_slice()));
392 try!(space(&mut self.s));
393 word(&mut self.s, "*/")
396 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
397 op: |&mut State, &T| -> IoResult<()>)
399 try!(self.rbox(0u, b));
400 let mut first = true;
401 for elt in elts.iter() {
402 if first { first = false; } else { try!(self.word_space(",")); }
409 pub fn commasep_cmnt<T>(
413 op: |&mut State, &T| -> IoResult<()>,
414 get_span: |&T| -> codemap::Span) -> IoResult<()> {
415 try!(self.rbox(0u, b));
416 let len = elts.len();
418 for elt in elts.iter() {
419 try!(self.maybe_print_comment(get_span(elt).hi));
423 try!(word(&mut self.s, ","));
424 try!(self.maybe_print_trailing_comment(get_span(elt),
425 Some(get_span(&elts[i]).hi)));
426 try!(self.space_if_not_bol());
432 pub fn commasep_exprs(&mut self, b: Breaks,
433 exprs: &[Gc<ast::Expr>]) -> IoResult<()> {
434 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
437 pub fn print_mod(&mut self, _mod: &ast::Mod,
438 attrs: &[ast::Attribute]) -> IoResult<()> {
439 try!(self.print_inner_attributes(attrs));
440 for vitem in _mod.view_items.iter() {
441 try!(self.print_view_item(vitem));
443 for item in _mod.items.iter() {
444 try!(self.print_item(&**item));
449 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
450 attrs: &[ast::Attribute]) -> IoResult<()> {
451 try!(self.print_inner_attributes(attrs));
452 for vitem in nmod.view_items.iter() {
453 try!(self.print_view_item(vitem));
455 for item in nmod.items.iter() {
456 try!(self.print_foreign_item(&**item));
461 pub fn print_opt_lifetime(&mut self,
462 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
463 for l in lifetime.iter() {
464 try!(self.print_lifetime(l));
470 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
471 try!(self.maybe_print_comment(ty.span.lo));
474 ast::TyNil => try!(word(&mut self.s, "()")),
475 ast::TyBot => try!(word(&mut self.s, "!")),
476 ast::TyBox(ref ty) => {
477 try!(word(&mut self.s, "@"));
478 try!(self.print_type(&**ty));
480 ast::TyUniq(ref ty) => {
481 try!(word(&mut self.s, "~"));
482 try!(self.print_type(&**ty));
484 ast::TyVec(ref ty) => {
485 try!(word(&mut self.s, "["));
486 try!(self.print_type(&**ty));
487 try!(word(&mut self.s, "]"));
489 ast::TyPtr(ref mt) => {
490 try!(word(&mut self.s, "*"));
492 ast::MutMutable => try!(self.word_nbsp("mut")),
493 ast::MutImmutable => try!(self.word_nbsp("const")),
495 try!(self.print_type(&*mt.ty));
497 ast::TyRptr(ref lifetime, ref mt) => {
498 try!(word(&mut self.s, "&"));
499 try!(self.print_opt_lifetime(lifetime));
500 try!(self.print_mt(mt));
502 ast::TyTup(ref elts) => {
504 try!(self.commasep(Inconsistent, elts.as_slice(),
505 |s, ty| s.print_type_ref(ty)));
507 try!(word(&mut self.s, ","));
511 ast::TyParen(ref typ) => {
513 try!(self.print_type(&**typ));
516 ast::TyBareFn(f) => {
517 let generics = ast::Generics {
518 lifetimes: f.lifetimes.clone(),
519 ty_params: OwnedSlice::empty()
521 try!(self.print_ty_fn(Some(f.abi),
533 ast::TyClosure(f, ref region) => {
534 let generics = ast::Generics {
535 lifetimes: f.lifetimes.clone(),
536 ty_params: OwnedSlice::empty()
538 try!(self.print_ty_fn(None,
550 ast::TyProc(ref f) => {
551 let generics = ast::Generics {
552 lifetimes: f.lifetimes.clone(),
553 ty_params: OwnedSlice::empty()
555 try!(self.print_ty_fn(None,
567 ast::TyUnboxedFn(f) => {
568 try!(self.print_ty_fn(None,
580 ast::TyPath(ref path, ref bounds, _) => {
581 try!(self.print_bounded_path(path, bounds));
583 ast::TyFixedLengthVec(ref ty, ref v) => {
584 try!(word(&mut self.s, "["));
585 try!(self.print_type(&**ty));
586 try!(word(&mut self.s, ", .."));
587 try!(self.print_expr(&**v));
588 try!(word(&mut self.s, "]"));
590 ast::TyTypeof(ref e) => {
591 try!(word(&mut self.s, "typeof("));
592 try!(self.print_expr(&**e));
593 try!(word(&mut self.s, ")"));
596 try!(word(&mut self.s, "_"));
602 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
603 self.print_type(&**ty)
606 pub fn print_foreign_item(&mut self,
607 item: &ast::ForeignItem) -> IoResult<()> {
608 try!(self.hardbreak_if_not_bol());
609 try!(self.maybe_print_comment(item.span.lo));
610 try!(self.print_outer_attributes(item.attrs.as_slice()));
612 ast::ForeignItemFn(ref decl, ref generics) => {
613 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
615 try!(self.end()); // end head-ibox
616 try!(word(&mut self.s, ";"));
617 self.end() // end the outer fn box
619 ast::ForeignItemStatic(ref t, m) => {
620 try!(self.head(visibility_qualified(item.vis,
621 "static").as_slice()));
623 try!(self.word_space("mut"));
625 try!(self.print_ident(item.ident));
626 try!(self.word_space(":"));
627 try!(self.print_type(&**t));
628 try!(word(&mut self.s, ";"));
629 try!(self.end()); // end the head-ibox
630 self.end() // end the outer cbox
635 /// Pretty-print an item
636 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
637 try!(self.hardbreak_if_not_bol());
638 try!(self.maybe_print_comment(item.span.lo));
639 try!(self.print_outer_attributes(item.attrs.as_slice()));
640 try!(self.ann.pre(self, NodeItem(item)));
642 ast::ItemStatic(ref ty, m, ref expr) => {
643 try!(self.head(visibility_qualified(item.vis,
644 "static").as_slice()));
645 if m == ast::MutMutable {
646 try!(self.word_space("mut"));
648 try!(self.print_ident(item.ident));
649 try!(self.word_space(":"));
650 try!(self.print_type(&**ty));
651 try!(space(&mut self.s));
652 try!(self.end()); // end the head-ibox
654 try!(self.word_space("="));
655 try!(self.print_expr(&**expr));
656 try!(word(&mut self.s, ";"));
657 try!(self.end()); // end the outer cbox
659 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
669 try!(word(&mut self.s, " "));
670 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
672 ast::ItemMod(ref _mod) => {
673 try!(self.head(visibility_qualified(item.vis,
675 try!(self.print_ident(item.ident));
678 try!(self.print_mod(_mod, item.attrs.as_slice()));
679 try!(self.bclose(item.span));
681 ast::ItemForeignMod(ref nmod) => {
682 try!(self.head("extern"));
683 try!(self.word_nbsp(nmod.abi.to_string().as_slice()));
685 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
686 try!(self.bclose(item.span));
688 ast::ItemTy(ref ty, ref params) => {
689 try!(self.ibox(indent_unit));
691 try!(self.word_nbsp(visibility_qualified(item.vis,
692 "type").as_slice()));
693 try!(self.print_ident(item.ident));
694 try!(self.print_generics(params));
695 try!(self.end()); // end the inner ibox
697 try!(space(&mut self.s));
698 try!(self.word_space("="));
699 try!(self.print_type(&**ty));
700 try!(word(&mut self.s, ";"));
701 try!(self.end()); // end the outer ibox
703 ast::ItemEnum(ref enum_definition, ref params) => {
704 try!(self.print_enum_def(
712 ast::ItemStruct(ref struct_def, ref generics) => {
713 if struct_def.is_virtual {
714 try!(self.word_space("virtual"));
716 try!(self.head(visibility_qualified(item.vis,
717 "struct").as_slice()));
718 try!(self.print_struct(&**struct_def, generics, item.ident,
722 ast::ItemImpl(ref generics, ref opt_trait, ref ty, ref methods) => {
723 try!(self.head(visibility_qualified(item.vis,
724 "impl").as_slice()));
725 if generics.is_parameterized() {
726 try!(self.print_generics(generics));
727 try!(space(&mut self.s));
732 try!(self.print_trait_ref(t));
733 try!(space(&mut self.s));
734 try!(self.word_space("for"));
739 try!(self.print_type(&**ty));
741 try!(space(&mut self.s));
743 try!(self.print_inner_attributes(item.attrs.as_slice()));
744 for meth in methods.iter() {
745 try!(self.print_method(&**meth));
747 try!(self.bclose(item.span));
749 ast::ItemTrait(ref generics, ref unbound, ref traits, ref methods) => {
750 try!(self.head(visibility_qualified(item.vis,
751 "trait").as_slice()));
752 try!(self.print_ident(item.ident));
753 try!(self.print_generics(generics));
755 &Some(TraitTyParamBound(ref tref)) => {
756 try!(space(&mut self.s));
757 try!(self.word_space("for"));
758 try!(self.print_trait_ref(tref));
759 try!(word(&mut self.s, "?"));
763 if traits.len() != 0u {
764 try!(word(&mut self.s, ":"));
765 for (i, trait_) in traits.iter().enumerate() {
768 try!(self.word_space("+"));
770 try!(self.print_path(&trait_.path, false));
773 try!(word(&mut self.s, " "));
775 for meth in methods.iter() {
776 try!(self.print_trait_method(meth));
778 try!(self.bclose(item.span));
780 // I think it's reasonable to hide the context here:
781 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
783 try!(self.print_visibility(item.vis));
784 try!(self.print_path(pth, false));
785 try!(word(&mut self.s, "! "));
786 try!(self.print_ident(item.ident));
787 try!(self.cbox(indent_unit));
789 try!(self.print_tts(tts.as_slice()));
794 self.ann.post(self, NodeItem(item))
797 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
798 self.print_path(&t.path, false)
801 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
802 generics: &ast::Generics, ident: ast::Ident,
804 visibility: ast::Visibility) -> IoResult<()> {
805 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
806 try!(self.print_ident(ident));
807 try!(self.print_generics(generics));
808 try!(space(&mut self.s));
809 self.print_variants(enum_definition.variants.as_slice(), span)
812 pub fn print_variants(&mut self,
813 variants: &[P<ast::Variant>],
814 span: codemap::Span) -> IoResult<()> {
816 for v in variants.iter() {
817 try!(self.space_if_not_bol());
818 try!(self.maybe_print_comment(v.span.lo));
819 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
820 try!(self.ibox(indent_unit));
821 try!(self.print_variant(&**v));
822 try!(word(&mut self.s, ","));
824 try!(self.maybe_print_trailing_comment(v.span, None));
829 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
831 ast::Public => self.word_nbsp("pub"),
832 ast::Inherited => Ok(())
836 pub fn print_struct(&mut self,
837 struct_def: &ast::StructDef,
838 generics: &ast::Generics,
840 span: codemap::Span) -> IoResult<()> {
841 try!(self.print_ident(ident));
842 try!(self.print_generics(generics));
843 match struct_def.super_struct {
845 try!(self.word_space(":"));
846 try!(self.print_type(&**t));
850 if ast_util::struct_def_is_tuple_like(struct_def) {
851 if !struct_def.fields.is_empty() {
854 Inconsistent, struct_def.fields.as_slice(),
856 match field.node.kind {
857 ast::NamedField(..) => fail!("unexpected named field"),
858 ast::UnnamedField(vis) => {
859 try!(s.print_visibility(vis));
860 try!(s.maybe_print_comment(field.span.lo));
861 s.print_type(&*field.node.ty)
868 try!(word(&mut self.s, ";"));
870 self.end() // close the outer-box
874 try!(self.hardbreak_if_not_bol());
876 for field in struct_def.fields.iter() {
877 match field.node.kind {
878 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
879 ast::NamedField(ident, visibility) => {
880 try!(self.hardbreak_if_not_bol());
881 try!(self.maybe_print_comment(field.span.lo));
882 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
883 try!(self.print_visibility(visibility));
884 try!(self.print_ident(ident));
885 try!(self.word_nbsp(":"));
886 try!(self.print_type(&*field.node.ty));
887 try!(word(&mut self.s, ","));
896 /// This doesn't deserve to be called "pretty" printing, but it should be
897 /// meaning-preserving. A quick hack that might help would be to look at the
898 /// spans embedded in the TTs to decide where to put spaces and newlines.
899 /// But it'd be better to parse these according to the grammar of the
900 /// appropriate macro, transcribe back into the grammar we just parsed from,
901 /// and then pretty-print the resulting AST nodes (so, e.g., we print
902 /// expression arguments as expressions). It can be done! I think.
903 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
905 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
906 ast::TTTok(_, ref tk) => {
907 try!(word(&mut self.s, parse::token::to_string(tk).as_slice()));
909 parse::token::DOC_COMMENT(..) => {
910 hardbreak(&mut self.s)
915 ast::TTSeq(_, ref tts, ref sep, zerok) => {
916 try!(word(&mut self.s, "$("));
917 for tt_elt in (*tts).iter() {
918 try!(self.print_tt(tt_elt));
920 try!(word(&mut self.s, ")"));
923 try!(word(&mut self.s,
924 parse::token::to_string(tk).as_slice()));
928 word(&mut self.s, if zerok { "*" } else { "+" })
930 ast::TTNonterminal(_, name) => {
931 try!(word(&mut self.s, "$"));
932 self.print_ident(name)
937 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
939 for (i, tt) in tts.iter().enumerate() {
941 try!(space(&mut self.s));
943 try!(self.print_tt(tt));
948 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
949 try!(self.print_visibility(v.node.vis));
951 ast::TupleVariantKind(ref args) => {
952 try!(self.print_ident(v.node.name));
953 if !args.is_empty() {
955 try!(self.commasep(Consistent,
957 |s, arg| s.print_type(&*arg.ty)));
961 ast::StructVariantKind(ref struct_def) => {
963 let generics = ast_util::empty_generics();
964 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
967 match v.node.disr_expr {
969 try!(space(&mut self.s));
970 try!(self.word_space("="));
971 self.print_expr(&**d)
977 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
978 try!(self.hardbreak_if_not_bol());
979 try!(self.maybe_print_comment(m.span.lo));
980 try!(self.print_outer_attributes(m.attrs.as_slice()));
981 try!(self.print_ty_fn(None,
990 Some(m.explicit_self.node),
992 word(&mut self.s, ";")
995 pub fn print_trait_method(&mut self,
996 m: &ast::TraitMethod) -> IoResult<()> {
998 Required(ref ty_m) => self.print_ty_method(ty_m),
999 Provided(ref m) => self.print_method(&**m)
1003 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1004 try!(self.hardbreak_if_not_bol());
1005 try!(self.maybe_print_comment(meth.span.lo));
1006 try!(self.print_outer_attributes(meth.attrs.as_slice()));
1008 ast::MethDecl(ident,
1016 try!(self.print_fn(&*decl,
1021 Some(explicit_self.node),
1023 try!(word(&mut self.s, " "));
1024 self.print_block_with_attrs(&*body, meth.attrs.as_slice())
1026 ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1028 // code copied from ItemMac:
1029 try!(self.print_path(pth, false));
1030 try!(word(&mut self.s, "! "));
1031 try!(self.cbox(indent_unit));
1033 try!(self.print_tts(tts.as_slice()));
1034 try!(self.pclose());
1040 pub fn print_outer_attributes(&mut self,
1041 attrs: &[ast::Attribute]) -> IoResult<()> {
1043 for attr in attrs.iter() {
1044 match attr.node.style {
1046 try!(self.print_attribute(attr));
1049 _ => {/* fallthrough */ }
1053 try!(self.hardbreak_if_not_bol());
1058 pub fn print_inner_attributes(&mut self,
1059 attrs: &[ast::Attribute]) -> IoResult<()> {
1061 for attr in attrs.iter() {
1062 match attr.node.style {
1064 try!(self.print_attribute(attr));
1067 _ => {/* fallthrough */ }
1071 try!(self.hardbreak_if_not_bol());
1076 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1077 try!(self.hardbreak_if_not_bol());
1078 try!(self.maybe_print_comment(attr.span.lo));
1079 if attr.node.is_sugared_doc {
1080 word(&mut self.s, attr.value_str().unwrap().get())
1082 match attr.node.style {
1083 ast::AttrInner => try!(word(&mut self.s, "#![")),
1084 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1086 try!(self.print_meta_item(&*attr.meta()));
1087 word(&mut self.s, "]")
1092 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1093 try!(self.maybe_print_comment(st.span.lo));
1095 ast::StmtDecl(ref decl, _) => {
1096 try!(self.print_decl(&**decl));
1098 ast::StmtExpr(ref expr, _) => {
1099 try!(self.space_if_not_bol());
1100 try!(self.print_expr(&**expr));
1102 ast::StmtSemi(ref expr, _) => {
1103 try!(self.space_if_not_bol());
1104 try!(self.print_expr(&**expr));
1105 try!(word(&mut self.s, ";"));
1107 ast::StmtMac(ref mac, semi) => {
1108 try!(self.space_if_not_bol());
1109 try!(self.print_mac(mac));
1111 try!(word(&mut self.s, ";"));
1115 if parse::classify::stmt_ends_with_semi(st) {
1116 try!(word(&mut self.s, ";"));
1118 self.maybe_print_trailing_comment(st.span, None)
1121 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1122 self.print_block_with_attrs(blk, &[])
1125 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1126 self.print_block_unclosed_indent(blk, indent_unit)
1129 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1130 indented: uint) -> IoResult<()> {
1131 self.print_block_maybe_unclosed(blk, indented, &[], false)
1134 pub fn print_block_with_attrs(&mut self,
1136 attrs: &[ast::Attribute]) -> IoResult<()> {
1137 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1140 pub fn print_block_maybe_unclosed(&mut self,
1143 attrs: &[ast::Attribute],
1144 close_box: bool) -> IoResult<()> {
1146 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1147 ast::DefaultBlock => ()
1149 try!(self.maybe_print_comment(blk.span.lo));
1150 try!(self.ann.pre(self, NodeBlock(blk)));
1153 try!(self.print_inner_attributes(attrs));
1155 for vi in blk.view_items.iter() {
1156 try!(self.print_view_item(vi));
1158 for st in blk.stmts.iter() {
1159 try!(self.print_stmt(&**st));
1163 try!(self.space_if_not_bol());
1164 try!(self.print_expr(&**expr));
1165 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1169 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1170 self.ann.post(self, NodeBlock(blk))
1173 fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1177 // "another else-if"
1178 ast::ExprIf(ref i, ref t, e) => {
1179 try!(self.cbox(indent_unit - 1u));
1180 try!(self.ibox(0u));
1181 try!(word(&mut self.s, " else if "));
1182 try!(self.print_expr(&**i));
1183 try!(space(&mut self.s));
1184 try!(self.print_block(&**t));
1188 ast::ExprBlock(ref b) => {
1189 try!(self.cbox(indent_unit - 1u));
1190 try!(self.ibox(0u));
1191 try!(word(&mut self.s, " else "));
1192 self.print_block(&**b)
1194 // BLEAH, constraints would be great here
1196 fail!("print_if saw if with weird alternative");
1204 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1205 elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1206 try!(self.head("if"));
1207 if chk { try!(self.word_nbsp("check")); }
1208 try!(self.print_expr(test));
1209 try!(space(&mut self.s));
1210 try!(self.print_block(blk));
1211 self.print_else(elseopt)
1214 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1216 // I think it's reasonable to hide the ctxt here:
1217 ast::MacInvocTT(ref pth, ref tts, _) => {
1218 try!(self.print_path(pth, false));
1219 try!(word(&mut self.s, "!"));
1221 try!(self.print_tts(tts.as_slice()));
1227 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1229 ast::ExprVstoreUniq => word(&mut self.s, "box "),
1230 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1231 ast::ExprVstoreMutSlice => {
1232 try!(word(&mut self.s, "&"));
1233 word(&mut self.s, "mut")
1238 fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1240 try!(self.commasep_exprs(Inconsistent, args));
1244 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1245 let needs_par = needs_parentheses(expr);
1249 try!(self.print_expr(expr));
1251 try!(self.pclose());
1256 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1257 try!(self.maybe_print_comment(expr.span.lo));
1258 try!(self.ibox(indent_unit));
1259 try!(self.ann.pre(self, NodeExpr(expr)));
1261 ast::ExprVstore(ref e, v) => {
1262 try!(self.print_expr_vstore(v));
1263 try!(self.print_expr(&**e));
1265 ast::ExprBox(ref p, ref e) => {
1266 try!(word(&mut self.s, "box"));
1267 try!(word(&mut self.s, "("));
1268 try!(self.print_expr(&**p));
1269 try!(self.word_space(")"));
1270 try!(self.print_expr(&**e));
1272 ast::ExprVec(ref exprs) => {
1273 try!(self.ibox(indent_unit));
1274 try!(word(&mut self.s, "["));
1275 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1276 try!(word(&mut self.s, "]"));
1280 ast::ExprRepeat(ref element, ref count) => {
1281 try!(self.ibox(indent_unit));
1282 try!(word(&mut self.s, "["));
1283 try!(self.print_expr(&**element));
1284 try!(word(&mut self.s, ","));
1285 try!(word(&mut self.s, ".."));
1286 try!(self.print_expr(&**count));
1287 try!(word(&mut self.s, "]"));
1291 ast::ExprStruct(ref path, ref fields, wth) => {
1292 try!(self.print_path(path, true));
1293 try!(word(&mut self.s, "{"));
1294 try!(self.commasep_cmnt(
1298 try!(s.ibox(indent_unit));
1299 try!(s.print_ident(field.ident.node));
1300 try!(s.word_space(":"));
1301 try!(s.print_expr(&*field.expr));
1307 try!(self.ibox(indent_unit));
1308 if !fields.is_empty() {
1309 try!(word(&mut self.s, ","));
1310 try!(space(&mut self.s));
1312 try!(word(&mut self.s, ".."));
1313 try!(self.print_expr(&**expr));
1316 _ => try!(word(&mut self.s, ","))
1318 try!(word(&mut self.s, "}"));
1320 ast::ExprTup(ref exprs) => {
1322 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1323 if exprs.len() == 1 {
1324 try!(word(&mut self.s, ","));
1326 try!(self.pclose());
1328 ast::ExprCall(ref func, ref args) => {
1329 try!(self.print_expr_maybe_paren(&**func));
1330 try!(self.print_call_post(args.as_slice()));
1332 ast::ExprMethodCall(ident, ref tys, ref args) => {
1333 let base_args = args.slice_from(1);
1334 try!(self.print_expr(&**args.get(0)));
1335 try!(word(&mut self.s, "."));
1336 try!(self.print_ident(ident.node));
1338 try!(word(&mut self.s, "::<"));
1339 try!(self.commasep(Inconsistent, tys.as_slice(),
1340 |s, ty| s.print_type_ref(ty)));
1341 try!(word(&mut self.s, ">"));
1343 try!(self.print_call_post(base_args));
1345 ast::ExprBinary(op, ref lhs, ref rhs) => {
1346 try!(self.print_expr(&**lhs));
1347 try!(space(&mut self.s));
1348 try!(self.word_space(ast_util::binop_to_string(op)));
1349 try!(self.print_expr(&**rhs));
1351 ast::ExprUnary(op, ref expr) => {
1352 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1353 try!(self.print_expr_maybe_paren(&**expr));
1355 ast::ExprAddrOf(m, ref expr) => {
1356 try!(word(&mut self.s, "&"));
1357 try!(self.print_mutability(m));
1358 try!(self.print_expr_maybe_paren(&**expr));
1360 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1361 ast::ExprCast(ref expr, ref ty) => {
1362 try!(self.print_expr(&**expr));
1363 try!(space(&mut self.s));
1364 try!(self.word_space("as"));
1365 try!(self.print_type(&**ty));
1367 ast::ExprIf(ref test, ref blk, elseopt) => {
1368 try!(self.print_if(&**test, &**blk, elseopt, false));
1370 ast::ExprWhile(ref test, ref blk) => {
1371 try!(self.head("while"));
1372 try!(self.print_expr(&**test));
1373 try!(space(&mut self.s));
1374 try!(self.print_block(&**blk));
1376 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1377 for ident in opt_ident.iter() {
1378 try!(self.print_ident(*ident));
1379 try!(self.word_space(":"));
1381 try!(self.head("for"));
1382 try!(self.print_pat(&**pat));
1383 try!(space(&mut self.s));
1384 try!(self.word_space("in"));
1385 try!(self.print_expr(&**iter));
1386 try!(space(&mut self.s));
1387 try!(self.print_block(&**blk));
1389 ast::ExprLoop(ref blk, opt_ident) => {
1390 for ident in opt_ident.iter() {
1391 try!(self.print_ident(*ident));
1392 try!(self.word_space(":"));
1394 try!(self.head("loop"));
1395 try!(space(&mut self.s));
1396 try!(self.print_block(&**blk));
1398 ast::ExprMatch(ref expr, ref arms) => {
1399 try!(self.cbox(indent_unit));
1401 try!(self.word_nbsp("match"));
1402 try!(self.print_expr(&**expr));
1403 try!(space(&mut self.s));
1405 let len = arms.len();
1406 for (i, arm) in arms.iter().enumerate() {
1407 // I have no idea why this check is necessary, but here it
1409 if arm.attrs.is_empty() {
1410 try!(space(&mut self.s));
1412 try!(self.cbox(indent_unit));
1413 try!(self.ibox(0u));
1414 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1415 let mut first = true;
1416 for p in arm.pats.iter() {
1420 try!(space(&mut self.s));
1421 try!(self.word_space("|"));
1423 try!(self.print_pat(&**p));
1425 try!(space(&mut self.s));
1428 try!(self.word_space("if"));
1429 try!(self.print_expr(&**e));
1430 try!(space(&mut self.s));
1434 try!(self.word_space("=>"));
1436 match arm.body.node {
1437 ast::ExprBlock(ref blk) => {
1438 // the block will close the pattern's ibox
1439 try!(self.print_block_unclosed_indent(&**blk,
1443 try!(self.end()); // close the ibox for the pattern
1444 try!(self.print_expr(&*arm.body));
1447 if !expr_is_simple_block(expr.clone())
1449 try!(word(&mut self.s, ","));
1451 try!(self.end()); // close enclosing cbox
1453 try!(self.bclose_(expr.span, indent_unit));
1455 ast::ExprFnBlock(ref decl, ref body) => {
1456 // in do/for blocks we don't want to show an empty
1457 // argument list, but at this point we don't know which
1460 // if !decl.inputs.is_empty() {
1461 try!(self.print_fn_block_args(&**decl, false));
1462 try!(space(&mut self.s));
1465 if !body.stmts.is_empty() || !body.expr.is_some() {
1466 try!(self.print_block_unclosed(&**body));
1468 // we extract the block, so as not to create another set of boxes
1469 match body.expr.unwrap().node {
1470 ast::ExprBlock(blk) => {
1471 try!(self.print_block_unclosed(&*blk));
1474 // this is a bare expression
1475 try!(self.print_expr(&*body.expr.unwrap()));
1476 try!(self.end()); // need to close a box
1480 // a box will be closed by print_expr, but we didn't want an overall
1481 // wrapper so we closed the corresponding opening. so create an
1482 // empty box to satisfy the close.
1485 ast::ExprUnboxedFn(ref decl, ref body) => {
1486 // in do/for blocks we don't want to show an empty
1487 // argument list, but at this point we don't know which
1490 // if !decl.inputs.is_empty() {
1491 try!(self.print_fn_block_args(&**decl, true));
1492 try!(space(&mut self.s));
1495 if !body.stmts.is_empty() || !body.expr.is_some() {
1496 try!(self.print_block_unclosed(&**body));
1498 // we extract the block, so as not to create another set of boxes
1499 match body.expr.unwrap().node {
1500 ast::ExprBlock(ref blk) => {
1501 try!(self.print_block_unclosed(&**blk));
1504 // this is a bare expression
1505 try!(self.print_expr(&*body.expr.unwrap()));
1506 try!(self.end()); // need to close a box
1510 // a box will be closed by print_expr, but we didn't want an overall
1511 // wrapper so we closed the corresponding opening. so create an
1512 // empty box to satisfy the close.
1515 ast::ExprProc(ref decl, ref body) => {
1516 // in do/for blocks we don't want to show an empty
1517 // argument list, but at this point we don't know which
1520 // if !decl.inputs.is_empty() {
1521 try!(self.print_proc_args(&**decl));
1522 try!(space(&mut self.s));
1524 assert!(body.stmts.is_empty());
1525 assert!(body.expr.is_some());
1526 // we extract the block, so as not to create another set of boxes
1527 match body.expr.unwrap().node {
1528 ast::ExprBlock(ref blk) => {
1529 try!(self.print_block_unclosed(&**blk));
1532 // this is a bare expression
1533 try!(self.print_expr(&*body.expr.unwrap()));
1534 try!(self.end()); // need to close a box
1537 // a box will be closed by print_expr, but we didn't want an overall
1538 // wrapper so we closed the corresponding opening. so create an
1539 // empty box to satisfy the close.
1542 ast::ExprBlock(ref blk) => {
1543 // containing cbox, will be closed by print-block at }
1544 try!(self.cbox(indent_unit));
1545 // head-box, will be closed by print-block after {
1546 try!(self.ibox(0u));
1547 try!(self.print_block(&**blk));
1549 ast::ExprAssign(ref lhs, ref rhs) => {
1550 try!(self.print_expr(&**lhs));
1551 try!(space(&mut self.s));
1552 try!(self.word_space("="));
1553 try!(self.print_expr(&**rhs));
1555 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1556 try!(self.print_expr(&**lhs));
1557 try!(space(&mut self.s));
1558 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1559 try!(self.word_space("="));
1560 try!(self.print_expr(&**rhs));
1562 ast::ExprField(ref expr, id, ref tys) => {
1563 try!(self.print_expr(&**expr));
1564 try!(word(&mut self.s, "."));
1565 try!(self.print_ident(id.node));
1567 try!(word(&mut self.s, "::<"));
1569 Inconsistent, tys.as_slice(),
1570 |s, ty| s.print_type_ref(ty)));
1571 try!(word(&mut self.s, ">"));
1574 ast::ExprIndex(ref expr, ref index) => {
1575 try!(self.print_expr(&**expr));
1576 try!(word(&mut self.s, "["));
1577 try!(self.print_expr(&**index));
1578 try!(word(&mut self.s, "]"));
1580 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1581 ast::ExprBreak(opt_ident) => {
1582 try!(word(&mut self.s, "break"));
1583 try!(space(&mut self.s));
1584 for ident in opt_ident.iter() {
1585 try!(self.print_ident(*ident));
1586 try!(space(&mut self.s));
1589 ast::ExprAgain(opt_ident) => {
1590 try!(word(&mut self.s, "continue"));
1591 try!(space(&mut self.s));
1592 for ident in opt_ident.iter() {
1593 try!(self.print_ident(*ident));
1594 try!(space(&mut self.s))
1597 ast::ExprRet(ref result) => {
1598 try!(word(&mut self.s, "return"));
1601 try!(word(&mut self.s, " "));
1602 try!(self.print_expr(&**expr));
1607 ast::ExprInlineAsm(ref a) => {
1609 try!(word(&mut self.s, "__volatile__ asm!"));
1611 try!(word(&mut self.s, "asm!"));
1614 try!(self.print_string(a.asm.get(), a.asm_str_style));
1615 try!(self.word_space(":"));
1617 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1618 |s, &(ref co, ref o)| {
1619 try!(s.print_string(co.get(), ast::CookedStr));
1621 try!(s.print_expr(&**o));
1625 try!(space(&mut self.s));
1626 try!(self.word_space(":"));
1628 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1629 |s, &(ref co, ref o)| {
1630 try!(s.print_string(co.get(), ast::CookedStr));
1632 try!(s.print_expr(&**o));
1636 try!(space(&mut self.s));
1637 try!(self.word_space(":"));
1639 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1640 try!(self.pclose());
1642 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1643 ast::ExprParen(ref e) => {
1645 try!(self.print_expr(&**e));
1646 try!(self.pclose());
1649 try!(self.ann.post(self, NodeExpr(expr)));
1653 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1654 try!(self.print_pat(&*loc.pat));
1656 ast::TyInfer => Ok(()),
1658 try!(self.word_space(":"));
1659 self.print_type(&*loc.ty)
1664 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1665 try!(self.maybe_print_comment(decl.span.lo));
1667 ast::DeclLocal(ref loc) => {
1668 try!(self.space_if_not_bol());
1669 try!(self.ibox(indent_unit));
1670 try!(self.word_nbsp("let"));
1672 try!(self.ibox(indent_unit));
1673 try!(self.print_local_decl(&**loc));
1678 try!(self.word_space("="));
1679 try!(self.print_expr(&**init));
1685 ast::DeclItem(ref item) => self.print_item(&**item)
1689 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1690 word(&mut self.s, token::get_ident(ident).get())
1693 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1694 word(&mut self.s, token::get_name(name).get())
1697 pub fn print_for_decl(&mut self, loc: &ast::Local,
1698 coll: &ast::Expr) -> IoResult<()> {
1699 try!(self.print_local_decl(loc));
1700 try!(space(&mut self.s));
1701 try!(self.word_space("in"));
1702 self.print_expr(coll)
1705 fn print_path_(&mut self,
1707 colons_before_params: bool,
1708 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1710 try!(self.maybe_print_comment(path.span.lo));
1712 try!(word(&mut self.s, "::"));
1715 let mut first = true;
1716 for segment in path.segments.iter() {
1720 try!(word(&mut self.s, "::"))
1723 try!(self.print_ident(segment.identifier));
1725 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1726 if colons_before_params {
1727 try!(word(&mut self.s, "::"))
1729 try!(word(&mut self.s, "<"));
1731 let mut comma = false;
1732 for lifetime in segment.lifetimes.iter() {
1734 try!(self.word_space(","))
1736 try!(self.print_lifetime(lifetime));
1740 if !segment.types.is_empty() {
1742 try!(self.word_space(","))
1746 segment.types.as_slice(),
1747 |s, ty| s.print_type_ref(ty)));
1750 try!(word(&mut self.s, ">"))
1756 Some(ref bounds) => self.print_bounds(&None, bounds, true, true),
1760 fn print_path(&mut self, path: &ast::Path,
1761 colons_before_params: bool) -> IoResult<()> {
1762 self.print_path_(path, colons_before_params, &None)
1765 fn print_bounded_path(&mut self, path: &ast::Path,
1766 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1768 self.print_path_(path, false, bounds)
1771 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1772 try!(self.maybe_print_comment(pat.span.lo));
1773 try!(self.ann.pre(self, NodePat(pat)));
1774 /* Pat isn't normalized, but the beauty of it
1775 is that it doesn't matter */
1777 ast::PatWild => try!(word(&mut self.s, "_")),
1778 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1779 ast::PatIdent(binding_mode, ref path1, sub) => {
1780 match binding_mode {
1781 ast::BindByRef(mutbl) => {
1782 try!(self.word_nbsp("ref"));
1783 try!(self.print_mutability(mutbl));
1785 ast::BindByValue(ast::MutImmutable) => {}
1786 ast::BindByValue(ast::MutMutable) => {
1787 try!(self.word_nbsp("mut"));
1790 try!(self.print_ident(path1.node));
1793 try!(word(&mut self.s, "@"));
1794 try!(self.print_pat(&**p));
1799 ast::PatEnum(ref path, ref args_) => {
1800 try!(self.print_path(path, true));
1802 None => try!(word(&mut self.s, "(..)")),
1804 if !args.is_empty() {
1806 try!(self.commasep(Inconsistent, args.as_slice(),
1807 |s, p| s.print_pat(&**p)));
1808 try!(self.pclose());
1813 ast::PatStruct(ref path, ref fields, etc) => {
1814 try!(self.print_path(path, true));
1816 try!(self.word_space("{"));
1817 try!(self.commasep_cmnt(
1818 Consistent, fields.as_slice(),
1820 try!(s.cbox(indent_unit));
1821 try!(s.print_ident(f.ident));
1822 try!(s.word_nbsp(":"));
1823 try!(s.print_pat(&*f.pat));
1828 if fields.len() != 0u { try!(self.word_space(",")); }
1829 try!(word(&mut self.s, ".."));
1831 try!(space(&mut self.s));
1832 try!(word(&mut self.s, "}"));
1834 ast::PatTup(ref elts) => {
1836 try!(self.commasep(Inconsistent,
1838 |s, p| s.print_pat(&**p)));
1839 if elts.len() == 1 {
1840 try!(word(&mut self.s, ","));
1842 try!(self.pclose());
1844 ast::PatBox(ref inner) => {
1845 try!(word(&mut self.s, "box "));
1846 try!(self.print_pat(&**inner));
1848 ast::PatRegion(ref inner) => {
1849 try!(word(&mut self.s, "&"));
1850 try!(self.print_pat(&**inner));
1852 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1853 ast::PatRange(ref begin, ref end) => {
1854 try!(self.print_expr(&**begin));
1855 try!(space(&mut self.s));
1856 try!(word(&mut self.s, ".."));
1857 try!(self.print_expr(&**end));
1859 ast::PatVec(ref before, slice, ref after) => {
1860 try!(word(&mut self.s, "["));
1861 try!(self.commasep(Inconsistent,
1863 |s, p| s.print_pat(&**p)));
1864 for p in slice.iter() {
1865 if !before.is_empty() { try!(self.word_space(",")); }
1867 ast::Pat { node: ast::PatWildMulti, .. } => {
1868 // this case is handled by print_pat
1870 _ => try!(word(&mut self.s, "..")),
1872 try!(self.print_pat(&**p));
1873 if !after.is_empty() { try!(self.word_space(",")); }
1875 try!(self.commasep(Inconsistent,
1877 |s, p| s.print_pat(&**p)));
1878 try!(word(&mut self.s, "]"));
1880 ast::PatMac(ref m) => try!(self.print_mac(m)),
1882 self.ann.post(self, NodePat(pat))
1885 // Returns whether it printed anything
1886 fn print_explicit_self(&mut self,
1887 explicit_self: ast::ExplicitSelf_,
1888 mutbl: ast::Mutability) -> IoResult<bool> {
1889 try!(self.print_mutability(mutbl));
1890 match explicit_self {
1891 ast::SelfStatic => { return Ok(false); }
1892 ast::SelfValue(_) => {
1893 try!(word(&mut self.s, "self"));
1895 ast::SelfRegion(ref lt, m, _) => {
1896 try!(word(&mut self.s, "&"));
1897 try!(self.print_opt_lifetime(lt));
1898 try!(self.print_mutability(m));
1899 try!(word(&mut self.s, "self"));
1901 ast::SelfExplicit(ref typ, _) => {
1902 try!(word(&mut self.s, "self"));
1903 try!(self.word_space(":"));
1904 try!(self.print_type(&**typ));
1910 pub fn print_fn(&mut self,
1912 fn_style: Option<ast::FnStyle>,
1915 generics: &ast::Generics,
1916 opt_explicit_self: Option<ast::ExplicitSelf_>,
1917 vis: ast::Visibility) -> IoResult<()> {
1918 try!(self.head(""));
1919 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1921 try!(self.print_ident(name));
1922 try!(self.print_generics(generics));
1923 self.print_fn_args_and_ret(decl, opt_explicit_self)
1926 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1927 opt_explicit_self: Option<ast::ExplicitSelf_>)
1929 // It is unfortunate to duplicate the commasep logic, but we want the
1930 // self type and the args all in the same box.
1931 try!(self.rbox(0u, Inconsistent));
1932 let mut first = true;
1933 for &explicit_self in opt_explicit_self.iter() {
1934 let m = match explicit_self {
1935 ast::SelfStatic => ast::MutImmutable,
1936 _ => match decl.inputs.get(0).pat.node {
1937 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1938 _ => ast::MutImmutable
1941 first = !try!(self.print_explicit_self(explicit_self, m));
1944 // HACK(eddyb) ignore the separately printed self argument.
1945 let args = if first {
1946 decl.inputs.as_slice()
1948 decl.inputs.slice_from(1)
1951 for arg in args.iter() {
1952 if first { first = false; } else { try!(self.word_space(",")); }
1953 try!(self.print_arg(arg));
1959 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1960 opt_explicit_self: Option<ast::ExplicitSelf_>)
1963 try!(self.print_fn_args(decl, opt_explicit_self));
1965 try!(word(&mut self.s, ", ..."));
1967 try!(self.pclose());
1969 try!(self.maybe_print_comment(decl.output.span.lo));
1970 match decl.output.node {
1971 ast::TyNil => Ok(()),
1973 try!(self.space_if_not_bol());
1974 try!(self.word_space("->"));
1975 self.print_type(&*decl.output)
1980 pub fn print_fn_block_args(&mut self,
1984 try!(word(&mut self.s, "|"));
1986 try!(self.word_space("&mut:"));
1988 try!(self.print_fn_args(decl, None));
1989 try!(word(&mut self.s, "|"));
1991 match decl.output.node {
1994 try!(self.space_if_not_bol());
1995 try!(self.word_space("->"));
1996 try!(self.print_type(&*decl.output));
2000 self.maybe_print_comment(decl.output.span.lo)
2003 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2004 try!(word(&mut self.s, "proc"));
2005 try!(word(&mut self.s, "("));
2006 try!(self.print_fn_args(decl, None));
2007 try!(word(&mut self.s, ")"));
2009 match decl.output.node {
2012 try!(self.space_if_not_bol());
2013 try!(self.word_space("->"));
2014 try!(self.print_type(&*decl.output));
2018 self.maybe_print_comment(decl.output.span.lo)
2021 pub fn print_bounds(&mut self,
2022 region: &Option<ast::Lifetime>,
2023 bounds: &OwnedSlice<ast::TyParamBound>,
2024 print_colon_anyway: bool,
2025 print_plus_before_bounds: bool)
2027 let separator = if print_plus_before_bounds {
2032 if !bounds.is_empty() || region.is_some() {
2033 try!(word(&mut self.s, separator));
2034 let mut first = true;
2037 let token = token::get_name(lt.name);
2038 if token.get() != "'static" {
2041 try!(self.print_lifetime(lt));
2046 for bound in bounds.iter() {
2051 try!(self.word_space("+"));
2055 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
2056 StaticRegionTyParamBound => word(&mut self.s, "'static"),
2057 UnboxedFnTyParamBound(ref unboxed_function_type) => {
2058 self.print_ty_fn(None,
2063 &*unboxed_function_type.decl,
2070 OtherRegionTyParamBound(_) => Ok(())
2074 } else if print_colon_anyway {
2075 word(&mut self.s, separator)
2081 pub fn print_lifetime(&mut self,
2082 lifetime: &ast::Lifetime) -> IoResult<()> {
2083 self.print_name(lifetime.name)
2086 pub fn print_generics(&mut self,
2087 generics: &ast::Generics) -> IoResult<()> {
2088 let total = generics.lifetimes.len() + generics.ty_params.len();
2090 try!(word(&mut self.s, "<"));
2092 let mut ints = Vec::new();
2093 for i in range(0u, total) {
2098 Inconsistent, ints.as_slice(),
2100 if idx < generics.lifetimes.len() {
2101 let lifetime = generics.lifetimes.get(idx);
2102 s.print_lifetime(lifetime)
2104 let idx = idx - generics.lifetimes.len();
2105 let param = generics.ty_params.get(idx);
2106 match param.unbound {
2107 Some(TraitTyParamBound(ref tref)) => {
2108 try!(s.print_trait_ref(tref));
2109 try!(s.word_space("?"));
2113 try!(s.print_ident(param.ident));
2114 try!(s.print_bounds(&None,
2118 match param.default {
2119 Some(ref default) => {
2120 try!(space(&mut s.s));
2121 try!(s.word_space("="));
2122 s.print_type(&**default)
2128 word(&mut self.s, ">")
2134 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2135 try!(self.ibox(indent_unit));
2137 ast::MetaWord(ref name) => {
2138 try!(word(&mut self.s, name.get()));
2140 ast::MetaNameValue(ref name, ref value) => {
2141 try!(self.word_space(name.get()));
2142 try!(self.word_space("="));
2143 try!(self.print_literal(value));
2145 ast::MetaList(ref name, ref items) => {
2146 try!(word(&mut self.s, name.get()));
2148 try!(self.commasep(Consistent,
2150 |s, i| s.print_meta_item(&**i)));
2151 try!(self.pclose());
2157 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2159 ast::ViewPathSimple(ident, ref path, _) => {
2160 // FIXME(#6993) can't compare identifiers directly here
2161 if path.segments.last().unwrap().identifier.name != ident.name {
2162 try!(self.print_ident(ident));
2163 try!(space(&mut self.s));
2164 try!(self.word_space("="));
2166 self.print_path(path, false)
2169 ast::ViewPathGlob(ref path, _) => {
2170 try!(self.print_path(path, false));
2171 word(&mut self.s, "::*")
2174 ast::ViewPathList(ref path, ref idents, _) => {
2175 if path.segments.is_empty() {
2176 try!(word(&mut self.s, "{"));
2178 try!(self.print_path(path, false));
2179 try!(word(&mut self.s, "::{"));
2181 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2183 ast::PathListIdent { name, .. } => {
2186 ast::PathListMod { .. } => {
2187 word(&mut s.s, "mod")
2191 word(&mut self.s, "}")
2196 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2197 try!(self.hardbreak_if_not_bol());
2198 try!(self.maybe_print_comment(item.span.lo));
2199 try!(self.print_outer_attributes(item.attrs.as_slice()));
2200 try!(self.print_visibility(item.vis));
2202 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2203 try!(self.head("extern crate"));
2204 try!(self.print_ident(id));
2205 for &(ref p, style) in optional_path.iter() {
2206 try!(space(&mut self.s));
2207 try!(word(&mut self.s, "="));
2208 try!(space(&mut self.s));
2209 try!(self.print_string(p.get(), style));
2213 ast::ViewItemUse(ref vp) => {
2214 try!(self.head("use"));
2215 try!(self.print_view_path(&**vp));
2218 try!(word(&mut self.s, ";"));
2219 try!(self.end()); // end inner head-block
2220 self.end() // end outer head-block
2223 pub fn print_mutability(&mut self,
2224 mutbl: ast::Mutability) -> IoResult<()> {
2226 ast::MutMutable => self.word_nbsp("mut"),
2227 ast::MutImmutable => Ok(()),
2231 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2232 try!(self.print_mutability(mt.mutbl));
2233 self.print_type(&*mt.ty)
2236 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2237 try!(self.ibox(indent_unit));
2238 match input.ty.node {
2239 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2241 match input.pat.node {
2242 ast::PatIdent(_, ref path1, _) if
2244 parse::token::special_idents::invalid.name => {
2248 try!(self.print_pat(&*input.pat));
2249 try!(word(&mut self.s, ":"));
2250 try!(space(&mut self.s));
2253 try!(self.print_type(&*input.ty));
2259 pub fn print_ty_fn(&mut self,
2260 opt_abi: Option<abi::Abi>,
2261 opt_sigil: Option<char>,
2262 opt_region: &Option<ast::Lifetime>,
2263 fn_style: ast::FnStyle,
2264 onceness: ast::Onceness,
2266 id: Option<ast::Ident>,
2267 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2268 generics: Option<&ast::Generics>,
2269 opt_explicit_self: Option<ast::ExplicitSelf_>,
2272 try!(self.ibox(indent_unit));
2274 // Duplicates the logic in `print_fn_header_info()`. This is because that
2275 // function prints the sigil in the wrong place. That should be fixed.
2276 if opt_sigil == Some('~') && onceness == ast::Once {
2277 try!(word(&mut self.s, "proc"));
2278 } else if opt_sigil == Some('&') {
2279 try!(self.print_fn_style(fn_style));
2280 try!(self.print_extern_opt_abi(opt_abi));
2281 try!(self.print_onceness(onceness));
2283 assert!(opt_sigil.is_none());
2284 try!(self.print_fn_style(fn_style));
2285 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2286 try!(self.print_onceness(onceness));
2288 try!(word(&mut self.s, "fn"));
2294 try!(word(&mut self.s, " "));
2295 try!(self.print_ident(id));
2300 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2301 try!(zerobreak(&mut self.s));
2303 if is_unboxed || opt_sigil == Some('&') {
2304 try!(word(&mut self.s, "|"));
2310 try!(word(&mut self.s, "&mut"));
2311 try!(self.word_space(":"));
2314 try!(self.print_fn_args(decl, opt_explicit_self));
2316 if is_unboxed || opt_sigil == Some('&') {
2317 try!(word(&mut self.s, "|"));
2320 try!(word(&mut self.s, ", ..."));
2322 try!(self.pclose());
2325 opt_bounds.as_ref().map(|bounds| {
2326 self.print_bounds(opt_region, bounds, true, false)
2329 try!(self.maybe_print_comment(decl.output.span.lo));
2331 match decl.output.node {
2334 try!(self.space_if_not_bol());
2335 try!(self.ibox(indent_unit));
2336 try!(self.word_space("->"));
2337 if decl.cf == ast::NoReturn {
2338 try!(self.word_nbsp("!"));
2340 try!(self.print_type(&*decl.output));
2349 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2350 next_pos: Option<BytePos>)
2352 let cm = match self.cm {
2356 match self.next_comment() {
2358 if (*cmnt).style != comments::Trailing { return Ok(()) }
2359 let span_line = cm.lookup_char_pos(span.hi);
2360 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2361 let mut next = (*cmnt).pos + BytePos(1);
2362 match next_pos { None => (), Some(p) => next = p }
2363 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2364 span_line.line == comment_line.line {
2365 try!(self.print_comment(cmnt));
2366 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2374 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2375 // If there aren't any remaining comments, then we need to manually
2376 // make sure there is a line break at the end.
2377 if self.next_comment().is_none() {
2378 try!(hardbreak(&mut self.s));
2381 match self.next_comment() {
2383 try!(self.print_comment(cmnt));
2384 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2392 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2393 try!(self.maybe_print_comment(lit.span.lo));
2394 match self.next_lit(lit.span.lo) {
2396 return word(&mut self.s, (*ltrl).lit.as_slice());
2401 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2402 ast::LitByte(byte) => {
2403 let mut res = String::from_str("b'");
2404 (byte as char).escape_default(|c| res.push_char(c));
2405 res.push_char('\'');
2406 word(&mut self.s, res.as_slice())
2408 ast::LitChar(ch) => {
2409 let mut res = String::from_str("'");
2410 ch.escape_default(|c| res.push_char(c));
2411 res.push_char('\'');
2412 word(&mut self.s, res.as_slice())
2414 ast::LitInt(i, t) => {
2416 ast_util::int_ty_to_string(t, Some(i)).as_slice())
2418 ast::LitUint(u, t) => {
2420 ast_util::uint_ty_to_string(t, Some(u)).as_slice())
2422 ast::LitIntUnsuffixed(i) => {
2423 word(&mut self.s, format!("{}", i).as_slice())
2425 ast::LitFloat(ref f, t) => {
2430 ast_util::float_ty_to_string(t).as_slice()).as_slice())
2432 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2433 ast::LitNil => word(&mut self.s, "()"),
2434 ast::LitBool(val) => {
2435 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2437 ast::LitBinary(ref v) => {
2438 let escaped: String = v.iter().map(|&b| b as char).collect();
2439 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2444 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2445 match self.literals {
2447 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2448 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2449 if ltrl.pos > pos { return None; }
2450 self.cur_cmnt_and_lit.cur_lit += 1u;
2451 if ltrl.pos == pos { return Some(ltrl); }
2459 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2461 match self.next_comment() {
2463 if (*cmnt).pos < pos {
2464 try!(self.print_comment(cmnt));
2465 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2474 pub fn print_comment(&mut self,
2475 cmnt: &comments::Comment) -> IoResult<()> {
2477 comments::Mixed => {
2478 assert_eq!(cmnt.lines.len(), 1u);
2479 try!(zerobreak(&mut self.s));
2480 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2481 zerobreak(&mut self.s)
2483 comments::Isolated => {
2484 try!(self.hardbreak_if_not_bol());
2485 for line in cmnt.lines.iter() {
2486 // Don't print empty lines because they will end up as trailing
2488 if !line.is_empty() {
2489 try!(word(&mut self.s, line.as_slice()));
2491 try!(hardbreak(&mut self.s));
2495 comments::Trailing => {
2496 try!(word(&mut self.s, " "));
2497 if cmnt.lines.len() == 1u {
2498 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2499 hardbreak(&mut self.s)
2501 try!(self.ibox(0u));
2502 for line in cmnt.lines.iter() {
2503 if !line.is_empty() {
2504 try!(word(&mut self.s, line.as_slice()));
2506 try!(hardbreak(&mut self.s));
2511 comments::BlankLine => {
2512 // We need to do at least one, possibly two hardbreaks.
2513 let is_semi = match self.s.last_token() {
2514 pp::String(s, _) => ";" == s.as_slice(),
2517 if is_semi || self.is_begin() || self.is_end() {
2518 try!(hardbreak(&mut self.s));
2520 hardbreak(&mut self.s)
2525 pub fn print_string(&mut self, st: &str,
2526 style: ast::StrStyle) -> IoResult<()> {
2527 let st = match style {
2529 (format!("\"{}\"", st.escape_default()))
2532 (format!("r{delim}\"{string}\"{delim}",
2533 delim="#".repeat(n),
2537 word(&mut self.s, st.as_slice())
2540 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2541 match self.comments {
2542 Some(ref cmnts) => {
2543 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2544 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2553 pub fn print_opt_fn_style(&mut self,
2554 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2555 match opt_fn_style {
2556 Some(fn_style) => self.print_fn_style(fn_style),
2561 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2562 opt_abi: Option<abi::Abi>)
2565 Some(abi::Rust) => Ok(()),
2567 try!(self.word_nbsp("extern"));
2568 self.word_nbsp(abi.to_string().as_slice())
2574 pub fn print_extern_opt_abi(&mut self,
2575 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2578 try!(self.word_nbsp("extern"));
2579 self.word_nbsp(abi.to_string().as_slice())
2585 pub fn print_fn_header_info(&mut self,
2586 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2587 opt_fn_style: Option<ast::FnStyle>,
2589 vis: ast::Visibility) -> IoResult<()> {
2590 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2591 try!(self.print_opt_fn_style(opt_fn_style));
2593 if abi != abi::Rust {
2594 try!(self.word_nbsp("extern"));
2595 try!(self.word_nbsp(abi.to_string().as_slice()));
2598 word(&mut self.s, "fn")
2601 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2603 ast::NormalFn => Ok(()),
2604 ast::UnsafeFn => self.word_nbsp("unsafe"),
2608 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2610 ast::Once => self.word_nbsp("once"),
2626 fn test_fun_to_string() {
2627 let abba_ident = token::str_to_ident("abba");
2629 let decl = ast::FnDecl {
2631 output: ast::P(ast::Ty {id: 0,
2633 span: codemap::DUMMY_SP}),
2637 let generics = ast_util::empty_generics();
2638 assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident,
2640 &"fn abba()".to_string());
2644 fn test_variant_to_string() {
2645 let ident = token::str_to_ident("principal_skinner");
2647 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2650 // making this up as I go.... ?
2651 kind: ast::TupleVariantKind(Vec::new()),
2657 let varstr = variant_to_string(&var);
2658 assert_eq!(&varstr,&"pub principal_skinner".to_string());