1 use crate::autoderef::Autoderef;
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
7 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::lang_items::LangItem;
11 use rustc_hir::ItemKind;
12 use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs};
13 use rustc_infer::infer::outlives::obligations::TypeOutlives;
14 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15 use rustc_middle::mir::ConstraintCategory;
16 use rustc_middle::ty::query::Providers;
17 use rustc_middle::ty::trait_def::TraitSpecializationKind;
18 use rustc_middle::ty::{
19 self, AdtKind, DefIdTree, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
20 TypeVisitable, TypeVisitor,
22 use rustc_middle::ty::{GenericArgKind, InternalSubsts};
23 use rustc_session::parse::feature_err;
24 use rustc_span::symbol::{sym, Ident, Symbol};
25 use rustc_span::{Span, DUMMY_SP};
26 use rustc_target::spec::abi::Abi;
27 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
28 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
29 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_trait_selection::traits::{
31 self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
34 use std::cell::LazyCell;
35 use std::ops::{ControlFlow, Deref};
37 pub(super) struct WfCheckingCtxt<'a, 'tcx> {
38 pub(super) ocx: ObligationCtxt<'a, 'tcx>,
40 body_def_id: LocalDefId,
41 param_env: ty::ParamEnv<'tcx>,
43 impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
44 type Target = ObligationCtxt<'a, 'tcx>;
45 fn deref(&self) -> &Self::Target {
50 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
51 fn tcx(&self) -> TyCtxt<'tcx> {
55 // Convenience function to normalize during wfcheck. This performs
56 // `ObligationCtxt::normalize`, but provides a nice `ObligationCauseCode`.
57 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
59 T: TypeFoldable<'tcx>,
62 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
68 fn register_wf_obligation(
71 loc: Option<WellFormedLoc>,
72 arg: ty::GenericArg<'tcx>,
74 let cause = traits::ObligationCause::new(
77 ObligationCauseCode::WellFormed(loc),
79 // for a type to be WF, we do not need to check if const trait predicates satisfy.
80 let param_env = self.param_env.without_const();
81 self.ocx.register_obligation(traits::Obligation::new(
85 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)),
90 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
93 body_def_id: LocalDefId,
96 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>),
98 let param_env = tcx.param_env(body_def_id);
99 let infcx = &tcx.infer_ctxt().build();
100 let ocx = ObligationCtxt::new(infcx);
102 let mut wfcx = WfCheckingCtxt { ocx, span, body_def_id, param_env };
104 if !tcx.features().trivial_bounds {
105 wfcx.check_false_global_bounds()
109 let assumed_wf_types = wfcx.ocx.assumed_wf_types(param_env, span, body_def_id);
110 let implied_bounds = infcx.implied_bounds_tys(param_env, body_def_id, assumed_wf_types);
112 let errors = wfcx.select_all_or_error();
113 if !errors.is_empty() {
114 infcx.err_ctxt().report_fulfillment_errors(&errors, None);
118 let outlives_environment =
119 OutlivesEnvironment::with_bounds(param_env, Some(infcx), implied_bounds);
123 .check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
126 fn check_well_formed(tcx: TyCtxt<'_>, def_id: hir::OwnerId) {
127 let node = tcx.hir().owner(def_id);
129 hir::OwnerNode::Crate(_) => {}
130 hir::OwnerNode::Item(item) => check_item(tcx, item),
131 hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
132 hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
133 hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
136 if let Some(generics) = node.generics() {
137 for param in generics.params {
138 check_param_wf(tcx, param)
143 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
144 /// well-formed, meaning that they do not require any constraints not declared in the struct
145 /// definition itself. For example, this definition would be illegal:
148 /// struct Ref<'a, T> { x: &'a T }
151 /// because the type did not declare that `T:'a`.
153 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
154 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
156 #[instrument(skip(tcx), level = "debug")]
157 fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
158 let def_id = item.owner_id.def_id;
162 item.name = ? tcx.def_path_str(def_id.to_def_id())
166 // Right now we check that every default trait implementation
167 // has an implementation of itself. Basically, a case like:
169 // impl Trait for T {}
171 // has a requirement of `T: Trait` which was required for default
172 // method implementations. Although this could be improved now that
173 // there's a better infrastructure in place for this, it's being left
174 // for a follow-up work.
176 // Since there's such a requirement, we need to check *just* positive
177 // implementations, otherwise things like:
179 // impl !Send for T {}
181 // won't be allowed unless there's an *explicit* implementation of `Send`
183 hir::ItemKind::Impl(impl_) => {
185 .impl_trait_ref(def_id)
186 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.skip_binder().def_id));
187 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
188 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
190 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
191 err.span_labels(impl_.defaultness_span, "default because of this");
192 err.span_label(sp, "auto trait");
195 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
196 match (tcx.impl_polarity(def_id), impl_.polarity) {
197 (ty::ImplPolarity::Positive, _) => {
198 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
200 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
201 // FIXME(#27579): what amount of WF checking do we need for neg impls?
202 if let hir::Defaultness::Default { .. } = impl_.defaultness {
203 let mut spans = vec![span];
204 spans.extend(impl_.defaultness_span);
209 "negative impls cannot be default impls"
214 (ty::ImplPolarity::Reservation, _) => {
215 // FIXME: what amount of WF checking do we need for reservation impls?
220 hir::ItemKind::Fn(ref sig, ..) => {
221 check_item_fn(tcx, def_id, item.ident, item.span, sig.decl);
223 hir::ItemKind::Static(ty, ..) => {
224 check_item_type(tcx, def_id, ty.span, false);
226 hir::ItemKind::Const(ty, ..) => {
227 check_item_type(tcx, def_id, ty.span, false);
229 hir::ItemKind::Struct(_, ast_generics) => {
230 check_type_defn(tcx, item, false);
231 check_variances_for_type_defn(tcx, item, ast_generics);
233 hir::ItemKind::Union(_, ast_generics) => {
234 check_type_defn(tcx, item, true);
235 check_variances_for_type_defn(tcx, item, ast_generics);
237 hir::ItemKind::Enum(_, ast_generics) => {
238 check_type_defn(tcx, item, true);
239 check_variances_for_type_defn(tcx, item, ast_generics);
241 hir::ItemKind::Trait(..) => {
242 check_trait(tcx, item);
244 hir::ItemKind::TraitAlias(..) => {
245 check_trait(tcx, item);
247 // `ForeignItem`s are handled separately.
248 hir::ItemKind::ForeignMod { .. } => {}
253 fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
254 let def_id = item.owner_id.def_id;
258 item.name = ? tcx.def_path_str(def_id.to_def_id())
262 hir::ForeignItemKind::Fn(decl, ..) => {
263 check_item_fn(tcx, def_id, item.ident, item.span, decl)
265 hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, def_id, ty.span, true),
266 hir::ForeignItemKind::Type => (),
270 fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
271 let def_id = trait_item.owner_id.def_id;
273 let (method_sig, span) = match trait_item.kind {
274 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
275 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
276 _ => (None, trait_item.span),
278 check_object_unsafe_self_trait_by_name(tcx, trait_item);
279 check_associated_item(tcx, def_id, span, method_sig);
281 let encl_trait_def_id = tcx.local_parent(def_id);
282 let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
283 let encl_trait_def_id = encl_trait.owner_id.to_def_id();
284 let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
286 } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
292 if let (Some(fn_lang_item_name), "call") =
293 (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
295 // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
296 // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
297 if let Some(hir::FnSig { decl, span, .. }) = method_sig {
298 if let [self_ty, _] = decl.inputs {
299 if !matches!(self_ty.kind, hir::TyKind::Ref(_, _)) {
304 "first argument of `call` in `{fn_lang_item_name}` lang item must be a reference",
314 "`call` function in `{fn_lang_item_name}` lang item takes exactly two arguments",
324 "`call` trait item in `{fn_lang_item_name}` lang item must be a function",
332 /// Require that the user writes where clauses on GATs for the implicit
333 /// outlives bounds involving trait parameters in trait functions and
334 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
336 /// We use the following trait as an example throughout this function:
337 /// ```rust,ignore (this code fails due to this lint)
339 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
341 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
344 fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRef]) {
345 // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
346 let mut required_bounds_by_item = FxHashMap::default();
348 // Loop over all GATs together, because if this lint suggests adding a where-clause bound
349 // to one GAT, it might then require us to an additional bound on another GAT.
350 // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
351 // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
354 let mut should_continue = false;
355 for gat_item in associated_items {
356 let gat_def_id = gat_item.id.owner_id;
357 let gat_item = tcx.associated_item(gat_def_id);
358 // If this item is not an assoc ty, or has no substs, then it's not a GAT
359 if gat_item.kind != ty::AssocKind::Type {
362 let gat_generics = tcx.generics_of(gat_def_id);
363 // FIXME(jackh726): we can also warn in the more general case
364 if gat_generics.params.is_empty() {
368 // Gather the bounds with which all other items inside of this trait constrain the GAT.
369 // This is calculated by taking the intersection of the bounds that each item
370 // constrains the GAT with individually.
371 let mut new_required_bounds: Option<FxHashSet<ty::Predicate<'_>>> = None;
372 for item in associated_items {
373 let item_def_id = item.id.owner_id;
374 // Skip our own GAT, since it does not constrain itself at all.
375 if item_def_id == gat_def_id {
379 let param_env = tcx.param_env(item_def_id);
381 let item_required_bounds = match item.kind {
382 // In our example, this corresponds to `into_iter` method
383 hir::AssocItemKind::Fn { .. } => {
384 // For methods, we check the function signature's return type for any GATs
385 // to constrain. In the `into_iter` case, we see that the return type
386 // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
387 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
388 item_def_id.to_def_id(),
389 tcx.fn_sig(item_def_id).subst_identity(),
395 sig.inputs_and_output,
396 // We also assume that all of the function signature's parameter types
398 &sig.inputs().iter().copied().collect(),
403 // In our example, this corresponds to the `Iter` and `Item` associated types
404 hir::AssocItemKind::Type => {
405 // If our associated item is a GAT with missing bounds, add them to
406 // the param-env here. This allows this GAT to propagate missing bounds
408 let param_env = augment_param_env(
411 required_bounds_by_item.get(&item_def_id),
417 tcx.explicit_item_bounds(item_def_id).to_vec(),
418 &FxIndexSet::default(),
423 hir::AssocItemKind::Const => None,
426 if let Some(item_required_bounds) = item_required_bounds {
427 // Take the intersection of the required bounds for this GAT, and
428 // the item_required_bounds which are the ones implied by just
430 // This is why we use an Option<_>, since we need to distinguish
431 // the empty set of bounds from the _uninitialized_ set of bounds.
432 if let Some(new_required_bounds) = &mut new_required_bounds {
433 new_required_bounds.retain(|b| item_required_bounds.contains(b));
435 new_required_bounds = Some(item_required_bounds);
440 if let Some(new_required_bounds) = new_required_bounds {
441 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
442 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
443 // Iterate until our required_bounds no longer change
444 // Since they changed here, we should continue the loop
445 should_continue = true;
449 // We know that this loop will eventually halt, since we only set `should_continue` if the
450 // `required_bounds` for this item grows. Since we are not creating any new region or type
451 // variables, the set of all region and type bounds that we could ever insert are limited
452 // by the number of unique types and regions we observe in a given item.
453 if !should_continue {
458 for (gat_def_id, required_bounds) in required_bounds_by_item {
459 let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id.def_id);
460 debug!(?required_bounds);
461 let param_env = tcx.param_env(gat_def_id);
463 let mut unsatisfied_bounds: Vec<_> = required_bounds
465 .filter(|clause| match clause.kind().skip_binder() {
466 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(ty::OutlivesPredicate(
469 ))) => !region_known_to_outlive(
473 &FxIndexSet::default(),
477 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
480 ))) => !ty_known_to_outlive(
484 &FxIndexSet::default(),
488 _ => bug!("Unexpected PredicateKind"),
490 .map(|clause| clause.to_string())
493 // We sort so that order is predictable
494 unsatisfied_bounds.sort();
496 if !unsatisfied_bounds.is_empty() {
497 let plural = pluralize!(unsatisfied_bounds.len());
498 let mut err = tcx.sess.struct_span_err(
500 &format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
503 let suggestion = format!(
505 gat_item_hir.generics.add_where_or_trailing_comma(),
506 unsatisfied_bounds.join(", "),
509 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
510 &format!("add the required where clause{plural}"),
512 Applicability::MachineApplicable,
516 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
518 "{} currently required to ensure that impls have maximum flexibility",
522 "we are soliciting feedback, see issue #87479 \
523 <https://github.com/rust-lang/rust/issues/87479> \
524 for more information",
532 /// Add a new set of predicates to the caller_bounds of an existing param_env.
533 fn augment_param_env<'tcx>(
535 param_env: ty::ParamEnv<'tcx>,
536 new_predicates: Option<&FxHashSet<ty::Predicate<'tcx>>>,
537 ) -> ty::ParamEnv<'tcx> {
538 let Some(new_predicates) = new_predicates else {
542 if new_predicates.is_empty() {
547 tcx.mk_predicates(param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()));
548 // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
549 // i.e. traits::normalize_param_env_or_error
550 ty::ParamEnv::new(bounds, param_env.reveal(), param_env.constness())
553 /// We use the following trait as an example throughout this function.
554 /// Specifically, let's assume that `to_check` here is the return type
555 /// of `into_iter`, and the GAT we are checking this for is `Iter`.
556 /// ```rust,ignore (this code fails due to this lint)
558 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
560 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
563 fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>(
565 param_env: ty::ParamEnv<'tcx>,
566 item_def_id: hir::OwnerId,
568 wf_tys: &FxIndexSet<Ty<'tcx>>,
569 gat_def_id: LocalDefId,
570 gat_generics: &'tcx ty::Generics,
571 ) -> Option<FxHashSet<ty::Predicate<'tcx>>> {
572 // The bounds we that we would require from `to_check`
573 let mut bounds = FxHashSet::default();
575 let (regions, types) = GATSubstCollector::visit(gat_def_id.to_def_id(), to_check);
577 // If both regions and types are empty, then this GAT isn't in the
578 // set of types we are checking, and we shouldn't try to do clause analysis
579 // (particularly, doing so would end up with an empty set of clauses,
580 // since the current method would require none, and we take the
581 // intersection of requirements of all methods)
582 if types.is_empty() && regions.is_empty() {
586 for (region_a, region_a_idx) in ®ions {
587 // Ignore `'static` lifetimes for the purpose of this lint: it's
588 // because we know it outlives everything and so doesn't give meaningful
590 if let ty::ReStatic = **region_a {
593 // For each region argument (e.g., `'a` in our example), check for a
594 // relationship to the type arguments (e.g., `Self`). If there is an
595 // outlives relationship (`Self: 'a`), then we want to ensure that is
596 // reflected in a where clause on the GAT itself.
597 for (ty, ty_idx) in &types {
598 // In our example, requires that `Self: 'a`
599 if ty_known_to_outlive(tcx, item_def_id.def_id, param_env, &wf_tys, *ty, *region_a) {
600 debug!(?ty_idx, ?region_a_idx);
601 debug!("required clause: {ty} must outlive {region_a}");
602 // Translate into the generic parameters of the GAT. In
603 // our example, the type was `Self`, which will also be
604 // `Self` in the GAT.
605 let ty_param = gat_generics.param_at(*ty_idx, tcx);
607 .mk_ty(ty::Param(ty::ParamTy { index: ty_param.index, name: ty_param.name }));
608 // Same for the region. In our example, 'a corresponds
609 // to the 'me parameter.
610 let region_param = gat_generics.param_at(*region_a_idx, tcx);
612 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
613 def_id: region_param.def_id,
614 index: region_param.index,
615 name: region_param.name,
617 // The predicate we expect to see. (In our example,
619 let clause = ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
620 ty::OutlivesPredicate(ty_param, region_param),
622 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
623 bounds.insert(clause);
627 // For each region argument (e.g., `'a` in our example), also check for a
628 // relationship to the other region arguments. If there is an outlives
629 // relationship, then we want to ensure that is reflected in the where clause
630 // on the GAT itself.
631 for (region_b, region_b_idx) in ®ions {
632 // Again, skip `'static` because it outlives everything. Also, we trivially
633 // know that a region outlives itself.
634 if ty::ReStatic == **region_b || region_a == region_b {
637 if region_known_to_outlive(
645 debug!(?region_a_idx, ?region_b_idx);
646 debug!("required clause: {region_a} must outlive {region_b}");
647 // Translate into the generic parameters of the GAT.
648 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
650 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
651 def_id: region_a_param.def_id,
652 index: region_a_param.index,
653 name: region_a_param.name,
655 // Same for the region.
656 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
658 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
659 def_id: region_b_param.def_id,
660 index: region_b_param.index,
661 name: region_b_param.name,
663 // The predicate we expect to see.
664 let clause = ty::PredicateKind::Clause(ty::Clause::RegionOutlives(
665 ty::OutlivesPredicate(region_a_param, region_b_param),
667 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
668 bounds.insert(clause);
676 /// Given a known `param_env` and a set of well formed types, can we prove that
677 /// `ty` outlives `region`.
678 fn ty_known_to_outlive<'tcx>(
681 param_env: ty::ParamEnv<'tcx>,
682 wf_tys: &FxIndexSet<Ty<'tcx>>,
684 region: ty::Region<'tcx>,
686 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
687 let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
688 let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
689 outlives.type_must_outlive(origin, ty, region, ConstraintCategory::BoringNoLocation);
693 /// Given a known `param_env` and a set of well formed types, can we prove that
694 /// `region_a` outlives `region_b`
695 fn region_known_to_outlive<'tcx>(
698 param_env: ty::ParamEnv<'tcx>,
699 wf_tys: &FxIndexSet<Ty<'tcx>>,
700 region_a: ty::Region<'tcx>,
701 region_b: ty::Region<'tcx>,
703 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
704 use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
705 let origin = infer::RelateRegionParamBound(DUMMY_SP);
706 // `region_a: region_b` -> `region_b <= region_a`
707 infcx.push_sub_region_constraint(
711 ConstraintCategory::BoringNoLocation,
716 /// Given a known `param_env` and a set of well formed types, set up an
717 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
718 /// to be tested), then resolve region and return errors
719 fn resolve_regions_with_wf_tys<'tcx>(
722 param_env: ty::ParamEnv<'tcx>,
723 wf_tys: &FxIndexSet<Ty<'tcx>>,
724 add_constraints: impl for<'a> FnOnce(&'a InferCtxt<'tcx>, &'a RegionBoundPairs<'tcx>),
726 // Unfortunately, we have to use a new `InferCtxt` each call, because
727 // region constraints get added and solved there and we need to test each
728 // call individually.
729 let infcx = tcx.infer_ctxt().build();
730 let outlives_environment = OutlivesEnvironment::with_bounds(
733 infcx.implied_bounds_tys(param_env, id, wf_tys.clone()),
735 let region_bound_pairs = outlives_environment.region_bound_pairs();
737 add_constraints(&infcx, region_bound_pairs);
739 infcx.process_registered_region_obligations(
740 outlives_environment.region_bound_pairs(),
743 let errors = infcx.resolve_regions(&outlives_environment);
745 debug!(?errors, "errors");
747 // If we were able to prove that the type outlives the region without
748 // an error, it must be because of the implied or explicit bounds...
752 /// TypeVisitor that looks for uses of GATs like
753 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
754 /// the two vectors, `regions` and `types` (depending on their kind). For each
755 /// parameter `Pi` also track the index `i`.
756 struct GATSubstCollector<'tcx> {
758 // Which region appears and which parameter index its substituted for
759 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
760 // Which params appears and which parameter index its substituted for
761 types: FxHashSet<(Ty<'tcx>, usize)>,
764 impl<'tcx> GATSubstCollector<'tcx> {
765 fn visit<T: TypeFoldable<'tcx>>(
768 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
770 GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
771 t.visit_with(&mut visitor);
772 (visitor.regions, visitor.types)
776 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
779 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
781 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
782 for (idx, subst) in p.substs.iter().enumerate() {
783 match subst.unpack() {
784 GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
785 self.regions.insert((lt, idx));
787 GenericArgKind::Type(t) => {
788 self.types.insert((t, idx));
796 t.super_visit_with(self)
800 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
802 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
803 [s] => s.res.opt_def_id() == Some(trait_def_id.to_def_id()),
810 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
811 /// When this is done, suggest using `Self` instead.
812 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
813 let (trait_name, trait_def_id) =
814 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id()).def_id) {
815 hir::Node::Item(item) => match item.kind {
816 hir::ItemKind::Trait(..) => (item.ident, item.owner_id),
821 let mut trait_should_be_self = vec![];
823 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
824 if could_be_self(trait_def_id.def_id, ty) =>
826 trait_should_be_self.push(ty.span)
828 hir::TraitItemKind::Fn(sig, _) => {
829 for ty in sig.decl.inputs {
830 if could_be_self(trait_def_id.def_id, ty) {
831 trait_should_be_self.push(ty.span);
834 match sig.decl.output {
835 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id.def_id, ty) => {
836 trait_should_be_self.push(ty.span);
843 if !trait_should_be_self.is_empty() {
844 if tcx.check_is_object_safe(trait_def_id) {
847 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
850 trait_should_be_self,
851 "associated item referring to unboxed trait object for its own trait",
853 .span_label(trait_name.span, "in this trait")
854 .multipart_suggestion(
855 "you might have meant to use `Self` to refer to the implementing type",
857 Applicability::MachineApplicable,
863 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
864 let (method_sig, span) = match impl_item.kind {
865 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
866 // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
867 hir::ImplItemKind::Type(ty) if ty.span != DUMMY_SP => (None, ty.span),
868 _ => (None, impl_item.span),
871 check_associated_item(tcx, impl_item.owner_id.def_id, span, method_sig);
874 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
876 // We currently only check wf of const params here.
877 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
879 // Const parameters are well formed if their type is structural match.
880 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
881 let ty = tcx.type_of(param.def_id);
883 if tcx.features().adt_const_params {
884 if let Some(non_structural_match_ty) =
885 traits::search_for_adt_const_param_violation(param.span, tcx, ty)
887 // We use the same error code in both branches, because this is really the same
888 // issue: we just special-case the message for type parameters to make it
890 match non_structural_match_ty.kind() {
892 // Const parameters may not have type parameters as their types,
893 // because we cannot be sure that the type parameter derives `PartialEq`
894 // and `Eq` (just implementing them is not enough for `structural_match`).
899 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
900 used as the type of a const parameter",
904 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
907 "it is not currently possible to use a type parameter as the type of a \
917 "`{ty}` is forbidden as the type of a const generic parameter",
919 .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
927 "using function pointers as const generic parameters is forbidden",
936 "using raw pointers as const generic parameters is forbidden",
941 let mut diag = struct_span_err!(
945 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
946 the type of a const parameter",
947 non_structural_match_ty,
950 if ty == non_structural_match_ty {
953 format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
963 let mut is_ptr = true;
965 let err = match ty.kind() {
966 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
967 ty::FnPtr(_) => Some("function pointers"),
968 ty::RawPtr(_) => Some("raw pointers"),
971 err_ty_str = format!("`{ty}`");
972 Some(err_ty_str.as_str())
976 if let Some(unsupported_type) = err {
981 "using {unsupported_type} as const generic parameters is forbidden",
985 let mut err = tcx.sess.struct_span_err(
988 "{unsupported_type} is forbidden as the type of a const generic parameter",
991 err.note("the only supported types are integers, `bool` and `char`");
992 if tcx.sess.is_nightly_build() {
994 "more complex types are supported with `#![feature(adt_const_params)]`",
1005 #[instrument(level = "debug", skip(tcx, span, sig_if_method))]
1006 fn check_associated_item(
1008 item_id: LocalDefId,
1010 sig_if_method: Option<&hir::FnSig<'_>>,
1012 let loc = Some(WellFormedLoc::Ty(item_id));
1013 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
1014 let item = tcx.associated_item(item_id);
1016 let self_ty = match item.container {
1017 ty::TraitContainer => tcx.types.self_param,
1018 ty::ImplContainer => tcx.type_of(item.container_id(tcx)),
1022 ty::AssocKind::Const => {
1023 let ty = tcx.type_of(item.def_id);
1024 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1025 wfcx.register_wf_obligation(span, loc, ty.into());
1027 ty::AssocKind::Fn => {
1028 let sig = tcx.fn_sig(item.def_id).subst_identity();
1029 let hir_sig = sig_if_method.expect("bad signature for method");
1032 item.ident(tcx).span,
1035 item.def_id.expect_local(),
1037 check_method_receiver(wfcx, hir_sig, item, self_ty);
1039 ty::AssocKind::Type => {
1040 if let ty::AssocItemContainer::TraitContainer = item.container {
1041 check_associated_type_bounds(wfcx, item, span)
1043 if item.defaultness(tcx).has_value() {
1044 let ty = tcx.type_of(item.def_id);
1045 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1046 wfcx.register_wf_obligation(span, loc, ty.into());
1053 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1055 ItemKind::Struct(..) => Some(AdtKind::Struct),
1056 ItemKind::Union(..) => Some(AdtKind::Union),
1057 ItemKind::Enum(..) => Some(AdtKind::Enum),
1062 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1063 fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: bool) {
1064 let _ = tcx.representability(item.owner_id.def_id);
1065 let adt_def = tcx.adt_def(item.owner_id);
1067 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1068 let variants = adt_def.variants();
1069 let packed = adt_def.repr().packed();
1071 for variant in variants.iter() {
1072 // All field types must be well-formed.
1073 for field in &variant.fields {
1074 let field_id = field.did.expect_local();
1075 let hir::Node::Field(hir::FieldDef { ty: hir_ty, .. }) = tcx.hir().get_by_def_id(field_id)
1077 let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did));
1078 wfcx.register_wf_obligation(
1080 Some(WellFormedLoc::Ty(field_id)),
1085 // For DST, or when drop needs to copy things around, all
1086 // intermediate types must be sized.
1087 let needs_drop_copy = || {
1089 let ty = tcx.type_of(variant.fields.last().unwrap().did);
1090 let ty = tcx.erase_regions(ty);
1091 if ty.needs_infer() {
1093 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1094 // Just treat unresolved type expression as if it needs drop.
1097 ty.needs_drop(tcx, tcx.param_env(item.owner_id))
1101 // All fields (except for possibly the last) should be sized.
1102 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1103 let unsized_len = if all_sized { 0 } else { 1 };
1105 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1107 let last = idx == variant.fields.len() - 1;
1108 let field_id = field.did.expect_local();
1109 let hir::Node::Field(hir::FieldDef { ty: hir_ty, .. }) = tcx.hir().get_by_def_id(field_id)
1111 let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did));
1112 wfcx.register_bound(
1113 traits::ObligationCause::new(
1116 traits::FieldSized {
1117 adt_kind: match item_adt_kind(&item.kind) {
1127 tcx.require_lang_item(LangItem::Sized, None),
1131 // Explicit `enum` discriminant values must const-evaluate successfully.
1132 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1133 let cause = traits::ObligationCause::new(
1134 tcx.def_span(discr_def_id),
1136 traits::MiscObligation,
1138 wfcx.register_obligation(traits::Obligation::new(
1142 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(
1143 ty::Const::from_anon_const(tcx, discr_def_id.expect_local()),
1149 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1153 #[instrument(skip(tcx, item))]
1154 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1155 debug!(?item.owner_id);
1157 let def_id = item.owner_id.def_id;
1158 let trait_def = tcx.trait_def(def_id);
1159 if trait_def.is_marker
1160 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1162 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1165 tcx.def_span(*associated_def_id),
1167 "marker traits cannot have associated items",
1173 enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| {
1174 check_where_clauses(wfcx, item.span, def_id)
1177 // Only check traits, don't check trait aliases
1178 if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1179 check_gat_where_clauses(tcx, items);
1183 /// Checks all associated type defaults of trait `trait_def_id`.
1185 /// Assuming the defaults are used, check that all predicates (bounds on the
1186 /// assoc type and where clauses on the trait) hold.
1187 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1188 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1190 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1191 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1192 let normalized_bound = wfcx.normalize(span, None, bound);
1193 traits::wf::predicate_obligations(
1202 wfcx.register_obligations(wf_obligations);
1210 decl: &hir::FnDecl<'_>,
1212 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1213 let sig = tcx.fn_sig(def_id).subst_identity();
1214 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1218 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1219 debug!("check_item_type: {:?}", item_id);
1221 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1222 let ty = tcx.type_of(item_id);
1223 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1225 let mut forbid_unsized = true;
1226 if allow_foreign_ty {
1227 let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1228 if let ty::Foreign(_) = tail.kind() {
1229 forbid_unsized = false;
1233 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1235 wfcx.register_bound(
1236 traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::WellFormed(None)),
1239 tcx.require_lang_item(LangItem::Sized, None),
1243 // Ensure that the end result is `Sync` in a non-thread local `static`.
1244 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1245 == Some(hir::Mutability::Not)
1246 && !tcx.is_foreign_item(item_id.to_def_id())
1247 && !tcx.is_thread_local_static(item_id.to_def_id());
1249 if should_check_for_sync {
1250 wfcx.register_bound(
1251 traits::ObligationCause::new(ty_span, wfcx.body_def_id, traits::SharedStatic),
1254 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1260 #[instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1261 fn check_impl<'tcx>(
1263 item: &'tcx hir::Item<'tcx>,
1264 ast_self_ty: &hir::Ty<'_>,
1265 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1266 constness: hir::Constness,
1268 enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| {
1269 match ast_trait_ref {
1270 Some(ast_trait_ref) => {
1271 // `#[rustc_reservation_impl]` impls are not real impls and
1272 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1274 let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().subst_identity();
1275 let trait_ref = wfcx.normalize(
1276 ast_trait_ref.path.span,
1277 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1280 let trait_pred = ty::TraitPredicate {
1282 constness: match constness {
1283 hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1284 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1286 polarity: ty::ImplPolarity::Positive,
1288 let mut obligations = traits::wf::trait_obligations(
1293 ast_trait_ref.path.span,
1296 for obligation in &mut obligations {
1297 if let Some(pred) = obligation.predicate.to_opt_poly_trait_pred()
1298 && pred.self_ty().skip_binder() == trait_ref.self_ty()
1300 obligation.cause.span = ast_self_ty.span;
1303 debug!(?obligations);
1304 wfcx.register_obligations(obligations);
1307 let self_ty = tcx.type_of(item.owner_id);
1308 let self_ty = wfcx.normalize(
1310 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1313 wfcx.register_wf_obligation(
1315 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1321 check_where_clauses(wfcx, item.span, item.owner_id.def_id);
1325 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1326 #[instrument(level = "debug", skip(wfcx))]
1327 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1328 let infcx = wfcx.infcx;
1329 let tcx = wfcx.tcx();
1331 let predicates = tcx.predicates_of(def_id.to_def_id());
1332 let generics = tcx.generics_of(def_id);
1334 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1335 GenericParamDefKind::Type { has_default, .. }
1336 | GenericParamDefKind::Const { has_default } => {
1337 has_default && def.index >= generics.parent_count as u32
1339 GenericParamDefKind::Lifetime => unreachable!(),
1342 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1343 // For example, this forbids the declaration:
1345 // struct Foo<T = Vec<[u32]>> { .. }
1347 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1348 for param in &generics.params {
1350 GenericParamDefKind::Type { .. } => {
1351 if is_our_default(param) {
1352 let ty = tcx.type_of(param.def_id);
1353 // Ignore dependent defaults -- that is, where the default of one type
1354 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1355 // be sure if it will error or not as user might always specify the other.
1356 if !ty.needs_subst() {
1357 wfcx.register_wf_obligation(
1358 tcx.def_span(param.def_id),
1359 Some(WellFormedLoc::Ty(param.def_id.expect_local())),
1365 GenericParamDefKind::Const { .. } => {
1366 if is_our_default(param) {
1367 // FIXME(const_generics_defaults): This
1368 // is incorrect when dealing with unused substs, for example
1369 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1370 // we should eagerly error.
1371 let default_ct = tcx.const_param_default(param.def_id).subst_identity();
1372 if !default_ct.needs_subst() {
1373 wfcx.register_wf_obligation(
1374 tcx.def_span(param.def_id),
1381 // Doesn't have defaults.
1382 GenericParamDefKind::Lifetime => {}
1386 // Check that trait predicates are WF when params are substituted by their defaults.
1387 // We don't want to overly constrain the predicates that may be written but we want to
1388 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1389 // Therefore we check if a predicate which contains a single type param
1390 // with a concrete default is WF with that default substituted.
1391 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1393 // First we build the defaulted substitution.
1394 let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1396 GenericParamDefKind::Lifetime => {
1397 // All regions are identity.
1398 tcx.mk_param_from_def(param)
1401 GenericParamDefKind::Type { .. } => {
1402 // If the param has a default, ...
1403 if is_our_default(param) {
1404 let default_ty = tcx.type_of(param.def_id);
1405 // ... and it's not a dependent default, ...
1406 if !default_ty.needs_subst() {
1407 // ... then substitute it with the default.
1408 return default_ty.into();
1412 tcx.mk_param_from_def(param)
1414 GenericParamDefKind::Const { .. } => {
1415 // If the param has a default, ...
1416 if is_our_default(param) {
1417 let default_ct = tcx.const_param_default(param.def_id).subst_identity();
1418 // ... and it's not a dependent default, ...
1419 if !default_ct.needs_subst() {
1420 // ... then substitute it with the default.
1421 return default_ct.into();
1425 tcx.mk_param_from_def(param)
1430 // Now we build the substituted predicates.
1431 let default_obligations = predicates
1434 .flat_map(|&(pred, sp)| {
1436 struct CountParams {
1437 params: FxHashSet<u32>,
1439 impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1442 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1443 if let ty::Param(param) = t.kind() {
1444 self.params.insert(param.index);
1446 t.super_visit_with(self)
1449 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1450 ControlFlow::Break(())
1453 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1454 if let ty::ConstKind::Param(param) = c.kind() {
1455 self.params.insert(param.index);
1457 c.super_visit_with(self)
1460 let mut param_count = CountParams::default();
1461 let has_region = pred.visit_with(&mut param_count).is_break();
1462 let substituted_pred = ty::EarlyBinder(pred).subst(tcx, substs);
1463 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1464 // or preds with multiple params.
1465 if substituted_pred.has_non_region_param() || param_count.params.len() > 1 || has_region
1468 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1469 // Avoid duplication of predicates that contain no parameters, for example.
1472 Some((substituted_pred, sp))
1476 // Convert each of those into an obligation. So if you have
1477 // something like `struct Foo<T: Copy = String>`, we would
1478 // take that predicate `T: Copy`, substitute to `String: Copy`
1479 // (actually that happens in the previous `flat_map` call),
1480 // and then try to prove it (in this case, we'll fail).
1482 // Note the subtle difference from how we handle `predicates`
1483 // below: there, we are not trying to prove those predicates
1484 // to be *true* but merely *well-formed*.
1485 let pred = wfcx.normalize(sp, None, pred);
1486 let cause = traits::ObligationCause::new(
1489 traits::ItemObligation(def_id.to_def_id()),
1491 traits::Obligation::new(tcx, cause, wfcx.param_env, pred)
1494 let predicates = predicates.instantiate_identity(tcx);
1496 let predicates = wfcx.normalize(span, None, predicates);
1498 debug!(?predicates.predicates);
1499 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1500 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1501 traits::wf::predicate_obligations(
1503 wfcx.param_env.without_const(),
1509 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1510 wfcx.register_obligations(obligations);
1513 #[instrument(level = "debug", skip(wfcx, span, hir_decl))]
1514 fn check_fn_or_method<'tcx>(
1515 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1517 sig: ty::PolyFnSig<'tcx>,
1518 hir_decl: &hir::FnDecl<'_>,
1521 let tcx = wfcx.tcx();
1522 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1524 // Normalize the input and output types one at a time, using a different
1525 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1526 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1527 // for each type, preventing the HIR wf check from generating
1528 // a nice error message.
1530 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1532 sig.inputs_and_output =
1533 tcx.mk_type_list(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1536 Some(WellFormedLoc::Param {
1538 // Note that the `param_idx` of the output type is
1539 // one greater than the index of the last input type.
1540 param_idx: idx.try_into().unwrap(),
1546 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1547 wfcx.register_wf_obligation(
1549 Some(WellFormedLoc::Param { function: def_id, param_idx: idx.try_into().unwrap() }),
1554 check_where_clauses(wfcx, span, def_id);
1556 check_return_position_impl_trait_in_trait_bounds(
1560 hir_decl.output.span(),
1563 if sig.abi == Abi::RustCall {
1564 let span = tcx.def_span(def_id);
1565 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1566 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1567 // Check that the argument is a tuple
1568 if let Some(ty) = inputs.next() {
1569 wfcx.register_bound(
1570 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1573 tcx.require_lang_item(hir::LangItem::Tuple, Some(span)),
1577 hir_decl.inputs.last().map_or(span, |input| input.span),
1578 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1581 // No more inputs other than the `self` type and the tuple type
1582 if inputs.next().is_some() {
1584 hir_decl.inputs.last().map_or(span, |input| input.span),
1585 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1591 /// Basically `check_associated_type_bounds`, but separated for now and should be
1592 /// deduplicated when RPITITs get lowered into real associated items.
1593 #[tracing::instrument(level = "trace", skip(wfcx))]
1594 fn check_return_position_impl_trait_in_trait_bounds<'tcx>(
1595 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1596 fn_def_id: LocalDefId,
1597 fn_output: Ty<'tcx>,
1600 let tcx = wfcx.tcx();
1601 if let Some(assoc_item) = tcx.opt_associated_item(fn_def_id.to_def_id())
1602 && assoc_item.container == ty::AssocItemContainer::TraitContainer
1604 for arg in fn_output.walk() {
1605 if let ty::GenericArgKind::Type(ty) = arg.unpack()
1606 && let ty::Alias(ty::Projection, proj) = ty.kind()
1607 && tcx.def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder
1608 && tcx.impl_trait_in_trait_parent(proj.def_id) == fn_def_id.to_def_id()
1610 let span = tcx.def_span(proj.def_id);
1611 let bounds = wfcx.tcx().explicit_item_bounds(proj.def_id);
1612 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1613 let bound = ty::EarlyBinder(bound).subst(tcx, proj.substs);
1614 let normalized_bound = wfcx.normalize(span, None, bound);
1615 traits::wf::predicate_obligations(
1623 wfcx.register_obligations(wf_obligations);
1629 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1630 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1631 of the previous types except `Self`)";
1633 #[instrument(level = "debug", skip(wfcx))]
1634 fn check_method_receiver<'tcx>(
1635 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1636 fn_sig: &hir::FnSig<'_>,
1637 method: &ty::AssocItem,
1640 let tcx = wfcx.tcx();
1642 if !method.fn_has_self_parameter {
1646 let span = fn_sig.decl.inputs[0].span;
1648 let sig = tcx.fn_sig(method.def_id).subst_identity();
1649 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1650 let sig = wfcx.normalize(span, None, sig);
1652 debug!("check_method_receiver: sig={:?}", sig);
1654 let self_ty = wfcx.normalize(span, None, self_ty);
1656 let receiver_ty = sig.inputs()[0];
1657 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1659 if tcx.features().arbitrary_self_types {
1660 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1661 // Report error; `arbitrary_self_types` was enabled.
1662 e0307(tcx, span, receiver_ty);
1665 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1666 if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1667 // Report error; would have worked with `arbitrary_self_types`.
1669 &tcx.sess.parse_sess,
1670 sym::arbitrary_self_types,
1673 "`{receiver_ty}` cannot be used as the type of `self` without \
1674 the `arbitrary_self_types` feature",
1677 .help(HELP_FOR_SELF_TYPE)
1680 // Report error; would not have worked with `arbitrary_self_types`.
1681 e0307(tcx, span, receiver_ty);
1687 fn e0307(tcx: TyCtxt<'_>, span: Span, receiver_ty: Ty<'_>) {
1689 tcx.sess.diagnostic(),
1692 "invalid `self` parameter type: {receiver_ty}"
1694 .note("type of `self` must be `Self` or a type that dereferences to it")
1695 .help(HELP_FOR_SELF_TYPE)
1699 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1700 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1701 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1702 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1703 /// `Deref<Target = self_ty>`.
1705 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1706 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1707 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1708 fn receiver_is_valid<'tcx>(
1709 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1711 receiver_ty: Ty<'tcx>,
1713 arbitrary_self_types_enabled: bool,
1715 let infcx = wfcx.infcx;
1716 let tcx = wfcx.tcx();
1718 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1720 let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1722 // `self: Self` is always valid.
1723 if can_eq_self(receiver_ty) {
1724 if let Err(err) = wfcx.eq(&cause, wfcx.param_env, self_ty, receiver_ty) {
1725 infcx.err_ctxt().report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1730 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1732 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1733 if arbitrary_self_types_enabled {
1734 autoderef = autoderef.include_raw_pointers();
1737 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1740 let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, Some(span));
1742 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1744 if let Some((potential_self_ty, _)) = autoderef.next() {
1746 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1747 potential_self_ty, self_ty
1750 if can_eq_self(potential_self_ty) {
1751 wfcx.register_obligations(autoderef.into_obligations());
1753 if let Err(err) = wfcx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty) {
1756 .report_mismatched_types(&cause, self_ty, potential_self_ty, err)
1762 // Without `feature(arbitrary_self_types)`, we require that each step in the
1763 // deref chain implement `receiver`
1764 if !arbitrary_self_types_enabled
1765 && !receiver_is_implemented(
1767 receiver_trait_def_id,
1776 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1777 // If the receiver already has errors reported due to it, consider it valid to avoid
1778 // unnecessary errors (#58712).
1779 return receiver_ty.references_error();
1783 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1784 if !arbitrary_self_types_enabled
1785 && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1793 fn receiver_is_implemented<'tcx>(
1794 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1795 receiver_trait_def_id: DefId,
1796 cause: ObligationCause<'tcx>,
1797 receiver_ty: Ty<'tcx>,
1799 let tcx = wfcx.tcx();
1800 let trait_ref = ty::Binder::dummy(tcx.mk_trait_ref(receiver_trait_def_id, [receiver_ty]));
1802 let obligation = traits::Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1804 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1808 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1815 fn check_variances_for_type_defn<'tcx>(
1817 item: &hir::Item<'tcx>,
1818 hir_generics: &hir::Generics<'_>,
1820 let ty = tcx.type_of(item.owner_id);
1821 if tcx.has_error_field(ty) {
1825 let ty_predicates = tcx.predicates_of(item.owner_id);
1826 assert_eq!(ty_predicates.parent, None);
1827 let variances = tcx.variances_of(item.owner_id);
1829 let mut constrained_parameters: FxHashSet<_> = variances
1832 .filter(|&(_, &variance)| variance != ty::Bivariant)
1833 .map(|(index, _)| Parameter(index as u32))
1836 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1838 // Lazily calculated because it is only needed in case of an error.
1839 let explicitly_bounded_params = LazyCell::new(|| {
1840 let icx = crate::collect::ItemCtxt::new(tcx, item.owner_id.to_def_id());
1844 .filter_map(|predicate| match predicate {
1845 hir::WherePredicate::BoundPredicate(predicate) => {
1846 match icx.to_ty(predicate.bounded_ty).kind() {
1847 ty::Param(data) => Some(Parameter(data.index)),
1853 .collect::<FxHashSet<_>>()
1856 for (index, _) in variances.iter().enumerate() {
1857 let parameter = Parameter(index as u32);
1859 if constrained_parameters.contains(¶meter) {
1863 let param = &hir_generics.params[index];
1866 hir::ParamName::Error => {}
1868 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
1869 report_bivariance(tcx, param, has_explicit_bounds);
1875 fn report_bivariance(
1877 param: &rustc_hir::GenericParam<'_>,
1878 has_explicit_bounds: bool,
1879 ) -> ErrorGuaranteed {
1880 let span = param.span;
1881 let param_name = param.name.ident().name;
1882 let mut err = error_392(tcx, span, param_name);
1884 let suggested_marker_id = tcx.lang_items().phantom_data();
1885 // Help is available only in presence of lang items.
1886 let msg = if let Some(def_id) = suggested_marker_id {
1888 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1890 tcx.def_path_str(def_id),
1893 format!("consider removing `{param_name}` or referring to it in a field")
1897 if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1899 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1906 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1907 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1909 #[instrument(level = "debug", skip(self))]
1910 fn check_false_global_bounds(&mut self) {
1911 let tcx = self.ocx.infcx.tcx;
1912 let mut span = self.span;
1913 let empty_env = ty::ParamEnv::empty();
1915 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
1916 // Check elaborated bounds.
1917 let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1919 for obligation in implied_obligations {
1920 // We lower empty bounds like `Vec<dyn Copy>:` as
1921 // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1922 // regular WF checking
1923 if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1926 let pred = obligation.predicate;
1927 // Match the existing behavior.
1928 if pred.is_global() && !pred.has_late_bound_vars() {
1929 let pred = self.normalize(span, None, pred);
1930 let hir_node = tcx.hir().find_by_def_id(self.body_def_id);
1932 // only use the span of the predicate clause (#90869)
1934 if let Some(hir::Generics { predicates, .. }) =
1935 hir_node.and_then(|node| node.generics())
1937 let obligation_span = obligation.cause.span();
1941 // There seems to be no better way to find out which predicate we are in
1942 .find(|pred| pred.span().contains(obligation_span))
1943 .map(|pred| pred.span())
1944 .unwrap_or(obligation_span);
1947 let obligation = traits::Obligation::new(
1949 traits::ObligationCause::new(span, self.body_def_id, traits::TrivialBound),
1953 self.ocx.register_obligation(obligation);
1959 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1960 let items = tcx.hir_module_items(module);
1961 items.par_items(|item| tcx.ensure().check_well_formed(item.owner_id));
1962 items.par_impl_items(|item| tcx.ensure().check_well_formed(item.owner_id));
1963 items.par_trait_items(|item| tcx.ensure().check_well_formed(item.owner_id));
1964 items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.owner_id));
1971 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1972 let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1973 err.span_label(span, "unused parameter");
1977 pub fn provide(providers: &mut Providers) {
1978 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };