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::{self, Ty};
77 use util::nodemap::{NodeMap};
78 use util::ppaux::{Repr, UserString};
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 #[derive(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 #[derive(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 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
115 pub enum PointerKind {
120 BorrowedPtr(ty::BorrowKind, ty::Region),
123 UnsafePtr(ast::Mutability),
125 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
126 Implicit(ty::BorrowKind, ty::Region),
129 // We use the term "interior" to mean "something reachable from the
130 // base without a pointer dereference", e.g. a field
131 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
132 pub enum InteriorKind {
133 InteriorField(FieldName),
134 InteriorElement(ElementKind),
137 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
139 NamedField(ast::Name),
140 PositionalField(uint)
143 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
144 pub enum ElementKind {
149 #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
150 pub enum MutabilityCategory {
151 McImmutable, // Immutable.
152 McDeclared, // Directly declared as mutable.
153 McInherited, // Inherited from the fact that owner is mutable.
156 // A note about the provenance of a `cmt`. This is used for
157 // special-case handling of upvars such as mutability inference.
158 // Upvar categorization can generate a variable number of nested
159 // derefs. The note allows detecting them without deep pattern
160 // matching on the categorization.
161 #[derive(Clone, Copy, PartialEq, Show)]
163 NoteClosureEnv(ty::UpvarId), // Deref through closure env
164 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
165 NoteNone // Nothing special
168 // `cmt`: "Category, Mutability, and Type".
170 // a complete categorization of a value indicating where it originated
171 // and how it is located, as well as the mutability of the memory in
172 // which the value is stored.
174 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
175 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
176 // always the `id` of the node producing the type; in an expression
177 // like `*x`, the type of this deref node is the deref'd type (`T`),
178 // but in a pattern like `@x`, the `@x` pattern is again a
179 // dereference, but its type is the type *before* the dereference
180 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
181 // fashion. For more details, see the method `cat_pattern`
182 #[derive(Clone, PartialEq, Show)]
183 pub struct cmt_<'tcx> {
184 pub id: ast::NodeId, // id of expr/pat producing this value
185 pub span: Span, // span of same expr/pat
186 pub cat: categorization<'tcx>, // categorization of expr
187 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
188 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
189 pub note: Note, // Note about the provenance of this cmt
192 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
194 // We pun on *T to mean both actual deref of a ptr as well
195 // as accessing of components:
197 pub enum deref_kind {
198 deref_ptr(PointerKind),
199 deref_interior(InteriorKind),
202 // Categorizes a derefable type. Note that we include vectors and strings as
203 // derefable (we model an index as the combination of a deref and then a
204 // pointer adjustment).
205 pub fn deref_kind(t: Ty) -> McResult<deref_kind> {
208 Ok(deref_ptr(Unique))
211 ty::ty_rptr(r, mt) => {
212 let kind = ty::BorrowKind::from_mutbl(mt.mutbl);
213 Ok(deref_ptr(BorrowedPtr(kind, *r)))
216 ty::ty_ptr(ref mt) => {
217 Ok(deref_ptr(UnsafePtr(mt.mutbl)))
221 ty::ty_struct(..) => { // newtype
222 Ok(deref_interior(InteriorField(PositionalField(0))))
225 ty::ty_vec(_, _) | ty::ty_str => {
226 Ok(deref_interior(InteriorElement(element_kind(t))))
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:'t> {
252 impl<'t,TYPER:'t> Copy for MemCategorizationContext<'t,TYPER> {}
254 pub type McResult<T> = Result<T, ()>;
256 /// The `Typer` trait provides the interface for the mem-categorization
257 /// module to the results of the type check. It can be used to query
258 /// the type assigned to an expression node, to inquire after adjustments,
261 /// This interface is needed because mem-categorization is used from
262 /// two places: `regionck` and `borrowck`. `regionck` executes before
263 /// type inference is complete, and hence derives types and so on from
264 /// intermediate tables. This also implies that type errors can occur,
265 /// and hence `node_ty()` and friends return a `Result` type -- any
266 /// error will propagate back up through the mem-categorization
269 /// In the borrow checker, in contrast, type checking is complete and we
270 /// know that no errors have occurred, so we simply consult the tcx and we
271 /// can be sure that only `Ok` results will occur.
272 pub trait Typer<'tcx> : ty::UnboxedClosureTyper<'tcx> {
273 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
274 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>>;
275 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>>;
276 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool;
277 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>>;
278 fn node_method_origin(&self, method_call: ty::MethodCall)
279 -> Option<ty::MethodOrigin<'tcx>>;
280 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>>;
281 fn is_method_call(&self, id: ast::NodeId) -> bool;
282 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent>;
283 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow>;
284 fn capture_mode(&self, closure_expr_id: ast::NodeId)
285 -> ast::CaptureClause;
288 impl MutabilityCategory {
289 pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory {
291 MutImmutable => McImmutable,
292 MutMutable => McDeclared
296 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
298 ty::ImmBorrow => McImmutable,
299 ty::UniqueImmBorrow => McImmutable,
300 ty::MutBorrow => McDeclared,
304 pub fn from_pointer_kind(base_mutbl: MutabilityCategory,
305 ptr: PointerKind) -> MutabilityCategory {
310 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
311 MutabilityCategory::from_borrow_kind(borrow_kind)
314 MutabilityCategory::from_mutbl(m)
319 fn from_local(tcx: &ty::ctxt, id: ast::NodeId) -> MutabilityCategory {
320 match tcx.map.get(id) {
321 ast_map::NodeLocal(p) | ast_map::NodeArg(p) => match p.node {
322 ast::PatIdent(bind_mode, _, _) => {
323 if bind_mode == ast::BindByValue(ast::MutMutable) {
329 _ => tcx.sess.span_bug(p.span, "expected identifier pattern")
331 _ => tcx.sess.span_bug(tcx.map.span(id), "expected identifier pattern")
335 pub fn inherit(&self) -> MutabilityCategory {
337 McImmutable => McImmutable,
338 McDeclared => McInherited,
339 McInherited => McInherited,
343 pub fn is_mutable(&self) -> bool {
345 McImmutable => false,
351 pub fn is_immutable(&self) -> bool {
354 McDeclared | McInherited => false
358 pub fn to_user_str(&self) -> &'static str {
360 McDeclared | McInherited => "mutable",
361 McImmutable => "immutable",
366 impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
367 pub fn new(typer: &'t TYPER) -> MemCategorizationContext<'t,TYPER> {
368 MemCategorizationContext { typer: typer }
371 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
375 fn expr_ty(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
376 self.typer.node_ty(expr.id)
379 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> McResult<Ty<'tcx>> {
380 let unadjusted_ty = try!(self.expr_ty(expr));
381 Ok(ty::adjust_ty(self.tcx(), expr.span, expr.id, unadjusted_ty,
382 self.typer.adjustments().borrow().get(&expr.id),
383 |method_call| self.typer.node_method_ty(method_call)))
386 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
387 self.typer.node_ty(id)
390 fn pat_ty(&self, pat: &ast::Pat) -> McResult<Ty<'tcx>> {
391 let tcx = self.typer.tcx();
392 let base_ty = try!(self.typer.node_ty(pat.id));
393 // FIXME (Issue #18207): This code detects whether we are
394 // looking at a `ref x`, and if so, figures out what the type
395 // *being borrowed* is. But ideally we would put in a more
396 // fundamental fix to this conflated use of the node id.
397 let ret_ty = match pat.node {
398 ast::PatIdent(ast::BindByRef(_), _, _) => {
399 // a bind-by-ref means that the base_ty will be the type of the ident itself,
400 // but what we want here is the type of the underlying value being borrowed.
401 // So peel off one-level, turning the &T into T.
402 match ty::deref(base_ty, false) {
404 None => { return Err(()); }
409 debug!("pat_ty(pat={}) base_ty={} ret_ty={}",
410 pat.repr(tcx), base_ty.repr(tcx), ret_ty.repr(tcx));
414 pub fn cat_expr(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
415 match self.typer.adjustments().borrow().get(&expr.id) {
418 self.cat_expr_unadjusted(expr)
421 Some(adjustment) => {
423 ty::AdjustReifyFnPointer(..) => {
424 debug!("cat_expr(AdjustReifyFnPointer): {}",
425 expr.repr(self.tcx()));
426 // Convert a bare fn to a closure by adding NULL env.
427 // Result is an rvalue.
428 let expr_ty = try!(self.expr_ty_adjusted(expr));
429 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
434 autoref: Some(_), ..}) => {
435 debug!("cat_expr(AdjustDerefRef): {}",
436 expr.repr(self.tcx()));
437 // Equivalent to &*expr or something similar.
438 // Result is an rvalue.
439 let expr_ty = try!(self.expr_ty_adjusted(expr));
440 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
445 autoref: None, autoderefs}) => {
446 // Equivalent to *expr or something similar.
447 self.cat_expr_autoderefd(expr, autoderefs)
454 pub fn cat_expr_autoderefd(&self,
457 -> McResult<cmt<'tcx>> {
458 let mut cmt = try!(self.cat_expr_unadjusted(expr));
459 debug!("cat_expr_autoderefd: autoderefs={}, cmt={}",
461 cmt.repr(self.tcx()));
462 for deref in range(1u, autoderefs + 1) {
463 cmt = try!(self.cat_deref(expr, cmt, deref));
468 pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
469 debug!("cat_expr: id={} expr={}", expr.id, expr.repr(self.tcx()));
471 let expr_ty = try!(self.expr_ty(expr));
473 ast::ExprUnary(ast::UnDeref, ref e_base) => {
474 let base_cmt = try!(self.cat_expr(&**e_base));
475 self.cat_deref(expr, base_cmt, 0)
478 ast::ExprField(ref base, f_name) => {
479 let base_cmt = try!(self.cat_expr(&**base));
480 debug!("cat_expr(cat_field): id={} expr={} base={}",
482 expr.repr(self.tcx()),
483 base_cmt.repr(self.tcx()));
484 Ok(self.cat_field(expr, base_cmt, f_name.node.name, expr_ty))
487 ast::ExprTupField(ref base, idx) => {
488 let base_cmt = try!(self.cat_expr(&**base));
489 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
492 ast::ExprIndex(ref base, _) => {
493 let method_call = ty::MethodCall::expr(expr.id());
494 match self.typer.node_method_ty(method_call) {
496 // If this is an index implemented by a method call, then it
497 // will include an implicit deref of the result.
498 let ret_ty = self.overloaded_method_return_ty(method_ty);
500 // The index method always returns an `&T`, so
501 // dereference it to find the result type.
502 let elem_ty = match ret_ty.sty {
503 ty::ty_rptr(_, mt) => mt.ty,
505 debug!("cat_expr_unadjusted: return type of overloaded index is {}?",
506 ret_ty.repr(self.tcx()));
511 // The call to index() returns a `&T` value, which
512 // is an rvalue. That is what we will be
514 let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
515 self.cat_deref_common(expr, base_cmt, 1, elem_ty, true)
518 self.cat_index(expr, try!(self.cat_expr(&**base)))
523 ast::ExprPath(_) => {
524 let def = (*self.tcx().def_map.borrow())[expr.id];
525 self.cat_def(expr.id, expr.span, expr_ty, def)
528 ast::ExprParen(ref e) => {
532 ast::ExprAddrOf(..) | ast::ExprCall(..) |
533 ast::ExprAssign(..) | ast::ExprAssignOp(..) |
534 ast::ExprClosure(..) | ast::ExprRet(..) |
535 ast::ExprUnary(..) | ast::ExprRange(..) |
536 ast::ExprMethodCall(..) | ast::ExprCast(..) |
537 ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) |
538 ast::ExprBinary(..) | ast::ExprWhile(..) |
539 ast::ExprBlock(..) | ast::ExprLoop(..) | ast::ExprMatch(..) |
540 ast::ExprLit(..) | ast::ExprBreak(..) | ast::ExprMac(..) |
541 ast::ExprAgain(..) | ast::ExprStruct(..) | ast::ExprRepeat(..) |
542 ast::ExprInlineAsm(..) | ast::ExprBox(..) |
543 ast::ExprForLoop(..) => {
544 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
547 ast::ExprIfLet(..) => {
548 self.tcx().sess.span_bug(expr.span, "non-desugared ExprIfLet");
550 ast::ExprWhileLet(..) => {
551 self.tcx().sess.span_bug(expr.span, "non-desugared ExprWhileLet");
556 pub fn cat_def(&self,
561 -> McResult<cmt<'tcx>> {
562 debug!("cat_def: id={} expr={} def={:?}",
563 id, expr_ty.repr(self.tcx()), def);
566 def::DefStruct(..) | def::DefVariant(..) | def::DefConst(..) |
567 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => {
568 Ok(self.cat_rvalue_node(id, span, expr_ty))
570 def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
571 def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
572 def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
573 def::DefLabel(_) | def::DefSelfTy(..) |
574 def::DefAssociatedTy(..) | def::DefAssociatedPath(..)=> {
585 def::DefStatic(_, mutbl) => {
590 mutbl: if mutbl { McDeclared } else { McImmutable},
596 def::DefUpvar(var_id, fn_node_id, _) => {
597 let ty = try!(self.node_ty(fn_node_id));
599 ty::ty_unboxed_closure(closure_id, _, _) => {
600 let kind = self.typer.unboxed_closure_kind(closure_id);
601 let mode = self.typer.capture_mode(fn_node_id);
602 self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, true)
605 self.tcx().sess.span_bug(
607 &format!("Upvar of non-closure {} - {}",
609 ty.repr(self.tcx()))[]);
614 def::DefLocal(vid) => {
619 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
627 // Categorize an upvar, complete with invisible derefs of closure
628 // environment and upvar reference as appropriate.
633 fn_node_id: ast::NodeId,
634 kind: ty::UnboxedClosureKind,
635 mode: ast::CaptureClause,
637 -> McResult<cmt<'tcx>> {
638 // An upvar can have up to 3 components. The base is a
639 // `cat_upvar`. Next, we add a deref through the implicit
640 // environment pointer with an anonymous free region 'env and
641 // appropriate borrow kind for closure kinds that take self by
642 // reference. Finally, if the upvar was captured
643 // by-reference, we add a deref through that reference. The
644 // region of this reference is an inference variable 'up that
645 // was previously generated and recorded in the upvar borrow
646 // map. The borrow kind bk is inferred by based on how the
649 // This results in the following table for concrete closure
653 // ---------------+----------------------+-------------------------------
654 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
655 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
656 // FnOnce | copied | upvar -> &'up bk
657 // old stack | N/A | upvar -> &'env mut -> &'up bk
658 // old proc/once | copied | N/A
659 let var_ty = try!(self.node_ty(var_id));
661 let upvar_id = ty::UpvarId { var_id: var_id,
662 closure_expr_id: fn_node_id };
664 // Mutability of original variable itself
665 let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
667 // Construct information about env pointer dereference, if any
668 let mutbl = match kind {
669 ty::FnOnceUnboxedClosureKind => None, // None, env is by-value
670 ty::FnMutUnboxedClosureKind => match mode { // Depends on capture type
671 ast::CaptureByValue => Some(var_mutbl), // Mutable if the original var is
672 ast::CaptureByRef => Some(McDeclared) // Mutable regardless
674 ty::FnUnboxedClosureKind => Some(McImmutable) // Never mutable
676 let env_info = mutbl.map(|env_mutbl| {
677 // Look up the node ID of the closure body so we can construct
678 // a free region within it
680 let fn_expr = match self.tcx().map.find(fn_node_id) {
681 Some(ast_map::NodeExpr(e)) => e,
686 ast::ExprClosure(_, _, _, ref body) => body.id,
691 // Region of environment pointer
692 let env_region = ty::ReFree(ty::FreeRegion {
693 scope: region::CodeExtent::from_node_id(fn_body_id),
694 bound_region: ty::BrEnv
697 let env_ptr = BorrowedPtr(if env_mutbl.is_mutable() {
706 // First, switch by capture mode
708 ast::CaptureByValue => {
709 let mut base = cmt_ {
712 cat: cat_upvar(Upvar {
715 is_unboxed: is_unboxed
723 Some((env_mutbl, env_ptr)) => {
724 // We need to add the env deref. This means
725 // that the above is actually immutable and
726 // has a ref type. However, nothing should
727 // actually look at the type, so we can get
728 // away with stuffing a `ty_err` in there
729 // instead of bothering to construct a proper
731 base.mutbl = McImmutable;
732 base.ty = self.tcx().types.err;
736 cat: cat_deref(Rc::new(base), 0, env_ptr),
739 note: NoteClosureEnv(upvar_id)
742 None => Rc::new(base)
745 ast::CaptureByRef => {
746 // The type here is actually a ref (or ref of a ref),
747 // but we can again get away with not constructing one
748 // properly since it will never be used.
749 let mut base = cmt_ {
752 cat: cat_upvar(Upvar {
755 is_unboxed: is_unboxed
758 ty: self.tcx().types.err,
763 Some((env_mutbl, env_ptr)) => {
767 cat: cat_deref(Rc::new(base), 0, env_ptr),
769 ty: self.tcx().types.err,
770 note: NoteClosureEnv(upvar_id)
776 // Look up upvar borrow so we can get its region
777 let upvar_borrow = self.typer.upvar_borrow(upvar_id).unwrap();
778 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
783 cat: cat_deref(Rc::new(base), 0, ptr),
784 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
786 note: NoteUpvarRef(upvar_id)
792 pub fn cat_rvalue_node(&self,
797 match self.typer.temporary_scope(id) {
800 ty::ty_vec(_, Some(0)) => self.cat_rvalue(id, span, ty::ReStatic, expr_ty),
801 _ => self.cat_rvalue(id, span, ty::ReScope(scope), expr_ty)
805 self.cat_rvalue(id, span, ty::ReStatic, expr_ty)
810 pub fn cat_rvalue(&self,
813 temp_scope: ty::Region,
814 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
818 cat:cat_rvalue(temp_scope),
825 pub fn cat_field<N:ast_node>(&self,
834 mutbl: base_cmt.mutbl.inherit(),
835 cat: cat_interior(base_cmt, InteriorField(NamedField(f_name))),
841 pub fn cat_tup_field<N:ast_node>(&self,
850 mutbl: base_cmt.mutbl.inherit(),
851 cat: cat_interior(base_cmt, InteriorField(PositionalField(f_idx))),
857 fn cat_deref<N:ast_node>(&self,
861 -> McResult<cmt<'tcx>> {
862 let adjustment = match self.typer.adjustments().borrow().get(&node.id()) {
863 Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject,
864 _ if deref_cnt != 0 => ty::AutoDeref(deref_cnt),
865 _ => ty::NoAdjustment
868 let method_call = ty::MethodCall {
870 adjustment: adjustment
872 let method_ty = self.typer.node_method_ty(method_call);
874 debug!("cat_deref: method_call={:?} method_ty={:?}",
875 method_call, method_ty.map(|ty| ty.repr(self.tcx())));
877 let base_cmt = match method_ty {
880 ty::assert_no_late_bound_regions(
881 self.tcx(), &ty::ty_fn_ret(method_ty)).unwrap();
882 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
886 let base_cmt_ty = base_cmt.ty;
887 match ty::deref(base_cmt_ty, true) {
888 Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty,
889 /* implicit: */ false),
891 debug!("Explicit deref of non-derefable type: {}",
892 base_cmt_ty.repr(self.tcx()));
898 fn cat_deref_common<N:ast_node>(&self,
904 -> McResult<cmt<'tcx>>
906 let (m, cat) = match try!(deref_kind(base_cmt.ty)) {
908 let ptr = if implicit {
910 BorrowedPtr(bk, r) => Implicit(bk, r),
911 _ => self.tcx().sess.span_bug(node.span(),
912 "Implicit deref of non-borrowed pointer")
917 // for unique ptrs, we inherit mutability from the
919 (MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
920 cat_deref(base_cmt, deref_cnt, ptr))
922 deref_interior(interior) => {
923 (base_cmt.mutbl.inherit(), cat_interior(base_cmt, interior))
936 pub fn cat_index<N:ast_node>(&self,
938 mut base_cmt: cmt<'tcx>)
939 -> McResult<cmt<'tcx>> {
940 //! Creates a cmt for an indexing operation (`[]`).
942 //! One subtle aspect of indexing that may not be
943 //! immediately obvious: for anything other than a fixed-length
944 //! vector, an operation like `x[y]` actually consists of two
945 //! disjoint (from the point of view of borrowck) operations.
946 //! The first is a deref of `x` to create a pointer `p` that points
947 //! at the first element in the array. The second operation is
948 //! an index which adds `y*sizeof(T)` to `p` to obtain the
949 //! pointer to `x[y]`. `cat_index` will produce a resulting
950 //! cmt containing both this deref and the indexing,
951 //! presuming that `base_cmt` is not of fixed-length type.
954 //! - `elt`: the AST node being indexed
955 //! - `base_cmt`: the cmt of `elt`
957 let method_call = ty::MethodCall::expr(elt.id());
958 let method_ty = self.typer.node_method_ty(method_call);
960 let element_ty = match method_ty {
962 let ref_ty = self.overloaded_method_return_ty(method_ty);
963 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
965 // FIXME(#20649) -- why are we using the `self_ty` as the element type...?
966 let self_ty = ty::ty_fn_sig(method_ty).input(0);
967 ty::assert_no_late_bound_regions(self.tcx(), &self_ty)
970 match ty::array_element_ty(self.tcx(), base_cmt.ty) {
979 let m = base_cmt.mutbl.inherit();
980 return Ok(interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty));
982 fn interior<'tcx, N: ast_node>(elt: &N,
985 mutbl: MutabilityCategory,
986 element_ty: Ty<'tcx>) -> cmt<'tcx>
991 cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
999 // Takes either a vec or a reference to a vec and returns the cmt for the
1001 fn deref_vec<N:ast_node>(&self,
1003 base_cmt: cmt<'tcx>)
1004 -> McResult<cmt<'tcx>>
1006 match try!(deref_kind(base_cmt.ty)) {
1008 // for unique ptrs, we inherit mutability from the
1009 // owning reference.
1010 let m = MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr);
1012 // the deref is explicit in the resulting cmt
1016 cat:cat_deref(base_cmt.clone(), 0, ptr),
1018 ty: match ty::deref(base_cmt.ty, false) {
1020 None => self.tcx().sess.bug("Found non-derefable type")
1026 deref_interior(_) => {
1032 /// Given a pattern P like: `[_, ..Q, _]`, where `vec_cmt` is the cmt for `P`, `slice_pat` is
1033 /// the pattern `Q`, returns:
1036 /// * the mutability and region of the slice `Q`
1038 /// These last two bits of info happen to be things that borrowck needs.
1039 pub fn cat_slice_pattern(&self,
1041 slice_pat: &ast::Pat)
1042 -> McResult<(cmt<'tcx>, ast::Mutability, ty::Region)> {
1043 let slice_ty = try!(self.node_ty(slice_pat.id));
1044 let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
1047 let cmt_slice = try!(self.cat_index(slice_pat, try!(self.deref_vec(slice_pat, vec_cmt))));
1048 return Ok((cmt_slice, slice_mutbl, slice_r));
1050 /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
1051 /// ..ref c], then the type of `ref c` will be `&&[]`, so to extract the slice details we
1052 /// have to recurse through rptrs.
1053 fn vec_slice_info(tcx: &ty::ctxt,
1056 -> (ast::Mutability, ty::Region) {
1057 match slice_ty.sty {
1058 ty::ty_rptr(r, ref mt) => match mt.ty.sty {
1059 ty::ty_vec(_, None) => (mt.mutbl, *r),
1060 _ => vec_slice_info(tcx, pat, mt.ty),
1064 tcx.sess.span_bug(pat.span,
1065 "type of slice pattern is not a slice");
1071 pub fn cat_imm_interior<N:ast_node>(&self,
1073 base_cmt: cmt<'tcx>,
1074 interior_ty: Ty<'tcx>,
1075 interior: InteriorKind)
1080 mutbl: base_cmt.mutbl.inherit(),
1081 cat: cat_interior(base_cmt, interior),
1087 pub fn cat_downcast<N:ast_node>(&self,
1089 base_cmt: cmt<'tcx>,
1090 downcast_ty: Ty<'tcx>,
1091 variant_did: ast::DefId)
1096 mutbl: base_cmt.mutbl.inherit(),
1097 cat: cat_downcast(base_cmt, variant_did),
1103 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, mut op: F) -> McResult<()>
1104 where F: FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1106 self.cat_pattern_(cmt, pat, &mut op)
1109 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1110 fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, op: &mut F)
1112 where F : FnMut(&MemCategorizationContext<'t, TYPER>, cmt<'tcx>, &ast::Pat),
1114 // Here, `cmt` is the categorization for the value being
1115 // matched and pat is the pattern it is being matched against.
1117 // In general, the way that this works is that we walk down
1118 // the pattern, constructing a cmt that represents the path
1119 // that will be taken to reach the value being matched.
1121 // When we encounter named bindings, we take the cmt that has
1122 // been built up and pass it off to guarantee_valid() so that
1123 // we can be sure that the binding will remain valid for the
1124 // duration of the arm.
1126 // (*2) There is subtlety concerning the correspondence between
1127 // pattern ids and types as compared to *expression* ids and
1128 // types. This is explained briefly. on the definition of the
1129 // type `cmt`, so go off and read what it says there, then
1130 // come back and I'll dive into a bit more detail here. :) OK,
1133 // In general, the id of the cmt should be the node that
1134 // "produces" the value---patterns aren't executable code
1135 // exactly, but I consider them to "execute" when they match a
1136 // value, and I consider them to produce the value that was
1137 // matched. So if you have something like:
1144 // In this case, the cmt and the relevant ids would be:
1146 // CMT Id Type of Id Type of cmt
1149 // ^~~~~~~^ `x` from discr @@int @@int
1150 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1151 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1153 // You can see that the types of the id and the cmt are in
1154 // sync in the first line, because that id is actually the id
1155 // of an expression. But once we get to pattern ids, the types
1156 // step out of sync again. So you'll see below that we always
1157 // get the type of the *subpattern* and use that.
1159 debug!("cat_pattern: id={} pat={} cmt={}",
1160 pat.id, pprust::pat_to_string(pat),
1161 cmt.repr(self.tcx()));
1163 (*op)(self, cmt.clone(), pat);
1165 let def_map = self.tcx().def_map.borrow();
1166 let opt_def = def_map.get(&pat.id);
1168 // Note: This goes up here (rather than within the PatEnum arm
1169 // alone) because struct patterns can refer to struct types or
1170 // to struct variants within enums.
1171 let cmt = match opt_def {
1172 Some(&def::DefVariant(enum_did, variant_did, _))
1173 // univariant enums do not need downcasts
1174 if !ty::enum_is_univariant(self.tcx(), enum_did) => {
1175 self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1181 ast::PatWild(_) => {
1185 ast::PatEnum(_, None) => {
1188 ast::PatEnum(_, Some(ref subpats)) => {
1190 Some(&def::DefVariant(..)) => {
1192 for (i, subpat) in subpats.iter().enumerate() {
1193 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1196 self.cat_imm_interior(
1197 pat, cmt.clone(), subpat_ty,
1198 InteriorField(PositionalField(i)));
1200 try!(self.cat_pattern_(subcmt, &**subpat, op));
1203 Some(&def::DefStruct(..)) => {
1204 for (i, subpat) in subpats.iter().enumerate() {
1205 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1207 self.cat_imm_interior(
1208 pat, cmt.clone(), subpat_ty,
1209 InteriorField(PositionalField(i)));
1210 try!(self.cat_pattern_(cmt_field, &**subpat, op));
1213 Some(&def::DefConst(..)) => {
1214 for subpat in subpats.iter() {
1215 try!(self.cat_pattern_(cmt.clone(), &**subpat, op));
1219 self.tcx().sess.span_bug(
1221 "enum pattern didn't resolve to enum or struct");
1226 ast::PatIdent(_, _, Some(ref subpat)) => {
1227 try!(self.cat_pattern_(cmt, &**subpat, op));
1230 ast::PatIdent(_, _, None) => {
1231 // nullary variant or identifier: ignore
1234 ast::PatStruct(_, ref field_pats, _) => {
1235 // {f1: p1, ..., fN: pN}
1236 for fp in field_pats.iter() {
1237 let field_ty = try!(self.pat_ty(&*fp.node.pat)); // see (*2)
1238 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.ident.name, field_ty);
1239 try!(self.cat_pattern_(cmt_field, &*fp.node.pat, op));
1243 ast::PatTup(ref subpats) => {
1245 for (i, subpat) in subpats.iter().enumerate() {
1246 let subpat_ty = try!(self.pat_ty(&**subpat)); // see (*2)
1248 self.cat_imm_interior(
1249 pat, cmt.clone(), subpat_ty,
1250 InteriorField(PositionalField(i)));
1251 try!(self.cat_pattern_(subcmt, &**subpat, op));
1255 ast::PatBox(ref subpat) | ast::PatRegion(ref subpat, _) => {
1256 // box p1, &p1, &mut p1. we can ignore the mutability of
1257 // PatRegion since that information is already contained
1259 let subcmt = try!(self.cat_deref(pat, cmt, 0));
1260 try!(self.cat_pattern_(subcmt, &**subpat, op));
1263 ast::PatVec(ref before, ref slice, ref after) => {
1264 let elt_cmt = try!(self.cat_index(pat, try!(self.deref_vec(pat, cmt))));
1265 for before_pat in before.iter() {
1266 try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
1268 for slice_pat in slice.iter() {
1269 let slice_ty = try!(self.pat_ty(&**slice_pat));
1270 let slice_cmt = self.cat_rvalue_node(pat.id(), pat.span(), slice_ty);
1271 try!(self.cat_pattern_(slice_cmt, &**slice_pat, op));
1273 for after_pat in after.iter() {
1274 try!(self.cat_pattern_(elt_cmt.clone(), &**after_pat, op));
1278 ast::PatLit(_) | ast::PatRange(_, _) => {
1283 self.tcx().sess.span_bug(pat.span, "unexpanded macro");
1290 fn overloaded_method_return_ty(&self,
1291 method_ty: Ty<'tcx>)
1294 // When we process an overloaded `*` or `[]` etc, we often
1295 // need to extract the return type of the method. These method
1296 // types are generated by method resolution and always have
1297 // all late-bound regions fully instantiated, so we just want
1298 // to skip past the binder.
1299 ty::assert_no_late_bound_regions(self.tcx(), &ty::ty_fn_ret(method_ty))
1300 .unwrap() // overloaded ops do not diverge, either
1305 pub enum InteriorSafety {
1311 pub enum AliasableReason {
1313 AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1315 AliasableStatic(InteriorSafety),
1316 AliasableStaticMut(InteriorSafety),
1319 impl<'tcx> cmt_<'tcx> {
1320 pub fn guarantor(&self) -> cmt<'tcx> {
1321 //! Returns `self` after stripping away any owned pointer derefs or
1322 //! interior content. The return value is basically the `cmt` which
1323 //! determines how long the value in `self` remains live.
1329 cat_deref(_, _, UnsafePtr(..)) |
1330 cat_deref(_, _, BorrowedPtr(..)) |
1331 cat_deref(_, _, Implicit(..)) |
1333 Rc::new((*self).clone())
1335 cat_downcast(ref b, _) |
1336 cat_interior(ref b, _) |
1337 cat_deref(ref b, _, Unique) => {
1343 /// Returns `Some(_)` if this lvalue represents a freely aliasable pointer type.
1344 pub fn freely_aliasable(&self, ctxt: &ty::ctxt<'tcx>)
1345 -> Option<AliasableReason> {
1346 // Maybe non-obvious: copied upvars can only be considered
1347 // non-aliasable in once closures, since any other kind can be
1348 // aliased and eventually recused.
1351 cat_deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1352 cat_deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1353 cat_deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1354 cat_deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1355 cat_downcast(ref b, _) |
1356 cat_deref(ref b, _, Unique) |
1357 cat_interior(ref b, _) => {
1358 // Aliasability depends on base cmt
1359 b.freely_aliasable(ctxt)
1365 cat_deref(_, _, UnsafePtr(..)) => { // yes, it's aliasable, but...
1369 cat_static_item(..) => {
1370 let int_safe = if ty::type_interior_is_unsafe(ctxt, self.ty) {
1376 if self.mutbl.is_mutable() {
1377 Some(AliasableStaticMut(int_safe))
1379 Some(AliasableStatic(int_safe))
1383 cat_deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1384 cat_deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1386 cat_upvar(Upvar{ id, .. }) => Some(AliasableClosure(id.closure_expr_id)),
1387 _ => Some(AliasableBorrowed)
1393 // Digs down through one or two layers of deref and grabs the cmt
1394 // for the upvar if a note indicates there is one.
1395 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1397 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1398 Some(match self.cat {
1399 cat_deref(ref inner, _, _) => {
1401 cat_deref(ref inner, _, _) => inner.clone(),
1402 cat_upvar(..) => inner.clone(),
1414 pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
1416 cat_static_item => {
1417 "static item".to_string()
1420 "non-lvalue".to_string()
1423 match tcx.map.find(vid) {
1424 Some(ast_map::NodeArg(_)) => {
1425 "argument".to_string()
1427 _ => "local variable".to_string()
1430 cat_deref(_, _, pk) => {
1431 let upvar = self.upvar();
1432 match upvar.as_ref().map(|i| &i.cat) {
1433 Some(&cat_upvar(ref var)) => {
1434 var.user_string(tcx)
1436 Some(_) => unreachable!(),
1440 format!("indexed content")
1443 format!("`Box` content")
1446 format!("dereference of unsafe pointer")
1448 BorrowedPtr(..) => {
1449 format!("borrowed content")
1455 cat_interior(_, InteriorField(NamedField(_))) => {
1458 cat_interior(_, InteriorField(PositionalField(_))) => {
1459 "anonymous field".to_string()
1461 cat_interior(_, InteriorElement(VecElement)) |
1462 cat_interior(_, InteriorElement(OtherElement)) => {
1463 "indexed content".to_string()
1465 cat_upvar(ref var) => {
1466 var.user_string(tcx)
1468 cat_downcast(ref cmt, _) => {
1469 cmt.descriptive_string(tcx)
1475 impl<'tcx> Repr<'tcx> for cmt_<'tcx> {
1476 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1477 format!("{{{} id:{} m:{:?} ty:{}}}",
1485 impl<'tcx> Repr<'tcx> for categorization<'tcx> {
1486 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1492 format!("{:?}", *self)
1494 cat_deref(ref cmt, derefs, ptr) => {
1495 format!("{}-{}{}->", cmt.cat.repr(tcx), ptr.repr(tcx), derefs)
1497 cat_interior(ref cmt, interior) => {
1498 format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx))
1500 cat_downcast(ref cmt, _) => {
1501 format!("{}->(enum)", cmt.cat.repr(tcx))
1507 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1510 BorrowedPtr(ty::ImmBorrow, _) |
1511 Implicit(ty::ImmBorrow, _) => "&",
1512 BorrowedPtr(ty::MutBorrow, _) |
1513 Implicit(ty::MutBorrow, _) => "&mut",
1514 BorrowedPtr(ty::UniqueImmBorrow, _) |
1515 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1516 UnsafePtr(_) => "*",
1520 impl<'tcx> Repr<'tcx> for PointerKind {
1521 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
1526 BorrowedPtr(ty::ImmBorrow, ref r) |
1527 Implicit(ty::ImmBorrow, ref r) => {
1528 format!("&{}", r.repr(tcx))
1530 BorrowedPtr(ty::MutBorrow, ref r) |
1531 Implicit(ty::MutBorrow, ref r) => {
1532 format!("&{} mut", r.repr(tcx))
1534 BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1535 Implicit(ty::UniqueImmBorrow, ref r) => {
1536 format!("&{} uniq", r.repr(tcx))
1545 impl<'tcx> Repr<'tcx> for InteriorKind {
1546 fn repr(&self, _tcx: &ty::ctxt) -> String {
1548 InteriorField(NamedField(fld)) => {
1549 token::get_name(fld).get().to_string()
1551 InteriorField(PositionalField(i)) => format!("#{}", i),
1552 InteriorElement(_) => "[]".to_string(),
1557 fn element_kind(t: Ty) -> ElementKind {
1559 ty::ty_rptr(_, ty::mt{ty, ..}) |
1560 ty::ty_uniq(ty) => match ty.sty {
1561 ty::ty_vec(_, None) => VecElement,
1564 ty::ty_vec(..) => VecElement,
1569 impl<'tcx> Repr<'tcx> for ty::UnboxedClosureKind {
1570 fn repr(&self, _: &ty::ctxt) -> String {
1571 format!("Upvar({:?})", self)
1575 impl<'tcx> Repr<'tcx> for Upvar {
1576 fn repr(&self, tcx: &ty::ctxt) -> String {
1577 format!("Upvar({})", self.kind.repr(tcx))
1581 impl<'tcx> UserString<'tcx> for Upvar {
1582 fn user_string(&self, _: &ty::ctxt) -> String {
1583 let kind = match self.kind {
1584 ty::FnUnboxedClosureKind => "Fn",
1585 ty::FnMutUnboxedClosureKind => "FnMut",
1586 ty::FnOnceUnboxedClosureKind => "FnOnce",
1588 format!("captured outer variable in an `{}` closure", kind)