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.
14 * The job of the categorization module is to analyze an expression to
15 * determine what kind of memory is used in evaluating it (for example,
16 * where dereferences occur and what kind of pointer is dereferenced;
17 * whether the memory is mutable; etc)
19 * Categorization effectively transforms all of our expressions into
20 * expressions of the following forms (the actual enum has many more
21 * possibilities, naturally, but they are all variants of these base
24 * E = rvalue // some computed rvalue
25 * | x // address of a local variable or argument
26 * | *E // deref of a ptr
27 * | E.comp // access to an interior component
29 * Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
30 * address where the result is to be found. If Expr is an lvalue, then this
31 * is the address of the lvalue. If Expr is an rvalue, this is the address of
32 * some temporary spot in memory where the result is stored.
34 * Now, cat_expr() classies the expression Expr and the address A=ToAddr(Expr)
37 * - cat: what kind of expression was this? This is a subset of the
38 * full expression forms which only includes those that we care about
39 * for the purpose of the analysis.
40 * - mutbl: mutability of the address A
41 * - ty: the type of data found at the address A
43 * The resulting categorization tree differs somewhat from the expressions
44 * themselves. For example, auto-derefs are explicit. Also, an index a[b] is
45 * decomposed into two operations: a derefence to reach the array data and
46 * then an index to jump forward to the relevant item.
48 * ## By-reference upvars
50 * One part of the translation which may be non-obvious is that we translate
51 * closure upvars into the dereference of a borrowed pointer; this more closely
52 * resembles the runtime translation. So, for example, if we had:
56 * let inc = || x += y;
58 * Then when we categorize `x` (*within* the closure) we would yield a
59 * result of `*x'`, effectively, where `x'` is a `cat_upvar` reference
60 * tied to `x`. The type of `x'` will be a borrowed pointer.
63 #[allow(non_camel_case_types)];
67 use util::ppaux::{ty_to_str, region_ptr_to_str, Repr};
70 use syntax::ast::{MutImmutable, MutMutable};
72 use syntax::codemap::Span;
73 use syntax::print::pprust;
74 use syntax::parse::token;
77 pub enum categorization {
78 cat_rvalue(ty::Region), // temporary val, argument is its scope
80 cat_copied_upvar(CopiedUpvar), // upvar copied into @fn or ~fn env
81 cat_upvar(ty::UpvarId, ty::UpvarBorrow), // by ref upvar from stack closure
82 cat_local(ast::NodeId), // local variable
83 cat_arg(ast::NodeId), // formal argument
84 cat_deref(cmt, uint, PointerKind), // deref of a ptr
85 cat_interior(cmt, InteriorKind), // something interior: field, tuple, etc
86 cat_downcast(cmt), // selects a particular enum variant (*1)
87 cat_discr(cmt, ast::NodeId), // match discriminant (see preserve())
89 // (*1) downcast is only required if the enum has more than one variant
93 pub struct CopiedUpvar {
94 upvar_id: ast::NodeId,
95 onceness: ast::Onceness,
98 // different kinds of pointers:
100 pub enum PointerKind {
103 BorrowedPtr(ty::BorrowKind, ty::Region),
104 UnsafePtr(ast::Mutability),
107 // We use the term "interior" to mean "something reachable from the
108 // base without a pointer dereference", e.g. a field
109 #[deriving(Eq, Hash)]
110 pub enum InteriorKind {
111 InteriorField(FieldName),
112 InteriorElement(ElementKind),
115 #[deriving(Eq, Hash)]
117 NamedField(ast::Name),
118 PositionalField(uint)
121 #[deriving(Eq, Hash)]
122 pub enum ElementKind {
128 #[deriving(Eq, Hash, Show)]
129 pub enum MutabilityCategory {
130 McImmutable, // Immutable.
131 McDeclared, // Directly declared as mutable.
132 McInherited, // Inherited from the fact that owner is mutable.
135 // `cmt`: "Category, Mutability, and Type".
137 // a complete categorization of a value indicating where it originated
138 // and how it is located, as well as the mutability of the memory in
139 // which the value is stored.
141 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
142 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
143 // always the `id` of the node producing the type; in an expression
144 // like `*x`, the type of this deref node is the deref'd type (`T`),
145 // but in a pattern like `@x`, the `@x` pattern is again a
146 // dereference, but its type is the type *before* the dereference
147 // (`@T`). So use `cmt.type` to find the type of the value in a consistent
148 // fashion. For more details, see the method `cat_pattern`
151 id: ast::NodeId, // id of expr/pat producing this value
152 span: Span, // span of same expr/pat
153 cat: categorization, // categorization of expr
154 mutbl: MutabilityCategory, // mutability of expr as lvalue
155 ty: ty::t // type of the expr (*see WARNING above*)
158 pub type cmt = @cmt_;
160 // We pun on *T to mean both actual deref of a ptr as well
161 // as accessing of components:
162 pub enum deref_kind {
163 deref_ptr(PointerKind),
164 deref_interior(InteriorKind),
167 // Categorizes a derefable type. Note that we include vectors and strings as
168 // derefable (we model an index as the combination of a deref and then a
169 // pointer adjustment).
170 pub fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
171 match ty::get(t).sty {
173 ty::ty_trait(~ty::TyTrait { store: ty::UniqTraitStore, .. }) |
174 ty::ty_vec(_, ty::vstore_uniq) |
175 ty::ty_str(ty::vstore_uniq) |
176 ty::ty_closure(~ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
177 Some(deref_ptr(OwnedPtr))
181 ty::ty_vec(mt, ty::vstore_slice(r)) => {
182 let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
183 Some(deref_ptr(BorrowedPtr(kind, r)))
186 ty::ty_trait(~ty::TyTrait { store: ty::RegionTraitStore(r), mutability: m, .. }) => {
187 let kind = ty::BorrowKind::from_mutbl(m);
188 Some(deref_ptr(BorrowedPtr(kind, r)))
191 ty::ty_str(ty::vstore_slice(r)) |
192 ty::ty_closure(~ty::ClosureTy {sigil: ast::BorrowedSigil,
194 Some(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
198 Some(deref_ptr(GcPtr))
201 ty::ty_ptr(ref mt) => {
202 Some(deref_ptr(UnsafePtr(mt.mutbl)))
206 ty::ty_struct(..) => { // newtype
207 Some(deref_interior(InteriorField(PositionalField(0))))
210 ty::ty_vec(_, ty::vstore_fixed(_)) |
211 ty::ty_str(ty::vstore_fixed(_)) => {
212 Some(deref_interior(InteriorElement(element_kind(t))))
219 pub fn deref_kind(tcx: &ty::ctxt, t: ty::t) -> deref_kind {
220 match opt_deref_kind(t) {
224 format!("deref_cat() invoked on non-derefable type {}",
231 fn id(&self) -> ast::NodeId;
232 fn span(&self) -> Span;
235 impl ast_node for ast::Expr {
236 fn id(&self) -> ast::NodeId { self.id }
237 fn span(&self) -> Span { self.span }
240 impl ast_node for ast::Pat {
241 fn id(&self) -> ast::NodeId { self.id }
242 fn span(&self) -> Span { self.span }
245 pub struct MemCategorizationContext<TYPER> {
249 pub type McResult<T> = Result<T, ()>;
252 * The `Typer` trait provides the interface for the mem-categorization
253 * module to the results of the type check. It can be used to query
254 * the type assigned to an expression node, to inquire after adjustments,
257 * This interface is needed because mem-categorization is used from
258 * two places: `regionck` and `borrowck`. `regionck` executes before
259 * type inference is complete, and hence derives types and so on from
260 * intermediate tables. This also implies that type errors can occur,
261 * and hence `node_ty()` and friends return a `Result` type -- any
262 * error will propagate back up through the mem-categorization
265 * In the borrow checker, in contrast, type checking is complete and we
266 * know that no errors have occurred, so we simply consult the tcx and we
267 * can be sure that only `Ok` results will occur.
270 fn tcx<'a>(&'a self) -> &'a ty::ctxt;
271 fn node_ty(&mut self, id: ast::NodeId) -> McResult<ty::t>;
272 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t>;
273 fn adjustment(&mut self, node_id: ast::NodeId) -> Option<@ty::AutoAdjustment>;
274 fn is_method_call(&mut self, id: ast::NodeId) -> bool;
275 fn temporary_scope(&mut self, rvalue_id: ast::NodeId) -> Option<ast::NodeId>;
276 fn upvar_borrow(&mut self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow;
279 impl MutabilityCategory {
280 pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
282 MutImmutable => McImmutable,
283 MutMutable => McDeclared
287 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
289 ty::ImmBorrow => McImmutable,
290 ty::UniqueImmBorrow => McImmutable,
291 ty::MutBorrow => McDeclared,
295 pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
296 ptr: PointerKind) -> MutabilityCategory {
301 BorrowedPtr(borrow_kind, _) => {
302 MutabilityCategory::from_borrow_kind(borrow_kind)
308 MutabilityCategory::from_mutbl(m)
313 pub fn inherit(&self) -> MutabilityCategory {
315 McImmutable => McImmutable,
316 McDeclared => McInherited,
317 McInherited => McInherited,
321 pub fn is_mutable(&self) -> bool {
323 McImmutable => false,
329 pub fn is_immutable(&self) -> bool {
332 McDeclared | McInherited => false
336 pub fn to_user_str(&self) -> &'static str {
338 McDeclared | McInherited => "mutable",
339 McImmutable => "immutable",
348 Err(e) => { return Err(e); }
353 impl<TYPER:Typer> MemCategorizationContext<TYPER> {
354 fn tcx<'a>(&'a self) -> &'a ty::ctxt {
358 fn adjustment(&mut self, id: ast::NodeId) -> Option<@ty::AutoAdjustment> {
359 self.typer.adjustment(id)
362 fn expr_ty(&mut self, expr: &ast::Expr) -> McResult<ty::t> {
363 self.typer.node_ty(expr.id)
366 fn expr_ty_adjusted(&mut self, expr: &ast::Expr) -> McResult<ty::t> {
367 let unadjusted_ty = if_ok!(self.expr_ty(expr));
368 let adjustment = self.adjustment(expr.id);
369 Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty, adjustment,
370 |method_call| self.typer.node_method_ty(method_call)))
373 fn node_ty(&mut self, id: ast::NodeId) -> McResult<ty::t> {
374 self.typer.node_ty(id)
377 fn pat_ty(&mut self, pat: @ast::Pat) -> McResult<ty::t> {
378 self.typer.node_ty(pat.id)
381 pub fn cat_expr(&mut self, expr: &ast::Expr) -> McResult<cmt> {
382 match self.adjustment(expr.id) {
385 self.cat_expr_unadjusted(expr)
388 Some(adjustment) => {
390 ty::AutoObject(..) => {
391 // Implicity casts a concrete object to trait object
392 // so just patch up the type
393 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
394 let expr_cmt = if_ok!(self.cat_expr_unadjusted(expr));
395 Ok(@cmt_ {ty: expr_ty, ..*expr_cmt})
398 ty::AutoAddEnv(..) => {
399 // Convert a bare fn to a closure by adding NULL env.
400 // Result is an rvalue.
401 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
402 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
407 autoref: Some(_), ..}) => {
408 // Equivalent to &*expr or something similar.
409 // Result is an rvalue.
410 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
411 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
416 autoref: None, autoderefs: autoderefs}) => {
417 // Equivalent to *expr or something similar.
418 self.cat_expr_autoderefd(expr, autoderefs)
425 pub fn cat_expr_autoderefd(&mut self, expr: &ast::Expr, autoderefs: uint)
427 let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
428 for deref in range(1u, autoderefs + 1) {
429 cmt = self.cat_deref(expr, cmt, deref);
434 pub fn cat_expr_unadjusted(&mut self, expr: &ast::Expr) -> McResult<cmt> {
435 debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
437 let expr_ty = if_ok!(self.expr_ty(expr));
439 ast::ExprUnary(ast::UnDeref, e_base) => {
440 let base_cmt = if_ok!(self.cat_expr(e_base));
441 Ok(self.cat_deref(expr, base_cmt, 0))
444 ast::ExprField(base, f_name, _) => {
445 let base_cmt = if_ok!(self.cat_expr(base));
446 Ok(self.cat_field(expr, base_cmt, f_name, expr_ty))
449 ast::ExprIndex(base, _) => {
450 if self.typer.is_method_call(expr.id) {
451 return Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty));
454 let base_cmt = if_ok!(self.cat_expr(base));
455 Ok(self.cat_index(expr, base_cmt, 0))
458 ast::ExprPath(_) => {
459 let def_map = self.tcx().def_map.borrow();
460 let def = def_map.get().get_copy(&expr.id);
461 self.cat_def(expr.id, expr.span, expr_ty, def)
464 ast::ExprParen(e) => self.cat_expr_unadjusted(e),
466 ast::ExprAddrOf(..) | ast::ExprCall(..) |
467 ast::ExprAssign(..) | ast::ExprAssignOp(..) |
468 ast::ExprFnBlock(..) | ast::ExprProc(..) | ast::ExprRet(..) |
470 ast::ExprMethodCall(..) | ast::ExprCast(..) | ast::ExprVstore(..) |
471 ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
472 ast::ExprBinary(..) | ast::ExprWhile(..) |
473 ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
474 ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
475 ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
476 ast::ExprInlineAsm(..) | ast::ExprBox(..) => {
477 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
480 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop")
484 pub fn cat_def(&mut self,
490 debug!("cat_def: id={} expr={}",
491 id, expr_ty.repr(self.tcx()));
494 ast::DefStruct(..) | ast::DefVariant(..) => {
495 Ok(self.cat_rvalue_node(id, span, expr_ty))
497 ast::DefFn(..) | ast::DefStaticMethod(..) | ast::DefMod(_) |
498 ast::DefForeignMod(_) | ast::DefStatic(_, false) |
499 ast::DefUse(_) | ast::DefTrait(_) | ast::DefTy(_) | ast::DefPrimTy(_) |
500 ast::DefTyParam(..) | ast::DefTyParamBinder(..) | ast::DefRegion(_) |
501 ast::DefLabel(_) | ast::DefSelfTy(..) | ast::DefMethod(..) => {
511 ast::DefStatic(_, true) => {
521 ast::DefArg(vid, binding_mode) => {
522 // Idea: make this could be rewritten to model by-ref
523 // stuff as `&const` and `&mut`?
525 // m: mutability of the argument
526 let m = match binding_mode {
527 ast::BindByValue(ast::MutMutable) => McDeclared,
539 ast::DefUpvar(var_id, _, fn_node_id, _) => {
540 let ty = if_ok!(self.node_ty(fn_node_id));
541 match ty::get(ty).sty {
542 ty::ty_closure(ref closure_ty) => {
543 // Decide whether to use implicit reference or by copy/move
544 // capture for the upvar. This, combined with the onceness,
545 // determines whether the closure can move out of it.
546 let var_is_refd = match (closure_ty.sigil, closure_ty.onceness) {
547 // Many-shot stack closures can never move out.
548 (ast::BorrowedSigil, ast::Many) => true,
549 // 1-shot stack closures can move out.
550 (ast::BorrowedSigil, ast::Once) => false,
551 // Heap closures always capture by copy/move, and can
552 // move out if they are once.
553 (ast::OwnedSigil, _) |
554 (ast::ManagedSigil, _) => false,
558 self.cat_upvar(id, span, var_id, fn_node_id)
560 // FIXME #2152 allow mutation of moved upvars
564 cat:cat_copied_upvar(CopiedUpvar {
566 onceness: closure_ty.onceness}),
573 self.tcx().sess.span_bug(
575 format!("Upvar of non-closure {} - {}",
576 fn_node_id, ty.repr(self.tcx())));
581 ast::DefLocal(vid, binding_mode) |
582 ast::DefBinding(vid, binding_mode) => {
583 // by-value/by-ref bindings are local variables
584 let m = match binding_mode {
585 ast::BindByValue(ast::MutMutable) => McDeclared,
600 fn cat_upvar(&mut self,
604 fn_node_id: ast::NodeId)
607 * Upvars through a closure are in fact indirect
608 * references. That is, when a closure refers to a
609 * variable from a parent stack frame like `x = 10`,
610 * that is equivalent to `*x_ = 10` where `x_` is a
611 * borrowed pointer (`&mut x`) created when the closure
612 * was created and store in the environment. This
613 * equivalence is expose in the mem-categorization.
616 let upvar_id = ty::UpvarId { var_id: var_id,
617 closure_expr_id: fn_node_id };
619 let upvar_borrow = self.typer.upvar_borrow(upvar_id);
621 let var_ty = if_ok!(self.node_ty(var_id));
623 // We can't actually represent the types of all upvars
624 // as user-describable types, since upvars support const
625 // and unique-imm borrows! Therefore, we cheat, and just
626 // give err type. Nobody should be inspecting this type anyhow.
627 let upvar_ty = ty::mk_err();
629 let base_cmt = @cmt_ {
632 cat:cat_upvar(upvar_id, upvar_borrow),
637 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
639 let deref_cmt = @cmt_ {
642 cat:cat_deref(base_cmt, 0, ptr),
643 mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
650 pub fn cat_rvalue_node(&mut self,
655 match self.typer.temporary_scope(id) {
657 self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
660 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
665 pub fn cat_rvalue(&mut self,
668 temp_scope: ty::Region,
669 expr_ty: ty::t) -> cmt {
673 cat:cat_rvalue(temp_scope),
679 /// inherited mutability: used in cases where the mutability of a
680 /// component is inherited from the base it is a part of. For
681 /// example, a record field is mutable if it is declared mutable
682 /// or if the container is mutable.
683 pub fn inherited_mutability(&mut self,
684 base_m: MutabilityCategory,
685 interior_m: ast::Mutability)
686 -> MutabilityCategory {
688 MutImmutable => base_m.inherit(),
689 MutMutable => McDeclared
693 pub fn cat_field<N:ast_node>(&mut self,
702 cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
703 mutbl: base_cmt.mutbl.inherit(),
708 pub fn cat_deref_fn_or_obj<N:ast_node>(&mut self,
713 // Bit of a hack: the "dereference" of a function pointer like
714 // `@fn()` is a mere logical concept. We interpret it as
715 // dereferencing the environment pointer; of course, we don't
716 // know what type lies at the other end, so we just call it
717 // `()` (the empty tuple).
719 let opaque_ty = ty::mk_tup(self.tcx(), Vec::new());
720 self.cat_deref_common(node, base_cmt, deref_cnt, opaque_ty)
723 fn cat_deref<N:ast_node>(&mut self,
728 let method_call = typeck::MethodCall {
730 autoderef: deref_cnt as u32
732 let method_ty = self.typer.node_method_ty(method_call);
734 debug!("cat_deref: method_call={:?} method_ty={}",
735 method_call, method_ty.map(|ty| ty.repr(self.tcx())));
737 let base_cmt = match method_ty {
739 let ref_ty = ty::ty_fn_ret(method_ty);
740 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
744 match ty::deref(base_cmt.ty, true) {
745 Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty),
747 self.tcx().sess.span_bug(
749 format!("Explicit deref of non-derefable type: {}",
750 base_cmt.ty.repr(self.tcx())));
755 fn cat_deref_common<N:ast_node>(&mut self,
761 let (m, cat) = match deref_kind(self.tcx(), base_cmt.ty) {
763 // for unique ptrs, we inherit mutability from the
765 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
766 cat_deref(base_cmt, deref_cnt, ptr))
768 deref_interior(interior) => {
769 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
781 pub fn cat_index<N:ast_node>(&mut self,
786 //! Creates a cmt for an indexing operation (`[]`); this
787 //! indexing operation may occurs as part of an
788 //! AutoBorrowVec, which when converting a `~[]` to an `&[]`
789 //! effectively takes the address of the 0th element.
791 //! One subtle aspect of indexing that may not be
792 //! immediately obvious: for anything other than a fixed-length
793 //! vector, an operation like `x[y]` actually consists of two
794 //! disjoint (from the point of view of borrowck) operations.
795 //! The first is a deref of `x` to create a pointer `p` that points
796 //! at the first element in the array. The second operation is
797 //! an index which adds `y*sizeof(T)` to `p` to obtain the
798 //! pointer to `x[y]`. `cat_index` will produce a resulting
799 //! cmt containing both this deref and the indexing,
800 //! presuming that `base_cmt` is not of fixed-length type.
802 //! In the event that a deref is needed, the "deref count"
803 //! is taken from the parameter `derefs`. See the comment
804 //! on the def'n of `root_map_key` in borrowck/mod.rs
805 //! for more details about deref counts; the summary is
806 //! that `derefs` should be 0 for an explicit indexing
807 //! operation and N+1 for an indexing that is part of
808 //! an auto-adjustment, where N is the number of autoderefs
809 //! in that adjustment.
812 //! - `elt`: the AST node being indexed
813 //! - `base_cmt`: the cmt of `elt`
814 //! - `derefs`: the deref number to be used for
815 //! the implicit index deref, if any (see above)
817 let element_ty = match ty::index(base_cmt.ty) {
818 Some(ref mt) => mt.ty,
820 self.tcx().sess.span_bug(
822 format!("Explicit index of non-index type `{}`",
823 base_cmt.ty.repr(self.tcx())));
827 return match deref_kind(self.tcx(), base_cmt.ty) {
829 // for unique ptrs, we inherit mutability from the
831 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
833 // the deref is explicit in the resulting cmt
834 let deref_cmt = @cmt_ {
837 cat:cat_deref(base_cmt, derefs, ptr),
842 interior(elt, deref_cmt, base_cmt.ty, m.inherit(), element_ty)
845 deref_interior(_) => {
846 // fixed-length vectors have no deref
847 let m = base_cmt.mutbl.inherit();
848 interior(elt, base_cmt, base_cmt.ty, m, element_ty)
852 fn interior<N: ast_node>(elt: &N,
855 mutbl: MutabilityCategory,
856 element_ty: ty::t) -> cmt
861 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
868 pub fn cat_slice_pattern(&mut self,
870 slice_pat: @ast::Pat)
871 -> McResult<(cmt, ast::Mutability, ty::Region)> {
873 * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
874 * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
876 * - the mutability and region of the slice `Q`
878 * These last two bits of info happen to be things that
882 let slice_ty = if_ok!(self.node_ty(slice_pat.id));
883 let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
886 let cmt_slice = self.cat_index(slice_pat, vec_cmt, 0);
887 return Ok((cmt_slice, slice_mutbl, slice_r));
889 fn vec_slice_info(tcx: &ty::ctxt,
892 -> (ast::Mutability, ty::Region) {
894 * In a pattern like [a, b, ..c], normally `c` has slice type,
895 * but if you have [a, b, ..ref c], then the type of `ref c`
896 * will be `&&[]`, so to extract the slice details we have
897 * to recurse through rptrs.
900 match ty::get(slice_ty).sty {
901 ty::ty_vec(slice_mt, ty::vstore_slice(slice_r)) => {
902 (slice_mt.mutbl, slice_r)
905 ty::ty_rptr(_, ref mt) => {
906 vec_slice_info(tcx, pat, mt.ty)
912 format!("Type of slice pattern is not a slice"));
918 pub fn cat_imm_interior<N:ast_node>(&mut self,
922 interior: InteriorKind)
927 cat: cat_interior(base_cmt, interior),
928 mutbl: base_cmt.mutbl.inherit(),
933 pub fn cat_downcast<N:ast_node>(&mut self,
941 cat: cat_downcast(base_cmt),
942 mutbl: base_cmt.mutbl.inherit(),
947 pub fn cat_pattern(&mut self,
950 op: |&mut MemCategorizationContext<TYPER>,
954 // Here, `cmt` is the categorization for the value being
955 // matched and pat is the pattern it is being matched against.
957 // In general, the way that this works is that we walk down
958 // the pattern, constructing a cmt that represents the path
959 // that will be taken to reach the value being matched.
961 // When we encounter named bindings, we take the cmt that has
962 // been built up and pass it off to guarantee_valid() so that
963 // we can be sure that the binding will remain valid for the
964 // duration of the arm.
966 // (*2) There is subtlety concerning the correspondence between
967 // pattern ids and types as compared to *expression* ids and
968 // types. This is explained briefly. on the definition of the
969 // type `cmt`, so go off and read what it says there, then
970 // come back and I'll dive into a bit more detail here. :) OK,
973 // In general, the id of the cmt should be the node that
974 // "produces" the value---patterns aren't executable code
975 // exactly, but I consider them to "execute" when they match a
976 // value, and I consider them to produce the value that was
977 // matched. So if you have something like:
984 // In this case, the cmt and the relevant ids would be:
986 // CMT Id Type of Id Type of cmt
989 // ^~~~~~~^ `x` from discr @@int @@int
990 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
991 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
993 // You can see that the types of the id and the cmt are in
994 // sync in the first line, because that id is actually the id
995 // of an expression. But once we get to pattern ids, the types
996 // step out of sync again. So you'll see below that we always
997 // get the type of the *subpattern* and use that.
999 debug!("cat_pattern: id={} pat={} cmt={}",
1000 pat.id, pprust::pat_to_str(pat),
1001 cmt.repr(self.tcx()));
1006 ast::PatWild | ast::PatWildMulti => {
1010 ast::PatEnum(_, None) => {
1013 ast::PatEnum(_, Some(ref subpats)) => {
1014 let def_map = self.tcx().def_map.borrow();
1015 match def_map.get().find(&pat.id) {
1016 Some(&ast::DefVariant(enum_did, _, _)) => {
1019 let downcast_cmt = {
1020 if ty::enum_is_univariant(self.tcx(), enum_did) {
1021 cmt // univariant, no downcast needed
1023 self.cat_downcast(pat, cmt, cmt.ty)
1027 for (i, &subpat) in subpats.iter().enumerate() {
1028 let subpat_ty = if_ok!(self.pat_ty(subpat)); // see (*2)
1031 self.cat_imm_interior(
1032 pat, downcast_cmt, subpat_ty,
1033 InteriorField(PositionalField(i)));
1035 if_ok!(self.cat_pattern(subcmt, subpat, |x,y,z| op(x,y,z)));
1038 Some(&ast::DefFn(..)) |
1039 Some(&ast::DefStruct(..)) => {
1040 for (i, &subpat) in subpats.iter().enumerate() {
1041 let subpat_ty = if_ok!(self.pat_ty(subpat)); // see (*2)
1043 self.cat_imm_interior(
1044 pat, cmt, subpat_ty,
1045 InteriorField(PositionalField(i)));
1046 if_ok!(self.cat_pattern(cmt_field, subpat, |x,y,z| op(x,y,z)));
1049 Some(&ast::DefStatic(..)) => {
1050 for &subpat in subpats.iter() {
1051 if_ok!(self.cat_pattern(cmt, subpat, |x,y,z| op(x,y,z)));
1055 self.tcx().sess.span_bug(
1057 "enum pattern didn't resolve to enum or struct");
1062 ast::PatIdent(_, _, Some(subpat)) => {
1063 if_ok!(self.cat_pattern(cmt, subpat, op));
1066 ast::PatIdent(_, _, None) => {
1067 // nullary variant or identifier: ignore
1070 ast::PatStruct(_, ref field_pats, _) => {
1071 // {f1: p1, ..., fN: pN}
1072 for fp in field_pats.iter() {
1073 let field_ty = if_ok!(self.pat_ty(fp.pat)); // see (*2)
1074 let cmt_field = self.cat_field(pat, cmt, fp.ident, field_ty);
1075 if_ok!(self.cat_pattern(cmt_field, fp.pat, |x,y,z| op(x,y,z)));
1079 ast::PatTup(ref subpats) => {
1081 for (i, &subpat) in subpats.iter().enumerate() {
1082 let subpat_ty = if_ok!(self.pat_ty(subpat)); // see (*2)
1084 self.cat_imm_interior(
1085 pat, cmt, subpat_ty,
1086 InteriorField(PositionalField(i)));
1087 if_ok!(self.cat_pattern(subcmt, subpat, |x,y,z| op(x,y,z)));
1091 ast::PatUniq(subpat) | ast::PatRegion(subpat) => {
1093 let subcmt = self.cat_deref(pat, cmt, 0);
1094 if_ok!(self.cat_pattern(subcmt, subpat, op));
1097 ast::PatVec(ref before, slice, ref after) => {
1098 let elt_cmt = self.cat_index(pat, cmt, 0);
1099 for &before_pat in before.iter() {
1100 if_ok!(self.cat_pattern(elt_cmt, before_pat, |x,y,z| op(x,y,z)));
1102 for &slice_pat in slice.iter() {
1103 let slice_ty = if_ok!(self.pat_ty(slice_pat));
1104 let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1105 if_ok!(self.cat_pattern(slice_cmt, slice_pat, |x,y,z| op(x,y,z)));
1107 for &after_pat in after.iter() {
1108 if_ok!(self.cat_pattern(elt_cmt, after_pat, |x,y,z| op(x,y,z)));
1112 ast::PatLit(_) | ast::PatRange(_, _) => {
1120 pub fn mut_to_str(&mut self, mutbl: ast::Mutability) -> ~str {
1122 MutMutable => ~"mutable",
1123 MutImmutable => ~"immutable"
1127 pub fn cmt_to_str(&self, cmt: cmt) -> ~str {
1129 cat_static_item => {
1132 cat_copied_upvar(_) => {
1133 ~"captured outer variable in a heap closure"
1144 cat_deref(base, _, pk) => {
1147 format!("captured outer variable")
1150 format!("dereference of `{}`-pointer", ptr_sigil(pk))
1154 cat_interior(_, InteriorField(NamedField(_))) => {
1157 cat_interior(_, InteriorField(PositionalField(_))) => {
1160 cat_interior(_, InteriorElement(VecElement)) => {
1163 cat_interior(_, InteriorElement(StrElement)) => {
1166 cat_interior(_, InteriorElement(OtherElement)) => {
1170 ~"captured outer variable"
1172 cat_discr(cmt, _) => {
1173 self.cmt_to_str(cmt)
1175 cat_downcast(cmt) => {
1176 self.cmt_to_str(cmt)
1181 pub fn region_to_str(&self, r: ty::Region) -> ~str {
1182 region_ptr_to_str(self.tcx(), r)
1186 /// The node_id here is the node of the expression that references the field.
1187 /// This function looks it up in the def map in case the type happens to be
1188 /// an enum to determine which variant is in use.
1189 pub fn field_mutbl(tcx: &ty::ctxt,
1191 // FIXME #6993: change type to Name
1193 node_id: ast::NodeId)
1194 -> Option<ast::Mutability> {
1195 // Need to refactor so that struct/enum fields can be treated uniformly.
1196 match ty::get(base_ty).sty {
1197 ty::ty_struct(did, _) => {
1198 let r = ty::lookup_struct_fields(tcx, did);
1199 for fld in r.iter() {
1200 if fld.name == f_name.name {
1201 return Some(ast::MutImmutable);
1205 ty::ty_enum(..) => {
1206 let def_map = tcx.def_map.borrow();
1207 match def_map.get().get_copy(&node_id) {
1208 ast::DefVariant(_, variant_id, _) => {
1209 let r = ty::lookup_struct_fields(tcx, variant_id);
1210 for fld in r.iter() {
1211 if fld.name == f_name.name {
1212 return Some(ast::MutImmutable);
1225 pub enum AliasableReason {
1234 pub fn guarantor(self) -> cmt {
1235 //! Returns `self` after stripping away any owned pointer derefs or
1236 //! interior content. The return value is basically the `cmt` which
1237 //! determines how long the value in `self` remains live.
1242 cat_copied_upvar(..) |
1245 cat_deref(_, _, UnsafePtr(..)) |
1246 cat_deref(_, _, GcPtr(..)) |
1247 cat_deref(_, _, BorrowedPtr(..)) |
1253 cat_interior(b, _) |
1254 cat_deref(b, _, OwnedPtr) => {
1260 pub fn freely_aliasable(&self) -> Option<AliasableReason> {
1262 * Returns `Some(_)` if this lvalue represents a freely aliasable
1266 // Maybe non-obvious: copied upvars can only be considered
1267 // non-aliasable in once closures, since any other kind can be
1268 // aliased and eventually recused.
1271 cat_deref(b, _, BorrowedPtr(ty::MutBorrow, _)) |
1272 cat_deref(b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1274 cat_deref(b, _, OwnedPtr) |
1275 cat_interior(b, _) |
1276 cat_discr(b, _) => {
1277 // Aliasability depends on base cmt
1278 b.freely_aliasable()
1281 cat_copied_upvar(CopiedUpvar {onceness: ast::Once, ..}) |
1286 cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1290 cat_copied_upvar(CopiedUpvar {onceness: ast::Many, ..}) => {
1291 Some(AliasableOther)
1294 cat_static_item(..) => {
1295 if self.mutbl.is_mutable() {
1296 Some(AliasableStaticMut)
1298 Some(AliasableStatic)
1302 cat_deref(_, _, GcPtr) => {
1303 Some(AliasableManaged)
1306 cat_deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) => {
1307 Some(AliasableBorrowed)
1313 impl Repr for cmt_ {
1314 fn repr(&self, tcx: &ty::ctxt) -> ~str {
1315 format!("\\{{} id:{} m:{:?} ty:{}\\}",
1323 impl Repr for categorization {
1324 fn repr(&self, tcx: &ty::ctxt) -> ~str {
1328 cat_copied_upvar(..) |
1332 format!("{:?}", *self)
1334 cat_deref(cmt, derefs, ptr) => {
1335 format!("{}-{}{}->",
1340 cat_interior(cmt, interior) => {
1345 cat_downcast(cmt) => {
1346 format!("{}->(enum)", cmt.cat.repr(tcx))
1348 cat_discr(cmt, _) => {
1355 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1359 BorrowedPtr(ty::ImmBorrow, _) => "&",
1360 BorrowedPtr(ty::MutBorrow, _) => "&mut",
1361 BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1366 impl Repr for InteriorKind {
1367 fn repr(&self, _tcx: &ty::ctxt) -> ~str {
1369 InteriorField(NamedField(fld)) => {
1370 token::get_name(fld).get().to_str()
1372 InteriorField(PositionalField(i)) => format!("\\#{:?}", i),
1373 InteriorElement(_) => ~"[]",
1378 fn element_kind(t: ty::t) -> ElementKind {
1379 match ty::get(t).sty {
1380 ty::ty_vec(..) => VecElement,
1381 ty::ty_str(..) => StrElement,