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