Skip to main content

rustc_trait_selection/traits/
effects.rs

1use rustc_attr_ir::lang_items::LangItem;
2use rustc_hir as hir;
3use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
4use rustc_infer::traits::{
5    ImplDerivedHostCause, ImplSource, Obligation, ObligationCause, ObligationCauseCode,
6    PredicateObligation,
7};
8use rustc_middle::traits::query::NoSolution;
9use rustc_middle::ty::elaborate::elaborate;
10use rustc_middle::ty::fast_reject::DeepRejectCtxt;
11use rustc_middle::ty::{self, CallerBoundsIterator, Ty, Unnormalized};
12use rustc_span::span_bug;
13use thin_vec::{ThinVec, thin_vec};
14
15use super::SelectionContext;
16use super::normalize::normalize_with_depth_to;
17
18pub type HostEffectObligation<'tcx> = Obligation<'tcx, ty::HostEffectClause<'tcx>>;
19
20pub enum EvaluationFailure {
21    Ambiguous,
22    NoSolution,
23}
24
25pub fn evaluate_host_effect_obligation<'tcx>(
26    selcx: &mut SelectionContext<'_, 'tcx>,
27    obligation: &HostEffectObligation<'tcx>,
28) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
29    if selcx.typing_mode().is_coherence() {
30        ::rustc_span::macros::bug_impl(Some(obligation.cause.span),
    format_args!("should not select host obligation in old solver in intercrate mode"),
    Location::caller());span_bug!(
31            obligation.cause.span,
32            "should not select host obligation in old solver in intercrate mode"
33        );
34    }
35
36    let ref obligation = selcx.infcx.deeply_resolve_ignoring_regions(obligation.clone());
37
38    // Force ambiguity for infer self ty.
39    if obligation.predicate.self_ty().is_ty_var() {
40        return Err(EvaluationFailure::Ambiguous);
41    }
42
43    match evaluate_host_effect_from_bounds(selcx, obligation) {
44        Ok(result) => return Ok(result),
45        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
46        Err(EvaluationFailure::NoSolution) => {}
47    }
48
49    match evaluate_host_effect_from_conditionally_const_item_bounds(selcx, obligation) {
50        Ok(result) => return Ok(result),
51        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
52        Err(EvaluationFailure::NoSolution) => {}
53    }
54
55    match evaluate_host_effect_from_item_bounds(selcx, obligation) {
56        Ok(result) => return Ok(result),
57        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
58        Err(EvaluationFailure::NoSolution) => {}
59    }
60
61    match evaluate_host_effect_from_builtin_impls(selcx, obligation) {
62        Ok(result) => return Ok(result),
63        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
64        Err(EvaluationFailure::NoSolution) => {}
65    }
66
67    match evaluate_host_effect_from_selection_candidate(selcx, obligation) {
68        Ok(result) => return Ok(result),
69        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
70        Err(EvaluationFailure::NoSolution) => {}
71    }
72
73    match evaluate_host_effect_from_trait_alias(selcx, obligation) {
74        Ok(result) => return Ok(result),
75        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
76        Err(EvaluationFailure::NoSolution) => {}
77    }
78
79    Err(EvaluationFailure::NoSolution)
80}
81
82fn match_candidate<'tcx>(
83    selcx: &mut SelectionContext<'_, 'tcx>,
84    obligation: &HostEffectObligation<'tcx>,
85    candidate: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
86    candidate_is_unnormalized: bool,
87    more_nested: impl FnOnce(&mut SelectionContext<'_, 'tcx>, &mut ThinVec<PredicateObligation<'tcx>>),
88) -> Result<ThinVec<PredicateObligation<'tcx>>, NoSolution> {
89    if !candidate.skip_binder().constness.satisfies(obligation.predicate.constness) {
90        return Err(NoSolution);
91    }
92
93    let mut candidate = selcx.infcx.instantiate_binder_with_fresh_vars(
94        obligation.cause.span,
95        BoundRegionConversionTime::HigherRankedType,
96        candidate,
97    );
98
99    let mut nested = ::thin_vec::ThinVec::new()thin_vec![];
100
101    // Unlike param-env bounds, item bounds may not be normalized.
102    if candidate_is_unnormalized {
103        candidate = normalize_with_depth_to(
104            selcx,
105            obligation.param_env,
106            obligation.cause.clone(),
107            obligation.recursion_depth,
108            Unnormalized::new_wip(candidate),
109            &mut nested,
110        );
111    }
112
113    nested.extend(
114        selcx
115            .infcx
116            .eq_raw(
117                &obligation.cause,
118                obligation.param_env,
119                DefineOpaqueTypes::Yes,
120                obligation.predicate.trait_ref,
121                candidate.trait_ref,
122            )?
123            .into_obligations(),
124    );
125
126    more_nested(selcx, &mut nested);
127
128    Ok(nested)
129}
130
131fn evaluate_host_effect_from_bounds<'tcx>(
132    selcx: &mut SelectionContext<'_, 'tcx>,
133    obligation: &HostEffectObligation<'tcx>,
134) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
135    let infcx = selcx.infcx;
136    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
137    let mut candidate = None;
138
139    for clause in obligation.param_env.caller_bounds().non_trait_clauses().iter() {
140        let bound_clause = clause.kind();
141        let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
142            continue;
143        };
144        let data = bound_clause.rebind(data);
145        if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
146            continue;
147        }
148
149        if !drcx
150            .args_may_unify(obligation.predicate.trait_ref.args, data.skip_binder().trait_ref.args)
151        {
152            continue;
153        }
154
155        let is_match =
156            infcx.probe(|_| match_candidate(selcx, obligation, data, false, |_, _| {}).is_ok());
157
158        if is_match {
159            if candidate.is_some() {
160                return Err(EvaluationFailure::Ambiguous);
161            } else {
162                candidate = Some(data);
163            }
164        }
165    }
166
167    if let Some(data) = candidate {
168        Ok(match_candidate(selcx, obligation, data, false, |_, _| {})
169            .expect("candidate matched before, so it should match again"))
170    } else {
171        Err(EvaluationFailure::NoSolution)
172    }
173}
174
175/// Assembles constness bounds from `~const` item bounds on alias types, which only
176/// hold if the `~const` where bounds also hold and the parent trait is `~const`.
177fn evaluate_host_effect_from_conditionally_const_item_bounds<'tcx>(
178    selcx: &mut SelectionContext<'_, 'tcx>,
179    obligation: &HostEffectObligation<'tcx>,
180) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
181    let infcx = selcx.infcx;
182    let tcx = infcx.tcx;
183    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
184    let mut candidate = None;
185
186    let mut consider_ty = obligation.predicate.self_ty();
187    while let ty::Alias(
188        _,
189        alias_ty @ ty::AliasTy {
190            kind: kind @ (ty::Projection { def_id } | ty::Opaque { def_id }),
191            ..
192        },
193    ) = *consider_ty.kind()
194    {
195        if tcx.is_conditionally_const(def_id) {
196            for clause in elaborate(
197                tcx,
198                tcx.explicit_implied_const_bounds(def_id)
199                    .iter_instantiated_copied(tcx, alias_ty.args)
200                    .map(Unnormalized::skip_norm_wip)
201                    .map(|(trait_ref, _)| {
202                        trait_ref.to_host_effect_clause(tcx, obligation.predicate.constness)
203                    }),
204            ) {
205                let bound_clause = clause.kind();
206                let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
207                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("should not elaborate non-HostEffect from HostEffect")));
}unreachable!("should not elaborate non-HostEffect from HostEffect")
208                };
209                let data = bound_clause.rebind(data);
210                if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
211                    continue;
212                }
213
214                if !drcx.args_may_unify(
215                    obligation.predicate.trait_ref.args,
216                    data.skip_binder().trait_ref.args,
217                ) {
218                    continue;
219                }
220
221                let is_match = infcx
222                    .probe(|_| match_candidate(selcx, obligation, data, true, |_, _| {}).is_ok());
223
224                if is_match {
225                    if candidate.is_some() {
226                        return Err(EvaluationFailure::Ambiguous);
227                    } else {
228                        candidate = Some((data, alias_ty, def_id));
229                    }
230                }
231            }
232        }
233
234        if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::Projection { .. } => true,
    _ => false,
}matches!(kind, ty::Projection { .. }) {
235            break;
236        }
237
238        consider_ty = alias_ty.self_ty();
239    }
240
241    if let Some((data, alias_ty, def_id)) = candidate {
242        Ok(match_candidate(selcx, obligation, data, true, |selcx, nested| {
243            // An alias bound only holds if we also check the const conditions
244            // of the alias, so we need to register those, too.
245            let const_conditions = tcx.const_conditions(def_id).instantiate(tcx, alias_ty.args);
246            let const_conditions: Vec<_> = const_conditions
247                .into_iter()
248                .map(|(trait_ref, span)| {
249                    let trait_ref = normalize_with_depth_to(
250                        selcx,
251                        obligation.param_env,
252                        obligation.cause.clone(),
253                        obligation.recursion_depth,
254                        trait_ref,
255                        nested,
256                    );
257                    (trait_ref, span)
258                })
259                .collect();
260            nested.extend(const_conditions.into_iter().map(|(trait_ref, _)| {
261                obligation
262                    .with(tcx, trait_ref.to_host_effect_clause(tcx, obligation.predicate.constness))
263            }));
264        })
265        .expect("candidate matched before, so it should match again"))
266    } else {
267        Err(EvaluationFailure::NoSolution)
268    }
269}
270
271/// Assembles constness bounds "normal" item bounds on aliases, which may include
272/// unconditionally `const` bounds that are *not* conditional and thus always hold.
273fn evaluate_host_effect_from_item_bounds<'tcx>(
274    selcx: &mut SelectionContext<'_, 'tcx>,
275    obligation: &HostEffectObligation<'tcx>,
276) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
277    let infcx = selcx.infcx;
278    let tcx = infcx.tcx;
279    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
280    let mut candidate = None;
281
282    let mut consider_ty = obligation.predicate.self_ty();
283    while let ty::Alias(
284        _,
285        alias_ty @ ty::AliasTy {
286            kind: kind @ (ty::Projection { def_id } | ty::Opaque { def_id }),
287            ..
288        },
289    ) = *consider_ty.kind()
290    {
291        for clause in tcx
292            .item_bounds(def_id)
293            .iter_instantiated(tcx, alias_ty.args)
294            .map(Unnormalized::skip_norm_wip)
295        {
296            let bound_clause = clause.kind();
297            let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
298                continue;
299            };
300            let data = bound_clause.rebind(data);
301            if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
302                continue;
303            }
304
305            if !drcx.args_may_unify(
306                obligation.predicate.trait_ref.args,
307                data.skip_binder().trait_ref.args,
308            ) {
309                continue;
310            }
311
312            let is_match =
313                infcx.probe(|_| match_candidate(selcx, obligation, data, true, |_, _| {}).is_ok());
314
315            if is_match {
316                if candidate.is_some() {
317                    return Err(EvaluationFailure::Ambiguous);
318                } else {
319                    candidate = Some(data);
320                }
321            }
322        }
323
324        if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::Projection { .. } => true,
    _ => false,
}matches!(kind, ty::Projection { .. }) {
325            break;
326        }
327
328        consider_ty = alias_ty.self_ty();
329    }
330
331    if let Some(data) = candidate {
332        Ok(match_candidate(selcx, obligation, data, true, |_, _| {})
333            .expect("candidate matched before, so it should match again"))
334    } else {
335        Err(EvaluationFailure::NoSolution)
336    }
337}
338
339fn evaluate_host_effect_from_builtin_impls<'tcx>(
340    selcx: &mut SelectionContext<'_, 'tcx>,
341    obligation: &HostEffectObligation<'tcx>,
342) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
343    match selcx.tcx().as_lang_item(obligation.predicate.def_id()) {
344        Some(LangItem::Copy | LangItem::Clone) => {
345            evaluate_host_effect_for_copy_clone_goal(selcx, obligation)
346        }
347        Some(LangItem::Destruct) => evaluate_host_effect_for_destruct_goal(selcx, obligation),
348        Some(LangItem::Fn | LangItem::FnMut | LangItem::FnOnce) => {
349            evaluate_host_effect_for_fn_goal(selcx, obligation)
350        }
351        _ => Err(EvaluationFailure::NoSolution),
352    }
353}
354
355fn evaluate_host_effect_for_copy_clone_goal<'tcx>(
356    selcx: &mut SelectionContext<'_, 'tcx>,
357    obligation: &HostEffectObligation<'tcx>,
358) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
359    let tcx = selcx.tcx();
360    let self_ty = obligation.predicate.self_ty();
361    let constituent_tys = match *self_ty.kind() {
362        // impl Copy/Clone for FnDef, FnPtr
363        ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => Ok(ty::Binder::dummy(::alloc::vec::Vec::new()vec![])),
364
365        // Implementations are provided in core
366        ty::Uint(_)
367        | ty::Int(_)
368        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
369        | ty::Bool
370        | ty::Float(_)
371        | ty::Char
372        | ty::RawPtr(..)
373        | ty::Never
374        | ty::Ref(_, _, ty::Mutability::Not)
375        | ty::Array(..) => Err(EvaluationFailure::NoSolution),
376
377        // Cannot implement in core, as we can't be generic over patterns yet,
378        // so we'd have to list all patterns and type combinations.
379        ty::Pat(ty, ..) => Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ty]))vec![ty])),
380
381        ty::Dynamic(..)
382        | ty::Str
383        | ty::Slice(_)
384        | ty::Foreign(..)
385        | ty::Ref(_, _, ty::Mutability::Mut)
386        | ty::Adt(_, _)
387        | ty::Alias(_, _)
388        | ty::Param(_)
389        | ty::Placeholder(..) => Err(EvaluationFailure::NoSolution),
390
391        ty::Bound(..)
392        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
393            {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
394        }
395
396        // impl Copy/Clone for (T1, T2, .., Tn) where T1: Copy/Clone, T2: Copy/Clone, .. Tn: Copy/Clone
397        ty::Tuple(tys) => Ok(ty::Binder::dummy(tys.to_vec())),
398
399        // impl Copy/Clone for Closure where Self::TupledUpvars: Copy/Clone
400        ty::Closure(_, args) => Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [args.as_closure().tupled_upvars_ty()]))vec![args.as_closure().tupled_upvars_ty()])),
401
402        // impl Copy/Clone for CoroutineClosure where Self::TupledUpvars: Copy/Clone
403        ty::CoroutineClosure(_, args) => {
404            Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [args.as_coroutine_closure().tupled_upvars_ty()]))vec![args.as_coroutine_closure().tupled_upvars_ty()]))
405        }
406
407        // only when `coroutine_clone` is enabled and the coroutine is movable
408        // impl Copy/Clone for Coroutine where T: Copy/Clone forall T in (upvars, witnesses)
409        ty::Coroutine(def_id, args) => {
410            if selcx.should_stall_coroutine(def_id) {
411                return Err(EvaluationFailure::Ambiguous);
412            }
413            match tcx.coroutine_movability(def_id) {
414                ty::Movability::Static => Err(EvaluationFailure::NoSolution),
415                ty::Movability::Movable => {
416                    if tcx.features().coroutine_clone() {
417                        Ok(ty::Binder::dummy(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [args.as_coroutine().tupled_upvars_ty(),
                Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args)]))vec![
418                            args.as_coroutine().tupled_upvars_ty(),
419                            Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args),
420                        ]))
421                    } else {
422                        Err(EvaluationFailure::NoSolution)
423                    }
424                }
425            }
426        }
427
428        ty::UnsafeBinder(_) => Err(EvaluationFailure::NoSolution),
429
430        // impl Copy/Clone for CoroutineWitness where T: Copy/Clone forall T in coroutine_hidden_types
431        ty::CoroutineWitness(def_id, args) => Ok(tcx
432            .coroutine_hidden_types(def_id)
433            .instantiate(tcx, args)
434            .skip_norm_wip()
435            .map_bound(|bound| bound.types.to_vec())),
436
437        // FIXME(scrabsha)
438        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
439    }?;
440
441    Ok(constituent_tys
442        .iter()
443        .map(|ty| {
444            obligation.with(
445                tcx,
446                ty.map_bound(|ty| ty::TraitRef::new(tcx, obligation.predicate.def_id(), [ty]))
447                    .to_host_effect_clause(tcx, obligation.predicate.constness),
448            )
449        })
450        .collect())
451}
452
453// NOTE: Keep this in sync with `const_conditions_for_destruct` in the new solver.
454fn evaluate_host_effect_for_destruct_goal<'tcx>(
455    selcx: &mut SelectionContext<'_, 'tcx>,
456    obligation: &HostEffectObligation<'tcx>,
457) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
458    let tcx = selcx.tcx();
459    let destruct_def_id = tcx.require_lang_item(LangItem::Destruct, obligation.cause.span);
460    let self_ty = obligation.predicate.self_ty();
461
462    let const_conditions = match *self_ty.kind() {
463        // `ManuallyDrop` is trivially `[const] Destruct` as we do not run any drop glue on it.
464        ty::Adt(adt_def, _) if adt_def.is_manually_drop() => ::thin_vec::ThinVec::new()thin_vec![],
465
466        // An ADT is `[const] Destruct` only if all of the fields are,
467        // *and* if there is a `Drop` impl, that `Drop` impl is also `[const]`.
468        ty::Adt(adt_def, args) => {
469            let mut const_conditions: ThinVec<_> = adt_def
470                .all_fields()
471                .map(|field| {
472                    ty::TraitRef::new(tcx, destruct_def_id, [field.ty(tcx, args).skip_norm_wip()])
473                })
474                .collect();
475            match adt_def.destructor(tcx).map(|dtor| tcx.constness(dtor.did)) {
476                Some(hir::Constness::Const { always: true }) => {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("FIXME(comptime)")));
}unimplemented!("FIXME(comptime)"),
477                // `Drop` impl exists, but it's not const. Type cannot be `[const] Destruct`.
478                Some(hir::Constness::NotConst) => return Err(EvaluationFailure::NoSolution),
479                // `Drop` impl exists, and it's const. Require `Ty: [const] Drop` to hold.
480                Some(hir::Constness::Const { always: false }) => {
481                    let drop_def_id = tcx.require_lang_item(LangItem::Drop, obligation.cause.span);
482                    let drop_trait_ref = ty::TraitRef::new(tcx, drop_def_id, [self_ty]);
483                    const_conditions.push(drop_trait_ref);
484                }
485                // No `Drop` impl, no need to require anything else.
486                None => {}
487            }
488            const_conditions
489        }
490
491        ty::Array(ty, _) | ty::Pat(ty, _) | ty::Slice(ty) => {
492            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ty::TraitRef::new(tcx, destruct_def_id, [ty]));
    vec
}thin_vec![ty::TraitRef::new(tcx, destruct_def_id, [ty])]
493        }
494
495        ty::Tuple(tys) => {
496            tys.iter().map(|field_ty| ty::TraitRef::new(tcx, destruct_def_id, [field_ty])).collect()
497        }
498
499        // Trivially implement `[const] Destruct`
500        ty::Bool
501        | ty::Char
502        | ty::Int(..)
503        | ty::Uint(..)
504        | ty::Float(..)
505        | ty::Str
506        | ty::RawPtr(..)
507        | ty::Ref(..)
508        | ty::FnDef(..)
509        | ty::FnPtr(..)
510        | ty::Never
511        | ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
512        | ty::Error(_) => ::thin_vec::ThinVec::new()thin_vec![],
513
514        // Closures are [const] Destruct when all of their upvars (captures) are [const] Destruct.
515        ty::Closure(_, args) => {
516            let closure_args = args.as_closure();
517            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ty::TraitRef::new(tcx, destruct_def_id,
            [closure_args.tupled_upvars_ty()]));
    vec
}thin_vec![ty::TraitRef::new(tcx, destruct_def_id, [closure_args.tupled_upvars_ty()])]
518        }
519
520        // Coroutines could implement `[const] Drop`,
521        // but they don't really need to right now.
522        ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) | ty::CoroutineWitness(_, _) => {
523            return Err(EvaluationFailure::NoSolution);
524        }
525
526        // FIXME(unsafe_binders): Unsafe binders could implement `[const] Drop`
527        // if their inner type implements it.
528        ty::UnsafeBinder(_) => return Err(EvaluationFailure::NoSolution),
529
530        ty::Dynamic(..) | ty::Param(_) | ty::Alias(..) | ty::Placeholder(_) | ty::Foreign(_) => {
531            return Err(EvaluationFailure::NoSolution);
532        }
533
534        ty::Bound(..)
535        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
536            {
    ::core::panicking::panic_fmt(format_args!("unexpected type `{0:?}`",
            self_ty));
}panic!("unexpected type `{self_ty:?}`")
537        }
538
539        // FIXME(scrabsha)
540        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
541    };
542
543    Ok(const_conditions
544        .into_iter()
545        .map(|trait_ref| {
546            obligation.with(
547                tcx,
548                ty::Binder::dummy(trait_ref)
549                    .to_host_effect_clause(tcx, obligation.predicate.constness),
550            )
551        })
552        .collect())
553}
554
555// NOTE: Keep this in sync with `extract_fn_def_from_const_callable` in the new solver.
556fn evaluate_host_effect_for_fn_goal<'tcx>(
557    selcx: &mut SelectionContext<'_, 'tcx>,
558    obligation: &HostEffectObligation<'tcx>,
559) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
560    let tcx = selcx.tcx();
561    let self_ty = obligation.predicate.self_ty();
562
563    let (def, args) = match *self_ty.kind() {
564        ty::FnDef(def, args) => (def, args),
565
566        // We may support function pointers at some point in the future
567        ty::FnPtr(..) => return Err(EvaluationFailure::NoSolution),
568
569        // Coroutines could implement `[const] Fn`,
570        // but they don't really need to right now.
571        ty::CoroutineClosure(_, _) => return Err(EvaluationFailure::NoSolution),
572
573        ty::Closure(def, args) => (def, ty::Binder::dummy(args)),
574
575        // Everything else needs explicit impls or cannot have an impl
576        _ => return Err(EvaluationFailure::NoSolution),
577    };
578
579    match tcx.constness(def) {
580        // FIXME(comptime)
581        hir::Constness::Const { always: true } => Err(EvaluationFailure::NoSolution),
582        hir::Constness::Const { always: false } => Ok(tcx
583            .const_conditions(def)
584            .instantiate(tcx, args.no_bound_vars().unwrap())
585            .into_iter()
586            .map(|(c, span)| {
587                let code = ObligationCauseCode::WhereClause(def, span);
588                let cause =
589                    ObligationCause::new(obligation.cause.span, obligation.cause.body_def_id, code);
590                Obligation::new(
591                    tcx,
592                    cause,
593                    obligation.param_env,
594                    c.to_host_effect_clause(tcx, obligation.predicate.constness).skip_norm_wip(),
595                )
596            })
597            .collect()),
598        hir::Constness::NotConst => Err(EvaluationFailure::NoSolution),
599    }
600}
601
602fn evaluate_host_effect_from_selection_candidate<'tcx>(
603    selcx: &mut SelectionContext<'_, 'tcx>,
604    obligation: &HostEffectObligation<'tcx>,
605) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
606    let tcx = selcx.tcx();
607    selcx.infcx.commit_if_ok(|_| {
608        match selcx.select(&obligation.with(tcx, obligation.predicate.trait_ref)) {
609            Ok(None) => Err(EvaluationFailure::Ambiguous),
610            Err(_) => Err(EvaluationFailure::NoSolution),
611            Ok(Some(source)) => match source {
612                ImplSource::UserDefined(impl_) => {
613                    match tcx.impl_trait_header(impl_.impl_def_id).constness {
614                        rustc_hir::Constness::Const { always } => {
615                            if always {
616                                // FIXME(comptime): just bailing for now to avoid an ICE in a test.
617                                return Err(EvaluationFailure::NoSolution);
618                            }
619                        }
620                        rustc_hir::Constness::NotConst => {
621                            return Err(EvaluationFailure::NoSolution);
622                        }
623                    }
624
625                    let mut nested = impl_.nested;
626                    nested.extend(
627                        tcx.const_conditions(impl_.impl_def_id)
628                            .instantiate(tcx, impl_.args)
629                            .into_iter()
630                            .map(|(trait_ref, span)| {
631                                Obligation::new(
632                                    tcx,
633                                    obligation.cause.clone().derived_host_cause(
634                                        ty::Binder::dummy(obligation.predicate),
635                                        |derived| {
636                                            ObligationCauseCode::ImplDerivedHost(Box::new(
637                                                ImplDerivedHostCause {
638                                                    derived,
639                                                    impl_def_id: impl_.impl_def_id,
640                                                    span,
641                                                },
642                                            ))
643                                        },
644                                    ),
645                                    obligation.param_env,
646                                    trait_ref
647                                        .to_host_effect_clause(tcx, obligation.predicate.constness)
648                                        .skip_norm_wip(),
649                                )
650                            }),
651                    );
652
653                    Ok(nested)
654                }
655                _ => Err(EvaluationFailure::NoSolution),
656            },
657        }
658    })
659}
660
661fn evaluate_host_effect_from_trait_alias<'tcx>(
662    selcx: &mut SelectionContext<'_, 'tcx>,
663    obligation: &HostEffectObligation<'tcx>,
664) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
665    let tcx = selcx.tcx();
666    let def_id = obligation.predicate.def_id();
667    if !tcx.trait_is_alias(def_id) {
668        return Err(EvaluationFailure::NoSolution);
669    }
670
671    Ok(tcx
672        .const_conditions(def_id)
673        .instantiate(tcx, obligation.predicate.trait_ref.args)
674        .into_iter()
675        .map(|(trait_ref, span)| {
676            Obligation::new(
677                tcx,
678                obligation.cause.clone().derived_host_cause(
679                    ty::Binder::dummy(obligation.predicate),
680                    |derived| {
681                        ObligationCauseCode::ImplDerivedHost(Box::new(ImplDerivedHostCause {
682                            derived,
683                            impl_def_id: def_id,
684                            span,
685                        }))
686                    },
687                ),
688                obligation.param_env,
689                trait_ref
690                    .to_host_effect_clause(tcx, obligation.predicate.constness)
691                    .skip_norm_wip(),
692            )
693        })
694        .collect())
695}