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;
36 use comment::{contains_comment, remove_trailing_white_spaces, CharClasses, FindUncommented,
38 use expr::rewrite_array;
39 use lists::{itemize_list, write_list, ListFormatting};
41 use rewrite::{Rewrite, RewriteContext};
42 use shape::{Indent, Shape};
44 use utils::{format_visibility, mk_sp, wrap_str};
46 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
48 // FIXME: use the enum from libsyntax?
49 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
56 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
57 pub enum MacroPosition {
65 fn opener(&self) -> &'static str {
67 MacroStyle::Parens => "(",
68 MacroStyle::Brackets => "[",
69 MacroStyle::Braces => "{",
76 Expr(ptr::P<ast::Expr>),
78 Pat(ptr::P<ast::Pat>),
79 Item(ptr::P<ast::Item>),
82 impl Rewrite for ast::Item {
83 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
84 let mut visitor = ::visitor::FmtVisitor::from_context(context);
85 visitor.block_indent = shape.indent;
86 visitor.last_pos = self.span().lo();
87 visitor.visit_item(self);
92 impl Rewrite for MacroArg {
93 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
95 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
96 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
97 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
98 MacroArg::Item(ref item) => item.rewrite(context, shape),
103 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
104 macro_rules! parse_macro_arg {
105 ($macro_arg:ident, $parser:ident, $f:expr) => {
106 let mut cloned_parser = (*parser).clone();
107 match cloned_parser.$parser() {
109 if parser.sess.span_diagnostic.has_errors() {
110 parser.sess.span_diagnostic.reset_err_count();
112 // Parsing succeeded.
113 *parser = cloned_parser;
114 return Some(MacroArg::$macro_arg($f(x)?));
119 parser.sess.span_diagnostic.reset_err_count();
125 parse_macro_arg!(Expr, parse_expr, |x: ptr::P<ast::Expr>| Some(x));
126 parse_macro_arg!(Ty, parse_ty, |x: ptr::P<ast::Ty>| Some(x));
127 parse_macro_arg!(Pat, parse_pat, |x: ptr::P<ast::Pat>| Some(x));
128 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
129 parse_macro_arg!(Item, parse_item, |x: Option<ptr::P<ast::Item>>| x);
134 /// Rewrite macro name without using pretty-printer if possible.
135 fn rewrite_macro_name(path: &ast::Path, extra_ident: Option<ast::Ident>) -> String {
136 let name = if path.segments.len() == 1 {
137 // Avoid using pretty-printer in the common case.
138 format!("{}!", path.segments[0].identifier)
143 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
148 pub fn rewrite_macro(
150 extra_ident: Option<ast::Ident>,
151 context: &RewriteContext,
153 position: MacroPosition,
154 ) -> Option<String> {
155 context.inside_macro.replace(true);
156 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position);
157 context.inside_macro.replace(false);
161 pub fn rewrite_macro_inner(
163 extra_ident: Option<ast::Ident>,
164 context: &RewriteContext,
166 position: MacroPosition,
167 ) -> Option<String> {
168 if context.config.use_try_shorthand() {
169 if let Some(expr) = convert_try_mac(mac, context) {
170 context.inside_macro.replace(false);
171 return expr.rewrite(context, shape);
175 let original_style = macro_style(mac, context);
177 let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
179 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
185 let ts: TokenStream = mac.node.stream();
186 let has_comment = contains_comment(context.snippet(mac.span));
187 if ts.is_empty() && !has_comment {
189 MacroStyle::Parens if position == MacroPosition::Item => {
190 Some(format!("{}();", macro_name))
192 MacroStyle::Parens => Some(format!("{}()", macro_name)),
193 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
194 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
197 // Format well-known macros which cannot be parsed as a valid AST.
198 // TODO: Maybe add more macros?
199 if macro_name == "lazy_static!" && !has_comment {
200 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
205 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
206 let mut arg_vec = Vec::new();
207 let mut vec_with_semi = false;
208 let mut trailing_comma = false;
210 if MacroStyle::Braces != style {
212 match parse_macro_arg(&mut parser) {
213 Some(arg) => arg_vec.push(arg),
214 None => return Some(context.snippet(mac.span).to_owned()),
221 // Try to parse `vec![expr; expr]`
222 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
224 if parser.token != Token::Eof {
225 match parse_macro_arg(&mut parser) {
229 if parser.token == Token::Eof && arg_vec.len() == 2 {
230 vec_with_semi = true;
234 None => return Some(context.snippet(mac.span).to_owned()),
238 return Some(context.snippet(mac.span).to_owned());
240 _ => return Some(context.snippet(mac.span).to_owned()),
245 if parser.token == Token::Eof {
246 trailing_comma = true;
253 MacroStyle::Parens => {
254 // Format macro invocation as function call, preserve the trailing
255 // comma because not all macros support them.
256 overflow::rewrite_with_parens(
259 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
262 context.config.width_heuristics().fn_call_width,
264 Some(SeparatorTactic::Always)
266 Some(SeparatorTactic::Never)
268 ).map(|rw| match position {
269 MacroPosition::Item => format!("{};", rw),
273 MacroStyle::Brackets => {
274 let mac_shape = shape.offset_left(macro_name.len())?;
275 // Handle special case: `vec![expr; expr]`
277 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
283 let total_overhead = lbr.len() + rbr.len() + 6;
284 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
285 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
286 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
287 if !lhs.contains('\n') && !rhs.contains('\n')
288 && lhs.len() + rhs.len() + total_overhead <= shape.width
290 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
296 nested_shape.indent.to_string_with_newline(context.config),
298 nested_shape.indent.to_string_with_newline(context.config),
300 shape.indent.to_string_with_newline(context.config),
305 // If we are rewriting `vec!` macro or other special macros,
306 // then we can rewrite this as an usual array literal.
307 // Otherwise, we must preserve the original existence of trailing comma.
308 if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) {
309 context.inside_macro.replace(false);
310 trailing_comma = false;
312 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
316 .span_after(mac.span, original_style.opener()),
317 mac.span.hi() - BytePos(1),
319 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
320 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
321 let comma = match position {
322 MacroPosition::Item => ";",
326 Some(format!("{}{}{}", macro_name, rewrite, comma))
329 MacroStyle::Braces => {
330 // Skip macro invocations with braces, for now.
331 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
336 pub fn rewrite_macro_def(
337 context: &RewriteContext,
342 vis: &ast::Visibility,
344 ) -> Option<String> {
345 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
346 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
350 let mut parser = MacroParser::new(def.stream().into_trees());
351 let parsed_def = match parser.parse() {
353 None => return snippet,
356 let mut result = if def.legacy {
357 String::from("macro_rules!")
359 format!("{}macro", format_visibility(vis))
363 result += &ident.name.as_str();
365 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
367 let arm_shape = if multi_branch_style {
369 .block_indent(context.config.tab_spaces())
370 .with_max_width(context.config)
375 let branch_items = itemize_list(
376 context.snippet_provider,
377 parsed_def.branches.iter(),
380 |branch| branch.span.lo(),
381 |branch| branch.span.hi(),
382 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
383 context.snippet_provider.span_after(span, "{"),
386 ).collect::<Vec<_>>();
388 let fmt = ListFormatting {
389 tactic: DefinitiveListTactic::Vertical,
390 separator: if def.legacy { ";" } else { "" },
391 trailing_separator: SeparatorTactic::Always,
392 separator_place: SeparatorPlace::Back,
394 ends_with_newline: true,
395 preserve_newline: true,
396 config: context.config,
399 if multi_branch_style {
401 result += &arm_shape.indent.to_string_with_newline(context.config);
404 result += write_list(&branch_items, &fmt)?.as_str();
406 if multi_branch_style {
407 result += &indent.to_string_with_newline(context.config);
414 fn register_metavariable(
415 map: &mut HashMap<String, String>,
420 let mut new_name = String::new();
421 let mut old_name = String::new();
424 for _ in 0..(dollar_count - 1) {
429 new_name.push_str(&name);
430 old_name.push_str(&name);
432 result.push_str(&new_name);
433 map.insert(old_name, new_name);
436 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
437 // aren't causing problems.
438 // This should also work for escaped `$` variables, where we leave earlier `$`s.
439 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
440 // Each substitution will require five or six extra bytes.
441 let mut result = String::with_capacity(input.len() + 64);
442 let mut substs = HashMap::new();
443 let mut dollar_count = 0;
444 let mut cur_name = String::new();
446 for (kind, c) in CharClasses::new(input.chars()) {
447 if kind != FullCodeCharKind::Normal {
451 } else if dollar_count == 0 {
453 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
454 // Terminates a name following one or more dollars.
455 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
460 } else if c == '(' && cur_name.is_empty() {
461 // FIXME: Support macro def with repeat.
463 } else if c.is_alphanumeric() || c == '_' {
468 if !cur_name.is_empty() {
469 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
472 debug!("replace_names `{}` {:?}", result, substs);
474 Some((result, substs))
477 #[derive(Debug, Clone)]
480 MetaVariable(ast::Ident, String),
481 /// e.g. `$($foo: expr),*`
483 /// `()`, `[]` or `{}`.
485 /// Inner arguments inside delimiters.
487 /// Something after the closing delimiter and the repeat token, if available.
488 Option<Box<ParsedMacroArg>>,
489 /// The repeat token. This could be one of `*`, `+` or `?`.
492 /// e.g. `[derive(Debug)]`
493 Delimited(DelimToken, Vec<ParsedMacroArg>),
494 /// A possible separator. e.g. `,` or `;`.
495 Separator(String, String),
496 /// Other random stuff that does not fit to other kinds.
497 /// e.g. `== foo` in `($x: expr == foo)`.
498 Other(String, String),
501 fn delim_token_to_str(
502 context: &RewriteContext,
503 delim_token: &DelimToken,
505 use_multiple_lines: bool,
506 ) -> (String, String) {
507 let (lhs, rhs) = match *delim_token {
508 DelimToken::Paren => ("(", ")"),
509 DelimToken::Bracket => ("[", "]"),
510 DelimToken::Brace => ("{ ", " }"),
511 DelimToken::NoDelim => ("", ""),
513 if use_multiple_lines {
514 let indent_str = shape.indent.to_string_with_newline(context.config);
515 let nested_indent_str = shape
517 .block_indent(context.config)
518 .to_string_with_newline(context.config);
520 format!("{}{}", lhs, nested_indent_str),
521 format!("{}{}", indent_str, rhs),
524 (lhs.to_owned(), rhs.to_owned())
529 fn starts_with_brace(&self) -> bool {
531 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
532 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
537 fn starts_with_dollar(&self) -> bool {
539 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
544 fn ends_with_space(&self) -> bool {
546 MacroArgKind::Separator(..) => true,
551 fn has_meta_var(&self) -> bool {
553 MacroArgKind::MetaVariable(..) => true,
554 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
561 context: &RewriteContext,
563 use_multiple_lines: bool,
564 ) -> Option<String> {
565 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
566 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false);
567 let inner = wrap_macro_args(context, args, shape)?;
568 if lhs.len() + inner.len() + rhs.len() <= shape.width {
569 return Some((lhs, inner, rhs));
572 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true);
573 let nested_shape = shape
574 .block_indent(context.config.tab_spaces())
575 .with_max_width(context.config);
576 let inner = wrap_macro_args(context, args, nested_shape)?;
577 Some((lhs, inner, rhs))
581 MacroArgKind::MetaVariable(ty, ref name) => {
582 Some(format!("${}:{}", name, ty.name.as_str()))
584 MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
585 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
586 let another = another
588 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
589 .unwrap_or("".to_owned());
590 let repeat_tok = pprust::token_to_string(tok);
592 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
594 MacroArgKind::Delimited(ref delim_tok, ref args) => {
595 rewrite_delimited_inner(delim_tok, args)
596 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
598 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
599 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
604 #[derive(Debug, Clone)]
605 struct ParsedMacroArg {
610 impl ParsedMacroArg {
613 context: &RewriteContext,
615 use_multiple_lines: bool,
616 ) -> Option<String> {
617 self.kind.rewrite(context, shape, use_multiple_lines)
621 /// Parses macro arguments on macro def.
622 struct MacroArgParser {
623 /// Holds either a name of the next metavariable, a separator or a junk.
625 /// The start position on the current buffer.
627 /// The first token of the current buffer.
629 /// Set to true if we are parsing a metavariable or a repeat.
631 /// The position of the last token.
633 /// The last token parsed.
635 /// Holds the parsed arguments.
636 result: Vec<ParsedMacroArg>,
639 fn last_tok(tt: &TokenTree) -> Token {
641 TokenTree::Token(_, ref t) => t.clone(),
642 TokenTree::Delimited(_, ref d) => d.close_token(),
646 impl MacroArgParser {
647 pub fn new() -> MacroArgParser {
653 last_tok: Token::Eof,
654 start_tok: Token::Eof,
659 fn set_last_tok(&mut self, tok: &TokenTree) {
660 self.hi = tok.span().hi();
661 self.last_tok = last_tok(tok);
664 fn add_separator(&mut self) {
665 let prefix = if self.need_space_prefix() {
670 self.result.push(ParsedMacroArg {
671 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
672 span: mk_sp(self.lo, self.hi),
677 fn add_other(&mut self) {
678 let prefix = if self.need_space_prefix() {
683 self.result.push(ParsedMacroArg {
684 kind: MacroArgKind::Other(self.buf.clone(), prefix),
685 span: mk_sp(self.lo, self.hi),
690 fn add_meta_variable(&mut self, iter: &mut Cursor) {
692 Some(TokenTree::Token(sp, Token::Ident(ref ident))) => {
693 self.result.push(ParsedMacroArg {
694 kind: MacroArgKind::MetaVariable(ident.clone(), self.buf.clone()),
695 span: mk_sp(self.lo, sp.hi()),
699 self.is_meta_var = false;
705 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
706 self.result.push(ParsedMacroArg {
707 kind: MacroArgKind::Delimited(delim, inner),
715 inner: Vec<ParsedMacroArg>,
720 let mut buffer = String::new();
721 let mut first = false;
722 let mut lo = span.lo();
723 let mut hi = span.hi();
725 // Parse '*', '+' or '?.
726 while let Some(ref tok) = iter.next() {
727 self.set_last_tok(tok);
730 lo = tok.span().lo();
734 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
735 | TokenTree::Token(_, Token::Question)
736 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
739 TokenTree::Token(sp, ref t) => {
740 buffer.push_str(&pprust::token_to_string(t));
747 // There could be some random stuff between ')' and '*', '+' or '?'.
748 let another = if buffer.trim().is_empty() {
751 Some(Box::new(ParsedMacroArg {
752 kind: MacroArgKind::Other(buffer, "".to_owned()),
757 self.result.push(ParsedMacroArg {
758 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
759 span: mk_sp(self.lo, self.hi),
763 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
764 if self.buf.is_empty() {
766 self.start_tok = t.clone();
768 let needs_space = match next_space(&self.last_tok) {
769 SpaceState::Ident => ident_like(t),
770 SpaceState::Punctuation => !ident_like(t),
771 SpaceState::Always => true,
772 SpaceState::Never => false,
774 if force_space_before(t) || needs_space {
779 self.buf.push_str(&pprust::token_to_string(t));
782 fn need_space_prefix(&self) -> bool {
783 if self.result.is_empty() {
787 let last_arg = self.result.last().unwrap();
788 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
789 if ident_like(&self.start_tok) {
792 if self.start_tok == Token::Colon {
797 if force_space_before(&self.start_tok) {
804 /// Returns a collection of parsed macro def's arguments.
805 pub fn parse(mut self, tokens: ThinTokenStream) -> Vec<ParsedMacroArg> {
806 let mut iter = (tokens.into(): TokenStream).trees();
808 while let Some(ref tok) = iter.next() {
810 TokenTree::Token(sp, Token::Dollar) => {
811 // We always want to add a separator before meta variables.
812 if !self.buf.is_empty() {
813 self.add_separator();
816 // Start keeping the name of this metavariable in the buffer.
817 self.is_meta_var = true;
819 self.start_tok = Token::Dollar;
821 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
822 self.add_meta_variable(&mut iter);
824 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
825 TokenTree::Delimited(sp, delimited) => {
826 if !self.buf.is_empty() {
827 if next_space(&self.last_tok) == SpaceState::Always {
828 self.add_separator();
834 // Parse the stuff inside delimiters.
835 let mut parser = MacroArgParser::new();
837 let delimited_arg = parser.parse(delimited.tts.clone());
839 if self.is_meta_var {
840 self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp);
842 self.add_delimited(delimited_arg, delimited.delim, *sp);
847 self.set_last_tok(tok);
850 // We are left with some stuff in the buffer. Since there is nothing
851 // left to separate, add this as `Other`.
852 if !self.buf.is_empty() {
861 context: &RewriteContext,
862 args: &[ParsedMacroArg],
864 ) -> Option<String> {
865 wrap_macro_args_inner(context, args, shape, false)
866 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
869 fn wrap_macro_args_inner(
870 context: &RewriteContext,
871 args: &[ParsedMacroArg],
873 use_multiple_lines: bool,
874 ) -> Option<String> {
875 let mut result = String::with_capacity(128);
876 let mut iter = args.iter().peekable();
877 let indent_str = shape.indent.to_string_with_newline(context.config);
879 while let Some(ref arg) = iter.next() {
880 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
882 if use_multiple_lines
883 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
885 if arg.kind.ends_with_space() {
888 result.push_str(&indent_str);
889 } else if let Some(ref next_arg) = iter.peek() {
890 let space_before_dollar =
891 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
892 let space_before_brace = next_arg.kind.starts_with_brace();
893 if space_before_dollar || space_before_brace {
899 if !use_multiple_lines && result.len() >= shape.width {
906 // This is a bit sketchy. The token rules probably need tweaking, but it works
907 // for some common cases. I hope the basic logic is sufficient. Note that the
908 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
909 // and `(`/`)` have special meaning.
911 // We always try and format on one line.
912 // FIXME: Use multi-line when every thing does not fit on one line.
913 fn format_macro_args(
914 context: &RewriteContext,
915 toks: ThinTokenStream,
917 ) -> Option<String> {
918 let parsed_args = MacroArgParser::new().parse(toks);
919 wrap_macro_args(context, &parsed_args, shape)
922 // We should insert a space if the next token is a:
923 #[derive(Copy, Clone, PartialEq)]
927 Ident, // Or ident/literal-like thing.
931 fn force_space_before(tok: &Token) -> bool {
932 debug!("tok: force_space_before {:?}", tok);
953 | Token::Dollar => true,
958 fn ident_like(tok: &Token) -> bool {
960 Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
965 fn next_space(tok: &Token) -> SpaceState {
966 debug!("next_space: {:?}", tok);
970 | Token::BinOp(BinOpToken::And)
979 | Token::Question => SpaceState::Punctuation,
984 | Token::OpenDelim(_)
985 | Token::CloseDelim(_)
986 | Token::Whitespace => SpaceState::Never,
988 Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
990 _ => SpaceState::Always,
994 /// Tries to convert a macro use into a short hand try expression. Returns None
995 /// when the macro is not an instance of try! (or parsing the inner expression
997 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
998 if &format!("{}", mac.node.path)[..] == "try" {
999 let ts: TokenStream = mac.node.tts.clone().into();
1000 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1003 id: ast::NodeId::new(0), // dummy value
1004 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1005 span: mac.span, // incorrect span, but shouldn't matter too much
1006 attrs: ThinVec::new(),
1013 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
1014 let snippet = context.snippet(mac.span);
1015 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1016 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1017 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1019 if paren_pos < bracket_pos && paren_pos < brace_pos {
1021 } else if bracket_pos < brace_pos {
1022 MacroStyle::Brackets
1028 /// Indent each line according to the specified `indent`.
1056 fn indent_macro_snippet(
1057 context: &RewriteContext,
1060 ) -> Option<String> {
1061 let mut lines = macro_str.lines();
1062 let first_line = lines.next().map(|s| s.trim_right())?;
1063 let mut trimmed_lines = Vec::with_capacity(16);
1065 let min_prefix_space_width = lines
1066 .filter_map(|line| {
1067 let prefix_space_width = if is_empty_line(line) {
1070 Some(get_prefix_space_width(context, line))
1072 trimmed_lines.push((line.trim(), prefix_space_width));
1078 String::from(first_line) + "\n"
1081 .map(|&(line, prefix_space_width)| match prefix_space_width {
1082 Some(original_indent_width) => {
1083 let new_indent_width = indent.width()
1084 + original_indent_width
1085 .checked_sub(min_prefix_space_width)
1087 let new_indent = Indent::from_width(context.config, new_indent_width);
1088 format!("{}{}", new_indent.to_string(context.config), line.trim())
1090 None => String::new(),
1092 .collect::<Vec<_>>()
1097 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1099 for c in s.chars() {
1102 '\t' => width += context.config.tab_spaces(),
1109 fn is_empty_line(s: &str) -> bool {
1110 s.is_empty() || s.chars().all(char::is_whitespace)
1113 // A very simple parser that just parses a macros 2.0 definition into its branches.
1114 // Currently we do not attempt to parse any further than that.
1116 struct MacroParser {
1121 // (`(` ... `)` `=>` `{` ... `}`)*
1122 fn parse(&mut self) -> Option<Macro> {
1123 let mut branches = vec![];
1124 while self.toks.look_ahead(1).is_some() {
1125 branches.push(self.parse_branch()?);
1128 Some(Macro { branches })
1131 // `(` ... `)` `=>` `{` ... `}`
1132 fn parse_branch(&mut self) -> Option<MacroBranch> {
1133 let tok = self.toks.next()?;
1134 let (lo, args_paren_kind) = match tok {
1135 TokenTree::Token(..) => return None,
1136 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1138 let args = tok.joint().into();
1139 match self.toks.next()? {
1140 TokenTree::Token(_, Token::FatArrow) => {}
1143 let (mut hi, body) = match self.toks.next()? {
1144 TokenTree::Token(..) => return None,
1145 TokenTree::Delimited(sp, _) => {
1146 let data = sp.data();
1149 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1153 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1158 span: mk_sp(lo, hi),
1166 // A parsed macros 2.0 macro definition.
1168 branches: Vec<MacroBranch>,
1171 // FIXME: it would be more efficient to use references to the token streams
1172 // rather than clone them, if we can make the borrowing work out.
1173 struct MacroBranch {
1175 args_paren_kind: DelimToken,
1176 args: ThinTokenStream,
1183 context: &RewriteContext,
1185 multi_branch_style: bool,
1186 ) -> Option<String> {
1187 // Only attempt to format function-like macros.
1188 if self.args_paren_kind != DelimToken::Paren {
1189 // FIXME(#1539): implement for non-sugared macros.
1194 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1196 if multi_branch_style {
1200 // The macro body is the most interesting part. It might end up as various
1201 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1202 // parsed as regular Rust code (and note that these can be escaped using
1203 // `$$`). We'll try and format like an AST node, but we'll substitute
1204 // variables for new names with the same length first.
1206 let old_body = context.snippet(self.body).trim();
1207 let (body_str, substs) = replace_names(old_body)?;
1209 let mut config = context.config.clone();
1210 config.set().hide_parse_errors(true);
1214 let has_block_body = old_body.starts_with('{');
1216 let body_indent = if has_block_body {
1219 // We'll hack the indent below, take this into account when formatting,
1220 let body_indent = shape.indent.block_indent(&config);
1221 let new_width = config.max_width() - body_indent.width();
1222 config.set().max_width(new_width);
1226 // First try to format as items, then as statements.
1227 let new_body = match ::format_snippet(&body_str, &config) {
1228 Some(new_body) => new_body,
1229 None => match ::format_code_block(&body_str, &config) {
1230 Some(new_body) => new_body,
1231 None => return None,
1234 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1236 // Indent the body since it is in a block.
1237 let indent_str = body_indent.to_string(&config);
1238 let mut new_body = new_body
1241 .fold(String::new(), |mut s, l| {
1248 // Undo our replacement of macro variables.
1249 // FIXME: this could be *much* more efficient.
1250 for (old, new) in &substs {
1251 if old_body.find(new).is_some() {
1252 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1255 new_body = new_body.replace(new, old);
1259 result += new_body.trim();
1260 } else if !new_body.is_empty() {
1262 result += &new_body;
1263 result += &shape.indent.to_string(&config);
1272 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1274 /// # Expected syntax
1278 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1279 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1281 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1284 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1285 let mut result = String::with_capacity(1024);
1286 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1287 let nested_shape = shape.block_indent(context.config.tab_spaces());
1289 result.push_str("lazy_static! {");
1290 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1292 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1293 match parser.$method($($arg,)*) {
1295 if parser.sess.span_diagnostic.has_errors() {
1296 parser.sess.span_diagnostic.reset_err_count();
1304 parser.sess.span_diagnostic.reset_err_count();
1310 while parser.token != Token::Eof {
1311 // Parse a `lazy_static!` item.
1312 let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1313 parser.eat_keyword(symbol::keywords::Static);
1314 parser.eat_keyword(symbol::keywords::Ref);
1315 let id = parse_or!(parse_ident);
1316 parser.eat(&Token::Colon);
1317 let ty = parse_or!(parse_ty);
1318 parser.eat(&Token::Eq);
1319 let expr = parse_or!(parse_expr);
1320 parser.eat(&Token::Semi);
1322 // Rewrite as a static item.
1323 let mut stmt = String::with_capacity(128);
1324 stmt.push_str(&format!(
1325 "{}static ref {}: {} =",
1328 ty.rewrite(context, nested_shape)?
1330 result.push_str(&::expr::rewrite_assign_rhs(
1334 nested_shape.sub_width(1)?,
1337 if parser.token != Token::Eof {
1338 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1342 result.push_str(&shape.indent.to_string_with_newline(context.config));