Skip to main content

rustc_hir_analysis/check/
always_applicable.rs

1//! This module contains methods that assist in checking that impls are general
2//! enough, i.e. that they always apply to every valid instantaiton of the ADT
3//! they're implemented for.
4//!
5//! This is necessary for `Drop` and negative impls to be well-formed.
6
7use rustc_data_structures::fx::FxHashSet;
8use rustc_errors::codes::*;
9use rustc_errors::{ErrorGuaranteed, struct_span_code_err};
10use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt};
11use rustc_infer::traits::{ObligationCause, ObligationCauseCode};
12use rustc_middle::span_bug;
13use rustc_middle::ty::util::CheckRegions;
14use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode};
15use rustc_span::sym;
16use rustc_trait_selection::regions::InferCtxtRegionExt;
17use rustc_trait_selection::traits::{self, ObligationCtxt};
18
19use crate::check::missing_items_must_implement_one_of_err;
20use crate::diagnostics;
21use crate::hir::def_id::{DefId, LocalDefId};
22
23/// This function confirms that the `Drop` implementation identified by
24/// `drop_impl_did` is not any more specialized than the type it is
25/// attached to (Issue #8142).
26///
27/// This means:
28///
29/// 1. The self type must be nominal (this is already checked during
30///    coherence),
31///
32/// 2. The generic region/type parameters of the impl's self type must
33///    all be parameters of the Drop impl itself (i.e., no
34///    specialization like `impl Drop for Foo<i32>`), and,
35///
36/// 3. Any bounds on the generic parameters must be reflected in the
37///    struct/enum definition for the nominal type itself (i.e.
38///    cannot do `struct S<T>; impl<T:Clone> Drop for S<T> { ... }`).
39pub(crate) fn check_drop_impl(
40    tcx: TyCtxt<'_>,
41    drop_impl_did: LocalDefId,
42) -> Result<(), ErrorGuaranteed> {
43    match tcx.impl_polarity(drop_impl_did) {
44        ty::ImplPolarity::Positive => {}
45        ty::ImplPolarity::Negative => {
46            return Err(tcx.dcx().emit_err(diagnostics::NegativeDropImplPolarity {
47                span: tcx.def_span(drop_impl_did),
48            }));
49        }
50    }
51
52    tcx.ensure_result().orphan_check_impl(drop_impl_did)?;
53
54    let self_ty = tcx.type_of(drop_impl_did).instantiate_identity().skip_norm_wip();
55
56    match self_ty.kind() {
57        ty::Adt(adt_def, adt_to_impl_args) => {
58            ensure_impl_params_and_item_params_correspond(
59                tcx,
60                drop_impl_did,
61                adt_def.did(),
62                adt_to_impl_args,
63            )?;
64
65            ensure_all_fields_are_const_destruct(tcx, drop_impl_did, adt_def.did())?;
66
67            ensure_impl_predicates_are_implied_by_item_defn(
68                tcx,
69                drop_impl_did,
70                adt_def.did(),
71                adt_to_impl_args,
72            )?;
73
74            check_drop_xor_pin_drop(tcx, adt_def.did(), drop_impl_did)?;
75
76            Ok(())
77        }
78        _ => {
79            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(drop_impl_did),
    format_args!("incoherent impl of Drop"));span_bug!(tcx.def_span(drop_impl_did), "incoherent impl of Drop");
80        }
81    }
82}
83
84pub(crate) fn check_negative_auto_trait_impl<'tcx>(
85    tcx: TyCtxt<'tcx>,
86    impl_def_id: LocalDefId,
87    impl_trait_ref: ty::TraitRef<'tcx>,
88    polarity: ty::ImplPolarity,
89) -> Result<(), ErrorGuaranteed> {
90    let ty::ImplPolarity::Negative = polarity else {
91        return Ok(());
92    };
93
94    if !tcx.trait_is_auto(impl_trait_ref.def_id) {
95        return Ok(());
96    }
97
98    if tcx.defaultness(impl_def_id).is_default() {
99        tcx.dcx().span_delayed_bug(tcx.def_span(impl_def_id), "default impl cannot be negative");
100    }
101
102    tcx.ensure_result().orphan_check_impl(impl_def_id)?;
103
104    match impl_trait_ref.self_ty().kind() {
105        ty::Adt(adt_def, adt_to_impl_args) => {
106            ensure_impl_params_and_item_params_correspond(
107                tcx,
108                impl_def_id,
109                adt_def.did(),
110                adt_to_impl_args,
111            )?;
112
113            ensure_impl_predicates_are_implied_by_item_defn(
114                tcx,
115                impl_def_id,
116                adt_def.did(),
117                adt_to_impl_args,
118            )
119        }
120        _ => {
121            if tcx.features().auto_traits() {
122                // NOTE: We ignore the applicability check for negative auto impls
123                // defined in libcore. In the (almost impossible) future where we
124                // stabilize auto impls, then the proper applicability check MUST
125                // be implemented here to handle non-ADT rigid types.
126                Ok(())
127            } else {
128                Err(tcx.dcx().span_delayed_bug(
129                    tcx.def_span(impl_def_id),
130                    "incoherent impl of negative auto trait",
131                ))
132            }
133        }
134    }
135}
136
137fn ensure_impl_params_and_item_params_correspond<'tcx>(
138    tcx: TyCtxt<'tcx>,
139    impl_def_id: LocalDefId,
140    adt_def_id: DefId,
141    adt_to_impl_args: GenericArgsRef<'tcx>,
142) -> Result<(), ErrorGuaranteed> {
143    let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_args, CheckRegions::OnlyParam) else {
144        return Ok(());
145    };
146
147    let impl_span = tcx.def_span(impl_def_id);
148    let item_span = tcx.def_span(adt_def_id);
149    let self_descr = tcx.def_descr(adt_def_id);
150    let polarity = match tcx.impl_polarity(impl_def_id) {
151        ty::ImplPolarity::Positive => "",
152        ty::ImplPolarity::Negative => "!",
153    };
154    let trait_name = tcx.item_name(tcx.impl_trait_id(impl_def_id.to_def_id()));
155    let mut err = {
    tcx.dcx().struct_span_err(impl_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}{1}` impls cannot be specialized",
                            polarity, trait_name))
                })).with_code(E0366)
}struct_span_code_err!(
156        tcx.dcx(),
157        impl_span,
158        E0366,
159        "`{polarity}{trait_name}` impls cannot be specialized",
160    );
161    match arg {
162        ty::util::NotUniqueParam::DuplicateParam(arg) => {
163            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is mentioned multiple times",
                arg))
    })format!("`{arg}` is mentioned multiple times"))
164        }
165        ty::util::NotUniqueParam::NotParam(arg) => {
166            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is not a generic parameter",
                arg))
    })format!("`{arg}` is not a generic parameter"))
167        }
168    };
169    err.span_note(
170        item_span,
171        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use the same sequence of generic lifetime, type and const parameters as the {0} definition",
                self_descr))
    })format!(
172            "use the same sequence of generic lifetime, type and const parameters \
173                     as the {self_descr} definition",
174        ),
175    );
176    Err(err.emit())
177}
178
179fn ensure_all_fields_are_const_destruct<'tcx>(
180    tcx: TyCtxt<'tcx>,
181    impl_def_id: LocalDefId,
182    adt_def_id: DefId,
183) -> Result<(), ErrorGuaranteed> {
184    if !tcx.is_conditionally_const(impl_def_id) {
185        return Ok(());
186    }
187    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
188    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
189
190    let impl_span = tcx.def_span(impl_def_id.to_def_id());
191    let env = ty::EarlyBinder::bind(tcx, tcx.param_env(impl_def_id))
192        .instantiate_identity()
193        .skip_norm_wip();
194    let args = ty::GenericArgs::identity_for_item(tcx, impl_def_id);
195    let destruct_trait = tcx.lang_items().destruct_trait().unwrap();
196    for field in tcx.adt_def(adt_def_id).all_fields() {
197        let field_ty = field.ty(tcx, args).skip_norm_wip();
198        let cause = traits::ObligationCause::new(
199            tcx.def_span(field.did),
200            impl_def_id,
201            ObligationCauseCode::Misc,
202        );
203        ocx.register_obligation(traits::Obligation::new(
204            tcx,
205            cause,
206            env,
207            ty::ClauseKind::HostEffect(ty::HostEffectClause {
208                trait_ref: ty::TraitRef::new(tcx, destruct_trait, [field_ty]),
209                constness: ty::BoundConstness::Maybe,
210            }),
211        ));
212    }
213    ocx.evaluate_obligations_error_on_ambiguity()
214        .into_iter()
215        .map(|error| {
216            let ty::ClauseKind::HostEffect(eff) =
217                error.root_obligation.predicate.expect_clause().kind().no_bound_vars().unwrap()
218            else {
219                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
220            };
221            let field_ty = eff.trait_ref.self_ty();
222            let mut diag = {
    tcx.dcx().struct_span_err(error.root_obligation.cause.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` does not implement `[const] Destruct`",
                            field_ty))
                })).with_code(E0367)
}struct_span_code_err!(
223                tcx.dcx(),
224                error.root_obligation.cause.span,
225                E0367,
226                "`{field_ty}` does not implement `[const] Destruct`",
227            )
228            .with_span_note(impl_span, "required for this `Drop` impl");
229            if field_ty.has_param()
230                && let Some(generics) = tcx.hir_node_by_def_id(impl_def_id).generics()
231            {
232                let destruct_def_id = tcx.lang_items().destruct_trait();
233                ty::suggest_constraining_type_param(
234                    tcx,
235                    generics,
236                    &mut diag,
237                    &field_ty.to_string(),
238                    "[const] Destruct",
239                    destruct_def_id,
240                    None,
241                );
242            }
243            Err(diag.emit())
244        })
245        .collect()
246}
247
248/// Confirms that all predicates defined on the `Drop` impl (`drop_impl_def_id`) are able to be
249/// proven from within `adt_def_id`'s environment. I.e. all the predicates on the impl are
250/// implied by the ADT being well formed.
251fn ensure_impl_predicates_are_implied_by_item_defn<'tcx>(
252    tcx: TyCtxt<'tcx>,
253    impl_def_id: LocalDefId,
254    adt_def_id: DefId,
255    adt_to_impl_args: GenericArgsRef<'tcx>,
256) -> Result<(), ErrorGuaranteed> {
257    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
258    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
259
260    let impl_span = tcx.def_span(impl_def_id.to_def_id());
261    let trait_name = tcx.item_name(tcx.impl_trait_id(impl_def_id.to_def_id()));
262    let polarity = match tcx.impl_polarity(impl_def_id) {
263        ty::ImplPolarity::Positive => "",
264        ty::ImplPolarity::Negative => "!",
265    };
266    // Take the param-env of the adt and instantiate the args that show up in
267    // the implementation's self type. This gives us the assumptions that the
268    // self ty of the implementation is allowed to know just from it being a
269    // well-formed adt, since that's all we're allowed to assume while proving
270    // the Drop implementation is not specialized.
271    //
272    // We don't need to normalize this param-env or anything, since we're only
273    // instantiating it with free params, so no additional param-env normalization
274    // can occur on top of what has been done in the param_env query itself.
275    //
276    // Note: Ideally instead of instantiating the `ParamEnv` with the arguments from the impl ty we
277    // could instead use identity args for the adt. Unfortunately this would cause any errors to
278    // reference the params from the ADT instead of from the impl which is bad UX. To resolve
279    // this we "rename" the ADT's params to be the impl's params which should not affect behaviour.
280    let impl_adt_ty = Ty::new_adt(tcx, tcx.adt_def(adt_def_id), adt_to_impl_args);
281    let adt_env = ty::EarlyBinder::bind_unchecked(tcx.param_env(adt_def_id))
282        .instantiate(tcx, adt_to_impl_args)
283        .skip_norm_wip();
284
285    let fresh_impl_args = infcx.fresh_args_for_item(impl_span, impl_def_id.to_def_id());
286    let fresh_adt_ty =
287        tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_impl_args).skip_norm_wip().self_ty();
288
289    ocx.eq(&ObligationCause::dummy_with_span(impl_span), adt_env, fresh_adt_ty, impl_adt_ty)
290        .expect("equating fully generic trait ref should never fail");
291
292    for (clause, span) in tcx.clauses_of(impl_def_id).instantiate(tcx, fresh_impl_args) {
293        let normalize_cause = traits::ObligationCause::misc(span, impl_def_id);
294        let pred = ocx.normalize(&normalize_cause, adt_env, clause);
295        let cause = traits::ObligationCause::new(
296            span,
297            impl_def_id,
298            ObligationCauseCode::AlwaysApplicableImpl,
299        );
300        ocx.register_obligation(traits::Obligation::new(tcx, cause, adt_env, pred));
301    }
302
303    // All of the custom error reporting logic is to preserve parity with the old
304    // error messages.
305    //
306    // They can probably get removed with better treatment of the new `DropImpl`
307    // obligation cause code, and perhaps some custom logic in `report_region_errors`.
308
309    let errors = ocx.evaluate_obligations_error_on_ambiguity();
310    if !errors.no_errors() {
311        let mut guar = None;
312        let mut root_predicates = FxHashSet::default();
313        for error in errors {
314            let root_predicate = error.root_obligation.predicate;
315            if root_predicates.insert(root_predicate) {
316                let item_span = tcx.def_span(adt_def_id);
317                let self_descr = tcx.def_descr(adt_def_id);
318                guar = Some(
319                    {
    tcx.dcx().struct_span_err(error.root_obligation.cause.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}{1}` impl requires `{2}` but the {3} it is implemented for does not",
                            polarity, trait_name, root_predicate, self_descr))
                })).with_code(E0367)
}struct_span_code_err!(
320                        tcx.dcx(),
321                        error.root_obligation.cause.span,
322                        E0367,
323                        "`{polarity}{trait_name}` impl requires `{root_predicate}` \
324                        but the {self_descr} it is implemented for does not",
325                    )
326                    .with_span_note(item_span, "the implementor must specify the same requirement")
327                    .emit(),
328                );
329            }
330        }
331        return Err(guar.unwrap());
332    }
333
334    let errors = ocx.infcx.resolve_regions(impl_def_id, adt_env, []);
335    if !errors.is_empty() {
336        let mut guar = None;
337        for error in errors {
338            let item_span = tcx.def_span(adt_def_id);
339            let self_descr = tcx.def_descr(adt_def_id);
340            let outlives = match error {
341                RegionResolutionError::ConcreteFailure(_, a, b) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}"),
342                RegionResolutionError::GenericBoundFailure(_, generic, r) => {
343                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", generic, r))
    })format!("{generic}: {r}")
344                }
345                RegionResolutionError::SubSupConflict(_, _, _, a, _, b, _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}"),
346                RegionResolutionError::UpperBoundUniverseConflict(a, _, _, _, b) => {
347                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}: {0}",
                ty::Region::new_var(tcx, a), b))
    })format!("{b}: {a}", a = ty::Region::new_var(tcx, a))
348                }
349                RegionResolutionError::CannotNormalize(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
350            };
351            guar = Some(
352                {
    tcx.dcx().struct_span_err(error.origin().span(),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}{1}` impl requires `{2}` but the {3} it is implemented for does not",
                            polarity, trait_name, outlives, self_descr))
                })).with_code(E0367)
}struct_span_code_err!(
353                    tcx.dcx(),
354                    error.origin().span(),
355                    E0367,
356                    "`{polarity}{trait_name}` impl requires `{outlives}` \
357                    but the {self_descr} it is implemented for does not",
358                )
359                .with_span_note(item_span, "the implementor must specify the same requirement")
360                .emit(),
361            );
362        }
363        return Err(guar.unwrap());
364    }
365
366    Ok(())
367}
368
369/// This function checks at least and at most one of `Drop::drop` and `Drop::pin_drop` is implemented.
370/// It also checks that `Drop::pin_drop` must be implemented if `#[pin_v2]` is present on the type.
371fn check_drop_xor_pin_drop<'tcx>(
372    tcx: TyCtxt<'tcx>,
373    adt_def_id: DefId,
374    drop_impl_did: LocalDefId,
375) -> Result<(), ErrorGuaranteed> {
376    let mut drop_span = None;
377    let mut pin_drop_span = None;
378    for item in tcx.associated_items(drop_impl_did).in_definition_order() {
379        match item.kind {
380            ty::AssocKind::Fn { name: sym::drop, .. } => {
381                drop_span = Some(tcx.def_span(item.def_id))
382            }
383            ty::AssocKind::Fn { name: sym::pin_drop, .. } => {
384                pin_drop_span = Some(tcx.def_span(item.def_id))
385            }
386            _ => {}
387        }
388    }
389
390    match (drop_span, pin_drop_span) {
391        (None, None) => {
392            if tcx.features().pin_ergonomics() {
393                return Err(missing_items_must_implement_one_of_err(
394                    tcx,
395                    drop_impl_did,
396                    [sym::drop, sym::pin_drop].into_iter(),
397                    None,
398                ));
399            } else {
400                return Err(tcx
401                    .dcx()
402                    .span_delayed_bug(tcx.def_span(drop_impl_did), "missing `Drop::drop`"));
403            }
404        }
405        (Some(span), None) => {
406            if tcx.adt_def(adt_def_id).is_pin_project() {
407                let pin_v2_span = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(adt_def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(PinV2(attr)) => {
                        break 'done Some(*attr);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}rustc_hir::find_attr!(tcx, adt_def_id, PinV2(attr) => *attr);
408                let adt_name = tcx.item_name(adt_def_id);
409                return Err(tcx.dcx().emit_err(crate::diagnostics::PinV2WithoutPinDrop {
410                    span,
411                    pin_v2_span,
412                    adt_name,
413                }));
414            }
415        }
416        (None, Some(span)) => {
417            if !tcx.features().pin_ergonomics() {
418                return Err(tcx.dcx().span_delayed_bug(
419                    span,
420                    "`Drop::pin_drop` should be guarded by the library feature gate",
421                ));
422            }
423        }
424        (Some(drop_span), Some(pin_drop_span)) => {
425            return Err(tcx.dcx().emit_err(crate::diagnostics::ConflictImplDropAndPinDrop {
426                span: tcx.def_span(drop_impl_did),
427                drop_span,
428                pin_drop_span,
429            }));
430        }
431    }
432    Ok(())
433}