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