]> git.lizzy.rs Git - rust.git/blob - src/librustc/front/feature_gate.rs
auto merge of #12823 : alexcrichton/rust/issue-12666, r=pcwalton
[rust.git] / src / librustc / front / 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
21 use middle::lint;
22
23 use syntax::ast;
24 use syntax::attr;
25 use syntax::attr::AttrMetaMethods;
26 use syntax::codemap::Span;
27 use syntax::visit;
28 use syntax::visit::Visitor;
29 use syntax::parse::token;
30
31 use driver::session::Session;
32
33 use std::cell::Cell;
34 use std::vec_ng::Vec;
35
36 /// This is a list of all known features since the beginning of time. This list
37 /// can never shrink, it may only be expanded (in order to prevent old programs
38 /// from failing to compile). The status of each feature may change, however.
39 static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
40     ("globs", Active),
41     ("macro_rules", Active),
42     ("struct_variant", Active),
43     ("once_fns", Active),
44     ("asm", Active),
45     ("managed_boxes", Active),
46     ("non_ascii_idents", Active),
47     ("thread_local", Active),
48     ("link_args", Active),
49     ("phase", Active),
50     ("macro_registrar", Active),
51     ("log_syntax", Active),
52     ("trace_macros", Active),
53     ("simd", Active),
54     ("default_type_params", Active),
55     ("quote", Active),
56     ("linkage", Active),
57
58     // These are used to test this portion of the compiler, they don't actually
59     // mean anything
60     ("test_accepted_feature", Accepted),
61     ("test_removed_feature", Removed),
62 ];
63
64 enum Status {
65     /// Represents an active feature that is currently being implemented or
66     /// currently being considered for addition/removal.
67     Active,
68
69     /// Represents a feature which has since been removed (it was once Active)
70     Removed,
71
72     /// This language feature has since been Accepted (it was once Active)
73     Accepted,
74 }
75
76 /// A set of features to be used by later passes.
77 pub struct Features {
78     default_type_params: Cell<bool>
79 }
80
81 impl Features {
82     pub fn new() -> Features {
83         Features {
84             default_type_params: Cell::new(false)
85         }
86     }
87 }
88
89 struct Context {
90     features: Vec<&'static str> ,
91     sess: Session,
92 }
93
94 impl Context {
95     fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
96         if !self.has_feature(feature) {
97             self.sess.span_err(span, explain);
98             self.sess.span_note(span, format!("add \\#[feature({})] to the \
99                                                   crate attributes to enable",
100                                                  feature));
101         }
102     }
103
104     fn gate_box(&self, span: Span) {
105         self.gate_feature("managed_boxes", span,
106                           "The managed box syntax is being replaced by the \
107                            `std::gc::Gc` and `std::rc::Rc` types. Equivalent \
108                            functionality to managed trait objects will be \
109                            implemented but is currently missing.");
110     }
111
112     fn has_feature(&self, feature: &str) -> bool {
113         self.features.iter().any(|n| n.as_slice() == feature)
114     }
115 }
116
117 impl Visitor<()> for Context {
118     fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
119         if !token::get_ident(id).get().is_ascii() {
120             self.gate_feature("non_ascii_idents", sp,
121                               "non-ascii idents are not fully supported.");
122         }
123     }
124
125     fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
126         match i.node {
127             ast::ViewItemUse(ref paths) => {
128                 for path in paths.iter() {
129                     match path.node {
130                         ast::ViewPathGlob(..) => {
131                             self.gate_feature("globs", path.span,
132                                               "glob import statements are \
133                                                experimental and possibly buggy");
134                         }
135                         _ => {}
136                     }
137                 }
138             }
139             ast::ViewItemExternCrate(..) => {
140                 for attr in i.attrs.iter() {
141                     if attr.name().get() == "phase"{
142                         self.gate_feature("phase", attr.span,
143                                           "compile time crate loading is \
144                                            experimental and possibly buggy");
145                     }
146                 }
147             }
148         }
149         visit::walk_view_item(self, i, ())
150     }
151
152     fn visit_item(&mut self, i: &ast::Item, _:()) {
153         for attr in i.attrs.iter() {
154             if attr.name().equiv(&("thread_local")) {
155                 self.gate_feature("thread_local", i.span,
156                                   "`#[thread_local]` is an experimental feature, and does not \
157                                   currently handle destructors. There is no corresponding \
158                                   `#[task_local]` mapping to the task model");
159             }
160         }
161         match i.node {
162             ast::ItemEnum(ref def, _) => {
163                 for variant in def.variants.iter() {
164                     match variant.node.kind {
165                         ast::StructVariantKind(..) => {
166                             self.gate_feature("struct_variant", variant.span,
167                                               "enum struct variants are \
168                                                experimental and possibly buggy");
169                         }
170                         _ => {}
171                     }
172                 }
173             }
174
175             ast::ItemForeignMod(..) => {
176                 if attr::contains_name(i.attrs.as_slice(), "link_args") {
177                     self.gate_feature("link_args", i.span,
178                                       "the `link_args` attribute is not portable \
179                                        across platforms, it is recommended to \
180                                        use `#[link(name = \"foo\")]` instead")
181                 }
182             }
183
184             ast::ItemFn(..) => {
185                 if attr::contains_name(i.attrs.as_slice(), "macro_registrar") {
186                     self.gate_feature("macro_registrar", i.span,
187                                       "cross-crate macro exports are \
188                                        experimental and possibly buggy");
189                 }
190             }
191
192             ast::ItemStruct(..) => {
193                 if attr::contains_name(i.attrs.as_slice(), "simd") {
194                     self.gate_feature("simd", i.span,
195                                       "SIMD types are experimental and possibly buggy");
196                 }
197             }
198
199             _ => {}
200         }
201
202         visit::walk_item(self, i, ());
203     }
204
205     fn visit_mac(&mut self, macro: &ast::Mac, _: ()) {
206         let ast::MacInvocTT(ref path, _, _) = macro.node;
207         let id = path.segments.last().unwrap().identifier;
208         let quotes = ["quote_tokens", "quote_expr", "quote_ty",
209                       "quote_item", "quote_pat", "quote_stmt"];
210         let msg = " is not stable enough for use and are subject to change";
211
212
213         if id == token::str_to_ident("macro_rules") {
214             self.gate_feature("macro_rules", path.span, "macro definitions are \
215                 not stable enough for use and are subject to change");
216         }
217
218         else if id == token::str_to_ident("asm") {
219             self.gate_feature("asm", path.span, "inline assembly is not \
220                 stable enough for use and is subject to change");
221         }
222
223         else if id == token::str_to_ident("log_syntax") {
224             self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
225                 stable enough for use and is subject to change");
226         }
227
228         else if id == token::str_to_ident("trace_macros") {
229             self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
230                 stable enough for use and is subject to change");
231         }
232
233         else {
234             for &quote in quotes.iter() {
235                 if id == token::str_to_ident(quote) {
236                   self.gate_feature("quote", path.span, quote + msg);
237                 }
238             }
239         }
240     }
241
242     fn visit_foreign_item(&mut self, i: &ast::ForeignItem, _: ()) {
243         match i.node {
244             ast::ForeignItemFn(..) | ast::ForeignItemStatic(..) => {
245                 if attr::contains_name(i.attrs.as_slice(), "linkage") {
246                     self.gate_feature("linkage", i.span,
247                                       "the `linkage` attribute is experimental \
248                                        and not portable across platforms")
249                 }
250             }
251         }
252         visit::walk_foreign_item(self, i, ())
253     }
254
255     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
256         match t.node {
257             ast::TyClosure(closure) if closure.onceness == ast::Once &&
258                     closure.sigil != ast::OwnedSigil => {
259                 self.gate_feature("once_fns", t.span,
260                                   "once functions are \
261                                    experimental and likely to be removed");
262
263             },
264             ast::TyBox(_) => { self.gate_box(t.span); }
265             _ => {}
266         }
267
268         visit::walk_ty(self, t, ());
269     }
270
271     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
272         match e.node {
273             ast::ExprUnary(ast::UnBox, _) => {
274                 self.gate_box(e.span);
275             }
276             _ => {}
277         }
278         visit::walk_expr(self, e, ());
279     }
280
281     fn visit_generics(&mut self, generics: &ast::Generics, _: ()) {
282         for type_parameter in generics.ty_params.iter() {
283             match type_parameter.default {
284                 Some(ty) => {
285                     self.gate_feature("default_type_params", ty.span,
286                                       "default type parameters are \
287                                        experimental and possibly buggy");
288                 }
289                 None => {}
290             }
291         }
292         visit::walk_generics(self, generics, ());
293     }
294 }
295
296 pub fn check_crate(sess: Session, krate: &ast::Crate) {
297     let mut cx = Context {
298         features: Vec::new(),
299         sess: sess,
300     };
301
302     for attr in krate.attrs.iter() {
303         if !attr.name().equiv(&("feature")) {
304             continue
305         }
306
307         match attr.meta_item_list() {
308             None => {
309                 sess.span_err(attr.span, "malformed feature attribute, \
310                                           expected #[feature(...)]");
311             }
312             Some(list) => {
313                 for &mi in list.iter() {
314                     let name = match mi.node {
315                         ast::MetaWord(ref word) => (*word).clone(),
316                         _ => {
317                             sess.span_err(mi.span,
318                                           "malformed feature, expected just \
319                                            one word");
320                             continue
321                         }
322                     };
323                     match KNOWN_FEATURES.iter()
324                                         .find(|& &(n, _)| name.equiv(&n)) {
325                         Some(&(name, Active)) => { cx.features.push(name); }
326                         Some(&(_, Removed)) => {
327                             sess.span_err(mi.span, "feature has been removed");
328                         }
329                         Some(&(_, Accepted)) => {
330                             sess.span_warn(mi.span, "feature has added to rust, \
331                                                      directive not necessary");
332                         }
333                         None => {
334                             sess.add_lint(lint::UnknownFeatures,
335                                           ast::CRATE_NODE_ID,
336                                           mi.span,
337                                           ~"unknown feature");
338                         }
339                     }
340                 }
341             }
342         }
343     }
344
345     visit::walk_crate(&mut cx, krate, ());
346
347     sess.abort_if_errors();
348
349     sess.features.default_type_params.set(cx.has_feature("default_type_params"));
350 }