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.
13 //! The job of the categorization module is to analyze an expression to
14 //! determine what kind of memory is used in evaluating it (for example,
15 //! where dereferences occur and what kind of pointer is dereferenced;
16 //! whether the memory is mutable; etc)
18 //! Categorization effectively transforms all of our expressions into
19 //! expressions of the following forms (the actual enum has many more
20 //! possibilities, naturally, but they are all variants of these base
23 //! E = rvalue // some computed rvalue
24 //! | x // address of a local variable or argument
25 //! | *E // deref of a ptr
26 //! | E.comp // access to an interior component
28 //! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
29 //! address where the result is to be found. If Expr is an lvalue, then this
30 //! is the address of the lvalue. If Expr is an rvalue, this is the address of
31 //! some temporary spot in memory where the result is stored.
33 //! Now, cat_expr() classifies the expression Expr and the address A=ToAddr(Expr)
36 //! - cat: what kind of expression was this? This is a subset of the
37 //! full expression forms which only includes those that we care about
38 //! for the purpose of the analysis.
39 //! - mutbl: mutability of the address A
40 //! - ty: the type of data found at the address A
42 //! The resulting categorization tree differs somewhat from the expressions
43 //! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
44 //! decomposed into two operations: a dereference to reach the array data and
45 //! then an index to jump forward to the relevant item.
47 //! ## By-reference upvars
49 //! One part of the translation which may be non-obvious is that we translate
50 //! closure upvars into the dereference of a borrowed pointer; this more closely
51 //! resembles the runtime translation. So, for example, if we had:
55 //! let inc = || x += y;
57 //! Then when we categorize `x` (*within* the closure) we would yield a
58 //! result of `*x'`, effectively, where `x'` is a `cat_upvar` reference
59 //! tied to `x`. The type of `x'` will be a borrowed pointer.
61 #![allow(non_camel_case_types)]
63 pub use self::PointerKind::*;
64 pub use self::InteriorKind::*;
65 pub use self::FieldName::*;
66 pub use self::ElementKind::*;
67 pub use self::MutabilityCategory::*;
68 pub use self::InteriorSafety::*;
69 pub use self::AliasableReason::*;
70 pub use self::Note::*;
71 pub use self::deref_kind::*;
72 pub use self::categorization::*;
76 use middle::ty::{mod, Ty};
77 use util::nodemap::{NodeMap};
78 use util::ppaux::{Repr};
80 use syntax::ast::{MutImmutable, MutMutable};
83 use syntax::codemap::Span;
84 use syntax::print::pprust;
85 use syntax::parse::token;
87 use std::cell::RefCell;
90 #[deriving(Clone, PartialEq, Show)]
91 pub enum categorization<'tcx> {
92 cat_rvalue(ty::Region), // temporary val, argument is its scope
94 cat_upvar(Upvar), // upvar referenced by closure env
95 cat_local(ast::NodeId), // local variable
96 cat_deref(cmt<'tcx>, uint, PointerKind), // deref of a ptr
97 cat_interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
98 cat_downcast(cmt<'tcx>, ast::DefId), // selects a particular enum variant (*1)
100 // (*1) downcast is only required if the enum has more than one variant
103 // Represents any kind of upvar
104 #[deriving(Clone, Copy, PartialEq, Show)]
107 // Unboxed closure kinds are used even for old-style closures for simplicity
108 pub kind: ty::UnboxedClosureKind,
109 // Is this from an unboxed closure? Used only for diagnostics.
113 // different kinds of pointers:
114 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
115 pub enum PointerKind {
117 BorrowedPtr(ty::BorrowKind, ty::Region),
118 Implicit(ty::BorrowKind, ty::Region), // Implicit deref of a borrowed ptr.
119 UnsafePtr(ast::Mutability)
122 // We use the term "interior" to mean "something reachable from the
123 // base without a pointer dereference", e.g. a field
124 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
125 pub enum InteriorKind {
126 InteriorField(FieldName),
127 InteriorElement(ElementKind),
130 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
132 NamedField(ast::Name),
133 PositionalField(uint)
136 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
137 pub enum ElementKind {
142 #[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
143 pub enum MutabilityCategory {
144 McImmutable, // Immutable.
145 McDeclared, // Directly declared as mutable.
146 McInherited, // Inherited from the fact that owner is mutable.
149 // A note about the provenance of a `cmt`. This is used for
150 // special-case handling of upvars such as mutability inference.
151 // Upvar categorization can generate a variable number of nested
152 // derefs. The note allows detecting them without deep pattern
153 // matching on the categorization.
154 #[deriving(Clone, Copy, PartialEq, Show)]
156 NoteClosureEnv(ty::UpvarId), // Deref through closure env
157 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
158 NoteNone // Nothing special
161 // `cmt`: "Category, Mutability, and Type".
163 // a complete categorization of a value indicating where it originated
164 // and how it is located, as well as the mutability of the memory in
165 // which the value is stored.
167 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
168 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
169 // always the `id` of the node producing the type; in an expression
170 // like `*x`, the type of this deref node is the deref'd type (`T`),
171 // but in a pattern like `@x`, the `@x` pattern is again a
172 // dereference, but its type is the type *before* the dereference
173 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
174 // fashion. For more details, see the method `cat_pattern`
175 #[deriving(Clone, PartialEq, Show)]
176 pub struct cmt_<'tcx> {
177 pub id: ast::NodeId, // id of expr/pat producing this value
178 pub span: Span, // span of same expr/pat
179 pub cat: categorization<'tcx>, // categorization of expr
180 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
181 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
182 pub note: Note, // Note about the provenance of this cmt
185 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
187 // We pun on *T to mean both actual deref of a ptr as well
188 // as accessing of components:
190 pub enum deref_kind {
191 deref_ptr(PointerKind),
192 deref_interior(InteriorKind),
195 // Categorizes a derefable type. Note that we include vectors and strings as
196 // derefable (we model an index as the combination of a deref and then a
197 // pointer adjustment).
198 pub fn deref_kind(t: Ty) -> McResult<deref_kind> {
201 ty::ty_closure(box ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
202 Ok(deref_ptr(Unique))
205 ty::ty_rptr(r, mt) => {
206 let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
207 Ok(deref_ptr(BorrowedPtr(kind, *r)))
210 ty::ty_closure(box ty::ClosureTy {
211 store: ty::RegionTraitStore(r, _),
214 Ok(deref_ptr(BorrowedPtr(ty::ImmBorrow, r)))
217 ty::ty_ptr(ref mt) => {
218 Ok(deref_ptr(UnsafePtr(mt.mutbl)))
222 ty::ty_struct(..) => { // newtype
223 Ok(deref_interior(InteriorField(PositionalField(0))))
226 ty::ty_vec(_, _) | ty::ty_str => {
227 Ok(deref_interior(InteriorElement(element_kind(t))))
235 fn id(&self) -> ast::NodeId;
236 fn span(&self) -> Span;
239 impl ast_node for ast::Expr {
240 fn id(&self) -> ast::NodeId { self.id }
241 fn span(&self) -> Span { self.span }
244 impl ast_node for ast::Pat {
245 fn id(&self) -> ast::NodeId { self.id }
246 fn span(&self) -> Span { self.span }
249 pub struct MemCategorizationContext<'t,TYPER:'t> {
253 impl<'t,TYPER:'t> Copy for MemCategorizationContext<'t,TYPER> {}
255 pub type McResult<T> = Result<T, ()>;
257 /// The `Typer` trait provides the interface for the mem-categorization
258 /// module to the results of the type check. It can be used to query
259 /// the type assigned to an expression node, to inquire after adjustments,
262 /// This interface is needed because mem-categorization is used from
263 /// two places: `regionck` and `borrowck`. `regionck` executes before
264 /// type inference is complete, and hence derives types and so on from
265 /// intermediate tables. This also implies that type errors can occur,
266 /// and hence `node_ty()` and friends return a `Result` type -- any
267 /// error will propagate back up through the mem-categorization
270 /// In the borrow checker, in contrast, type checking is complete and we
271 /// know that no errors have occurred, so we simply consult the tcx and we
272 /// can be sure that only `Ok` results will occur.
273 pub trait Typer<'tcx> : ty::UnboxedClosureTyper<'tcx> {
274 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
275 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>>;
276 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>>;
277 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool;
278 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>>;
279 fn node_method_origin(&self, method_call: ty::MethodCall)
280 -> Option<ty::MethodOrigin<'tcx>>;
281 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>>;
282 fn is_method_call(&self, id: ast::NodeId) -> bool;
283 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent>;
284 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow>;
285 fn capture_mode(&self, closure_expr_id: ast::NodeId)
286 -> ast::CaptureClause;
289 impl MutabilityCategory {
290 pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
292 MutImmutable => McImmutable,
293 MutMutable => McDeclared
297 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
299 ty::ImmBorrow => McImmutable,
300 ty::UniqueImmBorrow => McImmutable,
301 ty::MutBorrow => McDeclared,
305 pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
306 ptr: PointerKind) -> MutabilityCategory {
311 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
312 MutabilityCategory::from_borrow_kind(borrow_kind)
315 MutabilityCategory::from_mutbl(m)
320 fn from_local(tcx: &ty::ctxt, id: ast::NodeId) -> MutabilityCategory {
321 match tcx.map.get(id) {
322 ast_map::NodeLocal(p) | ast_map::NodeArg(p) => match p.node {
323 ast::PatIdent(bind_mode, _, _) => {
324 if bind_mode == ast::BindByValue(ast::MutMutable) {
330 _ => tcx.sess.span_bug(p.span, "expected identifier pattern")
332 _ => tcx.sess.span_bug(tcx.map.span(id), "expected identifier pattern")
336 pub fn inherit(&self) -> MutabilityCategory {
338 McImmutable => McImmutable,
339 McDeclared => McInherited,
340 McInherited => McInherited,
344 pub fn is_mutable(&self) -> bool {
346 McImmutable => false,
352 pub fn is_immutable(&self) -> bool {
355 McDeclared | McInherited => false
359 pub fn to_user_str(&self) -> &'static str {
361 McDeclared | McInherited => "mutable",
362 McImmutable => "immutable",
367 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
368 pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
369 MemCategorizationContext { typer: typer }
372 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
376 fn expr_ty(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
377 self.typer.node_ty(expr.id)
380 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
381 let unadjusted_ty = try!(self.expr_ty(expr));
382 Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
383 self.typer.adjustments().borrow().get(&expr.id),
384 |method_call| self.typer.node_method_ty(method_call)))
387 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
388 self.typer.node_ty(id)
391 fn pat_ty(&self, pat: &ast::Pat) -> McResult<Ty<'tcx>> {
392 let tcx = self.typer.tcx();
393 let base_ty = try!(self.typer.node_ty(pat.id));
394 // FIXME (Issue #18207): This code detects whether we are
395 // looking at a `ref x`, and if so, figures out what the type
396 // *being borrowed* is. But ideally we would put in a more
397 // fundamental fix to this conflated use of the node id.
398 let ret_ty = match pat.node {
399 ast::PatIdent(ast::BindByRef(_), _, _) => {
400 // a bind-by-ref means that the base_ty will be the type of the ident itself,
401 // but what we want here is the type of the underlying value being borrowed.
402 // So peel off one-level, turning the &T into T.
403 match ty::deref(base_ty, false) {
405 None => { return Err(()); }
410 debug!("pat_ty(pat={}) base_ty={} ret_ty={}",
411 pat.repr(tcx), base_ty.repr(tcx), ret_ty.repr(tcx));
415 pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
416 match self.typer.adjustments().borrow().get(&expr.id) {
419 self.cat_expr_unadjusted(expr)
422 Some(adjustment) => {
424 ty::AdjustAddEnv(..) | ty::AdjustReifyFnPointer(..) => {
425 debug!("cat_expr(AdjustAddEnv|AdjustReifyFnPointer): {}",
426 expr.repr(self.tcx()));
427 // Convert a bare fn to a closure by adding NULL env.
428 // Result is an rvalue.
429 let expr_ty = try!(self.expr_ty_adjusted(expr));
430 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
435 autoref: Some(_), ..}) => {
436 debug!("cat_expr(AdjustDerefRef): {}",
437 expr.repr(self.tcx()));
438 // Equivalent to &*expr or something similar.
439 // Result is an rvalue.
440 let expr_ty = try!(self.expr_ty_adjusted(expr));
441 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
446 autoref: None, autoderefs}) => {
447 // Equivalent to *expr or something similar.
448 self.cat_expr_autoderefd(expr, autoderefs)
455 pub fn cat_expr_autoderefd(&self,
458 -> McResult<cmt<'tcx>> {
459 let mut cmt = try!(self.cat_expr_unadjusted(expr));
460 debug!("cat_expr_autoderefd: autoderefs={}, cmt={}",
462 cmt.repr(self.tcx()));
463 for deref in range(1u, autoderefs + 1) {
464 cmt = try!(self.cat_deref(expr, cmt, deref, false));
469 pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
470 debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
472 let expr_ty = try!(self.expr_ty(expr));
474 ast::ExprUnary(ast::UnDeref, ref e_base) => {
475 let base_cmt = try!(self.cat_expr(&**e_base));
476 self.cat_deref(expr, base_cmt, 0, false)
479 ast::ExprField(ref base, f_name) => {
480 let base_cmt = try!(self.cat_expr(&**base));
481 debug!("cat_expr(cat_field): id={} expr={} base={}",
483 expr.repr(self.tcx()),
484 base_cmt.repr(self.tcx()));
485 Ok(self.cat_field(expr, base_cmt, f_name.node.name, expr_ty))
488 ast::ExprTupField(ref base, idx) => {
489 let base_cmt = try!(self.cat_expr(&**base));
490 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
493 ast::ExprIndex(ref base, ref idx) => {
495 ast::ExprRange(..) => {
496 // Slicing syntax special case (KILLME).
497 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
500 let method_call = ty::MethodCall::expr(expr.id());
501 match self.typer.node_method_ty(method_call) {
503 // If this is an index implemented by a method call, then it will
504 // include an implicit deref of the result.
505 let ret_ty = ty::ty_fn_ret(method_ty).unwrap();
507 self.cat_rvalue_node(expr.id(),
512 self.cat_index(expr, try!(self.cat_expr(&**base)))
519 ast::ExprPath(_) => {
520 let def = (*self.tcx().def_map.borrow())[expr.id];
521 self.cat_def(expr.id, expr.span, expr_ty, def)
524 ast::ExprParen(ref e) => {
528 ast::ExprAddrOf(..) | ast::ExprCall(..) |
529 ast::ExprAssign(..) | ast::ExprAssignOp(..) |
530 ast::ExprClosure(..) | ast::ExprRet(..) |
531 ast::ExprUnary(..) | ast::ExprRange(..) |
532 ast::ExprMethodCall(..) | ast::ExprCast(..) |
533 ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
534 ast::ExprBinary(..) | ast::ExprWhile(..) |
535 ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
536 ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
537 ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
538 ast::ExprInlineAsm(..) | ast::ExprBox(..) |
539 ast::ExprForLoop(..) => {
540 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
543 ast::ExprIfLet(..) => {
544 self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
546 ast::ExprWhileLet(..) => {
547 self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
552 pub fn cat_def(&self,
557 -> McResult<cmt<'tcx>> {
558 debug!("cat_def: id={} expr={} def={}",
559 id, expr_ty.repr(self.tcx()), def);
562 def::DefStruct(..) | def::DefVariant(..) | def::DefFn(..) |
563 def::DefStaticMethod(..) | def::DefConst(..) => {
564 Ok(self.cat_rvalue_node(id, span, expr_ty))
566 def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
567 def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
568 def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
569 def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) |
570 def::DefAssociatedTy(..) | def::DefAssociatedPath(..)=> {
581 def::DefStatic(_, mutbl) => {
586 mutbl: if mutbl { McDeclared } else { McImmutable},
592 def::DefUpvar(var_id, fn_node_id, _) => {
593 let ty = try!(self.node_ty(fn_node_id));
595 ty::ty_closure(ref closure_ty) => {
596 // Translate old closure type info into unboxed
597 // closure kind/capture mode
598 let (mode, kind) = match (closure_ty.store, closure_ty.onceness) {
600 (ty::RegionTraitStore(..), ast::Many) => {
601 (ast::CaptureByRef, ty::FnMutUnboxedClosureKind)
603 // proc or once closure
605 (ast::CaptureByValue, ty::FnOnceUnboxedClosureKind)
607 // There should be no such old closure type
608 (ty::UniqTraitStore, ast::Many) => {
609 self.tcx().sess.span_bug(span, "Impossible closure type");
612 self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, false)
614 ty::ty_unboxed_closure(closure_id, _, _) => {
615 let kind = self.typer.unboxed_closure_kind(closure_id);
616 let mode = self.typer.capture_mode(fn_node_id);
617 self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, true)
620 self.tcx().sess.span_bug(
622 format!("Upvar of non-closure {} - {}",
624 ty.repr(self.tcx()))[]);
629 def::DefLocal(vid) => {
634 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
642 // Categorize an upvar, complete with invisible derefs of closure
643 // environment and upvar reference as appropriate.
648 fn_node_id: ast::NodeId,
649 kind: ty::UnboxedClosureKind,
650 mode: ast::CaptureClause,
652 -> McResult<cmt<'tcx>> {
653 // An upvar can have up to 3 components. The base is a
654 // `cat_upvar`. Next, we add a deref through the implicit
655 // environment pointer with an anonymous free region 'env and
656 // appropriate borrow kind for closure kinds that take self by
657 // reference. Finally, if the upvar was captured
658 // by-reference, we add a deref through that reference. The
659 // region of this reference is an inference variable 'up that
660 // was previously generated and recorded in the upvar borrow
661 // map. The borrow kind bk is inferred by based on how the
664 // This results in the following table for concrete closure
668 // ---------------+----------------------+-------------------------------
669 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
670 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
671 // FnOnce | copied | upvar -> &'up bk
672 // old stack | N/A | upvar -> &'env mut -> &'up bk
673 // old proc/once | copied | N/A
674 let var_ty = try!(self.node_ty(var_id));
676 let upvar_id = ty::UpvarId { var_id: var_id,
677 closure_expr_id: fn_node_id };
679 // Mutability of original variable itself
680 let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
682 // Construct information about env pointer dereference, if any
683 let mutbl = match kind {
684 ty::FnOnceUnboxedClosureKind => None, // None, env is by-value
685 ty::FnMutUnboxedClosureKind => match mode { // Depends on capture type
686 ast::CaptureByValue => Some(var_mutbl), // Mutable if the original var is
687 ast::CaptureByRef => Some(McDeclared) // Mutable regardless
689 ty::FnUnboxedClosureKind => Some(McImmutable) // Never mutable
691 let env_info = mutbl.map(|env_mutbl| {
692 // Look up the node ID of the closure body so we can construct
693 // a free region within it
695 let fn_expr = match self.tcx().map.find(fn_node_id) {
696 Some(ast_map::NodeExpr(e)) => e,
701 ast::ExprClosure(_, _, _, ref body) => body.id,
706 // Region of environment pointer
707 let env_region = ty::ReFree(ty::FreeRegion {
708 scope: region::CodeExtent::from_node_id(fn_body_id),
709 bound_region: ty::BrEnv
712 let env_ptr = BorrowedPtr(if env_mutbl.is_mutable() {
721 // First, switch by capture mode
723 ast::CaptureByValue => {
724 let mut base = cmt_ {
727 cat: cat_upvar(Upvar {
730 is_unboxed: is_unboxed
738 Some((env_mutbl, env_ptr)) => {
739 // We need to add the env deref. This means
740 // that the above is actually immutable and
741 // has a ref type. However, nothing should
742 // actually look at the type, so we can get
743 // away with stuffing a `ty_err` in there
744 // instead of bothering to construct a proper
746 base.mutbl = McImmutable;
747 base.ty = self.tcx().types.err;
751 cat: cat_deref(Rc::new(base), 0, env_ptr),
754 note: NoteClosureEnv(upvar_id)
757 None => Rc::new(base)
760 ast::CaptureByRef => {
761 // The type here is actually a ref (or ref of a ref),
762 // but we can again get away with not constructing one
763 // properly since it will never be used.
764 let mut base = cmt_ {
767 cat: cat_upvar(Upvar {
770 is_unboxed: is_unboxed
773 ty: self.tcx().types.err,
778 Some((env_mutbl, env_ptr)) => {
782 cat: cat_deref(Rc::new(base), 0, env_ptr),
784 ty: self.tcx().types.err,
785 note: NoteClosureEnv(upvar_id)
791 // Look up upvar borrow so we can get its region
792 let upvar_borrow = self.typer.upvar_borrow(upvar_id).unwrap();
793 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
798 cat: cat_deref(Rc::new(base), 0, ptr),
799 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
801 note: NoteUpvarRef(upvar_id)
807 pub fn cat_rvalue_node(&self,
812 match self.typer.temporary_scope(id) {
815 ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
816 _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
820 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
825 pub fn cat_rvalue(&self,
828 temp_scope: ty::Region,
829 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
833 cat:cat_rvalue(temp_scope),
840 pub fn cat_field<N:ast_node>(&self,
849 mutbl: base_cmt.mutbl.inherit(),
850 cat: cat_interior(base_cmt, InteriorField(NamedField(f_name))),
856 pub fn cat_tup_field<N:ast_node>(&self,
865 mutbl: base_cmt.mutbl.inherit(),
866 cat: cat_interior(base_cmt, InteriorField(PositionalField(f_idx))),
872 fn cat_deref<N:ast_node>(&self,
877 -> McResult<cmt<'tcx>> {
878 let adjustment = match self.typer.adjustments().borrow().get(&node.id()) {
879 Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject,
880 _ if deref_cnt != 0 => ty::AutoDeref(deref_cnt),
881 _ => ty::NoAdjustment
884 let method_call = ty::MethodCall {
886 adjustment: adjustment
888 let method_ty = self.typer.node_method_ty(method_call);
890 debug!("cat_deref: method_call={} method_ty={}",
891 method_call, method_ty.map(|ty| ty.repr(self.tcx())));
893 let base_cmt = match method_ty {
895 let ref_ty = ty::ty_fn_ret(method_ty).unwrap();
896 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
900 let base_cmt_ty = base_cmt.ty;
901 match ty::deref(base_cmt_ty, true) {
902 Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit),
904 debug!("Explicit deref of non-derefable type: {}",
905 base_cmt_ty.repr(self.tcx()));
911 fn cat_deref_common<N:ast_node>(&self,
917 -> McResult<cmt<'tcx>>
919 let (m, cat) = match try!(deref_kind(base_cmt.ty)) {
921 let ptr = if implicit {
923 BorrowedPtr(bk, r) => Implicit(bk, r),
924 _ => self.tcx().sess.span_bug(node.span(),
925 "Implicit deref of non-borrowed pointer")
930 // for unique ptrs, we inherit mutability from the
932 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
933 cat_deref(base_cmt, deref_cnt, ptr))
935 deref_interior(interior) => {
936 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
949 pub fn cat_index<N:ast_node>(&self,
951 mut base_cmt: cmt<'tcx>)
952 -> McResult<cmt<'tcx>> {
953 //! Creates a cmt for an indexing operation (`[]`).
955 //! One subtle aspect of indexing that may not be
956 //! immediately obvious: for anything other than a fixed-length
957 //! vector, an operation like `x[y]` actually consists of two
958 //! disjoint (from the point of view of borrowck) operations.
959 //! The first is a deref of `x` to create a pointer `p` that points
960 //! at the first element in the array. The second operation is
961 //! an index which adds `y*sizeof(T)` to `p` to obtain the
962 //! pointer to `x[y]`. `cat_index` will produce a resulting
963 //! cmt containing both this deref and the indexing,
964 //! presuming that `base_cmt` is not of fixed-length type.
967 //! - `elt`: the AST node being indexed
968 //! - `base_cmt`: the cmt of `elt`
970 let method_call = ty::MethodCall::expr(elt.id());
971 let method_ty = self.typer.node_method_ty(method_call);
973 let element_ty = match method_ty {
975 let ref_ty = ty::ty_fn_ret(method_ty).unwrap();
976 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
977 ty::ty_fn_args(method_ty)[0]
980 match ty::array_element_ty(self.tcx(), base_cmt.ty) {
989 let m = base_cmt.mutbl.inherit();
990 return Ok(interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty));
992 fn interior<'tcx, N: ast_node>(elt: &N,
995 mutbl: MutabilityCategory,
996 element_ty: Ty<'tcx>) -> cmt<'tcx>
1001 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
1009 // Takes either a vec or a reference to a vec and returns the cmt for the
1011 fn deref_vec<N:ast_node>(&self,
1013 base_cmt: cmt<'tcx>)
1014 -> McResult<cmt<'tcx>>
1016 match try!(deref_kind(base_cmt.ty)) {
1018 // for unique ptrs, we inherit mutability from the
1019 // owning reference.
1020 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
1022 // the deref is explicit in the resulting cmt
1026 cat:cat_deref(base_cmt.clone(), 0, ptr),
1028 ty: match ty::deref(base_cmt.ty, false) {
1030 None => self.tcx().sess.bug("Found non-derefable type")
1036 deref_interior(_) => {
1042 /// Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is the cmt for `P`, `slice_pat` is
1043 /// the pattern `Q`, returns:
1046 /// * the mutability and region of the slice `Q`
1048 /// These last two bits of info happen to be things that borrowck needs.
1049 pub fn cat_slice_pattern(&self,
1051 slice_pat: &ast::Pat)
1052 -> McResult<(cmt<'tcx>, ast::Mutability, ty::Region)> {
1053 let slice_ty = try!(self.node_ty(slice_pat.id));
1054 let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
1057 let cmt_slice = try!(self.cat_index(slice_pat, try!(self.deref_vec(slice_pat, vec_cmt))));
1058 return Ok((cmt_slice, slice_mutbl, slice_r));
1060 /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
1061 /// ..ref c], then the type of `ref c` will be `&&[]`, so to extract the slice details we
1062 /// have to recurse through rptrs.
1063 fn vec_slice_info(tcx: &ty::ctxt,
1066 -> (ast::Mutability, ty::Region) {
1067 match slice_ty.sty {
1068 ty::ty_rptr(r, ref mt) => match mt.ty.sty {
1069 ty::ty_vec(_, None) => (mt.mutbl, *r),
1070 _ => vec_slice_info(tcx, pat, mt.ty),
1074 tcx.sess.span_bug(pat.span,
1075 "type of slice pattern is not a slice");
1081 pub fn cat_imm_interior<N:ast_node>(&self,
1083 base_cmt: cmt<'tcx>,
1084 interior_ty: Ty<'tcx>,
1085 interior: InteriorKind)
1090 mutbl: base_cmt.mutbl.inherit(),
1091 cat: cat_interior(base_cmt, interior),
1097 pub fn cat_downcast<N:ast_node>(&self,
1099 base_cmt: cmt<'tcx>,
1100 downcast_ty: Ty<'tcx>,
1101 variant_did: ast::DefId)
1106 mutbl: base_cmt.mutbl.inherit(),
1107 cat: cat_downcast(base_cmt, variant_did),
1113 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, mut op: F) -> McResult<()>
1114 where F: FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1116 self.cat_pattern_(cmt, pat, &mut op)
1119 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1120 fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, op: &mut F)
1122 where F : FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1124 // Here, `cmt` is the categorization for the value being
1125 // matched and pat is the pattern it is being matched against.
1127 // In general, the way that this works is that we walk down
1128 // the pattern, constructing a cmt that represents the path
1129 // that will be taken to reach the value being matched.
1131 // When we encounter named bindings, we take the cmt that has
1132 // been built up and pass it off to guarantee_valid() so that
1133 // we can be sure that the binding will remain valid for the
1134 // duration of the arm.
1136 // (*2) There is subtlety concerning the correspondence between
1137 // pattern ids and types as compared to *expression* ids and
1138 // types. This is explained briefly. on the definition of the
1139 // type `cmt`, so go off and read what it says there, then
1140 // come back and I'll dive into a bit more detail here. :) OK,
1143 // In general, the id of the cmt should be the node that
1144 // "produces" the value---patterns aren't executable code
1145 // exactly, but I consider them to "execute" when they match a
1146 // value, and I consider them to produce the value that was
1147 // matched. So if you have something like:
1154 // In this case, the cmt and the relevant ids would be:
1156 // CMT Id Type of Id Type of cmt
1159 // ^~~~~~~^ `x` from discr @@int @@int
1160 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1161 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1163 // You can see that the types of the id and the cmt are in
1164 // sync in the first line, because that id is actually the id
1165 // of an expression. But once we get to pattern ids, the types
1166 // step out of sync again. So you'll see below that we always
1167 // get the type of the *subpattern* and use that.
1169 debug!("cat_pattern: id={} pat={} cmt={}",
1170 pat.id, pprust::pat_to_string(pat),
1171 cmt.repr(self.tcx()));
1173 (*op)(self, cmt.clone(), pat);
1175 let def_map = self.tcx().def_map.borrow();
1176 let opt_def = def_map.get(&pat.id);
1178 // Note: This goes up here (rather than within the PatEnum arm
1179 // alone) because struct patterns can refer to struct types or
1180 // to struct variants within enums.
1181 let cmt = match opt_def {
1182 Some(&def::DefVariant(enum_did, variant_did, _))
1183 // univariant enums do not need downcasts
1184 if !ty::enum_is_univariant(self.tcx(), enum_did) => {
1185 self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1191 ast::PatWild(_) => {
1195 ast::PatEnum(_, None) => {
1198 ast::PatEnum(_, Some(ref subpats)) => {
1200 Some(&def::DefVariant(..)) => {
1202 for (i, subpat) in subpats.iter().enumerate() {
1203 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1206 self.cat_imm_interior(
1207 pat, cmt.clone(), subpat_ty,
1208 InteriorField(PositionalField(i)));
1210 try!(self.cat_pattern_(subcmt, &**subpat, op));
1213 Some(&def::DefStruct(..)) => {
1214 for (i, subpat) in subpats.iter().enumerate() {
1215 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1217 self.cat_imm_interior(
1218 pat, cmt.clone(), subpat_ty,
1219 InteriorField(PositionalField(i)));
1220 try!(self.cat_pattern_(cmt_field, &**subpat, op));
1223 Some(&def::DefConst(..)) => {
1224 for subpat in subpats.iter() {
1225 try!(self.cat_pattern_(cmt.clone(), &**subpat, op));
1229 self.tcx().sess.span_bug(
1231 "enum pattern didn't resolve to enum or struct");
1236 ast::PatIdent(_, _, Some(ref subpat)) => {
1237 try!(self.cat_pattern_(cmt, &**subpat, op));
1240 ast::PatIdent(_, _, None) => {
1241 // nullary variant or identifier: ignore
1244 ast::PatStruct(_, ref field_pats, _) => {
1245 // {f1: p1, ..., fN: pN}
1246 for fp in field_pats.iter() {
1247 let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2)
1248 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.ident.name, field_ty);
1249 try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op));
1253 ast::PatTup(ref subpats) => {
1255 for (i, subpat) in subpats.iter().enumerate() {
1256 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1258 self.cat_imm_interior(
1259 pat, cmt.clone(), subpat_ty,
1260 InteriorField(PositionalField(i)));
1261 try!(self.cat_pattern_(subcmt, &**subpat, op));
1265 ast::PatBox(ref subpat) | ast::PatRegion(ref subpat) => {
1267 let subcmt = try!(self.cat_deref(pat, cmt, 0, false));
1268 try!(self.cat_pattern_(subcmt, &**subpat, op));
1271 ast::PatVec(ref before, ref slice, ref after) => {
1272 let elt_cmt = try!(self.cat_index(pat, try!(self.deref_vec(pat, cmt))));
1273 for before_pat in before.iter() {
1274 try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
1276 for slice_pat in slice.iter() {
1277 let slice_ty = try!(self.pat_ty(&**slice_pat));
1278 let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1279 try!(self.cat_pattern_(slice_cmt, &**slice_pat, op));
1281 for after_pat in after.iter() {
1282 try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op));
1286 ast::PatLit(_) | ast::PatRange(_, _) => {
1291 self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1300 pub enum InteriorSafety {
1306 pub enum AliasableReason {
1308 AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1310 AliasableStatic(InteriorSafety),
1311 AliasableStaticMut(InteriorSafety),
1314 impl<'tcx> cmt_<'tcx> {
1315 pub fn guarantor(&self) -> cmt<'tcx> {
1316 //! Returns `self` after stripping away any owned pointer derefs or
1317 //! interior content. The return value is basically the `cmt` which
1318 //! determines how long the value in `self` remains live.
1324 cat_deref(_, _, UnsafePtr(..)) |
1325 cat_deref(_, _, BorrowedPtr(..)) |
1326 cat_deref(_, _, Implicit(..)) |
1328 Rc::new((*self).clone())
1330 cat_downcast(ref b, _) |
1331 cat_interior(ref b, _) |
1332 cat_deref(ref b, _, Unique) => {
1338 /// Returns `Some(_)` if this lvalue represents a freely aliasable pointer type.
1339 pub fn freely_aliasable(&self, ctxt: &ty::ctxt<'tcx>)
1340 -> Option<AliasableReason> {
1341 // Maybe non-obvious: copied upvars can only be considered
1342 // non-aliasable in once closures, since any other kind can be
1343 // aliased and eventually recused.
1346 cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1347 cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1348 cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1349 cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1350 cat_downcast(ref b, _) |
1351 cat_deref(ref b, _, Unique) |
1352 cat_interior(ref b, _) => {
1353 // Aliasability depends on base cmt
1354 b.freely_aliasable(ctxt)
1360 cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1364 cat_static_item(..) => {
1365 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1371 if self.mutbl.is_mutable() {
1372 Some(AliasableStaticMut(int_safe))
1374 Some(AliasableStatic(int_safe))
1378 cat_deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1379 cat_deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1381 cat_upvar(Upvar{ id, .. }) => Some(AliasableClosure(id.closure_expr_id)),
1382 _ => Some(AliasableBorrowed)
1388 // Digs down through one or two layers of deref and grabs the cmt
1389 // for the upvar if a note indicates there is one.
1390 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1392 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1393 Some(match self.cat {
1394 cat_deref(ref inner, _, _) => {
1396 cat_deref(ref inner, _, _) => inner.clone(),
1397 cat_upvar(..) => inner.clone(),
1409 pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
1410 fn upvar_to_string(upvar: &Upvar, is_copy: bool) -> String {
1411 if upvar.is_unboxed {
1412 let kind = match upvar.kind {
1413 ty::FnUnboxedClosureKind => "Fn",
1414 ty::FnMutUnboxedClosureKind => "FnMut",
1415 ty::FnOnceUnboxedClosureKind => "FnOnce"
1417 format!("captured outer variable in an `{}` closure", kind)
1419 (match (upvar.kind, is_copy) {
1420 (ty::FnOnceUnboxedClosureKind, true) => "captured outer variable in a proc",
1421 _ => "captured outer variable"
1427 cat_static_item => {
1428 "static item".to_string()
1431 "non-lvalue".to_string()
1434 match tcx.map.find(vid) {
1435 Some(ast_map::NodeArg(_)) => {
1436 "argument".to_string()
1438 _ => "local variable".to_string()
1441 cat_deref(_, _, pk) => {
1442 let upvar = self.upvar();
1443 match upvar.as_ref().map(|i| &i.cat) {
1444 Some(&cat_upvar(ref var)) => {
1445 upvar_to_string(var, false)
1447 Some(_) => unreachable!(),
1451 "dereference (dereference is implicit, due to indexing)".to_string()
1453 Unique => format!("dereference of `{}`", ptr_sigil(pk)),
1454 _ => format!("dereference of `{}`-pointer", ptr_sigil(pk))
1459 cat_interior(_, InteriorField(NamedField(_))) => {
1462 cat_interior(_, InteriorField(PositionalField(_))) => {
1463 "anonymous field".to_string()
1465 cat_interior(_, InteriorElement(VecElement)) => {
1466 "vec content".to_string()
1468 cat_interior(_, InteriorElement(OtherElement)) => {
1469 "indexed content".to_string()
1471 cat_upvar(ref var) => {
1472 upvar_to_string(var, true)
1474 cat_downcast(ref cmt, _) => {
1475 cmt.descriptive_string(tcx)
1481 impl<'tcx> Repr<'tcx> for cmt_<'tcx> {
1482 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1483 format!("{{{} id:{} m:{} ty:{}}}",
1491 impl<'tcx> Repr<'tcx> for categorization<'tcx> {
1492 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1498 format!("{}", *self)
1500 cat_deref(ref cmt, derefs, ptr) => {
1501 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs)
1503 cat_interior(ref cmt, interior) => {
1504 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1506 cat_downcast(ref cmt, _) => {
1507 format!("{}->(enum)", cmt.cat.repr(tcx))
1513 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1516 BorrowedPtr(ty::ImmBorrow, _) |
1517 Implicit(ty::ImmBorrow, _) => "&",
1518 BorrowedPtr(ty::MutBorrow, _) |
1519 Implicit(ty::MutBorrow, _) => "&mut",
1520 BorrowedPtr(ty::UniqueImmBorrow, _) |
1521 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1526 impl<'tcx> Repr<'tcx> for InteriorKind {
1527 fn repr(&self, _tcx: &ty::ctxt) -> String {
1529 InteriorField(NamedField(fld)) => {
1530 token::get_name(fld).get().to_string()
1532 InteriorField(PositionalField(i)) => format!("#{}", i),
1533 InteriorElement(_) => "[]".to_string(),
1538 fn element_kind(t: Ty) -> ElementKind {
1540 ty::ty_rptr(_, ty::mt{ty, ..}) |
1541 ty::ty_uniq(ty) => match ty.sty {
1542 ty::ty_vec(_, None) => VecElement,
1545 ty::ty_vec(..) => VecElement,