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
9 // List-like invocations with parentheses will be formatted as function calls,
10 // and those with brackets will be formatted as array literals.
12 use std::collections::HashMap;
13 use std::panic::{catch_unwind, AssertUnwindSafe};
15 use rustc_ast::token::{BinOpToken, DelimToken, Token, TokenKind};
16 use rustc_ast::tokenstream::{Cursor, Spacing, TokenStream, TokenTree};
17 use rustc_ast::{ast, ptr};
18 use rustc_ast_pretty::pprust;
21 BytePos, Span, Symbol, DUMMY_SP,
25 contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
27 use crate::config::lists::*;
28 use crate::expr::{rewrite_array, rewrite_assign_rhs, RhsAssignKind};
29 use crate::lists::{itemize_list, write_list, ListFormatting};
31 use crate::parse::macros::lazy_static::parse_lazy_static;
32 use crate::parse::macros::{parse_expr, parse_macro_args, ParsedMacroArgs};
33 use crate::rewrite::{Rewrite, RewriteContext};
34 use crate::shape::{Indent, Shape};
35 use crate::source_map::SpanUtils;
36 use crate::spanned::Spanned;
38 format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
39 rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
41 use crate::visitor::FmtVisitor;
43 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 pub(crate) enum MacroPosition {
54 pub(crate) enum MacroArg {
55 Expr(ptr::P<ast::Expr>),
57 Pat(ptr::P<ast::Pat>),
58 Item(ptr::P<ast::Item>),
59 Keyword(symbol::Ident, Span),
63 pub(crate) fn is_item(&self) -> bool {
65 MacroArg::Item(..) => true,
71 impl Rewrite for ast::Item {
72 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
73 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
74 visitor.block_indent = shape.indent;
75 visitor.last_pos = self.span().lo();
76 visitor.visit_item(self);
77 Some(visitor.buffer.to_owned())
81 impl Rewrite for MacroArg {
82 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
84 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
85 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
86 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
87 MacroArg::Item(ref item) => item.rewrite(context, shape),
88 MacroArg::Keyword(ident, _) => Some(ident.name.to_string()),
93 /// Rewrite macro name without using pretty-printer if possible.
94 fn rewrite_macro_name(
95 context: &RewriteContext<'_>,
97 extra_ident: Option<symbol::Ident>,
99 let name = if path.segments.len() == 1 {
100 // Avoid using pretty-printer in the common case.
101 format!("{}!", rewrite_ident(context, path.segments[0].ident))
103 format!("{}!", pprust::path_to_string(path))
106 Some(ident) if ident.name != kw::Empty => format!("{} {}", name, ident),
111 // Use this on failing to format the macro call.
112 fn return_macro_parse_failure_fallback(
113 context: &RewriteContext<'_>,
116 ) -> Option<String> {
117 // Mark this as a failure however we format it
118 context.macro_rewrite_failure.replace(true);
120 // Heuristically determine whether the last line of the macro uses "Block" style
121 // rather than using "Visual" style, or another indentation style.
122 let is_like_block_indent_style = context
126 .map(|closing_line| {
130 .all(|ch| matches!(ch, '}' | ')' | ']'))
133 if is_like_block_indent_style {
134 return trim_left_preserve_layout(context.snippet(span), indent, context.config);
137 context.skipped_range.borrow_mut().push((
138 context.parse_sess.line_of_byte_pos(span.lo()),
139 context.parse_sess.line_of_byte_pos(span.hi()),
142 // Return the snippet unmodified if the macro is not block-like
143 Some(context.snippet(span).to_owned())
146 pub(crate) fn rewrite_macro(
148 extra_ident: Option<symbol::Ident>,
149 context: &RewriteContext<'_>,
151 position: MacroPosition,
152 ) -> Option<String> {
153 let should_skip = context
155 .skip_macro(&context.snippet(mac.path.span).to_owned());
159 let guard = context.enter_macro();
160 let result = catch_unwind(AssertUnwindSafe(|| {
171 Err(..) | Ok(None) => {
172 context.macro_rewrite_failure.replace(true);
180 fn rewrite_macro_inner(
182 extra_ident: Option<symbol::Ident>,
183 context: &RewriteContext<'_>,
185 position: MacroPosition,
186 is_nested_macro: bool,
187 ) -> Option<String> {
188 if context.config.use_try_shorthand() {
189 if let Some(expr) = convert_try_mac(mac, context) {
190 context.leave_macro();
191 return expr.rewrite(context, shape);
195 let original_style = macro_style(mac, context);
197 let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
198 let is_forced_bracket = FORCED_BRACKET_MACROS.contains(&¯o_name[..]);
200 let style = if is_forced_bracket && !is_nested_macro {
206 let ts = mac.args.inner_tokens();
207 let has_comment = contains_comment(context.snippet(mac.span()));
208 if ts.is_empty() && !has_comment {
210 DelimToken::Paren if position == MacroPosition::Item => {
211 Some(format!("{}();", macro_name))
213 DelimToken::Bracket if position == MacroPosition::Item => {
214 Some(format!("{}[];", macro_name))
216 DelimToken::Paren => Some(format!("{}()", macro_name)),
217 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
218 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
222 // Format well-known macros which cannot be parsed as a valid AST.
223 if macro_name == "lazy_static!" && !has_comment {
224 if let success @ Some(..) = format_lazy_static(context, shape, ts.trees().collect()) {
229 let ParsedMacroArgs {
233 } = match parse_macro_args(context, ts, style, is_forced_bracket) {
236 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
240 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
241 return rewrite_macro_with_items(
253 DelimToken::Paren => {
254 // Handle special case: `vec!(expr; expr)`
256 handle_vec_semi(context, shape, arg_vec, macro_name, style)
258 // Format macro invocation as function call, preserve the trailing
259 // comma because not all macros support them.
260 overflow::rewrite_with_parens(
266 context.config.fn_call_width(),
268 Some(SeparatorTactic::Always)
270 Some(SeparatorTactic::Never)
273 .map(|rw| match position {
274 MacroPosition::Item => format!("{};", rw),
279 DelimToken::Bracket => {
280 // Handle special case: `vec![expr; expr]`
282 handle_vec_semi(context, shape, arg_vec, macro_name, style)
284 // If we are rewriting `vec!` macro or other special macros,
285 // then we can rewrite this as a usual array literal.
286 // Otherwise, we must preserve the original existence of trailing comma.
287 let macro_name = ¯o_name.as_str();
288 let mut force_trailing_comma = if trailing_comma {
289 Some(SeparatorTactic::Always)
291 Some(SeparatorTactic::Never)
293 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
294 context.leave_macro();
295 if context.use_block_indent() {
296 force_trailing_comma = Some(SeparatorTactic::Vertical);
299 let rewrite = rewrite_array(
305 force_trailing_comma,
306 Some(original_style),
308 let comma = match position {
309 MacroPosition::Item => ";",
313 Some(format!("{}{}", rewrite, comma))
316 DelimToken::Brace => {
317 // For macro invocations with braces, always put a space between
318 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
319 // anything in between the braces (for now).
320 let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
321 match trim_left_preserve_layout(snippet, shape.indent, context.config) {
322 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
323 None => Some(format!("{} {}", macro_name, snippet)),
331 context: &RewriteContext<'_>,
333 arg_vec: Vec<MacroArg>,
335 delim_token: DelimToken,
336 ) -> Option<String> {
337 let (left, right) = match delim_token {
338 DelimToken::Paren => ("(", ")"),
339 DelimToken::Bracket => ("[", "]"),
343 let mac_shape = shape.offset_left(macro_name.len())?;
344 // 8 = `vec![]` + `; ` or `vec!()` + `; `
345 let total_overhead = 8;
346 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
347 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
348 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
349 if !lhs.contains('\n')
350 && !rhs.contains('\n')
351 && lhs.len() + rhs.len() + total_overhead <= shape.width
353 // macro_name(lhs; rhs) or macro_name[lhs; rhs]
354 Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right))
356 // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
361 nested_shape.indent.to_string_with_newline(context.config),
363 nested_shape.indent.to_string_with_newline(context.config),
365 shape.indent.to_string_with_newline(context.config),
371 pub(crate) fn rewrite_macro_def(
372 context: &RewriteContext<'_>,
376 ident: symbol::Ident,
377 vis: &ast::Visibility,
379 ) -> Option<String> {
380 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
381 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
385 let ts = def.body.inner_tokens();
386 let mut parser = MacroParser::new(ts.into_trees());
387 let parsed_def = match parser.parse() {
389 None => return snippet,
392 let mut result = if def.macro_rules {
393 String::from("macro_rules!")
395 format!("{}macro", format_visibility(context, vis))
399 result += rewrite_ident(context, ident);
401 let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1;
403 let arm_shape = if multi_branch_style {
405 .block_indent(context.config.tab_spaces())
406 .with_max_width(context.config)
411 let branch_items = itemize_list(
412 context.snippet_provider,
413 parsed_def.branches.iter(),
416 |branch| branch.span.lo(),
417 |branch| branch.span.hi(),
418 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
420 // if the rewrite returned None because a macro could not be rewritten, then return the
422 None if context.macro_rewrite_failure.get() => {
423 Some(context.snippet(branch.body).trim().to_string())
427 context.snippet_provider.span_after(span, "{"),
431 .collect::<Vec<_>>();
433 let fmt = ListFormatting::new(arm_shape, context.config)
434 .separator(if def.macro_rules { ";" } else { "" })
435 .trailing_separator(SeparatorTactic::Always)
436 .preserve_newline(true);
438 if multi_branch_style {
440 result += &arm_shape.indent.to_string_with_newline(context.config);
443 match write_list(&branch_items, &fmt) {
444 Some(ref s) => result += s,
445 None => return snippet,
448 if multi_branch_style {
449 result += &indent.to_string_with_newline(context.config);
456 fn register_metavariable(
457 map: &mut HashMap<String, String>,
462 let mut new_name = "$".repeat(dollar_count - 1);
463 let mut old_name = "$".repeat(dollar_count);
466 new_name.push_str(name);
467 old_name.push_str(name);
469 result.push_str(&new_name);
470 map.insert(old_name, new_name);
473 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
474 // aren't causing problems.
475 // This should also work for escaped `$` variables, where we leave earlier `$`s.
476 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
477 // Each substitution will require five or six extra bytes.
478 let mut result = String::with_capacity(input.len() + 64);
479 let mut substs = HashMap::new();
480 let mut dollar_count = 0;
481 let mut cur_name = String::new();
483 for (kind, c) in CharClasses::new(input.chars()) {
484 if kind != FullCodeCharKind::Normal {
488 } else if dollar_count == 0 {
490 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
491 // Terminates a name following one or more dollars.
492 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
497 } else if c == '(' && cur_name.is_empty() {
498 // FIXME: Support macro def with repeat.
500 } else if c.is_alphanumeric() || c == '_' {
505 if !cur_name.is_empty() {
506 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
509 debug!("replace_names `{}` {:?}", result, substs);
511 Some((result, substs))
514 #[derive(Debug, Clone)]
516 /// e.g., `$x: expr`.
517 MetaVariable(Symbol, String),
518 /// e.g., `$($foo: expr),*`
520 /// `()`, `[]` or `{}`.
522 /// Inner arguments inside delimiters.
524 /// Something after the closing delimiter and the repeat token, if available.
525 Option<Box<ParsedMacroArg>>,
526 /// The repeat token. This could be one of `*`, `+` or `?`.
529 /// e.g., `[derive(Debug)]`
530 Delimited(DelimToken, Vec<ParsedMacroArg>),
531 /// A possible separator. e.g., `,` or `;`.
532 Separator(String, String),
533 /// Other random stuff that does not fit to other kinds.
534 /// e.g., `== foo` in `($x: expr == foo)`.
535 Other(String, String),
538 fn delim_token_to_str(
539 context: &RewriteContext<'_>,
540 delim_token: DelimToken,
542 use_multiple_lines: bool,
543 inner_is_empty: bool,
544 ) -> (String, String) {
545 let (lhs, rhs) = match delim_token {
546 DelimToken::Paren => ("(", ")"),
547 DelimToken::Bracket => ("[", "]"),
548 DelimToken::Brace => {
549 if inner_is_empty || use_multiple_lines {
555 DelimToken::NoDelim => ("", ""),
557 if use_multiple_lines {
558 let indent_str = shape.indent.to_string_with_newline(context.config);
559 let nested_indent_str = shape
561 .block_indent(context.config)
562 .to_string_with_newline(context.config);
564 format!("{}{}", lhs, nested_indent_str),
565 format!("{}{}", indent_str, rhs),
568 (lhs.to_owned(), rhs.to_owned())
573 fn starts_with_brace(&self) -> bool {
576 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
577 | MacroArgKind::Delimited(DelimToken::Brace, _)
581 fn starts_with_dollar(&self) -> bool {
584 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..)
588 fn ends_with_space(&self) -> bool {
589 matches!(*self, MacroArgKind::Separator(..))
592 fn has_meta_var(&self) -> bool {
594 MacroArgKind::MetaVariable(..) => true,
595 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
602 context: &RewriteContext<'_>,
604 use_multiple_lines: bool,
605 ) -> Option<String> {
606 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
607 let inner = wrap_macro_args(context, args, shape)?;
608 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
609 if lhs.len() + inner.len() + rhs.len() <= shape.width {
610 return Some((lhs, inner, rhs));
613 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
614 let nested_shape = shape
615 .block_indent(context.config.tab_spaces())
616 .with_max_width(context.config);
617 let inner = wrap_macro_args(context, args, nested_shape)?;
618 Some((lhs, inner, rhs))
622 MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)),
623 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
624 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
625 let another = another
627 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
628 .unwrap_or_else(|| "".to_owned());
629 let repeat_tok = pprust::token_to_string(tok);
631 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
633 MacroArgKind::Delimited(delim_tok, ref args) => {
634 rewrite_delimited_inner(delim_tok, args)
635 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
637 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
638 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
643 #[derive(Debug, Clone)]
644 struct ParsedMacroArg {
648 impl ParsedMacroArg {
651 context: &RewriteContext<'_>,
653 use_multiple_lines: bool,
654 ) -> Option<String> {
655 self.kind.rewrite(context, shape, use_multiple_lines)
659 /// Parses macro arguments on macro def.
660 struct MacroArgParser {
661 /// Either a name of the next metavariable, a separator, or junk.
663 /// The first token of the current buffer.
665 /// `true` if we are parsing a metavariable or a repeat.
667 /// The last token parsed.
669 /// Holds the parsed arguments.
670 result: Vec<ParsedMacroArg>,
673 fn last_tok(tt: &TokenTree) -> Token {
675 TokenTree::Token(ref t) => t.clone(),
676 TokenTree::Delimited(delim_span, delim, _) => Token {
677 kind: TokenKind::CloseDelim(delim),
678 span: delim_span.close,
683 impl MacroArgParser {
684 fn new() -> MacroArgParser {
689 kind: TokenKind::Eof,
693 kind: TokenKind::Eof,
700 fn set_last_tok(&mut self, tok: &TokenTree) {
701 self.last_tok = last_tok(tok);
704 fn add_separator(&mut self) {
705 let prefix = if self.need_space_prefix() {
710 self.result.push(ParsedMacroArg {
711 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
716 fn add_other(&mut self) {
717 let prefix = if self.need_space_prefix() {
722 self.result.push(ParsedMacroArg {
723 kind: MacroArgKind::Other(self.buf.clone(), prefix),
728 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
730 Some(TokenTree::Token(Token {
731 kind: TokenKind::Ident(name, _),
734 self.result.push(ParsedMacroArg {
735 kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
739 self.is_meta_var = false;
746 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken) {
747 self.result.push(ParsedMacroArg {
748 kind: MacroArgKind::Delimited(delim, inner),
755 inner: Vec<ParsedMacroArg>,
759 let mut buffer = String::new();
760 let mut first = true;
762 // Parse '*', '+' or '?.
764 self.set_last_tok(&tok);
770 TokenTree::Token(Token {
771 kind: TokenKind::BinOp(BinOpToken::Plus),
774 | TokenTree::Token(Token {
775 kind: TokenKind::Question,
778 | TokenTree::Token(Token {
779 kind: TokenKind::BinOp(BinOpToken::Star),
784 TokenTree::Token(ref t) => {
785 buffer.push_str(&pprust::token_to_string(t));
791 // There could be some random stuff between ')' and '*', '+' or '?'.
792 let another = if buffer.trim().is_empty() {
795 Some(Box::new(ParsedMacroArg {
796 kind: MacroArgKind::Other(buffer, "".to_owned()),
800 self.result.push(ParsedMacroArg {
801 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
806 fn update_buffer(&mut self, t: &Token) {
807 if self.buf.is_empty() {
808 self.start_tok = t.clone();
810 let needs_space = match next_space(&self.last_tok.kind) {
811 SpaceState::Ident => ident_like(t),
812 SpaceState::Punctuation => !ident_like(t),
813 SpaceState::Always => true,
814 SpaceState::Never => false,
816 if force_space_before(&t.kind) || needs_space {
821 self.buf.push_str(&pprust::token_to_string(t));
824 fn need_space_prefix(&self) -> bool {
825 if self.result.is_empty() {
829 let last_arg = self.result.last().unwrap();
830 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
831 if ident_like(&self.start_tok) {
834 if self.start_tok.kind == TokenKind::Colon {
839 if force_space_before(&self.start_tok.kind) {
846 /// Returns a collection of parsed macro def's arguments.
847 fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
848 let mut iter = tokens.trees();
850 while let Some(tok) = iter.next() {
852 TokenTree::Token(Token {
853 kind: TokenKind::Dollar,
856 // We always want to add a separator before meta variables.
857 if !self.buf.is_empty() {
858 self.add_separator();
861 // Start keeping the name of this metavariable in the buffer.
862 self.is_meta_var = true;
863 self.start_tok = Token {
864 kind: TokenKind::Dollar,
868 TokenTree::Token(Token {
869 kind: TokenKind::Colon,
871 }) if self.is_meta_var => {
872 self.add_meta_variable(&mut iter)?;
874 TokenTree::Token(ref t) => self.update_buffer(t),
875 TokenTree::Delimited(_delimited_span, delimited, ref tts) => {
876 if !self.buf.is_empty() {
877 if next_space(&self.last_tok.kind) == SpaceState::Always {
878 self.add_separator();
884 // Parse the stuff inside delimiters.
885 let parser = MacroArgParser::new();
886 let delimited_arg = parser.parse(tts.clone())?;
888 if self.is_meta_var {
889 self.add_repeat(delimited_arg, delimited, &mut iter)?;
890 self.is_meta_var = false;
892 self.add_delimited(delimited_arg, delimited);
897 self.set_last_tok(&tok);
900 // We are left with some stuff in the buffer. Since there is nothing
901 // left to separate, add this as `Other`.
902 if !self.buf.is_empty() {
911 context: &RewriteContext<'_>,
912 args: &[ParsedMacroArg],
914 ) -> Option<String> {
915 wrap_macro_args_inner(context, args, shape, false)
916 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
919 fn wrap_macro_args_inner(
920 context: &RewriteContext<'_>,
921 args: &[ParsedMacroArg],
923 use_multiple_lines: bool,
924 ) -> Option<String> {
925 let mut result = String::with_capacity(128);
926 let mut iter = args.iter().peekable();
927 let indent_str = shape.indent.to_string_with_newline(context.config);
929 while let Some(arg) = iter.next() {
930 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
932 if use_multiple_lines
933 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
935 if arg.kind.ends_with_space() {
938 result.push_str(&indent_str);
939 } else if let Some(next_arg) = iter.peek() {
940 let space_before_dollar =
941 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
942 let space_before_brace = next_arg.kind.starts_with_brace();
943 if space_before_dollar || space_before_brace {
949 if !use_multiple_lines && result.len() >= shape.width {
956 // This is a bit sketchy. The token rules probably need tweaking, but it works
957 // for some common cases. I hope the basic logic is sufficient. Note that the
958 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
959 // and `(`/`)` have special meaning.
961 // We always try and format on one line.
962 // FIXME: Use multi-line when every thing does not fit on one line.
963 fn format_macro_args(
964 context: &RewriteContext<'_>,
965 token_stream: TokenStream,
967 ) -> Option<String> {
968 if !context.config.format_macro_matchers() {
969 let span = span_for_token_stream(&token_stream);
970 return Some(match span {
971 Some(span) => context.snippet(span).to_owned(),
972 None => String::new(),
975 let parsed_args = MacroArgParser::new().parse(token_stream)?;
976 wrap_macro_args(context, &parsed_args, shape)
979 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
980 token_stream.trees().next().map(|tt| tt.span())
983 // We should insert a space if the next token is a:
984 #[derive(Copy, Clone, PartialEq)]
988 Ident, // Or ident/literal-like thing.
992 fn force_space_before(tok: &TokenKind) -> bool {
993 debug!("tok: force_space_before {:?}", tok);
1007 | TokenKind::BinOpEq(_)
1011 | TokenKind::FatArrow
1012 | TokenKind::BinOp(_)
1014 | TokenKind::Dollar => true,
1019 fn ident_like(tok: &Token) -> bool {
1022 TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_)
1026 fn next_space(tok: &TokenKind) -> SpaceState {
1027 debug!("next_space: {:?}", tok);
1031 | TokenKind::BinOp(BinOpToken::And)
1037 | TokenKind::DotDotDot
1038 | TokenKind::DotDotEq
1039 | TokenKind::Question => SpaceState::Punctuation,
1044 | TokenKind::OpenDelim(_)
1045 | TokenKind::CloseDelim(_) => SpaceState::Never,
1047 TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(_) => SpaceState::Ident,
1049 _ => SpaceState::Always,
1053 /// Tries to convert a macro use into a short hand try expression. Returns `None`
1054 /// when the macro is not an instance of `try!` (or parsing the inner expression
1056 pub(crate) fn convert_try_mac(
1058 context: &RewriteContext<'_>,
1059 ) -> Option<ast::Expr> {
1060 let path = &pprust::path_to_string(&mac.path);
1061 if path == "try" || path == "r#try" {
1062 let ts = mac.args.inner_tokens();
1065 id: ast::NodeId::root(), // dummy value
1066 kind: ast::ExprKind::Try(parse_expr(context, ts)?),
1067 span: mac.span(), // incorrect span, but shouldn't matter too much
1068 attrs: ast::AttrVec::new(),
1076 pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> DelimToken {
1077 let snippet = context.snippet(mac.span());
1078 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1079 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1080 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1082 if paren_pos < bracket_pos && paren_pos < brace_pos {
1084 } else if bracket_pos < brace_pos {
1091 // A very simple parser that just parses a macros 2.0 definition into its branches.
1092 // Currently we do not attempt to parse any further than that.
1094 struct MacroParser {
1099 // (`(` ... `)` `=>` `{` ... `}`)*
1100 fn parse(&mut self) -> Option<Macro> {
1101 let mut branches = vec![];
1102 while self.toks.look_ahead(1).is_some() {
1103 branches.push(self.parse_branch()?);
1106 Some(Macro { branches })
1109 // `(` ... `)` `=>` `{` ... `}`
1110 fn parse_branch(&mut self) -> Option<MacroBranch> {
1111 let tok = self.toks.next()?;
1112 let (lo, args_paren_kind) = match tok {
1113 TokenTree::Token(..) => return None,
1114 TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1116 let args = TokenStream::new(vec![(tok, Spacing::Joint)]);
1117 match self.toks.next()? {
1118 TokenTree::Token(Token {
1119 kind: TokenKind::FatArrow,
1124 let (mut hi, body, whole_body) = match self.toks.next()? {
1125 TokenTree::Token(..) => return None,
1126 TokenTree::Delimited(delimited_span, ..) => {
1127 let data = delimited_span.entire().data();
1131 data.lo + BytePos(1),
1132 data.hi - BytePos(1),
1136 delimited_span.entire(),
1140 if let Some(TokenTree::Token(Token {
1141 kind: TokenKind::Semi,
1143 })) = self.toks.look_ahead(0)
1149 span: mk_sp(lo, hi),
1158 // A parsed macros 2.0 macro definition.
1160 branches: Vec<MacroBranch>,
1163 // FIXME: it would be more efficient to use references to the token streams
1164 // rather than clone them, if we can make the borrowing work out.
1165 struct MacroBranch {
1167 args_paren_kind: DelimToken,
1176 context: &RewriteContext<'_>,
1178 multi_branch_style: bool,
1179 ) -> Option<String> {
1180 // Only attempt to format function-like macros.
1181 if self.args_paren_kind != DelimToken::Paren {
1182 // FIXME(#1539): implement for non-sugared macros.
1187 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1189 if multi_branch_style {
1193 if !context.config.format_macro_bodies() {
1195 result += context.snippet(self.whole_body);
1196 return Some(result);
1199 // The macro body is the most interesting part. It might end up as various
1200 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1201 // parsed as regular Rust code (and note that these can be escaped using
1202 // `$$`). We'll try and format like an AST node, but we'll substitute
1203 // variables for new names with the same length first.
1205 let old_body = context.snippet(self.body).trim();
1206 let (body_str, substs) = replace_names(old_body)?;
1207 let has_block_body = old_body.starts_with('{');
1209 let mut config = context.config.clone();
1210 config.set().hide_parse_errors(true);
1214 let body_indent = if has_block_body {
1217 shape.indent.block_indent(&config)
1219 let new_width = config.max_width() - body_indent.width();
1220 config.set().max_width(new_width);
1222 // First try to format as items, then as statements.
1223 let new_body_snippet = match crate::format_snippet(&body_str, &config, true) {
1224 Some(new_body) => new_body,
1226 let new_width = new_width + config.tab_spaces();
1227 config.set().max_width(new_width);
1228 match crate::format_code_block(&body_str, &config, true) {
1229 Some(new_body) => new_body,
1230 None => return None,
1234 let new_body = wrap_str(
1235 new_body_snippet.snippet.to_string(),
1240 // Indent the body since it is in a block.
1241 let indent_str = body_indent.to_string(&config);
1242 let mut new_body = LineClasses::new(new_body.trim_end())
1245 (String::new(), true),
1246 |(mut s, need_indent), (i, (kind, ref l))| {
1247 if !is_empty_line(l)
1249 && !new_body_snippet.is_line_non_formatted(i + 1)
1253 (s + l + "\n", indent_next_line(kind, l, &config))
1258 // Undo our replacement of macro variables.
1259 // FIXME: this could be *much* more efficient.
1260 for (old, new) in &substs {
1261 if old_body.contains(new) {
1262 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1265 new_body = new_body.replace(new, old);
1269 result += new_body.trim();
1270 } else if !new_body.is_empty() {
1272 result += &new_body;
1273 result += &shape.indent.to_string(&config);
1282 /// Format `lazy_static!` from <https://crates.io/crates/lazy_static>.
1284 /// # Expected syntax
1288 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1289 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1291 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1294 fn format_lazy_static(
1295 context: &RewriteContext<'_>,
1298 ) -> Option<String> {
1299 let mut result = String::with_capacity(1024);
1300 let nested_shape = shape
1301 .block_indent(context.config.tab_spaces())
1302 .with_max_width(context.config);
1304 result.push_str("lazy_static! {");
1305 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1307 let parsed_elems = parse_lazy_static(context, ts)?;
1308 let last = parsed_elems.len() - 1;
1309 for (i, (vis, id, ty, expr)) in parsed_elems.iter().enumerate() {
1310 // Rewrite as a static item.
1311 let vis = crate::utils::format_visibility(context, vis);
1312 let mut stmt = String::with_capacity(128);
1313 stmt.push_str(&format!(
1314 "{}static ref {}: {} =",
1317 ty.rewrite(context, nested_shape)?
1319 result.push_str(&rewrite_assign_rhs(
1323 &RhsAssignKind::Expr(&expr.kind, expr.span),
1324 nested_shape.sub_width(1)?,
1328 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1332 result.push_str(&shape.indent.to_string_with_newline(context.config));
1338 fn rewrite_macro_with_items(
1339 context: &RewriteContext<'_>,
1344 position: MacroPosition,
1346 ) -> Option<String> {
1347 let (opener, closer) = match style {
1348 DelimToken::Paren => ("(", ")"),
1349 DelimToken::Bracket => ("[", "]"),
1350 DelimToken::Brace => (" {", "}"),
1353 let trailing_semicolon = match style {
1354 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1358 let mut visitor = FmtVisitor::from_context(context);
1359 visitor.block_indent = shape.indent.block_indent(context.config);
1360 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1362 let item = match item {
1363 MacroArg::Item(item) => item,
1366 visitor.visit_item(item);
1369 let mut result = String::with_capacity(256);
1370 result.push_str(macro_name);
1371 result.push_str(opener);
1372 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1373 result.push_str(visitor.buffer.trim());
1374 result.push_str(&shape.indent.to_string_with_newline(context.config));
1375 result.push_str(closer);
1376 result.push_str(trailing_semicolon);