]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/feature_gate.rs
auto merge of #12998 : huonw/rust/log_syntax, r=alexcrichton
[rust.git] / src / librustc / front / feature_gate.rs
1 // Copyright 2013 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 //! Feature gating
12 //!
13 //! This modules implements the gating necessary for preventing certain compiler
14 //! features from being used by default. This module will crawl a pre-expanded
15 //! AST to ensure that there are no features which are used that are not
16 //! enabled.
17 //!
18 //! Features are enabled in programs via the crate-level attributes of
19 //! #[feature(...)] with a comma-separated list of features.
20
21 use middle::lint;
22
23 use syntax::ast;
24 use syntax::attr;
25 use syntax::attr::AttrMetaMethods;
26 use syntax::codemap::Span;
27 use syntax::visit;
28 use syntax::visit::Visitor;
29 use syntax::parse::token;
30
31 use driver::session::Session;
32
33 use std::cell::Cell;
34
35 /// This is a list of all known features since the beginning of time. This list
36 /// can never shrink, it may only be expanded (in order to prevent old programs
37 /// from failing to compile). The status of each feature may change, however.
38 static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
39     ("globs", Active),
40     ("macro_rules", Active),
41     ("struct_variant", Active),
42     ("once_fns", Active),
43     ("asm", Active),
44     ("managed_boxes", Active),
45     ("non_ascii_idents", Active),
46     ("thread_local", Active),
47     ("link_args", Active),
48     ("phase", Active),
49     ("macro_registrar", Active),
50     ("log_syntax", Active),
51     ("trace_macros", Active),
52     ("simd", Active),
53     ("default_type_params", Active),
54     ("quote", Active),
55     ("linkage", Active),
56
57     // These are used to test this portion of the compiler, they don't actually
58     // mean anything
59     ("test_accepted_feature", Accepted),
60     ("test_removed_feature", Removed),
61 ];
62
63 enum Status {
64     /// Represents an active feature that is currently being implemented or
65     /// currently being considered for addition/removal.
66     Active,
67
68     /// Represents a feature which has since been removed (it was once Active)
69     Removed,
70
71     /// This language feature has since been Accepted (it was once Active)
72     Accepted,
73 }
74
75 /// A set of features to be used by later passes.
76 pub struct Features {
77     default_type_params: Cell<bool>
78 }
79
80 impl Features {
81     pub fn new() -> Features {
82         Features {
83             default_type_params: Cell::new(false)
84         }
85     }
86 }
87
88 struct Context<'a> {
89     features: Vec<&'static str>,
90     sess: &'a Session,
91 }
92
93 impl<'a> Context<'a> {
94     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
95         if !self.has_feature(feature) {
96             self.sess.span_err(span, explain);
97             self.sess.span_note(span, format!("add \\#[feature({})] to the \
98                                                   crate attributes to enable",
99                                                  feature));
100         }
101     }
102
103     fn gate_box(&self, span: Span) {
104         self.gate_feature("managed_boxes", span,
105                           "The managed box syntax is being replaced by the \
106                            `std::gc::Gc` and `std::rc::Rc` types. Equivalent \
107                            functionality to managed trait objects will be \
108                            implemented but is currently missing.");
109     }
110
111     fn has_feature(&self, feature: &str) -> bool {
112         self.features.iter().any(|n| n.as_slice() == feature)
113     }
114 }
115
116 impl<'a> Visitor<()> for Context<'a> {
117     fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
118         if !token::get_ident(id).get().is_ascii() {
119             self.gate_feature("non_ascii_idents", sp,
120                               "non-ascii idents are not fully supported.");
121         }
122     }
123
124     fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
125         match i.node {
126             ast::ViewItemUse(ref paths) => {
127                 for path in paths.iter() {
128                     match path.node {
129                         ast::ViewPathGlob(..) => {
130                             self.gate_feature("globs", path.span,
131                                               "glob import statements are \
132                                                experimental and possibly buggy");
133                         }
134                         _ => {}
135                     }
136                 }
137             }
138             ast::ViewItemExternCrate(..) => {
139                 for attr in i.attrs.iter() {
140                     if attr.name().get() == "phase"{
141                         self.gate_feature("phase", attr.span,
142                                           "compile time crate loading is \
143                                            experimental and possibly buggy");
144                     }
145                 }
146             }
147         }
148         visit::walk_view_item(self, i, ())
149     }
150
151     fn visit_item(&mut self, i: &ast::Item, _:()) {
152         for attr in i.attrs.iter() {
153             if attr.name().equiv(&("thread_local")) {
154                 self.gate_feature("thread_local", i.span,
155                                   "`#[thread_local]` is an experimental feature, and does not \
156                                   currently handle destructors. There is no corresponding \
157                                   `#[task_local]` mapping to the task model");
158             }
159         }
160         match i.node {
161             ast::ItemEnum(ref def, _) => {
162                 for variant in def.variants.iter() {
163                     match variant.node.kind {
164                         ast::StructVariantKind(..) => {
165                             self.gate_feature("struct_variant", variant.span,
166                                               "enum struct variants are \
167                                                experimental and possibly buggy");
168                         }
169                         _ => {}
170                     }
171                 }
172             }
173
174             ast::ItemForeignMod(..) => {
175                 if attr::contains_name(i.attrs.as_slice(), "link_args") {
176                     self.gate_feature("link_args", i.span,
177                                       "the `link_args` attribute is not portable \
178                                        across platforms, it is recommended to \
179                                        use `#[link(name = \"foo\")]` instead")
180                 }
181             }
182
183             ast::ItemFn(..) => {
184                 if attr::contains_name(i.attrs.as_slice(), "macro_registrar") {
185                     self.gate_feature("macro_registrar", i.span,
186                                       "cross-crate macro exports are \
187                                        experimental and possibly buggy");
188                 }
189             }
190
191             ast::ItemStruct(..) => {
192                 if attr::contains_name(i.attrs.as_slice(), "simd") {
193                     self.gate_feature("simd", i.span,
194                                       "SIMD types are experimental and possibly buggy");
195                 }
196             }
197
198             _ => {}
199         }
200
201         visit::walk_item(self, i, ());
202     }
203
204     fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
205         let ast::MacInvocTT(ref path, _, _) = macro.node;
206         let id = path.segments.last().unwrap().identifier;
207         let quotes = ["quote_tokens", "quote_expr", "quote_ty",
208                       "quote_item", "quote_pat", "quote_stmt"];
209         let msg = " is not stable enough for use and are subject to change";
210
211
212         if id == token::str_to_ident("macro_rules") {
213             self.gate_feature("macro_rules", path.span, "macro definitions are \
214                 not stable enough for use and are subject to change");
215         }
216
217         else if id == token::str_to_ident("asm") {
218             self.gate_feature("asm", path.span, "inline assembly is not \
219                 stable enough for use and is subject to change");
220         }
221
222         else if id == token::str_to_ident("log_syntax") {
223             self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
224                 stable enough for use and is subject to change");
225         }
226
227         else if id == token::str_to_ident("trace_macros") {
228             self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
229                 stable enough for use and is subject to change");
230         }
231
232         else {
233             for &quote in quotes.iter() {
234                 if id == token::str_to_ident(quote) {
235                   self.gate_feature("quote", path.span, quote + msg);
236                 }
237             }
238         }
239     }
240
241     fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
242         match i.node {
243             ast::ForeignItemFn(..) | ast::ForeignItemStatic(..) => {
244                 if attr::contains_name(i.attrs.as_slice(), "linkage") {
245                     self.gate_feature("linkage", i.span,
246                                       "the `linkage` attribute is experimental \
247                                        and not portable across platforms")
248                 }
249             }
250         }
251         visit::walk_foreign_item(self, i, ())
252     }
253
254     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
255         match t.node {
256             ast::TyClosure(closure) if closure.onceness == ast::Once &&
257                     closure.sigil != ast::OwnedSigil => {
258                 self.gate_feature("once_fns", t.span,
259                                   "once functions are \
260                                    experimental and likely to be removed");
261
262             },
263             ast::TyBox(_) => { self.gate_box(t.span); }
264             _ => {}
265         }
266
267         visit::walk_ty(self, t, ());
268     }
269
270     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
271         match e.node {
272             ast::ExprUnary(ast::UnBox, _) => {
273                 self.gate_box(e.span);
274             }
275             _ => {}
276         }
277         visit::walk_expr(self, e, ());
278     }
279
280     fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
281         for type_parameter in generics.ty_params.iter() {
282             match type_parameter.default {
283                 Some(ty) => {
284                     self.gate_feature("default_type_params", ty.span,
285                                       "default type parameters are \
286                                        experimental and possibly buggy");
287                 }
288                 None => {}
289             }
290         }
291         visit::walk_generics(self, generics, ());
292     }
293 }
294
295 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
296     let mut cx = Context {
297         features: Vec::new(),
298         sess: sess,
299     };
300
301     for attr in krate.attrs.iter() {
302         if !attr.name().equiv(&("feature")) {
303             continue
304         }
305
306         match attr.meta_item_list() {
307             None => {
308                 sess.span_err(attr.span, "malformed feature attribute, \
309                                           expected #[feature(...)]");
310             }
311             Some(list) => {
312                 for &mi in list.iter() {
313                     let name = match mi.node {
314                         ast::MetaWord(ref word) => (*word).clone(),
315                         _ => {
316                             sess.span_err(mi.span,
317                                           "malformed feature, expected just \
318                                            one word");
319                             continue
320                         }
321                     };
322                     match KNOWN_FEATURES.iter()
323                                         .find(|& &(n, _)| name.equiv(&n)) {
324                         Some(&(name, Active)) => { cx.features.push(name); }
325                         Some(&(_, Removed)) => {
326                             sess.span_err(mi.span, "feature has been removed");
327                         }
328                         Some(&(_, Accepted)) => {
329                             sess.span_warn(mi.span, "feature has added to rust, \
330                                                      directive not necessary");
331                         }
332                         None => {
333                             sess.add_lint(lint::UnknownFeatures,
334                                           ast::CRATE_NODE_ID,
335                                           mi.span,
336                                           ~"unknown feature");
337                         }
338                     }
339                 }
340             }
341         }
342     }
343
344     visit::walk_crate(&mut cx, krate, ());
345
346     sess.abort_if_errors();
347
348     sess.features.default_type_params.set(cx.has_feature("default_type_params"));
349 }