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