Skip to main content

clippy_utils/
msrvs.rs

1use crate::{is_in_const_context, sym};
2use rustc_ast::Attribute;
3use rustc_attr_ir::{RustcVersion, StabilityLevel, StableSince};
4use rustc_attr_parsing::parse_version;
5use rustc_data_structures::smallvec::SmallVec;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::DefId;
8use rustc_hir::{Constness, HirId};
9use rustc_lint::LateContext;
10use rustc_middle::ty::TyCtxt;
11use rustc_session::Session;
12use std::iter::once;
13use std::sync::atomic::{AtomicBool, Ordering};
14
15macro_rules! msrv_aliases {
16    ($($major:literal,$minor:literal,$patch:literal {
17        $($name:ident),* $(,)?
18    })*) => {
19        $($(
20        pub const $name: RustcVersion = RustcVersion { major: $major, minor :$minor, patch: $patch };
21        )*)*
22    };
23}
24
25// names may refer to stabilized feature flags or library items
26msrv_aliases! {
27    1,99,0 { BOX_INTO_NON_NULL }
28    1,98,0 { MAP_OR_DEFAULT, NONZERO_FROM_STR_RADIX }
29    1,97,0 { ISOLATE_LOWEST_ONE, BIT_WIDTH }
30    1,94,0 { EULER_GAMMA, GOLDEN_RATIO, MUL_ADD_CONST }
31    1,93,0 { VEC_DEQUE_POP_BACK_IF, VEC_DEQUE_POP_FRONT_IF }
32    1,91,0 { DURATION_FROM_MINUTES_HOURS }
33    1,89,0 { NONNULL_FROM_MUT }
34    1,88,0 { LET_CHAINS, AS_CHUNKS, RAW_PTR_DEFAULT }
35    1,87,0 {
36        OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF, INTEGER_SIGN_CAST,
37        CONST_STR_FROM_UTF8_UNCHECKED_MUT, CONST_STR_FROM_UTF8_UNCHECKED, STR_FROM_UTF8, STR_FROM_UTF8_MUT
38    }
39    1,86,0 { VEC_POP_IF }
40    1,85,0 {
41        UINT_FLOAT_MIDPOINT, CONST_SIZE_OF_VAL, WAKER_NOOP, ABS_CONST, RADIANS_CONST, CONST_MEM_SWAP, CONST_PTR_SWAP,
42    }
43    1,84,0 { CONST_OPTION_AS_SLICE, MANUAL_DANGLING_PTR }
44    1,83,0 {
45        CONST_EXTERN_FN, CONST_FLOAT_BITS_CONV, CONST_FLOAT_CLASSIFY, CONST_MUT_REFS, CONST_UNWRAP,
46        CONST_STD_STR_FROM_UTF8_UNCHECKED_MUT
47    }
48    1,82,0 { IS_NONE_OR, REPEAT_N, RAW_REF_OP, SPECIALIZED_TO_STRING_FOR_REFS }
49    1,81,0 { LINT_REASONS_STABILIZATION, ERROR_IN_CORE, EXPLICIT_SELF_TYPE_ELISION, DURATION_ABS_DIFF }
50    1,80,0 { BOX_INTO_ITER, LAZY_CELL, BINARY_HEAP_AS_SLICE }
51    1,79,0 { CONST_BLOCKS, CSTR_COUNT_BYTES }
52    1,77,0 { C_STR_LITERALS }
53    1,76,0 { PTR_FROM_REF, OPTION_RESULT_INSPECT }
54    1,75,0 { OPTION_AS_SLICE }
55    1,74,0 { REPR_RUST, IO_ERROR_OTHER }
56    1,73,0 { DIV_CEIL }
57    1,71,0 { TUPLE_ARRAY_CONVERSIONS, BUILD_HASHER_HASH_ONE }
58    1,70,0 { OPTION_RESULT_IS_VARIANT_AND, BINARY_HEAP_RETAIN }
59    1,68,0 { PATH_MAIN_SEPARATOR_STR, PIN_MACRO }
60    1,67,0 { ILOG2 }
61    1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS }
62    1,63,0 { CLONE_INTO, CONST_SLICE_FROM_REF }
63    1,62,0 { BOOL_THEN_SOME, DEFAULT_ENUM_ATTRIBUTE, CONST_EXTERN_C_FN }
64    1,61,0 { CONST_FN_TRAIT_BOUND }
65    1,60,0 { ABS_DIFF }
66    1,59,0 { THREAD_LOCAL_CONST_INIT }
67    1,58,0 { FORMAT_ARGS_CAPTURE, PATTERN_TRAIT_CHAR_ARRAY, CONST_RAW_PTR_DEREF }
68    1,57,0 { MAP_WHILE, CONST_PANIC }
69    1,56,0 { CONST_FN_UNION }
70    1,55,0 { SEEK_REWIND, CONST_STD_STR_FROM_UTF8_UNCHECKED }
71    1,54,0 { INTO_KEYS }
72    1,53,0 { OR_PATTERNS, INTEGER_BITS, BTREE_MAP_RETAIN, BTREE_SET_RETAIN, ARRAY_INTO_ITERATOR }
73    1,52,0 { STR_SPLIT_ONCE, REM_EUCLID_CONST }
74    1,51,0 { BORROW_AS_PTR, SEEK_FROM_CURRENT, UNSIGNED_ABS }
75    1,50,0 { BOOL_THEN, CLAMP, SLICE_FILL }
76    1,47,0 { TAU, IS_ASCII_DIGIT_CONST, ARRAY_IMPL_ANY_LEN, SATURATING_SUB_CONST }
77    1,46,0 { CONST_IF_MATCH, OPTION_ZIP }
78    1,45,0 { STR_STRIP_PREFIX }
79    1,43,0 { LOG2_10, LOG10_2, NUMERIC_ASSOCIATED_CONSTANTS }
80    1,42,0 { MATCHES_MACRO, SLICE_PATTERNS, PTR_SLICE_RAW_PARTS }
81    1,41,0 { RE_REBALANCING_COHERENCE, RESULT_MAP_OR, RESULT_MAP_OR_ELSE }
82    1,40,0 { MEM_TAKE, NON_EXHAUSTIVE, OPTION_AS_DEREF }
83    1,38,0 { POINTER_CAST, REM_EUCLID }
84    1,37,0 { TYPE_ALIAS_ENUM_VARIANTS }
85    1,36,0 { ITERATOR_COPIED }
86    1,35,0 { OPTION_COPIED, RANGE_CONTAINS }
87    1,34,0 { TRY_FROM }
88    1,33,0 { UNDERSCORE_IMPORTS }
89    1,32,0 { CONST_IS_POWER_OF_TWO, CONST_DURATION_FROM_NANOS_MICROS_MILLIS_SECS }
90    1,31,0 { OPTION_REPLACE }
91    1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES }
92    1,29,0 { ITER_FLATTEN }
93    1,28,0 { FROM_BOOL, REPEAT_WITH, SLICE_FROM_REF }
94    1,27,0 { ITERATOR_TRY_FOLD, DOUBLE_ENDED_ITERATOR_RFIND, DURATION_FROM_NANOS_MICROS }
95    1,26,0 { RANGE_INCLUSIVE, STRING_RETAIN, POINTER_ADD_SUB_METHODS, BOX_LEAK }
96    1,24,0 { IS_ASCII_DIGIT, PTR_NULL }
97    1,20,0 { STD_STR_FROM_UTF8_MUT }
98    1,18,0 { HASH_MAP_RETAIN, HASH_SET_RETAIN }
99    1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR }
100    1,16,0 { STR_REPEAT, RESULT_UNWRAP_OR_DEFAULT }
101    1,15,0 { MAYBE_BOUND_IN_WHERE }
102    1,13,0 { QUESTION_MARK_OPERATOR }
103    1,6,0 { CORE_PTR_SWAP, CORE_STR_FROM_UTF8 }
104    1,3,0 { DURATION_FROM_MILLIS_SECS }
105}
106
107/// `#[clippy::msrv]` attributes are rarely used outside of Clippy's test suite, as a basic
108/// optimization we can skip traversing the HIR in [`Msrv::meets`] if we never saw an MSRV attribute
109/// during the early lint passes
110static SEEN_MSRV_ATTR: AtomicBool = AtomicBool::new(false);
111
112/// Tracks the current MSRV from `clippy.toml`, `Cargo.toml` or set via `#[clippy::msrv]` in late
113/// lint passes, use [`MsrvStack`] for early passes
114#[derive(Copy, Clone, Debug, Default)]
115pub struct Msrv(Option<RustcVersion>);
116
117impl From<Option<RustcVersion>> for Msrv {
118    #[inline]
119    fn from(value: Option<RustcVersion>) -> Self {
120        Self(value)
121    }
122}
123
124impl Msrv {
125    /// Returns the MSRV at the current node
126    ///
127    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
128    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
129    pub fn current(self, cx: &LateContext<'_>) -> Option<RustcVersion> {
130        if SEEN_MSRV_ATTR.load(Ordering::Relaxed) {
131            self.for_attrs(cx.tcx, cx.last_node_with_lint_attrs)
132        } else {
133            self.0
134        }
135    }
136
137    /// Returns the MSRV at the specified node
138    ///
139    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
140    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
141    pub fn at(self, tcx: TyCtxt<'_>, node: HirId) -> Option<RustcVersion> {
142        if SEEN_MSRV_ATTR.load(Ordering::Relaxed) {
143            self.for_attrs(tcx, node)
144        } else {
145            self.0
146        }
147    }
148
149    fn for_attrs(self, tcx: TyCtxt<'_>, node: HirId) -> Option<RustcVersion> {
150        once(node)
151            .chain(tcx.hir_parent_id_iter(node))
152            .find_map(|id| parse_hir_attrs(tcx.hir_attrs(id)))
153            .or(self.0)
154    }
155
156    /// Checks if a required version from [this module](self) is met at the current node
157    ///
158    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
159    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
160    pub fn meets(self, cx: &LateContext<'_>, required: RustcVersion) -> bool {
161        self.current(cx).is_none_or(|msrv| msrv >= required)
162    }
163    /// Checks if a required version from [this module](self) is met at the specified node
164    ///
165    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
166    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
167    pub fn meets_at(self, tcx: TyCtxt<'_>, node: HirId, required: RustcVersion) -> bool {
168        self.at(tcx, node).is_none_or(|msrv| msrv >= required)
169    }
170
171    pub fn is_stable(self, cx: &LateContext<'_>, def_id: DefId) -> bool {
172        self.stability_met(cx, cx.tcx.lookup_stability(def_id).map(|stability| stability.level))
173    }
174
175    /// Checks whether `def_id` is `const` and const-stable since a version met by the MSRV.
176    ///
177    /// `def_id` must identify a function-like definition or an impl.
178    ///
179    /// Nothing in the crate being linted carries a const-stability attribute, so `const` fns and
180    /// impls defined there are treated as meeting any MSRV, mirroring
181    /// [`is_stable`](Self::is_stable).
182    pub fn is_const_stable(self, cx: &LateContext<'_>, def_id: DefId) -> bool {
183        let constness = match cx.tcx.def_kind(def_id) {
184            // The constness of a trait impl is not encoded in crate metadata, where `constness`
185            // would decode as its default of `Const`. It is only available from the impl header.
186            DefKind::Impl { of_trait: true } => cx.tcx.impl_trait_header(def_id).constness,
187            _ => cx.tcx.constness(def_id),
188        };
189
190        matches!(constness, Constness::Const { .. })
191            && self.stability_met(
192                cx,
193                cx.tcx.lookup_const_stability(def_id).map(|stability| stability.level),
194            )
195    }
196
197    /// Checks the stability relevant to where we are: const-stability inside a `const` context,
198    /// regular stability everywhere else.
199    ///
200    /// Like [`is_in_const_context`], this requires the `LateContext` to have an enclosing body.
201    pub fn is_stable_or_const_stable(self, cx: &LateContext<'_>, def_id: DefId) -> bool {
202        if is_in_const_context(cx) {
203            self.is_const_stable(cx, def_id)
204        } else {
205            self.is_stable(cx, def_id)
206        }
207    }
208
209    fn stability_met(self, cx: &LateContext<'_>, level: Option<StabilityLevel>) -> bool {
210        level.is_none_or(|level| {
211            if let StabilityLevel::Stable { since, .. } = level {
212                let version = match since {
213                    StableSince::Version(version) => version,
214                    StableSince::Current => RustcVersion::CURRENT,
215                    StableSince::Err(_) => return false,
216                };
217
218                self.meets(cx, version)
219            } else {
220                // Unstable fn.
221                // FIXME: can we check that the feature is enabled?
222                // Please see https://github.com/rust-lang/rust-clippy/pull/17309#discussion_r3486693263 for false-positive concerns.
223                false
224            }
225        })
226    }
227}
228
229/// Tracks the current MSRV from `clippy.toml`, `Cargo.toml` or set via `#[clippy::msrv]` in early
230/// lint passes, use [`Msrv`] for late passes
231#[derive(Debug, Clone)]
232pub struct MsrvStack {
233    stack: SmallVec<[RustcVersion; 2]>,
234}
235
236impl From<Option<RustcVersion>> for MsrvStack {
237    #[inline]
238    fn from(value: Option<RustcVersion>) -> Self {
239        Self {
240            stack: SmallVec::from_iter(value),
241        }
242    }
243}
244
245impl MsrvStack {
246    pub fn current(&self) -> Option<RustcVersion> {
247        self.stack.last().copied()
248    }
249
250    pub fn meets(&self, required: RustcVersion) -> bool {
251        self.current().is_none_or(|msrv| msrv >= required)
252    }
253
254    pub fn check_attributes(&mut self, attrs: &[Attribute]) {
255        if let Some(version) = parse_ast_attrs(attrs) {
256            SEEN_MSRV_ATTR.store(true, Ordering::Relaxed);
257            self.stack.push(version);
258        }
259    }
260
261    pub fn check_attributes_post(&mut self, attrs: &[Attribute]) {
262        if parse_ast_attrs(attrs).is_some() {
263            self.stack.pop();
264        }
265    }
266}
267
268fn parse_ast_attrs(attrs: &[Attribute]) -> Option<RustcVersion> {
269    let msrv_attr = attrs.iter().find(|attr| attr.path_matches(&[sym::clippy, sym::msrv]))?;
270    parse_version(msrv_attr.value_str()?)
271}
272
273fn parse_hir_attrs(attrs: &[rustc_attr_ir::Attribute]) -> Option<RustcVersion> {
274    let msrv = attrs.iter().find_map(|attr| {
275        if let rustc_attr_ir::Attribute::Tool { item, .. } = attr
276            && let [sym::clippy, sym::msrv] = item.path.segments
277        {
278            attr.value_lit().and_then(rustc_ast::MetaItemLit::value_as_str)
279        } else {
280            None
281        }
282    })?;
283    parse_version(msrv)
284}
285
286pub fn check_attrs(sess: &Session, attrs: &[Attribute]) {
287    let mut msrv_attrs = attrs.iter().filter(|attr| attr.path_matches(&[sym::clippy, sym::msrv]));
288
289    let Some(msrv_attr) = msrv_attrs.next() else {
290        return;
291    };
292
293    if let Some(duplicate) = msrv_attrs.next_back() {
294        sess.dcx()
295            .struct_span_err(duplicate.span, "`clippy::msrv` is defined multiple times")
296            .with_span_note(msrv_attr.span, "first definition found here")
297            .emit();
298    }
299
300    let Some(msrv) = msrv_attr.value_str() else {
301        sess.dcx().span_err(msrv_attr.span, "bad clippy attribute");
302        return;
303    };
304
305    if parse_version(msrv).is_none() {
306        sess.dcx()
307            .span_err(msrv_attr.span, format!("`{msrv}` is not a valid Rust version"));
308    }
309}