Skip to main content

rustfmt_nightly/
macros.rs

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
12use std::borrow::Cow;
13use std::collections::HashMap;
14use std::panic::{AssertUnwindSafe, catch_unwind};
15
16use rustc_ast::ast;
17use rustc_ast::token::{Delimiter, Token, TokenKind};
18use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree};
19use rustc_ast_pretty::pprust;
20use rustc_span::{BytePos, DUMMY_SP, Ident, Pos, Span, Symbol};
21use tracing::debug;
22
23use crate::comment::{
24    CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
25    combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
26};
27use crate::config::lists::*;
28use crate::config::{ControlBraceStyle, StyleEdition};
29use crate::expr::{RhsAssignKind, rewrite_array, rewrite_assign_rhs};
30use crate::header::{HeaderPart, format_header};
31use crate::is_nightly_channel;
32use crate::lists::{ListFormatting, itemize_list, write_list};
33use crate::overflow;
34use crate::parse::macros::cfg_select::{
35    CfgSelectArm, CfgSelectFormatPredicate, parse_cfg_select_arms,
36};
37use crate::parse::macros::lazy_static::parse_lazy_static;
38use crate::parse::macros::{ParsedMacroArgs, parse_expr, parse_macro_args};
39use crate::rewrite::{
40    MacroErrorKind, Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult,
41};
42use crate::shape::{Indent, Shape};
43use crate::source_map::SpanUtils;
44use crate::spanned::Spanned;
45use crate::utils::{
46    NodeIdExt, extra_offset, filtered_str_fits, indent_next_line, is_empty_line,
47    last_line_contains_single_line_comment, mk_sp, remove_trailing_white_spaces, rewrite_ident,
48    trim_left_preserve_layout,
49};
50use crate::visitor::FmtVisitor;
51
52const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum MacroPosition {
56    Item,
57    Statement,
58    Expression,
59    Pat,
60}
61
62#[derive(Debug)]
63pub(crate) enum MacroArg {
64    Expr(Box<ast::Expr>),
65    Ty(Box<ast::Ty>),
66    Pat(Box<ast::Pat>),
67    Item(Box<ast::Item>),
68    Keyword(Ident, Span),
69}
70
71impl MacroArg {
72    pub(crate) fn is_item(&self) -> bool {
73        match self {
74            MacroArg::Item(..) => true,
75            _ => false,
76        }
77    }
78}
79
80impl Rewrite for ast::Item {
81    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
82        self.rewrite_result(context, shape).ok()
83    }
84
85    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
86        let mut visitor = crate::visitor::FmtVisitor::from_context(context);
87        visitor.block_indent = shape.indent;
88        visitor.last_pos = self.span().lo();
89        visitor.visit_item(self);
90        Ok(visitor.buffer.to_owned())
91    }
92}
93
94impl Rewrite for MacroArg {
95    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
96        self.rewrite_result(context, shape).ok()
97    }
98
99    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
100        match *self {
101            MacroArg::Expr(ref expr) => expr.rewrite_result(context, shape),
102            MacroArg::Ty(ref ty) => ty.rewrite_result(context, shape),
103            MacroArg::Pat(ref pat) => pat.rewrite_result(context, shape),
104            MacroArg::Item(ref item) => item.rewrite_result(context, shape),
105            MacroArg::Keyword(ident, _) => Ok(ident.name.to_string()),
106        }
107    }
108}
109
110/// Rewrite macro name without using pretty-printer if possible.
111fn rewrite_macro_name(context: &RewriteContext<'_>, path: &ast::Path) -> String {
112    if path.segments.len() == 1 {
113        // Avoid using pretty-printer in the common case.
114        format!("{}!", rewrite_ident(context, path.segments[0].ident))
115    } else {
116        format!("{}!", pprust::path_to_string(path))
117    }
118}
119
120// Use this on failing to format the macro call.
121// TODO(ding-young) We should also report macro parse failure to tell users why given snippet
122// is left unformatted. One possible improvement is appending formatting error to context.report
123fn return_macro_parse_failure_fallback(
124    context: &RewriteContext<'_>,
125    indent: Indent,
126    position: MacroPosition,
127    span: Span,
128) -> RewriteResult {
129    // Mark this as a failure however we format it
130    context.macro_rewrite_failure.replace(true);
131
132    // Heuristically determine whether the last line of the macro uses "Block" style
133    // rather than using "Visual" style, or another indentation style.
134    let is_like_block_indent_style = context
135        .snippet(span)
136        .lines()
137        .last()
138        .map(|closing_line| {
139            closing_line
140                .trim()
141                .chars()
142                .all(|ch| matches!(ch, '}' | ')' | ']'))
143        })
144        .unwrap_or(false);
145    if is_like_block_indent_style {
146        return trim_left_preserve_layout(context.snippet(span), indent, context.config)
147            .macro_error(MacroErrorKind::Unknown, span);
148    }
149
150    context.skipped_range.borrow_mut().push((
151        context.psess.line_of_byte_pos(span.lo()),
152        context.psess.line_of_byte_pos(span.hi()),
153    ));
154
155    // Return the snippet unmodified if the macro is not block-like
156    let mut snippet = context.snippet(span).to_owned();
157    if position == MacroPosition::Item {
158        snippet.push(';');
159    }
160    Ok(snippet)
161}
162
163pub(crate) fn rewrite_macro(
164    mac: &ast::MacCall,
165    context: &RewriteContext<'_>,
166    shape: Shape,
167    position: MacroPosition,
168) -> RewriteResult {
169    let should_skip = context
170        .skip_context
171        .macros
172        .skip(context.snippet(mac.path.span));
173    if should_skip {
174        Err(RewriteError::SkipFormatting)
175    } else {
176        let guard = context.enter_macro();
177        let result = catch_unwind(AssertUnwindSafe(|| {
178            rewrite_macro_inner(mac, context, shape, position, guard.is_nested())
179        }));
180        match result {
181            Err(..) => {
182                context.macro_rewrite_failure.replace(true);
183                Err(RewriteError::MacroFailure {
184                    kind: MacroErrorKind::Unknown,
185                    span: mac.span(),
186                })
187            }
188            Ok(Err(e)) => {
189                context.macro_rewrite_failure.replace(true);
190                Err(e)
191            }
192            Ok(rw) => rw,
193        }
194    }
195}
196
197fn rewrite_macro_inner(
198    mac: &ast::MacCall,
199    context: &RewriteContext<'_>,
200    shape: Shape,
201    position: MacroPosition,
202    is_nested_macro: bool,
203) -> RewriteResult {
204    if context.config.use_try_shorthand() {
205        if let Some(expr) = convert_try_mac(mac, context) {
206            context.leave_macro();
207            return expr.rewrite_result(context, shape);
208        }
209    }
210
211    let original_style = macro_style(mac, context);
212
213    let macro_name = rewrite_macro_name(context, &mac.path);
214    let is_forced_bracket = FORCED_BRACKET_MACROS.contains(&&macro_name[..]);
215
216    let style = if is_forced_bracket && !is_nested_macro {
217        Delimiter::Bracket
218    } else {
219        original_style
220    };
221
222    let ts = mac.args.tokens.clone();
223    let has_comment = contains_comment(context.snippet(mac.span()));
224    if ts.is_empty() && !has_comment {
225        return match style {
226            Delimiter::Parenthesis if position == MacroPosition::Item => {
227                Ok(format!("{macro_name}();"))
228            }
229            Delimiter::Bracket if position == MacroPosition::Item => Ok(format!("{macro_name}[];")),
230            Delimiter::Parenthesis => Ok(format!("{macro_name}()")),
231            Delimiter::Bracket => Ok(format!("{macro_name}[]")),
232            Delimiter::Brace => Ok(format!("{macro_name} {{}}")),
233            _ => unreachable!(),
234        };
235    }
236    // Format well-known macros which cannot be parsed as a valid AST.
237    if (macro_name == "lazy_static!"
238        || (context.config.style_edition() >= StyleEdition::Edition2027
239            && macro_name == "lazy_static::lazy_static!"))
240        && !has_comment
241    {
242        match format_lazy_static(context, shape, ts.clone(), mac.span(), &macro_name) {
243            Ok(rw) => return Ok(rw),
244            Err(err) => match err {
245                // We will move on to parsing macro args just like other macros
246                // if we could not parse lazy_static! with known syntax
247                RewriteError::MacroFailure { kind, span: _ }
248                    if kind == MacroErrorKind::ParseFailure => {}
249                // If formatting fails even though parsing succeeds, return the err early
250                _ => return Err(err),
251            },
252        }
253    }
254
255    if is_nightly_channel!() && macro_name.ends_with("cfg_select!") {
256        match format_cfg_select(context, shape, mac.span(), &macro_name, style, ts.clone()) {
257            Ok(rw) => return Ok(rw),
258            Err(err) => match err {
259                // We will move on to parsing macro args just like other macros
260                // if we could not parse cfg_select! with known syntax
261                RewriteError::MacroFailure { kind, span: _ }
262                    if kind == MacroErrorKind::ParseFailure => {}
263                // If formatting fails even though parsing succeeds, return the err early
264                other => return Err(other),
265            },
266        }
267    }
268
269    // If we're falling through to default macro handling check that the context is correct
270    debug_assert!(
271        context.inside_macro(),
272        "expect `context.inside_macro() == true`"
273    );
274
275    let ParsedMacroArgs {
276        args: arg_vec,
277        vec_with_semi,
278        trailing_comma,
279    } = match parse_macro_args(context, ts, style, is_forced_bracket) {
280        Some(args) => args,
281        None => {
282            return return_macro_parse_failure_fallback(
283                context,
284                shape.indent,
285                position,
286                mac.span(),
287            );
288        }
289    };
290
291    if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
292        return rewrite_macro_with_items(
293            context,
294            &arg_vec,
295            &macro_name,
296            shape,
297            style,
298            original_style,
299            position,
300            mac.span(),
301        );
302    }
303
304    match style {
305        Delimiter::Parenthesis => {
306            // Handle special case: `vec!(expr; expr)`
307            if vec_with_semi {
308                handle_vec_semi(context, shape, arg_vec, macro_name, style, mac.span())
309            } else {
310                // Format macro invocation as function call, preserve the trailing
311                // comma because not all macros support them.
312                overflow::rewrite_with_parens(
313                    context,
314                    &macro_name,
315                    arg_vec.iter(),
316                    shape,
317                    mac.span(),
318                    context.config.fn_call_width(),
319                    if trailing_comma {
320                        Some(SeparatorTactic::Always)
321                    } else {
322                        Some(SeparatorTactic::Never)
323                    },
324                )
325                .map(|rw| match position {
326                    MacroPosition::Item => format!("{};", rw),
327                    _ => rw,
328                })
329            }
330        }
331        Delimiter::Bracket => {
332            // Handle special case: `vec![expr; expr]`
333            if vec_with_semi {
334                handle_vec_semi(context, shape, arg_vec, macro_name, style, mac.span())
335            } else {
336                // If we are rewriting `vec!` macro or other special macros,
337                // then we can rewrite this as a usual array literal.
338                // Otherwise, we must preserve the original existence of trailing comma.
339                let mut force_trailing_comma = if trailing_comma {
340                    Some(SeparatorTactic::Always)
341                } else {
342                    Some(SeparatorTactic::Never)
343                };
344                if is_forced_bracket && !is_nested_macro {
345                    context.leave_macro();
346                    if context.use_block_indent() {
347                        force_trailing_comma = Some(SeparatorTactic::Vertical);
348                    };
349                }
350                let rewrite = rewrite_array(
351                    &macro_name,
352                    arg_vec.iter(),
353                    mac.span(),
354                    context,
355                    shape,
356                    force_trailing_comma,
357                    Some(original_style),
358                )?;
359                let comma = match position {
360                    MacroPosition::Item => ";",
361                    _ => "",
362                };
363
364                Ok(format!("{rewrite}{comma}"))
365            }
366        }
367        Delimiter::Brace => {
368            // For macro invocations with braces, always put a space between
369            // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
370            // anything in between the braces (for now).
371            let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
372            match trim_left_preserve_layout(snippet, shape.indent, context.config) {
373                Some(macro_body) => Ok(format!("{macro_name} {macro_body}")),
374                None => Ok(format!("{macro_name} {snippet}")),
375            }
376        }
377        _ => unreachable!(),
378    }
379}
380
381fn handle_vec_semi(
382    context: &RewriteContext<'_>,
383    shape: Shape,
384    arg_vec: Vec<MacroArg>,
385    macro_name: String,
386    delim_token: Delimiter,
387    span: Span,
388) -> RewriteResult {
389    let (left, right) = match delim_token {
390        Delimiter::Parenthesis => ("(", ")"),
391        Delimiter::Bracket => ("[", "]"),
392        _ => unreachable!(),
393    };
394
395    // Should we return MaxWidthError, Or Macro failure
396    let mac_shape = shape.offset_left(macro_name.len(), span)?;
397    // 8 = `vec![]` + `; ` or `vec!()` + `; `
398    let total_overhead = 8;
399    let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
400    let lhs = arg_vec[0].rewrite_result(context, nested_shape)?;
401    let rhs = arg_vec[1].rewrite_result(context, nested_shape)?;
402    if !lhs.contains('\n')
403        && !rhs.contains('\n')
404        && lhs.len() + rhs.len() + total_overhead <= shape.width
405    {
406        // macro_name(lhs; rhs) or macro_name[lhs; rhs]
407        Ok(format!("{macro_name}{left}{lhs}; {rhs}{right}"))
408    } else {
409        // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
410        Ok(format!(
411            "{}{}{}{};{}{}{}{}",
412            macro_name,
413            left,
414            nested_shape.indent.to_string_with_newline(context.config),
415            lhs,
416            nested_shape.indent.to_string_with_newline(context.config),
417            rhs,
418            shape.indent.to_string_with_newline(context.config),
419            right
420        ))
421    }
422}
423
424fn rewrite_empty_macro_def_body(
425    context: &RewriteContext<'_>,
426    span: Span,
427    shape: Shape,
428) -> RewriteResult {
429    // Create an empty, dummy `ast::Block` representing an empty macro body
430    let block = ast::Block {
431        stmts: vec![].into(),
432        id: rustc_ast::node_id::DUMMY_NODE_ID,
433        rules: ast::BlockCheckMode::Default,
434        span,
435    };
436    block.rewrite_result(context, shape)
437}
438
439pub(crate) fn rewrite_macro_def(
440    context: &RewriteContext<'_>,
441    shape: Shape,
442    indent: Indent,
443    def: &ast::MacroDef,
444    ident: Ident,
445    vis: &ast::Visibility,
446    span: Span,
447) -> RewriteResult {
448    let snippet = Ok(remove_trailing_white_spaces(context.snippet(span)));
449    if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
450        return snippet;
451    }
452
453    let ts = def.body.tokens.clone();
454    let mut parser = MacroParser::new(ts.iter());
455    let parsed_def = match parser.parse() {
456        Some(def) => def,
457        None => return snippet,
458    };
459
460    let mut header = if def.macro_rules {
461        let pos = context.snippet_provider.span_after(span, "!");
462        vec![HeaderPart::new("macro_rules!", span.with_hi(pos))]
463    } else {
464        let macro_lo = context.snippet_provider.span_before(span, "macro");
465        let macro_hi = macro_lo + BytePos("macro".len() as u32);
466        vec![
467            HeaderPart::visibility(context, vis),
468            HeaderPart::new("macro", mk_sp(macro_lo, macro_hi)),
469        ]
470    };
471
472    header.push(HeaderPart::ident(context, ident));
473
474    let mut result = format_header(context, shape, header);
475
476    let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1;
477
478    let arm_shape = if multi_branch_style {
479        shape
480            .block_indent(context.config.tab_spaces())
481            .with_max_width(context.config)
482    } else {
483        shape
484    };
485
486    if parsed_def.branches.len() == 0 {
487        let lo = context.snippet_provider.span_before(span, "{");
488        result += " ";
489        result += &rewrite_empty_macro_def_body(context, span.with_lo(lo), shape)?;
490        return Ok(result);
491    }
492
493    let branch_items = itemize_list(
494        context.snippet_provider,
495        parsed_def.branches.iter(),
496        "}",
497        ";",
498        |branch| branch.span.lo(),
499        |branch| branch.span.hi(),
500        |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
501            Ok(v) => Ok(v),
502            // if the rewrite returned None because a macro could not be rewritten, then return the
503            // original body
504            // TODO(ding-young) report rewrite error even if we return Ok with original snippet
505            Err(_) if context.macro_rewrite_failure.get() => {
506                Ok(context.snippet(branch.body).trim().to_string())
507            }
508            Err(e) => Err(e),
509        },
510        context.snippet_provider.span_after(span, "{"),
511        span.hi(),
512        false,
513    )
514    .collect::<Vec<_>>();
515
516    let fmt = ListFormatting::new(arm_shape, context.config)
517        .separator(if def.macro_rules { ";" } else { "" })
518        .trailing_separator(SeparatorTactic::Always)
519        .preserve_newline(true);
520
521    if multi_branch_style {
522        result += " {";
523        result += &arm_shape.indent.to_string_with_newline(context.config);
524    }
525
526    match write_list(&branch_items, &fmt) {
527        Ok(ref s) => result += s,
528        Err(_) => return snippet,
529    }
530
531    if multi_branch_style {
532        result += &indent.to_string_with_newline(context.config);
533        result += "}";
534    }
535
536    Ok(result)
537}
538
539fn register_metavariable(
540    map: &mut HashMap<String, String>,
541    result: &mut String,
542    name: &str,
543    dollar_count: usize,
544) {
545    let mut new_name = "$".repeat(dollar_count - 1);
546    let mut old_name = "$".repeat(dollar_count);
547
548    new_name.push('z');
549    new_name.push_str(name);
550    old_name.push_str(name);
551
552    result.push_str(&new_name);
553    map.insert(old_name, new_name);
554}
555
556// Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
557// aren't causing problems.
558// This should also work for escaped `$` variables, where we leave earlier `$`s.
559fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
560    // Each substitution will require five or six extra bytes.
561    let mut result = String::with_capacity(input.len() + 64);
562    let mut substs = HashMap::new();
563    let mut dollar_count = 0;
564    let mut cur_name = String::new();
565
566    for (kind, c) in CharClasses::new(input.chars()) {
567        if kind != FullCodeCharKind::Normal {
568            result.push(c);
569        } else if c == '$' {
570            dollar_count += 1;
571        } else if dollar_count == 0 {
572            result.push(c);
573        } else if !c.is_alphanumeric() && !cur_name.is_empty() {
574            // Terminates a name following one or more dollars.
575            register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
576
577            result.push(c);
578            dollar_count = 0;
579            cur_name.clear();
580        } else if c == '(' && cur_name.is_empty() {
581            // FIXME: Support macro def with repeat.
582            return None;
583        } else if c.is_alphanumeric() || c == '_' {
584            cur_name.push(c);
585        }
586    }
587
588    if !cur_name.is_empty() {
589        register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
590    }
591
592    debug!("replace_names `{}` {:?}", result, substs);
593
594    Some((result, substs))
595}
596
597#[derive(Debug, Clone)]
598enum MacroArgKind {
599    /// e.g., `$x: expr`.
600    MetaVariable(Symbol, String),
601    /// e.g., `$($foo: expr),*`
602    Repeat(
603        /// `()`, `[]` or `{}`.
604        Delimiter,
605        /// Inner arguments inside delimiters.
606        Vec<ParsedMacroArg>,
607        /// Something after the closing delimiter and the repeat token, if available.
608        Option<Box<ParsedMacroArg>>,
609        /// The repeat token. This could be one of `*`, `+` or `?`.
610        Token,
611    ),
612    /// e.g., `[derive(Debug)]`
613    Delimited(Delimiter, Vec<ParsedMacroArg>),
614    /// A possible separator. e.g., `,` or `;`.
615    Separator(String, String),
616    /// Other random stuff that does not fit to other kinds.
617    /// e.g., `== foo` in `($x: expr == foo)`.
618    Other(String, String),
619}
620
621fn delim_token_to_str(
622    context: &RewriteContext<'_>,
623    delim_token: Delimiter,
624    shape: Shape,
625    use_multiple_lines: bool,
626    inner_is_empty: bool,
627) -> (String, String) {
628    let (lhs, rhs) = match delim_token {
629        Delimiter::Parenthesis => ("(", ")"),
630        Delimiter::Bracket => ("[", "]"),
631        Delimiter::Brace => {
632            if inner_is_empty || use_multiple_lines {
633                ("{", "}")
634            } else {
635                ("{ ", " }")
636            }
637        }
638        Delimiter::Invisible(_) => unreachable!(),
639    };
640    if use_multiple_lines {
641        let indent_str = shape.indent.to_string_with_newline(context.config);
642        let nested_indent_str = shape
643            .indent
644            .block_indent(context.config)
645            .to_string_with_newline(context.config);
646        (
647            format!("{lhs}{nested_indent_str}"),
648            format!("{indent_str}{rhs}"),
649        )
650    } else {
651        (lhs.to_owned(), rhs.to_owned())
652    }
653}
654
655impl MacroArgKind {
656    fn starts_with_brace(&self) -> bool {
657        matches!(
658            *self,
659            MacroArgKind::Repeat(Delimiter::Brace, _, _, _)
660                | MacroArgKind::Delimited(Delimiter::Brace, _)
661        )
662    }
663
664    fn starts_with_dollar(&self) -> bool {
665        matches!(
666            *self,
667            MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..)
668        )
669    }
670
671    fn ends_with_space(&self) -> bool {
672        matches!(*self, MacroArgKind::Separator(..))
673    }
674
675    fn has_meta_var(&self) -> bool {
676        match *self {
677            MacroArgKind::MetaVariable(..) => true,
678            MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
679            _ => false,
680        }
681    }
682
683    fn rewrite(
684        &self,
685        context: &RewriteContext<'_>,
686        shape: Shape,
687        use_multiple_lines: bool,
688    ) -> RewriteResult {
689        type DelimitedArgsRewrite = Result<(String, String, String), RewriteError>;
690        let rewrite_delimited_inner = |delim_tok, args| -> DelimitedArgsRewrite {
691            let inner = wrap_macro_args(context, args, shape)?;
692            let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
693            if lhs.len() + inner.len() + rhs.len() <= shape.width {
694                return Ok((lhs, inner, rhs));
695            }
696
697            let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
698            let nested_shape = shape
699                .block_indent(context.config.tab_spaces())
700                .with_max_width(context.config);
701            let inner = wrap_macro_args(context, args, nested_shape)?;
702            Ok((lhs, inner, rhs))
703        };
704
705        match *self {
706            MacroArgKind::MetaVariable(ty, ref name) => Ok(format!("${name}:{ty}")),
707            MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
708                let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
709                let another = another
710                    .as_ref()
711                    .and_then(|a| a.rewrite(context, shape, use_multiple_lines).ok())
712                    .unwrap_or_else(|| "".to_owned());
713                let repeat_tok = pprust::token_to_string(tok);
714
715                Ok(format!("${lhs}{inner}{rhs}{another}{repeat_tok}"))
716            }
717            MacroArgKind::Delimited(delim_tok, ref args) => {
718                rewrite_delimited_inner(delim_tok, args)
719                    .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
720            }
721            MacroArgKind::Separator(ref sep, ref prefix) => Ok(format!("{prefix}{sep} ")),
722            MacroArgKind::Other(ref inner, ref prefix) => Ok(format!("{prefix}{inner}")),
723        }
724    }
725}
726
727#[derive(Debug, Clone)]
728struct ParsedMacroArg {
729    kind: MacroArgKind,
730}
731
732impl ParsedMacroArg {
733    fn rewrite(
734        &self,
735        context: &RewriteContext<'_>,
736        shape: Shape,
737        use_multiple_lines: bool,
738    ) -> RewriteResult {
739        self.kind.rewrite(context, shape, use_multiple_lines)
740    }
741}
742
743/// Parses macro arguments on macro def.
744struct MacroArgParser {
745    /// Either a name of the next metavariable, a separator, or junk.
746    buf: String,
747    /// The first token of the current buffer.
748    start_tok: Token,
749    /// `true` if we are parsing a metavariable or a repeat.
750    is_meta_var: bool,
751    /// The last token parsed.
752    last_tok: Token,
753    /// Holds the parsed arguments.
754    result: Vec<ParsedMacroArg>,
755}
756
757fn last_tok(tt: &TokenTree) -> Token {
758    match *tt {
759        TokenTree::Token(ref t, _) => t.clone(),
760        TokenTree::Delimited(delim_span, _, delim, _) => Token {
761            kind: delim.as_open_token_kind(),
762            span: delim_span.close,
763        },
764    }
765}
766
767impl MacroArgParser {
768    fn new() -> MacroArgParser {
769        MacroArgParser {
770            buf: String::new(),
771            is_meta_var: false,
772            last_tok: Token {
773                kind: TokenKind::Eof,
774                span: DUMMY_SP,
775            },
776            start_tok: Token {
777                kind: TokenKind::Eof,
778                span: DUMMY_SP,
779            },
780            result: vec![],
781        }
782    }
783
784    fn set_last_tok(&mut self, tok: &TokenTree) {
785        self.last_tok = last_tok(tok);
786    }
787
788    fn add_separator(&mut self) {
789        let prefix = if self.need_space_prefix() {
790            " ".to_owned()
791        } else {
792            "".to_owned()
793        };
794        self.result.push(ParsedMacroArg {
795            kind: MacroArgKind::Separator(self.buf.clone(), prefix),
796        });
797        self.buf.clear();
798    }
799
800    fn add_other(&mut self) {
801        let prefix = if self.need_space_prefix() {
802            " ".to_owned()
803        } else {
804            "".to_owned()
805        };
806        self.result.push(ParsedMacroArg {
807            kind: MacroArgKind::Other(self.buf.clone(), prefix),
808        });
809        self.buf.clear();
810    }
811
812    fn add_meta_variable(&mut self, iter: &mut TokenStreamIter<'_>) -> Option<()> {
813        match iter.next() {
814            Some(&TokenTree::Token(
815                Token {
816                    kind: TokenKind::Ident(name, _),
817                    ..
818                },
819                _,
820            )) => {
821                self.result.push(ParsedMacroArg {
822                    kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
823                });
824
825                self.buf.clear();
826                self.is_meta_var = false;
827                Some(())
828            }
829            _ => None,
830        }
831    }
832
833    fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: Delimiter) {
834        self.result.push(ParsedMacroArg {
835            kind: MacroArgKind::Delimited(delim, inner),
836        });
837    }
838
839    // $($foo: expr),?
840    fn add_repeat(
841        &mut self,
842        inner: Vec<ParsedMacroArg>,
843        delim: Delimiter,
844        iter: &mut TokenStreamIter<'_>,
845    ) -> Option<()> {
846        let mut buffer = String::new();
847        let mut first = true;
848
849        // Parse '*', '+' or '?.
850        for tok in iter {
851            self.set_last_tok(&tok);
852            if first {
853                first = false;
854            }
855
856            match tok {
857                TokenTree::Token(
858                    Token {
859                        kind: TokenKind::Plus,
860                        ..
861                    },
862                    _,
863                )
864                | TokenTree::Token(
865                    Token {
866                        kind: TokenKind::Question,
867                        ..
868                    },
869                    _,
870                )
871                | TokenTree::Token(
872                    Token {
873                        kind: TokenKind::Star,
874                        ..
875                    },
876                    _,
877                ) => {
878                    break;
879                }
880                TokenTree::Token(ref t, _) => {
881                    buffer.push_str(&pprust::token_to_string(t));
882                }
883                _ => return None,
884            }
885        }
886
887        // There could be some random stuff between ')' and '*', '+' or '?'.
888        let another = if buffer.trim().is_empty() {
889            None
890        } else {
891            Some(Box::new(ParsedMacroArg {
892                kind: MacroArgKind::Other(buffer, "".to_owned()),
893            }))
894        };
895
896        self.result.push(ParsedMacroArg {
897            kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok),
898        });
899        Some(())
900    }
901
902    fn update_buffer(&mut self, t: Token) {
903        if self.buf.is_empty() {
904            self.start_tok = t;
905        } else {
906            let needs_space = match next_space(&self.last_tok.kind) {
907                SpaceState::Ident => ident_like(&t),
908                SpaceState::Punctuation => !ident_like(&t),
909                SpaceState::Always => true,
910                SpaceState::Never => false,
911            };
912            if force_space_before(&t.kind) || needs_space {
913                self.buf.push(' ');
914            }
915        }
916
917        self.buf.push_str(&pprust::token_to_string(&t));
918    }
919
920    fn need_space_prefix(&self) -> bool {
921        if self.result.is_empty() {
922            return false;
923        }
924
925        let last_arg = self.result.last().unwrap();
926        if let MacroArgKind::MetaVariable(..) = last_arg.kind {
927            if ident_like(&self.start_tok) {
928                return true;
929            }
930            if self.start_tok.kind == TokenKind::Colon {
931                return true;
932            }
933        }
934
935        if force_space_before(&self.start_tok.kind) {
936            return true;
937        }
938
939        false
940    }
941
942    /// Returns a collection of parsed macro def's arguments.
943    fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
944        let mut iter = tokens.iter();
945
946        while let Some(tok) = iter.next() {
947            match tok {
948                &TokenTree::Token(
949                    Token {
950                        kind: TokenKind::Dollar,
951                        span,
952                    },
953                    _,
954                ) => {
955                    // We always want to add a separator before meta variables.
956                    if !self.buf.is_empty() {
957                        self.add_separator();
958                    }
959
960                    // Start keeping the name of this metavariable in the buffer.
961                    self.is_meta_var = true;
962                    self.start_tok = Token {
963                        kind: TokenKind::Dollar,
964                        span,
965                    };
966                }
967                TokenTree::Token(
968                    Token {
969                        kind: TokenKind::Colon,
970                        ..
971                    },
972                    _,
973                ) if self.is_meta_var => {
974                    self.add_meta_variable(&mut iter)?;
975                }
976                &TokenTree::Token(t, _) => self.update_buffer(t),
977                &TokenTree::Delimited(_dspan, _spacing, delimited, ref tts) => {
978                    if !self.buf.is_empty() {
979                        if next_space(&self.last_tok.kind) == SpaceState::Always {
980                            self.add_separator();
981                        } else {
982                            self.add_other();
983                        }
984                    }
985
986                    // Parse the stuff inside delimiters.
987                    let parser = MacroArgParser::new();
988                    let delimited_arg = parser.parse(tts.clone())?;
989
990                    if self.is_meta_var {
991                        self.add_repeat(delimited_arg, delimited, &mut iter)?;
992                        self.is_meta_var = false;
993                    } else {
994                        self.add_delimited(delimited_arg, delimited);
995                    }
996                }
997            }
998
999            self.set_last_tok(&tok);
1000        }
1001
1002        // We are left with some stuff in the buffer. Since there is nothing
1003        // left to separate, add this as `Other`.
1004        if !self.buf.is_empty() {
1005            self.add_other();
1006        }
1007
1008        Some(self.result)
1009    }
1010}
1011
1012fn wrap_macro_args(
1013    context: &RewriteContext<'_>,
1014    args: &[ParsedMacroArg],
1015    shape: Shape,
1016) -> RewriteResult {
1017    wrap_macro_args_inner(context, args, shape, false)
1018        .or_else(|_| wrap_macro_args_inner(context, args, shape, true))
1019}
1020
1021fn wrap_macro_args_inner(
1022    context: &RewriteContext<'_>,
1023    args: &[ParsedMacroArg],
1024    shape: Shape,
1025    use_multiple_lines: bool,
1026) -> RewriteResult {
1027    let mut result = String::with_capacity(128);
1028    let mut iter = args.iter().peekable();
1029    let indent_str = shape.indent.to_string_with_newline(context.config);
1030
1031    while let Some(arg) = iter.next() {
1032        result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1033
1034        if use_multiple_lines
1035            && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1036        {
1037            if arg.kind.ends_with_space() {
1038                result.pop();
1039            }
1040            result.push_str(&indent_str);
1041        } else if let Some(next_arg) = iter.peek() {
1042            let space_before_dollar =
1043                !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1044            let space_before_brace = next_arg.kind.starts_with_brace();
1045            if space_before_dollar || space_before_brace {
1046                result.push(' ');
1047            }
1048        }
1049    }
1050
1051    if !use_multiple_lines && result.len() >= shape.width {
1052        Err(RewriteError::Unknown)
1053    } else {
1054        Ok(result)
1055    }
1056}
1057
1058// This is a bit sketchy. The token rules probably need tweaking, but it works
1059// for some common cases. I hope the basic logic is sufficient. Note that the
1060// meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1061// and `(`/`)` have special meaning.
1062fn format_macro_args(
1063    context: &RewriteContext<'_>,
1064    token_stream: TokenStream,
1065    shape: Shape,
1066) -> RewriteResult {
1067    let span = span_for_token_stream(&token_stream);
1068    if !context.config.format_macro_matchers() {
1069        return Ok(match span {
1070            Some(span) => context.snippet(span).to_owned(),
1071            None => String::new(),
1072        });
1073    }
1074    let parsed_args = MacroArgParser::new()
1075        .parse(token_stream)
1076        .macro_error(MacroErrorKind::ParseFailure, span.unwrap())?;
1077    wrap_macro_args(context, &parsed_args, shape)
1078}
1079
1080fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1081    token_stream.iter().next().map(|tt| tt.span())
1082}
1083
1084// We should insert a space if the next token is a:
1085#[derive(Copy, Clone, PartialEq)]
1086enum SpaceState {
1087    Never,
1088    Punctuation,
1089    Ident, // Or ident/literal-like thing.
1090    Always,
1091}
1092
1093fn force_space_before(tok: &TokenKind) -> bool {
1094    debug!("tok: force_space_before {:?}", tok);
1095
1096    match tok {
1097        TokenKind::Eq
1098        | TokenKind::Lt
1099        | TokenKind::Le
1100        | TokenKind::EqEq
1101        | TokenKind::Ne
1102        | TokenKind::Ge
1103        | TokenKind::Gt
1104        | TokenKind::AndAnd
1105        | TokenKind::OrOr
1106        | TokenKind::Bang
1107        | TokenKind::Tilde
1108        | TokenKind::PlusEq
1109        | TokenKind::MinusEq
1110        | TokenKind::StarEq
1111        | TokenKind::SlashEq
1112        | TokenKind::PercentEq
1113        | TokenKind::CaretEq
1114        | TokenKind::AndEq
1115        | TokenKind::OrEq
1116        | TokenKind::ShlEq
1117        | TokenKind::ShrEq
1118        | TokenKind::At
1119        | TokenKind::RArrow
1120        | TokenKind::LArrow
1121        | TokenKind::FatArrow
1122        | TokenKind::Plus
1123        | TokenKind::Minus
1124        | TokenKind::Star
1125        | TokenKind::Slash
1126        | TokenKind::Percent
1127        | TokenKind::Caret
1128        | TokenKind::And
1129        | TokenKind::Or
1130        | TokenKind::Shl
1131        | TokenKind::Shr
1132        | TokenKind::Pound
1133        | TokenKind::Dollar => true,
1134        _ => false,
1135    }
1136}
1137
1138fn ident_like(tok: &Token) -> bool {
1139    matches!(
1140        tok.kind,
1141        TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(..)
1142    )
1143}
1144
1145fn next_space(tok: &TokenKind) -> SpaceState {
1146    debug!("next_space: {:?}", tok);
1147
1148    match tok {
1149        TokenKind::Bang
1150        | TokenKind::And
1151        | TokenKind::Tilde
1152        | TokenKind::At
1153        | TokenKind::Comma
1154        | TokenKind::Dot
1155        | TokenKind::DotDot
1156        | TokenKind::DotDotDot
1157        | TokenKind::DotDotEq
1158        | TokenKind::Question => SpaceState::Punctuation,
1159
1160        TokenKind::PathSep
1161        | TokenKind::Pound
1162        | TokenKind::Dollar
1163        | TokenKind::OpenParen
1164        | TokenKind::CloseParen
1165        | TokenKind::OpenBrace
1166        | TokenKind::CloseBrace
1167        | TokenKind::OpenBracket
1168        | TokenKind::CloseBracket
1169        | TokenKind::OpenInvisible(_)
1170        | TokenKind::CloseInvisible(_) => SpaceState::Never,
1171
1172        TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(..) => {
1173            SpaceState::Ident
1174        }
1175
1176        _ => SpaceState::Always,
1177    }
1178}
1179
1180/// Tries to convert a macro use into a short hand try expression. Returns `None`
1181/// when the macro is not an instance of `try!` (or parsing the inner expression
1182/// failed).
1183pub(crate) fn convert_try_mac(
1184    mac: &ast::MacCall,
1185    context: &RewriteContext<'_>,
1186) -> Option<ast::Expr> {
1187    let path = &pprust::path_to_string(&mac.path);
1188    if path == "try" || path == "r#try" {
1189        let ts = mac.args.tokens.clone();
1190
1191        Some(ast::Expr {
1192            id: ast::NodeId::root(), // dummy value
1193            kind: ast::ExprKind::Try(parse_expr(context, ts)?),
1194            span: mac.span(), // incorrect span, but shouldn't matter too much
1195            attrs: ast::AttrVec::new(),
1196            tokens: None,
1197        })
1198    } else {
1199        None
1200    }
1201}
1202
1203pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> Delimiter {
1204    let snippet = context.snippet(mac.span());
1205    let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::MAX);
1206    let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::MAX);
1207    let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::MAX);
1208
1209    if paren_pos < bracket_pos && paren_pos < brace_pos {
1210        Delimiter::Parenthesis
1211    } else if bracket_pos < brace_pos {
1212        Delimiter::Bracket
1213    } else {
1214        Delimiter::Brace
1215    }
1216}
1217
1218// A very simple parser that just parses a macros 2.0 definition into its branches.
1219// Currently we do not attempt to parse any further than that.
1220struct MacroParser<'a> {
1221    iter: TokenStreamIter<'a>,
1222}
1223
1224impl<'a> MacroParser<'a> {
1225    const fn new(iter: TokenStreamIter<'a>) -> Self {
1226        Self { iter }
1227    }
1228
1229    // (`(` ... `)` `=>` `{` ... `}`)*
1230    fn parse(&mut self) -> Option<Macro> {
1231        let mut branches = vec![];
1232        while self.iter.peek().is_some() {
1233            branches.push(self.parse_branch()?);
1234        }
1235
1236        Some(Macro { branches })
1237    }
1238
1239    // `(` ... `)` `=>` `{` ... `}`
1240    fn parse_branch(&mut self) -> Option<MacroBranch> {
1241        let tok = self.iter.next()?;
1242        let (lo, args_paren_kind) = match tok {
1243            TokenTree::Token(..) => return None,
1244            &TokenTree::Delimited(delimited_span, _, d, _) => (delimited_span.open.lo(), d),
1245        };
1246        let args = TokenStream::new(vec![tok.clone()]);
1247        match self.iter.next()? {
1248            TokenTree::Token(
1249                Token {
1250                    kind: TokenKind::FatArrow,
1251                    ..
1252                },
1253                _,
1254            ) => {}
1255            _ => return None,
1256        }
1257        let (mut hi, body, whole_body) = match self.iter.next()? {
1258            TokenTree::Token(..) => return None,
1259            TokenTree::Delimited(delimited_span, ..) => {
1260                let data = delimited_span.entire().data();
1261                (
1262                    data.hi,
1263                    Span::new(
1264                        data.lo + BytePos(1),
1265                        data.hi - BytePos(1),
1266                        data.ctxt,
1267                        data.parent,
1268                    ),
1269                    delimited_span.entire(),
1270                )
1271            }
1272        };
1273        if let Some(TokenTree::Token(
1274            Token {
1275                kind: TokenKind::Semi,
1276                span,
1277            },
1278            _,
1279        )) = self.iter.peek()
1280        {
1281            hi = span.hi();
1282            self.iter.next();
1283        }
1284        Some(MacroBranch {
1285            span: mk_sp(lo, hi),
1286            args_paren_kind,
1287            args,
1288            body,
1289            whole_body,
1290        })
1291    }
1292}
1293
1294// A parsed macros 2.0 macro definition.
1295struct Macro {
1296    branches: Vec<MacroBranch>,
1297}
1298
1299// FIXME: it would be more efficient to use references to the token streams
1300// rather than clone them, if we can make the borrowing work out.
1301struct MacroBranch {
1302    span: Span,
1303    args_paren_kind: Delimiter,
1304    args: TokenStream,
1305    body: Span,
1306    whole_body: Span,
1307}
1308
1309impl MacroBranch {
1310    fn rewrite(
1311        &self,
1312        context: &RewriteContext<'_>,
1313        shape: Shape,
1314        multi_branch_style: bool,
1315    ) -> RewriteResult {
1316        // Only attempt to format function-like macros.
1317        if self.args_paren_kind != Delimiter::Parenthesis {
1318            // FIXME(#1539): implement for non-sugared macros.
1319            return Err(RewriteError::MacroFailure {
1320                kind: MacroErrorKind::Unknown,
1321                span: self.span,
1322            });
1323        }
1324
1325        let old_body = context.snippet(self.body).trim();
1326        let has_block_body = old_body.starts_with('{');
1327        let mut prefix_width = 5; // 5 = " => {"
1328        if context.config.style_edition() >= StyleEdition::Edition2024 {
1329            if has_block_body {
1330                prefix_width = 6; // 6 = " => {{"
1331            }
1332        }
1333        let mut result = format_macro_args(
1334            context,
1335            self.args.clone(),
1336            shape.sub_width(prefix_width, self.span)?,
1337        )?;
1338
1339        if multi_branch_style {
1340            result += " =>";
1341        }
1342
1343        if !context.config.format_macro_bodies() {
1344            result += " ";
1345            result += context.snippet(self.whole_body);
1346            return Ok(result);
1347        }
1348
1349        // The macro body is the most interesting part. It might end up as various
1350        // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1351        // parsed as regular Rust code (and note that these can be escaped using
1352        // `$$`). We'll try and format like an AST node, but we'll substitute
1353        // variables for new names with the same length first.
1354
1355        let (body_str, substs) =
1356            replace_names(old_body).macro_error(MacroErrorKind::ReplaceMacroVariable, self.span)?;
1357
1358        let mut config = context.config.clone();
1359        config.set().show_parse_errors(false);
1360
1361        result += " {";
1362
1363        let body_indent = if has_block_body {
1364            shape.indent
1365        } else {
1366            shape.indent.block_indent(&config)
1367        };
1368        let new_width = config.max_width() - body_indent.width();
1369        config.set().max_width(new_width);
1370
1371        // First try to format as items, then as statements.
1372        let new_body_snippet = match crate::format_snippet(&body_str, &config, true) {
1373            Some(new_body) => new_body,
1374            None => {
1375                let new_width = new_width + config.tab_spaces();
1376                config.set().max_width(new_width);
1377                match crate::format_code_block(&body_str, &config, true) {
1378                    Some(new_body) => new_body,
1379                    None => {
1380                        return Err(RewriteError::MacroFailure {
1381                            kind: MacroErrorKind::Unknown,
1382                            span: self.span,
1383                        });
1384                    }
1385                }
1386            }
1387        };
1388
1389        if !filtered_str_fits(
1390            &new_body_snippet.snippet,
1391            config.max_width(),
1392            context.config.tab_spaces(),
1393            shape,
1394        ) {
1395            return Err(RewriteError::ExceedsMaxWidth {
1396                configured_width: shape.width,
1397                span: self.span,
1398            });
1399        }
1400
1401        // Indent the body since it is in a block.
1402        let indent_str = body_indent.to_string(&config);
1403        let mut new_body = LineClasses::new(new_body_snippet.snippet.trim_end())
1404            .enumerate()
1405            .fold(
1406                (String::new(), true),
1407                |(mut s, need_indent), (i, (kind, ref l))| {
1408                    if !is_empty_line(l)
1409                        && need_indent
1410                        && !new_body_snippet.is_line_non_formatted(i + 1)
1411                    {
1412                        s += &indent_str;
1413                    }
1414                    (s + l + "\n", indent_next_line(kind, l, &config))
1415                },
1416            )
1417            .0;
1418
1419        // Undo our replacement of macro variables.
1420        // FIXME: this could be *much* more efficient.
1421        for (old, new) in &substs {
1422            if old_body.contains(new) {
1423                debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1424                return Err(RewriteError::MacroFailure {
1425                    kind: MacroErrorKind::ReplaceMacroVariable,
1426                    span: self.span,
1427                });
1428            }
1429            new_body = new_body.replace(new, old);
1430        }
1431
1432        if has_block_body {
1433            result += new_body.trim();
1434        } else if !new_body.is_empty() {
1435            result += "\n";
1436            result += &new_body;
1437            result += &shape.indent.to_string(&config);
1438        }
1439
1440        result += "}";
1441
1442        Ok(result)
1443    }
1444}
1445
1446/// Format `lazy_static!` and `lazy_static::lazy_static!`
1447/// from <https://crates.io/crates/lazy_static>.
1448///
1449/// # Expected syntax
1450///
1451/// ```text
1452/// lazy_static! {
1453///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1454///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1455///     ...
1456///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1457/// }
1458///
1459/// lazy_static::lazy_static! {
1460///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1461///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1462///     ...
1463///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1464/// }
1465/// ```
1466fn format_lazy_static(
1467    context: &RewriteContext<'_>,
1468    shape: Shape,
1469    ts: TokenStream,
1470    span: Span,
1471    macro_name: &str,
1472) -> RewriteResult {
1473    let mut result = String::with_capacity(1024);
1474    let nested_shape = shape
1475        .block_indent(context.config.tab_spaces())
1476        .with_max_width(context.config);
1477
1478    result.push_str(macro_name);
1479    result.push_str(" {");
1480    result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1481
1482    let parsed_elems =
1483        parse_lazy_static(context, ts).macro_error(MacroErrorKind::ParseFailure, span)?;
1484    let last = parsed_elems.len() - 1;
1485    for (i, (vis, id, ty, expr)) in parsed_elems.iter().enumerate() {
1486        // Rewrite as a static item.
1487        let vis = crate::utils::format_visibility(context, vis);
1488        let mut stmt = String::with_capacity(128);
1489        stmt.push_str(&format!(
1490            "{}static ref {}: {} =",
1491            vis,
1492            id,
1493            ty.rewrite_result(context, nested_shape)?
1494        ));
1495        result.push_str(&rewrite_assign_rhs(
1496            context,
1497            stmt,
1498            &*expr,
1499            &RhsAssignKind::Expr(&expr.kind, expr.span),
1500            nested_shape.sub_width(1, expr.span)?,
1501        )?);
1502        result.push(';');
1503        if i != last {
1504            result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1505        }
1506    }
1507
1508    result.push_str(&shape.indent.to_string_with_newline(context.config));
1509    result.push('}');
1510
1511    Ok(result)
1512}
1513
1514fn rewrite_macro_with_items(
1515    context: &RewriteContext<'_>,
1516    items: &[MacroArg],
1517    macro_name: &str,
1518    shape: Shape,
1519    style: Delimiter,
1520    original_style: Delimiter,
1521    position: MacroPosition,
1522    span: Span,
1523) -> RewriteResult {
1524    let style_to_delims = |style| match style {
1525        Delimiter::Parenthesis => Ok(("(", ")")),
1526        Delimiter::Bracket => Ok(("[", "]")),
1527        Delimiter::Brace => Ok((" {", "}")),
1528        _ => Err(RewriteError::Unknown),
1529    };
1530
1531    let (opener, closer) = style_to_delims(style)?;
1532    let (original_opener, _) = style_to_delims(original_style)?;
1533    let trailing_semicolon = match style {
1534        Delimiter::Parenthesis | Delimiter::Bracket if position == MacroPosition::Item => ";",
1535        _ => "",
1536    };
1537
1538    let mut visitor = FmtVisitor::from_context(context);
1539    visitor.block_indent = shape.indent.block_indent(context.config);
1540
1541    // The current opener may be different from the original opener. This can happen
1542    // if our macro is a forced bracket macro originally written with non-bracket
1543    // delimiters. We need to use the original opener to locate the span after it.
1544    visitor.last_pos = context
1545        .snippet_provider
1546        .span_after(span, original_opener.trim());
1547    for item in items {
1548        let item = match item {
1549            MacroArg::Item(item) => item,
1550            _ => return Err(RewriteError::Unknown),
1551        };
1552        visitor.visit_item(item);
1553    }
1554
1555    let mut result = String::with_capacity(256);
1556    result.push_str(macro_name);
1557    result.push_str(opener);
1558    result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1559    result.push_str(visitor.buffer.trim());
1560    result.push_str(&shape.indent.to_string_with_newline(context.config));
1561    result.push_str(closer);
1562    result.push_str(trailing_semicolon);
1563    Ok(result)
1564}
1565
1566fn format_cfg_select(
1567    context: &RewriteContext<'_>,
1568    shape: Shape,
1569    span: Span,
1570    name: &str,
1571    delim_token: Delimiter,
1572    ts: TokenStream,
1573) -> RewriteResult {
1574    let mut rewrite = String::with_capacity((span.hi() - span.lo()).to_usize() * 2);
1575    rewrite.push_str(name);
1576
1577    let (opening_delim, closing_delim) = match delim_token {
1578        Delimiter::Brace => ("{", "}"),
1579        Delimiter::Bracket => ("[", "]"),
1580        Delimiter::Parenthesis => ("(", ")"),
1581        Delimiter::Invisible(_) => {
1582            unreachable!("cfg_select! macro will always have outer delimiters");
1583        }
1584    };
1585
1586    if matches!(delim_token, Delimiter::Brace) {
1587        rewrite.push(' ');
1588    };
1589
1590    let arms =
1591        parse_cfg_select_arms(context.psess, ts).macro_error(MacroErrorKind::ParseFailure, span)?;
1592
1593    if arms.is_empty() {
1594        let lo = context.snippet_provider.span_after(span, opening_delim);
1595        let hi = context.snippet_provider.span_before(span, closing_delim);
1596
1597        // NOTE(ytmimi) reusing `format_empty_struct_or_tuple` since
1598        // it handles proper indentation and recovering comments
1599        crate::items::format_empty_struct_or_tuple(
1600            context,
1601            mk_sp(lo, hi),
1602            shape.indent,
1603            &mut rewrite,
1604            opening_delim,
1605            closing_delim,
1606        );
1607        return Ok(rewrite);
1608    } else {
1609        rewrite.push_str(opening_delim);
1610    }
1611
1612    let nested_indent = shape.indent.block_indent(context.config);
1613    let nested_shape = Shape::indented(nested_indent, context.config);
1614    rewrite.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1615
1616    let last_arm = arms.last();
1617
1618    // We have to fib a little here and update the context to remove the `inside_macro` state.
1619    // The code that flattens match arms will refuse to do so if it's inside a macro. Mostly
1620    // this is done to prevent rustfmt from removing tokens in the context of a macro, but in
1621    // this case it should be fine since we know that each `cfg_select!` arm must be a valid expr.
1622    context.leave_macro();
1623
1624    let items = itemize_list(
1625        context.snippet_provider,
1626        arms.iter(),
1627        closing_delim,
1628        "}",
1629        |arm| arm.span().lo(),
1630        |arm| arm.span().hi(),
1631        |arm| rewrite_cfg_select_arm(context, nested_shape, last_arm, arm),
1632        // Start Span after the opening delimiter. For example,
1633        // ```
1634        // cfg_select! {
1635        //              ^ start here
1636        // }
1637        // ```
1638        context.snippet_provider.span_after(span, opening_delim),
1639        // End on closing delimiter. For example,
1640        // ```
1641        // cfg_select! {
1642        // }
1643        // ^ end here
1644        // ```
1645        span.hi(),
1646        false,
1647    );
1648    let arms_vec: Vec<_> = items.collect();
1649
1650    // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
1651    let fmt = ListFormatting::new(nested_shape, context.config)
1652        .separator("")
1653        .align_comments(false)
1654        .preserve_newline(true);
1655
1656    rewrite.push_str(&write_list(&arms_vec, &fmt)?);
1657    rewrite.push('\n');
1658    rewrite.push_str(&shape.indent.to_string(context.config));
1659    rewrite.push_str(closing_delim);
1660
1661    Ok(rewrite)
1662}
1663
1664fn rewrite_cfg_select_arm(
1665    context: &RewriteContext<'_>,
1666    nested_shape: Shape,
1667    last_arm: Option<&CfgSelectArm>,
1668    arm: &CfgSelectArm,
1669) -> Result<String, RewriteError> {
1670    let try_rewrite = || {
1671        let predicate_str = match &arm.predicate {
1672            CfgSelectFormatPredicate::Wildcard(_t) => Cow::Borrowed("_"),
1673            CfgSelectFormatPredicate::Cfg(meta_item_inner) => {
1674                Cow::Owned(meta_item_inner.rewrite_result(context, nested_shape)?)
1675            }
1676        };
1677
1678        // We need to account for comments between predicate and `=>`.
1679        let before_arrow_sp = arm.predicate.span().between(arm.arrow.span);
1680        let before_arrow = context.snippet(before_arrow_sp);
1681        let predicate_str = if contains_comment(before_arrow) {
1682            // We cannot rewrite if the last line is a line comment, it will comment out
1683            // `=>`.
1684            if last_line_contains_single_line_comment(before_arrow.trim_end()) {
1685                return Ok(context.snippet(arm.span()).to_owned());
1686            }
1687
1688            Cow::Owned(combine_strs_with_missing_comments(
1689                context,
1690                &predicate_str,
1691                "",
1692                before_arrow_sp,
1693                nested_shape,
1694                true,
1695            )?)
1696        } else {
1697            predicate_str
1698        };
1699
1700        match arm.maybe_double_block_concise_formatting(context) {
1701            // FIXME(ytmimi): the `rewrite_match_body` branch also handles
1702            // `control_brace_style` better. That said, it helps fix
1703            // <https://github.com/rust-lang/rustfmt/issues/7045>.
1704            Some(inner_expr) => {
1705                // ```
1706                // => /* comment */ {{ ... }}
1707                //    ^------------- between span
1708                // ```
1709                let after_arrow_comment = context
1710                    .snippet(arm.arrow.span.between(arm.expr.span()))
1711                    .trim();
1712                let after_arrow_comment = if after_arrow_comment.is_empty() {
1713                    None
1714                } else {
1715                    Some(rewrite_comment(
1716                        after_arrow_comment,
1717                        false,
1718                        nested_shape,
1719                        context.config,
1720                    )?)
1721                };
1722
1723                let trailing_comma = if arm.trailing_comma.is_some() {
1724                    ","
1725                } else {
1726                    ""
1727                };
1728
1729                // Force next-line layout if there's a comment after `=>`, like `match` arms.
1730                let next_line_open_brace = matches!(
1731                    context.config.control_brace_style(),
1732                    ControlBraceStyle::AlwaysNextLine,
1733                ) || after_arrow_comment.is_some();
1734
1735                let prefix_width = if next_line_open_brace {
1736                    0
1737                } else {
1738                    extra_offset(&predicate_str, nested_shape) + " => ".len()
1739                };
1740
1741                let body_shape = nested_shape
1742                    .offset_left(prefix_width + "{".len(), arm.span())?
1743                    .sub_width("}".len() + trailing_comma.len(), arm.span())?;
1744                let body = inner_expr.rewrite_result(context, body_shape)?;
1745
1746                let body = format!("{{{body}}}{trailing_comma}");
1747                match after_arrow_comment {
1748                    Some(comment) => {
1749                        let indent = nested_shape.indent.to_string_with_newline(context.config);
1750                        Ok(format!("{predicate_str} =>{indent}{comment}{indent}{body}"))
1751                    }
1752                    None if next_line_open_brace => {
1753                        let indent = nested_shape.indent.to_string_with_newline(context.config);
1754                        Ok(format!("{predicate_str} =>{indent}{body}"))
1755                    }
1756                    None => Ok(format!("{predicate_str} => {body}")),
1757                }
1758            }
1759            None => {
1760                // Note that we can't _just_ pass the `=>`'s span, we need to pass
1761                //
1762                // ```
1763                // => /* comment */ #[attr] { ... }
1764                // ^--------------- this whole span until outer expr
1765                // ```
1766                //
1767                // Using `Spanned::span` here for `arm.expr` to account for outer
1768                // attributes.
1769                crate::matches::rewrite_match_body(
1770                    context,
1771                    &arm.expr,
1772                    &predicate_str,
1773                    nested_shape,
1774                    false,
1775                    arm.arrow.span.until(arm.expr.span()),
1776                    last_arm.is_some_and(|la| la == arm),
1777                )
1778            }
1779        }
1780    };
1781
1782    let rw = try_rewrite()?;
1783    // NB: there could be a comment between body and trailing comma.
1784    Ok(recover_comment_removed(rw, arm.span(), context))
1785}