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, RegionTyParamBound, TraitTyParamBound, Required, Provided};
15 use owned_slice::OwnedSlice;
16 use attr::{AttrMetaMethods, AttributeMethods};
17 use codemap::{CodeMap, BytePos};
20 use parse::classify::expr_is_simple_block;
21 use parse::token::IdentInterner;
22 use parse::{comments, token};
24 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
25 use print::pp::{Breaks, Consistent, Inconsistent, eof};
30 use std::io::{IoResult, MemWriter};
34 use std::strbuf::StrBuf;
36 pub enum AnnNode<'a> {
37 NodeBlock(&'a ast::Block),
38 NodeItem(&'a ast::Item),
39 NodeExpr(&'a ast::Expr),
40 NodePat(&'a ast::Pat),
44 fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
45 fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
50 impl PpAnn for NoAnn {}
52 pub struct CurrentCommentAndLiteral {
57 pub struct State<'a> {
59 cm: Option<&'a CodeMap>,
60 intr: Rc<token::IdentInterner>,
61 comments: Option<Vec<comments::Comment> >,
62 literals: Option<Vec<comments::Literal> >,
63 cur_cmnt_and_lit: CurrentCommentAndLiteral,
64 boxes: Vec<pp::Breaks>,
68 pub fn rust_printer(writer: ~io::Writer) -> State<'static> {
69 static NO_ANN: NoAnn = NoAnn;
70 rust_printer_annotated(writer, &NO_ANN)
73 pub fn rust_printer_annotated<'a>(writer: ~io::Writer,
74 ann: &'a PpAnn) -> State<'a> {
76 s: pp::mk_printer(writer, default_columns),
78 intr: token::get_ident_interner(),
81 cur_cmnt_and_lit: CurrentCommentAndLiteral {
90 pub static indent_unit: uint = 4u;
92 pub static default_columns: uint = 78u;
94 // Requires you to pass an input filename and reader so that
95 // it can scan the input text for comments and literals to
97 pub fn print_crate<'a>(cm: &'a CodeMap,
98 span_diagnostic: &diagnostic::SpanHandler,
101 input: &mut io::Reader,
104 is_expanded: bool) -> IoResult<()> {
105 let (cmnts, lits) = comments::gather_comments_and_literals(
111 s: pp::mk_printer(out, default_columns),
113 intr: token::get_ident_interner(),
114 comments: Some(cmnts),
115 // If the code is post expansion, don't use the table of
116 // literals, since it doesn't correspond with the literals
117 // in the AST anymore.
118 literals: if is_expanded {
123 cur_cmnt_and_lit: CurrentCommentAndLiteral {
130 try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
131 try!(s.print_remaining_comments());
135 pub fn to_str(f: |&mut State| -> IoResult<()>) -> ~str {
136 let mut s = rust_printer(~MemWriter::new());
138 eof(&mut s.s).unwrap();
140 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
141 // that we "know" to be a `MemWriter` that works around the lack of checked
143 let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(&s.s.out);
144 let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap();
150 pub fn ty_to_str(ty: &ast::Ty) -> ~str {
151 to_str(|s| s.print_type(ty))
154 pub fn pat_to_str(pat: &ast::Pat) -> ~str {
155 to_str(|s| s.print_pat(pat))
158 pub fn expr_to_str(e: &ast::Expr) -> ~str {
159 to_str(|s| s.print_expr(e))
162 pub fn lifetime_to_str(e: &ast::Lifetime) -> ~str {
163 to_str(|s| s.print_lifetime(e))
166 pub fn tt_to_str(tt: &ast::TokenTree) -> ~str {
167 to_str(|s| s.print_tt(tt))
170 pub fn tts_to_str(tts: &[ast::TokenTree]) -> ~str {
171 to_str(|s| s.print_tts(&tts))
174 pub fn stmt_to_str(stmt: &ast::Stmt) -> ~str {
175 to_str(|s| s.print_stmt(stmt))
178 pub fn item_to_str(i: &ast::Item) -> ~str {
179 to_str(|s| s.print_item(i))
182 pub fn generics_to_str(generics: &ast::Generics) -> ~str {
183 to_str(|s| s.print_generics(generics))
186 pub fn ty_method_to_str(p: &ast::TypeMethod) -> ~str {
187 to_str(|s| s.print_ty_method(p))
190 pub fn method_to_str(p: &ast::Method) -> ~str {
191 to_str(|s| s.print_method(p))
194 pub fn fn_block_to_str(p: &ast::FnDecl) -> ~str {
195 to_str(|s| s.print_fn_block_args(p))
198 pub fn path_to_str(p: &ast::Path) -> ~str {
199 to_str(|s| s.print_path(p, false))
202 pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
203 opt_explicit_self: Option<ast::ExplicitSelf_>,
204 generics: &ast::Generics) -> ~str {
206 try!(s.print_fn(decl, Some(fn_style), abi::Rust,
207 name, generics, opt_explicit_self, ast::Inherited));
208 try!(s.end()); // Close the head box
209 s.end() // Close the outer box
213 pub fn block_to_str(blk: &ast::Block) -> ~str {
215 // containing cbox, will be closed by print-block at }
216 try!(s.cbox(indent_unit));
217 // head-ibox, will be closed by print-block after {
223 pub fn meta_item_to_str(mi: &ast::MetaItem) -> ~str {
224 to_str(|s| s.print_meta_item(mi))
227 pub fn attribute_to_str(attr: &ast::Attribute) -> ~str {
228 to_str(|s| s.print_attribute(attr))
231 pub fn lit_to_str(l: &ast::Lit) -> ~str {
232 to_str(|s| s.print_literal(l))
235 pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> ~str {
236 to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
239 pub fn variant_to_str(var: &ast::Variant) -> ~str {
240 to_str(|s| s.print_variant(var))
243 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str {
245 ast::Public => format!("pub {}", s),
246 ast::Inherited => s.to_owned()
251 pub fn ibox(&mut self, u: uint) -> IoResult<()> {
252 self.boxes.push(pp::Inconsistent);
253 pp::ibox(&mut self.s, u)
256 pub fn end(&mut self) -> IoResult<()> {
257 self.boxes.pop().unwrap();
261 pub fn cbox(&mut self, u: uint) -> IoResult<()> {
262 self.boxes.push(pp::Consistent);
263 pp::cbox(&mut self.s, u)
267 pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
269 pp::rbox(&mut self.s, u, b)
272 pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
274 pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
275 try!(word(&mut self.s, w));
279 pub fn word_space(&mut self, w: &str) -> IoResult<()> {
280 try!(word(&mut self.s, w));
284 pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
286 pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
288 pub fn head(&mut self, w: &str) -> IoResult<()> {
289 // outer-box is consistent
290 try!(self.cbox(indent_unit));
291 // head-box is inconsistent
292 try!(self.ibox(w.len() + 1));
293 // keyword that starts the head
295 try!(self.word_nbsp(w));
300 pub fn bopen(&mut self) -> IoResult<()> {
301 try!(word(&mut self.s, "{"));
302 self.end() // close the head-box
305 pub fn bclose_(&mut self, span: codemap::Span,
306 indented: uint) -> IoResult<()> {
307 self.bclose_maybe_open(span, indented, true)
309 pub fn bclose_maybe_open (&mut self, span: codemap::Span,
310 indented: uint, close_box: bool) -> IoResult<()> {
311 try!(self.maybe_print_comment(span.hi));
312 try!(self.break_offset_if_not_bol(1u, -(indented as int)));
313 try!(word(&mut self.s, "}"));
315 try!(self.end()); // close the outer-box
319 pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
320 self.bclose_(span, indent_unit)
323 pub fn is_begin(&mut self) -> bool {
324 match self.s.last_token() { pp::Begin(_) => true, _ => false }
327 pub fn is_end(&mut self) -> bool {
328 match self.s.last_token() { pp::End => true, _ => false }
331 pub fn is_bol(&mut self) -> bool {
332 self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
335 pub fn in_cbox(&self) -> bool {
336 match self.boxes.last() {
337 Some(&last_box) => last_box == pp::Consistent,
342 pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
344 try!(hardbreak(&mut self.s))
348 pub fn space_if_not_bol(&mut self) -> IoResult<()> {
349 if !self.is_bol() { try!(space(&mut self.s)); }
352 pub fn break_offset_if_not_bol(&mut self, n: uint,
353 off: int) -> IoResult<()> {
355 break_offset(&mut self.s, n, off)
357 if off != 0 && self.s.last_token().is_hardbreak_tok() {
358 // We do something pretty sketchy here: tuck the nonzero
359 // offset-adjustment we were going to deposit along with the
360 // break into the previous hardbreak.
361 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
367 // Synthesizes a comment that was not textually present in the original source
369 pub fn synth_comment(&mut self, text: ~str) -> IoResult<()> {
370 try!(word(&mut self.s, "/*"));
371 try!(space(&mut self.s));
372 try!(word(&mut self.s, text));
373 try!(space(&mut self.s));
374 word(&mut self.s, "*/")
377 pub fn commasep<T>(&mut self, b: Breaks, elts: &[T],
378 op: |&mut State, &T| -> IoResult<()>)
380 try!(self.rbox(0u, b));
381 let mut first = true;
382 for elt in elts.iter() {
383 if first { first = false; } else { try!(self.word_space(",")); }
390 pub fn commasep_cmnt<T>(
394 op: |&mut State, &T| -> IoResult<()>,
395 get_span: |&T| -> codemap::Span) -> IoResult<()> {
396 try!(self.rbox(0u, b));
397 let len = elts.len();
399 for elt in elts.iter() {
400 try!(self.maybe_print_comment(get_span(elt).hi));
404 try!(word(&mut self.s, ","));
405 try!(self.maybe_print_trailing_comment(get_span(elt),
406 Some(get_span(&elts[i]).hi)));
407 try!(self.space_if_not_bol());
413 pub fn commasep_exprs(&mut self, b: Breaks,
414 exprs: &[@ast::Expr]) -> IoResult<()> {
415 self.commasep_cmnt(b, exprs, |s, &e| s.print_expr(e), |e| e.span)
418 pub fn print_mod(&mut self, _mod: &ast::Mod,
419 attrs: &[ast::Attribute]) -> IoResult<()> {
420 try!(self.print_inner_attributes(attrs));
421 for vitem in _mod.view_items.iter() {
422 try!(self.print_view_item(vitem));
424 for item in _mod.items.iter() {
425 try!(self.print_item(*item));
430 pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
431 attrs: &[ast::Attribute]) -> IoResult<()> {
432 try!(self.print_inner_attributes(attrs));
433 for vitem in nmod.view_items.iter() {
434 try!(self.print_view_item(vitem));
436 for item in nmod.items.iter() {
437 try!(self.print_foreign_item(*item));
442 pub fn print_opt_lifetime(&mut self,
443 lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
444 for l in lifetime.iter() {
445 try!(self.print_lifetime(l));
451 pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
452 try!(self.maybe_print_comment(ty.span.lo));
455 ast::TyNil => try!(word(&mut self.s, "()")),
456 ast::TyBot => try!(word(&mut self.s, "!")),
458 try!(word(&mut self.s, "@"));
459 try!(self.print_type(ty));
462 try!(word(&mut self.s, "~"));
463 try!(self.print_type(ty));
466 try!(word(&mut self.s, "["));
467 try!(self.print_type(ty));
468 try!(word(&mut self.s, "]"));
470 ast::TyPtr(ref mt) => {
471 try!(word(&mut self.s, "*"));
472 try!(self.print_mt(mt));
474 ast::TyRptr(ref lifetime, ref mt) => {
475 try!(word(&mut self.s, "&"));
476 try!(self.print_opt_lifetime(lifetime));
477 try!(self.print_mt(mt));
479 ast::TyTup(ref elts) => {
481 try!(self.commasep(Inconsistent, elts.as_slice(),
482 |s, ty| s.print_type_ref(ty)));
484 try!(word(&mut self.s, ","));
488 ast::TyBareFn(f) => {
489 let generics = ast::Generics {
490 lifetimes: f.lifetimes.clone(),
491 ty_params: OwnedSlice::empty()
493 try!(self.print_ty_fn(Some(f.abi), None, &None,
494 f.fn_style, ast::Many, f.decl, None, &None,
495 Some(&generics), None));
497 ast::TyClosure(f, ref region) => {
498 let generics = ast::Generics {
499 lifetimes: f.lifetimes.clone(),
500 ty_params: OwnedSlice::empty()
502 try!(self.print_ty_fn(None, Some('&'), region, f.fn_style,
503 f.onceness, f.decl, None, &f.bounds,
504 Some(&generics), None));
507 let generics = ast::Generics {
508 lifetimes: f.lifetimes.clone(),
509 ty_params: OwnedSlice::empty()
511 try!(self.print_ty_fn(None, Some('~'), &None, f.fn_style,
512 f.onceness, f.decl, None, &f.bounds,
513 Some(&generics), None));
515 ast::TyPath(ref path, ref bounds, _) => {
516 try!(self.print_bounded_path(path, bounds));
518 ast::TyFixedLengthVec(ty, v) => {
519 try!(word(&mut self.s, "["));
520 try!(self.print_type(ty));
521 try!(word(&mut self.s, ", .."));
522 try!(self.print_expr(v));
523 try!(word(&mut self.s, "]"));
525 ast::TyTypeof(e) => {
526 try!(word(&mut self.s, "typeof("));
527 try!(self.print_expr(e));
528 try!(word(&mut self.s, ")"));
531 try!(word(&mut self.s, "_"));
537 pub fn print_type_ref(&mut self, ty: &P<ast::Ty>) -> IoResult<()> {
541 pub fn print_foreign_item(&mut self,
542 item: &ast::ForeignItem) -> IoResult<()> {
543 try!(self.hardbreak_if_not_bol());
544 try!(self.maybe_print_comment(item.span.lo));
545 try!(self.print_outer_attributes(item.attrs.as_slice()));
547 ast::ForeignItemFn(decl, ref generics) => {
548 try!(self.print_fn(decl, None, abi::Rust, item.ident, generics,
550 try!(self.end()); // end head-ibox
551 try!(word(&mut self.s, ";"));
552 self.end() // end the outer fn box
554 ast::ForeignItemStatic(t, m) => {
555 try!(self.head(visibility_qualified(item.vis, "static")));
557 try!(self.word_space("mut"));
559 try!(self.print_ident(item.ident));
560 try!(self.word_space(":"));
561 try!(self.print_type(t));
562 try!(word(&mut self.s, ";"));
563 try!(self.end()); // end the head-ibox
564 self.end() // end the outer cbox
569 pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
570 try!(self.hardbreak_if_not_bol());
571 try!(self.maybe_print_comment(item.span.lo));
572 try!(self.print_outer_attributes(item.attrs.as_slice()));
573 try!(self.ann.pre(self, NodeItem(item)));
575 ast::ItemStatic(ty, m, expr) => {
576 try!(self.head(visibility_qualified(item.vis, "static")));
577 if m == ast::MutMutable {
578 try!(self.word_space("mut"));
580 try!(self.print_ident(item.ident));
581 try!(self.word_space(":"));
582 try!(self.print_type(ty));
583 try!(space(&mut self.s));
584 try!(self.end()); // end the head-ibox
586 try!(self.word_space("="));
587 try!(self.print_expr(expr));
588 try!(word(&mut self.s, ";"));
589 try!(self.end()); // end the outer cbox
591 ast::ItemFn(decl, fn_style, abi, ref typarams, body) => {
601 try!(word(&mut self.s, " "));
602 try!(self.print_block_with_attrs(body, item.attrs.as_slice()));
604 ast::ItemMod(ref _mod) => {
605 try!(self.head(visibility_qualified(item.vis, "mod")));
606 try!(self.print_ident(item.ident));
609 try!(self.print_mod(_mod, item.attrs.as_slice()));
610 try!(self.bclose(item.span));
612 ast::ItemForeignMod(ref nmod) => {
613 try!(self.head("extern"));
614 try!(self.word_nbsp(nmod.abi.to_str()));
616 try!(self.print_foreign_mod(nmod, item.attrs.as_slice()));
617 try!(self.bclose(item.span));
619 ast::ItemTy(ty, ref params) => {
620 try!(self.ibox(indent_unit));
622 try!(self.word_nbsp(visibility_qualified(item.vis, "type")));
623 try!(self.print_ident(item.ident));
624 try!(self.print_generics(params));
625 try!(self.end()); // end the inner ibox
627 try!(space(&mut self.s));
628 try!(self.word_space("="));
629 try!(self.print_type(ty));
630 try!(word(&mut self.s, ";"));
631 try!(self.end()); // end the outer ibox
633 ast::ItemEnum(ref enum_definition, ref params) => {
634 try!(self.print_enum_def(
642 ast::ItemStruct(struct_def, ref generics) => {
643 try!(self.head(visibility_qualified(item.vis, "struct")));
644 try!(self.print_struct(struct_def, generics, item.ident, item.span));
647 ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
648 try!(self.head(visibility_qualified(item.vis, "impl")));
649 if generics.is_parameterized() {
650 try!(self.print_generics(generics));
651 try!(space(&mut self.s));
656 try!(self.print_trait_ref(t));
657 try!(space(&mut self.s));
658 try!(self.word_space("for"));
663 try!(self.print_type(ty));
665 try!(space(&mut self.s));
667 try!(self.print_inner_attributes(item.attrs.as_slice()));
668 for meth in methods.iter() {
669 try!(self.print_method(*meth));
671 try!(self.bclose(item.span));
673 ast::ItemTrait(ref generics, ref traits, ref methods) => {
674 try!(self.head(visibility_qualified(item.vis, "trait")));
675 try!(self.print_ident(item.ident));
676 try!(self.print_generics(generics));
677 if traits.len() != 0u {
678 try!(word(&mut self.s, ":"));
679 for (i, trait_) in traits.iter().enumerate() {
682 try!(self.word_space("+"));
684 try!(self.print_path(&trait_.path, false));
687 try!(word(&mut self.s, " "));
689 for meth in methods.iter() {
690 try!(self.print_trait_method(meth));
692 try!(self.bclose(item.span));
694 // I think it's reasonable to hide the context here:
695 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
697 try!(self.print_visibility(item.vis));
698 try!(self.print_path(pth, false));
699 try!(word(&mut self.s, "! "));
700 try!(self.print_ident(item.ident));
701 try!(self.cbox(indent_unit));
703 try!(self.print_tts(&(tts.as_slice())));
708 self.ann.post(self, NodeItem(item))
711 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
712 self.print_path(&t.path, false)
715 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
716 generics: &ast::Generics, ident: ast::Ident,
718 visibility: ast::Visibility) -> IoResult<()> {
719 try!(self.head(visibility_qualified(visibility, "enum")));
720 try!(self.print_ident(ident));
721 try!(self.print_generics(generics));
722 try!(space(&mut self.s));
723 self.print_variants(enum_definition.variants.as_slice(), span)
726 pub fn print_variants(&mut self,
727 variants: &[P<ast::Variant>],
728 span: codemap::Span) -> IoResult<()> {
730 for &v in variants.iter() {
731 try!(self.space_if_not_bol());
732 try!(self.maybe_print_comment(v.span.lo));
733 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
734 try!(self.ibox(indent_unit));
735 try!(self.print_variant(v));
736 try!(word(&mut self.s, ","));
738 try!(self.maybe_print_trailing_comment(v.span, None));
743 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
745 ast::Public => self.word_nbsp("pub"),
746 ast::Inherited => Ok(())
750 pub fn print_struct(&mut self,
751 struct_def: &ast::StructDef,
752 generics: &ast::Generics,
754 span: codemap::Span) -> IoResult<()> {
755 try!(self.print_ident(ident));
756 try!(self.print_generics(generics));
757 if ast_util::struct_def_is_tuple_like(struct_def) {
758 if !struct_def.fields.is_empty() {
761 Inconsistent, struct_def.fields.as_slice(),
763 match field.node.kind {
764 ast::NamedField(..) => fail!("unexpected named field"),
765 ast::UnnamedField(vis) => {
766 try!(s.print_visibility(vis));
767 try!(s.maybe_print_comment(field.span.lo));
768 s.print_type(field.node.ty)
775 try!(word(&mut self.s, ";"));
777 self.end() // close the outer-box
781 try!(self.hardbreak_if_not_bol());
783 for field in struct_def.fields.iter() {
784 match field.node.kind {
785 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
786 ast::NamedField(ident, visibility) => {
787 try!(self.hardbreak_if_not_bol());
788 try!(self.maybe_print_comment(field.span.lo));
789 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
790 try!(self.print_visibility(visibility));
791 try!(self.print_ident(ident));
792 try!(self.word_nbsp(":"));
793 try!(self.print_type(field.node.ty));
794 try!(word(&mut self.s, ","));
803 /// This doesn't deserve to be called "pretty" printing, but it should be
804 /// meaning-preserving. A quick hack that might help would be to look at the
805 /// spans embedded in the TTs to decide where to put spaces and newlines.
806 /// But it'd be better to parse these according to the grammar of the
807 /// appropriate macro, transcribe back into the grammar we just parsed from,
808 /// and then pretty-print the resulting AST nodes (so, e.g., we print
809 /// expression arguments as expressions). It can be done! I think.
810 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
812 ast::TTDelim(ref tts) => self.print_tts(&(tts.as_slice())),
813 ast::TTTok(_, ref tk) => {
814 word(&mut self.s, parse::token::to_str(tk))
816 ast::TTSeq(_, ref tts, ref sep, zerok) => {
817 try!(word(&mut self.s, "$("));
818 for tt_elt in (*tts).iter() {
819 try!(self.print_tt(tt_elt));
821 try!(word(&mut self.s, ")"));
824 try!(word(&mut self.s, parse::token::to_str(tk)));
828 word(&mut self.s, if zerok { "*" } else { "+" })
830 ast::TTNonterminal(_, name) => {
831 try!(word(&mut self.s, "$"));
832 self.print_ident(name)
837 pub fn print_tts(&mut self, tts: & &[ast::TokenTree]) -> IoResult<()> {
839 for (i, tt) in tts.iter().enumerate() {
841 try!(space(&mut self.s));
843 try!(self.print_tt(tt));
848 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
849 try!(self.print_visibility(v.node.vis));
851 ast::TupleVariantKind(ref args) => {
852 try!(self.print_ident(v.node.name));
853 if !args.is_empty() {
855 try!(self.commasep(Consistent,
857 |s, arg| s.print_type(arg.ty)));
861 ast::StructVariantKind(struct_def) => {
863 let generics = ast_util::empty_generics();
864 try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
867 match v.node.disr_expr {
869 try!(space(&mut self.s));
870 try!(self.word_space("="));
877 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
878 try!(self.hardbreak_if_not_bol());
879 try!(self.maybe_print_comment(m.span.lo));
880 try!(self.print_outer_attributes(m.attrs.as_slice()));
881 try!(self.print_ty_fn(None,
890 Some(m.explicit_self.node)));
891 word(&mut self.s, ";")
894 pub fn print_trait_method(&mut self,
895 m: &ast::TraitMethod) -> IoResult<()> {
897 Required(ref ty_m) => self.print_ty_method(ty_m),
898 Provided(m) => self.print_method(m)
902 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
903 try!(self.hardbreak_if_not_bol());
904 try!(self.maybe_print_comment(meth.span.lo));
905 try!(self.print_outer_attributes(meth.attrs.as_slice()));
906 try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
907 meth.ident, &meth.generics, Some(meth.explicit_self.node),
909 try!(word(&mut self.s, " "));
910 self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
913 pub fn print_outer_attributes(&mut self,
914 attrs: &[ast::Attribute]) -> IoResult<()> {
916 for attr in attrs.iter() {
917 match attr.node.style {
919 try!(self.print_attribute(attr));
922 _ => {/* fallthrough */ }
926 try!(self.hardbreak_if_not_bol());
931 pub fn print_inner_attributes(&mut self,
932 attrs: &[ast::Attribute]) -> IoResult<()> {
934 for attr in attrs.iter() {
935 match attr.node.style {
937 try!(self.print_attribute(attr));
940 _ => {/* fallthrough */ }
944 try!(self.hardbreak_if_not_bol());
949 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
950 try!(self.hardbreak_if_not_bol());
951 try!(self.maybe_print_comment(attr.span.lo));
952 if attr.node.is_sugared_doc {
953 word(&mut self.s, attr.value_str().unwrap().get())
955 match attr.node.style {
956 ast::AttrInner => try!(word(&mut self.s, "#![")),
957 ast::AttrOuter => try!(word(&mut self.s, "#[")),
959 try!(self.print_meta_item(attr.meta()));
960 word(&mut self.s, "]")
965 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
966 try!(self.maybe_print_comment(st.span.lo));
968 ast::StmtDecl(decl, _) => {
969 try!(self.print_decl(decl));
971 ast::StmtExpr(expr, _) => {
972 try!(self.space_if_not_bol());
973 try!(self.print_expr(expr));
975 ast::StmtSemi(expr, _) => {
976 try!(self.space_if_not_bol());
977 try!(self.print_expr(expr));
978 try!(word(&mut self.s, ";"));
980 ast::StmtMac(ref mac, semi) => {
981 try!(self.space_if_not_bol());
982 try!(self.print_mac(mac));
984 try!(word(&mut self.s, ";"));
988 if parse::classify::stmt_ends_with_semi(st) {
989 try!(word(&mut self.s, ";"));
991 self.maybe_print_trailing_comment(st.span, None)
994 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
995 self.print_block_with_attrs(blk, &[])
998 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
999 self.print_block_unclosed_indent(blk, indent_unit)
1002 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1003 indented: uint) -> IoResult<()> {
1004 self.print_block_maybe_unclosed(blk, indented, &[], false)
1007 pub fn print_block_with_attrs(&mut self,
1009 attrs: &[ast::Attribute]) -> IoResult<()> {
1010 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1013 pub fn print_block_maybe_unclosed(&mut self,
1016 attrs: &[ast::Attribute],
1017 close_box: bool) -> IoResult<()> {
1019 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1020 ast::DefaultBlock => ()
1022 try!(self.maybe_print_comment(blk.span.lo));
1023 try!(self.ann.pre(self, NodeBlock(blk)));
1026 try!(self.print_inner_attributes(attrs));
1028 for vi in blk.view_items.iter() {
1029 try!(self.print_view_item(vi));
1031 for st in blk.stmts.iter() {
1032 try!(self.print_stmt(*st));
1036 try!(self.space_if_not_bol());
1037 try!(self.print_expr(expr));
1038 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1042 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1043 self.ann.post(self, NodeBlock(blk))
1046 fn print_else(&mut self, els: Option<@ast::Expr>) -> IoResult<()> {
1050 // "another else-if"
1051 ast::ExprIf(i, t, e) => {
1052 try!(self.cbox(indent_unit - 1u));
1053 try!(self.ibox(0u));
1054 try!(word(&mut self.s, " else if "));
1055 try!(self.print_expr(i));
1056 try!(space(&mut self.s));
1057 try!(self.print_block(t));
1061 ast::ExprBlock(b) => {
1062 try!(self.cbox(indent_unit - 1u));
1063 try!(self.ibox(0u));
1064 try!(word(&mut self.s, " else "));
1067 // BLEAH, constraints would be great here
1069 fail!("print_if saw if with weird alternative");
1077 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1078 elseopt: Option<@ast::Expr>, chk: bool) -> IoResult<()> {
1079 try!(self.head("if"));
1080 if chk { try!(self.word_nbsp("check")); }
1081 try!(self.print_expr(test));
1082 try!(space(&mut self.s));
1083 try!(self.print_block(blk));
1084 self.print_else(elseopt)
1087 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1089 // I think it's reasonable to hide the ctxt here:
1090 ast::MacInvocTT(ref pth, ref tts, _) => {
1091 try!(self.print_path(pth, false));
1092 try!(word(&mut self.s, "!"));
1094 try!(self.print_tts(&tts.as_slice()));
1100 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1102 ast::ExprVstoreUniq => word(&mut self.s, "~"),
1103 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1104 ast::ExprVstoreMutSlice => {
1105 try!(word(&mut self.s, "&"));
1106 word(&mut self.s, "mut")
1111 fn print_call_post(&mut self, args: &[@ast::Expr]) -> IoResult<()> {
1113 try!(self.commasep_exprs(Inconsistent, args));
1117 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1118 try!(self.maybe_print_comment(expr.span.lo));
1119 try!(self.ibox(indent_unit));
1120 try!(self.ann.pre(self, NodeExpr(expr)));
1122 ast::ExprVstore(e, v) => {
1123 try!(self.print_expr_vstore(v));
1124 try!(self.print_expr(e));
1126 ast::ExprBox(p, e) => {
1127 try!(word(&mut self.s, "box"));
1128 try!(word(&mut self.s, "("));
1129 try!(self.print_expr(p));
1130 try!(self.word_space(")"));
1131 try!(self.print_expr(e));
1133 ast::ExprVec(ref exprs) => {
1134 try!(self.ibox(indent_unit));
1135 try!(word(&mut self.s, "["));
1136 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1137 try!(word(&mut self.s, "]"));
1141 ast::ExprRepeat(element, count) => {
1142 try!(self.ibox(indent_unit));
1143 try!(word(&mut self.s, "["));
1144 try!(self.print_expr(element));
1145 try!(word(&mut self.s, ","));
1146 try!(word(&mut self.s, ".."));
1147 try!(self.print_expr(count));
1148 try!(word(&mut self.s, "]"));
1152 ast::ExprStruct(ref path, ref fields, wth) => {
1153 try!(self.print_path(path, true));
1154 try!(word(&mut self.s, "{"));
1155 try!(self.commasep_cmnt(
1159 try!(s.ibox(indent_unit));
1160 try!(s.print_ident(field.ident.node));
1161 try!(s.word_space(":"));
1162 try!(s.print_expr(field.expr));
1168 try!(self.ibox(indent_unit));
1169 if !fields.is_empty() {
1170 try!(word(&mut self.s, ","));
1171 try!(space(&mut self.s));
1173 try!(word(&mut self.s, ".."));
1174 try!(self.print_expr(expr));
1177 _ => try!(word(&mut self.s, ","))
1179 try!(word(&mut self.s, "}"));
1181 ast::ExprTup(ref exprs) => {
1183 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1184 if exprs.len() == 1 {
1185 try!(word(&mut self.s, ","));
1187 try!(self.pclose());
1189 ast::ExprCall(func, ref args) => {
1190 try!(self.print_expr(func));
1191 try!(self.print_call_post(args.as_slice()));
1193 ast::ExprMethodCall(ident, ref tys, ref args) => {
1194 let base_args = args.slice_from(1);
1195 try!(self.print_expr(*args.get(0)));
1196 try!(word(&mut self.s, "."));
1197 try!(self.print_ident(ident));
1199 try!(word(&mut self.s, "::<"));
1200 try!(self.commasep(Inconsistent, tys.as_slice(),
1201 |s, ty| s.print_type_ref(ty)));
1202 try!(word(&mut self.s, ">"));
1204 try!(self.print_call_post(base_args));
1206 ast::ExprBinary(op, lhs, rhs) => {
1207 try!(self.print_expr(lhs));
1208 try!(space(&mut self.s));
1209 try!(self.word_space(ast_util::binop_to_str(op)));
1210 try!(self.print_expr(rhs));
1212 ast::ExprUnary(op, expr) => {
1213 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1214 try!(self.print_expr(expr));
1216 ast::ExprAddrOf(m, expr) => {
1217 try!(word(&mut self.s, "&"));
1218 try!(self.print_mutability(m));
1219 // Avoid `& &e` => `&&e`.
1220 match (m, &expr.node) {
1221 (ast::MutImmutable, &ast::ExprAddrOf(..)) => try!(space(&mut self.s)),
1224 try!(self.print_expr(expr));
1226 ast::ExprLit(lit) => try!(self.print_literal(lit)),
1227 ast::ExprCast(expr, ty) => {
1228 try!(self.print_expr(expr));
1229 try!(space(&mut self.s));
1230 try!(self.word_space("as"));
1231 try!(self.print_type(ty));
1233 ast::ExprIf(test, blk, elseopt) => {
1234 try!(self.print_if(test, blk, elseopt, false));
1236 ast::ExprWhile(test, blk) => {
1237 try!(self.head("while"));
1238 try!(self.print_expr(test));
1239 try!(space(&mut self.s));
1240 try!(self.print_block(blk));
1242 ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1243 for ident in opt_ident.iter() {
1244 try!(word(&mut self.s, "'"));
1245 try!(self.print_ident(*ident));
1246 try!(self.word_space(":"));
1248 try!(self.head("for"));
1249 try!(self.print_pat(pat));
1250 try!(space(&mut self.s));
1251 try!(self.word_space("in"));
1252 try!(self.print_expr(iter));
1253 try!(space(&mut self.s));
1254 try!(self.print_block(blk));
1256 ast::ExprLoop(blk, opt_ident) => {
1257 for ident in opt_ident.iter() {
1258 try!(word(&mut self.s, "'"));
1259 try!(self.print_ident(*ident));
1260 try!(self.word_space(":"));
1262 try!(self.head("loop"));
1263 try!(space(&mut self.s));
1264 try!(self.print_block(blk));
1266 ast::ExprMatch(expr, ref arms) => {
1267 try!(self.cbox(indent_unit));
1269 try!(self.word_nbsp("match"));
1270 try!(self.print_expr(expr));
1271 try!(space(&mut self.s));
1273 let len = arms.len();
1274 for (i, arm) in arms.iter().enumerate() {
1275 try!(space(&mut self.s));
1276 try!(self.cbox(indent_unit));
1277 try!(self.ibox(0u));
1278 let mut first = true;
1279 for p in arm.pats.iter() {
1283 try!(space(&mut self.s));
1284 try!(self.word_space("|"));
1286 try!(self.print_pat(*p));
1288 try!(space(&mut self.s));
1291 try!(self.word_space("if"));
1292 try!(self.print_expr(e));
1293 try!(space(&mut self.s));
1297 try!(self.word_space("=>"));
1299 match arm.body.node {
1300 ast::ExprBlock(blk) => {
1301 // the block will close the pattern's ibox
1302 try!(self.print_block_unclosed_indent(blk, indent_unit));
1305 try!(self.end()); // close the ibox for the pattern
1306 try!(self.print_expr(arm.body));
1309 if !expr_is_simple_block(expr)
1311 try!(word(&mut self.s, ","));
1313 try!(self.end()); // close enclosing cbox
1315 try!(self.bclose_(expr.span, indent_unit));
1317 ast::ExprFnBlock(decl, body) => {
1318 // in do/for blocks we don't want to show an empty
1319 // argument list, but at this point we don't know which
1322 // if !decl.inputs.is_empty() {
1323 try!(self.print_fn_block_args(decl));
1324 try!(space(&mut self.s));
1327 if !body.stmts.is_empty() || !body.expr.is_some() {
1328 try!(self.print_block_unclosed(body));
1330 // we extract the block, so as not to create another set of boxes
1331 match body.expr.unwrap().node {
1332 ast::ExprBlock(blk) => {
1333 try!(self.print_block_unclosed(blk));
1336 // this is a bare expression
1337 try!(self.print_expr(body.expr.unwrap()));
1338 try!(self.end()); // need to close a box
1342 // a box will be closed by print_expr, but we didn't want an overall
1343 // wrapper so we closed the corresponding opening. so create an
1344 // empty box to satisfy the close.
1347 ast::ExprProc(decl, body) => {
1348 // in do/for blocks we don't want to show an empty
1349 // argument list, but at this point we don't know which
1352 // if !decl.inputs.is_empty() {
1353 try!(self.print_proc_args(decl));
1354 try!(space(&mut self.s));
1356 assert!(body.stmts.is_empty());
1357 assert!(body.expr.is_some());
1358 // we extract the block, so as not to create another set of boxes
1359 match body.expr.unwrap().node {
1360 ast::ExprBlock(blk) => {
1361 try!(self.print_block_unclosed(blk));
1364 // this is a bare expression
1365 try!(self.print_expr(body.expr.unwrap()));
1366 try!(self.end()); // need to close a box
1369 // a box will be closed by print_expr, but we didn't want an overall
1370 // wrapper so we closed the corresponding opening. so create an
1371 // empty box to satisfy the close.
1374 ast::ExprBlock(blk) => {
1375 // containing cbox, will be closed by print-block at }
1376 try!(self.cbox(indent_unit));
1377 // head-box, will be closed by print-block after {
1378 try!(self.ibox(0u));
1379 try!(self.print_block(blk));
1381 ast::ExprAssign(lhs, rhs) => {
1382 try!(self.print_expr(lhs));
1383 try!(space(&mut self.s));
1384 try!(self.word_space("="));
1385 try!(self.print_expr(rhs));
1387 ast::ExprAssignOp(op, lhs, rhs) => {
1388 try!(self.print_expr(lhs));
1389 try!(space(&mut self.s));
1390 try!(word(&mut self.s, ast_util::binop_to_str(op)));
1391 try!(self.word_space("="));
1392 try!(self.print_expr(rhs));
1394 ast::ExprField(expr, id, ref tys) => {
1395 try!(self.print_expr(expr));
1396 try!(word(&mut self.s, "."));
1397 try!(self.print_ident(id));
1399 try!(word(&mut self.s, "::<"));
1401 Inconsistent, tys.as_slice(),
1402 |s, ty| s.print_type_ref(ty)));
1403 try!(word(&mut self.s, ">"));
1406 ast::ExprIndex(expr, index) => {
1407 try!(self.print_expr(expr));
1408 try!(word(&mut self.s, "["));
1409 try!(self.print_expr(index));
1410 try!(word(&mut self.s, "]"));
1412 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1413 ast::ExprBreak(opt_ident) => {
1414 try!(word(&mut self.s, "break"));
1415 try!(space(&mut self.s));
1416 for ident in opt_ident.iter() {
1417 try!(word(&mut self.s, "'"));
1418 try!(self.print_ident(*ident));
1419 try!(space(&mut self.s));
1422 ast::ExprAgain(opt_ident) => {
1423 try!(word(&mut self.s, "continue"));
1424 try!(space(&mut self.s));
1425 for ident in opt_ident.iter() {
1426 try!(word(&mut self.s, "'"));
1427 try!(self.print_ident(*ident));
1428 try!(space(&mut self.s))
1431 ast::ExprRet(result) => {
1432 try!(word(&mut self.s, "return"));
1435 try!(word(&mut self.s, " "));
1436 try!(self.print_expr(expr));
1441 ast::ExprInlineAsm(ref a) => {
1443 try!(word(&mut self.s, "__volatile__ asm!"));
1445 try!(word(&mut self.s, "asm!"));
1448 try!(self.print_string(a.asm.get(), a.asm_str_style));
1449 try!(self.word_space(":"));
1450 for &(ref co, o) in a.outputs.iter() {
1451 try!(self.print_string(co.get(), ast::CookedStr));
1453 try!(self.print_expr(o));
1454 try!(self.pclose());
1455 try!(self.word_space(","));
1457 try!(self.word_space(":"));
1458 for &(ref co, o) in a.inputs.iter() {
1459 try!(self.print_string(co.get(), ast::CookedStr));
1461 try!(self.print_expr(o));
1462 try!(self.pclose());
1463 try!(self.word_space(","));
1465 try!(self.word_space(":"));
1466 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1467 try!(self.pclose());
1469 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1470 ast::ExprParen(e) => {
1472 try!(self.print_expr(e));
1473 try!(self.pclose());
1476 try!(self.ann.post(self, NodeExpr(expr)));
1480 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1481 try!(self.print_pat(loc.pat));
1483 ast::TyInfer => Ok(()),
1485 try!(self.word_space(":"));
1486 self.print_type(loc.ty)
1491 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1492 try!(self.maybe_print_comment(decl.span.lo));
1494 ast::DeclLocal(loc) => {
1495 try!(self.space_if_not_bol());
1496 try!(self.ibox(indent_unit));
1497 try!(self.word_nbsp("let"));
1499 try!(self.ibox(indent_unit));
1500 try!(self.print_local_decl(loc));
1505 try!(self.word_space("="));
1506 try!(self.print_expr(init));
1512 ast::DeclItem(item) => self.print_item(item)
1516 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1517 word(&mut self.s, token::get_ident(ident).get())
1520 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1521 word(&mut self.s, token::get_name(name).get())
1524 pub fn print_for_decl(&mut self, loc: &ast::Local,
1525 coll: &ast::Expr) -> IoResult<()> {
1526 try!(self.print_local_decl(loc));
1527 try!(space(&mut self.s));
1528 try!(self.word_space("in"));
1529 self.print_expr(coll)
1532 fn print_path_(&mut self,
1534 colons_before_params: bool,
1535 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1537 try!(self.maybe_print_comment(path.span.lo));
1539 try!(word(&mut self.s, "::"));
1542 let mut first = true;
1543 for segment in path.segments.iter() {
1547 try!(word(&mut self.s, "::"))
1550 try!(self.print_ident(segment.identifier));
1552 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1553 if colons_before_params {
1554 try!(word(&mut self.s, "::"))
1556 try!(word(&mut self.s, "<"));
1558 let mut comma = false;
1559 for lifetime in segment.lifetimes.iter() {
1561 try!(self.word_space(","))
1563 try!(self.print_lifetime(lifetime));
1567 if !segment.types.is_empty() {
1569 try!(self.word_space(","))
1573 segment.types.as_slice(),
1574 |s, ty| s.print_type_ref(ty)));
1577 try!(word(&mut self.s, ">"))
1583 Some(ref bounds) => self.print_bounds(&None, bounds, true),
1587 fn print_path(&mut self, path: &ast::Path,
1588 colons_before_params: bool) -> IoResult<()> {
1589 self.print_path_(path, colons_before_params, &None)
1592 fn print_bounded_path(&mut self, path: &ast::Path,
1593 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1595 self.print_path_(path, false, bounds)
1598 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1599 try!(self.maybe_print_comment(pat.span.lo));
1600 try!(self.ann.pre(self, NodePat(pat)));
1601 /* Pat isn't normalized, but the beauty of it
1602 is that it doesn't matter */
1604 ast::PatWild => try!(word(&mut self.s, "_")),
1605 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1606 ast::PatIdent(binding_mode, ref path, sub) => {
1607 match binding_mode {
1608 ast::BindByRef(mutbl) => {
1609 try!(self.word_nbsp("ref"));
1610 try!(self.print_mutability(mutbl));
1612 ast::BindByValue(ast::MutImmutable) => {}
1613 ast::BindByValue(ast::MutMutable) => {
1614 try!(self.word_nbsp("mut"));
1617 try!(self.print_path(path, true));
1620 try!(word(&mut self.s, "@"));
1621 try!(self.print_pat(p));
1626 ast::PatEnum(ref path, ref args_) => {
1627 try!(self.print_path(path, true));
1629 None => try!(word(&mut self.s, "(..)")),
1631 if !args.is_empty() {
1633 try!(self.commasep(Inconsistent, args.as_slice(),
1634 |s, &p| s.print_pat(p)));
1635 try!(self.pclose());
1640 ast::PatStruct(ref path, ref fields, etc) => {
1641 try!(self.print_path(path, true));
1642 try!(word(&mut self.s, "{"));
1643 try!(self.commasep_cmnt(
1644 Consistent, fields.as_slice(),
1646 try!(s.cbox(indent_unit));
1647 try!(s.print_ident(f.ident));
1648 try!(s.word_space(":"));
1649 try!(s.print_pat(f.pat));
1654 if fields.len() != 0u { try!(self.word_space(",")); }
1655 try!(word(&mut self.s, ".."));
1657 try!(word(&mut self.s, "}"));
1659 ast::PatTup(ref elts) => {
1661 try!(self.commasep(Inconsistent,
1663 |s, &p| s.print_pat(p)));
1664 if elts.len() == 1 {
1665 try!(word(&mut self.s, ","));
1667 try!(self.pclose());
1669 ast::PatUniq(inner) => {
1670 try!(word(&mut self.s, "~"));
1671 try!(self.print_pat(inner));
1673 ast::PatRegion(inner) => {
1674 try!(word(&mut self.s, "&"));
1675 try!(self.print_pat(inner));
1677 ast::PatLit(e) => try!(self.print_expr(e)),
1678 ast::PatRange(begin, end) => {
1679 try!(self.print_expr(begin));
1680 try!(space(&mut self.s));
1681 try!(word(&mut self.s, ".."));
1682 try!(self.print_expr(end));
1684 ast::PatVec(ref before, slice, ref after) => {
1685 try!(word(&mut self.s, "["));
1686 try!(self.commasep(Inconsistent,
1688 |s, &p| s.print_pat(p)));
1689 for &p in slice.iter() {
1690 if !before.is_empty() { try!(self.word_space(",")); }
1692 ast::Pat { node: ast::PatWildMulti, .. } => {
1693 // this case is handled by print_pat
1695 _ => try!(word(&mut self.s, "..")),
1697 try!(self.print_pat(p));
1698 if !after.is_empty() { try!(self.word_space(",")); }
1700 try!(self.commasep(Inconsistent,
1702 |s, &p| s.print_pat(p)));
1703 try!(word(&mut self.s, "]"));
1706 self.ann.post(self, NodePat(pat))
1709 // Returns whether it printed anything
1710 fn print_explicit_self(&mut self,
1711 explicit_self: ast::ExplicitSelf_,
1712 mutbl: ast::Mutability) -> IoResult<bool> {
1713 try!(self.print_mutability(mutbl));
1714 match explicit_self {
1715 ast::SelfStatic => { return Ok(false); }
1717 try!(word(&mut self.s, "self"));
1720 try!(word(&mut self.s, "~self"));
1722 ast::SelfRegion(ref lt, m) => {
1723 try!(word(&mut self.s, "&"));
1724 try!(self.print_opt_lifetime(lt));
1725 try!(self.print_mutability(m));
1726 try!(word(&mut self.s, "self"));
1732 pub fn print_fn(&mut self,
1734 fn_style: Option<ast::FnStyle>,
1737 generics: &ast::Generics,
1738 opt_explicit_self: Option<ast::ExplicitSelf_>,
1739 vis: ast::Visibility) -> IoResult<()> {
1740 try!(self.head(""));
1741 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1743 try!(self.print_ident(name));
1744 try!(self.print_generics(generics));
1745 self.print_fn_args_and_ret(decl, opt_explicit_self)
1748 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1749 opt_explicit_self: Option<ast::ExplicitSelf_>)
1751 // It is unfortunate to duplicate the commasep logic, but we want the
1752 // self type and the args all in the same box.
1753 try!(self.rbox(0u, Inconsistent));
1754 let mut first = true;
1755 for &explicit_self in opt_explicit_self.iter() {
1756 let m = match explicit_self {
1757 ast::SelfStatic => ast::MutImmutable,
1758 _ => match decl.inputs.get(0).pat.node {
1759 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1760 _ => ast::MutImmutable
1763 first = !try!(self.print_explicit_self(explicit_self, m));
1766 // HACK(eddyb) ignore the separately printed self argument.
1767 let args = if first {
1768 decl.inputs.as_slice()
1770 decl.inputs.slice_from(1)
1773 for arg in args.iter() {
1774 if first { first = false; } else { try!(self.word_space(",")); }
1775 try!(self.print_arg(arg));
1781 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1782 opt_explicit_self: Option<ast::ExplicitSelf_>)
1785 try!(self.print_fn_args(decl, opt_explicit_self));
1787 try!(word(&mut self.s, ", ..."));
1789 try!(self.pclose());
1791 try!(self.maybe_print_comment(decl.output.span.lo));
1792 match decl.output.node {
1793 ast::TyNil => Ok(()),
1795 try!(self.space_if_not_bol());
1796 try!(self.word_space("->"));
1797 self.print_type(decl.output)
1802 pub fn print_fn_block_args(&mut self,
1803 decl: &ast::FnDecl) -> IoResult<()> {
1804 try!(word(&mut self.s, "|"));
1805 try!(self.print_fn_args(decl, None));
1806 try!(word(&mut self.s, "|"));
1808 match decl.output.node {
1811 try!(self.space_if_not_bol());
1812 try!(self.word_space("->"));
1813 try!(self.print_type(decl.output));
1817 self.maybe_print_comment(decl.output.span.lo)
1820 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1821 try!(word(&mut self.s, "proc"));
1822 try!(word(&mut self.s, "("));
1823 try!(self.print_fn_args(decl, None));
1824 try!(word(&mut self.s, ")"));
1826 match decl.output.node {
1829 try!(self.space_if_not_bol());
1830 try!(self.word_space("->"));
1831 try!(self.print_type(decl.output));
1835 self.maybe_print_comment(decl.output.span.lo)
1838 pub fn print_bounds(&mut self,
1839 region: &Option<ast::Lifetime>,
1840 bounds: &OwnedSlice<ast::TyParamBound>,
1841 print_colon_anyway: bool) -> IoResult<()> {
1842 if !bounds.is_empty() || region.is_some() {
1843 try!(word(&mut self.s, ":"));
1844 let mut first = true;
1847 let token = token::get_name(lt.name);
1848 if token.get() != "static" {
1851 try!(self.print_lifetime(lt));
1856 for bound in bounds.iter() {
1861 try!(self.word_space("+"));
1865 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
1866 RegionTyParamBound => word(&mut self.s, "'static"),
1870 } else if print_colon_anyway {
1871 word(&mut self.s, ":")
1877 pub fn print_lifetime(&mut self,
1878 lifetime: &ast::Lifetime) -> IoResult<()> {
1879 try!(word(&mut self.s, "'"));
1880 self.print_name(lifetime.name)
1883 pub fn print_generics(&mut self,
1884 generics: &ast::Generics) -> IoResult<()> {
1885 let total = generics.lifetimes.len() + generics.ty_params.len();
1887 try!(word(&mut self.s, "<"));
1889 let mut ints = Vec::new();
1890 for i in range(0u, total) {
1895 Inconsistent, ints.as_slice(),
1897 if idx < generics.lifetimes.len() {
1898 let lifetime = generics.lifetimes.get(idx);
1899 s.print_lifetime(lifetime)
1901 let idx = idx - generics.lifetimes.len();
1902 let param = generics.ty_params.get(idx);
1903 try!(s.print_ident(param.ident));
1904 try!(s.print_bounds(&None, ¶m.bounds, false));
1905 match param.default {
1907 try!(space(&mut s.s));
1908 try!(s.word_space("="));
1909 s.print_type(default)
1915 word(&mut self.s, ">")
1921 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
1922 try!(self.ibox(indent_unit));
1924 ast::MetaWord(ref name) => {
1925 try!(word(&mut self.s, name.get()));
1927 ast::MetaNameValue(ref name, ref value) => {
1928 try!(self.word_space(name.get()));
1929 try!(self.word_space("="));
1930 try!(self.print_literal(value));
1932 ast::MetaList(ref name, ref items) => {
1933 try!(word(&mut self.s, name.get()));
1935 try!(self.commasep(Consistent,
1937 |s, &i| s.print_meta_item(i)));
1938 try!(self.pclose());
1944 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
1946 ast::ViewPathSimple(ident, ref path, _) => {
1947 // FIXME(#6993) can't compare identifiers directly here
1948 if path.segments.last().unwrap().identifier.name != ident.name {
1949 try!(self.print_ident(ident));
1950 try!(space(&mut self.s));
1951 try!(self.word_space("="));
1953 self.print_path(path, false)
1956 ast::ViewPathGlob(ref path, _) => {
1957 try!(self.print_path(path, false));
1958 word(&mut self.s, "::*")
1961 ast::ViewPathList(ref path, ref idents, _) => {
1962 if path.segments.is_empty() {
1963 try!(word(&mut self.s, "{"));
1965 try!(self.print_path(path, false));
1966 try!(word(&mut self.s, "::{"));
1968 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
1969 s.print_ident(w.node.name)
1971 word(&mut self.s, "}")
1976 pub fn print_view_paths(&mut self,
1977 vps: &[@ast::ViewPath]) -> IoResult<()> {
1978 self.commasep(Inconsistent, vps, |s, &vp| s.print_view_path(vp))
1981 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
1982 try!(self.hardbreak_if_not_bol());
1983 try!(self.maybe_print_comment(item.span.lo));
1984 try!(self.print_outer_attributes(item.attrs.as_slice()));
1985 try!(self.print_visibility(item.vis));
1987 ast::ViewItemExternCrate(id, ref optional_path, _) => {
1988 try!(self.head("extern crate"));
1989 try!(self.print_ident(id));
1990 for &(ref p, style) in optional_path.iter() {
1991 try!(space(&mut self.s));
1992 try!(word(&mut self.s, "="));
1993 try!(space(&mut self.s));
1994 try!(self.print_string(p.get(), style));
1998 ast::ViewItemUse(ref vps) => {
1999 try!(self.head("use"));
2000 try!(self.print_view_paths(vps.as_slice()));
2003 try!(word(&mut self.s, ";"));
2004 try!(self.end()); // end inner head-block
2005 self.end() // end outer head-block
2008 pub fn print_mutability(&mut self,
2009 mutbl: ast::Mutability) -> IoResult<()> {
2011 ast::MutMutable => self.word_nbsp("mut"),
2012 ast::MutImmutable => Ok(()),
2016 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2017 try!(self.print_mutability(mt.mutbl));
2018 self.print_type(mt.ty)
2021 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2022 try!(self.ibox(indent_unit));
2023 match input.ty.node {
2024 ast::TyInfer => try!(self.print_pat(input.pat)),
2026 match input.pat.node {
2027 ast::PatIdent(_, ref path, _) if
2028 path.segments.len() == 1 &&
2029 path.segments.get(0).identifier.name ==
2030 parse::token::special_idents::invalid.name => {
2034 try!(self.print_pat(input.pat));
2035 try!(word(&mut self.s, ":"));
2036 try!(space(&mut self.s));
2039 try!(self.print_type(input.ty));
2045 pub fn print_ty_fn(&mut self,
2046 opt_abi: Option<abi::Abi>,
2047 opt_sigil: Option<char>,
2048 opt_region: &Option<ast::Lifetime>,
2049 fn_style: ast::FnStyle,
2050 onceness: ast::Onceness,
2052 id: Option<ast::Ident>,
2053 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2054 generics: Option<&ast::Generics>,
2055 opt_explicit_self: Option<ast::ExplicitSelf_>)
2057 try!(self.ibox(indent_unit));
2059 // Duplicates the logic in `print_fn_header_info()`. This is because that
2060 // function prints the sigil in the wrong place. That should be fixed.
2061 if opt_sigil == Some('~') && onceness == ast::Once {
2062 try!(word(&mut self.s, "proc"));
2063 } else if opt_sigil == Some('&') {
2064 try!(self.print_extern_opt_abi(opt_abi));
2065 try!(self.print_fn_style(fn_style));
2066 try!(self.print_onceness(onceness));
2068 assert!(opt_sigil.is_none());
2069 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2070 try!(self.print_fn_style(fn_style));
2071 try!(self.print_onceness(onceness));
2072 try!(word(&mut self.s, "fn"));
2077 try!(word(&mut self.s, " "));
2078 try!(self.print_ident(id));
2083 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2084 try!(zerobreak(&mut self.s));
2086 if opt_sigil == Some('&') {
2087 try!(word(&mut self.s, "|"));
2092 try!(self.print_fn_args(decl, opt_explicit_self));
2094 if opt_sigil == Some('&') {
2095 try!(word(&mut self.s, "|"));
2098 try!(word(&mut self.s, ", ..."));
2100 try!(self.pclose());
2103 opt_bounds.as_ref().map(|bounds| {
2104 self.print_bounds(opt_region, bounds, true)
2107 try!(self.maybe_print_comment(decl.output.span.lo));
2109 match decl.output.node {
2112 try!(self.space_if_not_bol());
2113 try!(self.ibox(indent_unit));
2114 try!(self.word_space("->"));
2115 if decl.cf == ast::NoReturn {
2116 try!(self.word_nbsp("!"));
2118 try!(self.print_type(decl.output));
2127 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2128 next_pos: Option<BytePos>)
2130 let cm = match self.cm {
2134 match self.next_comment() {
2136 if (*cmnt).style != comments::Trailing { return Ok(()) }
2137 let span_line = cm.lookup_char_pos(span.hi);
2138 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2139 let mut next = (*cmnt).pos + BytePos(1);
2140 match next_pos { None => (), Some(p) => next = p }
2141 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2142 span_line.line == comment_line.line {
2143 try!(self.print_comment(cmnt));
2144 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2152 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2153 // If there aren't any remaining comments, then we need to manually
2154 // make sure there is a line break at the end.
2155 if self.next_comment().is_none() {
2156 try!(hardbreak(&mut self.s));
2159 match self.next_comment() {
2161 try!(self.print_comment(cmnt));
2162 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2170 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2171 try!(self.maybe_print_comment(lit.span.lo));
2172 match self.next_lit(lit.span.lo) {
2174 return word(&mut self.s, (*ltrl).lit);
2179 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2180 ast::LitChar(ch) => {
2181 let mut res = StrBuf::from_str("'");
2182 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2183 res.push_char('\'');
2184 word(&mut self.s, res.into_owned())
2186 ast::LitInt(i, t) => {
2187 word(&mut self.s, ast_util::int_ty_to_str(t, Some(i)))
2189 ast::LitUint(u, t) => {
2190 word(&mut self.s, ast_util::uint_ty_to_str(t, Some(u)))
2192 ast::LitIntUnsuffixed(i) => {
2193 word(&mut self.s, format!("{}", i))
2195 ast::LitFloat(ref f, t) => {
2196 word(&mut self.s, f.get() + ast_util::float_ty_to_str(t))
2198 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2199 ast::LitNil => word(&mut self.s, "()"),
2200 ast::LitBool(val) => {
2201 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2203 ast::LitBinary(ref arr) => {
2204 try!(self.ibox(indent_unit));
2205 try!(word(&mut self.s, "["));
2206 try!(self.commasep_cmnt(Inconsistent, arr.as_slice(),
2207 |s, u| word(&mut s.s, format!("{}", *u)),
2209 try!(word(&mut self.s, "]"));
2215 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2216 match self.literals {
2218 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2219 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2220 if ltrl.pos > pos { return None; }
2221 self.cur_cmnt_and_lit.cur_lit += 1u;
2222 if ltrl.pos == pos { return Some(ltrl); }
2230 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2232 match self.next_comment() {
2234 if (*cmnt).pos < pos {
2235 try!(self.print_comment(cmnt));
2236 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2245 pub fn print_comment(&mut self,
2246 cmnt: &comments::Comment) -> IoResult<()> {
2248 comments::Mixed => {
2249 assert_eq!(cmnt.lines.len(), 1u);
2250 try!(zerobreak(&mut self.s));
2251 try!(word(&mut self.s, *cmnt.lines.get(0)));
2252 zerobreak(&mut self.s)
2254 comments::Isolated => {
2255 try!(self.hardbreak_if_not_bol());
2256 for line in cmnt.lines.iter() {
2257 // Don't print empty lines because they will end up as trailing
2259 if !line.is_empty() {
2260 try!(word(&mut self.s, *line));
2262 try!(hardbreak(&mut self.s));
2266 comments::Trailing => {
2267 try!(word(&mut self.s, " "));
2268 if cmnt.lines.len() == 1u {
2269 try!(word(&mut self.s, *cmnt.lines.get(0)));
2270 hardbreak(&mut self.s)
2272 try!(self.ibox(0u));
2273 for line in cmnt.lines.iter() {
2274 if !line.is_empty() {
2275 try!(word(&mut self.s, *line));
2277 try!(hardbreak(&mut self.s));
2282 comments::BlankLine => {
2283 // We need to do at least one, possibly two hardbreaks.
2284 let is_semi = match self.s.last_token() {
2285 pp::String(s, _) => ";" == s,
2288 if is_semi || self.is_begin() || self.is_end() {
2289 try!(hardbreak(&mut self.s));
2291 hardbreak(&mut self.s)
2296 pub fn print_string(&mut self, st: &str,
2297 style: ast::StrStyle) -> IoResult<()> {
2298 let st = match style {
2299 ast::CookedStr => format!("\"{}\"", st.escape_default()),
2300 ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2301 delim="#".repeat(n), string=st)
2303 word(&mut self.s, st)
2306 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2307 match self.comments {
2308 Some(ref cmnts) => {
2309 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2310 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2319 pub fn print_opt_fn_style(&mut self,
2320 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2321 match opt_fn_style {
2322 Some(fn_style) => self.print_fn_style(fn_style),
2327 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2328 opt_abi: Option<abi::Abi>)
2331 Some(abi::Rust) => Ok(()),
2333 try!(self.word_nbsp("extern"));
2334 self.word_nbsp(abi.to_str())
2340 pub fn print_extern_opt_abi(&mut self,
2341 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2344 try!(self.word_nbsp("extern"));
2345 self.word_nbsp(abi.to_str())
2351 pub fn print_fn_header_info(&mut self,
2352 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2353 opt_fn_style: Option<ast::FnStyle>,
2355 vis: ast::Visibility) -> IoResult<()> {
2356 try!(word(&mut self.s, visibility_qualified(vis, "")));
2358 if abi != abi::Rust {
2359 try!(self.word_nbsp("extern"));
2360 try!(self.word_nbsp(abi.to_str()));
2362 if opt_fn_style != Some(ast::ExternFn) {
2363 try!(self.print_opt_fn_style(opt_fn_style));
2366 try!(self.print_opt_fn_style(opt_fn_style));
2369 word(&mut self.s, "fn")
2372 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2374 ast::NormalFn => Ok(()),
2375 ast::UnsafeFn => self.word_nbsp("unsafe"),
2376 ast::ExternFn => self.word_nbsp("extern")
2380 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2382 ast::Once => self.word_nbsp("once"),
2398 fn test_fun_to_str() {
2399 let abba_ident = token::str_to_ident("abba");
2401 let decl = ast::FnDecl {
2403 output: ast::P(ast::Ty {id: 0,
2405 span: codemap::DUMMY_SP}),
2409 let generics = ast_util::empty_generics();
2410 assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2416 fn test_variant_to_str() {
2417 let ident = token::str_to_ident("principal_skinner");
2419 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2422 // making this up as I go.... ?
2423 kind: ast::TupleVariantKind(Vec::new()),
2429 let varstr = variant_to_str(&var);
2430 assert_eq!(&varstr,&~"pub principal_skinner");