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