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::{Applicability, 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 `#[repr(align(X))]` on enums.
552 (active, repr_align_enum, "1.34.0", Some(57996), None),
554 // Allows using C-variadics.
555 (active, c_variadic, "1.34.0", Some(44930), None),
557 // -------------------------------------------------------------------------
558 // feature-group-end: actual feature gates
559 // -------------------------------------------------------------------------
562 // Some features are known to be incomplete and using them is likely to have
563 // unanticipated results, such as compiler crashes. We warn the user about these
565 const INCOMPLETE_FEATURES: &[Symbol] = &[
566 sym::impl_trait_in_bindings,
567 sym::generic_associated_types,
572 // -------------------------------------------------------------------------
573 // feature-group-start: removed features
574 // -------------------------------------------------------------------------
576 (removed, import_shadowing, "1.0.0", None, None, None),
577 (removed, managed_boxes, "1.0.0", None, None, None),
578 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
579 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
580 (removed, reflect, "1.0.0", Some(27749), None, None),
581 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
582 (removed, opt_out_copy, "1.0.0", None, None, None),
583 (removed, quad_precision_float, "1.0.0", None, None, None),
584 (removed, struct_inherit, "1.0.0", None, None, None),
585 (removed, test_removed_feature, "1.0.0", None, None, None),
586 (removed, visible_private_types, "1.0.0", None, None, None),
587 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
588 // Allows using items which are missing stability attributes
589 (removed, unmarked_api, "1.0.0", None, None, None),
590 (removed, allocator, "1.0.0", None, None, None),
591 (removed, simd, "1.0.0", Some(27731), None,
592 Some("removed in favor of `#[repr(simd)]`")),
593 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
594 Some("merged into `#![feature(slice_patterns)]`")),
595 (removed, macro_reexport, "1.0.0", Some(29638), None,
596 Some("subsumed by `pub use`")),
597 (removed, pushpop_unsafe, "1.2.0", None, None, None),
598 (removed, needs_allocator, "1.4.0", Some(27389), None,
599 Some("subsumed by `#![feature(allocator_internals)]`")),
600 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
601 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
602 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
603 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
604 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
605 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
606 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
607 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
608 (removed, panic_implementation, "1.28.0", Some(44489), None,
609 Some("subsumed by `#[panic_handler]`")),
610 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
611 (removed, custom_derive, "1.32.0", Some(29644), None,
612 Some("subsumed by `#[proc_macro_derive]`")),
613 // Paths of the form: `extern::foo::bar`
614 (removed, extern_in_paths, "1.33.0", Some(55600), None,
615 Some("subsumed by `::foo::bar` paths")),
616 (removed, quote, "1.33.0", Some(29601), None, None),
618 // -------------------------------------------------------------------------
619 // feature-group-end: removed features
620 // -------------------------------------------------------------------------
624 (stable_removed, no_stack_check, "1.0.0", None, None),
628 // -------------------------------------------------------------------------
629 // feature-group-start: for testing purposes
630 // -------------------------------------------------------------------------
632 // A temporary feature gate used to enable parser extensions needed
633 // to bootstrap fix for #5723.
634 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
635 // These are used to test this portion of the compiler,
636 // they don't actually mean anything.
637 (accepted, test_accepted_feature, "1.0.0", None, None),
639 // -------------------------------------------------------------------------
640 // feature-group-end: for testing purposes
641 // -------------------------------------------------------------------------
643 // -------------------------------------------------------------------------
644 // feature-group-start: accepted features
645 // -------------------------------------------------------------------------
647 // Allows using associated `type`s in `trait`s.
648 (accepted, associated_types, "1.0.0", None, None),
649 // Allows using assigning a default type to type parameters in algebraic data type definitions.
650 (accepted, default_type_params, "1.0.0", None, None),
651 // FIXME: explain `globs`.
652 (accepted, globs, "1.0.0", None, None),
653 // Allows `macro_rules!` items.
654 (accepted, macro_rules, "1.0.0", None, None),
655 // Allows use of `&foo[a..b]` as a slicing syntax.
656 (accepted, slicing_syntax, "1.0.0", None, None),
657 // Allows struct variants `Foo { baz: u8, .. }` in enums (RFC 418).
658 (accepted, struct_variant, "1.0.0", None, None),
659 // Allows indexing tuples.
660 (accepted, tuple_indexing, "1.0.0", None, None),
661 // Allows the use of `if let` expressions.
662 (accepted, if_let, "1.0.0", None, None),
663 // Allows the use of `while let` expressions.
664 (accepted, while_let, "1.0.0", None, None),
665 // Allows using `#![no_std]`.
666 (accepted, no_std, "1.6.0", None, None),
667 // Allows overloading augmented assignment operations like `a += b`.
668 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
669 // Allows empty structs and enum variants with braces.
670 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
671 // Allows `#[deprecated]` attribute.
672 (accepted, deprecated, "1.9.0", Some(29935), None),
673 // Allows macros to appear in the type position.
674 (accepted, type_macros, "1.13.0", Some(27245), None),
675 // Allows use of the postfix `?` operator in expressions.
676 (accepted, question_mark, "1.13.0", Some(31436), None),
677 // Allows `..` in tuple (struct) patterns.
678 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
679 // Allows some increased flexibility in the name resolution rules,
680 // especially around globs and shadowing (RFC 1560).
681 (accepted, item_like_imports, "1.15.0", Some(35120), None),
682 // Allows using `Self` and associated types in struct expressions and patterns.
683 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
684 // Allows elision of `'static` lifetimes in `static`s and `const`s.
685 (accepted, static_in_const, "1.17.0", Some(35897), None),
686 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
687 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
688 // Allows the definition recursive static items.
689 (accepted, static_recursion, "1.17.0", Some(29719), None),
690 // Allows `pub(restricted)` visibilities (RFC 1422).
691 (accepted, pub_restricted, "1.18.0", Some(32409), None),
692 // Allows `#![windows_subsystem]`.
693 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
694 // Allows `break {expr}` with a value inside `loop`s.
695 (accepted, loop_break_value, "1.19.0", Some(37339), None),
696 // Allows numeric fields in struct expressions and patterns.
697 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
698 // Allows coercing non capturing closures to function pointers.
699 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
700 // Allows attributes on struct literal fields.
701 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
702 // Allows the definition of associated constants in `trait` or `impl` blocks.
703 (accepted, associated_consts, "1.20.0", Some(29646), None),
704 // Allows usage of the `compile_error!` macro.
705 (accepted, compile_error, "1.20.0", Some(40872), None),
706 // Allows code like `let x: &'static u32 = &42` to work (RFC 1414).
707 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
708 // Allows `Drop` types in constants (RFC 1440).
709 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
710 // Allows the sysV64 ABI to be specified on all platforms
711 // instead of just the platforms on which it is the C ABI.
712 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
713 // Allows `repr(align(16))` struct attribute (RFC 1358).
714 (accepted, repr_align, "1.25.0", Some(33626), None),
715 // Allows '|' at beginning of match arms (RFC 1925).
716 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
717 // Allows nested groups in `use` items (RFC 2128).
718 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
719 // Allows indexing into constant arrays.
720 (accepted, const_indexing, "1.26.0", Some(29947), None),
721 // Allows using `a..=b` and `..=b` as inclusive range syntaxes.
722 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
723 // Allows `..=` in patterns (RFC 1192).
724 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
725 // Allows `fn main()` with return types which implements `Termination` (RFC 1937).
726 (accepted, termination_trait, "1.26.0", Some(43301), None),
727 // Allows implementing `Clone` for closures where possible (RFC 2132).
728 (accepted, clone_closures, "1.26.0", Some(44490), None),
729 // Allows implementing `Copy` for closures where possible (RFC 2132).
730 (accepted, copy_closures, "1.26.0", Some(44490), None),
731 // Allows `impl Trait` in function arguments.
732 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
733 // Allows `impl Trait` in function return types.
734 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
735 // Allows using the `u128` and `i128` types.
736 (accepted, i128_type, "1.26.0", Some(35118), None),
737 // Allows default match binding modes (RFC 2005).
738 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
739 // Allows `'_` placeholder lifetimes.
740 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
741 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
742 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
743 // Allows `cfg(target_feature = "...")`.
744 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
745 // Allows `#[target_feature(...)]`.
746 (accepted, target_feature, "1.27.0", None, None),
747 // Allows using `dyn Trait` as a syntax for trait objects.
748 (accepted, dyn_trait, "1.27.0", Some(44662), None),
749 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
750 (accepted, fn_must_use, "1.27.0", Some(43302), None),
751 // Allows use of the `:lifetime` macro fragment specifier.
752 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
753 // Allows `#[test]` functions where the return type implements `Termination` (RFC 1937).
754 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
755 // Allows the `#[global_allocator]` attribute.
756 (accepted, global_allocator, "1.28.0", Some(27389), None),
757 // Allows `#[repr(transparent)]` attribute on newtype structs.
758 (accepted, repr_transparent, "1.28.0", Some(43036), None),
759 // Allows procedural macros in `proc-macro` crates.
760 (accepted, proc_macro, "1.29.0", Some(38356), None),
761 // Allows `foo.rs` as an alternative to `foo/mod.rs`.
762 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
763 // Allows use of the `:vis` macro fragment specifier
764 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
765 // Allows importing and reexporting macros with `use`,
766 // enables macro modularization in general.
767 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
768 // Allows keywords to be escaped for use as identifiers.
769 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
770 // Allows attributes scoped to tools.
771 (accepted, tool_attributes, "1.30.0", Some(44690), None),
772 // Allows multi-segment paths in attributes and derives.
773 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
774 // Allows all literals in attribute lists and values of key-value pairs.
775 (accepted, attr_literals, "1.30.0", Some(34981), None),
776 // Allows inferring outlives requirements (RFC 2093).
777 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
778 // Allows annotating functions conforming to `fn(&PanicInfo) -> !` with `#[panic_handler]`.
779 // This defines the behavior of panics.
780 (accepted, panic_handler, "1.30.0", Some(44489), None),
781 // Allows `#[used]` to preserve symbols (see llvm.used).
782 (accepted, used, "1.30.0", Some(40289), None),
783 // Allows `crate` in paths.
784 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
785 // Allows resolving absolute paths as paths from other crates.
786 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
787 // Allows access to crate names passed via `--extern` through prelude.
788 (accepted, extern_prelude, "1.30.0", Some(44660), None),
789 // Allows parentheses in patterns.
790 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
791 // Allows the definition of `const fn` functions.
792 (accepted, min_const_fn, "1.31.0", Some(53555), None),
793 // Allows scoped lints.
794 (accepted, tool_lints, "1.31.0", Some(44690), None),
795 // Allows lifetime elision in `impl` headers. For example:
796 // + `impl<I:Iterator> Iterator for &mut Iterator`
797 // + `impl Debug for Foo<'_>`
798 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
799 // Allows `extern crate foo as bar;`. This puts `bar` into extern prelude.
800 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
801 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
802 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
803 // Allows use of `?` as the Kleene "at most one" operator in macros.
804 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
805 // Allows `Self` struct constructor (RFC 2302).
806 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
807 // Allows `Self` in type definitions (RFC 2300).
808 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
809 // Allows `use x::y;` to search `x` in the current scope.
810 (accepted, uniform_paths, "1.32.0", Some(53130), None),
811 // Allows integer match exhaustiveness checking (RFC 2591).
812 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
813 // Allows `use path as _;` and `extern crate c as _;`.
814 (accepted, underscore_imports, "1.33.0", Some(48216), None),
815 // Allows `#[repr(packed(N))]` attribute on structs.
816 (accepted, repr_packed, "1.33.0", Some(33158), None),
817 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
818 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
819 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
820 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
821 // Allows let bindings, assignments and destructuring in `const` functions and constants.
822 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
823 // at the same time as let bindings.
824 (accepted, const_let, "1.33.0", Some(48821), None),
825 // Allows `#[cfg_attr(predicate, multiple, attributes, here)]`.
826 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
827 // Allows top level or-patterns (`p | q`) in `if let` and `while let`.
828 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
829 // Allows `cfg(target_vendor = "...")`.
830 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
831 // Allows `extern crate self as foo;`.
832 // This puts local crate root into extern prelude under name `foo`.
833 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
834 // Allows arbitrary delimited token streams in non-macro attributes.
835 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), 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 error_msg = format!("malformed `{}` attribute input", name);
1862 let mut msg = "attribute must be of the form ".to_owned();
1863 let mut suggestions = vec![];
1864 let mut first = true;
1867 let code = format!("#[{}]", name);
1868 msg.push_str(&format!("`{}`", &code));
1869 suggestions.push(code);
1871 if let Some(descr) = template.list {
1873 msg.push_str(" or ");
1876 let code = format!("#[{}({})]", name, descr);
1877 msg.push_str(&format!("`{}`", &code));
1878 suggestions.push(code);
1880 if let Some(descr) = template.name_value_str {
1882 msg.push_str(" or ");
1884 let code = format!("#[{} = \"{}\"]", name, descr);
1885 msg.push_str(&format!("`{}`", &code));
1886 suggestions.push(code);
1888 if should_warn(name) {
1889 self.context.parse_sess.buffer_lint(
1890 BufferedEarlyLintId::IllFormedAttributeInput,
1896 self.context.parse_sess.span_diagnostic.struct_span_err(meta.span, &error_msg)
1899 if suggestions.len() == 1 {
1900 "must be of the form"
1902 "the following are the possible correct uses"
1904 suggestions.into_iter(),
1905 Applicability::HasPlaceholders,
1909 Err(mut err) => err.emit(),
1914 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1915 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1916 let attr_info = attr.ident().and_then(|ident| {
1917 self.builtin_attributes.get(&ident.name).map(|a| *a)
1920 // check for gated attributes
1921 self.context.check_attribute(attr, attr_info, false);
1923 if attr.check_name(sym::doc) {
1924 if let Some(content) = attr.meta_item_list() {
1925 if content.len() == 1 && content[0].check_name(sym::cfg) {
1926 gate_feature_post!(&self, doc_cfg, attr.span,
1927 "#[doc(cfg(...))] is experimental"
1929 } else if content.iter().any(|c| c.check_name(sym::masked)) {
1930 gate_feature_post!(&self, doc_masked, attr.span,
1931 "#[doc(masked)] is experimental"
1933 } else if content.iter().any(|c| c.check_name(sym::spotlight)) {
1934 gate_feature_post!(&self, doc_spotlight, attr.span,
1935 "#[doc(spotlight)] is experimental"
1937 } else if content.iter().any(|c| c.check_name(sym::alias)) {
1938 gate_feature_post!(&self, doc_alias, attr.span,
1939 "#[doc(alias = \"...\")] is experimental"
1941 } else if content.iter().any(|c| c.check_name(sym::keyword)) {
1942 gate_feature_post!(&self, doc_keyword, attr.span,
1943 "#[doc(keyword = \"...\")] is experimental"
1950 Some(&(name, _, template, _)) => self.check_builtin_attribute(
1955 None => if let Some(TokenTree::Token(_, token::Eq)) = attr.tokens.trees().next() {
1956 // All key-value attributes are restricted to meta-item syntax.
1957 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
1962 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1963 if !name.as_str().is_ascii() {
1967 self.context.parse_sess.source_map().def_span(sp),
1968 "non-ascii idents are not fully supported"
1973 fn visit_item(&mut self, i: &'a ast::Item) {
1975 ast::ItemKind::Const(_,_) => {
1976 if i.ident.name == kw::Underscore {
1977 gate_feature_post!(&self, underscore_const_names, i.span,
1978 "naming constants with `_` is unstable");
1982 ast::ItemKind::ForeignMod(ref foreign_module) => {
1983 self.check_abi(foreign_module.abi, i.span);
1986 ast::ItemKind::Fn(..) => {
1987 if attr::contains_name(&i.attrs[..], sym::plugin_registrar) {
1988 gate_feature_post!(&self, plugin_registrar, i.span,
1989 "compiler plugins are experimental and possibly buggy");
1991 if attr::contains_name(&i.attrs[..], sym::start) {
1992 gate_feature_post!(&self, start, i.span,
1993 "a #[start] function is an experimental \
1994 feature whose signature may change \
1997 if attr::contains_name(&i.attrs[..], sym::main) {
1998 gate_feature_post!(&self, main, i.span,
1999 "declaration of a nonstandard #[main] \
2000 function may change over time, for now \
2001 a top-level `fn main()` is required");
2005 ast::ItemKind::Struct(..) => {
2006 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
2007 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
2008 if item.check_name(sym::simd) {
2009 gate_feature_post!(&self, repr_simd, attr.span,
2010 "SIMD types are experimental and possibly buggy");
2016 ast::ItemKind::Enum(..) => {
2017 for attr in attr::filter_by_name(&i.attrs[..], sym::repr) {
2018 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
2019 if item.check_name(sym::align) {
2020 gate_feature_post!(&self, repr_align_enum, attr.span,
2021 "`#[repr(align(x))]` on enums is experimental");
2027 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
2028 if polarity == ast::ImplPolarity::Negative {
2029 gate_feature_post!(&self, optin_builtin_traits,
2031 "negative trait bounds are not yet fully implemented; \
2032 use marker types for now");
2035 if let ast::Defaultness::Default = defaultness {
2036 gate_feature_post!(&self, specialization,
2038 "specialization is unstable");
2042 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
2043 gate_feature_post!(&self, optin_builtin_traits,
2045 "auto traits are experimental and possibly buggy");
2048 ast::ItemKind::TraitAlias(..) => {
2053 "trait aliases are experimental"
2057 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
2058 let msg = "`macro` is experimental";
2059 gate_feature_post!(&self, decl_macro, i.span, msg);
2062 ast::ItemKind::Existential(..) => {
2067 "existential types are unstable"
2074 visit::walk_item(self, i);
2077 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
2079 ast::ForeignItemKind::Fn(..) |
2080 ast::ForeignItemKind::Static(..) => {
2081 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
2082 let links_to_llvm = match link_name {
2083 Some(val) => val.as_str().starts_with("llvm."),
2087 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
2088 "linking to LLVM intrinsics is experimental");
2091 ast::ForeignItemKind::Ty => {
2092 gate_feature_post!(&self, extern_types, i.span,
2093 "extern types are experimental");
2095 ast::ForeignItemKind::Macro(..) => {}
2098 visit::walk_foreign_item(self, i)
2101 fn visit_ty(&mut self, ty: &'a ast::Ty) {
2103 ast::TyKind::BareFn(ref bare_fn_ty) => {
2104 self.check_abi(bare_fn_ty.abi, ty.span);
2106 ast::TyKind::Never => {
2107 gate_feature_post!(&self, never_type, ty.span,
2108 "The `!` type is experimental");
2112 visit::walk_ty(self, ty)
2115 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
2116 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
2117 if let ast::TyKind::Never = output_ty.node {
2120 self.visit_ty(output_ty)
2125 fn visit_expr(&mut self, e: &'a ast::Expr) {
2127 ast::ExprKind::Box(_) => {
2128 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
2130 ast::ExprKind::Type(..) => {
2131 // To avoid noise about type ascription in common syntax errors, only emit if it
2132 // is the *only* error.
2133 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
2134 gate_feature_post!(&self, type_ascription, e.span,
2135 "type ascription is experimental");
2138 ast::ExprKind::Yield(..) => {
2139 gate_feature_post!(&self, generators,
2141 "yield syntax is experimental");
2143 ast::ExprKind::TryBlock(_) => {
2144 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
2146 ast::ExprKind::Block(_, opt_label) => {
2147 if let Some(label) = opt_label {
2148 gate_feature_post!(&self, label_break_value, label.ident.span,
2149 "labels on blocks are unstable");
2152 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
2153 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
2155 ast::ExprKind::Async(..) => {
2156 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
2158 ast::ExprKind::Await(origin, _) => {
2160 ast::AwaitOrigin::FieldLike =>
2161 gate_feature_post!(&self, async_await, e.span, "async/await is unstable"),
2162 ast::AwaitOrigin::MacroLike =>
2167 "`await!(<expr>)` macro syntax is unstable, and will soon be removed \
2168 in favor of `<expr>.await` syntax."
2174 visit::walk_expr(self, e);
2177 fn visit_arm(&mut self, arm: &'a ast::Arm) {
2178 visit::walk_arm(self, arm)
2181 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
2182 match pattern.node {
2183 PatKind::Slice(_, Some(ref subslice), _) => {
2184 gate_feature_post!(&self, slice_patterns,
2186 "syntax for subslices in slice patterns is not yet stabilized");
2188 PatKind::Box(..) => {
2189 gate_feature_post!(&self, box_patterns,
2191 "box pattern syntax is experimental");
2193 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
2194 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
2195 "exclusive range pattern syntax is experimental");
2199 visit::walk_pat(self, pattern)
2202 fn visit_fn(&mut self,
2203 fn_kind: FnKind<'a>,
2204 fn_decl: &'a ast::FnDecl,
2207 if let Some(header) = fn_kind.header() {
2208 // Check for const fn and async fn declarations.
2209 if header.asyncness.node.is_async() {
2210 gate_feature_post!(&self, async_await, span, "async fn is unstable");
2213 // Stability of const fn methods are covered in
2214 // `visit_trait_item` and `visit_impl_item` below; this is
2215 // because default methods don't pass through this point.
2216 self.check_abi(header.abi, span);
2219 if fn_decl.c_variadic {
2220 gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
2223 visit::walk_fn(self, fn_kind, fn_decl, span);
2226 fn visit_generic_param(&mut self, param: &'a GenericParam) {
2227 if let GenericParamKind::Const { .. } = param.kind {
2228 gate_feature_post!(&self, const_generics, param.ident.span,
2229 "const generics are unstable");
2231 visit::walk_generic_param(self, param);
2234 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
2236 ast::TraitItemKind::Method(ref sig, ref block) => {
2237 if block.is_none() {
2238 self.check_abi(sig.header.abi, ti.span);
2240 if sig.header.asyncness.node.is_async() {
2241 gate_feature_post!(&self, async_await, ti.span, "async fn is unstable");
2243 if sig.decl.c_variadic {
2244 gate_feature_post!(&self, c_variadic, ti.span,
2245 "C-variadic functions are unstable");
2247 if sig.header.constness.node == ast::Constness::Const {
2248 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
2251 ast::TraitItemKind::Type(_, ref default) => {
2252 // We use three if statements instead of something like match guards so that all
2253 // of these errors can be emitted if all cases apply.
2254 if default.is_some() {
2255 gate_feature_post!(&self, associated_type_defaults, ti.span,
2256 "associated type defaults are unstable");
2258 if !ti.generics.params.is_empty() {
2259 gate_feature_post!(&self, generic_associated_types, ti.span,
2260 "generic associated types are unstable");
2262 if !ti.generics.where_clause.predicates.is_empty() {
2263 gate_feature_post!(&self, generic_associated_types, ti.span,
2264 "where clauses on associated types are unstable");
2269 visit::walk_trait_item(self, ti);
2272 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
2273 if ii.defaultness == ast::Defaultness::Default {
2274 gate_feature_post!(&self, specialization,
2276 "specialization is unstable");
2280 ast::ImplItemKind::Method(..) => {}
2281 ast::ImplItemKind::Existential(..) => {
2286 "existential types are unstable"
2289 ast::ImplItemKind::Type(_) => {
2290 if !ii.generics.params.is_empty() {
2291 gate_feature_post!(&self, generic_associated_types, ii.span,
2292 "generic associated types are unstable");
2294 if !ii.generics.where_clause.predicates.is_empty() {
2295 gate_feature_post!(&self, generic_associated_types, ii.span,
2296 "where clauses on associated types are unstable");
2301 visit::walk_impl_item(self, ii);
2304 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2305 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2306 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2307 "`crate` visibility modifier is experimental");
2309 visit::walk_vis(self, vis);
2313 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2314 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2315 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2316 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2317 if let Some(reason) = reason {
2318 err.span_note(span, reason);
2320 err.span_label(span, "feature has been removed");
2325 let mut features = Features::new();
2326 let mut edition_enabled_features = FxHashMap::default();
2328 for &edition in ALL_EDITIONS {
2329 if edition <= crate_edition {
2330 // The `crate_edition` implies its respective umbrella feature-gate
2331 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2332 edition_enabled_features.insert(edition.feature_name(), edition);
2336 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2337 if let Some(f_edition) = f_edition {
2338 if f_edition <= crate_edition {
2339 set(&mut features, DUMMY_SP);
2340 edition_enabled_features.insert(name, crate_edition);
2345 // Process the edition umbrella feature-gates first, to ensure
2346 // `edition_enabled_features` is completed before it's queried.
2347 for attr in krate_attrs {
2348 if !attr.check_name(sym::feature) {
2352 let list = match attr.meta_item_list() {
2362 let name = mi.name_or_empty();
2363 if INCOMPLETE_FEATURES.iter().any(|f| name == *f) {
2364 span_handler.struct_span_warn(
2367 "the feature `{}` is incomplete and may cause the compiler to crash",
2373 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2374 if *edition <= crate_edition {
2378 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2379 if let Some(f_edition) = f_edition {
2380 if f_edition <= *edition {
2381 // FIXME(Manishearth) there is currently no way to set
2382 // lib features by edition
2383 set(&mut features, DUMMY_SP);
2384 edition_enabled_features.insert(name, *edition);
2392 for attr in krate_attrs {
2393 if !attr.check_name(sym::feature) {
2397 let list = match attr.meta_item_list() {
2402 let bad_input = |span| {
2403 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
2407 let name = match mi.ident() {
2408 Some(ident) if mi.is_word() => ident.name,
2410 bad_input(mi.span()).span_suggestion(
2412 "expected just one word",
2413 format!("{}", ident.name),
2414 Applicability::MaybeIncorrect,
2419 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
2424 if let Some(edition) = edition_enabled_features.get(&name) {
2429 "the feature `{}` is included in the Rust {} edition",
2436 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2437 // Handled in the separate loop above.
2441 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2442 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2443 if let Some((.., reason)) = removed.or(stable_removed) {
2444 feature_removed(span_handler, mi.span(), *reason);
2448 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2449 let since = Some(Symbol::intern(since));
2450 features.declared_lang_features.push((name, mi.span(), since));
2454 if let Some(allowed) = allow_features.as_ref() {
2455 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2456 span_err!(span_handler, mi.span(), E0725,
2457 "the feature `{}` is not in the list of allowed features",
2463 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2464 set(&mut features, mi.span());
2465 features.declared_lang_features.push((name, mi.span(), None));
2469 features.declared_lib_features.push((name, mi.span()));
2476 pub fn check_crate(krate: &ast::Crate,
2478 features: &Features,
2479 plugin_attributes: &[(Symbol, AttributeType)],
2480 unstable: UnstableFeatures) {
2481 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2487 let visitor = &mut PostExpansionVisitor {
2489 builtin_attributes: &*BUILTIN_ATTRIBUTE_MAP,
2491 visit::walk_crate(visitor, krate);
2494 #[derive(Clone, Copy, Hash)]
2495 pub enum UnstableFeatures {
2496 /// Hard errors for unstable features are active, as on beta/stable channels.
2498 /// Allow features to be activated, as on nightly.
2500 /// Errors are bypassed for bootstrapping. This is required any time
2501 /// during the build that feature-related lints are set to warn or above
2502 /// because the build turns on warnings-as-errors and uses lots of unstable
2503 /// features. As a result, this is always required for building Rust itself.
2507 impl UnstableFeatures {
2508 pub fn from_environment() -> UnstableFeatures {
2509 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2510 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2511 // Whether we should enable unstable features for bootstrapping
2512 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2513 match (disable_unstable_features, bootstrap) {
2514 (_, true) => UnstableFeatures::Cheat,
2515 (true, _) => UnstableFeatures::Disallow,
2516 (false, _) => UnstableFeatures::Allow
2520 pub fn is_nightly_build(&self) -> bool {
2522 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2528 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2529 unstable: UnstableFeatures) {
2530 let allow_features = match unstable {
2531 UnstableFeatures::Allow => true,
2532 UnstableFeatures::Disallow => false,
2533 UnstableFeatures::Cheat => true
2535 if !allow_features {
2536 for attr in &krate.attrs {
2537 if attr.check_name(sym::feature) {
2538 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2539 span_err!(span_handler, attr.span, E0554,
2540 "#![feature] may not be used on the {} release channel",