1use std::collections::HashMap;
13use std::panic::{AssertUnwindSafe, catch_unwind};
14
15use rustc_ast::token::{Delimiter, Token, TokenKind};
16use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree};
17use rustc_ast::{ast, ptr};
18use rustc_ast_pretty::pprust;
19use rustc_span::{
20 BytePos, DUMMY_SP, Span, Symbol,
21 symbol::{self, kw},
22};
23use tracing::debug;
24
25use crate::comment::{
26 CharClasses, FindUncommented, FullCodeCharKind, LineClasses, contains_comment,
27};
28use crate::config::StyleEdition;
29use crate::config::lists::*;
30use crate::expr::{RhsAssignKind, rewrite_array, rewrite_assign_rhs};
31use crate::lists::{ListFormatting, itemize_list, write_list};
32use crate::overflow;
33use crate::parse::macros::lazy_static::parse_lazy_static;
34use crate::parse::macros::{ParsedMacroArgs, parse_expr, parse_macro_args};
35use crate::rewrite::{
36 MacroErrorKind, Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult,
37};
38use crate::shape::{Indent, Shape};
39use crate::source_map::SpanUtils;
40use crate::spanned::Spanned;
41use crate::utils::{
42 NodeIdExt, filtered_str_fits, format_visibility, indent_next_line, is_empty_line, mk_sp,
43 remove_trailing_white_spaces, rewrite_ident, trim_left_preserve_layout,
44};
45use crate::visitor::FmtVisitor;
46
47const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub(crate) enum MacroPosition {
51 Item,
52 Statement,
53 Expression,
54 Pat,
55}
56
57#[derive(Debug)]
58pub(crate) enum MacroArg {
59 Expr(ptr::P<ast::Expr>),
60 Ty(ptr::P<ast::Ty>),
61 Pat(ptr::P<ast::Pat>),
62 Item(ptr::P<ast::Item>),
63 Keyword(symbol::Ident, Span),
64}
65
66impl MacroArg {
67 pub(crate) fn is_item(&self) -> bool {
68 match self {
69 MacroArg::Item(..) => true,
70 _ => false,
71 }
72 }
73}
74
75impl Rewrite for ast::Item {
76 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
77 self.rewrite_result(context, shape).ok()
78 }
79
80 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
81 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
82 visitor.block_indent = shape.indent;
83 visitor.last_pos = self.span().lo();
84 visitor.visit_item(self);
85 Ok(visitor.buffer.to_owned())
86 }
87}
88
89impl Rewrite for MacroArg {
90 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
91 self.rewrite_result(context, shape).ok()
92 }
93
94 fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
95 match *self {
96 MacroArg::Expr(ref expr) => expr.rewrite_result(context, shape),
97 MacroArg::Ty(ref ty) => ty.rewrite_result(context, shape),
98 MacroArg::Pat(ref pat) => pat.rewrite_result(context, shape),
99 MacroArg::Item(ref item) => item.rewrite_result(context, shape),
100 MacroArg::Keyword(ident, _) => Ok(ident.name.to_string()),
101 }
102 }
103}
104
105fn rewrite_macro_name(
107 context: &RewriteContext<'_>,
108 path: &ast::Path,
109 extra_ident: Option<symbol::Ident>,
110) -> String {
111 let name = if path.segments.len() == 1 {
112 format!("{}!", rewrite_ident(context, path.segments[0].ident))
114 } else {
115 format!("{}!", pprust::path_to_string(path))
116 };
117 match extra_ident {
118 Some(ident) if ident.name != kw::Empty => format!("{name} {ident}"),
119 _ => name,
120 }
121}
122
123fn return_macro_parse_failure_fallback(
127 context: &RewriteContext<'_>,
128 indent: Indent,
129 position: MacroPosition,
130 span: Span,
131) -> RewriteResult {
132 context.macro_rewrite_failure.replace(true);
134
135 let is_like_block_indent_style = context
138 .snippet(span)
139 .lines()
140 .last()
141 .map(|closing_line| {
142 closing_line
143 .trim()
144 .chars()
145 .all(|ch| matches!(ch, '}' | ')' | ']'))
146 })
147 .unwrap_or(false);
148 if is_like_block_indent_style {
149 return trim_left_preserve_layout(context.snippet(span), indent, context.config)
150 .macro_error(MacroErrorKind::Unknown, span);
151 }
152
153 context.skipped_range.borrow_mut().push((
154 context.psess.line_of_byte_pos(span.lo()),
155 context.psess.line_of_byte_pos(span.hi()),
156 ));
157
158 let mut snippet = context.snippet(span).to_owned();
160 if position == MacroPosition::Item {
161 snippet.push(';');
162 }
163 Ok(snippet)
164}
165
166pub(crate) fn rewrite_macro(
167 mac: &ast::MacCall,
168 extra_ident: Option<symbol::Ident>,
169 context: &RewriteContext<'_>,
170 shape: Shape,
171 position: MacroPosition,
172) -> RewriteResult {
173 let should_skip = context
174 .skip_context
175 .macros
176 .skip(context.snippet(mac.path.span));
177 if should_skip {
178 Err(RewriteError::SkipFormatting)
179 } else {
180 let guard = context.enter_macro();
181 let result = catch_unwind(AssertUnwindSafe(|| {
182 rewrite_macro_inner(
183 mac,
184 extra_ident,
185 context,
186 shape,
187 position,
188 guard.is_nested(),
189 )
190 }));
191 match result {
192 Err(..) => {
193 context.macro_rewrite_failure.replace(true);
194 Err(RewriteError::MacroFailure {
195 kind: MacroErrorKind::Unknown,
196 span: mac.span(),
197 })
198 }
199 Ok(Err(e)) => {
200 context.macro_rewrite_failure.replace(true);
201 Err(e)
202 }
203 Ok(rw) => rw,
204 }
205 }
206}
207
208fn rewrite_macro_inner(
209 mac: &ast::MacCall,
210 extra_ident: Option<symbol::Ident>,
211 context: &RewriteContext<'_>,
212 shape: Shape,
213 position: MacroPosition,
214 is_nested_macro: bool,
215) -> RewriteResult {
216 if context.config.use_try_shorthand() {
217 if let Some(expr) = convert_try_mac(mac, context) {
218 context.leave_macro();
219 return expr.rewrite_result(context, shape);
220 }
221 }
222
223 let original_style = macro_style(mac, context);
224
225 let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
226 let is_forced_bracket = FORCED_BRACKET_MACROS.contains(&¯o_name[..]);
227
228 let style = if is_forced_bracket && !is_nested_macro {
229 Delimiter::Bracket
230 } else {
231 original_style
232 };
233
234 let ts = mac.args.tokens.clone();
235 let has_comment = contains_comment(context.snippet(mac.span()));
236 if ts.is_empty() && !has_comment {
237 return match style {
238 Delimiter::Parenthesis if position == MacroPosition::Item => {
239 Ok(format!("{macro_name}();"))
240 }
241 Delimiter::Bracket if position == MacroPosition::Item => Ok(format!("{macro_name}[];")),
242 Delimiter::Parenthesis => Ok(format!("{macro_name}()")),
243 Delimiter::Bracket => Ok(format!("{macro_name}[]")),
244 Delimiter::Brace => Ok(format!("{macro_name} {{}}")),
245 _ => unreachable!(),
246 };
247 }
248 if macro_name == "lazy_static!" && !has_comment {
250 match format_lazy_static(context, shape, ts.clone(), mac.span()) {
251 Ok(rw) => return Ok(rw),
252 Err(err) => match err {
253 RewriteError::MacroFailure { kind, span: _ }
256 if kind == MacroErrorKind::ParseFailure => {}
257 _ => return Err(err),
259 },
260 }
261 }
262
263 let ParsedMacroArgs {
264 args: arg_vec,
265 vec_with_semi,
266 trailing_comma,
267 } = match parse_macro_args(context, ts, style, is_forced_bracket) {
268 Some(args) => args,
269 None => {
270 return return_macro_parse_failure_fallback(
271 context,
272 shape.indent,
273 position,
274 mac.span(),
275 );
276 }
277 };
278
279 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
280 return rewrite_macro_with_items(
281 context,
282 &arg_vec,
283 ¯o_name,
284 shape,
285 style,
286 original_style,
287 position,
288 mac.span(),
289 );
290 }
291
292 match style {
293 Delimiter::Parenthesis => {
294 if vec_with_semi {
296 handle_vec_semi(context, shape, arg_vec, macro_name, style, mac.span())
297 } else {
298 overflow::rewrite_with_parens(
301 context,
302 ¯o_name,
303 arg_vec.iter(),
304 shape,
305 mac.span(),
306 context.config.fn_call_width(),
307 if trailing_comma {
308 Some(SeparatorTactic::Always)
309 } else {
310 Some(SeparatorTactic::Never)
311 },
312 )
313 .map(|rw| match position {
314 MacroPosition::Item => format!("{};", rw),
315 _ => rw,
316 })
317 }
318 }
319 Delimiter::Bracket => {
320 if vec_with_semi {
322 handle_vec_semi(context, shape, arg_vec, macro_name, style, mac.span())
323 } else {
324 let mut force_trailing_comma = if trailing_comma {
328 Some(SeparatorTactic::Always)
329 } else {
330 Some(SeparatorTactic::Never)
331 };
332 if is_forced_bracket && !is_nested_macro {
333 context.leave_macro();
334 if context.use_block_indent() {
335 force_trailing_comma = Some(SeparatorTactic::Vertical);
336 };
337 }
338 let rewrite = rewrite_array(
339 ¯o_name,
340 arg_vec.iter(),
341 mac.span(),
342 context,
343 shape,
344 force_trailing_comma,
345 Some(original_style),
346 )?;
347 let comma = match position {
348 MacroPosition::Item => ";",
349 _ => "",
350 };
351
352 Ok(format!("{rewrite}{comma}"))
353 }
354 }
355 Delimiter::Brace => {
356 let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
360 match trim_left_preserve_layout(snippet, shape.indent, context.config) {
361 Some(macro_body) => Ok(format!("{macro_name} {macro_body}")),
362 None => Ok(format!("{macro_name} {snippet}")),
363 }
364 }
365 _ => unreachable!(),
366 }
367}
368
369fn handle_vec_semi(
370 context: &RewriteContext<'_>,
371 shape: Shape,
372 arg_vec: Vec<MacroArg>,
373 macro_name: String,
374 delim_token: Delimiter,
375 span: Span,
376) -> RewriteResult {
377 let (left, right) = match delim_token {
378 Delimiter::Parenthesis => ("(", ")"),
379 Delimiter::Bracket => ("[", "]"),
380 _ => unreachable!(),
381 };
382
383 let mac_shape = shape
385 .offset_left(macro_name.len())
386 .max_width_error(shape.width, span)?;
387 let total_overhead = 8;
389 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
390 let lhs = arg_vec[0].rewrite_result(context, nested_shape)?;
391 let rhs = arg_vec[1].rewrite_result(context, nested_shape)?;
392 if !lhs.contains('\n')
393 && !rhs.contains('\n')
394 && lhs.len() + rhs.len() + total_overhead <= shape.width
395 {
396 Ok(format!("{macro_name}{left}{lhs}; {rhs}{right}"))
398 } else {
399 Ok(format!(
401 "{}{}{}{};{}{}{}{}",
402 macro_name,
403 left,
404 nested_shape.indent.to_string_with_newline(context.config),
405 lhs,
406 nested_shape.indent.to_string_with_newline(context.config),
407 rhs,
408 shape.indent.to_string_with_newline(context.config),
409 right
410 ))
411 }
412}
413
414fn rewrite_empty_macro_def_body(
415 context: &RewriteContext<'_>,
416 span: Span,
417 shape: Shape,
418) -> RewriteResult {
419 let block = ast::Block {
421 stmts: vec![].into(),
422 id: rustc_ast::node_id::DUMMY_NODE_ID,
423 rules: ast::BlockCheckMode::Default,
424 span,
425 tokens: None,
426 };
427 block.rewrite_result(context, shape)
428}
429
430pub(crate) fn rewrite_macro_def(
431 context: &RewriteContext<'_>,
432 shape: Shape,
433 indent: Indent,
434 def: &ast::MacroDef,
435 ident: symbol::Ident,
436 vis: &ast::Visibility,
437 span: Span,
438) -> RewriteResult {
439 let snippet = Ok(remove_trailing_white_spaces(context.snippet(span)));
440 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
441 return snippet;
442 }
443
444 let ts = def.body.tokens.clone();
445 let mut parser = MacroParser::new(ts.iter());
446 let parsed_def = match parser.parse() {
447 Some(def) => def,
448 None => return snippet,
449 };
450
451 let mut result = if def.macro_rules {
452 String::from("macro_rules!")
453 } else {
454 format!("{}macro", format_visibility(context, vis))
455 };
456
457 result += " ";
458 result += rewrite_ident(context, ident);
459
460 let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1;
461
462 let arm_shape = if multi_branch_style {
463 shape
464 .block_indent(context.config.tab_spaces())
465 .with_max_width(context.config)
466 } else {
467 shape
468 };
469
470 if parsed_def.branches.len() == 0 {
471 let lo = context.snippet_provider.span_before(span, "{");
472 result += " ";
473 result += &rewrite_empty_macro_def_body(context, span.with_lo(lo), shape)?;
474 return Ok(result);
475 }
476
477 let branch_items = itemize_list(
478 context.snippet_provider,
479 parsed_def.branches.iter(),
480 "}",
481 ";",
482 |branch| branch.span.lo(),
483 |branch| branch.span.hi(),
484 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
485 Ok(v) => Ok(v),
486 Err(_) if context.macro_rewrite_failure.get() => {
490 Ok(context.snippet(branch.body).trim().to_string())
491 }
492 Err(e) => Err(e),
493 },
494 context.snippet_provider.span_after(span, "{"),
495 span.hi(),
496 false,
497 )
498 .collect::<Vec<_>>();
499
500 let fmt = ListFormatting::new(arm_shape, context.config)
501 .separator(if def.macro_rules { ";" } else { "" })
502 .trailing_separator(SeparatorTactic::Always)
503 .preserve_newline(true);
504
505 if multi_branch_style {
506 result += " {";
507 result += &arm_shape.indent.to_string_with_newline(context.config);
508 }
509
510 match write_list(&branch_items, &fmt) {
511 Ok(ref s) => result += s,
512 Err(_) => return snippet,
513 }
514
515 if multi_branch_style {
516 result += &indent.to_string_with_newline(context.config);
517 result += "}";
518 }
519
520 Ok(result)
521}
522
523fn register_metavariable(
524 map: &mut HashMap<String, String>,
525 result: &mut String,
526 name: &str,
527 dollar_count: usize,
528) {
529 let mut new_name = "$".repeat(dollar_count - 1);
530 let mut old_name = "$".repeat(dollar_count);
531
532 new_name.push('z');
533 new_name.push_str(name);
534 old_name.push_str(name);
535
536 result.push_str(&new_name);
537 map.insert(old_name, new_name);
538}
539
540fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
544 let mut result = String::with_capacity(input.len() + 64);
546 let mut substs = HashMap::new();
547 let mut dollar_count = 0;
548 let mut cur_name = String::new();
549
550 for (kind, c) in CharClasses::new(input.chars()) {
551 if kind != FullCodeCharKind::Normal {
552 result.push(c);
553 } else if c == '$' {
554 dollar_count += 1;
555 } else if dollar_count == 0 {
556 result.push(c);
557 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
558 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
560
561 result.push(c);
562 dollar_count = 0;
563 cur_name.clear();
564 } else if c == '(' && cur_name.is_empty() {
565 return None;
567 } else if c.is_alphanumeric() || c == '_' {
568 cur_name.push(c);
569 }
570 }
571
572 if !cur_name.is_empty() {
573 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
574 }
575
576 debug!("replace_names `{}` {:?}", result, substs);
577
578 Some((result, substs))
579}
580
581#[derive(Debug, Clone)]
582enum MacroArgKind {
583 MetaVariable(Symbol, String),
585 Repeat(
587 Delimiter,
589 Vec<ParsedMacroArg>,
591 Option<Box<ParsedMacroArg>>,
593 Token,
595 ),
596 Delimited(Delimiter, Vec<ParsedMacroArg>),
598 Separator(String, String),
600 Other(String, String),
603}
604
605fn delim_token_to_str(
606 context: &RewriteContext<'_>,
607 delim_token: Delimiter,
608 shape: Shape,
609 use_multiple_lines: bool,
610 inner_is_empty: bool,
611) -> (String, String) {
612 let (lhs, rhs) = match delim_token {
613 Delimiter::Parenthesis => ("(", ")"),
614 Delimiter::Bracket => ("[", "]"),
615 Delimiter::Brace => {
616 if inner_is_empty || use_multiple_lines {
617 ("{", "}")
618 } else {
619 ("{ ", " }")
620 }
621 }
622 Delimiter::Invisible(_) => unreachable!(),
623 };
624 if use_multiple_lines {
625 let indent_str = shape.indent.to_string_with_newline(context.config);
626 let nested_indent_str = shape
627 .indent
628 .block_indent(context.config)
629 .to_string_with_newline(context.config);
630 (
631 format!("{lhs}{nested_indent_str}"),
632 format!("{indent_str}{rhs}"),
633 )
634 } else {
635 (lhs.to_owned(), rhs.to_owned())
636 }
637}
638
639impl MacroArgKind {
640 fn starts_with_brace(&self) -> bool {
641 matches!(
642 *self,
643 MacroArgKind::Repeat(Delimiter::Brace, _, _, _)
644 | MacroArgKind::Delimited(Delimiter::Brace, _)
645 )
646 }
647
648 fn starts_with_dollar(&self) -> bool {
649 matches!(
650 *self,
651 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..)
652 )
653 }
654
655 fn ends_with_space(&self) -> bool {
656 matches!(*self, MacroArgKind::Separator(..))
657 }
658
659 fn has_meta_var(&self) -> bool {
660 match *self {
661 MacroArgKind::MetaVariable(..) => true,
662 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
663 _ => false,
664 }
665 }
666
667 fn rewrite(
668 &self,
669 context: &RewriteContext<'_>,
670 shape: Shape,
671 use_multiple_lines: bool,
672 ) -> RewriteResult {
673 type DelimitedArgsRewrite = Result<(String, String, String), RewriteError>;
674 let rewrite_delimited_inner = |delim_tok, args| -> DelimitedArgsRewrite {
675 let inner = wrap_macro_args(context, args, shape)?;
676 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
677 if lhs.len() + inner.len() + rhs.len() <= shape.width {
678 return Ok((lhs, inner, rhs));
679 }
680
681 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
682 let nested_shape = shape
683 .block_indent(context.config.tab_spaces())
684 .with_max_width(context.config);
685 let inner = wrap_macro_args(context, args, nested_shape)?;
686 Ok((lhs, inner, rhs))
687 };
688
689 match *self {
690 MacroArgKind::MetaVariable(ty, ref name) => Ok(format!("${name}:{ty}")),
691 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
692 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
693 let another = another
694 .as_ref()
695 .and_then(|a| a.rewrite(context, shape, use_multiple_lines).ok())
696 .unwrap_or_else(|| "".to_owned());
697 let repeat_tok = pprust::token_to_string(tok);
698
699 Ok(format!("${lhs}{inner}{rhs}{another}{repeat_tok}"))
700 }
701 MacroArgKind::Delimited(delim_tok, ref args) => {
702 rewrite_delimited_inner(delim_tok, args)
703 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
704 }
705 MacroArgKind::Separator(ref sep, ref prefix) => Ok(format!("{prefix}{sep} ")),
706 MacroArgKind::Other(ref inner, ref prefix) => Ok(format!("{prefix}{inner}")),
707 }
708 }
709}
710
711#[derive(Debug, Clone)]
712struct ParsedMacroArg {
713 kind: MacroArgKind,
714}
715
716impl ParsedMacroArg {
717 fn rewrite(
718 &self,
719 context: &RewriteContext<'_>,
720 shape: Shape,
721 use_multiple_lines: bool,
722 ) -> RewriteResult {
723 self.kind.rewrite(context, shape, use_multiple_lines)
724 }
725}
726
727struct MacroArgParser {
729 buf: String,
731 start_tok: Token,
733 is_meta_var: bool,
735 last_tok: Token,
737 result: Vec<ParsedMacroArg>,
739}
740
741fn last_tok(tt: &TokenTree) -> Token {
742 match *tt {
743 TokenTree::Token(ref t, _) => t.clone(),
744 TokenTree::Delimited(delim_span, _, delim, _) => Token {
745 kind: TokenKind::CloseDelim(delim),
746 span: delim_span.close,
747 },
748 }
749}
750
751impl MacroArgParser {
752 fn new() -> MacroArgParser {
753 MacroArgParser {
754 buf: String::new(),
755 is_meta_var: false,
756 last_tok: Token {
757 kind: TokenKind::Eof,
758 span: DUMMY_SP,
759 },
760 start_tok: Token {
761 kind: TokenKind::Eof,
762 span: DUMMY_SP,
763 },
764 result: vec![],
765 }
766 }
767
768 fn set_last_tok(&mut self, tok: &TokenTree) {
769 self.last_tok = last_tok(tok);
770 }
771
772 fn add_separator(&mut self) {
773 let prefix = if self.need_space_prefix() {
774 " ".to_owned()
775 } else {
776 "".to_owned()
777 };
778 self.result.push(ParsedMacroArg {
779 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
780 });
781 self.buf.clear();
782 }
783
784 fn add_other(&mut self) {
785 let prefix = if self.need_space_prefix() {
786 " ".to_owned()
787 } else {
788 "".to_owned()
789 };
790 self.result.push(ParsedMacroArg {
791 kind: MacroArgKind::Other(self.buf.clone(), prefix),
792 });
793 self.buf.clear();
794 }
795
796 fn add_meta_variable(&mut self, iter: &mut TokenStreamIter<'_>) -> Option<()> {
797 match iter.next() {
798 Some(&TokenTree::Token(
799 Token {
800 kind: TokenKind::Ident(name, _),
801 ..
802 },
803 _,
804 )) => {
805 self.result.push(ParsedMacroArg {
806 kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
807 });
808
809 self.buf.clear();
810 self.is_meta_var = false;
811 Some(())
812 }
813 _ => None,
814 }
815 }
816
817 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: Delimiter) {
818 self.result.push(ParsedMacroArg {
819 kind: MacroArgKind::Delimited(delim, inner),
820 });
821 }
822
823 fn add_repeat(
825 &mut self,
826 inner: Vec<ParsedMacroArg>,
827 delim: Delimiter,
828 iter: &mut TokenStreamIter<'_>,
829 ) -> Option<()> {
830 let mut buffer = String::new();
831 let mut first = true;
832
833 for tok in iter {
835 self.set_last_tok(&tok);
836 if first {
837 first = false;
838 }
839
840 match tok {
841 TokenTree::Token(
842 Token {
843 kind: TokenKind::Plus,
844 ..
845 },
846 _,
847 )
848 | TokenTree::Token(
849 Token {
850 kind: TokenKind::Question,
851 ..
852 },
853 _,
854 )
855 | TokenTree::Token(
856 Token {
857 kind: TokenKind::Star,
858 ..
859 },
860 _,
861 ) => {
862 break;
863 }
864 TokenTree::Token(ref t, _) => {
865 buffer.push_str(&pprust::token_to_string(t));
866 }
867 _ => return None,
868 }
869 }
870
871 let another = if buffer.trim().is_empty() {
873 None
874 } else {
875 Some(Box::new(ParsedMacroArg {
876 kind: MacroArgKind::Other(buffer, "".to_owned()),
877 }))
878 };
879
880 self.result.push(ParsedMacroArg {
881 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
882 });
883 Some(())
884 }
885
886 fn update_buffer(&mut self, t: &Token) {
887 if self.buf.is_empty() {
888 self.start_tok = t.clone();
889 } else {
890 let needs_space = match next_space(&self.last_tok.kind) {
891 SpaceState::Ident => ident_like(t),
892 SpaceState::Punctuation => !ident_like(t),
893 SpaceState::Always => true,
894 SpaceState::Never => false,
895 };
896 if force_space_before(&t.kind) || needs_space {
897 self.buf.push(' ');
898 }
899 }
900
901 self.buf.push_str(&pprust::token_to_string(t));
902 }
903
904 fn need_space_prefix(&self) -> bool {
905 if self.result.is_empty() {
906 return false;
907 }
908
909 let last_arg = self.result.last().unwrap();
910 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
911 if ident_like(&self.start_tok) {
912 return true;
913 }
914 if self.start_tok.kind == TokenKind::Colon {
915 return true;
916 }
917 }
918
919 if force_space_before(&self.start_tok.kind) {
920 return true;
921 }
922
923 false
924 }
925
926 fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
928 let mut iter = tokens.iter();
929
930 while let Some(tok) = iter.next() {
931 match tok {
932 &TokenTree::Token(
933 Token {
934 kind: TokenKind::Dollar,
935 span,
936 },
937 _,
938 ) => {
939 if !self.buf.is_empty() {
941 self.add_separator();
942 }
943
944 self.is_meta_var = true;
946 self.start_tok = Token {
947 kind: TokenKind::Dollar,
948 span,
949 };
950 }
951 TokenTree::Token(
952 Token {
953 kind: TokenKind::Colon,
954 ..
955 },
956 _,
957 ) if self.is_meta_var => {
958 self.add_meta_variable(&mut iter)?;
959 }
960 TokenTree::Token(ref t, _) => self.update_buffer(t),
961 &TokenTree::Delimited(_dspan, _spacing, delimited, ref tts) => {
962 if !self.buf.is_empty() {
963 if next_space(&self.last_tok.kind) == SpaceState::Always {
964 self.add_separator();
965 } else {
966 self.add_other();
967 }
968 }
969
970 let parser = MacroArgParser::new();
972 let delimited_arg = parser.parse(tts.clone())?;
973
974 if self.is_meta_var {
975 self.add_repeat(delimited_arg, delimited, &mut iter)?;
976 self.is_meta_var = false;
977 } else {
978 self.add_delimited(delimited_arg, delimited);
979 }
980 }
981 }
982
983 self.set_last_tok(&tok);
984 }
985
986 if !self.buf.is_empty() {
989 self.add_other();
990 }
991
992 Some(self.result)
993 }
994}
995
996fn wrap_macro_args(
997 context: &RewriteContext<'_>,
998 args: &[ParsedMacroArg],
999 shape: Shape,
1000) -> RewriteResult {
1001 wrap_macro_args_inner(context, args, shape, false)
1002 .or_else(|_| wrap_macro_args_inner(context, args, shape, true))
1003}
1004
1005fn wrap_macro_args_inner(
1006 context: &RewriteContext<'_>,
1007 args: &[ParsedMacroArg],
1008 shape: Shape,
1009 use_multiple_lines: bool,
1010) -> RewriteResult {
1011 let mut result = String::with_capacity(128);
1012 let mut iter = args.iter().peekable();
1013 let indent_str = shape.indent.to_string_with_newline(context.config);
1014
1015 while let Some(arg) = iter.next() {
1016 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1017
1018 if use_multiple_lines
1019 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1020 {
1021 if arg.kind.ends_with_space() {
1022 result.pop();
1023 }
1024 result.push_str(&indent_str);
1025 } else if let Some(next_arg) = iter.peek() {
1026 let space_before_dollar =
1027 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1028 let space_before_brace = next_arg.kind.starts_with_brace();
1029 if space_before_dollar || space_before_brace {
1030 result.push(' ');
1031 }
1032 }
1033 }
1034
1035 if !use_multiple_lines && result.len() >= shape.width {
1036 Err(RewriteError::Unknown)
1037 } else {
1038 Ok(result)
1039 }
1040}
1041
1042fn format_macro_args(
1047 context: &RewriteContext<'_>,
1048 token_stream: TokenStream,
1049 shape: Shape,
1050) -> RewriteResult {
1051 let span = span_for_token_stream(&token_stream);
1052 if !context.config.format_macro_matchers() {
1053 return Ok(match span {
1054 Some(span) => context.snippet(span).to_owned(),
1055 None => String::new(),
1056 });
1057 }
1058 let parsed_args = MacroArgParser::new()
1059 .parse(token_stream)
1060 .macro_error(MacroErrorKind::ParseFailure, span.unwrap())?;
1061 wrap_macro_args(context, &parsed_args, shape)
1062}
1063
1064fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1065 token_stream.iter().next().map(|tt| tt.span())
1066}
1067
1068#[derive(Copy, Clone, PartialEq)]
1070enum SpaceState {
1071 Never,
1072 Punctuation,
1073 Ident, Always,
1075}
1076
1077fn force_space_before(tok: &TokenKind) -> bool {
1078 debug!("tok: force_space_before {:?}", tok);
1079
1080 match tok {
1081 TokenKind::Eq
1082 | TokenKind::Lt
1083 | TokenKind::Le
1084 | TokenKind::EqEq
1085 | TokenKind::Ne
1086 | TokenKind::Ge
1087 | TokenKind::Gt
1088 | TokenKind::AndAnd
1089 | TokenKind::OrOr
1090 | TokenKind::Bang
1091 | TokenKind::Tilde
1092 | TokenKind::PlusEq
1093 | TokenKind::MinusEq
1094 | TokenKind::StarEq
1095 | TokenKind::SlashEq
1096 | TokenKind::PercentEq
1097 | TokenKind::CaretEq
1098 | TokenKind::AndEq
1099 | TokenKind::OrEq
1100 | TokenKind::ShlEq
1101 | TokenKind::ShrEq
1102 | TokenKind::At
1103 | TokenKind::RArrow
1104 | TokenKind::LArrow
1105 | TokenKind::FatArrow
1106 | TokenKind::Plus
1107 | TokenKind::Minus
1108 | TokenKind::Star
1109 | TokenKind::Slash
1110 | TokenKind::Percent
1111 | TokenKind::Caret
1112 | TokenKind::And
1113 | TokenKind::Or
1114 | TokenKind::Shl
1115 | TokenKind::Shr
1116 | TokenKind::Pound
1117 | TokenKind::Dollar => true,
1118 _ => false,
1119 }
1120}
1121
1122fn ident_like(tok: &Token) -> bool {
1123 matches!(
1124 tok.kind,
1125 TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(..)
1126 )
1127}
1128
1129fn next_space(tok: &TokenKind) -> SpaceState {
1130 debug!("next_space: {:?}", tok);
1131
1132 match tok {
1133 TokenKind::Bang
1134 | TokenKind::And
1135 | TokenKind::Tilde
1136 | TokenKind::At
1137 | TokenKind::Comma
1138 | TokenKind::Dot
1139 | TokenKind::DotDot
1140 | TokenKind::DotDotDot
1141 | TokenKind::DotDotEq
1142 | TokenKind::Question => SpaceState::Punctuation,
1143
1144 TokenKind::PathSep
1145 | TokenKind::Pound
1146 | TokenKind::Dollar
1147 | TokenKind::OpenDelim(_)
1148 | TokenKind::CloseDelim(_) => SpaceState::Never,
1149
1150 TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(..) => {
1151 SpaceState::Ident
1152 }
1153
1154 _ => SpaceState::Always,
1155 }
1156}
1157
1158pub(crate) fn convert_try_mac(
1162 mac: &ast::MacCall,
1163 context: &RewriteContext<'_>,
1164) -> Option<ast::Expr> {
1165 let path = &pprust::path_to_string(&mac.path);
1166 if path == "try" || path == "r#try" {
1167 let ts = mac.args.tokens.clone();
1168
1169 Some(ast::Expr {
1170 id: ast::NodeId::root(), kind: ast::ExprKind::Try(parse_expr(context, ts)?),
1172 span: mac.span(), attrs: ast::AttrVec::new(),
1174 tokens: None,
1175 })
1176 } else {
1177 None
1178 }
1179}
1180
1181pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> Delimiter {
1182 let snippet = context.snippet(mac.span());
1183 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::MAX);
1184 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::MAX);
1185 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::MAX);
1186
1187 if paren_pos < bracket_pos && paren_pos < brace_pos {
1188 Delimiter::Parenthesis
1189 } else if bracket_pos < brace_pos {
1190 Delimiter::Bracket
1191 } else {
1192 Delimiter::Brace
1193 }
1194}
1195
1196struct MacroParser<'a> {
1199 iter: TokenStreamIter<'a>,
1200}
1201
1202impl<'a> MacroParser<'a> {
1203 const fn new(iter: TokenStreamIter<'a>) -> Self {
1204 Self { iter }
1205 }
1206
1207 fn parse(&mut self) -> Option<Macro> {
1209 let mut branches = vec![];
1210 while self.iter.peek().is_some() {
1211 branches.push(self.parse_branch()?);
1212 }
1213
1214 Some(Macro { branches })
1215 }
1216
1217 fn parse_branch(&mut self) -> Option<MacroBranch> {
1219 let tok = self.iter.next()?;
1220 let (lo, args_paren_kind) = match tok {
1221 TokenTree::Token(..) => return None,
1222 &TokenTree::Delimited(delimited_span, _, d, _) => (delimited_span.open.lo(), d),
1223 };
1224 let args = TokenStream::new(vec![tok.clone()]);
1225 match self.iter.next()? {
1226 TokenTree::Token(
1227 Token {
1228 kind: TokenKind::FatArrow,
1229 ..
1230 },
1231 _,
1232 ) => {}
1233 _ => return None,
1234 }
1235 let (mut hi, body, whole_body) = match self.iter.next()? {
1236 TokenTree::Token(..) => return None,
1237 TokenTree::Delimited(delimited_span, ..) => {
1238 let data = delimited_span.entire().data();
1239 (
1240 data.hi,
1241 Span::new(
1242 data.lo + BytePos(1),
1243 data.hi - BytePos(1),
1244 data.ctxt,
1245 data.parent,
1246 ),
1247 delimited_span.entire(),
1248 )
1249 }
1250 };
1251 if let Some(TokenTree::Token(
1252 Token {
1253 kind: TokenKind::Semi,
1254 span,
1255 },
1256 _,
1257 )) = self.iter.peek()
1258 {
1259 hi = span.hi();
1260 self.iter.next();
1261 }
1262 Some(MacroBranch {
1263 span: mk_sp(lo, hi),
1264 args_paren_kind,
1265 args,
1266 body,
1267 whole_body,
1268 })
1269 }
1270}
1271
1272struct Macro {
1274 branches: Vec<MacroBranch>,
1275}
1276
1277struct MacroBranch {
1280 span: Span,
1281 args_paren_kind: Delimiter,
1282 args: TokenStream,
1283 body: Span,
1284 whole_body: Span,
1285}
1286
1287impl MacroBranch {
1288 fn rewrite(
1289 &self,
1290 context: &RewriteContext<'_>,
1291 shape: Shape,
1292 multi_branch_style: bool,
1293 ) -> RewriteResult {
1294 if self.args_paren_kind != Delimiter::Parenthesis {
1296 return Err(RewriteError::MacroFailure {
1298 kind: MacroErrorKind::Unknown,
1299 span: self.span,
1300 });
1301 }
1302
1303 let old_body = context.snippet(self.body).trim();
1304 let has_block_body = old_body.starts_with('{');
1305 let mut prefix_width = 5; if context.config.style_edition() >= StyleEdition::Edition2024 {
1307 if has_block_body {
1308 prefix_width = 6; }
1310 }
1311 let mut result = format_macro_args(
1312 context,
1313 self.args.clone(),
1314 shape
1315 .sub_width(prefix_width)
1316 .max_width_error(shape.width, self.span)?,
1317 )?;
1318
1319 if multi_branch_style {
1320 result += " =>";
1321 }
1322
1323 if !context.config.format_macro_bodies() {
1324 result += " ";
1325 result += context.snippet(self.whole_body);
1326 return Ok(result);
1327 }
1328
1329 let (body_str, substs) =
1336 replace_names(old_body).macro_error(MacroErrorKind::ReplaceMacroVariable, self.span)?;
1337
1338 let mut config = context.config.clone();
1339 config.set().show_parse_errors(false);
1340
1341 result += " {";
1342
1343 let body_indent = if has_block_body {
1344 shape.indent
1345 } else {
1346 shape.indent.block_indent(&config)
1347 };
1348 let new_width = config.max_width() - body_indent.width();
1349 config.set().max_width(new_width);
1350
1351 let new_body_snippet = match crate::format_snippet(&body_str, &config, true) {
1353 Some(new_body) => new_body,
1354 None => {
1355 let new_width = new_width + config.tab_spaces();
1356 config.set().max_width(new_width);
1357 match crate::format_code_block(&body_str, &config, true) {
1358 Some(new_body) => new_body,
1359 None => {
1360 return Err(RewriteError::MacroFailure {
1361 kind: MacroErrorKind::Unknown,
1362 span: self.span,
1363 });
1364 }
1365 }
1366 }
1367 };
1368
1369 if !filtered_str_fits(&new_body_snippet.snippet, config.max_width(), shape) {
1370 return Err(RewriteError::ExceedsMaxWidth {
1371 configured_width: shape.width,
1372 span: self.span,
1373 });
1374 }
1375
1376 let indent_str = body_indent.to_string(&config);
1378 let mut new_body = LineClasses::new(new_body_snippet.snippet.trim_end())
1379 .enumerate()
1380 .fold(
1381 (String::new(), true),
1382 |(mut s, need_indent), (i, (kind, ref l))| {
1383 if !is_empty_line(l)
1384 && need_indent
1385 && !new_body_snippet.is_line_non_formatted(i + 1)
1386 {
1387 s += &indent_str;
1388 }
1389 (s + l + "\n", indent_next_line(kind, l, &config))
1390 },
1391 )
1392 .0;
1393
1394 for (old, new) in &substs {
1397 if old_body.contains(new) {
1398 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1399 return Err(RewriteError::MacroFailure {
1400 kind: MacroErrorKind::ReplaceMacroVariable,
1401 span: self.span,
1402 });
1403 }
1404 new_body = new_body.replace(new, old);
1405 }
1406
1407 if has_block_body {
1408 result += new_body.trim();
1409 } else if !new_body.is_empty() {
1410 result += "\n";
1411 result += &new_body;
1412 result += &shape.indent.to_string(&config);
1413 }
1414
1415 result += "}";
1416
1417 Ok(result)
1418 }
1419}
1420
1421fn format_lazy_static(
1434 context: &RewriteContext<'_>,
1435 shape: Shape,
1436 ts: TokenStream,
1437 span: Span,
1438) -> RewriteResult {
1439 let mut result = String::with_capacity(1024);
1440 let nested_shape = shape
1441 .block_indent(context.config.tab_spaces())
1442 .with_max_width(context.config);
1443
1444 result.push_str("lazy_static! {");
1445 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1446
1447 let parsed_elems =
1448 parse_lazy_static(context, ts).macro_error(MacroErrorKind::ParseFailure, span)?;
1449 let last = parsed_elems.len() - 1;
1450 for (i, (vis, id, ty, expr)) in parsed_elems.iter().enumerate() {
1451 let vis = crate::utils::format_visibility(context, vis);
1453 let mut stmt = String::with_capacity(128);
1454 stmt.push_str(&format!(
1455 "{}static ref {}: {} =",
1456 vis,
1457 id,
1458 ty.rewrite_result(context, nested_shape)?
1459 ));
1460 result.push_str(&rewrite_assign_rhs(
1461 context,
1462 stmt,
1463 &*expr,
1464 &RhsAssignKind::Expr(&expr.kind, expr.span),
1465 nested_shape
1466 .sub_width(1)
1467 .max_width_error(nested_shape.width, expr.span)?,
1468 )?);
1469 result.push(';');
1470 if i != last {
1471 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1472 }
1473 }
1474
1475 result.push_str(&shape.indent.to_string_with_newline(context.config));
1476 result.push('}');
1477
1478 Ok(result)
1479}
1480
1481fn rewrite_macro_with_items(
1482 context: &RewriteContext<'_>,
1483 items: &[MacroArg],
1484 macro_name: &str,
1485 shape: Shape,
1486 style: Delimiter,
1487 original_style: Delimiter,
1488 position: MacroPosition,
1489 span: Span,
1490) -> RewriteResult {
1491 let style_to_delims = |style| match style {
1492 Delimiter::Parenthesis => Ok(("(", ")")),
1493 Delimiter::Bracket => Ok(("[", "]")),
1494 Delimiter::Brace => Ok((" {", "}")),
1495 _ => Err(RewriteError::Unknown),
1496 };
1497
1498 let (opener, closer) = style_to_delims(style)?;
1499 let (original_opener, _) = style_to_delims(original_style)?;
1500 let trailing_semicolon = match style {
1501 Delimiter::Parenthesis | Delimiter::Bracket if position == MacroPosition::Item => ";",
1502 _ => "",
1503 };
1504
1505 let mut visitor = FmtVisitor::from_context(context);
1506 visitor.block_indent = shape.indent.block_indent(context.config);
1507
1508 visitor.last_pos = context
1512 .snippet_provider
1513 .span_after(span, original_opener.trim());
1514 for item in items {
1515 let item = match item {
1516 MacroArg::Item(item) => item,
1517 _ => return Err(RewriteError::Unknown),
1518 };
1519 visitor.visit_item(item);
1520 }
1521
1522 let mut result = String::with_capacity(256);
1523 result.push_str(macro_name);
1524 result.push_str(opener);
1525 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1526 result.push_str(visitor.buffer.trim());
1527 result.push_str(&shape.indent.to_string_with_newline(context.config));
1528 result.push_str(closer);
1529 result.push_str(trailing_semicolon);
1530 Ok(result)
1531}