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 `Categorization::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::AliasableReason::*;
69 pub use self::Note::*;
71 use self::Aliasability::*;
73 use hir::def_id::DefId;
74 use hir::map as hir_map;
76 use hir::def::{Def, CtorKind};
78 use ty::{self, Ty, TyCtxt};
80 use hir::{MutImmutable, MutMutable, PatKind};
81 use hir::pat_util::EnumerateAndAdjustIterator;
89 #[derive(Clone, PartialEq)]
90 pub enum Categorization<'tcx> {
91 // temporary val, argument is its scope
92 Rvalue(&'tcx ty::Region, &'tcx ty::Region),
94 Upvar(Upvar), // upvar referenced by closure env
95 Local(ast::NodeId), // local variable
96 Deref(cmt<'tcx>, usize, PointerKind<'tcx>), // deref of a ptr
97 Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
98 Downcast(cmt<'tcx>, 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)]
107 pub kind: ty::ClosureKind
110 // different kinds of pointers:
111 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
112 pub enum PointerKind<'tcx> {
117 BorrowedPtr(ty::BorrowKind, &'tcx ty::Region),
120 UnsafePtr(hir::Mutability),
122 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
123 Implicit(ty::BorrowKind, &'tcx ty::Region),
126 // We use the term "interior" to mean "something reachable from the
127 // base without a pointer dereference", e.g. a field
128 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
129 pub enum InteriorKind {
130 InteriorField(FieldName),
131 InteriorElement(InteriorOffsetKind, ElementKind),
134 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
136 NamedField(ast::Name),
137 PositionalField(usize)
140 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
141 pub enum InteriorOffsetKind {
142 Index, // e.g. `array_expr[index_expr]`
143 Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
146 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
147 pub enum ElementKind {
152 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
153 pub enum MutabilityCategory {
154 McImmutable, // Immutable.
155 McDeclared, // Directly declared as mutable.
156 McInherited, // Inherited from the fact that owner is mutable.
159 // A note about the provenance of a `cmt`. This is used for
160 // special-case handling of upvars such as mutability inference.
161 // Upvar categorization can generate a variable number of nested
162 // derefs. The note allows detecting them without deep pattern
163 // matching on the categorization.
164 #[derive(Clone, Copy, PartialEq, Debug)]
166 NoteClosureEnv(ty::UpvarId), // Deref through closure env
167 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
168 NoteNone // Nothing special
171 // `cmt`: "Category, Mutability, and Type".
173 // a complete categorization of a value indicating where it originated
174 // and how it is located, as well as the mutability of the memory in
175 // which the value is stored.
177 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
178 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
179 // always the `id` of the node producing the type; in an expression
180 // like `*x`, the type of this deref node is the deref'd type (`T`),
181 // but in a pattern like `@x`, the `@x` pattern is again a
182 // dereference, but its type is the type *before* the dereference
183 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
184 // fashion. For more details, see the method `cat_pattern`
185 #[derive(Clone, PartialEq)]
186 pub struct cmt_<'tcx> {
187 pub id: ast::NodeId, // id of expr/pat producing this value
188 pub span: Span, // span of same expr/pat
189 pub cat: Categorization<'tcx>, // categorization of expr
190 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
191 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
192 pub note: Note, // Note about the provenance of this cmt
195 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
197 impl<'tcx> cmt_<'tcx> {
198 pub fn get_field(&self, name: ast::Name) -> Option<DefId> {
200 Categorization::Deref(ref cmt, ..) |
201 Categorization::Interior(ref cmt, _) |
202 Categorization::Downcast(ref cmt, _) => {
203 if let Categorization::Local(_) = cmt.cat {
204 if let ty::TyAdt(def, _) = self.ty.sty {
205 return def.struct_variant().find_field_named(name).map(|x| x.did);
216 pub fn get_field_name(&self) -> Option<ast::Name> {
218 Categorization::Interior(_, ref ik) => {
219 if let InteriorKind::InteriorField(FieldName::NamedField(name)) = *ik {
225 Categorization::Deref(ref cmt, ..) |
226 Categorization::Downcast(ref cmt, _) => {
233 pub fn get_arg_if_immutable(&self, map: &hir_map::Map) -> Option<ast::NodeId> {
235 Categorization::Deref(ref cmt, ..) |
236 Categorization::Interior(ref cmt, _) |
237 Categorization::Downcast(ref cmt, _) => {
238 if let Categorization::Local(nid) = cmt.cat {
239 if let ty::TyAdt(_, _) = self.ty.sty {
240 if let ty::TyRef(_, ty::TypeAndMut{mutbl: MutImmutable, ..}) = cmt.ty.sty {
246 cmt.get_arg_if_immutable(map)
255 fn id(&self) -> ast::NodeId;
256 fn span(&self) -> Span;
259 impl ast_node for hir::Expr {
260 fn id(&self) -> ast::NodeId { self.id }
261 fn span(&self) -> Span { self.span }
264 impl ast_node for hir::Pat {
265 fn id(&self) -> ast::NodeId { self.id }
266 fn span(&self) -> Span { self.span }
269 #[derive(Copy, Clone)]
270 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
271 pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
272 options: MemCategorizationOptions,
275 #[derive(Copy, Clone, Default)]
276 pub struct MemCategorizationOptions {
277 // If true, then when analyzing a closure upvar, if the closure
278 // has a missing kind, we treat it like a Fn closure. When false,
279 // we ICE if the closure has a missing kind. Should be false
280 // except during closure kind inference. It is used by the
281 // mem-categorization code to be able to have stricter assertions
282 // (which are always true except during upvar inference).
283 pub during_closure_kind_inference: bool,
286 pub type McResult<T> = Result<T, ()>;
288 impl MutabilityCategory {
289 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
291 MutImmutable => McImmutable,
292 MutMutable => McDeclared
294 debug!("MutabilityCategory::{}({:?}) => {:?}",
295 "from_mutbl", m, ret);
299 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
300 let ret = match borrow_kind {
301 ty::ImmBorrow => McImmutable,
302 ty::UniqueImmBorrow => McImmutable,
303 ty::MutBorrow => McDeclared,
305 debug!("MutabilityCategory::{}({:?}) => {:?}",
306 "from_borrow_kind", borrow_kind, ret);
310 fn from_pointer_kind(base_mutbl: MutabilityCategory,
311 ptr: PointerKind) -> MutabilityCategory {
312 let ret = match ptr {
316 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
317 MutabilityCategory::from_borrow_kind(borrow_kind)
320 MutabilityCategory::from_mutbl(m)
323 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
324 "from_pointer_kind", base_mutbl, ptr, ret);
328 fn from_local(tcx: TyCtxt, id: ast::NodeId) -> MutabilityCategory {
329 let ret = match tcx.hir.get(id) {
330 hir_map::NodeLocal(p) => match p.node {
331 PatKind::Binding(bind_mode, ..) => {
332 if bind_mode == hir::BindByValue(hir::MutMutable) {
338 _ => span_bug!(p.span, "expected identifier pattern")
340 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
342 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
343 "from_local", id, ret);
347 pub fn inherit(&self) -> MutabilityCategory {
348 let ret = match *self {
349 McImmutable => McImmutable,
350 McDeclared => McInherited,
351 McInherited => McInherited,
353 debug!("{:?}.inherit() => {:?}", self, ret);
357 pub fn is_mutable(&self) -> bool {
358 let ret = match *self {
359 McImmutable => false,
363 debug!("{:?}.is_mutable() => {:?}", self, ret);
367 pub fn is_immutable(&self) -> bool {
368 let ret = match *self {
370 McDeclared | McInherited => false
372 debug!("{:?}.is_immutable() => {:?}", self, ret);
376 pub fn to_user_str(&self) -> &'static str {
378 McDeclared | McInherited => "mutable",
379 McImmutable => "immutable",
384 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
385 pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>)
386 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
387 MemCategorizationContext::with_options(infcx, MemCategorizationOptions::default())
390 pub fn with_options(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
391 options: MemCategorizationOptions)
392 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
393 MemCategorizationContext {
399 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
403 fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
404 match self.infcx.node_ty(expr.id) {
407 debug!("expr_ty({:?}) yielded Err", expr);
413 fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
414 self.infcx.expr_ty_adjusted(expr)
417 fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
418 self.infcx.node_ty(id)
421 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
422 let base_ty = self.infcx.node_ty(pat.id)?;
423 // FIXME (Issue #18207): This code detects whether we are
424 // looking at a `ref x`, and if so, figures out what the type
425 // *being borrowed* is. But ideally we would put in a more
426 // fundamental fix to this conflated use of the node id.
427 let ret_ty = match pat.node {
428 PatKind::Binding(hir::BindByRef(_), ..) => {
429 // a bind-by-ref means that the base_ty will be the type of the ident itself,
430 // but what we want here is the type of the underlying value being borrowed.
431 // So peel off one-level, turning the &T into T.
432 match base_ty.builtin_deref(false, ty::NoPreference) {
434 None => { return Err(()); }
439 debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
440 pat, base_ty, ret_ty);
444 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
445 match self.infcx.tables.borrow().adjustments.get(&expr.id) {
448 self.cat_expr_unadjusted(expr)
451 Some(adjustment) => {
452 match adjustment.kind {
453 adjustment::Adjust::DerefRef {
458 // Equivalent to *expr or something similar.
459 self.cat_expr_autoderefd(expr, autoderefs)
462 adjustment::Adjust::NeverToAny |
463 adjustment::Adjust::ReifyFnPointer |
464 adjustment::Adjust::UnsafeFnPointer |
465 adjustment::Adjust::MutToConstPointer |
466 adjustment::Adjust::DerefRef {..} => {
467 debug!("cat_expr({:?}): {:?}",
470 // Result is an rvalue.
471 let expr_ty = self.expr_ty_adjusted(expr)?;
472 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
479 pub fn cat_expr_autoderefd(&self,
482 -> McResult<cmt<'tcx>> {
483 let mut cmt = self.cat_expr_unadjusted(expr)?;
484 debug!("cat_expr_autoderefd: autoderefs={}, cmt={:?}",
487 for deref in 1..autoderefs + 1 {
488 cmt = self.cat_deref(expr, cmt, deref)?;
493 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
494 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
496 let expr_ty = self.expr_ty(expr)?;
498 hir::ExprUnary(hir::UnDeref, ref e_base) => {
499 let base_cmt = self.cat_expr(&e_base)?;
500 self.cat_deref(expr, base_cmt, 0)
503 hir::ExprField(ref base, f_name) => {
504 let base_cmt = self.cat_expr(&base)?;
505 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
509 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
512 hir::ExprTupField(ref base, idx) => {
513 let base_cmt = self.cat_expr(&base)?;
514 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
517 hir::ExprIndex(ref base, _) => {
518 let method_call = ty::MethodCall::expr(expr.id());
519 match self.infcx.node_method_ty(method_call) {
521 // If this is an index implemented by a method call, then it
522 // will include an implicit deref of the result.
523 let ret_ty = self.overloaded_method_return_ty(method_ty);
525 // The index method always returns an `&T`, so
526 // dereference it to find the result type.
527 let elem_ty = match ret_ty.sty {
528 ty::TyRef(_, mt) => mt.ty,
530 debug!("cat_expr_unadjusted: return type of overloaded index is {:?}?",
536 // The call to index() returns a `&T` value, which
537 // is an rvalue. That is what we will be
539 let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
540 Ok(self.cat_deref_common(expr, base_cmt, 1, elem_ty, true))
543 self.cat_index(expr, self.cat_expr(&base)?, InteriorOffsetKind::Index)
548 hir::ExprPath(ref qpath) => {
549 let def = self.infcx.tables.borrow().qpath_def(qpath, expr.id);
550 self.cat_def(expr.id, expr.span, expr_ty, def)
553 hir::ExprType(ref e, _) => {
557 hir::ExprAddrOf(..) | hir::ExprCall(..) |
558 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
559 hir::ExprClosure(..) | hir::ExprRet(..) |
561 hir::ExprMethodCall(..) | hir::ExprCast(..) |
562 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
563 hir::ExprBinary(..) | hir::ExprWhile(..) |
564 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
565 hir::ExprLit(..) | hir::ExprBreak(..) |
566 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
567 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
568 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
573 pub fn cat_def(&self,
578 -> McResult<cmt<'tcx>> {
579 debug!("cat_def: id={} expr={:?} def={:?}",
583 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
584 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
585 Ok(self.cat_rvalue_node(id, span, expr_ty))
588 Def::Static(_, mutbl) => {
592 cat:Categorization::StaticItem,
593 mutbl: if mutbl { McDeclared } else { McImmutable},
599 Def::Upvar(def_id, _, fn_node_id) => {
600 let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
601 let ty = self.node_ty(fn_node_id)?;
603 ty::TyClosure(closure_id, _) => {
604 match self.infcx.closure_kind(closure_id) {
606 self.cat_upvar(id, span, var_id, fn_node_id, kind)
609 if !self.options.during_closure_kind_inference {
612 "No closure kind for {:?}",
616 // during closure kind inference, we
617 // don't know the closure kind yet, but
618 // it's ok because we detect that we are
619 // accessing an upvar and handle that
620 // case specially anyhow. Use Fn
622 self.cat_upvar(id, span, var_id, fn_node_id, ty::ClosureKind::Fn)
629 "Upvar of non-closure {} - {:?}",
636 Def::Local(def_id) => {
637 let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
641 cat: Categorization::Local(vid),
642 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
648 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
652 // Categorize an upvar, complete with invisible derefs of closure
653 // environment and upvar reference as appropriate.
658 fn_node_id: ast::NodeId,
659 kind: ty::ClosureKind)
660 -> McResult<cmt<'tcx>>
662 // An upvar can have up to 3 components. We translate first to a
663 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
664 // field from the environment.
666 // `Categorization::Upvar`. Next, we add a deref through the implicit
667 // environment pointer with an anonymous free region 'env and
668 // appropriate borrow kind for closure kinds that take self by
669 // reference. Finally, if the upvar was captured
670 // by-reference, we add a deref through that reference. The
671 // region of this reference is an inference variable 'up that
672 // was previously generated and recorded in the upvar borrow
673 // map. The borrow kind bk is inferred by based on how the
676 // This results in the following table for concrete closure
680 // ---------------+----------------------+-------------------------------
681 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
682 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
683 // FnOnce | copied | upvar -> &'up bk
685 let upvar_id = ty::UpvarId { var_id: var_id,
686 closure_expr_id: fn_node_id };
687 let var_ty = self.node_ty(var_id)?;
689 // Mutability of original variable itself
690 let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
692 // Construct the upvar. This represents access to the field
693 // from the environment (perhaps we should eventually desugar
694 // this field further, but it will do for now).
695 let cmt_result = cmt_ {
698 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
704 // If this is a `FnMut` or `Fn` closure, then the above is
705 // conceptually a `&mut` or `&` reference, so we have to add a
707 let cmt_result = match kind {
708 ty::ClosureKind::FnOnce => {
711 ty::ClosureKind::FnMut => {
712 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
714 ty::ClosureKind::Fn => {
715 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
719 // If this is a by-ref capture, then the upvar we loaded is
720 // actually a reference, so we have to add an implicit deref
722 let upvar_id = ty::UpvarId { var_id: var_id,
723 closure_expr_id: fn_node_id };
724 let upvar_capture = self.infcx.upvar_capture(upvar_id).unwrap();
725 let cmt_result = match upvar_capture {
726 ty::UpvarCapture::ByValue => {
729 ty::UpvarCapture::ByRef(upvar_borrow) => {
730 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
734 cat: Categorization::Deref(Rc::new(cmt_result), 0, ptr),
735 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
737 note: NoteUpvarRef(upvar_id)
742 let ret = Rc::new(cmt_result);
743 debug!("cat_upvar ret={:?}", ret);
750 upvar_id: ty::UpvarId,
751 upvar_mutbl: MutabilityCategory,
752 env_borrow_kind: ty::BorrowKind,
753 cmt_result: cmt_<'tcx>)
756 // Look up the node ID of the closure body so we can construct
757 // a free region within it
759 let fn_expr = match self.tcx().hir.find(upvar_id.closure_expr_id) {
760 Some(hir_map::NodeExpr(e)) => e,
765 hir::ExprClosure(.., body_id, _) => body_id.node_id,
770 // Region of environment pointer
771 let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
772 // The environment of a closure is guaranteed to
773 // outlive any bindings introduced in the body of the
775 scope: self.tcx().region_maps.item_extent(fn_body_id),
776 bound_region: ty::BrEnv
779 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
781 let var_ty = cmt_result.ty;
783 // We need to add the env deref. This means
784 // that the above is actually immutable and
785 // has a ref type. However, nothing should
786 // actually look at the type, so we can get
787 // away with stuffing a `TyError` in there
788 // instead of bothering to construct a proper
790 let cmt_result = cmt_ {
792 ty: self.tcx().types.err,
796 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
798 // Issue #18335. If variable is declared as immutable, override the
799 // mutability from the environment and substitute an `&T` anyway.
801 McImmutable => { deref_mutbl = McImmutable; }
802 McDeclared | McInherited => { }
808 cat: Categorization::Deref(Rc::new(cmt_result), 0, env_ptr),
811 note: NoteClosureEnv(upvar_id)
814 debug!("env_deref ret {:?}", ret);
819 /// Returns the lifetime of a temporary created by expr with id `id`.
820 /// This could be `'static` if `id` is part of a constant expression.
821 pub fn temporary_scope(&self, id: ast::NodeId) -> (&'tcx ty::Region, &'tcx ty::Region)
823 let (scope, old_scope) =
824 self.tcx().region_maps.old_and_new_temporary_scope(id);
825 (self.tcx().mk_region(match scope {
826 Some(scope) => ty::ReScope(scope),
829 self.tcx().mk_region(match old_scope {
830 Some(scope) => ty::ReScope(scope),
835 pub fn cat_rvalue_node(&self,
840 let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
843 // Only promote `[T; 0]` before an RFC for rvalue promotions
845 let promotable = match expr_ty.sty {
846 ty::TyArray(_, 0) => true,
847 _ => promotable & false
850 // Compute maximum lifetime of this rvalue. This is 'static if
851 // we can promote to a constant, otherwise equal to enclosing temp
853 let (re, old_re) = if promotable {
854 (self.tcx().mk_region(ty::ReStatic),
855 self.tcx().mk_region(ty::ReStatic))
857 self.temporary_scope(id)
859 let ret = self.cat_rvalue(id, span, re, old_re, expr_ty);
860 debug!("cat_rvalue_node ret {:?}", ret);
864 pub fn cat_rvalue(&self,
867 temp_scope: &'tcx ty::Region,
868 old_temp_scope: &'tcx ty::Region,
869 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
870 let ret = Rc::new(cmt_ {
873 cat:Categorization::Rvalue(temp_scope, old_temp_scope),
878 debug!("cat_rvalue ret {:?}", ret);
882 pub fn cat_field<N:ast_node>(&self,
888 let ret = Rc::new(cmt_ {
891 mutbl: base_cmt.mutbl.inherit(),
892 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
896 debug!("cat_field ret {:?}", ret);
900 pub fn cat_tup_field<N:ast_node>(&self,
906 let ret = Rc::new(cmt_ {
909 mutbl: base_cmt.mutbl.inherit(),
910 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
914 debug!("cat_tup_field ret {:?}", ret);
918 fn cat_deref<N:ast_node>(&self,
922 -> McResult<cmt<'tcx>> {
923 let method_call = ty::MethodCall {
925 autoderef: deref_cnt as u32
927 let method_ty = self.infcx.node_method_ty(method_call);
929 debug!("cat_deref: method_call={:?} method_ty={:?}",
930 method_call, method_ty.map(|ty| ty));
932 let base_cmt = match method_ty {
935 self.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap();
936 self.cat_rvalue_node(node.id(), node.span(), ref_ty)
940 let base_cmt_ty = base_cmt.ty;
941 match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
943 let ret = self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, false);
944 debug!("cat_deref ret {:?}", ret);
948 debug!("Explicit deref of non-derefable type: {:?}",
955 fn cat_deref_common<N:ast_node>(&self,
963 let ptr = match base_cmt.ty.sty {
964 ty::TyAdt(def, ..) if def.is_box() => Unique,
965 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
966 ty::TyRef(r, mt) => {
967 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
968 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
970 ref ty => bug!("unexpected type in cat_deref_common: {:?}", ty)
972 let ret = Rc::new(cmt_ {
975 // For unique ptrs, we inherit mutability from the owning reference.
976 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
977 cat: Categorization::Deref(base_cmt, deref_cnt, ptr),
981 debug!("cat_deref_common ret {:?}", ret);
985 pub fn cat_index<N:ast_node>(&self,
987 mut base_cmt: cmt<'tcx>,
988 context: InteriorOffsetKind)
989 -> McResult<cmt<'tcx>> {
990 //! Creates a cmt for an indexing operation (`[]`).
992 //! One subtle aspect of indexing that may not be
993 //! immediately obvious: for anything other than a fixed-length
994 //! vector, an operation like `x[y]` actually consists of two
995 //! disjoint (from the point of view of borrowck) operations.
996 //! The first is a deref of `x` to create a pointer `p` that points
997 //! at the first element in the array. The second operation is
998 //! an index which adds `y*sizeof(T)` to `p` to obtain the
999 //! pointer to `x[y]`. `cat_index` will produce a resulting
1000 //! cmt containing both this deref and the indexing,
1001 //! presuming that `base_cmt` is not of fixed-length type.
1004 //! - `elt`: the AST node being indexed
1005 //! - `base_cmt`: the cmt of `elt`
1007 let method_call = ty::MethodCall::expr(elt.id());
1008 let method_ty = self.infcx.node_method_ty(method_call);
1010 let (element_ty, element_kind) = match method_ty {
1011 Some(method_ty) => {
1012 let ref_ty = self.overloaded_method_return_ty(method_ty);
1013 base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
1015 (ref_ty.builtin_deref(false, ty::NoPreference).unwrap().ty,
1016 ElementKind::OtherElement)
1019 match base_cmt.ty.builtin_index() {
1020 Some(ty) => (ty, ElementKind::VecElement),
1028 let interior_elem = InteriorElement(context, element_kind);
1030 self.cat_imm_interior(elt, base_cmt.clone(), element_ty, interior_elem);
1031 debug!("cat_index ret {:?}", ret);
1035 pub fn cat_imm_interior<N:ast_node>(&self,
1037 base_cmt: cmt<'tcx>,
1038 interior_ty: Ty<'tcx>,
1039 interior: InteriorKind)
1041 let ret = Rc::new(cmt_ {
1044 mutbl: base_cmt.mutbl.inherit(),
1045 cat: Categorization::Interior(base_cmt, interior),
1049 debug!("cat_imm_interior ret={:?}", ret);
1053 pub fn cat_downcast<N:ast_node>(&self,
1055 base_cmt: cmt<'tcx>,
1056 downcast_ty: Ty<'tcx>,
1059 let ret = Rc::new(cmt_ {
1062 mutbl: base_cmt.mutbl.inherit(),
1063 cat: Categorization::Downcast(base_cmt, variant_did),
1067 debug!("cat_downcast ret={:?}", ret);
1071 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1072 where F: FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat),
1074 self.cat_pattern_(cmt, pat, &mut op)
1077 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1078 fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1079 where F : FnMut(&MemCategorizationContext<'a, 'gcx, 'tcx>, cmt<'tcx>, &hir::Pat)
1081 // Here, `cmt` is the categorization for the value being
1082 // matched and pat is the pattern it is being matched against.
1084 // In general, the way that this works is that we walk down
1085 // the pattern, constructing a cmt that represents the path
1086 // that will be taken to reach the value being matched.
1088 // When we encounter named bindings, we take the cmt that has
1089 // been built up and pass it off to guarantee_valid() so that
1090 // we can be sure that the binding will remain valid for the
1091 // duration of the arm.
1093 // (*2) There is subtlety concerning the correspondence between
1094 // pattern ids and types as compared to *expression* ids and
1095 // types. This is explained briefly. on the definition of the
1096 // type `cmt`, so go off and read what it says there, then
1097 // come back and I'll dive into a bit more detail here. :) OK,
1100 // In general, the id of the cmt should be the node that
1101 // "produces" the value---patterns aren't executable code
1102 // exactly, but I consider them to "execute" when they match a
1103 // value, and I consider them to produce the value that was
1104 // matched. So if you have something like:
1111 // In this case, the cmt and the relevant ids would be:
1113 // CMT Id Type of Id Type of cmt
1116 // ^~~~~~~^ `x` from discr @@int @@int
1117 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1118 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1120 // You can see that the types of the id and the cmt are in
1121 // sync in the first line, because that id is actually the id
1122 // of an expression. But once we get to pattern ids, the types
1123 // step out of sync again. So you'll see below that we always
1124 // get the type of the *subpattern* and use that.
1126 debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1128 op(self, cmt.clone(), pat);
1130 // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1131 // alone) because PatKind::Struct can also refer to variants.
1132 let cmt = match pat.node {
1133 PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1134 PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1135 PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1137 Def::Err => return Err(()),
1138 Def::Variant(variant_did) |
1139 Def::VariantCtor(variant_did, ..) => {
1140 // univariant enums do not need downcasts
1141 let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1142 if !self.tcx().lookup_adt_def(enum_did).is_univariant() {
1143 self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1155 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1156 let def = self.infcx.tables.borrow().qpath_def(qpath, pat.id);
1157 let expected_len = match def {
1158 Def::VariantCtor(def_id, CtorKind::Fn) => {
1159 let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1160 self.tcx().lookup_adt_def(enum_def).variant_with_id(def_id).fields.len()
1162 Def::StructCtor(_, CtorKind::Fn) => {
1163 match self.pat_ty(&pat)?.sty {
1164 ty::TyAdt(adt_def, _) => {
1165 adt_def.struct_variant().fields.len()
1168 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1173 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1174 to variant or struct {:?}", def);
1178 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1179 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1180 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1181 InteriorField(PositionalField(i)));
1182 self.cat_pattern_(subcmt, &subpat, op)?;
1186 PatKind::Struct(_, ref field_pats, _) => {
1187 // {f1: p1, ..., fN: pN}
1188 for fp in field_pats {
1189 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1190 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1191 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1195 PatKind::Binding(.., Some(ref subpat)) => {
1196 self.cat_pattern_(cmt, &subpat, op)?;
1199 PatKind::Tuple(ref subpats, ddpos) => {
1201 let expected_len = match self.pat_ty(&pat)?.sty {
1202 ty::TyTuple(ref tys, _) => tys.len(),
1203 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1205 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1206 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1207 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1208 InteriorField(PositionalField(i)));
1209 self.cat_pattern_(subcmt, &subpat, op)?;
1213 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1214 // box p1, &p1, &mut p1. we can ignore the mutability of
1215 // PatKind::Ref since that information is already contained
1217 let subcmt = self.cat_deref(pat, cmt, 0)?;
1218 self.cat_pattern_(subcmt, &subpat, op)?;
1221 PatKind::Slice(ref before, ref slice, ref after) => {
1222 let context = InteriorOffsetKind::Pattern;
1223 let elt_cmt = self.cat_index(pat, cmt, context)?;
1224 for before_pat in before {
1225 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1227 if let Some(ref slice_pat) = *slice {
1228 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1230 for after_pat in after {
1231 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1235 PatKind::Path(_) | PatKind::Binding(.., None) |
1236 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1244 fn overloaded_method_return_ty(&self,
1245 method_ty: Ty<'tcx>)
1248 // When we process an overloaded `*` or `[]` etc, we often
1249 // need to extract the return type of the method. These method
1250 // types are generated by method resolution and always have
1251 // all late-bound regions fully instantiated, so we just want
1252 // to skip past the binder.
1253 self.tcx().no_late_bound_regions(&method_ty.fn_ret())
1258 #[derive(Clone, Debug)]
1259 pub enum Aliasability {
1260 FreelyAliasable(AliasableReason),
1262 ImmutableUnique(Box<Aliasability>),
1265 #[derive(Copy, Clone, Debug)]
1266 pub enum AliasableReason {
1268 AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
1270 UnaliasableImmutable, // Created as needed upon seeing ImmutableUnique
1275 impl<'tcx> cmt_<'tcx> {
1276 pub fn guarantor(&self) -> cmt<'tcx> {
1277 //! Returns `self` after stripping away any derefs or
1278 //! interior content. The return value is basically the `cmt` which
1279 //! determines how long the value in `self` remains live.
1282 Categorization::Rvalue(..) |
1283 Categorization::StaticItem |
1284 Categorization::Local(..) |
1285 Categorization::Deref(.., UnsafePtr(..)) |
1286 Categorization::Deref(.., BorrowedPtr(..)) |
1287 Categorization::Deref(.., Implicit(..)) |
1288 Categorization::Upvar(..) => {
1289 Rc::new((*self).clone())
1291 Categorization::Downcast(ref b, _) |
1292 Categorization::Interior(ref b, _) |
1293 Categorization::Deref(ref b, _, Unique) => {
1299 /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1300 pub fn freely_aliasable(&self) -> Aliasability {
1301 // Maybe non-obvious: copied upvars can only be considered
1302 // non-aliasable in once closures, since any other kind can be
1303 // aliased and eventually recused.
1306 Categorization::Deref(ref b, _, BorrowedPtr(ty::MutBorrow, _)) |
1307 Categorization::Deref(ref b, _, Implicit(ty::MutBorrow, _)) |
1308 Categorization::Deref(ref b, _, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1309 Categorization::Deref(ref b, _, Implicit(ty::UniqueImmBorrow, _)) |
1310 Categorization::Downcast(ref b, _) |
1311 Categorization::Interior(ref b, _) => {
1312 // Aliasability depends on base cmt
1313 b.freely_aliasable()
1316 Categorization::Deref(ref b, _, Unique) => {
1317 let sub = b.freely_aliasable();
1318 if b.mutbl.is_mutable() {
1319 // Aliasability depends on base cmt alone
1322 // Do not allow mutation through an immutable box.
1323 ImmutableUnique(Box::new(sub))
1327 Categorization::Rvalue(..) |
1328 Categorization::Local(..) |
1329 Categorization::Upvar(..) |
1330 Categorization::Deref(.., UnsafePtr(..)) => { // yes, it's aliasable, but...
1334 Categorization::StaticItem => {
1335 if self.mutbl.is_mutable() {
1336 FreelyAliasable(AliasableStaticMut)
1338 FreelyAliasable(AliasableStatic)
1342 Categorization::Deref(ref base, _, BorrowedPtr(ty::ImmBorrow, _)) |
1343 Categorization::Deref(ref base, _, Implicit(ty::ImmBorrow, _)) => {
1345 Categorization::Upvar(Upvar{ id, .. }) =>
1346 FreelyAliasable(AliasableClosure(id.closure_expr_id)),
1347 _ => FreelyAliasable(AliasableBorrowed)
1353 // Digs down through one or two layers of deref and grabs the cmt
1354 // for the upvar if a note indicates there is one.
1355 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1357 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1358 Some(match self.cat {
1359 Categorization::Deref(ref inner, ..) => {
1361 Categorization::Deref(ref inner, ..) => inner.clone(),
1362 Categorization::Upvar(..) => inner.clone(),
1374 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1376 Categorization::StaticItem => {
1377 "static item".to_string()
1379 Categorization::Rvalue(..) => {
1380 "non-lvalue".to_string()
1382 Categorization::Local(vid) => {
1383 if tcx.hir.is_argument(vid) {
1384 "argument".to_string()
1386 "local variable".to_string()
1389 Categorization::Deref(.., pk) => {
1390 let upvar = self.upvar();
1391 match upvar.as_ref().map(|i| &i.cat) {
1392 Some(&Categorization::Upvar(ref var)) => {
1399 format!("indexed content")
1402 format!("`Box` content")
1405 format!("dereference of raw pointer")
1407 BorrowedPtr(..) => {
1408 format!("borrowed content")
1414 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1417 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1418 "anonymous field".to_string()
1420 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1422 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index,
1424 "indexed content".to_string()
1426 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1428 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern,
1430 "pattern-bound indexed content".to_string()
1432 Categorization::Upvar(ref var) => {
1435 Categorization::Downcast(ref cmt, _) => {
1436 cmt.descriptive_string(tcx)
1442 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1444 write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1452 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1455 Categorization::StaticItem => write!(f, "static"),
1456 Categorization::Rvalue(r, or) => {
1457 write!(f, "rvalue({:?}, {:?})", r, or)
1459 Categorization::Local(id) => {
1460 let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1461 write!(f, "local({})", name)
1463 Categorization::Upvar(upvar) => {
1464 write!(f, "upvar({:?})", upvar)
1466 Categorization::Deref(ref cmt, derefs, ptr) => {
1467 write!(f, "{:?}-{:?}{}->", cmt.cat, ptr, derefs)
1469 Categorization::Interior(ref cmt, interior) => {
1470 write!(f, "{:?}.{:?}", cmt.cat, interior)
1472 Categorization::Downcast(ref cmt, _) => {
1473 write!(f, "{:?}->(enum)", cmt.cat)
1479 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1482 BorrowedPtr(ty::ImmBorrow, _) |
1483 Implicit(ty::ImmBorrow, _) => "&",
1484 BorrowedPtr(ty::MutBorrow, _) |
1485 Implicit(ty::MutBorrow, _) => "&mut",
1486 BorrowedPtr(ty::UniqueImmBorrow, _) |
1487 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1488 UnsafePtr(_) => "*",
1492 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1495 Unique => write!(f, "Box"),
1496 BorrowedPtr(ty::ImmBorrow, ref r) |
1497 Implicit(ty::ImmBorrow, ref r) => {
1498 write!(f, "&{:?}", r)
1500 BorrowedPtr(ty::MutBorrow, ref r) |
1501 Implicit(ty::MutBorrow, ref r) => {
1502 write!(f, "&{:?} mut", r)
1504 BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1505 Implicit(ty::UniqueImmBorrow, ref r) => {
1506 write!(f, "&{:?} uniq", r)
1508 UnsafePtr(_) => write!(f, "*")
1513 impl fmt::Debug for InteriorKind {
1514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1516 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1517 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1518 InteriorElement(..) => write!(f, "[]"),
1523 impl fmt::Debug for Upvar {
1524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1525 write!(f, "{:?}/{:?}", self.id, self.kind)
1529 impl fmt::Display for Upvar {
1530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1531 let kind = match self.kind {
1532 ty::ClosureKind::Fn => "Fn",
1533 ty::ClosureKind::FnMut => "FnMut",
1534 ty::ClosureKind::FnOnce => "FnOnce",
1536 write!(f, "captured outer variable in an `{}` closure", kind)