]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Sort imports in alphabetical and consistent order
[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 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 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) => 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 Some(context.snippet(mac.span));
120                     }
121
122                     expr
123                 }
124                 Err(mut e) => {
125                     e.cancel();
126                     return Some(context.snippet(mac.span));
127                 }
128             };
129
130             expr_vec.push(expr);
131
132             match parser.token {
133                 Token::Eof => break,
134                 Token::Comma => (),
135                 Token::Semi => {
136                     // Try to parse `vec![expr; expr]`
137                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
138                         parser.bump();
139                         if parser.token != Token::Eof {
140                             match parser.parse_expr() {
141                                 Ok(expr) => {
142                                     if context.parse_session.span_diagnostic.has_errors() {
143                                         return None;
144                                     }
145                                     expr_vec.push(expr);
146                                     parser.bump();
147                                     if parser.token == Token::Eof && expr_vec.len() == 2 {
148                                         vec_with_semi = true;
149                                         break;
150                                     }
151                                 }
152                                 Err(mut e) => e.cancel(),
153                             }
154                         }
155                     }
156                     return None;
157                 }
158                 _ => return None,
159             }
160
161             parser.bump();
162
163             if parser.token == Token::Eof {
164                 trailing_comma = true;
165                 break;
166             }
167         }
168     }
169
170     match style {
171         MacroStyle::Parens => {
172             // Format macro invocation as function call, forcing no trailing
173             // comma because not all macros support them.
174             let rw = rewrite_call_inner(
175                 context,
176                 &macro_name,
177                 &expr_vec.iter().map(|e| &**e).collect::<Vec<_>>()[..],
178                 mac.span,
179                 shape,
180                 context.config.fn_call_width(),
181                 trailing_comma,
182             );
183             rw.ok().map(|rw| match position {
184                 MacroPosition::Item => format!("{};", rw),
185                 _ => rw,
186             })
187         }
188         MacroStyle::Brackets => {
189             let mac_shape = try_opt!(shape.offset_left(macro_name.len()));
190             // Handle special case: `vec![expr; expr]`
191             if vec_with_semi {
192                 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
193                     ("[ ", " ]")
194                 } else {
195                     ("[", "]")
196                 };
197                 // 6 = `vec!` + `; `
198                 let total_overhead = lbr.len() + rbr.len() + 6;
199                 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
200                 let lhs = try_opt!(expr_vec[0].rewrite(context, nested_shape));
201                 let rhs = try_opt!(expr_vec[1].rewrite(context, nested_shape));
202                 if !lhs.contains('\n') && !rhs.contains('\n') &&
203                     lhs.len() + rhs.len() + total_overhead <= shape.width
204                 {
205                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
206                 } else {
207                     Some(format!(
208                         "{}{}\n{}{};\n{}{}\n{}{}",
209                         macro_name,
210                         lbr,
211                         nested_shape.indent.to_string(context.config),
212                         lhs,
213                         nested_shape.indent.to_string(context.config),
214                         rhs,
215                         shape.indent.to_string(context.config),
216                         rbr
217                     ))
218                 }
219             } else {
220                 // If we are rewriting `vec!` macro or other special macros,
221                 // then we can rewrite this as an usual array literal.
222                 // Otherwise, we must preserve the original existence of trailing comma.
223                 if FORCED_BRACKET_MACROS.contains(&&macro_name.as_str()) {
224                     context.inside_macro = false;
225                     trailing_comma = false;
226                 }
227                 let rewrite = try_opt!(rewrite_array(
228                     expr_vec.iter().map(|x| &**x),
229                     mk_sp(
230                         context
231                             .codemap
232                             .span_after(mac.span, original_style.opener()),
233                         mac.span.hi - BytePos(1),
234                     ),
235                     context,
236                     mac_shape,
237                     trailing_comma,
238                 ));
239
240                 Some(format!("{}{}", macro_name, rewrite))
241             }
242         }
243         MacroStyle::Braces => {
244             // Skip macro invocations with braces, for now.
245             None
246         }
247     }
248 }
249
250 /// Tries to convert a macro use into a short hand try expression. Returns None
251 /// when the macro is not an instance of try! (or parsing the inner expression
252 /// failed).
253 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
254     if &format!("{}", mac.node.path)[..] == "try" {
255         let ts: TokenStream = mac.node.tts.clone().into();
256         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
257
258         Some(ast::Expr {
259             id: ast::NodeId::new(0), // dummy value
260             node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
261             span: mac.span, // incorrect span, but shouldn't matter too much
262             attrs: ThinVec::new(),
263         })
264     } else {
265         None
266     }
267 }
268
269 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
270     let snippet = context.snippet(mac.span);
271     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
272     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
273     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
274
275     if paren_pos < bracket_pos && paren_pos < brace_pos {
276         MacroStyle::Parens
277     } else if bracket_pos < brace_pos {
278         MacroStyle::Brackets
279     } else {
280         MacroStyle::Braces
281     }
282 }