-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathty.rs
515 lines (456 loc) · 18.5 KB
/
ty.rs
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
use rustc_data_structures::svh::Svh;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
use rustc_infer::traits::util;
use rustc_middle::hir::map as hir_map;
use rustc_middle::ty::subst::{InternalSubsts, Subst};
use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc_session::CrateDisambiguator;
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use rustc_trait_selection::traits;
fn sized_constraint_for_ty<'tcx>(
tcx: TyCtxt<'tcx>,
adtdef: &ty::AdtDef,
ty: Ty<'tcx>,
) -> Vec<Ty<'tcx>> {
use ty::TyKind::*;
let result = match ty.kind {
Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..)
| FnPtr(_) | Array(..) | Closure(..) | Generator(..) | Never => vec![],
Str | Dynamic(..) | Slice(_) | Foreign(..) | Error(_) | GeneratorWitness(..) => {
// these are never sized - return the target type
vec![ty]
}
Tuple(ref tys) => match tys.last() {
None => vec![],
Some(ty) => sized_constraint_for_ty(tcx, adtdef, ty.expect_ty()),
},
Adt(adt, substs) => {
// recursive case
let adt_tys = adt.sized_constraint(tcx);
debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys);
adt_tys
.iter()
.map(|ty| ty.subst(tcx, substs))
.flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty))
.collect()
}
Projection(..) | Opaque(..) => {
// must calculate explicitly.
// FIXME: consider special-casing always-Sized projections
vec![ty]
}
Param(..) => {
// perf hack: if there is a `T: Sized` bound, then
// we know that `T` is Sized and do not need to check
// it on the impl.
let sized_trait = match tcx.lang_items().sized_trait() {
Some(x) => x,
_ => return vec![ty],
};
let sized_predicate = ty::Binder::dummy(ty::TraitRef {
def_id: sized_trait,
substs: tcx.mk_substs_trait(ty, &[]),
})
.without_const()
.to_predicate(tcx);
let predicates = tcx.predicates_of(adtdef.did).predicates;
if predicates.iter().any(|(p, _)| *p == sized_predicate) { vec![] } else { vec![ty] }
}
Placeholder(..) | Bound(..) | Infer(..) => {
bug!("unexpected type `{:?}` in sized_constraint_for_ty", ty)
}
};
debug!("sized_constraint_for_ty({:?}) = {:?}", ty, result);
result
}
fn associated_item_from_trait_item_ref(
tcx: TyCtxt<'_>,
parent_def_id: LocalDefId,
parent_vis: &hir::Visibility<'_>,
trait_item_ref: &hir::TraitItemRef,
) -> ty::AssocItem {
let def_id = tcx.hir().local_def_id(trait_item_ref.id.hir_id);
let (kind, has_self) = match trait_item_ref.kind {
hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
};
ty::AssocItem {
ident: trait_item_ref.ident,
kind,
// Visibility of trait items is inherited from their traits.
vis: ty::Visibility::from_hir(parent_vis, trait_item_ref.id.hir_id, tcx),
defaultness: trait_item_ref.defaultness,
def_id: def_id.to_def_id(),
container: ty::TraitContainer(parent_def_id.to_def_id()),
fn_has_self_parameter: has_self,
}
}
fn associated_item_from_impl_item_ref(
tcx: TyCtxt<'_>,
parent_def_id: LocalDefId,
impl_item_ref: &hir::ImplItemRef<'_>,
) -> ty::AssocItem {
let def_id = tcx.hir().local_def_id(impl_item_ref.id.hir_id);
let (kind, has_self) = match impl_item_ref.kind {
hir::AssocItemKind::Const => (ty::AssocKind::Const, false),
hir::AssocItemKind::Fn { has_self } => (ty::AssocKind::Fn, has_self),
hir::AssocItemKind::Type => (ty::AssocKind::Type, false),
};
ty::AssocItem {
ident: impl_item_ref.ident,
kind,
// Visibility of trait impl items doesn't matter.
vis: ty::Visibility::from_hir(&impl_item_ref.vis, impl_item_ref.id.hir_id, tcx),
defaultness: impl_item_ref.defaultness,
def_id: def_id.to_def_id(),
container: ty::ImplContainer(parent_def_id.to_def_id()),
fn_has_self_parameter: has_self,
}
}
fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
let id = tcx.hir().as_local_hir_id(def_id.expect_local());
let parent_id = tcx.hir().get_parent_item(id);
let parent_def_id = tcx.hir().local_def_id(parent_id);
let parent_item = tcx.hir().expect_item(parent_id);
match parent_item.kind {
hir::ItemKind::Impl { ref items, .. } => {
if let Some(impl_item_ref) = items.iter().find(|i| i.id.hir_id == id) {
let assoc_item =
associated_item_from_impl_item_ref(tcx, parent_def_id, impl_item_ref);
debug_assert_eq!(assoc_item.def_id, def_id);
return assoc_item;
}
}
hir::ItemKind::Trait(.., ref trait_item_refs) => {
if let Some(trait_item_ref) = trait_item_refs.iter().find(|i| i.id.hir_id == id) {
let assoc_item = associated_item_from_trait_item_ref(
tcx,
parent_def_id,
&parent_item.vis,
trait_item_ref,
);
debug_assert_eq!(assoc_item.def_id, def_id);
return assoc_item;
}
}
_ => {}
}
span_bug!(
parent_item.span,
"unexpected parent of trait or impl item or item not found: {:?}",
parent_item.kind
)
}
fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
let item = tcx.hir().expect_item(hir_id);
if let hir::ItemKind::Impl { defaultness, .. } = item.kind {
defaultness
} else {
bug!("`impl_defaultness` called on {:?}", item);
}
}
/// Calculates the `Sized` constraint.
///
/// In fact, there are only a few options for the types in the constraint:
/// - an obviously-unsized type
/// - a type parameter or projection whose Sizedness can't be known
/// - a tuple of type parameters or projections, if there are multiple
/// such.
/// - a Error, if a type contained itself. The representability
/// check should catch this case.
fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstraint<'_> {
let def = tcx.adt_def(def_id);
let result = tcx.mk_type_list(
def.variants
.iter()
.flat_map(|v| v.fields.last())
.flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did))),
);
debug!("adt_sized_constraint: {:?} => {:?}", def, result);
ty::AdtSizedConstraint(result)
}
fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
let id = tcx.hir().as_local_hir_id(def_id.expect_local());
let item = tcx.hir().expect_item(id);
match item.kind {
hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
trait_item_refs
.iter()
.map(|trait_item_ref| trait_item_ref.id)
.map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
),
hir::ItemKind::Impl { ref items, .. } => tcx.arena.alloc_from_iter(
items
.iter()
.map(|impl_item_ref| impl_item_ref.id)
.map(|id| tcx.hir().local_def_id(id.hir_id).to_def_id()),
),
hir::ItemKind::TraitAlias(..) => &[],
_ => span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
}
}
fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssociatedItems<'_> {
let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
ty::AssociatedItems::new(items)
}
fn def_span(tcx: TyCtxt<'_>, def_id: DefId) -> Span {
tcx.hir().span_if_local(def_id).unwrap()
}
/// If the given `DefId` describes an item belonging to a trait,
/// returns the `DefId` of the trait that the trait item belongs to;
/// otherwise, returns `None`.
fn trait_of_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
tcx.opt_associated_item(def_id).and_then(|associated_item| match associated_item.container {
ty::TraitContainer(def_id) => Some(def_id),
ty::ImplContainer(_) => None,
})
}
/// See `ParamEnv` struct definition for details.
fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
// The param_env of an impl Trait type is its defining function's param_env
if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) {
return param_env(tcx, parent);
}
// Compute the bounds on Self and the type parameters.
let ty::InstantiatedPredicates { predicates, .. } =
tcx.predicates_of(def_id).instantiate_identity(tcx);
// Finally, we have to normalize the bounds in the environment, in
// case they contain any associated type projections. This process
// can yield errors if the put in illegal associated types, like
// `<i32 as Foo>::Bar` where `i32` does not implement `Foo`. We
// report these errors right here; this doesn't actually feel
// right to me, because constructing the environment feels like a
// kind of a "idempotent" action, but I'm not sure where would be
// a better place. In practice, we construct environments for
// every fn once during type checking, and we'll abort if there
// are any errors at that point, so after type checking you can be
// sure that this will succeed without errors anyway.
let unnormalized_env = ty::ParamEnv::new(
tcx.intern_predicates(&predicates),
traits::Reveal::UserFacing,
tcx.sess.opts.debugging_opts.chalk.then_some(def_id),
);
let body_id = def_id
.as_local()
.map(|def_id| tcx.hir().as_local_hir_id(def_id))
.map_or(hir::CRATE_HIR_ID, |id| {
tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
});
let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
}
fn crate_disambiguator(tcx: TyCtxt<'_>, crate_num: CrateNum) -> CrateDisambiguator {
assert_eq!(crate_num, LOCAL_CRATE);
tcx.sess.local_crate_disambiguator()
}
fn original_crate_name(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Symbol {
assert_eq!(crate_num, LOCAL_CRATE);
tcx.crate_name
}
fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
tcx.index_hir(crate_num).crate_hash
}
fn instance_def_size_estimate<'tcx>(
tcx: TyCtxt<'tcx>,
instance_def: ty::InstanceDef<'tcx>,
) -> usize {
use ty::InstanceDef;
match instance_def {
InstanceDef::Item(..) | InstanceDef::DropGlue(..) => {
let mir = tcx.instance_mir(instance_def);
mir.basic_blocks().iter().map(|bb| bb.statements.len()).sum()
}
// Estimate the size of other compiler-generated shims to be 1.
_ => 1,
}
}
/// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`.
///
/// See [`ty::ImplOverlapKind::Issue33140`] for more details.
fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
debug!("issue33140_self_ty({:?})", def_id);
let trait_ref = tcx
.impl_trait_ref(def_id)
.unwrap_or_else(|| bug!("issue33140_self_ty called on inherent impl {:?}", def_id));
debug!("issue33140_self_ty({:?}), trait-ref={:?}", def_id, trait_ref);
let is_marker_like = tcx.impl_polarity(def_id) == ty::ImplPolarity::Positive
&& tcx.associated_item_def_ids(trait_ref.def_id).is_empty();
// Check whether these impls would be ok for a marker trait.
if !is_marker_like {
debug!("issue33140_self_ty - not marker-like!");
return None;
}
// impl must be `impl Trait for dyn Marker1 + Marker2 + ...`
if trait_ref.substs.len() != 1 {
debug!("issue33140_self_ty - impl has substs!");
return None;
}
let predicates = tcx.predicates_of(def_id);
if predicates.parent.is_some() || !predicates.predicates.is_empty() {
debug!("issue33140_self_ty - impl has predicates {:?}!", predicates);
return None;
}
let self_ty = trait_ref.self_ty();
let self_ty_matches = match self_ty.kind {
ty::Dynamic(ref data, ty::ReStatic) => data.principal().is_none(),
_ => false,
};
if self_ty_matches {
debug!("issue33140_self_ty - MATCHES!");
Some(self_ty)
} else {
debug!("issue33140_self_ty - non-matching self type");
None
}
}
/// Check if a function is async.
fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
let node = tcx.hir().get(hir_id);
let fn_like = hir_map::blocks::FnLikeNode::from_node(node).unwrap_or_else(|| {
bug!("asyncness: expected fn-like node but got `{:?}`", def_id);
});
fn_like.asyncness()
}
/// For associated types we allow bounds written on the associated type
/// (`type X: Trait`) to be used as candidates. We also allow the same bounds
/// when desugared as bounds on the trait `where Self::X: Trait`.
///
/// Note that this filtering is done with the items identity substs to
/// simplify checking that these bounds are met in impls. This means that
/// a bound such as `for<'b> <Self as X<'b>>::U: Clone` can't be used, as in
/// `hr-associated-type-bound-1.rs`.
fn associated_type_projection_predicates(
tcx: TyCtxt<'_>,
assoc_item_def_id: DefId,
) -> &'_ ty::List<ty::Predicate<'_>> {
let generic_trait_bounds = tcx.predicates_of(assoc_item_def_id);
// We include predicates from the trait as well to handle
// `where Self::X: Trait`.
let item_bounds = generic_trait_bounds.instantiate_identity(tcx);
let item_predicates = util::elaborate_predicates(tcx, item_bounds.predicates.into_iter());
let assoc_item_ty = ty::ProjectionTy {
item_def_id: assoc_item_def_id,
substs: InternalSubsts::identity_for_item(tcx, assoc_item_def_id),
};
let predicates = item_predicates.filter_map(|obligation| {
let pred = obligation.predicate;
match pred.skip_binders() {
ty::PredicateAtom::Trait(tr, _) => {
if let ty::Projection(p) = tr.self_ty().kind {
if p == assoc_item_ty {
return Some(pred);
}
}
}
ty::PredicateAtom::Projection(proj) => {
if let ty::Projection(p) = proj.projection_ty.self_ty().kind {
if p == assoc_item_ty {
return Some(pred);
}
}
}
ty::PredicateAtom::TypeOutlives(outlives) => {
if let ty::Projection(p) = outlives.0.kind {
if p == assoc_item_ty {
return Some(pred);
}
}
}
_ => {}
}
None
});
let result = tcx.mk_predicates(predicates);
debug!(
"associated_type_projection_predicates({}) = {:?}",
tcx.def_path_str(assoc_item_def_id),
result
);
result
}
/// Opaque types don't have the same issues as associated types: the only
/// predicates on an opaque type (excluding those it inherits from its parent
/// item) should be of the form we're expecting.
fn opaque_type_projection_predicates(
tcx: TyCtxt<'_>,
def_id: DefId,
) -> &'_ ty::List<ty::Predicate<'_>> {
let substs = InternalSubsts::identity_for_item(tcx, def_id);
let bounds = tcx.predicates_of(def_id);
let predicates =
util::elaborate_predicates(tcx, bounds.predicates.into_iter().map(|&(pred, _)| pred));
let filtered_predicates = predicates.filter_map(|obligation| {
let pred = obligation.predicate;
match pred.skip_binders() {
ty::PredicateAtom::Trait(tr, _) => {
if let ty::Opaque(opaque_def_id, opaque_substs) = tr.self_ty().kind {
if opaque_def_id == def_id && opaque_substs == substs {
return Some(pred);
}
}
}
ty::PredicateAtom::Projection(proj) => {
if let ty::Opaque(opaque_def_id, opaque_substs) = proj.projection_ty.self_ty().kind
{
if opaque_def_id == def_id && opaque_substs == substs {
return Some(pred);
}
}
}
ty::PredicateAtom::TypeOutlives(outlives) => {
if let ty::Opaque(opaque_def_id, opaque_substs) = outlives.0.kind {
if opaque_def_id == def_id && opaque_substs == substs {
return Some(pred);
}
} else {
// These can come from elaborating other predicates
return None;
}
}
// These can come from elaborating other predicates
ty::PredicateAtom::RegionOutlives(_) => return None,
_ => {}
}
tcx.sess.delay_span_bug(
obligation.cause.span(tcx),
&format!("unexpected predicate {:?} on opaque type", pred),
);
None
});
let result = tcx.mk_predicates(filtered_predicates);
debug!("opaque_type_projection_predicates({}) = {:?}", tcx.def_path_str(def_id), result);
result
}
fn projection_predicates(tcx: TyCtxt<'_>, def_id: DefId) -> &'_ ty::List<ty::Predicate<'_>> {
match tcx.def_kind(def_id) {
DefKind::AssocTy => associated_type_projection_predicates(tcx, def_id),
DefKind::OpaqueTy => opaque_type_projection_predicates(tcx, def_id),
k => bug!("projection_predicates called on {}", k.descr(def_id)),
}
}
pub fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers {
asyncness,
associated_item,
associated_item_def_ids,
associated_items,
adt_sized_constraint,
def_span,
param_env,
trait_of_item,
crate_disambiguator,
original_crate_name,
crate_hash,
instance_def_size_estimate,
issue33140_self_ty,
impl_defaultness,
projection_predicates,
..*providers
};
}