Skip to content

Commit ca87b53

Browse files
committed
Auto merge of #132250 - nnethercote:rustc_borrowck-cleanups, r=compiler-errors
`rustc_borrowck` cleanups A bunch of cleanups I made while reading over this crate. r? `@lqd`
2 parents 56c6a2f + e0e7a43 commit ca87b53

22 files changed

+251
-385
lines changed

Diff for: compiler/rustc_borrowck/src/borrow_set.rs

+13-13
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,18 @@ pub struct BorrowSet<'tcx> {
2020
/// by the `Location` of the assignment statement in which it
2121
/// appears on the right hand side. Thus the location is the map
2222
/// key, and its position in the map corresponds to `BorrowIndex`.
23-
pub location_map: FxIndexMap<Location, BorrowData<'tcx>>,
23+
pub(crate) location_map: FxIndexMap<Location, BorrowData<'tcx>>,
2424

2525
/// Locations which activate borrows.
2626
/// NOTE: a given location may activate more than one borrow in the future
2727
/// when more general two-phase borrow support is introduced, but for now we
2828
/// only need to store one borrow index.
29-
pub activation_map: FxIndexMap<Location, Vec<BorrowIndex>>,
29+
pub(crate) activation_map: FxIndexMap<Location, Vec<BorrowIndex>>,
3030

3131
/// Map from local to all the borrows on that local.
32-
pub local_map: FxIndexMap<mir::Local, FxIndexSet<BorrowIndex>>,
32+
pub(crate) local_map: FxIndexMap<mir::Local, FxIndexSet<BorrowIndex>>,
3333

34-
pub locals_state_at_exit: LocalsStateAtExit,
34+
pub(crate) locals_state_at_exit: LocalsStateAtExit,
3535
}
3636

3737
impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
@@ -45,7 +45,7 @@ impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
4545
/// Location where a two-phase borrow is activated, if a borrow
4646
/// is in fact a two-phase borrow.
4747
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
48-
pub enum TwoPhaseActivation {
48+
pub(crate) enum TwoPhaseActivation {
4949
NotTwoPhase,
5050
NotActivated,
5151
ActivatedAt(Location),
@@ -55,17 +55,17 @@ pub enum TwoPhaseActivation {
5555
pub struct BorrowData<'tcx> {
5656
/// Location where the borrow reservation starts.
5757
/// In many cases, this will be equal to the activation location but not always.
58-
pub reserve_location: Location,
58+
pub(crate) reserve_location: Location,
5959
/// Location where the borrow is activated.
60-
pub activation_location: TwoPhaseActivation,
60+
pub(crate) activation_location: TwoPhaseActivation,
6161
/// What kind of borrow this is
62-
pub kind: mir::BorrowKind,
62+
pub(crate) kind: mir::BorrowKind,
6363
/// The region for which this borrow is live
64-
pub region: RegionVid,
64+
pub(crate) region: RegionVid,
6565
/// Place from which we are borrowing
66-
pub borrowed_place: mir::Place<'tcx>,
66+
pub(crate) borrowed_place: mir::Place<'tcx>,
6767
/// Place to which the borrow was stored
68-
pub assigned_place: mir::Place<'tcx>,
68+
pub(crate) assigned_place: mir::Place<'tcx>,
6969
}
7070

7171
impl<'tcx> fmt::Display for BorrowData<'tcx> {
@@ -120,7 +120,7 @@ impl LocalsStateAtExit {
120120
}
121121

122122
impl<'tcx> BorrowSet<'tcx> {
123-
pub fn build(
123+
pub(crate) fn build(
124124
tcx: TyCtxt<'tcx>,
125125
body: &Body<'tcx>,
126126
locals_are_invalidated_at_exit: bool,
@@ -156,7 +156,7 @@ impl<'tcx> BorrowSet<'tcx> {
156156
self.activation_map.get(&location).map_or(&[], |activations| &activations[..])
157157
}
158158

159-
pub fn len(&self) -> usize {
159+
pub(crate) fn len(&self) -> usize {
160160
self.location_map.len()
161161
}
162162

Diff for: compiler/rustc_borrowck/src/constraints/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ impl<'tcx> fmt::Debug for OutlivesConstraint<'tcx> {
210210

211211
rustc_index::newtype_index! {
212212
#[debug_format = "OutlivesConstraintIndex({})"]
213-
pub struct OutlivesConstraintIndex {}
213+
pub(crate) struct OutlivesConstraintIndex {}
214214
}
215215

216216
rustc_index::newtype_index! {

Diff for: compiler/rustc_borrowck/src/dataflow.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -254,8 +254,8 @@ impl<'tcx> PoloniusOutOfScopePrecomputer<'_, 'tcx> {
254254
let sccs = self.regioncx.constraint_sccs();
255255
let universal_regions = self.regioncx.universal_regions();
256256

257-
// We first handle the cases where the loan doesn't go out of scope, depending on the issuing
258-
// region's successors.
257+
// We first handle the cases where the loan doesn't go out of scope, depending on the
258+
// issuing region's successors.
259259
for successor in graph::depth_first_search(&self.regioncx.region_graph(), issuing_region) {
260260
// 1. Via applied member constraints
261261
//

Diff for: compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs

+15-36
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use std::rc::Rc;
33

44
use rustc_errors::Diag;
55
use rustc_hir::def_id::LocalDefId;
6-
use rustc_infer::infer::canonical::CanonicalQueryInput;
76
use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
87
use rustc_infer::infer::{
98
InferCtxt, RegionResolutionError, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt as _,
@@ -21,7 +20,6 @@ use rustc_span::Span;
2120
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
2221
use rustc_trait_selection::error_reporting::infer::nice_region_error::NiceRegionError;
2322
use rustc_trait_selection::traits::ObligationCtxt;
24-
use rustc_trait_selection::traits::query::type_op;
2523
use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause};
2624
use tracing::{debug, instrument};
2725

@@ -31,12 +29,9 @@ use crate::session_diagnostics::{
3129
HigherRankedErrorCause, HigherRankedLifetimeError, HigherRankedSubtypeError,
3230
};
3331

34-
#[derive(Clone)]
35-
pub(crate) struct UniverseInfo<'tcx>(UniverseInfoInner<'tcx>);
36-
3732
/// What operation a universe was created for.
3833
#[derive(Clone)]
39-
enum UniverseInfoInner<'tcx> {
34+
pub(crate) enum UniverseInfo<'tcx> {
4035
/// Relating two types which have binders.
4136
RelateTys { expected: Ty<'tcx>, found: Ty<'tcx> },
4237
/// Created from performing a `TypeOp`.
@@ -47,11 +42,11 @@ enum UniverseInfoInner<'tcx> {
4742

4843
impl<'tcx> UniverseInfo<'tcx> {
4944
pub(crate) fn other() -> UniverseInfo<'tcx> {
50-
UniverseInfo(UniverseInfoInner::Other)
45+
UniverseInfo::Other
5146
}
5247

5348
pub(crate) fn relate(expected: Ty<'tcx>, found: Ty<'tcx>) -> UniverseInfo<'tcx> {
54-
UniverseInfo(UniverseInfoInner::RelateTys { expected, found })
49+
UniverseInfo::RelateTys { expected, found }
5550
}
5651

5752
pub(crate) fn report_error(
@@ -61,8 +56,8 @@ impl<'tcx> UniverseInfo<'tcx> {
6156
error_element: RegionElement,
6257
cause: ObligationCause<'tcx>,
6358
) {
64-
match self.0 {
65-
UniverseInfoInner::RelateTys { expected, found } => {
59+
match *self {
60+
UniverseInfo::RelateTys { expected, found } => {
6661
let err = mbcx.infcx.err_ctxt().report_mismatched_types(
6762
&cause,
6863
mbcx.param_env,
@@ -72,10 +67,10 @@ impl<'tcx> UniverseInfo<'tcx> {
7267
);
7368
mbcx.buffer_error(err);
7469
}
75-
UniverseInfoInner::TypeOp(ref type_op_info) => {
70+
UniverseInfo::TypeOp(ref type_op_info) => {
7671
type_op_info.report_error(mbcx, placeholder, error_element, cause);
7772
}
78-
UniverseInfoInner::Other => {
73+
UniverseInfo::Other => {
7974
// FIXME: This error message isn't great, but it doesn't show
8075
// up in the existing UI tests. Consider investigating this
8176
// some more.
@@ -93,46 +88,30 @@ pub(crate) trait ToUniverseInfo<'tcx> {
9388

9489
impl<'tcx> ToUniverseInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
9590
fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
96-
UniverseInfo(UniverseInfoInner::TypeOp(Rc::new(crate::type_check::InstantiateOpaqueType {
91+
UniverseInfo::TypeOp(Rc::new(crate::type_check::InstantiateOpaqueType {
9792
base_universe: Some(base_universe),
9893
..self
99-
})))
94+
}))
10095
}
10196
}
10297

10398
impl<'tcx> ToUniverseInfo<'tcx> for CanonicalTypeOpProvePredicateGoal<'tcx> {
10499
fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
105-
UniverseInfo(UniverseInfoInner::TypeOp(Rc::new(PredicateQuery {
106-
canonical_query: self,
107-
base_universe,
108-
})))
100+
UniverseInfo::TypeOp(Rc::new(PredicateQuery { canonical_query: self, base_universe }))
109101
}
110102
}
111103

112104
impl<'tcx, T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx> ToUniverseInfo<'tcx>
113105
for CanonicalTypeOpNormalizeGoal<'tcx, T>
114106
{
115107
fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
116-
UniverseInfo(UniverseInfoInner::TypeOp(Rc::new(NormalizeQuery {
117-
canonical_query: self,
118-
base_universe,
119-
})))
108+
UniverseInfo::TypeOp(Rc::new(NormalizeQuery { canonical_query: self, base_universe }))
120109
}
121110
}
122111

123112
impl<'tcx> ToUniverseInfo<'tcx> for CanonicalTypeOpAscribeUserTypeGoal<'tcx> {
124113
fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
125-
UniverseInfo(UniverseInfoInner::TypeOp(Rc::new(AscribeUserTypeQuery {
126-
canonical_query: self,
127-
base_universe,
128-
})))
129-
}
130-
}
131-
132-
impl<'tcx, F> ToUniverseInfo<'tcx> for CanonicalQueryInput<'tcx, type_op::custom::CustomTypeOp<F>> {
133-
fn to_universe_info(self, _base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
134-
// We can't rerun custom type ops.
135-
UniverseInfo::other()
114+
UniverseInfo::TypeOp(Rc::new(AscribeUserTypeQuery { canonical_query: self, base_universe }))
136115
}
137116
}
138117

@@ -143,7 +122,7 @@ impl<'tcx> ToUniverseInfo<'tcx> for ! {
143122
}
144123

145124
#[allow(unused_lifetimes)]
146-
trait TypeOpInfo<'tcx> {
125+
pub(crate) trait TypeOpInfo<'tcx> {
147126
/// Returns an error to be reported if rerunning the type op fails to
148127
/// recover the error's cause.
149128
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx>;
@@ -289,8 +268,8 @@ where
289268
// `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the
290269
// `ObligationCause`. The normalization results are currently different between
291270
// `QueryNormalizeExt::query_normalize` used in the query and `normalize` called below:
292-
// the former fails to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` test.
293-
// Check after #85499 lands to see if its fixes have erased this difference.
271+
// the former fails to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs`
272+
// test. Check after #85499 lands to see if its fixes have erased this difference.
294273
let (param_env, value) = key.into_parts();
295274
let _ = ocx.normalize(&cause, param_env, value.value);
296275

Diff for: compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+26-21
Original file line numberDiff line numberDiff line change
@@ -1345,11 +1345,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
13451345
// See `tests/ui/moves/needs-clone-through-deref.rs`
13461346
return false;
13471347
}
1348-
// We don't want to suggest `.clone()` in a move closure, since the value has already been captured.
1348+
// We don't want to suggest `.clone()` in a move closure, since the value has already been
1349+
// captured.
13491350
if self.in_move_closure(expr) {
13501351
return false;
13511352
}
1352-
// We also don't want to suggest cloning a closure itself, since the value has already been captured.
1353+
// We also don't want to suggest cloning a closure itself, since the value has already been
1354+
// captured.
13531355
if let hir::ExprKind::Closure(_) = expr.kind {
13541356
return false;
13551357
}
@@ -1381,7 +1383,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
13811383
}
13821384
}
13831385
}
1384-
// Cloning the raw pointer doesn't make sense in some cases and would cause a type mismatch error. (see #126863)
1386+
// Cloning the raw pointer doesn't make sense in some cases and would cause a type mismatch
1387+
// error. (see #126863)
13851388
if inner_expr.span.lo() != expr.span.lo() && !is_raw_ptr {
13861389
// Remove "(*" or "(&"
13871390
sugg.push((expr.span.with_hi(inner_expr.span.lo()), String::new()));
@@ -1553,8 +1556,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
15531556
let use_spans = self.move_spans(place.as_ref(), location);
15541557
let span = use_spans.var_or_use();
15551558

1556-
// If the attempted use is in a closure then we do not care about the path span of the place we are currently trying to use
1557-
// we call `var_span_label` on `borrow_spans` to annotate if the existing borrow was in a closure
1559+
// If the attempted use is in a closure then we do not care about the path span of the
1560+
// place we are currently trying to use we call `var_span_label` on `borrow_spans` to
1561+
// annotate if the existing borrow was in a closure.
15581562
let mut err = self.cannot_use_when_mutably_borrowed(
15591563
span,
15601564
&self.describe_any_place(place.as_ref()),
@@ -2480,7 +2484,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
24802484
if let hir::ExprKind::Closure(closure) = ex.kind
24812485
&& ex.span.contains(self.borrow_span)
24822486
// To support cases like `|| { v.call(|this| v.get()) }`
2483-
// FIXME: actually support such cases (need to figure out how to move from the capture place to original local)
2487+
// FIXME: actually support such cases (need to figure out how to move from the
2488+
// capture place to original local).
24842489
&& self.res.as_ref().map_or(true, |(prev_res, _)| prev_res.span.contains(ex.span))
24852490
{
24862491
self.res = Some((ex, closure));
@@ -2733,7 +2738,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
27332738
/// cannot borrow `a.u` (via `a.u.z.c`) as immutable because it is also borrowed as
27342739
/// mutable (via `a.u.s.b`) [E0502]
27352740
/// ```
2736-
pub(crate) fn describe_place_for_conflicting_borrow(
2741+
fn describe_place_for_conflicting_borrow(
27372742
&self,
27382743
first_borrowed_place: Place<'tcx>,
27392744
second_borrowed_place: Place<'tcx>,
@@ -3188,8 +3193,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
31883193
/// misleading users in cases like `tests/ui/nll/borrowed-temporary-error.rs`.
31893194
/// We could expand the analysis to suggest hoising all of the relevant parts of
31903195
/// the users' code to make the code compile, but that could be too much.
3191-
/// We found the `prop_expr` by the way to check whether the expression is a `FormatArguments`,
3192-
/// which is a special case since it's generated by the compiler.
3196+
/// We found the `prop_expr` by the way to check whether the expression is a
3197+
/// `FormatArguments`, which is a special case since it's generated by the
3198+
/// compiler.
31933199
struct NestedStatementVisitor<'tcx> {
31943200
span: Span,
31953201
current: usize,
@@ -3420,7 +3426,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
34203426
let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
34213427
Ok(string) => {
34223428
let coro_prefix = if string.starts_with("async") {
3423-
// `async` is 5 chars long. Not using `.len()` to avoid the cast from `usize` to `u32`
3429+
// `async` is 5 chars long. Not using `.len()` to avoid the cast from `usize`
3430+
// to `u32`.
34243431
Some(5)
34253432
} else if string.starts_with("gen") {
34263433
// `gen` is 3 chars long
@@ -3618,10 +3625,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
36183625
let stmt_kind =
36193626
self.body[location.block].statements.get(location.statement_index).map(|s| &s.kind);
36203627
if let Some(StatementKind::StorageDead(..)) = stmt_kind {
3621-
// this analysis only tries to find moves explicitly
3622-
// written by the user, so we ignore the move-outs
3623-
// created by `StorageDead` and at the beginning
3624-
// of a function.
3628+
// This analysis only tries to find moves explicitly written by the user, so we
3629+
// ignore the move-outs created by `StorageDead` and at the beginning of a
3630+
// function.
36253631
} else {
36263632
// If we are found a use of a.b.c which was in error, then we want to look for
36273633
// moves not only of a.b.c but also a.b and a.
@@ -3706,13 +3712,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
37063712
}
37073713
}
37083714
if (is_argument || !reached_start) && result.is_empty() {
3709-
/* Process back edges (moves in future loop iterations) only if
3710-
the move path is definitely initialized upon loop entry,
3711-
to avoid spurious "in previous iteration" errors.
3712-
During DFS, if there's a path from the error back to the start
3713-
of the function with no intervening init or move, then the
3714-
move path may be uninitialized at loop entry.
3715-
*/
3715+
// Process back edges (moves in future loop iterations) only if
3716+
// the move path is definitely initialized upon loop entry,
3717+
// to avoid spurious "in previous iteration" errors.
3718+
// During DFS, if there's a path from the error back to the start
3719+
// of the function with no intervening init or move, then the
3720+
// move path may be uninitialized at loop entry.
37163721
while let Some(location) = back_edge_stack.pop() {
37173722
if dfs_iter(&mut result, location, true) {
37183723
continue;

0 commit comments

Comments
 (0)