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};
30 use syntax::tokenstream::{Cursor, ThinTokenStream, 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>),
70 fn is_item(&self) -> bool {
72 MacroArg::Item(..) => true,
78 impl Rewrite for ast::Item {
79 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
80 let mut visitor = crate::visitor::FmtVisitor::from_context(context);
81 visitor.block_indent = shape.indent;
82 visitor.last_pos = self.span().lo();
83 visitor.visit_item(self);
84 Some(visitor.buffer.to_owned())
88 impl Rewrite for MacroArg {
89 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
91 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
92 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
93 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
94 MacroArg::Item(ref item) => item.rewrite(context, shape),
99 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
100 macro_rules! parse_macro_arg {
101 ($macro_arg:ident, $parser:expr, $f:expr) => {
102 let mut cloned_parser = (*parser).clone();
103 match $parser(&mut cloned_parser) {
105 if parser.sess.span_diagnostic.has_errors() {
106 parser.sess.span_diagnostic.reset_err_count();
108 // Parsing succeeded.
109 *parser = cloned_parser;
110 return Some(MacroArg::$macro_arg($f(x)?));
115 parser.sess.span_diagnostic.reset_err_count();
123 |parser: &mut parse::parser::Parser<'b>| parser.parse_expr(),
124 |x: ptr::P<ast::Expr>| Some(x)
128 |parser: &mut parse::parser::Parser<'b>| parser.parse_ty(),
129 |x: ptr::P<ast::Ty>| Some(x)
133 |parser: &mut parse::parser::Parser<'b>| parser.parse_pat(None),
134 |x: ptr::P<ast::Pat>| Some(x)
136 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
139 |parser: &mut parse::parser::Parser<'b>| parser.parse_item(),
140 |x: Option<ptr::P<ast::Item>>| x
146 /// Rewrite macro name without using pretty-printer if possible.
147 fn rewrite_macro_name(
148 context: &RewriteContext,
150 extra_ident: Option<ast::Ident>,
152 let name = if path.segments.len() == 1 {
153 // Avoid using pretty-printer in the common case.
154 format!("{}!", rewrite_ident(context, path.segments[0].ident))
159 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
164 // Use this on failing to format the macro call.
165 fn return_macro_parse_failure_fallback(
166 context: &RewriteContext,
169 ) -> Option<String> {
170 // Mark this as a failure however we format it
171 context.macro_rewrite_failure.replace(true);
173 // Heuristically determine whether the last line of the macro uses "Block" style
174 // rather than using "Visual" style, or another indentation style.
175 let is_like_block_indent_style = context
179 .map(|closing_line| {
180 closing_line.trim().chars().all(|ch| match ch {
181 '}' | ')' | ']' => true,
186 if is_like_block_indent_style {
187 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
190 // Return the snippet unmodified if the macro is not block-like
191 Some(context.snippet(span).to_owned())
194 struct InsideMacroGuard<'a> {
195 context: &'a RewriteContext<'a>,
199 impl<'a> InsideMacroGuard<'a> {
200 fn inside_macro_context(context: &'a RewriteContext) -> InsideMacroGuard<'a> {
201 let is_nested = context.inside_macro.replace(true);
202 InsideMacroGuard { context, is_nested }
206 impl<'a> Drop for InsideMacroGuard<'a> {
208 self.context.inside_macro.replace(self.is_nested);
212 pub fn rewrite_macro(
214 extra_ident: Option<ast::Ident>,
215 context: &RewriteContext,
217 position: MacroPosition,
218 ) -> Option<String> {
219 let guard = InsideMacroGuard::inside_macro_context(context);
220 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position, guard.is_nested);
221 if result.is_none() {
222 context.macro_rewrite_failure.replace(true);
227 pub fn rewrite_macro_inner(
229 extra_ident: Option<ast::Ident>,
230 context: &RewriteContext,
232 position: MacroPosition,
233 is_nested_macro: bool,
234 ) -> Option<String> {
235 if context.config.use_try_shorthand() {
236 if let Some(expr) = convert_try_mac(mac, context) {
237 context.inside_macro.replace(false);
238 return expr.rewrite(context, shape);
242 let original_style = macro_style(mac, context);
244 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
246 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
252 let ts: TokenStream = mac.node.stream();
253 let has_comment = contains_comment(context.snippet(mac.span));
254 if ts.is_empty() && !has_comment {
256 DelimToken::Paren if position == MacroPosition::Item => {
257 Some(format!("{}();", macro_name))
259 DelimToken::Paren => Some(format!("{}()", macro_name)),
260 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
261 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
265 // Format well-known macros which cannot be parsed as a valid AST.
266 if macro_name == "lazy_static!" && !has_comment {
267 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
272 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
273 let mut arg_vec = Vec::new();
274 let mut vec_with_semi = false;
275 let mut trailing_comma = false;
277 if DelimToken::Brace != style {
279 match parse_macro_arg(&mut parser) {
280 Some(arg) => arg_vec.push(arg),
282 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
290 // Try to parse `vec![expr; expr]`
291 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
293 if parser.token != Token::Eof {
294 match parse_macro_arg(&mut parser) {
298 if parser.token == Token::Eof && arg_vec.len() == 2 {
299 vec_with_semi = true;
304 return return_macro_parse_failure_fallback(
313 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
315 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
316 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span),
321 if parser.token == Token::Eof {
322 trailing_comma = true;
328 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
329 return rewrite_macro_with_items(
341 DelimToken::Paren => {
342 // Format macro invocation as function call, preserve the trailing
343 // comma because not all macros support them.
344 overflow::rewrite_with_parens(
350 context.config.width_heuristics().fn_call_width,
352 Some(SeparatorTactic::Always)
354 Some(SeparatorTactic::Never)
357 .map(|rw| match position {
358 MacroPosition::Item => format!("{};", rw),
362 DelimToken::Bracket => {
363 // Handle special case: `vec![expr; expr]`
365 let mac_shape = shape.offset_left(macro_name.len())?;
366 // 8 = `vec![]` + `; `
367 let total_overhead = 8;
368 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
369 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
370 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
371 if !lhs.contains('\n')
372 && !rhs.contains('\n')
373 && lhs.len() + rhs.len() + total_overhead <= shape.width
375 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
380 nested_shape.indent.to_string_with_newline(context.config),
382 nested_shape.indent.to_string_with_newline(context.config),
384 shape.indent.to_string_with_newline(context.config),
388 // If we are rewriting `vec!` macro or other special macros,
389 // then we can rewrite this as an usual array literal.
390 // Otherwise, we must preserve the original existence of trailing comma.
391 let macro_name = ¯o_name.as_str();
392 let mut force_trailing_comma = if trailing_comma {
393 Some(SeparatorTactic::Always)
395 Some(SeparatorTactic::Never)
397 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
398 context.inside_macro.replace(false);
399 if context.use_block_indent() {
400 force_trailing_comma = Some(SeparatorTactic::Vertical);
403 let rewrite = rewrite_array(
409 force_trailing_comma,
410 Some(original_style),
412 let comma = match position {
413 MacroPosition::Item => ";",
417 Some(format!("{}{}", rewrite, comma))
420 DelimToken::Brace => {
421 // For macro invocations with braces, always put a space between
422 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
423 // anything in between the braces (for now).
424 let snippet = context.snippet(mac.span);
425 let macro_raw = snippet.split_at(snippet.find('!')? + 1).1.trim_start();
426 match trim_left_preserve_layout(macro_raw, shape.indent, &context.config) {
427 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
428 None => Some(format!("{} {}", macro_name, macro_raw)),
435 pub fn rewrite_macro_def(
436 context: &RewriteContext,
441 vis: &ast::Visibility,
443 ) -> Option<String> {
444 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
445 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
449 let mut parser = MacroParser::new(def.stream().into_trees());
450 let parsed_def = match parser.parse() {
452 None => return snippet,
455 let mut result = if def.legacy {
456 String::from("macro_rules!")
458 format!("{}macro", format_visibility(context, vis))
462 result += rewrite_ident(context, ident);
464 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
466 let arm_shape = if multi_branch_style {
468 .block_indent(context.config.tab_spaces())
469 .with_max_width(context.config)
474 let branch_items = itemize_list(
475 context.snippet_provider,
476 parsed_def.branches.iter(),
479 |branch| branch.span.lo(),
480 |branch| branch.span.hi(),
481 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
483 // if the rewrite returned None because a macro could not be rewritten, then return the
485 None if *context.macro_rewrite_failure.borrow() => {
486 Some(context.snippet(branch.body).trim().to_string())
490 context.snippet_provider.span_after(span, "{"),
494 .collect::<Vec<_>>();
496 let fmt = ListFormatting::new(arm_shape, context.config)
497 .separator(if def.legacy { ";" } else { "" })
498 .trailing_separator(SeparatorTactic::Always)
499 .preserve_newline(true);
501 if multi_branch_style {
503 result += &arm_shape.indent.to_string_with_newline(context.config);
506 match write_list(&branch_items, &fmt) {
507 Some(ref s) => result += s,
508 None => return snippet,
511 if multi_branch_style {
512 result += &indent.to_string_with_newline(context.config);
519 fn register_metavariable(
520 map: &mut HashMap<String, String>,
525 let mut new_name = String::new();
526 let mut old_name = String::new();
529 for _ in 0..(dollar_count - 1) {
534 new_name.push_str(&name);
535 old_name.push_str(&name);
537 result.push_str(&new_name);
538 map.insert(old_name, new_name);
541 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
542 // aren't causing problems.
543 // This should also work for escaped `$` variables, where we leave earlier `$`s.
544 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
545 // Each substitution will require five or six extra bytes.
546 let mut result = String::with_capacity(input.len() + 64);
547 let mut substs = HashMap::new();
548 let mut dollar_count = 0;
549 let mut cur_name = String::new();
551 for (kind, c) in CharClasses::new(input.chars()) {
552 if kind != FullCodeCharKind::Normal {
556 } else if dollar_count == 0 {
558 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
559 // Terminates a name following one or more dollars.
560 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
565 } else if c == '(' && cur_name.is_empty() {
566 // FIXME: Support macro def with repeat.
568 } else if c.is_alphanumeric() || c == '_' {
573 if !cur_name.is_empty() {
574 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
577 debug!("replace_names `{}` {:?}", result, substs);
579 Some((result, substs))
582 #[derive(Debug, Clone)]
585 MetaVariable(ast::Ident, String),
586 /// e.g. `$($foo: expr),*`
588 /// `()`, `[]` or `{}`.
590 /// Inner arguments inside delimiters.
592 /// Something after the closing delimiter and the repeat token, if available.
593 Option<Box<ParsedMacroArg>>,
594 /// The repeat token. This could be one of `*`, `+` or `?`.
597 /// e.g. `[derive(Debug)]`
598 Delimited(DelimToken, Vec<ParsedMacroArg>),
599 /// A possible separator. e.g. `,` or `;`.
600 Separator(String, String),
601 /// Other random stuff that does not fit to other kinds.
602 /// e.g. `== foo` in `($x: expr == foo)`.
603 Other(String, String),
606 fn delim_token_to_str(
607 context: &RewriteContext,
608 delim_token: DelimToken,
610 use_multiple_lines: bool,
611 inner_is_empty: bool,
612 ) -> (String, String) {
613 let (lhs, rhs) = match delim_token {
614 DelimToken::Paren => ("(", ")"),
615 DelimToken::Bracket => ("[", "]"),
616 DelimToken::Brace => {
617 if inner_is_empty || use_multiple_lines {
623 DelimToken::NoDelim => ("", ""),
625 if use_multiple_lines {
626 let indent_str = shape.indent.to_string_with_newline(context.config);
627 let nested_indent_str = shape
629 .block_indent(context.config)
630 .to_string_with_newline(context.config);
632 format!("{}{}", lhs, nested_indent_str),
633 format!("{}{}", indent_str, rhs),
636 (lhs.to_owned(), rhs.to_owned())
641 fn starts_with_brace(&self) -> bool {
643 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
644 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
649 fn starts_with_dollar(&self) -> bool {
651 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
656 fn ends_with_space(&self) -> bool {
658 MacroArgKind::Separator(..) => true,
663 fn has_meta_var(&self) -> bool {
665 MacroArgKind::MetaVariable(..) => true,
666 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
673 context: &RewriteContext,
675 use_multiple_lines: bool,
676 ) -> Option<String> {
677 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
678 let inner = wrap_macro_args(context, args, shape)?;
679 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
680 if lhs.len() + inner.len() + rhs.len() <= shape.width {
681 return Some((lhs, inner, rhs));
684 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
685 let nested_shape = shape
686 .block_indent(context.config.tab_spaces())
687 .with_max_width(context.config);
688 let inner = wrap_macro_args(context, args, nested_shape)?;
689 Some((lhs, inner, rhs))
693 MacroArgKind::MetaVariable(ty, ref name) => {
694 Some(format!("${}:{}", name, ty.name.as_str()))
696 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
697 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
698 let another = another
700 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
701 .unwrap_or_else(|| "".to_owned());
702 let repeat_tok = pprust::token_to_string(tok);
704 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
706 MacroArgKind::Delimited(delim_tok, ref args) => {
707 rewrite_delimited_inner(delim_tok, args)
708 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
710 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
711 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
716 #[derive(Debug, Clone)]
717 struct ParsedMacroArg {
722 impl ParsedMacroArg {
725 context: &RewriteContext,
727 use_multiple_lines: bool,
728 ) -> Option<String> {
729 self.kind.rewrite(context, shape, use_multiple_lines)
733 /// Parses macro arguments on macro def.
734 struct MacroArgParser {
735 /// Holds either a name of the next metavariable, a separator or a junk.
737 /// The start position on the current buffer.
739 /// The first token of the current buffer.
741 /// Set to true if we are parsing a metavariable or a repeat.
743 /// The position of the last token.
745 /// The last token parsed.
747 /// Holds the parsed arguments.
748 result: Vec<ParsedMacroArg>,
751 fn last_tok(tt: &TokenTree) -> Token {
753 TokenTree::Token(_, ref t) => t.clone(),
754 TokenTree::Delimited(_, ref d) => d.close_token(),
758 impl MacroArgParser {
759 pub fn new() -> MacroArgParser {
765 last_tok: Token::Eof,
766 start_tok: Token::Eof,
771 fn set_last_tok(&mut self, tok: &TokenTree) {
772 self.hi = tok.span().hi();
773 self.last_tok = last_tok(tok);
776 fn add_separator(&mut self) {
777 let prefix = if self.need_space_prefix() {
782 self.result.push(ParsedMacroArg {
783 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
784 span: mk_sp(self.lo, self.hi),
789 fn add_other(&mut self) {
790 let prefix = if self.need_space_prefix() {
795 self.result.push(ParsedMacroArg {
796 kind: MacroArgKind::Other(self.buf.clone(), prefix),
797 span: mk_sp(self.lo, self.hi),
802 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
804 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
805 self.result.push(ParsedMacroArg {
806 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
807 span: mk_sp(self.lo, sp.hi()),
811 self.is_meta_var = false;
818 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
819 self.result.push(ParsedMacroArg {
820 kind: MacroArgKind::Delimited(delim, inner),
828 inner: Vec<ParsedMacroArg>,
833 let mut buffer = String::new();
834 let mut first = false;
835 let mut lo = span.lo();
836 let mut hi = span.hi();
838 // Parse '*', '+' or '?.
840 self.set_last_tok(&tok);
843 lo = tok.span().lo();
847 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
848 | TokenTree::Token(_, Token::Question)
849 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
852 TokenTree::Token(sp, ref t) => {
853 buffer.push_str(&pprust::token_to_string(t));
860 // There could be some random stuff between ')' and '*', '+' or '?'.
861 let another = if buffer.trim().is_empty() {
864 Some(Box::new(ParsedMacroArg {
865 kind: MacroArgKind::Other(buffer, "".to_owned()),
870 self.result.push(ParsedMacroArg {
871 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
872 span: mk_sp(self.lo, self.hi),
877 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
878 if self.buf.is_empty() {
880 self.start_tok = t.clone();
882 let needs_space = match next_space(&self.last_tok) {
883 SpaceState::Ident => ident_like(t),
884 SpaceState::Punctuation => !ident_like(t),
885 SpaceState::Always => true,
886 SpaceState::Never => false,
888 if force_space_before(t) || needs_space {
893 self.buf.push_str(&pprust::token_to_string(t));
896 fn need_space_prefix(&self) -> bool {
897 if self.result.is_empty() {
901 let last_arg = self.result.last().unwrap();
902 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
903 if ident_like(&self.start_tok) {
906 if self.start_tok == Token::Colon {
911 if force_space_before(&self.start_tok) {
918 /// Returns a collection of parsed macro def's arguments.
919 pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
920 let stream: TokenStream = tokens.into();
921 let mut iter = stream.trees();
923 while let Some(ref tok) = iter.next() {
925 TokenTree::Token(sp, Token::Dollar) => {
926 // We always want to add a separator before meta variables.
927 if !self.buf.is_empty() {
928 self.add_separator();
931 // Start keeping the name of this metavariable in the buffer.
932 self.is_meta_var = true;
934 self.start_tok = Token::Dollar;
936 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
937 self.add_meta_variable(&mut iter)?;
939 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
940 TokenTree::Delimited(delimited_span, delimited) => {
941 if !self.buf.is_empty() {
942 if next_space(&self.last_tok) == SpaceState::Always {
943 self.add_separator();
949 // Parse the stuff inside delimiters.
950 let mut parser = MacroArgParser::new();
951 parser.lo = delimited_span.open.lo();
952 let delimited_arg = parser.parse(delimited.tts.clone())?;
954 let span = delimited_span.entire();
955 if self.is_meta_var {
956 self.add_repeat(delimited_arg, delimited.delim, &mut iter, span)?;
957 self.is_meta_var = false;
959 self.add_delimited(delimited_arg, delimited.delim, span);
964 self.set_last_tok(tok);
967 // We are left with some stuff in the buffer. Since there is nothing
968 // left to separate, add this as `Other`.
969 if !self.buf.is_empty() {
978 context: &RewriteContext,
979 args: &[ParsedMacroArg],
981 ) -> Option<String> {
982 wrap_macro_args_inner(context, args, shape, false)
983 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
986 fn wrap_macro_args_inner(
987 context: &RewriteContext,
988 args: &[ParsedMacroArg],
990 use_multiple_lines: bool,
991 ) -> Option<String> {
992 let mut result = String::with_capacity(128);
993 let mut iter = args.iter().peekable();
994 let indent_str = shape.indent.to_string_with_newline(context.config);
996 while let Some(ref arg) = iter.next() {
997 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
999 if use_multiple_lines
1000 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1002 if arg.kind.ends_with_space() {
1005 result.push_str(&indent_str);
1006 } else if let Some(ref next_arg) = iter.peek() {
1007 let space_before_dollar =
1008 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1009 let space_before_brace = next_arg.kind.starts_with_brace();
1010 if space_before_dollar || space_before_brace {
1016 if !use_multiple_lines && result.len() >= shape.width {
1023 // This is a bit sketchy. The token rules probably need tweaking, but it works
1024 // for some common cases. I hope the basic logic is sufficient. Note that the
1025 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1026 // and `(`/`)` have special meaning.
1028 // We always try and format on one line.
1029 // FIXME: Use multi-line when every thing does not fit on one line.
1030 fn format_macro_args(
1031 context: &RewriteContext,
1032 toks: ThinTokenStream,
1034 ) -> Option<String> {
1035 if !context.config.format_macro_matchers() {
1036 let token_stream: TokenStream = toks.into();
1037 let span = span_for_token_stream(&token_stream);
1038 return Some(match span {
1039 Some(span) => context.snippet(span).to_owned(),
1040 None => String::new(),
1043 let parsed_args = MacroArgParser::new().parse(toks)?;
1044 wrap_macro_args(context, &parsed_args, shape)
1047 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1048 token_stream.trees().next().map(|tt| tt.span())
1051 // We should insert a space if the next token is a:
1052 #[derive(Copy, Clone, PartialEq)]
1056 Ident, // Or ident/literal-like thing.
1060 fn force_space_before(tok: &Token) -> bool {
1061 debug!("tok: force_space_before {:?}", tok);
1082 | Token::Dollar => true,
1087 fn ident_like(tok: &Token) -> bool {
1089 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1094 fn next_space(tok: &Token) -> SpaceState {
1095 debug!("next_space: {:?}", tok);
1099 | Token::BinOp(BinOpToken::And)
1107 | Token::Question => SpaceState::Punctuation,
1112 | Token::OpenDelim(_)
1113 | Token::CloseDelim(_)
1114 | Token::Whitespace => SpaceState::Never,
1116 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1118 _ => SpaceState::Always,
1122 /// Tries to convert a macro use into a short hand try expression. Returns None
1123 /// when the macro is not an instance of try! (or parsing the inner expression
1125 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1126 if &mac.node.path.to_string() == "try" {
1127 let ts: TokenStream = mac.node.tts.clone().into();
1128 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1131 id: ast::NodeId::root(), // dummy value
1132 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1133 span: mac.span, // incorrect span, but shouldn't matter too much
1134 attrs: ThinVec::new(),
1141 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1142 let snippet = context.snippet(mac.span);
1143 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1144 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1145 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1147 if paren_pos < bracket_pos && paren_pos < brace_pos {
1149 } else if bracket_pos < brace_pos {
1156 // A very simple parser that just parses a macros 2.0 definition into its branches.
1157 // Currently we do not attempt to parse any further than that.
1159 struct MacroParser {
1164 // (`(` ... `)` `=>` `{` ... `}`)*
1165 fn parse(&mut self) -> Option<Macro> {
1166 let mut branches = vec![];
1167 while self.toks.look_ahead(1).is_some() {
1168 branches.push(self.parse_branch()?);
1171 Some(Macro { branches })
1174 // `(` ... `)` `=>` `{` ... `}`
1175 fn parse_branch(&mut self) -> Option<MacroBranch> {
1176 let tok = self.toks.next()?;
1177 let (lo, args_paren_kind) = match tok {
1178 TokenTree::Token(..) => return None,
1179 TokenTree::Delimited(delimited_span, ref d) => (delimited_span.open.lo(), d.delim),
1181 let args = tok.joint().into();
1182 match self.toks.next()? {
1183 TokenTree::Token(_, Token::FatArrow) => {}
1186 let (mut hi, body, whole_body) = match self.toks.next()? {
1187 TokenTree::Token(..) => return None,
1188 TokenTree::Delimited(delimited_span, _) => {
1189 let data = delimited_span.entire().data();
1192 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1193 delimited_span.entire(),
1197 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1202 span: mk_sp(lo, hi),
1211 // A parsed macros 2.0 macro definition.
1213 branches: Vec<MacroBranch>,
1216 // FIXME: it would be more efficient to use references to the token streams
1217 // rather than clone them, if we can make the borrowing work out.
1218 struct MacroBranch {
1220 args_paren_kind: DelimToken,
1221 args: ThinTokenStream,
1229 context: &RewriteContext,
1231 multi_branch_style: bool,
1232 ) -> Option<String> {
1233 // Only attempt to format function-like macros.
1234 if self.args_paren_kind != DelimToken::Paren {
1235 // FIXME(#1539): implement for non-sugared macros.
1240 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1242 if multi_branch_style {
1246 if !context.config.format_macro_bodies() {
1248 result += context.snippet(self.whole_body);
1249 return Some(result);
1252 // The macro body is the most interesting part. It might end up as various
1253 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1254 // parsed as regular Rust code (and note that these can be escaped using
1255 // `$$`). We'll try and format like an AST node, but we'll substitute
1256 // variables for new names with the same length first.
1258 let old_body = context.snippet(self.body).trim();
1259 let (body_str, substs) = replace_names(old_body)?;
1260 let has_block_body = old_body.starts_with('{');
1262 let mut config = context.config.clone();
1263 config.set().hide_parse_errors(true);
1267 let body_indent = if has_block_body {
1270 shape.indent.block_indent(&config)
1272 let new_width = config.max_width() - body_indent.width();
1273 config.set().max_width(new_width);
1275 // First try to format as items, then as statements.
1276 let new_body_snippet = match crate::format_snippet(&body_str, &config) {
1277 Some(new_body) => new_body,
1279 let new_width = new_width + config.tab_spaces();
1280 config.set().max_width(new_width);
1281 match crate::format_code_block(&body_str, &config) {
1282 Some(new_body) => new_body,
1283 None => return None,
1287 let new_body = wrap_str(
1288 new_body_snippet.snippet.to_string(),
1293 // Indent the body since it is in a block.
1294 let indent_str = body_indent.to_string(&config);
1295 let mut new_body = LineClasses::new(new_body.trim_end())
1298 (String::new(), true),
1299 |(mut s, need_indent), (i, (kind, ref l))| {
1300 if !is_empty_line(l)
1302 && !new_body_snippet.is_line_non_formatted(i + 1)
1306 (s + l + "\n", indent_next_line(kind, &l, &config))
1311 // Undo our replacement of macro variables.
1312 // FIXME: this could be *much* more efficient.
1313 for (old, new) in &substs {
1314 if old_body.find(new).is_some() {
1315 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1318 new_body = new_body.replace(new, old);
1322 result += new_body.trim();
1323 } else if !new_body.is_empty() {
1325 result += &new_body;
1326 result += &shape.indent.to_string(&config);
1335 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1337 /// # Expected syntax
1341 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1342 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1344 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1347 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1348 let mut result = String::with_capacity(1024);
1349 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1350 let nested_shape = shape
1351 .block_indent(context.config.tab_spaces())
1352 .with_max_width(context.config);
1354 result.push_str("lazy_static! {");
1355 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1357 macro_rules! parse_or {
1358 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1359 match parser.$method($($arg,)*) {
1361 if parser.sess.span_diagnostic.has_errors() {
1362 parser.sess.span_diagnostic.reset_err_count();
1370 parser.sess.span_diagnostic.reset_err_count();
1377 while parser.token != Token::Eof {
1378 // Parse a `lazy_static!` item.
1379 let vis = crate::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1380 parser.eat_keyword(symbol::keywords::Static);
1381 parser.eat_keyword(symbol::keywords::Ref);
1382 let id = parse_or!(parse_ident);
1383 parser.eat(&Token::Colon);
1384 let ty = parse_or!(parse_ty);
1385 parser.eat(&Token::Eq);
1386 let expr = parse_or!(parse_expr);
1387 parser.eat(&Token::Semi);
1389 // Rewrite as a static item.
1390 let mut stmt = String::with_capacity(128);
1391 stmt.push_str(&format!(
1392 "{}static ref {}: {} =",
1395 ty.rewrite(context, nested_shape)?
1397 result.push_str(&crate::expr::rewrite_assign_rhs(
1401 nested_shape.sub_width(1)?,
1404 if parser.token != Token::Eof {
1405 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1409 result.push_str(&shape.indent.to_string_with_newline(context.config));
1415 fn rewrite_macro_with_items(
1416 context: &RewriteContext,
1421 position: MacroPosition,
1423 ) -> Option<String> {
1424 let (opener, closer) = match style {
1425 DelimToken::Paren => ("(", ")"),
1426 DelimToken::Bracket => ("[", "]"),
1427 DelimToken::Brace => (" {", "}"),
1430 let trailing_semicolon = match style {
1431 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1435 let mut visitor = FmtVisitor::from_context(context);
1436 visitor.block_indent = shape.indent.block_indent(context.config);
1437 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1439 let item = match item {
1440 MacroArg::Item(item) => item,
1443 visitor.visit_item(&item);
1446 let mut result = String::with_capacity(256);
1447 result.push_str(¯o_name);
1448 result.push_str(opener);
1449 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1450 result.push_str(visitor.buffer.trim());
1451 result.push_str(&shape.indent.to_string_with_newline(context.config));
1452 result.push_str(closer);
1453 result.push_str(trailing_semicolon);