frontend 0.4.1

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::rustc_hir as hir;
use crate::rustc_hir::attrs::lang_items::LangItem;
use crate::rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes};
use crate::rustc_infer::traits::{
    ImplDerivedHostCause, ImplSource, Obligation, ObligationCause, ObligationCauseCode,
    PredicateObligation,
};
use crate::span_bug;
use crate::rustc_middle::traits::query::NoSolution;
use crate::rustc_middle::ty::elaborate::elaborate;
use crate::rustc_middle::ty::fast_reject::DeepRejectCtxt;
use crate::rustc_middle::ty::{self, Ty, Unnormalized};
use thin_vec::{ThinVec, thin_vec};

use super::SelectionContext;
use super::normalize::normalize_with_depth_to;

pub type HostEffectObligation<'tcx> = Obligation<'tcx, ty::HostEffectClause<'tcx>>;

pub enum EvaluationFailure {
    Ambiguous,
    NoSolution,
}

pub fn evaluate_host_effect_obligation<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    if selcx.typing_mode().is_coherence() {
        span_bug!(
            obligation.cause.span,
            "should not select host obligation in old solver in intercrate mode"
        );
    }

    let ref obligation = selcx.infcx.resolve_vars_if_possible(obligation.clone());

    // Force ambiguity for infer self ty.
    if obligation.predicate.self_ty().is_ty_var() {
        return Err(EvaluationFailure::Ambiguous);
    }

    match evaluate_host_effect_from_bounds(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    match evaluate_host_effect_from_conditionally_const_item_bounds(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    match evaluate_host_effect_from_item_bounds(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    match evaluate_host_effect_from_builtin_impls(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    match evaluate_host_effect_from_selection_candidate(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    match evaluate_host_effect_from_trait_alias(selcx, obligation) {
        Ok(result) => return Ok(result),
        Err(EvaluationFailure::Ambiguous) => return Err(EvaluationFailure::Ambiguous),
        Err(EvaluationFailure::NoSolution) => {}
    }

    Err(EvaluationFailure::NoSolution)
}

fn match_candidate<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
    candidate: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
    candidate_is_unnormalized: bool,
    more_nested: impl FnOnce(&mut SelectionContext<'_, 'tcx>, &mut ThinVec<PredicateObligation<'tcx>>),
) -> Result<ThinVec<PredicateObligation<'tcx>>, NoSolution> {
    if !candidate.skip_binder().constness.satisfies(obligation.predicate.constness) {
        return Err(NoSolution);
    }

    let mut candidate = selcx.infcx.instantiate_binder_with_fresh_vars(
        obligation.cause.span,
        BoundRegionConversionTime::HigherRankedType,
        candidate,
    );

    let mut nested = thin_vec![];

    // Unlike param-env bounds, item bounds may not be normalized.
    if candidate_is_unnormalized {
        candidate = normalize_with_depth_to(
            selcx,
            obligation.param_env,
            obligation.cause.clone(),
            obligation.recursion_depth,
            Unnormalized::new_wip(candidate),
            &mut nested,
        );
    }

    nested.extend(
        selcx
            .infcx
            .at(&obligation.cause, obligation.param_env)
            .eq(DefineOpaqueTypes::Yes, obligation.predicate.trait_ref, candidate.trait_ref)?
            .into_obligations(),
    );

    more_nested(selcx, &mut nested);

    Ok(nested)
}

fn evaluate_host_effect_from_bounds<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let infcx = selcx.infcx;
    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
    let mut candidate = None;

    for clause in obligation.param_env.caller_bounds() {
        let bound_clause = clause.kind();
        let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
            continue;
        };
        let data = bound_clause.rebind(data);
        if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
            continue;
        }

        if !drcx
            .args_may_unify(obligation.predicate.trait_ref.args, data.skip_binder().trait_ref.args)
        {
            continue;
        }

        let is_match =
            infcx.probe(|_| match_candidate(selcx, obligation, data, false, |_, _| {}).is_ok());

        if is_match {
            if candidate.is_some() {
                return Err(EvaluationFailure::Ambiguous);
            } else {
                candidate = Some(data);
            }
        }
    }

    if let Some(data) = candidate {
        Ok(match_candidate(selcx, obligation, data, false, |_, _| {})
            .expect("candidate matched before, so it should match again"))
    } else {
        Err(EvaluationFailure::NoSolution)
    }
}

/// Assembles constness bounds from `~const` item bounds on alias types, which only
/// hold if the `~const` where bounds also hold and the parent trait is `~const`.
fn evaluate_host_effect_from_conditionally_const_item_bounds<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let infcx = selcx.infcx;
    let tcx = infcx.tcx;
    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
    let mut candidate = None;

    let mut consider_ty = obligation.predicate.self_ty();
    while let ty::Alias(
        _,
        alias_ty @ ty::AliasTy {
            kind: kind @ (ty::Projection { def_id } | ty::Opaque { def_id }),
            ..
        },
    ) = *consider_ty.kind()
    {
        if tcx.is_conditionally_const(def_id) {
            for clause in elaborate(
                tcx,
                tcx.explicit_implied_const_bounds(def_id)
                    .iter_instantiated_copied(tcx, alias_ty.args)
                    .map(Unnormalized::skip_norm_wip)
                    .map(|(trait_ref, _)| {
                        trait_ref.to_host_effect_clause(tcx, obligation.predicate.constness)
                    }),
            ) {
                let bound_clause = clause.kind();
                let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
                    unreachable!("should not elaborate non-HostEffect from HostEffect")
                };
                let data = bound_clause.rebind(data);
                if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
                    continue;
                }

                if !drcx.args_may_unify(
                    obligation.predicate.trait_ref.args,
                    data.skip_binder().trait_ref.args,
                ) {
                    continue;
                }

                let is_match = infcx
                    .probe(|_| match_candidate(selcx, obligation, data, true, |_, _| {}).is_ok());

                if is_match {
                    if candidate.is_some() {
                        return Err(EvaluationFailure::Ambiguous);
                    } else {
                        candidate = Some((data, alias_ty, def_id));
                    }
                }
            }
        }

        if !matches!(kind, ty::Projection { .. }) {
            break;
        }

        consider_ty = alias_ty.self_ty();
    }

    if let Some((data, alias_ty, def_id)) = candidate {
        Ok(match_candidate(selcx, obligation, data, true, |selcx, nested| {
            // An alias bound only holds if we also check the const conditions
            // of the alias, so we need to register those, too.
            let const_conditions = tcx.const_conditions(def_id).instantiate(tcx, alias_ty.args);
            let const_conditions: Vec<_> = const_conditions
                .into_iter()
                .map(|(trait_ref, span)| {
                    let trait_ref = normalize_with_depth_to(
                        selcx,
                        obligation.param_env,
                        obligation.cause.clone(),
                        obligation.recursion_depth,
                        trait_ref,
                        nested,
                    );
                    (trait_ref, span)
                })
                .collect();
            nested.extend(const_conditions.into_iter().map(|(trait_ref, _)| {
                obligation
                    .with(tcx, trait_ref.to_host_effect_clause(tcx, obligation.predicate.constness))
            }));
        })
        .expect("candidate matched before, so it should match again"))
    } else {
        Err(EvaluationFailure::NoSolution)
    }
}

/// Assembles constness bounds "normal" item bounds on aliases, which may include
/// unconditionally `const` bounds that are *not* conditional and thus always hold.
fn evaluate_host_effect_from_item_bounds<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let infcx = selcx.infcx;
    let tcx = infcx.tcx;
    let drcx = DeepRejectCtxt::relate_rigid_rigid(selcx.tcx());
    let mut candidate = None;

    let mut consider_ty = obligation.predicate.self_ty();
    while let ty::Alias(
        _,
        alias_ty @ ty::AliasTy {
            kind: kind @ (ty::Projection { def_id } | ty::Opaque { def_id }),
            ..
        },
    ) = *consider_ty.kind()
    {
        for clause in tcx
            .item_bounds(def_id)
            .iter_instantiated(tcx, alias_ty.args)
            .map(Unnormalized::skip_norm_wip)
        {
            let bound_clause = clause.kind();
            let ty::ClauseKind::HostEffect(data) = bound_clause.skip_binder() else {
                continue;
            };
            let data = bound_clause.rebind(data);
            if data.skip_binder().trait_ref.def_id != obligation.predicate.trait_ref.def_id {
                continue;
            }

            if !drcx.args_may_unify(
                obligation.predicate.trait_ref.args,
                data.skip_binder().trait_ref.args,
            ) {
                continue;
            }

            let is_match =
                infcx.probe(|_| match_candidate(selcx, obligation, data, true, |_, _| {}).is_ok());

            if is_match {
                if candidate.is_some() {
                    return Err(EvaluationFailure::Ambiguous);
                } else {
                    candidate = Some(data);
                }
            }
        }

        if !matches!(kind, ty::Projection { .. }) {
            break;
        }

        consider_ty = alias_ty.self_ty();
    }

    if let Some(data) = candidate {
        Ok(match_candidate(selcx, obligation, data, true, |_, _| {})
            .expect("candidate matched before, so it should match again"))
    } else {
        Err(EvaluationFailure::NoSolution)
    }
}

fn evaluate_host_effect_from_builtin_impls<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    match selcx.tcx().as_lang_item(obligation.predicate.def_id()) {
        Some(LangItem::Copy | LangItem::Clone) => {
            evaluate_host_effect_for_copy_clone_goal(selcx, obligation)
        }
        Some(LangItem::Destruct) => evaluate_host_effect_for_destruct_goal(selcx, obligation),
        Some(LangItem::Fn | LangItem::FnMut | LangItem::FnOnce) => {
            evaluate_host_effect_for_fn_goal(selcx, obligation)
        }
        _ => Err(EvaluationFailure::NoSolution),
    }
}

fn evaluate_host_effect_for_copy_clone_goal<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let tcx = selcx.tcx();
    let self_ty = obligation.predicate.self_ty();
    let constituent_tys = match *self_ty.kind() {
        // impl Copy/Clone for FnDef, FnPtr
        ty::FnDef(..) | ty::FnPtr(..) | ty::Error(_) => Ok(ty::Binder::dummy(vec![])),

        // Implementations are provided in core
        ty::Uint(_)
        | ty::Int(_)
        | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
        | ty::Bool
        | ty::Float(_)
        | ty::Char
        | ty::RawPtr(..)
        | ty::Never
        | ty::Ref(_, _, ty::Mutability::Not)
        | ty::Array(..) => Err(EvaluationFailure::NoSolution),

        // Cannot implement in core, as we can't be generic over patterns yet,
        // so we'd have to list all patterns and type combinations.
        ty::Pat(ty, ..) => Ok(ty::Binder::dummy(vec![ty])),

        ty::Dynamic(..)
        | ty::Str
        | ty::Slice(_)
        | ty::Foreign(..)
        | ty::Ref(_, _, ty::Mutability::Mut)
        | ty::Adt(_, _)
        | ty::Alias(_, _)
        | ty::Param(_)
        | ty::Placeholder(..) => Err(EvaluationFailure::NoSolution),

        ty::Bound(..)
        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
            panic!("unexpected type `{self_ty:?}`")
        }

        // impl Copy/Clone for (T1, T2, .., Tn) where T1: Copy/Clone, T2: Copy/Clone, .. Tn: Copy/Clone
        ty::Tuple(tys) => Ok(ty::Binder::dummy(tys.to_vec())),

        // impl Copy/Clone for Closure where Self::TupledUpvars: Copy/Clone
        ty::Closure(_, args) => Ok(ty::Binder::dummy(vec![args.as_closure().tupled_upvars_ty()])),

        // impl Copy/Clone for CoroutineClosure where Self::TupledUpvars: Copy/Clone
        ty::CoroutineClosure(_, args) => {
            Ok(ty::Binder::dummy(vec![args.as_coroutine_closure().tupled_upvars_ty()]))
        }

        // only when `coroutine_clone` is enabled and the coroutine is movable
        // impl Copy/Clone for Coroutine where T: Copy/Clone forall T in (upvars, witnesses)
        ty::Coroutine(def_id, args) => {
            if selcx.should_stall_coroutine(def_id) {
                return Err(EvaluationFailure::Ambiguous);
            }
            match tcx.coroutine_movability(def_id) {
                ty::Movability::Static => Err(EvaluationFailure::NoSolution),
                ty::Movability::Movable => {
                    if tcx.features().coroutine_clone() {
                        Ok(ty::Binder::dummy(vec![
                            args.as_coroutine().tupled_upvars_ty(),
                            Ty::new_coroutine_witness_for_coroutine(tcx, def_id, args),
                        ]))
                    } else {
                        Err(EvaluationFailure::NoSolution)
                    }
                }
            }
        }

        ty::UnsafeBinder(_) => Err(EvaluationFailure::NoSolution),

        // impl Copy/Clone for CoroutineWitness where T: Copy/Clone forall T in coroutine_hidden_types
        ty::CoroutineWitness(def_id, args) => Ok(tcx
            .coroutine_hidden_types(def_id)
            .instantiate(tcx, args)
            .skip_norm_wip()
            .map_bound(|bound| bound.types.to_vec())),
    }?;

    Ok(constituent_tys
        .iter()
        .map(|ty| {
            obligation.with(
                tcx,
                ty.map_bound(|ty| ty::TraitRef::new(tcx, obligation.predicate.def_id(), [ty]))
                    .to_host_effect_clause(tcx, obligation.predicate.constness),
            )
        })
        .collect())
}

// NOTE: Keep this in sync with `const_conditions_for_destruct` in the new solver.
fn evaluate_host_effect_for_destruct_goal<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let tcx = selcx.tcx();
    let destruct_def_id = tcx.require_lang_item(LangItem::Destruct, obligation.cause.span);
    let self_ty = obligation.predicate.self_ty();

    let const_conditions = match *self_ty.kind() {
        // `ManuallyDrop` is trivially `[const] Destruct` as we do not run any drop glue on it.
        ty::Adt(adt_def, _) if adt_def.is_manually_drop() => thin_vec![],

        // An ADT is `[const] Destruct` only if all of the fields are,
        // *and* if there is a `Drop` impl, that `Drop` impl is also `[const]`.
        ty::Adt(adt_def, args) => {
            let mut const_conditions: ThinVec<_> = adt_def
                .all_fields()
                .map(|field| {
                    ty::TraitRef::new(tcx, destruct_def_id, [field.ty(tcx, args).skip_norm_wip()])
                })
                .collect();
            match adt_def.destructor(tcx).map(|dtor| tcx.constness(dtor.did)) {
                Some(hir::Constness::Const { always: true }) => unimplemented!("FIXME(comptime)"),
                // `Drop` impl exists, but it's not const. Type cannot be `[const] Destruct`.
                Some(hir::Constness::NotConst) => return Err(EvaluationFailure::NoSolution),
                // `Drop` impl exists, and it's const. Require `Ty: [const] Drop` to hold.
                Some(hir::Constness::Const { always: false }) => {
                    let drop_def_id = tcx.require_lang_item(LangItem::Drop, obligation.cause.span);
                    let drop_trait_ref = ty::TraitRef::new(tcx, drop_def_id, [self_ty]);
                    const_conditions.push(drop_trait_ref);
                }
                // No `Drop` impl, no need to require anything else.
                None => {}
            }
            const_conditions
        }

        ty::Array(ty, _) | ty::Pat(ty, _) | ty::Slice(ty) => {
            thin_vec![ty::TraitRef::new(tcx, destruct_def_id, [ty])]
        }

        ty::Tuple(tys) => {
            tys.iter().map(|field_ty| ty::TraitRef::new(tcx, destruct_def_id, [field_ty])).collect()
        }

        // Trivially implement `[const] Destruct`
        ty::Bool
        | ty::Char
        | ty::Int(..)
        | ty::Uint(..)
        | ty::Float(..)
        | ty::Str
        | ty::RawPtr(..)
        | ty::Ref(..)
        | ty::FnDef(..)
        | ty::FnPtr(..)
        | ty::Never
        | ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
        | ty::Error(_) => thin_vec![],

        // Closures are [const] Destruct when all of their upvars (captures) are [const] Destruct.
        ty::Closure(_, args) => {
            let closure_args = args.as_closure();
            thin_vec![ty::TraitRef::new(tcx, destruct_def_id, [closure_args.tupled_upvars_ty()])]
        }

        // Coroutines could implement `[const] Drop`,
        // but they don't really need to right now.
        ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) | ty::CoroutineWitness(_, _) => {
            return Err(EvaluationFailure::NoSolution);
        }

        // FIXME(unsafe_binders): Unsafe binders could implement `[const] Drop`
        // if their inner type implements it.
        ty::UnsafeBinder(_) => return Err(EvaluationFailure::NoSolution),

        ty::Dynamic(..) | ty::Param(_) | ty::Alias(..) | ty::Placeholder(_) | ty::Foreign(_) => {
            return Err(EvaluationFailure::NoSolution);
        }

        ty::Bound(..)
        | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
            panic!("unexpected type `{self_ty:?}`")
        }
    };

    Ok(const_conditions
        .into_iter()
        .map(|trait_ref| {
            obligation.with(
                tcx,
                ty::Binder::dummy(trait_ref)
                    .to_host_effect_clause(tcx, obligation.predicate.constness),
            )
        })
        .collect())
}

// NOTE: Keep this in sync with `extract_fn_def_from_const_callable` in the new solver.
fn evaluate_host_effect_for_fn_goal<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let tcx = selcx.tcx();
    let self_ty = obligation.predicate.self_ty();

    let (def, args) = match *self_ty.kind() {
        ty::FnDef(def, args) => (def, args),

        // We may support function pointers at some point in the future
        ty::FnPtr(..) => return Err(EvaluationFailure::NoSolution),

        // Coroutines could implement `[const] Fn`,
        // but they don't really need to right now.
        ty::CoroutineClosure(_, _) => return Err(EvaluationFailure::NoSolution),

        ty::Closure(def, args) => (def, ty::Binder::dummy(args)),

        // Everything else needs explicit impls or cannot have an impl
        _ => return Err(EvaluationFailure::NoSolution),
    };

    match tcx.constness(def) {
        // FIXME(comptime)
        hir::Constness::Const { always: true } => Err(EvaluationFailure::NoSolution),
        hir::Constness::Const { always: false } => Ok(tcx
            .const_conditions(def)
            .instantiate(tcx, args.no_bound_vars().unwrap())
            .into_iter()
            .map(|(c, span)| {
                let code = ObligationCauseCode::WhereClause(def, span);
                let cause =
                    ObligationCause::new(obligation.cause.span, obligation.cause.body_def_id, code);
                Obligation::new(
                    tcx,
                    cause,
                    obligation.param_env,
                    c.to_host_effect_clause(tcx, obligation.predicate.constness).skip_norm_wip(),
                )
            })
            .collect()),
        hir::Constness::NotConst => Err(EvaluationFailure::NoSolution),
    }
}

fn evaluate_host_effect_from_selection_candidate<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let tcx = selcx.tcx();
    selcx.infcx.commit_if_ok(|_| {
        match selcx.select(&obligation.with(tcx, obligation.predicate.trait_ref)) {
            Ok(None) => Err(EvaluationFailure::Ambiguous),
            Err(_) => Err(EvaluationFailure::NoSolution),
            Ok(Some(source)) => match source {
                ImplSource::UserDefined(impl_) => {
                    match tcx.impl_trait_header(impl_.impl_def_id).constness {
                        crate::rustc_hir::Constness::Const { always } => {
                            if always {
                                // FIXME(comptime): just bailing for now to avoid an ICE in a test.
                                return Err(EvaluationFailure::NoSolution);
                            }
                        }
                        crate::rustc_hir::Constness::NotConst => {
                            return Err(EvaluationFailure::NoSolution);
                        }
                    }

                    let mut nested = impl_.nested;
                    nested.extend(
                        tcx.const_conditions(impl_.impl_def_id)
                            .instantiate(tcx, impl_.args)
                            .into_iter()
                            .map(|(trait_ref, span)| {
                                Obligation::new(
                                    tcx,
                                    obligation.cause.clone().derived_host_cause(
                                        ty::Binder::dummy(obligation.predicate),
                                        |derived| {
                                            ObligationCauseCode::ImplDerivedHost(Box::new(
                                                ImplDerivedHostCause {
                                                    derived,
                                                    impl_def_id: impl_.impl_def_id,
                                                    span,
                                                },
                                            ))
                                        },
                                    ),
                                    obligation.param_env,
                                    trait_ref
                                        .to_host_effect_clause(tcx, obligation.predicate.constness)
                                        .skip_norm_wip(),
                                )
                            }),
                    );

                    Ok(nested)
                }
                _ => Err(EvaluationFailure::NoSolution),
            },
        }
    })
}

fn evaluate_host_effect_from_trait_alias<'tcx>(
    selcx: &mut SelectionContext<'_, 'tcx>,
    obligation: &HostEffectObligation<'tcx>,
) -> Result<ThinVec<PredicateObligation<'tcx>>, EvaluationFailure> {
    let tcx = selcx.tcx();
    let def_id = obligation.predicate.def_id();
    if !tcx.trait_is_alias(def_id) {
        return Err(EvaluationFailure::NoSolution);
    }

    Ok(tcx
        .const_conditions(def_id)
        .instantiate(tcx, obligation.predicate.trait_ref.args)
        .into_iter()
        .map(|(trait_ref, span)| {
            Obligation::new(
                tcx,
                obligation.cause.clone().derived_host_cause(
                    ty::Binder::dummy(obligation.predicate),
                    |derived| {
                        ObligationCauseCode::ImplDerivedHost(Box::new(ImplDerivedHostCause {
                            derived,
                            impl_def_id: def_id,
                            span,
                        }))
                    },
                ),
                obligation.param_env,
                trait_ref
                    .to_host_effect_clause(tcx, obligation.predicate.constness)
                    .skip_norm_wip(),
            )
        })
        .collect())
}