1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Helper routines used for fragmenting structural paths due to moves for
12 //! tracking drop obligations. Please see the extensive comments in the
13 //! section "Structural fragments" in `doc.rs`.
15 use self::Fragment::*;
17 use borrowck::{LoanPath};
18 use borrowck::LoanPathKind::{LpVar, LpUpvar, LpDowncast, LpExtend};
19 use borrowck::LoanPathElem::{LpDeref, LpInterior};
20 use borrowck::move_data::{InvalidMovePathIndex};
21 use borrowck::move_data::{MoveData, MovePathIndex};
22 use rustc::middle::ty;
23 use rustc::middle::mem_categorization as mc;
24 use rustc::util::ppaux::{Repr, UserString};
29 use syntax::attr::AttrMetaMethods;
30 use syntax::codemap::Span;
32 #[derive(PartialEq, Eq, PartialOrd, Ord)]
34 // This represents the path described by the move path index
37 // This represents the collection of all but one of the elements
38 // from an array at the path described by the move path index.
39 // Note that attached MovePathIndex should have mem_categorization
40 // of InteriorElement (i.e. array dereference `&foo[]`).
41 AllButOneFrom(MovePathIndex),
45 fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) -> String {
46 let repr = |&: mpi| move_data.path_loan_path(mpi).repr(tcx);
48 Just(mpi) => repr(mpi),
49 AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
53 fn loan_path_user_string<'tcx>(&self,
54 move_data: &MoveData<'tcx>,
55 tcx: &ty::ctxt<'tcx>) -> String {
56 let user_string = |&: mpi| move_data.path_loan_path(mpi).user_string(tcx);
58 Just(mpi) => user_string(mpi),
59 AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
64 pub struct FragmentSets {
65 /// During move_data construction, `moved_leaf_paths` tracks paths
66 /// that have been used directly by being moved out of. When
67 /// move_data construction has been completed, `moved_leaf_paths`
68 /// tracks such paths that are *leaf fragments* (e.g. `a.j` if we
69 /// never move out any child like `a.j.x`); any parent paths
70 /// (e.g. `a` for the `a.j` example) are moved over to
71 /// `parents_of_fragments`.
72 moved_leaf_paths: Vec<MovePathIndex>,
74 /// `assigned_leaf_paths` tracks paths that have been used
75 /// directly by being overwritten, but is otherwise much like
76 /// `moved_leaf_paths`.
77 assigned_leaf_paths: Vec<MovePathIndex>,
79 /// `parents_of_fragments` tracks paths that are definitely
80 /// parents of paths that have been moved.
82 /// FIXME(pnkfelix) probably do not want/need
83 /// `parents_of_fragments` at all, if we can avoid it.
85 /// Update: I do not see a way to to avoid it. Maybe just remove
86 /// above fixme, or at least document why doing this may be hard.
87 parents_of_fragments: Vec<MovePathIndex>,
89 /// During move_data construction (specifically the
90 /// fixup_fragment_sets call), `unmoved_fragments` tracks paths
91 /// that have been "left behind" after a sibling has been moved or
92 /// assigned. When move_data construction has been completed,
93 /// `unmoved_fragments` tracks paths that were *only* results of
94 /// being left-behind, and never directly moved themselves.
95 unmoved_fragments: Vec<Fragment>,
99 pub fn new() -> FragmentSets {
101 unmoved_fragments: Vec::new(),
102 moved_leaf_paths: Vec::new(),
103 assigned_leaf_paths: Vec::new(),
104 parents_of_fragments: Vec::new(),
108 pub fn add_move(&mut self, path_index: MovePathIndex) {
109 self.moved_leaf_paths.push(path_index);
112 pub fn add_assignment(&mut self, path_index: MovePathIndex) {
113 self.assigned_leaf_paths.push(path_index);
117 pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
118 tcx: &ty::ctxt<'tcx>,
121 let (span_err, print) = {
122 let attrs : &[ast::Attribute];
123 attrs = match tcx.map.find(id) {
124 Some(ast_map::NodeItem(ref item)) =>
126 Some(ast_map::NodeImplItem(&ast::MethodImplItem(ref m))) =>
128 Some(ast_map::NodeTraitItem(&ast::ProvidedMethod(ref m))) =>
134 attrs.iter().any(|a| a.check_name("rustc_move_fragments"));
135 let print = tcx.sess.opts.debugging_opts.print_move_fragments;
140 if !span_err && !print { return; }
142 let instrument_all_paths = |&: kind, vec_rc: &Vec<MovePathIndex>| {
143 for (i, mpi) in vec_rc.iter().enumerate() {
144 let render = |&:| this.path_loan_path(*mpi).user_string(tcx);
146 tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
149 println!("id:{} {}[{}] `{}`", id, kind, i, render());
154 let instrument_all_fragments = |&: kind, vec_rc: &Vec<Fragment>| {
155 for (i, f) in vec_rc.iter().enumerate() {
156 let render = |&:| f.loan_path_user_string(this, tcx);
158 tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
161 println!("id:{} {}[{}] `{}`", id, kind, i, render());
166 let fragments = this.fragments.borrow();
167 instrument_all_paths("moved_leaf_path", &fragments.moved_leaf_paths);
168 instrument_all_fragments("unmoved_fragment", &fragments.unmoved_fragments);
169 instrument_all_paths("parent_of_fragments", &fragments.parents_of_fragments);
170 instrument_all_paths("assigned_leaf_path", &fragments.assigned_leaf_paths);
173 /// Normalizes the fragment sets in `this`; i.e., removes duplicate entries, constructs the set of
174 /// parents, and constructs the left-over fragments.
176 /// Note: "left-over fragments" means paths that were not directly referenced in moves nor
177 /// assignments, but must nonetheless be tracked as potential drop obligations.
178 pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) {
180 let mut fragments = this.fragments.borrow_mut();
182 // Swap out contents of fragments so that we can modify the fields
183 // without borrowing the common fragments.
184 let mut unmoved = mem::replace(&mut fragments.unmoved_fragments, vec![]);
185 let mut parents = mem::replace(&mut fragments.parents_of_fragments, vec![]);
186 let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
187 let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
189 let path_lps = |&: mpis: &[MovePathIndex]| -> Vec<String> {
190 mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
193 let frag_lps = |&: fs: &[Fragment]| -> Vec<String> {
194 fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
197 // First, filter out duplicates
200 debug!("fragments 1 moved: {:?}", path_lps(&moved[]));
204 debug!("fragments 1 assigned: {:?}", path_lps(&assigned[]));
206 // Second, build parents from the moved and assigned.
208 let mut p = this.path_parent(*m);
209 while p != InvalidMovePathIndex {
211 p = this.path_parent(p);
215 let mut p = this.path_parent(*a);
216 while p != InvalidMovePathIndex {
218 p = this.path_parent(p);
224 debug!("fragments 2 parents: {:?}", path_lps(&parents[]));
226 // Third, filter the moved and assigned fragments down to just the non-parents
227 moved.retain(|f| non_member(*f, &parents[]));
228 debug!("fragments 3 moved: {:?}", path_lps(&moved[]));
230 assigned.retain(|f| non_member(*f, &parents[]));
231 debug!("fragments 3 assigned: {:?}", path_lps(&assigned[]));
233 // Fourth, build the leftover from the moved, assigned, and parents.
235 let lp = this.path_loan_path(*m);
236 add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
239 let lp = this.path_loan_path(*a);
240 add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
243 let lp = this.path_loan_path(*p);
244 add_fragment_siblings(this, tcx, &mut unmoved, lp, None);
249 debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[]));
251 // Fifth, filter the leftover fragments down to its core.
252 unmoved.retain(|f| match *f {
253 AllButOneFrom(_) => true,
254 Just(mpi) => non_member(mpi, &parents[]) &&
255 non_member(mpi, &moved[]) &&
256 non_member(mpi, &assigned[])
258 debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[]));
260 // Swap contents back in.
261 fragments.unmoved_fragments = unmoved;
262 fragments.parents_of_fragments = parents;
263 fragments.moved_leaf_paths = moved;
264 fragments.assigned_leaf_paths = assigned;
268 fn non_member(elem: MovePathIndex, set: &[MovePathIndex]) -> bool {
269 match set.binary_search(&elem) {
276 /// Adds all of the precisely-tracked siblings of `lp` as potential move paths of interest. For
277 /// example, if `lp` represents `s.x.j`, then adds moves paths for `s.x.i` and `s.x.k`, the
278 /// siblings of `s.x.j`.
279 fn add_fragment_siblings<'tcx>(this: &MoveData<'tcx>,
280 tcx: &ty::ctxt<'tcx>,
281 gathered_fragments: &mut Vec<Fragment>,
282 lp: Rc<LoanPath<'tcx>>,
283 origin_id: Option<ast::NodeId>) {
285 LpVar(_) | LpUpvar(..) => {} // Local variables have no siblings.
287 // Consuming a downcast is like consuming the original value, so propage inward.
288 LpDowncast(ref loan_parent, _) => {
289 add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
292 // *LV for Unique consumes the contents of the box (at
293 // least when it is non-copy...), so propagate inward.
294 LpExtend(ref loan_parent, _, LpDeref(mc::Unique)) => {
295 add_fragment_siblings(this, tcx, gathered_fragments, loan_parent.clone(), origin_id);
298 // *LV for unsafe and borrowed pointers do not consume their loan path, so stop here.
299 LpExtend(_, _, LpDeref(mc::UnsafePtr(..))) |
300 LpExtend(_, _, LpDeref(mc::Implicit(..))) |
301 LpExtend(_, _, LpDeref(mc::BorrowedPtr(..))) => {}
303 // FIXME(pnkfelix): LV[j] should be tracked, at least in the
304 // sense of we will track the remaining drop obligation of the
305 // rest of the array.
307 // LV[j] is not tracked precisely
308 LpExtend(_, _, LpInterior(mc::InteriorElement(_))) => {
309 let mp = this.move_path(tcx, lp.clone());
310 gathered_fragments.push(AllButOneFrom(mp));
313 // field access LV.x and tuple access LV#k are the cases
314 // we are interested in
315 LpExtend(ref loan_parent, mc,
316 LpInterior(mc::InteriorField(ref field_name))) => {
317 let enum_variant_info = match loan_parent.kind {
318 LpDowncast(ref loan_parent_2, variant_def_id) =>
319 Some((variant_def_id, loan_parent_2.clone())),
320 LpExtend(..) | LpVar(..) | LpUpvar(..) =>
323 add_fragment_siblings_for_extension(
327 loan_parent, mc, field_name, &lp, origin_id, enum_variant_info);
332 /// We have determined that `origin_lp` destructures to LpExtend(parent, original_field_name).
333 /// Based on this, add move paths for all of the siblings of `origin_lp`.
334 fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>,
335 tcx: &ty::ctxt<'tcx>,
336 gathered_fragments: &mut Vec<Fragment>,
337 parent_lp: &Rc<LoanPath<'tcx>>,
338 mc: mc::MutabilityCategory,
339 origin_field_name: &mc::FieldName,
340 origin_lp: &Rc<LoanPath<'tcx>>,
341 origin_id: Option<ast::NodeId>,
342 enum_variant_info: Option<(ast::DefId,
343 Rc<LoanPath<'tcx>>)>) {
344 let parent_ty = parent_lp.to_type();
346 let mut add_fragment_sibling_local = |&mut : field_name, variant_did| {
347 add_fragment_sibling_core(
348 this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
352 match (&parent_ty.sty, enum_variant_info) {
353 (&ty::ty_tup(ref v), None) => {
354 let tuple_idx = match *origin_field_name {
355 mc::PositionalField(tuple_idx) => tuple_idx,
357 panic!("tuple type {} should not have named fields.",
358 parent_ty.repr(tcx)),
360 let tuple_len = v.len();
361 for i in 0..tuple_len {
362 if i == tuple_idx { continue }
363 let field_name = mc::PositionalField(i);
364 add_fragment_sibling_local(field_name, None);
368 (&ty::ty_struct(def_id, ref _substs), None) => {
369 let fields = ty::lookup_struct_fields(tcx, def_id);
370 match *origin_field_name {
371 mc::NamedField(ast_name) => {
373 if f.name == ast_name {
376 let field_name = mc::NamedField(f.name);
377 add_fragment_sibling_local(field_name, None);
380 mc::PositionalField(tuple_idx) => {
381 for (i, _f) in fields.iter().enumerate() {
385 let field_name = mc::PositionalField(i);
386 add_fragment_sibling_local(field_name, None);
392 (&ty::ty_enum(enum_def_id, substs), ref enum_variant_info) => {
394 let mut variants = ty::substd_enum_variants(tcx, enum_def_id, substs);
395 match *enum_variant_info {
396 Some((variant_def_id, ref _lp2)) =>
398 .find(|variant| variant.id == variant_def_id)
399 .expect("enum_variant_with_id(): no variant exists with that ID")
402 assert_eq!(variants.len(), 1);
403 variants.pop().unwrap()
407 match *origin_field_name {
408 mc::NamedField(ast_name) => {
409 let variant_arg_names = variant_info.arg_names.as_ref().unwrap();
410 for variant_arg_ident in variant_arg_names {
411 if variant_arg_ident.name == ast_name {
414 let field_name = mc::NamedField(variant_arg_ident.name);
415 add_fragment_sibling_local(field_name, Some(variant_info.id));
418 mc::PositionalField(tuple_idx) => {
419 let variant_arg_types = &variant_info.args;
420 for (i, _variant_arg_ty) in variant_arg_types.iter().enumerate() {
424 let field_name = mc::PositionalField(i);
425 add_fragment_sibling_local(field_name, None);
431 ref sty_and_variant_info => {
432 let msg = format!("type {} ({:?}) is not fragmentable",
433 parent_ty.repr(tcx), sty_and_variant_info);
434 let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id));
435 tcx.sess.opt_span_bug(opt_span, &msg[])
440 /// Adds the single sibling `LpExtend(parent, new_field_name)` of `origin_lp` (the original
442 fn add_fragment_sibling_core<'tcx>(this: &MoveData<'tcx>,
443 tcx: &ty::ctxt<'tcx>,
444 gathered_fragments: &mut Vec<Fragment>,
445 parent: Rc<LoanPath<'tcx>>,
446 mc: mc::MutabilityCategory,
447 new_field_name: mc::FieldName,
448 origin_lp: &Rc<LoanPath<'tcx>>,
449 enum_variant_did: Option<ast::DefId>) -> MovePathIndex {
450 let opt_variant_did = match parent.kind {
451 LpDowncast(_, variant_did) => Some(variant_did),
452 LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
455 let loan_path_elem = LpInterior(mc::InteriorField(new_field_name));
456 let new_lp_type = match new_field_name {
457 mc::NamedField(ast_name) =>
458 ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
459 mc::PositionalField(idx) =>
460 ty::positional_element_ty(tcx, parent.to_type(), idx, opt_variant_did),
462 let new_lp_variant = LpExtend(parent, mc, loan_path_elem);
463 let new_lp = LoanPath::new(new_lp_variant, new_lp_type.unwrap());
464 debug!("add_fragment_sibling_core(new_lp={}, origin_lp={})",
465 new_lp.repr(tcx), origin_lp.repr(tcx));
466 let mp = this.move_path(tcx, Rc::new(new_lp));
468 // Do not worry about checking for duplicates here; we will sort
469 // and dedup after all are added.
470 gathered_fragments.push(Just(mp));