1 // Copyright 2012-2014 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::{FnMutUnboxedClosureKind, FnOnceUnboxedClosureKind};
13 use ast::{FnUnboxedClosureKind, MethodImplItem, P};
14 use ast::{RegionTyParamBound, TraitTyParamBound, UnboxedClosureKind};
15 use ast::{UnboxedFnTyParamBound, RequiredMethod, ProvidedMethod};
18 use owned_slice::OwnedSlice;
19 use attr::{AttrMetaMethods, AttributeMethods};
20 use codemap::{CodeMap, BytePos};
24 use parse::lexer::comments;
26 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
27 use print::pp::{Breaks, Consistent, Inconsistent, eof};
31 use std::io::{IoResult, MemWriter};
35 pub enum AnnNode<'a> {
36 NodeIdent(&'a ast::Ident),
37 NodeName(&'a ast::Name),
38 NodeBlock(&'a ast::Block),
39 NodeItem(&'a ast::Item),
40 NodeExpr(&'a ast::Expr),
41 NodePat(&'a ast::Pat),
45 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
46 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
51 impl PpAnn for NoAnn {}
53 pub struct CurrentCommentAndLiteral {
58 pub struct State<'a> {
60 cm: Option<&'a CodeMap>,
61 comments: Option<Vec<comments::Comment> >,
62 literals: Option<Vec<comments::Literal> >,
63 cur_cmnt_and_lit: CurrentCommentAndLiteral,
64 boxes: Vec<pp::Breaks>,
66 encode_idents_with_hygiene: bool,
69 pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> {
70 static NO_ANN: NoAnn = NoAnn;
71 rust_printer_annotated(writer, &NO_ANN)
74 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>,
75 ann: &'a PpAnn) -> State<'a> {
77 s: pp::mk_printer(writer, default_columns),
81 cur_cmnt_and_lit: CurrentCommentAndLiteral {
87 encode_idents_with_hygiene: false,
91 pub static indent_unit: uint = 4u;
93 pub static default_columns: uint = 78u;
95 /// Requires you to pass an input filename and reader so that
96 /// it can scan the input text for comments and literals to
98 pub fn print_crate<'a>(cm: &'a CodeMap,
99 span_diagnostic: &diagnostic::SpanHandler,
102 input: &mut io::Reader,
103 out: Box<io::Writer+'static>,
105 is_expanded: bool) -> IoResult<()> {
106 let mut s = State::new_from_input(cm,
113 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
114 try!(s.print_remaining_comments());
119 pub fn new_from_input(cm: &'a CodeMap,
120 span_diagnostic: &diagnostic::SpanHandler,
122 input: &mut io::Reader,
123 out: Box<io::Writer+'static>,
125 is_expanded: bool) -> State<'a> {
126 let (cmnts, lits) = comments::gather_comments_and_literals(
136 // If the code is post expansion, don't use the table of
137 // literals, since it doesn't correspond with the literals
138 // in the AST anymore.
139 if is_expanded { None } else { Some(lits) })
142 pub fn new(cm: &'a CodeMap,
143 out: Box<io::Writer+'static>,
145 comments: Option<Vec<comments::Comment>>,
146 literals: Option<Vec<comments::Literal>>) -> State<'a> {
148 s: pp::mk_printer(out, default_columns),
152 cur_cmnt_and_lit: CurrentCommentAndLiteral {
158 encode_idents_with_hygiene: false,
163 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
164 use std::raw::TraitObject;
165 let mut s = rust_printer(box MemWriter::new());
167 eof(&mut s.s).unwrap();
169 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
170 // that we "know" to be a `MemWriter` that works around the lack of checked
172 let obj: TraitObject = mem::transmute_copy(&s.s.out);
173 let wr: Box<MemWriter> = mem::transmute(obj.data);
175 String::from_utf8(Vec::from_slice(wr.get_ref().as_slice())).unwrap();
181 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
182 // after we revise the syntax::ext::quote::ToToken impls to go directly
183 // to token-trees instead of thing -> string -> token-trees.
185 macro_rules! thing_to_string_impls {
186 ($to_string:ident) => {
188 pub fn ty_to_string(ty: &ast::Ty) -> String {
189 $to_string(|s| s.print_type(ty))
192 pub fn pat_to_string(pat: &ast::Pat) -> String {
193 $to_string(|s| s.print_pat(pat))
196 pub fn arm_to_string(arm: &ast::Arm) -> String {
197 $to_string(|s| s.print_arm(arm))
200 pub fn expr_to_string(e: &ast::Expr) -> String {
201 $to_string(|s| s.print_expr(e))
204 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
205 $to_string(|s| s.print_lifetime(e))
208 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
209 $to_string(|s| s.print_tt(tt))
212 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
213 $to_string(|s| s.print_tts(tts))
216 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
217 $to_string(|s| s.print_stmt(stmt))
220 pub fn item_to_string(i: &ast::Item) -> String {
221 $to_string(|s| s.print_item(i))
224 pub fn generics_to_string(generics: &ast::Generics) -> String {
225 $to_string(|s| s.print_generics(generics))
228 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
229 $to_string(|s| s.print_ty_method(p))
232 pub fn method_to_string(p: &ast::Method) -> String {
233 $to_string(|s| s.print_method(p))
236 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
237 $to_string(|s| s.print_fn_block_args(p, None))
240 pub fn path_to_string(p: &ast::Path) -> String {
241 $to_string(|s| s.print_path(p, false))
244 pub fn ident_to_string(id: &ast::Ident) -> String {
245 $to_string(|s| s.print_ident(*id))
248 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
249 opt_explicit_self: Option<ast::ExplicitSelf_>,
250 generics: &ast::Generics) -> String {
252 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
253 name, generics, opt_explicit_self, ast::Inherited));
254 try!(s.end()); // Close the head box
255 s.end() // Close the outer box
259 pub fn block_to_string(blk: &ast::Block) -> String {
261 // containing cbox, will be closed by print-block at }
262 try!(s.cbox(indent_unit));
263 // head-ibox, will be closed by print-block after {
269 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
270 $to_string(|s| s.print_meta_item(mi))
273 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
274 $to_string(|s| s.print_attribute(attr))
277 pub fn lit_to_string(l: &ast::Lit) -> String {
278 $to_string(|s| s.print_literal(l))
281 pub fn explicit_self_to_string(explicit_self: ast::ExplicitSelf_) -> String {
282 $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
285 pub fn variant_to_string(var: &ast::Variant) -> String {
286 $to_string(|s| s.print_variant(var))
289 pub fn arg_to_string(arg: &ast::Arg) -> String {
290 $to_string(|s| s.print_arg(arg))
293 pub fn mac_to_string(arg: &ast::Mac) -> String {
294 $to_string(|s| s.print_mac(arg))
299 thing_to_string_impls!(to_string)
301 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
302 // after we revise the syntax::ext::quote::ToToken impls to go directly
303 // to token-trees instea of thing -> string -> token-trees.
305 pub mod with_hygiene {
308 use std::io::IoResult;
309 use super::indent_unit;
311 // This function is the trick that all the rest of the routines
313 pub fn to_string_hyg(f: |&mut super::State| -> IoResult<()>) -> String {
314 super::to_string(|s| {
315 s.encode_idents_with_hygiene = true;
320 thing_to_string_impls!(to_string_hyg)
323 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
325 ast::Public => format!("pub {}", s),
326 ast::Inherited => s.to_string()
330 fn needs_parentheses(expr: &ast::Expr) -> bool {
332 ast::ExprAssign(..) | ast::ExprBinary(..) |
333 ast::ExprFnBlock(..) | ast::ExprProc(..) |
334 ast::ExprUnboxedFn(..) | ast::ExprAssignOp(..) |
335 ast::ExprCast(..) => true,
341 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
342 self.boxes.push(pp::Inconsistent);
343 pp::ibox(&mut self.s, u)
346 pub fn end(&mut self) -> IoResult<()> {
347 self.boxes.pop().unwrap();
351 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
352 self.boxes.push(pp::Consistent);
353 pp::cbox(&mut self.s, u)
357 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
359 pp::rbox(&mut self.s, u, b)
362 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
364 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
365 try!(word(&mut self.s, w));
369 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
370 try!(word(&mut self.s, w));
374 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
376 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
378 pub fn head(&mut self, w: &str) -> IoResult<()> {
379 // outer-box is consistent
380 try!(self.cbox(indent_unit));
381 // head-box is inconsistent
382 try!(self.ibox(w.len() + 1));
383 // keyword that starts the head
385 try!(self.word_nbsp(w));
390 pub fn bopen(&mut self) -> IoResult<()> {
391 try!(word(&mut self.s, "{"));
392 self.end() // close the head-box
395 pub fn bclose_(&mut self, span: codemap::Span,
396 indented: uint) -> IoResult<()> {
397 self.bclose_maybe_open(span, indented, true)
399 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
400 indented: uint, close_box: bool) -> IoResult<()> {
401 try!(self.maybe_print_comment(span.hi));
402 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
403 try!(word(&mut self.s, "}"));
405 try!(self.end()); // close the outer-box
409 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
410 self.bclose_(span, indent_unit)
413 pub fn is_begin(&mut self) -> bool {
414 match self.s.last_token() { pp::Begin(_) => true, _ => false }
417 pub fn is_end(&mut self) -> bool {
418 match self.s.last_token() { pp::End => true, _ => false }
421 // is this the beginning of a line?
422 pub fn is_bol(&mut self) -> bool {
423 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
426 pub fn in_cbox(&self) -> bool {
427 match self.boxes.last() {
428 Some(&last_box) => last_box == pp::Consistent,
433 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
435 try!(hardbreak(&mut self.s))
439 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
440 if !self.is_bol() { try!(space(&mut self.s)); }
443 pub fn break_offset_if_not_bol(&mut self, n: uint,
444 off: int) -> IoResult<()> {
446 break_offset(&mut self.s, n, off)
448 if off != 0 && self.s.last_token().is_hardbreak_tok() {
449 // We do something pretty sketchy here: tuck the nonzero
450 // offset-adjustment we were going to deposit along with the
451 // break into the previous hardbreak.
452 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
458 // Synthesizes a comment that was not textually present in the original source
460 pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
461 try!(word(&mut self.s, "/*"));
462 try!(space(&mut self.s));
463 try!(word(&mut self.s, text.as_slice()));
464 try!(space(&mut self.s));
465 word(&mut self.s, "*/")
468 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
469 op: |&mut State, &T| -> IoResult<()>)
471 try!(self.rbox(0u, b));
472 let mut first = true;
473 for elt in elts.iter() {
474 if first { first = false; } else { try!(self.word_space(",")); }
481 pub fn commasep_cmnt<T>(
485 op: |&mut State, &T| -> IoResult<()>,
486 get_span: |&T| -> codemap::Span) -> IoResult<()> {
487 try!(self.rbox(0u, b));
488 let len = elts.len();
490 for elt in elts.iter() {
491 try!(self.maybe_print_comment(get_span(elt).hi));
495 try!(word(&mut self.s, ","));
496 try!(self.maybe_print_trailing_comment(get_span(elt),
497 Some(get_span(&elts[i]).hi)));
498 try!(self.space_if_not_bol());
504 pub fn commasep_exprs(&mut self, b: Breaks,
505 exprs: &[Gc<ast::Expr>]) -> IoResult<()> {
506 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
509 pub fn print_mod(&mut self, _mod: &ast::Mod,
510 attrs: &[ast::Attribute]) -> IoResult<()> {
511 try!(self.print_inner_attributes(attrs));
512 for vitem in _mod.view_items.iter() {
513 try!(self.print_view_item(vitem));
515 for item in _mod.items.iter() {
516 try!(self.print_item(&**item));
521 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
522 attrs: &[ast::Attribute]) -> IoResult<()> {
523 try!(self.print_inner_attributes(attrs));
524 for vitem in nmod.view_items.iter() {
525 try!(self.print_view_item(vitem));
527 for item in nmod.items.iter() {
528 try!(self.print_foreign_item(&**item));
533 pub fn print_opt_lifetime(&mut self,
534 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
535 for l in lifetime.iter() {
536 try!(self.print_lifetime(l));
542 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
543 try!(self.maybe_print_comment(ty.span.lo));
546 ast::TyNil => try!(word(&mut self.s, "()")),
547 ast::TyBot => try!(word(&mut self.s, "!")),
548 ast::TyBox(ref ty) => {
549 try!(word(&mut self.s, "@"));
550 try!(self.print_type(&**ty));
552 ast::TyUniq(ref ty) => {
553 try!(word(&mut self.s, "~"));
554 try!(self.print_type(&**ty));
556 ast::TyVec(ref ty) => {
557 try!(word(&mut self.s, "["));
558 try!(self.print_type(&**ty));
559 try!(word(&mut self.s, "]"));
561 ast::TyPtr(ref mt) => {
562 try!(word(&mut self.s, "*"));
564 ast::MutMutable => try!(self.word_nbsp("mut")),
565 ast::MutImmutable => try!(self.word_nbsp("const")),
567 try!(self.print_type(&*mt.ty));
569 ast::TyRptr(ref lifetime, ref mt) => {
570 try!(word(&mut self.s, "&"));
571 try!(self.print_opt_lifetime(lifetime));
572 try!(self.print_mt(mt));
574 ast::TyTup(ref elts) => {
576 try!(self.commasep(Inconsistent, elts.as_slice(),
577 |s, ty| s.print_type_ref(ty)));
579 try!(word(&mut self.s, ","));
583 ast::TyParen(ref typ) => {
585 try!(self.print_type(&**typ));
588 ast::TyBareFn(f) => {
589 let generics = ast::Generics {
590 lifetimes: f.lifetimes.clone(),
591 ty_params: OwnedSlice::empty(),
592 where_clause: ast::WhereClause {
593 id: ast::DUMMY_NODE_ID,
594 predicates: Vec::new(),
597 try!(self.print_ty_fn(Some(f.abi),
603 &OwnedSlice::empty(),
608 ast::TyClosure(f) => {
609 let generics = ast::Generics {
610 lifetimes: f.lifetimes.clone(),
611 ty_params: OwnedSlice::empty(),
612 where_clause: ast::WhereClause {
613 id: ast::DUMMY_NODE_ID,
614 predicates: Vec::new(),
617 try!(self.print_ty_fn(None,
628 ast::TyProc(ref f) => {
629 let generics = ast::Generics {
630 lifetimes: f.lifetimes.clone(),
631 ty_params: OwnedSlice::empty(),
632 where_clause: ast::WhereClause {
633 id: ast::DUMMY_NODE_ID,
634 predicates: Vec::new(),
637 try!(self.print_ty_fn(None,
648 ast::TyUnboxedFn(f) => {
649 try!(self.print_ty_fn(None,
655 &OwnedSlice::empty(),
660 ast::TyPath(ref path, ref bounds, _) => {
661 try!(self.print_bounded_path(path, bounds));
663 ast::TyFixedLengthVec(ref ty, ref v) => {
664 try!(word(&mut self.s, "["));
665 try!(self.print_type(&**ty));
666 try!(word(&mut self.s, ", .."));
667 try!(self.print_expr(&**v));
668 try!(word(&mut self.s, "]"));
670 ast::TyTypeof(ref e) => {
671 try!(word(&mut self.s, "typeof("));
672 try!(self.print_expr(&**e));
673 try!(word(&mut self.s, ")"));
676 try!(word(&mut self.s, "_"));
682 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
683 self.print_type(&**ty)
686 pub fn print_foreign_item(&mut self,
687 item: &ast::ForeignItem) -> IoResult<()> {
688 try!(self.hardbreak_if_not_bol());
689 try!(self.maybe_print_comment(item.span.lo));
690 try!(self.print_outer_attributes(item.attrs.as_slice()));
692 ast::ForeignItemFn(ref decl, ref generics) => {
693 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
695 try!(self.end()); // end head-ibox
696 try!(word(&mut self.s, ";"));
697 self.end() // end the outer fn box
699 ast::ForeignItemStatic(ref t, m) => {
700 try!(self.head(visibility_qualified(item.vis,
701 "static").as_slice()));
703 try!(self.word_space("mut"));
705 try!(self.print_ident(item.ident));
706 try!(self.word_space(":"));
707 try!(self.print_type(&**t));
708 try!(word(&mut self.s, ";"));
709 try!(self.end()); // end the head-ibox
710 self.end() // end the outer cbox
715 /// Pretty-print an item
716 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
717 try!(self.hardbreak_if_not_bol());
718 try!(self.maybe_print_comment(item.span.lo));
719 try!(self.print_outer_attributes(item.attrs.as_slice()));
720 try!(self.ann.pre(self, NodeItem(item)));
722 ast::ItemStatic(ref ty, m, ref expr) => {
723 try!(self.head(visibility_qualified(item.vis,
724 "static").as_slice()));
725 if m == ast::MutMutable {
726 try!(self.word_space("mut"));
728 try!(self.print_ident(item.ident));
729 try!(self.word_space(":"));
730 try!(self.print_type(&**ty));
731 try!(space(&mut self.s));
732 try!(self.end()); // end the head-ibox
734 try!(self.word_space("="));
735 try!(self.print_expr(&**expr));
736 try!(word(&mut self.s, ";"));
737 try!(self.end()); // end the outer cbox
739 ast::ItemFn(ref decl, fn_style, abi, ref typarams, ref body) => {
749 try!(word(&mut self.s, " "));
750 try!(self.print_block_with_attrs(&**body, item.attrs.as_slice()));
752 ast::ItemMod(ref _mod) => {
753 try!(self.head(visibility_qualified(item.vis,
755 try!(self.print_ident(item.ident));
758 try!(self.print_mod(_mod, item.attrs.as_slice()));
759 try!(self.bclose(item.span));
761 ast::ItemForeignMod(ref nmod) => {
762 try!(self.head("extern"));
763 try!(self.word_nbsp(nmod.abi.to_string().as_slice()));
765 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
766 try!(self.bclose(item.span));
768 ast::ItemTy(ref ty, ref params) => {
769 try!(self.ibox(indent_unit));
771 try!(self.word_nbsp(visibility_qualified(item.vis,
772 "type").as_slice()));
773 try!(self.print_ident(item.ident));
774 try!(self.print_generics(params));
775 try!(self.end()); // end the inner ibox
777 try!(space(&mut self.s));
778 try!(self.word_space("="));
779 try!(self.print_type(&**ty));
780 try!(self.print_where_clause(params));
781 try!(word(&mut self.s, ";"));
782 try!(self.end()); // end the outer ibox
784 ast::ItemEnum(ref enum_definition, ref params) => {
785 try!(self.print_enum_def(
793 ast::ItemStruct(ref struct_def, ref generics) => {
794 if struct_def.is_virtual {
795 try!(self.word_space("virtual"));
797 try!(self.head(visibility_qualified(item.vis,
798 "struct").as_slice()));
799 try!(self.print_struct(&**struct_def, generics, item.ident,
803 ast::ItemImpl(ref generics,
807 try!(self.head(visibility_qualified(item.vis,
808 "impl").as_slice()));
809 if generics.is_parameterized() {
810 try!(self.print_generics(generics));
811 try!(space(&mut self.s));
816 try!(self.print_trait_ref(t));
817 try!(space(&mut self.s));
818 try!(self.word_space("for"));
823 try!(self.print_type(&**ty));
824 try!(self.print_where_clause(generics));
826 try!(space(&mut self.s));
828 try!(self.print_inner_attributes(item.attrs.as_slice()));
829 for impl_item in impl_items.iter() {
831 ast::MethodImplItem(meth) => {
832 try!(self.print_method(&*meth));
836 try!(self.bclose(item.span));
838 ast::ItemTrait(ref generics, ref unbound, ref bounds, ref methods) => {
839 try!(self.head(visibility_qualified(item.vis,
840 "trait").as_slice()));
841 try!(self.print_ident(item.ident));
842 try!(self.print_generics(generics));
844 &Some(TraitTyParamBound(ref tref)) => {
845 try!(space(&mut self.s));
846 try!(self.word_space("for"));
847 try!(self.print_trait_ref(tref));
848 try!(word(&mut self.s, "?"));
852 try!(self.print_bounds(":", bounds));
853 try!(self.print_where_clause(generics));
854 try!(word(&mut self.s, " "));
856 for meth in methods.iter() {
857 try!(self.print_trait_method(meth));
859 try!(self.bclose(item.span));
861 // I think it's reasonable to hide the context here:
862 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
864 try!(self.print_visibility(item.vis));
865 try!(self.print_path(pth, false));
866 try!(word(&mut self.s, "! "));
867 try!(self.print_ident(item.ident));
868 try!(self.cbox(indent_unit));
870 try!(self.print_tts(tts.as_slice()));
875 self.ann.post(self, NodeItem(item))
878 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
879 self.print_path(&t.path, false)
882 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
883 generics: &ast::Generics, ident: ast::Ident,
885 visibility: ast::Visibility) -> IoResult<()> {
886 try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
887 try!(self.print_ident(ident));
888 try!(self.print_generics(generics));
889 try!(self.print_where_clause(generics));
890 try!(space(&mut self.s));
891 self.print_variants(enum_definition.variants.as_slice(), span)
894 pub fn print_variants(&mut self,
895 variants: &[P<ast::Variant>],
896 span: codemap::Span) -> IoResult<()> {
898 for v in variants.iter() {
899 try!(self.space_if_not_bol());
900 try!(self.maybe_print_comment(v.span.lo));
901 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
902 try!(self.ibox(indent_unit));
903 try!(self.print_variant(&**v));
904 try!(word(&mut self.s, ","));
906 try!(self.maybe_print_trailing_comment(v.span, None));
911 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
913 ast::Public => self.word_nbsp("pub"),
914 ast::Inherited => Ok(())
918 pub fn print_struct(&mut self,
919 struct_def: &ast::StructDef,
920 generics: &ast::Generics,
922 span: codemap::Span) -> IoResult<()> {
923 try!(self.print_ident(ident));
924 try!(self.print_generics(generics));
925 match struct_def.super_struct {
927 try!(self.word_space(":"));
928 try!(self.print_type(&**t));
932 if ast_util::struct_def_is_tuple_like(struct_def) {
933 if !struct_def.fields.is_empty() {
936 Inconsistent, struct_def.fields.as_slice(),
938 match field.node.kind {
939 ast::NamedField(..) => fail!("unexpected named field"),
940 ast::UnnamedField(vis) => {
941 try!(s.print_visibility(vis));
942 try!(s.maybe_print_comment(field.span.lo));
943 s.print_type(&*field.node.ty)
950 try!(word(&mut self.s, ";"));
952 self.end() // close the outer-box
956 try!(self.hardbreak_if_not_bol());
958 for field in struct_def.fields.iter() {
959 match field.node.kind {
960 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
961 ast::NamedField(ident, visibility) => {
962 try!(self.hardbreak_if_not_bol());
963 try!(self.maybe_print_comment(field.span.lo));
964 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
965 try!(self.print_visibility(visibility));
966 try!(self.print_ident(ident));
967 try!(self.word_nbsp(":"));
968 try!(self.print_type(&*field.node.ty));
969 try!(word(&mut self.s, ","));
978 /// This doesn't deserve to be called "pretty" printing, but it should be
979 /// meaning-preserving. A quick hack that might help would be to look at the
980 /// spans embedded in the TTs to decide where to put spaces and newlines.
981 /// But it'd be better to parse these according to the grammar of the
982 /// appropriate macro, transcribe back into the grammar we just parsed from,
983 /// and then pretty-print the resulting AST nodes (so, e.g., we print
984 /// expression arguments as expressions). It can be done! I think.
985 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
987 ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
988 ast::TTTok(_, ref tk) => {
989 try!(word(&mut self.s, parse::token::to_string(tk).as_slice()));
991 parse::token::DOC_COMMENT(..) => {
992 hardbreak(&mut self.s)
997 ast::TTSeq(_, ref tts, ref sep, zerok) => {
998 try!(word(&mut self.s, "$("));
999 for tt_elt in (*tts).iter() {
1000 try!(self.print_tt(tt_elt));
1002 try!(word(&mut self.s, ")"));
1005 try!(word(&mut self.s,
1006 parse::token::to_string(tk).as_slice()));
1010 word(&mut self.s, if zerok { "*" } else { "+" })
1012 ast::TTNonterminal(_, name) => {
1013 try!(word(&mut self.s, "$"));
1014 self.print_ident(name)
1019 pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1021 for (i, tt) in tts.iter().enumerate() {
1023 try!(space(&mut self.s));
1025 try!(self.print_tt(tt));
1030 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1031 try!(self.print_visibility(v.node.vis));
1033 ast::TupleVariantKind(ref args) => {
1034 try!(self.print_ident(v.node.name));
1035 if !args.is_empty() {
1037 try!(self.commasep(Consistent,
1039 |s, arg| s.print_type(&*arg.ty)));
1040 try!(self.pclose());
1043 ast::StructVariantKind(ref struct_def) => {
1044 try!(self.head(""));
1045 let generics = ast_util::empty_generics();
1046 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1049 match v.node.disr_expr {
1051 try!(space(&mut self.s));
1052 try!(self.word_space("="));
1053 self.print_expr(&**d)
1059 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1060 try!(self.hardbreak_if_not_bol());
1061 try!(self.maybe_print_comment(m.span.lo));
1062 try!(self.print_outer_attributes(m.attrs.as_slice()));
1063 try!(self.print_ty_fn(None,
1069 &OwnedSlice::empty(),
1071 Some(m.explicit_self.node),
1073 word(&mut self.s, ";")
1076 pub fn print_trait_method(&mut self,
1077 m: &ast::TraitItem) -> IoResult<()> {
1079 RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1080 ProvidedMethod(ref m) => self.print_method(&**m)
1084 pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1086 MethodImplItem(ref m) => self.print_method(&**m),
1090 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1091 try!(self.hardbreak_if_not_bol());
1092 try!(self.maybe_print_comment(meth.span.lo));
1093 try!(self.print_outer_attributes(meth.attrs.as_slice()));
1095 ast::MethDecl(ident,
1103 try!(self.print_fn(&*decl,
1108 Some(explicit_self.node),
1110 try!(word(&mut self.s, " "));
1111 self.print_block_with_attrs(&*body, meth.attrs.as_slice())
1113 ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1115 // code copied from ItemMac:
1116 try!(self.print_path(pth, false));
1117 try!(word(&mut self.s, "! "));
1118 try!(self.cbox(indent_unit));
1120 try!(self.print_tts(tts.as_slice()));
1121 try!(self.pclose());
1127 pub fn print_outer_attributes(&mut self,
1128 attrs: &[ast::Attribute]) -> IoResult<()> {
1130 for attr in attrs.iter() {
1131 match attr.node.style {
1133 try!(self.print_attribute(attr));
1136 _ => {/* fallthrough */ }
1140 try!(self.hardbreak_if_not_bol());
1145 pub fn print_inner_attributes(&mut self,
1146 attrs: &[ast::Attribute]) -> IoResult<()> {
1148 for attr in attrs.iter() {
1149 match attr.node.style {
1151 try!(self.print_attribute(attr));
1154 _ => {/* fallthrough */ }
1158 try!(self.hardbreak_if_not_bol());
1163 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1164 try!(self.hardbreak_if_not_bol());
1165 try!(self.maybe_print_comment(attr.span.lo));
1166 if attr.node.is_sugared_doc {
1167 word(&mut self.s, attr.value_str().unwrap().get())
1169 match attr.node.style {
1170 ast::AttrInner => try!(word(&mut self.s, "#![")),
1171 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1173 try!(self.print_meta_item(&*attr.meta()));
1174 word(&mut self.s, "]")
1179 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1180 try!(self.maybe_print_comment(st.span.lo));
1182 ast::StmtDecl(ref decl, _) => {
1183 try!(self.print_decl(&**decl));
1185 ast::StmtExpr(ref expr, _) => {
1186 try!(self.space_if_not_bol());
1187 try!(self.print_expr(&**expr));
1189 ast::StmtSemi(ref expr, _) => {
1190 try!(self.space_if_not_bol());
1191 try!(self.print_expr(&**expr));
1192 try!(word(&mut self.s, ";"));
1194 ast::StmtMac(ref mac, semi) => {
1195 try!(self.space_if_not_bol());
1196 try!(self.print_mac(mac));
1198 try!(word(&mut self.s, ";"));
1202 if parse::classify::stmt_ends_with_semi(st) {
1203 try!(word(&mut self.s, ";"));
1205 self.maybe_print_trailing_comment(st.span, None)
1208 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1209 self.print_block_with_attrs(blk, &[])
1212 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1213 self.print_block_unclosed_indent(blk, indent_unit)
1216 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1217 indented: uint) -> IoResult<()> {
1218 self.print_block_maybe_unclosed(blk, indented, &[], false)
1221 pub fn print_block_with_attrs(&mut self,
1223 attrs: &[ast::Attribute]) -> IoResult<()> {
1224 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1227 pub fn print_block_maybe_unclosed(&mut self,
1230 attrs: &[ast::Attribute],
1231 close_box: bool) -> IoResult<()> {
1233 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1234 ast::DefaultBlock => ()
1236 try!(self.maybe_print_comment(blk.span.lo));
1237 try!(self.ann.pre(self, NodeBlock(blk)));
1240 try!(self.print_inner_attributes(attrs));
1242 for vi in blk.view_items.iter() {
1243 try!(self.print_view_item(vi));
1245 for st in blk.stmts.iter() {
1246 try!(self.print_stmt(&**st));
1250 try!(self.space_if_not_bol());
1251 try!(self.print_expr(&**expr));
1252 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1256 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1257 self.ann.post(self, NodeBlock(blk))
1260 fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1264 // "another else-if"
1265 ast::ExprIf(ref i, ref t, e) => {
1266 try!(self.cbox(indent_unit - 1u));
1267 try!(self.ibox(0u));
1268 try!(word(&mut self.s, " else if "));
1269 try!(self.print_expr(&**i));
1270 try!(space(&mut self.s));
1271 try!(self.print_block(&**t));
1275 ast::ExprBlock(ref b) => {
1276 try!(self.cbox(indent_unit - 1u));
1277 try!(self.ibox(0u));
1278 try!(word(&mut self.s, " else "));
1279 self.print_block(&**b)
1281 // BLEAH, constraints would be great here
1283 fail!("print_if saw if with weird alternative");
1291 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1292 elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1293 try!(self.head("if"));
1294 if chk { try!(self.word_nbsp("check")); }
1295 try!(self.print_expr(test));
1296 try!(space(&mut self.s));
1297 try!(self.print_block(blk));
1298 self.print_else(elseopt)
1301 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1303 // I think it's reasonable to hide the ctxt here:
1304 ast::MacInvocTT(ref pth, ref tts, _) => {
1305 try!(self.print_path(pth, false));
1306 try!(word(&mut self.s, "!"));
1308 try!(self.print_tts(tts.as_slice()));
1315 fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1317 try!(self.commasep_exprs(Inconsistent, args));
1321 pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1322 let needs_par = needs_parentheses(expr);
1326 try!(self.print_expr(expr));
1328 try!(self.pclose());
1333 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1334 try!(self.maybe_print_comment(expr.span.lo));
1335 try!(self.ibox(indent_unit));
1336 try!(self.ann.pre(self, NodeExpr(expr)));
1338 ast::ExprBox(ref p, ref e) => {
1339 try!(word(&mut self.s, "box"));
1340 try!(word(&mut self.s, "("));
1341 try!(self.print_expr(&**p));
1342 try!(self.word_space(")"));
1343 try!(self.print_expr(&**e));
1345 ast::ExprVec(ref exprs) => {
1346 try!(self.ibox(indent_unit));
1347 try!(word(&mut self.s, "["));
1348 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1349 try!(word(&mut self.s, "]"));
1353 ast::ExprRepeat(ref element, ref count) => {
1354 try!(self.ibox(indent_unit));
1355 try!(word(&mut self.s, "["));
1356 try!(self.print_expr(&**element));
1357 try!(word(&mut self.s, ","));
1358 try!(word(&mut self.s, ".."));
1359 try!(self.print_expr(&**count));
1360 try!(word(&mut self.s, "]"));
1364 ast::ExprStruct(ref path, ref fields, wth) => {
1365 try!(self.print_path(path, true));
1366 try!(word(&mut self.s, "{"));
1367 try!(self.commasep_cmnt(
1371 try!(s.ibox(indent_unit));
1372 try!(s.print_ident(field.ident.node));
1373 try!(s.word_space(":"));
1374 try!(s.print_expr(&*field.expr));
1380 try!(self.ibox(indent_unit));
1381 if !fields.is_empty() {
1382 try!(word(&mut self.s, ","));
1383 try!(space(&mut self.s));
1385 try!(word(&mut self.s, ".."));
1386 try!(self.print_expr(&**expr));
1389 _ => try!(word(&mut self.s, ","))
1391 try!(word(&mut self.s, "}"));
1393 ast::ExprTup(ref exprs) => {
1395 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1396 if exprs.len() == 1 {
1397 try!(word(&mut self.s, ","));
1399 try!(self.pclose());
1401 ast::ExprCall(ref func, ref args) => {
1402 try!(self.print_expr_maybe_paren(&**func));
1403 try!(self.print_call_post(args.as_slice()));
1405 ast::ExprMethodCall(ident, ref tys, ref args) => {
1406 let base_args = args.slice_from(1);
1407 try!(self.print_expr(&**args.get(0)));
1408 try!(word(&mut self.s, "."));
1409 try!(self.print_ident(ident.node));
1411 try!(word(&mut self.s, "::<"));
1412 try!(self.commasep(Inconsistent, tys.as_slice(),
1413 |s, ty| s.print_type_ref(ty)));
1414 try!(word(&mut self.s, ">"));
1416 try!(self.print_call_post(base_args));
1418 ast::ExprBinary(op, ref lhs, ref rhs) => {
1419 try!(self.print_expr(&**lhs));
1420 try!(space(&mut self.s));
1421 try!(self.word_space(ast_util::binop_to_string(op)));
1422 try!(self.print_expr(&**rhs));
1424 ast::ExprUnary(op, ref expr) => {
1425 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1426 try!(self.print_expr_maybe_paren(&**expr));
1428 ast::ExprAddrOf(m, ref expr) => {
1429 try!(word(&mut self.s, "&"));
1430 try!(self.print_mutability(m));
1431 try!(self.print_expr_maybe_paren(&**expr));
1433 ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1434 ast::ExprCast(ref expr, ref ty) => {
1435 try!(self.print_expr(&**expr));
1436 try!(space(&mut self.s));
1437 try!(self.word_space("as"));
1438 try!(self.print_type(&**ty));
1440 ast::ExprIf(ref test, ref blk, elseopt) => {
1441 try!(self.print_if(&**test, &**blk, elseopt, false));
1443 ast::ExprWhile(ref test, ref blk, opt_ident) => {
1444 for ident in opt_ident.iter() {
1445 try!(self.print_ident(*ident));
1446 try!(self.word_space(":"));
1448 try!(self.head("while"));
1449 try!(self.print_expr(&**test));
1450 try!(space(&mut self.s));
1451 try!(self.print_block(&**blk));
1453 ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1454 for ident in opt_ident.iter() {
1455 try!(self.print_ident(*ident));
1456 try!(self.word_space(":"));
1458 try!(self.head("for"));
1459 try!(self.print_pat(&**pat));
1460 try!(space(&mut self.s));
1461 try!(self.word_space("in"));
1462 try!(self.print_expr(&**iter));
1463 try!(space(&mut self.s));
1464 try!(self.print_block(&**blk));
1466 ast::ExprLoop(ref blk, opt_ident) => {
1467 for ident in opt_ident.iter() {
1468 try!(self.print_ident(*ident));
1469 try!(self.word_space(":"));
1471 try!(self.head("loop"));
1472 try!(space(&mut self.s));
1473 try!(self.print_block(&**blk));
1475 ast::ExprMatch(ref expr, ref arms) => {
1476 try!(self.cbox(indent_unit));
1478 try!(self.word_nbsp("match"));
1479 try!(self.print_expr(&**expr));
1480 try!(space(&mut self.s));
1482 for arm in arms.iter() {
1483 try!(self.print_arm(arm));
1485 try!(self.bclose_(expr.span, indent_unit));
1487 ast::ExprFnBlock(capture_clause, ref decl, ref body) => {
1488 try!(self.print_capture_clause(capture_clause));
1490 // in do/for blocks we don't want to show an empty
1491 // argument list, but at this point we don't know which
1494 // if !decl.inputs.is_empty() {
1495 try!(self.print_fn_block_args(&**decl, None));
1496 try!(space(&mut self.s));
1499 if !body.stmts.is_empty() || !body.expr.is_some() {
1500 try!(self.print_block_unclosed(&**body));
1502 // we extract the block, so as not to create another set of boxes
1503 match body.expr.unwrap().node {
1504 ast::ExprBlock(blk) => {
1505 try!(self.print_block_unclosed(&*blk));
1508 // this is a bare expression
1509 try!(self.print_expr(&*body.expr.unwrap()));
1510 try!(self.end()); // need to close a box
1514 // a box will be closed by print_expr, but we didn't want an overall
1515 // wrapper so we closed the corresponding opening. so create an
1516 // empty box to satisfy the close.
1519 ast::ExprUnboxedFn(capture_clause, kind, ref decl, ref body) => {
1520 try!(self.print_capture_clause(capture_clause));
1522 // in do/for blocks we don't want to show an empty
1523 // argument list, but at this point we don't know which
1526 // if !decl.inputs.is_empty() {
1527 try!(self.print_fn_block_args(&**decl, Some(kind)));
1528 try!(space(&mut self.s));
1531 if !body.stmts.is_empty() || !body.expr.is_some() {
1532 try!(self.print_block_unclosed(&**body));
1534 // we extract the block, so as not to create another set of boxes
1535 match body.expr.unwrap().node {
1536 ast::ExprBlock(ref blk) => {
1537 try!(self.print_block_unclosed(&**blk));
1540 // this is a bare expression
1541 try!(self.print_expr(&*body.expr.unwrap()));
1542 try!(self.end()); // need to close a box
1546 // a box will be closed by print_expr, but we didn't want an overall
1547 // wrapper so we closed the corresponding opening. so create an
1548 // empty box to satisfy the close.
1551 ast::ExprProc(ref decl, ref body) => {
1552 // in do/for blocks we don't want to show an empty
1553 // argument list, but at this point we don't know which
1556 // if !decl.inputs.is_empty() {
1557 try!(self.print_proc_args(&**decl));
1558 try!(space(&mut self.s));
1560 assert!(body.stmts.is_empty());
1561 assert!(body.expr.is_some());
1562 // we extract the block, so as not to create another set of boxes
1563 match body.expr.unwrap().node {
1564 ast::ExprBlock(ref blk) => {
1565 try!(self.print_block_unclosed(&**blk));
1568 // this is a bare expression
1569 try!(self.print_expr(&*body.expr.unwrap()));
1570 try!(self.end()); // need to close a box
1573 // a box will be closed by print_expr, but we didn't want an overall
1574 // wrapper so we closed the corresponding opening. so create an
1575 // empty box to satisfy the close.
1578 ast::ExprBlock(ref blk) => {
1579 // containing cbox, will be closed by print-block at }
1580 try!(self.cbox(indent_unit));
1581 // head-box, will be closed by print-block after {
1582 try!(self.ibox(0u));
1583 try!(self.print_block(&**blk));
1585 ast::ExprAssign(ref lhs, ref rhs) => {
1586 try!(self.print_expr(&**lhs));
1587 try!(space(&mut self.s));
1588 try!(self.word_space("="));
1589 try!(self.print_expr(&**rhs));
1591 ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1592 try!(self.print_expr(&**lhs));
1593 try!(space(&mut self.s));
1594 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1595 try!(self.word_space("="));
1596 try!(self.print_expr(&**rhs));
1598 ast::ExprField(ref expr, id, ref tys) => {
1599 try!(self.print_expr(&**expr));
1600 try!(word(&mut self.s, "."));
1601 try!(self.print_ident(id.node));
1603 try!(word(&mut self.s, "::<"));
1605 Inconsistent, tys.as_slice(),
1606 |s, ty| s.print_type_ref(ty)));
1607 try!(word(&mut self.s, ">"));
1610 ast::ExprIndex(ref expr, ref index) => {
1611 try!(self.print_expr(&**expr));
1612 try!(word(&mut self.s, "["));
1613 try!(self.print_expr(&**index));
1614 try!(word(&mut self.s, "]"));
1616 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1617 ast::ExprBreak(opt_ident) => {
1618 try!(word(&mut self.s, "break"));
1619 try!(space(&mut self.s));
1620 for ident in opt_ident.iter() {
1621 try!(self.print_ident(*ident));
1622 try!(space(&mut self.s));
1625 ast::ExprAgain(opt_ident) => {
1626 try!(word(&mut self.s, "continue"));
1627 try!(space(&mut self.s));
1628 for ident in opt_ident.iter() {
1629 try!(self.print_ident(*ident));
1630 try!(space(&mut self.s))
1633 ast::ExprRet(ref result) => {
1634 try!(word(&mut self.s, "return"));
1637 try!(word(&mut self.s, " "));
1638 try!(self.print_expr(&**expr));
1643 ast::ExprInlineAsm(ref a) => {
1645 try!(word(&mut self.s, "__volatile__ asm!"));
1647 try!(word(&mut self.s, "asm!"));
1650 try!(self.print_string(a.asm.get(), a.asm_str_style));
1651 try!(self.word_space(":"));
1653 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1654 |s, &(ref co, ref o, is_rw)| {
1655 match co.get().slice_shift_char() {
1656 (Some('='), operand) if is_rw => {
1657 try!(s.print_string(format!("+{}", operand).as_slice(),
1660 _ => try!(s.print_string(co.get(), ast::CookedStr))
1663 try!(s.print_expr(&**o));
1667 try!(space(&mut self.s));
1668 try!(self.word_space(":"));
1670 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1671 |s, &(ref co, ref o)| {
1672 try!(s.print_string(co.get(), ast::CookedStr));
1674 try!(s.print_expr(&**o));
1678 try!(space(&mut self.s));
1679 try!(self.word_space(":"));
1681 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1682 try!(self.pclose());
1684 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1685 ast::ExprParen(ref e) => {
1687 try!(self.print_expr(&**e));
1688 try!(self.pclose());
1691 try!(self.ann.post(self, NodeExpr(expr)));
1695 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1696 try!(self.print_pat(&*loc.pat));
1698 ast::TyInfer => Ok(()),
1700 try!(self.word_space(":"));
1701 self.print_type(&*loc.ty)
1706 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1707 try!(self.maybe_print_comment(decl.span.lo));
1709 ast::DeclLocal(ref loc) => {
1710 try!(self.space_if_not_bol());
1711 try!(self.ibox(indent_unit));
1712 try!(self.word_nbsp("let"));
1714 try!(self.ibox(indent_unit));
1715 try!(self.print_local_decl(&**loc));
1720 try!(self.word_space("="));
1721 try!(self.print_expr(&**init));
1727 ast::DeclItem(ref item) => self.print_item(&**item)
1731 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1732 if self.encode_idents_with_hygiene {
1733 let encoded = ident.encode_with_hygiene();
1734 try!(word(&mut self.s, encoded.as_slice()))
1736 try!(word(&mut self.s, token::get_ident(ident).get()))
1738 self.ann.post(self, NodeIdent(&ident))
1741 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1742 try!(word(&mut self.s, token::get_name(name).get()));
1743 self.ann.post(self, NodeName(&name))
1746 pub fn print_for_decl(&mut self, loc: &ast::Local,
1747 coll: &ast::Expr) -> IoResult<()> {
1748 try!(self.print_local_decl(loc));
1749 try!(space(&mut self.s));
1750 try!(self.word_space("in"));
1751 self.print_expr(coll)
1754 fn print_path_(&mut self,
1756 colons_before_params: bool,
1757 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1759 try!(self.maybe_print_comment(path.span.lo));
1761 try!(word(&mut self.s, "::"));
1764 let mut first = true;
1765 for segment in path.segments.iter() {
1769 try!(word(&mut self.s, "::"))
1772 try!(self.print_ident(segment.identifier));
1774 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1775 if colons_before_params {
1776 try!(word(&mut self.s, "::"))
1778 try!(word(&mut self.s, "<"));
1780 let mut comma = false;
1781 for lifetime in segment.lifetimes.iter() {
1783 try!(self.word_space(","))
1785 try!(self.print_lifetime(lifetime));
1789 if !segment.types.is_empty() {
1791 try!(self.word_space(","))
1795 segment.types.as_slice(),
1796 |s, ty| s.print_type_ref(ty)));
1799 try!(word(&mut self.s, ">"))
1805 Some(ref bounds) => self.print_bounds("+", bounds)
1809 fn print_path(&mut self, path: &ast::Path,
1810 colons_before_params: bool) -> IoResult<()> {
1811 self.print_path_(path, colons_before_params, &None)
1814 fn print_bounded_path(&mut self, path: &ast::Path,
1815 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1817 self.print_path_(path, false, bounds)
1820 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1821 try!(self.maybe_print_comment(pat.span.lo));
1822 try!(self.ann.pre(self, NodePat(pat)));
1823 /* Pat isn't normalized, but the beauty of it
1824 is that it doesn't matter */
1826 ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
1827 ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
1828 ast::PatIdent(binding_mode, ref path1, sub) => {
1829 match binding_mode {
1830 ast::BindByRef(mutbl) => {
1831 try!(self.word_nbsp("ref"));
1832 try!(self.print_mutability(mutbl));
1834 ast::BindByValue(ast::MutImmutable) => {}
1835 ast::BindByValue(ast::MutMutable) => {
1836 try!(self.word_nbsp("mut"));
1839 try!(self.print_ident(path1.node));
1842 try!(word(&mut self.s, "@"));
1843 try!(self.print_pat(&**p));
1848 ast::PatEnum(ref path, ref args_) => {
1849 try!(self.print_path(path, true));
1851 None => try!(word(&mut self.s, "(..)")),
1853 if !args.is_empty() {
1855 try!(self.commasep(Inconsistent, args.as_slice(),
1856 |s, p| s.print_pat(&**p)));
1857 try!(self.pclose());
1862 ast::PatStruct(ref path, ref fields, etc) => {
1863 try!(self.print_path(path, true));
1865 try!(self.word_space("{"));
1866 try!(self.commasep_cmnt(
1867 Consistent, fields.as_slice(),
1869 try!(s.cbox(indent_unit));
1870 try!(s.print_ident(f.ident));
1871 try!(s.word_nbsp(":"));
1872 try!(s.print_pat(&*f.pat));
1877 if fields.len() != 0u { try!(self.word_space(",")); }
1878 try!(word(&mut self.s, ".."));
1880 try!(space(&mut self.s));
1881 try!(word(&mut self.s, "}"));
1883 ast::PatTup(ref elts) => {
1885 try!(self.commasep(Inconsistent,
1887 |s, p| s.print_pat(&**p)));
1888 if elts.len() == 1 {
1889 try!(word(&mut self.s, ","));
1891 try!(self.pclose());
1893 ast::PatBox(ref inner) => {
1894 try!(word(&mut self.s, "box "));
1895 try!(self.print_pat(&**inner));
1897 ast::PatRegion(ref inner) => {
1898 try!(word(&mut self.s, "&"));
1899 try!(self.print_pat(&**inner));
1901 ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1902 ast::PatRange(ref begin, ref end) => {
1903 try!(self.print_expr(&**begin));
1904 try!(space(&mut self.s));
1905 try!(word(&mut self.s, ".."));
1906 try!(self.print_expr(&**end));
1908 ast::PatVec(ref before, slice, ref after) => {
1909 try!(word(&mut self.s, "["));
1910 try!(self.commasep(Inconsistent,
1912 |s, p| s.print_pat(&**p)));
1913 for p in slice.iter() {
1914 if !before.is_empty() { try!(self.word_space(",")); }
1915 try!(self.print_pat(&**p));
1917 ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
1918 // this case is handled by print_pat
1920 _ => try!(word(&mut self.s, "..")),
1922 if !after.is_empty() { try!(self.word_space(",")); }
1924 try!(self.commasep(Inconsistent,
1926 |s, p| s.print_pat(&**p)));
1927 try!(word(&mut self.s, "]"));
1929 ast::PatMac(ref m) => try!(self.print_mac(m)),
1931 self.ann.post(self, NodePat(pat))
1934 fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
1935 // I have no idea why this check is necessary, but here it
1937 if arm.attrs.is_empty() {
1938 try!(space(&mut self.s));
1940 try!(self.cbox(indent_unit));
1941 try!(self.ibox(0u));
1942 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1943 let mut first = true;
1944 for p in arm.pats.iter() {
1948 try!(space(&mut self.s));
1949 try!(self.word_space("|"));
1951 try!(self.print_pat(&**p));
1953 try!(space(&mut self.s));
1956 try!(self.word_space("if"));
1957 try!(self.print_expr(&**e));
1958 try!(space(&mut self.s));
1962 try!(self.word_space("=>"));
1964 match arm.body.node {
1965 ast::ExprBlock(ref blk) => {
1966 // the block will close the pattern's ibox
1967 try!(self.print_block_unclosed_indent(&**blk,
1971 try!(self.end()); // close the ibox for the pattern
1972 try!(self.print_expr(&*arm.body));
1973 try!(word(&mut self.s, ","));
1976 self.end() // close enclosing cbox
1979 // Returns whether it printed anything
1980 fn print_explicit_self(&mut self,
1981 explicit_self: ast::ExplicitSelf_,
1982 mutbl: ast::Mutability) -> IoResult<bool> {
1983 try!(self.print_mutability(mutbl));
1984 match explicit_self {
1985 ast::SelfStatic => { return Ok(false); }
1986 ast::SelfValue(_) => {
1987 try!(word(&mut self.s, "self"));
1989 ast::SelfRegion(ref lt, m, _) => {
1990 try!(word(&mut self.s, "&"));
1991 try!(self.print_opt_lifetime(lt));
1992 try!(self.print_mutability(m));
1993 try!(word(&mut self.s, "self"));
1995 ast::SelfExplicit(ref typ, _) => {
1996 try!(word(&mut self.s, "self"));
1997 try!(self.word_space(":"));
1998 try!(self.print_type(&**typ));
2004 pub fn print_fn(&mut self,
2006 fn_style: Option<ast::FnStyle>,
2009 generics: &ast::Generics,
2010 opt_explicit_self: Option<ast::ExplicitSelf_>,
2011 vis: ast::Visibility) -> IoResult<()> {
2012 try!(self.head(""));
2013 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
2015 try!(self.print_ident(name));
2016 try!(self.print_generics(generics));
2017 try!(self.print_fn_args_and_ret(decl, opt_explicit_self))
2018 self.print_where_clause(generics)
2021 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2022 opt_explicit_self: Option<ast::ExplicitSelf_>)
2024 // It is unfortunate to duplicate the commasep logic, but we want the
2025 // self type and the args all in the same box.
2026 try!(self.rbox(0u, Inconsistent));
2027 let mut first = true;
2028 for &explicit_self in opt_explicit_self.iter() {
2029 let m = match explicit_self {
2030 ast::SelfStatic => ast::MutImmutable,
2031 _ => match decl.inputs.get(0).pat.node {
2032 ast::PatIdent(ast::BindByValue(m), _, _) => m,
2033 _ => ast::MutImmutable
2036 first = !try!(self.print_explicit_self(explicit_self, m));
2039 // HACK(eddyb) ignore the separately printed self argument.
2040 let args = if first {
2041 decl.inputs.as_slice()
2043 decl.inputs.slice_from(1)
2046 for arg in args.iter() {
2047 if first { first = false; } else { try!(self.word_space(",")); }
2048 try!(self.print_arg(arg));
2054 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2055 opt_explicit_self: Option<ast::ExplicitSelf_>)
2058 try!(self.print_fn_args(decl, opt_explicit_self));
2060 try!(word(&mut self.s, ", ..."));
2062 try!(self.pclose());
2064 try!(self.maybe_print_comment(decl.output.span.lo));
2065 match decl.output.node {
2066 ast::TyNil => Ok(()),
2068 try!(self.space_if_not_bol());
2069 try!(self.word_space("->"));
2070 self.print_type(&*decl.output)
2075 pub fn print_fn_block_args(
2078 unboxed_closure_kind: Option<UnboxedClosureKind>)
2080 try!(word(&mut self.s, "|"));
2081 match unboxed_closure_kind {
2083 Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2084 Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2085 Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2087 try!(self.print_fn_args(decl, None));
2088 try!(word(&mut self.s, "|"));
2090 match decl.output.node {
2093 try!(self.space_if_not_bol());
2094 try!(self.word_space("->"));
2095 try!(self.print_type(&*decl.output));
2099 self.maybe_print_comment(decl.output.span.lo)
2102 pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2104 match capture_clause {
2105 ast::CaptureByValue => Ok(()),
2106 ast::CaptureByRef => self.word_space("ref"),
2110 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2111 try!(word(&mut self.s, "proc"));
2112 try!(word(&mut self.s, "("));
2113 try!(self.print_fn_args(decl, None));
2114 try!(word(&mut self.s, ")"));
2116 match decl.output.node {
2119 try!(self.space_if_not_bol());
2120 try!(self.word_space("->"));
2121 try!(self.print_type(&*decl.output));
2125 self.maybe_print_comment(decl.output.span.lo)
2128 pub fn print_bounds(&mut self,
2130 bounds: &OwnedSlice<ast::TyParamBound>)
2132 if !bounds.is_empty() {
2133 try!(word(&mut self.s, prefix));
2134 let mut first = true;
2135 for bound in bounds.iter() {
2140 try!(self.word_space("+"));
2144 TraitTyParamBound(ref tref) => {
2145 self.print_trait_ref(tref)
2147 RegionTyParamBound(ref lt) => {
2148 self.print_lifetime(lt)
2150 UnboxedFnTyParamBound(ref unboxed_function_type) => {
2151 self.print_ty_fn(None,
2155 &*unboxed_function_type.decl,
2157 &OwnedSlice::empty(),
2160 Some(unboxed_function_type.kind))
2170 pub fn print_lifetime(&mut self,
2171 lifetime: &ast::Lifetime)
2174 self.print_name(lifetime.name)
2177 pub fn print_lifetime_def(&mut self,
2178 lifetime: &ast::LifetimeDef)
2181 try!(self.print_lifetime(&lifetime.lifetime));
2183 for v in lifetime.bounds.iter() {
2184 try!(word(&mut self.s, sep));
2185 try!(self.print_lifetime(v));
2191 pub fn print_generics(&mut self,
2192 generics: &ast::Generics)
2195 let total = generics.lifetimes.len() + generics.ty_params.len();
2200 try!(word(&mut self.s, "<"));
2202 let mut ints = Vec::new();
2203 for i in range(0u, total) {
2207 try!(self.commasep(Inconsistent, ints.as_slice(), |s, &idx| {
2208 if idx < generics.lifetimes.len() {
2209 let lifetime = generics.lifetimes.get(idx);
2210 s.print_lifetime_def(lifetime)
2212 let idx = idx - generics.lifetimes.len();
2213 let param = generics.ty_params.get(idx);
2214 match param.unbound {
2215 Some(TraitTyParamBound(ref tref)) => {
2216 try!(s.print_trait_ref(tref));
2217 try!(s.word_space("?"));
2221 try!(s.print_ident(param.ident));
2222 try!(s.print_bounds(":", ¶m.bounds));
2223 match param.default {
2224 Some(ref default) => {
2225 try!(space(&mut s.s));
2226 try!(s.word_space("="));
2227 s.print_type(&**default)
2234 try!(word(&mut self.s, ">"));
2238 pub fn print_where_clause(&mut self, generics: &ast::Generics)
2240 if generics.where_clause.predicates.len() == 0 {
2244 try!(space(&mut self.s));
2245 try!(self.word_space("where"));
2247 for (i, predicate) in generics.where_clause
2252 try!(self.word_space(","));
2255 try!(self.print_ident(predicate.ident));
2256 try!(self.print_bounds(":", &predicate.bounds));
2262 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2263 try!(self.ibox(indent_unit));
2265 ast::MetaWord(ref name) => {
2266 try!(word(&mut self.s, name.get()));
2268 ast::MetaNameValue(ref name, ref value) => {
2269 try!(self.word_space(name.get()));
2270 try!(self.word_space("="));
2271 try!(self.print_literal(value));
2273 ast::MetaList(ref name, ref items) => {
2274 try!(word(&mut self.s, name.get()));
2276 try!(self.commasep(Consistent,
2278 |s, i| s.print_meta_item(&**i)));
2279 try!(self.pclose());
2285 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2287 ast::ViewPathSimple(ident, ref path, _) => {
2288 try!(self.print_path(path, false));
2290 // FIXME(#6993) can't compare identifiers directly here
2291 if path.segments.last().unwrap().identifier.name !=
2293 try!(space(&mut self.s));
2294 try!(self.word_space("as"));
2295 try!(self.print_ident(ident));
2301 ast::ViewPathGlob(ref path, _) => {
2302 try!(self.print_path(path, false));
2303 word(&mut self.s, "::*")
2306 ast::ViewPathList(ref path, ref idents, _) => {
2307 if path.segments.is_empty() {
2308 try!(word(&mut self.s, "{"));
2310 try!(self.print_path(path, false));
2311 try!(word(&mut self.s, "::{"));
2313 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2315 ast::PathListIdent { name, .. } => {
2318 ast::PathListMod { .. } => {
2319 word(&mut s.s, "mod")
2323 word(&mut self.s, "}")
2328 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2329 try!(self.hardbreak_if_not_bol());
2330 try!(self.maybe_print_comment(item.span.lo));
2331 try!(self.print_outer_attributes(item.attrs.as_slice()));
2332 try!(self.print_visibility(item.vis));
2334 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2335 try!(self.head("extern crate"));
2336 for &(ref p, style) in optional_path.iter() {
2337 try!(self.print_string(p.get(), style));
2338 try!(space(&mut self.s));
2339 try!(word(&mut self.s, "as"));
2340 try!(space(&mut self.s));
2342 try!(self.print_ident(id));
2345 ast::ViewItemUse(ref vp) => {
2346 try!(self.head("use"));
2347 try!(self.print_view_path(&**vp));
2350 try!(word(&mut self.s, ";"));
2351 try!(self.end()); // end inner head-block
2352 self.end() // end outer head-block
2355 pub fn print_mutability(&mut self,
2356 mutbl: ast::Mutability) -> IoResult<()> {
2358 ast::MutMutable => self.word_nbsp("mut"),
2359 ast::MutImmutable => Ok(()),
2363 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2364 try!(self.print_mutability(mt.mutbl));
2365 self.print_type(&*mt.ty)
2368 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2369 try!(self.ibox(indent_unit));
2370 match input.ty.node {
2371 ast::TyInfer => try!(self.print_pat(&*input.pat)),
2373 match input.pat.node {
2374 ast::PatIdent(_, ref path1, _) if
2376 parse::token::special_idents::invalid.name => {
2380 try!(self.print_pat(&*input.pat));
2381 try!(word(&mut self.s, ":"));
2382 try!(space(&mut self.s));
2385 try!(self.print_type(&*input.ty));
2391 pub fn print_ty_fn(&mut self,
2392 opt_abi: Option<abi::Abi>,
2393 opt_sigil: Option<char>,
2394 fn_style: ast::FnStyle,
2395 onceness: ast::Onceness,
2397 id: Option<ast::Ident>,
2398 bounds: &OwnedSlice<ast::TyParamBound>,
2399 generics: Option<&ast::Generics>,
2400 opt_explicit_self: Option<ast::ExplicitSelf_>,
2401 opt_unboxed_closure_kind:
2402 Option<ast::UnboxedClosureKind>)
2404 try!(self.ibox(indent_unit));
2406 // Duplicates the logic in `print_fn_header_info()`. This is because that
2407 // function prints the sigil in the wrong place. That should be fixed.
2408 if opt_sigil == Some('~') && onceness == ast::Once {
2409 try!(word(&mut self.s, "proc"));
2410 } else if opt_sigil == Some('&') {
2411 try!(self.print_fn_style(fn_style));
2412 try!(self.print_extern_opt_abi(opt_abi));
2413 try!(self.print_onceness(onceness));
2415 assert!(opt_sigil.is_none());
2416 try!(self.print_fn_style(fn_style));
2417 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2418 try!(self.print_onceness(onceness));
2419 if opt_unboxed_closure_kind.is_none() {
2420 try!(word(&mut self.s, "fn"));
2426 try!(word(&mut self.s, " "));
2427 try!(self.print_ident(id));
2432 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2433 try!(zerobreak(&mut self.s));
2435 if opt_unboxed_closure_kind.is_some() || opt_sigil == Some('&') {
2436 try!(word(&mut self.s, "|"));
2441 match opt_unboxed_closure_kind {
2442 Some(ast::FnUnboxedClosureKind) => {
2443 try!(word(&mut self.s, "&"));
2444 try!(self.word_space(":"));
2446 Some(ast::FnMutUnboxedClosureKind) => {
2447 try!(word(&mut self.s, "&mut"));
2448 try!(self.word_space(":"));
2450 Some(ast::FnOnceUnboxedClosureKind) => {
2451 try!(self.word_space(":"));
2456 try!(self.print_fn_args(decl, opt_explicit_self));
2458 if opt_unboxed_closure_kind.is_some() || opt_sigil == Some('&') {
2459 try!(word(&mut self.s, "|"));
2462 try!(word(&mut self.s, ", ..."));
2464 try!(self.pclose());
2467 try!(self.print_bounds(":", bounds));
2469 try!(self.maybe_print_comment(decl.output.span.lo));
2471 match decl.output.node {
2474 try!(self.space_if_not_bol());
2475 try!(self.ibox(indent_unit));
2476 try!(self.word_space("->"));
2477 if decl.cf == ast::NoReturn {
2478 try!(self.word_nbsp("!"));
2480 try!(self.print_type(&*decl.output));
2487 Some(generics) => try!(self.print_where_clause(generics)),
2494 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2495 next_pos: Option<BytePos>)
2497 let cm = match self.cm {
2501 match self.next_comment() {
2503 if (*cmnt).style != comments::Trailing { return Ok(()) }
2504 let span_line = cm.lookup_char_pos(span.hi);
2505 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2506 let mut next = (*cmnt).pos + BytePos(1);
2507 match next_pos { None => (), Some(p) => next = p }
2508 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2509 span_line.line == comment_line.line {
2510 try!(self.print_comment(cmnt));
2511 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2519 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2520 // If there aren't any remaining comments, then we need to manually
2521 // make sure there is a line break at the end.
2522 if self.next_comment().is_none() {
2523 try!(hardbreak(&mut self.s));
2526 match self.next_comment() {
2528 try!(self.print_comment(cmnt));
2529 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2537 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2538 try!(self.maybe_print_comment(lit.span.lo));
2539 match self.next_lit(lit.span.lo) {
2541 return word(&mut self.s, (*ltrl).lit.as_slice());
2546 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2547 ast::LitByte(byte) => {
2548 let mut res = String::from_str("b'");
2549 (byte as char).escape_default(|c| res.push_char(c));
2550 res.push_char('\'');
2551 word(&mut self.s, res.as_slice())
2553 ast::LitChar(ch) => {
2554 let mut res = String::from_str("'");
2555 ch.escape_default(|c| res.push_char(c));
2556 res.push_char('\'');
2557 word(&mut self.s, res.as_slice())
2559 ast::LitInt(i, t) => {
2561 ast::SignedIntLit(st, ast::Plus) => {
2563 ast_util::int_ty_to_string(st, Some(i as i64)).as_slice())
2565 ast::SignedIntLit(st, ast::Minus) => {
2567 ast_util::int_ty_to_string(st, Some(-(i as i64))).as_slice())
2569 ast::UnsignedIntLit(ut) => {
2570 word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
2572 ast::UnsuffixedIntLit(ast::Plus) => {
2573 word(&mut self.s, format!("{}", i).as_slice())
2575 ast::UnsuffixedIntLit(ast::Minus) => {
2576 word(&mut self.s, format!("-{}", i).as_slice())
2580 ast::LitFloat(ref f, t) => {
2585 ast_util::float_ty_to_string(t).as_slice()).as_slice())
2587 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2588 ast::LitNil => word(&mut self.s, "()"),
2589 ast::LitBool(val) => {
2590 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2592 ast::LitBinary(ref v) => {
2593 let escaped: String = v.iter().map(|&b| b as char).collect();
2594 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2599 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2600 match self.literals {
2602 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2603 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2604 if ltrl.pos > pos { return None; }
2605 self.cur_cmnt_and_lit.cur_lit += 1u;
2606 if ltrl.pos == pos { return Some(ltrl); }
2614 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2616 match self.next_comment() {
2618 if (*cmnt).pos < pos {
2619 try!(self.print_comment(cmnt));
2620 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2629 pub fn print_comment(&mut self,
2630 cmnt: &comments::Comment) -> IoResult<()> {
2632 comments::Mixed => {
2633 assert_eq!(cmnt.lines.len(), 1u);
2634 try!(zerobreak(&mut self.s));
2635 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2636 zerobreak(&mut self.s)
2638 comments::Isolated => {
2639 try!(self.hardbreak_if_not_bol());
2640 for line in cmnt.lines.iter() {
2641 // Don't print empty lines because they will end up as trailing
2643 if !line.is_empty() {
2644 try!(word(&mut self.s, line.as_slice()));
2646 try!(hardbreak(&mut self.s));
2650 comments::Trailing => {
2651 try!(word(&mut self.s, " "));
2652 if cmnt.lines.len() == 1u {
2653 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2654 hardbreak(&mut self.s)
2656 try!(self.ibox(0u));
2657 for line in cmnt.lines.iter() {
2658 if !line.is_empty() {
2659 try!(word(&mut self.s, line.as_slice()));
2661 try!(hardbreak(&mut self.s));
2666 comments::BlankLine => {
2667 // We need to do at least one, possibly two hardbreaks.
2668 let is_semi = match self.s.last_token() {
2669 pp::String(s, _) => ";" == s.as_slice(),
2672 if is_semi || self.is_begin() || self.is_end() {
2673 try!(hardbreak(&mut self.s));
2675 hardbreak(&mut self.s)
2680 pub fn print_string(&mut self, st: &str,
2681 style: ast::StrStyle) -> IoResult<()> {
2682 let st = match style {
2684 (format!("\"{}\"", st.escape_default()))
2687 (format!("r{delim}\"{string}\"{delim}",
2688 delim="#".repeat(n),
2692 word(&mut self.s, st.as_slice())
2695 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2696 match self.comments {
2697 Some(ref cmnts) => {
2698 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2699 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2708 pub fn print_opt_fn_style(&mut self,
2709 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2710 match opt_fn_style {
2711 Some(fn_style) => self.print_fn_style(fn_style),
2716 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2717 opt_abi: Option<abi::Abi>)
2720 Some(abi::Rust) => Ok(()),
2722 try!(self.word_nbsp("extern"));
2723 self.word_nbsp(abi.to_string().as_slice())
2729 pub fn print_extern_opt_abi(&mut self,
2730 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2733 try!(self.word_nbsp("extern"));
2734 self.word_nbsp(abi.to_string().as_slice())
2740 pub fn print_fn_header_info(&mut self,
2741 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2742 opt_fn_style: Option<ast::FnStyle>,
2744 vis: ast::Visibility) -> IoResult<()> {
2745 try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2746 try!(self.print_opt_fn_style(opt_fn_style));
2748 if abi != abi::Rust {
2749 try!(self.word_nbsp("extern"));
2750 try!(self.word_nbsp(abi.to_string().as_slice()));
2753 word(&mut self.s, "fn")
2756 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2758 ast::NormalFn => Ok(()),
2759 ast::UnsafeFn => self.word_nbsp("unsafe"),
2763 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2765 ast::Once => self.word_nbsp("once"),
2781 fn test_fun_to_string() {
2782 let abba_ident = token::str_to_ident("abba");
2784 let decl = ast::FnDecl {
2786 output: ast::P(ast::Ty {id: 0,
2788 span: codemap::DUMMY_SP}),
2792 let generics = ast_util::empty_generics();
2793 assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident,
2795 &"fn abba()".to_string());
2799 fn test_variant_to_string() {
2800 let ident = token::str_to_ident("principal_skinner");
2802 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2805 // making this up as I go.... ?
2806 kind: ast::TupleVariantKind(Vec::new()),
2812 let varstr = variant_to_string(&var);
2813 assert_eq!(&varstr,&"pub principal_skinner".to_string());