clippy_utils/
msrvs.rs

1use crate::sym;
2use rustc_ast::Attribute;
3use rustc_ast::attr::AttributeExt;
4use rustc_attr_parsing::parse_version;
5use rustc_hir::RustcVersion;
6use rustc_lint::LateContext;
7use rustc_session::Session;
8use rustc_span::Symbol;
9use serde::Deserialize;
10use smallvec::SmallVec;
11use std::iter::once;
12use std::sync::atomic::{AtomicBool, Ordering};
13
14macro_rules! msrv_aliases {
15    ($($major:literal,$minor:literal,$patch:literal {
16        $($name:ident),* $(,)?
17    })*) => {
18        $($(
19        pub const $name: RustcVersion = RustcVersion { major: $major, minor :$minor, patch: $patch };
20        )*)*
21    };
22}
23
24// names may refer to stabilized feature flags or library items
25msrv_aliases! {
26    1,88,0 { LET_CHAINS }
27    1,87,0 { OS_STR_DISPLAY, INT_MIDPOINT, CONST_CHAR_IS_DIGIT, UNSIGNED_IS_MULTIPLE_OF, INTEGER_SIGN_CAST }
28    1,85,0 { UINT_FLOAT_MIDPOINT, CONST_SIZE_OF_VAL }
29    1,84,0 { CONST_OPTION_AS_SLICE, MANUAL_DANGLING_PTR }
30    1,83,0 { CONST_EXTERN_FN, CONST_FLOAT_BITS_CONV, CONST_FLOAT_CLASSIFY, CONST_MUT_REFS, CONST_UNWRAP }
31    1,82,0 { IS_NONE_OR, REPEAT_N, RAW_REF_OP, SPECIALIZED_TO_STRING_FOR_REFS }
32    1,81,0 { LINT_REASONS_STABILIZATION, ERROR_IN_CORE, EXPLICIT_SELF_TYPE_ELISION, DURATION_ABS_DIFF }
33    1,80,0 { BOX_INTO_ITER, LAZY_CELL }
34    1,79,0 { CONST_BLOCKS }
35    1,77,0 { C_STR_LITERALS }
36    1,76,0 { PTR_FROM_REF, OPTION_RESULT_INSPECT }
37    1,75,0 { OPTION_AS_SLICE }
38    1,74,0 { REPR_RUST, IO_ERROR_OTHER }
39    1,73,0 { DIV_CEIL }
40    1,71,0 { TUPLE_ARRAY_CONVERSIONS, BUILD_HASHER_HASH_ONE }
41    1,70,0 { OPTION_RESULT_IS_VARIANT_AND, BINARY_HEAP_RETAIN }
42    1,68,0 { PATH_MAIN_SEPARATOR_STR }
43    1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS }
44    1,63,0 { CLONE_INTO, CONST_SLICE_FROM_REF }
45    1,62,0 { BOOL_THEN_SOME, DEFAULT_ENUM_ATTRIBUTE, CONST_EXTERN_C_FN }
46    1,61,0 { CONST_FN_TRAIT_BOUND }
47    1,60,0 { ABS_DIFF }
48    1,59,0 { THREAD_LOCAL_CONST_INIT }
49    1,58,0 { FORMAT_ARGS_CAPTURE, PATTERN_TRAIT_CHAR_ARRAY, CONST_RAW_PTR_DEREF }
50    1,57,0 { MAP_WHILE, CONST_PANIC }
51    1,56,0 { CONST_FN_UNION }
52    1,55,0 { SEEK_REWIND }
53    1,54,0 { INTO_KEYS }
54    1,53,0 { OR_PATTERNS, INTEGER_BITS, BTREE_MAP_RETAIN, BTREE_SET_RETAIN, ARRAY_INTO_ITERATOR }
55    1,52,0 { STR_SPLIT_ONCE, REM_EUCLID_CONST }
56    1,51,0 { BORROW_AS_PTR, SEEK_FROM_CURRENT, UNSIGNED_ABS }
57    1,50,0 { BOOL_THEN, CLAMP, SLICE_FILL }
58    1,47,0 { TAU, IS_ASCII_DIGIT_CONST, ARRAY_IMPL_ANY_LEN, SATURATING_SUB_CONST }
59    1,46,0 { CONST_IF_MATCH }
60    1,45,0 { STR_STRIP_PREFIX }
61    1,43,0 { LOG2_10, LOG10_2, NUMERIC_ASSOCIATED_CONSTANTS }
62    1,42,0 { MATCHES_MACRO, SLICE_PATTERNS, PTR_SLICE_RAW_PARTS }
63    1,41,0 { RE_REBALANCING_COHERENCE, RESULT_MAP_OR_ELSE }
64    1,40,0 { MEM_TAKE, NON_EXHAUSTIVE, OPTION_AS_DEREF }
65    1,38,0 { POINTER_CAST, REM_EUCLID }
66    1,37,0 { TYPE_ALIAS_ENUM_VARIANTS }
67    1,36,0 { ITERATOR_COPIED }
68    1,35,0 { OPTION_COPIED, RANGE_CONTAINS }
69    1,34,0 { TRY_FROM }
70    1,33,0 { UNDERSCORE_IMPORTS }
71    1,32,0 { CONST_IS_POWER_OF_TWO }
72    1,31,0 { OPTION_REPLACE }
73    1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES }
74    1,29,0 { ITER_FLATTEN }
75    1,28,0 { FROM_BOOL, REPEAT_WITH, SLICE_FROM_REF }
76    1,27,0 { ITERATOR_TRY_FOLD, DOUBLE_ENDED_ITERATOR_RFIND }
77    1,26,0 { RANGE_INCLUSIVE, STRING_RETAIN, POINTER_ADD_SUB_METHODS }
78    1,24,0 { IS_ASCII_DIGIT, PTR_NULL }
79    1,18,0 { HASH_MAP_RETAIN, HASH_SET_RETAIN }
80    1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR }
81    1,16,0 { STR_REPEAT, RESULT_UNWRAP_OR_DEFAULT }
82    1,15,0 { MAYBE_BOUND_IN_WHERE }
83    1,13,0 { QUESTION_MARK_OPERATOR }
84}
85
86/// `#[clippy::msrv]` attributes are rarely used outside of Clippy's test suite, as a basic
87/// optimization we can skip traversing the HIR in [`Msrv::meets`] if we never saw an MSRV attribute
88/// during the early lint passes
89static SEEN_MSRV_ATTR: AtomicBool = AtomicBool::new(false);
90
91/// Tracks the current MSRV from `clippy.toml`, `Cargo.toml` or set via `#[clippy::msrv]` in late
92/// lint passes, use [`MsrvStack`] for early passes
93#[derive(Copy, Clone, Debug, Default)]
94pub struct Msrv(Option<RustcVersion>);
95
96impl<'de> Deserialize<'de> for Msrv {
97    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
98    where
99        D: serde::Deserializer<'de>,
100    {
101        let v = String::deserialize(deserializer)?;
102        parse_version(Symbol::intern(&v))
103            .map(|v| Self(Some(v)))
104            .ok_or_else(|| serde::de::Error::custom("not a valid Rust version"))
105    }
106}
107
108impl Msrv {
109    /// Returns the MSRV at the current node
110    ///
111    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
112    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
113    pub fn current(self, cx: &LateContext<'_>) -> Option<RustcVersion> {
114        if SEEN_MSRV_ATTR.load(Ordering::Relaxed) {
115            let start = cx.last_node_with_lint_attrs;
116            if let Some(msrv_attr) = once(start)
117                .chain(cx.tcx.hir_parent_id_iter(start))
118                .find_map(|id| parse_attrs(cx.tcx.sess, cx.tcx.hir_attrs(id)))
119            {
120                return Some(msrv_attr);
121            }
122        }
123
124        self.0
125    }
126
127    /// Checks if a required version from [this module](self) is met at the current node
128    ///
129    /// If the crate being linted uses an `#[clippy::msrv]` attribute this will search the parent
130    /// nodes for that attribute, prefer to run this check after cheaper pattern matching operations
131    pub fn meets(self, cx: &LateContext<'_>, required: RustcVersion) -> bool {
132        self.current(cx).is_none_or(|msrv| msrv >= required)
133    }
134
135    pub fn read_cargo(&mut self, sess: &Session) {
136        let cargo_msrv = std::env::var("CARGO_PKG_RUST_VERSION")
137            .ok()
138            .and_then(|v| parse_version(Symbol::intern(&v)));
139
140        match (self.0, cargo_msrv) {
141            (None, Some(cargo_msrv)) => self.0 = Some(cargo_msrv),
142            (Some(clippy_msrv), Some(cargo_msrv)) => {
143                if clippy_msrv != cargo_msrv {
144                    sess.dcx().warn(format!(
145                        "the MSRV in `clippy.toml` and `Cargo.toml` differ; using `{clippy_msrv}` from `clippy.toml`"
146                    ));
147                }
148            },
149            _ => {},
150        }
151    }
152}
153
154/// Tracks the current MSRV from `clippy.toml`, `Cargo.toml` or set via `#[clippy::msrv]` in early
155/// lint passes, use [`Msrv`] for late passes
156#[derive(Debug, Clone)]
157pub struct MsrvStack {
158    stack: SmallVec<[RustcVersion; 2]>,
159}
160
161impl MsrvStack {
162    pub fn new(initial: Msrv) -> Self {
163        Self {
164            stack: SmallVec::from_iter(initial.0),
165        }
166    }
167
168    pub fn current(&self) -> Option<RustcVersion> {
169        self.stack.last().copied()
170    }
171
172    pub fn meets(&self, required: RustcVersion) -> bool {
173        self.current().is_none_or(|msrv| msrv >= required)
174    }
175
176    pub fn check_attributes(&mut self, sess: &Session, attrs: &[Attribute]) {
177        if let Some(version) = parse_attrs(sess, attrs) {
178            SEEN_MSRV_ATTR.store(true, Ordering::Relaxed);
179            self.stack.push(version);
180        }
181    }
182
183    pub fn check_attributes_post(&mut self, sess: &Session, attrs: &[Attribute]) {
184        if parse_attrs(sess, attrs).is_some() {
185            self.stack.pop();
186        }
187    }
188}
189
190fn parse_attrs(sess: &Session, attrs: &[impl AttributeExt]) -> Option<RustcVersion> {
191    let mut msrv_attrs = attrs.iter().filter(|attr| attr.path_matches(&[sym::clippy, sym::msrv]));
192
193    let msrv_attr = msrv_attrs.next()?;
194
195    if let Some(duplicate) = msrv_attrs.next_back() {
196        sess.dcx()
197            .struct_span_err(duplicate.span(), "`clippy::msrv` is defined multiple times")
198            .with_span_note(msrv_attr.span(), "first definition found here")
199            .emit();
200    }
201
202    let Some(msrv) = msrv_attr.value_str() else {
203        sess.dcx().span_err(msrv_attr.span(), "bad clippy attribute");
204        return None;
205    };
206
207    let Some(version) = parse_version(msrv) else {
208        sess.dcx()
209            .span_err(msrv_attr.span(), format!("`{msrv}` is not a valid Rust version"));
210        return None;
211    };
212
213    Some(version)
214}