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