]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Remove unreachable! from macros.rs
[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     // `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     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) -> Option<()> {
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                 Some(())
701             }
702             _ => None,
703         }
704     }
705
706     fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
707         self.result.push(ParsedMacroArg {
708             kind: MacroArgKind::Delimited(delim, inner),
709             span,
710         });
711     }
712
713     // $($foo: expr),?
714     fn add_repeat(
715         &mut self,
716         inner: Vec<ParsedMacroArg>,
717         delim: DelimToken,
718         iter: &mut Cursor,
719         span: Span,
720     ) -> Option<()> {
721         let mut buffer = String::new();
722         let mut first = false;
723         let mut lo = span.lo();
724         let mut hi = span.hi();
725
726         // Parse '*', '+' or '?.
727         while let Some(ref tok) = iter.next() {
728             self.set_last_tok(tok);
729             if first {
730                 first = false;
731                 lo = tok.span().lo();
732             }
733
734             match tok {
735                 TokenTree::Token(_, Token::BinOp(BinOpToken::Plus))
736                 | TokenTree::Token(_, Token::Question)
737                 | TokenTree::Token(_, Token::BinOp(BinOpToken::Star)) => {
738                     break;
739                 }
740                 TokenTree::Token(sp, ref t) => {
741                     buffer.push_str(&pprust::token_to_string(t));
742                     hi = sp.hi();
743                 }
744                 _ => return None,
745             }
746         }
747
748         // There could be some random stuff between ')' and '*', '+' or '?'.
749         let another = if buffer.trim().is_empty() {
750             None
751         } else {
752             Some(Box::new(ParsedMacroArg {
753                 kind: MacroArgKind::Other(buffer, "".to_owned()),
754                 span: mk_sp(lo, hi),
755             }))
756         };
757
758         self.result.push(ParsedMacroArg {
759             kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
760             span: mk_sp(self.lo, self.hi),
761         });
762         Some(())
763     }
764
765     fn update_buffer(&mut self, lo: BytePos, t: &Token) {
766         if self.buf.is_empty() {
767             self.lo = lo;
768             self.start_tok = t.clone();
769         } else {
770             let needs_space = match next_space(&self.last_tok) {
771                 SpaceState::Ident => ident_like(t),
772                 SpaceState::Punctuation => !ident_like(t),
773                 SpaceState::Always => true,
774                 SpaceState::Never => false,
775             };
776             if force_space_before(t) || needs_space {
777                 self.buf.push(' ');
778             }
779         }
780
781         self.buf.push_str(&pprust::token_to_string(t));
782     }
783
784     fn need_space_prefix(&self) -> bool {
785         if self.result.is_empty() {
786             return false;
787         }
788
789         let last_arg = self.result.last().unwrap();
790         if let MacroArgKind::MetaVariable(..) = last_arg.kind {
791             if ident_like(&self.start_tok) {
792                 return true;
793             }
794             if self.start_tok == Token::Colon {
795                 return true;
796             }
797         }
798
799         if force_space_before(&self.start_tok) {
800             return true;
801         }
802
803         false
804     }
805
806     /// Returns a collection of parsed macro def's arguments.
807     pub fn parse(mut self, tokens: ThinTokenStream) -> Option<Vec<ParsedMacroArg>> {
808         let mut iter = (tokens.into(): TokenStream).trees();
809
810         while let Some(ref tok) = iter.next() {
811             match tok {
812                 TokenTree::Token(sp, Token::Dollar) => {
813                     // We always want to add a separator before meta variables.
814                     if !self.buf.is_empty() {
815                         self.add_separator();
816                     }
817
818                     // Start keeping the name of this metavariable in the buffer.
819                     self.is_meta_var = true;
820                     self.lo = sp.lo();
821                     self.start_tok = Token::Dollar;
822                 }
823                 TokenTree::Token(_, Token::Colon) if self.is_meta_var => {
824                     self.add_meta_variable(&mut iter)?;
825                 }
826                 TokenTree::Token(sp, ref t) => self.update_buffer(sp.lo(), t),
827                 TokenTree::Delimited(sp, delimited) => {
828                     if !self.buf.is_empty() {
829                         if next_space(&self.last_tok) == SpaceState::Always {
830                             self.add_separator();
831                         } else {
832                             self.add_other();
833                         }
834                     }
835
836                     // Parse the stuff inside delimiters.
837                     let mut parser = MacroArgParser::new();
838                     parser.lo = sp.lo();
839                     let delimited_arg = parser.parse(delimited.tts.clone())?;
840
841                     if self.is_meta_var {
842                         self.add_repeat(delimited_arg, delimited.delim, &mut iter, *sp)?;
843                     } else {
844                         self.add_delimited(delimited_arg, delimited.delim, *sp);
845                     }
846                 }
847             }
848
849             self.set_last_tok(tok);
850         }
851
852         // We are left with some stuff in the buffer. Since there is nothing
853         // left to separate, add this as `Other`.
854         if !self.buf.is_empty() {
855             self.add_other();
856         }
857
858         Some(self.result)
859     }
860 }
861
862 fn wrap_macro_args(
863     context: &RewriteContext,
864     args: &[ParsedMacroArg],
865     shape: Shape,
866 ) -> Option<String> {
867     wrap_macro_args_inner(context, args, shape, false)
868         .or_else(|| wrap_macro_args_inner(context, args, shape, true))
869 }
870
871 fn wrap_macro_args_inner(
872     context: &RewriteContext,
873     args: &[ParsedMacroArg],
874     shape: Shape,
875     use_multiple_lines: bool,
876 ) -> Option<String> {
877     let mut result = String::with_capacity(128);
878     let mut iter = args.iter().peekable();
879     let indent_str = shape.indent.to_string_with_newline(context.config);
880
881     while let Some(ref arg) = iter.next() {
882         result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
883
884         if use_multiple_lines
885             && (arg.kind.ends_with_space() || iter.peek().map_or(false, |a| a.kind.has_meta_var()))
886         {
887             if arg.kind.ends_with_space() {
888                 result.pop();
889             }
890             result.push_str(&indent_str);
891         } else if let Some(ref next_arg) = iter.peek() {
892             let space_before_dollar =
893                 !arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
894             let space_before_brace = next_arg.kind.starts_with_brace();
895             if space_before_dollar || space_before_brace {
896                 result.push(' ');
897             }
898         }
899     }
900
901     if !use_multiple_lines && result.len() >= shape.width {
902         None
903     } else {
904         Some(result)
905     }
906 }
907
908 // This is a bit sketchy. The token rules probably need tweaking, but it works
909 // for some common cases. I hope the basic logic is sufficient. Note that the
910 // meaning of some tokens is a bit different here from usual Rust, e.g., `*`
911 // and `(`/`)` have special meaning.
912 //
913 // We always try and format on one line.
914 // FIXME: Use multi-line when every thing does not fit on one line.
915 fn format_macro_args(
916     context: &RewriteContext,
917     toks: ThinTokenStream,
918     shape: Shape,
919 ) -> Option<String> {
920     let parsed_args = MacroArgParser::new().parse(toks)?;
921     wrap_macro_args(context, &parsed_args, shape)
922 }
923
924 // We should insert a space if the next token is a:
925 #[derive(Copy, Clone, PartialEq)]
926 enum SpaceState {
927     Never,
928     Punctuation,
929     Ident, // Or ident/literal-like thing.
930     Always,
931 }
932
933 fn force_space_before(tok: &Token) -> bool {
934     debug!("tok: force_space_before {:?}", tok);
935
936     match *tok {
937         Token::Eq
938         | Token::Lt
939         | Token::Le
940         | Token::EqEq
941         | Token::Ne
942         | Token::Ge
943         | Token::Gt
944         | Token::AndAnd
945         | Token::OrOr
946         | Token::Not
947         | Token::Tilde
948         | Token::BinOpEq(_)
949         | Token::At
950         | Token::RArrow
951         | Token::LArrow
952         | Token::FatArrow
953         | Token::BinOp(_)
954         | Token::Pound
955         | Token::Dollar => true,
956         _ => false,
957     }
958 }
959
960 fn ident_like(tok: &Token) -> bool {
961     match *tok {
962         Token::Ident(_) | Token::Literal(..) | Token::Lifetime(_) => true,
963         _ => false,
964     }
965 }
966
967 fn next_space(tok: &Token) -> SpaceState {
968     debug!("next_space: {:?}", tok);
969
970     match *tok {
971         Token::Not
972         | Token::BinOp(BinOpToken::And)
973         | Token::Tilde
974         | Token::At
975         | Token::Comma
976         | Token::Dot
977         | Token::DotDot
978         | Token::DotDotDot
979         | Token::DotDotEq
980         | Token::DotEq
981         | Token::Question => SpaceState::Punctuation,
982
983         Token::ModSep
984         | Token::Pound
985         | Token::Dollar
986         | Token::OpenDelim(_)
987         | Token::CloseDelim(_)
988         | Token::Whitespace => SpaceState::Never,
989
990         Token::Literal(..) | Token::Ident(_) | Token::Lifetime(_) => SpaceState::Ident,
991
992         _ => SpaceState::Always,
993     }
994 }
995
996 /// Tries to convert a macro use into a short hand try expression. Returns None
997 /// when the macro is not an instance of try! (or parsing the inner expression
998 /// failed).
999 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
1000     if &format!("{}", mac.node.path)[..] == "try" {
1001         let ts: TokenStream = mac.node.tts.clone().into();
1002         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1003
1004         Some(ast::Expr {
1005             id: ast::NodeId::new(0), // dummy value
1006             node: ast::ExprKind::Try(parser.parse_expr().ok()?),
1007             span: mac.span, // incorrect span, but shouldn't matter too much
1008             attrs: ThinVec::new(),
1009         })
1010     } else {
1011         None
1012     }
1013 }
1014
1015 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
1016     let snippet = context.snippet(mac.span);
1017     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
1018     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
1019     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
1020
1021     if paren_pos < bracket_pos && paren_pos < brace_pos {
1022         MacroStyle::Parens
1023     } else if bracket_pos < brace_pos {
1024         MacroStyle::Brackets
1025     } else {
1026         MacroStyle::Braces
1027     }
1028 }
1029
1030 /// Indent each line according to the specified `indent`.
1031 /// e.g.
1032 ///
1033 /// ```rust,ignore
1034 /// foo!{
1035 /// x,
1036 /// y,
1037 /// foo(
1038 ///     a,
1039 ///     b,
1040 ///     c,
1041 /// ),
1042 /// }
1043 /// ```
1044 ///
1045 /// will become
1046 ///
1047 /// ```rust,ignore
1048 /// foo!{
1049 ///     x,
1050 ///     y,
1051 ///     foo(
1052 ///         a,
1053 ///         b,
1054 ///         c,
1055 ///     ),
1056 /// }
1057 /// ```
1058 fn indent_macro_snippet(
1059     context: &RewriteContext,
1060     macro_str: &str,
1061     indent: Indent,
1062 ) -> Option<String> {
1063     let mut lines = macro_str.lines();
1064     let first_line = lines.next().map(|s| s.trim_right())?;
1065     let mut trimmed_lines = Vec::with_capacity(16);
1066
1067     let min_prefix_space_width = lines
1068         .filter_map(|line| {
1069             let prefix_space_width = if is_empty_line(line) {
1070                 None
1071             } else {
1072                 Some(get_prefix_space_width(context, line))
1073             };
1074             trimmed_lines.push((line.trim(), prefix_space_width));
1075             prefix_space_width
1076         })
1077         .min()?;
1078
1079     Some(
1080         String::from(first_line) + "\n"
1081             + &trimmed_lines
1082                 .iter()
1083                 .map(|&(line, prefix_space_width)| match prefix_space_width {
1084                     Some(original_indent_width) => {
1085                         let new_indent_width = indent.width()
1086                             + original_indent_width
1087                                 .checked_sub(min_prefix_space_width)
1088                                 .unwrap_or(0);
1089                         let new_indent = Indent::from_width(context.config, new_indent_width);
1090                         format!("{}{}", new_indent.to_string(context.config), line.trim())
1091                     }
1092                     None => String::new(),
1093                 })
1094                 .collect::<Vec<_>>()
1095                 .join("\n"),
1096     )
1097 }
1098
1099 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
1100     let mut width = 0;
1101     for c in s.chars() {
1102         match c {
1103             ' ' => width += 1,
1104             '\t' => width += context.config.tab_spaces(),
1105             _ => return width,
1106         }
1107     }
1108     width
1109 }
1110
1111 fn is_empty_line(s: &str) -> bool {
1112     s.is_empty() || s.chars().all(char::is_whitespace)
1113 }
1114
1115 // A very simple parser that just parses a macros 2.0 definition into its branches.
1116 // Currently we do not attempt to parse any further than that.
1117 #[derive(new)]
1118 struct MacroParser {
1119     toks: Cursor,
1120 }
1121
1122 impl MacroParser {
1123     // (`(` ... `)` `=>` `{` ... `}`)*
1124     fn parse(&mut self) -> Option<Macro> {
1125         let mut branches = vec![];
1126         while self.toks.look_ahead(1).is_some() {
1127             branches.push(self.parse_branch()?);
1128         }
1129
1130         Some(Macro { branches })
1131     }
1132
1133     // `(` ... `)` `=>` `{` ... `}`
1134     fn parse_branch(&mut self) -> Option<MacroBranch> {
1135         let tok = self.toks.next()?;
1136         let (lo, args_paren_kind) = match tok {
1137             TokenTree::Token(..) => return None,
1138             TokenTree::Delimited(sp, ref d) => (sp.lo(), d.delim),
1139         };
1140         let args = tok.joint().into();
1141         match self.toks.next()? {
1142             TokenTree::Token(_, Token::FatArrow) => {}
1143             _ => return None,
1144         }
1145         let (mut hi, body) = match self.toks.next()? {
1146             TokenTree::Token(..) => return None,
1147             TokenTree::Delimited(sp, _) => {
1148                 let data = sp.data();
1149                 (
1150                     data.hi,
1151                     Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
1152                 )
1153             }
1154         };
1155         if let Some(TokenTree::Token(sp, Token::Semi)) = self.toks.look_ahead(0) {
1156             self.toks.next();
1157             hi = sp.hi();
1158         }
1159         Some(MacroBranch {
1160             span: mk_sp(lo, hi),
1161             args_paren_kind,
1162             args,
1163             body,
1164         })
1165     }
1166 }
1167
1168 // A parsed macros 2.0 macro definition.
1169 struct Macro {
1170     branches: Vec<MacroBranch>,
1171 }
1172
1173 // FIXME: it would be more efficient to use references to the token streams
1174 // rather than clone them, if we can make the borrowing work out.
1175 struct MacroBranch {
1176     span: Span,
1177     args_paren_kind: DelimToken,
1178     args: ThinTokenStream,
1179     body: Span,
1180 }
1181
1182 impl MacroBranch {
1183     fn rewrite(
1184         &self,
1185         context: &RewriteContext,
1186         shape: Shape,
1187         multi_branch_style: bool,
1188     ) -> Option<String> {
1189         // Only attempt to format function-like macros.
1190         if self.args_paren_kind != DelimToken::Paren {
1191             // FIXME(#1539): implement for non-sugared macros.
1192             return None;
1193         }
1194
1195         // 5 = " => {"
1196         let mut result = format_macro_args(context, self.args.clone(), shape.sub_width(5)?)?;
1197
1198         if multi_branch_style {
1199             result += " =>";
1200         }
1201
1202         // The macro body is the most interesting part. It might end up as various
1203         // AST nodes, but also has special variables (e.g, `$foo`) which can't be
1204         // parsed as regular Rust code (and note that these can be escaped using
1205         // `$$`). We'll try and format like an AST node, but we'll substitute
1206         // variables for new names with the same length first.
1207
1208         let old_body = context.snippet(self.body).trim();
1209         let (body_str, substs) = replace_names(old_body)?;
1210
1211         let mut config = context.config.clone();
1212         config.set().hide_parse_errors(true);
1213
1214         result += " {";
1215
1216         let has_block_body = old_body.starts_with('{');
1217
1218         let body_indent = if has_block_body {
1219             shape.indent
1220         } else {
1221             // We'll hack the indent below, take this into account when formatting,
1222             let body_indent = shape.indent.block_indent(&config);
1223             let new_width = config.max_width() - body_indent.width();
1224             config.set().max_width(new_width);
1225             body_indent
1226         };
1227
1228         // First try to format as items, then as statements.
1229         let new_body = match ::format_snippet(&body_str, &config) {
1230             Some(new_body) => new_body,
1231             None => match ::format_code_block(&body_str, &config) {
1232                 Some(new_body) => new_body,
1233                 None => return None,
1234             },
1235         };
1236         let new_body = wrap_str(new_body, config.max_width(), shape)?;
1237
1238         // Indent the body since it is in a block.
1239         let indent_str = body_indent.to_string(&config);
1240         let mut new_body = new_body
1241             .trim_right()
1242             .lines()
1243             .fold(String::new(), |mut s, l| {
1244                 if !l.is_empty() {
1245                     s += &indent_str;
1246                 }
1247                 s + l + "\n"
1248             });
1249
1250         // Undo our replacement of macro variables.
1251         // FIXME: this could be *much* more efficient.
1252         for (old, new) in &substs {
1253             if old_body.find(new).is_some() {
1254                 debug!("rewrite_macro_def: bailing matching variable: `{}`", new);
1255                 return None;
1256             }
1257             new_body = new_body.replace(new, old);
1258         }
1259
1260         if has_block_body {
1261             result += new_body.trim();
1262         } else if !new_body.is_empty() {
1263             result += "\n";
1264             result += &new_body;
1265             result += &shape.indent.to_string(&config);
1266         }
1267
1268         result += "}";
1269
1270         Some(result)
1271     }
1272 }
1273
1274 /// Format `lazy_static!` from https://crates.io/crates/lazy_static.
1275 ///
1276 /// # Expected syntax
1277 ///
1278 /// ```ignore
1279 /// lazy_static! {
1280 ///     [pub] static ref NAME_1: TYPE_1 = EXPR_1;
1281 ///     [pub] static ref NAME_2: TYPE_2 = EXPR_2;
1282 ///     ...
1283 ///     [pub] static ref NAME_N: TYPE_N = EXPR_N;
1284 /// }
1285 /// ```
1286 fn format_lazy_static(context: &RewriteContext, shape: Shape, ts: &TokenStream) -> Option<String> {
1287     let mut result = String::with_capacity(1024);
1288     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
1289     let nested_shape = shape.block_indent(context.config.tab_spaces());
1290
1291     result.push_str("lazy_static! {");
1292     result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1293
1294     macro parse_or($method:ident $(,)* $($arg:expr),* $(,)*) {
1295         match parser.$method($($arg,)*) {
1296             Ok(val) => {
1297                 if parser.sess.span_diagnostic.has_errors() {
1298                     parser.sess.span_diagnostic.reset_err_count();
1299                     return None;
1300                 } else {
1301                     val
1302                 }
1303             }
1304             Err(mut err) => {
1305                 err.cancel();
1306                 parser.sess.span_diagnostic.reset_err_count();
1307                 return None;
1308             }
1309         }
1310     }
1311
1312     while parser.token != Token::Eof {
1313         // Parse a `lazy_static!` item.
1314         let vis = ::utils::format_visibility(&parse_or!(parse_visibility, false));
1315         parser.eat_keyword(symbol::keywords::Static);
1316         parser.eat_keyword(symbol::keywords::Ref);
1317         let id = parse_or!(parse_ident);
1318         parser.eat(&Token::Colon);
1319         let ty = parse_or!(parse_ty);
1320         parser.eat(&Token::Eq);
1321         let expr = parse_or!(parse_expr);
1322         parser.eat(&Token::Semi);
1323
1324         // Rewrite as a static item.
1325         let mut stmt = String::with_capacity(128);
1326         stmt.push_str(&format!(
1327             "{}static ref {}: {} =",
1328             vis,
1329             id,
1330             ty.rewrite(context, nested_shape)?
1331         ));
1332         result.push_str(&::expr::rewrite_assign_rhs(
1333             context,
1334             stmt,
1335             &*expr,
1336             nested_shape.sub_width(1)?,
1337         )?);
1338         result.push(';');
1339         if parser.token != Token::Eof {
1340             result.push_str(&nested_shape.indent.to_string_with_newline(context.config));
1341         }
1342     }
1343
1344     result.push_str(&shape.indent.to_string_with_newline(context.config));
1345     result.push('}');
1346
1347     Some(result)
1348 }