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