]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
d2709bed809e5057124715b0f26f260421289b50
[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 // reformated.
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 syntax::ast;
23 use syntax::parse::token::Token;
24 use syntax::parse::tts_to_parser;
25 use syntax::codemap::{mk_sp, BytePos};
26
27 use Indent;
28 use rewrite::RewriteContext;
29 use expr::{rewrite_call, rewrite_array};
30 use comment::{FindUncommented, contains_comment};
31 use utils::{CodeMapSpanUtils, wrap_str};
32
33 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
34
35 // FIXME: use the enum from libsyntax?
36 #[derive(Clone, Copy, PartialEq, Eq)]
37 enum MacroStyle {
38     Parens,
39     Brackets,
40     Braces,
41 }
42
43 impl MacroStyle {
44     fn opener(&self) -> &'static str {
45         match *self {
46             MacroStyle::Parens => "(",
47             MacroStyle::Brackets => "[",
48             MacroStyle::Braces => "{",
49         }
50     }
51 }
52
53 pub fn rewrite_macro(mac: &ast::Mac,
54                      extra_ident: Option<ast::Ident>,
55                      context: &RewriteContext,
56                      width: usize,
57                      offset: Indent)
58                      -> Option<String> {
59     let original_style = macro_style(mac, context);
60     let macro_name = match extra_ident {
61         None | Some(ast::Ident { name: ast::Name(0), .. }) => format!("{}!", mac.node.path),
62         Some(ident) => format!("{}! {}", mac.node.path, ident),
63     };
64     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
65         MacroStyle::Brackets
66     } else {
67         original_style
68     };
69
70     if mac.node.tts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
71         return match style {
72             MacroStyle::Parens => Some(format!("{}()", macro_name)),
73             MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
74             MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
75         };
76     }
77
78     let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone(), Vec::new());
79     let mut expr_vec = Vec::new();
80
81     if MacroStyle::Braces != style {
82         loop {
83             expr_vec.push(match parser.parse_expr() {
84                 Ok(expr) => expr,
85                 Err(..) => return None,
86             });
87
88             match parser.token {
89                 Token::Eof => break,
90                 Token::Comma => (),
91                 _ => return None,
92             }
93
94             let _ = parser.bump();
95
96             if parser.token == Token::Eof {
97                 return None;
98             }
99         }
100     }
101
102     match style {
103         MacroStyle::Parens => {
104             // Format macro invocation as function call.
105             rewrite_call(context, &macro_name, &expr_vec, mac.span, width, offset)
106         }
107         MacroStyle::Brackets => {
108             // Format macro invocation as array literal.
109             let extra_offset = macro_name.len();
110             let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
111                                                  mk_sp(context.codemap.span_after(mac.span,
112                                                                   original_style.opener()),
113                                                        mac.span.hi - BytePos(1)),
114                                                  context,
115                                                  try_opt!(width.checked_sub(extra_offset)),
116                                                  offset + extra_offset));
117
118             Some(format!("{}{}", macro_name, rewrite))
119         }
120         MacroStyle::Braces => {
121             // Skip macro invocations with braces, for now.
122             wrap_str(context.snippet(mac.span),
123                      context.config.max_width,
124                      width,
125                      offset)
126         }
127     }
128 }
129
130 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
131     let snippet = context.snippet(mac.span);
132     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
133     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
134     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
135
136     if paren_pos < bracket_pos && paren_pos < brace_pos {
137         MacroStyle::Parens
138     } else if bracket_pos < brace_pos {
139         MacroStyle::Brackets
140     } else {
141         MacroStyle::Braces
142     }
143 }