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