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