]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Preserve trailing comma of macro invocation
[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::codemap::BytePos;
24 use syntax::parse::token::Token;
25 use syntax::parse::new_parser_from_tts;
26 use syntax::tokenstream::TokenStream;
27 use syntax::symbol;
28 use syntax::util::ThinVec;
29
30 use Shape;
31 use codemap::SpanUtils;
32 use rewrite::{Rewrite, RewriteContext};
33 use expr::{rewrite_call_inner, rewrite_array};
34 use comment::{FindUncommented, contains_comment};
35 use utils::mk_sp;
36
37 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
38
39 // FIXME: use the enum from libsyntax?
40 #[derive(Clone, Copy, PartialEq, Eq)]
41 enum MacroStyle {
42     Parens,
43     Brackets,
44     Braces,
45 }
46
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub enum MacroPosition {
49     Item,
50     Statement,
51     Expression,
52 }
53
54 impl MacroStyle {
55     fn opener(&self) -> &'static str {
56         match *self {
57             MacroStyle::Parens => "(",
58             MacroStyle::Brackets => "[",
59             MacroStyle::Braces => "{",
60         }
61     }
62 }
63
64 pub fn rewrite_macro(
65     mac: &ast::Mac,
66     extra_ident: Option<ast::Ident>,
67     context: &RewriteContext,
68     shape: Shape,
69     position: MacroPosition,
70 ) -> Option<String> {
71     let mut context = &mut context.clone();
72     context.inside_macro = true;
73     if context.config.use_try_shorthand() {
74         if let Some(expr) = convert_try_mac(mac, context) {
75             return expr.rewrite(context, shape);
76         }
77     }
78
79     let original_style = macro_style(mac, context);
80
81     let macro_name = match extra_ident {
82         None => format!("{}!", mac.node.path),
83         Some(ident) => {
84             if ident == symbol::keywords::Invalid.ident() {
85                 format!("{}!", mac.node.path)
86             } else {
87                 format!("{}! {}", mac.node.path, ident)
88             }
89         }
90     };
91
92     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
93         MacroStyle::Brackets
94     } else {
95         original_style
96     };
97
98     let ts: TokenStream = mac.node.tts.clone().into();
99     if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
100         return match style {
101             MacroStyle::Parens if position == MacroPosition::Item => {
102                 Some(format!("{}();", macro_name))
103             }
104             MacroStyle::Parens => Some(format!("{}()", macro_name)),
105             MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
106             MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
107         };
108     }
109
110     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
111     let mut expr_vec = Vec::new();
112     let mut vec_with_semi = false;
113     let mut trailing_comma = false;
114
115     if MacroStyle::Braces != style {
116         loop {
117             let expr = match parser.parse_expr() {
118                 Ok(expr) => {
119                     // Recovered errors.
120                     if context.parse_session.span_diagnostic.has_errors() {
121                         return Some(context.snippet(mac.span));
122                     }
123
124                     expr
125                 }
126                 Err(mut e) => {
127                     e.cancel();
128                     return Some(context.snippet(mac.span));
129                 }
130             };
131
132             expr_vec.push(expr);
133
134             match parser.token {
135                 Token::Eof => break,
136                 Token::Comma => (),
137                 Token::Semi => {
138                     // Try to parse `vec![expr; expr]`
139                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
140                         parser.bump();
141                         if parser.token != Token::Eof {
142                             match parser.parse_expr() {
143                                 Ok(expr) => {
144                                     if context.parse_session.span_diagnostic.has_errors() {
145                                         return None;
146                                     }
147                                     expr_vec.push(expr);
148                                     parser.bump();
149                                     if parser.token == Token::Eof && expr_vec.len() == 2 {
150                                         vec_with_semi = true;
151                                         break;
152                                     }
153                                 }
154                                 Err(mut e) => e.cancel(),
155                             }
156                         }
157                     }
158                     return None;
159                 }
160                 _ => return None,
161             }
162
163             parser.bump();
164
165             if parser.token == Token::Eof {
166                 trailing_comma = true;
167                 break;
168             }
169         }
170     }
171
172     match style {
173         MacroStyle::Parens => {
174             // Format macro invocation as function call, forcing no trailing
175             // comma because not all macros support them.
176             let rw = rewrite_call_inner(
177                 context,
178                 &macro_name,
179                 &expr_vec.iter().map(|e| &**e).collect::<Vec<_>>()[..],
180                 mac.span,
181                 shape,
182                 context.config.fn_call_width(),
183                 trailing_comma,
184             );
185             rw.ok().map(|rw| match position {
186                 MacroPosition::Item => format!("{};", rw),
187                 _ => rw,
188             })
189         }
190         MacroStyle::Brackets => {
191             let mac_shape = try_opt!(shape.offset_left(macro_name.len()));
192             // Handle special case: `vec![expr; expr]`
193             if vec_with_semi {
194                 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
195                     ("[ ", " ]")
196                 } else {
197                     ("[", "]")
198                 };
199                 // 6 = `vec!` + `; `
200                 let total_overhead = lbr.len() + rbr.len() + 6;
201                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
202                 let lhs = try_opt!(expr_vec[0].rewrite(context, nested_shape));
203                 let rhs = try_opt!(expr_vec[1].rewrite(context, nested_shape));
204                 if !lhs.contains('\n') && !rhs.contains('\n') &&
205                     lhs.len() + rhs.len() + total_overhead <= shape.width
206                 {
207                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
208                 } else {
209                     Some(format!(
210                         "{}{}\n{}{};\n{}{}\n{}{}",
211                         macro_name,
212                         lbr,
213                         nested_shape.indent.to_string(context.config),
214                         lhs,
215                         nested_shape.indent.to_string(context.config),
216                         rhs,
217                         shape.indent.to_string(context.config),
218                         rbr
219                     ))
220                 }
221             } else {
222                 // If we are rewriting `vec!` macro or other special macros,
223                 // then we can rewrite this as an usual array literal.
224                 // Otherwise, we must preserve the original existence of trailing comma.
225                 if FORCED_BRACKET_MACROS.contains(&&macro_name.as_str()) {
226                     context.inside_macro = false;
227                     trailing_comma = false;
228                 }
229                 let rewrite = try_opt!(rewrite_array(
230                     expr_vec.iter().map(|x| &**x),
231                     mk_sp(
232                         context
233                             .codemap
234                             .span_after(mac.span, original_style.opener()),
235                         mac.span.hi - BytePos(1),
236                     ),
237                     context,
238                     mac_shape,
239                     trailing_comma,
240                 ));
241
242                 Some(format!("{}{}", macro_name, rewrite))
243             }
244         }
245         MacroStyle::Braces => {
246             // Skip macro invocations with braces, for now.
247             None
248         }
249     }
250 }
251
252 /// Tries to convert a macro use into a short hand try expression. Returns None
253 /// when the macro is not an instance of try! (or parsing the inner expression
254 /// failed).
255 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
256     if &format!("{}", mac.node.path)[..] == "try" {
257         let ts: TokenStream = mac.node.tts.clone().into();
258         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
259
260         Some(ast::Expr {
261             id: ast::NodeId::new(0), // dummy value
262             node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
263             span: mac.span, // incorrect span, but shouldn't matter too much
264             attrs: ThinVec::new(),
265         })
266     } else {
267         None
268     }
269 }
270
271 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
272     let snippet = context.snippet(mac.span);
273     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
274     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
275     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
276
277     if paren_pos < bracket_pos && paren_pos < brace_pos {
278         MacroStyle::Parens
279     } else if bracket_pos < brace_pos {
280         MacroStyle::Brackets
281     } else {
282         MacroStyle::Braces
283     }
284 }