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