1pub mod auto_trait;
6pub(crate) mod coherence;
7pub mod const_evaluatable;
8mod dyn_compatibility;
9pub mod effects;
10mod engine;
11mod fulfill;
12pub mod misc;
13pub mod normalize;
14pub mod outlives_bounds;
15pub mod project;
16pub mod query;
17#[allow(hidden_glob_reexports)]
18mod select;
19mod specialize;
20mod structural_normalize;
21#[allow(hidden_glob_reexports)]
22mod util;
23pub mod vtable;
24pub mod wf;
25
26use std::fmt::Debug;
27use std::ops::ControlFlow;
28
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31pub use rustc_infer::traits::*;
32use rustc_macros::TypeVisitable;
33use rustc_middle::query::Providers;
34use rustc_middle::span_bug;
35use rustc_middle::ty::error::{ExpectedFound, TypeError};
36use rustc_middle::ty::{
37 self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
38 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, Upcast,
39};
40use rustc_span::Span;
41use rustc_span::def_id::DefId;
42use tracing::{debug, instrument};
43
44pub use self::coherence::{
45 InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams,
46 add_placeholder_note, orphan_check_trait_ref, overlapping_inherent_impls,
47 overlapping_trait_impls,
48};
49pub use self::dyn_compatibility::{
50 DynCompatibilityViolation, dyn_compatibility_violations_for_assoc_item,
51 hir_ty_lowering_dyn_compatibility_violations, is_vtable_safe_method,
52};
53pub use self::engine::{ObligationCtxt, TraitEngineExt};
54pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation};
55pub use self::normalize::NormalizeExt;
56pub use self::project::{normalize_inherent_projection, normalize_projection_term};
57pub use self::select::{
58 EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache,
59 SelectionContext,
60};
61pub use self::specialize::specialization_graph::{
62 FutureCompatOverlapError, FutureCompatOverlapErrorKind,
63};
64pub use self::specialize::{
65 OverlapError, specialization_graph, translate_args, translate_args_with_cause,
66};
67pub use self::structural_normalize::StructurallyNormalizeExt;
68pub use self::util::{
69 BoundVarReplacer, PlaceholderReplacer, elaborate, expand_trait_aliases, impl_item_is_final,
70 sizedness_fast_path, supertrait_def_ids, supertraits, transitive_bounds_that_define_assoc_item,
71 upcast_choices, with_replaced_escaping_bound_vars,
72};
73use crate::error_reporting::InferCtxtErrorExt;
74use crate::infer::outlives::env::OutlivesEnvironment;
75use crate::infer::{InferCtxt, TyCtxtInferExt};
76use crate::regions::InferCtxtRegionExt;
77use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
78
79#[derive(Debug, TypeVisitable)]
80pub struct FulfillmentError<'tcx> {
81 pub obligation: PredicateObligation<'tcx>,
82 pub code: FulfillmentErrorCode<'tcx>,
83 pub root_obligation: PredicateObligation<'tcx>,
87}
88
89impl<'tcx> FulfillmentError<'tcx> {
90 pub fn new(
91 obligation: PredicateObligation<'tcx>,
92 code: FulfillmentErrorCode<'tcx>,
93 root_obligation: PredicateObligation<'tcx>,
94 ) -> FulfillmentError<'tcx> {
95 FulfillmentError { obligation, code, root_obligation }
96 }
97
98 pub fn is_true_error(&self) -> bool {
99 match self.code {
100 FulfillmentErrorCode::Select(_)
101 | FulfillmentErrorCode::Project(_)
102 | FulfillmentErrorCode::Subtype(_, _)
103 | FulfillmentErrorCode::ConstEquate(_, _) => true,
104 FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
105 false
106 }
107 }
108 }
109}
110
111#[derive(Clone, TypeVisitable)]
112pub enum FulfillmentErrorCode<'tcx> {
113 Cycle(PredicateObligations<'tcx>),
116 Select(SelectionError<'tcx>),
117 Project(MismatchedProjectionTypes<'tcx>),
118 Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
120 Ambiguity {
121 overflow: Option<bool>,
125 },
126}
127
128impl<'tcx> Debug for FulfillmentErrorCode<'tcx> {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 match *self {
131 FulfillmentErrorCode::Select(ref e) => write!(f, "{e:?}"),
132 FulfillmentErrorCode::Project(ref e) => write!(f, "{e:?}"),
133 FulfillmentErrorCode::Subtype(ref a, ref b) => {
134 write!(f, "CodeSubtypeError({a:?}, {b:?})")
135 }
136 FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
137 write!(f, "CodeConstEquateError({a:?}, {b:?})")
138 }
139 FulfillmentErrorCode::Ambiguity { overflow: None } => write!(f, "Ambiguity"),
140 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
141 write!(f, "Overflow({suggest_increasing_limit})")
142 }
143 FulfillmentErrorCode::Cycle(ref cycle) => write!(f, "Cycle({cycle:?})"),
144 }
145 }
146}
147
148#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
154pub enum SkipLeakCheck {
155 Yes,
156 #[default]
157 No,
158}
159
160impl SkipLeakCheck {
161 fn is_yes(self) -> bool {
162 self == SkipLeakCheck::Yes
163 }
164}
165
166#[derive(Copy, Clone, PartialEq, Eq, Debug)]
168pub enum TraitQueryMode {
169 Standard,
173 Canonical,
177}
178
179#[instrument(level = "debug", skip(cause, param_env))]
181pub fn predicates_for_generics<'tcx>(
182 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
183 param_env: ty::ParamEnv<'tcx>,
184 generic_bounds: ty::InstantiatedPredicates<'tcx>,
185) -> impl Iterator<Item = PredicateObligation<'tcx>> {
186 generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
187 cause: cause(idx, span),
188 recursion_depth: 0,
189 param_env,
190 predicate: clause.as_predicate(),
191 })
192}
193
194pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
200 infcx: &InferCtxt<'tcx>,
201 param_env: ty::ParamEnv<'tcx>,
202 ty: Ty<'tcx>,
203 def_id: DefId,
204) -> bool {
205 let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
206 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
207}
208
209#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
214fn pred_known_to_hold_modulo_regions<'tcx>(
215 infcx: &InferCtxt<'tcx>,
216 param_env: ty::ParamEnv<'tcx>,
217 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
218) -> bool {
219 let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
220
221 let result = infcx.evaluate_obligation_no_overflow(&obligation);
222 debug!(?result);
223
224 if result.must_apply_modulo_regions() {
225 true
226 } else if result.may_apply() && !infcx.next_trait_solver() {
227 let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
232 infcx.probe(|_| {
233 let ocx = ObligationCtxt::new(infcx);
234 ocx.register_obligation(obligation);
235
236 let errors = ocx.evaluate_obligations_error_on_ambiguity();
237 match errors.as_slice() {
238 [] => infcx.resolve_vars_if_possible(goal) == goal,
240
241 errors => {
242 debug!(?errors);
243 false
244 }
245 }
246 })
247 } else {
248 false
249 }
250}
251
252#[instrument(level = "debug", skip(tcx, elaborated_env))]
253fn do_normalize_predicates<'tcx>(
254 tcx: TyCtxt<'tcx>,
255 cause: ObligationCause<'tcx>,
256 elaborated_env: ty::ParamEnv<'tcx>,
257 predicates: Vec<ty::Clause<'tcx>>,
258) -> Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> {
259 let span = cause.span;
260
261 let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
275 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
276 let predicates = ocx.normalize(&cause, elaborated_env, predicates);
277
278 let errors = ocx.evaluate_obligations_error_on_ambiguity();
279 if !errors.is_empty() {
280 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
281 return Err(reported);
282 }
283
284 debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
285
286 let errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
292 if !errors.is_empty() {
293 tcx.dcx().span_delayed_bug(
294 span,
295 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
296 );
297 }
298
299 match infcx.fully_resolve(predicates) {
300 Ok(predicates) => Ok(predicates),
301 Err(fixup_err) => {
302 span_bug!(
312 span,
313 "inference variables in normalized parameter environment: {}",
314 fixup_err
315 );
316 }
317 }
318}
319
320#[instrument(level = "debug", skip(tcx))]
323pub fn normalize_param_env_or_error<'tcx>(
324 tcx: TyCtxt<'tcx>,
325 unnormalized_env: ty::ParamEnv<'tcx>,
326 cause: ObligationCause<'tcx>,
327) -> ty::ParamEnv<'tcx> {
328 let mut predicates: Vec<_> = util::elaborate(
343 tcx,
344 unnormalized_env.caller_bounds().into_iter().map(|predicate| {
345 if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
346 return predicate;
347 }
348
349 struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
350
351 impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
352 fn cx(&self) -> TyCtxt<'tcx> {
353 self.0
354 }
355
356 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
357 if c.has_escaping_bound_vars() {
361 return ty::Const::new_misc_error(self.0);
362 }
363
364 if let ty::ConstKind::Unevaluated(uv) = c.kind()
369 && self.0.def_kind(uv.def) == DefKind::AnonConst
370 {
371 let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
372 let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
373 assert!(!c.has_infer() && !c.has_placeholders());
376 return c;
377 }
378
379 c
380 }
381 }
382
383 predicate.fold_with(&mut ConstNormalizer(tcx))
411 }),
412 )
413 .collect();
414
415 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
416
417 let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
418 if !elaborated_env.has_aliases() {
419 return elaborated_env;
420 }
421
422 let outlives_predicates: Vec<_> = predicates
441 .extract_if(.., |predicate| {
442 matches!(predicate.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
443 })
444 .collect();
445
446 debug!(
447 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
448 predicates, outlives_predicates
449 );
450 let Ok(non_outlives_predicates) =
451 do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates)
452 else {
453 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
455 return elaborated_env;
456 };
457
458 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
459
460 let outlives_env = non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
464 let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
465 let Ok(outlives_predicates) =
466 do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates)
467 else {
468 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
470 return elaborated_env;
471 };
472 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
473
474 let mut predicates = non_outlives_predicates;
475 predicates.extend(outlives_predicates);
476 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
477 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
478}
479
480#[instrument(level = "debug", skip(tcx))]
489pub fn deeply_normalize_param_env_ignoring_regions<'tcx>(
490 tcx: TyCtxt<'tcx>,
491 unnormalized_env: ty::ParamEnv<'tcx>,
492 cause: ObligationCause<'tcx>,
493) -> ty::ParamEnv<'tcx> {
494 let predicates: Vec<_> =
495 util::elaborate(tcx, unnormalized_env.caller_bounds().into_iter()).collect();
496
497 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
498
499 let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
500 if !elaborated_env.has_aliases() {
501 return elaborated_env;
502 }
503
504 let span = cause.span;
505 let infcx = tcx
506 .infer_ctxt()
507 .with_next_trait_solver(true)
508 .ignoring_regions()
509 .build(TypingMode::non_body_analysis());
510 let predicates = match crate::solve::deeply_normalize::<_, FulfillmentError<'tcx>>(
511 infcx.at(&cause, elaborated_env),
512 predicates,
513 ) {
514 Ok(predicates) => predicates,
515 Err(errors) => {
516 infcx.err_ctxt().report_fulfillment_errors(errors);
517 debug!("normalize_param_env_or_error: errored resolving predicates");
519 return elaborated_env;
520 }
521 };
522
523 debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
524 let _errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
528
529 let predicates = match infcx.fully_resolve(predicates) {
530 Ok(predicates) => predicates,
531 Err(fixup_err) => {
532 span_bug!(
533 span,
534 "inference variables in normalized parameter environment: {}",
535 fixup_err
536 )
537 }
538 };
539 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
540 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
541}
542
543#[derive(Debug)]
544pub enum EvaluateConstErr {
545 HasGenericsOrInfers,
549 InvalidConstParamTy(ErrorGuaranteed),
553 EvaluationFailure(ErrorGuaranteed),
556}
557
558pub fn evaluate_const<'tcx>(
568 infcx: &InferCtxt<'tcx>,
569 ct: ty::Const<'tcx>,
570 param_env: ty::ParamEnv<'tcx>,
571) -> ty::Const<'tcx> {
572 match try_evaluate_const(infcx, ct, param_env) {
573 Ok(ct) => ct,
574 Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
575 ty::Const::new_error(infcx.tcx, e)
576 }
577 Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
578 }
579}
580
581#[instrument(level = "debug", skip(infcx), ret)]
590pub fn try_evaluate_const<'tcx>(
591 infcx: &InferCtxt<'tcx>,
592 ct: ty::Const<'tcx>,
593 param_env: ty::ParamEnv<'tcx>,
594) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
595 let tcx = infcx.tcx;
596 let ct = infcx.resolve_vars_if_possible(ct);
597 debug!(?ct);
598
599 match ct.kind() {
600 ty::ConstKind::Value(..) => Ok(ct),
601 ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
602 ty::ConstKind::Param(_)
603 | ty::ConstKind::Infer(_)
604 | ty::ConstKind::Bound(_, _)
605 | ty::ConstKind::Placeholder(_)
606 | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
607 ty::ConstKind::Unevaluated(uv) => {
608 let opt_anon_const_kind =
609 (tcx.def_kind(uv.def) == DefKind::AnonConst).then(|| tcx.anon_const_kind(uv.def));
610
611 let (args, typing_env) = match opt_anon_const_kind {
623 Some(ty::AnonConstKind::GCE) => {
627 if uv.has_non_region_infer() || uv.has_non_region_param() {
628 match tcx.thir_abstract_const(uv.def) {
632 Ok(Some(ct)) => {
633 let ct = tcx.expand_abstract_consts(ct.instantiate(tcx, uv.args));
634 if let Err(e) = ct.error_reported() {
635 return Err(EvaluateConstErr::EvaluationFailure(e));
636 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
637 return Err(EvaluateConstErr::HasGenericsOrInfers);
640 } else {
641 let args =
642 replace_param_and_infer_args_with_placeholder(tcx, uv.args);
643 let typing_env = infcx
644 .typing_env(tcx.erase_and_anonymize_regions(param_env))
645 .with_post_analysis_normalized(tcx);
646 (args, typing_env)
647 }
648 }
649 Err(_) | Ok(None) => {
650 let args = GenericArgs::identity_for_item(tcx, uv.def);
651 let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
652 (args, typing_env)
653 }
654 }
655 } else {
656 let typing_env = infcx
657 .typing_env(tcx.erase_and_anonymize_regions(param_env))
658 .with_post_analysis_normalized(tcx);
659 (uv.args, typing_env)
660 }
661 }
662 Some(ty::AnonConstKind::RepeatExprCount) => {
663 if uv.has_non_region_infer() {
664 tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
673 }
674
675 let args = GenericArgs::identity_for_item(tcx, uv.def);
680 let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
681
682 (args, typing_env)
683 }
684 Some(ty::AnonConstKind::MCG) | Some(ty::AnonConstKind::NonTypeSystem) | None => {
685 if uv.args.has_non_region_param() || uv.args.has_non_region_infer() {
698 return Err(EvaluateConstErr::HasGenericsOrInfers);
699 }
700
701 let typing_env = ty::TypingEnv::fully_monomorphized();
704
705 (uv.args, typing_env)
706 }
707 };
708
709 let uv = ty::UnevaluatedConst::new(uv.def, args);
710 let erased_uv = tcx.erase_and_anonymize_regions(uv);
711
712 use rustc_middle::mir::interpret::ErrorHandled;
713 match tcx.const_eval_resolve_for_typeck(typing_env, erased_uv, tcx.def_span(uv.def)) {
716 Ok(Ok(val)) => Ok(ty::Const::new_value(
717 tcx,
718 val,
719 tcx.type_of(uv.def).instantiate(tcx, uv.args),
720 )),
721 Ok(Err(_)) => {
722 let e = tcx.dcx().delayed_bug(
723 "Type system constant with non valtree'able type evaluated but no error emitted",
724 );
725 Err(EvaluateConstErr::InvalidConstParamTy(e))
726 }
727 Err(ErrorHandled::Reported(info, _)) => {
728 Err(EvaluateConstErr::EvaluationFailure(info.into()))
729 }
730 Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
731 }
732 }
733 }
734}
735
736fn replace_param_and_infer_args_with_placeholder<'tcx>(
740 tcx: TyCtxt<'tcx>,
741 args: GenericArgsRef<'tcx>,
742) -> GenericArgsRef<'tcx> {
743 struct ReplaceParamAndInferWithPlaceholder<'tcx> {
744 tcx: TyCtxt<'tcx>,
745 idx: ty::BoundVar,
746 }
747
748 impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
749 fn cx(&self) -> TyCtxt<'tcx> {
750 self.tcx
751 }
752
753 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
754 if let ty::Infer(_) = t.kind() {
755 let idx = self.idx;
756 self.idx += 1;
757 Ty::new_placeholder(
758 self.tcx,
759 ty::PlaceholderType::new(
760 ty::UniverseIndex::ROOT,
761 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
762 ),
763 )
764 } else {
765 t.super_fold_with(self)
766 }
767 }
768
769 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
770 if let ty::ConstKind::Infer(_) = c.kind() {
771 let idx = self.idx;
772 self.idx += 1;
773 ty::Const::new_placeholder(
774 self.tcx,
775 ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst { var: idx }),
776 )
777 } else {
778 c.super_fold_with(self)
779 }
780 }
781 }
782
783 args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
784}
785
786pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause<'tcx>>) -> bool {
791 debug!("impossible_predicates(predicates={:?})", predicates);
792 let (infcx, param_env) = tcx
793 .infer_ctxt()
794 .with_next_trait_solver(true)
795 .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
796
797 let ocx = ObligationCtxt::new(&infcx);
798 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
799 for predicate in predicates {
800 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
801 ocx.register_obligation(obligation);
802 }
803
804 let true_errors = ocx.try_evaluate_obligations();
811 if !true_errors.is_empty() {
812 return true;
813 }
814
815 false
816}
817
818fn instantiate_and_check_impossible_predicates<'tcx>(
819 tcx: TyCtxt<'tcx>,
820 key: (DefId, GenericArgsRef<'tcx>),
821) -> bool {
822 debug!("instantiate_and_check_impossible_predicates(key={:?})", key);
823
824 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
825
826 if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
829 let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
830 predicates.push(trait_ref.upcast(tcx));
831 }
832
833 predicates.retain(|predicate| !predicate.has_param());
834 let result = impossible_predicates(tcx, predicates);
835
836 debug!("instantiate_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
837 result
838}
839
840fn is_impossible_associated_item(
845 tcx: TyCtxt<'_>,
846 (impl_def_id, trait_item_def_id): (DefId, DefId),
847) -> bool {
848 struct ReferencesOnlyParentGenerics<'tcx> {
849 tcx: TyCtxt<'tcx>,
850 generics: &'tcx ty::Generics,
851 trait_item_def_id: DefId,
852 }
853 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
854 type Result = ControlFlow<()>;
855 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
856 if let ty::Param(param) = *t.kind()
858 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
859 && self.tcx.parent(param_def_id) == self.trait_item_def_id
860 {
861 return ControlFlow::Break(());
862 }
863 t.super_visit_with(self)
864 }
865 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
866 if let ty::ReEarlyParam(param) = r.kind()
867 && let param_def_id = self.generics.region_param(param, self.tcx).def_id
868 && self.tcx.parent(param_def_id) == self.trait_item_def_id
869 {
870 return ControlFlow::Break(());
871 }
872 ControlFlow::Continue(())
873 }
874 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
875 if let ty::ConstKind::Param(param) = ct.kind()
876 && let param_def_id = self.generics.const_param(param, self.tcx).def_id
877 && self.tcx.parent(param_def_id) == self.trait_item_def_id
878 {
879 return ControlFlow::Break(());
880 }
881 ct.super_visit_with(self)
882 }
883 }
884
885 let generics = tcx.generics_of(trait_item_def_id);
886 let predicates = tcx.predicates_of(trait_item_def_id);
887
888 let infcx = tcx
893 .infer_ctxt()
894 .ignoring_regions()
895 .with_next_trait_solver(true)
896 .build(TypingMode::Coherence);
897 let param_env = ty::ParamEnv::empty();
898 let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
899
900 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args);
901
902 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
903 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
904 pred.visit_with(&mut visitor).is_continue().then(|| {
905 Obligation::new(
906 tcx,
907 ObligationCause::dummy_with_span(*span),
908 param_env,
909 ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args),
910 )
911 })
912 });
913
914 let ocx = ObligationCtxt::new(&infcx);
915 ocx.register_obligations(predicates_for_trait);
916 !ocx.try_evaluate_obligations().is_empty()
917}
918
919pub fn provide(providers: &mut Providers) {
920 dyn_compatibility::provide(providers);
921 vtable::provide(providers);
922 *providers = Providers {
923 specialization_graph_of: specialize::specialization_graph_provider,
924 specializes: specialize::specializes,
925 specialization_enabled_in: specialize::specialization_enabled_in,
926 instantiate_and_check_impossible_predicates,
927 is_impossible_associated_item,
928 ..*providers
929 };
930}