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_str(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_str(ty: &ast::Ty) -> String {
148 to_str(|s| s.print_type(ty))
151 pub fn pat_to_str(pat: &ast::Pat) -> String {
152 to_str(|s| s.print_pat(pat))
155 pub fn expr_to_str(e: &ast::Expr) -> String {
156 to_str(|s| s.print_expr(e))
159 pub fn lifetime_to_str(e: &ast::Lifetime) -> String {
160 to_str(|s| s.print_lifetime(e))
163 pub fn tt_to_str(tt: &ast::TokenTree) -> String {
164 to_str(|s| s.print_tt(tt))
167 pub fn tts_to_str(tts: &[ast::TokenTree]) -> String {
168 to_str(|s| s.print_tts(tts))
171 pub fn stmt_to_str(stmt: &ast::Stmt) -> String {
172 to_str(|s| s.print_stmt(stmt))
175 pub fn item_to_str(i: &ast::Item) -> String {
176 to_str(|s| s.print_item(i))
179 pub fn generics_to_str(generics: &ast::Generics) -> String {
180 to_str(|s| s.print_generics(generics))
183 pub fn ty_method_to_str(p: &ast::TypeMethod) -> String {
184 to_str(|s| s.print_ty_method(p))
187 pub fn method_to_str(p: &ast::Method) -> String {
188 to_str(|s| s.print_method(p))
191 pub fn fn_block_to_str(p: &ast::FnDecl) -> String {
192 to_str(|s| s.print_fn_block_args(p))
195 pub fn path_to_str(p: &ast::Path) -> String {
196 to_str(|s| s.print_path(p, false))
199 pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
200 opt_explicit_self: Option<ast::ExplicitSelf_>,
201 generics: &ast::Generics) -> String {
203 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
204 name, generics, opt_explicit_self, ast::Inherited));
205 try!(s.end()); // Close the head box
206 s.end() // Close the outer box
210 pub fn block_to_str(blk: &ast::Block) -> String {
212 // containing cbox, will be closed by print-block at }
213 try!(s.cbox(indent_unit));
214 // head-ibox, will be closed by print-block after {
220 pub fn meta_item_to_str(mi: &ast::MetaItem) -> String {
221 to_str(|s| s.print_meta_item(mi))
224 pub fn attribute_to_str(attr: &ast::Attribute) -> String {
225 to_str(|s| s.print_attribute(attr))
228 pub fn lit_to_str(l: &ast::Lit) -> String {
229 to_str(|s| s.print_literal(l))
232 pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> String {
233 to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
236 pub fn variant_to_str(var: &ast::Variant) -> String {
237 to_str(|s| s.print_variant(var))
240 pub fn arg_to_str(arg: &ast::Arg) -> String {
241 to_str(|s| s.print_arg(arg))
244 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
246 ast::Public => format!("pub {}", s).to_string(),
247 ast::Inherited => s.to_string()
251 fn needs_parentheses(expr: &ast::Expr) -> bool {
253 ast::ExprAssign(..) | ast::ExprBinary(..) |
254 ast::ExprFnBlock(..) | ast::ExprProc(..) |
255 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
261 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
262 self.boxes.push(pp::Inconsistent);
263 pp::ibox(&mut self.s, u)
266 pub fn end(&mut self) -> IoResult<()> {
267 self.boxes.pop().unwrap();
271 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
272 self.boxes.push(pp::Consistent);
273 pp::cbox(&mut self.s, u)
277 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
279 pp::rbox(&mut self.s, u, b)
282 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
284 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
285 try!(word(&mut self.s, w));
289 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
290 try!(word(&mut self.s, w));
294 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
296 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
298 pub fn head(&mut self, w: &str) -> IoResult<()> {
299 // outer-box is consistent
300 try!(self.cbox(indent_unit));
301 // head-box is inconsistent
302 try!(self.ibox(w.len() + 1));
303 // keyword that starts the head
305 try!(self.word_nbsp(w));
310 pub fn bopen(&mut self) -> IoResult<()> {
311 try!(word(&mut self.s, "{"));
312 self.end() // close the head-box
315 pub fn bclose_(&mut self, span: codemap::Span,
316 indented: uint) -> IoResult<()> {
317 self.bclose_maybe_open(span, indented, true)
319 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
320 indented: uint, close_box: bool) -> IoResult<()> {
321 try!(self.maybe_print_comment(span.hi));
322 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
323 try!(word(&mut self.s, "}"));
325 try!(self.end()); // close the outer-box
329 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
330 self.bclose_(span, indent_unit)
333 pub fn is_begin(&mut self) -> bool {
334 match self.s.last_token() { pp::Begin(_) => true, _ => false }
337 pub fn is_end(&mut self) -> bool {
338 match self.s.last_token() { pp::End => true, _ => false }
341 pub fn is_bol(&mut self) -> bool {
342 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
345 pub fn in_cbox(&self) -> bool {
346 match self.boxes.last() {
347 Some(&last_box) => last_box == pp::Consistent,
352 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
354 try!(hardbreak(&mut self.s))
358 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
359 if !self.is_bol() { try!(space(&mut self.s)); }
362 pub fn break_offset_if_not_bol(&mut self, n: uint,
363 off: int) -> IoResult<()> {
365 break_offset(&mut self.s, n, off)
367 if off != 0 && self.s.last_token().is_hardbreak_tok() {
368 // We do something pretty sketchy here: tuck the nonzero
369 // offset-adjustment we were going to deposit along with the
370 // break into the previous hardbreak.
371 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
377 // Synthesizes a comment that was not textually present in the original source
379 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
380 try!(word(&mut self.s, "/*"));
381 try!(space(&mut self.s));
382 try!(word(&mut self.s, text.as_slice()));
383 try!(space(&mut self.s));
384 word(&mut self.s, "*/")
387 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
388 op: |&mut State, &T| -> IoResult<()>)
390 try!(self.rbox(0u, b));
391 let mut first = true;
392 for elt in elts.iter() {
393 if first { first = false; } else { try!(self.word_space(",")); }
400 pub fn commasep_cmnt<T>(
404 op: |&mut State, &T| -> IoResult<()>,
405 get_span: |&T| -> codemap::Span) -> IoResult<()> {
406 try!(self.rbox(0u, b));
407 let len = elts.len();
409 for elt in elts.iter() {
410 try!(self.maybe_print_comment(get_span(elt).hi));
414 try!(word(&mut self.s, ","));
415 try!(self.maybe_print_trailing_comment(get_span(elt),
416 Some(get_span(&elts[i]).hi)));
417 try!(self.space_if_not_bol());
423 pub fn commasep_exprs(&mut self, b: Breaks,
424 exprs: &[Gc<ast::Expr>]) -> IoResult<()> {
425 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
428 pub fn print_mod(&mut self, _mod: &ast::Mod,
429 attrs: &[ast::Attribute]) -> IoResult<()> {
430 try!(self.print_inner_attributes(attrs));
431 for vitem in _mod.view_items.iter() {
432 try!(self.print_view_item(vitem));
434 for item in _mod.items.iter() {
435 try!(self.print_item(&**item));
440 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
441 attrs: &[ast::Attribute]) -> IoResult<()> {
442 try!(self.print_inner_attributes(attrs));
443 for vitem in nmod.view_items.iter() {
444 try!(self.print_view_item(vitem));
446 for item in nmod.items.iter() {
447 try!(self.print_foreign_item(&**item));
452 pub fn print_opt_lifetime(&mut self,
453 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
454 for l in lifetime.iter() {
455 try!(self.print_lifetime(l));
461 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
462 try!(self.maybe_print_comment(ty.span.lo));
465 ast::TyNil => try!(word(&mut self.s, "()")),
466 ast::TyBot => try!(word(&mut self.s, "!")),
467 ast::TyBox(ref ty) => {
468 try!(word(&mut self.s, "@"));
469 try!(self.print_type(&**ty));
471 ast::TyUniq(ref ty) => {
472 try!(word(&mut self.s, "~"));
473 try!(self.print_type(&**ty));
475 ast::TyVec(ref ty) => {
476 try!(word(&mut self.s, "["));
477 try!(self.print_type(&**ty));
478 try!(word(&mut self.s, "]"));
480 ast::TyPtr(ref mt) => {
481 try!(word(&mut self.s, "*"));
482 try!(self.print_mt(mt));
484 ast::TyRptr(ref lifetime, ref mt) => {
485 try!(word(&mut self.s, "&"));
486 try!(self.print_opt_lifetime(lifetime));
487 try!(self.print_mt(mt));
489 ast::TyTup(ref elts) => {
491 try!(self.commasep(Inconsistent, elts.as_slice(),
492 |s, ty| s.print_type_ref(ty)));
494 try!(word(&mut self.s, ","));
498 ast::TyBareFn(f) => {
499 let generics = ast::Generics {
500 lifetimes: f.lifetimes.clone(),
501 ty_params: OwnedSlice::empty()
503 try!(self.print_ty_fn(Some(f.abi),
515 ast::TyClosure(f, ref region) => {
516 let generics = ast::Generics {
517 lifetimes: f.lifetimes.clone(),
518 ty_params: OwnedSlice::empty()
520 try!(self.print_ty_fn(None,
532 ast::TyProc(ref f) => {
533 let generics = ast::Generics {
534 lifetimes: f.lifetimes.clone(),
535 ty_params: OwnedSlice::empty()
537 try!(self.print_ty_fn(None,
549 ast::TyUnboxedFn(f) => {
550 try!(self.print_ty_fn(None,
562 ast::TyPath(ref path, ref bounds, _) => {
563 try!(self.print_bounded_path(path, bounds));
565 ast::TyFixedLengthVec(ref ty, ref v) => {
566 try!(word(&mut self.s, "["));
567 try!(self.print_type(&**ty));
568 try!(word(&mut self.s, ", .."));
569 try!(self.print_expr(&**v));
570 try!(word(&mut self.s, "]"));
572 ast::TyTypeof(ref e) => {
573 try!(word(&mut self.s, "typeof("));
574 try!(self.print_expr(&**e));
575 try!(word(&mut self.s, ")"));
578 try!(word(&mut self.s, "_"));
584 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
585 self.print_type(&**ty)
588 pub fn print_foreign_item(&mut self,
589 item: &ast::ForeignItem) -> IoResult<()> {
590 try!(self.hardbreak_if_not_bol());
591 try!(self.maybe_print_comment(item.span.lo));
592 try!(self.print_outer_attributes(item.attrs.as_slice()));
594 ast::ForeignItemFn(ref decl, ref generics) => {
595 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
597 try!(self.end()); // end head-ibox
598 try!(word(&mut self.s, ";"));
599 self.end() // end the outer fn box
601 ast::ForeignItemStatic(ref t, m) => {
602 try!(self.head(visibility_qualified(item.vis,
603 "static").as_slice()));
605 try!(self.word_space("mut"));
607 try!(self.print_ident(item.ident));
608 try!(self.word_space(":"));
609 try!(self.print_type(&**t));
610 try!(word(&mut self.s, ";"));
611 try!(self.end()); // end the head-ibox
612 self.end() // end the outer cbox
617 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
618 try!(self.hardbreak_if_not_bol());
619 try!(self.maybe_print_comment(item.span.lo));
620 try!(self.print_outer_attributes(item.attrs.as_slice()));
621 try!(self.ann.pre(self, NodeItem(item)));
623 ast::ItemStatic(ref ty, m, ref expr) => {
624 try!(self.head(visibility_qualified(item.vis,
625 "static").as_slice()));
626 if m == ast::MutMutable {
627 try!(self.word_space("mut"));
629 try!(self.print_ident(item.ident));
630 try!(self.word_space(":"));
631 try!(self.print_type(&**ty));
632 try!(space(&mut self.s));
633 try!(self.end()); // end the head-ibox
635 try!(self.word_space("="));
636 try!(self.print_expr(&**expr));
637 try!(word(&mut self.s, ";"));
638 try!(self.end()); // end the outer cbox
640 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
650 try!(word(&mut self.s, " "));
651 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
653 ast::ItemMod(ref _mod) => {
654 try!(self.head(visibility_qualified(item.vis,
656 try!(self.print_ident(item.ident));
659 try!(self.print_mod(_mod, item.attrs.as_slice()));
660 try!(self.bclose(item.span));
662 ast::ItemForeignMod(ref nmod) => {
663 try!(self.head("extern"));
664 try!(self.word_nbsp(nmod.abi.to_str().as_slice()));
666 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
667 try!(self.bclose(item.span));
669 ast::ItemTy(ref ty, ref params) => {
670 try!(self.ibox(indent_unit));
672 try!(self.word_nbsp(visibility_qualified(item.vis,
673 "type").as_slice()));
674 try!(self.print_ident(item.ident));
675 try!(self.print_generics(params));
676 try!(self.end()); // end the inner ibox
678 try!(space(&mut self.s));
679 try!(self.word_space("="));
680 try!(self.print_type(&**ty));
681 try!(word(&mut self.s, ";"));
682 try!(self.end()); // end the outer ibox
684 ast::ItemEnum(ref enum_definition, ref params) => {
685 try!(self.print_enum_def(
693 ast::ItemStruct(ref struct_def, ref generics) => {
694 if struct_def.is_virtual {
695 try!(self.word_space("virtual"));
697 try!(self.head(visibility_qualified(item.vis,
698 "struct").as_slice()));
699 try!(self.print_struct(&**struct_def, generics, item.ident,
703 ast::ItemImpl(ref generics, ref opt_trait, ref ty, ref methods) => {
704 try!(self.head(visibility_qualified(item.vis,
705 "impl").as_slice()));
706 if generics.is_parameterized() {
707 try!(self.print_generics(generics));
708 try!(space(&mut self.s));
713 try!(self.print_trait_ref(t));
714 try!(space(&mut self.s));
715 try!(self.word_space("for"));
720 try!(self.print_type(&**ty));
722 try!(space(&mut self.s));
724 try!(self.print_inner_attributes(item.attrs.as_slice()));
725 for meth in methods.iter() {
726 try!(self.print_method(&**meth));
728 try!(self.bclose(item.span));
730 ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => {
731 try!(self.head(visibility_qualified(item.vis,
732 "trait").as_slice()));
733 try!(self.print_ident(item.ident));
734 try!(self.print_generics(generics));
735 if *sized == ast::DynSize {
736 try!(space(&mut self.s));
737 try!(word(&mut self.s, "for type"));
739 if traits.len() != 0u {
740 try!(word(&mut self.s, ":"));
741 for (i, trait_) in traits.iter().enumerate() {
744 try!(self.word_space("+"));
746 try!(self.print_path(&trait_.path, false));
749 try!(word(&mut self.s, " "));
751 for meth in methods.iter() {
752 try!(self.print_trait_method(meth));
754 try!(self.bclose(item.span));
756 // I think it's reasonable to hide the context here:
757 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
759 try!(self.print_visibility(item.vis));
760 try!(self.print_path(pth, false));
761 try!(word(&mut self.s, "! "));
762 try!(self.print_ident(item.ident));
763 try!(self.cbox(indent_unit));
765 try!(self.print_tts(tts.as_slice()));
770 self.ann.post(self, NodeItem(item))
773 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
774 self.print_path(&t.path, false)
777 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
778 generics: &ast::Generics, ident: ast::Ident,
780 visibility: ast::Visibility) -> IoResult<()> {
781 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
782 try!(self.print_ident(ident));
783 try!(self.print_generics(generics));
784 try!(space(&mut self.s));
785 self.print_variants(enum_definition.variants.as_slice(), span)
788 pub fn print_variants(&mut self,
789 variants: &[P<ast::Variant>],
790 span: codemap::Span) -> IoResult<()> {
792 for v in variants.iter() {
793 try!(self.space_if_not_bol());
794 try!(self.maybe_print_comment(v.span.lo));
795 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
796 try!(self.ibox(indent_unit));
797 try!(self.print_variant(&**v));
798 try!(word(&mut self.s, ","));
800 try!(self.maybe_print_trailing_comment(v.span, None));
805 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
807 ast::Public => self.word_nbsp("pub"),
808 ast::Inherited => Ok(())
812 pub fn print_struct(&mut self,
813 struct_def: &ast::StructDef,
814 generics: &ast::Generics,
816 span: codemap::Span) -> IoResult<()> {
817 try!(self.print_ident(ident));
818 try!(self.print_generics(generics));
819 match struct_def.super_struct {
821 try!(self.word_space(":"));
822 try!(self.print_type(&**t));
826 if ast_util::struct_def_is_tuple_like(struct_def) {
827 if !struct_def.fields.is_empty() {
830 Inconsistent, struct_def.fields.as_slice(),
832 match field.node.kind {
833 ast::NamedField(..) => fail!("unexpected named field"),
834 ast::UnnamedField(vis) => {
835 try!(s.print_visibility(vis));
836 try!(s.maybe_print_comment(field.span.lo));
837 s.print_type(&*field.node.ty)
844 try!(word(&mut self.s, ";"));
846 self.end() // close the outer-box
850 try!(self.hardbreak_if_not_bol());
852 for field in struct_def.fields.iter() {
853 match field.node.kind {
854 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
855 ast::NamedField(ident, visibility) => {
856 try!(self.hardbreak_if_not_bol());
857 try!(self.maybe_print_comment(field.span.lo));
858 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
859 try!(self.print_visibility(visibility));
860 try!(self.print_ident(ident));
861 try!(self.word_nbsp(":"));
862 try!(self.print_type(&*field.node.ty));
863 try!(word(&mut self.s, ","));
872 /// This doesn't deserve to be called "pretty" printing, but it should be
873 /// meaning-preserving. A quick hack that might help would be to look at the
874 /// spans embedded in the TTs to decide where to put spaces and newlines.
875 /// But it'd be better to parse these according to the grammar of the
876 /// appropriate macro, transcribe back into the grammar we just parsed from,
877 /// and then pretty-print the resulting AST nodes (so, e.g., we print
878 /// expression arguments as expressions). It can be done! I think.
879 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
881 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
882 ast::TTTok(_, ref tk) => {
883 try!(word(&mut self.s, parse::token::to_str(tk).as_slice()));
885 parse::token::DOC_COMMENT(..) => {
886 hardbreak(&mut self.s)
891 ast::TTSeq(_, ref tts, ref sep, zerok) => {
892 try!(word(&mut self.s, "$("));
893 for tt_elt in (*tts).iter() {
894 try!(self.print_tt(tt_elt));
896 try!(word(&mut self.s, ")"));
899 try!(word(&mut self.s,
900 parse::token::to_str(tk).as_slice()));
904 word(&mut self.s, if zerok { "*" } else { "+" })
906 ast::TTNonterminal(_, name) => {
907 try!(word(&mut self.s, "$"));
908 self.print_ident(name)
913 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
915 for (i, tt) in tts.iter().enumerate() {
917 try!(space(&mut self.s));
919 try!(self.print_tt(tt));
924 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
925 try!(self.print_visibility(v.node.vis));
927 ast::TupleVariantKind(ref args) => {
928 try!(self.print_ident(v.node.name));
929 if !args.is_empty() {
931 try!(self.commasep(Consistent,
933 |s, arg| s.print_type(&*arg.ty)));
937 ast::StructVariantKind(ref struct_def) => {
939 let generics = ast_util::empty_generics();
940 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
943 match v.node.disr_expr {
945 try!(space(&mut self.s));
946 try!(self.word_space("="));
947 self.print_expr(&**d)
953 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
954 try!(self.hardbreak_if_not_bol());
955 try!(self.maybe_print_comment(m.span.lo));
956 try!(self.print_outer_attributes(m.attrs.as_slice()));
957 try!(self.print_ty_fn(None,
966 Some(m.explicit_self.node),
968 word(&mut self.s, ";")
971 pub fn print_trait_method(&mut self,
972 m: &ast::TraitMethod) -> IoResult<()> {
974 Required(ref ty_m) => self.print_ty_method(ty_m),
975 Provided(ref m) => self.print_method(&**m)
979 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
980 try!(self.hardbreak_if_not_bol());
981 try!(self.maybe_print_comment(meth.span.lo));
982 try!(self.print_outer_attributes(meth.attrs.as_slice()));
983 try!(self.print_fn(&*meth.decl, Some(meth.fn_style), abi::Rust,
984 meth.ident, &meth.generics, Some(meth.explicit_self.node),
986 try!(word(&mut self.s, " "));
987 self.print_block_with_attrs(&*meth.body, meth.attrs.as_slice())
990 pub fn print_outer_attributes(&mut self,
991 attrs: &[ast::Attribute]) -> IoResult<()> {
993 for attr in attrs.iter() {
994 match attr.node.style {
996 try!(self.print_attribute(attr));
999 _ => {/* fallthrough */ }
1003 try!(self.hardbreak_if_not_bol());
1008 pub fn print_inner_attributes(&mut self,
1009 attrs: &[ast::Attribute]) -> IoResult<()> {
1011 for attr in attrs.iter() {
1012 match attr.node.style {
1014 try!(self.print_attribute(attr));
1017 _ => {/* fallthrough */ }
1021 try!(self.hardbreak_if_not_bol());
1026 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1027 try!(self.hardbreak_if_not_bol());
1028 try!(self.maybe_print_comment(attr.span.lo));
1029 if attr.node.is_sugared_doc {
1030 word(&mut self.s, attr.value_str().unwrap().get())
1032 match attr.node.style {
1033 ast::AttrInner => try!(word(&mut self.s, "#![")),
1034 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1036 try!(self.print_meta_item(&*attr.meta()));
1037 word(&mut self.s, "]")
1042 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1043 try!(self.maybe_print_comment(st.span.lo));
1045 ast::StmtDecl(ref decl, _) => {
1046 try!(self.print_decl(&**decl));
1048 ast::StmtExpr(ref expr, _) => {
1049 try!(self.space_if_not_bol());
1050 try!(self.print_expr(&**expr));
1052 ast::StmtSemi(ref expr, _) => {
1053 try!(self.space_if_not_bol());
1054 try!(self.print_expr(&**expr));
1055 try!(word(&mut self.s, ";"));
1057 ast::StmtMac(ref mac, semi) => {
1058 try!(self.space_if_not_bol());
1059 try!(self.print_mac(mac));
1061 try!(word(&mut self.s, ";"));
1065 if parse::classify::stmt_ends_with_semi(st) {
1066 try!(word(&mut self.s, ";"));
1068 self.maybe_print_trailing_comment(st.span, None)
1071 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1072 self.print_block_with_attrs(blk, &[])
1075 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1076 self.print_block_unclosed_indent(blk, indent_unit)
1079 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1080 indented: uint) -> IoResult<()> {
1081 self.print_block_maybe_unclosed(blk, indented, &[], false)
1084 pub fn print_block_with_attrs(&mut self,
1086 attrs: &[ast::Attribute]) -> IoResult<()> {
1087 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1090 pub fn print_block_maybe_unclosed(&mut self,
1093 attrs: &[ast::Attribute],
1094 close_box: bool) -> IoResult<()> {
1096 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1097 ast::DefaultBlock => ()
1099 try!(self.maybe_print_comment(blk.span.lo));
1100 try!(self.ann.pre(self, NodeBlock(blk)));
1103 try!(self.print_inner_attributes(attrs));
1105 for vi in blk.view_items.iter() {
1106 try!(self.print_view_item(vi));
1108 for st in blk.stmts.iter() {
1109 try!(self.print_stmt(&**st));
1113 try!(self.space_if_not_bol());
1114 try!(self.print_expr(&**expr));
1115 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1119 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1120 self.ann.post(self, NodeBlock(blk))
1123 fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1127 // "another else-if"
1128 ast::ExprIf(ref i, ref t, e) => {
1129 try!(self.cbox(indent_unit - 1u));
1130 try!(self.ibox(0u));
1131 try!(word(&mut self.s, " else if "));
1132 try!(self.print_expr(&**i));
1133 try!(space(&mut self.s));
1134 try!(self.print_block(&**t));
1138 ast::ExprBlock(ref b) => {
1139 try!(self.cbox(indent_unit - 1u));
1140 try!(self.ibox(0u));
1141 try!(word(&mut self.s, " else "));
1142 self.print_block(&**b)
1144 // BLEAH, constraints would be great here
1146 fail!("print_if saw if with weird alternative");
1154 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1155 elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1156 try!(self.head("if"));
1157 if chk { try!(self.word_nbsp("check")); }
1158 try!(self.print_expr(test));
1159 try!(space(&mut self.s));
1160 try!(self.print_block(blk));
1161 self.print_else(elseopt)
1164 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1166 // I think it's reasonable to hide the ctxt here:
1167 ast::MacInvocTT(ref pth, ref tts, _) => {
1168 try!(self.print_path(pth, false));
1169 try!(word(&mut self.s, "!"));
1171 try!(self.print_tts(tts.as_slice()));
1177 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1179 ast::ExprVstoreUniq => word(&mut self.s, "box "),
1180 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1181 ast::ExprVstoreMutSlice => {
1182 try!(word(&mut self.s, "&"));
1183 word(&mut self.s, "mut")
1188 fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1190 try!(self.commasep_exprs(Inconsistent, args));
1194 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1195 let needs_par = needs_parentheses(expr);
1199 try!(self.print_expr(expr));
1201 try!(self.pclose());
1206 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1207 try!(self.maybe_print_comment(expr.span.lo));
1208 try!(self.ibox(indent_unit));
1209 try!(self.ann.pre(self, NodeExpr(expr)));
1211 ast::ExprVstore(ref e, v) => {
1212 try!(self.print_expr_vstore(v));
1213 try!(self.print_expr(&**e));
1215 ast::ExprBox(ref p, ref e) => {
1216 try!(word(&mut self.s, "box"));
1217 try!(word(&mut self.s, "("));
1218 try!(self.print_expr(&**p));
1219 try!(self.word_space(")"));
1220 try!(self.print_expr(&**e));
1222 ast::ExprVec(ref exprs) => {
1223 try!(self.ibox(indent_unit));
1224 try!(word(&mut self.s, "["));
1225 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1226 try!(word(&mut self.s, "]"));
1230 ast::ExprRepeat(ref element, ref count) => {
1231 try!(self.ibox(indent_unit));
1232 try!(word(&mut self.s, "["));
1233 try!(self.print_expr(&**element));
1234 try!(word(&mut self.s, ","));
1235 try!(word(&mut self.s, ".."));
1236 try!(self.print_expr(&**count));
1237 try!(word(&mut self.s, "]"));
1241 ast::ExprStruct(ref path, ref fields, wth) => {
1242 try!(self.print_path(path, true));
1243 try!(word(&mut self.s, "{"));
1244 try!(self.commasep_cmnt(
1248 try!(s.ibox(indent_unit));
1249 try!(s.print_ident(field.ident.node));
1250 try!(s.word_space(":"));
1251 try!(s.print_expr(&*field.expr));
1257 try!(self.ibox(indent_unit));
1258 if !fields.is_empty() {
1259 try!(word(&mut self.s, ","));
1260 try!(space(&mut self.s));
1262 try!(word(&mut self.s, ".."));
1263 try!(self.print_expr(&**expr));
1266 _ => try!(word(&mut self.s, ","))
1268 try!(word(&mut self.s, "}"));
1270 ast::ExprTup(ref exprs) => {
1272 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1273 if exprs.len() == 1 {
1274 try!(word(&mut self.s, ","));
1276 try!(self.pclose());
1278 ast::ExprCall(ref func, ref args) => {
1279 try!(self.print_expr_maybe_paren(&**func));
1280 try!(self.print_call_post(args.as_slice()));
1282 ast::ExprMethodCall(ident, ref tys, ref args) => {
1283 let base_args = args.slice_from(1);
1284 try!(self.print_expr(&**args.get(0)));
1285 try!(word(&mut self.s, "."));
1286 try!(self.print_ident(ident.node));
1288 try!(word(&mut self.s, "::<"));
1289 try!(self.commasep(Inconsistent, tys.as_slice(),
1290 |s, ty| s.print_type_ref(ty)));
1291 try!(word(&mut self.s, ">"));
1293 try!(self.print_call_post(base_args));
1295 ast::ExprBinary(op, ref lhs, ref rhs) => {
1296 try!(self.print_expr(&**lhs));
1297 try!(space(&mut self.s));
1298 try!(self.word_space(ast_util::binop_to_str(op)));
1299 try!(self.print_expr(&**rhs));
1301 ast::ExprUnary(op, ref expr) => {
1302 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1303 try!(self.print_expr_maybe_paren(&**expr));
1305 ast::ExprAddrOf(m, ref expr) => {
1306 try!(word(&mut self.s, "&"));
1307 try!(self.print_mutability(m));
1308 try!(self.print_expr_maybe_paren(&**expr));
1310 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1311 ast::ExprCast(ref expr, ref ty) => {
1312 try!(self.print_expr(&**expr));
1313 try!(space(&mut self.s));
1314 try!(self.word_space("as"));
1315 try!(self.print_type(&**ty));
1317 ast::ExprIf(ref test, ref blk, elseopt) => {
1318 try!(self.print_if(&**test, &**blk, elseopt, false));
1320 ast::ExprWhile(ref test, ref blk) => {
1321 try!(self.head("while"));
1322 try!(self.print_expr(&**test));
1323 try!(space(&mut self.s));
1324 try!(self.print_block(&**blk));
1326 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1327 for ident in opt_ident.iter() {
1328 try!(self.print_ident(*ident));
1329 try!(self.word_space(":"));
1331 try!(self.head("for"));
1332 try!(self.print_pat(&**pat));
1333 try!(space(&mut self.s));
1334 try!(self.word_space("in"));
1335 try!(self.print_expr(&**iter));
1336 try!(space(&mut self.s));
1337 try!(self.print_block(&**blk));
1339 ast::ExprLoop(ref blk, opt_ident) => {
1340 for ident in opt_ident.iter() {
1341 try!(self.print_ident(*ident));
1342 try!(self.word_space(":"));
1344 try!(self.head("loop"));
1345 try!(space(&mut self.s));
1346 try!(self.print_block(&**blk));
1348 ast::ExprMatch(ref expr, ref arms) => {
1349 try!(self.cbox(indent_unit));
1351 try!(self.word_nbsp("match"));
1352 try!(self.print_expr(&**expr));
1353 try!(space(&mut self.s));
1355 let len = arms.len();
1356 for (i, arm) in arms.iter().enumerate() {
1357 // I have no idea why this check is necessary, but here it
1359 if arm.attrs.is_empty() {
1360 try!(space(&mut self.s));
1362 try!(self.cbox(indent_unit));
1363 try!(self.ibox(0u));
1364 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1365 let mut first = true;
1366 for p in arm.pats.iter() {
1370 try!(space(&mut self.s));
1371 try!(self.word_space("|"));
1373 try!(self.print_pat(&**p));
1375 try!(space(&mut self.s));
1378 try!(self.word_space("if"));
1379 try!(self.print_expr(&**e));
1380 try!(space(&mut self.s));
1384 try!(self.word_space("=>"));
1386 match arm.body.node {
1387 ast::ExprBlock(ref blk) => {
1388 // the block will close the pattern's ibox
1389 try!(self.print_block_unclosed_indent(&**blk,
1393 try!(self.end()); // close the ibox for the pattern
1394 try!(self.print_expr(&*arm.body));
1397 if !expr_is_simple_block(expr.clone())
1399 try!(word(&mut self.s, ","));
1401 try!(self.end()); // close enclosing cbox
1403 try!(self.bclose_(expr.span, indent_unit));
1405 ast::ExprFnBlock(ref decl, ref body) => {
1406 // in do/for blocks we don't want to show an empty
1407 // argument list, but at this point we don't know which
1410 // if !decl.inputs.is_empty() {
1411 try!(self.print_fn_block_args(&**decl));
1412 try!(space(&mut self.s));
1415 if !body.stmts.is_empty() || !body.expr.is_some() {
1416 try!(self.print_block_unclosed(&**body));
1418 // we extract the block, so as not to create another set of boxes
1419 match body.expr.unwrap().node {
1420 ast::ExprBlock(ref blk) => {
1421 try!(self.print_block_unclosed(&**blk));
1424 // this is a bare expression
1425 try!(self.print_expr(&*body.expr.unwrap()));
1426 try!(self.end()); // need to close a box
1430 // a box will be closed by print_expr, but we didn't want an overall
1431 // wrapper so we closed the corresponding opening. so create an
1432 // empty box to satisfy the close.
1435 ast::ExprProc(ref decl, ref body) => {
1436 // in do/for blocks we don't want to show an empty
1437 // argument list, but at this point we don't know which
1440 // if !decl.inputs.is_empty() {
1441 try!(self.print_proc_args(&**decl));
1442 try!(space(&mut self.s));
1444 assert!(body.stmts.is_empty());
1445 assert!(body.expr.is_some());
1446 // we extract the block, so as not to create another set of boxes
1447 match body.expr.unwrap().node {
1448 ast::ExprBlock(ref blk) => {
1449 try!(self.print_block_unclosed(&**blk));
1452 // this is a bare expression
1453 try!(self.print_expr(&*body.expr.unwrap()));
1454 try!(self.end()); // need to close a box
1457 // a box will be closed by print_expr, but we didn't want an overall
1458 // wrapper so we closed the corresponding opening. so create an
1459 // empty box to satisfy the close.
1462 ast::ExprBlock(ref blk) => {
1463 // containing cbox, will be closed by print-block at }
1464 try!(self.cbox(indent_unit));
1465 // head-box, will be closed by print-block after {
1466 try!(self.ibox(0u));
1467 try!(self.print_block(&**blk));
1469 ast::ExprAssign(ref lhs, ref rhs) => {
1470 try!(self.print_expr(&**lhs));
1471 try!(space(&mut self.s));
1472 try!(self.word_space("="));
1473 try!(self.print_expr(&**rhs));
1475 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1476 try!(self.print_expr(&**lhs));
1477 try!(space(&mut self.s));
1478 try!(word(&mut self.s, ast_util::binop_to_str(op)));
1479 try!(self.word_space("="));
1480 try!(self.print_expr(&**rhs));
1482 ast::ExprField(ref expr, id, ref tys) => {
1483 try!(self.print_expr(&**expr));
1484 try!(word(&mut self.s, "."));
1485 try!(self.print_ident(id));
1487 try!(word(&mut self.s, "::<"));
1489 Inconsistent, tys.as_slice(),
1490 |s, ty| s.print_type_ref(ty)));
1491 try!(word(&mut self.s, ">"));
1494 ast::ExprIndex(ref expr, ref index) => {
1495 try!(self.print_expr(&**expr));
1496 try!(word(&mut self.s, "["));
1497 try!(self.print_expr(&**index));
1498 try!(word(&mut self.s, "]"));
1500 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1501 ast::ExprBreak(opt_ident) => {
1502 try!(word(&mut self.s, "break"));
1503 try!(space(&mut self.s));
1504 for ident in opt_ident.iter() {
1505 try!(self.print_ident(*ident));
1506 try!(space(&mut self.s));
1509 ast::ExprAgain(opt_ident) => {
1510 try!(word(&mut self.s, "continue"));
1511 try!(space(&mut self.s));
1512 for ident in opt_ident.iter() {
1513 try!(self.print_ident(*ident));
1514 try!(space(&mut self.s))
1517 ast::ExprRet(ref result) => {
1518 try!(word(&mut self.s, "return"));
1521 try!(word(&mut self.s, " "));
1522 try!(self.print_expr(&**expr));
1527 ast::ExprInlineAsm(ref a) => {
1529 try!(word(&mut self.s, "__volatile__ asm!"));
1531 try!(word(&mut self.s, "asm!"));
1534 try!(self.print_string(a.asm.get(), a.asm_str_style));
1535 try!(self.word_space(":"));
1537 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1538 |s, &(ref co, ref o)| {
1539 try!(s.print_string(co.get(), ast::CookedStr));
1541 try!(s.print_expr(&**o));
1545 try!(space(&mut self.s));
1546 try!(self.word_space(":"));
1548 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1549 |s, &(ref co, ref o)| {
1550 try!(s.print_string(co.get(), ast::CookedStr));
1552 try!(s.print_expr(&**o));
1556 try!(space(&mut self.s));
1557 try!(self.word_space(":"));
1559 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1560 try!(self.pclose());
1562 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1563 ast::ExprParen(ref e) => {
1565 try!(self.print_expr(&**e));
1566 try!(self.pclose());
1569 try!(self.ann.post(self, NodeExpr(expr)));
1573 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1574 try!(self.print_pat(&*loc.pat));
1576 ast::TyInfer => Ok(()),
1578 try!(self.word_space(":"));
1579 self.print_type(&*loc.ty)
1584 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1585 try!(self.maybe_print_comment(decl.span.lo));
1587 ast::DeclLocal(ref loc) => {
1588 try!(self.space_if_not_bol());
1589 try!(self.ibox(indent_unit));
1590 try!(self.word_nbsp("let"));
1592 try!(self.ibox(indent_unit));
1593 try!(self.print_local_decl(&**loc));
1598 try!(self.word_space("="));
1599 try!(self.print_expr(&**init));
1605 ast::DeclItem(ref item) => self.print_item(&**item)
1609 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1610 word(&mut self.s, token::get_ident(ident).get())
1613 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1614 word(&mut self.s, token::get_name(name).get())
1617 pub fn print_for_decl(&mut self, loc: &ast::Local,
1618 coll: &ast::Expr) -> IoResult<()> {
1619 try!(self.print_local_decl(loc));
1620 try!(space(&mut self.s));
1621 try!(self.word_space("in"));
1622 self.print_expr(coll)
1625 fn print_path_(&mut self,
1627 colons_before_params: bool,
1628 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1630 try!(self.maybe_print_comment(path.span.lo));
1632 try!(word(&mut self.s, "::"));
1635 let mut first = true;
1636 for segment in path.segments.iter() {
1640 try!(word(&mut self.s, "::"))
1643 try!(self.print_ident(segment.identifier));
1645 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1646 if colons_before_params {
1647 try!(word(&mut self.s, "::"))
1649 try!(word(&mut self.s, "<"));
1651 let mut comma = false;
1652 for lifetime in segment.lifetimes.iter() {
1654 try!(self.word_space(","))
1656 try!(self.print_lifetime(lifetime));
1660 if !segment.types.is_empty() {
1662 try!(self.word_space(","))
1666 segment.types.as_slice(),
1667 |s, ty| s.print_type_ref(ty)));
1670 try!(word(&mut self.s, ">"))
1676 Some(ref bounds) => self.print_bounds(&None, bounds, true),
1680 fn print_path(&mut self, path: &ast::Path,
1681 colons_before_params: bool) -> IoResult<()> {
1682 self.print_path_(path, colons_before_params, &None)
1685 fn print_bounded_path(&mut self, path: &ast::Path,
1686 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1688 self.print_path_(path, false, bounds)
1691 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1692 try!(self.maybe_print_comment(pat.span.lo));
1693 try!(self.ann.pre(self, NodePat(pat)));
1694 /* Pat isn't normalized, but the beauty of it
1695 is that it doesn't matter */
1697 ast::PatWild => try!(word(&mut self.s, "_")),
1698 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1699 ast::PatIdent(binding_mode, ref path, sub) => {
1700 match binding_mode {
1701 ast::BindByRef(mutbl) => {
1702 try!(self.word_nbsp("ref"));
1703 try!(self.print_mutability(mutbl));
1705 ast::BindByValue(ast::MutImmutable) => {}
1706 ast::BindByValue(ast::MutMutable) => {
1707 try!(self.word_nbsp("mut"));
1710 try!(self.print_path(path, true));
1713 try!(word(&mut self.s, "@"));
1714 try!(self.print_pat(&**p));
1719 ast::PatEnum(ref path, ref args_) => {
1720 try!(self.print_path(path, true));
1722 None => try!(word(&mut self.s, "(..)")),
1724 if !args.is_empty() {
1726 try!(self.commasep(Inconsistent, args.as_slice(),
1727 |s, p| s.print_pat(&**p)));
1728 try!(self.pclose());
1733 ast::PatStruct(ref path, ref fields, etc) => {
1734 try!(self.print_path(path, true));
1735 try!(word(&mut self.s, "{"));
1736 try!(self.commasep_cmnt(
1737 Consistent, fields.as_slice(),
1739 try!(s.cbox(indent_unit));
1740 try!(s.print_ident(f.ident));
1741 try!(s.word_space(":"));
1742 try!(s.print_pat(&*f.pat));
1747 if fields.len() != 0u { try!(self.word_space(",")); }
1748 try!(word(&mut self.s, ".."));
1750 try!(word(&mut self.s, "}"));
1752 ast::PatTup(ref elts) => {
1754 try!(self.commasep(Inconsistent,
1756 |s, p| s.print_pat(&**p)));
1757 if elts.len() == 1 {
1758 try!(word(&mut self.s, ","));
1760 try!(self.pclose());
1762 ast::PatBox(ref inner) => {
1763 try!(word(&mut self.s, "box "));
1764 try!(self.print_pat(&**inner));
1766 ast::PatRegion(ref inner) => {
1767 try!(word(&mut self.s, "&"));
1768 try!(self.print_pat(&**inner));
1770 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1771 ast::PatRange(ref begin, ref end) => {
1772 try!(self.print_expr(&**begin));
1773 try!(space(&mut self.s));
1774 try!(word(&mut self.s, ".."));
1775 try!(self.print_expr(&**end));
1777 ast::PatVec(ref before, slice, ref after) => {
1778 try!(word(&mut self.s, "["));
1779 try!(self.commasep(Inconsistent,
1781 |s, p| s.print_pat(&**p)));
1782 for p in slice.iter() {
1783 if !before.is_empty() { try!(self.word_space(",")); }
1785 ast::Pat { node: ast::PatWildMulti, .. } => {
1786 // this case is handled by print_pat
1788 _ => try!(word(&mut self.s, "..")),
1790 try!(self.print_pat(&**p));
1791 if !after.is_empty() { try!(self.word_space(",")); }
1793 try!(self.commasep(Inconsistent,
1795 |s, p| s.print_pat(&**p)));
1796 try!(word(&mut self.s, "]"));
1798 ast::PatMac(ref m) => try!(self.print_mac(m)),
1800 self.ann.post(self, NodePat(pat))
1803 // Returns whether it printed anything
1804 fn print_explicit_self(&mut self,
1805 explicit_self: ast::ExplicitSelf_,
1806 mutbl: ast::Mutability) -> IoResult<bool> {
1807 try!(self.print_mutability(mutbl));
1808 match explicit_self {
1809 ast::SelfStatic => { return Ok(false); }
1811 try!(word(&mut self.s, "self"));
1814 try!(word(&mut self.s, "~self"));
1816 ast::SelfRegion(ref lt, m) => {
1817 try!(word(&mut self.s, "&"));
1818 try!(self.print_opt_lifetime(lt));
1819 try!(self.print_mutability(m));
1820 try!(word(&mut self.s, "self"));
1826 pub fn print_fn(&mut self,
1828 fn_style: Option<ast::FnStyle>,
1831 generics: &ast::Generics,
1832 opt_explicit_self: Option<ast::ExplicitSelf_>,
1833 vis: ast::Visibility) -> IoResult<()> {
1834 try!(self.head(""));
1835 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1837 try!(self.print_ident(name));
1838 try!(self.print_generics(generics));
1839 self.print_fn_args_and_ret(decl, opt_explicit_self)
1842 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1843 opt_explicit_self: Option<ast::ExplicitSelf_>)
1845 // It is unfortunate to duplicate the commasep logic, but we want the
1846 // self type and the args all in the same box.
1847 try!(self.rbox(0u, Inconsistent));
1848 let mut first = true;
1849 for &explicit_self in opt_explicit_self.iter() {
1850 let m = match explicit_self {
1851 ast::SelfStatic => ast::MutImmutable,
1852 _ => match decl.inputs.get(0).pat.node {
1853 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1854 _ => ast::MutImmutable
1857 first = !try!(self.print_explicit_self(explicit_self, m));
1860 // HACK(eddyb) ignore the separately printed self argument.
1861 let args = if first {
1862 decl.inputs.as_slice()
1864 decl.inputs.slice_from(1)
1867 for arg in args.iter() {
1868 if first { first = false; } else { try!(self.word_space(",")); }
1869 try!(self.print_arg(arg));
1875 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1876 opt_explicit_self: Option<ast::ExplicitSelf_>)
1879 try!(self.print_fn_args(decl, opt_explicit_self));
1881 try!(word(&mut self.s, ", ..."));
1883 try!(self.pclose());
1885 try!(self.maybe_print_comment(decl.output.span.lo));
1886 match decl.output.node {
1887 ast::TyNil => Ok(()),
1889 try!(self.space_if_not_bol());
1890 try!(self.word_space("->"));
1891 self.print_type(&*decl.output)
1896 pub fn print_fn_block_args(&mut self,
1897 decl: &ast::FnDecl) -> IoResult<()> {
1898 try!(word(&mut self.s, "|"));
1899 try!(self.print_fn_args(decl, None));
1900 try!(word(&mut self.s, "|"));
1902 match decl.output.node {
1905 try!(self.space_if_not_bol());
1906 try!(self.word_space("->"));
1907 try!(self.print_type(&*decl.output));
1911 self.maybe_print_comment(decl.output.span.lo)
1914 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1915 try!(word(&mut self.s, "proc"));
1916 try!(word(&mut self.s, "("));
1917 try!(self.print_fn_args(decl, None));
1918 try!(word(&mut self.s, ")"));
1920 match decl.output.node {
1923 try!(self.space_if_not_bol());
1924 try!(self.word_space("->"));
1925 try!(self.print_type(&*decl.output));
1929 self.maybe_print_comment(decl.output.span.lo)
1932 pub fn print_bounds(&mut self,
1933 region: &Option<ast::Lifetime>,
1934 bounds: &OwnedSlice<ast::TyParamBound>,
1935 print_colon_anyway: bool) -> IoResult<()> {
1936 if !bounds.is_empty() || region.is_some() {
1937 try!(word(&mut self.s, ":"));
1938 let mut first = true;
1941 let token = token::get_name(lt.name);
1942 if token.get() != "'static" {
1945 try!(self.print_lifetime(lt));
1950 for bound in bounds.iter() {
1955 try!(self.word_space("+"));
1959 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
1960 StaticRegionTyParamBound => word(&mut self.s, "'static"),
1961 UnboxedFnTyParamBound(ref unboxed_function_type) => {
1962 self.print_ty_fn(None,
1967 &*unboxed_function_type.decl,
1974 OtherRegionTyParamBound(_) => Ok(())
1978 } else if print_colon_anyway {
1979 word(&mut self.s, ":")
1985 pub fn print_lifetime(&mut self,
1986 lifetime: &ast::Lifetime) -> IoResult<()> {
1987 self.print_name(lifetime.name)
1990 pub fn print_generics(&mut self,
1991 generics: &ast::Generics) -> IoResult<()> {
1992 let total = generics.lifetimes.len() + generics.ty_params.len();
1994 try!(word(&mut self.s, "<"));
1996 let mut ints = Vec::new();
1997 for i in range(0u, total) {
2002 Inconsistent, ints.as_slice(),
2004 if idx < generics.lifetimes.len() {
2005 let lifetime = generics.lifetimes.get(idx);
2006 s.print_lifetime(lifetime)
2008 let idx = idx - generics.lifetimes.len();
2009 let param = generics.ty_params.get(idx);
2010 if param.sized == ast::DynSize {
2011 try!(s.word_space("type"));
2013 try!(s.print_ident(param.ident));
2014 try!(s.print_bounds(&None, ¶m.bounds, false));
2015 match param.default {
2016 Some(ref default) => {
2017 try!(space(&mut s.s));
2018 try!(s.word_space("="));
2019 s.print_type(&**default)
2025 word(&mut self.s, ">")
2031 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2032 try!(self.ibox(indent_unit));
2034 ast::MetaWord(ref name) => {
2035 try!(word(&mut self.s, name.get()));
2037 ast::MetaNameValue(ref name, ref value) => {
2038 try!(self.word_space(name.get()));
2039 try!(self.word_space("="));
2040 try!(self.print_literal(value));
2042 ast::MetaList(ref name, ref items) => {
2043 try!(word(&mut self.s, name.get()));
2045 try!(self.commasep(Consistent,
2047 |s, i| s.print_meta_item(&**i)));
2048 try!(self.pclose());
2054 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2056 ast::ViewPathSimple(ident, ref path, _) => {
2057 // FIXME(#6993) can't compare identifiers directly here
2058 if path.segments.last().unwrap().identifier.name != ident.name {
2059 try!(self.print_ident(ident));
2060 try!(space(&mut self.s));
2061 try!(self.word_space("="));
2063 self.print_path(path, false)
2066 ast::ViewPathGlob(ref path, _) => {
2067 try!(self.print_path(path, false));
2068 word(&mut self.s, "::*")
2071 ast::ViewPathList(ref path, ref idents, _) => {
2072 if path.segments.is_empty() {
2073 try!(word(&mut self.s, "{"));
2075 try!(self.print_path(path, false));
2076 try!(word(&mut self.s, "::{"));
2078 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2079 s.print_ident(w.node.name)
2081 word(&mut self.s, "}")
2086 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2087 try!(self.hardbreak_if_not_bol());
2088 try!(self.maybe_print_comment(item.span.lo));
2089 try!(self.print_outer_attributes(item.attrs.as_slice()));
2090 try!(self.print_visibility(item.vis));
2092 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2093 try!(self.head("extern crate"));
2094 try!(self.print_ident(id));
2095 for &(ref p, style) in optional_path.iter() {
2096 try!(space(&mut self.s));
2097 try!(word(&mut self.s, "="));
2098 try!(space(&mut self.s));
2099 try!(self.print_string(p.get(), style));
2103 ast::ViewItemUse(ref vp) => {
2104 try!(self.head("use"));
2105 try!(self.print_view_path(&**vp));
2108 try!(word(&mut self.s, ";"));
2109 try!(self.end()); // end inner head-block
2110 self.end() // end outer head-block
2113 pub fn print_mutability(&mut self,
2114 mutbl: ast::Mutability) -> IoResult<()> {
2116 ast::MutMutable => self.word_nbsp("mut"),
2117 ast::MutImmutable => Ok(()),
2121 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2122 try!(self.print_mutability(mt.mutbl));
2123 self.print_type(&*mt.ty)
2126 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2127 try!(self.ibox(indent_unit));
2128 match input.ty.node {
2129 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2131 match input.pat.node {
2132 ast::PatIdent(_, ref path, _) if
2133 path.segments.len() == 1 &&
2134 path.segments.get(0).identifier.name ==
2135 parse::token::special_idents::invalid.name => {
2139 try!(self.print_pat(&*input.pat));
2140 try!(word(&mut self.s, ":"));
2141 try!(space(&mut self.s));
2144 try!(self.print_type(&*input.ty));
2150 pub fn print_ty_fn(&mut self,
2151 opt_abi: Option<abi::Abi>,
2152 opt_sigil: Option<char>,
2153 opt_region: &Option<ast::Lifetime>,
2154 fn_style: ast::FnStyle,
2155 onceness: ast::Onceness,
2157 id: Option<ast::Ident>,
2158 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2159 generics: Option<&ast::Generics>,
2160 opt_explicit_self: Option<ast::ExplicitSelf_>,
2163 try!(self.ibox(indent_unit));
2165 // Duplicates the logic in `print_fn_header_info()`. This is because that
2166 // function prints the sigil in the wrong place. That should be fixed.
2167 if opt_sigil == Some('~') && onceness == ast::Once {
2168 try!(word(&mut self.s, "proc"));
2169 } else if opt_sigil == Some('&') {
2170 try!(self.print_fn_style(fn_style));
2171 try!(self.print_extern_opt_abi(opt_abi));
2172 try!(self.print_onceness(onceness));
2174 assert!(opt_sigil.is_none());
2175 try!(self.print_fn_style(fn_style));
2176 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2177 try!(self.print_onceness(onceness));
2179 try!(word(&mut self.s, "fn"));
2185 try!(word(&mut self.s, " "));
2186 try!(self.print_ident(id));
2191 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2192 try!(zerobreak(&mut self.s));
2194 if is_unboxed || opt_sigil == Some('&') {
2195 try!(word(&mut self.s, "|"));
2201 try!(word(&mut self.s, "&mut"));
2202 try!(self.word_space(":"));
2205 try!(self.print_fn_args(decl, opt_explicit_self));
2207 if is_unboxed || opt_sigil == Some('&') {
2208 try!(word(&mut self.s, "|"));
2211 try!(word(&mut self.s, ", ..."));
2213 try!(self.pclose());
2216 opt_bounds.as_ref().map(|bounds| {
2217 self.print_bounds(opt_region, bounds, true)
2220 try!(self.maybe_print_comment(decl.output.span.lo));
2222 match decl.output.node {
2225 try!(self.space_if_not_bol());
2226 try!(self.ibox(indent_unit));
2227 try!(self.word_space("->"));
2228 if decl.cf == ast::NoReturn {
2229 try!(self.word_nbsp("!"));
2231 try!(self.print_type(&*decl.output));
2240 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2241 next_pos: Option<BytePos>)
2243 let cm = match self.cm {
2247 match self.next_comment() {
2249 if (*cmnt).style != comments::Trailing { return Ok(()) }
2250 let span_line = cm.lookup_char_pos(span.hi);
2251 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2252 let mut next = (*cmnt).pos + BytePos(1);
2253 match next_pos { None => (), Some(p) => next = p }
2254 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2255 span_line.line == comment_line.line {
2256 try!(self.print_comment(cmnt));
2257 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2265 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2266 // If there aren't any remaining comments, then we need to manually
2267 // make sure there is a line break at the end.
2268 if self.next_comment().is_none() {
2269 try!(hardbreak(&mut self.s));
2272 match self.next_comment() {
2274 try!(self.print_comment(cmnt));
2275 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2283 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2284 try!(self.maybe_print_comment(lit.span.lo));
2285 match self.next_lit(lit.span.lo) {
2287 return word(&mut self.s, (*ltrl).lit.as_slice());
2292 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2293 ast::LitChar(ch) => {
2294 let mut res = String::from_str("'");
2295 ch.escape_default(|c| res.push_char(c));
2296 res.push_char('\'');
2297 word(&mut self.s, res.as_slice())
2299 ast::LitInt(i, t) => {
2301 ast_util::int_ty_to_str(t, Some(i),
2302 ast_util::AutoSuffix).as_slice())
2304 ast::LitUint(u, t) => {
2306 ast_util::uint_ty_to_str(t, Some(u),
2307 ast_util::ForceSuffix).as_slice())
2309 ast::LitIntUnsuffixed(i) => {
2310 word(&mut self.s, format!("{}", i).as_slice())
2312 ast::LitFloat(ref f, t) => {
2317 ast_util::float_ty_to_str(t).as_slice()).as_slice())
2319 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2320 ast::LitNil => word(&mut self.s, "()"),
2321 ast::LitBool(val) => {
2322 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2324 ast::LitBinary(ref arr) => {
2325 try!(self.ibox(indent_unit));
2326 try!(word(&mut self.s, "["));
2327 try!(self.commasep_cmnt(Inconsistent,
2335 try!(word(&mut self.s, "]"));
2341 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2342 match self.literals {
2344 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2345 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2346 if ltrl.pos > pos { return None; }
2347 self.cur_cmnt_and_lit.cur_lit += 1u;
2348 if ltrl.pos == pos { return Some(ltrl); }
2356 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2358 match self.next_comment() {
2360 if (*cmnt).pos < pos {
2361 try!(self.print_comment(cmnt));
2362 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2371 pub fn print_comment(&mut self,
2372 cmnt: &comments::Comment) -> IoResult<()> {
2374 comments::Mixed => {
2375 assert_eq!(cmnt.lines.len(), 1u);
2376 try!(zerobreak(&mut self.s));
2377 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2378 zerobreak(&mut self.s)
2380 comments::Isolated => {
2381 try!(self.hardbreak_if_not_bol());
2382 for line in cmnt.lines.iter() {
2383 // Don't print empty lines because they will end up as trailing
2385 if !line.is_empty() {
2386 try!(word(&mut self.s, line.as_slice()));
2388 try!(hardbreak(&mut self.s));
2392 comments::Trailing => {
2393 try!(word(&mut self.s, " "));
2394 if cmnt.lines.len() == 1u {
2395 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2396 hardbreak(&mut self.s)
2398 try!(self.ibox(0u));
2399 for line in cmnt.lines.iter() {
2400 if !line.is_empty() {
2401 try!(word(&mut self.s, line.as_slice()));
2403 try!(hardbreak(&mut self.s));
2408 comments::BlankLine => {
2409 // We need to do at least one, possibly two hardbreaks.
2410 let is_semi = match self.s.last_token() {
2411 pp::String(s, _) => ";" == s.as_slice(),
2414 if is_semi || self.is_begin() || self.is_end() {
2415 try!(hardbreak(&mut self.s));
2417 hardbreak(&mut self.s)
2422 pub fn print_string(&mut self, st: &str,
2423 style: ast::StrStyle) -> IoResult<()> {
2424 let st = match style {
2426 (format!("\"{}\"", st.escape_default()))
2429 (format!("r{delim}\"{string}\"{delim}",
2430 delim="#".repeat(n),
2434 word(&mut self.s, st.as_slice())
2437 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2438 match self.comments {
2439 Some(ref cmnts) => {
2440 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2441 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2450 pub fn print_opt_fn_style(&mut self,
2451 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2452 match opt_fn_style {
2453 Some(fn_style) => self.print_fn_style(fn_style),
2458 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2459 opt_abi: Option<abi::Abi>)
2462 Some(abi::Rust) => Ok(()),
2464 try!(self.word_nbsp("extern"));
2465 self.word_nbsp(abi.to_str().as_slice())
2471 pub fn print_extern_opt_abi(&mut self,
2472 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2475 try!(self.word_nbsp("extern"));
2476 self.word_nbsp(abi.to_str().as_slice())
2482 pub fn print_fn_header_info(&mut self,
2483 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2484 opt_fn_style: Option<ast::FnStyle>,
2486 vis: ast::Visibility) -> IoResult<()> {
2487 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2488 try!(self.print_opt_fn_style(opt_fn_style));
2490 if abi != abi::Rust {
2491 try!(self.word_nbsp("extern"));
2492 try!(self.word_nbsp(abi.to_str().as_slice()));
2495 word(&mut self.s, "fn")
2498 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2500 ast::NormalFn => Ok(()),
2501 ast::UnsafeFn => self.word_nbsp("unsafe"),
2505 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2507 ast::Once => self.word_nbsp("once"),
2523 fn test_fun_to_str() {
2524 let abba_ident = token::str_to_ident("abba");
2526 let decl = ast::FnDecl {
2528 output: ast::P(ast::Ty {id: 0,
2530 span: codemap::DUMMY_SP}),
2534 let generics = ast_util::empty_generics();
2535 assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2537 &"fn abba()".to_string());
2541 fn test_variant_to_str() {
2542 let ident = token::str_to_ident("principal_skinner");
2544 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2547 // making this up as I go.... ?
2548 kind: ast::TupleVariantKind(Vec::new()),
2554 let varstr = variant_to_str(&var);
2555 assert_eq!(&varstr,&"pub principal_skinner".to_string());