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