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::*;
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 const 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 ("plugin_registrar", "1.0.0", Active),
58 ("log_syntax", "1.0.0", Active),
59 ("trace_macros", "1.0.0", Active),
60 ("concat_idents", "1.0.0", Active),
61 ("intrinsics", "1.0.0", Active),
62 ("lang_items", "1.0.0", Active),
64 ("simd", "1.0.0", Active),
65 ("default_type_params", "1.0.0", Accepted),
66 ("quote", "1.0.0", Active),
67 ("link_llvm_intrinsics", "1.0.0", Active),
68 ("linkage", "1.0.0", Active),
69 ("struct_inherit", "1.0.0", Removed),
71 ("quad_precision_float", "1.0.0", Removed),
73 ("rustc_diagnostic_macros", "1.0.0", Active),
74 ("unboxed_closures", "1.0.0", Active),
75 ("reflect", "1.0.0", Active),
76 ("import_shadowing", "1.0.0", Removed),
77 ("advanced_slice_patterns", "1.0.0", Active),
78 ("tuple_indexing", "1.0.0", Accepted),
79 ("associated_types", "1.0.0", Accepted),
80 ("visible_private_types", "1.0.0", Active),
81 ("slicing_syntax", "1.0.0", Accepted),
82 ("box_syntax", "1.0.0", Active),
83 ("on_unimplemented", "1.0.0", Active),
84 ("simd_ffi", "1.0.0", Active),
85 ("allocator", "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 ("fundamental", "1.0.0", Active),
96 // Deprecate after snapshot
98 ("unsafe_destructor", "1.0.0", Active),
100 // A temporary feature gate used to enable parser extensions needed
101 // to bootstrap fix for #5723.
102 ("issue_5723_bootstrap", "1.0.0", Accepted),
104 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
105 ("opt_out_copy", "1.0.0", Removed),
107 // OIBIT specific features
108 ("optin_builtin_traits", "1.0.0", Active),
110 // macro reexport needs more discussion and stabilization
111 ("macro_reexport", "1.0.0", Active),
113 // These are used to test this portion of the compiler, they don't actually
115 ("test_accepted_feature", "1.0.0", Accepted),
116 ("test_removed_feature", "1.0.0", Removed),
118 // Allows use of #[staged_api]
119 ("staged_api", "1.0.0", Active),
121 // Allows using items which are missing stability attributes
122 ("unmarked_api", "1.0.0", Active),
124 // Allows using #![no_std]
125 ("no_std", "1.0.0", Active),
127 // Allows using `box` in patterns; RFC 469
128 ("box_patterns", "1.0.0", Active),
130 // Allows using the unsafe_no_drop_flag attribute (unlikely to
131 // switch to Accepted; see RFC 320)
132 ("unsafe_no_drop_flag", "1.0.0", Active),
134 // Allows the use of custom attributes; RFC 572
135 ("custom_attribute", "1.0.0", Active),
137 // Allows the use of #[derive(Anything)] as sugar for
138 // #[derive_Anything].
139 ("custom_derive", "1.0.0", Active),
141 // Allows the use of rustc_* attributes; RFC 572
142 ("rustc_attrs", "1.0.0", Active),
144 // Allows the use of `static_assert`
145 ("static_assert", "1.0.0", Active),
147 // Allows the use of #[allow_internal_unstable]. This is an
148 // attribute on macro_rules! and can't use the attribute handling
149 // below (it has to be checked before expansion possibly makes
150 // macros disappear).
151 ("allow_internal_unstable", "1.0.0", Active),
153 // #23121. Array patterns have some hazards yet.
154 ("slice_patterns", "1.0.0", Active),
156 // (changing above list without updating src/doc/reference.md makes @cmr sad)
159 /// Represents an active feature that is currently being implemented or
160 /// currently being considered for addition/removal.
163 /// Represents a feature which has since been removed (it was once Active)
166 /// This language feature has since been Accepted (it was once Active)
170 // Attributes that have a special meaning to rustc or rustdoc
171 pub const KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
179 ("macro_reexport", Normal),
180 ("macro_use", Normal),
181 ("macro_export", Normal),
182 ("plugin_registrar", Normal),
185 ("cfg_attr", Normal),
194 ("automatically_derived", Normal),
195 ("no_mangle", Normal),
198 ("should_panic", Normal),
200 ("no_implicit_prelude", Normal),
201 ("reexport_test_harness_main", Normal),
202 ("link_args", Normal),
203 ("macro_escape", Normal),
205 ("unsafe_destructor", Gated("unsafe_destructor",
206 "`#[unsafe_destructor]` does nothing anymore")),
207 ("staged_api", Gated("staged_api",
208 "staged_api is for use by rustc only")),
209 ("plugin", Gated("plugin",
210 "compiler plugins are experimental \
211 and possibly buggy")),
212 ("no_std", Gated("no_std",
213 "no_std is experimental")),
214 ("lang", Gated("lang_items",
215 "language items are subject to change")),
216 ("linkage", Gated("linkage",
217 "the `linkage` attribute is experimental \
218 and not portable across platforms")),
219 ("thread_local", Gated("thread_local",
220 "`#[thread_local]` is an experimental feature, and does not \
221 currently handle destructors. There is no corresponding \
222 `#[task_local]` mapping to the task model")),
224 ("rustc_on_unimplemented", Gated("on_unimplemented",
225 "the `#[rustc_on_unimplemented]` attribute \
226 is an experimental feature")),
227 ("allocator", Gated("allocator",
228 "the `#[allocator]` attribute is an experimental feature")),
229 ("rustc_variance", Gated("rustc_attrs",
230 "the `#[rustc_variance]` attribute \
231 is an experimental feature")),
232 ("rustc_error", Gated("rustc_attrs",
233 "the `#[rustc_error]` attribute \
234 is an experimental feature")),
235 ("rustc_move_fragments", Gated("rustc_attrs",
236 "the `#[rustc_move_fragments]` attribute \
237 is an experimental feature")),
239 ("allow_internal_unstable", Gated("allow_internal_unstable",
240 EXPLAIN_ALLOW_INTERNAL_UNSTABLE)),
242 ("fundamental", Gated("fundamental",
243 "the `#[fundamental]` attribute \
244 is an experimental feature")),
246 // FIXME: #14408 whitelist docs since rustdoc looks at them
247 ("doc", Whitelisted),
249 // FIXME: #14406 these are processed in trans, which happens after the
251 ("cold", Whitelisted),
252 ("export_name", Whitelisted),
253 ("inline", Whitelisted),
254 ("link", Whitelisted),
255 ("link_name", Whitelisted),
256 ("link_section", Whitelisted),
257 ("no_builtins", Whitelisted),
258 ("no_mangle", Whitelisted),
259 ("no_stack_check", Whitelisted),
260 ("packed", Whitelisted),
261 ("static_assert", Gated("static_assert",
262 "`#[static_assert]` is an experimental feature, and has a poor API")),
263 ("no_debug", Whitelisted),
264 ("omit_gdb_pretty_printer_section", Whitelisted),
265 ("unsafe_no_drop_flag", Gated("unsafe_no_drop_flag",
266 "unsafe_no_drop_flag has unstable semantics \
267 and may be removed in the future")),
270 ("prelude_import", Whitelisted),
272 // FIXME: #14407 these are only looked at on-demand so we can't
273 // guarantee they'll have already been checked
274 ("deprecated", Whitelisted),
275 ("must_use", Whitelisted),
276 ("stable", Whitelisted),
277 ("unstable", Whitelisted),
279 ("rustc_paren_sugar", Gated("unboxed_closures",
280 "unboxed_closures are still evolving")),
281 ("rustc_reflect_like", Gated("reflect",
282 "defining reflective traits is still evolving")),
284 // Crate level attributes
285 ("crate_name", CrateLevel),
286 ("crate_type", CrateLevel),
287 ("crate_id", CrateLevel),
288 ("feature", CrateLevel),
289 ("no_start", CrateLevel),
290 ("no_main", CrateLevel),
291 ("no_builtins", CrateLevel),
292 ("recursion_limit", CrateLevel),
295 #[derive(PartialEq, Copy, Debug)]
296 pub enum AttributeType {
297 /// Normal, builtin attribute that is consumed
298 /// by the compiler before the unused_attribute check
301 /// Builtin attribute that may not be consumed by the compiler
302 /// before the unused_attribute check. These attributes
303 /// will be ignored by the unused_attribute lint
306 /// Is gated by a given feature gate and reason
307 /// These get whitelisted too
308 Gated(&'static str, &'static str),
310 /// Builtin attribute that is only allowed at the crate level
314 /// A set of features to be used by later passes.
315 pub struct Features {
316 pub unboxed_closures: bool,
317 pub rustc_diagnostic_macros: bool,
318 pub visible_private_types: bool,
319 pub allow_quote: bool,
321 pub allow_log_syntax: bool,
322 pub allow_concat_idents: bool,
323 pub allow_trace_macros: bool,
324 pub allow_internal_unstable: bool,
325 pub allow_custom_derive: bool,
327 pub unmarked_api: bool,
328 /// spans of #![feature] attrs for stable language features. for error reporting
329 pub declared_stable_lang_features: Vec<Span>,
330 /// #![feature] attrs for non-language (library) features
331 pub declared_lib_features: Vec<(InternedString, Span)>
335 pub fn new() -> Features {
337 unboxed_closures: false,
338 rustc_diagnostic_macros: false,
339 visible_private_types: false,
342 allow_log_syntax: false,
343 allow_concat_idents: false,
344 allow_trace_macros: false,
345 allow_internal_unstable: false,
346 allow_custom_derive: false,
349 declared_stable_lang_features: Vec::new(),
350 declared_lib_features: Vec::new()
356 features: Vec<&'static str>,
357 span_handler: &'a SpanHandler,
361 impl<'a> Context<'a> {
362 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
363 let has_feature = self.has_feature(feature);
364 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", feature, span, has_feature);
366 emit_feature_err(self.span_handler, feature, span, explain);
369 fn has_feature(&self, feature: &str) -> bool {
370 self.features.iter().any(|&n| n == feature)
373 fn check_attribute(&self, attr: &ast::Attribute) {
374 debug!("check_attribute(attr = {:?})", attr);
375 let name = &*attr.name();
376 for &(n, ty) in KNOWN_ATTRIBUTES {
378 if let Gated(gate, desc) = ty {
379 self.gate_feature(gate, attr.span, desc);
381 debug!("check_attribute: {:?} is known, {:?}", name, ty);
385 if name.starts_with("rustc_") {
386 self.gate_feature("rustc_attrs", attr.span,
387 "unless otherwise specified, attributes \
388 with the prefix `rustc_` \
389 are reserved for internal compiler diagnostics");
390 } else if name.starts_with("derive_") {
391 self.gate_feature("custom_derive", attr.span,
392 "attributes of the form `#[derive_*]` are reserved
395 self.gate_feature("custom_attribute", attr.span,
396 &format!("The attribute `{}` is currently \
397 unknown to the the compiler and \
399 added to it in the future",
405 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
406 diag.span_err(span, explain);
407 diag.fileline_help(span, &format!("add #![feature({})] to the \
408 crate attributes to enable",
412 pub fn emit_feature_warn(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
413 diag.span_warn(span, explain);
414 if diag.handler.can_emit_warnings {
415 diag.fileline_help(span, &format!("add #![feature({})] to the \
416 crate attributes to silence this warning",
421 pub const EXPLAIN_ASM: &'static str =
422 "inline assembly is not stable enough for use and is subject to change";
424 pub const EXPLAIN_LOG_SYNTAX: &'static str =
425 "`log_syntax!` is not stable enough for use and is subject to change";
427 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
428 "`concat_idents` is not stable enough for use and is subject to change";
430 pub const EXPLAIN_TRACE_MACROS: &'static str =
431 "`trace_macros` is not stable enough for use and is subject to change";
432 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
433 "allow_internal_unstable side-steps feature gating and stability checks";
435 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
436 "`#[derive]` for custom traits is not stable enough for use and is subject to change";
438 struct MacroVisitor<'a> {
439 context: &'a Context<'a>
442 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
443 fn visit_mac(&mut self, mac: &ast::Mac) {
444 let ast::MacInvocTT(ref path, _, _) = mac.node;
445 let id = path.segments.last().unwrap().identifier;
447 // Issue 22234: If you add a new case here, make sure to also
448 // add code to catch the macro during or after expansion.
450 // We still keep this MacroVisitor (rather than *solely*
451 // relying on catching cases during or after expansion) to
452 // catch uses of these macros within conditionally-compiled
453 // code, e.g. `#[cfg]`-guarded functions.
455 if id == token::str_to_ident("asm") {
456 self.context.gate_feature("asm", path.span, EXPLAIN_ASM);
459 else if id == token::str_to_ident("log_syntax") {
460 self.context.gate_feature("log_syntax", path.span, EXPLAIN_LOG_SYNTAX);
463 else if id == token::str_to_ident("trace_macros") {
464 self.context.gate_feature("trace_macros", path.span, EXPLAIN_TRACE_MACROS);
467 else if id == token::str_to_ident("concat_idents") {
468 self.context.gate_feature("concat_idents", path.span, EXPLAIN_CONCAT_IDENTS);
472 fn visit_attribute(&mut self, attr: &'v ast::Attribute) {
473 self.context.check_attribute(attr);
477 struct PostExpansionVisitor<'a> {
478 context: &'a Context<'a>
481 impl<'a> PostExpansionVisitor<'a> {
482 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
483 if !self.context.cm.span_allows_unstable(span) {
484 self.context.gate_feature(feature, span, explain)
489 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
490 fn visit_attribute(&mut self, attr: &ast::Attribute) {
491 if !self.context.cm.span_allows_unstable(attr.span) {
492 self.context.check_attribute(attr);
496 fn visit_name(&mut self, sp: Span, name: ast::Name) {
497 if !token::get_name(name).is_ascii() {
498 self.gate_feature("non_ascii_idents", sp,
499 "non-ascii idents are not fully supported.");
503 fn visit_item(&mut self, i: &ast::Item) {
505 ast::ItemExternCrate(_) => {
506 if attr::contains_name(&i.attrs[..], "macro_reexport") {
507 self.gate_feature("macro_reexport", i.span,
508 "macros reexports are experimental \
509 and possibly buggy");
513 ast::ItemForeignMod(ref foreign_module) => {
514 if attr::contains_name(&i.attrs[..], "link_args") {
515 self.gate_feature("link_args", i.span,
516 "the `link_args` attribute is not portable \
517 across platforms, it is recommended to \
518 use `#[link(name = \"foo\")]` instead")
520 if foreign_module.abi == Abi::RustIntrinsic {
521 self.gate_feature("intrinsics",
523 "intrinsics are subject to change")
528 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
529 self.gate_feature("plugin_registrar", i.span,
530 "compiler plugins are experimental and possibly buggy");
532 if attr::contains_name(&i.attrs[..], "start") {
533 self.gate_feature("start", i.span,
534 "a #[start] function is an experimental \
535 feature whose signature may change \
538 if attr::contains_name(&i.attrs[..], "main") {
539 self.gate_feature("main", i.span,
540 "declaration of a nonstandard #[main] \
541 function may change over time, for now \
542 a top-level `fn main()` is required");
546 ast::ItemStruct(..) => {
547 if attr::contains_name(&i.attrs[..], "simd") {
548 self.gate_feature("simd", i.span,
549 "SIMD types are experimental and possibly buggy");
553 ast::ItemDefaultImpl(..) => {
554 self.gate_feature("optin_builtin_traits",
556 "default trait implementations are experimental \
557 and possibly buggy");
560 ast::ItemImpl(_, polarity, _, _, _, _) => {
562 ast::ImplPolarity::Negative => {
563 self.gate_feature("optin_builtin_traits",
565 "negative trait bounds are not yet fully implemented; \
566 use marker types for now");
575 visit::walk_item(self, i);
578 fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
579 let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
581 Some(val) => val.starts_with("llvm."),
585 self.gate_feature("link_llvm_intrinsics", i.span,
586 "linking to LLVM intrinsics is experimental");
589 visit::walk_foreign_item(self, i)
592 fn visit_expr(&mut self, e: &ast::Expr) {
594 ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
595 self.gate_feature("box_syntax",
597 "box expression syntax is experimental; \
598 you can call `Box::new` instead.");
602 visit::walk_expr(self, e);
605 fn visit_pat(&mut self, pattern: &ast::Pat) {
607 ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
608 self.gate_feature("advanced_slice_patterns",
610 "multiple-element slice matches anywhere \
611 but at the end of a slice (e.g. \
612 `[0, ..xs, 0]` are experimental")
615 self.gate_feature("slice_patterns",
617 "slice pattern syntax is experimental");
620 self.gate_feature("box_patterns",
622 "box pattern syntax is experimental");
626 visit::walk_pat(self, pattern)
629 fn visit_fn(&mut self,
630 fn_kind: visit::FnKind<'v>,
631 fn_decl: &'v ast::FnDecl,
632 block: &'v ast::Block,
636 visit::FkItemFn(_, _, _, abi) if abi == Abi::RustIntrinsic => {
637 self.gate_feature("intrinsics",
639 "intrinsics are subject to change")
641 visit::FkItemFn(_, _, _, abi) |
642 visit::FkMethod(_, &ast::MethodSig { abi, .. }) if abi == Abi::RustCall => {
643 self.gate_feature("unboxed_closures",
645 "rust-call ABI is subject to change")
649 visit::walk_fn(self, fn_kind, fn_decl, block, span);
653 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,
657 where F: FnOnce(&mut Context, &ast::Crate)
659 let mut cx = Context {
660 features: Vec::new(),
661 span_handler: span_handler,
665 let mut accepted_features = Vec::new();
666 let mut unknown_features = Vec::new();
668 for attr in &krate.attrs {
669 if !attr.check_name("feature") {
673 match attr.meta_item_list() {
675 span_handler.span_err(attr.span, "malformed feature attribute, \
676 expected #![feature(...)]");
680 let name = match mi.node {
681 ast::MetaWord(ref word) => (*word).clone(),
683 span_handler.span_err(mi.span,
684 "malformed feature, expected just \
689 match KNOWN_FEATURES.iter()
690 .find(|& &(n, _, _)| name == n) {
691 Some(&(name, _, Active)) => {
692 cx.features.push(name);
694 Some(&(_, _, Removed)) => {
695 span_handler.span_err(mi.span, "feature has been removed");
697 Some(&(_, _, Accepted)) => {
698 accepted_features.push(mi.span);
701 unknown_features.push((name, mi.span));
709 check(&mut cx, krate);
711 // FIXME (pnkfelix): Before adding the 99th entry below, change it
712 // to a single-pass (instead of N calls to `.has_feature`).
715 unboxed_closures: cx.has_feature("unboxed_closures"),
716 rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
717 visible_private_types: cx.has_feature("visible_private_types"),
718 allow_quote: cx.has_feature("quote"),
719 allow_asm: cx.has_feature("asm"),
720 allow_log_syntax: cx.has_feature("log_syntax"),
721 allow_concat_idents: cx.has_feature("concat_idents"),
722 allow_trace_macros: cx.has_feature("trace_macros"),
723 allow_internal_unstable: cx.has_feature("allow_internal_unstable"),
724 allow_custom_derive: cx.has_feature("custom_derive"),
725 simd_ffi: cx.has_feature("simd_ffi"),
726 unmarked_api: cx.has_feature("unmarked_api"),
727 declared_stable_lang_features: accepted_features,
728 declared_lib_features: unknown_features
732 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
734 check_crate_inner(cm, span_handler, krate,
735 |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
738 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
741 check_crate_inner(cm, span_handler, krate,
742 |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },