1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Format list-like macro invocations. These are invocations whose token trees
12 // can be interpreted as expressions and separated by commas.
13 // Note that these token trees do not actually have to be interpreted as
14 // expressions by the compiler. An example of an invocation we would reformat is
15 // foo!( x, y, z ). The token x may represent an identifier in the code, but we
16 // interpreted as an expression.
17 // Macro uses which are not-list like, such as bar!(key => val), will not be
19 // List-like invocations with parentheses will be formatted as function calls,
20 // and those with brackets will be formatted as array literals.
22 use std::collections::HashMap;
24 use syntax::parse::new_parser_from_tts;
25 use syntax::parse::parser::Parser;
26 use syntax::parse::token::{BinOpToken, DelimToken, Token};
27 use syntax::print::pprust;
28 use syntax::source_map::{BytePos, Span};
29 use syntax::symbol::keywords;
30 use syntax::tokenstream::{Cursor, TokenStream, TokenTree};
32 use syntax::{ast, parse, ptr};
35 contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses,
37 use crate::config::lists::*;
38 use crate::expr::rewrite_array;
39 use crate::lists::{itemize_list, write_list, ListFormatting};
41 use crate::rewrite::{Rewrite, RewriteContext};
42 use crate::shape::{Indent, Shape};
43 use crate::source_map::SpanUtils;
44 use crate::spanned::Spanned;
46 format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces,
47 rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt,
49 use crate::visitor::FmtVisitor;
51 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub enum MacroPosition {
63 Expr(ptr::P<ast::Expr>),
65 Pat(ptr::P<ast::Pat>),
66 Item(ptr::P<ast::Item>),
67 Keyword(ast::Ident, Span),
71 fn is_item(&self) -> bool {
73 MacroArg::Item(..) => true,
79 impl Rewrite for ast::Item {
80 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
81 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
82 visitor.block_indent = shape.indent;
83 visitor.last_pos = self.span().lo();
84 visitor.visit_item(self);
85 Some(visitor.buffer.to_owned())
89 impl Rewrite for MacroArg {
90 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
92 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
93 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
94 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
95 MacroArg::Item(ref item) => item.rewrite(context, shape),
96 MacroArg::Keyword(ident, _) => Some(ident.to_string()),
101 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
102 macro_rules! parse_macro_arg {
103 ($macro_arg:ident, $parser:expr, $f:expr) => {
104 let mut cloned_parser = (*parser).clone();
105 match $parser(&mut cloned_parser) {
107 if parser.sess.span_diagnostic.has_errors() {
108 parser.sess.span_diagnostic.reset_err_count();
110 // Parsing succeeded.
111 *parser = cloned_parser;
112 return Some(MacroArg::$macro_arg($f(x)?));
117 parser.sess.span_diagnostic.reset_err_count();
125 |parser: &mut parse::parser::Parser<'b>| parser.parse_expr(),
126 |x: ptr::P<ast::Expr>| Some(x)
130 |parser: &mut parse::parser::Parser<'b>| parser.parse_ty(),
131 |x: ptr::P<ast::Ty>| Some(x)
135 |parser: &mut parse::parser::Parser<'b>| parser.parse_pat(None),
136 |x: ptr::P<ast::Pat>| Some(x)
138 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
141 |parser: &mut parse::parser::Parser<'b>| parser.parse_item(),
142 |x: Option<ptr::P<ast::Item>>| x
148 /// Rewrite macro name without using pretty-printer if possible.
149 fn rewrite_macro_name(
150 context: &RewriteContext<'_>,
152 extra_ident: Option<ast::Ident>,
154 let name = if path.segments.len() == 1 {
155 // Avoid using pretty-printer in the common case.
156 format!("{}!", rewrite_ident(context, path.segments[0].ident))
161 Some(ident) if ident != keywords::Invalid.ident() => format!("{} {}", name, ident),
166 // Use this on failing to format the macro call.
167 fn return_macro_parse_failure_fallback(
168 context: &RewriteContext<'_>,
171 ) -> Option<String> {
172 // Mark this as a failure however we format it
173 context.macro_rewrite_failure.replace(true);
175 // Heuristically determine whether the last line of the macro uses "Block" style
176 // rather than using "Visual" style, or another indentation style.
177 let is_like_block_indent_style = context
181 .map(|closing_line| {
182 closing_line.trim().chars().all(|ch| match ch {
183 '}' | ')' | ']' => true,
188 if is_like_block_indent_style {
189 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
192 // Return the snippet unmodified if the macro is not block-like
193 Some(context.snippet(span).to_owned())
196 struct InsideMacroGuard<'a> {
197 context: &'a RewriteContext<'a>,
201 impl<'a> InsideMacroGuard<'a> {
202 fn inside_macro_context(context: &'a RewriteContext<'_>) -> InsideMacroGuard<'a> {
203 let is_nested = context.inside_macro.replace(true);
204 InsideMacroGuard { context, is_nested }
208 impl<'a> Drop for InsideMacroGuard<'a> {
210 self.context.inside_macro.replace(self.is_nested);
214 pub fn rewrite_macro(
216 extra_ident: Option<ast::Ident>,
217 context: &RewriteContext<'_>,
219 position: MacroPosition,
220 ) -> Option<String> {
221 let guard = InsideMacroGuard::inside_macro_context(context);
222 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position, guard.is_nested);
223 if result.is_none() {
224 context.macro_rewrite_failure.replace(true);
229 fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
230 for &keyword in RUST_KEYWORDS.iter() {
231 if parser.token.is_keyword(keyword)
232 && parser.look_ahead(1, |t| {
234 || *t == Token::Comma
235 || *t == Token::CloseDelim(DelimToken::NoDelim)
238 let macro_arg = MacroArg::Keyword(keyword.ident(), parser.span);
240 return Some(macro_arg);
246 pub fn rewrite_macro_inner(
248 extra_ident: Option<ast::Ident>,
249 context: &RewriteContext<'_>,
251 position: MacroPosition,
252 is_nested_macro: bool,
253 ) -> Option<String> {
254 if context.config.use_try_shorthand() {
255 if let Some(expr) = convert_try_mac(mac, context) {
256 context.inside_macro.replace(false);
257 return expr.rewrite(context, shape);
261 let original_style = macro_style(mac, context);
263 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
265 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
271 let ts: TokenStream = mac.node.stream();
272 let has_comment = contains_comment(context.snippet(mac.span));
273 if ts.is_empty() && !has_comment {
275 DelimToken::Paren if position == MacroPosition::Item => {
276 Some(format!("{}();", macro_name))
278 DelimToken::Paren => Some(format!("{}()", macro_name)),
279 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
280 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
284 // Format well-known macros which cannot be parsed as a valid AST.
285 if macro_name == "lazy_static!" && !has_comment {
286 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
291 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
292 let mut arg_vec = Vec::new();
293 let mut vec_with_semi = false;
294 let mut trailing_comma = false;
296 if DelimToken::Brace != style {
298 if let Some(arg) = parse_macro_arg(&mut parser) {
300 } else if let Some(arg) = check_keyword(&mut parser) {
303 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
310 // Try to parse `vec![expr; expr]`
311 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
313 if parser.token != Token::Eof {
314 match parse_macro_arg(&mut parser) {
318 if parser.token == Token::Eof && arg_vec.len() == 2 {
319 vec_with_semi = true;
324 return return_macro_parse_failure_fallback(
333 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
335 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
336 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span),
341 if parser.token == Token::Eof {
342 trailing_comma = true;
348 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
349 return rewrite_macro_with_items(
361 DelimToken::Paren => {
362 // Format macro invocation as function call, preserve the trailing
363 // comma because not all macros support them.
364 overflow::rewrite_with_parens(
370 context.config.width_heuristics().fn_call_width,
372 Some(SeparatorTactic::Always)
374 Some(SeparatorTactic::Never)
377 .map(|rw| match position {
378 MacroPosition::Item => format!("{};", rw),
382 DelimToken::Bracket => {
383 // Handle special case: `vec![expr; expr]`
385 let mac_shape = shape.offset_left(macro_name.len())?;
386 // 8 = `vec![]` + `; `
387 let total_overhead = 8;
388 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
389 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
390 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
391 if !lhs.contains('\n')
392 && !rhs.contains('\n')
393 && lhs.len() + rhs.len() + total_overhead <= shape.width
395 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
400 nested_shape.indent.to_string_with_newline(context.config),
402 nested_shape.indent.to_string_with_newline(context.config),
404 shape.indent.to_string_with_newline(context.config),
408 // If we are rewriting `vec!` macro or other special macros,
409 // then we can rewrite this as an usual array literal.
410 // Otherwise, we must preserve the original existence of trailing comma.
411 let macro_name = ¯o_name.as_str();
412 let mut force_trailing_comma = if trailing_comma {
413 Some(SeparatorTactic::Always)
415 Some(SeparatorTactic::Never)
417 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
418 context.inside_macro.replace(false);
419 if context.use_block_indent() {
420 force_trailing_comma = Some(SeparatorTactic::Vertical);
423 let rewrite = rewrite_array(
429 force_trailing_comma,
430 Some(original_style),
432 let comma = match position {
433 MacroPosition::Item => ";",
437 Some(format!("{}{}", rewrite, comma))
440 DelimToken::Brace => {
441 // For macro invocations with braces, always put a space between
442 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
443 // anything in between the braces (for now).
444 let snippet = context.snippet(mac.span);
445 let macro_raw = snippet.split_at(snippet.find('!')? + 1).1.trim_start();
446 match trim_left_preserve_layout(macro_raw, shape.indent, &context.config) {
447 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
448 None => Some(format!("{} {}", macro_name, macro_raw)),
455 pub fn rewrite_macro_def(
456 context: &RewriteContext<'_>,
461 vis: &ast::Visibility,
463 ) -> Option<String> {
464 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
465 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
469 let mut parser = MacroParser::new(def.stream().into_trees());
470 let parsed_def = match parser.parse() {
472 None => return snippet,
475 let mut result = if def.legacy {
476 String::from("macro_rules!")
478 format!("{}macro", format_visibility(context, vis))
482 result += rewrite_ident(context, ident);
484 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
486 let arm_shape = if multi_branch_style {
488 .block_indent(context.config.tab_spaces())
489 .with_max_width(context.config)
494 let branch_items = itemize_list(
495 context.snippet_provider,
496 parsed_def.branches.iter(),
499 |branch| branch.span.lo(),
500 |branch| branch.span.hi(),
501 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
503 // if the rewrite returned None because a macro could not be rewritten, then return the
505 None if *context.macro_rewrite_failure.borrow() => {
506 Some(context.snippet(branch.body).trim().to_string())
510 context.snippet_provider.span_after(span, "{"),
514 .collect::<Vec<_>>();
516 let fmt = ListFormatting::new(arm_shape, context.config)
517 .separator(if def.legacy { ";" } else { "" })
518 .trailing_separator(SeparatorTactic::Always)
519 .preserve_newline(true);
521 if multi_branch_style {
523 result += &arm_shape.indent.to_string_with_newline(context.config);
526 match write_list(&branch_items, &fmt) {
527 Some(ref s) => result += s,
528 None => return snippet,
531 if multi_branch_style {
532 result += &indent.to_string_with_newline(context.config);
539 fn register_metavariable(
540 map: &mut HashMap<String, String>,
545 let mut new_name = String::new();
546 let mut old_name = String::new();
549 for _ in 0..(dollar_count - 1) {
554 new_name.push_str(&name);
555 old_name.push_str(&name);
557 result.push_str(&new_name);
558 map.insert(old_name, new_name);
561 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
562 // aren't causing problems.
563 // This should also work for escaped `$` variables, where we leave earlier `$`s.
564 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
565 // Each substitution will require five or six extra bytes.
566 let mut result = String::with_capacity(input.len() + 64);
567 let mut substs = HashMap::new();
568 let mut dollar_count = 0;
569 let mut cur_name = String::new();
571 for (kind, c) in CharClasses::new(input.chars()) {
572 if kind != FullCodeCharKind::Normal {
576 } else if dollar_count == 0 {
578 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
579 // Terminates a name following one or more dollars.
580 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
585 } else if c == '(' && cur_name.is_empty() {
586 // FIXME: Support macro def with repeat.
588 } else if c.is_alphanumeric() || c == '_' {
593 if !cur_name.is_empty() {
594 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
597 debug!("replace_names `{}` {:?}", result, substs);
599 Some((result, substs))
602 #[derive(Debug, Clone)]
605 MetaVariable(ast::Ident, String),
606 /// e.g. `$($foo: expr),*`
608 /// `()`, `[]` or `{}`.
610 /// Inner arguments inside delimiters.
612 /// Something after the closing delimiter and the repeat token, if available.
613 Option<Box<ParsedMacroArg>>,
614 /// The repeat token. This could be one of `*`, `+` or `?`.
617 /// e.g. `[derive(Debug)]`
618 Delimited(DelimToken, Vec<ParsedMacroArg>),
619 /// A possible separator. e.g. `,` or `;`.
620 Separator(String, String),
621 /// Other random stuff that does not fit to other kinds.
622 /// e.g. `== foo` in `($x: expr == foo)`.
623 Other(String, String),
626 fn delim_token_to_str(
627 context: &RewriteContext<'_>,
628 delim_token: DelimToken,
630 use_multiple_lines: bool,
631 inner_is_empty: bool,
632 ) -> (String, String) {
633 let (lhs, rhs) = match delim_token {
634 DelimToken::Paren => ("(", ")"),
635 DelimToken::Bracket => ("[", "]"),
636 DelimToken::Brace => {
637 if inner_is_empty || use_multiple_lines {
643 DelimToken::NoDelim => ("", ""),
645 if use_multiple_lines {
646 let indent_str = shape.indent.to_string_with_newline(context.config);
647 let nested_indent_str = shape
649 .block_indent(context.config)
650 .to_string_with_newline(context.config);
652 format!("{}{}", lhs, nested_indent_str),
653 format!("{}{}", indent_str, rhs),
656 (lhs.to_owned(), rhs.to_owned())
661 fn starts_with_brace(&self) -> bool {
663 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
664 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
669 fn starts_with_dollar(&self) -> bool {
671 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
676 fn ends_with_space(&self) -> bool {
678 MacroArgKind::Separator(..) => true,
683 fn has_meta_var(&self) -> bool {
685 MacroArgKind::MetaVariable(..) => true,
686 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
693 context: &RewriteContext<'_>,
695 use_multiple_lines: bool,
696 ) -> Option<String> {
697 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
698 let inner = wrap_macro_args(context, args, shape)?;
699 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
700 if lhs.len() + inner.len() + rhs.len() <= shape.width {
701 return Some((lhs, inner, rhs));
704 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
705 let nested_shape = shape
706 .block_indent(context.config.tab_spaces())
707 .with_max_width(context.config);
708 let inner = wrap_macro_args(context, args, nested_shape)?;
709 Some((lhs, inner, rhs))
713 MacroArgKind::MetaVariable(ty, ref name) => {
714 Some(format!("${}:{}", name, ty.name.as_str()))
716 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
717 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
718 let another = another
720 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
721 .unwrap_or_else(|| "".to_owned());
722 let repeat_tok = pprust::token_to_string(tok);
724 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
726 MacroArgKind::Delimited(delim_tok, ref args) => {
727 rewrite_delimited_inner(delim_tok, args)
728 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
730 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
731 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
736 #[derive(Debug, Clone)]
737 struct ParsedMacroArg {
742 impl ParsedMacroArg {
745 context: &RewriteContext<'_>,
747 use_multiple_lines: bool,
748 ) -> Option<String> {
749 self.kind.rewrite(context, shape, use_multiple_lines)
753 /// Parses macro arguments on macro def.
754 struct MacroArgParser {
755 /// Holds either a name of the next metavariable, a separator or a junk.
757 /// The start position on the current buffer.
759 /// The first token of the current buffer.
761 /// Set to true if we are parsing a metavariable or a repeat.
763 /// The position of the last token.
765 /// The last token parsed.
767 /// Holds the parsed arguments.
768 result: Vec<ParsedMacroArg>,
771 fn last_tok(tt: &TokenTree) -> Token {
773 TokenTree::Token(_, ref t) => t.clone(),
774 TokenTree::Delimited(_, delim, _) => Token::CloseDelim(delim),
778 impl MacroArgParser {
779 pub fn new() -> MacroArgParser {
785 last_tok: Token::Eof,
786 start_tok: Token::Eof,
791 fn set_last_tok(&mut self, tok: &TokenTree) {
792 self.hi = tok.span().hi();
793 self.last_tok = last_tok(tok);
796 fn add_separator(&mut self) {
797 let prefix = if self.need_space_prefix() {
802 self.result.push(ParsedMacroArg {
803 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
804 span: mk_sp(self.lo, self.hi),
809 fn add_other(&mut self) {
810 let prefix = if self.need_space_prefix() {
815 self.result.push(ParsedMacroArg {
816 kind: MacroArgKind::Other(self.buf.clone(), prefix),
817 span: mk_sp(self.lo, self.hi),
822 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
824 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
825 self.result.push(ParsedMacroArg {
826 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
827 span: mk_sp(self.lo, sp.hi()),
831 self.is_meta_var = false;
838 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
839 self.result.push(ParsedMacroArg {
840 kind: MacroArgKind::Delimited(delim, inner),
848 inner: Vec<ParsedMacroArg>,
853 let mut buffer = String::new();
854 let mut first = false;
855 let mut lo = span.lo();
856 let mut hi = span.hi();
858 // Parse '*', '+' or '?.
860 self.set_last_tok(&tok);
863 lo = tok.span().lo();
867 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
868 | TokenTree::Token(_, Token::Question)
869 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
872 TokenTree::Token(sp, ref t) => {
873 buffer.push_str(&pprust::token_to_string(t));
880 // There could be some random stuff between ')' and '*', '+' or '?'.
881 let another = if buffer.trim().is_empty() {
884 Some(Box::new(ParsedMacroArg {
885 kind: MacroArgKind::Other(buffer, "".to_owned()),
890 self.result.push(ParsedMacroArg {
891 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
892 span: mk_sp(self.lo, self.hi),
897 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
898 if self.buf.is_empty() {
900 self.start_tok = t.clone();
902 let needs_space = match next_space(&self.last_tok) {
903 SpaceState::Ident => ident_like(t),
904 SpaceState::Punctuation => !ident_like(t),
905 SpaceState::Always => true,
906 SpaceState::Never => false,
908 if force_space_before(t) || needs_space {
913 self.buf.push_str(&pprust::token_to_string(t));
916 fn need_space_prefix(&self) -> bool {
917 if self.result.is_empty() {
921 let last_arg = self.result.last().unwrap();
922 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
923 if ident_like(&self.start_tok) {
926 if self.start_tok == Token::Colon {
931 if force_space_before(&self.start_tok) {
938 /// Returns a collection of parsed macro def's arguments.
939 pub fn parse(mut self, tokens: TokenStream) -> Option<Vec<ParsedMacroArg>> {
940 let stream: TokenStream = tokens.into();
941 let mut iter = stream.trees();
943 while let Some(tok) = iter.next() {
945 TokenTree::Token(sp, Token::Dollar) => {
946 // We always want to add a separator before meta variables.
947 if !self.buf.is_empty() {
948 self.add_separator();
951 // Start keeping the name of this metavariable in the buffer.
952 self.is_meta_var = true;
954 self.start_tok = Token::Dollar;
956 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
957 self.add_meta_variable(&mut iter)?;
959 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
960 TokenTree::Delimited(delimited_span, delimited, ref tts) => {
961 if !self.buf.is_empty() {
962 if next_space(&self.last_tok) == SpaceState::Always {
963 self.add_separator();
969 // Parse the stuff inside delimiters.
970 let mut parser = MacroArgParser::new();
971 parser.lo = delimited_span.open.lo();
972 let delimited_arg = parser.parse(tts.clone())?;
974 let span = delimited_span.entire();
975 if self.is_meta_var {
976 self.add_repeat(delimited_arg, delimited, &mut iter, span)?;
977 self.is_meta_var = false;
979 self.add_delimited(delimited_arg, delimited, span);
984 self.set_last_tok(&tok);
987 // We are left with some stuff in the buffer. Since there is nothing
988 // left to separate, add this as `Other`.
989 if !self.buf.is_empty() {
998 context: &RewriteContext<'_>,
999 args: &[ParsedMacroArg],
1001 ) -> Option<String> {
1002 wrap_macro_args_inner(context, args, shape, false)
1003 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
1006 fn wrap_macro_args_inner(
1007 context: &RewriteContext<'_>,
1008 args: &[ParsedMacroArg],
1010 use_multiple_lines: bool,
1011 ) -> Option<String> {
1012 let mut result = String::with_capacity(128);
1013 let mut iter = args.iter().peekable();
1014 let indent_str = shape.indent.to_string_with_newline(context.config);
1016 while let Some(ref arg) = iter.next() {
1017 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
1019 if use_multiple_lines
1020 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1022 if arg.kind.ends_with_space() {
1025 result.push_str(&indent_str);
1026 } else if let Some(ref next_arg) = iter.peek() {
1027 let space_before_dollar =
1028 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1029 let space_before_brace = next_arg.kind.starts_with_brace();
1030 if space_before_dollar || space_before_brace {
1036 if !use_multiple_lines && result.len() >= shape.width {
1043 // This is a bit sketchy. The token rules probably need tweaking, but it works
1044 // for some common cases. I hope the basic logic is sufficient. Note that the
1045 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1046 // and `(`/`)` have special meaning.
1048 // We always try and format on one line.
1049 // FIXME: Use multi-line when every thing does not fit on one line.
1050 fn format_macro_args(
1051 context: &RewriteContext<'_>,
1054 ) -> Option<String> {
1055 if !context.config.format_macro_matchers() {
1056 let token_stream: TokenStream = toks.into();
1057 let span = span_for_token_stream(&token_stream);
1058 return Some(match span {
1059 Some(span) => context.snippet(span).to_owned(),
1060 None => String::new(),
1063 let parsed_args = MacroArgParser::new().parse(toks)?;
1064 wrap_macro_args(context, &parsed_args, shape)
1067 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1068 token_stream.trees().next().map(|tt| tt.span())
1071 // We should insert a space if the next token is a:
1072 #[derive(Copy, Clone, PartialEq)]
1076 Ident, // Or ident/literal-like thing.
1080 fn force_space_before(tok: &Token) -> bool {
1081 debug!("tok: force_space_before {:?}", tok);
1102 | Token::Dollar => true,
1107 fn ident_like(tok: &Token) -> bool {
1109 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1114 fn next_space(tok: &Token) -> SpaceState {
1115 debug!("next_space: {:?}", tok);
1119 | Token::BinOp(BinOpToken::And)
1127 | Token::Question => SpaceState::Punctuation,
1132 | Token::OpenDelim(_)
1133 | Token::CloseDelim(_)
1134 | Token::Whitespace => SpaceState::Never,
1136 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1138 _ => SpaceState::Always,
1142 /// Tries to convert a macro use into a short hand try expression. Returns None
1143 /// when the macro is not an instance of try! (or parsing the inner expression
1145 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext<'_>) -> Option<ast::Expr> {
1146 if &mac.node.path.to_string() == "try" {
1147 let ts: TokenStream = mac.node.tts.clone().into();
1148 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1151 id: ast::NodeId::root(), // dummy value
1152 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1153 span: mac.span, // incorrect span, but shouldn't matter too much
1154 attrs: ThinVec::new(),
1161 fn macro_style(mac: &ast::Mac, context: &RewriteContext<'_>) -> DelimToken {
1162 let snippet = context.snippet(mac.span);
1163 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1164 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1165 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1167 if paren_pos < bracket_pos && paren_pos < brace_pos {
1169 } else if bracket_pos < brace_pos {
1176 // A very simple parser that just parses a macros 2.0 definition into its branches.
1177 // Currently we do not attempt to parse any further than that.
1179 struct MacroParser {
1184 // (`(` ... `)` `=>` `{` ... `}`)*
1185 fn parse(&mut self) -> Option<Macro> {
1186 let mut branches = vec![];
1187 while self.toks.look_ahead(1).is_some() {
1188 branches.push(self.parse_branch()?);
1191 Some(Macro { branches })
1194 // `(` ... `)` `=>` `{` ... `}`
1195 fn parse_branch(&mut self) -> Option<MacroBranch> {
1196 let tok = self.toks.next()?;
1197 let (lo, args_paren_kind) = match tok {
1198 TokenTree::Token(..) => return None,
1199 TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d),
1201 let args = tok.joint().into();
1202 match self.toks.next()? {
1203 TokenTree::Token(_, Token::FatArrow) => {}
1206 let (mut hi, body, whole_body) = match self.toks.next()? {
1207 TokenTree::Token(..) => return None,
1208 TokenTree::Delimited(delimited_span, ..) => {
1209 let data = delimited_span.entire().data();
1212 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1213 delimited_span.entire(),
1217 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1222 span: mk_sp(lo, hi),
1231 // A parsed macros 2.0 macro definition.
1233 branches: Vec<MacroBranch>,
1236 // FIXME: it would be more efficient to use references to the token streams
1237 // rather than clone them, if we can make the borrowing work out.
1238 struct MacroBranch {
1240 args_paren_kind: DelimToken,
1249 context: &RewriteContext<'_>,
1251 multi_branch_style: bool,
1252 ) -> Option<String> {
1253 // Only attempt to format function-like macros.
1254 if self.args_paren_kind != DelimToken::Paren {
1255 // FIXME(#1539): implement for non-sugared macros.
1260 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1262 if multi_branch_style {
1266 if !context.config.format_macro_bodies() {
1268 result += context.snippet(self.whole_body);
1269 return Some(result);
1272 // The macro body is the most interesting part. It might end up as various
1273 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1274 // parsed as regular Rust code (and note that these can be escaped using
1275 // `$$`). We'll try and format like an AST node, but we'll substitute
1276 // variables for new names with the same length first.
1278 let old_body = context.snippet(self.body).trim();
1279 let (body_str, substs) = replace_names(old_body)?;
1280 let has_block_body = old_body.starts_with('{');
1282 let mut config = context.config.clone();
1283 config.set().hide_parse_errors(true);
1287 let body_indent = if has_block_body {
1290 shape.indent.block_indent(&config)
1292 let new_width = config.max_width() - body_indent.width();
1293 config.set().max_width(new_width);
1295 // First try to format as items, then as statements.
1296 let new_body_snippet = match crate::format_snippet(&body_str, &config) {
1297 Some(new_body) => new_body,
1299 let new_width = new_width + config.tab_spaces();
1300 config.set().max_width(new_width);
1301 match crate::format_code_block(&body_str, &config) {
1302 Some(new_body) => new_body,
1303 None => return None,
1307 let new_body = wrap_str(
1308 new_body_snippet.snippet.to_string(),
1313 // Indent the body since it is in a block.
1314 let indent_str = body_indent.to_string(&config);
1315 let mut new_body = LineClasses::new(new_body.trim_end())
1318 (String::new(), true),
1319 |(mut s, need_indent), (i, (kind, ref l))| {
1320 if !is_empty_line(l)
1322 && !new_body_snippet.is_line_non_formatted(i + 1)
1326 (s + l + "\n", indent_next_line(kind, &l, &config))
1331 // Undo our replacement of macro variables.
1332 // FIXME: this could be *much* more efficient.
1333 for (old, new) in &substs {
1334 if old_body.find(new).is_some() {
1335 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1338 new_body = new_body.replace(new, old);
1342 result += new_body.trim();
1343 } else if !new_body.is_empty() {
1345 result += &new_body;
1346 result += &shape.indent.to_string(&config);
1355 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1357 /// # Expected syntax
1361 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1362 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1364 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1367 fn format_lazy_static(
1368 context: &RewriteContext<'_>,
1371 ) -> Option<String> {
1372 let mut result = String::with_capacity(1024);
1373 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1374 let nested_shape = shape
1375 .block_indent(context.config.tab_spaces())
1376 .with_max_width(context.config);
1378 result.push_str("lazy_static! {");
1379 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1381 macro_rules! parse_or {
1382 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1383 match parser.$method($($arg,)*) {
1385 if parser.sess.span_diagnostic.has_errors() {
1386 parser.sess.span_diagnostic.reset_err_count();
1394 parser.sess.span_diagnostic.reset_err_count();
1401 while parser.token != Token::Eof {
1402 // Parse a `lazy_static!` item.
1403 let vis = crate::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1404 parser.eat_keyword(keywords::Static);
1405 parser.eat_keyword(keywords::Ref);
1406 let id = parse_or!(parse_ident);
1407 parser.eat(&Token::Colon);
1408 let ty = parse_or!(parse_ty);
1409 parser.eat(&Token::Eq);
1410 let expr = parse_or!(parse_expr);
1411 parser.eat(&Token::Semi);
1413 // Rewrite as a static item.
1414 let mut stmt = String::with_capacity(128);
1415 stmt.push_str(&format!(
1416 "{}static ref {}: {} =",
1419 ty.rewrite(context, nested_shape)?
1421 result.push_str(&crate::expr::rewrite_assign_rhs(
1425 nested_shape.sub_width(1)?,
1428 if parser.token != Token::Eof {
1429 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1433 result.push_str(&shape.indent.to_string_with_newline(context.config));
1439 fn rewrite_macro_with_items(
1440 context: &RewriteContext<'_>,
1445 position: MacroPosition,
1447 ) -> Option<String> {
1448 let (opener, closer) = match style {
1449 DelimToken::Paren => ("(", ")"),
1450 DelimToken::Bracket => ("[", "]"),
1451 DelimToken::Brace => (" {", "}"),
1454 let trailing_semicolon = match style {
1455 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1459 let mut visitor = FmtVisitor::from_context(context);
1460 visitor.block_indent = shape.indent.block_indent(context.config);
1461 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1463 let item = match item {
1464 MacroArg::Item(item) => item,
1467 visitor.visit_item(&item);
1470 let mut result = String::with_capacity(256);
1471 result.push_str(¯o_name);
1472 result.push_str(opener);
1473 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1474 result.push_str(visitor.buffer.trim());
1475 result.push_str(&shape.indent.to_string_with_newline(context.config));
1476 result.push_str(closer);
1477 result.push_str(trailing_semicolon);
1481 const RUST_KEYWORDS: [keywords::Keyword; 60] = [
1483 keywords::DollarCrate,
1484 keywords::Underscore,
1509 keywords::SelfLower,
1510 keywords::SelfUpper,
1535 keywords::UnderscoreLifetime,
1536 keywords::StaticLifetime,
1540 keywords::Existential,