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