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