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