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() classifies 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 dereference 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)]
68 use util::nodemap::NodeMap;
69 use util::ppaux::{ty_to_str, Repr};
71 use syntax::ast::{MutImmutable, MutMutable};
73 use syntax::codemap::Span;
74 use syntax::print::pprust;
75 use syntax::parse::token;
77 use std::cell::RefCell;
80 #[deriving(Clone, PartialEq)]
81 pub enum categorization {
82 cat_rvalue(ty::Region), // temporary val, argument is its scope
84 cat_copied_upvar(CopiedUpvar), // upvar copied into proc env
85 cat_upvar(ty::UpvarId, ty::UpvarBorrow), // by ref upvar from stack closure
86 cat_local(ast::NodeId), // local variable
87 cat_arg(ast::NodeId), // formal argument
88 cat_deref(cmt, uint, PointerKind), // deref of a ptr
89 cat_interior(cmt, InteriorKind), // something interior: field, tuple, etc
90 cat_downcast(cmt), // selects a particular enum variant (*1)
91 cat_discr(cmt, ast::NodeId), // match discriminant (see preserve())
93 // (*1) downcast is only required if the enum has more than one variant
96 #[deriving(Clone, PartialEq)]
97 pub struct CopiedUpvar {
98 pub upvar_id: ast::NodeId,
99 pub onceness: ast::Onceness,
102 // different kinds of pointers:
103 #[deriving(Clone, PartialEq, Eq, Hash)]
104 pub enum PointerKind {
107 BorrowedPtr(ty::BorrowKind, ty::Region),
108 UnsafePtr(ast::Mutability),
111 // We use the term "interior" to mean "something reachable from the
112 // base without a pointer dereference", e.g. a field
113 #[deriving(Clone, PartialEq, Eq, Hash)]
114 pub enum InteriorKind {
115 InteriorField(FieldName),
116 InteriorElement(ElementKind),
119 #[deriving(Clone, PartialEq, Eq, Hash)]
121 NamedField(ast::Name),
122 PositionalField(uint)
125 #[deriving(Clone, PartialEq, Eq, Hash)]
126 pub enum ElementKind {
132 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
133 pub enum MutabilityCategory {
134 McImmutable, // Immutable.
135 McDeclared, // Directly declared as mutable.
136 McInherited, // Inherited from the fact that owner is mutable.
139 // `cmt`: "Category, Mutability, and Type".
141 // a complete categorization of a value indicating where it originated
142 // and how it is located, as well as the mutability of the memory in
143 // which the value is stored.
145 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
146 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
147 // always the `id` of the node producing the type; in an expression
148 // like `*x`, the type of this deref node is the deref'd type (`T`),
149 // but in a pattern like `@x`, the `@x` pattern is again a
150 // dereference, but its type is the type *before* the dereference
151 // (`@T`). So use `cmt.type` to find the type of the value in a consistent
152 // fashion. For more details, see the method `cat_pattern`
153 #[deriving(Clone, PartialEq)]
155 pub id: ast::NodeId, // id of expr/pat producing this value
156 pub span: Span, // span of same expr/pat
157 pub cat: categorization, // categorization of expr
158 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
159 pub ty: ty::t // type of the expr (*see WARNING above*)
162 pub type cmt = Rc<cmt_>;
164 // We pun on *T to mean both actual deref of a ptr as well
165 // as accessing of components:
166 pub enum deref_kind {
167 deref_ptr(PointerKind),
168 deref_interior(InteriorKind),
171 // Categorizes a derefable type. Note that we include vectors and strings as
172 // derefable (we model an index as the combination of a deref and then a
173 // pointer adjustment).
174 pub fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
175 match ty::get(t).sty {
177 ty::ty_trait(box ty::TyTrait { store: ty::UniqTraitStore, .. }) |
178 ty::ty_closure(box ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
179 Some(deref_ptr(OwnedPtr))
182 ty::ty_rptr(r, mt) => {
183 let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
184 Some(deref_ptr(BorrowedPtr(kind, r)))
186 ty::ty_trait(box ty::TyTrait {
187 store: ty::RegionTraitStore(r, mutbl),
190 let kind = ty::BorrowKind::from_mutbl(mutbl);
191 Some(deref_ptr(BorrowedPtr(kind, r)))
194 ty::ty_closure(box ty::ClosureTy {
195 store: ty::RegionTraitStore(r, _),
198 Some(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
202 Some(deref_ptr(GcPtr))
205 ty::ty_ptr(ref mt) => {
206 Some(deref_ptr(UnsafePtr(mt.mutbl)))
210 ty::ty_struct(..) => { // newtype
211 Some(deref_interior(InteriorField(PositionalField(0))))
214 ty::ty_vec(_, Some(_)) => {
215 Some(deref_interior(InteriorElement(element_kind(t))))
222 pub fn deref_kind(tcx: &ty::ctxt, t: ty::t) -> deref_kind {
223 match opt_deref_kind(t) {
227 format!("deref_cat() invoked on non-derefable type {}",
228 ty_to_str(tcx, t)).as_slice());
234 fn id(&self) -> ast::NodeId;
235 fn span(&self) -> Span;
238 impl ast_node for ast::Expr {
239 fn id(&self) -> ast::NodeId { self.id }
240 fn span(&self) -> Span { self.span }
243 impl ast_node for ast::Pat {
244 fn id(&self) -> ast::NodeId { self.id }
245 fn span(&self) -> Span { self.span }
248 pub struct MemCategorizationContext<'t,TYPER> {
252 pub type McResult<T> = Result<T, ()>;
255 * The `Typer` trait provides the interface for the mem-categorization
256 * module to the results of the type check. It can be used to query
257 * the type assigned to an expression node, to inquire after adjustments,
260 * This interface is needed because mem-categorization is used from
261 * two places: `regionck` and `borrowck`. `regionck` executes before
262 * type inference is complete, and hence derives types and so on from
263 * intermediate tables. This also implies that type errors can occur,
264 * and hence `node_ty()` and friends return a `Result` type -- any
265 * error will propagate back up through the mem-categorization
268 * In the borrow checker, in contrast, type checking is complete and we
269 * know that no errors have occurred, so we simply consult the tcx and we
270 * can be sure that only `Ok` results will occur.
273 fn tcx<'a>(&'a self) -> &'a ty::ctxt;
274 fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t>;
275 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t>;
276 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>>;
277 fn is_method_call(&self, id: ast::NodeId) -> bool;
278 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId>;
279 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow;
282 impl MutabilityCategory {
283 pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
285 MutImmutable => McImmutable,
286 MutMutable => McDeclared
290 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
292 ty::ImmBorrow => McImmutable,
293 ty::UniqueImmBorrow => McImmutable,
294 ty::MutBorrow => McDeclared,
298 pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
299 ptr: PointerKind) -> MutabilityCategory {
304 BorrowedPtr(borrow_kind, _) => {
305 MutabilityCategory::from_borrow_kind(borrow_kind)
311 MutabilityCategory::from_mutbl(m)
316 pub fn inherit(&self) -> MutabilityCategory {
318 McImmutable => McImmutable,
319 McDeclared => McInherited,
320 McInherited => McInherited,
324 pub fn is_mutable(&self) -> bool {
326 McImmutable => false,
332 pub fn is_immutable(&self) -> bool {
335 McDeclared | McInherited => false
339 pub fn to_user_str(&self) -> &'static str {
341 McDeclared | McInherited => "mutable",
342 McImmutable => "immutable",
351 Err(e) => { return Err(e); }
356 impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> {
357 pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
358 MemCategorizationContext { typer: typer }
361 fn tcx(&self) -> &'t ty::ctxt {
365 fn expr_ty(&self, expr: &ast::Expr) -> McResult<ty::t> {
366 self.typer.node_ty(expr.id)
369 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<ty::t> {
370 let unadjusted_ty = if_ok!(self.expr_ty(expr));
371 Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
372 self.typer.adjustments().borrow().find(&expr.id),
373 |method_call| self.typer.node_method_ty(method_call)))
376 fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t> {
377 self.typer.node_ty(id)
380 fn pat_ty(&self, pat: &ast::Pat) -> McResult<ty::t> {
381 self.typer.node_ty(pat.id)
384 pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt> {
385 match self.typer.adjustments().borrow().find(&expr.id) {
388 self.cat_expr_unadjusted(expr)
391 Some(adjustment) => {
393 ty::AutoObject(..) => {
394 // Implicity cast a concrete object to trait object.
395 // Result is an rvalue.
396 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
397 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
400 ty::AutoAddEnv(..) => {
401 // Convert a bare fn to a closure by adding NULL env.
402 // Result is an rvalue.
403 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
404 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
409 autoref: Some(_), ..}) => {
410 // Equivalent to &*expr or something similar.
411 // Result is an rvalue.
412 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
413 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
418 autoref: None, autoderefs: autoderefs}) => {
419 // Equivalent to *expr or something similar.
420 self.cat_expr_autoderefd(expr, autoderefs)
427 pub fn cat_expr_autoderefd(&self,
431 let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
432 for deref in range(1u, autoderefs + 1) {
433 cmt = self.cat_deref(expr, cmt, deref);
438 pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt> {
439 debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
441 let expr_ty = if_ok!(self.expr_ty(expr));
443 ast::ExprUnary(ast::UnDeref, ref e_base) => {
444 let base_cmt = if_ok!(self.cat_expr(&**e_base));
445 Ok(self.cat_deref(expr, base_cmt, 0))
448 ast::ExprField(ref base, f_name, _) => {
449 let base_cmt = if_ok!(self.cat_expr(&**base));
450 Ok(self.cat_field(expr, base_cmt, f_name, expr_ty))
453 ast::ExprIndex(ref base, _) => {
454 if self.typer.is_method_call(expr.id) {
455 return Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty));
458 let base_cmt = if_ok!(self.cat_expr(&**base));
459 Ok(self.cat_index(expr, base_cmt, 0))
462 ast::ExprPath(_) => {
463 let def = self.tcx().def_map.borrow().get_copy(&expr.id);
464 self.cat_def(expr.id, expr.span, expr_ty, def)
467 ast::ExprParen(ref e) => {
471 ast::ExprAddrOf(..) | ast::ExprCall(..) |
472 ast::ExprAssign(..) | ast::ExprAssignOp(..) |
473 ast::ExprFnBlock(..) | ast::ExprProc(..) | ast::ExprRet(..) |
475 ast::ExprMethodCall(..) | ast::ExprCast(..) | ast::ExprVstore(..) |
476 ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
477 ast::ExprBinary(..) | ast::ExprWhile(..) |
478 ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
479 ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
480 ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
481 ast::ExprInlineAsm(..) | ast::ExprBox(..) => {
482 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
485 ast::ExprForLoop(..) => fail!("non-desugared expr_for_loop")
489 pub fn cat_def(&self,
495 debug!("cat_def: id={} expr={} def={:?}",
496 id, expr_ty.repr(self.tcx()), def);
499 def::DefStruct(..) | def::DefVariant(..) => {
500 Ok(self.cat_rvalue_node(id, span, expr_ty))
502 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMod(_) |
503 def::DefForeignMod(_) | def::DefStatic(_, false) |
504 def::DefUse(_) | def::DefTrait(_) | def::DefTy(_) | def::DefPrimTy(_) |
505 def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
506 def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) => {
516 def::DefStatic(_, true) => {
526 def::DefArg(vid, binding_mode) => {
527 // Idea: make this could be rewritten to model by-ref
528 // stuff as `&const` and `&mut`?
530 // m: mutability of the argument
531 let m = match binding_mode {
532 ast::BindByValue(ast::MutMutable) => McDeclared,
544 def::DefUpvar(var_id, _, fn_node_id, _) => {
545 let ty = if_ok!(self.node_ty(fn_node_id));
546 match ty::get(ty).sty {
547 ty::ty_closure(ref closure_ty) => {
548 // Decide whether to use implicit reference or by copy/move
549 // capture for the upvar. This, combined with the onceness,
550 // determines whether the closure can move out of it.
551 let var_is_refd = match (closure_ty.store, closure_ty.onceness) {
552 // Many-shot stack closures can never move out.
553 (ty::RegionTraitStore(..), ast::Many) => true,
554 // 1-shot stack closures can move out.
555 (ty::RegionTraitStore(..), ast::Once) => false,
556 // Heap closures always capture by copy/move, and can
557 // move out if they are once.
558 (ty::UniqTraitStore, _) => false,
562 self.cat_upvar(id, span, var_id, fn_node_id)
564 // FIXME #2152 allow mutation of moved upvars
568 cat:cat_copied_upvar(CopiedUpvar {
570 onceness: closure_ty.onceness}),
577 self.tcx().sess.span_bug(
579 format!("Upvar of non-closure {} - {}",
581 ty.repr(self.tcx())).as_slice());
586 def::DefLocal(vid, binding_mode) |
587 def::DefBinding(vid, binding_mode) => {
588 // by-value/by-ref bindings are local variables
589 let m = match binding_mode {
590 ast::BindByValue(ast::MutMutable) => McDeclared,
609 fn_node_id: ast::NodeId)
612 * Upvars through a closure are in fact indirect
613 * references. That is, when a closure refers to a
614 * variable from a parent stack frame like `x = 10`,
615 * that is equivalent to `*x_ = 10` where `x_` is a
616 * borrowed pointer (`&mut x`) created when the closure
617 * was created and store in the environment. This
618 * equivalence is expose in the mem-categorization.
621 let upvar_id = ty::UpvarId { var_id: var_id,
622 closure_expr_id: fn_node_id };
624 let upvar_borrow = self.typer.upvar_borrow(upvar_id);
626 let var_ty = if_ok!(self.node_ty(var_id));
628 // We can't actually represent the types of all upvars
629 // as user-describable types, since upvars support const
630 // and unique-imm borrows! Therefore, we cheat, and just
631 // give err type. Nobody should be inspecting this type anyhow.
632 let upvar_ty = ty::mk_err();
634 let base_cmt = Rc::new(cmt_ {
637 cat:cat_upvar(upvar_id, upvar_borrow),
642 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
644 let deref_cmt = Rc::new(cmt_ {
647 cat:cat_deref(base_cmt, 0, ptr),
648 mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
655 pub fn cat_rvalue_node(&self,
660 match self.typer.temporary_scope(id) {
662 self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
665 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
670 pub fn cat_rvalue(&self,
673 temp_scope: ty::Region,
674 expr_ty: ty::t) -> cmt {
678 cat:cat_rvalue(temp_scope),
684 pub fn cat_field<N:ast_node>(&self,
693 mutbl: base_cmt.mutbl.inherit(),
694 cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
699 pub fn cat_deref_obj<N:ast_node>(&self, node: &N, base_cmt: cmt) -> cmt {
700 self.cat_deref_common(node, base_cmt, 0, ty::mk_nil())
703 fn cat_deref<N:ast_node>(&self,
708 let method_call = typeck::MethodCall {
710 autoderef: deref_cnt as u32
712 let method_ty = self.typer.node_method_ty(method_call);
714 debug!("cat_deref: method_call={:?} method_ty={}",
715 method_call, method_ty.map(|ty| ty.repr(self.tcx())));
717 let base_cmt = match method_ty {
719 let ref_ty = ty::ty_fn_ret(method_ty);
720 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
724 match ty::deref(base_cmt.ty, true) {
725 Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty),
727 self.tcx().sess.span_bug(
729 format!("Explicit deref of non-derefable type: {}",
730 base_cmt.ty.repr(self.tcx())).as_slice());
735 fn cat_deref_common<N:ast_node>(&self,
741 let (m, cat) = match deref_kind(self.tcx(), base_cmt.ty) {
743 // for unique ptrs, we inherit mutability from the
745 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
746 cat_deref(base_cmt, deref_cnt, ptr))
748 deref_interior(interior) => {
749 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
761 pub fn cat_index<N:ast_node>(&self,
766 //! Creates a cmt for an indexing operation (`[]`); this
767 //! indexing operation may occurs as part of an
768 //! AutoBorrowVec, which when converting a `~[]` to an `&[]`
769 //! effectively takes the address of the 0th element.
771 //! One subtle aspect of indexing that may not be
772 //! immediately obvious: for anything other than a fixed-length
773 //! vector, an operation like `x[y]` actually consists of two
774 //! disjoint (from the point of view of borrowck) operations.
775 //! The first is a deref of `x` to create a pointer `p` that points
776 //! at the first element in the array. The second operation is
777 //! an index which adds `y*sizeof(T)` to `p` to obtain the
778 //! pointer to `x[y]`. `cat_index` will produce a resulting
779 //! cmt containing both this deref and the indexing,
780 //! presuming that `base_cmt` is not of fixed-length type.
782 //! In the event that a deref is needed, the "deref count"
783 //! is taken from the parameter `derefs`. See the comment
784 //! on the def'n of `root_map_key` in borrowck/mod.rs
785 //! for more details about deref counts; the summary is
786 //! that `derefs` should be 0 for an explicit indexing
787 //! operation and N+1 for an indexing that is part of
788 //! an auto-adjustment, where N is the number of autoderefs
789 //! in that adjustment.
792 //! - `elt`: the AST node being indexed
793 //! - `base_cmt`: the cmt of `elt`
794 //! - `derefs`: the deref number to be used for
795 //! the implicit index deref, if any (see above)
797 let element_ty = match ty::index(base_cmt.ty) {
798 Some(ref mt) => mt.ty,
800 self.tcx().sess.span_bug(
802 format!("Explicit index of non-index type `{}`",
803 base_cmt.ty.repr(self.tcx())).as_slice());
807 return match deref_kind(self.tcx(), base_cmt.ty) {
809 // for unique ptrs, we inherit mutability from the
811 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
813 // the deref is explicit in the resulting cmt
814 let deref_cmt = Rc::new(cmt_ {
817 cat:cat_deref(base_cmt.clone(), derefs, ptr),
822 interior(elt, deref_cmt, base_cmt.ty, m.inherit(), element_ty)
825 deref_interior(_) => {
826 // fixed-length vectors have no deref
827 let m = base_cmt.mutbl.inherit();
828 interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty)
832 fn interior<N: ast_node>(elt: &N,
835 mutbl: MutabilityCategory,
836 element_ty: ty::t) -> cmt
841 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
848 pub fn cat_slice_pattern(&self,
850 slice_pat: &ast::Pat)
851 -> McResult<(cmt, ast::Mutability, ty::Region)> {
853 * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
854 * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
856 * - the mutability and region of the slice `Q`
858 * These last two bits of info happen to be things that
862 let slice_ty = if_ok!(self.node_ty(slice_pat.id));
863 let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
866 let cmt_slice = self.cat_index(slice_pat, vec_cmt, 0);
867 return Ok((cmt_slice, slice_mutbl, slice_r));
869 fn vec_slice_info(tcx: &ty::ctxt,
872 -> (ast::Mutability, ty::Region) {
874 * In a pattern like [a, b, ..c], normally `c` has slice type,
875 * but if you have [a, b, ..ref c], then the type of `ref c`
876 * will be `&&[]`, so to extract the slice details we have
877 * to recurse through rptrs.
880 match ty::get(slice_ty).sty {
881 ty::ty_rptr(r, ref mt) => match ty::get(mt.ty).sty {
882 ty::ty_vec(slice_mt, None) => (slice_mt.mutbl, r),
883 _ => vec_slice_info(tcx, pat, mt.ty),
887 tcx.sess.span_bug(pat.span,
888 "type of slice pattern is not a slice");
894 pub fn cat_imm_interior<N:ast_node>(&self,
898 interior: InteriorKind)
903 mutbl: base_cmt.mutbl.inherit(),
904 cat: cat_interior(base_cmt, interior),
909 pub fn cat_downcast<N:ast_node>(&self,
917 mutbl: base_cmt.mutbl.inherit(),
918 cat: cat_downcast(base_cmt),
923 pub fn cat_pattern(&self,
926 op: |&MemCategorizationContext<TYPER>,
930 // Here, `cmt` is the categorization for the value being
931 // matched and pat is the pattern it is being matched against.
933 // In general, the way that this works is that we walk down
934 // the pattern, constructing a cmt that represents the path
935 // that will be taken to reach the value being matched.
937 // When we encounter named bindings, we take the cmt that has
938 // been built up and pass it off to guarantee_valid() so that
939 // we can be sure that the binding will remain valid for the
940 // duration of the arm.
942 // (*2) There is subtlety concerning the correspondence between
943 // pattern ids and types as compared to *expression* ids and
944 // types. This is explained briefly. on the definition of the
945 // type `cmt`, so go off and read what it says there, then
946 // come back and I'll dive into a bit more detail here. :) OK,
949 // In general, the id of the cmt should be the node that
950 // "produces" the value---patterns aren't executable code
951 // exactly, but I consider them to "execute" when they match a
952 // value, and I consider them to produce the value that was
953 // matched. So if you have something like:
960 // In this case, the cmt and the relevant ids would be:
962 // CMT Id Type of Id Type of cmt
965 // ^~~~~~~^ `x` from discr @@int @@int
966 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
967 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
969 // You can see that the types of the id and the cmt are in
970 // sync in the first line, because that id is actually the id
971 // of an expression. But once we get to pattern ids, the types
972 // step out of sync again. So you'll see below that we always
973 // get the type of the *subpattern* and use that.
975 debug!("cat_pattern: id={} pat={} cmt={}",
976 pat.id, pprust::pat_to_str(pat),
977 cmt.repr(self.tcx()));
979 op(self, cmt.clone(), pat);
982 ast::PatWild | ast::PatWildMulti => {
986 ast::PatEnum(_, None) => {
989 ast::PatEnum(_, Some(ref subpats)) => {
990 match self.tcx().def_map.borrow().find(&pat.id) {
991 Some(&def::DefVariant(enum_did, _, _)) => {
995 if ty::enum_is_univariant(self.tcx(), enum_did) {
996 cmt // univariant, no downcast needed
998 self.cat_downcast(pat, cmt.clone(), cmt.ty)
1002 for (i, subpat) in subpats.iter().enumerate() {
1003 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1006 self.cat_imm_interior(
1007 pat, downcast_cmt.clone(), subpat_ty,
1008 InteriorField(PositionalField(i)));
1010 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1013 Some(&def::DefFn(..)) |
1014 Some(&def::DefStruct(..)) => {
1015 for (i, subpat) in subpats.iter().enumerate() {
1016 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1018 self.cat_imm_interior(
1019 pat, cmt.clone(), subpat_ty,
1020 InteriorField(PositionalField(i)));
1021 if_ok!(self.cat_pattern(cmt_field, &**subpat,
1022 |x,y,z| op(x,y,z)));
1025 Some(&def::DefStatic(..)) => {
1026 for subpat in subpats.iter() {
1027 if_ok!(self.cat_pattern(cmt.clone(), &**subpat, |x,y,z| op(x,y,z)));
1031 self.tcx().sess.span_bug(
1033 "enum pattern didn't resolve to enum or struct");
1038 ast::PatIdent(_, _, Some(ref subpat)) => {
1039 if_ok!(self.cat_pattern(cmt, &**subpat, op));
1042 ast::PatIdent(_, _, None) => {
1043 // nullary variant or identifier: ignore
1046 ast::PatStruct(_, ref field_pats, _) => {
1047 // {f1: p1, ..., fN: pN}
1048 for fp in field_pats.iter() {
1049 let field_ty = if_ok!(self.pat_ty(&*fp.pat)); // see (*2)
1050 let cmt_field = self.cat_field(pat, cmt.clone(), fp.ident, field_ty);
1051 if_ok!(self.cat_pattern(cmt_field, &*fp.pat, |x,y,z| op(x,y,z)));
1055 ast::PatTup(ref subpats) => {
1057 for (i, subpat) in subpats.iter().enumerate() {
1058 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1060 self.cat_imm_interior(
1061 pat, cmt.clone(), subpat_ty,
1062 InteriorField(PositionalField(i)));
1063 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1067 ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1069 let subcmt = self.cat_deref(pat, cmt, 0);
1070 if_ok!(self.cat_pattern(subcmt, &**subpat, op));
1073 ast::PatVec(ref before, slice, ref after) => {
1074 let elt_cmt = self.cat_index(pat, cmt, 0);
1075 for before_pat in before.iter() {
1076 if_ok!(self.cat_pattern(elt_cmt.clone(), &**before_pat,
1077 |x,y,z| op(x,y,z)));
1079 for slice_pat in slice.iter() {
1080 let slice_ty = if_ok!(self.pat_ty(&**slice_pat));
1081 let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1082 if_ok!(self.cat_pattern(slice_cmt, &**slice_pat, |x,y,z| op(x,y,z)));
1084 for after_pat in after.iter() {
1085 if_ok!(self.cat_pattern(elt_cmt.clone(), &**after_pat, |x,y,z| op(x,y,z)));
1089 ast::PatLit(_) | ast::PatRange(_, _) => {
1094 self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1101 pub fn cmt_to_str(&self, cmt: &cmt_) -> String {
1103 cat_static_item => {
1104 "static item".to_string()
1106 cat_copied_upvar(_) => {
1107 "captured outer variable in a proc".to_string()
1110 "non-lvalue".to_string()
1113 "local variable".to_string()
1116 "argument".to_string()
1118 cat_deref(ref base, _, pk) => {
1121 "captured outer variable".to_string()
1124 format!("dereference of `{}`-pointer", ptr_sigil(pk))
1128 cat_interior(_, InteriorField(NamedField(_))) => {
1131 cat_interior(_, InteriorField(PositionalField(_))) => {
1132 "anonymous field".to_string()
1134 cat_interior(_, InteriorElement(VecElement)) => {
1135 "vec content".to_string()
1137 cat_interior(_, InteriorElement(StrElement)) => {
1138 "str content".to_string()
1140 cat_interior(_, InteriorElement(OtherElement)) => {
1141 "indexed content".to_string()
1144 "captured outer variable".to_string()
1146 cat_discr(ref cmt, _) => {
1147 self.cmt_to_str(&**cmt)
1149 cat_downcast(ref cmt) => {
1150 self.cmt_to_str(&**cmt)
1156 pub enum InteriorSafety {
1161 pub enum AliasableReason {
1165 AliasableStatic(InteriorSafety),
1166 AliasableStaticMut(InteriorSafety),
1170 pub fn guarantor(&self) -> cmt {
1171 //! Returns `self` after stripping away any owned pointer derefs or
1172 //! interior content. The return value is basically the `cmt` which
1173 //! determines how long the value in `self` remains live.
1178 cat_copied_upvar(..) |
1181 cat_deref(_, _, UnsafePtr(..)) |
1182 cat_deref(_, _, GcPtr(..)) |
1183 cat_deref(_, _, BorrowedPtr(..)) |
1185 Rc::new((*self).clone())
1187 cat_downcast(ref b) |
1188 cat_discr(ref b, _) |
1189 cat_interior(ref b, _) |
1190 cat_deref(ref b, _, OwnedPtr) => {
1196 pub fn freely_aliasable(&self, ctxt: &ty::ctxt) -> Option<AliasableReason> {
1198 * Returns `Some(_)` if this lvalue represents a freely aliasable
1202 // Maybe non-obvious: copied upvars can only be considered
1203 // non-aliasable in once closures, since any other kind can be
1204 // aliased and eventually recused.
1207 cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1208 cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1209 cat_downcast(ref b) |
1210 cat_deref(ref b, _, OwnedPtr) |
1211 cat_interior(ref b, _) |
1212 cat_discr(ref b, _) => {
1213 // Aliasability depends on base cmt
1214 b.freely_aliasable(ctxt)
1217 cat_copied_upvar(CopiedUpvar {onceness: ast::Once, ..}) |
1222 cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1226 cat_copied_upvar(CopiedUpvar {onceness: ast::Many, ..}) => {
1227 Some(AliasableOther)
1230 cat_static_item(..) => {
1231 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1237 if self.mutbl.is_mutable() {
1238 Some(AliasableStaticMut(int_safe))
1240 Some(AliasableStatic(int_safe))
1244 cat_deref(_, _, GcPtr) => {
1245 Some(AliasableManaged)
1248 cat_deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) => {
1249 Some(AliasableBorrowed)
1255 impl Repr for cmt_ {
1256 fn repr(&self, tcx: &ty::ctxt) -> String {
1257 format!("{{{} id:{} m:{:?} ty:{}}}",
1265 impl Repr for categorization {
1266 fn repr(&self, tcx: &ty::ctxt) -> String {
1270 cat_copied_upvar(..) |
1274 format!("{:?}", *self)
1276 cat_deref(ref cmt, derefs, ptr) => {
1277 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1279 cat_interior(ref cmt, interior) => {
1280 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1282 cat_downcast(ref cmt) => {
1283 format!("{}->(enum)", cmt.cat.repr(tcx))
1285 cat_discr(ref cmt, _) => {
1292 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1296 BorrowedPtr(ty::ImmBorrow, _) => "&",
1297 BorrowedPtr(ty::MutBorrow, _) => "&mut",
1298 BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
1303 impl Repr for InteriorKind {
1304 fn repr(&self, _tcx: &ty::ctxt) -> String {
1306 InteriorField(NamedField(fld)) => {
1307 token::get_name(fld).get().to_str()
1309 InteriorField(PositionalField(i)) => format!("#{:?}", i),
1310 InteriorElement(_) => "[]".to_string(),
1315 fn element_kind(t: ty::t) -> ElementKind {
1316 match ty::get(t).sty {
1317 ty::ty_rptr(_, ty::mt{ty:ty, ..}) |
1318 ty::ty_uniq(ty) => match ty::get(ty).sty {
1319 ty::ty_vec(_, None) => VecElement,
1320 ty::ty_str => StrElement,
1323 ty::ty_vec(..) => VecElement,