rust/compiler/rustc_mir/src/borrow_check/mod.rs

2322 lines
93 KiB
Rust
Raw Normal View History

//! This query borrow-checks the MIR to (further) ensure it is not broken.
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
Merge indexed_set.rs into bitvec.rs, and rename it bit_set.rs. Currently we have two files implementing bitsets (and 2D bit matrices). This commit combines them into one, taking the best features from each. This involves renaming a lot of things. The high level changes are as follows. - bitvec.rs --> bit_set.rs - indexed_set.rs --> (removed) - BitArray + IdxSet --> BitSet (merged, see below) - BitVector --> GrowableBitSet - {,Sparse,Hybrid}IdxSet --> {,Sparse,Hybrid}BitSet - BitMatrix --> BitMatrix - SparseBitMatrix --> SparseBitMatrix The changes within the bitset types themselves are as follows. ``` OLD OLD NEW BitArray<C> IdxSet<T> BitSet<T> -------- ------ ------ grow - grow new - (remove) new_empty new_empty new_empty new_filled new_filled new_filled - to_hybrid to_hybrid clear clear clear set_up_to set_up_to set_up_to clear_above - clear_above count - count contains(T) contains(&T) contains(T) contains_all - superset is_empty - is_empty insert(T) add(&T) insert(T) insert_all - insert_all() remove(T) remove(&T) remove(T) words words words words_mut words_mut words_mut - overwrite overwrite merge union union - subtract subtract - intersect intersect iter iter iter ``` In general, when choosing names I went with: - names that are more obvious (e.g. `BitSet` over `IdxSet`). - names that are more like the Rust libraries (e.g. `T` over `C`, `insert` over `add`); - names that are more set-like (e.g. `union` over `merge`, `superset` over `contains_all`, `domain_size` over `num_bits`). Also, using `T` for index arguments seems more sensible than `&T` -- even though the latter is standard in Rust collection types -- because indices are always copyable. It also results in fewer `&` and `*` sigils in practice.
2018-09-14 07:07:25 +02:00
use rustc_data_structures::graph::dominators::Dominators;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
use rustc_hir as hir;
2020-05-11 10:29:05 +02:00
use rustc_hir::def_id::LocalDefId;
2020-12-13 06:11:15 +01:00
use rustc_hir::Node;
2019-12-22 23:42:04 +01:00
use rustc_index::bit_set::BitSet;
use rustc_index::vec::IndexVec;
2020-01-06 23:21:41 +01:00
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
2020-03-29 17:19:48 +02:00
use rustc_middle::mir::{
2020-04-12 19:31:00 +02:00
traversal, Body, ClearCrossCrate, Local, Location, Mutability, Operand, Place, PlaceElem,
PlaceRef, VarDebugInfoContents,
2020-03-29 17:19:48 +02:00
};
use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
2020-02-14 19:17:50 +01:00
use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
2020-03-29 17:19:48 +02:00
use rustc_middle::ty::query::Providers;
2020-12-13 06:11:15 +01:00
use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
use rustc_session::lint::builtin::{MUTABLE_BORROW_RESERVATION_CONFLICT, UNUSED_MUT};
2020-04-19 13:00:18 +02:00
use rustc_span::{Span, Symbol, DUMMY_SP};
use either::Either;
use smallvec::SmallVec;
2019-12-29 03:36:42 +01:00
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::mem;
use std::rc::Rc;
use crate::dataflow;
use crate::dataflow::impls::{
Borrows, EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces,
};
2019-02-07 22:28:15 +01:00
use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
use crate::dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError};
2019-02-07 22:28:15 +01:00
use crate::dataflow::MoveDataParamEnv;
use crate::dataflow::{Analysis, BorrowckFlowState as Flows, BorrowckResults};
2019-12-29 03:36:42 +01:00
use self::diagnostics::{AccessKind, RegionName};
use self::location::LocationTable;
use self::prefixes::PrefixSet;
use self::MutateMode::{JustWrite, WriteAndRead};
use self::path_utils::*;
2019-12-22 23:42:04 +01:00
mod borrow_set;
mod constraint_generation;
mod constraints;
mod def_use;
2019-11-27 18:39:25 +01:00
mod diagnostics;
2019-12-22 23:42:04 +01:00
mod facts;
mod invalidation;
mod location;
2019-12-22 23:42:04 +01:00
mod member_constraints;
mod nll;
2018-06-22 05:10:52 +02:00
mod path_utils;
2019-12-22 23:42:04 +01:00
mod place_ext;
mod places_conflict;
mod prefixes;
2019-12-22 23:42:04 +01:00
mod region_infer;
2019-11-30 02:48:29 +01:00
mod renumber;
2019-12-06 17:02:48 +01:00
mod type_check;
2019-12-22 23:42:04 +01:00
mod universal_regions;
mod used_muts;
New `ActiveBorrows` dataflow for two-phase `&mut`; not yet borrowed-checked. High-level picture: The old `Borrows` analysis is now called `Reservations` (implemented as a newtype wrapper around `Borrows`); this continues to compute whether a `Rvalue::Ref` can reach a statement without an intervening `EndRegion`. In addition, we also track what `Place` each such `Rvalue::Ref` was immediately assigned to in a given borrow (yay for MIR-structural properties!). The new `ActiveBorrows` analysis then tracks the initial use of any of those assigned `Places` for a given borrow. I.e. a borrow becomes "active" immediately after it starts being "used" in some way. (This is conservative in the sense that we will treat a copy `x = y;` as a use of `y`; in principle one might further delay activation in such cases.) The new `ActiveBorrows` analysis needs to take the `Reservations` results as an initial input, because the reservation state influences the gen/kill sets for `ActiveBorrows`. In particular, a use of `a` activates a borrow `a = &b` if and only if there exists a path (in the control flow graph) from the borrow to that use. So we need to know if the borrow reaches a given use to know if it really gets a gen-bit or not. * Incorporating the output from one dataflow analysis into the input of another required more changes to the infrastructure than I had expected, and even after those changes, the resulting code is still a bit subtle. * In particular, Since we need to know the intrablock reservation state, we need to dynamically update a bitvector for the reservations as we are also trying to compute the gen/kills bitvector for the active borrows. * The way I ended up deciding to do this (after also toying with at least two other designs) is to put both the reservation state and the active borrow state into a single bitvector. That is why we now have separate (but related) `BorrowIndex` and `ReserveOrActivateIndex`: each borrow index maps to a pair of neighboring reservation and activation indexes. As noted above, these changes are solely adding the active borrows dataflow analysis (and updating the existing code to cope with the switch from `Borrows` to `Reservations`). The code to process the bitvector in the borrow checker currently just skips over all of the active borrow bits. But atop this commit, one *can* observe the analysis results by looking at the graphviz output, e.g. via ```rust #[rustc_mir(borrowck_graphviz_preflow="pre_two_phase.dot", borrowck_graphviz_postflow="post_two_phase.dot")] ``` Includes doc for `FindPlaceUses`, as well as `Reservations` and `ActiveBorrows` structs, which are wrappers are the `Borrows` struct that dictate which flow analysis should be performed.
2017-12-01 12:32:51 +01:00
2019-12-22 23:42:04 +01:00
crate use borrow_set::{BorrowData, BorrowSet};
crate use nll::{PoloniusOutput, ToRegionVid};
2019-12-22 23:42:04 +01:00
crate use place_ext::PlaceExt;
crate use places_conflict::{places_conflict, PlaceConflictBias};
crate use region_infer::RegionInferenceContext;
// FIXME(eddyb) perhaps move this somewhere more centrally.
#[derive(Debug)]
2020-12-13 06:11:15 +01:00
crate struct Upvar<'tcx> {
2021-01-12 20:54:12 +01:00
// FIXME(project-rfc_2229#36): print capture precisely here.
2020-04-19 13:00:18 +02:00
name: Symbol,
2020-12-13 06:11:15 +01:00
place: CapturedPlace<'tcx>,
/// If true, the capture is behind a reference.
by_ref: bool,
}
const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref];
pub fn provide(providers: &mut Providers) {
2020-07-06 23:49:53 +02:00
*providers = Providers {
mir_borrowck: |tcx, did| {
2020-07-21 22:54:18 +02:00
if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
tcx.mir_borrowck_const_arg(def)
} else {
mir_borrowck(tcx, ty::WithOptConstParam::unknown(did))
}
},
2020-07-08 01:03:19 +02:00
mir_borrowck_const_arg: |tcx, (did, param_did)| {
2020-07-15 10:50:54 +02:00
mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
2020-07-06 23:49:53 +02:00
},
..*providers
};
}
2020-07-06 23:49:53 +02:00
fn mir_borrowck<'tcx>(
tcx: TyCtxt<'tcx>,
2020-07-15 10:50:54 +02:00
def: ty::WithOptConstParam<LocalDefId>,
2020-07-06 23:49:53 +02:00
) -> &'tcx BorrowCheckResult<'tcx> {
let (input_body, promoted) = tcx.mir_promoted(def);
2020-07-06 23:49:53 +02:00
debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id()));
let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
let input_body: &Body<'_> = &input_body.borrow();
2019-08-04 22:20:21 +02:00
let promoted: &IndexVec<_, _> = &promoted.borrow();
do_mir_borrowck(&infcx, input_body, promoted)
});
debug!("mir_borrowck done");
2020-07-03 22:15:27 +02:00
tcx.arena.alloc(opt_closure_req)
}
2019-06-13 23:48:52 +02:00
fn do_mir_borrowck<'a, 'tcx>(
infcx: &InferCtxt<'a, 'tcx>,
input_body: &Body<'tcx>,
2020-04-12 19:31:00 +02:00
input_promoted: &IndexVec<Promoted, Body<'tcx>>,
2019-06-13 23:48:52 +02:00
) -> BorrowCheckResult<'tcx> {
let def = input_body.source.with_opt_param().as_local().unwrap();
2020-07-06 23:49:53 +02:00
debug!("do_mir_borrowck(def = {:?})", def);
let tcx = infcx.tcx;
2020-07-06 23:49:53 +02:00
let param_env = tcx.param_env(def.did);
let id = tcx.hir().local_def_id_to_hir_id(def.did);
let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
for var_debug_info in &input_body.var_debug_info {
if let VarDebugInfoContents::Place(place) = var_debug_info.value {
if let Some(local) = place.as_local() {
if let Some(prev_name) = local_names[local] {
if var_debug_info.name != prev_name {
span_bug!(
var_debug_info.source_info.span,
"local {:?} has many names (`{}` vs `{}`)",
local,
prev_name,
var_debug_info.name
);
}
}
local_names[local] = Some(var_debug_info.name);
}
}
}
// Gather the upvars of a closure, if any.
2020-07-17 10:47:04 +02:00
let tables = tcx.typeck_opt_const_arg(def);
if let Some(ErrorReported) = tables.tainted_by_errors {
infcx.set_tainted_by_errors();
}
let upvars: Vec<_> = tables
.closure_min_captures_flattened(def.did.to_def_id())
.map(|captured_place| {
2020-12-13 06:11:15 +01:00
let var_hir_id = captured_place.get_root_variable();
let capture = captured_place.info.capture_kind;
let by_ref = match capture {
ty::UpvarCapture::ByValue(_) => false,
ty::UpvarCapture::ByRef(..) => true,
};
2020-12-13 06:11:15 +01:00
Upvar { name: tcx.hir().name(var_hir_id), place: captured_place.clone(), by_ref }
})
.collect();
// Replace all regions with fresh inference variables. This
// requires first making our own copy of the MIR. This copy will
// be modified (in place) to contain non-lexical lifetimes. It
// will have a lifetime tied to the inference context.
2020-04-12 19:31:00 +02:00
let mut body = input_body.clone();
let mut promoted = input_promoted.clone();
let free_regions = nll::replace_regions_in_mir(infcx, param_env, &mut body, &mut promoted);
2020-04-12 19:31:00 +02:00
let body = &body; // no further changes
let location_table = &LocationTable::new(&body);
let mut errors_buffer = Vec::new();
let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) =
match MoveData::gather_moves(&body, tcx, param_env) {
Ok(move_data) => (move_data, Vec::new()),
Err((move_data, move_errors)) => (move_data, move_errors),
};
let promoted_errors = promoted
.iter_enumerated()
.map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env)));
2019-12-22 23:42:04 +01:00
let mdpe = MoveDataParamEnv { move_data, param_env };
let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
.into_engine(tcx, &body)
.pass_name("borrowck")
.iterate_to_fixpoint()
.into_results_cursor(&body);
let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure();
2019-12-22 23:42:04 +01:00
let borrow_set =
Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
// Compute non-lexical lifetimes.
let nll::NllOutput {
regioncx,
opaque_type_values,
polonius_output,
opt_closure_req,
nll_errors,
} = nll::compute_regions(
infcx,
free_regions,
body,
&promoted,
location_table,
param_env,
&mut flow_inits,
&mdpe.move_data,
&borrow_set,
&upvars,
);
// Dump MIR results into a file, if that is enabled. This let us
// write unit-tests, as well as helping with debugging.
nll::dump_mir_results(infcx, &body, &regioncx, &opt_closure_req);
// We also have a `#[rustc_regions]` annotation that causes us to dump
// information.
nll::dump_annotation(
infcx,
&body,
&regioncx,
&opt_closure_req,
&opaque_type_values,
&mut errors_buffer,
);
// The various `flow_*` structures can be large. We drop `flow_inits` here
// so it doesn't overlap with the others below. This reduces peak memory
// usage significantly on some benchmarks.
drop(flow_inits);
let regioncx = Rc::new(regioncx);
2021-02-07 22:32:50 +01:00
let flow_borrows = Borrows::new(tcx, &body, &regioncx, &borrow_set)
.into_engine(tcx, &body)
.pass_name("borrowck")
.iterate_to_fixpoint();
let flow_uninits = MaybeUninitializedPlaces::new(tcx, &body, &mdpe)
.into_engine(tcx, &body)
.pass_name("borrowck")
.iterate_to_fixpoint();
let flow_ever_inits = EverInitializedPlaces::new(tcx, &body, &mdpe)
.into_engine(tcx, &body)
.pass_name("borrowck")
.iterate_to_fixpoint();
2018-03-05 08:44:10 +01:00
2019-06-20 10:39:19 +02:00
let movable_generator = match tcx.hir().get(id) {
2018-08-25 16:56:16 +02:00
Node::Expr(&hir::Expr {
kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)),
..
2018-04-07 13:11:01 +02:00
}) => false,
_ => true,
};
for (idx, move_data_results) in promoted_errors {
let promoted_body = &promoted[idx];
let dominators = promoted_body.dominators();
if let Err((move_data, move_errors)) = move_data_results {
let mut promoted_mbcx = MirBorrowckCtxt {
infcx,
param_env,
body: promoted_body,
move_data: &move_data,
location_table: &LocationTable::new(promoted_body),
movable_generator,
fn_self_span_reported: Default::default(),
locals_are_invalidated_at_exit,
access_place_error_reported: Default::default(),
reservation_error_reported: Default::default(),
reservation_warnings: Default::default(),
move_error_reported: BTreeMap::new(),
uninitialized_error_reported: Default::default(),
errors_buffer,
regioncx: regioncx.clone(),
used_mut: Default::default(),
used_mut_upvars: SmallVec::new(),
2021-02-07 22:32:50 +01:00
borrow_set: Rc::clone(&borrow_set),
dominators,
upvars: Vec::new(),
local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
region_names: RefCell::default(),
next_region_name: RefCell::new(1),
polonius_output: None,
};
promoted_mbcx.report_move_errors(move_errors);
errors_buffer = promoted_mbcx.errors_buffer;
};
}
let dominators = body.dominators();
let mut mbcx = MirBorrowckCtxt {
infcx,
param_env,
body,
move_data: &mdpe.move_data,
location_table,
movable_generator,
locals_are_invalidated_at_exit,
fn_self_span_reported: Default::default(),
access_place_error_reported: Default::default(),
reservation_error_reported: Default::default(),
reservation_warnings: Default::default(),
move_error_reported: BTreeMap::new(),
uninitialized_error_reported: Default::default(),
errors_buffer,
2021-02-07 22:32:50 +01:00
regioncx: Rc::clone(&regioncx),
used_mut: Default::default(),
used_mut_upvars: SmallVec::new(),
2021-02-07 22:32:50 +01:00
borrow_set: Rc::clone(&borrow_set),
dominators,
upvars,
local_names,
2019-12-29 03:36:42 +01:00
region_names: RefCell::default(),
next_region_name: RefCell::new(1),
polonius_output,
};
// Compute and report region errors, if any.
mbcx.report_region_errors(nll_errors);
let results = BorrowckResults {
ever_inits: flow_ever_inits,
uninits: flow_uninits,
borrows: flow_borrows,
};
New `ActiveBorrows` dataflow for two-phase `&mut`; not yet borrowed-checked. High-level picture: The old `Borrows` analysis is now called `Reservations` (implemented as a newtype wrapper around `Borrows`); this continues to compute whether a `Rvalue::Ref` can reach a statement without an intervening `EndRegion`. In addition, we also track what `Place` each such `Rvalue::Ref` was immediately assigned to in a given borrow (yay for MIR-structural properties!). The new `ActiveBorrows` analysis then tracks the initial use of any of those assigned `Places` for a given borrow. I.e. a borrow becomes "active" immediately after it starts being "used" in some way. (This is conservative in the sense that we will treat a copy `x = y;` as a use of `y`; in principle one might further delay activation in such cases.) The new `ActiveBorrows` analysis needs to take the `Reservations` results as an initial input, because the reservation state influences the gen/kill sets for `ActiveBorrows`. In particular, a use of `a` activates a borrow `a = &b` if and only if there exists a path (in the control flow graph) from the borrow to that use. So we need to know if the borrow reaches a given use to know if it really gets a gen-bit or not. * Incorporating the output from one dataflow analysis into the input of another required more changes to the infrastructure than I had expected, and even after those changes, the resulting code is still a bit subtle. * In particular, Since we need to know the intrablock reservation state, we need to dynamically update a bitvector for the reservations as we are also trying to compute the gen/kills bitvector for the active borrows. * The way I ended up deciding to do this (after also toying with at least two other designs) is to put both the reservation state and the active borrow state into a single bitvector. That is why we now have separate (but related) `BorrowIndex` and `ReserveOrActivateIndex`: each borrow index maps to a pair of neighboring reservation and activation indexes. As noted above, these changes are solely adding the active borrows dataflow analysis (and updating the existing code to cope with the switch from `Borrows` to `Reservations`). The code to process the bitvector in the borrow checker currently just skips over all of the active borrow bits. But atop this commit, one *can* observe the analysis results by looking at the graphviz output, e.g. via ```rust #[rustc_mir(borrowck_graphviz_preflow="pre_two_phase.dot", borrowck_graphviz_postflow="post_two_phase.dot")] ``` Includes doc for `FindPlaceUses`, as well as `Reservations` and `ActiveBorrows` structs, which are wrappers are the `Borrows` struct that dictate which flow analysis should be performed.
2017-12-01 12:32:51 +01:00
mbcx.report_move_errors(move_errors);
dataflow::visit_results(
&body,
traversal::reverse_postorder(&body).map(|(bb, _)| bb),
&results,
&mut mbcx,
);
// Convert any reservation warnings into lints.
2019-06-30 20:30:01 +02:00
let reservation_warnings = mem::take(&mut mbcx.reservation_warnings);
2019-05-01 23:03:17 +02:00
for (_, (place, span, location, bk, borrow)) in reservation_warnings {
2020-03-30 22:49:33 +02:00
let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow);
let scope = mbcx.body.source_info(location).scope;
let lint_root = match &mbcx.body.source_scopes[scope].local_data {
ClearCrossCrate::Set(data) => data.lint_root,
_ => id,
};
// Span and message don't matter; we overwrite them below anyway
mbcx.infcx.tcx.struct_span_lint_hir(
2019-12-22 23:42:04 +01:00
MUTABLE_BORROW_RESERVATION_CONFLICT,
lint_root,
DUMMY_SP,
|lint| {
let mut diag = lint.build("");
diag.message = initial_diag.styled_message().clone();
diag.span = initial_diag.span.clone();
diag.buffer(&mut mbcx.errors_buffer);
},
);
initial_diag.cancel();
}
// For each non-user used mutable variable, check if it's been assigned from
// a user-declared local. If so, then put that local into the used_mut set.
// Note that this set is expected to be small - only upvars from closures
// would have a chance of erroneously adding non-user-defined mutable vars
// to the set.
2019-12-22 23:42:04 +01:00
let temporary_used_locals: FxHashSet<Local> = mbcx
.used_mut
.iter()
.filter(|&local| !mbcx.body.local_decls[*local].is_user_variable())
2018-06-22 05:10:52 +02:00
.cloned()
.collect();
// For the remaining unused locals that are marked as mutable, we avoid linting any that
// were never initialized. These locals may have been removed as unreachable code; or will be
// linted as unused variables.
2019-12-22 23:42:04 +01:00
let unused_mut_locals =
mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect();
mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals);
debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
let used_mut = mbcx.used_mut;
2019-12-22 23:42:04 +01:00
for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
let local_decl = &mbcx.body.local_decls[local];
let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
ClearCrossCrate::Set(data) => data.lint_root,
_ => continue,
};
// Skip over locals that begin with an underscore or have no name
match mbcx.local_names[local] {
2019-12-22 23:42:04 +01:00
Some(name) => {
if name.as_str().starts_with('_') {
2019-12-22 23:42:04 +01:00
continue;
}
}
None => continue,
}
let span = local_decl.source_info.span;
if span.desugaring_kind().is_some() {
// If the `mut` arises as part of a desugaring, we should ignore it.
continue;
}
2020-02-02 00:47:58 +01:00
tcx.struct_span_lint_hir(UNUSED_MUT, lint_root, span, |lint| {
2020-02-05 16:27:46 +01:00
let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
2020-02-02 00:47:58 +01:00
lint.build("variable does not need to be mutable")
.span_suggestion_short(
mut_span,
"remove this `mut`",
String::new(),
Applicability::MachineApplicable,
)
.emit();
2020-02-02 00:47:58 +01:00
})
}
// Buffer any move errors that we collected and de-duplicated.
for (_, (_, diag)) in mbcx.move_error_reported {
diag.buffer(&mut mbcx.errors_buffer);
}
2018-10-16 15:06:59 +02:00
if !mbcx.errors_buffer.is_empty() {
2018-11-28 22:05:36 +01:00
mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span);
for diag in mbcx.errors_buffer.drain(..) {
mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag);
}
}
let result = BorrowCheckResult {
concrete_opaque_types: opaque_type_values,
closure_requirements: opt_closure_req,
used_mut_upvars: mbcx.used_mut_upvars,
};
debug!("do_mir_borrowck: result = {:#?}", result);
result
}
crate struct MirBorrowckCtxt<'cx, 'tcx> {
crate infcx: &'cx InferCtxt<'cx, 'tcx>,
param_env: ParamEnv<'tcx>,
2020-04-12 19:31:00 +02:00
body: &'cx Body<'tcx>,
move_data: &'cx MoveData<'tcx>,
/// Map from MIR `Location` to `LocationIndex`; created
/// when MIR borrowck begins.
location_table: &'cx LocationTable,
movable_generator: bool,
/// This keeps track of whether local variables are free-ed when the function
2017-12-05 23:51:47 +01:00
/// exits even without a `StorageDead`, which appears to be the case for
/// constants.
///
/// I'm not sure this is the right approach - @eddyb could you try and
/// figure this out?
locals_are_invalidated_at_exit: bool,
/// This field keeps track of when borrow errors are reported in the access_place function
/// so that there is no duplicate reporting. This field cannot also be used for the conflicting
/// borrow errors that is handled by the `reservation_error_reported` field as the inclusion
/// of the `Span` type (while required to mute some errors) stops the muting of the reservation
/// errors.
access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>,
/// This field keeps track of when borrow conflict errors are reported
/// for reservations, so that we don't report seemingly duplicate
2019-02-08 14:53:55 +01:00
/// errors for corresponding activations.
//
// FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s,
// but it is currently inconvenient to track down the `BorrowIndex`
// at the time we detect and report a reservation error.
reservation_error_reported: FxHashSet<Place<'tcx>>,
/// This fields keeps track of the `Span`s that we have
/// used to report extra information for `FnSelfUse`, to avoid
/// unnecessarily verbose errors.
fn_self_span_reported: FxHashSet<Span>,
/// Migration warnings to be reported for #56254. We delay reporting these
/// so that we can suppress the warning if there's a corresponding error
/// for the activation of the borrow.
2019-12-22 23:42:04 +01:00
reservation_warnings:
FxHashMap<BorrowIndex, (Place<'tcx>, Span, Location, BorrowKind, BorrowData<'tcx>)>,
2020-03-06 12:13:55 +01:00
/// This field keeps track of move errors that are to be reported for given move indices.
///
/// There are situations where many errors can be reported for a single move out (see #53807)
/// and we want only the best of those errors.
///
/// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
/// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the
/// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once
/// all move errors have been reported, any diagnostics in this map are added to the buffer
/// to be emitted.
///
/// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary
/// when errors in the map are being re-added to the error buffer so that errors with the
/// same primary span come out in a consistent order.
2020-03-04 22:25:03 +01:00
move_error_reported: BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'cx>)>,
/// This field keeps track of errors reported in the checking of uninitialized variables,
2018-07-06 22:25:40 +02:00
/// so that we don't report seemingly duplicate errors.
2020-03-04 22:25:03 +01:00
uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>,
/// Errors to be reported buffer
errors_buffer: Vec<Diagnostic>,
/// This field keeps track of all the local variables that are declared mut and are mutated.
/// Used for the warning issued by an unused mutable local variable.
used_mut: FxHashSet<Local>,
/// If the function we're checking is a closure, then we'll need to report back the list of
/// mutable upvars that have been used. This field keeps track of them.
used_mut_upvars: SmallVec<[Field; 8]>,
2019-12-29 03:02:20 +01:00
/// Region inference context. This contains the results from region inference and lets us e.g.
/// find out which CFG points are contained in each borrow region.
2019-12-29 03:02:20 +01:00
regioncx: Rc<RegionInferenceContext<'tcx>>,
/// The set of borrows extracted from the MIR
borrow_set: Rc<BorrowSet<'tcx>>,
/// Dominators for MIR
dominators: Dominators<BasicBlock>,
/// Information about upvars not necessarily preserved in types or MIR
2020-12-13 06:11:15 +01:00
upvars: Vec<Upvar<'tcx>>,
/// Names of local (user) variables (extracted from `var_debug_info`).
2020-04-19 13:00:18 +02:00
local_names: IndexVec<Local, Option<Symbol>>,
2019-12-29 03:36:42 +01:00
/// Record the region names generated for each region in the given
/// MIR def so that we can reuse them later in help/error messages.
region_names: RefCell<FxHashMap<RegionVid, RegionName>>,
/// The counter for generating new region names.
next_region_name: RefCell<usize>,
/// Results of Polonius analysis.
polonius_output: Option<Rc<PoloniusOutput>>,
}
// Check that:
// 1. assignments are always made to mutable locations (FIXME: does that still really go here?)
// 2. loans made in overlapping scopes do not conflict
// 3. assignments do not affect things loaned out as immutable
// 4. moves do not affect things loaned out in any way
impl<'cx, 'tcx> dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> {
2019-06-13 23:48:52 +02:00
type FlowState = Flows<'cx, 'tcx>;
2020-03-22 20:09:40 +01:00
fn visit_statement_before_primary_effect(
2017-11-17 10:47:02 +01:00
&mut self,
flow_state: &Flows<'cx, 'tcx>,
stmt: &'cx Statement<'tcx>,
location: Location,
2017-11-17 10:47:02 +01:00
) {
debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
let span = stmt.source_info.span;
self.check_activations(location, span, flow_state);
2020-03-30 22:49:33 +02:00
match &stmt.kind {
StatementKind::Assign(box (lhs, ref rhs)) => {
2019-12-22 23:42:04 +01:00
self.consume_rvalue(location, (rhs, span), flow_state);
2020-03-30 22:49:33 +02:00
self.mutate_place(location, (*lhs, span), Shallow(None), JustWrite, flow_state);
}
StatementKind::FakeRead(_, box ref place) => {
// Read for match doesn't access any memory and is used to
// assert that a place is safe and live. So we don't have to
// do any checks here.
//
// FIXME: Remove check that the place is initialized. This is
// needed for now because matches don't have never patterns yet.
// So this is the only place we prevent
// let x: !;
// match x {};
// from compiling.
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
2018-06-22 05:10:52 +02:00
flow_state,
);
}
2020-03-30 22:49:33 +02:00
StatementKind::SetDiscriminant { place, variant_index: _ } => {
self.mutate_place(location, (**place, span), Shallow(None), JustWrite, flow_state);
}
StatementKind::LlvmInlineAsm(ref asm) => {
for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
if o.is_indirect {
// FIXME(eddyb) indirect inline asm outputs should
// be encoded through MIR place derefs instead.
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2020-03-30 22:49:33 +02:00
(*output, o.span),
2017-11-17 10:47:02 +01:00
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
flow_state,
);
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use,
(output.as_ref(), o.span),
2017-11-17 10:47:02 +01:00
flow_state,
);
} else {
2017-11-17 10:47:02 +01:00
self.mutate_place(
2019-05-01 23:03:17 +02:00
location,
2020-03-30 22:49:33 +02:00
(*output, o.span),
if o.is_rw { Deep } else { Shallow(None) },
2017-11-17 10:47:02 +01:00
if o.is_rw { WriteAndRead } else { JustWrite },
flow_state,
);
}
}
for (_, input) in asm.inputs.iter() {
2019-05-01 23:03:17 +02:00
self.consume_operand(location, (input, span), flow_state);
}
}
2018-06-22 05:10:52 +02:00
StatementKind::Nop
| StatementKind::Coverage(..)
| StatementKind::AscribeUserType(..)
| StatementKind::Retag { .. }
2018-06-22 05:10:52 +02:00
| StatementKind::StorageLive(..) => {
// `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
// to borrow check.
}
StatementKind::StorageDead(local) => {
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2020-03-30 22:49:33 +02:00
(Place::from(*local), span),
(Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
LocalMutationIsAllowed::Yes,
2017-11-17 10:47:02 +01:00
flow_state,
);
}
}
}
2020-03-22 20:09:40 +01:00
fn visit_terminator_before_primary_effect(
2017-11-17 10:47:02 +01:00
&mut self,
flow_state: &Flows<'cx, 'tcx>,
term: &'cx Terminator<'tcx>,
loc: Location,
2017-11-17 10:47:02 +01:00
) {
debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
let span = term.source_info.span;
self.check_activations(loc, span, flow_state);
match term.kind {
TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
2019-05-01 23:03:17 +02:00
self.consume_operand(loc, (discr, span), flow_state);
}
2020-10-21 23:52:41 +02:00
TerminatorKind::Drop { place, target: _, unwind: _ } => {
2019-12-22 23:42:04 +01:00
debug!(
"visit_terminator_drop \
2020-10-21 23:52:41 +02:00
loc: {:?} term: {:?} place: {:?} span: {:?}",
loc, term, place, span
2019-12-22 23:42:04 +01:00
);
Special-case `Box` in `rustc_mir::borrow_check`. This should address issue 45696. Since we know dropping a box will not access any `&mut` or `&` references, it is safe to model its destructor as only touching the contents *owned* by the box. Note: At some point we may want to generalize this machinery to other reference and collection types that are "pure" in the same sense as box. If we add a `&move` reference type, it would probably also fall into this branch of code. But for the short term, we will be conservative and restrict this change to `Box<T>` alone. The code works by recursively descending a deref of the `Box`. We prevent `visit_terminator_drop` infinite-loop (which can arise in a very obscure scenario) via a linked-list of seen types. Note: A similar style stack-only linked-list definition can be found in `rustc_mir::borrow_check::places_conflict`. It might be good at some point in the future to unify the two types and put the resulting definition into `librustc_data_structures/`. ---- One final note: Review feedback led to significant simplification of logic here. During review, eddyb RalfJung and I uncovered the heart of why I needed a so-called "step 2" aka the Shallow Write to the Deref of the box. It was because the `visit_terminator_drop`, in its base case, will not emit any write at all (shallow or deep) to a place unless that place has a need_drop. So I was encoding a Shallow Write by hand for a `Box<T>`, as a separate step from recursively descending through `*a_box` (which was at the time known as "step 1"; it is now the *only* step, apart from the change to the base case for `visit_terminator_drop` that this commit now has encoded). eddyb aruged that *something* should be emitting some sort of write in the base case here (even a shallow one), of the dropped place, since by analogy we also emit a write when you *move* a place. That led to the revision here in this commit. * (Its possible that this desired write should be attached in some manner to StorageDead instead of Drop. But in this PR, I tried to leave the StorageDead logic alone and focus my attention solely on how Drop(x) is modelled in MIR-borrowck.)
2018-07-26 22:29:50 +02:00
self.access_place(
2019-05-01 23:03:17 +02:00
loc,
2020-10-21 23:52:41 +02:00
(place, span),
(AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
LocalMutationIsAllowed::Yes,
flow_state,
);
}
2017-11-17 10:47:02 +01:00
TerminatorKind::DropAndReplace {
place: drop_place,
2017-11-17 10:47:02 +01:00
value: ref new_value,
target: _,
unwind: _,
} => {
2019-12-22 23:42:04 +01:00
self.mutate_place(loc, (drop_place, span), Deep, JustWrite, flow_state);
self.consume_operand(loc, (new_value, span), flow_state);
}
2017-11-17 10:47:02 +01:00
TerminatorKind::Call {
ref func,
ref args,
ref destination,
cleanup: _,
from_hir_call: _,
fn_span: _,
2017-11-17 10:47:02 +01:00
} => {
2019-05-01 23:03:17 +02:00
self.consume_operand(loc, (func, span), flow_state);
for arg in args {
2019-12-22 23:42:04 +01:00
self.consume_operand(loc, (arg, span), flow_state);
}
2020-03-30 22:49:33 +02:00
if let Some((dest, _ /*bb*/)) = *destination {
2019-12-22 23:42:04 +01:00
self.mutate_place(loc, (dest, span), Deep, JustWrite, flow_state);
}
}
2019-12-22 23:42:04 +01:00
TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
2019-05-01 23:03:17 +02:00
self.consume_operand(loc, (cond, span), flow_state);
2020-03-29 16:41:09 +02:00
use rustc_middle::mir::AssertKind;
2020-02-12 19:40:31 +01:00
if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
2019-05-01 23:03:17 +02:00
self.consume_operand(loc, (len, span), flow_state);
self.consume_operand(loc, (index, span), flow_state);
}
}
2020-03-30 22:49:33 +02:00
TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => {
2019-05-01 23:03:17 +02:00
self.consume_operand(loc, (value, span), flow_state);
self.mutate_place(loc, (resume_arg, span), Deep, JustWrite, flow_state);
}
2020-05-26 21:07:59 +02:00
TerminatorKind::InlineAsm {
template: _,
ref operands,
options: _,
line_spans: _,
destination: _,
} => {
2020-02-14 19:17:50 +01:00
for op in operands {
match *op {
InlineAsmOperand::In { reg: _, ref value }
| InlineAsmOperand::Const { ref value } => {
self.consume_operand(loc, (value, span), flow_state);
}
InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
if let Some(place) = place {
self.mutate_place(
loc,
(place, span),
Shallow(None),
JustWrite,
flow_state,
);
}
}
InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
self.consume_operand(loc, (in_value, span), flow_state);
if let Some(out_place) = out_place {
self.mutate_place(
loc,
(out_place, span),
Shallow(None),
JustWrite,
flow_state,
);
}
}
InlineAsmOperand::SymFn { value: _ }
| InlineAsmOperand::SymStatic { def_id: _ } => {}
2020-02-14 19:17:50 +01:00
}
}
}
TerminatorKind::Goto { target: _ }
| TerminatorKind::Abort
| TerminatorKind::Unreachable
| TerminatorKind::Resume
| TerminatorKind::Return
| TerminatorKind::GeneratorDrop
2020-06-02 09:15:24 +02:00
| TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
| TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
// no data used, thus irrelevant to borrowck
}
}
}
2020-03-22 20:09:40 +01:00
fn visit_terminator_after_primary_effect(
&mut self,
flow_state: &Flows<'cx, 'tcx>,
term: &'cx Terminator<'tcx>,
loc: Location,
) {
let span = term.source_info.span;
match term.kind {
TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => {
if self.movable_generator {
// Look for any active borrows to locals
let borrow_set = self.borrow_set.clone();
for i in flow_state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_local_borrow(borrow, span);
}
}
2017-08-16 22:05:48 +02:00
}
2017-11-17 10:47:02 +01:00
TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
// Returning from the function implicitly kills storage for all locals and statics.
// Often, the storage will already have been killed by an explicit
// StorageDead, but we don't always emit those (notably on unwind paths),
// so this "extra check" serves as a kind of backup.
let borrow_set = self.borrow_set.clone();
for i in flow_state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_invalidation_at_exit(loc, borrow, span);
}
}
2020-02-11 21:04:46 +01:00
TerminatorKind::Abort
| TerminatorKind::Assert { .. }
| TerminatorKind::Call { .. }
| TerminatorKind::Drop { .. }
| TerminatorKind::DropAndReplace { .. }
2020-06-02 09:15:24 +02:00
| TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
2020-02-11 21:04:46 +01:00
| TerminatorKind::FalseUnwind { real_target: _, unwind: _ }
| TerminatorKind::Goto { .. }
| TerminatorKind::SwitchInt { .. }
2020-02-14 19:17:50 +01:00
| TerminatorKind::Unreachable
| TerminatorKind::InlineAsm { .. } => {}
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
2017-11-17 10:47:02 +01:00
enum MutateMode {
JustWrite,
WriteAndRead,
}
use self::AccessDepth::{Deep, Shallow};
2019-12-22 23:42:04 +01:00
use self::ReadOrWrite::{Activation, Read, Reservation, Write};
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ArtificialField {
ArrayLength,
ShallowBorrow,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum AccessDepth {
/// From the RFC: "A *shallow* access means that the immediate
/// fields reached at P are accessed, but references or pointers
/// found within are not dereferenced. Right now, the only access
/// that is shallow is an assignment like `x = ...;`, which would
/// be a *shallow write* of `x`."
Shallow(Option<ArtificialField>),
/// From the RFC: "A *deep* access means that all data reachable
/// through the given place may be invalidated or accesses by
/// this action."
Deep,
/// Access is Deep only when there is a Drop implementation that
/// can reach the data behind the reference.
Drop,
}
/// Kind of access to a value: read or write
/// (For informational purposes only)
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ReadOrWrite {
/// From the RFC: "A *read* means that the existing data may be
/// read, but will not be changed."
Read(ReadKind),
/// From the RFC: "A *write* means that the data may be mutated to
/// new values or otherwise invalidated (for example, it could be
/// de-initialized, as in a move operation).
Write(WriteKind),
/// For two-phase borrows, we distinguish a reservation (which is treated
/// like a Read) from an activation (which is treated like a write), and
/// each of those is furthermore distinguished from Reads/Writes above.
Reservation(WriteKind),
Activation(WriteKind, BorrowIndex),
}
/// Kind of read access to a value
/// (For informational purposes only)
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum ReadKind {
Borrow(BorrowKind),
Copy,
}
/// Kind of write access to a value
/// (For informational purposes only)
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum WriteKind {
StorageDeadOrDrop,
MutableBorrow(BorrowKind),
Mutate,
Move,
}
/// When checking permissions for a place access, this flag is used to indicate that an immutable
/// local place can be mutated.
2019-02-08 14:53:55 +01:00
//
// FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications:
// - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`.
// - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and
// `is_declared_mutable()`.
// - Take flow state into consideration in `is_assignable()` for local variables.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum LocalMutationIsAllowed {
Yes,
/// We want use of immutable upvars to cause a "write to immutable upvar"
/// error, not an "reassignment" error.
ExceptUpvars,
2017-12-14 13:33:29 +01:00
No,
}
#[derive(Copy, Clone, Debug)]
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
enum InitializationRequiringAction {
Update,
Borrow,
MatchOn,
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
Use,
Assignment,
PartialAssignment,
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
}
struct RootPlace<'tcx> {
place_local: Local,
place_projection: &'tcx [PlaceElem<'tcx>],
is_local_mutation_allowed: LocalMutationIsAllowed,
}
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
impl InitializationRequiringAction {
fn as_noun(self) -> &'static str {
match self {
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Update => "update",
InitializationRequiringAction::Borrow => "borrow",
InitializationRequiringAction::MatchOn => "use", // no good noun
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use => "use",
InitializationRequiringAction::Assignment => "assign",
InitializationRequiringAction::PartialAssignment => "assign to part",
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
}
}
fn as_verb_in_past_tense(self) -> &'static str {
match self {
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Update => "updated",
InitializationRequiringAction::Borrow => "borrowed",
InitializationRequiringAction::MatchOn => "matched on",
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use => "used",
InitializationRequiringAction::Assignment => "assigned",
InitializationRequiringAction::PartialAssignment => "partially assigned",
MIR: Fix value moved diagnose messages MIR: adopt borrowck test Fix trailing whitespace span_bug! on unexpected action Make RegionVid use newtype_index! Closes #45843 Check rvalue aggregates during check_stmt in tycheck, add initial, (not passing) test Fix failing test Remove attributes and test comments accidentally left behind, add in span_mirbugs Normalize LvalueTy for ops and format code to satisfy tidy check only normalize operand types when in an ADT constructor avoid early return handle the active field index in unions normalize types in ADT constructor Fixes #45940 Fix borrowck compiler errors for upvars contain "spurious" dereferences Fixes #46003 added associated function Box::leak Box::leak - improve documentation Box::leak - fixed bug in documentation Box::leak - relaxed constraints wrt. lifetimes Box::leak - updated documentation Box::leak - made an oops, fixed now =) Box::leak: update unstable issue number (46179). Add test for #44953 Add missing Debug impls to std_unicode Also adds #![deny(missing_debug_implementations)] so they don't get missed again. Amend RELEASES for 1.22.1 and fix the date for 1.22.0 Rename param in `[T]::swap_with_slice` from `src` to `other`. The idea of ‘source’ and ‘destination’ aren’t very applicable for this operation since both slices can both be considered sources and destinations. Clarify stdin behavior of `Command::output`. Fixes #44929. Add hints for the case of confusing enum with its variants Add failing testcases Add module population and case of enum in place of expression Use for_each_child_stable in find_module Use multiline text for crate conflict diagnostics Make float::from_bits transmute (and update the documentation to reflect this). The current implementation/documentation was made to avoid sNaN because of potential safety issues implied by old/bad LLVM documentation. These issues aren't real, so we can just make the implementation transmute (as permitted by the existing documentation of this method). Also the documentation didn't actually match the behaviour: it said we may change sNaNs, but in fact we canonicalized *all* NaNs. Also an example in the documentation was wrong: it said we *always* change sNaNs, when the documentation was explicitly written to indicate it was implementation-defined. This makes to_bits and from_bits perfectly roundtrip cross-platform, except for one caveat: although the 2008 edition of IEEE-754 specifies how to interpet the signaling bit, earlier editions didn't. This lead to some platforms picking the opposite interpretation, so all signaling NaNs on x86/ARM are quiet on MIPS, and vice-versa. NaN-boxing is a fairly important optimization, while we don't even guarantee that float operations properly preserve signalingness. As such, this seems like the more natural strategy to take (as opposed to trying to mangle the signaling bit on a per-platform basis). This implementation is also, of course, faster. Simplify an Iterator::fold to Iterator::any This method of once-diagnostics doesn't allow nesting UI tests extract the regular output from the 'rendered' field in json Merge cfail and ui tests into ui tests Add a MIR pass to lower 128-bit operators to lang item calls Runs only with `-Z lower_128bit_ops` since it's not hooked into targets yet. Include tuple projections in MIR tests Add type checking for the lang item As part of doing so, add more lang items instead of passing u128 to the i128 ones where it doesn't matter in twos-complement. Handle shifts properly * The overflow-checking shift items need to take a full 128-bit type, since they need to be able to detect idiocy like `1i128 << (1u128 << 127)` * The unchecked ones just take u32, like the `*_sh?` methods in core * Because shift-by-anything is allowed, cast into a new local for every shift incr.comp.: Make sure we don't lose unused green results from the query cache. rustbuild: Update LLVM and enable ThinLTO This commit updates LLVM to fix #45511 (https://reviews.llvm.org/D39981) and also reenables ThinLTO for libtest now that we shouldn't hit #45768. This also opportunistically enables ThinLTO for libstd which was previously blocked (#45661) on test failures related to debuginfo with a presumed cause of #45511. Closes #45511 std: Flag Windows TLS dtor symbol as #[used] Turns out ThinLTO was internalizing this symbol and eliminating it. Worse yet if you compiled with LTO turns out no TLS destructors would run on Windows! The `#[used]` annotation should be a more bulletproof implementation (in the face of LTO) of preserving this symbol all the way through in LLVM and ensuring it makes it all the way to the linker which will take care of it. Add enum InitializationRequiringAction Fix tidy tests
2017-11-23 12:36:48 +01:00
}
}
}
2019-06-13 23:48:52 +02:00
impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn body(&self) -> &'cx Body<'tcx> {
2020-04-12 19:28:41 +02:00
self.body
}
/// Checks an access to the given place to see if it is allowed. Examines the set of borrows
2017-11-17 01:09:18 +01:00
/// that are in scope, as well as which paths have been initialized, to ensure that (a) the
/// place is initialized and (b) it is not borrowed in some way that would prevent this
2017-11-17 01:09:18 +01:00
/// access.
///
2019-02-08 14:53:55 +01:00
/// Returns `true` if an error is reported.
2017-11-17 10:47:02 +01:00
fn access_place(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2020-03-30 22:49:33 +02:00
place_span: (Place<'tcx>, Span),
kind: (AccessDepth, ReadOrWrite),
2017-11-17 10:47:02 +01:00
is_local_mutation_allowed: LocalMutationIsAllowed,
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2018-08-10 23:34:56 +02:00
) {
let (sd, rw) = kind;
if let Activation(_, borrow_index) = rw {
if self.reservation_error_reported.contains(&place_span.0) {
2018-03-06 06:29:03 +01:00
debug!(
"skipping access_place for activation of invalid reservation \
place: {:?} borrow_index: {:?}",
place_span.0, borrow_index
);
2018-08-10 23:34:56 +02:00
return;
}
}
// Check is_empty() first because it's the common case, and doing that
// way we avoid the clone() call.
2019-12-22 23:42:04 +01:00
if !self.access_place_error_reported.is_empty()
2020-03-30 22:49:33 +02:00
&& self.access_place_error_reported.contains(&(place_span.0, place_span.1))
2018-03-06 06:29:03 +01:00
{
debug!(
"access_place: suppressing error place_span=`{:?}` kind=`{:?}`",
place_span, kind
);
2018-08-10 23:34:56 +02:00
return;
}
2019-12-22 23:42:04 +01:00
let mutability_error = self.check_access_permissions(
place_span,
rw,
is_local_mutation_allowed,
flow_state,
location,
);
let conflict_error =
2019-05-01 23:03:17 +02:00
self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) {
2019-11-27 04:19:54 +01:00
// Suppress this warning when there's an error being emitted for the
// same borrow: fixing the error is likely to fix the warning.
self.reservation_warnings.remove(&borrow_idx);
}
if conflict_error || mutability_error {
2019-12-22 23:42:04 +01:00
debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
2020-03-30 22:49:33 +02:00
self.access_place_error_reported.insert((place_span.0, place_span.1));
}
}
fn check_access_for_conflict(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2020-03-30 22:49:33 +02:00
place_span: (Place<'tcx>, Span),
sd: AccessDepth,
rw: ReadOrWrite,
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
) -> bool {
2018-04-07 00:03:23 +02:00
debug!(
2019-05-01 23:03:17 +02:00
"check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})",
location, place_span, sd, rw,
2018-04-07 00:03:23 +02:00
);
let mut error_reported = false;
let tcx = self.infcx.tcx;
let body = self.body;
let borrow_set = self.borrow_set.clone();
// Use polonius output if it has been enabled.
let polonius_output = self.polonius_output.clone();
let borrows_in_scope = if let Some(polonius) = &polonius_output {
let location = self.location_table.start_index(location);
Either::Left(polonius.errors_at(location).iter().copied())
} else {
Either::Right(flow_state.borrows.iter())
};
each_borrow_involving_path(
self,
tcx,
body,
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
(sd, place_span.0),
&borrow_set,
borrows_in_scope,
2018-06-22 05:10:52 +02:00
|this, borrow_index, borrow| match (rw, borrow.kind) {
// Obviously an activation is compatible with its own
// reservation (or even prior activating uses of same
// borrow); so don't check if they interfere.
//
// NOTE: *reservations* do conflict with themselves;
// thus aren't injecting unsoundenss w/ this check.)
(Activation(_, activating), _) if activating == borrow_index => {
2017-12-14 13:33:29 +01:00
debug!(
"check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \
skipping {:?} b/c activation of same borrow_index",
2017-12-14 13:33:29 +01:00
place_span,
sd,
rw,
(borrow_index, borrow),
2017-12-14 13:33:29 +01:00
);
Control::Continue
}
(Read(_), BorrowKind::Shared | BorrowKind::Shallow)
| (
Read(ReadKind::Borrow(BorrowKind::Shallow)),
BorrowKind::Unique | BorrowKind::Mut { .. },
) => Control::Continue,
(Write(WriteKind::Move), BorrowKind::Shallow) => {
// Handled by initialization checks.
2017-12-14 13:33:29 +01:00
Control::Continue
}
(Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
// Reading from mere reservations of mutable-borrows is OK.
2019-05-01 23:03:17 +02:00
if !is_active(&this.dominators, borrow, location) {
assert!(allow_two_phase_borrow(borrow.kind));
return Control::Continue;
}
error_reported = true;
2017-11-17 10:47:02 +01:00
match kind {
2019-12-22 23:42:04 +01:00
ReadKind::Copy => {
2019-05-01 23:03:17 +02:00
this.report_use_while_mutably_borrowed(location, place_span, borrow)
.buffer(&mut this.errors_buffer);
2017-11-17 10:47:02 +01:00
}
ReadKind::Borrow(bk) => {
2019-05-01 23:03:17 +02:00
this.report_conflicting_borrow(location, place_span, bk, borrow)
.buffer(&mut this.errors_buffer);
}
}
2017-11-17 10:47:02 +01:00
Control::Break
}
(
Reservation(WriteKind::MutableBorrow(bk)),
BorrowKind::Shallow | BorrowKind::Shared,
2020-08-08 05:47:33 +02:00
) if { tcx.migrate_borrowck() && this.borrow_set.contains(&location) } => {
let bi = this.borrow_set.get_index_of(&location).unwrap();
debug!(
"recording invalid reservation of place: {:?} with \
borrow index {:?} as warning",
2019-12-22 23:42:04 +01:00
place_span.0, bi,
);
// rust-lang/rust#56254 - This was previously permitted on
// the 2018 edition so we emit it as a warning. We buffer
// these sepately so that we only emit a warning if borrow
// checking was otherwise successful.
this.reservation_warnings
2020-03-30 22:49:33 +02:00
.insert(bi, (place_span.0, place_span.1, location, bk, borrow.clone()));
// Don't suppress actual errors.
Control::Continue
}
(Reservation(kind) | Activation(kind, _) | Write(kind), _) => {
match rw {
Reservation(..) => {
2017-12-14 13:33:29 +01:00
debug!(
"recording invalid reservation of \
place: {:?}",
place_span.0
);
this.reservation_error_reported.insert(place_span.0);
2018-03-06 06:29:03 +01:00
}
Activation(_, activating) => {
2017-12-14 13:33:29 +01:00
debug!(
"observing check_place for activation of \
borrow_index: {:?}",
activating
);
2018-03-06 06:29:03 +01:00
}
Read(..) | Write(..) => {}
}
error_reported = true;
2017-11-17 10:47:02 +01:00
match kind {
WriteKind::MutableBorrow(bk) => {
2019-05-01 23:03:17 +02:00
this.report_conflicting_borrow(location, place_span, bk, borrow)
.buffer(&mut this.errors_buffer);
2017-11-17 10:47:02 +01:00
}
2019-12-22 23:42:04 +01:00
WriteKind::StorageDeadOrDrop => this
.report_borrowed_value_does_not_live_long_enough(
2019-05-01 23:03:17 +02:00
location,
2017-12-14 13:33:29 +01:00
borrow,
place_span,
2019-12-22 23:42:04 +01:00
Some(kind),
),
2017-11-17 10:47:02 +01:00
WriteKind::Mutate => {
2019-05-01 23:03:17 +02:00
this.report_illegal_mutation_of_borrowed(location, place_span, borrow)
2017-11-17 10:47:02 +01:00
}
WriteKind::Move => {
2019-05-01 23:03:17 +02:00
this.report_move_out_while_borrowed(location, place_span, borrow)
}
}
2017-11-17 10:47:02 +01:00
Control::Break
}
2017-11-17 10:47:02 +01:00
},
);
error_reported
}
2017-11-17 10:47:02 +01:00
fn mutate_place(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2020-03-30 22:49:33 +02:00
place_span: (Place<'tcx>, Span),
kind: AccessDepth,
2017-11-17 10:47:02 +01:00
mode: MutateMode,
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
// Write of P[i] or *P, or WriteAndRead of any P, requires P init'd.
match mode {
MutateMode::WriteAndRead => {
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Update,
(place_span.0.as_ref(), place_span.1),
2017-11-17 10:47:02 +01:00
flow_state,
);
}
MutateMode::JustWrite => {
2019-05-01 23:03:17 +02:00
self.check_if_assigned_path_is_moved(location, place_span, flow_state);
}
}
2018-08-10 23:34:56 +02:00
// Special case: you can assign a immutable local variable
// (e.g., `x = ...`) so long as it has never been initialized
// before (at this point in the flow).
if let Some(local) = place_span.0.as_local() {
if let Mutability::Not = self.body.local_decls[local].mutability {
2018-08-10 23:34:56 +02:00
// check for reassignments to immutable local variables
self.check_if_reassignment_to_immutable_state(
2019-12-22 23:42:04 +01:00
location, local, place_span, flow_state,
);
2018-08-10 23:34:56 +02:00
return;
}
}
// Otherwise, use the normal access permission rules.
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
place_span,
(kind, Write(WriteKind::Mutate)),
2018-08-10 23:34:56 +02:00
LocalMutationIsAllowed::No,
2017-11-17 10:47:02 +01:00
flow_state,
);
}
2017-11-17 10:47:02 +01:00
fn consume_rvalue(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
(rvalue, span): (&'cx Rvalue<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
match *rvalue {
2020-03-30 22:49:33 +02:00
Rvalue::Ref(_ /*rgn*/, bk, place) => {
let access_kind = match bk {
BorrowKind::Shallow => {
(Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
2019-12-22 23:42:04 +01:00
}
BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
BorrowKind::Unique | BorrowKind::Mut { .. } => {
let wk = WriteKind::MutableBorrow(bk);
if allow_two_phase_borrow(bk) {
(Deep, Reservation(wk))
} else {
(Deep, Write(wk))
}
2017-11-17 10:47:02 +01:00
}
};
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
(place, span),
access_kind,
LocalMutationIsAllowed::No,
flow_state,
);
let action = if bk == BorrowKind::Shallow {
InitializationRequiringAction::MatchOn
} else {
InitializationRequiringAction::Borrow
};
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
action,
(place.as_ref(), span),
2017-11-17 10:47:02 +01:00
flow_state,
);
}
2020-03-30 22:49:33 +02:00
Rvalue::AddressOf(mutability, place) => {
let access_kind = match mutability {
2019-12-22 23:42:04 +01:00
Mutability::Mut => (
Deep,
Write(WriteKind::MutableBorrow(BorrowKind::Mut {
allow_two_phase_borrow: false,
})),
),
Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
};
self.access_place(
location,
(place, span),
access_kind,
LocalMutationIsAllowed::No,
flow_state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Borrow,
(place.as_ref(), span),
flow_state,
);
}
2020-05-02 21:44:25 +02:00
Rvalue::ThreadLocalRef(_) => {}
2017-12-14 13:33:29 +01:00
Rvalue::Use(ref operand)
| Rvalue::Repeat(ref operand, _)
| Rvalue::UnaryOp(_ /*un_op*/, ref operand)
| Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
2019-05-01 23:03:17 +02:00
self.consume_operand(location, (operand, span), flow_state)
}
2020-03-30 22:49:33 +02:00
Rvalue::Len(place) | Rvalue::Discriminant(place) => {
let af = match *rvalue {
Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
Rvalue::Discriminant(..) => None,
_ => unreachable!(),
};
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
(place, span),
(Shallow(af), Read(ReadKind::Copy)),
2017-11-17 10:47:02 +01:00
LocalMutationIsAllowed::No,
flow_state,
);
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use,
(place.as_ref(), span),
2017-11-17 10:47:02 +01:00
flow_state,
);
}
2017-12-14 13:33:29 +01:00
Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
| Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
2019-05-01 23:03:17 +02:00
self.consume_operand(location, (operand1, span), flow_state);
self.consume_operand(location, (operand2, span), flow_state);
}
Rvalue::NullaryOp(_op, _ty) => {
// nullary ops take no dynamic input; no borrowck effect.
//
// FIXME: is above actually true? Do we want to track
// the fact that uninitialized data can be created via
// `NullOp::Box`?
}
Rvalue::Aggregate(ref aggregate_kind, ref operands) => {
// We need to report back the list of mutable upvars that were
// moved into the closure and subsequently used by the closure,
// in order to populate our used_mut set.
2018-07-03 21:12:09 +02:00
match **aggregate_kind {
2019-12-22 23:42:04 +01:00
AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => {
let BorrowCheckResult { used_mut_upvars, .. } =
self.infcx.tcx.mir_borrowck(def_id.expect_local());
2018-07-03 21:12:09 +02:00
debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
for field in used_mut_upvars {
self.propagate_closure_used_mut_upvar(&operands[field.index()]);
}
}
2018-07-03 21:12:09 +02:00
AggregateKind::Adt(..)
| AggregateKind::Array(..)
| AggregateKind::Tuple { .. } => (),
}
for operand in operands {
2019-05-01 23:03:17 +02:00
self.consume_operand(location, (operand, span), flow_state);
}
}
}
}
fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) {
let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| {
2021-01-29 22:01:27 +01:00
// We have three possibilities here:
// a. We are modifying something through a mut-ref
// b. We are modifying something that is local to our parent
2021-01-29 22:01:27 +01:00
// c. Current body is a nested closure, and we are modifying path starting from
// a Place captured by our parent closure.
// Handle (c), the path being modified is exactly the path captured by our parent
if let Some(field) = this.is_upvar_field_projection(place.as_ref()) {
this.used_mut_upvars.push(field);
return;
}
for (place_ref, proj) in place.iter_projections().rev() {
// Handle (a)
if proj == ProjectionElem::Deref {
match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() {
// We aren't modifying a variable directly
ty::Ref(_, _, hir::Mutability::Mut) => return,
_ => {}
}
}
// Handle (c)
if let Some(field) = this.is_upvar_field_projection(place_ref) {
this.used_mut_upvars.push(field);
return;
}
}
// Handle(b)
this.used_mut.insert(place.local);
};
// This relies on the current way that by-value
// captures of a closure are copied/moved directly
// when generating MIR.
match *operand {
Operand::Move(place) | Operand::Copy(place) => {
match place.as_local() {
Some(local) if !self.body.local_decls[local].is_user_variable() => {
if self.body.local_decls[local].ty.is_mutable_ptr() {
// The variable will be marked as mutable by the borrow.
return;
}
// This is an edge case where we have a `move` closure
// inside a non-move closure, and the inner closure
// contains a mutation:
//
// let mut i = 0;
// || { move || { i += 1; }; };
//
// In this case our usual strategy of assuming that the
// variable will be captured by mutable reference is
// wrong, since `i` can be copied into the inner
// closure from a shared reference.
//
// As such we have to search for the local that this
// capture comes from and mark it as being used as mut.
let temp_mpi = self.move_data.rev_lookup.find_local(local);
let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] {
&self.move_data.inits[init_index]
} else {
bug!("temporary should be initialized exactly once")
};
let loc = match init.location {
InitLocation::Statement(stmt) => stmt,
_ => bug!("temporary initialized in arguments"),
};
let body = self.body;
let bbd = &body[loc.block];
let stmt = &bbd.statements[loc.statement_index];
debug!("temporary assigned in: stmt={:?}", stmt);
if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind
{
propagate_closure_used_mut_place(self, source);
} else {
bug!(
"closures should only capture user variables \
or references to user variables"
);
}
}
_ => propagate_closure_used_mut_place(self, place),
}
}
Operand::Constant(..) => {}
}
}
2017-11-17 10:47:02 +01:00
fn consume_operand(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
(operand, span): (&'cx Operand<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
match *operand {
2020-03-30 22:49:33 +02:00
Operand::Copy(place) => {
// copy of place: check if this is "copy of frozen path"
// (FIXME: see check_loans.rs)
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
flow_state,
);
// Finally, check if path was already moved.
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use,
(place.as_ref(), span),
2017-11-17 10:47:02 +01:00
flow_state,
);
}
2020-03-30 22:49:33 +02:00
Operand::Move(place) => {
// move of place: check if this is move of already borrowed path
2017-11-17 10:47:02 +01:00
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
(place, span),
(Deep, Write(WriteKind::Move)),
LocalMutationIsAllowed::Yes,
2017-11-17 10:47:02 +01:00
flow_state,
);
// Finally, check if path was already moved.
self.check_if_path_or_subpath_is_moved(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
InitializationRequiringAction::Use,
(place.as_ref(), span),
2017-11-17 10:47:02 +01:00
flow_state,
);
}
Operand::Constant(_) => {}
}
}
/// Checks whether a borrow of this place is invalidated when the function
/// exits
2017-12-14 13:33:29 +01:00
fn check_for_invalidation_at_exit(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2017-12-14 13:33:29 +01:00
borrow: &BorrowData<'tcx>,
span: Span,
) {
debug!("check_for_invalidation_at_exit({:?})", borrow);
2020-03-30 22:49:33 +02:00
let place = borrow.borrowed_place;
let mut root_place = PlaceRef { local: place.local, projection: &[] };
// FIXME(nll-rfc#40): do more precise destructor tracking here. For now
// we just know that all locals are dropped at function exit (otherwise
// we'll have a memory leak) and assume that all statics have a destructor.
//
2017-12-05 23:51:47 +01:00
// FIXME: allow thread-locals to borrow other thread locals?
let (might_be_alive, will_be_dropped) =
if self.body.local_decls[root_place.local].is_ref_to_thread_local() {
// Thread-locals might be dropped after the function exits
// We have to dereference the outer reference because
// borrows don't conflict behind shared references.
root_place.projection = DEREF_PROJECTION;
(true, true)
} else {
(false, self.locals_are_invalidated_at_exit)
};
if !will_be_dropped {
2019-12-22 23:42:04 +01:00
debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place);
return;
}
2017-12-14 13:33:29 +01:00
let sd = if might_be_alive { Deep } else { Shallow(None) };
if places_conflict::borrow_conflicts_with_place(
self.infcx.tcx,
&self.body,
place,
borrow.kind,
root_place,
sd,
places_conflict::PlaceConflictBias::Overlap,
) {
debug!("check_for_invalidation_at_exit({:?}): INVALID", place);
// FIXME: should be talking about the region lifetime instead
// of just a span here.
let span = self.infcx.tcx.sess.source_map().end_point(span);
self.report_borrowed_value_does_not_live_long_enough(
2019-05-01 23:03:17 +02:00
location,
borrow,
(place, span),
None,
)
2017-12-03 16:55:41 +01:00
}
}
/// Reports an error if this is a borrow of local data.
/// This is called for all Yield expressions on movable generators
2018-03-06 06:29:03 +01:00
fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) {
debug!("check_for_local_borrow({:?})", borrow);
if borrow_of_local_data(borrow.borrowed_place) {
let err = self.cannot_borrow_across_generator_yield(
2019-12-22 23:42:04 +01:00
self.retrieve_borrow_spans(borrow).var_or_use(),
yield_span,
);
err.buffer(&mut self.errors_buffer);
}
}
fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) {
// Two-phase borrow support: For each activation that is newly
// generated at this statement, check if it interferes with
// another borrow.
let borrow_set = self.borrow_set.clone();
for &borrow_index in borrow_set.activations_at_location(location) {
let borrow = &borrow_set[borrow_index];
// only mutable borrows should be 2-phase
assert!(match borrow.kind {
BorrowKind::Shared | BorrowKind::Shallow => false,
BorrowKind::Unique | BorrowKind::Mut { .. } => true,
});
self.access_place(
2019-05-01 23:03:17 +02:00
location,
2020-03-30 22:49:33 +02:00
(borrow.borrowed_place, span),
2019-12-22 23:42:04 +01:00
(Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
LocalMutationIsAllowed::No,
flow_state,
);
// We do not need to call `check_if_path_or_subpath_is_moved`
// again, as we already called it when we made the
// initial reservation.
}
}
2017-11-17 10:47:02 +01:00
fn check_if_reassignment_to_immutable_state(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
local: Local,
2020-03-30 22:49:33 +02:00
place_span: (Place<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
debug!("check_if_reassignment_to_immutable_state({:?})", local);
// Check if any of the initializiations of `local` have happened yet:
if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) {
// And, if so, report an error.
let init = &self.move_data.inits[init_index];
let span = init.span(&self.body);
2019-12-22 23:42:04 +01:00
self.report_illegal_reassignment(location, place_span, span, place_span.0);
}
}
2018-04-01 10:01:51 +02:00
fn check_if_full_path_is_moved(
2017-11-17 10:47:02 +01:00
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2017-11-17 10:47:02 +01:00
desired_action: InitializationRequiringAction,
2020-03-04 22:25:03 +01:00
place_span: (PlaceRef<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
let maybe_uninits = &flow_state.uninits;
// Bad scenarios:
//
// 1. Move of `a.b.c`, use of `a.b.c`
// 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`)
// 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with
// partial initialization support, one might have `a.x`
// initialized but not `a.b`.
//
// OK scenarios:
//
// 4. Move of `a.b.c`, use of `a.b.d`
// 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
// 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
// must have been initialized for the use to be sound.
// 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
// The dataflow tracks shallow prefixes distinctly (that is,
// field-accesses on P distinctly from P itself), in order to
// track substructure initialization separately from the whole
// structure.
//
// E.g., when looking at (*a.b.c).d, if the closest prefix for
// which we have a MovePath is `a.b`, then that means that the
// initialization state of `a.b` is all we need to inspect to
// know if `a.b.c` is valid (and from that we infer that the
// dereference and `.d` access is also valid, since we assume
// `a.b.c` is assigned a reference to a initialized and
// well-formed record structure.)
// Therefore, if we seek out the *closest* prefix for which we
// have a MovePath, that should capture the initialization
// state for the place scenario.
//
// This code covers scenarios 1, 2, and 3.
2018-09-03 22:50:03 +02:00
debug!("check_if_full_path_is_moved place: {:?}", place_span.0);
2019-12-11 14:39:24 +01:00
let (prefix, mpi) = self.move_path_closest_to(place_span.0);
if maybe_uninits.contains(mpi) {
self.report_use_of_moved_or_uninitialized(
location,
desired_action,
(prefix, place_span.0, place_span.1),
mpi,
);
} // Only query longest prefix with a MovePath, not further
// ancestors; dataflow recurs on children when parents
// move (to support partial (re)inits).
//
// (I.e., querying parents breaks scenario 7; but may want
// to do such a query based on partial-init feature-gate.)
}
/// Subslices correspond to multiple move paths, so we iterate through the
/// elements of the base array. For each element we check
///
/// * Does this element overlap with our slice.
/// * Is any part of it uninitialized.
fn check_if_subslice_element_is_moved(
&mut self,
location: Location,
desired_action: InitializationRequiringAction,
2020-03-04 22:25:03 +01:00
place_span: (PlaceRef<'tcx>, Span),
maybe_uninits: &BitSet<MovePathIndex>,
2020-08-23 14:54:58 +02:00
from: u64,
to: u64,
) {
if let Some(mpi) = self.move_path_for_place(place_span.0) {
let move_paths = &self.move_data.move_paths;
let root_path = &move_paths[mpi];
for (child_mpi, child_move_path) in root_path.children(move_paths) {
let last_proj = child_move_path.place.projection.last().unwrap();
if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj {
debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`.");
if (from..to).contains(offset) {
let uninit_child =
self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| {
maybe_uninits.contains(mpi)
});
if let Some(uninit_child) = uninit_child {
self.report_use_of_moved_or_uninitialized(
location,
desired_action,
(place_span.0, place_span.0, place_span.1),
uninit_child,
);
return; // don't bother finding other problems.
}
}
}
}
}
}
fn check_if_path_or_subpath_is_moved(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
desired_action: InitializationRequiringAction,
2020-03-04 22:25:03 +01:00
place_span: (PlaceRef<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
) {
let maybe_uninits = &flow_state.uninits;
// Bad scenarios:
//
// 1. Move of `a.b.c`, use of `a` or `a.b`
// partial initialization support, one might have `a.x`
// initialized but not `a.b`.
2018-04-01 10:01:51 +02:00
// 2. All bad scenarios from `check_if_full_path_is_moved`
//
// OK scenarios:
//
// 3. Move of `a.b.c`, use of `a.b.d`
// 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b`
// 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b`
// must have been initialized for the use to be sound.
// 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
2019-05-01 23:03:17 +02:00
self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
place_span.0.last_projection()
2019-12-22 23:42:04 +01:00
{
2021-01-16 11:34:22 +01:00
let place_ty = place_base.ty(self.body(), self.infcx.tcx);
2020-08-03 00:49:11 +02:00
if let ty::Array(..) = place_ty.ty.kind() {
self.check_if_subslice_element_is_moved(
location,
desired_action,
(place_base, place_span.1),
maybe_uninits,
from,
to,
);
return;
}
}
// A move of any shallow suffix of `place` also interferes
// with an attempt to use `place`. This is scenario 3 above.
//
// (Distinct from handling of scenarios 1+2+4 above because
// `place` does not interfere with suffixes of its prefixes,
// e.g., `a.b.c` does not interfere with `a.b.d`)
//
// This code covers scenario 1.
2018-09-03 22:50:03 +02:00
debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0);
if let Some(mpi) = self.move_path_for_place(place_span.0) {
let uninit_mpi = self
.move_data
.find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi));
if let Some(uninit_mpi) = uninit_mpi {
2017-11-17 10:47:02 +01:00
self.report_use_of_moved_or_uninitialized(
2019-05-01 23:03:17 +02:00
location,
2017-11-17 10:47:02 +01:00
desired_action,
(place_span.0, place_span.0, place_span.1),
uninit_mpi,
2017-11-17 10:47:02 +01:00
);
return; // don't bother finding other problems.
}
}
}
/// Currently MoveData does not store entries for all places in
/// the input MIR. For example it will currently filter out
/// places that are Copy; thus we do not track places of shared
/// reference type. This routine will walk up a place along its
/// prefixes, searching for a foundational place that *is*
/// tracked in the MoveData.
///
/// An Err result includes a tag indicated why the search failed.
2018-02-16 15:56:50 +01:00
/// Currently this can only occur if the place is built off of a
/// static variable, as we do not track those in the MoveData.
2020-03-04 22:25:03 +01:00
fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) {
match self.move_data.rev_lookup.find(place) {
2019-12-22 23:42:04 +01:00
LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => {
2019-12-11 14:39:24 +01:00
(self.move_data.move_paths[mpi].place.as_ref(), mpi)
2019-12-22 23:42:04 +01:00
}
2019-12-11 14:39:24 +01:00
LookupResult::Parent(None) => panic!("should have move path for every Local"),
}
}
2020-03-04 22:25:03 +01:00
fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> {
// If returns None, then there is no move path corresponding
// to a direct owner of `place` (which means there is nothing
// that borrowck tracks for its analysis).
match self.move_data.rev_lookup.find(place) {
LookupResult::Parent(_) => None,
LookupResult::Exact(mpi) => Some(mpi),
}
}
2017-11-17 10:47:02 +01:00
fn check_if_assigned_path_is_moved(
&mut self,
2019-05-01 23:03:17 +02:00
location: Location,
2020-03-30 22:49:33 +02:00
(place, span): (Place<'tcx>, Span),
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
2017-11-17 10:47:02 +01:00
) {
debug!("check_if_assigned_path_is_moved place: {:?}", place);
// None case => assigning to `x` does not require `x` be initialized.
for (place_base, elem) in place.iter_projections().rev() {
match elem {
ProjectionElem::Index(_/*operand*/) |
ProjectionElem::ConstantIndex { .. } |
// assigning to P[i] requires P to be valid.
ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) =>
// assigning to (P->variant) is okay if assigning to `P` is okay
//
// FIXME: is this true even if P is a adt with a dtor?
{ }
// assigning to (*P) requires P to be initialized
ProjectionElem::Deref => {
self.check_if_full_path_is_moved(
location, InitializationRequiringAction::Use,
(place_base, span), flow_state);
// (base initialized; no need to
// recur further)
break;
}
ProjectionElem::Subslice { .. } => {
panic!("we don't allow assignments to subslices, location: {:?}",
location);
}
ProjectionElem::Field(..) => {
// if type of `P` has a dtor, then
// assigning to `P.f` requires `P` itself
// be already initialized
let tcx = self.infcx.tcx;
2021-01-16 11:34:22 +01:00
let base_ty = place_base.ty(self.body(), tcx).ty;
2020-08-03 00:49:11 +02:00
match base_ty.kind() {
ty::Adt(def, _) if def.has_dtor(tcx) => {
self.check_if_path_or_subpath_is_moved(
location, InitializationRequiringAction::Assignment,
(place_base, span), flow_state);
2018-04-01 10:01:51 +02:00
// (base initialized; no need to
// recur further)
break;
}
// Once `let s; s.x = V; read(s.x);`,
// is allowed, remove this match arm.
ty::Adt(..) | ty::Tuple(..) => {
check_parent_of_field(self, location, place_base, span, flow_state);
// rust-lang/rust#21232, #54499, #54986: during period where we reject
// partial initialization, do not complain about unnecessary `mut` on
// an attempt to do a partial initialization.
self.used_mut.insert(place.local);
}
_ => {}
}
}
}
}
2019-06-13 23:48:52 +02:00
fn check_parent_of_field<'cx, 'tcx>(
this: &mut MirBorrowckCtxt<'cx, 'tcx>,
2019-05-01 23:03:17 +02:00
location: Location,
2020-03-04 22:25:03 +01:00
base: PlaceRef<'tcx>,
span: Span,
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
) {
// rust-lang/rust#21232: Until Rust allows reads from the
// initialized parts of partially initialized structs, we
// will, starting with the 2018 edition, reject attempts
// to write to structs that are not fully initialized.
//
// In other words, *until* we allow this:
//
// 1. `let mut s; s.x = Val; read(s.x);`
//
// we will for now disallow this:
//
// 2. `let mut s; s.x = Val;`
//
// and also this:
//
// 3. `let mut s = ...; drop(s); s.x=Val;`
//
// This does not use check_if_path_or_subpath_is_moved,
// because we want to *allow* reinitializations of fields:
// e.g., want to allow
//
// `let mut s = ...; drop(s.x); s.x=Val;`
//
// This does not use check_if_full_path_is_moved on
// `base`, because that would report an error about the
// `base` as a whole, but in this scenario we *really*
// want to report an error about the actual thing that was
// moved, which may be some prefix of `base`.
// Shallow so that we'll stop at any dereference; we'll
// report errors about issues with such bases elsewhere.
let maybe_uninits = &flow_state.uninits;
// Find the shortest uninitialized prefix you can reach
// without going over a Deref.
let mut shortest_uninit_seen = None;
for prefix in this.prefixes(base, PrefixSet::Shallow) {
let mpi = match this.move_path_for_place(prefix) {
2019-12-22 23:42:04 +01:00
Some(mpi) => mpi,
None => continue,
};
if maybe_uninits.contains(mpi) {
2019-12-22 23:42:04 +01:00
debug!(
"check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}",
shortest_uninit_seen,
Some((prefix, mpi))
);
shortest_uninit_seen = Some((prefix, mpi));
} else {
debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi));
}
}
if let Some((prefix, mpi)) = shortest_uninit_seen {
// Check for a reassignment into a uninitialized field of a union (for example,
// after a move out). In this case, do not report a error here. There is an
// exception, if this is the first assignment into the union (that is, there is
// no move out from an earlier location) then this is an attempt at initialization
// of the union - we should error in that case.
let tcx = this.infcx.tcx;
2021-01-16 11:34:22 +01:00
if let ty::Adt(def, _) = base.ty(this.body(), tcx).ty.kind() {
if def.is_union() {
if this.move_data.path_map[mpi].iter().any(|moi| {
2019-12-22 23:42:04 +01:00
this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
}) {
return;
}
}
}
this.report_use_of_moved_or_uninitialized(
2019-05-01 23:03:17 +02:00
location,
InitializationRequiringAction::PartialAssignment,
(prefix, base, span),
mpi,
);
}
}
}
2019-02-08 14:53:55 +01:00
/// Checks the permissions for the given place and read or write kind
///
2019-02-08 14:53:55 +01:00
/// Returns `true` if an error is reported.
2017-11-17 10:47:02 +01:00
fn check_access_permissions(
&mut self,
2020-03-30 22:49:33 +02:00
(place, span): (Place<'tcx>, Span),
2017-11-17 10:47:02 +01:00
kind: ReadOrWrite,
is_local_mutation_allowed: LocalMutationIsAllowed,
2019-06-13 23:48:52 +02:00
flow_state: &Flows<'cx, 'tcx>,
location: Location,
2017-11-17 10:47:02 +01:00
) -> bool {
debug!(
"check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})",
2018-03-06 06:29:03 +01:00
place, kind, is_local_mutation_allowed
2017-11-17 10:47:02 +01:00
);
let error_access;
let the_place_err;
match kind {
Reservation(WriteKind::MutableBorrow(
borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
))
| Write(WriteKind::MutableBorrow(
borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }),
)) => {
let is_local_mutation_allowed = match borrow_kind {
BorrowKind::Unique => LocalMutationIsAllowed::Yes,
BorrowKind::Mut { .. } => is_local_mutation_allowed,
BorrowKind::Shared | BorrowKind::Shallow => unreachable!(),
};
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, flow_state);
return false;
}
Err(place_err) => {
error_access = AccessKind::MutableBorrow;
the_place_err = place_err;
}
}
2017-11-17 10:47:02 +01:00
}
Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
self.add_used_mut(root_place, flow_state);
return false;
}
Err(place_err) => {
error_access = AccessKind::Mutate;
the_place_err = place_err;
}
}
}
Reservation(
WriteKind::Move
| WriteKind::StorageDeadOrDrop
| WriteKind::MutableBorrow(BorrowKind::Shared)
| WriteKind::MutableBorrow(BorrowKind::Shallow),
)
| Write(
WriteKind::Move
| WriteKind::StorageDeadOrDrop
| WriteKind::MutableBorrow(BorrowKind::Shared)
| WriteKind::MutableBorrow(BorrowKind::Shallow),
) => {
if let (Err(_), true) = (
self.is_mutable(place.as_ref(), is_local_mutation_allowed),
2019-12-22 23:42:04 +01:00
self.errors_buffer.is_empty(),
) {
// rust-lang/rust#46908: In pure NLL mode this code path should be
// unreachable, but we use `delay_span_bug` because we can hit this when
// dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
// enabled. We don't want to ICE for that case, as other errors will have
// been emitted (#52262).
2019-12-22 23:42:04 +01:00
self.infcx.tcx.sess.delay_span_bug(
span,
&format!(
"Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
place, kind,
),
);
}
return false;
}
Activation(..) => {
// permission checks are done at Reservation point.
return false;
2017-11-17 10:47:02 +01:00
}
Read(
ReadKind::Borrow(
BorrowKind::Unique
| BorrowKind::Mut { .. }
| BorrowKind::Shared
| BorrowKind::Shallow,
)
| ReadKind::Copy,
) => {
// Access authorized
return false;
}
}
// rust-lang/rust#21232, #54986: during period where we reject
// partial initialization, do not complain about mutability
// errors except for actual mutation (as opposed to an attempt
// to do a partial initialization).
let previously_initialized =
self.is_local_ever_initialized(place.local, flow_state).is_some();
// at this point, we have set up the error reporting state.
if previously_initialized {
2019-12-22 23:42:04 +01:00
self.report_mutability_error(place, span, the_place_err, error_access, location);
2018-10-16 15:25:18 +02:00
true
} else {
2018-10-16 15:25:18 +02:00
false
}
}
fn is_local_ever_initialized(
&self,
local: Local,
flow_state: &Flows<'cx, 'tcx>,
) -> Option<InitIndex> {
let mpi = self.move_data.rev_lookup.find_local(local);
let ii = &self.move_data.init_path_map[mpi];
for &index in ii {
if flow_state.ever_inits.contains(index) {
return Some(index);
}
}
2018-10-16 15:25:18 +02:00
None
}
/// Adds the place into the used mutable variables set
fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) {
match root_place {
RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
// If the local may have been initialized, and it is now currently being
// mutated, then it is justified to be annotated with the `mut`
// keyword, since the mutation may be a possible reassignment.
2019-12-22 23:42:04 +01:00
if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
&& self.is_local_ever_initialized(local, flow_state).is_some()
{
self.used_mut.insert(local);
}
}
2018-07-03 21:12:09 +02:00
RootPlace {
place_local: _,
place_projection: _,
2018-07-03 21:12:09 +02:00
is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
} => {}
RootPlace {
place_local,
place_projection: place_projection @ [.., _],
is_local_mutation_allowed: _,
} => {
if let Some(field) = self.is_upvar_field_projection(PlaceRef {
local: place_local,
projection: place_projection,
}) {
self.used_mut_upvars.push(field);
}
}
}
}
/// Whether this value can be written or borrowed mutably.
/// Returns the root place if the place passed in is a projection.
fn is_mutable(
2017-11-17 10:47:02 +01:00
&self,
2020-03-04 22:25:03 +01:00
place: PlaceRef<'tcx>,
2017-11-17 10:47:02 +01:00
is_local_mutation_allowed: LocalMutationIsAllowed,
2020-03-04 22:25:03 +01:00
) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> {
2021-01-12 20:54:12 +01:00
debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed);
match place.last_projection() {
None => {
let local = &self.body.local_decls[place.local];
match local.mutability {
2017-11-17 10:47:02 +01:00
Mutability::Not => match is_local_mutation_allowed {
2018-06-22 05:10:52 +02:00
LocalMutationIsAllowed::Yes => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
2018-06-22 05:10:52 +02:00
is_local_mutation_allowed: LocalMutationIsAllowed::Yes,
}),
LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
2018-06-22 05:10:52 +02:00
is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars,
}),
LocalMutationIsAllowed::No => Err(place),
2017-11-17 10:47:02 +01:00
},
2018-06-22 05:10:52 +02:00
Mutability::Mut => Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
2018-06-22 05:10:52 +02:00
is_local_mutation_allowed,
}),
}
2017-11-17 10:47:02 +01:00
}
Some((place_base, elem)) => {
match elem {
ProjectionElem::Deref => {
2021-01-16 11:34:22 +01:00
let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty;
// Check the kind of deref to decide
2020-08-03 00:49:11 +02:00
match base_ty.kind() {
ty::Ref(_, _, mutbl) => {
match mutbl {
// Shared borrowed data is never mutable
hir::Mutability::Not => Err(place),
// Mutably borrowed data is mutable, but only if we have a
// unique path to the `&mut`
hir::Mutability::Mut => {
let mode = match self.is_upvar_field_projection(place) {
2019-12-22 23:42:04 +01:00
Some(field) if self.upvars[field.index()].by_ref => {
2017-12-14 13:33:29 +01:00
is_local_mutation_allowed
}
_ => LocalMutationIsAllowed::Yes,
2017-12-07 20:11:10 +01:00
};
self.is_mutable(place_base, mode)
2017-11-17 10:47:02 +01:00
}
}
2017-11-17 10:47:02 +01:00
}
ty::RawPtr(tnm) => {
match tnm.mutbl {
// `*const` raw pointers are not mutable
hir::Mutability::Not => Err(place),
// `*mut` raw pointers are always mutable, regardless of
// context. The users have to check by themselves.
2019-12-22 23:42:04 +01:00
hir::Mutability::Mut => Ok(RootPlace {
place_local: place.local,
2019-12-22 23:42:04 +01:00
place_projection: place.projection,
is_local_mutation_allowed,
}),
}
2017-11-17 10:47:02 +01:00
}
// `Box<T>` owns its content, so mutable if its location is mutable
_ if base_ty.is_box() => {
self.is_mutable(place_base, is_local_mutation_allowed)
}
// Deref should only be for reference, pointers or boxes
_ => bug!("Deref of unexpected type: {:?}", base_ty),
}
2017-11-17 10:47:02 +01:00
}
// All other projections are owned by their base path, so mutable if
// base path is mutable
2017-12-14 13:33:29 +01:00
ProjectionElem::Field(..)
| ProjectionElem::Index(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. }
| ProjectionElem::Downcast(..) => {
let upvar_field_projection = self.is_upvar_field_projection(place);
2018-07-20 18:30:31 +02:00
if let Some(field) = upvar_field_projection {
let upvar = &self.upvars[field.index()];
2017-12-14 13:33:29 +01:00
debug!(
2021-01-12 20:54:12 +01:00
"is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \
place={:?}, place_base={:?}",
upvar, is_local_mutation_allowed, place, place_base
2017-12-14 13:33:29 +01:00
);
2020-12-13 06:11:15 +01:00
match (upvar.place.mutability, is_local_mutation_allowed) {
(
Mutability::Not,
LocalMutationIsAllowed::No
| LocalMutationIsAllowed::ExceptUpvars,
) => Err(place),
2017-12-14 13:33:29 +01:00
(Mutability::Not, LocalMutationIsAllowed::Yes)
| (Mutability::Mut, _) => {
2018-04-06 18:35:50 +02:00
// Subtle: this is an upvar
// reference, so it looks like
// `self.foo` -- we want to double
2019-05-01 23:03:17 +02:00
// check that the location `*self`
2018-04-06 18:35:50 +02:00
// is mutable (i.e., this is not a
// `Fn` closure). But if that
// check succeeds, we want to
// *blame* the mutability on
// `place` (that is,
// `self.foo`). This is used to
// propagate the info about
// whether mutability declarations
// are used outwards, so that we register
// the outer variable as mutable. Otherwise a
// test like this fails to record the `mut`
// as needed:
//
// ```
// fn foo<F: FnOnce()>(_f: F) { }
// fn main() {
// let var = Vec::new();
// foo(move || {
// var.push(1);
// });
// }
// ```
let _ =
self.is_mutable(place_base, is_local_mutation_allowed)?;
2018-06-22 05:10:52 +02:00
Ok(RootPlace {
place_local: place.local,
place_projection: place.projection,
2018-06-22 05:10:52 +02:00
is_local_mutation_allowed,
})
2017-12-14 13:33:29 +01:00
}
2017-11-17 10:47:02 +01:00
}
2017-12-07 20:11:10 +01:00
} else {
self.is_mutable(place_base, is_local_mutation_allowed)
}
2017-11-17 10:47:02 +01:00
}
}
}
}
}
/// If `place` is a field projection, and the field is being projected from a closure type,
/// then returns the index of the field being projected. Note that this closure will always
/// be `self` in the current MIR, because that is the only time we directly access the fields
/// of a closure type.
2020-03-04 22:25:03 +01:00
pub fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> {
path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
}
2017-09-22 15:37:43 +02:00
}
/// The degree of overlap between 2 places for borrow-checking.
enum Overlap {
/// The places might partially overlap - in this case, we give
/// up and say that they might conflict. This occurs when
/// different fields of a union are borrowed. For example,
/// if `u` is a union, we have no way of telling how disjoint
/// `u.a.x` and `a.b.y` are.
Arbitrary,
2017-12-05 23:51:47 +01:00
/// The places have the same type, and are either completely disjoint
/// or equal - i.e., they can't "partially" overlap as can occur with
2017-12-05 23:51:47 +01:00
/// unions. This is the "base case" on which we recur for extensions
/// of the place.
EqualOrDisjoint,
/// The places are disjoint, so we know all extensions of them
/// will also be disjoint.
Disjoint,
}