3 //! This module implements the gating necessary for preventing certain compiler
4 //! features from being used by default. This module will crawl a pre-expanded
5 //! AST to ensure that there are no features which are used that are not
8 //! Features are enabled in programs via the crate-level attributes of
9 //! `#![feature(...)]` with a comma-separated list of features.
11 //! For the purpose of future feature-tracking, once code for detection of feature
12 //! gate usage is added, *do not remove it again* even once the feature
18 use crate::ast::{self, NodeId, GenericParam, GenericParamKind, PatKind, RangeEnd};
20 use crate::early_buffered_lints::BufferedEarlyLintId;
21 use crate::source_map::Spanned;
22 use crate::edition::{ALL_EDITIONS, Edition};
23 use crate::visit::{self, FnKind, Visitor};
24 use crate::parse::{token, ParseSess};
25 use crate::symbol::{Symbol, kw, sym};
26 use crate::tokenstream::TokenTree;
28 use errors::{DiagnosticBuilder, Handler};
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_target::spec::abi::Abi;
31 use syntax_pos::{Span, DUMMY_SP};
33 use lazy_static::lazy_static;
39 fn f(features: &mut Features, _: Span) {
40 features.$field = true;
42 f as fn(&mut Features, Span)
46 macro_rules! declare_features {
47 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
48 /// Represents active features that are currently being implemented or
49 /// currently being considered for addition/removal.
50 const ACTIVE_FEATURES:
51 &[(Symbol, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
52 &[$((sym::$feature, $ver, $issue, $edition, set!($feature))),+];
54 /// A set of features to be used by later passes.
57 /// `#![feature]` attrs for language features, for error reporting
58 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
59 /// `#![feature]` attrs for non-language (library) features
60 pub declared_lib_features: Vec<(Symbol, Span)>,
61 $(pub $feature: bool),+
65 pub fn new() -> Features {
67 declared_lang_features: Vec::new(),
68 declared_lib_features: Vec::new(),
73 pub fn walk_feature_fields<F>(&self, mut f: F)
74 where F: FnMut(&str, bool)
76 $(f(stringify!($feature), self.$feature);)+
81 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
82 /// Represents unstable features which have since been removed (it was once Active)
83 const REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
84 $((sym::$feature, $ver, $issue, $reason)),+
88 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
89 /// Represents stable features which have since been removed (it was once Accepted)
90 const STABLE_REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
91 $((sym::$feature, $ver, $issue, None)),+
95 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
96 /// Those language feature has since been Accepted (it was once Active)
97 const ACCEPTED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
98 $((sym::$feature, $ver, $issue, None)),+
103 // If you change this, please modify `src/doc/unstable-book` as well.
105 // Don't ever remove anything from this list; set them to 'Removed'.
107 // The version numbers here correspond to the version in which the current status
108 // was set. This is most important for knowing when a particular feature became
111 // Note that the features are grouped into internal/user-facing and then
112 // sorted by version inside those groups. This is inforced with tidy.
114 // N.B., `tools/tidy/src/features.rs` parses this information directly out of the
115 // source, so take care when modifying it.
118 // -------------------------------------------------------------------------
119 // feature-group-start: internal feature gates
120 // -------------------------------------------------------------------------
122 // no-tracking-issue-start
124 // Allows using the `rust-intrinsic`'s "ABI".
125 (active, intrinsics, "1.0.0", None, None),
127 // Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
128 (active, lang_items, "1.0.0", None, None),
130 // Allows using the `#[stable]` and `#[unstable]` attributes.
131 (active, staged_api, "1.0.0", None, None),
133 // Allows using `#[allow_internal_unstable]`. This is an
134 // attribute on `macro_rules!` and can't use the attribute handling
135 // below (it has to be checked before expansion possibly makes
136 // macros disappear).
137 (active, allow_internal_unstable, "1.0.0", None, None),
139 // Allows using `#[allow_internal_unsafe]`. This is an
140 // attribute on `macro_rules!` and can't use the attribute handling
141 // below (it has to be checked before expansion possibly makes
142 // macros disappear).
143 (active, allow_internal_unsafe, "1.0.0", None, None),
145 // Allows using the macros:
146 // + `__diagnostic_used`
147 // + `__register_diagnostic`
148 // +`__build_diagnostic_array`
149 (active, rustc_diagnostic_macros, "1.0.0", None, None),
151 // Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
152 // lets a function to be `const` when opted into with `#![feature(foo)]`.
153 (active, rustc_const_unstable, "1.0.0", None, None),
155 // no-tracking-issue-end
157 // Allows using `#[link_name="llvm.*"]`.
158 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
160 // Allows using `rustc_*` attributes (RFC 572).
161 (active, rustc_attrs, "1.0.0", Some(29642), None),
163 // Allows using `#[on_unimplemented(..)]` on traits.
164 (active, on_unimplemented, "1.0.0", Some(29628), None),
166 // Allows using the `box $expr` syntax.
167 (active, box_syntax, "1.0.0", Some(49733), None),
169 // Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
170 (active, main, "1.0.0", Some(29634), None),
172 // Allows using `#[start]` on a function indicating that it is the program entrypoint.
173 (active, start, "1.0.0", Some(29633), None),
175 // Allows using the `#[fundamental]` attribute.
176 (active, fundamental, "1.0.0", Some(29635), None),
178 // Allows using the `rust-call` ABI.
179 (active, unboxed_closures, "1.0.0", Some(29625), None),
181 // Allows using the `#[linkage = ".."]` attribute.
182 (active, linkage, "1.0.0", Some(29603), None),
184 // Allows features specific to OIBIT (auto traits).
185 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
187 // Allows using `box` in patterns (RFC 469).
188 (active, box_patterns, "1.0.0", Some(29641), None),
190 // no-tracking-issue-start
192 // Allows using `#[prelude_import]` on glob `use` items.
193 (active, prelude_import, "1.2.0", None, None),
195 // no-tracking-issue-end
197 // Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238).
198 (active, dropck_parametricity, "1.3.0", Some(28498), None),
200 // no-tracking-issue-start
202 // Allows using `#[omit_gdb_pretty_printer_section]`.
203 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
205 // Allows using the `vectorcall` ABI.
206 (active, abi_vectorcall, "1.7.0", None, None),
208 // no-tracking-issue-end
210 // Allows using `#[structural_match]` which indicates that a type is structurally matchable.
211 (active, structural_match, "1.8.0", Some(31434), None),
213 // Allows using the `may_dangle` attribute (RFC 1327).
214 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
216 // Allows using the `#![panic_runtime]` attribute.
217 (active, panic_runtime, "1.10.0", Some(32837), None),
219 // Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed.
220 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
222 // no-tracking-issue-start
224 // Allows identifying the `compiler_builtins` crate.
225 (active, compiler_builtins, "1.13.0", None, None),
227 // Allows using the `unadjusted` ABI; perma-unstable.
228 (active, abi_unadjusted, "1.16.0", None, None),
230 // Allows identifying crates that contain sanitizer runtimes.
231 (active, sanitizer_runtime, "1.17.0", None, None),
233 // Used to identify crates that contain the profiler runtime.
234 (active, profiler_runtime, "1.18.0", None, None),
236 // Allows using the `thiscall` ABI.
237 (active, abi_thiscall, "1.19.0", None, None),
239 // Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`.
240 (active, allocator_internals, "1.20.0", None, None),
242 // Allows using the `format_args_nl` macro.
243 (active, format_args_nl, "1.29.0", None, None),
245 // no-tracking-issue-end
247 // Added for testing E0705; perma-unstable.
248 (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
250 // -------------------------------------------------------------------------
251 // feature-group-end: internal feature gates
252 // -------------------------------------------------------------------------
254 // -------------------------------------------------------------------------
255 // feature-group-start: actual feature gates (target features)
256 // -------------------------------------------------------------------------
258 // FIXME: Document these and merge with the list below.
260 // Unstable `#[target_feature]` directives.
261 (active, arm_target_feature, "1.27.0", Some(44839), None),
262 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
263 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
264 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
265 (active, mips_target_feature, "1.27.0", Some(44839), None),
266 (active, avx512_target_feature, "1.27.0", Some(44839), None),
267 (active, mmx_target_feature, "1.27.0", Some(44839), None),
268 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
269 (active, tbm_target_feature, "1.27.0", Some(44839), None),
270 (active, wasm_target_feature, "1.30.0", Some(44839), None),
271 (active, adx_target_feature, "1.32.0", Some(44839), None),
272 (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
273 (active, movbe_target_feature, "1.34.0", Some(44839), None),
274 (active, rtm_target_feature, "1.35.0", Some(44839), None),
275 (active, f16c_target_feature, "1.36.0", Some(44839), None),
277 // -------------------------------------------------------------------------
278 // feature-group-end: actual feature gates (target features)
279 // -------------------------------------------------------------------------
281 // -------------------------------------------------------------------------
282 // feature-group-start: actual feature gates
283 // -------------------------------------------------------------------------
285 // Allows using `asm!` macro with which inline assembly can be embedded.
286 (active, asm, "1.0.0", Some(29722), None),
288 // Allows using the `concat_idents!` macro with which identifiers can be concatenated.
289 (active, concat_idents, "1.0.0", Some(29599), None),
291 // Allows using the `#[link_args]` attribute.
292 (active, link_args, "1.0.0", Some(29596), None),
294 // Allows defining identifiers beyond ASCII.
295 (active, non_ascii_idents, "1.0.0", Some(55467), None),
297 // Allows using `#[plugin_registrar]` on functions.
298 (active, plugin_registrar, "1.0.0", Some(29597), None),
300 // Allows using `#![plugin(myplugin)]`.
301 (active, plugin, "1.0.0", Some(29597), None),
303 // Allows using `#[thread_local]` on `static` items.
304 (active, thread_local, "1.0.0", Some(29594), None),
306 // Allows using the `log_syntax!` macro.
307 (active, log_syntax, "1.0.0", Some(29598), None),
309 // Allows using the `trace_macros!` macro.
310 (active, trace_macros, "1.0.0", Some(29598), None),
312 // Allows the use of SIMD types in functions declared in `extern` blocks.
313 (active, simd_ffi, "1.0.0", Some(27731), None),
315 // Allows using custom attributes (RFC 572).
316 (active, custom_attribute, "1.0.0", Some(29642), None),
318 // Allows using non lexical lifetimes (RFC 2094).
319 (active, nll, "1.0.0", Some(43234), None),
321 // Allows using slice patterns.
322 (active, slice_patterns, "1.0.0", Some(23121), None),
324 // Allows the definition of `const` functions with some advanced features.
325 (active, const_fn, "1.2.0", Some(57563), None),
327 // Allows associated type defaults.
328 (active, associated_type_defaults, "1.2.0", Some(29661), None),
330 // Allows `#![no_core]`.
331 (active, no_core, "1.3.0", Some(29639), None),
333 // Allows default type parameters to influence type inference.
334 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
336 // Allows `repr(simd)` and importing the various simd intrinsics.
337 (active, repr_simd, "1.4.0", Some(27731), None),
339 // Allows `extern "platform-intrinsic" { ... }`.
340 (active, platform_intrinsics, "1.4.0", Some(27731), None),
342 // Allows `#[unwind(..)]`.
344 // Permits specifying whether a function should permit unwinding or abort on unwind.
345 (active, unwind_attributes, "1.4.0", Some(58760), None),
347 // Allows `#[no_debug]`.
348 (active, no_debug, "1.5.0", Some(29721), None),
350 // Allows attributes on expressions and non-item statements.
351 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
353 // Allows the use of type ascription in expressions.
354 (active, type_ascription, "1.6.0", Some(23416), None),
356 // Allows `cfg(target_thread_local)`.
357 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
359 // Allows specialization of implementations (RFC 1210).
360 (active, specialization, "1.7.0", Some(31844), None),
362 // Allows using `#[naked]` on functions.
363 (active, naked_functions, "1.9.0", Some(32408), None),
365 // Allows `cfg(target_has_atomic = "...")`.
366 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
368 // Allows `X..Y` patterns.
369 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
371 // Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more.
372 (active, never_type, "1.13.0", Some(35121), None),
374 // Allows exhaustive pattern matching on types that contain uninhabited types.
375 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
377 // Allows untagged unions `union U { ... }`.
378 (active, untagged_unions, "1.13.0", Some(32836), None),
380 // Allows `#[link(..., cfg(..))]`.
381 (active, link_cfg, "1.14.0", Some(37406), None),
383 // Allows `extern "ptx-*" fn()`.
384 (active, abi_ptx, "1.15.0", Some(38788), None),
386 // Allows the `#[repr(i128)]` attribute for enums.
387 (active, repr128, "1.16.0", Some(35118), None),
389 // Allows `#[link(kind="static-nobundle"...)]`.
390 (active, static_nobundle, "1.16.0", Some(37403), None),
392 // Allows `extern "msp430-interrupt" fn()`.
393 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
395 // Allows declarative macros 2.0 (`macro`).
396 (active, decl_macro, "1.17.0", Some(39412), None),
398 // Allows `extern "x86-interrupt" fn()`.
399 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
401 // Allows module-level inline assembly by way of `global_asm!()`.
402 (active, global_asm, "1.18.0", Some(35119), None),
404 // Allows overlapping impls of marker traits.
405 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
407 // Allows a test to fail without failing the whole suite.
408 (active, allow_fail, "1.19.0", Some(46488), None),
410 // Allows unsized tuple coercion.
411 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
413 // Allows defining generators.
414 (active, generators, "1.21.0", Some(43122), None),
416 // Allows `#[doc(cfg(...))]`.
417 (active, doc_cfg, "1.21.0", Some(43781), None),
419 // Allows `#[doc(masked)]`.
420 (active, doc_masked, "1.21.0", Some(44027), None),
422 // Allows `#[doc(spotlight)]`.
423 (active, doc_spotlight, "1.22.0", Some(45040), None),
425 // Allows `#[doc(include = "some-file")]`.
426 (active, external_doc, "1.22.0", Some(44732), None),
428 // Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008).
429 (active, non_exhaustive, "1.22.0", Some(44109), None),
431 // Allows using `crate` as visibility modifier, synonymous with `pub(crate)`.
432 (active, crate_visibility_modifier, "1.23.0", Some(53120), None),
434 // Allows defining `extern type`s.
435 (active, extern_types, "1.23.0", Some(43467), None),
437 // Allows trait methods with arbitrary self types.
438 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
440 // Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
441 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
443 // Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598).
444 (active, generic_associated_types, "1.23.0", Some(44265), None),
446 // Allows defining `trait X = A + B;` alias items.
447 (active, trait_alias, "1.24.0", Some(41517), None),
449 // Allows infering `'static` outlives requirements (RFC 2093).
450 (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
452 // Allows macro invocations in `extern {}` blocks.
453 (active, macros_in_extern, "1.27.0", Some(49476), None),
455 // Allows accessing fields of unions inside `const` functions.
456 (active, const_fn_union, "1.27.0", Some(51909), None),
458 // Allows casting raw pointers to `usize` during const eval.
459 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
461 // Allows dereferencing raw pointers during const eval.
462 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
464 // Allows comparing raw pointers during const eval.
465 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
467 // Allows `#[doc(alias = "...")]`.
468 (active, doc_alias, "1.27.0", Some(50146), None),
470 // Allows defining `existential type`s.
471 (active, existential_type, "1.28.0", Some(34511), None),
473 // Allows inconsistent bounds in where clauses.
474 (active, trivial_bounds, "1.28.0", Some(48214), None),
476 // Allows `'a: { break 'a; }`.
477 (active, label_break_value, "1.28.0", Some(48594), None),
479 // Allows using `#[doc(keyword = "...")]`.
480 (active, doc_keyword, "1.28.0", Some(51315), None),
482 // Allows async and await syntax.
483 (active, async_await, "1.28.0", Some(50547), None),
485 // Allows await! macro-like syntax.
486 // This will likely be removed prior to stabilization of async/await.
487 (active, await_macro, "1.28.0", Some(50547), None),
489 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
490 (active, const_transmute, "1.29.0", Some(53605), None),
492 // Allows using `try {...}` expressions.
493 (active, try_blocks, "1.29.0", Some(31436), None),
495 // Allows defining an `#[alloc_error_handler]`.
496 (active, alloc_error_handler, "1.29.0", Some(51540), None),
498 // Allows using the `amdgpu-kernel` ABI.
499 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
501 // Allows panicking during const eval (producing compile-time errors).
502 (active, const_panic, "1.30.0", Some(51999), None),
504 // Allows `#[marker]` on certain traits allowing overlapping implementations.
505 (active, marker_trait_attr, "1.30.0", Some(29864), None),
507 // Allows macro invocations on modules expressions and statements and
508 // procedural macros to expand to non-items.
509 (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
511 // Allows unsized rvalues at arguments and parameters.
512 (active, unsized_locals, "1.30.0", Some(48055), None),
514 // Allows custom test frameworks with `#![test_runner]` and `#[test_case]`.
515 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
517 // Allows non-builtin attributes in inner attribute position.
518 (active, custom_inner_attributes, "1.30.0", Some(54726), None),
520 // Allows mixing bind-by-move in patterns and references to those identifiers in guards.
521 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
523 // Allows `impl Trait` in bindings (`let`, `const`, `static`).
524 (active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
526 // Allows `const _: TYPE = VALUE`.
527 (active, underscore_const_names, "1.31.0", Some(54912), None),
529 // Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
530 (active, lint_reasons, "1.31.0", Some(54503), None),
532 // Allows paths to enum variants on type aliases.
533 (active, type_alias_enum_variants, "1.31.0", Some(49683), None),
535 // Allows exhaustive integer pattern matching on `usize` and `isize`.
536 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
538 // Allows relaxing the coherence rules such that
539 // `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
540 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
542 // Allows using `#[ffi_returns_twice]` on foreign functions.
543 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
545 // Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
546 (active, const_generics, "1.34.0", Some(44580), None),
548 // Allows using `#[optimize(X)]`.
549 (active, optimize_attribute, "1.34.0", Some(54882), None),
551 // Allows using C-variadics.
552 (active, c_variadic, "1.34.0", Some(44930), None),
554 // -------------------------------------------------------------------------
555 // feature-group-end: actual feature gates
556 // -------------------------------------------------------------------------
559 // Some features are known to be incomplete and using them is likely to have
560 // unanticipated results, such as compiler crashes. We warn the user about these
562 const INCOMPLETE_FEATURES: &[Symbol] = &[
563 sym::impl_trait_in_bindings,
564 sym::generic_associated_types,
569 // -------------------------------------------------------------------------
570 // feature-group-start: removed features
571 // -------------------------------------------------------------------------
573 (removed, import_shadowing, "1.0.0", None, None, None),
574 (removed, managed_boxes, "1.0.0", None, None, None),
575 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
576 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
577 (removed, reflect, "1.0.0", Some(27749), None, None),
578 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
579 (removed, opt_out_copy, "1.0.0", None, None, None),
580 (removed, quad_precision_float, "1.0.0", None, None, None),
581 (removed, struct_inherit, "1.0.0", None, None, None),
582 (removed, test_removed_feature, "1.0.0", None, None, None),
583 (removed, visible_private_types, "1.0.0", None, None, None),
584 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
585 // Allows using items which are missing stability attributes
586 (removed, unmarked_api, "1.0.0", None, None, None),
587 (removed, allocator, "1.0.0", None, None, None),
588 (removed, simd, "1.0.0", Some(27731), None,
589 Some("removed in favor of `#[repr(simd)]`")),
590 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
591 Some("merged into `#![feature(slice_patterns)]`")),
592 (removed, macro_reexport, "1.0.0", Some(29638), None,
593 Some("subsumed by `pub use`")),
594 (removed, pushpop_unsafe, "1.2.0", None, None, None),
595 (removed, needs_allocator, "1.4.0", Some(27389), None,
596 Some("subsumed by `#![feature(allocator_internals)]`")),
597 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
598 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
599 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
600 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
601 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
602 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
603 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
604 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
605 (removed, panic_implementation, "1.28.0", Some(44489), None,
606 Some("subsumed by `#[panic_handler]`")),
607 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
608 (removed, custom_derive, "1.32.0", Some(29644), None,
609 Some("subsumed by `#[proc_macro_derive]`")),
610 // Paths of the form: `extern::foo::bar`
611 (removed, extern_in_paths, "1.33.0", Some(55600), None,
612 Some("subsumed by `::foo::bar` paths")),
613 (removed, quote, "1.33.0", Some(29601), None, None),
615 // -------------------------------------------------------------------------
616 // feature-group-end: removed features
617 // -------------------------------------------------------------------------
621 (stable_removed, no_stack_check, "1.0.0", None, None),
625 // -------------------------------------------------------------------------
626 // feature-group-start: for testing purposes
627 // -------------------------------------------------------------------------
629 // A temporary feature gate used to enable parser extensions needed
630 // to bootstrap fix for #5723.
631 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
632 // These are used to test this portion of the compiler,
633 // they don't actually mean anything.
634 (accepted, test_accepted_feature, "1.0.0", None, None),
636 // -------------------------------------------------------------------------
637 // feature-group-end: for testing purposes
638 // -------------------------------------------------------------------------
640 // -------------------------------------------------------------------------
641 // feature-group-start: accepted features
642 // -------------------------------------------------------------------------
644 // Allows using associated `type`s in `trait`s.
645 (accepted, associated_types, "1.0.0", None, None),
646 // Allows using assigning a default type to type parameters in algebraic data type definitions.
647 (accepted, default_type_params, "1.0.0", None, None),
648 // FIXME: explain `globs`.
649 (accepted, globs, "1.0.0", None, None),
650 // Allows `macro_rules!` items.
651 (accepted, macro_rules, "1.0.0", None, None),
652 // Allows use of `&foo[a..b]` as a slicing syntax.
653 (accepted, slicing_syntax, "1.0.0", None, None),
654 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
655 (accepted, struct_variant, "1.0.0", None, None),
656 // Allows indexing tuples.
657 (accepted, tuple_indexing, "1.0.0", None, None),
658 // Allows the use of `if let` expressions.
659 (accepted, if_let, "1.0.0", None, None),
660 // Allows the use of `while let` expressions.
661 (accepted, while_let, "1.0.0", None, None),
662 // Allows using `#![no_std]`.
663 (accepted, no_std, "1.6.0", None, None),
664 // Allows overloading augmented assignment operations like `a += b`.
665 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
666 // Allows empty structs and enum variants with braces.
667 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
668 // Allows `#[deprecated]` attribute.
669 (accepted, deprecated, "1.9.0", Some(29935), None),
670 // Allows macros to appear in the type position.
671 (accepted, type_macros, "1.13.0", Some(27245), None),
672 // Allows use of the postfix `?` operator in expressions.
673 (accepted, question_mark, "1.13.0", Some(31436), None),
674 // Allows `..` in tuple (struct) patterns.
675 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
676 // Allows some increased flexibility in the name resolution rules,
677 // especially around globs and shadowing (RFC 1560).
678 (accepted, item_like_imports, "1.15.0", Some(35120), None),
679 // Allows using `Self` and associated types in struct expressions and patterns.
680 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
681 // Allows elision of `'static` lifetimes in `static`s and `const`s.
682 (accepted, static_in_const, "1.17.0", Some(35897), None),
683 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
684 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
685 // Allows the definition recursive static items.
686 (accepted, static_recursion, "1.17.0", Some(29719), None),
687 // Allows `pub(restricted)` visibilities (RFC 1422).
688 (accepted, pub_restricted, "1.18.0", Some(32409), None),
689 // Allows `#![windows_subsystem]`.
690 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
691 // Allows `break {expr}` with a value inside `loop`s.
692 (accepted, loop_break_value, "1.19.0", Some(37339), None),
693 // Allows numeric fields in struct expressions and patterns.
694 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
695 // Allows coercing non capturing closures to function pointers.
696 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
697 // Allows attributes on struct literal fields.
698 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
699 // Allows the definition of associated constants in `trait` or `impl` blocks.
700 (accepted, associated_consts, "1.20.0", Some(29646), None),
701 // Allows usage of the `compile_error!` macro.
702 (accepted, compile_error, "1.20.0", Some(40872), None),
703 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
704 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
705 // Allows `Drop` types in constants (RFC 1440).
706 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
707 // Allows the sysV64 ABI to be specified on all platforms
708 // instead of just the platforms on which it is the C ABI.
709 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
710 // Allows `repr(align(16))` struct attribute (RFC 1358).
711 (accepted, repr_align, "1.25.0", Some(33626), None),
712 // Allows '|' at beginning of match arms (RFC 1925).
713 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
714 // Allows nested groups in `use` items (RFC 2128).
715 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
716 // Allows indexing into constant arrays.
717 (accepted, const_indexing, "1.26.0", Some(29947), None),
718 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
719 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
720 // Allows `..=` in patterns (RFC 1192).
721 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
722 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
723 (accepted, termination_trait, "1.26.0", Some(43301), None),
724 // Allows implementing `Clone` for closures where possible (RFC 2132).
725 (accepted, clone_closures, "1.26.0", Some(44490), None),
726 // Allows implementing `Copy` for closures where possible (RFC 2132).
727 (accepted, copy_closures, "1.26.0", Some(44490), None),
728 // Allows `impl Trait` in function arguments.
729 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
730 // Allows `impl Trait` in function return types.
731 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
732 // Allows using the `u128` and `i128` types.
733 (accepted, i128_type, "1.26.0", Some(35118), None),
734 // Allows default match binding modes (RFC 2005).
735 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
736 // Allows `'_` placeholder lifetimes.
737 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
738 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
739 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
740 // Allows `cfg(target_feature = "...")`.
741 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
742 // Allows `#[target_feature(...)]`.
743 (accepted, target_feature, "1.27.0", None, None),
744 // Allows using `dyn Trait` as a syntax for trait objects.
745 (accepted, dyn_trait, "1.27.0", Some(44662), None),
746 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
747 (accepted, fn_must_use, "1.27.0", Some(43302), None),
748 // Allows use of the `:lifetime` macro fragment specifier.
749 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
750 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
751 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
752 // Allows the `#[global_allocator]` attribute.
753 (accepted, global_allocator, "1.28.0", Some(27389), None),
754 // Allows `#[repr(transparent)]` attribute on newtype structs.
755 (accepted, repr_transparent, "1.28.0", Some(43036), None),
756 // Allows procedural macros in `proc-macro` crates.
757 (accepted, proc_macro, "1.29.0", Some(38356), None),
758 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
759 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
760 // Allows use of the `:vis` macro fragment specifier
761 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
762 // Allows importing and reexporting macros with `use`,
763 // enables macro modularization in general.
764 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
765 // Allows keywords to be escaped for use as identifiers.
766 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
767 // Allows attributes scoped to tools.
768 (accepted, tool_attributes, "1.30.0", Some(44690), None),
769 // Allows multi-segment paths in attributes and derives.
770 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
771 // Allows all literals in attribute lists and values of key-value pairs.
772 (accepted, attr_literals, "1.30.0", Some(34981), None),
773 // Allows inferring outlives requirements (RFC 2093).
774 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
775 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
776 // This defines the behavior of panics.
777 (accepted, panic_handler, "1.30.0", Some(44489), None),
778 // Allows `#[used]` to preserve symbols (see llvm.used).
779 (accepted, used, "1.30.0", Some(40289), None),
780 // Allows `crate` in paths.
781 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
782 // Allows resolving absolute paths as paths from other crates.
783 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
784 // Allows access to crate names passed via `--extern` through prelude.
785 (accepted, extern_prelude, "1.30.0", Some(44660), None),
786 // Allows parentheses in patterns.
787 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
788 // Allows the definition of `const fn` functions.
789 (accepted, min_const_fn, "1.31.0", Some(53555), None),
790 // Allows scoped lints.
791 (accepted, tool_lints, "1.31.0", Some(44690), None),
792 // Allows lifetime elision in `impl` headers. For example:
793 // + `impl<I:Iterator> Iterator for &mut Iterator`
794 // + `impl Debug for Foo<'_>`
795 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
796 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
797 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
798 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
799 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
800 // Allows use of `?` as the Kleene "at most one" operator in macros.
801 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
802 // Allows `Self` struct constructor (RFC 2302).
803 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
804 // Allows `Self` in type definitions (RFC 2300).
805 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
806 // Allows `use x::y;` to search `x` in the current scope.
807 (accepted, uniform_paths, "1.32.0", Some(53130), None),
808 // Allows integer match exhaustiveness checking (RFC 2591).
809 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
810 // Allows `use path as _;` and `extern crate c as _;`.
811 (accepted, underscore_imports, "1.33.0", Some(48216), None),
812 // Allows `#[repr(packed(N))]` attribute on structs.
813 (accepted, repr_packed, "1.33.0", Some(33158), None),
814 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
815 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
816 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
817 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
818 // Allows let bindings, assignments and destructuring in `const` functions and constants.
819 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
820 // at the same time as let bindings.
821 (accepted, const_let, "1.33.0", Some(48821), None),
822 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
823 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
824 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
825 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
826 // Allows `cfg(target_vendor = "...")`.
827 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
828 // Allows `extern crate self as foo;`.
829 // This puts local crate root into extern prelude under name `foo`.
830 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
831 // Allows arbitrary delimited token streams in non-macro attributes.
832 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
833 // Allows using `#[repr(align(X))]` on enums with equivalent semantics
834 // to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
835 (accepted, repr_align_enum, "1.37.0", Some(57996), None),
837 // -------------------------------------------------------------------------
838 // feature-group-end: accepted features
839 // -------------------------------------------------------------------------
842 // If you change this, please modify `src/doc/unstable-book` as well. You must
843 // move that documentation into the relevant place in the other docs, and
844 // remove the chapter on the flag.
846 #[derive(Copy, Clone, PartialEq, Debug)]
847 pub enum AttributeType {
848 /// Normal, builtin attribute that is consumed
849 /// by the compiler before the unused_attribute check
852 /// Builtin attribute that may not be consumed by the compiler
853 /// before the unused_attribute check. These attributes
854 /// will be ignored by the unused_attribute lint
857 /// Builtin attribute that is only allowed at the crate level
861 pub enum AttributeGate {
862 /// Is gated by a given feature gate, reason
863 /// and function to check if enabled
864 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
866 /// Ungated attribute, can be used on all release channels
870 /// A template that the attribute input must match.
871 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
872 #[derive(Clone, Copy)]
873 pub struct AttributeTemplate {
875 list: Option<&'static str>,
876 name_value_str: Option<&'static str>,
879 impl AttributeTemplate {
880 /// Checks that the given meta-item is compatible with this template.
881 fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
882 match meta_item_kind {
883 ast::MetaItemKind::Word => self.word,
884 ast::MetaItemKind::List(..) => self.list.is_some(),
885 ast::MetaItemKind::NameValue(lit) if lit.node.is_str() => self.name_value_str.is_some(),
886 ast::MetaItemKind::NameValue(..) => false,
891 /// A convenience macro for constructing attribute templates.
892 /// E.g., `template!(Word, List: "description")` means that the attribute
893 /// supports forms `#[attr]` and `#[attr(description)]`.
894 macro_rules! template {
895 (Word) => { template!(@ true, None, None) };
896 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
897 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
898 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
899 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
900 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
901 template!(@ false, Some($descr1), Some($descr2))
903 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
904 template!(@ true, Some($descr1), Some($descr2))
906 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
907 word: $word, list: $list, name_value_str: $name_value_str
912 fn is_deprecated(&self) -> bool {
914 Gated(Stability::Deprecated(_, _), ..) => true,
920 #[derive(Copy, Clone, Debug)]
923 // First argument is tracking issue link; second argument is an optional
924 // help message, which defaults to "remove this attribute"
925 Deprecated(&'static str, Option<&'static str>),
929 impl std::fmt::Debug for AttributeGate {
930 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 Gated(ref stab, name, expl, _) =>
933 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
934 Ungated => write!(fmt, "Ungated")
939 macro_rules! cfg_fn {
940 ($field: ident) => {{
941 fn f(features: &Features) -> bool {
944 f as fn(&Features) -> bool
948 pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
949 AttributeTemplate, AttributeGate)> {
950 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
953 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
954 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
957 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
958 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
961 /// Attributes that have a special meaning to rustc or rustdoc
962 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
968 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
974 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
980 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
986 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
990 (sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
991 (sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
992 (sym::plugin_registrar, Normal, template!(Word), Ungated),
994 (sym::cfg, Normal, template!(List: "predicate"), Ungated),
995 (sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
996 (sym::main, Normal, template!(Word), Ungated),
997 (sym::start, Normal, template!(Word), Ungated),
998 (sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
999 (sym::path, Normal, template!(NameValueStr: "file"), Ungated),
1000 (sym::automatically_derived, Normal, template!(Word), Ungated),
1001 (sym::no_mangle, Whitelisted, template!(Word), Ungated),
1002 (sym::no_link, Normal, template!(Word), Ungated),
1003 (sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
1007 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
1010 (sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
1011 (sym::no_implicit_prelude, Normal, template!(Word), Ungated),
1012 (sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
1013 (sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
1015 "the `link_args` attribute is experimental and not \
1016 portable across platforms, it is recommended to \
1017 use `#[link(name = \"foo\")] instead",
1018 cfg_fn!(link_args))),
1019 (sym::macro_escape, Normal, template!(Word), Ungated),
1022 (sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
1023 sym::structural_match,
1024 "the semantics of constant patterns is \
1026 cfg_fn!(structural_match))),
1029 (sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
1030 sym::non_exhaustive,
1031 "non exhaustive is an experimental feature",
1032 cfg_fn!(non_exhaustive))),
1035 (sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
1036 sym::marker_trait_attr,
1037 "marker traits is an experimental feature",
1038 cfg_fn!(marker_trait_attr))),
1040 (sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
1042 "compiler plugins are experimental \
1043 and possibly buggy",
1046 (sym::no_std, CrateLevel, template!(Word), Ungated),
1047 (sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
1049 "no_core is experimental",
1051 (sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
1053 "language items are subject to change",
1054 cfg_fn!(lang_items))),
1055 (sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
1056 Gated(Stability::Unstable,
1058 "the `linkage` attribute is experimental \
1059 and not portable across platforms",
1061 (sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
1063 "`#[thread_local]` is an experimental feature, and does \
1064 not currently handle destructors",
1065 cfg_fn!(thread_local))),
1067 (sym::rustc_on_unimplemented, Whitelisted, template!(List:
1068 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
1069 NameValueStr: "message"),
1070 Gated(Stability::Unstable,
1071 sym::on_unimplemented,
1072 "the `#[rustc_on_unimplemented]` attribute \
1073 is an experimental feature",
1074 cfg_fn!(on_unimplemented))),
1075 (sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
1076 Gated(Stability::Unstable,
1077 sym::rustc_const_unstable,
1078 "the `#[rustc_const_unstable]` attribute \
1079 is an internal feature",
1080 cfg_fn!(rustc_const_unstable))),
1081 (sym::global_allocator, Normal, template!(Word), Ungated),
1082 (sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1083 sym::allocator_internals,
1084 "the `#[default_lib_allocator]` \
1085 attribute is an experimental feature",
1086 cfg_fn!(allocator_internals))),
1087 (sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
1088 sym::allocator_internals,
1089 "the `#[needs_allocator]` \
1090 attribute is an experimental \
1092 cfg_fn!(allocator_internals))),
1093 (sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1095 "the `#[panic_runtime]` attribute is \
1096 an experimental feature",
1097 cfg_fn!(panic_runtime))),
1098 (sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1099 sym::needs_panic_runtime,
1100 "the `#[needs_panic_runtime]` \
1101 attribute is an experimental \
1103 cfg_fn!(needs_panic_runtime))),
1104 (sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
1106 "the `#[rustc_outlives]` attribute \
1107 is just used for rustc unit tests \
1108 and will never be stable",
1109 cfg_fn!(rustc_attrs))),
1110 (sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
1112 "the `#[rustc_variance]` attribute \
1113 is just used for rustc unit tests \
1114 and will never be stable",
1115 cfg_fn!(rustc_attrs))),
1116 (sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
1117 Gated(Stability::Unstable,
1119 "the `#[rustc_layout]` attribute \
1120 is just used for rustc unit tests \
1121 and will never be stable",
1122 cfg_fn!(rustc_attrs))),
1123 (sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
1124 Gated(Stability::Unstable,
1126 "the `#[rustc_layout_scalar_valid_range_start]` attribute \
1127 is just used to enable niche optimizations in libcore \
1128 and will never be stable",
1129 cfg_fn!(rustc_attrs))),
1130 (sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
1131 Gated(Stability::Unstable,
1133 "the `#[rustc_layout_scalar_valid_range_end]` attribute \
1134 is just used to enable niche optimizations in libcore \
1135 and will never be stable",
1136 cfg_fn!(rustc_attrs))),
1137 (sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
1138 Gated(Stability::Unstable,
1140 "the `#[rustc_nonnull_optimization_guaranteed]` attribute \
1141 is just used to enable niche optimizations in libcore \
1142 and will never be stable",
1143 cfg_fn!(rustc_attrs))),
1144 (sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
1146 "the `#[rustc_regions]` attribute \
1147 is just used for rustc unit tests \
1148 and will never be stable",
1149 cfg_fn!(rustc_attrs))),
1150 (sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
1152 "the `#[rustc_error]` attribute \
1153 is just used for rustc unit tests \
1154 and will never be stable",
1155 cfg_fn!(rustc_attrs))),
1156 (sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
1159 is just used for rustc unit tests \
1160 and will never be stable",
1161 cfg_fn!(rustc_attrs))),
1162 (sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
1163 Gated(Stability::Unstable,
1165 "the `#[rustc_if_this_changed]` attribute \
1166 is just used for rustc unit tests \
1167 and will never be stable",
1168 cfg_fn!(rustc_attrs))),
1169 (sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
1170 Gated(Stability::Unstable,
1172 "the `#[rustc_if_this_changed]` attribute \
1173 is just used for rustc unit tests \
1174 and will never be stable",
1175 cfg_fn!(rustc_attrs))),
1176 (sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1177 /*opt*/ except = "...""#),
1178 Gated(Stability::Unstable,
1180 "the `#[rustc_dirty]` attribute \
1181 is just used for rustc unit tests \
1182 and will never be stable",
1183 cfg_fn!(rustc_attrs))),
1184 (sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1185 /*opt*/ except = "...""#),
1186 Gated(Stability::Unstable,
1188 "the `#[rustc_clean]` attribute \
1189 is just used for rustc unit tests \
1190 and will never be stable",
1191 cfg_fn!(rustc_attrs))),
1193 sym::rustc_partition_reused,
1195 template!(List: r#"cfg = "...", module = "...""#),
1197 Stability::Unstable,
1200 is just used for rustc unit tests \
1201 and will never be stable",
1202 cfg_fn!(rustc_attrs)
1206 sym::rustc_partition_codegened,
1208 template!(List: r#"cfg = "...", module = "...""#),
1210 Stability::Unstable,
1213 is just used for rustc unit tests \
1214 and will never be stable",
1215 cfg_fn!(rustc_attrs),
1218 (sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
1220 Gated(Stability::Unstable,
1223 is just used for rustc unit tests \
1224 and will never be stable",
1225 cfg_fn!(rustc_attrs))),
1226 (sym::rustc_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
1229 is just used for rustc unit tests \
1230 and will never be stable",
1231 cfg_fn!(rustc_attrs))),
1232 (sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
1234 "internal rustc attributes will never be stable",
1235 cfg_fn!(rustc_attrs))),
1236 (sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
1238 "internal rustc attributes will never be stable",
1239 cfg_fn!(rustc_attrs))),
1240 (sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1242 "the `#[rustc_mir]` attribute \
1243 is just used for rustc unit tests \
1244 and will never be stable",
1245 cfg_fn!(rustc_attrs))),
1247 sym::rustc_inherit_overflow_checks,
1251 Stability::Unstable,
1253 "the `#[rustc_inherit_overflow_checks]` \
1254 attribute is just used to control \
1255 overflow checking behavior of several \
1256 libcore functions that are inlined \
1257 across crates and will never be stable",
1258 cfg_fn!(rustc_attrs),
1262 (sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1264 "the `#[rustc_dump_program_clauses]` \
1265 attribute is just used for rustc unit \
1266 tests and will never be stable",
1267 cfg_fn!(rustc_attrs))),
1268 (sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
1270 "the `#[rustc_test_marker]` attribute \
1271 is used internally to track tests",
1272 cfg_fn!(rustc_attrs))),
1273 (sym::rustc_transparent_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1275 "used internally for testing macro hygiene",
1276 cfg_fn!(rustc_attrs))),
1277 (sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
1278 sym::compiler_builtins,
1279 "the `#[compiler_builtins]` attribute is used to \
1280 identify the `compiler_builtins` crate which \
1281 contains compiler-rt intrinsics and will never be \
1283 cfg_fn!(compiler_builtins))),
1284 (sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1285 sym::sanitizer_runtime,
1286 "the `#[sanitizer_runtime]` attribute is used to \
1287 identify crates that contain the runtime of a \
1288 sanitizer and will never be stable",
1289 cfg_fn!(sanitizer_runtime))),
1290 (sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1291 sym::profiler_runtime,
1292 "the `#[profiler_runtime]` attribute is used to \
1293 identify the `profiler_builtins` crate which \
1294 contains the profiler runtime and will never be \
1296 cfg_fn!(profiler_runtime))),
1298 (sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
1299 Gated(Stability::Unstable,
1300 sym::allow_internal_unstable,
1301 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1302 cfg_fn!(allow_internal_unstable))),
1304 (sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
1305 sym::allow_internal_unsafe,
1306 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1307 cfg_fn!(allow_internal_unsafe))),
1309 (sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
1311 "the `#[fundamental]` attribute \
1312 is an experimental feature",
1313 cfg_fn!(fundamental))),
1315 (sym::proc_macro_derive, Normal, template!(List: "TraitName, \
1316 /*opt*/ attributes(name1, name2, ...)"),
1319 (sym::rustc_copy_clone_marker, Whitelisted, template!(Word), Gated(Stability::Unstable,
1321 "internal implementation detail",
1322 cfg_fn!(rustc_attrs))),
1324 // FIXME: #14408 whitelist docs since rustdoc looks at them
1328 template!(List: "hidden|inline|...", NameValueStr: "string"),
1332 // FIXME: #14406 these are processed in codegen, which happens after the
1334 (sym::cold, Whitelisted, template!(Word), Ungated),
1335 (sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
1336 sym::naked_functions,
1337 "the `#[naked]` attribute \
1338 is an experimental feature",
1339 cfg_fn!(naked_functions))),
1340 (sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
1341 sym::ffi_returns_twice,
1342 "the `#[ffi_returns_twice]` attribute \
1343 is an experimental feature",
1344 cfg_fn!(ffi_returns_twice))),
1345 (sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1346 (sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1347 (sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
1348 (sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1349 /*opt*/ cfg = "...""#), Ungated),
1350 (sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1351 (sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
1352 (sym::no_builtins, Whitelisted, template!(Word), Ungated),
1353 (sym::no_debug, Whitelisted, template!(Word), Gated(
1354 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1356 "the `#[no_debug]` attribute was an experimental feature that has been \
1357 deprecated due to lack of demand",
1358 cfg_fn!(no_debug))),
1360 sym::omit_gdb_pretty_printer_section,
1364 Stability::Unstable,
1365 sym::omit_gdb_pretty_printer_section,
1366 "the `#[omit_gdb_pretty_printer_section]` \
1367 attribute is just used for the Rust test \
1369 cfg_fn!(omit_gdb_pretty_printer_section)
1372 (sym::unsafe_destructor_blind_to_params,
1375 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1376 Some("replace this attribute with `#[may_dangle]`")),
1377 sym::dropck_parametricity,
1378 "unsafe_destructor_blind_to_params has been replaced by \
1379 may_dangle and will be removed in the future",
1380 cfg_fn!(dropck_parametricity))),
1384 Gated(Stability::Unstable,
1385 sym::dropck_eyepatch,
1386 "may_dangle has unstable semantics and may be removed in the future",
1387 cfg_fn!(dropck_eyepatch))),
1388 (sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1389 sym::unwind_attributes,
1390 "#[unwind] is experimental",
1391 cfg_fn!(unwind_attributes))),
1392 (sym::used, Whitelisted, template!(Word), Ungated),
1395 (sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
1396 sym::prelude_import,
1397 "`#[prelude_import]` is for use by rustc only",
1398 cfg_fn!(prelude_import))),
1400 // FIXME: #14407 these are only looked at on-demand so we can't
1401 // guarantee they'll have already been checked
1403 sym::rustc_deprecated,
1405 template!(List: r#"since = "version", reason = "...""#),
1408 (sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1412 template!(List: r#"feature = "name", since = "version""#),
1418 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1425 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason"#,
1426 NameValueStr: "reason"
1431 (sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
1432 sym::unboxed_closures,
1433 "unboxed_closures are still evolving",
1434 cfg_fn!(unboxed_closures))),
1436 (sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1438 (sym::proc_macro_attribute, Normal, template!(Word), Ungated),
1439 (sym::proc_macro, Normal, template!(Word), Ungated),
1441 (sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
1443 "used internally by rustc",
1444 cfg_fn!(rustc_attrs))),
1446 (sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
1448 "allow_fail attribute is currently unstable",
1449 cfg_fn!(allow_fail))),
1451 (sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
1453 "this is an internal attribute that will \
1455 cfg_fn!(rustc_attrs))),
1457 // whitelists "identity-like" conversion methods to suggest on type mismatch
1458 (sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
1460 "this is an internal attribute that will \
1462 cfg_fn!(rustc_attrs))),
1465 sym::rustc_args_required_const,
1467 template!(List: "N"),
1468 Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
1469 cfg_fn!(rustc_attrs))
1472 (sym::panic_handler, Normal, template!(Word), Ungated),
1474 (sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
1475 sym::alloc_error_handler,
1476 "#[alloc_error_handler] is an unstable feature",
1477 cfg_fn!(alloc_error_handler))),
1480 (sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1481 sym::optimize_attribute,
1482 "#[optimize] attribute is an unstable feature",
1483 cfg_fn!(optimize_attribute))),
1485 // Crate level attributes
1486 (sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
1487 (sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1488 (sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1489 (sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1490 (sym::no_start, CrateLevel, template!(Word), Ungated),
1491 (sym::no_main, CrateLevel, template!(Word), Ungated),
1492 (sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1493 (sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1494 (sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1495 sym::custom_test_frameworks,
1496 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1497 cfg_fn!(custom_test_frameworks))),
1500 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
1503 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
1504 let mut map = FxHashMap::default();
1505 for attr in BUILTIN_ATTRIBUTES.iter() {
1506 if map.insert(attr.0, attr).is_some() {
1507 panic!("duplicate builtin attribute `{}`", attr.0);
1514 // cfg(...)'s that are feature gated
1515 const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
1516 // (name in cfg, feature, function to check if the feature is enabled)
1517 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
1518 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
1519 (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
1523 pub struct GatedCfg {
1529 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1531 .position(|info| cfg.check_name(info.0))
1540 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1541 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1542 if !has_feature(features) && !self.span.allows_unstable(feature) {
1543 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1544 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1549 struct Context<'a> {
1550 features: &'a Features,
1551 parse_sess: &'a ParseSess,
1552 plugin_attributes: &'a [(Symbol, AttributeType)],
1555 macro_rules! gate_feature_fn {
1556 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1557 let (cx, has_feature, span,
1558 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1559 let has_feature: bool = has_feature(&$cx.features);
1560 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1561 if !has_feature && !span.allows_unstable($name) {
1562 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1568 macro_rules! gate_feature {
1569 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1570 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1571 sym::$feature, $explain, GateStrength::Hard)
1573 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1574 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1575 sym::$feature, $explain, $level)
1579 impl<'a> Context<'a> {
1582 attr: &ast::Attribute,
1583 attr_info: Option<&BuiltinAttribute>,
1586 debug!("check_attribute(attr = {:?})", attr);
1587 if let Some(&(name, ty, _template, ref gateage)) = attr_info {
1588 if let Gated(_, name, desc, ref has_feature) = *gateage {
1589 if !attr.span.allows_unstable(name) {
1591 self, has_feature, attr.span, name, desc, GateStrength::Hard
1594 } else if name == sym::doc {
1595 if let Some(content) = attr.meta_item_list() {
1596 if content.iter().any(|c| c.check_name(sym::include)) {
1597 gate_feature!(self, external_doc, attr.span,
1598 "#[doc(include = \"...\")] is experimental"
1603 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1606 for &(n, ty) in self.plugin_attributes {
1608 // Plugins can't gate attributes, so we don't check for it
1609 // unlike the code above; we only use this loop to
1610 // short-circuit to avoid the checks below.
1611 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1615 if !attr::is_known(attr) {
1616 if attr.name_or_empty().as_str().starts_with("rustc_") {
1617 let msg = "unless otherwise specified, attributes with the prefix `rustc_` \
1618 are reserved for internal compiler diagnostics";
1619 gate_feature!(self, rustc_attrs, attr.span, msg);
1620 } else if !is_macro {
1621 // Only run the custom attribute lint during regular feature gate
1622 // checking. Macro gating runs before the plugin attributes are
1623 // registered, so we skip this in that case.
1624 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1625 may have meaning added to it in the future", attr.path);
1626 gate_feature!(self, custom_attribute, attr.span, &msg);
1632 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1633 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1636 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
1641 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
1642 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1644 // FIXME (#28244): enforce that active features have issue numbers
1645 // assert!(issue.is_some())
1648 // search in Accepted, Removed, or Stable Removed features
1649 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1650 .find(|t| t.0 == feature);
1652 Some(&(_, _, issue, _)) => issue,
1653 None => panic!("Feature `{}` is not declared anywhere", feature),
1658 pub enum GateIssue {
1660 Library(Option<u32>)
1663 #[derive(Debug, Copy, Clone, PartialEq)]
1664 pub enum GateStrength {
1665 /// A hard error. (Most feature gates should use this.)
1667 /// Only a warning. (Use this only as backwards-compatibility demands.)
1671 pub fn emit_feature_err(
1678 feature_err(sess, feature, span, issue, explain).emit();
1681 pub fn feature_err<'a>(
1682 sess: &'a ParseSess,
1687 ) -> DiagnosticBuilder<'a> {
1688 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1691 fn leveled_feature_err<'a>(
1692 sess: &'a ParseSess,
1697 level: GateStrength,
1698 ) -> DiagnosticBuilder<'a> {
1699 let diag = &sess.span_diagnostic;
1701 let issue = match issue {
1702 GateIssue::Language => find_lang_feature_issue(feature),
1703 GateIssue::Library(lib) => lib,
1706 let mut err = match level {
1707 GateStrength::Hard => {
1708 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
1710 GateStrength::Soft => diag.struct_span_warn(span, explain),
1714 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
1717 "for more information, see https://github.com/rust-lang/rust/issues/{}",
1723 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1724 if sess.unstable_features.is_nightly_build() {
1725 err.help(&format!("add #![feature({})] to the crate attributes to enable", feature));
1728 // If we're on stable and only emitting a "soft" warning, add a note to
1729 // clarify that the feature isn't "on" (rather than being on but
1731 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1732 err.help("a nightly build of the compiler is required to enable this feature");
1739 const EXPLAIN_BOX_SYNTAX: &str =
1740 "box expression syntax is experimental; you can call `Box::new` instead";
1742 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1743 "attributes on expressions are experimental";
1745 pub const EXPLAIN_ASM: &str =
1746 "inline assembly is not stable enough for use and is subject to change";
1748 pub const EXPLAIN_GLOBAL_ASM: &str =
1749 "`global_asm!` is not stable enough for use and is subject to change";
1751 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str =
1752 "custom test frameworks are an unstable feature";
1754 pub const EXPLAIN_LOG_SYNTAX: &str =
1755 "`log_syntax!` is not stable enough for use and is subject to change";
1757 pub const EXPLAIN_CONCAT_IDENTS: &str =
1758 "`concat_idents` is not stable enough for use and is subject to change";
1760 pub const EXPLAIN_FORMAT_ARGS_NL: &str =
1761 "`format_args_nl` is only for internal language use and is subject to change";
1763 pub const EXPLAIN_TRACE_MACROS: &str =
1764 "`trace_macros` is not stable enough for use and is subject to change";
1765 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1766 "allow_internal_unstable side-steps feature gating and stability checks";
1767 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1768 "allow_internal_unsafe side-steps the unsafe_code lint";
1770 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1771 "unsized tuple coercion is not stable enough for use and is subject to change";
1773 struct PostExpansionVisitor<'a> {
1774 context: &'a Context<'a>,
1775 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
1778 macro_rules! gate_feature_post {
1779 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1780 let (cx, span) = ($cx, $span);
1781 if !span.allows_unstable(sym::$feature) {
1782 gate_feature!(cx.context, $feature, span, $explain)
1785 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1786 let (cx, span) = ($cx, $span);
1787 if !span.allows_unstable(sym::$feature) {
1788 gate_feature!(cx.context, $feature, span, $explain, $level)
1793 impl<'a> PostExpansionVisitor<'a> {
1794 fn check_abi(&self, abi: Abi, span: Span) {
1796 Abi::RustIntrinsic => {
1797 gate_feature_post!(&self, intrinsics, span,
1798 "intrinsics are subject to change");
1800 Abi::PlatformIntrinsic => {
1801 gate_feature_post!(&self, platform_intrinsics, span,
1802 "platform intrinsics are experimental and possibly buggy");
1804 Abi::Vectorcall => {
1805 gate_feature_post!(&self, abi_vectorcall, span,
1806 "vectorcall is experimental and subject to change");
1809 gate_feature_post!(&self, abi_thiscall, span,
1810 "thiscall is experimental and subject to change");
1813 gate_feature_post!(&self, unboxed_closures, span,
1814 "rust-call ABI is subject to change");
1817 gate_feature_post!(&self, abi_ptx, span,
1818 "PTX ABIs are experimental and subject to change");
1820 Abi::Unadjusted => {
1821 gate_feature_post!(&self, abi_unadjusted, span,
1822 "unadjusted ABI is an implementation detail and perma-unstable");
1824 Abi::Msp430Interrupt => {
1825 gate_feature_post!(&self, abi_msp430_interrupt, span,
1826 "msp430-interrupt ABI is experimental and subject to change");
1828 Abi::X86Interrupt => {
1829 gate_feature_post!(&self, abi_x86_interrupt, span,
1830 "x86-interrupt ABI is experimental and subject to change");
1832 Abi::AmdGpuKernel => {
1833 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1834 "amdgpu-kernel ABI is experimental and subject to change");
1849 fn check_builtin_attribute(&mut self, attr: &ast::Attribute, name: Symbol,
1850 template: AttributeTemplate) {
1851 // Some special attributes like `cfg` must be checked
1852 // before the generic check, so we skip them here.
1853 let should_skip = |name| name == sym::cfg;
1854 // Some of previously accepted forms were used in practice,
1855 // report them as warnings for now.
1856 let should_warn = |name| name == sym::doc || name == sym::ignore ||
1857 name == sym::inline || name == sym::link;
1859 match attr.parse_meta(self.context.parse_sess) {
1860 Ok(meta) => if !should_skip(name) && !template.compatible(&meta.node) {
1861 let mut msg = "attribute must be of the form ".to_owned();
1862 let mut first = true;
1865 msg.push_str(&format!("`#[{}{}]`", name, ""));
1867 if let Some(descr) = template.list {
1869 msg.push_str(" or ");
1872 msg.push_str(&format!("`#[{}({})]`", name, descr));
1874 if let Some(descr) = template.name_value_str {
1876 msg.push_str(" or ");
1878 msg.push_str(&format!("`#[{} = \"{}\"]`", name, descr));
1880 if should_warn(name) {
1881 self.context.parse_sess.buffer_lint(
1882 BufferedEarlyLintId::IllFormedAttributeInput,
1888 self.context.parse_sess.span_diagnostic.span_err(meta.span, &msg);
1891 Err(mut err) => err.emit(),
1896 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1897 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1898 let attr_info = attr.ident().and_then(|ident| {
1899 self.builtin_attributes.get(&ident.name).map(|a| *a)
1902 // check for gated attributes
1903 self.context.check_attribute(attr, attr_info, false);
1905 if attr.check_name(sym::doc) {
1906 if let Some(content) = attr.meta_item_list() {
1907 if content.len() == 1 && content[0].check_name(sym::cfg) {
1908 gate_feature_post!(&self, doc_cfg, attr.span,
1909 "#[doc(cfg(...))] is experimental"
1911 } else if content.iter().any(|c| c.check_name(sym::masked)) {
1912 gate_feature_post!(&self, doc_masked, attr.span,
1913 "#[doc(masked)] is experimental"
1915 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
1916 gate_feature_post!(&self, doc_spotlight, attr.span,
1917 "#[doc(spotlight)] is experimental"
1919 } else if content.iter().any(|c| c.check_name(sym::alias)) {
1920 gate_feature_post!(&self, doc_alias, attr.span,
1921 "#[doc(alias = \"...\")] is experimental"
1923 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
1924 gate_feature_post!(&self, doc_keyword, attr.span,
1925 "#[doc(keyword = \"...\")] is experimental"
1932 Some(&(name, _, template, _)) => self.check_builtin_attribute(
1937 None => if let Some(TokenTree::Token(_, token::Eq)) = attr.tokens.trees().next() {
1938 // All key-value attributes are restricted to meta-item syntax.
1939 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
1944 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1945 if !name.as_str().is_ascii() {
1949 self.context.parse_sess.source_map().def_span(sp),
1950 "non-ascii idents are not fully supported"
1955 fn visit_item(&mut self, i: &'a ast::Item) {
1957 ast::ItemKind::Const(_,_) => {
1958 if i.ident.name == kw::Underscore {
1959 gate_feature_post!(&self, underscore_const_names, i.span,
1960 "naming constants with `_` is unstable");
1964 ast::ItemKind::ForeignMod(ref foreign_module) => {
1965 self.check_abi(foreign_module.abi, i.span);
1968 ast::ItemKind::Fn(..) => {
1969 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
1970 gate_feature_post!(&self, plugin_registrar, i.span,
1971 "compiler plugins are experimental and possibly buggy");
1973 if attr::contains_name(&i.attrs[..], sym::start) {
1974 gate_feature_post!(&self, start, i.span,
1975 "a #[start] function is an experimental \
1976 feature whose signature may change \
1979 if attr::contains_name(&i.attrs[..], sym::main) {
1980 gate_feature_post!(&self, main, i.span,
1981 "declaration of a nonstandard #[main] \
1982 function may change over time, for now \
1983 a top-level `fn main()` is required");
1987 ast::ItemKind::Struct(..) => {
1988 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
1989 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1990 if item.check_name(sym::simd) {
1991 gate_feature_post!(&self, repr_simd, attr.span,
1992 "SIMD types are experimental and possibly buggy");
1998 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
1999 if polarity == ast::ImplPolarity::Negative {
2000 gate_feature_post!(&self, optin_builtin_traits,
2002 "negative trait bounds are not yet fully implemented; \
2003 use marker types for now");
2006 if let ast::Defaultness::Default = defaultness {
2007 gate_feature_post!(&self, specialization,
2009 "specialization is unstable");
2013 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2014 gate_feature_post!(&self, optin_builtin_traits,
2016 "auto traits are experimental and possibly buggy");
2019 ast::ItemKind::TraitAlias(..) => {
2024 "trait aliases are experimental"
2028 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2029 let msg = "`macro` is experimental";
2030 gate_feature_post!(&self, decl_macro, i.span, msg);
2033 ast::ItemKind::Existential(..) => {
2038 "existential types are unstable"
2045 visit::walk_item(self, i);
2048 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2050 ast::ForeignItemKind::Fn(..) |
2051 ast::ForeignItemKind::Static(..) => {
2052 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2053 let links_to_llvm = match link_name {
2054 Some(val) => val.as_str().starts_with("llvm."),
2058 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2059 "linking to LLVM intrinsics is experimental");
2062 ast::ForeignItemKind::Ty => {
2063 gate_feature_post!(&self, extern_types, i.span,
2064 "extern types are experimental");
2066 ast::ForeignItemKind::Macro(..) => {}
2069 visit::walk_foreign_item(self, i)
2072 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2074 ast::TyKind::BareFn(ref bare_fn_ty) => {
2075 self.check_abi(bare_fn_ty.abi, ty.span);
2077 ast::TyKind::Never => {
2078 gate_feature_post!(&self, never_type, ty.span,
2079 "The `!` type is experimental");
2083 visit::walk_ty(self, ty)
2086 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2087 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2088 if let ast::TyKind::Never = output_ty.node {
2091 self.visit_ty(output_ty)
2096 fn visit_expr(&mut self, e: &'a ast::Expr) {
2098 ast::ExprKind::Box(_) => {
2099 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2101 ast::ExprKind::Type(..) => {
2102 // To avoid noise about type ascription in common syntax errors, only emit if it
2103 // is the *only* error.
2104 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2105 gate_feature_post!(&self, type_ascription, e.span,
2106 "type ascription is experimental");
2109 ast::ExprKind::Yield(..) => {
2110 gate_feature_post!(&self, generators,
2112 "yield syntax is experimental");
2114 ast::ExprKind::TryBlock(_) => {
2115 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2117 ast::ExprKind::Block(_, opt_label) => {
2118 if let Some(label) = opt_label {
2119 gate_feature_post!(&self, label_break_value, label.ident.span,
2120 "labels on blocks are unstable");
2123 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
2124 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
2126 ast::ExprKind::Async(..) => {
2127 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2129 ast::ExprKind::Await(origin, _) => {
2131 ast::AwaitOrigin::FieldLike =>
2132 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2133 ast::AwaitOrigin::MacroLike =>
2138 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2139 in favor of `<expr>.await` syntax."
2145 visit::walk_expr(self, e);
2148 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2149 visit::walk_arm(self, arm)
2152 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2153 match pattern.node {
2154 PatKind::Slice(_, Some(ref subslice), _) => {
2155 gate_feature_post!(&self, slice_patterns,
2157 "syntax for subslices in slice patterns is not yet stabilized");
2159 PatKind::Box(..) => {
2160 gate_feature_post!(&self, box_patterns,
2162 "box pattern syntax is experimental");
2164 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2165 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2166 "exclusive range pattern syntax is experimental");
2170 visit::walk_pat(self, pattern)
2173 fn visit_fn(&mut self,
2174 fn_kind: FnKind<'a>,
2175 fn_decl: &'a ast::FnDecl,
2178 if let Some(header) = fn_kind.header() {
2179 // Check for const fn and async fn declarations.
2180 if header.asyncness.node.is_async() {
2181 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2184 // Stability of const fn methods are covered in
2185 // `visit_trait_item` and `visit_impl_item` below; this is
2186 // because default methods don't pass through this point.
2187 self.check_abi(header.abi, span);
2190 if fn_decl.c_variadic {
2191 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2194 visit::walk_fn(self, fn_kind, fn_decl, span);
2197 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2198 if let GenericParamKind::Const { .. } = param.kind {
2199 gate_feature_post!(&self, const_generics, param.ident.span,
2200 "const generics are unstable");
2202 visit::walk_generic_param(self, param);
2205 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2207 ast::TraitItemKind::Method(ref sig, ref block) => {
2208 if block.is_none() {
2209 self.check_abi(sig.header.abi, ti.span);
2211 if sig.header.asyncness.node.is_async() {
2212 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2214 if sig.decl.c_variadic {
2215 gate_feature_post!(&self, c_variadic, ti.span,
2216 "C-variadic functions are unstable");
2218 if sig.header.constness.node == ast::Constness::Const {
2219 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2222 ast::TraitItemKind::Type(_, ref default) => {
2223 // We use three if statements instead of something like match guards so that all
2224 // of these errors can be emitted if all cases apply.
2225 if default.is_some() {
2226 gate_feature_post!(&self, associated_type_defaults, ti.span,
2227 "associated type defaults are unstable");
2229 if !ti.generics.params.is_empty() {
2230 gate_feature_post!(&self, generic_associated_types, ti.span,
2231 "generic associated types are unstable");
2233 if !ti.generics.where_clause.predicates.is_empty() {
2234 gate_feature_post!(&self, generic_associated_types, ti.span,
2235 "where clauses on associated types are unstable");
2240 visit::walk_trait_item(self, ti);
2243 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2244 if ii.defaultness == ast::Defaultness::Default {
2245 gate_feature_post!(&self, specialization,
2247 "specialization is unstable");
2251 ast::ImplItemKind::Method(..) => {}
2252 ast::ImplItemKind::Existential(..) => {
2257 "existential types are unstable"
2260 ast::ImplItemKind::Type(_) => {
2261 if !ii.generics.params.is_empty() {
2262 gate_feature_post!(&self, generic_associated_types, ii.span,
2263 "generic associated types are unstable");
2265 if !ii.generics.where_clause.predicates.is_empty() {
2266 gate_feature_post!(&self, generic_associated_types, ii.span,
2267 "where clauses on associated types are unstable");
2272 visit::walk_impl_item(self, ii);
2275 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2276 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2277 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2278 "`crate` visibility modifier is experimental");
2280 visit::walk_vis(self, vis);
2284 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2285 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2286 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2287 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2288 if let Some(reason) = reason {
2289 err.span_note(span, reason);
2294 let mut features = Features::new();
2295 let mut edition_enabled_features = FxHashMap::default();
2297 for &edition in ALL_EDITIONS {
2298 if edition <= crate_edition {
2299 // The `crate_edition` implies its respective umbrella feature-gate
2300 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2301 edition_enabled_features.insert(edition.feature_name(), edition);
2305 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2306 if let Some(f_edition) = f_edition {
2307 if f_edition <= crate_edition {
2308 set(&mut features, DUMMY_SP);
2309 edition_enabled_features.insert(name, crate_edition);
2314 // Process the edition umbrella feature-gates first, to ensure
2315 // `edition_enabled_features` is completed before it's queried.
2316 for attr in krate_attrs {
2317 if !attr.check_name(sym::feature) {
2321 let list = match attr.meta_item_list() {
2331 let name = mi.name_or_empty();
2332 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2333 span_handler.struct_span_warn(
2336 "the feature `{}` is incomplete and may cause the compiler to crash",
2342 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2343 if *edition <= crate_edition {
2347 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2348 if let Some(f_edition) = f_edition {
2349 if f_edition <= *edition {
2350 // FIXME(Manishearth) there is currently no way to set
2351 // lib features by edition
2352 set(&mut features, DUMMY_SP);
2353 edition_enabled_features.insert(name, *edition);
2361 for attr in krate_attrs {
2362 if !attr.check_name(sym::feature) {
2366 let list = match attr.meta_item_list() {
2372 let name = match mi.ident() {
2373 Some(ident) if mi.is_word() => ident.name,
2375 span_err!(span_handler, mi.span(), E0556,
2376 "malformed feature, expected just one word");
2381 if let Some(edition) = edition_enabled_features.get(&name) {
2386 "the feature `{}` is included in the Rust {} edition",
2393 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2394 // Handled in the separate loop above.
2398 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2399 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2400 if let Some((.., reason)) = removed.or(stable_removed) {
2401 feature_removed(span_handler, mi.span(), *reason);
2405 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2406 let since = Some(Symbol::intern(since));
2407 features.declared_lang_features.push((name, mi.span(), since));
2411 if let Some(allowed) = allow_features.as_ref() {
2412 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2413 span_err!(span_handler, mi.span(), E0725,
2414 "the feature `{}` is not in the list of allowed features",
2420 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2421 set(&mut features, mi.span());
2422 features.declared_lang_features.push((name, mi.span(), None));
2426 features.declared_lib_features.push((name, mi.span()));
2433 pub fn check_crate(krate: &ast::Crate,
2435 features: &Features,
2436 plugin_attributes: &[(Symbol, AttributeType)],
2437 unstable: UnstableFeatures) {
2438 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2444 let visitor = &mut PostExpansionVisitor {
2446 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2448 visit::walk_crate(visitor, krate);
2451 #[derive(Clone, Copy, Hash)]
2452 pub enum UnstableFeatures {
2453 /// Hard errors for unstable features are active, as on beta/stable channels.
2455 /// Allow features to be activated, as on nightly.
2457 /// Errors are bypassed for bootstrapping. This is required any time
2458 /// during the build that feature-related lints are set to warn or above
2459 /// because the build turns on warnings-as-errors and uses lots of unstable
2460 /// features. As a result, this is always required for building Rust itself.
2464 impl UnstableFeatures {
2465 pub fn from_environment() -> UnstableFeatures {
2466 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2467 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2468 // Whether we should enable unstable features for bootstrapping
2469 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2470 match (disable_unstable_features, bootstrap) {
2471 (_, true) => UnstableFeatures::Cheat,
2472 (true, _) => UnstableFeatures::Disallow,
2473 (false, _) => UnstableFeatures::Allow
2477 pub fn is_nightly_build(&self) -> bool {
2479 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2485 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2486 unstable: UnstableFeatures) {
2487 let allow_features = match unstable {
2488 UnstableFeatures::Allow => true,
2489 UnstableFeatures::Disallow => false,
2490 UnstableFeatures::Cheat => true
2492 if !allow_features {
2493 for attr in &krate.attrs {
2494 if attr.check_name(sym::feature) {
2495 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2496 span_err!(span_handler, attr.span, E0554,
2497 "#![feature] may not be used on the {} release channel",