]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #3050 from andrehjr/empty-impl-body-with-braces-newline
[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         Some(visitor.buffer.to_owned())
73     }
74 }
75
76 impl Rewrite for MacroArg {
77     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
78         match *self {
79             MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
80             MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
81             MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
82             MacroArg::Item(ref item) => item.rewrite(context, shape),
83         }
84     }
85 }
86
87 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
88     macro_rules! parse_macro_arg {
89         ($macro_arg:ident, $parser:ident, $f:expr) => {
90             let mut cloned_parser = (*parser).clone();
91             match cloned_parser.$parser() {
92                 Ok(x) => {
93                     if parser.sess.span_diagnostic.has_errors() {
94                         parser.sess.span_diagnostic.reset_err_count();
95                     } else {
96                         // Parsing succeeded.
97                         *parser = cloned_parser;
98                         return Some(MacroArg::$macro_arg($f(x)?));
99                     }
100                 }
101                 Err(mut e) => {
102                     e.cancel();
103                     parser.sess.span_diagnostic.reset_err_count();
104                 }
105             }
106         };
107     }
108
109     parse_macro_arg!(Expr, parse_expr, |x: ptr::P<ast::Expr>| Some(x));
110     parse_macro_arg!(Ty, parse_ty, |x: ptr::P<ast::Ty>| Some(x));
111     parse_macro_arg!(Pat, parse_pat, |x: ptr::P<ast::Pat>| Some(x));
112     // `parse_item` returns `Option<ptr::P<ast::Item>>`.
113     parse_macro_arg!(Item, parse_item, |x: Option<ptr::P<ast::Item>>| x);
114
115     None
116 }
117
118 /// Rewrite macro name without using pretty-printer if possible.
119 fn rewrite_macro_name(
120     context: &RewriteContext,
121     path: &ast::Path,
122     extra_ident: Option<ast::Ident>,
123 ) -> String {
124     let name = if path.segments.len() == 1 {
125         // Avoid using pretty-printer in the common case.
126         format!("{}!", rewrite_ident(context, path.segments[0].ident))
127     } else {
128         format!("{}!", path)
129     };
130     match extra_ident {
131         Some(ident) if ident != symbol::keywords::Invalid.ident() => format!("{} {}", name, ident),
132         _ => name,
133     }
134 }
135
136 // Use this on failing to format the macro call.
137 fn return_original_snippet_with_failure_marked(
138     context: &RewriteContext,
139     span: Span,
140 ) -> Option<String> {
141     context.macro_rewrite_failure.replace(true);
142     Some(context.snippet(span).to_owned())
143 }
144
145 struct InsideMacroGuard<'a> {
146     context: &'a RewriteContext<'a>,
147     is_nested: bool,
148 }
149
150 impl<'a> InsideMacroGuard<'a> {
151     fn inside_macro_context(context: &'a RewriteContext) -> InsideMacroGuard<'a> {
152         let is_nested = context.inside_macro.replace(true);
153         InsideMacroGuard { context, is_nested }
154     }
155 }
156
157 impl<'a> Drop for InsideMacroGuard<'a> {
158     fn drop(&mut self) {
159         self.context.inside_macro.replace(self.is_nested);
160     }
161 }
162
163 pub fn rewrite_macro(
164     mac: &ast::Mac,
165     extra_ident: Option<ast::Ident>,
166     context: &RewriteContext,
167     shape: Shape,
168     position: MacroPosition,
169 ) -> Option<String> {
170     let guard = InsideMacroGuard::inside_macro_context(context);
171     let result = rewrite_macro_inner(mac, extra_ident, context, shape, position, guard.is_nested);
172     if result.is_none() {
173         context.macro_rewrite_failure.replace(true);
174     }
175     result
176 }
177
178 pub fn rewrite_macro_inner(
179     mac: &ast::Mac,
180     extra_ident: Option<ast::Ident>,
181     context: &RewriteContext,
182     shape: Shape,
183     position: MacroPosition,
184     is_nested_macro: bool,
185 ) -> Option<String> {
186     if context.config.use_try_shorthand() {
187         if let Some(expr) = convert_try_mac(mac, context) {
188             context.inside_macro.replace(false);
189             return expr.rewrite(context, shape);
190         }
191     }
192
193     let original_style = macro_style(mac, context);
194
195     let macro_name = rewrite_macro_name(context, &mac.node.path, extra_ident);
196
197     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) && !is_nested_macro {
198         DelimToken::Bracket
199     } else {
200         original_style
201     };
202
203     let ts: TokenStream = mac.node.stream();
204     let has_comment = contains_comment(context.snippet(mac.span));
205     if ts.is_empty() && !has_comment {
206         return match style {
207             DelimToken::Paren if position == MacroPosition::Item => {
208                 Some(format!("{}();", macro_name))
209             }
210             DelimToken::Paren => Some(format!("{}()", macro_name)),
211             DelimToken::Bracket => Some(format!("{}[]", macro_name)),
212             DelimToken::Brace => Some(format!("{}{{}}", macro_name)),
213             _ => unreachable!(),
214         };
215     }
216     // Format well-known macros which cannot be parsed as a valid AST.
217     if macro_name == "lazy_static!" && !has_comment {
218         if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
219             return success;
220         }
221     }
222
223     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
224     let mut arg_vec = Vec::new();
225     let mut vec_with_semi = false;
226     let mut trailing_comma = false;
227
228     if DelimToken::Brace != style {
229         loop {
230             match parse_macro_arg(&mut parser) {
231                 Some(arg) => arg_vec.push(arg),
232                 None => return return_original_snippet_with_failure_marked(context, mac.span),
233             }
234
235             match parser.token {
236                 Token::Eof => break,
237                 Token::Comma => (),
238                 Token::Semi => {
239                     // Try to parse `vec![expr; expr]`
240                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
241                         parser.bump();
242                         if parser.token != Token::Eof {
243                             match parse_macro_arg(&mut parser) {
244                                 Some(arg) => {
245                                     arg_vec.push(arg);
246                                     parser.bump();
247                                     if parser.token == Token::Eof && arg_vec.len() == 2 {
248                                         vec_with_semi = true;
249                                         break;
250                                     }
251                                 }
252                                 None => {
253                                     return return_original_snippet_with_failure_marked(
254                                         context, mac.span,
255                                     )
256                                 }
257                             }
258                         }
259                     }
260                     return return_original_snippet_with_failure_marked(context, mac.span);
261                 }
262                 _ => return return_original_snippet_with_failure_marked(context, mac.span),
263             }
264
265             parser.bump();
266
267             if parser.token == Token::Eof {
268                 trailing_comma = true;
269                 break;
270             }
271         }
272     }
273
274     match style {
275         DelimToken::Paren => {
276             // Format macro invocation as function call, preserve the trailing
277             // comma because not all macros support them.
278             overflow::rewrite_with_parens(
279                 context,
280                 &macro_name,
281                 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>(),
282                 shape,
283                 mac.span,
284                 context.config.width_heuristics().fn_call_width,
285                 if trailing_comma {
286                     Some(SeparatorTactic::Always)
287                 } else {
288                     Some(SeparatorTactic::Never)
289                 },
290             )
291             .map(|rw| match position {
292                 MacroPosition::Item => format!("{};", rw),
293                 _ => rw,
294             })
295         }
296         DelimToken::Bracket => {
297             // Handle special case: `vec![expr; expr]`
298             if vec_with_semi {
299                 let mac_shape = shape.offset_left(macro_name.len())?;
300                 // 8 = `vec![]` + `; `
301                 let total_overhead = 8;
302                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
303                 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
304                 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
305                 if !lhs.contains('\n')
306                     && !rhs.contains('\n')
307                     && lhs.len() + rhs.len() + total_overhead <= shape.width
308                 {
309                     Some(format!("{}[{}; {}]", macro_name, lhs, rhs))
310                 } else {
311                     Some(format!(
312                         "{}[{}{};{}{}{}]",
313                         macro_name,
314                         nested_shape.indent.to_string_with_newline(context.config),
315                         lhs,
316                         nested_shape.indent.to_string_with_newline(context.config),
317                         rhs,
318                         shape.indent.to_string_with_newline(context.config),
319                     ))
320                 }
321             } else {
322                 // If we are rewriting `vec!` macro or other special macros,
323                 // then we can rewrite this as an usual array literal.
324                 // Otherwise, we must preserve the original existence of trailing comma.
325                 let macro_name = &macro_name.as_str();
326                 let mut force_trailing_comma = if trailing_comma {
327                     Some(SeparatorTactic::Always)
328                 } else {
329                     Some(SeparatorTactic::Never)
330                 };
331                 if FORCED_BRACKET_MACROS.contains(macro_name) && !is_nested_macro {
332                     context.inside_macro.replace(false);
333                     if context.use_block_indent() {
334                         force_trailing_comma = Some(SeparatorTactic::Vertical);
335                     };
336                 }
337                 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
338                 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>();
339                 let rewrite = rewrite_array(
340                     macro_name,
341                     arg_vec,
342                     mac.span,
343                     context,
344                     shape,
345                     force_trailing_comma,
346                     Some(original_style),
347                 )?;
348                 let comma = match position {
349                     MacroPosition::Item => ";",
350                     _ => "",
351                 };
352
353                 Some(format!("{}{}", rewrite, comma))
354             }
355         }
356         DelimToken::Brace => {
357             // Skip macro invocations with braces, for now.
358             indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
359         }
360         _ => unreachable!(),
361     }
362 }
363
364 pub fn rewrite_macro_def(
365     context: &RewriteContext,
366     shape: Shape,
367     indent: Indent,
368     def: &ast::MacroDef,
369     ident: ast::Ident,
370     vis: &ast::Visibility,
371     span: Span,
372 ) -> Option<String> {
373     let snippet = Some(remove_trailing_white_spaces(context.snippet(span)));
374     if snippet.as_ref().map_or(true, |s| s.ends_with(';')) {
375         return snippet;
376     }
377
378     let mut parser = MacroParser::new(def.stream().into_trees());
379     let parsed_def = match parser.parse() {
380         Some(def) => def,
381         None => return snippet,
382     };
383
384     let mut result = if def.legacy {
385         String::from("macro_rules!")
386     } else {
387         format!("{}macro", format_visibility(context, vis))
388     };
389
390     result += " ";
391     result += rewrite_ident(context, ident);
392
393     let multi_branch_style = def.legacy || parsed_def.branches.len() != 1;
394
395     let arm_shape = if multi_branch_style {
396         shape
397             .block_indent(context.config.tab_spaces())
398             .with_max_width(context.config)
399     } else {
400         shape
401     };
402
403     let branch_items = itemize_list(
404         context.snippet_provider,
405         parsed_def.branches.iter(),
406         "}",
407         ";",
408         |branch| branch.span.lo(),
409         |branch| branch.span.hi(),
410         |branch| match branch.rewrite(context, arm_shape, multi_branch_style) {
411             Some(v) => Some(v),
412             // if the rewrite returned None because a macro could not be rewritten, then return the
413             // original body
414             None if *context.macro_rewrite_failure.borrow() == true => {
415                 Some(context.snippet(branch.body).trim().to_string())
416             }
417             None => None,
418         },
419         context.snippet_provider.span_after(span, "{"),
420         span.hi(),
421         false,
422     )
423     .collect::<Vec<_>>();
424
425     let fmt = ListFormatting::new(arm_shape, context.config)
426         .separator(if def.legacy { ";" } else { "" })
427         .trailing_separator(SeparatorTactic::Always)
428         .preserve_newline(true);
429
430     if multi_branch_style {
431         result += " {";
432         result += &arm_shape.indent.to_string_with_newline(context.config);
433     }
434
435     match write_list(&branch_items, &fmt) {
436         Some(ref s) => result += s,
437         None => return snippet,
438     }
439
440     if multi_branch_style {
441         result += &indent.to_string_with_newline(context.config);
442         result += "}";
443     }
444
445     Some(result)
446 }
447
448 fn register_metavariable(
449     map: &mut HashMap<String, String>,
450     result: &mut String,
451     name: &str,
452     dollar_count: usize,
453 ) {
454     let mut new_name = String::new();
455     let mut old_name = String::new();
456
457     old_name.push('$');
458     for _ in 0..(dollar_count - 1) {
459         new_name.push('$');
460         old_name.push('$');
461     }
462     new_name.push('z');
463     new_name.push_str(&name);
464     old_name.push_str(&name);
465
466     result.push_str(&new_name);
467     map.insert(old_name, new_name);
468 }
469
470 // Replaces `$foo` with `zfoo`. We must check for name overlap to ensure we
471 // aren't causing problems.
472 // This should also work for escaped `$` variables, where we leave earlier `$`s.
473 fn replace_names(input: &str) -> Option<(String, HashMap<String, String>)> {
474     // Each substitution will require five or six extra bytes.
475     let mut result = String::with_capacity(input.len() + 64);
476     let mut substs = HashMap::new();
477     let mut dollar_count = 0;
478     let mut cur_name = String::new();
479
480     for (kind, c) in CharClasses::new(input.chars()) {
481         if kind != FullCodeCharKind::Normal {
482             result.push(c);
483         } else if c == '$' {
484             dollar_count += 1;
485         } else if dollar_count == 0 {
486             result.push(c);
487         } else if !c.is_alphanumeric() && !cur_name.is_empty() {
488             // Terminates a name following one or more dollars.
489             register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
490
491             result.push(c);
492             dollar_count = 0;
493             cur_name.clear();
494         } else if c == '(' && cur_name.is_empty() {
495             // FIXME: Support macro def with repeat.
496             return None;
497         } else if c.is_alphanumeric() || c == '_' {
498             cur_name.push(c);
499         }
500     }
501
502     if !cur_name.is_empty() {
503         register_metavariable(&mut substs, &mut result, &cur_name, dollar_count);
504     }
505
506     debug!("replace_names `{}` {:?}", result, substs);
507
508     Some((result, substs))
509 }
510
511 #[derive(Debug, Clone)]
512 enum MacroArgKind {
513     /// e.g. `$x: expr`.
514     MetaVariable(ast::Ident, String),
515     /// e.g. `$($foo: expr),*`
516     Repeat(
517         /// `()`, `[]` or `{}`.
518         DelimToken,
519         /// Inner arguments inside delimiters.
520         Vec<ParsedMacroArg>,
521         /// Something after the closing delimiter and the repeat token, if available.
522         Option<Box<ParsedMacroArg>>,
523         /// The repeat token. This could be one of `*`, `+` or `?`.
524         Token,
525     ),
526     /// e.g. `[derive(Debug)]`
527     Delimited(DelimToken, Vec<ParsedMacroArg>),
528     /// A possible separator. e.g. `,` or `;`.
529     Separator(String, String),
530     /// Other random stuff that does not fit to other kinds.
531     /// e.g. `== foo` in `($x: expr == foo)`.
532     Other(String, String),
533 }
534
535 fn delim_token_to_str(
536     context: &RewriteContext,
537     delim_token: DelimToken,
538     shape: Shape,
539     use_multiple_lines: bool,
540     inner_is_empty: bool,
541 ) -> (String, String) {
542     let (lhs, rhs) = match delim_token {
543         DelimToken::Paren => ("(", ")"),
544         DelimToken::Bracket => ("[", "]"),
545         DelimToken::Brace => {
546             if inner_is_empty || use_multiple_lines {
547                 ("{", "}")
548             } else {
549                 ("{ ", " }")
550             }
551         }
552         DelimToken::NoDelim => ("", ""),
553     };
554     if use_multiple_lines {
555         let indent_str = shape.indent.to_string_with_newline(context.config);
556         let nested_indent_str = shape
557             .indent
558             .block_indent(context.config)
559             .to_string_with_newline(context.config);
560         (
561             format!("{}{}", lhs, nested_indent_str),
562             format!("{}{}", indent_str, rhs),
563         )
564     } else {
565         (lhs.to_owned(), rhs.to_owned())
566     }
567 }
568
569 impl MacroArgKind {
570     fn starts_with_brace(&self) -> bool {
571         match *self {
572             MacroArgKind::Repeat(DelimToken::Brace, _, _, _)
573             | MacroArgKind::Delimited(DelimToken::Brace, _) => true,
574             _ => false,
575         }
576     }
577
578     fn starts_with_dollar(&self) -> bool {
579         match *self {
580             MacroArgKind::Repeat(..) | MacroArgKind::MetaVariable(..) => true,
581             _ => false,
582         }
583     }
584
585     fn ends_with_space(&self) -> bool {
586         match *self {
587             MacroArgKind::Separator(..) => true,
588             _ => false,
589         }
590     }
591
592     fn has_meta_var(&self) -> bool {
593         match *self {
594             MacroArgKind::MetaVariable(..) => true,
595             MacroArgKind::Repeat(_, ref args, _, _) => args.iter().any(|a| a.kind.has_meta_var()),
596             _ => false,
597         }
598     }
599
600     fn rewrite(
601         &self,
602         context: &RewriteContext,
603         shape: Shape,
604         use_multiple_lines: bool,
605     ) -> Option<String> {
606         let rewrite_delimited_inner = |delim_tok, args| -> Option<(String, String, String)> {
607             let inner = wrap_macro_args(context, args, shape)?;
608             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, false, inner.is_empty());
609             if lhs.len() + inner.len() + rhs.len() <= shape.width {
610                 return Some((lhs, inner, rhs));
611             }
612
613             let (lhs, rhs) = delim_token_to_str(context, delim_tok, shape, true, false);
614             let nested_shape = shape
615                 .block_indent(context.config.tab_spaces())
616                 .with_max_width(context.config);
617             let inner = wrap_macro_args(context, args, nested_shape)?;
618             Some((lhs, inner, rhs))
619         };
620
621         match *self {
622             MacroArgKind::MetaVariable(ty, ref name) => {
623                 Some(format!("${}:{}", name, ty.name.as_str()))
624             }
625             MacroArgKind::Repeat(delim_tok, ref args, ref another, ref tok) => {
626                 let (lhs, inner, rhs) = rewrite_delimited_inner(delim_tok, args)?;
627                 let another = another
628                     .as_ref()
629                     .and_then(|a| a.rewrite(context, shape, use_multiple_lines))
630                     .unwrap_or_else(|| "".to_owned());
631                 let repeat_tok = pprust::token_to_string(tok);
632
633                 Some(format!("${}{}{}{}{}", lhs, inner, rhs, another, repeat_tok))
634             }
635             MacroArgKind::Delimited(delim_tok, ref args) => {
636                 rewrite_delimited_inner(delim_tok, args)
637                     .map(|(lhs, inner, rhs)| format!("{}{}{}", lhs, inner, rhs))
638             }
639             MacroArgKind::Separator(ref sep, ref prefix) => Some(format!("{}{} ", prefix, sep)),
640             MacroArgKind::Other(ref inner, ref prefix) => Some(format!("{}{}", prefix, inner)),
641         }
642     }
643 }
644
645 #[derive(Debug, Clone)]
646 struct ParsedMacroArg {
647     kind: MacroArgKind,
648     span: Span,
649 }
650
651 impl ParsedMacroArg {
652     pub fn rewrite(
653         &self,
654         context: &RewriteContext,
655         shape: Shape,
656         use_multiple_lines: bool,
657     ) -> Option<String> {
658         self.kind.rewrite(context, shape, use_multiple_lines)
659     }
660 }
661
662 /// Parses macro arguments on macro def.
663 struct MacroArgParser {
664     /// Holds either a name of the next metavariable, a separator or a junk.
665     buf: String,
666     /// The start position on the current buffer.
667     lo: BytePos,
668     /// The first token of the current buffer.
669     start_tok: Token,
670     /// Set to true if we are parsing a metavariable or a repeat.
671     is_meta_var: bool,
672     /// The position of the last token.
673     hi: BytePos,
674     /// The last token parsed.
675     last_tok: Token,
676     /// Holds the parsed arguments.
677     result: Vec<ParsedMacroArg>,
678 }
679
680 fn last_tok(tt: &TokenTree) -> Token {
681     match *tt {
682         TokenTree::Token(_, ref t) => t.clone(),
683         TokenTree::Delimited(_, ref d) => d.close_token(),
684     }
685 }
686
687 impl MacroArgParser {
688     pub fn new() -> MacroArgParser {
689         MacroArgParser {
690             lo: BytePos(0),
691             hi: BytePos(0),
692             buf: String::new(),
693             is_meta_var: false,
694             last_tok: Token::Eof,
695             start_tok: Token::Eof,
696             result: vec![],
697         }
698     }
699
700     fn set_last_tok(&mut self, tok: &TokenTree) {
701         self.hi = tok.span().hi();
702         self.last_tok = last_tok(tok);
703     }
704
705     fn add_separator(&mut self) {
706         let prefix = if self.need_space_prefix() {
707             " ".to_owned()
708         } else {
709             "".to_owned()
710         };
711         self.result.push(ParsedMacroArg {
712             kind: MacroArgKind::Separator(self.buf.clone(), prefix),
713             span: mk_sp(self.lo, self.hi),
714         });
715         self.buf.clear();
716     }
717
718     fn add_other(&mut self) {
719         let prefix = if self.need_space_prefix() {
720             " ".to_owned()
721         } else {
722             "".to_owned()
723         };
724         self.result.push(ParsedMacroArg {
725             kind: MacroArgKind::Other(self.buf.clone(), prefix),
726             span: mk_sp(self.lo, self.hi),
727         });
728         self.buf.clear();
729     }
730
731     fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> {
732         match iter.next() {
733             Some(TokenTree::Token(sp, Token::Ident(ref ident, _))) => {
734                 self.result.push(ParsedMacroArg {
735                     kind: MacroArgKind::MetaVariable(*ident, self.buf.clone()),
736                     span: mk_sp(self.lo, sp.hi()),
737                 });
738
739                 self.buf.clear();
740                 self.is_meta_var = false;
741                 Some(())
742             }
743             _ => None,
744         }
745     }
746
747     fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
748         self.result.push(ParsedMacroArg {
749             kind: MacroArgKind::Delimited(delim, inner),
750             span,
751         });
752     }
753
754     // $($foo: expr),?
755     fn add_repeat(
756         &mut self,
757         inner: Vec<ParsedMacroArg>,
758         delim: DelimToken,
759         iter: &mut Cursor,
760         span: Span,
761     ) -> Option<()> {
762         let mut buffer = String::new();
763         let mut first = false;
764         let mut lo = span.lo();
765         let mut hi = span.hi();
766
767         // Parse '*', '+' or '?.
768         for tok in iter {
769             self.set_last_tok(&tok);
770             if first {
771                 first = false;
772                 lo = tok.span().lo();
773             }
774
775             match tok {
776                 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
777                 | TokenTree::Token(_, Token::Question)
778                 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
779                     break;
780                 }
781                 TokenTree::Token(sp, ref t) => {
782                     buffer.push_str(&pprust::token_to_string(t));
783                     hi = sp.hi();
784                 }
785                 _ => return None,
786             }
787         }
788
789         // There could be some random stuff between ')' and '*', '+' or '?'.
790         let another = if buffer.trim().is_empty() {
791             None
792         } else {
793             Some(Box::new(ParsedMacroArg {
794                 kind: MacroArgKind::Other(buffer, "".to_owned()),
795                 span: mk_sp(lo, hi),
796             }))
797         };
798
799         self.result.push(ParsedMacroArg {
800             kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
801             span: mk_sp(self.lo, self.hi),
802         });
803         Some(())
804     }
805
806     fn update_buffer(&mut self, lo: BytePos, t: &Token) {
807         if self.buf.is_empty() {
808             self.lo = lo;
809             self.start_tok = t.clone();
810         } else {
811             let needs_space = match next_space(&self.last_tok) {
812                 SpaceState::Ident => ident_like(t),
813                 SpaceState::Punctuation => !ident_like(t),
814                 SpaceState::Always => true,
815                 SpaceState::Never => false,
816             };
817             if force_space_before(t) || needs_space {
818                 self.buf.push(' ');
819             }
820         }
821
822         self.buf.push_str(&pprust::token_to_string(t));
823     }
824
825     fn need_space_prefix(&self) -> bool {
826         if self.result.is_empty() {
827             return false;
828         }
829
830         let last_arg = self.result.last().unwrap();
831         if let MacroArgKind::MetaVariable(..) = last_arg.kind {
832             if ident_like(&self.start_tok) {
833                 return true;
834             }
835             if self.start_tok == Token::Colon {
836                 return true;
837             }
838         }
839
840         if force_space_before(&self.start_tok) {
841             return true;
842         }
843
844         false
845     }
846
847     /// Returns a collection of parsed macro def's arguments.
848     pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
849         let mut iter = (tokens.into(): TokenStream).trees();
850
851         while let Some(ref tok) = iter.next() {
852             match tok {
853                 TokenTree::Token(sp, Token::Dollar) => {
854                     // We always want to add a separator before meta variables.
855                     if !self.buf.is_empty() {
856                         self.add_separator();
857                     }
858
859                     // Start keeping the name of this metavariable in the buffer.
860                     self.is_meta_var = true;
861                     self.lo = sp.lo();
862                     self.start_tok = Token::Dollar;
863                 }
864                 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
865                     self.add_meta_variable(&mut iter)?;
866                 }
867                 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
868                 TokenTree::Delimited(delimited_span, delimited) => {
869                     if !self.buf.is_empty() {
870                         if next_space(&self.last_tok) == SpaceState::Always {
871                             self.add_separator();
872                         } else {
873                             self.add_other();
874                         }
875                     }
876
877                     // Parse the stuff inside delimiters.
878                     let mut parser = MacroArgParser::new();
879                     parser.lo = delimited_span.open.lo();
880                     let delimited_arg = parser.parse(delimited.tts.clone())?;
881
882                     let span = delimited_span.entire();
883                     if self.is_meta_var {
884                         self.add_repeat(delimited_arg, delimited.delim, &mut iter, span)?;
885                         self.is_meta_var = false;
886                     } else {
887                         self.add_delimited(delimited_arg, delimited.delim, span);
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
1132             let line = if veto_trim || (kind.is_string() && !line.ends_with('\\')) {
1133                 veto_trim = kind.is_string() && !line.ends_with('\\');
1134                 trimmed = false;
1135                 line
1136             } else {
1137                 line.trim().to_owned()
1138             };
1139             trimmed_lines.push((trimmed, line, prefix_space_width));
1140
1141             // when computing the minimum, do not consider lines within a string
1142             match kind {
1143                 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
1144                 _ => prefix_space_width,
1145             }
1146         })
1147         .min()?;
1148
1149     Some(
1150         first_line + "\n" + &trimmed_lines
1151             .iter()
1152             .map(
1153                 |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
1154                     _ if !trimmed => line.to_owned(),
1155                     Some(original_indent_width) => {
1156                         let new_indent_width = indent.width() + original_indent_width
1157                             .saturating_sub(min_prefix_space_width);
1158                         let new_indent = Indent::from_width(context.config, new_indent_width);
1159                         format!("{}{}", new_indent.to_string(context.config), line)
1160                     }
1161                     None => String::new(),
1162                 },
1163             )
1164             .collect::<Vec<_>>()
1165             .join("\n"),
1166     )
1167 }
1168
1169 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1170     let mut width = 0;
1171     for c in s.chars() {
1172         match c {
1173             ' ' => width += 1,
1174             '\t' => width += context.config.tab_spaces(),
1175             _ => return width,
1176         }
1177     }
1178     width
1179 }
1180
1181 fn is_empty_line(s: &str) -> bool {
1182     s.is_empty() || s.chars().all(char::is_whitespace)
1183 }
1184
1185 // A very simple parser that just parses a macros 2.0 definition into its branches.
1186 // Currently we do not attempt to parse any further than that.
1187 #[derive(new)]
1188 struct MacroParser {
1189     toks: Cursor,
1190 }
1191
1192 impl MacroParser {
1193     // (`(` ... `)` `=>` `{` ... `}`)*
1194     fn parse(&mut self) -> Option<Macro> {
1195         let mut branches = vec![];
1196         while self.toks.look_ahead(1).is_some() {
1197             branches.push(self.parse_branch()?);
1198         }
1199
1200         Some(Macro { branches })
1201     }
1202
1203     // `(` ... `)` `=>` `{` ... `}`
1204     fn parse_branch(&mut self) -> Option<MacroBranch> {
1205         let tok = self.toks.next()?;
1206         let (lo, args_paren_kind) = match tok {
1207             TokenTree::Token(..) => return None,
1208             TokenTree::Delimited(delimited_span, ref d) => (delimited_span.open.lo(), d.delim),
1209         };
1210         let args = tok.joint().into();
1211         match self.toks.next()? {
1212             TokenTree::Token(_, Token::FatArrow) => {}
1213             _ => return None,
1214         }
1215         let (mut hi, body, whole_body) = match self.toks.next()? {
1216             TokenTree::Token(..) => return None,
1217             TokenTree::Delimited(delimited_span, _) => {
1218                 let data = delimited_span.entire().data();
1219                 (
1220                     data.hi,
1221                     Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1222                     delimited_span.entire(),
1223                 )
1224             }
1225         };
1226         if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1227             self.toks.next();
1228             hi = sp.hi();
1229         }
1230         Some(MacroBranch {
1231             span: mk_sp(lo, hi),
1232             args_paren_kind,
1233             args,
1234             body,
1235             whole_body,
1236         })
1237     }
1238 }
1239
1240 // A parsed macros 2.0 macro definition.
1241 struct Macro {
1242     branches: Vec<MacroBranch>,
1243 }
1244
1245 // FIXME: it would be more efficient to use references to the token streams
1246 // rather than clone them, if we can make the borrowing work out.
1247 struct MacroBranch {
1248     span: Span,
1249     args_paren_kind: DelimToken,
1250     args: ThinTokenStream,
1251     body: Span,
1252     whole_body: Span,
1253 }
1254
1255 impl MacroBranch {
1256     fn rewrite(
1257         &self,
1258         context: &RewriteContext,
1259         shape: Shape,
1260         multi_branch_style: bool,
1261     ) -> Option<String> {
1262         // Only attempt to format function-like macros.
1263         if self.args_paren_kind != DelimToken::Paren {
1264             // FIXME(#1539): implement for non-sugared macros.
1265             return None;
1266         }
1267
1268         // 5 = " => {"
1269         let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1270
1271         if multi_branch_style {
1272             result += " =>";
1273         }
1274
1275         if !context.config.format_macro_bodies() {
1276             result += " ";
1277             result += context.snippet(self.whole_body);
1278             return Some(result);
1279         }
1280
1281         // The macro body is the most interesting part. It might end up as various
1282         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1283         // parsed as regular Rust code (and note that these can be escaped using
1284         // `$$`). We'll try and format like an AST node, but we'll substitute
1285         // variables for new names with the same length first.
1286
1287         let old_body = context.snippet(self.body).trim();
1288         let (body_str, substs) = replace_names(old_body)?;
1289         let has_block_body = old_body.starts_with('{');
1290
1291         let mut config = context.config.clone();
1292         config.set().hide_parse_errors(true);
1293
1294         result += " {";
1295
1296         let body_indent = if has_block_body {
1297             shape.indent
1298         } else {
1299             shape.indent.block_indent(&config)
1300         };
1301         let new_width = config.max_width() - body_indent.width();
1302         config.set().max_width(new_width);
1303
1304         // First try to format as items, then as statements.
1305         let new_body = match ::format_snippet(&body_str, &config) {
1306             Some(new_body) => new_body,
1307             None => {
1308                 let new_width = new_width + config.tab_spaces();
1309                 config.set().max_width(new_width);
1310                 match ::format_code_block(&body_str, &config) {
1311                     Some(new_body) => new_body,
1312                     None => return None,
1313                 }
1314             }
1315         };
1316         let new_body = wrap_str(new_body, config.max_width(), shape)?;
1317
1318         // Indent the body since it is in a block.
1319         let indent_str = body_indent.to_string(&config);
1320         let mut new_body = LineClasses::new(new_body.trim_right())
1321             .fold(
1322                 (String::new(), true),
1323                 |(mut s, need_indent), (kind, ref l)| {
1324                     if !l.is_empty() && need_indent {
1325                         s += &indent_str;
1326                     }
1327                     (s + l + "\n", !kind.is_string() || l.ends_with('\\'))
1328                 },
1329             )
1330             .0;
1331
1332         // Undo our replacement of macro variables.
1333         // FIXME: this could be *much* more efficient.
1334         for (old, new) in &substs {
1335             if old_body.find(new).is_some() {
1336                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1337                 return None;
1338             }
1339             new_body = new_body.replace(new, old);
1340         }
1341
1342         if has_block_body {
1343             result += new_body.trim();
1344         } else if !new_body.is_empty() {
1345             result += "\n";
1346             result += &new_body;
1347             result += &shape.indent.to_string(&config);
1348         }
1349
1350         result += "}";
1351
1352         Some(result)
1353     }
1354 }
1355
1356 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1357 ///
1358 /// # Expected syntax
1359 ///
1360 /// ```ignore
1361 /// lazy_static! {
1362 ///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1363 ///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1364 ///     ...
1365 ///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1366 /// }
1367 /// ```
1368 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1369     let mut result = String::with_capacity(1024);
1370     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1371     let nested_shape = shape
1372         .block_indent(context.config.tab_spaces())
1373         .with_max_width(context.config);
1374
1375     result.push_str("lazy_static! {");
1376     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1377
1378     macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1379         match parser.$method($($arg,)*) {
1380             Ok(val) => {
1381                 if parser.sess.span_diagnostic.has_errors() {
1382                     parser.sess.span_diagnostic.reset_err_count();
1383                     return None;
1384                 } else {
1385                     val
1386                 }
1387             }
1388             Err(mut err) => {
1389                 err.cancel();
1390                 parser.sess.span_diagnostic.reset_err_count();
1391                 return None;
1392             }
1393         }
1394     }
1395
1396     while parser.token != Token::Eof {
1397         // Parse a `lazy_static!` item.
1398         let vis = ::utils::format_visibility(context, &parse_or!(parse_visibility, false));
1399         parser.eat_keyword(symbol::keywords::Static);
1400         parser.eat_keyword(symbol::keywords::Ref);
1401         let id = parse_or!(parse_ident);
1402         parser.eat(&Token::Colon);
1403         let ty = parse_or!(parse_ty);
1404         parser.eat(&Token::Eq);
1405         let expr = parse_or!(parse_expr);
1406         parser.eat(&Token::Semi);
1407
1408         // Rewrite as a static item.
1409         let mut stmt = String::with_capacity(128);
1410         stmt.push_str(&format!(
1411             "{}static ref {}: {} =",
1412             vis,
1413             id,
1414             ty.rewrite(context, nested_shape)?
1415         ));
1416         result.push_str(&::expr::rewrite_assign_rhs(
1417             context,
1418             stmt,
1419             &*expr,
1420             nested_shape.sub_width(1)?,
1421         )?);
1422         result.push(';');
1423         if parser.token != Token::Eof {
1424             result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1425         }
1426     }
1427
1428     result.push_str(&shape.indent.to_string_with_newline(context.config));
1429     result.push('}');
1430
1431     Some(result)
1432 }