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, ident_to_str, 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();
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);
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())
1097 Some(base_args.pop())
1099 ast::NoSugar => None
1103 pub fn print_call_post(s: &mut State,
1104 sugar: ast::CallSugar,
1105 blk: &Option<@ast::Expr>,
1106 base_args: &mut ~[@ast::Expr]) {
1107 if sugar == ast::NoSugar || !base_args.is_empty() {
1109 commasep_exprs(s, Inconsistent, *base_args);
1112 if sugar != ast::NoSugar {
1114 match blk.unwrap().node {
1115 // need to handle closures specifically
1116 ast::ExprDoBody(e) => {
1117 end(s); // we close our head box; closure
1118 // will create it's own.
1120 end(s); // close outer box, as closures don't
1123 // not sure if this can happen.
1124 print_expr(s, blk.unwrap());
1130 pub fn print_expr(s: &mut State, expr: &ast::Expr) {
1131 fn print_field(s: &mut State, field: &ast::Field) {
1132 ibox(s, indent_unit);
1133 print_ident(s, field.ident.node);
1135 print_expr(s, field.expr);
1138 fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1140 maybe_print_comment(s, expr.span.lo);
1141 ibox(s, indent_unit);
1143 let ann_node = NodeExpr(s, expr);
1144 s.ann.pre(ann_node);
1147 ast::ExprVstore(e, v) => {
1148 print_expr_vstore(s, v);
1151 ast::ExprBox(p, e) => {
1152 word(&mut s.s, "box");
1153 word(&mut s.s, "(");
1158 ast::ExprVec(ref exprs, mutbl) => {
1159 ibox(s, indent_unit);
1160 word(&mut s.s, "[");
1161 if mutbl == ast::MutMutable {
1162 word(&mut s.s, "mut");
1163 if exprs.len() > 0u { nbsp(s); }
1165 commasep_exprs(s, Inconsistent, *exprs);
1166 word(&mut s.s, "]");
1170 ast::ExprRepeat(element, count, mutbl) => {
1171 ibox(s, indent_unit);
1172 word(&mut s.s, "[");
1173 if mutbl == ast::MutMutable {
1174 word(&mut s.s, "mut");
1177 print_expr(s, element);
1178 word(&mut s.s, ",");
1179 word(&mut s.s, "..");
1180 print_expr(s, count);
1181 word(&mut s.s, "]");
1185 ast::ExprStruct(ref path, ref fields, wth) => {
1186 print_path(s, path, true);
1187 word(&mut s.s, "{");
1188 commasep_cmnt(s, Consistent, (*fields), print_field, get_span);
1191 ibox(s, indent_unit);
1192 word(&mut s.s, ",");
1194 word(&mut s.s, "..");
1195 print_expr(s, expr);
1198 _ => (word(&mut s.s, ","))
1200 word(&mut s.s, "}");
1202 ast::ExprTup(ref exprs) => {
1204 commasep_exprs(s, Inconsistent, *exprs);
1205 if exprs.len() == 1 {
1206 word(&mut s.s, ",");
1210 ast::ExprCall(func, ref args, sugar) => {
1211 let mut base_args = (*args).clone();
1212 let blk = print_call_pre(s, sugar, &mut base_args);
1213 print_expr(s, func);
1214 print_call_post(s, sugar, &blk, &mut base_args);
1216 ast::ExprMethodCall(_, func, ident, ref tys, ref args, sugar) => {
1217 let mut base_args = (*args).clone();
1218 let blk = print_call_pre(s, sugar, &mut base_args);
1219 print_expr(s, func);
1220 word(&mut s.s, ".");
1221 print_ident(s, ident);
1223 word(&mut s.s, "::<");
1224 commasep(s, Inconsistent, *tys, print_type_ref);
1225 word(&mut s.s, ">");
1227 print_call_post(s, sugar, &blk, &mut base_args);
1229 ast::ExprBinary(_, op, lhs, rhs) => {
1232 word_space(s, ast_util::binop_to_str(op));
1235 ast::ExprUnary(_, op, expr) => {
1236 word(&mut s.s, ast_util::unop_to_str(op));
1237 print_expr(s, expr);
1239 ast::ExprAddrOf(m, expr) => {
1240 word(&mut s.s, "&");
1241 print_mutability(s, m);
1242 // Avoid `& &e` => `&&e`.
1243 match (m, &expr.node) {
1244 (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(&mut s.s),
1247 print_expr(s, expr);
1249 ast::ExprLit(lit) => print_literal(s, lit),
1250 ast::ExprCast(expr, ty) => {
1251 print_expr(s, expr);
1253 word_space(s, "as");
1256 ast::ExprIf(test, blk, elseopt) => {
1257 print_if(s, test, blk, elseopt, false);
1259 ast::ExprWhile(test, blk) => {
1261 print_expr(s, test);
1263 print_block(s, blk);
1265 ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1266 for ident in opt_ident.iter() {
1267 word(&mut s.s, "'");
1268 print_ident(s, *ident);
1274 word_space(s, "in");
1275 print_expr(s, iter);
1277 print_block(s, blk);
1279 ast::ExprLoop(blk, opt_ident) => {
1280 for ident in opt_ident.iter() {
1281 word(&mut s.s, "'");
1282 print_ident(s, *ident);
1287 print_block(s, blk);
1289 ast::ExprMatch(expr, ref arms) => {
1290 cbox(s, indent_unit);
1292 word_nbsp(s, "match");
1293 print_expr(s, expr);
1296 let len = arms.len();
1297 for (i, arm) in arms.iter().enumerate() {
1299 cbox(s, indent_unit);
1301 let mut first = true;
1302 for p in arm.pats.iter() {
1305 } else { space(&mut s.s); word_space(s, "|"); }
1311 word_space(s, "if");
1317 word_space(s, "=>");
1319 // Extract the expression from the extra block the parser adds
1320 // in the case of foo => expr
1321 if arm.body.view_items.is_empty() &&
1322 arm.body.stmts.is_empty() &&
1323 arm.body.rules == ast::DefaultBlock &&
1324 arm.body.expr.is_some()
1326 match arm.body.expr {
1329 ast::ExprBlock(blk) => {
1330 // the block will close the pattern's ibox
1331 print_block_unclosed_indent(
1332 s, blk, indent_unit);
1335 end(s); // close the ibox for the pattern
1336 print_expr(s, expr);
1339 if !expr_is_simple_block(expr)
1341 word(&mut s.s, ",");
1343 end(s); // close enclosing cbox
1348 // the block will close the pattern's ibox
1349 print_block_unclosed_indent(s, arm.body, indent_unit);
1352 bclose_(s, expr.span, indent_unit);
1354 ast::ExprFnBlock(decl, body) => {
1355 // in do/for blocks we don't want to show an empty
1356 // argument list, but at this point we don't know which
1359 // if !decl.inputs.is_empty() {
1360 print_fn_block_args(s, decl);
1363 assert!(body.stmts.is_empty());
1364 assert!(body.expr.is_some());
1365 // we extract the block, so as not to create another set of boxes
1366 match body.expr.unwrap().node {
1367 ast::ExprBlock(blk) => {
1368 print_block_unclosed(s, blk);
1371 // this is a bare expression
1372 print_expr(s, body.expr.unwrap());
1373 end(s); // need to close a box
1376 // a box will be closed by print_expr, but we didn't want an overall
1377 // wrapper so we closed the corresponding opening. so create an
1378 // empty box to satisfy the close.
1381 ast::ExprProc(decl, body) => {
1382 // in do/for blocks we don't want to show an empty
1383 // argument list, but at this point we don't know which
1386 // if !decl.inputs.is_empty() {
1387 print_proc_args(s, decl);
1390 assert!(body.stmts.is_empty());
1391 assert!(body.expr.is_some());
1392 // we extract the block, so as not to create another set of boxes
1393 match body.expr.unwrap().node {
1394 ast::ExprBlock(blk) => {
1395 print_block_unclosed(s, blk);
1398 // this is a bare expression
1399 print_expr(s, body.expr.unwrap());
1400 end(s); // need to close a box
1403 // a box will be closed by print_expr, but we didn't want an overall
1404 // wrapper so we closed the corresponding opening. so create an
1405 // empty box to satisfy the close.
1408 ast::ExprDoBody(body) => {
1409 print_expr(s, body);
1411 ast::ExprBlock(blk) => {
1412 // containing cbox, will be closed by print-block at }
1413 cbox(s, indent_unit);
1414 // head-box, will be closed by print-block after {
1416 print_block(s, blk);
1418 ast::ExprAssign(lhs, rhs) => {
1424 ast::ExprAssignOp(_, op, lhs, rhs) => {
1427 word(&mut s.s, ast_util::binop_to_str(op));
1431 ast::ExprField(expr, id, ref tys) => {
1432 print_expr(s, expr);
1433 word(&mut s.s, ".");
1436 word(&mut s.s, "::<");
1437 commasep(s, Inconsistent, *tys, print_type_ref);
1438 word(&mut s.s, ">");
1441 ast::ExprIndex(_, expr, index) => {
1442 print_expr(s, expr);
1443 word(&mut s.s, "[");
1444 print_expr(s, index);
1445 word(&mut s.s, "]");
1447 ast::ExprPath(ref path) => print_path(s, path, true),
1448 ast::ExprSelf => word(&mut s.s, "self"),
1449 ast::ExprBreak(opt_ident) => {
1450 word(&mut s.s, "break");
1452 for ident in opt_ident.iter() {
1453 word(&mut s.s, "'");
1454 print_name(s, *ident);
1458 ast::ExprAgain(opt_ident) => {
1459 word(&mut s.s, "continue");
1461 for ident in opt_ident.iter() {
1462 word(&mut s.s, "'");
1463 print_name(s, *ident);
1467 ast::ExprRet(result) => {
1468 word(&mut s.s, "return");
1470 Some(expr) => { word(&mut s.s, " "); print_expr(s, expr); }
1474 ast::ExprLogLevel => {
1475 word(&mut s.s, "__log_level");
1479 ast::ExprInlineAsm(ref a) => {
1481 word(&mut s.s, "__volatile__ asm!");
1483 word(&mut s.s, "asm!");
1486 print_string(s, a.asm, a.asm_str_style);
1488 for &(co, o) in a.outputs.iter() {
1489 print_string(s, co, ast::CookedStr);
1496 for &(co, o) in a.inputs.iter() {
1497 print_string(s, co, ast::CookedStr);
1504 print_string(s, a.clobbers, ast::CookedStr);
1507 ast::ExprMac(ref m) => print_mac(s, m),
1508 ast::ExprParen(e) => {
1515 let ann_node = NodeExpr(s, expr);
1516 s.ann.post(ann_node);
1521 pub fn print_local_decl(s: &mut State, loc: &ast::Local) {
1522 print_pat(s, loc.pat);
1525 _ => { word_space(s, ":"); print_type(s, loc.ty); }
1529 pub fn print_decl(s: &mut State, decl: &ast::Decl) {
1530 maybe_print_comment(s, decl.span.lo);
1532 ast::DeclLocal(ref loc) => {
1533 space_if_not_bol(s);
1534 ibox(s, indent_unit);
1535 word_nbsp(s, "let");
1537 fn print_local(s: &mut State, loc: &ast::Local) {
1538 ibox(s, indent_unit);
1539 print_local_decl(s, loc);
1545 print_expr(s, init);
1551 print_local(s, *loc);
1554 ast::DeclItem(item) => print_item(s, item)
1558 pub fn print_ident(s: &mut State, ident: ast::Ident) {
1559 word(&mut s.s, ident_to_str(&ident));
1562 pub fn print_name(s: &mut State, name: ast::Name) {
1563 word(&mut s.s, interner_get(name));
1566 pub fn print_for_decl(s: &mut State, loc: &ast::Local, coll: &ast::Expr) {
1567 print_local_decl(s, loc);
1569 word_space(s, "in");
1570 print_expr(s, coll);
1573 fn print_path_(s: &mut State,
1575 colons_before_params: bool,
1576 opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1577 maybe_print_comment(s, path.span.lo);
1579 word(&mut s.s, "::");
1582 let mut first = true;
1583 for (i, segment) in path.segments.iter().enumerate() {
1587 word(&mut s.s, "::")
1590 print_ident(s, segment.identifier);
1592 // If this is the last segment, print the bounds.
1593 if i == path.segments.len() - 1 {
1596 Some(ref bounds) => print_bounds(s, bounds, true),
1600 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1601 if colons_before_params {
1602 word(&mut s.s, "::")
1604 word(&mut s.s, "<");
1606 let mut comma = false;
1607 for lifetime in segment.lifetimes.iter() {
1611 print_lifetime(s, lifetime);
1615 if !segment.types.is_empty() {
1621 segment.types.map_to_vec(|&t| t),
1630 pub fn print_path(s: &mut State, path: &ast::Path, colons_before_params: bool) {
1631 print_path_(s, path, colons_before_params, &None)
1634 pub fn print_bounded_path(s: &mut State, path: &ast::Path,
1635 bounds: &Option<OptVec<ast::TyParamBound>>) {
1636 print_path_(s, path, false, bounds)
1639 pub fn print_pat(s: &mut State, pat: &ast::Pat) {
1640 maybe_print_comment(s, pat.span.lo);
1642 let ann_node = NodePat(s, pat);
1643 s.ann.pre(ann_node);
1645 /* Pat isn't normalized, but the beauty of it
1646 is that it doesn't matter */
1648 ast::PatWild => word(&mut s.s, "_"),
1649 ast::PatWildMulti => word(&mut s.s, ".."),
1650 ast::PatIdent(binding_mode, ref path, sub) => {
1651 match binding_mode {
1652 ast::BindByRef(mutbl) => {
1653 word_nbsp(s, "ref");
1654 print_mutability(s, mutbl);
1656 ast::BindByValue(ast::MutImmutable) => {}
1657 ast::BindByValue(ast::MutMutable) => {
1658 word_nbsp(s, "mut");
1661 print_path(s, path, true);
1664 word(&mut s.s, "@");
1670 ast::PatEnum(ref path, ref args_) => {
1671 print_path(s, path, true);
1673 None => word(&mut s.s, "(..)"),
1675 if !args.is_empty() {
1677 commasep(s, Inconsistent, *args,
1678 |s, &p| print_pat(s, p));
1684 ast::PatStruct(ref path, ref fields, etc) => {
1685 print_path(s, path, true);
1686 word(&mut s.s, "{");
1687 fn print_field(s: &mut State, f: &ast::FieldPat) {
1688 cbox(s, indent_unit);
1689 print_ident(s, f.ident);
1691 print_pat(s, f.pat);
1694 fn get_span(f: &ast::FieldPat) -> codemap::Span { return f.pat.span; }
1695 commasep_cmnt(s, Consistent, *fields,
1696 |s, f| print_field(s,f),
1699 if fields.len() != 0u { word_space(s, ","); }
1700 word(&mut s.s, "..");
1702 word(&mut s.s, "}");
1704 ast::PatTup(ref elts) => {
1706 commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p));
1707 if elts.len() == 1 {
1708 word(&mut s.s, ",");
1712 ast::PatUniq(inner) => {
1713 word(&mut s.s, "~");
1714 print_pat(s, inner);
1716 ast::PatRegion(inner) => {
1717 word(&mut s.s, "&");
1718 print_pat(s, inner);
1720 ast::PatLit(e) => print_expr(s, e),
1721 ast::PatRange(begin, end) => {
1722 print_expr(s, begin);
1724 word(&mut s.s, "..");
1727 ast::PatVec(ref before, slice, ref after) => {
1728 word(&mut s.s, "[");
1729 commasep(s, Inconsistent, *before, |s, &p| print_pat(s, p));
1730 for &p in slice.iter() {
1731 if !before.is_empty() { word_space(s, ","); }
1733 ast::Pat { node: ast::PatWildMulti, .. } => {
1734 // this case is handled by print_pat
1736 _ => word(&mut s.s, ".."),
1739 if !after.is_empty() { word_space(s, ","); }
1741 commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p));
1742 word(&mut s.s, "]");
1746 let ann_node = NodePat(s, pat);
1747 s.ann.post(ann_node);
1751 pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_, intr: @IdentInterner) -> ~str {
1752 to_str(explicit_self, |a, &b| { print_explicit_self(a, b); () }, intr)
1755 // Returns whether it printed anything
1756 pub fn print_explicit_self(s: &mut State, explicit_self: ast::ExplicitSelf_) -> bool {
1757 match explicit_self {
1758 ast::SelfStatic => { return false; }
1759 ast::SelfValue(m) => {
1760 print_mutability(s, m);
1761 word(&mut s.s, "self");
1763 ast::SelfUniq(m) => {
1764 print_mutability(s, m);
1765 word(&mut s.s, "~self");
1767 ast::SelfRegion(ref lt, m) => {
1768 word(&mut s.s, "&");
1769 print_opt_lifetime(s, lt);
1770 print_mutability(s, m);
1771 word(&mut s.s, "self");
1774 word(&mut s.s, "@self");
1780 pub fn print_fn(s: &mut State,
1782 purity: Option<ast::Purity>,
1785 generics: &ast::Generics,
1786 opt_explicit_self: Option<ast::ExplicitSelf_>,
1787 vis: ast::Visibility) {
1789 print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1791 print_ident(s, name);
1792 print_generics(s, generics);
1793 print_fn_args_and_ret(s, decl, opt_explicit_self);
1796 pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl,
1797 opt_explicit_self: Option<ast::ExplicitSelf_>) {
1798 // It is unfortunate to duplicate the commasep logic, but we want the
1799 // self type and the args all in the same box.
1800 rbox(s, 0u, Inconsistent);
1801 let mut first = true;
1802 for explicit_self in opt_explicit_self.iter() {
1803 first = !print_explicit_self(s, *explicit_self);
1806 for arg in decl.inputs.iter() {
1807 if first { first = false; } else { word_space(s, ","); }
1814 pub fn print_fn_args_and_ret(s: &mut State, decl: &ast::FnDecl,
1815 opt_explicit_self: Option<ast::ExplicitSelf_>) {
1817 print_fn_args(s, decl, opt_explicit_self);
1819 word(&mut s.s, ", ...");
1823 maybe_print_comment(s, decl.output.span.lo);
1824 match decl.output.node {
1827 space_if_not_bol(s);
1828 word_space(s, "->");
1829 print_type(s, decl.output);
1834 pub fn print_fn_block_args(s: &mut State, decl: &ast::FnDecl) {
1835 word(&mut s.s, "|");
1836 print_fn_args(s, decl, None);
1837 word(&mut s.s, "|");
1839 match decl.output.node {
1842 space_if_not_bol(s);
1843 word_space(s, "->");
1844 print_type(s, decl.output);
1848 maybe_print_comment(s, decl.output.span.lo);
1851 pub fn print_proc_args(s: &mut State, decl: &ast::FnDecl) {
1852 word(&mut s.s, "proc");
1853 word(&mut s.s, "(");
1854 print_fn_args(s, decl, None);
1855 word(&mut s.s, ")");
1857 match decl.output.node {
1860 space_if_not_bol(s);
1861 word_space(s, "->");
1862 print_type(s, decl.output);
1866 maybe_print_comment(s, decl.output.span.lo);
1869 pub fn print_bounds(s: &mut State, bounds: &OptVec<ast::TyParamBound>,
1870 print_colon_anyway: bool) {
1871 if !bounds.is_empty() {
1872 word(&mut s.s, ":");
1873 let mut first = true;
1874 for bound in bounds.iter() {
1883 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1884 RegionTyParamBound => word(&mut s.s, "'static"),
1887 } else if print_colon_anyway {
1888 word(&mut s.s, ":");
1892 pub fn print_lifetime(s: &mut State, lifetime: &ast::Lifetime) {
1893 word(&mut s.s, "'");
1894 print_ident(s, lifetime.ident);
1897 pub fn print_generics(s: &mut State, generics: &ast::Generics) {
1898 let total = generics.lifetimes.len() + generics.ty_params.len();
1900 word(&mut s.s, "<");
1901 fn print_item(s: &mut State, generics: &ast::Generics, idx: uint) {
1902 if idx < generics.lifetimes.len() {
1903 let lifetime = generics.lifetimes.get(idx);
1904 print_lifetime(s, lifetime);
1906 let idx = idx - generics.lifetimes.len();
1907 let param = generics.ty_params.get(idx);
1908 print_ident(s, param.ident);
1909 print_bounds(s, ¶m.bounds, false);
1914 for i in range(0u, total) {
1918 commasep(s, Inconsistent, ints,
1919 |s, &i| print_item(s, generics, i));
1920 word(&mut s.s, ">");
1924 pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) {
1925 ibox(s, indent_unit);
1927 ast::MetaWord(name) => word(&mut s.s, name),
1928 ast::MetaNameValue(name, value) => {
1929 word_space(s, name);
1931 print_literal(s, &value);
1933 ast::MetaList(name, ref items) => {
1934 word(&mut s.s, name);
1939 |p, &i| print_meta_item(p, i));
1946 pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) {
1948 ast::ViewPathSimple(ident, ref path, _) => {
1949 // FIXME(#6993) can't compare identifiers directly here
1950 if path.segments.last().identifier.name != ident.name {
1951 print_ident(s, ident);
1955 print_path(s, path, false);
1958 ast::ViewPathGlob(ref path, _) => {
1959 print_path(s, path, false);
1960 word(&mut s.s, "::*");
1963 ast::ViewPathList(ref path, ref idents, _) => {
1964 if path.segments.is_empty() {
1965 word(&mut s.s, "{");
1967 print_path(s, path, false);
1968 word(&mut s.s, "::{");
1970 commasep(s, Inconsistent, (*idents), |s, w| {
1971 print_ident(s, w.node.name);
1973 word(&mut s.s, "}");
1978 pub fn print_view_paths(s: &mut State, vps: &[@ast::ViewPath]) {
1979 commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp));
1982 pub fn print_view_item(s: &mut State, item: &ast::ViewItem) {
1983 hardbreak_if_not_bol(s);
1984 maybe_print_comment(s, item.span.lo);
1985 print_outer_attributes(s, item.attrs);
1986 print_visibility(s, item.vis);
1988 ast::ViewItemExternMod(id, ref optional_path, _) => {
1989 head(s, "extern mod");
1991 for &(ref p, style) in optional_path.iter() {
1993 word(&mut s.s, "=");
1995 print_string(s, *p, style);
1999 ast::ViewItemUse(ref vps) => {
2001 print_view_paths(s, *vps);
2004 word(&mut s.s, ";");
2005 end(s); // end inner head-block
2006 end(s); // end outer head-block
2009 pub fn print_mutability(s: &mut State, mutbl: ast::Mutability) {
2011 ast::MutMutable => word_nbsp(s, "mut"),
2012 ast::MutImmutable => {/* nothing */ }
2016 pub fn print_mt(s: &mut State, mt: &ast::MutTy) {
2017 print_mutability(s, mt.mutbl);
2018 print_type(s, mt.ty);
2021 pub fn print_arg(s: &mut State, input: &ast::Arg) {
2022 ibox(s, indent_unit);
2023 match input.ty.node {
2024 ast::TyInfer => print_pat(s, input.pat),
2026 match input.pat.node {
2027 ast::PatIdent(_, ref path, _) if
2028 path.segments.len() == 1 &&
2029 path.segments[0].identifier.name ==
2030 parse::token::special_idents::invalid.name => {
2034 print_pat(s, input.pat);
2035 word(&mut s.s, ":");
2039 print_type(s, input.ty);
2045 pub fn print_ty_fn(s: &mut State,
2046 opt_abis: Option<AbiSet>,
2047 opt_sigil: Option<ast::Sigil>,
2048 opt_region: &Option<ast::Lifetime>,
2049 purity: ast::Purity,
2050 onceness: ast::Onceness,
2052 id: Option<ast::Ident>,
2053 opt_bounds: &Option<OptVec<ast::TyParamBound>>,
2054 generics: Option<&ast::Generics>,
2055 opt_explicit_self: Option<ast::ExplicitSelf_>) {
2056 ibox(s, indent_unit);
2058 // Duplicates the logic in `print_fn_header_info()`. This is because that
2059 // function prints the sigil in the wrong place. That should be fixed.
2060 if opt_sigil == Some(ast::OwnedSigil) && onceness == ast::Once {
2061 word(&mut s.s, "proc");
2062 } else if opt_sigil == Some(ast::BorrowedSigil) {
2063 print_extern_opt_abis(s, opt_abis);
2064 for lifetime in opt_region.iter() {
2065 print_lifetime(s, lifetime);
2067 print_purity(s, purity);
2068 print_onceness(s, onceness);
2070 print_opt_abis_and_extern_if_nondefault(s, opt_abis);
2071 print_opt_sigil(s, opt_sigil);
2072 print_opt_lifetime(s, opt_region);
2073 print_purity(s, purity);
2074 print_onceness(s, onceness);
2075 word(&mut s.s, "fn");
2078 match id { Some(id) => { word(&mut s.s, " "); print_ident(s, id); } _ => () }
2080 if opt_sigil != Some(ast::BorrowedSigil) {
2081 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2084 match generics { Some(g) => print_generics(s, g), _ => () }
2085 zerobreak(&mut s.s);
2087 if opt_sigil == Some(ast::BorrowedSigil) {
2088 word(&mut s.s, "|");
2093 // It is unfortunate to duplicate the commasep logic, but we want the
2094 // self type and the args all in the same box.
2095 rbox(s, 0u, Inconsistent);
2096 let mut first = true;
2097 for explicit_self in opt_explicit_self.iter() {
2098 first = !print_explicit_self(s, *explicit_self);
2100 for arg in decl.inputs.iter() {
2101 if first { first = false; } else { word_space(s, ","); }
2106 if opt_sigil == Some(ast::BorrowedSigil) {
2107 word(&mut s.s, "|");
2109 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2112 word(&mut s.s, ", ...");
2117 maybe_print_comment(s, decl.output.span.lo);
2119 match decl.output.node {
2122 space_if_not_bol(s);
2123 ibox(s, indent_unit);
2124 word_space(s, "->");
2125 if decl.cf == ast::NoReturn { word_nbsp(s, "!"); }
2126 else { print_type(s, decl.output); }
2134 pub fn maybe_print_trailing_comment(s: &mut State, span: codemap::Span,
2135 next_pos: Option<BytePos>) {
2137 match s.cm { Some(ccm) => cm = ccm, _ => return }
2138 match next_comment(s) {
2140 if (*cmnt).style != comments::Trailing { return; }
2141 let span_line = cm.lookup_char_pos(span.hi);
2142 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2143 let mut next = (*cmnt).pos + BytePos(1);
2144 match next_pos { None => (), Some(p) => next = p }
2145 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2146 span_line.line == comment_line.line {
2147 print_comment(s, cmnt);
2148 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2155 pub fn print_remaining_comments(s: &mut State) {
2156 // If there aren't any remaining comments, then we need to manually
2157 // make sure there is a line break at the end.
2158 if next_comment(s).is_none() { hardbreak(&mut s.s); }
2160 match next_comment(s) {
2162 print_comment(s, cmnt);
2163 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2170 pub fn print_literal(s: &mut State, lit: &ast::Lit) {
2171 maybe_print_comment(s, lit.span.lo);
2172 match next_lit(s, lit.span.lo) {
2174 word(&mut s.s, (*ltrl).lit);
2180 ast::LitStr(st, style) => print_string(s, st, style),
2181 ast::LitChar(ch) => {
2183 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2184 res.push_char('\'');
2185 word(&mut s.s, res);
2187 ast::LitInt(i, t) => {
2190 ~"-" + (-i as u64).to_str_radix(10u)
2191 + ast_util::int_ty_to_str(t));
2194 (i as u64).to_str_radix(10u)
2195 + ast_util::int_ty_to_str(t));
2198 ast::LitUint(u, t) => {
2201 + ast_util::uint_ty_to_str(t));
2203 ast::LitIntUnsuffixed(i) => {
2205 word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u));
2207 word(&mut s.s, (i as u64).to_str_radix(10u));
2210 ast::LitFloat(f, t) => {
2211 word(&mut s.s, f.to_owned() + ast_util::float_ty_to_str(t));
2213 ast::LitFloatUnsuffixed(f) => word(&mut s.s, f),
2214 ast::LitNil => word(&mut s.s, "()"),
2215 ast::LitBool(val) => {
2216 if val { word(&mut s.s, "true"); } else { word(&mut s.s, "false"); }
2218 ast::LitBinary(arr) => {
2219 ibox(s, indent_unit);
2220 word(&mut s.s, "[");
2221 commasep_cmnt(s, Inconsistent, arr, |s, u| word(&mut s.s, format!("{}", *u)),
2223 word(&mut s.s, "]");
2229 pub fn lit_to_str(l: &ast::Lit) -> ~str {
2230 return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2233 pub fn next_lit(s: &mut State, pos: BytePos) -> Option<comments::Literal> {
2236 while s.cur_cmnt_and_lit.cur_lit < lits.len() {
2237 let ltrl = (*lits)[s.cur_cmnt_and_lit.cur_lit].clone();
2238 if ltrl.pos > pos { return None; }
2239 s.cur_cmnt_and_lit.cur_lit += 1u;
2240 if ltrl.pos == pos { return Some(ltrl); }
2248 pub fn maybe_print_comment(s: &mut State, pos: BytePos) {
2250 match next_comment(s) {
2252 if (*cmnt).pos < pos {
2253 print_comment(s, cmnt);
2254 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2262 pub fn print_comment(s: &mut State, cmnt: &comments::Comment) {
2264 comments::Mixed => {
2265 assert_eq!(cmnt.lines.len(), 1u);
2266 zerobreak(&mut s.s);
2267 word(&mut s.s, cmnt.lines[0]);
2268 zerobreak(&mut s.s);
2270 comments::Isolated => {
2271 pprust::hardbreak_if_not_bol(s);
2272 for line in cmnt.lines.iter() {
2273 // Don't print empty lines because they will end up as trailing
2275 if !line.is_empty() { word(&mut s.s, *line); }
2276 hardbreak(&mut s.s);
2279 comments::Trailing => {
2280 word(&mut s.s, " ");
2281 if cmnt.lines.len() == 1u {
2282 word(&mut s.s, cmnt.lines[0]);
2283 hardbreak(&mut s.s);
2286 for line in cmnt.lines.iter() {
2287 if !line.is_empty() { word(&mut s.s, *line); }
2288 hardbreak(&mut s.s);
2293 comments::BlankLine => {
2294 // We need to do at least one, possibly two hardbreaks.
2295 let is_semi = match s.s.last_token() {
2296 pp::String(s, _) => ";" == s,
2299 if is_semi || is_begin(s) || is_end(s) { hardbreak(&mut s.s); }
2300 hardbreak(&mut s.s);
2305 pub fn print_string(s: &mut State, st: &str, style: ast::StrStyle) {
2306 let st = match style {
2307 ast::CookedStr => format!("\"{}\"", st.escape_default()),
2308 ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2309 delim="#".repeat(n), string=st)
2314 // XXX(pcwalton): A nasty function to extract the string from an `io::Writer`
2315 // that we "know" to be a `MemWriter` that works around the lack of checked
2317 unsafe fn get_mem_writer(writer: &mut ~io::Writer) -> ~str {
2318 let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(writer);
2319 let result = str::from_utf8_owned(wr.get_ref().to_owned());
2324 pub fn to_str<T>(t: &T, f: |&mut State, &T|, intr: @IdentInterner) -> ~str {
2325 let wr = ~MemWriter::new();
2326 let mut s = rust_printer(wr as ~io::Writer, intr);
2330 get_mem_writer(&mut s.s.out)
2334 pub fn next_comment(s: &mut State) -> Option<comments::Comment> {
2336 Some(ref cmnts) => {
2337 if s.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2338 Some(cmnts[s.cur_cmnt_and_lit.cur_cmnt].clone())
2347 pub fn print_opt_purity(s: &mut State, opt_purity: Option<ast::Purity>) {
2349 Some(ast::ImpureFn) => { }
2351 word_nbsp(s, purity_to_str(purity));
2357 pub fn print_opt_abis_and_extern_if_nondefault(s: &mut State,
2358 opt_abis: Option<AbiSet>) {
2360 Some(abis) if !abis.is_rust() => {
2361 word_nbsp(s, "extern");
2362 word_nbsp(s, abis.to_str());
2364 Some(_) | None => {}
2368 pub fn print_extern_opt_abis(s: &mut State, opt_abis: Option<AbiSet>) {
2371 word_nbsp(s, "extern");
2372 word_nbsp(s, abis.to_str());
2378 pub fn print_opt_sigil(s: &mut State, opt_sigil: Option<ast::Sigil>) {
2380 Some(ast::BorrowedSigil) => { word(&mut s.s, "&"); }
2381 Some(ast::OwnedSigil) => { word(&mut s.s, "~"); }
2382 Some(ast::ManagedSigil) => { word(&mut s.s, "@"); }
2387 pub fn print_fn_header_info(s: &mut State,
2388 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2389 opt_purity: Option<ast::Purity>,
2391 onceness: ast::Onceness,
2392 opt_sigil: Option<ast::Sigil>,
2393 vis: ast::Visibility) {
2394 word(&mut s.s, visibility_qualified(vis, ""));
2396 if abis != AbiSet::Rust() {
2397 word_nbsp(s, "extern");
2398 word_nbsp(s, abis.to_str());
2400 if opt_purity != Some(ast::ExternFn) {
2401 print_opt_purity(s, opt_purity);
2404 print_opt_purity(s, opt_purity);
2407 print_onceness(s, onceness);
2408 word(&mut s.s, "fn");
2409 print_opt_sigil(s, opt_sigil);
2412 pub fn purity_to_str(p: ast::Purity) -> &'static str {
2414 ast::ImpureFn => "impure",
2415 ast::UnsafeFn => "unsafe",
2416 ast::ExternFn => "extern"
2420 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2422 ast::Once => "once",
2427 pub fn print_purity(s: &mut State, p: ast::Purity) {
2429 ast::ImpureFn => (),
2430 _ => word_nbsp(s, purity_to_str(p))
2434 pub fn print_onceness(s: &mut State, o: ast::Onceness) {
2436 ast::Once => { word_nbsp(s, "once"); }
2451 fn test_fun_to_str() {
2452 let abba_ident = token::str_to_ident("abba");
2454 let decl = ast::FnDecl {
2456 output: ast::P(ast::Ty {id: 0,
2458 span: codemap::DUMMY_SP}),
2462 let generics = ast_util::empty_generics();
2463 assert_eq!(&fun_to_str(&decl, ast::ImpureFn, abba_ident,
2464 None, &generics, token::get_ident_interner()),
2469 fn test_variant_to_str() {
2470 let ident = token::str_to_ident("principal_skinner");
2472 let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2475 // making this up as I go.... ?
2476 kind: ast::TupleVariantKind(~[]),
2482 let varstr = variant_to_str(&var,token::get_ident_interner());
2483 assert_eq!(&varstr,&~"pub principal_skinner");