]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
Rollup merge of #40583 - jseyfried:fix_include_macro_regression, r=nrc
[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::ImplicitSelf => {
1099                 word(&mut self.s, "Self")?;
1100             }
1101             ast::TyKind::Mac(ref m) => {
1102                 self.print_mac(m, token::Paren)?;
1103             }
1104         }
1105         self.end()
1106     }
1107
1108     pub fn print_foreign_item(&mut self,
1109                               item: &ast::ForeignItem) -> io::Result<()> {
1110         self.hardbreak_if_not_bol()?;
1111         self.maybe_print_comment(item.span.lo)?;
1112         self.print_outer_attributes(&item.attrs)?;
1113         match item.node {
1114             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1115                 self.head("")?;
1116                 self.print_fn(decl, ast::Unsafety::Normal,
1117                               ast::Constness::NotConst,
1118                               Abi::Rust, Some(item.ident),
1119                               generics, &item.vis)?;
1120                 self.end()?; // end head-ibox
1121                 word(&mut self.s, ";")?;
1122                 self.end() // end the outer fn box
1123             }
1124             ast::ForeignItemKind::Static(ref t, m) => {
1125                 self.head(&visibility_qualified(&item.vis, "static"))?;
1126                 if m {
1127                     self.word_space("mut")?;
1128                 }
1129                 self.print_ident(item.ident)?;
1130                 self.word_space(":")?;
1131                 self.print_type(&t)?;
1132                 word(&mut self.s, ";")?;
1133                 self.end()?; // end the head-ibox
1134                 self.end() // end the outer cbox
1135             }
1136         }
1137     }
1138
1139     fn print_associated_const(&mut self,
1140                               ident: ast::Ident,
1141                               ty: &ast::Ty,
1142                               default: Option<&ast::Expr>,
1143                               vis: &ast::Visibility)
1144                               -> io::Result<()>
1145     {
1146         word(&mut self.s, &visibility_qualified(vis, ""))?;
1147         self.word_space("const")?;
1148         self.print_ident(ident)?;
1149         self.word_space(":")?;
1150         self.print_type(ty)?;
1151         if let Some(expr) = default {
1152             space(&mut self.s)?;
1153             self.word_space("=")?;
1154             self.print_expr(expr)?;
1155         }
1156         word(&mut self.s, ";")
1157     }
1158
1159     fn print_associated_type(&mut self,
1160                              ident: ast::Ident,
1161                              bounds: Option<&ast::TyParamBounds>,
1162                              ty: Option<&ast::Ty>)
1163                              -> io::Result<()> {
1164         self.word_space("type")?;
1165         self.print_ident(ident)?;
1166         if let Some(bounds) = bounds {
1167             self.print_bounds(":", bounds)?;
1168         }
1169         if let Some(ty) = ty {
1170             space(&mut self.s)?;
1171             self.word_space("=")?;
1172             self.print_type(ty)?;
1173         }
1174         word(&mut self.s, ";")
1175     }
1176
1177     /// Pretty-print an item
1178     pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
1179         self.hardbreak_if_not_bol()?;
1180         self.maybe_print_comment(item.span.lo)?;
1181         self.print_outer_attributes(&item.attrs)?;
1182         self.ann.pre(self, NodeItem(item))?;
1183         match item.node {
1184             ast::ItemKind::ExternCrate(ref optional_path) => {
1185                 self.head(&visibility_qualified(&item.vis, "extern crate"))?;
1186                 if let Some(p) = *optional_path {
1187                     let val = p.as_str();
1188                     if val.contains("-") {
1189                         self.print_string(&val, ast::StrStyle::Cooked)?;
1190                     } else {
1191                         self.print_name(p)?;
1192                     }
1193                     space(&mut self.s)?;
1194                     word(&mut self.s, "as")?;
1195                     space(&mut self.s)?;
1196                 }
1197                 self.print_ident(item.ident)?;
1198                 word(&mut self.s, ";")?;
1199                 self.end()?; // end inner head-block
1200                 self.end()?; // end outer head-block
1201             }
1202             ast::ItemKind::Use(ref vp) => {
1203                 self.head(&visibility_qualified(&item.vis, "use"))?;
1204                 self.print_view_path(&vp)?;
1205                 word(&mut self.s, ";")?;
1206                 self.end()?; // end inner head-block
1207                 self.end()?; // end outer head-block
1208             }
1209             ast::ItemKind::Static(ref ty, m, ref expr) => {
1210                 self.head(&visibility_qualified(&item.vis, "static"))?;
1211                 if m == ast::Mutability::Mutable {
1212                     self.word_space("mut")?;
1213                 }
1214                 self.print_ident(item.ident)?;
1215                 self.word_space(":")?;
1216                 self.print_type(&ty)?;
1217                 space(&mut self.s)?;
1218                 self.end()?; // end the head-ibox
1219
1220                 self.word_space("=")?;
1221                 self.print_expr(&expr)?;
1222                 word(&mut self.s, ";")?;
1223                 self.end()?; // end the outer cbox
1224             }
1225             ast::ItemKind::Const(ref ty, ref expr) => {
1226                 self.head(&visibility_qualified(&item.vis, "const"))?;
1227                 self.print_ident(item.ident)?;
1228                 self.word_space(":")?;
1229                 self.print_type(&ty)?;
1230                 space(&mut self.s)?;
1231                 self.end()?; // end the head-ibox
1232
1233                 self.word_space("=")?;
1234                 self.print_expr(&expr)?;
1235                 word(&mut self.s, ";")?;
1236                 self.end()?; // end the outer cbox
1237             }
1238             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
1239                 self.head("")?;
1240                 self.print_fn(
1241                     decl,
1242                     unsafety,
1243                     constness.node,
1244                     abi,
1245                     Some(item.ident),
1246                     typarams,
1247                     &item.vis
1248                 )?;
1249                 word(&mut self.s, " ")?;
1250                 self.print_block_with_attrs(&body, &item.attrs)?;
1251             }
1252             ast::ItemKind::Mod(ref _mod) => {
1253                 self.head(&visibility_qualified(&item.vis, "mod"))?;
1254                 self.print_ident(item.ident)?;
1255                 self.nbsp()?;
1256                 self.bopen()?;
1257                 self.print_mod(_mod, &item.attrs)?;
1258                 self.bclose(item.span)?;
1259             }
1260             ast::ItemKind::ForeignMod(ref nmod) => {
1261                 self.head("extern")?;
1262                 self.word_nbsp(&nmod.abi.to_string())?;
1263                 self.bopen()?;
1264                 self.print_foreign_mod(nmod, &item.attrs)?;
1265                 self.bclose(item.span)?;
1266             }
1267             ast::ItemKind::Ty(ref ty, ref params) => {
1268                 self.ibox(INDENT_UNIT)?;
1269                 self.ibox(0)?;
1270                 self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
1271                 self.print_ident(item.ident)?;
1272                 self.print_generics(params)?;
1273                 self.end()?; // end the inner ibox
1274
1275                 self.print_where_clause(&params.where_clause)?;
1276                 space(&mut self.s)?;
1277                 self.word_space("=")?;
1278                 self.print_type(&ty)?;
1279                 word(&mut self.s, ";")?;
1280                 self.end()?; // end the outer ibox
1281             }
1282             ast::ItemKind::Enum(ref enum_definition, ref params) => {
1283                 self.print_enum_def(
1284                     enum_definition,
1285                     params,
1286                     item.ident,
1287                     item.span,
1288                     &item.vis
1289                 )?;
1290             }
1291             ast::ItemKind::Struct(ref struct_def, ref generics) => {
1292                 self.head(&visibility_qualified(&item.vis, "struct"))?;
1293                 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1294             }
1295             ast::ItemKind::Union(ref struct_def, ref generics) => {
1296                 self.head(&visibility_qualified(&item.vis, "union"))?;
1297                 self.print_struct(&struct_def, generics, item.ident, item.span, true)?;
1298             }
1299             ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
1300                 self.head("")?;
1301                 self.print_visibility(&item.vis)?;
1302                 self.print_unsafety(unsafety)?;
1303                 self.word_nbsp("impl")?;
1304                 self.print_trait_ref(trait_ref)?;
1305                 space(&mut self.s)?;
1306                 self.word_space("for")?;
1307                 self.word_space("..")?;
1308                 self.bopen()?;
1309                 self.bclose(item.span)?;
1310             }
1311             ast::ItemKind::Impl(unsafety,
1312                           polarity,
1313                           ref generics,
1314                           ref opt_trait,
1315                           ref ty,
1316                           ref impl_items) => {
1317                 self.head("")?;
1318                 self.print_visibility(&item.vis)?;
1319                 self.print_unsafety(unsafety)?;
1320                 self.word_nbsp("impl")?;
1321
1322                 if generics.is_parameterized() {
1323                     self.print_generics(generics)?;
1324                     space(&mut self.s)?;
1325                 }
1326
1327                 match polarity {
1328                     ast::ImplPolarity::Negative => {
1329                         word(&mut self.s, "!")?;
1330                     },
1331                     _ => {}
1332                 }
1333
1334                 if let Some(ref t) = *opt_trait {
1335                     self.print_trait_ref(t)?;
1336                     space(&mut self.s)?;
1337                     self.word_space("for")?;
1338                 }
1339
1340                 self.print_type(&ty)?;
1341                 self.print_where_clause(&generics.where_clause)?;
1342
1343                 space(&mut self.s)?;
1344                 self.bopen()?;
1345                 self.print_inner_attributes(&item.attrs)?;
1346                 for impl_item in impl_items {
1347                     self.print_impl_item(impl_item)?;
1348                 }
1349                 self.bclose(item.span)?;
1350             }
1351             ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
1352                 self.head("")?;
1353                 self.print_visibility(&item.vis)?;
1354                 self.print_unsafety(unsafety)?;
1355                 self.word_nbsp("trait")?;
1356                 self.print_ident(item.ident)?;
1357                 self.print_generics(generics)?;
1358                 let mut real_bounds = Vec::with_capacity(bounds.len());
1359                 for b in bounds.iter() {
1360                     if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1361                         space(&mut self.s)?;
1362                         self.word_space("for ?")?;
1363                         self.print_trait_ref(&ptr.trait_ref)?;
1364                     } else {
1365                         real_bounds.push(b.clone());
1366                     }
1367                 }
1368                 self.print_bounds(":", &real_bounds[..])?;
1369                 self.print_where_clause(&generics.where_clause)?;
1370                 word(&mut self.s, " ")?;
1371                 self.bopen()?;
1372                 for trait_item in trait_items {
1373                     self.print_trait_item(trait_item)?;
1374                 }
1375                 self.bclose(item.span)?;
1376             }
1377             ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
1378                 self.print_path(&node.path, false, 0, false)?;
1379                 word(&mut self.s, "! ")?;
1380                 self.print_ident(item.ident)?;
1381                 self.cbox(INDENT_UNIT)?;
1382                 self.popen()?;
1383                 self.print_tts(node.stream())?;
1384                 self.pclose()?;
1385                 word(&mut self.s, ";")?;
1386                 self.end()?;
1387             }
1388             ast::ItemKind::MacroDef(ref tts) => {
1389                 word(&mut self.s, "macro_rules! ")?;
1390                 self.print_ident(item.ident)?;
1391                 self.cbox(INDENT_UNIT)?;
1392                 self.popen()?;
1393                 self.print_tts(tts.clone().into())?;
1394                 self.pclose()?;
1395                 word(&mut self.s, ";")?;
1396                 self.end()?;
1397             }
1398         }
1399         self.ann.post(self, NodeItem(item))
1400     }
1401
1402     fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
1403         self.print_path(&t.path, false, 0, false)
1404     }
1405
1406     fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
1407         if !lifetimes.is_empty() {
1408             word(&mut self.s, "for<")?;
1409             let mut comma = false;
1410             for lifetime_def in lifetimes {
1411                 if comma {
1412                     self.word_space(",")?
1413                 }
1414                 self.print_outer_attributes_inline(&lifetime_def.attrs)?;
1415                 self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
1416                 comma = true;
1417             }
1418             word(&mut self.s, ">")?;
1419         }
1420         Ok(())
1421     }
1422
1423     fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
1424         self.print_formal_lifetime_list(&t.bound_lifetimes)?;
1425         self.print_trait_ref(&t.trait_ref)
1426     }
1427
1428     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1429                           generics: &ast::Generics, ident: ast::Ident,
1430                           span: syntax_pos::Span,
1431                           visibility: &ast::Visibility) -> io::Result<()> {
1432         self.head(&visibility_qualified(visibility, "enum"))?;
1433         self.print_ident(ident)?;
1434         self.print_generics(generics)?;
1435         self.print_where_clause(&generics.where_clause)?;
1436         space(&mut self.s)?;
1437         self.print_variants(&enum_definition.variants, span)
1438     }
1439
1440     pub fn print_variants(&mut self,
1441                           variants: &[ast::Variant],
1442                           span: syntax_pos::Span) -> io::Result<()> {
1443         self.bopen()?;
1444         for v in variants {
1445             self.space_if_not_bol()?;
1446             self.maybe_print_comment(v.span.lo)?;
1447             self.print_outer_attributes(&v.node.attrs)?;
1448             self.ibox(INDENT_UNIT)?;
1449             self.print_variant(v)?;
1450             word(&mut self.s, ",")?;
1451             self.end()?;
1452             self.maybe_print_trailing_comment(v.span, None)?;
1453         }
1454         self.bclose(span)
1455     }
1456
1457     pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
1458         match *vis {
1459             ast::Visibility::Public => self.word_nbsp("pub"),
1460             ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
1461             ast::Visibility::Restricted { ref path, .. } => {
1462                 let path = to_string(|s| s.print_path(path, false, 0, true));
1463                 self.word_nbsp(&format!("pub({})", path))
1464             }
1465             ast::Visibility::Inherited => Ok(())
1466         }
1467     }
1468
1469     pub fn print_struct(&mut self,
1470                         struct_def: &ast::VariantData,
1471                         generics: &ast::Generics,
1472                         ident: ast::Ident,
1473                         span: syntax_pos::Span,
1474                         print_finalizer: bool) -> io::Result<()> {
1475         self.print_ident(ident)?;
1476         self.print_generics(generics)?;
1477         if !struct_def.is_struct() {
1478             if struct_def.is_tuple() {
1479                 self.popen()?;
1480                 self.commasep(
1481                     Inconsistent, struct_def.fields(),
1482                     |s, field| {
1483                         s.maybe_print_comment(field.span.lo)?;
1484                         s.print_outer_attributes(&field.attrs)?;
1485                         s.print_visibility(&field.vis)?;
1486                         s.print_type(&field.ty)
1487                     }
1488                 )?;
1489                 self.pclose()?;
1490             }
1491             self.print_where_clause(&generics.where_clause)?;
1492             if print_finalizer {
1493                 word(&mut self.s, ";")?;
1494             }
1495             self.end()?;
1496             self.end() // close the outer-box
1497         } else {
1498             self.print_where_clause(&generics.where_clause)?;
1499             self.nbsp()?;
1500             self.bopen()?;
1501             self.hardbreak_if_not_bol()?;
1502
1503             for field in struct_def.fields() {
1504                 self.hardbreak_if_not_bol()?;
1505                 self.maybe_print_comment(field.span.lo)?;
1506                 self.print_outer_attributes(&field.attrs)?;
1507                 self.print_visibility(&field.vis)?;
1508                 self.print_ident(field.ident.unwrap())?;
1509                 self.word_nbsp(":")?;
1510                 self.print_type(&field.ty)?;
1511                 word(&mut self.s, ",")?;
1512             }
1513
1514             self.bclose(span)
1515         }
1516     }
1517
1518     pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
1519         self.head("")?;
1520         let generics = ast::Generics::default();
1521         self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
1522         match v.node.disr_expr {
1523             Some(ref d) => {
1524                 space(&mut self.s)?;
1525                 self.word_space("=")?;
1526                 self.print_expr(&d)
1527             }
1528             _ => Ok(())
1529         }
1530     }
1531
1532     pub fn print_method_sig(&mut self,
1533                             ident: ast::Ident,
1534                             m: &ast::MethodSig,
1535                             vis: &ast::Visibility)
1536                             -> io::Result<()> {
1537         self.print_fn(&m.decl,
1538                       m.unsafety,
1539                       m.constness.node,
1540                       m.abi,
1541                       Some(ident),
1542                       &m.generics,
1543                       vis)
1544     }
1545
1546     pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
1547                             -> io::Result<()> {
1548         self.ann.pre(self, NodeSubItem(ti.id))?;
1549         self.hardbreak_if_not_bol()?;
1550         self.maybe_print_comment(ti.span.lo)?;
1551         self.print_outer_attributes(&ti.attrs)?;
1552         match ti.node {
1553             ast::TraitItemKind::Const(ref ty, ref default) => {
1554                 self.print_associated_const(ti.ident, &ty,
1555                                             default.as_ref().map(|expr| &**expr),
1556                                             &ast::Visibility::Inherited)?;
1557             }
1558             ast::TraitItemKind::Method(ref sig, ref body) => {
1559                 if body.is_some() {
1560                     self.head("")?;
1561                 }
1562                 self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
1563                 if let Some(ref body) = *body {
1564                     self.nbsp()?;
1565                     self.print_block_with_attrs(body, &ti.attrs)?;
1566                 } else {
1567                     word(&mut self.s, ";")?;
1568                 }
1569             }
1570             ast::TraitItemKind::Type(ref bounds, ref default) => {
1571                 self.print_associated_type(ti.ident, Some(bounds),
1572                                            default.as_ref().map(|ty| &**ty))?;
1573             }
1574             ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1575                 // code copied from ItemKind::Mac:
1576                 self.print_path(&node.path, false, 0, false)?;
1577                 word(&mut self.s, "! ")?;
1578                 self.cbox(INDENT_UNIT)?;
1579                 self.popen()?;
1580                 self.print_tts(node.stream())?;
1581                 self.pclose()?;
1582                 word(&mut self.s, ";")?;
1583                 self.end()?
1584             }
1585         }
1586         self.ann.post(self, NodeSubItem(ti.id))
1587     }
1588
1589     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
1590         self.ann.pre(self, NodeSubItem(ii.id))?;
1591         self.hardbreak_if_not_bol()?;
1592         self.maybe_print_comment(ii.span.lo)?;
1593         self.print_outer_attributes(&ii.attrs)?;
1594         if let ast::Defaultness::Default = ii.defaultness {
1595             self.word_nbsp("default")?;
1596         }
1597         match ii.node {
1598             ast::ImplItemKind::Const(ref ty, ref expr) => {
1599                 self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?;
1600             }
1601             ast::ImplItemKind::Method(ref sig, ref body) => {
1602                 self.head("")?;
1603                 self.print_method_sig(ii.ident, sig, &ii.vis)?;
1604                 self.nbsp()?;
1605                 self.print_block_with_attrs(body, &ii.attrs)?;
1606             }
1607             ast::ImplItemKind::Type(ref ty) => {
1608                 self.print_associated_type(ii.ident, None, Some(ty))?;
1609             }
1610             ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
1611                 // code copied from ItemKind::Mac:
1612                 self.print_path(&node.path, false, 0, false)?;
1613                 word(&mut self.s, "! ")?;
1614                 self.cbox(INDENT_UNIT)?;
1615                 self.popen()?;
1616                 self.print_tts(node.stream())?;
1617                 self.pclose()?;
1618                 word(&mut self.s, ";")?;
1619                 self.end()?
1620             }
1621         }
1622         self.ann.post(self, NodeSubItem(ii.id))
1623     }
1624
1625     pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
1626         self.maybe_print_comment(st.span.lo)?;
1627         match st.node {
1628             ast::StmtKind::Local(ref loc) => {
1629                 self.print_outer_attributes(&loc.attrs)?;
1630                 self.space_if_not_bol()?;
1631                 self.ibox(INDENT_UNIT)?;
1632                 self.word_nbsp("let")?;
1633
1634                 self.ibox(INDENT_UNIT)?;
1635                 self.print_local_decl(&loc)?;
1636                 self.end()?;
1637                 if let Some(ref init) = loc.init {
1638                     self.nbsp()?;
1639                     self.word_space("=")?;
1640                     self.print_expr(&init)?;
1641                 }
1642                 word(&mut self.s, ";")?;
1643                 self.end()?;
1644             }
1645             ast::StmtKind::Item(ref item) => self.print_item(&item)?,
1646             ast::StmtKind::Expr(ref expr) => {
1647                 self.space_if_not_bol()?;
1648                 self.print_expr_outer_attr_style(&expr, false)?;
1649                 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1650                     word(&mut self.s, ";")?;
1651                 }
1652             }
1653             ast::StmtKind::Semi(ref expr) => {
1654                 self.space_if_not_bol()?;
1655                 self.print_expr_outer_attr_style(&expr, false)?;
1656                 word(&mut self.s, ";")?;
1657             }
1658             ast::StmtKind::Mac(ref mac) => {
1659                 let (ref mac, style, ref attrs) = **mac;
1660                 self.space_if_not_bol()?;
1661                 self.print_outer_attributes(&attrs)?;
1662                 let delim = match style {
1663                     ast::MacStmtStyle::Braces => token::Brace,
1664                     _ => token::Paren
1665                 };
1666                 self.print_mac(&mac, delim)?;
1667                 if style == ast::MacStmtStyle::Semicolon {
1668                     word(&mut self.s, ";")?;
1669                 }
1670             }
1671         }
1672         self.maybe_print_trailing_comment(st.span, None)
1673     }
1674
1675     pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
1676         self.print_block_with_attrs(blk, &[])
1677     }
1678
1679     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
1680         self.print_block_unclosed_indent(blk, INDENT_UNIT)
1681     }
1682
1683     pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
1684                                             attrs: &[ast::Attribute])
1685                                            -> io::Result<()> {
1686         self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
1687     }
1688
1689     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1690                                        indented: usize) -> io::Result<()> {
1691         self.print_block_maybe_unclosed(blk, indented, &[], false)
1692     }
1693
1694     pub fn print_block_with_attrs(&mut self,
1695                                   blk: &ast::Block,
1696                                   attrs: &[ast::Attribute]) -> io::Result<()> {
1697         self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
1698     }
1699
1700     pub fn print_block_maybe_unclosed(&mut self,
1701                                       blk: &ast::Block,
1702                                       indented: usize,
1703                                       attrs: &[ast::Attribute],
1704                                       close_box: bool) -> io::Result<()> {
1705         match blk.rules {
1706             BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
1707             BlockCheckMode::Default => ()
1708         }
1709         self.maybe_print_comment(blk.span.lo)?;
1710         self.ann.pre(self, NodeBlock(blk))?;
1711         self.bopen()?;
1712
1713         self.print_inner_attributes(attrs)?;
1714
1715         for (i, st) in blk.stmts.iter().enumerate() {
1716             match st.node {
1717                 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1718                     self.maybe_print_comment(st.span.lo)?;
1719                     self.space_if_not_bol()?;
1720                     self.print_expr_outer_attr_style(&expr, false)?;
1721                     self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
1722                 }
1723                 _ => self.print_stmt(st)?,
1724             }
1725         }
1726
1727         self.bclose_maybe_open(blk.span, indented, close_box)?;
1728         self.ann.post(self, NodeBlock(blk))
1729     }
1730
1731     fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
1732         match els {
1733             Some(_else) => {
1734                 match _else.node {
1735                     // "another else-if"
1736                     ast::ExprKind::If(ref i, ref then, ref e) => {
1737                         self.cbox(INDENT_UNIT - 1)?;
1738                         self.ibox(0)?;
1739                         word(&mut self.s, " else if ")?;
1740                         self.print_expr(&i)?;
1741                         space(&mut self.s)?;
1742                         self.print_block(&then)?;
1743                         self.print_else(e.as_ref().map(|e| &**e))
1744                     }
1745                     // "another else-if-let"
1746                     ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
1747                         self.cbox(INDENT_UNIT - 1)?;
1748                         self.ibox(0)?;
1749                         word(&mut self.s, " else if let ")?;
1750                         self.print_pat(&pat)?;
1751                         space(&mut self.s)?;
1752                         self.word_space("=")?;
1753                         self.print_expr(&expr)?;
1754                         space(&mut self.s)?;
1755                         self.print_block(&then)?;
1756                         self.print_else(e.as_ref().map(|e| &**e))
1757                     }
1758                     // "final else"
1759                     ast::ExprKind::Block(ref b) => {
1760                         self.cbox(INDENT_UNIT - 1)?;
1761                         self.ibox(0)?;
1762                         word(&mut self.s, " else ")?;
1763                         self.print_block(&b)
1764                     }
1765                     // BLEAH, constraints would be great here
1766                     _ => {
1767                         panic!("print_if saw if with weird alternative");
1768                     }
1769                 }
1770             }
1771             _ => Ok(())
1772         }
1773     }
1774
1775     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1776                     elseopt: Option<&ast::Expr>) -> io::Result<()> {
1777         self.head("if")?;
1778         self.print_expr(test)?;
1779         space(&mut self.s)?;
1780         self.print_block(blk)?;
1781         self.print_else(elseopt)
1782     }
1783
1784     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1785                         elseopt: Option<&ast::Expr>) -> io::Result<()> {
1786         self.head("if let")?;
1787         self.print_pat(pat)?;
1788         space(&mut self.s)?;
1789         self.word_space("=")?;
1790         self.print_expr(expr)?;
1791         space(&mut self.s)?;
1792         self.print_block(blk)?;
1793         self.print_else(elseopt)
1794     }
1795
1796     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1797                      -> io::Result<()> {
1798         self.print_path(&m.node.path, false, 0, false)?;
1799         word(&mut self.s, "!")?;
1800         match delim {
1801             token::Paren => self.popen()?,
1802             token::Bracket => word(&mut self.s, "[")?,
1803             token::Brace => {
1804                 self.head("")?;
1805                 self.bopen()?;
1806             }
1807             token::NoDelim => {}
1808         }
1809         self.print_tts(m.node.stream())?;
1810         match delim {
1811             token::Paren => self.pclose(),
1812             token::Bracket => word(&mut self.s, "]"),
1813             token::Brace => self.bclose(m.span),
1814             token::NoDelim => Ok(()),
1815         }
1816     }
1817
1818
1819     fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
1820         self.popen()?;
1821         self.commasep_exprs(Inconsistent, args)?;
1822         self.pclose()
1823     }
1824
1825     pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
1826                                       binop: ast::BinOp) -> bool {
1827         match sub_expr.node {
1828             ast::ExprKind::Binary(ref sub_op, _, _) => {
1829                 if AssocOp::from_ast_binop(sub_op.node).precedence() <
1830                     AssocOp::from_ast_binop(binop.node).precedence() {
1831                     true
1832                 } else {
1833                     false
1834                 }
1835             }
1836             _ => true
1837         }
1838     }
1839
1840     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
1841         let needs_par = needs_parentheses(expr);
1842         if needs_par {
1843             self.popen()?;
1844         }
1845         self.print_expr(expr)?;
1846         if needs_par {
1847             self.pclose()?;
1848         }
1849         Ok(())
1850     }
1851
1852     fn print_expr_in_place(&mut self,
1853                            place: &ast::Expr,
1854                            expr: &ast::Expr) -> io::Result<()> {
1855         self.print_expr_maybe_paren(place)?;
1856         space(&mut self.s)?;
1857         self.word_space("<-")?;
1858         self.print_expr_maybe_paren(expr)
1859     }
1860
1861     fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1862                       attrs: &[Attribute]) -> io::Result<()> {
1863         self.ibox(INDENT_UNIT)?;
1864         word(&mut self.s, "[")?;
1865         self.print_inner_attributes_inline(attrs)?;
1866         self.commasep_exprs(Inconsistent, &exprs[..])?;
1867         word(&mut self.s, "]")?;
1868         self.end()
1869     }
1870
1871     fn print_expr_repeat(&mut self,
1872                          element: &ast::Expr,
1873                          count: &ast::Expr,
1874                          attrs: &[Attribute]) -> io::Result<()> {
1875         self.ibox(INDENT_UNIT)?;
1876         word(&mut self.s, "[")?;
1877         self.print_inner_attributes_inline(attrs)?;
1878         self.print_expr(element)?;
1879         self.word_space(";")?;
1880         self.print_expr(count)?;
1881         word(&mut self.s, "]")?;
1882         self.end()
1883     }
1884
1885     fn print_expr_struct(&mut self,
1886                          path: &ast::Path,
1887                          fields: &[ast::Field],
1888                          wth: &Option<P<ast::Expr>>,
1889                          attrs: &[Attribute]) -> io::Result<()> {
1890         self.print_path(path, true, 0, false)?;
1891         word(&mut self.s, "{")?;
1892         self.print_inner_attributes_inline(attrs)?;
1893         self.commasep_cmnt(
1894             Consistent,
1895             &fields[..],
1896             |s, field| {
1897                 s.ibox(INDENT_UNIT)?;
1898                 if !field.is_shorthand {
1899                     s.print_ident(field.ident.node)?;
1900                     s.word_space(":")?;
1901                 }
1902                 s.print_expr(&field.expr)?;
1903                 s.end()
1904             },
1905             |f| f.span)?;
1906         match *wth {
1907             Some(ref expr) => {
1908                 self.ibox(INDENT_UNIT)?;
1909                 if !fields.is_empty() {
1910                     word(&mut self.s, ",")?;
1911                     space(&mut self.s)?;
1912                 }
1913                 word(&mut self.s, "..")?;
1914                 self.print_expr(&expr)?;
1915                 self.end()?;
1916             }
1917             _ => if !fields.is_empty() {
1918                 word(&mut self.s, ",")?
1919             }
1920         }
1921         word(&mut self.s, "}")?;
1922         Ok(())
1923     }
1924
1925     fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1926                       attrs: &[Attribute]) -> io::Result<()> {
1927         self.popen()?;
1928         self.print_inner_attributes_inline(attrs)?;
1929         self.commasep_exprs(Inconsistent, &exprs[..])?;
1930         if exprs.len() == 1 {
1931             word(&mut self.s, ",")?;
1932         }
1933         self.pclose()
1934     }
1935
1936     fn print_expr_call(&mut self,
1937                        func: &ast::Expr,
1938                        args: &[P<ast::Expr>]) -> io::Result<()> {
1939         self.print_expr_maybe_paren(func)?;
1940         self.print_call_post(args)
1941     }
1942
1943     fn print_expr_method_call(&mut self,
1944                               ident: ast::SpannedIdent,
1945                               tys: &[P<ast::Ty>],
1946                               args: &[P<ast::Expr>]) -> io::Result<()> {
1947         let base_args = &args[1..];
1948         self.print_expr(&args[0])?;
1949         word(&mut self.s, ".")?;
1950         self.print_ident(ident.node)?;
1951         if !tys.is_empty() {
1952             word(&mut self.s, "::<")?;
1953             self.commasep(Inconsistent, tys,
1954                           |s, ty| s.print_type(&ty))?;
1955             word(&mut self.s, ">")?;
1956         }
1957         self.print_call_post(base_args)
1958     }
1959
1960     fn print_expr_binary(&mut self,
1961                          op: ast::BinOp,
1962                          lhs: &ast::Expr,
1963                          rhs: &ast::Expr) -> io::Result<()> {
1964         if self.check_expr_bin_needs_paren(lhs, op) {
1965             self.print_expr_maybe_paren(lhs)?;
1966         } else {
1967             self.print_expr(lhs)?;
1968         }
1969         space(&mut self.s)?;
1970         self.word_space(op.node.to_string())?;
1971         if self.check_expr_bin_needs_paren(rhs, op) {
1972             self.print_expr_maybe_paren(rhs)
1973         } else {
1974             self.print_expr(rhs)
1975         }
1976     }
1977
1978     fn print_expr_unary(&mut self,
1979                         op: ast::UnOp,
1980                         expr: &ast::Expr) -> io::Result<()> {
1981         word(&mut self.s, ast::UnOp::to_string(op))?;
1982         self.print_expr_maybe_paren(expr)
1983     }
1984
1985     fn print_expr_addr_of(&mut self,
1986                           mutability: ast::Mutability,
1987                           expr: &ast::Expr) -> io::Result<()> {
1988         word(&mut self.s, "&")?;
1989         self.print_mutability(mutability)?;
1990         self.print_expr_maybe_paren(expr)
1991     }
1992
1993     pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
1994         self.print_expr_outer_attr_style(expr, true)
1995     }
1996
1997     fn print_expr_outer_attr_style(&mut self,
1998                                   expr: &ast::Expr,
1999                                   is_inline: bool) -> io::Result<()> {
2000         self.maybe_print_comment(expr.span.lo)?;
2001
2002         let attrs = &expr.attrs;
2003         if is_inline {
2004             self.print_outer_attributes_inline(attrs)?;
2005         } else {
2006             self.print_outer_attributes(attrs)?;
2007         }
2008
2009         self.ibox(INDENT_UNIT)?;
2010         self.ann.pre(self, NodeExpr(expr))?;
2011         match expr.node {
2012             ast::ExprKind::Box(ref expr) => {
2013                 self.word_space("box")?;
2014                 self.print_expr(expr)?;
2015             }
2016             ast::ExprKind::InPlace(ref place, ref expr) => {
2017                 self.print_expr_in_place(place, expr)?;
2018             }
2019             ast::ExprKind::Array(ref exprs) => {
2020                 self.print_expr_vec(&exprs[..], attrs)?;
2021             }
2022             ast::ExprKind::Repeat(ref element, ref count) => {
2023                 self.print_expr_repeat(&element, &count, attrs)?;
2024             }
2025             ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2026                 self.print_expr_struct(path, &fields[..], wth, attrs)?;
2027             }
2028             ast::ExprKind::Tup(ref exprs) => {
2029                 self.print_expr_tup(&exprs[..], attrs)?;
2030             }
2031             ast::ExprKind::Call(ref func, ref args) => {
2032                 self.print_expr_call(&func, &args[..])?;
2033             }
2034             ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
2035                 self.print_expr_method_call(ident, &tys[..], &args[..])?;
2036             }
2037             ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2038                 self.print_expr_binary(op, &lhs, &rhs)?;
2039             }
2040             ast::ExprKind::Unary(op, ref expr) => {
2041                 self.print_expr_unary(op, &expr)?;
2042             }
2043             ast::ExprKind::AddrOf(m, ref expr) => {
2044                 self.print_expr_addr_of(m, &expr)?;
2045             }
2046             ast::ExprKind::Lit(ref lit) => {
2047                 self.print_literal(&lit)?;
2048             }
2049             ast::ExprKind::Cast(ref expr, ref ty) => {
2050                 if let ast::ExprKind::Cast(..) = expr.node {
2051                     self.print_expr(&expr)?;
2052                 } else {
2053                     self.print_expr_maybe_paren(&expr)?;
2054                 }
2055                 space(&mut self.s)?;
2056                 self.word_space("as")?;
2057                 self.print_type(&ty)?;
2058             }
2059             ast::ExprKind::Type(ref expr, ref ty) => {
2060                 self.print_expr(&expr)?;
2061                 self.word_space(":")?;
2062                 self.print_type(&ty)?;
2063             }
2064             ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2065                 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?;
2066             }
2067             ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
2068                 self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?;
2069             }
2070             ast::ExprKind::While(ref test, ref blk, opt_ident) => {
2071                 if let Some(ident) = opt_ident {
2072                     self.print_ident(ident.node)?;
2073                     self.word_space(":")?;
2074                 }
2075                 self.head("while")?;
2076                 self.print_expr(&test)?;
2077                 space(&mut self.s)?;
2078                 self.print_block_with_attrs(&blk, attrs)?;
2079             }
2080             ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
2081                 if let Some(ident) = opt_ident {
2082                     self.print_ident(ident.node)?;
2083                     self.word_space(":")?;
2084                 }
2085                 self.head("while let")?;
2086                 self.print_pat(&pat)?;
2087                 space(&mut self.s)?;
2088                 self.word_space("=")?;
2089                 self.print_expr(&expr)?;
2090                 space(&mut self.s)?;
2091                 self.print_block_with_attrs(&blk, attrs)?;
2092             }
2093             ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
2094                 if let Some(ident) = opt_ident {
2095                     self.print_ident(ident.node)?;
2096                     self.word_space(":")?;
2097                 }
2098                 self.head("for")?;
2099                 self.print_pat(&pat)?;
2100                 space(&mut self.s)?;
2101                 self.word_space("in")?;
2102                 self.print_expr(&iter)?;
2103                 space(&mut self.s)?;
2104                 self.print_block_with_attrs(&blk, attrs)?;
2105             }
2106             ast::ExprKind::Loop(ref blk, opt_ident) => {
2107                 if let Some(ident) = opt_ident {
2108                     self.print_ident(ident.node)?;
2109                     self.word_space(":")?;
2110                 }
2111                 self.head("loop")?;
2112                 space(&mut self.s)?;
2113                 self.print_block_with_attrs(&blk, attrs)?;
2114             }
2115             ast::ExprKind::Match(ref expr, ref arms) => {
2116                 self.cbox(INDENT_UNIT)?;
2117                 self.ibox(4)?;
2118                 self.word_nbsp("match")?;
2119                 self.print_expr(&expr)?;
2120                 space(&mut self.s)?;
2121                 self.bopen()?;
2122                 self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
2123                 for arm in arms {
2124                     self.print_arm(arm)?;
2125                 }
2126                 self.bclose_(expr.span, INDENT_UNIT)?;
2127             }
2128             ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
2129                 self.print_capture_clause(capture_clause)?;
2130
2131                 self.print_fn_block_args(&decl)?;
2132                 space(&mut self.s)?;
2133                 self.print_expr(body)?;
2134                 self.end()?; // need to close a box
2135
2136                 // a box will be closed by print_expr, but we didn't want an overall
2137                 // wrapper so we closed the corresponding opening. so create an
2138                 // empty box to satisfy the close.
2139                 self.ibox(0)?;
2140             }
2141             ast::ExprKind::Block(ref blk) => {
2142                 // containing cbox, will be closed by print-block at }
2143                 self.cbox(INDENT_UNIT)?;
2144                 // head-box, will be closed by print-block after {
2145                 self.ibox(0)?;
2146                 self.print_block_with_attrs(&blk, attrs)?;
2147             }
2148             ast::ExprKind::Assign(ref lhs, ref rhs) => {
2149                 self.print_expr(&lhs)?;
2150                 space(&mut self.s)?;
2151                 self.word_space("=")?;
2152                 self.print_expr(&rhs)?;
2153             }
2154             ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2155                 self.print_expr(&lhs)?;
2156                 space(&mut self.s)?;
2157                 word(&mut self.s, op.node.to_string())?;
2158                 self.word_space("=")?;
2159                 self.print_expr(&rhs)?;
2160             }
2161             ast::ExprKind::Field(ref expr, id) => {
2162                 self.print_expr(&expr)?;
2163                 word(&mut self.s, ".")?;
2164                 self.print_ident(id.node)?;
2165             }
2166             ast::ExprKind::TupField(ref expr, id) => {
2167                 self.print_expr(&expr)?;
2168                 word(&mut self.s, ".")?;
2169                 self.print_usize(id.node)?;
2170             }
2171             ast::ExprKind::Index(ref expr, ref index) => {
2172                 self.print_expr(&expr)?;
2173                 word(&mut self.s, "[")?;
2174                 self.print_expr(&index)?;
2175                 word(&mut self.s, "]")?;
2176             }
2177             ast::ExprKind::Range(ref start, ref end, limits) => {
2178                 if let &Some(ref e) = start {
2179                     self.print_expr(&e)?;
2180                 }
2181                 if limits == ast::RangeLimits::HalfOpen {
2182                     word(&mut self.s, "..")?;
2183                 } else {
2184                     word(&mut self.s, "...")?;
2185                 }
2186                 if let &Some(ref e) = end {
2187                     self.print_expr(&e)?;
2188                 }
2189             }
2190             ast::ExprKind::Path(None, ref path) => {
2191                 self.print_path(path, true, 0, false)?
2192             }
2193             ast::ExprKind::Path(Some(ref qself), ref path) => {
2194                 self.print_qpath(path, qself, true)?
2195             }
2196             ast::ExprKind::Break(opt_ident, ref opt_expr) => {
2197                 word(&mut self.s, "break")?;
2198                 space(&mut self.s)?;
2199                 if let Some(ident) = opt_ident {
2200                     self.print_ident(ident.node)?;
2201                     space(&mut self.s)?;
2202                 }
2203                 if let Some(ref expr) = *opt_expr {
2204                     self.print_expr(expr)?;
2205                     space(&mut self.s)?;
2206                 }
2207             }
2208             ast::ExprKind::Continue(opt_ident) => {
2209                 word(&mut self.s, "continue")?;
2210                 space(&mut self.s)?;
2211                 if let Some(ident) = opt_ident {
2212                     self.print_ident(ident.node)?;
2213                     space(&mut self.s)?
2214                 }
2215             }
2216             ast::ExprKind::Ret(ref result) => {
2217                 word(&mut self.s, "return")?;
2218                 match *result {
2219                     Some(ref expr) => {
2220                         word(&mut self.s, " ")?;
2221                         self.print_expr(&expr)?;
2222                     }
2223                     _ => ()
2224                 }
2225             }
2226             ast::ExprKind::InlineAsm(ref a) => {
2227                 word(&mut self.s, "asm!")?;
2228                 self.popen()?;
2229                 self.print_string(&a.asm.as_str(), a.asm_str_style)?;
2230                 self.word_space(":")?;
2231
2232                 self.commasep(Inconsistent, &a.outputs, |s, out| {
2233                     let constraint = out.constraint.as_str();
2234                     let mut ch = constraint.chars();
2235                     match ch.next() {
2236                         Some('=') if out.is_rw => {
2237                             s.print_string(&format!("+{}", ch.as_str()),
2238                                            ast::StrStyle::Cooked)?
2239                         }
2240                         _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
2241                     }
2242                     s.popen()?;
2243                     s.print_expr(&out.expr)?;
2244                     s.pclose()?;
2245                     Ok(())
2246                 })?;
2247                 space(&mut self.s)?;
2248                 self.word_space(":")?;
2249
2250                 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2251                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2252                     s.popen()?;
2253                     s.print_expr(&o)?;
2254                     s.pclose()?;
2255                     Ok(())
2256                 })?;
2257                 space(&mut self.s)?;
2258                 self.word_space(":")?;
2259
2260                 self.commasep(Inconsistent, &a.clobbers,
2261                                    |s, co| {
2262                     s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
2263                     Ok(())
2264                 })?;
2265
2266                 let mut options = vec![];
2267                 if a.volatile {
2268                     options.push("volatile");
2269                 }
2270                 if a.alignstack {
2271                     options.push("alignstack");
2272                 }
2273                 if a.dialect == ast::AsmDialect::Intel {
2274                     options.push("intel");
2275                 }
2276
2277                 if !options.is_empty() {
2278                     space(&mut self.s)?;
2279                     self.word_space(":")?;
2280                     self.commasep(Inconsistent, &options,
2281                                   |s, &co| {
2282                                       s.print_string(co, ast::StrStyle::Cooked)?;
2283                                       Ok(())
2284                                   })?;
2285                 }
2286
2287                 self.pclose()?;
2288             }
2289             ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2290             ast::ExprKind::Paren(ref e) => {
2291                 self.popen()?;
2292                 self.print_inner_attributes_inline(attrs)?;
2293                 self.print_expr(&e)?;
2294                 self.pclose()?;
2295             },
2296             ast::ExprKind::Try(ref e) => {
2297                 self.print_expr(e)?;
2298                 word(&mut self.s, "?")?
2299             }
2300             ast::ExprKind::Catch(ref blk) => {
2301                 self.head("do catch")?;
2302                 space(&mut self.s)?;
2303                 self.print_block_with_attrs(&blk, attrs)?
2304             }
2305         }
2306         self.ann.post(self, NodeExpr(expr))?;
2307         self.end()
2308     }
2309
2310     pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
2311         self.print_pat(&loc.pat)?;
2312         if let Some(ref ty) = loc.ty {
2313             self.word_space(":")?;
2314             self.print_type(&ty)?;
2315         }
2316         Ok(())
2317     }
2318
2319     pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
2320         word(&mut self.s, &ident.name.as_str())?;
2321         self.ann.post(self, NodeIdent(&ident))
2322     }
2323
2324     pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
2325         word(&mut self.s, &i.to_string())
2326     }
2327
2328     pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
2329         word(&mut self.s, &name.as_str())?;
2330         self.ann.post(self, NodeName(&name))
2331     }
2332
2333     pub fn print_for_decl(&mut self, loc: &ast::Local,
2334                           coll: &ast::Expr) -> io::Result<()> {
2335         self.print_local_decl(loc)?;
2336         space(&mut self.s)?;
2337         self.word_space("in")?;
2338         self.print_expr(coll)
2339     }
2340
2341     fn print_path(&mut self,
2342                   path: &ast::Path,
2343                   colons_before_params: bool,
2344                   depth: usize,
2345                   defaults_to_global: bool)
2346                   -> io::Result<()>
2347     {
2348         self.maybe_print_comment(path.span.lo)?;
2349
2350         let mut segments = path.segments[..path.segments.len()-depth].iter();
2351         if defaults_to_global && path.is_global() {
2352             segments.next();
2353         }
2354         for (i, segment) in segments.enumerate() {
2355             if i > 0 {
2356                 word(&mut self.s, "::")?
2357             }
2358             if segment.identifier.name != keywords::CrateRoot.name() &&
2359                segment.identifier.name != "$crate" {
2360                 self.print_ident(segment.identifier)?;
2361                 if let Some(ref parameters) = segment.parameters {
2362                     self.print_path_parameters(parameters, colons_before_params)?;
2363                 }
2364             }
2365         }
2366
2367         Ok(())
2368     }
2369
2370     fn print_qpath(&mut self,
2371                    path: &ast::Path,
2372                    qself: &ast::QSelf,
2373                    colons_before_params: bool)
2374                    -> io::Result<()>
2375     {
2376         word(&mut self.s, "<")?;
2377         self.print_type(&qself.ty)?;
2378         if qself.position > 0 {
2379             space(&mut self.s)?;
2380             self.word_space("as")?;
2381             let depth = path.segments.len() - qself.position;
2382             self.print_path(&path, false, depth, false)?;
2383         }
2384         word(&mut self.s, ">")?;
2385         word(&mut self.s, "::")?;
2386         let item_segment = path.segments.last().unwrap();
2387         self.print_ident(item_segment.identifier)?;
2388         match item_segment.parameters {
2389             Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
2390             None => Ok(()),
2391         }
2392     }
2393
2394     fn print_path_parameters(&mut self,
2395                              parameters: &ast::PathParameters,
2396                              colons_before_params: bool)
2397                              -> io::Result<()>
2398     {
2399         if colons_before_params {
2400             word(&mut self.s, "::")?
2401         }
2402
2403         match *parameters {
2404             ast::PathParameters::AngleBracketed(ref data) => {
2405                 word(&mut self.s, "<")?;
2406
2407                 let mut comma = false;
2408                 for lifetime in &data.lifetimes {
2409                     if comma {
2410                         self.word_space(",")?
2411                     }
2412                     self.print_lifetime(lifetime)?;
2413                     comma = true;
2414                 }
2415
2416                 if !data.types.is_empty() {
2417                     if comma {
2418                         self.word_space(",")?
2419                     }
2420                     self.commasep(
2421                         Inconsistent,
2422                         &data.types,
2423                         |s, ty| s.print_type(&ty))?;
2424                         comma = true;
2425                 }
2426
2427                 for binding in data.bindings.iter() {
2428                     if comma {
2429                         self.word_space(",")?
2430                     }
2431                     self.print_ident(binding.ident)?;
2432                     space(&mut self.s)?;
2433                     self.word_space("=")?;
2434                     self.print_type(&binding.ty)?;
2435                     comma = true;
2436                 }
2437
2438                 word(&mut self.s, ">")?
2439             }
2440
2441             ast::PathParameters::Parenthesized(ref data) => {
2442                 word(&mut self.s, "(")?;
2443                 self.commasep(
2444                     Inconsistent,
2445                     &data.inputs,
2446                     |s, ty| s.print_type(&ty))?;
2447                 word(&mut self.s, ")")?;
2448
2449                 if let Some(ref ty) = data.output {
2450                     self.space_if_not_bol()?;
2451                     self.word_space("->")?;
2452                     self.print_type(&ty)?;
2453                 }
2454             }
2455         }
2456
2457         Ok(())
2458     }
2459
2460     pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
2461         self.maybe_print_comment(pat.span.lo)?;
2462         self.ann.pre(self, NodePat(pat))?;
2463         /* Pat isn't normalized, but the beauty of it
2464          is that it doesn't matter */
2465         match pat.node {
2466             PatKind::Wild => word(&mut self.s, "_")?,
2467             PatKind::Ident(binding_mode, ref path1, ref sub) => {
2468                 match binding_mode {
2469                     ast::BindingMode::ByRef(mutbl) => {
2470                         self.word_nbsp("ref")?;
2471                         self.print_mutability(mutbl)?;
2472                     }
2473                     ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2474                     ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2475                         self.word_nbsp("mut")?;
2476                     }
2477                 }
2478                 self.print_ident(path1.node)?;
2479                 if let Some(ref p) = *sub {
2480                     word(&mut self.s, "@")?;
2481                     self.print_pat(&p)?;
2482                 }
2483             }
2484             PatKind::TupleStruct(ref path, ref elts, ddpos) => {
2485                 self.print_path(path, true, 0, false)?;
2486                 self.popen()?;
2487                 if let Some(ddpos) = ddpos {
2488                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2489                     if ddpos != 0 {
2490                         self.word_space(",")?;
2491                     }
2492                     word(&mut self.s, "..")?;
2493                     if ddpos != elts.len() {
2494                         word(&mut self.s, ",")?;
2495                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2496                     }
2497                 } else {
2498                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2499                 }
2500                 self.pclose()?;
2501             }
2502             PatKind::Path(None, ref path) => {
2503                 self.print_path(path, true, 0, false)?;
2504             }
2505             PatKind::Path(Some(ref qself), ref path) => {
2506                 self.print_qpath(path, qself, false)?;
2507             }
2508             PatKind::Struct(ref path, ref fields, etc) => {
2509                 self.print_path(path, true, 0, false)?;
2510                 self.nbsp()?;
2511                 self.word_space("{")?;
2512                 self.commasep_cmnt(
2513                     Consistent, &fields[..],
2514                     |s, f| {
2515                         s.cbox(INDENT_UNIT)?;
2516                         if !f.node.is_shorthand {
2517                             s.print_ident(f.node.ident)?;
2518                             s.word_nbsp(":")?;
2519                         }
2520                         s.print_pat(&f.node.pat)?;
2521                         s.end()
2522                     },
2523                     |f| f.node.pat.span)?;
2524                 if etc {
2525                     if !fields.is_empty() { self.word_space(",")?; }
2526                     word(&mut self.s, "..")?;
2527                 }
2528                 space(&mut self.s)?;
2529                 word(&mut self.s, "}")?;
2530             }
2531             PatKind::Tuple(ref elts, ddpos) => {
2532                 self.popen()?;
2533                 if let Some(ddpos) = ddpos {
2534                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?;
2535                     if ddpos != 0 {
2536                         self.word_space(",")?;
2537                     }
2538                     word(&mut self.s, "..")?;
2539                     if ddpos != elts.len() {
2540                         word(&mut self.s, ",")?;
2541                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?;
2542                     }
2543                 } else {
2544                     self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?;
2545                     if elts.len() == 1 {
2546                         word(&mut self.s, ",")?;
2547                     }
2548                 }
2549                 self.pclose()?;
2550             }
2551             PatKind::Box(ref inner) => {
2552                 word(&mut self.s, "box ")?;
2553                 self.print_pat(&inner)?;
2554             }
2555             PatKind::Ref(ref inner, mutbl) => {
2556                 word(&mut self.s, "&")?;
2557                 if mutbl == ast::Mutability::Mutable {
2558                     word(&mut self.s, "mut ")?;
2559                 }
2560                 self.print_pat(&inner)?;
2561             }
2562             PatKind::Lit(ref e) => self.print_expr(&**e)?,
2563             PatKind::Range(ref begin, ref end, ref end_kind) => {
2564                 self.print_expr(&begin)?;
2565                 space(&mut self.s)?;
2566                 match *end_kind {
2567                     RangeEnd::Included => word(&mut self.s, "...")?,
2568                     RangeEnd::Excluded => word(&mut self.s, "..")?,
2569                 }
2570                 self.print_expr(&end)?;
2571             }
2572             PatKind::Slice(ref before, ref slice, ref after) => {
2573                 word(&mut self.s, "[")?;
2574                 self.commasep(Inconsistent,
2575                                    &before[..],
2576                                    |s, p| s.print_pat(&p))?;
2577                 if let Some(ref p) = *slice {
2578                     if !before.is_empty() { self.word_space(",")?; }
2579                     if p.node != PatKind::Wild {
2580                         self.print_pat(&p)?;
2581                     }
2582                     word(&mut self.s, "..")?;
2583                     if !after.is_empty() { self.word_space(",")?; }
2584                 }
2585                 self.commasep(Inconsistent,
2586                                    &after[..],
2587                                    |s, p| s.print_pat(&p))?;
2588                 word(&mut self.s, "]")?;
2589             }
2590             PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
2591         }
2592         self.ann.post(self, NodePat(pat))
2593     }
2594
2595     fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
2596         // I have no idea why this check is necessary, but here it
2597         // is :(
2598         if arm.attrs.is_empty() {
2599             space(&mut self.s)?;
2600         }
2601         self.cbox(INDENT_UNIT)?;
2602         self.ibox(0)?;
2603         self.maybe_print_comment(arm.pats[0].span.lo)?;
2604         self.print_outer_attributes(&arm.attrs)?;
2605         let mut first = true;
2606         for p in &arm.pats {
2607             if first {
2608                 first = false;
2609             } else {
2610                 space(&mut self.s)?;
2611                 self.word_space("|")?;
2612             }
2613             self.print_pat(&p)?;
2614         }
2615         space(&mut self.s)?;
2616         if let Some(ref e) = arm.guard {
2617             self.word_space("if")?;
2618             self.print_expr(&e)?;
2619             space(&mut self.s)?;
2620         }
2621         self.word_space("=>")?;
2622
2623         match arm.body.node {
2624             ast::ExprKind::Block(ref blk) => {
2625                 // the block will close the pattern's ibox
2626                 self.print_block_unclosed_indent(&blk, INDENT_UNIT)?;
2627
2628                 // If it is a user-provided unsafe block, print a comma after it
2629                 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2630                     word(&mut self.s, ",")?;
2631                 }
2632             }
2633             _ => {
2634                 self.end()?; // close the ibox for the pattern
2635                 self.print_expr(&arm.body)?;
2636                 word(&mut self.s, ",")?;
2637             }
2638         }
2639         self.end() // close enclosing cbox
2640     }
2641
2642     fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
2643         match explicit_self.node {
2644             SelfKind::Value(m) => {
2645                 self.print_mutability(m)?;
2646                 word(&mut self.s, "self")
2647             }
2648             SelfKind::Region(ref lt, m) => {
2649                 word(&mut self.s, "&")?;
2650                 self.print_opt_lifetime(lt)?;
2651                 self.print_mutability(m)?;
2652                 word(&mut self.s, "self")
2653             }
2654             SelfKind::Explicit(ref typ, m) => {
2655                 self.print_mutability(m)?;
2656                 word(&mut self.s, "self")?;
2657                 self.word_space(":")?;
2658                 self.print_type(&typ)
2659             }
2660         }
2661     }
2662
2663     pub fn print_fn(&mut self,
2664                     decl: &ast::FnDecl,
2665                     unsafety: ast::Unsafety,
2666                     constness: ast::Constness,
2667                     abi: abi::Abi,
2668                     name: Option<ast::Ident>,
2669                     generics: &ast::Generics,
2670                     vis: &ast::Visibility) -> io::Result<()> {
2671         self.print_fn_header_info(unsafety, constness, abi, vis)?;
2672
2673         if let Some(name) = name {
2674             self.nbsp()?;
2675             self.print_ident(name)?;
2676         }
2677         self.print_generics(generics)?;
2678         self.print_fn_args_and_ret(decl)?;
2679         self.print_where_clause(&generics.where_clause)
2680     }
2681
2682     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
2683         -> io::Result<()> {
2684         self.popen()?;
2685         self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
2686         if decl.variadic {
2687             word(&mut self.s, ", ...")?;
2688         }
2689         self.pclose()?;
2690
2691         self.print_fn_output(decl)
2692     }
2693
2694     pub fn print_fn_block_args(
2695             &mut self,
2696             decl: &ast::FnDecl)
2697             -> io::Result<()> {
2698         word(&mut self.s, "|")?;
2699         self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
2700         word(&mut self.s, "|")?;
2701
2702         if let ast::FunctionRetTy::Default(..) = decl.output {
2703             return Ok(());
2704         }
2705
2706         self.space_if_not_bol()?;
2707         self.word_space("->")?;
2708         match decl.output {
2709             ast::FunctionRetTy::Ty(ref ty) => {
2710                 self.print_type(&ty)?;
2711                 self.maybe_print_comment(ty.span.lo)
2712             }
2713             ast::FunctionRetTy::Default(..) => unreachable!(),
2714         }
2715     }
2716
2717     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
2718                                 -> io::Result<()> {
2719         match capture_clause {
2720             ast::CaptureBy::Value => self.word_space("move"),
2721             ast::CaptureBy::Ref => Ok(()),
2722         }
2723     }
2724
2725     pub fn print_bounds(&mut self,
2726                         prefix: &str,
2727                         bounds: &[ast::TyParamBound])
2728                         -> io::Result<()> {
2729         if !bounds.is_empty() {
2730             word(&mut self.s, prefix)?;
2731             let mut first = true;
2732             for bound in bounds {
2733                 self.nbsp()?;
2734                 if first {
2735                     first = false;
2736                 } else {
2737                     self.word_space("+")?;
2738                 }
2739
2740                 (match *bound {
2741                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2742                         self.print_poly_trait_ref(tref)
2743                     }
2744                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2745                         word(&mut self.s, "?")?;
2746                         self.print_poly_trait_ref(tref)
2747                     }
2748                     RegionTyParamBound(ref lt) => {
2749                         self.print_lifetime(lt)
2750                     }
2751                 })?
2752             }
2753             Ok(())
2754         } else {
2755             Ok(())
2756         }
2757     }
2758
2759     pub fn print_lifetime(&mut self,
2760                           lifetime: &ast::Lifetime)
2761                           -> io::Result<()>
2762     {
2763         self.print_name(lifetime.name)
2764     }
2765
2766     pub fn print_lifetime_bounds(&mut self,
2767                                  lifetime: &ast::Lifetime,
2768                                  bounds: &[ast::Lifetime])
2769                                  -> io::Result<()>
2770     {
2771         self.print_lifetime(lifetime)?;
2772         if !bounds.is_empty() {
2773             word(&mut self.s, ": ")?;
2774             for (i, bound) in bounds.iter().enumerate() {
2775                 if i != 0 {
2776                     word(&mut self.s, " + ")?;
2777                 }
2778                 self.print_lifetime(bound)?;
2779             }
2780         }
2781         Ok(())
2782     }
2783
2784     pub fn print_generics(&mut self,
2785                           generics: &ast::Generics)
2786                           -> io::Result<()>
2787     {
2788         let total = generics.lifetimes.len() + generics.ty_params.len();
2789         if total == 0 {
2790             return Ok(());
2791         }
2792
2793         word(&mut self.s, "<")?;
2794
2795         let mut ints = Vec::new();
2796         for i in 0..total {
2797             ints.push(i);
2798         }
2799
2800         self.commasep(Inconsistent, &ints[..], |s, &idx| {
2801             if idx < generics.lifetimes.len() {
2802                 let lifetime_def = &generics.lifetimes[idx];
2803                 s.print_outer_attributes_inline(&lifetime_def.attrs)?;
2804                 s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
2805             } else {
2806                 let idx = idx - generics.lifetimes.len();
2807                 let param = &generics.ty_params[idx];
2808                 s.print_ty_param(param)
2809             }
2810         })?;
2811
2812         word(&mut self.s, ">")?;
2813         Ok(())
2814     }
2815
2816     pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
2817         self.print_outer_attributes_inline(&param.attrs)?;
2818         self.print_ident(param.ident)?;
2819         self.print_bounds(":", &param.bounds)?;
2820         match param.default {
2821             Some(ref default) => {
2822                 space(&mut self.s)?;
2823                 self.word_space("=")?;
2824                 self.print_type(&default)
2825             }
2826             _ => Ok(())
2827         }
2828     }
2829
2830     pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
2831                               -> io::Result<()> {
2832         if where_clause.predicates.is_empty() {
2833             return Ok(())
2834         }
2835
2836         space(&mut self.s)?;
2837         self.word_space("where")?;
2838
2839         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2840             if i != 0 {
2841                 self.word_space(",")?;
2842             }
2843
2844             match *predicate {
2845                 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
2846                                                                              ref bounded_ty,
2847                                                                              ref bounds,
2848                                                                              ..}) => {
2849                     self.print_formal_lifetime_list(bound_lifetimes)?;
2850                     self.print_type(&bounded_ty)?;
2851                     self.print_bounds(":", bounds)?;
2852                 }
2853                 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2854                                                                                ref bounds,
2855                                                                                ..}) => {
2856                     self.print_lifetime_bounds(lifetime, bounds)?;
2857                 }
2858                 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2859                                                                        ref rhs_ty,
2860                                                                        ..}) => {
2861                     self.print_type(lhs_ty)?;
2862                     space(&mut self.s)?;
2863                     self.word_space("=")?;
2864                     self.print_type(rhs_ty)?;
2865                 }
2866             }
2867         }
2868
2869         Ok(())
2870     }
2871
2872     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
2873         match vp.node {
2874             ast::ViewPathSimple(ident, ref path) => {
2875                 self.print_path(path, false, 0, true)?;
2876
2877                 if path.segments.last().unwrap().identifier.name !=
2878                         ident.name {
2879                     space(&mut self.s)?;
2880                     self.word_space("as")?;
2881                     self.print_ident(ident)?;
2882                 }
2883
2884                 Ok(())
2885             }
2886
2887             ast::ViewPathGlob(ref path) => {
2888                 self.print_path(path, false, 0, true)?;
2889                 word(&mut self.s, "::*")
2890             }
2891
2892             ast::ViewPathList(ref path, ref idents) => {
2893                 if path.segments.is_empty() {
2894                     word(&mut self.s, "{")?;
2895                 } else {
2896                     self.print_path(path, false, 0, true)?;
2897                     word(&mut self.s, "::{")?;
2898                 }
2899                 self.commasep(Inconsistent, &idents[..], |s, w| {
2900                     s.print_ident(w.node.name)?;
2901                     if let Some(ident) = w.node.rename {
2902                         space(&mut s.s)?;
2903                         s.word_space("as")?;
2904                         s.print_ident(ident)?;
2905                     }
2906                     Ok(())
2907                 })?;
2908                 word(&mut self.s, "}")
2909             }
2910         }
2911     }
2912
2913     pub fn print_mutability(&mut self,
2914                             mutbl: ast::Mutability) -> io::Result<()> {
2915         match mutbl {
2916             ast::Mutability::Mutable => self.word_nbsp("mut"),
2917             ast::Mutability::Immutable => Ok(()),
2918         }
2919     }
2920
2921     pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
2922         self.print_mutability(mt.mutbl)?;
2923         self.print_type(&mt.ty)
2924     }
2925
2926     pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
2927         self.ibox(INDENT_UNIT)?;
2928         match input.ty.node {
2929             ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
2930             _ => {
2931                 if let Some(eself) = input.to_self() {
2932                     self.print_explicit_self(&eself)?;
2933                 } else {
2934                     let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
2935                         ident.node.name == keywords::Invalid.name()
2936                     } else {
2937                         false
2938                     };
2939                     if !invalid {
2940                         self.print_pat(&input.pat)?;
2941                         word(&mut self.s, ":")?;
2942                         space(&mut self.s)?;
2943                     }
2944                     self.print_type(&input.ty)?;
2945                 }
2946             }
2947         }
2948         self.end()
2949     }
2950
2951     pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
2952         if let ast::FunctionRetTy::Default(..) = decl.output {
2953             return Ok(());
2954         }
2955
2956         self.space_if_not_bol()?;
2957         self.ibox(INDENT_UNIT)?;
2958         self.word_space("->")?;
2959         match decl.output {
2960             ast::FunctionRetTy::Default(..) => unreachable!(),
2961             ast::FunctionRetTy::Ty(ref ty) =>
2962                 self.print_type(&ty)?
2963         }
2964         self.end()?;
2965
2966         match decl.output {
2967             ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
2968             _ => Ok(())
2969         }
2970     }
2971
2972     pub fn print_ty_fn(&mut self,
2973                        abi: abi::Abi,
2974                        unsafety: ast::Unsafety,
2975                        decl: &ast::FnDecl,
2976                        name: Option<ast::Ident>,
2977                        generics: &ast::Generics)
2978                        -> io::Result<()> {
2979         self.ibox(INDENT_UNIT)?;
2980         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
2981             word(&mut self.s, "for")?;
2982             self.print_generics(generics)?;
2983         }
2984         let generics = ast::Generics {
2985             lifetimes: Vec::new(),
2986             ty_params: Vec::new(),
2987             where_clause: ast::WhereClause {
2988                 id: ast::DUMMY_NODE_ID,
2989                 predicates: Vec::new(),
2990             },
2991             span: syntax_pos::DUMMY_SP,
2992         };
2993         self.print_fn(decl,
2994                       unsafety,
2995                       ast::Constness::NotConst,
2996                       abi,
2997                       name,
2998                       &generics,
2999                       &ast::Visibility::Inherited)?;
3000         self.end()
3001     }
3002
3003     pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
3004                                         next_pos: Option<BytePos>)
3005         -> io::Result<()> {
3006         let cm = match self.cm {
3007             Some(cm) => cm,
3008             _ => return Ok(())
3009         };
3010         if let Some(ref cmnt) = self.next_comment() {
3011             if cmnt.style != comments::Trailing { return Ok(()) }
3012             let span_line = cm.lookup_char_pos(span.hi);
3013             let comment_line = cm.lookup_char_pos(cmnt.pos);
3014             let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
3015             if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
3016                 self.print_comment(cmnt)?;
3017                 self.cur_cmnt_and_lit.cur_cmnt += 1;
3018             }
3019         }
3020         Ok(())
3021     }
3022
3023     pub fn print_remaining_comments(&mut self) -> io::Result<()> {
3024         // If there aren't any remaining comments, then we need to manually
3025         // make sure there is a line break at the end.
3026         if self.next_comment().is_none() {
3027             hardbreak(&mut self.s)?;
3028         }
3029         loop {
3030             match self.next_comment() {
3031                 Some(ref cmnt) => {
3032                     self.print_comment(cmnt)?;
3033                     self.cur_cmnt_and_lit.cur_cmnt += 1;
3034                 }
3035                 _ => break
3036             }
3037         }
3038         Ok(())
3039     }
3040
3041     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
3042                                                   opt_abi: Option<Abi>)
3043         -> io::Result<()> {
3044         match opt_abi {
3045             Some(Abi::Rust) => Ok(()),
3046             Some(abi) => {
3047                 self.word_nbsp("extern")?;
3048                 self.word_nbsp(&abi.to_string())
3049             }
3050             None => Ok(())
3051         }
3052     }
3053
3054     pub fn print_extern_opt_abi(&mut self,
3055                                 opt_abi: Option<Abi>) -> io::Result<()> {
3056         match opt_abi {
3057             Some(abi) => {
3058                 self.word_nbsp("extern")?;
3059                 self.word_nbsp(&abi.to_string())
3060             }
3061             None => Ok(())
3062         }
3063     }
3064
3065     pub fn print_fn_header_info(&mut self,
3066                                 unsafety: ast::Unsafety,
3067                                 constness: ast::Constness,
3068                                 abi: Abi,
3069                                 vis: &ast::Visibility) -> io::Result<()> {
3070         word(&mut self.s, &visibility_qualified(vis, ""))?;
3071
3072         match constness {
3073             ast::Constness::NotConst => {}
3074             ast::Constness::Const => self.word_nbsp("const")?
3075         }
3076
3077         self.print_unsafety(unsafety)?;
3078
3079         if abi != Abi::Rust {
3080             self.word_nbsp("extern")?;
3081             self.word_nbsp(&abi.to_string())?;
3082         }
3083
3084         word(&mut self.s, "fn")
3085     }
3086
3087     pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
3088         match s {
3089             ast::Unsafety::Normal => Ok(()),
3090             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
3091         }
3092     }
3093 }
3094
3095 fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
3096
3097 #[cfg(test)]
3098 mod tests {
3099     use super::*;
3100
3101     use ast;
3102     use codemap;
3103     use syntax_pos;
3104
3105     #[test]
3106     fn test_fun_to_string() {
3107         let abba_ident = ast::Ident::from_str("abba");
3108
3109         let decl = ast::FnDecl {
3110             inputs: Vec::new(),
3111             output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
3112             variadic: false
3113         };
3114         let generics = ast::Generics::default();
3115         assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
3116                                  ast::Constness::NotConst,
3117                                  abba_ident, &generics),
3118                    "fn abba()");
3119     }
3120
3121     #[test]
3122     fn test_variant_to_string() {
3123         let ident = ast::Ident::from_str("principal_skinner");
3124
3125         let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
3126             name: ident,
3127             attrs: Vec::new(),
3128             // making this up as I go.... ?
3129             data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
3130             disr_expr: None,
3131         });
3132
3133         let varstr = variant_to_string(&var);
3134         assert_eq!(varstr, "principal_skinner");
3135     }
3136 }