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::{ast, ptr};
26 use syntax::codemap::{BytePos, Span};
27 use syntax::parse::new_parser_from_tts;
28 use syntax::parse::parser::Parser;
29 use syntax::parse::token::{BinOpToken, DelimToken, Token};
30 use syntax::print::pprust;
32 use syntax::tokenstream::{Cursor, ThinTokenStream, TokenStream, TokenTree};
33 use syntax::util::ThinVec;
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 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
80 Item(Option<ptr::P<ast::Item>>),
83 impl Rewrite for ast::Item {
84 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
85 let mut visitor = ::visitor::FmtVisitor::from_context(context);
86 visitor.block_indent = shape.indent;
87 visitor.last_pos = self.span().lo();
88 visitor.visit_item(self);
93 impl Rewrite for MacroArg {
94 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
96 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
97 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
98 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
99 MacroArg::Item(ref item) => item.as_ref().and_then(|item| item.rewrite(context, shape)),
104 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
105 macro_rules! parse_macro_arg {
106 ($macro_arg: ident, $parser: ident) => {
107 let mut cloned_parser = (*parser).clone();
108 match cloned_parser.$parser() {
110 if parser.sess.span_diagnostic.has_errors() {
111 parser.sess.span_diagnostic.reset_err_count();
113 // Parsing succeeded.
114 *parser = cloned_parser;
115 return Some(MacroArg::$macro_arg(x.clone()));
120 parser.sess.span_diagnostic.reset_err_count();
126 parse_macro_arg!(Expr, parse_expr);
127 parse_macro_arg!(Ty, parse_ty);
128 parse_macro_arg!(Pat, parse_pat);
129 parse_macro_arg!(Item, parse_item);
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 let context = &mut context.clone();
156 context.inside_macro = true;
157 if context.config.use_try_shorthand() {
158 if let Some(expr) = convert_try_mac(mac, context) {
159 context.inside_macro = false;
160 return expr.rewrite(context, shape);
164 let original_style = macro_style(mac, context);
166 let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
168 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
174 let ts: TokenStream = mac.node.stream();
175 let has_comment = contains_comment(context.snippet(mac.span));
176 if ts.is_empty() && !has_comment {
178 MacroStyle::Parens if position == MacroPosition::Item => {
179 Some(format!("{}();", macro_name))
181 MacroStyle::Parens => Some(format!("{}()", macro_name)),
182 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
183 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
186 // Format well-known macros which cannot be parsed as a valid AST.
187 // TODO: Maybe add more macros?
188 if macro_name == "lazy_static!" && !has_comment {
189 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
194 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
195 let mut arg_vec = Vec::new();
196 let mut vec_with_semi = false;
197 let mut trailing_comma = false;
199 if MacroStyle::Braces != style {
201 match parse_macro_arg(&mut parser) {
202 Some(arg) => arg_vec.push(arg),
203 None => return Some(context.snippet(mac.span).to_owned()),
210 // Try to parse `vec![expr; expr]`
211 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
213 if parser.token != Token::Eof {
214 match parse_macro_arg(&mut parser) {
218 if parser.token == Token::Eof && arg_vec.len() == 2 {
219 vec_with_semi = true;
223 None => return Some(context.snippet(mac.span).to_owned()),
227 return Some(context.snippet(mac.span).to_owned());
229 _ => return Some(context.snippet(mac.span).to_owned()),
234 if parser.token == Token::Eof {
235 trailing_comma = true;
242 MacroStyle::Parens => {
243 // Format macro invocation as function call, preserve the trailing
244 // comma because not all macros support them.
245 overflow::rewrite_with_parens(
248 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
251 context.config.width_heuristics().fn_call_width,
253 Some(SeparatorTactic::Always)
255 Some(SeparatorTactic::Never)
257 ).map(|rw| match position {
258 MacroPosition::Item => format!("{};", rw),
262 MacroStyle::Brackets => {
263 let mac_shape = shape.offset_left(macro_name.len())?;
264 // Handle special case: `vec![expr; expr]`
266 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
272 let total_overhead = lbr.len() + rbr.len() + 6;
273 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
274 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
275 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
276 if !lhs.contains('\n') && !rhs.contains('\n')
277 && lhs.len() + rhs.len() + total_overhead <= shape.width
279 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
285 nested_shape.indent.to_string_with_newline(context.config),
287 nested_shape.indent.to_string_with_newline(context.config),
289 shape.indent.to_string_with_newline(context.config),
294 // If we are rewriting `vec!` macro or other special macros,
295 // then we can rewrite this as an usual array literal.
296 // Otherwise, we must preserve the original existence of trailing comma.
297 if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) {
298 context.inside_macro = false;
299 trailing_comma = false;
301 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
305 .span_after(mac.span, original_style.opener()),
306 mac.span.hi() - BytePos(1),
308 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
309 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
310 let comma = match position {
311 MacroPosition::Item => ";",
315 Some(format!("{}{}{}", macro_name, rewrite, comma))
318 MacroStyle::Braces => {
319 // Skip macro invocations with braces, for now.
320 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
325 pub fn rewrite_macro_def(
326 context: &RewriteContext,
331 vis: &ast::Visibility,
333 ) -> Option<String> {
334 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
335 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
339 let mut parser = MacroParser::new(def.stream().into_trees());
340 let parsed_def = match parser.parse() {
342 None => return snippet,
345 let mut result = if def.legacy {
346 String::from("macro_rules!")
348 format!("{}macro", format_visibility(vis))
352 result += &ident.name.as_str();
354 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
356 let arm_shape = if multi_branch_style {
358 .block_indent(context.config.tab_spaces())
359 .with_max_width(context.config)
364 let branch_items = itemize_list(
365 context.snippet_provider,
366 parsed_def.branches.iter(),
369 |branch| branch.span.lo(),
370 |branch| branch.span.hi(),
371 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
372 context.snippet_provider.span_after(span, "{"),
375 ).collect::<Vec<_>>();
377 let fmt = ListFormatting {
378 tactic: DefinitiveListTactic::Vertical,
379 separator: if def.legacy { ";" } else { "" },
380 trailing_separator: SeparatorTactic::Always,
381 separator_place: SeparatorPlace::Back,
383 ends_with_newline: true,
384 preserve_newline: true,
385 config: context.config,
388 if multi_branch_style {
390 result += &arm_shape.indent.to_string_with_newline(context.config);
393 result += write_list(&branch_items, &fmt)?.as_str();
395 if multi_branch_style {
396 result += &indent.to_string_with_newline(context.config);
403 fn register_metavariable(
404 map: &mut HashMap<String, String>,
409 let mut new_name = String::new();
410 let mut old_name = String::new();
413 for _ in 0..(dollar_count - 1) {
418 new_name.push_str(&name);
419 old_name.push_str(&name);
421 result.push_str(&new_name);
422 map.insert(old_name, new_name);
425 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
426 // aren't causing problems.
427 // This should also work for escaped `$` variables, where we leave earlier `$`s.
428 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
429 // Each substitution will require five or six extra bytes.
430 let mut result = String::with_capacity(input.len() + 64);
431 let mut substs = HashMap::new();
432 let mut dollar_count = 0;
433 let mut cur_name = String::new();
435 for (kind, c) in CharClasses::new(input.chars()) {
436 if kind != FullCodeCharKind::Normal {
440 } else if dollar_count == 0 {
442 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
443 // Terminates a name following one or more dollars.
444 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
449 } else if c == '(' && cur_name.is_empty() {
450 // FIXME: Support macro def with repeat.
452 } else if c.is_alphanumeric() {
457 if !cur_name.is_empty() {
458 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
461 debug!("replace_names `{}` {:?}", result, substs);
463 Some((result, substs))
466 #[derive(Debug, Clone)]
469 MetaVariable(ast::Ident, String),
470 /// e.g. `$($foo: expr),*`
472 /// `()`, `[]` or `{}`.
474 /// Inner arguments inside delimiters.
476 /// Something after the closing delimiter and the repeat token, if available.
477 Option<Box<ParsedMacroArg>>,
478 /// The repeat token. This could be one of `*`, `+` or `?`.
481 /// e.g. `[derive(Debug)]`
482 Delimited(DelimToken, Vec<ParsedMacroArg>),
483 /// A possible separator. e.g. `,` or `;`.
484 Separator(String, String),
485 /// Other random stuff that does not fit to other kinds.
486 /// e.g. `== foo` in `($x: expr == foo)`.
487 Other(String, String),
490 fn delim_token_to_str(
491 context: &RewriteContext,
492 delim_token: &DelimToken,
494 use_multiple_lines: bool,
495 ) -> (String, String) {
496 let (lhs, rhs) = match *delim_token {
497 DelimToken::Paren => ("(", ")"),
498 DelimToken::Bracket => ("[", "]"),
499 DelimToken::Brace => ("{ ", " }"),
500 DelimToken::NoDelim => ("", ""),
502 if use_multiple_lines {
503 let indent_str = shape.indent.to_string_with_newline(context.config);
504 let nested_indent_str = shape
506 .block_indent(context.config)
507 .to_string_with_newline(context.config);
509 format!("{}{}", lhs, nested_indent_str),
510 format!("{}{}", indent_str, rhs),
513 (lhs.to_owned(), rhs.to_owned())
518 fn starts_with_brace(&self) -> bool {
520 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
521 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
526 fn starts_with_dollar(&self) -> bool {
528 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
533 fn ends_with_space(&self) -> bool {
535 MacroArgKind::Separator(..) => true,
540 fn has_meta_var(&self) -> bool {
542 MacroArgKind::MetaVariable(..) => true,
543 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
550 context: &RewriteContext,
552 use_multiple_lines: bool,
553 ) -> Option<String> {
554 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
555 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false);
556 let inner = wrap_macro_args(context, args, shape)?;
557 if lhs.len() + inner.len() + rhs.len() <= shape.width {
558 return Some((lhs, inner, rhs));
561 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true);
562 let nested_shape = shape
563 .block_indent(context.config.tab_spaces())
564 .with_max_width(context.config);
565 let inner = wrap_macro_args(context, args, nested_shape)?;
566 Some((lhs, inner, rhs))
570 MacroArgKind::MetaVariable(ty, ref name) => {
571 Some(format!("${}: {}", name, ty.name.as_str()))
573 MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
574 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
575 let another = another
577 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
578 .unwrap_or("".to_owned());
579 let repeat_tok = pprust::token_to_string(tok);
581 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
583 MacroArgKind::Delimited(ref delim_tok, ref args) => {
584 rewrite_delimited_inner(delim_tok, args)
585 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
587 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
588 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
593 #[derive(Debug, Clone)]
594 struct ParsedMacroArg {
599 impl ParsedMacroArg {
602 context: &RewriteContext,
604 use_multiple_lines: bool,
605 ) -> Option<String> {
606 self.kind.rewrite(context, shape, use_multiple_lines)
610 /// Parses macro arguments on macro def.
611 struct MacroArgParser {
612 /// Holds either a name of the next metavariable, a separator or a junk.
614 /// The start position on the current buffer.
616 /// The first token of the current buffer.
618 /// Set to true if we are parsing a metavariable or a repeat.
620 /// The position of the last token.
622 /// The last token parsed.
624 /// Holds the parsed arguments.
625 result: Vec<ParsedMacroArg>,
628 fn last_tok(tt: &TokenTree) -> Token {
630 TokenTree::Token(_, ref t) => t.clone(),
631 TokenTree::Delimited(_, ref d) => d.close_token(),
635 impl MacroArgParser {
636 pub fn new() -> MacroArgParser {
642 last_tok: Token::Eof,
643 start_tok: Token::Eof,
648 fn set_last_tok(&mut self, tok: &TokenTree) {
649 self.hi = tok.span().hi();
650 self.last_tok = last_tok(tok);
653 fn add_separator(&mut self) {
654 let prefix = if self.need_space_prefix() {
659 self.result.push(ParsedMacroArg {
660 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
661 span: mk_sp(self.lo, self.hi),
666 fn add_other(&mut self) {
667 let prefix = if self.need_space_prefix() {
672 self.result.push(ParsedMacroArg {
673 kind: MacroArgKind::Other(self.buf.clone(), prefix),
674 span: mk_sp(self.lo, self.hi),
679 fn add_meta_variable(&mut self, iter: &mut Cursor) {
681 Some(TokenTree::Token(sp, Token::Ident(ref ident))) => {
682 self.result.push(ParsedMacroArg {
683 kind: MacroArgKind::MetaVariable(ident.clone(), self.buf.clone()),
684 span: mk_sp(self.lo, sp.hi()),
688 self.is_meta_var = false;
694 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
695 self.result.push(ParsedMacroArg {
696 kind: MacroArgKind::Delimited(delim, inner),
704 inner: Vec<ParsedMacroArg>,
709 let mut buffer = String::new();
710 let mut first = false;
711 let mut lo = span.lo();
712 let mut hi = span.hi();
714 // Parse '*', '+' or '?.
715 while let Some(ref tok) = iter.next() {
716 self.set_last_tok(tok);
719 lo = tok.span().lo();
723 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
724 | TokenTree::Token(_, Token::Question)
725 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
728 TokenTree::Token(sp, ref t) => {
729 buffer.push_str(&pprust::token_to_string(t));
736 // There could be some random stuff between ')' and '*', '+' or '?'.
737 let another = if buffer.trim().is_empty() {
740 Some(Box::new(ParsedMacroArg {
741 kind: MacroArgKind::Other(buffer, "".to_owned()),
746 self.result.push(ParsedMacroArg {
747 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
748 span: mk_sp(self.lo, self.hi),
752 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
753 if self.buf.is_empty() {
755 self.start_tok = t.clone();
757 let needs_space = match next_space(&self.last_tok) {
758 SpaceState::Ident => ident_like(t),
759 SpaceState::Punctuation => !ident_like(t),
760 SpaceState::Always => true,
761 SpaceState::Never => false,
763 if force_space_before(t) || needs_space {
768 self.buf.push_str(&pprust::token_to_string(t));
771 fn need_space_prefix(&self) -> bool {
772 if self.result.is_empty() {
776 let last_arg = self.result.last().unwrap();
777 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
778 if ident_like(&self.start_tok) {
781 if self.start_tok == Token::Colon {
786 if force_space_before(&self.start_tok) {
793 /// Returns a collection of parsed macro def's arguments.
794 pub fn parse(mut self, tokens: ThinTokenStream) -> Vec<ParsedMacroArg> {
795 let mut iter = (tokens.into(): TokenStream).trees();
797 while let Some(ref tok) = iter.next() {
799 TokenTree::Token(sp, Token::Dollar) => {
800 // We always want to add a separator before meta variables.
801 if !self.buf.is_empty() {
802 self.add_separator();
805 // Start keeping the name of this metavariable in the buffer.
806 self.is_meta_var = true;
808 self.start_tok = Token::Dollar;
810 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
811 self.add_meta_variable(&mut iter);
813 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
814 TokenTree::Delimited(sp, delimited) => {
815 if !self.buf.is_empty() {
816 if next_space(&self.last_tok) == SpaceState::Always {
817 self.add_separator();
823 // Parse the stuff inside delimiters.
824 let mut parser = MacroArgParser::new();
826 let delimited_arg = parser.parse(delimited.tts.clone());
828 if self.is_meta_var {
829 self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp);
831 self.add_delimited(delimited_arg, delimited.delim, *sp);
836 self.set_last_tok(tok);
839 // We are left with some stuff in the buffer. Since there is nothing
840 // left to separate, add this as `Other`.
841 if !self.buf.is_empty() {
850 context: &RewriteContext,
851 args: &[ParsedMacroArg],
853 ) -> Option<String> {
854 wrap_macro_args_inner(context, args, shape, false)
855 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
858 fn wrap_macro_args_inner(
859 context: &RewriteContext,
860 args: &[ParsedMacroArg],
862 use_multiple_lines: bool,
863 ) -> Option<String> {
864 let mut result = String::with_capacity(128);
865 let mut iter = args.iter().peekable();
866 let indent_str = shape.indent.to_string_with_newline(context.config);
868 while let Some(ref arg) = iter.next() {
869 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
871 if use_multiple_lines
872 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
874 if arg.kind.ends_with_space() {
877 result.push_str(&indent_str);
878 } else if let Some(ref next_arg) = iter.peek() {
879 let space_before_dollar =
880 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
881 let space_before_brace = next_arg.kind.starts_with_brace();
882 if space_before_dollar || space_before_brace {
888 if !use_multiple_lines && result.len() >= shape.width {
895 // This is a bit sketchy. The token rules probably need tweaking, but it works
896 // for some common cases. I hope the basic logic is sufficient. Note that the
897 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
898 // and `(`/`)` have special meaning.
900 // We always try and format on one line.
901 // FIXME: Use multi-line when every thing does not fit on one line.
902 fn format_macro_args(
903 context: &RewriteContext,
904 toks: ThinTokenStream,
906 ) -> Option<String> {
907 let parsed_args = MacroArgParser::new().parse(toks);
908 wrap_macro_args(context, &parsed_args, shape)
911 // We should insert a space if the next token is a:
912 #[derive(Copy, Clone, PartialEq)]
916 Ident, // Or ident/literal-like thing.
920 fn force_space_before(tok: &Token) -> bool {
921 debug!("tok: force_space_before {:?}", tok);
942 | Token::Dollar => true,
947 fn ident_like(tok: &Token) -> bool {
949 Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
954 fn next_space(tok: &Token) -> SpaceState {
955 debug!("next_space: {:?}", tok);
959 | Token::BinOp(BinOpToken::And)
969 | Token::Underscore => SpaceState::Punctuation,
974 | Token::OpenDelim(_)
975 | Token::CloseDelim(_)
976 | Token::Whitespace => SpaceState::Never,
978 Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
980 _ => SpaceState::Always,
984 /// Tries to convert a macro use into a short hand try expression. Returns None
985 /// when the macro is not an instance of try! (or parsing the inner expression
987 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
988 if &format!("{}", mac.node.path)[..] == "try" {
989 let ts: TokenStream = mac.node.tts.clone().into();
990 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
993 id: ast::NodeId::new(0), // dummy value
994 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
995 span: mac.span, // incorrect span, but shouldn't matter too much
996 attrs: ThinVec::new(),
1003 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
1004 let snippet = context.snippet(mac.span);
1005 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1006 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1007 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1009 if paren_pos < bracket_pos && paren_pos < brace_pos {
1011 } else if bracket_pos < brace_pos {
1012 MacroStyle::Brackets
1018 /// Indent each line according to the specified `indent`.
1046 fn indent_macro_snippet(
1047 context: &RewriteContext,
1050 ) -> Option<String> {
1051 let mut lines = macro_str.lines();
1052 let first_line = lines.next().map(|s| s.trim_right())?;
1053 let mut trimmed_lines = Vec::with_capacity(16);
1055 let min_prefix_space_width = lines
1056 .filter_map(|line| {
1057 let prefix_space_width = if is_empty_line(line) {
1060 Some(get_prefix_space_width(context, line))
1062 trimmed_lines.push((line.trim(), prefix_space_width));
1068 String::from(first_line) + "\n"
1071 .map(|&(line, prefix_space_width)| match prefix_space_width {
1072 Some(original_indent_width) => {
1073 let new_indent_width = indent.width()
1074 + original_indent_width
1075 .checked_sub(min_prefix_space_width)
1077 let new_indent = Indent::from_width(context.config, new_indent_width);
1078 format!("{}{}", new_indent.to_string(context.config), line.trim())
1080 None => String::new(),
1082 .collect::<Vec<_>>()
1087 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1089 for c in s.chars() {
1092 '\t' => width += context.config.tab_spaces(),
1099 fn is_empty_line(s: &str) -> bool {
1100 s.is_empty() || s.chars().all(char::is_whitespace)
1103 // A very simple parser that just parses a macros 2.0 definition into its branches.
1104 // Currently we do not attempt to parse any further than that.
1106 struct MacroParser {
1111 // (`(` ... `)` `=>` `{` ... `}`)*
1112 fn parse(&mut self) -> Option<Macro> {
1113 let mut branches = vec![];
1114 while self.toks.look_ahead(1).is_some() {
1115 branches.push(self.parse_branch()?);
1118 Some(Macro { branches })
1121 // `(` ... `)` `=>` `{` ... `}`
1122 fn parse_branch(&mut self) -> Option<MacroBranch> {
1123 let tok = self.toks.next()?;
1124 let (lo, args_paren_kind) = match tok {
1125 TokenTree::Token(..) => return None,
1126 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1128 let args = tok.joint().into();
1129 match self.toks.next()? {
1130 TokenTree::Token(_, Token::FatArrow) => {}
1133 let (mut hi, body) = match self.toks.next()? {
1134 TokenTree::Token(..) => return None,
1135 TokenTree::Delimited(sp, _) => {
1136 let data = sp.data();
1139 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1143 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1148 span: mk_sp(lo, hi),
1156 // A parsed macros 2.0 macro definition.
1158 branches: Vec<MacroBranch>,
1161 // FIXME: it would be more efficient to use references to the token streams
1162 // rather than clone them, if we can make the borrowing work out.
1163 struct MacroBranch {
1165 args_paren_kind: DelimToken,
1166 args: ThinTokenStream,
1173 context: &RewriteContext,
1175 multi_branch_style: bool,
1176 ) -> Option<String> {
1177 // Only attempt to format function-like macros.
1178 if self.args_paren_kind != DelimToken::Paren {
1179 // FIXME(#1539): implement for non-sugared macros.
1184 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1186 if multi_branch_style {
1190 // The macro body is the most interesting part. It might end up as various
1191 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1192 // parsed as regular Rust code (and note that these can be escaped using
1193 // `$$`). We'll try and format like an AST node, but we'll substitute
1194 // variables for new names with the same length first.
1196 let old_body = context.snippet(self.body).trim();
1197 let (body_str, substs) = replace_names(old_body)?;
1199 let mut config = context.config.clone();
1200 config.set().hide_parse_errors(true);
1204 let has_block_body = old_body.starts_with('{');
1206 let body_indent = if has_block_body {
1209 // We'll hack the indent below, take this into account when formatting,
1210 let body_indent = shape.indent.block_indent(&config);
1211 let new_width = config.max_width() - body_indent.width();
1212 config.set().max_width(new_width);
1216 // First try to format as items, then as statements.
1217 let new_body = match ::format_snippet(&body_str, &config) {
1218 Some(new_body) => new_body,
1219 None => match ::format_code_block(&body_str, &config) {
1220 Some(new_body) => new_body,
1221 None => return None,
1224 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1226 // Indent the body since it is in a block.
1227 let indent_str = body_indent.to_string(&config);
1228 let mut new_body = new_body
1231 .fold(String::new(), |mut s, l| {
1238 // Undo our replacement of macro variables.
1239 // FIXME: this could be *much* more efficient.
1240 for (old, new) in &substs {
1241 if old_body.find(new).is_some() {
1242 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1245 new_body = new_body.replace(new, old);
1249 result += new_body.trim();
1250 } else if !new_body.is_empty() {
1252 result += &new_body;
1253 result += &shape.indent.to_string(&config);
1262 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1264 /// # Expected syntax
1268 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1269 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1271 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1274 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1275 let mut result = String::with_capacity(1024);
1276 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1277 let nested_shape = shape.block_indent(context.config.tab_spaces());
1279 result.push_str("lazy_static! {");
1280 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1282 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1283 match parser.$method($($arg,)*) {
1285 if parser.sess.span_diagnostic.has_errors() {
1286 parser.sess.span_diagnostic.reset_err_count();
1294 parser.sess.span_diagnostic.reset_err_count();
1300 while parser.token != Token::Eof {
1301 // Parse a `lazy_static!` item.
1302 let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1303 parser.eat_keyword(symbol::keywords::Static);
1304 parser.eat_keyword(symbol::keywords::Ref);
1305 let id = parse_or!(parse_ident);
1306 parser.eat(&Token::Colon);
1307 let ty = parse_or!(parse_ty);
1308 parser.eat(&Token::Eq);
1309 let expr = parse_or!(parse_expr);
1310 parser.eat(&Token::Semi);
1312 // Rewrite as a static item.
1313 let mut stmt = String::with_capacity(128);
1314 stmt.push_str(&format!(
1315 "{}static ref {}: {} =",
1318 ty.rewrite(context, nested_shape)?
1320 result.push_str(&::expr::rewrite_assign_rhs(
1324 nested_shape.sub_width(1)?,
1327 if parser.token != Token::Eof {
1328 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1332 result.push_str(&shape.indent.to_string_with_newline(context.config));