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