]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
cd3e638d97cfd2a42c4dea2b6ee624b57eba66d2
[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::{mk_sp, BytePos};
24 use syntax::parse::token::Token;
25 use syntax::parse::tts_to_parser;
26 use syntax::symbol;
27 use syntax::util::ThinVec;
28
29 use Shape;
30 use codemap::SpanUtils;
31 use rewrite::{Rewrite, RewriteContext};
32 use expr::{rewrite_call, rewrite_array};
33 use comment::{FindUncommented, contains_comment};
34
35 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
36
37 // FIXME: use the enum from libsyntax?
38 #[derive(Clone, Copy, PartialEq, Eq)]
39 enum MacroStyle {
40     Parens,
41     Brackets,
42     Braces,
43 }
44
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 pub enum MacroPosition {
47     Item,
48     Statement,
49     Expression,
50 }
51
52 impl MacroStyle {
53     fn opener(&self) -> &'static str {
54         match *self {
55             MacroStyle::Parens => "(",
56             MacroStyle::Brackets => "[",
57             MacroStyle::Braces => "{",
58         }
59     }
60 }
61
62 pub fn rewrite_macro(mac: &ast::Mac,
63                      extra_ident: Option<ast::Ident>,
64                      context: &RewriteContext,
65                      shape: Shape,
66                      position: MacroPosition)
67                      -> Option<String> {
68     if context.config.use_try_shorthand {
69         if let Some(expr) = convert_try_mac(mac, context) {
70             return expr.rewrite(context, shape);
71         }
72     }
73
74     let original_style = macro_style(mac, context);
75
76     let macro_name = match extra_ident {
77         None => format!("{}!", mac.node.path),
78         Some(ident) => {
79             if ident == symbol::keywords::Invalid.ident() {
80                 format!("{}!", mac.node.path)
81             } else {
82                 format!("{}! {}", mac.node.path, ident)
83             }
84         }
85     };
86
87     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
88         MacroStyle::Brackets
89     } else {
90         original_style
91     };
92
93     if mac.node.tts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
94         return match style {
95                    MacroStyle::Parens if position == MacroPosition::Item => {
96                        Some(format!("{}();", macro_name))
97                    }
98                    MacroStyle::Parens => Some(format!("{}()", macro_name)),
99                    MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
100                    MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
101                };
102     }
103
104     let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone());
105     let mut expr_vec = Vec::new();
106
107     if MacroStyle::Braces != style {
108         loop {
109             let expr = match parser.parse_expr() {
110                 Ok(expr) => {
111                     // Recovered errors.
112                     if context.parse_session.span_diagnostic.has_errors() {
113                         return None;
114                     }
115
116                     expr
117                 }
118                 Err(mut e) => {
119                     e.cancel();
120                     return None;
121                 }
122             };
123
124             expr_vec.push(expr);
125
126             match parser.token {
127                 Token::Eof => break,
128                 Token::Comma => (),
129                 _ => return None,
130             }
131
132             parser.bump();
133
134             if parser.token == Token::Eof {
135                 // vec! is a special case of bracket macro which should be formated as an array.
136                 if macro_name == "vec!" {
137                     break;
138                 } else {
139                     return None;
140                 }
141             }
142         }
143     }
144
145     match style {
146         MacroStyle::Parens => {
147             // Format macro invocation as function call, forcing no trailing
148             // comma because not all macros support them.
149             rewrite_call(context, &macro_name, &expr_vec, mac.span, shape, true)
150                 .map(|rw| match position {
151                          MacroPosition::Item => format!("{};", rw),
152                          _ => rw,
153                      })
154         }
155         MacroStyle::Brackets => {
156             // Format macro invocation as array literal.
157             let extra_offset = macro_name.len();
158             let shape = try_opt!(shape.shrink_left(extra_offset));
159             let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
160                                                  mk_sp(context
161                                                            .codemap
162                                                            .span_after(mac.span,
163                                                                        original_style
164                                                                            .opener()),
165                                                        mac.span.hi - BytePos(1)),
166                                                  context,
167                                                  shape));
168
169             Some(format!("{}{}", macro_name, rewrite))
170         }
171         MacroStyle::Braces => {
172             // Skip macro invocations with braces, for now.
173             None
174         }
175     }
176 }
177
178 /// Tries to convert a macro use into a short hand try expression. Returns None
179 /// when the macro is not an instance of try! (or parsing the inner expression
180 /// failed).
181 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
182     if &format!("{}", mac.node.path)[..] == "try" {
183         let mut parser = tts_to_parser(context.parse_session, mac.node.tts.clone());
184
185         Some(ast::Expr {
186                  id: ast::NodeId::new(0), // dummy value
187                  node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
188                  span: mac.span, // incorrect span, but shouldn't matter too much
189                  attrs: ThinVec::new(),
190              })
191     } else {
192         None
193     }
194 }
195
196 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
197     let snippet = context.snippet(mac.span);
198     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
199     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
200     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
201
202     if paren_pos < bracket_pos && paren_pos < brace_pos {
203         MacroStyle::Parens
204     } else if bracket_pos < brace_pos {
205         MacroStyle::Brackets
206     } else {
207         MacroStyle::Braces
208     }
209 }