]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
auto merge of #11598 : alexcrichton/rust/io-export, r=brson
[rust.git] / src / libsyntax / print / pprust.rs
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.
4 //
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.
10
11 use abi::AbiSet;
12 use ast::{P, RegionTyParamBound, TraitTyParamBound, Required, Provided};
13 use ast;
14 use ast_util;
15 use opt_vec::OptVec;
16 use opt_vec;
17 use attr::{AttrMetaMethods, AttributeMethods};
18 use codemap::{CodeMap, BytePos};
19 use codemap;
20 use diagnostic;
21 use parse::classify::expr_is_simple_block;
22 use parse::token::{IdentInterner, ident_to_str, interner_get};
23 use parse::{comments, token};
24 use parse;
25 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, Consistent, Inconsistent, eof};
27 use print::pp;
28 use print::pprust;
29
30 use std::cast;
31 use std::cell::RefCell;
32 use std::char;
33 use std::str;
34 use std::io;
35 use std::io::MemWriter;
36
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),
43 }
44
45 pub trait PpAnn {
46     fn pre(&self, _node: AnnNode) {}
47     fn post(&self, _node: AnnNode) {}
48 }
49
50 pub struct NoAnn;
51
52 impl PpAnn for NoAnn {}
53
54 pub struct CurrentCommentAndLiteral {
55     cur_cmnt: uint,
56     cur_lit: uint,
57 }
58
59 pub struct State {
60     s: pp::Printer,
61     cm: Option<@CodeMap>,
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]>,
67     ann: @PpAnn
68 }
69
70 pub fn ibox(s: &mut State, u: uint) {
71     {
72         let mut boxes = s.boxes.borrow_mut();
73         boxes.get().push(pp::Inconsistent);
74     }
75     pp::ibox(&mut s.s, u);
76 }
77
78 pub fn end(s: &mut State) {
79     {
80         let mut boxes = s.boxes.borrow_mut();
81         boxes.get().pop();
82     }
83     pp::end(&mut s.s);
84 }
85
86 pub fn rust_printer(writer: ~io::Writer, intr: @IdentInterner) -> State {
87     return rust_printer_annotated(writer, intr, @NoAnn as @PpAnn);
88 }
89
90 pub fn rust_printer_annotated(writer: ~io::Writer,
91                               intr: @IdentInterner,
92                               ann: @PpAnn)
93                               -> State {
94     return State {
95         s: pp::mk_printer(writer, default_columns),
96         cm: None,
97         intr: intr,
98         comments: None,
99         literals: None,
100         cur_cmnt_and_lit: CurrentCommentAndLiteral {
101             cur_cmnt: 0,
102             cur_lit: 0
103         },
104         boxes: RefCell::new(~[]),
105         ann: ann
106     };
107 }
108
109 pub static indent_unit: uint = 4u;
110
111 pub static default_columns: uint = 78u;
112
113 // Requires you to pass an input filename and reader so that
114 // it can scan the input text for comments and literals to
115 // copy forward.
116 pub fn print_crate(cm: @CodeMap,
117                    intr: @IdentInterner,
118                    span_diagnostic: @diagnostic::SpanHandler,
119                    crate: &ast::Crate,
120                    filename: @str,
121                    input: &mut io::Reader,
122                    out: ~io::Writer,
123                    ann: @PpAnn,
124                    is_expanded: bool) {
125     let (cmnts, lits) = comments::gather_comments_and_literals(
126         span_diagnostic,
127         filename,
128         input
129     );
130     let mut s = State {
131         s: pp::mk_printer(out, default_columns),
132         cm: Some(cm),
133         intr: intr,
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 {
139             None
140         } else {
141             Some(lits)
142         },
143         cur_cmnt_and_lit: CurrentCommentAndLiteral {
144             cur_cmnt: 0,
145             cur_lit: 0
146         },
147         boxes: RefCell::new(~[]),
148         ann: ann
149     };
150     print_crate_(&mut s, crate);
151 }
152
153 pub fn print_crate_(s: &mut State, crate: &ast::Crate) {
154     print_mod(s, &crate.module, crate.attrs);
155     print_remaining_comments(s);
156     eof(&mut s.s);
157 }
158
159 pub fn ty_to_str(ty: &ast::Ty, intr: @IdentInterner) -> ~str {
160     to_str(ty, print_type, intr)
161 }
162
163 pub fn pat_to_str(pat: &ast::Pat, intr: @IdentInterner) -> ~str {
164     to_str(pat, print_pat, intr)
165 }
166
167 pub fn expr_to_str(e: &ast::Expr, intr: @IdentInterner) -> ~str {
168     to_str(e, print_expr, intr)
169 }
170
171 pub fn lifetime_to_str(e: &ast::Lifetime, intr: @IdentInterner) -> ~str {
172     to_str(e, print_lifetime, intr)
173 }
174
175 pub fn tt_to_str(tt: &ast::TokenTree, intr: @IdentInterner) -> ~str {
176     to_str(tt, print_tt, intr)
177 }
178
179 pub fn tts_to_str(tts: &[ast::TokenTree], intr: @IdentInterner) -> ~str {
180     to_str(&tts, print_tts, intr)
181 }
182
183 pub fn stmt_to_str(s: &ast::Stmt, intr: @IdentInterner) -> ~str {
184     to_str(s, print_stmt, intr)
185 }
186
187 pub fn item_to_str(i: &ast::Item, intr: @IdentInterner) -> ~str {
188     to_str(i, print_item, intr)
189 }
190
191 pub fn generics_to_str(generics: &ast::Generics,
192                        intr: @IdentInterner) -> ~str {
193     to_str(generics, print_generics, intr)
194 }
195
196 pub fn path_to_str(p: &ast::Path, intr: @IdentInterner) -> ~str {
197     to_str(p, |a,b| print_path(a, b, false), intr)
198 }
199
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
209     eof(&mut s.s);
210     unsafe {
211         get_mem_writer(&mut s.s.out)
212     }
213 }
214
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 {
221     ibox(&mut s, 0u);
222     print_block(&mut s, blk);
223     eof(&mut s.s);
224     unsafe {
225         get_mem_writer(&mut s.s.out)
226     }
227 }
228
229 pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @IdentInterner) -> ~str {
230     to_str(mi, print_meta_item, intr)
231 }
232
233 pub fn attribute_to_str(attr: &ast::Attribute, intr: @IdentInterner) -> ~str {
234     to_str(attr, print_attribute, intr)
235 }
236
237 pub fn variant_to_str(var: &ast::Variant, intr: @IdentInterner) -> ~str {
238     to_str(var, print_variant, intr)
239 }
240
241 pub fn cbox(s: &mut State, u: uint) {
242     {
243         let mut boxes = s.boxes.borrow_mut();
244         boxes.get().push(pp::Consistent);
245     }
246     pp::cbox(&mut s.s, u);
247 }
248
249 // "raw box"
250 pub fn rbox(s: &mut State, u: uint, b: pp::Breaks) {
251     {
252         let mut boxes = s.boxes.borrow_mut();
253         boxes.get().push(b);
254     }
255     pp::rbox(&mut s.s, u, b);
256 }
257
258 pub fn nbsp(s: &mut State) { word(&mut s.s, " "); }
259
260 pub fn word_nbsp(s: &mut State, w: &str) { word(&mut s.s, w); nbsp(s); }
261
262 pub fn word_space(s: &mut State, w: &str) { word(&mut s.s, w); space(&mut s.s); }
263
264 pub fn popen(s: &mut State) { word(&mut s.s, "("); }
265
266 pub fn pclose(s: &mut State) { word(&mut s.s, ")"); }
267
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
274     if !w.is_empty() {
275         word_nbsp(s, w);
276     }
277 }
278
279 pub fn bopen(s: &mut State) {
280     word(&mut s.s, "{");
281     end(s); // close the head-box
282 }
283
284 pub fn bclose_(s: &mut State, span: codemap::Span, indented: uint) {
285     bclose_maybe_open(s, span, indented, true);
286 }
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));
291     word(&mut s.s, "}");
292     if close_box {
293         end(s); // close the outer-box
294     }
295 }
296 pub fn bclose(s: &mut State, span: codemap::Span) {
297     bclose_(s, span, indent_unit);
298 }
299
300 pub fn is_begin(s: &mut State) -> bool {
301     match s.s.last_token() { pp::Begin(_) => true, _ => false }
302 }
303
304 pub fn is_end(s: &mut State) -> bool {
305     match s.s.last_token() { pp::End => true, _ => false }
306 }
307
308 pub fn is_bol(s: &mut State) -> bool {
309     return s.s.last_token().is_eof() || s.s.last_token().is_hardbreak_tok();
310 }
311
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;
317 }
318
319 pub fn hardbreak_if_not_bol(s: &mut State) {
320     if !is_bol(s) {
321         hardbreak(&mut s.s)
322     }
323 }
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) {
326     if !is_bol(s) {
327         break_offset(&mut s.s, n, off);
328     } else {
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));
334         }
335     }
336 }
337
338 // Synthesizes a comment that was not textually present in the original source
339 // file.
340 pub fn synth_comment(s: &mut State, text: ~str) {
341     word(&mut s.s, "/*");
342     space(&mut s.s);
343     word(&mut s.s, text);
344     space(&mut s.s);
345     word(&mut s.s, "*/");
346 }
347
348 pub fn commasep<T>(s: &mut State, b: Breaks, elts: &[T], op: |&mut State, &T|) {
349     rbox(s, 0u, b);
350     let mut first = true;
351     for elt in elts.iter() {
352         if first { first = false; } else { word_space(s, ","); }
353         op(s, elt);
354     }
355     end(s);
356 }
357
358
359 pub fn commasep_cmnt<T>(
360                      s: &mut State,
361                      b: Breaks,
362                      elts: &[T],
363                      op: |&mut State, &T|,
364                      get_span: |&T| -> codemap::Span) {
365     rbox(s, 0u, b);
366     let len = elts.len();
367     let mut i = 0u;
368     for elt in elts.iter() {
369         maybe_print_comment(s, get_span(elt).hi);
370         op(s, elt);
371         i += 1u;
372         if i < len {
373             word(&mut s.s, ",");
374             maybe_print_trailing_comment(s, get_span(elt),
375                                          Some(get_span(&elts[i]).hi));
376             space_if_not_bol(s);
377         }
378     }
379     end(s);
380 }
381
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);
384 }
385
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);
390     }
391     for item in _mod.items.iter() { print_item(s, *item); }
392 }
393
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);
399     }
400     for item in nmod.items.iter() { print_foreign_item(s, *item); }
401 }
402
403 pub fn print_opt_lifetime(s: &mut State, lifetime: &Option<ast::Lifetime>) {
404     for l in lifetime.iter() {
405         print_lifetime(s, l);
406         nbsp(s);
407     }
408 }
409
410 pub fn print_type(s: &mut State, ty: &ast::Ty) {
411     maybe_print_comment(s, ty.span.lo);
412     ibox(s, 0u);
413     match ty.node {
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); }
418         ast::TyVec(ty) => {
419             word(&mut s.s, "[");
420             print_type(s, ty);
421             word(&mut s.s, "]");
422         }
423         ast::TyPtr(ref mt) => { word(&mut s.s, "*"); print_mt(s, mt); }
424         ast::TyRptr(ref lifetime, ref mt) => {
425             word(&mut s.s, "&");
426             print_opt_lifetime(s, lifetime);
427             print_mt(s, mt);
428         }
429         ast::TyTup(ref elts) => {
430             popen(s);
431             commasep(s, Inconsistent, *elts, print_type_ref);
432             if elts.len() == 1 {
433                 word(&mut s.s, ",");
434             }
435             pclose(s);
436         }
437         ast::TyBareFn(f) => {
438             let generics = ast::Generics {
439                 lifetimes: f.lifetimes.clone(),
440                 ty_params: opt_vec::Empty
441             };
442             print_ty_fn(s, Some(f.abis), None, &None,
443                         f.purity, ast::Many, f.decl, None, &None,
444                         Some(&generics), None);
445         }
446         ast::TyClosure(f) => {
447             let generics = ast::Generics {
448                 lifetimes: f.lifetimes.clone(),
449                 ty_params: opt_vec::Empty
450             };
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);
454         }
455         ast::TyPath(ref path, ref bounds, _) => print_bounded_path(s, path, bounds),
456         ast::TyFixedLengthVec(ty, v) => {
457             word(&mut s.s, "[");
458             print_type(s, ty);
459             word(&mut s.s, ", ..");
460             print_expr(s, v);
461             word(&mut s.s, "]");
462         }
463         ast::TyTypeof(e) => {
464             word(&mut s.s, "typeof(");
465             print_expr(s, e);
466             word(&mut s.s, ")");
467         }
468         ast::TyInfer => {
469             fail!("print_type shouldn't see a ty_infer");
470         }
471     }
472     end(s);
473 }
474
475 pub fn print_type_ref(s: &mut State, ty: &P<ast::Ty>) {
476     print_type(s, *ty);
477 }
478
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);
483     match item.node {
484       ast::ForeignItemFn(decl, ref generics) => {
485         print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, None,
486                  item.vis);
487         end(s); // end head-ibox
488         word(&mut s.s, ";");
489         end(s); // end the outer fn box
490       }
491       ast::ForeignItemStatic(t, m) => {
492         head(s, visibility_qualified(item.vis, "static"));
493         if m {
494             word_space(s, "mut");
495         }
496         print_ident(s, item.ident);
497         word_space(s, ":");
498         print_type(s, t);
499         word(&mut s.s, ";");
500         end(s); // end the head-ibox
501         end(s); // end the outer cbox
502       }
503     }
504 }
505
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);
510     {
511         let ann_node = NodeItem(s, item);
512         s.ann.pre(ann_node);
513     }
514     match item.node {
515       ast::ItemStatic(ty, m, expr) => {
516         head(s, visibility_qualified(item.vis, "static"));
517         if m == ast::MutMutable {
518             word_space(s, "mut");
519         }
520         print_ident(s, item.ident);
521         word_space(s, ":");
522         print_type(s, ty);
523         space(&mut s.s);
524         end(s); // end the head-ibox
525
526         word_space(s, "=");
527         print_expr(s, expr);
528         word(&mut s.s, ";");
529         end(s); // end the outer cbox
530
531       }
532       ast::ItemFn(decl, purity, abi, ref typarams, body) => {
533         print_fn(
534             s,
535             decl,
536             Some(purity),
537             abi,
538             item.ident,
539             typarams,
540             None,
541             item.vis
542         );
543         word(&mut s.s, " ");
544         print_block_with_attrs(s, body, item.attrs);
545       }
546       ast::ItemMod(ref _mod) => {
547         head(s, visibility_qualified(item.vis, "mod"));
548         print_ident(s, item.ident);
549         nbsp(s);
550         bopen(s);
551         print_mod(s, _mod, item.attrs);
552         bclose(s, item.span);
553       }
554       ast::ItemForeignMod(ref nmod) => {
555         head(s, "extern");
556         word_nbsp(s, nmod.abis.to_str());
557         bopen(s);
558         print_foreign_mod(s, nmod, item.attrs);
559         bclose(s, item.span);
560       }
561       ast::ItemTy(ty, ref params) => {
562         ibox(s, indent_unit);
563         ibox(s, 0u);
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
568
569         space(&mut s.s);
570         word_space(s, "=");
571         print_type(s, ty);
572         word(&mut s.s, ";");
573         end(s); // end the outer ibox
574       }
575       ast::ItemEnum(ref enum_definition, ref params) => {
576         print_enum_def(
577             s,
578             enum_definition,
579             params,
580             item.ident,
581             item.span,
582             item.vis
583         );
584       }
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);
588       }
589
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);
594             space(&mut s.s);
595         }
596
597         match opt_trait {
598             &Some(ref t) => {
599                 print_trait_ref(s, t);
600                 space(&mut s.s);
601                 word_space(s, "for");
602             }
603             &None => ()
604         };
605
606         print_type(s, ty);
607
608         space(&mut s.s);
609         bopen(s);
610         print_inner_attributes(s, item.attrs);
611         for meth in methods.iter() {
612            print_method(s, *meth);
613         }
614         bclose(s, item.span);
615       }
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 {
621             word(&mut s.s, ":");
622             for (i, trait_) in traits.iter().enumerate() {
623                 nbsp(s);
624                 if i != 0 {
625                     word_space(s, "+");
626                 }
627                 print_path(s, &trait_.path, false);
628             }
629         }
630         word(&mut s.s, " ");
631         bopen(s);
632         for meth in methods.iter() {
633             print_trait_method(s, meth);
634         }
635         bclose(s, item.span);
636       }
637       // I think it's reasonable to hide the context here:
638       ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
639                                    ..}) => {
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);
645         popen(s);
646         print_tts(s, &(tts.as_slice()));
647         pclose(s);
648         end(s);
649       }
650     }
651     {
652         let ann_node = NodeItem(s, item);
653         s.ann.post(ann_node);
654     }
655 }
656
657 fn print_trait_ref(s: &mut State, t: &ast::TraitRef) {
658     print_path(s, &t.path, false);
659 }
660
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);
667     space(&mut s.s);
668     print_variants(s, enum_definition.variants, span);
669 }
670
671 pub fn print_variants(s: &mut State,
672                       variants: &[P<ast::Variant>],
673                       span: codemap::Span) {
674     bopen(s);
675     for &v in variants.iter() {
676         space_if_not_bol(s);
677         maybe_print_comment(s, v.span.lo);
678         print_outer_attributes(s, v.node.attrs);
679         ibox(s, indent_unit);
680         print_variant(s, v);
681         word(&mut s.s, ",");
682         end(s);
683         maybe_print_trailing_comment(s, v.span, None);
684     }
685     bclose(s, span);
686 }
687
688 pub fn visibility_to_str(vis: ast::Visibility) -> ~str {
689     match vis {
690         ast::Private => ~"priv",
691         ast::Public => ~"pub",
692         ast::Inherited => ~""
693     }
694 }
695
696 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str {
697     match vis {
698         ast::Private | ast::Public => visibility_to_str(vis) + " " + s,
699         ast::Inherited => s.to_owned()
700     }
701 }
702
703 pub fn print_visibility(s: &mut State, vis: ast::Visibility) {
704     match vis {
705         ast::Private | ast::Public =>
706         word_nbsp(s, visibility_to_str(vis)),
707         ast::Inherited => ()
708     }
709 }
710
711 pub fn print_struct(s: &mut State,
712                     struct_def: &ast::StructDef,
713                     generics: &ast::Generics,
714                     ident: ast::Ident,
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() {
720             popen(s);
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);
727                     }
728                 }
729             });
730             pclose(s);
731         }
732         word(&mut s.s, ";");
733         end(s);
734         end(s); // close the outer-box
735     } else {
736         nbsp(s);
737         bopen(s);
738         hardbreak_if_not_bol(s);
739
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);
749                     word_nbsp(s, ":");
750                     print_type(s, field.node.ty);
751                     word(&mut s.s, ",");
752                 }
753             }
754         }
755
756         bclose(s, span);
757     }
758 }
759
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) {
768     match *tt {
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));
772       }
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); }
776         word(&mut s.s, ")");
777         match (*sep) {
778           Some(ref tk) => word(&mut s.s, parse::token::to_str(s.intr, tk)),
779           None => ()
780         }
781         word(&mut s.s, if zerok { "*" } else { "+" });
782       }
783       ast::TTNonterminal(_, name) => {
784         word(&mut s.s, "$");
785         print_ident(s, name);
786       }
787     }
788 }
789
790 pub fn print_tts(s: &mut State, tts: & &[ast::TokenTree]) {
791     ibox(s, 0);
792     for (i, tt) in tts.iter().enumerate() {
793         if i != 0 {
794             space(&mut s.s);
795         }
796         print_tt(s, tt);
797     }
798     end(s);
799 }
800
801 pub fn print_variant(s: &mut State, v: &ast::Variant) {
802     print_visibility(s, v.node.vis);
803     match v.node.kind {
804         ast::TupleVariantKind(ref args) => {
805             print_ident(s, v.node.name);
806             if !args.is_empty() {
807                 popen(s);
808                 fn print_variant_arg(s: &mut State, arg: &ast::VariantArg) {
809                     print_type(s, arg.ty);
810                 }
811                 commasep(s, Consistent, *args, print_variant_arg);
812                 pclose(s);
813             }
814         }
815         ast::StructVariantKind(struct_def) => {
816             head(s, "");
817             let generics = ast_util::empty_generics();
818             print_struct(s, struct_def, &generics, v.node.name, v.span);
819         }
820     }
821     match v.node.disr_expr {
822       Some(d) => {
823         space(&mut s.s);
824         word_space(s, "=");
825         print_expr(s, d);
826       }
827       _ => ()
828     }
829 }
830
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);
835     print_ty_fn(s,
836                 None,
837                 None,
838                 &None,
839                 m.purity,
840                 ast::Many,
841                 m.decl,
842                 Some(m.ident),
843                 &None,
844                 Some(&m.generics),
845                 Some(m.explicit_self.node));
846     word(&mut s.s, ";");
847 }
848
849 pub fn print_trait_method(s: &mut State, m: &ast::TraitMethod) {
850     match *m {
851         Required(ref ty_m) => print_ty_method(s, ty_m),
852         Provided(m) => print_method(s, m)
853     }
854 }
855
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),
862              meth.vis);
863     word(&mut s.s, " ");
864     print_block_with_attrs(s, meth.body, meth.attrs);
865 }
866
867 pub fn print_outer_attributes(s: &mut State, attrs: &[ast::Attribute]) {
868     let mut count = 0;
869     for attr in attrs.iter() {
870         match attr.node.style {
871           ast::AttrOuter => { print_attribute(s, attr); count += 1; }
872           _ => {/* fallthrough */ }
873         }
874     }
875     if count > 0 { hardbreak_if_not_bol(s); }
876 }
877
878 pub fn print_inner_attributes(s: &mut State, attrs: &[ast::Attribute]) {
879     let mut count = 0;
880     for attr in attrs.iter() {
881         match attr.node.style {
882           ast::AttrInner => {
883             print_attribute(s, attr);
884             if !attr.node.is_sugared_doc {
885                 word(&mut s.s, ";");
886             }
887             count += 1;
888           }
889           _ => {/* fallthrough */ }
890         }
891     }
892     if count > 0 { hardbreak_if_not_bol(s); }
893 }
894
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);
901     } else {
902         word(&mut s.s, "#[");
903         print_meta_item(s, attr.meta());
904         word(&mut s.s, "]");
905     }
906 }
907
908
909 pub fn print_stmt(s: &mut State, st: &ast::Stmt) {
910     maybe_print_comment(s, st.span.lo);
911     match st.node {
912       ast::StmtDecl(decl, _) => {
913         print_decl(s, decl);
914       }
915       ast::StmtExpr(expr, _) => {
916         space_if_not_bol(s);
917         print_expr(s, expr);
918       }
919       ast::StmtSemi(expr, _) => {
920         space_if_not_bol(s);
921         print_expr(s, expr);
922         word(&mut s.s, ";");
923       }
924       ast::StmtMac(ref mac, semi) => {
925         space_if_not_bol(s);
926         print_mac(s, mac);
927         if semi { word(&mut s.s, ";"); }
928       }
929     }
930     if parse::classify::stmt_ends_with_semi(st) { word(&mut s.s, ";"); }
931     maybe_print_trailing_comment(s, st.span, None);
932 }
933
934 pub fn print_block(s: &mut State, blk: &ast::Block) {
935     print_possibly_embedded_block(s, blk, BlockNormal, indent_unit);
936 }
937
938 pub fn print_block_unclosed(s: &mut State, blk: &ast::Block) {
939     print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, &[],
940                                  false);
941 }
942
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);
945 }
946
947 pub fn print_block_with_attrs(s: &mut State,
948                               blk: &ast::Block,
949                               attrs: &[ast::Attribute]) {
950     print_possibly_embedded_block_(s, blk, BlockNormal, indent_unit, attrs,
951                                   true);
952 }
953
954 enum EmbedType {
955     BlockBlockFn,
956     BlockNormal,
957 }
958
959 pub fn print_possibly_embedded_block(s: &mut State,
960                                      blk: &ast::Block,
961                                      embedded: EmbedType,
962                                      indented: uint) {
963     print_possibly_embedded_block_(
964         s, blk, embedded, indented, &[], true);
965 }
966
967 pub fn print_possibly_embedded_block_(s: &mut State,
968                                       blk: &ast::Block,
969                                       embedded: EmbedType,
970                                       indented: uint,
971                                       attrs: &[ast::Attribute],
972                                       close_box: bool) {
973     match blk.rules {
974       ast::UnsafeBlock(..) => word_space(s, "unsafe"),
975       ast::DefaultBlock => ()
976     }
977     maybe_print_comment(s, blk.span.lo);
978     {
979         let ann_node = NodeBlock(s, blk);
980         s.ann.pre(ann_node);
981     }
982     match embedded {
983         BlockBlockFn => end(s),
984         BlockNormal => bopen(s)
985     }
986
987     print_inner_attributes(s, attrs);
988
989     for vi in blk.view_items.iter() { print_view_item(s, vi); }
990     for st in blk.stmts.iter() {
991         print_stmt(s, *st);
992     }
993     match blk.expr {
994       Some(expr) => {
995         space_if_not_bol(s);
996         print_expr(s, expr);
997         maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
998       }
999       _ => ()
1000     }
1001     bclose_maybe_open(s, blk.span, indented, close_box);
1002     {
1003         let ann_node = NodeBlock(s, blk);
1004         s.ann.post(ann_node);
1005     }
1006 }
1007
1008 pub fn print_if(s: &mut State, test: &ast::Expr, blk: &ast::Block,
1009                 elseopt: Option<@ast::Expr>, chk: bool) {
1010     head(s, "if");
1011     if chk { word_nbsp(s, "check"); }
1012     print_expr(s, test);
1013     space(&mut s.s);
1014     print_block(s, blk);
1015     fn do_else(s: &mut State, els: Option<@ast::Expr>) {
1016         match els {
1017           Some(_else) => {
1018             match _else.node {
1019               // "another else-if"
1020               ast::ExprIf(i, t, e) => {
1021                 cbox(s, indent_unit - 1u);
1022                 ibox(s, 0u);
1023                 word(&mut s.s, " else if ");
1024                 print_expr(s, i);
1025                 space(&mut s.s);
1026                 print_block(s, t);
1027                 do_else(s, e);
1028               }
1029               // "final else"
1030               ast::ExprBlock(b) => {
1031                 cbox(s, indent_unit - 1u);
1032                 ibox(s, 0u);
1033                 word(&mut s.s, " else ");
1034                 print_block(s, b);
1035               }
1036               // BLEAH, constraints would be great here
1037               _ => {
1038                   fail!("print_if saw if with weird alternative");
1039               }
1040             }
1041           }
1042           _ => {/* fall through */ }
1043         }
1044     }
1045     do_else(s, elseopt);
1046 }
1047
1048 pub fn print_mac(s: &mut State, m: &ast::Mac) {
1049     match m.node {
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, "!");
1054         popen(s);
1055         print_tts(s, &tts.as_slice());
1056         pclose(s);
1057       }
1058     }
1059 }
1060
1061 pub fn print_vstore(s: &mut State, t: ast::Vstore) {
1062     match t {
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);
1070         }
1071     }
1072 }
1073
1074 pub fn print_expr_vstore(s: &mut State, t: ast::ExprVstore) {
1075     match t {
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");
1082       }
1083     }
1084 }
1085
1086 pub fn print_call_pre(s: &mut State,
1087                       sugar: ast::CallSugar,
1088                       base_args: &mut ~[@ast::Expr])
1089                    -> Option<@ast::Expr> {
1090     match sugar {
1091         ast::DoSugar => {
1092             head(s, "do");
1093             Some(base_args.pop())
1094         }
1095         ast::ForSugar => {
1096             head(s, "for");
1097             Some(base_args.pop())
1098         }
1099         ast::NoSugar => None
1100     }
1101 }
1102
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() {
1108         popen(s);
1109         commasep_exprs(s, Inconsistent, *base_args);
1110         pclose(s);
1111     }
1112     if sugar != ast::NoSugar {
1113         nbsp(s);
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.
1119             print_expr(s, e);
1120             end(s); // close outer box, as closures don't
1121           }
1122           _ => {
1123             // not sure if this can happen.
1124             print_expr(s, blk.unwrap());
1125           }
1126         }
1127     }
1128 }
1129
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);
1134         word_space(s, ":");
1135         print_expr(s, field.expr);
1136         end(s);
1137     }
1138     fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1139
1140     maybe_print_comment(s, expr.span.lo);
1141     ibox(s, indent_unit);
1142     {
1143         let ann_node = NodeExpr(s, expr);
1144         s.ann.pre(ann_node);
1145     }
1146     match expr.node {
1147         ast::ExprVstore(e, v) => {
1148             print_expr_vstore(s, v);
1149             print_expr(s, e);
1150         },
1151         ast::ExprBox(p, e) => {
1152             word(&mut s.s, "box");
1153             word(&mut s.s, "(");
1154             print_expr(s, p);
1155             word_space(s, ")");
1156             print_expr(s, e);
1157         }
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); }
1164         }
1165         commasep_exprs(s, Inconsistent, *exprs);
1166         word(&mut s.s, "]");
1167         end(s);
1168       }
1169
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");
1175             nbsp(s);
1176         }
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, "]");
1182         end(s);
1183       }
1184
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);
1189         match wth {
1190             Some(expr) => {
1191                 ibox(s, indent_unit);
1192                 word(&mut s.s, ",");
1193                 space(&mut s.s);
1194                 word(&mut s.s, "..");
1195                 print_expr(s, expr);
1196                 end(s);
1197             }
1198             _ => (word(&mut s.s, ","))
1199         }
1200         word(&mut s.s, "}");
1201       }
1202       ast::ExprTup(ref exprs) => {
1203         popen(s);
1204         commasep_exprs(s, Inconsistent, *exprs);
1205         if exprs.len() == 1 {
1206             word(&mut s.s, ",");
1207         }
1208         pclose(s);
1209       }
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);
1215       }
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);
1222         if tys.len() > 0u {
1223             word(&mut s.s, "::<");
1224             commasep(s, Inconsistent, *tys, print_type_ref);
1225             word(&mut s.s, ">");
1226         }
1227         print_call_post(s, sugar, &blk, &mut base_args);
1228       }
1229       ast::ExprBinary(_, op, lhs, rhs) => {
1230         print_expr(s, lhs);
1231         space(&mut s.s);
1232         word_space(s, ast_util::binop_to_str(op));
1233         print_expr(s, rhs);
1234       }
1235       ast::ExprUnary(_, op, expr) => {
1236         word(&mut s.s, ast_util::unop_to_str(op));
1237         print_expr(s, expr);
1238       }
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),
1245             _ => { }
1246         }
1247         print_expr(s, expr);
1248       }
1249       ast::ExprLit(lit) => print_literal(s, lit),
1250       ast::ExprCast(expr, ty) => {
1251         print_expr(s, expr);
1252         space(&mut s.s);
1253         word_space(s, "as");
1254         print_type(s, ty);
1255       }
1256       ast::ExprIf(test, blk, elseopt) => {
1257         print_if(s, test, blk, elseopt, false);
1258       }
1259       ast::ExprWhile(test, blk) => {
1260         head(s, "while");
1261         print_expr(s, test);
1262         space(&mut s.s);
1263         print_block(s, blk);
1264       }
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);
1269             word_space(s, ":");
1270         }
1271         head(s, "for");
1272         print_pat(s, pat);
1273         space(&mut s.s);
1274         word_space(s, "in");
1275         print_expr(s, iter);
1276         space(&mut s.s);
1277         print_block(s, blk);
1278       }
1279       ast::ExprLoop(blk, opt_ident) => {
1280         for ident in opt_ident.iter() {
1281             word(&mut s.s, "'");
1282             print_ident(s, *ident);
1283             word_space(s, ":");
1284         }
1285         head(s, "loop");
1286         space(&mut s.s);
1287         print_block(s, blk);
1288       }
1289       ast::ExprMatch(expr, ref arms) => {
1290         cbox(s, indent_unit);
1291         ibox(s, 4);
1292         word_nbsp(s, "match");
1293         print_expr(s, expr);
1294         space(&mut s.s);
1295         bopen(s);
1296         let len = arms.len();
1297         for (i, arm) in arms.iter().enumerate() {
1298             space(&mut s.s);
1299             cbox(s, indent_unit);
1300             ibox(s, 0u);
1301             let mut first = true;
1302             for p in arm.pats.iter() {
1303                 if first {
1304                     first = false;
1305                 } else { space(&mut s.s); word_space(s, "|"); }
1306                 print_pat(s, *p);
1307             }
1308             space(&mut s.s);
1309             match arm.guard {
1310               Some(e) => {
1311                 word_space(s, "if");
1312                 print_expr(s, e);
1313                 space(&mut s.s);
1314               }
1315               None => ()
1316             }
1317             word_space(s, "=>");
1318
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()
1325             {
1326                 match arm.body.expr {
1327                     Some(expr) => {
1328                         match expr.node {
1329                             ast::ExprBlock(blk) => {
1330                                 // the block will close the pattern's ibox
1331                                 print_block_unclosed_indent(
1332                                     s, blk, indent_unit);
1333                             }
1334                             _ => {
1335                                 end(s); // close the ibox for the pattern
1336                                 print_expr(s, expr);
1337                             }
1338                         }
1339                         if !expr_is_simple_block(expr)
1340                             && i < len - 1 {
1341                             word(&mut s.s, ",");
1342                         }
1343                         end(s); // close enclosing cbox
1344                     }
1345                     None => fail!()
1346                 }
1347             } else {
1348                 // the block will close the pattern's ibox
1349                 print_block_unclosed_indent(s, arm.body, indent_unit);
1350             }
1351         }
1352         bclose_(s, expr.span, indent_unit);
1353       }
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
1357         // we are inside.
1358         //
1359         // if !decl.inputs.is_empty() {
1360         print_fn_block_args(s, decl);
1361         space(&mut s.s);
1362         // }
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);
1369             }
1370             _ => {
1371                 // this is a bare expression
1372                 print_expr(s, body.expr.unwrap());
1373                 end(s); // need to close a box
1374             }
1375         }
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.
1379         ibox(s, 0);
1380       }
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
1384         // we are inside.
1385         //
1386         // if !decl.inputs.is_empty() {
1387         print_proc_args(s, decl);
1388         space(&mut s.s);
1389         // }
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);
1396             }
1397             _ => {
1398                 // this is a bare expression
1399                 print_expr(s, body.expr.unwrap());
1400                 end(s); // need to close a box
1401             }
1402         }
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.
1406         ibox(s, 0);
1407       }
1408       ast::ExprDoBody(body) => {
1409         print_expr(s, body);
1410       }
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 {
1415         ibox(s, 0u);
1416         print_block(s, blk);
1417       }
1418       ast::ExprAssign(lhs, rhs) => {
1419         print_expr(s, lhs);
1420         space(&mut s.s);
1421         word_space(s, "=");
1422         print_expr(s, rhs);
1423       }
1424       ast::ExprAssignOp(_, op, lhs, rhs) => {
1425         print_expr(s, lhs);
1426         space(&mut s.s);
1427         word(&mut s.s, ast_util::binop_to_str(op));
1428         word_space(s, "=");
1429         print_expr(s, rhs);
1430       }
1431       ast::ExprField(expr, id, ref tys) => {
1432         print_expr(s, expr);
1433         word(&mut s.s, ".");
1434         print_ident(s, id);
1435         if tys.len() > 0u {
1436             word(&mut s.s, "::<");
1437             commasep(s, Inconsistent, *tys, print_type_ref);
1438             word(&mut s.s, ">");
1439         }
1440       }
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, "]");
1446       }
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");
1451         space(&mut s.s);
1452         for ident in opt_ident.iter() {
1453             word(&mut s.s, "'");
1454             print_name(s, *ident);
1455             space(&mut s.s);
1456         }
1457       }
1458       ast::ExprAgain(opt_ident) => {
1459         word(&mut s.s, "continue");
1460         space(&mut s.s);
1461         for ident in opt_ident.iter() {
1462             word(&mut s.s, "'");
1463             print_name(s, *ident);
1464             space(&mut s.s)
1465         }
1466       }
1467       ast::ExprRet(result) => {
1468         word(&mut s.s, "return");
1469         match result {
1470           Some(expr) => { word(&mut s.s, " "); print_expr(s, expr); }
1471           _ => ()
1472         }
1473       }
1474       ast::ExprLogLevel => {
1475         word(&mut s.s, "__log_level");
1476         popen(s);
1477         pclose(s);
1478       }
1479       ast::ExprInlineAsm(ref a) => {
1480         if a.volatile {
1481             word(&mut s.s, "__volatile__ asm!");
1482         } else {
1483             word(&mut s.s, "asm!");
1484         }
1485         popen(s);
1486         print_string(s, a.asm, a.asm_str_style);
1487         word_space(s, ":");
1488         for &(co, o) in a.outputs.iter() {
1489             print_string(s, co, ast::CookedStr);
1490             popen(s);
1491             print_expr(s, o);
1492             pclose(s);
1493             word_space(s, ",");
1494         }
1495         word_space(s, ":");
1496         for &(co, o) in a.inputs.iter() {
1497             print_string(s, co, ast::CookedStr);
1498             popen(s);
1499             print_expr(s, o);
1500             pclose(s);
1501             word_space(s, ",");
1502         }
1503         word_space(s, ":");
1504         print_string(s, a.clobbers, ast::CookedStr);
1505         pclose(s);
1506       }
1507       ast::ExprMac(ref m) => print_mac(s, m),
1508       ast::ExprParen(e) => {
1509           popen(s);
1510           print_expr(s, e);
1511           pclose(s);
1512       }
1513     }
1514     {
1515         let ann_node = NodeExpr(s, expr);
1516         s.ann.post(ann_node);
1517     }
1518     end(s);
1519 }
1520
1521 pub fn print_local_decl(s: &mut State, loc: &ast::Local) {
1522     print_pat(s, loc.pat);
1523     match loc.ty.node {
1524         ast::TyInfer => {}
1525         _ => { word_space(s, ":"); print_type(s, loc.ty); }
1526     }
1527 }
1528
1529 pub fn print_decl(s: &mut State, decl: &ast::Decl) {
1530     maybe_print_comment(s, decl.span.lo);
1531     match decl.node {
1532       ast::DeclLocal(ref loc) => {
1533         space_if_not_bol(s);
1534         ibox(s, indent_unit);
1535         word_nbsp(s, "let");
1536
1537         fn print_local(s: &mut State, loc: &ast::Local) {
1538             ibox(s, indent_unit);
1539             print_local_decl(s, loc);
1540             end(s);
1541             match loc.init {
1542               Some(init) => {
1543                 nbsp(s);
1544                 word_space(s, "=");
1545                 print_expr(s, init);
1546               }
1547               _ => ()
1548             }
1549         }
1550
1551         print_local(s, *loc);
1552         end(s);
1553       }
1554       ast::DeclItem(item) => print_item(s, item)
1555     }
1556 }
1557
1558 pub fn print_ident(s: &mut State, ident: ast::Ident) {
1559     word(&mut s.s, ident_to_str(&ident));
1560 }
1561
1562 pub fn print_name(s: &mut State, name: ast::Name) {
1563     word(&mut s.s, interner_get(name));
1564 }
1565
1566 pub fn print_for_decl(s: &mut State, loc: &ast::Local, coll: &ast::Expr) {
1567     print_local_decl(s, loc);
1568     space(&mut s.s);
1569     word_space(s, "in");
1570     print_expr(s, coll);
1571 }
1572
1573 fn print_path_(s: &mut State,
1574                path: &ast::Path,
1575                colons_before_params: bool,
1576                opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1577     maybe_print_comment(s, path.span.lo);
1578     if path.global {
1579         word(&mut s.s, "::");
1580     }
1581
1582     let mut first = true;
1583     for (i, segment) in path.segments.iter().enumerate() {
1584         if first {
1585             first = false
1586         } else {
1587             word(&mut s.s, "::")
1588         }
1589
1590         print_ident(s, segment.identifier);
1591
1592         // If this is the last segment, print the bounds.
1593         if i == path.segments.len() - 1 {
1594             match *opt_bounds {
1595                 None => {}
1596                 Some(ref bounds) => print_bounds(s, bounds, true),
1597             }
1598         }
1599
1600         if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1601             if colons_before_params {
1602                 word(&mut s.s, "::")
1603             }
1604             word(&mut s.s, "<");
1605
1606             let mut comma = false;
1607             for lifetime in segment.lifetimes.iter() {
1608                 if comma {
1609                     word_space(s, ",")
1610                 }
1611                 print_lifetime(s, lifetime);
1612                 comma = true;
1613             }
1614
1615             if !segment.types.is_empty() {
1616                 if comma {
1617                     word_space(s, ",")
1618                 }
1619                 commasep(s,
1620                          Inconsistent,
1621                          segment.types.map_to_vec(|&t| t),
1622                          print_type_ref);
1623             }
1624
1625             word(&mut s.s, ">")
1626         }
1627     }
1628 }
1629
1630 pub fn print_path(s: &mut State, path: &ast::Path, colons_before_params: bool) {
1631     print_path_(s, path, colons_before_params, &None)
1632 }
1633
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)
1637 }
1638
1639 pub fn print_pat(s: &mut State, pat: &ast::Pat) {
1640     maybe_print_comment(s, pat.span.lo);
1641     {
1642         let ann_node = NodePat(s, pat);
1643         s.ann.pre(ann_node);
1644     }
1645     /* Pat isn't normalized, but the beauty of it
1646      is that it doesn't matter */
1647     match pat.node {
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);
1655               }
1656               ast::BindByValue(ast::MutImmutable) => {}
1657               ast::BindByValue(ast::MutMutable) => {
1658                   word_nbsp(s, "mut");
1659               }
1660           }
1661           print_path(s, path, true);
1662           match sub {
1663               Some(p) => {
1664                   word(&mut s.s, "@");
1665                   print_pat(s, p);
1666               }
1667               None => ()
1668           }
1669       }
1670       ast::PatEnum(ref path, ref args_) => {
1671         print_path(s, path, true);
1672         match *args_ {
1673           None => word(&mut s.s, "(..)"),
1674           Some(ref args) => {
1675             if !args.is_empty() {
1676               popen(s);
1677               commasep(s, Inconsistent, *args,
1678                        |s, &p| print_pat(s, p));
1679               pclose(s);
1680             } else { }
1681           }
1682         }
1683       }
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);
1690             word_space(s, ":");
1691             print_pat(s, f.pat);
1692             end(s);
1693         }
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),
1697                       get_span);
1698         if etc {
1699             if fields.len() != 0u { word_space(s, ","); }
1700             word(&mut s.s, "..");
1701         }
1702         word(&mut s.s, "}");
1703       }
1704       ast::PatTup(ref elts) => {
1705         popen(s);
1706         commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p));
1707         if elts.len() == 1 {
1708             word(&mut s.s, ",");
1709         }
1710         pclose(s);
1711       }
1712       ast::PatUniq(inner) => {
1713           word(&mut s.s, "~");
1714           print_pat(s, inner);
1715       }
1716       ast::PatRegion(inner) => {
1717           word(&mut s.s, "&");
1718           print_pat(s, inner);
1719       }
1720       ast::PatLit(e) => print_expr(s, e),
1721       ast::PatRange(begin, end) => {
1722         print_expr(s, begin);
1723         space(&mut s.s);
1724         word(&mut s.s, "..");
1725         print_expr(s, end);
1726       }
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, ","); }
1732             match *p {
1733                 ast::Pat { node: ast::PatWildMulti, .. } => {
1734                     // this case is handled by print_pat
1735                 }
1736                 _ => word(&mut s.s, ".."),
1737             }
1738             print_pat(s, p);
1739             if !after.is_empty() { word_space(s, ","); }
1740         }
1741         commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p));
1742         word(&mut s.s, "]");
1743       }
1744     }
1745     {
1746         let ann_node = NodePat(s, pat);
1747         s.ann.post(ann_node);
1748     }
1749 }
1750
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)
1753 }
1754
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");
1762         }
1763         ast::SelfUniq(m) => {
1764             print_mutability(s, m);
1765             word(&mut s.s, "~self");
1766         }
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");
1772         }
1773         ast::SelfBox => {
1774             word(&mut s.s, "@self");
1775         }
1776     }
1777     return true;
1778 }
1779
1780 pub fn print_fn(s: &mut State,
1781                 decl: &ast::FnDecl,
1782                 purity: Option<ast::Purity>,
1783                 abis: AbiSet,
1784                 name: ast::Ident,
1785                 generics: &ast::Generics,
1786                 opt_explicit_self: Option<ast::ExplicitSelf_>,
1787                 vis: ast::Visibility) {
1788     head(s, "");
1789     print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1790     nbsp(s);
1791     print_ident(s, name);
1792     print_generics(s, generics);
1793     print_fn_args_and_ret(s, decl, opt_explicit_self);
1794 }
1795
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);
1804     }
1805
1806     for arg in decl.inputs.iter() {
1807         if first { first = false; } else { word_space(s, ","); }
1808         print_arg(s, arg);
1809     }
1810
1811     end(s);
1812 }
1813
1814 pub fn print_fn_args_and_ret(s: &mut State, decl: &ast::FnDecl,
1815                              opt_explicit_self: Option<ast::ExplicitSelf_>) {
1816     popen(s);
1817     print_fn_args(s, decl, opt_explicit_self);
1818     if decl.variadic {
1819         word(&mut s.s, ", ...");
1820     }
1821     pclose(s);
1822
1823     maybe_print_comment(s, decl.output.span.lo);
1824     match decl.output.node {
1825         ast::TyNil => {}
1826         _ => {
1827             space_if_not_bol(s);
1828             word_space(s, "->");
1829             print_type(s, decl.output);
1830         }
1831     }
1832 }
1833
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, "|");
1838
1839     match decl.output.node {
1840         ast::TyInfer => {}
1841         _ => {
1842             space_if_not_bol(s);
1843             word_space(s, "->");
1844             print_type(s, decl.output);
1845         }
1846     }
1847
1848     maybe_print_comment(s, decl.output.span.lo);
1849 }
1850
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, ")");
1856
1857     match decl.output.node {
1858         ast::TyInfer => {}
1859         _ => {
1860             space_if_not_bol(s);
1861             word_space(s, "->");
1862             print_type(s, decl.output);
1863         }
1864     }
1865
1866     maybe_print_comment(s, decl.output.span.lo);
1867 }
1868
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() {
1875             nbsp(s);
1876             if first {
1877                 first = false;
1878             } else {
1879                 word_space(s, "+");
1880             }
1881
1882             match *bound {
1883                 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1884                 RegionTyParamBound => word(&mut s.s, "'static"),
1885             }
1886         }
1887     } else if print_colon_anyway {
1888         word(&mut s.s, ":");
1889     }
1890 }
1891
1892 pub fn print_lifetime(s: &mut State, lifetime: &ast::Lifetime) {
1893     word(&mut s.s, "'");
1894     print_ident(s, lifetime.ident);
1895 }
1896
1897 pub fn print_generics(s: &mut State, generics: &ast::Generics) {
1898     let total = generics.lifetimes.len() + generics.ty_params.len();
1899     if total > 0 {
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);
1905             } else {
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, &param.bounds, false);
1910             }
1911         }
1912
1913         let mut ints = ~[];
1914         for i in range(0u, total) {
1915             ints.push(i);
1916         }
1917
1918         commasep(s, Inconsistent, ints,
1919                  |s, &i| print_item(s, generics, i));
1920         word(&mut s.s, ">");
1921     }
1922 }
1923
1924 pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) {
1925     ibox(s, indent_unit);
1926     match item.node {
1927       ast::MetaWord(name) => word(&mut s.s, name),
1928       ast::MetaNameValue(name, value) => {
1929         word_space(s, name);
1930         word_space(s, "=");
1931         print_literal(s, &value);
1932       }
1933       ast::MetaList(name, ref items) => {
1934         word(&mut s.s, name);
1935         popen(s);
1936         commasep(s,
1937                  Consistent,
1938                  items.as_slice(),
1939                  |p, &i| print_meta_item(p, i));
1940         pclose(s);
1941       }
1942     }
1943     end(s);
1944 }
1945
1946 pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) {
1947     match vp.node {
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);
1952             space(&mut s.s);
1953             word_space(s, "=");
1954         }
1955         print_path(s, path, false);
1956       }
1957
1958       ast::ViewPathGlob(ref path, _) => {
1959         print_path(s, path, false);
1960         word(&mut s.s, "::*");
1961       }
1962
1963       ast::ViewPathList(ref path, ref idents, _) => {
1964         if path.segments.is_empty() {
1965             word(&mut s.s, "{");
1966         } else {
1967             print_path(s, path, false);
1968             word(&mut s.s, "::{");
1969         }
1970         commasep(s, Inconsistent, (*idents), |s, w| {
1971             print_ident(s, w.node.name);
1972         });
1973         word(&mut s.s, "}");
1974       }
1975     }
1976 }
1977
1978 pub fn print_view_paths(s: &mut State, vps: &[@ast::ViewPath]) {
1979     commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp));
1980 }
1981
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);
1987     match item.node {
1988         ast::ViewItemExternMod(id, ref optional_path, _) => {
1989             head(s, "extern mod");
1990             print_ident(s, id);
1991             for &(ref p, style) in optional_path.iter() {
1992                 space(&mut s.s);
1993                 word(&mut s.s, "=");
1994                 space(&mut s.s);
1995                 print_string(s, *p, style);
1996             }
1997         }
1998
1999         ast::ViewItemUse(ref vps) => {
2000             head(s, "use");
2001             print_view_paths(s, *vps);
2002         }
2003     }
2004     word(&mut s.s, ";");
2005     end(s); // end inner head-block
2006     end(s); // end outer head-block
2007 }
2008
2009 pub fn print_mutability(s: &mut State, mutbl: ast::Mutability) {
2010     match mutbl {
2011       ast::MutMutable => word_nbsp(s, "mut"),
2012       ast::MutImmutable => {/* nothing */ }
2013     }
2014 }
2015
2016 pub fn print_mt(s: &mut State, mt: &ast::MutTy) {
2017     print_mutability(s, mt.mutbl);
2018     print_type(s, mt.ty);
2019 }
2020
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),
2025         _ => {
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 => {
2031                     // Do nothing.
2032                 }
2033                 _ => {
2034                     print_pat(s, input.pat);
2035                     word(&mut s.s, ":");
2036                     space(&mut s.s);
2037                 }
2038             }
2039             print_type(s, input.ty);
2040         }
2041     }
2042     end(s);
2043 }
2044
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,
2051                    decl: &ast::FnDecl,
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);
2057
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);
2066         }
2067         print_purity(s, purity);
2068         print_onceness(s, onceness);
2069     } else {
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");
2076     }
2077
2078     match id { Some(id) => { word(&mut s.s, " "); print_ident(s, id); } _ => () }
2079
2080     if opt_sigil != Some(ast::BorrowedSigil) {
2081         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2082     }
2083
2084     match generics { Some(g) => print_generics(s, g), _ => () }
2085     zerobreak(&mut s.s);
2086
2087     if opt_sigil == Some(ast::BorrowedSigil) {
2088         word(&mut s.s, "|");
2089     } else {
2090         popen(s);
2091     }
2092
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);
2099     }
2100     for arg in decl.inputs.iter() {
2101         if first { first = false; } else { word_space(s, ","); }
2102         print_arg(s, arg);
2103     }
2104     end(s);
2105
2106     if opt_sigil == Some(ast::BorrowedSigil) {
2107         word(&mut s.s, "|");
2108
2109         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2110     } else {
2111         if decl.variadic {
2112             word(&mut s.s, ", ...");
2113         }
2114         pclose(s);
2115     }
2116
2117     maybe_print_comment(s, decl.output.span.lo);
2118
2119     match decl.output.node {
2120         ast::TyNil => {}
2121         _ => {
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); }
2127             end(s);
2128         }
2129     }
2130
2131     end(s);
2132 }
2133
2134 pub fn maybe_print_trailing_comment(s: &mut State, span: codemap::Span,
2135                                     next_pos: Option<BytePos>) {
2136     let cm;
2137     match s.cm { Some(ccm) => cm = ccm, _ => return }
2138     match next_comment(s) {
2139       Some(ref cmnt) => {
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;
2149         }
2150       }
2151       _ => ()
2152     }
2153 }
2154
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); }
2159     loop {
2160         match next_comment(s) {
2161           Some(ref cmnt) => {
2162             print_comment(s, cmnt);
2163             s.cur_cmnt_and_lit.cur_cmnt += 1u;
2164           }
2165           _ => break
2166         }
2167     }
2168 }
2169
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) {
2173       Some(ref ltrl) => {
2174         word(&mut s.s, (*ltrl).lit);
2175         return;
2176       }
2177       _ => ()
2178     }
2179     match lit.node {
2180       ast::LitStr(st, style) => print_string(s, st, style),
2181       ast::LitChar(ch) => {
2182           let mut res = ~"'";
2183           char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2184           res.push_char('\'');
2185           word(&mut s.s, res);
2186       }
2187       ast::LitInt(i, t) => {
2188         if i < 0_i64 {
2189             word(&mut s.s,
2190                  ~"-" + (-i as u64).to_str_radix(10u)
2191                  + ast_util::int_ty_to_str(t));
2192         } else {
2193             word(&mut s.s,
2194                  (i as u64).to_str_radix(10u)
2195                  + ast_util::int_ty_to_str(t));
2196         }
2197       }
2198       ast::LitUint(u, t) => {
2199         word(&mut s.s,
2200              u.to_str_radix(10u)
2201              + ast_util::uint_ty_to_str(t));
2202       }
2203       ast::LitIntUnsuffixed(i) => {
2204         if i < 0_i64 {
2205             word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u));
2206         } else {
2207             word(&mut s.s, (i as u64).to_str_radix(10u));
2208         }
2209       }
2210       ast::LitFloat(f, t) => {
2211         word(&mut s.s, f.to_owned() + ast_util::float_ty_to_str(t));
2212       }
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"); }
2217       }
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)),
2222                       |_| lit.span);
2223         word(&mut s.s, "]");
2224         end(s);
2225       }
2226     }
2227 }
2228
2229 pub fn lit_to_str(l: &ast::Lit) -> ~str {
2230     return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2231 }
2232
2233 pub fn next_lit(s: &mut State, pos: BytePos) -> Option<comments::Literal> {
2234     match s.literals {
2235       Some(ref lits) => {
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); }
2241         }
2242         return None;
2243       }
2244       _ => return None
2245     }
2246 }
2247
2248 pub fn maybe_print_comment(s: &mut State, pos: BytePos) {
2249     loop {
2250         match next_comment(s) {
2251           Some(ref cmnt) => {
2252             if (*cmnt).pos < pos {
2253                 print_comment(s, cmnt);
2254                 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2255             } else { break; }
2256           }
2257           _ => break
2258         }
2259     }
2260 }
2261
2262 pub fn print_comment(s: &mut State, cmnt: &comments::Comment) {
2263     match cmnt.style {
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);
2269         }
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
2274                 // whitespace
2275                 if !line.is_empty() { word(&mut s.s, *line); }
2276                 hardbreak(&mut s.s);
2277             }
2278         }
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);
2284             } else {
2285                 ibox(s, 0u);
2286                 for line in cmnt.lines.iter() {
2287                     if !line.is_empty() { word(&mut s.s, *line); }
2288                     hardbreak(&mut s.s);
2289                 }
2290                 end(s);
2291             }
2292         }
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,
2297                 _ => false
2298             };
2299             if is_semi || is_begin(s) || is_end(s) { hardbreak(&mut s.s); }
2300             hardbreak(&mut s.s);
2301         }
2302     }
2303 }
2304
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)
2310     };
2311     word(&mut s.s, st);
2312 }
2313
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
2316 // downcasts.
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());
2320     cast::forget(wr);
2321     result
2322 }
2323
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);
2327     f(&mut s, t);
2328     eof(&mut s.s);
2329     unsafe {
2330         get_mem_writer(&mut s.s.out)
2331     }
2332 }
2333
2334 pub fn next_comment(s: &mut State) -> Option<comments::Comment> {
2335     match s.comments {
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())
2339             } else {
2340                 None
2341             }
2342         }
2343         _ => None
2344     }
2345 }
2346
2347 pub fn print_opt_purity(s: &mut State, opt_purity: Option<ast::Purity>) {
2348     match opt_purity {
2349         Some(ast::ImpureFn) => { }
2350         Some(purity) => {
2351             word_nbsp(s, purity_to_str(purity));
2352         }
2353         None => {}
2354     }
2355 }
2356
2357 pub fn print_opt_abis_and_extern_if_nondefault(s: &mut State,
2358                                                opt_abis: Option<AbiSet>) {
2359     match opt_abis {
2360         Some(abis) if !abis.is_rust() => {
2361             word_nbsp(s, "extern");
2362             word_nbsp(s, abis.to_str());
2363         }
2364         Some(_) | None => {}
2365     };
2366 }
2367
2368 pub fn print_extern_opt_abis(s: &mut State, opt_abis: Option<AbiSet>) {
2369     match opt_abis {
2370         Some(abis) => {
2371             word_nbsp(s, "extern");
2372             word_nbsp(s, abis.to_str());
2373         }
2374         None => {}
2375     };
2376 }
2377
2378 pub fn print_opt_sigil(s: &mut State, opt_sigil: Option<ast::Sigil>) {
2379     match opt_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, "@"); }
2383         None => {}
2384     };
2385 }
2386
2387 pub fn print_fn_header_info(s: &mut State,
2388                             _opt_explicit_self: Option<ast::ExplicitSelf_>,
2389                             opt_purity: Option<ast::Purity>,
2390                             abis: AbiSet,
2391                             onceness: ast::Onceness,
2392                             opt_sigil: Option<ast::Sigil>,
2393                             vis: ast::Visibility) {
2394     word(&mut s.s, visibility_qualified(vis, ""));
2395
2396     if abis != AbiSet::Rust() {
2397         word_nbsp(s, "extern");
2398         word_nbsp(s, abis.to_str());
2399
2400         if opt_purity != Some(ast::ExternFn) {
2401             print_opt_purity(s, opt_purity);
2402         }
2403     } else {
2404         print_opt_purity(s, opt_purity);
2405     }
2406
2407     print_onceness(s, onceness);
2408     word(&mut s.s, "fn");
2409     print_opt_sigil(s, opt_sigil);
2410 }
2411
2412 pub fn purity_to_str(p: ast::Purity) -> &'static str {
2413     match p {
2414       ast::ImpureFn => "impure",
2415       ast::UnsafeFn => "unsafe",
2416       ast::ExternFn => "extern"
2417     }
2418 }
2419
2420 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2421     match o {
2422         ast::Once => "once",
2423         ast::Many => "many"
2424     }
2425 }
2426
2427 pub fn print_purity(s: &mut State, p: ast::Purity) {
2428     match p {
2429       ast::ImpureFn => (),
2430       _ => word_nbsp(s, purity_to_str(p))
2431     }
2432 }
2433
2434 pub fn print_onceness(s: &mut State, o: ast::Onceness) {
2435     match o {
2436         ast::Once => { word_nbsp(s, "once"); }
2437         ast::Many => {}
2438     }
2439 }
2440
2441 #[cfg(test)]
2442 mod test {
2443     use super::*;
2444
2445     use ast;
2446     use ast_util;
2447     use codemap;
2448     use parse::token;
2449
2450     #[test]
2451     fn test_fun_to_str() {
2452         let abba_ident = token::str_to_ident("abba");
2453
2454         let decl = ast::FnDecl {
2455             inputs: ~[],
2456             output: ast::P(ast::Ty {id: 0,
2457                                     node: ast::TyNil,
2458                                     span: codemap::DUMMY_SP}),
2459             cf: ast::Return,
2460             variadic: false
2461         };
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()),
2465                    &~"fn abba()");
2466     }
2467
2468     #[test]
2469     fn test_variant_to_str() {
2470         let ident = token::str_to_ident("principal_skinner");
2471
2472         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2473             name: ident,
2474             attrs: ~[],
2475             // making this up as I go.... ?
2476             kind: ast::TupleVariantKind(~[]),
2477             id: 0,
2478             disr_expr: None,
2479             vis: ast::Public,
2480         });
2481
2482         let varstr = variant_to_str(&var,token::get_ident_interner());
2483         assert_eq!(&varstr,&~"pub principal_skinner");
2484     }
2485 }