]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / libsyntax / 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 use self::Status::*;
21
22 use abi::RustIntrinsic;
23 use ast::NodeId;
24 use ast;
25 use attr;
26 use attr::AttrMetaMethods;
27 use codemap::{CodeMap, Span};
28 use diagnostic::SpanHandler;
29 use visit;
30 use visit::Visitor;
31 use parse::token;
32
33 use std::slice;
34 use std::ascii::AsciiExt;
35
36
37 // if you change this list without updating src/doc/reference.md, @cmr will be sad
38 static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
39     ("globs", Active),
40     ("macro_rules", Active),
41     ("struct_variant", Accepted),
42     ("asm", Active),
43     ("managed_boxes", Removed),
44     ("non_ascii_idents", Active),
45     ("thread_local", Active),
46     ("link_args", Active),
47     ("phase", Active),
48     ("plugin_registrar", Active),
49     ("log_syntax", Active),
50     ("trace_macros", Active),
51     ("concat_idents", Active),
52     ("unsafe_destructor", Active),
53     ("intrinsics", Active),
54     ("lang_items", Active),
55
56     ("simd", Active),
57     ("default_type_params", Active),
58     ("quote", Active),
59     ("link_llvm_intrinsics", Active),
60     ("linkage", Active),
61     ("struct_inherit", Removed),
62
63     ("quad_precision_float", Removed),
64
65     ("rustc_diagnostic_macros", Active),
66     ("unboxed_closures", Active),
67     ("import_shadowing", Active),
68     ("advanced_slice_patterns", Active),
69     ("tuple_indexing", Accepted),
70     ("associated_types", Active),
71     ("visible_private_types", Active),
72     ("slicing_syntax", Active),
73
74     ("if_let", Accepted),
75     ("while_let", Accepted),
76
77     // A temporary feature gate used to enable parser extensions needed
78     // to bootstrap fix for #5723.
79     ("issue_5723_bootstrap", Accepted),
80
81     // A way to temporarily opt out of opt in copy. This will *never* be accepted.
82     ("opt_out_copy", Deprecated),
83
84     // A way to temporarily opt out of the new orphan rules. This will *never* be accepted.
85     ("old_orphan_check", Deprecated),
86
87     // These are used to test this portion of the compiler, they don't actually
88     // mean anything
89     ("test_accepted_feature", Accepted),
90     ("test_removed_feature", Removed),
91 ];
92
93 enum Status {
94     /// Represents an active feature that is currently being implemented or
95     /// currently being considered for addition/removal.
96     Active,
97
98     /// Represents a feature gate that is temporarily enabling deprecated behavior.
99     /// This gate will never be accepted.
100     Deprecated,
101
102     /// Represents a feature which has since been removed (it was once Active)
103     Removed,
104
105     /// This language feature has since been Accepted (it was once Active)
106     Accepted,
107 }
108
109 /// A set of features to be used by later passes.
110 #[derive(Copy)]
111 pub struct Features {
112     pub default_type_params: bool,
113     pub unboxed_closures: bool,
114     pub rustc_diagnostic_macros: bool,
115     pub import_shadowing: bool,
116     pub visible_private_types: bool,
117     pub quote: bool,
118     pub opt_out_copy: bool,
119     pub old_orphan_check: bool,
120 }
121
122 impl Features {
123     pub fn new() -> Features {
124         Features {
125             default_type_params: false,
126             unboxed_closures: false,
127             rustc_diagnostic_macros: false,
128             import_shadowing: false,
129             visible_private_types: false,
130             quote: false,
131             opt_out_copy: false,
132             old_orphan_check: false,
133         }
134     }
135 }
136
137 struct Context<'a> {
138     features: Vec<&'static str>,
139     span_handler: &'a SpanHandler,
140     cm: &'a CodeMap,
141 }
142
143 impl<'a> Context<'a> {
144     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
145         if !self.has_feature(feature) {
146             self.span_handler.span_err(span, explain);
147             self.span_handler.span_help(span, format!("add #![feature({})] to the \
148                                                        crate attributes to enable",
149                                                       feature)[]);
150         }
151     }
152
153     fn has_feature(&self, feature: &str) -> bool {
154         self.features.iter().any(|&n| n == feature)
155     }
156 }
157
158 struct MacroVisitor<'a> {
159     context: &'a Context<'a>
160 }
161
162 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
163     fn visit_view_item(&mut self, i: &ast::ViewItem) {
164         match i.node {
165             ast::ViewItemExternCrate(..) => {
166                 for attr in i.attrs.iter() {
167                     if attr.name().get() == "phase"{
168                         self.context.gate_feature("phase", attr.span,
169                                           "compile time crate loading is \
170                                            experimental and possibly buggy");
171                     }
172                 }
173             },
174             _ => { }
175         }
176         visit::walk_view_item(self, i)
177     }
178
179     fn visit_mac(&mut self, macro: &ast::Mac) {
180         let ast::MacInvocTT(ref path, _, _) = macro.node;
181         let id = path.segments.last().unwrap().identifier;
182
183         if id == token::str_to_ident("macro_rules") {
184             self.context.gate_feature("macro_rules", path.span, "macro definitions are \
185                 not stable enough for use and are subject to change");
186         }
187
188         else if id == token::str_to_ident("asm") {
189             self.context.gate_feature("asm", path.span, "inline assembly is not \
190                 stable enough for use and is subject to change");
191         }
192
193         else if id == token::str_to_ident("log_syntax") {
194             self.context.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
195                 stable enough for use and is subject to change");
196         }
197
198         else if id == token::str_to_ident("trace_macros") {
199             self.context.gate_feature("trace_macros", path.span, "`trace_macros` is not \
200                 stable enough for use and is subject to change");
201         }
202
203         else if id == token::str_to_ident("concat_idents") {
204             self.context.gate_feature("concat_idents", path.span, "`concat_idents` is not \
205                 stable enough for use and is subject to change");
206         }
207     }
208 }
209
210 struct PostExpansionVisitor<'a> {
211     context: &'a Context<'a>
212 }
213
214 impl<'a> PostExpansionVisitor<'a> {
215     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
216         if !self.context.cm.span_is_internal(span) {
217             self.context.gate_feature(feature, span, explain)
218         }
219     }
220 }
221
222 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
223     fn visit_name(&mut self, sp: Span, name: ast::Name) {
224         if !token::get_name(name).get().is_ascii() {
225             self.gate_feature("non_ascii_idents", sp,
226                               "non-ascii idents are not fully supported.");
227         }
228     }
229
230     fn visit_view_item(&mut self, i: &ast::ViewItem) {
231         match i.node {
232             ast::ViewItemUse(ref path) => {
233                 if let ast::ViewPathGlob(..) = path.node {
234                     self.gate_feature("globs", path.span,
235                                       "glob import statements are \
236                                        experimental and possibly buggy");
237                 }
238             }
239             ast::ViewItemExternCrate(..) => {
240                 for attr in i.attrs.iter() {
241                     if attr.name().get() == "phase"{
242                         self.gate_feature("phase", attr.span,
243                                           "compile time crate loading is \
244                                            experimental and possibly buggy");
245                     }
246                 }
247             }
248         }
249         visit::walk_view_item(self, i)
250     }
251
252     fn visit_item(&mut self, i: &ast::Item) {
253         for attr in i.attrs.iter() {
254             if attr.name() == "thread_local" {
255                 self.gate_feature("thread_local", i.span,
256                                   "`#[thread_local]` is an experimental feature, and does not \
257                                   currently handle destructors. There is no corresponding \
258                                   `#[task_local]` mapping to the task model");
259             } else if attr.name() == "linkage" {
260                 self.gate_feature("linkage", i.span,
261                                   "the `linkage` attribute is experimental \
262                                    and not portable across platforms")
263             }
264         }
265         match i.node {
266             ast::ItemForeignMod(ref foreign_module) => {
267                 if attr::contains_name(i.attrs[], "link_args") {
268                     self.gate_feature("link_args", i.span,
269                                       "the `link_args` attribute is not portable \
270                                        across platforms, it is recommended to \
271                                        use `#[link(name = \"foo\")]` instead")
272                 }
273                 if foreign_module.abi == RustIntrinsic {
274                     self.gate_feature("intrinsics",
275                                       i.span,
276                                       "intrinsics are subject to change")
277                 }
278             }
279
280             ast::ItemFn(..) => {
281                 if attr::contains_name(i.attrs[], "plugin_registrar") {
282                     self.gate_feature("plugin_registrar", i.span,
283                                       "compiler plugins are experimental and possibly buggy");
284                 }
285             }
286
287             ast::ItemStruct(..) => {
288                 if attr::contains_name(i.attrs[], "simd") {
289                     self.gate_feature("simd", i.span,
290                                       "SIMD types are experimental and possibly buggy");
291                 }
292             }
293
294             ast::ItemImpl(_, _, _, _, ref items) => {
295                 if attr::contains_name(i.attrs[],
296                                        "unsafe_destructor") {
297                     self.gate_feature("unsafe_destructor",
298                                       i.span,
299                                       "`#[unsafe_destructor]` allows too \
300                                        many unsafe patterns and may be \
301                                        removed in the future");
302                 }
303
304                 for item in items.iter() {
305                     match *item {
306                         ast::MethodImplItem(_) => {}
307                         ast::TypeImplItem(ref typedef) => {
308                             self.gate_feature("associated_types",
309                                               typedef.span,
310                                               "associated types are \
311                                                experimental")
312                         }
313                     }
314                 }
315             }
316
317             _ => {}
318         }
319
320         visit::walk_item(self, i);
321     }
322
323     fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
324         match *trait_item {
325             ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
326             ast::TypeTraitItem(ref ti) => {
327                 self.gate_feature("associated_types",
328                                   ti.ty_param.span,
329                                   "associated types are experimental")
330             }
331         }
332     }
333
334     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
335         if attr::contains_name(i.attrs[], "linkage") {
336             self.gate_feature("linkage", i.span,
337                               "the `linkage` attribute is experimental \
338                                and not portable across platforms")
339         }
340
341         let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") {
342             Some(val) => val.get().starts_with("llvm."),
343             _ => false
344         };
345         if links_to_llvm {
346             self.gate_feature("link_llvm_intrinsics", i.span,
347                               "linking to LLVM intrinsics is experimental");
348         }
349
350         visit::walk_foreign_item(self, i)
351     }
352
353     fn visit_ty(&mut self, t: &ast::Ty) {
354         if let ast::TyClosure(ref closure) =  t.node {
355             // this used to be blocked by a feature gate, but it should just
356             // be plain impossible right now
357             assert!(closure.onceness != ast::Once);
358         }
359
360         visit::walk_ty(self, t);
361     }
362
363     fn visit_expr(&mut self, e: &ast::Expr) {
364         match e.node {
365             ast::ExprRange(..) => {
366                 self.gate_feature("slicing_syntax",
367                                   e.span,
368                                   "range syntax is experimental");
369             }
370             _ => {}
371         }
372         visit::walk_expr(self, e);
373     }
374
375     fn visit_generics(&mut self, generics: &ast::Generics) {
376         for type_parameter in generics.ty_params.iter() {
377             match type_parameter.default {
378                 Some(ref ty) => {
379                     self.gate_feature("default_type_params", ty.span,
380                                       "default type parameters are \
381                                        experimental and possibly buggy");
382                 }
383                 None => {}
384             }
385         }
386         visit::walk_generics(self, generics);
387     }
388
389     fn visit_attribute(&mut self, attr: &ast::Attribute) {
390         if attr::contains_name(slice::ref_slice(attr), "lang") {
391             self.gate_feature("lang_items",
392                               attr.span,
393                               "language items are subject to change");
394         }
395     }
396
397     fn visit_pat(&mut self, pattern: &ast::Pat) {
398         match pattern.node {
399             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
400                 self.gate_feature("advanced_slice_patterns",
401                                   pattern.span,
402                                   "multiple-element slice matches anywhere \
403                                    but at the end of a slice (e.g. \
404                                    `[0, ..xs, 0]` are experimental")
405             }
406             _ => {}
407         }
408         visit::walk_pat(self, pattern)
409     }
410
411     fn visit_fn(&mut self,
412                 fn_kind: visit::FnKind<'v>,
413                 fn_decl: &'v ast::FnDecl,
414                 block: &'v ast::Block,
415                 span: Span,
416                 _node_id: NodeId) {
417         match fn_kind {
418             visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
419                 self.gate_feature("intrinsics",
420                                   span,
421                                   "intrinsics are subject to change")
422             }
423             _ => {}
424         }
425         visit::walk_fn(self, fn_kind, fn_decl, block, span);
426     }
427 }
428
429 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
430                         check: F)
431                        -> (Features, Vec<Span>)
432     where F: FnOnce(&mut Context, &ast::Crate)
433 {
434     let mut cx = Context {
435         features: Vec::new(),
436         span_handler: span_handler,
437         cm: cm,
438     };
439
440     let mut unknown_features = Vec::new();
441
442     for attr in krate.attrs.iter() {
443         if !attr.check_name("feature") {
444             continue
445         }
446
447         match attr.meta_item_list() {
448             None => {
449                 span_handler.span_err(attr.span, "malformed feature attribute, \
450                                                   expected #![feature(...)]");
451             }
452             Some(list) => {
453                 for mi in list.iter() {
454                     let name = match mi.node {
455                         ast::MetaWord(ref word) => (*word).clone(),
456                         _ => {
457                             span_handler.span_err(mi.span,
458                                                   "malformed feature, expected just \
459                                                    one word");
460                             continue
461                         }
462                     };
463                     match KNOWN_FEATURES.iter()
464                                         .find(|& &(n, _)| name == n) {
465                         Some(&(name, Active)) => {
466                             cx.features.push(name);
467                         }
468                         Some(&(name, Deprecated)) => {
469                             cx.features.push(name);
470                             span_handler.span_warn(
471                                 mi.span,
472                                 "feature is deprecated and will only be available \
473                                  for a limited time, please rewrite code that relies on it");
474                         }
475                         Some(&(_, Removed)) => {
476                             span_handler.span_err(mi.span, "feature has been removed");
477                         }
478                         Some(&(_, Accepted)) => {
479                             span_handler.span_warn(mi.span, "feature has been added to Rust, \
480                                                              directive not necessary");
481                         }
482                         None => {
483                             unknown_features.push(mi.span);
484                         }
485                     }
486                 }
487             }
488         }
489     }
490
491     check(&mut cx, krate);
492
493     (Features {
494         default_type_params: cx.has_feature("default_type_params"),
495         unboxed_closures: cx.has_feature("unboxed_closures"),
496         rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
497         import_shadowing: cx.has_feature("import_shadowing"),
498         visible_private_types: cx.has_feature("visible_private_types"),
499         quote: cx.has_feature("quote"),
500         opt_out_copy: cx.has_feature("opt_out_copy"),
501         old_orphan_check: cx.has_feature("old_orphan_check"),
502     },
503     unknown_features)
504 }
505
506 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
507 -> (Features, Vec<Span>) {
508     check_crate_inner(cm, span_handler, krate,
509                       |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
510 }
511
512 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
513 -> (Features, Vec<Span>) {
514     check_crate_inner(cm, span_handler, krate,
515                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
516                                                      krate))
517 }