]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #1615 from Mitranim/patch-1
[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::token::Token;
25 use syntax::parse::new_parser_from_tts;
26 use syntax::tokenstream::TokenStream;
27 use syntax::symbol;
28 use syntax::util::ThinVec;
29
30 use Shape;
31 use codemap::SpanUtils;
32 use rewrite::{Rewrite, RewriteContext};
33 use expr::{rewrite_call, rewrite_array};
34 use comment::{FindUncommented, contains_comment};
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) => {
84             if ident == symbol::keywords::Invalid.ident() {
85                 format!("{}!", mac.node.path)
86             } else {
87                 format!("{}! {}", mac.node.path, ident)
88             }
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
114     if MacroStyle::Braces != style {
115         loop {
116             let expr = match parser.parse_expr() {
117                 Ok(expr) => {
118                     // Recovered errors.
119                     if context.parse_session.span_diagnostic.has_errors() {
120                         return Some(context.snippet(mac.span));
121                     }
122
123                     expr
124                 }
125                 Err(mut e) => {
126                     e.cancel();
127                     return Some(context.snippet(mac.span));
128                 }
129             };
130
131             expr_vec.push(expr);
132
133             match parser.token {
134                 Token::Eof => break,
135                 Token::Comma => (),
136                 Token::Semi => {
137                     // Try to parse `vec![expr; expr]`
138                     if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
139                         parser.bump();
140                         if parser.token != Token::Eof {
141                             match parser.parse_expr() {
142                                 Ok(expr) => {
143                                     if context.parse_session.span_diagnostic.has_errors() {
144                                         return None;
145                                     }
146                                     expr_vec.push(expr);
147                                     parser.bump();
148                                     if parser.token == Token::Eof && expr_vec.len() == 2 {
149                                         vec_with_semi = true;
150                                         break;
151                                     }
152                                 }
153                                 Err(mut e) => e.cancel(),
154                             }
155                         }
156                     }
157                     return None;
158                 }
159                 _ => return None,
160             }
161
162             parser.bump();
163
164             if parser.token == Token::Eof {
165                 // vec! is a special case of bracket macro which should be formated as an array.
166                 if macro_name == "vec!" {
167                     break;
168                 } else {
169                     return None;
170                 }
171             }
172         }
173     }
174
175     match style {
176         MacroStyle::Parens => {
177             // Format macro invocation as function call, forcing no trailing
178             // comma because not all macros support them.
179             rewrite_call(context, &macro_name, &expr_vec, mac.span, shape).map(
180                 |rw| match position {
181                     MacroPosition::Item => format!("{};", rw),
182                     _ => rw,
183                 },
184             )
185         }
186         MacroStyle::Brackets => {
187             let mac_shape = try_opt!(shape.shrink_left(macro_name.len()));
188             // Handle special case: `vec![expr; expr]`
189             if vec_with_semi {
190                 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
191                     ("[ ", " ]")
192                 } else {
193                     ("[", "]")
194                 };
195                 // 6 = `vec!` + `; `
196                 let total_overhead = lbr.len() + rbr.len() + 6;
197                 let lhs = try_opt!(expr_vec[0].rewrite(context, mac_shape));
198                 let rhs = try_opt!(expr_vec[1].rewrite(context, mac_shape));
199                 if !lhs.contains('\n') && !rhs.contains('\n') &&
200                     lhs.len() + rhs.len() + total_overhead <= shape.width
201                 {
202                     Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
203                 } else {
204                     let nested_indent = shape.indent.block_indent(context.config);
205                     Some(format!(
206                         "{}{}\n{}{};\n{}{}\n{}{}",
207                         macro_name,
208                         lbr,
209                         nested_indent.to_string(context.config),
210                         lhs,
211                         nested_indent.to_string(context.config),
212                         rhs,
213                         shape.indent.to_string(context.config),
214                         rbr
215                     ))
216                 }
217             } else {
218                 // Format macro invocation as array literal.
219                 let rewrite = try_opt!(rewrite_array(
220                     expr_vec.iter().map(|x| &**x),
221                     mk_sp(
222                         context.codemap.span_after(
223                             mac.span,
224                             original_style.opener(),
225                         ),
226                         mac.span.hi - BytePos(1),
227                     ),
228                     context,
229                     mac_shape,
230                 ));
231
232                 Some(format!("{}{}", macro_name, rewrite))
233             }
234         }
235         MacroStyle::Braces => {
236             // Skip macro invocations with braces, for now.
237             None
238         }
239     }
240 }
241
242 /// Tries to convert a macro use into a short hand try expression. Returns None
243 /// when the macro is not an instance of try! (or parsing the inner expression
244 /// failed).
245 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
246     if &format!("{}", mac.node.path)[..] == "try" {
247         let ts: TokenStream = mac.node.tts.clone().into();
248         let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
249
250         Some(ast::Expr {
251             id: ast::NodeId::new(0), // dummy value
252             node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
253             span: mac.span, // incorrect span, but shouldn't matter too much
254             attrs: ThinVec::new(),
255         })
256     } else {
257         None
258     }
259 }
260
261 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
262     let snippet = context.snippet(mac.span);
263     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
264     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
265     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
266
267     if paren_pos < bracket_pos && paren_pos < brace_pos {
268         MacroStyle::Parens
269     } else if bracket_pos < brace_pos {
270         MacroStyle::Brackets
271     } else {
272         MacroStyle::Braces
273     }
274 }