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