Feature Gate Checking

For the how-to steps to add, remove, rename, or stabilize feature gates, see Feature gates.

Feature gates prevent usage of unstable language and library features without a nightly-only #![feature(...)] opt-in. This chapter documents the implementation of feature gating: where gates are defined, how they are enabled, and how usage is verified.

Feature Definitions

All feature gate definitions are located in the rustc_feature crate:

The rustc_feature::Features type represents the active feature set for a crate. Helpers like enabled, incomplete, and internal are used during compilation to check status.

Collecting Features

Before AST validation or expansion, rustc collects crate-level #![feature(...)] attributes to build the active Features set.

Parser Gating

Some syntax is detected and gated during parsing. The parser records spans for later checking to keep diagnostics consistent and deferred until after parsing.

Checking Pass

The central logic lives in rustc_ast_passes/src/feature_gate.rs, primarily in check_crate and its AST visitor.

check_crate

check_crate performs high-level validation:

Checking GatedSpans

check_crate iterates over sess.psess.gated_spans:

AST Visitor

A PostExpansionVisitor walks the expanded AST to check constructs that are easier to validate after expansion.

Attributes and cfg

Beyond syntax, rustc also gates attributes and cfg options.

Built-in attributes

cfg options

Diagnostics

Diagnostic helpers are located in rustc_session/src/parse.rs.