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::TyCtxtInferExt;
18 use rustc_infer::infer::{self, RegionckMode, SubregionOrigin};
19 use rustc_middle::hir::map as hir_map;
20 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
21 use rustc_middle::ty::trait_def::TraitSpecializationKind;
22 use rustc_middle::ty::{
23 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 hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
88 let item = tcx.hir().expect_item(hir_id);
92 item.name = ? tcx.def_path_str(def_id.to_def_id())
96 // Right now we check that every default trait implementation
97 // has an implementation of itself. Basically, a case like:
99 // impl Trait for T {}
101 // has a requirement of `T: Trait` which was required for default
102 // method implementations. Although this could be improved now that
103 // there's a better infrastructure in place for this, it's being left
104 // for a follow-up work.
106 // Since there's such a requirement, we need to check *just* positive
107 // implementations, otherwise things like:
109 // impl !Send for T {}
111 // won't be allowed unless there's an *explicit* implementation of `Send`
113 hir::ItemKind::Impl(ref impl_) => {
115 .impl_trait_ref(item.def_id)
116 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
117 if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
118 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
120 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
121 err.span_labels(impl_.defaultness_span, "default because of this");
122 err.span_label(sp, "auto trait");
125 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
126 match (tcx.impl_polarity(def_id), impl_.polarity) {
127 (ty::ImplPolarity::Positive, _) => {
128 check_impl(tcx, item, impl_.self_ty, &impl_.of_trait);
130 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
131 // FIXME(#27579): what amount of WF checking do we need for neg impls?
132 if let hir::Defaultness::Default { .. } = impl_.defaultness {
133 let mut spans = vec![span];
134 spans.extend(impl_.defaultness_span);
139 "negative impls cannot be default impls"
144 (ty::ImplPolarity::Reservation, _) => {
145 // FIXME: what amount of WF checking do we need for reservation impls?
150 hir::ItemKind::Fn(ref sig, ..) => {
151 check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
153 hir::ItemKind::Static(ty, ..) => {
154 check_item_type(tcx, item.def_id, ty.span, false);
156 hir::ItemKind::Const(ty, ..) => {
157 check_item_type(tcx, item.def_id, ty.span, false);
159 hir::ItemKind::ForeignMod { items, .. } => {
160 for it in items.iter() {
161 let it = tcx.hir().foreign_item(it.id);
163 hir::ForeignItemKind::Fn(decl, ..) => {
164 check_item_fn(tcx, it.def_id, it.ident, it.span, decl)
166 hir::ForeignItemKind::Static(ty, ..) => {
167 check_item_type(tcx, it.def_id, ty.span, true)
169 hir::ForeignItemKind::Type => (),
173 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
174 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
176 check_variances_for_type_defn(tcx, item, ast_generics);
178 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
179 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
181 check_variances_for_type_defn(tcx, item, ast_generics);
183 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
184 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
186 check_variances_for_type_defn(tcx, item, ast_generics);
188 hir::ItemKind::Trait(..) => {
189 check_trait(tcx, item);
191 hir::ItemKind::TraitAlias(..) => {
192 check_trait(tcx, item);
198 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
199 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
200 let trait_item = tcx.hir().expect_trait_item(hir_id);
202 let (method_sig, span) = match trait_item.kind {
203 hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
204 hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
205 _ => (None, trait_item.span),
207 check_object_unsafe_self_trait_by_name(tcx, trait_item);
208 check_associated_item(tcx, trait_item.def_id, span, method_sig);
210 let encl_trait_hir_id = tcx.hir().get_parent_item(hir_id);
211 let encl_trait = tcx.hir().expect_item(encl_trait_hir_id);
212 let encl_trait_def_id = encl_trait.def_id.to_def_id();
213 let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
215 } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
221 if let (Some(fn_lang_item_name), "call") =
222 (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
224 // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
225 // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
226 if let Some(hir::FnSig { decl, span, .. }) = method_sig {
227 if let [self_ty, _] = decl.inputs {
228 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
233 "first argument of `call` in `{}` lang item must be a reference",
244 "`call` function in `{}` lang item takes exactly two arguments",
255 "`call` trait item in `{}` lang item must be a function",
263 check_gat_where_clauses(tcx, trait_item, encl_trait_def_id);
266 /// Require that the user writes where clauses on GATs for the implicit
267 /// outlives bounds involving trait parameters in trait functions and
268 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
270 /// This trait will be our running example. We are currently WF checking the `Item` item...
273 /// trait LendingIterator {
274 /// type Item<'me>; // <-- WF checking this trait item
276 /// fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
279 fn check_gat_where_clauses(
281 trait_item: &hir::TraitItem<'_>,
282 encl_trait_def_id: DefId,
284 let item = tcx.associated_item(trait_item.def_id);
285 // If the current trait item isn't a type, it isn't a GAT
286 if !matches!(item.kind, ty::AssocKind::Type) {
289 let generics: &ty::Generics = tcx.generics_of(trait_item.def_id);
290 // If the current associated type doesn't have any (own) params, it's not a GAT
291 // FIXME(jackh726): we can also warn in the more general case
292 if generics.params.len() == 0 {
295 let associated_items: &ty::AssocItems<'_> = tcx.associated_items(encl_trait_def_id);
296 let mut clauses: Option<FxHashSet<ty::Predicate<'_>>> = None;
297 // For every function in this trait...
298 // In our example, this would be the `next` method
300 associated_items.in_definition_order().filter(|item| matches!(item.kind, ty::AssocKind::Fn))
302 // The clauses we that we would require from this function
303 let mut function_clauses = FxHashSet::default();
305 let id = hir::HirId::make_owner(item.def_id.expect_local());
306 let param_env = tcx.param_env(item.def_id.expect_local());
308 let sig = tcx.fn_sig(item.def_id);
309 // Get the signature using placeholders. In our example, this would
310 // convert the late-bound 'a into a free region.
311 let sig = tcx.liberate_late_bound_regions(item.def_id, sig);
312 // Collect the arguments that are given to this GAT in the return type
313 // of the function signature. In our example, the GAT in the return
314 // type is `<Self as LendingIterator>::Item<'a>`, so 'a and Self are arguments.
315 let (regions, types) =
316 GATSubstCollector::visit(tcx, trait_item.def_id.to_def_id(), sig.output());
318 // If both regions and types are empty, then this GAT isn't in the
319 // return type, and we shouldn't try to do clause analysis
320 // (particularly, doing so would end up with an empty set of clauses,
321 // since the current method would require none, and we take the
322 // intersection of requirements of all methods)
323 if types.is_empty() && regions.is_empty() {
327 // The types we can assume to be well-formed. In our example, this
328 // would be &'a mut Self, from the first argument.
329 let mut wf_tys = FxHashSet::default();
330 wf_tys.extend(sig.inputs());
332 // For each region argument (e.g., 'a in our example), check for a
333 // relationship to the type arguments (e.g., Self). If there is an
334 // outlives relationship (`Self: 'a`), then we want to ensure that is
335 // reflected in a where clause on the GAT itself.
336 for (region, region_idx) in ®ions {
337 for (ty, ty_idx) in &types {
338 // In our example, requires that Self: 'a
339 if ty_known_to_outlive(tcx, id, param_env, &wf_tys, *ty, *region) {
340 debug!(?ty_idx, ?region_idx);
341 debug!("required clause: {} must outlive {}", ty, region);
342 // Translate into the generic parameters of the GAT. In
343 // our example, the type was Self, which will also be
345 let ty_param = generics.param_at(*ty_idx, tcx);
346 let ty_param = tcx.mk_ty(ty::Param(ty::ParamTy {
347 index: ty_param.index,
350 // Same for the region. In our example, 'a corresponds
351 // to the 'me parameter.
352 let region_param = generics.param_at(*region_idx, tcx);
354 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
355 def_id: region_param.def_id,
356 index: region_param.index,
357 name: region_param.name,
359 // The predicate we expect to see. (In our example,
361 let clause = ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(
365 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
366 function_clauses.insert(clause);
371 // For each region argument (e.g., 'a in our example), also check for a
372 // relationship to the other region arguments. If there is an
373 // outlives relationship, then we want to ensure that is
374 // reflected in a where clause on the GAT itself.
375 for (region_a, region_a_idx) in ®ions {
376 for (region_b, region_b_idx) in ®ions {
377 if region_a == region_b {
381 if region_known_to_outlive(tcx, id, param_env, &wf_tys, *region_a, *region_b) {
382 debug!(?region_a_idx, ?region_b_idx);
383 debug!("required clause: {} must outlive {}", region_a, region_b);
384 // Translate into the generic parameters of the GAT.
385 let region_a_param = generics.param_at(*region_a_idx, tcx);
387 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
388 def_id: region_a_param.def_id,
389 index: region_a_param.index,
390 name: region_a_param.name,
392 // Same for the region.
393 let region_b_param = generics.param_at(*region_b_idx, tcx);
395 tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
396 def_id: region_b_param.def_id,
397 index: region_b_param.index,
398 name: region_b_param.name,
400 // The predicate we expect to see.
401 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
405 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
406 function_clauses.insert(clause);
415 // fn gimme(&self) -> Self::Bar<'_>;
416 // fn gimme_default(&self) -> Self::Bar<'static>;
419 // We only want to require clauses on `Bar` that we can prove from *all* functions (in this
420 // case, `'me` can be `static` from `gimme_default`)
421 match clauses.as_mut() {
423 clauses.drain_filter(|p| !function_clauses.contains(p));
426 clauses = Some(function_clauses);
431 // If there are any missing clauses, emit an error
432 let mut clauses = clauses.unwrap_or_default();
434 if !clauses.is_empty() {
435 let written_predicates: ty::GenericPredicates<'_> =
436 tcx.explicit_predicates_of(trait_item.def_id);
437 let mut clauses: Vec<_> = clauses
438 .drain_filter(|clause| !written_predicates.predicates.iter().any(|p| &p.0 == clause))
439 .map(|clause| format!("{}", clause))
441 // We sort so that order is predictable
443 if !clauses.is_empty() {
444 let mut err = tcx.sess.struct_span_err(
446 &format!("Missing required bounds on {}", trait_item.ident),
449 let suggestion = format!(
451 if !trait_item.generics.where_clause.predicates.is_empty() {
459 trait_item.generics.where_clause.tail_span_for_suggestion(),
460 "add the required where clauses",
462 Applicability::MachineApplicable,
470 // FIXME(jackh726): refactor some of the shared logic between the two functions below
472 /// Given a known `param_env` and a set of well formed types, can we prove that
473 /// `ty` outlives `region`.
474 fn ty_known_to_outlive<'tcx>(
477 param_env: ty::ParamEnv<'tcx>,
478 wf_tys: &FxHashSet<Ty<'tcx>>,
480 region: ty::Region<'tcx>,
482 // Unfortunately, we have to use a new `InferCtxt` each call, because
483 // region constraints get added and solved there and we need to test each
484 // call individually.
485 tcx.infer_ctxt().enter(|infcx| {
486 let mut outlives_environment = OutlivesEnvironment::new(param_env);
487 outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id, DUMMY_SP);
488 outlives_environment.save_implied_bounds(id);
489 let region_bound_pairs = outlives_environment.region_bound_pairs_map().get(&id).unwrap();
491 let cause = ObligationCause::new(DUMMY_SP, id, ObligationCauseCode::MiscObligation);
494 let sub_region = region;
496 let origin = SubregionOrigin::from_obligation_cause(&cause, || {
497 infer::RelateParamBound(cause.span, sup_type, None)
500 let outlives = &mut TypeOutlives::new(
504 Some(infcx.tcx.lifetimes.re_root_empty),
507 outlives.type_must_outlive(origin, sup_type, sub_region);
509 let errors = infcx.resolve_regions(
510 id.expect_owner().to_def_id(),
511 &outlives_environment,
512 RegionckMode::default(),
515 debug!(?errors, "errors");
517 // If we were able to prove that the type outlives the region without
518 // an error, it must be because of the implied or explicit bounds...
523 fn region_known_to_outlive<'tcx>(
526 param_env: ty::ParamEnv<'tcx>,
527 wf_tys: &FxHashSet<Ty<'tcx>>,
528 region_a: ty::Region<'tcx>,
529 region_b: ty::Region<'tcx>,
531 // Unfortunately, we have to use a new `InferCtxt` each call, because
532 // region constraints get added and solved there and we need to test each
533 // call individually.
534 tcx.infer_ctxt().enter(|infcx| {
535 let mut outlives_environment = OutlivesEnvironment::new(param_env);
536 outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id, DUMMY_SP);
537 outlives_environment.save_implied_bounds(id);
539 let cause = ObligationCause::new(DUMMY_SP, id, ObligationCauseCode::MiscObligation);
541 let origin = SubregionOrigin::from_obligation_cause(&cause, || {
542 infer::RelateRegionParamBound(cause.span)
545 use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
546 (&infcx).push_sub_region_constraint(origin, region_a, region_b);
548 let errors = infcx.resolve_regions(
549 id.expect_owner().to_def_id(),
550 &outlives_environment,
551 RegionckMode::default(),
554 debug!(?errors, "errors");
556 // If we were able to prove that the type outlives the region without
557 // an error, it must be because of the implied or explicit bounds...
562 /// TypeVisitor that looks for uses of GATs like
563 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
564 /// the two vectors, `regions` and `types` (depending on their kind). For each
565 /// parameter `Pi` also track the index `i`.
566 struct GATSubstCollector<'tcx> {
569 // Which region appears and which parameter index its subsituted for
570 regions: FxHashSet<(ty::Region<'tcx>, usize)>,
571 // Which params appears and which parameter index its subsituted for
572 types: FxHashSet<(Ty<'tcx>, usize)>,
575 impl<'tcx> GATSubstCollector<'tcx> {
576 fn visit<T: TypeFoldable<'tcx>>(
580 ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
581 let mut visitor = GATSubstCollector {
584 regions: FxHashSet::default(),
585 types: FxHashSet::default(),
587 t.visit_with(&mut visitor);
588 (visitor.regions, visitor.types)
592 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
595 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
597 ty::Projection(p) if p.item_def_id == self.gat => {
598 for (idx, subst) in p.substs.iter().enumerate() {
599 match subst.unpack() {
600 GenericArgKind::Lifetime(lt) => {
601 self.regions.insert((lt, idx));
603 GenericArgKind::Type(t) => {
604 self.types.insert((t, idx));
612 t.super_visit_with(self)
615 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
620 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
622 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
623 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
630 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
631 /// When this is done, suggest using `Self` instead.
632 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
633 let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id())) {
634 hir::Node::Item(item) => match item.kind {
635 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
640 let mut trait_should_be_self = vec![];
642 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
643 if could_be_self(trait_def_id, ty) =>
645 trait_should_be_self.push(ty.span)
647 hir::TraitItemKind::Fn(sig, _) => {
648 for ty in sig.decl.inputs {
649 if could_be_self(trait_def_id, ty) {
650 trait_should_be_self.push(ty.span);
653 match sig.decl.output {
654 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
655 trait_should_be_self.push(ty.span);
662 if !trait_should_be_self.is_empty() {
663 if tcx.object_safety_violations(trait_def_id).is_empty() {
666 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
669 trait_should_be_self,
670 "associated item referring to unboxed trait object for its own trait",
672 .span_label(trait_name.span, "in this trait")
673 .multipart_suggestion(
674 "you might have meant to use `Self` to refer to the implementing type",
676 Applicability::MachineApplicable,
682 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
683 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
684 let impl_item = tcx.hir().expect_impl_item(hir_id);
686 let (method_sig, span) = match impl_item.kind {
687 hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
688 hir::ImplItemKind::TyAlias(ty) => (None, ty.span),
689 _ => (None, impl_item.span),
692 check_associated_item(tcx, impl_item.def_id, span, method_sig);
695 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
697 // We currently only check wf of const params here.
698 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
700 // Const parameters are well formed if their type is structural match.
701 // FIXME(const_generics_defaults): we also need to check that the `default` is wf.
702 hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
703 let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
706 let mut is_ptr = true;
707 let err = if tcx.features().adt_const_params {
708 match ty.peel_refs().kind() {
709 ty::FnPtr(_) => Some("function pointers"),
710 ty::RawPtr(_) => Some("raw pointers"),
715 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
716 ty::FnPtr(_) => Some("function pointers"),
717 ty::RawPtr(_) => Some("raw pointers"),
720 err_ty_str = format!("`{}`", ty);
721 Some(err_ty_str.as_str())
725 if let Some(unsupported_type) = err {
730 "using {} as const generic parameters is forbidden",
735 let mut err = tcx.sess.struct_span_err(
738 "{} is forbidden as the type of a const generic parameter",
742 err.note("the only supported types are integers, `bool` and `char`");
743 if tcx.sess.is_nightly_build() {
745 "more complex types are supported with `#![feature(adt_const_params)]`",
752 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
755 // We use the same error code in both branches, because this is really the same
756 // issue: we just special-case the message for type parameters to make it
758 if let ty::Param(_) = ty.peel_refs().kind() {
759 // Const parameters may not have type parameters as their types,
760 // because we cannot be sure that the type parameter derives `PartialEq`
761 // and `Eq` (just implementing them is not enough for `structural_match`).
766 "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
767 used as the type of a const parameter",
772 format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
775 "it is not currently possible to use a type parameter as the type of a \
784 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
785 the type of a const parameter",
790 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
799 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
800 fn check_associated_item(
804 sig_if_method: Option<&hir::FnSig<'_>>,
806 let code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id)));
807 for_id(tcx, item_id, span).with_fcx(|fcx| {
808 let item = fcx.tcx.associated_item(item_id);
810 let (mut implied_bounds, self_ty) = match item.container {
811 ty::TraitContainer(_) => (FxHashSet::default(), fcx.tcx.types.self_param),
812 ty::ImplContainer(def_id) => {
813 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
818 ty::AssocKind::Const => {
819 let ty = fcx.tcx.type_of(item.def_id);
820 let ty = fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
821 fcx.register_wf_obligation(ty.into(), span, code.clone());
823 ty::AssocKind::Fn => {
824 let sig = fcx.tcx.fn_sig(item.def_id);
825 let hir_sig = sig_if_method.expect("bad signature for method");
834 check_method_receiver(fcx, hir_sig, item, self_ty);
836 ty::AssocKind::Type => {
837 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
838 check_associated_type_bounds(fcx, item, span)
840 if item.defaultness.has_value() {
841 let ty = fcx.tcx.type_of(item.def_id);
843 fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
844 fcx.register_wf_obligation(ty.into(), span, code.clone());
853 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
854 for_id(tcx, item.def_id, item.span)
857 fn for_id(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> CheckWfFcxBuilder<'_> {
859 inherited: Inherited::build(tcx, def_id),
860 id: hir::HirId::make_owner(def_id),
862 param_env: tcx.param_env(def_id),
866 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
868 ItemKind::Struct(..) => Some(AdtKind::Struct),
869 ItemKind::Union(..) => Some(AdtKind::Union),
870 ItemKind::Enum(..) => Some(AdtKind::Enum),
875 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
876 fn check_type_defn<'tcx, F>(
878 item: &hir::Item<'tcx>,
880 mut lookup_fields: F,
882 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
884 for_item(tcx, item).with_fcx(|fcx| {
885 let variants = lookup_fields(fcx);
886 let packed = tcx.adt_def(item.def_id).repr.packed();
888 for variant in &variants {
889 // For DST, or when drop needs to copy things around, all
890 // intermediate types must be sized.
891 let needs_drop_copy = || {
893 let ty = variant.fields.last().unwrap().ty;
894 let ty = tcx.erase_regions(ty);
895 if ty.needs_infer() {
897 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
898 // Just treat unresolved type expression as if it needs drop.
901 ty.needs_drop(tcx, tcx.param_env(item.def_id))
905 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
906 let unsized_len = if all_sized { 0 } else { 1 };
908 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
910 let last = idx == variant.fields.len() - 1;
913 tcx.require_lang_item(LangItem::Sized, None),
914 traits::ObligationCause::new(
918 adt_kind: match item_adt_kind(&item.kind) {
929 // All field types must be well-formed.
930 for field in &variant.fields {
931 fcx.register_wf_obligation(
934 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(field.def_id))),
938 // Explicit `enum` discriminant values must const-evaluate successfully.
939 if let Some(discr_def_id) = variant.explicit_discr {
940 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
942 let cause = traits::ObligationCause::new(
943 tcx.def_span(discr_def_id),
945 traits::MiscObligation,
947 fcx.register_predicate(traits::Obligation::new(
950 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
951 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
959 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
961 // No implied bounds in a struct definition.
966 #[instrument(skip(tcx, item))]
967 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
968 debug!(?item.def_id);
970 let trait_def = tcx.trait_def(item.def_id);
971 if trait_def.is_marker
972 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
974 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
977 tcx.def_span(*associated_def_id),
979 "marker traits cannot have associated items",
985 // FIXME: this shouldn't use an `FnCtxt` at all.
986 for_item(tcx, item).with_fcx(|fcx| {
987 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
993 /// Checks all associated type defaults of trait `trait_def_id`.
995 /// Assuming the defaults are used, check that all predicates (bounds on the
996 /// assoc type and where clauses on the trait) hold.
997 fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1000 let bounds = tcx.explicit_item_bounds(item.def_id);
1002 debug!("check_associated_type_bounds: bounds={:?}", bounds);
1003 let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1004 let normalized_bound = fcx.normalize_associated_types_in(span, bound);
1005 traits::wf::predicate_obligations(
1014 for obligation in wf_obligations {
1015 debug!("next obligation cause: {:?}", obligation.cause);
1016 fcx.register_predicate(obligation);
1025 decl: &hir::FnDecl<'_>,
1027 for_id(tcx, def_id, span).with_fcx(|fcx| {
1028 let sig = tcx.fn_sig(def_id);
1029 let mut implied_bounds = FxHashSet::default();
1030 check_fn_or_method(fcx, ident.span, sig, decl, def_id.to_def_id(), &mut implied_bounds);
1035 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1036 debug!("check_item_type: {:?}", item_id);
1038 for_id(tcx, item_id, ty_span).with_fcx(|fcx| {
1039 let ty = tcx.type_of(item_id);
1040 let item_ty = fcx.normalize_associated_types_in_wf(ty_span, ty, WellFormedLoc::Ty(item_id));
1042 let mut forbid_unsized = true;
1043 if allow_foreign_ty {
1044 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
1045 if let ty::Foreign(_) = tail.kind() {
1046 forbid_unsized = false;
1050 fcx.register_wf_obligation(
1053 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id))),
1058 tcx.require_lang_item(LangItem::Sized, None),
1059 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
1063 // No implied bounds in a const, etc.
1064 FxHashSet::default()
1068 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1069 fn check_impl<'tcx>(
1071 item: &'tcx hir::Item<'tcx>,
1072 ast_self_ty: &hir::Ty<'_>,
1073 ast_trait_ref: &Option<hir::TraitRef<'_>>,
1075 for_item(tcx, item).with_fcx(|fcx| {
1076 match *ast_trait_ref {
1077 Some(ref ast_trait_ref) => {
1078 // `#[rustc_reservation_impl]` impls are not real impls and
1079 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1081 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1083 fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
1084 let obligations = traits::wf::trait_obligations(
1089 ast_trait_ref.path.span,
1092 debug!(?obligations);
1093 for obligation in obligations {
1094 fcx.register_predicate(obligation);
1098 let self_ty = tcx.type_of(item.def_id);
1099 let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
1100 fcx.register_wf_obligation(
1103 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(
1104 item.hir_id().expect_owner(),
1110 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
1112 fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
1116 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1117 #[instrument(skip(fcx), level = "debug")]
1118 fn check_where_clauses<'tcx, 'fcx>(
1119 fcx: &FnCtxt<'fcx, 'tcx>,
1122 return_ty: Option<(Ty<'tcx>, Span)>,
1126 let predicates = tcx.predicates_of(def_id);
1127 let generics = tcx.generics_of(def_id);
1129 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1130 GenericParamDefKind::Type { has_default, .. }
1131 | GenericParamDefKind::Const { has_default } => {
1132 has_default && def.index >= generics.parent_count as u32
1134 GenericParamDefKind::Lifetime => unreachable!(),
1137 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1138 // For example, this forbids the declaration:
1140 // struct Foo<T = Vec<[u32]>> { .. }
1142 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1143 for param in &generics.params {
1145 GenericParamDefKind::Type { .. } => {
1146 if is_our_default(param) {
1147 let ty = tcx.type_of(param.def_id);
1148 // Ignore dependent defaults -- that is, where the default of one type
1149 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1150 // be sure if it will error or not as user might always specify the other.
1151 if !ty.definitely_needs_subst(tcx) {
1152 fcx.register_wf_obligation(
1154 tcx.def_span(param.def_id),
1155 ObligationCauseCode::MiscObligation,
1160 GenericParamDefKind::Const { .. } => {
1161 if is_our_default(param) {
1162 // FIXME(const_generics_defaults): This
1163 // is incorrect when dealing with unused substs, for example
1164 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1165 // we should eagerly error.
1166 let default_ct = tcx.const_param_default(param.def_id);
1167 if !default_ct.definitely_needs_subst(tcx) {
1168 fcx.register_wf_obligation(
1170 tcx.def_span(param.def_id),
1171 ObligationCauseCode::WellFormed(None),
1176 // Doesn't have defaults.
1177 GenericParamDefKind::Lifetime => {}
1181 // Check that trait predicates are WF when params are substituted by their defaults.
1182 // We don't want to overly constrain the predicates that may be written but we want to
1183 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1184 // Therefore we check if a predicate which contains a single type param
1185 // with a concrete default is WF with that default substituted.
1186 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1188 // First we build the defaulted substitution.
1189 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
1191 GenericParamDefKind::Lifetime => {
1192 // All regions are identity.
1193 tcx.mk_param_from_def(param)
1196 GenericParamDefKind::Type { .. } => {
1197 // If the param has a default, ...
1198 if is_our_default(param) {
1199 let default_ty = tcx.type_of(param.def_id);
1200 // ... and it's not a dependent default, ...
1201 if !default_ty.definitely_needs_subst(tcx) {
1202 // ... then substitute it with the default.
1203 return default_ty.into();
1207 tcx.mk_param_from_def(param)
1209 GenericParamDefKind::Const { .. } => {
1210 // If the param has a default, ...
1211 if is_our_default(param) {
1212 let default_ct = tcx.const_param_default(param.def_id);
1213 // ... and it's not a dependent default, ...
1214 if !default_ct.definitely_needs_subst(tcx) {
1215 // ... then substitute it with the default.
1216 return default_ct.into();
1220 tcx.mk_param_from_def(param)
1225 // Now we build the substituted predicates.
1226 let default_obligations = predicates
1229 .flat_map(|&(pred, sp)| {
1230 struct CountParams<'tcx> {
1232 params: FxHashSet<u32>,
1234 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams<'tcx> {
1236 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
1240 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1241 if let ty::Param(param) = t.kind() {
1242 self.params.insert(param.index);
1244 t.super_visit_with(self)
1247 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1251 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1252 if let ty::ConstKind::Param(param) = c.val {
1253 self.params.insert(param.index);
1255 c.super_visit_with(self)
1258 let mut param_count = CountParams { tcx: fcx.tcx, params: FxHashSet::default() };
1259 let has_region = pred.visit_with(&mut param_count).is_break();
1260 let substituted_pred = pred.subst(tcx, substs);
1261 // Don't check non-defaulted params, dependent defaults (including lifetimes)
1262 // or preds with multiple params.
1263 if substituted_pred.definitely_has_param_types_or_consts(tcx)
1264 || param_count.params.len() > 1
1268 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1269 // Avoid duplication of predicates that contain no parameters, for example.
1272 Some((substituted_pred, sp))
1276 // Convert each of those into an obligation. So if you have
1277 // something like `struct Foo<T: Copy = String>`, we would
1278 // take that predicate `T: Copy`, substitute to `String: Copy`
1279 // (actually that happens in the previous `flat_map` call),
1280 // and then try to prove it (in this case, we'll fail).
1282 // Note the subtle difference from how we handle `predicates`
1283 // below: there, we are not trying to prove those predicates
1284 // to be *true* but merely *well-formed*.
1285 let pred = fcx.normalize_associated_types_in(sp, pred);
1287 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
1288 traits::Obligation::new(cause, fcx.param_env, pred)
1291 let predicates = predicates.instantiate_identity(tcx);
1293 if let Some((return_ty, _)) = return_ty {
1294 if return_ty.has_infer_types_or_consts() {
1295 fcx.select_obligations_where_possible(false, |_| {});
1299 let predicates = fcx.normalize_associated_types_in(span, predicates);
1301 debug!(?predicates.predicates);
1302 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1303 let wf_obligations =
1304 iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1305 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
1308 for obligation in wf_obligations.chain(default_obligations) {
1309 debug!("next obligation cause: {:?}", obligation.cause);
1310 fcx.register_predicate(obligation);
1314 #[tracing::instrument(level = "debug", skip(fcx, span, hir_decl))]
1315 fn check_fn_or_method<'fcx, 'tcx>(
1316 fcx: &FnCtxt<'fcx, 'tcx>,
1318 sig: ty::PolyFnSig<'tcx>,
1319 hir_decl: &hir::FnDecl<'_>,
1321 implied_bounds: &mut FxHashSet<Ty<'tcx>>,
1323 let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
1325 // Unnormalized types in signature are WF too
1326 implied_bounds.extend(sig.inputs());
1327 // FIXME(#27579) return types should not be implied bounds
1328 implied_bounds.insert(sig.output());
1330 // Normalize the input and output types one at a time, using a different
1331 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1332 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1333 // for each type, preventing the HIR wf check from generating
1334 // a nice error message.
1335 let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1337 fcx.tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1338 fcx.normalize_associated_types_in_wf(
1341 WellFormedLoc::Param {
1342 function: def_id.expect_local(),
1343 // Note that the `param_idx` of the output type is
1344 // one greater than the index of the last input type.
1345 param_idx: i.try_into().unwrap(),
1349 // Manually call `normalize_assocaited_types_in` on the other types
1350 // in `FnSig`. This ensures that if the types of these fields
1351 // ever change to include projections, we will start normalizing
1352 // them automatically.
1353 let sig = ty::FnSig {
1355 c_variadic: fcx.normalize_associated_types_in(span, c_variadic),
1356 unsafety: fcx.normalize_associated_types_in(span, unsafety),
1357 abi: fcx.normalize_associated_types_in(span, abi),
1360 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1361 fcx.register_wf_obligation(
1364 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
1365 function: def_id.expect_local(),
1366 param_idx: i.try_into().unwrap(),
1371 implied_bounds.extend(sig.inputs());
1373 fcx.register_wf_obligation(
1374 sig.output().into(),
1375 hir_decl.output.span(),
1376 ObligationCauseCode::ReturnType,
1379 // FIXME(#27579) return types should not be implied bounds
1380 implied_bounds.insert(sig.output());
1382 debug!(?implied_bounds);
1384 check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
1387 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1388 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1389 of the previous types except `Self`)";
1391 #[tracing::instrument(level = "debug", skip(fcx))]
1392 fn check_method_receiver<'fcx, 'tcx>(
1393 fcx: &FnCtxt<'fcx, 'tcx>,
1394 fn_sig: &hir::FnSig<'_>,
1395 method: &ty::AssocItem,
1398 // Check that the method has a valid receiver type, given the type `Self`.
1399 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1401 if !method.fn_has_self_parameter {
1405 let span = fn_sig.decl.inputs[0].span;
1407 let sig = fcx.tcx.fn_sig(method.def_id);
1408 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
1409 let sig = fcx.normalize_associated_types_in(span, sig);
1411 debug!("check_method_receiver: sig={:?}", sig);
1413 let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1415 let receiver_ty = sig.inputs()[0];
1416 let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
1418 if fcx.tcx.features().arbitrary_self_types {
1419 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1420 // Report error; `arbitrary_self_types` was enabled.
1421 e0307(fcx, span, receiver_ty);
1424 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1425 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1426 // Report error; would have worked with `arbitrary_self_types`.
1428 &fcx.tcx.sess.parse_sess,
1429 sym::arbitrary_self_types,
1432 "`{}` cannot be used as the type of `self` without \
1433 the `arbitrary_self_types` feature",
1437 .help(HELP_FOR_SELF_TYPE)
1440 // Report error; would not have worked with `arbitrary_self_types`.
1441 e0307(fcx, span, receiver_ty);
1447 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1449 fcx.tcx.sess.diagnostic(),
1452 "invalid `self` parameter type: {}",
1455 .note("type of `self` must be `Self` or a type that dereferences to it")
1456 .help(HELP_FOR_SELF_TYPE)
1460 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1461 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1462 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1463 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1464 /// `Deref<Target = self_ty>`.
1466 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1467 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1468 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1469 fn receiver_is_valid<'fcx, 'tcx>(
1470 fcx: &FnCtxt<'fcx, 'tcx>,
1472 receiver_ty: Ty<'tcx>,
1474 arbitrary_self_types_enabled: bool,
1476 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1478 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1480 // `self: Self` is always valid.
1481 if can_eq_self(receiver_ty) {
1482 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1488 let mut autoderef = fcx.autoderef(span, receiver_ty);
1490 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1491 if arbitrary_self_types_enabled {
1492 autoderef = autoderef.include_raw_pointers();
1495 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1498 let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1500 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1502 if let Some((potential_self_ty, _)) = autoderef.next() {
1504 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1505 potential_self_ty, self_ty
1508 if can_eq_self(potential_self_ty) {
1509 fcx.register_predicates(autoderef.into_obligations());
1511 if let Some(mut err) =
1512 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1519 // Without `feature(arbitrary_self_types)`, we require that each step in the
1520 // deref chain implement `receiver`
1521 if !arbitrary_self_types_enabled
1522 && !receiver_is_implemented(
1524 receiver_trait_def_id,
1533 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1534 // If he receiver already has errors reported due to it, consider it valid to avoid
1535 // unnecessary errors (#58712).
1536 return receiver_ty.references_error();
1540 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1541 if !arbitrary_self_types_enabled
1542 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1550 fn receiver_is_implemented(
1551 fcx: &FnCtxt<'_, 'tcx>,
1552 receiver_trait_def_id: DefId,
1553 cause: ObligationCause<'tcx>,
1554 receiver_ty: Ty<'tcx>,
1556 let trait_ref = ty::Binder::dummy(ty::TraitRef {
1557 def_id: receiver_trait_def_id,
1558 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1561 let obligation = traits::Obligation::new(
1564 trait_ref.without_const().to_predicate(fcx.tcx),
1567 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1571 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1578 fn check_variances_for_type_defn<'tcx>(
1580 item: &hir::Item<'tcx>,
1581 hir_generics: &hir::Generics<'_>,
1583 let ty = tcx.type_of(item.def_id);
1584 if tcx.has_error_field(ty) {
1588 let ty_predicates = tcx.predicates_of(item.def_id);
1589 assert_eq!(ty_predicates.parent, None);
1590 let variances = tcx.variances_of(item.def_id);
1592 let mut constrained_parameters: FxHashSet<_> = variances
1595 .filter(|&(_, &variance)| variance != ty::Bivariant)
1596 .map(|(index, _)| Parameter(index as u32))
1599 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1601 for (index, _) in variances.iter().enumerate() {
1602 if constrained_parameters.contains(&Parameter(index as u32)) {
1606 let param = &hir_generics.params[index];
1609 hir::ParamName::Error => {}
1610 _ => report_bivariance(tcx, param),
1615 fn report_bivariance(tcx: TyCtxt<'_>, param: &rustc_hir::GenericParam<'_>) {
1616 let span = param.span;
1617 let param_name = param.name.ident().name;
1618 let mut err = error_392(tcx, span, param_name);
1620 let suggested_marker_id = tcx.lang_items().phantom_data();
1621 // Help is available only in presence of lang items.
1622 let msg = if let Some(def_id) = suggested_marker_id {
1624 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1626 tcx.def_path_str(def_id),
1629 format!("consider removing `{}` or referring to it in a field", param_name)
1633 if matches!(param.kind, rustc_hir::GenericParamKind::Type { .. }) {
1635 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1642 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1644 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, mut span: Span, id: hir::HirId) {
1645 let empty_env = ty::ParamEnv::empty();
1647 let def_id = fcx.tcx.hir().local_def_id(id);
1648 let predicates_with_span =
1649 fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, span)| (*p, *span));
1650 // Check elaborated bounds.
1651 let implied_obligations = traits::elaborate_predicates_with_span(fcx.tcx, predicates_with_span);
1653 for obligation in implied_obligations {
1654 let pred = obligation.predicate;
1655 // Match the existing behavior.
1656 if pred.is_global(fcx.tcx) && !pred.has_late_bound_regions() {
1657 let pred = fcx.normalize_associated_types_in(span, pred);
1658 let hir_node = fcx.tcx.hir().find(id);
1660 // only use the span of the predicate clause (#90869)
1662 if let Some(hir::Generics { where_clause, .. }) =
1663 hir_node.and_then(|node| node.generics())
1665 let obligation_span = obligation.cause.span(fcx.tcx);
1670 // There seems to be no better way to find out which predicate we are in
1671 .find(|pred| pred.span().contains(obligation_span))
1672 .map(|pred| pred.span())
1673 .unwrap_or(obligation_span);
1676 let obligation = traits::Obligation::new(
1677 traits::ObligationCause::new(span, id, traits::TrivialBound),
1681 fcx.register_predicate(obligation);
1685 fcx.select_all_obligations_or_error();
1688 #[derive(Clone, Copy)]
1689 pub struct CheckTypeWellFormedVisitor<'tcx> {
1693 impl CheckTypeWellFormedVisitor<'tcx> {
1694 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1695 CheckTypeWellFormedVisitor { tcx }
1699 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1700 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1701 Visitor::visit_item(&mut self.clone(), i);
1704 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1705 Visitor::visit_trait_item(&mut self.clone(), trait_item);
1708 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1709 Visitor::visit_impl_item(&mut self.clone(), impl_item);
1712 fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1713 Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1717 impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1718 type Map = hir_map::Map<'tcx>;
1720 fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
1721 hir_visit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
1724 #[instrument(skip(self, i), level = "debug")]
1725 fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
1727 self.tcx.ensure().check_item_well_formed(i.def_id);
1728 hir_visit::walk_item(self, i);
1731 #[instrument(skip(self, trait_item), level = "debug")]
1732 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1733 trace!(?trait_item);
1734 self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id);
1735 hir_visit::walk_trait_item(self, trait_item);
1738 #[instrument(skip(self, impl_item), level = "debug")]
1739 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1741 self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id);
1742 hir_visit::walk_impl_item(self, impl_item);
1745 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
1746 check_param_wf(self.tcx, p);
1747 hir_visit::walk_generic_param(self, p);
1751 ///////////////////////////////////////////////////////////////////////////
1754 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1755 struct AdtVariant<'tcx> {
1756 /// Types of fields in the variant, that must be well-formed.
1757 fields: Vec<AdtField<'tcx>>,
1759 /// Explicit discriminant of this variant (e.g. `A = 123`),
1760 /// that must evaluate to a constant value.
1761 explicit_discr: Option<LocalDefId>,
1764 struct AdtField<'tcx> {
1770 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1771 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1772 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1773 let fields = struct_def
1777 let def_id = self.tcx.hir().local_def_id(field.hir_id);
1778 let field_ty = self.tcx.type_of(def_id);
1779 let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
1780 let field_ty = self.resolve_vars_if_possible(field_ty);
1781 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1782 AdtField { ty: field_ty, span: field.ty.span, def_id }
1785 AdtVariant { fields, explicit_discr: None }
1788 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1792 .map(|variant| AdtVariant {
1793 fields: self.non_enum_variant(&variant.data).fields,
1794 explicit_discr: variant
1796 .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1801 pub(super) fn impl_implied_bounds(
1805 ) -> FxHashSet<Ty<'tcx>> {
1806 match self.tcx.impl_trait_ref(impl_def_id) {
1807 Some(trait_ref) => {
1808 // Trait impl: take implied bounds from all types that
1809 // appear in the trait reference.
1810 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1811 trait_ref.substs.types().collect()
1815 // Inherent impl: take implied bounds from the `self` type.
1816 let self_ty = self.tcx.type_of(impl_def_id);
1817 let self_ty = self.normalize_associated_types_in(span, self_ty);
1818 std::array::IntoIter::new([self_ty]).collect()
1824 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1826 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1827 err.span_label(span, "unused parameter");