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