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