-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathmem_categorization.rs
1550 lines (1412 loc) · 58.6 KB
/
mem_categorization.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # Categorization
//!
//! The job of the categorization module is to analyze an expression to
//! determine what kind of memory is used in evaluating it (for example,
//! where dereferences occur and what kind of pointer is dereferenced;
//! whether the memory is mutable; etc)
//!
//! Categorization effectively transforms all of our expressions into
//! expressions of the following forms (the actual enum has many more
//! possibilities, naturally, but they are all variants of these base
//! forms):
//!
//! E = rvalue // some computed rvalue
//! | x // address of a local variable or argument
//! | *E // deref of a ptr
//! | E.comp // access to an interior component
//!
//! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
//! address where the result is to be found. If Expr is a place, then this
//! is the address of the place. If Expr is an rvalue, this is the address of
//! some temporary spot in memory where the result is stored.
//!
//! Now, cat_expr() classifies the expression Expr and the address A=ToAddr(Expr)
//! as follows:
//!
//! - cat: what kind of expression was this? This is a subset of the
//! full expression forms which only includes those that we care about
//! for the purpose of the analysis.
//! - mutbl: mutability of the address A
//! - ty: the type of data found at the address A
//!
//! The resulting categorization tree differs somewhat from the expressions
//! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
//! decomposed into two operations: a dereference to reach the array data and
//! then an index to jump forward to the relevant item.
//!
//! ## By-reference upvars
//!
//! One part of the translation which may be non-obvious is that we translate
//! closure upvars into the dereference of a borrowed pointer; this more closely
//! resembles the runtime translation. So, for example, if we had:
//!
//! let mut x = 3;
//! let y = 5;
//! let inc = || x += y;
//!
//! Then when we categorize `x` (*within* the closure) we would yield a
//! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
//! tied to `x`. The type of `x'` will be a borrowed pointer.
#![allow(non_camel_case_types)]
pub use self::PointerKind::*;
pub use self::InteriorKind::*;
pub use self::FieldName::*;
pub use self::MutabilityCategory::*;
pub use self::AliasableReason::*;
pub use self::Note::*;
use self::Aliasability::*;
use middle::region;
use hir::def_id::{DefId, LocalDefId};
use hir::map as hir_map;
use infer::InferCtxt;
use hir::def::{Def, CtorKind};
use ty::adjustment;
use ty::{self, Ty, TyCtxt};
use ty::fold::TypeFoldable;
use hir::{MutImmutable, MutMutable, PatKind};
use hir::pat_util::EnumerateAndAdjustIterator;
use hir;
use syntax::ast;
use syntax_pos::Span;
use std::fmt;
use rustc_data_structures::sync::Lrc;
use std::rc::Rc;
use util::nodemap::ItemLocalSet;
#[derive(Clone, Debug, PartialEq)]
pub enum Categorization<'tcx> {
Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
StaticItem,
Upvar(Upvar), // upvar referenced by closure env
Local(ast::NodeId), // local variable
Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
// (*1) downcast is only required if the enum has more than one variant
}
// Represents any kind of upvar
#[derive(Clone, Copy, PartialEq)]
pub struct Upvar {
pub id: ty::UpvarId,
pub kind: ty::ClosureKind
}
// different kinds of pointers:
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PointerKind<'tcx> {
/// `Box<T>`
Unique,
/// `&T`
BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
/// `*T`
UnsafePtr(hir::Mutability),
/// Implicit deref of the `&T` that results from an overloaded index `[]`.
Implicit(ty::BorrowKind, ty::Region<'tcx>),
}
// We use the term "interior" to mean "something reachable from the
// base without a pointer dereference", e.g. a field
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum InteriorKind {
InteriorField(FieldName),
InteriorElement(InteriorOffsetKind),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum FieldName {
NamedField(ast::Name),
PositionalField(usize)
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum InteriorOffsetKind {
Index, // e.g. `array_expr[index_expr]`
Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum MutabilityCategory {
McImmutable, // Immutable.
McDeclared, // Directly declared as mutable.
McInherited, // Inherited from the fact that owner is mutable.
}
// A note about the provenance of a `cmt`. This is used for
// special-case handling of upvars such as mutability inference.
// Upvar categorization can generate a variable number of nested
// derefs. The note allows detecting them without deep pattern
// matching on the categorization.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Note {
NoteClosureEnv(ty::UpvarId), // Deref through closure env
NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
NoteNone // Nothing special
}
// `cmt`: "Category, Mutability, and Type".
//
// a complete categorization of a value indicating where it originated
// and how it is located, as well as the mutability of the memory in
// which the value is stored.
//
// *WARNING* The field `cmt.type` is NOT necessarily the same as the
// result of `node_id_to_type(cmt.id)`. This is because the `id` is
// always the `id` of the node producing the type; in an expression
// like `*x`, the type of this deref node is the deref'd type (`T`),
// but in a pattern like `@x`, the `@x` pattern is again a
// dereference, but its type is the type *before* the dereference
// (`@T`). So use `cmt.ty` to find the type of the value in a consistent
// fashion. For more details, see the method `cat_pattern`
#[derive(Clone, Debug, PartialEq)]
pub struct cmt_<'tcx> {
pub id: ast::NodeId, // id of expr/pat producing this value
pub span: Span, // span of same expr/pat
pub cat: Categorization<'tcx>, // categorization of expr
pub mutbl: MutabilityCategory, // mutability of expr as place
pub ty: Ty<'tcx>, // type of the expr (*see WARNING above*)
pub note: Note, // Note about the provenance of this cmt
}
pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
pub enum ImmutabilityBlame<'tcx> {
ImmLocal(ast::NodeId),
ClosureEnv(LocalDefId),
LocalDeref(ast::NodeId),
AdtFieldDeref(&'tcx ty::AdtDef, &'tcx ty::FieldDef)
}
impl<'tcx> cmt_<'tcx> {
fn resolve_field(&self, field_name: FieldName) -> Option<(&'tcx ty::AdtDef, &'tcx ty::FieldDef)>
{
let adt_def = match self.ty.sty {
ty::TyAdt(def, _) => def,
ty::TyTuple(..) => return None,
// closures get `Categorization::Upvar` rather than `Categorization::Interior`
_ => bug!("interior cmt {:?} is not an ADT", self)
};
let variant_def = match self.cat {
Categorization::Downcast(_, variant_did) => {
adt_def.variant_with_id(variant_did)
}
_ => {
assert_eq!(adt_def.variants.len(), 1);
&adt_def.variants[0]
}
};
let field_def = match field_name {
NamedField(name) => variant_def.field_named(name),
PositionalField(idx) => &variant_def.fields[idx]
};
Some((adt_def, field_def))
}
pub fn immutability_blame(&self) -> Option<ImmutabilityBlame<'tcx>> {
match self.cat {
Categorization::Deref(ref base_cmt, BorrowedPtr(ty::ImmBorrow, _)) |
Categorization::Deref(ref base_cmt, Implicit(ty::ImmBorrow, _)) => {
// try to figure out where the immutable reference came from
match base_cmt.cat {
Categorization::Local(node_id) =>
Some(ImmutabilityBlame::LocalDeref(node_id)),
Categorization::Interior(ref base_cmt, InteriorField(field_name)) => {
base_cmt.resolve_field(field_name).map(|(adt_def, field_def)| {
ImmutabilityBlame::AdtFieldDeref(adt_def, field_def)
})
}
Categorization::Upvar(Upvar { id, .. }) => {
if let NoteClosureEnv(..) = self.note {
Some(ImmutabilityBlame::ClosureEnv(id.closure_expr_id))
} else {
None
}
}
_ => None
}
}
Categorization::Local(node_id) => {
Some(ImmutabilityBlame::ImmLocal(node_id))
}
Categorization::Rvalue(..) |
Categorization::Upvar(..) |
Categorization::Deref(_, UnsafePtr(..)) => {
// This should not be reachable up to inference limitations.
None
}
Categorization::Interior(ref base_cmt, _) |
Categorization::Downcast(ref base_cmt, _) |
Categorization::Deref(ref base_cmt, _) => {
base_cmt.immutability_blame()
}
Categorization::StaticItem => {
// Do we want to do something here?
None
}
}
}
}
pub trait ast_node {
fn id(&self) -> ast::NodeId;
fn span(&self) -> Span;
}
impl ast_node for hir::Expr {
fn id(&self) -> ast::NodeId { self.id }
fn span(&self) -> Span { self.span }
}
impl ast_node for hir::Pat {
fn id(&self) -> ast::NodeId { self.id }
fn span(&self) -> Span { self.span }
}
#[derive(Clone)]
pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
pub region_scope_tree: &'a region::ScopeTree,
pub tables: &'a ty::TypeckTables<'tcx>,
rvalue_promotable_map: Option<Lrc<ItemLocalSet>>,
infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>,
}
pub type McResult<T> = Result<T, ()>;
impl MutabilityCategory {
pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
let ret = match m {
MutImmutable => McImmutable,
MutMutable => McDeclared
};
debug!("MutabilityCategory::{}({:?}) => {:?}",
"from_mutbl", m, ret);
ret
}
pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
let ret = match borrow_kind {
ty::ImmBorrow => McImmutable,
ty::UniqueImmBorrow => McImmutable,
ty::MutBorrow => McDeclared,
};
debug!("MutabilityCategory::{}({:?}) => {:?}",
"from_borrow_kind", borrow_kind, ret);
ret
}
fn from_pointer_kind(base_mutbl: MutabilityCategory,
ptr: PointerKind) -> MutabilityCategory {
let ret = match ptr {
Unique => {
base_mutbl.inherit()
}
BorrowedPtr(borrow_kind, _) | Implicit(borrow_kind, _) => {
MutabilityCategory::from_borrow_kind(borrow_kind)
}
UnsafePtr(m) => {
MutabilityCategory::from_mutbl(m)
}
};
debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
"from_pointer_kind", base_mutbl, ptr, ret);
ret
}
fn from_local(tcx: TyCtxt, tables: &ty::TypeckTables, id: ast::NodeId) -> MutabilityCategory {
let ret = match tcx.hir.get(id) {
hir_map::NodeBinding(p) => match p.node {
PatKind::Binding(..) => {
let bm = *tables.pat_binding_modes()
.get(p.hir_id)
.expect("missing binding mode");
if bm == ty::BindByValue(hir::MutMutable) {
McDeclared
} else {
McImmutable
}
}
_ => span_bug!(p.span, "expected identifier pattern")
},
_ => span_bug!(tcx.hir.span(id), "expected identifier pattern")
};
debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
"from_local", id, ret);
ret
}
pub fn inherit(&self) -> MutabilityCategory {
let ret = match *self {
McImmutable => McImmutable,
McDeclared => McInherited,
McInherited => McInherited,
};
debug!("{:?}.inherit() => {:?}", self, ret);
ret
}
pub fn is_mutable(&self) -> bool {
let ret = match *self {
McImmutable => false,
McInherited => true,
McDeclared => true,
};
debug!("{:?}.is_mutable() => {:?}", self, ret);
ret
}
pub fn is_immutable(&self) -> bool {
let ret = match *self {
McImmutable => true,
McDeclared | McInherited => false
};
debug!("{:?}.is_immutable() => {:?}", self, ret);
ret
}
pub fn to_user_str(&self) -> &'static str {
match *self {
McDeclared | McInherited => "mutable",
McImmutable => "immutable",
}
}
}
impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
region_scope_tree: &'a region::ScopeTree,
tables: &'a ty::TypeckTables<'tcx>,
rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
-> MemCategorizationContext<'a, 'tcx, 'tcx> {
MemCategorizationContext {
tcx,
region_scope_tree,
tables,
rvalue_promotable_map,
infcx: None
}
}
}
impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> {
/// Creates a `MemCategorizationContext` during type inference.
/// This is used during upvar analysis and a few other places.
/// Because the typeck tables are not yet complete, the results
/// from the analysis must be used with caution:
///
/// - rvalue promotions are not known, so the lifetimes of
/// temporaries may be overly conservative;
/// - similarly, as the results of upvar analysis are not yet
/// known, the results around upvar accesses may be incorrect.
pub fn with_infer(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
region_scope_tree: &'a region::ScopeTree,
tables: &'a ty::TypeckTables<'tcx>)
-> MemCategorizationContext<'a, 'gcx, 'tcx> {
let tcx = infcx.tcx;
// Subtle: we can't do rvalue promotion analysis until the
// typeck phase is complete, which means that you can't trust
// the rvalue lifetimes that result, but that's ok, since we
// don't need to know those during type inference.
let rvalue_promotable_map = None;
MemCategorizationContext {
tcx,
region_scope_tree,
tables,
rvalue_promotable_map,
infcx: Some(infcx),
}
}
pub fn type_moves_by_default(&self,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
span: Span)
-> bool {
self.infcx.map(|infcx| infcx.type_moves_by_default(param_env, ty, span))
.or_else(|| {
self.tcx.lift_to_global(&(param_env, ty)).map(|(param_env, ty)| {
ty.moves_by_default(self.tcx.global_tcx(), param_env, span)
})
})
.unwrap_or(true)
}
fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
where T: TypeFoldable<'tcx>
{
self.infcx.map(|infcx| infcx.resolve_type_vars_if_possible(value))
.unwrap_or_else(|| value.clone())
}
fn is_tainted_by_errors(&self) -> bool {
self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
}
fn resolve_type_vars_or_error(&self,
id: hir::HirId,
ty: Option<Ty<'tcx>>)
-> McResult<Ty<'tcx>> {
match ty {
Some(ty) => {
let ty = self.resolve_type_vars_if_possible(&ty);
if ty.references_error() || ty.is_ty_var() {
debug!("resolve_type_vars_or_error: error from {:?}", ty);
Err(())
} else {
Ok(ty)
}
}
// FIXME
None if self.is_tainted_by_errors() => Err(()),
None => {
let id = self.tcx.hir.definitions().find_node_for_hir_id(id);
bug!("no type for node {}: {} in mem_categorization",
id, self.tcx.hir.node_to_string(id));
}
}
}
pub fn node_ty(&self,
hir_id: hir::HirId)
-> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(hir_id,
self.tables.node_id_to_type_opt(hir_id))
}
pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
}
pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
}
fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
let base_ty = self.node_ty(pat.hir_id)?;
// This code detects whether we are looking at a `ref x`,
// and if so, figures out what the type *being borrowed* is.
let ret_ty = match pat.node {
PatKind::Binding(..) => {
let bm = *self.tables
.pat_binding_modes()
.get(pat.hir_id)
.expect("missing binding mode");
if let ty::BindByReference(_) = bm {
// a bind-by-ref means that the base_ty will be the type of the ident itself,
// but what we want here is the type of the underlying value being borrowed.
// So peel off one-level, turning the &T into T.
match base_ty.builtin_deref(false) {
Some(t) => t.ty,
None => {
debug!("By-ref binding of non-derefable type {:?}", base_ty);
return Err(());
}
}
} else {
base_ty
}
}
_ => base_ty,
};
debug!("pat_ty(pat={:?}) base_ty={:?} ret_ty={:?}",
pat, base_ty, ret_ty);
Ok(ret_ty)
}
pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
// This recursion helper avoids going through *too many*
// adjustments, since *only* non-overloaded deref recurses.
fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
expr: &hir::Expr,
adjustments: &[adjustment::Adjustment<'tcx>])
-> McResult<cmt<'tcx>> {
match adjustments.split_last() {
None => mc.cat_expr_unadjusted(expr),
Some((adjustment, previous)) => {
mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
}
}
}
helper(self, expr, self.tables.expr_adjustments(expr))
}
pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
previous: cmt<'tcx>,
adjustment: &adjustment::Adjustment<'tcx>)
-> McResult<cmt<'tcx>> {
self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
}
fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
previous: F,
adjustment: &adjustment::Adjustment<'tcx>)
-> McResult<cmt<'tcx>>
where F: FnOnce() -> McResult<cmt<'tcx>>
{
debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
let target = self.resolve_type_vars_if_possible(&adjustment.target);
match adjustment.kind {
adjustment::Adjust::Deref(overloaded) => {
// Equivalent to *expr or something similar.
let base = if let Some(deref) = overloaded {
let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
ty: target,
mutbl: deref.mutbl,
});
self.cat_rvalue_node(expr.id, expr.span, ref_ty)
} else {
previous()?
};
self.cat_deref(expr, base, false)
}
adjustment::Adjust::NeverToAny |
adjustment::Adjust::ReifyFnPointer |
adjustment::Adjust::UnsafeFnPointer |
adjustment::Adjust::ClosureFnPointer |
adjustment::Adjust::MutToConstPointer |
adjustment::Adjust::Borrow(_) |
adjustment::Adjust::Unsize => {
// Result is an rvalue.
Ok(self.cat_rvalue_node(expr.id, expr.span, target))
}
}
}
pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt<'tcx>> {
debug!("cat_expr: id={} expr={:?}", expr.id, expr);
let expr_ty = self.expr_ty(expr)?;
match expr.node {
hir::ExprUnary(hir::UnDeref, ref e_base) => {
if self.tables.is_method_call(expr) {
self.cat_overloaded_place(expr, e_base, false)
} else {
let base_cmt = self.cat_expr(&e_base)?;
self.cat_deref(expr, base_cmt, false)
}
}
hir::ExprField(ref base, f_name) => {
let base_cmt = self.cat_expr(&base)?;
debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
expr.id,
expr,
base_cmt);
Ok(self.cat_field(expr, base_cmt, f_name.node, expr_ty))
}
hir::ExprTupField(ref base, idx) => {
let base_cmt = self.cat_expr(&base)?;
Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty))
}
hir::ExprIndex(ref base, _) => {
if self.tables.is_method_call(expr) {
// If this is an index implemented by a method call, then it
// will include an implicit deref of the result.
// The call to index() returns a `&T` value, which
// is an rvalue. That is what we will be
// dereferencing.
self.cat_overloaded_place(expr, base, true)
} else {
let base_cmt = self.cat_expr(&base)?;
self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
}
}
hir::ExprPath(ref qpath) => {
let def = self.tables.qpath_def(qpath, expr.hir_id);
self.cat_def(expr.id, expr.span, expr_ty, def)
}
hir::ExprType(ref e, _) => {
self.cat_expr(&e)
}
hir::ExprAddrOf(..) | hir::ExprCall(..) |
hir::ExprAssign(..) | hir::ExprAssignOp(..) |
hir::ExprClosure(..) | hir::ExprRet(..) |
hir::ExprUnary(..) | hir::ExprYield(..) |
hir::ExprMethodCall(..) | hir::ExprCast(..) |
hir::ExprArray(..) | hir::ExprTup(..) | hir::ExprIf(..) |
hir::ExprBinary(..) | hir::ExprWhile(..) |
hir::ExprBlock(..) | hir::ExprLoop(..) | hir::ExprMatch(..) |
hir::ExprLit(..) | hir::ExprBreak(..) |
hir::ExprAgain(..) | hir::ExprStruct(..) | hir::ExprRepeat(..) |
hir::ExprInlineAsm(..) | hir::ExprBox(..) => {
Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty))
}
}
}
pub fn cat_def(&self,
id: ast::NodeId,
span: Span,
expr_ty: Ty<'tcx>,
def: Def)
-> McResult<cmt<'tcx>> {
debug!("cat_def: id={} expr={:?} def={:?}",
id, expr_ty, def);
match def {
Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) => {
Ok(self.cat_rvalue_node(id, span, expr_ty))
}
Def::Static(def_id, mutbl) => {
// `#[thread_local]` statics may not outlive the current function.
for attr in &self.tcx.get_attrs(def_id)[..] {
if attr.check_name("thread_local") {
return Ok(self.cat_rvalue_node(id, span, expr_ty));
}
}
Ok(Rc::new(cmt_ {
id:id,
span:span,
cat:Categorization::StaticItem,
mutbl: if mutbl { McDeclared } else { McImmutable},
ty:expr_ty,
note: NoteNone
}))
}
Def::Upvar(var_id, _, fn_node_id) => {
self.cat_upvar(id, span, var_id, fn_node_id)
}
Def::Local(vid) => {
Ok(Rc::new(cmt_ {
id,
span,
cat: Categorization::Local(vid),
mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
ty: expr_ty,
note: NoteNone
}))
}
def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
}
}
// Categorize an upvar, complete with invisible derefs of closure
// environment and upvar reference as appropriate.
fn cat_upvar(&self,
id: ast::NodeId,
span: Span,
var_id: ast::NodeId,
fn_node_id: ast::NodeId)
-> McResult<cmt<'tcx>>
{
let fn_hir_id = self.tcx.hir.node_to_hir_id(fn_node_id);
// An upvar can have up to 3 components. We translate first to a
// `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
// field from the environment.
//
// `Categorization::Upvar`. Next, we add a deref through the implicit
// environment pointer with an anonymous free region 'env and
// appropriate borrow kind for closure kinds that take self by
// reference. Finally, if the upvar was captured
// by-reference, we add a deref through that reference. The
// region of this reference is an inference variable 'up that
// was previously generated and recorded in the upvar borrow
// map. The borrow kind bk is inferred by based on how the
// upvar is used.
//
// This results in the following table for concrete closure
// types:
//
// | move | ref
// ---------------+----------------------+-------------------------------
// Fn | copied -> &'env | upvar -> &'env -> &'up bk
// FnMut | copied -> &'env mut | upvar -> &'env mut -> &'up bk
// FnOnce | copied | upvar -> &'up bk
let kind = match self.node_ty(fn_hir_id)?.sty {
ty::TyGenerator(..) => ty::ClosureKind::FnOnce,
ty::TyClosure(closure_def_id, closure_substs) => {
match self.infcx {
// During upvar inference we may not know the
// closure kind, just use the LATTICE_BOTTOM value.
Some(infcx) =>
infcx.closure_kind(closure_def_id, closure_substs)
.unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
None =>
self.tcx.global_tcx()
.lift(&closure_substs)
.expect("no inference cx, but inference variables in closure ty")
.closure_kind(closure_def_id, self.tcx.global_tcx()),
}
}
ref t => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", t),
};
let closure_expr_def_id = self.tcx.hir.local_def_id(fn_node_id);
let var_hir_id = self.tcx.hir.node_to_hir_id(var_id);
let upvar_id = ty::UpvarId {
var_id: var_hir_id,
closure_expr_id: closure_expr_def_id.to_local(),
};
let var_ty = self.node_ty(var_hir_id)?;
// Mutability of original variable itself
let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
// Construct the upvar. This represents access to the field
// from the environment (perhaps we should eventually desugar
// this field further, but it will do for now).
let cmt_result = cmt_ {
id,
span,
cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
mutbl: var_mutbl,
ty: var_ty,
note: NoteNone
};
// If this is a `FnMut` or `Fn` closure, then the above is
// conceptually a `&mut` or `&` reference, so we have to add a
// deref.
let cmt_result = match kind {
ty::ClosureKind::FnOnce => {
cmt_result
}
ty::ClosureKind::FnMut => {
self.env_deref(id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
}
ty::ClosureKind::Fn => {
self.env_deref(id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
}
};
// If this is a by-ref capture, then the upvar we loaded is
// actually a reference, so we have to add an implicit deref
// for that.
let upvar_capture = self.tables.upvar_capture(upvar_id);
let cmt_result = match upvar_capture {
ty::UpvarCapture::ByValue => {
cmt_result
}
ty::UpvarCapture::ByRef(upvar_borrow) => {
let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
cmt_ {
id,
span,
cat: Categorization::Deref(Rc::new(cmt_result), ptr),
mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
ty: var_ty,
note: NoteUpvarRef(upvar_id)
}
}
};
let ret = Rc::new(cmt_result);
debug!("cat_upvar ret={:?}", ret);
Ok(ret)
}
fn env_deref(&self,
id: ast::NodeId,
span: Span,
upvar_id: ty::UpvarId,
upvar_mutbl: MutabilityCategory,
env_borrow_kind: ty::BorrowKind,
cmt_result: cmt_<'tcx>)
-> cmt_<'tcx>
{
// Region of environment pointer
let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
// The environment of a closure is guaranteed to
// outlive any bindings introduced in the body of the
// closure itself.
scope: upvar_id.closure_expr_id.to_def_id(),
bound_region: ty::BrEnv
}));
let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
let var_ty = cmt_result.ty;
// We need to add the env deref. This means
// that the above is actually immutable and
// has a ref type. However, nothing should
// actually look at the type, so we can get
// away with stuffing a `TyError` in there
// instead of bothering to construct a proper
// one.
let cmt_result = cmt_ {
mutbl: McImmutable,
ty: self.tcx.types.err,
..cmt_result
};
let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
// Issue #18335. If variable is declared as immutable, override the
// mutability from the environment and substitute an `&T` anyway.
match upvar_mutbl {
McImmutable => { deref_mutbl = McImmutable; }
McDeclared | McInherited => { }
}
let ret = cmt_ {
id,
span,
cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
mutbl: deref_mutbl,
ty: var_ty,
note: NoteClosureEnv(upvar_id)
};
debug!("env_deref ret {:?}", ret);
ret
}
/// Returns the lifetime of a temporary created by expr with id `id`.
/// This could be `'static` if `id` is part of a constant expression.
pub fn temporary_scope(&self, id: hir::ItemLocalId) -> ty::Region<'tcx> {
let scope = self.region_scope_tree.temporary_scope(id);
self.tcx.mk_region(match scope {
Some(scope) => ty::ReScope(scope),
None => ty::ReStatic
})
}
pub fn cat_rvalue_node(&self,
id: ast::NodeId,
span: Span,
expr_ty: Ty<'tcx>)
-> cmt<'tcx> {
let hir_id = self.tcx.hir.node_to_hir_id(id);
let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
.unwrap_or(false);
// Always promote `[T; 0]` (even when e.g. borrowed mutably).
let promotable = match expr_ty.sty {
ty::TyArray(_, len) if len.val.to_raw_bits() == Some(0) => true,
_ => promotable,
};
// Compute maximum lifetime of this rvalue. This is 'static if
// we can promote to a constant, otherwise equal to enclosing temp
// lifetime.
let re = if promotable {
self.tcx.types.re_static
} else {
self.temporary_scope(hir_id.local_id)
};
let ret = self.cat_rvalue(id, span, re, expr_ty);
debug!("cat_rvalue_node ret {:?}", ret);
ret
}
pub fn cat_rvalue(&self,
cmt_id: ast::NodeId,
span: Span,
temp_scope: ty::Region<'tcx>,
expr_ty: Ty<'tcx>) -> cmt<'tcx> {
let ret = Rc::new(cmt_ {
id:cmt_id,
span:span,
cat:Categorization::Rvalue(temp_scope),
mutbl:McDeclared,
ty:expr_ty,
note: NoteNone
});
debug!("cat_rvalue ret {:?}", ret);
ret
}
pub fn cat_field<N:ast_node>(&self,
node: &N,
base_cmt: cmt<'tcx>,
f_name: ast::Name,
f_ty: Ty<'tcx>)
-> cmt<'tcx> {
let ret = Rc::new(cmt_ {
id: node.id(),
span: node.span(),
mutbl: base_cmt.mutbl.inherit(),
cat: Categorization::Interior(base_cmt, InteriorField(NamedField(f_name))),
ty: f_ty,
note: NoteNone
});
debug!("cat_field ret {:?}", ret);
ret
}
pub fn cat_tup_field<N:ast_node>(&self,
node: &N,
base_cmt: cmt<'tcx>,
f_idx: usize,
f_ty: Ty<'tcx>)
-> cmt<'tcx> {
let ret = Rc::new(cmt_ {
id: node.id(),
span: node.span(),
mutbl: base_cmt.mutbl.inherit(),
cat: Categorization::Interior(base_cmt, InteriorField(PositionalField(f_idx))),
ty: f_ty,
note: NoteNone
});
debug!("cat_tup_field ret {:?}", ret);
ret
}
fn cat_overloaded_place(&self,
expr: &hir::Expr,
base: &hir::Expr,
implicit: bool)
-> McResult<cmt<'tcx>> {
debug!("cat_overloaded_place: implicit={}", implicit);
// Reconstruct the output assuming it's a reference with the
// same region and mutability as the receiver. This holds for
// `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
let place_ty = self.expr_ty(expr)?;
let base_ty = self.expr_ty_adjusted(base)?;
let (region, mutbl) = match base_ty.sty {
ty::TyRef(region, mt) => (region, mt.mutbl),