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