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};
17 use attr::{AttrMetaMethods, AttributeMethods};
18 use codemap::{CodeMap, BytePos};
21 use parse::classify::expr_is_simple_block;
22 use parse::token::{IdentInterner, interner_get};
23 use parse::{comments, token};
25 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, Consistent, Inconsistent, eof};
31 use std::cell::RefCell;
35 use std::io::MemWriter;
37 // The &mut State is stored here to prevent recursive type.
38 pub enum AnnNode<'a,'b> {
39 NodeBlock(&'b mut State, &'a ast::Block),
40 NodeItem(&'b mut State, &'a ast::Item),
41 NodeExpr(&'b mut State, &'a ast::Expr),
42 NodePat(&'b mut State, &'a ast::Pat),
46 fn pre(&self, _node: AnnNode) {}
47 fn post(&self, _node: AnnNode) {}
52 impl PpAnn for NoAnn {}
54 pub struct CurrentCommentAndLiteral {
62 intr: @token::IdentInterner,
63 comments: Option<~[comments::Comment]>,
64 literals: Option<~[comments::Literal]>,
65 cur_cmnt_and_lit: CurrentCommentAndLiteral,
66 boxes: RefCell<~[pp::Breaks]>,
70 pub fn ibox(s: &mut State, u: uint) {
72 let mut boxes = s.boxes.borrow_mut();
73 boxes.get().push(pp::Inconsistent);
75 pp::ibox(&mut s.s, u);
78 pub fn end(s: &mut State) {
80 let mut boxes = s.boxes.borrow_mut();
81 boxes.get().pop().unwrap();
86 pub fn rust_printer(writer: ~io::Writer, intr: @IdentInterner) -> State {
87 return rust_printer_annotated(writer, intr, @NoAnn as @PpAnn);
90 pub fn rust_printer_annotated(writer: ~io::Writer,
95 s: pp::mk_printer(writer, default_columns),
100 cur_cmnt_and_lit: CurrentCommentAndLiteral {
104 boxes: RefCell::new(~[]),
109 pub static indent_unit: uint = 4u;
111 pub static default_columns: uint = 78u;
113 // Requires you to pass an input filename and reader so that
114 // it can scan the input text for comments and literals to
116 pub fn print_crate(cm: @CodeMap,
117 intr: @IdentInterner,
118 span_diagnostic: @diagnostic::SpanHandler,
121 input: &mut io::Reader,
125 let (cmnts, lits) = comments::gather_comments_and_literals(
131 s: pp::mk_printer(out, default_columns),
134 comments: Some(cmnts),
135 // If the code is post expansion, don't use the table of
136 // literals, since it doesn't correspond with the literals
137 // in the AST anymore.
138 literals: if is_expanded {
143 cur_cmnt_and_lit: CurrentCommentAndLiteral {
147 boxes: RefCell::new(~[]),
150 print_crate_(&mut s, crate);
153 pub fn print_crate_(s: &mut State, crate: &ast::Crate) {
154 print_mod(s, &crate.module, crate.attrs);
155 print_remaining_comments(s);
159 pub fn ty_to_str(ty: &ast::Ty, intr: @IdentInterner) -> ~str {
160 to_str(ty, print_type, intr)
163 pub fn pat_to_str(pat: &ast::Pat, intr: @IdentInterner) -> ~str {
164 to_str(pat, print_pat, intr)
167 pub fn expr_to_str(e: &ast::Expr, intr: @IdentInterner) -> ~str {
168 to_str(e, print_expr, intr)
171 pub fn lifetime_to_str(e: &ast::Lifetime, intr: @IdentInterner) -> ~str {
172 to_str(e, print_lifetime, intr)
175 pub fn tt_to_str(tt: &ast::TokenTree, intr: @IdentInterner) -> ~str {
176 to_str(tt, print_tt, intr)
179 pub fn tts_to_str(tts: &[ast::TokenTree], intr: @IdentInterner) -> ~str {
180 to_str(&tts, print_tts, intr)
183 pub fn stmt_to_str(s: &ast::Stmt, intr: @IdentInterner) -> ~str {
184 to_str(s, print_stmt, intr)
187 pub fn item_to_str(i: &ast::Item, intr: @IdentInterner) -> ~str {
188 to_str(i, print_item, intr)
191 pub fn generics_to_str(generics: &ast::Generics,
192 intr: @IdentInterner) -> ~str {
193 to_str(generics, print_generics, intr)
196 pub fn path_to_str(p: &ast::Path, intr: @IdentInterner) -> ~str {
197 to_str(p, |a,b| print_path(a, b, false), intr)
200 pub fn fun_to_str(decl: &ast::FnDecl, purity: ast::Purity, name: ast::Ident,
201 opt_explicit_self: Option<ast::ExplicitSelf_>,
202 generics: &ast::Generics, intr: @IdentInterner) -> ~str {
203 let wr = ~MemWriter::new();
204 let mut s = rust_printer(wr as ~io::Writer, intr);
205 print_fn(&mut s, decl, Some(purity), AbiSet::Rust(),
206 name, generics, opt_explicit_self, ast::Inherited);
207 end(&mut s); // Close the head box
208 end(&mut s); // Close the outer box
211 get_mem_writer(&mut s.s.out)
215 pub fn block_to_str(blk: &ast::Block, intr: @IdentInterner) -> ~str {
216 let wr = ~MemWriter::new();
217 let mut s = rust_printer(wr as ~io::Writer, intr);
218 // containing cbox, will be closed by print-block at }
219 cbox(&mut s, indent_unit);
220 // head-ibox, will be closed by print-block after {
222 print_block(&mut s, blk);
225 get_mem_writer(&mut s.s.out)
229 pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @IdentInterner) -> ~str {
230 to_str(mi, print_meta_item, intr)
233 pub fn attribute_to_str(attr: &ast::Attribute, intr: @IdentInterner) -> ~str {
234 to_str(attr, print_attribute, intr)
237 pub fn variant_to_str(var: &ast::Variant, intr: @IdentInterner) -> ~str {
238 to_str(var, print_variant, intr)
241 pub fn cbox(s: &mut State, u: uint) {
243 let mut boxes = s.boxes.borrow_mut();
244 boxes.get().push(pp::Consistent);
246 pp::cbox(&mut s.s, u);
250 pub fn rbox(s: &mut State, u: uint, b: pp::Breaks) {
252 let mut boxes = s.boxes.borrow_mut();
255 pp::rbox(&mut s.s, u, b);
258 pub fn nbsp(s: &mut State) { word(&mut s.s, " "); }
260 pub fn word_nbsp(s: &mut State, w: &str) { word(&mut s.s, w); nbsp(s); }
262 pub fn word_space(s: &mut State, w: &str) { word(&mut s.s, w); space(&mut s.s); }
264 pub fn popen(s: &mut State) { word(&mut s.s, "("); }
266 pub fn pclose(s: &mut State) { word(&mut s.s, ")"); }
268 pub fn head(s: &mut State, w: &str) {
269 // outer-box is consistent
270 cbox(s, indent_unit);
271 // head-box is inconsistent
272 ibox(s, w.len() + 1);
273 // keyword that starts the head
279 pub fn bopen(s: &mut State) {
281 end(s); // close the head-box
284 pub fn bclose_(s: &mut State, span: codemap::Span, indented: uint) {
285 bclose_maybe_open(s, span, indented, true);
287 pub fn bclose_maybe_open (s: &mut State, span: codemap::Span,
288 indented: uint, close_box: bool) {
289 maybe_print_comment(s, span.hi);
290 break_offset_if_not_bol(s, 1u, -(indented as int));
293 end(s); // close the outer-box
296 pub fn bclose(s: &mut State, span: codemap::Span) {
297 bclose_(s, span, indent_unit);
300 pub fn is_begin(s: &mut State) -> bool {
301 match s.s.last_token() { pp::Begin(_) => true, _ => false }
304 pub fn is_end(s: &mut State) -> bool {
305 match s.s.last_token() { pp::End => true, _ => false }
308 pub fn is_bol(s: &mut State) -> bool {
309 return s.s.last_token().is_eof() || s.s.last_token().is_hardbreak_tok();
312 pub fn in_cbox(s: &mut State) -> bool {
313 let boxes = s.boxes.borrow();
314 let len = boxes.get().len();
315 if len == 0u { return false; }
316 return boxes.get()[len - 1u] == pp::Consistent;
319 pub fn hardbreak_if_not_bol(s: &mut State) {
324 pub fn space_if_not_bol(s: &mut State) { if !is_bol(s) { space(&mut s.s); } }
325 pub fn break_offset_if_not_bol(s: &mut State, n: uint, off: int) {
327 break_offset(&mut s.s, n, off);
329 if off != 0 && s.s.last_token().is_hardbreak_tok() {
330 // We do something pretty sketchy here: tuck the nonzero
331 // offset-adjustment we were going to deposit along with the
332 // break into the previous hardbreak.
333 s.s.replace_last_token(pp::hardbreak_tok_offset(off));
338 // Synthesizes a comment that was not textually present in the original source
340 pub fn synth_comment(s: &mut State, text: ~str) {
341 word(&mut s.s, "/*");
343 word(&mut s.s, text);
345 word(&mut s.s, "*/");
348 pub fn commasep<T>(s: &mut State, b: Breaks, elts: &[T], op: |&mut State, &T|) {
350 let mut first = true;
351 for elt in elts.iter() {
352 if first { first = false; } else { word_space(s, ","); }
359 pub fn commasep_cmnt<T>(
363 op: |&mut State, &T|,
364 get_span: |&T| -> codemap::Span) {
366 let len = elts.len();
368 for elt in elts.iter() {
369 maybe_print_comment(s, get_span(elt).hi);
374 maybe_print_trailing_comment(s, get_span(elt),
375 Some(get_span(&elts[i]).hi));
382 pub fn commasep_exprs(s: &mut State, b: Breaks, exprs: &[@ast::Expr]) {
383 commasep_cmnt(s, b, exprs, |p, &e| print_expr(p, e), |e| e.span);
386 pub fn print_mod(s: &mut State, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
387 print_inner_attributes(s, attrs);
388 for vitem in _mod.view_items.iter() {
389 print_view_item(s, vitem);
391 for item in _mod.items.iter() { print_item(s, *item); }
394 pub fn print_foreign_mod(s: &mut State, nmod: &ast::ForeignMod,
395 attrs: &[ast::Attribute]) {
396 print_inner_attributes(s, attrs);
397 for vitem in nmod.view_items.iter() {
398 print_view_item(s, vitem);
400 for item in nmod.items.iter() { print_foreign_item(s, *item); }
403 pub fn print_opt_lifetime(s: &mut State, lifetime: &Option<ast::Lifetime>) {
404 for l in lifetime.iter() {
405 print_lifetime(s, l);
410 pub fn print_type(s: &mut State, ty: &ast::Ty) {
411 maybe_print_comment(s, ty.span.lo);
414 ast::TyNil => word(&mut s.s, "()"),
415 ast::TyBot => word(&mut s.s, "!"),
416 ast::TyBox(ty) => { word(&mut s.s, "@"); print_type(s, ty); }
417 ast::TyUniq(ty) => { word(&mut s.s, "~"); print_type(s, ty); }
423 ast::TyPtr(ref mt) => { word(&mut s.s, "*"); print_mt(s, mt); }
424 ast::TyRptr(ref lifetime, ref mt) => {
426 print_opt_lifetime(s, lifetime);
429 ast::TyTup(ref elts) => {
431 commasep(s, Inconsistent, *elts, print_type_ref);
437 ast::TyBareFn(f) => {
438 let generics = ast::Generics {
439 lifetimes: f.lifetimes.clone(),
440 ty_params: opt_vec::Empty
442 print_ty_fn(s, Some(f.abis), None, &None,
443 f.purity, ast::Many, f.decl, None, &None,
444 Some(&generics), None);
446 ast::TyClosure(f) => {
447 let generics = ast::Generics {
448 lifetimes: f.lifetimes.clone(),
449 ty_params: opt_vec::Empty
451 print_ty_fn(s, None, Some(f.sigil), &f.region,
452 f.purity, f.onceness, f.decl, None, &f.bounds,
453 Some(&generics), None);
455 ast::TyPath(ref path, ref bounds, _) => print_bounded_path(s, path, bounds),
456 ast::TyFixedLengthVec(ty, v) => {
459 word(&mut s.s, ", ..");
463 ast::TyTypeof(e) => {
464 word(&mut s.s, "typeof(");
469 fail!("print_type shouldn't see a ty_infer");
475 pub fn print_type_ref(s: &mut State, ty: &P<ast::Ty>) {
479 pub fn print_foreign_item(s: &mut State, item: &ast::ForeignItem) {
480 hardbreak_if_not_bol(s);
481 maybe_print_comment(s, item.span.lo);
482 print_outer_attributes(s, item.attrs);
484 ast::ForeignItemFn(decl, ref generics) => {
485 print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, None,
487 end(s); // end head-ibox
489 end(s); // end the outer fn box
491 ast::ForeignItemStatic(t, m) => {
492 head(s, visibility_qualified(item.vis, "static"));
494 word_space(s, "mut");
496 print_ident(s, item.ident);
500 end(s); // end the head-ibox
501 end(s); // end the outer cbox
506 pub fn print_item(s: &mut State, item: &ast::Item) {
507 hardbreak_if_not_bol(s);
508 maybe_print_comment(s, item.span.lo);
509 print_outer_attributes(s, item.attrs);
511 let ann_node = NodeItem(s, item);
515 ast::ItemStatic(ty, m, expr) => {
516 head(s, visibility_qualified(item.vis, "static"));
517 if m == ast::MutMutable {
518 word_space(s, "mut");
520 print_ident(s, item.ident);
524 end(s); // end the head-ibox
529 end(s); // end the outer cbox
532 ast::ItemFn(decl, purity, abi, ref typarams, body) => {
544 print_block_with_attrs(s, body, item.attrs);
546 ast::ItemMod(ref _mod) => {
547 head(s, visibility_qualified(item.vis, "mod"));
548 print_ident(s, item.ident);
551 print_mod(s, _mod, item.attrs);
552 bclose(s, item.span);
554 ast::ItemForeignMod(ref nmod) => {
556 word_nbsp(s, nmod.abis.to_str());
558 print_foreign_mod(s, nmod, item.attrs);
559 bclose(s, item.span);
561 ast::ItemTy(ty, ref params) => {
562 ibox(s, indent_unit);
564 word_nbsp(s, visibility_qualified(item.vis, "type"));
565 print_ident(s, item.ident);
566 print_generics(s, params);
567 end(s); // end the inner ibox
573 end(s); // end the outer ibox
575 ast::ItemEnum(ref enum_definition, ref params) => {
585 ast::ItemStruct(struct_def, ref generics) => {
586 head(s, visibility_qualified(item.vis, "struct"));
587 print_struct(s, struct_def, generics, item.ident, item.span);
590 ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
591 head(s, visibility_qualified(item.vis, "impl"));
592 if generics.is_parameterized() {
593 print_generics(s, generics);
599 print_trait_ref(s, t);
601 word_space(s, "for");
610 print_inner_attributes(s, item.attrs);
611 for meth in methods.iter() {
612 print_method(s, *meth);
614 bclose(s, item.span);
616 ast::ItemTrait(ref generics, ref traits, ref methods) => {
617 head(s, visibility_qualified(item.vis, "trait"));
618 print_ident(s, item.ident);
619 print_generics(s, generics);
620 if traits.len() != 0u {
622 for (i, trait_) in traits.iter().enumerate() {
627 print_path(s, &trait_.path, false);
632 for meth in methods.iter() {
633 print_trait_method(s, meth);
635 bclose(s, item.span);
637 // I think it's reasonable to hide the context here:
638 ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
640 print_visibility(s, item.vis);
641 print_path(s, pth, false);
642 word(&mut s.s, "! ");
643 print_ident(s, item.ident);
644 cbox(s, indent_unit);
646 print_tts(s, &(tts.as_slice()));
652 let ann_node = NodeItem(s, item);
653 s.ann.post(ann_node);
657 fn print_trait_ref(s: &mut State, t: &ast::TraitRef) {
658 print_path(s, &t.path, false);
661 pub fn print_enum_def(s: &mut State, enum_definition: &ast::EnumDef,
662 generics: &ast::Generics, ident: ast::Ident,
663 span: codemap::Span, visibility: ast::Visibility) {
664 head(s, visibility_qualified(visibility, "enum"));
665 print_ident(s, ident);
666 print_generics(s, generics);
668 print_variants(s, enum_definition.variants, span);
671 pub fn print_variants(s: &mut State,
672 variants: &[P<ast::Variant>],
673 span: codemap::Span) {
675 for &v in variants.iter() {
677 maybe_print_comment(s, v.span.lo);
678 print_outer_attributes(s, v.node.attrs);
679 ibox(s, indent_unit);
683 maybe_print_trailing_comment(s, v.span, None);
688 pub fn visibility_to_str(vis: ast::Visibility) -> ~str {
690 ast::Private => ~"priv",
691 ast::Public => ~"pub",
692 ast::Inherited => ~""
696 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str {
698 ast::Private | ast::Public => visibility_to_str(vis) + " " + s,
699 ast::Inherited => s.to_owned()
703 pub fn print_visibility(s: &mut State, vis: ast::Visibility) {
705 ast::Private | ast::Public =>
706 word_nbsp(s, visibility_to_str(vis)),
711 pub fn print_struct(s: &mut State,
712 struct_def: &ast::StructDef,
713 generics: &ast::Generics,
715 span: codemap::Span) {
716 print_ident(s, ident);
717 print_generics(s, generics);
718 if ast_util::struct_def_is_tuple_like(struct_def) {
719 if !struct_def.fields.is_empty() {
721 commasep(s, Inconsistent, struct_def.fields, |s, field| {
722 match field.node.kind {
723 ast::NamedField(..) => fail!("unexpected named field"),
724 ast::UnnamedField => {
725 maybe_print_comment(s, field.span.lo);
726 print_type(s, field.node.ty);
734 end(s); // close the outer-box
738 hardbreak_if_not_bol(s);
740 for field in struct_def.fields.iter() {
741 match field.node.kind {
742 ast::UnnamedField => fail!("unexpected unnamed field"),
743 ast::NamedField(ident, visibility) => {
744 hardbreak_if_not_bol(s);
745 maybe_print_comment(s, field.span.lo);
746 print_outer_attributes(s, field.node.attrs);
747 print_visibility(s, visibility);
748 print_ident(s, ident);
750 print_type(s, field.node.ty);
760 /// This doesn't deserve to be called "pretty" printing, but it should be
761 /// meaning-preserving. A quick hack that might help would be to look at the
762 /// spans embedded in the TTs to decide where to put spaces and newlines.
763 /// But it'd be better to parse these according to the grammar of the
764 /// appropriate macro, transcribe back into the grammar we just parsed from,
765 /// and then pretty-print the resulting AST nodes (so, e.g., we print
766 /// expression arguments as expressions). It can be done! I think.
767 pub fn print_tt(s: &mut State, tt: &ast::TokenTree) {
769 ast::TTDelim(ref tts) => print_tts(s, &(tts.as_slice())),
770 ast::TTTok(_, ref tk) => {
771 word(&mut s.s, parse::token::to_str(s.intr, tk));
773 ast::TTSeq(_, ref tts, ref sep, zerok) => {
774 word(&mut s.s, "$(");
775 for tt_elt in (*tts).iter() { print_tt(s, tt_elt); }
778 Some(ref tk) => word(&mut s.s, parse::token::to_str(s.intr, tk)),
781 word(&mut s.s, if zerok { "*" } else { "+" });
783 ast::TTNonterminal(_, name) => {
785 print_ident(s, name);
790 pub fn print_tts(s: &mut State, tts: & &[ast::TokenTree]) {
792 for (i, tt) in tts.iter().enumerate() {
801 pub fn print_variant(s: &mut State, v: &ast::Variant) {
802 print_visibility(s, v.node.vis);
804 ast::TupleVariantKind(ref args) => {
805 print_ident(s, v.node.name);
806 if !args.is_empty() {
808 fn print_variant_arg(s: &mut State, arg: &ast::VariantArg) {
809 print_type(s, arg.ty);
811 commasep(s, Consistent, *args, print_variant_arg);
815 ast::StructVariantKind(struct_def) => {
817 let generics = ast_util::empty_generics();
818 print_struct(s, struct_def, &generics, v.node.name, v.span);
821 match v.node.disr_expr {
831 pub fn print_ty_method(s: &mut State, m: &ast::TypeMethod) {
832 hardbreak_if_not_bol(s);
833 maybe_print_comment(s, m.span.lo);
834 print_outer_attributes(s, m.attrs);
845 Some(m.explicit_self.node));
849 pub fn print_trait_method(s: &mut State, m: &ast::TraitMethod) {
851 Required(ref ty_m) => print_ty_method(s, ty_m),
852 Provided(m) => print_method(s, m)
856 pub fn print_method(s: &mut State, meth: &ast::Method) {
857 hardbreak_if_not_bol(s);
858 maybe_print_comment(s, meth.span.lo);
859 print_outer_attributes(s, meth.attrs);
860 print_fn(s, meth.decl, Some(meth.purity), AbiSet::Rust(),
861 meth.ident, &meth.generics, Some(meth.explicit_self.node),
864 print_block_with_attrs(s, meth.body, meth.attrs);
867 pub fn print_outer_attributes(s: &mut State, attrs: &[ast::Attribute]) {
869 for attr in attrs.iter() {
870 match attr.node.style {
871 ast::AttrOuter => { print_attribute(s, attr); count += 1; }
872 _ => {/* fallthrough */ }
875 if count > 0 { hardbreak_if_not_bol(s); }
878 pub fn print_inner_attributes(s: &mut State, attrs: &[ast::Attribute]) {
880 for attr in attrs.iter() {
881 match attr.node.style {
883 print_attribute(s, attr);
884 if !attr.node.is_sugared_doc {
889 _ => {/* fallthrough */ }
892 if count > 0 { hardbreak_if_not_bol(s); }
895 pub fn print_attribute(s: &mut State, attr: &ast::Attribute) {
896 hardbreak_if_not_bol(s);
897 maybe_print_comment(s, attr.span.lo);
898 if attr.node.is_sugared_doc {
899 let comment = attr.value_str().unwrap();
900 word(&mut s.s, comment.get());
902 word(&mut s.s, "#[");
903 print_meta_item(s, attr.meta());
909 pub fn print_stmt(s: &mut State, st: &ast::Stmt) {
910 maybe_print_comment(s, st.span.lo);
912 ast::StmtDecl(decl, _) => {
915 ast::StmtExpr(expr, _) => {
919 ast::StmtSemi(expr, _) => {
924 ast::StmtMac(ref mac, semi) => {
927 if semi { word(&mut s.s, ";"); }
930 if parse::classify::stmt_ends_with_semi(st) { word(&mut s.s, ";"); }
931 maybe_print_trailing_comment(s, st.span, None);
934 pub fn print_block(s: &mut State, blk: &ast::Block) {
935 print_possibly_embedded_block(s, blk, BlockNormal, indent_unit);
938 pub fn print_block_unclosed(s: &mut State, blk: &ast::Block) {
939 print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, &[],
943 pub fn print_block_unclosed_indent(s: &mut State, blk: &ast::Block, indented: uint) {
944 print_possibly_embedded_block_(s, blk, BlockNormal, indented, &[], false);
947 pub fn print_block_with_attrs(s: &mut State,
949 attrs: &[ast::Attribute]) {
950 print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, attrs,
959 pub fn print_possibly_embedded_block(s: &mut State,
963 print_possibly_embedded_block_(
964 s, blk, embedded, indented, &[], true);
967 pub fn print_possibly_embedded_block_(s: &mut State,
971 attrs: &[ast::Attribute],
974 ast::UnsafeBlock(..) => word_space(s, "unsafe"),
975 ast::DefaultBlock => ()
977 maybe_print_comment(s, blk.span.lo);
979 let ann_node = NodeBlock(s, blk);
983 BlockBlockFn => end(s),
984 BlockNormal => bopen(s)
987 print_inner_attributes(s, attrs);
989 for vi in blk.view_items.iter() { print_view_item(s, vi); }
990 for st in blk.stmts.iter() {
997 maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
1001 bclose_maybe_open(s, blk.span, indented, close_box);
1003 let ann_node = NodeBlock(s, blk);
1004 s.ann.post(ann_node);
1008 pub fn print_if(s: &mut State, test: &ast::Expr, blk: &ast::Block,
1009 elseopt: Option<@ast::Expr>, chk: bool) {
1011 if chk { word_nbsp(s, "check"); }
1012 print_expr(s, test);
1014 print_block(s, blk);
1015 fn do_else(s: &mut State, els: Option<@ast::Expr>) {
1019 // "another else-if"
1020 ast::ExprIf(i, t, e) => {
1021 cbox(s, indent_unit - 1u);
1023 word(&mut s.s, " else if ");
1030 ast::ExprBlock(b) => {
1031 cbox(s, indent_unit - 1u);
1033 word(&mut s.s, " else ");
1036 // BLEAH, constraints would be great here
1038 fail!("print_if saw if with weird alternative");
1042 _ => {/* fall through */ }
1045 do_else(s, elseopt);
1048 pub fn print_mac(s: &mut State, m: &ast::Mac) {
1050 // I think it's reasonable to hide the ctxt here:
1051 ast::MacInvocTT(ref pth, ref tts, _) => {
1052 print_path(s, pth, false);
1053 word(&mut s.s, "!");
1055 print_tts(s, &tts.as_slice());
1061 pub fn print_vstore(s: &mut State, t: ast::Vstore) {
1063 ast::VstoreFixed(Some(i)) => word(&mut s.s, format!("{}", i)),
1064 ast::VstoreFixed(None) => word(&mut s.s, "_"),
1065 ast::VstoreUniq => word(&mut s.s, "~"),
1066 ast::VstoreBox => word(&mut s.s, "@"),
1067 ast::VstoreSlice(ref r) => {
1068 word(&mut s.s, "&");
1069 print_opt_lifetime(s, r);
1074 pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) {
1076 ast::ExprVstoreUniq => word(&mut s.s, "~"),
1077 ast::ExprVstoreBox => word(&mut s.s, "@"),
1078 ast::ExprVstoreSlice => word(&mut s.s, "&"),
1079 ast::ExprVstoreMutSlice => {
1080 word(&mut s.s, "&");
1081 word(&mut s.s, "mut");
1086 pub fn print_call_pre(s: &mut State,
1087 sugar: ast::CallSugar,
1088 base_args: &mut ~[@ast::Expr])
1089 -> Option<@ast::Expr> {
1093 Some(base_args.pop().unwrap())
1095 ast::NoSugar => None
1099 pub fn print_call_post(s: &mut State,
1100 sugar: ast::CallSugar,
1101 blk: &Option<@ast::Expr>,
1102 base_args: &mut ~[@ast::Expr]) {
1103 if sugar == ast::NoSugar || !base_args.is_empty() {
1105 commasep_exprs(s, Inconsistent, *base_args);
1108 if sugar != ast::NoSugar {
1110 // not sure if this can happen
1111 print_expr(s, blk.unwrap());
1115 pub fn print_expr(s: &mut State, expr: &ast::Expr) {
1116 fn print_field(s: &mut State, field: &ast::Field) {
1117 ibox(s, indent_unit);
1118 print_ident(s, field.ident.node);
1120 print_expr(s, field.expr);
1123 fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1125 maybe_print_comment(s, expr.span.lo);
1126 ibox(s, indent_unit);
1128 let ann_node = NodeExpr(s, expr);
1129 s.ann.pre(ann_node);
1132 ast::ExprVstore(e, v) => {
1133 print_expr_vstore(s, v);
1136 ast::ExprBox(p, e) => {
1137 word(&mut s.s, "box");
1138 word(&mut s.s, "(");
1143 ast::ExprVec(ref exprs, mutbl) => {
1144 ibox(s, indent_unit);
1145 word(&mut s.s, "[");
1146 if mutbl == ast::MutMutable {
1147 word(&mut s.s, "mut");
1148 if exprs.len() > 0u { nbsp(s); }
1150 commasep_exprs(s, Inconsistent, *exprs);
1151 word(&mut s.s, "]");
1155 ast::ExprRepeat(element, count, mutbl) => {
1156 ibox(s, indent_unit);
1157 word(&mut s.s, "[");
1158 if mutbl == ast::MutMutable {
1159 word(&mut s.s, "mut");
1162 print_expr(s, element);
1163 word(&mut s.s, ",");
1164 word(&mut s.s, "..");
1165 print_expr(s, count);
1166 word(&mut s.s, "]");
1170 ast::ExprStruct(ref path, ref fields, wth) => {
1171 print_path(s, path, true);
1172 word(&mut s.s, "{");
1173 commasep_cmnt(s, Consistent, (*fields), print_field, get_span);
1176 ibox(s, indent_unit);
1177 if !fields.is_empty() {
1178 word(&mut s.s, ",");
1181 word(&mut s.s, "..");
1182 print_expr(s, expr);
1185 _ => (word(&mut s.s, ","))
1187 word(&mut s.s, "}");
1189 ast::ExprTup(ref exprs) => {
1191 commasep_exprs(s, Inconsistent, *exprs);
1192 if exprs.len() == 1 {
1193 word(&mut s.s, ",");
1197 ast::ExprCall(func, ref args, sugar) => {
1198 let mut base_args = (*args).clone();
1199 let blk = print_call_pre(s, sugar, &mut base_args);
1200 print_expr(s, func);
1201 print_call_post(s, sugar, &blk, &mut base_args);
1203 ast::ExprMethodCall(_, ident, ref tys, ref args, sugar) => {
1204 let mut base_args = args.slice_from(1).to_owned();
1205 let blk = print_call_pre(s, sugar, &mut base_args);
1206 print_expr(s, args[0]);
1207 word(&mut s.s, ".");
1208 print_ident(s, ident);
1210 word(&mut s.s, "::<");
1211 commasep(s, Inconsistent, *tys, print_type_ref);
1212 word(&mut s.s, ">");
1214 print_call_post(s, sugar, &blk, &mut base_args);
1216 ast::ExprBinary(_, op, lhs, rhs) => {
1219 word_space(s, ast_util::binop_to_str(op));
1222 ast::ExprUnary(_, op, expr) => {
1223 word(&mut s.s, ast_util::unop_to_str(op));
1224 print_expr(s, expr);
1226 ast::ExprAddrOf(m, expr) => {
1227 word(&mut s.s, "&");
1228 print_mutability(s, m);
1229 // Avoid `& &e` => `&&e`.
1230 match (m, &expr.node) {
1231 (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(&mut s.s),
1234 print_expr(s, expr);
1236 ast::ExprLit(lit) => print_literal(s, lit),
1237 ast::ExprCast(expr, ty) => {
1238 print_expr(s, expr);
1240 word_space(s, "as");
1243 ast::ExprIf(test, blk, elseopt) => {
1244 print_if(s, test, blk, elseopt, false);
1246 ast::ExprWhile(test, blk) => {
1248 print_expr(s, test);
1250 print_block(s, blk);
1252 ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1253 for ident in opt_ident.iter() {
1254 word(&mut s.s, "'");
1255 print_ident(s, *ident);
1261 word_space(s, "in");
1262 print_expr(s, iter);
1264 print_block(s, blk);
1266 ast::ExprLoop(blk, opt_ident) => {
1267 for ident in opt_ident.iter() {
1268 word(&mut s.s, "'");
1269 print_ident(s, *ident);
1274 print_block(s, blk);
1276 ast::ExprMatch(expr, ref arms) => {
1277 cbox(s, indent_unit);
1279 word_nbsp(s, "match");
1280 print_expr(s, expr);
1283 let len = arms.len();
1284 for (i, arm) in arms.iter().enumerate() {
1286 cbox(s, indent_unit);
1288 let mut first = true;
1289 for p in arm.pats.iter() {
1292 } else { space(&mut s.s); word_space(s, "|"); }
1298 word_space(s, "if");
1304 word_space(s, "=>");
1306 // Extract the expression from the extra block the parser adds
1307 // in the case of foo => expr
1308 if arm.body.view_items.is_empty() &&
1309 arm.body.stmts.is_empty() &&
1310 arm.body.rules == ast::DefaultBlock &&
1311 arm.body.expr.is_some()
1313 match arm.body.expr {
1316 ast::ExprBlock(blk) => {
1317 // the block will close the pattern's ibox
1318 print_block_unclosed_indent(
1319 s, blk, indent_unit);
1322 end(s); // close the ibox for the pattern
1323 print_expr(s, expr);
1326 if !expr_is_simple_block(expr)
1328 word(&mut s.s, ",");
1330 end(s); // close enclosing cbox
1335 // the block will close the pattern's ibox
1336 print_block_unclosed_indent(s, arm.body, indent_unit);
1339 bclose_(s, expr.span, indent_unit);
1341 ast::ExprFnBlock(decl, body) => {
1342 // in do/for blocks we don't want to show an empty
1343 // argument list, but at this point we don't know which
1346 // if !decl.inputs.is_empty() {
1347 print_fn_block_args(s, decl);
1350 assert!(body.stmts.is_empty());
1351 assert!(body.expr.is_some());
1352 // we extract the block, so as not to create another set of boxes
1353 match body.expr.unwrap().node {
1354 ast::ExprBlock(blk) => {
1355 print_block_unclosed(s, blk);
1358 // this is a bare expression
1359 print_expr(s, body.expr.unwrap());
1360 end(s); // need to close a box
1363 // a box will be closed by print_expr, but we didn't want an overall
1364 // wrapper so we closed the corresponding opening. so create an
1365 // empty box to satisfy the close.
1368 ast::ExprProc(decl, body) => {
1369 // in do/for blocks we don't want to show an empty
1370 // argument list, but at this point we don't know which
1373 // if !decl.inputs.is_empty() {
1374 print_proc_args(s, decl);
1377 assert!(body.stmts.is_empty());
1378 assert!(body.expr.is_some());
1379 // we extract the block, so as not to create another set of boxes
1380 match body.expr.unwrap().node {
1381 ast::ExprBlock(blk) => {
1382 print_block_unclosed(s, blk);
1385 // this is a bare expression
1386 print_expr(s, body.expr.unwrap());
1387 end(s); // need to close a box
1390 // a box will be closed by print_expr, but we didn't want an overall
1391 // wrapper so we closed the corresponding opening. so create an
1392 // empty box to satisfy the close.
1395 ast::ExprBlock(blk) => {
1396 // containing cbox, will be closed by print-block at }
1397 cbox(s, indent_unit);
1398 // head-box, will be closed by print-block after {
1400 print_block(s, blk);
1402 ast::ExprAssign(lhs, rhs) => {
1408 ast::ExprAssignOp(_, op, lhs, rhs) => {
1411 word(&mut s.s, ast_util::binop_to_str(op));
1415 ast::ExprField(expr, id, ref tys) => {
1416 print_expr(s, expr);
1417 word(&mut s.s, ".");
1420 word(&mut s.s, "::<");
1421 commasep(s, Inconsistent, *tys, print_type_ref);
1422 word(&mut s.s, ">");
1425 ast::ExprIndex(_, expr, index) => {
1426 print_expr(s, expr);
1427 word(&mut s.s, "[");
1428 print_expr(s, index);
1429 word(&mut s.s, "]");
1431 ast::ExprPath(ref path) => print_path(s, path, true),
1432 ast::ExprBreak(opt_ident) => {
1433 word(&mut s.s, "break");
1435 for ident in opt_ident.iter() {
1436 word(&mut s.s, "'");
1437 print_name(s, *ident);
1441 ast::ExprAgain(opt_ident) => {
1442 word(&mut s.s, "continue");
1444 for ident in opt_ident.iter() {
1445 word(&mut s.s, "'");
1446 print_name(s, *ident);
1450 ast::ExprRet(result) => {
1451 word(&mut s.s, "return");
1453 Some(expr) => { word(&mut s.s, " "); print_expr(s, expr); }
1457 ast::ExprLogLevel => {
1458 word(&mut s.s, "__log_level");
1462 ast::ExprInlineAsm(ref a) => {
1464 word(&mut s.s, "__volatile__ asm!");
1466 word(&mut s.s, "asm!");
1469 print_string(s, a.asm.get(), a.asm_str_style);
1471 for &(ref co, o) in a.outputs.iter() {
1472 print_string(s, co.get(), ast::CookedStr);
1479 for &(ref co, o) in a.inputs.iter() {
1480 print_string(s, co.get(), ast::CookedStr);
1487 print_string(s, a.clobbers.get(), ast::CookedStr);
1490 ast::ExprMac(ref m) => print_mac(s, m),
1491 ast::ExprParen(e) => {
1498 let ann_node = NodeExpr(s, expr);
1499 s.ann.post(ann_node);
1504 pub fn print_local_decl(s: &mut State, loc: &ast::Local) {
1505 print_pat(s, loc.pat);
1508 _ => { word_space(s, ":"); print_type(s, loc.ty); }
1512 pub fn print_decl(s: &mut State, decl: &ast::Decl) {
1513 maybe_print_comment(s, decl.span.lo);
1515 ast::DeclLocal(ref loc) => {
1516 space_if_not_bol(s);
1517 ibox(s, indent_unit);
1518 word_nbsp(s, "let");
1520 fn print_local(s: &mut State, loc: &ast::Local) {
1521 ibox(s, indent_unit);
1522 print_local_decl(s, loc);
1528 print_expr(s, init);
1534 print_local(s, *loc);
1537 ast::DeclItem(item) => print_item(s, item)
1541 pub fn print_ident(s: &mut State, ident: ast::Ident) {
1542 let string = token::get_ident(ident.name);
1543 word(&mut s.s, string.get());
1546 pub fn print_name(s: &mut State, name: ast::Name) {
1547 word(&mut s.s, interner_get(name));
1550 pub fn print_for_decl(s: &mut State, loc: &ast::Local, coll: &ast::Expr) {
1551 print_local_decl(s, loc);
1553 word_space(s, "in");
1554 print_expr(s, coll);
1557 fn print_path_(s: &mut State,
1559 colons_before_params: bool,
1560 opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1561 maybe_print_comment(s, path.span.lo);
1563 word(&mut s.s, "::");
1566 let mut first = true;
1567 for (i, segment) in path.segments.iter().enumerate() {
1571 word(&mut s.s, "::")
1574 print_ident(s, segment.identifier);
1576 // If this is the last segment, print the bounds.
1577 if i == path.segments.len() - 1 {
1580 Some(ref bounds) => print_bounds(s, bounds, true),
1584 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1585 if colons_before_params {
1586 word(&mut s.s, "::")
1588 word(&mut s.s, "<");
1590 let mut comma = false;
1591 for lifetime in segment.lifetimes.iter() {
1595 print_lifetime(s, lifetime);
1599 if !segment.types.is_empty() {
1605 segment.types.map_to_vec(|&t| t),
1614 pub fn print_path(s: &mut State, path: &ast::Path, colons_before_params: bool) {
1615 print_path_(s, path, colons_before_params, &None)
1618 pub fn print_bounded_path(s: &mut State, path: &ast::Path,
1619 bounds: &Option<OptVec<ast::TyParamBound>>) {
1620 print_path_(s, path, false, bounds)
1623 pub fn print_pat(s: &mut State, pat: &ast::Pat) {
1624 maybe_print_comment(s, pat.span.lo);
1626 let ann_node = NodePat(s, pat);
1627 s.ann.pre(ann_node);
1629 /* Pat isn't normalized, but the beauty of it
1630 is that it doesn't matter */
1632 ast::PatWild => word(&mut s.s, "_"),
1633 ast::PatWildMulti => word(&mut s.s, ".."),
1634 ast::PatIdent(binding_mode, ref path, sub) => {
1635 match binding_mode {
1636 ast::BindByRef(mutbl) => {
1637 word_nbsp(s, "ref");
1638 print_mutability(s, mutbl);
1640 ast::BindByValue(ast::MutImmutable) => {}
1641 ast::BindByValue(ast::MutMutable) => {
1642 word_nbsp(s, "mut");
1645 print_path(s, path, true);
1648 word(&mut s.s, "@");
1654 ast::PatEnum(ref path, ref args_) => {
1655 print_path(s, path, true);
1657 None => word(&mut s.s, "(..)"),
1659 if !args.is_empty() {
1661 commasep(s, Inconsistent, *args,
1662 |s, &p| print_pat(s, p));
1668 ast::PatStruct(ref path, ref fields, etc) => {
1669 print_path(s, path, true);
1670 word(&mut s.s, "{");
1671 fn print_field(s: &mut State, f: &ast::FieldPat) {
1672 cbox(s, indent_unit);
1673 print_ident(s, f.ident);
1675 print_pat(s, f.pat);
1678 fn get_span(f: &ast::FieldPat) -> codemap::Span { return f.pat.span; }
1679 commasep_cmnt(s, Consistent, *fields,
1680 |s, f| print_field(s,f),
1683 if fields.len() != 0u { word_space(s, ","); }
1684 word(&mut s.s, "..");
1686 word(&mut s.s, "}");
1688 ast::PatTup(ref elts) => {
1690 commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p));
1691 if elts.len() == 1 {
1692 word(&mut s.s, ",");
1696 ast::PatUniq(inner) => {
1697 word(&mut s.s, "~");
1698 print_pat(s, inner);
1700 ast::PatRegion(inner) => {
1701 word(&mut s.s, "&");
1702 print_pat(s, inner);
1704 ast::PatLit(e) => print_expr(s, e),
1705 ast::PatRange(begin, end) => {
1706 print_expr(s, begin);
1708 word(&mut s.s, "..");
1711 ast::PatVec(ref before, slice, ref after) => {
1712 word(&mut s.s, "[");
1713 commasep(s, Inconsistent, *before, |s, &p| print_pat(s, p));
1714 for &p in slice.iter() {
1715 if !before.is_empty() { word_space(s, ","); }
1717 ast::Pat { node: ast::PatWildMulti, .. } => {
1718 // this case is handled by print_pat
1720 _ => word(&mut s.s, ".."),
1723 if !after.is_empty() { word_space(s, ","); }
1725 commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p));
1726 word(&mut s.s, "]");
1730 let ann_node = NodePat(s, pat);
1731 s.ann.post(ann_node);
1735 pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_, intr: @IdentInterner) -> ~str {
1736 to_str(explicit_self, |a, &b| { print_explicit_self(a, b, ast::MutImmutable); () }, intr)
1739 // Returns whether it printed anything
1740 fn print_explicit_self(s: &mut State,
1741 explicit_self: ast::ExplicitSelf_,
1742 mutbl: ast::Mutability) -> bool {
1743 print_mutability(s, mutbl);
1744 match explicit_self {
1745 ast::SelfStatic => { return false; }
1747 word(&mut s.s, "self");
1750 word(&mut s.s, "~self");
1752 ast::SelfRegion(ref lt, m) => {
1753 word(&mut s.s, "&");
1754 print_opt_lifetime(s, lt);
1755 print_mutability(s, m);
1756 word(&mut s.s, "self");
1759 word(&mut s.s, "@self");
1765 pub fn print_fn(s: &mut State,
1767 purity: Option<ast::Purity>,
1770 generics: &ast::Generics,
1771 opt_explicit_self: Option<ast::ExplicitSelf_>,
1772 vis: ast::Visibility) {
1774 print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1776 print_ident(s, name);
1777 print_generics(s, generics);
1778 print_fn_args_and_ret(s, decl, opt_explicit_self);
1781 pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl,
1782 opt_explicit_self: Option<ast::ExplicitSelf_>) {
1783 // It is unfortunate to duplicate the commasep logic, but we want the
1784 // self type and the args all in the same box.
1785 rbox(s, 0u, Inconsistent);
1786 let mut first = true;
1787 for &explicit_self in opt_explicit_self.iter() {
1788 let m = match explicit_self {
1789 ast::SelfStatic => ast::MutImmutable,
1790 _ => match decl.inputs[0].pat.node {
1791 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1792 _ => ast::MutImmutable
1795 first = !print_explicit_self(s, explicit_self, m);
1798 // HACK(eddyb) ignore the separately printed self argument.
1799 let args = if first {
1800 decl.inputs.as_slice()
1802 decl.inputs.slice_from(1)
1805 for arg in args.iter() {
1806 if first { first = false; } else { word_space(s, ","); }
1813 pub fn print_fn_args_and_ret(s: &mut State, decl: &ast::FnDecl,
1814 opt_explicit_self: Option<ast::ExplicitSelf_>) {
1816 print_fn_args(s, decl, opt_explicit_self);
1818 word(&mut s.s, ", ...");
1822 maybe_print_comment(s, decl.output.span.lo);
1823 match decl.output.node {
1826 space_if_not_bol(s);
1827 word_space(s, "->");
1828 print_type(s, decl.output);
1833 pub fn print_fn_block_args(s: &mut State, decl: &ast::FnDecl) {
1834 word(&mut s.s, "|");
1835 print_fn_args(s, decl, None);
1836 word(&mut s.s, "|");
1838 match decl.output.node {
1841 space_if_not_bol(s);
1842 word_space(s, "->");
1843 print_type(s, decl.output);
1847 maybe_print_comment(s, decl.output.span.lo);
1850 pub fn print_proc_args(s: &mut State, decl: &ast::FnDecl) {
1851 word(&mut s.s, "proc");
1852 word(&mut s.s, "(");
1853 print_fn_args(s, decl, None);
1854 word(&mut s.s, ")");
1856 match decl.output.node {
1859 space_if_not_bol(s);
1860 word_space(s, "->");
1861 print_type(s, decl.output);
1865 maybe_print_comment(s, decl.output.span.lo);
1868 pub fn print_bounds(s: &mut State, bounds: &OptVec<ast::TyParamBound>,
1869 print_colon_anyway: bool) {
1870 if !bounds.is_empty() {
1871 word(&mut s.s, ":");
1872 let mut first = true;
1873 for bound in bounds.iter() {
1882 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1883 RegionTyParamBound => word(&mut s.s, "'static"),
1886 } else if print_colon_anyway {
1887 word(&mut s.s, ":");
1891 pub fn print_lifetime(s: &mut State, lifetime: &ast::Lifetime) {
1892 word(&mut s.s, "'");
1893 print_ident(s, lifetime.ident);
1896 pub fn print_generics(s: &mut State, generics: &ast::Generics) {
1897 let total = generics.lifetimes.len() + generics.ty_params.len();
1899 word(&mut s.s, "<");
1900 fn print_item(s: &mut State, generics: &ast::Generics, idx: uint) {
1901 if idx < generics.lifetimes.len() {
1902 let lifetime = generics.lifetimes.get(idx);
1903 print_lifetime(s, lifetime);
1905 let idx = idx - generics.lifetimes.len();
1906 let param = generics.ty_params.get(idx);
1907 print_ident(s, param.ident);
1908 print_bounds(s, ¶m.bounds, false);
1909 match param.default {
1913 print_type(s, default);
1921 for i in range(0u, total) {
1925 commasep(s, Inconsistent, ints,
1926 |s, &i| print_item(s, generics, i));
1927 word(&mut s.s, ">");
1931 pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) {
1932 ibox(s, indent_unit);
1934 ast::MetaWord(ref name) => word(&mut s.s, name.get()),
1935 ast::MetaNameValue(ref name, ref value) => {
1936 word_space(s, name.get());
1938 print_literal(s, value);
1940 ast::MetaList(ref name, ref items) => {
1941 word(&mut s.s, name.get());
1946 |p, &i| print_meta_item(p, i));
1953 pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) {
1955 ast::ViewPathSimple(ident, ref path, _) => {
1956 // FIXME(#6993) can't compare identifiers directly here
1957 if path.segments.last().unwrap().identifier.name != ident.name {
1958 print_ident(s, ident);
1962 print_path(s, path, false);
1965 ast::ViewPathGlob(ref path, _) => {
1966 print_path(s, path, false);
1967 word(&mut s.s, "::*");
1970 ast::ViewPathList(ref path, ref idents, _) => {
1971 if path.segments.is_empty() {
1972 word(&mut s.s, "{");
1974 print_path(s, path, false);
1975 word(&mut s.s, "::{");
1977 commasep(s, Inconsistent, (*idents), |s, w| {
1978 print_ident(s, w.node.name);
1980 word(&mut s.s, "}");
1985 pub fn print_view_paths(s: &mut State, vps: &[@ast::ViewPath]) {
1986 commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp));
1989 pub fn print_view_item(s: &mut State, item: &ast::ViewItem) {
1990 hardbreak_if_not_bol(s);
1991 maybe_print_comment(s, item.span.lo);
1992 print_outer_attributes(s, item.attrs);
1993 print_visibility(s, item.vis);
1995 ast::ViewItemExternMod(id, ref optional_path, _) => {
1996 head(s, "extern mod");
1998 for &(ref p, style) in optional_path.iter() {
2000 word(&mut s.s, "=");
2002 print_string(s, p.get(), style);
2006 ast::ViewItemUse(ref vps) => {
2008 print_view_paths(s, *vps);
2011 word(&mut s.s, ";");
2012 end(s); // end inner head-block
2013 end(s); // end outer head-block
2016 pub fn print_mutability(s: &mut State, mutbl: ast::Mutability) {
2018 ast::MutMutable => word_nbsp(s, "mut"),
2019 ast::MutImmutable => {/* nothing */ }
2023 pub fn print_mt(s: &mut State, mt: &ast::MutTy) {
2024 print_mutability(s, mt.mutbl);
2025 print_type(s, mt.ty);
2028 pub fn print_arg(s: &mut State, input: &ast::Arg) {
2029 ibox(s, indent_unit);
2030 match input.ty.node {
2031 ast::TyInfer => print_pat(s, input.pat),
2033 match input.pat.node {
2034 ast::PatIdent(_, ref path, _) if
2035 path.segments.len() == 1 &&
2036 path.segments[0].identifier.name ==
2037 parse::token::special_idents::invalid.name => {
2041 print_pat(s, input.pat);
2042 word(&mut s.s, ":");
2046 print_type(s, input.ty);
2052 pub fn print_ty_fn(s: &mut State,
2053 opt_abis: Option<AbiSet>,
2054 opt_sigil: Option<ast::Sigil>,
2055 opt_region: &Option<ast::Lifetime>,
2056 purity: ast::Purity,
2057 onceness: ast::Onceness,
2059 id: Option<ast::Ident>,
2060 opt_bounds: &Option<OptVec<ast::TyParamBound>>,
2061 generics: Option<&ast::Generics>,
2062 opt_explicit_self: Option<ast::ExplicitSelf_>) {
2063 ibox(s, indent_unit);
2065 // Duplicates the logic in `print_fn_header_info()`. This is because that
2066 // function prints the sigil in the wrong place. That should be fixed.
2067 if opt_sigil == Some(ast::OwnedSigil) && onceness == ast::Once {
2068 word(&mut s.s, "proc");
2069 } else if opt_sigil == Some(ast::BorrowedSigil) {
2070 print_extern_opt_abis(s, opt_abis);
2071 for lifetime in opt_region.iter() {
2072 print_lifetime(s, lifetime);
2074 print_purity(s, purity);
2075 print_onceness(s, onceness);
2077 print_opt_abis_and_extern_if_nondefault(s, opt_abis);
2078 print_opt_sigil(s, opt_sigil);
2079 print_opt_lifetime(s, opt_region);
2080 print_purity(s, purity);
2081 print_onceness(s, onceness);
2082 word(&mut s.s, "fn");
2085 match id { Some(id) => { word(&mut s.s, " "); print_ident(s, id); } _ => () }
2087 if opt_sigil != Some(ast::BorrowedSigil) {
2088 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2091 match generics { Some(g) => print_generics(s, g), _ => () }
2092 zerobreak(&mut s.s);
2094 if opt_sigil == Some(ast::BorrowedSigil) {
2095 word(&mut s.s, "|");
2100 print_fn_args(s, decl, opt_explicit_self);
2102 if opt_sigil == Some(ast::BorrowedSigil) {
2103 word(&mut s.s, "|");
2105 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2108 word(&mut s.s, ", ...");
2113 maybe_print_comment(s, decl.output.span.lo);
2115 match decl.output.node {
2118 space_if_not_bol(s);
2119 ibox(s, indent_unit);
2120 word_space(s, "->");
2121 if decl.cf == ast::NoReturn { word_nbsp(s, "!"); }
2122 else { print_type(s, decl.output); }
2130 pub fn maybe_print_trailing_comment(s: &mut State, span: codemap::Span,
2131 next_pos: Option<BytePos>) {
2133 match s.cm { Some(ccm) => cm = ccm, _ => return }
2134 match next_comment(s) {
2136 if (*cmnt).style != comments::Trailing { return; }
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 print_comment(s, cmnt);
2144 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2151 pub fn print_remaining_comments(s: &mut State) {
2152 // If there aren't any remaining comments, then we need to manually
2153 // make sure there is a line break at the end.
2154 if next_comment(s).is_none() { hardbreak(&mut s.s); }
2156 match next_comment(s) {
2158 print_comment(s, cmnt);
2159 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2166 pub fn print_literal(s: &mut State, lit: &ast::Lit) {
2167 maybe_print_comment(s, lit.span.lo);
2168 match next_lit(s, lit.span.lo) {
2170 word(&mut s.s, (*ltrl).lit);
2176 ast::LitStr(ref st, style) => print_string(s, st.get(), style),
2177 ast::LitChar(ch) => {
2179 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2180 res.push_char('\'');
2181 word(&mut s.s, res);
2183 ast::LitInt(i, t) => {
2186 ~"-" + (-i as u64).to_str_radix(10u)
2187 + ast_util::int_ty_to_str(t));
2190 (i as u64).to_str_radix(10u)
2191 + ast_util::int_ty_to_str(t));
2194 ast::LitUint(u, t) => {
2197 + ast_util::uint_ty_to_str(t));
2199 ast::LitIntUnsuffixed(i) => {
2201 word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u));
2203 word(&mut s.s, (i as u64).to_str_radix(10u));
2206 ast::LitFloat(ref f, t) => {
2207 word(&mut s.s, f.get() + ast_util::float_ty_to_str(t));
2209 ast::LitFloatUnsuffixed(ref f) => word(&mut s.s, f.get()),
2210 ast::LitNil => word(&mut s.s, "()"),
2211 ast::LitBool(val) => {
2212 if val { word(&mut s.s, "true"); } else { word(&mut s.s, "false"); }
2214 ast::LitBinary(arr) => {
2215 ibox(s, indent_unit);
2216 word(&mut s.s, "[");
2217 commasep_cmnt(s, Inconsistent, arr, |s, u| word(&mut s.s, format!("{}", *u)),
2219 word(&mut s.s, "]");
2225 pub fn lit_to_str(l: &ast::Lit) -> ~str {
2226 return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2229 pub fn next_lit(s: &mut State, pos: BytePos) -> Option<comments::Literal> {
2232 while s.cur_cmnt_and_lit.cur_lit < lits.len() {
2233 let ltrl = (*lits)[s.cur_cmnt_and_lit.cur_lit].clone();
2234 if ltrl.pos > pos { return None; }
2235 s.cur_cmnt_and_lit.cur_lit += 1u;
2236 if ltrl.pos == pos { return Some(ltrl); }
2244 pub fn maybe_print_comment(s: &mut State, pos: BytePos) {
2246 match next_comment(s) {
2248 if (*cmnt).pos < pos {
2249 print_comment(s, cmnt);
2250 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2258 pub fn print_comment(s: &mut State, cmnt: &comments::Comment) {
2260 comments::Mixed => {
2261 assert_eq!(cmnt.lines.len(), 1u);
2262 zerobreak(&mut s.s);
2263 word(&mut s.s, cmnt.lines[0]);
2264 zerobreak(&mut s.s);
2266 comments::Isolated => {
2267 pprust::hardbreak_if_not_bol(s);
2268 for line in cmnt.lines.iter() {
2269 // Don't print empty lines because they will end up as trailing
2271 if !line.is_empty() { word(&mut s.s, *line); }
2272 hardbreak(&mut s.s);
2275 comments::Trailing => {
2276 word(&mut s.s, " ");
2277 if cmnt.lines.len() == 1u {
2278 word(&mut s.s, cmnt.lines[0]);
2279 hardbreak(&mut s.s);
2282 for line in cmnt.lines.iter() {
2283 if !line.is_empty() { word(&mut s.s, *line); }
2284 hardbreak(&mut s.s);
2289 comments::BlankLine => {
2290 // We need to do at least one, possibly two hardbreaks.
2291 let is_semi = match s.s.last_token() {
2292 pp::String(s, _) => ";" == s,
2295 if is_semi || is_begin(s) || is_end(s) { hardbreak(&mut s.s); }
2296 hardbreak(&mut s.s);
2301 pub fn print_string(s: &mut State, st: &str, style: ast::StrStyle) {
2302 let st = match style {
2303 ast::CookedStr => format!("\"{}\"", st.escape_default()),
2304 ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2305 delim="#".repeat(n), string=st)
2310 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
2311 // that we "know" to be a `MemWriter` that works around the lack of checked
2313 unsafe fn get_mem_writer(writer: &mut ~io::Writer) -> ~str {
2314 let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(writer);
2315 let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap();
2320 pub fn to_str<T>(t: &T, f: |&mut State, &T|, intr: @IdentInterner) -> ~str {
2321 let wr = ~MemWriter::new();
2322 let mut s = rust_printer(wr as ~io::Writer, intr);
2326 get_mem_writer(&mut s.s.out)
2330 pub fn next_comment(s: &mut State) -> Option<comments::Comment> {
2332 Some(ref cmnts) => {
2333 if s.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2334 Some(cmnts[s.cur_cmnt_and_lit.cur_cmnt].clone())
2343 pub fn print_opt_purity(s: &mut State, opt_purity: Option<ast::Purity>) {
2345 Some(ast::ImpureFn) => { }
2347 word_nbsp(s, purity_to_str(purity));
2353 pub fn print_opt_abis_and_extern_if_nondefault(s: &mut State,
2354 opt_abis: Option<AbiSet>) {
2356 Some(abis) if !abis.is_rust() => {
2357 word_nbsp(s, "extern");
2358 word_nbsp(s, abis.to_str());
2360 Some(_) | None => {}
2364 pub fn print_extern_opt_abis(s: &mut State, opt_abis: Option<AbiSet>) {
2367 word_nbsp(s, "extern");
2368 word_nbsp(s, abis.to_str());
2374 pub fn print_opt_sigil(s: &mut State, opt_sigil: Option<ast::Sigil>) {
2376 Some(ast::BorrowedSigil) => { word(&mut s.s, "&"); }
2377 Some(ast::OwnedSigil) => { word(&mut s.s, "~"); }
2378 Some(ast::ManagedSigil) => { word(&mut s.s, "@"); }
2383 pub fn print_fn_header_info(s: &mut State,
2384 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2385 opt_purity: Option<ast::Purity>,
2387 onceness: ast::Onceness,
2388 opt_sigil: Option<ast::Sigil>,
2389 vis: ast::Visibility) {
2390 word(&mut s.s, visibility_qualified(vis, ""));
2392 if abis != AbiSet::Rust() {
2393 word_nbsp(s, "extern");
2394 word_nbsp(s, abis.to_str());
2396 if opt_purity != Some(ast::ExternFn) {
2397 print_opt_purity(s, opt_purity);
2400 print_opt_purity(s, opt_purity);
2403 print_onceness(s, onceness);
2404 word(&mut s.s, "fn");
2405 print_opt_sigil(s, opt_sigil);
2408 pub fn purity_to_str(p: ast::Purity) -> &'static str {
2410 ast::ImpureFn => "impure",
2411 ast::UnsafeFn => "unsafe",
2412 ast::ExternFn => "extern"
2416 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2418 ast::Once => "once",
2423 pub fn print_purity(s: &mut State, p: ast::Purity) {
2425 ast::ImpureFn => (),
2426 _ => word_nbsp(s, purity_to_str(p))
2430 pub fn print_onceness(s: &mut State, o: ast::Onceness) {
2432 ast::Once => { word_nbsp(s, "once"); }
2447 fn test_fun_to_str() {
2448 let abba_ident = token::str_to_ident("abba");
2450 let decl = ast::FnDecl {
2452 output: ast::P(ast::Ty {id: 0,
2454 span: codemap::DUMMY_SP}),
2458 let generics = ast_util::empty_generics();
2459 assert_eq!(&fun_to_str(&decl, ast::ImpureFn, abba_ident,
2460 None, &generics, token::get_ident_interner()),
2465 fn test_variant_to_str() {
2466 let ident = token::str_to_ident("principal_skinner");
2468 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2471 // making this up as I go.... ?
2472 kind: ast::TupleVariantKind(~[]),
2478 let varstr = variant_to_str(&var,token::get_ident_interner());
2479 assert_eq!(&varstr,&~"pub principal_skinner");