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