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::codemap::{BytePos, Span};
26 use syntax::parse::new_parser_from_tts;
27 use syntax::parse::parser::Parser;
28 use syntax::parse::token::{BinOpToken, DelimToken, Token};
29 use syntax::print::pprust;
31 use syntax::tokenstream::{Cursor, ThinTokenStream, TokenStream, TokenTree};
32 use syntax::util::ThinVec;
33 use syntax::{ast, ptr};
35 use codemap::SpanUtils;
37 contains_comment, remove_trailing_white_spaces, CharClasses, FindUncommented, FullCodeCharKind,
40 use expr::rewrite_array;
41 use lists::{itemize_list, write_list, ListFormatting};
43 use rewrite::{Rewrite, RewriteContext};
44 use shape::{Indent, Shape};
46 use utils::{format_visibility, mk_sp, rewrite_ident, wrap_str};
48 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
51 pub enum MacroPosition {
60 Expr(ptr::P<ast::Expr>),
62 Pat(ptr::P<ast::Pat>),
63 Item(ptr::P<ast::Item>),
66 impl Rewrite for ast::Item {
67 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
68 let mut visitor = ::visitor::FmtVisitor::from_context(context);
69 visitor.block_indent = shape.indent;
70 visitor.last_pos = self.span().lo();
71 visitor.visit_item(self);
76 impl Rewrite for MacroArg {
77 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
79 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
80 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
81 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
82 MacroArg::Item(ref item) => item.rewrite(context, shape),
87 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
88 macro_rules! parse_macro_arg {
89 ($macro_arg:ident, $parser:ident, $f:expr) => {
90 let mut cloned_parser = (*parser).clone();
91 match cloned_parser.$parser() {
93 if parser.sess.span_diagnostic.has_errors() {
94 parser.sess.span_diagnostic.reset_err_count();
97 *parser = cloned_parser;
98 return Some(MacroArg::$macro_arg($f(x)?));
103 parser.sess.span_diagnostic.reset_err_count();
109 parse_macro_arg!(Expr, parse_expr, |x: ptr::P<ast::Expr>| Some(x));
110 parse_macro_arg!(Ty, parse_ty, |x: ptr::P<ast::Ty>| Some(x));
111 parse_macro_arg!(Pat, parse_pat, |x: ptr::P<ast::Pat>| Some(x));
112 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
113 parse_macro_arg!(Item, parse_item, |x: Option<ptr::P<ast::Item>>| x);
118 /// Rewrite macro name without using pretty-printer if possible.
119 fn rewrite_macro_name(
120 context: &RewriteContext,
122 extra_ident: Option<ast::Ident>,
124 let name = if path.segments.len() == 1 {
125 // Avoid using pretty-printer in the common case.
126 format!("{}!", rewrite_ident(context, path.segments[0].ident))
131 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
136 // Use this on failing to format the macro call.
137 fn return_original_snippet_with_failure_marked(
138 context: &RewriteContext,
140 ) -> Option<String> {
141 context.macro_rewrite_failure.replace(true);
142 Some(context.snippet(span).to_owned())
145 struct InsideMacroGuard<'a> {
146 context: &'a RewriteContext<'a>,
150 impl<'a> InsideMacroGuard<'a> {
151 fn inside_macro_context(context: &'a RewriteContext) -> InsideMacroGuard<'a> {
152 let is_nested = context.inside_macro.replace(true);
153 InsideMacroGuard { context, is_nested }
157 impl<'a> Drop for InsideMacroGuard<'a> {
159 self.context.inside_macro.replace(self.is_nested);
163 pub fn rewrite_macro(
165 extra_ident: Option<ast::Ident>,
166 context: &RewriteContext,
168 position: MacroPosition,
169 ) -> Option<String> {
170 let guard = InsideMacroGuard::inside_macro_context(context);
171 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position);
172 if result.is_none() {
173 context.macro_rewrite_failure.replace(true);
178 pub fn rewrite_macro_inner(
180 extra_ident: Option<ast::Ident>,
181 context: &RewriteContext,
183 position: MacroPosition,
184 ) -> Option<String> {
185 if context.config.use_try_shorthand() {
186 if let Some(expr) = convert_try_mac(mac, context) {
187 context.inside_macro.replace(false);
188 return expr.rewrite(context, shape);
192 let original_style = macro_style(mac, context);
194 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
196 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
202 let ts: TokenStream = mac.node.stream();
203 let has_comment = contains_comment(context.snippet(mac.span));
204 if ts.is_empty() && !has_comment {
206 DelimToken::Paren if position == MacroPosition::Item => {
207 Some(format!("{}();", macro_name))
209 DelimToken::Paren => Some(format!("{}()", macro_name)),
210 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
211 DelimToken::Brace => Some(format!("{}{{}}", macro_name)),
215 // Format well-known macros which cannot be parsed as a valid AST.
216 if macro_name == "lazy_static!" && !has_comment {
217 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
222 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
223 let mut arg_vec = Vec::new();
224 let mut vec_with_semi = false;
225 let mut trailing_comma = false;
227 if DelimToken::Brace != style {
229 match parse_macro_arg(&mut parser) {
230 Some(arg) => arg_vec.push(arg),
231 None => return return_original_snippet_with_failure_marked(context, mac.span),
238 // Try to parse `vec![expr; expr]`
239 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
241 if parser.token != Token::Eof {
242 match parse_macro_arg(&mut parser) {
246 if parser.token == Token::Eof && arg_vec.len() == 2 {
247 vec_with_semi = true;
252 return return_original_snippet_with_failure_marked(
259 return return_original_snippet_with_failure_marked(context, mac.span);
261 _ => return return_original_snippet_with_failure_marked(context, mac.span),
266 if parser.token == Token::Eof {
267 trailing_comma = true;
274 DelimToken::Paren => {
275 // Format macro invocation as function call, preserve the trailing
276 // comma because not all macros support them.
277 overflow::rewrite_with_parens(
280 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>(),
283 context.config.width_heuristics().fn_call_width,
285 Some(SeparatorTactic::Always)
287 Some(SeparatorTactic::Never)
289 ).map(|rw| match position {
290 MacroPosition::Item => format!("{};", rw),
294 DelimToken::Bracket => {
295 // Handle special case: `vec![expr; expr]`
297 let mac_shape = shape.offset_left(macro_name.len())?;
298 // 8 = `vec![]` + `; `
299 let total_overhead = 8;
300 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
301 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
302 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
303 if !lhs.contains('\n')
304 && !rhs.contains('\n')
305 && lhs.len() + rhs.len() + total_overhead <= shape.width
307 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
312 nested_shape.indent.to_string_with_newline(context.config),
314 nested_shape.indent.to_string_with_newline(context.config),
316 shape.indent.to_string_with_newline(context.config),
320 // If we are rewriting `vec!` macro or other special macros,
321 // then we can rewrite this as an usual array literal.
322 // Otherwise, we must preserve the original existence of trailing comma.
323 let macro_name = ¯o_name.as_str();
324 let mut force_trailing_comma = if trailing_comma {
325 Some(SeparatorTactic::Always)
327 Some(SeparatorTactic::Never)
329 if FORCED_BRACKET_MACROS.contains(macro_name) {
330 context.inside_macro.replace(false);
331 if context.use_block_indent() {
332 force_trailing_comma = Some(SeparatorTactic::Vertical);
335 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
336 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>();
337 let rewrite = rewrite_array(
343 force_trailing_comma,
344 Some(original_style),
346 let comma = match position {
347 MacroPosition::Item => ";",
351 Some(format!("{}{}", rewrite, comma))
354 DelimToken::Brace => {
355 // Skip macro invocations with braces, for now.
356 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
362 pub fn rewrite_macro_def(
363 context: &RewriteContext,
368 vis: &ast::Visibility,
370 ) -> Option<String> {
371 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
372 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
376 let mut parser = MacroParser::new(def.stream().into_trees());
377 let parsed_def = match parser.parse() {
379 None => return snippet,
382 let mut result = if def.legacy {
383 String::from("macro_rules!")
385 format!("{}macro", format_visibility(context, vis))
389 result += rewrite_ident(context, ident);
391 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
393 let arm_shape = if multi_branch_style {
395 .block_indent(context.config.tab_spaces())
396 .with_max_width(context.config)
401 let branch_items = itemize_list(
402 context.snippet_provider,
403 parsed_def.branches.iter(),
406 |branch| branch.span.lo(),
407 |branch| branch.span.hi(),
408 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
409 context.snippet_provider.span_after(span, "{"),
412 ).collect::<Vec<_>>();
414 let fmt = ListFormatting {
415 tactic: DefinitiveListTactic::Vertical,
416 separator: if def.legacy { ";" } else { "" },
417 trailing_separator: SeparatorTactic::Always,
418 separator_place: SeparatorPlace::Back,
420 ends_with_newline: true,
421 preserve_newline: true,
423 config: context.config,
426 if multi_branch_style {
428 result += &arm_shape.indent.to_string_with_newline(context.config);
431 match write_list(&branch_items, &fmt) {
432 Some(ref s) => result += s,
433 None => return snippet,
436 if multi_branch_style {
437 result += &indent.to_string_with_newline(context.config);
444 fn register_metavariable(
445 map: &mut HashMap<String, String>,
450 let mut new_name = String::new();
451 let mut old_name = String::new();
454 for _ in 0..(dollar_count - 1) {
459 new_name.push_str(&name);
460 old_name.push_str(&name);
462 result.push_str(&new_name);
463 map.insert(old_name, new_name);
466 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
467 // aren't causing problems.
468 // This should also work for escaped `$` variables, where we leave earlier `$`s.
469 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
470 // Each substitution will require five or six extra bytes.
471 let mut result = String::with_capacity(input.len() + 64);
472 let mut substs = HashMap::new();
473 let mut dollar_count = 0;
474 let mut cur_name = String::new();
476 for (kind, c) in CharClasses::new(input.chars()) {
477 if kind != FullCodeCharKind::Normal {
481 } else if dollar_count == 0 {
483 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
484 // Terminates a name following one or more dollars.
485 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
490 } else if c == '(' && cur_name.is_empty() {
491 // FIXME: Support macro def with repeat.
493 } else if c.is_alphanumeric() || c == '_' {
498 if !cur_name.is_empty() {
499 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
502 debug!("replace_names `{}` {:?}", result, substs);
504 Some((result, substs))
507 #[derive(Debug, Clone)]
510 MetaVariable(ast::Ident, String),
511 /// e.g. `$($foo: expr),*`
513 /// `()`, `[]` or `{}`.
515 /// Inner arguments inside delimiters.
517 /// Something after the closing delimiter and the repeat token, if available.
518 Option<Box<ParsedMacroArg>>,
519 /// The repeat token. This could be one of `*`, `+` or `?`.
522 /// e.g. `[derive(Debug)]`
523 Delimited(DelimToken, Vec<ParsedMacroArg>),
524 /// A possible separator. e.g. `,` or `;`.
525 Separator(String, String),
526 /// Other random stuff that does not fit to other kinds.
527 /// e.g. `== foo` in `($x: expr == foo)`.
528 Other(String, String),
531 fn delim_token_to_str(
532 context: &RewriteContext,
533 delim_token: &DelimToken,
535 use_multiple_lines: bool,
536 inner_is_empty: bool,
537 ) -> (String, String) {
538 let (lhs, rhs) = match *delim_token {
539 DelimToken::Paren => ("(", ")"),
540 DelimToken::Bracket => ("[", "]"),
541 DelimToken::Brace => {
542 if inner_is_empty || use_multiple_lines {
548 DelimToken::NoDelim => ("", ""),
550 if use_multiple_lines {
551 let indent_str = shape.indent.to_string_with_newline(context.config);
552 let nested_indent_str = shape
554 .block_indent(context.config)
555 .to_string_with_newline(context.config);
557 format!("{}{}", lhs, nested_indent_str),
558 format!("{}{}", indent_str, rhs),
561 (lhs.to_owned(), rhs.to_owned())
566 fn starts_with_brace(&self) -> bool {
568 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
569 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
574 fn starts_with_dollar(&self) -> bool {
576 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
581 fn ends_with_space(&self) -> bool {
583 MacroArgKind::Separator(..) => true,
588 fn has_meta_var(&self) -> bool {
590 MacroArgKind::MetaVariable(..) => true,
591 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
598 context: &RewriteContext,
600 use_multiple_lines: bool,
601 ) -> Option<String> {
602 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
603 let inner = wrap_macro_args(context, args, shape)?;
604 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
605 if lhs.len() + inner.len() + rhs.len() <= shape.width {
606 return Some((lhs, inner, rhs));
609 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
610 let nested_shape = shape
611 .block_indent(context.config.tab_spaces())
612 .with_max_width(context.config);
613 let inner = wrap_macro_args(context, args, nested_shape)?;
614 Some((lhs, inner, rhs))
618 MacroArgKind::MetaVariable(ty, ref name) => {
619 Some(format!("${}:{}", name, ty.name.as_str()))
621 MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
622 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
623 let another = another
625 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
626 .unwrap_or_else(|| "".to_owned());
627 let repeat_tok = pprust::token_to_string(tok);
629 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
631 MacroArgKind::Delimited(ref delim_tok, ref args) => {
632 rewrite_delimited_inner(delim_tok, args)
633 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
635 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
636 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
641 #[derive(Debug, Clone)]
642 struct ParsedMacroArg {
647 impl ParsedMacroArg {
650 context: &RewriteContext,
652 use_multiple_lines: bool,
653 ) -> Option<String> {
654 self.kind.rewrite(context, shape, use_multiple_lines)
658 /// Parses macro arguments on macro def.
659 struct MacroArgParser {
660 /// Holds either a name of the next metavariable, a separator or a junk.
662 /// The start position on the current buffer.
664 /// The first token of the current buffer.
666 /// Set to true if we are parsing a metavariable or a repeat.
668 /// The position of the last token.
670 /// The last token parsed.
672 /// Holds the parsed arguments.
673 result: Vec<ParsedMacroArg>,
676 fn last_tok(tt: &TokenTree) -> Token {
678 TokenTree::Token(_, ref t) => t.clone(),
679 TokenTree::Delimited(_, ref d) => d.close_token(),
683 impl MacroArgParser {
684 pub fn new() -> MacroArgParser {
690 last_tok: Token::Eof,
691 start_tok: Token::Eof,
696 fn set_last_tok(&mut self, tok: &TokenTree) {
697 self.hi = tok.span().hi();
698 self.last_tok = last_tok(tok);
701 fn add_separator(&mut self) {
702 let prefix = if self.need_space_prefix() {
707 self.result.push(ParsedMacroArg {
708 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
709 span: mk_sp(self.lo, self.hi),
714 fn add_other(&mut self) {
715 let prefix = if self.need_space_prefix() {
720 self.result.push(ParsedMacroArg {
721 kind: MacroArgKind::Other(self.buf.clone(), prefix),
722 span: mk_sp(self.lo, self.hi),
727 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
729 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
730 self.result.push(ParsedMacroArg {
731 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
732 span: mk_sp(self.lo, sp.hi()),
736 self.is_meta_var = false;
743 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
744 self.result.push(ParsedMacroArg {
745 kind: MacroArgKind::Delimited(delim, inner),
753 inner: Vec<ParsedMacroArg>,
758 let mut buffer = String::new();
759 let mut first = false;
760 let mut lo = span.lo();
761 let mut hi = span.hi();
763 // Parse '*', '+' or '?.
764 for ref tok in iter {
765 self.set_last_tok(tok);
768 lo = tok.span().lo();
772 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
773 | TokenTree::Token(_, Token::Question)
774 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
777 TokenTree::Token(sp, ref t) => {
778 buffer.push_str(&pprust::token_to_string(t));
785 // There could be some random stuff between ')' and '*', '+' or '?'.
786 let another = if buffer.trim().is_empty() {
789 Some(Box::new(ParsedMacroArg {
790 kind: MacroArgKind::Other(buffer, "".to_owned()),
795 self.result.push(ParsedMacroArg {
796 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
797 span: mk_sp(self.lo, self.hi),
802 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
803 if self.buf.is_empty() {
805 self.start_tok = t.clone();
807 let needs_space = match next_space(&self.last_tok) {
808 SpaceState::Ident => ident_like(t),
809 SpaceState::Punctuation => !ident_like(t),
810 SpaceState::Always => true,
811 SpaceState::Never => false,
813 if force_space_before(t) || needs_space {
818 self.buf.push_str(&pprust::token_to_string(t));
821 fn need_space_prefix(&self) -> bool {
822 if self.result.is_empty() {
826 let last_arg = self.result.last().unwrap();
827 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
828 if ident_like(&self.start_tok) {
831 if self.start_tok == Token::Colon {
836 if force_space_before(&self.start_tok) {
843 /// Returns a collection of parsed macro def's arguments.
844 pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
845 let mut iter = (tokens.into(): TokenStream).trees();
847 while let Some(ref tok) = iter.next() {
849 TokenTree::Token(sp, Token::Dollar) => {
850 // We always want to add a separator before meta variables.
851 if !self.buf.is_empty() {
852 self.add_separator();
855 // Start keeping the name of this metavariable in the buffer.
856 self.is_meta_var = true;
858 self.start_tok = Token::Dollar;
860 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
861 self.add_meta_variable(&mut iter)?;
863 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
864 TokenTree::Delimited(sp, delimited) => {
865 if !self.buf.is_empty() {
866 if next_space(&self.last_tok) == SpaceState::Always {
867 self.add_separator();
873 // Parse the stuff inside delimiters.
874 let mut parser = MacroArgParser::new();
876 let delimited_arg = parser.parse(delimited.tts.clone())?;
878 if self.is_meta_var {
879 self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp)?;
880 self.is_meta_var = false;
882 self.add_delimited(delimited_arg, delimited.delim, *sp);
887 self.set_last_tok(tok);
890 // We are left with some stuff in the buffer. Since there is nothing
891 // left to separate, add this as `Other`.
892 if !self.buf.is_empty() {
901 context: &RewriteContext,
902 args: &[ParsedMacroArg],
904 ) -> Option<String> {
905 wrap_macro_args_inner(context, args, shape, false)
906 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
909 fn wrap_macro_args_inner(
910 context: &RewriteContext,
911 args: &[ParsedMacroArg],
913 use_multiple_lines: bool,
914 ) -> Option<String> {
915 let mut result = String::with_capacity(128);
916 let mut iter = args.iter().peekable();
917 let indent_str = shape.indent.to_string_with_newline(context.config);
919 while let Some(ref arg) = iter.next() {
920 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
922 if use_multiple_lines
923 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
925 if arg.kind.ends_with_space() {
928 result.push_str(&indent_str);
929 } else if let Some(ref next_arg) = iter.peek() {
930 let space_before_dollar =
931 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
932 let space_before_brace = next_arg.kind.starts_with_brace();
933 if space_before_dollar || space_before_brace {
939 if !use_multiple_lines && result.len() >= shape.width {
946 // This is a bit sketchy. The token rules probably need tweaking, but it works
947 // for some common cases. I hope the basic logic is sufficient. Note that the
948 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
949 // and `(`/`)` have special meaning.
951 // We always try and format on one line.
952 // FIXME: Use multi-line when every thing does not fit on one line.
953 fn format_macro_args(
954 context: &RewriteContext,
955 toks: ThinTokenStream,
957 ) -> Option<String> {
958 if !context.config.format_macro_matchers() {
959 let token_stream: TokenStream = toks.into();
960 let span = span_for_token_stream(token_stream);
961 return Some(match span {
962 Some(span) => context.snippet(span).to_owned(),
963 None => String::new(),
966 let parsed_args = MacroArgParser::new().parse(toks)?;
967 wrap_macro_args(context, &parsed_args, shape)
970 fn span_for_token_stream(token_stream: TokenStream) -> Option<Span> {
971 token_stream.trees().next().map(|tt| tt.span())
974 // We should insert a space if the next token is a:
975 #[derive(Copy, Clone, PartialEq)]
979 Ident, // Or ident/literal-like thing.
983 fn force_space_before(tok: &Token) -> bool {
984 debug!("tok: force_space_before {:?}", tok);
1005 | Token::Dollar => true,
1010 fn ident_like(tok: &Token) -> bool {
1012 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1017 fn next_space(tok: &Token) -> SpaceState {
1018 debug!("next_space: {:?}", tok);
1022 | Token::BinOp(BinOpToken::And)
1031 | Token::Question => SpaceState::Punctuation,
1036 | Token::OpenDelim(_)
1037 | Token::CloseDelim(_)
1038 | Token::Whitespace => SpaceState::Never,
1040 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1042 _ => SpaceState::Always,
1046 /// Tries to convert a macro use into a short hand try expression. Returns None
1047 /// when the macro is not an instance of try! (or parsing the inner expression
1049 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1050 if &format!("{}", mac.node.path) == "try" {
1051 let ts: TokenStream = mac.node.tts.clone().into();
1052 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1055 id: ast::NodeId::new(0), // dummy value
1056 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1057 span: mac.span, // incorrect span, but shouldn't matter too much
1058 attrs: ThinVec::new(),
1065 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1066 let snippet = context.snippet(mac.span);
1067 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1068 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1069 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1071 if paren_pos < bracket_pos && paren_pos < brace_pos {
1073 } else if bracket_pos < brace_pos {
1080 /// Indent each line according to the specified `indent`.
1108 fn indent_macro_snippet(
1109 context: &RewriteContext,
1112 ) -> Option<String> {
1113 let mut lines = LineClasses::new(macro_str);
1114 let first_line = lines.next().map(|(_, s)| s.trim_right().to_owned())?;
1115 let mut trimmed_lines = Vec::with_capacity(16);
1117 let mut veto_trim = false;
1118 let min_prefix_space_width = lines
1119 .filter_map(|(kind, line)| {
1120 let mut trimmed = true;
1121 let prefix_space_width = if is_empty_line(&line) {
1124 Some(get_prefix_space_width(context, &line))
1126 let line = if veto_trim || (kind.is_string() && !line.ends_with('\\')) {
1127 veto_trim = kind.is_string() && !line.ends_with('\\');
1131 line.trim().to_owned()
1133 trimmed_lines.push((trimmed, line, prefix_space_width));
1138 first_line + "\n" + &trimmed_lines
1141 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
1142 _ if !trimmed => line.to_owned(),
1143 Some(original_indent_width) => {
1144 let new_indent_width = indent.width() + original_indent_width
1145 .saturating_sub(min_prefix_space_width);
1146 let new_indent = Indent::from_width(context.config, new_indent_width);
1147 format!("{}{}", new_indent.to_string(context.config), line.trim())
1149 None => String::new(),
1151 ).collect::<Vec<_>>()
1156 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1158 for c in s.chars() {
1161 '\t' => width += context.config.tab_spaces(),
1168 fn is_empty_line(s: &str) -> bool {
1169 s.is_empty() || s.chars().all(char::is_whitespace)
1172 // A very simple parser that just parses a macros 2.0 definition into its branches.
1173 // Currently we do not attempt to parse any further than that.
1175 struct MacroParser {
1180 // (`(` ... `)` `=>` `{` ... `}`)*
1181 fn parse(&mut self) -> Option<Macro> {
1182 let mut branches = vec![];
1183 while self.toks.look_ahead(1).is_some() {
1184 branches.push(self.parse_branch()?);
1187 Some(Macro { branches })
1190 // `(` ... `)` `=>` `{` ... `}`
1191 fn parse_branch(&mut self) -> Option<MacroBranch> {
1192 let tok = self.toks.next()?;
1193 let (lo, args_paren_kind) = match tok {
1194 TokenTree::Token(..) => return None,
1195 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1197 let args = tok.joint().into();
1198 match self.toks.next()? {
1199 TokenTree::Token(_, Token::FatArrow) => {}
1202 let (mut hi, body, whole_body) = match self.toks.next()? {
1203 TokenTree::Token(..) => return None,
1204 TokenTree::Delimited(sp, _) => {
1205 let data = sp.data();
1208 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1213 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1218 span: mk_sp(lo, hi),
1227 // A parsed macros 2.0 macro definition.
1229 branches: Vec<MacroBranch>,
1232 // FIXME: it would be more efficient to use references to the token streams
1233 // rather than clone them, if we can make the borrowing work out.
1234 struct MacroBranch {
1236 args_paren_kind: DelimToken,
1237 args: ThinTokenStream,
1245 context: &RewriteContext,
1247 multi_branch_style: bool,
1248 ) -> Option<String> {
1249 // Only attempt to format function-like macros.
1250 if self.args_paren_kind != DelimToken::Paren {
1251 // FIXME(#1539): implement for non-sugared macros.
1256 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1258 if multi_branch_style {
1262 if !context.config.format_macro_bodies() {
1264 result += context.snippet(self.whole_body);
1265 return Some(result);
1268 // The macro body is the most interesting part. It might end up as various
1269 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1270 // parsed as regular Rust code (and note that these can be escaped using
1271 // `$$`). We'll try and format like an AST node, but we'll substitute
1272 // variables for new names with the same length first.
1274 let old_body = context.snippet(self.body).trim();
1275 let (body_str, substs) = replace_names(old_body)?;
1276 let has_block_body = old_body.starts_with('{');
1278 let mut config = context.config.clone();
1279 config.set().hide_parse_errors(true);
1283 let body_indent = if has_block_body {
1286 // We'll hack the indent below, take this into account when formatting,
1287 let body_indent = shape.indent.block_indent(&config);
1288 let new_width = config.max_width() - body_indent.width();
1289 config.set().max_width(new_width);
1293 // First try to format as items, then as statements.
1294 let new_body = match ::format_snippet(&body_str, &config) {
1295 Some(new_body) => new_body,
1296 None => match ::format_code_block(&body_str, &config) {
1297 Some(new_body) => new_body,
1298 None => return None,
1301 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1303 // Indent the body since it is in a block.
1304 let indent_str = body_indent.to_string(&config);
1305 let mut new_body = LineClasses::new(new_body.trim_right())
1307 (String::new(), true),
1308 |(mut s, need_indent), (kind, ref l)| {
1309 if !l.is_empty() && need_indent {
1312 (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1316 // Undo our replacement of macro variables.
1317 // FIXME: this could be *much* more efficient.
1318 for (old, new) in &substs {
1319 if old_body.find(new).is_some() {
1320 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1323 new_body = new_body.replace(new, old);
1327 result += new_body.trim();
1328 } else if !new_body.is_empty() {
1330 result += &new_body;
1331 result += &shape.indent.to_string(&config);
1340 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1342 /// # Expected syntax
1346 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1347 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1349 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1352 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1353 let mut result = String::with_capacity(1024);
1354 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1355 let nested_shape = shape
1356 .block_indent(context.config.tab_spaces())
1357 .with_max_width(context.config);
1359 result.push_str("lazy_static! {");
1360 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1362 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1363 match parser.$method($($arg,)*) {
1365 if parser.sess.span_diagnostic.has_errors() {
1366 parser.sess.span_diagnostic.reset_err_count();
1374 parser.sess.span_diagnostic.reset_err_count();
1380 while parser.token != Token::Eof {
1381 // Parse a `lazy_static!` item.
1382 let vis = ::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1383 parser.eat_keyword(symbol::keywords::Static);
1384 parser.eat_keyword(symbol::keywords::Ref);
1385 let id = parse_or!(parse_ident);
1386 parser.eat(&Token::Colon);
1387 let ty = parse_or!(parse_ty);
1388 parser.eat(&Token::Eq);
1389 let expr = parse_or!(parse_expr);
1390 parser.eat(&Token::Semi);
1392 // Rewrite as a static item.
1393 let mut stmt = String::with_capacity(128);
1394 stmt.push_str(&format!(
1395 "{}static ref {}: {} =",
1398 ty.rewrite(context, nested_shape)?
1400 result.push_str(&::expr::rewrite_assign_rhs(
1404 nested_shape.sub_width(1)?,
1407 if parser.token != Token::Eof {
1408 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1412 result.push_str(&shape.indent.to_string_with_newline(context.config));