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