1 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
2 use crate::outlives::outlives_bounds::InferCtxtExt as _;
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 self.ocx.register_obligation(traits::Obligation::new(
75 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
80 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
83 body_def_id: LocalDefId,
86 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>),
88 let param_env = tcx.param_env(body_def_id);
89 let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
90 tcx.infer_ctxt().enter(|ref infcx| {
91 let ocx = ObligationCtxt::new(infcx);
93 let assumed_wf_types = ocx.assumed_wf_types(param_env, span, body_def_id);
95 let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
97 if !tcx.features().trivial_bounds {
98 wfcx.check_false_global_bounds()
101 let errors = wfcx.select_all_or_error();
102 if !errors.is_empty() {
103 infcx.report_fulfillment_errors(&errors, None, false);
107 let mut outlives_environment = OutlivesEnvironment::builder(param_env);
108 outlives_environment.add_implied_bounds(infcx, assumed_wf_types, body_id);
109 let outlives_environment = outlives_environment.build();
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 outlives_environment = OutlivesEnvironment::with_bounds(
702 infcx.implied_bounds_tys(param_env, id, wf_tys.iter().map(|ty| *ty)),
704 let region_bound_pairs = outlives_environment.region_bound_pairs();
706 add_constraints(&infcx, region_bound_pairs);
708 let errors = infcx.resolve_regions(&outlives_environment);
710 debug!(?errors, "errors");
712 // If we were able to prove that the type outlives the region without
713 // an error, it must be because of the implied or explicit bounds...
718 /// TypeVisitor that looks for uses of GATs like
719 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
720 /// the two vectors, `regions` and `types` (depending on their kind). For each
721 /// parameter `Pi` also track the index `i`.
722 struct GATSubstCollector<'tcx> {
724 // Which region appears and which parameter index its substituted for
725 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
726 // Which params appears and which parameter index its substituted for
727 types: FxHashSet<(Ty<'tcx>, usize)>,
730 impl<'tcx> GATSubstCollector<'tcx> {
731 fn visit<T: TypeFoldable<'tcx>>(
734 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
736 GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
737 t.visit_with(&mut visitor);
738 (visitor.regions, visitor.types)
742 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
745 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
747 ty::Projection(p) if p.item_def_id == self.gat => {
748 for (idx, subst) in p.substs.iter().enumerate() {
749 match subst.unpack() {
750 GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
751 self.regions.insert((lt, idx));
753 GenericArgKind::Type(t) => {
754 self.types.insert((t, idx));
762 t.super_visit_with(self)
766 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
768 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
769 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
776 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
777 /// When this is done, suggest using `Self` instead.
778 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
779 let (trait_name, trait_def_id) =
780 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
781 hir::Node::Item(item) => match item.kind {
782 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
787 let mut trait_should_be_self = vec![];
789 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
790 if could_be_self(trait_def_id, ty) =>
792 trait_should_be_self.push(ty.span)
794 hir::TraitItemKind::Fn(sig, _) => {
795 for ty in sig.decl.inputs {
796 if could_be_self(trait_def_id, ty) {
797 trait_should_be_self.push(ty.span);
800 match sig.decl.output {
801 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
802 trait_should_be_self.push(ty.span);
809 if !trait_should_be_self.is_empty() {
810 if tcx.object_safety_violations(trait_def_id).is_empty() {
813 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
816 trait_should_be_self,
817 "associated item referring to unboxed trait object for its own trait",
819 .span_label(trait_name.span, "in this trait")
820 .multipart_suggestion(
821 "you might have meant to use `Self` to refer to the implementing type",
823 Applicability::MachineApplicable,
829 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
830 let def_id = impl_item.def_id;
832 let (method_sig, span) = match impl_item.kind {
833 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
834 // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
835 hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
836 _ => (None, impl_item.span),
839 check_associated_item(tcx, def_id, span, method_sig);
842 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
844 // We currently only check wf of const params here.
845 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
847 // Const parameters are well formed if their type is structural match.
848 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
849 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
851 if tcx.features().adt_const_params {
852 if let Some(non_structural_match_ty) =
853 traits::search_for_adt_const_param_violation(param.span, tcx, ty)
855 // We use the same error code in both branches, because this is really the same
856 // issue: we just special-case the message for type parameters to make it
858 match non_structural_match_ty.kind() {
860 // Const parameters may not have type parameters as their types,
861 // because we cannot be sure that the type parameter derives `PartialEq`
862 // and `Eq` (just implementing them is not enough for `structural_match`).
867 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
868 used as the type of a const parameter",
872 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
875 "it is not currently possible to use a type parameter as the type of a \
885 "`{ty}` is forbidden as the type of a const generic parameter",
887 .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
895 "using function pointers as const generic parameters is forbidden",
904 "using raw pointers as const generic parameters is forbidden",
909 let mut diag = struct_span_err!(
913 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
914 the type of a const parameter",
915 non_structural_match_ty,
918 if ty == non_structural_match_ty {
921 format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
931 let mut is_ptr = true;
933 let err = match ty.kind() {
934 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
935 ty::FnPtr(_) => Some("function pointers"),
936 ty::RawPtr(_) => Some("raw pointers"),
939 err_ty_str = format!("`{ty}`");
940 Some(err_ty_str.as_str())
944 if let Some(unsupported_type) = err {
949 "using {unsupported_type} as const generic parameters is forbidden",
953 let mut err = tcx.sess.struct_span_err(
956 "{unsupported_type} is forbidden as the type of a const generic parameter",
959 err.note("the only supported types are integers, `bool` and `char`");
960 if tcx.sess.is_nightly_build() {
962 "more complex types are supported with `#![feature(adt_const_params)]`",
973 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
974 fn check_associated_item(
978 sig_if_method: Option<&hir::FnSig<'_>>,
980 let loc = Some(WellFormedLoc::Ty(item_id));
981 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
982 let item = tcx.associated_item(item_id);
984 let self_ty = match item.container {
985 ty::TraitContainer => tcx.types.self_param,
986 ty::ImplContainer => tcx.type_of(item.container_id(tcx)),
990 ty::AssocKind::Const => {
991 let ty = tcx.type_of(item.def_id);
992 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
993 wfcx.register_wf_obligation(span, loc, ty.into());
995 ty::AssocKind::Fn => {
996 let sig = tcx.fn_sig(item.def_id);
997 let hir_sig = sig_if_method.expect("bad signature for method");
1000 item.ident(tcx).span,
1003 item.def_id.expect_local(),
1005 check_method_receiver(wfcx, hir_sig, item, self_ty);
1007 ty::AssocKind::Type => {
1008 if let ty::AssocItemContainer::TraitContainer = item.container {
1009 check_associated_type_bounds(wfcx, item, span)
1011 if item.defaultness(tcx).has_value() {
1012 let ty = tcx.type_of(item.def_id);
1013 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1014 wfcx.register_wf_obligation(span, loc, ty.into());
1021 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1023 ItemKind::Struct(..) => Some(AdtKind::Struct),
1024 ItemKind::Union(..) => Some(AdtKind::Union),
1025 ItemKind::Enum(..) => Some(AdtKind::Enum),
1030 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1031 fn check_type_defn<'tcx, F>(
1033 item: &hir::Item<'tcx>,
1035 mut lookup_fields: F,
1037 F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
1039 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1040 let variants = lookup_fields(wfcx);
1041 let packed = tcx.adt_def(item.def_id).repr().packed();
1043 for variant in &variants {
1044 // All field types must be well-formed.
1045 for field in &variant.fields {
1046 wfcx.register_wf_obligation(
1048 Some(WellFormedLoc::Ty(field.def_id)),
1053 // For DST, or when drop needs to copy things around, all
1054 // intermediate types must be sized.
1055 let needs_drop_copy = || {
1057 let ty = variant.fields.last().unwrap().ty;
1058 let ty = tcx.erase_regions(ty);
1059 if ty.needs_infer() {
1061 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1062 // Just treat unresolved type expression as if it needs drop.
1065 ty.needs_drop(tcx, tcx.param_env(item.def_id))
1069 // All fields (except for possibly the last) should be sized.
1070 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1071 let unsized_len = if all_sized { 0 } else { 1 };
1073 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1075 let last = idx == variant.fields.len() - 1;
1076 wfcx.register_bound(
1077 traits::ObligationCause::new(
1080 traits::FieldSized {
1081 adt_kind: match item_adt_kind(&item.kind) {
1091 tcx.require_lang_item(LangItem::Sized, None),
1095 // Explicit `enum` discriminant values must const-evaluate successfully.
1096 if let Some(discr_def_id) = variant.explicit_discr {
1097 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
1099 let cause = traits::ObligationCause::new(
1100 tcx.def_span(discr_def_id),
1102 traits::MiscObligation,
1104 wfcx.register_obligation(traits::Obligation::new(
1107 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
1108 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
1116 check_where_clauses(wfcx, item.span, item.def_id);
1120 #[instrument(skip(tcx, item))]
1121 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1122 debug!(?item.def_id);
1124 let trait_def = tcx.trait_def(item.def_id);
1125 if trait_def.is_marker
1126 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1128 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1131 tcx.def_span(*associated_def_id),
1133 "marker traits cannot have associated items",
1139 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1140 check_where_clauses(wfcx, item.span, item.def_id)
1143 // Only check traits, don't check trait aliases
1144 if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1145 check_gat_where_clauses(tcx, items);
1149 /// Checks all associated type defaults of trait `trait_def_id`.
1151 /// Assuming the defaults are used, check that all predicates (bounds on the
1152 /// assoc type and where clauses on the trait) hold.
1153 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1154 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1156 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1157 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1158 let normalized_bound = wfcx.normalize(span, None, bound);
1159 traits::wf::predicate_obligations(
1168 wfcx.register_obligations(wf_obligations);
1176 decl: &hir::FnDecl<'_>,
1178 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1179 let sig = tcx.fn_sig(def_id);
1180 check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1184 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1185 debug!("check_item_type: {:?}", item_id);
1187 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1188 let ty = tcx.type_of(item_id);
1189 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1191 let mut forbid_unsized = true;
1192 if allow_foreign_ty {
1193 let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1194 if let ty::Foreign(_) = tail.kind() {
1195 forbid_unsized = false;
1199 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1201 wfcx.register_bound(
1202 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
1205 tcx.require_lang_item(LangItem::Sized, None),
1209 // Ensure that the end result is `Sync` in a non-thread local `static`.
1210 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1211 == Some(hir::Mutability::Not)
1212 && !tcx.is_foreign_item(item_id.to_def_id())
1213 && !tcx.is_thread_local_static(item_id.to_def_id());
1215 if should_check_for_sync {
1216 wfcx.register_bound(
1217 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
1220 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1226 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1227 fn check_impl<'tcx>(
1229 item: &'tcx hir::Item<'tcx>,
1230 ast_self_ty: &hir::Ty<'_>,
1231 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1232 constness: hir::Constness,
1234 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1235 match *ast_trait_ref {
1236 Some(ref ast_trait_ref) => {
1237 // `#[rustc_reservation_impl]` impls are not real impls and
1238 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1240 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1241 let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
1242 let trait_pred = ty::TraitPredicate {
1244 constness: match constness {
1245 hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1246 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1248 polarity: ty::ImplPolarity::Positive,
1250 let obligations = traits::wf::trait_obligations(
1255 ast_trait_ref.path.span,
1258 debug!(?obligations);
1259 wfcx.register_obligations(obligations);
1262 let self_ty = tcx.type_of(item.def_id);
1263 let self_ty = wfcx.normalize(item.span, None, self_ty);
1264 wfcx.register_wf_obligation(
1266 Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1272 check_where_clauses(wfcx, item.span, item.def_id);
1276 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1277 #[instrument(level = "debug", skip(wfcx))]
1278 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1279 let infcx = wfcx.infcx;
1280 let tcx = wfcx.tcx();
1282 let predicates = tcx.bound_predicates_of(def_id.to_def_id());
1283 let generics = tcx.generics_of(def_id);
1285 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1286 GenericParamDefKind::Type { has_default, .. }
1287 | GenericParamDefKind::Const { has_default } => {
1288 has_default && def.index >= generics.parent_count as u32
1290 GenericParamDefKind::Lifetime => unreachable!(),
1293 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1294 // For example, this forbids the declaration:
1296 // struct Foo<T = Vec<[u32]>> { .. }
1298 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1299 for param in &generics.params {
1301 GenericParamDefKind::Type { .. } => {
1302 if is_our_default(param) {
1303 let ty = tcx.type_of(param.def_id);
1304 // Ignore dependent defaults -- that is, where the default of one type
1305 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1306 // be sure if it will error or not as user might always specify the other.
1307 if !ty.needs_subst() {
1308 wfcx.register_wf_obligation(tcx.def_span(param.def_id), None, ty.into());
1312 GenericParamDefKind::Const { .. } => {
1313 if is_our_default(param) {
1314 // FIXME(const_generics_defaults): This
1315 // is incorrect when dealing with unused substs, for example
1316 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1317 // we should eagerly error.
1318 let default_ct = tcx.const_param_default(param.def_id);
1319 if !default_ct.needs_subst() {
1320 wfcx.register_wf_obligation(
1321 tcx.def_span(param.def_id),
1328 // Doesn't have defaults.
1329 GenericParamDefKind::Lifetime => {}
1333 // Check that trait predicates are WF when params are substituted by their defaults.
1334 // We don't want to overly constrain the predicates that may be written but we want to
1335 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1336 // Therefore we check if a predicate which contains a single type param
1337 // with a concrete default is WF with that default substituted.
1338 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1340 // First we build the defaulted substitution.
1341 let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1343 GenericParamDefKind::Lifetime => {
1344 // All regions are identity.
1345 tcx.mk_param_from_def(param)
1348 GenericParamDefKind::Type { .. } => {
1349 // If the param has a default, ...
1350 if is_our_default(param) {
1351 let default_ty = tcx.type_of(param.def_id);
1352 // ... and it's not a dependent default, ...
1353 if !default_ty.needs_subst() {
1354 // ... then substitute it with the default.
1355 return default_ty.into();
1359 tcx.mk_param_from_def(param)
1361 GenericParamDefKind::Const { .. } => {
1362 // If the param has a default, ...
1363 if is_our_default(param) {
1364 let default_ct = tcx.const_param_default(param.def_id);
1365 // ... and it's not a dependent default, ...
1366 if !default_ct.needs_subst() {
1367 // ... then substitute it with the default.
1368 return default_ct.into();
1372 tcx.mk_param_from_def(param)
1377 // Now we build the substituted predicates.
1378 let default_obligations = predicates
1382 .flat_map(|&(pred, sp)| {
1384 struct CountParams {
1385 params: FxHashSet<u32>,
1387 impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1390 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1391 if let ty::Param(param) = t.kind() {
1392 self.params.insert(param.index);
1394 t.super_visit_with(self)
1397 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1401 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1402 if let ty::ConstKind::Param(param) = c.kind() {
1403 self.params.insert(param.index);
1405 c.super_visit_with(self)
1408 let mut param_count = CountParams::default();
1409 let has_region = pred.visit_with(&mut param_count).is_break();
1410 let substituted_pred = predicates.rebind(pred).subst(tcx, substs);
1411 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1412 // or preds with multiple params.
1413 if substituted_pred.has_param_types_or_consts()
1414 || param_count.params.len() > 1
1418 } else if predicates.0.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1419 // Avoid duplication of predicates that contain no parameters, for example.
1422 Some((substituted_pred, sp))
1426 // Convert each of those into an obligation. So if you have
1427 // something like `struct Foo<T: Copy = String>`, we would
1428 // take that predicate `T: Copy`, substitute to `String: Copy`
1429 // (actually that happens in the previous `flat_map` call),
1430 // and then try to prove it (in this case, we'll fail).
1432 // Note the subtle difference from how we handle `predicates`
1433 // below: there, we are not trying to prove those predicates
1434 // to be *true* but merely *well-formed*.
1435 let pred = wfcx.normalize(sp, None, pred);
1436 let cause = traits::ObligationCause::new(
1439 traits::ItemObligation(def_id.to_def_id()),
1441 traits::Obligation::new(cause, wfcx.param_env, pred)
1444 let predicates = predicates.0.instantiate_identity(tcx);
1446 let predicates = wfcx.normalize(span, None, predicates);
1448 debug!(?predicates.predicates);
1449 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1450 let wf_obligations =
1451 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1452 traits::wf::predicate_obligations(infcx, wfcx.param_env, wfcx.body_id, p, sp)
1455 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1456 wfcx.register_obligations(obligations);
1459 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1460 fn check_fn_or_method<'tcx>(
1461 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1463 sig: ty::PolyFnSig<'tcx>,
1464 hir_decl: &hir::FnDecl<'_>,
1467 let tcx = wfcx.tcx();
1468 let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1470 // Normalize the input and output types one at a time, using a different
1471 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1472 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1473 // for each type, preventing the HIR wf check from generating
1474 // a nice error message.
1475 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1476 inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1479 Some(WellFormedLoc::Param {
1481 // Note that the `param_idx` of the output type is
1482 // one greater than the index of the last input type.
1483 param_idx: i.try_into().unwrap(),
1488 // Manually call `normalize_associated_types_in` on the other types
1489 // in `FnSig`. This ensures that if the types of these fields
1490 // ever change to include projections, we will start normalizing
1491 // them automatically.
1492 let sig = ty::FnSig {
1494 c_variadic: wfcx.normalize(span, None, c_variadic),
1495 unsafety: wfcx.normalize(span, None, unsafety),
1496 abi: wfcx.normalize(span, None, abi),
1499 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1500 wfcx.register_wf_obligation(
1502 Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1507 wfcx.register_wf_obligation(hir_decl.output.span(), None, sig.output().into());
1509 check_where_clauses(wfcx, span, def_id);
1512 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1513 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1514 of the previous types except `Self`)";
1516 #[tracing::instrument(level = "debug", skip(wfcx))]
1517 fn check_method_receiver<'tcx>(
1518 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1519 fn_sig: &hir::FnSig<'_>,
1520 method: &ty::AssocItem,
1523 let tcx = wfcx.tcx();
1525 if !method.fn_has_self_parameter {
1529 let span = fn_sig.decl.inputs[0].span;
1531 let sig = tcx.fn_sig(method.def_id);
1532 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1533 let sig = wfcx.normalize(span, None, sig);
1535 debug!("check_method_receiver: sig={:?}", sig);
1537 let self_ty = wfcx.normalize(span, None, self_ty);
1539 let receiver_ty = sig.inputs()[0];
1540 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1542 if tcx.features().arbitrary_self_types {
1543 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1544 // Report error; `arbitrary_self_types` was enabled.
1545 e0307(tcx, span, receiver_ty);
1548 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1549 if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1550 // Report error; would have worked with `arbitrary_self_types`.
1552 &tcx.sess.parse_sess,
1553 sym::arbitrary_self_types,
1556 "`{receiver_ty}` cannot be used as the type of `self` without \
1557 the `arbitrary_self_types` feature",
1560 .help(HELP_FOR_SELF_TYPE)
1563 // Report error; would not have worked with `arbitrary_self_types`.
1564 e0307(tcx, span, receiver_ty);
1570 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1572 tcx.sess.diagnostic(),
1575 "invalid `self` parameter type: {receiver_ty}"
1577 .note("type of `self` must be `Self` or a type that dereferences to it")
1578 .help(HELP_FOR_SELF_TYPE)
1582 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1583 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1584 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1585 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1586 /// `Deref<Target = self_ty>`.
1588 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1589 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1590 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1591 fn receiver_is_valid<'tcx>(
1592 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1594 receiver_ty: Ty<'tcx>,
1596 arbitrary_self_types_enabled: bool,
1598 let infcx = wfcx.infcx;
1599 let tcx = wfcx.tcx();
1601 ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1603 let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1605 // `self: Self` is always valid.
1606 if can_eq_self(receiver_ty) {
1607 if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1608 infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1614 Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1616 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1617 if arbitrary_self_types_enabled {
1618 autoderef = autoderef.include_raw_pointers();
1621 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1624 let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1626 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1628 if let Some((potential_self_ty, _)) = autoderef.next() {
1630 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1631 potential_self_ty, self_ty
1634 if can_eq_self(potential_self_ty) {
1635 wfcx.register_obligations(autoderef.into_obligations());
1638 wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1640 infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1645 // Without `feature(arbitrary_self_types)`, we require that each step in the
1646 // deref chain implement `receiver`
1647 if !arbitrary_self_types_enabled
1648 && !receiver_is_implemented(
1650 receiver_trait_def_id,
1659 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1660 // If the receiver already has errors reported due to it, consider it valid to avoid
1661 // unnecessary errors (#58712).
1662 return receiver_ty.references_error();
1666 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1667 if !arbitrary_self_types_enabled
1668 && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1676 fn receiver_is_implemented<'tcx>(
1677 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1678 receiver_trait_def_id: DefId,
1679 cause: ObligationCause<'tcx>,
1680 receiver_ty: Ty<'tcx>,
1682 let tcx = wfcx.tcx();
1683 let trait_ref = ty::Binder::dummy(ty::TraitRef {
1684 def_id: receiver_trait_def_id,
1685 substs: tcx.mk_substs_trait(receiver_ty, &[]),
1689 traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1691 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1695 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1702 fn check_variances_for_type_defn<'tcx>(
1704 item: &hir::Item<'tcx>,
1705 hir_generics: &hir::Generics<'_>,
1707 let ty = tcx.type_of(item.def_id);
1708 if tcx.has_error_field(ty) {
1712 let ty_predicates = tcx.predicates_of(item.def_id);
1713 assert_eq!(ty_predicates.parent, None);
1714 let variances = tcx.variances_of(item.def_id);
1716 let mut constrained_parameters: FxHashSet<_> = variances
1719 .filter(|&(_, &variance)| variance != ty::Bivariant)
1720 .map(|(index, _)| Parameter(index as u32))
1723 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1725 // Lazily calculated because it is only needed in case of an error.
1726 let explicitly_bounded_params = LazyCell::new(|| {
1727 let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1731 .filter_map(|predicate| match predicate {
1732 hir::WherePredicate::BoundPredicate(predicate) => {
1733 match icx.to_ty(predicate.bounded_ty).kind() {
1734 ty::Param(data) => Some(Parameter(data.index)),
1740 .collect::<FxHashSet<_>>()
1743 for (index, _) in variances.iter().enumerate() {
1744 let parameter = Parameter(index as u32);
1746 if constrained_parameters.contains(¶meter) {
1750 let param = &hir_generics.params[index];
1753 hir::ParamName::Error => {}
1755 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
1756 report_bivariance(tcx, param, has_explicit_bounds);
1762 fn report_bivariance(
1764 param: &rustc_hir::GenericParam<'_>,
1765 has_explicit_bounds: bool,
1766 ) -> ErrorGuaranteed {
1767 let span = param.span;
1768 let param_name = param.name.ident().name;
1769 let mut err = error_392(tcx, span, param_name);
1771 let suggested_marker_id = tcx.lang_items().phantom_data();
1772 // Help is available only in presence of lang items.
1773 let msg = if let Some(def_id) = suggested_marker_id {
1775 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1777 tcx.def_path_str(def_id),
1780 format!("consider removing `{param_name}` or referring to it in a field")
1784 if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1786 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1793 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1794 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1796 fn check_false_global_bounds(&mut self) {
1797 let tcx = self.ocx.infcx.tcx;
1798 let mut span = self.span;
1799 let empty_env = ty::ParamEnv::empty();
1801 let def_id = tcx.hir().local_def_id(self.body_id);
1802 let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1803 // Check elaborated bounds.
1804 let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1806 for obligation in implied_obligations {
1807 // We lower empty bounds like `Vec<dyn Copy>:` as
1808 // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1809 // regular WF checking
1810 if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1813 let pred = obligation.predicate;
1814 // Match the existing behavior.
1815 if pred.is_global() && !pred.has_late_bound_regions() {
1816 let pred = self.normalize(span, None, pred);
1817 let hir_node = tcx.hir().find(self.body_id);
1819 // only use the span of the predicate clause (#90869)
1821 if let Some(hir::Generics { predicates, .. }) =
1822 hir_node.and_then(|node| node.generics())
1824 let obligation_span = obligation.cause.span();
1828 // There seems to be no better way to find out which predicate we are in
1829 .find(|pred| pred.span().contains(obligation_span))
1830 .map(|pred| pred.span())
1831 .unwrap_or(obligation_span);
1834 let obligation = traits::Obligation::new(
1835 traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1839 self.ocx.register_obligation(obligation);
1845 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1846 let items = tcx.hir_module_items(module);
1847 items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1848 items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1849 items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1850 items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1853 ///////////////////////////////////////////////////////////////////////////
1856 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1857 struct AdtVariant<'tcx> {
1858 /// Types of fields in the variant, that must be well-formed.
1859 fields: Vec<AdtField<'tcx>>,
1861 /// Explicit discriminant of this variant (e.g. `A = 123`),
1862 /// that must evaluate to a constant value.
1863 explicit_discr: Option<LocalDefId>,
1866 struct AdtField<'tcx> {
1872 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1873 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1874 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1875 let fields = struct_def
1879 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1880 let field_ty = self.tcx().type_of(def_id);
1881 let field_ty = self.normalize(field.ty.span, None, field_ty);
1882 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1883 AdtField { ty: field_ty, span: field.ty.span, def_id }
1886 AdtVariant { fields, explicit_discr: None }
1889 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1893 .map(|variant| AdtVariant {
1894 fields: self.non_enum_variant(&variant.data).fields,
1895 explicit_discr: variant
1897 .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1907 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1908 let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1909 err.span_label(span, "unused parameter");
1913 pub fn provide(providers: &mut Providers) {
1914 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };