rust/src/libsyntax/feature_gate.rs

2196 lines
92 KiB
Rust
Raw Normal View History

//! # Feature gating
//!
2015-04-16 02:18:29 -05:00
//! This module implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
//! AST to ensure that there are no features which are used that are not
//! enabled.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
//!
//! For the purpose of future feature-tracking, once code for detection of feature
//! gate usage is added, *do not remove it again* even once the feature
//! becomes stable.
2015-02-03 16:31:06 -06:00
mod accepted;
use accepted::ACCEPTED_FEATURES;
mod removed;
use removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
2019-02-06 11:33:01 -06:00
use AttributeType::*;
use AttributeGate::*;
2019-03-21 13:40:00 -05:00
use crate::ast::{
self, AssocTyConstraint, AssocTyConstraintKind, NodeId, GenericParam, GenericParamKind,
PatKind, RangeEnd,
};
use crate::attr::{self, check_builtin_attribute, AttributeTemplate};
2019-02-06 11:33:01 -06:00
use crate::source_map::Spanned;
use crate::edition::{ALL_EDITIONS, Edition};
use crate::visit::{self, FnKind, Visitor};
use crate::parse::{token, ParseSess};
2019-05-09 16:08:55 -05:00
use crate::parse::parser::Parser;
2019-05-30 05:30:03 -05:00
use crate::symbol::{Symbol, sym};
use crate::tokenstream::TokenTree;
use errors::{Applicability, DiagnosticBuilder, Handler};
use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::abi::Abi;
2019-05-09 16:08:55 -05:00
use syntax_pos::{Span, DUMMY_SP, MultiSpan};
2019-02-06 11:33:01 -06:00
use log::debug;
use lazy_static::lazy_static;
2019-01-13 07:18:00 -06:00
use std::env;
macro_rules! set {
($field: ident) => {{
fn f(features: &mut Features, _: Span) {
features.$field = true;
}
f as fn(&mut Features, Span)
}}
}
macro_rules! declare_features {
2018-03-14 22:30:06 -05:00
($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
/// Represents active features that are currently being implemented or
/// currently being considered for addition/removal.
const ACTIVE_FEATURES:
&[(Symbol, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
&[$((sym::$feature, $ver, $issue, $edition, set!($feature))),+];
/// A set of features to be used by later passes.
2018-02-14 09:11:02 -06:00
#[derive(Clone)]
pub struct Features {
2018-07-22 20:03:01 -05:00
/// `#![feature]` attrs for language features, for error reporting
pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
2017-12-31 10:17:01 -06:00
/// `#![feature]` attrs for non-language (library) features
pub declared_lib_features: Vec<(Symbol, Span)>,
$(pub $feature: bool),+
}
impl Features {
pub fn new() -> Features {
Features {
2018-07-22 20:03:01 -05:00
declared_lang_features: Vec::new(),
declared_lib_features: Vec::new(),
$($feature: false),+
}
}
2018-02-14 09:11:02 -06:00
pub fn walk_feature_fields<F>(&self, mut f: F)
where F: FnMut(&str, bool)
{
$(f(stringify!($feature), self.$feature);)+
}
}
};
}
// If you change this, please modify `src/doc/unstable-book` as well.
//
// Don't ever remove anything from this list; set them to 'Removed'.
//
// The version numbers here correspond to the version in which the current status
// was set. This is most important for knowing when a particular feature became
// stable (active).
//
// Note that the features are grouped into internal/user-facing and then
// sorted by version inside those groups. This is inforced with tidy.
//
// N.B., `tools/tidy/src/features.rs` parses this information directly out of the
// source, so take care when modifying it.
declare_features! (
// -------------------------------------------------------------------------
2019-05-01 14:42:57 -05:00
// feature-group-start: internal feature gates
// -------------------------------------------------------------------------
// no-tracking-issue-start
// Allows using compiler's own crates.
(active, rustc_private, "1.0.0", Some(27812), None),
// Allows using the `rust-intrinsic`'s "ABI".
(active, intrinsics, "1.0.0", None, None),
// Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
(active, lang_items, "1.0.0", None, None),
// Allows using the `#[stable]` and `#[unstable]` attributes.
(active, staged_api, "1.0.0", None, None),
// Allows using `#[allow_internal_unstable]`. This is an
// attribute on `macro_rules!` and can't use the attribute handling
// below (it has to be checked before expansion possibly makes
// macros disappear).
(active, allow_internal_unstable, "1.0.0", None, None),
// Allows using `#[allow_internal_unsafe]`. This is an
// attribute on `macro_rules!` and can't use the attribute handling
// below (it has to be checked before expansion possibly makes
// macros disappear).
(active, allow_internal_unsafe, "1.0.0", None, None),
// Allows using the macros:
// + `__diagnostic_used`
// + `__register_diagnostic`
// +`__build_diagnostic_array`
(active, rustc_diagnostic_macros, "1.0.0", None, None),
// Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
// lets a function to be `const` when opted into with `#![feature(foo)]`.
(active, rustc_const_unstable, "1.0.0", None, None),
// no-tracking-issue-end
// Allows using `#[link_name="llvm.*"]`.
(active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
// Allows using `rustc_*` attributes (RFC 572).
(active, rustc_attrs, "1.0.0", Some(29642), None),
// Allows using `#[on_unimplemented(..)]` on traits.
(active, on_unimplemented, "1.0.0", Some(29628), None),
// Allows using the `box $expr` syntax.
(active, box_syntax, "1.0.0", Some(49733), None),
// Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
(active, main, "1.0.0", Some(29634), None),
// Allows using `#[start]` on a function indicating that it is the program entrypoint.
(active, start, "1.0.0", Some(29633), None),
Fix orphan checking (cc #19470). (This is not a complete fix of #19470 because of the backwards compatibility feature gate.) This is a [breaking-change]. The new rules require that, for an impl of a trait defined in some other crate, two conditions must hold: 1. Some type must be local. 2. Every type parameter must appear "under" some local type. Here are some examples that are legal: ```rust struct MyStruct<T> { ... } // Here `T` appears "under' `MyStruct`. impl<T> Clone for MyStruct<T> { } // Here `T` appears "under' `MyStruct` as well. Note that it also appears // elsewhere. impl<T> Iterator<T> for MyStruct<T> { } ``` Here is an illegal example: ```rust // Here `U` does not appear "under" `MyStruct` or any other local type. // We call `U` "uncovered". impl<T,U> Iterator<U> for MyStruct<T> { } ``` There are a couple of ways to rewrite this last example so that it is legal: 1. In some cases, the uncovered type parameter (here, `U`) should be converted into an associated type. This is however a non-local change that requires access to the original trait. Also, associated types are not fully baked. 2. Add `U` as a type parameter of `MyStruct`: ```rust struct MyStruct<T,U> { ... } impl<T,U> Iterator<U> for MyStruct<T,U> { } ``` 3. Create a newtype wrapper for `U` ```rust impl<T,U> Iterator<Wrapper<U>> for MyStruct<T,U> { } ``` Because associated types are not fully baked, which in the case of the `Hash` trait makes adhering to this rule impossible, you can temporarily disable this rule in your crate by using `#![feature(old_orphan_check)]`. Note that the `old_orphan_check` feature will be removed before 1.0 is released.
2014-12-26 02:30:51 -06:00
// Allows using the `#[fundamental]` attribute.
(active, fundamental, "1.0.0", Some(29635), None),
// Allows using the `rust-call` ABI.
(active, unboxed_closures, "1.0.0", Some(29625), None),
// Allows using the `#[linkage = ".."]` attribute.
(active, linkage, "1.0.0", Some(29603), None),
// Allows features specific to OIBIT (auto traits).
(active, optin_builtin_traits, "1.0.0", Some(13231), None),
// Allows using `box` in patterns (RFC 469).
(active, box_patterns, "1.0.0", Some(29641), None),
// no-tracking-issue-start
// Allows using `#[prelude_import]` on glob `use` items.
(active, prelude_import, "1.2.0", None, None),
// no-tracking-issue-end
// no-tracking-issue-start
// Allows using `#[omit_gdb_pretty_printer_section]`.
(active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
// Allows using the `vectorcall` ABI.
(active, abi_vectorcall, "1.7.0", None, None),
// no-tracking-issue-end
// Allows using `#[structural_match]` which indicates that a type is structurally matchable.
(active, structural_match, "1.8.0", Some(31434), None),
2015-02-16 14:16:36 -06:00
2019-05-01 14:42:57 -05:00
// Allows using the `may_dangle` attribute (RFC 1327).
(active, dropck_eyepatch, "1.10.0", Some(34761), None),
// Allows using the `#![panic_runtime]` attribute.
(active, panic_runtime, "1.10.0", Some(32837), None),
// Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed.
(active, needs_panic_runtime, "1.10.0", Some(32837), None),
// no-tracking-issue-start
// Allows identifying the `compiler_builtins` crate.
(active, compiler_builtins, "1.13.0", None, None),
// Allows using the `unadjusted` ABI; perma-unstable.
(active, abi_unadjusted, "1.16.0", None, None),
2015-03-26 14:06:26 -05:00
// Allows identifying crates that contain sanitizer runtimes.
(active, sanitizer_runtime, "1.17.0", None, None),
2015-06-30 22:05:17 -05:00
// Used to identify crates that contain the profiler runtime.
(active, profiler_runtime, "1.18.0", None, None),
// Allows using the `thiscall` ABI.
(active, abi_thiscall, "1.19.0", None, None),
// Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`.
(active, allocator_internals, "1.20.0", None, None),
// no-tracking-issue-end
// Added for testing E0705; perma-unstable.
(active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
// -------------------------------------------------------------------------
2019-05-01 14:42:57 -05:00
// feature-group-end: internal feature gates
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// feature-group-start: actual feature gates (target features)
// -------------------------------------------------------------------------
2015-07-02 16:07:42 -05:00
// FIXME: Document these and merge with the list below.
// Unstable `#[target_feature]` directives.
(active, arm_target_feature, "1.27.0", Some(44839), None),
(active, aarch64_target_feature, "1.27.0", Some(44839), None),
(active, hexagon_target_feature, "1.27.0", Some(44839), None),
(active, powerpc_target_feature, "1.27.0", Some(44839), None),
(active, mips_target_feature, "1.27.0", Some(44839), None),
(active, avx512_target_feature, "1.27.0", Some(44839), None),
(active, mmx_target_feature, "1.27.0", Some(44839), None),
(active, sse4a_target_feature, "1.27.0", Some(44839), None),
(active, tbm_target_feature, "1.27.0", Some(44839), None),
(active, wasm_target_feature, "1.30.0", Some(44839), None),
(active, adx_target_feature, "1.32.0", Some(44839), None),
(active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
(active, movbe_target_feature, "1.34.0", Some(44839), None),
(active, rtm_target_feature, "1.35.0", Some(44839), None),
(active, f16c_target_feature, "1.36.0", Some(44839), None),
// -------------------------------------------------------------------------
2019-05-01 14:42:57 -05:00
// feature-group-end: actual feature gates (target features)
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// feature-group-start: actual feature gates
// -------------------------------------------------------------------------
// Allows using the `#[link_args]` attribute.
(active, link_args, "1.0.0", Some(29596), None),
// Allows defining identifiers beyond ASCII.
(active, non_ascii_idents, "1.0.0", Some(55467), None),
// Allows using `#[plugin_registrar]` on functions.
(active, plugin_registrar, "1.0.0", Some(29597), None),
// Allows using `#![plugin(myplugin)]`.
(active, plugin, "1.0.0", Some(29597), None),
// Allows using `#[thread_local]` on `static` items.
(active, thread_local, "1.0.0", Some(29594), None),
// Allows the use of SIMD types in functions declared in `extern` blocks.
(active, simd_ffi, "1.0.0", Some(27731), None),
// Allows using custom attributes (RFC 572).
(active, custom_attribute, "1.0.0", Some(29642), None),
// Allows using non lexical lifetimes (RFC 2094).
(active, nll, "1.0.0", Some(43234), None),
// Allows using slice patterns.
(active, slice_patterns, "1.0.0", Some(62254), None),
// Allows the definition of `const` functions with some advanced features.
(active, const_fn, "1.2.0", Some(57563), None),
// Allows associated type defaults.
(active, associated_type_defaults, "1.2.0", Some(29661), None),
2015-08-03 22:32:02 -05:00
// Allows `#![no_core]`.
(active, no_core, "1.3.0", Some(29639), None),
// Allows default type parameters to influence type inference.
(active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
// Allows `repr(simd)` and importing the various simd intrinsics.
(active, repr_simd, "1.4.0", Some(27731), None),
// Allows `extern "platform-intrinsic" { ... }`.
(active, platform_intrinsics, "1.4.0", Some(27731), None),
// Allows `#[unwind(..)]`.
//
// Permits specifying whether a function should permit unwinding or abort on unwind.
(active, unwind_attributes, "1.4.0", Some(58760), None),
2015-09-18 05:36:45 -05:00
// Allows `#[no_debug]`.
(active, no_debug, "1.5.0", Some(29721), None),
// Allows attributes on expressions and non-item statements.
(active, stmt_expr_attributes, "1.6.0", Some(15701), None),
// Allows the use of type ascription in expressions.
(active, type_ascription, "1.6.0", Some(23416), None),
// Allows `cfg(target_thread_local)`.
(active, cfg_target_thread_local, "1.7.0", Some(29594), None),
// Allows specialization of implementations (RFC 1210).
(active, specialization, "1.7.0", Some(31844), None),
2016-04-10 18:33:36 -05:00
2019-05-01 14:42:57 -05:00
// Allows using `#[naked]` on functions.
(active, naked_functions, "1.9.0", Some(32408), None),
// Allows `cfg(target_has_atomic = "...")`.
(active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
// Allows `X..Y` patterns.
(active, exclusive_range_pattern, "1.11.0", Some(37854), None),
// Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more.
(active, never_type, "1.13.0", Some(35121), None),
// Allows exhaustive pattern matching on types that contain uninhabited types.
(active, exhaustive_patterns, "1.13.0", Some(51085), None),
// Allows untagged unions `union U { ... }`.
(active, untagged_unions, "1.13.0", Some(32836), None),
// Allows `#[link(..., cfg(..))]`.
(active, link_cfg, "1.14.0", Some(37406), None),
2016-11-10 04:29:36 -06:00
// Allows `extern "ptx-*" fn()`.
(active, abi_ptx, "1.15.0", Some(38788), None),
// Allows the `#[repr(i128)]` attribute for enums.
(active, repr128, "1.16.0", Some(35118), None),
// Allows `#[link(kind="static-nobundle"...)]`.
(active, static_nobundle, "1.16.0", Some(37403), None),
2016-12-16 01:46:21 -06:00
// Allows `extern "msp430-interrupt" fn()`.
(active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
2016-12-29 22:28:11 -06:00
// Allows declarative macros 2.0 (`macro`).
(active, decl_macro, "1.17.0", Some(39412), None),
// Allows `extern "x86-interrupt" fn()`.
(active, abi_x86_interrupt, "1.17.0", Some(40180), None),
add an #[used] attribute similar to GCC's __attribute((used))__. This attribute prevents LLVM from optimizing away a non-exported symbol, within a compilation unit (object file), when there are no references to it. This is better explained with an example: ``` #[used] static LIVE: i32 = 0; static REFERENCED: i32 = 0; static DEAD: i32 = 0; fn internal() {} pub fn exported() -> &'static i32 { &REFERENCED } ``` Without optimizations, LLVM pretty much preserves all the static variables and functions within the compilation unit. ``` $ rustc --crate-type=lib --emit=obj symbols.rs && nm -C symbols.o 0000000000000000 t drop::h1be0f8f27a2ba94a 0000000000000000 r symbols::REFERENCED::hb3bdfd46050bc84c 0000000000000000 r symbols::DEAD::hc2ea8f9bd06f380b 0000000000000000 r symbols::LIVE::h0970cf9889edb56e 0000000000000000 T symbols::exported::h6f096c2b1fc292b2 0000000000000000 t symbols::internal::h0ac1aadbc1e3a494 ``` With optimizations, LLVM will drop dead code. Here `internal` is dropped because it's not a exported function/symbol (i.e. not `pub`lic). `DEAD` is dropped for the same reason. `REFERENCED` is preserved, even though it's not exported, because it's referenced by the `exported` function. Finally, `LIVE` survives because of the `#[used]` attribute even though it's not exported or referenced. ``` $ rustc --crate-type=lib -C opt-level=3 --emit=obj symbols.rs && nm -C symbols.o 0000000000000000 r symbols::REFERENCED::hb3bdfd46050bc84c 0000000000000000 r symbols::LIVE::h0970cf9889edb56e 0000000000000000 T symbols::exported::h6f096c2b1fc292b2 ``` Note that the linker knows nothing about `#[used]` and will drop `LIVE` because no other object references to it. ``` $ echo 'fn main() {}' >> symbols.rs $ rustc symbols.rs && nm -C symbols | grep LIVE ``` At this time, `#[used]` only works on `static` variables.
2017-02-20 13:42:47 -06:00
// Allows overlapping impls of marker traits.
(active, overlapping_marker_traits, "1.18.0", Some(29864), None),
2017-04-15 16:39:19 -05:00
// Allows a test to fail without failing the whole suite.
(active, allow_fail, "1.19.0", Some(46488), None),
// Allows unsized tuple coercion.
(active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
// Allows defining generators.
(active, generators, "1.21.0", Some(43122), None),
2016-12-26 07:34:03 -06:00
// Allows `#[doc(cfg(...))]`.
(active, doc_cfg, "1.21.0", Some(43781), None),
// Allows `#[doc(masked)]`.
(active, doc_masked, "1.21.0", Some(44027), None),
// Allows `#[doc(spotlight)]`.
(active, doc_spotlight, "1.22.0", Some(45040), None),
// Allows `#[doc(include = "some-file")]`.
(active, external_doc, "1.22.0", Some(44732), None),
// Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008).
(active, non_exhaustive, "1.22.0", Some(44109), None),
2017-11-03 14:14:39 -05:00
// Allows using `crate` as visibility modifier, synonymous with `pub(crate)`.
(active, crate_visibility_modifier, "1.23.0", Some(53120), None),
2017-09-03 13:53:58 -05:00
// Allows defining `extern type`s.
(active, extern_types, "1.23.0", Some(43467), None),
// Allows trait methods with arbitrary self types.
(active, arbitrary_self_types, "1.23.0", Some(44874), None),
std: Add a new wasm32-unknown-unknown target This commit adds a new target to the compiler: wasm32-unknown-unknown. This target is a reimagining of what it looks like to generate WebAssembly code from Rust. Instead of using Emscripten which can bring with it a weighty runtime this instead is a target which uses only the LLVM backend for WebAssembly and a "custom linker" for now which will hopefully one day be direct calls to lld. Notable features of this target include: * There is zero runtime footprint. The target assumes nothing exists other than the wasm32 instruction set. * There is zero toolchain footprint beyond adding the target. No custom linker is needed, rustc contains everything. * Very small wasm modules can be generated directly from Rust code using this target. * Most of the standard library is stubbed out to return an error, but anything related to allocation works (aka `HashMap`, `Vec`, etc). * Naturally, any `#[no_std]` crate should be 100% compatible with this new target. This target is currently somewhat janky due to how linking works. The "linking" is currently unconditional whole program LTO (aka LLVM is being used as a linker). Naturally that means compiling programs is pretty slow! Eventually though this target should have a linker. This target is also intended to be quite experimental. I'm hoping that this can act as a catalyst for further experimentation in Rust with WebAssembly. Breaking changes are very likely to land to this target, so it's not recommended to rely on it in any critical capacity yet. We'll let you know when it's "production ready". --- Currently testing-wise this target is looking pretty good but isn't complete. I've got almost the entire `run-pass` test suite working with this target (lots of tests ignored, but many passing as well). The `core` test suite is still getting LLVM bugs fixed to get that working and will take some time. Relatively simple programs all seem to work though! --- It's worth nothing that you may not immediately see the "smallest possible wasm module" for the input you feed to rustc. For various reasons it's very difficult to get rid of the final "bloat" in vanilla rustc (again, a real linker should fix all this). For now what you'll have to do is: cargo install --git https://github.com/alexcrichton/wasm-gc wasm-gc foo.wasm bar.wasm And then `bar.wasm` should be the smallest we can get it! --- In any case for now I'd love feedback on this, particularly on the various integration points if you've got better ideas of how to approach them!
2017-10-22 22:01:00 -05:00
// Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
(active, in_band_lifetimes, "1.23.0", Some(44524), None),
// Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598).
(active, generic_associated_types, "1.23.0", Some(44265), None),
// Allows defining `trait X = A + B;` alias items.
(active, trait_alias, "1.24.0", Some(41517), None),
// Allows infering `'static` outlives requirements (RFC 2093).
(active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
// Allows macro invocations in `extern {}` blocks.
(active, macros_in_extern, "1.27.0", Some(49476), None),
// Allows accessing fields of unions inside `const` functions.
(active, const_fn_union, "1.27.0", Some(51909), None),
2018-07-03 12:38:14 -05:00
// Allows casting raw pointers to `usize` during const eval.
(active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
rustc: Tweak custom attribute capabilities This commit starts to lay some groundwork for the stabilization of custom attribute invocations and general procedural macros. It applies a number of changes discussed on [internals] as well as a [recent issue][issue], namely: * The path used to specify a custom attribute must be of length one and cannot be a global path. This'll help future-proof us against any ambiguities and give us more time to settle the precise syntax. In the meantime though a bare identifier can be used and imported to invoke a custom attribute macro. A new feature gate, `proc_macro_path_invoc`, was added to gate multi-segment paths and absolute paths. * The set of items which can be annotated by a custom procedural attribute has been restricted. Statements, expressions, and modules are disallowed behind two new feature gates: `proc_macro_expr` and `proc_macro_mod`. * The input to procedural macro attributes has been restricted and adjusted. Today an invocation like `#[foo(bar)]` will receive `(bar)` as the input token stream, but after this PR it will only receive `bar` (the delimiters were removed). Invocations like `#[foo]` are still allowed and will be invoked in the same way as `#[foo()]`. This is a **breaking change** for all nightly users as the syntax coming in to procedural macros will be tweaked slightly. * Procedural macros (`foo!()` style) can only be expanded to item-like items by default. A separate feature gate, `proc_macro_non_items`, is required to expand to items like expressions, statements, etc. Closes #50038 [internals]: https://internals.rust-lang.org/t/help-stabilize-a-subset-of-macros-2-0/7252 [issue]: https://github.com/rust-lang/rust/issues/50038
2018-04-20 09:50:39 -05:00
// Allows dereferencing raw pointers during const eval.
(active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
// Allows comparing raw pointers during const eval.
(active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
2018-04-19 10:46:13 -05:00
// Allows `#[doc(alias = "...")]`.
(active, doc_alias, "1.27.0", Some(50146), None),
// Allows inconsistent bounds in where clauses.
2018-05-06 16:50:35 -05:00
(active, trivial_bounds, "1.28.0", Some(48214), None),
2018-05-12 04:33:33 -05:00
// Allows `'a: { break 'a; }`.
2018-05-12 04:33:33 -05:00
(active, label_break_value, "1.28.0", Some(48594), None),
2018-04-30 03:55:24 -05:00
// Allows using `#[doc(keyword = "...")]`.
2018-06-02 17:45:49 -05:00
(active, doc_keyword, "1.28.0", Some(51315), None),
// Allows reinterpretation of the bits of a value of one type as another type during const eval.
(active, const_transmute, "1.29.0", Some(53605), None),
// Allows using `try {...}` expressions.
(active, try_blocks, "1.29.0", Some(31436), None),
// Allows defining an `#[alloc_error_handler]`.
(active, alloc_error_handler, "1.29.0", Some(51540), None),
// Allows using the `amdgpu-kernel` ABI.
(active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
// Allows panicking during const eval (producing compile-time errors).
(active, const_panic, "1.30.0", Some(51999), None),
// Allows `#[marker]` on certain traits allowing overlapping implementations.
(active, marker_trait_attr, "1.30.0", Some(29864), None),
// Allows macro invocations on modules expressions and statements and
// procedural macros to expand to non-items.
(active, proc_macro_hygiene, "1.30.0", Some(54727), None),
// Allows unsized rvalues at arguments and parameters.
2018-05-28 10:10:09 -05:00
(active, unsized_locals, "1.30.0", Some(48055), None),
2018-07-20 20:04:02 -05:00
// Allows custom test frameworks with `#![test_runner]` and `#[test_case]`.
2018-07-20 20:04:02 -05:00
(active, custom_test_frameworks, "1.30.0", Some(50297), None),
// Allows non-builtin attributes in inner attribute position.
(active, custom_inner_attributes, "1.30.0", Some(54726), None),
// Allows mixing bind-by-move in patterns and references to those identifiers in guards.
(active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
// Allows `impl Trait` in bindings (`let`, `const`, `static`).
(active, impl_trait_in_bindings, "1.30.0", Some(63065), None),
2018-10-04 06:55:47 -05:00
// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
(active, lint_reasons, "1.31.0", Some(54503), None),
// Allows exhaustive integer pattern matching on `usize` and `isize`.
(active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
// Allows relaxing the coherence rules such that
// `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
(active, re_rebalance_coherence, "1.32.0", Some(55437), None),
// Allows using `#[ffi_returns_twice]` on foreign functions.
(active, ffi_returns_twice, "1.34.0", Some(58314), None),
// Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
(active, const_generics, "1.34.0", Some(44580), None),
// Allows using `#[optimize(X)]`.
(active, optimize_attribute, "1.34.0", Some(54882), None),
// Allows using C-variadics.
2019-02-24 16:40:11 -06:00
(active, c_variadic, "1.34.0", Some(44930), None),
2019-05-01 14:42:57 -05:00
2019-03-21 13:40:00 -05:00
// Allows the user of associated type bounds.
(active, associated_type_bounds, "1.34.0", Some(52662), None),
2019-06-15 12:00:49 -05:00
// Attributes on formal function params.
(active, param_attrs, "1.36.0", Some(60406), None),
2019-06-15 12:00:49 -05:00
// Allows calling constructor functions in `const fn`.
(active, const_constructor, "1.37.0", Some(61456), None),
2019-05-11 08:11:04 -05:00
// Allows `if/while p && let q = r && ...` chains.
(active, let_chains, "1.37.0", Some(53667), None),
// Allows #[repr(transparent)] on enums (RFC 2645).
(active, transparent_enums, "1.37.0", Some(60405), None),
// Allows #[repr(transparent)] on unions (RFC 2645).
(active, transparent_unions, "1.37.0", Some(60405), None),
2019-05-09 16:08:55 -05:00
// Allows explicit discriminants on non-unit enum variants.
(active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
2019-06-24 14:55:39 -05:00
// Allows `impl Trait` with multiple unrelated lifetimes.
(active, member_constraints, "1.37.0", Some(61977), None),
// Allows `async || body` closures.
(active, async_closure, "1.37.0", Some(62290), None),
// Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests
(active, cfg_doctest, "1.37.0", Some(62210), None),
// Allows `[x; N]` where `x` is a constant (RFC 2203).
(active, const_in_array_repeat_expressions, "1.37.0", Some(49147), None),
// Allows `impl Trait` to be used inside type aliases (RFC 2515).
(active, type_alias_impl_trait, "1.38.0", Some(63063), None),
// Allows the use of or-patterns, e.g. `0 | 1`.
(active, or_patterns, "1.38.0", Some(54883), None),
2019-05-01 14:42:57 -05:00
// -------------------------------------------------------------------------
// feature-group-end: actual feature gates
// -------------------------------------------------------------------------
);
2019-07-28 19:00:53 -05:00
/// Some features are known to be incomplete and using them is likely to have
/// unanticipated results, such as compiler crashes. We warn the user about these
/// to alert them.
pub const INCOMPLETE_FEATURES: &[Symbol] = &[
sym::impl_trait_in_bindings,
sym::generic_associated_types,
2019-05-11 08:11:04 -05:00
sym::const_generics,
sym::or_patterns,
2019-05-11 08:11:04 -05:00
sym::let_chains,
];
2018-11-29 20:57:30 -06:00
// If you change this, please modify `src/doc/unstable-book` as well. You must
// move that documentation into the relevant place in the other docs, and
// remove the chapter on the flag.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum AttributeType {
/// Normal, builtin attribute that is consumed
/// by the compiler before the unused_attribute check
Normal,
/// Builtin attribute that may not be consumed by the compiler
/// before the unused_attribute check. These attributes
/// will be ignored by the unused_attribute lint
Whitelisted,
/// Builtin attribute that is only allowed at the crate level
CrateLevel,
}
pub enum AttributeGate {
/// Is gated by a given feature gate, reason
/// and function to check if enabled
Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
/// Ungated attribute, can be used on all release channels
Ungated,
}
2019-01-12 10:00:42 -06:00
/// A convenience macro for constructing attribute templates.
2019-02-08 07:53:55 -06:00
/// E.g., `template!(Word, List: "description")` means that the attribute
2019-01-12 10:00:42 -06:00
/// supports forms `#[attr]` and `#[attr(description)]`.
macro_rules! template {
(Word) => { template!(@ true, None, None) };
(List: $descr: expr) => { template!(@ false, Some($descr), None) };
(NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
(Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
(Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
(List: $descr1: expr, NameValueStr: $descr2: expr) => {
template!(@ false, Some($descr1), Some($descr2))
};
(Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
template!(@ true, Some($descr1), Some($descr2))
};
2019-01-12 10:00:42 -06:00
(@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
word: $word, list: $list, name_value_str: $name_value_str
} };
}
2016-10-18 00:04:28 -05:00
impl AttributeGate {
fn is_deprecated(&self) -> bool {
match *self {
Gated(Stability::Deprecated(_, _), ..) => true,
2016-10-18 00:04:28 -05:00
_ => false,
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Stability {
Unstable,
// First argument is tracking issue link; second argument is an optional
// help message, which defaults to "remove this attribute"
Deprecated(&'static str, Option<&'static str>),
}
// fn() is not Debug
2019-02-06 11:33:01 -06:00
impl std::fmt::Debug for AttributeGate {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Gated(ref stab, name, expl, _) =>
2016-10-18 00:04:28 -05:00
write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
Ungated => write!(fmt, "Ungated")
}
}
}
macro_rules! cfg_fn {
($field: ident) => {{
fn f(features: &Features) -> bool {
features.$field
}
f as fn(&Features) -> bool
}}
}
pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
AttributeTemplate, AttributeGate)> {
BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
2016-10-18 00:04:28 -05:00
}
pub fn is_builtin_attr_name(name: ast::Name) -> bool {
BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
}
pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
}
/// Attributes that have a special meaning to rustc or rustdoc
pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
// Normal attributes
(
sym::warn,
Normal,
template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
Ungated
),
(
sym::allow,
Normal,
template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
Ungated
),
(
sym::forbid,
Normal,
template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
Ungated
),
(
sym::deny,
Normal,
template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
Ungated
),
(sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
(sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
(sym::plugin_registrar, Normal, template!(Word), Ungated),
(sym::cfg, Normal, template!(List: "predicate"), Ungated),
(sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
(sym::main, Normal, template!(Word), Ungated),
(sym::start, Normal, template!(Word), Ungated),
(sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
(sym::path, Normal, template!(NameValueStr: "file"), Ungated),
(sym::automatically_derived, Normal, template!(Word), Ungated),
(sym::no_mangle, Whitelisted, template!(Word), Ungated),
(sym::no_link, Normal, template!(Word), Ungated),
(sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
(
sym::should_panic,
Normal,
template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
Ungated
),
(sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
(sym::no_implicit_prelude, Normal, template!(Word), Ungated),
(sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
(sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
sym::link_args,
"the `link_args` attribute is experimental and not \
portable across platforms, it is recommended to \
use `#[link(name = \"foo\")] instead",
cfg_fn!(link_args))),
(sym::macro_escape, Normal, template!(Word), Ungated),
// RFC #1445.
(sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::structural_match,
"the semantics of constant patterns is \
not yet settled",
cfg_fn!(structural_match))),
2017-11-03 14:14:39 -05:00
// RFC #2008
(sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::non_exhaustive,
"non exhaustive is an experimental feature",
cfg_fn!(non_exhaustive))),
2017-11-03 14:14:39 -05:00
// RFC #1268
(sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
sym::marker_trait_attr,
"marker traits is an experimental feature",
cfg_fn!(marker_trait_attr))),
(sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
sym::plugin,
"compiler plugins are experimental \
and possibly buggy",
cfg_fn!(plugin))),
(sym::no_std, CrateLevel, template!(Word), Ungated),
(sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
sym::no_core,
"no_core is experimental",
cfg_fn!(no_core))),
(sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
sym::lang_items,
"language items are subject to change",
cfg_fn!(lang_items))),
(sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
Gated(Stability::Unstable,
sym::linkage,
"the `linkage` attribute is experimental \
and not portable across platforms",
cfg_fn!(linkage))),
(sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::thread_local,
"`#[thread_local]` is an experimental feature, and does \
2019-04-10 18:40:12 -05:00
not currently handle destructors",
cfg_fn!(thread_local))),
(sym::rustc_on_unimplemented, Whitelisted, template!(List:
r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
NameValueStr: "message"),
Gated(Stability::Unstable,
sym::on_unimplemented,
"the `#[rustc_on_unimplemented]` attribute \
is an experimental feature",
cfg_fn!(on_unimplemented))),
(sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
Gated(Stability::Unstable,
sym::rustc_const_unstable,
"the `#[rustc_const_unstable]` attribute \
is an internal feature",
cfg_fn!(rustc_const_unstable))),
(sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::allocator_internals,
"the `#[default_lib_allocator]` \
attribute is an experimental feature",
cfg_fn!(allocator_internals))),
(sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
sym::allocator_internals,
"the `#[needs_allocator]` \
attribute is an experimental \
feature",
cfg_fn!(allocator_internals))),
(sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::panic_runtime,
"the `#[panic_runtime]` attribute is \
an experimental feature",
cfg_fn!(panic_runtime))),
(sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::needs_panic_runtime,
"the `#[needs_panic_runtime]` \
rustc: Implement custom panic runtimes This commit is an implementation of [RFC 1513] which allows applications to alter the behavior of panics at compile time. A new compiler flag, `-C panic`, is added and accepts the values `unwind` or `panic`, with the default being `unwind`. This model affects how code is generated for the local crate, skipping generation of landing pads with `-C panic=abort`. [RFC 1513]: https://github.com/rust-lang/rfcs/blob/master/text/1513-less-unwinding.md Panic implementations are then provided by crates tagged with `#![panic_runtime]` and lazily required by crates with `#![needs_panic_runtime]`. The panic strategy (`-C panic` value) of the panic runtime must match the final product, and if the panic strategy is not `abort` then the entire DAG must have the same panic strategy. With the `-C panic=abort` strategy, users can expect a stable method to disable generation of landing pads, improving optimization in niche scenarios, decreasing compile time, and decreasing output binary size. With the `-C panic=unwind` strategy users can expect the existing ability to isolate failure in Rust code from the outside world. Organizationally, this commit dismantles the `sys_common::unwind` module in favor of some bits moving part of it to `libpanic_unwind` and the rest into the `panicking` module in libstd. The custom panic runtime support is pretty similar to the custom allocator support with the only major difference being how the panic runtime is injected (takes the `-C panic` flag into account).
2016-04-08 18:18:40 -05:00
attribute is an experimental \
feature",
cfg_fn!(needs_panic_runtime))),
(sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_outlives]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_variance]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_layout]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_layout_scalar_valid_range_start]` attribute \
is just used to enable niche optimizations in libcore \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_layout_scalar_valid_range_end]` attribute \
is just used to enable niche optimizations in libcore \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_nonnull_optimization_guaranteed]` attribute \
is just used to enable niche optimizations in libcore \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_regions]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_error]` attribute \
2015-08-18 16:59:21 -05:00
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"this attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_if_this_changed]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_if_this_changed]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
/*opt*/ except = "...""#),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_dirty]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
/*opt*/ except = "...""#),
Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_clean]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(
sym::rustc_partition_reused,
Whitelisted,
template!(List: r#"cfg = "...", module = "...""#),
Gated(
Stability::Unstable,
sym::rustc_attrs,
"this attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs)
)
),
(
sym::rustc_partition_codegened,
Whitelisted,
template!(List: r#"cfg = "...", module = "...""#),
Gated(
Stability::Unstable,
sym::rustc_attrs,
"this attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs),
)
),
(sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
kind = "...""#),
Gated(Stability::Unstable,
sym::rustc_attrs,
"this attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"this attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal rustc attributes will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal rustc attributes will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_mir]` attribute \
is just used for rustc unit tests \
and will never be stable",
cfg_fn!(rustc_attrs))),
(
sym::rustc_inherit_overflow_checks,
Whitelisted,
template!(Word),
Gated(
Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_inherit_overflow_checks]` \
attribute is just used to control \
overflow checking behavior of several \
libcore functions that are inlined \
across crates and will never be stable",
cfg_fn!(rustc_attrs),
)
),
(sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_dump_program_clauses]` \
attribute is just used for rustc unit \
tests and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_dump_env_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_dump_env_program_clauses]` \
attribute is just used for rustc unit \
tests and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_object_lifetime_default, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_object_lifetime_default]` \
attribute is just used for rustc unit \
tests and will never be stable",
cfg_fn!(rustc_attrs))),
(sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"the `#[rustc_test_marker]` attribute \
is used internally to track tests",
cfg_fn!(rustc_attrs))),
(sym::rustc_macro_transparency, Whitelisted, template!(NameValueStr:
"transparent|semitransparent|opaque"),
Gated(Stability::Unstable,
sym::rustc_attrs,
"used internally for testing macro hygiene",
cfg_fn!(rustc_attrs))),
(sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::compiler_builtins,
"the `#[compiler_builtins]` attribute is used to \
identify the `compiler_builtins` crate which \
contains compiler-rt intrinsics and will never be \
stable",
cfg_fn!(compiler_builtins))),
(sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::sanitizer_runtime,
"the `#[sanitizer_runtime]` attribute is used to \
identify crates that contain the runtime of a \
sanitizer and will never be stable",
cfg_fn!(sanitizer_runtime))),
(sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::profiler_runtime,
"the `#[profiler_runtime]` attribute is used to \
identify the `profiler_builtins` crate which \
contains the profiler runtime and will never be \
stable",
cfg_fn!(profiler_runtime))),
(sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
Gated(Stability::Unstable,
sym::allow_internal_unstable,
EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
cfg_fn!(allow_internal_unstable))),
(sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
sym::allow_internal_unsafe,
EXPLAIN_ALLOW_INTERNAL_UNSAFE,
cfg_fn!(allow_internal_unsafe))),
(sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::fundamental,
"the `#[fundamental]` attribute \
is an experimental feature",
cfg_fn!(fundamental))),
(sym::proc_macro_derive, Normal, template!(List: "TraitName, \
/*opt*/ attributes(name1, name2, ...)"),
Ungated),
rustc: Implement custom derive (macros 1.1) This commit is an implementation of [RFC 1681] which adds support to the compiler for first-class user-define custom `#[derive]` modes with a far more stable API than plugins have today. [RFC 1681]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md The main features added by this commit are: * A new `rustc-macro` crate-type. This crate type represents one which will provide custom `derive` implementations and perhaps eventually flower into the implementation of macros 2.0 as well. * A new `rustc_macro` crate in the standard distribution. This crate will provide the runtime interface between macro crates and the compiler. The API here is particularly conservative right now but has quite a bit of room to expand into any manner of APIs required by macro authors. * The ability to load new derive modes through the `#[macro_use]` annotations on other crates. All support added here is gated behind the `rustc_macro` feature gate, both for the library support (the `rustc_macro` crate) as well as the language features. There are a few minor differences from the implementation outlined in the RFC, such as the `rustc_macro` crate being available as a dylib and all symbols are `dlsym`'d directly instead of having a shim compiled. These should only affect the implementation, however, not the public interface. This commit also ended up touching a lot of code related to `#[derive]`, making a few notable changes: * Recognized derive attributes are no longer desugared to `derive_Foo`. Wasn't sure how to keep this behavior and *not* expose it to custom derive. * Derive attributes no longer have access to unstable features by default, they have to opt in on a granular level. * The `derive(Copy,Clone)` optimization is now done through another "obscure attribute" which is just intended to ferry along in the compiler that such an optimization is possible. The `derive(PartialEq,Eq)` optimization was also updated to do something similar. --- One part of this PR which needs to be improved before stabilizing are the errors and exact interfaces here. The error messages are relatively poor quality and there are surprising spects of this such as `#[derive(PartialEq, Eq, MyTrait)]` not working by default. The custom attributes added by the compiler end up becoming unstable again when going through a custom impl. Hopefully though this is enough to start allowing experimentation on crates.io! syntax-[breaking-change]
2016-08-22 19:07:11 -05:00
(sym::rustc_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal implementation detail",
cfg_fn!(rustc_attrs))),
(sym::rustc_allocator_nounwind, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal implementation detail",
cfg_fn!(rustc_attrs))),
(sym::rustc_builtin_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal implementation detail",
cfg_fn!(rustc_attrs))),
(sym::rustc_promotable, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal implementation detail",
cfg_fn!(rustc_attrs))),
(sym::rustc_allow_const_fn_ptr, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"internal implementation detail",
cfg_fn!(rustc_attrs))),
(sym::rustc_dummy, Normal, template!(Word /* doesn't matter*/), Gated(Stability::Unstable,
sym::rustc_attrs,
"used by the test suite",
cfg_fn!(rustc_attrs))),
// FIXME: #14408 whitelist docs since rustdoc looks at them
(
sym::doc,
Whitelisted,
template!(List: "hidden|inline|...", NameValueStr: "string"),
Ungated
),
2018-05-08 08:10:16 -05:00
// FIXME: #14406 these are processed in codegen, which happens after the
// lint pass
(sym::cold, Whitelisted, template!(Word), Ungated),
(sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::naked_functions,
"the `#[naked]` attribute \
is an experimental feature",
cfg_fn!(naked_functions))),
(sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::ffi_returns_twice,
"the `#[ffi_returns_twice]` attribute \
is an experimental feature",
cfg_fn!(ffi_returns_twice))),
(sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
(sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
(sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
(sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
/*opt*/ cfg = "...""#), Ungated),
(sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
(sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
(sym::no_builtins, Whitelisted, template!(Word), Ungated),
(sym::no_debug, Whitelisted, template!(Word), Gated(
Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
sym::no_debug,
"the `#[no_debug]` attribute was an experimental feature that has been \
deprecated due to lack of demand",
2016-10-18 00:04:28 -05:00
cfg_fn!(no_debug))),
(
sym::omit_gdb_pretty_printer_section,
Whitelisted,
template!(Word),
Gated(
Stability::Unstable,
sym::omit_gdb_pretty_printer_section,
"the `#[omit_gdb_pretty_printer_section]` \
attribute is just used for the Rust test \
suite",
cfg_fn!(omit_gdb_pretty_printer_section)
)
),
(sym::may_dangle,
Normal,
template!(Word),
Gated(Stability::Unstable,
sym::dropck_eyepatch,
2019-07-12 21:33:51 -05:00
"`may_dangle` has unstable semantics and may be removed in the future",
cfg_fn!(dropck_eyepatch))),
(sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
sym::unwind_attributes,
"`#[unwind]` is experimental",
cfg_fn!(unwind_attributes))),
(sym::used, Whitelisted, template!(Word), Ungated),
// used in resolve
(sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::prelude_import,
"`#[prelude_import]` is for use by rustc only",
cfg_fn!(prelude_import))),
// FIXME: #14407 these are only looked at on-demand so we can't
// guarantee they'll have already been checked
(
sym::rustc_deprecated,
Whitelisted,
template!(List: r#"since = "version", reason = "...""#),
Ungated
),
(sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
(
sym::stable,
Whitelisted,
template!(List: r#"feature = "name", since = "version""#),
Ungated
),
(
sym::unstable,
Whitelisted,
template!(List: r#"feature = "name", reason = "...", issue = "N""#),
Ungated
),
(sym::deprecated,
Normal,
template!(
Word,
List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
NameValueStr: "reason"
),
Ungated
),
(sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
sym::unboxed_closures,
"unboxed_closures are still evolving",
cfg_fn!(unboxed_closures))),
(sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
(sym::proc_macro_attribute, Normal, template!(Word), Ungated),
(sym::proc_macro, Normal, template!(Word), Ungated),
(sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"used internally by rustc",
cfg_fn!(rustc_attrs))),
(sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
sym::allow_fail,
"allow_fail attribute is currently unstable",
cfg_fn!(allow_fail))),
(sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"this is an internal attribute that will \
never be stable",
cfg_fn!(rustc_attrs))),
type error method suggestions use whitelisted identity-like conversions Previously, on a type mismatch (and if this wasn't preëmpted by a higher-priority suggestion), we would look for argumentless methods returning the expected type, and list them in a `help` note. This had two major shortcomings. Firstly, a lot of the suggestions didn't really make sense (if you used a &str where a String was expected, `.to_ascii_uppercase()` is probably not the solution you were hoping for). Secondly, we weren't generating suggestions from the most useful traits! We address the first problem with an internal `#[rustc_conversion_suggestion]` attribute meant to mark methods that keep the "same value" in the relevant sense, just converting the type. We address the second problem by making `FnCtxt.probe_for_return_type` pass the `ProbeScope::AllTraits` to `probe_op`: this would seem to be safe because grep reveals no other callers of `probe_for_return_type`. Also, structured suggestions are preferred (because they're pretty, but also for RLS and friends). Also also, we make the E0055 autoderef recursion limit error use the one-time-diagnostics set, because we can potentially hit the limit a lot during probing. (Without this, test/ui/did_you_mean/recursion_limit_deref.rs would report "aborting due to 51 errors"). Unfortunately, the trait probing is still not all one would hope for: at a minimum, we don't know how to rule out `into()` in cases where it wouldn't actually work, and we don't know how to rule in `.to_owned()` where it would. Issues #46459 and #46460 have been filed and are ref'd in a FIXME. This is hoped to resolve #42929, #44672, and #45777.
2017-11-19 13:25:35 -06:00
// whitelists "identity-like" conversion methods to suggest on type mismatch
(sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
sym::rustc_attrs,
"this is an internal attribute that will \
type error method suggestions use whitelisted identity-like conversions Previously, on a type mismatch (and if this wasn't preëmpted by a higher-priority suggestion), we would look for argumentless methods returning the expected type, and list them in a `help` note. This had two major shortcomings. Firstly, a lot of the suggestions didn't really make sense (if you used a &str where a String was expected, `.to_ascii_uppercase()` is probably not the solution you were hoping for). Secondly, we weren't generating suggestions from the most useful traits! We address the first problem with an internal `#[rustc_conversion_suggestion]` attribute meant to mark methods that keep the "same value" in the relevant sense, just converting the type. We address the second problem by making `FnCtxt.probe_for_return_type` pass the `ProbeScope::AllTraits` to `probe_op`: this would seem to be safe because grep reveals no other callers of `probe_for_return_type`. Also, structured suggestions are preferred (because they're pretty, but also for RLS and friends). Also also, we make the E0055 autoderef recursion limit error use the one-time-diagnostics set, because we can potentially hit the limit a lot during probing. (Without this, test/ui/did_you_mean/recursion_limit_deref.rs would report "aborting due to 51 errors"). Unfortunately, the trait probing is still not all one would hope for: at a minimum, we don't know how to rule out `into()` in cases where it wouldn't actually work, and we don't know how to rule in `.to_owned()` where it would. Issues #46459 and #46460 have been filed and are ref'd in a FIXME. This is hoped to resolve #42929, #44672, and #45777.
2017-11-19 13:25:35 -06:00
never be stable",
cfg_fn!(rustc_attrs))),
type error method suggestions use whitelisted identity-like conversions Previously, on a type mismatch (and if this wasn't preëmpted by a higher-priority suggestion), we would look for argumentless methods returning the expected type, and list them in a `help` note. This had two major shortcomings. Firstly, a lot of the suggestions didn't really make sense (if you used a &str where a String was expected, `.to_ascii_uppercase()` is probably not the solution you were hoping for). Secondly, we weren't generating suggestions from the most useful traits! We address the first problem with an internal `#[rustc_conversion_suggestion]` attribute meant to mark methods that keep the "same value" in the relevant sense, just converting the type. We address the second problem by making `FnCtxt.probe_for_return_type` pass the `ProbeScope::AllTraits` to `probe_op`: this would seem to be safe because grep reveals no other callers of `probe_for_return_type`. Also, structured suggestions are preferred (because they're pretty, but also for RLS and friends). Also also, we make the E0055 autoderef recursion limit error use the one-time-diagnostics set, because we can potentially hit the limit a lot during probing. (Without this, test/ui/did_you_mean/recursion_limit_deref.rs would report "aborting due to 51 errors"). Unfortunately, the trait probing is still not all one would hope for: at a minimum, we don't know how to rule out `into()` in cases where it wouldn't actually work, and we don't know how to rule in `.to_owned()` where it would. Issues #46459 and #46460 have been filed and are ref'd in a FIXME. This is hoped to resolve #42929, #44672, and #45777.
2017-11-19 13:25:35 -06:00
(
sym::rustc_args_required_const,
Whitelisted,
template!(List: "N"),
Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
cfg_fn!(rustc_attrs))
),
2018-04-30 03:55:24 -05:00
// RFC 2070
(sym::panic_handler, Normal, template!(Word), Ungated),
2018-04-30 03:55:24 -05:00
(sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
sym::alloc_error_handler,
"`#[alloc_error_handler]` is an unstable feature",
cfg_fn!(alloc_error_handler))),
// RFC 2412
(sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
sym::optimize_attribute,
"`#[optimize]` attribute is an unstable feature",
cfg_fn!(optimize_attribute))),
// Crate level attributes
(sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
(sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
(sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
(sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
(sym::no_start, CrateLevel, template!(Word), Ungated),
(sym::no_main, CrateLevel, template!(Word), Ungated),
(sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
(sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
(sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
sym::custom_test_frameworks,
"custom test frameworks are an unstable feature",
2018-07-20 20:04:02 -05:00
cfg_fn!(custom_test_frameworks))),
];
pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
lazy_static! {
pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
let mut map = FxHashMap::default();
for attr in BUILTIN_ATTRIBUTES.iter() {
if map.insert(attr.0, attr).is_some() {
panic!("duplicate builtin attribute `{}`", attr.0);
}
}
map
};
}
// cfg(...)'s that are feature gated
const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
// (name in cfg, feature, function to check if the feature is enabled)
(sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
(sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
(sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
(sym::doctest, sym::cfg_doctest, cfg_fn!(cfg_doctest)),
];
#[derive(Debug)]
pub struct GatedCfg {
span: Span,
index: usize,
}
2015-07-31 02:04:06 -05:00
impl GatedCfg {
pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
GATED_CFGS.iter()
.position(|info| cfg.check_name(info.0))
.map(|idx| {
GatedCfg {
span: cfg.span,
index: idx
}
})
}
2016-06-10 20:37:24 -05:00
pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
let (cfg, feature, has_feature) = GATED_CFGS[self.index];
if !has_feature(features) && !self.span.allows_unstable(feature) {
let explain = format!("`cfg({})` is experimental and subject to change", cfg);
2016-09-24 11:42:54 -05:00
emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
}
}
}
2014-03-05 08:36:01 -06:00
struct Context<'a> {
features: &'a Features,
2016-09-24 11:42:54 -05:00
parse_sess: &'a ParseSess,
plugin_attributes: &'a [(Symbol, AttributeType)],
}
macro_rules! gate_feature_fn {
($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
let (cx, has_feature, span,
name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
let has_feature: bool = has_feature(&$cx.features);
debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
if !has_feature && !span.allows_unstable($name) {
leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
.emit();
}
}}
}
macro_rules! gate_feature {
($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
sym::$feature, $explain, GateStrength::Hard)
};
($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
sym::$feature, $explain, $level)
};
}
impl<'a> Context<'a> {
fn check_attribute(
&self,
attr: &ast::Attribute,
attr_info: Option<&BuiltinAttribute>,
is_macro: bool
) {
debug!("check_attribute(attr = {:?})", attr);
if let Some(&(name, ty, _template, ref gateage)) = attr_info {
if let Gated(_, name, desc, ref has_feature) = *gateage {
if !attr.span.allows_unstable(name) {
gate_feature_fn!(
self, has_feature, attr.span, name, desc, GateStrength::Hard
);
}
} else if name == sym::doc {
if let Some(content) = attr.meta_item_list() {
if content.iter().any(|c| c.check_name(sym::include)) {
gate_feature!(self, external_doc, attr.span,
"`#[doc(include = \"...\")]` is experimental"
);
}
}
}
debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
return;
2019-06-30 05:00:45 -05:00
} else {
for segment in &attr.path.segments {
if segment.ident.as_str().starts_with("rustc") {
let msg = "attributes starting with `rustc` are \
reserved for use by the `rustc` compiler";
gate_feature!(self, rustc_attrs, segment.ident.span, msg);
}
}
}
for &(n, ty) in self.plugin_attributes {
if attr.path == n {
// Plugins can't gate attributes, so we don't check for it
2015-05-13 01:53:43 -05:00
// unlike the code above; we only use this loop to
// short-circuit to avoid the checks below.
debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
return;
}
}
if !is_macro && !attr::is_known(attr) {
// Only run the custom attribute lint during regular feature gate
// checking. Macro gating runs before the plugin attributes are
// registered, so we skip this in that case.
2019-07-12 21:33:51 -05:00
let msg = format!("the attribute `{}` is currently unknown to the compiler and \
may have meaning added to it in the future", attr.path);
gate_feature!(self, custom_attribute, attr.span, &msg);
}
}
}
2017-03-16 23:04:41 -05:00
pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
2019-06-25 16:22:45 -05:00
let cx = Context { features, parse_sess, plugin_attributes: &[] };
cx.check_attribute(
attr,
attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
true
);
}
fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
let issue = info.2;
// FIXME (#28244): enforce that active features have issue numbers
// assert!(issue.is_some())
issue
} else {
// search in Accepted, Removed, or Stable Removed features
let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
.find(|t| t.0 == feature);
match found {
Some(&(_, _, issue, _)) => issue,
None => panic!("Feature `{}` is not declared anywhere", feature),
}
}
}
pub enum GateIssue {
Language,
Library(Option<u32>)
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum GateStrength {
/// A hard error. (Most feature gates should use this.)
Hard,
/// Only a warning. (Use this only as backwards-compatibility demands.)
Soft,
}
2019-04-10 18:40:12 -05:00
pub fn emit_feature_err(
sess: &ParseSess,
feature: Symbol,
2019-04-10 18:40:12 -05:00
span: Span,
issue: GateIssue,
explain: &str,
) {
2016-10-04 12:10:33 -05:00
feature_err(sess, feature, span, issue, explain).emit();
}
2019-05-09 16:08:55 -05:00
pub fn feature_err<'a, S: Into<MultiSpan>>(
2019-04-10 18:40:12 -05:00
sess: &'a ParseSess,
feature: Symbol,
2019-05-09 16:08:55 -05:00
span: S,
2019-04-10 18:40:12 -05:00
issue: GateIssue,
explain: &str,
) -> DiagnosticBuilder<'a> {
leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
}
2019-05-09 16:08:55 -05:00
fn leveled_feature_err<'a, S: Into<MultiSpan>>(
2019-04-10 18:40:12 -05:00
sess: &'a ParseSess,
feature: Symbol,
2019-05-09 16:08:55 -05:00
span: S,
2019-04-10 18:40:12 -05:00
issue: GateIssue,
explain: &str,
level: GateStrength,
) -> DiagnosticBuilder<'a> {
2016-09-24 11:42:54 -05:00
let diag = &sess.span_diagnostic;
let issue = match issue {
GateIssue::Language => find_lang_feature_issue(feature),
GateIssue::Library(lib) => lib,
};
let mut err = match level {
GateStrength::Hard => {
2019-04-10 18:40:12 -05:00
diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
}
2019-04-10 18:40:12 -05:00
GateStrength::Soft => diag.struct_span_warn(span, explain),
2015-12-20 15:00:43 -06:00
};
2019-04-10 18:40:12 -05:00
match issue {
2019-04-11 13:42:06 -05:00
None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
2019-04-10 18:40:12 -05:00
Some(n) => {
2019-04-11 13:42:06 -05:00
err.note(&format!(
"for more information, see https://github.com/rust-lang/rust/issues/{}",
n,
));
2019-04-10 18:40:12 -05:00
}
}
// #23973: do not suggest `#![feature(...)]` if we are in beta/stable
2016-09-24 12:28:46 -05:00
if sess.unstable_features.is_nightly_build() {
err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
2015-12-20 15:00:43 -06:00
}
2016-09-24 12:28:46 -05:00
// If we're on stable and only emitting a "soft" warning, add a note to
// clarify that the feature isn't "on" (rather than being on but
// warning-worthy).
if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
err.help("a nightly build of the compiler is required to enable this feature");
}
2016-10-04 12:10:33 -05:00
err
}
const EXPLAIN_BOX_SYNTAX: &str =
2019-04-10 18:40:12 -05:00
"box expression syntax is experimental; you can call `Box::new` instead";
2016-04-09 11:01:14 -05:00
pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
2019-04-10 18:40:12 -05:00
"attributes on expressions are experimental";
2016-04-09 11:01:14 -05:00
pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
"allow_internal_unstable side-steps feature gating and stability checks";
pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
"allow_internal_unsafe side-steps the unsafe_code lint";
pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
2018-06-25 21:29:13 -05:00
"unsized tuple coercion is not stable enough for use and is subject to change";
struct PostExpansionVisitor<'a> {
2015-09-28 19:46:01 -05:00
context: &'a Context<'a>,
builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
}
macro_rules! gate_feature_post {
($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
let (cx, span) = ($cx, $span);
if !span.allows_unstable(sym::$feature) {
gate_feature!(cx.context, $feature, span, $explain)
}
}};
($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
let (cx, span) = ($cx, $span);
if !span.allows_unstable(sym::$feature) {
gate_feature!(cx.context, $feature, span, $explain, $level)
}
}}
}
impl<'a> PostExpansionVisitor<'a> {
fn check_abi(&self, abi: Abi, span: Span) {
match abi {
Abi::RustIntrinsic => {
gate_feature_post!(&self, intrinsics, span,
"intrinsics are subject to change");
},
Abi::PlatformIntrinsic => {
gate_feature_post!(&self, platform_intrinsics, span,
"platform intrinsics are experimental and possibly buggy");
},
Abi::Vectorcall => {
gate_feature_post!(&self, abi_vectorcall, span,
"vectorcall is experimental and subject to change");
},
Abi::Thiscall => {
gate_feature_post!(&self, abi_thiscall, span,
"thiscall is experimental and subject to change");
},
Abi::RustCall => {
gate_feature_post!(&self, unboxed_closures, span,
"rust-call ABI is subject to change");
},
Abi::PtxKernel => {
gate_feature_post!(&self, abi_ptx, span,
"PTX ABIs are experimental and subject to change");
},
Abi::Unadjusted => {
gate_feature_post!(&self, abi_unadjusted, span,
"unadjusted ABI is an implementation detail and perma-unstable");
},
Abi::Msp430Interrupt => {
gate_feature_post!(&self, abi_msp430_interrupt, span,
"msp430-interrupt ABI is experimental and subject to change");
},
Abi::X86Interrupt => {
gate_feature_post!(&self, abi_x86_interrupt, span,
"x86-interrupt ABI is experimental and subject to change");
},
Abi::AmdGpuKernel => {
gate_feature_post!(&self, abi_amdgpu_kernel, span,
"amdgpu-kernel ABI is experimental and subject to change");
},
// Stable
Abi::Cdecl |
Abi::Stdcall |
Abi::Fastcall |
Abi::Aapcs |
Abi::Win64 |
2017-12-05 18:19:35 -06:00
Abi::SysV64 |
Abi::Rust |
Abi::C |
Abi::System => {}
}
}
}
impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
fn visit_attribute(&mut self, attr: &ast::Attribute) {
let attr_info = attr.ident().and_then(|ident| {
self.builtin_attributes.get(&ident.name).map(|a| *a)
});
2019-03-21 13:40:00 -05:00
// Check for gated attributes.
self.context.check_attribute(attr, attr_info, false);
if attr.check_name(sym::doc) {
if let Some(content) = attr.meta_item_list() {
if content.len() == 1 && content[0].check_name(sym::cfg) {
gate_feature_post!(&self, doc_cfg, attr.span,
"`#[doc(cfg(...))]` is experimental"
);
} else if content.iter().any(|c| c.check_name(sym::masked)) {
2017-08-21 20:20:21 -05:00
gate_feature_post!(&self, doc_masked, attr.span,
"`#[doc(masked)]` is experimental"
2017-08-21 20:20:21 -05:00
);
} else if content.iter().any(|c| c.check_name(sym::spotlight)) {
gate_feature_post!(&self, doc_spotlight, attr.span,
"`#[doc(spotlight)]` is experimental"
);
} else if content.iter().any(|c| c.check_name(sym::alias)) {
2018-04-19 10:46:13 -05:00
gate_feature_post!(&self, doc_alias, attr.span,
"`#[doc(alias = \"...\")]` is experimental"
2018-04-19 10:46:13 -05:00
);
} else if content.iter().any(|c| c.check_name(sym::keyword)) {
2018-06-02 17:45:49 -05:00
gate_feature_post!(&self, doc_keyword, attr.span,
"`#[doc(keyword = \"...\")]` is experimental"
2018-06-02 17:45:49 -05:00
);
}
}
}
match attr_info {
// `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
Some(&(name, _, template, _)) if name != sym::rustc_dummy =>
check_builtin_attribute(self.context.parse_sess, attr, name, template),
_ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
if token == token::Eq {
// All key-value attributes are restricted to meta-item syntax.
attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
}
}
}
}
fn visit_name(&mut self, sp: Span, name: ast::Name) {
if !name.as_str().is_ascii() {
2019-04-10 18:40:12 -05:00
gate_feature_post!(
&self,
non_ascii_idents,
self.context.parse_sess.source_map().def_span(sp),
"non-ascii idents are not fully supported"
);
}
}
fn visit_item(&mut self, i: &'a ast::Item) {
match i.node {
ast::ItemKind::ForeignMod(ref foreign_module) => {
self.check_abi(foreign_module.abi, i.span);
Add generation of static libraries to rustc This commit implements the support necessary for generating both intermediate and result static rust libraries. This is an implementation of my thoughts in https://mail.mozilla.org/pipermail/rust-dev/2013-November/006686.html. When compiling a library, we still retain the "lib" option, although now there are "rlib", "staticlib", and "dylib" as options for crate_type (and these are stackable). The idea of "lib" is to generate the "compiler default" instead of having too choose (although all are interchangeable). For now I have left the "complier default" to be a dynamic library for size reasons. Of the rust libraries, lib{std,extra,rustuv} will bootstrap with an rlib/dylib pair, but lib{rustc,syntax,rustdoc,rustpkg} will only be built as a dynamic object. I chose this for size reasons, but also because you're probably not going to be embedding the rustc compiler anywhere any time soon. Other than the options outlined above, there are a few defaults/preferences that are now opinionated in the compiler: * If both a .dylib and .rlib are found for a rust library, the compiler will prefer the .rlib variant. This is overridable via the -Z prefer-dynamic option * If generating a "lib", the compiler will generate a dynamic library. This is overridable by explicitly saying what flavor you'd like (rlib, staticlib, dylib). * If no options are passed to the command line, and no crate_type is found in the destination crate, then an executable is generated With this change, you can successfully build a rust program with 0 dynamic dependencies on rust libraries. There is still a dynamic dependency on librustrt, but I plan on removing that in a subsequent commit. This change includes no tests just yet. Our current testing infrastructure/harnesses aren't very amenable to doing flavorful things with linking, so I'm planning on adding a new mode of testing which I believe belongs as a separate commit. Closes #552
2013-11-15 16:03:29 -06:00
}
ast::ItemKind::Fn(..) => {
if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
gate_feature_post!(&self, plugin_registrar, i.span,
"compiler plugins are experimental and possibly buggy");
2013-12-25 12:10:33 -06:00
}
if attr::contains_name(&i.attrs[..], sym::start) {
gate_feature_post!(&self, start, i.span,
"a `#[start]` function is an experimental \
feature whose signature may change \
over time");
}
if attr::contains_name(&i.attrs[..], sym::main) {
gate_feature_post!(&self, main, i.span,
"declaration of a non-standard `#[main]` \
function may change over time, for now \
a top-level `fn main()` is required");
}
2013-12-25 12:10:33 -06:00
}
ast::ItemKind::Struct(..) => {
for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(sym::simd) {
gate_feature_post!(&self, repr_simd, attr.span,
"SIMD types are experimental and possibly buggy");
}
}
}
}
2019-05-09 16:08:55 -05:00
ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => {
for variant in variants {
2019-08-13 19:40:21 -05:00
match (&variant.data, &variant.disr_expr) {
2019-05-09 16:08:55 -05:00
(ast::VariantData::Unit(..), _) => {},
(_, Some(disr_expr)) =>
gate_feature_post!(
&self,
arbitrary_enum_discriminant,
disr_expr.value.span,
"discriminants on non-unit variants are experimental"),
_ => {},
}
}
let has_feature = self.context.features.arbitrary_enum_discriminant;
if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
Parser::maybe_report_invalid_custom_discriminants(
self.context.parse_sess,
&variants,
);
}
}
ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
if polarity == ast::ImplPolarity::Negative {
gate_feature_post!(&self, optin_builtin_traits,
i.span,
"negative trait bounds are not yet fully implemented; \
use marker types for now");
}
if let ast::Defaultness::Default = defaultness {
gate_feature_post!(&self, specialization,
i.span,
"specialization is unstable");
}
}
ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
gate_feature_post!(&self, optin_builtin_traits,
i.span,
"auto traits are experimental and possibly buggy");
}
ast::ItemKind::TraitAlias(..) => {
gate_feature_post!(
&self,
trait_alias,
i.span,
"trait aliases are experimental"
);
}
ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
let msg = "`macro` is experimental";
gate_feature_post!(&self, decl_macro, i.span, msg);
}
2019-07-31 18:41:54 -05:00
ast::ItemKind::OpaqueTy(..) => {
2018-07-03 12:38:14 -05:00
gate_feature_post!(
&self,
type_alias_impl_trait,
2018-07-03 12:38:14 -05:00
i.span,
2019-07-31 18:41:54 -05:00
"`impl Trait` in type aliases is unstable"
2018-07-03 12:38:14 -05:00
);
}
_ => {}
}
visit::walk_item(self, i);
}
fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2017-09-03 13:53:58 -05:00
match i.node {
ast::ForeignItemKind::Fn(..) |
ast::ForeignItemKind::Static(..) => {
let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2017-09-03 13:53:58 -05:00
let links_to_llvm = match link_name {
Some(val) => val.as_str().starts_with("llvm."),
_ => false
};
if links_to_llvm {
gate_feature_post!(&self, link_llvm_intrinsics, i.span,
"linking to LLVM intrinsics is experimental");
}
}
ast::ForeignItemKind::Ty => {
gate_feature_post!(&self, extern_types, i.span,
"extern types are experimental");
}
ast::ForeignItemKind::Macro(..) => {}
}
visit::walk_foreign_item(self, i)
}
fn visit_ty(&mut self, ty: &'a ast::Ty) {
match ty.node {
ast::TyKind::BareFn(ref bare_fn_ty) => {
self.check_abi(bare_fn_ty.abi, ty.span);
}
ast::TyKind::Never => {
gate_feature_post!(&self, never_type, ty.span,
"The `!` type is experimental");
}
_ => {}
}
visit::walk_ty(self, ty)
}
fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
if let ast::TyKind::Never = output_ty.node {
2019-03-21 13:40:00 -05:00
// Do nothing.
} else {
self.visit_ty(output_ty)
}
}
}
fn visit_expr(&mut self, e: &'a ast::Expr) {
match e.node {
ast::ExprKind::Box(_) => {
gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
}
ast::ExprKind::Type(..) => {
// To avoid noise about type ascription in common syntax errors, only emit if it
// is the *only* error.
if self.context.parse_sess.span_diagnostic.err_count() == 0 {
gate_feature_post!(&self, type_ascription, e.span,
"type ascription is experimental");
}
}
ast::ExprKind::TryBlock(_) => {
gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
}
2018-05-12 04:33:33 -05:00
ast::ExprKind::Block(_, opt_label) => {
if let Some(label) = opt_label {
gate_feature_post!(&self, label_break_value, label.ident.span,
"labels on blocks are unstable");
}
}
_ => {}
}
2019-03-21 13:40:00 -05:00
visit::walk_expr(self, e)
}
2017-08-26 17:09:31 -05:00
fn visit_arm(&mut self, arm: &'a ast::Arm) {
2017-09-01 14:39:46 -05:00
visit::walk_arm(self, arm)
2017-08-26 17:09:31 -05:00
}
fn visit_pat(&mut self, pattern: &'a ast::Pat) {
match &pattern.node {
PatKind::Slice(pats) => {
for pat in &*pats {
let span = pat.span;
let inner_pat = match &pat.node {
PatKind::Ident(.., Some(pat)) => pat,
_ => pat,
};
if inner_pat.is_rest() {
gate_feature_post!(
&self,
slice_patterns,
span,
"subslice patterns are unstable"
);
}
}
}
2016-02-11 12:16:33 -06:00
PatKind::Box(..) => {
gate_feature_post!(&self, box_patterns,
pattern.span,
"box pattern syntax is experimental");
}
PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
"exclusive range pattern syntax is experimental");
}
_ => {}
}
visit::walk_pat(self, pattern)
}
fn visit_fn(&mut self,
fn_kind: FnKind<'a>,
fn_decl: &'a ast::FnDecl,
span: Span,
_node_id: NodeId) {
2019-04-18 13:15:43 -05:00
if let Some(header) = fn_kind.header() {
// Stability of const fn methods are covered in
// `visit_trait_item` and `visit_impl_item` below; this is
// because default methods don't pass through this point.
self.check_abi(header.abi, span);
}
2019-04-18 13:15:43 -05:00
if fn_decl.c_variadic {
gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
}
2019-04-18 13:15:43 -05:00
2019-03-21 13:40:00 -05:00
visit::walk_fn(self, fn_kind, fn_decl, span)
}
2015-03-26 14:06:26 -05:00
fn visit_generic_param(&mut self, param: &'a GenericParam) {
2019-03-21 13:40:00 -05:00
match param.kind {
GenericParamKind::Const { .. } =>
gate_feature_post!(&self, const_generics, param.ident.span,
"const generics are unstable"),
_ => {}
}
visit::walk_generic_param(self, param)
}
fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
match constraint.kind {
AssocTyConstraintKind::Bound { .. } =>
gate_feature_post!(&self, associated_type_bounds, constraint.span,
"associated type bounds are unstable"),
_ => {}
}
2019-03-21 13:40:00 -05:00
visit::walk_assoc_ty_constraint(self, constraint)
}
fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2015-03-26 14:06:26 -05:00
match ti.node {
ast::TraitItemKind::Method(ref sig, ref block) => {
if block.is_none() {
self.check_abi(sig.header.abi, ti.span);
}
2019-02-24 16:40:11 -06:00
if sig.decl.c_variadic {
gate_feature_post!(&self, c_variadic, ti.span,
2019-04-18 14:36:32 -05:00
"C-variadic functions are unstable");
2019-02-24 16:40:11 -06:00
}
if sig.header.constness.node == ast::Constness::Const {
gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
}
}
ast::TraitItemKind::Type(_, ref default) => {
// We use three if statements instead of something like match guards so that all
// of these errors can be emitted if all cases apply.
if default.is_some() {
gate_feature_post!(&self, associated_type_defaults, ti.span,
"associated type defaults are unstable");
}
if !ti.generics.params.is_empty() {
gate_feature_post!(&self, generic_associated_types, ti.span,
"generic associated types are unstable");
}
if !ti.generics.where_clause.predicates.is_empty() {
gate_feature_post!(&self, generic_associated_types, ti.span,
"where clauses on associated types are unstable");
}
2017-11-09 20:40:14 -06:00
}
2015-03-26 14:06:26 -05:00
_ => {}
}
2019-03-21 13:40:00 -05:00
visit::walk_trait_item(self, ti)
2015-03-26 14:06:26 -05:00
}
fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2015-12-30 17:16:43 -06:00
if ii.defaultness == ast::Defaultness::Default {
gate_feature_post!(&self, specialization,
2015-12-30 17:16:43 -06:00
ii.span,
"specialization is unstable");
}
2015-03-26 14:06:26 -05:00
match ii.node {
2018-10-05 03:17:16 -05:00
ast::ImplItemKind::Method(..) => {}
2019-07-31 18:41:54 -05:00
ast::ImplItemKind::OpaqueTy(..) => {
2018-07-03 12:38:14 -05:00
gate_feature_post!(
&self,
type_alias_impl_trait,
2018-07-03 12:38:14 -05:00
ii.span,
2019-07-31 18:41:54 -05:00
"`impl Trait` in type aliases is unstable"
2018-07-03 12:38:14 -05:00
);
}
ast::ImplItemKind::TyAlias(_) => {
if !ii.generics.params.is_empty() {
gate_feature_post!(&self, generic_associated_types, ii.span,
"generic associated types are unstable");
}
if !ii.generics.where_clause.predicates.is_empty() {
gate_feature_post!(&self, generic_associated_types, ii.span,
"where clauses on associated types are unstable");
}
2017-11-09 20:40:14 -06:00
}
2015-03-26 14:06:26 -05:00
_ => {}
}
2019-03-21 13:40:00 -05:00
visit::walk_impl_item(self, ii)
2015-03-26 14:06:26 -05:00
}
2016-04-10 18:33:36 -05:00
fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2018-01-28 23:12:09 -06:00
if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
gate_feature_post!(&self, crate_visibility_modifier, vis.span,
"`crate` visibility modifier is experimental");
}
2019-03-21 13:40:00 -05:00
visit::walk_vis(self, vis)
}
}
pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2019-03-13 18:29:24 -05:00
crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
if let Some(reason) = reason {
err.span_note(span, reason);
} else {
err.span_label(span, "feature has been removed");
}
err.emit();
2018-03-21 17:48:56 -05:00
}
let mut features = Features::new();
let mut edition_enabled_features = FxHashMap::default();
for &edition in ALL_EDITIONS {
if edition <= crate_edition {
// The `crate_edition` implies its respective umbrella feature-gate
// (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
edition_enabled_features.insert(edition.feature_name(), edition);
}
}
for &(name, .., f_edition, set) in ACTIVE_FEATURES {
if let Some(f_edition) = f_edition {
if f_edition <= crate_edition {
set(&mut features, DUMMY_SP);
edition_enabled_features.insert(name, crate_edition);
}
2018-05-04 13:18:33 -05:00
}
}
// Process the edition umbrella feature-gates first, to ensure
// `edition_enabled_features` is completed before it's queried.
2016-06-10 20:37:24 -05:00
for attr in krate_attrs {
if !attr.check_name(sym::feature) {
continue
}
let list = match attr.meta_item_list() {
Some(list) => list,
None => continue,
};
for mi in list {
if !mi.is_word() {
continue;
}
let name = mi.name_or_empty();
if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
if *edition <= crate_edition {
continue;
}
for &(name, .., f_edition, set) in ACTIVE_FEATURES {
if let Some(f_edition) = f_edition {
if f_edition <= *edition {
// FIXME(Manishearth) there is currently no way to set
// lib features by edition
set(&mut features, DUMMY_SP);
edition_enabled_features.insert(name, *edition);
}
}
}
}
}
}
for attr in krate_attrs {
if !attr.check_name(sym::feature) {
continue
}
let list = match attr.meta_item_list() {
Some(list) => list,
None => continue,
};
let bad_input = |span| {
struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
};
for mi in list {
let name = match mi.ident() {
Some(ident) if mi.is_word() => ident.name,
Some(ident) => {
bad_input(mi.span()).span_suggestion(
mi.span(),
"expected just one word",
format!("{}", ident.name),
Applicability::MaybeIncorrect,
).emit();
continue
}
None => {
bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
continue
}
};
if let Some(edition) = edition_enabled_features.get(&name) {
struct_span_warn!(
span_handler,
mi.span(),
E0705,
"the feature `{}` is included in the Rust {} edition",
name,
edition,
).emit();
continue;
}
if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
// Handled in the separate loop above.
continue;
}
let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
if let Some((.., reason)) = removed.or(stable_removed) {
feature_removed(span_handler, mi.span(), *reason);
continue;
}
2018-07-22 20:03:01 -05:00
if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
let since = Some(Symbol::intern(since));
features.declared_lang_features.push((name, mi.span(), since));
continue;
}
if let Some(allowed) = allow_features.as_ref() {
if allowed.iter().find(|f| *f == name.as_str()).is_none() {
span_err!(span_handler, mi.span(), E0725,
"the feature `{}` is not in the list of allowed features",
name);
continue;
}
}
if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
set(&mut features, mi.span());
features.declared_lang_features.push((name, mi.span(), None));
continue;
}
features.declared_lib_features.push((name, mi.span()));
}
}
features
}
2016-06-10 20:37:24 -05:00
pub fn check_crate(krate: &ast::Crate,
sess: &ParseSess,
features: &Features,
plugin_attributes: &[(Symbol, AttributeType)],
2016-06-10 20:37:24 -05:00
unstable: UnstableFeatures) {
maybe_stage_features(&sess.span_diagnostic, krate, unstable);
let ctx = Context {
features,
2016-09-24 11:42:54 -05:00
parse_sess: sess,
plugin_attributes,
2016-06-10 20:37:24 -05:00
};
macro_rules! gate_all {
($gate:ident, $msg:literal) => { gate_all!($gate, $gate, $msg); };
($spans:ident, $gate:ident, $msg:literal) => {
for span in &*sess.gated_spans.$spans.borrow() {
gate_feature!(&ctx, $gate, *span, $msg);
}
}
}
gate_all!(param_attrs, "attributes on function parameters are unstable");
gate_all!(let_chains, "`let` expressions in this position are experimental");
gate_all!(async_closure, "async closures are unstable");
gate_all!(yields, generators, "yield syntax is experimental");
gate_all!(or_patterns, "or-patterns syntax is experimental");
2019-08-13 22:44:32 -05:00
let visitor = &mut PostExpansionVisitor {
context: &ctx,
builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
};
2017-11-27 20:14:24 -06:00
visit::walk_crate(visitor, krate);
}
#[derive(Clone, Copy, Hash)]
pub enum UnstableFeatures {
2019-02-08 07:53:55 -06:00
/// Hard errors for unstable features are active, as on beta/stable channels.
Disallow,
2016-10-25 22:14:46 -05:00
/// Allow features to be activated, as on nightly.
Allow,
/// Errors are bypassed for bootstrapping. This is required any time
/// during the build that feature-related lints are set to warn or above
/// because the build turns on warnings-as-errors and uses lots of unstable
/// features. As a result, this is always required for building Rust itself.
Cheat
}
2016-09-24 12:04:07 -05:00
impl UnstableFeatures {
pub fn from_environment() -> UnstableFeatures {
// Whether this is a feature-staged build, i.e., on the beta or stable channel
2016-09-24 12:04:07 -05:00
let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
// Whether we should enable unstable features for bootstrapping
let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
match (disable_unstable_features, bootstrap) {
(_, true) => UnstableFeatures::Cheat,
(true, _) => UnstableFeatures::Disallow,
(false, _) => UnstableFeatures::Allow
2016-09-24 12:04:07 -05:00
}
}
pub fn is_nightly_build(&self) -> bool {
match *self {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
_ => false,
}
}
2016-09-24 12:04:07 -05:00
}
fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
unstable: UnstableFeatures) {
let allow_features = match unstable {
UnstableFeatures::Allow => true,
UnstableFeatures::Disallow => false,
UnstableFeatures::Cheat => true
};
if !allow_features {
for attr in &krate.attrs {
if attr.check_name(sym::feature) {
let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2016-06-29 10:23:51 -05:00
span_err!(span_handler, attr.span, E0554,
"`#![feature]` may not be used on the {} release channel",
2016-06-28 12:40:40 -05:00
release_channel);
}
}
}
}