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;
14 use syntax::parse::new_parser_from_tts;
15 use syntax::parse::parser::Parser;
16 use syntax::parse::token::{BinOpToken, DelimToken, Token};
17 use syntax::print::pprust;
18 use syntax::source_map::{BytePos, Span};
19 use syntax::symbol::keywords;
20 use syntax::tokenstream::{Cursor, TokenStream, TokenTree};
22 use syntax::{ast, parse, ptr};
25 contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
27 use crate::config::lists::*;
28 use crate::expr::rewrite_array;
29 use crate::lists::{itemize_list, write_list, ListFormatting};
31 use crate::rewrite::{Rewrite, RewriteContext};
32 use crate::shape::{Indent, Shape};
33 use crate::source_map::SpanUtils;
34 use crate::spanned::Spanned;
36 format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
37 rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
39 use crate::visitor::FmtVisitor;
41 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
44 pub enum MacroPosition {
53 Expr(ptr::P<ast::Expr>),
55 Pat(ptr::P<ast::Pat>),
56 Item(ptr::P<ast::Item>),
57 Keyword(ast::Ident, Span),
61 fn is_item(&self) -> bool {
63 MacroArg::Item(..) => true,
69 impl Rewrite for ast::Item {
70 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
71 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
72 visitor.block_indent = shape.indent;
73 visitor.last_pos = self.span().lo();
74 visitor.visit_item(self);
75 Some(visitor.buffer.to_owned())
79 impl Rewrite for MacroArg {
80 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
82 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
83 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
84 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
85 MacroArg::Item(ref item) => item.rewrite(context, shape),
86 MacroArg::Keyword(ident, _) => Some(ident.to_string()),
91 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
92 macro_rules! parse_macro_arg {
93 ($macro_arg:ident, $parser:expr, $f:expr) => {
94 let mut cloned_parser = (*parser).clone();
95 match $parser(&mut cloned_parser) {
97 if parser.sess.span_diagnostic.has_errors() {
98 parser.sess.span_diagnostic.reset_err_count();
100 // Parsing succeeded.
101 *parser = cloned_parser;
102 return Some(MacroArg::$macro_arg($f(x)?));
107 parser.sess.span_diagnostic.reset_err_count();
115 |parser: &mut parse::parser::Parser<'b>| parser.parse_expr(),
116 |x: ptr::P<ast::Expr>| Some(x)
120 |parser: &mut parse::parser::Parser<'b>| parser.parse_ty(),
121 |x: ptr::P<ast::Ty>| Some(x)
125 |parser: &mut parse::parser::Parser<'b>| parser.parse_pat(None),
126 |x: ptr::P<ast::Pat>| Some(x)
128 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
131 |parser: &mut parse::parser::Parser<'b>| parser.parse_item(),
132 |x: Option<ptr::P<ast::Item>>| x
138 /// Rewrite macro name without using pretty-printer if possible.
139 fn rewrite_macro_name(
140 context: &RewriteContext<'_>,
142 extra_ident: Option<ast::Ident>,
144 let name = if path.segments.len() == 1 {
145 // Avoid using pretty-printer in the common case.
146 format!("{}!", rewrite_ident(context, path.segments[0].ident))
151 Some(ident) if ident != keywords::Invalid.ident() => format!("{} {}", name, ident),
156 // Use this on failing to format the macro call.
157 fn return_macro_parse_failure_fallback(
158 context: &RewriteContext<'_>,
161 ) -> Option<String> {
162 // Mark this as a failure however we format it
163 context.macro_rewrite_failure.replace(true);
165 // Heuristically determine whether the last line of the macro uses "Block" style
166 // rather than using "Visual" style, or another indentation style.
167 let is_like_block_indent_style = context
171 .map(|closing_line| {
172 closing_line.trim().chars().all(|ch| match ch {
173 '}' | ')' | ']' => true,
178 if is_like_block_indent_style {
179 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
182 // Return the snippet unmodified if the macro is not block-like
183 Some(context.snippet(span).to_owned())
186 struct InsideMacroGuard<'a> {
187 context: &'a RewriteContext<'a>,
191 impl<'a> InsideMacroGuard<'a> {
192 fn inside_macro_context(context: &'a RewriteContext<'_>) -> InsideMacroGuard<'a> {
193 let is_nested = context.inside_macro.replace(true);
194 InsideMacroGuard { context, is_nested }
198 impl<'a> Drop for InsideMacroGuard<'a> {
200 self.context.inside_macro.replace(self.is_nested);
204 pub fn rewrite_macro(
206 extra_ident: Option<ast::Ident>,
207 context: &RewriteContext<'_>,
209 position: MacroPosition,
210 ) -> Option<String> {
211 let should_skip = context
214 .contains(&context.snippet(mac.node.path.span).to_owned());
218 let guard = InsideMacroGuard::inside_macro_context(context);
220 rewrite_macro_inner(mac, extra_ident, context, shape, position, guard.is_nested);
221 if result.is_none() {
222 context.macro_rewrite_failure.replace(true);
228 fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
229 for &keyword in RUST_KEYWORDS.iter() {
230 if parser.token.is_keyword(keyword)
231 && parser.look_ahead(1, |t| {
233 || *t == Token::Comma
234 || *t == Token::CloseDelim(DelimToken::NoDelim)
237 let macro_arg = MacroArg::Keyword(keyword.ident(), parser.span);
239 return Some(macro_arg);
245 pub fn rewrite_macro_inner(
247 extra_ident: Option<ast::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.inside_macro.replace(false);
256 return expr.rewrite(context, shape);
260 let original_style = macro_style(mac, context);
262 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
264 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
270 let ts: TokenStream = mac.node.stream();
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::Paren => Some(format!("{}()", macro_name)),
278 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
279 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
283 // Format well-known macros which cannot be parsed as a valid AST.
284 if macro_name == "lazy_static!" && !has_comment {
285 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
290 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
291 let mut arg_vec = Vec::new();
292 let mut vec_with_semi = false;
293 let mut trailing_comma = false;
295 if DelimToken::Brace != style {
297 if let Some(arg) = parse_macro_arg(&mut parser) {
299 } else if let Some(arg) = check_keyword(&mut parser) {
302 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
309 // Try to parse `vec![expr; expr]`
310 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
312 if parser.token != Token::Eof {
313 match parse_macro_arg(&mut parser) {
317 if parser.token == Token::Eof && arg_vec.len() == 2 {
318 vec_with_semi = true;
323 return return_macro_parse_failure_fallback(
332 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
334 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
335 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span),
340 if parser.token == Token::Eof {
341 trailing_comma = true;
347 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
348 return rewrite_macro_with_items(
360 DelimToken::Paren => {
361 // Format macro invocation as function call, preserve the trailing
362 // comma because not all macros support them.
363 overflow::rewrite_with_parens(
369 context.config.width_heuristics().fn_call_width,
371 Some(SeparatorTactic::Always)
373 Some(SeparatorTactic::Never)
376 .map(|rw| match position {
377 MacroPosition::Item => format!("{};", rw),
381 DelimToken::Bracket => {
382 // Handle special case: `vec![expr; expr]`
384 let mac_shape = shape.offset_left(macro_name.len())?;
385 // 8 = `vec![]` + `; `
386 let total_overhead = 8;
387 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
388 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
389 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
390 if !lhs.contains('\n')
391 && !rhs.contains('\n')
392 && lhs.len() + rhs.len() + total_overhead <= shape.width
394 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
399 nested_shape.indent.to_string_with_newline(context.config),
401 nested_shape.indent.to_string_with_newline(context.config),
403 shape.indent.to_string_with_newline(context.config),
407 // If we are rewriting `vec!` macro or other special macros,
408 // then we can rewrite this as an usual array literal.
409 // Otherwise, we must preserve the original existence of trailing comma.
410 let macro_name = ¯o_name.as_str();
411 let mut force_trailing_comma = if trailing_comma {
412 Some(SeparatorTactic::Always)
414 Some(SeparatorTactic::Never)
416 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
417 context.inside_macro.replace(false);
418 if context.use_block_indent() {
419 force_trailing_comma = Some(SeparatorTactic::Vertical);
422 let rewrite = rewrite_array(
428 force_trailing_comma,
429 Some(original_style),
431 let comma = match position {
432 MacroPosition::Item => ";",
436 Some(format!("{}{}", rewrite, comma))
439 DelimToken::Brace => {
440 // For macro invocations with braces, always put a space between
441 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
442 // anything in between the braces (for now).
443 let snippet = context.snippet(mac.span).trim_start_matches(|c| c != '{');
444 match trim_left_preserve_layout(snippet, shape.indent, &context.config) {
445 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
446 None => Some(format!("{} {}", macro_name, snippet)),
453 pub fn rewrite_macro_def(
454 context: &RewriteContext<'_>,
459 vis: &ast::Visibility,
461 ) -> Option<String> {
462 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
463 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
467 let mut parser = MacroParser::new(def.stream().into_trees());
468 let parsed_def = match parser.parse() {
470 None => return snippet,
473 let mut result = if def.legacy {
474 String::from("macro_rules!")
476 format!("{}macro", format_visibility(context, vis))
480 result += rewrite_ident(context, ident);
482 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
484 let arm_shape = if multi_branch_style {
486 .block_indent(context.config.tab_spaces())
487 .with_max_width(context.config)
492 let branch_items = itemize_list(
493 context.snippet_provider,
494 parsed_def.branches.iter(),
497 |branch| branch.span.lo(),
498 |branch| branch.span.hi(),
499 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
501 // if the rewrite returned None because a macro could not be rewritten, then return the
503 None if *context.macro_rewrite_failure.borrow() => {
504 Some(context.snippet(branch.body).trim().to_string())
508 context.snippet_provider.span_after(span, "{"),
512 .collect::<Vec<_>>();
514 let fmt = ListFormatting::new(arm_shape, context.config)
515 .separator(if def.legacy { ";" } else { "" })
516 .trailing_separator(SeparatorTactic::Always)
517 .preserve_newline(true);
519 if multi_branch_style {
521 result += &arm_shape.indent.to_string_with_newline(context.config);
524 match write_list(&branch_items, &fmt) {
525 Some(ref s) => result += s,
526 None => return snippet,
529 if multi_branch_style {
530 result += &indent.to_string_with_newline(context.config);
537 fn register_metavariable(
538 map: &mut HashMap<String, String>,
543 let mut new_name = String::new();
544 let mut old_name = String::new();
547 for _ in 0..(dollar_count - 1) {
552 new_name.push_str(&name);
553 old_name.push_str(&name);
555 result.push_str(&new_name);
556 map.insert(old_name, new_name);
559 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
560 // aren't causing problems.
561 // This should also work for escaped `$` variables, where we leave earlier `$`s.
562 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
563 // Each substitution will require five or six extra bytes.
564 let mut result = String::with_capacity(input.len() + 64);
565 let mut substs = HashMap::new();
566 let mut dollar_count = 0;
567 let mut cur_name = String::new();
569 for (kind, c) in CharClasses::new(input.chars()) {
570 if kind != FullCodeCharKind::Normal {
574 } else if dollar_count == 0 {
576 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
577 // Terminates a name following one or more dollars.
578 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
583 } else if c == '(' && cur_name.is_empty() {
584 // FIXME: Support macro def with repeat.
586 } else if c.is_alphanumeric() || c == '_' {
591 if !cur_name.is_empty() {
592 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
595 debug!("replace_names `{}` {:?}", result, substs);
597 Some((result, substs))
600 #[derive(Debug, Clone)]
602 /// e.g., `$x: expr`.
603 MetaVariable(ast::Ident, String),
604 /// e.g., `$($foo: expr),*`
606 /// `()`, `[]` or `{}`.
608 /// Inner arguments inside delimiters.
610 /// Something after the closing delimiter and the repeat token, if available.
611 Option<Box<ParsedMacroArg>>,
612 /// The repeat token. This could be one of `*`, `+` or `?`.
615 /// e.g., `[derive(Debug)]`
616 Delimited(DelimToken, Vec<ParsedMacroArg>),
617 /// A possible separator. e.g., `,` or `;`.
618 Separator(String, String),
619 /// Other random stuff that does not fit to other kinds.
620 /// e.g., `== foo` in `($x: expr == foo)`.
621 Other(String, String),
624 fn delim_token_to_str(
625 context: &RewriteContext<'_>,
626 delim_token: DelimToken,
628 use_multiple_lines: bool,
629 inner_is_empty: bool,
630 ) -> (String, String) {
631 let (lhs, rhs) = match delim_token {
632 DelimToken::Paren => ("(", ")"),
633 DelimToken::Bracket => ("[", "]"),
634 DelimToken::Brace => {
635 if inner_is_empty || use_multiple_lines {
641 DelimToken::NoDelim => ("", ""),
643 if use_multiple_lines {
644 let indent_str = shape.indent.to_string_with_newline(context.config);
645 let nested_indent_str = shape
647 .block_indent(context.config)
648 .to_string_with_newline(context.config);
650 format!("{}{}", lhs, nested_indent_str),
651 format!("{}{}", indent_str, rhs),
654 (lhs.to_owned(), rhs.to_owned())
659 fn starts_with_brace(&self) -> bool {
661 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
662 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
667 fn starts_with_dollar(&self) -> bool {
669 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
674 fn ends_with_space(&self) -> bool {
676 MacroArgKind::Separator(..) => true,
681 fn has_meta_var(&self) -> bool {
683 MacroArgKind::MetaVariable(..) => true,
684 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
691 context: &RewriteContext<'_>,
693 use_multiple_lines: bool,
694 ) -> Option<String> {
695 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
696 let inner = wrap_macro_args(context, args, shape)?;
697 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
698 if lhs.len() + inner.len() + rhs.len() <= shape.width {
699 return Some((lhs, inner, rhs));
702 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
703 let nested_shape = shape
704 .block_indent(context.config.tab_spaces())
705 .with_max_width(context.config);
706 let inner = wrap_macro_args(context, args, nested_shape)?;
707 Some((lhs, inner, rhs))
711 MacroArgKind::MetaVariable(ty, ref name) => {
712 Some(format!("${}:{}", name, ty.name.as_str()))
714 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
715 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
716 let another = another
718 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
719 .unwrap_or_else(|| "".to_owned());
720 let repeat_tok = pprust::token_to_string(tok);
722 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
724 MacroArgKind::Delimited(delim_tok, ref args) => {
725 rewrite_delimited_inner(delim_tok, args)
726 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
728 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
729 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
734 #[derive(Debug, Clone)]
735 struct ParsedMacroArg {
740 impl ParsedMacroArg {
743 context: &RewriteContext<'_>,
745 use_multiple_lines: bool,
746 ) -> Option<String> {
747 self.kind.rewrite(context, shape, use_multiple_lines)
751 /// Parses macro arguments on macro def.
752 struct MacroArgParser {
753 /// Either a name of the next metavariable, a separator, or junk.
755 /// The start position on the current buffer.
757 /// The first token of the current buffer.
759 /// `true` if we are parsing a metavariable or a repeat.
761 /// The position of the last token.
763 /// The last token parsed.
765 /// Holds the parsed arguments.
766 result: Vec<ParsedMacroArg>,
769 fn last_tok(tt: &TokenTree) -> Token {
771 TokenTree::Token(_, ref t) => t.clone(),
772 TokenTree::Delimited(_, delim, _) => Token::CloseDelim(delim),
776 impl MacroArgParser {
777 pub fn new() -> MacroArgParser {
783 last_tok: Token::Eof,
784 start_tok: Token::Eof,
789 fn set_last_tok(&mut self, tok: &TokenTree) {
790 self.hi = tok.span().hi();
791 self.last_tok = last_tok(tok);
794 fn add_separator(&mut self) {
795 let prefix = if self.need_space_prefix() {
800 self.result.push(ParsedMacroArg {
801 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
802 span: mk_sp(self.lo, self.hi),
807 fn add_other(&mut self) {
808 let prefix = if self.need_space_prefix() {
813 self.result.push(ParsedMacroArg {
814 kind: MacroArgKind::Other(self.buf.clone(), prefix),
815 span: mk_sp(self.lo, self.hi),
820 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
822 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
823 self.result.push(ParsedMacroArg {
824 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
825 span: mk_sp(self.lo, sp.hi()),
829 self.is_meta_var = false;
836 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
837 self.result.push(ParsedMacroArg {
838 kind: MacroArgKind::Delimited(delim, inner),
846 inner: Vec<ParsedMacroArg>,
851 let mut buffer = String::new();
852 let mut first = false;
853 let mut lo = span.lo();
854 let mut hi = span.hi();
856 // Parse '*', '+' or '?.
858 self.set_last_tok(&tok);
861 lo = tok.span().lo();
865 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
866 | TokenTree::Token(_, Token::Question)
867 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
870 TokenTree::Token(sp, ref t) => {
871 buffer.push_str(&pprust::token_to_string(t));
878 // There could be some random stuff between ')' and '*', '+' or '?'.
879 let another = if buffer.trim().is_empty() {
882 Some(Box::new(ParsedMacroArg {
883 kind: MacroArgKind::Other(buffer, "".to_owned()),
888 self.result.push(ParsedMacroArg {
889 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
890 span: mk_sp(self.lo, self.hi),
895 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
896 if self.buf.is_empty() {
898 self.start_tok = t.clone();
900 let needs_space = match next_space(&self.last_tok) {
901 SpaceState::Ident => ident_like(t),
902 SpaceState::Punctuation => !ident_like(t),
903 SpaceState::Always => true,
904 SpaceState::Never => false,
906 if force_space_before(t) || needs_space {
911 self.buf.push_str(&pprust::token_to_string(t));
914 fn need_space_prefix(&self) -> bool {
915 if self.result.is_empty() {
919 let last_arg = self.result.last().unwrap();
920 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
921 if ident_like(&self.start_tok) {
924 if self.start_tok == Token::Colon {
929 if force_space_before(&self.start_tok) {
936 /// Returns a collection of parsed macro def's arguments.
937 pub fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
938 let stream: TokenStream = tokens.into();
939 let mut iter = stream.trees();
941 while let Some(tok) = iter.next() {
943 TokenTree::Token(sp, Token::Dollar) => {
944 // We always want to add a separator before meta variables.
945 if !self.buf.is_empty() {
946 self.add_separator();
949 // Start keeping the name of this metavariable in the buffer.
950 self.is_meta_var = true;
952 self.start_tok = Token::Dollar;
954 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
955 self.add_meta_variable(&mut iter)?;
957 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
958 TokenTree::Delimited(delimited_span, delimited, ref tts) => {
959 if !self.buf.is_empty() {
960 if next_space(&self.last_tok) == SpaceState::Always {
961 self.add_separator();
967 // Parse the stuff inside delimiters.
968 let mut parser = MacroArgParser::new();
969 parser.lo = delimited_span.open.lo();
970 let delimited_arg = parser.parse(tts.clone())?;
972 let span = delimited_span.entire();
973 if self.is_meta_var {
974 self.add_repeat(delimited_arg, delimited, &mut iter, span)?;
975 self.is_meta_var = false;
977 self.add_delimited(delimited_arg, delimited, span);
982 self.set_last_tok(&tok);
985 // We are left with some stuff in the buffer. Since there is nothing
986 // left to separate, add this as `Other`.
987 if !self.buf.is_empty() {
996 context: &RewriteContext<'_>,
997 args: &[ParsedMacroArg],
999 ) -> Option<String> {
1000 wrap_macro_args_inner(context, args, shape, false)
1001 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
1004 fn wrap_macro_args_inner(
1005 context: &RewriteContext<'_>,
1006 args: &[ParsedMacroArg],
1008 use_multiple_lines: bool,
1009 ) -> Option<String> {
1010 let mut result = String::with_capacity(128);
1011 let mut iter = args.iter().peekable();
1012 let indent_str = shape.indent.to_string_with_newline(context.config);
1014 while let Some(ref arg) = iter.next() {
1015 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1017 if use_multiple_lines
1018 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1020 if arg.kind.ends_with_space() {
1023 result.push_str(&indent_str);
1024 } else if let Some(ref next_arg) = iter.peek() {
1025 let space_before_dollar =
1026 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1027 let space_before_brace = next_arg.kind.starts_with_brace();
1028 if space_before_dollar || space_before_brace {
1034 if !use_multiple_lines && result.len() >= shape.width {
1041 // This is a bit sketchy. The token rules probably need tweaking, but it works
1042 // for some common cases. I hope the basic logic is sufficient. Note that the
1043 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1044 // and `(`/`)` have special meaning.
1046 // We always try and format on one line.
1047 // FIXME: Use multi-line when every thing does not fit on one line.
1048 fn format_macro_args(
1049 context: &RewriteContext<'_>,
1052 ) -> Option<String> {
1053 if !context.config.format_macro_matchers() {
1054 let token_stream: TokenStream = toks.into();
1055 let span = span_for_token_stream(&token_stream);
1056 return Some(match span {
1057 Some(span) => context.snippet(span).to_owned(),
1058 None => String::new(),
1061 let parsed_args = MacroArgParser::new().parse(toks)?;
1062 wrap_macro_args(context, &parsed_args, shape)
1065 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1066 token_stream.trees().next().map(|tt| tt.span())
1069 // We should insert a space if the next token is a:
1070 #[derive(Copy, Clone, PartialEq)]
1074 Ident, // Or ident/literal-like thing.
1078 fn force_space_before(tok: &Token) -> bool {
1079 debug!("tok: force_space_before {:?}", tok);
1100 | Token::Dollar => true,
1105 fn ident_like(tok: &Token) -> bool {
1107 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1112 fn next_space(tok: &Token) -> SpaceState {
1113 debug!("next_space: {:?}", tok);
1117 | Token::BinOp(BinOpToken::And)
1125 | Token::Question => SpaceState::Punctuation,
1130 | Token::OpenDelim(_)
1131 | Token::CloseDelim(_)
1132 | Token::Whitespace => SpaceState::Never,
1134 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1136 _ => SpaceState::Always,
1140 /// Tries to convert a macro use into a short hand try expression. Returns `None`
1141 /// when the macro is not an instance of `try!` (or parsing the inner expression
1143 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> {
1144 if &mac.node.path.to_string() == "try" {
1145 let ts: TokenStream = mac.node.tts.clone().into();
1146 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1149 id: ast::NodeId::root(), // dummy value
1150 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1151 span: mac.span, // incorrect span, but shouldn't matter too much
1152 attrs: ThinVec::new(),
1159 fn macro_style(mac: &ast::Mac, context: &RewriteContext<'_>) -> DelimToken {
1160 let snippet = context.snippet(mac.span);
1161 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1162 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1163 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1165 if paren_pos < bracket_pos && paren_pos < brace_pos {
1167 } else if bracket_pos < brace_pos {
1174 // A very simple parser that just parses a macros 2.0 definition into its branches.
1175 // Currently we do not attempt to parse any further than that.
1177 struct MacroParser {
1182 // (`(` ... `)` `=>` `{` ... `}`)*
1183 fn parse(&mut self) -> Option<Macro> {
1184 let mut branches = vec![];
1185 while self.toks.look_ahead(1).is_some() {
1186 branches.push(self.parse_branch()?);
1189 Some(Macro { branches })
1192 // `(` ... `)` `=>` `{` ... `}`
1193 fn parse_branch(&mut self) -> Option<MacroBranch> {
1194 let tok = self.toks.next()?;
1195 let (lo, args_paren_kind) = match tok {
1196 TokenTree::Token(..) => return None,
1197 TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1199 let args = tok.joint().into();
1200 match self.toks.next()? {
1201 TokenTree::Token(_, Token::FatArrow) => {}
1204 let (mut hi, body, whole_body) = match self.toks.next()? {
1205 TokenTree::Token(..) => return None,
1206 TokenTree::Delimited(delimited_span, ..) => {
1207 let data = delimited_span.entire().data();
1210 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1211 delimited_span.entire(),
1215 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1220 span: mk_sp(lo, hi),
1229 // A parsed macros 2.0 macro definition.
1231 branches: Vec<MacroBranch>,
1234 // FIXME: it would be more efficient to use references to the token streams
1235 // rather than clone them, if we can make the borrowing work out.
1236 struct MacroBranch {
1238 args_paren_kind: DelimToken,
1247 context: &RewriteContext<'_>,
1249 multi_branch_style: bool,
1250 ) -> Option<String> {
1251 // Only attempt to format function-like macros.
1252 if self.args_paren_kind != DelimToken::Paren {
1253 // FIXME(#1539): implement for non-sugared macros.
1258 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1260 if multi_branch_style {
1264 if !context.config.format_macro_bodies() {
1266 result += context.snippet(self.whole_body);
1267 return Some(result);
1270 // The macro body is the most interesting part. It might end up as various
1271 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1272 // parsed as regular Rust code (and note that these can be escaped using
1273 // `$$`). We'll try and format like an AST node, but we'll substitute
1274 // variables for new names with the same length first.
1276 let old_body = context.snippet(self.body).trim();
1277 let (body_str, substs) = replace_names(old_body)?;
1278 let has_block_body = old_body.starts_with('{');
1280 let mut config = context.config.clone();
1281 config.set().hide_parse_errors(true);
1285 let body_indent = if has_block_body {
1288 shape.indent.block_indent(&config)
1290 let new_width = config.max_width() - body_indent.width();
1291 config.set().max_width(new_width);
1293 // First try to format as items, then as statements.
1294 let new_body_snippet = match crate::format_snippet(&body_str, &config) {
1295 Some(new_body) => new_body,
1297 let new_width = new_width + config.tab_spaces();
1298 config.set().max_width(new_width);
1299 match crate::format_code_block(&body_str, &config) {
1300 Some(new_body) => new_body,
1301 None => return None,
1305 let new_body = wrap_str(
1306 new_body_snippet.snippet.to_string(),
1311 // Indent the body since it is in a block.
1312 let indent_str = body_indent.to_string(&config);
1313 let mut new_body = LineClasses::new(new_body.trim_end())
1316 (String::new(), true),
1317 |(mut s, need_indent), (i, (kind, ref l))| {
1318 if !is_empty_line(l)
1320 && !new_body_snippet.is_line_non_formatted(i + 1)
1324 (s + l + "\n", indent_next_line(kind, &l, &config))
1329 // Undo our replacement of macro variables.
1330 // FIXME: this could be *much* more efficient.
1331 for (old, new) in &substs {
1332 if old_body.find(new).is_some() {
1333 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1336 new_body = new_body.replace(new, old);
1340 result += new_body.trim();
1341 } else if !new_body.is_empty() {
1343 result += &new_body;
1344 result += &shape.indent.to_string(&config);
1353 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1355 /// # Expected syntax
1359 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1360 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1362 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1365 fn format_lazy_static(
1366 context: &RewriteContext<'_>,
1369 ) -> Option<String> {
1370 let mut result = String::with_capacity(1024);
1371 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1372 let nested_shape = shape
1373 .block_indent(context.config.tab_spaces())
1374 .with_max_width(context.config);
1376 result.push_str("lazy_static! {");
1377 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1379 macro_rules! parse_or {
1380 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1381 match parser.$method($($arg,)*) {
1383 if parser.sess.span_diagnostic.has_errors() {
1384 parser.sess.span_diagnostic.reset_err_count();
1392 parser.sess.span_diagnostic.reset_err_count();
1399 while parser.token != Token::Eof {
1400 // Parse a `lazy_static!` item.
1401 let vis = crate::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1402 parser.eat_keyword(keywords::Static);
1403 parser.eat_keyword(keywords::Ref);
1404 let id = parse_or!(parse_ident);
1405 parser.eat(&Token::Colon);
1406 let ty = parse_or!(parse_ty);
1407 parser.eat(&Token::Eq);
1408 let expr = parse_or!(parse_expr);
1409 parser.eat(&Token::Semi);
1411 // Rewrite as a static item.
1412 let mut stmt = String::with_capacity(128);
1413 stmt.push_str(&format!(
1414 "{}static ref {}: {} =",
1417 ty.rewrite(context, nested_shape)?
1419 result.push_str(&crate::expr::rewrite_assign_rhs(
1423 nested_shape.sub_width(1)?,
1426 if parser.token != Token::Eof {
1427 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1431 result.push_str(&shape.indent.to_string_with_newline(context.config));
1437 fn rewrite_macro_with_items(
1438 context: &RewriteContext<'_>,
1443 position: MacroPosition,
1445 ) -> Option<String> {
1446 let (opener, closer) = match style {
1447 DelimToken::Paren => ("(", ")"),
1448 DelimToken::Bracket => ("[", "]"),
1449 DelimToken::Brace => (" {", "}"),
1452 let trailing_semicolon = match style {
1453 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1457 let mut visitor = FmtVisitor::from_context(context);
1458 visitor.block_indent = shape.indent.block_indent(context.config);
1459 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1461 let item = match item {
1462 MacroArg::Item(item) => item,
1465 visitor.visit_item(&item);
1468 let mut result = String::with_capacity(256);
1469 result.push_str(¯o_name);
1470 result.push_str(opener);
1471 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1472 result.push_str(visitor.buffer.trim());
1473 result.push_str(&shape.indent.to_string_with_newline(context.config));
1474 result.push_str(closer);
1475 result.push_str(trailing_semicolon);
1479 const RUST_KEYWORDS: [keywords::Keyword; 60] = [
1481 keywords::DollarCrate,
1482 keywords::Underscore,
1507 keywords::SelfLower,
1508 keywords::SelfUpper,
1533 keywords::UnderscoreLifetime,
1534 keywords::StaticLifetime,
1538 keywords::Existential,