1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use rustc::middle::lang_items;
5 use rustc::ty::subst::{InternalSubsts, Subst};
6 use rustc::ty::trait_def::TraitSpecializationKind;
8 self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
16 use rustc_hir::ItemKind;
17 use rustc_session::parse::feature_err;
18 use rustc_span::symbol::sym;
20 use rustc_trait_selection::opaque_types::may_define_opaque_type;
21 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
22 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
24 /// Helper type of a temporary returned by `.for_item(...)`.
25 /// This is necessary because we can't write the following bound:
28 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
30 struct CheckWfFcxBuilder<'tcx> {
31 inherited: super::InheritedBuilder<'tcx>,
34 param_env: ty::ParamEnv<'tcx>,
37 impl<'tcx> CheckWfFcxBuilder<'tcx> {
38 fn with_fcx<F>(&mut self, f: F)
40 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
44 let param_env = self.param_env;
45 self.inherited.enter(|inh| {
46 let fcx = FnCtxt::new(&inh, param_env, id);
47 if !inh.tcx.features().trivial_bounds {
48 // As predicates are cached rather than obligations, this
49 // needsto be called first so that they are checked with an
51 check_false_global_bounds(&fcx, span, id);
53 let wf_tys = f(&fcx, fcx.tcx);
54 fcx.select_all_obligations_or_error();
55 fcx.regionck_item(id, span, &wf_tys);
60 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
61 /// well-formed, meaning that they do not require any constraints not declared in the struct
62 /// definition itself. For example, this definition would be illegal:
65 /// struct Ref<'a, T> { x: &'a T }
68 /// because the type did not declare that `T:'a`.
70 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
71 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
73 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
74 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
75 let item = tcx.hir().expect_item(hir_id);
78 "check_item_well_formed(it.hir_id={:?}, it.name={})",
80 tcx.def_path_str(def_id)
84 // Right now we check that every default trait implementation
85 // has an implementation of itself. Basically, a case like:
87 // impl Trait for T {}
89 // has a requirement of `T: Trait` which was required for default
90 // method implementations. Although this could be improved now that
91 // there's a better infrastructure in place for this, it's being left
92 // for a follow-up work.
94 // Since there's such a requirement, we need to check *just* positive
95 // implementations, otherwise things like:
97 // impl !Send for T {}
99 // won't be allowed unless there's an *explicit* implementation of `Send`
101 hir::ItemKind::Impl { defaultness, ref of_trait, ref self_ty, .. } => {
103 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
104 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
105 let polarity = tcx.impl_polarity(def_id);
106 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
107 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
110 ty::ImplPolarity::Positive => {
111 check_impl(tcx, item, self_ty, of_trait);
113 ty::ImplPolarity::Negative => {
114 // FIXME(#27579): what amount of WF checking do we need for neg impls?
115 if of_trait.is_some() && !is_auto {
120 "negative impls are only allowed for \
121 auto traits (e.g., `Send` and `Sync`)"
126 ty::ImplPolarity::Reservation => {
127 // FIXME: what amount of WF checking do we need for reservation impls?
131 hir::ItemKind::Fn(..) => {
132 check_item_fn(tcx, item);
134 hir::ItemKind::Static(ref ty, ..) => {
135 check_item_type(tcx, item.hir_id, ty.span, false);
137 hir::ItemKind::Const(ref ty, ..) => {
138 check_item_type(tcx, item.hir_id, ty.span, false);
140 hir::ItemKind::ForeignMod(ref module) => {
141 for it in module.items.iter() {
142 if let hir::ForeignItemKind::Static(ref ty, ..) = it.kind {
143 check_item_type(tcx, it.hir_id, ty.span, true);
147 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
148 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
150 check_variances_for_type_defn(tcx, item, ast_generics);
152 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
153 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
155 check_variances_for_type_defn(tcx, item, ast_generics);
157 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
158 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
160 check_variances_for_type_defn(tcx, item, ast_generics);
162 hir::ItemKind::Trait(..) => {
163 check_trait(tcx, item);
165 hir::ItemKind::TraitAlias(..) => {
166 check_trait(tcx, item);
172 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
173 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
174 let trait_item = tcx.hir().expect_trait_item(hir_id);
176 let method_sig = match trait_item.kind {
177 hir::TraitItemKind::Fn(ref sig, _) => Some(sig),
180 check_object_unsafe_self_trait_by_name(tcx, &trait_item);
181 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
184 fn could_be_self(trait_def_id: DefId, ty: &hir::Ty<'_>) -> bool {
186 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
187 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id),
194 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
195 /// When this is done, suggest using `Self` instead.
196 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
197 let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id)) {
198 hir::Node::Item(item) => match item.kind {
199 hir::ItemKind::Trait(..) => (item.ident, tcx.hir().local_def_id(item.hir_id)),
204 let mut trait_should_be_self = vec![];
206 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
207 if could_be_self(trait_def_id, ty) =>
209 trait_should_be_self.push(ty.span)
211 hir::TraitItemKind::Fn(sig, _) => {
212 for ty in sig.decl.inputs {
213 if could_be_self(trait_def_id, ty) {
214 trait_should_be_self.push(ty.span);
217 match sig.decl.output {
218 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
219 trait_should_be_self.push(ty.span);
226 if !trait_should_be_self.is_empty() {
227 if tcx.object_safety_violations(trait_def_id).is_empty() {
230 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
233 trait_should_be_self,
234 "associated item referring to unboxed trait object for its own trait",
236 .span_label(trait_name.span, "in this trait")
237 .multipart_suggestion(
238 "you might have meant to use `Self` to refer to the implementing type",
240 Applicability::MachineApplicable,
246 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
247 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
248 let impl_item = tcx.hir().expect_impl_item(hir_id);
250 let method_sig = match impl_item.kind {
251 hir::ImplItemKind::Fn(ref sig, _) => Some(sig),
255 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
258 fn check_associated_item(
262 sig_if_method: Option<&hir::FnSig<'_>>,
264 debug!("check_associated_item: {:?}", item_id);
266 let code = ObligationCauseCode::MiscObligation;
267 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
268 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
270 let (mut implied_bounds, self_ty) = match item.container {
271 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
272 ty::ImplContainer(def_id) => {
273 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
278 ty::AssocKind::Const => {
279 let ty = fcx.tcx.type_of(item.def_id);
280 let ty = fcx.normalize_associated_types_in(span, &ty);
281 fcx.register_wf_obligation(ty, span, code.clone());
283 ty::AssocKind::Method => {
284 let sig = fcx.tcx.fn_sig(item.def_id);
285 let sig = fcx.normalize_associated_types_in(span, &sig);
286 let hir_sig = sig_if_method.expect("bad signature for method");
296 check_method_receiver(fcx, hir_sig, &item, self_ty);
298 ty::AssocKind::Type => {
299 if item.defaultness.has_value() {
300 let ty = fcx.tcx.type_of(item.def_id);
301 let ty = fcx.normalize_associated_types_in(span, &ty);
302 fcx.register_wf_obligation(ty, span, code.clone());
305 ty::AssocKind::OpaqueTy => {
306 // Do nothing: opaque types check themselves.
314 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
315 for_id(tcx, item.hir_id, item.span)
318 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
319 let def_id = tcx.hir().local_def_id(id).expect_local();
321 inherited: Inherited::build(tcx, def_id),
324 param_env: tcx.param_env(def_id.to_def_id()),
328 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
330 ItemKind::Struct(..) => Some(AdtKind::Struct),
331 ItemKind::Union(..) => Some(AdtKind::Union),
332 ItemKind::Enum(..) => Some(AdtKind::Enum),
337 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
338 fn check_type_defn<'tcx, F>(
340 item: &hir::Item<'tcx>,
342 mut lookup_fields: F,
344 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
346 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
347 let variants = lookup_fields(fcx);
348 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
349 let packed = fcx.tcx.adt_def(def_id).repr.packed();
351 for variant in &variants {
352 // For DST, or when drop needs to copy things around, all
353 // intermediate types must be sized.
354 let needs_drop_copy = || {
356 let ty = variant.fields.last().unwrap().ty;
357 let ty = fcx.tcx.erase_regions(&ty);
358 if ty.has_local_value() {
361 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
362 // Just treat unresolved type expression as if it needs drop.
365 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
369 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
370 let unsized_len = if all_sized { 0 } else { 1 };
372 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
374 let last = idx == variant.fields.len() - 1;
377 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
378 traits::ObligationCause::new(
382 adt_kind: match item_adt_kind(&item.kind) {
392 // All field types must be well-formed.
393 for field in &variant.fields {
394 fcx.register_wf_obligation(
397 ObligationCauseCode::MiscObligation,
402 check_where_clauses(tcx, fcx, item.span, def_id, None);
404 // No implied bounds in a struct definition.
409 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
410 debug!("check_trait: {:?}", item.hir_id);
412 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
414 let trait_def = tcx.trait_def(trait_def_id);
415 if trait_def.is_marker
416 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
418 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
421 tcx.def_span(*associated_def_id),
423 "marker traits cannot have associated items",
429 for_item(tcx, item).with_fcx(|fcx, _| {
430 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
431 check_associated_type_defaults(fcx, trait_def_id);
437 /// Checks all associated type defaults of trait `trait_def_id`.
439 /// Assuming the defaults are used, check that all predicates (bounds on the
440 /// assoc type and where clauses on the trait) hold.
441 fn check_associated_type_defaults(fcx: &FnCtxt<'_, '_>, trait_def_id: DefId) {
443 let substs = InternalSubsts::identity_for_item(tcx, trait_def_id);
445 // For all assoc. types with defaults, build a map from
446 // `<Self as Trait<...>>::Assoc` to the default type.
448 .associated_items(trait_def_id)
449 .in_definition_order()
451 if item.kind == ty::AssocKind::Type && item.defaultness.has_value() {
452 // `<Self as Trait<...>>::Assoc`
453 let proj = ty::ProjectionTy { substs, item_def_id: item.def_id };
454 let default_ty = tcx.type_of(item.def_id);
455 debug!("assoc. type default mapping: {} -> {}", proj, default_ty);
456 Some((proj, default_ty))
461 .collect::<FxHashMap<_, _>>();
463 /// Replaces projections of associated types with their default types.
465 /// This does a "shallow substitution", meaning that defaults that refer to
466 /// other defaulted assoc. types will still refer to the projection
467 /// afterwards, not to the other default. For example:
471 /// type A: Clone = Vec<Self::B>;
476 /// This will end up replacing the bound `Self::A: Clone` with
477 /// `Vec<Self::B>: Clone`, not with `Vec<u8>: Clone`. If we did a deep
478 /// substitution and ended up with the latter, the trait would be accepted.
479 /// If an `impl` then replaced `B` with something that isn't `Clone`,
480 /// suddenly the default for `A` is no longer valid. The shallow
481 /// substitution forces the trait to add a `B: Clone` bound to be accepted,
482 /// which means that an `impl` can replace any default without breaking
485 /// Note that this isn't needed for soundness: The defaults would still be
486 /// checked in any impl that doesn't override them.
487 struct DefaultNormalizer<'tcx> {
489 map: FxHashMap<ty::ProjectionTy<'tcx>, Ty<'tcx>>,
492 impl<'tcx> ty::fold::TypeFolder<'tcx> for DefaultNormalizer<'tcx> {
493 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
497 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
499 ty::Projection(proj_ty) => {
500 if let Some(default) = self.map.get(&proj_ty) {
503 t.super_fold_with(self)
506 _ => t.super_fold_with(self),
511 // Now take all predicates defined on the trait, replace any mention of
512 // the assoc. types with their default, and prove them.
513 // We only consider predicates that directly mention the assoc. type.
514 let mut norm = DefaultNormalizer { tcx, map };
515 let predicates = fcx.tcx.predicates_of(trait_def_id);
516 for &(orig_pred, span) in predicates.predicates.iter() {
517 let pred = orig_pred.fold_with(&mut norm);
518 if pred != orig_pred {
519 // Mentions one of the defaulted assoc. types
520 debug!("default suitability check: proving predicate: {} -> {}", orig_pred, pred);
521 let pred = fcx.normalize_associated_types_in(span, &pred);
522 let cause = traits::ObligationCause::new(
525 traits::ItemObligation(trait_def_id),
527 let obligation = traits::Obligation::new(cause, fcx.param_env, pred);
529 fcx.register_predicate(obligation);
534 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
535 for_item(tcx, item).with_fcx(|fcx, tcx| {
536 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
537 let sig = fcx.tcx.fn_sig(def_id);
538 let sig = fcx.normalize_associated_types_in(item.span, &sig);
539 let mut implied_bounds = vec![];
540 let hir_sig = match &item.kind {
541 ItemKind::Fn(sig, ..) => sig,
542 _ => bug!("expected `ItemKind::Fn`, found `{:?}`", item.kind),
544 check_fn_or_method(tcx, fcx, item.ident.span, sig, hir_sig, def_id, &mut implied_bounds);
549 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
550 debug!("check_item_type: {:?}", item_id);
552 for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
553 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
554 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
556 let mut forbid_unsized = true;
557 if allow_foreign_ty {
558 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
559 if let ty::Foreign(_) = tail.kind {
560 forbid_unsized = false;
564 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
568 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
569 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
573 // No implied bounds in a const, etc.
580 item: &'tcx hir::Item<'tcx>,
581 ast_self_ty: &hir::Ty<'_>,
582 ast_trait_ref: &Option<hir::TraitRef<'_>>,
584 debug!("check_impl: {:?}", item);
586 for_item(tcx, item).with_fcx(|fcx, tcx| {
587 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
589 match *ast_trait_ref {
590 Some(ref ast_trait_ref) => {
591 // `#[rustc_reservation_impl]` impls are not real impls and
592 // therefore don't need to be WF (the trait's `Self: Trait` predicate
594 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
596 fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
597 let obligations = traits::wf::trait_obligations(
602 ast_trait_ref.path.span,
605 for obligation in obligations {
606 fcx.register_predicate(obligation);
610 let self_ty = fcx.tcx.type_of(item_def_id);
611 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
612 fcx.register_wf_obligation(
615 ObligationCauseCode::MiscObligation,
620 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
622 fcx.impl_implied_bounds(item_def_id, item.span)
626 /// Checks where-clauses and inline bounds that are declared on `def_id`.
627 fn check_where_clauses<'tcx, 'fcx>(
629 fcx: &FnCtxt<'fcx, 'tcx>,
632 return_ty: Option<(Ty<'tcx>, Span)>,
634 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
636 let predicates = fcx.tcx.predicates_of(def_id);
637 let generics = tcx.generics_of(def_id);
639 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
640 GenericParamDefKind::Type { has_default, .. } => {
641 has_default && def.index >= generics.parent_count as u32
646 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
647 // For example, this forbids the declaration:
649 // struct Foo<T = Vec<[u32]>> { .. }
651 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
652 for param in &generics.params {
653 if let GenericParamDefKind::Type { .. } = param.kind {
654 if is_our_default(¶m) {
655 let ty = fcx.tcx.type_of(param.def_id);
656 // Ignore dependent defaults -- that is, where the default of one type
657 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
658 // be sure if it will error or not as user might always specify the other.
659 if !ty.needs_subst() {
660 fcx.register_wf_obligation(
662 fcx.tcx.def_span(param.def_id),
663 ObligationCauseCode::MiscObligation,
670 // Check that trait predicates are WF when params are substituted by their defaults.
671 // We don't want to overly constrain the predicates that may be written but we want to
672 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
673 // Therefore we check if a predicate which contains a single type param
674 // with a concrete default is WF with that default substituted.
675 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
677 // First we build the defaulted substitution.
678 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
680 GenericParamDefKind::Lifetime => {
681 // All regions are identity.
682 fcx.tcx.mk_param_from_def(param)
685 GenericParamDefKind::Type { .. } => {
686 // If the param has a default, ...
687 if is_our_default(param) {
688 let default_ty = fcx.tcx.type_of(param.def_id);
689 // ... and it's not a dependent default, ...
690 if !default_ty.needs_subst() {
691 // ... then substitute it with the default.
692 return default_ty.into();
695 // Mark unwanted params as error.
696 fcx.tcx.types.err.into()
699 GenericParamDefKind::Const => {
700 // FIXME(const_generics:defaults)
701 fcx.tcx.consts.err.into()
706 // Now we build the substituted predicates.
707 let default_obligations = predicates
710 .flat_map(|&(pred, sp)| {
713 params: FxHashSet<u32>,
715 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
716 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
717 if let ty::Param(param) = t.kind {
718 self.params.insert(param.index);
720 t.super_visit_with(self)
723 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
727 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
728 if let ty::ConstKind::Param(param) = c.val {
729 self.params.insert(param.index);
731 c.super_visit_with(self)
734 let mut param_count = CountParams::default();
735 let has_region = pred.visit_with(&mut param_count);
736 let substituted_pred = pred.subst(fcx.tcx, substs);
737 // Don't check non-defaulted params, dependent defaults (including lifetimes)
738 // or preds with multiple params.
739 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
741 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
742 // Avoid duplication of predicates that contain no parameters, for example.
745 Some((substituted_pred, sp))
749 // Convert each of those into an obligation. So if you have
750 // something like `struct Foo<T: Copy = String>`, we would
751 // take that predicate `T: Copy`, substitute to `String: Copy`
752 // (actually that happens in the previous `flat_map` call),
753 // and then try to prove it (in this case, we'll fail).
755 // Note the subtle difference from how we handle `predicates`
756 // below: there, we are not trying to prove those predicates
757 // to be *true* but merely *well-formed*.
758 let pred = fcx.normalize_associated_types_in(sp, &pred);
760 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
761 traits::Obligation::new(cause, fcx.param_env, pred)
764 let mut predicates = predicates.instantiate_identity(fcx.tcx);
766 if let Some((return_ty, span)) = return_ty {
767 let opaque_types = check_opaque_types(tcx, fcx, def_id, span, return_ty);
768 for _ in 0..opaque_types.len() {
769 predicates.spans.push(span);
771 predicates.predicates.extend(opaque_types);
774 let predicates = fcx.normalize_associated_types_in(span, &predicates);
776 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
777 assert_eq!(predicates.predicates.len(), predicates.spans.len());
779 predicates.predicates.iter().zip(predicates.spans.iter()).flat_map(|(p, sp)| {
780 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, *sp)
783 for obligation in wf_obligations.chain(default_obligations) {
784 debug!("next obligation cause: {:?}", obligation.cause);
785 fcx.register_predicate(obligation);
789 fn check_fn_or_method<'fcx, 'tcx>(
791 fcx: &FnCtxt<'fcx, 'tcx>,
793 sig: ty::PolyFnSig<'tcx>,
794 hir_sig: &hir::FnSig<'_>,
796 implied_bounds: &mut Vec<Ty<'tcx>>,
798 let sig = fcx.normalize_associated_types_in(span, &sig);
799 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
801 for (input_ty, span) in sig.inputs().iter().zip(hir_sig.decl.inputs.iter().map(|t| t.span)) {
802 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
804 implied_bounds.extend(sig.inputs());
806 fcx.register_wf_obligation(
808 hir_sig.decl.output.span(),
809 ObligationCauseCode::ReturnType,
812 // FIXME(#25759) return types should not be implied bounds
813 implied_bounds.push(sig.output());
815 check_where_clauses(tcx, fcx, span, def_id, Some((sig.output(), hir_sig.decl.output.span())));
818 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
819 /// laid for "higher-order pattern unification".
820 /// This ensures that inference is tractable.
821 /// In particular, definitions of opaque types can only use other generics as arguments,
822 /// and they cannot repeat an argument. Example:
825 /// type Foo<A, B> = impl Bar<A, B>;
827 /// // Okay -- `Foo` is applied to two distinct, generic types.
828 /// fn a<T, U>() -> Foo<T, U> { .. }
830 /// // Not okay -- `Foo` is applied to `T` twice.
831 /// fn b<T>() -> Foo<T, T> { .. }
833 /// // Not okay -- `Foo` is applied to a non-generic type.
834 /// fn b<T>() -> Foo<T, u32> { .. }
837 fn check_opaque_types<'fcx, 'tcx>(
839 fcx: &FnCtxt<'fcx, 'tcx>,
843 ) -> Vec<ty::Predicate<'tcx>> {
844 trace!("check_opaque_types(ty={:?})", ty);
845 let mut substituted_predicates = Vec::new();
846 ty.fold_with(&mut ty::fold::BottomUpFolder {
849 if let ty::Opaque(def_id, substs) = ty.kind {
850 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
851 let generics = tcx.generics_of(def_id);
852 // Only check named `impl Trait` types defined in this crate.
853 if generics.parent.is_none() && def_id.is_local() {
854 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
855 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
856 trace!("check_opaque_types: may define, generics={:#?}", generics);
857 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
858 for (subst, param) in substs.iter().zip(&generics.params) {
859 match subst.unpack() {
860 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
862 // Prevent `fn foo() -> Foo<u32>` from being defining.
867 "non-defining opaque type use \
871 tcx.def_span(param.def_id),
873 "used non-generic type {} for \
882 ty::subst::GenericArgKind::Lifetime(region) => {
883 let param_span = tcx.def_span(param.def_id);
884 if let ty::ReStatic = region {
888 "non-defining opaque type use \
893 "cannot use static lifetime; use a bound lifetime \
894 instead or remove the lifetime parameter from the \
899 seen.entry(region).or_default().push(param_span);
903 ty::subst::GenericArgKind::Const(ct) => match ct.val {
904 ty::ConstKind::Param(_) => {}
909 "non-defining opaque type use \
913 tcx.def_span(param.def_id),
915 "used non-generic const {} for \
924 } // for (subst, param)
925 for (_, spans) in seen {
930 "non-defining opaque type use \
933 .span_note(spans, "lifetime used multiple times")
937 } // if may_define_opaque_type
939 // Now register the bounds on the parameters of the opaque type
940 // so the parameters given by the function need to fulfill them.
942 // type Foo<T: Bar> = impl Baz + 'static;
943 // fn foo<U>() -> Foo<U> { .. *}
947 // type Foo<T: Bar> = impl Baz + 'static;
948 // fn foo<U: Bar>() -> Foo<U> { .. *}
949 let predicates = tcx.predicates_of(def_id);
950 trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
951 for &(pred, _) in predicates.predicates {
952 let substituted_pred = pred.subst(fcx.tcx, substs);
953 // Avoid duplication of predicates that contain no parameters, for example.
954 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
955 substituted_predicates.push(substituted_pred);
958 } // if is_named_opaque_type
965 substituted_predicates
968 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
969 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
970 of the previous types except `Self`)";
972 fn check_method_receiver<'fcx, 'tcx>(
973 fcx: &FnCtxt<'fcx, 'tcx>,
974 fn_sig: &hir::FnSig<'_>,
975 method: &ty::AssocItem,
978 // Check that the method has a valid receiver type, given the type `Self`.
979 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
981 if !method.method_has_self_argument {
985 let span = fn_sig.decl.inputs[0].span;
987 let sig = fcx.tcx.fn_sig(method.def_id);
988 let sig = fcx.normalize_associated_types_in(span, &sig);
989 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
991 debug!("check_method_receiver: sig={:?}", sig);
993 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
994 let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
996 let receiver_ty = sig.inputs()[0];
998 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
1000 fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
1002 if fcx.tcx.features().arbitrary_self_types {
1003 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1004 // Report error; `arbitrary_self_types` was enabled.
1005 e0307(fcx, span, receiver_ty);
1008 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1009 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1010 // Report error; would have worked with `arbitrary_self_types`.
1012 &fcx.tcx.sess.parse_sess,
1013 sym::arbitrary_self_types,
1016 "`{}` cannot be used as the type of `self` without \
1017 the `arbitrary_self_types` feature",
1021 .help(HELP_FOR_SELF_TYPE)
1024 // Report error; would not have worked with `arbitrary_self_types`.
1025 e0307(fcx, span, receiver_ty);
1031 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1033 fcx.tcx.sess.diagnostic(),
1036 "invalid `self` parameter type: {:?}",
1039 .note("type of `self` must be `Self` or a type that dereferences to it")
1040 .help(HELP_FOR_SELF_TYPE)
1044 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1045 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1046 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1047 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1048 /// `Deref<Target = self_ty>`.
1050 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1051 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1052 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1053 fn receiver_is_valid<'fcx, 'tcx>(
1054 fcx: &FnCtxt<'fcx, 'tcx>,
1056 receiver_ty: Ty<'tcx>,
1058 arbitrary_self_types_enabled: bool,
1060 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1062 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1064 // `self: Self` is always valid.
1065 if can_eq_self(receiver_ty) {
1066 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1072 let mut autoderef = fcx.autoderef(span, receiver_ty);
1074 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1075 if arbitrary_self_types_enabled {
1076 autoderef = autoderef.include_raw_pointers();
1079 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1082 let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
1084 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1086 if let Some((potential_self_ty, _)) = autoderef.next() {
1088 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1089 potential_self_ty, self_ty
1092 if can_eq_self(potential_self_ty) {
1093 autoderef.finalize(fcx);
1095 if let Some(mut err) =
1096 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1103 // Without `feature(arbitrary_self_types)`, we require that each step in the
1104 // deref chain implement `receiver`
1105 if !arbitrary_self_types_enabled
1106 && !receiver_is_implemented(
1108 receiver_trait_def_id,
1117 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1118 // If he receiver already has errors reported due to it, consider it valid to avoid
1119 // unnecessary errors (#58712).
1120 return receiver_ty.references_error();
1124 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1125 if !arbitrary_self_types_enabled
1126 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1134 fn receiver_is_implemented(
1135 fcx: &FnCtxt<'_, 'tcx>,
1136 receiver_trait_def_id: DefId,
1137 cause: ObligationCause<'tcx>,
1138 receiver_ty: Ty<'tcx>,
1140 let trait_ref = ty::TraitRef {
1141 def_id: receiver_trait_def_id,
1142 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1146 traits::Obligation::new(cause, fcx.param_env, trait_ref.without_const().to_predicate());
1148 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1152 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1159 fn check_variances_for_type_defn<'tcx>(
1161 item: &hir::Item<'tcx>,
1162 hir_generics: &hir::Generics<'_>,
1164 let item_def_id = tcx.hir().local_def_id(item.hir_id);
1165 let ty = tcx.type_of(item_def_id);
1166 if tcx.has_error_field(ty) {
1170 let ty_predicates = tcx.predicates_of(item_def_id);
1171 assert_eq!(ty_predicates.parent, None);
1172 let variances = tcx.variances_of(item_def_id);
1174 let mut constrained_parameters: FxHashSet<_> = variances
1177 .filter(|&(_, &variance)| variance != ty::Bivariant)
1178 .map(|(index, _)| Parameter(index as u32))
1181 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1183 for (index, _) in variances.iter().enumerate() {
1184 if constrained_parameters.contains(&Parameter(index as u32)) {
1188 let param = &hir_generics.params[index];
1191 hir::ParamName::Error => {}
1192 _ => report_bivariance(tcx, param.span, param.name.ident().name),
1197 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
1198 let mut err = error_392(tcx, span, param_name);
1200 let suggested_marker_id = tcx.lang_items().phantom_data();
1201 // Help is available only in presence of lang items.
1202 let msg = if let Some(def_id) = suggested_marker_id {
1204 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1206 tcx.def_path_str(def_id),
1209 format!("consider removing `{}` or referring to it in a field", param_name)
1215 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1217 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1218 let empty_env = ty::ParamEnv::empty();
1220 let def_id = fcx.tcx.hir().local_def_id(id);
1221 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p).collect();
1222 // Check elaborated bounds.
1223 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1225 for pred in implied_obligations {
1226 // Match the existing behavior.
1227 if pred.is_global() && !pred.has_late_bound_regions() {
1228 let pred = fcx.normalize_associated_types_in(span, &pred);
1229 let obligation = traits::Obligation::new(
1230 traits::ObligationCause::new(span, id, traits::TrivialBound),
1234 fcx.register_predicate(obligation);
1238 fcx.select_all_obligations_or_error();
1241 pub struct CheckTypeWellFormedVisitor<'tcx> {
1245 impl CheckTypeWellFormedVisitor<'tcx> {
1246 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1247 CheckTypeWellFormedVisitor { tcx }
1251 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1252 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1253 debug!("visit_item: {:?}", i);
1254 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1255 self.tcx.ensure().check_item_well_formed(def_id);
1258 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1259 debug!("visit_trait_item: {:?}", trait_item);
1260 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1261 self.tcx.ensure().check_trait_item_well_formed(def_id);
1264 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1265 debug!("visit_impl_item: {:?}", impl_item);
1266 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1267 self.tcx.ensure().check_impl_item_well_formed(def_id);
1271 ///////////////////////////////////////////////////////////////////////////
1274 struct AdtVariant<'tcx> {
1275 fields: Vec<AdtField<'tcx>>,
1278 struct AdtField<'tcx> {
1283 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1284 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1285 let fields = struct_def
1289 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1290 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1291 let field_ty = self.resolve_vars_if_possible(&field_ty);
1292 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1293 AdtField { ty: field_ty, span: field.span }
1296 AdtVariant { fields }
1299 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1300 enum_def.variants.iter().map(|variant| self.non_enum_variant(&variant.data)).collect()
1303 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1304 match self.tcx.impl_trait_ref(impl_def_id) {
1305 Some(ref trait_ref) => {
1306 // Trait impl: take implied bounds from all types that
1307 // appear in the trait reference.
1308 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1309 trait_ref.substs.types().collect()
1313 // Inherent impl: take implied bounds from the `self` type.
1314 let self_ty = self.tcx.type_of(impl_def_id);
1315 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1322 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) -> DiagnosticBuilder<'_> {
1324 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1325 err.span_label(span, "unused parameter");