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 ident_to_str(id: &ast::Ident) -> String {
200 to_str(|s| s.print_ident(*id))
203 pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
204 opt_explicit_self: Option<ast::ExplicitSelf_>,
205 generics: &ast::Generics) -> String {
207 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
208 name, generics, opt_explicit_self, ast::Inherited));
209 try!(s.end()); // Close the head box
210 s.end() // Close the outer box
214 pub fn block_to_str(blk: &ast::Block) -> String {
216 // containing cbox, will be closed by print-block at }
217 try!(s.cbox(indent_unit));
218 // head-ibox, will be closed by print-block after {
224 pub fn meta_item_to_str(mi: &ast::MetaItem) -> String {
225 to_str(|s| s.print_meta_item(mi))
228 pub fn attribute_to_str(attr: &ast::Attribute) -> String {
229 to_str(|s| s.print_attribute(attr))
232 pub fn lit_to_str(l: &ast::Lit) -> String {
233 to_str(|s| s.print_literal(l))
236 pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> String {
237 to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
240 pub fn variant_to_str(var: &ast::Variant) -> String {
241 to_str(|s| s.print_variant(var))
244 pub fn arg_to_str(arg: &ast::Arg) -> String {
245 to_str(|s| s.print_arg(arg))
248 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
250 ast::Public => format!("pub {}", s),
251 ast::Inherited => s.to_string()
255 fn needs_parentheses(expr: &ast::Expr) -> bool {
257 ast::ExprAssign(..) | ast::ExprBinary(..) |
258 ast::ExprFnBlock(..) | ast::ExprProc(..) |
259 ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
265 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
266 self.boxes.push(pp::Inconsistent);
267 pp::ibox(&mut self.s, u)
270 pub fn end(&mut self) -> IoResult<()> {
271 self.boxes.pop().unwrap();
275 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
276 self.boxes.push(pp::Consistent);
277 pp::cbox(&mut self.s, u)
281 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
283 pp::rbox(&mut self.s, u, b)
286 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
288 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
289 try!(word(&mut self.s, w));
293 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
294 try!(word(&mut self.s, w));
298 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
300 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
302 pub fn head(&mut self, w: &str) -> IoResult<()> {
303 // outer-box is consistent
304 try!(self.cbox(indent_unit));
305 // head-box is inconsistent
306 try!(self.ibox(w.len() + 1));
307 // keyword that starts the head
309 try!(self.word_nbsp(w));
314 pub fn bopen(&mut self) -> IoResult<()> {
315 try!(word(&mut self.s, "{"));
316 self.end() // close the head-box
319 pub fn bclose_(&mut self, span: codemap::Span,
320 indented: uint) -> IoResult<()> {
321 self.bclose_maybe_open(span, indented, true)
323 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
324 indented: uint, close_box: bool) -> IoResult<()> {
325 try!(self.maybe_print_comment(span.hi));
326 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
327 try!(word(&mut self.s, "}"));
329 try!(self.end()); // close the outer-box
333 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
334 self.bclose_(span, indent_unit)
337 pub fn is_begin(&mut self) -> bool {
338 match self.s.last_token() { pp::Begin(_) => true, _ => false }
341 pub fn is_end(&mut self) -> bool {
342 match self.s.last_token() { pp::End => true, _ => false }
345 pub fn is_bol(&mut self) -> bool {
346 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
349 pub fn in_cbox(&self) -> bool {
350 match self.boxes.last() {
351 Some(&last_box) => last_box == pp::Consistent,
356 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
358 try!(hardbreak(&mut self.s))
362 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
363 if !self.is_bol() { try!(space(&mut self.s)); }
366 pub fn break_offset_if_not_bol(&mut self, n: uint,
367 off: int) -> IoResult<()> {
369 break_offset(&mut self.s, n, off)
371 if off != 0 && self.s.last_token().is_hardbreak_tok() {
372 // We do something pretty sketchy here: tuck the nonzero
373 // offset-adjustment we were going to deposit along with the
374 // break into the previous hardbreak.
375 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
381 // Synthesizes a comment that was not textually present in the original source
383 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
384 try!(word(&mut self.s, "/*"));
385 try!(space(&mut self.s));
386 try!(word(&mut self.s, text.as_slice()));
387 try!(space(&mut self.s));
388 word(&mut self.s, "*/")
391 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
392 op: |&mut State, &T| -> IoResult<()>)
394 try!(self.rbox(0u, b));
395 let mut first = true;
396 for elt in elts.iter() {
397 if first { first = false; } else { try!(self.word_space(",")); }
404 pub fn commasep_cmnt<T>(
408 op: |&mut State, &T| -> IoResult<()>,
409 get_span: |&T| -> codemap::Span) -> IoResult<()> {
410 try!(self.rbox(0u, b));
411 let len = elts.len();
413 for elt in elts.iter() {
414 try!(self.maybe_print_comment(get_span(elt).hi));
418 try!(word(&mut self.s, ","));
419 try!(self.maybe_print_trailing_comment(get_span(elt),
420 Some(get_span(&elts[i]).hi)));
421 try!(self.space_if_not_bol());
427 pub fn commasep_exprs(&mut self, b: Breaks,
428 exprs: &[Gc<ast::Expr>]) -> IoResult<()> {
429 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
432 pub fn print_mod(&mut self, _mod: &ast::Mod,
433 attrs: &[ast::Attribute]) -> IoResult<()> {
434 try!(self.print_inner_attributes(attrs));
435 for vitem in _mod.view_items.iter() {
436 try!(self.print_view_item(vitem));
438 for item in _mod.items.iter() {
439 try!(self.print_item(&**item));
444 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
445 attrs: &[ast::Attribute]) -> IoResult<()> {
446 try!(self.print_inner_attributes(attrs));
447 for vitem in nmod.view_items.iter() {
448 try!(self.print_view_item(vitem));
450 for item in nmod.items.iter() {
451 try!(self.print_foreign_item(&**item));
456 pub fn print_opt_lifetime(&mut self,
457 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
458 for l in lifetime.iter() {
459 try!(self.print_lifetime(l));
465 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
466 try!(self.maybe_print_comment(ty.span.lo));
469 ast::TyNil => try!(word(&mut self.s, "()")),
470 ast::TyBot => try!(word(&mut self.s, "!")),
471 ast::TyBox(ref ty) => {
472 try!(word(&mut self.s, "@"));
473 try!(self.print_type(&**ty));
475 ast::TyUniq(ref ty) => {
476 try!(word(&mut self.s, "~"));
477 try!(self.print_type(&**ty));
479 ast::TyVec(ref ty) => {
480 try!(word(&mut self.s, "["));
481 try!(self.print_type(&**ty));
482 try!(word(&mut self.s, "]"));
484 ast::TyPtr(ref mt) => {
485 try!(word(&mut self.s, "*"));
487 ast::MutMutable => try!(self.word_nbsp("mut")),
488 ast::MutImmutable => try!(self.word_nbsp("const")),
490 try!(self.print_type(&*mt.ty));
492 ast::TyRptr(ref lifetime, ref mt) => {
493 try!(word(&mut self.s, "&"));
494 try!(self.print_opt_lifetime(lifetime));
495 try!(self.print_mt(mt));
497 ast::TyTup(ref elts) => {
499 try!(self.commasep(Inconsistent, elts.as_slice(),
500 |s, ty| s.print_type_ref(ty)));
502 try!(word(&mut self.s, ","));
506 ast::TyParen(ref typ) => {
508 try!(self.print_type(&**typ));
511 ast::TyBareFn(f) => {
512 let generics = ast::Generics {
513 lifetimes: f.lifetimes.clone(),
514 ty_params: OwnedSlice::empty()
516 try!(self.print_ty_fn(Some(f.abi),
528 ast::TyClosure(f, ref region) => {
529 let generics = ast::Generics {
530 lifetimes: f.lifetimes.clone(),
531 ty_params: OwnedSlice::empty()
533 try!(self.print_ty_fn(None,
545 ast::TyProc(ref f) => {
546 let generics = ast::Generics {
547 lifetimes: f.lifetimes.clone(),
548 ty_params: OwnedSlice::empty()
550 try!(self.print_ty_fn(None,
562 ast::TyUnboxedFn(f) => {
563 try!(self.print_ty_fn(None,
575 ast::TyPath(ref path, ref bounds, _) => {
576 try!(self.print_bounded_path(path, bounds));
578 ast::TyFixedLengthVec(ref ty, ref v) => {
579 try!(word(&mut self.s, "["));
580 try!(self.print_type(&**ty));
581 try!(word(&mut self.s, ", .."));
582 try!(self.print_expr(&**v));
583 try!(word(&mut self.s, "]"));
585 ast::TyTypeof(ref e) => {
586 try!(word(&mut self.s, "typeof("));
587 try!(self.print_expr(&**e));
588 try!(word(&mut self.s, ")"));
591 try!(word(&mut self.s, "_"));
597 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
598 self.print_type(&**ty)
601 pub fn print_foreign_item(&mut self,
602 item: &ast::ForeignItem) -> IoResult<()> {
603 try!(self.hardbreak_if_not_bol());
604 try!(self.maybe_print_comment(item.span.lo));
605 try!(self.print_outer_attributes(item.attrs.as_slice()));
607 ast::ForeignItemFn(ref decl, ref generics) => {
608 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
610 try!(self.end()); // end head-ibox
611 try!(word(&mut self.s, ";"));
612 self.end() // end the outer fn box
614 ast::ForeignItemStatic(ref t, m) => {
615 try!(self.head(visibility_qualified(item.vis,
616 "static").as_slice()));
618 try!(self.word_space("mut"));
620 try!(self.print_ident(item.ident));
621 try!(self.word_space(":"));
622 try!(self.print_type(&**t));
623 try!(word(&mut self.s, ";"));
624 try!(self.end()); // end the head-ibox
625 self.end() // end the outer cbox
630 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
631 try!(self.hardbreak_if_not_bol());
632 try!(self.maybe_print_comment(item.span.lo));
633 try!(self.print_outer_attributes(item.attrs.as_slice()));
634 try!(self.ann.pre(self, NodeItem(item)));
636 ast::ItemStatic(ref ty, m, ref expr) => {
637 try!(self.head(visibility_qualified(item.vis,
638 "static").as_slice()));
639 if m == ast::MutMutable {
640 try!(self.word_space("mut"));
642 try!(self.print_ident(item.ident));
643 try!(self.word_space(":"));
644 try!(self.print_type(&**ty));
645 try!(space(&mut self.s));
646 try!(self.end()); // end the head-ibox
648 try!(self.word_space("="));
649 try!(self.print_expr(&**expr));
650 try!(word(&mut self.s, ";"));
651 try!(self.end()); // end the outer cbox
653 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
663 try!(word(&mut self.s, " "));
664 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
666 ast::ItemMod(ref _mod) => {
667 try!(self.head(visibility_qualified(item.vis,
669 try!(self.print_ident(item.ident));
672 try!(self.print_mod(_mod, item.attrs.as_slice()));
673 try!(self.bclose(item.span));
675 ast::ItemForeignMod(ref nmod) => {
676 try!(self.head("extern"));
677 try!(self.word_nbsp(nmod.abi.to_str().as_slice()));
679 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
680 try!(self.bclose(item.span));
682 ast::ItemTy(ref ty, ref params) => {
683 try!(self.ibox(indent_unit));
685 try!(self.word_nbsp(visibility_qualified(item.vis,
686 "type").as_slice()));
687 try!(self.print_ident(item.ident));
688 try!(self.print_generics(params));
689 try!(self.end()); // end the inner ibox
691 try!(space(&mut self.s));
692 try!(self.word_space("="));
693 try!(self.print_type(&**ty));
694 try!(word(&mut self.s, ";"));
695 try!(self.end()); // end the outer ibox
697 ast::ItemEnum(ref enum_definition, ref params) => {
698 try!(self.print_enum_def(
706 ast::ItemStruct(ref struct_def, ref generics) => {
707 if struct_def.is_virtual {
708 try!(self.word_space("virtual"));
710 try!(self.head(visibility_qualified(item.vis,
711 "struct").as_slice()));
712 try!(self.print_struct(&**struct_def, generics, item.ident,
716 ast::ItemImpl(ref generics, ref opt_trait, ref ty, ref methods) => {
717 try!(self.head(visibility_qualified(item.vis,
718 "impl").as_slice()));
719 if generics.is_parameterized() {
720 try!(self.print_generics(generics));
721 try!(space(&mut self.s));
726 try!(self.print_trait_ref(t));
727 try!(space(&mut self.s));
728 try!(self.word_space("for"));
733 try!(self.print_type(&**ty));
735 try!(space(&mut self.s));
737 try!(self.print_inner_attributes(item.attrs.as_slice()));
738 for meth in methods.iter() {
739 try!(self.print_method(&**meth));
741 try!(self.bclose(item.span));
743 ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => {
744 try!(self.head(visibility_qualified(item.vis,
745 "trait").as_slice()));
746 try!(self.print_ident(item.ident));
747 try!(self.print_generics(generics));
748 if *sized == ast::DynSize {
749 try!(space(&mut self.s));
750 try!(word(&mut self.s, "for type"));
752 if traits.len() != 0u {
753 try!(word(&mut self.s, ":"));
754 for (i, trait_) in traits.iter().enumerate() {
757 try!(self.word_space("+"));
759 try!(self.print_path(&trait_.path, false));
762 try!(word(&mut self.s, " "));
764 for meth in methods.iter() {
765 try!(self.print_trait_method(meth));
767 try!(self.bclose(item.span));
769 // I think it's reasonable to hide the context here:
770 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
772 try!(self.print_visibility(item.vis));
773 try!(self.print_path(pth, false));
774 try!(word(&mut self.s, "! "));
775 try!(self.print_ident(item.ident));
776 try!(self.cbox(indent_unit));
778 try!(self.print_tts(tts.as_slice()));
783 self.ann.post(self, NodeItem(item))
786 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
787 self.print_path(&t.path, false)
790 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
791 generics: &ast::Generics, ident: ast::Ident,
793 visibility: ast::Visibility) -> IoResult<()> {
794 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
795 try!(self.print_ident(ident));
796 try!(self.print_generics(generics));
797 try!(space(&mut self.s));
798 self.print_variants(enum_definition.variants.as_slice(), span)
801 pub fn print_variants(&mut self,
802 variants: &[P<ast::Variant>],
803 span: codemap::Span) -> IoResult<()> {
805 for v in variants.iter() {
806 try!(self.space_if_not_bol());
807 try!(self.maybe_print_comment(v.span.lo));
808 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
809 try!(self.ibox(indent_unit));
810 try!(self.print_variant(&**v));
811 try!(word(&mut self.s, ","));
813 try!(self.maybe_print_trailing_comment(v.span, None));
818 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
820 ast::Public => self.word_nbsp("pub"),
821 ast::Inherited => Ok(())
825 pub fn print_struct(&mut self,
826 struct_def: &ast::StructDef,
827 generics: &ast::Generics,
829 span: codemap::Span) -> IoResult<()> {
830 try!(self.print_ident(ident));
831 try!(self.print_generics(generics));
832 match struct_def.super_struct {
834 try!(self.word_space(":"));
835 try!(self.print_type(&**t));
839 if ast_util::struct_def_is_tuple_like(struct_def) {
840 if !struct_def.fields.is_empty() {
843 Inconsistent, struct_def.fields.as_slice(),
845 match field.node.kind {
846 ast::NamedField(..) => fail!("unexpected named field"),
847 ast::UnnamedField(vis) => {
848 try!(s.print_visibility(vis));
849 try!(s.maybe_print_comment(field.span.lo));
850 s.print_type(&*field.node.ty)
857 try!(word(&mut self.s, ";"));
859 self.end() // close the outer-box
863 try!(self.hardbreak_if_not_bol());
865 for field in struct_def.fields.iter() {
866 match field.node.kind {
867 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
868 ast::NamedField(ident, visibility) => {
869 try!(self.hardbreak_if_not_bol());
870 try!(self.maybe_print_comment(field.span.lo));
871 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
872 try!(self.print_visibility(visibility));
873 try!(self.print_ident(ident));
874 try!(self.word_nbsp(":"));
875 try!(self.print_type(&*field.node.ty));
876 try!(word(&mut self.s, ","));
885 /// This doesn't deserve to be called "pretty" printing, but it should be
886 /// meaning-preserving. A quick hack that might help would be to look at the
887 /// spans embedded in the TTs to decide where to put spaces and newlines.
888 /// But it'd be better to parse these according to the grammar of the
889 /// appropriate macro, transcribe back into the grammar we just parsed from,
890 /// and then pretty-print the resulting AST nodes (so, e.g., we print
891 /// expression arguments as expressions). It can be done! I think.
892 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
894 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
895 ast::TTTok(_, ref tk) => {
896 try!(word(&mut self.s, parse::token::to_str(tk).as_slice()));
898 parse::token::DOC_COMMENT(..) => {
899 hardbreak(&mut self.s)
904 ast::TTSeq(_, ref tts, ref sep, zerok) => {
905 try!(word(&mut self.s, "$("));
906 for tt_elt in (*tts).iter() {
907 try!(self.print_tt(tt_elt));
909 try!(word(&mut self.s, ")"));
912 try!(word(&mut self.s,
913 parse::token::to_str(tk).as_slice()));
917 word(&mut self.s, if zerok { "*" } else { "+" })
919 ast::TTNonterminal(_, name) => {
920 try!(word(&mut self.s, "$"));
921 self.print_ident(name)
926 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
928 for (i, tt) in tts.iter().enumerate() {
930 try!(space(&mut self.s));
932 try!(self.print_tt(tt));
937 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
938 try!(self.print_visibility(v.node.vis));
940 ast::TupleVariantKind(ref args) => {
941 try!(self.print_ident(v.node.name));
942 if !args.is_empty() {
944 try!(self.commasep(Consistent,
946 |s, arg| s.print_type(&*arg.ty)));
950 ast::StructVariantKind(ref struct_def) => {
952 let generics = ast_util::empty_generics();
953 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
956 match v.node.disr_expr {
958 try!(space(&mut self.s));
959 try!(self.word_space("="));
960 self.print_expr(&**d)
966 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
967 try!(self.hardbreak_if_not_bol());
968 try!(self.maybe_print_comment(m.span.lo));
969 try!(self.print_outer_attributes(m.attrs.as_slice()));
970 try!(self.print_ty_fn(None,
979 Some(m.explicit_self.node),
981 word(&mut self.s, ";")
984 pub fn print_trait_method(&mut self,
985 m: &ast::TraitMethod) -> IoResult<()> {
987 Required(ref ty_m) => self.print_ty_method(ty_m),
988 Provided(ref m) => self.print_method(&**m)
992 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
993 try!(self.hardbreak_if_not_bol());
994 try!(self.maybe_print_comment(meth.span.lo));
995 try!(self.print_outer_attributes(meth.attrs.as_slice()));
996 try!(self.print_fn(&*meth.decl, Some(meth.fn_style), abi::Rust,
997 meth.ident, &meth.generics, Some(meth.explicit_self.node),
999 try!(word(&mut self.s, " "));
1000 self.print_block_with_attrs(&*meth.body, meth.attrs.as_slice())
1003 pub fn print_outer_attributes(&mut self,
1004 attrs: &[ast::Attribute]) -> IoResult<()> {
1006 for attr in attrs.iter() {
1007 match attr.node.style {
1009 try!(self.print_attribute(attr));
1012 _ => {/* fallthrough */ }
1016 try!(self.hardbreak_if_not_bol());
1021 pub fn print_inner_attributes(&mut self,
1022 attrs: &[ast::Attribute]) -> IoResult<()> {
1024 for attr in attrs.iter() {
1025 match attr.node.style {
1027 try!(self.print_attribute(attr));
1030 _ => {/* fallthrough */ }
1034 try!(self.hardbreak_if_not_bol());
1039 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1040 try!(self.hardbreak_if_not_bol());
1041 try!(self.maybe_print_comment(attr.span.lo));
1042 if attr.node.is_sugared_doc {
1043 word(&mut self.s, attr.value_str().unwrap().get())
1045 match attr.node.style {
1046 ast::AttrInner => try!(word(&mut self.s, "#![")),
1047 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1049 try!(self.print_meta_item(&*attr.meta()));
1050 word(&mut self.s, "]")
1055 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1056 try!(self.maybe_print_comment(st.span.lo));
1058 ast::StmtDecl(ref decl, _) => {
1059 try!(self.print_decl(&**decl));
1061 ast::StmtExpr(ref expr, _) => {
1062 try!(self.space_if_not_bol());
1063 try!(self.print_expr(&**expr));
1065 ast::StmtSemi(ref expr, _) => {
1066 try!(self.space_if_not_bol());
1067 try!(self.print_expr(&**expr));
1068 try!(word(&mut self.s, ";"));
1070 ast::StmtMac(ref mac, semi) => {
1071 try!(self.space_if_not_bol());
1072 try!(self.print_mac(mac));
1074 try!(word(&mut self.s, ";"));
1078 if parse::classify::stmt_ends_with_semi(st) {
1079 try!(word(&mut self.s, ";"));
1081 self.maybe_print_trailing_comment(st.span, None)
1084 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1085 self.print_block_with_attrs(blk, &[])
1088 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1089 self.print_block_unclosed_indent(blk, indent_unit)
1092 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1093 indented: uint) -> IoResult<()> {
1094 self.print_block_maybe_unclosed(blk, indented, &[], false)
1097 pub fn print_block_with_attrs(&mut self,
1099 attrs: &[ast::Attribute]) -> IoResult<()> {
1100 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1103 pub fn print_block_maybe_unclosed(&mut self,
1106 attrs: &[ast::Attribute],
1107 close_box: bool) -> IoResult<()> {
1109 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1110 ast::DefaultBlock => ()
1112 try!(self.maybe_print_comment(blk.span.lo));
1113 try!(self.ann.pre(self, NodeBlock(blk)));
1116 try!(self.print_inner_attributes(attrs));
1118 for vi in blk.view_items.iter() {
1119 try!(self.print_view_item(vi));
1121 for st in blk.stmts.iter() {
1122 try!(self.print_stmt(&**st));
1126 try!(self.space_if_not_bol());
1127 try!(self.print_expr(&**expr));
1128 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1132 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1133 self.ann.post(self, NodeBlock(blk))
1136 fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1140 // "another else-if"
1141 ast::ExprIf(ref i, ref t, e) => {
1142 try!(self.cbox(indent_unit - 1u));
1143 try!(self.ibox(0u));
1144 try!(word(&mut self.s, " else if "));
1145 try!(self.print_expr(&**i));
1146 try!(space(&mut self.s));
1147 try!(self.print_block(&**t));
1151 ast::ExprBlock(ref b) => {
1152 try!(self.cbox(indent_unit - 1u));
1153 try!(self.ibox(0u));
1154 try!(word(&mut self.s, " else "));
1155 self.print_block(&**b)
1157 // BLEAH, constraints would be great here
1159 fail!("print_if saw if with weird alternative");
1167 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1168 elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1169 try!(self.head("if"));
1170 if chk { try!(self.word_nbsp("check")); }
1171 try!(self.print_expr(test));
1172 try!(space(&mut self.s));
1173 try!(self.print_block(blk));
1174 self.print_else(elseopt)
1177 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1179 // I think it's reasonable to hide the ctxt here:
1180 ast::MacInvocTT(ref pth, ref tts, _) => {
1181 try!(self.print_path(pth, false));
1182 try!(word(&mut self.s, "!"));
1184 try!(self.print_tts(tts.as_slice()));
1190 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1192 ast::ExprVstoreUniq => word(&mut self.s, "box "),
1193 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1194 ast::ExprVstoreMutSlice => {
1195 try!(word(&mut self.s, "&"));
1196 word(&mut self.s, "mut")
1201 fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1203 try!(self.commasep_exprs(Inconsistent, args));
1207 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1208 let needs_par = needs_parentheses(expr);
1212 try!(self.print_expr(expr));
1214 try!(self.pclose());
1219 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1220 try!(self.maybe_print_comment(expr.span.lo));
1221 try!(self.ibox(indent_unit));
1222 try!(self.ann.pre(self, NodeExpr(expr)));
1224 ast::ExprVstore(ref e, v) => {
1225 try!(self.print_expr_vstore(v));
1226 try!(self.print_expr(&**e));
1228 ast::ExprBox(ref p, ref e) => {
1229 try!(word(&mut self.s, "box"));
1230 try!(word(&mut self.s, "("));
1231 try!(self.print_expr(&**p));
1232 try!(self.word_space(")"));
1233 try!(self.print_expr(&**e));
1235 ast::ExprVec(ref exprs) => {
1236 try!(self.ibox(indent_unit));
1237 try!(word(&mut self.s, "["));
1238 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1239 try!(word(&mut self.s, "]"));
1243 ast::ExprRepeat(ref element, ref count) => {
1244 try!(self.ibox(indent_unit));
1245 try!(word(&mut self.s, "["));
1246 try!(self.print_expr(&**element));
1247 try!(word(&mut self.s, ","));
1248 try!(word(&mut self.s, ".."));
1249 try!(self.print_expr(&**count));
1250 try!(word(&mut self.s, "]"));
1254 ast::ExprStruct(ref path, ref fields, wth) => {
1255 try!(self.print_path(path, true));
1256 try!(word(&mut self.s, "{"));
1257 try!(self.commasep_cmnt(
1261 try!(s.ibox(indent_unit));
1262 try!(s.print_ident(field.ident.node));
1263 try!(s.word_space(":"));
1264 try!(s.print_expr(&*field.expr));
1270 try!(self.ibox(indent_unit));
1271 if !fields.is_empty() {
1272 try!(word(&mut self.s, ","));
1273 try!(space(&mut self.s));
1275 try!(word(&mut self.s, ".."));
1276 try!(self.print_expr(&**expr));
1279 _ => try!(word(&mut self.s, ","))
1281 try!(word(&mut self.s, "}"));
1283 ast::ExprTup(ref exprs) => {
1285 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1286 if exprs.len() == 1 {
1287 try!(word(&mut self.s, ","));
1289 try!(self.pclose());
1291 ast::ExprCall(ref func, ref args) => {
1292 try!(self.print_expr_maybe_paren(&**func));
1293 try!(self.print_call_post(args.as_slice()));
1295 ast::ExprMethodCall(ident, ref tys, ref args) => {
1296 let base_args = args.slice_from(1);
1297 try!(self.print_expr(&**args.get(0)));
1298 try!(word(&mut self.s, "."));
1299 try!(self.print_ident(ident.node));
1301 try!(word(&mut self.s, "::<"));
1302 try!(self.commasep(Inconsistent, tys.as_slice(),
1303 |s, ty| s.print_type_ref(ty)));
1304 try!(word(&mut self.s, ">"));
1306 try!(self.print_call_post(base_args));
1308 ast::ExprBinary(op, ref lhs, ref rhs) => {
1309 try!(self.print_expr(&**lhs));
1310 try!(space(&mut self.s));
1311 try!(self.word_space(ast_util::binop_to_str(op)));
1312 try!(self.print_expr(&**rhs));
1314 ast::ExprUnary(op, ref expr) => {
1315 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1316 try!(self.print_expr_maybe_paren(&**expr));
1318 ast::ExprAddrOf(m, ref expr) => {
1319 try!(word(&mut self.s, "&"));
1320 try!(self.print_mutability(m));
1321 try!(self.print_expr_maybe_paren(&**expr));
1323 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1324 ast::ExprCast(ref expr, ref ty) => {
1325 try!(self.print_expr(&**expr));
1326 try!(space(&mut self.s));
1327 try!(self.word_space("as"));
1328 try!(self.print_type(&**ty));
1330 ast::ExprIf(ref test, ref blk, elseopt) => {
1331 try!(self.print_if(&**test, &**blk, elseopt, false));
1333 ast::ExprWhile(ref test, ref blk) => {
1334 try!(self.head("while"));
1335 try!(self.print_expr(&**test));
1336 try!(space(&mut self.s));
1337 try!(self.print_block(&**blk));
1339 ast::ExprForLoop(ref pat, ref iter, 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("for"));
1345 try!(self.print_pat(&**pat));
1346 try!(space(&mut self.s));
1347 try!(self.word_space("in"));
1348 try!(self.print_expr(&**iter));
1349 try!(space(&mut self.s));
1350 try!(self.print_block(&**blk));
1352 ast::ExprLoop(ref blk, opt_ident) => {
1353 for ident in opt_ident.iter() {
1354 try!(self.print_ident(*ident));
1355 try!(self.word_space(":"));
1357 try!(self.head("loop"));
1358 try!(space(&mut self.s));
1359 try!(self.print_block(&**blk));
1361 ast::ExprMatch(ref expr, ref arms) => {
1362 try!(self.cbox(indent_unit));
1364 try!(self.word_nbsp("match"));
1365 try!(self.print_expr(&**expr));
1366 try!(space(&mut self.s));
1368 let len = arms.len();
1369 for (i, arm) in arms.iter().enumerate() {
1370 // I have no idea why this check is necessary, but here it
1372 if arm.attrs.is_empty() {
1373 try!(space(&mut self.s));
1375 try!(self.cbox(indent_unit));
1376 try!(self.ibox(0u));
1377 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1378 let mut first = true;
1379 for p in arm.pats.iter() {
1383 try!(space(&mut self.s));
1384 try!(self.word_space("|"));
1386 try!(self.print_pat(&**p));
1388 try!(space(&mut self.s));
1391 try!(self.word_space("if"));
1392 try!(self.print_expr(&**e));
1393 try!(space(&mut self.s));
1397 try!(self.word_space("=>"));
1399 match arm.body.node {
1400 ast::ExprBlock(ref blk) => {
1401 // the block will close the pattern's ibox
1402 try!(self.print_block_unclosed_indent(&**blk,
1406 try!(self.end()); // close the ibox for the pattern
1407 try!(self.print_expr(&*arm.body));
1410 if !expr_is_simple_block(expr.clone())
1412 try!(word(&mut self.s, ","));
1414 try!(self.end()); // close enclosing cbox
1416 try!(self.bclose_(expr.span, indent_unit));
1418 ast::ExprFnBlock(ref decl, ref body) => {
1419 // in do/for blocks we don't want to show an empty
1420 // argument list, but at this point we don't know which
1423 // if !decl.inputs.is_empty() {
1424 try!(self.print_fn_block_args(&**decl));
1425 try!(space(&mut self.s));
1428 if !body.stmts.is_empty() || !body.expr.is_some() {
1429 try!(self.print_block_unclosed(&**body));
1431 // we extract the block, so as not to create another set of boxes
1432 match body.expr.unwrap().node {
1433 ast::ExprBlock(ref blk) => {
1434 try!(self.print_block_unclosed(&**blk));
1437 // this is a bare expression
1438 try!(self.print_expr(&*body.expr.unwrap()));
1439 try!(self.end()); // need to close a box
1443 // a box will be closed by print_expr, but we didn't want an overall
1444 // wrapper so we closed the corresponding opening. so create an
1445 // empty box to satisfy the close.
1448 ast::ExprProc(ref decl, ref body) => {
1449 // in do/for blocks we don't want to show an empty
1450 // argument list, but at this point we don't know which
1453 // if !decl.inputs.is_empty() {
1454 try!(self.print_proc_args(&**decl));
1455 try!(space(&mut self.s));
1457 assert!(body.stmts.is_empty());
1458 assert!(body.expr.is_some());
1459 // we extract the block, so as not to create another set of boxes
1460 match body.expr.unwrap().node {
1461 ast::ExprBlock(ref blk) => {
1462 try!(self.print_block_unclosed(&**blk));
1465 // this is a bare expression
1466 try!(self.print_expr(&*body.expr.unwrap()));
1467 try!(self.end()); // need to close a box
1470 // a box will be closed by print_expr, but we didn't want an overall
1471 // wrapper so we closed the corresponding opening. so create an
1472 // empty box to satisfy the close.
1475 ast::ExprBlock(ref blk) => {
1476 // containing cbox, will be closed by print-block at }
1477 try!(self.cbox(indent_unit));
1478 // head-box, will be closed by print-block after {
1479 try!(self.ibox(0u));
1480 try!(self.print_block(&**blk));
1482 ast::ExprAssign(ref lhs, ref rhs) => {
1483 try!(self.print_expr(&**lhs));
1484 try!(space(&mut self.s));
1485 try!(self.word_space("="));
1486 try!(self.print_expr(&**rhs));
1488 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1489 try!(self.print_expr(&**lhs));
1490 try!(space(&mut self.s));
1491 try!(word(&mut self.s, ast_util::binop_to_str(op)));
1492 try!(self.word_space("="));
1493 try!(self.print_expr(&**rhs));
1495 ast::ExprField(ref expr, id, ref tys) => {
1496 try!(self.print_expr(&**expr));
1497 try!(word(&mut self.s, "."));
1498 try!(self.print_ident(id.node));
1500 try!(word(&mut self.s, "::<"));
1502 Inconsistent, tys.as_slice(),
1503 |s, ty| s.print_type_ref(ty)));
1504 try!(word(&mut self.s, ">"));
1507 ast::ExprIndex(ref expr, ref index) => {
1508 try!(self.print_expr(&**expr));
1509 try!(word(&mut self.s, "["));
1510 try!(self.print_expr(&**index));
1511 try!(word(&mut self.s, "]"));
1513 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1514 ast::ExprBreak(opt_ident) => {
1515 try!(word(&mut self.s, "break"));
1516 try!(space(&mut self.s));
1517 for ident in opt_ident.iter() {
1518 try!(self.print_ident(*ident));
1519 try!(space(&mut self.s));
1522 ast::ExprAgain(opt_ident) => {
1523 try!(word(&mut self.s, "continue"));
1524 try!(space(&mut self.s));
1525 for ident in opt_ident.iter() {
1526 try!(self.print_ident(*ident));
1527 try!(space(&mut self.s))
1530 ast::ExprRet(ref result) => {
1531 try!(word(&mut self.s, "return"));
1534 try!(word(&mut self.s, " "));
1535 try!(self.print_expr(&**expr));
1540 ast::ExprInlineAsm(ref a) => {
1542 try!(word(&mut self.s, "__volatile__ asm!"));
1544 try!(word(&mut self.s, "asm!"));
1547 try!(self.print_string(a.asm.get(), a.asm_str_style));
1548 try!(self.word_space(":"));
1550 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1551 |s, &(ref co, ref o)| {
1552 try!(s.print_string(co.get(), ast::CookedStr));
1554 try!(s.print_expr(&**o));
1558 try!(space(&mut self.s));
1559 try!(self.word_space(":"));
1561 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1562 |s, &(ref co, ref o)| {
1563 try!(s.print_string(co.get(), ast::CookedStr));
1565 try!(s.print_expr(&**o));
1569 try!(space(&mut self.s));
1570 try!(self.word_space(":"));
1572 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1573 try!(self.pclose());
1575 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1576 ast::ExprParen(ref e) => {
1578 try!(self.print_expr(&**e));
1579 try!(self.pclose());
1582 try!(self.ann.post(self, NodeExpr(expr)));
1586 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1587 try!(self.print_pat(&*loc.pat));
1589 ast::TyInfer => Ok(()),
1591 try!(self.word_space(":"));
1592 self.print_type(&*loc.ty)
1597 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1598 try!(self.maybe_print_comment(decl.span.lo));
1600 ast::DeclLocal(ref loc) => {
1601 try!(self.space_if_not_bol());
1602 try!(self.ibox(indent_unit));
1603 try!(self.word_nbsp("let"));
1605 try!(self.ibox(indent_unit));
1606 try!(self.print_local_decl(&**loc));
1611 try!(self.word_space("="));
1612 try!(self.print_expr(&**init));
1618 ast::DeclItem(ref item) => self.print_item(&**item)
1622 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1623 word(&mut self.s, token::get_ident(ident).get())
1626 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1627 word(&mut self.s, token::get_name(name).get())
1630 pub fn print_for_decl(&mut self, loc: &ast::Local,
1631 coll: &ast::Expr) -> IoResult<()> {
1632 try!(self.print_local_decl(loc));
1633 try!(space(&mut self.s));
1634 try!(self.word_space("in"));
1635 self.print_expr(coll)
1638 fn print_path_(&mut self,
1640 colons_before_params: bool,
1641 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1643 try!(self.maybe_print_comment(path.span.lo));
1645 try!(word(&mut self.s, "::"));
1648 let mut first = true;
1649 for segment in path.segments.iter() {
1653 try!(word(&mut self.s, "::"))
1656 try!(self.print_ident(segment.identifier));
1658 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1659 if colons_before_params {
1660 try!(word(&mut self.s, "::"))
1662 try!(word(&mut self.s, "<"));
1664 let mut comma = false;
1665 for lifetime in segment.lifetimes.iter() {
1667 try!(self.word_space(","))
1669 try!(self.print_lifetime(lifetime));
1673 if !segment.types.is_empty() {
1675 try!(self.word_space(","))
1679 segment.types.as_slice(),
1680 |s, ty| s.print_type_ref(ty)));
1683 try!(word(&mut self.s, ">"))
1689 Some(ref bounds) => self.print_bounds(&None, bounds, true, true),
1693 fn print_path(&mut self, path: &ast::Path,
1694 colons_before_params: bool) -> IoResult<()> {
1695 self.print_path_(path, colons_before_params, &None)
1698 fn print_bounded_path(&mut self, path: &ast::Path,
1699 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1701 self.print_path_(path, false, bounds)
1704 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1705 try!(self.maybe_print_comment(pat.span.lo));
1706 try!(self.ann.pre(self, NodePat(pat)));
1707 /* Pat isn't normalized, but the beauty of it
1708 is that it doesn't matter */
1710 ast::PatWild => try!(word(&mut self.s, "_")),
1711 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1712 ast::PatIdent(binding_mode, ref path1, sub) => {
1713 match binding_mode {
1714 ast::BindByRef(mutbl) => {
1715 try!(self.word_nbsp("ref"));
1716 try!(self.print_mutability(mutbl));
1718 ast::BindByValue(ast::MutImmutable) => {}
1719 ast::BindByValue(ast::MutMutable) => {
1720 try!(self.word_nbsp("mut"));
1723 try!(self.print_ident(path1.node));
1726 try!(word(&mut self.s, "@"));
1727 try!(self.print_pat(&**p));
1732 ast::PatEnum(ref path, ref args_) => {
1733 try!(self.print_path(path, true));
1735 None => try!(word(&mut self.s, "(..)")),
1737 if !args.is_empty() {
1739 try!(self.commasep(Inconsistent, args.as_slice(),
1740 |s, p| s.print_pat(&**p)));
1741 try!(self.pclose());
1746 ast::PatStruct(ref path, ref fields, etc) => {
1747 try!(self.print_path(path, true));
1748 try!(word(&mut self.s, "{"));
1749 try!(self.commasep_cmnt(
1750 Consistent, fields.as_slice(),
1752 try!(s.cbox(indent_unit));
1753 try!(s.print_ident(f.ident));
1754 try!(s.word_space(":"));
1755 try!(s.print_pat(&*f.pat));
1760 if fields.len() != 0u { try!(self.word_space(",")); }
1761 try!(word(&mut self.s, ".."));
1763 try!(word(&mut self.s, "}"));
1765 ast::PatTup(ref elts) => {
1767 try!(self.commasep(Inconsistent,
1769 |s, p| s.print_pat(&**p)));
1770 if elts.len() == 1 {
1771 try!(word(&mut self.s, ","));
1773 try!(self.pclose());
1775 ast::PatBox(ref inner) => {
1776 try!(word(&mut self.s, "box "));
1777 try!(self.print_pat(&**inner));
1779 ast::PatRegion(ref inner) => {
1780 try!(word(&mut self.s, "&"));
1781 try!(self.print_pat(&**inner));
1783 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1784 ast::PatRange(ref begin, ref end) => {
1785 try!(self.print_expr(&**begin));
1786 try!(space(&mut self.s));
1787 try!(word(&mut self.s, ".."));
1788 try!(self.print_expr(&**end));
1790 ast::PatVec(ref before, slice, ref after) => {
1791 try!(word(&mut self.s, "["));
1792 try!(self.commasep(Inconsistent,
1794 |s, p| s.print_pat(&**p)));
1795 for p in slice.iter() {
1796 if !before.is_empty() { try!(self.word_space(",")); }
1798 ast::Pat { node: ast::PatWildMulti, .. } => {
1799 // this case is handled by print_pat
1801 _ => try!(word(&mut self.s, "..")),
1803 try!(self.print_pat(&**p));
1804 if !after.is_empty() { try!(self.word_space(",")); }
1806 try!(self.commasep(Inconsistent,
1808 |s, p| s.print_pat(&**p)));
1809 try!(word(&mut self.s, "]"));
1811 ast::PatMac(ref m) => try!(self.print_mac(m)),
1813 self.ann.post(self, NodePat(pat))
1816 // Returns whether it printed anything
1817 fn print_explicit_self(&mut self,
1818 explicit_self: ast::ExplicitSelf_,
1819 mutbl: ast::Mutability) -> IoResult<bool> {
1820 try!(self.print_mutability(mutbl));
1821 match explicit_self {
1822 ast::SelfStatic => { return Ok(false); }
1824 try!(word(&mut self.s, "self"));
1827 try!(word(&mut self.s, "~self"));
1829 ast::SelfRegion(ref lt, m) => {
1830 try!(word(&mut self.s, "&"));
1831 try!(self.print_opt_lifetime(lt));
1832 try!(self.print_mutability(m));
1833 try!(word(&mut self.s, "self"));
1839 pub fn print_fn(&mut self,
1841 fn_style: Option<ast::FnStyle>,
1844 generics: &ast::Generics,
1845 opt_explicit_self: Option<ast::ExplicitSelf_>,
1846 vis: ast::Visibility) -> IoResult<()> {
1847 try!(self.head(""));
1848 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1850 try!(self.print_ident(name));
1851 try!(self.print_generics(generics));
1852 self.print_fn_args_and_ret(decl, opt_explicit_self)
1855 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1856 opt_explicit_self: Option<ast::ExplicitSelf_>)
1858 // It is unfortunate to duplicate the commasep logic, but we want the
1859 // self type and the args all in the same box.
1860 try!(self.rbox(0u, Inconsistent));
1861 let mut first = true;
1862 for &explicit_self in opt_explicit_self.iter() {
1863 let m = match explicit_self {
1864 ast::SelfStatic => ast::MutImmutable,
1865 _ => match decl.inputs.get(0).pat.node {
1866 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1867 _ => ast::MutImmutable
1870 first = !try!(self.print_explicit_self(explicit_self, m));
1873 // HACK(eddyb) ignore the separately printed self argument.
1874 let args = if first {
1875 decl.inputs.as_slice()
1877 decl.inputs.slice_from(1)
1880 for arg in args.iter() {
1881 if first { first = false; } else { try!(self.word_space(",")); }
1882 try!(self.print_arg(arg));
1888 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1889 opt_explicit_self: Option<ast::ExplicitSelf_>)
1892 try!(self.print_fn_args(decl, opt_explicit_self));
1894 try!(word(&mut self.s, ", ..."));
1896 try!(self.pclose());
1898 try!(self.maybe_print_comment(decl.output.span.lo));
1899 match decl.output.node {
1900 ast::TyNil => Ok(()),
1902 try!(self.space_if_not_bol());
1903 try!(self.word_space("->"));
1904 self.print_type(&*decl.output)
1909 pub fn print_fn_block_args(&mut self,
1910 decl: &ast::FnDecl) -> IoResult<()> {
1911 try!(word(&mut self.s, "|"));
1912 try!(self.print_fn_args(decl, None));
1913 try!(word(&mut self.s, "|"));
1915 match decl.output.node {
1918 try!(self.space_if_not_bol());
1919 try!(self.word_space("->"));
1920 try!(self.print_type(&*decl.output));
1924 self.maybe_print_comment(decl.output.span.lo)
1927 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1928 try!(word(&mut self.s, "proc"));
1929 try!(word(&mut self.s, "("));
1930 try!(self.print_fn_args(decl, None));
1931 try!(word(&mut self.s, ")"));
1933 match decl.output.node {
1936 try!(self.space_if_not_bol());
1937 try!(self.word_space("->"));
1938 try!(self.print_type(&*decl.output));
1942 self.maybe_print_comment(decl.output.span.lo)
1945 pub fn print_bounds(&mut self,
1946 region: &Option<ast::Lifetime>,
1947 bounds: &OwnedSlice<ast::TyParamBound>,
1948 print_colon_anyway: bool,
1949 print_plus_before_bounds: bool)
1951 let separator = if print_plus_before_bounds {
1956 if !bounds.is_empty() || region.is_some() {
1957 try!(word(&mut self.s, separator));
1958 let mut first = true;
1961 let token = token::get_name(lt.name);
1962 if token.get() != "'static" {
1965 try!(self.print_lifetime(lt));
1970 for bound in bounds.iter() {
1975 try!(self.word_space("+"));
1979 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
1980 StaticRegionTyParamBound => word(&mut self.s, "'static"),
1981 UnboxedFnTyParamBound(ref unboxed_function_type) => {
1982 self.print_ty_fn(None,
1987 &*unboxed_function_type.decl,
1994 OtherRegionTyParamBound(_) => Ok(())
1998 } else if print_colon_anyway {
1999 word(&mut self.s, separator)
2005 pub fn print_lifetime(&mut self,
2006 lifetime: &ast::Lifetime) -> IoResult<()> {
2007 self.print_name(lifetime.name)
2010 pub fn print_generics(&mut self,
2011 generics: &ast::Generics) -> IoResult<()> {
2012 let total = generics.lifetimes.len() + generics.ty_params.len();
2014 try!(word(&mut self.s, "<"));
2016 let mut ints = Vec::new();
2017 for i in range(0u, total) {
2022 Inconsistent, ints.as_slice(),
2024 if idx < generics.lifetimes.len() {
2025 let lifetime = generics.lifetimes.get(idx);
2026 s.print_lifetime(lifetime)
2028 let idx = idx - generics.lifetimes.len();
2029 let param = generics.ty_params.get(idx);
2030 if param.sized == ast::DynSize {
2031 try!(s.word_space("type"));
2033 try!(s.print_ident(param.ident));
2034 try!(s.print_bounds(&None,
2038 match param.default {
2039 Some(ref default) => {
2040 try!(space(&mut s.s));
2041 try!(s.word_space("="));
2042 s.print_type(&**default)
2048 word(&mut self.s, ">")
2054 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2055 try!(self.ibox(indent_unit));
2057 ast::MetaWord(ref name) => {
2058 try!(word(&mut self.s, name.get()));
2060 ast::MetaNameValue(ref name, ref value) => {
2061 try!(self.word_space(name.get()));
2062 try!(self.word_space("="));
2063 try!(self.print_literal(value));
2065 ast::MetaList(ref name, ref items) => {
2066 try!(word(&mut self.s, name.get()));
2068 try!(self.commasep(Consistent,
2070 |s, i| s.print_meta_item(&**i)));
2071 try!(self.pclose());
2077 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2079 ast::ViewPathSimple(ident, ref path, _) => {
2080 // FIXME(#6993) can't compare identifiers directly here
2081 if path.segments.last().unwrap().identifier.name != ident.name {
2082 try!(self.print_ident(ident));
2083 try!(space(&mut self.s));
2084 try!(self.word_space("="));
2086 self.print_path(path, false)
2089 ast::ViewPathGlob(ref path, _) => {
2090 try!(self.print_path(path, false));
2091 word(&mut self.s, "::*")
2094 ast::ViewPathList(ref path, ref idents, _) => {
2095 if path.segments.is_empty() {
2096 try!(word(&mut self.s, "{"));
2098 try!(self.print_path(path, false));
2099 try!(word(&mut self.s, "::{"));
2101 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2102 s.print_ident(w.node.name)
2104 word(&mut self.s, "}")
2109 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2110 try!(self.hardbreak_if_not_bol());
2111 try!(self.maybe_print_comment(item.span.lo));
2112 try!(self.print_outer_attributes(item.attrs.as_slice()));
2113 try!(self.print_visibility(item.vis));
2115 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2116 try!(self.head("extern crate"));
2117 try!(self.print_ident(id));
2118 for &(ref p, style) in optional_path.iter() {
2119 try!(space(&mut self.s));
2120 try!(word(&mut self.s, "="));
2121 try!(space(&mut self.s));
2122 try!(self.print_string(p.get(), style));
2126 ast::ViewItemUse(ref vp) => {
2127 try!(self.head("use"));
2128 try!(self.print_view_path(&**vp));
2131 try!(word(&mut self.s, ";"));
2132 try!(self.end()); // end inner head-block
2133 self.end() // end outer head-block
2136 pub fn print_mutability(&mut self,
2137 mutbl: ast::Mutability) -> IoResult<()> {
2139 ast::MutMutable => self.word_nbsp("mut"),
2140 ast::MutImmutable => Ok(()),
2144 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2145 try!(self.print_mutability(mt.mutbl));
2146 self.print_type(&*mt.ty)
2149 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2150 try!(self.ibox(indent_unit));
2151 match input.ty.node {
2152 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2154 match input.pat.node {
2155 ast::PatIdent(_, ref path1, _) if
2157 parse::token::special_idents::invalid.name => {
2161 try!(self.print_pat(&*input.pat));
2162 try!(word(&mut self.s, ":"));
2163 try!(space(&mut self.s));
2166 try!(self.print_type(&*input.ty));
2172 pub fn print_ty_fn(&mut self,
2173 opt_abi: Option<abi::Abi>,
2174 opt_sigil: Option<char>,
2175 opt_region: &Option<ast::Lifetime>,
2176 fn_style: ast::FnStyle,
2177 onceness: ast::Onceness,
2179 id: Option<ast::Ident>,
2180 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2181 generics: Option<&ast::Generics>,
2182 opt_explicit_self: Option<ast::ExplicitSelf_>,
2185 try!(self.ibox(indent_unit));
2187 // Duplicates the logic in `print_fn_header_info()`. This is because that
2188 // function prints the sigil in the wrong place. That should be fixed.
2189 if opt_sigil == Some('~') && onceness == ast::Once {
2190 try!(word(&mut self.s, "proc"));
2191 } else if opt_sigil == Some('&') {
2192 try!(self.print_fn_style(fn_style));
2193 try!(self.print_extern_opt_abi(opt_abi));
2194 try!(self.print_onceness(onceness));
2196 assert!(opt_sigil.is_none());
2197 try!(self.print_fn_style(fn_style));
2198 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2199 try!(self.print_onceness(onceness));
2201 try!(word(&mut self.s, "fn"));
2207 try!(word(&mut self.s, " "));
2208 try!(self.print_ident(id));
2213 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2214 try!(zerobreak(&mut self.s));
2216 if is_unboxed || opt_sigil == Some('&') {
2217 try!(word(&mut self.s, "|"));
2223 try!(word(&mut self.s, "&mut"));
2224 try!(self.word_space(":"));
2227 try!(self.print_fn_args(decl, opt_explicit_self));
2229 if is_unboxed || opt_sigil == Some('&') {
2230 try!(word(&mut self.s, "|"));
2233 try!(word(&mut self.s, ", ..."));
2235 try!(self.pclose());
2238 opt_bounds.as_ref().map(|bounds| {
2239 self.print_bounds(opt_region, bounds, true, false)
2242 try!(self.maybe_print_comment(decl.output.span.lo));
2244 match decl.output.node {
2247 try!(self.space_if_not_bol());
2248 try!(self.ibox(indent_unit));
2249 try!(self.word_space("->"));
2250 if decl.cf == ast::NoReturn {
2251 try!(self.word_nbsp("!"));
2253 try!(self.print_type(&*decl.output));
2262 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2263 next_pos: Option<BytePos>)
2265 let cm = match self.cm {
2269 match self.next_comment() {
2271 if (*cmnt).style != comments::Trailing { return Ok(()) }
2272 let span_line = cm.lookup_char_pos(span.hi);
2273 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2274 let mut next = (*cmnt).pos + BytePos(1);
2275 match next_pos { None => (), Some(p) => next = p }
2276 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2277 span_line.line == comment_line.line {
2278 try!(self.print_comment(cmnt));
2279 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2287 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2288 // If there aren't any remaining comments, then we need to manually
2289 // make sure there is a line break at the end.
2290 if self.next_comment().is_none() {
2291 try!(hardbreak(&mut self.s));
2294 match self.next_comment() {
2296 try!(self.print_comment(cmnt));
2297 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2305 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2306 try!(self.maybe_print_comment(lit.span.lo));
2307 match self.next_lit(lit.span.lo) {
2309 return word(&mut self.s, (*ltrl).lit.as_slice());
2314 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2315 ast::LitByte(byte) => {
2316 let mut res = String::from_str("b'");
2317 (byte as char).escape_default(|c| res.push_char(c));
2318 res.push_char('\'');
2319 word(&mut self.s, res.as_slice())
2321 ast::LitChar(ch) => {
2322 let mut res = String::from_str("'");
2323 ch.escape_default(|c| res.push_char(c));
2324 res.push_char('\'');
2325 word(&mut self.s, res.as_slice())
2327 ast::LitInt(i, t) => {
2329 ast_util::int_ty_to_str(t, Some(i)).as_slice())
2331 ast::LitUint(u, t) => {
2333 ast_util::uint_ty_to_str(t, Some(u)).as_slice())
2335 ast::LitIntUnsuffixed(i) => {
2336 word(&mut self.s, format!("{}", i).as_slice())
2338 ast::LitFloat(ref f, t) => {
2343 ast_util::float_ty_to_str(t).as_slice()).as_slice())
2345 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2346 ast::LitNil => word(&mut self.s, "()"),
2347 ast::LitBool(val) => {
2348 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2350 ast::LitBinary(ref v) => {
2351 let escaped: String = v.iter().map(|&b| b as char).collect();
2352 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2357 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2358 match self.literals {
2360 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2361 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2362 if ltrl.pos > pos { return None; }
2363 self.cur_cmnt_and_lit.cur_lit += 1u;
2364 if ltrl.pos == pos { return Some(ltrl); }
2372 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2374 match self.next_comment() {
2376 if (*cmnt).pos < pos {
2377 try!(self.print_comment(cmnt));
2378 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2387 pub fn print_comment(&mut self,
2388 cmnt: &comments::Comment) -> IoResult<()> {
2390 comments::Mixed => {
2391 assert_eq!(cmnt.lines.len(), 1u);
2392 try!(zerobreak(&mut self.s));
2393 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2394 zerobreak(&mut self.s)
2396 comments::Isolated => {
2397 try!(self.hardbreak_if_not_bol());
2398 for line in cmnt.lines.iter() {
2399 // Don't print empty lines because they will end up as trailing
2401 if !line.is_empty() {
2402 try!(word(&mut self.s, line.as_slice()));
2404 try!(hardbreak(&mut self.s));
2408 comments::Trailing => {
2409 try!(word(&mut self.s, " "));
2410 if cmnt.lines.len() == 1u {
2411 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2412 hardbreak(&mut self.s)
2414 try!(self.ibox(0u));
2415 for line in cmnt.lines.iter() {
2416 if !line.is_empty() {
2417 try!(word(&mut self.s, line.as_slice()));
2419 try!(hardbreak(&mut self.s));
2424 comments::BlankLine => {
2425 // We need to do at least one, possibly two hardbreaks.
2426 let is_semi = match self.s.last_token() {
2427 pp::String(s, _) => ";" == s.as_slice(),
2430 if is_semi || self.is_begin() || self.is_end() {
2431 try!(hardbreak(&mut self.s));
2433 hardbreak(&mut self.s)
2438 pub fn print_string(&mut self, st: &str,
2439 style: ast::StrStyle) -> IoResult<()> {
2440 let st = match style {
2442 (format!("\"{}\"", st.escape_default()))
2445 (format!("r{delim}\"{string}\"{delim}",
2446 delim="#".repeat(n),
2450 word(&mut self.s, st.as_slice())
2453 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2454 match self.comments {
2455 Some(ref cmnts) => {
2456 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2457 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2466 pub fn print_opt_fn_style(&mut self,
2467 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2468 match opt_fn_style {
2469 Some(fn_style) => self.print_fn_style(fn_style),
2474 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2475 opt_abi: Option<abi::Abi>)
2478 Some(abi::Rust) => Ok(()),
2480 try!(self.word_nbsp("extern"));
2481 self.word_nbsp(abi.to_str().as_slice())
2487 pub fn print_extern_opt_abi(&mut self,
2488 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2491 try!(self.word_nbsp("extern"));
2492 self.word_nbsp(abi.to_str().as_slice())
2498 pub fn print_fn_header_info(&mut self,
2499 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2500 opt_fn_style: Option<ast::FnStyle>,
2502 vis: ast::Visibility) -> IoResult<()> {
2503 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2504 try!(self.print_opt_fn_style(opt_fn_style));
2506 if abi != abi::Rust {
2507 try!(self.word_nbsp("extern"));
2508 try!(self.word_nbsp(abi.to_str().as_slice()));
2511 word(&mut self.s, "fn")
2514 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2516 ast::NormalFn => Ok(()),
2517 ast::UnsafeFn => self.word_nbsp("unsafe"),
2521 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2523 ast::Once => self.word_nbsp("once"),
2539 fn test_fun_to_str() {
2540 let abba_ident = token::str_to_ident("abba");
2542 let decl = ast::FnDecl {
2544 output: ast::P(ast::Ty {id: 0,
2546 span: codemap::DUMMY_SP}),
2550 let generics = ast_util::empty_generics();
2551 assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2553 &"fn abba()".to_string());
2557 fn test_variant_to_str() {
2558 let ident = token::str_to_ident("principal_skinner");
2560 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2563 // making this up as I go.... ?
2564 kind: ast::TupleVariantKind(Vec::new()),
2570 let varstr = variant_to_str(&var);
2571 assert_eq!(&varstr,&"pub principal_skinner".to_string());