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