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::{ident_interner, 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};
33 use std::io::Decorator;
34 use std::io::mem::MemWriter;
36 // The @ps is stored here to prevent recursive type.
37 pub enum ann_node<'a> {
38 node_block(@ps, &'a ast::Block),
39 node_item(@ps, &'a ast::item),
40 node_expr(@ps, &'a ast::Expr),
41 node_pat(@ps, &'a ast::Pat),
45 fn pre(&self, _node: ann_node) {}
46 fn post(&self, _node: ann_node) {}
54 pub fn new() -> no_ann {
61 impl pp_ann for no_ann {}
63 pub struct CurrentCommentAndLiteral {
71 intr: @token::ident_interner,
72 comments: Option<~[comments::cmnt]>,
73 literals: Option<~[comments::lit]>,
74 cur_cmnt_and_lit: @mut CurrentCommentAndLiteral,
75 boxes: @mut ~[pp::breaks],
79 pub fn ibox(s: @ps, u: uint) {
80 s.boxes.push(pp::inconsistent);
89 pub fn rust_printer(writer: @mut io::Writer, intr: @ident_interner) -> @ps {
90 return rust_printer_annotated(writer, intr, @no_ann::new() as @pp_ann);
93 pub fn rust_printer_annotated(writer: @mut io::Writer,
94 intr: @ident_interner,
98 s: pp::mk_printer(writer, default_columns),
101 comments: None::<~[comments::cmnt]>,
102 literals: None::<~[comments::lit]>,
103 cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
112 pub static indent_unit: uint = 4u;
114 pub static default_columns: uint = 78u;
116 // Requires you to pass an input filename and reader so that
117 // it can scan the input text for comments and literals to
119 pub fn print_crate(cm: @CodeMap,
120 intr: @ident_interner,
121 span_diagnostic: @mut diagnostic::SpanHandler,
124 input: @mut io::Reader,
125 out: @mut io::Writer,
128 let (cmnts, lits) = comments::gather_comments_and_literals(
134 s: pp::mk_printer(out, default_columns),
137 comments: Some(cmnts),
138 // If the code is post expansion, don't use the table of
139 // literals, since it doesn't correspond with the literals
140 // in the AST anymore.
141 literals: if is_expanded {
146 cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
153 print_crate_(s, crate);
156 pub fn print_crate_(s: @ps, crate: &ast::Crate) {
157 print_mod(s, &crate.module, crate.attrs);
158 print_remaining_comments(s);
162 pub fn ty_to_str(ty: &ast::Ty, intr: @ident_interner) -> ~str {
163 to_str(ty, print_type, intr)
166 pub fn pat_to_str(pat: &ast::Pat, intr: @ident_interner) -> ~str {
167 to_str(pat, print_pat, intr)
170 pub fn expr_to_str(e: &ast::Expr, intr: @ident_interner) -> ~str {
171 to_str(e, print_expr, intr)
174 pub fn lifetime_to_str(e: &ast::Lifetime, intr: @ident_interner) -> ~str {
175 to_str(e, print_lifetime, intr)
178 pub fn tt_to_str(tt: &ast::token_tree, intr: @ident_interner) -> ~str {
179 to_str(tt, print_tt, intr)
182 pub fn tts_to_str(tts: &[ast::token_tree], intr: @ident_interner) -> ~str {
183 to_str(&tts, print_tts, intr)
186 pub fn stmt_to_str(s: &ast::Stmt, intr: @ident_interner) -> ~str {
187 to_str(s, print_stmt, intr)
190 pub fn item_to_str(i: &ast::item, intr: @ident_interner) -> ~str {
191 to_str(i, print_item, intr)
194 pub fn generics_to_str(generics: &ast::Generics,
195 intr: @ident_interner) -> ~str {
196 to_str(generics, print_generics, intr)
199 pub fn path_to_str(p: &ast::Path, intr: @ident_interner) -> ~str {
200 to_str(p, |a,b| print_path(a, b, false), intr)
203 pub fn fun_to_str(decl: &ast::fn_decl, purity: ast::purity, name: ast::Ident,
204 opt_explicit_self: Option<ast::explicit_self_>,
205 generics: &ast::Generics, intr: @ident_interner) -> ~str {
206 let wr = @mut MemWriter::new();
207 let s = rust_printer(wr as @mut io::Writer, intr);
208 print_fn(s, decl, Some(purity), AbiSet::Rust(),
209 name, generics, opt_explicit_self, ast::inherited);
210 end(s); // Close the head box
211 end(s); // Close the outer box
213 str::from_utf8_owned(wr.inner_ref().to_owned())
216 pub fn block_to_str(blk: &ast::Block, intr: @ident_interner) -> ~str {
217 let wr = @mut MemWriter::new();
218 let s = rust_printer(wr as @mut io::Writer, intr);
219 // containing cbox, will be closed by print-block at }
220 cbox(s, indent_unit);
221 // head-ibox, will be closed by print-block after {
225 str::from_utf8_owned(wr.inner_ref().to_owned())
228 pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @ident_interner) -> ~str {
229 to_str(mi, print_meta_item, intr)
232 pub fn attribute_to_str(attr: &ast::Attribute, intr: @ident_interner) -> ~str {
233 to_str(attr, print_attribute, intr)
236 pub fn variant_to_str(var: &ast::variant, intr: @ident_interner) -> ~str {
237 to_str(var, print_variant, intr)
240 pub fn cbox(s: @ps, u: uint) {
241 s.boxes.push(pp::consistent);
246 pub fn rbox(s: @ps, u: uint, b: pp::breaks) {
251 pub fn nbsp(s: @ps) { word(s.s, " "); }
253 pub fn word_nbsp(s: @ps, w: &str) { word(s.s, w); nbsp(s); }
255 pub fn word_space(s: @ps, w: &str) { word(s.s, w); space(s.s); }
257 pub fn popen(s: @ps) { word(s.s, "("); }
259 pub fn pclose(s: @ps) { word(s.s, ")"); }
261 pub fn head(s: @ps, w: &str) {
262 // outer-box is consistent
263 cbox(s, indent_unit);
264 // head-box is inconsistent
265 ibox(s, w.len() + 1);
266 // keyword that starts the head
272 pub fn bopen(s: @ps) {
274 end(s); // close the head-box
277 pub fn bclose_(s: @ps, span: codemap::Span, indented: uint) {
278 bclose_maybe_open(s, span, indented, true);
280 pub fn bclose_maybe_open (s: @ps, span: codemap::Span, indented: uint,
282 maybe_print_comment(s, span.hi);
283 break_offset_if_not_bol(s, 1u, -(indented as int));
286 end(s); // close the outer-box
289 pub fn bclose(s: @ps, span: codemap::Span) { bclose_(s, span, indent_unit); }
291 pub fn is_begin(s: @ps) -> bool {
292 match s.s.last_token() { pp::BEGIN(_) => true, _ => false }
295 pub fn is_end(s: @ps) -> bool {
296 match s.s.last_token() { pp::END => true, _ => false }
299 pub fn is_bol(s: @ps) -> bool {
300 return s.s.last_token().is_eof() || s.s.last_token().is_hardbreak_tok();
303 pub fn in_cbox(s: @ps) -> bool {
304 let boxes = &*s.boxes;
305 let len = boxes.len();
306 if len == 0u { return false; }
307 return boxes[len - 1u] == pp::consistent;
310 pub fn hardbreak_if_not_bol(s: @ps) { if !is_bol(s) { hardbreak(s.s); } }
311 pub fn space_if_not_bol(s: @ps) { if !is_bol(s) { space(s.s); } }
312 pub fn break_offset_if_not_bol(s: @ps, n: uint, off: int) {
314 break_offset(s.s, n, off);
316 if off != 0 && s.s.last_token().is_hardbreak_tok() {
317 // We do something pretty sketchy here: tuck the nonzero
318 // offset-adjustment we were going to deposit along with the
319 // break into the previous hardbreak.
320 s.s.replace_last_token(pp::hardbreak_tok_offset(off));
325 // Synthesizes a comment that was not textually present in the original source
327 pub fn synth_comment(s: @ps, text: ~str) {
335 pub fn commasep<T>(s: @ps, b: breaks, elts: &[T], op: |@ps, &T|) {
337 let mut first = true;
338 for elt in elts.iter() {
339 if first { first = false; } else { word_space(s, ","); }
346 pub fn commasep_cmnt<T>(
351 get_span: |&T| -> codemap::Span) {
353 let len = elts.len();
355 for elt in elts.iter() {
356 maybe_print_comment(s, get_span(elt).hi);
361 maybe_print_trailing_comment(s, get_span(elt),
362 Some(get_span(&elts[i]).hi));
369 pub fn commasep_exprs(s: @ps, b: breaks, exprs: &[@ast::Expr]) {
370 commasep_cmnt(s, b, exprs, |p, &e| print_expr(p, e), |e| e.span);
373 pub fn print_mod(s: @ps, _mod: &ast::_mod, attrs: &[ast::Attribute]) {
374 print_inner_attributes(s, attrs);
375 for vitem in _mod.view_items.iter() {
376 print_view_item(s, vitem);
378 for item in _mod.items.iter() { print_item(s, *item); }
381 pub fn print_foreign_mod(s: @ps, nmod: &ast::foreign_mod,
382 attrs: &[ast::Attribute]) {
383 print_inner_attributes(s, attrs);
384 for vitem in nmod.view_items.iter() {
385 print_view_item(s, vitem);
387 for item in nmod.items.iter() { print_foreign_item(s, *item); }
390 pub fn print_opt_lifetime(s: @ps, lifetime: &Option<ast::Lifetime>) {
391 for l in lifetime.iter() {
392 print_lifetime(s, l);
397 pub fn print_type(s: @ps, ty: &ast::Ty) {
398 maybe_print_comment(s, ty.span.lo);
401 ast::ty_nil => word(s.s, "()"),
402 ast::ty_bot => word(s.s, "!"),
403 ast::ty_box(ref mt) => { word(s.s, "@"); print_mt(s, mt); }
404 ast::ty_uniq(ty) => { word(s.s, "~"); print_type(s, ty); }
410 ast::ty_ptr(ref mt) => { word(s.s, "*"); print_mt(s, mt); }
411 ast::ty_rptr(ref lifetime, ref mt) => {
413 print_opt_lifetime(s, lifetime);
416 ast::ty_tup(ref elts) => {
418 commasep(s, inconsistent, *elts, print_type_ref);
424 ast::ty_bare_fn(f) => {
425 let generics = ast::Generics {
426 lifetimes: f.lifetimes.clone(),
427 ty_params: opt_vec::Empty
429 print_ty_fn(s, Some(f.abis), None, &None,
430 f.purity, ast::Many, f.decl, None, &None,
431 Some(&generics), None);
433 ast::ty_closure(f) => {
434 let generics = ast::Generics {
435 lifetimes: f.lifetimes.clone(),
436 ty_params: opt_vec::Empty
438 print_ty_fn(s, None, Some(f.sigil), &f.region,
439 f.purity, f.onceness, f.decl, None, &f.bounds,
440 Some(&generics), None);
442 ast::ty_path(ref path, ref bounds, _) => print_bounded_path(s, path, bounds),
443 ast::ty_fixed_length_vec(ty, v) => {
450 ast::ty_typeof(e) => {
451 word(s.s, "typeof(");
456 fail!("print_type shouldn't see a ty_infer");
463 pub fn print_type_ref(s: @ps, ty: &P<ast::Ty>) {
467 pub fn print_foreign_item(s: @ps, item: &ast::foreign_item) {
468 hardbreak_if_not_bol(s);
469 maybe_print_comment(s, item.span.lo);
470 print_outer_attributes(s, item.attrs);
472 ast::foreign_item_fn(decl, ref generics) => {
473 print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, None,
475 end(s); // end head-ibox
477 end(s); // end the outer fn box
479 ast::foreign_item_static(t, m) => {
480 head(s, visibility_qualified(item.vis, "static"));
482 word_space(s, "mut");
484 print_ident(s, item.ident);
488 end(s); // end the head-ibox
489 end(s); // end the outer cbox
494 pub fn print_item(s: @ps, item: &ast::item) {
495 hardbreak_if_not_bol(s);
496 maybe_print_comment(s, item.span.lo);
497 print_outer_attributes(s, item.attrs);
498 let ann_node = node_item(s, item);
501 ast::item_static(ty, m, expr) => {
502 head(s, visibility_qualified(item.vis, "static"));
503 if m == ast::MutMutable {
504 word_space(s, "mut");
506 print_ident(s, item.ident);
510 end(s); // end the head-ibox
515 end(s); // end the outer cbox
518 ast::item_fn(decl, purity, abi, ref typarams, body) => {
530 print_block_with_attrs(s, body, item.attrs);
532 ast::item_mod(ref _mod) => {
533 head(s, visibility_qualified(item.vis, "mod"));
534 print_ident(s, item.ident);
537 print_mod(s, _mod, item.attrs);
538 bclose(s, item.span);
540 ast::item_foreign_mod(ref nmod) => {
542 word_nbsp(s, nmod.abis.to_str());
544 print_foreign_mod(s, nmod, item.attrs);
545 bclose(s, item.span);
547 ast::item_ty(ty, ref params) => {
548 ibox(s, indent_unit);
550 word_nbsp(s, visibility_qualified(item.vis, "type"));
551 print_ident(s, item.ident);
552 print_generics(s, params);
553 end(s); // end the inner ibox
559 end(s); // end the outer ibox
561 ast::item_enum(ref enum_definition, ref params) => {
571 ast::item_struct(struct_def, ref generics) => {
572 head(s, visibility_qualified(item.vis, "struct"));
573 print_struct(s, struct_def, generics, item.ident, item.span);
576 ast::item_impl(ref generics, ref opt_trait, ty, ref methods) => {
577 head(s, visibility_qualified(item.vis, "impl"));
578 if generics.is_parameterized() {
579 print_generics(s, generics);
585 print_trait_ref(s, t);
587 word_space(s, "for");
596 print_inner_attributes(s, item.attrs);
597 for meth in methods.iter() {
598 print_method(s, *meth);
600 bclose(s, item.span);
602 ast::item_trait(ref generics, ref traits, ref methods) => {
603 head(s, visibility_qualified(item.vis, "trait"));
604 print_ident(s, item.ident);
605 print_generics(s, generics);
606 if traits.len() != 0u {
608 for (i, trait_) in traits.iter().enumerate() {
613 print_path(s, &trait_.path, false);
618 for meth in methods.iter() {
619 print_trait_method(s, meth);
621 bclose(s, item.span);
623 // I think it's reasonable to hide the context here:
624 ast::item_mac(codemap::Spanned { node: ast::mac_invoc_tt(ref pth, ref tts, _),
626 print_visibility(s, item.vis);
627 print_path(s, pth, false);
629 print_ident(s, item.ident);
630 cbox(s, indent_unit);
632 print_tts(s, &(tts.as_slice()));
637 s.ann.post(ann_node);
640 fn print_trait_ref(s: @ps, t: &ast::trait_ref) {
641 print_path(s, &t.path, false);
644 pub fn print_enum_def(s: @ps, enum_definition: &ast::enum_def,
645 generics: &ast::Generics, ident: ast::Ident,
646 span: codemap::Span, visibility: ast::visibility) {
647 head(s, visibility_qualified(visibility, "enum"));
648 print_ident(s, ident);
649 print_generics(s, generics);
651 print_variants(s, enum_definition.variants, span);
654 pub fn print_variants(s: @ps,
655 variants: &[P<ast::variant>],
656 span: codemap::Span) {
658 for &v in variants.iter() {
660 maybe_print_comment(s, v.span.lo);
661 print_outer_attributes(s, v.node.attrs);
662 ibox(s, indent_unit);
666 maybe_print_trailing_comment(s, v.span, None);
671 pub fn visibility_to_str(vis: ast::visibility) -> ~str {
673 ast::private => ~"priv",
674 ast::public => ~"pub",
675 ast::inherited => ~""
679 pub fn visibility_qualified(vis: ast::visibility, s: &str) -> ~str {
681 ast::private | ast::public => visibility_to_str(vis) + " " + s,
682 ast::inherited => s.to_owned()
686 pub fn print_visibility(s: @ps, vis: ast::visibility) {
688 ast::private | ast::public =>
689 word_nbsp(s, visibility_to_str(vis)),
694 pub fn print_struct(s: @ps,
695 struct_def: &ast::struct_def,
696 generics: &ast::Generics,
698 span: codemap::Span) {
699 print_ident(s, ident);
700 print_generics(s, generics);
701 if ast_util::struct_def_is_tuple_like(struct_def) {
702 if !struct_def.fields.is_empty() {
704 commasep(s, inconsistent, struct_def.fields, |s, field| {
705 match field.node.kind {
706 ast::named_field(..) => fail!("unexpected named field"),
707 ast::unnamed_field => {
708 maybe_print_comment(s, field.span.lo);
709 print_type(s, field.node.ty);
717 end(s); // close the outer-box
721 hardbreak_if_not_bol(s);
723 for field in struct_def.fields.iter() {
724 match field.node.kind {
725 ast::unnamed_field => fail!("unexpected unnamed field"),
726 ast::named_field(ident, visibility) => {
727 hardbreak_if_not_bol(s);
728 maybe_print_comment(s, field.span.lo);
729 print_outer_attributes(s, field.node.attrs);
730 print_visibility(s, visibility);
731 print_ident(s, ident);
733 print_type(s, field.node.ty);
743 /// This doesn't deserve to be called "pretty" printing, but it should be
744 /// meaning-preserving. A quick hack that might help would be to look at the
745 /// spans embedded in the TTs to decide where to put spaces and newlines.
746 /// But it'd be better to parse these according to the grammar of the
747 /// appropriate macro, transcribe back into the grammar we just parsed from,
748 /// and then pretty-print the resulting AST nodes (so, e.g., we print
749 /// expression arguments as expressions). It can be done! I think.
750 pub fn print_tt(s: @ps, tt: &ast::token_tree) {
752 ast::tt_delim(ref tts) => print_tts(s, &(tts.as_slice())),
753 ast::tt_tok(_, ref tk) => {
754 word(s.s, parse::token::to_str(s.intr, tk));
756 ast::tt_seq(_, ref tts, ref sep, zerok) => {
758 for tt_elt in (*tts).iter() { print_tt(s, tt_elt); }
761 Some(ref tk) => word(s.s, parse::token::to_str(s.intr, tk)),
764 word(s.s, if zerok { "*" } else { "+" });
766 ast::tt_nonterminal(_, name) => {
768 print_ident(s, name);
773 pub fn print_tts(s: @ps, tts: & &[ast::token_tree]) {
775 for (i, tt) in tts.iter().enumerate() {
784 pub fn print_variant(s: @ps, v: &ast::variant) {
785 print_visibility(s, v.node.vis);
787 ast::tuple_variant_kind(ref args) => {
788 print_ident(s, v.node.name);
789 if !args.is_empty() {
791 fn print_variant_arg(s: @ps, arg: &ast::variant_arg) {
792 print_type(s, arg.ty);
794 commasep(s, consistent, *args, print_variant_arg);
798 ast::struct_variant_kind(struct_def) => {
800 let generics = ast_util::empty_generics();
801 print_struct(s, struct_def, &generics, v.node.name, v.span);
804 match v.node.disr_expr {
814 pub fn print_ty_method(s: @ps, m: &ast::TypeMethod) {
815 hardbreak_if_not_bol(s);
816 maybe_print_comment(s, m.span.lo);
817 print_outer_attributes(s, m.attrs);
828 Some(m.explicit_self.node));
832 pub fn print_trait_method(s: @ps, m: &ast::trait_method) {
834 required(ref ty_m) => print_ty_method(s, ty_m),
835 provided(m) => print_method(s, m)
839 pub fn print_method(s: @ps, meth: &ast::method) {
840 hardbreak_if_not_bol(s);
841 maybe_print_comment(s, meth.span.lo);
842 print_outer_attributes(s, meth.attrs);
843 print_fn(s, meth.decl, Some(meth.purity), AbiSet::Rust(),
844 meth.ident, &meth.generics, Some(meth.explicit_self.node),
847 print_block_with_attrs(s, meth.body, meth.attrs);
850 pub fn print_outer_attributes(s: @ps, attrs: &[ast::Attribute]) {
852 for attr in attrs.iter() {
853 match attr.node.style {
854 ast::AttrOuter => { print_attribute(s, attr); count += 1; }
855 _ => {/* fallthrough */ }
858 if count > 0 { hardbreak_if_not_bol(s); }
861 pub fn print_inner_attributes(s: @ps, attrs: &[ast::Attribute]) {
863 for attr in attrs.iter() {
864 match attr.node.style {
866 print_attribute(s, attr);
867 if !attr.node.is_sugared_doc {
872 _ => {/* fallthrough */ }
875 if count > 0 { hardbreak_if_not_bol(s); }
878 pub fn print_attribute(s: @ps, attr: &ast::Attribute) {
879 hardbreak_if_not_bol(s);
880 maybe_print_comment(s, attr.span.lo);
881 if attr.node.is_sugared_doc {
882 let comment = attr.value_str().unwrap();
886 print_meta_item(s, attr.meta());
892 pub fn print_stmt(s: @ps, st: &ast::Stmt) {
893 maybe_print_comment(s, st.span.lo);
895 ast::StmtDecl(decl, _) => {
898 ast::StmtExpr(expr, _) => {
902 ast::StmtSemi(expr, _) => {
907 ast::StmtMac(ref mac, semi) => {
910 if semi { word(s.s, ";"); }
913 if parse::classify::stmt_ends_with_semi(st) { word(s.s, ";"); }
914 maybe_print_trailing_comment(s, st.span, None);
917 pub fn print_block(s: @ps, blk: &ast::Block) {
918 print_possibly_embedded_block(s, blk, block_normal, indent_unit);
921 pub fn print_block_unclosed(s: @ps, blk: &ast::Block) {
922 print_possibly_embedded_block_(s, blk, block_normal, indent_unit, &[],
926 pub fn print_block_unclosed_indent(s: @ps, blk: &ast::Block, indented: uint) {
927 print_possibly_embedded_block_(s, blk, block_normal, indented, &[],
931 pub fn print_block_with_attrs(s: @ps,
933 attrs: &[ast::Attribute]) {
934 print_possibly_embedded_block_(s, blk, block_normal, indent_unit, attrs,
938 pub enum embed_type { block_block_fn, block_normal, }
940 pub fn print_possibly_embedded_block(s: @ps,
942 embedded: embed_type,
944 print_possibly_embedded_block_(
945 s, blk, embedded, indented, &[], true);
948 pub fn print_possibly_embedded_block_(s: @ps,
950 embedded: embed_type,
952 attrs: &[ast::Attribute],
955 ast::UnsafeBlock(..) => word_space(s, "unsafe"),
956 ast::DefaultBlock => ()
958 maybe_print_comment(s, blk.span.lo);
959 let ann_node = node_block(s, blk);
962 block_block_fn => end(s),
963 block_normal => bopen(s)
966 print_inner_attributes(s, attrs);
968 for vi in blk.view_items.iter() { print_view_item(s, vi); }
969 for st in blk.stmts.iter() {
976 maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
980 bclose_maybe_open(s, blk.span, indented, close_box);
981 s.ann.post(ann_node);
984 pub fn print_if(s: @ps, test: &ast::Expr, blk: &ast::Block,
985 elseopt: Option<@ast::Expr>, chk: bool) {
987 if chk { word_nbsp(s, "check"); }
991 fn do_else(s: @ps, els: Option<@ast::Expr>) {
996 ast::ExprIf(i, t, e) => {
997 cbox(s, indent_unit - 1u);
999 word(s.s, " else if ");
1006 ast::ExprBlock(b) => {
1007 cbox(s, indent_unit - 1u);
1009 word(s.s, " else ");
1012 // BLEAH, constraints would be great here
1014 fail!("print_if saw if with weird alternative");
1018 _ => {/* fall through */ }
1021 do_else(s, elseopt);
1024 pub fn print_mac(s: @ps, m: &ast::mac) {
1026 // I think it's reasonable to hide the ctxt here:
1027 ast::mac_invoc_tt(ref pth, ref tts, _) => {
1028 print_path(s, pth, false);
1031 print_tts(s, &tts.as_slice());
1037 pub fn print_vstore(s: @ps, t: ast::Vstore) {
1039 ast::VstoreFixed(Some(i)) => word(s.s, format!("{}", i)),
1040 ast::VstoreFixed(None) => word(s.s, "_"),
1041 ast::VstoreUniq => word(s.s, "~"),
1042 ast::VstoreBox => word(s.s, "@"),
1043 ast::VstoreSlice(ref r) => {
1045 print_opt_lifetime(s, r);
1050 pub fn print_expr_vstore(s: @ps, t: ast::ExprVstore) {
1052 ast::ExprVstoreUniq => word(s.s, "~"),
1053 ast::ExprVstoreBox => word(s.s, "@"),
1054 ast::ExprVstoreMutBox => {
1058 ast::ExprVstoreSlice => word(s.s, "&"),
1059 ast::ExprVstoreMutSlice => {
1066 pub fn print_call_pre(s: @ps,
1067 sugar: ast::CallSugar,
1068 base_args: &mut ~[@ast::Expr])
1069 -> Option<@ast::Expr> {
1073 Some(base_args.pop())
1077 Some(base_args.pop())
1079 ast::NoSugar => None
1083 pub fn print_call_post(s: @ps,
1084 sugar: ast::CallSugar,
1085 blk: &Option<@ast::Expr>,
1086 base_args: &mut ~[@ast::Expr]) {
1087 if sugar == ast::NoSugar || !base_args.is_empty() {
1089 commasep_exprs(s, inconsistent, *base_args);
1092 if sugar != ast::NoSugar {
1094 match blk.unwrap().node {
1095 // need to handle closures specifically
1096 ast::ExprDoBody(e) => {
1097 end(s); // we close our head box; closure
1098 // will create it's own.
1100 end(s); // close outer box, as closures don't
1103 // not sure if this can happen.
1104 print_expr(s, blk.unwrap());
1110 pub fn print_expr(s: @ps, expr: &ast::Expr) {
1111 fn print_field(s: @ps, field: &ast::Field) {
1112 ibox(s, indent_unit);
1113 print_ident(s, field.ident.node);
1115 print_expr(s, field.expr);
1118 fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1120 maybe_print_comment(s, expr.span.lo);
1121 ibox(s, indent_unit);
1122 let ann_node = node_expr(s, expr);
1123 s.ann.pre(ann_node);
1125 ast::ExprVstore(e, v) => {
1126 print_expr_vstore(s, v);
1129 ast::ExprVec(ref exprs, mutbl) => {
1130 ibox(s, indent_unit);
1132 if mutbl == ast::MutMutable {
1134 if exprs.len() > 0u { nbsp(s); }
1136 commasep_exprs(s, inconsistent, *exprs);
1141 ast::ExprRepeat(element, count, mutbl) => {
1142 ibox(s, indent_unit);
1144 if mutbl == ast::MutMutable {
1148 print_expr(s, element);
1151 print_expr(s, count);
1156 ast::ExprStruct(ref path, ref fields, wth) => {
1157 print_path(s, path, true);
1159 commasep_cmnt(s, consistent, (*fields), print_field, get_span);
1162 ibox(s, indent_unit);
1166 print_expr(s, expr);
1169 _ => (word(s.s, ","))
1173 ast::ExprTup(ref exprs) => {
1175 commasep_exprs(s, inconsistent, *exprs);
1176 if exprs.len() == 1 {
1181 ast::ExprCall(func, ref args, sugar) => {
1182 let mut base_args = (*args).clone();
1183 let blk = print_call_pre(s, sugar, &mut base_args);
1184 print_expr(s, func);
1185 print_call_post(s, sugar, &blk, &mut base_args);
1187 ast::ExprMethodCall(_, func, ident, ref tys, ref args, sugar) => {
1188 let mut base_args = (*args).clone();
1189 let blk = print_call_pre(s, sugar, &mut base_args);
1190 print_expr(s, func);
1192 print_ident(s, ident);
1195 commasep(s, inconsistent, *tys, print_type_ref);
1198 print_call_post(s, sugar, &blk, &mut base_args);
1200 ast::ExprBinary(_, op, lhs, rhs) => {
1203 word_space(s, ast_util::binop_to_str(op));
1206 ast::ExprUnary(_, op, expr) => {
1207 word(s.s, ast_util::unop_to_str(op));
1208 print_expr(s, expr);
1210 ast::ExprAddrOf(m, expr) => {
1212 print_mutability(s, m);
1213 // Avoid `& &e` => `&&e`.
1214 match (m, &expr.node) {
1215 (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(s.s),
1218 print_expr(s, expr);
1220 ast::ExprLit(lit) => print_literal(s, lit),
1221 ast::ExprCast(expr, ty) => {
1222 print_expr(s, expr);
1224 word_space(s, "as");
1227 ast::ExprIf(test, blk, elseopt) => {
1228 print_if(s, test, blk, elseopt, false);
1230 ast::ExprWhile(test, blk) => {
1232 print_expr(s, test);
1234 print_block(s, blk);
1236 ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1237 for ident in opt_ident.iter() {
1239 print_ident(s, *ident);
1245 word_space(s, "in");
1246 print_expr(s, iter);
1248 print_block(s, blk);
1250 ast::ExprLoop(blk, opt_ident) => {
1251 for ident in opt_ident.iter() {
1253 print_ident(s, *ident);
1258 print_block(s, blk);
1260 ast::ExprMatch(expr, ref arms) => {
1261 cbox(s, indent_unit);
1263 word_nbsp(s, "match");
1264 print_expr(s, expr);
1267 let len = arms.len();
1268 for (i, arm) in arms.iter().enumerate() {
1270 cbox(s, indent_unit);
1272 let mut first = true;
1273 for p in arm.pats.iter() {
1276 } else { space(s.s); word_space(s, "|"); }
1282 word_space(s, "if");
1288 word_space(s, "=>");
1290 // Extract the expression from the extra block the parser adds
1291 // in the case of foo => expr
1292 if arm.body.view_items.is_empty() &&
1293 arm.body.stmts.is_empty() &&
1294 arm.body.rules == ast::DefaultBlock &&
1295 arm.body.expr.is_some()
1297 match arm.body.expr {
1300 ast::ExprBlock(blk) => {
1301 // the block will close the pattern's ibox
1302 print_block_unclosed_indent(
1303 s, blk, indent_unit);
1306 end(s); // close the ibox for the pattern
1307 print_expr(s, expr);
1310 if !expr_is_simple_block(expr)
1314 end(s); // close enclosing cbox
1319 // the block will close the pattern's ibox
1320 print_block_unclosed_indent(s, arm.body, indent_unit);
1323 bclose_(s, expr.span, indent_unit);
1325 ast::ExprFnBlock(decl, body) => {
1326 // in do/for blocks we don't want to show an empty
1327 // argument list, but at this point we don't know which
1330 // if !decl.inputs.is_empty() {
1331 print_fn_block_args(s, decl);
1334 assert!(body.stmts.is_empty());
1335 assert!(body.expr.is_some());
1336 // we extract the block, so as not to create another set of boxes
1337 match body.expr.unwrap().node {
1338 ast::ExprBlock(blk) => {
1339 print_block_unclosed(s, blk);
1342 // this is a bare expression
1343 print_expr(s, body.expr.unwrap());
1344 end(s); // need to close a box
1347 // a box will be closed by print_expr, but we didn't want an overall
1348 // wrapper so we closed the corresponding opening. so create an
1349 // empty box to satisfy the close.
1352 ast::ExprProc(decl, body) => {
1353 // in do/for blocks we don't want to show an empty
1354 // argument list, but at this point we don't know which
1357 // if !decl.inputs.is_empty() {
1358 print_proc_args(s, decl);
1361 assert!(body.stmts.is_empty());
1362 assert!(body.expr.is_some());
1363 // we extract the block, so as not to create another set of boxes
1364 match body.expr.unwrap().node {
1365 ast::ExprBlock(blk) => {
1366 print_block_unclosed(s, blk);
1369 // this is a bare expression
1370 print_expr(s, body.expr.unwrap());
1371 end(s); // need to close a box
1374 // a box will be closed by print_expr, but we didn't want an overall
1375 // wrapper so we closed the corresponding opening. so create an
1376 // empty box to satisfy the close.
1379 ast::ExprDoBody(body) => {
1380 print_expr(s, body);
1382 ast::ExprBlock(blk) => {
1383 // containing cbox, will be closed by print-block at }
1384 cbox(s, indent_unit);
1385 // head-box, will be closed by print-block after {
1387 print_block(s, blk);
1389 ast::ExprAssign(lhs, rhs) => {
1395 ast::ExprAssignOp(_, op, lhs, rhs) => {
1398 word(s.s, ast_util::binop_to_str(op));
1402 ast::ExprField(expr, id, ref tys) => {
1403 print_expr(s, expr);
1408 commasep(s, inconsistent, *tys, print_type_ref);
1412 ast::ExprIndex(_, expr, index) => {
1413 print_expr(s, expr);
1415 print_expr(s, index);
1418 ast::ExprPath(ref path) => print_path(s, path, true),
1419 ast::ExprSelf => word(s.s, "self"),
1420 ast::ExprBreak(opt_ident) => {
1423 for ident in opt_ident.iter() {
1425 print_name(s, *ident);
1429 ast::ExprAgain(opt_ident) => {
1430 word(s.s, "continue");
1432 for ident in opt_ident.iter() {
1434 print_name(s, *ident);
1438 ast::ExprRet(result) => {
1439 word(s.s, "return");
1441 Some(expr) => { word(s.s, " "); print_expr(s, expr); }
1445 ast::ExprLogLevel => {
1446 word(s.s, "__log_level");
1450 ast::ExprInlineAsm(ref a) => {
1452 word(s.s, "__volatile__ asm!");
1457 print_string(s, a.asm, a.asm_str_style);
1459 for &(co, o) in a.outputs.iter() {
1460 print_string(s, co, ast::CookedStr);
1467 for &(co, o) in a.inputs.iter() {
1468 print_string(s, co, ast::CookedStr);
1475 print_string(s, a.clobbers, ast::CookedStr);
1478 ast::ExprMac(ref m) => print_mac(s, m),
1479 ast::ExprParen(e) => {
1485 s.ann.post(ann_node);
1489 pub fn print_local_decl(s: @ps, loc: &ast::Local) {
1490 print_pat(s, loc.pat);
1492 ast::ty_infer => (),
1493 _ => { word_space(s, ":"); print_type(s, loc.ty); }
1497 pub fn print_decl(s: @ps, decl: &ast::Decl) {
1498 maybe_print_comment(s, decl.span.lo);
1500 ast::DeclLocal(ref loc) => {
1501 space_if_not_bol(s);
1502 ibox(s, indent_unit);
1503 word_nbsp(s, "let");
1505 fn print_local(s: @ps, loc: &ast::Local) {
1506 ibox(s, indent_unit);
1507 print_local_decl(s, loc);
1513 print_expr(s, init);
1519 print_local(s, *loc);
1522 ast::DeclItem(item) => print_item(s, item)
1526 pub fn print_ident(s: @ps, ident: ast::Ident) {
1527 word(s.s, ident_to_str(&ident));
1530 pub fn print_name(s: @ps, name: ast::Name) {
1531 word(s.s, interner_get(name));
1534 pub fn print_for_decl(s: @ps, loc: &ast::Local, coll: &ast::Expr) {
1535 print_local_decl(s, loc);
1537 word_space(s, "in");
1538 print_expr(s, coll);
1541 fn print_path_(s: @ps,
1543 colons_before_params: bool,
1544 opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1545 maybe_print_comment(s, path.span.lo);
1550 let mut first = true;
1551 for (i, segment) in path.segments.iter().enumerate() {
1558 print_ident(s, segment.identifier);
1560 // If this is the last segment, print the bounds.
1561 if i == path.segments.len() - 1 {
1564 Some(ref bounds) => print_bounds(s, bounds, true),
1568 if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1569 if colons_before_params {
1574 let mut comma = false;
1575 for lifetime in segment.lifetimes.iter() {
1579 print_lifetime(s, lifetime);
1583 if !segment.types.is_empty() {
1589 segment.types.map_to_vec(|&t| t),
1598 pub fn print_path(s: @ps, path: &ast::Path, colons_before_params: bool) {
1599 print_path_(s, path, colons_before_params, &None)
1602 pub fn print_bounded_path(s: @ps, path: &ast::Path,
1603 bounds: &Option<OptVec<ast::TyParamBound>>) {
1604 print_path_(s, path, false, bounds)
1607 pub fn print_pat(s: @ps, pat: &ast::Pat) {
1608 maybe_print_comment(s, pat.span.lo);
1609 let ann_node = node_pat(s, pat);
1610 s.ann.pre(ann_node);
1611 /* Pat isn't normalized, but the beauty of it
1612 is that it doesn't matter */
1614 ast::PatWild => word(s.s, "_"),
1615 ast::PatWildMulti => word(s.s, ".."),
1616 ast::PatIdent(binding_mode, ref path, sub) => {
1617 match binding_mode {
1618 ast::BindByRef(mutbl) => {
1619 word_nbsp(s, "ref");
1620 print_mutability(s, mutbl);
1622 ast::BindByValue(ast::MutImmutable) => {}
1623 ast::BindByValue(ast::MutMutable) => {
1624 word_nbsp(s, "mut");
1627 print_path(s, path, true);
1636 ast::PatEnum(ref path, ref args_) => {
1637 print_path(s, path, true);
1639 None => word(s.s, "(..)"),
1641 if !args.is_empty() {
1643 commasep(s, inconsistent, *args,
1644 |s, &p| print_pat(s, p));
1650 ast::PatStruct(ref path, ref fields, etc) => {
1651 print_path(s, path, true);
1653 fn print_field(s: @ps, f: &ast::FieldPat) {
1654 cbox(s, indent_unit);
1655 print_ident(s, f.ident);
1657 print_pat(s, f.pat);
1660 fn get_span(f: &ast::FieldPat) -> codemap::Span { return f.pat.span; }
1661 commasep_cmnt(s, consistent, *fields,
1662 |s, f| print_field(s,f),
1665 if fields.len() != 0u { word_space(s, ","); }
1670 ast::PatTup(ref elts) => {
1672 commasep(s, inconsistent, *elts, |s, &p| print_pat(s, p));
1673 if elts.len() == 1 {
1678 ast::PatBox(inner) => {
1680 print_pat(s, inner);
1682 ast::PatUniq(inner) => {
1684 print_pat(s, inner);
1686 ast::PatRegion(inner) => {
1688 print_pat(s, inner);
1690 ast::PatLit(e) => print_expr(s, e),
1691 ast::PatRange(begin, end) => {
1692 print_expr(s, begin);
1697 ast::PatVec(ref before, slice, ref after) => {
1699 commasep(s, inconsistent, *before, |s, &p| print_pat(s, p));
1700 for &p in slice.iter() {
1701 if !before.is_empty() { word_space(s, ","); }
1703 @ast::Pat { node: ast::PatWildMulti, .. } => {
1704 // this case is handled by print_pat
1706 _ => word(s.s, ".."),
1709 if !after.is_empty() { word_space(s, ","); }
1711 commasep(s, inconsistent, *after, |s, &p| print_pat(s, p));
1715 s.ann.post(ann_node);
1718 pub fn explicit_self_to_str(explicit_self: &ast::explicit_self_, intr: @ident_interner) -> ~str {
1719 to_str(explicit_self, |a, &b| { print_explicit_self(a, b); () }, intr)
1722 // Returns whether it printed anything
1723 pub fn print_explicit_self(s: @ps, explicit_self: ast::explicit_self_) -> bool {
1724 match explicit_self {
1725 ast::sty_static => { return false; }
1726 ast::sty_value(m) => {
1727 print_mutability(s, m);
1730 ast::sty_uniq(m) => {
1731 print_mutability(s, m);
1734 ast::sty_region(ref lt, m) => {
1736 print_opt_lifetime(s, lt);
1737 print_mutability(s, m);
1740 ast::sty_box(m) => {
1741 word(s.s, "@"); print_mutability(s, m); word(s.s, "self");
1747 pub fn print_fn(s: @ps,
1748 decl: &ast::fn_decl,
1749 purity: Option<ast::purity>,
1752 generics: &ast::Generics,
1753 opt_explicit_self: Option<ast::explicit_self_>,
1754 vis: ast::visibility) {
1756 print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1758 print_ident(s, name);
1759 print_generics(s, generics);
1760 print_fn_args_and_ret(s, decl, opt_explicit_self);
1763 pub fn print_fn_args(s: @ps, decl: &ast::fn_decl,
1764 opt_explicit_self: Option<ast::explicit_self_>) {
1765 // It is unfortunate to duplicate the commasep logic, but we want the
1766 // self type and the args all in the same box.
1767 rbox(s, 0u, inconsistent);
1768 let mut first = true;
1769 for explicit_self in opt_explicit_self.iter() {
1770 first = !print_explicit_self(s, *explicit_self);
1773 for arg in decl.inputs.iter() {
1774 if first { first = false; } else { word_space(s, ","); }
1781 pub fn print_fn_args_and_ret(s: @ps, decl: &ast::fn_decl,
1782 opt_explicit_self: Option<ast::explicit_self_>) {
1784 print_fn_args(s, decl, opt_explicit_self);
1790 maybe_print_comment(s, decl.output.span.lo);
1791 match decl.output.node {
1794 space_if_not_bol(s);
1795 word_space(s, "->");
1796 print_type(s, decl.output);
1801 pub fn print_fn_block_args(s: @ps, decl: &ast::fn_decl) {
1803 print_fn_args(s, decl, None);
1806 match decl.output.node {
1809 space_if_not_bol(s);
1810 word_space(s, "->");
1811 print_type(s, decl.output);
1815 maybe_print_comment(s, decl.output.span.lo);
1818 pub fn print_proc_args(s: @ps, decl: &ast::fn_decl) {
1821 print_fn_args(s, decl, None);
1824 match decl.output.node {
1827 space_if_not_bol(s);
1828 word_space(s, "->");
1829 print_type(s, decl.output);
1833 maybe_print_comment(s, decl.output.span.lo);
1836 pub fn print_bounds(s: @ps, bounds: &OptVec<ast::TyParamBound>,
1837 print_colon_anyway: bool) {
1838 if !bounds.is_empty() {
1840 let mut first = true;
1841 for bound in bounds.iter() {
1850 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1851 RegionTyParamBound => word(s.s, "'static"),
1854 } else if print_colon_anyway {
1859 pub fn print_lifetime(s: @ps, lifetime: &ast::Lifetime) {
1861 print_ident(s, lifetime.ident);
1864 pub fn print_generics(s: @ps, generics: &ast::Generics) {
1865 let total = generics.lifetimes.len() + generics.ty_params.len();
1868 fn print_item(s: @ps, generics: &ast::Generics, idx: uint) {
1869 if idx < generics.lifetimes.len() {
1870 let lifetime = generics.lifetimes.get(idx);
1871 print_lifetime(s, lifetime);
1873 let idx = idx - generics.lifetimes.len();
1874 let param = generics.ty_params.get(idx);
1875 print_ident(s, param.ident);
1876 print_bounds(s, ¶m.bounds, false);
1881 for i in range(0u, total) {
1885 commasep(s, inconsistent, ints,
1886 |s, &i| print_item(s, generics, i));
1891 pub fn print_meta_item(s: @ps, item: &ast::MetaItem) {
1892 ibox(s, indent_unit);
1894 ast::MetaWord(name) => word(s.s, name),
1895 ast::MetaNameValue(name, value) => {
1896 word_space(s, name);
1898 print_literal(s, &value);
1900 ast::MetaList(name, ref items) => {
1906 |p, &i| print_meta_item(p, i));
1913 pub fn print_view_path(s: @ps, vp: &ast::view_path) {
1915 ast::view_path_simple(ident, ref path, _) => {
1916 // FIXME(#6993) can't compare identifiers directly here
1917 if path.segments.last().identifier.name != ident.name {
1918 print_ident(s, ident);
1922 print_path(s, path, false);
1925 ast::view_path_glob(ref path, _) => {
1926 print_path(s, path, false);
1930 ast::view_path_list(ref path, ref idents, _) => {
1931 if path.segments.is_empty() {
1934 print_path(s, path, false);
1937 commasep(s, inconsistent, (*idents), |s, w| {
1938 print_ident(s, w.node.name);
1945 pub fn print_view_paths(s: @ps, vps: &[@ast::view_path]) {
1946 commasep(s, inconsistent, vps, |p, &vp| print_view_path(p, vp));
1949 pub fn print_view_item(s: @ps, item: &ast::view_item) {
1950 hardbreak_if_not_bol(s);
1951 maybe_print_comment(s, item.span.lo);
1952 print_outer_attributes(s, item.attrs);
1953 print_visibility(s, item.vis);
1955 ast::view_item_extern_mod(id, ref optional_path, ref mta, _) => {
1956 head(s, "extern mod");
1958 for &(ref p, style) in optional_path.iter() {
1962 print_string(s, *p, style);
1964 if !mta.is_empty() {
1966 commasep(s, consistent, *mta, |p, &i| print_meta_item(p, i));
1971 ast::view_item_use(ref vps) => {
1973 print_view_paths(s, *vps);
1977 end(s); // end inner head-block
1978 end(s); // end outer head-block
1981 pub fn print_mutability(s: @ps, mutbl: ast::Mutability) {
1983 ast::MutMutable => word_nbsp(s, "mut"),
1984 ast::MutImmutable => {/* nothing */ }
1988 pub fn print_mt(s: @ps, mt: &ast::mt) {
1989 print_mutability(s, mt.mutbl);
1990 print_type(s, mt.ty);
1993 pub fn print_arg(s: @ps, input: &ast::arg) {
1994 ibox(s, indent_unit);
1995 match input.ty.node {
1996 ast::ty_infer => print_pat(s, input.pat),
1998 match input.pat.node {
1999 ast::PatIdent(_, ref path, _) if
2000 path.segments.len() == 1 &&
2001 path.segments[0].identifier.name ==
2002 parse::token::special_idents::invalid.name => {
2006 print_pat(s, input.pat);
2011 print_type(s, input.ty);
2017 pub fn print_ty_fn(s: @ps,
2018 opt_abis: Option<AbiSet>,
2019 opt_sigil: Option<ast::Sigil>,
2020 opt_region: &Option<ast::Lifetime>,
2021 purity: ast::purity,
2022 onceness: ast::Onceness,
2023 decl: &ast::fn_decl,
2024 id: Option<ast::Ident>,
2025 opt_bounds: &Option<OptVec<ast::TyParamBound>>,
2026 generics: Option<&ast::Generics>,
2027 opt_explicit_self: Option<ast::explicit_self_>) {
2028 ibox(s, indent_unit);
2030 // Duplicates the logic in `print_fn_header_info()`. This is because that
2031 // function prints the sigil in the wrong place. That should be fixed.
2032 if opt_sigil == Some(ast::OwnedSigil) && onceness == ast::Once {
2034 } else if opt_sigil == Some(ast::BorrowedSigil) {
2035 print_extern_opt_abis(s, opt_abis);
2036 for lifetime in opt_region.iter() {
2037 print_lifetime(s, lifetime);
2039 print_purity(s, purity);
2040 print_onceness(s, onceness);
2042 print_opt_abis_and_extern_if_nondefault(s, opt_abis);
2043 print_opt_sigil(s, opt_sigil);
2044 print_opt_lifetime(s, opt_region);
2045 print_purity(s, purity);
2046 print_onceness(s, onceness);
2050 match id { Some(id) => { word(s.s, " "); print_ident(s, id); } _ => () }
2052 if opt_sigil != Some(ast::BorrowedSigil) {
2053 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2056 match generics { Some(g) => print_generics(s, g), _ => () }
2059 if opt_sigil == Some(ast::BorrowedSigil) {
2065 // It is unfortunate to duplicate the commasep logic, but we want the
2066 // self type and the args all in the same box.
2067 rbox(s, 0u, inconsistent);
2068 let mut first = true;
2069 for explicit_self in opt_explicit_self.iter() {
2070 first = !print_explicit_self(s, *explicit_self);
2072 for arg in decl.inputs.iter() {
2073 if first { first = false; } else { word_space(s, ","); }
2078 if opt_sigil == Some(ast::BorrowedSigil) {
2081 opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2089 maybe_print_comment(s, decl.output.span.lo);
2091 match decl.output.node {
2094 space_if_not_bol(s);
2095 ibox(s, indent_unit);
2096 word_space(s, "->");
2097 if decl.cf == ast::noreturn { word_nbsp(s, "!"); }
2098 else { print_type(s, decl.output); }
2106 pub fn maybe_print_trailing_comment(s: @ps, span: codemap::Span,
2107 next_pos: Option<BytePos>) {
2109 match s.cm { Some(ccm) => cm = ccm, _ => return }
2110 match next_comment(s) {
2112 if (*cmnt).style != comments::trailing { return; }
2113 let span_line = cm.lookup_char_pos(span.hi);
2114 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2115 let mut next = (*cmnt).pos + BytePos(1);
2116 match next_pos { None => (), Some(p) => next = p }
2117 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2118 span_line.line == comment_line.line {
2119 print_comment(s, cmnt);
2120 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2127 pub fn print_remaining_comments(s: @ps) {
2128 // If there aren't any remaining comments, then we need to manually
2129 // make sure there is a line break at the end.
2130 if next_comment(s).is_none() { hardbreak(s.s); }
2132 match next_comment(s) {
2134 print_comment(s, cmnt);
2135 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2142 pub fn print_literal(s: @ps, lit: &ast::lit) {
2143 maybe_print_comment(s, lit.span.lo);
2144 match next_lit(s, lit.span.lo) {
2146 word(s.s, (*ltrl).lit);
2152 ast::lit_str(st, style) => print_string(s, st, style),
2153 ast::lit_char(ch) => {
2155 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2156 res.push_char('\'');
2159 ast::lit_int(i, t) => {
2162 ~"-" + (-i as u64).to_str_radix(10u)
2163 + ast_util::int_ty_to_str(t));
2166 (i as u64).to_str_radix(10u)
2167 + ast_util::int_ty_to_str(t));
2170 ast::lit_uint(u, t) => {
2173 + ast_util::uint_ty_to_str(t));
2175 ast::lit_int_unsuffixed(i) => {
2177 word(s.s, ~"-" + (-i as u64).to_str_radix(10u));
2179 word(s.s, (i as u64).to_str_radix(10u));
2182 ast::lit_float(f, t) => {
2183 word(s.s, f.to_owned() + ast_util::float_ty_to_str(t));
2185 ast::lit_float_unsuffixed(f) => word(s.s, f),
2186 ast::lit_nil => word(s.s, "()"),
2187 ast::lit_bool(val) => {
2188 if val { word(s.s, "true"); } else { word(s.s, "false"); }
2190 ast::lit_binary(arr) => {
2191 ibox(s, indent_unit);
2193 commasep_cmnt(s, inconsistent, arr, |s, u| word(s.s, format!("{}", *u)),
2201 pub fn lit_to_str(l: &ast::lit) -> ~str {
2202 return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2205 pub fn next_lit(s: @ps, pos: BytePos) -> Option<comments::lit> {
2208 while s.cur_cmnt_and_lit.cur_lit < lits.len() {
2209 let ltrl = (*lits)[s.cur_cmnt_and_lit.cur_lit].clone();
2210 if ltrl.pos > pos { return None; }
2211 s.cur_cmnt_and_lit.cur_lit += 1u;
2212 if ltrl.pos == pos { return Some(ltrl); }
2220 pub fn maybe_print_comment(s: @ps, pos: BytePos) {
2222 match next_comment(s) {
2224 if (*cmnt).pos < pos {
2225 print_comment(s, cmnt);
2226 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2234 pub fn print_comment(s: @ps, cmnt: &comments::cmnt) {
2236 comments::mixed => {
2237 assert_eq!(cmnt.lines.len(), 1u);
2239 word(s.s, cmnt.lines[0]);
2242 comments::isolated => {
2243 pprust::hardbreak_if_not_bol(s);
2244 for line in cmnt.lines.iter() {
2245 // Don't print empty lines because they will end up as trailing
2247 if !line.is_empty() { word(s.s, *line); }
2251 comments::trailing => {
2253 if cmnt.lines.len() == 1u {
2254 word(s.s, cmnt.lines[0]);
2258 for line in cmnt.lines.iter() {
2259 if !line.is_empty() { word(s.s, *line); }
2265 comments::blank_line => {
2266 // We need to do at least one, possibly two hardbreaks.
2268 match s.s.last_token() {
2269 pp::STRING(s, _) => ";" == s,
2272 if is_semi || is_begin(s) || is_end(s) { hardbreak(s.s); }
2278 pub fn print_string(s: @ps, st: &str, style: ast::StrStyle) {
2279 let st = match style {
2280 ast::CookedStr => format!("\"{}\"", st.escape_default()),
2281 ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2282 delim="#".repeat(n), string=st)
2287 pub fn to_str<T>(t: &T, f: |@ps, &T|, intr: @ident_interner) -> ~str {
2288 let wr = @mut MemWriter::new();
2289 let s = rust_printer(wr as @mut io::Writer, intr);
2292 str::from_utf8_owned(wr.inner_ref().to_owned())
2295 pub fn next_comment(s: @ps) -> Option<comments::cmnt> {
2297 Some(ref cmnts) => {
2298 if s.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2299 return Some(cmnts[s.cur_cmnt_and_lit.cur_cmnt].clone());
2301 return None::<comments::cmnt>;
2304 _ => return None::<comments::cmnt>
2308 pub fn print_opt_purity(s: @ps, opt_purity: Option<ast::purity>) {
2310 Some(ast::impure_fn) => { }
2312 word_nbsp(s, purity_to_str(purity));
2318 pub fn print_opt_abis_and_extern_if_nondefault(s: @ps,
2319 opt_abis: Option<AbiSet>) {
2321 Some(abis) if !abis.is_rust() => {
2322 word_nbsp(s, "extern");
2323 word_nbsp(s, abis.to_str());
2325 Some(_) | None => {}
2329 pub fn print_extern_opt_abis(s: @ps, opt_abis: Option<AbiSet>) {
2332 word_nbsp(s, "extern");
2333 word_nbsp(s, abis.to_str());
2339 pub fn print_opt_sigil(s: @ps, opt_sigil: Option<ast::Sigil>) {
2341 Some(ast::BorrowedSigil) => { word(s.s, "&"); }
2342 Some(ast::OwnedSigil) => { word(s.s, "~"); }
2343 Some(ast::ManagedSigil) => { word(s.s, "@"); }
2348 pub fn print_fn_header_info(s: @ps,
2349 _opt_explicit_self: Option<ast::explicit_self_>,
2350 opt_purity: Option<ast::purity>,
2352 onceness: ast::Onceness,
2353 opt_sigil: Option<ast::Sigil>,
2354 vis: ast::visibility) {
2355 word(s.s, visibility_qualified(vis, ""));
2357 if abis != AbiSet::Rust() {
2358 word_nbsp(s, "extern");
2359 word_nbsp(s, abis.to_str());
2361 if opt_purity != Some(ast::extern_fn) {
2362 print_opt_purity(s, opt_purity);
2365 print_opt_purity(s, opt_purity);
2368 print_onceness(s, onceness);
2370 print_opt_sigil(s, opt_sigil);
2373 pub fn purity_to_str(p: ast::purity) -> &'static str {
2375 ast::impure_fn => "impure",
2376 ast::unsafe_fn => "unsafe",
2377 ast::extern_fn => "extern"
2381 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2383 ast::Once => "once",
2388 pub fn print_purity(s: @ps, p: ast::purity) {
2390 ast::impure_fn => (),
2391 _ => word_nbsp(s, purity_to_str(p))
2395 pub fn print_onceness(s: @ps, o: ast::Onceness) {
2397 ast::Once => { word_nbsp(s, "once"); }
2411 fn string_check<T:Eq> (given : &T, expected: &T) {
2412 if !(given == expected) {
2413 fail!("given {:?}, expected {:?}", given, expected);
2418 fn test_fun_to_str() {
2419 let abba_ident = token::str_to_ident("abba");
2421 let decl = ast::fn_decl {
2423 output: ast::P(ast::Ty {id: 0,
2425 span: codemap::DUMMY_SP}),
2426 cf: ast::return_val,
2429 let generics = ast_util::empty_generics();
2430 assert_eq!(&fun_to_str(&decl, ast::impure_fn, abba_ident,
2431 None, &generics, token::get_ident_interner()),
2436 fn test_variant_to_str() {
2437 let ident = token::str_to_ident("principal_skinner");
2439 let var = codemap::respan(codemap::DUMMY_SP, ast::variant_ {
2442 // making this up as I go.... ?
2443 kind: ast::tuple_variant_kind(~[]),
2449 let varstr = variant_to_str(&var,token::get_ident_interner());
2450 assert_eq!(&varstr,&~"pub principal_skinner");