1 use crate::check::regionck::OutlivesEnvironmentExt;
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
7 use rustc_hir::def_id::{DefId, LocalDefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::ItemKind;
10 use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs};
11 use rustc_infer::infer::outlives::obligations::TypeOutlives;
12 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
13 use rustc_middle::ty::query::Providers;
14 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
15 use rustc_middle::ty::trait_def::TraitSpecializationKind;
16 use rustc_middle::ty::{
17 self, AdtKind, DefIdTree, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable,
18 TypeSuperVisitable, TypeVisitable, TypeVisitor,
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::{sym, Ident, Symbol};
22 use rustc_span::{Span, DUMMY_SP};
23 use rustc_trait_selection::autoderef::Autoderef;
24 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
25 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
26 use rustc_trait_selection::traits::{
27 self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
30 use std::cell::LazyCell;
31 use std::convert::TryInto;
33 use std::ops::{ControlFlow, Deref};
35 pub(super) struct WfCheckingCtxt<'a, 'tcx> {
36 pub(super) ocx: ObligationCtxt<'a, 'tcx>,
39 param_env: ty::ParamEnv<'tcx>,
41 impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
42 type Target = ObligationCtxt<'a, 'tcx>;
43 fn deref(&self) -> &Self::Target {
48 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
49 fn tcx(&self) -> TyCtxt<'tcx> {
53 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
55 T: TypeFoldable<'tcx>,
58 ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)),
64 fn register_wf_obligation(
67 loc: Option<WellFormedLoc>,
68 arg: ty::GenericArg<'tcx>,
71 traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc));
72 // for a type to be WF, we do not need to check if const trait predicates satisfy.
73 let param_env = self.param_env.without_const();
74 self.ocx.register_obligation(traits::Obligation::new(
77 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
82 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
85 body_def_id: LocalDefId,
88 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>),
90 let param_env = tcx.param_env(body_def_id);
91 let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
92 tcx.infer_ctxt().enter(|ref infcx| {
93 let ocx = ObligationCtxt::new(infcx);
95 let assumed_wf_types = ocx.assumed_wf_types(param_env, span, body_def_id);
97 let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
99 if !tcx.features().trivial_bounds {
100 wfcx.check_false_global_bounds()
103 let errors = wfcx.select_all_or_error();
104 if !errors.is_empty() {
105 infcx.report_fulfillment_errors(&errors, None, false);
109 let mut outlives_environment = OutlivesEnvironment::new(param_env);
110 outlives_environment.add_implied_bounds(infcx, assumed_wf_types, body_id);
111 infcx.check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
115 fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
116 let node = tcx.hir().expect_owner(def_id);
118 hir::OwnerNode::Crate(_) => {}
119 hir::OwnerNode::Item(item) => check_item(tcx, item),
120 hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
121 hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
122 hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
125 if let Some(generics) = node.generics() {
126 for param in generics.params {
127 check_param_wf(tcx, param)
132 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
133 /// well-formed, meaning that they do not require any constraints not declared in the struct
134 /// definition itself. For example, this definition would be illegal:
137 /// struct Ref<'a, T> { x: &'a T }
140 /// because the type did not declare that `T:'a`.
142 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
143 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
145 #[instrument(skip(tcx), level = "debug")]
146 fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
147 let def_id = item.def_id;
151 item.name = ? tcx.def_path_str(def_id.to_def_id())
155 // Right now we check that every default trait implementation
156 // has an implementation of itself. Basically, a case like:
158 // impl Trait for T {}
160 // has a requirement of `T: Trait` which was required for default
161 // method implementations. Although this could be improved now that
162 // there's a better infrastructure in place for this, it's being left
163 // for a follow-up work.
165 // Since there's such a requirement, we need to check *just* positive
166 // implementations, otherwise things like:
168 // impl !Send for T {}
170 // won't be allowed unless there's an *explicit* implementation of `Send`
172 hir::ItemKind::Impl(ref impl_) => {
174 .impl_trait_ref(item.def_id)
175 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
176 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
177 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
179 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
180 err.span_labels(impl_.defaultness_span, "default because of this");
181 err.span_label(sp, "auto trait");
184 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
185 match (tcx.impl_polarity(def_id), impl_.polarity) {
186 (ty::ImplPolarity::Positive, _) => {
187 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
189 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
190 // FIXME(#27579): what amount of WF checking do we need for neg impls?
191 if let hir::Defaultness::Default { .. } = impl_.defaultness {
192 let mut spans = vec![span];
193 spans.extend(impl_.defaultness_span);
198 "negative impls cannot be default impls"
203 (ty::ImplPolarity::Reservation, _) => {
204 // FIXME: what amount of WF checking do we need for reservation impls?
209 hir::ItemKind::Fn(ref sig, ..) => {
210 check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
212 hir::ItemKind::Static(ty, ..) => {
213 check_item_type(tcx, item.def_id, ty.span, false);
215 hir::ItemKind::Const(ty, ..) => {
216 check_item_type(tcx, item.def_id, ty.span, false);
218 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
219 check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
221 check_variances_for_type_defn(tcx, item, ast_generics);
223 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
224 check_type_defn(tcx, item, true, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
226 check_variances_for_type_defn(tcx, item, ast_generics);
228 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
229 check_type_defn(tcx, item, true, |wfcx| wfcx.enum_variants(enum_def));
231 check_variances_for_type_defn(tcx, item, ast_generics);
233 hir::ItemKind::Trait(..) => {
234 check_trait(tcx, item);
236 hir::ItemKind::TraitAlias(..) => {
237 check_trait(tcx, item);
239 // `ForeignItem`s are handled separately.
240 hir::ItemKind::ForeignMod { .. } => {}
245 fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
246 let def_id = item.def_id;
250 item.name = ? tcx.def_path_str(def_id.to_def_id())
254 hir::ForeignItemKind::Fn(decl, ..) => {
255 check_item_fn(tcx, item.def_id, item.ident, item.span, decl)
257 hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true),
258 hir::ForeignItemKind::Type => (),
262 fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
263 let def_id = trait_item.def_id;
265 let (method_sig, span) = match trait_item.kind {
266 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
267 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
268 _ => (None, trait_item.span),
270 check_object_unsafe_self_trait_by_name(tcx, trait_item);
271 check_associated_item(tcx, trait_item.def_id, span, method_sig);
273 let encl_trait_def_id = tcx.local_parent(def_id);
274 let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
275 let encl_trait_def_id = encl_trait.def_id.to_def_id();
276 let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
278 } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
284 if let (Some(fn_lang_item_name), "call") =
285 (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
287 // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
288 // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
289 if let Some(hir::FnSig { decl, span, .. }) = method_sig {
290 if let [self_ty, _] = decl.inputs {
291 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
296 "first argument of `call` in `{fn_lang_item_name}` lang item must be a reference",
306 "`call` function in `{fn_lang_item_name}` lang item takes exactly two arguments",
316 "`call` trait item in `{fn_lang_item_name}` lang item must be a function",
324 /// Require that the user writes where clauses on GATs for the implicit
325 /// outlives bounds involving trait parameters in trait functions and
326 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
328 /// We use the following trait as an example throughout this function:
329 /// ```rust,ignore (this code fails due to this lint)
331 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
333 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
336 fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRef]) {
337 // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
338 let mut required_bounds_by_item = FxHashMap::default();
340 // Loop over all GATs together, because if this lint suggests adding a where-clause bound
341 // to one GAT, it might then require us to an additional bound on another GAT.
342 // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
343 // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
346 let mut should_continue = false;
347 for gat_item in associated_items {
348 let gat_def_id = gat_item.id.def_id;
349 let gat_item = tcx.associated_item(gat_def_id);
350 // If this item is not an assoc ty, or has no substs, then it's not a GAT
351 if gat_item.kind != ty::AssocKind::Type {
354 let gat_generics = tcx.generics_of(gat_def_id);
355 // FIXME(jackh726): we can also warn in the more general case
356 if gat_generics.params.is_empty() {
360 // Gather the bounds with which all other items inside of this trait constrain the GAT.
361 // This is calculated by taking the intersection of the bounds that each item
362 // constrains the GAT with individually.
363 let mut new_required_bounds: Option<FxHashSet<ty::Predicate<'_>>> = None;
364 for item in associated_items {
365 let item_def_id = item.id.def_id;
366 // Skip our own GAT, since it does not constrain itself at all.
367 if item_def_id == gat_def_id {
371 let item_hir_id = item.id.hir_id();
372 let param_env = tcx.param_env(item_def_id);
374 let item_required_bounds = match item.kind {
375 // In our example, this corresponds to `into_iter` method
376 hir::AssocItemKind::Fn { .. } => {
377 // For methods, we check the function signature's return type for any GATs
378 // to constrain. In the `into_iter` case, we see that the return type
379 // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
380 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
381 item_def_id.to_def_id(),
382 tcx.fn_sig(item_def_id),
389 // We also assume that all of the function signature's parameter types
391 &sig.inputs().iter().copied().collect(),
396 // In our example, this corresponds to the `Iter` and `Item` associated types
397 hir::AssocItemKind::Type => {
398 // If our associated item is a GAT with missing bounds, add them to
399 // the param-env here. This allows this GAT to propagate missing bounds
401 let param_env = augment_param_env(
404 required_bounds_by_item.get(&item_def_id),
410 tcx.explicit_item_bounds(item_def_id)
413 .collect::<Vec<_>>(),
414 &FxHashSet::default(),
419 hir::AssocItemKind::Const => None,
422 if let Some(item_required_bounds) = item_required_bounds {
423 // Take the intersection of the required bounds for this GAT, and
424 // the item_required_bounds which are the ones implied by just
426 // This is why we use an Option<_>, since we need to distinguish
427 // the empty set of bounds from the _uninitialized_ set of bounds.
428 if let Some(new_required_bounds) = &mut new_required_bounds {
429 new_required_bounds.retain(|b| item_required_bounds.contains(b));
431 new_required_bounds = Some(item_required_bounds);
436 if let Some(new_required_bounds) = new_required_bounds {
437 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
438 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
439 // Iterate until our required_bounds no longer change
440 // Since they changed here, we should continue the loop
441 should_continue = true;
445 // We know that this loop will eventually halt, since we only set `should_continue` if the
446 // `required_bounds` for this item grows. Since we are not creating any new region or type
447 // variables, the set of all region and type bounds that we could ever insert are limited
448 // by the number of unique types and regions we observe in a given item.
449 if !should_continue {
454 for (gat_def_id, required_bounds) in required_bounds_by_item {
455 let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id);
456 debug!(?required_bounds);
457 let param_env = tcx.param_env(gat_def_id);
458 let gat_hir = gat_item_hir.hir_id();
460 let mut unsatisfied_bounds: Vec<_> = required_bounds
462 .filter(|clause| match clause.kind().skip_binder() {
463 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
464 !region_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
466 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
467 !ty_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
469 _ => bug!("Unexpected PredicateKind"),
471 .map(|clause| clause.to_string())
474 // We sort so that order is predictable
475 unsatisfied_bounds.sort();
477 if !unsatisfied_bounds.is_empty() {
478 let plural = pluralize!(unsatisfied_bounds.len());
479 let mut err = tcx.sess.struct_span_err(
481 &format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
484 let suggestion = format!(
486 gat_item_hir.generics.add_where_or_trailing_comma(),
487 unsatisfied_bounds.join(", "),
490 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
491 &format!("add the required where clause{plural}"),
493 Applicability::MachineApplicable,
497 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
499 "{} currently required to ensure that impls have maximum flexibility",
503 "we are soliciting feedback, see issue #87479 \
504 <https://github.com/rust-lang/rust/issues/87479> \
505 for more information",
513 /// Add a new set of predicates to the caller_bounds of an existing param_env.
514 fn augment_param_env<'tcx>(
516 param_env: ty::ParamEnv<'tcx>,
517 new_predicates: Option<&FxHashSet<ty::Predicate<'tcx>>>,
518 ) -> ty::ParamEnv<'tcx> {
519 let Some(new_predicates) = new_predicates else {
523 if new_predicates.is_empty() {
528 tcx.mk_predicates(param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()));
529 // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
530 // i.e. traits::normalize_param_env_or_error
531 ty::ParamEnv::new(bounds, param_env.reveal(), param_env.constness())
534 /// We use the following trait as an example throughout this function.
535 /// Specifically, let's assume that `to_check` here is the return type
536 /// of `into_iter`, and the GAT we are checking this for is `Iter`.
537 /// ```rust,ignore (this code fails due to this lint)
539 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
541 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
544 fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>(
546 param_env: ty::ParamEnv<'tcx>,
547 item_hir: hir::HirId,
549 wf_tys: &FxHashSet<Ty<'tcx>>,
550 gat_def_id: LocalDefId,
551 gat_generics: &'tcx ty::Generics,
552 ) -> Option<FxHashSet<ty::Predicate<'tcx>>> {
553 // The bounds we that we would require from `to_check`
554 let mut bounds = FxHashSet::default();
556 let (regions, types) = GATSubstCollector::visit(gat_def_id.to_def_id(), to_check);
558 // If both regions and types are empty, then this GAT isn't in the
559 // set of types we are checking, and we shouldn't try to do clause analysis
560 // (particularly, doing so would end up with an empty set of clauses,
561 // since the current method would require none, and we take the
562 // intersection of requirements of all methods)
563 if types.is_empty() && regions.is_empty() {
567 for (region_a, region_a_idx) in ®ions {
568 // Ignore `'static` lifetimes for the purpose of this lint: it's
569 // because we know it outlives everything and so doesn't give meaningful
571 if let ty::ReStatic = **region_a {
574 // For each region argument (e.g., `'a` in our example), check for a
575 // relationship to the type arguments (e.g., `Self`). If there is an
576 // outlives relationship (`Self: 'a`), then we want to ensure that is
577 // reflected in a where clause on the GAT itself.
578 for (ty, ty_idx) in &types {
579 // In our example, requires that `Self: 'a`
580 if ty_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *ty, *region_a) {
581 debug!(?ty_idx, ?region_a_idx);
582 debug!("required clause: {ty} must outlive {region_a}");
583 // Translate into the generic parameters of the GAT. In
584 // our example, the type was `Self`, which will also be
585 // `Self` in the GAT.
586 let ty_param = gat_generics.param_at(*ty_idx, tcx);
588 .mk_ty(ty::Param(ty::ParamTy { index: ty_param.index, name: ty_param.name }));
589 // Same for the region. In our example, 'a corresponds
590 // to the 'me parameter.
591 let region_param = gat_generics.param_at(*region_a_idx, tcx);
593 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
594 def_id: region_param.def_id,
595 index: region_param.index,
596 name: region_param.name,
598 // The predicate we expect to see. (In our example,
601 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param));
602 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
603 bounds.insert(clause);
607 // For each region argument (e.g., `'a` in our example), also check for a
608 // relationship to the other region arguments. If there is an outlives
609 // relationship, then we want to ensure that is reflected in the where clause
610 // on the GAT itself.
611 for (region_b, region_b_idx) in ®ions {
612 // Again, skip `'static` because it outlives everything. Also, we trivially
613 // know that a region outlives itself.
614 if ty::ReStatic == **region_b || region_a == region_b {
617 if region_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *region_a, *region_b) {
618 debug!(?region_a_idx, ?region_b_idx);
619 debug!("required clause: {region_a} must outlive {region_b}");
620 // Translate into the generic parameters of the GAT.
621 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
623 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
624 def_id: region_a_param.def_id,
625 index: region_a_param.index,
626 name: region_a_param.name,
628 // Same for the region.
629 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
631 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
632 def_id: region_b_param.def_id,
633 index: region_b_param.index,
634 name: region_b_param.name,
636 // The predicate we expect to see.
637 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
641 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
642 bounds.insert(clause);
650 /// Given a known `param_env` and a set of well formed types, can we prove that
651 /// `ty` outlives `region`.
652 fn ty_known_to_outlive<'tcx>(
655 param_env: ty::ParamEnv<'tcx>,
656 wf_tys: &FxHashSet<Ty<'tcx>>,
658 region: ty::Region<'tcx>,
660 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
661 let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
662 let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
663 outlives.type_must_outlive(origin, ty, region);
667 /// Given a known `param_env` and a set of well formed types, can we prove that
668 /// `region_a` outlives `region_b`
669 fn region_known_to_outlive<'tcx>(
672 param_env: ty::ParamEnv<'tcx>,
673 wf_tys: &FxHashSet<Ty<'tcx>>,
674 region_a: ty::Region<'tcx>,
675 region_b: ty::Region<'tcx>,
677 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
678 use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
679 let origin = infer::RelateRegionParamBound(DUMMY_SP);
680 // `region_a: region_b` -> `region_b <= region_a`
681 infcx.push_sub_region_constraint(origin, region_b, region_a);
685 /// Given a known `param_env` and a set of well formed types, set up an
686 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
687 /// to be tested), then resolve region and return errors
688 fn resolve_regions_with_wf_tys<'tcx>(
691 param_env: ty::ParamEnv<'tcx>,
692 wf_tys: &FxHashSet<Ty<'tcx>>,
693 add_constraints: impl for<'a> FnOnce(&'a InferCtxt<'a, 'tcx>, &'a RegionBoundPairs<'tcx>),
695 // Unfortunately, we have to use a new `InferCtxt` each call, because
696 // region constraints get added and solved there and we need to test each
697 // call individually.
698 tcx.infer_ctxt().enter(|infcx| {
699 let mut outlives_environment = OutlivesEnvironment::new(param_env);
700 outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
701 let region_bound_pairs = outlives_environment.region_bound_pairs();
703 add_constraints(&infcx, region_bound_pairs);
705 let errors = infcx.resolve_regions(&outlives_environment);
707 debug!(?errors, "errors");
709 // If we were able to prove that the type outlives the region without
710 // an error, it must be because of the implied or explicit bounds...
715 /// TypeVisitor that looks for uses of GATs like
716 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
717 /// the two vectors, `regions` and `types` (depending on their kind). For each
718 /// parameter `Pi` also track the index `i`.
719 struct GATSubstCollector<'tcx> {
721 // Which region appears and which parameter index its substituted for
722 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
723 // Which params appears and which parameter index its substituted for
724 types: FxHashSet<(Ty<'tcx>, usize)>,
727 impl<'tcx> GATSubstCollector<'tcx> {
728 fn visit<T: TypeFoldable<'tcx>>(
731 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
733 GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
734 t.visit_with(&mut visitor);
735 (visitor.regions, visitor.types)
739 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
742 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
744 ty::Projection(p) if p.item_def_id == self.gat => {
745 for (idx, subst) in p.substs.iter().enumerate() {
746 match subst.unpack() {
747 GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
748 self.regions.insert((lt, idx));
750 GenericArgKind::Type(t) => {
751 self.types.insert((t, idx));
759 t.super_visit_with(self)
763 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
765 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
766 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
773 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
774 /// When this is done, suggest using `Self` instead.
775 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
776 let (trait_name, trait_def_id) =
777 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
778 hir::Node::Item(item) => match item.kind {
779 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
784 let mut trait_should_be_self = vec![];
786 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
787 if could_be_self(trait_def_id, ty) =>
789 trait_should_be_self.push(ty.span)
791 hir::TraitItemKind::Fn(sig, _) => {
792 for ty in sig.decl.inputs {
793 if could_be_self(trait_def_id, ty) {
794 trait_should_be_self.push(ty.span);
797 match sig.decl.output {
798 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
799 trait_should_be_self.push(ty.span);
806 if !trait_should_be_self.is_empty() {
807 if tcx.object_safety_violations(trait_def_id).is_empty() {
810 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
813 trait_should_be_self,
814 "associated item referring to unboxed trait object for its own trait",
816 .span_label(trait_name.span, "in this trait")
817 .multipart_suggestion(
818 "you might have meant to use `Self` to refer to the implementing type",
820 Applicability::MachineApplicable,
826 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
827 let def_id = impl_item.def_id;
829 let (method_sig, span) = match impl_item.kind {
830 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
831 // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
832 hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
833 _ => (None, impl_item.span),
836 check_associated_item(tcx, def_id, span, method_sig);
839 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
841 // We currently only check wf of const params here.
842 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
844 // Const parameters are well formed if their type is structural match.
845 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
846 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
848 if tcx.features().adt_const_params {
849 if let Some(non_structural_match_ty) =
850 traits::search_for_adt_const_param_violation(param.span, tcx, ty)
852 // We use the same error code in both branches, because this is really the same
853 // issue: we just special-case the message for type parameters to make it
855 match non_structural_match_ty.kind() {
857 // Const parameters may not have type parameters as their types,
858 // because we cannot be sure that the type parameter derives `PartialEq`
859 // and `Eq` (just implementing them is not enough for `structural_match`).
864 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
865 used as the type of a const parameter",
869 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
872 "it is not currently possible to use a type parameter as the type of a \
882 "`{ty}` is forbidden as the type of a const generic parameter",
884 .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
892 "using function pointers as const generic parameters is forbidden",
901 "using raw pointers as const generic parameters is forbidden",
906 let mut diag = struct_span_err!(
910 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
911 the type of a const parameter",
912 non_structural_match_ty,
915 if ty == non_structural_match_ty {
918 format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
928 let mut is_ptr = true;
930 let err = match ty.kind() {
931 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
932 ty::FnPtr(_) => Some("function pointers"),
933 ty::RawPtr(_) => Some("raw pointers"),
936 err_ty_str = format!("`{ty}`");
937 Some(err_ty_str.as_str())
941 if let Some(unsupported_type) = err {
946 "using {unsupported_type} as const generic parameters is forbidden",
950 let mut err = tcx.sess.struct_span_err(
953 "{unsupported_type} is forbidden as the type of a const generic parameter",
956 err.note("the only supported types are integers, `bool` and `char`");
957 if tcx.sess.is_nightly_build() {
959 "more complex types are supported with `#![feature(adt_const_params)]`",
970 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
971 fn check_associated_item(
975 sig_if_method: Option<&hir::FnSig<'_>>,
977 let loc = Some(WellFormedLoc::Ty(item_id));
978 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
979 let item = tcx.associated_item(item_id);
981 let self_ty = match item.container {
982 ty::TraitContainer => tcx.types.self_param,
983 ty::ImplContainer => tcx.type_of(item.container_id(tcx)),
987 ty::AssocKind::Const => {
988 let ty = tcx.type_of(item.def_id);
989 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
990 wfcx.register_wf_obligation(span, loc, ty.into());
992 ty::AssocKind::Fn => {
993 let sig = tcx.fn_sig(item.def_id);
994 let hir_sig = sig_if_method.expect("bad signature for method");
997 item.ident(tcx).span,
1000 item.def_id.expect_local(),
1002 check_method_receiver(wfcx, hir_sig, item, self_ty);
1004 ty::AssocKind::Type => {
1005 if let ty::AssocItemContainer::TraitContainer = item.container {
1006 check_associated_type_bounds(wfcx, item, span)
1008 if item.defaultness(tcx).has_value() {
1009 let ty = tcx.type_of(item.def_id);
1010 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1011 wfcx.register_wf_obligation(span, loc, ty.into());
1018 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1020 ItemKind::Struct(..) => Some(AdtKind::Struct),
1021 ItemKind::Union(..) => Some(AdtKind::Union),
1022 ItemKind::Enum(..) => Some(AdtKind::Enum),
1027 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1028 fn check_type_defn<'tcx, F>(
1030 item: &hir::Item<'tcx>,
1032 mut lookup_fields: F,
1034 F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
1036 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1037 let variants = lookup_fields(wfcx);
1038 let packed = tcx.adt_def(item.def_id).repr().packed();
1040 for variant in &variants {
1041 // All field types must be well-formed.
1042 for field in &variant.fields {
1043 wfcx.register_wf_obligation(
1045 Some(WellFormedLoc::Ty(field.def_id)),
1050 // For DST, or when drop needs to copy things around, all
1051 // intermediate types must be sized.
1052 let needs_drop_copy = || {
1054 let ty = variant.fields.last().unwrap().ty;
1055 let ty = tcx.erase_regions(ty);
1056 if ty.needs_infer() {
1058 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1059 // Just treat unresolved type expression as if it needs drop.
1062 ty.needs_drop(tcx, tcx.param_env(item.def_id))
1066 // All fields (except for possibly the last) should be sized.
1067 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1068 let unsized_len = if all_sized { 0 } else { 1 };
1070 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1072 let last = idx == variant.fields.len() - 1;
1073 wfcx.register_bound(
1074 traits::ObligationCause::new(
1077 traits::FieldSized {
1078 adt_kind: match item_adt_kind(&item.kind) {
1088 tcx.require_lang_item(LangItem::Sized, None),
1092 // Explicit `enum` discriminant values must const-evaluate successfully.
1093 if let Some(discr_def_id) = variant.explicit_discr {
1094 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
1096 let cause = traits::ObligationCause::new(
1097 tcx.def_span(discr_def_id),
1099 traits::MiscObligation,
1101 wfcx.register_obligation(traits::Obligation::new(
1104 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
1105 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
1113 check_where_clauses(wfcx, item.span, item.def_id);
1117 #[instrument(skip(tcx, item))]
1118 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1119 debug!(?item.def_id);
1121 let trait_def = tcx.trait_def(item.def_id);
1122 if trait_def.is_marker
1123 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1125 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1128 tcx.def_span(*associated_def_id),
1130 "marker traits cannot have associated items",
1136 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1137 check_where_clauses(wfcx, item.span, item.def_id)
1140 // Only check traits, don't check trait aliases
1141 if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1142 check_gat_where_clauses(tcx, items);
1146 /// Checks all associated type defaults of trait `trait_def_id`.
1148 /// Assuming the defaults are used, check that all predicates (bounds on the
1149 /// assoc type and where clauses on the trait) hold.
1150 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1151 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1153 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1154 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1155 let normalized_bound = wfcx.normalize(span, None, bound);
1156 traits::wf::predicate_obligations(
1165 wfcx.register_obligations(wf_obligations);
1173 decl: &hir::FnDecl<'_>,
1175 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1176 let sig = tcx.fn_sig(def_id);
1177 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1181 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1182 debug!("check_item_type: {:?}", item_id);
1184 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1185 let ty = tcx.type_of(item_id);
1186 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1188 let mut forbid_unsized = true;
1189 if allow_foreign_ty {
1190 let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1191 if let ty::Foreign(_) = tail.kind() {
1192 forbid_unsized = false;
1196 wfcx.register_wf_obligation(
1198 Some(WellFormedLoc::Ty(item_id)),
1202 wfcx.register_bound(
1203 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
1206 tcx.require_lang_item(LangItem::Sized, None),
1210 // Ensure that the end result is `Sync` in a non-thread local `static`.
1211 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1212 == Some(hir::Mutability::Not)
1213 && !tcx.is_foreign_item(item_id.to_def_id())
1214 && !tcx.is_thread_local_static(item_id.to_def_id());
1216 if should_check_for_sync {
1217 wfcx.register_bound(
1218 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
1221 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1227 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1228 fn check_impl<'tcx>(
1230 item: &'tcx hir::Item<'tcx>,
1231 ast_self_ty: &hir::Ty<'_>,
1232 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1233 constness: hir::Constness,
1235 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1236 match *ast_trait_ref {
1237 Some(ref ast_trait_ref) => {
1238 // `#[rustc_reservation_impl]` impls are not real impls and
1239 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1241 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1242 let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
1243 let trait_pred = ty::TraitPredicate {
1245 constness: match constness {
1246 hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1247 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1249 polarity: ty::ImplPolarity::Positive,
1251 let obligations = traits::wf::trait_obligations(
1256 ast_trait_ref.path.span,
1259 debug!(?obligations);
1260 wfcx.register_obligations(obligations);
1263 let self_ty = tcx.type_of(item.def_id);
1264 let self_ty = wfcx.normalize(item.span, None, self_ty);
1265 wfcx.register_wf_obligation(
1267 Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1273 check_where_clauses(wfcx, item.span, item.def_id);
1277 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1278 #[instrument(level = "debug", skip(wfcx))]
1279 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1280 let infcx = wfcx.infcx;
1281 let tcx = wfcx.tcx();
1283 let predicates = tcx.bound_predicates_of(def_id.to_def_id());
1284 let generics = tcx.generics_of(def_id);
1286 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1287 GenericParamDefKind::Type { has_default, .. }
1288 | GenericParamDefKind::Const { has_default } => {
1289 has_default && def.index >= generics.parent_count as u32
1291 GenericParamDefKind::Lifetime => unreachable!(),
1294 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1295 // For example, this forbids the declaration:
1297 // struct Foo<T = Vec<[u32]>> { .. }
1299 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1300 for param in &generics.params {
1302 GenericParamDefKind::Type { .. } => {
1303 if is_our_default(param) {
1304 let ty = tcx.type_of(param.def_id);
1305 // Ignore dependent defaults -- that is, where the default of one type
1306 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1307 // be sure if it will error or not as user might always specify the other.
1308 if !ty.needs_subst() {
1309 wfcx.register_wf_obligation(
1310 tcx.def_span(param.def_id),
1317 GenericParamDefKind::Const { .. } => {
1318 if is_our_default(param) {
1319 // FIXME(const_generics_defaults): This
1320 // is incorrect when dealing with unused substs, for example
1321 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1322 // we should eagerly error.
1323 let default_ct = tcx.const_param_default(param.def_id);
1324 if !default_ct.needs_subst() {
1325 wfcx.register_wf_obligation(
1326 tcx.def_span(param.def_id),
1333 // Doesn't have defaults.
1334 GenericParamDefKind::Lifetime => {}
1338 // Check that trait predicates are WF when params are substituted by their defaults.
1339 // We don't want to overly constrain the predicates that may be written but we want to
1340 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1341 // Therefore we check if a predicate which contains a single type param
1342 // with a concrete default is WF with that default substituted.
1343 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1345 // First we build the defaulted substitution.
1346 let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1348 GenericParamDefKind::Lifetime => {
1349 // All regions are identity.
1350 tcx.mk_param_from_def(param)
1353 GenericParamDefKind::Type { .. } => {
1354 // If the param has a default, ...
1355 if is_our_default(param) {
1356 let default_ty = tcx.type_of(param.def_id);
1357 // ... and it's not a dependent default, ...
1358 if !default_ty.needs_subst() {
1359 // ... then substitute it with the default.
1360 return default_ty.into();
1364 tcx.mk_param_from_def(param)
1366 GenericParamDefKind::Const { .. } => {
1367 // If the param has a default, ...
1368 if is_our_default(param) {
1369 let default_ct = tcx.const_param_default(param.def_id);
1370 // ... and it's not a dependent default, ...
1371 if !default_ct.needs_subst() {
1372 // ... then substitute it with the default.
1373 return default_ct.into();
1377 tcx.mk_param_from_def(param)
1382 // Now we build the substituted predicates.
1383 let default_obligations = predicates
1387 .flat_map(|&(pred, sp)| {
1389 struct CountParams {
1390 params: FxHashSet<u32>,
1392 impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1395 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1396 if let ty::Param(param) = t.kind() {
1397 self.params.insert(param.index);
1399 t.super_visit_with(self)
1402 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1406 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1407 if let ty::ConstKind::Param(param) = c.kind() {
1408 self.params.insert(param.index);
1410 c.super_visit_with(self)
1413 let mut param_count = CountParams::default();
1414 let has_region = pred.visit_with(&mut param_count).is_break();
1415 let substituted_pred = predicates.rebind(pred).subst(tcx, substs);
1416 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1417 // or preds with multiple params.
1418 if substituted_pred.has_param_types_or_consts()
1419 || param_count.params.len() > 1
1423 } else if predicates.0.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1424 // Avoid duplication of predicates that contain no parameters, for example.
1427 Some((substituted_pred, sp))
1431 // Convert each of those into an obligation. So if you have
1432 // something like `struct Foo<T: Copy = String>`, we would
1433 // take that predicate `T: Copy`, substitute to `String: Copy`
1434 // (actually that happens in the previous `flat_map` call),
1435 // and then try to prove it (in this case, we'll fail).
1437 // Note the subtle difference from how we handle `predicates`
1438 // below: there, we are not trying to prove those predicates
1439 // to be *true* but merely *well-formed*.
1440 let pred = wfcx.normalize(sp, None, pred);
1441 let cause = traits::ObligationCause::new(
1444 traits::ItemObligation(def_id.to_def_id()),
1446 traits::Obligation::new(cause, wfcx.param_env, pred)
1449 let predicates = predicates.0.instantiate_identity(tcx);
1451 let predicates = wfcx.normalize(span, None, predicates);
1453 debug!(?predicates.predicates);
1454 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1455 let wf_obligations =
1456 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1457 traits::wf::predicate_obligations(infcx, wfcx.param_env.without_const(), wfcx.body_id, p, sp)
1460 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1461 wfcx.register_obligations(obligations);
1464 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1465 fn check_fn_or_method<'tcx>(
1466 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1468 sig: ty::PolyFnSig<'tcx>,
1469 hir_decl: &hir::FnDecl<'_>,
1472 let tcx = wfcx.tcx();
1473 let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1475 // Normalize the input and output types one at a time, using a different
1476 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1477 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1478 // for each type, preventing the HIR wf check from generating
1479 // a nice error message.
1480 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1481 inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1484 Some(WellFormedLoc::Param {
1486 // Note that the `param_idx` of the output type is
1487 // one greater than the index of the last input type.
1488 param_idx: i.try_into().unwrap(),
1493 // Manually call `normalize_associated_types_in` on the other types
1494 // in `FnSig`. This ensures that if the types of these fields
1495 // ever change to include projections, we will start normalizing
1496 // them automatically.
1497 let sig = ty::FnSig {
1499 c_variadic: wfcx.normalize(span, None, c_variadic),
1500 unsafety: wfcx.normalize(span, None, unsafety),
1501 abi: wfcx.normalize(span, None, abi),
1504 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1505 wfcx.register_wf_obligation(
1507 Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1512 wfcx.register_wf_obligation(
1513 hir_decl.output.span(),
1515 sig.output().into(),
1518 check_where_clauses(wfcx, span, def_id);
1521 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1522 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1523 of the previous types except `Self`)";
1525 #[tracing::instrument(level = "debug", skip(wfcx))]
1526 fn check_method_receiver<'tcx>(
1527 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1528 fn_sig: &hir::FnSig<'_>,
1529 method: &ty::AssocItem,
1532 let tcx = wfcx.tcx();
1534 if !method.fn_has_self_parameter {
1538 let span = fn_sig.decl.inputs[0].span;
1540 let sig = tcx.fn_sig(method.def_id);
1541 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1542 let sig = wfcx.normalize(span, None, sig);
1544 debug!("check_method_receiver: sig={:?}", sig);
1546 let self_ty = wfcx.normalize(span, None, self_ty);
1548 let receiver_ty = sig.inputs()[0];
1549 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1551 if tcx.features().arbitrary_self_types {
1552 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1553 // Report error; `arbitrary_self_types` was enabled.
1554 e0307(tcx, span, receiver_ty);
1557 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1558 if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1559 // Report error; would have worked with `arbitrary_self_types`.
1561 &tcx.sess.parse_sess,
1562 sym::arbitrary_self_types,
1565 "`{receiver_ty}` cannot be used as the type of `self` without \
1566 the `arbitrary_self_types` feature",
1569 .help(HELP_FOR_SELF_TYPE)
1572 // Report error; would not have worked with `arbitrary_self_types`.
1573 e0307(tcx, span, receiver_ty);
1579 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1581 tcx.sess.diagnostic(),
1584 "invalid `self` parameter type: {receiver_ty}"
1586 .note("type of `self` must be `Self` or a type that dereferences to it")
1587 .help(HELP_FOR_SELF_TYPE)
1591 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1592 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1593 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1594 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1595 /// `Deref<Target = self_ty>`.
1597 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1598 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1599 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1600 fn receiver_is_valid<'tcx>(
1601 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1603 receiver_ty: Ty<'tcx>,
1605 arbitrary_self_types_enabled: bool,
1607 let infcx = wfcx.infcx;
1608 let tcx = wfcx.tcx();
1610 ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1612 let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1614 // `self: Self` is always valid.
1615 if can_eq_self(receiver_ty) {
1616 if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1617 infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1623 Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1625 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1626 if arbitrary_self_types_enabled {
1627 autoderef = autoderef.include_raw_pointers();
1630 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1633 let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1635 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1637 if let Some((potential_self_ty, _)) = autoderef.next() {
1639 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1640 potential_self_ty, self_ty
1643 if can_eq_self(potential_self_ty) {
1644 wfcx.register_obligations(autoderef.into_obligations());
1647 wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1649 infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1654 // Without `feature(arbitrary_self_types)`, we require that each step in the
1655 // deref chain implement `receiver`
1656 if !arbitrary_self_types_enabled
1657 && !receiver_is_implemented(
1659 receiver_trait_def_id,
1668 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1669 // If the receiver already has errors reported due to it, consider it valid to avoid
1670 // unnecessary errors (#58712).
1671 return receiver_ty.references_error();
1675 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1676 if !arbitrary_self_types_enabled
1677 && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1685 fn receiver_is_implemented<'tcx>(
1686 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1687 receiver_trait_def_id: DefId,
1688 cause: ObligationCause<'tcx>,
1689 receiver_ty: Ty<'tcx>,
1691 let tcx = wfcx.tcx();
1692 let trait_ref = ty::Binder::dummy(ty::TraitRef {
1693 def_id: receiver_trait_def_id,
1694 substs: tcx.mk_substs_trait(receiver_ty, &[]),
1698 traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1700 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1704 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1711 fn check_variances_for_type_defn<'tcx>(
1713 item: &hir::Item<'tcx>,
1714 hir_generics: &hir::Generics<'_>,
1716 let ty = tcx.type_of(item.def_id);
1717 if tcx.has_error_field(ty) {
1721 let ty_predicates = tcx.predicates_of(item.def_id);
1722 assert_eq!(ty_predicates.parent, None);
1723 let variances = tcx.variances_of(item.def_id);
1725 let mut constrained_parameters: FxHashSet<_> = variances
1728 .filter(|&(_, &variance)| variance != ty::Bivariant)
1729 .map(|(index, _)| Parameter(index as u32))
1732 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1734 // Lazily calculated because it is only needed in case of an error.
1735 let explicitly_bounded_params = LazyCell::new(|| {
1736 let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1740 .filter_map(|predicate| match predicate {
1741 hir::WherePredicate::BoundPredicate(predicate) => {
1742 match icx.to_ty(predicate.bounded_ty).kind() {
1743 ty::Param(data) => Some(Parameter(data.index)),
1749 .collect::<FxHashSet<_>>()
1752 for (index, _) in variances.iter().enumerate() {
1753 let parameter = Parameter(index as u32);
1755 if constrained_parameters.contains(¶meter) {
1759 let param = &hir_generics.params[index];
1762 hir::ParamName::Error => {}
1764 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
1765 report_bivariance(tcx, param, has_explicit_bounds);
1771 fn report_bivariance(
1773 param: &rustc_hir::GenericParam<'_>,
1774 has_explicit_bounds: bool,
1775 ) -> ErrorGuaranteed {
1776 let span = param.span;
1777 let param_name = param.name.ident().name;
1778 let mut err = error_392(tcx, span, param_name);
1780 let suggested_marker_id = tcx.lang_items().phantom_data();
1781 // Help is available only in presence of lang items.
1782 let msg = if let Some(def_id) = suggested_marker_id {
1784 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1786 tcx.def_path_str(def_id),
1789 format!("consider removing `{param_name}` or referring to it in a field")
1793 if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1795 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1802 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1803 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1805 fn check_false_global_bounds(&mut self) {
1806 let tcx = self.ocx.infcx.tcx;
1807 let mut span = self.span;
1808 let empty_env = ty::ParamEnv::empty();
1810 let def_id = tcx.hir().local_def_id(self.body_id);
1811 let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1812 // Check elaborated bounds.
1813 let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1815 for obligation in implied_obligations {
1816 // We lower empty bounds like `Vec<dyn Copy>:` as
1817 // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1818 // regular WF checking
1819 if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1822 let pred = obligation.predicate;
1823 // Match the existing behavior.
1824 if pred.is_global() && !pred.has_late_bound_regions() {
1825 let pred = self.normalize(span, None, pred);
1826 let hir_node = tcx.hir().find(self.body_id);
1828 // only use the span of the predicate clause (#90869)
1830 if let Some(hir::Generics { predicates, .. }) =
1831 hir_node.and_then(|node| node.generics())
1833 let obligation_span = obligation.cause.span();
1837 // There seems to be no better way to find out which predicate we are in
1838 .find(|pred| pred.span().contains(obligation_span))
1839 .map(|pred| pred.span())
1840 .unwrap_or(obligation_span);
1843 let obligation = traits::Obligation::new(
1844 traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1848 self.ocx.register_obligation(obligation);
1854 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1855 let items = tcx.hir_module_items(module);
1856 items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1857 items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1858 items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1859 items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1862 ///////////////////////////////////////////////////////////////////////////
1865 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1866 struct AdtVariant<'tcx> {
1867 /// Types of fields in the variant, that must be well-formed.
1868 fields: Vec<AdtField<'tcx>>,
1870 /// Explicit discriminant of this variant (e.g. `A = 123`),
1871 /// that must evaluate to a constant value.
1872 explicit_discr: Option<LocalDefId>,
1875 struct AdtField<'tcx> {
1881 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1882 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1883 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1884 let fields = struct_def
1888 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1889 let field_ty = self.tcx().type_of(def_id);
1890 let field_ty = self.normalize(field.ty.span, None, field_ty);
1891 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1892 AdtField { ty: field_ty, span: field.ty.span, def_id }
1895 AdtVariant { fields, explicit_discr: None }
1898 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1902 .map(|variant| AdtVariant {
1903 fields: self.non_enum_variant(&variant.data).fields,
1904 explicit_discr: variant
1906 .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1916 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1917 let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1918 err.span_label(span, "unused parameter");
1922 pub fn provide(providers: &mut Providers) {
1923 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };