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