]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
Add a special macro nonterminal $crate
[rust.git] / src / libsyntax / print / pprust.rs
1 // Copyright 2012-2014 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 pub use self::AnnNode::*;
12
13 use abi;
14 use ast::{self, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
15 use ast::{FnOnceUnboxedClosureKind};
16 use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
18 use ast::{UnboxedClosureKind};
19 use ast_util;
20 use owned_slice::OwnedSlice;
21 use attr::{AttrMetaMethods, AttributeMethods};
22 use codemap::{self, CodeMap, BytePos};
23 use diagnostic;
24 use parse::token::{self, BinOpToken, Token};
25 use parse::lexer::comments;
26 use parse;
27 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
28 use print::pp::{Breaks, Consistent, Inconsistent, eof};
29 use ptr::P;
30
31 use std::{ascii, mem};
32 use std::io::{self, IoResult};
33 use std::iter;
34
35 pub enum AnnNode<'a> {
36     NodeIdent(&'a ast::Ident),
37     NodeName(&'a ast::Name),
38     NodeBlock(&'a ast::Block),
39     NodeItem(&'a ast::Item),
40     NodeExpr(&'a ast::Expr),
41     NodePat(&'a ast::Pat),
42 }
43
44 pub trait PpAnn {
45     fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
46     fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
47 }
48
49 #[derive(Copy)]
50 pub struct NoAnn;
51
52 impl PpAnn for NoAnn {}
53
54 #[derive(Copy)]
55 pub struct CurrentCommentAndLiteral {
56     cur_cmnt: uint,
57     cur_lit: uint,
58 }
59
60 pub struct State<'a> {
61     pub s: pp::Printer,
62     cm: Option<&'a CodeMap>,
63     comments: Option<Vec<comments::Comment> >,
64     literals: Option<Vec<comments::Literal> >,
65     cur_cmnt_and_lit: CurrentCommentAndLiteral,
66     boxes: Vec<pp::Breaks>,
67     ann: &'a (PpAnn+'a),
68     encode_idents_with_hygiene: bool,
69 }
70
71 pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> {
72     static NO_ANN: NoAnn = NoAnn;
73     rust_printer_annotated(writer, &NO_ANN)
74 }
75
76 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>,
77                                   ann: &'a PpAnn) -> State<'a> {
78     State {
79         s: pp::mk_printer(writer, default_columns),
80         cm: None,
81         comments: None,
82         literals: None,
83         cur_cmnt_and_lit: CurrentCommentAndLiteral {
84             cur_cmnt: 0,
85             cur_lit: 0
86         },
87         boxes: Vec::new(),
88         ann: ann,
89         encode_idents_with_hygiene: false,
90     }
91 }
92
93 #[allow(non_upper_case_globals)]
94 pub const indent_unit: uint = 4u;
95
96 #[allow(non_upper_case_globals)]
97 pub const default_columns: uint = 78u;
98
99 /// Requires you to pass an input filename and reader so that
100 /// it can scan the input text for comments and literals to
101 /// copy forward.
102 pub fn print_crate<'a>(cm: &'a CodeMap,
103                        span_diagnostic: &diagnostic::SpanHandler,
104                        krate: &ast::Crate,
105                        filename: String,
106                        input: &mut io::Reader,
107                        out: Box<io::Writer+'static>,
108                        ann: &'a PpAnn,
109                        is_expanded: bool) -> IoResult<()> {
110     let mut s = State::new_from_input(cm,
111                                       span_diagnostic,
112                                       filename,
113                                       input,
114                                       out,
115                                       ann,
116                                       is_expanded);
117     try!(s.print_mod(&krate.module, krate.attrs[]));
118     try!(s.print_remaining_comments());
119     eof(&mut s.s)
120 }
121
122 impl<'a> State<'a> {
123     pub fn new_from_input(cm: &'a CodeMap,
124                           span_diagnostic: &diagnostic::SpanHandler,
125                           filename: String,
126                           input: &mut io::Reader,
127                           out: Box<io::Writer+'static>,
128                           ann: &'a PpAnn,
129                           is_expanded: bool) -> State<'a> {
130         let (cmnts, lits) = comments::gather_comments_and_literals(
131             span_diagnostic,
132             filename,
133             input);
134
135         State::new(
136             cm,
137             out,
138             ann,
139             Some(cmnts),
140             // If the code is post expansion, don't use the table of
141             // literals, since it doesn't correspond with the literals
142             // in the AST anymore.
143             if is_expanded { None } else { Some(lits) })
144     }
145
146     pub fn new(cm: &'a CodeMap,
147                out: Box<io::Writer+'static>,
148                ann: &'a PpAnn,
149                comments: Option<Vec<comments::Comment>>,
150                literals: Option<Vec<comments::Literal>>) -> State<'a> {
151         State {
152             s: pp::mk_printer(out, default_columns),
153             cm: Some(cm),
154             comments: comments,
155             literals: literals,
156             cur_cmnt_and_lit: CurrentCommentAndLiteral {
157                 cur_cmnt: 0,
158                 cur_lit: 0
159             },
160             boxes: Vec::new(),
161             ann: ann,
162             encode_idents_with_hygiene: false,
163         }
164     }
165 }
166
167 pub fn to_string<F>(f: F) -> String where
168     F: FnOnce(&mut State) -> IoResult<()>,
169 {
170     use std::raw::TraitObject;
171     let mut s = rust_printer(box Vec::new());
172     f(&mut s).unwrap();
173     eof(&mut s.s).unwrap();
174     let wr = unsafe {
175         // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
176         // that we "know" to be a `Vec<u8>` that works around the lack of checked
177         // downcasts.
178         let obj: &TraitObject = mem::transmute(&s.s.out);
179         mem::transmute::<*mut (), &Vec<u8>>(obj.data)
180     };
181     String::from_utf8(wr.clone()).unwrap()
182 }
183
184 pub fn binop_to_string(op: BinOpToken) -> &'static str {
185     match op {
186         token::Plus     => "+",
187         token::Minus    => "-",
188         token::Star     => "*",
189         token::Slash    => "/",
190         token::Percent  => "%",
191         token::Caret    => "^",
192         token::And      => "&",
193         token::Or       => "|",
194         token::Shl      => "<<",
195         token::Shr      => ">>",
196     }
197 }
198
199 pub fn token_to_string(tok: &Token) -> String {
200     match *tok {
201         token::Eq                   => "=".to_string(),
202         token::Lt                   => "<".to_string(),
203         token::Le                   => "<=".to_string(),
204         token::EqEq                 => "==".to_string(),
205         token::Ne                   => "!=".to_string(),
206         token::Ge                   => ">=".to_string(),
207         token::Gt                   => ">".to_string(),
208         token::Not                  => "!".to_string(),
209         token::Tilde                => "~".to_string(),
210         token::OrOr                 => "||".to_string(),
211         token::AndAnd               => "&&".to_string(),
212         token::BinOp(op)            => binop_to_string(op).to_string(),
213         token::BinOpEq(op)          => format!("{}=", binop_to_string(op)),
214
215         /* Structural symbols */
216         token::At                   => "@".to_string(),
217         token::Dot                  => ".".to_string(),
218         token::DotDot               => "..".to_string(),
219         token::DotDotDot            => "...".to_string(),
220         token::Comma                => ",".to_string(),
221         token::Semi                 => ";".to_string(),
222         token::Colon                => ":".to_string(),
223         token::ModSep               => "::".to_string(),
224         token::RArrow               => "->".to_string(),
225         token::LArrow               => "<-".to_string(),
226         token::FatArrow             => "=>".to_string(),
227         token::OpenDelim(token::Paren) => "(".to_string(),
228         token::CloseDelim(token::Paren) => ")".to_string(),
229         token::OpenDelim(token::Bracket) => "[".to_string(),
230         token::CloseDelim(token::Bracket) => "]".to_string(),
231         token::OpenDelim(token::Brace) => "{".to_string(),
232         token::CloseDelim(token::Brace) => "}".to_string(),
233         token::Pound                => "#".to_string(),
234         token::Dollar               => "$".to_string(),
235         token::Question             => "?".to_string(),
236
237         /* Literals */
238         token::Literal(lit, suf) => {
239             let mut out = match lit {
240                 token::Byte(b)           => format!("b'{}'", b.as_str()),
241                 token::Char(c)           => format!("'{}'", c.as_str()),
242                 token::Float(c)          => c.as_str().to_string(),
243                 token::Integer(c)        => c.as_str().to_string(),
244                 token::Str_(s)           => format!("\"{}\"", s.as_str()),
245                 token::StrRaw(s, n)      => format!("r{delim}\"{string}\"{delim}",
246                                                     delim=repeat("#", n),
247                                                     string=s.as_str()),
248                 token::Binary(v)         => format!("b\"{}\"", v.as_str()),
249                 token::BinaryRaw(s, n)   => format!("br{delim}\"{string}\"{delim}",
250                                                     delim=repeat("#", n),
251                                                     string=s.as_str()),
252             };
253
254             if let Some(s) = suf {
255                 out.push_str(s.as_str())
256             }
257
258             out
259         }
260
261         /* Name components */
262         token::Ident(s, _)          => token::get_ident(s).get().to_string(),
263         token::Lifetime(s)          => format!("{}", token::get_ident(s)),
264         token::Underscore           => "_".to_string(),
265
266         /* Other */
267         token::DocComment(s)        => s.as_str().to_string(),
268         token::SubstNt(s, _)        => format!("${}", s),
269         token::MatchNt(s, t, _, _)  => format!("${}:{}", s, t),
270         token::Eof                  => "<eof>".to_string(),
271         token::Whitespace           => " ".to_string(),
272         token::Comment              => "/* */".to_string(),
273         token::Shebang(s)           => format!("/* shebang: {}*/", s.as_str()),
274
275         token::SpecialVarNt(var)    => format!("${}", var.as_str()),
276
277         token::Interpolated(ref nt) => match *nt {
278             token::NtExpr(ref e)  => expr_to_string(&**e),
279             token::NtMeta(ref e)  => meta_item_to_string(&**e),
280             token::NtTy(ref e)    => ty_to_string(&**e),
281             token::NtPath(ref e)  => path_to_string(&**e),
282             token::NtItem(..)     => "an interpolated item".to_string(),
283             token::NtBlock(..)    => "an interpolated block".to_string(),
284             token::NtStmt(..)     => "an interpolated statement".to_string(),
285             token::NtPat(..)      => "an interpolated pattern".to_string(),
286             token::NtIdent(..)    => "an interpolated identifier".to_string(),
287             token::NtTT(..)       => "an interpolated tt".to_string(),
288         }
289     }
290 }
291
292 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
293 // after we revise the syntax::ext::quote::ToToken impls to go directly
294 // to token-trees instead of thing -> string -> token-trees.
295
296 macro_rules! thing_to_string_impls {
297     ($to_string:ident) => {
298
299 pub fn ty_to_string(ty: &ast::Ty) -> String {
300     $to_string(|s| s.print_type(ty))
301 }
302
303 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
304     $to_string(|s| s.print_bounds("", bounds))
305 }
306
307 pub fn pat_to_string(pat: &ast::Pat) -> String {
308     $to_string(|s| s.print_pat(pat))
309 }
310
311 pub fn arm_to_string(arm: &ast::Arm) -> String {
312     $to_string(|s| s.print_arm(arm))
313 }
314
315 pub fn expr_to_string(e: &ast::Expr) -> String {
316     $to_string(|s| s.print_expr(e))
317 }
318
319 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
320     $to_string(|s| s.print_lifetime(e))
321 }
322
323 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
324     $to_string(|s| s.print_tt(tt))
325 }
326
327 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
328     $to_string(|s| s.print_tts(tts))
329 }
330
331 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
332     $to_string(|s| s.print_stmt(stmt))
333 }
334
335 pub fn item_to_string(i: &ast::Item) -> String {
336     $to_string(|s| s.print_item(i))
337 }
338
339 pub fn view_item_to_string(i: &ast::ViewItem) -> String {
340     $to_string(|s| s.print_view_item(i))
341 }
342
343 pub fn generics_to_string(generics: &ast::Generics) -> String {
344     $to_string(|s| s.print_generics(generics))
345 }
346
347 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
348     $to_string(|s| s.print_ty_method(p))
349 }
350
351 pub fn method_to_string(p: &ast::Method) -> String {
352     $to_string(|s| s.print_method(p))
353 }
354
355 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
356     $to_string(|s| s.print_fn_block_args(p, None))
357 }
358
359 pub fn path_to_string(p: &ast::Path) -> String {
360     $to_string(|s| s.print_path(p, false))
361 }
362
363 pub fn ident_to_string(id: &ast::Ident) -> String {
364     $to_string(|s| s.print_ident(*id))
365 }
366
367 pub fn fun_to_string(decl: &ast::FnDecl, unsafety: ast::Unsafety, name: ast::Ident,
368                   opt_explicit_self: Option<&ast::ExplicitSelf_>,
369                   generics: &ast::Generics) -> String {
370     $to_string(|s| {
371         try!(s.print_fn(decl, Some(unsafety), abi::Rust,
372                         name, generics, opt_explicit_self, ast::Inherited));
373         try!(s.end()); // Close the head box
374         s.end() // Close the outer box
375     })
376 }
377
378 pub fn block_to_string(blk: &ast::Block) -> String {
379     $to_string(|s| {
380         // containing cbox, will be closed by print-block at }
381         try!(s.cbox(indent_unit));
382         // head-ibox, will be closed by print-block after {
383         try!(s.ibox(0u));
384         s.print_block(blk)
385     })
386 }
387
388 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
389     $to_string(|s| s.print_meta_item(mi))
390 }
391
392 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
393     $to_string(|s| s.print_attribute(attr))
394 }
395
396 pub fn lit_to_string(l: &ast::Lit) -> String {
397     $to_string(|s| s.print_literal(l))
398 }
399
400 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
401     $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
402 }
403
404 pub fn variant_to_string(var: &ast::Variant) -> String {
405     $to_string(|s| s.print_variant(var))
406 }
407
408 pub fn arg_to_string(arg: &ast::Arg) -> String {
409     $to_string(|s| s.print_arg(arg))
410 }
411
412 pub fn mac_to_string(arg: &ast::Mac) -> String {
413     $to_string(|s| s.print_mac(arg, ::parse::token::Paren))
414 }
415
416 } }
417
418 thing_to_string_impls! { to_string }
419
420 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
421 // after we revise the syntax::ext::quote::ToToken impls to go directly
422 // to token-trees instea of thing -> string -> token-trees.
423
424 pub mod with_hygiene {
425     use abi;
426     use ast;
427     use std::io::IoResult;
428     use super::indent_unit;
429
430     // This function is the trick that all the rest of the routines
431     // hang on.
432     pub fn to_string_hyg<F>(f: F) -> String where
433         F: FnOnce(&mut super::State) -> IoResult<()>,
434     {
435         super::to_string(move |s| {
436             s.encode_idents_with_hygiene = true;
437             f(s)
438         })
439     }
440
441     thing_to_string_impls! { to_string_hyg }
442 }
443
444 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
445     match vis {
446         ast::Public => format!("pub {}", s),
447         ast::Inherited => s.to_string()
448     }
449 }
450
451 fn needs_parentheses(expr: &ast::Expr) -> bool {
452     match expr.node {
453         ast::ExprAssign(..) | ast::ExprBinary(..) |
454         ast::ExprClosure(..) |
455         ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
456         _ => false,
457     }
458 }
459
460 impl<'a> State<'a> {
461     pub fn ibox(&mut self, u: uint) -> IoResult<()> {
462         self.boxes.push(pp::Inconsistent);
463         pp::ibox(&mut self.s, u)
464     }
465
466     pub fn end(&mut self) -> IoResult<()> {
467         self.boxes.pop().unwrap();
468         pp::end(&mut self.s)
469     }
470
471     pub fn cbox(&mut self, u: uint) -> IoResult<()> {
472         self.boxes.push(pp::Consistent);
473         pp::cbox(&mut self.s, u)
474     }
475
476     // "raw box"
477     pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
478         self.boxes.push(b);
479         pp::rbox(&mut self.s, u, b)
480     }
481
482     pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
483
484     pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
485         try!(word(&mut self.s, w));
486         self.nbsp()
487     }
488
489     pub fn word_space(&mut self, w: &str) -> IoResult<()> {
490         try!(word(&mut self.s, w));
491         space(&mut self.s)
492     }
493
494     pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
495
496     pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
497
498     pub fn head(&mut self, w: &str) -> IoResult<()> {
499         // outer-box is consistent
500         try!(self.cbox(indent_unit));
501         // head-box is inconsistent
502         try!(self.ibox(w.len() + 1));
503         // keyword that starts the head
504         if !w.is_empty() {
505             try!(self.word_nbsp(w));
506         }
507         Ok(())
508     }
509
510     pub fn bopen(&mut self) -> IoResult<()> {
511         try!(word(&mut self.s, "{"));
512         self.end() // close the head-box
513     }
514
515     pub fn bclose_(&mut self, span: codemap::Span,
516                    indented: uint) -> IoResult<()> {
517         self.bclose_maybe_open(span, indented, true)
518     }
519     pub fn bclose_maybe_open (&mut self, span: codemap::Span,
520                               indented: uint, close_box: bool) -> IoResult<()> {
521         try!(self.maybe_print_comment(span.hi));
522         try!(self.break_offset_if_not_bol(1u, -(indented as int)));
523         try!(word(&mut self.s, "}"));
524         if close_box {
525             try!(self.end()); // close the outer-box
526         }
527         Ok(())
528     }
529     pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
530         self.bclose_(span, indent_unit)
531     }
532
533     pub fn is_begin(&mut self) -> bool {
534         match self.s.last_token() { pp::Begin(_) => true, _ => false }
535     }
536
537     pub fn is_end(&mut self) -> bool {
538         match self.s.last_token() { pp::End => true, _ => false }
539     }
540
541     // is this the beginning of a line?
542     pub fn is_bol(&mut self) -> bool {
543         self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
544     }
545
546     pub fn in_cbox(&self) -> bool {
547         match self.boxes.last() {
548             Some(&last_box) => last_box == pp::Consistent,
549             None => false
550         }
551     }
552
553     pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
554         if !self.is_bol() {
555             try!(hardbreak(&mut self.s))
556         }
557         Ok(())
558     }
559     pub fn space_if_not_bol(&mut self) -> IoResult<()> {
560         if !self.is_bol() { try!(space(&mut self.s)); }
561         Ok(())
562     }
563     pub fn break_offset_if_not_bol(&mut self, n: uint,
564                                    off: int) -> IoResult<()> {
565         if !self.is_bol() {
566             break_offset(&mut self.s, n, off)
567         } else {
568             if off != 0 && self.s.last_token().is_hardbreak_tok() {
569                 // We do something pretty sketchy here: tuck the nonzero
570                 // offset-adjustment we were going to deposit along with the
571                 // break into the previous hardbreak.
572                 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
573             }
574             Ok(())
575         }
576     }
577
578     // Synthesizes a comment that was not textually present in the original source
579     // file.
580     pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
581         try!(word(&mut self.s, "/*"));
582         try!(space(&mut self.s));
583         try!(word(&mut self.s, text[]));
584         try!(space(&mut self.s));
585         word(&mut self.s, "*/")
586     }
587
588     pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where
589         F: FnMut(&mut State, &T) -> IoResult<()>,
590     {
591         try!(self.rbox(0u, b));
592         let mut first = true;
593         for elt in elts.iter() {
594             if first { first = false; } else { try!(self.word_space(",")); }
595             try!(op(self, elt));
596         }
597         self.end()
598     }
599
600
601     pub fn commasep_cmnt<T, F, G>(&mut self,
602                                   b: Breaks,
603                                   elts: &[T],
604                                   mut op: F,
605                                   mut get_span: G) -> IoResult<()> where
606         F: FnMut(&mut State, &T) -> IoResult<()>,
607         G: FnMut(&T) -> codemap::Span,
608     {
609         try!(self.rbox(0u, b));
610         let len = elts.len();
611         let mut i = 0u;
612         for elt in elts.iter() {
613             try!(self.maybe_print_comment(get_span(elt).hi));
614             try!(op(self, elt));
615             i += 1u;
616             if i < len {
617                 try!(word(&mut self.s, ","));
618                 try!(self.maybe_print_trailing_comment(get_span(elt),
619                                                     Some(get_span(&elts[i]).hi)));
620                 try!(self.space_if_not_bol());
621             }
622         }
623         self.end()
624     }
625
626     pub fn commasep_exprs(&mut self, b: Breaks,
627                           exprs: &[P<ast::Expr>]) -> IoResult<()> {
628         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
629     }
630
631     pub fn print_mod(&mut self, _mod: &ast::Mod,
632                      attrs: &[ast::Attribute]) -> IoResult<()> {
633         try!(self.print_inner_attributes(attrs));
634         for vitem in _mod.view_items.iter() {
635             try!(self.print_view_item(vitem));
636         }
637         for item in _mod.items.iter() {
638             try!(self.print_item(&**item));
639         }
640         Ok(())
641     }
642
643     pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
644                              attrs: &[ast::Attribute]) -> IoResult<()> {
645         try!(self.print_inner_attributes(attrs));
646         for vitem in nmod.view_items.iter() {
647             try!(self.print_view_item(vitem));
648         }
649         for item in nmod.items.iter() {
650             try!(self.print_foreign_item(&**item));
651         }
652         Ok(())
653     }
654
655     pub fn print_opt_lifetime(&mut self,
656                               lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
657         for l in lifetime.iter() {
658             try!(self.print_lifetime(l));
659             try!(self.nbsp());
660         }
661         Ok(())
662     }
663
664     pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
665         try!(self.maybe_print_comment(ty.span.lo));
666         try!(self.ibox(0u));
667         match ty.node {
668             ast::TyVec(ref ty) => {
669                 try!(word(&mut self.s, "["));
670                 try!(self.print_type(&**ty));
671                 try!(word(&mut self.s, "]"));
672             }
673             ast::TyPtr(ref mt) => {
674                 try!(word(&mut self.s, "*"));
675                 match mt.mutbl {
676                     ast::MutMutable => try!(self.word_nbsp("mut")),
677                     ast::MutImmutable => try!(self.word_nbsp("const")),
678                 }
679                 try!(self.print_type(&*mt.ty));
680             }
681             ast::TyRptr(ref lifetime, ref mt) => {
682                 try!(word(&mut self.s, "&"));
683                 try!(self.print_opt_lifetime(lifetime));
684                 try!(self.print_mt(mt));
685             }
686             ast::TyTup(ref elts) => {
687                 try!(self.popen());
688                 try!(self.commasep(Inconsistent, elts[],
689                                    |s, ty| s.print_type(&**ty)));
690                 if elts.len() == 1 {
691                     try!(word(&mut self.s, ","));
692                 }
693                 try!(self.pclose());
694             }
695             ast::TyParen(ref typ) => {
696                 try!(self.popen());
697                 try!(self.print_type(&**typ));
698                 try!(self.pclose());
699             }
700             ast::TyBareFn(ref f) => {
701                 let generics = ast::Generics {
702                     lifetimes: f.lifetimes.clone(),
703                     ty_params: OwnedSlice::empty(),
704                     where_clause: ast::WhereClause {
705                         id: ast::DUMMY_NODE_ID,
706                         predicates: Vec::new(),
707                     },
708                 };
709                 try!(self.print_ty_fn(Some(f.abi),
710                                       None,
711                                       f.unsafety,
712                                       ast::Many,
713                                       &*f.decl,
714                                       None,
715                                       &OwnedSlice::empty(),
716                                       Some(&generics),
717                                       None));
718             }
719             ast::TyClosure(ref f) => {
720                 let generics = ast::Generics {
721                     lifetimes: f.lifetimes.clone(),
722                     ty_params: OwnedSlice::empty(),
723                     where_clause: ast::WhereClause {
724                         id: ast::DUMMY_NODE_ID,
725                         predicates: Vec::new(),
726                     },
727                 };
728                 try!(self.print_ty_fn(None,
729                                       Some('&'),
730                                       f.unsafety,
731                                       f.onceness,
732                                       &*f.decl,
733                                       None,
734                                       &f.bounds,
735                                       Some(&generics),
736                                       None));
737             }
738             ast::TyPath(ref path, _) => {
739                 try!(self.print_path(path, false));
740             }
741             ast::TyObjectSum(ref ty, ref bounds) => {
742                 try!(self.print_type(&**ty));
743                 try!(self.print_bounds("+", bounds[]));
744             }
745             ast::TyPolyTraitRef(ref bounds) => {
746                 try!(self.print_bounds("", bounds[]));
747             }
748             ast::TyQPath(ref qpath) => {
749                 try!(word(&mut self.s, "<"));
750                 try!(self.print_type(&*qpath.self_type));
751                 try!(space(&mut self.s));
752                 try!(self.word_space("as"));
753                 try!(self.print_trait_ref(&*qpath.trait_ref));
754                 try!(word(&mut self.s, ">"));
755                 try!(word(&mut self.s, "::"));
756                 try!(self.print_ident(qpath.item_name));
757             }
758             ast::TyFixedLengthVec(ref ty, ref v) => {
759                 try!(word(&mut self.s, "["));
760                 try!(self.print_type(&**ty));
761                 try!(word(&mut self.s, "; "));
762                 try!(self.print_expr(&**v));
763                 try!(word(&mut self.s, "]"));
764             }
765             ast::TyTypeof(ref e) => {
766                 try!(word(&mut self.s, "typeof("));
767                 try!(self.print_expr(&**e));
768                 try!(word(&mut self.s, ")"));
769             }
770             ast::TyInfer => {
771                 try!(word(&mut self.s, "_"));
772             }
773         }
774         self.end()
775     }
776
777     pub fn print_foreign_item(&mut self,
778                               item: &ast::ForeignItem) -> IoResult<()> {
779         try!(self.hardbreak_if_not_bol());
780         try!(self.maybe_print_comment(item.span.lo));
781         try!(self.print_outer_attributes(item.attrs[]));
782         match item.node {
783             ast::ForeignItemFn(ref decl, ref generics) => {
784                 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
785                                    None, item.vis));
786                 try!(self.end()); // end head-ibox
787                 try!(word(&mut self.s, ";"));
788                 self.end() // end the outer fn box
789             }
790             ast::ForeignItemStatic(ref t, m) => {
791                 try!(self.head(visibility_qualified(item.vis,
792                                                     "static")[]));
793                 if m {
794                     try!(self.word_space("mut"));
795                 }
796                 try!(self.print_ident(item.ident));
797                 try!(self.word_space(":"));
798                 try!(self.print_type(&**t));
799                 try!(word(&mut self.s, ";"));
800                 try!(self.end()); // end the head-ibox
801                 self.end() // end the outer cbox
802             }
803         }
804     }
805
806     fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
807                              -> IoResult<()>
808     {
809         try!(self.print_outer_attributes(typedef.attrs[]));
810         try!(self.word_space("type"));
811         try!(self.print_ty_param(&typedef.ty_param));
812         word(&mut self.s, ";")
813     }
814
815     fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
816         try!(self.word_space("type"));
817         try!(self.print_ident(typedef.ident));
818         try!(space(&mut self.s));
819         try!(self.word_space("="));
820         try!(self.print_type(&*typedef.typ));
821         word(&mut self.s, ";")
822     }
823
824     /// Pretty-print an item
825     pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
826         try!(self.hardbreak_if_not_bol());
827         try!(self.maybe_print_comment(item.span.lo));
828         try!(self.print_outer_attributes(item.attrs[]));
829         try!(self.ann.pre(self, NodeItem(item)));
830         match item.node {
831             ast::ItemStatic(ref ty, m, ref expr) => {
832                 try!(self.head(visibility_qualified(item.vis,
833                                                     "static")[]));
834                 if m == ast::MutMutable {
835                     try!(self.word_space("mut"));
836                 }
837                 try!(self.print_ident(item.ident));
838                 try!(self.word_space(":"));
839                 try!(self.print_type(&**ty));
840                 try!(space(&mut self.s));
841                 try!(self.end()); // end the head-ibox
842
843                 try!(self.word_space("="));
844                 try!(self.print_expr(&**expr));
845                 try!(word(&mut self.s, ";"));
846                 try!(self.end()); // end the outer cbox
847             }
848             ast::ItemConst(ref ty, ref expr) => {
849                 try!(self.head(visibility_qualified(item.vis,
850                                                     "const")[]));
851                 try!(self.print_ident(item.ident));
852                 try!(self.word_space(":"));
853                 try!(self.print_type(&**ty));
854                 try!(space(&mut self.s));
855                 try!(self.end()); // end the head-ibox
856
857                 try!(self.word_space("="));
858                 try!(self.print_expr(&**expr));
859                 try!(word(&mut self.s, ";"));
860                 try!(self.end()); // end the outer cbox
861             }
862             ast::ItemFn(ref decl, unsafety, abi, ref typarams, ref body) => {
863                 try!(self.print_fn(
864                     &**decl,
865                     Some(unsafety),
866                     abi,
867                     item.ident,
868                     typarams,
869                     None,
870                     item.vis
871                 ));
872                 try!(word(&mut self.s, " "));
873                 try!(self.print_block_with_attrs(&**body, item.attrs[]));
874             }
875             ast::ItemMod(ref _mod) => {
876                 try!(self.head(visibility_qualified(item.vis,
877                                                     "mod")[]));
878                 try!(self.print_ident(item.ident));
879                 try!(self.nbsp());
880                 try!(self.bopen());
881                 try!(self.print_mod(_mod, item.attrs[]));
882                 try!(self.bclose(item.span));
883             }
884             ast::ItemForeignMod(ref nmod) => {
885                 try!(self.head("extern"));
886                 try!(self.word_nbsp(nmod.abi.to_string()[]));
887                 try!(self.bopen());
888                 try!(self.print_foreign_mod(nmod, item.attrs[]));
889                 try!(self.bclose(item.span));
890             }
891             ast::ItemTy(ref ty, ref params) => {
892                 try!(self.ibox(indent_unit));
893                 try!(self.ibox(0u));
894                 try!(self.word_nbsp(visibility_qualified(item.vis,
895                                                          "type")[]));
896                 try!(self.print_ident(item.ident));
897                 try!(self.print_generics(params));
898                 try!(self.end()); // end the inner ibox
899
900                 try!(space(&mut self.s));
901                 try!(self.word_space("="));
902                 try!(self.print_type(&**ty));
903                 try!(self.print_where_clause(params));
904                 try!(word(&mut self.s, ";"));
905                 try!(self.end()); // end the outer ibox
906             }
907             ast::ItemEnum(ref enum_definition, ref params) => {
908                 try!(self.print_enum_def(
909                     enum_definition,
910                     params,
911                     item.ident,
912                     item.span,
913                     item.vis
914                 ));
915             }
916             ast::ItemStruct(ref struct_def, ref generics) => {
917                 try!(self.head(visibility_qualified(item.vis,"struct")[]));
918                 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
919             }
920
921             ast::ItemImpl(unsafety,
922                           polarity,
923                           ref generics,
924                           ref opt_trait,
925                           ref ty,
926                           ref impl_items) => {
927                 try!(self.head(""));
928                 try!(self.print_visibility(item.vis));
929                 try!(self.print_unsafety(unsafety));
930                 try!(self.word_nbsp("impl"));
931
932                 if generics.is_parameterized() {
933                     try!(self.print_generics(generics));
934                     try!(space(&mut self.s));
935                 }
936
937                 match polarity {
938                     ast::ImplPolarity::Negative => {
939                         try!(word(&mut self.s, "!"));
940                     },
941                     _ => {}
942                 }
943
944                 match opt_trait {
945                     &Some(ref t) => {
946                         try!(self.print_trait_ref(t));
947                         try!(space(&mut self.s));
948                         try!(self.word_space("for"));
949                     }
950                     &None => {}
951                 }
952
953                 try!(self.print_type(&**ty));
954                 try!(self.print_where_clause(generics));
955
956                 try!(space(&mut self.s));
957                 try!(self.bopen());
958                 try!(self.print_inner_attributes(item.attrs[]));
959                 for impl_item in impl_items.iter() {
960                     match *impl_item {
961                         ast::MethodImplItem(ref meth) => {
962                             try!(self.print_method(&**meth));
963                         }
964                         ast::TypeImplItem(ref typ) => {
965                             try!(self.print_typedef(&**typ));
966                         }
967                     }
968                 }
969                 try!(self.bclose(item.span));
970             }
971             ast::ItemTrait(unsafety, ref generics, ref bounds, ref methods) => {
972                 try!(self.head(""));
973                 try!(self.print_visibility(item.vis));
974                 try!(self.print_unsafety(unsafety));
975                 try!(self.word_nbsp("trait"));
976                 try!(self.print_ident(item.ident));
977                 try!(self.print_generics(generics));
978                 let bounds: Vec<_> = bounds.iter().map(|b| b.clone()).collect();
979                 let mut real_bounds = Vec::with_capacity(bounds.len());
980                 for b in bounds.into_iter() {
981                     if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = b {
982                         try!(space(&mut self.s));
983                         try!(self.word_space("for ?"));
984                         try!(self.print_trait_ref(&ptr.trait_ref));
985                     } else {
986                         real_bounds.push(b);
987                     }
988                 }
989                 try!(self.print_bounds(":", real_bounds[]));
990                 try!(self.print_where_clause(generics));
991                 try!(word(&mut self.s, " "));
992                 try!(self.bopen());
993                 for meth in methods.iter() {
994                     try!(self.print_trait_method(meth));
995                 }
996                 try!(self.bclose(item.span));
997             }
998             // I think it's reasonable to hide the context here:
999             ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1000                                             ..}) => {
1001                 try!(self.print_visibility(item.vis));
1002                 try!(self.print_path(pth, false));
1003                 try!(word(&mut self.s, "! "));
1004                 try!(self.print_ident(item.ident));
1005                 try!(self.cbox(indent_unit));
1006                 try!(self.popen());
1007                 try!(self.print_tts(tts[]));
1008                 try!(self.pclose());
1009                 try!(word(&mut self.s, ";"));
1010                 try!(self.end());
1011             }
1012         }
1013         self.ann.post(self, NodeItem(item))
1014     }
1015
1016     fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
1017         self.print_path(&t.path, false)
1018     }
1019
1020     fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
1021         if !t.bound_lifetimes.is_empty() {
1022             try!(word(&mut self.s, "for<"));
1023             let mut comma = false;
1024             for lifetime_def in t.bound_lifetimes.iter() {
1025                 if comma {
1026                     try!(self.word_space(","))
1027                 }
1028                 try!(self.print_lifetime_def(lifetime_def));
1029                 comma = true;
1030             }
1031             try!(word(&mut self.s, ">"));
1032         }
1033
1034         self.print_trait_ref(&t.trait_ref)
1035     }
1036
1037     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1038                           generics: &ast::Generics, ident: ast::Ident,
1039                           span: codemap::Span,
1040                           visibility: ast::Visibility) -> IoResult<()> {
1041         try!(self.head(visibility_qualified(visibility, "enum")[]));
1042         try!(self.print_ident(ident));
1043         try!(self.print_generics(generics));
1044         try!(self.print_where_clause(generics));
1045         try!(space(&mut self.s));
1046         self.print_variants(enum_definition.variants[], span)
1047     }
1048
1049     pub fn print_variants(&mut self,
1050                           variants: &[P<ast::Variant>],
1051                           span: codemap::Span) -> IoResult<()> {
1052         try!(self.bopen());
1053         for v in variants.iter() {
1054             try!(self.space_if_not_bol());
1055             try!(self.maybe_print_comment(v.span.lo));
1056             try!(self.print_outer_attributes(v.node.attrs[]));
1057             try!(self.ibox(indent_unit));
1058             try!(self.print_variant(&**v));
1059             try!(word(&mut self.s, ","));
1060             try!(self.end());
1061             try!(self.maybe_print_trailing_comment(v.span, None));
1062         }
1063         self.bclose(span)
1064     }
1065
1066     pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
1067         match vis {
1068             ast::Public => self.word_nbsp("pub"),
1069             ast::Inherited => Ok(())
1070         }
1071     }
1072
1073     pub fn print_struct(&mut self,
1074                         struct_def: &ast::StructDef,
1075                         generics: &ast::Generics,
1076                         ident: ast::Ident,
1077                         span: codemap::Span) -> IoResult<()> {
1078         try!(self.print_ident(ident));
1079         try!(self.print_generics(generics));
1080         try!(self.print_where_clause(generics));
1081         if ast_util::struct_def_is_tuple_like(struct_def) {
1082             if !struct_def.fields.is_empty() {
1083                 try!(self.popen());
1084                 try!(self.commasep(
1085                     Inconsistent, struct_def.fields[],
1086                     |s, field| {
1087                         match field.node.kind {
1088                             ast::NamedField(..) => panic!("unexpected named field"),
1089                             ast::UnnamedField(vis) => {
1090                                 try!(s.print_visibility(vis));
1091                                 try!(s.maybe_print_comment(field.span.lo));
1092                                 s.print_type(&*field.node.ty)
1093                             }
1094                         }
1095                     }
1096                 ));
1097                 try!(self.pclose());
1098             }
1099             try!(word(&mut self.s, ";"));
1100             try!(self.end());
1101             self.end() // close the outer-box
1102         } else {
1103             try!(self.nbsp());
1104             try!(self.bopen());
1105             try!(self.hardbreak_if_not_bol());
1106
1107             for field in struct_def.fields.iter() {
1108                 match field.node.kind {
1109                     ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1110                     ast::NamedField(ident, visibility) => {
1111                         try!(self.hardbreak_if_not_bol());
1112                         try!(self.maybe_print_comment(field.span.lo));
1113                         try!(self.print_outer_attributes(field.node.attrs[]));
1114                         try!(self.print_visibility(visibility));
1115                         try!(self.print_ident(ident));
1116                         try!(self.word_nbsp(":"));
1117                         try!(self.print_type(&*field.node.ty));
1118                         try!(word(&mut self.s, ","));
1119                     }
1120                 }
1121             }
1122
1123             self.bclose(span)
1124         }
1125     }
1126
1127     /// This doesn't deserve to be called "pretty" printing, but it should be
1128     /// meaning-preserving. A quick hack that might help would be to look at the
1129     /// spans embedded in the TTs to decide where to put spaces and newlines.
1130     /// But it'd be better to parse these according to the grammar of the
1131     /// appropriate macro, transcribe back into the grammar we just parsed from,
1132     /// and then pretty-print the resulting AST nodes (so, e.g., we print
1133     /// expression arguments as expressions). It can be done! I think.
1134     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1135         match *tt {
1136             ast::TtToken(_, ref tk) => {
1137                 try!(word(&mut self.s, token_to_string(tk)[]));
1138                 match *tk {
1139                     parse::token::DocComment(..) => {
1140                         hardbreak(&mut self.s)
1141                     }
1142                     _ => Ok(())
1143                 }
1144             }
1145             ast::TtDelimited(_, ref delimed) => {
1146                 try!(word(&mut self.s, token_to_string(&delimed.open_token())[]));
1147                 try!(space(&mut self.s));
1148                 try!(self.print_tts(delimed.tts[]));
1149                 try!(space(&mut self.s));
1150                 word(&mut self.s, token_to_string(&delimed.close_token())[])
1151             },
1152             ast::TtSequence(_, ref seq) => {
1153                 try!(word(&mut self.s, "$("));
1154                 for tt_elt in seq.tts.iter() {
1155                     try!(self.print_tt(tt_elt));
1156                 }
1157                 try!(word(&mut self.s, ")"));
1158                 match seq.separator {
1159                     Some(ref tk) => {
1160                         try!(word(&mut self.s, token_to_string(tk)[]));
1161                     }
1162                     None => {},
1163                 }
1164                 match seq.op {
1165                     ast::ZeroOrMore => word(&mut self.s, "*"),
1166                     ast::OneOrMore => word(&mut self.s, "+"),
1167                 }
1168             }
1169         }
1170     }
1171
1172     pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1173         try!(self.ibox(0));
1174         for (i, tt) in tts.iter().enumerate() {
1175             if i != 0 {
1176                 try!(space(&mut self.s));
1177             }
1178             try!(self.print_tt(tt));
1179         }
1180         self.end()
1181     }
1182
1183     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1184         try!(self.print_visibility(v.node.vis));
1185         match v.node.kind {
1186             ast::TupleVariantKind(ref args) => {
1187                 try!(self.print_ident(v.node.name));
1188                 if !args.is_empty() {
1189                     try!(self.popen());
1190                     try!(self.commasep(Consistent,
1191                                        args[],
1192                                        |s, arg| s.print_type(&*arg.ty)));
1193                     try!(self.pclose());
1194                 }
1195             }
1196             ast::StructVariantKind(ref struct_def) => {
1197                 try!(self.head(""));
1198                 let generics = ast_util::empty_generics();
1199                 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1200             }
1201         }
1202         match v.node.disr_expr {
1203             Some(ref d) => {
1204                 try!(space(&mut self.s));
1205                 try!(self.word_space("="));
1206                 self.print_expr(&**d)
1207             }
1208             _ => Ok(())
1209         }
1210     }
1211
1212     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1213         try!(self.hardbreak_if_not_bol());
1214         try!(self.maybe_print_comment(m.span.lo));
1215         try!(self.print_outer_attributes(m.attrs[]));
1216         try!(self.print_ty_fn(None,
1217                               None,
1218                               m.unsafety,
1219                               ast::Many,
1220                               &*m.decl,
1221                               Some(m.ident),
1222                               &OwnedSlice::empty(),
1223                               Some(&m.generics),
1224                               Some(&m.explicit_self.node)));
1225         word(&mut self.s, ";")
1226     }
1227
1228     pub fn print_trait_method(&mut self,
1229                               m: &ast::TraitItem) -> IoResult<()> {
1230         match *m {
1231             RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1232             ProvidedMethod(ref m) => self.print_method(&**m),
1233             TypeTraitItem(ref t) => self.print_associated_type(&**t),
1234         }
1235     }
1236
1237     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1238         match *ii {
1239             MethodImplItem(ref m) => self.print_method(&**m),
1240             TypeImplItem(ref td) => self.print_typedef(&**td),
1241         }
1242     }
1243
1244     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1245         try!(self.hardbreak_if_not_bol());
1246         try!(self.maybe_print_comment(meth.span.lo));
1247         try!(self.print_outer_attributes(meth.attrs[]));
1248         match meth.node {
1249             ast::MethDecl(ident,
1250                           ref generics,
1251                           abi,
1252                           ref explicit_self,
1253                           unsafety,
1254                           ref decl,
1255                           ref body,
1256                           vis) => {
1257                 try!(self.print_fn(&**decl,
1258                                    Some(unsafety),
1259                                    abi,
1260                                    ident,
1261                                    generics,
1262                                    Some(&explicit_self.node),
1263                                    vis));
1264                 try!(word(&mut self.s, " "));
1265                 self.print_block_with_attrs(&**body, meth.attrs[])
1266             },
1267             ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1268                                             ..}) => {
1269                 // code copied from ItemMac:
1270                 try!(self.print_path(pth, false));
1271                 try!(word(&mut self.s, "! "));
1272                 try!(self.cbox(indent_unit));
1273                 try!(self.popen());
1274                 try!(self.print_tts(tts[]));
1275                 try!(self.pclose());
1276                 try!(word(&mut self.s, ";"));
1277                 self.end()
1278             }
1279         }
1280     }
1281
1282     pub fn print_outer_attributes(&mut self,
1283                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1284         let mut count = 0u;
1285         for attr in attrs.iter() {
1286             match attr.node.style {
1287                 ast::AttrOuter => {
1288                     try!(self.print_attribute(attr));
1289                     count += 1;
1290                 }
1291                 _ => {/* fallthrough */ }
1292             }
1293         }
1294         if count > 0 {
1295             try!(self.hardbreak_if_not_bol());
1296         }
1297         Ok(())
1298     }
1299
1300     pub fn print_inner_attributes(&mut self,
1301                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1302         let mut count = 0u;
1303         for attr in attrs.iter() {
1304             match attr.node.style {
1305                 ast::AttrInner => {
1306                     try!(self.print_attribute(attr));
1307                     count += 1;
1308                 }
1309                 _ => {/* fallthrough */ }
1310             }
1311         }
1312         if count > 0 {
1313             try!(self.hardbreak_if_not_bol());
1314         }
1315         Ok(())
1316     }
1317
1318     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1319         try!(self.hardbreak_if_not_bol());
1320         try!(self.maybe_print_comment(attr.span.lo));
1321         if attr.node.is_sugared_doc {
1322             word(&mut self.s, attr.value_str().unwrap().get())
1323         } else {
1324             match attr.node.style {
1325                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1326                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1327             }
1328             try!(self.print_meta_item(&*attr.meta()));
1329             word(&mut self.s, "]")
1330         }
1331     }
1332
1333
1334     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1335         try!(self.maybe_print_comment(st.span.lo));
1336         match st.node {
1337             ast::StmtDecl(ref decl, _) => {
1338                 try!(self.print_decl(&**decl));
1339             }
1340             ast::StmtExpr(ref expr, _) => {
1341                 try!(self.space_if_not_bol());
1342                 try!(self.print_expr(&**expr));
1343             }
1344             ast::StmtSemi(ref expr, _) => {
1345                 try!(self.space_if_not_bol());
1346                 try!(self.print_expr(&**expr));
1347                 try!(word(&mut self.s, ";"));
1348             }
1349             ast::StmtMac(ref mac, style) => {
1350                 try!(self.space_if_not_bol());
1351                 let delim = match style {
1352                     ast::MacStmtWithBraces => token::Brace,
1353                     _ => token::Paren
1354                 };
1355                 try!(self.print_mac(&**mac, delim));
1356                 match style {
1357                     ast::MacStmtWithBraces => {}
1358                     _ => try!(word(&mut self.s, ";")),
1359                 }
1360             }
1361         }
1362         if parse::classify::stmt_ends_with_semi(&st.node) {
1363             try!(word(&mut self.s, ";"));
1364         }
1365         self.maybe_print_trailing_comment(st.span, None)
1366     }
1367
1368     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1369         self.print_block_with_attrs(blk, &[])
1370     }
1371
1372     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1373         self.print_block_unclosed_indent(blk, indent_unit)
1374     }
1375
1376     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1377                                        indented: uint) -> IoResult<()> {
1378         self.print_block_maybe_unclosed(blk, indented, &[], false)
1379     }
1380
1381     pub fn print_block_with_attrs(&mut self,
1382                                   blk: &ast::Block,
1383                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1384         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1385     }
1386
1387     pub fn print_block_maybe_unclosed(&mut self,
1388                                       blk: &ast::Block,
1389                                       indented: uint,
1390                                       attrs: &[ast::Attribute],
1391                                       close_box: bool) -> IoResult<()> {
1392         match blk.rules {
1393             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1394             ast::DefaultBlock => ()
1395         }
1396         try!(self.maybe_print_comment(blk.span.lo));
1397         try!(self.ann.pre(self, NodeBlock(blk)));
1398         try!(self.bopen());
1399
1400         try!(self.print_inner_attributes(attrs));
1401
1402         for vi in blk.view_items.iter() {
1403             try!(self.print_view_item(vi));
1404         }
1405         for st in blk.stmts.iter() {
1406             try!(self.print_stmt(&**st));
1407         }
1408         match blk.expr {
1409             Some(ref expr) => {
1410                 try!(self.space_if_not_bol());
1411                 try!(self.print_expr(&**expr));
1412                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1413             }
1414             _ => ()
1415         }
1416         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1417         self.ann.post(self, NodeBlock(blk))
1418     }
1419
1420     fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1421         match els {
1422             Some(_else) => {
1423                 match _else.node {
1424                     // "another else-if"
1425                     ast::ExprIf(ref i, ref then, ref e) => {
1426                         try!(self.cbox(indent_unit - 1u));
1427                         try!(self.ibox(0u));
1428                         try!(word(&mut self.s, " else if "));
1429                         try!(self.print_expr(&**i));
1430                         try!(space(&mut self.s));
1431                         try!(self.print_block(&**then));
1432                         self.print_else(e.as_ref().map(|e| &**e))
1433                     }
1434                     // "another else-if-let"
1435                     ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1436                         try!(self.cbox(indent_unit - 1u));
1437                         try!(self.ibox(0u));
1438                         try!(word(&mut self.s, " else if let "));
1439                         try!(self.print_pat(&**pat));
1440                         try!(space(&mut self.s));
1441                         try!(self.word_space("="));
1442                         try!(self.print_expr(&**expr));
1443                         try!(space(&mut self.s));
1444                         try!(self.print_block(&**then));
1445                         self.print_else(e.as_ref().map(|e| &**e))
1446                     }
1447                     // "final else"
1448                     ast::ExprBlock(ref b) => {
1449                         try!(self.cbox(indent_unit - 1u));
1450                         try!(self.ibox(0u));
1451                         try!(word(&mut self.s, " else "));
1452                         self.print_block(&**b)
1453                     }
1454                     // BLEAH, constraints would be great here
1455                     _ => {
1456                         panic!("print_if saw if with weird alternative");
1457                     }
1458                 }
1459             }
1460             _ => Ok(())
1461         }
1462     }
1463
1464     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1465                     elseopt: Option<&ast::Expr>) -> IoResult<()> {
1466         try!(self.head("if"));
1467         try!(self.print_expr(test));
1468         try!(space(&mut self.s));
1469         try!(self.print_block(blk));
1470         self.print_else(elseopt)
1471     }
1472
1473     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1474                         elseopt: Option<&ast::Expr>) -> IoResult<()> {
1475         try!(self.head("if let"));
1476         try!(self.print_pat(pat));
1477         try!(space(&mut self.s));
1478         try!(self.word_space("="));
1479         try!(self.print_expr(expr));
1480         try!(space(&mut self.s));
1481         try!(self.print_block(blk));
1482         self.print_else(elseopt)
1483     }
1484
1485     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1486                      -> IoResult<()> {
1487         match m.node {
1488             // I think it's reasonable to hide the ctxt here:
1489             ast::MacInvocTT(ref pth, ref tts, _) => {
1490                 try!(self.print_path(pth, false));
1491                 try!(word(&mut self.s, "!"));
1492                 match delim {
1493                     token::Paren => try!(self.popen()),
1494                     token::Bracket => try!(word(&mut self.s, "[")),
1495                     token::Brace => try!(self.bopen()),
1496                 }
1497                 try!(self.print_tts(tts.as_slice()));
1498                 match delim {
1499                     token::Paren => self.pclose(),
1500                     token::Bracket => word(&mut self.s, "]"),
1501                     token::Brace => self.bclose(m.span),
1502                 }
1503             }
1504         }
1505     }
1506
1507
1508     fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1509         try!(self.popen());
1510         try!(self.commasep_exprs(Inconsistent, args));
1511         self.pclose()
1512     }
1513
1514     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1515         let needs_par = needs_parentheses(expr);
1516         if needs_par {
1517             try!(self.popen());
1518         }
1519         try!(self.print_expr(expr));
1520         if needs_par {
1521             try!(self.pclose());
1522         }
1523         Ok(())
1524     }
1525
1526     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1527         try!(self.maybe_print_comment(expr.span.lo));
1528         try!(self.ibox(indent_unit));
1529         try!(self.ann.pre(self, NodeExpr(expr)));
1530         match expr.node {
1531             ast::ExprBox(ref p, ref e) => {
1532                 try!(word(&mut self.s, "box"));
1533                 try!(word(&mut self.s, "("));
1534                 try!(p.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1535                 try!(self.word_space(")"));
1536                 try!(self.print_expr(&**e));
1537             }
1538             ast::ExprVec(ref exprs) => {
1539                 try!(self.ibox(indent_unit));
1540                 try!(word(&mut self.s, "["));
1541                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1542                 try!(word(&mut self.s, "]"));
1543                 try!(self.end());
1544             }
1545
1546             ast::ExprRepeat(ref element, ref count) => {
1547                 try!(self.ibox(indent_unit));
1548                 try!(word(&mut self.s, "["));
1549                 try!(self.print_expr(&**element));
1550                 try!(self.word_space(";"));
1551                 try!(self.print_expr(&**count));
1552                 try!(word(&mut self.s, "]"));
1553                 try!(self.end());
1554             }
1555
1556             ast::ExprStruct(ref path, ref fields, ref wth) => {
1557                 try!(self.print_path(path, true));
1558                 try!(word(&mut self.s, "{"));
1559                 try!(self.commasep_cmnt(
1560                     Consistent,
1561                     fields[],
1562                     |s, field| {
1563                         try!(s.ibox(indent_unit));
1564                         try!(s.print_ident(field.ident.node));
1565                         try!(s.word_space(":"));
1566                         try!(s.print_expr(&*field.expr));
1567                         s.end()
1568                     },
1569                     |f| f.span));
1570                 match *wth {
1571                     Some(ref expr) => {
1572                         try!(self.ibox(indent_unit));
1573                         if !fields.is_empty() {
1574                             try!(word(&mut self.s, ","));
1575                             try!(space(&mut self.s));
1576                         }
1577                         try!(word(&mut self.s, ".."));
1578                         try!(self.print_expr(&**expr));
1579                         try!(self.end());
1580                     }
1581                     _ => try!(word(&mut self.s, ","))
1582                 }
1583                 try!(word(&mut self.s, "}"));
1584             }
1585             ast::ExprTup(ref exprs) => {
1586                 try!(self.popen());
1587                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1588                 if exprs.len() == 1 {
1589                     try!(word(&mut self.s, ","));
1590                 }
1591                 try!(self.pclose());
1592             }
1593             ast::ExprCall(ref func, ref args) => {
1594                 try!(self.print_expr_maybe_paren(&**func));
1595                 try!(self.print_call_post(args[]));
1596             }
1597             ast::ExprMethodCall(ident, ref tys, ref args) => {
1598                 let base_args = args.slice_from(1);
1599                 try!(self.print_expr(&*args[0]));
1600                 try!(word(&mut self.s, "."));
1601                 try!(self.print_ident(ident.node));
1602                 if tys.len() > 0u {
1603                     try!(word(&mut self.s, "::<"));
1604                     try!(self.commasep(Inconsistent, tys[],
1605                                        |s, ty| s.print_type(&**ty)));
1606                     try!(word(&mut self.s, ">"));
1607                 }
1608                 try!(self.print_call_post(base_args));
1609             }
1610             ast::ExprBinary(op, ref lhs, ref rhs) => {
1611                 try!(self.print_expr(&**lhs));
1612                 try!(space(&mut self.s));
1613                 try!(self.word_space(ast_util::binop_to_string(op)));
1614                 try!(self.print_expr(&**rhs));
1615             }
1616             ast::ExprUnary(op, ref expr) => {
1617                 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1618                 try!(self.print_expr_maybe_paren(&**expr));
1619             }
1620             ast::ExprAddrOf(m, ref expr) => {
1621                 try!(word(&mut self.s, "&"));
1622                 try!(self.print_mutability(m));
1623                 try!(self.print_expr_maybe_paren(&**expr));
1624             }
1625             ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1626             ast::ExprCast(ref expr, ref ty) => {
1627                 try!(self.print_expr(&**expr));
1628                 try!(space(&mut self.s));
1629                 try!(self.word_space("as"));
1630                 try!(self.print_type(&**ty));
1631             }
1632             ast::ExprIf(ref test, ref blk, ref elseopt) => {
1633                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1634             }
1635             ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1636                 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1637             }
1638             ast::ExprWhile(ref test, ref blk, opt_ident) => {
1639                 for ident in opt_ident.iter() {
1640                     try!(self.print_ident(*ident));
1641                     try!(self.word_space(":"));
1642                 }
1643                 try!(self.head("while"));
1644                 try!(self.print_expr(&**test));
1645                 try!(space(&mut self.s));
1646                 try!(self.print_block(&**blk));
1647             }
1648             ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1649                 for ident in opt_ident.iter() {
1650                     try!(self.print_ident(*ident));
1651                     try!(self.word_space(":"));
1652                 }
1653                 try!(self.head("while let"));
1654                 try!(self.print_pat(&**pat));
1655                 try!(space(&mut self.s));
1656                 try!(self.word_space("="));
1657                 try!(self.print_expr(&**expr));
1658                 try!(space(&mut self.s));
1659                 try!(self.print_block(&**blk));
1660             }
1661             ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1662                 for ident in opt_ident.iter() {
1663                     try!(self.print_ident(*ident));
1664                     try!(self.word_space(":"));
1665                 }
1666                 try!(self.head("for"));
1667                 try!(self.print_pat(&**pat));
1668                 try!(space(&mut self.s));
1669                 try!(self.word_space("in"));
1670                 try!(self.print_expr(&**iter));
1671                 try!(space(&mut self.s));
1672                 try!(self.print_block(&**blk));
1673             }
1674             ast::ExprLoop(ref blk, opt_ident) => {
1675                 for ident in opt_ident.iter() {
1676                     try!(self.print_ident(*ident));
1677                     try!(self.word_space(":"));
1678                 }
1679                 try!(self.head("loop"));
1680                 try!(space(&mut self.s));
1681                 try!(self.print_block(&**blk));
1682             }
1683             ast::ExprMatch(ref expr, ref arms, _) => {
1684                 try!(self.cbox(indent_unit));
1685                 try!(self.ibox(4));
1686                 try!(self.word_nbsp("match"));
1687                 try!(self.print_expr(&**expr));
1688                 try!(space(&mut self.s));
1689                 try!(self.bopen());
1690                 for arm in arms.iter() {
1691                     try!(self.print_arm(arm));
1692                 }
1693                 try!(self.bclose_(expr.span, indent_unit));
1694             }
1695             ast::ExprClosure(capture_clause, opt_kind, ref decl, ref body) => {
1696                 try!(self.print_capture_clause(capture_clause));
1697
1698                 try!(self.print_fn_block_args(&**decl, opt_kind));
1699                 try!(space(&mut self.s));
1700
1701                 if !body.stmts.is_empty() || !body.expr.is_some() {
1702                     try!(self.print_block_unclosed(&**body));
1703                 } else {
1704                     // we extract the block, so as not to create another set of boxes
1705                     match body.expr.as_ref().unwrap().node {
1706                         ast::ExprBlock(ref blk) => {
1707                             try!(self.print_block_unclosed(&**blk));
1708                         }
1709                         _ => {
1710                             // this is a bare expression
1711                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1712                             try!(self.end()); // need to close a box
1713                         }
1714                     }
1715                 }
1716                 // a box will be closed by print_expr, but we didn't want an overall
1717                 // wrapper so we closed the corresponding opening. so create an
1718                 // empty box to satisfy the close.
1719                 try!(self.ibox(0));
1720             }
1721             ast::ExprBlock(ref blk) => {
1722                 // containing cbox, will be closed by print-block at }
1723                 try!(self.cbox(indent_unit));
1724                 // head-box, will be closed by print-block after {
1725                 try!(self.ibox(0u));
1726                 try!(self.print_block(&**blk));
1727             }
1728             ast::ExprAssign(ref lhs, ref rhs) => {
1729                 try!(self.print_expr(&**lhs));
1730                 try!(space(&mut self.s));
1731                 try!(self.word_space("="));
1732                 try!(self.print_expr(&**rhs));
1733             }
1734             ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1735                 try!(self.print_expr(&**lhs));
1736                 try!(space(&mut self.s));
1737                 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1738                 try!(self.word_space("="));
1739                 try!(self.print_expr(&**rhs));
1740             }
1741             ast::ExprField(ref expr, id) => {
1742                 try!(self.print_expr(&**expr));
1743                 try!(word(&mut self.s, "."));
1744                 try!(self.print_ident(id.node));
1745             }
1746             ast::ExprTupField(ref expr, id) => {
1747                 try!(self.print_expr(&**expr));
1748                 try!(word(&mut self.s, "."));
1749                 try!(self.print_uint(id.node));
1750             }
1751             ast::ExprIndex(ref expr, ref index) => {
1752                 try!(self.print_expr(&**expr));
1753                 try!(word(&mut self.s, "["));
1754                 try!(self.print_expr(&**index));
1755                 try!(word(&mut self.s, "]"));
1756             }
1757             ast::ExprRange(ref start, ref end) => {
1758                 if let &Some(ref e) = start {
1759                     try!(self.print_expr(&**e));
1760                 }
1761                 if start.is_some() || end.is_some() {
1762                     try!(word(&mut self.s, ".."));
1763                 }
1764                 if let &Some(ref e) = end {
1765                     try!(self.print_expr(&**e));
1766                 }
1767             }
1768             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1769             ast::ExprBreak(opt_ident) => {
1770                 try!(word(&mut self.s, "break"));
1771                 try!(space(&mut self.s));
1772                 for ident in opt_ident.iter() {
1773                     try!(self.print_ident(*ident));
1774                     try!(space(&mut self.s));
1775                 }
1776             }
1777             ast::ExprAgain(opt_ident) => {
1778                 try!(word(&mut self.s, "continue"));
1779                 try!(space(&mut self.s));
1780                 for ident in opt_ident.iter() {
1781                     try!(self.print_ident(*ident));
1782                     try!(space(&mut self.s))
1783                 }
1784             }
1785             ast::ExprRet(ref result) => {
1786                 try!(word(&mut self.s, "return"));
1787                 match *result {
1788                     Some(ref expr) => {
1789                         try!(word(&mut self.s, " "));
1790                         try!(self.print_expr(&**expr));
1791                     }
1792                     _ => ()
1793                 }
1794             }
1795             ast::ExprInlineAsm(ref a) => {
1796                 try!(word(&mut self.s, "asm!"));
1797                 try!(self.popen());
1798                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1799                 try!(self.word_space(":"));
1800
1801                 try!(self.commasep(Inconsistent, a.outputs[],
1802                                    |s, &(ref co, ref o, is_rw)| {
1803                     match co.get().slice_shift_char() {
1804                         Some(('=', operand)) if is_rw => {
1805                             try!(s.print_string(format!("+{}", operand)[],
1806                                                 ast::CookedStr))
1807                         }
1808                         _ => try!(s.print_string(co.get(), ast::CookedStr))
1809                     }
1810                     try!(s.popen());
1811                     try!(s.print_expr(&**o));
1812                     try!(s.pclose());
1813                     Ok(())
1814                 }));
1815                 try!(space(&mut self.s));
1816                 try!(self.word_space(":"));
1817
1818                 try!(self.commasep(Inconsistent, a.inputs[],
1819                                    |s, &(ref co, ref o)| {
1820                     try!(s.print_string(co.get(), ast::CookedStr));
1821                     try!(s.popen());
1822                     try!(s.print_expr(&**o));
1823                     try!(s.pclose());
1824                     Ok(())
1825                 }));
1826                 try!(space(&mut self.s));
1827                 try!(self.word_space(":"));
1828
1829                 try!(self.commasep(Inconsistent, a.clobbers[],
1830                                    |s, co| {
1831                     try!(s.print_string(co.get(), ast::CookedStr));
1832                     Ok(())
1833                 }));
1834
1835                 let mut options = vec!();
1836                 if a.volatile {
1837                     options.push("volatile");
1838                 }
1839                 if a.alignstack {
1840                     options.push("alignstack");
1841                 }
1842                 if a.dialect == ast::AsmDialect::AsmIntel {
1843                     options.push("intel");
1844                 }
1845
1846                 if options.len() > 0 {
1847                     try!(space(&mut self.s));
1848                     try!(self.word_space(":"));
1849                     try!(self.commasep(Inconsistent, &*options,
1850                                        |s, &co| {
1851                         try!(s.print_string(co, ast::CookedStr));
1852                         Ok(())
1853                     }));
1854                 }
1855
1856                 try!(self.pclose());
1857             }
1858             ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1859             ast::ExprParen(ref e) => {
1860                 try!(self.popen());
1861                 try!(self.print_expr(&**e));
1862                 try!(self.pclose());
1863             }
1864         }
1865         try!(self.ann.post(self, NodeExpr(expr)));
1866         self.end()
1867     }
1868
1869     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1870         try!(self.print_pat(&*loc.pat));
1871         if let Some(ref ty) = loc.ty {
1872             try!(self.word_space(":"));
1873             try!(self.print_type(&**ty));
1874         }
1875         Ok(())
1876     }
1877
1878     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1879         try!(self.maybe_print_comment(decl.span.lo));
1880         match decl.node {
1881             ast::DeclLocal(ref loc) => {
1882                 try!(self.space_if_not_bol());
1883                 try!(self.ibox(indent_unit));
1884                 try!(self.word_nbsp("let"));
1885
1886                 try!(self.ibox(indent_unit));
1887                 try!(self.print_local_decl(&**loc));
1888                 try!(self.end());
1889                 if let Some(ref init) = loc.init {
1890                     try!(self.nbsp());
1891                     try!(self.word_space("="));
1892                     try!(self.print_expr(&**init));
1893                 }
1894                 self.end()
1895             }
1896             ast::DeclItem(ref item) => self.print_item(&**item)
1897         }
1898     }
1899
1900     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1901         if self.encode_idents_with_hygiene {
1902             let encoded = ident.encode_with_hygiene();
1903             try!(word(&mut self.s, encoded[]))
1904         } else {
1905             try!(word(&mut self.s, token::get_ident(ident).get()))
1906         }
1907         self.ann.post(self, NodeIdent(&ident))
1908     }
1909
1910     pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1911         word(&mut self.s, i.to_string()[])
1912     }
1913
1914     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1915         try!(word(&mut self.s, token::get_name(name).get()));
1916         self.ann.post(self, NodeName(&name))
1917     }
1918
1919     pub fn print_for_decl(&mut self, loc: &ast::Local,
1920                           coll: &ast::Expr) -> IoResult<()> {
1921         try!(self.print_local_decl(loc));
1922         try!(space(&mut self.s));
1923         try!(self.word_space("in"));
1924         self.print_expr(coll)
1925     }
1926
1927     fn print_path(&mut self,
1928                   path: &ast::Path,
1929                   colons_before_params: bool)
1930                   -> IoResult<()>
1931     {
1932         try!(self.maybe_print_comment(path.span.lo));
1933         if path.global {
1934             try!(word(&mut self.s, "::"));
1935         }
1936
1937         let mut first = true;
1938         for segment in path.segments.iter() {
1939             if first {
1940                 first = false
1941             } else {
1942                 try!(word(&mut self.s, "::"))
1943             }
1944
1945             try!(self.print_ident(segment.identifier));
1946
1947             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1948         }
1949
1950         Ok(())
1951     }
1952
1953     fn print_path_parameters(&mut self,
1954                              parameters: &ast::PathParameters,
1955                              colons_before_params: bool)
1956                              -> IoResult<()>
1957     {
1958         if parameters.is_empty() {
1959             return Ok(());
1960         }
1961
1962         if colons_before_params {
1963             try!(word(&mut self.s, "::"))
1964         }
1965
1966         match *parameters {
1967             ast::AngleBracketedParameters(ref data) => {
1968                 try!(word(&mut self.s, "<"));
1969
1970                 let mut comma = false;
1971                 for lifetime in data.lifetimes.iter() {
1972                     if comma {
1973                         try!(self.word_space(","))
1974                     }
1975                     try!(self.print_lifetime(lifetime));
1976                     comma = true;
1977                 }
1978
1979                 if !data.types.is_empty() {
1980                     if comma {
1981                         try!(self.word_space(","))
1982                     }
1983                     try!(self.commasep(
1984                         Inconsistent,
1985                         data.types[],
1986                         |s, ty| s.print_type(&**ty)));
1987                         comma = true;
1988                 }
1989
1990                 for binding in data.bindings.iter() {
1991                     if comma {
1992                         try!(self.word_space(","))
1993                     }
1994                     try!(self.print_ident(binding.ident));
1995                     try!(space(&mut self.s));
1996                     try!(self.word_space("="));
1997                     try!(self.print_type(&*binding.ty));
1998                     comma = true;
1999                 }
2000
2001                 try!(word(&mut self.s, ">"))
2002             }
2003
2004             ast::ParenthesizedParameters(ref data) => {
2005                 try!(word(&mut self.s, "("));
2006                 try!(self.commasep(
2007                     Inconsistent,
2008                     data.inputs[],
2009                     |s, ty| s.print_type(&**ty)));
2010                 try!(word(&mut self.s, ")"));
2011
2012                 match data.output {
2013                     None => { }
2014                     Some(ref ty) => {
2015                         try!(self.space_if_not_bol());
2016                         try!(self.word_space("->"));
2017                         try!(self.print_type(&**ty));
2018                     }
2019                 }
2020             }
2021         }
2022
2023         Ok(())
2024     }
2025
2026     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
2027         try!(self.maybe_print_comment(pat.span.lo));
2028         try!(self.ann.pre(self, NodePat(pat)));
2029         /* Pat isn't normalized, but the beauty of it
2030          is that it doesn't matter */
2031         match pat.node {
2032             ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2033             ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2034             ast::PatIdent(binding_mode, ref path1, ref sub) => {
2035                 match binding_mode {
2036                     ast::BindByRef(mutbl) => {
2037                         try!(self.word_nbsp("ref"));
2038                         try!(self.print_mutability(mutbl));
2039                     }
2040                     ast::BindByValue(ast::MutImmutable) => {}
2041                     ast::BindByValue(ast::MutMutable) => {
2042                         try!(self.word_nbsp("mut"));
2043                     }
2044                 }
2045                 try!(self.print_ident(path1.node));
2046                 match *sub {
2047                     Some(ref p) => {
2048                         try!(word(&mut self.s, "@"));
2049                         try!(self.print_pat(&**p));
2050                     }
2051                     None => ()
2052                 }
2053             }
2054             ast::PatEnum(ref path, ref args_) => {
2055                 try!(self.print_path(path, true));
2056                 match *args_ {
2057                     None => try!(word(&mut self.s, "(..)")),
2058                     Some(ref args) => {
2059                         if !args.is_empty() {
2060                             try!(self.popen());
2061                             try!(self.commasep(Inconsistent, args[],
2062                                               |s, p| s.print_pat(&**p)));
2063                             try!(self.pclose());
2064                         }
2065                     }
2066                 }
2067             }
2068             ast::PatStruct(ref path, ref fields, etc) => {
2069                 try!(self.print_path(path, true));
2070                 try!(self.nbsp());
2071                 try!(self.word_space("{"));
2072                 try!(self.commasep_cmnt(
2073                     Consistent, fields[],
2074                     |s, f| {
2075                         try!(s.cbox(indent_unit));
2076                         if !f.node.is_shorthand {
2077                             try!(s.print_ident(f.node.ident));
2078                             try!(s.word_nbsp(":"));
2079                         }
2080                         try!(s.print_pat(&*f.node.pat));
2081                         s.end()
2082                     },
2083                     |f| f.node.pat.span));
2084                 if etc {
2085                     if fields.len() != 0u { try!(self.word_space(",")); }
2086                     try!(word(&mut self.s, ".."));
2087                 }
2088                 try!(space(&mut self.s));
2089                 try!(word(&mut self.s, "}"));
2090             }
2091             ast::PatTup(ref elts) => {
2092                 try!(self.popen());
2093                 try!(self.commasep(Inconsistent,
2094                                    elts[],
2095                                    |s, p| s.print_pat(&**p)));
2096                 if elts.len() == 1 {
2097                     try!(word(&mut self.s, ","));
2098                 }
2099                 try!(self.pclose());
2100             }
2101             ast::PatBox(ref inner) => {
2102                 try!(word(&mut self.s, "box "));
2103                 try!(self.print_pat(&**inner));
2104             }
2105             ast::PatRegion(ref inner) => {
2106                 try!(word(&mut self.s, "&"));
2107                 try!(self.print_pat(&**inner));
2108             }
2109             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2110             ast::PatRange(ref begin, ref end) => {
2111                 try!(self.print_expr(&**begin));
2112                 try!(space(&mut self.s));
2113                 try!(word(&mut self.s, "..."));
2114                 try!(self.print_expr(&**end));
2115             }
2116             ast::PatVec(ref before, ref slice, ref after) => {
2117                 try!(word(&mut self.s, "["));
2118                 try!(self.commasep(Inconsistent,
2119                                    before[],
2120                                    |s, p| s.print_pat(&**p)));
2121                 for p in slice.iter() {
2122                     if !before.is_empty() { try!(self.word_space(",")); }
2123                     try!(self.print_pat(&**p));
2124                     match **p {
2125                         ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2126                             // this case is handled by print_pat
2127                         }
2128                         _ => try!(word(&mut self.s, "..")),
2129                     }
2130                     if !after.is_empty() { try!(self.word_space(",")); }
2131                 }
2132                 try!(self.commasep(Inconsistent,
2133                                    after[],
2134                                    |s, p| s.print_pat(&**p)));
2135                 try!(word(&mut self.s, "]"));
2136             }
2137             ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2138         }
2139         self.ann.post(self, NodePat(pat))
2140     }
2141
2142     fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2143         // I have no idea why this check is necessary, but here it
2144         // is :(
2145         if arm.attrs.is_empty() {
2146             try!(space(&mut self.s));
2147         }
2148         try!(self.cbox(indent_unit));
2149         try!(self.ibox(0u));
2150         try!(self.print_outer_attributes(arm.attrs[]));
2151         let mut first = true;
2152         for p in arm.pats.iter() {
2153             if first {
2154                 first = false;
2155             } else {
2156                 try!(space(&mut self.s));
2157                 try!(self.word_space("|"));
2158             }
2159             try!(self.print_pat(&**p));
2160         }
2161         try!(space(&mut self.s));
2162         if let Some(ref e) = arm.guard {
2163             try!(self.word_space("if"));
2164             try!(self.print_expr(&**e));
2165             try!(space(&mut self.s));
2166         }
2167         try!(self.word_space("=>"));
2168
2169         match arm.body.node {
2170             ast::ExprBlock(ref blk) => {
2171                 // the block will close the pattern's ibox
2172                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2173
2174                 // If it is a user-provided unsafe block, print a comma after it
2175                 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2176                     try!(word(&mut self.s, ","));
2177                 }
2178             }
2179             _ => {
2180                 try!(self.end()); // close the ibox for the pattern
2181                 try!(self.print_expr(&*arm.body));
2182                 try!(word(&mut self.s, ","));
2183             }
2184         }
2185         self.end() // close enclosing cbox
2186     }
2187
2188     // Returns whether it printed anything
2189     fn print_explicit_self(&mut self,
2190                            explicit_self: &ast::ExplicitSelf_,
2191                            mutbl: ast::Mutability) -> IoResult<bool> {
2192         try!(self.print_mutability(mutbl));
2193         match *explicit_self {
2194             ast::SelfStatic => { return Ok(false); }
2195             ast::SelfValue(_) => {
2196                 try!(word(&mut self.s, "self"));
2197             }
2198             ast::SelfRegion(ref lt, m, _) => {
2199                 try!(word(&mut self.s, "&"));
2200                 try!(self.print_opt_lifetime(lt));
2201                 try!(self.print_mutability(m));
2202                 try!(word(&mut self.s, "self"));
2203             }
2204             ast::SelfExplicit(ref typ, _) => {
2205                 try!(word(&mut self.s, "self"));
2206                 try!(self.word_space(":"));
2207                 try!(self.print_type(&**typ));
2208             }
2209         }
2210         return Ok(true);
2211     }
2212
2213     pub fn print_fn(&mut self,
2214                     decl: &ast::FnDecl,
2215                     unsafety: Option<ast::Unsafety>,
2216                     abi: abi::Abi,
2217                     name: ast::Ident,
2218                     generics: &ast::Generics,
2219                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
2220                     vis: ast::Visibility) -> IoResult<()> {
2221         try!(self.head(""));
2222         try!(self.print_fn_header_info(opt_explicit_self, unsafety, abi, vis));
2223         try!(self.nbsp());
2224         try!(self.print_ident(name));
2225         try!(self.print_generics(generics));
2226         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2227         self.print_where_clause(generics)
2228     }
2229
2230     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2231                          opt_explicit_self: Option<&ast::ExplicitSelf_>)
2232         -> IoResult<()> {
2233         // It is unfortunate to duplicate the commasep logic, but we want the
2234         // self type and the args all in the same box.
2235         try!(self.rbox(0u, Inconsistent));
2236         let mut first = true;
2237         for &explicit_self in opt_explicit_self.iter() {
2238             let m = match explicit_self {
2239                 &ast::SelfStatic => ast::MutImmutable,
2240                 _ => match decl.inputs[0].pat.node {
2241                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
2242                     _ => ast::MutImmutable
2243                 }
2244             };
2245             first = !try!(self.print_explicit_self(explicit_self, m));
2246         }
2247
2248         // HACK(eddyb) ignore the separately printed self argument.
2249         let args = if first {
2250             decl.inputs[]
2251         } else {
2252             decl.inputs.slice_from(1)
2253         };
2254
2255         for arg in args.iter() {
2256             if first { first = false; } else { try!(self.word_space(",")); }
2257             try!(self.print_arg(arg));
2258         }
2259
2260         self.end()
2261     }
2262
2263     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2264                                  opt_explicit_self: Option<&ast::ExplicitSelf_>)
2265         -> IoResult<()> {
2266         try!(self.popen());
2267         try!(self.print_fn_args(decl, opt_explicit_self));
2268         if decl.variadic {
2269             try!(word(&mut self.s, ", ..."));
2270         }
2271         try!(self.pclose());
2272
2273         self.print_fn_output(decl)
2274     }
2275
2276     pub fn print_fn_block_args(
2277             &mut self,
2278             decl: &ast::FnDecl,
2279             unboxed_closure_kind: Option<UnboxedClosureKind>)
2280             -> IoResult<()> {
2281         try!(word(&mut self.s, "|"));
2282         match unboxed_closure_kind {
2283             None => {}
2284             Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2285             Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2286             Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2287         }
2288         try!(self.print_fn_args(decl, None));
2289         try!(word(&mut self.s, "|"));
2290
2291         if let ast::Return(ref ty) = decl.output {
2292             if ty.node == ast::TyInfer {
2293                 return self.maybe_print_comment(ty.span.lo);
2294             }
2295         }
2296
2297         try!(self.space_if_not_bol());
2298         try!(self.word_space("->"));
2299         match decl.output {
2300             ast::Return(ref ty) => {
2301                 try!(self.print_type(&**ty));
2302                 self.maybe_print_comment(ty.span.lo)
2303             }
2304             ast::NoReturn(span) => {
2305                 try!(self.word_nbsp("!"));
2306                 self.maybe_print_comment(span.lo)
2307             }
2308         }
2309     }
2310
2311     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2312                                 -> IoResult<()> {
2313         match capture_clause {
2314             ast::CaptureByValue => self.word_space("move"),
2315             ast::CaptureByRef => Ok(()),
2316         }
2317     }
2318
2319     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2320         try!(word(&mut self.s, "proc"));
2321         try!(word(&mut self.s, "("));
2322         try!(self.print_fn_args(decl, None));
2323         try!(word(&mut self.s, ")"));
2324
2325         if let ast::Return(ref ty) = decl.output {
2326             if ty.node == ast::TyInfer {
2327                 return self.maybe_print_comment(ty.span.lo);
2328             }
2329         }
2330
2331         try!(self.space_if_not_bol());
2332         try!(self.word_space("->"));
2333         match decl.output {
2334             ast::Return(ref ty) => {
2335                 try!(self.print_type(&**ty));
2336                 self.maybe_print_comment(ty.span.lo)
2337             }
2338             ast::NoReturn(span) => {
2339                 try!(self.word_nbsp("!"));
2340                 self.maybe_print_comment(span.lo)
2341             }
2342         }
2343     }
2344
2345     pub fn print_bounds(&mut self,
2346                         prefix: &str,
2347                         bounds: &[ast::TyParamBound])
2348                         -> IoResult<()> {
2349         if !bounds.is_empty() {
2350             try!(word(&mut self.s, prefix));
2351             let mut first = true;
2352             for bound in bounds.iter() {
2353                 try!(self.nbsp());
2354                 if first {
2355                     first = false;
2356                 } else {
2357                     try!(self.word_space("+"));
2358                 }
2359
2360                 try!(match *bound {
2361                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2362                         self.print_poly_trait_ref(tref)
2363                     }
2364                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2365                         try!(word(&mut self.s, "?"));
2366                         self.print_poly_trait_ref(tref)
2367                     }
2368                     RegionTyParamBound(ref lt) => {
2369                         self.print_lifetime(lt)
2370                     }
2371                 })
2372             }
2373             Ok(())
2374         } else {
2375             Ok(())
2376         }
2377     }
2378
2379     pub fn print_lifetime(&mut self,
2380                           lifetime: &ast::Lifetime)
2381                           -> IoResult<()>
2382     {
2383         self.print_name(lifetime.name)
2384     }
2385
2386     pub fn print_lifetime_def(&mut self,
2387                               lifetime: &ast::LifetimeDef)
2388                               -> IoResult<()>
2389     {
2390         try!(self.print_lifetime(&lifetime.lifetime));
2391         let mut sep = ":";
2392         for v in lifetime.bounds.iter() {
2393             try!(word(&mut self.s, sep));
2394             try!(self.print_lifetime(v));
2395             sep = "+";
2396         }
2397         Ok(())
2398     }
2399
2400     pub fn print_generics(&mut self,
2401                           generics: &ast::Generics)
2402                           -> IoResult<()>
2403     {
2404         let total = generics.lifetimes.len() + generics.ty_params.len();
2405         if total == 0 {
2406             return Ok(());
2407         }
2408
2409         try!(word(&mut self.s, "<"));
2410
2411         let mut ints = Vec::new();
2412         for i in range(0u, total) {
2413             ints.push(i);
2414         }
2415
2416         try!(self.commasep(Inconsistent, ints[], |s, &idx| {
2417             if idx < generics.lifetimes.len() {
2418                 let lifetime = &generics.lifetimes[idx];
2419                 s.print_lifetime_def(lifetime)
2420             } else {
2421                 let idx = idx - generics.lifetimes.len();
2422                 let param = &generics.ty_params[idx];
2423                 s.print_ty_param(param)
2424             }
2425         }));
2426
2427         try!(word(&mut self.s, ">"));
2428         Ok(())
2429     }
2430
2431     pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
2432         try!(self.print_ident(param.ident));
2433         try!(self.print_bounds(":", param.bounds[]));
2434         match param.default {
2435             Some(ref default) => {
2436                 try!(space(&mut self.s));
2437                 try!(self.word_space("="));
2438                 self.print_type(&**default)
2439             }
2440             _ => Ok(())
2441         }
2442     }
2443
2444     pub fn print_where_clause(&mut self, generics: &ast::Generics)
2445                               -> IoResult<()> {
2446         if generics.where_clause.predicates.len() == 0 {
2447             return Ok(())
2448         }
2449
2450         try!(space(&mut self.s));
2451         try!(self.word_space("where"));
2452
2453         for (i, predicate) in generics.where_clause
2454                                       .predicates
2455                                       .iter()
2456                                       .enumerate() {
2457             if i != 0 {
2458                 try!(self.word_space(","));
2459             }
2460
2461             match predicate {
2462                 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty,
2463                                                                               ref bounds,
2464                                                                               ..}) => {
2465                     try!(self.print_type(&**bounded_ty));
2466                     try!(self.print_bounds(":", bounds.as_slice()));
2467                 }
2468                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2469                                                                                 ref bounds,
2470                                                                                 ..}) => {
2471                     try!(self.print_lifetime(lifetime));
2472                     try!(word(&mut self.s, ":"));
2473
2474                     for (i, bound) in bounds.iter().enumerate() {
2475                         try!(self.print_lifetime(bound));
2476
2477                         if i != 0 {
2478                             try!(word(&mut self.s, ":"));
2479                         }
2480                     }
2481                 }
2482                 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2483                     try!(self.print_path(path, false));
2484                     try!(space(&mut self.s));
2485                     try!(self.word_space("="));
2486                     try!(self.print_type(&**ty));
2487                 }
2488             }
2489         }
2490
2491         Ok(())
2492     }
2493
2494     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2495         try!(self.ibox(indent_unit));
2496         match item.node {
2497             ast::MetaWord(ref name) => {
2498                 try!(word(&mut self.s, name.get()));
2499             }
2500             ast::MetaNameValue(ref name, ref value) => {
2501                 try!(self.word_space(name.get()));
2502                 try!(self.word_space("="));
2503                 try!(self.print_literal(value));
2504             }
2505             ast::MetaList(ref name, ref items) => {
2506                 try!(word(&mut self.s, name.get()));
2507                 try!(self.popen());
2508                 try!(self.commasep(Consistent,
2509                                    items[],
2510                                    |s, i| s.print_meta_item(&**i)));
2511                 try!(self.pclose());
2512             }
2513         }
2514         self.end()
2515     }
2516
2517     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2518         match vp.node {
2519             ast::ViewPathSimple(ident, ref path, _) => {
2520                 try!(self.print_path(path, false));
2521
2522                 // FIXME(#6993) can't compare identifiers directly here
2523                 if path.segments.last().unwrap().identifier.name !=
2524                         ident.name {
2525                     try!(space(&mut self.s));
2526                     try!(self.word_space("as"));
2527                     try!(self.print_ident(ident));
2528                 }
2529
2530                 Ok(())
2531             }
2532
2533             ast::ViewPathGlob(ref path, _) => {
2534                 try!(self.print_path(path, false));
2535                 word(&mut self.s, "::*")
2536             }
2537
2538             ast::ViewPathList(ref path, ref idents, _) => {
2539                 if path.segments.is_empty() {
2540                     try!(word(&mut self.s, "{"));
2541                 } else {
2542                     try!(self.print_path(path, false));
2543                     try!(word(&mut self.s, "::{"));
2544                 }
2545                 try!(self.commasep(Inconsistent, idents[], |s, w| {
2546                     match w.node {
2547                         ast::PathListIdent { name, .. } => {
2548                             s.print_ident(name)
2549                         },
2550                         ast::PathListMod { .. } => {
2551                             word(&mut s.s, "self")
2552                         }
2553                     }
2554                 }));
2555                 word(&mut self.s, "}")
2556             }
2557         }
2558     }
2559
2560     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2561         try!(self.hardbreak_if_not_bol());
2562         try!(self.maybe_print_comment(item.span.lo));
2563         try!(self.print_outer_attributes(item.attrs[]));
2564         try!(self.print_visibility(item.vis));
2565         match item.node {
2566             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2567                 try!(self.head("extern crate"));
2568                 for &(ref p, style) in optional_path.iter() {
2569                     try!(self.print_string(p.get(), style));
2570                     try!(space(&mut self.s));
2571                     try!(word(&mut self.s, "as"));
2572                     try!(space(&mut self.s));
2573                 }
2574                 try!(self.print_ident(id));
2575             }
2576
2577             ast::ViewItemUse(ref vp) => {
2578                 try!(self.head("use"));
2579                 try!(self.print_view_path(&**vp));
2580             }
2581         }
2582         try!(word(&mut self.s, ";"));
2583         try!(self.end()); // end inner head-block
2584         self.end() // end outer head-block
2585     }
2586
2587     pub fn print_mutability(&mut self,
2588                             mutbl: ast::Mutability) -> IoResult<()> {
2589         match mutbl {
2590             ast::MutMutable => self.word_nbsp("mut"),
2591             ast::MutImmutable => Ok(()),
2592         }
2593     }
2594
2595     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2596         try!(self.print_mutability(mt.mutbl));
2597         self.print_type(&*mt.ty)
2598     }
2599
2600     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2601         try!(self.ibox(indent_unit));
2602         match input.ty.node {
2603             ast::TyInfer => try!(self.print_pat(&*input.pat)),
2604             _ => {
2605                 match input.pat.node {
2606                     ast::PatIdent(_, ref path1, _) if
2607                         path1.node.name ==
2608                             parse::token::special_idents::invalid.name => {
2609                         // Do nothing.
2610                     }
2611                     _ => {
2612                         try!(self.print_pat(&*input.pat));
2613                         try!(word(&mut self.s, ":"));
2614                         try!(space(&mut self.s));
2615                     }
2616                 }
2617                 try!(self.print_type(&*input.ty));
2618             }
2619         }
2620         self.end()
2621     }
2622
2623     pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2624         if let ast::Return(ref ty) = decl.output {
2625             match ty.node {
2626                 ast::TyTup(ref tys) if tys.is_empty() => {
2627                     return self.maybe_print_comment(ty.span.lo);
2628                 }
2629                 _ => ()
2630             }
2631         }
2632
2633         try!(self.space_if_not_bol());
2634         try!(self.ibox(indent_unit));
2635         try!(self.word_space("->"));
2636         match decl.output {
2637             ast::NoReturn(_) =>
2638                 try!(self.word_nbsp("!")),
2639             ast::Return(ref ty) =>
2640                 try!(self.print_type(&**ty))
2641         }
2642         try!(self.end());
2643
2644         match decl.output {
2645             ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2646             _ => Ok(())
2647         }
2648     }
2649
2650     pub fn print_ty_fn(&mut self,
2651                        opt_abi: Option<abi::Abi>,
2652                        opt_sigil: Option<char>,
2653                        unsafety: ast::Unsafety,
2654                        onceness: ast::Onceness,
2655                        decl: &ast::FnDecl,
2656                        id: Option<ast::Ident>,
2657                        bounds: &OwnedSlice<ast::TyParamBound>,
2658                        generics: Option<&ast::Generics>,
2659                        opt_explicit_self: Option<&ast::ExplicitSelf_>)
2660                        -> IoResult<()> {
2661         try!(self.ibox(indent_unit));
2662
2663         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2664         // function prints the sigil in the wrong place.  That should be fixed.
2665         if opt_sigil == Some('~') && onceness == ast::Once {
2666             try!(word(&mut self.s, "proc"));
2667         } else if opt_sigil == Some('&') {
2668             try!(self.print_unsafety(unsafety));
2669             try!(self.print_extern_opt_abi(opt_abi));
2670         } else {
2671             assert!(opt_sigil.is_none());
2672             try!(self.print_unsafety(unsafety));
2673             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2674             try!(word(&mut self.s, "fn"));
2675         }
2676
2677         match id {
2678             Some(id) => {
2679                 try!(word(&mut self.s, " "));
2680                 try!(self.print_ident(id));
2681             }
2682             _ => ()
2683         }
2684
2685         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2686         try!(zerobreak(&mut self.s));
2687
2688         if opt_sigil == Some('&') {
2689             try!(word(&mut self.s, "|"));
2690         } else {
2691             try!(self.popen());
2692         }
2693
2694         try!(self.print_fn_args(decl, opt_explicit_self));
2695
2696         if opt_sigil == Some('&') {
2697             try!(word(&mut self.s, "|"));
2698         } else {
2699             if decl.variadic {
2700                 try!(word(&mut self.s, ", ..."));
2701             }
2702             try!(self.pclose());
2703         }
2704
2705         try!(self.print_bounds(":", bounds[]));
2706
2707         try!(self.print_fn_output(decl));
2708
2709         match generics {
2710             Some(generics) => try!(self.print_where_clause(generics)),
2711             None => {}
2712         }
2713
2714         self.end()
2715     }
2716
2717     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2718                                         next_pos: Option<BytePos>)
2719         -> IoResult<()> {
2720         let cm = match self.cm {
2721             Some(cm) => cm,
2722             _ => return Ok(())
2723         };
2724         match self.next_comment() {
2725             Some(ref cmnt) => {
2726                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2727                 let span_line = cm.lookup_char_pos(span.hi);
2728                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2729                 let mut next = (*cmnt).pos + BytePos(1);
2730                 match next_pos { None => (), Some(p) => next = p }
2731                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2732                     span_line.line == comment_line.line {
2733                         try!(self.print_comment(cmnt));
2734                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2735                     }
2736             }
2737             _ => ()
2738         }
2739         Ok(())
2740     }
2741
2742     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2743         // If there aren't any remaining comments, then we need to manually
2744         // make sure there is a line break at the end.
2745         if self.next_comment().is_none() {
2746             try!(hardbreak(&mut self.s));
2747         }
2748         loop {
2749             match self.next_comment() {
2750                 Some(ref cmnt) => {
2751                     try!(self.print_comment(cmnt));
2752                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2753                 }
2754                 _ => break
2755             }
2756         }
2757         Ok(())
2758     }
2759
2760     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2761         try!(self.maybe_print_comment(lit.span.lo));
2762         match self.next_lit(lit.span.lo) {
2763             Some(ref ltrl) => {
2764                 return word(&mut self.s, (*ltrl).lit[]);
2765             }
2766             _ => ()
2767         }
2768         match lit.node {
2769             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2770             ast::LitByte(byte) => {
2771                 let mut res = String::from_str("b'");
2772                 ascii::escape_default(byte, |c| res.push(c as char));
2773                 res.push('\'');
2774                 word(&mut self.s, res[])
2775             }
2776             ast::LitChar(ch) => {
2777                 let mut res = String::from_str("'");
2778                 for c in ch.escape_default() {
2779                     res.push(c);
2780                 }
2781                 res.push('\'');
2782                 word(&mut self.s, res[])
2783             }
2784             ast::LitInt(i, t) => {
2785                 match t {
2786                     ast::SignedIntLit(st, ast::Plus) => {
2787                         word(&mut self.s,
2788                              ast_util::int_ty_to_string(st, Some(i as i64))[])
2789                     }
2790                     ast::SignedIntLit(st, ast::Minus) => {
2791                         let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2792                         word(&mut self.s,
2793                              format!("-{}", istr)[])
2794                     }
2795                     ast::UnsignedIntLit(ut) => {
2796                         word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[])
2797                     }
2798                     ast::UnsuffixedIntLit(ast::Plus) => {
2799                         word(&mut self.s, format!("{}", i)[])
2800                     }
2801                     ast::UnsuffixedIntLit(ast::Minus) => {
2802                         word(&mut self.s, format!("-{}", i)[])
2803                     }
2804                 }
2805             }
2806             ast::LitFloat(ref f, t) => {
2807                 word(&mut self.s,
2808                      format!(
2809                          "{}{}",
2810                          f.get(),
2811                          ast_util::float_ty_to_string(t)[])[])
2812             }
2813             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2814             ast::LitBool(val) => {
2815                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2816             }
2817             ast::LitBinary(ref v) => {
2818                 let mut escaped: String = String::new();
2819                 for &ch in v.iter() {
2820                     ascii::escape_default(ch as u8,
2821                                           |ch| escaped.push(ch as char));
2822                 }
2823                 word(&mut self.s, format!("b\"{}\"", escaped)[])
2824             }
2825         }
2826     }
2827
2828     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2829         match self.literals {
2830             Some(ref lits) => {
2831                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2832                     let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2833                     if ltrl.pos > pos { return None; }
2834                     self.cur_cmnt_and_lit.cur_lit += 1u;
2835                     if ltrl.pos == pos { return Some(ltrl); }
2836                 }
2837                 None
2838             }
2839             _ => None
2840         }
2841     }
2842
2843     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2844         loop {
2845             match self.next_comment() {
2846                 Some(ref cmnt) => {
2847                     if (*cmnt).pos < pos {
2848                         try!(self.print_comment(cmnt));
2849                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2850                     } else { break; }
2851                 }
2852                 _ => break
2853             }
2854         }
2855         Ok(())
2856     }
2857
2858     pub fn print_comment(&mut self,
2859                          cmnt: &comments::Comment) -> IoResult<()> {
2860         match cmnt.style {
2861             comments::Mixed => {
2862                 assert_eq!(cmnt.lines.len(), 1u);
2863                 try!(zerobreak(&mut self.s));
2864                 try!(word(&mut self.s, cmnt.lines[0][]));
2865                 zerobreak(&mut self.s)
2866             }
2867             comments::Isolated => {
2868                 try!(self.hardbreak_if_not_bol());
2869                 for line in cmnt.lines.iter() {
2870                     // Don't print empty lines because they will end up as trailing
2871                     // whitespace
2872                     if !line.is_empty() {
2873                         try!(word(&mut self.s, line[]));
2874                     }
2875                     try!(hardbreak(&mut self.s));
2876                 }
2877                 Ok(())
2878             }
2879             comments::Trailing => {
2880                 try!(word(&mut self.s, " "));
2881                 if cmnt.lines.len() == 1u {
2882                     try!(word(&mut self.s, cmnt.lines[0][]));
2883                     hardbreak(&mut self.s)
2884                 } else {
2885                     try!(self.ibox(0u));
2886                     for line in cmnt.lines.iter() {
2887                         if !line.is_empty() {
2888                             try!(word(&mut self.s, line[]));
2889                         }
2890                         try!(hardbreak(&mut self.s));
2891                     }
2892                     self.end()
2893                 }
2894             }
2895             comments::BlankLine => {
2896                 // We need to do at least one, possibly two hardbreaks.
2897                 let is_semi = match self.s.last_token() {
2898                     pp::String(s, _) => ";" == s,
2899                     _ => false
2900                 };
2901                 if is_semi || self.is_begin() || self.is_end() {
2902                     try!(hardbreak(&mut self.s));
2903                 }
2904                 hardbreak(&mut self.s)
2905             }
2906         }
2907     }
2908
2909     pub fn print_string(&mut self, st: &str,
2910                         style: ast::StrStyle) -> IoResult<()> {
2911         let st = match style {
2912             ast::CookedStr => {
2913                 (format!("\"{}\"", st.escape_default()))
2914             }
2915             ast::RawStr(n) => {
2916                 (format!("r{delim}\"{string}\"{delim}",
2917                          delim=repeat("#", n),
2918                          string=st))
2919             }
2920         };
2921         word(&mut self.s, st[])
2922     }
2923
2924     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2925         match self.comments {
2926             Some(ref cmnts) => {
2927                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2928                     Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2929                 } else {
2930                     None
2931                 }
2932             }
2933             _ => None
2934         }
2935     }
2936
2937     pub fn print_opt_unsafety(&mut self,
2938                             opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
2939         match opt_unsafety {
2940             Some(unsafety) => self.print_unsafety(unsafety),
2941             None => Ok(())
2942         }
2943     }
2944
2945     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2946                                                   opt_abi: Option<abi::Abi>)
2947         -> IoResult<()> {
2948         match opt_abi {
2949             Some(abi::Rust) => Ok(()),
2950             Some(abi) => {
2951                 try!(self.word_nbsp("extern"));
2952                 self.word_nbsp(abi.to_string()[])
2953             }
2954             None => Ok(())
2955         }
2956     }
2957
2958     pub fn print_extern_opt_abi(&mut self,
2959                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2960         match opt_abi {
2961             Some(abi) => {
2962                 try!(self.word_nbsp("extern"));
2963                 self.word_nbsp(abi.to_string()[])
2964             }
2965             None => Ok(())
2966         }
2967     }
2968
2969     pub fn print_fn_header_info(&mut self,
2970                                 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2971                                 opt_unsafety: Option<ast::Unsafety>,
2972                                 abi: abi::Abi,
2973                                 vis: ast::Visibility) -> IoResult<()> {
2974         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2975         try!(self.print_opt_unsafety(opt_unsafety));
2976
2977         if abi != abi::Rust {
2978             try!(self.word_nbsp("extern"));
2979             try!(self.word_nbsp(abi.to_string()[]));
2980         }
2981
2982         word(&mut self.s, "fn")
2983     }
2984
2985     pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
2986         match s {
2987             ast::Unsafety::Normal => Ok(()),
2988             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2989         }
2990     }
2991 }
2992
2993 fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() }
2994
2995 #[cfg(test)]
2996 mod test {
2997     use super::*;
2998
2999     use ast;
3000     use ast_util;
3001     use codemap;
3002     use parse::token;
3003     use ptr::P;
3004
3005     #[test]
3006     fn test_fun_to_string() {
3007         let abba_ident = token::str_to_ident("abba");
3008
3009         let decl = ast::FnDecl {
3010             inputs: Vec::new(),
3011             output: ast::Return(P(ast::Ty {id: 0,
3012                                node: ast::TyTup(vec![]),
3013                                span: codemap::DUMMY_SP})),
3014             variadic: false
3015         };
3016         let generics = ast_util::empty_generics();
3017         assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3018                                None, &generics),
3019                    "fn abba()");
3020     }
3021
3022     #[test]
3023     fn test_variant_to_string() {
3024         let ident = token::str_to_ident("principal_skinner");
3025
3026         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3027             name: ident,
3028             attrs: Vec::new(),
3029             // making this up as I go.... ?
3030             kind: ast::TupleVariantKind(Vec::new()),
3031             id: 0,
3032             disr_expr: None,
3033             vis: ast::Public,
3034         });
3035
3036         let varstr = variant_to_string(&var);
3037         assert_eq!(varstr, "pub principal_skinner");
3038     }
3039
3040     #[test]
3041     fn test_signed_int_to_string() {
3042         let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3043         let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3044         assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3045                    lit_to_string(&codemap::dummy_spanned(neg_int)));
3046     }
3047 }