Skip to main content

rustc_middle/middle/
stability.rs

1//! A pass that annotates every item and method with its stability level,
2//! propagating default levels lexically from parent to children ast nodes.
3
4use std::num::NonZero;
5
6use rustc_ast::NodeId;
7use rustc_errors::{Applicability, Diag, EmissionGuarantee, LintBuffer, inline_fluent};
8use rustc_feature::GateIssue;
9use rustc_hir::attrs::{DeprecatedSince, Deprecation};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::{self as hir, ConstStability, DefaultBodyStability, HirId, Stability};
12use rustc_macros::{Decodable, Encodable, HashStable, Subdiagnostic};
13use rustc_session::Session;
14use rustc_session::lint::builtin::{DEPRECATED, DEPRECATED_IN_FUTURE, SOFT_UNSTABLE};
15use rustc_session::lint::{BuiltinLintDiag, DeprecatedSinceKind, Level, Lint};
16use rustc_session::parse::feature_err_issue;
17use rustc_span::{Span, Symbol, sym};
18use tracing::debug;
19
20pub use self::StabilityLevel::*;
21use crate::ty::TyCtxt;
22use crate::ty::print::with_no_trimmed_paths;
23
24#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for StabilityLevel {
    #[inline]
    fn eq(&self, other: &StabilityLevel) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for StabilityLevel {
    #[inline]
    fn clone(&self) -> StabilityLevel { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for StabilityLevel { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for StabilityLevel {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                StabilityLevel::Unstable => "Unstable",
                StabilityLevel::Stable => "Stable",
            })
    }
}Debug)]
25pub enum StabilityLevel {
26    Unstable,
27    Stable,
28}
29
30#[derive(#[automatically_derived]
impl ::core::marker::Copy for UnstableKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for UnstableKind {
    #[inline]
    fn clone(&self) -> UnstableKind {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone)]
31pub enum UnstableKind {
32    /// Enforcing regular stability of an item
33    Regular,
34    /// Enforcing const stability of an item
35    Const(Span),
36}
37
38/// An entry in the `depr_map`.
39#[derive(#[automatically_derived]
impl ::core::marker::Copy for DeprecationEntry { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DeprecationEntry {
    #[inline]
    fn clone(&self) -> DeprecationEntry {
        let _: ::core::clone::AssertParamIsClone<Deprecation>;
        let _: ::core::clone::AssertParamIsClone<Option<LocalDefId>>;
        *self
    }
}Clone, const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
            for DeprecationEntry {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    DeprecationEntry {
                        attr: ref __binding_0, origin: ref __binding_1 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, #[automatically_derived]
impl ::core::fmt::Debug for DeprecationEntry {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DeprecationEntry", "attr", &self.attr, "origin", &&self.origin)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DeprecationEntry {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DeprecationEntry {
                        attr: ref __binding_0, origin: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DeprecationEntry {
            fn decode(__decoder: &mut __D) -> Self {
                DeprecationEntry {
                    attr: ::rustc_serialize::Decodable::decode(__decoder),
                    origin: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
40pub struct DeprecationEntry {
41    /// The metadata of the attribute associated with this entry.
42    pub attr: Deprecation,
43    /// The `DefId` where the attr was originally attached. `None` for non-local
44    /// `DefId`'s.
45    origin: Option<LocalDefId>,
46}
47
48impl DeprecationEntry {
49    pub fn local(attr: Deprecation, def_id: LocalDefId) -> DeprecationEntry {
50        DeprecationEntry { attr, origin: Some(def_id) }
51    }
52
53    pub fn external(attr: Deprecation) -> DeprecationEntry {
54        DeprecationEntry { attr, origin: None }
55    }
56
57    pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
58        match (self.origin, other.origin) {
59            (Some(o1), Some(o2)) => o1 == o2,
60            _ => false,
61        }
62    }
63}
64
65pub fn report_unstable(
66    sess: &Session,
67    feature: Symbol,
68    reason: Option<Symbol>,
69    issue: Option<NonZero<u32>>,
70    suggestion: Option<(Span, String, String, Applicability)>,
71    is_soft: bool,
72    span: Span,
73    soft_handler: impl FnOnce(&'static Lint, Span, String),
74    kind: UnstableKind,
75) {
76    let qual = match kind {
77        UnstableKind::Regular => "",
78        UnstableKind::Const(_) => " const",
79    };
80
81    let msg = match reason {
82        Some(r) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of unstable{0} library feature `{1}`: {2}",
                qual, feature, r))
    })format!("use of unstable{qual} library feature `{feature}`: {r}"),
83        None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of unstable{0} library feature `{1}`",
                qual, feature))
    })format!("use of unstable{qual} library feature `{feature}`"),
84    };
85
86    if is_soft {
87        soft_handler(SOFT_UNSTABLE, span, msg)
88    } else {
89        let mut err = feature_err_issue(sess, feature, span, GateIssue::Library(issue), msg);
90        if let Some((inner_types, msg, sugg, applicability)) = suggestion {
91            err.span_suggestion(inner_types, msg, sugg, applicability);
92        }
93        if let UnstableKind::Const(kw) = kind {
94            err.span_label(kw, "trait is not stable as const yet");
95        }
96        err.emit();
97    }
98}
99
100fn deprecation_lint(is_in_effect: bool) -> &'static Lint {
101    if is_in_effect { DEPRECATED } else { DEPRECATED_IN_FUTURE }
102}
103
104#[derive(const _: () =
    {
        impl rustc_errors::Subdiagnostic for DeprecationSuggestion {
            fn add_to_diag<__G>(self, diag: &mut rustc_errors::Diag<'_, __G>)
                where __G: rustc_errors::EmissionGuarantee {
                match self {
                    DeprecationSuggestion {
                        span: __binding_0,
                        kind: __binding_1,
                        suggestion: __binding_2 } => {
                        let __code_0 =
                            [::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}", __binding_2))
                                            })].into_iter();
                        diag.store_args();
                        diag.arg("kind", __binding_1);
                        diag.arg("suggestion", __binding_2);
                        let __message =
                            diag.eagerly_translate(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("replace the use of the deprecated {$kind}")));
                        diag.span_suggestions_with_style(__binding_0, __message,
                            __code_0, rustc_errors::Applicability::MachineApplicable,
                            rustc_errors::SuggestionStyle::ShowAlways);
                        diag.restore_args();
                    }
                }
            }
        }
    };Subdiagnostic)]
105#[suggestion(
106    "replace the use of the deprecated {$kind}",
107    code = "{suggestion}",
108    style = "verbose",
109    applicability = "machine-applicable"
110)]
111pub struct DeprecationSuggestion {
112    #[primary_span]
113    pub span: Span,
114
115    pub kind: String,
116    pub suggestion: Symbol,
117}
118
119pub struct Deprecated {
120    pub sub: Option<DeprecationSuggestion>,
121
122    pub kind: String,
123    pub path: String,
124    pub note: Option<Symbol>,
125    pub since_kind: DeprecatedSinceKind,
126}
127
128impl<'a, G: EmissionGuarantee> rustc_errors::LintDiagnostic<'a, G> for Deprecated {
129    fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>) {
130        diag.primary_message(match &self.since_kind {
131            DeprecatedSinceKind::InEffect => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use of deprecated {$kind} `{$path}`{$has_note ->
                [true] : {$note}
                *[other] {\"\"}
            }"))inline_fluent!("use of deprecated {$kind} `{$path}`{$has_note ->
132                [true] : {$note}
133                *[other] {\"\"}
134            }"),
135            DeprecatedSinceKind::InFuture => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use of {$kind} `{$path}` that will be deprecated in a future Rust version{$has_note ->
                [true] : {$note}
                *[other] {\"\"}
            }"))inline_fluent!("use of {$kind} `{$path}` that will be deprecated in a future Rust version{$has_note ->
136                [true] : {$note}
137                *[other] {\"\"}
138            }"),
139            DeprecatedSinceKind::InVersion(_) => {
140                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use of {$kind} `{$path}` that will be deprecated in future version {$version}{$has_note ->
                    [true] : {$note}
                    *[other] {\"\"}
                }"))inline_fluent!("use of {$kind} `{$path}` that will be deprecated in future version {$version}{$has_note ->
141                    [true] : {$note}
142                    *[other] {\"\"}
143                }")
144            }
145        });
146        diag.arg("kind", self.kind);
147        diag.arg("path", self.path);
148        if let DeprecatedSinceKind::InVersion(version) = self.since_kind {
149            diag.arg("version", version);
150        }
151        if let Some(note) = self.note {
152            diag.arg("has_note", true);
153            diag.arg("note", note);
154        } else {
155            diag.arg("has_note", false);
156        }
157        if let Some(sub) = self.sub {
158            diag.subdiagnostic(sub);
159        }
160    }
161}
162
163fn deprecated_since_kind(is_in_effect: bool, since: DeprecatedSince) -> DeprecatedSinceKind {
164    if is_in_effect {
165        DeprecatedSinceKind::InEffect
166    } else {
167        match since {
168            DeprecatedSince::RustcVersion(version) => {
169                DeprecatedSinceKind::InVersion(version.to_string())
170            }
171            DeprecatedSince::Future => DeprecatedSinceKind::InFuture,
172            DeprecatedSince::NonStandard(_)
173            | DeprecatedSince::Unspecified
174            | DeprecatedSince::Err => {
175                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("this deprecation is always in effect; {0:?}",
                since)));
}unreachable!("this deprecation is always in effect; {since:?}")
176            }
177        }
178    }
179}
180
181pub fn early_report_macro_deprecation(
182    lint_buffer: &mut LintBuffer,
183    depr: &Deprecation,
184    span: Span,
185    node_id: NodeId,
186    path: String,
187) {
188    if span.in_derive_expansion() {
189        return;
190    }
191
192    let is_in_effect = depr.is_in_effect();
193    let diag = BuiltinLintDiag::DeprecatedMacro {
194        suggestion: depr.suggestion,
195        suggestion_span: span,
196        note: depr.note.map(|ident| ident.name),
197        path,
198        since_kind: deprecated_since_kind(is_in_effect, depr.since),
199    };
200    lint_buffer.buffer_lint(deprecation_lint(is_in_effect), node_id, span, diag);
201}
202
203fn late_report_deprecation(
204    tcx: TyCtxt<'_>,
205    depr: &Deprecation,
206    span: Span,
207    method_span: Option<Span>,
208    hir_id: HirId,
209    def_id: DefId,
210) {
211    if span.in_derive_expansion() {
212        return;
213    }
214
215    let is_in_effect = depr.is_in_effect();
216    let lint = deprecation_lint(is_in_effect);
217
218    // Calculating message for lint involves calling `self.def_path_str`,
219    // which will by default invoke the expensive `visible_parent_map` query.
220    // Skip all that work if the lint is allowed anyway.
221    if tcx.lint_level_at_node(lint, hir_id).level == Level::Allow {
222        return;
223    }
224
225    let def_path = { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(def_id) }with_no_trimmed_paths!(tcx.def_path_str(def_id));
226    let def_kind = tcx.def_descr(def_id);
227
228    let method_span = method_span.unwrap_or(span);
229    let suggestion =
230        if let hir::Node::Expr(_) = tcx.hir_node(hir_id) { depr.suggestion } else { None };
231    let diag = Deprecated {
232        sub: suggestion.map(|suggestion| DeprecationSuggestion {
233            span: method_span,
234            kind: def_kind.to_owned(),
235            suggestion,
236        }),
237        kind: def_kind.to_owned(),
238        path: def_path,
239        note: depr.note.map(|ident| ident.name),
240        since_kind: deprecated_since_kind(is_in_effect, depr.since),
241    };
242    tcx.emit_node_span_lint(lint, hir_id, method_span, diag);
243}
244
245/// Result of `TyCtxt::eval_stability`.
246pub enum EvalResult {
247    /// We can use the item because it is stable or we provided the
248    /// corresponding feature gate.
249    Allow,
250    /// We cannot use the item because it is unstable and we did not provide the
251    /// corresponding feature gate.
252    Deny {
253        feature: Symbol,
254        reason: Option<Symbol>,
255        issue: Option<NonZero<u32>>,
256        suggestion: Option<(Span, String, String, Applicability)>,
257        is_soft: bool,
258    },
259    /// The item does not have the `#[stable]` or `#[unstable]` marker assigned.
260    Unmarked,
261}
262
263// See issue #83250.
264fn suggestion_for_allocator_api(
265    tcx: TyCtxt<'_>,
266    def_id: DefId,
267    span: Span,
268    feature: Symbol,
269) -> Option<(Span, String, String, Applicability)> {
270    if feature == sym::allocator_api {
271        if let Some(trait_) = tcx.opt_parent(def_id) {
272            if tcx.is_diagnostic_item(sym::Vec, trait_) {
273                let sm = tcx.sess.psess.source_map();
274                let inner_types = sm.span_extend_to_prev_char(span, '<', true);
275                if let Ok(snippet) = sm.span_to_snippet(inner_types) {
276                    return Some((
277                        inner_types,
278                        "consider wrapping the inner types in tuple".to_string(),
279                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", snippet))
    })format!("({snippet})"),
280                        Applicability::MaybeIncorrect,
281                    ));
282                }
283            }
284        }
285    }
286    None
287}
288
289/// An override option for eval_stability.
290pub enum AllowUnstable {
291    /// Don't emit an unstable error for the item
292    Yes,
293    /// Handle the item normally
294    No,
295}
296
297impl<'tcx> TyCtxt<'tcx> {
298    /// Evaluates the stability of an item.
299    ///
300    /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
301    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
302    /// unstable feature otherwise.
303    ///
304    /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
305    /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
306    /// `id`.
307    pub fn eval_stability(
308        self,
309        def_id: DefId,
310        id: Option<HirId>,
311        span: Span,
312        method_span: Option<Span>,
313    ) -> EvalResult {
314        self.eval_stability_allow_unstable(def_id, id, span, method_span, AllowUnstable::No)
315    }
316
317    /// Evaluates the stability of an item.
318    ///
319    /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
320    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
321    /// unstable feature otherwise.
322    ///
323    /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
324    /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
325    /// `id`.
326    ///
327    /// Pass `AllowUnstable::Yes` to `allow_unstable` to force an unstable item to be allowed. Deprecation warnings will be emitted normally.
328    pub fn eval_stability_allow_unstable(
329        self,
330        def_id: DefId,
331        id: Option<HirId>,
332        span: Span,
333        method_span: Option<Span>,
334        allow_unstable: AllowUnstable,
335    ) -> EvalResult {
336        // Deprecated attributes apply in-crate and cross-crate.
337        if let Some(id) = id {
338            if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
339                let parent_def_id = self.hir_get_parent_item(id);
340                let skip = self
341                    .lookup_deprecation_entry(parent_def_id.to_def_id())
342                    .is_some_and(|parent_depr| parent_depr.same_origin(&depr_entry));
343
344                // #[deprecated] doesn't emit a notice if we're not on the
345                // topmost deprecation. For example, if a struct is deprecated,
346                // the use of a field won't be linted.
347                //
348                // With #![staged_api], we want to emit down the whole
349                // hierarchy.
350                let depr_attr = &depr_entry.attr;
351                if !skip || depr_attr.is_since_rustc_version() {
352                    late_report_deprecation(self, depr_attr, span, method_span, id, def_id);
353                }
354            };
355        }
356
357        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
358        if !is_staged_api {
359            return EvalResult::Allow;
360        }
361
362        // Only the cross-crate scenario matters when checking unstable APIs
363        let cross_crate = !def_id.is_local();
364        if !cross_crate {
365            return EvalResult::Allow;
366        }
367
368        let stability = self.lookup_stability(def_id);
369        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:369",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(369u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("stability: inspecting def_id={0:?} span={1:?} of stability={2:?}",
                                                    def_id, span, stability) as &dyn Value))])
            });
    } else { ; }
};debug!(
370            "stability: \
371                inspecting def_id={:?} span={:?} of stability={:?}",
372            def_id, span, stability
373        );
374
375        match stability {
376            Some(Stability {
377                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. },
378                feature,
379                ..
380            }) => {
381                if span.allows_unstable(feature) {
382                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:382",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(382u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("stability: skipping span={0:?} since it is internal",
                                                    span) as &dyn Value))])
            });
    } else { ; }
};debug!("stability: skipping span={:?} since it is internal", span);
383                    return EvalResult::Allow;
384                }
385                if self.features().enabled(feature) {
386                    return EvalResult::Allow;
387                }
388
389                // If this item was previously part of a now-stabilized feature which is still
390                // enabled (i.e. the user hasn't removed the attribute for the stabilized feature
391                // yet) then allow use of this item.
392                if let Some(implied_by) = implied_by
393                    && self.features().enabled(implied_by)
394                {
395                    return EvalResult::Allow;
396                }
397
398                // When we're compiling the compiler itself we may pull in
399                // crates from crates.io, but those crates may depend on other
400                // crates also pulled in from crates.io. We want to ideally be
401                // able to compile everything without requiring upstream
402                // modifications, so in the case that this looks like a
403                // `rustc_private` crate (e.g., a compiler crate) and we also have
404                // the `-Z force-unstable-if-unmarked` flag present (we're
405                // compiling a compiler crate), then let this missing feature
406                // annotation slide.
407                if feature == sym::rustc_private
408                    && issue == NonZero::new(27812)
409                    && self.sess.opts.unstable_opts.force_unstable_if_unmarked
410                {
411                    return EvalResult::Allow;
412                }
413
414                if #[allow(non_exhaustive_omitted_patterns)] match allow_unstable {
    AllowUnstable::Yes => true,
    _ => false,
}matches!(allow_unstable, AllowUnstable::Yes) {
415                    return EvalResult::Allow;
416                }
417
418                let suggestion = suggestion_for_allocator_api(self, def_id, span, feature);
419                EvalResult::Deny {
420                    feature,
421                    reason: reason.to_opt_reason(),
422                    issue,
423                    suggestion,
424                    is_soft,
425                }
426            }
427            Some(_) => {
428                // Stable APIs are always ok to call and deprecated APIs are
429                // handled by the lint emitting logic above.
430                EvalResult::Allow
431            }
432            None => EvalResult::Unmarked,
433        }
434    }
435
436    /// Evaluates the default-impl stability of an item.
437    ///
438    /// Returns `EvalResult::Allow` if the item's default implementation is stable, or unstable but the corresponding
439    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
440    /// unstable feature otherwise.
441    pub fn eval_default_body_stability(self, def_id: DefId, span: Span) -> EvalResult {
442        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
443        if !is_staged_api {
444            return EvalResult::Allow;
445        }
446
447        // Only the cross-crate scenario matters when checking unstable APIs
448        let cross_crate = !def_id.is_local();
449        if !cross_crate {
450            return EvalResult::Allow;
451        }
452
453        let stability = self.lookup_default_body_stability(def_id);
454        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:454",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(454u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("body stability: inspecting def_id={0:?} span={1:?} of stability={2:?}",
                                                    def_id, span, stability) as &dyn Value))])
            });
    } else { ; }
};debug!(
455            "body stability: inspecting def_id={def_id:?} span={span:?} of stability={stability:?}"
456        );
457
458        match stability {
459            Some(DefaultBodyStability {
460                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, .. },
461                feature,
462            }) => {
463                if span.allows_unstable(feature) {
464                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:464",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(464u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("body stability: skipping span={0:?} since it is internal",
                                                    span) as &dyn Value))])
            });
    } else { ; }
};debug!("body stability: skipping span={:?} since it is internal", span);
465                    return EvalResult::Allow;
466                }
467                if self.features().enabled(feature) {
468                    return EvalResult::Allow;
469                }
470
471                EvalResult::Deny {
472                    feature,
473                    reason: reason.to_opt_reason(),
474                    issue,
475                    suggestion: None,
476                    is_soft,
477                }
478            }
479            Some(_) => {
480                // Stable APIs are always ok to call
481                EvalResult::Allow
482            }
483            None => EvalResult::Unmarked,
484        }
485    }
486
487    /// Checks if an item is stable or error out.
488    ///
489    /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
490    /// exist, emits an error.
491    ///
492    /// This function will also check if the item is deprecated.
493    /// If so, and `id` is not `None`, a deprecated lint attached to `id` will be emitted.
494    ///
495    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
496    pub fn check_stability(
497        self,
498        def_id: DefId,
499        id: Option<HirId>,
500        span: Span,
501        method_span: Option<Span>,
502    ) -> bool {
503        self.check_stability_allow_unstable(def_id, id, span, method_span, AllowUnstable::No)
504    }
505
506    /// Checks if an item is stable or error out.
507    ///
508    /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
509    /// exist, emits an error.
510    ///
511    /// This function will also check if the item is deprecated.
512    /// If so, and `id` is not `None`, a deprecated lint attached to `id` will be emitted.
513    ///
514    /// Pass `AllowUnstable::Yes` to `allow_unstable` to force an unstable item to be allowed. Deprecation warnings will be emitted normally.
515    ///
516    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
517    pub fn check_stability_allow_unstable(
518        self,
519        def_id: DefId,
520        id: Option<HirId>,
521        span: Span,
522        method_span: Option<Span>,
523        allow_unstable: AllowUnstable,
524    ) -> bool {
525        self.check_optional_stability(
526            def_id,
527            id,
528            span,
529            method_span,
530            allow_unstable,
531            |span, def_id| {
532                // The API could be uncallable for other reasons, for example when a private module
533                // was referenced.
534                self.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("encountered unmarked API: {0:?}",
                def_id))
    })format!("encountered unmarked API: {def_id:?}"));
535            },
536        )
537    }
538
539    /// Like `check_stability`, except that we permit items to have custom behaviour for
540    /// missing stability attributes (not necessarily just emit a `bug!`). This is necessary
541    /// for default generic parameters, which only have stability attributes if they were
542    /// added after the type on which they're defined.
543    ///
544    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
545    pub fn check_optional_stability(
546        self,
547        def_id: DefId,
548        id: Option<HirId>,
549        span: Span,
550        method_span: Option<Span>,
551        allow_unstable: AllowUnstable,
552        unmarked: impl FnOnce(Span, DefId),
553    ) -> bool {
554        let soft_handler = |lint, span, msg: String| {
555            self.node_span_lint(lint, id.unwrap_or(hir::CRATE_HIR_ID), span, |lint| {
556                lint.primary_message(msg);
557            })
558        };
559        let eval_result =
560            self.eval_stability_allow_unstable(def_id, id, span, method_span, allow_unstable);
561        let is_allowed = #[allow(non_exhaustive_omitted_patterns)] match eval_result {
    EvalResult::Allow => true,
    _ => false,
}matches!(eval_result, EvalResult::Allow);
562        match eval_result {
563            EvalResult::Allow => {}
564            EvalResult::Deny { feature, reason, issue, suggestion, is_soft } => report_unstable(
565                self.sess,
566                feature,
567                reason,
568                issue,
569                suggestion,
570                is_soft,
571                span,
572                soft_handler,
573                UnstableKind::Regular,
574            ),
575            EvalResult::Unmarked => unmarked(span, def_id),
576        }
577
578        is_allowed
579    }
580
581    /// This function is analogous to `check_optional_stability` but with the logic in
582    /// `eval_stability_allow_unstable` inlined, and which operating on const stability
583    /// instead of regular stability.
584    ///
585    /// This enforces *syntactical* const stability of const traits. In other words,
586    /// it enforces the ability to name `[const]`/`const` traits in trait bounds in various
587    /// syntax positions in HIR (including in the trait of an impl header).
588    pub fn check_const_stability(self, def_id: DefId, span: Span, const_kw_span: Span) {
589        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
590        if !is_staged_api {
591            return;
592        }
593
594        // Only the cross-crate scenario matters when checking unstable APIs
595        let cross_crate = !def_id.is_local();
596        if !cross_crate {
597            return;
598        }
599
600        let stability = self.lookup_const_stability(def_id);
601        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:601",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(601u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("stability: inspecting def_id={0:?} span={1:?} of stability={2:?}",
                                                    def_id, span, stability) as &dyn Value))])
            });
    } else { ; }
};debug!(
602            "stability: \
603                inspecting def_id={:?} span={:?} of stability={:?}",
604            def_id, span, stability
605        );
606
607        match stability {
608            Some(ConstStability {
609                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. },
610                feature,
611                ..
612            }) => {
613                if !!is_soft { ::core::panicking::panic("assertion failed: !is_soft") };assert!(!is_soft);
614
615                if span.allows_unstable(feature) {
616                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/middle/stability.rs:616",
                        "rustc_middle::middle::stability", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/middle/stability.rs"),
                        ::tracing_core::__macro_support::Option::Some(616u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::middle::stability"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("body stability: skipping span={0:?} since it is internal",
                                                    span) as &dyn Value))])
            });
    } else { ; }
};debug!("body stability: skipping span={:?} since it is internal", span);
617                    return;
618                }
619                if self.features().enabled(feature) {
620                    return;
621                }
622
623                // If this item was previously part of a now-stabilized feature which is still
624                // enabled (i.e. the user hasn't removed the attribute for the stabilized feature
625                // yet) then allow use of this item.
626                if let Some(implied_by) = implied_by
627                    && self.features().enabled(implied_by)
628                {
629                    return;
630                }
631
632                report_unstable(
633                    self.sess,
634                    feature,
635                    reason.to_opt_reason(),
636                    issue,
637                    None,
638                    false,
639                    span,
640                    |_, _, _| {},
641                    UnstableKind::Const(const_kw_span),
642                );
643            }
644            Some(_) | None => {}
645        }
646    }
647
648    pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
649        self.lookup_deprecation_entry(id).map(|depr| depr.attr)
650    }
651}