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