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, TokenStream, TokenTree};
17 use rustc_ast::{ast, ptr};
18 use rustc_ast_pretty::pprust;
19 use rustc_parse::{new_parser_from_tts, parser::Parser};
22 BytePos, Span, Symbol, DUMMY_SP,
26 contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
28 use crate::config::lists::*;
29 use crate::expr::rewrite_array;
30 use crate::lists::{itemize_list, write_list, ListFormatting};
32 use crate::rewrite::{Rewrite, RewriteContext};
33 use crate::shape::{Indent, Shape};
34 use crate::source_map::SpanUtils;
35 use crate::spanned::Spanned;
37 format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
38 rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
40 use crate::visitor::FmtVisitor;
42 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub(crate) enum MacroPosition {
53 pub(crate) enum MacroArg {
54 Expr(ptr::P<ast::Expr>),
56 Pat(ptr::P<ast::Pat>),
57 Item(ptr::P<ast::Item>),
58 Keyword(symbol::Ident, Span),
62 fn is_item(&self) -> bool {
64 MacroArg::Item(..) => true,
70 impl Rewrite for ast::Item {
71 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
72 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
73 visitor.block_indent = shape.indent;
74 visitor.last_pos = self.span().lo();
75 visitor.visit_item(self);
76 Some(visitor.buffer.to_owned())
80 impl Rewrite for MacroArg {
81 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
83 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
84 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
85 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
86 MacroArg::Item(ref item) => item.rewrite(context, shape),
87 MacroArg::Keyword(ident, _) => Some(ident.name.to_string()),
92 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
93 macro_rules! parse_macro_arg {
94 ($macro_arg:ident, $parser:expr, $f:expr) => {
95 let mut cloned_parser = (*parser).clone();
96 match $parser(&mut cloned_parser) {
98 if parser.sess.span_diagnostic.has_errors() {
99 parser.sess.span_diagnostic.reset_err_count();
101 // Parsing succeeded.
102 *parser = cloned_parser;
103 return Some(MacroArg::$macro_arg($f(x)?));
108 parser.sess.span_diagnostic.reset_err_count();
116 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(),
117 |x: ptr::P<ast::Expr>| Some(x)
121 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(),
122 |x: ptr::P<ast::Ty>| Some(x)
126 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat(None),
127 |x: ptr::P<ast::Pat>| Some(x)
129 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
132 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_item(),
133 |x: Option<ptr::P<ast::Item>>| x
139 /// Rewrite macro name without using pretty-printer if possible.
140 fn rewrite_macro_name(
141 context: &RewriteContext<'_>,
143 extra_ident: Option<symbol::Ident>,
145 let name = if path.segments.len() == 1 {
146 // Avoid using pretty-printer in the common case.
147 format!("{}!", rewrite_ident(context, path.segments[0].ident))
149 format!("{}!", pprust::path_to_string(path))
152 Some(ident) if ident.name != kw::Invalid => format!("{} {}", name, ident),
157 // Use this on failing to format the macro call.
158 fn return_macro_parse_failure_fallback(
159 context: &RewriteContext<'_>,
162 ) -> Option<String> {
163 // Mark this as a failure however we format it
164 context.macro_rewrite_failure.replace(true);
166 // Heuristically determine whether the last line of the macro uses "Block" style
167 // rather than using "Visual" style, or another indentation style.
168 let is_like_block_indent_style = context
172 .map(|closing_line| {
173 closing_line.trim().chars().all(|ch| match ch {
174 '}' | ')' | ']' => true,
179 if is_like_block_indent_style {
180 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
183 context.skipped_range.borrow_mut().push((
184 context.parse_sess.line_of_byte_pos(span.lo()),
185 context.parse_sess.line_of_byte_pos(span.hi()),
188 // Return the snippet unmodified if the macro is not block-like
189 Some(context.snippet(span).to_owned())
192 pub(crate) fn rewrite_macro(
194 extra_ident: Option<symbol::Ident>,
195 context: &RewriteContext<'_>,
197 position: MacroPosition,
198 ) -> Option<String> {
199 let should_skip = context
201 .skip_macro(&context.snippet(mac.path.span).to_owned());
205 let guard = context.enter_macro();
206 let result = catch_unwind(AssertUnwindSafe(|| {
217 Err(..) | Ok(None) => {
218 context.macro_rewrite_failure.replace(true);
226 fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
227 for &keyword in RUST_KW.iter() {
228 if parser.token.is_keyword(keyword)
229 && parser.look_ahead(1, |t| {
230 t.kind == TokenKind::Eof
231 || t.kind == TokenKind::Comma
232 || t.kind == TokenKind::CloseDelim(DelimToken::NoDelim)
236 return Some(MacroArg::Keyword(
237 symbol::Ident::with_dummy_span(keyword),
238 parser.prev_token.span,
245 fn rewrite_macro_inner(
247 extra_ident: Option<symbol::Ident>,
248 context: &RewriteContext<'_>,
250 position: MacroPosition,
251 is_nested_macro: bool,
252 ) -> Option<String> {
253 if context.config.use_try_shorthand() {
254 if let Some(expr) = convert_try_mac(mac, context) {
255 context.leave_macro();
256 return expr.rewrite(context, shape);
260 let original_style = macro_style(mac, context);
262 let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
264 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
270 let ts = mac.args.inner_tokens();
271 let has_comment = contains_comment(context.snippet(mac.span()));
272 if ts.is_empty() && !has_comment {
274 DelimToken::Paren if position == MacroPosition::Item => {
275 Some(format!("{}();", macro_name))
277 DelimToken::Bracket if position == MacroPosition::Item => {
278 Some(format!("{}[];", macro_name))
280 DelimToken::Paren => Some(format!("{}()", macro_name)),
281 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
282 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
286 // Format well-known macros which cannot be parsed as a valid AST.
287 if macro_name == "lazy_static!" && !has_comment {
288 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
293 let mut parser = new_parser_from_tts(context.parse_sess.inner(), ts.trees().collect());
294 let mut arg_vec = Vec::new();
295 let mut vec_with_semi = false;
296 let mut trailing_comma = false;
298 if DelimToken::Brace != style {
300 if let Some(arg) = check_keyword(&mut parser) {
302 } else if let Some(arg) = parse_macro_arg(&mut parser) {
305 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
308 match parser.token.kind {
309 TokenKind::Eof => break,
310 TokenKind::Comma => (),
312 // Try to parse `vec![expr; expr]`
313 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
315 if parser.token.kind != TokenKind::Eof {
316 match parse_macro_arg(&mut parser) {
320 if parser.token.kind == TokenKind::Eof && arg_vec.len() == 2 {
321 vec_with_semi = true;
326 return return_macro_parse_failure_fallback(
335 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
337 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
338 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span()),
343 if parser.token.kind == TokenKind::Eof {
344 trailing_comma = true;
350 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
351 return rewrite_macro_with_items(
363 DelimToken::Paren => {
364 // Handle special case: `vec!(expr; expr)`
366 handle_vec_semi(context, shape, arg_vec, macro_name, style)
368 // Format macro invocation as function call, preserve the trailing
369 // comma because not all macros support them.
370 overflow::rewrite_with_parens(
376 context.config.width_heuristics().fn_call_width,
378 Some(SeparatorTactic::Always)
380 Some(SeparatorTactic::Never)
383 .map(|rw| match position {
384 MacroPosition::Item => format!("{};", rw),
389 DelimToken::Bracket => {
390 // Handle special case: `vec![expr; expr]`
392 handle_vec_semi(context, shape, arg_vec, macro_name, style)
394 // If we are rewriting `vec!` macro or other special macros,
395 // then we can rewrite this as an usual array literal.
396 // Otherwise, we must preserve the original existence of trailing comma.
397 let macro_name = ¯o_name.as_str();
398 let mut force_trailing_comma = if trailing_comma {
399 Some(SeparatorTactic::Always)
401 Some(SeparatorTactic::Never)
403 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
404 context.leave_macro();
405 if context.use_block_indent() {
406 force_trailing_comma = Some(SeparatorTactic::Vertical);
409 let rewrite = rewrite_array(
415 force_trailing_comma,
416 Some(original_style),
418 let comma = match position {
419 MacroPosition::Item => ";",
423 Some(format!("{}{}", rewrite, comma))
426 DelimToken::Brace => {
427 // For macro invocations with braces, always put a space between
428 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
429 // anything in between the braces (for now).
430 let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
431 match trim_left_preserve_layout(snippet, shape.indent, &context.config) {
432 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
433 None => Some(format!("{} {}", macro_name, snippet)),
441 context: &RewriteContext<'_>,
443 arg_vec: Vec<MacroArg>,
445 delim_token: DelimToken,
446 ) -> Option<String> {
447 let (left, right) = match delim_token {
448 DelimToken::Paren => ("(", ")"),
449 DelimToken::Bracket => ("[", "]"),
453 let mac_shape = shape.offset_left(macro_name.len())?;
454 // 8 = `vec![]` + `; ` or `vec!()` + `; `
455 let total_overhead = 8;
456 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
457 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
458 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
459 if !lhs.contains('\n')
460 && !rhs.contains('\n')
461 && lhs.len() + rhs.len() + total_overhead <= shape.width
463 // macro_name(lhs; rhs) or macro_name[lhs; rhs]
464 Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right))
466 // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
471 nested_shape.indent.to_string_with_newline(context.config),
473 nested_shape.indent.to_string_with_newline(context.config),
475 shape.indent.to_string_with_newline(context.config),
481 pub(crate) fn rewrite_macro_def(
482 context: &RewriteContext<'_>,
486 ident: symbol::Ident,
487 vis: &ast::Visibility,
489 ) -> Option<String> {
490 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
491 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
495 let ts = def.body.inner_tokens();
496 let mut parser = MacroParser::new(ts.into_trees());
497 let parsed_def = match parser.parse() {
499 None => return snippet,
502 let mut result = if def.macro_rules {
503 String::from("macro_rules!")
505 format!("{}macro", format_visibility(context, vis))
509 result += rewrite_ident(context, ident);
511 let multi_branch_style = def.macro_rules || parsed_def.branches.len() != 1;
513 let arm_shape = if multi_branch_style {
515 .block_indent(context.config.tab_spaces())
516 .with_max_width(context.config)
521 let branch_items = itemize_list(
522 context.snippet_provider,
523 parsed_def.branches.iter(),
526 |branch| branch.span.lo(),
527 |branch| branch.span.hi(),
528 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
530 // if the rewrite returned None because a macro could not be rewritten, then return the
532 None if context.macro_rewrite_failure.get() => {
533 Some(context.snippet(branch.body).trim().to_string())
537 context.snippet_provider.span_after(span, "{"),
541 .collect::<Vec<_>>();
543 let fmt = ListFormatting::new(arm_shape, context.config)
544 .separator(if def.macro_rules { ";" } else { "" })
545 .trailing_separator(SeparatorTactic::Always)
546 .preserve_newline(true);
548 if multi_branch_style {
550 result += &arm_shape.indent.to_string_with_newline(context.config);
553 match write_list(&branch_items, &fmt) {
554 Some(ref s) => result += s,
555 None => return snippet,
558 if multi_branch_style {
559 result += &indent.to_string_with_newline(context.config);
566 fn register_metavariable(
567 map: &mut HashMap<String, String>,
572 let mut new_name = "$".repeat(dollar_count - 1);
573 let mut old_name = "$".repeat(dollar_count);
576 new_name.push_str(name);
577 old_name.push_str(name);
579 result.push_str(&new_name);
580 map.insert(old_name, new_name);
583 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
584 // aren't causing problems.
585 // This should also work for escaped `$` variables, where we leave earlier `$`s.
586 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
587 // Each substitution will require five or six extra bytes.
588 let mut result = String::with_capacity(input.len() + 64);
589 let mut substs = HashMap::new();
590 let mut dollar_count = 0;
591 let mut cur_name = String::new();
593 for (kind, c) in CharClasses::new(input.chars()) {
594 if kind != FullCodeCharKind::Normal {
598 } else if dollar_count == 0 {
600 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
601 // Terminates a name following one or more dollars.
602 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
607 } else if c == '(' && cur_name.is_empty() {
608 // FIXME: Support macro def with repeat.
610 } else if c.is_alphanumeric() || c == '_' {
615 if !cur_name.is_empty() {
616 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
619 debug!("replace_names `{}` {:?}", result, substs);
621 Some((result, substs))
624 #[derive(Debug, Clone)]
626 /// e.g., `$x: expr`.
627 MetaVariable(Symbol, String),
628 /// e.g., `$($foo: expr),*`
630 /// `()`, `[]` or `{}`.
632 /// Inner arguments inside delimiters.
634 /// Something after the closing delimiter and the repeat token, if available.
635 Option<Box<ParsedMacroArg>>,
636 /// The repeat token. This could be one of `*`, `+` or `?`.
639 /// e.g., `[derive(Debug)]`
640 Delimited(DelimToken, Vec<ParsedMacroArg>),
641 /// A possible separator. e.g., `,` or `;`.
642 Separator(String, String),
643 /// Other random stuff that does not fit to other kinds.
644 /// e.g., `== foo` in `($x: expr == foo)`.
645 Other(String, String),
648 fn delim_token_to_str(
649 context: &RewriteContext<'_>,
650 delim_token: DelimToken,
652 use_multiple_lines: bool,
653 inner_is_empty: bool,
654 ) -> (String, String) {
655 let (lhs, rhs) = match delim_token {
656 DelimToken::Paren => ("(", ")"),
657 DelimToken::Bracket => ("[", "]"),
658 DelimToken::Brace => {
659 if inner_is_empty || use_multiple_lines {
665 DelimToken::NoDelim => ("", ""),
667 if use_multiple_lines {
668 let indent_str = shape.indent.to_string_with_newline(context.config);
669 let nested_indent_str = shape
671 .block_indent(context.config)
672 .to_string_with_newline(context.config);
674 format!("{}{}", lhs, nested_indent_str),
675 format!("{}{}", indent_str, rhs),
678 (lhs.to_owned(), rhs.to_owned())
683 fn starts_with_brace(&self) -> bool {
685 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
686 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
691 fn starts_with_dollar(&self) -> bool {
693 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
698 fn ends_with_space(&self) -> bool {
700 MacroArgKind::Separator(..) => true,
705 fn has_meta_var(&self) -> bool {
707 MacroArgKind::MetaVariable(..) => true,
708 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
715 context: &RewriteContext<'_>,
717 use_multiple_lines: bool,
718 ) -> Option<String> {
719 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
720 let inner = wrap_macro_args(context, args, shape)?;
721 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
722 if lhs.len() + inner.len() + rhs.len() <= shape.width {
723 return Some((lhs, inner, rhs));
726 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
727 let nested_shape = shape
728 .block_indent(context.config.tab_spaces())
729 .with_max_width(context.config);
730 let inner = wrap_macro_args(context, args, nested_shape)?;
731 Some((lhs, inner, rhs))
735 MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)),
736 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
737 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
738 let another = another
740 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
741 .unwrap_or_else(|| "".to_owned());
742 let repeat_tok = pprust::token_to_string(tok);
744 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
746 MacroArgKind::Delimited(delim_tok, ref args) => {
747 rewrite_delimited_inner(delim_tok, args)
748 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
750 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
751 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
756 #[derive(Debug, Clone)]
757 struct ParsedMacroArg {
762 impl ParsedMacroArg {
765 context: &RewriteContext<'_>,
767 use_multiple_lines: bool,
768 ) -> Option<String> {
769 self.kind.rewrite(context, shape, use_multiple_lines)
773 /// Parses macro arguments on macro def.
774 struct MacroArgParser {
775 /// Either a name of the next metavariable, a separator, or junk.
777 /// The start position on the current buffer.
779 /// The first token of the current buffer.
781 /// `true` if we are parsing a metavariable or a repeat.
783 /// The position of the last token.
785 /// The last token parsed.
787 /// Holds the parsed arguments.
788 result: Vec<ParsedMacroArg>,
791 fn last_tok(tt: &TokenTree) -> Token {
793 TokenTree::Token(ref t) => t.clone(),
794 TokenTree::Delimited(delim_span, delim, _) => Token {
795 kind: TokenKind::CloseDelim(delim),
796 span: delim_span.close,
801 impl MacroArgParser {
802 fn new() -> MacroArgParser {
809 kind: TokenKind::Eof,
813 kind: TokenKind::Eof,
820 fn set_last_tok(&mut self, tok: &TokenTree) {
821 self.hi = tok.span().hi();
822 self.last_tok = last_tok(tok);
825 fn add_separator(&mut self) {
826 let prefix = if self.need_space_prefix() {
831 self.result.push(ParsedMacroArg {
832 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
833 span: mk_sp(self.lo, self.hi),
838 fn add_other(&mut self) {
839 let prefix = if self.need_space_prefix() {
844 self.result.push(ParsedMacroArg {
845 kind: MacroArgKind::Other(self.buf.clone(), prefix),
846 span: mk_sp(self.lo, self.hi),
851 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
853 Some(TokenTree::Token(Token {
854 kind: TokenKind::Ident(name, _),
857 self.result.push(ParsedMacroArg {
858 kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
859 span: mk_sp(self.lo, span.hi()),
863 self.is_meta_var = false;
870 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
871 self.result.push(ParsedMacroArg {
872 kind: MacroArgKind::Delimited(delim, inner),
880 inner: Vec<ParsedMacroArg>,
885 let mut buffer = String::new();
886 let mut first = true;
887 let mut lo = span.lo();
888 let mut hi = span.hi();
890 // Parse '*', '+' or '?.
892 self.set_last_tok(&tok);
895 lo = tok.span().lo();
899 TokenTree::Token(Token {
900 kind: TokenKind::BinOp(BinOpToken::Plus),
903 | TokenTree::Token(Token {
904 kind: TokenKind::Question,
907 | TokenTree::Token(Token {
908 kind: TokenKind::BinOp(BinOpToken::Star),
913 TokenTree::Token(ref t) => {
914 buffer.push_str(&pprust::token_to_string(&t));
921 // There could be some random stuff between ')' and '*', '+' or '?'.
922 let another = if buffer.trim().is_empty() {
925 Some(Box::new(ParsedMacroArg {
926 kind: MacroArgKind::Other(buffer, "".to_owned()),
931 self.result.push(ParsedMacroArg {
932 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
933 span: mk_sp(self.lo, self.hi),
938 fn update_buffer(&mut self, t: &Token) {
939 if self.buf.is_empty() {
940 self.lo = t.span.lo();
941 self.start_tok = t.clone();
943 let needs_space = match next_space(&self.last_tok.kind) {
944 SpaceState::Ident => ident_like(t),
945 SpaceState::Punctuation => !ident_like(t),
946 SpaceState::Always => true,
947 SpaceState::Never => false,
949 if force_space_before(&t.kind) || needs_space {
954 self.buf.push_str(&pprust::token_to_string(t));
957 fn need_space_prefix(&self) -> bool {
958 if self.result.is_empty() {
962 let last_arg = self.result.last().unwrap();
963 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
964 if ident_like(&self.start_tok) {
967 if self.start_tok.kind == TokenKind::Colon {
972 if force_space_before(&self.start_tok.kind) {
979 /// Returns a collection of parsed macro def's arguments.
980 fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
981 let mut iter = tokens.trees();
983 while let Some(tok) = iter.next() {
985 TokenTree::Token(Token {
986 kind: TokenKind::Dollar,
989 // We always want to add a separator before meta variables.
990 if !self.buf.is_empty() {
991 self.add_separator();
994 // Start keeping the name of this metavariable in the buffer.
995 self.is_meta_var = true;
997 self.start_tok = Token {
998 kind: TokenKind::Dollar,
1002 TokenTree::Token(Token {
1003 kind: TokenKind::Colon,
1005 }) if self.is_meta_var => {
1006 self.add_meta_variable(&mut iter)?;
1008 TokenTree::Token(ref t) => self.update_buffer(t),
1009 TokenTree::Delimited(delimited_span, delimited, ref tts) => {
1010 if !self.buf.is_empty() {
1011 if next_space(&self.last_tok.kind) == SpaceState::Always {
1012 self.add_separator();
1018 // Parse the stuff inside delimiters.
1019 let mut parser = MacroArgParser::new();
1020 parser.lo = delimited_span.open.lo();
1021 let delimited_arg = parser.parse(tts.clone())?;
1023 let span = delimited_span.entire();
1024 if self.is_meta_var {
1025 self.add_repeat(delimited_arg, delimited, &mut iter, span)?;
1026 self.is_meta_var = false;
1028 self.add_delimited(delimited_arg, delimited, span);
1033 self.set_last_tok(&tok);
1036 // We are left with some stuff in the buffer. Since there is nothing
1037 // left to separate, add this as `Other`.
1038 if !self.buf.is_empty() {
1047 context: &RewriteContext<'_>,
1048 args: &[ParsedMacroArg],
1050 ) -> Option<String> {
1051 wrap_macro_args_inner(context, args, shape, false)
1052 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
1055 fn wrap_macro_args_inner(
1056 context: &RewriteContext<'_>,
1057 args: &[ParsedMacroArg],
1059 use_multiple_lines: bool,
1060 ) -> Option<String> {
1061 let mut result = String::with_capacity(128);
1062 let mut iter = args.iter().peekable();
1063 let indent_str = shape.indent.to_string_with_newline(context.config);
1065 while let Some(ref arg) = iter.next() {
1066 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1068 if use_multiple_lines
1069 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1071 if arg.kind.ends_with_space() {
1074 result.push_str(&indent_str);
1075 } else if let Some(ref next_arg) = iter.peek() {
1076 let space_before_dollar =
1077 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1078 let space_before_brace = next_arg.kind.starts_with_brace();
1079 if space_before_dollar || space_before_brace {
1085 if !use_multiple_lines && result.len() >= shape.width {
1092 // This is a bit sketchy. The token rules probably need tweaking, but it works
1093 // for some common cases. I hope the basic logic is sufficient. Note that the
1094 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1095 // and `(`/`)` have special meaning.
1097 // We always try and format on one line.
1098 // FIXME: Use multi-line when every thing does not fit on one line.
1099 fn format_macro_args(
1100 context: &RewriteContext<'_>,
1101 token_stream: TokenStream,
1103 ) -> Option<String> {
1104 if !context.config.format_macro_matchers() {
1105 let span = span_for_token_stream(&token_stream);
1106 return Some(match span {
1107 Some(span) => context.snippet(span).to_owned(),
1108 None => String::new(),
1111 let parsed_args = MacroArgParser::new().parse(token_stream)?;
1112 wrap_macro_args(context, &parsed_args, shape)
1115 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1116 token_stream.trees().next().map(|tt| tt.span())
1119 // We should insert a space if the next token is a:
1120 #[derive(Copy, Clone, PartialEq)]
1124 Ident, // Or ident/literal-like thing.
1128 fn force_space_before(tok: &TokenKind) -> bool {
1129 debug!("tok: force_space_before {:?}", tok);
1143 | TokenKind::BinOpEq(_)
1147 | TokenKind::FatArrow
1148 | TokenKind::BinOp(_)
1150 | TokenKind::Dollar => true,
1155 fn ident_like(tok: &Token) -> bool {
1157 TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_) => true,
1162 fn next_space(tok: &TokenKind) -> SpaceState {
1163 debug!("next_space: {:?}", tok);
1167 | TokenKind::BinOp(BinOpToken::And)
1173 | TokenKind::DotDotDot
1174 | TokenKind::DotDotEq
1175 | TokenKind::Question => SpaceState::Punctuation,
1180 | TokenKind::OpenDelim(_)
1181 | TokenKind::CloseDelim(_)
1182 | TokenKind::Whitespace => SpaceState::Never,
1184 TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(_) => SpaceState::Ident,
1186 _ => SpaceState::Always,
1190 /// Tries to convert a macro use into a short hand try expression. Returns `None`
1191 /// when the macro is not an instance of `try!` (or parsing the inner expression
1193 pub(crate) fn convert_try_mac(
1195 context: &RewriteContext<'_>,
1196 ) -> Option<ast::Expr> {
1197 let path = &pprust::path_to_string(&mac.path);
1198 if path == "try" || path == "r#try" {
1199 let ts = mac.args.inner_tokens();
1200 let mut parser = new_parser_from_tts(context.parse_sess.inner(), ts.trees().collect());
1203 id: ast::NodeId::root(), // dummy value
1204 kind: ast::ExprKind::Try(parser.parse_expr().ok()?),
1205 span: mac.span(), // incorrect span, but shouldn't matter too much
1206 attrs: ast::AttrVec::new(),
1214 pub(crate) fn macro_style(mac: &ast::MacCall, context: &RewriteContext<'_>) -> DelimToken {
1215 let snippet = context.snippet(mac.span());
1216 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1217 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1218 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1220 if paren_pos < bracket_pos && paren_pos < brace_pos {
1222 } else if bracket_pos < brace_pos {
1229 // A very simple parser that just parses a macros 2.0 definition into its branches.
1230 // Currently we do not attempt to parse any further than that.
1232 struct MacroParser {
1237 // (`(` ... `)` `=>` `{` ... `}`)*
1238 fn parse(&mut self) -> Option<Macro> {
1239 let mut branches = vec![];
1240 while self.toks.look_ahead(1).is_some() {
1241 branches.push(self.parse_branch()?);
1244 Some(Macro { branches })
1247 // `(` ... `)` `=>` `{` ... `}`
1248 fn parse_branch(&mut self) -> Option<MacroBranch> {
1249 let tok = self.toks.next()?;
1250 let (lo, args_paren_kind) = match tok {
1251 TokenTree::Token(..) => return None,
1252 TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1254 let args = tok.joint();
1255 match self.toks.next()? {
1256 TokenTree::Token(Token {
1257 kind: TokenKind::FatArrow,
1262 let (mut hi, body, whole_body) = match self.toks.next()? {
1263 TokenTree::Token(..) => return None,
1264 TokenTree::Delimited(delimited_span, ..) => {
1265 let data = delimited_span.entire().data();
1268 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1269 delimited_span.entire(),
1273 if let Some(TokenTree::Token(Token {
1274 kind: TokenKind::Semi,
1276 })) = self.toks.look_ahead(0)
1282 span: mk_sp(lo, hi),
1291 // A parsed macros 2.0 macro definition.
1293 branches: Vec<MacroBranch>,
1296 // FIXME: it would be more efficient to use references to the token streams
1297 // rather than clone them, if we can make the borrowing work out.
1298 struct MacroBranch {
1300 args_paren_kind: DelimToken,
1309 context: &RewriteContext<'_>,
1311 multi_branch_style: bool,
1312 ) -> Option<String> {
1313 // Only attempt to format function-like macros.
1314 if self.args_paren_kind != DelimToken::Paren {
1315 // FIXME(#1539): implement for non-sugared macros.
1320 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1322 if multi_branch_style {
1326 if !context.config.format_macro_bodies() {
1328 result += context.snippet(self.whole_body);
1329 return Some(result);
1332 // The macro body is the most interesting part. It might end up as various
1333 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1334 // parsed as regular Rust code (and note that these can be escaped using
1335 // `$$`). We'll try and format like an AST node, but we'll substitute
1336 // variables for new names with the same length first.
1338 let old_body = context.snippet(self.body).trim();
1339 let (body_str, substs) = replace_names(old_body)?;
1340 let has_block_body = old_body.starts_with('{');
1342 let mut config = context.config.clone();
1343 config.set().hide_parse_errors(true);
1347 let body_indent = if has_block_body {
1350 shape.indent.block_indent(&config)
1352 let new_width = config.max_width() - body_indent.width();
1353 config.set().max_width(new_width);
1355 // First try to format as items, then as statements.
1356 let new_body_snippet = match crate::format_snippet(&body_str, &config) {
1357 Some(new_body) => new_body,
1359 let new_width = new_width + config.tab_spaces();
1360 config.set().max_width(new_width);
1361 match crate::format_code_block(&body_str, &config) {
1362 Some(new_body) => new_body,
1363 None => return None,
1367 let new_body = wrap_str(
1368 new_body_snippet.snippet.to_string(),
1373 // Indent the body since it is in a block.
1374 let indent_str = body_indent.to_string(&config);
1375 let mut new_body = LineClasses::new(new_body.trim_end())
1378 (String::new(), true),
1379 |(mut s, need_indent), (i, (kind, ref l))| {
1380 if !is_empty_line(l)
1382 && !new_body_snippet.is_line_non_formatted(i + 1)
1386 (s + l + "\n", indent_next_line(kind, &l, &config))
1391 // Undo our replacement of macro variables.
1392 // FIXME: this could be *much* more efficient.
1393 for (old, new) in &substs {
1394 if old_body.find(new).is_some() {
1395 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1398 new_body = new_body.replace(new, old);
1402 result += new_body.trim();
1403 } else if !new_body.is_empty() {
1405 result += &new_body;
1406 result += &shape.indent.to_string(&config);
1415 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1417 /// # Expected syntax
1421 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1422 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1424 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1427 fn format_lazy_static(
1428 context: &RewriteContext<'_>,
1431 ) -> Option<String> {
1432 let mut result = String::with_capacity(1024);
1433 let mut parser = new_parser_from_tts(context.parse_sess.inner(), ts.trees().collect());
1434 let nested_shape = shape
1435 .block_indent(context.config.tab_spaces())
1436 .with_max_width(context.config);
1438 result.push_str("lazy_static! {");
1439 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1441 macro_rules! parse_or {
1442 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1443 match parser.$method($($arg,)*) {
1445 if parser.sess.span_diagnostic.has_errors() {
1446 parser.sess.span_diagnostic.reset_err_count();
1454 parser.sess.span_diagnostic.reset_err_count();
1461 while parser.token.kind != TokenKind::Eof {
1462 // Parse a `lazy_static!` item.
1463 let vis = crate::utils::format_visibility(
1465 &parse_or!(parse_visibility, rustc_parse::parser::FollowedByType::No),
1467 parser.eat_keyword(kw::Static);
1468 parser.eat_keyword(kw::Ref);
1469 let id = parse_or!(parse_ident);
1470 parser.eat(&TokenKind::Colon);
1471 let ty = parse_or!(parse_ty);
1472 parser.eat(&TokenKind::Eq);
1473 let expr = parse_or!(parse_expr);
1474 parser.eat(&TokenKind::Semi);
1476 // Rewrite as a static item.
1477 let mut stmt = String::with_capacity(128);
1478 stmt.push_str(&format!(
1479 "{}static ref {}: {} =",
1482 ty.rewrite(context, nested_shape)?
1484 result.push_str(&crate::expr::rewrite_assign_rhs(
1488 nested_shape.sub_width(1)?,
1491 if parser.token.kind != TokenKind::Eof {
1492 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1496 result.push_str(&shape.indent.to_string_with_newline(context.config));
1502 fn rewrite_macro_with_items(
1503 context: &RewriteContext<'_>,
1508 position: MacroPosition,
1510 ) -> Option<String> {
1511 let (opener, closer) = match style {
1512 DelimToken::Paren => ("(", ")"),
1513 DelimToken::Bracket => ("[", "]"),
1514 DelimToken::Brace => (" {", "}"),
1517 let trailing_semicolon = match style {
1518 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1522 let mut visitor = FmtVisitor::from_context(context);
1523 visitor.block_indent = shape.indent.block_indent(context.config);
1524 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1526 let item = match item {
1527 MacroArg::Item(item) => item,
1530 visitor.visit_item(&item);
1533 let mut result = String::with_capacity(256);
1534 result.push_str(¯o_name);
1535 result.push_str(opener);
1536 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1537 result.push_str(visitor.buffer.trim());
1538 result.push_str(&shape.indent.to_string_with_newline(context.config));
1539 result.push_str(closer);
1540 result.push_str(trailing_semicolon);
1544 const RUST_KW: [Symbol; 59] = [
1598 kw::UnderscoreLifetime,