- 
                Notifications
    You must be signed in to change notification settings 
- Fork 13.9k
Warn on inductive cycle in coherence leading to impls being considered not overlapping #114023
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
            bors
  merged 5 commits into
  rust-lang:master
from
compiler-errors:coinductive-cycle-lint
  
      
      
   
  Aug 15, 2023 
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      2ae4bed
              
                more span info
              
              
                compiler-errors 56f5704
              
                Implement lint against coinductive impl overlap
              
              
                compiler-errors d2a14df
              
                nits
              
              
                compiler-errors ca49a37
              
                Reuse the selection context, compute failing obligations first in amb…
              
              
                compiler-errors 0e20155
              
                more nits
              
              
                compiler-errors File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -7,7 +7,7 @@ | |
| use crate::infer::outlives::env::OutlivesEnvironment; | ||
| use crate::infer::InferOk; | ||
| use crate::traits::outlives_bounds::InferCtxtExt as _; | ||
| use crate::traits::select::IntercrateAmbiguityCause; | ||
| use crate::traits::select::{IntercrateAmbiguityCause, TreatInductiveCycleAs}; | ||
| use crate::traits::util::impl_subject_and_oblig; | ||
| use crate::traits::SkipLeakCheck; | ||
| use crate::traits::{ | ||
|  | @@ -24,6 +24,7 @@ use rustc_middle::traits::DefiningAnchor; | |
| use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; | ||
| use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; | ||
| use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor}; | ||
| use rustc_session::lint::builtin::COINDUCTIVE_OVERLAP_IN_COHERENCE; | ||
| use rustc_span::symbol::sym; | ||
| use rustc_span::DUMMY_SP; | ||
| use std::fmt::Debug; | ||
|  | @@ -151,14 +152,16 @@ fn with_fresh_ty_vars<'cx, 'tcx>( | |
| .predicates_of(impl_def_id) | ||
| .instantiate(tcx, impl_args) | ||
| .iter() | ||
| .map(|(c, _)| c.as_predicate()) | ||
| .map(|(c, s)| (c.as_predicate(), s)) | ||
| .collect(), | ||
| }; | ||
|  | ||
| let InferOk { value: mut header, obligations } = | ||
| selcx.infcx.at(&ObligationCause::dummy(), param_env).normalize(header); | ||
| let InferOk { value: mut header, obligations } = selcx | ||
| .infcx | ||
| .at(&ObligationCause::dummy_with_span(tcx.def_span(impl_def_id)), param_env) | ||
| .normalize(header); | ||
|  | ||
| header.predicates.extend(obligations.into_iter().map(|o| o.predicate)); | ||
| header.predicates.extend(obligations.into_iter().map(|o| (o.predicate, o.cause.span))); | ||
| header | ||
| } | ||
|  | ||
|  | @@ -207,16 +210,76 @@ fn overlap<'tcx>( | |
| let equate_obligations = equate_impl_headers(selcx.infcx, &impl1_header, &impl2_header)?; | ||
| debug!("overlap: unification check succeeded"); | ||
|  | ||
| if overlap_mode.use_implicit_negative() | ||
| && impl_intersection_has_impossible_obligation( | ||
| selcx, | ||
| param_env, | ||
| &impl1_header, | ||
| impl2_header, | ||
| equate_obligations, | ||
| ) | ||
| { | ||
| return None; | ||
| if overlap_mode.use_implicit_negative() { | ||
| for mode in [TreatInductiveCycleAs::Ambig, TreatInductiveCycleAs::Recur] { | ||
| if let Some(failing_obligation) = selcx.with_treat_inductive_cycle_as(mode, |selcx| { | ||
|          | ||
| impl_intersection_has_impossible_obligation( | ||
| selcx, | ||
| param_env, | ||
| &impl1_header, | ||
| &impl2_header, | ||
| &equate_obligations, | ||
| ) | ||
| }) { | ||
| if matches!(mode, TreatInductiveCycleAs::Recur) { | ||
| let first_local_impl = impl1_header | ||
| .impl_def_id | ||
| .as_local() | ||
| .or(impl2_header.impl_def_id.as_local()) | ||
| .expect("expected one of the impls to be local"); | ||
| infcx.tcx.struct_span_lint_hir( | ||
| COINDUCTIVE_OVERLAP_IN_COHERENCE, | ||
| infcx.tcx.local_def_id_to_hir_id(first_local_impl), | ||
| infcx.tcx.def_span(first_local_impl), | ||
| format!( | ||
| "implementations {} will conflict in the future", | ||
| match impl1_header.trait_ref { | ||
| Some(trait_ref) => { | ||
| let trait_ref = infcx.resolve_vars_if_possible(trait_ref); | ||
| format!( | ||
| "of `{}` for `{}`", | ||
| trait_ref.print_only_trait_path(), | ||
| trait_ref.self_ty() | ||
| ) | ||
| } | ||
| None => format!( | ||
| "for `{}`", | ||
| infcx.resolve_vars_if_possible(impl1_header.self_ty) | ||
| ), | ||
| }, | ||
| ), | ||
| |lint| { | ||
| lint.note( | ||
| "impls that are not considered to overlap may be considered to \ | ||
| overlap in the future", | ||
| ) | ||
| .span_label( | ||
| infcx.tcx.def_span(impl1_header.impl_def_id), | ||
| "the first impl is here", | ||
| ) | ||
| .span_label( | ||
| infcx.tcx.def_span(impl2_header.impl_def_id), | ||
| "the second impl is here", | ||
| ); | ||
| if !failing_obligation.cause.span.is_dummy() { | ||
| lint.span_label( | ||
| failing_obligation.cause.span, | ||
| format!( | ||
| "`{}` may be considered to hold in future releases, \ | ||
| causing the impls to overlap", | ||
| infcx | ||
| .resolve_vars_if_possible(failing_obligation.predicate) | ||
| ), | ||
| ); | ||
| } | ||
| lint | ||
| }, | ||
| ); | ||
| } | ||
|  | ||
| return None; | ||
| } | ||
| } | ||
| } | ||
|  | ||
| // We toggle the `leak_check` by using `skip_leak_check` when constructing the | ||
|  | @@ -284,40 +347,30 @@ fn impl_intersection_has_impossible_obligation<'cx, 'tcx>( | |
| selcx: &mut SelectionContext<'cx, 'tcx>, | ||
| param_env: ty::ParamEnv<'tcx>, | ||
| impl1_header: &ty::ImplHeader<'tcx>, | ||
| impl2_header: ty::ImplHeader<'tcx>, | ||
| obligations: PredicateObligations<'tcx>, | ||
| ) -> bool { | ||
| impl2_header: &ty::ImplHeader<'tcx>, | ||
| obligations: &PredicateObligations<'tcx>, | ||
| ) -> Option<PredicateObligation<'tcx>> { | ||
| let infcx = selcx.infcx; | ||
|  | ||
| let obligation_guaranteed_to_fail = move |obligation: &PredicateObligation<'tcx>| { | ||
| if infcx.next_trait_solver() { | ||
| infcx.evaluate_obligation(obligation).map_or(false, |result| !result.may_apply()) | ||
| } else { | ||
| // We use `evaluate_root_obligation` to correctly track | ||
| // intercrate ambiguity clauses. We do not need this in the | ||
| // new solver. | ||
| selcx.evaluate_root_obligation(obligation).map_or( | ||
| false, // Overflow has occurred, and treat the obligation as possibly holding. | ||
| |result| !result.may_apply(), | ||
| ) | ||
| } | ||
| }; | ||
|  | ||
| let opt_failing_obligation = [&impl1_header.predicates, &impl2_header.predicates] | ||
| [&impl1_header.predicates, &impl2_header.predicates] | ||
| .into_iter() | ||
| .flatten() | ||
| .map(|&predicate| { | ||
| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate) | ||
| .map(|&(predicate, span)| { | ||
| Obligation::new(infcx.tcx, ObligationCause::dummy_with_span(span), param_env, predicate) | ||
| }) | ||
| .chain(obligations.into_iter().cloned()) | ||
| .find(|obligation: &PredicateObligation<'tcx>| { | ||
| if infcx.next_trait_solver() { | ||
| infcx.evaluate_obligation(obligation).map_or(false, |result| !result.may_apply()) | ||
| } else { | ||
| // We use `evaluate_root_obligation` to correctly track intercrate | ||
| // ambiguity clauses. We cannot use this in the new solver. | ||
| selcx.evaluate_root_obligation(obligation).map_or( | ||
| false, // Overflow has occurred, and treat the obligation as possibly holding. | ||
| |result| !result.may_apply(), | ||
| ) | ||
| } | ||
| }) | ||
| .chain(obligations) | ||
| .find(obligation_guaranteed_to_fail); | ||
|  | ||
| if let Some(failing_obligation) = opt_failing_obligation { | ||
| debug!("overlap: obligation unsatisfiable {:?}", failing_obligation); | ||
| true | ||
| } else { | ||
| false | ||
| } | ||
| } | ||
|  | ||
| /// Check if both impls can be satisfied by a common type by considering whether | ||
|  | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            35 changes: 35 additions & 0 deletions
          
          35 
        
  tests/ui/coherence/warn-when-cycle-is-error-in-coherence.rs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| #![deny(coinductive_overlap_in_coherence)] | ||
|  | ||
| use std::borrow::Borrow; | ||
| use std::cmp::Ordering; | ||
| use std::marker::PhantomData; | ||
|  | ||
| #[derive(PartialEq, Default)] | ||
| pub(crate) struct Interval<T>(PhantomData<T>); | ||
|  | ||
| // This impl overlaps with the `derive` unless we reject the nested | ||
| // `Interval<?1>: PartialOrd<Interval<?1>>` candidate which results | ||
| // in a - currently inductive - cycle. | ||
| impl<T, Q> PartialEq<Q> for Interval<T> | ||
| //~^ ERROR implementations of `PartialEq<Interval<_>>` for `Interval<_>` will conflict in the future | ||
| //~| WARN this was previously accepted by the compiler but is being phased out | ||
| where | ||
| T: Borrow<Q>, | ||
| Q: ?Sized + PartialOrd, | ||
| { | ||
| fn eq(&self, _: &Q) -> bool { | ||
| true | ||
| } | ||
| } | ||
|  | ||
| impl<T, Q> PartialOrd<Q> for Interval<T> | ||
| where | ||
| T: Borrow<Q>, | ||
| Q: ?Sized + PartialOrd, | ||
| { | ||
| fn partial_cmp(&self, _: &Q) -> Option<Ordering> { | ||
| None | ||
| } | ||
| } | ||
|  | ||
| fn main() {} | 
        
          
          
            23 changes: 23 additions & 0 deletions
          
          23 
        
  tests/ui/coherence/warn-when-cycle-is-error-in-coherence.stderr
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| error: implementations of `PartialEq<Interval<_>>` for `Interval<_>` will conflict in the future | ||
| --> $DIR/warn-when-cycle-is-error-in-coherence.rs:13:1 | ||
| | | ||
| LL | #[derive(PartialEq, Default)] | ||
| | --------- the second impl is here | ||
| ... | ||
| LL | impl<T, Q> PartialEq<Q> for Interval<T> | ||
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the first impl is here | ||
| ... | ||
| LL | Q: ?Sized + PartialOrd, | ||
| | ---------- `Interval<_>: PartialOrd` may be considered to hold in future releases, causing the impls to overlap | ||
| | | ||
| = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! | ||
| = note: for more information, see issue #114040 <https://github.com/rust-lang/rust/issues/114040> | ||
| = note: impls that are not considered to overlap may be considered to overlap in the future | ||
| note: the lint level is defined here | ||
| --> $DIR/warn-when-cycle-is-error-in-coherence.rs:1:9 | ||
| | | ||
| LL | #![deny(coinductive_overlap_in_coherence)] | ||
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
|  | ||
| error: aborting due to previous error | ||
|  | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.