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