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