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