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