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