]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #2795 from jechase/issue-2794
[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         nested: false,
403         config: context.config,
404     };
405
406     if multi_branch_style {
407         result += " {";
408         result += &arm_shape.indent.to_string_with_newline(context.config);
409     }
410
411     result += write_list(&branch_items, &fmt)?.as_str();
412
413     if multi_branch_style {
414         result += &indent.to_string_with_newline(context.config);
415         result += "}";
416     }
417
418     Some(result)
419 }
420
421 fn register_metavariable(
422     map: &mut HashMap<String, String>,
423     result: &mut String,
424     name: &str,
425     dollar_count: usize,
426 ) {
427     let mut new_name = String::new();
428     let mut old_name = String::new();
429
430     old_name.push('$');
431     for _ in 0..(dollar_count - 1) {
432         new_name.push('$');
433         old_name.push('$');
434     }
435     new_name.push('z');
436     new_name.push_str(&name);
437     old_name.push_str(&name);
438
439     result.push_str(&new_name);
440     map.insert(old_name, new_name);
441 }
442
443 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
444 // aren't causing problems.
445 // This should also work for escaped `$` variables, where we leave earlier `$`s.
446 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
447     // Each substitution will require five or six extra bytes.
448     let mut result = String::with_capacity(input.len() + 64);
449     let mut substs = HashMap::new();
450     let mut dollar_count = 0;
451     let mut cur_name = String::new();
452
453     for (kind, c) in CharClasses::new(input.chars()) {
454         if kind != FullCodeCharKind::Normal {
455             result.push(c);
456         } else if c == '$' {
457             dollar_count += 1;
458         } else if dollar_count == 0 {
459             result.push(c);
460         } else if !c.is_alphanumeric() && !cur_name.is_empty() {
461             // Terminates a name following one or more dollars.
462             register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
463
464             result.push(c);
465             dollar_count = 0;
466             cur_name.clear();
467         } else if c == '(' && cur_name.is_empty() {
468             // FIXME: Support macro def with repeat.
469             return None;
470         } else if c.is_alphanumeric() || c == '_' {
471             cur_name.push(c);
472         }
473     }
474
475     if !cur_name.is_empty() {
476         register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
477     }
478
479     debug!("replace_names `{}` {:?}", result, substs);
480
481     Some((result, substs))
482 }
483
484 #[derive(Debug, Clone)]
485 enum MacroArgKind {
486     /// e.g. `$x: expr`.
487     MetaVariable(ast::Ident, String),
488     /// e.g. `$($foo: expr),*`
489     Repeat(
490         /// `()`, `[]` or `{}`.
491         DelimToken,
492         /// Inner arguments inside delimiters.
493         Vec<ParsedMacroArg>,
494         /// Something after the closing delimiter and the repeat token, if available.
495         Option<Box<ParsedMacroArg>>,
496         /// The repeat token. This could be one of `*`, `+` or `?`.
497         Token,
498     ),
499     /// e.g. `[derive(Debug)]`
500     Delimited(DelimToken, Vec<ParsedMacroArg>),
501     /// A possible separator. e.g. `,` or `;`.
502     Separator(String, String),
503     /// Other random stuff that does not fit to other kinds.
504     /// e.g. `== foo` in `($x: expr == foo)`.
505     Other(String, String),
506 }
507
508 fn delim_token_to_str(
509     context: &RewriteContext,
510     delim_token: &DelimToken,
511     shape: Shape,
512     use_multiple_lines: bool,
513     inner_is_empty: bool,
514 ) -> (String, String) {
515     let (lhs, rhs) = match *delim_token {
516         DelimToken::Paren => ("(", ")"),
517         DelimToken::Bracket => ("[", "]"),
518         DelimToken::Brace => {
519             if inner_is_empty || use_multiple_lines {
520                 ("{", "}")
521             } else {
522                 ("{ ", " }")
523             }
524         }
525         DelimToken::NoDelim => ("", ""),
526     };
527     if use_multiple_lines {
528         let indent_str = shape.indent.to_string_with_newline(context.config);
529         let nested_indent_str = shape
530             .indent
531             .block_indent(context.config)
532             .to_string_with_newline(context.config);
533         (
534             format!("{}{}", lhs, nested_indent_str),
535             format!("{}{}", indent_str, rhs),
536         )
537     } else {
538         (lhs.to_owned(), rhs.to_owned())
539     }
540 }
541
542 impl MacroArgKind {
543     fn starts_with_brace(&self) -> bool {
544         match *self {
545             MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
546             | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
547             _ => false,
548         }
549     }
550
551     fn starts_with_dollar(&self) -> bool {
552         match *self {
553             MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
554             _ => false,
555         }
556     }
557
558     fn ends_with_space(&self) -> bool {
559         match *self {
560             MacroArgKind::Separator(..) => true,
561             _ => false,
562         }
563     }
564
565     fn has_meta_var(&self) -> bool {
566         match *self {
567             MacroArgKind::MetaVariable(..) => true,
568             MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
569             _ => false,
570         }
571     }
572
573     fn rewrite(
574         &self,
575         context: &RewriteContext,
576         shape: Shape,
577         use_multiple_lines: bool,
578     ) -> Option<String> {
579         let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
580             let inner = wrap_macro_args(context, args, shape)?;
581             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
582             if lhs.len() + inner.len() + rhs.len() <= shape.width {
583                 return Some((lhs, inner, rhs));
584             }
585
586             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
587             let nested_shape = shape
588                 .block_indent(context.config.tab_spaces())
589                 .with_max_width(context.config);
590             let inner = wrap_macro_args(context, args, nested_shape)?;
591             Some((lhs, inner, rhs))
592         };
593
594         match *self {
595             MacroArgKind::MetaVariable(ty, ref name) => {
596                 Some(format!("${}:{}", name, ty.name.as_str()))
597             }
598             MacroArgKind::Repeat(ref delim_tok, ref args, ref another, ref tok) => {
599                 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
600                 let another = another
601                     .as_ref()
602                     .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
603                     .unwrap_or_else(|| "".to_owned());
604                 let repeat_tok = pprust::token_to_string(tok);
605
606                 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
607             }
608             MacroArgKind::Delimited(ref delim_tok, ref args) => {
609                 rewrite_delimited_inner(delim_tok, args)
610                     .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
611             }
612             MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
613             MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
614         }
615     }
616 }
617
618 #[derive(Debug, Clone)]
619 struct ParsedMacroArg {
620     kind: MacroArgKind,
621     span: Span,
622 }
623
624 impl ParsedMacroArg {
625     pub fn rewrite(
626         &self,
627         context: &RewriteContext,
628         shape: Shape,
629         use_multiple_lines: bool,
630     ) -> Option<String> {
631         self.kind.rewrite(context, shape, use_multiple_lines)
632     }
633 }
634
635 /// Parses macro arguments on macro def.
636 struct MacroArgParser {
637     /// Holds either a name of the next metavariable, a separator or a junk.
638     buf: String,
639     /// The start position on the current buffer.
640     lo: BytePos,
641     /// The first token of the current buffer.
642     start_tok: Token,
643     /// Set to true if we are parsing a metavariable or a repeat.
644     is_meta_var: bool,
645     /// The position of the last token.
646     hi: BytePos,
647     /// The last token parsed.
648     last_tok: Token,
649     /// Holds the parsed arguments.
650     result: Vec<ParsedMacroArg>,
651 }
652
653 fn last_tok(tt: &TokenTree) -> Token {
654     match *tt {
655         TokenTree::Token(_, ref t) => t.clone(),
656         TokenTree::Delimited(_, ref d) => d.close_token(),
657     }
658 }
659
660 impl MacroArgParser {
661     pub fn new() -> MacroArgParser {
662         MacroArgParser {
663             lo: BytePos(0),
664             hi: BytePos(0),
665             buf: String::new(),
666             is_meta_var: false,
667             last_tok: Token::Eof,
668             start_tok: Token::Eof,
669             result: vec![],
670         }
671     }
672
673     fn set_last_tok(&mut self, tok: &TokenTree) {
674         self.hi = tok.span().hi();
675         self.last_tok = last_tok(tok);
676     }
677
678     fn add_separator(&mut self) {
679         let prefix = if self.need_space_prefix() {
680             " ".to_owned()
681         } else {
682             "".to_owned()
683         };
684         self.result.push(ParsedMacroArg {
685             kind: MacroArgKind::Separator(self.buf.clone(), prefix),
686             span: mk_sp(self.lo, self.hi),
687         });
688         self.buf.clear();
689     }
690
691     fn add_other(&mut self) {
692         let prefix = if self.need_space_prefix() {
693             " ".to_owned()
694         } else {
695             "".to_owned()
696         };
697         self.result.push(ParsedMacroArg {
698             kind: MacroArgKind::Other(self.buf.clone(), prefix),
699             span: mk_sp(self.lo, self.hi),
700         });
701         self.buf.clear();
702     }
703
704     fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
705         match iter.next() {
706             Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
707                 self.result.push(ParsedMacroArg {
708                     kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
709                     span: mk_sp(self.lo, sp.hi()),
710                 });
711
712                 self.buf.clear();
713                 self.is_meta_var = false;
714                 Some(())
715             }
716             _ => None,
717         }
718     }
719
720     fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
721         self.result.push(ParsedMacroArg {
722             kind: MacroArgKind::Delimited(delim, inner),
723             span,
724         });
725     }
726
727     // $($foo: expr),?
728     fn add_repeat(
729         &mut self,
730         inner: Vec<ParsedMacroArg>,
731         delim: DelimToken,
732         iter: &mut Cursor,
733         span: Span,
734     ) -> Option<()> {
735         let mut buffer = String::new();
736         let mut first = false;
737         let mut lo = span.lo();
738         let mut hi = span.hi();
739
740         // Parse '*', '+' or '?.
741         for ref tok in iter {
742             self.set_last_tok(tok);
743             if first {
744                 first = false;
745                 lo = tok.span().lo();
746             }
747
748             match tok {
749                 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
750                 | TokenTree::Token(_, Token::Question)
751                 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
752                     break;
753                 }
754                 TokenTree::Token(sp, ref t) => {
755                     buffer.push_str(&pprust::token_to_string(t));
756                     hi = sp.hi();
757                 }
758                 _ => return None,
759             }
760         }
761
762         // There could be some random stuff between ')' and '*', '+' or '?'.
763         let another = if buffer.trim().is_empty() {
764             None
765         } else {
766             Some(Box::new(ParsedMacroArg {
767                 kind: MacroArgKind::Other(buffer, "".to_owned()),
768                 span: mk_sp(lo, hi),
769             }))
770         };
771
772         self.result.push(ParsedMacroArg {
773             kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
774             span: mk_sp(self.lo, self.hi),
775         });
776         Some(())
777     }
778
779     fn update_buffer(&mut self, lo: BytePos, t: &Token) {
780         if self.buf.is_empty() {
781             self.lo = lo;
782             self.start_tok = t.clone();
783         } else {
784             let needs_space = match next_space(&self.last_tok) {
785                 SpaceState::Ident => ident_like(t),
786                 SpaceState::Punctuation => !ident_like(t),
787                 SpaceState::Always => true,
788                 SpaceState::Never => false,
789             };
790             if force_space_before(t) || needs_space {
791                 self.buf.push(' ');
792             }
793         }
794
795         self.buf.push_str(&pprust::token_to_string(t));
796     }
797
798     fn need_space_prefix(&self) -> bool {
799         if self.result.is_empty() {
800             return false;
801         }
802
803         let last_arg = self.result.last().unwrap();
804         if let MacroArgKind::MetaVariable(..) = last_arg.kind {
805             if ident_like(&self.start_tok) {
806                 return true;
807             }
808             if self.start_tok == Token::Colon {
809                 return true;
810             }
811         }
812
813         if force_space_before(&self.start_tok) {
814             return true;
815         }
816
817         false
818     }
819
820     /// Returns a collection of parsed macro def's arguments.
821     pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
822         let mut iter = (tokens.into(): TokenStream).trees();
823
824         while let Some(ref tok) = iter.next() {
825             match tok {
826                 TokenTree::Token(sp, Token::Dollar) => {
827                     // We always want to add a separator before meta variables.
828                     if !self.buf.is_empty() {
829                         self.add_separator();
830                     }
831
832                     // Start keeping the name of this metavariable in the buffer.
833                     self.is_meta_var = true;
834                     self.lo = sp.lo();
835                     self.start_tok = Token::Dollar;
836                 }
837                 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
838                     self.add_meta_variable(&mut iter)?;
839                 }
840                 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
841                 TokenTree::Delimited(sp, delimited) => {
842                     if !self.buf.is_empty() {
843                         if next_space(&self.last_tok) == SpaceState::Always {
844                             self.add_separator();
845                         } else {
846                             self.add_other();
847                         }
848                     }
849
850                     // Parse the stuff inside delimiters.
851                     let mut parser = MacroArgParser::new();
852                     parser.lo = sp.lo();
853                     let delimited_arg = parser.parse(delimited.tts.clone())?;
854
855                     if self.is_meta_var {
856                         self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp)?;
857                         self.is_meta_var = false;
858                     } else {
859                         self.add_delimited(delimited_arg, delimited.delim, *sp);
860                     }
861                 }
862             }
863
864             self.set_last_tok(tok);
865         }
866
867         // We are left with some stuff in the buffer. Since there is nothing
868         // left to separate, add this as `Other`.
869         if !self.buf.is_empty() {
870             self.add_other();
871         }
872
873         Some(self.result)
874     }
875 }
876
877 fn wrap_macro_args(
878     context: &RewriteContext,
879     args: &[ParsedMacroArg],
880     shape: Shape,
881 ) -> Option<String> {
882     wrap_macro_args_inner(context, args, shape, false)
883         .or_else(|| wrap_macro_args_inner(context, args, shape, true))
884 }
885
886 fn wrap_macro_args_inner(
887     context: &RewriteContext,
888     args: &[ParsedMacroArg],
889     shape: Shape,
890     use_multiple_lines: bool,
891 ) -> Option<String> {
892     let mut result = String::with_capacity(128);
893     let mut iter = args.iter().peekable();
894     let indent_str = shape.indent.to_string_with_newline(context.config);
895
896     while let Some(ref arg) = iter.next() {
897         result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
898
899         if use_multiple_lines
900             && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
901         {
902             if arg.kind.ends_with_space() {
903                 result.pop();
904             }
905             result.push_str(&indent_str);
906         } else if let Some(ref next_arg) = iter.peek() {
907             let space_before_dollar =
908                 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
909             let space_before_brace = next_arg.kind.starts_with_brace();
910             if space_before_dollar || space_before_brace {
911                 result.push(' ');
912             }
913         }
914     }
915
916     if !use_multiple_lines && result.len() >= shape.width {
917         None
918     } else {
919         Some(result)
920     }
921 }
922
923 // This is a bit sketchy. The token rules probably need tweaking, but it works
924 // for some common cases. I hope the basic logic is sufficient. Note that the
925 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
926 // and `(`/`)` have special meaning.
927 //
928 // We always try and format on one line.
929 // FIXME: Use multi-line when every thing does not fit on one line.
930 fn format_macro_args(
931     context: &RewriteContext,
932     toks: ThinTokenStream,
933     shape: Shape,
934 ) -> Option<String> {
935     let parsed_args = MacroArgParser::new().parse(toks)?;
936     wrap_macro_args(context, &parsed_args, shape)
937 }
938
939 // We should insert a space if the next token is a:
940 #[derive(Copy, Clone, PartialEq)]
941 enum SpaceState {
942     Never,
943     Punctuation,
944     Ident, // Or ident/literal-like thing.
945     Always,
946 }
947
948 fn force_space_before(tok: &Token) -> bool {
949     debug!("tok: force_space_before {:?}", tok);
950
951     match *tok {
952         Token::Eq
953         | Token::Lt
954         | Token::Le
955         | Token::EqEq
956         | Token::Ne
957         | Token::Ge
958         | Token::Gt
959         | Token::AndAnd
960         | Token::OrOr
961         | Token::Not
962         | Token::Tilde
963         | Token::BinOpEq(_)
964         | Token::At
965         | Token::RArrow
966         | Token::LArrow
967         | Token::FatArrow
968         | Token::BinOp(_)
969         | Token::Pound
970         | Token::Dollar => true,
971         _ => false,
972     }
973 }
974
975 fn ident_like(tok: &Token) -> bool {
976     match *tok {
977         Token::Ident(..) | Token::Literal(..) | Token::Lifetime(_) => true,
978         _ => false,
979     }
980 }
981
982 fn next_space(tok: &Token) -> SpaceState {
983     debug!("next_space: {:?}", tok);
984
985     match *tok {
986         Token::Not
987         | Token::BinOp(BinOpToken::And)
988         | Token::Tilde
989         | Token::At
990         | Token::Comma
991         | Token::Dot
992         | Token::DotDot
993         | Token::DotDotDot
994         | Token::DotDotEq
995         | Token::DotEq
996         | Token::Question => SpaceState::Punctuation,
997
998         Token::ModSep
999         | Token::Pound
1000         | Token::Dollar
1001         | Token::OpenDelim(_)
1002         | Token::CloseDelim(_)
1003         | Token::Whitespace => SpaceState::Never,
1004
1005         Token::Literal(..) | Token::Ident(..) | Token::Lifetime(_) => SpaceState::Ident,
1006
1007         _ => SpaceState::Always,
1008     }
1009 }
1010
1011 /// Tries to convert a macro use into a short hand try expression. Returns None
1012 /// when the macro is not an instance of try! (or parsing the inner expression
1013 /// failed).
1014 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1015     if &format!("{}", mac.node.path) == "try" {
1016         let ts: TokenStream = mac.node.tts.clone().into();
1017         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1018
1019         Some(ast::Expr {
1020             id: ast::NodeId::new(0), // dummy value
1021             node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1022             span: mac.span, // incorrect span, but shouldn't matter too much
1023             attrs: ThinVec::new(),
1024         })
1025     } else {
1026         None
1027     }
1028 }
1029
1030 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> DelimToken {
1031     let snippet = context.snippet(mac.span);
1032     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1033     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1034     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1035
1036     if paren_pos < bracket_pos && paren_pos < brace_pos {
1037         DelimToken::Paren
1038     } else if bracket_pos < brace_pos {
1039         DelimToken::Bracket
1040     } else {
1041         DelimToken::Brace
1042     }
1043 }
1044
1045 /// Indent each line according to the specified `indent`.
1046 /// e.g.
1047 ///
1048 /// ```rust,ignore
1049 /// foo!{
1050 /// x,
1051 /// y,
1052 /// foo(
1053 ///     a,
1054 ///     b,
1055 ///     c,
1056 /// ),
1057 /// }
1058 /// ```
1059 ///
1060 /// will become
1061 ///
1062 /// ```rust,ignore
1063 /// foo!{
1064 ///     x,
1065 ///     y,
1066 ///     foo(
1067 ///         a,
1068 ///         b,
1069 ///         c,
1070 ///     ),
1071 /// }
1072 /// ```
1073 fn indent_macro_snippet(
1074     context: &RewriteContext,
1075     macro_str: &str,
1076     indent: Indent,
1077 ) -> Option<String> {
1078     let mut lines = LineClasses::new(macro_str);
1079     let first_line = lines.next().map(|(_, s)| s.trim_right().to_owned())?;
1080     let mut trimmed_lines = Vec::with_capacity(16);
1081
1082     let mut veto_trim = false;
1083     let min_prefix_space_width = lines
1084         .filter_map(|(kind, line)| {
1085             let mut trimmed = true;
1086             let prefix_space_width = if is_empty_line(&line) {
1087                 None
1088             } else {
1089                 Some(get_prefix_space_width(context, &line))
1090             };
1091             let line = if veto_trim || (kind.is_string() && !line.ends_with('\\')) {
1092                 veto_trim = kind.is_string() && !line.ends_with('\\');
1093                 trimmed = false;
1094                 line
1095             } else {
1096                 line.trim().to_owned()
1097             };
1098             trimmed_lines.push((trimmed, line, prefix_space_width));
1099             prefix_space_width
1100         })
1101         .min()?;
1102
1103     Some(
1104         first_line + "\n"
1105             + &trimmed_lines
1106                 .iter()
1107                 .map(
1108                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
1109                         _ if !trimmed => line.to_owned(),
1110                         Some(original_indent_width) => {
1111                             let new_indent_width = indent.width()
1112                                 + original_indent_width.saturating_sub(min_prefix_space_width);
1113                             let new_indent = Indent::from_width(context.config, new_indent_width);
1114                             format!("{}{}", new_indent.to_string(context.config), line.trim())
1115                         }
1116                         None => String::new(),
1117                     },
1118                 )
1119                 .collect::<Vec<_>>()
1120                 .join("\n"),
1121     )
1122 }
1123
1124 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1125     let mut width = 0;
1126     for c in s.chars() {
1127         match c {
1128             ' ' => width += 1,
1129             '\t' => width += context.config.tab_spaces(),
1130             _ => return width,
1131         }
1132     }
1133     width
1134 }
1135
1136 fn is_empty_line(s: &str) -> bool {
1137     s.is_empty() || s.chars().all(char::is_whitespace)
1138 }
1139
1140 // A very simple parser that just parses a macros 2.0 definition into its branches.
1141 // Currently we do not attempt to parse any further than that.
1142 #[derive(new)]
1143 struct MacroParser {
1144     toks: Cursor,
1145 }
1146
1147 impl MacroParser {
1148     // (`(` ... `)` `=>` `{` ... `}`)*
1149     fn parse(&mut self) -> Option<Macro> {
1150         let mut branches = vec![];
1151         while self.toks.look_ahead(1).is_some() {
1152             branches.push(self.parse_branch()?);
1153         }
1154
1155         Some(Macro { branches })
1156     }
1157
1158     // `(` ... `)` `=>` `{` ... `}`
1159     fn parse_branch(&mut self) -> Option<MacroBranch> {
1160         let tok = self.toks.next()?;
1161         let (lo, args_paren_kind) = match tok {
1162             TokenTree::Token(..) => return None,
1163             TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1164         };
1165         let args = tok.joint().into();
1166         match self.toks.next()? {
1167             TokenTree::Token(_, Token::FatArrow) => {}
1168             _ => return None,
1169         }
1170         let (mut hi, body) = match self.toks.next()? {
1171             TokenTree::Token(..) => return None,
1172             TokenTree::Delimited(sp, _) => {
1173                 let data = sp.data();
1174                 (
1175                     data.hi,
1176                     Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1177                 )
1178             }
1179         };
1180         if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1181             self.toks.next();
1182             hi = sp.hi();
1183         }
1184         Some(MacroBranch {
1185             span: mk_sp(lo, hi),
1186             args_paren_kind,
1187             args,
1188             body,
1189         })
1190     }
1191 }
1192
1193 // A parsed macros 2.0 macro definition.
1194 struct Macro {
1195     branches: Vec<MacroBranch>,
1196 }
1197
1198 // FIXME: it would be more efficient to use references to the token streams
1199 // rather than clone them, if we can make the borrowing work out.
1200 struct MacroBranch {
1201     span: Span,
1202     args_paren_kind: DelimToken,
1203     args: ThinTokenStream,
1204     body: Span,
1205 }
1206
1207 impl MacroBranch {
1208     fn rewrite(
1209         &self,
1210         context: &RewriteContext,
1211         shape: Shape,
1212         multi_branch_style: bool,
1213     ) -> Option<String> {
1214         // Only attempt to format function-like macros.
1215         if self.args_paren_kind != DelimToken::Paren {
1216             // FIXME(#1539): implement for non-sugared macros.
1217             return None;
1218         }
1219
1220         // 5 = " => {"
1221         let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1222
1223         if multi_branch_style {
1224             result += " =>";
1225         }
1226
1227         // The macro body is the most interesting part. It might end up as various
1228         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1229         // parsed as regular Rust code (and note that these can be escaped using
1230         // `$$`). We'll try and format like an AST node, but we'll substitute
1231         // variables for new names with the same length first.
1232
1233         let old_body = context.snippet(self.body).trim();
1234         let (body_str, substs) = replace_names(old_body)?;
1235
1236         let mut config = context.config.clone();
1237         config.set().hide_parse_errors(true);
1238
1239         result += " {";
1240
1241         let has_block_body = old_body.starts_with('{');
1242
1243         let body_indent = if has_block_body {
1244             shape.indent
1245         } else {
1246             // We'll hack the indent below, take this into account when formatting,
1247             let body_indent = shape.indent.block_indent(&config);
1248             let new_width = config.max_width() - body_indent.width();
1249             config.set().max_width(new_width);
1250             body_indent
1251         };
1252
1253         // First try to format as items, then as statements.
1254         let new_body = match ::format_snippet(&body_str, &config) {
1255             Some(new_body) => new_body,
1256             None => match ::format_code_block(&body_str, &config) {
1257                 Some(new_body) => new_body,
1258                 None => return None,
1259             },
1260         };
1261         let new_body = wrap_str(new_body, config.max_width(), shape)?;
1262
1263         // Indent the body since it is in a block.
1264         let indent_str = body_indent.to_string(&config);
1265         let mut new_body = LineClasses::new(new_body.trim_right())
1266             .fold(
1267                 (String::new(), true),
1268                 |(mut s, need_indent), (kind, ref l)| {
1269                     if !l.is_empty() && need_indent {
1270                         s += &indent_str;
1271                     }
1272                     (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1273                 },
1274             )
1275             .0;
1276
1277         // Undo our replacement of macro variables.
1278         // FIXME: this could be *much* more efficient.
1279         for (old, new) in &substs {
1280             if old_body.find(new).is_some() {
1281                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1282                 return None;
1283             }
1284             new_body = new_body.replace(new, old);
1285         }
1286
1287         if has_block_body {
1288             result += new_body.trim();
1289         } else if !new_body.is_empty() {
1290             result += "\n";
1291             result += &new_body;
1292             result += &shape.indent.to_string(&config);
1293         }
1294
1295         result += "}";
1296
1297         Some(result)
1298     }
1299 }
1300
1301 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1302 ///
1303 /// # Expected syntax
1304 ///
1305 /// ```ignore
1306 /// lazy_static! {
1307 ///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1308 ///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1309 ///     ...
1310 ///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1311 /// }
1312 /// ```
1313 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1314     let mut result = String::with_capacity(1024);
1315     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1316     let nested_shape = shape
1317         .block_indent(context.config.tab_spaces())
1318         .with_max_width(context.config);
1319
1320     result.push_str("lazy_static! {");
1321     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1322
1323     macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1324         match parser.$method($($arg,)*) {
1325             Ok(val) => {
1326                 if parser.sess.span_diagnostic.has_errors() {
1327                     parser.sess.span_diagnostic.reset_err_count();
1328                     return None;
1329                 } else {
1330                     val
1331                 }
1332             }
1333             Err(mut err) => {
1334                 err.cancel();
1335                 parser.sess.span_diagnostic.reset_err_count();
1336                 return None;
1337             }
1338         }
1339     }
1340
1341     while parser.token != Token::Eof {
1342         // Parse a `lazy_static!` item.
1343         let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1344         parser.eat_keyword(symbol::keywords::Static);
1345         parser.eat_keyword(symbol::keywords::Ref);
1346         let id = parse_or!(parse_ident);
1347         parser.eat(&Token::Colon);
1348         let ty = parse_or!(parse_ty);
1349         parser.eat(&Token::Eq);
1350         let expr = parse_or!(parse_expr);
1351         parser.eat(&Token::Semi);
1352
1353         // Rewrite as a static item.
1354         let mut stmt = String::with_capacity(128);
1355         stmt.push_str(&format!(
1356             "{}static ref {}: {} =",
1357             vis,
1358             id,
1359             ty.rewrite(context, nested_shape)?
1360         ));
1361         result.push_str(&::expr::rewrite_assign_rhs(
1362             context,
1363             stmt,
1364             &*expr,
1365             nested_shape.sub_width(1)?,
1366         )?);
1367         result.push(';');
1368         if parser.token != Token::Eof {
1369             result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1370         }
1371     }
1372
1373     result.push_str(&shape.indent.to_string_with_newline(context.config));
1374     result.push('}');
1375
1376     Some(result)
1377 }