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