]> git.lizzy.rs Git - rust.git/blob - src/macros.rs
Merge pull request #474 from marcusklaas/fn-indent
[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::thread;
23
24 use syntax::ast;
25 use syntax::parse::token::{Eof, Comma, Token};
26 use syntax::parse::{ParseSess, tts_to_parser};
27 use syntax::codemap::{mk_sp, BytePos};
28
29 use Indent;
30 use rewrite::RewriteContext;
31 use expr::{rewrite_call, rewrite_array};
32 use comment::FindUncommented;
33 use utils::{wrap_str, span_after};
34
35 static FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
36
37 // We need to pass `TokenTree`s to our expression parsing thread, but they are
38 // not `Send`. We wrap them in a `Send` container to force our will.
39 // FIXME: this is a pretty terrible hack. Any other solution would be preferred.
40 struct ForceSend<T>(pub T);
41 unsafe impl<T> Send for ForceSend<T> {}
42
43 // FIXME: use the enum from libsyntax?
44 #[derive(Clone, Copy)]
45 enum MacroStyle {
46     Parens,
47     Brackets,
48     Braces,
49 }
50
51 impl MacroStyle {
52     fn opener(&self) -> &'static str {
53         match *self {
54             MacroStyle::Parens => "(",
55             MacroStyle::Brackets => "[",
56             MacroStyle::Braces => "{",
57         }
58     }
59 }
60
61 pub fn rewrite_macro(mac: &ast::Mac,
62                      context: &RewriteContext,
63                      width: usize,
64                      offset: Indent)
65                      -> Option<String> {
66     let original_style = macro_style(mac, context);
67     let macro_name = format!("{}!", mac.node.path);
68     let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
69         MacroStyle::Brackets
70     } else {
71         original_style
72     };
73
74     if let MacroStyle::Braces = style {
75         return None;
76     } else if mac.node.tts.is_empty() {
77         return if let MacroStyle::Parens = style {
78             Some(format!("{}()", macro_name))
79         } else {
80             Some(format!("{}[]", macro_name))
81         };
82     }
83
84     let wrapped_tt_vec = ForceSend(mac.node.tts.clone());
85     // Wrap expression parsing logic in a thread since the libsyntax parser
86     // panics on failure, which we do not want to propagate.
87     // The expression vector is wrapped in an Option inside a Result.
88     let expr_vec_result = thread::catch_panic(move || {
89         let parse_session = ParseSess::new();
90         let mut parser = tts_to_parser(&parse_session, wrapped_tt_vec.0, vec![]);
91         let mut expr_vec = vec![];
92
93         loop {
94             expr_vec.push(parser.parse_expr());
95
96             match parser.token {
97                 Token::Eof => break,
98                 Token::Comma => (),
99                 _ => panic!("Macro not list-like, skiping..."),
100             }
101
102             let _ = parser.bump();
103
104             if parser.token == Token::Eof {
105                 return None;
106             }
107         }
108
109         Some(expr_vec)
110     });
111     let expr_vec = try_opt!(try_opt!(expr_vec_result.ok()));
112
113     match style {
114         MacroStyle::Parens => {
115             // Format macro invocation as function call.
116             rewrite_call(context, &macro_name, &expr_vec, mac.span, width, offset)
117         }
118         MacroStyle::Brackets => {
119             // Format macro invocation as array literal.
120             let extra_offset = macro_name.len();
121             let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
122                                                  mk_sp(span_after(mac.span,
123                                                                   original_style.opener(),
124                                                                   context.codemap),
125                                                        mac.span.hi - BytePos(1)),
126                                                  context,
127                                                  try_opt!(width.checked_sub(extra_offset)),
128                                                  offset + extra_offset));
129
130             Some(format!("{}{}", macro_name, rewrite))
131         }
132         MacroStyle::Braces => {
133             // Skip macro invocations with braces, for now.
134             wrap_str(context.snippet(mac.span),
135                      context.config.max_width,
136                      width,
137                      offset)
138         }
139     }
140 }
141
142 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
143     let snippet = context.snippet(mac.span);
144     let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
145     let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
146     let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
147
148     if paren_pos < bracket_pos && paren_pos < brace_pos {
149         MacroStyle::Parens
150     } else if bracket_pos < brace_pos {
151         MacroStyle::Brackets
152     } else {
153         MacroStyle::Braces
154     }
155 }