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