1 use crate::check::regionck::OutlivesEnvironmentExt;
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
7 use rustc_hir::def_id::{DefId, LocalDefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::ItemKind;
10 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
11 use rustc_infer::infer::outlives::obligations::TypeOutlives;
12 use rustc_infer::infer::region_constraints::GenericKind;
13 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
14 use rustc_infer::traits::Normalized;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
17 use rustc_middle::ty::trait_def::TraitSpecializationKind;
18 use rustc_middle::ty::{
19 self, AdtKind, DefIdTree, EarlyBinder, GenericParamDefKind, ToPredicate, Ty, TyCtxt,
20 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitor,
22 use rustc_session::parse::feature_err;
23 use rustc_span::symbol::{sym, Ident, Symbol};
24 use rustc_span::{Span, DUMMY_SP};
25 use rustc_trait_selection::autoderef::Autoderef;
26 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
28 use rustc_trait_selection::traits::query::normalize::AtExt;
29 use rustc_trait_selection::traits::query::NoSolution;
30 use rustc_trait_selection::traits::{
31 self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
34 use std::cell::LazyCell;
35 use std::convert::TryInto;
37 use std::ops::{ControlFlow, Deref};
39 pub(super) struct WfCheckingCtxt<'a, 'tcx> {
40 pub(super) ocx: ObligationCtxt<'a, 'tcx>,
43 param_env: ty::ParamEnv<'tcx>,
45 impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
46 type Target = ObligationCtxt<'a, 'tcx>;
47 fn deref(&self) -> &Self::Target {
52 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
53 fn tcx(&self) -> TyCtxt<'tcx> {
57 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
59 T: TypeFoldable<'tcx>,
62 ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)),
68 fn register_wf_obligation(
71 loc: Option<WellFormedLoc>,
72 arg: ty::GenericArg<'tcx>,
75 traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc));
76 self.ocx.register_obligation(traits::Obligation::new(
79 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
84 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
87 body_def_id: LocalDefId,
90 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> FxHashSet<Ty<'tcx>>,
92 let param_env = tcx.param_env(body_def_id);
93 let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
94 tcx.infer_ctxt().enter(|ref infcx| {
95 let ocx = ObligationCtxt::new(infcx);
96 let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
98 if !tcx.features().trivial_bounds {
99 wfcx.check_false_global_bounds()
101 let wf_tys = f(&mut wfcx);
102 let errors = wfcx.select_all_or_error();
103 if !errors.is_empty() {
104 infcx.report_fulfillment_errors(&errors, None, false);
108 let mut outlives_environment = OutlivesEnvironment::new(param_env);
109 outlives_environment.add_implied_bounds(infcx, wf_tys, body_id);
110 infcx.check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
114 fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
115 let node = tcx.hir().expect_owner(def_id);
117 hir::OwnerNode::Crate(_) => {}
118 hir::OwnerNode::Item(item) => check_item(tcx, item),
119 hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
120 hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
121 hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
124 if let Some(generics) = node.generics() {
125 for param in generics.params {
126 check_param_wf(tcx, param)
131 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
132 /// well-formed, meaning that they do not require any constraints not declared in the struct
133 /// definition itself. For example, this definition would be illegal:
136 /// struct Ref<'a, T> { x: &'a T }
139 /// because the type did not declare that `T:'a`.
141 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
142 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
144 #[instrument(skip(tcx), level = "debug")]
145 fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
146 let def_id = item.def_id;
150 item.name = ? tcx.def_path_str(def_id.to_def_id())
154 // Right now we check that every default trait implementation
155 // has an implementation of itself. Basically, a case like:
157 // impl Trait for T {}
159 // has a requirement of `T: Trait` which was required for default
160 // method implementations. Although this could be improved now that
161 // there's a better infrastructure in place for this, it's being left
162 // for a follow-up work.
164 // Since there's such a requirement, we need to check *just* positive
165 // implementations, otherwise things like:
167 // impl !Send for T {}
169 // won't be allowed unless there's an *explicit* implementation of `Send`
171 hir::ItemKind::Impl(ref impl_) => {
173 .impl_trait_ref(item.def_id)
174 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
175 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
176 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
178 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
179 err.span_labels(impl_.defaultness_span, "default because of this");
180 err.span_label(sp, "auto trait");
183 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
184 match (tcx.impl_polarity(def_id), impl_.polarity) {
185 (ty::ImplPolarity::Positive, _) => {
186 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
188 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
189 // FIXME(#27579): what amount of WF checking do we need for neg impls?
190 if let hir::Defaultness::Default { .. } = impl_.defaultness {
191 let mut spans = vec![span];
192 spans.extend(impl_.defaultness_span);
197 "negative impls cannot be default impls"
202 (ty::ImplPolarity::Reservation, _) => {
203 // FIXME: what amount of WF checking do we need for reservation impls?
208 hir::ItemKind::Fn(ref sig, ..) => {
209 check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
211 hir::ItemKind::Static(ty, ..) => {
212 check_item_type(tcx, item.def_id, ty.span, false);
214 hir::ItemKind::Const(ty, ..) => {
215 check_item_type(tcx, item.def_id, ty.span, false);
217 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
218 check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
220 check_variances_for_type_defn(tcx, item, ast_generics);
222 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
223 check_type_defn(tcx, item, true, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
225 check_variances_for_type_defn(tcx, item, ast_generics);
227 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
228 check_type_defn(tcx, item, true, |wfcx| wfcx.enum_variants(enum_def));
230 check_variances_for_type_defn(tcx, item, ast_generics);
232 hir::ItemKind::Trait(..) => {
233 check_trait(tcx, item);
235 hir::ItemKind::TraitAlias(..) => {
236 check_trait(tcx, item);
238 // `ForeignItem`s are handled separately.
239 hir::ItemKind::ForeignMod { .. } => {}
244 fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
245 let def_id = item.def_id;
249 item.name = ? tcx.def_path_str(def_id.to_def_id())
253 hir::ForeignItemKind::Fn(decl, ..) => {
254 check_item_fn(tcx, item.def_id, item.ident, item.span, decl)
256 hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true),
257 hir::ForeignItemKind::Type => (),
261 fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
262 let def_id = trait_item.def_id;
264 let (method_sig, span) = match trait_item.kind {
265 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
266 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
267 _ => (None, trait_item.span),
269 check_object_unsafe_self_trait_by_name(tcx, trait_item);
270 check_associated_item(tcx, trait_item.def_id, span, method_sig);
272 let encl_trait_def_id = tcx.local_parent(def_id);
273 let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
274 let encl_trait_def_id = encl_trait.def_id.to_def_id();
275 let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
277 } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
283 if let (Some(fn_lang_item_name), "call") =
284 (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
286 // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
287 // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
288 if let Some(hir::FnSig { decl, span, .. }) = method_sig {
289 if let [self_ty, _] = decl.inputs {
290 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
295 "first argument of `call` in `{fn_lang_item_name}` lang item must be a reference",
305 "`call` function in `{fn_lang_item_name}` lang item takes exactly two arguments",
315 "`call` trait item in `{fn_lang_item_name}` lang item must be a function",
323 /// Require that the user writes where clauses on GATs for the implicit
324 /// outlives bounds involving trait parameters in trait functions and
325 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
327 /// We use the following trait as an example throughout this function:
328 /// ```rust,ignore (this code fails due to this lint)
330 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
332 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
335 fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRef]) {
336 // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
337 let mut required_bounds_by_item = FxHashMap::default();
339 // Loop over all GATs together, because if this lint suggests adding a where-clause bound
340 // to one GAT, it might then require us to an additional bound on another GAT.
341 // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
342 // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
345 let mut should_continue = false;
346 for gat_item in associated_items {
347 let gat_def_id = gat_item.id.def_id;
348 let gat_item = tcx.associated_item(gat_def_id);
349 // If this item is not an assoc ty, or has no substs, then it's not a GAT
350 if gat_item.kind != ty::AssocKind::Type {
353 let gat_generics = tcx.generics_of(gat_def_id);
354 // FIXME(jackh726): we can also warn in the more general case
355 if gat_generics.params.is_empty() {
359 // Gather the bounds with which all other items inside of this trait constrain the GAT.
360 // This is calculated by taking the intersection of the bounds that each item
361 // constrains the GAT with individually.
362 let mut new_required_bounds: Option<FxHashSet<ty::Predicate<'_>>> = None;
363 for item in associated_items {
364 let item_def_id = item.id.def_id;
365 // Skip our own GAT, since it does not constrain itself at all.
366 if item_def_id == gat_def_id {
370 let item_hir_id = item.id.hir_id();
371 let param_env = tcx.param_env(item_def_id);
373 let item_required_bounds = match item.kind {
374 // In our example, this corresponds to `into_iter` method
375 hir::AssocItemKind::Fn { .. } => {
376 // For methods, we check the function signature's return type for any GATs
377 // to constrain. In the `into_iter` case, we see that the return type
378 // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
379 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
380 item_def_id.to_def_id(),
381 tcx.fn_sig(item_def_id),
388 // We also assume that all of the function signature's parameter types
390 &sig.inputs().iter().copied().collect(),
395 // In our example, this corresponds to the `Iter` and `Item` associated types
396 hir::AssocItemKind::Type => {
397 // If our associated item is a GAT with missing bounds, add them to
398 // the param-env here. This allows this GAT to propagate missing bounds
400 let param_env = augment_param_env(
403 required_bounds_by_item.get(&item_def_id),
409 tcx.explicit_item_bounds(item_def_id)
412 .collect::<Vec<_>>(),
413 &FxHashSet::default(),
418 hir::AssocItemKind::Const => None,
421 if let Some(item_required_bounds) = item_required_bounds {
422 // Take the intersection of the required bounds for this GAT, and
423 // the item_required_bounds which are the ones implied by just
425 // This is why we use an Option<_>, since we need to distinguish
426 // the empty set of bounds from the _uninitialized_ set of bounds.
427 if let Some(new_required_bounds) = &mut new_required_bounds {
428 new_required_bounds.retain(|b| item_required_bounds.contains(b));
430 new_required_bounds = Some(item_required_bounds);
435 if let Some(new_required_bounds) = new_required_bounds {
436 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
437 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
438 // Iterate until our required_bounds no longer change
439 // Since they changed here, we should continue the loop
440 should_continue = true;
444 // We know that this loop will eventually halt, since we only set `should_continue` if the
445 // `required_bounds` for this item grows. Since we are not creating any new region or type
446 // variables, the set of all region and type bounds that we could ever insert are limited
447 // by the number of unique types and regions we observe in a given item.
448 if !should_continue {
453 for (gat_def_id, required_bounds) in required_bounds_by_item {
454 let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id);
455 debug!(?required_bounds);
456 let param_env = tcx.param_env(gat_def_id);
457 let gat_hir = gat_item_hir.hir_id();
459 let mut unsatisfied_bounds: Vec<_> = required_bounds
461 .filter(|clause| match clause.kind().skip_binder() {
462 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
463 !region_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
465 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
466 !ty_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
468 _ => bug!("Unexpected PredicateKind"),
470 .map(|clause| clause.to_string())
473 // We sort so that order is predictable
474 unsatisfied_bounds.sort();
476 if !unsatisfied_bounds.is_empty() {
477 let plural = pluralize!(unsatisfied_bounds.len());
478 let mut err = tcx.sess.struct_span_err(
480 &format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
483 let suggestion = format!(
485 gat_item_hir.generics.add_where_or_trailing_comma(),
486 unsatisfied_bounds.join(", "),
489 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
490 &format!("add the required where clause{plural}"),
492 Applicability::MachineApplicable,
496 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
498 "{} currently required to ensure that impls have maximum flexibility",
502 "we are soliciting feedback, see issue #87479 \
503 <https://github.com/rust-lang/rust/issues/87479> \
504 for more information",
512 /// Add a new set of predicates to the caller_bounds of an existing param_env.
513 fn augment_param_env<'tcx>(
515 param_env: ty::ParamEnv<'tcx>,
516 new_predicates: Option<&FxHashSet<ty::Predicate<'tcx>>>,
517 ) -> ty::ParamEnv<'tcx> {
518 let Some(new_predicates) = new_predicates else {
522 if new_predicates.is_empty() {
527 tcx.mk_predicates(param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()));
528 // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
529 // i.e. traits::normalize_param_env_or_error
530 ty::ParamEnv::new(bounds, param_env.reveal(), param_env.constness())
533 /// We use the following trait as an example throughout this function.
534 /// Specifically, let's assume that `to_check` here is the return type
535 /// of `into_iter`, and the GAT we are checking this for is `Iter`.
536 /// ```rust,ignore (this code fails due to this lint)
538 /// type Iter<'a>: Iterator<Item = Self::Item<'a>>;
540 /// fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
543 fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>(
545 param_env: ty::ParamEnv<'tcx>,
546 item_hir: hir::HirId,
548 wf_tys: &FxHashSet<Ty<'tcx>>,
549 gat_def_id: LocalDefId,
550 gat_generics: &'tcx ty::Generics,
551 ) -> Option<FxHashSet<ty::Predicate<'tcx>>> {
552 // The bounds we that we would require from `to_check`
553 let mut bounds = FxHashSet::default();
555 let (regions, types) = GATSubstCollector::visit(gat_def_id.to_def_id(), to_check);
557 // If both regions and types are empty, then this GAT isn't in the
558 // set of types we are checking, and we shouldn't try to do clause analysis
559 // (particularly, doing so would end up with an empty set of clauses,
560 // since the current method would require none, and we take the
561 // intersection of requirements of all methods)
562 if types.is_empty() && regions.is_empty() {
566 for (region_a, region_a_idx) in ®ions {
567 // Ignore `'static` lifetimes for the purpose of this lint: it's
568 // because we know it outlives everything and so doesn't give meaningful
570 if let ty::ReStatic = **region_a {
573 // For each region argument (e.g., `'a` in our example), check for a
574 // relationship to the type arguments (e.g., `Self`). If there is an
575 // outlives relationship (`Self: 'a`), then we want to ensure that is
576 // reflected in a where clause on the GAT itself.
577 for (ty, ty_idx) in &types {
578 // In our example, requires that `Self: 'a`
579 if ty_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *ty, *region_a) {
580 debug!(?ty_idx, ?region_a_idx);
581 debug!("required clause: {ty} must outlive {region_a}");
582 // Translate into the generic parameters of the GAT. In
583 // our example, the type was `Self`, which will also be
584 // `Self` in the GAT.
585 let ty_param = gat_generics.param_at(*ty_idx, tcx);
587 .mk_ty(ty::Param(ty::ParamTy { index: ty_param.index, name: ty_param.name }));
588 // Same for the region. In our example, 'a corresponds
589 // to the 'me parameter.
590 let region_param = gat_generics.param_at(*region_a_idx, tcx);
592 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
593 def_id: region_param.def_id,
594 index: region_param.index,
595 name: region_param.name,
597 // The predicate we expect to see. (In our example,
600 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param));
601 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
602 bounds.insert(clause);
606 // For each region argument (e.g., `'a` in our example), also check for a
607 // relationship to the other region arguments. If there is an outlives
608 // relationship, then we want to ensure that is reflected in the where clause
609 // on the GAT itself.
610 for (region_b, region_b_idx) in ®ions {
611 // Again, skip `'static` because it outlives everything. Also, we trivially
612 // know that a region outlives itself.
613 if ty::ReStatic == **region_b || region_a == region_b {
616 if region_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *region_a, *region_b) {
617 debug!(?region_a_idx, ?region_b_idx);
618 debug!("required clause: {region_a} must outlive {region_b}");
619 // Translate into the generic parameters of the GAT.
620 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
622 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
623 def_id: region_a_param.def_id,
624 index: region_a_param.index,
625 name: region_a_param.name,
627 // Same for the region.
628 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
630 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
631 def_id: region_b_param.def_id,
632 index: region_b_param.index,
633 name: region_b_param.name,
635 // The predicate we expect to see.
636 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
640 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
641 bounds.insert(clause);
649 /// Given a known `param_env` and a set of well formed types, can we prove that
650 /// `ty` outlives `region`.
651 fn ty_known_to_outlive<'tcx>(
654 param_env: ty::ParamEnv<'tcx>,
655 wf_tys: &FxHashSet<Ty<'tcx>>,
657 region: ty::Region<'tcx>,
659 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
660 let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
661 let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
662 outlives.type_must_outlive(origin, ty, region);
666 /// Given a known `param_env` and a set of well formed types, can we prove that
667 /// `region_a` outlives `region_b`
668 fn region_known_to_outlive<'tcx>(
671 param_env: ty::ParamEnv<'tcx>,
672 wf_tys: &FxHashSet<Ty<'tcx>>,
673 region_a: ty::Region<'tcx>,
674 region_b: ty::Region<'tcx>,
676 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
677 use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
678 let origin = infer::RelateRegionParamBound(DUMMY_SP);
679 // `region_a: region_b` -> `region_b <= region_a`
680 infcx.push_sub_region_constraint(origin, region_b, region_a);
684 /// Given a known `param_env` and a set of well formed types, set up an
685 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
686 /// to be tested), then resolve region and return errors
687 fn resolve_regions_with_wf_tys<'tcx>(
690 param_env: ty::ParamEnv<'tcx>,
691 wf_tys: &FxHashSet<Ty<'tcx>>,
692 add_constraints: impl for<'a> FnOnce(
693 &'a InferCtxt<'a, 'tcx>,
694 &'a Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
697 // Unfortunately, we have to use a new `InferCtxt` each call, because
698 // region constraints get added and solved there and we need to test each
699 // call individually.
700 tcx.infer_ctxt().enter(|infcx| {
701 let mut outlives_environment = OutlivesEnvironment::new(param_env);
702 outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
703 let region_bound_pairs = outlives_environment.region_bound_pairs();
705 add_constraints(&infcx, region_bound_pairs);
707 let errors = infcx.resolve_regions(&outlives_environment);
709 debug!(?errors, "errors");
711 // If we were able to prove that the type outlives the region without
712 // an error, it must be because of the implied or explicit bounds...
717 /// TypeVisitor that looks for uses of GATs like
718 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
719 /// the two vectors, `regions` and `types` (depending on their kind). For each
720 /// parameter `Pi` also track the index `i`.
721 struct GATSubstCollector<'tcx> {
723 // Which region appears and which parameter index its substituted for
724 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
725 // Which params appears and which parameter index its substituted for
726 types: FxHashSet<(Ty<'tcx>, usize)>,
729 impl<'tcx> GATSubstCollector<'tcx> {
730 fn visit<T: TypeFoldable<'tcx>>(
733 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
735 GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
736 t.visit_with(&mut visitor);
737 (visitor.regions, visitor.types)
741 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
744 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
746 ty::Projection(p) if p.item_def_id == self.gat => {
747 for (idx, subst) in p.substs.iter().enumerate() {
748 match subst.unpack() {
749 GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
750 self.regions.insert((lt, idx));
752 GenericArgKind::Type(t) => {
753 self.types.insert((t, idx));
761 t.super_visit_with(self)
765 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
767 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
768 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
775 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
776 /// When this is done, suggest using `Self` instead.
777 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
778 let (trait_name, trait_def_id) =
779 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
780 hir::Node::Item(item) => match item.kind {
781 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
786 let mut trait_should_be_self = vec![];
788 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
789 if could_be_self(trait_def_id, ty) =>
791 trait_should_be_self.push(ty.span)
793 hir::TraitItemKind::Fn(sig, _) => {
794 for ty in sig.decl.inputs {
795 if could_be_self(trait_def_id, ty) {
796 trait_should_be_self.push(ty.span);
799 match sig.decl.output {
800 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
801 trait_should_be_self.push(ty.span);
808 if !trait_should_be_self.is_empty() {
809 if tcx.object_safety_violations(trait_def_id).is_empty() {
812 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
815 trait_should_be_self,
816 "associated item referring to unboxed trait object for its own trait",
818 .span_label(trait_name.span, "in this trait")
819 .multipart_suggestion(
820 "you might have meant to use `Self` to refer to the implementing type",
822 Applicability::MachineApplicable,
828 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
829 let def_id = impl_item.def_id;
831 let (method_sig, span) = match impl_item.kind {
832 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
833 // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
834 hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
835 _ => (None, impl_item.span),
838 check_associated_item(tcx, def_id, span, method_sig);
841 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
843 // We currently only check wf of const params here.
844 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
846 // Const parameters are well formed if their type is structural match.
847 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
848 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
850 if tcx.features().adt_const_params {
851 let err = match ty.peel_refs().kind() {
852 ty::FnPtr(_) => Some("function pointers"),
853 ty::RawPtr(_) => Some("raw pointers"),
857 if let Some(unsupported_type) = err {
861 "using {} as const generic parameters is forbidden",
867 if let Some(non_structural_match_ty) =
868 traits::search_for_structural_match_violation(param.span, tcx, ty, false)
870 // We use the same error code in both branches, because this is really the same
871 // issue: we just special-case the message for type parameters to make it
873 match ty.peel_refs().kind() {
875 // Const parameters may not have type parameters as their types,
876 // because we cannot be sure that the type parameter derives `PartialEq`
877 // and `Eq` (just implementing them is not enough for `structural_match`).
882 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
883 used as the type of a const parameter",
887 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
890 "it is not currently possible to use a type parameter as the type of a \
900 "`{ty}` is forbidden as the type of a const generic parameter",
902 .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
906 let mut diag = struct_span_err!(
910 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
911 the type of a const parameter",
912 non_structural_match_ty.ty,
915 if ty == non_structural_match_ty.ty {
918 format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
928 let mut is_ptr = true;
930 let err = match ty.kind() {
931 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
932 ty::FnPtr(_) => Some("function pointers"),
933 ty::RawPtr(_) => Some("raw pointers"),
936 err_ty_str = format!("`{ty}`");
937 Some(err_ty_str.as_str())
941 if let Some(unsupported_type) = err {
946 "using {unsupported_type} as const generic parameters is forbidden",
950 let mut err = tcx.sess.struct_span_err(
953 "{unsupported_type} is forbidden as the type of a const generic parameter",
956 err.note("the only supported types are integers, `bool` and `char`");
957 if tcx.sess.is_nightly_build() {
959 "more complex types are supported with `#![feature(adt_const_params)]`",
970 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
971 fn check_associated_item(
975 sig_if_method: Option<&hir::FnSig<'_>>,
977 let loc = Some(WellFormedLoc::Ty(item_id));
978 enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
979 let item = tcx.associated_item(item_id);
981 let (mut implied_bounds, self_ty) = match item.container {
982 ty::TraitContainer(_) => (FxHashSet::default(), tcx.types.self_param),
983 ty::ImplContainer(def_id) => (
984 impl_implied_bounds(tcx, wfcx.param_env, def_id.expect_local(), span),
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(),
1004 &mut implied_bounds,
1006 check_method_receiver(wfcx, hir_sig, item, self_ty);
1008 ty::AssocKind::Type => {
1009 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
1010 check_associated_type_bounds(wfcx, item, span)
1012 if item.defaultness.has_value() {
1013 let ty = tcx.type_of(item.def_id);
1014 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1015 wfcx.register_wf_obligation(span, loc, ty.into());
1024 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1026 ItemKind::Struct(..) => Some(AdtKind::Struct),
1027 ItemKind::Union(..) => Some(AdtKind::Union),
1028 ItemKind::Enum(..) => Some(AdtKind::Enum),
1033 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1034 fn check_type_defn<'tcx, F>(
1036 item: &hir::Item<'tcx>,
1038 mut lookup_fields: F,
1040 F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
1042 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1043 let variants = lookup_fields(wfcx);
1044 let packed = tcx.adt_def(item.def_id).repr().packed();
1046 for variant in &variants {
1047 // All field types must be well-formed.
1048 for field in &variant.fields {
1049 wfcx.register_wf_obligation(
1051 Some(WellFormedLoc::Ty(field.def_id)),
1056 // For DST, or when drop needs to copy things around, all
1057 // intermediate types must be sized.
1058 let needs_drop_copy = || {
1060 let ty = variant.fields.last().unwrap().ty;
1061 let ty = tcx.erase_regions(ty);
1062 if ty.needs_infer() {
1064 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1065 // Just treat unresolved type expression as if it needs drop.
1068 ty.needs_drop(tcx, tcx.param_env(item.def_id))
1072 // All fields (except for possibly the last) should be sized.
1073 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1074 let unsized_len = if all_sized { 0 } else { 1 };
1076 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1078 let last = idx == variant.fields.len() - 1;
1079 wfcx.register_bound(
1080 traits::ObligationCause::new(
1083 traits::FieldSized {
1084 adt_kind: match item_adt_kind(&item.kind) {
1094 tcx.require_lang_item(LangItem::Sized, None),
1098 // Explicit `enum` discriminant values must const-evaluate successfully.
1099 if let Some(discr_def_id) = variant.explicit_discr {
1100 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
1102 let cause = traits::ObligationCause::new(
1103 tcx.def_span(discr_def_id),
1105 traits::MiscObligation,
1107 wfcx.register_obligation(traits::Obligation::new(
1110 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
1111 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
1119 check_where_clauses(wfcx, item.span, item.def_id);
1121 // No implied bounds in a struct definition.
1122 FxHashSet::default()
1126 #[instrument(skip(tcx, item))]
1127 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1128 debug!(?item.def_id);
1130 let trait_def = tcx.trait_def(item.def_id);
1131 if trait_def.is_marker
1132 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1134 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1137 tcx.def_span(*associated_def_id),
1139 "marker traits cannot have associated items",
1145 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1146 check_where_clauses(wfcx, item.span, item.def_id);
1148 FxHashSet::default()
1151 // Only check traits, don't check trait aliases
1152 if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1153 check_gat_where_clauses(tcx, items);
1157 /// Checks all associated type defaults of trait `trait_def_id`.
1159 /// Assuming the defaults are used, check that all predicates (bounds on the
1160 /// assoc type and where clauses on the trait) hold.
1161 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1162 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1164 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1165 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1166 let normalized_bound = wfcx.normalize(span, None, bound);
1167 traits::wf::predicate_obligations(
1176 wfcx.register_obligations(wf_obligations);
1184 decl: &hir::FnDecl<'_>,
1186 enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1187 let sig = tcx.fn_sig(def_id);
1188 let mut implied_bounds = FxHashSet::default();
1189 check_fn_or_method(wfcx, ident.span, sig, decl, def_id, &mut implied_bounds);
1194 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1195 debug!("check_item_type: {:?}", item_id);
1197 enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1198 let ty = tcx.type_of(item_id);
1199 let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1201 let mut forbid_unsized = true;
1202 if allow_foreign_ty {
1203 let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1204 if let ty::Foreign(_) = tail.kind() {
1205 forbid_unsized = false;
1209 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1211 wfcx.register_bound(
1212 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
1215 tcx.require_lang_item(LangItem::Sized, None),
1219 // Ensure that the end result is `Sync` in a non-thread local `static`.
1220 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1221 == Some(hir::Mutability::Not)
1222 && !tcx.is_foreign_item(item_id.to_def_id())
1223 && !tcx.is_thread_local_static(item_id.to_def_id());
1225 if should_check_for_sync {
1226 wfcx.register_bound(
1227 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
1230 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1234 // No implied bounds in a const, etc.
1235 FxHashSet::default()
1239 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1240 fn check_impl<'tcx>(
1242 item: &'tcx hir::Item<'tcx>,
1243 ast_self_ty: &hir::Ty<'_>,
1244 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1245 constness: hir::Constness,
1247 enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1248 match *ast_trait_ref {
1249 Some(ref ast_trait_ref) => {
1250 // `#[rustc_reservation_impl]` impls are not real impls and
1251 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1253 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1254 let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
1255 let trait_pred = ty::TraitPredicate {
1257 constness: match constness {
1258 hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1259 hir::Constness::NotConst => ty::BoundConstness::NotConst,
1261 polarity: ty::ImplPolarity::Positive,
1263 let obligations = traits::wf::trait_obligations(
1268 ast_trait_ref.path.span,
1271 debug!(?obligations);
1272 wfcx.register_obligations(obligations);
1275 let self_ty = tcx.type_of(item.def_id);
1276 let self_ty = wfcx.normalize(item.span, None, self_ty);
1277 wfcx.register_wf_obligation(
1279 Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1285 check_where_clauses(wfcx, item.span, item.def_id);
1287 impl_implied_bounds(tcx, wfcx.param_env, item.def_id, item.span)
1291 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1292 #[instrument(level = "debug", skip(wfcx))]
1293 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1294 let infcx = wfcx.infcx;
1295 let tcx = wfcx.tcx();
1297 let predicates = tcx.predicates_of(def_id);
1298 let generics = tcx.generics_of(def_id);
1300 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1301 GenericParamDefKind::Type { has_default, .. }
1302 | GenericParamDefKind::Const { has_default } => {
1303 has_default && def.index >= generics.parent_count as u32
1305 GenericParamDefKind::Lifetime => unreachable!(),
1308 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1309 // For example, this forbids the declaration:
1311 // struct Foo<T = Vec<[u32]>> { .. }
1313 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1314 for param in &generics.params {
1316 GenericParamDefKind::Type { .. } => {
1317 if is_our_default(param) {
1318 let ty = tcx.type_of(param.def_id);
1319 // Ignore dependent defaults -- that is, where the default of one type
1320 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1321 // be sure if it will error or not as user might always specify the other.
1322 if !ty.needs_subst() {
1323 wfcx.register_wf_obligation(tcx.def_span(param.def_id), None, ty.into());
1327 GenericParamDefKind::Const { .. } => {
1328 if is_our_default(param) {
1329 // FIXME(const_generics_defaults): This
1330 // is incorrect when dealing with unused substs, for example
1331 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1332 // we should eagerly error.
1333 let default_ct = tcx.const_param_default(param.def_id);
1334 if !default_ct.needs_subst() {
1335 wfcx.register_wf_obligation(
1336 tcx.def_span(param.def_id),
1343 // Doesn't have defaults.
1344 GenericParamDefKind::Lifetime => {}
1348 // Check that trait predicates are WF when params are substituted by their defaults.
1349 // We don't want to overly constrain the predicates that may be written but we want to
1350 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1351 // Therefore we check if a predicate which contains a single type param
1352 // with a concrete default is WF with that default substituted.
1353 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1355 // First we build the defaulted substitution.
1356 let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1358 GenericParamDefKind::Lifetime => {
1359 // All regions are identity.
1360 tcx.mk_param_from_def(param)
1363 GenericParamDefKind::Type { .. } => {
1364 // If the param has a default, ...
1365 if is_our_default(param) {
1366 let default_ty = tcx.type_of(param.def_id);
1367 // ... and it's not a dependent default, ...
1368 if !default_ty.needs_subst() {
1369 // ... then substitute it with the default.
1370 return default_ty.into();
1374 tcx.mk_param_from_def(param)
1376 GenericParamDefKind::Const { .. } => {
1377 // If the param has a default, ...
1378 if is_our_default(param) {
1379 let default_ct = tcx.const_param_default(param.def_id);
1380 // ... and it's not a dependent default, ...
1381 if !default_ct.needs_subst() {
1382 // ... then substitute it with the default.
1383 return default_ct.into();
1387 tcx.mk_param_from_def(param)
1392 // Now we build the substituted predicates.
1393 let default_obligations = predicates
1396 .flat_map(|&(pred, sp)| {
1398 struct CountParams {
1399 params: FxHashSet<u32>,
1401 impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1404 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1405 if let ty::Param(param) = t.kind() {
1406 self.params.insert(param.index);
1408 t.super_visit_with(self)
1411 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1415 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1416 if let ty::ConstKind::Param(param) = c.kind() {
1417 self.params.insert(param.index);
1419 c.super_visit_with(self)
1422 let mut param_count = CountParams::default();
1423 let has_region = pred.visit_with(&mut param_count).is_break();
1424 let substituted_pred = EarlyBinder(pred).subst(tcx, substs);
1425 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1426 // or preds with multiple params.
1427 if substituted_pred.has_param_types_or_consts()
1428 || param_count.params.len() > 1
1432 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1433 // Avoid duplication of predicates that contain no parameters, for example.
1436 Some((substituted_pred, sp))
1440 // Convert each of those into an obligation. So if you have
1441 // something like `struct Foo<T: Copy = String>`, we would
1442 // take that predicate `T: Copy`, substitute to `String: Copy`
1443 // (actually that happens in the previous `flat_map` call),
1444 // and then try to prove it (in this case, we'll fail).
1446 // Note the subtle difference from how we handle `predicates`
1447 // below: there, we are not trying to prove those predicates
1448 // to be *true* but merely *well-formed*.
1449 let pred = wfcx.normalize(sp, None, pred);
1450 let cause = traits::ObligationCause::new(
1453 traits::ItemObligation(def_id.to_def_id()),
1455 traits::Obligation::new(cause, wfcx.param_env, pred)
1458 let predicates = predicates.instantiate_identity(tcx);
1460 let predicates = wfcx.normalize(span, None, predicates);
1462 debug!(?predicates.predicates);
1463 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1464 let wf_obligations =
1465 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1466 traits::wf::predicate_obligations(infcx, wfcx.param_env, wfcx.body_id, p, sp)
1469 let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1470 wfcx.register_obligations(obligations);
1473 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1474 fn check_fn_or_method<'tcx>(
1475 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1477 sig: ty::PolyFnSig<'tcx>,
1478 hir_decl: &hir::FnDecl<'_>,
1480 implied_bounds: &mut FxHashSet<Ty<'tcx>>,
1482 let tcx = wfcx.tcx();
1483 let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1485 // Normalize the input and output types one at a time, using a different
1486 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1487 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1488 // for each type, preventing the HIR wf check from generating
1489 // a nice error message.
1490 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1491 inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1494 Some(WellFormedLoc::Param {
1496 // Note that the `param_idx` of the output type is
1497 // one greater than the index of the last input type.
1498 param_idx: i.try_into().unwrap(),
1503 // Manually call `normalize_associated_types_in` on the other types
1504 // in `FnSig`. This ensures that if the types of these fields
1505 // ever change to include projections, we will start normalizing
1506 // them automatically.
1507 let sig = ty::FnSig {
1509 c_variadic: wfcx.normalize(span, None, c_variadic),
1510 unsafety: wfcx.normalize(span, None, unsafety),
1511 abi: wfcx.normalize(span, None, abi),
1514 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1515 wfcx.register_wf_obligation(
1517 Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1522 implied_bounds.extend(sig.inputs());
1524 wfcx.register_wf_obligation(hir_decl.output.span(), None, sig.output().into());
1526 // FIXME(#27579) return types should not be implied bounds
1527 implied_bounds.insert(sig.output());
1529 debug!(?implied_bounds);
1531 check_where_clauses(wfcx, span, def_id);
1534 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1535 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1536 of the previous types except `Self`)";
1538 #[tracing::instrument(level = "debug", skip(wfcx))]
1539 fn check_method_receiver<'tcx>(
1540 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1541 fn_sig: &hir::FnSig<'_>,
1542 method: &ty::AssocItem,
1545 let tcx = wfcx.tcx();
1547 if !method.fn_has_self_parameter {
1551 let span = fn_sig.decl.inputs[0].span;
1553 let sig = tcx.fn_sig(method.def_id);
1554 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1555 let sig = wfcx.normalize(span, None, sig);
1557 debug!("check_method_receiver: sig={:?}", sig);
1559 let self_ty = wfcx.normalize(span, None, self_ty);
1561 let receiver_ty = sig.inputs()[0];
1562 let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1564 if tcx.features().arbitrary_self_types {
1565 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1566 // Report error; `arbitrary_self_types` was enabled.
1567 e0307(tcx, span, receiver_ty);
1570 if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1571 if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1572 // Report error; would have worked with `arbitrary_self_types`.
1574 &tcx.sess.parse_sess,
1575 sym::arbitrary_self_types,
1578 "`{receiver_ty}` cannot be used as the type of `self` without \
1579 the `arbitrary_self_types` feature",
1582 .help(HELP_FOR_SELF_TYPE)
1585 // Report error; would not have worked with `arbitrary_self_types`.
1586 e0307(tcx, span, receiver_ty);
1592 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1594 tcx.sess.diagnostic(),
1597 "invalid `self` parameter type: {receiver_ty}"
1599 .note("type of `self` must be `Self` or a type that dereferences to it")
1600 .help(HELP_FOR_SELF_TYPE)
1604 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1605 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1606 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1607 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1608 /// `Deref<Target = self_ty>`.
1610 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1611 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1612 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1613 fn receiver_is_valid<'tcx>(
1614 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1616 receiver_ty: Ty<'tcx>,
1618 arbitrary_self_types_enabled: bool,
1620 let infcx = wfcx.infcx;
1621 let tcx = wfcx.tcx();
1623 ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1625 let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1627 // `self: Self` is always valid.
1628 if can_eq_self(receiver_ty) {
1629 if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1630 infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1636 Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1638 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1639 if arbitrary_self_types_enabled {
1640 autoderef = autoderef.include_raw_pointers();
1643 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1646 let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1648 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1650 if let Some((potential_self_ty, _)) = autoderef.next() {
1652 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1653 potential_self_ty, self_ty
1656 if can_eq_self(potential_self_ty) {
1657 wfcx.register_obligations(autoderef.into_obligations());
1660 wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1662 infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1667 // Without `feature(arbitrary_self_types)`, we require that each step in the
1668 // deref chain implement `receiver`
1669 if !arbitrary_self_types_enabled
1670 && !receiver_is_implemented(
1672 receiver_trait_def_id,
1681 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1682 // If the receiver already has errors reported due to it, consider it valid to avoid
1683 // unnecessary errors (#58712).
1684 return receiver_ty.references_error();
1688 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1689 if !arbitrary_self_types_enabled
1690 && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1698 fn receiver_is_implemented<'tcx>(
1699 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1700 receiver_trait_def_id: DefId,
1701 cause: ObligationCause<'tcx>,
1702 receiver_ty: Ty<'tcx>,
1704 let tcx = wfcx.tcx();
1705 let trait_ref = ty::Binder::dummy(ty::TraitRef {
1706 def_id: receiver_trait_def_id,
1707 substs: tcx.mk_substs_trait(receiver_ty, &[]),
1711 traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1713 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1717 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1724 fn check_variances_for_type_defn<'tcx>(
1726 item: &hir::Item<'tcx>,
1727 hir_generics: &hir::Generics<'_>,
1729 let ty = tcx.type_of(item.def_id);
1730 if tcx.has_error_field(ty) {
1734 let ty_predicates = tcx.predicates_of(item.def_id);
1735 assert_eq!(ty_predicates.parent, None);
1736 let variances = tcx.variances_of(item.def_id);
1738 let mut constrained_parameters: FxHashSet<_> = variances
1741 .filter(|&(_, &variance)| variance != ty::Bivariant)
1742 .map(|(index, _)| Parameter(index as u32))
1745 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1747 // Lazily calculated because it is only needed in case of an error.
1748 let explicitly_bounded_params = LazyCell::new(|| {
1749 let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1753 .filter_map(|predicate| match predicate {
1754 hir::WherePredicate::BoundPredicate(predicate) => {
1755 match icx.to_ty(predicate.bounded_ty).kind() {
1756 ty::Param(data) => Some(Parameter(data.index)),
1762 .collect::<FxHashSet<_>>()
1765 for (index, _) in variances.iter().enumerate() {
1766 let parameter = Parameter(index as u32);
1768 if constrained_parameters.contains(¶meter) {
1772 let param = &hir_generics.params[index];
1775 hir::ParamName::Error => {}
1777 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
1778 report_bivariance(tcx, param, has_explicit_bounds);
1784 fn report_bivariance(
1786 param: &rustc_hir::GenericParam<'_>,
1787 has_explicit_bounds: bool,
1788 ) -> ErrorGuaranteed {
1789 let span = param.span;
1790 let param_name = param.name.ident().name;
1791 let mut err = error_392(tcx, span, param_name);
1793 let suggested_marker_id = tcx.lang_items().phantom_data();
1794 // Help is available only in presence of lang items.
1795 let msg = if let Some(def_id) = suggested_marker_id {
1797 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1799 tcx.def_path_str(def_id),
1802 format!("consider removing `{param_name}` or referring to it in a field")
1806 if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1808 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1815 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1816 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1818 fn check_false_global_bounds(&mut self) {
1819 let tcx = self.ocx.infcx.tcx;
1820 let mut span = self.span;
1821 let empty_env = ty::ParamEnv::empty();
1823 let def_id = tcx.hir().local_def_id(self.body_id);
1824 let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1825 // Check elaborated bounds.
1826 let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1828 for obligation in implied_obligations {
1829 // We lower empty bounds like `Vec<dyn Copy>:` as
1830 // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1831 // regular WF checking
1832 if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1835 let pred = obligation.predicate;
1836 // Match the existing behavior.
1837 if pred.is_global() && !pred.has_late_bound_regions() {
1838 let pred = self.normalize(span, None, pred);
1839 let hir_node = tcx.hir().find(self.body_id);
1841 // only use the span of the predicate clause (#90869)
1843 if let Some(hir::Generics { predicates, .. }) =
1844 hir_node.and_then(|node| node.generics())
1846 let obligation_span = obligation.cause.span();
1850 // There seems to be no better way to find out which predicate we are in
1851 .find(|pred| pred.span().contains(obligation_span))
1852 .map(|pred| pred.span())
1853 .unwrap_or(obligation_span);
1856 let obligation = traits::Obligation::new(
1857 traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1861 self.ocx.register_obligation(obligation);
1867 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1868 let items = tcx.hir_module_items(module);
1869 items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1870 items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1871 items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1872 items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1875 ///////////////////////////////////////////////////////////////////////////
1878 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1879 struct AdtVariant<'tcx> {
1880 /// Types of fields in the variant, that must be well-formed.
1881 fields: Vec<AdtField<'tcx>>,
1883 /// Explicit discriminant of this variant (e.g. `A = 123`),
1884 /// that must evaluate to a constant value.
1885 explicit_discr: Option<LocalDefId>,
1888 struct AdtField<'tcx> {
1894 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1895 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1896 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1897 let fields = struct_def
1901 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1902 let field_ty = self.tcx().type_of(def_id);
1903 let field_ty = self.normalize(field.ty.span, None, field_ty);
1904 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1905 AdtField { ty: field_ty, span: field.ty.span, def_id }
1908 AdtVariant { fields, explicit_discr: None }
1911 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1915 .map(|variant| AdtVariant {
1916 fields: self.non_enum_variant(&variant.data).fields,
1917 explicit_discr: variant
1919 .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1925 pub fn impl_implied_bounds<'tcx>(
1927 param_env: ty::ParamEnv<'tcx>,
1928 impl_def_id: LocalDefId,
1930 ) -> FxHashSet<Ty<'tcx>> {
1931 // We completely ignore any obligations caused by normalizing the types
1932 // we assume to be well formed. Considering that the user of the implied
1933 // bounds will also normalize them, we leave it to them to emit errors
1934 // which should result in better causes and spans.
1935 tcx.infer_ctxt().enter(|infcx| {
1936 let cause = ObligationCause::misc(span, tcx.hir().local_def_id_to_hir_id(impl_def_id));
1937 match tcx.impl_trait_ref(impl_def_id) {
1938 Some(trait_ref) => {
1939 // Trait impl: take implied bounds from all types that
1940 // appear in the trait reference.
1941 match infcx.at(&cause, param_env).normalize(trait_ref) {
1942 Ok(Normalized { value, obligations: _ }) => value.substs.types().collect(),
1943 Err(NoSolution) => FxHashSet::default(),
1948 // Inherent impl: take implied bounds from the `self` type.
1949 let self_ty = tcx.type_of(impl_def_id);
1950 match infcx.at(&cause, param_env).normalize(self_ty) {
1951 Ok(Normalized { value, obligations: _ }) => FxHashSet::from_iter([value]),
1952 Err(NoSolution) => FxHashSet::default(),
1963 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1964 let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1965 err.span_label(span, "unused parameter");
1969 pub fn provide(providers: &mut Providers) {
1970 *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };