Skip to content

Commit 08eb3ff

Browse files
committed
inspect: strongly typed CandidateKind
1 parent 55a7f9f commit 08eb3ff

File tree

10 files changed

+148
-56
lines changed

10 files changed

+148
-56
lines changed

compiler/rustc_middle/src/traits/solve.rs

+63
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ use crate::ty::{
99
self, FallibleTypeFolder, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeVisitable,
1010
TypeVisitor,
1111
};
12+
use rustc_span::def_id::DefId;
13+
14+
use super::BuiltinImplSource;
1215

1316
mod cache;
1417
pub mod inspect;
@@ -235,3 +238,63 @@ pub enum IsNormalizesToHack {
235238
Yes,
236239
No,
237240
}
241+
242+
/// Possible ways the given goal can be proven.
243+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244+
pub enum CandidateSource {
245+
/// A user written impl.
246+
///
247+
/// ## Examples
248+
///
249+
/// ```rust
250+
/// fn main() {
251+
/// let x: Vec<u32> = Vec::new();
252+
/// // This uses the impl from the standard library to prove `Vec<T>: Clone`.
253+
/// let y = x.clone();
254+
/// }
255+
/// ```
256+
Impl(DefId),
257+
/// A builtin impl generated by the compiler. When adding a new special
258+
/// trait, try to use actual impls whenever possible. Builtin impls should
259+
/// only be used in cases where the impl cannot be manually be written.
260+
///
261+
/// Notable examples are auto traits, `Sized`, and `DiscriminantKind`.
262+
/// For a list of all traits with builtin impls, check out the
263+
/// [`EvalCtxt::assemble_builtin_impl_candidates`] method. Not
264+
BuiltinImpl(BuiltinImplSource),
265+
/// An assumption from the environment.
266+
///
267+
/// More precisely we've used the `n-th` assumption in the `param_env`.
268+
///
269+
/// ## Examples
270+
///
271+
/// ```rust
272+
/// fn is_clone<T: Clone>(x: T) -> (T, T) {
273+
/// // This uses the assumption `T: Clone` from the `where`-bounds
274+
/// // to prove `T: Clone`.
275+
/// (x.clone(), x)
276+
/// }
277+
/// ```
278+
ParamEnv(usize),
279+
/// If the self type is an alias type, e.g. an opaque type or a projection,
280+
/// we know the bounds on that alias to hold even without knowing its concrete
281+
/// underlying type.
282+
///
283+
/// More precisely this candidate is using the `n-th` bound in the `item_bounds` of
284+
/// the self type.
285+
///
286+
/// ## Examples
287+
///
288+
/// ```rust
289+
/// trait Trait {
290+
/// type Assoc: Clone;
291+
/// }
292+
///
293+
/// fn foo<T: Trait>(x: <T as Trait>::Assoc) {
294+
/// // We prove `<T as Trait>::Assoc` by looking at the bounds on `Assoc` in
295+
/// // in the trait definition.
296+
/// let _y = x.clone();
297+
/// }
298+
/// ```
299+
AliasBound,
300+
}
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
11
use super::{
2-
CanonicalInput, Certainty, Goal, IsNormalizesToHack, NoSolution, QueryInput, QueryResult,
2+
CandidateSource, CanonicalInput, Certainty, Goal, IsNormalizesToHack, NoSolution, QueryInput,
3+
QueryResult,
34
};
45
use crate::ty;
56
use format::ProofTreeFormatter;
67
use std::fmt::{Debug, Write};
78

89
mod format;
910

10-
#[derive(Eq, PartialEq, Debug, Hash, HashStable)]
11+
#[derive(Debug, Eq, PartialEq)]
1112
pub enum CacheHit {
1213
Provisional,
1314
Global,
1415
}
1516

16-
#[derive(Eq, PartialEq, Hash, HashStable)]
17+
#[derive(Eq, PartialEq)]
1718
pub struct GoalEvaluation<'tcx> {
1819
pub uncanonicalized_goal: Goal<'tcx, ty::Predicate<'tcx>>,
1920
pub is_normalizes_to_hack: IsNormalizesToHack,
2021
pub evaluation: CanonicalGoalEvaluation<'tcx>,
2122
pub returned_goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
2223
}
2324

24-
#[derive(Eq, PartialEq, Hash, HashStable)]
25+
#[derive(Eq, PartialEq)]
2526
pub struct CanonicalGoalEvaluation<'tcx> {
2627
pub goal: CanonicalInput<'tcx>,
2728
pub kind: GoalEvaluationKind<'tcx>,
2829
pub result: QueryResult<'tcx>,
2930
}
3031

31-
#[derive(Eq, PartialEq, Hash, HashStable)]
32+
#[derive(Eq, PartialEq)]
3233
pub enum GoalEvaluationKind<'tcx> {
3334
CacheHit(CacheHit),
3435
Uncached { revisions: Vec<GoalEvaluationStep<'tcx>> },
@@ -39,13 +40,13 @@ impl Debug for GoalEvaluation<'_> {
3940
}
4041
}
4142

42-
#[derive(Eq, PartialEq, Hash, HashStable)]
43+
#[derive(Eq, PartialEq)]
4344
pub struct AddedGoalsEvaluation<'tcx> {
4445
pub evaluations: Vec<Vec<GoalEvaluation<'tcx>>>,
4546
pub result: Result<Certainty, NoSolution>,
4647
}
4748

48-
#[derive(Eq, PartialEq, Hash, HashStable)]
49+
#[derive(Eq, PartialEq)]
4950
pub struct GoalEvaluationStep<'tcx> {
5051
pub instantiated_goal: QueryInput<'tcx, ty::Predicate<'tcx>>,
5152

@@ -55,24 +56,28 @@ pub struct GoalEvaluationStep<'tcx> {
5556
pub result: QueryResult<'tcx>,
5657
}
5758

58-
#[derive(Eq, PartialEq, Hash, HashStable)]
59+
#[derive(Eq, PartialEq)]
5960
pub struct GoalCandidate<'tcx> {
6061
pub added_goals_evaluations: Vec<AddedGoalsEvaluation<'tcx>>,
6162
pub candidates: Vec<GoalCandidate<'tcx>>,
62-
pub kind: CandidateKind<'tcx>,
63+
pub kind: ProbeKind<'tcx>,
6364
}
6465

65-
#[derive(Eq, PartialEq, Debug, Hash, HashStable)]
66-
pub enum CandidateKind<'tcx> {
66+
#[derive(Debug, PartialEq, Eq)]
67+
pub enum ProbeKind<'tcx> {
6768
/// Probe entered when normalizing the self ty during candidate assembly
6869
NormalizedSelfTyAssembly,
69-
/// A normal candidate for proving a goal
70-
Candidate { name: String, result: QueryResult<'tcx> },
70+
/// Some candidate to prove the current goal.
71+
///
72+
/// FIXME: Remove this in favor of always using more strongly typed variants.
73+
MiscCandidate { name: &'static str, result: QueryResult<'tcx> },
74+
/// A candidate for proving a trait or alias-relate goal.
75+
TraitCandidate { source: CandidateSource, result: QueryResult<'tcx> },
7176
/// Used in the probe that wraps normalizing the non-self type for the unsize
7277
/// trait, which is also structurally matched on.
7378
UnsizeAssembly,
7479
/// During upcasting from some source object to target object type, used to
7580
/// do a probe to find out what projection type(s) may be used to prove that
7681
/// the source type upholds all of the target type's object bounds.
77-
UpcastProbe,
82+
UpcastProjectionCompatibility,
7883
}

compiler/rustc_middle/src/traits/solve/inspect/format.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -102,18 +102,21 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> {
102102

103103
pub(super) fn format_candidate(&mut self, candidate: &GoalCandidate<'_>) -> std::fmt::Result {
104104
match &candidate.kind {
105-
CandidateKind::NormalizedSelfTyAssembly => {
105+
ProbeKind::NormalizedSelfTyAssembly => {
106106
writeln!(self.f, "NORMALIZING SELF TY FOR ASSEMBLY:")
107107
}
108-
CandidateKind::UnsizeAssembly => {
108+
ProbeKind::UnsizeAssembly => {
109109
writeln!(self.f, "ASSEMBLING CANDIDATES FOR UNSIZING:")
110110
}
111-
CandidateKind::UpcastProbe => {
111+
ProbeKind::UpcastProjectionCompatibility => {
112112
writeln!(self.f, "PROBING FOR PROJECTION COMPATIBILITY FOR UPCASTING:")
113113
}
114-
CandidateKind::Candidate { name, result } => {
114+
ProbeKind::MiscCandidate { name, result } => {
115115
writeln!(self.f, "CANDIDATE {name}: {result:?}")
116116
}
117+
ProbeKind::TraitCandidate { source, result } => {
118+
writeln!(self.f, "CANDIDATE {source:?}: {result:?}")
119+
}
117120
}?;
118121

119122
self.nested(|this| {

compiler/rustc_trait_selection/src/solve/alias_relate.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
125125
direction: ty::AliasRelationDirection,
126126
invert: Invert,
127127
) -> QueryResult<'tcx> {
128-
self.probe_candidate("normalizes-to").enter(|ecx| {
128+
self.probe_misc_candidate("normalizes-to").enter(|ecx| {
129129
ecx.normalizes_to_inner(param_env, alias, other, direction, invert)?;
130130
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
131131
})
@@ -175,7 +175,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
175175
alias_rhs: ty::AliasTy<'tcx>,
176176
direction: ty::AliasRelationDirection,
177177
) -> QueryResult<'tcx> {
178-
self.probe_candidate("args relate").enter(|ecx| {
178+
self.probe_misc_candidate("args relate").enter(|ecx| {
179179
match direction {
180180
ty::AliasRelationDirection::Equate => {
181181
ecx.eq(param_env, alias_lhs, alias_rhs)?;
@@ -196,7 +196,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
196196
rhs: ty::Term<'tcx>,
197197
direction: ty::AliasRelationDirection,
198198
) -> QueryResult<'tcx> {
199-
self.probe_candidate("bidir normalizes-to").enter(|ecx| {
199+
self.probe_misc_candidate("bidir normalizes-to").enter(|ecx| {
200200
ecx.normalizes_to_inner(
201201
param_env,
202202
lhs.to_alias_ty(ecx.tcx()).unwrap(),

compiler/rustc_trait_selection/src/solve/assembly/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::traits::coherence;
55
use rustc_hir::def_id::DefId;
66
use rustc_infer::traits::query::NoSolution;
77
use rustc_infer::traits::Reveal;
8-
use rustc_middle::traits::solve::inspect::CandidateKind;
8+
use rustc_middle::traits::solve::inspect::ProbeKind;
99
use rustc_middle::traits::solve::{CanonicalResponse, Certainty, Goal, QueryResult};
1010
use rustc_middle::traits::BuiltinImplSource;
1111
use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams};
@@ -393,7 +393,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
393393
let tcx = self.tcx();
394394
let &ty::Alias(_, projection_ty) = goal.predicate.self_ty().kind() else { return };
395395

396-
candidates.extend(self.probe(|_| CandidateKind::NormalizedSelfTyAssembly).enter(|ecx| {
396+
candidates.extend(self.probe(|_| ProbeKind::NormalizedSelfTyAssembly).enter(|ecx| {
397397
if num_steps < ecx.local_overflow_limit() {
398398
let normalized_ty = ecx.next_ty_infer();
399399
let normalizes_to_goal = goal.with(
@@ -882,7 +882,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
882882
SolverMode::Coherence => {}
883883
};
884884

885-
let result = self.probe_candidate("coherence unknowable").enter(|ecx| {
885+
let result = self.probe_misc_candidate("coherence unknowable").enter(|ecx| {
886886
let trait_ref = goal.predicate.trait_ref(tcx);
887887

888888
#[derive(Debug)]

compiler/rustc_trait_selection/src/solve/eval_ctxt.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
920920
if candidate_key.def_id != key.def_id {
921921
continue;
922922
}
923-
values.extend(self.probe_candidate("opaque type storage").enter(|ecx| {
923+
values.extend(self.probe_misc_candidate("opaque type storage").enter(|ecx| {
924924
for (a, b) in std::iter::zip(candidate_key.args, key.args) {
925925
ecx.eq(param_env, a, b)?;
926926
}

compiler/rustc_trait_selection/src/solve/eval_ctxt/probe.rs

+29-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use super::EvalCtxt;
2-
use rustc_middle::traits::solve::{inspect, QueryResult};
2+
use rustc_middle::traits::solve::{inspect, CandidateSource, QueryResult};
33
use std::marker::PhantomData;
44

55
pub(in crate::solve) struct ProbeCtxt<'me, 'a, 'tcx, F, T> {
@@ -10,7 +10,7 @@ pub(in crate::solve) struct ProbeCtxt<'me, 'a, 'tcx, F, T> {
1010

1111
impl<'tcx, F, T> ProbeCtxt<'_, '_, 'tcx, F, T>
1212
where
13-
F: FnOnce(&T) -> inspect::CandidateKind<'tcx>,
13+
F: FnOnce(&T) -> inspect::ProbeKind<'tcx>,
1414
{
1515
pub(in crate::solve) fn enter(self, f: impl FnOnce(&mut EvalCtxt<'_, 'tcx>) -> T) -> T {
1616
let ProbeCtxt { ecx: outer_ecx, probe_kind, _result } = self;
@@ -28,8 +28,8 @@ where
2828
};
2929
let r = nested_ecx.infcx.probe(|_| f(&mut nested_ecx));
3030
if !outer_ecx.inspect.is_noop() {
31-
let cand_kind = probe_kind(&r);
32-
nested_ecx.inspect.candidate_kind(cand_kind);
31+
let probe_kind = probe_kind(&r);
32+
nested_ecx.inspect.probe_kind(probe_kind);
3333
outer_ecx.inspect.goal_candidate(nested_ecx.inspect);
3434
}
3535
r
@@ -41,25 +41,45 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
4141
/// as expensive as necessary to output the desired information.
4242
pub(in crate::solve) fn probe<F, T>(&mut self, probe_kind: F) -> ProbeCtxt<'_, 'a, 'tcx, F, T>
4343
where
44-
F: FnOnce(&T) -> inspect::CandidateKind<'tcx>,
44+
F: FnOnce(&T) -> inspect::ProbeKind<'tcx>,
4545
{
4646
ProbeCtxt { ecx: self, probe_kind, _result: PhantomData }
4747
}
4848

49-
pub(in crate::solve) fn probe_candidate(
49+
pub(in crate::solve) fn probe_misc_candidate(
5050
&mut self,
5151
name: &'static str,
5252
) -> ProbeCtxt<
5353
'_,
5454
'a,
5555
'tcx,
56-
impl FnOnce(&QueryResult<'tcx>) -> inspect::CandidateKind<'tcx>,
56+
impl FnOnce(&QueryResult<'tcx>) -> inspect::ProbeKind<'tcx>,
5757
QueryResult<'tcx>,
5858
> {
5959
ProbeCtxt {
6060
ecx: self,
61-
probe_kind: move |result: &QueryResult<'tcx>| inspect::CandidateKind::Candidate {
62-
name: name.to_string(),
61+
probe_kind: move |result: &QueryResult<'tcx>| inspect::ProbeKind::MiscCandidate {
62+
name,
63+
result: *result,
64+
},
65+
_result: PhantomData,
66+
}
67+
}
68+
69+
pub(in crate::solve) fn probe_trait_candidate(
70+
&mut self,
71+
source: CandidateSource,
72+
) -> ProbeCtxt<
73+
'_,
74+
'a,
75+
'tcx,
76+
impl FnOnce(&QueryResult<'tcx>) -> inspect::ProbeKind<'tcx>,
77+
QueryResult<'tcx>,
78+
> {
79+
ProbeCtxt {
80+
ecx: self,
81+
probe_kind: move |result: &QueryResult<'tcx>| inspect::ProbeKind::TraitCandidate {
82+
source,
6383
result: *result,
6484
},
6585
_result: PhantomData,

0 commit comments

Comments
 (0)