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