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_pretty::pprust;
16 use rustc_parse::{new_parser_from_tts, parser::Parser};
17 use rustc_span::{symbol::kw, BytePos, Span, Symbol, DUMMY_SP};
18 use syntax::token::{BinOpToken, DelimToken, Token, TokenKind};
19 use syntax::tokenstream::{Cursor, TokenStream, TokenTree};
20 use syntax::{ast, ptr};
23 contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
25 use crate::config::lists::*;
26 use crate::expr::rewrite_array;
27 use crate::lists::{itemize_list, write_list, ListFormatting};
29 use crate::rewrite::{Rewrite, RewriteContext};
30 use crate::shape::{Indent, Shape};
31 use crate::source_map::SpanUtils;
32 use crate::spanned::Spanned;
34 format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
35 rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
37 use crate::visitor::FmtVisitor;
39 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
41 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
42 pub(crate) enum MacroPosition {
50 pub(crate) enum MacroArg {
51 Expr(ptr::P<ast::Expr>),
53 Pat(ptr::P<ast::Pat>),
54 Item(ptr::P<ast::Item>),
55 Keyword(ast::Ident, Span),
59 fn is_item(&self) -> bool {
61 MacroArg::Item(..) => true,
67 impl Rewrite for ast::Item {
68 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
69 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
70 visitor.block_indent = shape.indent;
71 visitor.last_pos = self.span().lo();
72 visitor.visit_item(self);
73 Some(visitor.buffer.to_owned())
77 impl Rewrite for MacroArg {
78 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
80 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
81 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
82 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
83 MacroArg::Item(ref item) => item.rewrite(context, shape),
84 MacroArg::Keyword(ident, _) => Some(ident.name.to_string()),
89 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
90 macro_rules! parse_macro_arg {
91 ($macro_arg:ident, $parser:expr, $f:expr) => {
92 let mut cloned_parser = (*parser).clone();
93 match $parser(&mut cloned_parser) {
95 if parser.sess.span_diagnostic.has_errors() {
96 parser.sess.span_diagnostic.reset_err_count();
99 *parser = cloned_parser;
100 return Some(MacroArg::$macro_arg($f(x)?));
105 parser.sess.span_diagnostic.reset_err_count();
113 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(),
114 |x: ptr::P<ast::Expr>| Some(x)
118 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(),
119 |x: ptr::P<ast::Ty>| Some(x)
123 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat(None),
124 |x: ptr::P<ast::Pat>| Some(x)
126 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
129 |parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_item(),
130 |x: Option<ptr::P<ast::Item>>| x
136 /// Rewrite macro name without using pretty-printer if possible.
137 fn rewrite_macro_name(
138 context: &RewriteContext<'_>,
140 extra_ident: Option<ast::Ident>,
142 let name = if path.segments.len() == 1 {
143 // Avoid using pretty-printer in the common case.
144 format!("{}!", rewrite_ident(context, path.segments[0].ident))
146 format!("{}!", pprust::path_to_string(path))
149 Some(ident) if ident.name != kw::Invalid => format!("{} {}", name, ident),
154 // Use this on failing to format the macro call.
155 fn return_macro_parse_failure_fallback(
156 context: &RewriteContext<'_>,
159 ) -> Option<String> {
160 // Mark this as a failure however we format it
161 context.macro_rewrite_failure.replace(true);
163 // Heuristically determine whether the last line of the macro uses "Block" style
164 // rather than using "Visual" style, or another indentation style.
165 let is_like_block_indent_style = context
169 .map(|closing_line| {
170 closing_line.trim().chars().all(|ch| match ch {
171 '}' | ')' | ']' => true,
176 if is_like_block_indent_style {
177 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
180 context.skipped_range.borrow_mut().push((
181 context.source_map.lookup_line(span.lo()).unwrap().line,
182 context.source_map.lookup_line(span.hi()).unwrap().line,
185 // Return the snippet unmodified if the macro is not block-like
186 Some(context.snippet(span).to_owned())
189 pub(crate) fn rewrite_macro(
191 extra_ident: Option<ast::Ident>,
192 context: &RewriteContext<'_>,
194 position: MacroPosition,
195 ) -> Option<String> {
196 let should_skip = context
198 .skip_macro(&context.snippet(mac.path.span).to_owned());
202 let guard = context.enter_macro();
203 let result = catch_unwind(AssertUnwindSafe(|| {
214 Err(..) | Ok(None) => {
215 context.macro_rewrite_failure.replace(true);
223 fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
224 for &keyword in RUST_KW.iter() {
225 if parser.token.is_keyword(keyword)
226 && parser.look_ahead(1, |t| {
227 t.kind == TokenKind::Eof
228 || t.kind == TokenKind::Comma
229 || t.kind == TokenKind::CloseDelim(DelimToken::NoDelim)
234 MacroArg::Keyword(ast::Ident::with_dummy_span(keyword), parser.prev_span);
235 return Some(macro_arg);
241 fn rewrite_macro_inner(
243 extra_ident: Option<ast::Ident>,
244 context: &RewriteContext<'_>,
246 position: MacroPosition,
247 is_nested_macro: bool,
248 ) -> Option<String> {
249 if context.config.use_try_shorthand() {
250 if let Some(expr) = convert_try_mac(mac, context) {
251 context.leave_macro();
252 return expr.rewrite(context, shape);
256 let original_style = macro_style(mac, context);
258 let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
260 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
266 let ts = mac.args.inner_tokens();
267 let has_comment = contains_comment(context.snippet(mac.span()));
268 if ts.is_empty() && !has_comment {
270 DelimToken::Paren if position == MacroPosition::Item => {
271 Some(format!("{}();", macro_name))
273 DelimToken::Bracket if position == MacroPosition::Item => {
274 Some(format!("{}[];", macro_name))
276 DelimToken::Paren => Some(format!("{}()", macro_name)),
277 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
278 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
282 // Format well-known macros which cannot be parsed as a valid AST.
283 if macro_name == "lazy_static!" && !has_comment {
284 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
289 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
290 let mut arg_vec = Vec::new();
291 let mut vec_with_semi = false;
292 let mut trailing_comma = false;
294 if DelimToken::Brace != style {
296 if let Some(arg) = check_keyword(&mut parser) {
298 } else if let Some(arg) = parse_macro_arg(&mut parser) {
301 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
304 match parser.token.kind {
305 TokenKind::Eof => break,
306 TokenKind::Comma => (),
308 // Try to parse `vec![expr; expr]`
309 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
311 if parser.token.kind != TokenKind::Eof {
312 match parse_macro_arg(&mut parser) {
316 if parser.token.kind == TokenKind::Eof && arg_vec.len() == 2 {
317 vec_with_semi = true;
322 return return_macro_parse_failure_fallback(
331 return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
333 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
334 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span()),
339 if parser.token.kind == TokenKind::Eof {
340 trailing_comma = true;
346 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
347 return rewrite_macro_with_items(
359 DelimToken::Paren => {
360 // Handle special case: `vec!(expr; expr)`
362 handle_vec_semi(context, shape, arg_vec, macro_name, style)
364 // Format macro invocation as function call, preserve the trailing
365 // comma because not all macros support them.
366 overflow::rewrite_with_parens(
372 context.config.width_heuristics().fn_call_width,
374 Some(SeparatorTactic::Always)
376 Some(SeparatorTactic::Never)
379 .map(|rw| match position {
380 MacroPosition::Item => format!("{};", rw),
385 DelimToken::Bracket => {
386 // Handle special case: `vec![expr; expr]`
388 handle_vec_semi(context, shape, arg_vec, macro_name, style)
390 // If we are rewriting `vec!` macro or other special macros,
391 // then we can rewrite this as an usual array literal.
392 // Otherwise, we must preserve the original existence of trailing comma.
393 let macro_name = ¯o_name.as_str();
394 let mut force_trailing_comma = if trailing_comma {
395 Some(SeparatorTactic::Always)
397 Some(SeparatorTactic::Never)
399 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
400 context.leave_macro();
401 if context.use_block_indent() {
402 force_trailing_comma = Some(SeparatorTactic::Vertical);
405 let rewrite = rewrite_array(
411 force_trailing_comma,
412 Some(original_style),
414 let comma = match position {
415 MacroPosition::Item => ";",
419 Some(format!("{}{}", rewrite, comma))
422 DelimToken::Brace => {
423 // For macro invocations with braces, always put a space between
424 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
425 // anything in between the braces (for now).
426 let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
427 match trim_left_preserve_layout(snippet, shape.indent, &context.config) {
428 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
429 None => Some(format!("{} {}", macro_name, snippet)),
437 context: &RewriteContext<'_>,
439 arg_vec: Vec<MacroArg>,
441 delim_token: DelimToken,
442 ) -> Option<String> {
443 let (left, right) = match delim_token {
444 DelimToken::Paren => ("(", ")"),
445 DelimToken::Bracket => ("[", "]"),
449 let mac_shape = shape.offset_left(macro_name.len())?;
450 // 8 = `vec![]` + `; ` or `vec!()` + `; `
451 let total_overhead = 8;
452 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
453 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
454 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
455 if !lhs.contains('\n')
456 && !rhs.contains('\n')
457 && lhs.len() + rhs.len() + total_overhead <= shape.width
459 // macro_name(lhs; rhs) or macro_name[lhs; rhs]
460 Some(format!("{}{}{}; {}{}", macro_name, left, lhs, rhs, right))
462 // macro_name(\nlhs;\nrhs\n) or macro_name[\nlhs;\nrhs\n]
467 nested_shape.indent.to_string_with_newline(context.config),
469 nested_shape.indent.to_string_with_newline(context.config),
471 shape.indent.to_string_with_newline(context.config),
477 pub(crate) fn rewrite_macro_def(
478 context: &RewriteContext<'_>,
483 vis: &ast::Visibility,
485 ) -> Option<String> {
486 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
487 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
491 let ts = def.body.inner_tokens();
492 let mut parser = MacroParser::new(ts.into_trees());
493 let parsed_def = match parser.parse() {
495 None => return snippet,
498 let mut result = if def.legacy {
499 String::from("macro_rules!")
501 format!("{}macro", format_visibility(context, vis))
505 result += rewrite_ident(context, ident);
507 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
509 let arm_shape = if multi_branch_style {
511 .block_indent(context.config.tab_spaces())
512 .with_max_width(context.config)
517 let branch_items = itemize_list(
518 context.snippet_provider,
519 parsed_def.branches.iter(),
522 |branch| branch.span.lo(),
523 |branch| branch.span.hi(),
524 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
526 // if the rewrite returned None because a macro could not be rewritten, then return the
528 None if context.macro_rewrite_failure.get() => {
529 Some(context.snippet(branch.body).trim().to_string())
533 context.snippet_provider.span_after(span, "{"),
537 .collect::<Vec<_>>();
539 let fmt = ListFormatting::new(arm_shape, context.config)
540 .separator(if def.legacy { ";" } else { "" })
541 .trailing_separator(SeparatorTactic::Always)
542 .preserve_newline(true);
544 if multi_branch_style {
546 result += &arm_shape.indent.to_string_with_newline(context.config);
549 match write_list(&branch_items, &fmt) {
550 Some(ref s) => result += s,
551 None => return snippet,
554 if multi_branch_style {
555 result += &indent.to_string_with_newline(context.config);
562 fn register_metavariable(
563 map: &mut HashMap<String, String>,
568 let mut new_name = "$".repeat(dollar_count - 1);
569 let mut old_name = "$".repeat(dollar_count);
572 new_name.push_str(name);
573 old_name.push_str(name);
575 result.push_str(&new_name);
576 map.insert(old_name, new_name);
579 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
580 // aren't causing problems.
581 // This should also work for escaped `$` variables, where we leave earlier `$`s.
582 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
583 // Each substitution will require five or six extra bytes.
584 let mut result = String::with_capacity(input.len() + 64);
585 let mut substs = HashMap::new();
586 let mut dollar_count = 0;
587 let mut cur_name = String::new();
589 for (kind, c) in CharClasses::new(input.chars()) {
590 if kind != FullCodeCharKind::Normal {
594 } else if dollar_count == 0 {
596 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
597 // Terminates a name following one or more dollars.
598 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
603 } else if c == '(' && cur_name.is_empty() {
604 // FIXME: Support macro def with repeat.
606 } else if c.is_alphanumeric() || c == '_' {
611 if !cur_name.is_empty() {
612 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
615 debug!("replace_names `{}` {:?}", result, substs);
617 Some((result, substs))
620 #[derive(Debug, Clone)]
622 /// e.g., `$x: expr`.
623 MetaVariable(ast::Name, String),
624 /// e.g., `$($foo: expr),*`
626 /// `()`, `[]` or `{}`.
628 /// Inner arguments inside delimiters.
630 /// Something after the closing delimiter and the repeat token, if available.
631 Option<Box<ParsedMacroArg>>,
632 /// The repeat token. This could be one of `*`, `+` or `?`.
635 /// e.g., `[derive(Debug)]`
636 Delimited(DelimToken, Vec<ParsedMacroArg>),
637 /// A possible separator. e.g., `,` or `;`.
638 Separator(String, String),
639 /// Other random stuff that does not fit to other kinds.
640 /// e.g., `== foo` in `($x: expr == foo)`.
641 Other(String, String),
644 fn delim_token_to_str(
645 context: &RewriteContext<'_>,
646 delim_token: DelimToken,
648 use_multiple_lines: bool,
649 inner_is_empty: bool,
650 ) -> (String, String) {
651 let (lhs, rhs) = match delim_token {
652 DelimToken::Paren => ("(", ")"),
653 DelimToken::Bracket => ("[", "]"),
654 DelimToken::Brace => {
655 if inner_is_empty || use_multiple_lines {
661 DelimToken::NoDelim => ("", ""),
663 if use_multiple_lines {
664 let indent_str = shape.indent.to_string_with_newline(context.config);
665 let nested_indent_str = shape
667 .block_indent(context.config)
668 .to_string_with_newline(context.config);
670 format!("{}{}", lhs, nested_indent_str),
671 format!("{}{}", indent_str, rhs),
674 (lhs.to_owned(), rhs.to_owned())
679 fn starts_with_brace(&self) -> bool {
681 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
682 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
687 fn starts_with_dollar(&self) -> bool {
689 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
694 fn ends_with_space(&self) -> bool {
696 MacroArgKind::Separator(..) => true,
701 fn has_meta_var(&self) -> bool {
703 MacroArgKind::MetaVariable(..) => true,
704 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
711 context: &RewriteContext<'_>,
713 use_multiple_lines: bool,
714 ) -> Option<String> {
715 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
716 let inner = wrap_macro_args(context, args, shape)?;
717 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
718 if lhs.len() + inner.len() + rhs.len() <= shape.width {
719 return Some((lhs, inner, rhs));
722 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
723 let nested_shape = shape
724 .block_indent(context.config.tab_spaces())
725 .with_max_width(context.config);
726 let inner = wrap_macro_args(context, args, nested_shape)?;
727 Some((lhs, inner, rhs))
731 MacroArgKind::MetaVariable(ty, ref name) => Some(format!("${}:{}", name, ty)),
732 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
733 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
734 let another = another
736 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
737 .unwrap_or_else(|| "".to_owned());
738 let repeat_tok = pprust::token_to_string(tok);
740 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
742 MacroArgKind::Delimited(delim_tok, ref args) => {
743 rewrite_delimited_inner(delim_tok, args)
744 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
746 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
747 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
752 #[derive(Debug, Clone)]
753 struct ParsedMacroArg {
758 impl ParsedMacroArg {
761 context: &RewriteContext<'_>,
763 use_multiple_lines: bool,
764 ) -> Option<String> {
765 self.kind.rewrite(context, shape, use_multiple_lines)
769 /// Parses macro arguments on macro def.
770 struct MacroArgParser {
771 /// Either a name of the next metavariable, a separator, or junk.
773 /// The start position on the current buffer.
775 /// The first token of the current buffer.
777 /// `true` if we are parsing a metavariable or a repeat.
779 /// The position of the last token.
781 /// The last token parsed.
783 /// Holds the parsed arguments.
784 result: Vec<ParsedMacroArg>,
787 fn last_tok(tt: &TokenTree) -> Token {
789 TokenTree::Token(ref t) => t.clone(),
790 TokenTree::Delimited(delim_span, delim, _) => Token {
791 kind: TokenKind::CloseDelim(delim),
792 span: delim_span.close,
797 impl MacroArgParser {
798 fn new() -> MacroArgParser {
805 kind: TokenKind::Eof,
809 kind: TokenKind::Eof,
816 fn set_last_tok(&mut self, tok: &TokenTree) {
817 self.hi = tok.span().hi();
818 self.last_tok = last_tok(tok);
821 fn add_separator(&mut self) {
822 let prefix = if self.need_space_prefix() {
827 self.result.push(ParsedMacroArg {
828 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
829 span: mk_sp(self.lo, self.hi),
834 fn add_other(&mut self) {
835 let prefix = if self.need_space_prefix() {
840 self.result.push(ParsedMacroArg {
841 kind: MacroArgKind::Other(self.buf.clone(), prefix),
842 span: mk_sp(self.lo, self.hi),
847 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
849 Some(TokenTree::Token(Token {
850 kind: TokenKind::Ident(name, _),
853 self.result.push(ParsedMacroArg {
854 kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
855 span: mk_sp(self.lo, span.hi()),
859 self.is_meta_var = false;
866 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
867 self.result.push(ParsedMacroArg {
868 kind: MacroArgKind::Delimited(delim, inner),
876 inner: Vec<ParsedMacroArg>,
881 let mut buffer = String::new();
882 let mut first = true;
883 let mut lo = span.lo();
884 let mut hi = span.hi();
886 // Parse '*', '+' or '?.
888 self.set_last_tok(&tok);
891 lo = tok.span().lo();
895 TokenTree::Token(Token {
896 kind: TokenKind::BinOp(BinOpToken::Plus),
899 | TokenTree::Token(Token {
900 kind: TokenKind::Question,
903 | TokenTree::Token(Token {
904 kind: TokenKind::BinOp(BinOpToken::Star),
909 TokenTree::Token(ref t) => {
910 buffer.push_str(&pprust::token_to_string(&t));
917 // There could be some random stuff between ')' and '*', '+' or '?'.
918 let another = if buffer.trim().is_empty() {
921 Some(Box::new(ParsedMacroArg {
922 kind: MacroArgKind::Other(buffer, "".to_owned()),
927 self.result.push(ParsedMacroArg {
928 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
929 span: mk_sp(self.lo, self.hi),
934 fn update_buffer(&mut self, t: &Token) {
935 if self.buf.is_empty() {
936 self.lo = t.span.lo();
937 self.start_tok = t.clone();
939 let needs_space = match next_space(&self.last_tok.kind) {
940 SpaceState::Ident => ident_like(t),
941 SpaceState::Punctuation => !ident_like(t),
942 SpaceState::Always => true,
943 SpaceState::Never => false,
945 if force_space_before(&t.kind) || needs_space {
950 self.buf.push_str(&pprust::token_to_string(t));
953 fn need_space_prefix(&self) -> bool {
954 if self.result.is_empty() {
958 let last_arg = self.result.last().unwrap();
959 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
960 if ident_like(&self.start_tok) {
963 if self.start_tok.kind == TokenKind::Colon {
968 if force_space_before(&self.start_tok.kind) {
975 /// Returns a collection of parsed macro def's arguments.
976 fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
977 let mut iter = tokens.trees();
979 while let Some(tok) = iter.next() {
981 TokenTree::Token(Token {
982 kind: TokenKind::Dollar,
985 // We always want to add a separator before meta variables.
986 if !self.buf.is_empty() {
987 self.add_separator();
990 // Start keeping the name of this metavariable in the buffer.
991 self.is_meta_var = true;
993 self.start_tok = Token {
994 kind: TokenKind::Dollar,
998 TokenTree::Token(Token {
999 kind: TokenKind::Colon,
1001 }) if self.is_meta_var => {
1002 self.add_meta_variable(&mut iter)?;
1004 TokenTree::Token(ref t) => self.update_buffer(t),
1005 TokenTree::Delimited(delimited_span, delimited, ref tts) => {
1006 if !self.buf.is_empty() {
1007 if next_space(&self.last_tok.kind) == SpaceState::Always {
1008 self.add_separator();
1014 // Parse the stuff inside delimiters.
1015 let mut parser = MacroArgParser::new();
1016 parser.lo = delimited_span.open.lo();
1017 let delimited_arg = parser.parse(tts.clone())?;
1019 let span = delimited_span.entire();
1020 if self.is_meta_var {
1021 self.add_repeat(delimited_arg, delimited, &mut iter, span)?;
1022 self.is_meta_var = false;
1024 self.add_delimited(delimited_arg, delimited, span);
1029 self.set_last_tok(&tok);
1032 // We are left with some stuff in the buffer. Since there is nothing
1033 // left to separate, add this as `Other`.
1034 if !self.buf.is_empty() {
1043 context: &RewriteContext<'_>,
1044 args: &[ParsedMacroArg],
1046 ) -> Option<String> {
1047 wrap_macro_args_inner(context, args, shape, false)
1048 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
1051 fn wrap_macro_args_inner(
1052 context: &RewriteContext<'_>,
1053 args: &[ParsedMacroArg],
1055 use_multiple_lines: bool,
1056 ) -> Option<String> {
1057 let mut result = String::with_capacity(128);
1058 let mut iter = args.iter().peekable();
1059 let indent_str = shape.indent.to_string_with_newline(context.config);
1061 while let Some(ref arg) = iter.next() {
1062 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1064 if use_multiple_lines
1065 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1067 if arg.kind.ends_with_space() {
1070 result.push_str(&indent_str);
1071 } else if let Some(ref next_arg) = iter.peek() {
1072 let space_before_dollar =
1073 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1074 let space_before_brace = next_arg.kind.starts_with_brace();
1075 if space_before_dollar || space_before_brace {
1081 if !use_multiple_lines && result.len() >= shape.width {
1088 // This is a bit sketchy. The token rules probably need tweaking, but it works
1089 // for some common cases. I hope the basic logic is sufficient. Note that the
1090 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1091 // and `(`/`)` have special meaning.
1093 // We always try and format on one line.
1094 // FIXME: Use multi-line when every thing does not fit on one line.
1095 fn format_macro_args(
1096 context: &RewriteContext<'_>,
1097 token_stream: TokenStream,
1099 ) -> Option<String> {
1100 if !context.config.format_macro_matchers() {
1101 let span = span_for_token_stream(&token_stream);
1102 return Some(match span {
1103 Some(span) => context.snippet(span).to_owned(),
1104 None => String::new(),
1107 let parsed_args = MacroArgParser::new().parse(token_stream)?;
1108 wrap_macro_args(context, &parsed_args, shape)
1111 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1112 token_stream.trees().next().map(|tt| tt.span())
1115 // We should insert a space if the next token is a:
1116 #[derive(Copy, Clone, PartialEq)]
1120 Ident, // Or ident/literal-like thing.
1124 fn force_space_before(tok: &TokenKind) -> bool {
1125 debug!("tok: force_space_before {:?}", tok);
1139 | TokenKind::BinOpEq(_)
1143 | TokenKind::FatArrow
1144 | TokenKind::BinOp(_)
1146 | TokenKind::Dollar => true,
1151 fn ident_like(tok: &Token) -> bool {
1153 TokenKind::Ident(..) | TokenKind::Literal(..) | TokenKind::Lifetime(_) => true,
1158 fn next_space(tok: &TokenKind) -> SpaceState {
1159 debug!("next_space: {:?}", tok);
1163 | TokenKind::BinOp(BinOpToken::And)
1169 | TokenKind::DotDotDot
1170 | TokenKind::DotDotEq
1171 | TokenKind::Question => SpaceState::Punctuation,
1176 | TokenKind::OpenDelim(_)
1177 | TokenKind::CloseDelim(_)
1178 | TokenKind::Whitespace => SpaceState::Never,
1180 TokenKind::Literal(..) | TokenKind::Ident(..) | TokenKind::Lifetime(_) => SpaceState::Ident,
1182 _ => SpaceState::Always,
1186 /// Tries to convert a macro use into a short hand try expression. Returns `None`
1187 /// when the macro is not an instance of `try!` (or parsing the inner expression
1189 pub(crate) fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> {
1190 let path = &pprust::path_to_string(&mac.path);
1191 if path == "try" || path == "r#try" {
1192 let ts = mac.args.inner_tokens();
1193 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1196 id: ast::NodeId::root(), // dummy value
1197 kind: ast::ExprKind::Try(parser.parse_expr().ok()?),
1198 span: mac.span(), // incorrect span, but shouldn't matter too much
1199 attrs: ast::AttrVec::new(),
1206 pub(crate) fn macro_style(mac: &ast::Mac, context: &RewriteContext<'_>) -> DelimToken {
1207 let snippet = context.snippet(mac.span());
1208 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1209 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1210 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1212 if paren_pos < bracket_pos && paren_pos < brace_pos {
1214 } else if bracket_pos < brace_pos {
1221 // A very simple parser that just parses a macros 2.0 definition into its branches.
1222 // Currently we do not attempt to parse any further than that.
1224 struct MacroParser {
1229 // (`(` ... `)` `=>` `{` ... `}`)*
1230 fn parse(&mut self) -> Option<Macro> {
1231 let mut branches = vec![];
1232 while self.toks.look_ahead(1).is_some() {
1233 branches.push(self.parse_branch()?);
1236 Some(Macro { branches })
1239 // `(` ... `)` `=>` `{` ... `}`
1240 fn parse_branch(&mut self) -> Option<MacroBranch> {
1241 let tok = self.toks.next()?;
1242 let (lo, args_paren_kind) = match tok {
1243 TokenTree::Token(..) => return None,
1244 TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1246 let args = tok.joint();
1247 match self.toks.next()? {
1248 TokenTree::Token(Token {
1249 kind: TokenKind::FatArrow,
1254 let (mut hi, body, whole_body) = match self.toks.next()? {
1255 TokenTree::Token(..) => return None,
1256 TokenTree::Delimited(delimited_span, ..) => {
1257 let data = delimited_span.entire().data();
1260 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1261 delimited_span.entire(),
1265 if let Some(TokenTree::Token(Token {
1266 kind: TokenKind::Semi,
1268 })) = self.toks.look_ahead(0)
1274 span: mk_sp(lo, hi),
1283 // A parsed macros 2.0 macro definition.
1285 branches: Vec<MacroBranch>,
1288 // FIXME: it would be more efficient to use references to the token streams
1289 // rather than clone them, if we can make the borrowing work out.
1290 struct MacroBranch {
1292 args_paren_kind: DelimToken,
1301 context: &RewriteContext<'_>,
1303 multi_branch_style: bool,
1304 ) -> Option<String> {
1305 // Only attempt to format function-like macros.
1306 if self.args_paren_kind != DelimToken::Paren {
1307 // FIXME(#1539): implement for non-sugared macros.
1312 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1314 if multi_branch_style {
1318 if !context.config.format_macro_bodies() {
1320 result += context.snippet(self.whole_body);
1321 return Some(result);
1324 // The macro body is the most interesting part. It might end up as various
1325 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1326 // parsed as regular Rust code (and note that these can be escaped using
1327 // `$$`). We'll try and format like an AST node, but we'll substitute
1328 // variables for new names with the same length first.
1330 let old_body = context.snippet(self.body).trim();
1331 let (body_str, substs) = replace_names(old_body)?;
1332 let has_block_body = old_body.starts_with('{');
1334 let mut config = context.config.clone();
1335 config.set().hide_parse_errors(true);
1339 let body_indent = if has_block_body {
1342 shape.indent.block_indent(&config)
1344 let new_width = config.max_width() - body_indent.width();
1345 config.set().max_width(new_width);
1347 // First try to format as items, then as statements.
1348 let new_body_snippet = match crate::format_snippet(&body_str, &config) {
1349 Some(new_body) => new_body,
1351 let new_width = new_width + config.tab_spaces();
1352 config.set().max_width(new_width);
1353 match crate::format_code_block(&body_str, &config) {
1354 Some(new_body) => new_body,
1355 None => return None,
1359 let new_body = wrap_str(
1360 new_body_snippet.snippet.to_string(),
1365 // Indent the body since it is in a block.
1366 let indent_str = body_indent.to_string(&config);
1367 let mut new_body = LineClasses::new(new_body.trim_end())
1370 (String::new(), true),
1371 |(mut s, need_indent), (i, (kind, ref l))| {
1372 if !is_empty_line(l)
1374 && !new_body_snippet.is_line_non_formatted(i + 1)
1378 (s + l + "\n", indent_next_line(kind, &l, &config))
1383 // Undo our replacement of macro variables.
1384 // FIXME: this could be *much* more efficient.
1385 for (old, new) in &substs {
1386 if old_body.find(new).is_some() {
1387 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1390 new_body = new_body.replace(new, old);
1394 result += new_body.trim();
1395 } else if !new_body.is_empty() {
1397 result += &new_body;
1398 result += &shape.indent.to_string(&config);
1407 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1409 /// # Expected syntax
1413 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1414 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1416 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1419 fn format_lazy_static(
1420 context: &RewriteContext<'_>,
1423 ) -> Option<String> {
1424 let mut result = String::with_capacity(1024);
1425 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1426 let nested_shape = shape
1427 .block_indent(context.config.tab_spaces())
1428 .with_max_width(context.config);
1430 result.push_str("lazy_static! {");
1431 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1433 macro_rules! parse_or {
1434 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1435 match parser.$method($($arg,)*) {
1437 if parser.sess.span_diagnostic.has_errors() {
1438 parser.sess.span_diagnostic.reset_err_count();
1446 parser.sess.span_diagnostic.reset_err_count();
1453 while parser.token.kind != TokenKind::Eof {
1454 // Parse a `lazy_static!` item.
1455 let vis = crate::utils::format_visibility(
1457 &parse_or!(parse_visibility, rustc_parse::parser::FollowedByType::No),
1459 parser.eat_keyword(kw::Static);
1460 parser.eat_keyword(kw::Ref);
1461 let id = parse_or!(parse_ident);
1462 parser.eat(&TokenKind::Colon);
1463 let ty = parse_or!(parse_ty);
1464 parser.eat(&TokenKind::Eq);
1465 let expr = parse_or!(parse_expr);
1466 parser.eat(&TokenKind::Semi);
1468 // Rewrite as a static item.
1469 let mut stmt = String::with_capacity(128);
1470 stmt.push_str(&format!(
1471 "{}static ref {}: {} =",
1474 ty.rewrite(context, nested_shape)?
1476 result.push_str(&crate::expr::rewrite_assign_rhs(
1480 nested_shape.sub_width(1)?,
1483 if parser.token.kind != TokenKind::Eof {
1484 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1488 result.push_str(&shape.indent.to_string_with_newline(context.config));
1494 fn rewrite_macro_with_items(
1495 context: &RewriteContext<'_>,
1500 position: MacroPosition,
1502 ) -> Option<String> {
1503 let (opener, closer) = match style {
1504 DelimToken::Paren => ("(", ")"),
1505 DelimToken::Bracket => ("[", "]"),
1506 DelimToken::Brace => (" {", "}"),
1509 let trailing_semicolon = match style {
1510 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1514 let mut visitor = FmtVisitor::from_context(context);
1515 visitor.block_indent = shape.indent.block_indent(context.config);
1516 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1518 let item = match item {
1519 MacroArg::Item(item) => item,
1522 visitor.visit_item(&item);
1525 let mut result = String::with_capacity(256);
1526 result.push_str(¯o_name);
1527 result.push_str(opener);
1528 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1529 result.push_str(visitor.buffer.trim());
1530 result.push_str(&shape.indent.to_string_with_newline(context.config));
1531 result.push_str(closer);
1532 result.push_str(trailing_semicolon);
1536 const RUST_KW: [Symbol; 59] = [
1590 kw::UnderscoreLifetime,