]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/feature_gate.rs
f08c40ff0997b0556d15e904e65645fbf9a1b08d
[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                 if attr::contains_name(i.attrs[],
305                                        "old_orphan_check") {
306                     self.gate_feature(
307                         "old_orphan_check",
308                         i.span,
309                         "the new orphan check rules will eventually be strictly enforced");
310                 }
311
312                 for item in items.iter() {
313                     match *item {
314                         ast::MethodImplItem(_) => {}
315                         ast::TypeImplItem(ref typedef) => {
316                             self.gate_feature("associated_types",
317                                               typedef.span,
318                                               "associated types are \
319                                                experimental")
320                         }
321                     }
322                 }
323             }
324
325             _ => {}
326         }
327
328         visit::walk_item(self, i);
329     }
330
331     fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
332         match *trait_item {
333             ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
334             ast::TypeTraitItem(ref ti) => {
335                 self.gate_feature("associated_types",
336                                   ti.ty_param.span,
337                                   "associated types are experimental")
338             }
339         }
340     }
341
342     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
343         if attr::contains_name(i.attrs[], "linkage") {
344             self.gate_feature("linkage", i.span,
345                               "the `linkage` attribute is experimental \
346                                and not portable across platforms")
347         }
348
349         let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") {
350             Some(val) => val.get().starts_with("llvm."),
351             _ => false
352         };
353         if links_to_llvm {
354             self.gate_feature("link_llvm_intrinsics", i.span,
355                               "linking to LLVM intrinsics is experimental");
356         }
357
358         visit::walk_foreign_item(self, i)
359     }
360
361     fn visit_ty(&mut self, t: &ast::Ty) {
362         if let ast::TyClosure(ref closure) =  t.node {
363             // this used to be blocked by a feature gate, but it should just
364             // be plain impossible right now
365             assert!(closure.onceness != ast::Once);
366         }
367
368         visit::walk_ty(self, t);
369     }
370
371     fn visit_expr(&mut self, e: &ast::Expr) {
372         match e.node {
373             ast::ExprRange(..) => {
374                 self.gate_feature("slicing_syntax",
375                                   e.span,
376                                   "range syntax is experimental");
377             }
378             _ => {}
379         }
380         visit::walk_expr(self, e);
381     }
382
383     fn visit_generics(&mut self, generics: &ast::Generics) {
384         for type_parameter in generics.ty_params.iter() {
385             match type_parameter.default {
386                 Some(ref ty) => {
387                     self.gate_feature("default_type_params", ty.span,
388                                       "default type parameters are \
389                                        experimental and possibly buggy");
390                 }
391                 None => {}
392             }
393         }
394         visit::walk_generics(self, generics);
395     }
396
397     fn visit_attribute(&mut self, attr: &ast::Attribute) {
398         if attr::contains_name(slice::ref_slice(attr), "lang") {
399             self.gate_feature("lang_items",
400                               attr.span,
401                               "language items are subject to change");
402         }
403     }
404
405     fn visit_pat(&mut self, pattern: &ast::Pat) {
406         match pattern.node {
407             ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
408                 self.gate_feature("advanced_slice_patterns",
409                                   pattern.span,
410                                   "multiple-element slice matches anywhere \
411                                    but at the end of a slice (e.g. \
412                                    `[0, ..xs, 0]` are experimental")
413             }
414             _ => {}
415         }
416         visit::walk_pat(self, pattern)
417     }
418
419     fn visit_fn(&mut self,
420                 fn_kind: visit::FnKind<'v>,
421                 fn_decl: &'v ast::FnDecl,
422                 block: &'v ast::Block,
423                 span: Span,
424                 _node_id: NodeId) {
425         match fn_kind {
426             visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
427                 self.gate_feature("intrinsics",
428                                   span,
429                                   "intrinsics are subject to change")
430             }
431             _ => {}
432         }
433         visit::walk_fn(self, fn_kind, fn_decl, block, span);
434     }
435 }
436
437 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
438                         check: F)
439                        -> (Features, Vec<Span>)
440     where F: FnOnce(&mut Context, &ast::Crate)
441 {
442     let mut cx = Context {
443         features: Vec::new(),
444         span_handler: span_handler,
445         cm: cm,
446     };
447
448     let mut unknown_features = Vec::new();
449
450     for attr in krate.attrs.iter() {
451         if !attr.check_name("feature") {
452             continue
453         }
454
455         match attr.meta_item_list() {
456             None => {
457                 span_handler.span_err(attr.span, "malformed feature attribute, \
458                                                   expected #![feature(...)]");
459             }
460             Some(list) => {
461                 for mi in list.iter() {
462                     let name = match mi.node {
463                         ast::MetaWord(ref word) => (*word).clone(),
464                         _ => {
465                             span_handler.span_err(mi.span,
466                                                   "malformed feature, expected just \
467                                                    one word");
468                             continue
469                         }
470                     };
471                     match KNOWN_FEATURES.iter()
472                                         .find(|& &(n, _)| name == n) {
473                         Some(&(name, Active)) => {
474                             cx.features.push(name);
475                         }
476                         Some(&(name, Deprecated)) => {
477                             cx.features.push(name);
478                             span_handler.span_warn(
479                                 mi.span,
480                                 "feature is deprecated and will only be available \
481                                  for a limited time, please rewrite code that relies on it");
482                         }
483                         Some(&(_, Removed)) => {
484                             span_handler.span_err(mi.span, "feature has been removed");
485                         }
486                         Some(&(_, Accepted)) => {
487                             span_handler.span_warn(mi.span, "feature has been added to Rust, \
488                                                              directive not necessary");
489                         }
490                         None => {
491                             unknown_features.push(mi.span);
492                         }
493                     }
494                 }
495             }
496         }
497     }
498
499     check(&mut cx, krate);
500
501     (Features {
502         default_type_params: cx.has_feature("default_type_params"),
503         unboxed_closures: cx.has_feature("unboxed_closures"),
504         rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
505         import_shadowing: cx.has_feature("import_shadowing"),
506         visible_private_types: cx.has_feature("visible_private_types"),
507         quote: cx.has_feature("quote"),
508         opt_out_copy: cx.has_feature("opt_out_copy"),
509         old_orphan_check: cx.has_feature("old_orphan_check"),
510     },
511     unknown_features)
512 }
513
514 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
515 -> (Features, Vec<Span>) {
516     check_crate_inner(cm, span_handler, krate,
517                       |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
518 }
519
520 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
521 -> (Features, Vec<Span>) {
522     check_crate_inner(cm, span_handler, krate,
523                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
524                                                      krate))
525 }