]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/feature_gate.rs
Add a few more derivings to AST types
[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 lint;
22
23 use syntax::abi::RustIntrinsic;
24 use syntax::ast::NodeId;
25 use syntax::ast;
26 use syntax::attr;
27 use syntax::attr::AttrMetaMethods;
28 use syntax::codemap::Span;
29 use syntax::visit;
30 use syntax::visit::Visitor;
31 use syntax::parse::token;
32
33 use driver::session::Session;
34
35 use std::cell::Cell;
36
37 /// This is a list of all known features since the beginning of time. This list
38 /// can never shrink, it may only be expanded (in order to prevent old programs
39 /// from failing to compile). The status of each feature may change, however.
40 static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
41     ("globs", Active),
42     ("macro_rules", Active),
43     ("struct_variant", Active),
44     ("once_fns", Active),
45     ("asm", Active),
46     ("managed_boxes", Active),
47     ("non_ascii_idents", Active),
48     ("thread_local", Active),
49     ("link_args", Active),
50     ("phase", Active),
51     ("plugin_registrar", Active),
52     ("log_syntax", Active),
53     ("trace_macros", Active),
54     ("concat_idents", Active),
55     ("unsafe_destructor", Active),
56     ("intrinsics", Active),
57     ("lang_items", Active),
58
59     ("simd", Active),
60     ("default_type_params", Active),
61     ("quote", Active),
62     ("linkage", Active),
63     ("struct_inherit", Active),
64     ("overloaded_calls", Active),
65     ("unboxed_closure_sugar", Active),
66
67     ("quad_precision_float", Removed),
68
69     ("rustc_diagnostic_macros", Active),
70     ("unboxed_closures", Active),
71
72     // A temporary feature gate used to enable parser extensions needed
73     // to bootstrap fix for #5723.
74     ("issue_5723_bootstrap", Active),
75
76     // These are used to test this portion of the compiler, they don't actually
77     // mean anything
78     ("test_accepted_feature", Accepted),
79     ("test_removed_feature", Removed),
80 ];
81
82 enum Status {
83     /// Represents an active feature that is currently being implemented or
84     /// currently being considered for addition/removal.
85     Active,
86
87     /// Represents a feature which has since been removed (it was once Active)
88     Removed,
89
90     /// This language feature has since been Accepted (it was once Active)
91     Accepted,
92 }
93
94 /// A set of features to be used by later passes.
95 pub struct Features {
96     pub default_type_params: Cell<bool>,
97     pub issue_5723_bootstrap: Cell<bool>,
98     pub overloaded_calls: Cell<bool>,
99     pub rustc_diagnostic_macros: Cell<bool>
100 }
101
102 impl Features {
103     pub fn new() -> Features {
104         Features {
105             default_type_params: Cell::new(false),
106             issue_5723_bootstrap: Cell::new(false),
107             overloaded_calls: Cell::new(false),
108             rustc_diagnostic_macros: Cell::new(false)
109         }
110     }
111 }
112
113 struct Context<'a> {
114     features: Vec<&'static str>,
115     sess: &'a Session,
116 }
117
118 impl<'a> Context<'a> {
119     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
120         if !self.has_feature(feature) {
121             self.sess.span_err(span, explain);
122             self.sess.span_note(span, format!("add #![feature({})] to the \
123                                                crate attributes to enable",
124                                               feature).as_slice());
125         }
126     }
127
128     fn gate_box(&self, span: Span) {
129         self.gate_feature("managed_boxes", span,
130                           "The managed box syntax is being replaced by the \
131                            `std::gc::Gc` and `std::rc::Rc` types. Equivalent \
132                            functionality to managed trait objects will be \
133                            implemented but is currently missing.");
134     }
135
136     fn has_feature(&self, feature: &str) -> bool {
137         self.features.iter().any(|n| n.as_slice() == feature)
138     }
139 }
140
141 impl<'a> Visitor<()> for Context<'a> {
142     fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
143         if !token::get_ident(id).get().is_ascii() {
144             self.gate_feature("non_ascii_idents", sp,
145                               "non-ascii idents are not fully supported.");
146         }
147     }
148
149     fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
150         match i.node {
151             ast::ViewItemUse(ref path) => {
152                 match path.node {
153                     ast::ViewPathGlob(..) => {
154                         self.gate_feature("globs", path.span,
155                                           "glob import statements are \
156                                            experimental and possibly buggy");
157                     }
158                     _ => {}
159                 }
160             }
161             ast::ViewItemExternCrate(..) => {
162                 for attr in i.attrs.iter() {
163                     if attr.name().get() == "phase"{
164                         self.gate_feature("phase", attr.span,
165                                           "compile time crate loading is \
166                                            experimental and possibly buggy");
167                     }
168                 }
169             }
170         }
171         visit::walk_view_item(self, i, ())
172     }
173
174     fn visit_item(&mut self, i: &ast::Item, _:()) {
175         for attr in i.attrs.iter() {
176             if attr.name().equiv(&("thread_local")) {
177                 self.gate_feature("thread_local", i.span,
178                                   "`#[thread_local]` is an experimental feature, and does not \
179                                   currently handle destructors. There is no corresponding \
180                                   `#[task_local]` mapping to the task model");
181             }
182         }
183         match i.node {
184             ast::ItemEnum(ref def, _) => {
185                 for variant in def.variants.iter() {
186                     match variant.node.kind {
187                         ast::StructVariantKind(..) => {
188                             self.gate_feature("struct_variant", variant.span,
189                                               "enum struct variants are \
190                                                experimental and possibly buggy");
191                         }
192                         _ => {}
193                     }
194                 }
195             }
196
197             ast::ItemForeignMod(ref foreign_module) => {
198                 if attr::contains_name(i.attrs.as_slice(), "link_args") {
199                     self.gate_feature("link_args", i.span,
200                                       "the `link_args` attribute is not portable \
201                                        across platforms, it is recommended to \
202                                        use `#[link(name = \"foo\")]` instead")
203                 }
204                 if foreign_module.abi == RustIntrinsic {
205                     self.gate_feature("intrinsics",
206                                       i.span,
207                                       "intrinsics are subject to change")
208                 }
209             }
210
211             ast::ItemFn(..) => {
212                 if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
213                     self.gate_feature("plugin_registrar", i.span,
214                                       "compiler plugins are experimental and possibly buggy");
215                 }
216             }
217
218             ast::ItemStruct(struct_definition, _) => {
219                 if attr::contains_name(i.attrs.as_slice(), "simd") {
220                     self.gate_feature("simd", i.span,
221                                       "SIMD types are experimental and possibly buggy");
222                 }
223                 match struct_definition.super_struct {
224                     Some(ref path) => self.gate_feature("struct_inherit", path.span,
225                                                         "struct inheritance is experimental \
226                                                          and possibly buggy"),
227                     None => {}
228                 }
229                 if struct_definition.is_virtual {
230                     self.gate_feature("struct_inherit", i.span,
231                                       "struct inheritance (`virtual` keyword) is \
232                                        experimental and possibly buggy");
233                 }
234             }
235
236             ast::ItemImpl(..) => {
237                 if attr::contains_name(i.attrs.as_slice(),
238                                        "unsafe_destructor") {
239                     self.gate_feature("unsafe_destructor",
240                                       i.span,
241                                       "`#[unsafe_destructor]` allows too \
242                                        many unsafe patterns and may be \
243                                        removed in the future");
244                 }
245             }
246
247             _ => {}
248         }
249
250         visit::walk_item(self, i, ());
251     }
252
253     fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
254         let ast::MacInvocTT(ref path, _, _) = macro.node;
255         let id = path.segments.last().unwrap().identifier;
256         let quotes = ["quote_tokens", "quote_expr", "quote_ty",
257                       "quote_item", "quote_pat", "quote_stmt"];
258         let msg = " is not stable enough for use and are subject to change";
259
260
261         if id == token::str_to_ident("macro_rules") {
262             self.gate_feature("macro_rules", path.span, "macro definitions are \
263                 not stable enough for use and are subject to change");
264         }
265
266         else if id == token::str_to_ident("asm") {
267             self.gate_feature("asm", path.span, "inline assembly is not \
268                 stable enough for use and is subject to change");
269         }
270
271         else if id == token::str_to_ident("log_syntax") {
272             self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
273                 stable enough for use and is subject to change");
274         }
275
276         else if id == token::str_to_ident("trace_macros") {
277             self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
278                 stable enough for use and is subject to change");
279         }
280
281         else if id == token::str_to_ident("concat_idents") {
282             self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
283                 stable enough for use and is subject to change");
284         }
285
286         else {
287             for &quote in quotes.iter() {
288                 if id == token::str_to_ident(quote) {
289                   self.gate_feature("quote",
290                                     path.span,
291                                     format!("{}{}", quote, msg).as_slice());
292                 }
293             }
294         }
295     }
296
297     fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
298         if attr::contains_name(i.attrs.as_slice(), "linkage") {
299             self.gate_feature("linkage", i.span,
300                               "the `linkage` attribute is experimental \
301                                and not portable across platforms")
302         }
303         visit::walk_foreign_item(self, i, ())
304     }
305
306     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
307         match t.node {
308             ast::TyClosure(closure, _) if closure.onceness == ast::Once => {
309                 self.gate_feature("once_fns", t.span,
310                                   "once functions are \
311                                    experimental and likely to be removed");
312
313             },
314             ast::TyBox(_) => { self.gate_box(t.span); }
315             ast::TyUnboxedFn(_) => {
316                 self.gate_feature("unboxed_closure_sugar",
317                                   t.span,
318                                   "unboxed closure trait sugar is experimental");
319             }
320             _ => {}
321         }
322
323         visit::walk_ty(self, t, ());
324     }
325
326     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
327         match e.node {
328             ast::ExprUnary(ast::UnBox, _) => {
329                 self.gate_box(e.span);
330             }
331             ast::ExprUnboxedFn(..) => {
332                 self.gate_feature("unboxed_closures",
333                                   e.span,
334                                   "unboxed closures are a work-in-progress \
335                                    feature with known bugs");
336             }
337             _ => {}
338         }
339         visit::walk_expr(self, e, ());
340     }
341
342     fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
343         for type_parameter in generics.ty_params.iter() {
344             match type_parameter.default {
345                 Some(ty) => {
346                     self.gate_feature("default_type_params", ty.span,
347                                       "default type parameters are \
348                                        experimental and possibly buggy");
349                 }
350                 None => {}
351             }
352         }
353         visit::walk_generics(self, generics, ());
354     }
355
356     fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
357         if attr::contains_name([*attr], "lang") {
358             self.gate_feature("lang_items",
359                               attr.span,
360                               "language items are subject to change");
361         }
362     }
363
364     fn visit_fn(&mut self,
365                 fn_kind: &visit::FnKind,
366                 fn_decl: &ast::FnDecl,
367                 block: &ast::Block,
368                 span: Span,
369                 _: NodeId,
370                 (): ()) {
371         match *fn_kind {
372             visit::FkItemFn(_, _, _, ref abi) if *abi == RustIntrinsic => {
373                 self.gate_feature("intrinsics",
374                                   span,
375                                   "intrinsics are subject to change")
376             }
377             _ => {}
378         }
379         visit::walk_fn(self, fn_kind, fn_decl, block, span, ());
380     }
381 }
382
383 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
384     let mut cx = Context {
385         features: Vec::new(),
386         sess: sess,
387     };
388
389     for attr in krate.attrs.iter() {
390         if !attr.check_name("feature") {
391             continue
392         }
393
394         match attr.meta_item_list() {
395             None => {
396                 sess.span_err(attr.span, "malformed feature attribute, \
397                                           expected #![feature(...)]");
398             }
399             Some(list) => {
400                 for &mi in list.iter() {
401                     let name = match mi.node {
402                         ast::MetaWord(ref word) => (*word).clone(),
403                         _ => {
404                             sess.span_err(mi.span,
405                                           "malformed feature, expected just \
406                                            one word");
407                             continue
408                         }
409                     };
410                     match KNOWN_FEATURES.iter()
411                                         .find(|& &(n, _)| name.equiv(&n)) {
412                         Some(&(name, Active)) => { cx.features.push(name); }
413                         Some(&(_, Removed)) => {
414                             sess.span_err(mi.span, "feature has been removed");
415                         }
416                         Some(&(_, Accepted)) => {
417                             sess.span_warn(mi.span, "feature has added to rust, \
418                                                      directive not necessary");
419                         }
420                         None => {
421                             sess.add_lint(lint::builtin::UNKNOWN_FEATURES,
422                                           ast::CRATE_NODE_ID,
423                                           mi.span,
424                                           "unknown feature".to_string());
425                         }
426                     }
427                 }
428             }
429         }
430     }
431
432     visit::walk_crate(&mut cx, krate, ());
433
434     sess.abort_if_errors();
435
436     sess.features.default_type_params.set(cx.has_feature("default_type_params"));
437     sess.features.issue_5723_bootstrap.set(cx.has_feature("issue_5723_bootstrap"));
438     sess.features.overloaded_calls.set(cx.has_feature("overloaded_calls"));
439     sess.features.rustc_diagnostic_macros.set(cx.has_feature("rustc_diagnostic_macros"));
440 }