]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #1925 from topecongiro/enhance-comment
[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::new_parser_from_tts;
25 use syntax::parse::token::Token;
26 use syntax::symbol;
27 use syntax::tokenstream::TokenStream;
28 use syntax::util::ThinVec;
29
30 use {Indent, Shape};
31 use codemap::SpanUtils;
32 use comment::{contains_comment, FindUncommented};
33 use expr::{rewrite_array, rewrite_call_inner};
34 use rewrite::{Rewrite, RewriteContext};
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 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) => if ident == symbol::keywords::Invalid.ident() {
84             format!("{}!", mac.node.path)
85         } else {
86             format!("{}! {}", mac.node.path, ident)
87         },
88     };
89
90     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
91         MacroStyle::Brackets
92     } else {
93         original_style
94     };
95
96     let ts: TokenStream = mac.node.tts.clone().into();
97     if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
98         return match style {
99             MacroStyle::Parens if position == MacroPosition::Item => {
100                 Some(format!("{}();", macro_name))
101             }
102             MacroStyle::Parens => Some(format!("{}()", macro_name)),
103             MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
104             MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
105         };
106     }
107
108     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
109     let mut expr_vec = Vec::new();
110     let mut vec_with_semi = false;
111     let mut trailing_comma = false;
112
113     if MacroStyle::Braces != style {
114         loop {
115             let expr = match parser.parse_expr() {
116                 Ok(expr) => {
117                     // Recovered errors.
118                     if context.parse_session.span_diagnostic.has_errors() {
119                         return indent_macro_snippet(
120                             context,
121                             &context.snippet(mac.span),
122                             shape.indent,
123                         );
124                     }
125
126                     expr
127                 }
128                 Err(mut e) => {
129                     e.cancel();
130                     return indent_macro_snippet(context, &context.snippet(mac.span), shape.indent);
131                 }
132             };
133
134             expr_vec.push(expr);
135
136             match parser.token {
137                 Token::Eof => break,
138                 Token::Comma => (),
139                 Token::Semi => {
140                     // Try to parse `vec![expr; expr]`
141                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
142                         parser.bump();
143                         if parser.token != Token::Eof {
144                             match parser.parse_expr() {
145                                 Ok(expr) => {
146                                     if context.parse_session.span_diagnostic.has_errors() {
147                                         return None;
148                                     }
149                                     expr_vec.push(expr);
150                                     parser.bump();
151                                     if parser.token == Token::Eof && expr_vec.len() == 2 {
152                                         vec_with_semi = true;
153                                         break;
154                                     }
155                                 }
156                                 Err(mut e) => e.cancel(),
157                             }
158                         }
159                     }
160                     return None;
161                 }
162                 _ => return None,
163             }
164
165             parser.bump();
166
167             if parser.token == Token::Eof {
168                 trailing_comma = true;
169                 break;
170             }
171         }
172     }
173
174     match style {
175         MacroStyle::Parens => {
176             // Format macro invocation as function call, forcing no trailing
177             // comma because not all macros support them.
178             let rw = rewrite_call_inner(
179                 context,
180                 &macro_name,
181                 &expr_vec.iter().map(|e| &**e).collect::<Vec<_>>()[..],
182                 mac.span,
183                 shape,
184                 context.config.fn_call_width(),
185                 trailing_comma,
186             );
187             rw.ok().map(|rw| match position {
188                 MacroPosition::Item => format!("{};", rw),
189                 _ => rw,
190             })
191         }
192         MacroStyle::Brackets => {
193             let mac_shape = try_opt!(shape.offset_left(macro_name.len()));
194             // Handle special case: `vec![expr; expr]`
195             if vec_with_semi {
196                 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
197                     ("[ ", " ]")
198                 } else {
199                     ("[", "]")
200                 };
201                 // 6 = `vec!` + `; `
202                 let total_overhead = lbr.len() + rbr.len() + 6;
203                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
204                 let lhs = try_opt!(expr_vec[0].rewrite(context, nested_shape));
205                 let rhs = try_opt!(expr_vec[1].rewrite(context, nested_shape));
206                 if !lhs.contains('\n') && !rhs.contains('\n') &&
207                     lhs.len() + rhs.len() + total_overhead <= shape.width
208                 {
209                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
210                 } else {
211                     Some(format!(
212                         "{}{}\n{}{};\n{}{}\n{}{}",
213                         macro_name,
214                         lbr,
215                         nested_shape.indent.to_string(context.config),
216                         lhs,
217                         nested_shape.indent.to_string(context.config),
218                         rhs,
219                         shape.indent.to_string(context.config),
220                         rbr
221                     ))
222                 }
223             } else {
224                 // If we are rewriting `vec!` macro or other special macros,
225                 // then we can rewrite this as an usual array literal.
226                 // Otherwise, we must preserve the original existence of trailing comma.
227                 if FORCED_BRACKET_MACROS.contains(&&macro_name.as_str()) {
228                     context.inside_macro = false;
229                     trailing_comma = false;
230                 }
231                 let rewrite = try_opt!(rewrite_array(
232                     expr_vec.iter().map(|x| &**x),
233                     mk_sp(
234                         context
235                             .codemap
236                             .span_after(mac.span, original_style.opener()),
237                         mac.span.hi - BytePos(1),
238                     ),
239                     context,
240                     mac_shape,
241                     trailing_comma,
242                 ));
243
244                 Some(format!("{}{}", macro_name, rewrite))
245             }
246         }
247         MacroStyle::Braces => {
248             // Skip macro invocations with braces, for now.
249             indent_macro_snippet(context, &context.snippet(mac.span), shape.indent)
250         }
251     }
252 }
253
254 /// Tries to convert a macro use into a short hand try expression. Returns None
255 /// when the macro is not an instance of try! (or parsing the inner expression
256 /// failed).
257 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
258     if &format!("{}", mac.node.path)[..] == "try" {
259         let ts: TokenStream = mac.node.tts.clone().into();
260         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
261
262         Some(ast::Expr {
263             id: ast::NodeId::new(0), // dummy value
264             node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
265             span: mac.span, // incorrect span, but shouldn't matter too much
266             attrs: ThinVec::new(),
267         })
268     } else {
269         None
270     }
271 }
272
273 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
274     let snippet = context.snippet(mac.span);
275     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
276     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
277     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
278
279     if paren_pos < bracket_pos && paren_pos < brace_pos {
280         MacroStyle::Parens
281     } else if bracket_pos < brace_pos {
282         MacroStyle::Brackets
283     } else {
284         MacroStyle::Braces
285     }
286 }
287
288 /// Indent each line according to the specified `indent`.
289 /// e.g.
290 /// ```rust
291 /// foo!{
292 /// x,
293 /// y,
294 /// foo(
295 ///     a,
296 ///     b,
297 ///     c,
298 /// ),
299 /// }
300 /// ```
301 /// will become
302 /// ```rust
303 /// foo!{
304 ///     x,
305 ///     y,
306 ///     foo(
307 ///         a,
308 ///         b,
309 ///         c,
310 //      ),
311 /// }
312 /// ```
313 fn indent_macro_snippet(
314     context: &RewriteContext,
315     macro_str: &str,
316     indent: Indent,
317 ) -> Option<String> {
318     let mut lines = macro_str.lines();
319     let first_line = try_opt!(lines.next().map(|s| s.trim_right()));
320     let mut trimmed_lines = Vec::with_capacity(16);
321
322     let min_prefix_space_width = try_opt!(
323         lines
324             .filter_map(|line| {
325                 let prefix_space_width = if is_empty_line(line) {
326                     None
327                 } else {
328                     Some(get_prefix_space_width(context, line))
329                 };
330                 trimmed_lines.push((line.trim(), prefix_space_width));
331                 prefix_space_width
332             })
333             .min()
334     );
335
336     Some(
337         String::from(first_line) + "\n" +
338             &trimmed_lines
339                 .iter()
340                 .map(|&(line, prefix_space_width)| match prefix_space_width {
341                     Some(original_indent_width) => {
342                         let new_indent_width = indent.width() +
343                             original_indent_width
344                                 .checked_sub(min_prefix_space_width)
345                                 .unwrap_or(0);
346                         let new_indent = Indent::from_width(context.config, new_indent_width);
347                         new_indent.to_string(context.config) + line.trim()
348                     }
349                     None => String::new(),
350                 })
351                 .collect::<Vec<_>>()
352                 .join("\n"),
353     )
354 }
355
356 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
357     let mut width = 0;
358     let mut iter = s.chars();
359     while let Some(c) = iter.next() {
360         match c {
361             ' ' => width += 1,
362             '\t' => width += context.config.tab_spaces(),
363             _ => return width,
364         }
365     }
366     width
367 }
368
369 fn is_empty_line(s: &str) -> bool {
370     s.is_empty() || s.chars().all(char::is_whitespace)
371 }