]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Cargo clippy
[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 syntax::ast;
23 use syntax::codemap::BytePos;
24 use syntax::parse::new_parser_from_tts;
25 use syntax::parse::parser::Parser;
26 use syntax::parse::token::Token;
27 use syntax::symbol;
28 use syntax::tokenstream::TokenStream;
29 use syntax::util::ThinVec;
30
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 shape::{Indent, Shape};
36 use utils::mk_sp;
37
38 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
39
40 // FIXME: use the enum from libsyntax?
41 #[derive(Clone, Copy, PartialEq, Eq)]
42 enum MacroStyle {
43     Parens,
44     Brackets,
45     Braces,
46 }
47
48 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49 pub enum MacroPosition {
50     Item,
51     Statement,
52     Expression,
53     Pat,
54 }
55
56 impl MacroStyle {
57     fn opener(&self) -> &'static str {
58         match *self {
59             MacroStyle::Parens => "(",
60             MacroStyle::Brackets => "[",
61             MacroStyle::Braces => "{",
62         }
63     }
64 }
65
66 pub enum MacroArg {
67     Expr(ast::Expr),
68     Ty(ast::Ty),
69     Pat(ast::Pat),
70 }
71
72 impl Rewrite for MacroArg {
73     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
74         match *self {
75             MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
76             MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
77             MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
78         }
79     }
80 }
81
82 fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
83     macro_rules! parse_macro_arg {
84         ($target:tt, $macro_arg:ident, $parser:ident) => {
85             let mut cloned_parser = (*parser).clone();
86             match cloned_parser.$parser() {
87                 Ok($target) => {
88                     if parser.sess.span_diagnostic.has_errors() {
89                         parser.sess.span_diagnostic.reset_err_count();
90                     } else {
91                         // Parsing succeeded.
92                         *parser = cloned_parser;
93                         return Some(MacroArg::$macro_arg((*$target).clone()));
94                     }
95                 }
96                 Err(mut e) => {
97                     e.cancel();
98                     parser.sess.span_diagnostic.reset_err_count();
99                 }
100             }
101         }
102     }
103
104     parse_macro_arg!(expr, Expr, parse_expr);
105     parse_macro_arg!(ty, Ty, parse_ty);
106     parse_macro_arg!(pat, Pat, parse_pat);
107
108     None
109 }
110
111 pub fn rewrite_macro(
112     mac: &ast::Mac,
113     extra_ident: Option<ast::Ident>,
114     context: &RewriteContext,
115     shape: Shape,
116     position: MacroPosition,
117 ) -> Option<String> {
118     let context = &mut context.clone();
119     context.inside_macro = true;
120     if context.config.use_try_shorthand() {
121         if let Some(expr) = convert_try_mac(mac, context) {
122             context.inside_macro = false;
123             return expr.rewrite(context, shape);
124         }
125     }
126
127     let original_style = macro_style(mac, context);
128
129     let macro_name = match extra_ident {
130         None => format!("{}!", mac.node.path),
131         Some(ident) => {
132             if ident == symbol::keywords::Invalid.ident() {
133                 format!("{}!", mac.node.path)
134             } else {
135                 format!("{}! {}", mac.node.path, ident)
136             }
137         }
138     };
139
140     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
141         MacroStyle::Brackets
142     } else {
143         original_style
144     };
145
146     let ts: TokenStream = mac.node.stream();
147     if ts.is_empty() && !contains_comment(context.snippet(mac.span)) {
148         return match style {
149             MacroStyle::Parens if position == MacroPosition::Item => {
150                 Some(format!("{}();", macro_name))
151             }
152             MacroStyle::Parens => Some(format!("{}()", macro_name)),
153             MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
154             MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
155         };
156     }
157
158     let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
159     let mut arg_vec = Vec::new();
160     let mut vec_with_semi = false;
161     let mut trailing_comma = false;
162
163     if MacroStyle::Braces != style {
164         loop {
165             match parse_macro_arg(&mut parser) {
166                 Some(arg) => arg_vec.push(arg),
167                 None => return Some(context.snippet(mac.span).to_owned()),
168             }
169
170             match parser.token {
171                 Token::Eof => break,
172                 Token::Comma => (),
173                 Token::Semi => {
174                     // Try to parse `vec![expr; expr]`
175                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
176                         parser.bump();
177                         if parser.token != Token::Eof {
178                             match parse_macro_arg(&mut parser) {
179                                 Some(arg) => {
180                                     arg_vec.push(arg);
181                                     parser.bump();
182                                     if parser.token == Token::Eof && arg_vec.len() == 2 {
183                                         vec_with_semi = true;
184                                         break;
185                                     }
186                                 }
187                                 None => return Some(context.snippet(mac.span).to_owned()),
188                             }
189                         }
190                     }
191                     return Some(context.snippet(mac.span).to_owned());
192                 }
193                 _ => return Some(context.snippet(mac.span).to_owned()),
194             }
195
196             parser.bump();
197
198             if parser.token == Token::Eof {
199                 trailing_comma = true;
200                 break;
201             }
202         }
203     }
204
205     match style {
206         MacroStyle::Parens => {
207             // Format macro invocation as function call, forcing no trailing
208             // comma because not all macros support them.
209             rewrite_call_inner(
210                 context,
211                 &macro_name,
212                 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
213                 mac.span,
214                 shape,
215                 context.config.width_heuristics().fn_call_width,
216                 trailing_comma,
217             ).map(|rw| match position {
218                 MacroPosition::Item => format!("{};", rw),
219                 _ => rw,
220             })
221         }
222         MacroStyle::Brackets => {
223             let mac_shape = shape.offset_left(macro_name.len())?;
224             // Handle special case: `vec![expr; expr]`
225             if vec_with_semi {
226                 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
227                     ("[ ", " ]")
228                 } else {
229                     ("[", "]")
230                 };
231                 // 6 = `vec!` + `; `
232                 let total_overhead = lbr.len() + rbr.len() + 6;
233                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
234                 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
235                 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
236                 if !lhs.contains('\n') && !rhs.contains('\n')
237                     && lhs.len() + rhs.len() + total_overhead <= shape.width
238                 {
239                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
240                 } else {
241                     Some(format!(
242                         "{}{}\n{}{};\n{}{}\n{}{}",
243                         macro_name,
244                         lbr,
245                         nested_shape.indent.to_string(context.config),
246                         lhs,
247                         nested_shape.indent.to_string(context.config),
248                         rhs,
249                         shape.indent.to_string(context.config),
250                         rbr
251                     ))
252                 }
253             } else {
254                 // If we are rewriting `vec!` macro or other special macros,
255                 // then we can rewrite this as an usual array literal.
256                 // Otherwise, we must preserve the original existence of trailing comma.
257                 if FORCED_BRACKET_MACROS.contains(&macro_name.as_str()) {
258                     context.inside_macro = false;
259                     trailing_comma = false;
260                 }
261                 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
262                 let sp = mk_sp(
263                     context
264                         .codemap
265                         .span_after(mac.span, original_style.opener()),
266                     mac.span.hi() - BytePos(1),
267                 );
268                 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
269                 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
270
271                 Some(format!("{}{}", macro_name, rewrite))
272             }
273         }
274         MacroStyle::Braces => {
275             // Skip macro invocations with braces, for now.
276             indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
277         }
278     }
279 }
280
281 /// Tries to convert a macro use into a short hand try expression. Returns None
282 /// when the macro is not an instance of try! (or parsing the inner expression
283 /// failed).
284 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
285     if &format!("{}", mac.node.path)[..] == "try" {
286         let ts: TokenStream = mac.node.tts.clone().into();
287         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
288
289         Some(ast::Expr {
290             id: ast::NodeId::new(0), // dummy value
291             node: ast::ExprKind::Try(parser.parse_expr().ok()?),
292             span: mac.span, // incorrect span, but shouldn't matter too much
293             attrs: ThinVec::new(),
294         })
295     } else {
296         None
297     }
298 }
299
300 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
301     let snippet = context.snippet(mac.span);
302     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
303     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
304     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
305
306     if paren_pos < bracket_pos && paren_pos < brace_pos {
307         MacroStyle::Parens
308     } else if bracket_pos < brace_pos {
309         MacroStyle::Brackets
310     } else {
311         MacroStyle::Braces
312     }
313 }
314
315 /// Indent each line according to the specified `indent`.
316 /// e.g.
317 /// ```rust
318 /// foo!{
319 /// x,
320 /// y,
321 /// foo(
322 ///     a,
323 ///     b,
324 ///     c,
325 /// ),
326 /// }
327 /// ```
328 /// will become
329 /// ```rust
330 /// foo!{
331 ///     x,
332 ///     y,
333 ///     foo(
334 ///         a,
335 ///         b,
336 ///         c,
337 //      ),
338 /// }
339 /// ```
340 fn indent_macro_snippet(
341     context: &RewriteContext,
342     macro_str: &str,
343     indent: Indent,
344 ) -> Option<String> {
345     let mut lines = macro_str.lines();
346     let first_line = lines.next().map(|s| s.trim_right())?;
347     let mut trimmed_lines = Vec::with_capacity(16);
348
349     let min_prefix_space_width = lines
350         .filter_map(|line| {
351             let prefix_space_width = if is_empty_line(line) {
352                 None
353             } else {
354                 Some(get_prefix_space_width(context, line))
355             };
356             trimmed_lines.push((line.trim(), prefix_space_width));
357             prefix_space_width
358         })
359         .min()?;
360
361     Some(
362         String::from(first_line) + "\n"
363             + &trimmed_lines
364                 .iter()
365                 .map(|&(line, prefix_space_width)| match prefix_space_width {
366                     Some(original_indent_width) => {
367                         let new_indent_width = indent.width()
368                             + original_indent_width
369                                 .checked_sub(min_prefix_space_width)
370                                 .unwrap_or(0);
371                         let new_indent = Indent::from_width(context.config, new_indent_width);
372                         format!("{}{}", new_indent.to_string(context.config), line.trim())
373                     }
374                     None => String::new(),
375                 })
376                 .collect::<Vec<_>>()
377                 .join("\n"),
378     )
379 }
380
381 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
382     let mut width = 0;
383     for c in s.chars() {
384         match c {
385             ' ' => width += 1,
386             '\t' => width += context.config.tab_spaces(),
387             _ => return width,
388         }
389     }
390     width
391 }
392
393 fn is_empty_line(s: &str) -> bool {
394     s.is_empty() || s.chars().all(char::is_whitespace)
395 }