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 module 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;
42 // If you change this list without updating src/doc/reference.md, @cmr will be sad
43 // Don't ever remove anything from this list; set them to 'Removed'.
44 // The version numbers here correspond to the version in which the current status
45 // was set. This is most important for knowing when a particular feature became
47 // NB: The featureck.py script parses this information directly out of the source
48 // so take care when modifying it.
49 const KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
50 ("globs", "1.0.0", Accepted),
51 ("macro_rules", "1.0.0", Accepted),
52 ("struct_variant", "1.0.0", Accepted),
53 ("asm", "1.0.0", Active),
54 ("managed_boxes", "1.0.0", Removed),
55 ("non_ascii_idents", "1.0.0", Active),
56 ("thread_local", "1.0.0", Active),
57 ("link_args", "1.0.0", Active),
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 ("intrinsics", "1.0.0", Active),
63 ("lang_items", "1.0.0", Active),
65 ("simd", "1.0.0", Active),
66 ("default_type_params", "1.0.0", Accepted),
67 ("quote", "1.0.0", Active),
68 ("link_llvm_intrinsics", "1.0.0", Active),
69 ("linkage", "1.0.0", Active),
70 ("struct_inherit", "1.0.0", Removed),
72 ("quad_precision_float", "1.0.0", Removed),
74 ("rustc_diagnostic_macros", "1.0.0", Active),
75 ("unboxed_closures", "1.0.0", Active),
76 ("reflect", "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 ("placement_in_syntax", "1.0.0", Active),
85 ("pushpop_unsafe", "1.2.0", Active),
86 ("on_unimplemented", "1.0.0", Active),
87 ("simd_ffi", "1.0.0", Active),
88 ("allocator", "1.0.0", Active),
89 ("needs_allocator", "1.4.0", Active),
90 ("linked_from", "1.3.0", Active),
92 ("if_let", "1.0.0", Accepted),
93 ("while_let", "1.0.0", Accepted),
95 ("plugin", "1.0.0", Active),
96 ("start", "1.0.0", Active),
97 ("main", "1.0.0", Active),
99 ("fundamental", "1.0.0", Active),
101 // A temporary feature gate used to enable parser extensions needed
102 // to bootstrap fix for #5723.
103 ("issue_5723_bootstrap", "1.0.0", Accepted),
105 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
106 ("opt_out_copy", "1.0.0", Removed),
108 // OIBIT specific features
109 ("optin_builtin_traits", "1.0.0", Active),
111 // macro reexport needs more discussion and stabilization
112 ("macro_reexport", "1.0.0", Active),
114 // These are used to test this portion of the compiler, they don't actually
116 ("test_accepted_feature", "1.0.0", Accepted),
117 ("test_removed_feature", "1.0.0", Removed),
119 // Allows use of #[staged_api]
120 ("staged_api", "1.0.0", Active),
122 // Allows using items which are missing stability attributes
123 ("unmarked_api", "1.0.0", Active),
125 // Allows using #![no_std]
126 ("no_std", "1.0.0", Active),
128 // Allows using #![no_core]
129 ("no_core", "1.3.0", Active),
131 // Allows using `box` in patterns; RFC 469
132 ("box_patterns", "1.0.0", Active),
134 // Allows using the unsafe_no_drop_flag attribute (unlikely to
135 // switch to Accepted; see RFC 320)
136 ("unsafe_no_drop_flag", "1.0.0", Active),
138 // Allows the use of custom attributes; RFC 572
139 ("custom_attribute", "1.0.0", Active),
141 // Allows the use of #[derive(Anything)] as sugar for
142 // #[derive_Anything].
143 ("custom_derive", "1.0.0", Active),
145 // Allows the use of rustc_* attributes; RFC 572
146 ("rustc_attrs", "1.0.0", Active),
148 // Allows the use of #[allow_internal_unstable]. This is an
149 // attribute on macro_rules! and can't use the attribute handling
150 // below (it has to be checked before expansion possibly makes
151 // macros disappear).
152 ("allow_internal_unstable", "1.0.0", Active),
154 // #23121. Array patterns have some hazards yet.
155 ("slice_patterns", "1.0.0", Active),
157 // Allows use of unary negate on unsigned integers, e.g. -e for e: u8
158 ("negate_unsigned", "1.0.0", Active),
160 // Allows the definition of associated constants in `trait` or `impl`
162 ("associated_consts", "1.0.0", Active),
164 // Allows the definition of `const fn` functions.
165 ("const_fn", "1.2.0", Active),
167 // Allows using #[prelude_import] on glob `use` items.
168 ("prelude_import", "1.2.0", Active),
170 // Allows the definition recursive static items.
171 ("static_recursion", "1.3.0", Active),
173 // Allows default type parameters to influence type inference.
174 ("default_type_parameter_fallback", "1.3.0", Active),
176 // Allows associated type defaults
177 ("associated_type_defaults", "1.2.0", Active),
178 // Allows macros to appear in the type position.
180 ("type_macros", "1.3.0", Active),
182 // allow `repr(simd)`, and importing the various simd intrinsics
183 ("simd_basics", "1.3.0", Active),
185 // Allows cfg(target_feature = "...").
186 ("cfg_target_feature", "1.3.0", Active),
188 // (changing above list without updating src/doc/reference.md makes @cmr sad)
191 /// Represents an active feature that is currently being implemented or
192 /// currently being considered for addition/removal.
195 /// Represents a feature which has since been removed (it was once Active)
198 /// This language feature has since been Accepted (it was once Active)
202 // Attributes that have a special meaning to rustc or rustdoc
203 pub const KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
211 ("macro_reexport", Normal),
212 ("macro_use", Normal),
213 ("macro_export", Normal),
214 ("plugin_registrar", Normal),
217 ("cfg_attr", Normal),
226 ("automatically_derived", Normal),
227 ("no_mangle", Normal),
230 ("should_panic", Normal),
232 ("no_implicit_prelude", Normal),
233 ("reexport_test_harness_main", Normal),
234 ("link_args", Normal),
235 ("macro_escape", Normal),
237 // Not used any more, but we can't feature gate it
238 ("no_stack_check", Normal),
240 ("staged_api", Gated("staged_api",
241 "staged_api is for use by rustc only")),
242 ("plugin", Gated("plugin",
243 "compiler plugins are experimental \
244 and possibly buggy")),
245 ("no_std", Gated("no_std",
246 "no_std is experimental")),
247 ("no_core", Gated("no_core",
248 "no_core is experimental")),
249 ("lang", Gated("lang_items",
250 "language items are subject to change")),
251 ("linkage", Gated("linkage",
252 "the `linkage` attribute is experimental \
253 and not portable across platforms")),
254 ("thread_local", Gated("thread_local",
255 "`#[thread_local]` is an experimental feature, and does not \
256 currently handle destructors. There is no corresponding \
257 `#[task_local]` mapping to the task model")),
259 ("rustc_on_unimplemented", Gated("on_unimplemented",
260 "the `#[rustc_on_unimplemented]` attribute \
261 is an experimental feature")),
262 ("allocator", Gated("allocator",
263 "the `#[allocator]` attribute is an experimental feature")),
264 ("needs_allocator", Gated("needs_allocator", "the `#[needs_allocator]` \
265 attribute is an experimental \
267 ("rustc_variance", Gated("rustc_attrs",
268 "the `#[rustc_variance]` attribute \
269 is an experimental feature")),
270 ("rustc_error", Gated("rustc_attrs",
271 "the `#[rustc_error]` attribute \
272 is an experimental feature")),
273 ("rustc_move_fragments", Gated("rustc_attrs",
274 "the `#[rustc_move_fragments]` attribute \
275 is an experimental feature")),
277 ("allow_internal_unstable", Gated("allow_internal_unstable",
278 EXPLAIN_ALLOW_INTERNAL_UNSTABLE)),
280 ("fundamental", Gated("fundamental",
281 "the `#[fundamental]` attribute \
282 is an experimental feature")),
284 ("linked_from", Gated("linked_from",
285 "the `#[linked_from]` attribute \
286 is an experimental feature")),
288 // FIXME: #14408 whitelist docs since rustdoc looks at them
289 ("doc", Whitelisted),
291 // FIXME: #14406 these are processed in trans, which happens after the
293 ("cold", Whitelisted),
294 ("export_name", Whitelisted),
295 ("inline", Whitelisted),
296 ("link", Whitelisted),
297 ("link_name", Whitelisted),
298 ("link_section", Whitelisted),
299 ("no_builtins", Whitelisted),
300 ("no_mangle", Whitelisted),
301 ("no_debug", Whitelisted),
302 ("omit_gdb_pretty_printer_section", Whitelisted),
303 ("unsafe_no_drop_flag", Gated("unsafe_no_drop_flag",
304 "unsafe_no_drop_flag has unstable semantics \
305 and may be removed in the future")),
308 ("prelude_import", Gated("prelude_import",
309 "`#[prelude_import]` is for use by rustc only")),
311 // FIXME: #14407 these are only looked at on-demand so we can't
312 // guarantee they'll have already been checked
313 ("deprecated", Whitelisted),
314 ("must_use", Whitelisted),
315 ("stable", Whitelisted),
316 ("unstable", Whitelisted),
318 ("rustc_paren_sugar", Gated("unboxed_closures",
319 "unboxed_closures are still evolving")),
320 ("rustc_reflect_like", Gated("reflect",
321 "defining reflective traits is still evolving")),
323 // Crate level attributes
324 ("crate_name", CrateLevel),
325 ("crate_type", CrateLevel),
326 ("crate_id", CrateLevel),
327 ("feature", CrateLevel),
328 ("no_start", CrateLevel),
329 ("no_main", CrateLevel),
330 ("no_builtins", CrateLevel),
331 ("recursion_limit", CrateLevel),
334 macro_rules! cfg_fn {
335 (|$x: ident| $e: expr) => {{
336 fn f($x: &Features) -> bool {
339 f as fn(&Features) -> bool
342 // cfg(...)'s that are feature gated
343 const GATED_CFGS: &'static [(&'static str, &'static str, fn(&Features) -> bool)] = &[
344 // (name in cfg, feature, function to check if the feature is enabled)
345 ("target_feature", "cfg_target_feature", cfg_fn!(|x| x.cfg_target_feature)),
348 #[derive(Debug, Eq, PartialEq)]
349 pub struct GatedCfg {
353 impl Ord for GatedCfg {
354 fn cmp(&self, other: &GatedCfg) -> cmp::Ordering {
355 (self.span.lo.0, self.span.hi.0, self.index)
356 .cmp(&(other.span.lo.0, other.span.hi.0, other.index))
359 impl PartialOrd for GatedCfg {
360 fn partial_cmp(&self, other: &GatedCfg) -> Option<cmp::Ordering> {
361 Some(self.cmp(other))
366 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
367 let name = cfg.name();
369 .position(|info| info.0 == name)
377 pub fn check_and_emit(&self, diagnostic: &SpanHandler, features: &Features) {
378 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
379 if !has_feature(features) {
380 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
381 emit_feature_err(diagnostic, feature, self.span, &explain);
387 #[derive(PartialEq, Copy, Clone, Debug)]
388 pub enum AttributeType {
389 /// Normal, builtin attribute that is consumed
390 /// by the compiler before the unused_attribute check
393 /// Builtin attribute that may not be consumed by the compiler
394 /// before the unused_attribute check. These attributes
395 /// will be ignored by the unused_attribute lint
398 /// Is gated by a given feature gate and reason
399 /// These get whitelisted too
400 Gated(&'static str, &'static str),
402 /// Builtin attribute that is only allowed at the crate level
406 /// A set of features to be used by later passes.
407 pub struct Features {
408 pub unboxed_closures: bool,
409 pub rustc_diagnostic_macros: bool,
410 pub visible_private_types: bool,
411 pub allow_quote: bool,
413 pub allow_log_syntax: bool,
414 pub allow_concat_idents: bool,
415 pub allow_trace_macros: bool,
416 pub allow_internal_unstable: bool,
417 pub allow_custom_derive: bool,
418 pub allow_placement_in: bool,
420 pub allow_pushpop_unsafe: bool,
422 pub simd_basics: bool,
423 pub unmarked_api: bool,
424 pub negate_unsigned: bool,
425 /// spans of #![feature] attrs for stable language features. for error reporting
426 pub declared_stable_lang_features: Vec<Span>,
427 /// #![feature] attrs for non-language (library) features
428 pub declared_lib_features: Vec<(InternedString, Span)>,
430 pub static_recursion: bool,
431 pub default_type_parameter_fallback: bool,
432 pub type_macros: bool,
433 pub cfg_target_feature: bool,
437 pub fn new() -> Features {
439 unboxed_closures: false,
440 rustc_diagnostic_macros: false,
441 visible_private_types: false,
444 allow_log_syntax: false,
445 allow_concat_idents: false,
446 allow_trace_macros: false,
447 allow_internal_unstable: false,
448 allow_custom_derive: false,
449 allow_placement_in: false,
451 allow_pushpop_unsafe: false,
455 negate_unsigned: false,
456 declared_stable_lang_features: Vec::new(),
457 declared_lib_features: Vec::new(),
459 static_recursion: false,
460 default_type_parameter_fallback: false,
462 cfg_target_feature: false,
467 const EXPLAIN_BOX_SYNTAX: &'static str =
468 "box expression syntax is experimental; you can call `Box::new` instead.";
470 const EXPLAIN_PLACEMENT_IN: &'static str =
471 "placement-in expression syntax is experimental and subject to change.";
473 const EXPLAIN_PUSHPOP_UNSAFE: &'static str =
474 "push/pop_unsafe macros are experimental and subject to change.";
476 pub fn check_for_box_syntax(f: Option<&Features>, diag: &SpanHandler, span: Span) {
477 if let Some(&Features { allow_box: true, .. }) = f {
480 emit_feature_err(diag, "box_syntax", span, EXPLAIN_BOX_SYNTAX);
483 pub fn check_for_placement_in(f: Option<&Features>, diag: &SpanHandler, span: Span) {
484 if let Some(&Features { allow_placement_in: true, .. }) = f {
487 emit_feature_err(diag, "placement_in_syntax", span, EXPLAIN_PLACEMENT_IN);
490 pub fn check_for_pushpop_syntax(f: Option<&Features>, diag: &SpanHandler, span: Span) {
491 if let Some(&Features { allow_pushpop_unsafe: true, .. }) = f {
494 emit_feature_err(diag, "pushpop_unsafe", span, EXPLAIN_PUSHPOP_UNSAFE);
498 features: Vec<&'static str>,
499 span_handler: &'a SpanHandler,
501 plugin_attributes: &'a [(String, AttributeType)],
504 impl<'a> Context<'a> {
505 fn enable_feature(&mut self, feature: &'static str) {
506 debug!("enabling feature: {}", feature);
507 self.features.push(feature);
510 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
511 let has_feature = self.has_feature(feature);
512 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", feature, span, has_feature);
514 emit_feature_err(self.span_handler, feature, span, explain);
517 fn has_feature(&self, feature: &str) -> bool {
518 self.features.iter().any(|&n| n == feature)
521 fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
522 debug!("check_attribute(attr = {:?})", attr);
523 let name = &*attr.name();
524 for &(n, ty) in KNOWN_ATTRIBUTES {
526 if let Gated(gate, desc) = ty {
527 self.gate_feature(gate, attr.span, desc);
529 debug!("check_attribute: {:?} is known, {:?}", name, ty);
533 for &(ref n, ref ty) in self.plugin_attributes {
535 // Plugins can't gate attributes, so we don't check for it
536 // unlike the code above; we only use this loop to
537 // short-circuit to avoid the checks below
538 debug!("check_attribute: {:?} is registered by a plugin, {:?}", name, ty);
542 if name.starts_with("rustc_") {
543 self.gate_feature("rustc_attrs", attr.span,
544 "unless otherwise specified, attributes \
545 with the prefix `rustc_` \
546 are reserved for internal compiler diagnostics");
547 } else if name.starts_with("derive_") {
548 self.gate_feature("custom_derive", attr.span,
549 "attributes of the form `#[derive_*]` are reserved \
552 // Only run the custom attribute lint during regular
553 // feature gate checking. Macro gating runs
554 // before the plugin attributes are registered
555 // so we skip this then
557 self.gate_feature("custom_attribute", attr.span,
558 &format!("The attribute `{}` is currently \
559 unknown to the compiler and \
561 added to it in the future",
568 pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) {
569 diag.span_err(span, explain);
571 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
572 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
573 diag.fileline_help(span, &format!("add #![feature({})] to the \
574 crate attributes to enable",
578 pub const EXPLAIN_ASM: &'static str =
579 "inline assembly is not stable enough for use and is subject to change";
581 pub const EXPLAIN_LOG_SYNTAX: &'static str =
582 "`log_syntax!` is not stable enough for use and is subject to change";
584 pub const EXPLAIN_CONCAT_IDENTS: &'static str =
585 "`concat_idents` is not stable enough for use and is subject to change";
587 pub const EXPLAIN_TRACE_MACROS: &'static str =
588 "`trace_macros` is not stable enough for use and is subject to change";
589 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str =
590 "allow_internal_unstable side-steps feature gating and stability checks";
592 pub const EXPLAIN_CUSTOM_DERIVE: &'static str =
593 "`#[derive]` for custom traits is not stable enough for use and is subject to change";
595 struct MacroVisitor<'a> {
596 context: &'a Context<'a>
599 impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
600 fn visit_mac(&mut self, mac: &ast::Mac) {
601 let ast::MacInvocTT(ref path, _, _) = mac.node;
602 let id = path.segments.last().unwrap().identifier;
604 // Issue 22234: If you add a new case here, make sure to also
605 // add code to catch the macro during or after expansion.
607 // We still keep this MacroVisitor (rather than *solely*
608 // relying on catching cases during or after expansion) to
609 // catch uses of these macros within conditionally-compiled
610 // code, e.g. `#[cfg]`-guarded functions.
612 if id == token::str_to_ident("asm") {
613 self.context.gate_feature("asm", path.span, EXPLAIN_ASM);
616 else if id == token::str_to_ident("log_syntax") {
617 self.context.gate_feature("log_syntax", path.span, EXPLAIN_LOG_SYNTAX);
620 else if id == token::str_to_ident("trace_macros") {
621 self.context.gate_feature("trace_macros", path.span, EXPLAIN_TRACE_MACROS);
624 else if id == token::str_to_ident("concat_idents") {
625 self.context.gate_feature("concat_idents", path.span, EXPLAIN_CONCAT_IDENTS);
629 fn visit_attribute(&mut self, attr: &'v ast::Attribute) {
630 self.context.check_attribute(attr, true);
633 fn visit_expr(&mut self, e: &ast::Expr) {
634 // Issue 22181: overloaded-`box` and placement-`in` are
635 // implemented via a desugaring expansion, so their feature
636 // gates go into MacroVisitor since that works pre-expansion.
638 // Issue 22234: we also check during expansion as well.
639 // But we keep these checks as a pre-expansion check to catch
640 // uses in e.g. conditionalized code.
642 if let ast::ExprBox(None, _) = e.node {
643 self.context.gate_feature("box_syntax", e.span, EXPLAIN_BOX_SYNTAX);
646 if let ast::ExprBox(Some(_), _) = e.node {
647 self.context.gate_feature("placement_in_syntax", e.span, EXPLAIN_PLACEMENT_IN);
650 visit::walk_expr(self, e);
654 struct PostExpansionVisitor<'a> {
655 context: &'a Context<'a>
658 impl<'a> PostExpansionVisitor<'a> {
659 fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
660 if !self.context.cm.span_allows_unstable(span) {
661 self.context.gate_feature(feature, span, explain)
666 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
667 fn visit_attribute(&mut self, attr: &ast::Attribute) {
668 if !self.context.cm.span_allows_unstable(attr.span) {
669 self.context.check_attribute(attr, false);
673 fn visit_name(&mut self, sp: Span, name: ast::Name) {
674 if !name.as_str().is_ascii() {
675 self.gate_feature("non_ascii_idents", sp,
676 "non-ascii idents are not fully supported.");
680 fn visit_item(&mut self, i: &ast::Item) {
682 ast::ItemExternCrate(_) => {
683 if attr::contains_name(&i.attrs[..], "macro_reexport") {
684 self.gate_feature("macro_reexport", i.span,
685 "macros reexports are experimental \
686 and possibly buggy");
690 ast::ItemForeignMod(ref foreign_module) => {
691 if attr::contains_name(&i.attrs[..], "link_args") {
692 self.gate_feature("link_args", i.span,
693 "the `link_args` attribute is not portable \
694 across platforms, it is recommended to \
695 use `#[link(name = \"foo\")]` instead")
697 if foreign_module.abi == Abi::RustIntrinsic {
698 self.gate_feature("intrinsics",
700 "intrinsics are subject to change")
705 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
706 self.gate_feature("plugin_registrar", i.span,
707 "compiler plugins are experimental and possibly buggy");
709 if attr::contains_name(&i.attrs[..], "start") {
710 self.gate_feature("start", i.span,
711 "a #[start] function is an experimental \
712 feature whose signature may change \
715 if attr::contains_name(&i.attrs[..], "main") {
716 self.gate_feature("main", i.span,
717 "declaration of a nonstandard #[main] \
718 function may change over time, for now \
719 a top-level `fn main()` is required");
723 ast::ItemStruct(..) => {
724 if attr::contains_name(&i.attrs[..], "simd") {
725 self.gate_feature("simd", i.span,
726 "SIMD types are experimental and possibly buggy");
727 self.context.span_handler.span_warn(i.span,
728 "the `#[simd]` attribute is deprecated, \
729 use `#[repr(simd)]` instead");
731 for attr in &i.attrs {
732 if attr.name() == "repr" {
733 for item in attr.meta_item_list().unwrap_or(&[]) {
734 if item.name() == "simd" {
735 self.gate_feature("simd_basics", i.span,
736 "SIMD types are experimental and possibly buggy");
744 ast::ItemDefaultImpl(..) => {
745 self.gate_feature("optin_builtin_traits",
747 "default trait implementations are experimental \
748 and possibly buggy");
751 ast::ItemImpl(_, polarity, _, _, _, _) => {
753 ast::ImplPolarity::Negative => {
754 self.gate_feature("optin_builtin_traits",
756 "negative trait bounds are not yet fully implemented; \
757 use marker types for now");
766 visit::walk_item(self, i);
769 fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
770 let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
772 Some(val) => val.starts_with("llvm."),
776 self.gate_feature("link_llvm_intrinsics", i.span,
777 "linking to LLVM intrinsics is experimental");
780 visit::walk_foreign_item(self, i)
783 fn visit_expr(&mut self, e: &ast::Expr) {
785 ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => {
786 self.gate_feature("box_syntax",
788 "box expression syntax is experimental; \
789 you can call `Box::new` instead.");
793 visit::walk_expr(self, e);
796 fn visit_pat(&mut self, pattern: &ast::Pat) {
798 ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
799 self.gate_feature("advanced_slice_patterns",
801 "multiple-element slice matches anywhere \
802 but at the end of a slice (e.g. \
803 `[0, ..xs, 0]`) are experimental")
806 self.gate_feature("slice_patterns",
808 "slice pattern syntax is experimental");
811 self.gate_feature("box_patterns",
813 "box pattern syntax is experimental");
817 visit::walk_pat(self, pattern)
820 fn visit_fn(&mut self,
821 fn_kind: visit::FnKind<'v>,
822 fn_decl: &'v ast::FnDecl,
823 block: &'v ast::Block,
826 // check for const fn declarations
828 visit::FkItemFn(_, _, _, ast::Constness::Const, _, _) => {
829 self.gate_feature("const_fn", span, "const fn is unstable");
832 // stability of const fn methods are covered in
833 // visit_trait_item and visit_impl_item below; this is
834 // because default methods don't pass through this
840 visit::FkItemFn(_, _, _, _, abi, _) if abi == Abi::RustIntrinsic => {
841 self.gate_feature("intrinsics",
843 "intrinsics are subject to change")
845 visit::FkItemFn(_, _, _, _, abi, _) |
846 visit::FkMethod(_, &ast::MethodSig { abi, .. }, _) if abi == Abi::RustCall => {
847 self.gate_feature("unboxed_closures",
849 "rust-call ABI is subject to change")
853 visit::walk_fn(self, fn_kind, fn_decl, block, span);
856 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
858 ast::ConstTraitItem(..) => {
859 self.gate_feature("associated_consts",
861 "associated constants are experimental")
863 ast::MethodTraitItem(ref sig, _) => {
864 if sig.constness == ast::Constness::Const {
865 self.gate_feature("const_fn", ti.span, "const fn is unstable");
868 ast::TypeTraitItem(_, Some(_)) => {
869 self.gate_feature("associated_type_defaults", ti.span,
870 "associated type defaults are unstable");
874 visit::walk_trait_item(self, ti);
877 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
879 ast::ConstImplItem(..) => {
880 self.gate_feature("associated_consts",
882 "associated constants are experimental")
884 ast::MethodImplItem(ref sig, _) => {
885 if sig.constness == ast::Constness::Const {
886 self.gate_feature("const_fn", ii.span, "const fn is unstable");
891 visit::walk_impl_item(self, ii);
895 fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,
897 plugin_attributes: &[(String, AttributeType)],
900 where F: FnOnce(&mut Context, &ast::Crate)
902 let mut cx = Context {
903 features: Vec::new(),
904 span_handler: span_handler,
906 plugin_attributes: plugin_attributes,
909 let mut accepted_features = Vec::new();
910 let mut unknown_features = Vec::new();
912 for attr in &krate.attrs {
913 if !attr.check_name("feature") {
917 match attr.meta_item_list() {
919 span_handler.span_err(attr.span, "malformed feature attribute, \
920 expected #![feature(...)]");
924 let name = match mi.node {
925 ast::MetaWord(ref word) => (*word).clone(),
927 span_handler.span_err(mi.span,
928 "malformed feature, expected just \
933 match KNOWN_FEATURES.iter()
934 .find(|& &(n, _, _)| name == n) {
935 Some(&(name, _, Active)) => {
936 cx.enable_feature(name);
938 Some(&(_, _, Removed)) => {
939 span_handler.span_err(mi.span, "feature has been removed");
941 Some(&(_, _, Accepted)) => {
942 accepted_features.push(mi.span);
945 unknown_features.push((name, mi.span));
953 check(&mut cx, krate);
955 // FIXME (pnkfelix): Before adding the 99th entry below, change it
956 // to a single-pass (instead of N calls to `.has_feature`).
959 unboxed_closures: cx.has_feature("unboxed_closures"),
960 rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
961 visible_private_types: cx.has_feature("visible_private_types"),
962 allow_quote: cx.has_feature("quote"),
963 allow_asm: cx.has_feature("asm"),
964 allow_log_syntax: cx.has_feature("log_syntax"),
965 allow_concat_idents: cx.has_feature("concat_idents"),
966 allow_trace_macros: cx.has_feature("trace_macros"),
967 allow_internal_unstable: cx.has_feature("allow_internal_unstable"),
968 allow_custom_derive: cx.has_feature("custom_derive"),
969 allow_placement_in: cx.has_feature("placement_in_syntax"),
970 allow_box: cx.has_feature("box_syntax"),
971 allow_pushpop_unsafe: cx.has_feature("pushpop_unsafe"),
972 simd_ffi: cx.has_feature("simd_ffi"),
973 simd_basics: cx.has_feature("simd_basics"),
974 unmarked_api: cx.has_feature("unmarked_api"),
975 negate_unsigned: cx.has_feature("negate_unsigned"),
976 declared_stable_lang_features: accepted_features,
977 declared_lib_features: unknown_features,
978 const_fn: cx.has_feature("const_fn"),
979 static_recursion: cx.has_feature("static_recursion"),
980 default_type_parameter_fallback: cx.has_feature("default_type_parameter_fallback"),
981 type_macros: cx.has_feature("type_macros"),
982 cfg_target_feature: cx.has_feature("cfg_target_feature"),
986 pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
988 check_crate_inner(cm, span_handler, krate, &[] as &'static [_],
989 |ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
992 pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
993 plugin_attributes: &[(String, AttributeType)],
994 unstable: UnstableFeatures) -> Features
996 maybe_stage_features(span_handler, krate, unstable);
998 check_crate_inner(cm, span_handler, krate, plugin_attributes,
999 |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
1003 #[derive(Clone, Copy)]
1004 pub enum UnstableFeatures {
1005 /// Hard errors for unstable features are active, as on
1006 /// beta/stable channels.
1008 /// Allow features to me activated, as on nightly.
1010 /// Errors are bypassed for bootstrapping. This is required any time
1011 /// during the build that feature-related lints are set to warn or above
1012 /// because the build turns on warnings-as-errors and uses lots of unstable
1013 /// features. As a result, this this is always required for building Rust
1018 fn maybe_stage_features(span_handler: &SpanHandler, krate: &ast::Crate,
1019 unstable: UnstableFeatures) {
1020 let allow_features = match unstable {
1021 UnstableFeatures::Allow => true,
1022 UnstableFeatures::Disallow => false,
1023 UnstableFeatures::Cheat => true
1025 if !allow_features {
1026 for attr in &krate.attrs {
1027 if attr.check_name("feature") {
1028 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
1029 let ref msg = format!("#[feature] may not be used on the {} release channel",
1031 span_handler.span_err(attr.span, msg);