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
19 self, AssocTyConstraint, AssocTyConstraintKind, NodeId, GenericParam, GenericParamKind,
23 use crate::early_buffered_lints::BufferedEarlyLintId;
24 use crate::source_map::Spanned;
25 use crate::edition::{ALL_EDITIONS, Edition};
26 use crate::visit::{self, FnKind, Visitor};
27 use crate::parse::{token, ParseSess};
28 use crate::symbol::{Symbol, kw, sym};
29 use crate::tokenstream::TokenTree;
31 use errors::{Applicability, DiagnosticBuilder, Handler};
32 use rustc_data_structures::fx::FxHashMap;
33 use rustc_target::spec::abi::Abi;
34 use syntax_pos::{Span, DUMMY_SP};
36 use lazy_static::lazy_static;
42 fn f(features: &mut Features, _: Span) {
43 features.$field = true;
45 f as fn(&mut Features, Span)
49 macro_rules! declare_features {
50 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
51 /// Represents active features that are currently being implemented or
52 /// currently being considered for addition/removal.
53 const ACTIVE_FEATURES:
54 &[(Symbol, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
55 &[$((sym::$feature, $ver, $issue, $edition, set!($feature))),+];
57 /// A set of features to be used by later passes.
60 /// `#![feature]` attrs for language features, for error reporting
61 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
62 /// `#![feature]` attrs for non-language (library) features
63 pub declared_lib_features: Vec<(Symbol, Span)>,
64 $(pub $feature: bool),+
68 pub fn new() -> Features {
70 declared_lang_features: Vec::new(),
71 declared_lib_features: Vec::new(),
76 pub fn walk_feature_fields<F>(&self, mut f: F)
77 where F: FnMut(&str, bool)
79 $(f(stringify!($feature), self.$feature);)+
84 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
85 /// Represents unstable features which have since been removed (it was once Active)
86 const REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
87 $((sym::$feature, $ver, $issue, $reason)),+
91 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
92 /// Represents stable features which have since been removed (it was once Accepted)
93 const STABLE_REMOVED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
94 $((sym::$feature, $ver, $issue, None)),+
98 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
99 /// Those language feature has since been Accepted (it was once Active)
100 const ACCEPTED_FEATURES: &[(Symbol, &str, Option<u32>, Option<&str>)] = &[
101 $((sym::$feature, $ver, $issue, None)),+
106 // If you change this, please modify `src/doc/unstable-book` as well.
108 // Don't ever remove anything from this list; set them to 'Removed'.
110 // The version numbers here correspond to the version in which the current status
111 // was set. This is most important for knowing when a particular feature became
114 // Note that the features are grouped into internal/user-facing and then
115 // sorted by version inside those groups. This is inforced with tidy.
117 // N.B., `tools/tidy/src/features.rs` parses this information directly out of the
118 // source, so take care when modifying it.
121 // -------------------------------------------------------------------------
122 // feature-group-start: internal feature gates
123 // -------------------------------------------------------------------------
125 // no-tracking-issue-start
127 // Allows using the `rust-intrinsic`'s "ABI".
128 (active, intrinsics, "1.0.0", None, None),
130 // Allows using `#[lang = ".."]` attribute for linking items to special compiler logic.
131 (active, lang_items, "1.0.0", None, None),
133 // Allows using the `#[stable]` and `#[unstable]` attributes.
134 (active, staged_api, "1.0.0", None, None),
136 // Allows using `#[allow_internal_unstable]`. This is an
137 // attribute on `macro_rules!` and can't use the attribute handling
138 // below (it has to be checked before expansion possibly makes
139 // macros disappear).
140 (active, allow_internal_unstable, "1.0.0", None, None),
142 // Allows using `#[allow_internal_unsafe]`. This is an
143 // attribute on `macro_rules!` and can't use the attribute handling
144 // below (it has to be checked before expansion possibly makes
145 // macros disappear).
146 (active, allow_internal_unsafe, "1.0.0", None, None),
148 // Allows using the macros:
149 // + `__diagnostic_used`
150 // + `__register_diagnostic`
151 // +`__build_diagnostic_array`
152 (active, rustc_diagnostic_macros, "1.0.0", None, None),
154 // Allows using `#[rustc_const_unstable(feature = "foo", ..)]` which
155 // lets a function to be `const` when opted into with `#![feature(foo)]`.
156 (active, rustc_const_unstable, "1.0.0", None, None),
158 // no-tracking-issue-end
160 // Allows using `#[link_name="llvm.*"]`.
161 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
163 // Allows using `rustc_*` attributes (RFC 572).
164 (active, rustc_attrs, "1.0.0", Some(29642), None),
166 // Allows using `#[on_unimplemented(..)]` on traits.
167 (active, on_unimplemented, "1.0.0", Some(29628), None),
169 // Allows using the `box $expr` syntax.
170 (active, box_syntax, "1.0.0", Some(49733), None),
172 // Allows using `#[main]` to replace the entrypoint `#[lang = "start"]` calls.
173 (active, main, "1.0.0", Some(29634), None),
175 // Allows using `#[start]` on a function indicating that it is the program entrypoint.
176 (active, start, "1.0.0", Some(29633), None),
178 // Allows using the `#[fundamental]` attribute.
179 (active, fundamental, "1.0.0", Some(29635), None),
181 // Allows using the `rust-call` ABI.
182 (active, unboxed_closures, "1.0.0", Some(29625), None),
184 // Allows using the `#[linkage = ".."]` attribute.
185 (active, linkage, "1.0.0", Some(29603), None),
187 // Allows features specific to OIBIT (auto traits).
188 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
190 // Allows using `box` in patterns (RFC 469).
191 (active, box_patterns, "1.0.0", Some(29641), None),
193 // no-tracking-issue-start
195 // Allows using `#[prelude_import]` on glob `use` items.
196 (active, prelude_import, "1.2.0", None, None),
198 // no-tracking-issue-end
200 // Allows using `#[unsafe_destructor_blind_to_params]` (RFC 1238).
201 (active, dropck_parametricity, "1.3.0", Some(28498), None),
203 // no-tracking-issue-start
205 // Allows using `#[omit_gdb_pretty_printer_section]`.
206 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
208 // Allows using the `vectorcall` ABI.
209 (active, abi_vectorcall, "1.7.0", None, None),
211 // no-tracking-issue-end
213 // Allows using `#[structural_match]` which indicates that a type is structurally matchable.
214 (active, structural_match, "1.8.0", Some(31434), None),
216 // Allows using the `may_dangle` attribute (RFC 1327).
217 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
219 // Allows using the `#![panic_runtime]` attribute.
220 (active, panic_runtime, "1.10.0", Some(32837), None),
222 // Allows declaring with `#![needs_panic_runtime]` that a panic runtime is needed.
223 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
225 // no-tracking-issue-start
227 // Allows identifying the `compiler_builtins` crate.
228 (active, compiler_builtins, "1.13.0", None, None),
230 // Allows using the `unadjusted` ABI; perma-unstable.
231 (active, abi_unadjusted, "1.16.0", None, None),
233 // Allows identifying crates that contain sanitizer runtimes.
234 (active, sanitizer_runtime, "1.17.0", None, None),
236 // Used to identify crates that contain the profiler runtime.
237 (active, profiler_runtime, "1.18.0", None, None),
239 // Allows using the `thiscall` ABI.
240 (active, abi_thiscall, "1.19.0", None, None),
242 // Allows using `#![needs_allocator]`, an implementation detail of `#[global_allocator]`.
243 (active, allocator_internals, "1.20.0", None, None),
245 // Allows using the `format_args_nl` macro.
246 (active, format_args_nl, "1.29.0", None, None),
248 // no-tracking-issue-end
250 // Added for testing E0705; perma-unstable.
251 (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
253 // -------------------------------------------------------------------------
254 // feature-group-end: internal feature gates
255 // -------------------------------------------------------------------------
257 // -------------------------------------------------------------------------
258 // feature-group-start: actual feature gates (target features)
259 // -------------------------------------------------------------------------
261 // FIXME: Document these and merge with the list below.
263 // Unstable `#[target_feature]` directives.
264 (active, arm_target_feature, "1.27.0", Some(44839), None),
265 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
266 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
267 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
268 (active, mips_target_feature, "1.27.0", Some(44839), None),
269 (active, avx512_target_feature, "1.27.0", Some(44839), None),
270 (active, mmx_target_feature, "1.27.0", Some(44839), None),
271 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
272 (active, tbm_target_feature, "1.27.0", Some(44839), None),
273 (active, wasm_target_feature, "1.30.0", Some(44839), None),
274 (active, adx_target_feature, "1.32.0", Some(44839), None),
275 (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
276 (active, movbe_target_feature, "1.34.0", Some(44839), None),
277 (active, rtm_target_feature, "1.35.0", Some(44839), None),
278 (active, f16c_target_feature, "1.36.0", Some(44839), None),
280 // -------------------------------------------------------------------------
281 // feature-group-end: actual feature gates (target features)
282 // -------------------------------------------------------------------------
284 // -------------------------------------------------------------------------
285 // feature-group-start: actual feature gates
286 // -------------------------------------------------------------------------
288 // Allows using `asm!` macro with which inline assembly can be embedded.
289 (active, asm, "1.0.0", Some(29722), None),
291 // Allows using the `concat_idents!` macro with which identifiers can be concatenated.
292 (active, concat_idents, "1.0.0", Some(29599), None),
294 // Allows using the `#[link_args]` attribute.
295 (active, link_args, "1.0.0", Some(29596), None),
297 // Allows defining identifiers beyond ASCII.
298 (active, non_ascii_idents, "1.0.0", Some(55467), None),
300 // Allows using `#[plugin_registrar]` on functions.
301 (active, plugin_registrar, "1.0.0", Some(29597), None),
303 // Allows using `#![plugin(myplugin)]`.
304 (active, plugin, "1.0.0", Some(29597), None),
306 // Allows using `#[thread_local]` on `static` items.
307 (active, thread_local, "1.0.0", Some(29594), None),
309 // Allows using the `log_syntax!` macro.
310 (active, log_syntax, "1.0.0", Some(29598), None),
312 // Allows using the `trace_macros!` macro.
313 (active, trace_macros, "1.0.0", Some(29598), None),
315 // Allows the use of SIMD types in functions declared in `extern` blocks.
316 (active, simd_ffi, "1.0.0", Some(27731), None),
318 // Allows using custom attributes (RFC 572).
319 (active, custom_attribute, "1.0.0", Some(29642), None),
321 // Allows using non lexical lifetimes (RFC 2094).
322 (active, nll, "1.0.0", Some(43234), None),
324 // Allows using slice patterns.
325 (active, slice_patterns, "1.0.0", Some(23121), None),
327 // Allows the definition of `const` functions with some advanced features.
328 (active, const_fn, "1.2.0", Some(57563), None),
330 // Allows associated type defaults.
331 (active, associated_type_defaults, "1.2.0", Some(29661), None),
333 // Allows `#![no_core]`.
334 (active, no_core, "1.3.0", Some(29639), None),
336 // Allows default type parameters to influence type inference.
337 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
339 // Allows `repr(simd)` and importing the various simd intrinsics.
340 (active, repr_simd, "1.4.0", Some(27731), None),
342 // Allows `extern "platform-intrinsic" { ... }`.
343 (active, platform_intrinsics, "1.4.0", Some(27731), None),
345 // Allows `#[unwind(..)]`.
347 // Permits specifying whether a function should permit unwinding or abort on unwind.
348 (active, unwind_attributes, "1.4.0", Some(58760), None),
350 // Allows `#[no_debug]`.
351 (active, no_debug, "1.5.0", Some(29721), None),
353 // Allows attributes on expressions and non-item statements.
354 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
356 // Allows the use of type ascription in expressions.
357 (active, type_ascription, "1.6.0", Some(23416), None),
359 // Allows `cfg(target_thread_local)`.
360 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
362 // Allows specialization of implementations (RFC 1210).
363 (active, specialization, "1.7.0", Some(31844), None),
365 // Allows using `#[naked]` on functions.
366 (active, naked_functions, "1.9.0", Some(32408), None),
368 // Allows `cfg(target_has_atomic = "...")`.
369 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
371 // Allows `X..Y` patterns.
372 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
374 // Allows the `!` type. Does not imply 'exhaustive_patterns' (below) any more.
375 (active, never_type, "1.13.0", Some(35121), None),
377 // Allows exhaustive pattern matching on types that contain uninhabited types.
378 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
380 // Allows untagged unions `union U { ... }`.
381 (active, untagged_unions, "1.13.0", Some(32836), None),
383 // Allows `#[link(..., cfg(..))]`.
384 (active, link_cfg, "1.14.0", Some(37406), None),
386 // Allows `extern "ptx-*" fn()`.
387 (active, abi_ptx, "1.15.0", Some(38788), None),
389 // Allows the `#[repr(i128)]` attribute for enums.
390 (active, repr128, "1.16.0", Some(35118), None),
392 // Allows `#[link(kind="static-nobundle"...)]`.
393 (active, static_nobundle, "1.16.0", Some(37403), None),
395 // Allows `extern "msp430-interrupt" fn()`.
396 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
398 // Allows declarative macros 2.0 (`macro`).
399 (active, decl_macro, "1.17.0", Some(39412), None),
401 // Allows `extern "x86-interrupt" fn()`.
402 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
404 // Allows module-level inline assembly by way of `global_asm!()`.
405 (active, global_asm, "1.18.0", Some(35119), None),
407 // Allows overlapping impls of marker traits.
408 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
410 // Allows a test to fail without failing the whole suite.
411 (active, allow_fail, "1.19.0", Some(46488), None),
413 // Allows unsized tuple coercion.
414 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
416 // Allows defining generators.
417 (active, generators, "1.21.0", Some(43122), None),
419 // Allows `#[doc(cfg(...))]`.
420 (active, doc_cfg, "1.21.0", Some(43781), None),
422 // Allows `#[doc(masked)]`.
423 (active, doc_masked, "1.21.0", Some(44027), None),
425 // Allows `#[doc(spotlight)]`.
426 (active, doc_spotlight, "1.22.0", Some(45040), None),
428 // Allows `#[doc(include = "some-file")]`.
429 (active, external_doc, "1.22.0", Some(44732), None),
431 // Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008).
432 (active, non_exhaustive, "1.22.0", Some(44109), None),
434 // Allows using `crate` as visibility modifier, synonymous with `pub(crate)`.
435 (active, crate_visibility_modifier, "1.23.0", Some(53120), None),
437 // Allows defining `extern type`s.
438 (active, extern_types, "1.23.0", Some(43467), None),
440 // Allows trait methods with arbitrary self types.
441 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
443 // Allows in-band quantification of lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
444 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
446 // Allows associated types to be generic, e.g., `type Foo<T>;` (RFC 1598).
447 (active, generic_associated_types, "1.23.0", Some(44265), None),
449 // Allows defining `trait X = A + B;` alias items.
450 (active, trait_alias, "1.24.0", Some(41517), None),
452 // Allows infering `'static` outlives requirements (RFC 2093).
453 (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
455 // Allows macro invocations in `extern {}` blocks.
456 (active, macros_in_extern, "1.27.0", Some(49476), None),
458 // Allows accessing fields of unions inside `const` functions.
459 (active, const_fn_union, "1.27.0", Some(51909), None),
461 // Allows casting raw pointers to `usize` during const eval.
462 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
464 // Allows dereferencing raw pointers during const eval.
465 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
467 // Allows comparing raw pointers during const eval.
468 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
470 // Allows `#[doc(alias = "...")]`.
471 (active, doc_alias, "1.27.0", Some(50146), None),
473 // Allows defining `existential type`s.
474 (active, existential_type, "1.28.0", Some(34511), None),
476 // Allows inconsistent bounds in where clauses.
477 (active, trivial_bounds, "1.28.0", Some(48214), None),
479 // Allows `'a: { break 'a; }`.
480 (active, label_break_value, "1.28.0", Some(48594), None),
482 // Allows using `#[doc(keyword = "...")]`.
483 (active, doc_keyword, "1.28.0", Some(51315), None),
485 // Allows async and await syntax.
486 (active, async_await, "1.28.0", Some(50547), None),
488 // Allows await! macro-like syntax.
489 // This will likely be removed prior to stabilization of async/await.
490 (active, await_macro, "1.28.0", Some(50547), None),
492 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
493 (active, const_transmute, "1.29.0", Some(53605), None),
495 // Allows using `try {...}` expressions.
496 (active, try_blocks, "1.29.0", Some(31436), None),
498 // Allows defining an `#[alloc_error_handler]`.
499 (active, alloc_error_handler, "1.29.0", Some(51540), None),
501 // Allows using the `amdgpu-kernel` ABI.
502 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
504 // Allows panicking during const eval (producing compile-time errors).
505 (active, const_panic, "1.30.0", Some(51999), None),
507 // Allows `#[marker]` on certain traits allowing overlapping implementations.
508 (active, marker_trait_attr, "1.30.0", Some(29864), None),
510 // Allows macro invocations on modules expressions and statements and
511 // procedural macros to expand to non-items.
512 (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
514 // Allows unsized rvalues at arguments and parameters.
515 (active, unsized_locals, "1.30.0", Some(48055), None),
517 // Allows custom test frameworks with `#![test_runner]` and `#[test_case]`.
518 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
520 // Allows non-builtin attributes in inner attribute position.
521 (active, custom_inner_attributes, "1.30.0", Some(54726), None),
523 // Allows mixing bind-by-move in patterns and references to those identifiers in guards.
524 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
526 // Allows `impl Trait` in bindings (`let`, `const`, `static`).
527 (active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
529 // Allows `const _: TYPE = VALUE`.
530 (active, underscore_const_names, "1.31.0", Some(54912), None),
532 // Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
533 (active, lint_reasons, "1.31.0", Some(54503), None),
535 // Allows paths to enum variants on type aliases.
536 (active, type_alias_enum_variants, "1.31.0", Some(49683), None),
538 // Allows exhaustive integer pattern matching on `usize` and `isize`.
539 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
541 // Allows relaxing the coherence rules such that
542 // `impl<T> ForeignTrait<LocalType> for ForeignType<T> is permitted.
543 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
545 // Allows using `#[ffi_returns_twice]` on foreign functions.
546 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
548 // Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
549 (active, const_generics, "1.34.0", Some(44580), None),
551 // Allows using `#[optimize(X)]`.
552 (active, optimize_attribute, "1.34.0", Some(54882), None),
554 // Allows using C-variadics.
555 (active, c_variadic, "1.34.0", Some(44930), None),
557 // Allows the user of associated type bounds.
558 (active, associated_type_bounds, "1.34.0", Some(52662), None),
560 // Attributes on formal function params.
561 (active, param_attrs, "1.36.0", Some(60406), None),
563 // Allows calling constructor functions in `const fn`.
564 (active, const_constructor, "1.37.0", Some(61456), None),
566 // #[repr(transparent)] on enums.
567 (active, transparent_enums, "1.37.0", Some(60405), None),
569 // #[repr(transparent)] on unions.
570 (active, transparent_unions, "1.37.0", Some(60405), None),
572 // -------------------------------------------------------------------------
573 // feature-group-end: actual feature gates
574 // -------------------------------------------------------------------------
577 // Some features are known to be incomplete and using them is likely to have
578 // unanticipated results, such as compiler crashes. We warn the user about these
580 const INCOMPLETE_FEATURES: &[Symbol] = &[
581 sym::impl_trait_in_bindings,
582 sym::generic_associated_types,
587 // -------------------------------------------------------------------------
588 // feature-group-start: removed features
589 // -------------------------------------------------------------------------
591 (removed, import_shadowing, "1.0.0", None, None, None),
592 (removed, managed_boxes, "1.0.0", None, None, None),
593 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
594 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
595 (removed, reflect, "1.0.0", Some(27749), None, None),
596 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
597 (removed, opt_out_copy, "1.0.0", None, None, None),
598 (removed, quad_precision_float, "1.0.0", None, None, None),
599 (removed, struct_inherit, "1.0.0", None, None, None),
600 (removed, test_removed_feature, "1.0.0", None, None, None),
601 (removed, visible_private_types, "1.0.0", None, None, None),
602 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
603 // Allows using items which are missing stability attributes
604 (removed, unmarked_api, "1.0.0", None, None, None),
605 (removed, allocator, "1.0.0", None, None, None),
606 (removed, simd, "1.0.0", Some(27731), None,
607 Some("removed in favor of `#[repr(simd)]`")),
608 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
609 Some("merged into `#![feature(slice_patterns)]`")),
610 (removed, macro_reexport, "1.0.0", Some(29638), None,
611 Some("subsumed by `pub use`")),
612 (removed, pushpop_unsafe, "1.2.0", None, None, None),
613 (removed, needs_allocator, "1.4.0", Some(27389), None,
614 Some("subsumed by `#![feature(allocator_internals)]`")),
615 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
616 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
617 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
618 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
619 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
620 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
621 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
622 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
623 (removed, panic_implementation, "1.28.0", Some(44489), None,
624 Some("subsumed by `#[panic_handler]`")),
625 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
626 (removed, custom_derive, "1.32.0", Some(29644), None,
627 Some("subsumed by `#[proc_macro_derive]`")),
628 // Paths of the form: `extern::foo::bar`
629 (removed, extern_in_paths, "1.33.0", Some(55600), None,
630 Some("subsumed by `::foo::bar` paths")),
631 (removed, quote, "1.33.0", Some(29601), None, None),
633 // -------------------------------------------------------------------------
634 // feature-group-end: removed features
635 // -------------------------------------------------------------------------
639 (stable_removed, no_stack_check, "1.0.0", None, None),
643 // -------------------------------------------------------------------------
644 // feature-group-start: for testing purposes
645 // -------------------------------------------------------------------------
647 // A temporary feature gate used to enable parser extensions needed
648 // to bootstrap fix for #5723.
649 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
650 // These are used to test this portion of the compiler,
651 // they don't actually mean anything.
652 (accepted, test_accepted_feature, "1.0.0", None, None),
654 // -------------------------------------------------------------------------
655 // feature-group-end: for testing purposes
656 // -------------------------------------------------------------------------
658 // -------------------------------------------------------------------------
659 // feature-group-start: accepted features
660 // -------------------------------------------------------------------------
662 // Allows using associated `type`s in `trait`s.
663 (accepted, associated_types, "1.0.0", None, None),
664 // Allows using assigning a default type to type parameters in algebraic data type definitions.
665 (accepted, default_type_params, "1.0.0", None, None),
666 // FIXME: explain `globs`.
667 (accepted, globs, "1.0.0", None, None),
668 // Allows `macro_rules!` items.
669 (accepted, macro_rules, "1.0.0", None, None),
670 // Allows use of `&foo[a..b]` as a slicing syntax.
671 (accepted, slicing_syntax, "1.0.0", None, None),
672 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
673 (accepted, struct_variant, "1.0.0", None, None),
674 // Allows indexing tuples.
675 (accepted, tuple_indexing, "1.0.0", None, None),
676 // Allows the use of `if let` expressions.
677 (accepted, if_let, "1.0.0", None, None),
678 // Allows the use of `while let` expressions.
679 (accepted, while_let, "1.0.0", None, None),
680 // Allows using `#![no_std]`.
681 (accepted, no_std, "1.6.0", None, None),
682 // Allows overloading augmented assignment operations like `a += b`.
683 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
684 // Allows empty structs and enum variants with braces.
685 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
686 // Allows `#[deprecated]` attribute.
687 (accepted, deprecated, "1.9.0", Some(29935), None),
688 // Allows macros to appear in the type position.
689 (accepted, type_macros, "1.13.0", Some(27245), None),
690 // Allows use of the postfix `?` operator in expressions.
691 (accepted, question_mark, "1.13.0", Some(31436), None),
692 // Allows `..` in tuple (struct) patterns.
693 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
694 // Allows some increased flexibility in the name resolution rules,
695 // especially around globs and shadowing (RFC 1560).
696 (accepted, item_like_imports, "1.15.0", Some(35120), None),
697 // Allows using `Self` and associated types in struct expressions and patterns.
698 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
699 // Allows elision of `'static` lifetimes in `static`s and `const`s.
700 (accepted, static_in_const, "1.17.0", Some(35897), None),
701 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
702 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
703 // Allows the definition recursive static items.
704 (accepted, static_recursion, "1.17.0", Some(29719), None),
705 // Allows `pub(restricted)` visibilities (RFC 1422).
706 (accepted, pub_restricted, "1.18.0", Some(32409), None),
707 // Allows `#![windows_subsystem]`.
708 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
709 // Allows `break {expr}` with a value inside `loop`s.
710 (accepted, loop_break_value, "1.19.0", Some(37339), None),
711 // Allows numeric fields in struct expressions and patterns.
712 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
713 // Allows coercing non capturing closures to function pointers.
714 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
715 // Allows attributes on struct literal fields.
716 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
717 // Allows the definition of associated constants in `trait` or `impl` blocks.
718 (accepted, associated_consts, "1.20.0", Some(29646), None),
719 // Allows usage of the `compile_error!` macro.
720 (accepted, compile_error, "1.20.0", Some(40872), None),
721 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
722 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
723 // Allows `Drop` types in constants (RFC 1440).
724 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
725 // Allows the sysV64 ABI to be specified on all platforms
726 // instead of just the platforms on which it is the C ABI.
727 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
728 // Allows `repr(align(16))` struct attribute (RFC 1358).
729 (accepted, repr_align, "1.25.0", Some(33626), None),
730 // Allows '|' at beginning of match arms (RFC 1925).
731 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
732 // Allows nested groups in `use` items (RFC 2128).
733 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
734 // Allows indexing into constant arrays.
735 (accepted, const_indexing, "1.26.0", Some(29947), None),
736 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
737 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
738 // Allows `..=` in patterns (RFC 1192).
739 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
740 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
741 (accepted, termination_trait, "1.26.0", Some(43301), None),
742 // Allows implementing `Clone` for closures where possible (RFC 2132).
743 (accepted, clone_closures, "1.26.0", Some(44490), None),
744 // Allows implementing `Copy` for closures where possible (RFC 2132).
745 (accepted, copy_closures, "1.26.0", Some(44490), None),
746 // Allows `impl Trait` in function arguments.
747 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
748 // Allows `impl Trait` in function return types.
749 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
750 // Allows using the `u128` and `i128` types.
751 (accepted, i128_type, "1.26.0", Some(35118), None),
752 // Allows default match binding modes (RFC 2005).
753 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
754 // Allows `'_` placeholder lifetimes.
755 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
756 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
757 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
758 // Allows `cfg(target_feature = "...")`.
759 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
760 // Allows `#[target_feature(...)]`.
761 (accepted, target_feature, "1.27.0", None, None),
762 // Allows using `dyn Trait` as a syntax for trait objects.
763 (accepted, dyn_trait, "1.27.0", Some(44662), None),
764 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
765 (accepted, fn_must_use, "1.27.0", Some(43302), None),
766 // Allows use of the `:lifetime` macro fragment specifier.
767 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
768 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
769 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
770 // Allows the `#[global_allocator]` attribute.
771 (accepted, global_allocator, "1.28.0", Some(27389), None),
772 // Allows `#[repr(transparent)]` attribute on newtype structs.
773 (accepted, repr_transparent, "1.28.0", Some(43036), None),
774 // Allows procedural macros in `proc-macro` crates.
775 (accepted, proc_macro, "1.29.0", Some(38356), None),
776 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
777 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
778 // Allows use of the `:vis` macro fragment specifier
779 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
780 // Allows importing and reexporting macros with `use`,
781 // enables macro modularization in general.
782 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
783 // Allows keywords to be escaped for use as identifiers.
784 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
785 // Allows attributes scoped to tools.
786 (accepted, tool_attributes, "1.30.0", Some(44690), None),
787 // Allows multi-segment paths in attributes and derives.
788 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
789 // Allows all literals in attribute lists and values of key-value pairs.
790 (accepted, attr_literals, "1.30.0", Some(34981), None),
791 // Allows inferring outlives requirements (RFC 2093).
792 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
793 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
794 // This defines the behavior of panics.
795 (accepted, panic_handler, "1.30.0", Some(44489), None),
796 // Allows `#[used]` to preserve symbols (see llvm.used).
797 (accepted, used, "1.30.0", Some(40289), None),
798 // Allows `crate` in paths.
799 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
800 // Allows resolving absolute paths as paths from other crates.
801 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
802 // Allows access to crate names passed via `--extern` through prelude.
803 (accepted, extern_prelude, "1.30.0", Some(44660), None),
804 // Allows parentheses in patterns.
805 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
806 // Allows the definition of `const fn` functions.
807 (accepted, min_const_fn, "1.31.0", Some(53555), None),
808 // Allows scoped lints.
809 (accepted, tool_lints, "1.31.0", Some(44690), None),
810 // Allows lifetime elision in `impl` headers. For example:
811 // + `impl<I:Iterator> Iterator for &mut Iterator`
812 // + `impl Debug for Foo<'_>`
813 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
814 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
815 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
816 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
817 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
818 // Allows use of `?` as the Kleene "at most one" operator in macros.
819 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
820 // Allows `Self` struct constructor (RFC 2302).
821 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
822 // Allows `Self` in type definitions (RFC 2300).
823 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
824 // Allows `use x::y;` to search `x` in the current scope.
825 (accepted, uniform_paths, "1.32.0", Some(53130), None),
826 // Allows integer match exhaustiveness checking (RFC 2591).
827 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
828 // Allows `use path as _;` and `extern crate c as _;`.
829 (accepted, underscore_imports, "1.33.0", Some(48216), None),
830 // Allows `#[repr(packed(N))]` attribute on structs.
831 (accepted, repr_packed, "1.33.0", Some(33158), None),
832 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
833 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
834 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
835 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
836 // Allows let bindings, assignments and destructuring in `const` functions and constants.
837 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
838 // at the same time as let bindings.
839 (accepted, const_let, "1.33.0", Some(48821), None),
840 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
841 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
842 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
843 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
844 // Allows `cfg(target_vendor = "...")`.
845 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
846 // Allows `extern crate self as foo;`.
847 // This puts local crate root into extern prelude under name `foo`.
848 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
849 // Allows arbitrary delimited token streams in non-macro attributes.
850 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
851 // Allows using `#[repr(align(X))]` on enums with equivalent semantics
852 // to wrapping an enum in a wrapper struct with `#[repr(align(X))]`.
853 (accepted, repr_align_enum, "1.37.0", Some(57996), None),
855 // -------------------------------------------------------------------------
856 // feature-group-end: accepted features
857 // -------------------------------------------------------------------------
860 // If you change this, please modify `src/doc/unstable-book` as well. You must
861 // move that documentation into the relevant place in the other docs, and
862 // remove the chapter on the flag.
864 #[derive(Copy, Clone, PartialEq, Debug)]
865 pub enum AttributeType {
866 /// Normal, builtin attribute that is consumed
867 /// by the compiler before the unused_attribute check
870 /// Builtin attribute that may not be consumed by the compiler
871 /// before the unused_attribute check. These attributes
872 /// will be ignored by the unused_attribute lint
875 /// Builtin attribute that is only allowed at the crate level
879 pub enum AttributeGate {
880 /// Is gated by a given feature gate, reason
881 /// and function to check if enabled
882 Gated(Stability, Symbol, &'static str, fn(&Features) -> bool),
884 /// Ungated attribute, can be used on all release channels
888 /// A template that the attribute input must match.
889 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
890 #[derive(Clone, Copy)]
891 pub struct AttributeTemplate {
893 list: Option<&'static str>,
894 name_value_str: Option<&'static str>,
897 impl AttributeTemplate {
898 /// Checks that the given meta-item is compatible with this template.
899 fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
900 match meta_item_kind {
901 ast::MetaItemKind::Word => self.word,
902 ast::MetaItemKind::List(..) => self.list.is_some(),
903 ast::MetaItemKind::NameValue(lit) if lit.node.is_str() => self.name_value_str.is_some(),
904 ast::MetaItemKind::NameValue(..) => false,
909 /// A convenience macro for constructing attribute templates.
910 /// E.g., `template!(Word, List: "description")` means that the attribute
911 /// supports forms `#[attr]` and `#[attr(description)]`.
912 macro_rules! template {
913 (Word) => { template!(@ true, None, None) };
914 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
915 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
916 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
917 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
918 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
919 template!(@ false, Some($descr1), Some($descr2))
921 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
922 template!(@ true, Some($descr1), Some($descr2))
924 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
925 word: $word, list: $list, name_value_str: $name_value_str
930 fn is_deprecated(&self) -> bool {
932 Gated(Stability::Deprecated(_, _), ..) => true,
938 #[derive(Copy, Clone, Debug)]
941 // First argument is tracking issue link; second argument is an optional
942 // help message, which defaults to "remove this attribute"
943 Deprecated(&'static str, Option<&'static str>),
947 impl std::fmt::Debug for AttributeGate {
948 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
950 Gated(ref stab, name, expl, _) =>
951 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
952 Ungated => write!(fmt, "Ungated")
957 macro_rules! cfg_fn {
958 ($field: ident) => {{
959 fn f(features: &Features) -> bool {
962 f as fn(&Features) -> bool
966 pub fn deprecated_attributes() -> Vec<&'static (Symbol, AttributeType,
967 AttributeTemplate, AttributeGate)> {
968 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
971 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
972 BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
975 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
976 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
979 /// Attributes that have a special meaning to rustc or rustdoc
980 pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
986 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
992 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
998 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1004 template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#),
1008 (sym::macro_use, Normal, template!(Word, List: "name1, name2, ..."), Ungated),
1009 (sym::macro_export, Normal, template!(Word, List: "local_inner_macros"), Ungated),
1010 (sym::plugin_registrar, Normal, template!(Word), Ungated),
1012 (sym::cfg, Normal, template!(List: "predicate"), Ungated),
1013 (sym::cfg_attr, Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
1014 (sym::main, Normal, template!(Word), Ungated),
1015 (sym::start, Normal, template!(Word), Ungated),
1016 (sym::repr, Normal, template!(List: "C, packed, ..."), Ungated),
1017 (sym::path, Normal, template!(NameValueStr: "file"), Ungated),
1018 (sym::automatically_derived, Normal, template!(Word), Ungated),
1019 (sym::no_mangle, Whitelisted, template!(Word), Ungated),
1020 (sym::no_link, Normal, template!(Word), Ungated),
1021 (sym::derive, Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
1025 template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
1028 (sym::ignore, Normal, template!(Word, NameValueStr: "reason"), Ungated),
1029 (sym::no_implicit_prelude, Normal, template!(Word), Ungated),
1030 (sym::reexport_test_harness_main, Normal, template!(NameValueStr: "name"), Ungated),
1031 (sym::link_args, Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
1033 "the `link_args` attribute is experimental and not \
1034 portable across platforms, it is recommended to \
1035 use `#[link(name = \"foo\")] instead",
1036 cfg_fn!(link_args))),
1037 (sym::macro_escape, Normal, template!(Word), Ungated),
1040 (sym::structural_match, Whitelisted, template!(Word), Gated(Stability::Unstable,
1041 sym::structural_match,
1042 "the semantics of constant patterns is \
1044 cfg_fn!(structural_match))),
1047 (sym::non_exhaustive, Whitelisted, template!(Word), Gated(Stability::Unstable,
1048 sym::non_exhaustive,
1049 "non exhaustive is an experimental feature",
1050 cfg_fn!(non_exhaustive))),
1053 (sym::marker, Normal, template!(Word), Gated(Stability::Unstable,
1054 sym::marker_trait_attr,
1055 "marker traits is an experimental feature",
1056 cfg_fn!(marker_trait_attr))),
1058 (sym::plugin, CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
1060 "compiler plugins are experimental \
1061 and possibly buggy",
1064 (sym::no_std, CrateLevel, template!(Word), Ungated),
1065 (sym::no_core, CrateLevel, template!(Word), Gated(Stability::Unstable,
1067 "no_core is experimental",
1069 (sym::lang, Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
1071 "language items are subject to change",
1072 cfg_fn!(lang_items))),
1073 (sym::linkage, Whitelisted, template!(NameValueStr: "external|internal|..."),
1074 Gated(Stability::Unstable,
1076 "the `linkage` attribute is experimental \
1077 and not portable across platforms",
1079 (sym::thread_local, Whitelisted, template!(Word), Gated(Stability::Unstable,
1081 "`#[thread_local]` is an experimental feature, and does \
1082 not currently handle destructors",
1083 cfg_fn!(thread_local))),
1085 (sym::rustc_on_unimplemented, Whitelisted, template!(List:
1086 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
1087 NameValueStr: "message"),
1088 Gated(Stability::Unstable,
1089 sym::on_unimplemented,
1090 "the `#[rustc_on_unimplemented]` attribute \
1091 is an experimental feature",
1092 cfg_fn!(on_unimplemented))),
1093 (sym::rustc_const_unstable, Normal, template!(List: r#"feature = "name""#),
1094 Gated(Stability::Unstable,
1095 sym::rustc_const_unstable,
1096 "the `#[rustc_const_unstable]` attribute \
1097 is an internal feature",
1098 cfg_fn!(rustc_const_unstable))),
1099 (sym::global_allocator, Normal, template!(Word), Ungated),
1100 (sym::default_lib_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1101 sym::allocator_internals,
1102 "the `#[default_lib_allocator]` \
1103 attribute is an experimental feature",
1104 cfg_fn!(allocator_internals))),
1105 (sym::needs_allocator, Normal, template!(Word), Gated(Stability::Unstable,
1106 sym::allocator_internals,
1107 "the `#[needs_allocator]` \
1108 attribute is an experimental \
1110 cfg_fn!(allocator_internals))),
1111 (sym::panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1113 "the `#[panic_runtime]` attribute is \
1114 an experimental feature",
1115 cfg_fn!(panic_runtime))),
1116 (sym::needs_panic_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1117 sym::needs_panic_runtime,
1118 "the `#[needs_panic_runtime]` \
1119 attribute is an experimental \
1121 cfg_fn!(needs_panic_runtime))),
1122 (sym::rustc_outlives, Normal, template!(Word), Gated(Stability::Unstable,
1124 "the `#[rustc_outlives]` attribute \
1125 is just used for rustc unit tests \
1126 and will never be stable",
1127 cfg_fn!(rustc_attrs))),
1128 (sym::rustc_variance, Normal, template!(Word), Gated(Stability::Unstable,
1130 "the `#[rustc_variance]` attribute \
1131 is just used for rustc unit tests \
1132 and will never be stable",
1133 cfg_fn!(rustc_attrs))),
1134 (sym::rustc_layout, Normal, template!(List: "field1, field2, ..."),
1135 Gated(Stability::Unstable,
1137 "the `#[rustc_layout]` attribute \
1138 is just used for rustc unit tests \
1139 and will never be stable",
1140 cfg_fn!(rustc_attrs))),
1141 (sym::rustc_layout_scalar_valid_range_start, Whitelisted, template!(List: "value"),
1142 Gated(Stability::Unstable,
1144 "the `#[rustc_layout_scalar_valid_range_start]` attribute \
1145 is just used to enable niche optimizations in libcore \
1146 and will never be stable",
1147 cfg_fn!(rustc_attrs))),
1148 (sym::rustc_layout_scalar_valid_range_end, Whitelisted, template!(List: "value"),
1149 Gated(Stability::Unstable,
1151 "the `#[rustc_layout_scalar_valid_range_end]` attribute \
1152 is just used to enable niche optimizations in libcore \
1153 and will never be stable",
1154 cfg_fn!(rustc_attrs))),
1155 (sym::rustc_nonnull_optimization_guaranteed, Whitelisted, template!(Word),
1156 Gated(Stability::Unstable,
1158 "the `#[rustc_nonnull_optimization_guaranteed]` attribute \
1159 is just used to enable niche optimizations in libcore \
1160 and will never be stable",
1161 cfg_fn!(rustc_attrs))),
1162 (sym::rustc_regions, Normal, template!(Word), Gated(Stability::Unstable,
1164 "the `#[rustc_regions]` attribute \
1165 is just used for rustc unit tests \
1166 and will never be stable",
1167 cfg_fn!(rustc_attrs))),
1168 (sym::rustc_error, Whitelisted, template!(Word), Gated(Stability::Unstable,
1170 "the `#[rustc_error]` attribute \
1171 is just used for rustc unit tests \
1172 and will never be stable",
1173 cfg_fn!(rustc_attrs))),
1174 (sym::rustc_dump_user_substs, Whitelisted, template!(Word), Gated(Stability::Unstable,
1177 is just used for rustc unit tests \
1178 and will never be stable",
1179 cfg_fn!(rustc_attrs))),
1180 (sym::rustc_if_this_changed, Whitelisted, template!(Word, List: "DepNode"),
1181 Gated(Stability::Unstable,
1183 "the `#[rustc_if_this_changed]` attribute \
1184 is just used for rustc unit tests \
1185 and will never be stable",
1186 cfg_fn!(rustc_attrs))),
1187 (sym::rustc_then_this_would_need, Whitelisted, template!(List: "DepNode"),
1188 Gated(Stability::Unstable,
1190 "the `#[rustc_if_this_changed]` attribute \
1191 is just used for rustc unit tests \
1192 and will never be stable",
1193 cfg_fn!(rustc_attrs))),
1194 (sym::rustc_dirty, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1195 /*opt*/ except = "...""#),
1196 Gated(Stability::Unstable,
1198 "the `#[rustc_dirty]` attribute \
1199 is just used for rustc unit tests \
1200 and will never be stable",
1201 cfg_fn!(rustc_attrs))),
1202 (sym::rustc_clean, Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1203 /*opt*/ except = "...""#),
1204 Gated(Stability::Unstable,
1206 "the `#[rustc_clean]` attribute \
1207 is just used for rustc unit tests \
1208 and will never be stable",
1209 cfg_fn!(rustc_attrs))),
1211 sym::rustc_partition_reused,
1213 template!(List: r#"cfg = "...", module = "...""#),
1215 Stability::Unstable,
1218 is just used for rustc unit tests \
1219 and will never be stable",
1220 cfg_fn!(rustc_attrs)
1224 sym::rustc_partition_codegened,
1226 template!(List: r#"cfg = "...", module = "...""#),
1228 Stability::Unstable,
1231 is just used for rustc unit tests \
1232 and will never be stable",
1233 cfg_fn!(rustc_attrs),
1236 (sym::rustc_expected_cgu_reuse, Whitelisted, template!(List: r#"cfg = "...", module = "...",
1238 Gated(Stability::Unstable,
1241 is just used for rustc unit tests \
1242 and will never be stable",
1243 cfg_fn!(rustc_attrs))),
1244 (sym::rustc_synthetic, Whitelisted, template!(Word), Gated(Stability::Unstable,
1247 is just used for rustc unit tests \
1248 and will never be stable",
1249 cfg_fn!(rustc_attrs))),
1250 (sym::rustc_symbol_name, Whitelisted, template!(Word), Gated(Stability::Unstable,
1252 "internal rustc attributes will never be stable",
1253 cfg_fn!(rustc_attrs))),
1254 (sym::rustc_def_path, Whitelisted, template!(Word), Gated(Stability::Unstable,
1256 "internal rustc attributes will never be stable",
1257 cfg_fn!(rustc_attrs))),
1258 (sym::rustc_mir, Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1260 "the `#[rustc_mir]` attribute \
1261 is just used for rustc unit tests \
1262 and will never be stable",
1263 cfg_fn!(rustc_attrs))),
1265 sym::rustc_inherit_overflow_checks,
1269 Stability::Unstable,
1271 "the `#[rustc_inherit_overflow_checks]` \
1272 attribute is just used to control \
1273 overflow checking behavior of several \
1274 libcore functions that are inlined \
1275 across crates and will never be stable",
1276 cfg_fn!(rustc_attrs),
1280 (sym::rustc_dump_program_clauses, Whitelisted, template!(Word), Gated(Stability::Unstable,
1282 "the `#[rustc_dump_program_clauses]` \
1283 attribute is just used for rustc unit \
1284 tests and will never be stable",
1285 cfg_fn!(rustc_attrs))),
1286 (sym::rustc_test_marker, Normal, template!(Word), Gated(Stability::Unstable,
1288 "the `#[rustc_test_marker]` attribute \
1289 is used internally to track tests",
1290 cfg_fn!(rustc_attrs))),
1291 (sym::rustc_transparent_macro, Whitelisted, template!(Word), Gated(Stability::Unstable,
1293 "used internally for testing macro hygiene",
1294 cfg_fn!(rustc_attrs))),
1295 (sym::compiler_builtins, Whitelisted, template!(Word), Gated(Stability::Unstable,
1296 sym::compiler_builtins,
1297 "the `#[compiler_builtins]` attribute is used to \
1298 identify the `compiler_builtins` crate which \
1299 contains compiler-rt intrinsics and will never be \
1301 cfg_fn!(compiler_builtins))),
1302 (sym::sanitizer_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1303 sym::sanitizer_runtime,
1304 "the `#[sanitizer_runtime]` attribute is used to \
1305 identify crates that contain the runtime of a \
1306 sanitizer and will never be stable",
1307 cfg_fn!(sanitizer_runtime))),
1308 (sym::profiler_runtime, Whitelisted, template!(Word), Gated(Stability::Unstable,
1309 sym::profiler_runtime,
1310 "the `#[profiler_runtime]` attribute is used to \
1311 identify the `profiler_builtins` crate which \
1312 contains the profiler runtime and will never be \
1314 cfg_fn!(profiler_runtime))),
1316 (sym::allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
1317 Gated(Stability::Unstable,
1318 sym::allow_internal_unstable,
1319 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1320 cfg_fn!(allow_internal_unstable))),
1322 (sym::allow_internal_unsafe, Normal, template!(Word), Gated(Stability::Unstable,
1323 sym::allow_internal_unsafe,
1324 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1325 cfg_fn!(allow_internal_unsafe))),
1327 (sym::fundamental, Whitelisted, template!(Word), Gated(Stability::Unstable,
1329 "the `#[fundamental]` attribute \
1330 is an experimental feature",
1331 cfg_fn!(fundamental))),
1333 (sym::proc_macro_derive, Normal, template!(List: "TraitName, \
1334 /*opt*/ attributes(name1, name2, ...)"),
1337 (sym::rustc_copy_clone_marker, Whitelisted, template!(Word), Gated(Stability::Unstable,
1339 "internal implementation detail",
1340 cfg_fn!(rustc_attrs))),
1342 (sym::rustc_allocator, Whitelisted, template!(Word), Gated(Stability::Unstable,
1344 "internal implementation detail",
1345 cfg_fn!(rustc_attrs))),
1347 (sym::rustc_dummy, Normal, template!(Word /* doesn't matter*/), Gated(Stability::Unstable,
1349 "used by the test suite",
1350 cfg_fn!(rustc_attrs))),
1352 // FIXME: #14408 whitelist docs since rustdoc looks at them
1356 template!(List: "hidden|inline|...", NameValueStr: "string"),
1360 // FIXME: #14406 these are processed in codegen, which happens after the
1362 (sym::cold, Whitelisted, template!(Word), Ungated),
1363 (sym::naked, Whitelisted, template!(Word), Gated(Stability::Unstable,
1364 sym::naked_functions,
1365 "the `#[naked]` attribute \
1366 is an experimental feature",
1367 cfg_fn!(naked_functions))),
1368 (sym::ffi_returns_twice, Whitelisted, template!(Word), Gated(Stability::Unstable,
1369 sym::ffi_returns_twice,
1370 "the `#[ffi_returns_twice]` attribute \
1371 is an experimental feature",
1372 cfg_fn!(ffi_returns_twice))),
1373 (sym::target_feature, Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1374 (sym::export_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1375 (sym::inline, Whitelisted, template!(Word, List: "always|never"), Ungated),
1376 (sym::link, Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1377 /*opt*/ cfg = "...""#), Ungated),
1378 (sym::link_name, Whitelisted, template!(NameValueStr: "name"), Ungated),
1379 (sym::link_section, Whitelisted, template!(NameValueStr: "name"), Ungated),
1380 (sym::no_builtins, Whitelisted, template!(Word), Ungated),
1381 (sym::no_debug, Whitelisted, template!(Word), Gated(
1382 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1384 "the `#[no_debug]` attribute was an experimental feature that has been \
1385 deprecated due to lack of demand",
1386 cfg_fn!(no_debug))),
1388 sym::omit_gdb_pretty_printer_section,
1392 Stability::Unstable,
1393 sym::omit_gdb_pretty_printer_section,
1394 "the `#[omit_gdb_pretty_printer_section]` \
1395 attribute is just used for the Rust test \
1397 cfg_fn!(omit_gdb_pretty_printer_section)
1400 (sym::unsafe_destructor_blind_to_params,
1403 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1404 Some("replace this attribute with `#[may_dangle]`")),
1405 sym::dropck_parametricity,
1406 "unsafe_destructor_blind_to_params has been replaced by \
1407 may_dangle and will be removed in the future",
1408 cfg_fn!(dropck_parametricity))),
1412 Gated(Stability::Unstable,
1413 sym::dropck_eyepatch,
1414 "may_dangle has unstable semantics and may be removed in the future",
1415 cfg_fn!(dropck_eyepatch))),
1416 (sym::unwind, Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1417 sym::unwind_attributes,
1418 "#[unwind] is experimental",
1419 cfg_fn!(unwind_attributes))),
1420 (sym::used, Whitelisted, template!(Word), Ungated),
1423 (sym::prelude_import, Whitelisted, template!(Word), Gated(Stability::Unstable,
1424 sym::prelude_import,
1425 "`#[prelude_import]` is for use by rustc only",
1426 cfg_fn!(prelude_import))),
1428 // FIXME: #14407 these are only looked at on-demand so we can't
1429 // guarantee they'll have already been checked
1431 sym::rustc_deprecated,
1433 template!(List: r#"since = "version", reason = "...""#),
1436 (sym::must_use, Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1440 template!(List: r#"feature = "name", since = "version""#),
1446 template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1453 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason""#,
1454 NameValueStr: "reason"
1459 (sym::rustc_paren_sugar, Normal, template!(Word), Gated(Stability::Unstable,
1460 sym::unboxed_closures,
1461 "unboxed_closures are still evolving",
1462 cfg_fn!(unboxed_closures))),
1464 (sym::windows_subsystem, Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1466 (sym::proc_macro_attribute, Normal, template!(Word), Ungated),
1467 (sym::proc_macro, Normal, template!(Word), Ungated),
1469 (sym::rustc_proc_macro_decls, Normal, template!(Word), Gated(Stability::Unstable,
1471 "used internally by rustc",
1472 cfg_fn!(rustc_attrs))),
1474 (sym::allow_fail, Normal, template!(Word), Gated(Stability::Unstable,
1476 "allow_fail attribute is currently unstable",
1477 cfg_fn!(allow_fail))),
1479 (sym::rustc_std_internal_symbol, Whitelisted, template!(Word), Gated(Stability::Unstable,
1481 "this is an internal attribute that will \
1483 cfg_fn!(rustc_attrs))),
1485 // whitelists "identity-like" conversion methods to suggest on type mismatch
1486 (sym::rustc_conversion_suggestion, Whitelisted, template!(Word), Gated(Stability::Unstable,
1488 "this is an internal attribute that will \
1490 cfg_fn!(rustc_attrs))),
1493 sym::rustc_args_required_const,
1495 template!(List: "N"),
1496 Gated(Stability::Unstable, sym::rustc_attrs, "never will be stable",
1497 cfg_fn!(rustc_attrs))
1500 (sym::panic_handler, Normal, template!(Word), Ungated),
1502 (sym::alloc_error_handler, Normal, template!(Word), Gated(Stability::Unstable,
1503 sym::alloc_error_handler,
1504 "#[alloc_error_handler] is an unstable feature",
1505 cfg_fn!(alloc_error_handler))),
1508 (sym::optimize, Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1509 sym::optimize_attribute,
1510 "#[optimize] attribute is an unstable feature",
1511 cfg_fn!(optimize_attribute))),
1513 // Crate level attributes
1514 (sym::crate_name, CrateLevel, template!(NameValueStr: "name"), Ungated),
1515 (sym::crate_type, CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1516 (sym::crate_id, CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1517 (sym::feature, CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1518 (sym::no_start, CrateLevel, template!(Word), Ungated),
1519 (sym::no_main, CrateLevel, template!(Word), Ungated),
1520 (sym::recursion_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1521 (sym::type_length_limit, CrateLevel, template!(NameValueStr: "N"), Ungated),
1522 (sym::test_runner, CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1523 sym::custom_test_frameworks,
1524 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1525 cfg_fn!(custom_test_frameworks))),
1528 pub type BuiltinAttribute = (Symbol, AttributeType, AttributeTemplate, AttributeGate);
1531 pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
1532 let mut map = FxHashMap::default();
1533 for attr in BUILTIN_ATTRIBUTES.iter() {
1534 if map.insert(attr.0, attr).is_some() {
1535 panic!("duplicate builtin attribute `{}`", attr.0);
1542 // cfg(...)'s that are feature gated
1543 const GATED_CFGS: &[(Symbol, Symbol, fn(&Features) -> bool)] = &[
1544 // (name in cfg, feature, function to check if the feature is enabled)
1545 (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
1546 (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
1547 (sym::rustdoc, sym::doc_cfg, cfg_fn!(doc_cfg)),
1551 pub struct GatedCfg {
1557 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1559 .position(|info| cfg.check_name(info.0))
1568 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1569 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1570 if !has_feature(features) && !self.span.allows_unstable(feature) {
1571 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1572 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1577 struct Context<'a> {
1578 features: &'a Features,
1579 parse_sess: &'a ParseSess,
1580 plugin_attributes: &'a [(Symbol, AttributeType)],
1583 macro_rules! gate_feature_fn {
1584 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1585 let (cx, has_feature, span,
1586 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1587 let has_feature: bool = has_feature(&$cx.features);
1588 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1589 if !has_feature && !span.allows_unstable($name) {
1590 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1596 macro_rules! gate_feature {
1597 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1598 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1599 sym::$feature, $explain, GateStrength::Hard)
1601 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1602 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1603 sym::$feature, $explain, $level)
1607 impl<'a> Context<'a> {
1610 attr: &ast::Attribute,
1611 attr_info: Option<&BuiltinAttribute>,
1614 debug!("check_attribute(attr = {:?})", attr);
1615 if let Some(&(name, ty, _template, ref gateage)) = attr_info {
1616 if let Gated(_, name, desc, ref has_feature) = *gateage {
1617 if !attr.span.allows_unstable(name) {
1619 self, has_feature, attr.span, name, desc, GateStrength::Hard
1622 } else if name == sym::doc {
1623 if let Some(content) = attr.meta_item_list() {
1624 if content.iter().any(|c| c.check_name(sym::include)) {
1625 gate_feature!(self, external_doc, attr.span,
1626 "#[doc(include = \"...\")] is experimental"
1631 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1634 for &(n, ty) in self.plugin_attributes {
1636 // Plugins can't gate attributes, so we don't check for it
1637 // unlike the code above; we only use this loop to
1638 // short-circuit to avoid the checks below.
1639 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1643 if !attr::is_known(attr) {
1644 if attr.name_or_empty().as_str().starts_with("rustc_") {
1645 let msg = "unless otherwise specified, attributes with the prefix `rustc_` \
1646 are reserved for internal compiler diagnostics";
1647 gate_feature!(self, rustc_attrs, attr.span, msg);
1648 } else if !is_macro {
1649 // Only run the custom attribute lint during regular feature gate
1650 // checking. Macro gating runs before the plugin attributes are
1651 // registered, so we skip this in that case.
1652 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1653 may have meaning added to it in the future", attr.path);
1654 gate_feature!(self, custom_attribute, attr.span, &msg);
1660 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1661 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1664 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name).map(|a| *a)),
1669 fn find_lang_feature_issue(feature: Symbol) -> Option<u32> {
1670 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1672 // FIXME (#28244): enforce that active features have issue numbers
1673 // assert!(issue.is_some())
1676 // search in Accepted, Removed, or Stable Removed features
1677 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1678 .find(|t| t.0 == feature);
1680 Some(&(_, _, issue, _)) => issue,
1681 None => panic!("Feature `{}` is not declared anywhere", feature),
1686 pub enum GateIssue {
1688 Library(Option<u32>)
1691 #[derive(Debug, Copy, Clone, PartialEq)]
1692 pub enum GateStrength {
1693 /// A hard error. (Most feature gates should use this.)
1695 /// Only a warning. (Use this only as backwards-compatibility demands.)
1699 pub fn emit_feature_err(
1706 feature_err(sess, feature, span, issue, explain).emit();
1709 pub fn feature_err<'a>(
1710 sess: &'a ParseSess,
1715 ) -> DiagnosticBuilder<'a> {
1716 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1719 fn leveled_feature_err<'a>(
1720 sess: &'a ParseSess,
1725 level: GateStrength,
1726 ) -> DiagnosticBuilder<'a> {
1727 let diag = &sess.span_diagnostic;
1729 let issue = match issue {
1730 GateIssue::Language => find_lang_feature_issue(feature),
1731 GateIssue::Library(lib) => lib,
1734 let mut err = match level {
1735 GateStrength::Hard => {
1736 diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
1738 GateStrength::Soft => diag.struct_span_warn(span, explain),
1742 None | Some(0) => {} // We still accept `0` as a stand-in for backwards compatibility
1745 "for more information, see https://github.com/rust-lang/rust/issues/{}",
1751 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1752 if sess.unstable_features.is_nightly_build() {
1753 err.help(&format!("add #![feature({})] to the crate attributes to enable", feature));
1756 // If we're on stable and only emitting a "soft" warning, add a note to
1757 // clarify that the feature isn't "on" (rather than being on but
1759 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1760 err.help("a nightly build of the compiler is required to enable this feature");
1767 const EXPLAIN_BOX_SYNTAX: &str =
1768 "box expression syntax is experimental; you can call `Box::new` instead";
1770 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1771 "attributes on expressions are experimental";
1773 pub const EXPLAIN_ASM: &str =
1774 "inline assembly is not stable enough for use and is subject to change";
1776 pub const EXPLAIN_GLOBAL_ASM: &str =
1777 "`global_asm!` is not stable enough for use and is subject to change";
1779 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str =
1780 "custom test frameworks are an unstable feature";
1782 pub const EXPLAIN_LOG_SYNTAX: &str =
1783 "`log_syntax!` is not stable enough for use and is subject to change";
1785 pub const EXPLAIN_CONCAT_IDENTS: &str =
1786 "`concat_idents` is not stable enough for use and is subject to change";
1788 pub const EXPLAIN_FORMAT_ARGS_NL: &str =
1789 "`format_args_nl` is only for internal language use and is subject to change";
1791 pub const EXPLAIN_TRACE_MACROS: &str =
1792 "`trace_macros` is not stable enough for use and is subject to change";
1793 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1794 "allow_internal_unstable side-steps feature gating and stability checks";
1795 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1796 "allow_internal_unsafe side-steps the unsafe_code lint";
1798 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1799 "unsized tuple coercion is not stable enough for use and is subject to change";
1801 struct PostExpansionVisitor<'a> {
1802 context: &'a Context<'a>,
1803 builtin_attributes: &'static FxHashMap<Symbol, &'static BuiltinAttribute>,
1806 macro_rules! gate_feature_post {
1807 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1808 let (cx, span) = ($cx, $span);
1809 if !span.allows_unstable(sym::$feature) {
1810 gate_feature!(cx.context, $feature, span, $explain)
1813 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1814 let (cx, span) = ($cx, $span);
1815 if !span.allows_unstable(sym::$feature) {
1816 gate_feature!(cx.context, $feature, span, $explain, $level)
1821 impl<'a> PostExpansionVisitor<'a> {
1822 fn check_abi(&self, abi: Abi, span: Span) {
1824 Abi::RustIntrinsic => {
1825 gate_feature_post!(&self, intrinsics, span,
1826 "intrinsics are subject to change");
1828 Abi::PlatformIntrinsic => {
1829 gate_feature_post!(&self, platform_intrinsics, span,
1830 "platform intrinsics are experimental and possibly buggy");
1832 Abi::Vectorcall => {
1833 gate_feature_post!(&self, abi_vectorcall, span,
1834 "vectorcall is experimental and subject to change");
1837 gate_feature_post!(&self, abi_thiscall, span,
1838 "thiscall is experimental and subject to change");
1841 gate_feature_post!(&self, unboxed_closures, span,
1842 "rust-call ABI is subject to change");
1845 gate_feature_post!(&self, abi_ptx, span,
1846 "PTX ABIs are experimental and subject to change");
1848 Abi::Unadjusted => {
1849 gate_feature_post!(&self, abi_unadjusted, span,
1850 "unadjusted ABI is an implementation detail and perma-unstable");
1852 Abi::Msp430Interrupt => {
1853 gate_feature_post!(&self, abi_msp430_interrupt, span,
1854 "msp430-interrupt ABI is experimental and subject to change");
1856 Abi::X86Interrupt => {
1857 gate_feature_post!(&self, abi_x86_interrupt, span,
1858 "x86-interrupt ABI is experimental and subject to change");
1860 Abi::AmdGpuKernel => {
1861 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1862 "amdgpu-kernel ABI is experimental and subject to change");
1877 fn check_builtin_attribute(&mut self, attr: &ast::Attribute, name: Symbol,
1878 template: AttributeTemplate) {
1879 // Some special attributes like `cfg` must be checked
1880 // before the generic check, so we skip them here.
1881 let should_skip = |name| name == sym::cfg;
1882 // Some of previously accepted forms were used in practice,
1883 // report them as warnings for now.
1884 let should_warn = |name| name == sym::doc || name == sym::ignore ||
1885 name == sym::inline || name == sym::link;
1887 match attr.parse_meta(self.context.parse_sess) {
1888 Ok(meta) => if !should_skip(name) && !template.compatible(&meta.node) {
1889 let error_msg = format!("malformed `{}` attribute input", name);
1890 let mut msg = "attribute must be of the form ".to_owned();
1891 let mut suggestions = vec![];
1892 let mut first = true;
1895 let code = format!("#[{}]", name);
1896 msg.push_str(&format!("`{}`", &code));
1897 suggestions.push(code);
1899 if let Some(descr) = template.list {
1901 msg.push_str(" or ");
1904 let code = format!("#[{}({})]", name, descr);
1905 msg.push_str(&format!("`{}`", &code));
1906 suggestions.push(code);
1908 if let Some(descr) = template.name_value_str {
1910 msg.push_str(" or ");
1912 let code = format!("#[{} = \"{}\"]", name, descr);
1913 msg.push_str(&format!("`{}`", &code));
1914 suggestions.push(code);
1916 if should_warn(name) {
1917 self.context.parse_sess.buffer_lint(
1918 BufferedEarlyLintId::IllFormedAttributeInput,
1924 self.context.parse_sess.span_diagnostic.struct_span_err(meta.span, &error_msg)
1927 if suggestions.len() == 1 {
1928 "must be of the form"
1930 "the following are the possible correct uses"
1932 suggestions.into_iter(),
1933 Applicability::HasPlaceholders,
1937 Err(mut err) => err.emit(),
1942 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1943 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1944 let attr_info = attr.ident().and_then(|ident| {
1945 self.builtin_attributes.get(&ident.name).map(|a| *a)
1948 // Check for gated attributes.
1949 self.context.check_attribute(attr, attr_info, false);
1951 if attr.check_name(sym::doc) {
1952 if let Some(content) = attr.meta_item_list() {
1953 if content.len() == 1 && content[0].check_name(sym::cfg) {
1954 gate_feature_post!(&self, doc_cfg, attr.span,
1955 "#[doc(cfg(...))] is experimental"
1957 } else if content.iter().any(|c| c.check_name(sym::masked)) {
1958 gate_feature_post!(&self, doc_masked, attr.span,
1959 "#[doc(masked)] is experimental"
1961 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
1962 gate_feature_post!(&self, doc_spotlight, attr.span,
1963 "#[doc(spotlight)] is experimental"
1965 } else if content.iter().any(|c| c.check_name(sym::alias)) {
1966 gate_feature_post!(&self, doc_alias, attr.span,
1967 "#[doc(alias = \"...\")] is experimental"
1969 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
1970 gate_feature_post!(&self, doc_keyword, attr.span,
1971 "#[doc(keyword = \"...\")] is experimental"
1978 // `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
1979 Some(&(name, _, template, _)) if name != sym::rustc_dummy =>
1980 self.check_builtin_attribute(attr, name, template),
1981 _ => if let Some(TokenTree::Token(token)) = attr.tokens.trees().next() {
1982 if token == token::Eq {
1983 // All key-value attributes are restricted to meta-item syntax.
1984 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
1990 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1991 if !name.as_str().is_ascii() {
1995 self.context.parse_sess.source_map().def_span(sp),
1996 "non-ascii idents are not fully supported"
2001 fn visit_item(&mut self, i: &'a ast::Item) {
2003 ast::ItemKind::Const(_,_) => {
2004 if i.ident.name == kw::Underscore {
2005 gate_feature_post!(&self, underscore_const_names, i.span,
2006 "naming constants with `_` is unstable");
2010 ast::ItemKind::ForeignMod(ref foreign_module) => {
2011 self.check_abi(foreign_module.abi, i.span);
2014 ast::ItemKind::Fn(..) => {
2015 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
2016 gate_feature_post!(&self, plugin_registrar, i.span,
2017 "compiler plugins are experimental and possibly buggy");
2019 if attr::contains_name(&i.attrs[..], sym::start) {
2020 gate_feature_post!(&self, start, i.span,
2021 "a #[start] function is an experimental \
2022 feature whose signature may change \
2025 if attr::contains_name(&i.attrs[..], sym::main) {
2026 gate_feature_post!(&self, main, i.span,
2027 "declaration of a nonstandard #[main] \
2028 function may change over time, for now \
2029 a top-level `fn main()` is required");
2033 ast::ItemKind::Struct(..) => {
2034 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
2035 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
2036 if item.check_name(sym::simd) {
2037 gate_feature_post!(&self, repr_simd, attr.span,
2038 "SIMD types are experimental and possibly buggy");
2044 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
2045 if polarity == ast::ImplPolarity::Negative {
2046 gate_feature_post!(&self, optin_builtin_traits,
2048 "negative trait bounds are not yet fully implemented; \
2049 use marker types for now");
2052 if let ast::Defaultness::Default = defaultness {
2053 gate_feature_post!(&self, specialization,
2055 "specialization is unstable");
2059 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2060 gate_feature_post!(&self, optin_builtin_traits,
2062 "auto traits are experimental and possibly buggy");
2065 ast::ItemKind::TraitAlias(..) => {
2070 "trait aliases are experimental"
2074 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2075 let msg = "`macro` is experimental";
2076 gate_feature_post!(&self, decl_macro, i.span, msg);
2079 ast::ItemKind::Existential(..) => {
2084 "existential types are unstable"
2091 visit::walk_item(self, i);
2094 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2096 ast::ForeignItemKind::Fn(..) |
2097 ast::ForeignItemKind::Static(..) => {
2098 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2099 let links_to_llvm = match link_name {
2100 Some(val) => val.as_str().starts_with("llvm."),
2104 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2105 "linking to LLVM intrinsics is experimental");
2108 ast::ForeignItemKind::Ty => {
2109 gate_feature_post!(&self, extern_types, i.span,
2110 "extern types are experimental");
2112 ast::ForeignItemKind::Macro(..) => {}
2115 visit::walk_foreign_item(self, i)
2118 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2120 ast::TyKind::BareFn(ref bare_fn_ty) => {
2121 self.check_abi(bare_fn_ty.abi, ty.span);
2123 ast::TyKind::Never => {
2124 gate_feature_post!(&self, never_type, ty.span,
2125 "The `!` type is experimental");
2129 visit::walk_ty(self, ty)
2132 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2133 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2134 if let ast::TyKind::Never = output_ty.node {
2137 self.visit_ty(output_ty)
2142 fn visit_expr(&mut self, e: &'a ast::Expr) {
2144 ast::ExprKind::Box(_) => {
2145 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2147 ast::ExprKind::Type(..) => {
2148 // To avoid noise about type ascription in common syntax errors, only emit if it
2149 // is the *only* error.
2150 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2151 gate_feature_post!(&self, type_ascription, e.span,
2152 "type ascription is experimental");
2155 ast::ExprKind::Yield(..) => {
2156 gate_feature_post!(&self, generators,
2158 "yield syntax is experimental");
2160 ast::ExprKind::TryBlock(_) => {
2161 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2163 ast::ExprKind::Block(_, opt_label) => {
2164 if let Some(label) = opt_label {
2165 gate_feature_post!(&self, label_break_value, label.ident.span,
2166 "labels on blocks are unstable");
2169 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
2170 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
2172 ast::ExprKind::Async(..) => {
2173 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2175 ast::ExprKind::Await(origin, _) => {
2177 ast::AwaitOrigin::FieldLike =>
2178 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2179 ast::AwaitOrigin::MacroLike =>
2184 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2185 in favor of `<expr>.await` syntax."
2191 visit::walk_expr(self, e)
2194 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2195 visit::walk_arm(self, arm)
2198 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2199 match pattern.node {
2200 PatKind::Slice(_, Some(ref subslice), _) => {
2201 gate_feature_post!(&self, slice_patterns,
2203 "syntax for subslices in slice patterns is not yet stabilized");
2205 PatKind::Box(..) => {
2206 gate_feature_post!(&self, box_patterns,
2208 "box pattern syntax is experimental");
2210 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2211 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2212 "exclusive range pattern syntax is experimental");
2216 visit::walk_pat(self, pattern)
2219 fn visit_fn(&mut self,
2220 fn_kind: FnKind<'a>,
2221 fn_decl: &'a ast::FnDecl,
2224 if let Some(header) = fn_kind.header() {
2225 // Check for const fn and async fn declarations.
2226 if header.asyncness.node.is_async() {
2227 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2230 // Stability of const fn methods are covered in
2231 // `visit_trait_item` and `visit_impl_item` below; this is
2232 // because default methods don't pass through this point.
2233 self.check_abi(header.abi, span);
2236 if fn_decl.c_variadic {
2237 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2240 visit::walk_fn(self, fn_kind, fn_decl, span)
2243 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2245 GenericParamKind::Const { .. } =>
2246 gate_feature_post!(&self, const_generics, param.ident.span,
2247 "const generics are unstable"),
2250 visit::walk_generic_param(self, param)
2253 fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) {
2254 match constraint.kind {
2255 AssocTyConstraintKind::Bound { .. } =>
2256 gate_feature_post!(&self, associated_type_bounds, constraint.span,
2257 "associated type bounds are unstable"),
2260 visit::walk_assoc_ty_constraint(self, constraint)
2263 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2265 ast::TraitItemKind::Method(ref sig, ref block) => {
2266 if block.is_none() {
2267 self.check_abi(sig.header.abi, ti.span);
2269 if sig.header.asyncness.node.is_async() {
2270 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2272 if sig.decl.c_variadic {
2273 gate_feature_post!(&self, c_variadic, ti.span,
2274 "C-variadic functions are unstable");
2276 if sig.header.constness.node == ast::Constness::Const {
2277 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2280 ast::TraitItemKind::Type(_, ref default) => {
2281 // We use three if statements instead of something like match guards so that all
2282 // of these errors can be emitted if all cases apply.
2283 if default.is_some() {
2284 gate_feature_post!(&self, associated_type_defaults, ti.span,
2285 "associated type defaults are unstable");
2287 if !ti.generics.params.is_empty() {
2288 gate_feature_post!(&self, generic_associated_types, ti.span,
2289 "generic associated types are unstable");
2291 if !ti.generics.where_clause.predicates.is_empty() {
2292 gate_feature_post!(&self, generic_associated_types, ti.span,
2293 "where clauses on associated types are unstable");
2298 visit::walk_trait_item(self, ti)
2301 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2302 if ii.defaultness == ast::Defaultness::Default {
2303 gate_feature_post!(&self, specialization,
2305 "specialization is unstable");
2309 ast::ImplItemKind::Method(..) => {}
2310 ast::ImplItemKind::Existential(..) => {
2315 "existential types are unstable"
2318 ast::ImplItemKind::Type(_) => {
2319 if !ii.generics.params.is_empty() {
2320 gate_feature_post!(&self, generic_associated_types, ii.span,
2321 "generic associated types are unstable");
2323 if !ii.generics.where_clause.predicates.is_empty() {
2324 gate_feature_post!(&self, generic_associated_types, ii.span,
2325 "where clauses on associated types are unstable");
2330 visit::walk_impl_item(self, ii)
2333 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2334 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2335 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2336 "`crate` visibility modifier is experimental");
2338 visit::walk_vis(self, vis)
2342 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2343 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2344 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2345 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2346 if let Some(reason) = reason {
2347 err.span_note(span, reason);
2349 err.span_label(span, "feature has been removed");
2354 let mut features = Features::new();
2355 let mut edition_enabled_features = FxHashMap::default();
2357 for &edition in ALL_EDITIONS {
2358 if edition <= crate_edition {
2359 // The `crate_edition` implies its respective umbrella feature-gate
2360 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2361 edition_enabled_features.insert(edition.feature_name(), edition);
2365 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2366 if let Some(f_edition) = f_edition {
2367 if f_edition <= crate_edition {
2368 set(&mut features, DUMMY_SP);
2369 edition_enabled_features.insert(name, crate_edition);
2374 // Process the edition umbrella feature-gates first, to ensure
2375 // `edition_enabled_features` is completed before it's queried.
2376 for attr in krate_attrs {
2377 if !attr.check_name(sym::feature) {
2381 let list = match attr.meta_item_list() {
2391 let name = mi.name_or_empty();
2392 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2393 span_handler.struct_span_warn(
2396 "the feature `{}` is incomplete and may cause the compiler to crash",
2402 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2403 if *edition <= crate_edition {
2407 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2408 if let Some(f_edition) = f_edition {
2409 if f_edition <= *edition {
2410 // FIXME(Manishearth) there is currently no way to set
2411 // lib features by edition
2412 set(&mut features, DUMMY_SP);
2413 edition_enabled_features.insert(name, *edition);
2421 for attr in krate_attrs {
2422 if !attr.check_name(sym::feature) {
2426 let list = match attr.meta_item_list() {
2431 let bad_input = |span| {
2432 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
2436 let name = match mi.ident() {
2437 Some(ident) if mi.is_word() => ident.name,
2439 bad_input(mi.span()).span_suggestion(
2441 "expected just one word",
2442 format!("{}", ident.name),
2443 Applicability::MaybeIncorrect,
2448 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
2453 if let Some(edition) = edition_enabled_features.get(&name) {
2458 "the feature `{}` is included in the Rust {} edition",
2465 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2466 // Handled in the separate loop above.
2470 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2471 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2472 if let Some((.., reason)) = removed.or(stable_removed) {
2473 feature_removed(span_handler, mi.span(), *reason);
2477 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2478 let since = Some(Symbol::intern(since));
2479 features.declared_lang_features.push((name, mi.span(), since));
2483 if let Some(allowed) = allow_features.as_ref() {
2484 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2485 span_err!(span_handler, mi.span(), E0725,
2486 "the feature `{}` is not in the list of allowed features",
2492 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2493 set(&mut features, mi.span());
2494 features.declared_lang_features.push((name, mi.span(), None));
2498 features.declared_lib_features.push((name, mi.span()));
2505 pub fn check_crate(krate: &ast::Crate,
2507 features: &Features,
2508 plugin_attributes: &[(Symbol, AttributeType)],
2509 unstable: UnstableFeatures) {
2510 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2521 .for_each(|span| gate_feature!(
2525 "attributes on function parameters are unstable"
2528 let visitor = &mut PostExpansionVisitor {
2530 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2532 visit::walk_crate(visitor, krate);
2535 #[derive(Clone, Copy, Hash)]
2536 pub enum UnstableFeatures {
2537 /// Hard errors for unstable features are active, as on beta/stable channels.
2539 /// Allow features to be activated, as on nightly.
2541 /// Errors are bypassed for bootstrapping. This is required any time
2542 /// during the build that feature-related lints are set to warn or above
2543 /// because the build turns on warnings-as-errors and uses lots of unstable
2544 /// features. As a result, this is always required for building Rust itself.
2548 impl UnstableFeatures {
2549 pub fn from_environment() -> UnstableFeatures {
2550 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2551 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2552 // Whether we should enable unstable features for bootstrapping
2553 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2554 match (disable_unstable_features, bootstrap) {
2555 (_, true) => UnstableFeatures::Cheat,
2556 (true, _) => UnstableFeatures::Disallow,
2557 (false, _) => UnstableFeatures::Allow
2561 pub fn is_nightly_build(&self) -> bool {
2563 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2569 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2570 unstable: UnstableFeatures) {
2571 let allow_features = match unstable {
2572 UnstableFeatures::Allow => true,
2573 UnstableFeatures::Disallow => false,
2574 UnstableFeatures::Cheat => true
2576 if !allow_features {
2577 for attr in &krate.attrs {
2578 if attr.check_name(sym::feature) {
2579 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2580 span_err!(span_handler, attr.span, E0554,
2581 "#![feature] may not be used on the {} release channel",