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 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49 pub enum MacroPosition {
58 Expr(ptr::P<ast::Expr>),
60 Pat(ptr::P<ast::Pat>),
61 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
62 Item(Option<ptr::P<ast::Item>>),
65 impl Rewrite for ast::Item {
66 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
67 let mut visitor = ::visitor::FmtVisitor::from_context(context);
68 visitor.block_indent = shape.indent;
69 visitor.last_pos = self.span().lo();
70 visitor.visit_item(self);
75 impl Rewrite for MacroArg {
76 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
78 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
79 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
80 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
81 MacroArg::Item(ref item) => item.as_ref().and_then(|item| item.rewrite(context, shape)),
86 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
87 macro_rules! parse_macro_arg {
88 ($macro_arg:ident, $parser:ident) => {
89 let mut cloned_parser = (*parser).clone();
90 match cloned_parser.$parser() {
92 if parser.sess.span_diagnostic.has_errors() {
93 parser.sess.span_diagnostic.reset_err_count();
96 *parser = cloned_parser;
97 return Some(MacroArg::$macro_arg(x.clone()));
102 parser.sess.span_diagnostic.reset_err_count();
108 parse_macro_arg!(Expr, parse_expr);
109 parse_macro_arg!(Ty, parse_ty);
110 parse_macro_arg!(Pat, parse_pat);
111 parse_macro_arg!(Item, parse_item);
116 /// Rewrite macro name without using pretty-printer if possible.
117 fn rewrite_macro_name(path: &ast::Path, extra_ident: Option<ast::Ident>) -> String {
118 let name = if path.segments.len() == 1 {
119 // Avoid using pretty-printer in the common case.
120 format!("{}!", path.segments[0].identifier)
125 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
130 pub fn rewrite_macro(
132 extra_ident: Option<ast::Ident>,
133 context: &RewriteContext,
135 position: MacroPosition,
136 ) -> Option<String> {
137 context.inside_macro.replace(true);
138 let result = rewrite_macro_inner(mac, extra_ident, context, shape, position);
139 context.inside_macro.replace(false);
143 pub fn rewrite_macro_inner(
145 extra_ident: Option<ast::Ident>,
146 context: &RewriteContext,
148 position: MacroPosition,
149 ) -> Option<String> {
150 if context.config.use_try_shorthand() {
151 if let Some(expr) = convert_try_mac(mac, context) {
152 context.inside_macro.replace(false);
153 return expr.rewrite(context, shape);
157 let original_style = macro_style(mac, context);
159 let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
161 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
167 let ts: TokenStream = mac.node.stream();
168 let has_comment = contains_comment(context.snippet(mac.span));
169 if ts.is_empty() && !has_comment {
171 DelimToken::Paren if position == MacroPosition::Item => {
172 Some(format!("{}();", macro_name))
174 DelimToken::Paren => Some(format!("{}()", macro_name)),
175 DelimToken::Bracket => Some(format!("{}[]", macro_name)),
176 DelimToken::Brace => Some(format!("{}{{}}", macro_name)),
180 // Format well-known macros which cannot be parsed as a valid AST.
181 // TODO: Maybe add more macros?
182 if macro_name == "lazy_static!" && !has_comment {
183 if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
188 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
189 let mut arg_vec = Vec::new();
190 let mut vec_with_semi = false;
191 let mut trailing_comma = false;
193 if DelimToken::Brace != style {
195 match parse_macro_arg(&mut parser) {
196 Some(arg) => arg_vec.push(arg),
197 None => return Some(context.snippet(mac.span).to_owned()),
204 // Try to parse `vec![expr; expr]`
205 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
207 if parser.token != Token::Eof {
208 match parse_macro_arg(&mut parser) {
212 if parser.token == Token::Eof && arg_vec.len() == 2 {
213 vec_with_semi = true;
217 None => return Some(context.snippet(mac.span).to_owned()),
221 return Some(context.snippet(mac.span).to_owned());
223 _ => return Some(context.snippet(mac.span).to_owned()),
228 if parser.token == Token::Eof {
229 trailing_comma = true;
236 DelimToken::Paren => {
237 // Format macro invocation as function call, preserve the trailing
238 // comma because not all macros support them.
239 overflow::rewrite_with_parens(
242 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
245 context.config.width_heuristics().fn_call_width,
247 Some(SeparatorTactic::Always)
249 Some(SeparatorTactic::Never)
251 ).map(|rw| match position {
252 MacroPosition::Item => format!("{};", rw),
256 DelimToken::Bracket => {
257 // Handle special case: `vec![expr; expr]`
259 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
265 let total_overhead = lbr.len() + rbr.len() + 6;
266 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
267 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
268 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
269 if !lhs.contains('\n') && !rhs.contains('\n')
270 && lhs.len() + rhs.len() + total_overhead <= shape.width
272 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
278 nested_shape.indent.to_string_with_newline(context.config),
280 nested_shape.indent.to_string_with_newline(context.config),
282 shape.indent.to_string_with_newline(context.config),
287 // If we are rewriting `vec!` macro or other special macros,
288 // then we can rewrite this as an usual array literal.
289 // Otherwise, we must preserve the original existence of trailing comma.
290 if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) {
291 context.inside_macro.replace(false);
292 trailing_comma = false;
294 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
298 .span_after(mac.span, original_style.opener()),
299 mac.span.hi() - BytePos(1),
301 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
302 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
303 let comma = match position {
304 MacroPosition::Item => ";",
308 Some(format!("{}{}{}", macro_name, rewrite, comma))
311 DelimToken::Brace => {
312 // Skip macro invocations with braces, for now.
313 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
319 pub fn rewrite_macro_def(
320 context: &RewriteContext,
325 vis: &ast::Visibility,
327 ) -> Option<String> {
328 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
329 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
333 let mut parser = MacroParser::new(def.stream().into_trees());
334 let parsed_def = match parser.parse() {
336 None => return snippet,
339 let mut result = if def.legacy {
340 String::from("macro_rules!")
342 format!("{}macro", format_visibility(vis))
346 result += &ident.name.as_str();
348 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
350 let arm_shape = if multi_branch_style {
352 .block_indent(context.config.tab_spaces())
353 .with_max_width(context.config)
358 let branch_items = itemize_list(
359 context.snippet_provider,
360 parsed_def.branches.iter(),
363 |branch| branch.span.lo(),
364 |branch| branch.span.hi(),
365 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
366 context.snippet_provider.span_after(span, "{"),
369 ).collect::<Vec<_>>();
371 let fmt = ListFormatting {
372 tactic: DefinitiveListTactic::Vertical,
373 separator: if def.legacy { ";" } else { "" },
374 trailing_separator: SeparatorTactic::Always,
375 separator_place: SeparatorPlace::Back,
377 ends_with_newline: true,
378 preserve_newline: true,
379 config: context.config,
382 if multi_branch_style {
384 result += &arm_shape.indent.to_string_with_newline(context.config);
387 result += write_list(&branch_items, &fmt)?.as_str();
389 if multi_branch_style {
390 result += &indent.to_string_with_newline(context.config);
397 fn register_metavariable(
398 map: &mut HashMap<String, String>,
403 let mut new_name = String::new();
404 let mut old_name = String::new();
407 for _ in 0..(dollar_count - 1) {
412 new_name.push_str(&name);
413 old_name.push_str(&name);
415 result.push_str(&new_name);
416 map.insert(old_name, new_name);
419 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
420 // aren't causing problems.
421 // This should also work for escaped `$` variables, where we leave earlier `$`s.
422 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
423 // Each substitution will require five or six extra bytes.
424 let mut result = String::with_capacity(input.len() + 64);
425 let mut substs = HashMap::new();
426 let mut dollar_count = 0;
427 let mut cur_name = String::new();
429 for (kind, c) in CharClasses::new(input.chars()) {
430 if kind != FullCodeCharKind::Normal {
434 } else if dollar_count == 0 {
436 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
437 // Terminates a name following one or more dollars.
438 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
443 } else if c == '(' && cur_name.is_empty() {
444 // FIXME: Support macro def with repeat.
446 } else if c.is_alphanumeric() {
451 if !cur_name.is_empty() {
452 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
455 debug!("replace_names `{}` {:?}", result, substs);
457 Some((result, substs))
460 #[derive(Debug, Clone)]
463 MetaVariable(ast::Ident, String),
464 /// e.g. `$($foo: expr),*`
466 /// `()`, `[]` or `{}`.
468 /// Inner arguments inside delimiters.
470 /// Something after the closing delimiter and the repeat token, if available.
471 Option<Box<ParsedMacroArg>>,
472 /// The repeat token. This could be one of `*`, `+` or `?`.
475 /// e.g. `[derive(Debug)]`
476 Delimited(DelimToken, Vec<ParsedMacroArg>),
477 /// A possible separator. e.g. `,` or `;`.
478 Separator(String, String),
479 /// Other random stuff that does not fit to other kinds.
480 /// e.g. `== foo` in `($x: expr == foo)`.
481 Other(String, String),
484 fn delim_token_to_str(
485 context: &RewriteContext,
486 delim_token: &DelimToken,
488 use_multiple_lines: bool,
489 ) -> (String, String) {
490 let (lhs, rhs) = match *delim_token {
491 DelimToken::Paren => ("(", ")"),
492 DelimToken::Bracket => ("[", "]"),
493 DelimToken::Brace => ("{ ", " }"),
494 DelimToken::NoDelim => ("", ""),
496 if use_multiple_lines {
497 let indent_str = shape.indent.to_string_with_newline(context.config);
498 let nested_indent_str = shape
500 .block_indent(context.config)
501 .to_string_with_newline(context.config);
503 format!("{}{}", lhs, nested_indent_str),
504 format!("{}{}", indent_str, rhs),
507 (lhs.to_owned(), rhs.to_owned())
512 fn starts_with_brace(&self) -> bool {
514 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
515 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
520 fn starts_with_dollar(&self) -> bool {
522 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
527 fn ends_with_space(&self) -> bool {
529 MacroArgKind::Separator(..) => true,
534 fn has_meta_var(&self) -> bool {
536 MacroArgKind::MetaVariable(..) => true,
537 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
544 context: &RewriteContext,
546 use_multiple_lines: bool,
547 ) -> Option<String> {
548 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
549 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false);
550 let inner = wrap_macro_args(context, args, shape)?;
551 if lhs.len() + inner.len() + rhs.len() <= shape.width {
552 return Some((lhs, inner, rhs));
555 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true);
556 let nested_shape = shape
557 .block_indent(context.config.tab_spaces())
558 .with_max_width(context.config);
559 let inner = wrap_macro_args(context, args, nested_shape)?;
560 Some((lhs, inner, rhs))
564 MacroArgKind::MetaVariable(ty, ref name) => {
565 Some(format!("${}:{}", name, ty.name.as_str()))
567 MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
568 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
569 let another = another
571 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
572 .unwrap_or("".to_owned());
573 let repeat_tok = pprust::token_to_string(tok);
575 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
577 MacroArgKind::Delimited(ref delim_tok, ref args) => {
578 rewrite_delimited_inner(delim_tok, args)
579 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
581 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
582 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
587 #[derive(Debug, Clone)]
588 struct ParsedMacroArg {
593 impl ParsedMacroArg {
596 context: &RewriteContext,
598 use_multiple_lines: bool,
599 ) -> Option<String> {
600 self.kind.rewrite(context, shape, use_multiple_lines)
604 /// Parses macro arguments on macro def.
605 struct MacroArgParser {
606 /// Holds either a name of the next metavariable, a separator or a junk.
608 /// The start position on the current buffer.
610 /// The first token of the current buffer.
612 /// Set to true if we are parsing a metavariable or a repeat.
614 /// The position of the last token.
616 /// The last token parsed.
618 /// Holds the parsed arguments.
619 result: Vec<ParsedMacroArg>,
622 fn last_tok(tt: &TokenTree) -> Token {
624 TokenTree::Token(_, ref t) => t.clone(),
625 TokenTree::Delimited(_, ref d) => d.close_token(),
629 impl MacroArgParser {
630 pub fn new() -> MacroArgParser {
636 last_tok: Token::Eof,
637 start_tok: Token::Eof,
642 fn set_last_tok(&mut self, tok: &TokenTree) {
643 self.hi = tok.span().hi();
644 self.last_tok = last_tok(tok);
647 fn add_separator(&mut self) {
648 let prefix = if self.need_space_prefix() {
653 self.result.push(ParsedMacroArg {
654 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
655 span: mk_sp(self.lo, self.hi),
660 fn add_other(&mut self) {
661 let prefix = if self.need_space_prefix() {
666 self.result.push(ParsedMacroArg {
667 kind: MacroArgKind::Other(self.buf.clone(), prefix),
668 span: mk_sp(self.lo, self.hi),
673 fn add_meta_variable(&mut self, iter: &mut Cursor) {
675 Some(TokenTree::Token(sp, Token::Ident(ref ident))) => {
676 self.result.push(ParsedMacroArg {
677 kind: MacroArgKind::MetaVariable(ident.clone(), self.buf.clone()),
678 span: mk_sp(self.lo, sp.hi()),
682 self.is_meta_var = false;
688 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
689 self.result.push(ParsedMacroArg {
690 kind: MacroArgKind::Delimited(delim, inner),
698 inner: Vec<ParsedMacroArg>,
703 let mut buffer = String::new();
704 let mut first = false;
705 let mut lo = span.lo();
706 let mut hi = span.hi();
708 // Parse '*', '+' or '?.
709 while let Some(ref tok) = iter.next() {
710 self.set_last_tok(tok);
713 lo = tok.span().lo();
717 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
718 | TokenTree::Token(_, Token::Question)
719 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
722 TokenTree::Token(sp, ref t) => {
723 buffer.push_str(&pprust::token_to_string(t));
730 // There could be some random stuff between ')' and '*', '+' or '?'.
731 let another = if buffer.trim().is_empty() {
734 Some(Box::new(ParsedMacroArg {
735 kind: MacroArgKind::Other(buffer, "".to_owned()),
740 self.result.push(ParsedMacroArg {
741 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
742 span: mk_sp(self.lo, self.hi),
746 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
747 if self.buf.is_empty() {
749 self.start_tok = t.clone();
751 let needs_space = match next_space(&self.last_tok) {
752 SpaceState::Ident => ident_like(t),
753 SpaceState::Punctuation => !ident_like(t),
754 SpaceState::Always => true,
755 SpaceState::Never => false,
757 if force_space_before(t) || needs_space {
762 self.buf.push_str(&pprust::token_to_string(t));
765 fn need_space_prefix(&self) -> bool {
766 if self.result.is_empty() {
770 let last_arg = self.result.last().unwrap();
771 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
772 if ident_like(&self.start_tok) {
775 if self.start_tok == Token::Colon {
780 if force_space_before(&self.start_tok) {
787 /// Returns a collection of parsed macro def's arguments.
788 pub fn parse(mut self, tokens: ThinTokenStream) -> Vec<ParsedMacroArg> {
789 let mut iter = (tokens.into(): TokenStream).trees();
791 while let Some(ref tok) = iter.next() {
793 TokenTree::Token(sp, Token::Dollar) => {
794 // We always want to add a separator before meta variables.
795 if !self.buf.is_empty() {
796 self.add_separator();
799 // Start keeping the name of this metavariable in the buffer.
800 self.is_meta_var = true;
802 self.start_tok = Token::Dollar;
804 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
805 self.add_meta_variable(&mut iter);
807 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
808 TokenTree::Delimited(sp, delimited) => {
809 if !self.buf.is_empty() {
810 if next_space(&self.last_tok) == SpaceState::Always {
811 self.add_separator();
817 // Parse the stuff inside delimiters.
818 let mut parser = MacroArgParser::new();
820 let delimited_arg = parser.parse(delimited.tts.clone());
822 if self.is_meta_var {
823 self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp);
825 self.add_delimited(delimited_arg, delimited.delim, *sp);
830 self.set_last_tok(tok);
833 // We are left with some stuff in the buffer. Since there is nothing
834 // left to separate, add this as `Other`.
835 if !self.buf.is_empty() {
844 context: &RewriteContext,
845 args: &[ParsedMacroArg],
847 ) -> Option<String> {
848 wrap_macro_args_inner(context, args, shape, false)
849 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
852 fn wrap_macro_args_inner(
853 context: &RewriteContext,
854 args: &[ParsedMacroArg],
856 use_multiple_lines: bool,
857 ) -> Option<String> {
858 let mut result = String::with_capacity(128);
859 let mut iter = args.iter().peekable();
860 let indent_str = shape.indent.to_string_with_newline(context.config);
862 while let Some(ref arg) = iter.next() {
863 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
865 if use_multiple_lines
866 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
868 if arg.kind.ends_with_space() {
871 result.push_str(&indent_str);
872 } else if let Some(ref next_arg) = iter.peek() {
873 let space_before_dollar =
874 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
875 let space_before_brace = next_arg.kind.starts_with_brace();
876 if space_before_dollar || space_before_brace {
882 if !use_multiple_lines && result.len() >= shape.width {
889 // This is a bit sketchy. The token rules probably need tweaking, but it works
890 // for some common cases. I hope the basic logic is sufficient. Note that the
891 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
892 // and `(`/`)` have special meaning.
894 // We always try and format on one line.
895 // FIXME: Use multi-line when every thing does not fit on one line.
896 fn format_macro_args(
897 context: &RewriteContext,
898 toks: ThinTokenStream,
900 ) -> Option<String> {
901 let parsed_args = MacroArgParser::new().parse(toks);
902 wrap_macro_args(context, &parsed_args, shape)
905 // We should insert a space if the next token is a:
906 #[derive(Copy, Clone, PartialEq)]
910 Ident, // Or ident/literal-like thing.
914 fn force_space_before(tok: &Token) -> bool {
915 debug!("tok: force_space_before {:?}", tok);
936 | Token::Dollar => true,
941 fn ident_like(tok: &Token) -> bool {
943 Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
948 fn next_space(tok: &Token) -> SpaceState {
949 debug!("next_space: {:?}", tok);
953 | Token::BinOp(BinOpToken::And)
962 | Token::Question => SpaceState::Punctuation,
967 | Token::OpenDelim(_)
968 | Token::CloseDelim(_)
969 | Token::Whitespace => SpaceState::Never,
971 Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
973 _ => SpaceState::Always,
977 /// Tries to convert a macro use into a short hand try expression. Returns None
978 /// when the macro is not an instance of try! (or parsing the inner expression
980 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
981 if &format!("{}", mac.node.path)[..] == "try" {
982 let ts: TokenStream = mac.node.tts.clone().into();
983 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
986 id: ast::NodeId::new(0), // dummy value
987 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
988 span: mac.span, // incorrect span, but shouldn't matter too much
989 attrs: ThinVec::new(),
996 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
997 let snippet = context.snippet(mac.span);
998 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
999 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1000 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1002 if paren_pos < bracket_pos && paren_pos < brace_pos {
1004 } else if bracket_pos < brace_pos {
1011 /// Indent each line according to the specified `indent`.
1039 fn indent_macro_snippet(
1040 context: &RewriteContext,
1043 ) -> Option<String> {
1044 let mut lines = macro_str.lines();
1045 let first_line = lines.next().map(|s| s.trim_right())?;
1046 let mut trimmed_lines = Vec::with_capacity(16);
1048 let min_prefix_space_width = lines
1049 .filter_map(|line| {
1050 let prefix_space_width = if is_empty_line(line) {
1053 Some(get_prefix_space_width(context, line))
1055 trimmed_lines.push((line.trim(), prefix_space_width));
1061 String::from(first_line) + "\n"
1064 .map(|&(line, prefix_space_width)| match prefix_space_width {
1065 Some(original_indent_width) => {
1066 let new_indent_width = indent.width()
1067 + original_indent_width
1068 .checked_sub(min_prefix_space_width)
1070 let new_indent = Indent::from_width(context.config, new_indent_width);
1071 format!("{}{}", new_indent.to_string(context.config), line.trim())
1073 None => String::new(),
1075 .collect::<Vec<_>>()
1080 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1082 for c in s.chars() {
1085 '\t' => width += context.config.tab_spaces(),
1092 fn is_empty_line(s: &str) -> bool {
1093 s.is_empty() || s.chars().all(char::is_whitespace)
1096 // A very simple parser that just parses a macros 2.0 definition into its branches.
1097 // Currently we do not attempt to parse any further than that.
1099 struct MacroParser {
1104 // (`(` ... `)` `=>` `{` ... `}`)*
1105 fn parse(&mut self) -> Option<Macro> {
1106 let mut branches = vec![];
1107 while self.toks.look_ahead(1).is_some() {
1108 branches.push(self.parse_branch()?);
1111 Some(Macro { branches })
1114 // `(` ... `)` `=>` `{` ... `}`
1115 fn parse_branch(&mut self) -> Option<MacroBranch> {
1116 let tok = self.toks.next()?;
1117 let (lo, args_paren_kind) = match tok {
1118 TokenTree::Token(..) => return None,
1119 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1121 let args = tok.joint().into();
1122 match self.toks.next()? {
1123 TokenTree::Token(_, Token::FatArrow) => {}
1126 let (mut hi, body) = match self.toks.next()? {
1127 TokenTree::Token(..) => return None,
1128 TokenTree::Delimited(sp, _) => {
1129 let data = sp.data();
1132 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1136 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1141 span: mk_sp(lo, hi),
1149 // A parsed macros 2.0 macro definition.
1151 branches: Vec<MacroBranch>,
1154 // FIXME: it would be more efficient to use references to the token streams
1155 // rather than clone them, if we can make the borrowing work out.
1156 struct MacroBranch {
1158 args_paren_kind: DelimToken,
1159 args: ThinTokenStream,
1166 context: &RewriteContext,
1168 multi_branch_style: bool,
1169 ) -> Option<String> {
1170 // Only attempt to format function-like macros.
1171 if self.args_paren_kind != DelimToken::Paren {
1172 // FIXME(#1539): implement for non-sugared macros.
1177 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1179 if multi_branch_style {
1183 // The macro body is the most interesting part. It might end up as various
1184 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1185 // parsed as regular Rust code (and note that these can be escaped using
1186 // `$$`). We'll try and format like an AST node, but we'll substitute
1187 // variables for new names with the same length first.
1189 let old_body = context.snippet(self.body).trim();
1190 let (body_str, substs) = replace_names(old_body)?;
1192 let mut config = context.config.clone();
1193 config.set().hide_parse_errors(true);
1197 let has_block_body = old_body.starts_with('{');
1199 let body_indent = if has_block_body {
1202 // We'll hack the indent below, take this into account when formatting,
1203 let body_indent = shape.indent.block_indent(&config);
1204 let new_width = config.max_width() - body_indent.width();
1205 config.set().max_width(new_width);
1209 // First try to format as items, then as statements.
1210 let new_body = match ::format_snippet(&body_str, &config) {
1211 Some(new_body) => new_body,
1212 None => match ::format_code_block(&body_str, &config) {
1213 Some(new_body) => new_body,
1214 None => return None,
1217 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1219 // Indent the body since it is in a block.
1220 let indent_str = body_indent.to_string(&config);
1221 let mut new_body = new_body
1224 .fold(String::new(), |mut s, l| {
1231 // Undo our replacement of macro variables.
1232 // FIXME: this could be *much* more efficient.
1233 for (old, new) in &substs {
1234 if old_body.find(new).is_some() {
1235 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1238 new_body = new_body.replace(new, old);
1242 result += new_body.trim();
1243 } else if !new_body.is_empty() {
1245 result += &new_body;
1246 result += &shape.indent.to_string(&config);
1255 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1257 /// # Expected syntax
1261 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1262 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1264 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1267 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1268 let mut result = String::with_capacity(1024);
1269 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1270 let nested_shape = shape.block_indent(context.config.tab_spaces());
1272 result.push_str("lazy_static! {");
1273 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1275 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1276 match parser.$method($($arg,)*) {
1278 if parser.sess.span_diagnostic.has_errors() {
1279 parser.sess.span_diagnostic.reset_err_count();
1287 parser.sess.span_diagnostic.reset_err_count();
1293 while parser.token != Token::Eof {
1294 // Parse a `lazy_static!` item.
1295 let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1296 parser.eat_keyword(symbol::keywords::Static);
1297 parser.eat_keyword(symbol::keywords::Ref);
1298 let id = parse_or!(parse_ident);
1299 parser.eat(&Token::Colon);
1300 let ty = parse_or!(parse_ty);
1301 parser.eat(&Token::Eq);
1302 let expr = parse_or!(parse_expr);
1303 parser.eat(&Token::Semi);
1305 // Rewrite as a static item.
1306 let mut stmt = String::with_capacity(128);
1307 stmt.push_str(&format!(
1308 "{}static ref {}: {} =",
1311 ty.rewrite(context, nested_shape)?
1313 result.push_str(&::expr::rewrite_assign_rhs(
1317 nested_shape.sub_width(1)?,
1320 if parser.token != Token::Eof {
1321 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1325 result.push_str(&shape.indent.to_string_with_newline(context.config));