-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathopaques.rs
More file actions
198 lines (173 loc) · 7.14 KB
/
Copy pathopaques.rs
File metadata and controls
198 lines (173 loc) · 7.14 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
//! Defining opaque types via inference.
use std::ops::ControlFlow;
use rustc_type_ir::{
TypeSuperVisitable, TypeVisitable, TypeVisitableExt, fold_regions, inherent::IntoKind,
};
use tracing::{debug, instrument};
use crate::{
Span,
infer::InferenceContext,
next_solver::{
Const, ConstKind, DbInterner, EarlyBinder, GenericArgKind, GenericArgs, OpaqueTypeKey,
SolverDefId, Ty, TyKind, TypingMode,
infer::{opaque_types::OpaqueHiddenType, traits::ObligationCause},
},
};
impl<'db> InferenceContext<'db> {
/// This takes all the opaque type uses during HIR typeck. It first computes
/// the concrete hidden type by iterating over all defining uses.
///
/// A use during HIR typeck is defining if all non-lifetime arguments are
/// unique generic parameters and the hidden type does not reference any
/// inference variables.
///
/// It then uses these defining uses to guide inference for all other uses.
#[instrument(level = "debug", skip(self))]
pub(super) fn handle_opaque_type_uses(&mut self) {
// We clone the opaques instead of stealing them here as they are still used for
// normalization in the next generation trait solver.
let opaque_types: Vec<_> = self.table.infer_ctxt.clone_opaque_types();
self.compute_definition_site_hidden_types(opaque_types);
}
}
#[expect(unused, reason = "rustc has this")]
#[derive(Copy, Clone, Debug)]
enum UsageKind<'db> {
None,
NonDefiningUse(OpaqueTypeKey<'db>, OpaqueHiddenType<'db>),
UnconstrainedHiddenType(OpaqueHiddenType<'db>),
HasDefiningUse(OpaqueHiddenType<'db>),
}
impl<'db> UsageKind<'db> {
fn merge(&mut self, other: UsageKind<'db>) {
match (&*self, &other) {
(UsageKind::HasDefiningUse(_), _) | (_, UsageKind::None) => unreachable!(),
(UsageKind::None, _) => *self = other,
// When mergining non-defining uses, prefer earlier ones. This means
// the error happens as early as possible.
(
UsageKind::NonDefiningUse(..) | UsageKind::UnconstrainedHiddenType(..),
UsageKind::NonDefiningUse(..),
) => {}
// When merging unconstrained hidden types, we prefer later ones. This is
// used as in most cases, the defining use is the final return statement
// of our function, and other uses with defining arguments are likely not
// intended to be defining.
(
UsageKind::NonDefiningUse(..) | UsageKind::UnconstrainedHiddenType(..),
UsageKind::UnconstrainedHiddenType(..) | UsageKind::HasDefiningUse(_),
) => *self = other,
}
}
}
// rejects hidden types with foreign params
struct ForeignParamChecker<'db> {
args: GenericArgs<'db>,
}
impl<'db> rustc_type_ir::TypeVisitor<DbInterner<'db>> for ForeignParamChecker<'db> {
type Result = ControlFlow<()>;
fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
if let TyKind::Param(param) = ty.kind()
&& !matches!(
self.args.get(param.index as usize).map(|arg| arg.kind()),
Some(GenericArgKind::Type(_))
)
{
return ControlFlow::Break(());
}
ty.super_visit_with(self)
}
fn visit_const(&mut self, ct: Const<'db>) -> Self::Result {
if let ConstKind::Param(param) = ct.kind()
&& !matches!(
self.args.get(param.index as usize).map(|arg| arg.kind()),
Some(GenericArgKind::Const(_))
)
{
return ControlFlow::Break(());
}
ct.super_visit_with(self)
}
}
impl<'db> InferenceContext<'db> {
fn compute_definition_site_hidden_types(
&mut self,
mut opaque_types: Vec<(OpaqueTypeKey<'db>, OpaqueHiddenType<'db>)>,
) {
for entry in opaque_types.iter_mut() {
*entry = self.resolve_vars_if_possible(*entry);
}
debug!(?opaque_types);
let interner = self.interner();
let TypingMode::Analysis { defining_opaque_types_and_generators } =
self.table.infer_ctxt.typing_mode_raw()
else {
unreachable!();
};
for def_id in defining_opaque_types_and_generators {
let def_id = match def_id {
SolverDefId::InternedOpaqueTyId(it) => it,
_ => continue,
};
// We do actually need to check this the second pass (we can't just
// store this), because we can go from `UnconstrainedHiddenType` to
// `HasDefiningUse` (because of fallback)
let mut usage_kind = UsageKind::None;
for &(opaque_type_key, hidden_type) in &opaque_types {
if opaque_type_key.def_id != def_id.into() {
continue;
}
usage_kind.merge(self.consider_opaque_type_use(opaque_type_key, hidden_type));
if let UsageKind::HasDefiningUse(..) = usage_kind {
break;
}
}
if let UsageKind::HasDefiningUse(ty) = usage_kind {
for &(opaque_type_key, hidden_type) in &opaque_types {
if opaque_type_key.def_id != def_id.into() {
continue;
}
let expected = EarlyBinder::bind(ty.ty)
.instantiate(interner, opaque_type_key.args)
.skip_norm_wip();
_ = self.demand_eqtype_fixme_no_diag(expected, hidden_type.ty);
}
self.result.type_of_opaque.insert(def_id, ty.ty.store());
continue;
}
self.result.type_of_opaque.insert(def_id, self.types.types.error.store());
}
}
#[tracing::instrument(skip(self), ret)]
fn consider_opaque_type_use(
&self,
opaque_type_key: OpaqueTypeKey<'db>,
hidden_type: OpaqueHiddenType<'db>,
) -> UsageKind<'db> {
// We ignore uses of the opaque if they have any inference variables
// as this can frequently happen with recursive calls.
//
// See `tests/ui/traits/next-solver/opaques/universal-args-non-defining.rs`.
if hidden_type.ty.has_non_region_infer() {
return UsageKind::UnconstrainedHiddenType(hidden_type);
}
// FIXME: This should not use a dummy span.
let cause = ObligationCause::new(Span::Dummy);
let at = self.table.infer_ctxt.at(&cause, self.table.param_env);
let hidden_type = match at.deeply_normalize(hidden_type) {
Ok(hidden_type) => hidden_type,
Err(_errors) => OpaqueHiddenType { ty: self.types.types.error },
};
let hidden_type =
fold_regions(self.interner(), hidden_type, |_, _| self.types.regions.erased);
// skip uses with foreign params
if hidden_type
.ty
.visit_with(&mut ForeignParamChecker { args: opaque_type_key.args })
.is_break()
{
return UsageKind::NonDefiningUse(opaque_type_key, hidden_type);
}
UsageKind::HasDefiningUse(hidden_type)
}
}