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