]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / wfcheck.rs
1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
7 use rustc_hir as hir;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::intravisit as hir_visit;
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
12 use rustc_hir::lang_items::LangItem;
13 use rustc_hir::ItemKind;
14 use rustc_middle::hir::map as hir_map;
15 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
16 use rustc_middle::ty::trait_def::TraitSpecializationKind;
17 use rustc_middle::ty::{
18 self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
19 };
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::{sym, Ident, Symbol};
22 use rustc_span::Span;
23 use rustc_trait_selection::opaque_types::may_define_opaque_type;
24 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
25 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, WellFormedLoc};
26
27 use std::convert::TryInto;
28 use std::iter;
29 use std::ops::ControlFlow;
30
31 /// Helper type of a temporary returned by `.for_item(...)`.
32 /// This is necessary because we can't write the following bound:
33 ///
34 /// ```rust
35 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
36 /// ```
37 struct CheckWfFcxBuilder<'tcx> {
38 inherited: super::InheritedBuilder<'tcx>,
39 id: hir::HirId,
40 span: Span,
41 param_env: ty::ParamEnv<'tcx>,
42 }
43
44 impl<'tcx> CheckWfFcxBuilder<'tcx> {
45 fn with_fcx<F>(&mut self, f: F)
46 where
47 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>) -> Vec<Ty<'tcx>>,
48 {
49 let id = self.id;
50 let span = self.span;
51 let param_env = self.param_env;
52 self.inherited.enter(|inh| {
53 let fcx = FnCtxt::new(&inh, param_env, id);
54 if !inh.tcx.features().trivial_bounds {
55 // As predicates are cached rather than obligations, this
56 // needs to be called first so that they are checked with an
57 // empty `param_env`.
58 check_false_global_bounds(&fcx, span, id);
59 }
60 let wf_tys = f(&fcx);
61 fcx.select_all_obligations_or_error();
62 fcx.regionck_item(id, span, &wf_tys);
63 });
64 }
65 }
66
67 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
68 /// well-formed, meaning that they do not require any constraints not declared in the struct
69 /// definition itself. For example, this definition would be illegal:
70 ///
71 /// ```rust
72 /// struct Ref<'a, T> { x: &'a T }
73 /// ```
74 ///
75 /// because the type did not declare that `T:'a`.
76 ///
77 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
78 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
79 /// the types first.
80 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
81 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
82 let item = tcx.hir().expect_item(hir_id);
83
84 debug!(
85 "check_item_well_formed(it.def_id={:?}, it.name={})",
86 item.def_id,
87 tcx.def_path_str(def_id.to_def_id())
88 );
89
90 match item.kind {
91 // Right now we check that every default trait implementation
92 // has an implementation of itself. Basically, a case like:
93 //
94 // impl Trait for T {}
95 //
96 // has a requirement of `T: Trait` which was required for default
97 // method implementations. Although this could be improved now that
98 // there's a better infrastructure in place for this, it's being left
99 // for a follow-up work.
100 //
101 // Since there's such a requirement, we need to check *just* positive
102 // implementations, otherwise things like:
103 //
104 // impl !Send for T {}
105 //
106 // won't be allowed unless there's an *explicit* implementation of `Send`
107 // for `T`
108 hir::ItemKind::Impl(ref impl_) => {
109 let is_auto = tcx
110 .impl_trait_ref(item.def_id)
111 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
112 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
113 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
114 let mut err =
115 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
116 err.span_labels(impl_.defaultness_span, "default because of this");
117 err.span_label(sp, "auto trait");
118 err.emit();
119 }
120 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
121 match (tcx.impl_polarity(def_id), impl_.polarity) {
122 (ty::ImplPolarity::Positive, _) => {
123 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait);
124 }
125 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
126 // FIXME(#27579): what amount of WF checking do we need for neg impls?
127 if let hir::Defaultness::Default { .. } = impl_.defaultness {
128 let mut spans = vec![span];
129 spans.extend(impl_.defaultness_span);
130 struct_span_err!(
131 tcx.sess,
132 spans,
133 E0750,
134 "negative impls cannot be default impls"
135 )
136 .emit();
137 }
138 }
139 (ty::ImplPolarity::Reservation, _) => {
140 // FIXME: what amount of WF checking do we need for reservation impls?
141 }
142 _ => unreachable!(),
143 }
144 }
145 hir::ItemKind::Fn(ref sig, ..) => {
146 check_item_fn(tcx, item.hir_id(), item.ident, item.span, sig.decl);
147 }
148 hir::ItemKind::Static(ref ty, ..) => {
149 check_item_type(tcx, item.hir_id(), ty.span, false);
150 }
151 hir::ItemKind::Const(ref ty, ..) => {
152 check_item_type(tcx, item.hir_id(), ty.span, false);
153 }
154 hir::ItemKind::ForeignMod { items, .. } => {
155 for it in items.iter() {
156 let it = tcx.hir().foreign_item(it.id);
157 match it.kind {
158 hir::ForeignItemKind::Fn(ref decl, ..) => {
159 check_item_fn(tcx, it.hir_id(), it.ident, it.span, decl)
160 }
161 hir::ForeignItemKind::Static(ref ty, ..) => {
162 check_item_type(tcx, it.hir_id(), ty.span, true)
163 }
164 hir::ForeignItemKind::Type => (),
165 }
166 }
167 }
168 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
169 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
170
171 check_variances_for_type_defn(tcx, item, ast_generics);
172 }
173 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
174 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
175
176 check_variances_for_type_defn(tcx, item, ast_generics);
177 }
178 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
179 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
180
181 check_variances_for_type_defn(tcx, item, ast_generics);
182 }
183 hir::ItemKind::Trait(..) => {
184 check_trait(tcx, item);
185 }
186 hir::ItemKind::TraitAlias(..) => {
187 check_trait(tcx, item);
188 }
189 _ => {}
190 }
191 }
192
193 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
194 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
195 let trait_item = tcx.hir().expect_trait_item(hir_id);
196
197 let (method_sig, span) = match trait_item.kind {
198 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
199 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
200 _ => (None, trait_item.span),
201 };
202 check_object_unsafe_self_trait_by_name(tcx, &trait_item);
203 check_associated_item(tcx, trait_item.hir_id(), span, method_sig);
204 }
205
206 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
207 match ty.kind {
208 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
209 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
210 _ => false,
211 },
212 _ => false,
213 }
214 }
215
216 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
217 /// When this is done, suggest using `Self` instead.
218 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
219 let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id())) {
220 hir::Node::Item(item) => match item.kind {
221 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
222 _ => return,
223 },
224 _ => return,
225 };
226 let mut trait_should_be_self = vec![];
227 match &item.kind {
228 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
229 if could_be_self(trait_def_id, ty) =>
230 {
231 trait_should_be_self.push(ty.span)
232 }
233 hir::TraitItemKind::Fn(sig, _) => {
234 for ty in sig.decl.inputs {
235 if could_be_self(trait_def_id, ty) {
236 trait_should_be_self.push(ty.span);
237 }
238 }
239 match sig.decl.output {
240 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
241 trait_should_be_self.push(ty.span);
242 }
243 _ => {}
244 }
245 }
246 _ => {}
247 }
248 if !trait_should_be_self.is_empty() {
249 if tcx.object_safety_violations(trait_def_id).is_empty() {
250 return;
251 }
252 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
253 tcx.sess
254 .struct_span_err(
255 trait_should_be_self,
256 "associated item referring to unboxed trait object for its own trait",
257 )
258 .span_label(trait_name.span, "in this trait")
259 .multipart_suggestion(
260 "you might have meant to use `Self` to refer to the implementing type",
261 sugg,
262 Applicability::MachineApplicable,
263 )
264 .emit();
265 }
266 }
267
268 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
269 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
270 let impl_item = tcx.hir().expect_impl_item(hir_id);
271
272 let (method_sig, span) = match impl_item.kind {
273 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
274 hir::ImplItemKind::TyAlias(ty) => (None, ty.span),
275 _ => (None, impl_item.span),
276 };
277
278 check_associated_item(tcx, impl_item.hir_id(), span, method_sig);
279 }
280
281 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
282 match param.kind {
283 // We currently only check wf of const params here.
284 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
285
286 // Const parameters are well formed if their type is structural match.
287 // FIXME(const_generics_defaults): we also need to check that the `default` is wf.
288 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
289 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
290
291 let err_ty_str;
292 let mut is_ptr = true;
293 let err = if tcx.features().adt_const_params {
294 match ty.peel_refs().kind() {
295 ty::FnPtr(_) => Some("function pointers"),
296 ty::RawPtr(_) => Some("raw pointers"),
297 _ => None,
298 }
299 } else {
300 match ty.kind() {
301 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
302 ty::FnPtr(_) => Some("function pointers"),
303 ty::RawPtr(_) => Some("raw pointers"),
304 _ => {
305 is_ptr = false;
306 err_ty_str = format!("`{}`", ty);
307 Some(err_ty_str.as_str())
308 }
309 }
310 };
311 if let Some(unsupported_type) = err {
312 if is_ptr {
313 tcx.sess.span_err(
314 hir_ty.span,
315 &format!(
316 "using {} as const generic parameters is forbidden",
317 unsupported_type
318 ),
319 )
320 } else {
321 let mut err = tcx.sess.struct_span_err(
322 hir_ty.span,
323 &format!(
324 "{} is forbidden as the type of a const generic parameter",
325 unsupported_type
326 ),
327 );
328 err.note("the only supported types are integers, `bool` and `char`");
329 if tcx.sess.is_nightly_build() {
330 err.help(
331 "more complex types are supported with `#![feature(adt_const_params)]`",
332 );
333 }
334 err.emit()
335 }
336 };
337
338 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
339 .is_some()
340 {
341 // We use the same error code in both branches, because this is really the same
342 // issue: we just special-case the message for type parameters to make it
343 // clearer.
344 if let ty::Param(_) = ty.peel_refs().kind() {
345 // Const parameters may not have type parameters as their types,
346 // because we cannot be sure that the type parameter derives `PartialEq`
347 // and `Eq` (just implementing them is not enough for `structural_match`).
348 struct_span_err!(
349 tcx.sess,
350 hir_ty.span,
351 E0741,
352 "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
353 used as the type of a const parameter",
354 ty,
355 )
356 .span_label(
357 hir_ty.span,
358 format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
359 )
360 .note(
361 "it is not currently possible to use a type parameter as the type of a \
362 const parameter",
363 )
364 .emit();
365 } else {
366 struct_span_err!(
367 tcx.sess,
368 hir_ty.span,
369 E0741,
370 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
371 the type of a const parameter",
372 ty,
373 )
374 .span_label(
375 hir_ty.span,
376 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
377 )
378 .emit();
379 }
380 }
381 }
382 }
383 }
384
385 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
386 fn check_associated_item(
387 tcx: TyCtxt<'_>,
388 item_id: hir::HirId,
389 span: Span,
390 sig_if_method: Option<&hir::FnSig<'_>>,
391 ) {
392 let code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id.expect_owner())));
393 for_id(tcx, item_id, span).with_fcx(|fcx| {
394 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
395
396 let (mut implied_bounds, self_ty) = match item.container {
397 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
398 ty::ImplContainer(def_id) => {
399 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
400 }
401 };
402
403 match item.kind {
404 ty::AssocKind::Const => {
405 let ty = fcx.tcx.type_of(item.def_id);
406 let ty = fcx.normalize_associated_types_in_wf(
407 span,
408 ty,
409 WellFormedLoc::Ty(item_id.expect_owner()),
410 );
411 fcx.register_wf_obligation(ty.into(), span, code.clone());
412 }
413 ty::AssocKind::Fn => {
414 let sig = fcx.tcx.fn_sig(item.def_id);
415 let hir_sig = sig_if_method.expect("bad signature for method");
416 check_fn_or_method(
417 fcx,
418 item.ident.span,
419 sig,
420 hir_sig.decl,
421 item.def_id,
422 &mut implied_bounds,
423 );
424 check_method_receiver(fcx, hir_sig, &item, self_ty);
425 }
426 ty::AssocKind::Type => {
427 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
428 check_associated_type_bounds(fcx, item, span)
429 }
430 if item.defaultness.has_value() {
431 let ty = fcx.tcx.type_of(item.def_id);
432 let ty = fcx.normalize_associated_types_in_wf(
433 span,
434 ty,
435 WellFormedLoc::Ty(item_id.expect_owner()),
436 );
437 fcx.register_wf_obligation(ty.into(), span, code.clone());
438 }
439 }
440 }
441
442 implied_bounds
443 })
444 }
445
446 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
447 for_id(tcx, item.hir_id(), item.span)
448 }
449
450 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
451 let def_id = tcx.hir().local_def_id(id);
452 CheckWfFcxBuilder {
453 inherited: Inherited::build(tcx, def_id),
454 id,
455 span,
456 param_env: tcx.param_env(def_id),
457 }
458 }
459
460 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
461 match kind {
462 ItemKind::Struct(..) => Some(AdtKind::Struct),
463 ItemKind::Union(..) => Some(AdtKind::Union),
464 ItemKind::Enum(..) => Some(AdtKind::Enum),
465 _ => None,
466 }
467 }
468
469 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
470 fn check_type_defn<'tcx, F>(
471 tcx: TyCtxt<'tcx>,
472 item: &hir::Item<'tcx>,
473 all_sized: bool,
474 mut lookup_fields: F,
475 ) where
476 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
477 {
478 for_item(tcx, item).with_fcx(|fcx| {
479 let variants = lookup_fields(fcx);
480 let packed = tcx.adt_def(item.def_id).repr.packed();
481
482 for variant in &variants {
483 // For DST, or when drop needs to copy things around, all
484 // intermediate types must be sized.
485 let needs_drop_copy = || {
486 packed && {
487 let ty = variant.fields.last().unwrap().ty;
488 let ty = tcx.erase_regions(ty);
489 if ty.needs_infer() {
490 tcx.sess
491 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
492 // Just treat unresolved type expression as if it needs drop.
493 true
494 } else {
495 ty.needs_drop(tcx, tcx.param_env(item.def_id))
496 }
497 }
498 };
499 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
500 let unsized_len = if all_sized { 0 } else { 1 };
501 for (idx, field) in
502 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
503 {
504 let last = idx == variant.fields.len() - 1;
505 fcx.register_bound(
506 field.ty,
507 tcx.require_lang_item(LangItem::Sized, None),
508 traits::ObligationCause::new(
509 field.span,
510 fcx.body_id,
511 traits::FieldSized {
512 adt_kind: match item_adt_kind(&item.kind) {
513 Some(i) => i,
514 None => bug!(),
515 },
516 span: field.span,
517 last,
518 },
519 ),
520 );
521 }
522
523 // All field types must be well-formed.
524 for field in &variant.fields {
525 fcx.register_wf_obligation(
526 field.ty.into(),
527 field.span,
528 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(field.def_id))),
529 )
530 }
531
532 // Explicit `enum` discriminant values must const-evaluate successfully.
533 if let Some(discr_def_id) = variant.explicit_discr {
534 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
535
536 let cause = traits::ObligationCause::new(
537 tcx.def_span(discr_def_id),
538 fcx.body_id,
539 traits::MiscObligation,
540 );
541 fcx.register_predicate(traits::Obligation::new(
542 cause,
543 fcx.param_env,
544 ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
545 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
546 discr_substs,
547 ))
548 .to_predicate(tcx),
549 ));
550 }
551 }
552
553 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
554
555 // No implied bounds in a struct definition.
556 vec![]
557 });
558 }
559
560 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
561 debug!("check_trait: {:?}", item.def_id);
562
563 let trait_def = tcx.trait_def(item.def_id);
564 if trait_def.is_marker
565 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
566 {
567 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
568 struct_span_err!(
569 tcx.sess,
570 tcx.def_span(*associated_def_id),
571 E0714,
572 "marker traits cannot have associated items",
573 )
574 .emit();
575 }
576 }
577
578 // FIXME: this shouldn't use an `FnCtxt` at all.
579 for_item(tcx, item).with_fcx(|fcx| {
580 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
581
582 vec![]
583 });
584 }
585
586 /// Checks all associated type defaults of trait `trait_def_id`.
587 ///
588 /// Assuming the defaults are used, check that all predicates (bounds on the
589 /// assoc type and where clauses on the trait) hold.
590 fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
591 let tcx = fcx.tcx;
592
593 let bounds = tcx.explicit_item_bounds(item.def_id);
594
595 debug!("check_associated_type_bounds: bounds={:?}", bounds);
596 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
597 let normalized_bound = fcx.normalize_associated_types_in(span, bound);
598 traits::wf::predicate_obligations(
599 fcx,
600 fcx.param_env,
601 fcx.body_id,
602 normalized_bound,
603 bound_span,
604 )
605 });
606
607 for obligation in wf_obligations {
608 debug!("next obligation cause: {:?}", obligation.cause);
609 fcx.register_predicate(obligation);
610 }
611 }
612
613 fn check_item_fn(
614 tcx: TyCtxt<'_>,
615 item_id: hir::HirId,
616 ident: Ident,
617 span: Span,
618 decl: &hir::FnDecl<'_>,
619 ) {
620 for_id(tcx, item_id, span).with_fcx(|fcx| {
621 let def_id = tcx.hir().local_def_id(item_id);
622 let sig = tcx.fn_sig(def_id);
623 let mut implied_bounds = vec![];
624 check_fn_or_method(fcx, ident.span, sig, decl, def_id.to_def_id(), &mut implied_bounds);
625 implied_bounds
626 })
627 }
628
629 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
630 debug!("check_item_type: {:?}", item_id);
631
632 for_id(tcx, item_id, ty_span).with_fcx(|fcx| {
633 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
634 let item_ty = fcx.normalize_associated_types_in_wf(
635 ty_span,
636 ty,
637 WellFormedLoc::Ty(item_id.expect_owner()),
638 );
639
640 let mut forbid_unsized = true;
641 if allow_foreign_ty {
642 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
643 if let ty::Foreign(_) = tail.kind() {
644 forbid_unsized = false;
645 }
646 }
647
648 fcx.register_wf_obligation(
649 item_ty.into(),
650 ty_span,
651 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id.expect_owner()))),
652 );
653 if forbid_unsized {
654 fcx.register_bound(
655 item_ty,
656 tcx.require_lang_item(LangItem::Sized, None),
657 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
658 );
659 }
660
661 // No implied bounds in a const, etc.
662 vec![]
663 });
664 }
665
666 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
667 fn check_impl<'tcx>(
668 tcx: TyCtxt<'tcx>,
669 item: &'tcx hir::Item<'tcx>,
670 ast_self_ty: &hir::Ty<'_>,
671 ast_trait_ref: &Option<hir::TraitRef<'_>>,
672 ) {
673 for_item(tcx, item).with_fcx(|fcx| {
674 match *ast_trait_ref {
675 Some(ref ast_trait_ref) => {
676 // `#[rustc_reservation_impl]` impls are not real impls and
677 // therefore don't need to be WF (the trait's `Self: Trait` predicate
678 // won't hold).
679 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
680 let trait_ref =
681 fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
682 let obligations = traits::wf::trait_obligations(
683 fcx,
684 fcx.param_env,
685 fcx.body_id,
686 &trait_ref,
687 ast_trait_ref.path.span,
688 Some(item),
689 );
690 debug!(?obligations);
691 for obligation in obligations {
692 fcx.register_predicate(obligation);
693 }
694 }
695 None => {
696 let self_ty = tcx.type_of(item.def_id);
697 let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
698 fcx.register_wf_obligation(
699 self_ty.into(),
700 ast_self_ty.span,
701 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(
702 item.hir_id().expect_owner(),
703 ))),
704 );
705 }
706 }
707
708 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
709
710 fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
711 });
712 }
713
714 /// Checks where-clauses and inline bounds that are declared on `def_id`.
715 fn check_where_clauses<'tcx, 'fcx>(
716 fcx: &FnCtxt<'fcx, 'tcx>,
717 span: Span,
718 def_id: DefId,
719 return_ty: Option<(Ty<'tcx>, Span)>,
720 ) {
721 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
722 let tcx = fcx.tcx;
723
724 let predicates = tcx.predicates_of(def_id);
725 let generics = tcx.generics_of(def_id);
726
727 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
728 GenericParamDefKind::Type { has_default, .. }
729 | GenericParamDefKind::Const { has_default } => {
730 has_default && def.index >= generics.parent_count as u32
731 }
732 GenericParamDefKind::Lifetime => unreachable!(),
733 };
734
735 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
736 // For example, this forbids the declaration:
737 //
738 // struct Foo<T = Vec<[u32]>> { .. }
739 //
740 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
741 for param in &generics.params {
742 match param.kind {
743 GenericParamDefKind::Type { .. } => {
744 if is_our_default(&param) {
745 let ty = tcx.type_of(param.def_id);
746 // Ignore dependent defaults -- that is, where the default of one type
747 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
748 // be sure if it will error or not as user might always specify the other.
749 if !ty.definitely_needs_subst(tcx) {
750 fcx.register_wf_obligation(
751 ty.into(),
752 tcx.def_span(param.def_id),
753 ObligationCauseCode::MiscObligation,
754 );
755 }
756 }
757 }
758 GenericParamDefKind::Const { .. } => {
759 if is_our_default(&param) {
760 // FIXME(const_generics_defaults): This
761 // is incorrect when dealing with unused substs, for example
762 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
763 // we should eagerly error.
764 let default_ct = tcx.const_param_default(param.def_id);
765 if !default_ct.definitely_needs_subst(tcx) {
766 fcx.register_wf_obligation(
767 default_ct.into(),
768 tcx.def_span(param.def_id),
769 ObligationCauseCode::WellFormed(None),
770 );
771 }
772 }
773 }
774 // Doesn't have defaults.
775 GenericParamDefKind::Lifetime => {}
776 }
777 }
778
779 // Check that trait predicates are WF when params are substituted by their defaults.
780 // We don't want to overly constrain the predicates that may be written but we want to
781 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
782 // Therefore we check if a predicate which contains a single type param
783 // with a concrete default is WF with that default substituted.
784 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
785 //
786 // First we build the defaulted substitution.
787 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
788 match param.kind {
789 GenericParamDefKind::Lifetime => {
790 // All regions are identity.
791 tcx.mk_param_from_def(param)
792 }
793
794 GenericParamDefKind::Type { .. } => {
795 // If the param has a default, ...
796 if is_our_default(param) {
797 let default_ty = tcx.type_of(param.def_id);
798 // ... and it's not a dependent default, ...
799 if !default_ty.definitely_needs_subst(tcx) {
800 // ... then substitute it with the default.
801 return default_ty.into();
802 }
803 }
804
805 tcx.mk_param_from_def(param)
806 }
807 GenericParamDefKind::Const { .. } => {
808 // If the param has a default, ...
809 if is_our_default(param) {
810 let default_ct = tcx.const_param_default(param.def_id);
811 // ... and it's not a dependent default, ...
812 if !default_ct.definitely_needs_subst(tcx) {
813 // ... then substitute it with the default.
814 return default_ct.into();
815 }
816 }
817
818 tcx.mk_param_from_def(param)
819 }
820 }
821 });
822
823 // Now we build the substituted predicates.
824 let default_obligations = predicates
825 .predicates
826 .iter()
827 .flat_map(|&(pred, sp)| {
828 struct CountParams<'tcx> {
829 tcx: TyCtxt<'tcx>,
830 params: FxHashSet<u32>,
831 }
832 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams<'tcx> {
833 type BreakTy = ();
834 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
835 Some(self.tcx)
836 }
837
838 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
839 if let ty::Param(param) = t.kind() {
840 self.params.insert(param.index);
841 }
842 t.super_visit_with(self)
843 }
844
845 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
846 ControlFlow::BREAK
847 }
848
849 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
850 if let ty::ConstKind::Param(param) = c.val {
851 self.params.insert(param.index);
852 }
853 c.super_visit_with(self)
854 }
855 }
856 let mut param_count = CountParams { tcx: fcx.tcx, params: FxHashSet::default() };
857 let has_region = pred.visit_with(&mut param_count).is_break();
858 let substituted_pred = pred.subst(tcx, substs);
859 // Don't check non-defaulted params, dependent defaults (including lifetimes)
860 // or preds with multiple params.
861 if substituted_pred.definitely_has_param_types_or_consts(tcx)
862 || param_count.params.len() > 1
863 || has_region
864 {
865 None
866 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
867 // Avoid duplication of predicates that contain no parameters, for example.
868 None
869 } else {
870 Some((substituted_pred, sp))
871 }
872 })
873 .map(|(pred, sp)| {
874 // Convert each of those into an obligation. So if you have
875 // something like `struct Foo<T: Copy = String>`, we would
876 // take that predicate `T: Copy`, substitute to `String: Copy`
877 // (actually that happens in the previous `flat_map` call),
878 // and then try to prove it (in this case, we'll fail).
879 //
880 // Note the subtle difference from how we handle `predicates`
881 // below: there, we are not trying to prove those predicates
882 // to be *true* but merely *well-formed*.
883 let pred = fcx.normalize_associated_types_in(sp, pred);
884 let cause =
885 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
886 traits::Obligation::new(cause, fcx.param_env, pred)
887 });
888
889 let predicates = predicates.instantiate_identity(tcx);
890
891 if let Some((mut return_ty, span)) = return_ty {
892 if return_ty.has_infer_types_or_consts() {
893 fcx.select_obligations_where_possible(false, |_| {});
894 return_ty = fcx.resolve_vars_if_possible(return_ty);
895 }
896 check_opaque_types(fcx, def_id.expect_local(), span, return_ty);
897 }
898
899 let predicates = fcx.normalize_associated_types_in(span, predicates);
900
901 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
902 assert_eq!(predicates.predicates.len(), predicates.spans.len());
903 let wf_obligations =
904 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
905 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
906 });
907
908 for obligation in wf_obligations.chain(default_obligations) {
909 debug!("next obligation cause: {:?}", obligation.cause);
910 fcx.register_predicate(obligation);
911 }
912 }
913
914 #[tracing::instrument(level = "debug", skip(fcx, span, hir_decl))]
915 fn check_fn_or_method<'fcx, 'tcx>(
916 fcx: &FnCtxt<'fcx, 'tcx>,
917 span: Span,
918 sig: ty::PolyFnSig<'tcx>,
919 hir_decl: &hir::FnDecl<'_>,
920 def_id: DefId,
921 implied_bounds: &mut Vec<Ty<'tcx>>,
922 ) {
923 let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
924
925 // Unnormalized types in signature are WF too
926 implied_bounds.extend(sig.inputs());
927 // FIXME(#27579) return types should not be implied bounds
928 implied_bounds.push(sig.output());
929
930 // Normalize the input and output types one at a time, using a different
931 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
932 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
933 // for each type, preventing the HIR wf check from generating
934 // a nice error message.
935 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
936 inputs_and_output =
937 fcx.tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
938 fcx.normalize_associated_types_in_wf(
939 span,
940 ty,
941 WellFormedLoc::Param {
942 function: def_id.expect_local(),
943 // Note that the `param_idx` of the output type is
944 // one greater than the index of the last input type.
945 param_idx: i.try_into().unwrap(),
946 },
947 )
948 }));
949 // Manually call `normalize_assocaited_types_in` on the other types
950 // in `FnSig`. This ensures that if the types of these fields
951 // ever change to include projections, we will start normalizing
952 // them automatically.
953 let sig = ty::FnSig {
954 inputs_and_output,
955 c_variadic: fcx.normalize_associated_types_in(span, c_variadic),
956 unsafety: fcx.normalize_associated_types_in(span, unsafety),
957 abi: fcx.normalize_associated_types_in(span, abi),
958 };
959
960 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
961 fcx.register_wf_obligation(
962 input_ty.into(),
963 ty.span,
964 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
965 function: def_id.expect_local(),
966 param_idx: i.try_into().unwrap(),
967 })),
968 );
969 }
970
971 implied_bounds.extend(sig.inputs());
972
973 fcx.register_wf_obligation(
974 sig.output().into(),
975 hir_decl.output.span(),
976 ObligationCauseCode::ReturnType,
977 );
978
979 // FIXME(#27579) return types should not be implied bounds
980 implied_bounds.push(sig.output());
981
982 debug!(?implied_bounds);
983
984 check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
985 }
986
987 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
988 /// laid for "higher-order pattern unification".
989 /// This ensures that inference is tractable.
990 /// In particular, definitions of opaque types can only use other generics as arguments,
991 /// and they cannot repeat an argument. Example:
992 ///
993 /// ```rust
994 /// type Foo<A, B> = impl Bar<A, B>;
995 ///
996 /// // Okay -- `Foo` is applied to two distinct, generic types.
997 /// fn a<T, U>() -> Foo<T, U> { .. }
998 ///
999 /// // Not okay -- `Foo` is applied to `T` twice.
1000 /// fn b<T>() -> Foo<T, T> { .. }
1001 ///
1002 /// // Not okay -- `Foo` is applied to a non-generic type.
1003 /// fn b<T>() -> Foo<T, u32> { .. }
1004 /// ```
1005 ///
1006 fn check_opaque_types<'fcx, 'tcx>(
1007 fcx: &FnCtxt<'fcx, 'tcx>,
1008 fn_def_id: LocalDefId,
1009 span: Span,
1010 ty: Ty<'tcx>,
1011 ) {
1012 trace!("check_opaque_types(fn_def_id={:?}, ty={:?})", fn_def_id, ty);
1013 let tcx = fcx.tcx;
1014
1015 ty.fold_with(&mut ty::fold::BottomUpFolder {
1016 tcx,
1017 ty_op: |ty| {
1018 if let ty::Opaque(def_id, substs) = *ty.kind() {
1019 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
1020 let generics = tcx.generics_of(def_id);
1021
1022 let opaque_hir_id = if let Some(local_id) = def_id.as_local() {
1023 tcx.hir().local_def_id_to_hir_id(local_id)
1024 } else {
1025 // Opaque types from other crates won't have defining uses in this crate.
1026 return ty;
1027 };
1028 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) =
1029 tcx.hir().expect_item(opaque_hir_id).kind
1030 {
1031 // No need to check return position impl trait (RPIT)
1032 // because for type and const parameters they are correct
1033 // by construction: we convert
1034 //
1035 // fn foo<P0..Pn>() -> impl Trait
1036 //
1037 // into
1038 //
1039 // type Foo<P0...Pn>
1040 // fn foo<P0..Pn>() -> Foo<P0...Pn>.
1041 //
1042 // For lifetime parameters we convert
1043 //
1044 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
1045 //
1046 // into
1047 //
1048 // type foo::<'p0..'pn>::Foo<'q0..'qm>
1049 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
1050 //
1051 // which would error here on all of the `'static` args.
1052 return ty;
1053 }
1054 if !may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
1055 return ty;
1056 }
1057 trace!("check_opaque_types: may define, generics={:#?}", generics);
1058 let mut seen_params: FxHashMap<_, Vec<_>> = FxHashMap::default();
1059 for (i, arg) in substs.iter().enumerate() {
1060 let arg_is_param = match arg.unpack() {
1061 GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
1062
1063 GenericArgKind::Lifetime(region) if let ty::ReStatic = region => {
1064 tcx.sess
1065 .struct_span_err(
1066 span,
1067 "non-defining opaque type use in defining scope",
1068 )
1069 .span_label(
1070 tcx.def_span(generics.param_at(i, tcx).def_id),
1071 "cannot use static lifetime; use a bound lifetime \
1072 instead or remove the lifetime parameter from the \
1073 opaque type",
1074 )
1075 .emit();
1076 continue;
1077 }
1078
1079 GenericArgKind::Lifetime(_) => true,
1080
1081 GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
1082 };
1083
1084 if arg_is_param {
1085 seen_params.entry(arg).or_default().push(i);
1086 } else {
1087 // Prevent `fn foo() -> Foo<u32>` from being defining.
1088 let opaque_param = generics.param_at(i, tcx);
1089 tcx.sess
1090 .struct_span_err(span, "non-defining opaque type use in defining scope")
1091 .span_note(
1092 tcx.def_span(opaque_param.def_id),
1093 &format!(
1094 "used non-generic {} `{}` for generic parameter",
1095 opaque_param.kind.descr(),
1096 arg,
1097 ),
1098 )
1099 .emit();
1100 }
1101 } // for (arg, param)
1102
1103 for (_, indices) in seen_params {
1104 if indices.len() > 1 {
1105 let descr = generics.param_at(indices[0], tcx).kind.descr();
1106 let spans: Vec<_> = indices
1107 .into_iter()
1108 .map(|i| tcx.def_span(generics.param_at(i, tcx).def_id))
1109 .collect();
1110 tcx.sess
1111 .struct_span_err(span, "non-defining opaque type use in defining scope")
1112 .span_note(spans, &format!("{} used multiple times", descr))
1113 .emit();
1114 }
1115 }
1116 } // if let Opaque
1117 ty
1118 },
1119 lt_op: |lt| lt,
1120 ct_op: |ct| ct,
1121 });
1122 }
1123
1124 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1125 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1126 of the previous types except `Self`)";
1127
1128 #[tracing::instrument(level = "debug", skip(fcx))]
1129 fn check_method_receiver<'fcx, 'tcx>(
1130 fcx: &FnCtxt<'fcx, 'tcx>,
1131 fn_sig: &hir::FnSig<'_>,
1132 method: &ty::AssocItem,
1133 self_ty: Ty<'tcx>,
1134 ) {
1135 // Check that the method has a valid receiver type, given the type `Self`.
1136 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1137
1138 if !method.fn_has_self_parameter {
1139 return;
1140 }
1141
1142 let span = fn_sig.decl.inputs[0].span;
1143
1144 let sig = fcx.tcx.fn_sig(method.def_id);
1145 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
1146 let sig = fcx.normalize_associated_types_in(span, sig);
1147
1148 debug!("check_method_receiver: sig={:?}", sig);
1149
1150 let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1151
1152 let receiver_ty = sig.inputs()[0];
1153 let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
1154
1155 if fcx.tcx.features().arbitrary_self_types {
1156 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1157 // Report error; `arbitrary_self_types` was enabled.
1158 e0307(fcx, span, receiver_ty);
1159 }
1160 } else {
1161 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1162 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1163 // Report error; would have worked with `arbitrary_self_types`.
1164 feature_err(
1165 &fcx.tcx.sess.parse_sess,
1166 sym::arbitrary_self_types,
1167 span,
1168 &format!(
1169 "`{}` cannot be used as the type of `self` without \
1170 the `arbitrary_self_types` feature",
1171 receiver_ty,
1172 ),
1173 )
1174 .help(HELP_FOR_SELF_TYPE)
1175 .emit();
1176 } else {
1177 // Report error; would not have worked with `arbitrary_self_types`.
1178 e0307(fcx, span, receiver_ty);
1179 }
1180 }
1181 }
1182 }
1183
1184 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1185 struct_span_err!(
1186 fcx.tcx.sess.diagnostic(),
1187 span,
1188 E0307,
1189 "invalid `self` parameter type: {}",
1190 receiver_ty,
1191 )
1192 .note("type of `self` must be `Self` or a type that dereferences to it")
1193 .help(HELP_FOR_SELF_TYPE)
1194 .emit();
1195 }
1196
1197 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1198 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1199 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1200 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1201 /// `Deref<Target = self_ty>`.
1202 ///
1203 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1204 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1205 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1206 fn receiver_is_valid<'fcx, 'tcx>(
1207 fcx: &FnCtxt<'fcx, 'tcx>,
1208 span: Span,
1209 receiver_ty: Ty<'tcx>,
1210 self_ty: Ty<'tcx>,
1211 arbitrary_self_types_enabled: bool,
1212 ) -> bool {
1213 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1214
1215 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1216
1217 // `self: Self` is always valid.
1218 if can_eq_self(receiver_ty) {
1219 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1220 err.emit();
1221 }
1222 return true;
1223 }
1224
1225 let mut autoderef = fcx.autoderef(span, receiver_ty);
1226
1227 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1228 if arbitrary_self_types_enabled {
1229 autoderef = autoderef.include_raw_pointers();
1230 }
1231
1232 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1233 autoderef.next();
1234
1235 let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1236
1237 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1238 loop {
1239 if let Some((potential_self_ty, _)) = autoderef.next() {
1240 debug!(
1241 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1242 potential_self_ty, self_ty
1243 );
1244
1245 if can_eq_self(potential_self_ty) {
1246 fcx.register_predicates(autoderef.into_obligations());
1247
1248 if let Some(mut err) =
1249 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1250 {
1251 err.emit();
1252 }
1253
1254 break;
1255 } else {
1256 // Without `feature(arbitrary_self_types)`, we require that each step in the
1257 // deref chain implement `receiver`
1258 if !arbitrary_self_types_enabled
1259 && !receiver_is_implemented(
1260 fcx,
1261 receiver_trait_def_id,
1262 cause.clone(),
1263 potential_self_ty,
1264 )
1265 {
1266 return false;
1267 }
1268 }
1269 } else {
1270 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1271 // If he receiver already has errors reported due to it, consider it valid to avoid
1272 // unnecessary errors (#58712).
1273 return receiver_ty.references_error();
1274 }
1275 }
1276
1277 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1278 if !arbitrary_self_types_enabled
1279 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1280 {
1281 return false;
1282 }
1283
1284 true
1285 }
1286
1287 fn receiver_is_implemented(
1288 fcx: &FnCtxt<'_, 'tcx>,
1289 receiver_trait_def_id: DefId,
1290 cause: ObligationCause<'tcx>,
1291 receiver_ty: Ty<'tcx>,
1292 ) -> bool {
1293 let trait_ref = ty::TraitRef {
1294 def_id: receiver_trait_def_id,
1295 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1296 };
1297
1298 let obligation = traits::Obligation::new(
1299 cause,
1300 fcx.param_env,
1301 trait_ref.without_const().to_predicate(fcx.tcx),
1302 );
1303
1304 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1305 true
1306 } else {
1307 debug!(
1308 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1309 receiver_ty
1310 );
1311 false
1312 }
1313 }
1314
1315 fn check_variances_for_type_defn<'tcx>(
1316 tcx: TyCtxt<'tcx>,
1317 item: &hir::Item<'tcx>,
1318 hir_generics: &hir::Generics<'_>,
1319 ) {
1320 let ty = tcx.type_of(item.def_id);
1321 if tcx.has_error_field(ty) {
1322 return;
1323 }
1324
1325 let ty_predicates = tcx.predicates_of(item.def_id);
1326 assert_eq!(ty_predicates.parent, None);
1327 let variances = tcx.variances_of(item.def_id);
1328
1329 let mut constrained_parameters: FxHashSet<_> = variances
1330 .iter()
1331 .enumerate()
1332 .filter(|&(_, &variance)| variance != ty::Bivariant)
1333 .map(|(index, _)| Parameter(index as u32))
1334 .collect();
1335
1336 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1337
1338 for (index, _) in variances.iter().enumerate() {
1339 if constrained_parameters.contains(&Parameter(index as u32)) {
1340 continue;
1341 }
1342
1343 let param = &hir_generics.params[index];
1344
1345 match param.name {
1346 hir::ParamName::Error => {}
1347 _ => report_bivariance(tcx, param),
1348 }
1349 }
1350 }
1351
1352 fn report_bivariance(tcx: TyCtxt<'_>, param: &rustc_hir::GenericParam<'_>) {
1353 let span = param.span;
1354 let param_name = param.name.ident().name;
1355 let mut err = error_392(tcx, span, param_name);
1356
1357 let suggested_marker_id = tcx.lang_items().phantom_data();
1358 // Help is available only in presence of lang items.
1359 let msg = if let Some(def_id) = suggested_marker_id {
1360 format!(
1361 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1362 param_name,
1363 tcx.def_path_str(def_id),
1364 )
1365 } else {
1366 format!("consider removing `{}` or referring to it in a field", param_name)
1367 };
1368 err.help(&msg);
1369
1370 if matches!(param.kind, rustc_hir::GenericParamKind::Type { .. }) {
1371 err.help(&format!(
1372 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1373 param_name
1374 ));
1375 }
1376 err.emit()
1377 }
1378
1379 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1380 /// aren't true.
1381 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1382 let empty_env = ty::ParamEnv::empty();
1383
1384 let def_id = fcx.tcx.hir().local_def_id(id);
1385 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p);
1386 // Check elaborated bounds.
1387 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1388
1389 for obligation in implied_obligations {
1390 let pred = obligation.predicate;
1391 // Match the existing behavior.
1392 if pred.is_global(fcx.tcx) && !pred.has_late_bound_regions() {
1393 let pred = fcx.normalize_associated_types_in(span, pred);
1394 let obligation = traits::Obligation::new(
1395 traits::ObligationCause::new(span, id, traits::TrivialBound),
1396 empty_env,
1397 pred,
1398 );
1399 fcx.register_predicate(obligation);
1400 }
1401 }
1402
1403 fcx.select_all_obligations_or_error();
1404 }
1405
1406 #[derive(Clone, Copy)]
1407 pub struct CheckTypeWellFormedVisitor<'tcx> {
1408 tcx: TyCtxt<'tcx>,
1409 }
1410
1411 impl CheckTypeWellFormedVisitor<'tcx> {
1412 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1413 CheckTypeWellFormedVisitor { tcx }
1414 }
1415 }
1416
1417 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1418 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1419 Visitor::visit_item(&mut self.clone(), i);
1420 }
1421
1422 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1423 Visitor::visit_trait_item(&mut self.clone(), trait_item);
1424 }
1425
1426 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1427 Visitor::visit_impl_item(&mut self.clone(), impl_item);
1428 }
1429
1430 fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1431 Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1432 }
1433 }
1434
1435 impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1436 type Map = hir_map::Map<'tcx>;
1437
1438 fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
1439 hir_visit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
1440 }
1441
1442 fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
1443 debug!("visit_item: {:?}", i);
1444 self.tcx.ensure().check_item_well_formed(i.def_id);
1445 hir_visit::walk_item(self, i);
1446 }
1447
1448 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1449 debug!("visit_trait_item: {:?}", trait_item);
1450 self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id);
1451 hir_visit::walk_trait_item(self, trait_item);
1452 }
1453
1454 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1455 debug!("visit_impl_item: {:?}", impl_item);
1456 self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id);
1457 hir_visit::walk_impl_item(self, impl_item);
1458 }
1459
1460 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
1461 check_param_wf(self.tcx, p);
1462 hir_visit::walk_generic_param(self, p);
1463 }
1464 }
1465
1466 ///////////////////////////////////////////////////////////////////////////
1467 // ADT
1468
1469 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1470 struct AdtVariant<'tcx> {
1471 /// Types of fields in the variant, that must be well-formed.
1472 fields: Vec<AdtField<'tcx>>,
1473
1474 /// Explicit discriminant of this variant (e.g. `A = 123`),
1475 /// that must evaluate to a constant value.
1476 explicit_discr: Option<LocalDefId>,
1477 }
1478
1479 struct AdtField<'tcx> {
1480 ty: Ty<'tcx>,
1481 def_id: LocalDefId,
1482 span: Span,
1483 }
1484
1485 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1486 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1487 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1488 let fields = struct_def
1489 .fields()
1490 .iter()
1491 .map(|field| {
1492 let def_id = self.tcx.hir().local_def_id(field.hir_id);
1493 let field_ty = self.tcx.type_of(def_id);
1494 let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
1495 let field_ty = self.resolve_vars_if_possible(field_ty);
1496 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1497 AdtField { ty: field_ty, span: field.ty.span, def_id }
1498 })
1499 .collect();
1500 AdtVariant { fields, explicit_discr: None }
1501 }
1502
1503 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1504 enum_def
1505 .variants
1506 .iter()
1507 .map(|variant| AdtVariant {
1508 fields: self.non_enum_variant(&variant.data).fields,
1509 explicit_discr: variant
1510 .disr_expr
1511 .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1512 })
1513 .collect()
1514 }
1515
1516 pub(super) fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1517 match self.tcx.impl_trait_ref(impl_def_id) {
1518 Some(trait_ref) => {
1519 // Trait impl: take implied bounds from all types that
1520 // appear in the trait reference.
1521 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1522 trait_ref.substs.types().collect()
1523 }
1524
1525 None => {
1526 // Inherent impl: take implied bounds from the `self` type.
1527 let self_ty = self.tcx.type_of(impl_def_id);
1528 let self_ty = self.normalize_associated_types_in(span, self_ty);
1529 vec![self_ty]
1530 }
1531 }
1532 }
1533 }
1534
1535 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1536 let mut err =
1537 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1538 err.span_label(span, "unused parameter");
1539 err
1540 }