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