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