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 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};
29 use std::io::{IoResult, MemWriter};
33 use std::string::String;
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: &[@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, "!")),
468 try!(word(&mut self.s, "@"));
469 try!(self.print_type(ty));
472 try!(word(&mut self.s, "~"));
473 try!(self.print_type(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,
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(ty, 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(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<()> {
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(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(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(ty, m, 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(decl, fn_style, abi, ref typarams, 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(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(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, item.span));
702 ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
703 try!(self.head(visibility_qualified(item.vis,
704 "impl").as_slice()));
705 if generics.is_parameterized() {
706 try!(self.print_generics(generics));
707 try!(space(&mut self.s));
712 try!(self.print_trait_ref(t));
713 try!(space(&mut self.s));
714 try!(self.word_space("for"));
719 try!(self.print_type(ty));
721 try!(space(&mut self.s));
723 try!(self.print_inner_attributes(item.attrs.as_slice()));
724 for meth in methods.iter() {
725 try!(self.print_method(*meth));
727 try!(self.bclose(item.span));
729 ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => {
730 try!(self.head(visibility_qualified(item.vis,
731 "trait").as_slice()));
732 try!(self.print_ident(item.ident));
733 try!(self.print_generics(generics));
734 if *sized == ast::DynSize {
735 try!(space(&mut self.s));
736 try!(word(&mut self.s, "for type"));
738 if traits.len() != 0u {
739 try!(word(&mut self.s, ":"));
740 for (i, trait_) in traits.iter().enumerate() {
743 try!(self.word_space("+"));
745 try!(self.print_path(&trait_.path, false));
748 try!(word(&mut self.s, " "));
750 for meth in methods.iter() {
751 try!(self.print_trait_method(meth));
753 try!(self.bclose(item.span));
755 // I think it's reasonable to hide the context here:
756 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
758 try!(self.print_visibility(item.vis));
759 try!(self.print_path(pth, false));
760 try!(word(&mut self.s, "! "));
761 try!(self.print_ident(item.ident));
762 try!(self.cbox(indent_unit));
764 try!(self.print_tts(tts.as_slice()));
769 self.ann.post(self, NodeItem(item))
772 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
773 self.print_path(&t.path, false)
776 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
777 generics: &ast::Generics, ident: ast::Ident,
779 visibility: ast::Visibility) -> IoResult<()> {
780 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
781 try!(self.print_ident(ident));
782 try!(self.print_generics(generics));
783 try!(space(&mut self.s));
784 self.print_variants(enum_definition.variants.as_slice(), span)
787 pub fn print_variants(&mut self,
788 variants: &[P<ast::Variant>],
789 span: codemap::Span) -> IoResult<()> {
791 for &v in variants.iter() {
792 try!(self.space_if_not_bol());
793 try!(self.maybe_print_comment(v.span.lo));
794 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
795 try!(self.ibox(indent_unit));
796 try!(self.print_variant(v));
797 try!(word(&mut self.s, ","));
799 try!(self.maybe_print_trailing_comment(v.span, None));
804 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
806 ast::Public => self.word_nbsp("pub"),
807 ast::Inherited => Ok(())
811 pub fn print_struct(&mut self,
812 struct_def: &ast::StructDef,
813 generics: &ast::Generics,
815 span: codemap::Span) -> IoResult<()> {
816 try!(self.print_ident(ident));
817 try!(self.print_generics(generics));
818 match struct_def.super_struct {
820 try!(self.word_space(":"));
821 try!(self.print_type(t));
825 if ast_util::struct_def_is_tuple_like(struct_def) {
826 if !struct_def.fields.is_empty() {
829 Inconsistent, struct_def.fields.as_slice(),
831 match field.node.kind {
832 ast::NamedField(..) => fail!("unexpected named field"),
833 ast::UnnamedField(vis) => {
834 try!(s.print_visibility(vis));
835 try!(s.maybe_print_comment(field.span.lo));
836 s.print_type(field.node.ty)
843 try!(word(&mut self.s, ";"));
845 self.end() // close the outer-box
849 try!(self.hardbreak_if_not_bol());
851 for field in struct_def.fields.iter() {
852 match field.node.kind {
853 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
854 ast::NamedField(ident, visibility) => {
855 try!(self.hardbreak_if_not_bol());
856 try!(self.maybe_print_comment(field.span.lo));
857 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
858 try!(self.print_visibility(visibility));
859 try!(self.print_ident(ident));
860 try!(self.word_nbsp(":"));
861 try!(self.print_type(field.node.ty));
862 try!(word(&mut self.s, ","));
871 /// This doesn't deserve to be called "pretty" printing, but it should be
872 /// meaning-preserving. A quick hack that might help would be to look at the
873 /// spans embedded in the TTs to decide where to put spaces and newlines.
874 /// But it'd be better to parse these according to the grammar of the
875 /// appropriate macro, transcribe back into the grammar we just parsed from,
876 /// and then pretty-print the resulting AST nodes (so, e.g., we print
877 /// expression arguments as expressions). It can be done! I think.
878 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
880 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
881 ast::TTTok(_, ref tk) => {
882 try!(word(&mut self.s, parse::token::to_str(tk).as_slice()));
884 parse::token::DOC_COMMENT(..) => {
885 hardbreak(&mut self.s)
890 ast::TTSeq(_, ref tts, ref sep, zerok) => {
891 try!(word(&mut self.s, "$("));
892 for tt_elt in (*tts).iter() {
893 try!(self.print_tt(tt_elt));
895 try!(word(&mut self.s, ")"));
898 try!(word(&mut self.s,
899 parse::token::to_str(tk).as_slice()));
903 word(&mut self.s, if zerok { "*" } else { "+" })
905 ast::TTNonterminal(_, name) => {
906 try!(word(&mut self.s, "$"));
907 self.print_ident(name)
912 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
914 for (i, tt) in tts.iter().enumerate() {
916 try!(space(&mut self.s));
918 try!(self.print_tt(tt));
923 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
924 try!(self.print_visibility(v.node.vis));
926 ast::TupleVariantKind(ref args) => {
927 try!(self.print_ident(v.node.name));
928 if !args.is_empty() {
930 try!(self.commasep(Consistent,
932 |s, arg| s.print_type(arg.ty)));
936 ast::StructVariantKind(struct_def) => {
938 let generics = ast_util::empty_generics();
939 try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
942 match v.node.disr_expr {
944 try!(space(&mut self.s));
945 try!(self.word_space("="));
952 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
953 try!(self.hardbreak_if_not_bol());
954 try!(self.maybe_print_comment(m.span.lo));
955 try!(self.print_outer_attributes(m.attrs.as_slice()));
956 try!(self.print_ty_fn(None,
965 Some(m.explicit_self.node),
967 word(&mut self.s, ";")
970 pub fn print_trait_method(&mut self,
971 m: &ast::TraitMethod) -> IoResult<()> {
973 Required(ref ty_m) => self.print_ty_method(ty_m),
974 Provided(m) => self.print_method(m)
978 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
979 try!(self.hardbreak_if_not_bol());
980 try!(self.maybe_print_comment(meth.span.lo));
981 try!(self.print_outer_attributes(meth.attrs.as_slice()));
982 try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
983 meth.ident, &meth.generics, Some(meth.explicit_self.node),
985 try!(word(&mut self.s, " "));
986 self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
989 pub fn print_outer_attributes(&mut self,
990 attrs: &[ast::Attribute]) -> IoResult<()> {
992 for attr in attrs.iter() {
993 match attr.node.style {
995 try!(self.print_attribute(attr));
998 _ => {/* fallthrough */ }
1002 try!(self.hardbreak_if_not_bol());
1007 pub fn print_inner_attributes(&mut self,
1008 attrs: &[ast::Attribute]) -> IoResult<()> {
1010 for attr in attrs.iter() {
1011 match attr.node.style {
1013 try!(self.print_attribute(attr));
1016 _ => {/* fallthrough */ }
1020 try!(self.hardbreak_if_not_bol());
1025 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1026 try!(self.hardbreak_if_not_bol());
1027 try!(self.maybe_print_comment(attr.span.lo));
1028 if attr.node.is_sugared_doc {
1029 word(&mut self.s, attr.value_str().unwrap().get())
1031 match attr.node.style {
1032 ast::AttrInner => try!(word(&mut self.s, "#![")),
1033 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1035 try!(self.print_meta_item(attr.meta()));
1036 word(&mut self.s, "]")
1041 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1042 try!(self.maybe_print_comment(st.span.lo));
1044 ast::StmtDecl(decl, _) => {
1045 try!(self.print_decl(decl));
1047 ast::StmtExpr(expr, _) => {
1048 try!(self.space_if_not_bol());
1049 try!(self.print_expr(expr));
1051 ast::StmtSemi(expr, _) => {
1052 try!(self.space_if_not_bol());
1053 try!(self.print_expr(expr));
1054 try!(word(&mut self.s, ";"));
1056 ast::StmtMac(ref mac, semi) => {
1057 try!(self.space_if_not_bol());
1058 try!(self.print_mac(mac));
1060 try!(word(&mut self.s, ";"));
1064 if parse::classify::stmt_ends_with_semi(st) {
1065 try!(word(&mut self.s, ";"));
1067 self.maybe_print_trailing_comment(st.span, None)
1070 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1071 self.print_block_with_attrs(blk, &[])
1074 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1075 self.print_block_unclosed_indent(blk, indent_unit)
1078 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1079 indented: uint) -> IoResult<()> {
1080 self.print_block_maybe_unclosed(blk, indented, &[], false)
1083 pub fn print_block_with_attrs(&mut self,
1085 attrs: &[ast::Attribute]) -> IoResult<()> {
1086 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1089 pub fn print_block_maybe_unclosed(&mut self,
1092 attrs: &[ast::Attribute],
1093 close_box: bool) -> IoResult<()> {
1095 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1096 ast::DefaultBlock => ()
1098 try!(self.maybe_print_comment(blk.span.lo));
1099 try!(self.ann.pre(self, NodeBlock(blk)));
1102 try!(self.print_inner_attributes(attrs));
1104 for vi in blk.view_items.iter() {
1105 try!(self.print_view_item(vi));
1107 for st in blk.stmts.iter() {
1108 try!(self.print_stmt(*st));
1112 try!(self.space_if_not_bol());
1113 try!(self.print_expr(expr));
1114 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1118 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1119 self.ann.post(self, NodeBlock(blk))
1122 fn print_else(&mut self, els: Option<@ast::Expr>) -> IoResult<()> {
1126 // "another else-if"
1127 ast::ExprIf(i, t, e) => {
1128 try!(self.cbox(indent_unit - 1u));
1129 try!(self.ibox(0u));
1130 try!(word(&mut self.s, " else if "));
1131 try!(self.print_expr(i));
1132 try!(space(&mut self.s));
1133 try!(self.print_block(t));
1137 ast::ExprBlock(b) => {
1138 try!(self.cbox(indent_unit - 1u));
1139 try!(self.ibox(0u));
1140 try!(word(&mut self.s, " else "));
1143 // BLEAH, constraints would be great here
1145 fail!("print_if saw if with weird alternative");
1153 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1154 elseopt: Option<@ast::Expr>, chk: bool) -> IoResult<()> {
1155 try!(self.head("if"));
1156 if chk { try!(self.word_nbsp("check")); }
1157 try!(self.print_expr(test));
1158 try!(space(&mut self.s));
1159 try!(self.print_block(blk));
1160 self.print_else(elseopt)
1163 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1165 // I think it's reasonable to hide the ctxt here:
1166 ast::MacInvocTT(ref pth, ref tts, _) => {
1167 try!(self.print_path(pth, false));
1168 try!(word(&mut self.s, "!"));
1170 try!(self.print_tts(tts.as_slice()));
1176 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1178 ast::ExprVstoreUniq => word(&mut self.s, "box "),
1179 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1180 ast::ExprVstoreMutSlice => {
1181 try!(word(&mut self.s, "&"));
1182 word(&mut self.s, "mut")
1187 fn print_call_post(&mut self, args: &[@ast::Expr]) -> IoResult<()> {
1189 try!(self.commasep_exprs(Inconsistent, args));
1193 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1194 let needs_par = needs_parentheses(expr);
1198 try!(self.print_expr(expr));
1200 try!(self.pclose());
1205 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1206 try!(self.maybe_print_comment(expr.span.lo));
1207 try!(self.ibox(indent_unit));
1208 try!(self.ann.pre(self, NodeExpr(expr)));
1210 ast::ExprVstore(e, v) => {
1211 try!(self.print_expr_vstore(v));
1212 try!(self.print_expr(e));
1214 ast::ExprBox(p, e) => {
1215 try!(word(&mut self.s, "box"));
1216 try!(word(&mut self.s, "("));
1217 try!(self.print_expr(p));
1218 try!(self.word_space(")"));
1219 try!(self.print_expr(e));
1221 ast::ExprVec(ref exprs) => {
1222 try!(self.ibox(indent_unit));
1223 try!(word(&mut self.s, "["));
1224 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1225 try!(word(&mut self.s, "]"));
1229 ast::ExprRepeat(element, count) => {
1230 try!(self.ibox(indent_unit));
1231 try!(word(&mut self.s, "["));
1232 try!(self.print_expr(element));
1233 try!(word(&mut self.s, ","));
1234 try!(word(&mut self.s, ".."));
1235 try!(self.print_expr(count));
1236 try!(word(&mut self.s, "]"));
1240 ast::ExprStruct(ref path, ref fields, wth) => {
1241 try!(self.print_path(path, true));
1242 try!(word(&mut self.s, "{"));
1243 try!(self.commasep_cmnt(
1247 try!(s.ibox(indent_unit));
1248 try!(s.print_ident(field.ident.node));
1249 try!(s.word_space(":"));
1250 try!(s.print_expr(field.expr));
1256 try!(self.ibox(indent_unit));
1257 if !fields.is_empty() {
1258 try!(word(&mut self.s, ","));
1259 try!(space(&mut self.s));
1261 try!(word(&mut self.s, ".."));
1262 try!(self.print_expr(expr));
1265 _ => try!(word(&mut self.s, ","))
1267 try!(word(&mut self.s, "}"));
1269 ast::ExprTup(ref exprs) => {
1271 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1272 if exprs.len() == 1 {
1273 try!(word(&mut self.s, ","));
1275 try!(self.pclose());
1277 ast::ExprCall(func, ref args) => {
1278 try!(self.print_expr_maybe_paren(func));
1279 try!(self.print_call_post(args.as_slice()));
1281 ast::ExprMethodCall(ident, ref tys, ref args) => {
1282 let base_args = args.slice_from(1);
1283 try!(self.print_expr(*args.get(0)));
1284 try!(word(&mut self.s, "."));
1285 try!(self.print_ident(ident.node));
1287 try!(word(&mut self.s, "::<"));
1288 try!(self.commasep(Inconsistent, tys.as_slice(),
1289 |s, ty| s.print_type_ref(ty)));
1290 try!(word(&mut self.s, ">"));
1292 try!(self.print_call_post(base_args));
1294 ast::ExprBinary(op, lhs, rhs) => {
1295 try!(self.print_expr(lhs));
1296 try!(space(&mut self.s));
1297 try!(self.word_space(ast_util::binop_to_str(op)));
1298 try!(self.print_expr(rhs));
1300 ast::ExprUnary(op, expr) => {
1301 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1302 try!(self.print_expr_maybe_paren(expr));
1304 ast::ExprAddrOf(m, expr) => {
1305 try!(word(&mut self.s, "&"));
1306 try!(self.print_mutability(m));
1307 try!(self.print_expr_maybe_paren(expr));
1309 ast::ExprLit(lit) => try!(self.print_literal(lit)),
1310 ast::ExprCast(expr, ty) => {
1311 try!(self.print_expr(expr));
1312 try!(space(&mut self.s));
1313 try!(self.word_space("as"));
1314 try!(self.print_type(ty));
1316 ast::ExprIf(test, blk, elseopt) => {
1317 try!(self.print_if(test, blk, elseopt, false));
1319 ast::ExprWhile(test, blk) => {
1320 try!(self.head("while"));
1321 try!(self.print_expr(test));
1322 try!(space(&mut self.s));
1323 try!(self.print_block(blk));
1325 ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1326 for ident in opt_ident.iter() {
1327 try!(word(&mut self.s, "'"));
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(blk, opt_ident) => {
1340 for ident in opt_ident.iter() {
1341 try!(word(&mut self.s, "'"));
1342 try!(self.print_ident(*ident));
1343 try!(self.word_space(":"));
1345 try!(self.head("loop"));
1346 try!(space(&mut self.s));
1347 try!(self.print_block(blk));
1349 ast::ExprMatch(expr, ref arms) => {
1350 try!(self.cbox(indent_unit));
1352 try!(self.word_nbsp("match"));
1353 try!(self.print_expr(expr));
1354 try!(space(&mut self.s));
1356 let len = arms.len();
1357 for (i, arm) in arms.iter().enumerate() {
1358 // I have no idea why this check is necessary, but here it
1360 if arm.attrs.is_empty() {
1361 try!(space(&mut self.s));
1363 try!(self.cbox(indent_unit));
1364 try!(self.ibox(0u));
1365 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1366 let mut first = true;
1367 for p in arm.pats.iter() {
1371 try!(space(&mut self.s));
1372 try!(self.word_space("|"));
1374 try!(self.print_pat(*p));
1376 try!(space(&mut self.s));
1379 try!(self.word_space("if"));
1380 try!(self.print_expr(e));
1381 try!(space(&mut self.s));
1385 try!(self.word_space("=>"));
1387 match arm.body.node {
1388 ast::ExprBlock(blk) => {
1389 // the block will close the pattern's ibox
1390 try!(self.print_block_unclosed_indent(blk, indent_unit));
1393 try!(self.end()); // close the ibox for the pattern
1394 try!(self.print_expr(arm.body));
1397 if !expr_is_simple_block(expr)
1399 try!(word(&mut self.s, ","));
1401 try!(self.end()); // close enclosing cbox
1403 try!(self.bclose_(expr.span, indent_unit));
1405 ast::ExprFnBlock(decl, 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(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(decl, 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(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(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(lhs, 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, lhs, 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(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(expr, 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!(word(&mut self.s, "'"));
1506 try!(self.print_ident(*ident));
1507 try!(space(&mut self.s));
1510 ast::ExprAgain(opt_ident) => {
1511 try!(word(&mut self.s, "continue"));
1512 try!(space(&mut self.s));
1513 for ident in opt_ident.iter() {
1514 try!(word(&mut self.s, "'"));
1515 try!(self.print_ident(*ident));
1516 try!(space(&mut self.s))
1519 ast::ExprRet(result) => {
1520 try!(word(&mut self.s, "return"));
1523 try!(word(&mut self.s, " "));
1524 try!(self.print_expr(expr));
1529 ast::ExprInlineAsm(ref a) => {
1531 try!(word(&mut self.s, "__volatile__ asm!"));
1533 try!(word(&mut self.s, "asm!"));
1536 try!(self.print_string(a.asm.get(), a.asm_str_style));
1537 try!(self.word_space(":"));
1539 try!(self.commasep(Inconsistent, a.outputs.as_slice(), |s, &(ref co, o)| {
1540 try!(s.print_string(co.get(), ast::CookedStr));
1542 try!(s.print_expr(o));
1546 try!(space(&mut self.s));
1547 try!(self.word_space(":"));
1549 try!(self.commasep(Inconsistent, a.inputs.as_slice(), |s, &(ref co, 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(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(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(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(inner) => {
1763 try!(word(&mut self.s, "box "));
1764 try!(self.print_pat(inner));
1766 ast::PatRegion(inner) => {
1767 try!(word(&mut self.s, "&"));
1768 try!(self.print_pat(inner));
1770 ast::PatLit(e) => try!(self.print_expr(e)),
1771 ast::PatRange(begin, 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 try!(word(&mut self.s, "'"));
1988 self.print_name(lifetime.name)
1991 pub fn print_generics(&mut self,
1992 generics: &ast::Generics) -> IoResult<()> {
1993 let total = generics.lifetimes.len() + generics.ty_params.len();
1995 try!(word(&mut self.s, "<"));
1997 let mut ints = Vec::new();
1998 for i in range(0u, total) {
2003 Inconsistent, ints.as_slice(),
2005 if idx < generics.lifetimes.len() {
2006 let lifetime = generics.lifetimes.get(idx);
2007 s.print_lifetime(lifetime)
2009 let idx = idx - generics.lifetimes.len();
2010 let param = generics.ty_params.get(idx);
2011 if param.sized == ast::DynSize {
2012 try!(s.word_space("type"));
2014 try!(s.print_ident(param.ident));
2015 try!(s.print_bounds(&None, ¶m.bounds, false));
2016 match param.default {
2018 try!(space(&mut s.s));
2019 try!(s.word_space("="));
2020 s.print_type(default)
2026 word(&mut self.s, ">")
2032 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2033 try!(self.ibox(indent_unit));
2035 ast::MetaWord(ref name) => {
2036 try!(word(&mut self.s, name.get()));
2038 ast::MetaNameValue(ref name, ref value) => {
2039 try!(self.word_space(name.get()));
2040 try!(self.word_space("="));
2041 try!(self.print_literal(value));
2043 ast::MetaList(ref name, ref items) => {
2044 try!(word(&mut self.s, name.get()));
2046 try!(self.commasep(Consistent,
2048 |s, &i| s.print_meta_item(i)));
2049 try!(self.pclose());
2055 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2057 ast::ViewPathSimple(ident, ref path, _) => {
2058 // FIXME(#6993) can't compare identifiers directly here
2059 if path.segments.last().unwrap().identifier.name != ident.name {
2060 try!(self.print_ident(ident));
2061 try!(space(&mut self.s));
2062 try!(self.word_space("="));
2064 self.print_path(path, false)
2067 ast::ViewPathGlob(ref path, _) => {
2068 try!(self.print_path(path, false));
2069 word(&mut self.s, "::*")
2072 ast::ViewPathList(ref path, ref idents, _) => {
2073 if path.segments.is_empty() {
2074 try!(word(&mut self.s, "{"));
2076 try!(self.print_path(path, false));
2077 try!(word(&mut self.s, "::{"));
2079 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2080 s.print_ident(w.node.name)
2082 word(&mut self.s, "}")
2087 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2088 try!(self.hardbreak_if_not_bol());
2089 try!(self.maybe_print_comment(item.span.lo));
2090 try!(self.print_outer_attributes(item.attrs.as_slice()));
2091 try!(self.print_visibility(item.vis));
2093 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2094 try!(self.head("extern crate"));
2095 try!(self.print_ident(id));
2096 for &(ref p, style) in optional_path.iter() {
2097 try!(space(&mut self.s));
2098 try!(word(&mut self.s, "="));
2099 try!(space(&mut self.s));
2100 try!(self.print_string(p.get(), style));
2104 ast::ViewItemUse(ref vp) => {
2105 try!(self.head("use"));
2106 try!(self.print_view_path(*vp));
2109 try!(word(&mut self.s, ";"));
2110 try!(self.end()); // end inner head-block
2111 self.end() // end outer head-block
2114 pub fn print_mutability(&mut self,
2115 mutbl: ast::Mutability) -> IoResult<()> {
2117 ast::MutMutable => self.word_nbsp("mut"),
2118 ast::MutImmutable => Ok(()),
2122 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2123 try!(self.print_mutability(mt.mutbl));
2124 self.print_type(mt.ty)
2127 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2128 try!(self.ibox(indent_unit));
2129 match input.ty.node {
2130 ast::TyInfer => try!(self.print_pat(input.pat)),
2132 match input.pat.node {
2133 ast::PatIdent(_, ref path, _) if
2134 path.segments.len() == 1 &&
2135 path.segments.get(0).identifier.name ==
2136 parse::token::special_idents::invalid.name => {
2140 try!(self.print_pat(input.pat));
2141 try!(word(&mut self.s, ":"));
2142 try!(space(&mut self.s));
2145 try!(self.print_type(input.ty));
2151 pub fn print_ty_fn(&mut self,
2152 opt_abi: Option<abi::Abi>,
2153 opt_sigil: Option<char>,
2154 opt_region: &Option<ast::Lifetime>,
2155 fn_style: ast::FnStyle,
2156 onceness: ast::Onceness,
2158 id: Option<ast::Ident>,
2159 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2160 generics: Option<&ast::Generics>,
2161 opt_explicit_self: Option<ast::ExplicitSelf_>,
2164 try!(self.ibox(indent_unit));
2166 // Duplicates the logic in `print_fn_header_info()`. This is because that
2167 // function prints the sigil in the wrong place. That should be fixed.
2168 if opt_sigil == Some('~') && onceness == ast::Once {
2169 try!(word(&mut self.s, "proc"));
2170 } else if opt_sigil == Some('&') {
2171 try!(self.print_fn_style(fn_style));
2172 try!(self.print_extern_opt_abi(opt_abi));
2173 try!(self.print_onceness(onceness));
2175 assert!(opt_sigil.is_none());
2176 try!(self.print_fn_style(fn_style));
2177 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2178 try!(self.print_onceness(onceness));
2180 try!(word(&mut self.s, "fn"));
2186 try!(word(&mut self.s, " "));
2187 try!(self.print_ident(id));
2192 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2193 try!(zerobreak(&mut self.s));
2195 if is_unboxed || opt_sigil == Some('&') {
2196 try!(word(&mut self.s, "|"));
2202 try!(word(&mut self.s, "&mut"));
2203 try!(self.word_space(":"));
2206 try!(self.print_fn_args(decl, opt_explicit_self));
2208 if is_unboxed || opt_sigil == Some('&') {
2209 try!(word(&mut self.s, "|"));
2212 try!(word(&mut self.s, ", ..."));
2214 try!(self.pclose());
2217 opt_bounds.as_ref().map(|bounds| {
2218 self.print_bounds(opt_region, bounds, true)
2221 try!(self.maybe_print_comment(decl.output.span.lo));
2223 match decl.output.node {
2226 try!(self.space_if_not_bol());
2227 try!(self.ibox(indent_unit));
2228 try!(self.word_space("->"));
2229 if decl.cf == ast::NoReturn {
2230 try!(self.word_nbsp("!"));
2232 try!(self.print_type(decl.output));
2241 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2242 next_pos: Option<BytePos>)
2244 let cm = match self.cm {
2248 match self.next_comment() {
2250 if (*cmnt).style != comments::Trailing { return Ok(()) }
2251 let span_line = cm.lookup_char_pos(span.hi);
2252 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2253 let mut next = (*cmnt).pos + BytePos(1);
2254 match next_pos { None => (), Some(p) => next = p }
2255 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2256 span_line.line == comment_line.line {
2257 try!(self.print_comment(cmnt));
2258 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2266 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2267 // If there aren't any remaining comments, then we need to manually
2268 // make sure there is a line break at the end.
2269 if self.next_comment().is_none() {
2270 try!(hardbreak(&mut self.s));
2273 match self.next_comment() {
2275 try!(self.print_comment(cmnt));
2276 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2284 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2285 try!(self.maybe_print_comment(lit.span.lo));
2286 match self.next_lit(lit.span.lo) {
2288 return word(&mut self.s, (*ltrl).lit.as_slice());
2293 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2294 ast::LitChar(ch) => {
2295 let mut res = String::from_str("'");
2296 ch.escape_default(|c| res.push_char(c));
2297 res.push_char('\'');
2298 word(&mut self.s, res.as_slice())
2300 ast::LitInt(i, t) => {
2302 ast_util::int_ty_to_str(t, Some(i),
2303 ast_util::AutoSuffix).as_slice())
2305 ast::LitUint(u, t) => {
2307 ast_util::uint_ty_to_str(t, Some(u),
2308 ast_util::ForceSuffix).as_slice())
2310 ast::LitIntUnsuffixed(i) => {
2311 word(&mut self.s, format!("{}", i).as_slice())
2313 ast::LitFloat(ref f, t) => {
2318 ast_util::float_ty_to_str(t).as_slice()).as_slice())
2320 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2321 ast::LitNil => word(&mut self.s, "()"),
2322 ast::LitBool(val) => {
2323 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2325 ast::LitBinary(ref arr) => {
2326 try!(self.ibox(indent_unit));
2327 try!(word(&mut self.s, "["));
2328 try!(self.commasep_cmnt(Inconsistent,
2336 try!(word(&mut self.s, "]"));
2342 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2343 match self.literals {
2345 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2346 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2347 if ltrl.pos > pos { return None; }
2348 self.cur_cmnt_and_lit.cur_lit += 1u;
2349 if ltrl.pos == pos { return Some(ltrl); }
2357 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2359 match self.next_comment() {
2361 if (*cmnt).pos < pos {
2362 try!(self.print_comment(cmnt));
2363 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2372 pub fn print_comment(&mut self,
2373 cmnt: &comments::Comment) -> IoResult<()> {
2375 comments::Mixed => {
2376 assert_eq!(cmnt.lines.len(), 1u);
2377 try!(zerobreak(&mut self.s));
2378 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2379 zerobreak(&mut self.s)
2381 comments::Isolated => {
2382 try!(self.hardbreak_if_not_bol());
2383 for line in cmnt.lines.iter() {
2384 // Don't print empty lines because they will end up as trailing
2386 if !line.is_empty() {
2387 try!(word(&mut self.s, line.as_slice()));
2389 try!(hardbreak(&mut self.s));
2393 comments::Trailing => {
2394 try!(word(&mut self.s, " "));
2395 if cmnt.lines.len() == 1u {
2396 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2397 hardbreak(&mut self.s)
2399 try!(self.ibox(0u));
2400 for line in cmnt.lines.iter() {
2401 if !line.is_empty() {
2402 try!(word(&mut self.s, line.as_slice()));
2404 try!(hardbreak(&mut self.s));
2409 comments::BlankLine => {
2410 // We need to do at least one, possibly two hardbreaks.
2411 let is_semi = match self.s.last_token() {
2412 pp::String(s, _) => ";" == s.as_slice(),
2415 if is_semi || self.is_begin() || self.is_end() {
2416 try!(hardbreak(&mut self.s));
2418 hardbreak(&mut self.s)
2423 pub fn print_string(&mut self, st: &str,
2424 style: ast::StrStyle) -> IoResult<()> {
2425 let st = match style {
2427 (format!("\"{}\"", st.escape_default()))
2430 (format!("r{delim}\"{string}\"{delim}",
2431 delim="#".repeat(n),
2435 word(&mut self.s, st.as_slice())
2438 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2439 match self.comments {
2440 Some(ref cmnts) => {
2441 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2442 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2451 pub fn print_opt_fn_style(&mut self,
2452 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2453 match opt_fn_style {
2454 Some(fn_style) => self.print_fn_style(fn_style),
2459 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2460 opt_abi: Option<abi::Abi>)
2463 Some(abi::Rust) => Ok(()),
2465 try!(self.word_nbsp("extern"));
2466 self.word_nbsp(abi.to_str().as_slice())
2472 pub fn print_extern_opt_abi(&mut self,
2473 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2476 try!(self.word_nbsp("extern"));
2477 self.word_nbsp(abi.to_str().as_slice())
2483 pub fn print_fn_header_info(&mut self,
2484 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2485 opt_fn_style: Option<ast::FnStyle>,
2487 vis: ast::Visibility) -> IoResult<()> {
2488 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2489 try!(self.print_opt_fn_style(opt_fn_style));
2491 if abi != abi::Rust {
2492 try!(self.word_nbsp("extern"));
2493 try!(self.word_nbsp(abi.to_str().as_slice()));
2496 word(&mut self.s, "fn")
2499 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2501 ast::NormalFn => Ok(()),
2502 ast::UnsafeFn => self.word_nbsp("unsafe"),
2506 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2508 ast::Once => self.word_nbsp("once"),
2524 fn test_fun_to_str() {
2525 let abba_ident = token::str_to_ident("abba");
2527 let decl = ast::FnDecl {
2529 output: ast::P(ast::Ty {id: 0,
2531 span: codemap::DUMMY_SP}),
2535 let generics = ast_util::empty_generics();
2536 assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2538 &"fn abba()".to_string());
2542 fn test_variant_to_str() {
2543 let ident = token::str_to_ident("principal_skinner");
2545 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2548 // making this up as I go.... ?
2549 kind: ast::TupleVariantKind(Vec::new()),
2555 let varstr = variant_to_str(&var);
2556 assert_eq!(&varstr,&"pub principal_skinner".to_string());