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