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