rustc_passes/
lib_features.rs

1//! Detecting lib features (i.e., features that are not lang features).
2//!
3//! These are declared using stability attributes (e.g., `#[stable (..)]` and `#[unstable (..)]`),
4//! but are not declared in one single location (unlike lang features), which means we need to
5//! collect them instead.
6
7use rustc_attr_parsing::VERSION_PLACEHOLDER;
8use rustc_hir::Attribute;
9use rustc_hir::intravisit::Visitor;
10use rustc_middle::hir::nested_filter;
11use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};
12use rustc_middle::query::{LocalCrate, Providers};
13use rustc_middle::ty::TyCtxt;
14use rustc_span::{Span, Symbol, sym};
15
16use crate::errors::{FeaturePreviouslyDeclared, FeatureStableTwice};
17
18struct LibFeatureCollector<'tcx> {
19    tcx: TyCtxt<'tcx>,
20    lib_features: LibFeatures,
21}
22
23impl<'tcx> LibFeatureCollector<'tcx> {
24    fn new(tcx: TyCtxt<'tcx>) -> LibFeatureCollector<'tcx> {
25        LibFeatureCollector { tcx, lib_features: LibFeatures::default() }
26    }
27
28    fn extract(&self, attr: &Attribute) -> Option<(Symbol, FeatureStability, Span)> {
29        let stab_attrs = [
30            sym::stable,
31            sym::unstable,
32            sym::rustc_const_stable,
33            sym::rustc_const_unstable,
34            sym::rustc_default_body_unstable,
35        ];
36
37        // Find a stability attribute: one of #[stable(…)], #[unstable(…)],
38        // #[rustc_const_stable(…)], #[rustc_const_unstable(…)] or #[rustc_default_body_unstable].
39        if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| attr.has_name(**stab_attr)) {
40            if let Some(metas) = attr.meta_item_list() {
41                let mut feature = None;
42                let mut since = None;
43                for meta in metas {
44                    if let Some(mi) = meta.meta_item() {
45                        // Find the `feature = ".."` meta-item.
46                        match (mi.name_or_empty(), mi.value_str()) {
47                            (sym::feature, val) => feature = val,
48                            (sym::since, val) => since = val,
49                            _ => {}
50                        }
51                    }
52                }
53
54                if let Some(s) = since
55                    && s.as_str() == VERSION_PLACEHOLDER
56                {
57                    since = Some(sym::env_CFG_RELEASE);
58                }
59
60                if let Some(feature) = feature {
61                    // This additional check for stability is to make sure we
62                    // don't emit additional, irrelevant errors for malformed
63                    // attributes.
64                    let is_unstable = matches!(
65                        *stab_attr,
66                        sym::unstable
67                            | sym::rustc_const_unstable
68                            | sym::rustc_default_body_unstable
69                    );
70                    if is_unstable {
71                        return Some((feature, FeatureStability::Unstable, attr.span));
72                    }
73                    if let Some(since) = since {
74                        return Some((feature, FeatureStability::AcceptedSince(since), attr.span));
75                    }
76                }
77                // We need to iterate over the other attributes, because
78                // `rustc_const_unstable` is not mutually exclusive with
79                // the other stability attributes, so we can't just `break`
80                // here.
81            }
82        }
83
84        None
85    }
86
87    fn collect_feature(&mut self, feature: Symbol, stability: FeatureStability, span: Span) {
88        let existing_stability = self.lib_features.stability.get(&feature).cloned();
89
90        match (stability, existing_stability) {
91            (_, None) => {
92                self.lib_features.stability.insert(feature, (stability, span));
93            }
94            (
95                FeatureStability::AcceptedSince(since),
96                Some((FeatureStability::AcceptedSince(prev_since), _)),
97            ) => {
98                if prev_since != since {
99                    self.tcx.dcx().emit_err(FeatureStableTwice {
100                        span,
101                        feature,
102                        since,
103                        prev_since,
104                    });
105                }
106            }
107            (FeatureStability::AcceptedSince(_), Some((FeatureStability::Unstable, _))) => {
108                self.tcx.dcx().emit_err(FeaturePreviouslyDeclared {
109                    span,
110                    feature,
111                    declared: "stable",
112                    prev_declared: "unstable",
113                });
114            }
115            (FeatureStability::Unstable, Some((FeatureStability::AcceptedSince(_), _))) => {
116                self.tcx.dcx().emit_err(FeaturePreviouslyDeclared {
117                    span,
118                    feature,
119                    declared: "unstable",
120                    prev_declared: "stable",
121                });
122            }
123            // duplicate `unstable` feature is ok.
124            (FeatureStability::Unstable, Some((FeatureStability::Unstable, _))) => {}
125        }
126    }
127}
128
129impl<'tcx> Visitor<'tcx> for LibFeatureCollector<'tcx> {
130    type NestedFilter = nested_filter::All;
131
132    fn nested_visit_map(&mut self) -> Self::Map {
133        self.tcx.hir()
134    }
135
136    fn visit_attribute(&mut self, attr: &'tcx Attribute) {
137        if let Some((feature, stable, span)) = self.extract(attr) {
138            self.collect_feature(feature, stable, span);
139        }
140    }
141}
142
143fn lib_features(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> LibFeatures {
144    // If `staged_api` is not enabled then we aren't allowed to define lib
145    // features; there is no point collecting them.
146    if !tcx.features().staged_api() {
147        return LibFeatures::default();
148    }
149
150    let mut collector = LibFeatureCollector::new(tcx);
151    tcx.hir().walk_attributes(&mut collector);
152    collector.lib_features
153}
154
155pub(crate) fn provide(providers: &mut Providers) {
156    providers.lib_features = lib_features;
157}