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