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