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