]> git.lizzy.rs Git - rust.git/blob - rustfmt-core/src/macros.rs
Cargo clippy
[rust.git] / rustfmt-core / src / macros.rs
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.
4 //
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.
10
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
18 // reformatted.
19 // List-like invocations with parentheses will be formatted as function calls,
20 // and those with brackets will be formatted as array literals.
21
22 use std::collections::HashMap;
23
24 use config::lists::*;
25 use syntax::ast;
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;
31 use syntax::symbol;
32 use syntax::tokenstream::{Cursor, ThinTokenStream, TokenStream, TokenTree};
33 use syntax::util::ThinVec;
34
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};
42
43 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
44
45 // FIXME: use the enum from libsyntax?
46 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
47 enum MacroStyle {
48     Parens,
49     Brackets,
50     Braces,
51 }
52
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub enum MacroPosition {
55     Item,
56     Statement,
57     Expression,
58     Pat,
59 }
60
61 impl MacroStyle {
62     fn opener(&self) -> &'static str {
63         match *self {
64             MacroStyle::Parens => "(",
65             MacroStyle::Brackets => "[",
66             MacroStyle::Braces => "{",
67         }
68     }
69 }
70
71 #[derive(Debug)]
72 pub enum MacroArg {
73     Expr(ast::Expr),
74     Ty(ast::Ty),
75     Pat(ast::Pat),
76 }
77
78 impl Rewrite for MacroArg {
79     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
80         match *self {
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),
84         }
85     }
86 }
87
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() {
93                 Ok(x) => {
94                     if parser.sess.span_diagnostic.has_errors() {
95                         parser.sess.span_diagnostic.reset_err_count();
96                     } else {
97                         // Parsing succeeded.
98                         *parser = cloned_parser;
99                         return Some(MacroArg::$macro_arg((*x).clone()));
100                     }
101                 }
102                 Err(mut e) => {
103                     e.cancel();
104                     parser.sess.span_diagnostic.reset_err_count();
105                 }
106             }
107         };
108     }
109
110     parse_macro_arg!(Expr, parse_expr);
111     parse_macro_arg!(Ty, parse_ty);
112     parse_macro_arg!(Pat, parse_pat);
113
114     None
115 }
116
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)
122     } else {
123         format!("{}!", path)
124     };
125     match extra_ident {
126         Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
127         _ => name,
128     }
129 }
130
131 pub fn rewrite_macro(
132     mac: &ast::Mac,
133     extra_ident: Option<ast::Ident>,
134     context: &RewriteContext,
135     shape: Shape,
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);
144         }
145     }
146
147     let original_style = macro_style(mac, context);
148
149     let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
150
151     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
152         MacroStyle::Brackets
153     } else {
154         original_style
155     };
156
157     let ts: TokenStream = mac.node.stream();
158     if ts.is_empty() && !contains_comment(context.snippet(mac.span)) {
159         return match style {
160             MacroStyle::Parens if position == MacroPosition::Item => {
161                 Some(format!("{}();", macro_name))
162             }
163             MacroStyle::Parens => Some(format!("{}()", macro_name)),
164             MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
165             MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
166         };
167     }
168
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;
173
174     if MacroStyle::Braces != style {
175         loop {
176             match parse_macro_arg(&mut parser) {
177                 Some(arg) => arg_vec.push(arg),
178                 None => return Some(context.snippet(mac.span).to_owned()),
179             }
180
181             match parser.token {
182                 Token::Eof => break,
183                 Token::Comma => (),
184                 Token::Semi => {
185                     // Try to parse `vec![expr; expr]`
186                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
187                         parser.bump();
188                         if parser.token != Token::Eof {
189                             match parse_macro_arg(&mut parser) {
190                                 Some(arg) => {
191                                     arg_vec.push(arg);
192                                     parser.bump();
193                                     if parser.token == Token::Eof && arg_vec.len() == 2 {
194                                         vec_with_semi = true;
195                                         break;
196                                     }
197                                 }
198                                 None => return Some(context.snippet(mac.span).to_owned()),
199                             }
200                         }
201                     }
202                     return Some(context.snippet(mac.span).to_owned());
203                 }
204                 _ => return Some(context.snippet(mac.span).to_owned()),
205             }
206
207             parser.bump();
208
209             if parser.token == Token::Eof {
210                 trailing_comma = true;
211                 break;
212             }
213         }
214     }
215
216     match style {
217         MacroStyle::Parens => {
218             // Format macro invocation as function call, forcing no trailing
219             // comma because not all macros support them.
220             rewrite_call_inner(
221                 context,
222                 &macro_name,
223                 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
224                 mac.span,
225                 shape,
226                 context.config.width_heuristics().fn_call_width,
227                 trailing_comma,
228             ).map(|rw| match position {
229                 MacroPosition::Item => format!("{};", rw),
230                 _ => rw,
231             })
232         }
233         MacroStyle::Brackets => {
234             let mac_shape = shape.offset_left(macro_name.len())?;
235             // Handle special case: `vec![expr; expr]`
236             if vec_with_semi {
237                 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
238                     ("[ ", " ]")
239                 } else {
240                     ("[", "]")
241                 };
242                 // 6 = `vec!` + `; `
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
249                 {
250                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
251                 } else {
252                     Some(format!(
253                         "{}{}{}{};{}{}{}{}",
254                         macro_name,
255                         lbr,
256                         nested_shape.indent.to_string_with_newline(context.config),
257                         lhs,
258                         nested_shape.indent.to_string_with_newline(context.config),
259                         rhs,
260                         shape.indent.to_string_with_newline(context.config),
261                         rbr
262                     ))
263                 }
264             } else {
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(&macro_name.as_str()) {
269                     context.inside_macro = false;
270                     trailing_comma = false;
271                 }
272                 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
273                 let sp = mk_sp(
274                     context
275                         .snippet_provider
276                         .span_after(mac.span, original_style.opener()),
277                     mac.span.hi() - BytePos(1),
278                 );
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)?;
281
282                 Some(format!("{}{}", macro_name, rewrite))
283             }
284         }
285         MacroStyle::Braces => {
286             // Skip macro invocations with braces, for now.
287             indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
288         }
289     }
290 }
291
292 pub fn rewrite_macro_def(
293     context: &RewriteContext,
294     shape: Shape,
295     indent: Indent,
296     def: &ast::MacroDef,
297     ident: ast::Ident,
298     vis: &ast::Visibility,
299     span: Span,
300 ) -> Option<String> {
301     let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
302     if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
303         return snippet;
304     }
305
306     let mut parser = MacroParser::new(def.stream().into_trees());
307     let parsed_def = match parser.parse() {
308         Some(def) => def,
309         None => return snippet,
310     };
311
312     let mut result = if def.legacy {
313         String::from("macro_rules!")
314     } else {
315         format!("{}macro", format_visibility(vis))
316     };
317
318     result += " ";
319     result += &ident.name.as_str();
320
321     let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
322
323     let arm_shape = if multi_branch_style {
324         shape
325             .block_indent(context.config.tab_spaces())
326             .with_max_width(context.config)
327     } else {
328         shape
329     };
330
331     let branch_items = itemize_list(
332         context.snippet_provider,
333         parsed_def.branches.iter(),
334         "}",
335         ";",
336         |branch| branch.span.lo(),
337         |branch| branch.span.hi(),
338         |branch| branch.rewrite(context, arm_shape, multi_branch_style),
339         context.snippet_provider.span_after(span, "{"),
340         span.hi(),
341         false,
342     ).collect::<Vec<_>>();
343
344     let fmt = ListFormatting {
345         tactic: DefinitiveListTactic::Vertical,
346         separator: if def.legacy { ";" } else { "" },
347         trailing_separator: SeparatorTactic::Always,
348         separator_place: SeparatorPlace::Back,
349         shape: arm_shape,
350         ends_with_newline: true,
351         preserve_newline: true,
352         config: context.config,
353     };
354
355     if multi_branch_style {
356         result += " {";
357         result += &arm_shape.indent.to_string_with_newline(context.config);
358     }
359
360     result += write_list(&branch_items, &fmt)?.as_str();
361
362     if multi_branch_style {
363         result += &indent.to_string_with_newline(context.config);
364         result += "}";
365     }
366
367     Some(result)
368 }
369
370 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
371 // aren't causing problems.
372 // This should also work for escaped `$` variables, where we leave earlier `$`s.
373 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
374     // Each substitution will require five or six extra bytes.
375     let mut result = String::with_capacity(input.len() + 64);
376     let mut substs = HashMap::new();
377     let mut dollar_count = 0;
378     let mut cur_name = String::new();
379
380     for c in input.chars() {
381         if c == '$' {
382             dollar_count += 1;
383         } else if dollar_count == 0 {
384             result.push(c);
385         } else if !c.is_alphanumeric() && !cur_name.is_empty() {
386             // Terminates a name following one or more dollars.
387             let mut new_name = String::new();
388             let mut old_name = String::new();
389             old_name.push('$');
390             for _ in 0..(dollar_count - 1) {
391                 new_name.push('$');
392                 old_name.push('$');
393             }
394             new_name.push('z');
395             new_name.push_str(&cur_name);
396             old_name.push_str(&cur_name);
397
398             result.push_str(&new_name);
399             substs.insert(old_name, new_name);
400
401             result.push(c);
402
403             dollar_count = 0;
404             cur_name = String::new();
405         } else if c == '(' && cur_name.is_empty() {
406             // FIXME: Support macro def with repeat.
407             return None;
408         } else if c.is_alphanumeric() {
409             cur_name.push(c);
410         }
411     }
412
413     // FIXME: duplicate code
414     if !cur_name.is_empty() {
415         let mut new_name = String::new();
416         let mut old_name = String::new();
417         old_name.push('$');
418         for _ in 0..(dollar_count - 1) {
419             new_name.push('$');
420             old_name.push('$');
421         }
422         new_name.push('z');
423         new_name.push_str(&cur_name);
424         old_name.push_str(&cur_name);
425
426         result.push_str(&new_name);
427         substs.insert(old_name, new_name);
428     }
429
430     debug!("replace_names `{}` {:?}", result, substs);
431
432     Some((result, substs))
433 }
434
435 // This is a bit sketchy. The token rules probably need tweaking, but it works
436 // for some common cases. I hope the basic logic is sufficient. Note that the
437 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
438 // and `(`/`)` have special meaning.
439 //
440 // We always try and format on one line.
441 // FIXME: Use multi-line when every thing does not fit on one line.
442 fn format_macro_args(toks: ThinTokenStream, shape: Shape) -> Option<String> {
443     let mut result = String::with_capacity(128);
444     let mut insert_space = SpaceState::Never;
445
446     for tok in (toks.into(): TokenStream).trees() {
447         match tok {
448             TokenTree::Token(_, t) => {
449                 if !result.is_empty() && force_space_before(&t) {
450                     insert_space = SpaceState::Always;
451                 }
452                 if force_no_space_before(&t) {
453                     insert_space = SpaceState::Never;
454                 }
455                 match (insert_space, ident_like(&t)) {
456                     (SpaceState::Always, _)
457                     | (SpaceState::Punctuation, false)
458                     | (SpaceState::Ident, true) => {
459                         result.push(' ');
460                     }
461                     _ => {}
462                 }
463                 result.push_str(&pprust::token_to_string(&t));
464                 insert_space = next_space(&t);
465             }
466             TokenTree::Delimited(_, d) => {
467                 if let SpaceState::Always = insert_space {
468                     result.push(' ');
469                 }
470                 let formatted = format_macro_args(d.tts, shape)?;
471                 match d.delim {
472                     DelimToken::Paren => {
473                         result.push_str(&format!("({})", formatted));
474                         insert_space = SpaceState::Always;
475                     }
476                     DelimToken::Bracket => {
477                         result.push_str(&format!("[{}]", formatted));
478                         insert_space = SpaceState::Always;
479                     }
480                     DelimToken::Brace => {
481                         result.push_str(&format!(" {{ {} }}", formatted));
482                         insert_space = SpaceState::Always;
483                     }
484                     DelimToken::NoDelim => {
485                         result.push_str(&format!("{}", formatted));
486                         insert_space = SpaceState::Always;
487                     }
488                 }
489             }
490         }
491     }
492
493     if result.len() <= shape.width {
494         Some(result)
495     } else {
496         None
497     }
498 }
499
500 // We should insert a space if the next token is a:
501 #[derive(Copy, Clone)]
502 enum SpaceState {
503     Never,
504     Punctuation,
505     Ident, // Or ident/literal-like thing.
506     Always,
507 }
508
509 fn force_space_before(tok: &Token) -> bool {
510     match *tok {
511         Token::Eq
512         | Token::Lt
513         | Token::Le
514         | Token::EqEq
515         | Token::Ne
516         | Token::Ge
517         | Token::Gt
518         | Token::AndAnd
519         | Token::OrOr
520         | Token::Not
521         | Token::Tilde
522         | Token::BinOpEq(_)
523         | Token::At
524         | Token::RArrow
525         | Token::LArrow
526         | Token::FatArrow
527         | Token::Pound
528         | Token::Dollar => true,
529         Token::BinOp(bot) => bot != BinOpToken::Star,
530         _ => false,
531     }
532 }
533
534 fn force_no_space_before(tok: &Token) -> bool {
535     match *tok {
536         Token::Semi | Token::Comma | Token::Dot => true,
537         Token::BinOp(bot) => bot == BinOpToken::Star,
538         _ => false,
539     }
540 }
541 fn ident_like(tok: &Token) -> bool {
542     match *tok {
543         Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
544         _ => false,
545     }
546 }
547
548 fn next_space(tok: &Token) -> SpaceState {
549     match *tok {
550         Token::Not
551         | Token::Tilde
552         | Token::At
553         | Token::Comma
554         | Token::Dot
555         | Token::DotDot
556         | Token::DotDotDot
557         | Token::DotDotEq
558         | Token::DotEq
559         | Token::Question
560         | Token::Underscore
561         | Token::BinOp(_) => SpaceState::Punctuation,
562
563         Token::ModSep
564         | Token::Pound
565         | Token::Dollar
566         | Token::OpenDelim(_)
567         | Token::CloseDelim(_)
568         | Token::Whitespace => SpaceState::Never,
569
570         Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
571
572         _ => SpaceState::Always,
573     }
574 }
575
576 /// Tries to convert a macro use into a short hand try expression. Returns None
577 /// when the macro is not an instance of try! (or parsing the inner expression
578 /// failed).
579 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
580     if &format!("{}", mac.node.path)[..] == "try" {
581         let ts: TokenStream = mac.node.tts.clone().into();
582         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
583
584         Some(ast::Expr {
585             id: ast::NodeId::new(0), // dummy value
586             node: ast::ExprKind::Try(parser.parse_expr().ok()?),
587             span: mac.span, // incorrect span, but shouldn't matter too much
588             attrs: ThinVec::new(),
589         })
590     } else {
591         None
592     }
593 }
594
595 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
596     let snippet = context.snippet(mac.span);
597     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
598     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
599     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
600
601     if paren_pos < bracket_pos && paren_pos < brace_pos {
602         MacroStyle::Parens
603     } else if bracket_pos < brace_pos {
604         MacroStyle::Brackets
605     } else {
606         MacroStyle::Braces
607     }
608 }
609
610 /// Indent each line according to the specified `indent`.
611 /// e.g.
612 /// ```rust
613 /// foo!{
614 /// x,
615 /// y,
616 /// foo(
617 ///     a,
618 ///     b,
619 ///     c,
620 /// ),
621 /// }
622 /// ```
623 /// will become
624 /// ```rust
625 /// foo!{
626 ///     x,
627 ///     y,
628 ///     foo(
629 ///         a,
630 ///         b,
631 ///         c,
632 ///     ),
633 /// }
634 /// ```
635 fn indent_macro_snippet(
636     context: &RewriteContext,
637     macro_str: &str,
638     indent: Indent,
639 ) -> Option<String> {
640     let mut lines = macro_str.lines();
641     let first_line = lines.next().map(|s| s.trim_right())?;
642     let mut trimmed_lines = Vec::with_capacity(16);
643
644     let min_prefix_space_width = lines
645         .filter_map(|line| {
646             let prefix_space_width = if is_empty_line(line) {
647                 None
648             } else {
649                 Some(get_prefix_space_width(context, line))
650             };
651             trimmed_lines.push((line.trim(), prefix_space_width));
652             prefix_space_width
653         })
654         .min()?;
655
656     Some(
657         String::from(first_line) + "\n"
658             + &trimmed_lines
659                 .iter()
660                 .map(|&(line, prefix_space_width)| match prefix_space_width {
661                     Some(original_indent_width) => {
662                         let new_indent_width = indent.width()
663                             + original_indent_width
664                                 .checked_sub(min_prefix_space_width)
665                                 .unwrap_or(0);
666                         let new_indent = Indent::from_width(context.config, new_indent_width);
667                         format!("{}{}", new_indent.to_string(context.config), line.trim())
668                     }
669                     None => String::new(),
670                 })
671                 .collect::<Vec<_>>()
672                 .join("\n"),
673     )
674 }
675
676 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
677     let mut width = 0;
678     for c in s.chars() {
679         match c {
680             ' ' => width += 1,
681             '\t' => width += context.config.tab_spaces(),
682             _ => return width,
683         }
684     }
685     width
686 }
687
688 fn is_empty_line(s: &str) -> bool {
689     s.is_empty() || s.chars().all(char::is_whitespace)
690 }
691
692 // A very simple parser that just parses a macros 2.0 definition into its branches.
693 // Currently we do not attempt to parse any further than that.
694 #[derive(new)]
695 struct MacroParser {
696     toks: Cursor,
697 }
698
699 impl MacroParser {
700     // (`(` ... `)` `=>` `{` ... `}`)*
701     fn parse(&mut self) -> Option<Macro> {
702         let mut branches = vec![];
703         while self.toks.look_ahead(1).is_some() {
704             branches.push(self.parse_branch()?);
705         }
706
707         Some(Macro { branches })
708     }
709
710     // `(` ... `)` `=>` `{` ... `}`
711     fn parse_branch(&mut self) -> Option<MacroBranch> {
712         let tok = self.toks.next()?;
713         let (lo, args_paren_kind) = match tok {
714             TokenTree::Token(..) => return None,
715             TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
716         };
717         let args = tok.joint().into();
718         match self.toks.next()? {
719             TokenTree::Token(_, Token::FatArrow) => {}
720             _ => return None,
721         }
722         let (mut hi, body) = match self.toks.next()? {
723             TokenTree::Token(..) => return None,
724             TokenTree::Delimited(sp, _) => {
725                 let data = sp.data();
726                 (
727                     data.hi,
728                     Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
729                 )
730             }
731         };
732         if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
733             self.toks.next();
734             hi = sp.hi();
735         }
736         Some(MacroBranch {
737             span: mk_sp(lo, hi),
738             args_paren_kind,
739             args,
740             body,
741         })
742     }
743 }
744
745 // A parsed macros 2.0 macro definition.
746 struct Macro {
747     branches: Vec<MacroBranch>,
748 }
749
750 // FIXME: it would be more efficient to use references to the token streams
751 // rather than clone them, if we can make the borrowing work out.
752 struct MacroBranch {
753     span: Span,
754     args_paren_kind: DelimToken,
755     args: ThinTokenStream,
756     body: Span,
757 }
758
759 impl MacroBranch {
760     fn rewrite(
761         &self,
762         context: &RewriteContext,
763         shape: Shape,
764         multi_branch_style: bool,
765     ) -> Option<String> {
766         // Only attempt to format function-like macros.
767         if self.args_paren_kind != DelimToken::Paren {
768             // FIXME(#1539): implement for non-sugared macros.
769             return None;
770         }
771
772         // 5 = " => {"
773         let mut result = format_macro_args(self.args.clone(), shape.sub_width(5)?)?;
774
775         if multi_branch_style {
776             result += " =>";
777         }
778
779         // The macro body is the most interesting part. It might end up as various
780         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
781         // parsed as regular Rust code (and note that these can be escaped using
782         // `$$`). We'll try and format like an AST node, but we'll substitute
783         // variables for new names with the same length first.
784
785         let old_body = context.snippet(self.body).trim();
786         let (body_str, substs) = replace_names(old_body)?;
787
788         let mut config = context.config.clone();
789         config.set().hide_parse_errors(true);
790
791         result += " {";
792
793         let has_block_body = old_body.starts_with('{');
794
795         let body_indent = if has_block_body {
796             shape.indent
797         } else {
798             // We'll hack the indent below, take this into account when formatting,
799             let body_indent = shape.indent.block_indent(&config);
800             let new_width = config.max_width() - body_indent.width();
801             config.set().max_width(new_width);
802             body_indent
803         };
804
805         // First try to format as items, then as statements.
806         let new_body = match ::format_snippet(&body_str, &config) {
807             Some(new_body) => new_body,
808             None => match ::format_code_block(&body_str, &config) {
809                 Some(new_body) => new_body,
810                 None => return None,
811             },
812         };
813
814         // Indent the body since it is in a block.
815         let indent_str = body_indent.to_string(&config);
816         let mut new_body = new_body
817             .trim_right()
818             .lines()
819             .fold(String::new(), |mut s, l| {
820                 if !l.is_empty() {
821                     s += &indent_str;
822                 }
823                 s + l + "\n"
824             });
825
826         // Undo our replacement of macro variables.
827         // FIXME: this could be *much* more efficient.
828         for (old, new) in &substs {
829             if old_body.find(new).is_some() {
830                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
831                 return None;
832             }
833             new_body = new_body.replace(new, old);
834         }
835
836         if has_block_body {
837             result += new_body.trim();
838         } else if !new_body.is_empty() {
839             result += "\n";
840             result += &new_body;
841             result += &shape.indent.to_string(&config);
842         }
843
844         result += "}";
845
846         Some(result)
847     }
848 }
849
850 #[cfg(test)]
851 mod test {
852     use super::*;
853     use syntax::parse::{parse_stream_from_source_str, ParseSess};
854     use syntax::codemap::{FileName, FilePathMapping};
855
856     fn format_macro_args_str(s: &str) -> String {
857         let input = parse_stream_from_source_str(
858             FileName::Custom("stdin".to_owned()),
859             s.to_owned(),
860             &ParseSess::new(FilePathMapping::empty()),
861             None,
862         );
863         let shape = Shape {
864             width: 100,
865             indent: Indent::empty(),
866             offset: 0,
867         };
868         format_macro_args(input.into(), shape).unwrap()
869     }
870
871     #[test]
872     fn test_format_macro_args() {
873         assert_eq!(format_macro_args_str(""), "".to_owned());
874         assert_eq!(format_macro_args_str("$ x : ident"), "$x: ident".to_owned());
875         assert_eq!(
876             format_macro_args_str("$ m1 : ident , $ m2 : ident , $ x : ident"),
877             "$m1: ident, $m2: ident, $x: ident".to_owned()
878         );
879         assert_eq!(
880             format_macro_args_str("$($beginning:ident),*;$middle:ident;$($end:ident),*"),
881             "$($beginning: ident),*; $middle: ident; $($end: ident),*".to_owned()
882         );
883         assert_eq!(
884             format_macro_args_str(
885                 "$ name : ident ( $ ( $ dol : tt $ var : ident ) * ) $ ( $ body : tt ) *"
886             ),
887             "$name: ident($($dol: tt $var: ident)*) $($body: tt)*".to_owned()
888         );
889     }
890 }