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