1 use crate::check::regionck::OutlivesEnvironmentExt;
2 use crate::check::{FnCtxt, Inherited};
3 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit as hir_visit;
11 use rustc_hir::intravisit::Visitor;
12 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_hir::ItemKind;
15 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
16 use rustc_infer::infer::outlives::obligations::TypeOutlives;
17 use rustc_infer::infer::region_constraints::GenericKind;
18 use rustc_infer::infer::{self, RegionckMode};
19 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
20 use rustc_middle::hir::nested_filter;
21 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
22 use rustc_middle::ty::trait_def::TraitSpecializationKind;
23 use rustc_middle::ty::{
24 self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeVisitor,
26 use rustc_session::parse::feature_err;
27 use rustc_span::symbol::{sym, Ident, Symbol};
28 use rustc_span::{Span, DUMMY_SP};
29 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, WellFormedLoc};
32 use std::convert::TryInto;
34 use std::ops::ControlFlow;
36 /// Helper type of a temporary returned by `.for_item(...)`.
37 /// This is necessary because we can't write the following bound:
40 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
42 struct CheckWfFcxBuilder<'tcx> {
43 inherited: super::InheritedBuilder<'tcx>,
46 param_env: ty::ParamEnv<'tcx>,
49 impl<'tcx> CheckWfFcxBuilder<'tcx> {
50 fn with_fcx<F>(&mut self, f: F)
52 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>) -> FxHashSet<Ty<'tcx>>,
56 let param_env = self.param_env;
57 self.inherited.enter(|inh| {
58 let fcx = FnCtxt::new(&inh, param_env, id);
59 if !inh.tcx.features().trivial_bounds {
60 // As predicates are cached rather than obligations, this
61 // needs to be called first so that they are checked with an
63 check_false_global_bounds(&fcx, span, id);
66 fcx.select_all_obligations_or_error();
67 fcx.regionck_item(id, span, wf_tys);
72 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
73 /// well-formed, meaning that they do not require any constraints not declared in the struct
74 /// definition itself. For example, this definition would be illegal:
77 /// struct Ref<'a, T> { x: &'a T }
80 /// because the type did not declare that `T:'a`.
82 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
83 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
85 #[instrument(skip(tcx), level = "debug")]
86 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
87 let item = tcx.hir().expect_item(def_id);
91 item.name = ? tcx.def_path_str(def_id.to_def_id())
95 // Right now we check that every default trait implementation
96 // has an implementation of itself. Basically, a case like:
98 // impl Trait for T {}
100 // has a requirement of `T: Trait` which was required for default
101 // method implementations. Although this could be improved now that
102 // there's a better infrastructure in place for this, it's being left
103 // for a follow-up work.
105 // Since there's such a requirement, we need to check *just* positive
106 // implementations, otherwise things like:
108 // impl !Send for T {}
110 // won't be allowed unless there's an *explicit* implementation of `Send`
112 hir::ItemKind::Impl(ref impl_) => {
114 .impl_trait_ref(item.def_id)
115 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
116 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
117 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
119 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
120 err.span_labels(impl_.defaultness_span, "default because of this");
121 err.span_label(sp, "auto trait");
124 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
125 match (tcx.impl_polarity(def_id), impl_.polarity) {
126 (ty::ImplPolarity::Positive, _) => {
127 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait);
129 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
130 // FIXME(#27579): what amount of WF checking do we need for neg impls?
131 if let hir::Defaultness::Default { .. } = impl_.defaultness {
132 let mut spans = vec![span];
133 spans.extend(impl_.defaultness_span);
138 "negative impls cannot be default impls"
143 (ty::ImplPolarity::Reservation, _) => {
144 // FIXME: what amount of WF checking do we need for reservation impls?
149 hir::ItemKind::Fn(ref sig, ..) => {
150 check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
152 hir::ItemKind::Static(ty, ..) => {
153 check_item_type(tcx, item.def_id, ty.span, false);
155 hir::ItemKind::Const(ty, ..) => {
156 check_item_type(tcx, item.def_id, ty.span, false);
158 hir::ItemKind::ForeignMod { items, .. } => {
159 for it in items.iter() {
160 let it = tcx.hir().foreign_item(it.id);
162 hir::ForeignItemKind::Fn(decl, ..) => {
163 check_item_fn(tcx, it.def_id, it.ident, it.span, decl)
165 hir::ForeignItemKind::Static(ty, ..) => {
166 check_item_type(tcx, it.def_id, ty.span, true)
168 hir::ForeignItemKind::Type => (),
172 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
173 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
175 check_variances_for_type_defn(tcx, item, ast_generics);
177 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
178 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
180 check_variances_for_type_defn(tcx, item, ast_generics);
182 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
183 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
185 check_variances_for_type_defn(tcx, item, ast_generics);
187 hir::ItemKind::Trait(..) => {
188 check_trait(tcx, item);
190 hir::ItemKind::TraitAlias(..) => {
191 check_trait(tcx, item);
197 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
198 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
199 let trait_item = tcx.hir().expect_trait_item(def_id);
201 let (method_sig, span) = match trait_item.kind {
202 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
203 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
204 _ => (None, trait_item.span),
206 check_object_unsafe_self_trait_by_name(tcx, trait_item);
207 check_associated_item(tcx, trait_item.def_id, span, method_sig);
209 let encl_trait_def_id = tcx.hir().get_parent_item(hir_id);
210 let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
211 let encl_trait_def_id = encl_trait.def_id.to_def_id();
212 let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
214 } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
220 if let (Some(fn_lang_item_name), "call") =
221 (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
223 // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
224 // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
225 if let Some(hir::FnSig { decl, span, .. }) = method_sig {
226 if let [self_ty, _] = decl.inputs {
227 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
232 "first argument of `call` in `{}` lang item must be a reference",
243 "`call` function in `{}` lang item takes exactly two arguments",
254 "`call` trait item in `{}` lang item must be a function",
262 check_gat_where_clauses(tcx, trait_item, encl_trait_def_id);
265 /// Require that the user writes where clauses on GATs for the implicit
266 /// outlives bounds involving trait parameters in trait functions and
267 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
269 /// This trait will be our running example. We are currently WF checking the `Item` item...
272 /// trait LendingIterator {
273 /// type Item<'me>; // <-- WF checking this trait item
275 /// fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
278 fn check_gat_where_clauses(
280 trait_item: &hir::TraitItem<'_>,
281 encl_trait_def_id: DefId,
283 let item = tcx.associated_item(trait_item.def_id);
284 // If the current trait item isn't a type, it isn't a GAT
285 if !matches!(item.kind, ty::AssocKind::Type) {
288 let generics: &ty::Generics = tcx.generics_of(trait_item.def_id);
289 // If the current associated type doesn't have any (own) params, it's not a GAT
290 // FIXME(jackh726): we can also warn in the more general case
291 if generics.params.len() == 0 {
294 let associated_items: &ty::AssocItems<'_> = tcx.associated_items(encl_trait_def_id);
295 let mut clauses: Option<FxHashSet<ty::Predicate<'_>>> = None;
296 // For every function in this trait...
297 // In our example, this would be the `next` method
299 associated_items.in_definition_order().filter(|item| matches!(item.kind, ty::AssocKind::Fn))
301 // The clauses we that we would require from this function
302 let mut function_clauses = FxHashSet::default();
304 let id = hir::HirId::make_owner(item.def_id.expect_local());
305 let param_env = tcx.param_env(item.def_id.expect_local());
307 let sig = tcx.fn_sig(item.def_id);
308 // Get the signature using placeholders. In our example, this would
309 // convert the late-bound 'a into a free region.
310 let sig = tcx.liberate_late_bound_regions(item.def_id, sig);
311 // Collect the arguments that are given to this GAT in the return type
312 // of the function signature. In our example, the GAT in the return
313 // type is `<Self as LendingIterator>::Item<'a>`, so 'a and Self are arguments.
314 let (regions, types) =
315 GATSubstCollector::visit(tcx, trait_item.def_id.to_def_id(), sig.output());
317 // If both regions and types are empty, then this GAT isn't in the
318 // return type, and we shouldn't try to do clause analysis
319 // (particularly, doing so would end up with an empty set of clauses,
320 // since the current method would require none, and we take the
321 // intersection of requirements of all methods)
322 if types.is_empty() && regions.is_empty() {
326 // The types we can assume to be well-formed. In our example, this
327 // would be &'a mut Self, from the first argument.
328 let mut wf_tys = FxHashSet::default();
329 wf_tys.extend(sig.inputs());
331 // For each region argument (e.g., 'a in our example), check for a
332 // relationship to the type arguments (e.g., Self). If there is an
333 // outlives relationship (`Self: 'a`), then we want to ensure that is
334 // reflected in a where clause on the GAT itself.
335 for (region, region_idx) in ®ions {
336 // Ignore `'static` lifetimes for the purpose of this lint: it's
337 // because we know it outlives everything and so doesn't give meaninful
339 if let ty::ReStatic = region {
342 for (ty, ty_idx) in &types {
343 // In our example, requires that Self: 'a
344 if ty_known_to_outlive(tcx, id, param_env, &wf_tys, *ty, *region) {
345 debug!(?ty_idx, ?region_idx);
346 debug!("required clause: {} must outlive {}", ty, region);
347 // Translate into the generic parameters of the GAT. In
348 // our example, the type was Self, which will also be
350 let ty_param = generics.param_at(*ty_idx, tcx);
351 let ty_param = tcx.mk_ty(ty::Param(ty::ParamTy {
352 index: ty_param.index,
355 // Same for the region. In our example, 'a corresponds
356 // to the 'me parameter.
357 let region_param = generics.param_at(*region_idx, tcx);
359 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
360 def_id: region_param.def_id,
361 index: region_param.index,
362 name: region_param.name,
364 // The predicate we expect to see. (In our example,
366 let clause = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
370 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
371 function_clauses.insert(clause);
376 // For each region argument (e.g., 'a in our example), also check for a
377 // relationship to the other region arguments. If there is an
378 // outlives relationship, then we want to ensure that is
379 // reflected in a where clause on the GAT itself.
380 for (region_a, region_a_idx) in ®ions {
381 // Ignore `'static` lifetimes for the purpose of this lint: it's
382 // because we know it outlives everything and so doesn't give meaninful
384 if let ty::ReStatic = region_a {
387 for (region_b, region_b_idx) in ®ions {
388 if region_a == region_b {
391 if let ty::ReStatic = region_b {
395 if region_known_to_outlive(tcx, id, param_env, &wf_tys, *region_a, *region_b) {
396 debug!(?region_a_idx, ?region_b_idx);
397 debug!("required clause: {} must outlive {}", region_a, region_b);
398 // Translate into the generic parameters of the GAT.
399 let region_a_param = generics.param_at(*region_a_idx, tcx);
401 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
402 def_id: region_a_param.def_id,
403 index: region_a_param.index,
404 name: region_a_param.name,
406 // Same for the region.
407 let region_b_param = generics.param_at(*region_b_idx, tcx);
409 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
410 def_id: region_b_param.def_id,
411 index: region_b_param.index,
412 name: region_b_param.name,
414 // The predicate we expect to see.
415 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
419 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
420 function_clauses.insert(clause);
429 // fn gimme(&self) -> Self::Bar<'_>;
430 // fn gimme_default(&self) -> Self::Bar<'static>;
433 // We only want to require clauses on `Bar` that we can prove from *all* functions (in this
434 // case, `'me` can be `static` from `gimme_default`)
435 match clauses.as_mut() {
437 clauses.drain_filter(|p| !function_clauses.contains(p));
440 clauses = Some(function_clauses);
445 // If there are any clauses that aren't provable, emit an error
446 let clauses = clauses.unwrap_or_default();
448 if !clauses.is_empty() {
449 let param_env = tcx.param_env(trait_item.def_id);
451 let mut clauses: Vec<_> = clauses
453 .filter(|clause| match clause.kind().skip_binder() {
454 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
455 !region_known_to_outlive(
459 &FxHashSet::default(),
464 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
465 !ty_known_to_outlive(
469 &FxHashSet::default(),
474 _ => bug!("Unexpected PredicateKind"),
476 .map(|clause| format!("{}", clause))
479 // We sort so that order is predictable
482 if !clauses.is_empty() {
483 let plural = if clauses.len() > 1 { "s" } else { "" };
484 let mut err = tcx.sess.struct_span_err(
486 &format!("missing required bound{} on `{}`", plural, trait_item.ident),
489 let suggestion = format!(
491 if !trait_item.generics.where_clause.predicates.is_empty() {
499 trait_item.generics.where_clause.tail_span_for_suggestion(),
500 &format!("add the required where clause{}", plural),
502 Applicability::MachineApplicable,
505 let bound = if clauses.len() > 1 { "these bounds are" } else { "this bound is" };
507 "{} currently required to ensure that impls have maximum flexibility",
511 "we are soliciting feedback, see issue #87479 \
512 <https://github.com/rust-lang/rust/issues/87479> \
513 for more information",
521 /// Given a known `param_env` and a set of well formed types, can we prove that
522 /// `ty` outlives `region`.
523 fn ty_known_to_outlive<'tcx>(
526 param_env: ty::ParamEnv<'tcx>,
527 wf_tys: &FxHashSet<Ty<'tcx>>,
529 region: ty::Region<'tcx>,
531 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
532 let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
533 let outlives = &mut TypeOutlives::new(
537 Some(infcx.tcx.lifetimes.re_root_empty),
540 outlives.type_must_outlive(origin, ty, region);
544 /// Given a known `param_env` and a set of well formed types, can we prove that
545 /// `region_a` outlives `region_b`
546 fn region_known_to_outlive<'tcx>(
549 param_env: ty::ParamEnv<'tcx>,
550 wf_tys: &FxHashSet<Ty<'tcx>>,
551 region_a: ty::Region<'tcx>,
552 region_b: ty::Region<'tcx>,
554 resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
555 use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
556 let origin = infer::RelateRegionParamBound(DUMMY_SP);
557 // `region_a: region_b` -> `region_b <= region_a`
558 infcx.push_sub_region_constraint(origin, region_b, region_a);
562 /// Given a known `param_env` and a set of well formed types, set up an
563 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
564 /// to be tested), then resolve region and return errors
565 fn resolve_regions_with_wf_tys<'tcx>(
568 param_env: ty::ParamEnv<'tcx>,
569 wf_tys: &FxHashSet<Ty<'tcx>>,
570 add_constraints: impl for<'a> FnOnce(
571 &'a InferCtxt<'a, 'tcx>,
572 &'a Vec<(&'tcx ty::RegionKind, GenericKind<'tcx>)>,
575 // Unfortunately, we have to use a new `InferCtxt` each call, because
576 // region constraints get added and solved there and we need to test each
577 // call individually.
578 tcx.infer_ctxt().enter(|infcx| {
579 let mut outlives_environment = OutlivesEnvironment::new(param_env);
580 outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id, DUMMY_SP);
581 outlives_environment.save_implied_bounds(id);
582 let region_bound_pairs = outlives_environment.region_bound_pairs_map().get(&id).unwrap();
584 add_constraints(&infcx, region_bound_pairs);
586 let errors = infcx.resolve_regions(
587 id.expect_owner().to_def_id(),
588 &outlives_environment,
589 RegionckMode::default(),
592 debug!(?errors, "errors");
594 // If we were able to prove that the type outlives the region without
595 // an error, it must be because of the implied or explicit bounds...
600 /// TypeVisitor that looks for uses of GATs like
601 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
602 /// the two vectors, `regions` and `types` (depending on their kind). For each
603 /// parameter `Pi` also track the index `i`.
604 struct GATSubstCollector<'tcx> {
607 // Which region appears and which parameter index its subsituted for
608 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
609 // Which params appears and which parameter index its subsituted for
610 types: FxHashSet<(Ty<'tcx>, usize)>,
613 impl<'tcx> GATSubstCollector<'tcx> {
614 fn visit<T: TypeFoldable<'tcx>>(
618 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
619 let mut visitor = GATSubstCollector {
622 regions: FxHashSet::default(),
623 types: FxHashSet::default(),
625 t.visit_with(&mut visitor);
626 (visitor.regions, visitor.types)
630 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
633 fn visit_binder<T: TypeFoldable<'tcx>>(
635 t: &ty::Binder<'tcx, T>,
636 ) -> ControlFlow<Self::BreakTy> {
637 self.tcx.liberate_late_bound_regions(self.gat, t.clone()).visit_with(self)
640 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
642 ty::Projection(p) if p.item_def_id == self.gat => {
643 for (idx, subst) in p.substs.iter().enumerate() {
644 match subst.unpack() {
645 GenericArgKind::Lifetime(lt) => {
646 self.regions.insert((lt, idx));
648 GenericArgKind::Type(t) => {
649 self.types.insert((t, idx));
657 t.super_visit_with(self)
661 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
663 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
664 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
671 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
672 /// When this is done, suggest using `Self` instead.
673 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
674 let (trait_name, trait_def_id) =
675 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
676 hir::Node::Item(item) => match item.kind {
677 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
682 let mut trait_should_be_self = vec![];
684 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
685 if could_be_self(trait_def_id, ty) =>
687 trait_should_be_self.push(ty.span)
689 hir::TraitItemKind::Fn(sig, _) => {
690 for ty in sig.decl.inputs {
691 if could_be_self(trait_def_id, ty) {
692 trait_should_be_self.push(ty.span);
695 match sig.decl.output {
696 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
697 trait_should_be_self.push(ty.span);
704 if !trait_should_be_self.is_empty() {
705 if tcx.object_safety_violations(trait_def_id).is_empty() {
708 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
711 trait_should_be_self,
712 "associated item referring to unboxed trait object for its own trait",
714 .span_label(trait_name.span, "in this trait")
715 .multipart_suggestion(
716 "you might have meant to use `Self` to refer to the implementing type",
718 Applicability::MachineApplicable,
724 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
725 let impl_item = tcx.hir().expect_impl_item(def_id);
727 let (method_sig, span) = match impl_item.kind {
728 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
729 // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
730 hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
731 _ => (None, impl_item.span),
734 check_associated_item(tcx, impl_item.def_id, span, method_sig);
737 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
739 // We currently only check wf of const params here.
740 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
742 // Const parameters are well formed if their type is structural match.
743 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
744 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
747 let mut is_ptr = true;
748 let err = if tcx.features().adt_const_params {
749 match ty.peel_refs().kind() {
750 ty::FnPtr(_) => Some("function pointers"),
751 ty::RawPtr(_) => Some("raw pointers"),
756 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
757 ty::FnPtr(_) => Some("function pointers"),
758 ty::RawPtr(_) => Some("raw pointers"),
761 err_ty_str = format!("`{}`", ty);
762 Some(err_ty_str.as_str())
766 if let Some(unsupported_type) = err {
771 "using {} as const generic parameters is forbidden",
776 let mut err = tcx.sess.struct_span_err(
779 "{} is forbidden as the type of a const generic parameter",
783 err.note("the only supported types are integers, `bool` and `char`");
784 if tcx.sess.is_nightly_build() {
786 "more complex types are supported with `#![feature(adt_const_params)]`",
793 if traits::search_for_structural_match_violation(param.span, tcx, ty).is_some() {
794 // We use the same error code in both branches, because this is really the same
795 // issue: we just special-case the message for type parameters to make it
797 if let ty::Param(_) = ty.peel_refs().kind() {
798 // Const parameters may not have type parameters as their types,
799 // because we cannot be sure that the type parameter derives `PartialEq`
800 // and `Eq` (just implementing them is not enough for `structural_match`).
805 "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
806 used as the type of a const parameter",
811 format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
814 "it is not currently possible to use a type parameter as the type of a \
823 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
824 the type of a const parameter",
829 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
838 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
839 fn check_associated_item(
843 sig_if_method: Option<&hir::FnSig<'_>>,
845 let code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id)));
846 for_id(tcx, item_id, span).with_fcx(|fcx| {
847 let item = fcx.tcx.associated_item(item_id);
849 let (mut implied_bounds, self_ty) = match item.container {
850 ty::TraitContainer(_) => (FxHashSet::default(), fcx.tcx.types.self_param),
851 ty::ImplContainer(def_id) => {
852 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
857 ty::AssocKind::Const => {
858 let ty = fcx.tcx.type_of(item.def_id);
859 let ty = fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
860 fcx.register_wf_obligation(ty.into(), span, code.clone());
862 ty::AssocKind::Fn => {
863 let sig = fcx.tcx.fn_sig(item.def_id);
864 let hir_sig = sig_if_method.expect("bad signature for method");
867 item.ident(fcx.tcx).span,
873 check_method_receiver(fcx, hir_sig, item, self_ty);
875 ty::AssocKind::Type => {
876 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
877 check_associated_type_bounds(fcx, item, span)
879 if item.defaultness.has_value() {
880 let ty = fcx.tcx.type_of(item.def_id);
882 fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
883 fcx.register_wf_obligation(ty.into(), span, code.clone());
892 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
893 for_id(tcx, item.def_id, item.span)
896 fn for_id(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> CheckWfFcxBuilder<'_> {
898 inherited: Inherited::build(tcx, def_id),
899 id: hir::HirId::make_owner(def_id),
901 param_env: tcx.param_env(def_id),
905 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
907 ItemKind::Struct(..) => Some(AdtKind::Struct),
908 ItemKind::Union(..) => Some(AdtKind::Union),
909 ItemKind::Enum(..) => Some(AdtKind::Enum),
914 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
915 fn check_type_defn<'tcx, F>(
917 item: &hir::Item<'tcx>,
919 mut lookup_fields: F,
921 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
923 for_item(tcx, item).with_fcx(|fcx| {
924 let variants = lookup_fields(fcx);
925 let packed = tcx.adt_def(item.def_id).repr.packed();
927 for variant in &variants {
928 // For DST, or when drop needs to copy things around, all
929 // intermediate types must be sized.
930 let needs_drop_copy = || {
932 let ty = variant.fields.last().unwrap().ty;
933 let ty = tcx.erase_regions(ty);
934 if ty.needs_infer() {
936 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
937 // Just treat unresolved type expression as if it needs drop.
940 ty.needs_drop(tcx, tcx.param_env(item.def_id))
944 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
945 let unsized_len = if all_sized { 0 } else { 1 };
947 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
949 let last = idx == variant.fields.len() - 1;
952 tcx.require_lang_item(LangItem::Sized, None),
953 traits::ObligationCause::new(
957 adt_kind: match item_adt_kind(&item.kind) {
968 // All field types must be well-formed.
969 for field in &variant.fields {
970 fcx.register_wf_obligation(
973 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(field.def_id))),
977 // Explicit `enum` discriminant values must const-evaluate successfully.
978 if let Some(discr_def_id) = variant.explicit_discr {
979 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
981 let cause = traits::ObligationCause::new(
982 tcx.def_span(discr_def_id),
984 traits::MiscObligation,
986 fcx.register_predicate(traits::Obligation::new(
989 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
990 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
998 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
1000 // No implied bounds in a struct definition.
1001 FxHashSet::default()
1005 #[instrument(skip(tcx, item))]
1006 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1007 debug!(?item.def_id);
1009 let trait_def = tcx.trait_def(item.def_id);
1010 if trait_def.is_marker
1011 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1013 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1016 tcx.def_span(*associated_def_id),
1018 "marker traits cannot have associated items",
1024 // FIXME: this shouldn't use an `FnCtxt` at all.
1025 for_item(tcx, item).with_fcx(|fcx| {
1026 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
1028 FxHashSet::default()
1032 /// Checks all associated type defaults of trait `trait_def_id`.
1034 /// Assuming the defaults are used, check that all predicates (bounds on the
1035 /// assoc type and where clauses on the trait) hold.
1036 fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1039 let bounds = tcx.explicit_item_bounds(item.def_id);
1041 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1042 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1043 let normalized_bound = fcx.normalize_associated_types_in(span, bound);
1044 traits::wf::predicate_obligations(
1053 for obligation in wf_obligations {
1054 debug!("next obligation cause: {:?}", obligation.cause);
1055 fcx.register_predicate(obligation);
1064 decl: &hir::FnDecl<'_>,
1066 for_id(tcx, def_id, span).with_fcx(|fcx| {
1067 let sig = tcx.fn_sig(def_id);
1068 let mut implied_bounds = FxHashSet::default();
1069 check_fn_or_method(fcx, ident.span, sig, decl, def_id.to_def_id(), &mut implied_bounds);
1074 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1075 debug!("check_item_type: {:?}", item_id);
1077 for_id(tcx, item_id, ty_span).with_fcx(|fcx| {
1078 let ty = tcx.type_of(item_id);
1079 let item_ty = fcx.normalize_associated_types_in_wf(ty_span, ty, WellFormedLoc::Ty(item_id));
1081 let mut forbid_unsized = true;
1082 if allow_foreign_ty {
1083 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
1084 if let ty::Foreign(_) = tail.kind() {
1085 forbid_unsized = false;
1089 fcx.register_wf_obligation(
1092 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id))),
1097 tcx.require_lang_item(LangItem::Sized, None),
1098 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
1102 // Ensure that the end result is `Sync` in a non-thread local `static`.
1103 let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1104 == Some(hir::Mutability::Not)
1105 && !tcx.is_foreign_item(item_id.to_def_id())
1106 && !tcx.is_thread_local_static(item_id.to_def_id());
1108 if should_check_for_sync {
1111 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1112 traits::ObligationCause::new(ty_span, fcx.body_id, traits::SharedStatic),
1116 // No implied bounds in a const, etc.
1117 FxHashSet::default()
1121 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1122 fn check_impl<'tcx>(
1124 item: &'tcx hir::Item<'tcx>,
1125 ast_self_ty: &hir::Ty<'_>,
1126 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1128 for_item(tcx, item).with_fcx(|fcx| {
1129 match *ast_trait_ref {
1130 Some(ref ast_trait_ref) => {
1131 // `#[rustc_reservation_impl]` impls are not real impls and
1132 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1134 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1136 fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
1137 let obligations = traits::wf::trait_obligations(
1142 ast_trait_ref.path.span,
1145 debug!(?obligations);
1146 for obligation in obligations {
1147 fcx.register_predicate(obligation);
1151 let self_ty = tcx.type_of(item.def_id);
1152 let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
1153 fcx.register_wf_obligation(
1156 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(
1157 item.hir_id().expect_owner(),
1163 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
1165 fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
1169 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1170 #[instrument(skip(fcx), level = "debug")]
1171 fn check_where_clauses<'tcx, 'fcx>(
1172 fcx: &FnCtxt<'fcx, 'tcx>,
1175 return_ty: Option<(Ty<'tcx>, Span)>,
1179 let predicates = tcx.predicates_of(def_id);
1180 let generics = tcx.generics_of(def_id);
1182 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1183 GenericParamDefKind::Type { has_default, .. }
1184 | GenericParamDefKind::Const { has_default } => {
1185 has_default && def.index >= generics.parent_count as u32
1187 GenericParamDefKind::Lifetime => unreachable!(),
1190 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1191 // For example, this forbids the declaration:
1193 // struct Foo<T = Vec<[u32]>> { .. }
1195 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1196 for param in &generics.params {
1198 GenericParamDefKind::Type { .. } => {
1199 if is_our_default(param) {
1200 let ty = tcx.type_of(param.def_id);
1201 // Ignore dependent defaults -- that is, where the default of one type
1202 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1203 // be sure if it will error or not as user might always specify the other.
1204 if !ty.needs_subst() {
1205 fcx.register_wf_obligation(
1207 tcx.def_span(param.def_id),
1208 ObligationCauseCode::MiscObligation,
1213 GenericParamDefKind::Const { .. } => {
1214 if is_our_default(param) {
1215 // FIXME(const_generics_defaults): This
1216 // is incorrect when dealing with unused substs, for example
1217 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1218 // we should eagerly error.
1219 let default_ct = tcx.const_param_default(param.def_id);
1220 if !default_ct.needs_subst() {
1221 fcx.register_wf_obligation(
1223 tcx.def_span(param.def_id),
1224 ObligationCauseCode::WellFormed(None),
1229 // Doesn't have defaults.
1230 GenericParamDefKind::Lifetime => {}
1234 // Check that trait predicates are WF when params are substituted by their defaults.
1235 // We don't want to overly constrain the predicates that may be written but we want to
1236 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1237 // Therefore we check if a predicate which contains a single type param
1238 // with a concrete default is WF with that default substituted.
1239 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1241 // First we build the defaulted substitution.
1242 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
1244 GenericParamDefKind::Lifetime => {
1245 // All regions are identity.
1246 tcx.mk_param_from_def(param)
1249 GenericParamDefKind::Type { .. } => {
1250 // If the param has a default, ...
1251 if is_our_default(param) {
1252 let default_ty = tcx.type_of(param.def_id);
1253 // ... and it's not a dependent default, ...
1254 if !default_ty.needs_subst() {
1255 // ... then substitute it with the default.
1256 return default_ty.into();
1260 tcx.mk_param_from_def(param)
1262 GenericParamDefKind::Const { .. } => {
1263 // If the param has a default, ...
1264 if is_our_default(param) {
1265 let default_ct = tcx.const_param_default(param.def_id);
1266 // ... and it's not a dependent default, ...
1267 if !default_ct.needs_subst() {
1268 // ... then substitute it with the default.
1269 return default_ct.into();
1273 tcx.mk_param_from_def(param)
1278 // Now we build the substituted predicates.
1279 let default_obligations = predicates
1282 .flat_map(|&(pred, sp)| {
1284 struct CountParams {
1285 params: FxHashSet<u32>,
1287 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
1290 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1291 if let ty::Param(param) = t.kind() {
1292 self.params.insert(param.index);
1294 t.super_visit_with(self)
1297 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1301 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1302 if let ty::ConstKind::Param(param) = c.val {
1303 self.params.insert(param.index);
1305 c.super_visit_with(self)
1308 let mut param_count = CountParams::default();
1309 let has_region = pred.visit_with(&mut param_count).is_break();
1310 let substituted_pred = pred.subst(tcx, substs);
1311 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1312 // or preds with multiple params.
1313 if substituted_pred.has_param_types_or_consts()
1314 || param_count.params.len() > 1
1318 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1319 // Avoid duplication of predicates that contain no parameters, for example.
1322 Some((substituted_pred, sp))
1326 // Convert each of those into an obligation. So if you have
1327 // something like `struct Foo<T: Copy = String>`, we would
1328 // take that predicate `T: Copy`, substitute to `String: Copy`
1329 // (actually that happens in the previous `flat_map` call),
1330 // and then try to prove it (in this case, we'll fail).
1332 // Note the subtle difference from how we handle `predicates`
1333 // below: there, we are not trying to prove those predicates
1334 // to be *true* but merely *well-formed*.
1335 let pred = fcx.normalize_associated_types_in(sp, pred);
1337 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
1338 traits::Obligation::new(cause, fcx.param_env, pred)
1341 let predicates = predicates.instantiate_identity(tcx);
1343 if let Some((return_ty, _)) = return_ty {
1344 if return_ty.has_infer_types_or_consts() {
1345 fcx.select_obligations_where_possible(false, |_| {});
1349 let predicates = fcx.normalize_associated_types_in(span, predicates);
1351 debug!(?predicates.predicates);
1352 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1353 let wf_obligations =
1354 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1355 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
1358 for obligation in wf_obligations.chain(default_obligations) {
1359 debug!("next obligation cause: {:?}", obligation.cause);
1360 fcx.register_predicate(obligation);
1364 #[tracing::instrument(level = "debug", skip(fcx, span, hir_decl))]
1365 fn check_fn_or_method<'fcx, 'tcx>(
1366 fcx: &FnCtxt<'fcx, 'tcx>,
1368 sig: ty::PolyFnSig<'tcx>,
1369 hir_decl: &hir::FnDecl<'_>,
1371 implied_bounds: &mut FxHashSet<Ty<'tcx>>,
1373 let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
1375 // Normalize the input and output types one at a time, using a different
1376 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1377 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1378 // for each type, preventing the HIR wf check from generating
1379 // a nice error message.
1380 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1382 fcx.tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1383 fcx.normalize_associated_types_in_wf(
1386 WellFormedLoc::Param {
1387 function: def_id.expect_local(),
1388 // Note that the `param_idx` of the output type is
1389 // one greater than the index of the last input type.
1390 param_idx: i.try_into().unwrap(),
1394 // Manually call `normalize_assocaited_types_in` on the other types
1395 // in `FnSig`. This ensures that if the types of these fields
1396 // ever change to include projections, we will start normalizing
1397 // them automatically.
1398 let sig = ty::FnSig {
1400 c_variadic: fcx.normalize_associated_types_in(span, c_variadic),
1401 unsafety: fcx.normalize_associated_types_in(span, unsafety),
1402 abi: fcx.normalize_associated_types_in(span, abi),
1405 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1406 fcx.register_wf_obligation(
1409 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
1410 function: def_id.expect_local(),
1411 param_idx: i.try_into().unwrap(),
1416 implied_bounds.extend(sig.inputs());
1418 fcx.register_wf_obligation(
1419 sig.output().into(),
1420 hir_decl.output.span(),
1421 ObligationCauseCode::ReturnType,
1424 // FIXME(#27579) return types should not be implied bounds
1425 implied_bounds.insert(sig.output());
1427 debug!(?implied_bounds);
1429 check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
1432 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1433 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1434 of the previous types except `Self`)";
1436 #[tracing::instrument(level = "debug", skip(fcx))]
1437 fn check_method_receiver<'fcx, 'tcx>(
1438 fcx: &FnCtxt<'fcx, 'tcx>,
1439 fn_sig: &hir::FnSig<'_>,
1440 method: &ty::AssocItem,
1443 // Check that the method has a valid receiver type, given the type `Self`.
1444 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1446 if !method.fn_has_self_parameter {
1450 let span = fn_sig.decl.inputs[0].span;
1452 let sig = fcx.tcx.fn_sig(method.def_id);
1453 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
1454 let sig = fcx.normalize_associated_types_in(span, sig);
1456 debug!("check_method_receiver: sig={:?}", sig);
1458 let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1460 let receiver_ty = sig.inputs()[0];
1461 let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
1463 if fcx.tcx.features().arbitrary_self_types {
1464 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1465 // Report error; `arbitrary_self_types` was enabled.
1466 e0307(fcx, span, receiver_ty);
1469 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1470 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1471 // Report error; would have worked with `arbitrary_self_types`.
1473 &fcx.tcx.sess.parse_sess,
1474 sym::arbitrary_self_types,
1477 "`{}` cannot be used as the type of `self` without \
1478 the `arbitrary_self_types` feature",
1482 .help(HELP_FOR_SELF_TYPE)
1485 // Report error; would not have worked with `arbitrary_self_types`.
1486 e0307(fcx, span, receiver_ty);
1492 fn e0307<'tcx>(fcx: &FnCtxt<'_, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1494 fcx.tcx.sess.diagnostic(),
1497 "invalid `self` parameter type: {}",
1500 .note("type of `self` must be `Self` or a type that dereferences to it")
1501 .help(HELP_FOR_SELF_TYPE)
1505 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1506 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1507 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1508 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1509 /// `Deref<Target = self_ty>`.
1511 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1512 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1513 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1514 fn receiver_is_valid<'fcx, 'tcx>(
1515 fcx: &FnCtxt<'fcx, 'tcx>,
1517 receiver_ty: Ty<'tcx>,
1519 arbitrary_self_types_enabled: bool,
1521 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1523 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1525 // `self: Self` is always valid.
1526 if can_eq_self(receiver_ty) {
1527 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1533 let mut autoderef = fcx.autoderef(span, receiver_ty);
1535 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1536 if arbitrary_self_types_enabled {
1537 autoderef = autoderef.include_raw_pointers();
1540 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1543 let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1545 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1547 if let Some((potential_self_ty, _)) = autoderef.next() {
1549 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1550 potential_self_ty, self_ty
1553 if can_eq_self(potential_self_ty) {
1554 fcx.register_predicates(autoderef.into_obligations());
1556 if let Some(mut err) =
1557 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1564 // Without `feature(arbitrary_self_types)`, we require that each step in the
1565 // deref chain implement `receiver`
1566 if !arbitrary_self_types_enabled
1567 && !receiver_is_implemented(
1569 receiver_trait_def_id,
1578 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1579 // If he receiver already has errors reported due to it, consider it valid to avoid
1580 // unnecessary errors (#58712).
1581 return receiver_ty.references_error();
1585 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1586 if !arbitrary_self_types_enabled
1587 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1595 fn receiver_is_implemented<'tcx>(
1596 fcx: &FnCtxt<'_, 'tcx>,
1597 receiver_trait_def_id: DefId,
1598 cause: ObligationCause<'tcx>,
1599 receiver_ty: Ty<'tcx>,
1601 let trait_ref = ty::Binder::dummy(ty::TraitRef {
1602 def_id: receiver_trait_def_id,
1603 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1606 let obligation = traits::Obligation::new(
1609 trait_ref.without_const().to_predicate(fcx.tcx),
1612 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1616 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1623 fn check_variances_for_type_defn<'tcx>(
1625 item: &hir::Item<'tcx>,
1626 hir_generics: &hir::Generics<'_>,
1628 let ty = tcx.type_of(item.def_id);
1629 if tcx.has_error_field(ty) {
1633 let ty_predicates = tcx.predicates_of(item.def_id);
1634 assert_eq!(ty_predicates.parent, None);
1635 let variances = tcx.variances_of(item.def_id);
1637 let mut constrained_parameters: FxHashSet<_> = variances
1640 .filter(|&(_, &variance)| variance != ty::Bivariant)
1641 .map(|(index, _)| Parameter(index as u32))
1644 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1646 for (index, _) in variances.iter().enumerate() {
1647 if constrained_parameters.contains(&Parameter(index as u32)) {
1651 let param = &hir_generics.params[index];
1654 hir::ParamName::Error => {}
1655 _ => report_bivariance(tcx, param),
1660 fn report_bivariance(tcx: TyCtxt<'_>, param: &rustc_hir::GenericParam<'_>) {
1661 let span = param.span;
1662 let param_name = param.name.ident().name;
1663 let mut err = error_392(tcx, span, param_name);
1665 let suggested_marker_id = tcx.lang_items().phantom_data();
1666 // Help is available only in presence of lang items.
1667 let msg = if let Some(def_id) = suggested_marker_id {
1669 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1671 tcx.def_path_str(def_id),
1674 format!("consider removing `{}` or referring to it in a field", param_name)
1678 if matches!(param.kind, rustc_hir::GenericParamKind::Type { .. }) {
1680 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1687 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1689 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, mut span: Span, id: hir::HirId) {
1690 let empty_env = ty::ParamEnv::empty();
1692 let def_id = fcx.tcx.hir().local_def_id(id);
1693 let predicates_with_span =
1694 fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, span)| (*p, *span));
1695 // Check elaborated bounds.
1696 let implied_obligations = traits::elaborate_predicates_with_span(fcx.tcx, predicates_with_span);
1698 for obligation in implied_obligations {
1699 let pred = obligation.predicate;
1700 // Match the existing behavior.
1701 if pred.is_global() && !pred.has_late_bound_regions() {
1702 let pred = fcx.normalize_associated_types_in(span, pred);
1703 let hir_node = fcx.tcx.hir().find(id);
1705 // only use the span of the predicate clause (#90869)
1707 if let Some(hir::Generics { where_clause, .. }) =
1708 hir_node.and_then(|node| node.generics())
1710 let obligation_span = obligation.cause.span(fcx.tcx);
1715 // There seems to be no better way to find out which predicate we are in
1716 .find(|pred| pred.span().contains(obligation_span))
1717 .map(|pred| pred.span())
1718 .unwrap_or(obligation_span);
1721 let obligation = traits::Obligation::new(
1722 traits::ObligationCause::new(span, id, traits::TrivialBound),
1726 fcx.register_predicate(obligation);
1730 fcx.select_all_obligations_or_error();
1733 #[derive(Clone, Copy)]
1734 pub struct CheckTypeWellFormedVisitor<'tcx> {
1738 impl<'tcx> CheckTypeWellFormedVisitor<'tcx> {
1739 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1740 CheckTypeWellFormedVisitor { tcx }
1744 impl<'tcx> ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1745 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1746 Visitor::visit_item(&mut self.clone(), i);
1749 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1750 Visitor::visit_trait_item(&mut self.clone(), trait_item);
1753 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1754 Visitor::visit_impl_item(&mut self.clone(), impl_item);
1757 fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1758 Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1762 impl<'tcx> Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1763 type NestedFilter = nested_filter::OnlyBodies;
1765 fn nested_visit_map(&mut self) -> Self::Map {
1769 #[instrument(skip(self, i), level = "debug")]
1770 fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
1772 self.tcx.ensure().check_item_well_formed(i.def_id);
1773 hir_visit::walk_item(self, i);
1776 #[instrument(skip(self, trait_item), level = "debug")]
1777 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1778 trace!(?trait_item);
1779 self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id);
1780 hir_visit::walk_trait_item(self, trait_item);
1783 #[instrument(skip(self, impl_item), level = "debug")]
1784 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1786 self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id);
1787 hir_visit::walk_impl_item(self, impl_item);
1790 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
1791 check_param_wf(self.tcx, p);
1792 hir_visit::walk_generic_param(self, p);
1796 ///////////////////////////////////////////////////////////////////////////
1799 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1800 struct AdtVariant<'tcx> {
1801 /// Types of fields in the variant, that must be well-formed.
1802 fields: Vec<AdtField<'tcx>>,
1804 /// Explicit discriminant of this variant (e.g. `A = 123`),
1805 /// that must evaluate to a constant value.
1806 explicit_discr: Option<LocalDefId>,
1809 struct AdtField<'tcx> {
1815 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1816 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1817 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1818 let fields = struct_def
1822 let def_id = self.tcx.hir().local_def_id(field.hir_id);
1823 let field_ty = self.tcx.type_of(def_id);
1824 let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
1825 let field_ty = self.resolve_vars_if_possible(field_ty);
1826 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1827 AdtField { ty: field_ty, span: field.ty.span, def_id }
1830 AdtVariant { fields, explicit_discr: None }
1833 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1837 .map(|variant| AdtVariant {
1838 fields: self.non_enum_variant(&variant.data).fields,
1839 explicit_discr: variant
1841 .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1846 pub(super) fn impl_implied_bounds(
1850 ) -> FxHashSet<Ty<'tcx>> {
1851 match self.tcx.impl_trait_ref(impl_def_id) {
1852 Some(trait_ref) => {
1853 // Trait impl: take implied bounds from all types that
1854 // appear in the trait reference.
1855 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1856 trait_ref.substs.types().collect()
1860 // Inherent impl: take implied bounds from the `self` type.
1861 let self_ty = self.tcx.type_of(impl_def_id);
1862 let self_ty = self.normalize_associated_types_in(span, self_ty);
1863 FxHashSet::from_iter([self_ty])
1869 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1871 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1872 err.span_label(span, "unused parameter");