]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
libsyntax: Remove many uses of `token::ident_to_str`
[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, 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().unwrap();
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.get());
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::ForSugar => {
1092             head(s, "for");
1093             Some(base_args.pop().unwrap())
1094         }
1095         ast::NoSugar => None
1096     }
1097 }
1098
1099 pub fn print_call_post(s: &mut State,
1100                        sugar: ast::CallSugar,
1101                        blk: &Option<@ast::Expr>,
1102                        base_args: &mut ~[@ast::Expr]) {
1103     if sugar == ast::NoSugar || !base_args.is_empty() {
1104         popen(s);
1105         commasep_exprs(s, Inconsistent, *base_args);
1106         pclose(s);
1107     }
1108     if sugar != ast::NoSugar {
1109         nbsp(s);
1110         // not sure if this can happen
1111         print_expr(s, blk.unwrap());
1112     }
1113 }
1114
1115 pub fn print_expr(s: &mut State, expr: &ast::Expr) {
1116     fn print_field(s: &mut State, field: &ast::Field) {
1117         ibox(s, indent_unit);
1118         print_ident(s, field.ident.node);
1119         word_space(s, ":");
1120         print_expr(s, field.expr);
1121         end(s);
1122     }
1123     fn get_span(field: &ast::Field) -> codemap::Span { return field.span; }
1124
1125     maybe_print_comment(s, expr.span.lo);
1126     ibox(s, indent_unit);
1127     {
1128         let ann_node = NodeExpr(s, expr);
1129         s.ann.pre(ann_node);
1130     }
1131     match expr.node {
1132         ast::ExprVstore(e, v) => {
1133             print_expr_vstore(s, v);
1134             print_expr(s, e);
1135         },
1136         ast::ExprBox(p, e) => {
1137             word(&mut s.s, "box");
1138             word(&mut s.s, "(");
1139             print_expr(s, p);
1140             word_space(s, ")");
1141             print_expr(s, e);
1142         }
1143       ast::ExprVec(ref exprs, mutbl) => {
1144         ibox(s, indent_unit);
1145         word(&mut s.s, "[");
1146         if mutbl == ast::MutMutable {
1147             word(&mut s.s, "mut");
1148             if exprs.len() > 0u { nbsp(s); }
1149         }
1150         commasep_exprs(s, Inconsistent, *exprs);
1151         word(&mut s.s, "]");
1152         end(s);
1153       }
1154
1155       ast::ExprRepeat(element, count, mutbl) => {
1156         ibox(s, indent_unit);
1157         word(&mut s.s, "[");
1158         if mutbl == ast::MutMutable {
1159             word(&mut s.s, "mut");
1160             nbsp(s);
1161         }
1162         print_expr(s, element);
1163         word(&mut s.s, ",");
1164         word(&mut s.s, "..");
1165         print_expr(s, count);
1166         word(&mut s.s, "]");
1167         end(s);
1168       }
1169
1170       ast::ExprStruct(ref path, ref fields, wth) => {
1171         print_path(s, path, true);
1172         word(&mut s.s, "{");
1173         commasep_cmnt(s, Consistent, (*fields), print_field, get_span);
1174         match wth {
1175             Some(expr) => {
1176                 ibox(s, indent_unit);
1177                 if !fields.is_empty() {
1178                     word(&mut s.s, ",");
1179                     space(&mut s.s);
1180                 }
1181                 word(&mut s.s, "..");
1182                 print_expr(s, expr);
1183                 end(s);
1184             }
1185             _ => (word(&mut s.s, ","))
1186         }
1187         word(&mut s.s, "}");
1188       }
1189       ast::ExprTup(ref exprs) => {
1190         popen(s);
1191         commasep_exprs(s, Inconsistent, *exprs);
1192         if exprs.len() == 1 {
1193             word(&mut s.s, ",");
1194         }
1195         pclose(s);
1196       }
1197       ast::ExprCall(func, ref args, sugar) => {
1198         let mut base_args = (*args).clone();
1199         let blk = print_call_pre(s, sugar, &mut base_args);
1200         print_expr(s, func);
1201         print_call_post(s, sugar, &blk, &mut base_args);
1202       }
1203       ast::ExprMethodCall(_, ident, ref tys, ref args, sugar) => {
1204         let mut base_args = args.slice_from(1).to_owned();
1205         let blk = print_call_pre(s, sugar, &mut base_args);
1206         print_expr(s, args[0]);
1207         word(&mut s.s, ".");
1208         print_ident(s, ident);
1209         if tys.len() > 0u {
1210             word(&mut s.s, "::<");
1211             commasep(s, Inconsistent, *tys, print_type_ref);
1212             word(&mut s.s, ">");
1213         }
1214         print_call_post(s, sugar, &blk, &mut base_args);
1215       }
1216       ast::ExprBinary(_, op, lhs, rhs) => {
1217         print_expr(s, lhs);
1218         space(&mut s.s);
1219         word_space(s, ast_util::binop_to_str(op));
1220         print_expr(s, rhs);
1221       }
1222       ast::ExprUnary(_, op, expr) => {
1223         word(&mut s.s, ast_util::unop_to_str(op));
1224         print_expr(s, expr);
1225       }
1226       ast::ExprAddrOf(m, expr) => {
1227         word(&mut s.s, "&");
1228         print_mutability(s, m);
1229         // Avoid `& &e` => `&&e`.
1230         match (m, &expr.node) {
1231             (ast::MutImmutable, &ast::ExprAddrOf(..)) => space(&mut s.s),
1232             _ => { }
1233         }
1234         print_expr(s, expr);
1235       }
1236       ast::ExprLit(lit) => print_literal(s, lit),
1237       ast::ExprCast(expr, ty) => {
1238         print_expr(s, expr);
1239         space(&mut s.s);
1240         word_space(s, "as");
1241         print_type(s, ty);
1242       }
1243       ast::ExprIf(test, blk, elseopt) => {
1244         print_if(s, test, blk, elseopt, false);
1245       }
1246       ast::ExprWhile(test, blk) => {
1247         head(s, "while");
1248         print_expr(s, test);
1249         space(&mut s.s);
1250         print_block(s, blk);
1251       }
1252       ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1253         for ident in opt_ident.iter() {
1254             word(&mut s.s, "'");
1255             print_ident(s, *ident);
1256             word_space(s, ":");
1257         }
1258         head(s, "for");
1259         print_pat(s, pat);
1260         space(&mut s.s);
1261         word_space(s, "in");
1262         print_expr(s, iter);
1263         space(&mut s.s);
1264         print_block(s, blk);
1265       }
1266       ast::ExprLoop(blk, opt_ident) => {
1267         for ident in opt_ident.iter() {
1268             word(&mut s.s, "'");
1269             print_ident(s, *ident);
1270             word_space(s, ":");
1271         }
1272         head(s, "loop");
1273         space(&mut s.s);
1274         print_block(s, blk);
1275       }
1276       ast::ExprMatch(expr, ref arms) => {
1277         cbox(s, indent_unit);
1278         ibox(s, 4);
1279         word_nbsp(s, "match");
1280         print_expr(s, expr);
1281         space(&mut s.s);
1282         bopen(s);
1283         let len = arms.len();
1284         for (i, arm) in arms.iter().enumerate() {
1285             space(&mut s.s);
1286             cbox(s, indent_unit);
1287             ibox(s, 0u);
1288             let mut first = true;
1289             for p in arm.pats.iter() {
1290                 if first {
1291                     first = false;
1292                 } else { space(&mut s.s); word_space(s, "|"); }
1293                 print_pat(s, *p);
1294             }
1295             space(&mut s.s);
1296             match arm.guard {
1297               Some(e) => {
1298                 word_space(s, "if");
1299                 print_expr(s, e);
1300                 space(&mut s.s);
1301               }
1302               None => ()
1303             }
1304             word_space(s, "=>");
1305
1306             // Extract the expression from the extra block the parser adds
1307             // in the case of foo => expr
1308             if arm.body.view_items.is_empty() &&
1309                 arm.body.stmts.is_empty() &&
1310                 arm.body.rules == ast::DefaultBlock &&
1311                 arm.body.expr.is_some()
1312             {
1313                 match arm.body.expr {
1314                     Some(expr) => {
1315                         match expr.node {
1316                             ast::ExprBlock(blk) => {
1317                                 // the block will close the pattern's ibox
1318                                 print_block_unclosed_indent(
1319                                     s, blk, indent_unit);
1320                             }
1321                             _ => {
1322                                 end(s); // close the ibox for the pattern
1323                                 print_expr(s, expr);
1324                             }
1325                         }
1326                         if !expr_is_simple_block(expr)
1327                             && i < len - 1 {
1328                             word(&mut s.s, ",");
1329                         }
1330                         end(s); // close enclosing cbox
1331                     }
1332                     None => fail!()
1333                 }
1334             } else {
1335                 // the block will close the pattern's ibox
1336                 print_block_unclosed_indent(s, arm.body, indent_unit);
1337             }
1338         }
1339         bclose_(s, expr.span, indent_unit);
1340       }
1341       ast::ExprFnBlock(decl, body) => {
1342         // in do/for blocks we don't want to show an empty
1343         // argument list, but at this point we don't know which
1344         // we are inside.
1345         //
1346         // if !decl.inputs.is_empty() {
1347         print_fn_block_args(s, decl);
1348         space(&mut s.s);
1349         // }
1350         assert!(body.stmts.is_empty());
1351         assert!(body.expr.is_some());
1352         // we extract the block, so as not to create another set of boxes
1353         match body.expr.unwrap().node {
1354             ast::ExprBlock(blk) => {
1355                 print_block_unclosed(s, blk);
1356             }
1357             _ => {
1358                 // this is a bare expression
1359                 print_expr(s, body.expr.unwrap());
1360                 end(s); // need to close a box
1361             }
1362         }
1363         // a box will be closed by print_expr, but we didn't want an overall
1364         // wrapper so we closed the corresponding opening. so create an
1365         // empty box to satisfy the close.
1366         ibox(s, 0);
1367       }
1368       ast::ExprProc(decl, body) => {
1369         // in do/for blocks we don't want to show an empty
1370         // argument list, but at this point we don't know which
1371         // we are inside.
1372         //
1373         // if !decl.inputs.is_empty() {
1374         print_proc_args(s, decl);
1375         space(&mut s.s);
1376         // }
1377         assert!(body.stmts.is_empty());
1378         assert!(body.expr.is_some());
1379         // we extract the block, so as not to create another set of boxes
1380         match body.expr.unwrap().node {
1381             ast::ExprBlock(blk) => {
1382                 print_block_unclosed(s, blk);
1383             }
1384             _ => {
1385                 // this is a bare expression
1386                 print_expr(s, body.expr.unwrap());
1387                 end(s); // need to close a box
1388             }
1389         }
1390         // a box will be closed by print_expr, but we didn't want an overall
1391         // wrapper so we closed the corresponding opening. so create an
1392         // empty box to satisfy the close.
1393         ibox(s, 0);
1394       }
1395       ast::ExprBlock(blk) => {
1396         // containing cbox, will be closed by print-block at }
1397         cbox(s, indent_unit);
1398         // head-box, will be closed by print-block after {
1399         ibox(s, 0u);
1400         print_block(s, blk);
1401       }
1402       ast::ExprAssign(lhs, rhs) => {
1403         print_expr(s, lhs);
1404         space(&mut s.s);
1405         word_space(s, "=");
1406         print_expr(s, rhs);
1407       }
1408       ast::ExprAssignOp(_, op, lhs, rhs) => {
1409         print_expr(s, lhs);
1410         space(&mut s.s);
1411         word(&mut s.s, ast_util::binop_to_str(op));
1412         word_space(s, "=");
1413         print_expr(s, rhs);
1414       }
1415       ast::ExprField(expr, id, ref tys) => {
1416         print_expr(s, expr);
1417         word(&mut s.s, ".");
1418         print_ident(s, id);
1419         if tys.len() > 0u {
1420             word(&mut s.s, "::<");
1421             commasep(s, Inconsistent, *tys, print_type_ref);
1422             word(&mut s.s, ">");
1423         }
1424       }
1425       ast::ExprIndex(_, expr, index) => {
1426         print_expr(s, expr);
1427         word(&mut s.s, "[");
1428         print_expr(s, index);
1429         word(&mut s.s, "]");
1430       }
1431       ast::ExprPath(ref path) => print_path(s, path, true),
1432       ast::ExprBreak(opt_ident) => {
1433         word(&mut s.s, "break");
1434         space(&mut s.s);
1435         for ident in opt_ident.iter() {
1436             word(&mut s.s, "'");
1437             print_name(s, *ident);
1438             space(&mut s.s);
1439         }
1440       }
1441       ast::ExprAgain(opt_ident) => {
1442         word(&mut s.s, "continue");
1443         space(&mut s.s);
1444         for ident in opt_ident.iter() {
1445             word(&mut s.s, "'");
1446             print_name(s, *ident);
1447             space(&mut s.s)
1448         }
1449       }
1450       ast::ExprRet(result) => {
1451         word(&mut s.s, "return");
1452         match result {
1453           Some(expr) => { word(&mut s.s, " "); print_expr(s, expr); }
1454           _ => ()
1455         }
1456       }
1457       ast::ExprLogLevel => {
1458         word(&mut s.s, "__log_level");
1459         popen(s);
1460         pclose(s);
1461       }
1462       ast::ExprInlineAsm(ref a) => {
1463         if a.volatile {
1464             word(&mut s.s, "__volatile__ asm!");
1465         } else {
1466             word(&mut s.s, "asm!");
1467         }
1468         popen(s);
1469         print_string(s, a.asm.get(), a.asm_str_style);
1470         word_space(s, ":");
1471         for &(ref co, o) in a.outputs.iter() {
1472             print_string(s, co.get(), ast::CookedStr);
1473             popen(s);
1474             print_expr(s, o);
1475             pclose(s);
1476             word_space(s, ",");
1477         }
1478         word_space(s, ":");
1479         for &(ref co, o) in a.inputs.iter() {
1480             print_string(s, co.get(), ast::CookedStr);
1481             popen(s);
1482             print_expr(s, o);
1483             pclose(s);
1484             word_space(s, ",");
1485         }
1486         word_space(s, ":");
1487         print_string(s, a.clobbers.get(), ast::CookedStr);
1488         pclose(s);
1489       }
1490       ast::ExprMac(ref m) => print_mac(s, m),
1491       ast::ExprParen(e) => {
1492           popen(s);
1493           print_expr(s, e);
1494           pclose(s);
1495       }
1496     }
1497     {
1498         let ann_node = NodeExpr(s, expr);
1499         s.ann.post(ann_node);
1500     }
1501     end(s);
1502 }
1503
1504 pub fn print_local_decl(s: &mut State, loc: &ast::Local) {
1505     print_pat(s, loc.pat);
1506     match loc.ty.node {
1507         ast::TyInfer => {}
1508         _ => { word_space(s, ":"); print_type(s, loc.ty); }
1509     }
1510 }
1511
1512 pub fn print_decl(s: &mut State, decl: &ast::Decl) {
1513     maybe_print_comment(s, decl.span.lo);
1514     match decl.node {
1515       ast::DeclLocal(ref loc) => {
1516         space_if_not_bol(s);
1517         ibox(s, indent_unit);
1518         word_nbsp(s, "let");
1519
1520         fn print_local(s: &mut State, loc: &ast::Local) {
1521             ibox(s, indent_unit);
1522             print_local_decl(s, loc);
1523             end(s);
1524             match loc.init {
1525               Some(init) => {
1526                 nbsp(s);
1527                 word_space(s, "=");
1528                 print_expr(s, init);
1529               }
1530               _ => ()
1531             }
1532         }
1533
1534         print_local(s, *loc);
1535         end(s);
1536       }
1537       ast::DeclItem(item) => print_item(s, item)
1538     }
1539 }
1540
1541 pub fn print_ident(s: &mut State, ident: ast::Ident) {
1542     let string = token::get_ident(ident.name);
1543     word(&mut s.s, string.get());
1544 }
1545
1546 pub fn print_name(s: &mut State, name: ast::Name) {
1547     word(&mut s.s, interner_get(name));
1548 }
1549
1550 pub fn print_for_decl(s: &mut State, loc: &ast::Local, coll: &ast::Expr) {
1551     print_local_decl(s, loc);
1552     space(&mut s.s);
1553     word_space(s, "in");
1554     print_expr(s, coll);
1555 }
1556
1557 fn print_path_(s: &mut State,
1558                path: &ast::Path,
1559                colons_before_params: bool,
1560                opt_bounds: &Option<OptVec<ast::TyParamBound>>) {
1561     maybe_print_comment(s, path.span.lo);
1562     if path.global {
1563         word(&mut s.s, "::");
1564     }
1565
1566     let mut first = true;
1567     for (i, segment) in path.segments.iter().enumerate() {
1568         if first {
1569             first = false
1570         } else {
1571             word(&mut s.s, "::")
1572         }
1573
1574         print_ident(s, segment.identifier);
1575
1576         // If this is the last segment, print the bounds.
1577         if i == path.segments.len() - 1 {
1578             match *opt_bounds {
1579                 None => {}
1580                 Some(ref bounds) => print_bounds(s, bounds, true),
1581             }
1582         }
1583
1584         if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1585             if colons_before_params {
1586                 word(&mut s.s, "::")
1587             }
1588             word(&mut s.s, "<");
1589
1590             let mut comma = false;
1591             for lifetime in segment.lifetimes.iter() {
1592                 if comma {
1593                     word_space(s, ",")
1594                 }
1595                 print_lifetime(s, lifetime);
1596                 comma = true;
1597             }
1598
1599             if !segment.types.is_empty() {
1600                 if comma {
1601                     word_space(s, ",")
1602                 }
1603                 commasep(s,
1604                          Inconsistent,
1605                          segment.types.map_to_vec(|&t| t),
1606                          print_type_ref);
1607             }
1608
1609             word(&mut s.s, ">")
1610         }
1611     }
1612 }
1613
1614 pub fn print_path(s: &mut State, path: &ast::Path, colons_before_params: bool) {
1615     print_path_(s, path, colons_before_params, &None)
1616 }
1617
1618 pub fn print_bounded_path(s: &mut State, path: &ast::Path,
1619                           bounds: &Option<OptVec<ast::TyParamBound>>) {
1620     print_path_(s, path, false, bounds)
1621 }
1622
1623 pub fn print_pat(s: &mut State, pat: &ast::Pat) {
1624     maybe_print_comment(s, pat.span.lo);
1625     {
1626         let ann_node = NodePat(s, pat);
1627         s.ann.pre(ann_node);
1628     }
1629     /* Pat isn't normalized, but the beauty of it
1630      is that it doesn't matter */
1631     match pat.node {
1632       ast::PatWild => word(&mut s.s, "_"),
1633       ast::PatWildMulti => word(&mut s.s, ".."),
1634       ast::PatIdent(binding_mode, ref path, sub) => {
1635           match binding_mode {
1636               ast::BindByRef(mutbl) => {
1637                   word_nbsp(s, "ref");
1638                   print_mutability(s, mutbl);
1639               }
1640               ast::BindByValue(ast::MutImmutable) => {}
1641               ast::BindByValue(ast::MutMutable) => {
1642                   word_nbsp(s, "mut");
1643               }
1644           }
1645           print_path(s, path, true);
1646           match sub {
1647               Some(p) => {
1648                   word(&mut s.s, "@");
1649                   print_pat(s, p);
1650               }
1651               None => ()
1652           }
1653       }
1654       ast::PatEnum(ref path, ref args_) => {
1655         print_path(s, path, true);
1656         match *args_ {
1657           None => word(&mut s.s, "(..)"),
1658           Some(ref args) => {
1659             if !args.is_empty() {
1660               popen(s);
1661               commasep(s, Inconsistent, *args,
1662                        |s, &p| print_pat(s, p));
1663               pclose(s);
1664             } else { }
1665           }
1666         }
1667       }
1668       ast::PatStruct(ref path, ref fields, etc) => {
1669         print_path(s, path, true);
1670         word(&mut s.s, "{");
1671         fn print_field(s: &mut State, f: &ast::FieldPat) {
1672             cbox(s, indent_unit);
1673             print_ident(s, f.ident);
1674             word_space(s, ":");
1675             print_pat(s, f.pat);
1676             end(s);
1677         }
1678         fn get_span(f: &ast::FieldPat) -> codemap::Span { return f.pat.span; }
1679         commasep_cmnt(s, Consistent, *fields,
1680                       |s, f| print_field(s,f),
1681                       get_span);
1682         if etc {
1683             if fields.len() != 0u { word_space(s, ","); }
1684             word(&mut s.s, "..");
1685         }
1686         word(&mut s.s, "}");
1687       }
1688       ast::PatTup(ref elts) => {
1689         popen(s);
1690         commasep(s, Inconsistent, *elts, |s, &p| print_pat(s, p));
1691         if elts.len() == 1 {
1692             word(&mut s.s, ",");
1693         }
1694         pclose(s);
1695       }
1696       ast::PatUniq(inner) => {
1697           word(&mut s.s, "~");
1698           print_pat(s, inner);
1699       }
1700       ast::PatRegion(inner) => {
1701           word(&mut s.s, "&");
1702           print_pat(s, inner);
1703       }
1704       ast::PatLit(e) => print_expr(s, e),
1705       ast::PatRange(begin, end) => {
1706         print_expr(s, begin);
1707         space(&mut s.s);
1708         word(&mut s.s, "..");
1709         print_expr(s, end);
1710       }
1711       ast::PatVec(ref before, slice, ref after) => {
1712         word(&mut s.s, "[");
1713         commasep(s, Inconsistent, *before, |s, &p| print_pat(s, p));
1714         for &p in slice.iter() {
1715             if !before.is_empty() { word_space(s, ","); }
1716             match *p {
1717                 ast::Pat { node: ast::PatWildMulti, .. } => {
1718                     // this case is handled by print_pat
1719                 }
1720                 _ => word(&mut s.s, ".."),
1721             }
1722             print_pat(s, p);
1723             if !after.is_empty() { word_space(s, ","); }
1724         }
1725         commasep(s, Inconsistent, *after, |s, &p| print_pat(s, p));
1726         word(&mut s.s, "]");
1727       }
1728     }
1729     {
1730         let ann_node = NodePat(s, pat);
1731         s.ann.post(ann_node);
1732     }
1733 }
1734
1735 pub fn explicit_self_to_str(explicit_self: &ast::ExplicitSelf_, intr: @IdentInterner) -> ~str {
1736     to_str(explicit_self, |a, &b| { print_explicit_self(a, b, ast::MutImmutable); () }, intr)
1737 }
1738
1739 // Returns whether it printed anything
1740 fn print_explicit_self(s: &mut State,
1741                        explicit_self: ast::ExplicitSelf_,
1742                        mutbl: ast::Mutability) -> bool {
1743     print_mutability(s, mutbl);
1744     match explicit_self {
1745         ast::SelfStatic => { return false; }
1746         ast::SelfValue => {
1747             word(&mut s.s, "self");
1748         }
1749         ast::SelfUniq => {
1750             word(&mut s.s, "~self");
1751         }
1752         ast::SelfRegion(ref lt, m) => {
1753             word(&mut s.s, "&");
1754             print_opt_lifetime(s, lt);
1755             print_mutability(s, m);
1756             word(&mut s.s, "self");
1757         }
1758         ast::SelfBox => {
1759             word(&mut s.s, "@self");
1760         }
1761     }
1762     return true;
1763 }
1764
1765 pub fn print_fn(s: &mut State,
1766                 decl: &ast::FnDecl,
1767                 purity: Option<ast::Purity>,
1768                 abis: AbiSet,
1769                 name: ast::Ident,
1770                 generics: &ast::Generics,
1771                 opt_explicit_self: Option<ast::ExplicitSelf_>,
1772                 vis: ast::Visibility) {
1773     head(s, "");
1774     print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis);
1775     nbsp(s);
1776     print_ident(s, name);
1777     print_generics(s, generics);
1778     print_fn_args_and_ret(s, decl, opt_explicit_self);
1779 }
1780
1781 pub fn print_fn_args(s: &mut State, decl: &ast::FnDecl,
1782                  opt_explicit_self: Option<ast::ExplicitSelf_>) {
1783     // It is unfortunate to duplicate the commasep logic, but we want the
1784     // self type and the args all in the same box.
1785     rbox(s, 0u, Inconsistent);
1786     let mut first = true;
1787     for &explicit_self in opt_explicit_self.iter() {
1788         let m = match explicit_self {
1789             ast::SelfStatic => ast::MutImmutable,
1790             _ => match decl.inputs[0].pat.node {
1791                 ast::PatIdent(ast::BindByValue(m), _, _) => m,
1792                 _ => ast::MutImmutable
1793             }
1794         };
1795         first = !print_explicit_self(s, explicit_self, m);
1796     }
1797
1798     // HACK(eddyb) ignore the separately printed self argument.
1799     let args = if first {
1800         decl.inputs.as_slice()
1801     } else {
1802         decl.inputs.slice_from(1)
1803     };
1804
1805     for arg in args.iter() {
1806         if first { first = false; } else { word_space(s, ","); }
1807         print_arg(s, arg);
1808     }
1809
1810     end(s);
1811 }
1812
1813 pub fn print_fn_args_and_ret(s: &mut State, decl: &ast::FnDecl,
1814                              opt_explicit_self: Option<ast::ExplicitSelf_>) {
1815     popen(s);
1816     print_fn_args(s, decl, opt_explicit_self);
1817     if decl.variadic {
1818         word(&mut s.s, ", ...");
1819     }
1820     pclose(s);
1821
1822     maybe_print_comment(s, decl.output.span.lo);
1823     match decl.output.node {
1824         ast::TyNil => {}
1825         _ => {
1826             space_if_not_bol(s);
1827             word_space(s, "->");
1828             print_type(s, decl.output);
1829         }
1830     }
1831 }
1832
1833 pub fn print_fn_block_args(s: &mut State, decl: &ast::FnDecl) {
1834     word(&mut s.s, "|");
1835     print_fn_args(s, decl, None);
1836     word(&mut s.s, "|");
1837
1838     match decl.output.node {
1839         ast::TyInfer => {}
1840         _ => {
1841             space_if_not_bol(s);
1842             word_space(s, "->");
1843             print_type(s, decl.output);
1844         }
1845     }
1846
1847     maybe_print_comment(s, decl.output.span.lo);
1848 }
1849
1850 pub fn print_proc_args(s: &mut State, decl: &ast::FnDecl) {
1851     word(&mut s.s, "proc");
1852     word(&mut s.s, "(");
1853     print_fn_args(s, decl, None);
1854     word(&mut s.s, ")");
1855
1856     match decl.output.node {
1857         ast::TyInfer => {}
1858         _ => {
1859             space_if_not_bol(s);
1860             word_space(s, "->");
1861             print_type(s, decl.output);
1862         }
1863     }
1864
1865     maybe_print_comment(s, decl.output.span.lo);
1866 }
1867
1868 pub fn print_bounds(s: &mut State, bounds: &OptVec<ast::TyParamBound>,
1869                     print_colon_anyway: bool) {
1870     if !bounds.is_empty() {
1871         word(&mut s.s, ":");
1872         let mut first = true;
1873         for bound in bounds.iter() {
1874             nbsp(s);
1875             if first {
1876                 first = false;
1877             } else {
1878                 word_space(s, "+");
1879             }
1880
1881             match *bound {
1882                 TraitTyParamBound(ref tref) => print_trait_ref(s, tref),
1883                 RegionTyParamBound => word(&mut s.s, "'static"),
1884             }
1885         }
1886     } else if print_colon_anyway {
1887         word(&mut s.s, ":");
1888     }
1889 }
1890
1891 pub fn print_lifetime(s: &mut State, lifetime: &ast::Lifetime) {
1892     word(&mut s.s, "'");
1893     print_ident(s, lifetime.ident);
1894 }
1895
1896 pub fn print_generics(s: &mut State, generics: &ast::Generics) {
1897     let total = generics.lifetimes.len() + generics.ty_params.len();
1898     if total > 0 {
1899         word(&mut s.s, "<");
1900         fn print_item(s: &mut State, generics: &ast::Generics, idx: uint) {
1901             if idx < generics.lifetimes.len() {
1902                 let lifetime = generics.lifetimes.get(idx);
1903                 print_lifetime(s, lifetime);
1904             } else {
1905                 let idx = idx - generics.lifetimes.len();
1906                 let param = generics.ty_params.get(idx);
1907                 print_ident(s, param.ident);
1908                 print_bounds(s, &param.bounds, false);
1909                 match param.default {
1910                     Some(default) => {
1911                         space(&mut s.s);
1912                         word_space(s, "=");
1913                         print_type(s, default);
1914                     }
1915                     _ => {}
1916                 }
1917             }
1918         }
1919
1920         let mut ints = ~[];
1921         for i in range(0u, total) {
1922             ints.push(i);
1923         }
1924
1925         commasep(s, Inconsistent, ints,
1926                  |s, &i| print_item(s, generics, i));
1927         word(&mut s.s, ">");
1928     }
1929 }
1930
1931 pub fn print_meta_item(s: &mut State, item: &ast::MetaItem) {
1932     ibox(s, indent_unit);
1933     match item.node {
1934       ast::MetaWord(ref name) => word(&mut s.s, name.get()),
1935       ast::MetaNameValue(ref name, ref value) => {
1936         word_space(s, name.get());
1937         word_space(s, "=");
1938         print_literal(s, value);
1939       }
1940       ast::MetaList(ref name, ref items) => {
1941         word(&mut s.s, name.get());
1942         popen(s);
1943         commasep(s,
1944                  Consistent,
1945                  items.as_slice(),
1946                  |p, &i| print_meta_item(p, i));
1947         pclose(s);
1948       }
1949     }
1950     end(s);
1951 }
1952
1953 pub fn print_view_path(s: &mut State, vp: &ast::ViewPath) {
1954     match vp.node {
1955       ast::ViewPathSimple(ident, ref path, _) => {
1956         // FIXME(#6993) can't compare identifiers directly here
1957         if path.segments.last().unwrap().identifier.name != ident.name {
1958             print_ident(s, ident);
1959             space(&mut s.s);
1960             word_space(s, "=");
1961         }
1962         print_path(s, path, false);
1963       }
1964
1965       ast::ViewPathGlob(ref path, _) => {
1966         print_path(s, path, false);
1967         word(&mut s.s, "::*");
1968       }
1969
1970       ast::ViewPathList(ref path, ref idents, _) => {
1971         if path.segments.is_empty() {
1972             word(&mut s.s, "{");
1973         } else {
1974             print_path(s, path, false);
1975             word(&mut s.s, "::{");
1976         }
1977         commasep(s, Inconsistent, (*idents), |s, w| {
1978             print_ident(s, w.node.name);
1979         });
1980         word(&mut s.s, "}");
1981       }
1982     }
1983 }
1984
1985 pub fn print_view_paths(s: &mut State, vps: &[@ast::ViewPath]) {
1986     commasep(s, Inconsistent, vps, |p, &vp| print_view_path(p, vp));
1987 }
1988
1989 pub fn print_view_item(s: &mut State, item: &ast::ViewItem) {
1990     hardbreak_if_not_bol(s);
1991     maybe_print_comment(s, item.span.lo);
1992     print_outer_attributes(s, item.attrs);
1993     print_visibility(s, item.vis);
1994     match item.node {
1995         ast::ViewItemExternMod(id, ref optional_path, _) => {
1996             head(s, "extern mod");
1997             print_ident(s, id);
1998             for &(ref p, style) in optional_path.iter() {
1999                 space(&mut s.s);
2000                 word(&mut s.s, "=");
2001                 space(&mut s.s);
2002                 print_string(s, p.get(), style);
2003             }
2004         }
2005
2006         ast::ViewItemUse(ref vps) => {
2007             head(s, "use");
2008             print_view_paths(s, *vps);
2009         }
2010     }
2011     word(&mut s.s, ";");
2012     end(s); // end inner head-block
2013     end(s); // end outer head-block
2014 }
2015
2016 pub fn print_mutability(s: &mut State, mutbl: ast::Mutability) {
2017     match mutbl {
2018       ast::MutMutable => word_nbsp(s, "mut"),
2019       ast::MutImmutable => {/* nothing */ }
2020     }
2021 }
2022
2023 pub fn print_mt(s: &mut State, mt: &ast::MutTy) {
2024     print_mutability(s, mt.mutbl);
2025     print_type(s, mt.ty);
2026 }
2027
2028 pub fn print_arg(s: &mut State, input: &ast::Arg) {
2029     ibox(s, indent_unit);
2030     match input.ty.node {
2031         ast::TyInfer => print_pat(s, input.pat),
2032         _ => {
2033             match input.pat.node {
2034                 ast::PatIdent(_, ref path, _) if
2035                     path.segments.len() == 1 &&
2036                     path.segments[0].identifier.name ==
2037                         parse::token::special_idents::invalid.name => {
2038                     // Do nothing.
2039                 }
2040                 _ => {
2041                     print_pat(s, input.pat);
2042                     word(&mut s.s, ":");
2043                     space(&mut s.s);
2044                 }
2045             }
2046             print_type(s, input.ty);
2047         }
2048     }
2049     end(s);
2050 }
2051
2052 pub fn print_ty_fn(s: &mut State,
2053                    opt_abis: Option<AbiSet>,
2054                    opt_sigil: Option<ast::Sigil>,
2055                    opt_region: &Option<ast::Lifetime>,
2056                    purity: ast::Purity,
2057                    onceness: ast::Onceness,
2058                    decl: &ast::FnDecl,
2059                    id: Option<ast::Ident>,
2060                    opt_bounds: &Option<OptVec<ast::TyParamBound>>,
2061                    generics: Option<&ast::Generics>,
2062                    opt_explicit_self: Option<ast::ExplicitSelf_>) {
2063     ibox(s, indent_unit);
2064
2065     // Duplicates the logic in `print_fn_header_info()`.  This is because that
2066     // function prints the sigil in the wrong place.  That should be fixed.
2067     if opt_sigil == Some(ast::OwnedSigil) && onceness == ast::Once {
2068         word(&mut s.s, "proc");
2069     } else if opt_sigil == Some(ast::BorrowedSigil) {
2070         print_extern_opt_abis(s, opt_abis);
2071         for lifetime in opt_region.iter() {
2072             print_lifetime(s, lifetime);
2073         }
2074         print_purity(s, purity);
2075         print_onceness(s, onceness);
2076     } else {
2077         print_opt_abis_and_extern_if_nondefault(s, opt_abis);
2078         print_opt_sigil(s, opt_sigil);
2079         print_opt_lifetime(s, opt_region);
2080         print_purity(s, purity);
2081         print_onceness(s, onceness);
2082         word(&mut s.s, "fn");
2083     }
2084
2085     match id { Some(id) => { word(&mut s.s, " "); print_ident(s, id); } _ => () }
2086
2087     if opt_sigil != Some(ast::BorrowedSigil) {
2088         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2089     }
2090
2091     match generics { Some(g) => print_generics(s, g), _ => () }
2092     zerobreak(&mut s.s);
2093
2094     if opt_sigil == Some(ast::BorrowedSigil) {
2095         word(&mut s.s, "|");
2096     } else {
2097         popen(s);
2098     }
2099
2100     print_fn_args(s, decl, opt_explicit_self);
2101
2102     if opt_sigil == Some(ast::BorrowedSigil) {
2103         word(&mut s.s, "|");
2104
2105         opt_bounds.as_ref().map(|bounds| print_bounds(s, bounds, true));
2106     } else {
2107         if decl.variadic {
2108             word(&mut s.s, ", ...");
2109         }
2110         pclose(s);
2111     }
2112
2113     maybe_print_comment(s, decl.output.span.lo);
2114
2115     match decl.output.node {
2116         ast::TyNil => {}
2117         _ => {
2118             space_if_not_bol(s);
2119             ibox(s, indent_unit);
2120             word_space(s, "->");
2121             if decl.cf == ast::NoReturn { word_nbsp(s, "!"); }
2122             else { print_type(s, decl.output); }
2123             end(s);
2124         }
2125     }
2126
2127     end(s);
2128 }
2129
2130 pub fn maybe_print_trailing_comment(s: &mut State, span: codemap::Span,
2131                                     next_pos: Option<BytePos>) {
2132     let cm;
2133     match s.cm { Some(ccm) => cm = ccm, _ => return }
2134     match next_comment(s) {
2135       Some(ref cmnt) => {
2136         if (*cmnt).style != comments::Trailing { return; }
2137         let span_line = cm.lookup_char_pos(span.hi);
2138         let comment_line = cm.lookup_char_pos((*cmnt).pos);
2139         let mut next = (*cmnt).pos + BytePos(1);
2140         match next_pos { None => (), Some(p) => next = p }
2141         if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2142                span_line.line == comment_line.line {
2143             print_comment(s, cmnt);
2144             s.cur_cmnt_and_lit.cur_cmnt += 1u;
2145         }
2146       }
2147       _ => ()
2148     }
2149 }
2150
2151 pub fn print_remaining_comments(s: &mut State) {
2152     // If there aren't any remaining comments, then we need to manually
2153     // make sure there is a line break at the end.
2154     if next_comment(s).is_none() { hardbreak(&mut s.s); }
2155     loop {
2156         match next_comment(s) {
2157           Some(ref cmnt) => {
2158             print_comment(s, cmnt);
2159             s.cur_cmnt_and_lit.cur_cmnt += 1u;
2160           }
2161           _ => break
2162         }
2163     }
2164 }
2165
2166 pub fn print_literal(s: &mut State, lit: &ast::Lit) {
2167     maybe_print_comment(s, lit.span.lo);
2168     match next_lit(s, lit.span.lo) {
2169       Some(ref ltrl) => {
2170         word(&mut s.s, (*ltrl).lit);
2171         return;
2172       }
2173       _ => ()
2174     }
2175     match lit.node {
2176       ast::LitStr(ref st, style) => print_string(s, st.get(), style),
2177       ast::LitChar(ch) => {
2178           let mut res = ~"'";
2179           char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2180           res.push_char('\'');
2181           word(&mut s.s, res);
2182       }
2183       ast::LitInt(i, t) => {
2184         if i < 0_i64 {
2185             word(&mut s.s,
2186                  ~"-" + (-i as u64).to_str_radix(10u)
2187                  + ast_util::int_ty_to_str(t));
2188         } else {
2189             word(&mut s.s,
2190                  (i as u64).to_str_radix(10u)
2191                  + ast_util::int_ty_to_str(t));
2192         }
2193       }
2194       ast::LitUint(u, t) => {
2195         word(&mut s.s,
2196              u.to_str_radix(10u)
2197              + ast_util::uint_ty_to_str(t));
2198       }
2199       ast::LitIntUnsuffixed(i) => {
2200         if i < 0_i64 {
2201             word(&mut s.s, ~"-" + (-i as u64).to_str_radix(10u));
2202         } else {
2203             word(&mut s.s, (i as u64).to_str_radix(10u));
2204         }
2205       }
2206       ast::LitFloat(ref f, t) => {
2207         word(&mut s.s, f.get() + ast_util::float_ty_to_str(t));
2208       }
2209       ast::LitFloatUnsuffixed(ref f) => word(&mut s.s, f.get()),
2210       ast::LitNil => word(&mut s.s, "()"),
2211       ast::LitBool(val) => {
2212         if val { word(&mut s.s, "true"); } else { word(&mut s.s, "false"); }
2213       }
2214       ast::LitBinary(arr) => {
2215         ibox(s, indent_unit);
2216         word(&mut s.s, "[");
2217         commasep_cmnt(s, Inconsistent, arr, |s, u| word(&mut s.s, format!("{}", *u)),
2218                       |_| lit.span);
2219         word(&mut s.s, "]");
2220         end(s);
2221       }
2222     }
2223 }
2224
2225 pub fn lit_to_str(l: &ast::Lit) -> ~str {
2226     return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
2227 }
2228
2229 pub fn next_lit(s: &mut State, pos: BytePos) -> Option<comments::Literal> {
2230     match s.literals {
2231       Some(ref lits) => {
2232         while s.cur_cmnt_and_lit.cur_lit < lits.len() {
2233             let ltrl = (*lits)[s.cur_cmnt_and_lit.cur_lit].clone();
2234             if ltrl.pos > pos { return None; }
2235             s.cur_cmnt_and_lit.cur_lit += 1u;
2236             if ltrl.pos == pos { return Some(ltrl); }
2237         }
2238         return None;
2239       }
2240       _ => return None
2241     }
2242 }
2243
2244 pub fn maybe_print_comment(s: &mut State, pos: BytePos) {
2245     loop {
2246         match next_comment(s) {
2247           Some(ref cmnt) => {
2248             if (*cmnt).pos < pos {
2249                 print_comment(s, cmnt);
2250                 s.cur_cmnt_and_lit.cur_cmnt += 1u;
2251             } else { break; }
2252           }
2253           _ => break
2254         }
2255     }
2256 }
2257
2258 pub fn print_comment(s: &mut State, cmnt: &comments::Comment) {
2259     match cmnt.style {
2260         comments::Mixed => {
2261             assert_eq!(cmnt.lines.len(), 1u);
2262             zerobreak(&mut s.s);
2263             word(&mut s.s, cmnt.lines[0]);
2264             zerobreak(&mut s.s);
2265         }
2266         comments::Isolated => {
2267             pprust::hardbreak_if_not_bol(s);
2268             for line in cmnt.lines.iter() {
2269                 // Don't print empty lines because they will end up as trailing
2270                 // whitespace
2271                 if !line.is_empty() { word(&mut s.s, *line); }
2272                 hardbreak(&mut s.s);
2273             }
2274         }
2275         comments::Trailing => {
2276             word(&mut s.s, " ");
2277             if cmnt.lines.len() == 1u {
2278                 word(&mut s.s, cmnt.lines[0]);
2279                 hardbreak(&mut s.s);
2280             } else {
2281                 ibox(s, 0u);
2282                 for line in cmnt.lines.iter() {
2283                     if !line.is_empty() { word(&mut s.s, *line); }
2284                     hardbreak(&mut s.s);
2285                 }
2286                 end(s);
2287             }
2288         }
2289         comments::BlankLine => {
2290             // We need to do at least one, possibly two hardbreaks.
2291             let is_semi = match s.s.last_token() {
2292                 pp::String(s, _) => ";" == s,
2293                 _ => false
2294             };
2295             if is_semi || is_begin(s) || is_end(s) { hardbreak(&mut s.s); }
2296             hardbreak(&mut s.s);
2297         }
2298     }
2299 }
2300
2301 pub fn print_string(s: &mut State, st: &str, style: ast::StrStyle) {
2302     let st = match style {
2303         ast::CookedStr => format!("\"{}\"", st.escape_default()),
2304         ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2305                                   delim="#".repeat(n), string=st)
2306     };
2307     word(&mut s.s, st);
2308 }
2309
2310 // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
2311 // that we "know" to be a `MemWriter` that works around the lack of checked
2312 // downcasts.
2313 unsafe fn get_mem_writer(writer: &mut ~io::Writer) -> ~str {
2314     let (_, wr): (uint, ~MemWriter) = cast::transmute_copy(writer);
2315     let result = str::from_utf8_owned(wr.get_ref().to_owned()).unwrap();
2316     cast::forget(wr);
2317     result
2318 }
2319
2320 pub fn to_str<T>(t: &T, f: |&mut State, &T|, intr: @IdentInterner) -> ~str {
2321     let wr = ~MemWriter::new();
2322     let mut s = rust_printer(wr as ~io::Writer, intr);
2323     f(&mut s, t);
2324     eof(&mut s.s);
2325     unsafe {
2326         get_mem_writer(&mut s.s.out)
2327     }
2328 }
2329
2330 pub fn next_comment(s: &mut State) -> Option<comments::Comment> {
2331     match s.comments {
2332         Some(ref cmnts) => {
2333             if s.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2334                 Some(cmnts[s.cur_cmnt_and_lit.cur_cmnt].clone())
2335             } else {
2336                 None
2337             }
2338         }
2339         _ => None
2340     }
2341 }
2342
2343 pub fn print_opt_purity(s: &mut State, opt_purity: Option<ast::Purity>) {
2344     match opt_purity {
2345         Some(ast::ImpureFn) => { }
2346         Some(purity) => {
2347             word_nbsp(s, purity_to_str(purity));
2348         }
2349         None => {}
2350     }
2351 }
2352
2353 pub fn print_opt_abis_and_extern_if_nondefault(s: &mut State,
2354                                                opt_abis: Option<AbiSet>) {
2355     match opt_abis {
2356         Some(abis) if !abis.is_rust() => {
2357             word_nbsp(s, "extern");
2358             word_nbsp(s, abis.to_str());
2359         }
2360         Some(_) | None => {}
2361     };
2362 }
2363
2364 pub fn print_extern_opt_abis(s: &mut State, opt_abis: Option<AbiSet>) {
2365     match opt_abis {
2366         Some(abis) => {
2367             word_nbsp(s, "extern");
2368             word_nbsp(s, abis.to_str());
2369         }
2370         None => {}
2371     };
2372 }
2373
2374 pub fn print_opt_sigil(s: &mut State, opt_sigil: Option<ast::Sigil>) {
2375     match opt_sigil {
2376         Some(ast::BorrowedSigil) => { word(&mut s.s, "&"); }
2377         Some(ast::OwnedSigil) => { word(&mut s.s, "~"); }
2378         Some(ast::ManagedSigil) => { word(&mut s.s, "@"); }
2379         None => {}
2380     };
2381 }
2382
2383 pub fn print_fn_header_info(s: &mut State,
2384                             _opt_explicit_self: Option<ast::ExplicitSelf_>,
2385                             opt_purity: Option<ast::Purity>,
2386                             abis: AbiSet,
2387                             onceness: ast::Onceness,
2388                             opt_sigil: Option<ast::Sigil>,
2389                             vis: ast::Visibility) {
2390     word(&mut s.s, visibility_qualified(vis, ""));
2391
2392     if abis != AbiSet::Rust() {
2393         word_nbsp(s, "extern");
2394         word_nbsp(s, abis.to_str());
2395
2396         if opt_purity != Some(ast::ExternFn) {
2397             print_opt_purity(s, opt_purity);
2398         }
2399     } else {
2400         print_opt_purity(s, opt_purity);
2401     }
2402
2403     print_onceness(s, onceness);
2404     word(&mut s.s, "fn");
2405     print_opt_sigil(s, opt_sigil);
2406 }
2407
2408 pub fn purity_to_str(p: ast::Purity) -> &'static str {
2409     match p {
2410       ast::ImpureFn => "impure",
2411       ast::UnsafeFn => "unsafe",
2412       ast::ExternFn => "extern"
2413     }
2414 }
2415
2416 pub fn onceness_to_str(o: ast::Onceness) -> &'static str {
2417     match o {
2418         ast::Once => "once",
2419         ast::Many => "many"
2420     }
2421 }
2422
2423 pub fn print_purity(s: &mut State, p: ast::Purity) {
2424     match p {
2425       ast::ImpureFn => (),
2426       _ => word_nbsp(s, purity_to_str(p))
2427     }
2428 }
2429
2430 pub fn print_onceness(s: &mut State, o: ast::Onceness) {
2431     match o {
2432         ast::Once => { word_nbsp(s, "once"); }
2433         ast::Many => {}
2434     }
2435 }
2436
2437 #[cfg(test)]
2438 mod test {
2439     use super::*;
2440
2441     use ast;
2442     use ast_util;
2443     use codemap;
2444     use parse::token;
2445
2446     #[test]
2447     fn test_fun_to_str() {
2448         let abba_ident = token::str_to_ident("abba");
2449
2450         let decl = ast::FnDecl {
2451             inputs: ~[],
2452             output: ast::P(ast::Ty {id: 0,
2453                                     node: ast::TyNil,
2454                                     span: codemap::DUMMY_SP}),
2455             cf: ast::Return,
2456             variadic: false
2457         };
2458         let generics = ast_util::empty_generics();
2459         assert_eq!(&fun_to_str(&decl, ast::ImpureFn, abba_ident,
2460                                None, &generics, token::get_ident_interner()),
2461                    &~"fn abba()");
2462     }
2463
2464     #[test]
2465     fn test_variant_to_str() {
2466         let ident = token::str_to_ident("principal_skinner");
2467
2468         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2469             name: ident,
2470             attrs: ~[],
2471             // making this up as I go.... ?
2472             kind: ast::TupleVariantKind(~[]),
2473             id: 0,
2474             disr_expr: None,
2475             vis: ast::Public,
2476         });
2477
2478         let varstr = variant_to_str(&var,token::get_ident_interner());
2479         assert_eq!(&varstr,&~"pub principal_skinner");
2480     }
2481 }