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