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