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