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