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.
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.
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
18 //! Features are enabled in programs via the crate-level attributes of
19 //! `#![feature(...)]` with a comma-separated list of features.
21 //! For the purpose of future feature-tracking, once code for detection of feature
22 //! gate usage is added, *do not remove it again* even once the feature
26 use self::AttributeType::*;
28 use abi::RustIntrinsic;
32 use attr::AttrMetaMethods;
33 use codemap::{CodeMap, Span};
34 use diagnostic::SpanHandler;
37 use parse::token::{self, InternedString};
39 use std::ascii::AsciiExt;
41 // If you change this list without updating src/doc/reference.md, @cmr will be sad
42 // Don't ever remove anything from this list; set them to 'Removed'.
43 // The version numbers here correspond to the version in which the current status
44 // was set. This is most important for knowing when a particular feature became
46 // NB: The featureck.py script parses this information directly out of the source
47 // so take care when modifying it.
48 static KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
49 ("globs", "1.0.0", Accepted),
50 ("macro_rules", "1.0.0", Accepted),
51 ("struct_variant", "1.0.0", Accepted),
52 ("asm", "1.0.0", Active),
53 ("managed_boxes", "1.0.0", Removed),
54 ("non_ascii_idents", "1.0.0", Active),
55 ("thread_local", "1.0.0", Active),
56 ("link_args", "1.0.0", Active),
57 ("phase", "1.0.0", Removed),
58 ("plugin_registrar", "1.0.0", Active),
59 ("log_syntax", "1.0.0", Active),
60 ("trace_macros", "1.0.0", Active),
61 ("concat_idents", "1.0.0", Active),
62 ("unsafe_destructor", "1.0.0", Active),
63 ("intrinsics", "1.0.0", Active),
64 ("lang_items", "1.0.0", Active),
66 ("simd", "1.0.0", Active),
67 ("default_type_params", "1.0.0", Accepted),
68 ("quote", "1.0.0", Active),
69 ("link_llvm_intrinsics", "1.0.0", Active),
70 ("linkage", "1.0.0", Active),
71 ("struct_inherit", "1.0.0", Removed),
73 ("quad_precision_float", "1.0.0", Removed),
75 ("rustc_diagnostic_macros", "1.0.0", Active),
76 ("unboxed_closures", "1.0.0", Active),
77 ("import_shadowing", "1.0.0", Removed),
78 ("advanced_slice_patterns", "1.0.0", Active),
79 ("tuple_indexing", "1.0.0", Accepted),
80 ("associated_types", "1.0.0", Accepted),
81 ("visible_private_types", "1.0.0", Active),
82 ("slicing_syntax", "1.0.0", Accepted),
83 ("box_syntax", "1.0.0", Active),
84 ("on_unimplemented", "1.0.0", Active),
85 ("simd_ffi", "1.0.0", Active),
87 ("if_let", "1.0.0", Accepted),
88 ("while_let", "1.0.0", Accepted),
90 ("plugin", "1.0.0", Active),
91 ("start", "1.0.0", Active),
92 ("main", "1.0.0", Active),
94 // A temporary feature gate used to enable parser extensions needed
95 // to bootstrap fix for #5723.
96 ("issue_5723_bootstrap", "1.0.0", Accepted),
98 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
99 ("opt_out_copy", "1.0.0", Removed),
101 // A way to temporarily opt out of the new orphan rules. This will *never* be accepted.
102 ("old_orphan_check", "1.0.0", Deprecated),
104 // A way to temporarily opt out of the new impl rules. This will *never* be accepted.
105 ("old_impl_check", "1.0.0", Deprecated),
107 // OIBIT specific features
108 ("optin_builtin_traits", "1.0.0", Active),
110 // int and uint are now deprecated
111 ("int_uint", "1.0.0", Active),
113 // macro reexport needs more discussion and stabilization
114 ("macro_reexport", "1.0.0", Active),
116 // These are used to test this portion of the compiler, they don't actually
118 ("test_accepted_feature", "1.0.0", Accepted),
119 ("test_removed_feature", "1.0.0", Removed),
121 // Allows use of #[staged_api]
122 ("staged_api", "1.0.0", Active),
124 // Allows using items which are missing stability attributes
125 ("unmarked_api", "1.0.0", Active),
127 // Allows using #![no_std]
128 ("no_std", "1.0.0", Active),
130 // Allows using `box` in patterns; RFC 469
131 ("box_patterns", "1.0.0", Active),
133 // Allows using the unsafe_no_drop_flag attribute (unlikely to
134 // switch to Accepted; see RFC 320)
135 ("unsafe_no_drop_flag", "1.0.0", Active),
137 // Allows the use of custom attributes; RFC 572
138 ("custom_attribute", "1.0.0", Active),
140 // Allows the use of rustc_* attributes; RFC 572
141 ("rustc_attrs", "1.0.0", Active),
143 // (changing above list without updating src/doc/reference.md makes @cmr sad)
146 /// Represents an active feature that is currently being implemented or
147 /// currently being considered for addition/removal.
150 /// Represents a feature gate that is temporarily enabling deprecated behavior.
151 /// This gate will never be accepted.
154 /// Represents a feature which has since been removed (it was once Active)
157 /// This language feature has since been Accepted (it was once Active)
161 // Attributes that have a special meaning to rustc or rustdoc
162 pub static KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
170 ("macro_reexport", Normal),
171 ("macro_use", Normal),
172 ("macro_export", Normal),
173 ("plugin_registrar", Normal),
184 ("unsafe_destructor", Normal),
185 ("automatically_derived", Normal),
186 ("no_mangle", Normal),
189 ("should_fail", Normal),
191 ("no_implicit_prelude", Normal),
192 ("reexport_test_harness_main", Normal),
193 ("link_args", Normal),
194 ("macro_escape", Normal),
197 ("staged_api", Gated("staged_api",
198 "staged_api is for use by rustc only")),
199 ("plugin", Gated("plugin",
200 "compiler plugins are experimental \
201 and possibly buggy")),
202 ("no_std", Gated("no_std",
203 "no_std is experimental")),
204 ("lang", Gated("lang_items",
205 "language items are subject to change")),
206 ("linkage", Gated("linkage",
207 "the `linkage` attribute is experimental \
208 and not portable across platforms")),
209 ("thread_local", Gated("thread_local",
210 "`#[thread_local]` is an experimental feature, and does not \
211 currently handle destructors. There is no corresponding \
212 `#[task_local]` mapping to the task model")),
214 ("rustc_on_unimplemented", Gated("on_unimplemented",
215 "the `#[rustc_on_unimplemented]` attribute \
216 is an experimental feature")),
217 ("rustc_variance", Gated("rustc_attrs",
218 "the `#[rustc_variance]` attribute \
219 is an experimental feature")),
220 ("rustc_error", Gated("rustc_attrs",
221 "the `#[rustc_error]` attribute \
222 is an experimental feature")),
223 ("rustc_move_fragments", Gated("rustc_attrs",
224 "the `#[rustc_move_fragments]` attribute \
225 is an experimental feature")),
227 // FIXME: #14408 whitelist docs since rustdoc looks at them
228 ("doc", Whitelisted),
230 // FIXME: #14406 these are processed in trans, which happens after the
232 ("cold", Whitelisted),
233 ("export_name", Whitelisted),
234 ("inline", Whitelisted),
235 ("link", Whitelisted),
236 ("link_name", Whitelisted),
237 ("link_section", Whitelisted),
238 ("no_builtins", Whitelisted),
239 ("no_mangle", Whitelisted),
240 ("no_split_stack", Whitelisted),
241 ("no_stack_check", Whitelisted),
242 ("packed", Whitelisted),
243 ("static_assert", Whitelisted),
244 ("no_debug", Whitelisted),
245 ("omit_gdb_pretty_printer_section", Whitelisted),
246 ("unsafe_no_drop_flag", Whitelisted),
249 ("prelude_import", Whitelisted),
251 // FIXME: #14407 these are only looked at on-demand so we can't
252 // guarantee they'll have already been checked
253 ("deprecated", Whitelisted),
254 ("must_use", Whitelisted),
255 ("stable", Whitelisted),
256 ("unstable", Whitelisted),
258 // FIXME: #19470 this shouldn't be needed forever
259 ("old_orphan_check", Whitelisted),
260 ("old_impl_check", Whitelisted),
261 ("rustc_paren_sugar", Whitelisted), // FIXME: #18101 temporary unboxed closure hack
263 // Crate level attributes
264 ("crate_name", CrateLevel),
265 ("crate_type", CrateLevel),
266 ("crate_id", CrateLevel),
267 ("feature", CrateLevel),
268 ("no_start", CrateLevel),
269 ("no_main", CrateLevel),
270 ("no_builtins", CrateLevel),
271 ("recursion_limit", CrateLevel),
274 #[derive(PartialEq, Copy)]
275 pub enum AttributeType {
276 /// Normal, builtin attribute that is consumed
277 /// by the compiler before the unused_attribute check
280 /// Builtin attribute that may not be consumed by the compiler
281 /// before the unused_attribute check. These attributes
282 /// will be ignored by the unused_attribute lint
285 /// Is gated by a given feature gate and reason
286 /// These get whitelisted too
287 Gated(&'static str, &'static str),
289 /// Builtin attribute that is only allowed at the crate level
293 /// A set of features to be used by later passes.
294 pub struct Features {
295 pub unboxed_closures: bool,
296 pub rustc_diagnostic_macros: bool,
297 pub visible_private_types: bool,
298 pub allow_quote: bool,
300 pub allow_log_syntax: bool,
301 pub allow_concat_idents: bool,
302 pub allow_trace_macros: bool,
303 pub old_orphan_check: bool,
305 pub unmarked_api: bool,
306 /// spans of #![feature] attrs for stable language features. for error reporting
307 pub declared_stable_lang_features: Vec<Span>,
308 /// #![feature] attrs for non-language (library) features
309 pub declared_lib_features: Vec<(InternedString, Span)>
313 pub fn new() -> Features {
315 unboxed_closures: false,
316 rustc_diagnostic_macros: false,
317 visible_private_types: false,
320 allow_log_syntax: false,
321 allow_concat_idents: false,
322 allow_trace_macros: false,
323 old_orphan_check: false,
326 declared_stable_lang_features: Vec::new(),
327 declared_lib_features: Vec::new()
333 features: Vec<&'static str>,
334 span_handler: &'a SpanHandler,
338 impl<'a> Context<'a> {
339 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
340 if !self.has_feature(feature) {
341 emit_feature_err(self.span_handler, feature, span, explain);
345 fn warn_feature(&self, feature: &str, span: Span, explain: &str) {
346 if !self.has_feature(feature) {
347 emit_feature_warn(self.span_handler, feature, span, explain);
350 fn has_feature(&self, feature: &str) -> bool {
351 self.features.iter().any(|&n| n == feature)
355 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
356 diag.span_err(span, explain);
357 diag.span_help(span, &format!("add #![feature({})] to the \
358 crate attributes to enable",
362 pub fn emit_feature_warn(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
363 diag.span_warn(span, explain);
364 if diag.handler.can_emit_warnings {
365 diag.span_help(span, &format!("add #![feature({})] to the \
366 crate attributes to silence this warning",
371 pub const EXPLAIN_ASM: &'static str =
372 "inline assembly is not stable enough for use and is subject to change";
374 pub const EXPLAIN_LOG_SYNTAX: &'static str =
375 "`log_syntax!` is not stable enough for use and is subject to change";
377 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
378 "`concat_idents` is not stable enough for use and is subject to change";
380 pub const EXPLAIN_TRACE_MACROS: &'static str =
381 "`trace_macros` is not stable enough for use and is subject to change";
383 struct MacroVisitor<'a> {
384 context: &'a Context<'a>
387 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
388 fn visit_mac(&mut self, mac: &ast::Mac) {
389 let ast::MacInvocTT(ref path, _, _) = mac.node;
390 let id = path.segments.last().unwrap().identifier;
392 // Issue 22234: If you add a new case here, make sure to also
393 // add code to catch the macro during or after expansion.
395 // We still keep this MacroVisitor (rather than *solely*
396 // relying on catching cases during or after expansion) to
397 // catch uses of these macros within conditionally-compiled
398 // code, e.g. `#[cfg]`-guarded functions.
400 if id == token::str_to_ident("asm") {
401 self.context.gate_feature("asm", path.span, EXPLAIN_ASM);
404 else if id == token::str_to_ident("log_syntax") {
405 self.context.gate_feature("log_syntax", path.span, EXPLAIN_LOG_SYNTAX);
408 else if id == token::str_to_ident("trace_macros") {
409 self.context.gate_feature("trace_macros", path.span, EXPLAIN_TRACE_MACROS);
412 else if id == token::str_to_ident("concat_idents") {
413 self.context.gate_feature("concat_idents", path.span, EXPLAIN_CONCAT_IDENTS);
418 struct PostExpansionVisitor<'a> {
419 context: &'a Context<'a>
422 impl<'a> PostExpansionVisitor<'a> {
423 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
424 if !self.context.cm.span_is_internal(span) {
425 self.context.gate_feature(feature, span, explain)
430 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
431 fn visit_name(&mut self, sp: Span, name: ast::Name) {
432 if !token::get_name(name).is_ascii() {
433 self.gate_feature("non_ascii_idents", sp,
434 "non-ascii idents are not fully supported.");
438 fn visit_item(&mut self, i: &ast::Item) {
440 ast::ItemExternCrate(_) => {
441 if attr::contains_name(&i.attrs[..], "macro_reexport") {
442 self.gate_feature("macro_reexport", i.span,
443 "macros reexports are experimental \
444 and possibly buggy");
448 ast::ItemForeignMod(ref foreign_module) => {
449 if attr::contains_name(&i.attrs[..], "link_args") {
450 self.gate_feature("link_args", i.span,
451 "the `link_args` attribute is not portable \
452 across platforms, it is recommended to \
453 use `#[link(name = \"foo\")]` instead")
455 if foreign_module.abi == RustIntrinsic {
456 self.gate_feature("intrinsics",
458 "intrinsics are subject to change")
463 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
464 self.gate_feature("plugin_registrar", i.span,
465 "compiler plugins are experimental and possibly buggy");
467 if attr::contains_name(&i.attrs[..], "start") {
468 self.gate_feature("start", i.span,
469 "a #[start] function is an experimental \
470 feature whose signature may change \
473 if attr::contains_name(&i.attrs[..], "main") {
474 self.gate_feature("main", i.span,
475 "declaration of a nonstandard #[main] \
476 function may change over time, for now \
477 a top-level `fn main()` is required");
481 ast::ItemStruct(..) => {
482 if attr::contains_name(&i.attrs[..], "simd") {
483 self.gate_feature("simd", i.span,
484 "SIMD types are experimental and possibly buggy");
488 ast::ItemImpl(_, polarity, _, _, _, _) => {
490 ast::ImplPolarity::Negative => {
491 self.gate_feature("optin_builtin_traits",
493 "negative trait bounds are not yet fully implemented; \
494 use marker types for now");
499 if attr::contains_name(&i.attrs,
500 "unsafe_destructor") {
501 self.gate_feature("unsafe_destructor",
503 "`#[unsafe_destructor]` allows too \
504 many unsafe patterns and may be \
505 removed in the future");
508 if attr::contains_name(&i.attrs[..],
509 "old_orphan_check") {
513 "the new orphan check rules will eventually be strictly enforced");
516 if attr::contains_name(&i.attrs[..],
518 self.gate_feature("old_impl_check",
520 "`#[old_impl_check]` will be removed in the future");
527 visit::walk_item(self, i);
530 fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
531 if attr::contains_name(&i.attrs, "linkage") {
532 self.gate_feature("linkage", i.span,
533 "the `linkage` attribute is experimental \
534 and not portable across platforms")
537 let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
539 Some(val) => val.starts_with("llvm."),
543 self.gate_feature("link_llvm_intrinsics", i.span,
544 "linking to LLVM intrinsics is experimental");
547 visit::walk_foreign_item(self, i)
550 fn visit_ty(&mut self, t: &ast::Ty) {
552 ast::TyPath(ref p, _) => {
555 [ast::PathSegment { identifier, .. }] => {
556 let name = token::get_ident(identifier);
557 let msg = if name == "int" {
558 Some("the `int` type is deprecated; \
559 use `isize` or a fixed-sized integer")
560 } else if name == "uint" {
561 Some("the `uint` type is deprecated; \
562 use `usize` or a fixed-sized integer")
567 if let Some(msg) = msg {
568 self.context.warn_feature("int_uint", t.span, msg)
576 visit::walk_ty(self, t);
579 fn visit_expr(&mut self, e: &ast::Expr) {
581 ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
582 self.gate_feature("box_syntax",
584 "box expression syntax is experimental; \
585 you can call `Box::new` instead.");
587 ast::ExprLit(ref lit) => {
589 ast::LitInt(_, ty) => {
590 let msg = if let ast::SignedIntLit(ast::TyIs(true), _) = ty {
591 Some("the `i` and `is` suffixes on integers are deprecated; \
592 use `isize` or one of the fixed-sized suffixes")
593 } else if let ast::UnsignedIntLit(ast::TyUs(true)) = ty {
594 Some("the `u` and `us` suffixes on integers are deprecated; \
595 use `usize` or one of the fixed-sized suffixes")
599 if let Some(msg) = msg {
600 self.context.warn_feature("int_uint", e.span, msg);
608 visit::walk_expr(self, e);
611 fn visit_attribute(&mut self, attr: &ast::Attribute) {
612 let name = &*attr.name();
613 for &(n, ty) in KNOWN_ATTRIBUTES {
615 if let Gated(gate, desc) = ty {
616 self.gate_feature(gate, attr.span, desc);
621 if name.starts_with("rustc_") {
622 self.gate_feature("rustc_attrs", attr.span,
623 "unless otherwise specified, attributes \
624 with the prefix `rustc_` \
625 are reserved for internal compiler diagnostics");
627 self.gate_feature("custom_attribute", attr.span,
628 format!("The attribute `{}` is currently \
629 unknown to the the compiler and \
631 added to it in the future",
636 fn visit_pat(&mut self, pattern: &ast::Pat) {
638 ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
639 self.gate_feature("advanced_slice_patterns",
641 "multiple-element slice matches anywhere \
642 but at the end of a slice (e.g. \
643 `[0, ..xs, 0]` are experimental")
646 self.gate_feature("box_patterns",
648 "box pattern syntax is experimental");
652 visit::walk_pat(self, pattern)
655 fn visit_fn(&mut self,
656 fn_kind: visit::FnKind<'v>,
657 fn_decl: &'v ast::FnDecl,
658 block: &'v ast::Block,
662 visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
663 self.gate_feature("intrinsics",
665 "intrinsics are subject to change")
669 visit::walk_fn(self, fn_kind, fn_decl, block, span);
673 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
676 where F: FnOnce(&mut Context, &ast::Crate)
678 let mut cx = Context {
679 features: Vec::new(),
680 span_handler: span_handler,
684 let mut accepted_features = Vec::new();
685 let mut unknown_features = Vec::new();
687 for attr in &krate.attrs {
688 if !attr.check_name("feature") {
692 match attr.meta_item_list() {
694 span_handler.span_err(attr.span, "malformed feature attribute, \
695 expected #![feature(...)]");
699 let name = match mi.node {
700 ast::MetaWord(ref word) => (*word).clone(),
702 span_handler.span_err(mi.span,
703 "malformed feature, expected just \
708 match KNOWN_FEATURES.iter()
709 .find(|& &(n, _, _)| name == n) {
710 Some(&(name, _, Active)) => {
711 cx.features.push(name);
713 Some(&(name, _, Deprecated)) => {
714 cx.features.push(name);
715 span_handler.span_warn(
717 "feature is deprecated and will only be available \
718 for a limited time, please rewrite code that relies on it");
720 Some(&(_, _, Removed)) => {
721 span_handler.span_err(mi.span, "feature has been removed");
723 Some(&(_, _, Accepted)) => {
724 accepted_features.push(mi.span);
727 unknown_features.push((name, mi.span));
735 check(&mut cx, krate);
737 // FIXME (pnkfelix): Before adding the 99th entry below, change it
738 // to a single-pass (instead of N calls to `.has_feature`).
741 unboxed_closures: cx.has_feature("unboxed_closures"),
742 rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
743 visible_private_types: cx.has_feature("visible_private_types"),
744 allow_quote: cx.has_feature("quote"),
745 allow_asm: cx.has_feature("asm"),
746 allow_log_syntax: cx.has_feature("log_syntax"),
747 allow_concat_idents: cx.has_feature("concat_idents"),
748 allow_trace_macros: cx.has_feature("trace_macros"),
749 old_orphan_check: cx.has_feature("old_orphan_check"),
750 simd_ffi: cx.has_feature("simd_ffi"),
751 unmarked_api: cx.has_feature("unmarked_api"),
752 declared_stable_lang_features: accepted_features,
753 declared_lib_features: unknown_features
757 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
759 check_crate_inner(cm, span_handler, krate,
760 |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
763 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
765 check_crate_inner(cm, span_handler, krate,
766 |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },