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;
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, FindUncommented};
37 use expr::{rewrite_array, rewrite_call_inner};
38 use lists::{itemize_list, write_list, ListFormatting};
39 use rewrite::{Rewrite, RewriteContext};
40 use shape::{Indent, Shape};
41 use utils::{format_visibility, mk_sp};
43 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
45 // FIXME: use the enum from libsyntax?
46 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub enum MacroPosition {
62 fn opener(&self) -> &'static str {
64 MacroStyle::Parens => "(",
65 MacroStyle::Brackets => "[",
66 MacroStyle::Braces => "{",
78 impl Rewrite for MacroArg {
79 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
81 MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
82 MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
83 MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
88 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
89 macro_rules! parse_macro_arg {
90 ($macro_arg: ident, $parser: ident) => {
91 let mut cloned_parser = (*parser).clone();
92 match cloned_parser.$parser() {
94 if parser.sess.span_diagnostic.has_errors() {
95 parser.sess.span_diagnostic.reset_err_count();
98 *parser = cloned_parser;
99 return Some(MacroArg::$macro_arg((*x).clone()));
104 parser.sess.span_diagnostic.reset_err_count();
110 parse_macro_arg!(Expr, parse_expr);
111 parse_macro_arg!(Ty, parse_ty);
112 parse_macro_arg!(Pat, parse_pat);
117 /// Rewrite macro name without using pretty-printer if possible.
118 fn rewrite_macro_name(path: &ast::Path, extra_ident: Option<ast::Ident>) -> String {
119 let name = if path.segments.len() == 1 {
120 // Avoid using pretty-printer in the common case.
121 format!("{}!", path.segments[0].identifier)
126 Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
131 pub fn rewrite_macro(
133 extra_ident: Option<ast::Ident>,
134 context: &RewriteContext,
136 position: MacroPosition,
137 ) -> Option<String> {
138 let context = &mut context.clone();
139 context.inside_macro = true;
140 if context.config.use_try_shorthand() {
141 if let Some(expr) = convert_try_mac(mac, context) {
142 context.inside_macro = false;
143 return expr.rewrite(context, shape);
147 let original_style = macro_style(mac, context);
149 let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
151 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
157 let ts: TokenStream = mac.node.stream();
158 if ts.is_empty() && !contains_comment(context.snippet(mac.span)) {
160 MacroStyle::Parens if position == MacroPosition::Item => {
161 Some(format!("{}();", macro_name))
163 MacroStyle::Parens => Some(format!("{}()", macro_name)),
164 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
165 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
169 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
170 let mut arg_vec = Vec::new();
171 let mut vec_with_semi = false;
172 let mut trailing_comma = false;
174 if MacroStyle::Braces != style {
176 match parse_macro_arg(&mut parser) {
177 Some(arg) => arg_vec.push(arg),
178 None => return Some(context.snippet(mac.span).to_owned()),
185 // Try to parse `vec![expr; expr]`
186 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
188 if parser.token != Token::Eof {
189 match parse_macro_arg(&mut parser) {
193 if parser.token == Token::Eof && arg_vec.len() == 2 {
194 vec_with_semi = true;
198 None => return Some(context.snippet(mac.span).to_owned()),
202 return Some(context.snippet(mac.span).to_owned());
204 _ => return Some(context.snippet(mac.span).to_owned()),
209 if parser.token == Token::Eof {
210 trailing_comma = true;
217 MacroStyle::Parens => {
218 // Format macro invocation as function call, forcing no trailing
219 // comma because not all macros support them.
223 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
226 context.config.width_heuristics().fn_call_width,
228 ).map(|rw| match position {
229 MacroPosition::Item => format!("{};", rw),
233 MacroStyle::Brackets => {
234 let mac_shape = shape.offset_left(macro_name.len())?;
235 // Handle special case: `vec![expr; expr]`
237 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
243 let total_overhead = lbr.len() + rbr.len() + 6;
244 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
245 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
246 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
247 if !lhs.contains('\n') && !rhs.contains('\n')
248 && lhs.len() + rhs.len() + total_overhead <= shape.width
250 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
256 nested_shape.indent.to_string_with_newline(context.config),
258 nested_shape.indent.to_string_with_newline(context.config),
260 shape.indent.to_string_with_newline(context.config),
265 // If we are rewriting `vec!` macro or other special macros,
266 // then we can rewrite this as an usual array literal.
267 // Otherwise, we must preserve the original existence of trailing comma.
268 if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) {
269 context.inside_macro = false;
270 trailing_comma = false;
272 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
276 .span_after(mac.span, original_style.opener()),
277 mac.span.hi() - BytePos(1),
279 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
280 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
282 Some(format!("{}{}", macro_name, rewrite))
285 MacroStyle::Braces => {
286 // Skip macro invocations with braces, for now.
287 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
292 pub fn rewrite_macro_def(
293 context: &RewriteContext,
298 vis: &ast::Visibility,
300 ) -> Option<String> {
301 let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
303 let mut parser = MacroParser::new(def.stream().into_trees());
304 let parsed_def = match parser.parse() {
306 None => return snippet,
309 let mut result = if def.legacy {
310 String::from("macro_rules!")
312 format!("{}macro", format_visibility(vis))
316 result += &ident.name.as_str();
318 let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
320 let arm_shape = if multi_branch_style {
322 .block_indent(context.config.tab_spaces())
323 .with_max_width(context.config)
328 let branch_items = itemize_list(
329 context.snippet_provider,
330 parsed_def.branches.iter(),
333 |branch| branch.span.lo(),
334 |branch| branch.span.hi(),
335 |branch| branch.rewrite(context, arm_shape, multi_branch_style),
336 context.snippet_provider.span_after(span, "{"),
339 ).collect::<Vec<_>>();
341 let fmt = ListFormatting {
342 tactic: DefinitiveListTactic::Vertical,
343 separator: if def.legacy { ";" } else { "" },
344 trailing_separator: SeparatorTactic::Always,
345 separator_place: SeparatorPlace::Back,
347 ends_with_newline: true,
348 preserve_newline: true,
349 config: context.config,
352 if multi_branch_style {
354 result += &arm_shape.indent.to_string_with_newline(context.config);
357 result += write_list(&branch_items, &fmt)?.as_str();
359 if multi_branch_style {
360 result += &indent.to_string_with_newline(context.config);
367 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
368 // aren't causing problems.
369 // This should also work for escaped `$` variables, where we leave earlier `$`s.
370 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
371 // Each substitution will require five or six extra bytes.
372 let mut result = String::with_capacity(input.len() + 64);
373 let mut substs = HashMap::new();
374 let mut dollar_count = 0;
375 let mut cur_name = String::new();
377 for c in input.chars() {
380 } else if dollar_count == 0 {
382 } else if !c.is_alphanumeric() && !cur_name.is_empty() {
383 // Terminates a name following one or more dollars.
384 let mut new_name = String::new();
385 let mut old_name = String::new();
387 for _ in 0..(dollar_count - 1) {
392 new_name.push_str(&cur_name);
393 old_name.push_str(&cur_name);
395 result.push_str(&new_name);
396 substs.insert(old_name, new_name);
401 cur_name = String::new();
402 } else if c == '(' && cur_name.is_empty() {
403 // FIXME: Support macro def with repeat.
405 } else if c.is_alphanumeric() {
410 // FIXME: duplicate code
411 if !cur_name.is_empty() {
412 let mut new_name = String::new();
413 let mut old_name = String::new();
415 for _ in 0..(dollar_count - 1) {
420 new_name.push_str(&cur_name);
421 old_name.push_str(&cur_name);
423 result.push_str(&new_name);
424 substs.insert(old_name, new_name);
427 debug!("replace_names `{}` {:?}", result, substs);
429 Some((result, substs))
432 // This is a bit sketchy. The token rules probably need tweaking, but it works
433 // for some common cases. I hope the basic logic is sufficient. Note that the
434 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
435 // and `(`/`)` have special meaning.
437 // We always try and format on one line.
438 // FIXME: Use multi-line when every thing does not fit on one line.
439 fn format_macro_args(toks: ThinTokenStream, shape: Shape) -> Option<String> {
440 let mut result = String::with_capacity(128);
441 let mut insert_space = SpaceState::Never;
443 for tok in (toks.into(): TokenStream).trees() {
445 TokenTree::Token(_, t) => {
446 if !result.is_empty() && force_space_before(&t) {
447 insert_space = SpaceState::Always;
449 if force_no_space_before(&t) {
450 insert_space = SpaceState::Never;
452 match (insert_space, ident_like(&t)) {
453 (SpaceState::Always, _)
454 | (SpaceState::Punctuation, false)
455 | (SpaceState::Ident, true) => {
460 result.push_str(&pprust::token_to_string(&t));
461 insert_space = next_space(&t);
463 TokenTree::Delimited(_, d) => {
464 if let SpaceState::Always = insert_space {
467 let formatted = format_macro_args(d.tts, shape)?;
469 DelimToken::Paren => {
470 result.push_str(&format!("({})", formatted));
471 insert_space = SpaceState::Always;
473 DelimToken::Bracket => {
474 result.push_str(&format!("[{}]", formatted));
475 insert_space = SpaceState::Always;
477 DelimToken::Brace => {
478 result.push_str(&format!(" {{ {} }}", formatted));
479 insert_space = SpaceState::Always;
481 DelimToken::NoDelim => {
482 result.push_str(&format!("{}", formatted));
483 insert_space = SpaceState::Always;
490 if result.len() <= shape.width {
497 // We should insert a space if the next token is a:
498 #[derive(Copy, Clone)]
502 Ident, // Or ident/literal-like thing.
506 fn force_space_before(tok: &Token) -> bool {
525 | Token::Dollar => true,
526 Token::BinOp(bot) => bot != BinOpToken::Star,
531 fn force_no_space_before(tok: &Token) -> bool {
533 Token::Semi | Token::Comma | Token::Dot => true,
534 Token::BinOp(bot) => bot == BinOpToken::Star,
538 fn ident_like(tok: &Token) -> bool {
540 Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
545 fn next_space(tok: &Token) -> SpaceState {
558 | Token::BinOp(_) => SpaceState::Punctuation,
563 | Token::OpenDelim(_)
564 | Token::CloseDelim(_)
565 | Token::Whitespace => SpaceState::Never,
567 Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
569 _ => SpaceState::Always,
573 /// Tries to convert a macro use into a short hand try expression. Returns None
574 /// when the macro is not an instance of try! (or parsing the inner expression
576 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
577 if &format!("{}", mac.node.path)[..] == "try" {
578 let ts: TokenStream = mac.node.tts.clone().into();
579 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
582 id: ast::NodeId::new(0), // dummy value
583 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
584 span: mac.span, // incorrect span, but shouldn't matter too much
585 attrs: ThinVec::new(),
592 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
593 let snippet = context.snippet(mac.span);
594 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
595 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
596 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
598 if paren_pos < bracket_pos && paren_pos < brace_pos {
600 } else if bracket_pos < brace_pos {
607 /// Indent each line according to the specified `indent`.
632 fn indent_macro_snippet(
633 context: &RewriteContext,
636 ) -> Option<String> {
637 let mut lines = macro_str.lines();
638 let first_line = lines.next().map(|s| s.trim_right())?;
639 let mut trimmed_lines = Vec::with_capacity(16);
641 let min_prefix_space_width = lines
643 let prefix_space_width = if is_empty_line(line) {
646 Some(get_prefix_space_width(context, line))
648 trimmed_lines.push((line.trim(), prefix_space_width));
654 String::from(first_line) + "\n"
657 .map(|&(line, prefix_space_width)| match prefix_space_width {
658 Some(original_indent_width) => {
659 let new_indent_width = indent.width()
660 + original_indent_width
661 .checked_sub(min_prefix_space_width)
663 let new_indent = Indent::from_width(context.config, new_indent_width);
664 format!("{}{}", new_indent.to_string(context.config), line.trim())
666 None => String::new(),
673 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
678 '\t' => width += context.config.tab_spaces(),
685 fn is_empty_line(s: &str) -> bool {
686 s.is_empty() || s.chars().all(char::is_whitespace)
689 // A very simple parser that just parses a macros 2.0 definition into its branches.
690 // Currently we do not attempt to parse any further than that.
697 // (`(` ... `)` `=>` `{` ... `}`)*
698 fn parse(&mut self) -> Option<Macro> {
699 let mut branches = vec![];
700 while self.toks.look_ahead(1).is_some() {
701 branches.push(self.parse_branch()?);
704 Some(Macro { branches })
707 // `(` ... `)` `=>` `{` ... `}`
708 fn parse_branch(&mut self) -> Option<MacroBranch> {
709 let tok = self.toks.next()?;
710 let (lo, args_paren_kind) = match tok {
711 TokenTree::Token(..) => return None,
712 TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
714 let args = tok.joint().into();
715 match self.toks.next()? {
716 TokenTree::Token(_, Token::FatArrow) => {}
719 let (mut hi, body) = match self.toks.next()? {
720 TokenTree::Token(..) => return None,
721 TokenTree::Delimited(sp, _) => {
722 let data = sp.data();
725 Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
729 if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
742 // A parsed macros 2.0 macro definition.
744 branches: Vec<MacroBranch>,
747 // FIXME: it would be more efficient to use references to the token streams
748 // rather than clone them, if we can make the borrowing work out.
751 args_paren_kind: DelimToken,
752 args: ThinTokenStream,
759 context: &RewriteContext,
761 multi_branch_style: bool,
762 ) -> Option<String> {
763 // Only attempt to format function-like macros.
764 if self.args_paren_kind != DelimToken::Paren {
765 // FIXME(#1539): implement for non-sugared macros.
770 let mut result = format_macro_args(self.args.clone(), shape.sub_width(5)?)?;
772 if multi_branch_style {
776 // The macro body is the most interesting part. It might end up as various
777 // AST nodes, but also has special variables (e.g, `$foo`) which can't be
778 // parsed as regular Rust code (and note that these can be escaped using
779 // `$$`). We'll try and format like an AST node, but we'll substitute
780 // variables for new names with the same length first.
782 let old_body = context.snippet(self.body).trim();
783 let (body_str, substs) = replace_names(old_body)?;
785 let mut config = context.config.clone();
786 config.set().hide_parse_errors(true);
790 let has_block_body = old_body.starts_with('{');
792 let body_indent = if has_block_body {
795 // We'll hack the indent below, take this into account when formatting,
796 let body_indent = shape.indent.block_indent(&config);
797 let new_width = config.max_width() - body_indent.width();
798 config.set().max_width(new_width);
802 // First try to format as items, then as statements.
803 let new_body = match ::format_snippet(&body_str, &config) {
804 Some(new_body) => new_body,
805 None => match ::format_code_block(&body_str, &config) {
806 Some(new_body) => new_body,
811 // Indent the body since it is in a block.
812 let indent_str = body_indent.to_string(&config);
813 let mut new_body = new_body
816 .fold(String::new(), |mut s, l| {
823 // Undo our replacement of macro variables.
824 // FIXME: this could be *much* more efficient.
825 for (old, new) in &substs {
826 if old_body.find(new).is_some() {
827 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
830 new_body = new_body.replace(new, old);
834 result += new_body.trim();
835 } else if !new_body.is_empty() {
838 result += &shape.indent.to_string(&config);
850 use syntax::parse::{parse_stream_from_source_str, ParseSess};
851 use syntax::codemap::{FileName, FilePathMapping};
853 fn format_macro_args_str(s: &str) -> String {
854 let input = parse_stream_from_source_str(
855 FileName::Custom("stdin".to_owned()),
857 &ParseSess::new(FilePathMapping::empty()),
862 indent: Indent::empty(),
865 format_macro_args(input.into(), shape).unwrap()
869 fn test_format_macro_args() {
870 assert_eq!(format_macro_args_str(""), "".to_owned());
871 assert_eq!(format_macro_args_str("$ x : ident"), "$x: ident".to_owned());
873 format_macro_args_str("$ m1 : ident , $ m2 : ident , $ x : ident"),
874 "$m1: ident, $m2: ident, $x: ident".to_owned()
877 format_macro_args_str("$($beginning:ident),*;$middle:ident;$($end:ident),*"),
878 "$($beginning: ident),*; $middle: ident; $($end: ident),*".to_owned()
881 format_macro_args_str(
882 "$ name : ident ( $ ( $ dol : tt $ var : ident ) * ) $ ( $ body : tt ) *"
884 "$name: ident($($dol: tt $var: ident)*) $($body: tt)*".to_owned()