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