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, ptr};
36 contains_comment, remove_trailing_white_spaces, CharClasses, FindUncommented, FullCodeCharKind,
39 use expr::rewrite_array;
40 use lists::{itemize_list, write_list, ListFormatting};
42 use rewrite::{Rewrite, RewriteContext};
43 use shape::{Indent, Shape};
44 use source_map::SpanUtils;
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);
72 Some(visitor.buffer.to_owned())
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, guard.is_nested);
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 is_nested_macro: bool,
185 ) -> Option<String> {
186 if context.config.use_try_shorthand() {
187 if let Some(expr) = convert_try_mac(mac, context) {
188 context.inside_macro.replace(false);
189 return expr.rewrite(context, shape);
193 let original_style = macro_style(mac, context);
195 let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
197 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) && !is_nested_macro {
203 let ts: TokenStream = mac.node.stream();
204 let has_comment = contains_comment(context.snippet(mac.span));
205 if ts.is_empty() && !has_comment {
207 DelimToken::Paren if position == MacroPosition::Item => {
208 Some(format!("{}();", macro_name))
210 DelimToken::Paren => Some(format!("{}()", macro_name)),
211 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
212 DelimToken::Brace => Some(format!("{}{{}}", macro_name)),
216 // Format well-known macros which cannot be parsed as a valid AST.
217 if macro_name == "lazy_static!" && !has_comment {
218 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
223 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
224 let mut arg_vec = Vec::new();
225 let mut vec_with_semi = false;
226 let mut trailing_comma = false;
228 if DelimToken::Brace != style {
230 match parse_macro_arg(&mut parser) {
231 Some(arg) => arg_vec.push(arg),
232 None => return return_original_snippet_with_failure_marked(context, mac.span),
239 // Try to parse `vec![expr; expr]`
240 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
242 if parser.token != Token::Eof {
243 match parse_macro_arg(&mut parser) {
247 if parser.token == Token::Eof && arg_vec.len() == 2 {
248 vec_with_semi = true;
253 return return_original_snippet_with_failure_marked(
260 return return_original_snippet_with_failure_marked(context, mac.span);
262 _ => return return_original_snippet_with_failure_marked(context, mac.span),
267 if parser.token == Token::Eof {
268 trailing_comma = true;
275 DelimToken::Paren => {
276 // Format macro invocation as function call, preserve the trailing
277 // comma because not all macros support them.
278 overflow::rewrite_with_parens(
284 context.config.width_heuristics().fn_call_width,
286 Some(SeparatorTactic::Always)
288 Some(SeparatorTactic::Never)
291 .map(|rw| match position {
292 MacroPosition::Item => format!("{};", rw),
296 DelimToken::Bracket => {
297 // Handle special case: `vec![expr; expr]`
299 let mac_shape = shape.offset_left(macro_name.len())?;
300 // 8 = `vec![]` + `; `
301 let total_overhead = 8;
302 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
303 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
304 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
305 if !lhs.contains('\n')
306 && !rhs.contains('\n')
307 && lhs.len() + rhs.len() + total_overhead <= shape.width
309 Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
314 nested_shape.indent.to_string_with_newline(context.config),
316 nested_shape.indent.to_string_with_newline(context.config),
318 shape.indent.to_string_with_newline(context.config),
322 // If we are rewriting `vec!` macro or other special macros,
323 // then we can rewrite this as an usual array literal.
324 // Otherwise, we must preserve the original existence of trailing comma.
325 let macro_name = ¯o_name.as_str();
326 let mut force_trailing_comma = if trailing_comma {
327 Some(SeparatorTactic::Always)
329 Some(SeparatorTactic::Never)
331 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
332 context.inside_macro.replace(false);
333 if context.use_block_indent() {
334 force_trailing_comma = Some(SeparatorTactic::Vertical);
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| match branch.rewrite(context, arm_shape, multi_branch_style) {
410 // if the rewrite returned None because a macro could not be rewritten, then return the
412 None if *context.macro_rewrite_failure.borrow() == true => {
413 Some(context.snippet(branch.body).trim().to_string())
417 context.snippet_provider.span_after(span, "{"),
421 .collect::<Vec<_>>();
423 let fmt = ListFormatting::new(arm_shape, context.config)
424 .separator(if def.legacy { ";" } else { "" })
425 .trailing_separator(SeparatorTactic::Always)
426 .preserve_newline(true);
428 if multi_branch_style {
430 result += &arm_shape.indent.to_string_with_newline(context.config);
433 match write_list(&branch_items, &fmt) {
434 Some(ref s) => result += s,
435 None => return snippet,
438 if multi_branch_style {
439 result += &indent.to_string_with_newline(context.config);
446 fn register_metavariable(
447 map: &mut HashMap<String, String>,
452 let mut new_name = String::new();
453 let mut old_name = String::new();
456 for _ in 0..(dollar_count - 1) {
461 new_name.push_str(&name);
462 old_name.push_str(&name);
464 result.push_str(&new_name);
465 map.insert(old_name, new_name);
468 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
469 // aren't causing problems.
470 // This should also work for escaped `$` variables, where we leave earlier `$`s.
471 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
472 // Each substitution will require five or six extra bytes.
473 let mut result = String::with_capacity(input.len() + 64);
474 let mut substs = HashMap::new();
475 let mut dollar_count = 0;
476 let mut cur_name = String::new();
478 for (kind, c) in CharClasses::new(input.chars()) {
479 if kind != FullCodeCharKind::Normal {
483 } else if dollar_count == 0 {
485 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
486 // Terminates a name following one or more dollars.
487 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
492 } else if c == '(' && cur_name.is_empty() {
493 // FIXME: Support macro def with repeat.
495 } else if c.is_alphanumeric() || c == '_' {
500 if !cur_name.is_empty() {
501 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
504 debug!("replace_names `{}` {:?}", result, substs);
506 Some((result, substs))
509 #[derive(Debug, Clone)]
512 MetaVariable(ast::Ident, String),
513 /// e.g. `$($foo: expr),*`
515 /// `()`, `[]` or `{}`.
517 /// Inner arguments inside delimiters.
519 /// Something after the closing delimiter and the repeat token, if available.
520 Option<Box<ParsedMacroArg>>,
521 /// The repeat token. This could be one of `*`, `+` or `?`.
524 /// e.g. `[derive(Debug)]`
525 Delimited(DelimToken, Vec<ParsedMacroArg>),
526 /// A possible separator. e.g. `,` or `;`.
527 Separator(String, String),
528 /// Other random stuff that does not fit to other kinds.
529 /// e.g. `== foo` in `($x: expr == foo)`.
530 Other(String, String),
533 fn delim_token_to_str(
534 context: &RewriteContext,
535 delim_token: DelimToken,
537 use_multiple_lines: bool,
538 inner_is_empty: bool,
539 ) -> (String, String) {
540 let (lhs, rhs) = match delim_token {
541 DelimToken::Paren => ("(", ")"),
542 DelimToken::Bracket => ("[", "]"),
543 DelimToken::Brace => {
544 if inner_is_empty || use_multiple_lines {
550 DelimToken::NoDelim => ("", ""),
552 if use_multiple_lines {
553 let indent_str = shape.indent.to_string_with_newline(context.config);
554 let nested_indent_str = shape
556 .block_indent(context.config)
557 .to_string_with_newline(context.config);
559 format!("{}{}", lhs, nested_indent_str),
560 format!("{}{}", indent_str, rhs),
563 (lhs.to_owned(), rhs.to_owned())
568 fn starts_with_brace(&self) -> bool {
570 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
571 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
576 fn starts_with_dollar(&self) -> bool {
578 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
583 fn ends_with_space(&self) -> bool {
585 MacroArgKind::Separator(..) => true,
590 fn has_meta_var(&self) -> bool {
592 MacroArgKind::MetaVariable(..) => true,
593 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
600 context: &RewriteContext,
602 use_multiple_lines: bool,
603 ) -> Option<String> {
604 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
605 let inner = wrap_macro_args(context, args, shape)?;
606 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
607 if lhs.len() + inner.len() + rhs.len() <= shape.width {
608 return Some((lhs, inner, rhs));
611 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
612 let nested_shape = shape
613 .block_indent(context.config.tab_spaces())
614 .with_max_width(context.config);
615 let inner = wrap_macro_args(context, args, nested_shape)?;
616 Some((lhs, inner, rhs))
620 MacroArgKind::MetaVariable(ty, ref name) => {
621 Some(format!("${}:{}", name, ty.name.as_str()))
623 MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
624 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
625 let another = another
627 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
628 .unwrap_or_else(|| "".to_owned());
629 let repeat_tok = pprust::token_to_string(tok);
631 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
633 MacroArgKind::Delimited(delim_tok, ref args) => {
634 rewrite_delimited_inner(delim_tok, args)
635 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
637 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
638 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
643 #[derive(Debug, Clone)]
644 struct ParsedMacroArg {
649 impl ParsedMacroArg {
652 context: &RewriteContext,
654 use_multiple_lines: bool,
655 ) -> Option<String> {
656 self.kind.rewrite(context, shape, use_multiple_lines)
660 /// Parses macro arguments on macro def.
661 struct MacroArgParser {
662 /// Holds either a name of the next metavariable, a separator or a junk.
664 /// The start position on the current buffer.
666 /// The first token of the current buffer.
668 /// Set to true if we are parsing a metavariable or a repeat.
670 /// The position of the last token.
672 /// The last token parsed.
674 /// Holds the parsed arguments.
675 result: Vec<ParsedMacroArg>,
678 fn last_tok(tt: &TokenTree) -> Token {
680 TokenTree::Token(_, ref t) => t.clone(),
681 TokenTree::Delimited(_, ref d) => d.close_token(),
685 impl MacroArgParser {
686 pub fn new() -> MacroArgParser {
692 last_tok: Token::Eof,
693 start_tok: Token::Eof,
698 fn set_last_tok(&mut self, tok: &TokenTree) {
699 self.hi = tok.span().hi();
700 self.last_tok = last_tok(tok);
703 fn add_separator(&mut self) {
704 let prefix = if self.need_space_prefix() {
709 self.result.push(ParsedMacroArg {
710 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
711 span: mk_sp(self.lo, self.hi),
716 fn add_other(&mut self) {
717 let prefix = if self.need_space_prefix() {
722 self.result.push(ParsedMacroArg {
723 kind: MacroArgKind::Other(self.buf.clone(), prefix),
724 span: mk_sp(self.lo, self.hi),
729 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
731 Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
732 self.result.push(ParsedMacroArg {
733 kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
734 span: mk_sp(self.lo, sp.hi()),
738 self.is_meta_var = false;
745 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
746 self.result.push(ParsedMacroArg {
747 kind: MacroArgKind::Delimited(delim, inner),
755 inner: Vec<ParsedMacroArg>,
760 let mut buffer = String::new();
761 let mut first = false;
762 let mut lo = span.lo();
763 let mut hi = span.hi();
765 // Parse '*', '+' or '?.
767 self.set_last_tok(&tok);
770 lo = tok.span().lo();
774 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
775 | TokenTree::Token(_, Token::Question)
776 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
779 TokenTree::Token(sp, ref t) => {
780 buffer.push_str(&pprust::token_to_string(t));
787 // There could be some random stuff between ')' and '*', '+' or '?'.
788 let another = if buffer.trim().is_empty() {
791 Some(Box::new(ParsedMacroArg {
792 kind: MacroArgKind::Other(buffer, "".to_owned()),
797 self.result.push(ParsedMacroArg {
798 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
799 span: mk_sp(self.lo, self.hi),
804 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
805 if self.buf.is_empty() {
807 self.start_tok = t.clone();
809 let needs_space = match next_space(&self.last_tok) {
810 SpaceState::Ident => ident_like(t),
811 SpaceState::Punctuation => !ident_like(t),
812 SpaceState::Always => true,
813 SpaceState::Never => false,
815 if force_space_before(t) || needs_space {
820 self.buf.push_str(&pprust::token_to_string(t));
823 fn need_space_prefix(&self) -> bool {
824 if self.result.is_empty() {
828 let last_arg = self.result.last().unwrap();
829 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
830 if ident_like(&self.start_tok) {
833 if self.start_tok == Token::Colon {
838 if force_space_before(&self.start_tok) {
845 /// Returns a collection of parsed macro def's arguments.
846 pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
847 let mut iter = (tokens.into(): TokenStream).trees();
849 while let Some(ref tok) = iter.next() {
851 TokenTree::Token(sp, Token::Dollar) => {
852 // We always want to add a separator before meta variables.
853 if !self.buf.is_empty() {
854 self.add_separator();
857 // Start keeping the name of this metavariable in the buffer.
858 self.is_meta_var = true;
860 self.start_tok = Token::Dollar;
862 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
863 self.add_meta_variable(&mut iter)?;
865 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
866 TokenTree::Delimited(delimited_span, delimited) => {
867 if !self.buf.is_empty() {
868 if next_space(&self.last_tok) == SpaceState::Always {
869 self.add_separator();
875 // Parse the stuff inside delimiters.
876 let mut parser = MacroArgParser::new();
877 parser.lo = delimited_span.open.lo();
878 let delimited_arg = parser.parse(delimited.tts.clone())?;
880 let span = delimited_span.entire();
881 if self.is_meta_var {
882 self.add_repeat(delimited_arg, delimited.delim, &mut iter, span)?;
883 self.is_meta_var = false;
885 self.add_delimited(delimited_arg, delimited.delim, span);
890 self.set_last_tok(tok);
893 // We are left with some stuff in the buffer. Since there is nothing
894 // left to separate, add this as `Other`.
895 if !self.buf.is_empty() {
904 context: &RewriteContext,
905 args: &[ParsedMacroArg],
907 ) -> Option<String> {
908 wrap_macro_args_inner(context, args, shape, false)
909 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
912 fn wrap_macro_args_inner(
913 context: &RewriteContext,
914 args: &[ParsedMacroArg],
916 use_multiple_lines: bool,
917 ) -> Option<String> {
918 let mut result = String::with_capacity(128);
919 let mut iter = args.iter().peekable();
920 let indent_str = shape.indent.to_string_with_newline(context.config);
922 while let Some(ref arg) = iter.next() {
923 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
925 if use_multiple_lines
926 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
928 if arg.kind.ends_with_space() {
931 result.push_str(&indent_str);
932 } else if let Some(ref next_arg) = iter.peek() {
933 let space_before_dollar =
934 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
935 let space_before_brace = next_arg.kind.starts_with_brace();
936 if space_before_dollar || space_before_brace {
942 if !use_multiple_lines && result.len() >= shape.width {
949 // This is a bit sketchy. The token rules probably need tweaking, but it works
950 // for some common cases. I hope the basic logic is sufficient. Note that the
951 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
952 // and `(`/`)` have special meaning.
954 // We always try and format on one line.
955 // FIXME: Use multi-line when every thing does not fit on one line.
956 fn format_macro_args(
957 context: &RewriteContext,
958 toks: ThinTokenStream,
960 ) -> Option<String> {
961 if !context.config.format_macro_matchers() {
962 let token_stream: TokenStream = toks.into();
963 let span = span_for_token_stream(token_stream);
964 return Some(match span {
965 Some(span) => context.snippet(span).to_owned(),
966 None => String::new(),
969 let parsed_args = MacroArgParser::new().parse(toks)?;
970 wrap_macro_args(context, &parsed_args, shape)
973 fn span_for_token_stream(token_stream: TokenStream) -> Option<Span> {
974 token_stream.trees().next().map(|tt| tt.span())
977 // We should insert a space if the next token is a:
978 #[derive(Copy, Clone, PartialEq)]
982 Ident, // Or ident/literal-like thing.
986 fn force_space_before(tok: &Token) -> bool {
987 debug!("tok: force_space_before {:?}", tok);
1008 | Token::Dollar => true,
1013 fn ident_like(tok: &Token) -> bool {
1015 Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
1020 fn next_space(tok: &Token) -> SpaceState {
1021 debug!("next_space: {:?}", tok);
1025 | Token::BinOp(BinOpToken::And)
1034 | Token::Question => SpaceState::Punctuation,
1039 | Token::OpenDelim(_)
1040 | Token::CloseDelim(_)
1041 | Token::Whitespace => SpaceState::Never,
1043 Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1045 _ => SpaceState::Always,
1049 /// Tries to convert a macro use into a short hand try expression. Returns None
1050 /// when the macro is not an instance of try! (or parsing the inner expression
1052 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1053 if &format!("{}", mac.node.path) == "try" {
1054 let ts: TokenStream = mac.node.tts.clone().into();
1055 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1058 id: ast::NodeId::new(0), // dummy value
1059 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1060 span: mac.span, // incorrect span, but shouldn't matter too much
1061 attrs: ThinVec::new(),
1068 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1069 let snippet = context.snippet(mac.span);
1070 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1071 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1072 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1074 if paren_pos < bracket_pos && paren_pos < brace_pos {
1076 } else if bracket_pos < brace_pos {
1083 /// Indent each line according to the specified `indent`.
1111 fn indent_macro_snippet(
1112 context: &RewriteContext,
1115 ) -> Option<String> {
1116 let mut lines = LineClasses::new(macro_str);
1117 let first_line = lines.next().map(|(_, s)| s.trim_right().to_owned())?;
1118 let mut trimmed_lines = Vec::with_capacity(16);
1120 let mut veto_trim = false;
1121 let min_prefix_space_width = lines
1122 .filter_map(|(kind, line)| {
1123 let mut trimmed = true;
1124 let prefix_space_width = if is_empty_line(&line) {
1127 Some(get_prefix_space_width(context, &line))
1130 let line = if veto_trim || (kind.is_string() && !line.ends_with('\\')) {
1131 veto_trim = kind.is_string() && !line.ends_with('\\');
1135 line.trim().to_owned()
1137 trimmed_lines.push((trimmed, line, prefix_space_width));
1139 // when computing the minimum, do not consider lines within a string
1141 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
1142 _ => prefix_space_width,
1148 first_line + "\n" + &trimmed_lines
1151 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
1152 _ if !trimmed => line.to_owned(),
1153 Some(original_indent_width) => {
1154 let new_indent_width = indent.width() + original_indent_width
1155 .saturating_sub(min_prefix_space_width);
1156 let new_indent = Indent::from_width(context.config, new_indent_width);
1157 format!("{}{}", new_indent.to_string(context.config), line)
1159 None => String::new(),
1162 .collect::<Vec<_>>()
1167 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1169 for c in s.chars() {
1172 '\t' => width += context.config.tab_spaces(),
1179 fn is_empty_line(s: &str) -> bool {
1180 s.is_empty() || s.chars().all(char::is_whitespace)
1183 // A very simple parser that just parses a macros 2.0 definition into its branches.
1184 // Currently we do not attempt to parse any further than that.
1186 struct MacroParser {
1191 // (`(` ... `)` `=>` `{` ... `}`)*
1192 fn parse(&mut self) -> Option<Macro> {
1193 let mut branches = vec![];
1194 while self.toks.look_ahead(1).is_some() {
1195 branches.push(self.parse_branch()?);
1198 Some(Macro { branches })
1201 // `(` ... `)` `=>` `{` ... `}`
1202 fn parse_branch(&mut self) -> Option<MacroBranch> {
1203 let tok = self.toks.next()?;
1204 let (lo, args_paren_kind) = match tok {
1205 TokenTree::Token(..) => return None,
1206 TokenTree::Delimited(delimited_span, ref d) => (delimited_span.open.lo(), d.delim),
1208 let args = tok.joint().into();
1209 match self.toks.next()? {
1210 TokenTree::Token(_, Token::FatArrow) => {}
1213 let (mut hi, body, whole_body) = match self.toks.next()? {
1214 TokenTree::Token(..) => return None,
1215 TokenTree::Delimited(delimited_span, _) => {
1216 let data = delimited_span.entire().data();
1219 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1220 delimited_span.entire(),
1224 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1229 span: mk_sp(lo, hi),
1238 // A parsed macros 2.0 macro definition.
1240 branches: Vec<MacroBranch>,
1243 // FIXME: it would be more efficient to use references to the token streams
1244 // rather than clone them, if we can make the borrowing work out.
1245 struct MacroBranch {
1247 args_paren_kind: DelimToken,
1248 args: ThinTokenStream,
1256 context: &RewriteContext,
1258 multi_branch_style: bool,
1259 ) -> Option<String> {
1260 // Only attempt to format function-like macros.
1261 if self.args_paren_kind != DelimToken::Paren {
1262 // FIXME(#1539): implement for non-sugared macros.
1267 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1269 if multi_branch_style {
1273 if !context.config.format_macro_bodies() {
1275 result += context.snippet(self.whole_body);
1276 return Some(result);
1279 // The macro body is the most interesting part. It might end up as various
1280 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1281 // parsed as regular Rust code (and note that these can be escaped using
1282 // `$$`). We'll try and format like an AST node, but we'll substitute
1283 // variables for new names with the same length first.
1285 let old_body = context.snippet(self.body).trim();
1286 let (body_str, substs) = replace_names(old_body)?;
1287 let has_block_body = old_body.starts_with('{');
1289 let mut config = context.config.clone();
1290 config.set().hide_parse_errors(true);
1294 let body_indent = if has_block_body {
1297 shape.indent.block_indent(&config)
1299 let new_width = config.max_width() - body_indent.width();
1300 config.set().max_width(new_width);
1302 // First try to format as items, then as statements.
1303 let new_body = match ::format_snippet(&body_str, &config) {
1304 Some(new_body) => new_body,
1306 let new_width = new_width + config.tab_spaces();
1307 config.set().max_width(new_width);
1308 match ::format_code_block(&body_str, &config) {
1309 Some(new_body) => new_body,
1310 None => return None,
1314 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1316 // Indent the body since it is in a block.
1317 let indent_str = body_indent.to_string(&config);
1318 let mut new_body = LineClasses::new(new_body.trim_right())
1320 (String::new(), true),
1321 |(mut s, need_indent), (kind, ref l)| {
1322 if !l.is_empty() && need_indent {
1325 (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1330 // Undo our replacement of macro variables.
1331 // FIXME: this could be *much* more efficient.
1332 for (old, new) in &substs {
1333 if old_body.find(new).is_some() {
1334 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1337 new_body = new_body.replace(new, old);
1341 result += new_body.trim();
1342 } else if !new_body.is_empty() {
1344 result += &new_body;
1345 result += &shape.indent.to_string(&config);
1354 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1356 /// # Expected syntax
1360 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1361 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1363 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1366 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1367 let mut result = String::with_capacity(1024);
1368 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1369 let nested_shape = shape
1370 .block_indent(context.config.tab_spaces())
1371 .with_max_width(context.config);
1373 result.push_str("lazy_static! {");
1374 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1376 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1377 match parser.$method($($arg,)*) {
1379 if parser.sess.span_diagnostic.has_errors() {
1380 parser.sess.span_diagnostic.reset_err_count();
1388 parser.sess.span_diagnostic.reset_err_count();
1394 while parser.token != Token::Eof {
1395 // Parse a `lazy_static!` item.
1396 let vis = ::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1397 parser.eat_keyword(symbol::keywords::Static);
1398 parser.eat_keyword(symbol::keywords::Ref);
1399 let id = parse_or!(parse_ident);
1400 parser.eat(&Token::Colon);
1401 let ty = parse_or!(parse_ty);
1402 parser.eat(&Token::Eq);
1403 let expr = parse_or!(parse_expr);
1404 parser.eat(&Token::Semi);
1406 // Rewrite as a static item.
1407 let mut stmt = String::with_capacity(128);
1408 stmt.push_str(&format!(
1409 "{}static ref {}: {} =",
1412 ty.rewrite(context, nested_shape)?
1414 result.push_str(&::expr::rewrite_assign_rhs(
1418 nested_shape.sub_width(1)?,
1421 if parser.token != Token::Eof {
1422 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1426 result.push_str(&shape.indent.to_string_with_newline(context.config));