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