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