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;
25 use syntax::parse::new_parser_from_tts;
26 use syntax::parse::parser::Parser;
27 use syntax::parse::token::{BinOpToken, DelimToken, Token};
28 use syntax::print::pprust;
29 use syntax::source_map::{BytePos, Span};
31 use syntax::tokenstream::{Cursor, ThinTokenStream, TokenStream, TokenTree};
33 use syntax::{ast, parse, ptr};
35 use comment::{contains_comment, CharClasses, FindUncommented, FullCodeCharKind, LineClasses};
36 use expr::rewrite_array;
37 use lists::{itemize_list, write_list, ListFormatting};
39 use rewrite::{Rewrite, RewriteContext};
40 use shape::{Indent, Shape};
41 use source_map::SpanUtils;
44 format_visibility, is_empty_line, mk_sp, remove_trailing_white_spaces, rewrite_ident,
45 trim_left_preserve_layout, wrap_str, NodeIdExt,
47 use visitor::FmtVisitor;
49 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub enum MacroPosition {
61 Expr(ptr::P<ast::Expr>),
63 Pat(ptr::P<ast::Pat>),
64 Item(ptr::P<ast::Item>),
68 fn is_item(&self) -> bool {
70 MacroArg::Item(..) => true,
76 impl Rewrite for ast::Item {
77 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
78 let mut visitor = ::visitor::FmtVisitor::from_context(context);
79 visitor.block_indent = shape.indent;
80 visitor.last_pos = self.span().lo();
81 visitor.visit_item(self);
82 Some(visitor.buffer.to_owned())
86 impl Rewrite for MacroArg {
87 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
89 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
90 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
91 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
92 MacroArg::Item(ref item) => item.rewrite(context, shape),
97 fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
98 macro_rules! parse_macro_arg {
99 ($macro_arg:ident, $parser:expr, $f:expr) => {
100 let mut cloned_parser = (*parser).clone();
101 match $parser(&mut cloned_parser) {
103 if parser.sess.span_diagnostic.has_errors() {
104 parser.sess.span_diagnostic.reset_err_count();
106 // Parsing succeeded.
107 *parser = cloned_parser;
108 return Some(MacroArg::$macro_arg($f(x)?));
113 parser.sess.span_diagnostic.reset_err_count();
121 |parser: &mut parse::parser::Parser<'b>| parser.parse_expr(),
122 |x: ptr::P<ast::Expr>| Some(x)
126 |parser: &mut parse::parser::Parser<'b>| parser.parse_ty(),
127 |x: ptr::P<ast::Ty>| Some(x)
131 |parser: &mut parse::parser::Parser<'b>| parser.parse_pat(None),
132 |x: ptr::P<ast::Pat>| Some(x)
134 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
137 |parser: &mut parse::parser::Parser<'b>| parser.parse_item(),
138 |x: Option<ptr::P<ast::Item>>| x
144 /// Rewrite macro name without using pretty-printer if possible.
145 fn rewrite_macro_name(
146 context: &RewriteContext,
148 extra_ident: Option<ast::Ident>,
150 let name = if path.segments.len() == 1 {
151 // Avoid using pretty-printer in the common case.
152 format!("{}!", rewrite_ident(context, path.segments[0].ident))
157 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
162 // Use this on failing to format the macro call.
163 fn return_macro_parse_failure_fallback(
164 context: &RewriteContext,
167 ) -> Option<String> {
168 // Mark this as a failure however we format it
169 context.macro_rewrite_failure.replace(true);
171 // Heuristically determine whether the last line of the macro uses "Block" style
172 // rather than using "Visual" style, or another indentation style.
173 let is_like_block_indent_style = context
177 .map(|closing_line| {
178 closing_line.trim().chars().all(|ch| match ch {
179 '}' | ')' | ']' => true,
184 if is_like_block_indent_style {
185 return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
188 // Return the snippet unmodified if the macro is not block-like
189 Some(context.snippet(span).to_owned())
192 struct InsideMacroGuard<'a> {
193 context: &'a RewriteContext<'a>,
197 impl<'a> InsideMacroGuard<'a> {
198 fn inside_macro_context(context: &'a RewriteContext) -> InsideMacroGuard<'a> {
199 let is_nested = context.inside_macro.replace(true);
200 InsideMacroGuard { context, is_nested }
204 impl<'a> Drop for InsideMacroGuard<'a> {
206 self.context.inside_macro.replace(self.is_nested);
210 pub fn rewrite_macro(
212 extra_ident: Option<ast::Ident>,
213 context: &RewriteContext,
215 position: MacroPosition,
216 ) -> Option<String> {
217 let guard = InsideMacroGuard::inside_macro_context(context);
218 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position, guard.is_nested);
219 if result.is_none() {
220 context.macro_rewrite_failure.replace(true);
225 pub fn rewrite_macro_inner(
227 extra_ident: Option<ast::Ident>,
228 context: &RewriteContext,
230 position: MacroPosition,
231 is_nested_macro: bool,
232 ) -> Option<String> {
233 if context.config.use_try_shorthand() {
234 if let Some(expr) = convert_try_mac(mac, context) {
235 context.inside_macro.replace(false);
236 return expr.rewrite(context, shape);
240 let original_style = macro_style(mac, context);
242 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
244 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
250 let ts: TokenStream = mac.node.stream();
251 let has_comment = contains_comment(context.snippet(mac.span));
252 if ts.is_empty() && !has_comment {
254 DelimToken::Paren if position == MacroPosition::Item => {
255 Some(format!("{}();", macro_name))
257 DelimToken::Paren => Some(format!("{}()", macro_name)),
258 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
259 DelimToken::Brace => Some(format!("{} {{}}", macro_name)),
263 // Format well-known macros which cannot be parsed as a valid AST.
264 if macro_name == "lazy_static!" && !has_comment {
265 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
270 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
271 let mut arg_vec = Vec::new();
272 let mut vec_with_semi = false;
273 let mut trailing_comma = false;
275 if DelimToken::Brace != style {
277 match parse_macro_arg(&mut parser) {
278 Some(arg) => arg_vec.push(arg),
280 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
288 // Try to parse `vec![expr; expr]`
289 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
291 if parser.token != Token::Eof {
292 match parse_macro_arg(&mut parser) {
296 if parser.token == Token::Eof && arg_vec.len() == 2 {
297 vec_with_semi = true;
302 return return_macro_parse_failure_fallback(
311 return return_macro_parse_failure_fallback(context, shape.indent, mac.span);
313 _ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
314 _ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span),
319 if parser.token == Token::Eof {
320 trailing_comma = true;
326 if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
327 return rewrite_macro_with_items(
339 DelimToken::Paren => {
340 // Format macro invocation as function call, preserve the trailing
341 // comma because not all macros support them.
342 overflow::rewrite_with_parens(
348 context.config.width_heuristics().fn_call_width,
350 Some(SeparatorTactic::Always)
352 Some(SeparatorTactic::Never)
355 .map(|rw| match position {
356 MacroPosition::Item => format!("{};", rw),
360 DelimToken::Bracket => {
361 // Handle special case: `vec![expr; expr]`
363 let mac_shape = shape.offset_left(macro_name.len())?;
364 // 8 = `vec![]` + `; `
365 let total_overhead = 8;
366 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
367 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
368 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
369 if !lhs.contains('\n')
370 && !rhs.contains('\n')
371 && lhs.len() + rhs.len() + total_overhead <= shape.width
373 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
378 nested_shape.indent.to_string_with_newline(context.config),
380 nested_shape.indent.to_string_with_newline(context.config),
382 shape.indent.to_string_with_newline(context.config),
386 // If we are rewriting `vec!` macro or other special macros,
387 // then we can rewrite this as an usual array literal.
388 // Otherwise, we must preserve the original existence of trailing comma.
389 let macro_name = ¯o_name.as_str();
390 let mut force_trailing_comma = if trailing_comma {
391 Some(SeparatorTactic::Always)
393 Some(SeparatorTactic::Never)
395 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
396 context.inside_macro.replace(false);
397 if context.use_block_indent() {
398 force_trailing_comma = Some(SeparatorTactic::Vertical);
401 let rewrite = rewrite_array(
407 force_trailing_comma,
408 Some(original_style),
410 let comma = match position {
411 MacroPosition::Item => ";",
415 Some(format!("{}{}", rewrite, comma))
418 DelimToken::Brace => {
419 // For macro invocations with braces, always put a space between
420 // the `macro_name!` and `{ /* macro_body */ }` but skip modifying
421 // anything in between the braces (for now).
422 let snippet = context.snippet(mac.span);
423 let macro_raw = snippet.split_at(snippet.find('!')? + 1).1.trim_start();
424 match trim_left_preserve_layout(macro_raw, shape.indent, &context.config) {
425 Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
426 None => Some(format!("{} {}", macro_name, macro_raw)),
433 pub fn rewrite_macro_def(
434 context: &RewriteContext,
439 vis: &ast::Visibility,
441 ) -> Option<String> {
442 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
443 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
447 let mut parser = MacroParser::new(def.stream().into_trees());
448 let parsed_def = match parser.parse() {
450 None => return snippet,
453 let mut result = if def.legacy {
454 String::from("macro_rules!")
456 format!("{}macro", format_visibility(context, vis))
460 result += rewrite_ident(context, ident);
462 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
464 let arm_shape = if multi_branch_style {
466 .block_indent(context.config.tab_spaces())
467 .with_max_width(context.config)
472 let branch_items = itemize_list(
473 context.snippet_provider,
474 parsed_def.branches.iter(),
477 |branch| branch.span.lo(),
478 |branch| branch.span.hi(),
479 |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
481 // if the rewrite returned None because a macro could not be rewritten, then return the
483 None if *context.macro_rewrite_failure.borrow() => {
484 Some(context.snippet(branch.body).trim().to_string())
488 context.snippet_provider.span_after(span, "{"),
492 .collect::<Vec<_>>();
494 let fmt = ListFormatting::new(arm_shape, context.config)
495 .separator(if def.legacy { ";" } else { "" })
496 .trailing_separator(SeparatorTactic::Always)
497 .preserve_newline(true);
499 if multi_branch_style {
501 result += &arm_shape.indent.to_string_with_newline(context.config);
504 match write_list(&branch_items, &fmt) {
505 Some(ref s) => result += s,
506 None => return snippet,
509 if multi_branch_style {
510 result += &indent.to_string_with_newline(context.config);
517 fn register_metavariable(
518 map: &mut HashMap<String, String>,
523 let mut new_name = String::new();
524 let mut old_name = String::new();
527 for _ in 0..(dollar_count - 1) {
532 new_name.push_str(&name);
533 old_name.push_str(&name);
535 result.push_str(&new_name);
536 map.insert(old_name, new_name);
539 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
540 // aren't causing problems.
541 // This should also work for escaped `$` variables, where we leave earlier `$`s.
542 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
543 // Each substitution will require five or six extra bytes.
544 let mut result = String::with_capacity(input.len() + 64);
545 let mut substs = HashMap::new();
546 let mut dollar_count = 0;
547 let mut cur_name = String::new();
549 for (kind, c) in CharClasses::new(input.chars()) {
550 if kind != FullCodeCharKind::Normal {
554 } else if dollar_count == 0 {
556 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
557 // Terminates a name following one or more dollars.
558 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
563 } else if c == '(' && cur_name.is_empty() {
564 // FIXME: Support macro def with repeat.
566 } else if c.is_alphanumeric() || c == '_' {
571 if !cur_name.is_empty() {
572 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
575 debug!("replace_names `{}` {:?}", result, substs);
577 Some((result, substs))
580 #[derive(Debug, Clone)]
583 MetaVariable(ast::Ident, String),
584 /// e.g. `$($foo: expr),*`
586 /// `()`, `[]` or `{}`.
588 /// Inner arguments inside delimiters.
590 /// Something after the closing delimiter and the repeat token, if available.
591 Option<Box<ParsedMacroArg>>,
592 /// The repeat token. This could be one of `*`, `+` or `?`.
595 /// e.g. `[derive(Debug)]`
596 Delimited(DelimToken, Vec<ParsedMacroArg>),
597 /// A possible separator. e.g. `,` or `;`.
598 Separator(String, String),
599 /// Other random stuff that does not fit to other kinds.
600 /// e.g. `== foo` in `($x: expr == foo)`.
601 Other(String, String),
604 fn delim_token_to_str(
605 context: &RewriteContext,
606 delim_token: DelimToken,
608 use_multiple_lines: bool,
609 inner_is_empty: bool,
610 ) -> (String, String) {
611 let (lhs, rhs) = match delim_token {
612 DelimToken::Paren => ("(", ")"),
613 DelimToken::Bracket => ("[", "]"),
614 DelimToken::Brace => {
615 if inner_is_empty || use_multiple_lines {
621 DelimToken::NoDelim => ("", ""),
623 if use_multiple_lines {
624 let indent_str = shape.indent.to_string_with_newline(context.config);
625 let nested_indent_str = shape
627 .block_indent(context.config)
628 .to_string_with_newline(context.config);
630 format!("{}{}", lhs, nested_indent_str),
631 format!("{}{}", indent_str, rhs),
634 (lhs.to_owned(), rhs.to_owned())
639 fn starts_with_brace(&self) -> bool {
641 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
642 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
647 fn starts_with_dollar(&self) -> bool {
649 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
654 fn ends_with_space(&self) -> bool {
656 MacroArgKind::Separator(..) => true,
661 fn has_meta_var(&self) -> bool {
663 MacroArgKind::MetaVariable(..) => true,
664 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
671 context: &RewriteContext,
673 use_multiple_lines: bool,
674 ) -> Option<String> {
675 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
676 let inner = wrap_macro_args(context, args, shape)?;
677 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
678 if lhs.len() + inner.len() + rhs.len() <= shape.width {
679 return Some((lhs, inner, rhs));
682 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
683 let nested_shape = shape
684 .block_indent(context.config.tab_spaces())
685 .with_max_width(context.config);
686 let inner = wrap_macro_args(context, args, nested_shape)?;
687 Some((lhs, inner, rhs))
691 MacroArgKind::MetaVariable(ty, ref name) => {
692 Some(format!("${}:{}", name, ty.name.as_str()))
694 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
695 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
696 let another = another
698 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
699 .unwrap_or_else(|| "".to_owned());
700 let repeat_tok = pprust::token_to_string(tok);
702 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
704 MacroArgKind::Delimited(delim_tok, ref args) => {
705 rewrite_delimited_inner(delim_tok, args)
706 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
708 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
709 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
714 #[derive(Debug, Clone)]
715 struct ParsedMacroArg {
720 impl ParsedMacroArg {
723 context: &RewriteContext,
725 use_multiple_lines: bool,
726 ) -> Option<String> {
727 self.kind.rewrite(context, shape, use_multiple_lines)
731 /// Parses macro arguments on macro def.
732 struct MacroArgParser {
733 /// Holds either a name of the next metavariable, a separator or a junk.
735 /// The start position on the current buffer.
737 /// The first token of the current buffer.
739 /// Set to true if we are parsing a metavariable or a repeat.
741 /// The position of the last token.
743 /// The last token parsed.
745 /// Holds the parsed arguments.
746 result: Vec<ParsedMacroArg>,
749 fn last_tok(tt: &TokenTree) -> Token {
751 TokenTree::Token(_, ref t) => t.clone(),
752 TokenTree::Delimited(_, ref d) => d.close_token(),
756 impl MacroArgParser {
757 pub fn new() -> MacroArgParser {
763 last_tok: Token::Eof,
764 start_tok: Token::Eof,
769 fn set_last_tok(&mut self, tok: &TokenTree) {
770 self.hi = tok.span().hi();
771 self.last_tok = last_tok(tok);
774 fn add_separator(&mut self) {
775 let prefix = if self.need_space_prefix() {
780 self.result.push(ParsedMacroArg {
781 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
782 span: mk_sp(self.lo, self.hi),
787 fn add_other(&mut self) {
788 let prefix = if self.need_space_prefix() {
793 self.result.push(ParsedMacroArg {
794 kind: MacroArgKind::Other(self.buf.clone(), prefix),
795 span: mk_sp(self.lo, self.hi),
800 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
802 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
803 self.result.push(ParsedMacroArg {
804 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
805 span: mk_sp(self.lo, sp.hi()),
809 self.is_meta_var = false;
816 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
817 self.result.push(ParsedMacroArg {
818 kind: MacroArgKind::Delimited(delim, inner),
826 inner: Vec<ParsedMacroArg>,
831 let mut buffer = String::new();
832 let mut first = false;
833 let mut lo = span.lo();
834 let mut hi = span.hi();
836 // Parse '*', '+' or '?.
838 self.set_last_tok(&tok);
841 lo = tok.span().lo();
845 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
846 | TokenTree::Token(_, Token::Question)
847 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
850 TokenTree::Token(sp, ref t) => {
851 buffer.push_str(&pprust::token_to_string(t));
858 // There could be some random stuff between ')' and '*', '+' or '?'.
859 let another = if buffer.trim().is_empty() {
862 Some(Box::new(ParsedMacroArg {
863 kind: MacroArgKind::Other(buffer, "".to_owned()),
868 self.result.push(ParsedMacroArg {
869 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
870 span: mk_sp(self.lo, self.hi),
875 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
876 if self.buf.is_empty() {
878 self.start_tok = t.clone();
880 let needs_space = match next_space(&self.last_tok) {
881 SpaceState::Ident => ident_like(t),
882 SpaceState::Punctuation => !ident_like(t),
883 SpaceState::Always => true,
884 SpaceState::Never => false,
886 if force_space_before(t) || needs_space {
891 self.buf.push_str(&pprust::token_to_string(t));
894 fn need_space_prefix(&self) -> bool {
895 if self.result.is_empty() {
899 let last_arg = self.result.last().unwrap();
900 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
901 if ident_like(&self.start_tok) {
904 if self.start_tok == Token::Colon {
909 if force_space_before(&self.start_tok) {
916 /// Returns a collection of parsed macro def's arguments.
917 pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
918 let stream: TokenStream = tokens.into();
919 let mut iter = stream.trees();
921 while let Some(ref tok) = iter.next() {
923 TokenTree::Token(sp, Token::Dollar) => {
924 // We always want to add a separator before meta variables.
925 if !self.buf.is_empty() {
926 self.add_separator();
929 // Start keeping the name of this metavariable in the buffer.
930 self.is_meta_var = true;
932 self.start_tok = Token::Dollar;
934 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
935 self.add_meta_variable(&mut iter)?;
937 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
938 TokenTree::Delimited(delimited_span, delimited) => {
939 if !self.buf.is_empty() {
940 if next_space(&self.last_tok) == SpaceState::Always {
941 self.add_separator();
947 // Parse the stuff inside delimiters.
948 let mut parser = MacroArgParser::new();
949 parser.lo = delimited_span.open.lo();
950 let delimited_arg = parser.parse(delimited.tts.clone())?;
952 let span = delimited_span.entire();
953 if self.is_meta_var {
954 self.add_repeat(delimited_arg, delimited.delim, &mut iter, span)?;
955 self.is_meta_var = false;
957 self.add_delimited(delimited_arg, delimited.delim, span);
962 self.set_last_tok(tok);
965 // We are left with some stuff in the buffer. Since there is nothing
966 // left to separate, add this as `Other`.
967 if !self.buf.is_empty() {
976 context: &RewriteContext,
977 args: &[ParsedMacroArg],
979 ) -> Option<String> {
980 wrap_macro_args_inner(context, args, shape, false)
981 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
984 fn wrap_macro_args_inner(
985 context: &RewriteContext,
986 args: &[ParsedMacroArg],
988 use_multiple_lines: bool,
989 ) -> Option<String> {
990 let mut result = String::with_capacity(128);
991 let mut iter = args.iter().peekable();
992 let indent_str = shape.indent.to_string_with_newline(context.config);
994 while let Some(ref arg) = iter.next() {
995 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
997 if use_multiple_lines
998 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
1000 if arg.kind.ends_with_space() {
1003 result.push_str(&indent_str);
1004 } else if let Some(ref next_arg) = iter.peek() {
1005 let space_before_dollar =
1006 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
1007 let space_before_brace = next_arg.kind.starts_with_brace();
1008 if space_before_dollar || space_before_brace {
1014 if !use_multiple_lines && result.len() >= shape.width {
1021 // This is a bit sketchy. The token rules probably need tweaking, but it works
1022 // for some common cases. I hope the basic logic is sufficient. Note that the
1023 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
1024 // and `(`/`)` have special meaning.
1026 // We always try and format on one line.
1027 // FIXME: Use multi-line when every thing does not fit on one line.
1028 fn format_macro_args(
1029 context: &RewriteContext,
1030 toks: ThinTokenStream,
1032 ) -> Option<String> {
1033 if !context.config.format_macro_matchers() {
1034 let token_stream: TokenStream = toks.into();
1035 let span = span_for_token_stream(&token_stream);
1036 return Some(match span {
1037 Some(span) => context.snippet(span).to_owned(),
1038 None => String::new(),
1041 let parsed_args = MacroArgParser::new().parse(toks)?;
1042 wrap_macro_args(context, &parsed_args, shape)
1045 fn span_for_token_stream(token_stream: &TokenStream) -> Option<Span> {
1046 token_stream.trees().next().map(|tt| tt.span())
1049 // We should insert a space if the next token is a:
1050 #[derive(Copy, Clone, PartialEq)]
1054 Ident, // Or ident/literal-like thing.
1058 fn force_space_before(tok: &Token) -> bool {
1059 debug!("tok: force_space_before {:?}", tok);
1080 | Token::Dollar => true,
1085 fn ident_like(tok: &Token) -> bool {
1087 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1092 fn next_space(tok: &Token) -> SpaceState {
1093 debug!("next_space: {:?}", tok);
1097 | Token::BinOp(BinOpToken::And)
1105 | Token::Question => SpaceState::Punctuation,
1110 | Token::OpenDelim(_)
1111 | Token::CloseDelim(_)
1112 | Token::Whitespace => SpaceState::Never,
1114 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1116 _ => SpaceState::Always,
1120 /// Tries to convert a macro use into a short hand try expression. Returns None
1121 /// when the macro is not an instance of try! (or parsing the inner expression
1123 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1124 if &mac.node.path.to_string() == "try" {
1125 let ts: TokenStream = mac.node.tts.clone().into();
1126 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1129 id: ast::NodeId::root(), // dummy value
1130 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1131 span: mac.span, // incorrect span, but shouldn't matter too much
1132 attrs: ThinVec::new(),
1139 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1140 let snippet = context.snippet(mac.span);
1141 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1142 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1143 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1145 if paren_pos < bracket_pos && paren_pos < brace_pos {
1147 } else if bracket_pos < brace_pos {
1154 // A very simple parser that just parses a macros 2.0 definition into its branches.
1155 // Currently we do not attempt to parse any further than that.
1157 struct MacroParser {
1162 // (`(` ... `)` `=>` `{` ... `}`)*
1163 fn parse(&mut self) -> Option<Macro> {
1164 let mut branches = vec![];
1165 while self.toks.look_ahead(1).is_some() {
1166 branches.push(self.parse_branch()?);
1169 Some(Macro { branches })
1172 // `(` ... `)` `=>` `{` ... `}`
1173 fn parse_branch(&mut self) -> Option<MacroBranch> {
1174 let tok = self.toks.next()?;
1175 let (lo, args_paren_kind) = match tok {
1176 TokenTree::Token(..) => return None,
1177 TokenTree::Delimited(delimited_span, ref d) => (delimited_span.open.lo(), d.delim),
1179 let args = tok.joint().into();
1180 match self.toks.next()? {
1181 TokenTree::Token(_, Token::FatArrow) => {}
1184 let (mut hi, body, whole_body) = match self.toks.next()? {
1185 TokenTree::Token(..) => return None,
1186 TokenTree::Delimited(delimited_span, _) => {
1187 let data = delimited_span.entire().data();
1190 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1191 delimited_span.entire(),
1195 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1200 span: mk_sp(lo, hi),
1209 // A parsed macros 2.0 macro definition.
1211 branches: Vec<MacroBranch>,
1214 // FIXME: it would be more efficient to use references to the token streams
1215 // rather than clone them, if we can make the borrowing work out.
1216 struct MacroBranch {
1218 args_paren_kind: DelimToken,
1219 args: ThinTokenStream,
1227 context: &RewriteContext,
1229 multi_branch_style: bool,
1230 ) -> Option<String> {
1231 // Only attempt to format function-like macros.
1232 if self.args_paren_kind != DelimToken::Paren {
1233 // FIXME(#1539): implement for non-sugared macros.
1238 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1240 if multi_branch_style {
1244 if !context.config.format_macro_bodies() {
1246 result += context.snippet(self.whole_body);
1247 return Some(result);
1250 // The macro body is the most interesting part. It might end up as various
1251 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1252 // parsed as regular Rust code (and note that these can be escaped using
1253 // `$$`). We'll try and format like an AST node, but we'll substitute
1254 // variables for new names with the same length first.
1256 let old_body = context.snippet(self.body).trim();
1257 let (body_str, substs) = replace_names(old_body)?;
1258 let has_block_body = old_body.starts_with('{');
1260 let mut config = context.config.clone();
1261 config.set().hide_parse_errors(true);
1265 let body_indent = if has_block_body {
1268 shape.indent.block_indent(&config)
1270 let new_width = config.max_width() - body_indent.width();
1271 config.set().max_width(new_width);
1273 // First try to format as items, then as statements.
1274 let new_body_snippet = match ::format_snippet(&body_str, &config) {
1275 Some(new_body) => new_body,
1277 let new_width = new_width + config.tab_spaces();
1278 config.set().max_width(new_width);
1279 match ::format_code_block(&body_str, &config) {
1280 Some(new_body) => new_body,
1281 None => return None,
1285 let new_body = wrap_str(
1286 new_body_snippet.snippet.to_string(),
1291 // Indent the body since it is in a block.
1292 let indent_str = body_indent.to_string(&config);
1293 let mut new_body = LineClasses::new(new_body.trim_end())
1296 (String::new(), true),
1297 |(mut s, need_indent), (i, (kind, ref l))| {
1298 if !is_empty_line(l)
1300 && !new_body_snippet.is_line_non_formatted(i + 1)
1304 (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1309 // Undo our replacement of macro variables.
1310 // FIXME: this could be *much* more efficient.
1311 for (old, new) in &substs {
1312 if old_body.find(new).is_some() {
1313 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1316 new_body = new_body.replace(new, old);
1320 result += new_body.trim();
1321 } else if !new_body.is_empty() {
1323 result += &new_body;
1324 result += &shape.indent.to_string(&config);
1333 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1335 /// # Expected syntax
1339 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1340 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1342 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1345 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1346 let mut result = String::with_capacity(1024);
1347 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1348 let nested_shape = shape
1349 .block_indent(context.config.tab_spaces())
1350 .with_max_width(context.config);
1352 result.push_str("lazy_static! {");
1353 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1355 macro_rules! parse_or {
1356 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1357 match parser.$method($($arg,)*) {
1359 if parser.sess.span_diagnostic.has_errors() {
1360 parser.sess.span_diagnostic.reset_err_count();
1368 parser.sess.span_diagnostic.reset_err_count();
1375 while parser.token != Token::Eof {
1376 // Parse a `lazy_static!` item.
1377 let vis = ::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1378 parser.eat_keyword(symbol::keywords::Static);
1379 parser.eat_keyword(symbol::keywords::Ref);
1380 let id = parse_or!(parse_ident);
1381 parser.eat(&Token::Colon);
1382 let ty = parse_or!(parse_ty);
1383 parser.eat(&Token::Eq);
1384 let expr = parse_or!(parse_expr);
1385 parser.eat(&Token::Semi);
1387 // Rewrite as a static item.
1388 let mut stmt = String::with_capacity(128);
1389 stmt.push_str(&format!(
1390 "{}static ref {}: {} =",
1393 ty.rewrite(context, nested_shape)?
1395 result.push_str(&::expr::rewrite_assign_rhs(
1399 nested_shape.sub_width(1)?,
1402 if parser.token != Token::Eof {
1403 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1407 result.push_str(&shape.indent.to_string_with_newline(context.config));
1413 fn rewrite_macro_with_items(
1414 context: &RewriteContext,
1419 position: MacroPosition,
1421 ) -> Option<String> {
1422 let (opener, closer) = match style {
1423 DelimToken::Paren => ("(", ")"),
1424 DelimToken::Bracket => ("[", "]"),
1425 DelimToken::Brace => (" {", "}"),
1428 let trailing_semicolon = match style {
1429 DelimToken::Paren | DelimToken::Bracket if position == MacroPosition::Item => ";",
1433 let mut visitor = FmtVisitor::from_context(context);
1434 visitor.block_indent = shape.indent.block_indent(context.config);
1435 visitor.last_pos = context.snippet_provider.span_after(span, opener.trim());
1437 let item = match item {
1438 MacroArg::Item(item) => item,
1441 visitor.visit_item(&item);
1444 let mut result = String::with_capacity(256);
1445 result.push_str(¯o_name);
1446 result.push_str(opener);
1447 result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
1448 result.push_str(visitor.buffer.trim());
1449 result.push_str(&shape.indent.to_string_with_newline(context.config));
1450 result.push_str(closer);
1451 result.push_str(trailing_semicolon);