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