]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/feature_gate.rs
auto merge of #14715 : vhbit/rust/ios-pr2, 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 middle::lint;
22
23 use syntax::ast;
24 use syntax::attr;
25 use syntax::attr::AttrMetaMethods;
26 use syntax::codemap::Span;
27 use syntax::visit;
28 use syntax::visit::Visitor;
29 use syntax::parse::token;
30
31 use driver::session::Session;
32
33 use std::cell::Cell;
34
35 /// This is a list of all known features since the beginning of time. This list
36 /// can never shrink, it may only be expanded (in order to prevent old programs
37 /// from failing to compile). The status of each feature may change, however.
38 static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
39     ("globs", Active),
40     ("macro_rules", Active),
41     ("struct_variant", Active),
42     ("once_fns", Active),
43     ("asm", Active),
44     ("managed_boxes", Active),
45     ("non_ascii_idents", Active),
46     ("thread_local", Active),
47     ("link_args", Active),
48     ("phase", Active),
49     ("plugin_registrar", Active),
50     ("log_syntax", Active),
51     ("trace_macros", Active),
52     ("concat_idents", Active),
53
54     ("simd", Active),
55     ("default_type_params", Active),
56     ("quote", Active),
57     ("linkage", Active),
58     ("struct_inherit", Active),
59     ("overloaded_calls", Active),
60     ("unboxed_closure_sugar", Active),
61
62     ("quad_precision_float", Active),
63
64     // A temporary feature gate used to enable parser extensions needed
65     // to bootstrap fix for #5723.
66     ("issue_5723_bootstrap", Active),
67
68     // These are used to test this portion of the compiler, they don't actually
69     // mean anything
70     ("test_accepted_feature", Accepted),
71     ("test_removed_feature", Removed),
72 ];
73
74 enum Status {
75     /// Represents an active feature that is currently being implemented or
76     /// currently being considered for addition/removal.
77     Active,
78
79     /// Represents a feature which has since been removed (it was once Active)
80     Removed,
81
82     /// This language feature has since been Accepted (it was once Active)
83     Accepted,
84 }
85
86 /// A set of features to be used by later passes.
87 pub struct Features {
88     pub default_type_params: Cell<bool>,
89     pub quad_precision_float: Cell<bool>,
90     pub issue_5723_bootstrap: Cell<bool>,
91     pub overloaded_calls: Cell<bool>,
92 }
93
94 impl Features {
95     pub fn new() -> Features {
96         Features {
97             default_type_params: Cell::new(false),
98             quad_precision_float: Cell::new(false),
99             issue_5723_bootstrap: Cell::new(false),
100             overloaded_calls: Cell::new(false),
101         }
102     }
103 }
104
105 struct Context<'a> {
106     features: Vec<&'static str>,
107     sess: &'a Session,
108 }
109
110 impl<'a> Context<'a> {
111     #[cfg(stage0)]
112     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
113         if !self.has_feature(feature) {
114             self.sess.span_err(span, explain);
115             self.sess.span_note(span, format!("add \\#![feature({})] to the \
116                                                   crate attributes to enable",
117                                                  feature).as_slice());
118         }
119     }
120     #[cfg(not(stage0))]
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(..) => {
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             }
207
208             ast::ItemFn(..) => {
209                 if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
210                     self.gate_feature("plugin_registrar", i.span,
211                                       "compiler plugins are experimental and possibly buggy");
212                 }
213             }
214
215             ast::ItemStruct(struct_definition, _) => {
216                 if attr::contains_name(i.attrs.as_slice(), "simd") {
217                     self.gate_feature("simd", i.span,
218                                       "SIMD types are experimental and possibly buggy");
219                 }
220                 match struct_definition.super_struct {
221                     Some(ref path) => self.gate_feature("struct_inherit", path.span,
222                                                         "struct inheritance is experimental \
223                                                          and possibly buggy"),
224                     None => {}
225                 }
226                 if struct_definition.is_virtual {
227                     self.gate_feature("struct_inherit", i.span,
228                                       "struct inheritance (`virtual` keyword) is \
229                                        experimental and possibly buggy");
230                 }
231             }
232
233             _ => {}
234         }
235
236         visit::walk_item(self, i, ());
237     }
238
239     fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
240         let ast::MacInvocTT(ref path, _, _) = macro.node;
241         let id = path.segments.last().unwrap().identifier;
242         let quotes = ["quote_tokens", "quote_expr", "quote_ty",
243                       "quote_item", "quote_pat", "quote_stmt"];
244         let msg = " is not stable enough for use and are subject to change";
245
246
247         if id == token::str_to_ident("macro_rules") {
248             self.gate_feature("macro_rules", path.span, "macro definitions are \
249                 not stable enough for use and are subject to change");
250         }
251
252         else if id == token::str_to_ident("asm") {
253             self.gate_feature("asm", path.span, "inline assembly is not \
254                 stable enough for use and is subject to change");
255         }
256
257         else if id == token::str_to_ident("log_syntax") {
258             self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
259                 stable enough for use and is subject to change");
260         }
261
262         else if id == token::str_to_ident("trace_macros") {
263             self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
264                 stable enough for use and is subject to change");
265         }
266
267         else if id == token::str_to_ident("concat_idents") {
268             self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
269                 stable enough for use and is subject to change");
270         }
271
272         else {
273             for &quote in quotes.iter() {
274                 if id == token::str_to_ident(quote) {
275                   self.gate_feature("quote",
276                                     path.span,
277                                     format!("{}{}", quote, msg).as_slice());
278                 }
279             }
280         }
281     }
282
283     fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
284         match i.node {
285             ast::ForeignItemFn(..) | ast::ForeignItemStatic(..) => {
286                 if attr::contains_name(i.attrs.as_slice(), "linkage") {
287                     self.gate_feature("linkage", i.span,
288                                       "the `linkage` attribute is experimental \
289                                        and not portable across platforms")
290                 }
291             }
292         }
293         visit::walk_foreign_item(self, i, ())
294     }
295
296     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
297         match t.node {
298             ast::TyClosure(closure, _) if closure.onceness == ast::Once => {
299                 self.gate_feature("once_fns", t.span,
300                                   "once functions are \
301                                    experimental and likely to be removed");
302
303             },
304             ast::TyBox(_) => { self.gate_box(t.span); }
305             ast::TyUnboxedFn(_) => {
306                 self.gate_feature("unboxed_closure_sugar",
307                                   t.span,
308                                   "unboxed closure trait sugar is experimental");
309             }
310             _ => {}
311         }
312
313         visit::walk_ty(self, t, ());
314     }
315
316     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
317         match e.node {
318             ast::ExprUnary(ast::UnBox, _) => {
319                 self.gate_box(e.span);
320             }
321             _ => {}
322         }
323         visit::walk_expr(self, e, ());
324     }
325
326     fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
327         for type_parameter in generics.ty_params.iter() {
328             match type_parameter.default {
329                 Some(ty) => {
330                     self.gate_feature("default_type_params", ty.span,
331                                       "default type parameters are \
332                                        experimental and possibly buggy");
333                 }
334                 None => {}
335             }
336         }
337         visit::walk_generics(self, generics, ());
338     }
339 }
340
341 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
342     let mut cx = Context {
343         features: Vec::new(),
344         sess: sess,
345     };
346
347     for attr in krate.attrs.iter() {
348         if !attr.check_name("feature") {
349             continue
350         }
351
352         match attr.meta_item_list() {
353             None => {
354                 sess.span_err(attr.span, "malformed feature attribute, \
355                                           expected #![feature(...)]");
356             }
357             Some(list) => {
358                 for &mi in list.iter() {
359                     let name = match mi.node {
360                         ast::MetaWord(ref word) => (*word).clone(),
361                         _ => {
362                             sess.span_err(mi.span,
363                                           "malformed feature, expected just \
364                                            one word");
365                             continue
366                         }
367                     };
368                     match KNOWN_FEATURES.iter()
369                                         .find(|& &(n, _)| name.equiv(&n)) {
370                         Some(&(name, Active)) => { cx.features.push(name); }
371                         Some(&(_, Removed)) => {
372                             sess.span_err(mi.span, "feature has been removed");
373                         }
374                         Some(&(_, Accepted)) => {
375                             sess.span_warn(mi.span, "feature has added to rust, \
376                                                      directive not necessary");
377                         }
378                         None => {
379                             sess.add_lint(lint::UnknownFeatures,
380                                           ast::CRATE_NODE_ID,
381                                           mi.span,
382                                           "unknown feature".to_string());
383                         }
384                     }
385                 }
386             }
387         }
388     }
389
390     visit::walk_crate(&mut cx, krate, ());
391
392     sess.abort_if_errors();
393
394     sess.features.default_type_params.set(cx.has_feature("default_type_params"));
395     sess.features.quad_precision_float.set(cx.has_feature("quad_precision_float"));
396     sess.features.issue_5723_bootstrap.set(cx.has_feature("issue_5723_bootstrap"));
397     sess.features.overloaded_calls.set(cx.has_feature("overloaded_calls"));
398 }