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