]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Add indent to macro we could not format
[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 std::iter::repeat;
23
24 use syntax::ast;
25 use syntax::codemap::BytePos;
26 use syntax::parse::new_parser_from_tts;
27 use syntax::parse::token::Token;
28 use syntax::symbol;
29 use syntax::tokenstream::TokenStream;
30 use syntax::util::ThinVec;
31
32 use {Indent, Shape};
33 use codemap::SpanUtils;
34 use comment::{contains_comment, FindUncommented};
35 use expr::{rewrite_array, rewrite_call_inner};
36 use rewrite::{Rewrite, RewriteContext};
37 use utils::mk_sp;
38
39 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
40
41 // FIXME: use the enum from libsyntax?
42 #[derive(Clone, Copy, PartialEq, Eq)]
43 enum MacroStyle {
44     Parens,
45     Brackets,
46     Braces,
47 }
48
49 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
50 pub enum MacroPosition {
51     Item,
52     Statement,
53     Expression,
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 fn rewrite_macro(
67     mac: &ast::Mac,
68     extra_ident: Option<ast::Ident>,
69     context: &RewriteContext,
70     shape: Shape,
71     position: MacroPosition,
72 ) -> Option<String> {
73     let context = &mut context.clone();
74     context.inside_macro = true;
75     if context.config.use_try_shorthand() {
76         if let Some(expr) = convert_try_mac(mac, context) {
77             return expr.rewrite(context, shape);
78         }
79     }
80
81     let original_style = macro_style(mac, context);
82
83     let macro_name = match extra_ident {
84         None => format!("{}!", mac.node.path),
85         Some(ident) => if ident == symbol::keywords::Invalid.ident() {
86             format!("{}!", mac.node.path)
87         } else {
88             format!("{}! {}", mac.node.path, ident)
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 indent_macro_snippet(&context.snippet(mac.span), shape.indent);
122                     }
123
124                     expr
125                 }
126                 Err(mut e) => {
127                     e.cancel();
128                     return indent_macro_snippet(&context.snippet(mac.span), shape.indent);
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             indent_macro_snippet(&context.snippet(mac.span), shape.indent)
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 }
285
286 /// Indent each line according to the specified `indent`.
287 /// e.g.
288 /// ```rust
289 /// foo!{
290 /// x,
291 /// y,
292 /// foo(
293 ///     a,
294 ///     b,
295 ///     c,
296 /// ),
297 /// }
298 /// ```
299 /// will become
300 /// ```rust
301 /// foo!{
302 ///     x,
303 ///     y,
304 ///     foo(
305 ///         a,
306 ///         b,
307 ///         c,
308 //      ),
309 /// }
310 /// ```
311 fn indent_macro_snippet(macro_str: &str, indent: Indent) -> Option<String> {
312     let min_prefix_space_width =
313         try_opt!(macro_str.lines().skip(1).map(get_prefix_space_width).min());
314
315     let mut lines = macro_str.lines();
316     let first_line = try_opt!(lines.next());
317
318     Some(
319         String::from(first_line) + "\n" +
320             &lines
321                 .map(|line| {
322                     let new_indent_width = indent.width() +
323                         get_prefix_space_width(line)
324                             .checked_sub(min_prefix_space_width)
325                             .unwrap_or(0);
326                     repeat_white_space(new_indent_width) + line.trim()
327                 })
328                 .collect::<Vec<_>>()
329                 .join("\n"),
330     )
331 }
332
333 fn get_prefix_space_width(s: &str) -> usize {
334     s.chars().position(|c| c != ' ').unwrap_or(0)
335 }
336
337 fn repeat_white_space(ws_count: usize) -> String {
338     repeat(" ").take(ws_count).collect::<String>()
339 }