]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/macros.rs
Rollup merge of #88722 - WaffleLapkin:unsafe_cell_const_get_mut, r=dtolnay
[rust.git] / src / tools / rustfmt / src / macros.rs
1 // Format list-like macro invocations. These are invocations whose token trees
2 // can be interpreted as expressions and separated by commas.
3 // Note that these token trees do not actually have to be interpreted as
4 // expressions by the compiler. An example of an invocation we would reformat is
5 // foo!( x, y, z ). The token x may represent an identifier in the code, but we
6 // interpreted as an expression.
7 // Macro uses which are not-list like, such as bar!(key => val), will not be
8 // reformatted.
9 // List-like invocations with parentheses will be formatted as function calls,
10 // and those with brackets will be formatted as array literals.
11
12 use std::collections::HashMap;
13 use std::panic::{catch_unwind, AssertUnwindSafe};
14
15 use rustc_ast::token::{BinOpToken, DelimToken, Token, TokenKind};
16 use rustc_ast::tokenstream::{Cursor, Spacing, TokenStream, TokenTree};
17 use rustc_ast::{ast, ptr};
18 use rustc_ast_pretty::pprust;
19 use rustc_parse::parser::{ForceCollect, Parser};
20 use rustc_parse::{stream_to_parser, MACRO_ARGUMENTS};
21 use rustc_span::{
22     symbol::{self, kw},
23     BytePos, Span, Symbol, DUMMY_SP,
24 };
25
26 use crate::comment::{
27     contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
28 };
29 use crate::config::lists::*;
30 use crate::expr::rewrite_array;
31 use crate::lists::{itemize_list, write_list, ListFormatting};
32 use crate::overflow;
33 use crate::rewrite::{Rewrite, RewriteContext};
34 use crate::shape::{Indent, Shape};
35 use crate::source_map::SpanUtils;
36 use crate::spanned::Spanned;
37 use crate::utils::{
38     format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
39     rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
40 };
41 use crate::visitor::FmtVisitor;
42
43 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
44
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 pub(crate) enum MacroPosition {
47     Item,
48     Statement,
49     Expression,
50     Pat,
51 }
52
53 #[derive(Debug)]
54 pub(crate) enum MacroArg {
55     Expr(ptr::P<ast::Expr>),
56     Ty(ptr::P<ast::Ty>),
57     Pat(ptr::P<ast::Pat>),
58     Item(ptr::P<ast::Item>),
59     Keyword(symbol::Ident, Span),
60 }
61
62 impl MacroArg {
63     fn is_item(&self) -> bool {
64         match self {
65             MacroArg::Item(..) => true,
66             _ => false,
67         }
68     }
69 }
70
71 impl Rewrite for ast::Item {
72     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
73         let mut visitor = crate::visitor::FmtVisitor::from_context(context);
74         visitor.block_indent = shape.indent;
75         visitor.last_pos = self.span().lo();
76         visitor.visit_item(self);
77         Some(visitor.buffer.to_owned())
78     }
79 }
80
81 impl Rewrite for MacroArg {
82     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
83         match *self {
84             MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
85             MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
86             MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
87             MacroArg::Item(ref item) => item.rewrite(context, shape),
88             MacroArg::Keyword(ident, _) => Some(ident.name.to_string()),
89         }
90     }
91 }
92
93 fn build_parser<'a>(context: &RewriteContext<'a>, cursor: Cursor) -> Parser<'a> {
94     stream_to_parser(
95         context.parse_sess.inner(),
96         cursor.collect(),
97         MACRO_ARGUMENTS,
98     )
99 }
100
101 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
102     macro_rules! parse_macro_arg {
103         ($macro_arg:ident, $parser:expr, $f:expr) => {
104             let mut cloned_parser = (*parser).clone();
105             match $parser(&mut cloned_parser) {
106                 Ok(x) => {
107                     if parser.sess.span_diagnostic.has_errors() {
108                         parser.sess.span_diagnostic.reset_err_count();
109                     } else {
110                         // Parsing succeeded.
111                         *parser = cloned_parser;
112                         return Some(MacroArg::$macro_arg($f(x)?));
113                     }
114                 }
115                 Err(mut e) => {
116                     e.cancel();
117                     parser.sess.span_diagnostic.reset_err_count();
118                 }
119             }
120         };
121     }
122
123     parse_macro_arg!(
124         Expr,
125         |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(),
126         |x: ptr::P<ast::Expr>| Some(x)
127     );
128     parse_macro_arg!(
129         Ty,
130         |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(),
131         |x: ptr::P<ast::Ty>| Some(x)
132     );
133     parse_macro_arg!(
134         Pat,
135         |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat_no_top_alt(None),
136         |x: ptr::P<ast::Pat>| Some(x)
137     );
138     // `parse_item` returns `Option<ptr::P<ast::Item>>`.
139     parse_macro_arg!(
140         Item,
141         |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_item(ForceCollect::No),
142         |x: Option<ptr::P<ast::Item>>| x
143     );
144
145     None
146 }
147
148 /// Rewrite macro name without using pretty-printer if possible.
149 fn rewrite_macro_name(
150     context: &RewriteContext<'_>,
151     path: &ast::Path,
152     extra_ident: Option<symbol::Ident>,
153 ) -> String {
154     let name = if path.segments.len() == 1 {
155         // Avoid using pretty-printer in the common case.
156         format!("{}!", rewrite_ident(context, path.segments[0].ident))
157     } else {
158         format!("{}!", pprust::path_to_string(path))
159     };
160     match extra_ident {
161         Some(ident) if ident.name != kw::Empty => format!("{} {}", name, ident),
162         _ => name,
163     }
164 }
165
166 // Use this on failing to format the macro call.
167 fn return_macro_parse_failure_fallback(
168     context: &RewriteContext<'_>,
169     indent: Indent,
170     span: Span,
171 ) -> Option<String> {
172     // Mark this as a failure however we format it
173     context.macro_rewrite_failure.replace(true);
174
175     // Heuristically determine whether the last line of the macro uses "Block" style
176     // rather than using "Visual" style, or another indentation style.
177     let is_like_block_indent_style = context
178         .snippet(span)
179         .lines()
180         .last()
181         .map(|closing_line| {
182             closing_line
183                 .trim()
184                 .chars()
185                 .all(|ch| matches!(ch, '}' | ')' | ']'))
186         })
187         .unwrap_or(false);
188     if is_like_block_indent_style {
189         return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
190     }
191
192     context.skipped_range.borrow_mut().push((
193         context.parse_sess.line_of_byte_pos(span.lo()),
194         context.parse_sess.line_of_byte_pos(span.hi()),
195     ));
196
197     // Return the snippet unmodified if the macro is not block-like
198     Some(context.snippet(span).to_owned())
199 }
200
201 pub(crate) fn rewrite_macro(
202     mac: &ast::MacCall,
203     extra_ident: Option<symbol::Ident>,
204     context: &RewriteContext<'_>,
205     shape: Shape,
206     position: MacroPosition,
207 ) -> Option<String> {
208     let should_skip = context
209         .skip_context
210         .skip_macro(&context.snippet(mac.path.span).to_owned());
211     if should_skip {
212         None
213     } else {
214         let guard = context.enter_macro();
215         let result = catch_unwind(AssertUnwindSafe(|| {
216             rewrite_macro_inner(
217                 mac,
218                 extra_ident,
219                 context,
220                 shape,
221                 position,
222                 guard.is_nested(),
223             )
224         }));
225         match result {
226             Err(..) | Ok(None) => {
227                 context.macro_rewrite_failure.replace(true);
228                 None
229             }
230             Ok(rw) => rw,
231         }
232     }
233 }
234
235 fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
236     for &keyword in RUST_KW.iter() {
237         if parser.token.is_keyword(keyword)
238             && parser.look_ahead(1, |t| {
239                 t.kind == TokenKind::Eof
240                     || t.kind == TokenKind::Comma
241                     || t.kind == TokenKind::CloseDelim(DelimToken::NoDelim)
242             })
243         {
244             parser.bump();
245             return Some(MacroArg::Keyword(
246                 symbol::Ident::with_dummy_span(keyword),
247                 parser.prev_token.span,
248             ));
249         }
250     }
251     None
252 }
253
254 fn rewrite_macro_inner(
255     mac: &ast::MacCall,
256     extra_ident: Option<symbol::Ident>,
257     context: &RewriteContext<'_>,
258     shape: Shape,
259     position: MacroPosition,
260     is_nested_macro: bool,
261 ) -> Option<String> {
262     if context.config.use_try_shorthand() {
263         if let Some(expr) = convert_try_mac(mac, context) {
264             context.leave_macro();
265             return expr.rewrite(context, shape);
266         }
267     }
268
269     let original_style = macro_style(mac, context);
270
271     let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
272
273     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) && !is_nested_macro {
274         DelimToken::Bracket
275     } else {
276         original_style
277     };
278
279     let ts = mac.args.inner_tokens();
280     let has_comment = contains_comment(context.snippet(mac.span()));
281     if ts.is_empty() && !has_comment {
282         return match style {
283             DelimToken::Paren if position == MacroPosition::Item => {
284                 Some(format!("{}();", macro_name))
285             }
286             DelimToken::Bracket if position == MacroPosition::Item => {
287                 Some(format!("{}[];", macro_name))
288             }
289             DelimToken::Paren => Some(format!("{}()", macro_name)),
290             DelimToken::Bracket => Some(format!("{}[]", macro_name)),
291             DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
292             _ => unreachable!(),
293         };
294     }
295     // Format well-known macros which cannot be parsed as a valid AST.
296     if macro_name == "lazy_static!" && !has_comment {
297         if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
298             return success;
299         }
300     }
301
302     let mut parser = build_parser(context, ts.trees());
303     let mut arg_vec = Vec::new();
304     let mut vec_with_semi = false;
305     let mut trailing_comma = false;
306
307     if DelimToken::Brace != style {
308         loop {
309             if let Some(arg) = check_keyword(&mut parser) {
310                 arg_vec.push(arg);
311             } else if let Some(arg) = parse_macro_arg(&mut parser) {
312                 arg_vec.push(arg);
313             } else {
314                 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
315             }
316
317             match parser.token.kind {
318                 TokenKind::Eof => break,
319                 TokenKind::Comma => (),
320                 TokenKind::Semi => {
321                     // Try to parse `vec![expr; expr]`
322                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
323                         parser.bump();
324                         if parser.token.kind != TokenKind::Eof {
325                             match parse_macro_arg(&mut parser) {
326                                 Some(arg) => {
327                                     arg_vec.push(arg);
328                                     parser.bump();
329                                     if parser.token.kind == TokenKind::Eof && arg_vec.len() == 2 {
330                                         vec_with_semi = true;
331                                         break;
332                                     }
333                                 }
334                                 None => {
335                                     return return_macro_parse_failure_fallback(
336                                         context,
337                                         shape.indent,
338                                         mac.span(),
339                                     );
340                                 }
341                             }
342                         }
343                     }
344                     return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
345                 }
346                 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
347                 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span()),
348             }
349
350             parser.bump();
351
352             if parser.token.kind == TokenKind::Eof {
353                 trailing_comma = true;
354                 break;
355             }
356         }
357     }
358
359     if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
360         return rewrite_macro_with_items(
361             context,
362             &arg_vec,
363             &macro_name,
364             shape,
365             style,
366             position,
367             mac.span(),
368         );
369     }
370
371     match style {
372         DelimToken::Paren => {
373             // Handle special case: `vec!(expr; expr)`
374             if vec_with_semi {
375                 handle_vec_semi(context, shape, arg_vec, macro_name, style)
376             } else {
377                 // Format macro invocation as function call, preserve the trailing
378                 // comma because not all macros support them.
379                 overflow::rewrite_with_parens(
380                     context,
381                     &macro_name,
382                     arg_vec.iter(),
383                     shape,
384                     mac.span(),
385                     context.config.fn_call_width(),
386                     if trailing_comma {
387                         Some(SeparatorTactic::Always)
388                     } else {
389                         Some(SeparatorTactic::Never)
390                     },
391                 )
392                 .map(|rw| match position {
393                     MacroPosition::Item => format!("{};", rw),
394                     _ => rw,
395                 })
396             }
397         }
398         DelimToken::Bracket => {
399             // Handle special case: `vec![expr; expr]`
400             if vec_with_semi {
401                 handle_vec_semi(context, shape, arg_vec, macro_name, style)
402             } else {
403                 // If we are rewriting `vec!` macro or other special macros,
404                 // then we can rewrite this as a usual array literal.
405                 // Otherwise, we must preserve the original existence of trailing comma.
406                 let macro_name = &macro_name.as_str();
407                 let mut force_trailing_comma = if trailing_comma {
408                     Some(SeparatorTactic::Always)
409                 } else {
410                     Some(SeparatorTactic::Never)
411                 };
412                 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
413                     context.leave_macro();
414                     if context.use_block_indent() {
415                         force_trailing_comma = Some(SeparatorTactic::Vertical);
416                     };
417                 }
418                 let rewrite = rewrite_array(
419                     macro_name,
420                     arg_vec.iter(),
421                     mac.span(),
422                     context,
423                     shape,
424                     force_trailing_comma,
425                     Some(original_style),
426                 )?;
427                 let comma = match position {
428                     MacroPosition::Item => ";",
429                     _ => "",
430                 };
431
432                 Some(format!("{}{}", rewrite, comma))
433             }
434         }
435         DelimToken::Brace => {
436             // For macro invocations with braces, always put a space between
437             // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
438             // anything in between the braces (for now).
439             let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
440             match trim_left_preserve_layout(snippet, shape.indent, &context.config) {
441                 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
442                 None => Some(format!("{} {}", macro_name, snippet)),
443             }
444         }
445         _ => unreachable!(),
446     }
447 }
448
449 fn handle_vec_semi(
450     context: &RewriteContext<'_>,
451     shape: Shape,
452     arg_vec: Vec<MacroArg>,
453     macro_name: String,
454     delim_token: DelimToken,
455 ) -> Option<String> {
456     let (left, right) = match delim_token {
457         DelimToken::Paren => ("(", ")"),
458         DelimToken::Bracket => ("[", "]"),
459         _ => unreachable!(),
460     };
461
462     let mac_shape = shape.offset_left(macro_name.len())?;
463     // 8 = `vec![]` + `; ` or `vec!()` + `; `
464     let total_overhead = 8;
465     let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
466     let lhs = arg_vec[0].rewrite(context, nested_shape)?;
467     let rhs = arg_vec[1].rewrite(context, nested_shape)?;
468     if !lhs.contains('\n')
469         && !rhs.contains('\n')
470         && lhs.len() + rhs.len() + total_overhead <= shape.width
471     {
472         // macro_name(lhs; rhs) or macro_name[lhs; rhs]
473         Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right))
474     } else {
475         // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
476         Some(format!(
477             "{}{}{}{};{}{}{}{}",
478             macro_name,
479             left,
480             nested_shape.indent.to_string_with_newline(context.config),
481             lhs,
482             nested_shape.indent.to_string_with_newline(context.config),
483             rhs,
484             shape.indent.to_string_with_newline(context.config),
485             right
486         ))
487     }
488 }
489
490 pub(crate) fn rewrite_macro_def(
491     context: &RewriteContext<'_>,
492     shape: Shape,
493     indent: Indent,
494     def: &ast::MacroDef,
495     ident: symbol::Ident,
496     vis: &ast::Visibility,
497     span: Span,
498 ) -> Option<String> {
499     let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
500     if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
501         return snippet;
502     }
503
504     let ts = def.body.inner_tokens();
505     let mut parser = MacroParser::new(ts.into_trees());
506     let parsed_def = match parser.parse() {
507         Some(def) => def,
508         None => return snippet,
509     };
510
511     let mut result = if def.macro_rules {
512         String::from("macro_rules!")
513     } else {
514         format!("{}macro", format_visibility(context, vis))
515     };
516
517     result += " ";
518     result += rewrite_ident(context, ident);
519
520     let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1;
521
522     let arm_shape = if multi_branch_style {
523         shape
524             .block_indent(context.config.tab_spaces())
525             .with_max_width(context.config)
526     } else {
527         shape
528     };
529
530     let branch_items = itemize_list(
531         context.snippet_provider,
532         parsed_def.branches.iter(),
533         "}",
534         ";",
535         |branch| branch.span.lo(),
536         |branch| branch.span.hi(),
537         |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
538             Some(v) => Some(v),
539             // if the rewrite returned None because a macro could not be rewritten, then return the
540             // original body
541             None if context.macro_rewrite_failure.get() => {
542                 Some(context.snippet(branch.body).trim().to_string())
543             }
544             None => None,
545         },
546         context.snippet_provider.span_after(span, "{"),
547         span.hi(),
548         false,
549     )
550     .collect::<Vec<_>>();
551
552     let fmt = ListFormatting::new(arm_shape, context.config)
553         .separator(if def.macro_rules { ";" } else { "" })
554         .trailing_separator(SeparatorTactic::Always)
555         .preserve_newline(true);
556
557     if multi_branch_style {
558         result += " {";
559         result += &arm_shape.indent.to_string_with_newline(context.config);
560     }
561
562     match write_list(&branch_items, &fmt) {
563         Some(ref s) => result += s,
564         None => return snippet,
565     }
566
567     if multi_branch_style {
568         result += &indent.to_string_with_newline(context.config);
569         result += "}";
570     }
571
572     Some(result)
573 }
574
575 fn register_metavariable(
576     map: &mut HashMap<String, String>,
577     result: &mut String,
578     name: &str,
579     dollar_count: usize,
580 ) {
581     let mut new_name = "$".repeat(dollar_count - 1);
582     let mut old_name = "$".repeat(dollar_count);
583
584     new_name.push('z');
585     new_name.push_str(name);
586     old_name.push_str(name);
587
588     result.push_str(&new_name);
589     map.insert(old_name, new_name);
590 }
591
592 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
593 // aren't causing problems.
594 // This should also work for escaped `$` variables, where we leave earlier `$`s.
595 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
596     // Each substitution will require five or six extra bytes.
597     let mut result = String::with_capacity(input.len() + 64);
598     let mut substs = HashMap::new();
599     let mut dollar_count = 0;
600     let mut cur_name = String::new();
601
602     for (kind, c) in CharClasses::new(input.chars()) {
603         if kind != FullCodeCharKind::Normal {
604             result.push(c);
605         } else if c == '$' {
606             dollar_count += 1;
607         } else if dollar_count == 0 {
608             result.push(c);
609         } else if !c.is_alphanumeric() && !cur_name.is_empty() {
610             // Terminates a name following one or more dollars.
611             register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
612
613             result.push(c);
614             dollar_count = 0;
615             cur_name.clear();
616         } else if c == '(' && cur_name.is_empty() {
617             // FIXME: Support macro def with repeat.
618             return None;
619         } else if c.is_alphanumeric() || c == '_' {
620             cur_name.push(c);
621         }
622     }
623
624     if !cur_name.is_empty() {
625         register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
626     }
627
628     debug!("replace_names `{}` {:?}", result, substs);
629
630     Some((result, substs))
631 }
632
633 #[derive(Debug, Clone)]
634 enum MacroArgKind {
635     /// e.g., `$x: expr`.
636     MetaVariable(Symbol, String),
637     /// e.g., `$($foo: expr),*`
638     Repeat(
639         /// `()`, `[]` or `{}`.
640         DelimToken,
641         /// Inner arguments inside delimiters.
642         Vec<ParsedMacroArg>,
643         /// Something after the closing delimiter and the repeat token, if available.
644         Option<Box<ParsedMacroArg>>,
645         /// The repeat token. This could be one of `*`, `+` or `?`.
646         Token,
647     ),
648     /// e.g., `[derive(Debug)]`
649     Delimited(DelimToken, Vec<ParsedMacroArg>),
650     /// A possible separator. e.g., `,` or `;`.
651     Separator(String, String),
652     /// Other random stuff that does not fit to other kinds.
653     /// e.g., `== foo` in `($x: expr == foo)`.
654     Other(String, String),
655 }
656
657 fn delim_token_to_str(
658     context: &RewriteContext<'_>,
659     delim_token: DelimToken,
660     shape: Shape,
661     use_multiple_lines: bool,
662     inner_is_empty: bool,
663 ) -> (String, String) {
664     let (lhs, rhs) = match delim_token {
665         DelimToken::Paren => ("(", ")"),
666         DelimToken::Bracket => ("[", "]"),
667         DelimToken::Brace => {
668             if inner_is_empty || use_multiple_lines {
669                 ("{", "}")
670             } else {
671                 ("{ ", " }")
672             }
673         }
674         DelimToken::NoDelim => ("", ""),
675     };
676     if use_multiple_lines {
677         let indent_str = shape.indent.to_string_with_newline(context.config);
678         let nested_indent_str = shape
679             .indent
680             .block_indent(context.config)
681             .to_string_with_newline(context.config);
682         (
683             format!("{}{}", lhs, nested_indent_str),
684             format!("{}{}", indent_str, rhs),
685         )
686     } else {
687         (lhs.to_owned(), rhs.to_owned())
688     }
689 }
690
691 impl MacroArgKind {
692     fn starts_with_brace(&self) -> bool {
693         matches!(
694             *self,
695             MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
696                 | MacroArgKind::Delimited(DelimToken::Brace, _)
697         )
698     }
699
700     fn starts_with_dollar(&self) -> bool {
701         matches!(
702             *self,
703             MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..)
704         )
705     }
706
707     fn ends_with_space(&self) -> bool {
708         matches!(*self, MacroArgKind::Separator(..))
709     }
710
711     fn has_meta_var(&self) -> bool {
712         match *self {
713             MacroArgKind::MetaVariable(..) => true,
714             MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
715             _ => false,
716         }
717     }
718
719     fn rewrite(
720         &self,
721         context: &RewriteContext<'_>,
722         shape: Shape,
723         use_multiple_lines: bool,
724     ) -> Option<String> {
725         let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
726             let inner = wrap_macro_args(context, args, shape)?;
727             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
728             if lhs.len() + inner.len() + rhs.len() <= shape.width {
729                 return Some((lhs, inner, rhs));
730             }
731
732             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
733             let nested_shape = shape
734                 .block_indent(context.config.tab_spaces())
735                 .with_max_width(context.config);
736             let inner = wrap_macro_args(context, args, nested_shape)?;
737             Some((lhs, inner, rhs))
738         };
739
740         match *self {
741             MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)),
742             MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
743                 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
744                 let another = another
745                     .as_ref()
746                     .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
747                     .unwrap_or_else(|| "".to_owned());
748                 let repeat_tok = pprust::token_to_string(tok);
749
750                 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
751             }
752             MacroArgKind::Delimited(delim_tok, ref args) => {
753                 rewrite_delimited_inner(delim_tok, args)
754                     .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
755             }
756             MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
757             MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
758         }
759     }
760 }
761
762 #[derive(Debug, Clone)]
763 struct ParsedMacroArg {
764     kind: MacroArgKind,
765 }
766
767 impl ParsedMacroArg {
768     fn rewrite(
769         &self,
770         context: &RewriteContext<'_>,
771         shape: Shape,
772         use_multiple_lines: bool,
773     ) -> Option<String> {
774         self.kind.rewrite(context, shape, use_multiple_lines)
775     }
776 }
777
778 /// Parses macro arguments on macro def.
779 struct MacroArgParser {
780     /// Either a name of the next metavariable, a separator, or junk.
781     buf: String,
782     /// The first token of the current buffer.
783     start_tok: Token,
784     /// `true` if we are parsing a metavariable or a repeat.
785     is_meta_var: bool,
786     /// The last token parsed.
787     last_tok: Token,
788     /// Holds the parsed arguments.
789     result: Vec<ParsedMacroArg>,
790 }
791
792 fn last_tok(tt: &TokenTree) -> Token {
793     match *tt {
794         TokenTree::Token(ref t) => t.clone(),
795         TokenTree::Delimited(delim_span, delim, _) => Token {
796             kind: TokenKind::CloseDelim(delim),
797             span: delim_span.close,
798         },
799     }
800 }
801
802 impl MacroArgParser {
803     fn new() -> MacroArgParser {
804         MacroArgParser {
805             buf: String::new(),
806             is_meta_var: false,
807             last_tok: Token {
808                 kind: TokenKind::Eof,
809                 span: DUMMY_SP,
810             },
811             start_tok: Token {
812                 kind: TokenKind::Eof,
813                 span: DUMMY_SP,
814             },
815             result: vec![],
816         }
817     }
818
819     fn set_last_tok(&mut self, tok: &TokenTree) {
820         self.last_tok = last_tok(tok);
821     }
822
823     fn add_separator(&mut self) {
824         let prefix = if self.need_space_prefix() {
825             " ".to_owned()
826         } else {
827             "".to_owned()
828         };
829         self.result.push(ParsedMacroArg {
830             kind: MacroArgKind::Separator(self.buf.clone(), prefix),
831         });
832         self.buf.clear();
833     }
834
835     fn add_other(&mut self) {
836         let prefix = if self.need_space_prefix() {
837             " ".to_owned()
838         } else {
839             "".to_owned()
840         };
841         self.result.push(ParsedMacroArg {
842             kind: MacroArgKind::Other(self.buf.clone(), prefix),
843         });
844         self.buf.clear();
845     }
846
847     fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
848         match iter.next() {
849             Some(TokenTree::Token(Token {
850                 kind: TokenKind::Ident(name, _),
851                 ..
852             })) => {
853                 self.result.push(ParsedMacroArg {
854                     kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
855                 });
856
857                 self.buf.clear();
858                 self.is_meta_var = false;
859                 Some(())
860             }
861             _ => None,
862         }
863     }
864
865     fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken) {
866         self.result.push(ParsedMacroArg {
867             kind: MacroArgKind::Delimited(delim, inner),
868         });
869     }
870
871     // $($foo: expr),?
872     fn add_repeat(
873         &mut self,
874         inner: Vec<ParsedMacroArg>,
875         delim: DelimToken,
876         iter: &mut Cursor,
877     ) -> Option<()> {
878         let mut buffer = String::new();
879         let mut first = true;
880
881         // Parse '*', '+' or '?.
882         for tok in iter {
883             self.set_last_tok(&tok);
884             if first {
885                 first = false;
886             }
887
888             match tok {
889                 TokenTree::Token(Token {
890                     kind: TokenKind::BinOp(BinOpToken::Plus),
891                     ..
892                 })
893                 | TokenTree::Token(Token {
894                     kind: TokenKind::Question,
895                     ..
896                 })
897                 | TokenTree::Token(Token {
898                     kind: TokenKind::BinOp(BinOpToken::Star),
899                     ..
900                 }) => {
901                     break;
902                 }
903                 TokenTree::Token(ref t) => {
904                     buffer.push_str(&pprust::token_to_string(&t));
905                 }
906                 _ => return None,
907             }
908         }
909
910         // There could be some random stuff between ')' and '*', '+' or '?'.
911         let another = if buffer.trim().is_empty() {
912             None
913         } else {
914             Some(Box::new(ParsedMacroArg {
915                 kind: MacroArgKind::Other(buffer, "".to_owned()),
916             }))
917         };
918
919         self.result.push(ParsedMacroArg {
920             kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
921         });
922         Some(())
923     }
924
925     fn update_buffer(&mut self, t: &Token) {
926         if self.buf.is_empty() {
927             self.start_tok = t.clone();
928         } else {
929             let needs_space = match next_space(&self.last_tok.kind) {
930                 SpaceState::Ident => ident_like(t),
931                 SpaceState::Punctuation => !ident_like(t),
932                 SpaceState::Always => true,
933                 SpaceState::Never => false,
934             };
935             if force_space_before(&t.kind) || needs_space {
936                 self.buf.push(' ');
937             }
938         }
939
940         self.buf.push_str(&pprust::token_to_string(t));
941     }
942
943     fn need_space_prefix(&self) -> bool {
944         if self.result.is_empty() {
945             return false;
946         }
947
948         let last_arg = self.result.last().unwrap();
949         if let MacroArgKind::MetaVariable(..) = last_arg.kind {
950             if ident_like(&self.start_tok) {
951                 return true;
952             }
953             if self.start_tok.kind == TokenKind::Colon {
954                 return true;
955             }
956         }
957
958         if force_space_before(&self.start_tok.kind) {
959             return true;
960         }
961
962         false
963     }
964
965     /// Returns a collection of parsed macro def's arguments.
966     fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
967         let mut iter = tokens.trees();
968
969         while let Some(tok) = iter.next() {
970             match tok {
971                 TokenTree::Token(Token {
972                     kind: TokenKind::Dollar,
973                     span,
974                 }) => {
975                     // We always want to add a separator before meta variables.
976                     if !self.buf.is_empty() {
977                         self.add_separator();
978                     }
979
980                     // Start keeping the name of this metavariable in the buffer.
981                     self.is_meta_var = true;
982                     self.start_tok = Token {
983                         kind: TokenKind::Dollar,
984                         span,
985                     };
986                 }
987                 TokenTree::Token(Token {
988                     kind: TokenKind::Colon,
989                     ..
990                 }) if self.is_meta_var => {
991                     self.add_meta_variable(&mut iter)?;
992                 }
993                 TokenTree::Token(ref t) => self.update_buffer(t),
994                 TokenTree::Delimited(_delimited_span, delimited, ref tts) => {
995                     if !self.buf.is_empty() {
996                         if next_space(&self.last_tok.kind) == SpaceState::Always {
997                             self.add_separator();
998                         } else {
999                             self.add_other();
1000                         }
1001                     }
1002
1003                     // Parse the stuff inside delimiters.
1004                     let parser = MacroArgParser::new();
1005                     let delimited_arg = parser.parse(tts.clone())?;
1006
1007                     if self.is_meta_var {
1008                         self.add_repeat(delimited_arg, delimited, &mut iter)?;
1009                         self.is_meta_var = false;
1010                     } else {
1011                         self.add_delimited(delimited_arg, delimited);
1012                     }
1013                 }
1014             }
1015
1016             self.set_last_tok(&tok);
1017         }
1018
1019         // We are left with some stuff in the buffer. Since there is nothing
1020         // left to separate, add this as `Other`.
1021         if !self.buf.is_empty() {
1022             self.add_other();
1023         }
1024
1025         Some(self.result)
1026     }
1027 }
1028
1029 fn wrap_macro_args(
1030     context: &RewriteContext<'_>,
1031     args: &[ParsedMacroArg],
1032     shape: Shape,
1033 ) -> Option<String> {
1034     wrap_macro_args_inner(context, args, shape, false)
1035         .or_else(|| wrap_macro_args_inner(context, args, shape, true))
1036 }
1037
1038 fn wrap_macro_args_inner(
1039     context: &RewriteContext<'_>,
1040     args: &[ParsedMacroArg],
1041     shape: Shape,
1042     use_multiple_lines: bool,
1043 ) -> Option<String> {
1044     let mut result = String::with_capacity(128);
1045     let mut iter = args.iter().peekable();
1046     let indent_str = shape.indent.to_string_with_newline(context.config);
1047
1048     while let Some(ref arg) = iter.next() {
1049         result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1050
1051         if use_multiple_lines
1052             && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1053         {
1054             if arg.kind.ends_with_space() {
1055                 result.pop();
1056             }
1057             result.push_str(&indent_str);
1058         } else if let Some(ref next_arg) = iter.peek() {
1059             let space_before_dollar =
1060                 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1061             let space_before_brace = next_arg.kind.starts_with_brace();
1062             if space_before_dollar || space_before_brace {
1063                 result.push(' ');
1064             }
1065         }
1066     }
1067
1068     if !use_multiple_lines && result.len() >= shape.width {
1069         None
1070     } else {
1071         Some(result)
1072     }
1073 }
1074
1075 // This is a bit sketchy. The token rules probably need tweaking, but it works
1076 // for some common cases. I hope the basic logic is sufficient. Note that the
1077 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1078 // and `(`/`)` have special meaning.
1079 //
1080 // We always try and format on one line.
1081 // FIXME: Use multi-line when every thing does not fit on one line.
1082 fn format_macro_args(
1083     context: &RewriteContext<'_>,
1084     token_stream: TokenStream,
1085     shape: Shape,
1086 ) -> Option<String> {
1087     if !context.config.format_macro_matchers() {
1088         let span = span_for_token_stream(&token_stream);
1089         return Some(match span {
1090             Some(span) => context.snippet(span).to_owned(),
1091             None => String::new(),
1092         });
1093     }
1094     let parsed_args = MacroArgParser::new().parse(token_stream)?;
1095     wrap_macro_args(context, &parsed_args, shape)
1096 }
1097
1098 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1099     token_stream.trees().next().map(|tt| tt.span())
1100 }
1101
1102 // We should insert a space if the next token is a:
1103 #[derive(Copy, Clone, PartialEq)]
1104 enum SpaceState {
1105     Never,
1106     Punctuation,
1107     Ident, // Or ident/literal-like thing.
1108     Always,
1109 }
1110
1111 fn force_space_before(tok: &TokenKind) -> bool {
1112     debug!("tok: force_space_before {:?}", tok);
1113
1114     match tok {
1115         TokenKind::Eq
1116         | TokenKind::Lt
1117         | TokenKind::Le
1118         | TokenKind::EqEq
1119         | TokenKind::Ne
1120         | TokenKind::Ge
1121         | TokenKind::Gt
1122         | TokenKind::AndAnd
1123         | TokenKind::OrOr
1124         | TokenKind::Not
1125         | TokenKind::Tilde
1126         | TokenKind::BinOpEq(_)
1127         | TokenKind::At
1128         | TokenKind::RArrow
1129         | TokenKind::LArrow
1130         | TokenKind::FatArrow
1131         | TokenKind::BinOp(_)
1132         | TokenKind::Pound
1133         | TokenKind::Dollar => true,
1134         _ => false,
1135     }
1136 }
1137
1138 fn ident_like(tok: &Token) -> bool {
1139     matches!(
1140         tok.kind,
1141         TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_)
1142     )
1143 }
1144
1145 fn next_space(tok: &TokenKind) -> SpaceState {
1146     debug!("next_space: {:?}", tok);
1147
1148     match tok {
1149         TokenKind::Not
1150         | TokenKind::BinOp(BinOpToken::And)
1151         | TokenKind::Tilde
1152         | TokenKind::At
1153         | TokenKind::Comma
1154         | TokenKind::Dot
1155         | TokenKind::DotDot
1156         | TokenKind::DotDotDot
1157         | TokenKind::DotDotEq
1158         | TokenKind::Question => SpaceState::Punctuation,
1159
1160         TokenKind::ModSep
1161         | TokenKind::Pound
1162         | TokenKind::Dollar
1163         | TokenKind::OpenDelim(_)
1164         | TokenKind::CloseDelim(_) => SpaceState::Never,
1165
1166         TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(_) => SpaceState::Ident,
1167
1168         _ => SpaceState::Always,
1169     }
1170 }
1171
1172 /// Tries to convert a macro use into a short hand try expression. Returns `None`
1173 /// when the macro is not an instance of `try!` (or parsing the inner expression
1174 /// failed).
1175 pub(crate) fn convert_try_mac(
1176     mac: &ast::MacCall,
1177     context: &RewriteContext<'_>,
1178 ) -> Option<ast::Expr> {
1179     let path = &pprust::path_to_string(&mac.path);
1180     if path == "try" || path == "r#try" {
1181         let ts = mac.args.inner_tokens();
1182         let mut parser = build_parser(context, ts.trees());
1183
1184         Some(ast::Expr {
1185             id: ast::NodeId::root(), // dummy value
1186             kind: ast::ExprKind::Try(parser.parse_expr().ok()?),
1187             span: mac.span(), // incorrect span, but shouldn't matter too much
1188             attrs: ast::AttrVec::new(),
1189             tokens: None,
1190         })
1191     } else {
1192         None
1193     }
1194 }
1195
1196 pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> DelimToken {
1197     let snippet = context.snippet(mac.span());
1198     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1199     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1200     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1201
1202     if paren_pos < bracket_pos && paren_pos < brace_pos {
1203         DelimToken::Paren
1204     } else if bracket_pos < brace_pos {
1205         DelimToken::Bracket
1206     } else {
1207         DelimToken::Brace
1208     }
1209 }
1210
1211 // A very simple parser that just parses a macros 2.0 definition into its branches.
1212 // Currently we do not attempt to parse any further than that.
1213 #[derive(new)]
1214 struct MacroParser {
1215     toks: Cursor,
1216 }
1217
1218 impl MacroParser {
1219     // (`(` ... `)` `=>` `{` ... `}`)*
1220     fn parse(&mut self) -> Option<Macro> {
1221         let mut branches = vec![];
1222         while self.toks.look_ahead(1).is_some() {
1223             branches.push(self.parse_branch()?);
1224         }
1225
1226         Some(Macro { branches })
1227     }
1228
1229     // `(` ... `)` `=>` `{` ... `}`
1230     fn parse_branch(&mut self) -> Option<MacroBranch> {
1231         let tok = self.toks.next()?;
1232         let (lo, args_paren_kind) = match tok {
1233             TokenTree::Token(..) => return None,
1234             TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1235         };
1236         let args = TokenStream::new(vec![(tok, Spacing::Joint)]);
1237         match self.toks.next()? {
1238             TokenTree::Token(Token {
1239                 kind: TokenKind::FatArrow,
1240                 ..
1241             }) => {}
1242             _ => return None,
1243         }
1244         let (mut hi, body, whole_body) = match self.toks.next()? {
1245             TokenTree::Token(..) => return None,
1246             TokenTree::Delimited(delimited_span, ..) => {
1247                 let data = delimited_span.entire().data();
1248                 (
1249                     data.hi,
1250                     Span::new(
1251                         data.lo + BytePos(1),
1252                         data.hi - BytePos(1),
1253                         data.ctxt,
1254                         data.parent,
1255                     ),
1256                     delimited_span.entire(),
1257                 )
1258             }
1259         };
1260         if let Some(TokenTree::Token(Token {
1261             kind: TokenKind::Semi,
1262             span,
1263         })) = self.toks.look_ahead(0)
1264         {
1265             hi = span.hi();
1266             self.toks.next();
1267         }
1268         Some(MacroBranch {
1269             span: mk_sp(lo, hi),
1270             args_paren_kind,
1271             args,
1272             body,
1273             whole_body,
1274         })
1275     }
1276 }
1277
1278 // A parsed macros 2.0 macro definition.
1279 struct Macro {
1280     branches: Vec<MacroBranch>,
1281 }
1282
1283 // FIXME: it would be more efficient to use references to the token streams
1284 // rather than clone them, if we can make the borrowing work out.
1285 struct MacroBranch {
1286     span: Span,
1287     args_paren_kind: DelimToken,
1288     args: TokenStream,
1289     body: Span,
1290     whole_body: Span,
1291 }
1292
1293 impl MacroBranch {
1294     fn rewrite(
1295         &self,
1296         context: &RewriteContext<'_>,
1297         shape: Shape,
1298         multi_branch_style: bool,
1299     ) -> Option<String> {
1300         // Only attempt to format function-like macros.
1301         if self.args_paren_kind != DelimToken::Paren {
1302             // FIXME(#1539): implement for non-sugared macros.
1303             return None;
1304         }
1305
1306         // 5 = " => {"
1307         let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1308
1309         if multi_branch_style {
1310             result += " =>";
1311         }
1312
1313         if !context.config.format_macro_bodies() {
1314             result += " ";
1315             result += context.snippet(self.whole_body);
1316             return Some(result);
1317         }
1318
1319         // The macro body is the most interesting part. It might end up as various
1320         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1321         // parsed as regular Rust code (and note that these can be escaped using
1322         // `$$`). We'll try and format like an AST node, but we'll substitute
1323         // variables for new names with the same length first.
1324
1325         let old_body = context.snippet(self.body).trim();
1326         let (body_str, substs) = replace_names(old_body)?;
1327         let has_block_body = old_body.starts_with('{');
1328
1329         let mut config = context.config.clone();
1330         config.set().hide_parse_errors(true);
1331
1332         result += " {";
1333
1334         let body_indent = if has_block_body {
1335             shape.indent
1336         } else {
1337             shape.indent.block_indent(&config)
1338         };
1339         let new_width = config.max_width() - body_indent.width();
1340         config.set().max_width(new_width);
1341
1342         // First try to format as items, then as statements.
1343         let new_body_snippet = match crate::format_snippet(&body_str, &config, true) {
1344             Some(new_body) => new_body,
1345             None => {
1346                 let new_width = new_width + config.tab_spaces();
1347                 config.set().max_width(new_width);
1348                 match crate::format_code_block(&body_str, &config, true) {
1349                     Some(new_body) => new_body,
1350                     None => return None,
1351                 }
1352             }
1353         };
1354         let new_body = wrap_str(
1355             new_body_snippet.snippet.to_string(),
1356             config.max_width(),
1357             shape,
1358         )?;
1359
1360         // Indent the body since it is in a block.
1361         let indent_str = body_indent.to_string(&config);
1362         let mut new_body = LineClasses::new(new_body.trim_end())
1363             .enumerate()
1364             .fold(
1365                 (String::new(), true),
1366                 |(mut s, need_indent), (i, (kind, ref l))| {
1367                     if !is_empty_line(l)
1368                         && need_indent
1369                         && !new_body_snippet.is_line_non_formatted(i + 1)
1370                     {
1371                         s += &indent_str;
1372                     }
1373                     (s + l + "\n", indent_next_line(kind, &l, &config))
1374                 },
1375             )
1376             .0;
1377
1378         // Undo our replacement of macro variables.
1379         // FIXME: this could be *much* more efficient.
1380         for (old, new) in &substs {
1381             if old_body.contains(new) {
1382                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1383                 return None;
1384             }
1385             new_body = new_body.replace(new, old);
1386         }
1387
1388         if has_block_body {
1389             result += new_body.trim();
1390         } else if !new_body.is_empty() {
1391             result += "\n";
1392             result += &new_body;
1393             result += &shape.indent.to_string(&config);
1394         }
1395
1396         result += "}";
1397
1398         Some(result)
1399     }
1400 }
1401
1402 /// Format `lazy_static!` from <https://crates.io/crates/lazy_static>.
1403 ///
1404 /// # Expected syntax
1405 ///
1406 /// ```text
1407 /// lazy_static! {
1408 ///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1409 ///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1410 ///     ...
1411 ///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1412 /// }
1413 /// ```
1414 fn format_lazy_static(
1415     context: &RewriteContext<'_>,
1416     shape: Shape,
1417     ts: &TokenStream,
1418 ) -> Option<String> {
1419     let mut result = String::with_capacity(1024);
1420     let mut parser = build_parser(context, ts.trees());
1421     let nested_shape = shape
1422         .block_indent(context.config.tab_spaces())
1423         .with_max_width(context.config);
1424
1425     result.push_str("lazy_static! {");
1426     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1427
1428     macro_rules! parse_or {
1429         ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1430             match parser.$method($($arg,)*) {
1431                 Ok(val) => {
1432                     if parser.sess.span_diagnostic.has_errors() {
1433                         parser.sess.span_diagnostic.reset_err_count();
1434                         return None;
1435                     } else {
1436                         val
1437                     }
1438                 }
1439                 Err(mut err) => {
1440                     err.cancel();
1441                     parser.sess.span_diagnostic.reset_err_count();
1442                     return None;
1443                 }
1444             }
1445         }
1446     }
1447
1448     while parser.token.kind != TokenKind::Eof {
1449         // Parse a `lazy_static!` item.
1450         let vis = crate::utils::format_visibility(
1451             context,
1452             &parse_or!(parse_visibility, rustc_parse::parser::FollowedByType::No),
1453         );
1454         parser.eat_keyword(kw::Static);
1455         parser.eat_keyword(kw::Ref);
1456         let id = parse_or!(parse_ident);
1457         parser.eat(&TokenKind::Colon);
1458         let ty = parse_or!(parse_ty);
1459         parser.eat(&TokenKind::Eq);
1460         let expr = parse_or!(parse_expr);
1461         parser.eat(&TokenKind::Semi);
1462
1463         // Rewrite as a static item.
1464         let mut stmt = String::with_capacity(128);
1465         stmt.push_str(&format!(
1466             "{}static ref {}: {} =",
1467             vis,
1468             id,
1469             ty.rewrite(context, nested_shape)?
1470         ));
1471         result.push_str(&crate::expr::rewrite_assign_rhs(
1472             context,
1473             stmt,
1474             &*expr,
1475             nested_shape.sub_width(1)?,
1476         )?);
1477         result.push(';');
1478         if parser.token.kind != TokenKind::Eof {
1479             result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1480         }
1481     }
1482
1483     result.push_str(&shape.indent.to_string_with_newline(context.config));
1484     result.push('}');
1485
1486     Some(result)
1487 }
1488
1489 fn rewrite_macro_with_items(
1490     context: &RewriteContext<'_>,
1491     items: &[MacroArg],
1492     macro_name: &str,
1493     shape: Shape,
1494     style: DelimToken,
1495     position: MacroPosition,
1496     span: Span,
1497 ) -> Option<String> {
1498     let (opener, closer) = match style {
1499         DelimToken::Paren => ("(", ")"),
1500         DelimToken::Bracket => ("[", "]"),
1501         DelimToken::Brace => (" {", "}"),
1502         _ => return None,
1503     };
1504     let trailing_semicolon = match style {
1505         DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1506         _ => "",
1507     };
1508
1509     let mut visitor = FmtVisitor::from_context(context);
1510     visitor.block_indent = shape.indent.block_indent(context.config);
1511     visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1512     for item in items {
1513         let item = match item {
1514             MacroArg::Item(item) => item,
1515             _ => return None,
1516         };
1517         visitor.visit_item(&item);
1518     }
1519
1520     let mut result = String::with_capacity(256);
1521     result.push_str(&macro_name);
1522     result.push_str(opener);
1523     result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1524     result.push_str(visitor.buffer.trim());
1525     result.push_str(&shape.indent.to_string_with_newline(context.config));
1526     result.push_str(closer);
1527     result.push_str(trailing_semicolon);
1528     Some(result)
1529 }
1530
1531 const RUST_KW: [Symbol; 59] = [
1532     kw::PathRoot,
1533     kw::DollarCrate,
1534     kw::Underscore,
1535     kw::As,
1536     kw::Box,
1537     kw::Break,
1538     kw::Const,
1539     kw::Continue,
1540     kw::Crate,
1541     kw::Else,
1542     kw::Enum,
1543     kw::Extern,
1544     kw::False,
1545     kw::Fn,
1546     kw::For,
1547     kw::If,
1548     kw::Impl,
1549     kw::In,
1550     kw::Let,
1551     kw::Loop,
1552     kw::Match,
1553     kw::Mod,
1554     kw::Move,
1555     kw::Mut,
1556     kw::Pub,
1557     kw::Ref,
1558     kw::Return,
1559     kw::SelfLower,
1560     kw::SelfUpper,
1561     kw::Static,
1562     kw::Struct,
1563     kw::Super,
1564     kw::Trait,
1565     kw::True,
1566     kw::Type,
1567     kw::Unsafe,
1568     kw::Use,
1569     kw::Where,
1570     kw::While,
1571     kw::Abstract,
1572     kw::Become,
1573     kw::Do,
1574     kw::Final,
1575     kw::Macro,
1576     kw::Override,
1577     kw::Priv,
1578     kw::Typeof,
1579     kw::Unsized,
1580     kw::Virtual,
1581     kw::Yield,
1582     kw::Dyn,
1583     kw::Async,
1584     kw::Try,
1585     kw::UnderscoreLifetime,
1586     kw::StaticLifetime,
1587     kw::Auto,
1588     kw::Catch,
1589     kw::Default,
1590     kw::Union,
1591 ];