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;
26 use crate::tokenstream::TokenTree;
28 use errors::{DiagnosticBuilder, Handler};
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_target::spec::abi::Abi;
31 use syntax_pos::{Span, DUMMY_SP};
38 fn f(features: &mut Features, _: Span) {
39 features.$field = true;
41 f as fn(&mut Features, Span)
45 macro_rules! declare_features {
46 ($((active, $feature: ident, $ver: expr, $issue: expr, $edition: expr),)+) => {
47 /// Represents active features that are currently being implemented or
48 /// currently being considered for addition/removal.
49 const ACTIVE_FEATURES:
50 &[(&str, &str, Option<u32>, Option<Edition>, fn(&mut Features, Span))] =
51 &[$((stringify!($feature), $ver, $issue, $edition, set!($feature))),+];
53 /// A set of features to be used by later passes.
56 /// `#![feature]` attrs for language features, for error reporting
57 pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
58 /// `#![feature]` attrs for non-language (library) features
59 pub declared_lib_features: Vec<(Symbol, Span)>,
60 $(pub $feature: bool),+
64 pub fn new() -> Features {
66 declared_lang_features: Vec::new(),
67 declared_lib_features: Vec::new(),
72 pub fn walk_feature_fields<F>(&self, mut f: F)
73 where F: FnMut(&str, bool)
75 $(f(stringify!($feature), self.$feature);)+
80 ($((removed, $feature: ident, $ver: expr, $issue: expr, None, $reason: expr),)+) => {
81 /// Represents unstable features which have since been removed (it was once Active)
82 const REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
83 $((stringify!($feature), $ver, $issue, $reason)),+
87 ($((stable_removed, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
88 /// Represents stable features which have since been removed (it was once Accepted)
89 const STABLE_REMOVED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
90 $((stringify!($feature), $ver, $issue, None)),+
94 ($((accepted, $feature: ident, $ver: expr, $issue: expr, None),)+) => {
95 /// Those language feature has since been Accepted (it was once Active)
96 const ACCEPTED_FEATURES: &[(&str, &str, Option<u32>, Option<&str>)] = &[
97 $((stringify!($feature), $ver, $issue, None)),+
102 // If you change this, please modify `src/doc/unstable-book` as well.
104 // Don't ever remove anything from this list; set them to 'Removed'.
106 // The version numbers here correspond to the version in which the current status
107 // was set. This is most important for knowing when a particular feature became
110 // N.B., `tools/tidy/src/features.rs` parses this information directly out of the
111 // source, so take care when modifying it.
114 (active, asm, "1.0.0", Some(29722), None),
115 (active, concat_idents, "1.0.0", Some(29599), None),
116 (active, link_args, "1.0.0", Some(29596), None),
117 (active, log_syntax, "1.0.0", Some(29598), None),
118 (active, non_ascii_idents, "1.0.0", Some(55467), None),
119 (active, plugin_registrar, "1.0.0", Some(29597), None),
120 (active, thread_local, "1.0.0", Some(29594), None),
121 (active, trace_macros, "1.0.0", Some(29598), None),
123 // rustc internal, for now
124 (active, intrinsics, "1.0.0", None, None),
125 (active, lang_items, "1.0.0", None, None),
126 (active, format_args_nl, "1.29.0", None, None),
128 (active, link_llvm_intrinsics, "1.0.0", Some(29602), None),
129 (active, linkage, "1.0.0", Some(29603), None),
132 (active, rustc_diagnostic_macros, "1.0.0", None, None),
133 (active, rustc_const_unstable, "1.0.0", None, None),
134 (active, box_syntax, "1.0.0", Some(49733), None),
135 (active, unboxed_closures, "1.0.0", Some(29625), None),
137 (active, fundamental, "1.0.0", Some(29635), None),
138 (active, main, "1.0.0", Some(29634), None),
139 (active, needs_allocator, "1.4.0", Some(27389), None),
140 (active, on_unimplemented, "1.0.0", Some(29628), None),
141 (active, plugin, "1.0.0", Some(29597), None),
142 (active, simd_ffi, "1.0.0", Some(27731), None),
143 (active, start, "1.0.0", Some(29633), None),
144 (active, structural_match, "1.8.0", Some(31434), None),
145 (active, panic_runtime, "1.10.0", Some(32837), None),
146 (active, needs_panic_runtime, "1.10.0", Some(32837), None),
148 // Features specific to OIBIT (auto traits)
149 (active, optin_builtin_traits, "1.0.0", Some(13231), None),
151 // Allows `#[staged_api]`.
154 (active, staged_api, "1.0.0", None, None),
156 // Allows `#![no_core]`.
157 (active, no_core, "1.3.0", Some(29639), None),
159 // Allows the use of `box` in patterns (RFC 469).
160 (active, box_patterns, "1.0.0", Some(29641), None),
162 // Allows the use of the `unsafe_destructor_blind_to_params` attribute (RFC 1238).
163 (active, dropck_parametricity, "1.3.0", Some(28498), None),
165 // Allows using the `may_dangle` attribute (RFC 1327).
166 (active, dropck_eyepatch, "1.10.0", Some(34761), None),
168 // Allows the use of custom attributes (RFC 572).
169 (active, custom_attribute, "1.0.0", Some(29642), None),
171 // Allows the use of `rustc_*` attributes (RFC 572).
172 (active, rustc_attrs, "1.0.0", Some(29642), None),
174 // Allows the use of non lexical lifetimes (RFC 2094).
175 (active, nll, "1.0.0", Some(43234), None),
177 // Allows the use of `#[allow_internal_unstable]`. This is an
178 // attribute on `macro_rules!` and can't use the attribute handling
179 // below (it has to be checked before expansion possibly makes
180 // macros disappear).
183 (active, allow_internal_unstable, "1.0.0", None, None),
185 // Allows the use of `#[allow_internal_unsafe]`. This is an
186 // attribute on `macro_rules!` and can't use the attribute handling
187 // below (it has to be checked before expansion possibly makes
188 // macros disappear).
191 (active, allow_internal_unsafe, "1.0.0", None, None),
193 // Allows the use of slice patterns (issue #23121).
194 (active, slice_patterns, "1.0.0", Some(23121), None),
196 // Allows the definition of `const` functions with some advanced features.
197 (active, const_fn, "1.2.0", Some(57563), None),
199 // Allows accessing fields of unions inside `const` functions.
200 (active, const_fn_union, "1.27.0", Some(51909), None),
202 // Allows casting raw pointers to `usize` during const eval.
203 (active, const_raw_ptr_to_usize_cast, "1.27.0", Some(51910), None),
205 // Allows dereferencing raw pointers during const eval.
206 (active, const_raw_ptr_deref, "1.27.0", Some(51911), None),
208 // Allows reinterpretation of the bits of a value of one type as another type during const eval.
209 (active, const_transmute, "1.29.0", Some(53605), None),
211 // Allows comparing raw pointers during const eval.
212 (active, const_compare_raw_pointers, "1.27.0", Some(53020), None),
214 // Allows panicking during const eval (producing compile-time errors).
215 (active, const_panic, "1.30.0", Some(51999), None),
217 // Allows using `#[prelude_import]` on glob `use` items.
220 (active, prelude_import, "1.2.0", None, None),
222 // Allows default type parameters to influence type inference.
223 (active, default_type_parameter_fallback, "1.3.0", Some(27336), None),
225 // Allows associated type defaults.
226 (active, associated_type_defaults, "1.2.0", Some(29661), None),
228 // Allows `repr(simd)` and importing the various simd intrinsics.
229 (active, repr_simd, "1.4.0", Some(27731), None),
231 // Allows `extern "platform-intrinsic" { ... }`.
232 (active, platform_intrinsics, "1.4.0", Some(27731), None),
234 // Allows `#[unwind(..)]`.
236 // Permits specifying whether a function should permit unwinding or abort on unwind.
237 (active, unwind_attributes, "1.4.0", Some(58760), None),
239 // Allows the use of `#[naked]` on functions.
240 (active, naked_functions, "1.9.0", Some(32408), None),
242 // Allows `#[no_debug]`.
243 (active, no_debug, "1.5.0", Some(29721), None),
245 // Allows `#[omit_gdb_pretty_printer_section]`.
248 (active, omit_gdb_pretty_printer_section, "1.5.0", None, None),
250 // Allows attributes on expressions and non-item statements.
251 (active, stmt_expr_attributes, "1.6.0", Some(15701), None),
253 // Allows the use of type ascription in expressions.
254 (active, type_ascription, "1.6.0", Some(23416), None),
256 // Allows `cfg(target_thread_local)`.
257 (active, cfg_target_thread_local, "1.7.0", Some(29594), None),
260 (active, abi_vectorcall, "1.7.0", None, None),
262 // Allows `X..Y` patterns.
263 (active, exclusive_range_pattern, "1.11.0", Some(37854), None),
265 // impl specialization (RFC 1210)
266 (active, specialization, "1.7.0", Some(31844), None),
268 // Allows `cfg(target_has_atomic = "...")`.
269 (active, cfg_target_has_atomic, "1.9.0", Some(32976), None),
271 // The `!` type. Does not imply 'exhaustive_patterns' (below) any more.
272 (active, never_type, "1.13.0", Some(35121), None),
274 // Allows exhaustive pattern matching on types that contain uninhabited types.
275 (active, exhaustive_patterns, "1.13.0", Some(51085), None),
277 // Allows untagged unions `union U { ... }`.
278 (active, untagged_unions, "1.13.0", Some(32836), None),
280 // Used to identify the `compiler_builtins` crate.
283 (active, compiler_builtins, "1.13.0", None, None),
285 // Allows `#[link(..., cfg(..))]`.
286 (active, link_cfg, "1.14.0", Some(37406), None),
288 // Allows `extern "ptx-*" fn()`.
289 (active, abi_ptx, "1.15.0", Some(38788), None),
291 // The `repr(i128)` annotation for enums.
292 (active, repr128, "1.16.0", Some(35118), None),
294 // Allows the use of `#[ffi_returns_twice]` on foreign functions.
295 (active, ffi_returns_twice, "1.34.0", Some(58314), None),
297 // The `unadjusted` ABI; perma-unstable.
300 (active, abi_unadjusted, "1.16.0", None, None),
302 // Declarative macros 2.0 (`macro`).
303 (active, decl_macro, "1.17.0", Some(39412), None),
305 // Allows `#[link(kind="static-nobundle"...)]`.
306 (active, static_nobundle, "1.16.0", Some(37403), None),
308 // Allows `extern "msp430-interrupt" fn()`.
309 (active, abi_msp430_interrupt, "1.16.0", Some(38487), None),
311 // Used to identify crates that contain sanitizer runtimes.
314 (active, sanitizer_runtime, "1.17.0", None, None),
316 // Used to identify crates that contain the profiler runtime.
319 (active, profiler_runtime, "1.18.0", None, None),
321 // Allows `extern "x86-interrupt" fn()`.
322 (active, abi_x86_interrupt, "1.17.0", Some(40180), None),
324 // Allows the `try {...}` expression.
325 (active, try_blocks, "1.29.0", Some(31436), None),
327 // Allows module-level inline assembly by way of `global_asm!()`.
328 (active, global_asm, "1.18.0", Some(35119), None),
330 // Allows overlapping impls of marker traits.
331 (active, overlapping_marker_traits, "1.18.0", Some(29864), None),
333 // Trait attribute to allow overlapping impls.
334 (active, marker_trait_attr, "1.30.0", Some(29864), None),
337 (active, abi_thiscall, "1.19.0", None, None),
339 // Allows a test to fail without failing the whole suite.
340 (active, allow_fail, "1.19.0", Some(46488), None),
342 // Allows unsized tuple coercion.
343 (active, unsized_tuple_coercion, "1.20.0", Some(42877), None),
346 (active, generators, "1.21.0", Some(43122), None),
349 (active, trait_alias, "1.24.0", Some(41517), None),
352 (active, allocator_internals, "1.20.0", None, None),
354 // `#[doc(cfg(...))]`
355 (active, doc_cfg, "1.21.0", Some(43781), None),
357 (active, doc_masked, "1.21.0", Some(44027), None),
358 // `#[doc(spotlight)]`
359 (active, doc_spotlight, "1.22.0", Some(45040), None),
360 // `#[doc(include = "some-file")]`
361 (active, external_doc, "1.22.0", Some(44732), None),
363 // Future-proofing enums/structs with `#[non_exhaustive]` attribute (RFC 2008).
364 (active, non_exhaustive, "1.22.0", Some(44109), None),
366 // Adds `crate` as visibility modifier, synonymous with `pub(crate)`.
367 (active, crate_visibility_modifier, "1.23.0", Some(53120), None),
370 (active, extern_types, "1.23.0", Some(43467), None),
372 // Allows trait methods with arbitrary self types.
373 (active, arbitrary_self_types, "1.23.0", Some(44874), None),
375 // In-band lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`).
376 (active, in_band_lifetimes, "1.23.0", Some(44524), None),
378 // Generic associated types (RFC 1598)
379 (active, generic_associated_types, "1.23.0", Some(44265), None),
381 // Infer static outlives requirements (RFC 2093).
382 (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None),
384 // Allows macro invocations in `extern {}` blocks.
385 (active, macros_in_extern, "1.27.0", Some(49476), None),
387 // `existential type`
388 (active, existential_type, "1.28.0", Some(34511), None),
390 // unstable `#[target_feature]` directives
391 (active, arm_target_feature, "1.27.0", Some(44839), None),
392 (active, aarch64_target_feature, "1.27.0", Some(44839), None),
393 (active, hexagon_target_feature, "1.27.0", Some(44839), None),
394 (active, powerpc_target_feature, "1.27.0", Some(44839), None),
395 (active, mips_target_feature, "1.27.0", Some(44839), None),
396 (active, avx512_target_feature, "1.27.0", Some(44839), None),
397 (active, mmx_target_feature, "1.27.0", Some(44839), None),
398 (active, sse4a_target_feature, "1.27.0", Some(44839), None),
399 (active, tbm_target_feature, "1.27.0", Some(44839), None),
400 (active, wasm_target_feature, "1.30.0", Some(44839), None),
401 (active, adx_target_feature, "1.32.0", Some(44839), None),
402 (active, cmpxchg16b_target_feature, "1.32.0", Some(44839), None),
403 (active, movbe_target_feature, "1.34.0", Some(44839), None),
405 // Allows macro invocations on modules expressions and statements and
406 // procedural macros to expand to non-items.
407 (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
409 // `#[doc(alias = "...")]`
410 (active, doc_alias, "1.27.0", Some(50146), None),
412 // inconsistent bounds in where clauses
413 (active, trivial_bounds, "1.28.0", Some(48214), None),
415 // `'a: { break 'a; }`
416 (active, label_break_value, "1.28.0", Some(48594), None),
418 // Exhaustive pattern matching on `usize` and `isize`.
419 (active, precise_pointer_size_matching, "1.32.0", Some(56354), None),
421 // `#[doc(keyword = "...")]`
422 (active, doc_keyword, "1.28.0", Some(51315), None),
424 // Allows async and await syntax.
425 (active, async_await, "1.28.0", Some(50547), None),
427 // `#[alloc_error_handler]`
428 (active, alloc_error_handler, "1.29.0", Some(51540), None),
430 (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None),
432 // Added for testing E0705; perma-unstable.
433 (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)),
435 // Allows unsized rvalues at arguments and parameters.
436 (active, unsized_locals, "1.30.0", Some(48055), None),
440 (active, custom_test_frameworks, "1.30.0", Some(50297), None),
442 // non-builtin attributes in inner attribute position
443 (active, custom_inner_attributes, "1.30.0", Some(54726), None),
445 // Allow mixing of bind-by-move in patterns and references to
446 // those identifiers in guards, *if* we are using MIR-borrowck
447 // (aka NLL). Essentially this means you need to be using the
448 // 2018 edition or later.
449 (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None),
451 // Allows `impl Trait` in bindings (`let`, `const`, `static`).
452 (active, impl_trait_in_bindings, "1.30.0", Some(34511), None),
454 // Allows `const _: TYPE = VALUE`.
455 (active, underscore_const_names, "1.31.0", Some(54912), None),
457 // Adds `reason` and `expect` lint attributes.
458 (active, lint_reasons, "1.31.0", Some(54503), None),
460 // Allows paths to enum variants on type aliases.
461 (active, type_alias_enum_variants, "1.31.0", Some(49683), None),
463 // Re-Rebalance coherence
464 (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
466 // Const generic types.
467 (active, const_generics, "1.34.0", Some(44580), None),
470 (active, optimize_attribute, "1.34.0", Some(54882), None),
472 // #[repr(align(X))] on enums
473 (active, repr_align_enum, "1.34.0", Some(57996), None),
475 // Allows the use of C-variadics
476 (active, c_variadic, "1.34.0", Some(44930), None),
480 (removed, import_shadowing, "1.0.0", None, None, None),
481 (removed, managed_boxes, "1.0.0", None, None, None),
482 // Allows use of unary negate on unsigned integers, e.g., -e for e: u8
483 (removed, negate_unsigned, "1.0.0", Some(29645), None, None),
484 (removed, reflect, "1.0.0", Some(27749), None, None),
485 // A way to temporarily opt out of opt in copy. This will *never* be accepted.
486 (removed, opt_out_copy, "1.0.0", None, None, None),
487 (removed, quad_precision_float, "1.0.0", None, None, None),
488 (removed, struct_inherit, "1.0.0", None, None, None),
489 (removed, test_removed_feature, "1.0.0", None, None, None),
490 (removed, visible_private_types, "1.0.0", None, None, None),
491 (removed, unsafe_no_drop_flag, "1.0.0", None, None, None),
492 // Allows using items which are missing stability attributes
494 (removed, unmarked_api, "1.0.0", None, None, None),
495 (removed, pushpop_unsafe, "1.2.0", None, None, None),
496 (removed, allocator, "1.0.0", None, None, None),
497 (removed, simd, "1.0.0", Some(27731), None,
498 Some("removed in favor of `#[repr(simd)]`")),
499 (removed, advanced_slice_patterns, "1.0.0", Some(23121), None,
500 Some("merged into `#![feature(slice_patterns)]`")),
501 (removed, macro_reexport, "1.0.0", Some(29638), None,
502 Some("subsumed by `pub use`")),
503 (removed, proc_macro_mod, "1.27.0", Some(54727), None,
504 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
505 (removed, proc_macro_expr, "1.27.0", Some(54727), None,
506 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
507 (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
508 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
509 (removed, proc_macro_gen, "1.27.0", Some(54727), None,
510 Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
511 (removed, panic_implementation, "1.28.0", Some(44489), None,
512 Some("subsumed by `#[panic_handler]`")),
513 // Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`.
514 (removed, custom_derive, "1.0.0", Some(29644), None,
515 Some("subsumed by `#[proc_macro_derive]`")),
516 // Paths of the form: `extern::foo::bar`
517 (removed, extern_in_paths, "1.33.0", Some(55600), None,
518 Some("subsumed by `::foo::bar` paths")),
519 (removed, quote, "1.0.0", Some(29601), None, None),
523 (stable_removed, no_stack_check, "1.0.0", None, None),
527 (accepted, associated_types, "1.0.0", None, None),
528 // Allows overloading augmented assignment operations like `a += b`.
529 (accepted, augmented_assignments, "1.8.0", Some(28235), None),
530 // Allows empty structs and enum variants with braces.
531 (accepted, braced_empty_structs, "1.8.0", Some(29720), None),
532 // Allows indexing into constant arrays.
533 (accepted, const_indexing, "1.26.0", Some(29947), None),
534 (accepted, default_type_params, "1.0.0", None, None),
535 (accepted, globs, "1.0.0", None, None),
536 (accepted, if_let, "1.0.0", None, None),
537 // A temporary feature gate used to enable parser extensions needed
538 // to bootstrap fix for #5723.
539 (accepted, issue_5723_bootstrap, "1.0.0", None, None),
540 (accepted, macro_rules, "1.0.0", None, None),
541 // Allows using `#![no_std]`.
542 (accepted, no_std, "1.6.0", None, None),
543 (accepted, slicing_syntax, "1.0.0", None, None),
544 (accepted, struct_variant, "1.0.0", None, None),
545 // These are used to test this portion of the compiler, they don't actually
547 (accepted, test_accepted_feature, "1.0.0", None, None),
548 (accepted, tuple_indexing, "1.0.0", None, None),
549 // Allows macros to appear in the type position.
550 (accepted, type_macros, "1.13.0", Some(27245), None),
551 (accepted, while_let, "1.0.0", None, None),
552 // Allows `#[deprecated]` attribute.
553 (accepted, deprecated, "1.9.0", Some(29935), None),
555 (accepted, question_mark, "1.13.0", Some(31436), None),
556 // Allows `..` in tuple (struct) patterns.
557 (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None),
558 (accepted, item_like_imports, "1.15.0", Some(35120), None),
559 // Allows using `Self` and associated types in struct expressions and patterns.
560 (accepted, more_struct_aliases, "1.16.0", Some(37544), None),
561 // elide `'static` lifetimes in `static`s and `const`s.
562 (accepted, static_in_const, "1.17.0", Some(35897), None),
563 // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions.
564 (accepted, field_init_shorthand, "1.17.0", Some(37340), None),
565 // Allows the definition recursive static items.
566 (accepted, static_recursion, "1.17.0", Some(29719), None),
567 // `pub(restricted)` visibilities (RFC 1422)
568 (accepted, pub_restricted, "1.18.0", Some(32409), None),
569 // `#![windows_subsystem]`
570 (accepted, windows_subsystem, "1.18.0", Some(37499), None),
571 // Allows `break {expr}` with a value inside `loop`s.
572 (accepted, loop_break_value, "1.19.0", Some(37339), None),
573 // Permits numeric fields in struct expressions and patterns.
574 (accepted, relaxed_adts, "1.19.0", Some(35626), None),
575 // Coerces non capturing closures to function pointers.
576 (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None),
577 // Allows attributes on struct literal fields.
578 (accepted, struct_field_attributes, "1.20.0", Some(38814), None),
579 // Allows the definition of associated constants in `trait` or `impl` blocks.
580 (accepted, associated_consts, "1.20.0", Some(29646), None),
581 // Usage of the `compile_error!` macro.
582 (accepted, compile_error, "1.20.0", Some(40872), None),
583 // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work.
584 (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None),
585 // Allows `Drop` types in constants (RFC 1440).
586 (accepted, drop_types_in_const, "1.22.0", Some(33156), None),
587 // Allows the sysV64 ABI to be specified on all platforms
588 // instead of just the platforms on which it is the C ABI.
589 (accepted, abi_sysv64, "1.24.0", Some(36167), None),
590 // Allows `repr(align(16))` struct attribute (RFC 1358).
591 (accepted, repr_align, "1.25.0", Some(33626), None),
592 // Allows '|' at beginning of match arms (RFC 1925).
593 (accepted, match_beginning_vert, "1.25.0", Some(44101), None),
594 // Nested groups in `use` (RFC 2128)
595 (accepted, use_nested_groups, "1.25.0", Some(44494), None),
596 // `a..=b` and `..=b`
597 (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None),
598 // Allows `..=` in patterns (RFC 1192).
599 (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None),
600 // Termination trait in main (RFC 1937)
601 (accepted, termination_trait, "1.26.0", Some(43301), None),
602 // `Copy`/`Clone` closures (RFC 2132).
603 (accepted, clone_closures, "1.26.0", Some(44490), None),
604 (accepted, copy_closures, "1.26.0", Some(44490), None),
605 // Allows `impl Trait` in function arguments.
606 (accepted, universal_impl_trait, "1.26.0", Some(34511), None),
607 // Allows `impl Trait` in function return types.
608 (accepted, conservative_impl_trait, "1.26.0", Some(34511), None),
610 (accepted, i128_type, "1.26.0", Some(35118), None),
611 // Default match binding modes (RFC 2005)
612 (accepted, match_default_bindings, "1.26.0", Some(42640), None),
613 // Allows `'_` placeholder lifetimes.
614 (accepted, underscore_lifetimes, "1.26.0", Some(44524), None),
615 // Allows attributes on lifetime/type formal parameters in generics (RFC 1327).
616 (accepted, generic_param_attrs, "1.27.0", Some(48848), None),
617 // Allows `cfg(target_feature = "...")`.
618 (accepted, cfg_target_feature, "1.27.0", Some(29717), None),
619 // Allows `#[target_feature(...)]`.
620 (accepted, target_feature, "1.27.0", None, None),
621 // Trait object syntax with `dyn` prefix
622 (accepted, dyn_trait, "1.27.0", Some(44662), None),
623 // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940).
624 (accepted, fn_must_use, "1.27.0", Some(43302), None),
625 // Allows use of the `:lifetime` macro fragment specifier.
626 (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None),
627 // Termination trait in tests (RFC 1937)
628 (accepted, termination_trait_test, "1.27.0", Some(48854), None),
629 // The `#[global_allocator]` attribute
630 (accepted, global_allocator, "1.28.0", Some(27389), None),
631 // Allows `#[repr(transparent)]` attribute on newtype structs.
632 (accepted, repr_transparent, "1.28.0", Some(43036), None),
633 // Procedural macros in `proc-macro` crates
634 (accepted, proc_macro, "1.29.0", Some(38356), None),
635 // `foo.rs` as an alternative to `foo/mod.rs`
636 (accepted, non_modrs_mods, "1.30.0", Some(44660), None),
637 // Allows use of the `:vis` macro fragment specifier
638 (accepted, macro_vis_matcher, "1.30.0", Some(41022), None),
639 // Allows importing and reexporting macros with `use`,
640 // enables macro modularization in general.
641 (accepted, use_extern_macros, "1.30.0", Some(35896), None),
642 // Allows keywords to be escaped for use as identifiers.
643 (accepted, raw_identifiers, "1.30.0", Some(48589), None),
644 // Attributes scoped to tools.
645 (accepted, tool_attributes, "1.30.0", Some(44690), None),
646 // Allows multi-segment paths in attributes and derives.
647 (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None),
648 // Allows all literals in attribute lists and values of key-value pairs.
649 (accepted, attr_literals, "1.30.0", Some(34981), None),
650 // Infer outlives requirements (RFC 2093).
651 (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None),
652 (accepted, panic_handler, "1.30.0", Some(44489), None),
653 // Used to preserve symbols (see llvm.used).
654 (accepted, used, "1.30.0", Some(40289), None),
656 (accepted, crate_in_paths, "1.30.0", Some(45477), None),
657 // Resolve absolute paths as paths from other crates.
658 (accepted, extern_absolute_paths, "1.30.0", Some(44660), None),
659 // Access to crate names passed via `--extern` through prelude.
660 (accepted, extern_prelude, "1.30.0", Some(44660), None),
661 // Parentheses in patterns
662 (accepted, pattern_parentheses, "1.31.0", Some(51087), None),
663 // Allows the definition of `const fn` functions.
664 (accepted, min_const_fn, "1.31.0", Some(53555), None),
666 (accepted, tool_lints, "1.31.0", Some(44690), None),
667 // `impl<I:Iterator> Iterator for &mut Iterator`
668 // `impl Debug for Foo<'_>`
669 (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None),
670 // `extern crate foo as bar;` puts `bar` into extern prelude.
671 (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None),
672 // Allows use of the `:literal` macro fragment specifier (RFC 1576).
673 (accepted, macro_literal_matcher, "1.32.0", Some(35625), None),
674 // Use `?` as the Kleene "at most one" operator.
675 (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None),
676 // `Self` struct constructor (RFC 2302)
677 (accepted, self_struct_ctor, "1.32.0", Some(51994), None),
678 // `Self` in type definitions (RFC 2300)
679 (accepted, self_in_typedefs, "1.32.0", Some(49303), None),
680 // Allows `use x::y;` to search `x` in the current scope.
681 (accepted, uniform_paths, "1.32.0", Some(53130), None),
682 // Integer match exhaustiveness checking (RFC 2591)
683 (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907), None),
684 // `use path as _;` and `extern crate c as _;`
685 (accepted, underscore_imports, "1.33.0", Some(48216), None),
686 // Allows `#[repr(packed(N))]` attribute on structs.
687 (accepted, repr_packed, "1.33.0", Some(33158), None),
688 // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086).
689 (accepted, irrefutable_let_patterns, "1.33.0", Some(44495), None),
690 // Allows calling `const unsafe fn` inside `unsafe` blocks in `const fn` functions.
691 (accepted, min_const_unsafe_fn, "1.33.0", Some(55607), None),
692 // Allows let bindings, assignments and destructuring in `const` functions and constants.
693 // As long as control flow is not implemented in const eval, `&&` and `||` may not be used
694 // at the same time as let bindings.
695 (accepted, const_let, "1.33.0", Some(48821), None),
696 // `#[cfg_attr(predicate, multiple, attributes, here)]`
697 (accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
698 // Top level or-patterns (`p | q`) in `if let` and `while let`.
699 (accepted, if_while_or_patterns, "1.33.0", Some(48215), None),
700 // Allows `cfg(target_vendor = "...")`.
701 (accepted, cfg_target_vendor, "1.33.0", Some(29718), None),
702 // `extern crate self as foo;` puts local crate root into extern prelude under name `foo`.
703 (accepted, extern_crate_self, "1.34.0", Some(56409), None),
704 // support for arbitrary delimited token streams in non-macro attributes
705 (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208), None),
708 // If you change this, please modify `src/doc/unstable-book` as well. You must
709 // move that documentation into the relevant place in the other docs, and
710 // remove the chapter on the flag.
712 #[derive(Copy, Clone, PartialEq, Debug)]
713 pub enum AttributeType {
714 /// Normal, builtin attribute that is consumed
715 /// by the compiler before the unused_attribute check
718 /// Builtin attribute that may not be consumed by the compiler
719 /// before the unused_attribute check. These attributes
720 /// will be ignored by the unused_attribute lint
723 /// Builtin attribute that is only allowed at the crate level
727 pub enum AttributeGate {
728 /// Is gated by a given feature gate, reason
729 /// and function to check if enabled
730 Gated(Stability, &'static str, &'static str, fn(&Features) -> bool),
732 /// Ungated attribute, can be used on all release channels
736 /// A template that the attribute input must match.
737 /// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
738 #[derive(Clone, Copy)]
739 pub struct AttributeTemplate {
741 list: Option<&'static str>,
742 name_value_str: Option<&'static str>,
745 impl AttributeTemplate {
746 /// Checks that the given meta-item is compatible with this template.
747 fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
748 match meta_item_kind {
749 ast::MetaItemKind::Word => self.word,
750 ast::MetaItemKind::List(..) => self.list.is_some(),
751 ast::MetaItemKind::NameValue(lit) if lit.node.is_str() => self.name_value_str.is_some(),
752 ast::MetaItemKind::NameValue(..) => false,
757 /// A convenience macro for constructing attribute templates.
758 /// E.g., `template!(Word, List: "description")` means that the attribute
759 /// supports forms `#[attr]` and `#[attr(description)]`.
760 macro_rules! template {
761 (Word) => { template!(@ true, None, None) };
762 (List: $descr: expr) => { template!(@ false, Some($descr), None) };
763 (NameValueStr: $descr: expr) => { template!(@ false, None, Some($descr)) };
764 (Word, List: $descr: expr) => { template!(@ true, Some($descr), None) };
765 (Word, NameValueStr: $descr: expr) => { template!(@ true, None, Some($descr)) };
766 (List: $descr1: expr, NameValueStr: $descr2: expr) => {
767 template!(@ false, Some($descr1), Some($descr2))
769 (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
770 template!(@ true, Some($descr1), Some($descr2))
772 (@ $word: expr, $list: expr, $name_value_str: expr) => { AttributeTemplate {
773 word: $word, list: $list, name_value_str: $name_value_str
778 fn is_deprecated(&self) -> bool {
780 Gated(Stability::Deprecated(_, _), ..) => true,
786 #[derive(Copy, Clone, Debug)]
789 // First argument is tracking issue link; second argument is an optional
790 // help message, which defaults to "remove this attribute"
791 Deprecated(&'static str, Option<&'static str>),
795 impl std::fmt::Debug for AttributeGate {
796 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798 Gated(ref stab, name, expl, _) =>
799 write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
800 Ungated => write!(fmt, "Ungated")
805 macro_rules! cfg_fn {
806 ($field: ident) => {{
807 fn f(features: &Features) -> bool {
810 f as fn(&Features) -> bool
814 pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType,
815 AttributeTemplate, AttributeGate)> {
816 BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
819 pub fn is_builtin_attr_name(name: ast::Name) -> bool {
820 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, ..)| name == builtin_name)
823 pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
824 BUILTIN_ATTRIBUTES.iter().any(|&(builtin_name, ..)| attr.path == builtin_name)
827 // Attributes that have a special meaning to rustc or rustdoc
828 pub const BUILTIN_ATTRIBUTES: &[(&str, AttributeType, AttributeTemplate, AttributeGate)] = &[
831 ("warn", Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), Ungated),
832 ("allow", Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), Ungated),
833 ("forbid", Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), Ungated),
834 ("deny", Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#), Ungated),
836 ("macro_use", Normal, template!(Word, List: "name1, name2, ..."), Ungated),
837 ("macro_export", Normal, template!(Word, List: "local_inner_macros"), Ungated),
838 ("plugin_registrar", Normal, template!(Word), Ungated),
840 ("cfg", Normal, template!(List: "predicate"), Ungated),
841 ("cfg_attr", Normal, template!(List: "predicate, attr1, attr2, ..."), Ungated),
842 ("main", Normal, template!(Word), Ungated),
843 ("start", Normal, template!(Word), Ungated),
844 ("repr", Normal, template!(List: "C, packed, ..."), Ungated),
845 ("path", Normal, template!(NameValueStr: "file"), Ungated),
846 ("automatically_derived", Normal, template!(Word), Ungated),
847 ("no_mangle", Normal, template!(Word), Ungated),
848 ("no_link", Normal, template!(Word), Ungated),
849 ("derive", Normal, template!(List: "Trait1, Trait2, ..."), Ungated),
850 ("should_panic", Normal, template!(Word, List: r#"expected = "reason"#, NameValueStr: "reason"),
852 ("ignore", Normal, template!(Word, NameValueStr: "reason"), Ungated),
853 ("no_implicit_prelude", Normal, template!(Word), Ungated),
854 ("reexport_test_harness_main", Normal, template!(NameValueStr: "name"), Ungated),
855 ("link_args", Normal, template!(NameValueStr: "args"), Gated(Stability::Unstable,
857 "the `link_args` attribute is experimental and not \
858 portable across platforms, it is recommended to \
859 use `#[link(name = \"foo\")] instead",
860 cfg_fn!(link_args))),
861 ("macro_escape", Normal, template!(Word), Ungated),
864 ("structural_match", Whitelisted, template!(Word), Gated(Stability::Unstable,
866 "the semantics of constant patterns is \
868 cfg_fn!(structural_match))),
871 ("non_exhaustive", Whitelisted, template!(Word), Gated(Stability::Unstable,
873 "non exhaustive is an experimental feature",
874 cfg_fn!(non_exhaustive))),
877 ("marker", Normal, template!(Word), Gated(Stability::Unstable,
879 "marker traits is an experimental feature",
880 cfg_fn!(marker_trait_attr))),
882 ("plugin", CrateLevel, template!(List: "name|name(args)"), Gated(Stability::Unstable,
884 "compiler plugins are experimental \
888 ("no_std", CrateLevel, template!(Word), Ungated),
889 ("no_core", CrateLevel, template!(Word), Gated(Stability::Unstable,
891 "no_core is experimental",
893 ("lang", Normal, template!(NameValueStr: "name"), Gated(Stability::Unstable,
895 "language items are subject to change",
896 cfg_fn!(lang_items))),
897 ("linkage", Whitelisted, template!(NameValueStr: "external|internal|..."),
898 Gated(Stability::Unstable,
900 "the `linkage` attribute is experimental \
901 and not portable across platforms",
903 ("thread_local", Whitelisted, template!(Word), Gated(Stability::Unstable,
905 "`#[thread_local]` is an experimental feature, and does \
906 not currently handle destructors.",
907 cfg_fn!(thread_local))),
909 ("rustc_on_unimplemented", Normal, template!(List:
910 r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#,
911 NameValueStr: "message"),
912 Gated(Stability::Unstable,
914 "the `#[rustc_on_unimplemented]` attribute \
915 is an experimental feature",
916 cfg_fn!(on_unimplemented))),
917 ("rustc_const_unstable", Normal, template!(List: r#"feature = "name""#),
918 Gated(Stability::Unstable,
919 "rustc_const_unstable",
920 "the `#[rustc_const_unstable]` attribute \
921 is an internal feature",
922 cfg_fn!(rustc_const_unstable))),
923 ("global_allocator", Normal, template!(Word), Ungated),
924 ("default_lib_allocator", Whitelisted, template!(Word), Gated(Stability::Unstable,
925 "allocator_internals",
926 "the `#[default_lib_allocator]` \
927 attribute is an experimental feature",
928 cfg_fn!(allocator_internals))),
929 ("needs_allocator", Normal, template!(Word), Gated(Stability::Unstable,
930 "allocator_internals",
931 "the `#[needs_allocator]` \
932 attribute is an experimental \
934 cfg_fn!(allocator_internals))),
935 ("panic_runtime", Whitelisted, template!(Word), Gated(Stability::Unstable,
937 "the `#[panic_runtime]` attribute is \
938 an experimental feature",
939 cfg_fn!(panic_runtime))),
940 ("needs_panic_runtime", Whitelisted, template!(Word), Gated(Stability::Unstable,
941 "needs_panic_runtime",
942 "the `#[needs_panic_runtime]` \
943 attribute is an experimental \
945 cfg_fn!(needs_panic_runtime))),
946 ("rustc_outlives", Normal, template!(Word), Gated(Stability::Unstable,
948 "the `#[rustc_outlives]` attribute \
949 is just used for rustc unit tests \
950 and will never be stable",
951 cfg_fn!(rustc_attrs))),
952 ("rustc_variance", Normal, template!(Word), Gated(Stability::Unstable,
954 "the `#[rustc_variance]` attribute \
955 is just used for rustc unit tests \
956 and will never be stable",
957 cfg_fn!(rustc_attrs))),
958 ("rustc_layout", Normal, template!(List: "field1, field2, ..."),
959 Gated(Stability::Unstable,
961 "the `#[rustc_layout]` attribute \
962 is just used for rustc unit tests \
963 and will never be stable",
964 cfg_fn!(rustc_attrs))),
965 ("rustc_regions", Normal, template!(Word), Gated(Stability::Unstable,
967 "the `#[rustc_regions]` attribute \
968 is just used for rustc unit tests \
969 and will never be stable",
970 cfg_fn!(rustc_attrs))),
971 ("rustc_error", Whitelisted, template!(Word), Gated(Stability::Unstable,
973 "the `#[rustc_error]` attribute \
974 is just used for rustc unit tests \
975 and will never be stable",
976 cfg_fn!(rustc_attrs))),
977 ("rustc_dump_user_substs", Whitelisted, template!(Word), Gated(Stability::Unstable,
980 is just used for rustc unit tests \
981 and will never be stable",
982 cfg_fn!(rustc_attrs))),
983 ("rustc_if_this_changed", Whitelisted, template!(Word, List: "DepNode"),
984 Gated(Stability::Unstable,
986 "the `#[rustc_if_this_changed]` attribute \
987 is just used for rustc unit tests \
988 and will never be stable",
989 cfg_fn!(rustc_attrs))),
990 ("rustc_then_this_would_need", Whitelisted, template!(List: "DepNode"),
991 Gated(Stability::Unstable,
993 "the `#[rustc_if_this_changed]` attribute \
994 is just used for rustc unit tests \
995 and will never be stable",
996 cfg_fn!(rustc_attrs))),
997 ("rustc_dirty", Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
998 /*opt*/ except = "...""#),
999 Gated(Stability::Unstable,
1001 "the `#[rustc_dirty]` attribute \
1002 is just used for rustc unit tests \
1003 and will never be stable",
1004 cfg_fn!(rustc_attrs))),
1005 ("rustc_clean", Whitelisted, template!(List: r#"cfg = "...", /*opt*/ label = "...",
1006 /*opt*/ except = "...""#),
1007 Gated(Stability::Unstable,
1009 "the `#[rustc_clean]` attribute \
1010 is just used for rustc unit tests \
1011 and will never be stable",
1012 cfg_fn!(rustc_attrs))),
1013 ("rustc_partition_reused", Whitelisted, template!(List: r#"cfg = "...", module = "...""#),
1014 Gated(Stability::Unstable,
1017 is just used for rustc unit tests \
1018 and will never be stable",
1019 cfg_fn!(rustc_attrs))),
1020 ("rustc_partition_codegened", Whitelisted, template!(List: r#"cfg = "...", module = "...""#),
1021 Gated(Stability::Unstable,
1024 is just used for rustc unit tests \
1025 and will never be stable",
1026 cfg_fn!(rustc_attrs))),
1027 ("rustc_expected_cgu_reuse", Whitelisted, template!(List: r#"cfg = "...", module = "...",
1029 Gated(Stability::Unstable,
1032 is just used for rustc unit tests \
1033 and will never be stable",
1034 cfg_fn!(rustc_attrs))),
1035 ("rustc_synthetic", Whitelisted, template!(Word), Gated(Stability::Unstable,
1038 is just used for rustc unit tests \
1039 and will never be stable",
1040 cfg_fn!(rustc_attrs))),
1041 ("rustc_symbol_name", Whitelisted, template!(Word), Gated(Stability::Unstable,
1043 "internal rustc attributes will never be stable",
1044 cfg_fn!(rustc_attrs))),
1045 ("rustc_def_path", Whitelisted, template!(Word), Gated(Stability::Unstable,
1047 "internal rustc attributes will never be stable",
1048 cfg_fn!(rustc_attrs))),
1049 ("rustc_mir", Whitelisted, template!(List: "arg1, arg2, ..."), Gated(Stability::Unstable,
1051 "the `#[rustc_mir]` attribute \
1052 is just used for rustc unit tests \
1053 and will never be stable",
1054 cfg_fn!(rustc_attrs))),
1055 ("rustc_inherit_overflow_checks", Whitelisted, template!(Word), Gated(Stability::Unstable,
1057 "the `#[rustc_inherit_overflow_checks]` \
1058 attribute is just used to control \
1059 overflow checking behavior of several \
1060 libcore functions that are inlined \
1061 across crates and will never be stable",
1062 cfg_fn!(rustc_attrs))),
1064 ("rustc_dump_program_clauses", Whitelisted, template!(Word), Gated(Stability::Unstable,
1066 "the `#[rustc_dump_program_clauses]` \
1067 attribute is just used for rustc unit \
1068 tests and will never be stable",
1069 cfg_fn!(rustc_attrs))),
1070 ("rustc_test_marker", Normal, template!(Word), Gated(Stability::Unstable,
1072 "the `#[rustc_test_marker]` attribute \
1073 is used internally to track tests",
1074 cfg_fn!(rustc_attrs))),
1075 ("rustc_transparent_macro", Whitelisted, template!(Word), Gated(Stability::Unstable,
1077 "used internally for testing macro hygiene",
1078 cfg_fn!(rustc_attrs))),
1079 ("compiler_builtins", Whitelisted, template!(Word), Gated(Stability::Unstable,
1080 "compiler_builtins",
1081 "the `#[compiler_builtins]` attribute is used to \
1082 identify the `compiler_builtins` crate which \
1083 contains compiler-rt intrinsics and will never be \
1085 cfg_fn!(compiler_builtins))),
1086 ("sanitizer_runtime", Whitelisted, template!(Word), Gated(Stability::Unstable,
1087 "sanitizer_runtime",
1088 "the `#[sanitizer_runtime]` attribute is used to \
1089 identify crates that contain the runtime of a \
1090 sanitizer and will never be stable",
1091 cfg_fn!(sanitizer_runtime))),
1092 ("profiler_runtime", Whitelisted, template!(Word), Gated(Stability::Unstable,
1094 "the `#[profiler_runtime]` attribute is used to \
1095 identify the `profiler_builtins` crate which \
1096 contains the profiler runtime and will never be \
1098 cfg_fn!(profiler_runtime))),
1100 ("allow_internal_unstable", Normal, template!(Word, List: "feat1, feat2, ..."),
1101 Gated(Stability::Unstable,
1102 "allow_internal_unstable",
1103 EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
1104 cfg_fn!(allow_internal_unstable))),
1106 ("allow_internal_unsafe", Normal, template!(Word), Gated(Stability::Unstable,
1107 "allow_internal_unsafe",
1108 EXPLAIN_ALLOW_INTERNAL_UNSAFE,
1109 cfg_fn!(allow_internal_unsafe))),
1111 ("fundamental", Whitelisted, template!(Word), Gated(Stability::Unstable,
1113 "the `#[fundamental]` attribute \
1114 is an experimental feature",
1115 cfg_fn!(fundamental))),
1117 ("proc_macro_derive", Normal, template!(List: "TraitName, \
1118 /*opt*/ attributes(name1, name2, ...)"),
1121 ("rustc_copy_clone_marker", Whitelisted, template!(Word), Gated(Stability::Unstable,
1123 "internal implementation detail",
1124 cfg_fn!(rustc_attrs))),
1126 // FIXME: #14408 whitelist docs since rustdoc looks at them
1127 ("doc", Whitelisted, template!(List: "hidden|inline|...", NameValueStr: "string"), Ungated),
1129 // FIXME: #14406 these are processed in codegen, which happens after the
1131 ("cold", Whitelisted, template!(Word), Ungated),
1132 ("naked", Whitelisted, template!(Word), Gated(Stability::Unstable,
1134 "the `#[naked]` attribute \
1135 is an experimental feature",
1136 cfg_fn!(naked_functions))),
1137 ("ffi_returns_twice", Whitelisted, template!(Word), Gated(Stability::Unstable,
1138 "ffi_returns_twice",
1139 "the `#[ffi_returns_twice]` attribute \
1140 is an experimental feature",
1141 cfg_fn!(ffi_returns_twice))),
1142 ("target_feature", Whitelisted, template!(List: r#"enable = "name""#), Ungated),
1143 ("export_name", Whitelisted, template!(NameValueStr: "name"), Ungated),
1144 ("inline", Whitelisted, template!(Word, List: "always|never"), Ungated),
1145 ("link", Whitelisted, template!(List: r#"name = "...", /*opt*/ kind = "dylib|static|...",
1146 /*opt*/ cfg = "...""#), Ungated),
1147 ("link_name", Whitelisted, template!(NameValueStr: "name"), Ungated),
1148 ("link_section", Whitelisted, template!(NameValueStr: "name"), Ungated),
1149 ("no_builtins", Whitelisted, template!(Word), Ungated),
1150 ("no_mangle", Whitelisted, template!(Word), Ungated),
1151 ("no_debug", Whitelisted, template!(Word), Gated(
1152 Stability::Deprecated("https://github.com/rust-lang/rust/issues/29721", None),
1154 "the `#[no_debug]` attribute was an experimental feature that has been \
1155 deprecated due to lack of demand",
1156 cfg_fn!(no_debug))),
1157 ("omit_gdb_pretty_printer_section", Whitelisted, template!(Word), Gated(Stability::Unstable,
1158 "omit_gdb_pretty_printer_section",
1159 "the `#[omit_gdb_pretty_printer_section]` \
1160 attribute is just used for the Rust test \
1162 cfg_fn!(omit_gdb_pretty_printer_section))),
1163 ("unsafe_destructor_blind_to_params",
1166 Gated(Stability::Deprecated("https://github.com/rust-lang/rust/issues/34761",
1167 Some("replace this attribute with `#[may_dangle]`")),
1168 "dropck_parametricity",
1169 "unsafe_destructor_blind_to_params has been replaced by \
1170 may_dangle and will be removed in the future",
1171 cfg_fn!(dropck_parametricity))),
1175 Gated(Stability::Unstable,
1177 "may_dangle has unstable semantics and may be removed in the future",
1178 cfg_fn!(dropck_eyepatch))),
1179 ("unwind", Whitelisted, template!(List: "allowed|aborts"), Gated(Stability::Unstable,
1180 "unwind_attributes",
1181 "#[unwind] is experimental",
1182 cfg_fn!(unwind_attributes))),
1183 ("used", Whitelisted, template!(Word), Ungated),
1186 ("prelude_import", Whitelisted, template!(Word), Gated(Stability::Unstable,
1188 "`#[prelude_import]` is for use by rustc only",
1189 cfg_fn!(prelude_import))),
1191 // FIXME: #14407 these are only looked at on-demand so we can't
1192 // guarantee they'll have already been checked
1193 ("rustc_deprecated", Whitelisted, template!(List: r#"since = "version", reason = "...""#),
1195 ("must_use", Whitelisted, template!(Word, NameValueStr: "reason"), Ungated),
1196 ("stable", Whitelisted, template!(List: r#"feature = "name", since = "version""#), Ungated),
1197 ("unstable", Whitelisted, template!(List: r#"feature = "name", reason = "...", issue = "N""#),
1203 List: r#"/*opt*/ since = "version", /*opt*/ note = "reason"#,
1204 NameValueStr: "reason"
1209 ("rustc_paren_sugar", Normal, template!(Word), Gated(Stability::Unstable,
1211 "unboxed_closures are still evolving",
1212 cfg_fn!(unboxed_closures))),
1214 ("windows_subsystem", Whitelisted, template!(NameValueStr: "windows|console"), Ungated),
1216 ("proc_macro_attribute", Normal, template!(Word), Ungated),
1217 ("proc_macro", Normal, template!(Word), Ungated),
1219 ("rustc_proc_macro_decls", Normal, template!(Word), Gated(Stability::Unstable,
1221 "used internally by rustc",
1222 cfg_fn!(rustc_attrs))),
1224 ("allow_fail", Normal, template!(Word), Gated(Stability::Unstable,
1226 "allow_fail attribute is currently unstable",
1227 cfg_fn!(allow_fail))),
1229 ("rustc_std_internal_symbol", Whitelisted, template!(Word), Gated(Stability::Unstable,
1231 "this is an internal attribute that will \
1233 cfg_fn!(rustc_attrs))),
1235 // whitelists "identity-like" conversion methods to suggest on type mismatch
1236 ("rustc_conversion_suggestion", Whitelisted, template!(Word), Gated(Stability::Unstable,
1238 "this is an internal attribute that will \
1240 cfg_fn!(rustc_attrs))),
1242 ("rustc_args_required_const", Whitelisted, template!(List: "N"), Gated(Stability::Unstable,
1244 "never will be stable",
1245 cfg_fn!(rustc_attrs))),
1247 ("panic_handler", Normal, template!(Word), Ungated),
1249 ("alloc_error_handler", Normal, template!(Word), Gated(Stability::Unstable,
1250 "alloc_error_handler",
1251 "#[alloc_error_handler] is an unstable feature",
1252 cfg_fn!(alloc_error_handler))),
1255 ("optimize", Whitelisted, template!(List: "size|speed"), Gated(Stability::Unstable,
1256 "optimize_attribute",
1257 "#[optimize] attribute is an unstable feature",
1258 cfg_fn!(optimize_attribute))),
1260 // Crate level attributes
1261 ("crate_name", CrateLevel, template!(NameValueStr: "name"), Ungated),
1262 ("crate_type", CrateLevel, template!(NameValueStr: "bin|lib|..."), Ungated),
1263 ("crate_id", CrateLevel, template!(NameValueStr: "ignored"), Ungated),
1264 ("feature", CrateLevel, template!(List: "name1, name1, ..."), Ungated),
1265 ("no_start", CrateLevel, template!(Word), Ungated),
1266 ("no_main", CrateLevel, template!(Word), Ungated),
1267 ("no_builtins", CrateLevel, template!(Word), Ungated),
1268 ("recursion_limit", CrateLevel, template!(NameValueStr: "N"), Ungated),
1269 ("type_length_limit", CrateLevel, template!(NameValueStr: "N"), Ungated),
1270 ("test_runner", CrateLevel, template!(List: "path"), Gated(Stability::Unstable,
1271 "custom_test_frameworks",
1272 EXPLAIN_CUSTOM_TEST_FRAMEWORKS,
1273 cfg_fn!(custom_test_frameworks))),
1276 // cfg(...)'s that are feature gated
1277 const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
1278 // (name in cfg, feature, function to check if the feature is enabled)
1279 ("target_thread_local", "cfg_target_thread_local", cfg_fn!(cfg_target_thread_local)),
1280 ("target_has_atomic", "cfg_target_has_atomic", cfg_fn!(cfg_target_has_atomic)),
1281 ("rustdoc", "doc_cfg", cfg_fn!(doc_cfg)),
1285 pub struct GatedCfg {
1291 pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
1293 .position(|info| cfg.check_name(info.0))
1302 pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
1303 let (cfg, feature, has_feature) = GATED_CFGS[self.index];
1304 if !has_feature(features) && !self.span.allows_unstable(feature) {
1305 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
1306 emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
1311 struct Context<'a> {
1312 features: &'a Features,
1313 parse_sess: &'a ParseSess,
1314 plugin_attributes: &'a [(String, AttributeType)],
1317 macro_rules! gate_feature_fn {
1318 ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
1319 let (cx, has_feature, span,
1320 name, explain, level) = ($cx, $has_feature, $span, $name, $explain, $level);
1321 let has_feature: bool = has_feature(&$cx.features);
1322 debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
1323 if !has_feature && !span.allows_unstable($name) {
1324 leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level)
1330 macro_rules! gate_feature {
1331 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {
1332 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1333 stringify!($feature), $explain, GateStrength::Hard)
1335 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {
1336 gate_feature_fn!($cx, |x:&Features| x.$feature, $span,
1337 stringify!($feature), $explain, $level)
1341 impl<'a> Context<'a> {
1342 fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
1343 debug!("check_attribute(attr = {:?})", attr);
1344 let name = attr.name_or_empty();
1345 for &(n, ty, _template, ref gateage) in BUILTIN_ATTRIBUTES {
1347 if let Gated(_, name, desc, ref has_feature) = *gateage {
1348 if !attr.span.allows_unstable(name) {
1350 self, has_feature, attr.span, name, desc, GateStrength::Hard
1353 } else if n == "doc" {
1354 if let Some(content) = attr.meta_item_list() {
1355 if content.iter().any(|c| c.check_name("include")) {
1356 gate_feature!(self, external_doc, attr.span,
1357 "#[doc(include = \"...\")] is experimental"
1362 debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
1366 for &(ref n, ref ty) in self.plugin_attributes {
1367 if attr.path == &**n {
1368 // Plugins can't gate attributes, so we don't check for it
1369 // unlike the code above; we only use this loop to
1370 // short-circuit to avoid the checks below.
1371 debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty);
1375 if !attr::is_known(attr) {
1376 if name.starts_with("rustc_") {
1377 let msg = "unless otherwise specified, attributes with the prefix `rustc_` \
1378 are reserved for internal compiler diagnostics";
1379 gate_feature!(self, rustc_attrs, attr.span, msg);
1380 } else if !is_macro {
1381 // Only run the custom attribute lint during regular feature gate
1382 // checking. Macro gating runs before the plugin attributes are
1383 // registered, so we skip this in that case.
1384 let msg = format!("The attribute `{}` is currently unknown to the compiler and \
1385 may have meaning added to it in the future", attr.path);
1386 gate_feature!(self, custom_attribute, attr.span, &msg);
1392 pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features: &Features) {
1393 let cx = Context { features: features, parse_sess: parse_sess, plugin_attributes: &[] };
1394 cx.check_attribute(attr, true);
1397 fn find_lang_feature_issue(feature: &str) -> Option<u32> {
1398 if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.0 == feature) {
1400 // FIXME (#28244): enforce that active features have issue numbers
1401 // assert!(issue.is_some())
1404 // search in Accepted, Removed, or Stable Removed features
1405 let found = ACCEPTED_FEATURES.iter().chain(REMOVED_FEATURES).chain(STABLE_REMOVED_FEATURES)
1406 .find(|t| t.0 == feature);
1408 Some(&(_, _, issue, _)) => issue,
1409 None => panic!("Feature `{}` is not declared anywhere", feature),
1414 pub enum GateIssue {
1416 Library(Option<u32>)
1419 #[derive(Debug, Copy, Clone, PartialEq)]
1420 pub enum GateStrength {
1421 /// A hard error. (Most feature gates should use this.)
1423 /// Only a warning. (Use this only as backwards-compatibility demands.)
1427 pub fn emit_feature_err(sess: &ParseSess, feature: &str, span: Span, issue: GateIssue,
1429 feature_err(sess, feature, span, issue, explain).emit();
1432 pub fn feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1433 explain: &str) -> DiagnosticBuilder<'a> {
1434 leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
1437 fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue: GateIssue,
1438 explain: &str, level: GateStrength) -> DiagnosticBuilder<'a> {
1439 let diag = &sess.span_diagnostic;
1441 let issue = match issue {
1442 GateIssue::Language => find_lang_feature_issue(feature),
1443 GateIssue::Library(lib) => lib,
1446 let explanation = match issue {
1447 None | Some(0) => explain.to_owned(),
1448 Some(n) => format!("{} (see issue #{})", explain, n)
1451 let mut err = match level {
1452 GateStrength::Hard => {
1453 diag.struct_span_err_with_code(span, &explanation, stringify_error_code!(E0658))
1455 GateStrength::Soft => diag.struct_span_warn(span, &explanation),
1458 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
1459 if sess.unstable_features.is_nightly_build() {
1460 err.help(&format!("add #![feature({})] to the \
1461 crate attributes to enable",
1465 // If we're on stable and only emitting a "soft" warning, add a note to
1466 // clarify that the feature isn't "on" (rather than being on but
1468 if !sess.unstable_features.is_nightly_build() && level == GateStrength::Soft {
1469 err.help("a nightly build of the compiler is required to enable this feature");
1476 const EXPLAIN_BOX_SYNTAX: &str =
1477 "box expression syntax is experimental; you can call `Box::new` instead.";
1479 pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
1480 "attributes on expressions are experimental.";
1482 pub const EXPLAIN_ASM: &str =
1483 "inline assembly is not stable enough for use and is subject to change";
1485 pub const EXPLAIN_GLOBAL_ASM: &str =
1486 "`global_asm!` is not stable enough for use and is subject to change";
1488 pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str =
1489 "custom test frameworks are an unstable feature";
1491 pub const EXPLAIN_LOG_SYNTAX: &str =
1492 "`log_syntax!` is not stable enough for use and is subject to change";
1494 pub const EXPLAIN_CONCAT_IDENTS: &str =
1495 "`concat_idents` is not stable enough for use and is subject to change";
1497 pub const EXPLAIN_FORMAT_ARGS_NL: &str =
1498 "`format_args_nl` is only for internal language use and is subject to change";
1500 pub const EXPLAIN_TRACE_MACROS: &str =
1501 "`trace_macros` is not stable enough for use and is subject to change";
1502 pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
1503 "allow_internal_unstable side-steps feature gating and stability checks";
1504 pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
1505 "allow_internal_unsafe side-steps the unsafe_code lint";
1507 pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
1508 "unsized tuple coercion is not stable enough for use and is subject to change";
1510 struct PostExpansionVisitor<'a> {
1511 context: &'a Context<'a>,
1514 macro_rules! gate_feature_post {
1515 ($cx: expr, $feature: ident, $span: expr, $explain: expr) => {{
1516 let (cx, span) = ($cx, $span);
1517 if !span.allows_unstable(stringify!($feature)) {
1518 gate_feature!(cx.context, $feature, span, $explain)
1521 ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => {{
1522 let (cx, span) = ($cx, $span);
1523 if !span.allows_unstable(stringify!($feature)) {
1524 gate_feature!(cx.context, $feature, span, $explain, $level)
1529 impl<'a> PostExpansionVisitor<'a> {
1530 fn check_abi(&self, abi: Abi, span: Span) {
1532 Abi::RustIntrinsic => {
1533 gate_feature_post!(&self, intrinsics, span,
1534 "intrinsics are subject to change");
1536 Abi::PlatformIntrinsic => {
1537 gate_feature_post!(&self, platform_intrinsics, span,
1538 "platform intrinsics are experimental and possibly buggy");
1540 Abi::Vectorcall => {
1541 gate_feature_post!(&self, abi_vectorcall, span,
1542 "vectorcall is experimental and subject to change");
1545 gate_feature_post!(&self, abi_thiscall, span,
1546 "thiscall is experimental and subject to change");
1549 gate_feature_post!(&self, unboxed_closures, span,
1550 "rust-call ABI is subject to change");
1553 gate_feature_post!(&self, abi_ptx, span,
1554 "PTX ABIs are experimental and subject to change");
1556 Abi::Unadjusted => {
1557 gate_feature_post!(&self, abi_unadjusted, span,
1558 "unadjusted ABI is an implementation detail and perma-unstable");
1560 Abi::Msp430Interrupt => {
1561 gate_feature_post!(&self, abi_msp430_interrupt, span,
1562 "msp430-interrupt ABI is experimental and subject to change");
1564 Abi::X86Interrupt => {
1565 gate_feature_post!(&self, abi_x86_interrupt, span,
1566 "x86-interrupt ABI is experimental and subject to change");
1568 Abi::AmdGpuKernel => {
1569 gate_feature_post!(&self, abi_amdgpu_kernel, span,
1570 "amdgpu-kernel ABI is experimental and subject to change");
1585 fn check_builtin_attribute(&mut self, attr: &ast::Attribute, name: &str,
1586 template: AttributeTemplate) {
1587 // Some special attributes like `cfg` must be checked
1588 // before the generic check, so we skip them here.
1589 let should_skip = |name| name == "cfg";
1590 // Some of previously accepted forms were used in practice,
1591 // report them as warnings for now.
1592 let should_warn = |name| name == "doc" || name == "ignore" ||
1593 name == "inline" || name == "link";
1595 match attr.parse_meta(self.context.parse_sess) {
1596 Ok(meta) => if !should_skip(name) && !template.compatible(&meta.node) {
1597 let mut msg = "attribute must be of the form ".to_owned();
1598 let mut first = true;
1601 msg.push_str(&format!("`#[{}{}]`", name, ""));
1603 if let Some(descr) = template.list {
1605 msg.push_str(" or ");
1608 msg.push_str(&format!("`#[{}({})]`", name, descr));
1610 if let Some(descr) = template.name_value_str {
1612 msg.push_str(" or ");
1614 msg.push_str(&format!("`#[{} = \"{}\"]`", name, descr));
1616 if should_warn(name) {
1617 self.context.parse_sess.buffer_lint(
1618 BufferedEarlyLintId::IllFormedAttributeInput,
1624 self.context.parse_sess.span_diagnostic.span_err(meta.span, &msg);
1627 Err(mut err) => err.emit(),
1632 impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
1633 fn visit_attribute(&mut self, attr: &ast::Attribute) {
1634 // check for gated attributes
1635 self.context.check_attribute(attr, false);
1637 if attr.check_name("doc") {
1638 if let Some(content) = attr.meta_item_list() {
1639 if content.len() == 1 && content[0].check_name("cfg") {
1640 gate_feature_post!(&self, doc_cfg, attr.span,
1641 "#[doc(cfg(...))] is experimental"
1643 } else if content.iter().any(|c| c.check_name("masked")) {
1644 gate_feature_post!(&self, doc_masked, attr.span,
1645 "#[doc(masked)] is experimental"
1647 } else if content.iter().any(|c| c.check_name("spotlight")) {
1648 gate_feature_post!(&self, doc_spotlight, attr.span,
1649 "#[doc(spotlight)] is experimental"
1651 } else if content.iter().any(|c| c.check_name("alias")) {
1652 gate_feature_post!(&self, doc_alias, attr.span,
1653 "#[doc(alias = \"...\")] is experimental"
1655 } else if content.iter().any(|c| c.check_name("keyword")) {
1656 gate_feature_post!(&self, doc_keyword, attr.span,
1657 "#[doc(keyword = \"...\")] is experimental"
1663 match BUILTIN_ATTRIBUTES.iter().find(|(name, ..)| attr.path == name) {
1664 Some(&(name, _, template, _)) => self.check_builtin_attribute(attr, name, template),
1665 None => if let Some(TokenTree::Token(_, token::Eq)) = attr.tokens.trees().next() {
1666 // All key-value attributes are restricted to meta-item syntax.
1667 attr.parse_meta(self.context.parse_sess).map_err(|mut err| err.emit()).ok();
1672 fn visit_name(&mut self, sp: Span, name: ast::Name) {
1673 if !name.as_str().is_ascii() {
1674 gate_feature_post!(&self,
1676 self.context.parse_sess.source_map().def_span(sp),
1677 "non-ascii idents are not fully supported.");
1681 fn visit_item(&mut self, i: &'a ast::Item) {
1683 ast::ItemKind::Const(_,_) => {
1684 if i.ident.name == "_" {
1685 gate_feature_post!(&self, underscore_const_names, i.span,
1686 "naming constants with `_` is unstable");
1690 ast::ItemKind::ForeignMod(ref foreign_module) => {
1691 self.check_abi(foreign_module.abi, i.span);
1694 ast::ItemKind::Fn(..) => {
1695 if attr::contains_name(&i.attrs[..], "plugin_registrar") {
1696 gate_feature_post!(&self, plugin_registrar, i.span,
1697 "compiler plugins are experimental and possibly buggy");
1699 if attr::contains_name(&i.attrs[..], "start") {
1700 gate_feature_post!(&self, start, i.span,
1701 "a #[start] function is an experimental \
1702 feature whose signature may change \
1705 if attr::contains_name(&i.attrs[..], "main") {
1706 gate_feature_post!(&self, main, i.span,
1707 "declaration of a nonstandard #[main] \
1708 function may change over time, for now \
1709 a top-level `fn main()` is required");
1713 ast::ItemKind::Struct(..) => {
1714 for attr in attr::filter_by_name(&i.attrs[..], "repr") {
1715 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1716 if item.check_name("simd") {
1717 gate_feature_post!(&self, repr_simd, attr.span,
1718 "SIMD types are experimental and possibly buggy");
1724 ast::ItemKind::Enum(..) => {
1725 for attr in attr::filter_by_name(&i.attrs[..], "repr") {
1726 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
1727 if item.check_name("align") {
1728 gate_feature_post!(&self, repr_align_enum, attr.span,
1729 "`#[repr(align(x))]` on enums is experimental");
1735 ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
1736 if polarity == ast::ImplPolarity::Negative {
1737 gate_feature_post!(&self, optin_builtin_traits,
1739 "negative trait bounds are not yet fully implemented; \
1740 use marker types for now");
1743 if let ast::Defaultness::Default = defaultness {
1744 gate_feature_post!(&self, specialization,
1746 "specialization is unstable");
1750 ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => {
1751 gate_feature_post!(&self, optin_builtin_traits,
1753 "auto traits are experimental and possibly buggy");
1756 ast::ItemKind::TraitAlias(..) => {
1761 "trait aliases are experimental"
1765 ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
1766 let msg = "`macro` is experimental";
1767 gate_feature_post!(&self, decl_macro, i.span, msg);
1770 ast::ItemKind::Existential(..) => {
1775 "existential types are unstable"
1782 visit::walk_item(self, i);
1785 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
1787 ast::ForeignItemKind::Fn(..) |
1788 ast::ForeignItemKind::Static(..) => {
1789 let link_name = attr::first_attr_value_str_by_name(&i.attrs, "link_name");
1790 let links_to_llvm = match link_name {
1791 Some(val) => val.as_str().starts_with("llvm."),
1795 gate_feature_post!(&self, link_llvm_intrinsics, i.span,
1796 "linking to LLVM intrinsics is experimental");
1799 ast::ForeignItemKind::Ty => {
1800 gate_feature_post!(&self, extern_types, i.span,
1801 "extern types are experimental");
1803 ast::ForeignItemKind::Macro(..) => {}
1806 visit::walk_foreign_item(self, i)
1809 fn visit_ty(&mut self, ty: &'a ast::Ty) {
1811 ast::TyKind::BareFn(ref bare_fn_ty) => {
1812 self.check_abi(bare_fn_ty.abi, ty.span);
1814 ast::TyKind::Never => {
1815 gate_feature_post!(&self, never_type, ty.span,
1816 "The `!` type is experimental");
1820 visit::walk_ty(self, ty)
1823 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
1824 if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
1825 if let ast::TyKind::Never = output_ty.node {
1828 self.visit_ty(output_ty)
1833 fn visit_expr(&mut self, e: &'a ast::Expr) {
1835 ast::ExprKind::Box(_) => {
1836 gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
1838 ast::ExprKind::Type(..) => {
1839 // To avoid noise about type ascription in common syntax errors, only emit if it
1840 // is the *only* error.
1841 if self.context.parse_sess.span_diagnostic.err_count() == 0 {
1842 gate_feature_post!(&self, type_ascription, e.span,
1843 "type ascription is experimental");
1846 ast::ExprKind::ObsoleteInPlace(..) => {
1847 // these get a hard error in ast-validation
1849 ast::ExprKind::Yield(..) => {
1850 gate_feature_post!(&self, generators,
1852 "yield syntax is experimental");
1854 ast::ExprKind::TryBlock(_) => {
1855 gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
1857 ast::ExprKind::Block(_, opt_label) => {
1858 if let Some(label) = opt_label {
1859 gate_feature_post!(&self, label_break_value, label.ident.span,
1860 "labels on blocks are unstable");
1863 ast::ExprKind::Closure(_, ast::IsAsync::Async { .. }, ..) => {
1864 gate_feature_post!(&self, async_await, e.span, "async closures are unstable");
1866 ast::ExprKind::Async(..) => {
1867 gate_feature_post!(&self, async_await, e.span, "async blocks are unstable");
1871 visit::walk_expr(self, e);
1874 fn visit_arm(&mut self, arm: &'a ast::Arm) {
1875 visit::walk_arm(self, arm)
1878 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
1879 match pattern.node {
1880 PatKind::Slice(_, Some(ref subslice), _) => {
1881 gate_feature_post!(&self, slice_patterns,
1883 "syntax for subslices in slice patterns is not yet stabilized");
1885 PatKind::Box(..) => {
1886 gate_feature_post!(&self, box_patterns,
1888 "box pattern syntax is experimental");
1890 PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
1891 gate_feature_post!(&self, exclusive_range_pattern, pattern.span,
1892 "exclusive range pattern syntax is experimental");
1896 visit::walk_pat(self, pattern)
1899 fn visit_fn(&mut self,
1900 fn_kind: FnKind<'a>,
1901 fn_decl: &'a ast::FnDecl,
1905 FnKind::ItemFn(_, header, _, _) => {
1906 // Check for const fn and async fn declarations.
1907 if header.asyncness.node.is_async() {
1908 gate_feature_post!(&self, async_await, span, "async fn is unstable");
1911 if fn_decl.c_variadic {
1912 gate_feature_post!(&self, c_variadic, span,
1913 "C-varaidic functions are unstable");
1915 // Stability of const fn methods are covered in
1916 // `visit_trait_item` and `visit_impl_item` below; this is
1917 // because default methods don't pass through this point.
1919 self.check_abi(header.abi, span);
1921 FnKind::Method(_, sig, _, _) => {
1922 self.check_abi(sig.header.abi, span);
1926 visit::walk_fn(self, fn_kind, fn_decl, span);
1929 fn visit_generic_param(&mut self, param: &'a GenericParam) {
1930 if let GenericParamKind::Const { .. } = param.kind {
1931 gate_feature_post!(&self, const_generics, param.ident.span,
1932 "const generics are unstable");
1934 visit::walk_generic_param(self, param);
1937 fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
1939 ast::TraitItemKind::Method(ref sig, ref block) => {
1940 if block.is_none() {
1941 self.check_abi(sig.header.abi, ti.span);
1943 if sig.decl.c_variadic {
1944 gate_feature_post!(&self, c_variadic, ti.span,
1945 "C-varaidic functions are unstable");
1947 if sig.header.constness.node == ast::Constness::Const {
1948 gate_feature_post!(&self, const_fn, ti.span, "const fn is unstable");
1951 ast::TraitItemKind::Type(_, ref default) => {
1952 // We use three if statements instead of something like match guards so that all
1953 // of these errors can be emitted if all cases apply.
1954 if default.is_some() {
1955 gate_feature_post!(&self, associated_type_defaults, ti.span,
1956 "associated type defaults are unstable");
1958 if !ti.generics.params.is_empty() {
1959 gate_feature_post!(&self, generic_associated_types, ti.span,
1960 "generic associated types are unstable");
1962 if !ti.generics.where_clause.predicates.is_empty() {
1963 gate_feature_post!(&self, generic_associated_types, ti.span,
1964 "where clauses on associated types are unstable");
1969 visit::walk_trait_item(self, ti);
1972 fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
1973 if ii.defaultness == ast::Defaultness::Default {
1974 gate_feature_post!(&self, specialization,
1976 "specialization is unstable");
1980 ast::ImplItemKind::Method(..) => {}
1981 ast::ImplItemKind::Existential(..) => {
1986 "existential types are unstable"
1989 ast::ImplItemKind::Type(_) => {
1990 if !ii.generics.params.is_empty() {
1991 gate_feature_post!(&self, generic_associated_types, ii.span,
1992 "generic associated types are unstable");
1994 if !ii.generics.where_clause.predicates.is_empty() {
1995 gate_feature_post!(&self, generic_associated_types, ii.span,
1996 "where clauses on associated types are unstable");
2001 visit::walk_impl_item(self, ii);
2004 fn visit_vis(&mut self, vis: &'a ast::Visibility) {
2005 if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node {
2006 gate_feature_post!(&self, crate_visibility_modifier, vis.span,
2007 "`crate` visibility modifier is experimental");
2009 visit::walk_vis(self, vis);
2013 pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
2014 crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features {
2015 fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
2016 let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
2017 if let Some(reason) = reason {
2018 err.span_note(span, reason);
2023 // Some features are known to be incomplete and using them is likely to have
2024 // unanticipated results, such as compiler crashes. We warn the user about these
2026 let incomplete_features = ["generic_associated_types", "const_generics"];
2028 let mut features = Features::new();
2029 let mut edition_enabled_features = FxHashMap::default();
2031 for &edition in ALL_EDITIONS {
2032 if edition <= crate_edition {
2033 // The `crate_edition` implies its respective umbrella feature-gate
2034 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
2035 edition_enabled_features.insert(Symbol::intern(edition.feature_name()), edition);
2039 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2040 if let Some(f_edition) = f_edition {
2041 if f_edition <= crate_edition {
2042 set(&mut features, DUMMY_SP);
2043 edition_enabled_features.insert(Symbol::intern(name), crate_edition);
2048 // Process the edition umbrella feature-gates first, to ensure
2049 // `edition_enabled_features` is completed before it's queried.
2050 for attr in krate_attrs {
2051 if !attr.check_name("feature") {
2055 let list = match attr.meta_item_list() {
2065 let name = mi.name_or_empty();
2066 if incomplete_features.iter().any(|f| name == *f) {
2067 span_handler.struct_span_warn(
2070 "the feature `{}` is incomplete and may cause the compiler to crash",
2076 if let Some(edition) = ALL_EDITIONS.iter().find(|e| name == e.feature_name()) {
2077 if *edition <= crate_edition {
2081 for &(name, .., f_edition, set) in ACTIVE_FEATURES {
2082 if let Some(f_edition) = f_edition {
2083 if f_edition <= *edition {
2084 // FIXME(Manishearth) there is currently no way to set
2085 // lib features by edition
2086 set(&mut features, DUMMY_SP);
2087 edition_enabled_features.insert(Symbol::intern(name), *edition);
2095 for attr in krate_attrs {
2096 if !attr.check_name("feature") {
2100 let list = match attr.meta_item_list() {
2106 let name = match mi.ident() {
2107 Some(ident) if mi.is_word() => ident.name,
2109 span_err!(span_handler, mi.span(), E0556,
2110 "malformed feature, expected just one word");
2115 if let Some(edition) = edition_enabled_features.get(&name) {
2120 "the feature `{}` is included in the Rust {} edition",
2127 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
2128 // Handled in the separate loop above.
2132 if let Some((.., set)) = ACTIVE_FEATURES.iter().find(|f| name == f.0) {
2133 if let Some(allowed) = allow_features.as_ref() {
2134 if allowed.iter().find(|f| *f == name.as_str()).is_none() {
2135 span_err!(span_handler, mi.span(), E0725,
2136 "the feature `{}` is not in the list of allowed features",
2142 set(&mut features, mi.span());
2143 features.declared_lang_features.push((name, mi.span(), None));
2147 let removed = REMOVED_FEATURES.iter().find(|f| name == f.0);
2148 let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.0);
2149 if let Some((.., reason)) = removed.or(stable_removed) {
2150 feature_removed(span_handler, mi.span(), *reason);
2154 if let Some((_, since, ..)) = ACCEPTED_FEATURES.iter().find(|f| name == f.0) {
2155 let since = Some(Symbol::intern(since));
2156 features.declared_lang_features.push((name, mi.span(), since));
2160 features.declared_lib_features.push((name, mi.span()));
2167 pub fn check_crate(krate: &ast::Crate,
2169 features: &Features,
2170 plugin_attributes: &[(String, AttributeType)],
2171 unstable: UnstableFeatures) {
2172 maybe_stage_features(&sess.span_diagnostic, krate, unstable);
2179 let visitor = &mut PostExpansionVisitor { context: &ctx };
2180 visit::walk_crate(visitor, krate);
2183 #[derive(Clone, Copy, Hash)]
2184 pub enum UnstableFeatures {
2185 /// Hard errors for unstable features are active, as on beta/stable channels.
2187 /// Allow features to be activated, as on nightly.
2189 /// Errors are bypassed for bootstrapping. This is required any time
2190 /// during the build that feature-related lints are set to warn or above
2191 /// because the build turns on warnings-as-errors and uses lots of unstable
2192 /// features. As a result, this is always required for building Rust itself.
2196 impl UnstableFeatures {
2197 pub fn from_environment() -> UnstableFeatures {
2198 // Whether this is a feature-staged build, i.e., on the beta or stable channel
2199 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
2200 // Whether we should enable unstable features for bootstrapping
2201 let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
2202 match (disable_unstable_features, bootstrap) {
2203 (_, true) => UnstableFeatures::Cheat,
2204 (true, _) => UnstableFeatures::Disallow,
2205 (false, _) => UnstableFeatures::Allow
2209 pub fn is_nightly_build(&self) -> bool {
2211 UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
2217 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate,
2218 unstable: UnstableFeatures) {
2219 let allow_features = match unstable {
2220 UnstableFeatures::Allow => true,
2221 UnstableFeatures::Disallow => false,
2222 UnstableFeatures::Cheat => true
2224 if !allow_features {
2225 for attr in &krate.attrs {
2226 if attr.check_name("feature") {
2227 let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)");
2228 span_err!(span_handler, attr.span, E0554,
2229 "#![feature] may not be used on the {} release channel",