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