]>
Commit | Line | Data |
---|---|---|
ff7c6d11 XL |
1 | //! This query borrow-checks the MIR to (further) ensure it is not broken. |
2 | ||
5e7ed085 | 3 | #![allow(rustc::potential_query_instability)] |
c295e0f8 | 4 | #![feature(box_patterns)] |
5e7ed085 | 5 | #![feature(let_chains)] |
c295e0f8 | 6 | #![feature(min_specialization)] |
5e7ed085 | 7 | #![feature(never_type)] |
064997fb | 8 | #![feature(rustc_attrs)] |
c295e0f8 XL |
9 | #![feature(stmt_expr_attributes)] |
10 | #![feature(trusted_step)] | |
11 | #![feature(try_blocks)] | |
12 | #![recursion_limit = "256"] | |
13 | ||
14 | #[macro_use] | |
15 | extern crate rustc_middle; | |
16 | #[macro_use] | |
17 | extern crate tracing; | |
18 | ||
532ac7d7 | 19 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
0bf4aa26 | 20 | use rustc_data_structures::graph::dominators::Dominators; |
f2b60f7d | 21 | use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed}; |
dfeec247 | 22 | use rustc_hir as hir; |
f9f354fc | 23 | use rustc_hir::def_id::LocalDefId; |
5e7ed085 | 24 | use rustc_index::bit_set::ChunkedBitSet; |
e74abb32 | 25 | use rustc_index::vec::IndexVec; |
064997fb | 26 | use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt}; |
ba9703b0 | 27 | use rustc_middle::mir::{ |
f2b60f7d FG |
28 | traversal, Body, ClearCrossCrate, Local, Location, Mutability, NonDivergingIntrinsic, Operand, |
29 | Place, PlaceElem, PlaceRef, VarDebugInfoContents, | |
ba9703b0 XL |
30 | }; |
31 | use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind}; | |
32 | use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind}; | |
f9f354fc | 33 | use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind}; |
ba9703b0 | 34 | use rustc_middle::ty::query::Providers; |
5869c6ff | 35 | use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt}; |
04454e1e FG |
36 | use rustc_session::lint::builtin::UNUSED_MUT; |
37 | use rustc_span::{Span, Symbol}; | |
ff7c6d11 | 38 | |
74b04a01 | 39 | use either::Either; |
dfeec247 XL |
40 | use smallvec::SmallVec; |
41 | use std::cell::RefCell; | |
0bf4aa26 | 42 | use std::collections::BTreeMap; |
532ac7d7 | 43 | use std::rc::Rc; |
ff7c6d11 | 44 | |
c295e0f8 XL |
45 | use rustc_mir_dataflow::impls::{ |
46 | EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, | |
f9f354fc | 47 | }; |
c295e0f8 XL |
48 | use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex}; |
49 | use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData, MoveError}; | |
50 | use rustc_mir_dataflow::Analysis; | |
51 | use rustc_mir_dataflow::MoveDataParamEnv; | |
ff7c6d11 | 52 | |
f2b60f7d FG |
53 | use crate::session_diagnostics::VarNeedNotMut; |
54 | ||
dfeec247 | 55 | use self::diagnostics::{AccessKind, RegionName}; |
83c7162d | 56 | use self::location::LocationTable; |
ff7c6d11 | 57 | use self::prefixes::PrefixSet; |
94222f64 | 58 | use facts::AllFacts; |
ff7c6d11 | 59 | |
94b46f34 XL |
60 | use self::path_utils::*; |
61 | ||
3c0e092e | 62 | pub mod borrow_set; |
c295e0f8 | 63 | mod borrowck_errors; |
dfeec247 XL |
64 | mod constraint_generation; |
65 | mod constraints; | |
c295e0f8 | 66 | mod dataflow; |
f9f354fc | 67 | mod def_use; |
60c5eb7d | 68 | mod diagnostics; |
dfeec247 | 69 | mod facts; |
dfeec247 | 70 | mod invalidation; |
83c7162d | 71 | mod location; |
dfeec247 XL |
72 | mod member_constraints; |
73 | mod nll; | |
8faf50e0 | 74 | mod path_utils; |
dfeec247 XL |
75 | mod place_ext; |
76 | mod places_conflict; | |
ff7c6d11 | 77 | mod prefixes; |
dfeec247 | 78 | mod region_infer; |
60c5eb7d | 79 | mod renumber; |
064997fb | 80 | mod session_diagnostics; |
60c5eb7d | 81 | mod type_check; |
dfeec247 XL |
82 | mod universal_regions; |
83 | mod used_muts; | |
60c5eb7d | 84 | |
c295e0f8 XL |
85 | // A public API provided for the Rust compiler consumers. |
86 | pub mod consumers; | |
87 | ||
88 | use borrow_set::{BorrowData, BorrowSet}; | |
89 | use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows}; | |
90 | use nll::{PoloniusOutput, ToRegionVid}; | |
91 | use place_ext::PlaceExt; | |
92 | use places_conflict::{places_conflict, PlaceConflictBias}; | |
93 | use region_infer::RegionInferenceContext; | |
ff7c6d11 | 94 | |
48663c56 XL |
95 | // FIXME(eddyb) perhaps move this somewhere more centrally. |
96 | #[derive(Debug)] | |
c295e0f8 | 97 | struct Upvar<'tcx> { |
5869c6ff | 98 | place: CapturedPlace<'tcx>, |
48663c56 XL |
99 | |
100 | /// If true, the capture is behind a reference. | |
101 | by_ref: bool, | |
48663c56 XL |
102 | } |
103 | ||
923072b8 FG |
104 | /// Associate some local constants with the `'tcx` lifetime |
105 | struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>); | |
106 | impl<'tcx> TyCtxtConsts<'tcx> { | |
107 | const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref]; | |
108 | } | |
74b04a01 | 109 | |
f035d41b | 110 | pub fn provide(providers: &mut Providers) { |
3dfed10e XL |
111 | *providers = Providers { |
112 | mir_borrowck: |tcx, did| { | |
113 | if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { | |
114 | tcx.mir_borrowck_const_arg(def) | |
115 | } else { | |
116 | mir_borrowck(tcx, ty::WithOptConstParam::unknown(did)) | |
117 | } | |
118 | }, | |
119 | mir_borrowck_const_arg: |tcx, (did, param_did)| { | |
120 | mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }) | |
121 | }, | |
122 | ..*providers | |
123 | }; | |
ff7c6d11 XL |
124 | } |
125 | ||
3dfed10e XL |
126 | fn mir_borrowck<'tcx>( |
127 | tcx: TyCtxt<'tcx>, | |
128 | def: ty::WithOptConstParam<LocalDefId>, | |
129 | ) -> &'tcx BorrowCheckResult<'tcx> { | |
130 | let (input_body, promoted) = tcx.mir_promoted(def); | |
131 | debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id())); | |
5e7ed085 | 132 | let hir_owner = tcx.hir().local_def_id_to_hir_id(def.did).owner; |
ff7c6d11 | 133 | |
2b03887a FG |
134 | let infcx = |
135 | tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)).build(); | |
136 | let input_body: &Body<'_> = &input_body.borrow(); | |
137 | let promoted: &IndexVec<_, _> = &promoted.borrow(); | |
138 | let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, false).0; | |
ff7c6d11 XL |
139 | debug!("mir_borrowck done"); |
140 | ||
3dfed10e | 141 | tcx.arena.alloc(opt_closure_req) |
ff7c6d11 XL |
142 | } |
143 | ||
94222f64 XL |
144 | /// Perform the actual borrow checking. |
145 | /// | |
146 | /// If `return_body_with_facts` is true, then return the body with non-erased | |
147 | /// region ids on which the borrow checking was performed together with Polonius | |
148 | /// facts. | |
5e7ed085 | 149 | #[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.with_opt_param().as_local().unwrap()), level = "debug")] |
2b03887a FG |
150 | fn do_mir_borrowck<'tcx>( |
151 | infcx: &InferCtxt<'tcx>, | |
dc9dc135 | 152 | input_body: &Body<'tcx>, |
f9f354fc | 153 | input_promoted: &IndexVec<Promoted, Body<'tcx>>, |
94222f64 XL |
154 | return_body_with_facts: bool, |
155 | ) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) { | |
29967ef6 XL |
156 | let def = input_body.source.with_opt_param().as_local().unwrap(); |
157 | ||
c295e0f8 | 158 | debug!(?def); |
94222f64 | 159 | |
ff7c6d11 | 160 | let tcx = infcx.tcx; |
3dfed10e | 161 | let param_env = tcx.param_env(def.did); |
ff7c6d11 | 162 | |
60c5eb7d XL |
163 | let mut local_names = IndexVec::from_elem(None, &input_body.local_decls); |
164 | for var_debug_info in &input_body.var_debug_info { | |
fc512014 XL |
165 | if let VarDebugInfoContents::Place(place) = var_debug_info.value { |
166 | if let Some(local) = place.as_local() { | |
5e7ed085 FG |
167 | if let Some(prev_name) = local_names[local] && var_debug_info.name != prev_name { |
168 | span_bug!( | |
169 | var_debug_info.source_info.span, | |
170 | "local {:?} has many names (`{}` vs `{}`)", | |
171 | local, | |
172 | prev_name, | |
173 | var_debug_info.name | |
174 | ); | |
60c5eb7d | 175 | } |
fc512014 | 176 | local_names[local] = Some(var_debug_info.name); |
60c5eb7d | 177 | } |
60c5eb7d XL |
178 | } |
179 | } | |
180 | ||
5099ac24 FG |
181 | let mut errors = error::BorrowckErrors::new(); |
182 | ||
48663c56 | 183 | // Gather the upvars of a closure, if any. |
3dfed10e | 184 | let tables = tcx.typeck_opt_const_arg(def); |
5e7ed085 | 185 | if let Some(ErrorGuaranteed { .. }) = tables.tainted_by_errors { |
74b04a01 | 186 | infcx.set_tainted_by_errors(); |
5099ac24 | 187 | errors.set_tainted_by_errors(); |
74b04a01 | 188 | } |
48663c56 | 189 | let upvars: Vec<_> = tables |
064997fb | 190 | .closure_min_captures_flattened(def.did) |
fc512014 | 191 | .map(|captured_place| { |
fc512014 | 192 | let capture = captured_place.info.capture_kind; |
48663c56 | 193 | let by_ref = match capture { |
5099ac24 | 194 | ty::UpvarCapture::ByValue => false, |
48663c56 XL |
195 | ty::UpvarCapture::ByRef(..) => true, |
196 | }; | |
17df50a5 | 197 | Upvar { place: captured_place.clone(), by_ref } |
48663c56 XL |
198 | }) |
199 | .collect(); | |
200 | ||
83c7162d XL |
201 | // Replace all regions with fresh inference variables. This |
202 | // requires first making our own copy of the MIR. This copy will | |
203 | // be modified (in place) to contain non-lexical lifetimes. It | |
204 | // will have a lifetime tied to the inference context. | |
94222f64 | 205 | let mut body_owned = input_body.clone(); |
60c5eb7d | 206 | let mut promoted = input_promoted.clone(); |
94222f64 XL |
207 | let free_regions = |
208 | nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted); | |
209 | let body = &body_owned; // no further changes | |
60c5eb7d | 210 | |
94222f64 XL |
211 | let location_table_owned = LocationTable::new(body); |
212 | let location_table = &location_table_owned; | |
ff7c6d11 | 213 | |
f9f354fc | 214 | let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) = |
60c5eb7d | 215 | match MoveData::gather_moves(&body, tcx, param_env) { |
064997fb | 216 | Ok((_, move_data)) => (move_data, Vec::new()), |
f9f354fc | 217 | Err((move_data, move_errors)) => (move_data, move_errors), |
8faf50e0 | 218 | }; |
f9f354fc XL |
219 | let promoted_errors = promoted |
220 | .iter_enumerated() | |
221 | .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env))); | |
ff7c6d11 | 222 | |
dfeec247 | 223 | let mdpe = MoveDataParamEnv { move_data, param_env }; |
ff7c6d11 | 224 | |
74b04a01 | 225 | let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe) |
29967ef6 | 226 | .into_engine(tcx, &body) |
1b1a35ee | 227 | .pass_name("borrowck") |
74b04a01 XL |
228 | .iterate_to_fixpoint() |
229 | .into_results_cursor(&body); | |
ff7c6d11 | 230 | |
5e7ed085 | 231 | let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def.did).is_fn_or_closure(); |
dfeec247 XL |
232 | let borrow_set = |
233 | Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data)); | |
234 | ||
064997fb | 235 | let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.unstable_opts.polonius; |
c295e0f8 | 236 | |
dfeec247 | 237 | // Compute non-lexical lifetimes. |
74b04a01 XL |
238 | let nll::NllOutput { |
239 | regioncx, | |
240 | opaque_type_values, | |
94222f64 | 241 | polonius_input, |
74b04a01 XL |
242 | polonius_output, |
243 | opt_closure_req, | |
244 | nll_errors, | |
245 | } = nll::compute_regions( | |
246 | infcx, | |
74b04a01 XL |
247 | free_regions, |
248 | body, | |
249 | &promoted, | |
250 | location_table, | |
251 | param_env, | |
252 | &mut flow_inits, | |
253 | &mdpe.move_data, | |
254 | &borrow_set, | |
f035d41b | 255 | &upvars, |
c295e0f8 | 256 | use_polonius, |
74b04a01 | 257 | ); |
83c7162d | 258 | |
dfeec247 XL |
259 | // Dump MIR results into a file, if that is enabled. This let us |
260 | // write unit-tests, as well as helping with debugging. | |
29967ef6 | 261 | nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req); |
dfeec247 | 262 | |
74b04a01 | 263 | // We also have a `#[rustc_regions]` annotation that causes us to dump |
dfeec247 | 264 | // information. |
74b04a01 XL |
265 | nll::dump_annotation( |
266 | infcx, | |
267 | &body, | |
74b04a01 XL |
268 | ®ioncx, |
269 | &opt_closure_req, | |
270 | &opaque_type_values, | |
5099ac24 | 271 | &mut errors, |
74b04a01 | 272 | ); |
b7449926 XL |
273 | |
274 | // The various `flow_*` structures can be large. We drop `flow_inits` here | |
275 | // so it doesn't overlap with the others below. This reduces peak memory | |
276 | // usage significantly on some benchmarks. | |
277 | drop(flow_inits); | |
278 | ||
83c7162d | 279 | let regioncx = Rc::new(regioncx); |
ff7c6d11 | 280 | |
c295e0f8 XL |
281 | let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set) |
282 | .into_engine(tcx, body) | |
1b1a35ee | 283 | .pass_name("borrowck") |
74b04a01 | 284 | .iterate_to_fixpoint(); |
c295e0f8 XL |
285 | let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe) |
286 | .into_engine(tcx, body) | |
1b1a35ee | 287 | .pass_name("borrowck") |
74b04a01 | 288 | .iterate_to_fixpoint(); |
c295e0f8 XL |
289 | let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe) |
290 | .into_engine(tcx, body) | |
1b1a35ee | 291 | .pass_name("borrowck") |
74b04a01 | 292 | .iterate_to_fixpoint(); |
0531ce1d | 293 | |
04454e1e FG |
294 | let movable_generator = |
295 | // The first argument is the generator type passed by value | |
296 | if let Some(local) = body.local_decls.raw.get(1) | |
297 | // Get the interior types and substs which typeck computed | |
298 | && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind() | |
299 | { | |
300 | false | |
301 | } else { | |
302 | true | |
303 | }; | |
2c00a5a8 | 304 | |
f9f354fc XL |
305 | for (idx, move_data_results) in promoted_errors { |
306 | let promoted_body = &promoted[idx]; | |
f9f354fc XL |
307 | |
308 | if let Err((move_data, move_errors)) = move_data_results { | |
309 | let mut promoted_mbcx = MirBorrowckCtxt { | |
310 | infcx, | |
1b1a35ee | 311 | param_env, |
f9f354fc | 312 | body: promoted_body, |
f9f354fc | 313 | move_data: &move_data, |
6a06907d | 314 | location_table, // no need to create a real one for the promoted, it is not used |
f9f354fc | 315 | movable_generator, |
f035d41b | 316 | fn_self_span_reported: Default::default(), |
f9f354fc XL |
317 | locals_are_invalidated_at_exit, |
318 | access_place_error_reported: Default::default(), | |
319 | reservation_error_reported: Default::default(), | |
f9f354fc | 320 | uninitialized_error_reported: Default::default(), |
f9f354fc XL |
321 | regioncx: regioncx.clone(), |
322 | used_mut: Default::default(), | |
323 | used_mut_upvars: SmallVec::new(), | |
6a06907d XL |
324 | borrow_set: Rc::clone(&borrow_set), |
325 | dominators: Dominators::dummy(), // not used | |
f9f354fc XL |
326 | upvars: Vec::new(), |
327 | local_names: IndexVec::from_elem(None, &promoted_body.local_decls), | |
328 | region_names: RefCell::default(), | |
329 | next_region_name: RefCell::new(1), | |
330 | polonius_output: None, | |
5099ac24 | 331 | errors, |
f9f354fc XL |
332 | }; |
333 | promoted_mbcx.report_move_errors(move_errors); | |
5099ac24 | 334 | errors = promoted_mbcx.errors; |
f9f354fc XL |
335 | }; |
336 | } | |
337 | ||
064997fb | 338 | let dominators = body.basic_blocks.dominators(); |
83c7162d | 339 | |
ff7c6d11 | 340 | let mut mbcx = MirBorrowckCtxt { |
0bf4aa26 | 341 | infcx, |
1b1a35ee | 342 | param_env, |
dc9dc135 | 343 | body, |
ff7c6d11 | 344 | move_data: &mdpe.move_data, |
8faf50e0 | 345 | location_table, |
2c00a5a8 | 346 | movable_generator, |
b7449926 | 347 | locals_are_invalidated_at_exit, |
f035d41b | 348 | fn_self_span_reported: Default::default(), |
0bf4aa26 XL |
349 | access_place_error_reported: Default::default(), |
350 | reservation_error_reported: Default::default(), | |
0bf4aa26 | 351 | uninitialized_error_reported: Default::default(), |
6a06907d | 352 | regioncx: Rc::clone(®ioncx), |
0bf4aa26 | 353 | used_mut: Default::default(), |
83c7162d | 354 | used_mut_upvars: SmallVec::new(), |
6a06907d | 355 | borrow_set: Rc::clone(&borrow_set), |
83c7162d | 356 | dominators, |
48663c56 | 357 | upvars, |
60c5eb7d | 358 | local_names, |
dfeec247 XL |
359 | region_names: RefCell::default(), |
360 | next_region_name: RefCell::new(1), | |
74b04a01 | 361 | polonius_output, |
5099ac24 | 362 | errors, |
ff7c6d11 XL |
363 | }; |
364 | ||
dfeec247 XL |
365 | // Compute and report region errors, if any. |
366 | mbcx.report_region_errors(nll_errors); | |
367 | ||
74b04a01 XL |
368 | let results = BorrowckResults { |
369 | ever_inits: flow_ever_inits, | |
370 | uninits: flow_uninits, | |
371 | borrows: flow_borrows, | |
372 | }; | |
ff7c6d11 | 373 | |
f9f354fc | 374 | mbcx.report_move_errors(move_errors); |
74b04a01 | 375 | |
c295e0f8 XL |
376 | rustc_mir_dataflow::visit_results( |
377 | body, | |
378 | traversal::reverse_postorder(body).map(|(bb, _)| bb), | |
74b04a01 XL |
379 | &results, |
380 | &mut mbcx, | |
381 | ); | |
ff7c6d11 | 382 | |
83c7162d XL |
383 | // For each non-user used mutable variable, check if it's been assigned from |
384 | // a user-declared local. If so, then put that local into the used_mut set. | |
385 | // Note that this set is expected to be small - only upvars from closures | |
386 | // would have a chance of erroneously adding non-user-defined mutable vars | |
387 | // to the set. | |
dfeec247 XL |
388 | let temporary_used_locals: FxHashSet<Local> = mbcx |
389 | .used_mut | |
390 | .iter() | |
60c5eb7d | 391 | .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable()) |
8faf50e0 XL |
392 | .cloned() |
393 | .collect(); | |
a1dfa0c6 XL |
394 | // For the remaining unused locals that are marked as mutable, we avoid linting any that |
395 | // were never initialized. These locals may have been removed as unreachable code; or will be | |
396 | // linted as unused variables. | |
dfeec247 XL |
397 | let unused_mut_locals = |
398 | mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect(); | |
a1dfa0c6 | 399 | mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals); |
83c7162d XL |
400 | |
401 | debug!("mbcx.used_mut: {:?}", mbcx.used_mut); | |
5099ac24 | 402 | let used_mut = std::mem::take(&mut mbcx.used_mut); |
dfeec247 | 403 | for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) { |
60c5eb7d XL |
404 | let local_decl = &mbcx.body.local_decls[local]; |
405 | let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data { | |
406 | ClearCrossCrate::Set(data) => data.lint_root, | |
407 | _ => continue, | |
408 | }; | |
83c7162d | 409 | |
60c5eb7d XL |
410 | // Skip over locals that begin with an underscore or have no name |
411 | match mbcx.local_names[local] { | |
dfeec247 | 412 | Some(name) => { |
74b04a01 | 413 | if name.as_str().starts_with('_') { |
dfeec247 XL |
414 | continue; |
415 | } | |
416 | } | |
60c5eb7d XL |
417 | None => continue, |
418 | } | |
83c7162d | 419 | |
60c5eb7d XL |
420 | let span = local_decl.source_info.span; |
421 | if span.desugaring_kind().is_some() { | |
422 | // If the `mut` arises as part of a desugaring, we should ignore it. | |
423 | continue; | |
8faf50e0 | 424 | } |
60c5eb7d | 425 | |
f2b60f7d FG |
426 | let mut_span = tcx.sess.source_map().span_until_non_whitespace(span); |
427 | ||
428 | tcx.emit_spanned_lint(UNUSED_MUT, lint_root, span, VarNeedNotMut { span: mut_span }) | |
8faf50e0 XL |
429 | } |
430 | ||
5099ac24 | 431 | let tainted_by_errors = mbcx.emit_errors(); |
83c7162d | 432 | |
8faf50e0 | 433 | let result = BorrowCheckResult { |
74b04a01 | 434 | concrete_opaque_types: opaque_type_values, |
83c7162d XL |
435 | closure_requirements: opt_closure_req, |
436 | used_mut_upvars: mbcx.used_mut_upvars, | |
5099ac24 | 437 | tainted_by_errors, |
8faf50e0 XL |
438 | }; |
439 | ||
94222f64 XL |
440 | let body_with_facts = if return_body_with_facts { |
441 | let output_facts = mbcx.polonius_output.expect("Polonius output was not computed"); | |
442 | Some(Box::new(BodyWithBorrowckFacts { | |
443 | body: body_owned, | |
444 | input_facts: *polonius_input.expect("Polonius input facts were not generated"), | |
445 | output_facts, | |
446 | location_table: location_table_owned, | |
447 | })) | |
448 | } else { | |
449 | None | |
450 | }; | |
451 | ||
8faf50e0 XL |
452 | debug!("do_mir_borrowck: result = {:#?}", result); |
453 | ||
94222f64 XL |
454 | (result, body_with_facts) |
455 | } | |
456 | ||
457 | /// A `Body` with information computed by the borrow checker. This struct is | |
458 | /// intended to be consumed by compiler consumers. | |
459 | /// | |
460 | /// We need to include the MIR body here because the region identifiers must | |
461 | /// match the ones in the Polonius facts. | |
462 | pub struct BodyWithBorrowckFacts<'tcx> { | |
463 | /// A mir body that contains region identifiers. | |
464 | pub body: Body<'tcx>, | |
465 | /// Polonius input facts. | |
466 | pub input_facts: AllFacts, | |
467 | /// Polonius output facts. | |
468 | pub output_facts: Rc<self::nll::PoloniusOutput>, | |
469 | /// The table that maps Polonius points to locations in the table. | |
470 | pub location_table: LocationTable, | |
ff7c6d11 XL |
471 | } |
472 | ||
c295e0f8 | 473 | struct MirBorrowckCtxt<'cx, 'tcx> { |
2b03887a | 474 | infcx: &'cx InferCtxt<'tcx>, |
1b1a35ee | 475 | param_env: ParamEnv<'tcx>, |
f9f354fc | 476 | body: &'cx Body<'tcx>, |
ff7c6d11 | 477 | move_data: &'cx MoveData<'tcx>, |
8faf50e0 XL |
478 | |
479 | /// Map from MIR `Location` to `LocationIndex`; created | |
480 | /// when MIR borrowck begins. | |
481 | location_table: &'cx LocationTable, | |
482 | ||
2c00a5a8 | 483 | movable_generator: bool, |
ff7c6d11 XL |
484 | /// This keeps track of whether local variables are free-ed when the function |
485 | /// exits even without a `StorageDead`, which appears to be the case for | |
486 | /// constants. | |
487 | /// | |
488 | /// I'm not sure this is the right approach - @eddyb could you try and | |
489 | /// figure this out? | |
490 | locals_are_invalidated_at_exit: bool, | |
2c00a5a8 XL |
491 | /// This field keeps track of when borrow errors are reported in the access_place function |
492 | /// so that there is no duplicate reporting. This field cannot also be used for the conflicting | |
493 | /// borrow errors that is handled by the `reservation_error_reported` field as the inclusion | |
494 | /// of the `Span` type (while required to mute some errors) stops the muting of the reservation | |
495 | /// errors. | |
496 | access_place_error_reported: FxHashSet<(Place<'tcx>, Span)>, | |
ff7c6d11 XL |
497 | /// This field keeps track of when borrow conflict errors are reported |
498 | /// for reservations, so that we don't report seemingly duplicate | |
9fa01778 XL |
499 | /// errors for corresponding activations. |
500 | // | |
501 | // FIXME: ideally this would be a set of `BorrowIndex`, not `Place`s, | |
502 | // but it is currently inconvenient to track down the `BorrowIndex` | |
503 | // at the time we detect and report a reservation error. | |
ff7c6d11 | 504 | reservation_error_reported: FxHashSet<Place<'tcx>>, |
f035d41b XL |
505 | /// This fields keeps track of the `Span`s that we have |
506 | /// used to report extra information for `FnSelfUse`, to avoid | |
507 | /// unnecessarily verbose errors. | |
508 | fn_self_span_reported: FxHashSet<Span>, | |
0bf4aa26 | 509 | /// This field keeps track of errors reported in the checking of uninitialized variables, |
8faf50e0 | 510 | /// so that we don't report seemingly duplicate errors. |
74b04a01 | 511 | uninitialized_error_reported: FxHashSet<PlaceRef<'tcx>>, |
83c7162d XL |
512 | /// This field keeps track of all the local variables that are declared mut and are mutated. |
513 | /// Used for the warning issued by an unused mutable local variable. | |
514 | used_mut: FxHashSet<Local>, | |
515 | /// If the function we're checking is a closure, then we'll need to report back the list of | |
516 | /// mutable upvars that have been used. This field keeps track of them. | |
517 | used_mut_upvars: SmallVec<[Field; 8]>, | |
dfeec247 | 518 | /// Region inference context. This contains the results from region inference and lets us e.g. |
ff7c6d11 | 519 | /// find out which CFG points are contained in each borrow region. |
dfeec247 | 520 | regioncx: Rc<RegionInferenceContext<'tcx>>, |
83c7162d XL |
521 | |
522 | /// The set of borrows extracted from the MIR | |
523 | borrow_set: Rc<BorrowSet<'tcx>>, | |
524 | ||
525 | /// Dominators for MIR | |
526 | dominators: Dominators<BasicBlock>, | |
48663c56 XL |
527 | |
528 | /// Information about upvars not necessarily preserved in types or MIR | |
5869c6ff | 529 | upvars: Vec<Upvar<'tcx>>, |
60c5eb7d XL |
530 | |
531 | /// Names of local (user) variables (extracted from `var_debug_info`). | |
f9f354fc | 532 | local_names: IndexVec<Local, Option<Symbol>>, |
dfeec247 XL |
533 | |
534 | /// Record the region names generated for each region in the given | |
535 | /// MIR def so that we can reuse them later in help/error messages. | |
536 | region_names: RefCell<FxHashMap<RegionVid, RegionName>>, | |
537 | ||
538 | /// The counter for generating new region names. | |
539 | next_region_name: RefCell<usize>, | |
74b04a01 XL |
540 | |
541 | /// Results of Polonius analysis. | |
542 | polonius_output: Option<Rc<PoloniusOutput>>, | |
5099ac24 FG |
543 | |
544 | errors: error::BorrowckErrors<'tcx>, | |
ff7c6d11 XL |
545 | } |
546 | ||
547 | // Check that: | |
548 | // 1. assignments are always made to mutable locations (FIXME: does that still really go here?) | |
549 | // 2. loans made in overlapping scopes do not conflict | |
550 | // 3. assignments do not affect things loaned out as immutable | |
551 | // 4. moves do not affect things loaned out in any way | |
c295e0f8 | 552 | impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> { |
dc9dc135 | 553 | type FlowState = Flows<'cx, 'tcx>; |
ff7c6d11 | 554 | |
f9f354fc | 555 | fn visit_statement_before_primary_effect( |
ff7c6d11 | 556 | &mut self, |
74b04a01 | 557 | flow_state: &Flows<'cx, 'tcx>, |
416331ca | 558 | stmt: &'cx Statement<'tcx>, |
74b04a01 | 559 | location: Location, |
ff7c6d11 | 560 | ) { |
74b04a01 | 561 | debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state); |
ff7c6d11 XL |
562 | let span = stmt.source_info.span; |
563 | ||
564 | self.check_activations(location, span, flow_state); | |
565 | ||
ba9703b0 XL |
566 | match &stmt.kind { |
567 | StatementKind::Assign(box (lhs, ref rhs)) => { | |
dfeec247 | 568 | self.consume_rvalue(location, (rhs, span), flow_state); |
2c00a5a8 | 569 | |
5099ac24 | 570 | self.mutate_place(location, (*lhs, span), Shallow(None), flow_state); |
ff7c6d11 | 571 | } |
cdc7bbd5 | 572 | StatementKind::FakeRead(box (_, ref place)) => { |
0bf4aa26 XL |
573 | // Read for match doesn't access any memory and is used to |
574 | // assert that a place is safe and live. So we don't have to | |
575 | // do any checks here. | |
576 | // | |
577 | // FIXME: Remove check that the place is initialized. This is | |
578 | // needed for now because matches don't have never patterns yet. | |
579 | // So this is the only place we prevent | |
580 | // let x: !; | |
581 | // match x {}; | |
582 | // from compiling. | |
583 | self.check_if_path_or_subpath_is_moved( | |
48663c56 | 584 | location, |
0bf4aa26 | 585 | InitializationRequiringAction::Use, |
416331ca | 586 | (place.as_ref(), span), |
8faf50e0 XL |
587 | flow_state, |
588 | ); | |
94b46f34 | 589 | } |
f2b60f7d FG |
590 | StatementKind::Intrinsic(box ref kind) => match kind { |
591 | NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), flow_state), | |
592 | NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!( | |
6a06907d XL |
593 | span, |
594 | "Unexpected CopyNonOverlapping, should only appear after lower_intrinsics", | |
595 | ) | |
596 | } | |
f2b60f7d FG |
597 | // Only relevant for mir typeck |
598 | StatementKind::AscribeUserType(..) | |
599 | // Doesn't have any language semantics | |
3dfed10e | 600 | | StatementKind::Coverage(..) |
f2b60f7d FG |
601 | // Does not actually affect borrowck |
602 | | StatementKind::StorageLive(..) => {} | |
ff7c6d11 XL |
603 | StatementKind::StorageDead(local) => { |
604 | self.access_place( | |
48663c56 | 605 | location, |
ba9703b0 | 606 | (Place::from(*local), span), |
ff7c6d11 XL |
607 | (Shallow(None), Write(WriteKind::StorageDeadOrDrop)), |
608 | LocalMutationIsAllowed::Yes, | |
609 | flow_state, | |
610 | ); | |
611 | } | |
f2b60f7d FG |
612 | StatementKind::Nop |
613 | | StatementKind::Retag { .. } | |
614 | | StatementKind::Deinit(..) | |
615 | | StatementKind::SetDiscriminant { .. } => { | |
04454e1e FG |
616 | bug!("Statement not allowed in this MIR phase") |
617 | } | |
ff7c6d11 XL |
618 | } |
619 | } | |
620 | ||
f9f354fc | 621 | fn visit_terminator_before_primary_effect( |
ff7c6d11 | 622 | &mut self, |
74b04a01 | 623 | flow_state: &Flows<'cx, 'tcx>, |
416331ca | 624 | term: &'cx Terminator<'tcx>, |
74b04a01 | 625 | loc: Location, |
ff7c6d11 | 626 | ) { |
74b04a01 | 627 | debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state); |
ff7c6d11 XL |
628 | let span = term.source_info.span; |
629 | ||
74b04a01 | 630 | self.check_activations(loc, span, flow_state); |
ff7c6d11 XL |
631 | |
632 | match term.kind { | |
29967ef6 | 633 | TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => { |
48663c56 | 634 | self.consume_operand(loc, (discr, span), flow_state); |
ff7c6d11 | 635 | } |
29967ef6 | 636 | TerminatorKind::Drop { place, target: _, unwind: _ } => { |
dfeec247 XL |
637 | debug!( |
638 | "visit_terminator_drop \ | |
29967ef6 XL |
639 | loc: {:?} term: {:?} place: {:?} span: {:?}", |
640 | loc, term, place, span | |
dfeec247 | 641 | ); |
b7449926 | 642 | |
0bf4aa26 | 643 | self.access_place( |
48663c56 | 644 | loc, |
29967ef6 | 645 | (place, span), |
0bf4aa26 XL |
646 | (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)), |
647 | LocalMutationIsAllowed::Yes, | |
648 | flow_state, | |
649 | ); | |
ff7c6d11 XL |
650 | } |
651 | TerminatorKind::DropAndReplace { | |
f035d41b | 652 | place: drop_place, |
ff7c6d11 XL |
653 | value: ref new_value, |
654 | target: _, | |
655 | unwind: _, | |
656 | } => { | |
5099ac24 | 657 | self.mutate_place(loc, (drop_place, span), Deep, flow_state); |
dfeec247 | 658 | self.consume_operand(loc, (new_value, span), flow_state); |
ff7c6d11 XL |
659 | } |
660 | TerminatorKind::Call { | |
661 | ref func, | |
662 | ref args, | |
923072b8 FG |
663 | destination, |
664 | target: _, | |
ff7c6d11 | 665 | cleanup: _, |
0bf4aa26 | 666 | from_hir_call: _, |
f035d41b | 667 | fn_span: _, |
ff7c6d11 | 668 | } => { |
48663c56 | 669 | self.consume_operand(loc, (func, span), flow_state); |
ff7c6d11 | 670 | for arg in args { |
dfeec247 | 671 | self.consume_operand(loc, (arg, span), flow_state); |
ff7c6d11 | 672 | } |
923072b8 | 673 | self.mutate_place(loc, (destination, span), Deep, flow_state); |
ff7c6d11 | 674 | } |
dfeec247 | 675 | TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => { |
48663c56 | 676 | self.consume_operand(loc, (cond, span), flow_state); |
ba9703b0 | 677 | use rustc_middle::mir::AssertKind; |
74b04a01 | 678 | if let AssertKind::BoundsCheck { ref len, ref index } = *msg { |
48663c56 XL |
679 | self.consume_operand(loc, (len, span), flow_state); |
680 | self.consume_operand(loc, (index, span), flow_state); | |
ff7c6d11 XL |
681 | } |
682 | } | |
683 | ||
ba9703b0 | 684 | TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => { |
48663c56 | 685 | self.consume_operand(loc, (value, span), flow_state); |
5099ac24 | 686 | self.mutate_place(loc, (resume_arg, span), Deep, flow_state); |
74b04a01 | 687 | } |
2c00a5a8 | 688 | |
f9f354fc XL |
689 | TerminatorKind::InlineAsm { |
690 | template: _, | |
691 | ref operands, | |
692 | options: _, | |
693 | line_spans: _, | |
694 | destination: _, | |
a2a8927a | 695 | cleanup: _, |
f9f354fc XL |
696 | } => { |
697 | for op in operands { | |
698 | match *op { | |
cdc7bbd5 | 699 | InlineAsmOperand::In { reg: _, ref value } => { |
f9f354fc XL |
700 | self.consume_operand(loc, (value, span), flow_state); |
701 | } | |
702 | InlineAsmOperand::Out { reg: _, late: _, place, .. } => { | |
703 | if let Some(place) = place { | |
5099ac24 | 704 | self.mutate_place(loc, (place, span), Shallow(None), flow_state); |
f9f354fc XL |
705 | } |
706 | } | |
707 | InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => { | |
708 | self.consume_operand(loc, (in_value, span), flow_state); | |
709 | if let Some(out_place) = out_place { | |
710 | self.mutate_place( | |
711 | loc, | |
712 | (out_place, span), | |
713 | Shallow(None), | |
f9f354fc XL |
714 | flow_state, |
715 | ); | |
716 | } | |
717 | } | |
cdc7bbd5 XL |
718 | InlineAsmOperand::Const { value: _ } |
719 | | InlineAsmOperand::SymFn { value: _ } | |
f035d41b | 720 | | InlineAsmOperand::SymStatic { def_id: _ } => {} |
f9f354fc XL |
721 | } |
722 | } | |
723 | } | |
724 | ||
74b04a01 XL |
725 | TerminatorKind::Goto { target: _ } |
726 | | TerminatorKind::Abort | |
727 | | TerminatorKind::Unreachable | |
728 | | TerminatorKind::Resume | |
729 | | TerminatorKind::Return | |
730 | | TerminatorKind::GeneratorDrop | |
f035d41b | 731 | | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } |
74b04a01 XL |
732 | | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => { |
733 | // no data used, thus irrelevant to borrowck | |
734 | } | |
735 | } | |
736 | } | |
737 | ||
f9f354fc | 738 | fn visit_terminator_after_primary_effect( |
74b04a01 XL |
739 | &mut self, |
740 | flow_state: &Flows<'cx, 'tcx>, | |
741 | term: &'cx Terminator<'tcx>, | |
742 | loc: Location, | |
743 | ) { | |
744 | let span = term.source_info.span; | |
745 | ||
746 | match term.kind { | |
747 | TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => { | |
2c00a5a8 XL |
748 | if self.movable_generator { |
749 | // Look for any active borrows to locals | |
83c7162d | 750 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
751 | for i in flow_state.borrows.iter() { |
752 | let borrow = &borrow_set[i]; | |
753 | self.check_for_local_borrow(borrow, span); | |
754 | } | |
2c00a5a8 | 755 | } |
ff7c6d11 XL |
756 | } |
757 | ||
758 | TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => { | |
759 | // Returning from the function implicitly kills storage for all locals and statics. | |
760 | // Often, the storage will already have been killed by an explicit | |
761 | // StorageDead, but we don't always emit those (notably on unwind paths), | |
762 | // so this "extra check" serves as a kind of backup. | |
83c7162d | 763 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
764 | for i in flow_state.borrows.iter() { |
765 | let borrow = &borrow_set[i]; | |
766 | self.check_for_invalidation_at_exit(loc, borrow, span); | |
767 | } | |
ff7c6d11 | 768 | } |
74b04a01 XL |
769 | |
770 | TerminatorKind::Abort | |
771 | | TerminatorKind::Assert { .. } | |
772 | | TerminatorKind::Call { .. } | |
773 | | TerminatorKind::Drop { .. } | |
774 | | TerminatorKind::DropAndReplace { .. } | |
f035d41b | 775 | | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } |
74b04a01 XL |
776 | | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } |
777 | | TerminatorKind::Goto { .. } | |
778 | | TerminatorKind::SwitchInt { .. } | |
f9f354fc XL |
779 | | TerminatorKind::Unreachable |
780 | | TerminatorKind::InlineAsm { .. } => {} | |
ff7c6d11 XL |
781 | } |
782 | } | |
783 | } | |
784 | ||
0bf4aa26 | 785 | use self::AccessDepth::{Deep, Shallow}; |
dfeec247 | 786 | use self::ReadOrWrite::{Activation, Read, Reservation, Write}; |
ff7c6d11 XL |
787 | |
788 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
789 | enum ArtificialField { | |
ff7c6d11 | 790 | ArrayLength, |
0bf4aa26 | 791 | ShallowBorrow, |
ff7c6d11 XL |
792 | } |
793 | ||
794 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
0bf4aa26 | 795 | enum AccessDepth { |
ff7c6d11 | 796 | /// From the RFC: "A *shallow* access means that the immediate |
2c00a5a8 | 797 | /// fields reached at P are accessed, but references or pointers |
ff7c6d11 XL |
798 | /// found within are not dereferenced. Right now, the only access |
799 | /// that is shallow is an assignment like `x = ...;`, which would | |
800 | /// be a *shallow write* of `x`." | |
801 | Shallow(Option<ArtificialField>), | |
802 | ||
803 | /// From the RFC: "A *deep* access means that all data reachable | |
804 | /// through the given place may be invalidated or accesses by | |
805 | /// this action." | |
806 | Deep, | |
0bf4aa26 XL |
807 | |
808 | /// Access is Deep only when there is a Drop implementation that | |
809 | /// can reach the data behind the reference. | |
810 | Drop, | |
ff7c6d11 XL |
811 | } |
812 | ||
813 | /// Kind of access to a value: read or write | |
814 | /// (For informational purposes only) | |
815 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
816 | enum ReadOrWrite { | |
817 | /// From the RFC: "A *read* means that the existing data may be | |
818 | /// read, but will not be changed." | |
819 | Read(ReadKind), | |
820 | ||
821 | /// From the RFC: "A *write* means that the data may be mutated to | |
822 | /// new values or otherwise invalidated (for example, it could be | |
823 | /// de-initialized, as in a move operation). | |
824 | Write(WriteKind), | |
825 | ||
826 | /// For two-phase borrows, we distinguish a reservation (which is treated | |
827 | /// like a Read) from an activation (which is treated like a write), and | |
828 | /// each of those is furthermore distinguished from Reads/Writes above. | |
829 | Reservation(WriteKind), | |
830 | Activation(WriteKind, BorrowIndex), | |
831 | } | |
832 | ||
833 | /// Kind of read access to a value | |
834 | /// (For informational purposes only) | |
835 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
836 | enum ReadKind { | |
837 | Borrow(BorrowKind), | |
838 | Copy, | |
839 | } | |
840 | ||
841 | /// Kind of write access to a value | |
842 | /// (For informational purposes only) | |
843 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
844 | enum WriteKind { | |
845 | StorageDeadOrDrop, | |
846 | MutableBorrow(BorrowKind), | |
847 | Mutate, | |
848 | Move, | |
849 | } | |
850 | ||
851 | /// When checking permissions for a place access, this flag is used to indicate that an immutable | |
852 | /// local place can be mutated. | |
9fa01778 XL |
853 | // |
854 | // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications: | |
855 | // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`. | |
856 | // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and | |
857 | // `is_declared_mutable()`. | |
858 | // - Take flow state into consideration in `is_assignable()` for local variables. | |
ff7c6d11 XL |
859 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
860 | enum LocalMutationIsAllowed { | |
861 | Yes, | |
862 | /// We want use of immutable upvars to cause a "write to immutable upvar" | |
863 | /// error, not an "reassignment" error. | |
864 | ExceptUpvars, | |
865 | No, | |
866 | } | |
867 | ||
0bf4aa26 | 868 | #[derive(Copy, Clone, Debug)] |
ff7c6d11 | 869 | enum InitializationRequiringAction { |
ff7c6d11 | 870 | Borrow, |
0bf4aa26 | 871 | MatchOn, |
ff7c6d11 XL |
872 | Use, |
873 | Assignment, | |
0bf4aa26 | 874 | PartialAssignment, |
ff7c6d11 XL |
875 | } |
876 | ||
74b04a01 XL |
877 | struct RootPlace<'tcx> { |
878 | place_local: Local, | |
879 | place_projection: &'tcx [PlaceElem<'tcx>], | |
83c7162d XL |
880 | is_local_mutation_allowed: LocalMutationIsAllowed, |
881 | } | |
882 | ||
ff7c6d11 XL |
883 | impl InitializationRequiringAction { |
884 | fn as_noun(self) -> &'static str { | |
885 | match self { | |
ff7c6d11 | 886 | InitializationRequiringAction::Borrow => "borrow", |
0bf4aa26 | 887 | InitializationRequiringAction::MatchOn => "use", // no good noun |
ff7c6d11 XL |
888 | InitializationRequiringAction::Use => "use", |
889 | InitializationRequiringAction::Assignment => "assign", | |
0bf4aa26 | 890 | InitializationRequiringAction::PartialAssignment => "assign to part", |
ff7c6d11 XL |
891 | } |
892 | } | |
893 | ||
894 | fn as_verb_in_past_tense(self) -> &'static str { | |
895 | match self { | |
ff7c6d11 | 896 | InitializationRequiringAction::Borrow => "borrowed", |
0bf4aa26 | 897 | InitializationRequiringAction::MatchOn => "matched on", |
ff7c6d11 XL |
898 | InitializationRequiringAction::Use => "used", |
899 | InitializationRequiringAction::Assignment => "assigned", | |
0bf4aa26 | 900 | InitializationRequiringAction::PartialAssignment => "partially assigned", |
b7449926 XL |
901 | } |
902 | } | |
064997fb FG |
903 | |
904 | fn as_general_verb_in_past_tense(self) -> &'static str { | |
905 | match self { | |
906 | InitializationRequiringAction::Borrow | |
907 | | InitializationRequiringAction::MatchOn | |
908 | | InitializationRequiringAction::Use => "used", | |
909 | InitializationRequiringAction::Assignment => "assigned", | |
910 | InitializationRequiringAction::PartialAssignment => "partially assigned", | |
911 | } | |
912 | } | |
b7449926 XL |
913 | } |
914 | ||
dc9dc135 | 915 | impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { |
74b04a01 | 916 | fn body(&self) -> &'cx Body<'tcx> { |
f9f354fc | 917 | self.body |
74b04a01 XL |
918 | } |
919 | ||
ff7c6d11 XL |
920 | /// Checks an access to the given place to see if it is allowed. Examines the set of borrows |
921 | /// that are in scope, as well as which paths have been initialized, to ensure that (a) the | |
922 | /// place is initialized and (b) it is not borrowed in some way that would prevent this | |
923 | /// access. | |
924 | /// | |
9fa01778 | 925 | /// Returns `true` if an error is reported. |
ff7c6d11 XL |
926 | fn access_place( |
927 | &mut self, | |
48663c56 | 928 | location: Location, |
ba9703b0 | 929 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 930 | kind: (AccessDepth, ReadOrWrite), |
ff7c6d11 | 931 | is_local_mutation_allowed: LocalMutationIsAllowed, |
dc9dc135 | 932 | flow_state: &Flows<'cx, 'tcx>, |
b7449926 | 933 | ) { |
ff7c6d11 XL |
934 | let (sd, rw) = kind; |
935 | ||
936 | if let Activation(_, borrow_index) = rw { | |
937 | if self.reservation_error_reported.contains(&place_span.0) { | |
0531ce1d XL |
938 | debug!( |
939 | "skipping access_place for activation of invalid reservation \ | |
940 | place: {:?} borrow_index: {:?}", | |
941 | place_span.0, borrow_index | |
942 | ); | |
b7449926 | 943 | return; |
ff7c6d11 XL |
944 | } |
945 | } | |
946 | ||
b7449926 XL |
947 | // Check is_empty() first because it's the common case, and doing that |
948 | // way we avoid the clone() call. | |
dfeec247 | 949 | if !self.access_place_error_reported.is_empty() |
ba9703b0 | 950 | && self.access_place_error_reported.contains(&(place_span.0, place_span.1)) |
0531ce1d XL |
951 | { |
952 | debug!( | |
953 | "access_place: suppressing error place_span=`{:?}` kind=`{:?}`", | |
954 | place_span, kind | |
955 | ); | |
b7449926 | 956 | return; |
2c00a5a8 XL |
957 | } |
958 | ||
dfeec247 XL |
959 | let mutability_error = self.check_access_permissions( |
960 | place_span, | |
961 | rw, | |
962 | is_local_mutation_allowed, | |
963 | flow_state, | |
964 | location, | |
965 | ); | |
ff7c6d11 | 966 | let conflict_error = |
48663c56 | 967 | self.check_access_for_conflict(location, place_span, sd, rw, flow_state); |
ff7c6d11 | 968 | |
2c00a5a8 | 969 | if conflict_error || mutability_error { |
dfeec247 | 970 | debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind); |
ba9703b0 | 971 | self.access_place_error_reported.insert((place_span.0, place_span.1)); |
2c00a5a8 | 972 | } |
ff7c6d11 XL |
973 | } |
974 | ||
f2b60f7d | 975 | #[instrument(level = "debug", skip(self, flow_state))] |
ff7c6d11 XL |
976 | fn check_access_for_conflict( |
977 | &mut self, | |
48663c56 | 978 | location: Location, |
ba9703b0 | 979 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 980 | sd: AccessDepth, |
ff7c6d11 | 981 | rw: ReadOrWrite, |
dc9dc135 | 982 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
983 | ) -> bool { |
984 | let mut error_reported = false; | |
0bf4aa26 | 985 | let tcx = self.infcx.tcx; |
dc9dc135 | 986 | let body = self.body; |
94b46f34 | 987 | let borrow_set = self.borrow_set.clone(); |
74b04a01 XL |
988 | |
989 | // Use polonius output if it has been enabled. | |
990 | let polonius_output = self.polonius_output.clone(); | |
991 | let borrows_in_scope = if let Some(polonius) = &polonius_output { | |
992 | let location = self.location_table.start_index(location); | |
993 | Either::Left(polonius.errors_at(location).iter().copied()) | |
994 | } else { | |
995 | Either::Right(flow_state.borrows.iter()) | |
996 | }; | |
997 | ||
94b46f34 XL |
998 | each_borrow_involving_path( |
999 | self, | |
1000 | tcx, | |
dc9dc135 | 1001 | body, |
48663c56 | 1002 | location, |
ff7c6d11 | 1003 | (sd, place_span.0), |
94b46f34 | 1004 | &borrow_set, |
74b04a01 | 1005 | borrows_in_scope, |
8faf50e0 | 1006 | |this, borrow_index, borrow| match (rw, borrow.kind) { |
ff7c6d11 XL |
1007 | // Obviously an activation is compatible with its own |
1008 | // reservation (or even prior activating uses of same | |
1009 | // borrow); so don't check if they interfere. | |
1010 | // | |
1011 | // NOTE: *reservations* do conflict with themselves; | |
5e7ed085 | 1012 | // thus aren't injecting unsoundness w/ this check.) |
83c7162d | 1013 | (Activation(_, activating), _) if activating == borrow_index => { |
ff7c6d11 XL |
1014 | debug!( |
1015 | "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \ | |
83c7162d | 1016 | skipping {:?} b/c activation of same borrow_index", |
ff7c6d11 XL |
1017 | place_span, |
1018 | sd, | |
1019 | rw, | |
83c7162d | 1020 | (borrow_index, borrow), |
ff7c6d11 XL |
1021 | ); |
1022 | Control::Continue | |
1023 | } | |
1024 | ||
ba9703b0 XL |
1025 | (Read(_), BorrowKind::Shared | BorrowKind::Shallow) |
1026 | | ( | |
1027 | Read(ReadKind::Borrow(BorrowKind::Shallow)), | |
1028 | BorrowKind::Unique | BorrowKind::Mut { .. }, | |
1029 | ) => Control::Continue, | |
0bf4aa26 | 1030 | |
04454e1e FG |
1031 | (Reservation(_), BorrowKind::Shallow | BorrowKind::Shared) => { |
1032 | // This used to be a future compatibility warning (to be | |
1033 | // disallowed on NLL). See rust-lang/rust#56254 | |
1034 | Control::Continue | |
1035 | } | |
1036 | ||
0bf4aa26 XL |
1037 | (Write(WriteKind::Move), BorrowKind::Shallow) => { |
1038 | // Handled by initialization checks. | |
ff7c6d11 XL |
1039 | Control::Continue |
1040 | } | |
1041 | ||
ba9703b0 | 1042 | (Read(kind), BorrowKind::Unique | BorrowKind::Mut { .. }) => { |
ff7c6d11 | 1043 | // Reading from mere reservations of mutable-borrows is OK. |
48663c56 XL |
1044 | if !is_active(&this.dominators, borrow, location) { |
1045 | assert!(allow_two_phase_borrow(borrow.kind)); | |
ff7c6d11 XL |
1046 | return Control::Continue; |
1047 | } | |
1048 | ||
0bf4aa26 | 1049 | error_reported = true; |
ff7c6d11 | 1050 | match kind { |
dfeec247 | 1051 | ReadKind::Copy => { |
5099ac24 FG |
1052 | let err = this |
1053 | .report_use_while_mutably_borrowed(location, place_span, borrow); | |
1054 | this.buffer_error(err); | |
ff7c6d11 XL |
1055 | } |
1056 | ReadKind::Borrow(bk) => { | |
5099ac24 FG |
1057 | let err = |
1058 | this.report_conflicting_borrow(location, place_span, bk, borrow); | |
1059 | this.buffer_error(err); | |
ff7c6d11 XL |
1060 | } |
1061 | } | |
1062 | Control::Break | |
1063 | } | |
1064 | ||
ba9703b0 | 1065 | (Reservation(kind) | Activation(kind, _) | Write(kind), _) => { |
ff7c6d11 | 1066 | match rw { |
532ac7d7 | 1067 | Reservation(..) => { |
ff7c6d11 XL |
1068 | debug!( |
1069 | "recording invalid reservation of \ | |
1070 | place: {:?}", | |
1071 | place_span.0 | |
1072 | ); | |
ba9703b0 | 1073 | this.reservation_error_reported.insert(place_span.0); |
0531ce1d | 1074 | } |
ff7c6d11 XL |
1075 | Activation(_, activating) => { |
1076 | debug!( | |
1077 | "observing check_place for activation of \ | |
1078 | borrow_index: {:?}", | |
1079 | activating | |
1080 | ); | |
0531ce1d XL |
1081 | } |
1082 | Read(..) | Write(..) => {} | |
ff7c6d11 XL |
1083 | } |
1084 | ||
0bf4aa26 | 1085 | error_reported = true; |
ff7c6d11 XL |
1086 | match kind { |
1087 | WriteKind::MutableBorrow(bk) => { | |
5099ac24 FG |
1088 | let err = |
1089 | this.report_conflicting_borrow(location, place_span, bk, borrow); | |
1090 | this.buffer_error(err); | |
ff7c6d11 | 1091 | } |
dfeec247 XL |
1092 | WriteKind::StorageDeadOrDrop => this |
1093 | .report_borrowed_value_does_not_live_long_enough( | |
48663c56 | 1094 | location, |
ff7c6d11 | 1095 | borrow, |
94b46f34 | 1096 | place_span, |
dfeec247 XL |
1097 | Some(kind), |
1098 | ), | |
ff7c6d11 | 1099 | WriteKind::Mutate => { |
48663c56 | 1100 | this.report_illegal_mutation_of_borrowed(location, place_span, borrow) |
ff7c6d11 XL |
1101 | } |
1102 | WriteKind::Move => { | |
48663c56 | 1103 | this.report_move_out_while_borrowed(location, place_span, borrow) |
ff7c6d11 XL |
1104 | } |
1105 | } | |
1106 | Control::Break | |
1107 | } | |
1108 | }, | |
1109 | ); | |
1110 | ||
1111 | error_reported | |
1112 | } | |
1113 | ||
1114 | fn mutate_place( | |
1115 | &mut self, | |
48663c56 | 1116 | location: Location, |
ba9703b0 | 1117 | place_span: (Place<'tcx>, Span), |
0bf4aa26 | 1118 | kind: AccessDepth, |
dc9dc135 | 1119 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1120 | ) { |
5099ac24 FG |
1121 | // Write of P[i] or *P requires P init'd. |
1122 | self.check_if_assigned_path_is_moved(location, place_span, flow_state); | |
ff7c6d11 | 1123 | |
94222f64 | 1124 | // Special case: you can assign an immutable local variable |
b7449926 XL |
1125 | // (e.g., `x = ...`) so long as it has never been initialized |
1126 | // before (at this point in the flow). | |
e74abb32 XL |
1127 | if let Some(local) = place_span.0.as_local() { |
1128 | if let Mutability::Not = self.body.local_decls[local].mutability { | |
b7449926 XL |
1129 | // check for reassignments to immutable local variables |
1130 | self.check_if_reassignment_to_immutable_state( | |
dfeec247 | 1131 | location, local, place_span, flow_state, |
b7449926 XL |
1132 | ); |
1133 | return; | |
1134 | } | |
1135 | } | |
1136 | ||
1137 | // Otherwise, use the normal access permission rules. | |
1138 | self.access_place( | |
48663c56 | 1139 | location, |
ff7c6d11 XL |
1140 | place_span, |
1141 | (kind, Write(WriteKind::Mutate)), | |
b7449926 | 1142 | LocalMutationIsAllowed::No, |
ff7c6d11 XL |
1143 | flow_state, |
1144 | ); | |
ff7c6d11 XL |
1145 | } |
1146 | ||
1147 | fn consume_rvalue( | |
1148 | &mut self, | |
48663c56 | 1149 | location: Location, |
416331ca | 1150 | (rvalue, span): (&'cx Rvalue<'tcx>, Span), |
dc9dc135 | 1151 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
1152 | ) { |
1153 | match *rvalue { | |
ba9703b0 | 1154 | Rvalue::Ref(_ /*rgn*/, bk, place) => { |
ff7c6d11 | 1155 | let access_kind = match bk { |
0bf4aa26 XL |
1156 | BorrowKind::Shallow => { |
1157 | (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk))) | |
dfeec247 | 1158 | } |
ff7c6d11 | 1159 | BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))), |
2c00a5a8 | 1160 | BorrowKind::Unique | BorrowKind::Mut { .. } => { |
ff7c6d11 | 1161 | let wk = WriteKind::MutableBorrow(bk); |
48663c56 | 1162 | if allow_two_phase_borrow(bk) { |
ff7c6d11 XL |
1163 | (Deep, Reservation(wk)) |
1164 | } else { | |
1165 | (Deep, Write(wk)) | |
1166 | } | |
1167 | } | |
1168 | }; | |
1169 | ||
1170 | self.access_place( | |
48663c56 | 1171 | location, |
ff7c6d11 XL |
1172 | (place, span), |
1173 | access_kind, | |
1174 | LocalMutationIsAllowed::No, | |
1175 | flow_state, | |
1176 | ); | |
1177 | ||
0bf4aa26 XL |
1178 | let action = if bk == BorrowKind::Shallow { |
1179 | InitializationRequiringAction::MatchOn | |
1180 | } else { | |
1181 | InitializationRequiringAction::Borrow | |
1182 | }; | |
1183 | ||
83c7162d | 1184 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1185 | location, |
0bf4aa26 | 1186 | action, |
416331ca | 1187 | (place.as_ref(), span), |
ff7c6d11 XL |
1188 | flow_state, |
1189 | ); | |
1190 | } | |
1191 | ||
ba9703b0 | 1192 | Rvalue::AddressOf(mutability, place) => { |
dfeec247 XL |
1193 | let access_kind = match mutability { |
1194 | Mutability::Mut => ( | |
1195 | Deep, | |
1196 | Write(WriteKind::MutableBorrow(BorrowKind::Mut { | |
1197 | allow_two_phase_borrow: false, | |
1198 | })), | |
1199 | ), | |
1200 | Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))), | |
1201 | }; | |
1202 | ||
1203 | self.access_place( | |
1204 | location, | |
1205 | (place, span), | |
1206 | access_kind, | |
1207 | LocalMutationIsAllowed::No, | |
1208 | flow_state, | |
1209 | ); | |
1210 | ||
1211 | self.check_if_path_or_subpath_is_moved( | |
1212 | location, | |
1213 | InitializationRequiringAction::Borrow, | |
1214 | (place.as_ref(), span), | |
1215 | flow_state, | |
1216 | ); | |
1217 | } | |
1218 | ||
f9f354fc XL |
1219 | Rvalue::ThreadLocalRef(_) => {} |
1220 | ||
ff7c6d11 XL |
1221 | Rvalue::Use(ref operand) |
1222 | | Rvalue::Repeat(ref operand, _) | |
1223 | | Rvalue::UnaryOp(_ /*un_op*/, ref operand) | |
c295e0f8 XL |
1224 | | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) |
1225 | | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => { | |
48663c56 | 1226 | self.consume_operand(location, (operand, span), flow_state) |
ff7c6d11 | 1227 | } |
064997fb FG |
1228 | Rvalue::CopyForDeref(place) => { |
1229 | self.access_place( | |
1230 | location, | |
1231 | (place, span), | |
1232 | (Deep, Read(ReadKind::Copy)), | |
1233 | LocalMutationIsAllowed::No, | |
1234 | flow_state, | |
1235 | ); | |
1236 | ||
1237 | // Finally, check if path was already moved. | |
1238 | self.check_if_path_or_subpath_is_moved( | |
1239 | location, | |
1240 | InitializationRequiringAction::Use, | |
1241 | (place.as_ref(), span), | |
1242 | flow_state, | |
1243 | ); | |
1244 | } | |
ff7c6d11 | 1245 | |
ba9703b0 | 1246 | Rvalue::Len(place) | Rvalue::Discriminant(place) => { |
ff7c6d11 | 1247 | let af = match *rvalue { |
0731742a XL |
1248 | Rvalue::Len(..) => Some(ArtificialField::ArrayLength), |
1249 | Rvalue::Discriminant(..) => None, | |
ff7c6d11 XL |
1250 | _ => unreachable!(), |
1251 | }; | |
1252 | self.access_place( | |
48663c56 | 1253 | location, |
ff7c6d11 | 1254 | (place, span), |
0731742a | 1255 | (Shallow(af), Read(ReadKind::Copy)), |
ff7c6d11 XL |
1256 | LocalMutationIsAllowed::No, |
1257 | flow_state, | |
1258 | ); | |
83c7162d | 1259 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1260 | location, |
ff7c6d11 | 1261 | InitializationRequiringAction::Use, |
416331ca | 1262 | (place.as_ref(), span), |
ff7c6d11 XL |
1263 | flow_state, |
1264 | ); | |
1265 | } | |
1266 | ||
6a06907d XL |
1267 | Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2)) |
1268 | | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => { | |
48663c56 XL |
1269 | self.consume_operand(location, (operand1, span), flow_state); |
1270 | self.consume_operand(location, (operand2, span), flow_state); | |
ff7c6d11 XL |
1271 | } |
1272 | ||
1273 | Rvalue::NullaryOp(_op, _ty) => { | |
1274 | // nullary ops take no dynamic input; no borrowck effect. | |
ff7c6d11 XL |
1275 | } |
1276 | ||
83c7162d XL |
1277 | Rvalue::Aggregate(ref aggregate_kind, ref operands) => { |
1278 | // We need to report back the list of mutable upvars that were | |
1279 | // moved into the closure and subsequently used by the closure, | |
1280 | // in order to populate our used_mut set. | |
8faf50e0 | 1281 | match **aggregate_kind { |
dfeec247 XL |
1282 | AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => { |
1283 | let BorrowCheckResult { used_mut_upvars, .. } = | |
064997fb | 1284 | self.infcx.tcx.mir_borrowck(def_id); |
8faf50e0 XL |
1285 | debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars); |
1286 | for field in used_mut_upvars { | |
48663c56 | 1287 | self.propagate_closure_used_mut_upvar(&operands[field.index()]); |
83c7162d XL |
1288 | } |
1289 | } | |
8faf50e0 XL |
1290 | AggregateKind::Adt(..) |
1291 | | AggregateKind::Array(..) | |
1292 | | AggregateKind::Tuple { .. } => (), | |
83c7162d XL |
1293 | } |
1294 | ||
1295 | for operand in operands { | |
48663c56 XL |
1296 | self.consume_operand(location, (operand, span), flow_state); |
1297 | } | |
1298 | } | |
1299 | } | |
1300 | } | |
1301 | ||
1302 | fn propagate_closure_used_mut_upvar(&mut self, operand: &Operand<'tcx>) { | |
ba9703b0 | 1303 | let propagate_closure_used_mut_place = |this: &mut Self, place: Place<'tcx>| { |
5869c6ff XL |
1304 | // We have three possibilities here: |
1305 | // a. We are modifying something through a mut-ref | |
1306 | // b. We are modifying something that is local to our parent | |
1307 | // c. Current body is a nested closure, and we are modifying path starting from | |
1308 | // a Place captured by our parent closure. | |
1309 | ||
1310 | // Handle (c), the path being modified is exactly the path captured by our parent | |
1311 | if let Some(field) = this.is_upvar_field_projection(place.as_ref()) { | |
1312 | this.used_mut_upvars.push(field); | |
1313 | return; | |
1314 | } | |
1315 | ||
1316 | for (place_ref, proj) in place.iter_projections().rev() { | |
1317 | // Handle (a) | |
1318 | if proj == ProjectionElem::Deref { | |
1319 | match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() { | |
1320 | // We aren't modifying a variable directly | |
1321 | ty::Ref(_, _, hir::Mutability::Mut) => return, | |
1322 | ||
1323 | _ => {} | |
1324 | } | |
1325 | } | |
1326 | ||
1327 | // Handle (c) | |
1328 | if let Some(field) = this.is_upvar_field_projection(place_ref) { | |
416331ca | 1329 | this.used_mut_upvars.push(field); |
5869c6ff | 1330 | return; |
48663c56 | 1331 | } |
48663c56 | 1332 | } |
5869c6ff XL |
1333 | |
1334 | // Handle(b) | |
1335 | this.used_mut.insert(place.local); | |
48663c56 XL |
1336 | }; |
1337 | ||
1338 | // This relies on the current way that by-value | |
1339 | // captures of a closure are copied/moved directly | |
1340 | // when generating MIR. | |
1341 | match *operand { | |
ba9703b0 | 1342 | Operand::Move(place) | Operand::Copy(place) => { |
e74abb32 | 1343 | match place.as_local() { |
60c5eb7d | 1344 | Some(local) if !self.body.local_decls[local].is_user_variable() => { |
e74abb32 XL |
1345 | if self.body.local_decls[local].ty.is_mutable_ptr() { |
1346 | // The variable will be marked as mutable by the borrow. | |
1347 | return; | |
1348 | } | |
1349 | // This is an edge case where we have a `move` closure | |
1350 | // inside a non-move closure, and the inner closure | |
1351 | // contains a mutation: | |
1352 | // | |
1353 | // let mut i = 0; | |
1354 | // || { move || { i += 1; }; }; | |
1355 | // | |
1356 | // In this case our usual strategy of assuming that the | |
1357 | // variable will be captured by mutable reference is | |
1358 | // wrong, since `i` can be copied into the inner | |
1359 | // closure from a shared reference. | |
1360 | // | |
1361 | // As such we have to search for the local that this | |
1362 | // capture comes from and mark it as being used as mut. | |
1363 | ||
1364 | let temp_mpi = self.move_data.rev_lookup.find_local(local); | |
1365 | let init = if let [init_index] = *self.move_data.init_path_map[temp_mpi] { | |
1366 | &self.move_data.inits[init_index] | |
1367 | } else { | |
1368 | bug!("temporary should be initialized exactly once") | |
1369 | }; | |
48663c56 | 1370 | |
5099ac24 FG |
1371 | let InitLocation::Statement(loc) = init.location else { |
1372 | bug!("temporary initialized in arguments") | |
e74abb32 | 1373 | }; |
48663c56 | 1374 | |
60c5eb7d XL |
1375 | let body = self.body; |
1376 | let bbd = &body[loc.block]; | |
e74abb32 XL |
1377 | let stmt = &bbd.statements[loc.statement_index]; |
1378 | debug!("temporary assigned in: stmt={:?}", stmt); | |
48663c56 | 1379 | |
ba9703b0 | 1380 | if let StatementKind::Assign(box (_, Rvalue::Ref(_, _, source))) = stmt.kind |
e74abb32 XL |
1381 | { |
1382 | propagate_closure_used_mut_place(self, source); | |
1383 | } else { | |
1384 | bug!( | |
1385 | "closures should only capture user variables \ | |
1386 | or references to user variables" | |
1387 | ); | |
1388 | } | |
1389 | } | |
1390 | _ => propagate_closure_used_mut_place(self, place), | |
83c7162d XL |
1391 | } |
1392 | } | |
48663c56 | 1393 | Operand::Constant(..) => {} |
ff7c6d11 XL |
1394 | } |
1395 | } | |
1396 | ||
1397 | fn consume_operand( | |
1398 | &mut self, | |
48663c56 | 1399 | location: Location, |
416331ca | 1400 | (operand, span): (&'cx Operand<'tcx>, Span), |
dc9dc135 | 1401 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 XL |
1402 | ) { |
1403 | match *operand { | |
ba9703b0 | 1404 | Operand::Copy(place) => { |
ff7c6d11 XL |
1405 | // copy of place: check if this is "copy of frozen path" |
1406 | // (FIXME: see check_loans.rs) | |
1407 | self.access_place( | |
48663c56 | 1408 | location, |
ff7c6d11 XL |
1409 | (place, span), |
1410 | (Deep, Read(ReadKind::Copy)), | |
1411 | LocalMutationIsAllowed::No, | |
1412 | flow_state, | |
1413 | ); | |
1414 | ||
1415 | // Finally, check if path was already moved. | |
83c7162d | 1416 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1417 | location, |
ff7c6d11 | 1418 | InitializationRequiringAction::Use, |
416331ca | 1419 | (place.as_ref(), span), |
ff7c6d11 XL |
1420 | flow_state, |
1421 | ); | |
1422 | } | |
ba9703b0 | 1423 | Operand::Move(place) => { |
ff7c6d11 XL |
1424 | // move of place: check if this is move of already borrowed path |
1425 | self.access_place( | |
48663c56 | 1426 | location, |
ff7c6d11 XL |
1427 | (place, span), |
1428 | (Deep, Write(WriteKind::Move)), | |
1429 | LocalMutationIsAllowed::Yes, | |
1430 | flow_state, | |
1431 | ); | |
1432 | ||
1433 | // Finally, check if path was already moved. | |
83c7162d | 1434 | self.check_if_path_or_subpath_is_moved( |
48663c56 | 1435 | location, |
ff7c6d11 | 1436 | InitializationRequiringAction::Use, |
416331ca | 1437 | (place.as_ref(), span), |
ff7c6d11 XL |
1438 | flow_state, |
1439 | ); | |
1440 | } | |
1441 | Operand::Constant(_) => {} | |
1442 | } | |
1443 | } | |
1444 | ||
0bf4aa26 | 1445 | /// Checks whether a borrow of this place is invalidated when the function |
ff7c6d11 | 1446 | /// exits |
f2b60f7d | 1447 | #[instrument(level = "debug", skip(self))] |
ff7c6d11 XL |
1448 | fn check_for_invalidation_at_exit( |
1449 | &mut self, | |
48663c56 | 1450 | location: Location, |
ff7c6d11 XL |
1451 | borrow: &BorrowData<'tcx>, |
1452 | span: Span, | |
ff7c6d11 | 1453 | ) { |
ba9703b0 | 1454 | let place = borrow.borrowed_place; |
74b04a01 | 1455 | let mut root_place = PlaceRef { local: place.local, projection: &[] }; |
ff7c6d11 XL |
1456 | |
1457 | // FIXME(nll-rfc#40): do more precise destructor tracking here. For now | |
1458 | // we just know that all locals are dropped at function exit (otherwise | |
1459 | // we'll have a memory leak) and assume that all statics have a destructor. | |
1460 | // | |
1461 | // FIXME: allow thread-locals to borrow other thread locals? | |
416331ca | 1462 | |
dfeec247 | 1463 | let (might_be_alive, will_be_dropped) = |
74b04a01 | 1464 | if self.body.local_decls[root_place.local].is_ref_to_thread_local() { |
dfeec247 XL |
1465 | // Thread-locals might be dropped after the function exits |
1466 | // We have to dereference the outer reference because | |
1467 | // borrows don't conflict behind shared references. | |
923072b8 | 1468 | root_place.projection = TyCtxtConsts::DEREF_PROJECTION; |
dfeec247 XL |
1469 | (true, true) |
1470 | } else { | |
1471 | (false, self.locals_are_invalidated_at_exit) | |
1472 | }; | |
ff7c6d11 XL |
1473 | |
1474 | if !will_be_dropped { | |
dfeec247 | 1475 | debug!("place_is_invalidated_at_exit({:?}) - won't be dropped", place); |
ff7c6d11 XL |
1476 | return; |
1477 | } | |
1478 | ||
ff7c6d11 XL |
1479 | let sd = if might_be_alive { Deep } else { Shallow(None) }; |
1480 | ||
0bf4aa26 XL |
1481 | if places_conflict::borrow_conflicts_with_place( |
1482 | self.infcx.tcx, | |
60c5eb7d | 1483 | &self.body, |
0bf4aa26 XL |
1484 | place, |
1485 | borrow.kind, | |
1486 | root_place, | |
0731742a XL |
1487 | sd, |
1488 | places_conflict::PlaceConflictBias::Overlap, | |
0bf4aa26 | 1489 | ) { |
ff7c6d11 XL |
1490 | debug!("check_for_invalidation_at_exit({:?}): INVALID", place); |
1491 | // FIXME: should be talking about the region lifetime instead | |
1492 | // of just a span here. | |
0bf4aa26 | 1493 | let span = self.infcx.tcx.sess.source_map().end_point(span); |
ff7c6d11 | 1494 | self.report_borrowed_value_does_not_live_long_enough( |
48663c56 | 1495 | location, |
ff7c6d11 | 1496 | borrow, |
94b46f34 XL |
1497 | (place, span), |
1498 | None, | |
ff7c6d11 XL |
1499 | ) |
1500 | } | |
1501 | } | |
1502 | ||
2c00a5a8 | 1503 | /// Reports an error if this is a borrow of local data. |
dfeec247 | 1504 | /// This is called for all Yield expressions on movable generators |
0531ce1d | 1505 | fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) { |
2c00a5a8 XL |
1506 | debug!("check_for_local_borrow({:?})", borrow); |
1507 | ||
ba9703b0 | 1508 | if borrow_of_local_data(borrow.borrowed_place) { |
416331ca | 1509 | let err = self.cannot_borrow_across_generator_yield( |
dfeec247 XL |
1510 | self.retrieve_borrow_spans(borrow).var_or_use(), |
1511 | yield_span, | |
1512 | ); | |
8faf50e0 | 1513 | |
5099ac24 | 1514 | self.buffer_error(err); |
2c00a5a8 XL |
1515 | } |
1516 | } | |
1517 | ||
dc9dc135 | 1518 | fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) { |
ff7c6d11 XL |
1519 | // Two-phase borrow support: For each activation that is newly |
1520 | // generated at this statement, check if it interferes with | |
1521 | // another borrow. | |
83c7162d XL |
1522 | let borrow_set = self.borrow_set.clone(); |
1523 | for &borrow_index in borrow_set.activations_at_location(location) { | |
1524 | let borrow = &borrow_set[borrow_index]; | |
1525 | ||
1526 | // only mutable borrows should be 2-phase | |
1527 | assert!(match borrow.kind { | |
0bf4aa26 | 1528 | BorrowKind::Shared | BorrowKind::Shallow => false, |
83c7162d XL |
1529 | BorrowKind::Unique | BorrowKind::Mut { .. } => true, |
1530 | }); | |
1531 | ||
1532 | self.access_place( | |
48663c56 | 1533 | location, |
ba9703b0 | 1534 | (borrow.borrowed_place, span), |
dfeec247 | 1535 | (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)), |
83c7162d XL |
1536 | LocalMutationIsAllowed::No, |
1537 | flow_state, | |
1538 | ); | |
1539 | // We do not need to call `check_if_path_or_subpath_is_moved` | |
1540 | // again, as we already called it when we made the | |
1541 | // initial reservation. | |
1542 | } | |
ff7c6d11 | 1543 | } |
ff7c6d11 | 1544 | |
ff7c6d11 XL |
1545 | fn check_if_reassignment_to_immutable_state( |
1546 | &mut self, | |
48663c56 | 1547 | location: Location, |
b7449926 | 1548 | local: Local, |
ba9703b0 | 1549 | place_span: (Place<'tcx>, Span), |
dc9dc135 | 1550 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1551 | ) { |
b7449926 XL |
1552 | debug!("check_if_reassignment_to_immutable_state({:?})", local); |
1553 | ||
5e7ed085 | 1554 | // Check if any of the initializations of `local` have happened yet: |
0bf4aa26 | 1555 | if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) { |
b7449926 XL |
1556 | // And, if so, report an error. |
1557 | let init = &self.move_data.inits[init_index]; | |
dc9dc135 | 1558 | let span = init.span(&self.body); |
dfeec247 | 1559 | self.report_illegal_reassignment(location, place_span, span, place_span.0); |
ff7c6d11 XL |
1560 | } |
1561 | } | |
1562 | ||
83c7162d | 1563 | fn check_if_full_path_is_moved( |
ff7c6d11 | 1564 | &mut self, |
48663c56 | 1565 | location: Location, |
ff7c6d11 | 1566 | desired_action: InitializationRequiringAction, |
74b04a01 | 1567 | place_span: (PlaceRef<'tcx>, Span), |
dc9dc135 | 1568 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1569 | ) { |
ff7c6d11 | 1570 | let maybe_uninits = &flow_state.uninits; |
ff7c6d11 XL |
1571 | |
1572 | // Bad scenarios: | |
1573 | // | |
1574 | // 1. Move of `a.b.c`, use of `a.b.c` | |
1575 | // 2. Move of `a.b.c`, use of `a.b.c.d` (without first reinitializing `a.b.c.d`) | |
83c7162d | 1576 | // 3. Uninitialized `(a.b.c: &_)`, use of `*a.b.c`; note that with |
ff7c6d11 XL |
1577 | // partial initialization support, one might have `a.x` |
1578 | // initialized but not `a.b`. | |
1579 | // | |
1580 | // OK scenarios: | |
1581 | // | |
83c7162d XL |
1582 | // 4. Move of `a.b.c`, use of `a.b.d` |
1583 | // 5. Uninitialized `a.x`, initialized `a.b`, use of `a.b` | |
1584 | // 6. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b` | |
ff7c6d11 | 1585 | // must have been initialized for the use to be sound. |
83c7162d | 1586 | // 7. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d` |
ff7c6d11 XL |
1587 | |
1588 | // The dataflow tracks shallow prefixes distinctly (that is, | |
1589 | // field-accesses on P distinctly from P itself), in order to | |
1590 | // track substructure initialization separately from the whole | |
1591 | // structure. | |
1592 | // | |
1593 | // E.g., when looking at (*a.b.c).d, if the closest prefix for | |
1594 | // which we have a MovePath is `a.b`, then that means that the | |
1595 | // initialization state of `a.b` is all we need to inspect to | |
1596 | // know if `a.b.c` is valid (and from that we infer that the | |
1597 | // dereference and `.d` access is also valid, since we assume | |
94222f64 | 1598 | // `a.b.c` is assigned a reference to an initialized and |
ff7c6d11 XL |
1599 | // well-formed record structure.) |
1600 | ||
1601 | // Therefore, if we seek out the *closest* prefix for which we | |
1602 | // have a MovePath, that should capture the initialization | |
1603 | // state for the place scenario. | |
1604 | // | |
83c7162d | 1605 | // This code covers scenarios 1, 2, and 3. |
ff7c6d11 | 1606 | |
b7449926 | 1607 | debug!("check_if_full_path_is_moved place: {:?}", place_span.0); |
dfeec247 XL |
1608 | let (prefix, mpi) = self.move_path_closest_to(place_span.0); |
1609 | if maybe_uninits.contains(mpi) { | |
1610 | self.report_use_of_moved_or_uninitialized( | |
1611 | location, | |
1612 | desired_action, | |
1613 | (prefix, place_span.0, place_span.1), | |
1614 | mpi, | |
1615 | ); | |
1616 | } // Only query longest prefix with a MovePath, not further | |
1617 | // ancestors; dataflow recurs on children when parents | |
1618 | // move (to support partial (re)inits). | |
1619 | // | |
1620 | // (I.e., querying parents breaks scenario 7; but may want | |
1621 | // to do such a query based on partial-init feature-gate.) | |
83c7162d XL |
1622 | } |
1623 | ||
60c5eb7d XL |
1624 | /// Subslices correspond to multiple move paths, so we iterate through the |
1625 | /// elements of the base array. For each element we check | |
1626 | /// | |
1627 | /// * Does this element overlap with our slice. | |
1628 | /// * Is any part of it uninitialized. | |
1629 | fn check_if_subslice_element_is_moved( | |
1630 | &mut self, | |
1631 | location: Location, | |
1632 | desired_action: InitializationRequiringAction, | |
74b04a01 | 1633 | place_span: (PlaceRef<'tcx>, Span), |
5e7ed085 | 1634 | maybe_uninits: &ChunkedBitSet<MovePathIndex>, |
1b1a35ee XL |
1635 | from: u64, |
1636 | to: u64, | |
60c5eb7d XL |
1637 | ) { |
1638 | if let Some(mpi) = self.move_path_for_place(place_span.0) { | |
74b04a01 XL |
1639 | let move_paths = &self.move_data.move_paths; |
1640 | ||
1641 | let root_path = &move_paths[mpi]; | |
1642 | for (child_mpi, child_move_path) in root_path.children(move_paths) { | |
1643 | let last_proj = child_move_path.place.projection.last().unwrap(); | |
60c5eb7d XL |
1644 | if let ProjectionElem::ConstantIndex { offset, from_end, .. } = last_proj { |
1645 | debug_assert!(!from_end, "Array constant indexing shouldn't be `from_end`."); | |
1646 | ||
1647 | if (from..to).contains(offset) { | |
74b04a01 XL |
1648 | let uninit_child = |
1649 | self.move_data.find_in_move_path_or_its_descendants(child_mpi, |mpi| { | |
1650 | maybe_uninits.contains(mpi) | |
1651 | }); | |
1652 | ||
1653 | if let Some(uninit_child) = uninit_child { | |
60c5eb7d XL |
1654 | self.report_use_of_moved_or_uninitialized( |
1655 | location, | |
1656 | desired_action, | |
1657 | (place_span.0, place_span.0, place_span.1), | |
1658 | uninit_child, | |
1659 | ); | |
1660 | return; // don't bother finding other problems. | |
1661 | } | |
1662 | } | |
1663 | } | |
60c5eb7d XL |
1664 | } |
1665 | } | |
1666 | } | |
1667 | ||
83c7162d XL |
1668 | fn check_if_path_or_subpath_is_moved( |
1669 | &mut self, | |
48663c56 | 1670 | location: Location, |
83c7162d | 1671 | desired_action: InitializationRequiringAction, |
74b04a01 | 1672 | place_span: (PlaceRef<'tcx>, Span), |
dc9dc135 | 1673 | flow_state: &Flows<'cx, 'tcx>, |
83c7162d | 1674 | ) { |
83c7162d | 1675 | let maybe_uninits = &flow_state.uninits; |
83c7162d XL |
1676 | |
1677 | // Bad scenarios: | |
1678 | // | |
1679 | // 1. Move of `a.b.c`, use of `a` or `a.b` | |
1680 | // partial initialization support, one might have `a.x` | |
1681 | // initialized but not `a.b`. | |
1682 | // 2. All bad scenarios from `check_if_full_path_is_moved` | |
1683 | // | |
1684 | // OK scenarios: | |
1685 | // | |
1686 | // 3. Move of `a.b.c`, use of `a.b.d` | |
1687 | // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b` | |
1688 | // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b` | |
1689 | // must have been initialized for the use to be sound. | |
1690 | // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d` | |
1691 | ||
48663c56 | 1692 | self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state); |
ff7c6d11 | 1693 | |
5869c6ff XL |
1694 | if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) = |
1695 | place_span.0.last_projection() | |
dfeec247 | 1696 | { |
5869c6ff | 1697 | let place_ty = place_base.ty(self.body(), self.infcx.tcx); |
1b1a35ee | 1698 | if let ty::Array(..) = place_ty.ty.kind() { |
60c5eb7d XL |
1699 | self.check_if_subslice_element_is_moved( |
1700 | location, | |
1701 | desired_action, | |
5869c6ff | 1702 | (place_base, place_span.1), |
60c5eb7d | 1703 | maybe_uninits, |
5869c6ff XL |
1704 | from, |
1705 | to, | |
60c5eb7d XL |
1706 | ); |
1707 | return; | |
1708 | } | |
1709 | } | |
1710 | ||
ff7c6d11 XL |
1711 | // A move of any shallow suffix of `place` also interferes |
1712 | // with an attempt to use `place`. This is scenario 3 above. | |
1713 | // | |
1714 | // (Distinct from handling of scenarios 1+2+4 above because | |
1715 | // `place` does not interfere with suffixes of its prefixes, | |
0731742a | 1716 | // e.g., `a.b.c` does not interfere with `a.b.d`) |
83c7162d XL |
1717 | // |
1718 | // This code covers scenario 1. | |
ff7c6d11 | 1719 | |
b7449926 XL |
1720 | debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0); |
1721 | if let Some(mpi) = self.move_path_for_place(place_span.0) { | |
74b04a01 XL |
1722 | let uninit_mpi = self |
1723 | .move_data | |
1724 | .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi)); | |
1725 | ||
1726 | if let Some(uninit_mpi) = uninit_mpi { | |
ff7c6d11 | 1727 | self.report_use_of_moved_or_uninitialized( |
48663c56 | 1728 | location, |
ff7c6d11 | 1729 | desired_action, |
0bf4aa26 | 1730 | (place_span.0, place_span.0, place_span.1), |
74b04a01 | 1731 | uninit_mpi, |
ff7c6d11 XL |
1732 | ); |
1733 | return; // don't bother finding other problems. | |
1734 | } | |
1735 | } | |
1736 | } | |
1737 | ||
1738 | /// Currently MoveData does not store entries for all places in | |
1739 | /// the input MIR. For example it will currently filter out | |
1740 | /// places that are Copy; thus we do not track places of shared | |
1741 | /// reference type. This routine will walk up a place along its | |
1742 | /// prefixes, searching for a foundational place that *is* | |
1743 | /// tracked in the MoveData. | |
1744 | /// | |
1745 | /// An Err result includes a tag indicated why the search failed. | |
0531ce1d | 1746 | /// Currently this can only occur if the place is built off of a |
ff7c6d11 | 1747 | /// static variable, as we do not track those in the MoveData. |
74b04a01 | 1748 | fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) { |
60c5eb7d | 1749 | match self.move_data.rev_lookup.find(place) { |
dfeec247 XL |
1750 | LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => { |
1751 | (self.move_data.move_paths[mpi].place.as_ref(), mpi) | |
1752 | } | |
1753 | LookupResult::Parent(None) => panic!("should have move path for every Local"), | |
ff7c6d11 XL |
1754 | } |
1755 | } | |
1756 | ||
74b04a01 | 1757 | fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option<MovePathIndex> { |
ff7c6d11 XL |
1758 | // If returns None, then there is no move path corresponding |
1759 | // to a direct owner of `place` (which means there is nothing | |
1760 | // that borrowck tracks for its analysis). | |
1761 | ||
1762 | match self.move_data.rev_lookup.find(place) { | |
1763 | LookupResult::Parent(_) => None, | |
1764 | LookupResult::Exact(mpi) => Some(mpi), | |
1765 | } | |
1766 | } | |
1767 | ||
1768 | fn check_if_assigned_path_is_moved( | |
1769 | &mut self, | |
48663c56 | 1770 | location: Location, |
ba9703b0 | 1771 | (place, span): (Place<'tcx>, Span), |
dc9dc135 | 1772 | flow_state: &Flows<'cx, 'tcx>, |
ff7c6d11 | 1773 | ) { |
83c7162d | 1774 | debug!("check_if_assigned_path_is_moved place: {:?}", place); |
416331ca XL |
1775 | |
1776 | // None case => assigning to `x` does not require `x` be initialized. | |
5869c6ff | 1777 | for (place_base, elem) in place.iter_projections().rev() { |
e1599b0c | 1778 | match elem { |
416331ca | 1779 | ProjectionElem::Index(_/*operand*/) | |
2b03887a | 1780 | ProjectionElem::OpaqueCast(_) | |
416331ca XL |
1781 | ProjectionElem::ConstantIndex { .. } | |
1782 | // assigning to P[i] requires P to be valid. | |
1783 | ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => | |
1784 | // assigning to (P->variant) is okay if assigning to `P` is okay | |
1785 | // | |
94222f64 | 1786 | // FIXME: is this true even if P is an adt with a dtor? |
416331ca XL |
1787 | { } |
1788 | ||
1789 | // assigning to (*P) requires P to be initialized | |
1790 | ProjectionElem::Deref => { | |
1791 | self.check_if_full_path_is_moved( | |
1792 | location, InitializationRequiringAction::Use, | |
5869c6ff | 1793 | (place_base, span), flow_state); |
416331ca XL |
1794 | // (base initialized; no need to |
1795 | // recur further) | |
ff7c6d11 XL |
1796 | break; |
1797 | } | |
416331ca XL |
1798 | |
1799 | ProjectionElem::Subslice { .. } => { | |
1800 | panic!("we don't allow assignments to subslices, location: {:?}", | |
1801 | location); | |
1802 | } | |
1803 | ||
1804 | ProjectionElem::Field(..) => { | |
1805 | // if type of `P` has a dtor, then | |
1806 | // assigning to `P.f` requires `P` itself | |
1807 | // be already initialized | |
1808 | let tcx = self.infcx.tcx; | |
5869c6ff | 1809 | let base_ty = place_base.ty(self.body(), tcx).ty; |
1b1a35ee | 1810 | match base_ty.kind() { |
416331ca XL |
1811 | ty::Adt(def, _) if def.has_dtor(tcx) => { |
1812 | self.check_if_path_or_subpath_is_moved( | |
1813 | location, InitializationRequiringAction::Assignment, | |
5869c6ff | 1814 | (place_base, span), flow_state); |
416331ca | 1815 | |
83c7162d XL |
1816 | // (base initialized; no need to |
1817 | // recur further) | |
1818 | break; | |
1819 | } | |
1820 | ||
416331ca XL |
1821 | // Once `let s; s.x = V; read(s.x);`, |
1822 | // is allowed, remove this match arm. | |
1823 | ty::Adt(..) | ty::Tuple(..) => { | |
5869c6ff | 1824 | check_parent_of_field(self, location, place_base, span, flow_state); |
416331ca | 1825 | |
dfeec247 XL |
1826 | // rust-lang/rust#21232, #54499, #54986: during period where we reject |
1827 | // partial initialization, do not complain about unnecessary `mut` on | |
1828 | // an attempt to do a partial initialization. | |
1829 | self.used_mut.insert(place.local); | |
ff7c6d11 | 1830 | } |
ff7c6d11 | 1831 | |
416331ca XL |
1832 | _ => {} |
1833 | } | |
ff7c6d11 XL |
1834 | } |
1835 | } | |
1836 | } | |
ff7c6d11 | 1837 | |
dc9dc135 XL |
1838 | fn check_parent_of_field<'cx, 'tcx>( |
1839 | this: &mut MirBorrowckCtxt<'cx, 'tcx>, | |
48663c56 | 1840 | location: Location, |
74b04a01 | 1841 | base: PlaceRef<'tcx>, |
a1dfa0c6 | 1842 | span: Span, |
dc9dc135 | 1843 | flow_state: &Flows<'cx, 'tcx>, |
a1dfa0c6 | 1844 | ) { |
0bf4aa26 XL |
1845 | // rust-lang/rust#21232: Until Rust allows reads from the |
1846 | // initialized parts of partially initialized structs, we | |
1847 | // will, starting with the 2018 edition, reject attempts | |
1848 | // to write to structs that are not fully initialized. | |
1849 | // | |
1850 | // In other words, *until* we allow this: | |
1851 | // | |
1852 | // 1. `let mut s; s.x = Val; read(s.x);` | |
1853 | // | |
1854 | // we will for now disallow this: | |
1855 | // | |
1856 | // 2. `let mut s; s.x = Val;` | |
1857 | // | |
1858 | // and also this: | |
1859 | // | |
1860 | // 3. `let mut s = ...; drop(s); s.x=Val;` | |
1861 | // | |
1862 | // This does not use check_if_path_or_subpath_is_moved, | |
1863 | // because we want to *allow* reinitializations of fields: | |
0731742a | 1864 | // e.g., want to allow |
0bf4aa26 XL |
1865 | // |
1866 | // `let mut s = ...; drop(s.x); s.x=Val;` | |
1867 | // | |
1868 | // This does not use check_if_full_path_is_moved on | |
1869 | // `base`, because that would report an error about the | |
1870 | // `base` as a whole, but in this scenario we *really* | |
1871 | // want to report an error about the actual thing that was | |
1872 | // moved, which may be some prefix of `base`. | |
1873 | ||
1874 | // Shallow so that we'll stop at any dereference; we'll | |
1875 | // report errors about issues with such bases elsewhere. | |
1876 | let maybe_uninits = &flow_state.uninits; | |
1877 | ||
1878 | // Find the shortest uninitialized prefix you can reach | |
1879 | // without going over a Deref. | |
1880 | let mut shortest_uninit_seen = None; | |
1881 | for prefix in this.prefixes(base, PrefixSet::Shallow) { | |
5e7ed085 | 1882 | let Some(mpi) = this.move_path_for_place(prefix) else { continue }; |
0bf4aa26 XL |
1883 | |
1884 | if maybe_uninits.contains(mpi) { | |
dfeec247 XL |
1885 | debug!( |
1886 | "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}", | |
1887 | shortest_uninit_seen, | |
1888 | Some((prefix, mpi)) | |
1889 | ); | |
0bf4aa26 XL |
1890 | shortest_uninit_seen = Some((prefix, mpi)); |
1891 | } else { | |
1892 | debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi)); | |
1893 | } | |
1894 | } | |
1895 | ||
1896 | if let Some((prefix, mpi)) = shortest_uninit_seen { | |
94222f64 XL |
1897 | // Check for a reassignment into an uninitialized field of a union (for example, |
1898 | // after a move out). In this case, do not report an error here. There is an | |
a1dfa0c6 XL |
1899 | // exception, if this is the first assignment into the union (that is, there is |
1900 | // no move out from an earlier location) then this is an attempt at initialization | |
1901 | // of the union - we should error in that case. | |
1902 | let tcx = this.infcx.tcx; | |
17df50a5 XL |
1903 | if base.ty(this.body(), tcx).ty.is_union() { |
1904 | if this.move_data.path_map[mpi].iter().any(|moi| { | |
1905 | this.move_data.moves[*moi].source.is_predecessor_of(location, this.body) | |
1906 | }) { | |
1907 | return; | |
a1dfa0c6 XL |
1908 | } |
1909 | } | |
1910 | ||
0bf4aa26 | 1911 | this.report_use_of_moved_or_uninitialized( |
48663c56 | 1912 | location, |
0bf4aa26 XL |
1913 | InitializationRequiringAction::PartialAssignment, |
1914 | (prefix, base, span), | |
1915 | mpi, | |
1916 | ); | |
1917 | } | |
1918 | } | |
1919 | } | |
8faf50e0 | 1920 | |
9fa01778 | 1921 | /// Checks the permissions for the given place and read or write kind |
ff7c6d11 | 1922 | /// |
9fa01778 | 1923 | /// Returns `true` if an error is reported. |
ff7c6d11 | 1924 | fn check_access_permissions( |
83c7162d | 1925 | &mut self, |
ba9703b0 | 1926 | (place, span): (Place<'tcx>, Span), |
ff7c6d11 XL |
1927 | kind: ReadOrWrite, |
1928 | is_local_mutation_allowed: LocalMutationIsAllowed, | |
dc9dc135 | 1929 | flow_state: &Flows<'cx, 'tcx>, |
8faf50e0 | 1930 | location: Location, |
ff7c6d11 XL |
1931 | ) -> bool { |
1932 | debug!( | |
0bf4aa26 | 1933 | "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})", |
0531ce1d | 1934 | place, kind, is_local_mutation_allowed |
ff7c6d11 | 1935 | ); |
94b46f34 | 1936 | |
94b46f34 XL |
1937 | let error_access; |
1938 | let the_place_err; | |
1939 | ||
ff7c6d11 | 1940 | match kind { |
ba9703b0 XL |
1941 | Reservation(WriteKind::MutableBorrow( |
1942 | borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), | |
1943 | )) | |
1944 | | Write(WriteKind::MutableBorrow( | |
1945 | borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), | |
1946 | )) => { | |
94b46f34 XL |
1947 | let is_local_mutation_allowed = match borrow_kind { |
1948 | BorrowKind::Unique => LocalMutationIsAllowed::Yes, | |
1949 | BorrowKind::Mut { .. } => is_local_mutation_allowed, | |
0bf4aa26 | 1950 | BorrowKind::Shared | BorrowKind::Shallow => unreachable!(), |
94b46f34 | 1951 | }; |
416331ca | 1952 | match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { |
94b46f34 XL |
1953 | Ok(root_place) => { |
1954 | self.add_used_mut(root_place, flow_state); | |
1955 | return false; | |
1956 | } | |
83c7162d | 1957 | Err(place_err) => { |
94b46f34 XL |
1958 | error_access = AccessKind::MutableBorrow; |
1959 | the_place_err = place_err; | |
ff7c6d11 XL |
1960 | } |
1961 | } | |
83c7162d | 1962 | } |
ff7c6d11 | 1963 | Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => { |
416331ca | 1964 | match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { |
94b46f34 XL |
1965 | Ok(root_place) => { |
1966 | self.add_used_mut(root_place, flow_state); | |
1967 | return false; | |
1968 | } | |
83c7162d | 1969 | Err(place_err) => { |
94b46f34 XL |
1970 | error_access = AccessKind::Mutate; |
1971 | the_place_err = place_err; | |
ff7c6d11 | 1972 | } |
ff7c6d11 XL |
1973 | } |
1974 | } | |
94b46f34 | 1975 | |
ba9703b0 XL |
1976 | Reservation( |
1977 | WriteKind::Move | |
1978 | | WriteKind::StorageDeadOrDrop | |
1979 | | WriteKind::MutableBorrow(BorrowKind::Shared) | |
1980 | | WriteKind::MutableBorrow(BorrowKind::Shallow), | |
1981 | ) | |
1982 | | Write( | |
1983 | WriteKind::Move | |
1984 | | WriteKind::StorageDeadOrDrop | |
1985 | | WriteKind::MutableBorrow(BorrowKind::Shared) | |
1986 | | WriteKind::MutableBorrow(BorrowKind::Shallow), | |
1987 | ) => { | |
5099ac24 FG |
1988 | if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err() |
1989 | && !self.has_buffered_errors() | |
1990 | { | |
e74abb32 XL |
1991 | // rust-lang/rust#46908: In pure NLL mode this code path should be |
1992 | // unreachable, but we use `delay_span_bug` because we can hit this when | |
1993 | // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug` | |
1994 | // enabled. We don't want to ICE for that case, as other errors will have | |
1995 | // been emitted (#52262). | |
dfeec247 XL |
1996 | self.infcx.tcx.sess.delay_span_bug( |
1997 | span, | |
1998 | &format!( | |
1999 | "Accessing `{:?}` with the kind `{:?}` shouldn't be possible", | |
2000 | place, kind, | |
2001 | ), | |
2002 | ); | |
ff7c6d11 | 2003 | } |
94b46f34 XL |
2004 | return false; |
2005 | } | |
2006 | Activation(..) => { | |
2007 | // permission checks are done at Reservation point. | |
2008 | return false; | |
ff7c6d11 | 2009 | } |
ba9703b0 XL |
2010 | Read( |
2011 | ReadKind::Borrow( | |
2012 | BorrowKind::Unique | |
2013 | | BorrowKind::Mut { .. } | |
2014 | | BorrowKind::Shared | |
2015 | | BorrowKind::Shallow, | |
2016 | ) | |
2017 | | ReadKind::Copy, | |
2018 | ) => { | |
94b46f34 XL |
2019 | // Access authorized |
2020 | return false; | |
2021 | } | |
ff7c6d11 XL |
2022 | } |
2023 | ||
60c5eb7d XL |
2024 | // rust-lang/rust#21232, #54986: during period where we reject |
2025 | // partial initialization, do not complain about mutability | |
2026 | // errors except for actual mutation (as opposed to an attempt | |
2027 | // to do a partial initialization). | |
dfeec247 XL |
2028 | let previously_initialized = |
2029 | self.is_local_ever_initialized(place.local, flow_state).is_some(); | |
60c5eb7d | 2030 | |
94b46f34 | 2031 | // at this point, we have set up the error reporting state. |
60c5eb7d | 2032 | if previously_initialized { |
dfeec247 | 2033 | self.report_mutability_error(place, span, the_place_err, error_access, location); |
0bf4aa26 XL |
2034 | true |
2035 | } else { | |
2036 | false | |
60c5eb7d | 2037 | } |
0bf4aa26 XL |
2038 | } |
2039 | ||
dc9dc135 XL |
2040 | fn is_local_ever_initialized( |
2041 | &self, | |
2042 | local: Local, | |
2043 | flow_state: &Flows<'cx, 'tcx>, | |
2044 | ) -> Option<InitIndex> { | |
0bf4aa26 XL |
2045 | let mpi = self.move_data.rev_lookup.find_local(local); |
2046 | let ii = &self.move_data.init_path_map[mpi]; | |
2047 | for &index in ii { | |
2048 | if flow_state.ever_inits.contains(index) { | |
2049 | return Some(index); | |
2050 | } | |
2051 | } | |
2052 | None | |
ff7c6d11 XL |
2053 | } |
2054 | ||
83c7162d | 2055 | /// Adds the place into the used mutable variables set |
74b04a01 | 2056 | fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) { |
83c7162d | 2057 | match root_place { |
dfeec247 | 2058 | RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => { |
0bf4aa26 XL |
2059 | // If the local may have been initialized, and it is now currently being |
2060 | // mutated, then it is justified to be annotated with the `mut` | |
2061 | // keyword, since the mutation may be a possible reassignment. | |
dfeec247 | 2062 | if is_local_mutation_allowed != LocalMutationIsAllowed::Yes |
74b04a01 | 2063 | && self.is_local_ever_initialized(local, flow_state).is_some() |
0bf4aa26 | 2064 | { |
74b04a01 | 2065 | self.used_mut.insert(local); |
83c7162d XL |
2066 | } |
2067 | } | |
8faf50e0 | 2068 | RootPlace { |
dfeec247 | 2069 | place_local: _, |
416331ca | 2070 | place_projection: _, |
8faf50e0 XL |
2071 | is_local_mutation_allowed: LocalMutationIsAllowed::Yes, |
2072 | } => {} | |
83c7162d | 2073 | RootPlace { |
dfeec247 | 2074 | place_local, |
e1599b0c | 2075 | place_projection: place_projection @ [.., _], |
83c7162d XL |
2076 | is_local_mutation_allowed: _, |
2077 | } => { | |
416331ca | 2078 | if let Some(field) = self.is_upvar_field_projection(PlaceRef { |
dfeec247 XL |
2079 | local: place_local, |
2080 | projection: place_projection, | |
416331ca | 2081 | }) { |
83c7162d XL |
2082 | self.used_mut_upvars.push(field); |
2083 | } | |
2084 | } | |
83c7162d XL |
2085 | } |
2086 | } | |
2087 | ||
0bf4aa26 | 2088 | /// Whether this value can be written or borrowed mutably. |
83c7162d | 2089 | /// Returns the root place if the place passed in is a projection. |
74b04a01 | 2090 | fn is_mutable( |
ff7c6d11 | 2091 | &self, |
74b04a01 | 2092 | place: PlaceRef<'tcx>, |
ff7c6d11 | 2093 | is_local_mutation_allowed: LocalMutationIsAllowed, |
74b04a01 | 2094 | ) -> Result<RootPlace<'tcx>, PlaceRef<'tcx>> { |
5869c6ff XL |
2095 | debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed); |
2096 | match place.last_projection() { | |
2097 | None => { | |
2098 | let local = &self.body.local_decls[place.local]; | |
ff7c6d11 XL |
2099 | match local.mutability { |
2100 | Mutability::Not => match is_local_mutation_allowed { | |
8faf50e0 | 2101 | LocalMutationIsAllowed::Yes => Ok(RootPlace { |
dfeec247 | 2102 | place_local: place.local, |
416331ca | 2103 | place_projection: place.projection, |
8faf50e0 XL |
2104 | is_local_mutation_allowed: LocalMutationIsAllowed::Yes, |
2105 | }), | |
2106 | LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace { | |
dfeec247 | 2107 | place_local: place.local, |
416331ca | 2108 | place_projection: place.projection, |
8faf50e0 XL |
2109 | is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars, |
2110 | }), | |
ff7c6d11 XL |
2111 | LocalMutationIsAllowed::No => Err(place), |
2112 | }, | |
8faf50e0 | 2113 | Mutability::Mut => Ok(RootPlace { |
dfeec247 | 2114 | place_local: place.local, |
416331ca | 2115 | place_projection: place.projection, |
8faf50e0 XL |
2116 | is_local_mutation_allowed, |
2117 | }), | |
ff7c6d11 XL |
2118 | } |
2119 | } | |
5869c6ff | 2120 | Some((place_base, elem)) => { |
e1599b0c | 2121 | match elem { |
ff7c6d11 | 2122 | ProjectionElem::Deref => { |
5869c6ff | 2123 | let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty; |
ff7c6d11 XL |
2124 | |
2125 | // Check the kind of deref to decide | |
1b1a35ee | 2126 | match base_ty.kind() { |
b7449926 | 2127 | ty::Ref(_, _, mutbl) => { |
94b46f34 | 2128 | match mutbl { |
ff7c6d11 | 2129 | // Shared borrowed data is never mutable |
dfeec247 | 2130 | hir::Mutability::Not => Err(place), |
ff7c6d11 XL |
2131 | // Mutably borrowed data is mutable, but only if we have a |
2132 | // unique path to the `&mut` | |
dfeec247 | 2133 | hir::Mutability::Mut => { |
48663c56 | 2134 | let mode = match self.is_upvar_field_projection(place) { |
dfeec247 | 2135 | Some(field) if self.upvars[field.index()].by_ref => { |
ff7c6d11 XL |
2136 | is_local_mutation_allowed |
2137 | } | |
2138 | _ => LocalMutationIsAllowed::Yes, | |
2139 | }; | |
2140 | ||
5869c6ff | 2141 | self.is_mutable(place_base, mode) |
ff7c6d11 XL |
2142 | } |
2143 | } | |
2144 | } | |
b7449926 | 2145 | ty::RawPtr(tnm) => { |
ff7c6d11 XL |
2146 | match tnm.mutbl { |
2147 | // `*const` raw pointers are not mutable | |
dfeec247 | 2148 | hir::Mutability::Not => Err(place), |
83c7162d XL |
2149 | // `*mut` raw pointers are always mutable, regardless of |
2150 | // context. The users have to check by themselves. | |
dfeec247 XL |
2151 | hir::Mutability::Mut => Ok(RootPlace { |
2152 | place_local: place.local, | |
2153 | place_projection: place.projection, | |
2154 | is_local_mutation_allowed, | |
2155 | }), | |
ff7c6d11 XL |
2156 | } |
2157 | } | |
2158 | // `Box<T>` owns its content, so mutable if its location is mutable | |
5869c6ff XL |
2159 | _ if base_ty.is_box() => { |
2160 | self.is_mutable(place_base, is_local_mutation_allowed) | |
2161 | } | |
ff7c6d11 XL |
2162 | // Deref should only be for reference, pointers or boxes |
2163 | _ => bug!("Deref of unexpected type: {:?}", base_ty), | |
2164 | } | |
2165 | } | |
2166 | // All other projections are owned by their base path, so mutable if | |
2167 | // base path is mutable | |
2168 | ProjectionElem::Field(..) | |
2169 | | ProjectionElem::Index(..) | |
2170 | | ProjectionElem::ConstantIndex { .. } | |
2171 | | ProjectionElem::Subslice { .. } | |
2b03887a | 2172 | | ProjectionElem::OpaqueCast { .. } |
ff7c6d11 | 2173 | | ProjectionElem::Downcast(..) => { |
48663c56 | 2174 | let upvar_field_projection = self.is_upvar_field_projection(place); |
8faf50e0 | 2175 | if let Some(field) = upvar_field_projection { |
48663c56 | 2176 | let upvar = &self.upvars[field.index()]; |
ff7c6d11 | 2177 | debug!( |
5869c6ff XL |
2178 | "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \ |
2179 | place={:?}, place_base={:?}", | |
2180 | upvar, is_local_mutation_allowed, place, place_base | |
ff7c6d11 | 2181 | ); |
5869c6ff | 2182 | match (upvar.place.mutability, is_local_mutation_allowed) { |
ba9703b0 XL |
2183 | ( |
2184 | Mutability::Not, | |
2185 | LocalMutationIsAllowed::No | |
2186 | | LocalMutationIsAllowed::ExceptUpvars, | |
2187 | ) => Err(place), | |
ff7c6d11 XL |
2188 | (Mutability::Not, LocalMutationIsAllowed::Yes) |
2189 | | (Mutability::Mut, _) => { | |
83c7162d XL |
2190 | // Subtle: this is an upvar |
2191 | // reference, so it looks like | |
2192 | // `self.foo` -- we want to double | |
48663c56 | 2193 | // check that the location `*self` |
83c7162d XL |
2194 | // is mutable (i.e., this is not a |
2195 | // `Fn` closure). But if that | |
2196 | // check succeeds, we want to | |
2197 | // *blame* the mutability on | |
2198 | // `place` (that is, | |
2199 | // `self.foo`). This is used to | |
2200 | // propagate the info about | |
2201 | // whether mutability declarations | |
2202 | // are used outwards, so that we register | |
2203 | // the outer variable as mutable. Otherwise a | |
2204 | // test like this fails to record the `mut` | |
2205 | // as needed: | |
2206 | // | |
2207 | // ``` | |
2208 | // fn foo<F: FnOnce()>(_f: F) { } | |
2209 | // fn main() { | |
2210 | // let var = Vec::new(); | |
2211 | // foo(move || { | |
2212 | // var.push(1); | |
2213 | // }); | |
2214 | // } | |
2215 | // ``` | |
5869c6ff XL |
2216 | let _ = |
2217 | self.is_mutable(place_base, is_local_mutation_allowed)?; | |
8faf50e0 | 2218 | Ok(RootPlace { |
dfeec247 | 2219 | place_local: place.local, |
416331ca | 2220 | place_projection: place.projection, |
8faf50e0 XL |
2221 | is_local_mutation_allowed, |
2222 | }) | |
ff7c6d11 XL |
2223 | } |
2224 | } | |
2225 | } else { | |
5869c6ff | 2226 | self.is_mutable(place_base, is_local_mutation_allowed) |
ff7c6d11 XL |
2227 | } |
2228 | } | |
2229 | } | |
2230 | } | |
2231 | } | |
2232 | } | |
48663c56 XL |
2233 | |
2234 | /// If `place` is a field projection, and the field is being projected from a closure type, | |
2235 | /// then returns the index of the field being projected. Note that this closure will always | |
2236 | /// be `self` in the current MIR, because that is the only time we directly access the fields | |
2237 | /// of a closure type. | |
c295e0f8 | 2238 | fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> { |
f035d41b | 2239 | path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body()) |
48663c56 | 2240 | } |
ff7c6d11 XL |
2241 | } |
2242 | ||
5099ac24 | 2243 | mod error { |
5e7ed085 FG |
2244 | use rustc_errors::ErrorGuaranteed; |
2245 | ||
5099ac24 FG |
2246 | use super::*; |
2247 | ||
2248 | pub struct BorrowckErrors<'tcx> { | |
2249 | /// This field keeps track of move errors that are to be reported for given move indices. | |
2250 | /// | |
2251 | /// There are situations where many errors can be reported for a single move out (see #53807) | |
2252 | /// and we want only the best of those errors. | |
2253 | /// | |
2254 | /// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the | |
2255 | /// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of the | |
2256 | /// `Place` of the previous most diagnostic. This happens instead of buffering the error. Once | |
2257 | /// all move errors have been reported, any diagnostics in this map are added to the buffer | |
2258 | /// to be emitted. | |
2259 | /// | |
2260 | /// `BTreeMap` is used to preserve the order of insertions when iterating. This is necessary | |
2261 | /// when errors in the map are being re-added to the error buffer so that errors with the | |
2262 | /// same primary span come out in a consistent order. | |
2263 | buffered_move_errors: | |
5e7ed085 FG |
2264 | BTreeMap<Vec<MoveOutIndex>, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>)>, |
2265 | /// Diagnostics to be reported buffer. | |
5099ac24 FG |
2266 | buffered: Vec<Diagnostic>, |
2267 | /// Set to Some if we emit an error during borrowck | |
5e7ed085 | 2268 | tainted_by_errors: Option<ErrorGuaranteed>, |
5099ac24 FG |
2269 | } |
2270 | ||
2271 | impl BorrowckErrors<'_> { | |
2272 | pub fn new() -> Self { | |
2273 | BorrowckErrors { | |
2274 | buffered_move_errors: BTreeMap::new(), | |
2275 | buffered: Default::default(), | |
2276 | tainted_by_errors: None, | |
2277 | } | |
2278 | } | |
2279 | ||
5e7ed085 FG |
2280 | // FIXME(eddyb) this is a suboptimal API because `tainted_by_errors` is |
2281 | // set before any emission actually happens (weakening the guarantee). | |
2282 | pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) { | |
2283 | self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()); | |
5099ac24 FG |
2284 | t.buffer(&mut self.buffered); |
2285 | } | |
2286 | ||
5e7ed085 | 2287 | pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) { |
5099ac24 FG |
2288 | t.buffer(&mut self.buffered); |
2289 | } | |
2290 | ||
2291 | pub fn set_tainted_by_errors(&mut self) { | |
5e7ed085 | 2292 | self.tainted_by_errors = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted()); |
5099ac24 FG |
2293 | } |
2294 | } | |
2295 | ||
2296 | impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { | |
5e7ed085 | 2297 | pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_, ErrorGuaranteed>) { |
5099ac24 FG |
2298 | self.errors.buffer_error(t); |
2299 | } | |
2300 | ||
5e7ed085 | 2301 | pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) { |
5099ac24 FG |
2302 | self.errors.buffer_non_error_diag(t); |
2303 | } | |
2304 | ||
2305 | pub fn buffer_move_error( | |
2306 | &mut self, | |
2307 | move_out_indices: Vec<MoveOutIndex>, | |
5e7ed085 | 2308 | place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx, ErrorGuaranteed>), |
5099ac24 | 2309 | ) -> bool { |
5e7ed085 | 2310 | if let Some((_, diag)) = |
5099ac24 FG |
2311 | self.errors.buffered_move_errors.insert(move_out_indices, place_and_err) |
2312 | { | |
2313 | // Cancel the old diagnostic so we don't ICE | |
2314 | diag.cancel(); | |
2315 | false | |
2316 | } else { | |
2317 | true | |
2318 | } | |
2319 | } | |
2320 | ||
5e7ed085 | 2321 | pub fn emit_errors(&mut self) -> Option<ErrorGuaranteed> { |
5099ac24 FG |
2322 | // Buffer any move errors that we collected and de-duplicated. |
2323 | for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) { | |
2324 | // We have already set tainted for this error, so just buffer it. | |
2325 | diag.buffer(&mut self.errors.buffered); | |
2326 | } | |
2327 | ||
2328 | if !self.errors.buffered.is_empty() { | |
2329 | self.errors.buffered.sort_by_key(|diag| diag.sort_span); | |
2330 | ||
5e7ed085 FG |
2331 | for mut diag in self.errors.buffered.drain(..) { |
2332 | self.infcx.tcx.sess.diagnostic().emit_diagnostic(&mut diag); | |
5099ac24 FG |
2333 | } |
2334 | } | |
2335 | ||
2336 | self.errors.tainted_by_errors | |
2337 | } | |
2338 | ||
2339 | pub fn has_buffered_errors(&self) -> bool { | |
2340 | self.errors.buffered.is_empty() | |
2341 | } | |
2342 | ||
2343 | pub fn has_move_error( | |
2344 | &self, | |
2345 | move_out_indices: &[MoveOutIndex], | |
5e7ed085 | 2346 | ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx, ErrorGuaranteed>)> { |
5099ac24 FG |
2347 | self.errors.buffered_move_errors.get(move_out_indices) |
2348 | } | |
2349 | } | |
2350 | } | |
2351 | ||
ff7c6d11 XL |
2352 | /// The degree of overlap between 2 places for borrow-checking. |
2353 | enum Overlap { | |
2354 | /// The places might partially overlap - in this case, we give | |
2355 | /// up and say that they might conflict. This occurs when | |
2356 | /// different fields of a union are borrowed. For example, | |
2357 | /// if `u` is a union, we have no way of telling how disjoint | |
2358 | /// `u.a.x` and `a.b.y` are. | |
2359 | Arbitrary, | |
2360 | /// The places have the same type, and are either completely disjoint | |
0731742a | 2361 | /// or equal - i.e., they can't "partially" overlap as can occur with |
ff7c6d11 XL |
2362 | /// unions. This is the "base case" on which we recur for extensions |
2363 | /// of the place. | |
2364 | EqualOrDisjoint, | |
2365 | /// The places are disjoint, so we know all extensions of them | |
2366 | /// will also be disjoint. | |
2367 | Disjoint, | |
2368 | } |