]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #2775 from topecongiro/macro-def-with-complex-macro
[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::codemap::{BytePos, Span};
26 use syntax::parse::new_parser_from_tts;
27 use syntax::parse::parser::Parser;
28 use syntax::parse::token::{BinOpToken, DelimToken, Token};
29 use syntax::print::pprust;
30 use syntax::symbol;
31 use syntax::tokenstream::{Cursor, ThinTokenStream, TokenStream, TokenTree};
32 use syntax::util::ThinVec;
33 use syntax::{ast, ptr};
34
35 use codemap::SpanUtils;
36 use comment::{
37     contains_comment, remove_trailing_white_spaces, CharClasses, FindUncommented, FullCodeCharKind,
38     LineClasses,
39 };
40 use expr::rewrite_array;
41 use lists::{itemize_list, write_list, ListFormatting};
42 use overflow;
43 use rewrite::{Rewrite, RewriteContext};
44 use shape::{Indent, Shape};
45 use spanned::Spanned;
46 use utils::{format_visibility, mk_sp, wrap_str};
47
48 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
49
50 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
51 pub enum MacroPosition {
52     Item,
53     Statement,
54     Expression,
55     Pat,
56 }
57
58 #[derive(Debug)]
59 pub enum MacroArg {
60     Expr(ptr::P<ast::Expr>),
61     Ty(ptr::P<ast::Ty>),
62     Pat(ptr::P<ast::Pat>),
63     Item(ptr::P<ast::Item>),
64 }
65
66 impl Rewrite for ast::Item {
67     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
68         let mut visitor = ::visitor::FmtVisitor::from_context(context);
69         visitor.block_indent = shape.indent;
70         visitor.last_pos = self.span().lo();
71         visitor.visit_item(self);
72         Some(visitor.buffer)
73     }
74 }
75
76 impl Rewrite for MacroArg {
77     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
78         match *self {
79             MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
80             MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
81             MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
82             MacroArg::Item(ref item) => item.rewrite(context, shape),
83         }
84     }
85 }
86
87 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
88     macro_rules! parse_macro_arg {
89         ($macro_arg:ident, $parser:ident, $f:expr) => {
90             let mut cloned_parser = (*parser).clone();
91             match cloned_parser.$parser() {
92                 Ok(x) => {
93                     if parser.sess.span_diagnostic.has_errors() {
94                         parser.sess.span_diagnostic.reset_err_count();
95                     } else {
96                         // Parsing succeeded.
97                         *parser = cloned_parser;
98                         return Some(MacroArg::$macro_arg($f(x)?));
99                     }
100                 }
101                 Err(mut e) => {
102                     e.cancel();
103                     parser.sess.span_diagnostic.reset_err_count();
104                 }
105             }
106         };
107     }
108
109     parse_macro_arg!(Expr, parse_expr, |x: ptr::P<ast::Expr>| Some(x));
110     parse_macro_arg!(Ty, parse_ty, |x: ptr::P<ast::Ty>| Some(x));
111     parse_macro_arg!(Pat, parse_pat, |x: ptr::P<ast::Pat>| Some(x));
112     // `parse_item` returns `Option<ptr::P<ast::Item>>`.
113     parse_macro_arg!(Item, parse_item, |x: Option<ptr::P<ast::Item>>| x);
114
115     None
116 }
117
118 /// Rewrite macro name without using pretty-printer if possible.
119 fn rewrite_macro_name(path: &ast::Path, extra_ident: Option<ast::Ident>) -> String {
120     let name = if path.segments.len() == 1 {
121         // Avoid using pretty-printer in the common case.
122         format!("{}!", path.segments[0].ident)
123     } else {
124         format!("{}!", path)
125     };
126     match extra_ident {
127         Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
128         _ => name,
129     }
130 }
131
132 // Use this on failing to format the macro call.
133 fn return_original_snippet_with_failure_marked(
134     context: &RewriteContext,
135     span: Span,
136 ) -> Option<String> {
137     context.macro_rewrite_failure.replace(true);
138     Some(context.snippet(span).to_owned())
139 }
140
141 pub fn rewrite_macro(
142     mac: &ast::Mac,
143     extra_ident: Option<ast::Ident>,
144     context: &RewriteContext,
145     shape: Shape,
146     position: MacroPosition,
147 ) -> Option<String> {
148     context.inside_macro.replace(true);
149     let result = rewrite_macro_inner(mac, extra_ident, context, shape, position);
150     if result.is_none() {
151         context.macro_rewrite_failure.replace(true);
152     }
153     context.inside_macro.replace(false);
154     result
155 }
156
157 pub fn rewrite_macro_inner(
158     mac: &ast::Mac,
159     extra_ident: Option<ast::Ident>,
160     context: &RewriteContext,
161     shape: Shape,
162     position: MacroPosition,
163 ) -> Option<String> {
164     if context.config.use_try_shorthand() {
165         if let Some(expr) = convert_try_mac(mac, context) {
166             context.inside_macro.replace(false);
167             return expr.rewrite(context, shape);
168         }
169     }
170
171     let original_style = macro_style(mac, context);
172
173     let macro_name = rewrite_macro_name(&mac.node.path, extra_ident);
174
175     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
176         DelimToken::Bracket
177     } else {
178         original_style
179     };
180
181     let ts: TokenStream = mac.node.stream();
182     let has_comment = contains_comment(context.snippet(mac.span));
183     if ts.is_empty() && !has_comment {
184         return match style {
185             DelimToken::Paren if position == MacroPosition::Item => {
186                 Some(format!("{}();", macro_name))
187             }
188             DelimToken::Paren => Some(format!("{}()", macro_name)),
189             DelimToken::Bracket => Some(format!("{}[]", macro_name)),
190             DelimToken::Brace => Some(format!("{}{{}}", macro_name)),
191             _ => unreachable!(),
192         };
193     }
194     // Format well-known macros which cannot be parsed as a valid AST.
195     // TODO: Maybe add more macros?
196     if macro_name == "lazy_static!" && !has_comment {
197         if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
198             return success;
199         }
200     }
201
202     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
203     let mut arg_vec = Vec::new();
204     let mut vec_with_semi = false;
205     let mut trailing_comma = false;
206
207     if DelimToken::Brace != style {
208         loop {
209             match parse_macro_arg(&mut parser) {
210                 Some(arg) => arg_vec.push(arg),
211                 None => return return_original_snippet_with_failure_marked(context, mac.span),
212             }
213
214             match parser.token {
215                 Token::Eof => break,
216                 Token::Comma => (),
217                 Token::Semi => {
218                     // Try to parse `vec![expr; expr]`
219                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
220                         parser.bump();
221                         if parser.token != Token::Eof {
222                             match parse_macro_arg(&mut parser) {
223                                 Some(arg) => {
224                                     arg_vec.push(arg);
225                                     parser.bump();
226                                     if parser.token == Token::Eof && arg_vec.len() == 2 {
227                                         vec_with_semi = true;
228                                         break;
229                                     }
230                                 }
231                                 None => {
232                                     return return_original_snippet_with_failure_marked(
233                                         context, mac.span,
234                                     )
235                                 }
236                             }
237                         }
238                     }
239                     return return_original_snippet_with_failure_marked(context, mac.span);
240                 }
241                 _ => return return_original_snippet_with_failure_marked(context, mac.span),
242             }
243
244             parser.bump();
245
246             if parser.token == Token::Eof {
247                 trailing_comma = true;
248                 break;
249             }
250         }
251     }
252
253     match style {
254         DelimToken::Paren => {
255             // Format macro invocation as function call, preserve the trailing
256             // comma because not all macros support them.
257             overflow::rewrite_with_parens(
258                 context,
259                 &macro_name,
260                 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>(),
261                 shape,
262                 mac.span,
263                 context.config.width_heuristics().fn_call_width,
264                 if trailing_comma {
265                     Some(SeparatorTactic::Always)
266                 } else {
267                     Some(SeparatorTactic::Never)
268                 },
269             ).map(|rw| match position {
270                 MacroPosition::Item => format!("{};", rw),
271                 _ => rw,
272             })
273         }
274         DelimToken::Bracket => {
275             // Handle special case: `vec![expr; expr]`
276             if vec_with_semi {
277                 let mac_shape = shape.offset_left(macro_name.len())?;
278                 // 8 = `vec![]` + `; `
279                 let total_overhead = 8;
280                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
281                 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
282                 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
283                 if !lhs.contains('\n')
284                     && !rhs.contains('\n')
285                     && lhs.len() + rhs.len() + total_overhead <= shape.width
286                 {
287                     Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
288                 } else {
289                     Some(format!(
290                         "{}[{}{};{}{}{}]",
291                         macro_name,
292                         nested_shape.indent.to_string_with_newline(context.config),
293                         lhs,
294                         nested_shape.indent.to_string_with_newline(context.config),
295                         rhs,
296                         shape.indent.to_string_with_newline(context.config),
297                     ))
298                 }
299             } else {
300                 // If we are rewriting `vec!` macro or other special macros,
301                 // then we can rewrite this as an usual array literal.
302                 // Otherwise, we must preserve the original existence of trailing comma.
303                 let macro_name = &macro_name.as_str();
304                 let mut force_trailing_comma = if trailing_comma {
305                     Some(SeparatorTactic::Always)
306                 } else {
307                     Some(SeparatorTactic::Never)
308                 };
309                 if FORCED_BRACKET_MACROS.contains(macro_name) {
310                     context.inside_macro.replace(false);
311                     if context.use_block_indent() {
312                         force_trailing_comma = Some(SeparatorTactic::Vertical);
313                     };
314                 }
315                 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
316                 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>();
317                 let rewrite = rewrite_array(
318                     macro_name,
319                     arg_vec,
320                     mac.span,
321                     context,
322                     shape,
323                     force_trailing_comma,
324                     Some(original_style),
325                 )?;
326                 let comma = match position {
327                     MacroPosition::Item => ";",
328                     _ => "",
329                 };
330
331                 Some(format!("{}{}", rewrite, comma))
332             }
333         }
334         DelimToken::Brace => {
335             // Skip macro invocations with braces, for now.
336             indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
337         }
338         _ => unreachable!(),
339     }
340 }
341
342 pub fn rewrite_macro_def(
343     context: &RewriteContext,
344     shape: Shape,
345     indent: Indent,
346     def: &ast::MacroDef,
347     ident: ast::Ident,
348     vis: &ast::Visibility,
349     span: Span,
350 ) -> Option<String> {
351     let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
352     if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
353         return snippet;
354     }
355
356     let mut parser = MacroParser::new(def.stream().into_trees());
357     let parsed_def = match parser.parse() {
358         Some(def) => def,
359         None => return snippet,
360     };
361
362     let mut result = if def.legacy {
363         String::from("macro_rules!")
364     } else {
365         format!("{}macro", format_visibility(vis))
366     };
367
368     result += " ";
369     result += &ident.name.as_str();
370
371     let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
372
373     let arm_shape = if multi_branch_style {
374         shape
375             .block_indent(context.config.tab_spaces())
376             .with_max_width(context.config)
377     } else {
378         shape
379     };
380
381     let branch_items = itemize_list(
382         context.snippet_provider,
383         parsed_def.branches.iter(),
384         "}",
385         ";",
386         |branch| branch.span.lo(),
387         |branch| branch.span.hi(),
388         |branch| branch.rewrite(context, arm_shape, multi_branch_style),
389         context.snippet_provider.span_after(span, "{"),
390         span.hi(),
391         false,
392     ).collect::<Vec<_>>();
393
394     let fmt = ListFormatting {
395         tactic: DefinitiveListTactic::Vertical,
396         separator: if def.legacy { ";" } else { "" },
397         trailing_separator: SeparatorTactic::Always,
398         separator_place: SeparatorPlace::Back,
399         shape: arm_shape,
400         ends_with_newline: true,
401         preserve_newline: true,
402         config: context.config,
403     };
404
405     if multi_branch_style {
406         result += " {";
407         result += &arm_shape.indent.to_string_with_newline(context.config);
408     }
409
410     result += write_list(&branch_items, &fmt)?.as_str();
411
412     if multi_branch_style {
413         result += &indent.to_string_with_newline(context.config);
414         result += "}";
415     }
416
417     Some(result)
418 }
419
420 fn register_metavariable(
421     map: &mut HashMap<String, String>,
422     result: &mut String,
423     name: &str,
424     dollar_count: usize,
425 ) {
426     let mut new_name = String::new();
427     let mut old_name = String::new();
428
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(&name);
436     old_name.push_str(&name);
437
438     result.push_str(&new_name);
439     map.insert(old_name, new_name);
440 }
441
442 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
443 // aren't causing problems.
444 // This should also work for escaped `$` variables, where we leave earlier `$`s.
445 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
446     // Each substitution will require five or six extra bytes.
447     let mut result = String::with_capacity(input.len() + 64);
448     let mut substs = HashMap::new();
449     let mut dollar_count = 0;
450     let mut cur_name = String::new();
451
452     for (kind, c) in CharClasses::new(input.chars()) {
453         if kind != FullCodeCharKind::Normal {
454             result.push(c);
455         } else if c == '$' {
456             dollar_count += 1;
457         } else if dollar_count == 0 {
458             result.push(c);
459         } else if !c.is_alphanumeric() && !cur_name.is_empty() {
460             // Terminates a name following one or more dollars.
461             register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
462
463             result.push(c);
464             dollar_count = 0;
465             cur_name.clear();
466         } else if c == '(' && cur_name.is_empty() {
467             // FIXME: Support macro def with repeat.
468             return None;
469         } else if c.is_alphanumeric() || c == '_' {
470             cur_name.push(c);
471         }
472     }
473
474     if !cur_name.is_empty() {
475         register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
476     }
477
478     debug!("replace_names `{}` {:?}", result, substs);
479
480     Some((result, substs))
481 }
482
483 #[derive(Debug, Clone)]
484 enum MacroArgKind {
485     /// e.g. `$x: expr`.
486     MetaVariable(ast::Ident, String),
487     /// e.g. `$($foo: expr),*`
488     Repeat(
489         /// `()`, `[]` or `{}`.
490         DelimToken,
491         /// Inner arguments inside delimiters.
492         Vec<ParsedMacroArg>,
493         /// Something after the closing delimiter and the repeat token, if available.
494         Option<Box<ParsedMacroArg>>,
495         /// The repeat token. This could be one of `*`, `+` or `?`.
496         Token,
497     ),
498     /// e.g. `[derive(Debug)]`
499     Delimited(DelimToken, Vec<ParsedMacroArg>),
500     /// A possible separator. e.g. `,` or `;`.
501     Separator(String, String),
502     /// Other random stuff that does not fit to other kinds.
503     /// e.g. `== foo` in `($x: expr == foo)`.
504     Other(String, String),
505 }
506
507 fn delim_token_to_str(
508     context: &RewriteContext,
509     delim_token: &DelimToken,
510     shape: Shape,
511     use_multiple_lines: bool,
512     inner_is_empty: bool,
513 ) -> (String, String) {
514     let (lhs, rhs) = match *delim_token {
515         DelimToken::Paren => ("(", ")"),
516         DelimToken::Bracket => ("[", "]"),
517         DelimToken::Brace => {
518             if inner_is_empty || use_multiple_lines {
519                 ("{", "}")
520             } else {
521                 ("{ ", " }")
522             }
523         }
524         DelimToken::NoDelim => ("", ""),
525     };
526     if use_multiple_lines {
527         let indent_str = shape.indent.to_string_with_newline(context.config);
528         let nested_indent_str = shape
529             .indent
530             .block_indent(context.config)
531             .to_string_with_newline(context.config);
532         (
533             format!("{}{}", lhs, nested_indent_str),
534             format!("{}{}", indent_str, rhs),
535         )
536     } else {
537         (lhs.to_owned(), rhs.to_owned())
538     }
539 }
540
541 impl MacroArgKind {
542     fn starts_with_brace(&self) -> bool {
543         match *self {
544             MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
545             | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
546             _ => false,
547         }
548     }
549
550     fn starts_with_dollar(&self) -> bool {
551         match *self {
552             MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
553             _ => false,
554         }
555     }
556
557     fn ends_with_space(&self) -> bool {
558         match *self {
559             MacroArgKind::Separator(..) => true,
560             _ => false,
561         }
562     }
563
564     fn has_meta_var(&self) -> bool {
565         match *self {
566             MacroArgKind::MetaVariable(..) => true,
567             MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
568             _ => false,
569         }
570     }
571
572     fn rewrite(
573         &self,
574         context: &RewriteContext,
575         shape: Shape,
576         use_multiple_lines: bool,
577     ) -> Option<String> {
578         let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
579             let inner = wrap_macro_args(context, args, shape)?;
580             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
581             if lhs.len() + inner.len() + rhs.len() <= shape.width {
582                 return Some((lhs, inner, rhs));
583             }
584
585             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
586             let nested_shape = shape
587                 .block_indent(context.config.tab_spaces())
588                 .with_max_width(context.config);
589             let inner = wrap_macro_args(context, args, nested_shape)?;
590             Some((lhs, inner, rhs))
591         };
592
593         match *self {
594             MacroArgKind::MetaVariable(ty, ref name) => {
595                 Some(format!("${}:{}", name, ty.name.as_str()))
596             }
597             MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
598                 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
599                 let another = another
600                     .as_ref()
601                     .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
602                     .unwrap_or_else(|| "".to_owned());
603                 let repeat_tok = pprust::token_to_string(tok);
604
605                 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
606             }
607             MacroArgKind::Delimited(ref delim_tok, ref args) => {
608                 rewrite_delimited_inner(delim_tok, args)
609                     .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
610             }
611             MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
612             MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
613         }
614     }
615 }
616
617 #[derive(Debug, Clone)]
618 struct ParsedMacroArg {
619     kind: MacroArgKind,
620     span: Span,
621 }
622
623 impl ParsedMacroArg {
624     pub fn rewrite(
625         &self,
626         context: &RewriteContext,
627         shape: Shape,
628         use_multiple_lines: bool,
629     ) -> Option<String> {
630         self.kind.rewrite(context, shape, use_multiple_lines)
631     }
632 }
633
634 /// Parses macro arguments on macro def.
635 struct MacroArgParser {
636     /// Holds either a name of the next metavariable, a separator or a junk.
637     buf: String,
638     /// The start position on the current buffer.
639     lo: BytePos,
640     /// The first token of the current buffer.
641     start_tok: Token,
642     /// Set to true if we are parsing a metavariable or a repeat.
643     is_meta_var: bool,
644     /// The position of the last token.
645     hi: BytePos,
646     /// The last token parsed.
647     last_tok: Token,
648     /// Holds the parsed arguments.
649     result: Vec<ParsedMacroArg>,
650 }
651
652 fn last_tok(tt: &TokenTree) -> Token {
653     match *tt {
654         TokenTree::Token(_, ref t) => t.clone(),
655         TokenTree::Delimited(_, ref d) => d.close_token(),
656     }
657 }
658
659 impl MacroArgParser {
660     pub fn new() -> MacroArgParser {
661         MacroArgParser {
662             lo: BytePos(0),
663             hi: BytePos(0),
664             buf: String::new(),
665             is_meta_var: false,
666             last_tok: Token::Eof,
667             start_tok: Token::Eof,
668             result: vec![],
669         }
670     }
671
672     fn set_last_tok(&mut self, tok: &TokenTree) {
673         self.hi = tok.span().hi();
674         self.last_tok = last_tok(tok);
675     }
676
677     fn add_separator(&mut self) {
678         let prefix = if self.need_space_prefix() {
679             " ".to_owned()
680         } else {
681             "".to_owned()
682         };
683         self.result.push(ParsedMacroArg {
684             kind: MacroArgKind::Separator(self.buf.clone(), prefix),
685             span: mk_sp(self.lo, self.hi),
686         });
687         self.buf.clear();
688     }
689
690     fn add_other(&mut self) {
691         let prefix = if self.need_space_prefix() {
692             " ".to_owned()
693         } else {
694             "".to_owned()
695         };
696         self.result.push(ParsedMacroArg {
697             kind: MacroArgKind::Other(self.buf.clone(), prefix),
698             span: mk_sp(self.lo, self.hi),
699         });
700         self.buf.clear();
701     }
702
703     fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
704         match iter.next() {
705             Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
706                 self.result.push(ParsedMacroArg {
707                     kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
708                     span: mk_sp(self.lo, sp.hi()),
709                 });
710
711                 self.buf.clear();
712                 self.is_meta_var = false;
713                 Some(())
714             }
715             _ => None,
716         }
717     }
718
719     fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
720         self.result.push(ParsedMacroArg {
721             kind: MacroArgKind::Delimited(delim, inner),
722             span,
723         });
724     }
725
726     // $($foo: expr),?
727     fn add_repeat(
728         &mut self,
729         inner: Vec<ParsedMacroArg>,
730         delim: DelimToken,
731         iter: &mut Cursor,
732         span: Span,
733     ) -> Option<()> {
734         let mut buffer = String::new();
735         let mut first = false;
736         let mut lo = span.lo();
737         let mut hi = span.hi();
738
739         // Parse '*', '+' or '?.
740         for ref tok in iter {
741             self.set_last_tok(tok);
742             if first {
743                 first = false;
744                 lo = tok.span().lo();
745             }
746
747             match tok {
748                 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
749                 | TokenTree::Token(_, Token::Question)
750                 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
751                     break;
752                 }
753                 TokenTree::Token(sp, ref t) => {
754                     buffer.push_str(&pprust::token_to_string(t));
755                     hi = sp.hi();
756                 }
757                 _ => return None,
758             }
759         }
760
761         // There could be some random stuff between ')' and '*', '+' or '?'.
762         let another = if buffer.trim().is_empty() {
763             None
764         } else {
765             Some(Box::new(ParsedMacroArg {
766                 kind: MacroArgKind::Other(buffer, "".to_owned()),
767                 span: mk_sp(lo, hi),
768             }))
769         };
770
771         self.result.push(ParsedMacroArg {
772             kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
773             span: mk_sp(self.lo, self.hi),
774         });
775         Some(())
776     }
777
778     fn update_buffer(&mut self, lo: BytePos, t: &Token) {
779         if self.buf.is_empty() {
780             self.lo = lo;
781             self.start_tok = t.clone();
782         } else {
783             let needs_space = match next_space(&self.last_tok) {
784                 SpaceState::Ident => ident_like(t),
785                 SpaceState::Punctuation => !ident_like(t),
786                 SpaceState::Always => true,
787                 SpaceState::Never => false,
788             };
789             if force_space_before(t) || needs_space {
790                 self.buf.push(' ');
791             }
792         }
793
794         self.buf.push_str(&pprust::token_to_string(t));
795     }
796
797     fn need_space_prefix(&self) -> bool {
798         if self.result.is_empty() {
799             return false;
800         }
801
802         let last_arg = self.result.last().unwrap();
803         if let MacroArgKind::MetaVariable(..) = last_arg.kind {
804             if ident_like(&self.start_tok) {
805                 return true;
806             }
807             if self.start_tok == Token::Colon {
808                 return true;
809             }
810         }
811
812         if force_space_before(&self.start_tok) {
813             return true;
814         }
815
816         false
817     }
818
819     /// Returns a collection of parsed macro def's arguments.
820     pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
821         let mut iter = (tokens.into(): TokenStream).trees();
822
823         while let Some(ref tok) = iter.next() {
824             match tok {
825                 TokenTree::Token(sp, Token::Dollar) => {
826                     // We always want to add a separator before meta variables.
827                     if !self.buf.is_empty() {
828                         self.add_separator();
829                     }
830
831                     // Start keeping the name of this metavariable in the buffer.
832                     self.is_meta_var = true;
833                     self.lo = sp.lo();
834                     self.start_tok = Token::Dollar;
835                 }
836                 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
837                     self.add_meta_variable(&mut iter)?;
838                 }
839                 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
840                 TokenTree::Delimited(sp, delimited) => {
841                     if !self.buf.is_empty() {
842                         if next_space(&self.last_tok) == SpaceState::Always {
843                             self.add_separator();
844                         } else {
845                             self.add_other();
846                         }
847                     }
848
849                     // Parse the stuff inside delimiters.
850                     let mut parser = MacroArgParser::new();
851                     parser.lo = sp.lo();
852                     let delimited_arg = parser.parse(delimited.tts.clone())?;
853
854                     if self.is_meta_var {
855                         self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp)?;
856                         self.is_meta_var = false;
857                     } else {
858                         self.add_delimited(delimited_arg, delimited.delim, *sp);
859                     }
860                 }
861             }
862
863             self.set_last_tok(tok);
864         }
865
866         // We are left with some stuff in the buffer. Since there is nothing
867         // left to separate, add this as `Other`.
868         if !self.buf.is_empty() {
869             self.add_other();
870         }
871
872         Some(self.result)
873     }
874 }
875
876 fn wrap_macro_args(
877     context: &RewriteContext,
878     args: &[ParsedMacroArg],
879     shape: Shape,
880 ) -> Option<String> {
881     wrap_macro_args_inner(context, args, shape, false)
882         .or_else(|| wrap_macro_args_inner(context, args, shape, true))
883 }
884
885 fn wrap_macro_args_inner(
886     context: &RewriteContext,
887     args: &[ParsedMacroArg],
888     shape: Shape,
889     use_multiple_lines: bool,
890 ) -> Option<String> {
891     let mut result = String::with_capacity(128);
892     let mut iter = args.iter().peekable();
893     let indent_str = shape.indent.to_string_with_newline(context.config);
894
895     while let Some(ref arg) = iter.next() {
896         result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
897
898         if use_multiple_lines
899             && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
900         {
901             if arg.kind.ends_with_space() {
902                 result.pop();
903             }
904             result.push_str(&indent_str);
905         } else if let Some(ref next_arg) = iter.peek() {
906             let space_before_dollar =
907                 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
908             let space_before_brace = next_arg.kind.starts_with_brace();
909             if space_before_dollar || space_before_brace {
910                 result.push(' ');
911             }
912         }
913     }
914
915     if !use_multiple_lines && result.len() >= shape.width {
916         None
917     } else {
918         Some(result)
919     }
920 }
921
922 // This is a bit sketchy. The token rules probably need tweaking, but it works
923 // for some common cases. I hope the basic logic is sufficient. Note that the
924 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
925 // and `(`/`)` have special meaning.
926 //
927 // We always try and format on one line.
928 // FIXME: Use multi-line when every thing does not fit on one line.
929 fn format_macro_args(
930     context: &RewriteContext,
931     toks: ThinTokenStream,
932     shape: Shape,
933 ) -> Option<String> {
934     let parsed_args = MacroArgParser::new().parse(toks)?;
935     wrap_macro_args(context, &parsed_args, shape)
936 }
937
938 // We should insert a space if the next token is a:
939 #[derive(Copy, Clone, PartialEq)]
940 enum SpaceState {
941     Never,
942     Punctuation,
943     Ident, // Or ident/literal-like thing.
944     Always,
945 }
946
947 fn force_space_before(tok: &Token) -> bool {
948     debug!("tok: force_space_before {:?}", tok);
949
950     match *tok {
951         Token::Eq
952         | Token::Lt
953         | Token::Le
954         | Token::EqEq
955         | Token::Ne
956         | Token::Ge
957         | Token::Gt
958         | Token::AndAnd
959         | Token::OrOr
960         | Token::Not
961         | Token::Tilde
962         | Token::BinOpEq(_)
963         | Token::At
964         | Token::RArrow
965         | Token::LArrow
966         | Token::FatArrow
967         | Token::BinOp(_)
968         | Token::Pound
969         | Token::Dollar => true,
970         _ => false,
971     }
972 }
973
974 fn ident_like(tok: &Token) -> bool {
975     match *tok {
976         Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
977         _ => false,
978     }
979 }
980
981 fn next_space(tok: &Token) -> SpaceState {
982     debug!("next_space: {:?}", tok);
983
984     match *tok {
985         Token::Not
986         | Token::BinOp(BinOpToken::And)
987         | Token::Tilde
988         | Token::At
989         | Token::Comma
990         | Token::Dot
991         | Token::DotDot
992         | Token::DotDotDot
993         | Token::DotDotEq
994         | Token::DotEq
995         | Token::Question => SpaceState::Punctuation,
996
997         Token::ModSep
998         | Token::Pound
999         | Token::Dollar
1000         | Token::OpenDelim(_)
1001         | Token::CloseDelim(_)
1002         | Token::Whitespace => SpaceState::Never,
1003
1004         Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1005
1006         _ => SpaceState::Always,
1007     }
1008 }
1009
1010 /// Tries to convert a macro use into a short hand try expression. Returns None
1011 /// when the macro is not an instance of try! (or parsing the inner expression
1012 /// failed).
1013 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1014     if &format!("{}", mac.node.path) == "try" {
1015         let ts: TokenStream = mac.node.tts.clone().into();
1016         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1017
1018         Some(ast::Expr {
1019             id: ast::NodeId::new(0), // dummy value
1020             node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1021             span: mac.span, // incorrect span, but shouldn't matter too much
1022             attrs: ThinVec::new(),
1023         })
1024     } else {
1025         None
1026     }
1027 }
1028
1029 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1030     let snippet = context.snippet(mac.span);
1031     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1032     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1033     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1034
1035     if paren_pos < bracket_pos && paren_pos < brace_pos {
1036         DelimToken::Paren
1037     } else if bracket_pos < brace_pos {
1038         DelimToken::Bracket
1039     } else {
1040         DelimToken::Brace
1041     }
1042 }
1043
1044 /// Indent each line according to the specified `indent`.
1045 /// e.g.
1046 ///
1047 /// ```rust,ignore
1048 /// foo!{
1049 /// x,
1050 /// y,
1051 /// foo(
1052 ///     a,
1053 ///     b,
1054 ///     c,
1055 /// ),
1056 /// }
1057 /// ```
1058 ///
1059 /// will become
1060 ///
1061 /// ```rust,ignore
1062 /// foo!{
1063 ///     x,
1064 ///     y,
1065 ///     foo(
1066 ///         a,
1067 ///         b,
1068 ///         c,
1069 ///     ),
1070 /// }
1071 /// ```
1072 fn indent_macro_snippet(
1073     context: &RewriteContext,
1074     macro_str: &str,
1075     indent: Indent,
1076 ) -> Option<String> {
1077     let mut lines = LineClasses::new(macro_str);
1078     let first_line = lines.next().map(|(_, s)| s.trim_right().to_owned())?;
1079     let mut trimmed_lines = Vec::with_capacity(16);
1080
1081     let mut veto_trim = false;
1082     let min_prefix_space_width = lines
1083         .filter_map(|(kind, line)| {
1084             let mut trimmed = true;
1085             let prefix_space_width = if is_empty_line(&line) {
1086                 None
1087             } else {
1088                 Some(get_prefix_space_width(context, &line))
1089             };
1090             let line = if veto_trim || (kind.is_string() && !line.ends_with('\\')) {
1091                 veto_trim = kind.is_string() && !line.ends_with('\\');
1092                 trimmed = false;
1093                 line
1094             } else {
1095                 line.trim().to_owned()
1096             };
1097             trimmed_lines.push((trimmed, line, prefix_space_width));
1098             prefix_space_width
1099         })
1100         .min()?;
1101
1102     Some(
1103         first_line + "\n"
1104             + &trimmed_lines
1105                 .iter()
1106                 .map(
1107                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
1108                         _ if !trimmed => line.to_owned(),
1109                         Some(original_indent_width) => {
1110                             let new_indent_width = indent.width()
1111                                 + original_indent_width.saturating_sub(min_prefix_space_width);
1112                             let new_indent = Indent::from_width(context.config, new_indent_width);
1113                             format!("{}{}", new_indent.to_string(context.config), line.trim())
1114                         }
1115                         None => String::new(),
1116                     },
1117                 )
1118                 .collect::<Vec<_>>()
1119                 .join("\n"),
1120     )
1121 }
1122
1123 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1124     let mut width = 0;
1125     for c in s.chars() {
1126         match c {
1127             ' ' => width += 1,
1128             '\t' => width += context.config.tab_spaces(),
1129             _ => return width,
1130         }
1131     }
1132     width
1133 }
1134
1135 fn is_empty_line(s: &str) -> bool {
1136     s.is_empty() || s.chars().all(char::is_whitespace)
1137 }
1138
1139 // A very simple parser that just parses a macros 2.0 definition into its branches.
1140 // Currently we do not attempt to parse any further than that.
1141 #[derive(new)]
1142 struct MacroParser {
1143     toks: Cursor,
1144 }
1145
1146 impl MacroParser {
1147     // (`(` ... `)` `=>` `{` ... `}`)*
1148     fn parse(&mut self) -> Option<Macro> {
1149         let mut branches = vec![];
1150         while self.toks.look_ahead(1).is_some() {
1151             branches.push(self.parse_branch()?);
1152         }
1153
1154         Some(Macro { branches })
1155     }
1156
1157     // `(` ... `)` `=>` `{` ... `}`
1158     fn parse_branch(&mut self) -> Option<MacroBranch> {
1159         let tok = self.toks.next()?;
1160         let (lo, args_paren_kind) = match tok {
1161             TokenTree::Token(..) => return None,
1162             TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1163         };
1164         let args = tok.joint().into();
1165         match self.toks.next()? {
1166             TokenTree::Token(_, Token::FatArrow) => {}
1167             _ => return None,
1168         }
1169         let (mut hi, body) = match self.toks.next()? {
1170             TokenTree::Token(..) => return None,
1171             TokenTree::Delimited(sp, _) => {
1172                 let data = sp.data();
1173                 (
1174                     data.hi,
1175                     Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1176                 )
1177             }
1178         };
1179         if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1180             self.toks.next();
1181             hi = sp.hi();
1182         }
1183         Some(MacroBranch {
1184             span: mk_sp(lo, hi),
1185             args_paren_kind,
1186             args,
1187             body,
1188         })
1189     }
1190 }
1191
1192 // A parsed macros 2.0 macro definition.
1193 struct Macro {
1194     branches: Vec<MacroBranch>,
1195 }
1196
1197 // FIXME: it would be more efficient to use references to the token streams
1198 // rather than clone them, if we can make the borrowing work out.
1199 struct MacroBranch {
1200     span: Span,
1201     args_paren_kind: DelimToken,
1202     args: ThinTokenStream,
1203     body: Span,
1204 }
1205
1206 impl MacroBranch {
1207     fn rewrite(
1208         &self,
1209         context: &RewriteContext,
1210         shape: Shape,
1211         multi_branch_style: bool,
1212     ) -> Option<String> {
1213         // Only attempt to format function-like macros.
1214         if self.args_paren_kind != DelimToken::Paren {
1215             // FIXME(#1539): implement for non-sugared macros.
1216             return None;
1217         }
1218
1219         // 5 = " => {"
1220         let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1221
1222         if multi_branch_style {
1223             result += " =>";
1224         }
1225
1226         // The macro body is the most interesting part. It might end up as various
1227         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1228         // parsed as regular Rust code (and note that these can be escaped using
1229         // `$$`). We'll try and format like an AST node, but we'll substitute
1230         // variables for new names with the same length first.
1231
1232         let old_body = context.snippet(self.body).trim();
1233         let (body_str, substs) = replace_names(old_body)?;
1234
1235         let mut config = context.config.clone();
1236         config.set().hide_parse_errors(true);
1237
1238         result += " {";
1239
1240         let has_block_body = old_body.starts_with('{');
1241
1242         let body_indent = if has_block_body {
1243             shape.indent
1244         } else {
1245             // We'll hack the indent below, take this into account when formatting,
1246             let body_indent = shape.indent.block_indent(&config);
1247             let new_width = config.max_width() - body_indent.width();
1248             config.set().max_width(new_width);
1249             body_indent
1250         };
1251
1252         // First try to format as items, then as statements.
1253         let new_body = match ::format_snippet(&body_str, &config) {
1254             Some(new_body) => new_body,
1255             None => match ::format_code_block(&body_str, &config) {
1256                 Some(new_body) => new_body,
1257                 None => return None,
1258             },
1259         };
1260         let new_body = wrap_str(new_body, config.max_width(), shape)?;
1261
1262         // Indent the body since it is in a block.
1263         let indent_str = body_indent.to_string(&config);
1264         let mut new_body = LineClasses::new(new_body.trim_right())
1265             .fold(
1266                 (String::new(), true),
1267                 |(mut s, need_indent), (kind, ref l)| {
1268                     if !l.is_empty() && need_indent {
1269                         s += &indent_str;
1270                     }
1271                     (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1272                 },
1273             )
1274             .0;
1275
1276         // Undo our replacement of macro variables.
1277         // FIXME: this could be *much* more efficient.
1278         for (old, new) in &substs {
1279             if old_body.find(new).is_some() {
1280                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1281                 return None;
1282             }
1283             new_body = new_body.replace(new, old);
1284         }
1285
1286         if has_block_body {
1287             result += new_body.trim();
1288         } else if !new_body.is_empty() {
1289             result += "\n";
1290             result += &new_body;
1291             result += &shape.indent.to_string(&config);
1292         }
1293
1294         result += "}";
1295
1296         Some(result)
1297     }
1298 }
1299
1300 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1301 ///
1302 /// # Expected syntax
1303 ///
1304 /// ```ignore
1305 /// lazy_static! {
1306 ///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1307 ///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1308 ///     ...
1309 ///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1310 /// }
1311 /// ```
1312 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1313     let mut result = String::with_capacity(1024);
1314     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1315     let nested_shape = shape
1316         .block_indent(context.config.tab_spaces())
1317         .with_max_width(context.config);
1318
1319     result.push_str("lazy_static! {");
1320     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1321
1322     macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1323         match parser.$method($($arg,)*) {
1324             Ok(val) => {
1325                 if parser.sess.span_diagnostic.has_errors() {
1326                     parser.sess.span_diagnostic.reset_err_count();
1327                     return None;
1328                 } else {
1329                     val
1330                 }
1331             }
1332             Err(mut err) => {
1333                 err.cancel();
1334                 parser.sess.span_diagnostic.reset_err_count();
1335                 return None;
1336             }
1337         }
1338     }
1339
1340     while parser.token != Token::Eof {
1341         // Parse a `lazy_static!` item.
1342         let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1343         parser.eat_keyword(symbol::keywords::Static);
1344         parser.eat_keyword(symbol::keywords::Ref);
1345         let id = parse_or!(parse_ident);
1346         parser.eat(&Token::Colon);
1347         let ty = parse_or!(parse_ty);
1348         parser.eat(&Token::Eq);
1349         let expr = parse_or!(parse_expr);
1350         parser.eat(&Token::Semi);
1351
1352         // Rewrite as a static item.
1353         let mut stmt = String::with_capacity(128);
1354         stmt.push_str(&format!(
1355             "{}static ref {}: {} =",
1356             vis,
1357             id,
1358             ty.rewrite(context, nested_shape)?
1359         ));
1360         result.push_str(&::expr::rewrite_assign_rhs(
1361             context,
1362             stmt,
1363             &*expr,
1364             nested_shape.sub_width(1)?,
1365         )?);
1366         result.push(';');
1367         if parser.token != Token::Eof {
1368             result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1369         }
1370     }
1371
1372     result.push_str(&shape.indent.to_string_with_newline(context.config));
1373     result.push('}');
1374
1375     Some(result)
1376 }