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