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::MutabilityCategory::*;
67 pub use self::AliasableReason::*;
68 pub use self::Note::*;
70 use self::Aliasability::*;
72 use middle::region::RegionMaps;
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};
79 use ty::fold::TypeFoldable;
81 use hir::{MutImmutable, MutMutable, PatKind};
82 use hir::pat_util::EnumerateAndAdjustIterator;
90 #[derive(Clone, PartialEq)]
91 pub enum Categorization<'tcx> {
92 Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
94 Upvar(Upvar), // upvar referenced by closure env
95 Local(ast::NodeId), // local variable
96 Deref(cmt<'tcx>, 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, ty::Region<'tcx>),
120 UnsafePtr(hir::Mutability),
122 /// Implicit deref of the `&T` that results from an overloaded index `[]`.
123 Implicit(ty::BorrowKind, ty::Region<'tcx>),
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),
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 MutabilityCategory {
148 McImmutable, // Immutable.
149 McDeclared, // Directly declared as mutable.
150 McInherited, // Inherited from the fact that owner is mutable.
153 // A note about the provenance of a `cmt`. This is used for
154 // special-case handling of upvars such as mutability inference.
155 // Upvar categorization can generate a variable number of nested
156 // derefs. The note allows detecting them without deep pattern
157 // matching on the categorization.
158 #[derive(Clone, Copy, PartialEq, Debug)]
160 NoteClosureEnv(ty::UpvarId), // Deref through closure env
161 NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
162 NoteNone // Nothing special
165 // `cmt`: "Category, Mutability, and Type".
167 // a complete categorization of a value indicating where it originated
168 // and how it is located, as well as the mutability of the memory in
169 // which the value is stored.
171 // *WARNING* The field `cmt.type` is NOT necessarily the same as the
172 // result of `node_id_to_type(cmt.id)`. This is because the `id` is
173 // always the `id` of the node producing the type; in an expression
174 // like `*x`, the type of this deref node is the deref'd type (`T`),
175 // but in a pattern like `@x`, the `@x` pattern is again a
176 // dereference, but its type is the type *before* the dereference
177 // (`@T`). So use `cmt.ty` to find the type of the value in a consistent
178 // fashion. For more details, see the method `cat_pattern`
179 #[derive(Clone, PartialEq)]
180 pub struct cmt_<'tcx> {
181 pub id: ast::NodeId, // id of expr/pat producing this value
182 pub span: Span, // span of same expr/pat
183 pub cat: Categorization<'tcx>, // categorization of expr
184 pub mutbl: MutabilityCategory, // mutability of expr as lvalue
185 pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
186 pub note: Note, // Note about the provenance of this cmt
189 pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
191 pub enum ImmutabilityBlame<'tcx> {
192 ImmLocal(ast::NodeId),
193 ClosureEnv(ast::NodeId),
194 LocalDeref(ast::NodeId),
195 AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
198 impl<'tcx> cmt_<'tcx> {
199 fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
201 let adt_def = match self.ty.sty {
202 ty::TyAdt(def, _) => def,
203 ty::TyTuple(..) => return None,
204 // closures get `Categorization::Upvar` rather than `Categorization::Interior`
205 _ => bug!("interior cmt {:?} is not an ADT", self)
207 let variant_def = match self.cat {
208 Categorization::Downcast(_, variant_did) => {
209 adt_def.variant_with_id(variant_did)
212 assert!(adt_def.is_univariant());
216 let field_def = match field_name {
217 NamedField(name) => variant_def.field_named(name),
218 PositionalField(idx) => &variant_def.fields[idx]
220 Some((adt_def, field_def))
223 pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
225 Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) |
226 Categorization::Deref(ref base_cmt, Implicit(ty::ImmBorrow, _)) => {
227 // try to figure out where the immutable reference came from
229 Categorization::Local(node_id) =>
230 Some(ImmutabilityBlame::LocalDeref(node_id)),
231 Categorization::Interior(ref base_cmt, InteriorField(field_name)) => {
232 base_cmt.resolve_field(field_name).map(|(adt_def, field_def)| {
233 ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
236 Categorization::Upvar(Upvar { id, .. }) => {
237 if let NoteClosureEnv(..) = self.note {
238 Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
246 Categorization::Local(node_id) => {
247 Some(ImmutabilityBlame::ImmLocal(node_id))
249 Categorization::Rvalue(..) |
250 Categorization::Upvar(..) |
251 Categorization::Deref(_, UnsafePtr(..)) => {
252 // This should not be reachable up to inference limitations.
255 Categorization::Interior(ref base_cmt, _) |
256 Categorization::Downcast(ref base_cmt, _) |
257 Categorization::Deref(ref base_cmt, _) => {
258 base_cmt.immutability_blame()
260 Categorization::StaticItem => {
261 // Do we want to do something here?
269 fn id(&self) -> ast::NodeId;
270 fn span(&self) -> Span;
273 impl ast_node for hir::Expr {
274 fn id(&self) -> ast::NodeId { self.id }
275 fn span(&self) -> Span { self.span }
278 impl ast_node for hir::Pat {
279 fn id(&self) -> ast::NodeId { self.id }
280 fn span(&self) -> Span { self.span }
284 pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
285 pub infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
286 pub region_maps: &'a RegionMaps,
287 pub tables: &'a ty::TypeckTables<'tcx>,
290 pub type McResult<T> = Result<T, ()>;
292 impl MutabilityCategory {
293 pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
295 MutImmutable => McImmutable,
296 MutMutable => McDeclared
298 debug!("MutabilityCategory::{}({:?}) => {:?}",
299 "from_mutbl", m, ret);
303 pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
304 let ret = match borrow_kind {
305 ty::ImmBorrow => McImmutable,
306 ty::UniqueImmBorrow => McImmutable,
307 ty::MutBorrow => McDeclared,
309 debug!("MutabilityCategory::{}({:?}) => {:?}",
310 "from_borrow_kind", borrow_kind, ret);
314 fn from_pointer_kind(base_mutbl: MutabilityCategory,
315 ptr: PointerKind) -> MutabilityCategory {
316 let ret = match ptr {
320 BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
321 MutabilityCategory::from_borrow_kind(borrow_kind)
324 MutabilityCategory::from_mutbl(m)
327 debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
328 "from_pointer_kind", base_mutbl, ptr, ret);
332 fn from_local(tcx: TyCtxt, id: ast::NodeId) -> MutabilityCategory {
333 let ret = match tcx.hir.get(id) {
334 hir_map::NodeLocal(p) => match p.node {
335 PatKind::Binding(bind_mode, ..) => {
336 if bind_mode == hir::BindByValue(hir::MutMutable) {
342 _ => span_bug!(p.span, "expected identifier pattern")
344 _ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
346 debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
347 "from_local", id, ret);
351 pub fn inherit(&self) -> MutabilityCategory {
352 let ret = match *self {
353 McImmutable => McImmutable,
354 McDeclared => McInherited,
355 McInherited => McInherited,
357 debug!("{:?}.inherit() => {:?}", self, ret);
361 pub fn is_mutable(&self) -> bool {
362 let ret = match *self {
363 McImmutable => false,
367 debug!("{:?}.is_mutable() => {:?}", self, ret);
371 pub fn is_immutable(&self) -> bool {
372 let ret = match *self {
374 McDeclared | McInherited => false
376 debug!("{:?}.is_immutable() => {:?}", self, ret);
380 pub fn to_user_str(&self) -> &'static str {
382 McDeclared | McInherited => "mutable",
383 McImmutable => "immutable",
388 impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
389 /// Context should be the `DefId` we use to fetch region-maps.
390 pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
391 region_maps: &'a RegionMaps,
392 tables: &'a ty::TypeckTables<'tcx>)
393 -> MemCategorizationContext<'a, 'gcx, 'tcx> {
394 MemCategorizationContext { infcx, region_maps, tables }
397 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
401 fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
402 where T: TypeFoldable<'tcx>
404 self.infcx.resolve_type_vars_if_possible(value)
407 fn is_tainted_by_errors(&self) -> bool {
408 self.infcx.is_tainted_by_errors()
411 fn resolve_type_vars_or_error(&self,
413 ty: Option<Ty<'tcx>>)
414 -> McResult<Ty<'tcx>> {
417 let ty = self.resolve_type_vars_if_possible(&ty);
418 if ty.references_error() || ty.is_ty_var() {
419 debug!("resolve_type_vars_or_error: error from {:?}", ty);
426 None if self.is_tainted_by_errors() => Err(()),
428 bug!("no type for node {}: {} in mem_categorization",
429 id, self.tcx().hir.node_to_string(id));
434 pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
435 self.resolve_type_vars_or_error(id, self.tables.node_id_to_type_opt(id))
438 pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
439 self.resolve_type_vars_or_error(expr.id, self.tables.expr_ty_opt(expr))
442 pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
443 self.resolve_type_vars_or_error(expr.id, self.tables.expr_ty_adjusted_opt(expr))
446 fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
447 let base_ty = self.node_ty(pat.id)?;
448 // FIXME (Issue #18207): This code detects whether we are
449 // looking at a `ref x`, and if so, figures out what the type
450 // *being borrowed* is. But ideally we would put in a more
451 // fundamental fix to this conflated use of the node id.
452 let ret_ty = match pat.node {
453 PatKind::Binding(hir::BindByRef(_), ..) => {
454 // a bind-by-ref means that the base_ty will be the type of the ident itself,
455 // but what we want here is the type of the underlying value being borrowed.
456 // So peel off one-level, turning the &T into T.
457 match base_ty.builtin_deref(false, ty::NoPreference) {
460 debug!("By-ref binding of non-derefable type {:?}", base_ty);
467 debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
468 pat, base_ty, ret_ty);
472 pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
473 // This recursion helper avoids going through *too many*
474 // adjustments, since *only* non-overloaded deref recurses.
475 fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
477 adjustments: &[adjustment::Adjustment<'tcx>])
478 -> McResult<cmt<'tcx>> {
479 match adjustments.split_last() {
480 None => mc.cat_expr_unadjusted(expr),
481 Some((adjustment, previous)) => {
482 mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
487 helper(self, expr, self.tables.expr_adjustments(expr))
490 pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
492 adjustment: &adjustment::Adjustment<'tcx>)
493 -> McResult<cmt<'tcx>> {
494 self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
497 fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
499 adjustment: &adjustment::Adjustment<'tcx>)
500 -> McResult<cmt<'tcx>>
501 where F: FnOnce() -> McResult<cmt<'tcx>>
503 debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
504 let target = self.resolve_type_vars_if_possible(&adjustment.target);
505 match adjustment.kind {
506 adjustment::Adjust::Deref(overloaded) => {
507 // Equivalent to *expr or something similar.
508 let base = if let Some(deref) = overloaded {
509 let ref_ty = self.tcx().mk_ref(deref.region, ty::TypeAndMut {
513 self.cat_rvalue_node(expr.id, expr.span, ref_ty)
517 self.cat_deref(expr, base, false)
520 adjustment::Adjust::NeverToAny |
521 adjustment::Adjust::ReifyFnPointer |
522 adjustment::Adjust::UnsafeFnPointer |
523 adjustment::Adjust::ClosureFnPointer |
524 adjustment::Adjust::MutToConstPointer |
525 adjustment::Adjust::Borrow(_) |
526 adjustment::Adjust::Unsize => {
527 // Result is an rvalue.
528 Ok(self.cat_rvalue_node(expr.id, expr.span, target))
533 pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
534 debug!("cat_expr: id={} expr={:?}", expr.id, expr);
536 let expr_ty = self.expr_ty(expr)?;
538 hir::ExprUnary(hir::UnDeref, ref e_base) => {
539 if self.tables.is_method_call(expr) {
540 self.cat_overloaded_lvalue(expr, e_base, false)
542 let base_cmt = self.cat_expr(&e_base)?;
543 self.cat_deref(expr, base_cmt, false)
547 hir::ExprField(ref base, f_name) => {
548 let base_cmt = self.cat_expr(&base)?;
549 debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
553 Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
556 hir::ExprTupField(ref base, idx) => {
557 let base_cmt = self.cat_expr(&base)?;
558 Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
561 hir::ExprIndex(ref base, _) => {
562 if self.tables.is_method_call(expr) {
563 // If this is an index implemented by a method call, then it
564 // will include an implicit deref of the result.
565 // The call to index() returns a `&T` value, which
566 // is an rvalue. That is what we will be
568 self.cat_overloaded_lvalue(expr, base, true)
570 let base_cmt = self.cat_expr(&base)?;
571 self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
575 hir::ExprPath(ref qpath) => {
576 let def = self.tables.qpath_def(qpath, expr.id);
577 self.cat_def(expr.id, expr.span, expr_ty, def)
580 hir::ExprType(ref e, _) => {
584 hir::ExprAddrOf(..) | hir::ExprCall(..) |
585 hir::ExprAssign(..) | hir::ExprAssignOp(..) |
586 hir::ExprClosure(..) | hir::ExprRet(..) |
588 hir::ExprMethodCall(..) | hir::ExprCast(..) |
589 hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
590 hir::ExprBinary(..) | hir::ExprWhile(..) |
591 hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
592 hir::ExprLit(..) | hir::ExprBreak(..) |
593 hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
594 hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
595 Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
600 pub fn cat_def(&self,
605 -> McResult<cmt<'tcx>> {
606 debug!("cat_def: id={} expr={:?} def={:?}",
610 Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
611 Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
612 Ok(self.cat_rvalue_node(id, span, expr_ty))
615 Def::Static(_, mutbl) => {
619 cat:Categorization::StaticItem,
620 mutbl: if mutbl { McDeclared } else { McImmutable},
626 Def::Upvar(def_id, _, fn_node_id) => {
627 let var_id = self.tcx().hir.as_local_node_id(def_id).unwrap();
628 self.cat_upvar(id, span, var_id, fn_node_id)
631 Def::Local(def_id) => {
632 let vid = self.tcx().hir.as_local_node_id(def_id).unwrap();
636 cat: Categorization::Local(vid),
637 mutbl: MutabilityCategory::from_local(self.tcx(), vid),
643 def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
647 // Categorize an upvar, complete with invisible derefs of closure
648 // environment and upvar reference as appropriate.
653 fn_node_id: ast::NodeId)
654 -> McResult<cmt<'tcx>>
656 // An upvar can have up to 3 components. We translate first to a
657 // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
658 // field from the environment.
660 // `Categorization::Upvar`. Next, we add a deref through the implicit
661 // environment pointer with an anonymous free region 'env and
662 // appropriate borrow kind for closure kinds that take self by
663 // reference. Finally, if the upvar was captured
664 // by-reference, we add a deref through that reference. The
665 // region of this reference is an inference variable 'up that
666 // was previously generated and recorded in the upvar borrow
667 // map. The borrow kind bk is inferred by based on how the
670 // This results in the following table for concrete closure
674 // ---------------+----------------------+-------------------------------
675 // Fn | copied -> &'env | upvar -> &'env -> &'up bk
676 // FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
677 // FnOnce | copied | upvar -> &'up bk
679 let kind = match self.tables.closure_kinds.get(&fn_node_id) {
680 Some(&(kind, _)) => kind,
681 None => span_bug!(span, "missing closure kind")
684 let upvar_id = ty::UpvarId { var_id: var_id,
685 closure_expr_id: fn_node_id };
686 let var_ty = self.node_ty(var_id)?;
688 // Mutability of original variable itself
689 let var_mutbl = MutabilityCategory::from_local(self.tcx(), var_id);
691 // Construct the upvar. This represents access to the field
692 // from the environment (perhaps we should eventually desugar
693 // this field further, but it will do for now).
694 let cmt_result = cmt_ {
697 cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
703 // If this is a `FnMut` or `Fn` closure, then the above is
704 // conceptually a `&mut` or `&` reference, so we have to add a
706 let cmt_result = match kind {
707 ty::ClosureKind::FnOnce => {
710 ty::ClosureKind::FnMut => {
711 self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
713 ty::ClosureKind::Fn => {
714 self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
718 // If this is a by-ref capture, then the upvar we loaded is
719 // actually a reference, so we have to add an implicit deref
721 let upvar_id = ty::UpvarId { var_id: var_id,
722 closure_expr_id: fn_node_id };
723 let upvar_capture = self.tables.upvar_capture(upvar_id);
724 let cmt_result = match upvar_capture {
725 ty::UpvarCapture::ByValue => {
728 ty::UpvarCapture::ByRef(upvar_borrow) => {
729 let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
733 cat: Categorization::Deref(Rc::new(cmt_result), ptr),
734 mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
736 note: NoteUpvarRef(upvar_id)
741 let ret = Rc::new(cmt_result);
742 debug!("cat_upvar ret={:?}", ret);
749 upvar_id: ty::UpvarId,
750 upvar_mutbl: MutabilityCategory,
751 env_borrow_kind: ty::BorrowKind,
752 cmt_result: cmt_<'tcx>)
755 // Region of environment pointer
756 let env_region = self.tcx().mk_region(ty::ReFree(ty::FreeRegion {
757 // The environment of a closure is guaranteed to
758 // outlive any bindings introduced in the body of the
760 scope: self.tcx().hir.local_def_id(upvar_id.closure_expr_id),
761 bound_region: ty::BrEnv
764 let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
766 let var_ty = cmt_result.ty;
768 // We need to add the env deref. This means
769 // that the above is actually immutable and
770 // has a ref type. However, nothing should
771 // actually look at the type, so we can get
772 // away with stuffing a `TyError` in there
773 // instead of bothering to construct a proper
775 let cmt_result = cmt_ {
777 ty: self.tcx().types.err,
781 let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
783 // Issue #18335. If variable is declared as immutable, override the
784 // mutability from the environment and substitute an `&T` anyway.
786 McImmutable => { deref_mutbl = McImmutable; }
787 McDeclared | McInherited => { }
793 cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
796 note: NoteClosureEnv(upvar_id)
799 debug!("env_deref ret {:?}", ret);
804 /// Returns the lifetime of a temporary created by expr with id `id`.
805 /// This could be `'static` if `id` is part of a constant expression.
806 pub fn temporary_scope(&self, id: ast::NodeId) -> ty::Region<'tcx>
808 let scope = self.region_maps.temporary_scope(id);
809 self.tcx().mk_region(match scope {
810 Some(scope) => ty::ReScope(scope),
815 pub fn cat_rvalue_node(&self,
820 let promotable = self.tcx().rvalue_promotable_to_static.borrow().get(&id).cloned()
823 // When the corresponding feature isn't toggled, only promote `[T; 0]`.
824 let promotable = match expr_ty.sty {
825 ty::TyArray(_, 0) => true,
826 _ => promotable && self.tcx().sess.features.borrow().rvalue_static_promotion,
829 // Compute maximum lifetime of this rvalue. This is 'static if
830 // we can promote to a constant, otherwise equal to enclosing temp
832 let re = if promotable {
833 self.tcx().types.re_static
835 self.temporary_scope(id)
837 let ret = self.cat_rvalue(id, span, re, expr_ty);
838 debug!("cat_rvalue_node ret {:?}", ret);
842 pub fn cat_rvalue(&self,
845 temp_scope: ty::Region<'tcx>,
846 expr_ty: Ty<'tcx>) -> cmt<'tcx> {
847 let ret = Rc::new(cmt_ {
850 cat:Categorization::Rvalue(temp_scope),
855 debug!("cat_rvalue ret {:?}", ret);
859 pub fn cat_field<N:ast_node>(&self,
865 let ret = Rc::new(cmt_ {
868 mutbl: base_cmt.mutbl.inherit(),
869 cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
873 debug!("cat_field ret {:?}", ret);
877 pub fn cat_tup_field<N:ast_node>(&self,
883 let ret = Rc::new(cmt_ {
886 mutbl: base_cmt.mutbl.inherit(),
887 cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
891 debug!("cat_tup_field ret {:?}", ret);
895 fn cat_overloaded_lvalue(&self,
899 -> McResult<cmt<'tcx>> {
900 debug!("cat_overloaded_lvalue: implicit={}", implicit);
902 // Reconstruct the output assuming it's a reference with the
903 // same region and mutability as the receiver. This holds for
904 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
905 let lvalue_ty = self.expr_ty(expr)?;
906 let base_ty = self.expr_ty_adjusted(base)?;
908 let (region, mutbl) = match base_ty.sty {
909 ty::TyRef(region, mt) => (region, mt.mutbl),
911 span_bug!(expr.span, "cat_overloaded_lvalue: base is not a reference")
914 let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut {
919 let base_cmt = self.cat_rvalue_node(expr.id, expr.span, ref_ty);
920 self.cat_deref(expr, base_cmt, implicit)
923 pub fn cat_deref<N:ast_node>(&self,
927 -> McResult<cmt<'tcx>> {
928 debug!("cat_deref: base_cmt={:?}", base_cmt);
930 let base_cmt_ty = base_cmt.ty;
931 let deref_ty = match base_cmt_ty.builtin_deref(true, ty::NoPreference) {
934 debug!("Explicit deref of non-derefable type: {:?}",
940 let ptr = match base_cmt.ty.sty {
941 ty::TyAdt(def, ..) if def.is_box() => Unique,
942 ty::TyRawPtr(ref mt) => UnsafePtr(mt.mutbl),
943 ty::TyRef(r, mt) => {
944 let bk = ty::BorrowKind::from_mutbl(mt.mutbl);
945 if implicit { Implicit(bk, r) } else { BorrowedPtr(bk, r) }
947 ref ty => bug!("unexpected type in cat_deref: {:?}", ty)
949 let ret = Rc::new(cmt_ {
952 // For unique ptrs, we inherit mutability from the owning reference.
953 mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
954 cat: Categorization::Deref(base_cmt, ptr),
958 debug!("cat_deref ret {:?}", ret);
962 fn cat_index<N:ast_node>(&self,
965 element_ty: Ty<'tcx>,
966 context: InteriorOffsetKind)
967 -> McResult<cmt<'tcx>> {
968 //! Creates a cmt for an indexing operation (`[]`).
970 //! One subtle aspect of indexing that may not be
971 //! immediately obvious: for anything other than a fixed-length
972 //! vector, an operation like `x[y]` actually consists of two
973 //! disjoint (from the point of view of borrowck) operations.
974 //! The first is a deref of `x` to create a pointer `p` that points
975 //! at the first element in the array. The second operation is
976 //! an index which adds `y*sizeof(T)` to `p` to obtain the
977 //! pointer to `x[y]`. `cat_index` will produce a resulting
978 //! cmt containing both this deref and the indexing,
979 //! presuming that `base_cmt` is not of fixed-length type.
982 //! - `elt`: the AST node being indexed
983 //! - `base_cmt`: the cmt of `elt`
985 let interior_elem = InteriorElement(context);
987 self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
988 debug!("cat_index ret {:?}", ret);
992 pub fn cat_imm_interior<N:ast_node>(&self,
995 interior_ty: Ty<'tcx>,
996 interior: InteriorKind)
998 let ret = Rc::new(cmt_ {
1001 mutbl: base_cmt.mutbl.inherit(),
1002 cat: Categorization::Interior(base_cmt, interior),
1006 debug!("cat_imm_interior ret={:?}", ret);
1010 pub fn cat_downcast<N:ast_node>(&self,
1012 base_cmt: cmt<'tcx>,
1013 downcast_ty: Ty<'tcx>,
1016 let ret = Rc::new(cmt_ {
1019 mutbl: base_cmt.mutbl.inherit(),
1020 cat: Categorization::Downcast(base_cmt, variant_did),
1024 debug!("cat_downcast ret={:?}", ret);
1028 pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
1029 where F: FnMut(cmt<'tcx>, &hir::Pat),
1031 self.cat_pattern_(cmt, pat, &mut op)
1034 // FIXME(#19596) This is a workaround, but there should be a better way to do this
1035 fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
1036 where F : FnMut(cmt<'tcx>, &hir::Pat)
1038 // Here, `cmt` is the categorization for the value being
1039 // matched and pat is the pattern it is being matched against.
1041 // In general, the way that this works is that we walk down
1042 // the pattern, constructing a cmt that represents the path
1043 // that will be taken to reach the value being matched.
1045 // When we encounter named bindings, we take the cmt that has
1046 // been built up and pass it off to guarantee_valid() so that
1047 // we can be sure that the binding will remain valid for the
1048 // duration of the arm.
1050 // (*2) There is subtlety concerning the correspondence between
1051 // pattern ids and types as compared to *expression* ids and
1052 // types. This is explained briefly. on the definition of the
1053 // type `cmt`, so go off and read what it says there, then
1054 // come back and I'll dive into a bit more detail here. :) OK,
1057 // In general, the id of the cmt should be the node that
1058 // "produces" the value---patterns aren't executable code
1059 // exactly, but I consider them to "execute" when they match a
1060 // value, and I consider them to produce the value that was
1061 // matched. So if you have something like:
1068 // In this case, the cmt and the relevant ids would be:
1070 // CMT Id Type of Id Type of cmt
1073 // ^~~~~~~^ `x` from discr @@int @@int
1074 // ^~~~~~~~~~^ `@@y` pattern node @@int @int
1075 // ^~~~~~~~~~~~~^ `@y` pattern node @int int
1077 // You can see that the types of the id and the cmt are in
1078 // sync in the first line, because that id is actually the id
1079 // of an expression. But once we get to pattern ids, the types
1080 // step out of sync again. So you'll see below that we always
1081 // get the type of the *subpattern* and use that.
1083 debug!("cat_pattern: {:?} cmt={:?}", pat, cmt);
1085 op(cmt.clone(), pat);
1087 // Note: This goes up here (rather than within the PatKind::TupleStruct arm
1088 // alone) because PatKind::Struct can also refer to variants.
1089 let cmt = match pat.node {
1090 PatKind::Path(hir::QPath::Resolved(_, ref path)) |
1091 PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) |
1092 PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => {
1095 debug!("access to unresolvable pattern {:?}", pat);
1098 Def::Variant(variant_did) |
1099 Def::VariantCtor(variant_did, ..) => {
1100 // univariant enums do not need downcasts
1101 let enum_did = self.tcx().parent_def_id(variant_did).unwrap();
1102 if !self.tcx().adt_def(enum_did).is_univariant() {
1103 self.cat_downcast(pat, cmt.clone(), cmt.ty, variant_did)
1115 PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
1116 let def = self.tables.qpath_def(qpath, pat.id);
1117 let expected_len = match def {
1118 Def::VariantCtor(def_id, CtorKind::Fn) => {
1119 let enum_def = self.tcx().parent_def_id(def_id).unwrap();
1120 self.tcx().adt_def(enum_def).variant_with_id(def_id).fields.len()
1122 Def::StructCtor(_, CtorKind::Fn) => {
1123 match self.pat_ty(&pat)?.sty {
1124 ty::TyAdt(adt_def, _) => {
1125 adt_def.struct_variant().fields.len()
1128 span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
1133 span_bug!(pat.span, "tuple struct pattern didn't resolve \
1134 to variant or struct {:?}", def);
1138 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1139 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1140 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1141 InteriorField(PositionalField(i)));
1142 self.cat_pattern_(subcmt, &subpat, op)?;
1146 PatKind::Struct(_, ref field_pats, _) => {
1147 // {f1: p1, ..., fN: pN}
1148 for fp in field_pats {
1149 let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
1150 let cmt_field = self.cat_field(pat, cmt.clone(), fp.node.name, field_ty);
1151 self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
1155 PatKind::Binding(.., Some(ref subpat)) => {
1156 self.cat_pattern_(cmt, &subpat, op)?;
1159 PatKind::Tuple(ref subpats, ddpos) => {
1161 let expected_len = match self.pat_ty(&pat)?.sty {
1162 ty::TyTuple(ref tys, _) => tys.len(),
1163 ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
1165 for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
1166 let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
1167 let subcmt = self.cat_imm_interior(pat, cmt.clone(), subpat_ty,
1168 InteriorField(PositionalField(i)));
1169 self.cat_pattern_(subcmt, &subpat, op)?;
1173 PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
1174 // box p1, &p1, &mut p1. we can ignore the mutability of
1175 // PatKind::Ref since that information is already contained
1177 let subcmt = self.cat_deref(pat, cmt, false)?;
1178 self.cat_pattern_(subcmt, &subpat, op)?;
1181 PatKind::Slice(ref before, ref slice, ref after) => {
1182 let element_ty = match cmt.ty.builtin_index() {
1185 debug!("Explicit index of non-indexable type {:?}", cmt);
1189 let context = InteriorOffsetKind::Pattern;
1190 let elt_cmt = self.cat_index(pat, cmt, element_ty, context)?;
1191 for before_pat in before {
1192 self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
1194 if let Some(ref slice_pat) = *slice {
1195 self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
1197 for after_pat in after {
1198 self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
1202 PatKind::Path(_) | PatKind::Binding(.., None) |
1203 PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
1212 #[derive(Clone, Debug)]
1213 pub enum Aliasability {
1214 FreelyAliasable(AliasableReason),
1216 ImmutableUnique(Box<Aliasability>),
1219 #[derive(Copy, Clone, Debug)]
1220 pub enum AliasableReason {
1226 impl<'tcx> cmt_<'tcx> {
1227 pub fn guarantor(&self) -> cmt<'tcx> {
1228 //! Returns `self` after stripping away any derefs or
1229 //! interior content. The return value is basically the `cmt` which
1230 //! determines how long the value in `self` remains live.
1233 Categorization::Rvalue(..) |
1234 Categorization::StaticItem |
1235 Categorization::Local(..) |
1236 Categorization::Deref(_, UnsafePtr(..)) |
1237 Categorization::Deref(_, BorrowedPtr(..)) |
1238 Categorization::Deref(_, Implicit(..)) |
1239 Categorization::Upvar(..) => {
1240 Rc::new((*self).clone())
1242 Categorization::Downcast(ref b, _) |
1243 Categorization::Interior(ref b, _) |
1244 Categorization::Deref(ref b, Unique) => {
1250 /// Returns `FreelyAliasable(_)` if this lvalue represents a freely aliasable pointer type.
1251 pub fn freely_aliasable(&self) -> Aliasability {
1252 // Maybe non-obvious: copied upvars can only be considered
1253 // non-aliasable in once closures, since any other kind can be
1254 // aliased and eventually recused.
1257 Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
1258 Categorization::Deref(ref b, Implicit(ty::MutBorrow, _)) |
1259 Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
1260 Categorization::Deref(ref b, Implicit(ty::UniqueImmBorrow, _)) |
1261 Categorization::Deref(ref b, Unique) |
1262 Categorization::Downcast(ref b, _) |
1263 Categorization::Interior(ref b, _) => {
1264 // Aliasability depends on base cmt
1265 b.freely_aliasable()
1268 Categorization::Rvalue(..) |
1269 Categorization::Local(..) |
1270 Categorization::Upvar(..) |
1271 Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
1275 Categorization::StaticItem => {
1276 if self.mutbl.is_mutable() {
1277 FreelyAliasable(AliasableStaticMut)
1279 FreelyAliasable(AliasableStatic)
1283 Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) |
1284 Categorization::Deref(_, Implicit(ty::ImmBorrow, _)) => {
1285 FreelyAliasable(AliasableBorrowed)
1290 // Digs down through one or two layers of deref and grabs the cmt
1291 // for the upvar if a note indicates there is one.
1292 pub fn upvar(&self) -> Option<cmt<'tcx>> {
1294 NoteClosureEnv(..) | NoteUpvarRef(..) => {
1295 Some(match self.cat {
1296 Categorization::Deref(ref inner, _) => {
1298 Categorization::Deref(ref inner, _) => inner.clone(),
1299 Categorization::Upvar(..) => inner.clone(),
1311 pub fn descriptive_string(&self, tcx: TyCtxt) -> String {
1313 Categorization::StaticItem => {
1314 "static item".to_string()
1316 Categorization::Rvalue(..) => {
1317 "non-lvalue".to_string()
1319 Categorization::Local(vid) => {
1320 if tcx.hir.is_argument(vid) {
1321 "argument".to_string()
1323 "local variable".to_string()
1326 Categorization::Deref(_, pk) => {
1327 let upvar = self.upvar();
1328 match upvar.as_ref().map(|i| &i.cat) {
1329 Some(&Categorization::Upvar(ref var)) => {
1336 format!("indexed content")
1339 format!("`Box` content")
1342 format!("dereference of raw pointer")
1344 BorrowedPtr(..) => {
1345 format!("borrowed content")
1351 Categorization::Interior(_, InteriorField(NamedField(_))) => {
1354 Categorization::Interior(_, InteriorField(PositionalField(_))) => {
1355 "anonymous field".to_string()
1357 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
1358 "indexed content".to_string()
1360 Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
1361 "pattern-bound indexed content".to_string()
1363 Categorization::Upvar(ref var) => {
1366 Categorization::Downcast(ref cmt, _) => {
1367 cmt.descriptive_string(tcx)
1373 impl<'tcx> fmt::Debug for cmt_<'tcx> {
1374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1375 write!(f, "{{{:?} id:{} m:{:?} ty:{:?}}}",
1383 impl<'tcx> fmt::Debug for Categorization<'tcx> {
1384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1386 Categorization::StaticItem => write!(f, "static"),
1387 Categorization::Rvalue(r) => { write!(f, "rvalue({:?})", r) }
1388 Categorization::Local(id) => {
1389 let name = ty::tls::with(|tcx| tcx.local_var_name_str(id));
1390 write!(f, "local({})", name)
1392 Categorization::Upvar(upvar) => {
1393 write!(f, "upvar({:?})", upvar)
1395 Categorization::Deref(ref cmt, ptr) => {
1396 write!(f, "{:?}-{:?}->", cmt.cat, ptr)
1398 Categorization::Interior(ref cmt, interior) => {
1399 write!(f, "{:?}.{:?}", cmt.cat, interior)
1401 Categorization::Downcast(ref cmt, _) => {
1402 write!(f, "{:?}->(enum)", cmt.cat)
1408 pub fn ptr_sigil(ptr: PointerKind) -> &'static str {
1411 BorrowedPtr(ty::ImmBorrow, _) |
1412 Implicit(ty::ImmBorrow, _) => "&",
1413 BorrowedPtr(ty::MutBorrow, _) |
1414 Implicit(ty::MutBorrow, _) => "&mut",
1415 BorrowedPtr(ty::UniqueImmBorrow, _) |
1416 Implicit(ty::UniqueImmBorrow, _) => "&unique",
1417 UnsafePtr(_) => "*",
1421 impl<'tcx> fmt::Debug for PointerKind<'tcx> {
1422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1424 Unique => write!(f, "Box"),
1425 BorrowedPtr(ty::ImmBorrow, ref r) |
1426 Implicit(ty::ImmBorrow, ref r) => {
1427 write!(f, "&{:?}", r)
1429 BorrowedPtr(ty::MutBorrow, ref r) |
1430 Implicit(ty::MutBorrow, ref r) => {
1431 write!(f, "&{:?} mut", r)
1433 BorrowedPtr(ty::UniqueImmBorrow, ref r) |
1434 Implicit(ty::UniqueImmBorrow, ref r) => {
1435 write!(f, "&{:?} uniq", r)
1437 UnsafePtr(_) => write!(f, "*")
1442 impl fmt::Debug for InteriorKind {
1443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1445 InteriorField(NamedField(fld)) => write!(f, "{}", fld),
1446 InteriorField(PositionalField(i)) => write!(f, "#{}", i),
1447 InteriorElement(..) => write!(f, "[]"),
1452 impl fmt::Debug for Upvar {
1453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1454 write!(f, "{:?}/{:?}", self.id, self.kind)
1458 impl fmt::Display for Upvar {
1459 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1460 let kind = match self.kind {
1461 ty::ClosureKind::Fn => "Fn",
1462 ty::ClosureKind::FnMut => "FnMut",
1463 ty::ClosureKind::FnOnce => "FnOnce",
1465 write!(f, "captured outer variable in an `{}` closure", kind)