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 if struct_def.is_virtual {
644 try!(self.word_space("virtual"));
646 try!(self.head(visibility_qualified(item.vis, "struct")));
647 try!(self.print_struct(struct_def, generics, item.ident, item.span));
650 ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
651 try!(self.head(visibility_qualified(item.vis, "impl")));
652 if generics.is_parameterized() {
653 try!(self.print_generics(generics));
654 try!(space(&mut self.s));
659 try!(self.print_trait_ref(t));
660 try!(space(&mut self.s));
661 try!(self.word_space("for"));
666 try!(self.print_type(ty));
668 try!(space(&mut self.s));
670 try!(self.print_inner_attributes(item.attrs.as_slice()));
671 for meth in methods.iter() {
672 try!(self.print_method(*meth));
674 try!(self.bclose(item.span));
676 ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => {
677 try!(self.head(visibility_qualified(item.vis, "trait")));
678 try!(self.print_ident(item.ident));
679 try!(self.print_generics(generics));
680 if *sized == ast::DynSize {
681 try!(space(&mut self.s));
682 try!(word(&mut self.s, "for type"));
684 if traits.len() != 0u {
685 try!(word(&mut self.s, ":"));
686 for (i, trait_) in traits.iter().enumerate() {
689 try!(self.word_space("+"));
691 try!(self.print_path(&trait_.path, false));
694 try!(word(&mut self.s, " "));
696 for meth in methods.iter() {
697 try!(self.print_trait_method(meth));
699 try!(self.bclose(item.span));
701 // I think it's reasonable to hide the context here:
702 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
704 try!(self.print_visibility(item.vis));
705 try!(self.print_path(pth, false));
706 try!(word(&mut self.s, "! "));
707 try!(self.print_ident(item.ident));
708 try!(self.cbox(indent_unit));
710 try!(self.print_tts(&(tts.as_slice())));
715 self.ann.post(self, NodeItem(item))
718 fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
719 self.print_path(&t.path, false)
722 pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
723 generics: &ast::Generics, ident: ast::Ident,
725 visibility: ast::Visibility) -> IoResult<()> {
726 try!(self.head(visibility_qualified(visibility, "enum")));
727 try!(self.print_ident(ident));
728 try!(self.print_generics(generics));
729 try!(space(&mut self.s));
730 self.print_variants(enum_definition.variants.as_slice(), span)
733 pub fn print_variants(&mut self,
734 variants: &[P<ast::Variant>],
735 span: codemap::Span) -> IoResult<()> {
737 for &v in variants.iter() {
738 try!(self.space_if_not_bol());
739 try!(self.maybe_print_comment(v.span.lo));
740 try!(self.print_outer_attributes(v.node.attrs.as_slice()));
741 try!(self.ibox(indent_unit));
742 try!(self.print_variant(v));
743 try!(word(&mut self.s, ","));
745 try!(self.maybe_print_trailing_comment(v.span, None));
750 pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
752 ast::Public => self.word_nbsp("pub"),
753 ast::Inherited => Ok(())
757 pub fn print_struct(&mut self,
758 struct_def: &ast::StructDef,
759 generics: &ast::Generics,
761 span: codemap::Span) -> IoResult<()> {
762 try!(self.print_ident(ident));
763 try!(self.print_generics(generics));
764 match struct_def.super_struct {
766 try!(self.word_space(":"));
767 try!(self.print_type(t));
771 if ast_util::struct_def_is_tuple_like(struct_def) {
772 if !struct_def.fields.is_empty() {
775 Inconsistent, struct_def.fields.as_slice(),
777 match field.node.kind {
778 ast::NamedField(..) => fail!("unexpected named field"),
779 ast::UnnamedField(vis) => {
780 try!(s.print_visibility(vis));
781 try!(s.maybe_print_comment(field.span.lo));
782 s.print_type(field.node.ty)
789 try!(word(&mut self.s, ";"));
791 self.end() // close the outer-box
795 try!(self.hardbreak_if_not_bol());
797 for field in struct_def.fields.iter() {
798 match field.node.kind {
799 ast::UnnamedField(..) => fail!("unexpected unnamed field"),
800 ast::NamedField(ident, visibility) => {
801 try!(self.hardbreak_if_not_bol());
802 try!(self.maybe_print_comment(field.span.lo));
803 try!(self.print_outer_attributes(field.node.attrs.as_slice()));
804 try!(self.print_visibility(visibility));
805 try!(self.print_ident(ident));
806 try!(self.word_nbsp(":"));
807 try!(self.print_type(field.node.ty));
808 try!(word(&mut self.s, ","));
817 /// This doesn't deserve to be called "pretty" printing, but it should be
818 /// meaning-preserving. A quick hack that might help would be to look at the
819 /// spans embedded in the TTs to decide where to put spaces and newlines.
820 /// But it'd be better to parse these according to the grammar of the
821 /// appropriate macro, transcribe back into the grammar we just parsed from,
822 /// and then pretty-print the resulting AST nodes (so, e.g., we print
823 /// expression arguments as expressions). It can be done! I think.
824 pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
826 ast::TTDelim(ref tts) => self.print_tts(&(tts.as_slice())),
827 ast::TTTok(_, ref tk) => {
828 word(&mut self.s, parse::token::to_str(tk))
830 ast::TTSeq(_, ref tts, ref sep, zerok) => {
831 try!(word(&mut self.s, "$("));
832 for tt_elt in (*tts).iter() {
833 try!(self.print_tt(tt_elt));
835 try!(word(&mut self.s, ")"));
838 try!(word(&mut self.s, parse::token::to_str(tk)));
842 word(&mut self.s, if zerok { "*" } else { "+" })
844 ast::TTNonterminal(_, name) => {
845 try!(word(&mut self.s, "$"));
846 self.print_ident(name)
851 pub fn print_tts(&mut self, tts: & &[ast::TokenTree]) -> IoResult<()> {
853 for (i, tt) in tts.iter().enumerate() {
855 try!(space(&mut self.s));
857 try!(self.print_tt(tt));
862 pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
863 try!(self.print_visibility(v.node.vis));
865 ast::TupleVariantKind(ref args) => {
866 try!(self.print_ident(v.node.name));
867 if !args.is_empty() {
869 try!(self.commasep(Consistent,
871 |s, arg| s.print_type(arg.ty)));
875 ast::StructVariantKind(struct_def) => {
877 let generics = ast_util::empty_generics();
878 try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
881 match v.node.disr_expr {
883 try!(space(&mut self.s));
884 try!(self.word_space("="));
891 pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
892 try!(self.hardbreak_if_not_bol());
893 try!(self.maybe_print_comment(m.span.lo));
894 try!(self.print_outer_attributes(m.attrs.as_slice()));
895 try!(self.print_ty_fn(None,
904 Some(m.explicit_self.node)));
905 word(&mut self.s, ";")
908 pub fn print_trait_method(&mut self,
909 m: &ast::TraitMethod) -> IoResult<()> {
911 Required(ref ty_m) => self.print_ty_method(ty_m),
912 Provided(m) => self.print_method(m)
916 pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
917 try!(self.hardbreak_if_not_bol());
918 try!(self.maybe_print_comment(meth.span.lo));
919 try!(self.print_outer_attributes(meth.attrs.as_slice()));
920 try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
921 meth.ident, &meth.generics, Some(meth.explicit_self.node),
923 try!(word(&mut self.s, " "));
924 self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
927 pub fn print_outer_attributes(&mut self,
928 attrs: &[ast::Attribute]) -> IoResult<()> {
930 for attr in attrs.iter() {
931 match attr.node.style {
933 try!(self.print_attribute(attr));
936 _ => {/* fallthrough */ }
940 try!(self.hardbreak_if_not_bol());
945 pub fn print_inner_attributes(&mut self,
946 attrs: &[ast::Attribute]) -> IoResult<()> {
948 for attr in attrs.iter() {
949 match attr.node.style {
951 try!(self.print_attribute(attr));
954 _ => {/* fallthrough */ }
958 try!(self.hardbreak_if_not_bol());
963 pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
964 try!(self.hardbreak_if_not_bol());
965 try!(self.maybe_print_comment(attr.span.lo));
966 if attr.node.is_sugared_doc {
967 word(&mut self.s, attr.value_str().unwrap().get())
969 match attr.node.style {
970 ast::AttrInner => try!(word(&mut self.s, "#![")),
971 ast::AttrOuter => try!(word(&mut self.s, "#[")),
973 try!(self.print_meta_item(attr.meta()));
974 word(&mut self.s, "]")
979 pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
980 try!(self.maybe_print_comment(st.span.lo));
982 ast::StmtDecl(decl, _) => {
983 try!(self.print_decl(decl));
985 ast::StmtExpr(expr, _) => {
986 try!(self.space_if_not_bol());
987 try!(self.print_expr(expr));
989 ast::StmtSemi(expr, _) => {
990 try!(self.space_if_not_bol());
991 try!(self.print_expr(expr));
992 try!(word(&mut self.s, ";"));
994 ast::StmtMac(ref mac, semi) => {
995 try!(self.space_if_not_bol());
996 try!(self.print_mac(mac));
998 try!(word(&mut self.s, ";"));
1002 if parse::classify::stmt_ends_with_semi(st) {
1003 try!(word(&mut self.s, ";"));
1005 self.maybe_print_trailing_comment(st.span, None)
1008 pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1009 self.print_block_with_attrs(blk, &[])
1012 pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1013 self.print_block_unclosed_indent(blk, indent_unit)
1016 pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1017 indented: uint) -> IoResult<()> {
1018 self.print_block_maybe_unclosed(blk, indented, &[], false)
1021 pub fn print_block_with_attrs(&mut self,
1023 attrs: &[ast::Attribute]) -> IoResult<()> {
1024 self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1027 pub fn print_block_maybe_unclosed(&mut self,
1030 attrs: &[ast::Attribute],
1031 close_box: bool) -> IoResult<()> {
1033 ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1034 ast::DefaultBlock => ()
1036 try!(self.maybe_print_comment(blk.span.lo));
1037 try!(self.ann.pre(self, NodeBlock(blk)));
1040 try!(self.print_inner_attributes(attrs));
1042 for vi in blk.view_items.iter() {
1043 try!(self.print_view_item(vi));
1045 for st in blk.stmts.iter() {
1046 try!(self.print_stmt(*st));
1050 try!(self.space_if_not_bol());
1051 try!(self.print_expr(expr));
1052 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1056 try!(self.bclose_maybe_open(blk.span, indented, close_box));
1057 self.ann.post(self, NodeBlock(blk))
1060 fn print_else(&mut self, els: Option<@ast::Expr>) -> IoResult<()> {
1064 // "another else-if"
1065 ast::ExprIf(i, t, e) => {
1066 try!(self.cbox(indent_unit - 1u));
1067 try!(self.ibox(0u));
1068 try!(word(&mut self.s, " else if "));
1069 try!(self.print_expr(i));
1070 try!(space(&mut self.s));
1071 try!(self.print_block(t));
1075 ast::ExprBlock(b) => {
1076 try!(self.cbox(indent_unit - 1u));
1077 try!(self.ibox(0u));
1078 try!(word(&mut self.s, " else "));
1081 // BLEAH, constraints would be great here
1083 fail!("print_if saw if with weird alternative");
1091 pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1092 elseopt: Option<@ast::Expr>, chk: bool) -> IoResult<()> {
1093 try!(self.head("if"));
1094 if chk { try!(self.word_nbsp("check")); }
1095 try!(self.print_expr(test));
1096 try!(space(&mut self.s));
1097 try!(self.print_block(blk));
1098 self.print_else(elseopt)
1101 pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1103 // I think it's reasonable to hide the ctxt here:
1104 ast::MacInvocTT(ref pth, ref tts, _) => {
1105 try!(self.print_path(pth, false));
1106 try!(word(&mut self.s, "!"));
1108 try!(self.print_tts(&tts.as_slice()));
1114 pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1116 ast::ExprVstoreUniq => word(&mut self.s, "~"),
1117 ast::ExprVstoreSlice => word(&mut self.s, "&"),
1118 ast::ExprVstoreMutSlice => {
1119 try!(word(&mut self.s, "&"));
1120 word(&mut self.s, "mut")
1125 fn print_call_post(&mut self, args: &[@ast::Expr]) -> IoResult<()> {
1127 try!(self.commasep_exprs(Inconsistent, args));
1131 pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1132 try!(self.maybe_print_comment(expr.span.lo));
1133 try!(self.ibox(indent_unit));
1134 try!(self.ann.pre(self, NodeExpr(expr)));
1136 ast::ExprVstore(e, v) => {
1137 try!(self.print_expr_vstore(v));
1138 try!(self.print_expr(e));
1140 ast::ExprBox(p, e) => {
1141 try!(word(&mut self.s, "box"));
1142 try!(word(&mut self.s, "("));
1143 try!(self.print_expr(p));
1144 try!(self.word_space(")"));
1145 try!(self.print_expr(e));
1147 ast::ExprVec(ref exprs) => {
1148 try!(self.ibox(indent_unit));
1149 try!(word(&mut self.s, "["));
1150 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1151 try!(word(&mut self.s, "]"));
1155 ast::ExprRepeat(element, count) => {
1156 try!(self.ibox(indent_unit));
1157 try!(word(&mut self.s, "["));
1158 try!(self.print_expr(element));
1159 try!(word(&mut self.s, ","));
1160 try!(word(&mut self.s, ".."));
1161 try!(self.print_expr(count));
1162 try!(word(&mut self.s, "]"));
1166 ast::ExprStruct(ref path, ref fields, wth) => {
1167 try!(self.print_path(path, true));
1168 try!(word(&mut self.s, "{"));
1169 try!(self.commasep_cmnt(
1173 try!(s.ibox(indent_unit));
1174 try!(s.print_ident(field.ident.node));
1175 try!(s.word_space(":"));
1176 try!(s.print_expr(field.expr));
1182 try!(self.ibox(indent_unit));
1183 if !fields.is_empty() {
1184 try!(word(&mut self.s, ","));
1185 try!(space(&mut self.s));
1187 try!(word(&mut self.s, ".."));
1188 try!(self.print_expr(expr));
1191 _ => try!(word(&mut self.s, ","))
1193 try!(word(&mut self.s, "}"));
1195 ast::ExprTup(ref exprs) => {
1197 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1198 if exprs.len() == 1 {
1199 try!(word(&mut self.s, ","));
1201 try!(self.pclose());
1203 ast::ExprCall(func, ref args) => {
1204 try!(self.print_expr(func));
1205 try!(self.print_call_post(args.as_slice()));
1207 ast::ExprMethodCall(ident, ref tys, ref args) => {
1208 let base_args = args.slice_from(1);
1209 try!(self.print_expr(*args.get(0)));
1210 try!(word(&mut self.s, "."));
1211 try!(self.print_ident(ident.node));
1213 try!(word(&mut self.s, "::<"));
1214 try!(self.commasep(Inconsistent, tys.as_slice(),
1215 |s, ty| s.print_type_ref(ty)));
1216 try!(word(&mut self.s, ">"));
1218 try!(self.print_call_post(base_args));
1220 ast::ExprBinary(op, lhs, rhs) => {
1221 try!(self.print_expr(lhs));
1222 try!(space(&mut self.s));
1223 try!(self.word_space(ast_util::binop_to_str(op)));
1224 try!(self.print_expr(rhs));
1226 ast::ExprUnary(op, expr) => {
1227 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1228 try!(self.print_expr(expr));
1230 ast::ExprAddrOf(m, expr) => {
1231 try!(word(&mut self.s, "&"));
1232 try!(self.print_mutability(m));
1233 // Avoid `& &e` => `&&e`.
1234 match (m, &expr.node) {
1235 (ast::MutImmutable, &ast::ExprAddrOf(..)) => try!(space(&mut self.s)),
1238 try!(self.print_expr(expr));
1240 ast::ExprLit(lit) => try!(self.print_literal(lit)),
1241 ast::ExprCast(expr, ty) => {
1242 try!(self.print_expr(expr));
1243 try!(space(&mut self.s));
1244 try!(self.word_space("as"));
1245 try!(self.print_type(ty));
1247 ast::ExprIf(test, blk, elseopt) => {
1248 try!(self.print_if(test, blk, elseopt, false));
1250 ast::ExprWhile(test, blk) => {
1251 try!(self.head("while"));
1252 try!(self.print_expr(test));
1253 try!(space(&mut self.s));
1254 try!(self.print_block(blk));
1256 ast::ExprForLoop(pat, iter, 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("for"));
1263 try!(self.print_pat(pat));
1264 try!(space(&mut self.s));
1265 try!(self.word_space("in"));
1266 try!(self.print_expr(iter));
1267 try!(space(&mut self.s));
1268 try!(self.print_block(blk));
1270 ast::ExprLoop(blk, opt_ident) => {
1271 for ident in opt_ident.iter() {
1272 try!(word(&mut self.s, "'"));
1273 try!(self.print_ident(*ident));
1274 try!(self.word_space(":"));
1276 try!(self.head("loop"));
1277 try!(space(&mut self.s));
1278 try!(self.print_block(blk));
1280 ast::ExprMatch(expr, ref arms) => {
1281 try!(self.cbox(indent_unit));
1283 try!(self.word_nbsp("match"));
1284 try!(self.print_expr(expr));
1285 try!(space(&mut self.s));
1287 let len = arms.len();
1288 for (i, arm) in arms.iter().enumerate() {
1289 // I have no idea why this check is necessary, but here it
1291 if arm.attrs.is_empty() {
1292 try!(space(&mut self.s));
1294 try!(self.cbox(indent_unit));
1295 try!(self.ibox(0u));
1296 try!(self.print_outer_attributes(arm.attrs.as_slice()));
1297 let mut first = true;
1298 for p in arm.pats.iter() {
1302 try!(space(&mut self.s));
1303 try!(self.word_space("|"));
1305 try!(self.print_pat(*p));
1307 try!(space(&mut self.s));
1310 try!(self.word_space("if"));
1311 try!(self.print_expr(e));
1312 try!(space(&mut self.s));
1316 try!(self.word_space("=>"));
1318 match arm.body.node {
1319 ast::ExprBlock(blk) => {
1320 // the block will close the pattern's ibox
1321 try!(self.print_block_unclosed_indent(blk, indent_unit));
1324 try!(self.end()); // close the ibox for the pattern
1325 try!(self.print_expr(arm.body));
1328 if !expr_is_simple_block(expr)
1330 try!(word(&mut self.s, ","));
1332 try!(self.end()); // close enclosing cbox
1334 try!(self.bclose_(expr.span, indent_unit));
1336 ast::ExprFnBlock(decl, body) => {
1337 // in do/for blocks we don't want to show an empty
1338 // argument list, but at this point we don't know which
1341 // if !decl.inputs.is_empty() {
1342 try!(self.print_fn_block_args(decl));
1343 try!(space(&mut self.s));
1346 if !body.stmts.is_empty() || !body.expr.is_some() {
1347 try!(self.print_block_unclosed(body));
1349 // we extract the block, so as not to create another set of boxes
1350 match body.expr.unwrap().node {
1351 ast::ExprBlock(blk) => {
1352 try!(self.print_block_unclosed(blk));
1355 // this is a bare expression
1356 try!(self.print_expr(body.expr.unwrap()));
1357 try!(self.end()); // need to close a box
1361 // a box will be closed by print_expr, but we didn't want an overall
1362 // wrapper so we closed the corresponding opening. so create an
1363 // empty box to satisfy the close.
1366 ast::ExprProc(decl, body) => {
1367 // in do/for blocks we don't want to show an empty
1368 // argument list, but at this point we don't know which
1371 // if !decl.inputs.is_empty() {
1372 try!(self.print_proc_args(decl));
1373 try!(space(&mut self.s));
1375 assert!(body.stmts.is_empty());
1376 assert!(body.expr.is_some());
1377 // we extract the block, so as not to create another set of boxes
1378 match body.expr.unwrap().node {
1379 ast::ExprBlock(blk) => {
1380 try!(self.print_block_unclosed(blk));
1383 // this is a bare expression
1384 try!(self.print_expr(body.expr.unwrap()));
1385 try!(self.end()); // need to close a box
1388 // a box will be closed by print_expr, but we didn't want an overall
1389 // wrapper so we closed the corresponding opening. so create an
1390 // empty box to satisfy the close.
1393 ast::ExprBlock(blk) => {
1394 // containing cbox, will be closed by print-block at }
1395 try!(self.cbox(indent_unit));
1396 // head-box, will be closed by print-block after {
1397 try!(self.ibox(0u));
1398 try!(self.print_block(blk));
1400 ast::ExprAssign(lhs, rhs) => {
1401 try!(self.print_expr(lhs));
1402 try!(space(&mut self.s));
1403 try!(self.word_space("="));
1404 try!(self.print_expr(rhs));
1406 ast::ExprAssignOp(op, lhs, rhs) => {
1407 try!(self.print_expr(lhs));
1408 try!(space(&mut self.s));
1409 try!(word(&mut self.s, ast_util::binop_to_str(op)));
1410 try!(self.word_space("="));
1411 try!(self.print_expr(rhs));
1413 ast::ExprField(expr, id, ref tys) => {
1414 try!(self.print_expr(expr));
1415 try!(word(&mut self.s, "."));
1416 try!(self.print_ident(id));
1418 try!(word(&mut self.s, "::<"));
1420 Inconsistent, tys.as_slice(),
1421 |s, ty| s.print_type_ref(ty)));
1422 try!(word(&mut self.s, ">"));
1425 ast::ExprIndex(expr, index) => {
1426 try!(self.print_expr(expr));
1427 try!(word(&mut self.s, "["));
1428 try!(self.print_expr(index));
1429 try!(word(&mut self.s, "]"));
1431 ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1432 ast::ExprBreak(opt_ident) => {
1433 try!(word(&mut self.s, "break"));
1434 try!(space(&mut self.s));
1435 for ident in opt_ident.iter() {
1436 try!(word(&mut self.s, "'"));
1437 try!(self.print_ident(*ident));
1438 try!(space(&mut self.s));
1441 ast::ExprAgain(opt_ident) => {
1442 try!(word(&mut self.s, "continue"));
1443 try!(space(&mut self.s));
1444 for ident in opt_ident.iter() {
1445 try!(word(&mut self.s, "'"));
1446 try!(self.print_ident(*ident));
1447 try!(space(&mut self.s))
1450 ast::ExprRet(result) => {
1451 try!(word(&mut self.s, "return"));
1454 try!(word(&mut self.s, " "));
1455 try!(self.print_expr(expr));
1460 ast::ExprInlineAsm(ref a) => {
1462 try!(word(&mut self.s, "__volatile__ asm!"));
1464 try!(word(&mut self.s, "asm!"));
1467 try!(self.print_string(a.asm.get(), a.asm_str_style));
1468 try!(self.word_space(":"));
1469 for &(ref co, o) in a.outputs.iter() {
1470 try!(self.print_string(co.get(), ast::CookedStr));
1472 try!(self.print_expr(o));
1473 try!(self.pclose());
1474 try!(self.word_space(","));
1476 try!(self.word_space(":"));
1477 for &(ref co, o) in a.inputs.iter() {
1478 try!(self.print_string(co.get(), ast::CookedStr));
1480 try!(self.print_expr(o));
1481 try!(self.pclose());
1482 try!(self.word_space(","));
1484 try!(self.word_space(":"));
1485 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1486 try!(self.pclose());
1488 ast::ExprMac(ref m) => try!(self.print_mac(m)),
1489 ast::ExprParen(e) => {
1491 try!(self.print_expr(e));
1492 try!(self.pclose());
1495 try!(self.ann.post(self, NodeExpr(expr)));
1499 pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1500 try!(self.print_pat(loc.pat));
1502 ast::TyInfer => Ok(()),
1504 try!(self.word_space(":"));
1505 self.print_type(loc.ty)
1510 pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1511 try!(self.maybe_print_comment(decl.span.lo));
1513 ast::DeclLocal(loc) => {
1514 try!(self.space_if_not_bol());
1515 try!(self.ibox(indent_unit));
1516 try!(self.word_nbsp("let"));
1518 try!(self.ibox(indent_unit));
1519 try!(self.print_local_decl(loc));
1524 try!(self.word_space("="));
1525 try!(self.print_expr(init));
1531 ast::DeclItem(item) => self.print_item(item)
1535 pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1536 word(&mut self.s, token::get_ident(ident).get())
1539 pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1540 word(&mut self.s, token::get_name(name).get())
1543 pub fn print_for_decl(&mut self, loc: &ast::Local,
1544 coll: &ast::Expr) -> IoResult<()> {
1545 try!(self.print_local_decl(loc));
1546 try!(space(&mut self.s));
1547 try!(self.word_space("in"));
1548 self.print_expr(coll)
1551 fn print_path_(&mut self,
1553 colons_before_params: bool,
1554 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1556 try!(self.maybe_print_comment(path.span.lo));
1558 try!(word(&mut self.s, "::"));
1561 let mut first = true;
1562 for segment in path.segments.iter() {
1566 try!(word(&mut self.s, "::"))
1569 try!(self.print_ident(segment.identifier));
1571 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1572 if colons_before_params {
1573 try!(word(&mut self.s, "::"))
1575 try!(word(&mut self.s, "<"));
1577 let mut comma = false;
1578 for lifetime in segment.lifetimes.iter() {
1580 try!(self.word_space(","))
1582 try!(self.print_lifetime(lifetime));
1586 if !segment.types.is_empty() {
1588 try!(self.word_space(","))
1592 segment.types.as_slice(),
1593 |s, ty| s.print_type_ref(ty)));
1596 try!(word(&mut self.s, ">"))
1602 Some(ref bounds) => self.print_bounds(&None, bounds, true),
1606 fn print_path(&mut self, path: &ast::Path,
1607 colons_before_params: bool) -> IoResult<()> {
1608 self.print_path_(path, colons_before_params, &None)
1611 fn print_bounded_path(&mut self, path: &ast::Path,
1612 bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1614 self.print_path_(path, false, bounds)
1617 pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1618 try!(self.maybe_print_comment(pat.span.lo));
1619 try!(self.ann.pre(self, NodePat(pat)));
1620 /* Pat isn't normalized, but the beauty of it
1621 is that it doesn't matter */
1623 ast::PatWild => try!(word(&mut self.s, "_")),
1624 ast::PatWildMulti => try!(word(&mut self.s, "..")),
1625 ast::PatIdent(binding_mode, ref path, sub) => {
1626 match binding_mode {
1627 ast::BindByRef(mutbl) => {
1628 try!(self.word_nbsp("ref"));
1629 try!(self.print_mutability(mutbl));
1631 ast::BindByValue(ast::MutImmutable) => {}
1632 ast::BindByValue(ast::MutMutable) => {
1633 try!(self.word_nbsp("mut"));
1636 try!(self.print_path(path, true));
1639 try!(word(&mut self.s, "@"));
1640 try!(self.print_pat(p));
1645 ast::PatEnum(ref path, ref args_) => {
1646 try!(self.print_path(path, true));
1648 None => try!(word(&mut self.s, "(..)")),
1650 if !args.is_empty() {
1652 try!(self.commasep(Inconsistent, args.as_slice(),
1653 |s, &p| s.print_pat(p)));
1654 try!(self.pclose());
1659 ast::PatStruct(ref path, ref fields, etc) => {
1660 try!(self.print_path(path, true));
1661 try!(word(&mut self.s, "{"));
1662 try!(self.commasep_cmnt(
1663 Consistent, fields.as_slice(),
1665 try!(s.cbox(indent_unit));
1666 try!(s.print_ident(f.ident));
1667 try!(s.word_space(":"));
1668 try!(s.print_pat(f.pat));
1673 if fields.len() != 0u { try!(self.word_space(",")); }
1674 try!(word(&mut self.s, ".."));
1676 try!(word(&mut self.s, "}"));
1678 ast::PatTup(ref elts) => {
1680 try!(self.commasep(Inconsistent,
1682 |s, &p| s.print_pat(p)));
1683 if elts.len() == 1 {
1684 try!(word(&mut self.s, ","));
1686 try!(self.pclose());
1688 ast::PatUniq(inner) => {
1689 try!(word(&mut self.s, "~"));
1690 try!(self.print_pat(inner));
1692 ast::PatRegion(inner) => {
1693 try!(word(&mut self.s, "&"));
1694 try!(self.print_pat(inner));
1696 ast::PatLit(e) => try!(self.print_expr(e)),
1697 ast::PatRange(begin, end) => {
1698 try!(self.print_expr(begin));
1699 try!(space(&mut self.s));
1700 try!(word(&mut self.s, ".."));
1701 try!(self.print_expr(end));
1703 ast::PatVec(ref before, slice, ref after) => {
1704 try!(word(&mut self.s, "["));
1705 try!(self.commasep(Inconsistent,
1707 |s, &p| s.print_pat(p)));
1708 for &p in slice.iter() {
1709 if !before.is_empty() { try!(self.word_space(",")); }
1711 ast::Pat { node: ast::PatWildMulti, .. } => {
1712 // this case is handled by print_pat
1714 _ => try!(word(&mut self.s, "..")),
1716 try!(self.print_pat(p));
1717 if !after.is_empty() { try!(self.word_space(",")); }
1719 try!(self.commasep(Inconsistent,
1721 |s, &p| s.print_pat(p)));
1722 try!(word(&mut self.s, "]"));
1725 self.ann.post(self, NodePat(pat))
1728 // Returns whether it printed anything
1729 fn print_explicit_self(&mut self,
1730 explicit_self: ast::ExplicitSelf_,
1731 mutbl: ast::Mutability) -> IoResult<bool> {
1732 try!(self.print_mutability(mutbl));
1733 match explicit_self {
1734 ast::SelfStatic => { return Ok(false); }
1736 try!(word(&mut self.s, "self"));
1739 try!(word(&mut self.s, "~self"));
1741 ast::SelfRegion(ref lt, m) => {
1742 try!(word(&mut self.s, "&"));
1743 try!(self.print_opt_lifetime(lt));
1744 try!(self.print_mutability(m));
1745 try!(word(&mut self.s, "self"));
1751 pub fn print_fn(&mut self,
1753 fn_style: Option<ast::FnStyle>,
1756 generics: &ast::Generics,
1757 opt_explicit_self: Option<ast::ExplicitSelf_>,
1758 vis: ast::Visibility) -> IoResult<()> {
1759 try!(self.head(""));
1760 try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1762 try!(self.print_ident(name));
1763 try!(self.print_generics(generics));
1764 self.print_fn_args_and_ret(decl, opt_explicit_self)
1767 pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1768 opt_explicit_self: Option<ast::ExplicitSelf_>)
1770 // It is unfortunate to duplicate the commasep logic, but we want the
1771 // self type and the args all in the same box.
1772 try!(self.rbox(0u, Inconsistent));
1773 let mut first = true;
1774 for &explicit_self in opt_explicit_self.iter() {
1775 let m = match explicit_self {
1776 ast::SelfStatic => ast::MutImmutable,
1777 _ => match decl.inputs.get(0).pat.node {
1778 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1779 _ => ast::MutImmutable
1782 first = !try!(self.print_explicit_self(explicit_self, m));
1785 // HACK(eddyb) ignore the separately printed self argument.
1786 let args = if first {
1787 decl.inputs.as_slice()
1789 decl.inputs.slice_from(1)
1792 for arg in args.iter() {
1793 if first { first = false; } else { try!(self.word_space(",")); }
1794 try!(self.print_arg(arg));
1800 pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1801 opt_explicit_self: Option<ast::ExplicitSelf_>)
1804 try!(self.print_fn_args(decl, opt_explicit_self));
1806 try!(word(&mut self.s, ", ..."));
1808 try!(self.pclose());
1810 try!(self.maybe_print_comment(decl.output.span.lo));
1811 match decl.output.node {
1812 ast::TyNil => Ok(()),
1814 try!(self.space_if_not_bol());
1815 try!(self.word_space("->"));
1816 self.print_type(decl.output)
1821 pub fn print_fn_block_args(&mut self,
1822 decl: &ast::FnDecl) -> IoResult<()> {
1823 try!(word(&mut self.s, "|"));
1824 try!(self.print_fn_args(decl, None));
1825 try!(word(&mut self.s, "|"));
1827 match decl.output.node {
1830 try!(self.space_if_not_bol());
1831 try!(self.word_space("->"));
1832 try!(self.print_type(decl.output));
1836 self.maybe_print_comment(decl.output.span.lo)
1839 pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1840 try!(word(&mut self.s, "proc"));
1841 try!(word(&mut self.s, "("));
1842 try!(self.print_fn_args(decl, None));
1843 try!(word(&mut self.s, ")"));
1845 match decl.output.node {
1848 try!(self.space_if_not_bol());
1849 try!(self.word_space("->"));
1850 try!(self.print_type(decl.output));
1854 self.maybe_print_comment(decl.output.span.lo)
1857 pub fn print_bounds(&mut self,
1858 region: &Option<ast::Lifetime>,
1859 bounds: &OwnedSlice<ast::TyParamBound>,
1860 print_colon_anyway: bool) -> IoResult<()> {
1861 if !bounds.is_empty() || region.is_some() {
1862 try!(word(&mut self.s, ":"));
1863 let mut first = true;
1866 let token = token::get_name(lt.name);
1867 if token.get() != "static" {
1870 try!(self.print_lifetime(lt));
1875 for bound in bounds.iter() {
1880 try!(self.word_space("+"));
1884 TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
1885 RegionTyParamBound => word(&mut self.s, "'static"),
1889 } else if print_colon_anyway {
1890 word(&mut self.s, ":")
1896 pub fn print_lifetime(&mut self,
1897 lifetime: &ast::Lifetime) -> IoResult<()> {
1898 try!(word(&mut self.s, "'"));
1899 self.print_name(lifetime.name)
1902 pub fn print_generics(&mut self,
1903 generics: &ast::Generics) -> IoResult<()> {
1904 let total = generics.lifetimes.len() + generics.ty_params.len();
1906 try!(word(&mut self.s, "<"));
1908 let mut ints = Vec::new();
1909 for i in range(0u, total) {
1914 Inconsistent, ints.as_slice(),
1916 if idx < generics.lifetimes.len() {
1917 let lifetime = generics.lifetimes.get(idx);
1918 s.print_lifetime(lifetime)
1920 let idx = idx - generics.lifetimes.len();
1921 let param = generics.ty_params.get(idx);
1922 if param.sized == ast::DynSize {
1923 try!(s.word_space("type"));
1925 try!(s.print_ident(param.ident));
1926 try!(s.print_bounds(&None, ¶m.bounds, false));
1927 match param.default {
1929 try!(space(&mut s.s));
1930 try!(s.word_space("="));
1931 s.print_type(default)
1937 word(&mut self.s, ">")
1943 pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
1944 try!(self.ibox(indent_unit));
1946 ast::MetaWord(ref name) => {
1947 try!(word(&mut self.s, name.get()));
1949 ast::MetaNameValue(ref name, ref value) => {
1950 try!(self.word_space(name.get()));
1951 try!(self.word_space("="));
1952 try!(self.print_literal(value));
1954 ast::MetaList(ref name, ref items) => {
1955 try!(word(&mut self.s, name.get()));
1957 try!(self.commasep(Consistent,
1959 |s, &i| s.print_meta_item(i)));
1960 try!(self.pclose());
1966 pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
1968 ast::ViewPathSimple(ident, ref path, _) => {
1969 // FIXME(#6993) can't compare identifiers directly here
1970 if path.segments.last().unwrap().identifier.name != ident.name {
1971 try!(self.print_ident(ident));
1972 try!(space(&mut self.s));
1973 try!(self.word_space("="));
1975 self.print_path(path, false)
1978 ast::ViewPathGlob(ref path, _) => {
1979 try!(self.print_path(path, false));
1980 word(&mut self.s, "::*")
1983 ast::ViewPathList(ref path, ref idents, _) => {
1984 if path.segments.is_empty() {
1985 try!(word(&mut self.s, "{"));
1987 try!(self.print_path(path, false));
1988 try!(word(&mut self.s, "::{"));
1990 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
1991 s.print_ident(w.node.name)
1993 word(&mut self.s, "}")
1998 pub fn print_view_paths(&mut self,
1999 vps: &[@ast::ViewPath]) -> IoResult<()> {
2000 self.commasep(Inconsistent, vps, |s, &vp| s.print_view_path(vp))
2003 pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2004 try!(self.hardbreak_if_not_bol());
2005 try!(self.maybe_print_comment(item.span.lo));
2006 try!(self.print_outer_attributes(item.attrs.as_slice()));
2007 try!(self.print_visibility(item.vis));
2009 ast::ViewItemExternCrate(id, ref optional_path, _) => {
2010 try!(self.head("extern crate"));
2011 try!(self.print_ident(id));
2012 for &(ref p, style) in optional_path.iter() {
2013 try!(space(&mut self.s));
2014 try!(word(&mut self.s, "="));
2015 try!(space(&mut self.s));
2016 try!(self.print_string(p.get(), style));
2020 ast::ViewItemUse(ref vps) => {
2021 try!(self.head("use"));
2022 try!(self.print_view_paths(vps.as_slice()));
2025 try!(word(&mut self.s, ";"));
2026 try!(self.end()); // end inner head-block
2027 self.end() // end outer head-block
2030 pub fn print_mutability(&mut self,
2031 mutbl: ast::Mutability) -> IoResult<()> {
2033 ast::MutMutable => self.word_nbsp("mut"),
2034 ast::MutImmutable => Ok(()),
2038 pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2039 try!(self.print_mutability(mt.mutbl));
2040 self.print_type(mt.ty)
2043 pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2044 try!(self.ibox(indent_unit));
2045 match input.ty.node {
2046 ast::TyInfer => try!(self.print_pat(input.pat)),
2048 match input.pat.node {
2049 ast::PatIdent(_, ref path, _) if
2050 path.segments.len() == 1 &&
2051 path.segments.get(0).identifier.name ==
2052 parse::token::special_idents::invalid.name => {
2056 try!(self.print_pat(input.pat));
2057 try!(word(&mut self.s, ":"));
2058 try!(space(&mut self.s));
2061 try!(self.print_type(input.ty));
2067 pub fn print_ty_fn(&mut self,
2068 opt_abi: Option<abi::Abi>,
2069 opt_sigil: Option<char>,
2070 opt_region: &Option<ast::Lifetime>,
2071 fn_style: ast::FnStyle,
2072 onceness: ast::Onceness,
2074 id: Option<ast::Ident>,
2075 opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2076 generics: Option<&ast::Generics>,
2077 opt_explicit_self: Option<ast::ExplicitSelf_>)
2079 try!(self.ibox(indent_unit));
2081 // Duplicates the logic in `print_fn_header_info()`. This is because that
2082 // function prints the sigil in the wrong place. That should be fixed.
2083 if opt_sigil == Some('~') && onceness == ast::Once {
2084 try!(word(&mut self.s, "proc"));
2085 } else if opt_sigil == Some('&') {
2086 try!(self.print_extern_opt_abi(opt_abi));
2087 try!(self.print_fn_style(fn_style));
2088 try!(self.print_onceness(onceness));
2090 assert!(opt_sigil.is_none());
2091 try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2092 try!(self.print_fn_style(fn_style));
2093 try!(self.print_onceness(onceness));
2094 try!(word(&mut self.s, "fn"));
2099 try!(word(&mut self.s, " "));
2100 try!(self.print_ident(id));
2105 match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2106 try!(zerobreak(&mut self.s));
2108 if opt_sigil == Some('&') {
2109 try!(word(&mut self.s, "|"));
2114 try!(self.print_fn_args(decl, opt_explicit_self));
2116 if opt_sigil == Some('&') {
2117 try!(word(&mut self.s, "|"));
2120 try!(word(&mut self.s, ", ..."));
2122 try!(self.pclose());
2125 opt_bounds.as_ref().map(|bounds| {
2126 self.print_bounds(opt_region, bounds, true)
2129 try!(self.maybe_print_comment(decl.output.span.lo));
2131 match decl.output.node {
2134 try!(self.space_if_not_bol());
2135 try!(self.ibox(indent_unit));
2136 try!(self.word_space("->"));
2137 if decl.cf == ast::NoReturn {
2138 try!(self.word_nbsp("!"));
2140 try!(self.print_type(decl.output));
2149 pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2150 next_pos: Option<BytePos>)
2152 let cm = match self.cm {
2156 match self.next_comment() {
2158 if (*cmnt).style != comments::Trailing { return Ok(()) }
2159 let span_line = cm.lookup_char_pos(span.hi);
2160 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2161 let mut next = (*cmnt).pos + BytePos(1);
2162 match next_pos { None => (), Some(p) => next = p }
2163 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2164 span_line.line == comment_line.line {
2165 try!(self.print_comment(cmnt));
2166 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2174 pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2175 // If there aren't any remaining comments, then we need to manually
2176 // make sure there is a line break at the end.
2177 if self.next_comment().is_none() {
2178 try!(hardbreak(&mut self.s));
2181 match self.next_comment() {
2183 try!(self.print_comment(cmnt));
2184 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2192 pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2193 try!(self.maybe_print_comment(lit.span.lo));
2194 match self.next_lit(lit.span.lo) {
2196 return word(&mut self.s, (*ltrl).lit);
2201 ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2202 ast::LitChar(ch) => {
2203 let mut res = StrBuf::from_str("'");
2204 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2205 res.push_char('\'');
2206 word(&mut self.s, res.into_owned())
2208 ast::LitInt(i, t) => {
2209 word(&mut self.s, ast_util::int_ty_to_str(t, Some(i)))
2211 ast::LitUint(u, t) => {
2212 word(&mut self.s, ast_util::uint_ty_to_str(t, Some(u)))
2214 ast::LitIntUnsuffixed(i) => {
2215 word(&mut self.s, format!("{}", i))
2217 ast::LitFloat(ref f, t) => {
2218 word(&mut self.s, f.get() + ast_util::float_ty_to_str(t))
2220 ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2221 ast::LitNil => word(&mut self.s, "()"),
2222 ast::LitBool(val) => {
2223 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2225 ast::LitBinary(ref arr) => {
2226 try!(self.ibox(indent_unit));
2227 try!(word(&mut self.s, "["));
2228 try!(self.commasep_cmnt(Inconsistent, arr.as_slice(),
2229 |s, u| word(&mut s.s, format!("{}", *u)),
2231 try!(word(&mut self.s, "]"));
2237 pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2238 match self.literals {
2240 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2241 let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2242 if ltrl.pos > pos { return None; }
2243 self.cur_cmnt_and_lit.cur_lit += 1u;
2244 if ltrl.pos == pos { return Some(ltrl); }
2252 pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2254 match self.next_comment() {
2256 if (*cmnt).pos < pos {
2257 try!(self.print_comment(cmnt));
2258 self.cur_cmnt_and_lit.cur_cmnt += 1u;
2267 pub fn print_comment(&mut self,
2268 cmnt: &comments::Comment) -> IoResult<()> {
2270 comments::Mixed => {
2271 assert_eq!(cmnt.lines.len(), 1u);
2272 try!(zerobreak(&mut self.s));
2273 try!(word(&mut self.s, *cmnt.lines.get(0)));
2274 zerobreak(&mut self.s)
2276 comments::Isolated => {
2277 try!(self.hardbreak_if_not_bol());
2278 for line in cmnt.lines.iter() {
2279 // Don't print empty lines because they will end up as trailing
2281 if !line.is_empty() {
2282 try!(word(&mut self.s, *line));
2284 try!(hardbreak(&mut self.s));
2288 comments::Trailing => {
2289 try!(word(&mut self.s, " "));
2290 if cmnt.lines.len() == 1u {
2291 try!(word(&mut self.s, *cmnt.lines.get(0)));
2292 hardbreak(&mut self.s)
2294 try!(self.ibox(0u));
2295 for line in cmnt.lines.iter() {
2296 if !line.is_empty() {
2297 try!(word(&mut self.s, *line));
2299 try!(hardbreak(&mut self.s));
2304 comments::BlankLine => {
2305 // We need to do at least one, possibly two hardbreaks.
2306 let is_semi = match self.s.last_token() {
2307 pp::String(s, _) => ";" == s,
2310 if is_semi || self.is_begin() || self.is_end() {
2311 try!(hardbreak(&mut self.s));
2313 hardbreak(&mut self.s)
2318 pub fn print_string(&mut self, st: &str,
2319 style: ast::StrStyle) -> IoResult<()> {
2320 let st = match style {
2321 ast::CookedStr => format!("\"{}\"", st.escape_default()),
2322 ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2323 delim="#".repeat(n), string=st)
2325 word(&mut self.s, st)
2328 pub fn next_comment(&mut self) -> Option<comments::Comment> {
2329 match self.comments {
2330 Some(ref cmnts) => {
2331 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2332 Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2341 pub fn print_opt_fn_style(&mut self,
2342 opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2343 match opt_fn_style {
2344 Some(fn_style) => self.print_fn_style(fn_style),
2349 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2350 opt_abi: Option<abi::Abi>)
2353 Some(abi::Rust) => Ok(()),
2355 try!(self.word_nbsp("extern"));
2356 self.word_nbsp(abi.to_str())
2362 pub fn print_extern_opt_abi(&mut self,
2363 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2366 try!(self.word_nbsp("extern"));
2367 self.word_nbsp(abi.to_str())
2373 pub fn print_fn_header_info(&mut self,
2374 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2375 opt_fn_style: Option<ast::FnStyle>,
2377 vis: ast::Visibility) -> IoResult<()> {
2378 try!(word(&mut self.s, visibility_qualified(vis, "")));
2380 if abi != abi::Rust {
2381 try!(self.word_nbsp("extern"));
2382 try!(self.word_nbsp(abi.to_str()));
2384 if opt_fn_style != Some(ast::ExternFn) {
2385 try!(self.print_opt_fn_style(opt_fn_style));
2388 try!(self.print_opt_fn_style(opt_fn_style));
2391 word(&mut self.s, "fn")
2394 pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2396 ast::NormalFn => Ok(()),
2397 ast::UnsafeFn => self.word_nbsp("unsafe"),
2398 ast::ExternFn => self.word_nbsp("extern")
2402 pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2404 ast::Once => self.word_nbsp("once"),
2420 fn test_fun_to_str() {
2421 let abba_ident = token::str_to_ident("abba");
2423 let decl = ast::FnDecl {
2425 output: ast::P(ast::Ty {id: 0,
2427 span: codemap::DUMMY_SP}),
2431 let generics = ast_util::empty_generics();
2432 assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2434 &"fn abba()".to_owned());
2438 fn test_variant_to_str() {
2439 let ident = token::str_to_ident("principal_skinner");
2441 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2444 // making this up as I go.... ?
2445 kind: ast::TupleVariantKind(Vec::new()),
2451 let varstr = variant_to_str(&var);
2452 assert_eq!(&varstr,&"pub principal_skinner".to_owned());