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