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 Item(ptr::P<ast::Item>),
64 impl Rewrite for ast::Item {
65 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
66 let mut visitor = ::visitor::FmtVisitor::from_context(context);
67 visitor.block_indent = shape.indent;
68 visitor.last_pos = self.span().lo();
69 visitor.visit_item(self);
74 impl Rewrite for MacroArg {
75 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
77 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
78 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
79 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
80 MacroArg::Item(ref item) => item.rewrite(context, shape),
85 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
86 macro_rules! parse_macro_arg {
87 ($macro_arg:ident, $parser:ident, $f:expr) => {
88 let mut cloned_parser = (*parser).clone();
89 match cloned_parser.$parser() {
91 if parser.sess.span_diagnostic.has_errors() {
92 parser.sess.span_diagnostic.reset_err_count();
95 *parser = cloned_parser;
96 return Some(MacroArg::$macro_arg($f(x)?));
101 parser.sess.span_diagnostic.reset_err_count();
107 parse_macro_arg!(Expr, parse_expr, |x: ptr::P<ast::Expr>| Some(x));
108 parse_macro_arg!(Ty, parse_ty, |x: ptr::P<ast::Ty>| Some(x));
109 parse_macro_arg!(Pat, parse_pat, |x: ptr::P<ast::Pat>| Some(x));
110 // `parse_item` returns `Option<ptr::P<ast::Item>>`.
111 parse_macro_arg!(Item, parse_item, |x: Option<ptr::P<ast::Item>>| x);
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 mac_shape = shape.offset_left(macro_name.len())?;
260 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
266 let total_overhead = lbr.len() + rbr.len() + 6;
267 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
268 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
269 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
270 if !lhs.contains('\n') && !rhs.contains('\n')
271 && lhs.len() + rhs.len() + total_overhead <= shape.width
273 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
279 nested_shape.indent.to_string_with_newline(context.config),
281 nested_shape.indent.to_string_with_newline(context.config),
283 shape.indent.to_string_with_newline(context.config),
288 // If we are rewriting `vec!` macro or other special macros,
289 // then we can rewrite this as an usual array literal.
290 // Otherwise, we must preserve the original existence of trailing comma.
291 let macro_name = ¯o_name.as_str();
292 let mut force_trailing_comma = if trailing_comma {
293 Some(SeparatorTactic::Always)
295 Some(SeparatorTactic::Never)
297 if FORCED_BRACKET_MACROS.contains(macro_name) {
298 context.inside_macro.replace(false);
299 if context.use_block_indent() {
300 force_trailing_comma = Some(SeparatorTactic::Vertical);
303 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
304 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
305 let rewrite = rewrite_array(
311 force_trailing_comma,
312 Some(original_style),
314 let comma = match position {
315 MacroPosition::Item => ";",
319 Some(format!("{}{}", rewrite, comma))
322 DelimToken::Brace => {
323 // Skip macro invocations with braces, for now.
324 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
330 pub fn rewrite_macro_def(
331 context: &RewriteContext,
336 vis: &ast::Visibility,
338 ) -> Option<String> {
339 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
340 if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
344 let mut parser = MacroParser::new(def.stream().into_trees());
345 let parsed_def = match parser.parse() {
347 None => return snippet,
350 let mut result = if def.legacy {
351 String::from("macro_rules!")
353 format!("{}macro", format_visibility(vis))
357 result += &ident.name.as_str();
359 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
361 let arm_shape = if multi_branch_style {
363 .block_indent(context.config.tab_spaces())
364 .with_max_width(context.config)
369 let branch_items = itemize_list(
370 context.snippet_provider,
371 parsed_def.branches.iter(),
374 |branch| branch.span.lo(),
375 |branch| branch.span.hi(),
376 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
377 context.snippet_provider.span_after(span, "{"),
380 ).collect::<Vec<_>>();
382 let fmt = ListFormatting {
383 tactic: DefinitiveListTactic::Vertical,
384 separator: if def.legacy { ";" } else { "" },
385 trailing_separator: SeparatorTactic::Always,
386 separator_place: SeparatorPlace::Back,
388 ends_with_newline: true,
389 preserve_newline: true,
390 config: context.config,
393 if multi_branch_style {
395 result += &arm_shape.indent.to_string_with_newline(context.config);
398 result += write_list(&branch_items, &fmt)?.as_str();
400 if multi_branch_style {
401 result += &indent.to_string_with_newline(context.config);
408 fn register_metavariable(
409 map: &mut HashMap<String, String>,
414 let mut new_name = String::new();
415 let mut old_name = String::new();
418 for _ in 0..(dollar_count - 1) {
423 new_name.push_str(&name);
424 old_name.push_str(&name);
426 result.push_str(&new_name);
427 map.insert(old_name, new_name);
430 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
431 // aren't causing problems.
432 // This should also work for escaped `$` variables, where we leave earlier `$`s.
433 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
434 // Each substitution will require five or six extra bytes.
435 let mut result = String::with_capacity(input.len() + 64);
436 let mut substs = HashMap::new();
437 let mut dollar_count = 0;
438 let mut cur_name = String::new();
440 for (kind, c) in CharClasses::new(input.chars()) {
441 if kind != FullCodeCharKind::Normal {
445 } else if dollar_count == 0 {
447 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
448 // Terminates a name following one or more dollars.
449 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
454 } else if c == '(' && cur_name.is_empty() {
455 // FIXME: Support macro def with repeat.
457 } else if c.is_alphanumeric() || c == '_' {
462 if !cur_name.is_empty() {
463 register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
466 debug!("replace_names `{}` {:?}", result, substs);
468 Some((result, substs))
471 #[derive(Debug, Clone)]
474 MetaVariable(ast::Ident, String),
475 /// e.g. `$($foo: expr),*`
477 /// `()`, `[]` or `{}`.
479 /// Inner arguments inside delimiters.
481 /// Something after the closing delimiter and the repeat token, if available.
482 Option<Box<ParsedMacroArg>>,
483 /// The repeat token. This could be one of `*`, `+` or `?`.
486 /// e.g. `[derive(Debug)]`
487 Delimited(DelimToken, Vec<ParsedMacroArg>),
488 /// A possible separator. e.g. `,` or `;`.
489 Separator(String, String),
490 /// Other random stuff that does not fit to other kinds.
491 /// e.g. `== foo` in `($x: expr == foo)`.
492 Other(String, String),
495 fn delim_token_to_str(
496 context: &RewriteContext,
497 delim_token: &DelimToken,
499 use_multiple_lines: bool,
500 ) -> (String, String) {
501 let (lhs, rhs) = match *delim_token {
502 DelimToken::Paren => ("(", ")"),
503 DelimToken::Bracket => ("[", "]"),
504 DelimToken::Brace => ("{ ", " }"),
505 DelimToken::NoDelim => ("", ""),
507 if use_multiple_lines {
508 let indent_str = shape.indent.to_string_with_newline(context.config);
509 let nested_indent_str = shape
511 .block_indent(context.config)
512 .to_string_with_newline(context.config);
514 format!("{}{}", lhs, nested_indent_str),
515 format!("{}{}", indent_str, rhs),
518 (lhs.to_owned(), rhs.to_owned())
523 fn starts_with_brace(&self) -> bool {
525 MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
526 | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
531 fn starts_with_dollar(&self) -> bool {
533 MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
538 fn ends_with_space(&self) -> bool {
540 MacroArgKind::Separator(..) => true,
545 fn has_meta_var(&self) -> bool {
547 MacroArgKind::MetaVariable(..) => true,
548 MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
555 context: &RewriteContext,
557 use_multiple_lines: bool,
558 ) -> Option<String> {
559 let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
560 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false);
561 let inner = wrap_macro_args(context, args, shape)?;
562 if lhs.len() + inner.len() + rhs.len() <= shape.width {
563 return Some((lhs, inner, rhs));
566 let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true);
567 let nested_shape = shape
568 .block_indent(context.config.tab_spaces())
569 .with_max_width(context.config);
570 let inner = wrap_macro_args(context, args, nested_shape)?;
571 Some((lhs, inner, rhs))
575 MacroArgKind::MetaVariable(ty, ref name) => {
576 Some(format!("${}:{}", name, ty.name.as_str()))
578 MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
579 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
580 let another = another
582 .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
583 .unwrap_or("".to_owned());
584 let repeat_tok = pprust::token_to_string(tok);
586 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
588 MacroArgKind::Delimited(ref delim_tok, ref args) => {
589 rewrite_delimited_inner(delim_tok, args)
590 .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
592 MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
593 MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
598 #[derive(Debug, Clone)]
599 struct ParsedMacroArg {
604 impl ParsedMacroArg {
607 context: &RewriteContext,
609 use_multiple_lines: bool,
610 ) -> Option<String> {
611 self.kind.rewrite(context, shape, use_multiple_lines)
615 /// Parses macro arguments on macro def.
616 struct MacroArgParser {
617 /// Holds either a name of the next metavariable, a separator or a junk.
619 /// The start position on the current buffer.
621 /// The first token of the current buffer.
623 /// Set to true if we are parsing a metavariable or a repeat.
625 /// The position of the last token.
627 /// The last token parsed.
629 /// Holds the parsed arguments.
630 result: Vec<ParsedMacroArg>,
633 fn last_tok(tt: &TokenTree) -> Token {
635 TokenTree::Token(_, ref t) => t.clone(),
636 TokenTree::Delimited(_, ref d) => d.close_token(),
640 impl MacroArgParser {
641 pub fn new() -> MacroArgParser {
647 last_tok: Token::Eof,
648 start_tok: Token::Eof,
653 fn set_last_tok(&mut self, tok: &TokenTree) {
654 self.hi = tok.span().hi();
655 self.last_tok = last_tok(tok);
658 fn add_separator(&mut self) {
659 let prefix = if self.need_space_prefix() {
664 self.result.push(ParsedMacroArg {
665 kind: MacroArgKind::Separator(self.buf.clone(), prefix),
666 span: mk_sp(self.lo, self.hi),
671 fn add_other(&mut self) {
672 let prefix = if self.need_space_prefix() {
677 self.result.push(ParsedMacroArg {
678 kind: MacroArgKind::Other(self.buf.clone(), prefix),
679 span: mk_sp(self.lo, self.hi),
684 fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
686 Some(TokenTree::Token(sp, Token::Ident(ref ident))) => {
687 self.result.push(ParsedMacroArg {
688 kind: MacroArgKind::MetaVariable(ident.clone(), self.buf.clone()),
689 span: mk_sp(self.lo, sp.hi()),
693 self.is_meta_var = false;
700 fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
701 self.result.push(ParsedMacroArg {
702 kind: MacroArgKind::Delimited(delim, inner),
710 inner: Vec<ParsedMacroArg>,
715 let mut buffer = String::new();
716 let mut first = false;
717 let mut lo = span.lo();
718 let mut hi = span.hi();
720 // Parse '*', '+' or '?.
721 while let Some(ref tok) = iter.next() {
722 self.set_last_tok(tok);
725 lo = tok.span().lo();
729 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
730 | TokenTree::Token(_, Token::Question)
731 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
734 TokenTree::Token(sp, ref t) => {
735 buffer.push_str(&pprust::token_to_string(t));
742 // There could be some random stuff between ')' and '*', '+' or '?'.
743 let another = if buffer.trim().is_empty() {
746 Some(Box::new(ParsedMacroArg {
747 kind: MacroArgKind::Other(buffer, "".to_owned()),
752 self.result.push(ParsedMacroArg {
753 kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
754 span: mk_sp(self.lo, self.hi),
759 fn update_buffer(&mut self, lo: BytePos, t: &Token) {
760 if self.buf.is_empty() {
762 self.start_tok = t.clone();
764 let needs_space = match next_space(&self.last_tok) {
765 SpaceState::Ident => ident_like(t),
766 SpaceState::Punctuation => !ident_like(t),
767 SpaceState::Always => true,
768 SpaceState::Never => false,
770 if force_space_before(t) || needs_space {
775 self.buf.push_str(&pprust::token_to_string(t));
778 fn need_space_prefix(&self) -> bool {
779 if self.result.is_empty() {
783 let last_arg = self.result.last().unwrap();
784 if let MacroArgKind::MetaVariable(..) = last_arg.kind {
785 if ident_like(&self.start_tok) {
788 if self.start_tok == Token::Colon {
793 if force_space_before(&self.start_tok) {
800 /// Returns a collection of parsed macro def's arguments.
801 pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
802 let mut iter = (tokens.into(): TokenStream).trees();
804 while let Some(ref tok) = iter.next() {
806 TokenTree::Token(sp, Token::Dollar) => {
807 // We always want to add a separator before meta variables.
808 if !self.buf.is_empty() {
809 self.add_separator();
812 // Start keeping the name of this metavariable in the buffer.
813 self.is_meta_var = true;
815 self.start_tok = Token::Dollar;
817 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
818 self.add_meta_variable(&mut iter)?;
820 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
821 TokenTree::Delimited(sp, delimited) => {
822 if !self.buf.is_empty() {
823 if next_space(&self.last_tok) == SpaceState::Always {
824 self.add_separator();
830 // Parse the stuff inside delimiters.
831 let mut parser = MacroArgParser::new();
833 let delimited_arg = parser.parse(delimited.tts.clone())?;
835 if self.is_meta_var {
836 self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp)?;
838 self.add_delimited(delimited_arg, delimited.delim, *sp);
843 self.set_last_tok(tok);
846 // We are left with some stuff in the buffer. Since there is nothing
847 // left to separate, add this as `Other`.
848 if !self.buf.is_empty() {
857 context: &RewriteContext,
858 args: &[ParsedMacroArg],
860 ) -> Option<String> {
861 wrap_macro_args_inner(context, args, shape, false)
862 .or_else(|| wrap_macro_args_inner(context, args, shape, true))
865 fn wrap_macro_args_inner(
866 context: &RewriteContext,
867 args: &[ParsedMacroArg],
869 use_multiple_lines: bool,
870 ) -> Option<String> {
871 let mut result = String::with_capacity(128);
872 let mut iter = args.iter().peekable();
873 let indent_str = shape.indent.to_string_with_newline(context.config);
875 while let Some(ref arg) = iter.next() {
876 result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
878 if use_multiple_lines
879 && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
881 if arg.kind.ends_with_space() {
884 result.push_str(&indent_str);
885 } else if let Some(ref next_arg) = iter.peek() {
886 let space_before_dollar =
887 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
888 let space_before_brace = next_arg.kind.starts_with_brace();
889 if space_before_dollar || space_before_brace {
895 if !use_multiple_lines && result.len() >= shape.width {
902 // This is a bit sketchy. The token rules probably need tweaking, but it works
903 // for some common cases. I hope the basic logic is sufficient. Note that the
904 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
905 // and `(`/`)` have special meaning.
907 // We always try and format on one line.
908 // FIXME: Use multi-line when every thing does not fit on one line.
909 fn format_macro_args(
910 context: &RewriteContext,
911 toks: ThinTokenStream,
913 ) -> Option<String> {
914 let parsed_args = MacroArgParser::new().parse(toks)?;
915 wrap_macro_args(context, &parsed_args, shape)
918 // We should insert a space if the next token is a:
919 #[derive(Copy, Clone, PartialEq)]
923 Ident, // Or ident/literal-like thing.
927 fn force_space_before(tok: &Token) -> bool {
928 debug!("tok: force_space_before {:?}", tok);
949 | Token::Dollar => true,
954 fn ident_like(tok: &Token) -> bool {
956 Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
961 fn next_space(tok: &Token) -> SpaceState {
962 debug!("next_space: {:?}", tok);
966 | Token::BinOp(BinOpToken::And)
975 | Token::Question => SpaceState::Punctuation,
980 | Token::OpenDelim(_)
981 | Token::CloseDelim(_)
982 | Token::Whitespace => SpaceState::Never,
984 Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
986 _ => SpaceState::Always,
990 /// Tries to convert a macro use into a short hand try expression. Returns None
991 /// when the macro is not an instance of try! (or parsing the inner expression
993 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
994 if &format!("{}", mac.node.path)[..] == "try" {
995 let ts: TokenStream = mac.node.tts.clone().into();
996 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
999 id: ast::NodeId::new(0), // dummy value
1000 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1001 span: mac.span, // incorrect span, but shouldn't matter too much
1002 attrs: ThinVec::new(),
1009 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1010 let snippet = context.snippet(mac.span);
1011 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1012 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1013 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1015 if paren_pos < bracket_pos && paren_pos < brace_pos {
1017 } else if bracket_pos < brace_pos {
1024 /// Indent each line according to the specified `indent`.
1052 fn indent_macro_snippet(
1053 context: &RewriteContext,
1056 ) -> Option<String> {
1057 let mut lines = macro_str.lines();
1058 let first_line = lines.next().map(|s| s.trim_right())?;
1059 let mut trimmed_lines = Vec::with_capacity(16);
1061 let min_prefix_space_width = lines
1062 .filter_map(|line| {
1063 let prefix_space_width = if is_empty_line(line) {
1066 Some(get_prefix_space_width(context, line))
1068 trimmed_lines.push((line.trim(), prefix_space_width));
1074 String::from(first_line) + "\n"
1077 .map(|&(line, prefix_space_width)| match prefix_space_width {
1078 Some(original_indent_width) => {
1079 let new_indent_width = indent.width()
1080 + original_indent_width
1081 .checked_sub(min_prefix_space_width)
1083 let new_indent = Indent::from_width(context.config, new_indent_width);
1084 format!("{}{}", new_indent.to_string(context.config), line.trim())
1086 None => String::new(),
1088 .collect::<Vec<_>>()
1093 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1095 for c in s.chars() {
1098 '\t' => width += context.config.tab_spaces(),
1105 fn is_empty_line(s: &str) -> bool {
1106 s.is_empty() || s.chars().all(char::is_whitespace)
1109 // A very simple parser that just parses a macros 2.0 definition into its branches.
1110 // Currently we do not attempt to parse any further than that.
1112 struct MacroParser {
1117 // (`(` ... `)` `=>` `{` ... `}`)*
1118 fn parse(&mut self) -> Option<Macro> {
1119 let mut branches = vec![];
1120 while self.toks.look_ahead(1).is_some() {
1121 branches.push(self.parse_branch()?);
1124 Some(Macro { branches })
1127 // `(` ... `)` `=>` `{` ... `}`
1128 fn parse_branch(&mut self) -> Option<MacroBranch> {
1129 let tok = self.toks.next()?;
1130 let (lo, args_paren_kind) = match tok {
1131 TokenTree::Token(..) => return None,
1132 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1134 let args = tok.joint().into();
1135 match self.toks.next()? {
1136 TokenTree::Token(_, Token::FatArrow) => {}
1139 let (mut hi, body) = match self.toks.next()? {
1140 TokenTree::Token(..) => return None,
1141 TokenTree::Delimited(sp, _) => {
1142 let data = sp.data();
1145 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1149 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1154 span: mk_sp(lo, hi),
1162 // A parsed macros 2.0 macro definition.
1164 branches: Vec<MacroBranch>,
1167 // FIXME: it would be more efficient to use references to the token streams
1168 // rather than clone them, if we can make the borrowing work out.
1169 struct MacroBranch {
1171 args_paren_kind: DelimToken,
1172 args: ThinTokenStream,
1179 context: &RewriteContext,
1181 multi_branch_style: bool,
1182 ) -> Option<String> {
1183 // Only attempt to format function-like macros.
1184 if self.args_paren_kind != DelimToken::Paren {
1185 // FIXME(#1539): implement for non-sugared macros.
1190 let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1192 if multi_branch_style {
1196 // The macro body is the most interesting part. It might end up as various
1197 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1198 // parsed as regular Rust code (and note that these can be escaped using
1199 // `$$`). We'll try and format like an AST node, but we'll substitute
1200 // variables for new names with the same length first.
1202 let old_body = context.snippet(self.body).trim();
1203 let (body_str, substs) = replace_names(old_body)?;
1205 let mut config = context.config.clone();
1206 config.set().hide_parse_errors(true);
1210 let has_block_body = old_body.starts_with('{');
1212 let body_indent = if has_block_body {
1215 // We'll hack the indent below, take this into account when formatting,
1216 let body_indent = shape.indent.block_indent(&config);
1217 let new_width = config.max_width() - body_indent.width();
1218 config.set().max_width(new_width);
1222 // First try to format as items, then as statements.
1223 let new_body = match ::format_snippet(&body_str, &config) {
1224 Some(new_body) => new_body,
1225 None => match ::format_code_block(&body_str, &config) {
1226 Some(new_body) => new_body,
1227 None => return None,
1230 let new_body = wrap_str(new_body, config.max_width(), shape)?;
1232 // Indent the body since it is in a block.
1233 let indent_str = body_indent.to_string(&config);
1234 let mut new_body = new_body
1237 .fold(String::new(), |mut s, l| {
1244 // Undo our replacement of macro variables.
1245 // FIXME: this could be *much* more efficient.
1246 for (old, new) in &substs {
1247 if old_body.find(new).is_some() {
1248 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1251 new_body = new_body.replace(new, old);
1255 result += new_body.trim();
1256 } else if !new_body.is_empty() {
1258 result += &new_body;
1259 result += &shape.indent.to_string(&config);
1268 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1270 /// # Expected syntax
1274 /// [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1275 /// [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1277 /// [pub] static ref NAME_N: TYPE_N = EXPR_N;
1280 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1281 let mut result = String::with_capacity(1024);
1282 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1283 let nested_shape = shape.block_indent(context.config.tab_spaces());
1285 result.push_str("lazy_static! {");
1286 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1288 macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1289 match parser.$method($($arg,)*) {
1291 if parser.sess.span_diagnostic.has_errors() {
1292 parser.sess.span_diagnostic.reset_err_count();
1300 parser.sess.span_diagnostic.reset_err_count();
1306 while parser.token != Token::Eof {
1307 // Parse a `lazy_static!` item.
1308 let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1309 parser.eat_keyword(symbol::keywords::Static);
1310 parser.eat_keyword(symbol::keywords::Ref);
1311 let id = parse_or!(parse_ident);
1312 parser.eat(&Token::Colon);
1313 let ty = parse_or!(parse_ty);
1314 parser.eat(&Token::Eq);
1315 let expr = parse_or!(parse_expr);
1316 parser.eat(&Token::Semi);
1318 // Rewrite as a static item.
1319 let mut stmt = String::with_capacity(128);
1320 stmt.push_str(&format!(
1321 "{}static ref {}: {} =",
1324 ty.rewrite(context, nested_shape)?
1326 result.push_str(&::expr::rewrite_assign_rhs(
1330 nested_shape.sub_width(1)?,
1333 if parser.token != Token::Eof {
1334 result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1338 result.push_str(&shape.indent.to_string_with_newline(context.config));