-
-
Notifications
You must be signed in to change notification settings - Fork 15.5k
Expand file tree
/
Copy pathdelegate.rs
More file actions
390 lines (353 loc) · 14.9 KB
/
Copy pathdelegate.rs
File metadata and controls
390 lines (353 loc) · 14.9 KB
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
use std::collections::hash_map::Entry;
use std::ops::Deref;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::LangItem;
use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId, LocalModDefId};
use rustc_infer::infer::canonical::query_response::make_query_region_constraints;
use rustc_infer::infer::canonical::{
Canonical, CanonicalExt as _, CanonicalQueryInput, CanonicalVarKind, CanonicalVarValues,
};
use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt};
use rustc_infer::traits::solve::{FetchEligibleAssocItemResponse, Goal};
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::solve::Certainty;
use rustc_middle::ty::{
self, MayBeErased, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeVisitableExt, TypingMode,
};
use rustc_span::{DUMMY_SP, Span};
use crate::traits::{EvaluateConstErr, ObligationCause, sizedness_fast_path, specialization_graph};
#[repr(transparent)]
pub struct SolverDelegate<'tcx>(InferCtxt<'tcx>);
impl<'a, 'tcx> From<&'a InferCtxt<'tcx>> for &'a SolverDelegate<'tcx> {
fn from(infcx: &'a InferCtxt<'tcx>) -> Self {
// SAFETY: `repr(transparent)`
unsafe { std::mem::transmute(infcx) }
}
}
impl<'tcx> Deref for SolverDelegate<'tcx> {
type Target = InferCtxt<'tcx>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'tcx> SolverDelegate<'tcx> {
fn known_no_opaque_types_in_storage(&self) -> bool {
self.inner.borrow_mut().opaque_types().is_empty()
// in erased mode, observing that opaques are empty aren't enough to give a result
// here, so let's try the slow path instead.
&& !self.typing_mode_raw().is_erased_not_coherence()
}
}
impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<'tcx> {
type Infcx = InferCtxt<'tcx>;
type Interner = TyCtxt<'tcx>;
fn cx(&self) -> TyCtxt<'tcx> {
self.0.tcx
}
fn build_with_canonical<V>(
interner: TyCtxt<'tcx>,
canonical: &CanonicalQueryInput<'tcx, V>,
) -> (Self, V, CanonicalVarValues<'tcx>)
where
V: TypeFoldable<TyCtxt<'tcx>>,
{
let (infcx, value, vars) = interner
.infer_ctxt()
.with_next_trait_solver(true)
.build_with_canonical(DUMMY_SP, canonical);
(SolverDelegate(infcx), value, vars)
}
fn compute_goal_fast_path(
&self,
goal: Goal<'tcx, ty::Predicate<'tcx>>,
span: Span,
) -> Option<Certainty> {
// FIXME(-Zassumptions-on-binders): actually handle fast path
if self.tcx.assumptions_on_binders() {
return None;
}
let pred = goal.predicate.kind();
match pred.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
let trait_pred = pred.rebind(trait_pred);
if self.shallow_resolve(trait_pred.self_ty().skip_binder()).is_ty_var()
// We don't do this fast path when opaques are defined since we may
// eventually use opaques to incompletely guide inference via ty var
// self types.
// FIXME: Properly consider opaques here.
&& self.known_no_opaque_types_in_storage()
{
Some(Certainty::AMBIGUOUS)
} else if trait_pred.polarity() == ty::PredicatePolarity::Positive {
match self.0.tcx.as_lang_item(trait_pred.def_id()) {
Some(LangItem::Sized) | Some(LangItem::MetaSized) => {
let predicate = self.resolve_vars_if_possible(goal.predicate);
if sizedness_fast_path(self.tcx, predicate, goal.param_env) {
return Some(Certainty::Yes);
} else {
None
}
}
Some(LangItem::Copy | LangItem::Clone) => {
let self_ty =
self.resolve_vars_if_possible(trait_pred.self_ty().skip_binder());
// Unlike `Sized` traits, which always prefer the built-in impl,
// `Copy`/`Clone` may be shadowed by a param-env candidate which
// could force a lifetime error or guide inference. While that's
// not generally desirable, it is observable, so for now let's
// ignore this fast path for types that have regions or infer.
if !self_ty
.has_type_flags(TypeFlags::HAS_FREE_REGIONS | TypeFlags::HAS_INFER)
&& self_ty.is_trivially_pure_clone_copy()
{
return Some(Certainty::Yes);
} else {
None
}
}
_ => None,
}
} else {
None
}
}
ty::PredicateKind::DynCompatible(def_id) if self.0.tcx.is_dyn_compatible(def_id) => {
Some(Certainty::Yes)
}
ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(outlives)) => {
if outlives.has_escaping_bound_vars() {
return None;
}
self.0.sub_regions(
SubregionOrigin::RelateRegionParamBound(span, None),
outlives.1,
outlives.0,
ty::VisibleForLeakCheck::Yes,
);
Some(Certainty::Yes)
}
ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(outlives)) => {
if outlives.has_escaping_bound_vars() {
return None;
}
self.0.register_type_outlives_constraint(
outlives.0,
outlives.1,
&ObligationCause::dummy_with_span(span),
);
Some(Certainty::Yes)
}
ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, .. })
| ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
if a.has_escaping_bound_vars() || b.has_escaping_bound_vars() {
return None;
}
match (self.shallow_resolve(a).kind(), self.shallow_resolve(b).kind()) {
(&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
self.sub_unify_ty_vids_raw(a_vid, b_vid);
Some(Certainty::AMBIGUOUS)
}
_ => None,
}
}
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) => {
if ct.has_escaping_bound_vars() {
return None;
}
if self.shallow_resolve_const(ct).is_ct_infer() {
Some(Certainty::AMBIGUOUS)
} else {
None
}
}
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
if arg.has_escaping_bound_vars() {
return None;
}
let arg = self.shallow_resolve_term(arg);
if arg.is_trivially_wf(self.tcx) {
Some(Certainty::Yes)
} else if arg.is_infer() {
Some(Certainty::AMBIGUOUS)
} else {
None
}
}
_ => None,
}
}
fn fresh_var_for_kind_with_span(
&self,
arg: ty::GenericArg<'tcx>,
span: Span,
) -> ty::GenericArg<'tcx> {
match arg.kind() {
ty::GenericArgKind::Lifetime(_) => {
self.next_region_var(RegionVariableOrigin::Misc(span)).into()
}
ty::GenericArgKind::Type(_) => self.next_ty_var(span).into(),
ty::GenericArgKind::Const(_) => self.next_const_var(span).into(),
}
}
fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution> {
self.0.leak_check(max_input_universe, None).map_err(|_| NoSolution)
}
fn evaluate_const(
&self,
param_env: ty::ParamEnv<'tcx>,
uv: ty::UnevaluatedConst<'tcx>,
) -> Option<ty::Const<'tcx>> {
let ct = ty::Const::new_unevaluated(self.tcx, uv);
match crate::traits::try_evaluate_const(&self.0, ct, param_env) {
Ok(ct) => Some(ct),
Err(EvaluateConstErr::EvaluationFailure(e)) => Some(ty::Const::new_error(self.tcx, e)),
Err(
EvaluateConstErr::InvalidConstParamTy(_) | EvaluateConstErr::HasGenericsOrInfers,
) => None,
}
}
fn well_formed_goals(
&self,
param_env: ty::ParamEnv<'tcx>,
term: ty::Term<'tcx>,
) -> Option<Vec<Goal<'tcx, ty::Predicate<'tcx>>>> {
crate::traits::wf::unnormalized_obligations(
&self.0,
param_env,
term,
DUMMY_SP,
CRATE_DEF_ID,
)
.map(|obligations| obligations.into_iter().map(|obligation| obligation.as_goal()).collect())
}
fn make_deduplicated_region_constraints(
&self,
) -> Vec<(ty::RegionConstraint<'tcx>, ty::VisibleForLeakCheck)> {
// Cannot use `take_registered_region_obligations` as we may compute the response
// inside of a `probe` whenever we have multiple choices inside of the solver.
let region_obligations = self.0.inner.borrow().region_obligations().to_owned();
let region_assumptions = self.0.inner.borrow().region_assumptions().to_owned();
let region_constraints = self.0.with_region_constraints(|region_constraints| {
make_query_region_constraints(
region_obligations,
region_constraints,
region_assumptions,
)
});
let mut seen = FxHashMap::default();
let mut constraints = vec![];
for (outlives, _, vis) in region_constraints.constraints {
match seen.entry(outlives) {
Entry::Occupied(occupied) => {
let idx = occupied.get();
let (_, prev_vis): &mut (_, ty::VisibleForLeakCheck) =
constraints.get_mut(*idx).unwrap();
*prev_vis = (*prev_vis).or(vis);
}
Entry::Vacant(vacant) => {
vacant.insert(constraints.len());
constraints.push((outlives, vis));
}
}
}
constraints
}
fn instantiate_canonical<V>(
&self,
canonical: Canonical<'tcx, V>,
values: CanonicalVarValues<'tcx>,
) -> V
where
V: TypeFoldable<TyCtxt<'tcx>>,
{
canonical.instantiate(self.tcx, &values)
}
fn instantiate_canonical_var(
&self,
kind: CanonicalVarKind<'tcx>,
span: Span,
var_values: &[ty::GenericArg<'tcx>],
universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex,
) -> ty::GenericArg<'tcx> {
self.0.instantiate_canonical_var(span, kind, var_values, universe_map)
}
fn add_item_bounds_for_hidden_type(
&self,
def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
param_env: ty::ParamEnv<'tcx>,
hidden_ty: Ty<'tcx>,
goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
) {
self.0.add_item_bounds_for_hidden_type(def_id, args, param_env, hidden_ty, goals);
}
fn fetch_eligible_assoc_item(
&self,
goal_trait_ref: ty::TraitRef<'tcx>,
trait_assoc_def_id: DefId,
impl_def_id: DefId,
) -> FetchEligibleAssocItemResponse<'tcx> {
let node_item =
match specialization_graph::assoc_def(self.tcx, impl_def_id, trait_assoc_def_id) {
Ok(i) => i,
Err(guar) => return FetchEligibleAssocItemResponse::Err(guar),
};
let typing_mode = self.typing_mode_raw();
let eligible = if node_item.is_final() {
// Non-specializable items are always projectable.
true
} else {
// Only reveal a specializable default if we're past type-checking
// and the obligation is monomorphic, otherwise passes such as
// transmute checking and polymorphic MIR optimizations could
// get a result which isn't correct for all monomorphizations.
match typing_mode {
TypingMode::Coherence
| TypingMode::Analysis { .. }
| TypingMode::Borrowck { .. }
| TypingMode::PostBorrowckAnalysis { .. } => false,
TypingMode::PostAnalysis | TypingMode::Codegen => {
let poly_trait_ref = self.resolve_vars_if_possible(goal_trait_ref);
!poly_trait_ref.still_further_specializable()
}
TypingMode::ErasedNotCoherence(MayBeErased) => {
return FetchEligibleAssocItemResponse::NotFoundBecauseErased;
}
}
};
// FIXME: Check for defaultness here may cause diagnostics problems.
if eligible {
FetchEligibleAssocItemResponse::Found(node_item.item.def_id)
} else {
// We know it's not erased since then we'd have returned in the match above,
// or node_item.final() was true and eligible is always true.
FetchEligibleAssocItemResponse::NotFound(typing_mode.assert_not_erased())
}
}
// FIXME: This actually should destructure the `Result` we get from transmutability and
// register candidates. We probably need to register >1 since we may have an OR of ANDs.
fn is_transmutable(
&self,
src: Ty<'tcx>,
dst: Ty<'tcx>,
assume: ty::Const<'tcx>,
body_id: Option<LocalDefId>,
) -> Result<Certainty, NoSolution> {
// Erase regions because we compute layouts in `rustc_transmute`,
// which will ICE for region vars.
let (dst, src) = self.tcx.erase_and_anonymize_regions((dst, src));
let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
return Err(NoSolution);
};
let caller_module = body_id
.map(|body_id| self.tcx.parent_module_from_def_id(body_id))
.unwrap_or(LocalModDefId::CRATE_DEF_ID);
// FIXME(transmutability): This really should be returning nested goals for `Answer::If*`
match rustc_transmute::TransmuteTypeEnv::new(self.0.tcx, caller_module)
.is_transmutable(src, dst, assume)
{
rustc_transmute::Answer::Yes => Ok(Certainty::Yes),
rustc_transmute::Answer::No(_) | rustc_transmute::Answer::If(_) => Err(NoSolution),
}
}
}