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, msg};
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 ->\n                    [true] : {$note}\n                    *[other] {\"\"}\n                }"))msg!(
132                "use of deprecated {$kind} `{$path}`{$has_note ->
133                    [true] : {$note}
134                    *[other] {\"\"}
135                }"
136            ),
137            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 ->\n                    [true] : {$note}\n                    *[other] {\"\"}\n                }"))msg!(
138                "use of {$kind} `{$path}` that will be deprecated in a future Rust version{$has_note ->
139                    [true] : {$note}
140                    *[other] {\"\"}
141                }"
142            ),
143            DeprecatedSinceKind::InVersion(_) => {
144                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use of {$kind} `{$path}` that will be deprecated in future version {$version}{$has_note ->\n                        [true] : {$note}\n                        *[other] {\"\"}\n                    }"))msg!(
145                    "use of {$kind} `{$path}` that will be deprecated in future version {$version}{$has_note ->
146                        [true] : {$note}
147                        *[other] {\"\"}
148                    }"
149                )
150            }
151        });
152        diag.arg("kind", self.kind);
153        diag.arg("path", self.path);
154        if let DeprecatedSinceKind::InVersion(version) = self.since_kind {
155            diag.arg("version", version);
156        }
157        if let Some(note) = self.note {
158            diag.arg("has_note", true);
159            diag.arg("note", note);
160        } else {
161            diag.arg("has_note", false);
162        }
163        if let Some(sub) = self.sub {
164            diag.subdiagnostic(sub);
165        }
166    }
167}
168
169fn deprecated_since_kind(is_in_effect: bool, since: DeprecatedSince) -> DeprecatedSinceKind {
170    if is_in_effect {
171        DeprecatedSinceKind::InEffect
172    } else {
173        match since {
174            DeprecatedSince::RustcVersion(version) => {
175                DeprecatedSinceKind::InVersion(version.to_string())
176            }
177            DeprecatedSince::Future => DeprecatedSinceKind::InFuture,
178            DeprecatedSince::NonStandard(_)
179            | DeprecatedSince::Unspecified
180            | DeprecatedSince::Err => {
181                {
    ::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:?}")
182            }
183        }
184    }
185}
186
187pub fn early_report_macro_deprecation(
188    lint_buffer: &mut LintBuffer,
189    depr: &Deprecation,
190    span: Span,
191    node_id: NodeId,
192    path: String,
193) {
194    if span.in_derive_expansion() {
195        return;
196    }
197
198    let is_in_effect = depr.is_in_effect();
199    let diag = BuiltinLintDiag::DeprecatedMacro {
200        suggestion: depr.suggestion,
201        suggestion_span: span,
202        note: depr.note.map(|ident| ident.name),
203        path,
204        since_kind: deprecated_since_kind(is_in_effect, depr.since),
205    };
206    lint_buffer.buffer_lint(deprecation_lint(is_in_effect), node_id, span, diag);
207}
208
209fn late_report_deprecation(
210    tcx: TyCtxt<'_>,
211    depr: &Deprecation,
212    span: Span,
213    method_span: Option<Span>,
214    hir_id: HirId,
215    def_id: DefId,
216) {
217    if span.in_derive_expansion() {
218        return;
219    }
220
221    let is_in_effect = depr.is_in_effect();
222    let lint = deprecation_lint(is_in_effect);
223
224    // Calculating message for lint involves calling `self.def_path_str`,
225    // which will by default invoke the expensive `visible_parent_map` query.
226    // Skip all that work if the lint is allowed anyway.
227    if tcx.lint_level_at_node(lint, hir_id).level == Level::Allow {
228        return;
229    }
230
231    let def_path = { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(def_id) }with_no_trimmed_paths!(tcx.def_path_str(def_id));
232    let def_kind = tcx.def_descr(def_id);
233
234    let method_span = method_span.unwrap_or(span);
235    let suggestion =
236        if let hir::Node::Expr(_) = tcx.hir_node(hir_id) { depr.suggestion } else { None };
237    let diag = Deprecated {
238        sub: suggestion.map(|suggestion| DeprecationSuggestion {
239            span: method_span,
240            kind: def_kind.to_owned(),
241            suggestion,
242        }),
243        kind: def_kind.to_owned(),
244        path: def_path,
245        note: depr.note.map(|ident| ident.name),
246        since_kind: deprecated_since_kind(is_in_effect, depr.since),
247    };
248    tcx.emit_node_span_lint(lint, hir_id, method_span, diag);
249}
250
251/// Result of `TyCtxt::eval_stability`.
252pub enum EvalResult {
253    /// We can use the item because it is stable or we provided the
254    /// corresponding feature gate.
255    Allow,
256    /// We cannot use the item because it is unstable and we did not provide the
257    /// corresponding feature gate.
258    Deny {
259        feature: Symbol,
260        reason: Option<Symbol>,
261        issue: Option<NonZero<u32>>,
262        suggestion: Option<(Span, String, String, Applicability)>,
263        is_soft: bool,
264    },
265    /// The item does not have the `#[stable]` or `#[unstable]` marker assigned.
266    Unmarked,
267}
268
269// See issue #83250.
270fn suggestion_for_allocator_api(
271    tcx: TyCtxt<'_>,
272    def_id: DefId,
273    span: Span,
274    feature: Symbol,
275) -> Option<(Span, String, String, Applicability)> {
276    if feature == sym::allocator_api {
277        if let Some(trait_) = tcx.opt_parent(def_id) {
278            if tcx.is_diagnostic_item(sym::Vec, trait_) {
279                let sm = tcx.sess.psess.source_map();
280                let inner_types = sm.span_extend_to_prev_char(span, '<', true);
281                if let Ok(snippet) = sm.span_to_snippet(inner_types) {
282                    return Some((
283                        inner_types,
284                        "consider wrapping the inner types in tuple".to_string(),
285                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", snippet))
    })format!("({snippet})"),
286                        Applicability::MaybeIncorrect,
287                    ));
288                }
289            }
290        }
291    }
292    None
293}
294
295/// An override option for eval_stability.
296pub enum AllowUnstable {
297    /// Don't emit an unstable error for the item
298    Yes,
299    /// Handle the item normally
300    No,
301}
302
303impl<'tcx> TyCtxt<'tcx> {
304    /// Evaluates the stability of an item.
305    ///
306    /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
307    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
308    /// unstable feature otherwise.
309    ///
310    /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
311    /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
312    /// `id`.
313    pub fn eval_stability(
314        self,
315        def_id: DefId,
316        id: Option<HirId>,
317        span: Span,
318        method_span: Option<Span>,
319    ) -> EvalResult {
320        self.eval_stability_allow_unstable(def_id, id, span, method_span, AllowUnstable::No)
321    }
322
323    /// Evaluates the stability of an item.
324    ///
325    /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
326    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
327    /// unstable feature otherwise.
328    ///
329    /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
330    /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
331    /// `id`.
332    ///
333    /// Pass `AllowUnstable::Yes` to `allow_unstable` to force an unstable item to be allowed. Deprecation warnings will be emitted normally.
334    pub fn eval_stability_allow_unstable(
335        self,
336        def_id: DefId,
337        id: Option<HirId>,
338        span: Span,
339        method_span: Option<Span>,
340        allow_unstable: AllowUnstable,
341    ) -> EvalResult {
342        // Deprecated attributes apply in-crate and cross-crate.
343        if let Some(id) = id {
344            if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
345                let parent_def_id = self.hir_get_parent_item(id);
346                let skip = self
347                    .lookup_deprecation_entry(parent_def_id.to_def_id())
348                    .is_some_and(|parent_depr| parent_depr.same_origin(&depr_entry));
349
350                // #[deprecated] doesn't emit a notice if we're not on the
351                // topmost deprecation. For example, if a struct is deprecated,
352                // the use of a field won't be linted.
353                //
354                // With #![staged_api], we want to emit down the whole
355                // hierarchy.
356                let depr_attr = &depr_entry.attr;
357                if !skip || depr_attr.is_since_rustc_version() {
358                    late_report_deprecation(self, depr_attr, span, method_span, id, def_id);
359                }
360            };
361        }
362
363        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
364        if !is_staged_api {
365            return EvalResult::Allow;
366        }
367
368        // Only the cross-crate scenario matters when checking unstable APIs
369        let cross_crate = !def_id.is_local();
370        if !cross_crate {
371            return EvalResult::Allow;
372        }
373
374        let stability = self.lookup_stability(def_id);
375        {
    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:375",
                        "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(375u32),
                        ::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!(
376            "stability: \
377                inspecting def_id={:?} span={:?} of stability={:?}",
378            def_id, span, stability
379        );
380
381        match stability {
382            Some(Stability {
383                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. },
384                feature,
385                ..
386            }) => {
387                if span.allows_unstable(feature) {
388                    {
    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:388",
                        "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(388u32),
                        ::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);
389                    return EvalResult::Allow;
390                }
391                if self.features().enabled(feature) {
392                    return EvalResult::Allow;
393                }
394
395                // If this item was previously part of a now-stabilized feature which is still
396                // enabled (i.e. the user hasn't removed the attribute for the stabilized feature
397                // yet) then allow use of this item.
398                if let Some(implied_by) = implied_by
399                    && self.features().enabled(implied_by)
400                {
401                    return EvalResult::Allow;
402                }
403
404                // When we're compiling the compiler itself we may pull in
405                // crates from crates.io, but those crates may depend on other
406                // crates also pulled in from crates.io. We want to ideally be
407                // able to compile everything without requiring upstream
408                // modifications, so in the case that this looks like a
409                // `rustc_private` crate (e.g., a compiler crate) and we also have
410                // the `-Z force-unstable-if-unmarked` flag present (we're
411                // compiling a compiler crate), then let this missing feature
412                // annotation slide.
413                if feature == sym::rustc_private
414                    && issue == NonZero::new(27812)
415                    && self.sess.opts.unstable_opts.force_unstable_if_unmarked
416                {
417                    return EvalResult::Allow;
418                }
419
420                if #[allow(non_exhaustive_omitted_patterns)] match allow_unstable {
    AllowUnstable::Yes => true,
    _ => false,
}matches!(allow_unstable, AllowUnstable::Yes) {
421                    return EvalResult::Allow;
422                }
423
424                let suggestion = suggestion_for_allocator_api(self, def_id, span, feature);
425                EvalResult::Deny {
426                    feature,
427                    reason: reason.to_opt_reason(),
428                    issue,
429                    suggestion,
430                    is_soft,
431                }
432            }
433            Some(_) => {
434                // Stable APIs are always ok to call and deprecated APIs are
435                // handled by the lint emitting logic above.
436                EvalResult::Allow
437            }
438            None => EvalResult::Unmarked,
439        }
440    }
441
442    /// Evaluates the default-impl stability of an item.
443    ///
444    /// Returns `EvalResult::Allow` if the item's default implementation is stable, or unstable but the corresponding
445    /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
446    /// unstable feature otherwise.
447    pub fn eval_default_body_stability(self, def_id: DefId, span: Span) -> EvalResult {
448        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
449        if !is_staged_api {
450            return EvalResult::Allow;
451        }
452
453        // Only the cross-crate scenario matters when checking unstable APIs
454        let cross_crate = !def_id.is_local();
455        if !cross_crate {
456            return EvalResult::Allow;
457        }
458
459        let stability = self.lookup_default_body_stability(def_id);
460        {
    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:460",
                        "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(460u32),
                        ::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!(
461            "body stability: inspecting def_id={def_id:?} span={span:?} of stability={stability:?}"
462        );
463
464        match stability {
465            Some(DefaultBodyStability {
466                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, .. },
467                feature,
468            }) => {
469                if span.allows_unstable(feature) {
470                    {
    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:470",
                        "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(470u32),
                        ::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);
471                    return EvalResult::Allow;
472                }
473                if self.features().enabled(feature) {
474                    return EvalResult::Allow;
475                }
476
477                EvalResult::Deny {
478                    feature,
479                    reason: reason.to_opt_reason(),
480                    issue,
481                    suggestion: None,
482                    is_soft,
483                }
484            }
485            Some(_) => {
486                // Stable APIs are always ok to call
487                EvalResult::Allow
488            }
489            None => EvalResult::Unmarked,
490        }
491    }
492
493    /// Checks if an item is stable or error out.
494    ///
495    /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
496    /// exist, emits an error.
497    ///
498    /// This function will also check if the item is deprecated.
499    /// If so, and `id` is not `None`, a deprecated lint attached to `id` will be emitted.
500    ///
501    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
502    pub fn check_stability(
503        self,
504        def_id: DefId,
505        id: Option<HirId>,
506        span: Span,
507        method_span: Option<Span>,
508    ) -> bool {
509        self.check_stability_allow_unstable(def_id, id, span, method_span, AllowUnstable::No)
510    }
511
512    /// Checks if an item is stable or error out.
513    ///
514    /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
515    /// exist, emits an error.
516    ///
517    /// This function will also check if the item is deprecated.
518    /// If so, and `id` is not `None`, a deprecated lint attached to `id` will be emitted.
519    ///
520    /// Pass `AllowUnstable::Yes` to `allow_unstable` to force an unstable item to be allowed. Deprecation warnings will be emitted normally.
521    ///
522    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
523    pub fn check_stability_allow_unstable(
524        self,
525        def_id: DefId,
526        id: Option<HirId>,
527        span: Span,
528        method_span: Option<Span>,
529        allow_unstable: AllowUnstable,
530    ) -> bool {
531        self.check_optional_stability(
532            def_id,
533            id,
534            span,
535            method_span,
536            allow_unstable,
537            |span, def_id| {
538                // The API could be uncallable for other reasons, for example when a private module
539                // was referenced.
540                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:?}"));
541            },
542        )
543    }
544
545    /// Like `check_stability`, except that we permit items to have custom behaviour for
546    /// missing stability attributes (not necessarily just emit a `bug!`). This is necessary
547    /// for default generic parameters, which only have stability attributes if they were
548    /// added after the type on which they're defined.
549    ///
550    /// Returns `true` if item is allowed aka, stable or unstable under an enabled feature.
551    pub fn check_optional_stability(
552        self,
553        def_id: DefId,
554        id: Option<HirId>,
555        span: Span,
556        method_span: Option<Span>,
557        allow_unstable: AllowUnstable,
558        unmarked: impl FnOnce(Span, DefId),
559    ) -> bool {
560        let soft_handler = |lint, span, msg: String| {
561            self.node_span_lint(lint, id.unwrap_or(hir::CRATE_HIR_ID), span, |lint| {
562                lint.primary_message(msg);
563            })
564        };
565        let eval_result =
566            self.eval_stability_allow_unstable(def_id, id, span, method_span, allow_unstable);
567        let is_allowed = #[allow(non_exhaustive_omitted_patterns)] match eval_result {
    EvalResult::Allow => true,
    _ => false,
}matches!(eval_result, EvalResult::Allow);
568        match eval_result {
569            EvalResult::Allow => {}
570            EvalResult::Deny { feature, reason, issue, suggestion, is_soft } => report_unstable(
571                self.sess,
572                feature,
573                reason,
574                issue,
575                suggestion,
576                is_soft,
577                span,
578                soft_handler,
579                UnstableKind::Regular,
580            ),
581            EvalResult::Unmarked => unmarked(span, def_id),
582        }
583
584        is_allowed
585    }
586
587    /// This function is analogous to `check_optional_stability` but with the logic in
588    /// `eval_stability_allow_unstable` inlined, and which operating on const stability
589    /// instead of regular stability.
590    ///
591    /// This enforces *syntactical* const stability of const traits. In other words,
592    /// it enforces the ability to name `[const]`/`const` traits in trait bounds in various
593    /// syntax positions in HIR (including in the trait of an impl header).
594    pub fn check_const_stability(self, def_id: DefId, span: Span, const_kw_span: Span) {
595        let is_staged_api = self.lookup_stability(def_id.krate.as_def_id()).is_some();
596        if !is_staged_api {
597            return;
598        }
599
600        // Only the cross-crate scenario matters when checking unstable APIs
601        let cross_crate = !def_id.is_local();
602        if !cross_crate {
603            return;
604        }
605
606        let stability = self.lookup_const_stability(def_id);
607        {
    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:607",
                        "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(607u32),
                        ::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!(
608            "stability: \
609                inspecting def_id={:?} span={:?} of stability={:?}",
610            def_id, span, stability
611        );
612
613        match stability {
614            Some(ConstStability {
615                level: hir::StabilityLevel::Unstable { reason, issue, is_soft, implied_by, .. },
616                feature,
617                ..
618            }) => {
619                if !!is_soft { ::core::panicking::panic("assertion failed: !is_soft") };assert!(!is_soft);
620
621                if span.allows_unstable(feature) {
622                    {
    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:622",
                        "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(622u32),
                        ::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);
623                    return;
624                }
625                if self.features().enabled(feature) {
626                    return;
627                }
628
629                // If this item was previously part of a now-stabilized feature which is still
630                // enabled (i.e. the user hasn't removed the attribute for the stabilized feature
631                // yet) then allow use of this item.
632                if let Some(implied_by) = implied_by
633                    && self.features().enabled(implied_by)
634                {
635                    return;
636                }
637
638                report_unstable(
639                    self.sess,
640                    feature,
641                    reason.to_opt_reason(),
642                    issue,
643                    None,
644                    false,
645                    span,
646                    |_, _, _| {},
647                    UnstableKind::Const(const_kw_span),
648                );
649            }
650            Some(_) | None => {}
651        }
652    }
653
654    pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
655        self.lookup_deprecation_entry(id).map(|depr| depr.attr)
656    }
657}