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)]
69 use util::nodemap::{DefIdMap, NodeMap};
70 use util::ppaux::{ty_to_string, Repr};
72 use syntax::ast::{MutImmutable, MutMutable};
74 use syntax::codemap::Span;
75 use syntax::print::pprust;
76 use syntax::parse::token;
78 use std::cell::RefCell;
81 #[deriving(Clone, PartialEq)]
82 pub enum categorization {
83 cat_rvalue(ty::Region), // temporary val, argument is its scope
85 cat_copied_upvar(CopiedUpvar), // upvar copied into proc env
86 cat_upvar(ty::UpvarId, ty::UpvarBorrow), // by ref upvar from stack closure
87 cat_local(ast::NodeId), // local variable
88 cat_arg(ast::NodeId), // formal argument
89 cat_deref(cmt, uint, PointerKind), // deref of a ptr
90 cat_interior(cmt, InteriorKind), // something interior: field, tuple, etc
91 cat_downcast(cmt), // selects a particular enum variant (*1)
92 cat_discr(cmt, ast::NodeId), // match discriminant (see preserve())
94 // (*1) downcast is only required if the enum has more than one variant
97 #[deriving(Clone, PartialEq)]
98 pub struct CopiedUpvar {
99 pub upvar_id: ast::NodeId,
100 pub onceness: ast::Onceness,
101 pub capturing_proc: ast::NodeId,
104 // different kinds of pointers:
105 #[deriving(Clone, PartialEq, Eq, Hash)]
106 pub enum PointerKind {
109 BorrowedPtr(ty::BorrowKind, ty::Region),
110 Implicit(ty::BorrowKind, ty::Region), // Implicit deref of a borrowed ptr.
111 UnsafePtr(ast::Mutability)
114 // We use the term "interior" to mean "something reachable from the
115 // base without a pointer dereference", e.g. a field
116 #[deriving(Clone, PartialEq, Eq, Hash)]
117 pub enum InteriorKind {
118 InteriorField(FieldName),
119 InteriorElement(ElementKind),
122 #[deriving(Clone, PartialEq, Eq, Hash)]
124 NamedField(ast::Name),
125 PositionalField(uint)
128 #[deriving(Clone, PartialEq, Eq, Hash)]
129 pub enum ElementKind {
134 #[deriving(Clone, PartialEq, Eq, Hash, Show)]
135 pub enum MutabilityCategory {
136 McImmutable, // Immutable.
137 McDeclared, // Directly declared as mutable.
138 McInherited, // Inherited from the fact that owner is mutable.
141 // `cmt`: "Category, Mutability, and Type".
143 // a complete categorization of a value indicating where it originated
144 // and how it is located, as well as the mutability of the memory in
145 // which the value is stored.
147 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
148 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
149 // always the `id` of the node producing the type; in an expression
150 // like `*x`, the type of this deref node is the deref'd type (`T`),
151 // but in a pattern like `@x`, the `@x` pattern is again a
152 // dereference, but its type is the type *before* the dereference
153 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
154 // fashion. For more details, see the method `cat_pattern`
155 #[deriving(Clone, PartialEq)]
157 pub id: ast::NodeId, // id of expr/pat producing this value
158 pub span: Span, // span of same expr/pat
159 pub cat: categorization, // categorization of expr
160 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
161 pub ty: ty::t // type of the expr (*see WARNING above*)
164 pub type cmt = Rc<cmt_>;
166 // We pun on *T to mean both actual deref of a ptr as well
167 // as accessing of components:
168 pub enum deref_kind {
169 deref_ptr(PointerKind),
170 deref_interior(InteriorKind),
173 // Categorizes a derefable type. Note that we include vectors and strings as
174 // derefable (we model an index as the combination of a deref and then a
175 // pointer adjustment).
176 pub fn opt_deref_kind(t: ty::t) -> Option<deref_kind> {
177 match ty::get(t).sty {
179 ty::ty_closure(box ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
180 Some(deref_ptr(OwnedPtr))
183 ty::ty_rptr(r, mt) => {
184 let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
185 Some(deref_ptr(BorrowedPtr(kind, r)))
188 ty::ty_closure(box ty::ClosureTy {
189 store: ty::RegionTraitStore(r, _),
192 Some(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
196 Some(deref_ptr(GcPtr))
199 ty::ty_ptr(ref mt) => {
200 Some(deref_ptr(UnsafePtr(mt.mutbl)))
204 ty::ty_struct(..) => { // newtype
205 Some(deref_interior(InteriorField(PositionalField(0))))
208 ty::ty_vec(_, _) | ty::ty_str => {
209 Some(deref_interior(InteriorElement(element_kind(t))))
216 pub fn deref_kind(tcx: &ty::ctxt, t: ty::t) -> deref_kind {
217 debug!("deref_kind {}", ty_to_string(tcx, t));
218 match opt_deref_kind(t) {
222 format!("deref_kind() invoked on non-derefable type {}",
223 ty_to_string(tcx, t)).as_slice());
229 fn id(&self) -> ast::NodeId;
230 fn span(&self) -> Span;
233 impl ast_node for ast::Expr {
234 fn id(&self) -> ast::NodeId { self.id }
235 fn span(&self) -> Span { self.span }
238 impl ast_node for ast::Pat {
239 fn id(&self) -> ast::NodeId { self.id }
240 fn span(&self) -> Span { self.span }
243 pub struct MemCategorizationContext<'t,TYPER:'t> {
247 pub type McResult<T> = Result<T, ()>;
250 * The `Typer` trait provides the interface for the mem-categorization
251 * module to the results of the type check. It can be used to query
252 * the type assigned to an expression node, to inquire after adjustments,
255 * This interface is needed because mem-categorization is used from
256 * two places: `regionck` and `borrowck`. `regionck` executes before
257 * type inference is complete, and hence derives types and so on from
258 * intermediate tables. This also implies that type errors can occur,
259 * and hence `node_ty()` and friends return a `Result` type -- any
260 * error will propagate back up through the mem-categorization
263 * In the borrow checker, in contrast, type checking is complete and we
264 * know that no errors have occurred, so we simply consult the tcx and we
265 * can be sure that only `Ok` results will occur.
267 pub trait Typer<'tcx> {
268 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
269 fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t>;
270 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t>;
271 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>>;
272 fn is_method_call(&self, id: ast::NodeId) -> bool;
273 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId>;
274 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow;
275 fn capture_mode(&self, closure_expr_id: ast::NodeId)
276 -> freevars::CaptureMode;
277 fn unboxed_closures<'a>(&'a self)
278 -> &'a RefCell<DefIdMap<ty::UnboxedClosure>>;
281 impl MutabilityCategory {
282 pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
284 MutImmutable => McImmutable,
285 MutMutable => McDeclared
289 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
291 ty::ImmBorrow => McImmutable,
292 ty::UniqueImmBorrow => McImmutable,
293 ty::MutBorrow => McDeclared,
297 pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
298 ptr: PointerKind) -> MutabilityCategory {
303 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
304 MutabilityCategory::from_borrow_kind(borrow_kind)
310 MutabilityCategory::from_mutbl(m)
315 fn from_def(def: &def::Def) -> MutabilityCategory {
317 def::DefFn(..) | def::DefStaticMethod(..) | def::DefSelfTy(..) |
318 def::DefMod(..) | def::DefForeignMod(..) | def::DefVariant(..) |
319 def::DefTy(..) | def::DefTrait(..) | def::DefPrimTy(..) |
320 def::DefTyParam(..) | def::DefUse(..) | def::DefStruct(..) |
321 def::DefTyParamBinder(..) | def::DefRegion(..) | def::DefLabel(..) |
322 def::DefMethod(..) => fail!("no MutabilityCategory for def: {}", *def),
324 def::DefStatic(_, false) => McImmutable,
325 def::DefStatic(_, true) => McDeclared,
327 def::DefArg(_, binding_mode) |
328 def::DefBinding(_, binding_mode) |
329 def::DefLocal(_, binding_mode) => match binding_mode {
330 ast::BindByValue(ast::MutMutable) => McDeclared,
334 def::DefUpvar(_, def, _, _) => MutabilityCategory::from_def(&*def)
338 pub fn inherit(&self) -> MutabilityCategory {
340 McImmutable => McImmutable,
341 McDeclared => McInherited,
342 McInherited => McInherited,
346 pub fn is_mutable(&self) -> bool {
348 McImmutable => false,
354 pub fn is_immutable(&self) -> bool {
357 McDeclared | McInherited => false
361 pub fn to_user_str(&self) -> &'static str {
363 McDeclared | McInherited => "mutable",
364 McImmutable => "immutable",
373 Err(e) => { return Err(e); }
378 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
379 pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
380 MemCategorizationContext { typer: typer }
383 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
387 fn expr_ty(&self, expr: &ast::Expr) -> McResult<ty::t> {
388 self.typer.node_ty(expr.id)
391 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<ty::t> {
392 let unadjusted_ty = if_ok!(self.expr_ty(expr));
393 Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
394 self.typer.adjustments().borrow().find(&expr.id),
395 |method_call| self.typer.node_method_ty(method_call)))
398 fn node_ty(&self, id: ast::NodeId) -> McResult<ty::t> {
399 self.typer.node_ty(id)
402 fn pat_ty(&self, pat: &ast::Pat) -> McResult<ty::t> {
403 self.typer.node_ty(pat.id)
406 pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt> {
407 match self.typer.adjustments().borrow().find(&expr.id) {
410 self.cat_expr_unadjusted(expr)
413 Some(adjustment) => {
415 ty::AutoAddEnv(..) => {
416 // Convert a bare fn to a closure by adding NULL env.
417 // Result is an rvalue.
418 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
419 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
424 autoref: Some(_), ..}) => {
425 // Equivalent to &*expr or something similar.
426 // Result is an rvalue.
427 let expr_ty = if_ok!(self.expr_ty_adjusted(expr));
428 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
433 autoref: None, autoderefs: autoderefs}) => {
434 // Equivalent to *expr or something similar.
435 self.cat_expr_autoderefd(expr, autoderefs)
442 pub fn cat_expr_autoderefd(&self,
446 let mut cmt = if_ok!(self.cat_expr_unadjusted(expr));
447 for deref in range(1u, autoderefs + 1) {
448 cmt = self.cat_deref(expr, cmt, deref, false);
453 pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt> {
454 debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
456 let expr_ty = if_ok!(self.expr_ty(expr));
458 ast::ExprUnary(ast::UnDeref, ref e_base) => {
459 let base_cmt = if_ok!(self.cat_expr(&**e_base));
460 Ok(self.cat_deref(expr, base_cmt, 0, false))
463 ast::ExprField(ref base, f_name, _) => {
464 let base_cmt = if_ok!(self.cat_expr(&**base));
465 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
468 ast::ExprIndex(ref base, _) => {
469 let method_call = typeck::MethodCall::expr(expr.id());
470 match self.typer.node_method_ty(method_call) {
472 // If this is an index implemented by a method call, then it will
473 // include an implicit deref of the result.
474 let ret_ty = ty::ty_fn_ret(method_ty);
475 Ok(self.cat_deref(expr,
476 self.cat_rvalue_node(expr.id(),
481 let base_cmt = if_ok!(self.cat_expr(&**base));
482 Ok(self.cat_index(expr, base_cmt))
487 ast::ExprPath(_) => {
488 let def = self.tcx().def_map.borrow().get_copy(&expr.id);
489 self.cat_def(expr.id, expr.span, expr_ty, def)
492 ast::ExprParen(ref e) => {
496 ast::ExprAddrOf(..) | ast::ExprCall(..) |
497 ast::ExprAssign(..) | ast::ExprAssignOp(..) |
498 ast::ExprFnBlock(..) | ast::ExprProc(..) |
499 ast::ExprUnboxedFn(..) | ast::ExprRet(..) |
501 ast::ExprMethodCall(..) | ast::ExprCast(..) |
502 ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
503 ast::ExprBinary(..) | ast::ExprWhile(..) |
504 ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
505 ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
506 ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
507 ast::ExprInlineAsm(..) | ast::ExprBox(..) |
508 ast::ExprForLoop(..) => {
509 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
514 pub fn cat_def(&self,
520 debug!("cat_def: id={} expr={} def={:?}",
521 id, expr_ty.repr(self.tcx()), def);
524 def::DefStruct(..) | def::DefVariant(..) | def::DefFn(..) |
525 def::DefStaticMethod(..) => {
526 Ok(self.cat_rvalue_node(id, span, expr_ty))
528 def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
529 def::DefTrait(_) | def::DefTy(_) | def::DefPrimTy(_) |
530 def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
531 def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) => {
541 def::DefStatic(_, _) => {
546 mutbl: MutabilityCategory::from_def(&def),
551 def::DefArg(vid, _) => {
552 // Idea: make this could be rewritten to model by-ref
553 // stuff as `&const` and `&mut`?
559 mutbl: MutabilityCategory::from_def(&def),
564 def::DefUpvar(var_id, _, fn_node_id, _) => {
565 let ty = if_ok!(self.node_ty(fn_node_id));
566 match ty::get(ty).sty {
567 ty::ty_closure(ref closure_ty) => {
568 // Decide whether to use implicit reference or by copy/move
569 // capture for the upvar. This, combined with the onceness,
570 // determines whether the closure can move out of it.
571 let var_is_refd = match (closure_ty.store, closure_ty.onceness) {
572 // Many-shot stack closures can never move out.
573 (ty::RegionTraitStore(..), ast::Many) => true,
574 // 1-shot stack closures can move out.
575 (ty::RegionTraitStore(..), ast::Once) => false,
576 // Heap closures always capture by copy/move, and can
577 // move out if they are once.
578 (ty::UniqTraitStore, _) => false,
582 self.cat_upvar(id, span, var_id, fn_node_id)
587 cat:cat_copied_upvar(CopiedUpvar {
589 onceness: closure_ty.onceness,
590 capturing_proc: fn_node_id,
592 mutbl: MutabilityCategory::from_def(&def),
597 ty::ty_unboxed_closure(closure_id, _) => {
598 let unboxed_closures = self.typer
601 let kind = unboxed_closures.get(&closure_id).kind;
602 let onceness = match kind {
603 ty::FnUnboxedClosureKind |
604 ty::FnMutUnboxedClosureKind => ast::Many,
605 ty::FnOnceUnboxedClosureKind => ast::Once,
610 cat: cat_copied_upvar(CopiedUpvar {
613 capturing_proc: fn_node_id,
615 mutbl: MutabilityCategory::from_def(&def),
620 self.tcx().sess.span_bug(
622 format!("Upvar of non-closure {} - {}",
624 ty.repr(self.tcx())).as_slice());
629 def::DefLocal(vid, _) |
630 def::DefBinding(vid, _) => {
631 // by-value/by-ref bindings are local variables
636 mutbl: MutabilityCategory::from_def(&def),
647 fn_node_id: ast::NodeId)
650 * Upvars through a closure are in fact indirect
651 * references. That is, when a closure refers to a
652 * variable from a parent stack frame like `x = 10`,
653 * that is equivalent to `*x_ = 10` where `x_` is a
654 * borrowed pointer (`&mut x`) created when the closure
655 * was created and store in the environment. This
656 * equivalence is expose in the mem-categorization.
659 let upvar_id = ty::UpvarId { var_id: var_id,
660 closure_expr_id: fn_node_id };
662 let upvar_borrow = self.typer.upvar_borrow(upvar_id);
664 let var_ty = if_ok!(self.node_ty(var_id));
666 // We can't actually represent the types of all upvars
667 // as user-describable types, since upvars support const
668 // and unique-imm borrows! Therefore, we cheat, and just
669 // give err type. Nobody should be inspecting this type anyhow.
670 let upvar_ty = ty::mk_err();
672 let base_cmt = Rc::new(cmt_ {
675 cat:cat_upvar(upvar_id, upvar_borrow),
680 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
682 let deref_cmt = Rc::new(cmt_ {
685 cat:cat_deref(base_cmt, 0, ptr),
686 mutbl:MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
693 pub fn cat_rvalue_node(&self,
698 match self.typer.temporary_scope(id) {
700 match ty::get(expr_ty).sty {
701 ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
702 _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
706 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
711 pub fn cat_rvalue(&self,
714 temp_scope: ty::Region,
715 expr_ty: ty::t) -> cmt {
719 cat:cat_rvalue(temp_scope),
725 pub fn cat_field<N:ast_node>(&self,
734 mutbl: base_cmt.mutbl.inherit(),
735 cat: cat_interior(base_cmt, InteriorField(NamedField(f_name.name))),
740 pub fn cat_deref_obj<N:ast_node>(&self, node: &N, base_cmt: cmt) -> cmt {
741 self.cat_deref_common(node, base_cmt, 0, ty::mk_nil(), false)
744 fn cat_deref<N:ast_node>(&self,
750 let adjustment = match self.typer.adjustments().borrow().find(&node.id()) {
751 Some(adj) if ty::adjust_is_object(adj) => typeck::AutoObject,
752 _ if deref_cnt != 0 => typeck::AutoDeref(deref_cnt),
753 _ => typeck::NoAdjustment
756 let method_call = typeck::MethodCall {
758 adjustment: adjustment
760 let method_ty = self.typer.node_method_ty(method_call);
762 debug!("cat_deref: method_call={:?} method_ty={}",
763 method_call, method_ty.map(|ty| ty.repr(self.tcx())));
765 let base_cmt = match method_ty {
767 let ref_ty = ty::ty_fn_ret(method_ty);
768 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
772 match ty::deref(base_cmt.ty, true) {
773 Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit),
775 self.tcx().sess.span_bug(
777 format!("Explicit deref of non-derefable type: {}",
778 base_cmt.ty.repr(self.tcx())).as_slice());
783 fn cat_deref_common<N:ast_node>(&self,
790 let (m, cat) = match deref_kind(self.tcx(), base_cmt.ty) {
792 let ptr = if implicit {
794 BorrowedPtr(bk, r) => Implicit(bk, r),
795 _ => self.tcx().sess.span_bug(node.span(),
796 "Implicit deref of non-borrowed pointer")
801 // for unique ptrs, we inherit mutability from the
803 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
804 cat_deref(base_cmt, deref_cnt, ptr))
806 deref_interior(interior) => {
807 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
819 pub fn cat_index<N:ast_node>(&self,
823 //! Creates a cmt for an indexing operation (`[]`).
825 //! One subtle aspect of indexing that may not be
826 //! immediately obvious: for anything other than a fixed-length
827 //! vector, an operation like `x[y]` actually consists of two
828 //! disjoint (from the point of view of borrowck) operations.
829 //! The first is a deref of `x` to create a pointer `p` that points
830 //! at the first element in the array. The second operation is
831 //! an index which adds `y*sizeof(T)` to `p` to obtain the
832 //! pointer to `x[y]`. `cat_index` will produce a resulting
833 //! cmt containing both this deref and the indexing,
834 //! presuming that `base_cmt` is not of fixed-length type.
837 //! - `elt`: the AST node being indexed
838 //! - `base_cmt`: the cmt of `elt`
840 let method_call = typeck::MethodCall::expr(elt.id());
841 let method_ty = self.typer.node_method_ty(method_call);
843 let element_ty = match method_ty {
845 let ref_ty = ty::ty_fn_ret(method_ty);
846 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
847 *ty::ty_fn_args(method_ty).get(0)
850 match ty::array_element_ty(base_cmt.ty) {
853 self.tcx().sess.span_bug(
855 format!("Explicit index of non-index type `{}`",
856 base_cmt.ty.repr(self.tcx())).as_slice());
862 let m = base_cmt.mutbl.inherit();
863 return interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty);
865 fn interior<N: ast_node>(elt: &N,
868 mutbl: MutabilityCategory,
869 element_ty: ty::t) -> cmt
874 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
881 // Takes either a vec or a reference to a vec and returns the cmt for the
883 fn deref_vec<N:ast_node>(&self,
887 match deref_kind(self.tcx(), base_cmt.ty) {
889 // for unique ptrs, we inherit mutability from the
891 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
893 // the deref is explicit in the resulting cmt
897 cat:cat_deref(base_cmt.clone(), 0, ptr),
899 ty: match ty::deref(base_cmt.ty, false) {
901 None => self.tcx().sess.bug("Found non-derefable type")
906 deref_interior(_) => {
912 pub fn cat_slice_pattern(&self,
914 slice_pat: &ast::Pat)
915 -> McResult<(cmt, ast::Mutability, ty::Region)> {
917 * Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is
918 * the cmt for `P`, `slice_pat` is the pattern `Q`, returns:
920 * - the mutability and region of the slice `Q`
922 * These last two bits of info happen to be things that
926 let slice_ty = if_ok!(self.node_ty(slice_pat.id));
927 let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
930 let cmt_slice = self.cat_index(slice_pat, self.deref_vec(slice_pat, vec_cmt));
931 return Ok((cmt_slice, slice_mutbl, slice_r));
933 fn vec_slice_info(tcx: &ty::ctxt,
936 -> (ast::Mutability, ty::Region) {
938 * In a pattern like [a, b, ..c], normally `c` has slice type,
939 * but if you have [a, b, ..ref c], then the type of `ref c`
940 * will be `&&[]`, so to extract the slice details we have
941 * to recurse through rptrs.
944 match ty::get(slice_ty).sty {
945 ty::ty_rptr(r, ref mt) => match ty::get(mt.ty).sty {
946 ty::ty_vec(_, None) => (mt.mutbl, r),
947 _ => vec_slice_info(tcx, pat, mt.ty),
951 tcx.sess.span_bug(pat.span,
952 "type of slice pattern is not a slice");
958 pub fn cat_imm_interior<N:ast_node>(&self,
962 interior: InteriorKind)
967 mutbl: base_cmt.mutbl.inherit(),
968 cat: cat_interior(base_cmt, interior),
973 pub fn cat_downcast<N:ast_node>(&self,
981 mutbl: base_cmt.mutbl.inherit(),
982 cat: cat_downcast(base_cmt),
987 pub fn cat_pattern(&self,
990 op: |&MemCategorizationContext<TYPER>,
994 // Here, `cmt` is the categorization for the value being
995 // matched and pat is the pattern it is being matched against.
997 // In general, the way that this works is that we walk down
998 // the pattern, constructing a cmt that represents the path
999 // that will be taken to reach the value being matched.
1001 // When we encounter named bindings, we take the cmt that has
1002 // been built up and pass it off to guarantee_valid() so that
1003 // we can be sure that the binding will remain valid for the
1004 // duration of the arm.
1006 // (*2) There is subtlety concerning the correspondence between
1007 // pattern ids and types as compared to *expression* ids and
1008 // types. This is explained briefly. on the definition of the
1009 // type `cmt`, so go off and read what it says there, then
1010 // come back and I'll dive into a bit more detail here. :) OK,
1013 // In general, the id of the cmt should be the node that
1014 // "produces" the value---patterns aren't executable code
1015 // exactly, but I consider them to "execute" when they match a
1016 // value, and I consider them to produce the value that was
1017 // matched. So if you have something like:
1024 // In this case, the cmt and the relevant ids would be:
1026 // CMT Id Type of Id Type of cmt
1029 // ^~~~~~~^ `x` from discr @@int @@int
1030 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1031 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1033 // You can see that the types of the id and the cmt are in
1034 // sync in the first line, because that id is actually the id
1035 // of an expression. But once we get to pattern ids, the types
1036 // step out of sync again. So you'll see below that we always
1037 // get the type of the *subpattern* and use that.
1039 debug!("cat_pattern: id={} pat={} cmt={}",
1040 pat.id, pprust::pat_to_string(pat),
1041 cmt.repr(self.tcx()));
1043 op(self, cmt.clone(), pat);
1046 ast::PatWild(_) => {
1050 ast::PatEnum(_, None) => {
1053 ast::PatEnum(_, Some(ref subpats)) => {
1054 match self.tcx().def_map.borrow().find(&pat.id) {
1055 Some(&def::DefVariant(enum_did, _, _)) => {
1058 let downcast_cmt = {
1059 if ty::enum_is_univariant(self.tcx(), enum_did) {
1060 cmt // univariant, no downcast needed
1062 self.cat_downcast(pat, cmt.clone(), cmt.ty)
1066 for (i, subpat) in subpats.iter().enumerate() {
1067 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1070 self.cat_imm_interior(
1071 pat, downcast_cmt.clone(), subpat_ty,
1072 InteriorField(PositionalField(i)));
1074 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1077 Some(&def::DefFn(..)) |
1078 Some(&def::DefStruct(..)) => {
1079 for (i, subpat) in subpats.iter().enumerate() {
1080 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1082 self.cat_imm_interior(
1083 pat, cmt.clone(), subpat_ty,
1084 InteriorField(PositionalField(i)));
1085 if_ok!(self.cat_pattern(cmt_field, &**subpat,
1086 |x,y,z| op(x,y,z)));
1089 Some(&def::DefStatic(..)) => {
1090 for subpat in subpats.iter() {
1091 if_ok!(self.cat_pattern(cmt.clone(), &**subpat, |x,y,z| op(x,y,z)));
1095 self.tcx().sess.span_bug(
1097 "enum pattern didn't resolve to enum or struct");
1102 ast::PatIdent(_, _, Some(ref subpat)) => {
1103 if_ok!(self.cat_pattern(cmt, &**subpat, op));
1106 ast::PatIdent(_, _, None) => {
1107 // nullary variant or identifier: ignore
1110 ast::PatStruct(_, ref field_pats, _) => {
1111 // {f1: p1, ..., fN: pN}
1112 for fp in field_pats.iter() {
1113 let field_ty = if_ok!(self.pat_ty(&*fp.pat)); // see (*2)
1114 let cmt_field = self.cat_field(pat, cmt.clone(), fp.ident, field_ty);
1115 if_ok!(self.cat_pattern(cmt_field, &*fp.pat, |x,y,z| op(x,y,z)));
1119 ast::PatTup(ref subpats) => {
1121 for (i, subpat) in subpats.iter().enumerate() {
1122 let subpat_ty = if_ok!(self.pat_ty(&**subpat)); // see (*2)
1124 self.cat_imm_interior(
1125 pat, cmt.clone(), subpat_ty,
1126 InteriorField(PositionalField(i)));
1127 if_ok!(self.cat_pattern(subcmt, &**subpat, |x,y,z| op(x,y,z)));
1131 ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1133 let subcmt = self.cat_deref(pat, cmt, 0, false);
1134 if_ok!(self.cat_pattern(subcmt, &**subpat, op));
1137 ast::PatVec(ref before, slice, ref after) => {
1138 let elt_cmt = self.cat_index(pat, self.deref_vec(pat, cmt));
1139 for before_pat in before.iter() {
1140 if_ok!(self.cat_pattern(elt_cmt.clone(), &**before_pat,
1141 |x,y,z| op(x,y,z)));
1143 for slice_pat in slice.iter() {
1144 let slice_ty = if_ok!(self.pat_ty(&**slice_pat));
1145 let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1146 if_ok!(self.cat_pattern(slice_cmt, &**slice_pat, |x,y,z| op(x,y,z)));
1148 for after_pat in after.iter() {
1149 if_ok!(self.cat_pattern(elt_cmt.clone(), &**after_pat, |x,y,z| op(x,y,z)));
1153 ast::PatLit(_) | ast::PatRange(_, _) => {
1158 self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1165 pub fn cmt_to_string(&self, cmt: &cmt_) -> String {
1167 cat_static_item => {
1168 "static item".to_string()
1170 cat_copied_upvar(_) => {
1171 "captured outer variable in a proc".to_string()
1174 "non-lvalue".to_string()
1177 "local variable".to_string()
1180 "argument".to_string()
1182 cat_deref(ref base, _, pk) => {
1185 "captured outer variable".to_string()
1190 "dereference (dereference is implicit, due to indexing)".to_string()
1192 OwnedPtr | GcPtr => format!("dereference of `{}`", ptr_sigil(pk)),
1193 _ => format!("dereference of `{}`-pointer", ptr_sigil(pk))
1198 cat_interior(_, InteriorField(NamedField(_))) => {
1201 cat_interior(_, InteriorField(PositionalField(_))) => {
1202 "anonymous field".to_string()
1204 cat_interior(_, InteriorElement(VecElement)) => {
1205 "vec content".to_string()
1207 cat_interior(_, InteriorElement(OtherElement)) => {
1208 "indexed content".to_string()
1211 "captured outer variable".to_string()
1213 cat_discr(ref cmt, _) => {
1214 self.cmt_to_string(&**cmt)
1216 cat_downcast(ref cmt) => {
1217 self.cmt_to_string(&**cmt)
1223 pub enum InteriorSafety {
1228 pub enum AliasableReason {
1232 AliasableStatic(InteriorSafety),
1233 AliasableStaticMut(InteriorSafety),
1237 pub fn guarantor(&self) -> cmt {
1238 //! Returns `self` after stripping away any owned pointer derefs or
1239 //! interior content. The return value is basically the `cmt` which
1240 //! determines how long the value in `self` remains live.
1245 cat_copied_upvar(..) |
1248 cat_deref(_, _, UnsafePtr(..)) |
1249 cat_deref(_, _, GcPtr(..)) |
1250 cat_deref(_, _, BorrowedPtr(..)) |
1251 cat_deref(_, _, Implicit(..)) |
1253 Rc::new((*self).clone())
1255 cat_downcast(ref b) |
1256 cat_discr(ref b, _) |
1257 cat_interior(ref b, _) |
1258 cat_deref(ref b, _, OwnedPtr) => {
1264 pub fn freely_aliasable(&self, ctxt: &ty::ctxt) -> Option<AliasableReason> {
1266 * Returns `Some(_)` if this lvalue represents a freely aliasable
1270 // Maybe non-obvious: copied upvars can only be considered
1271 // non-aliasable in once closures, since any other kind can be
1272 // aliased and eventually recused.
1275 cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1276 cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1277 cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1278 cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1279 cat_downcast(ref b) |
1280 cat_deref(ref b, _, OwnedPtr) |
1281 cat_interior(ref b, _) |
1282 cat_discr(ref b, _) => {
1283 // Aliasability depends on base cmt
1284 b.freely_aliasable(ctxt)
1287 cat_copied_upvar(CopiedUpvar {onceness: ast::Once, ..}) |
1292 cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1296 cat_copied_upvar(CopiedUpvar {onceness: ast::Many, ..}) => {
1297 Some(AliasableOther)
1300 cat_static_item(..) => {
1301 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1307 if self.mutbl.is_mutable() {
1308 Some(AliasableStaticMut(int_safe))
1310 Some(AliasableStatic(int_safe))
1314 cat_deref(_, _, GcPtr) => {
1315 Some(AliasableManaged)
1318 cat_deref(_, _, BorrowedPtr(ty::ImmBorrow, _)) |
1319 cat_deref(_, _, Implicit(ty::ImmBorrow, _)) => {
1320 Some(AliasableBorrowed)
1326 impl Repr for cmt_ {
1327 fn repr(&self, tcx: &ty::ctxt) -> String {
1328 format!("{{{} id:{} m:{:?} ty:{}}}",
1336 impl Repr for categorization {
1337 fn repr(&self, tcx: &ty::ctxt) -> String {
1341 cat_copied_upvar(..) |
1345 format!("{:?}", *self)
1347 cat_deref(ref cmt, derefs, ptr) => {
1348 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1350 cat_interior(ref cmt, interior) => {
1351 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1353 cat_downcast(ref cmt) => {
1354 format!("{}->(enum)", cmt.cat.repr(tcx))
1356 cat_discr(ref cmt, _) => {
1363 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1367 BorrowedPtr(ty::ImmBorrow, _) |
1368 Implicit(ty::ImmBorrow, _) => "&",
1369 BorrowedPtr(ty::MutBorrow, _) |
1370 Implicit(ty::MutBorrow, _) => "&mut",
1371 BorrowedPtr(ty::UniqueImmBorrow, _) |
1372 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1377 impl Repr for InteriorKind {
1378 fn repr(&self, _tcx: &ty::ctxt) -> String {
1380 InteriorField(NamedField(fld)) => {
1381 token::get_name(fld).get().to_string()
1383 InteriorField(PositionalField(i)) => format!("#{:?}", i),
1384 InteriorElement(_) => "[]".to_string(),
1389 fn element_kind(t: ty::t) -> ElementKind {
1390 match ty::get(t).sty {
1391 ty::ty_rptr(_, ty::mt{ty:ty, ..}) |
1392 ty::ty_uniq(ty) => match ty::get(ty).sty {
1393 ty::ty_vec(_, None) => VecElement,
1396 ty::ty_vec(..) => VecElement,