Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7a89b05

Browse files
authoredNov 10, 2022
Rollup merge of #104206 - compiler-errors:ocx-more-2, r=lcnr
Remove `save_and_restore_in_snapshot_flag`, use `ObligationCtxt` more r? `@lcnr`
2 parents f1d08bc + 63217e0 commit 7a89b05

File tree

4 files changed

+128
-188
lines changed

4 files changed

+128
-188
lines changed
 

‎compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryRespons
1818
use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
1919
use rustc_infer::infer::{InferOk, InferResult};
2020
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
21+
use rustc_middle::ty::error::TypeError;
2122
use rustc_middle::ty::fold::TypeFoldable;
2223
use rustc_middle::ty::visit::TypeVisitable;
2324
use rustc_middle::ty::{
@@ -32,9 +33,7 @@ use rustc_span::symbol::{kw, sym, Ident};
3233
use rustc_span::{Span, DUMMY_SP};
3334
use rustc_trait_selection::infer::InferCtxtExt as _;
3435
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
35-
use rustc_trait_selection::traits::{
36-
self, ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt,
37-
};
36+
use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, ObligationCtxt};
3837

3938
use std::collections::hash_map::Entry;
4039
use std::slice;
@@ -766,34 +765,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
766765

767766
let expect_args = self
768767
.fudge_inference_if_ok(|| {
768+
let ocx = ObligationCtxt::new_in_snapshot(self);
769+
769770
// Attempt to apply a subtyping relationship between the formal
770771
// return type (likely containing type variables if the function
771772
// is polymorphic) and the expected return type.
772773
// No argument expectations are produced if unification fails.
773774
let origin = self.misc(call_span);
774-
let ures = self.at(&origin, self.param_env).sup(ret_ty, formal_ret);
775-
776-
// FIXME(#27336) can't use ? here, Try::from_error doesn't default
777-
// to identity so the resulting type is not constrained.
778-
match ures {
779-
Ok(ok) => {
780-
// Process any obligations locally as much as
781-
// we can. We don't care if some things turn
782-
// out unconstrained or ambiguous, as we're
783-
// just trying to get hints here.
784-
let errors = self.save_and_restore_in_snapshot_flag(|_| {
785-
let mut fulfill = <dyn TraitEngine<'_>>::new(self.tcx);
786-
for obligation in ok.obligations {
787-
fulfill.register_predicate_obligation(self, obligation);
788-
}
789-
fulfill.select_where_possible(self)
790-
});
791-
792-
if !errors.is_empty() {
793-
return Err(());
794-
}
795-
}
796-
Err(_) => return Err(()),
775+
ocx.sup(&origin, self.param_env, ret_ty, formal_ret)?;
776+
if !ocx.select_where_possible().is_empty() {
777+
return Err(TypeError::Mismatch);
797778
}
798779

799780
// Record all the argument types, with the substitutions

‎compiler/rustc_infer/src/infer/mod.rs

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -778,32 +778,6 @@ impl<'tcx> InferCtxt<'tcx> {
778778
}
779779
}
780780

781-
/// Clear the "currently in a snapshot" flag, invoke the closure,
782-
/// then restore the flag to its original value. This flag is a
783-
/// debugging measure designed to detect cases where we start a
784-
/// snapshot, create type variables, and register obligations
785-
/// which may involve those type variables in the fulfillment cx,
786-
/// potentially leaving "dangling type variables" behind.
787-
/// In such cases, an assertion will fail when attempting to
788-
/// register obligations, within a snapshot. Very useful, much
789-
/// better than grovelling through megabytes of `RUSTC_LOG` output.
790-
///
791-
/// HOWEVER, in some cases the flag is unhelpful. In particular, we
792-
/// sometimes create a "mini-fulfilment-cx" in which we enroll
793-
/// obligations. As long as this fulfillment cx is fully drained
794-
/// before we return, this is not a problem, as there won't be any
795-
/// escaping obligations in the main cx. In those cases, you can
796-
/// use this function.
797-
pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
798-
where
799-
F: FnOnce(&Self) -> R,
800-
{
801-
let flag = self.in_snapshot.replace(false);
802-
let result = func(self);
803-
self.in_snapshot.set(flag);
804-
result
805-
}
806-
807781
fn start_snapshot(&self) -> CombinedSnapshot<'tcx> {
808782
debug!("start_snapshot()");
809783

‎compiler/rustc_trait_selection/src/traits/specialize/mod.rs

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@
1010
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
1111
1212
pub mod specialization_graph;
13+
use rustc_infer::traits::{TraitEngine, TraitEngineExt as _};
1314
use specialization_graph::GraphExt;
1415

1516
use crate::errors::NegativePositiveConflict;
1617
use crate::infer::{InferCtxt, InferOk, TyCtxtInferExt};
18+
use crate::traits::engine::TraitEngineExt as _;
1719
use crate::traits::select::IntercrateAmbiguityCause;
1820
use crate::traits::{self, coherence, FutureCompatOverlapErrorKind, ObligationCause};
1921
use rustc_data_structures::fx::FxIndexSet;
@@ -200,36 +202,32 @@ fn fulfill_implication<'tcx>(
200202
return Err(());
201203
};
202204

205+
// Needs to be `in_snapshot` because this function is used to rebase
206+
// substitutions, which may happen inside of a select within a probe.
207+
let mut engine = <dyn TraitEngine<'tcx>>::new_in_snapshot(infcx.tcx);
203208
// attempt to prove all of the predicates for impl2 given those for impl1
204209
// (which are packed up in penv)
210+
engine.register_predicate_obligations(infcx, obligations.chain(more_obligations));
205211

206-
infcx.save_and_restore_in_snapshot_flag(|infcx| {
207-
let errors = traits::fully_solve_obligations(&infcx, obligations.chain(more_obligations));
208-
match &errors[..] {
209-
[] => {
210-
debug!(
211-
"fulfill_implication: an impl for {:?} specializes {:?}",
212-
source_trait, target_trait
213-
);
212+
let errors = engine.select_all_or_error(infcx);
213+
if !errors.is_empty() {
214+
// no dice!
215+
debug!(
216+
"fulfill_implication: for impls on {:?} and {:?}, \
217+
could not fulfill: {:?} given {:?}",
218+
source_trait,
219+
target_trait,
220+
errors,
221+
param_env.caller_bounds()
222+
);
223+
return Err(());
224+
}
214225

215-
// Now resolve the *substitution* we built for the target earlier, replacing
216-
// the inference variables inside with whatever we got from fulfillment.
217-
Ok(infcx.resolve_vars_if_possible(target_substs))
218-
}
219-
errors => {
220-
// no dice!
221-
debug!(
222-
"fulfill_implication: for impls on {:?} and {:?}, \
223-
could not fulfill: {:?} given {:?}",
224-
source_trait,
225-
target_trait,
226-
errors,
227-
param_env.caller_bounds()
228-
);
229-
Err(())
230-
}
231-
}
232-
})
226+
debug!("fulfill_implication: an impl for {:?} specializes {:?}", source_trait, target_trait);
227+
228+
// Now resolve the *substitution* we built for the target earlier, replacing
229+
// the inference variables inside with whatever we got from fulfillment.
230+
Ok(infcx.resolve_vars_if_possible(target_substs))
233231
}
234232

235233
// Query provider for `specialization_graph_of`.

‎compiler/rustc_traits/src/dropck_outlives.rs

Lines changed: 97 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,18 @@ use rustc_data_structures::fx::FxHashSet;
22
use rustc_hir::def_id::DefId;
33
use rustc_infer::infer::canonical::{Canonical, QueryResponse};
44
use rustc_infer::infer::TyCtxtInferExt;
5-
use rustc_infer::traits::TraitEngineExt as _;
65
use rustc_middle::ty::query::Providers;
76
use rustc_middle::ty::InternalSubsts;
87
use rustc_middle::ty::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt};
98
use rustc_span::source_map::{Span, DUMMY_SP};
9+
use rustc_trait_selection::infer::InferCtxtBuilderExt;
1010
use rustc_trait_selection::traits::query::dropck_outlives::trivial_dropck_outlives;
1111
use rustc_trait_selection::traits::query::dropck_outlives::{
1212
DropckConstraint, DropckOutlivesResult,
1313
};
1414
use rustc_trait_selection::traits::query::normalize::AtExt;
1515
use rustc_trait_selection::traits::query::{CanonicalTyGoal, NoSolution};
16-
use rustc_trait_selection::traits::{
17-
Normalized, ObligationCause, TraitEngine, TraitEngineExt as _,
18-
};
16+
use rustc_trait_selection::traits::{Normalized, ObligationCause};
1917

2018
pub(crate) fn provide(p: &mut Providers) {
2119
*p = Providers { dropck_outlives, adt_dtorck_constraint, ..*p };
@@ -27,120 +25,109 @@ fn dropck_outlives<'tcx>(
2725
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
2826
debug!("dropck_outlives(goal={:#?})", canonical_goal);
2927

30-
let (ref infcx, goal, canonical_inference_vars) =
31-
tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &canonical_goal);
32-
let tcx = infcx.tcx;
33-
let ParamEnvAnd { param_env, value: for_ty } = goal;
34-
35-
let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
36-
37-
// A stack of types left to process. Each round, we pop
38-
// something from the stack and invoke
39-
// `dtorck_constraint_for_ty`. This may produce new types that
40-
// have to be pushed on the stack. This continues until we have explored
41-
// all the reachable types from the type `for_ty`.
42-
//
43-
// Example: Imagine that we have the following code:
44-
//
45-
// ```rust
46-
// struct A {
47-
// value: B,
48-
// children: Vec<A>,
49-
// }
50-
//
51-
// struct B {
52-
// value: u32
53-
// }
54-
//
55-
// fn f() {
56-
// let a: A = ...;
57-
// ..
58-
// } // here, `a` is dropped
59-
// ```
60-
//
61-
// at the point where `a` is dropped, we need to figure out
62-
// which types inside of `a` contain region data that may be
63-
// accessed by any destructors in `a`. We begin by pushing `A`
64-
// onto the stack, as that is the type of `a`. We will then
65-
// invoke `dtorck_constraint_for_ty` which will expand `A`
66-
// into the types of its fields `(B, Vec<A>)`. These will get
67-
// pushed onto the stack. Eventually, expanding `Vec<A>` will
68-
// lead to us trying to push `A` a second time -- to prevent
69-
// infinite recursion, we notice that `A` was already pushed
70-
// once and stop.
71-
let mut ty_stack = vec![(for_ty, 0)];
72-
73-
// Set used to detect infinite recursion.
74-
let mut ty_set = FxHashSet::default();
75-
76-
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
77-
78-
let cause = ObligationCause::dummy();
79-
let mut constraints = DropckConstraint::empty();
80-
while let Some((ty, depth)) = ty_stack.pop() {
81-
debug!(
82-
"{} kinds, {} overflows, {} ty_stack",
83-
result.kinds.len(),
84-
result.overflows.len(),
85-
ty_stack.len()
86-
);
87-
dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
88-
89-
// "outlives" represent types/regions that may be touched
90-
// by a destructor.
91-
result.kinds.append(&mut constraints.outlives);
92-
result.overflows.append(&mut constraints.overflows);
93-
94-
// If we have even one overflow, we should stop trying to evaluate further --
95-
// chances are, the subsequent overflows for this evaluation won't provide useful
96-
// information and will just decrease the speed at which we can emit these errors
97-
// (since we'll be printing for just that much longer for the often enormous types
98-
// that result here).
99-
if !result.overflows.is_empty() {
100-
break;
101-
}
28+
tcx.infer_ctxt().enter_canonical_trait_query(&canonical_goal, |ocx, goal| {
29+
let tcx = ocx.infcx.tcx;
30+
let ParamEnvAnd { param_env, value: for_ty } = goal;
31+
32+
let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
33+
34+
// A stack of types left to process. Each round, we pop
35+
// something from the stack and invoke
36+
// `dtorck_constraint_for_ty`. This may produce new types that
37+
// have to be pushed on the stack. This continues until we have explored
38+
// all the reachable types from the type `for_ty`.
39+
//
40+
// Example: Imagine that we have the following code:
41+
//
42+
// ```rust
43+
// struct A {
44+
// value: B,
45+
// children: Vec<A>,
46+
// }
47+
//
48+
// struct B {
49+
// value: u32
50+
// }
51+
//
52+
// fn f() {
53+
// let a: A = ...;
54+
// ..
55+
// } // here, `a` is dropped
56+
// ```
57+
//
58+
// at the point where `a` is dropped, we need to figure out
59+
// which types inside of `a` contain region data that may be
60+
// accessed by any destructors in `a`. We begin by pushing `A`
61+
// onto the stack, as that is the type of `a`. We will then
62+
// invoke `dtorck_constraint_for_ty` which will expand `A`
63+
// into the types of its fields `(B, Vec<A>)`. These will get
64+
// pushed onto the stack. Eventually, expanding `Vec<A>` will
65+
// lead to us trying to push `A` a second time -- to prevent
66+
// infinite recursion, we notice that `A` was already pushed
67+
// once and stop.
68+
let mut ty_stack = vec![(for_ty, 0)];
69+
70+
// Set used to detect infinite recursion.
71+
let mut ty_set = FxHashSet::default();
72+
73+
let cause = ObligationCause::dummy();
74+
let mut constraints = DropckConstraint::empty();
75+
while let Some((ty, depth)) = ty_stack.pop() {
76+
debug!(
77+
"{} kinds, {} overflows, {} ty_stack",
78+
result.kinds.len(),
79+
result.overflows.len(),
80+
ty_stack.len()
81+
);
82+
dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
83+
84+
// "outlives" represent types/regions that may be touched
85+
// by a destructor.
86+
result.kinds.append(&mut constraints.outlives);
87+
result.overflows.append(&mut constraints.overflows);
88+
89+
// If we have even one overflow, we should stop trying to evaluate further --
90+
// chances are, the subsequent overflows for this evaluation won't provide useful
91+
// information and will just decrease the speed at which we can emit these errors
92+
// (since we'll be printing for just that much longer for the often enormous types
93+
// that result here).
94+
if !result.overflows.is_empty() {
95+
break;
96+
}
10297

103-
// dtorck types are "types that will get dropped but which
104-
// do not themselves define a destructor", more or less. We have
105-
// to push them onto the stack to be expanded.
106-
for ty in constraints.dtorck_types.drain(..) {
107-
match infcx.at(&cause, param_env).normalize(ty) {
108-
Ok(Normalized { value: ty, obligations }) => {
109-
fulfill_cx.register_predicate_obligations(infcx, obligations);
110-
111-
debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
112-
113-
match ty.kind() {
114-
// All parameters live for the duration of the
115-
// function.
116-
ty::Param(..) => {}
117-
118-
// A projection that we couldn't resolve - it
119-
// might have a destructor.
120-
ty::Projection(..) | ty::Opaque(..) => {
121-
result.kinds.push(ty.into());
122-
}
98+
// dtorck types are "types that will get dropped but which
99+
// do not themselves define a destructor", more or less. We have
100+
// to push them onto the stack to be expanded.
101+
for ty in constraints.dtorck_types.drain(..) {
102+
let Normalized { value: ty, obligations } =
103+
ocx.infcx.at(&cause, param_env).normalize(ty)?;
104+
ocx.register_obligations(obligations);
105+
106+
debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
107+
108+
match ty.kind() {
109+
// All parameters live for the duration of the
110+
// function.
111+
ty::Param(..) => {}
112+
113+
// A projection that we couldn't resolve - it
114+
// might have a destructor.
115+
ty::Projection(..) | ty::Opaque(..) => {
116+
result.kinds.push(ty.into());
117+
}
123118

124-
_ => {
125-
if ty_set.insert(ty) {
126-
ty_stack.push((ty, depth + 1));
127-
}
119+
_ => {
120+
if ty_set.insert(ty) {
121+
ty_stack.push((ty, depth + 1));
128122
}
129123
}
130124
}
131-
132-
// We don't actually expect to fail to normalize.
133-
// That implies a WF error somewhere else.
134-
Err(NoSolution) => {
135-
return Err(NoSolution);
136-
}
137125
}
138126
}
139-
}
140-
141-
debug!("dropck_outlives: result = {:#?}", result);
142127

143-
infcx.make_canonicalized_query_response(canonical_inference_vars, result, &mut *fulfill_cx)
128+
debug!("dropck_outlives: result = {:#?}", result);
129+
Ok(result)
130+
})
144131
}
145132

146133
/// Returns a set of constraints that needs to be satisfied in

0 commit comments

Comments
 (0)
Please sign in to comment.