1 use rustc::ty::{self, TyCtxt};
3 use rustc::util::nodemap::FxHashMap;
4 use rustc_data_structures::indexed_vec::{IndexVec};
5 use smallvec::SmallVec;
6 use syntax_pos::{Span};
9 use std::ops::{Index, IndexMut};
11 use self::abs_domain::{AbstractElem, Lift};
15 // This submodule holds some newtype'd Index wrappers that are using
16 // NonZero to ensure that Option<Index> occupies only a single word.
17 // They are in a submodule to impose privacy restrictions; namely, to
18 // ensure that other code does not accidentally access `index.0`
19 // (which is likely to yield a subtle off-by-one error).
20 pub(crate) mod indexes {
22 use std::num::NonZeroUsize;
23 use rustc_data_structures::indexed_vec::Idx;
25 macro_rules! new_index {
26 ($(#[$attrs:meta])* $Index:ident, $debug_name:expr) => {
27 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
28 pub struct $Index(NonZeroUsize);
31 fn new(idx: usize) -> Self {
32 $Index(NonZeroUsize::new(idx + 1).unwrap())
34 fn index(self) -> usize {
39 impl fmt::Debug for $Index {
40 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(fmt, "{}{}", $debug_name, self.index())
48 /// Index into MovePathData.move_paths
54 /// Index into MoveData.moves.
60 /// Index into MoveData.inits.
66 /// Index into Borrows.locations
72 pub use self::indexes::MovePathIndex;
73 pub use self::indexes::MoveOutIndex;
74 pub use self::indexes::InitIndex;
77 pub fn move_path_index(&self, move_data: &MoveData<'_>) -> MovePathIndex {
78 move_data.moves[*self].path
82 /// `MovePath` is a canonicalized representation of a path that is
83 /// moved or assigned to.
85 /// It follows a tree structure.
87 /// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
88 /// move *out* of the place `x.m`.
90 /// The MovePaths representing `x.m` and `x.n` are siblings (that is,
91 /// one of them will link to the other via the `next_sibling` field,
92 /// and the other will have no entry in its `next_sibling` field), and
93 /// they both have the MovePath representing `x` as their parent.
95 pub struct MovePath<'tcx> {
96 pub next_sibling: Option<MovePathIndex>,
97 pub first_child: Option<MovePathIndex>,
98 pub parent: Option<MovePathIndex>,
99 pub place: Place<'tcx>,
102 impl<'tcx> MovePath<'tcx> {
105 move_paths: &IndexVec<MovePathIndex, MovePath<'_>>,
106 ) -> Vec<MovePathIndex> {
107 let mut parents = Vec::new();
109 let mut curr_parent = self.parent;
110 while let Some(parent_mpi) = curr_parent {
111 parents.push(parent_mpi);
112 curr_parent = move_paths[parent_mpi].parent;
119 impl<'tcx> fmt::Debug for MovePath<'tcx> {
120 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(w, "MovePath {{")?;
122 if let Some(parent) = self.parent {
123 write!(w, " parent: {:?},", parent)?;
125 if let Some(first_child) = self.first_child {
126 write!(w, " first_child: {:?},", first_child)?;
128 if let Some(next_sibling) = self.next_sibling {
129 write!(w, " next_sibling: {:?}", next_sibling)?;
131 write!(w, " place: {:?} }}", self.place)
135 impl<'tcx> fmt::Display for MovePath<'tcx> {
136 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
137 write!(w, "{:?}", self.place)
142 pub struct MoveData<'tcx> {
143 pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
144 pub moves: IndexVec<MoveOutIndex, MoveOut>,
145 /// Each Location `l` is mapped to the MoveOut's that are effects
146 /// of executing the code at `l`. (There can be multiple MoveOut's
147 /// for a given `l` because each MoveOut is associated with one
148 /// particular path being moved.)
149 pub loc_map: LocationMap<SmallVec<[MoveOutIndex; 4]>>,
150 pub path_map: IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
151 pub rev_lookup: MovePathLookup<'tcx>,
152 pub inits: IndexVec<InitIndex, Init>,
153 /// Each Location `l` is mapped to the Inits that are effects
154 /// of executing the code at `l`.
155 pub init_loc_map: LocationMap<SmallVec<[InitIndex; 4]>>,
156 pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
159 pub trait HasMoveData<'tcx> {
160 fn move_data(&self) -> &MoveData<'tcx>;
164 pub struct LocationMap<T> {
165 /// Location-indexed (BasicBlock for outer index, index within BB
166 /// for inner index) map.
167 pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
170 impl<T> Index<Location> for LocationMap<T> {
172 fn index(&self, index: Location) -> &Self::Output {
173 &self.map[index.block][index.statement_index]
177 impl<T> IndexMut<Location> for LocationMap<T> {
178 fn index_mut(&mut self, index: Location) -> &mut Self::Output {
179 &mut self.map[index.block][index.statement_index]
183 impl<T> LocationMap<T> where T: Default + Clone {
184 fn new(mir: &Mir<'_>) -> Self {
186 map: mir.basic_blocks().iter().map(|block| {
187 vec![T::default(); block.statements.len()+1]
193 /// `MoveOut` represents a point in a program that moves out of some
194 /// L-value; i.e., "creates" uninitialized memory.
196 /// With respect to dataflow analysis:
197 /// - Generated by moves and declaration of uninitialized variables.
198 /// - Killed by assignments to the memory.
199 #[derive(Copy, Clone)]
202 pub path: MovePathIndex,
204 pub source: Location,
207 impl fmt::Debug for MoveOut {
208 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
209 write!(fmt, "{:?}@{:?}", self.path, self.source)
213 /// `Init` represents a point in a program that initializes some L-value;
214 #[derive(Copy, Clone)]
216 /// path being initialized
217 pub path: MovePathIndex,
218 /// location of initialization
219 pub location: InitLocation,
220 /// Extra information about this initialization
225 /// Initializations can be from an argument or from a statement. Arguments
226 /// do not have locations, in those cases the `Local` is kept..
227 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
228 pub enum InitLocation {
233 /// Additional information about the initialization.
234 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
236 /// Deep init, even on panic
238 /// Only does a shallow init
240 /// This doesn't initialize the variable on panic (and a panic is possible).
244 impl fmt::Debug for Init {
245 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
246 write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
251 crate fn span<'gcx>(&self, mir: &Mir<'gcx>) -> Span {
252 match self.location {
253 InitLocation::Argument(local) => mir.local_decls[local].source_info.span,
254 InitLocation::Statement(location) => mir.source_info(location).span,
259 /// Tables mapping from a place to its MovePathIndex.
261 pub struct MovePathLookup<'tcx> {
262 locals: IndexVec<Local, MovePathIndex>,
264 /// projections are made from a base-place and a projection
265 /// elem. The base-place will have a unique MovePathIndex; we use
266 /// the latter as the index into the outer vector (narrowing
267 /// subsequent search so that it is solely relative to that
268 /// base-place). For the remaining lookup, we map the projection
269 /// elem to the associated MovePathIndex.
270 projections: FxHashMap<(MovePathIndex, AbstractElem<'tcx>), MovePathIndex>
275 #[derive(Copy, Clone, Debug)]
276 pub enum LookupResult {
277 Exact(MovePathIndex),
278 Parent(Option<MovePathIndex>)
281 impl<'tcx> MovePathLookup<'tcx> {
282 // Unlike the builder `fn move_path_for` below, this lookup
283 // alternative will *not* create a MovePath on the fly for an
284 // unknown place, but will rather return the nearest available
286 pub fn find(&self, place: &Place<'tcx>) -> LookupResult {
288 Place::Base(PlaceBase::Local(local)) => LookupResult::Exact(self.locals[local]),
289 Place::Base(PlaceBase::Static(..)) => LookupResult::Parent(None),
290 Place::Projection(ref proj) => {
291 match self.find(&proj.base) {
292 LookupResult::Exact(base_path) => {
293 match self.projections.get(&(base_path, proj.elem.lift())) {
294 Some(&subpath) => LookupResult::Exact(subpath),
295 None => LookupResult::Parent(Some(base_path))
304 pub fn find_local(&self, local: Local) -> MovePathIndex {
310 pub struct IllegalMoveOrigin<'tcx> {
311 pub(crate) location: Location,
312 pub(crate) kind: IllegalMoveOriginKind<'tcx>,
316 pub(crate) enum IllegalMoveOriginKind<'tcx> {
317 /// Illegal move due to attempt to move from `static` variable.
320 /// Illegal move due to attempt to move from behind a reference.
322 /// The place the reference refers to: if erroneous code was trying to
323 /// move from `(*x).f` this will be `*x`.
324 target_place: Place<'tcx>,
327 /// Illegal move due to attempt to move from field of an ADT that
328 /// implements `Drop`. Rust maintains invariant that all `Drop`
329 /// ADT's remain fully-initialized so that user-defined destructor
330 /// can safely read from all of the ADT's fields.
331 InteriorOfTypeWithDestructor { container_ty: ty::Ty<'tcx> },
333 /// Illegal move due to attempt to move out of a slice or array.
334 InteriorOfSliceOrArray { ty: ty::Ty<'tcx>, is_index: bool, },
338 pub enum MoveError<'tcx> {
339 IllegalMove { cannot_move_out_of: IllegalMoveOrigin<'tcx> },
340 UnionMove { path: MovePathIndex },
343 impl<'tcx> MoveError<'tcx> {
344 fn cannot_move_out_of(location: Location, kind: IllegalMoveOriginKind<'tcx>) -> Self {
345 let origin = IllegalMoveOrigin { location, kind };
346 MoveError::IllegalMove { cannot_move_out_of: origin }
350 impl<'a, 'gcx, 'tcx> MoveData<'tcx> {
351 pub fn gather_moves(mir: &Mir<'tcx>, tcx: TyCtxt<'a, 'gcx, 'tcx>)
352 -> Result<Self, (Self, Vec<(Place<'tcx>, MoveError<'tcx>)>)> {
353 builder::gather_moves(mir, tcx)
356 /// For the move path `mpi`, returns the root local variable (if any) that starts the path.
357 /// (e.g., for a path like `a.b.c` returns `Some(a)`)
358 pub fn base_local(&self, mut mpi: MovePathIndex) -> Option<Local> {
360 let path = &self.move_paths[mpi];
361 if let Place::Base(PlaceBase::Local(l)) = path.place { return Some(l); }
362 if let Some(parent) = path.parent { mpi = parent; continue } else { return None }