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