]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
960e28ca84f8fc81658e4cd485933c059ec5c685
[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::{ident_interner, 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::char;
31 use std::str;
32 use std::io;
33 use std::io::Decorator;
34 use std::io::mem::MemWriter;
35
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),
42 }
43
44 pub trait pp_ann {
45     fn pre(&self, _node: ann_node) {}
46     fn post(&self, _node: ann_node) {}
47 }
48
49 pub struct no_ann {
50     contents: (),
51 }
52
53 impl no_ann {
54     pub fn new() -> no_ann {
55         no_ann {
56             contents: (),
57         }
58     }
59 }
60
61 impl pp_ann for no_ann {}
62
63 pub struct CurrentCommentAndLiteral {
64     cur_cmnt: uint,
65     cur_lit: uint,
66 }
67
68 pub struct ps {
69     s: @mut pp::Printer,
70     cm: Option<@CodeMap>,
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],
76     ann: @pp_ann
77 }
78
79 pub fn ibox(s: @ps, u: uint) {
80     s.boxes.push(pp::inconsistent);
81     pp::ibox(s.s, u);
82 }
83
84 pub fn end(s: @ps) {
85     s.boxes.pop();
86     pp::end(s.s);
87 }
88
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);
91 }
92
93 pub fn rust_printer_annotated(writer: @mut io::Writer,
94                               intr: @ident_interner,
95                               ann: @pp_ann)
96                               -> @ps {
97     return @ps {
98         s: pp::mk_printer(writer, default_columns),
99         cm: None::<@CodeMap>,
100         intr: intr,
101         comments: None::<~[comments::cmnt]>,
102         literals: None::<~[comments::lit]>,
103         cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
104             cur_cmnt: 0,
105             cur_lit: 0
106         },
107         boxes: @mut ~[],
108         ann: ann
109     };
110 }
111
112 pub static indent_unit: uint = 4u;
113
114 pub static default_columns: uint = 78u;
115
116 // Requires you to pass an input filename and reader so that
117 // it can scan the input text for comments and literals to
118 // copy forward.
119 pub fn print_crate(cm: @CodeMap,
120                    intr: @ident_interner,
121                    span_diagnostic: @mut diagnostic::SpanHandler,
122                    crate: &ast::Crate,
123                    filename: @str,
124                    input: @mut io::Reader,
125                    out: @mut io::Writer,
126                    ann: @pp_ann,
127                    is_expanded: bool) {
128     let (cmnts, lits) = comments::gather_comments_and_literals(
129         span_diagnostic,
130         filename,
131         input
132     );
133     let s = @ps {
134         s: pp::mk_printer(out, default_columns),
135         cm: Some(cm),
136         intr: intr,
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 {
142             None
143         } else {
144             Some(lits)
145         },
146         cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
147             cur_cmnt: 0,
148             cur_lit: 0
149         },
150         boxes: @mut ~[],
151         ann: ann
152     };
153     print_crate_(s, crate);
154 }
155
156 pub fn print_crate_(s: @ps, crate: &ast::Crate) {
157     print_mod(s, &crate.module, crate.attrs);
158     print_remaining_comments(s);
159     eof(s.s);
160 }
161
162 pub fn ty_to_str(ty: &ast::Ty, intr: @ident_interner) -> ~str {
163     to_str(ty, print_type, intr)
164 }
165
166 pub fn pat_to_str(pat: &ast::Pat, intr: @ident_interner) -> ~str {
167     to_str(pat, print_pat, intr)
168 }
169
170 pub fn expr_to_str(e: &ast::Expr, intr: @ident_interner) -> ~str {
171     to_str(e, print_expr, intr)
172 }
173
174 pub fn lifetime_to_str(e: &ast::Lifetime, intr: @ident_interner) -> ~str {
175     to_str(e, print_lifetime, intr)
176 }
177
178 pub fn tt_to_str(tt: &ast::token_tree, intr: @ident_interner) -> ~str {
179     to_str(tt, print_tt, intr)
180 }
181
182 pub fn tts_to_str(tts: &[ast::token_tree], intr: @ident_interner) -> ~str {
183     to_str(&tts, print_tts, intr)
184 }
185
186 pub fn stmt_to_str(s: &ast::Stmt, intr: @ident_interner) -> ~str {
187     to_str(s, print_stmt, intr)
188 }
189
190 pub fn item_to_str(i: &ast::item, intr: @ident_interner) -> ~str {
191     to_str(i, print_item, intr)
192 }
193
194 pub fn generics_to_str(generics: &ast::Generics,
195                        intr: @ident_interner) -> ~str {
196     to_str(generics, print_generics, intr)
197 }
198
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)
201 }
202
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
212     eof(s.s);
213     str::from_utf8_owned(wr.inner_ref().to_owned())
214 }
215
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 {
222     ibox(s, 0u);
223     print_block(s, blk);
224     eof(s.s);
225     str::from_utf8_owned(wr.inner_ref().to_owned())
226 }
227
228 pub fn meta_item_to_str(mi: &ast::MetaItem, intr: @ident_interner) -> ~str {
229     to_str(mi, print_meta_item, intr)
230 }
231
232 pub fn attribute_to_str(attr: &ast::Attribute, intr: @ident_interner) -> ~str {
233     to_str(attr, print_attribute, intr)
234 }
235
236 pub fn variant_to_str(var: &ast::variant, intr: @ident_interner) -> ~str {
237     to_str(var, print_variant, intr)
238 }
239
240 pub fn cbox(s: @ps, u: uint) {
241     s.boxes.push(pp::consistent);
242     pp::cbox(s.s, u);
243 }
244
245 // "raw box"
246 pub fn rbox(s: @ps, u: uint, b: pp::breaks) {
247     s.boxes.push(b);
248     pp::rbox(s.s, u, b);
249 }
250
251 pub fn nbsp(s: @ps) { word(s.s, " "); }
252
253 pub fn word_nbsp(s: @ps, w: &str) { word(s.s, w); nbsp(s); }
254
255 pub fn word_space(s: @ps, w: &str) { word(s.s, w); space(s.s); }
256
257 pub fn popen(s: @ps) { word(s.s, "("); }
258
259 pub fn pclose(s: @ps) { word(s.s, ")"); }
260
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
267     if !w.is_empty() {
268         word_nbsp(s, w);
269     }
270 }
271
272 pub fn bopen(s: @ps) {
273     word(s.s, "{");
274     end(s); // close the head-box
275 }
276
277 pub fn bclose_(s: @ps, span: codemap::Span, indented: uint) {
278     bclose_maybe_open(s, span, indented, true);
279 }
280 pub fn bclose_maybe_open (s: @ps, span: codemap::Span, indented: uint,
281                           close_box: bool) {
282     maybe_print_comment(s, span.hi);
283     break_offset_if_not_bol(s, 1u, -(indented as int));
284     word(s.s, "}");
285     if close_box {
286         end(s); // close the outer-box
287     }
288 }
289 pub fn bclose(s: @ps, span: codemap::Span) { bclose_(s, span, indent_unit); }
290
291 pub fn is_begin(s: @ps) -> bool {
292     match s.s.last_token() { pp::BEGIN(_) => true, _ => false }
293 }
294
295 pub fn is_end(s: @ps) -> bool {
296     match s.s.last_token() { pp::END => true, _ => false }
297 }
298
299 pub fn is_bol(s: @ps) -> bool {
300     return s.s.last_token().is_eof() || s.s.last_token().is_hardbreak_tok();
301 }
302
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;
308 }
309
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) {
313     if !is_bol(s) {
314         break_offset(s.s, n, off);
315     } else {
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));
321         }
322     }
323 }
324
325 // Synthesizes a comment that was not textually present in the original source
326 // file.
327 pub fn synth_comment(s: @ps, text: ~str) {
328     word(s.s, "/*");
329     space(s.s);
330     word(s.s, text);
331     space(s.s);
332     word(s.s, "*/");
333 }
334
335 pub fn commasep<T>(s: @ps, b: breaks, elts: &[T], op: |@ps, &T|) {
336     rbox(s, 0u, b);
337     let mut first = true;
338     for elt in elts.iter() {
339         if first { first = false; } else { word_space(s, ","); }
340         op(s, elt);
341     }
342     end(s);
343 }
344
345
346 pub fn commasep_cmnt<T>(
347                      s: @ps,
348                      b: breaks,
349                      elts: &[T],
350                      op: |@ps, &T|,
351                      get_span: |&T| -> codemap::Span) {
352     rbox(s, 0u, b);
353     let len = elts.len();
354     let mut i = 0u;
355     for elt in elts.iter() {
356         maybe_print_comment(s, get_span(elt).hi);
357         op(s, elt);
358         i += 1u;
359         if i < len {
360             word(s.s, ",");
361             maybe_print_trailing_comment(s, get_span(elt),
362                                          Some(get_span(&elts[i]).hi));
363             space_if_not_bol(s);
364         }
365     }
366     end(s);
367 }
368
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);
371 }
372
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);
377     }
378     for item in _mod.items.iter() { print_item(s, *item); }
379 }
380
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);
386     }
387     for item in nmod.items.iter() { print_foreign_item(s, *item); }
388 }
389
390 pub fn print_opt_lifetime(s: @ps, lifetime: &Option<ast::Lifetime>) {
391     for l in lifetime.iter() {
392         print_lifetime(s, l);
393         nbsp(s);
394     }
395 }
396
397 pub fn print_type(s: @ps, ty: &ast::Ty) {
398     maybe_print_comment(s, ty.span.lo);
399     ibox(s, 0u);
400     match ty.node {
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); }
405       ast::ty_vec(ty) => {
406         word(s.s, "[");
407         print_type(s, ty);
408         word(s.s, "]");
409       }
410       ast::ty_ptr(ref mt) => { word(s.s, "*"); print_mt(s, mt); }
411       ast::ty_rptr(ref lifetime, ref mt) => {
412           word(s.s, "&");
413           print_opt_lifetime(s, lifetime);
414           print_mt(s, mt);
415       }
416       ast::ty_tup(ref elts) => {
417         popen(s);
418         commasep(s, inconsistent, *elts, print_type_ref);
419         if elts.len() == 1 {
420             word(s.s, ",");
421         }
422         pclose(s);
423       }
424       ast::ty_bare_fn(f) => {
425           let generics = ast::Generics {
426             lifetimes: f.lifetimes.clone(),
427             ty_params: opt_vec::Empty
428           };
429           print_ty_fn(s, Some(f.abis), None, &None,
430                       f.purity, ast::Many, f.decl, None, &None,
431                       Some(&generics), None);
432       }
433       ast::ty_closure(f) => {
434           let generics = ast::Generics {
435             lifetimes: f.lifetimes.clone(),
436             ty_params: opt_vec::Empty
437           };
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);
441       }
442       ast::ty_path(ref path, ref bounds, _) => print_bounded_path(s, path, bounds),
443       ast::ty_fixed_length_vec(ty, v) => {
444         word(s.s, "[");
445         print_type(s, ty);
446         word(s.s, ", ..");
447         print_expr(s, v);
448         word(s.s, "]");
449       }
450       ast::ty_typeof(e) => {
451           word(s.s, "typeof(");
452           print_expr(s, e);
453           word(s.s, ")");
454       }
455       ast::ty_infer => {
456           fail!("print_type shouldn't see a ty_infer");
457       }
458
459     }
460     end(s);
461 }
462
463 pub fn print_type_ref(s: @ps, ty: &P<ast::Ty>) {
464     print_type(s, *ty);
465 }
466
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);
471     match item.node {
472       ast::foreign_item_fn(decl, ref generics) => {
473         print_fn(s, decl, None, AbiSet::Rust(), item.ident, generics, None,
474                  item.vis);
475         end(s); // end head-ibox
476         word(s.s, ";");
477         end(s); // end the outer fn box
478       }
479       ast::foreign_item_static(t, m) => {
480         head(s, visibility_qualified(item.vis, "static"));
481         if m {
482             word_space(s, "mut");
483         }
484         print_ident(s, item.ident);
485         word_space(s, ":");
486         print_type(s, t);
487         word(s.s, ";");
488         end(s); // end the head-ibox
489         end(s); // end the outer cbox
490       }
491     }
492 }
493
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);
499     s.ann.pre(ann_node);
500     match item.node {
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");
505         }
506         print_ident(s, item.ident);
507         word_space(s, ":");
508         print_type(s, ty);
509         space(s.s);
510         end(s); // end the head-ibox
511
512         word_space(s, "=");
513         print_expr(s, expr);
514         word(s.s, ";");
515         end(s); // end the outer cbox
516
517       }
518       ast::item_fn(decl, purity, abi, ref typarams, body) => {
519         print_fn(
520             s,
521             decl,
522             Some(purity),
523             abi,
524             item.ident,
525             typarams,
526             None,
527             item.vis
528         );
529         word(s.s, " ");
530         print_block_with_attrs(s, body, item.attrs);
531       }
532       ast::item_mod(ref _mod) => {
533         head(s, visibility_qualified(item.vis, "mod"));
534         print_ident(s, item.ident);
535         nbsp(s);
536         bopen(s);
537         print_mod(s, _mod, item.attrs);
538         bclose(s, item.span);
539       }
540       ast::item_foreign_mod(ref nmod) => {
541         head(s, "extern");
542         word_nbsp(s, nmod.abis.to_str());
543         bopen(s);
544         print_foreign_mod(s, nmod, item.attrs);
545         bclose(s, item.span);
546       }
547       ast::item_ty(ty, ref params) => {
548         ibox(s, indent_unit);
549         ibox(s, 0u);
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
554
555         space(s.s);
556         word_space(s, "=");
557         print_type(s, ty);
558         word(s.s, ";");
559         end(s); // end the outer ibox
560       }
561       ast::item_enum(ref enum_definition, ref params) => {
562         print_enum_def(
563             s,
564             enum_definition,
565             params,
566             item.ident,
567             item.span,
568             item.vis
569         );
570       }
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);
574       }
575
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);
580             space(s.s);
581         }
582
583         match opt_trait {
584             &Some(ref t) => {
585                 print_trait_ref(s, t);
586                 space(s.s);
587                 word_space(s, "for");
588             }
589             &None => ()
590         };
591
592         print_type(s, ty);
593
594         space(s.s);
595         bopen(s);
596         print_inner_attributes(s, item.attrs);
597         for meth in methods.iter() {
598            print_method(s, *meth);
599         }
600         bclose(s, item.span);
601       }
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 {
607             word(s.s, ":");
608             for (i, trait_) in traits.iter().enumerate() {
609                 nbsp(s);
610                 if i != 0 {
611                     word_space(s, "+");
612                 }
613                 print_path(s, &trait_.path, false);
614             }
615         }
616         word(s.s, " ");
617         bopen(s);
618         for meth in methods.iter() {
619             print_trait_method(s, meth);
620         }
621         bclose(s, item.span);
622       }
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, _),
625                                    ..}) => {
626         print_visibility(s, item.vis);
627         print_path(s, pth, false);
628         word(s.s, "! ");
629         print_ident(s, item.ident);
630         cbox(s, indent_unit);
631         popen(s);
632         print_tts(s, &(tts.as_slice()));
633         pclose(s);
634         end(s);
635       }
636     }
637     s.ann.post(ann_node);
638 }
639
640 fn print_trait_ref(s: @ps, t: &ast::trait_ref) {
641     print_path(s, &t.path, false);
642 }
643
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);
650     space(s.s);
651     print_variants(s, enum_definition.variants, span);
652 }
653
654 pub fn print_variants(s: @ps,
655                       variants: &[P<ast::variant>],
656                       span: codemap::Span) {
657     bopen(s);
658     for &v in variants.iter() {
659         space_if_not_bol(s);
660         maybe_print_comment(s, v.span.lo);
661         print_outer_attributes(s, v.node.attrs);
662         ibox(s, indent_unit);
663         print_variant(s, v);
664         word(s.s, ",");
665         end(s);
666         maybe_print_trailing_comment(s, v.span, None);
667     }
668     bclose(s, span);
669 }
670
671 pub fn visibility_to_str(vis: ast::visibility) -> ~str {
672     match vis {
673         ast::private => ~"priv",
674         ast::public => ~"pub",
675         ast::inherited => ~""
676     }
677 }
678
679 pub fn visibility_qualified(vis: ast::visibility, s: &str) -> ~str {
680     match vis {
681         ast::private | ast::public => visibility_to_str(vis) + " " + s,
682         ast::inherited => s.to_owned()
683     }
684 }
685
686 pub fn print_visibility(s: @ps, vis: ast::visibility) {
687     match vis {
688         ast::private | ast::public =>
689         word_nbsp(s, visibility_to_str(vis)),
690         ast::inherited => ()
691     }
692 }
693
694 pub fn print_struct(s: @ps,
695                     struct_def: &ast::struct_def,
696                     generics: &ast::Generics,
697                     ident: ast::Ident,
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() {
703             popen(s);
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);
710                     }
711                 }
712             });
713             pclose(s);
714         }
715         word(s.s, ";");
716         end(s);
717         end(s); // close the outer-box
718     } else {
719         nbsp(s);
720         bopen(s);
721         hardbreak_if_not_bol(s);
722
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);
732                     word_nbsp(s, ":");
733                     print_type(s, field.node.ty);
734                     word(s.s, ",");
735                 }
736             }
737         }
738
739         bclose(s, span);
740     }
741 }
742
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) {
751     match *tt {
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));
755       }
756       ast::tt_seq(_, ref tts, ref sep, zerok) => {
757         word(s.s, "$(");
758         for tt_elt in (*tts).iter() { print_tt(s, tt_elt); }
759         word(s.s, ")");
760         match (*sep) {
761           Some(ref tk) => word(s.s, parse::token::to_str(s.intr, tk)),
762           None => ()
763         }
764         word(s.s, if zerok { "*" } else { "+" });
765       }
766       ast::tt_nonterminal(_, name) => {
767         word(s.s, "$");
768         print_ident(s, name);
769       }
770     }
771 }
772
773 pub fn print_tts(s: @ps, tts: & &[ast::token_tree]) {
774     ibox(s, 0);
775     for (i, tt) in tts.iter().enumerate() {
776         if i != 0 {
777             space(s.s);
778         }
779         print_tt(s, tt);
780     }
781     end(s);
782 }
783
784 pub fn print_variant(s: @ps, v: &ast::variant) {
785     print_visibility(s, v.node.vis);
786     match v.node.kind {
787         ast::tuple_variant_kind(ref args) => {
788             print_ident(s, v.node.name);
789             if !args.is_empty() {
790                 popen(s);
791                 fn print_variant_arg(s: @ps, arg: &ast::variant_arg) {
792                     print_type(s, arg.ty);
793                 }
794                 commasep(s, consistent, *args, print_variant_arg);
795                 pclose(s);
796             }
797         }
798         ast::struct_variant_kind(struct_def) => {
799             head(s, "");
800             let generics = ast_util::empty_generics();
801             print_struct(s, struct_def, &generics, v.node.name, v.span);
802         }
803     }
804     match v.node.disr_expr {
805       Some(d) => {
806         space(s.s);
807         word_space(s, "=");
808         print_expr(s, d);
809       }
810       _ => ()
811     }
812 }
813
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);
818     print_ty_fn(s,
819                 None,
820                 None,
821                 &None,
822                 m.purity,
823                 ast::Many,
824                 m.decl,
825                 Some(m.ident),
826                 &None,
827                 Some(&m.generics),
828                 Some(m.explicit_self.node));
829     word(s.s, ";");
830 }
831
832 pub fn print_trait_method(s: @ps, m: &ast::trait_method) {
833     match *m {
834         required(ref ty_m) => print_ty_method(s, ty_m),
835         provided(m) => print_method(s, m)
836     }
837 }
838
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),
845              meth.vis);
846     word(s.s, " ");
847     print_block_with_attrs(s, meth.body, meth.attrs);
848 }
849
850 pub fn print_outer_attributes(s: @ps, attrs: &[ast::Attribute]) {
851     let mut count = 0;
852     for attr in attrs.iter() {
853         match attr.node.style {
854           ast::AttrOuter => { print_attribute(s, attr); count += 1; }
855           _ => {/* fallthrough */ }
856         }
857     }
858     if count > 0 { hardbreak_if_not_bol(s); }
859 }
860
861 pub fn print_inner_attributes(s: @ps, attrs: &[ast::Attribute]) {
862     let mut count = 0;
863     for attr in attrs.iter() {
864         match attr.node.style {
865           ast::AttrInner => {
866             print_attribute(s, attr);
867             if !attr.node.is_sugared_doc {
868                 word(s.s, ";");
869             }
870             count += 1;
871           }
872           _ => {/* fallthrough */ }
873         }
874     }
875     if count > 0 { hardbreak_if_not_bol(s); }
876 }
877
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();
883         word(s.s, comment);
884     } else {
885         word(s.s, "#[");
886         print_meta_item(s, attr.meta());
887         word(s.s, "]");
888     }
889 }
890
891
892 pub fn print_stmt(s: @ps, st: &ast::Stmt) {
893     maybe_print_comment(s, st.span.lo);
894     match st.node {
895       ast::StmtDecl(decl, _) => {
896         print_decl(s, decl);
897       }
898       ast::StmtExpr(expr, _) => {
899         space_if_not_bol(s);
900         print_expr(s, expr);
901       }
902       ast::StmtSemi(expr, _) => {
903         space_if_not_bol(s);
904         print_expr(s, expr);
905         word(s.s, ";");
906       }
907       ast::StmtMac(ref mac, semi) => {
908         space_if_not_bol(s);
909         print_mac(s, mac);
910         if semi { word(s.s, ";"); }
911       }
912     }
913     if parse::classify::stmt_ends_with_semi(st) { word(s.s, ";"); }
914     maybe_print_trailing_comment(s, st.span, None);
915 }
916
917 pub fn print_block(s: @ps, blk: &ast::Block) {
918     print_possibly_embedded_block(s, blk, block_normal, indent_unit);
919 }
920
921 pub fn print_block_unclosed(s: @ps, blk: &ast::Block) {
922     print_possibly_embedded_block_(s, blk, block_normal, indent_unit, &[],
923                                  false);
924 }
925
926 pub fn print_block_unclosed_indent(s: @ps, blk: &ast::Block, indented: uint) {
927     print_possibly_embedded_block_(s, blk, block_normal, indented, &[],
928                                    false);
929 }
930
931 pub fn print_block_with_attrs(s: @ps,
932                               blk: &ast::Block,
933                               attrs: &[ast::Attribute]) {
934     print_possibly_embedded_block_(s, blk, block_normal, indent_unit, attrs,
935                                   true);
936 }
937
938 pub enum embed_type { block_block_fn, block_normal, }
939
940 pub fn print_possibly_embedded_block(s: @ps,
941                                      blk: &ast::Block,
942                                      embedded: embed_type,
943                                      indented: uint) {
944     print_possibly_embedded_block_(
945         s, blk, embedded, indented, &[], true);
946 }
947
948 pub fn print_possibly_embedded_block_(s: @ps,
949                                       blk: &ast::Block,
950                                       embedded: embed_type,
951                                       indented: uint,
952                                       attrs: &[ast::Attribute],
953                                       close_box: bool) {
954     match blk.rules {
955       ast::UnsafeBlock(..) => word_space(s, "unsafe"),
956       ast::DefaultBlock => ()
957     }
958     maybe_print_comment(s, blk.span.lo);
959     let ann_node = node_block(s, blk);
960     s.ann.pre(ann_node);
961     match embedded {
962       block_block_fn => end(s),
963       block_normal => bopen(s)
964     }
965
966     print_inner_attributes(s, attrs);
967
968     for vi in blk.view_items.iter() { print_view_item(s, vi); }
969     for st in blk.stmts.iter() {
970         print_stmt(s, *st);
971     }
972     match blk.expr {
973       Some(expr) => {
974         space_if_not_bol(s);
975         print_expr(s, expr);
976         maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
977       }
978       _ => ()
979     }
980     bclose_maybe_open(s, blk.span, indented, close_box);
981     s.ann.post(ann_node);
982 }
983
984 pub fn print_if(s: @ps, test: &ast::Expr, blk: &ast::Block,
985                 elseopt: Option<@ast::Expr>, chk: bool) {
986     head(s, "if");
987     if chk { word_nbsp(s, "check"); }
988     print_expr(s, test);
989     space(s.s);
990     print_block(s, blk);
991     fn do_else(s: @ps, els: Option<@ast::Expr>) {
992         match els {
993           Some(_else) => {
994             match _else.node {
995               // "another else-if"
996               ast::ExprIf(i, t, e) => {
997                 cbox(s, indent_unit - 1u);
998                 ibox(s, 0u);
999                 word(s.s, " else if ");
1000                 print_expr(s, i);
1001                 space(s.s);
1002                 print_block(s, t);
1003                 do_else(s, e);
1004               }
1005               // "final else"
1006               ast::ExprBlock(b) => {
1007                 cbox(s, indent_unit - 1u);
1008                 ibox(s, 0u);
1009                 word(s.s, " else ");
1010                 print_block(s, b);
1011               }
1012               // BLEAH, constraints would be great here
1013               _ => {
1014                   fail!("print_if saw if with weird alternative");
1015               }
1016             }
1017           }
1018           _ => {/* fall through */ }
1019         }
1020     }
1021     do_else(s, elseopt);
1022 }
1023
1024 pub fn print_mac(s: @ps, m: &ast::mac) {
1025     match m.node {
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);
1029         word(s.s, "!");
1030         popen(s);
1031         print_tts(s, &tts.as_slice());
1032         pclose(s);
1033       }
1034     }
1035 }
1036
1037 pub fn print_vstore(s: @ps, t: ast::Vstore) {
1038     match t {
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) => {
1044             word(s.s, "&");
1045             print_opt_lifetime(s, r);
1046         }
1047     }
1048 }
1049
1050 pub fn print_expr_vstore(s: @ps, t: ast::ExprVstore) {
1051     match t {
1052       ast::ExprVstoreUniq => word(s.s, "~"),
1053       ast::ExprVstoreBox => word(s.s, "@"),
1054       ast::ExprVstoreMutBox => {
1055         word(s.s, "@");
1056         word(s.s, "mut");
1057       }
1058       ast::ExprVstoreSlice => word(s.s, "&"),
1059       ast::ExprVstoreMutSlice => {
1060         word(s.s, "&");
1061         word(s.s, "mut");
1062       }
1063     }
1064 }
1065
1066 pub fn print_call_pre(s: @ps,
1067                       sugar: ast::CallSugar,
1068                       base_args: &mut ~[@ast::Expr])
1069                    -> Option<@ast::Expr> {
1070     match sugar {
1071         ast::DoSugar => {
1072             head(s, "do");
1073             Some(base_args.pop())
1074         }
1075         ast::ForSugar => {
1076             head(s, "for");
1077             Some(base_args.pop())
1078         }
1079         ast::NoSugar => None
1080     }
1081 }
1082
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() {
1088         popen(s);
1089         commasep_exprs(s, inconsistent, *base_args);
1090         pclose(s);
1091     }
1092     if sugar != ast::NoSugar {
1093         nbsp(s);
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.
1099             print_expr(s, e);
1100             end(s); // close outer box, as closures don't
1101           }
1102           _ => {
1103             // not sure if this can happen.
1104             print_expr(s, blk.unwrap());
1105           }
1106         }
1107     }
1108 }
1109
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);
1114         word_space(s, ":");
1115         print_expr(s, field.expr);
1116         end(s);
1117     }
1118     fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1119
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);
1124     match expr.node {
1125         ast::ExprVstore(e, v) => {
1126             print_expr_vstore(s, v);
1127             print_expr(s, e);
1128         },
1129       ast::ExprVec(ref exprs, mutbl) => {
1130         ibox(s, indent_unit);
1131         word(s.s, "[");
1132         if mutbl == ast::MutMutable {
1133             word(s.s, "mut");
1134             if exprs.len() > 0u { nbsp(s); }
1135         }
1136         commasep_exprs(s, inconsistent, *exprs);
1137         word(s.s, "]");
1138         end(s);
1139       }
1140
1141       ast::ExprRepeat(element, count, mutbl) => {
1142         ibox(s, indent_unit);
1143         word(s.s, "[");
1144         if mutbl == ast::MutMutable {
1145             word(s.s, "mut");
1146             nbsp(s);
1147         }
1148         print_expr(s, element);
1149         word(s.s, ",");
1150         word(s.s, "..");
1151         print_expr(s, count);
1152         word(s.s, "]");
1153         end(s);
1154       }
1155
1156       ast::ExprStruct(ref path, ref fields, wth) => {
1157         print_path(s, path, true);
1158         word(s.s, "{");
1159         commasep_cmnt(s, consistent, (*fields), print_field, get_span);
1160         match wth {
1161             Some(expr) => {
1162                 ibox(s, indent_unit);
1163                 word(s.s, ",");
1164                 space(s.s);
1165                 word(s.s, "..");
1166                 print_expr(s, expr);
1167                 end(s);
1168             }
1169             _ => (word(s.s, ","))
1170         }
1171         word(s.s, "}");
1172       }
1173       ast::ExprTup(ref exprs) => {
1174         popen(s);
1175         commasep_exprs(s, inconsistent, *exprs);
1176         if exprs.len() == 1 {
1177             word(s.s, ",");
1178         }
1179         pclose(s);
1180       }
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);
1186       }
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);
1191         word(s.s, ".");
1192         print_ident(s, ident);
1193         if tys.len() > 0u {
1194             word(s.s, "::<");
1195             commasep(s, inconsistent, *tys, print_type_ref);
1196             word(s.s, ">");
1197         }
1198         print_call_post(s, sugar, &blk, &mut base_args);
1199       }
1200       ast::ExprBinary(_, op, lhs, rhs) => {
1201         print_expr(s, lhs);
1202         space(s.s);
1203         word_space(s, ast_util::binop_to_str(op));
1204         print_expr(s, rhs);
1205       }
1206       ast::ExprUnary(_, op, expr) => {
1207         word(s.s, ast_util::unop_to_str(op));
1208         print_expr(s, expr);
1209       }
1210       ast::ExprAddrOf(m, expr) => {
1211         word(s.s, "&");
1212         print_mutability(s, m);
1213         // Avoid `& &e` => `&&e`.
1214         match (m, &expr.node) {
1215             (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(s.s),
1216             _ => { }
1217         }
1218         print_expr(s, expr);
1219       }
1220       ast::ExprLit(lit) => print_literal(s, lit),
1221       ast::ExprCast(expr, ty) => {
1222         print_expr(s, expr);
1223         space(s.s);
1224         word_space(s, "as");
1225         print_type(s, ty);
1226       }
1227       ast::ExprIf(test, blk, elseopt) => {
1228         print_if(s, test, blk, elseopt, false);
1229       }
1230       ast::ExprWhile(test, blk) => {
1231         head(s, "while");
1232         print_expr(s, test);
1233         space(s.s);
1234         print_block(s, blk);
1235       }
1236       ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1237         for ident in opt_ident.iter() {
1238             word(s.s, "'");
1239             print_ident(s, *ident);
1240             word_space(s, ":");
1241         }
1242         head(s, "for");
1243         print_pat(s, pat);
1244         space(s.s);
1245         word_space(s, "in");
1246         print_expr(s, iter);
1247         space(s.s);
1248         print_block(s, blk);
1249       }
1250       ast::ExprLoop(blk, opt_ident) => {
1251         for ident in opt_ident.iter() {
1252             word(s.s, "'");
1253             print_ident(s, *ident);
1254             word_space(s, ":");
1255         }
1256         head(s, "loop");
1257         space(s.s);
1258         print_block(s, blk);
1259       }
1260       ast::ExprMatch(expr, ref arms) => {
1261         cbox(s, indent_unit);
1262         ibox(s, 4);
1263         word_nbsp(s, "match");
1264         print_expr(s, expr);
1265         space(s.s);
1266         bopen(s);
1267         let len = arms.len();
1268         for (i, arm) in arms.iter().enumerate() {
1269             space(s.s);
1270             cbox(s, indent_unit);
1271             ibox(s, 0u);
1272             let mut first = true;
1273             for p in arm.pats.iter() {
1274                 if first {
1275                     first = false;
1276                 } else { space(s.s); word_space(s, "|"); }
1277                 print_pat(s, *p);
1278             }
1279             space(s.s);
1280             match arm.guard {
1281               Some(e) => {
1282                 word_space(s, "if");
1283                 print_expr(s, e);
1284                 space(s.s);
1285               }
1286               None => ()
1287             }
1288             word_space(s, "=>");
1289
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()
1296             {
1297                 match arm.body.expr {
1298                     Some(expr) => {
1299                         match expr.node {
1300                             ast::ExprBlock(blk) => {
1301                                 // the block will close the pattern's ibox
1302                                 print_block_unclosed_indent(
1303                                     s, blk, indent_unit);
1304                             }
1305                             _ => {
1306                                 end(s); // close the ibox for the pattern
1307                                 print_expr(s, expr);
1308                             }
1309                         }
1310                         if !expr_is_simple_block(expr)
1311                             && i < len - 1 {
1312                             word(s.s, ",");
1313                         }
1314                         end(s); // close enclosing cbox
1315                     }
1316                     None => fail!()
1317                 }
1318             } else {
1319                 // the block will close the pattern's ibox
1320                 print_block_unclosed_indent(s, arm.body, indent_unit);
1321             }
1322         }
1323         bclose_(s, expr.span, indent_unit);
1324       }
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
1328         // we are inside.
1329         //
1330         // if !decl.inputs.is_empty() {
1331         print_fn_block_args(s, decl);
1332         space(s.s);
1333         // }
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);
1340             }
1341             _ => {
1342                 // this is a bare expression
1343                 print_expr(s, body.expr.unwrap());
1344                 end(s); // need to close a box
1345             }
1346         }
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.
1350         ibox(s, 0);
1351       }
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
1355         // we are inside.
1356         //
1357         // if !decl.inputs.is_empty() {
1358         print_proc_args(s, decl);
1359         space(s.s);
1360         // }
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);
1367             }
1368             _ => {
1369                 // this is a bare expression
1370                 print_expr(s, body.expr.unwrap());
1371                 end(s); // need to close a box
1372             }
1373         }
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.
1377         ibox(s, 0);
1378       }
1379       ast::ExprDoBody(body) => {
1380         print_expr(s, body);
1381       }
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 {
1386         ibox(s, 0u);
1387         print_block(s, blk);
1388       }
1389       ast::ExprAssign(lhs, rhs) => {
1390         print_expr(s, lhs);
1391         space(s.s);
1392         word_space(s, "=");
1393         print_expr(s, rhs);
1394       }
1395       ast::ExprAssignOp(_, op, lhs, rhs) => {
1396         print_expr(s, lhs);
1397         space(s.s);
1398         word(s.s, ast_util::binop_to_str(op));
1399         word_space(s, "=");
1400         print_expr(s, rhs);
1401       }
1402       ast::ExprField(expr, id, ref tys) => {
1403         print_expr(s, expr);
1404         word(s.s, ".");
1405         print_ident(s, id);
1406         if tys.len() > 0u {
1407             word(s.s, "::<");
1408             commasep(s, inconsistent, *tys, print_type_ref);
1409             word(s.s, ">");
1410         }
1411       }
1412       ast::ExprIndex(_, expr, index) => {
1413         print_expr(s, expr);
1414         word(s.s, "[");
1415         print_expr(s, index);
1416         word(s.s, "]");
1417       }
1418       ast::ExprPath(ref path) => print_path(s, path, true),
1419       ast::ExprSelf => word(s.s, "self"),
1420       ast::ExprBreak(opt_ident) => {
1421         word(s.s, "break");
1422         space(s.s);
1423         for ident in opt_ident.iter() {
1424             word(s.s, "'");
1425             print_name(s, *ident);
1426             space(s.s);
1427         }
1428       }
1429       ast::ExprAgain(opt_ident) => {
1430         word(s.s, "continue");
1431         space(s.s);
1432         for ident in opt_ident.iter() {
1433             word(s.s, "'");
1434             print_name(s, *ident);
1435             space(s.s)
1436         }
1437       }
1438       ast::ExprRet(result) => {
1439         word(s.s, "return");
1440         match result {
1441           Some(expr) => { word(s.s, " "); print_expr(s, expr); }
1442           _ => ()
1443         }
1444       }
1445       ast::ExprLogLevel => {
1446         word(s.s, "__log_level");
1447         popen(s);
1448         pclose(s);
1449       }
1450       ast::ExprInlineAsm(ref a) => {
1451         if a.volatile {
1452             word(s.s, "__volatile__ asm!");
1453         } else {
1454             word(s.s, "asm!");
1455         }
1456         popen(s);
1457         print_string(s, a.asm, a.asm_str_style);
1458         word_space(s, ":");
1459         for &(co, o) in a.outputs.iter() {
1460             print_string(s, co, ast::CookedStr);
1461             popen(s);
1462             print_expr(s, o);
1463             pclose(s);
1464             word_space(s, ",");
1465         }
1466         word_space(s, ":");
1467         for &(co, o) in a.inputs.iter() {
1468             print_string(s, co, ast::CookedStr);
1469             popen(s);
1470             print_expr(s, o);
1471             pclose(s);
1472             word_space(s, ",");
1473         }
1474         word_space(s, ":");
1475         print_string(s, a.clobbers, ast::CookedStr);
1476         pclose(s);
1477       }
1478       ast::ExprMac(ref m) => print_mac(s, m),
1479       ast::ExprParen(e) => {
1480           popen(s);
1481           print_expr(s, e);
1482           pclose(s);
1483       }
1484     }
1485     s.ann.post(ann_node);
1486     end(s);
1487 }
1488
1489 pub fn print_local_decl(s: @ps, loc: &ast::Local) {
1490     print_pat(s, loc.pat);
1491     match loc.ty.node {
1492       ast::ty_infer => (),
1493       _ => { word_space(s, ":"); print_type(s, loc.ty); }
1494     }
1495 }
1496
1497 pub fn print_decl(s: @ps, decl: &ast::Decl) {
1498     maybe_print_comment(s, decl.span.lo);
1499     match decl.node {
1500       ast::DeclLocal(ref loc) => {
1501         space_if_not_bol(s);
1502         ibox(s, indent_unit);
1503         word_nbsp(s, "let");
1504
1505         fn print_local(s: @ps, loc: &ast::Local) {
1506             ibox(s, indent_unit);
1507             print_local_decl(s, loc);
1508             end(s);
1509             match loc.init {
1510               Some(init) => {
1511                 nbsp(s);
1512                 word_space(s, "=");
1513                 print_expr(s, init);
1514               }
1515               _ => ()
1516             }
1517         }
1518
1519         print_local(s, *loc);
1520         end(s);
1521       }
1522       ast::DeclItem(item) => print_item(s, item)
1523     }
1524 }
1525
1526 pub fn print_ident(s: @ps, ident: ast::Ident) {
1527     word(s.s, ident_to_str(&ident));
1528 }
1529
1530 pub fn print_name(s: @ps, name: ast::Name) {
1531     word(s.s, interner_get(name));
1532 }
1533
1534 pub fn print_for_decl(s: @ps, loc: &ast::Local, coll: &ast::Expr) {
1535     print_local_decl(s, loc);
1536     space(s.s);
1537     word_space(s, "in");
1538     print_expr(s, coll);
1539 }
1540
1541 fn print_path_(s: @ps,
1542                path: &ast::Path,
1543                colons_before_params: bool,
1544                opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1545     maybe_print_comment(s, path.span.lo);
1546     if path.global {
1547         word(s.s, "::");
1548     }
1549
1550     let mut first = true;
1551     for (i, segment) in path.segments.iter().enumerate() {
1552         if first {
1553             first = false
1554         } else {
1555             word(s.s, "::")
1556         }
1557
1558         print_ident(s, segment.identifier);
1559
1560         // If this is the last segment, print the bounds.
1561         if i == path.segments.len() - 1 {
1562             match *opt_bounds {
1563                 None => {}
1564                 Some(ref bounds) => print_bounds(s, bounds, true),
1565             }
1566         }
1567
1568         if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1569             if colons_before_params {
1570                 word(s.s, "::")
1571             }
1572             word(s.s, "<");
1573
1574             let mut comma = false;
1575             for lifetime in segment.lifetimes.iter() {
1576                 if comma {
1577                     word_space(s, ",")
1578                 }
1579                 print_lifetime(s, lifetime);
1580                 comma = true;
1581             }
1582
1583             if !segment.types.is_empty() {
1584                 if comma {
1585                     word_space(s, ",")
1586                 }
1587                 commasep(s,
1588                          inconsistent,
1589                          segment.types.map_to_vec(|&t| t),
1590                          print_type_ref);
1591             }
1592
1593             word(s.s, ">")
1594         }
1595     }
1596 }
1597
1598 pub fn print_path(s: @ps, path: &ast::Path, colons_before_params: bool) {
1599     print_path_(s, path, colons_before_params, &None)
1600 }
1601
1602 pub fn print_bounded_path(s: @ps, path: &ast::Path,
1603                           bounds: &Option<OptVec<ast::TyParamBound>>) {
1604     print_path_(s, path, false, bounds)
1605 }
1606
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 */
1613     match pat.node {
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);
1621               }
1622               ast::BindByValue(ast::MutImmutable) => {}
1623               ast::BindByValue(ast::MutMutable) => {
1624                   word_nbsp(s, "mut");
1625               }
1626           }
1627           print_path(s, path, true);
1628           match sub {
1629               Some(p) => {
1630                   word(s.s, "@");
1631                   print_pat(s, p);
1632               }
1633               None => ()
1634           }
1635       }
1636       ast::PatEnum(ref path, ref args_) => {
1637         print_path(s, path, true);
1638         match *args_ {
1639           None => word(s.s, "(..)"),
1640           Some(ref args) => {
1641             if !args.is_empty() {
1642               popen(s);
1643               commasep(s, inconsistent, *args,
1644                        |s, &p| print_pat(s, p));
1645               pclose(s);
1646             } else { }
1647           }
1648         }
1649       }
1650       ast::PatStruct(ref path, ref fields, etc) => {
1651         print_path(s, path, true);
1652         word(s.s, "{");
1653         fn print_field(s: @ps, f: &ast::FieldPat) {
1654             cbox(s, indent_unit);
1655             print_ident(s, f.ident);
1656             word_space(s, ":");
1657             print_pat(s, f.pat);
1658             end(s);
1659         }
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),
1663                       get_span);
1664         if etc {
1665             if fields.len() != 0u { word_space(s, ","); }
1666             word(s.s, "..");
1667         }
1668         word(s.s, "}");
1669       }
1670       ast::PatTup(ref elts) => {
1671         popen(s);
1672         commasep(s, inconsistent, *elts, |s, &p| print_pat(s, p));
1673         if elts.len() == 1 {
1674             word(s.s, ",");
1675         }
1676         pclose(s);
1677       }
1678       ast::PatBox(inner) => {
1679           word(s.s, "@");
1680           print_pat(s, inner);
1681       }
1682       ast::PatUniq(inner) => {
1683           word(s.s, "~");
1684           print_pat(s, inner);
1685       }
1686       ast::PatRegion(inner) => {
1687           word(s.s, "&");
1688           print_pat(s, inner);
1689       }
1690       ast::PatLit(e) => print_expr(s, e),
1691       ast::PatRange(begin, end) => {
1692         print_expr(s, begin);
1693         space(s.s);
1694         word(s.s, "..");
1695         print_expr(s, end);
1696       }
1697       ast::PatVec(ref before, slice, ref after) => {
1698         word(s.s, "[");
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, ","); }
1702             match p {
1703                 @ast::Pat { node: ast::PatWildMulti, .. } => {
1704                     // this case is handled by print_pat
1705                 }
1706                 _ => word(s.s, ".."),
1707             }
1708             print_pat(s, p);
1709             if !after.is_empty() { word_space(s, ","); }
1710         }
1711         commasep(s, inconsistent, *after, |s, &p| print_pat(s, p));
1712         word(s.s, "]");
1713       }
1714     }
1715     s.ann.post(ann_node);
1716 }
1717
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)
1720 }
1721
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);
1728             word(s.s, "self");
1729         }
1730         ast::sty_uniq(m) => {
1731             print_mutability(s, m);
1732             word(s.s, "~self");
1733         }
1734         ast::sty_region(ref lt, m) => {
1735             word(s.s, "&");
1736             print_opt_lifetime(s, lt);
1737             print_mutability(s, m);
1738             word(s.s, "self");
1739         }
1740         ast::sty_box(m) => {
1741             word(s.s, "@"); print_mutability(s, m); word(s.s, "self");
1742         }
1743     }
1744     return true;
1745 }
1746
1747 pub fn print_fn(s: @ps,
1748                 decl: &ast::fn_decl,
1749                 purity: Option<ast::purity>,
1750                 abis: AbiSet,
1751                 name: ast::Ident,
1752                 generics: &ast::Generics,
1753                 opt_explicit_self: Option<ast::explicit_self_>,
1754                 vis: ast::visibility) {
1755     head(s, "");
1756     print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1757     nbsp(s);
1758     print_ident(s, name);
1759     print_generics(s, generics);
1760     print_fn_args_and_ret(s, decl, opt_explicit_self);
1761 }
1762
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);
1771     }
1772
1773     for arg in decl.inputs.iter() {
1774         if first { first = false; } else { word_space(s, ","); }
1775         print_arg(s, arg);
1776     }
1777
1778     end(s);
1779 }
1780
1781 pub fn print_fn_args_and_ret(s: @ps, decl: &ast::fn_decl,
1782                              opt_explicit_self: Option<ast::explicit_self_>) {
1783     popen(s);
1784     print_fn_args(s, decl, opt_explicit_self);
1785     if decl.variadic {
1786         word(s.s, ", ...");
1787     }
1788     pclose(s);
1789
1790     maybe_print_comment(s, decl.output.span.lo);
1791     match decl.output.node {
1792         ast::ty_nil => {}
1793         _ => {
1794             space_if_not_bol(s);
1795             word_space(s, "->");
1796             print_type(s, decl.output);
1797         }
1798     }
1799 }
1800
1801 pub fn print_fn_block_args(s: @ps, decl: &ast::fn_decl) {
1802     word(s.s, "|");
1803     print_fn_args(s, decl, None);
1804     word(s.s, "|");
1805
1806     match decl.output.node {
1807         ast::ty_infer => {}
1808         _ => {
1809             space_if_not_bol(s);
1810             word_space(s, "->");
1811             print_type(s, decl.output);
1812         }
1813     }
1814
1815     maybe_print_comment(s, decl.output.span.lo);
1816 }
1817
1818 pub fn print_proc_args(s: @ps, decl: &ast::fn_decl) {
1819     word(s.s, "proc");
1820     word(s.s, "(");
1821     print_fn_args(s, decl, None);
1822     word(s.s, ")");
1823
1824     match decl.output.node {
1825         ast::ty_infer => {}
1826         _ => {
1827             space_if_not_bol(s);
1828             word_space(s, "->");
1829             print_type(s, decl.output);
1830         }
1831     }
1832
1833     maybe_print_comment(s, decl.output.span.lo);
1834 }
1835
1836 pub fn print_bounds(s: @ps, bounds: &OptVec<ast::TyParamBound>,
1837                     print_colon_anyway: bool) {
1838     if !bounds.is_empty() {
1839         word(s.s, ":");
1840         let mut first = true;
1841         for bound in bounds.iter() {
1842             nbsp(s);
1843             if first {
1844                 first = false;
1845             } else {
1846                 word_space(s, "+");
1847             }
1848
1849             match *bound {
1850                 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1851                 RegionTyParamBound => word(s.s, "'static"),
1852             }
1853         }
1854     } else if print_colon_anyway {
1855         word(s.s, ":");
1856     }
1857 }
1858
1859 pub fn print_lifetime(s: @ps, lifetime: &ast::Lifetime) {
1860     word(s.s, "'");
1861     print_ident(s, lifetime.ident);
1862 }
1863
1864 pub fn print_generics(s: @ps, generics: &ast::Generics) {
1865     let total = generics.lifetimes.len() + generics.ty_params.len();
1866     if total > 0 {
1867         word(s.s, "<");
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);
1872             } else {
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, &param.bounds, false);
1877             }
1878         }
1879
1880         let mut ints = ~[];
1881         for i in range(0u, total) {
1882             ints.push(i);
1883         }
1884
1885         commasep(s, inconsistent, ints,
1886                  |s, &i| print_item(s, generics, i));
1887         word(s.s, ">");
1888     }
1889 }
1890
1891 pub fn print_meta_item(s: @ps, item: &ast::MetaItem) {
1892     ibox(s, indent_unit);
1893     match item.node {
1894       ast::MetaWord(name) => word(s.s, name),
1895       ast::MetaNameValue(name, value) => {
1896         word_space(s, name);
1897         word_space(s, "=");
1898         print_literal(s, &value);
1899       }
1900       ast::MetaList(name, ref items) => {
1901         word(s.s, name);
1902         popen(s);
1903         commasep(s,
1904                  consistent,
1905                  items.as_slice(),
1906                  |p, &i| print_meta_item(p, i));
1907         pclose(s);
1908       }
1909     }
1910     end(s);
1911 }
1912
1913 pub fn print_view_path(s: @ps, vp: &ast::view_path) {
1914     match vp.node {
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);
1919             space(s.s);
1920             word_space(s, "=");
1921         }
1922         print_path(s, path, false);
1923       }
1924
1925       ast::view_path_glob(ref path, _) => {
1926         print_path(s, path, false);
1927         word(s.s, "::*");
1928       }
1929
1930       ast::view_path_list(ref path, ref idents, _) => {
1931         if path.segments.is_empty() {
1932             word(s.s, "{");
1933         } else {
1934             print_path(s, path, false);
1935             word(s.s, "::{");
1936         }
1937         commasep(s, inconsistent, (*idents), |s, w| {
1938             print_ident(s, w.node.name);
1939         });
1940         word(s.s, "}");
1941       }
1942     }
1943 }
1944
1945 pub fn print_view_paths(s: @ps, vps: &[@ast::view_path]) {
1946     commasep(s, inconsistent, vps, |p, &vp| print_view_path(p, vp));
1947 }
1948
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);
1954     match item.node {
1955         ast::view_item_extern_mod(id, ref optional_path, ref mta, _) => {
1956             head(s, "extern mod");
1957             print_ident(s, id);
1958             for &(ref p, style) in optional_path.iter() {
1959                 space(s.s);
1960                 word(s.s, "=");
1961                 space(s.s);
1962                 print_string(s, *p, style);
1963             }
1964             if !mta.is_empty() {
1965                 popen(s);
1966                 commasep(s, consistent, *mta, |p, &i| print_meta_item(p, i));
1967                 pclose(s);
1968             }
1969         }
1970
1971         ast::view_item_use(ref vps) => {
1972             head(s, "use");
1973             print_view_paths(s, *vps);
1974         }
1975     }
1976     word(s.s, ";");
1977     end(s); // end inner head-block
1978     end(s); // end outer head-block
1979 }
1980
1981 pub fn print_mutability(s: @ps, mutbl: ast::Mutability) {
1982     match mutbl {
1983       ast::MutMutable => word_nbsp(s, "mut"),
1984       ast::MutImmutable => {/* nothing */ }
1985     }
1986 }
1987
1988 pub fn print_mt(s: @ps, mt: &ast::mt) {
1989     print_mutability(s, mt.mutbl);
1990     print_type(s, mt.ty);
1991 }
1992
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),
1997       _ => {
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 => {
2003                 // Do nothing.
2004             }
2005             _ => {
2006                 print_pat(s, input.pat);
2007                 word(s.s, ":");
2008                 space(s.s);
2009             }
2010         }
2011         print_type(s, input.ty);
2012       }
2013     }
2014     end(s);
2015 }
2016
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);
2029
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 {
2033         word(s.s, "proc");
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);
2038         }
2039         print_purity(s, purity);
2040         print_onceness(s, onceness);
2041     } else {
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);
2047         word(s.s, "fn");
2048     }
2049
2050     match id { Some(id) => { word(s.s, " "); print_ident(s, id); } _ => () }
2051
2052     if opt_sigil != Some(ast::BorrowedSigil) {
2053         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2054     }
2055
2056     match generics { Some(g) => print_generics(s, g), _ => () }
2057     zerobreak(s.s);
2058
2059     if opt_sigil == Some(ast::BorrowedSigil) {
2060         word(s.s, "|");
2061     } else {
2062         popen(s);
2063     }
2064
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);
2071     }
2072     for arg in decl.inputs.iter() {
2073         if first { first = false; } else { word_space(s, ","); }
2074         print_arg(s, arg);
2075     }
2076     end(s);
2077
2078     if opt_sigil == Some(ast::BorrowedSigil) {
2079         word(s.s, "|");
2080
2081         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2082     } else {
2083         if decl.variadic {
2084             word(s.s, ", ...");
2085         }
2086         pclose(s);
2087     }
2088
2089     maybe_print_comment(s, decl.output.span.lo);
2090
2091     match decl.output.node {
2092         ast::ty_nil => {}
2093         _ => {
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); }
2099             end(s);
2100         }
2101     }
2102
2103     end(s);
2104 }
2105
2106 pub fn maybe_print_trailing_comment(s: @ps, span: codemap::Span,
2107                                     next_pos: Option<BytePos>) {
2108     let cm;
2109     match s.cm { Some(ccm) => cm = ccm, _ => return }
2110     match next_comment(s) {
2111       Some(ref cmnt) => {
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;
2121         }
2122       }
2123       _ => ()
2124     }
2125 }
2126
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); }
2131     loop {
2132         match next_comment(s) {
2133           Some(ref cmnt) => {
2134             print_comment(s, cmnt);
2135             s.cur_cmnt_and_lit.cur_cmnt += 1u;
2136           }
2137           _ => break
2138         }
2139     }
2140 }
2141
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) {
2145       Some(ref ltrl) => {
2146         word(s.s, (*ltrl).lit);
2147         return;
2148       }
2149       _ => ()
2150     }
2151     match lit.node {
2152       ast::lit_str(st, style) => print_string(s, st, style),
2153       ast::lit_char(ch) => {
2154           let mut res = ~"'";
2155           char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2156           res.push_char('\'');
2157           word(s.s, res);
2158       }
2159       ast::lit_int(i, t) => {
2160         if i < 0_i64 {
2161             word(s.s,
2162                  ~"-" + (-i as u64).to_str_radix(10u)
2163                  + ast_util::int_ty_to_str(t));
2164         } else {
2165             word(s.s,
2166                  (i as u64).to_str_radix(10u)
2167                  + ast_util::int_ty_to_str(t));
2168         }
2169       }
2170       ast::lit_uint(u, t) => {
2171         word(s.s,
2172              u.to_str_radix(10u)
2173              + ast_util::uint_ty_to_str(t));
2174       }
2175       ast::lit_int_unsuffixed(i) => {
2176         if i < 0_i64 {
2177             word(s.s, ~"-" + (-i as u64).to_str_radix(10u));
2178         } else {
2179             word(s.s, (i as u64).to_str_radix(10u));
2180         }
2181       }
2182       ast::lit_float(f, t) => {
2183         word(s.s, f.to_owned() + ast_util::float_ty_to_str(t));
2184       }
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"); }
2189       }
2190       ast::lit_binary(arr) => {
2191         ibox(s, indent_unit);
2192         word(s.s, "[");
2193         commasep_cmnt(s, inconsistent, arr, |s, u| word(s.s, format!("{}", *u)),
2194                       |_| lit.span);
2195         word(s.s, "]");
2196         end(s);
2197       }
2198     }
2199 }
2200
2201 pub fn lit_to_str(l: &ast::lit) -> ~str {
2202     return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2203 }
2204
2205 pub fn next_lit(s: @ps, pos: BytePos) -> Option<comments::lit> {
2206     match s.literals {
2207       Some(ref lits) => {
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); }
2213         }
2214         return None;
2215       }
2216       _ => return None
2217     }
2218 }
2219
2220 pub fn maybe_print_comment(s: @ps, pos: BytePos) {
2221     loop {
2222         match next_comment(s) {
2223           Some(ref cmnt) => {
2224             if (*cmnt).pos < pos {
2225                 print_comment(s, cmnt);
2226                 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2227             } else { break; }
2228           }
2229           _ => break
2230         }
2231     }
2232 }
2233
2234 pub fn print_comment(s: @ps, cmnt: &comments::cmnt) {
2235     match cmnt.style {
2236       comments::mixed => {
2237         assert_eq!(cmnt.lines.len(), 1u);
2238         zerobreak(s.s);
2239         word(s.s, cmnt.lines[0]);
2240         zerobreak(s.s);
2241       }
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
2246             // whitespace
2247             if !line.is_empty() { word(s.s, *line); }
2248             hardbreak(s.s);
2249         }
2250       }
2251       comments::trailing => {
2252         word(s.s, " ");
2253         if cmnt.lines.len() == 1u {
2254             word(s.s, cmnt.lines[0]);
2255             hardbreak(s.s);
2256         } else {
2257             ibox(s, 0u);
2258             for line in cmnt.lines.iter() {
2259                 if !line.is_empty() { word(s.s, *line); }
2260                 hardbreak(s.s);
2261             }
2262             end(s);
2263         }
2264       }
2265       comments::blank_line => {
2266         // We need to do at least one, possibly two hardbreaks.
2267         let is_semi =
2268             match s.s.last_token() {
2269               pp::STRING(s, _) => ";" == s,
2270               _ => false
2271             };
2272         if is_semi || is_begin(s) || is_end(s) { hardbreak(s.s); }
2273         hardbreak(s.s);
2274       }
2275     }
2276 }
2277
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)
2283     };
2284     word(s.s, st);
2285 }
2286
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);
2290     f(s, t);
2291     eof(s.s);
2292     str::from_utf8_owned(wr.inner_ref().to_owned())
2293 }
2294
2295 pub fn next_comment(s: @ps) -> Option<comments::cmnt> {
2296     match s.comments {
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());
2300         } else {
2301             return None::<comments::cmnt>;
2302         }
2303       }
2304       _ => return None::<comments::cmnt>
2305     }
2306 }
2307
2308 pub fn print_opt_purity(s: @ps, opt_purity: Option<ast::purity>) {
2309     match opt_purity {
2310         Some(ast::impure_fn) => { }
2311         Some(purity) => {
2312             word_nbsp(s, purity_to_str(purity));
2313         }
2314         None => {}
2315     }
2316 }
2317
2318 pub fn print_opt_abis_and_extern_if_nondefault(s: @ps,
2319                                                opt_abis: Option<AbiSet>) {
2320     match opt_abis {
2321         Some(abis) if !abis.is_rust() => {
2322             word_nbsp(s, "extern");
2323             word_nbsp(s, abis.to_str());
2324         }
2325         Some(_) | None => {}
2326     };
2327 }
2328
2329 pub fn print_extern_opt_abis(s: @ps, opt_abis: Option<AbiSet>) {
2330     match opt_abis {
2331         Some(abis) => {
2332             word_nbsp(s, "extern");
2333             word_nbsp(s, abis.to_str());
2334         }
2335         None => {}
2336     };
2337 }
2338
2339 pub fn print_opt_sigil(s: @ps, opt_sigil: Option<ast::Sigil>) {
2340     match opt_sigil {
2341         Some(ast::BorrowedSigil) => { word(s.s, "&"); }
2342         Some(ast::OwnedSigil) => { word(s.s, "~"); }
2343         Some(ast::ManagedSigil) => { word(s.s, "@"); }
2344         None => {}
2345     };
2346 }
2347
2348 pub fn print_fn_header_info(s: @ps,
2349                             _opt_explicit_self: Option<ast::explicit_self_>,
2350                             opt_purity: Option<ast::purity>,
2351                             abis: AbiSet,
2352                             onceness: ast::Onceness,
2353                             opt_sigil: Option<ast::Sigil>,
2354                             vis: ast::visibility) {
2355     word(s.s, visibility_qualified(vis, ""));
2356
2357     if abis != AbiSet::Rust() {
2358         word_nbsp(s, "extern");
2359         word_nbsp(s, abis.to_str());
2360
2361         if opt_purity != Some(ast::extern_fn) {
2362             print_opt_purity(s, opt_purity);
2363         }
2364     } else {
2365         print_opt_purity(s, opt_purity);
2366     }
2367
2368     print_onceness(s, onceness);
2369     word(s.s, "fn");
2370     print_opt_sigil(s, opt_sigil);
2371 }
2372
2373 pub fn purity_to_str(p: ast::purity) -> &'static str {
2374     match p {
2375       ast::impure_fn => "impure",
2376       ast::unsafe_fn => "unsafe",
2377       ast::extern_fn => "extern"
2378     }
2379 }
2380
2381 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2382     match o {
2383         ast::Once => "once",
2384         ast::Many => "many"
2385     }
2386 }
2387
2388 pub fn print_purity(s: @ps, p: ast::purity) {
2389     match p {
2390       ast::impure_fn => (),
2391       _ => word_nbsp(s, purity_to_str(p))
2392     }
2393 }
2394
2395 pub fn print_onceness(s: @ps, o: ast::Onceness) {
2396     match o {
2397         ast::Once => { word_nbsp(s, "once"); }
2398         ast::Many => {}
2399     }
2400 }
2401
2402 #[cfg(test)]
2403 mod test {
2404     use super::*;
2405
2406     use ast;
2407     use ast_util;
2408     use codemap;
2409     use parse::token;
2410
2411     fn string_check<T:Eq> (given : &T, expected: &T) {
2412         if !(given == expected) {
2413             fail!("given {:?}, expected {:?}", given, expected);
2414         }
2415     }
2416
2417     #[test]
2418     fn test_fun_to_str() {
2419         let abba_ident = token::str_to_ident("abba");
2420
2421         let decl = ast::fn_decl {
2422             inputs: ~[],
2423             output: ast::P(ast::Ty {id: 0,
2424                                     node: ast::ty_nil,
2425                                     span: codemap::DUMMY_SP}),
2426             cf: ast::return_val,
2427             variadic: false
2428         };
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()),
2432                    &~"fn abba()");
2433     }
2434
2435     #[test]
2436     fn test_variant_to_str() {
2437         let ident = token::str_to_ident("principal_skinner");
2438
2439         let var = codemap::respan(codemap::DUMMY_SP, ast::variant_ {
2440             name: ident,
2441             attrs: ~[],
2442             // making this up as I go.... ?
2443             kind: ast::tuple_variant_kind(~[]),
2444             id: 0,
2445             disr_expr: None,
2446             vis: ast::public,
2447         });
2448
2449         let varstr = variant_to_str(&var,token::get_ident_interner());
2450         assert_eq!(&varstr,&~"pub principal_skinner");
2451     }
2452 }