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