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