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