-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
ty.rs
5349 lines (4726 loc) · 175 KB
/
ty.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.
#![allow(non_camel_case_types)]
use back::svh::Svh;
use driver::session::Session;
use lint;
use metadata::csearch;
use middle::const_eval;
use middle::def;
use middle::dependency_format;
use middle::freevars::CaptureModeMap;
use middle::freevars;
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
use middle::lang_items::{FnOnceTraitLangItem, OpaqueStructLangItem};
use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
use middle::mem_categorization as mc;
use middle::resolve;
use middle::resolve_lifetime;
use middle::stability;
use middle::subst::{Subst, Substs, VecPerParamSpace};
use middle::subst;
use middle::ty;
use middle::typeck;
use middle::typeck::MethodCall;
use middle::ty_fold;
use middle::ty_fold::{TypeFoldable,TypeFolder};
use middle;
use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
use util::ppaux::{trait_store_to_string, ty_to_string};
use util::ppaux::{Repr, UserString};
use util::common::{indenter};
use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap};
use std::cell::{Cell, RefCell};
use std::cmp;
use std::fmt::Show;
use std::fmt;
use std::hash::{Hash, sip, Writer};
use std::gc::Gc;
use std::iter::AdditiveIterator;
use std::mem;
use std::ops;
use std::rc::Rc;
use std::collections::{HashMap, HashSet};
use syntax::abi;
use syntax::ast::{CrateNum, DefId, FnStyle, Ident, ItemTrait, LOCAL_CRATE};
use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
use syntax::ast::{Visibility};
use syntax::ast_util::{PostExpansionMethod, is_local, lit_is_str};
use syntax::ast_util;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::parse::token::InternedString;
use syntax::{ast, ast_map};
use syntax::util::small_vector::SmallVector;
use std::collections::enum_set::{EnumSet, CLike};
pub type Disr = u64;
pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
// Data types
#[deriving(PartialEq, Eq, Hash)]
pub struct field {
pub ident: ast::Ident,
pub mt: mt
}
#[deriving(Clone)]
pub enum ImplOrTraitItemContainer {
TraitContainer(ast::DefId),
ImplContainer(ast::DefId),
}
impl ImplOrTraitItemContainer {
pub fn id(&self) -> ast::DefId {
match *self {
TraitContainer(id) => id,
ImplContainer(id) => id,
}
}
}
#[deriving(Clone)]
pub enum ImplOrTraitItem {
MethodTraitItem(Rc<Method>),
}
impl ImplOrTraitItem {
fn id(&self) -> ImplOrTraitItemId {
match *self {
MethodTraitItem(ref method) => MethodTraitItemId(method.def_id),
}
}
pub fn def_id(&self) -> ast::DefId {
match *self {
MethodTraitItem(ref method) => method.def_id,
}
}
pub fn ident(&self) -> ast::Ident {
match *self {
MethodTraitItem(ref method) => method.ident,
}
}
pub fn container(&self) -> ImplOrTraitItemContainer {
match *self {
MethodTraitItem(ref method) => method.container,
}
}
}
#[deriving(Clone)]
pub enum ImplOrTraitItemId {
MethodTraitItemId(ast::DefId),
}
impl ImplOrTraitItemId {
pub fn def_id(&self) -> ast::DefId {
match *self {
MethodTraitItemId(def_id) => def_id,
}
}
}
#[deriving(Clone)]
pub struct Method {
pub ident: ast::Ident,
pub generics: ty::Generics,
pub fty: BareFnTy,
pub explicit_self: ExplicitSelfCategory,
pub vis: ast::Visibility,
pub def_id: ast::DefId,
pub container: ImplOrTraitItemContainer,
// If this method is provided, we need to know where it came from
pub provided_source: Option<ast::DefId>
}
impl Method {
pub fn new(ident: ast::Ident,
generics: ty::Generics,
fty: BareFnTy,
explicit_self: ExplicitSelfCategory,
vis: ast::Visibility,
def_id: ast::DefId,
container: ImplOrTraitItemContainer,
provided_source: Option<ast::DefId>)
-> Method {
Method {
ident: ident,
generics: generics,
fty: fty,
explicit_self: explicit_self,
vis: vis,
def_id: def_id,
container: container,
provided_source: provided_source
}
}
pub fn container_id(&self) -> ast::DefId {
match self.container {
TraitContainer(id) => id,
ImplContainer(id) => id,
}
}
}
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub struct mt {
pub ty: t,
pub mutbl: ast::Mutability,
}
#[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
pub enum TraitStore {
/// Box<Trait>
UniqTraitStore,
/// &Trait and &mut Trait
RegionTraitStore(Region, ast::Mutability),
}
#[deriving(Clone, Show)]
pub struct field_ty {
pub name: Name,
pub id: DefId,
pub vis: ast::Visibility,
pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
}
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
#[deriving(PartialEq, Eq, Hash)]
pub struct creader_cache_key {
pub cnum: CrateNum,
pub pos: uint,
pub len: uint
}
pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>;
pub struct intern_key {
sty: *const sty,
}
// NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived
// implementation will not recurse through sty and you will get stack
// exhaustion.
impl cmp::PartialEq for intern_key {
fn eq(&self, other: &intern_key) -> bool {
unsafe {
*self.sty == *other.sty
}
}
fn ne(&self, other: &intern_key) -> bool {
!self.eq(other)
}
}
impl Eq for intern_key {}
impl<W:Writer> Hash<W> for intern_key {
fn hash(&self, s: &mut W) {
unsafe { (*self.sty).hash(s) }
}
}
pub enum ast_ty_to_ty_cache_entry {
atttce_unresolved, /* not resolved yet */
atttce_resolved(t) /* resolved to a type, irrespective of region */
}
#[deriving(Clone, PartialEq, Decodable, Encodable)]
pub struct ItemVariances {
pub types: VecPerParamSpace<Variance>,
pub regions: VecPerParamSpace<Variance>,
}
#[deriving(Clone, PartialEq, Decodable, Encodable, Show)]
pub enum Variance {
Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
Contravariant, // T<A> <: T<B> iff B <: A -- e.g., function param type
Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
}
#[deriving(Clone)]
pub enum AutoAdjustment {
AutoAddEnv(ty::TraitStore),
AutoDerefRef(AutoDerefRef)
}
#[deriving(Clone, PartialEq)]
pub enum UnsizeKind {
// [T, ..n] -> [T], the uint field is n.
UnsizeLength(uint),
// An unsize coercion applied to the tail field of a struct.
// The uint is the index of the type parameter which is unsized.
UnsizeStruct(Box<UnsizeKind>, uint),
UnsizeVtable(ty::BuiltinBounds,
ast::DefId, /* Trait ID */
subst::Substs /* Trait substitutions */)
}
#[deriving(Clone)]
pub struct AutoDerefRef {
pub autoderefs: uint,
pub autoref: Option<AutoRef>
}
#[deriving(Clone, PartialEq)]
pub enum AutoRef {
/// Convert from T to &T
/// The third field allows us to wrap other AutoRef adjustments.
AutoPtr(Region, ast::Mutability, Option<Box<AutoRef>>),
/// Convert [T, ..n] to [T] (or similar, depending on the kind)
AutoUnsize(UnsizeKind),
/// Convert Box<[T, ..n]> to Box<[T]> or something similar in a Box.
/// With DST and Box a library type, this should be replaced by UnsizeStruct.
AutoUnsizeUniq(UnsizeKind),
/// Convert from T to *T
/// Value to thin pointer
AutoUnsafe(ast::Mutability),
}
// Ugly little helper function. The first bool in the returned tuple is true if
// there is an 'unsize to trait object' adjustment at the bottom of the
// adjustment. If that is surrounded by an AutoPtr, then we also return the
// region of the AutoPtr (in the third argument). The second bool is true if the
// adjustment is unique.
fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option<Region>) {
fn unsize_kind_is_object(k: &UnsizeKind) -> bool {
match k {
&UnsizeVtable(..) => true,
&UnsizeStruct(box ref k, _) => unsize_kind_is_object(k),
_ => false
}
}
match autoref {
&AutoUnsize(ref k) => (unsize_kind_is_object(k), false, None),
&AutoUnsizeUniq(ref k) => (unsize_kind_is_object(k), true, None),
&AutoPtr(adj_r, _, Some(box ref autoref)) => {
let (b, u, r) = autoref_object_region(autoref);
if r.is_some() || u {
(b, u, r)
} else {
(b, u, Some(adj_r))
}
}
_ => (false, false, None)
}
}
// If the adjustment introduces a borrowed reference to a trait object, then
// returns the region of the borrowed reference.
pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option<Region> {
match adj {
&AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
let (b, _, r) = autoref_object_region(autoref);
if b {
r
} else {
None
}
}
_ => None
}
}
// Returns true if there is a trait cast at the bottom of the adjustment.
pub fn adjust_is_object(adj: &AutoAdjustment) -> bool {
match adj {
&AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
let (b, _, _) = autoref_object_region(autoref);
b
}
_ => false
}
}
// If possible, returns the type expected from the given adjustment. This is not
// possible if the adjustment depends on the type of the adjusted expression.
pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option<t> {
fn type_of_autoref(cx: &ctxt, autoref: &AutoRef) -> Option<t> {
match autoref {
&AutoUnsize(ref k) => match k {
&UnsizeVtable(bounds, def_id, ref substs) => {
Some(mk_trait(cx, def_id, substs.clone(), bounds))
}
_ => None
},
&AutoUnsizeUniq(ref k) => match k {
&UnsizeVtable(bounds, def_id, ref substs) => {
Some(mk_uniq(cx, mk_trait(cx, def_id, substs.clone(), bounds)))
}
_ => None
},
&AutoPtr(r, m, Some(box ref autoref)) => {
match type_of_autoref(cx, autoref) {
Some(t) => Some(mk_rptr(cx, r, mt {mutbl: m, ty: t})),
None => None
}
}
_ => None
}
}
match adj {
&AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => {
type_of_autoref(cx, autoref)
}
_ => None
}
}
/// A restriction that certain types must be the same size. The use of
/// `transmute` gives rise to these restrictions.
pub struct TransmuteRestriction {
/// The span from whence the restriction comes.
pub span: Span,
/// The type being transmuted from.
pub from: t,
/// The type being transmuted to.
pub to: t,
/// NodeIf of the transmute intrinsic.
pub id: ast::NodeId,
}
/// The data structure to keep track of all the information that typechecker
/// generates so that so that it can be reused and doesn't have to be redone
/// later on.
pub struct ctxt {
/// Specifically use a speedy hash algorithm for this hash map, it's used
/// quite often.
pub interner: RefCell<FnvHashMap<intern_key, Box<t_box_>>>,
pub next_id: Cell<uint>,
pub sess: Session,
pub def_map: resolve::DefMap,
pub named_region_map: resolve_lifetime::NamedRegionMap,
pub region_maps: middle::region::RegionMaps,
/// Stores the types for various nodes in the AST. Note that this table
/// is not guaranteed to be populated until after typeck. See
/// typeck::check::fn_ctxt for details.
pub node_types: node_type_table,
/// Stores the type parameters which were substituted to obtain the type
/// of this node. This only applies to nodes that refer to entities
/// parameterized by type parameters, such as generic fns, types, or
/// other items.
pub item_substs: RefCell<NodeMap<ItemSubsts>>,
/// Maps from a trait item to the trait item "descriptor"
pub impl_or_trait_items: RefCell<DefIdMap<ImplOrTraitItem>>,
/// Maps from a trait def-id to a list of the def-ids of its trait items
pub trait_item_def_ids: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItemId>>>>,
/// A cache for the trait_items() routine
pub trait_items_cache: RefCell<DefIdMap<Rc<Vec<ImplOrTraitItem>>>>,
pub impl_trait_cache: RefCell<DefIdMap<Option<Rc<ty::TraitRef>>>>,
pub trait_refs: RefCell<NodeMap<Rc<TraitRef>>>,
pub trait_defs: RefCell<DefIdMap<Rc<TraitDef>>>,
pub map: ast_map::Map,
pub intrinsic_defs: RefCell<DefIdMap<t>>,
pub freevars: RefCell<freevars::freevar_map>,
pub tcache: type_cache,
pub rcache: creader_cache,
pub short_names_cache: RefCell<HashMap<t, String>>,
pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo>>>>>,
pub ty_param_defs: RefCell<NodeMap<TypeParameterDef>>,
pub adjustments: RefCell<NodeMap<AutoAdjustment>>,
pub normalized_cache: RefCell<HashMap<t, t>>,
pub lang_items: middle::lang_items::LanguageItems,
/// A mapping of fake provided method def_ids to the default implementation
pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
pub supertraits: RefCell<DefIdMap<Rc<Vec<Rc<TraitRef>>>>>,
pub superstructs: RefCell<DefIdMap<Option<ast::DefId>>>,
pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
/// Maps from def-id of a type or region parameter to its
/// (inferred) variance.
pub item_variance_map: RefCell<DefIdMap<Rc<ItemVariances>>>,
/// True if the variance has been computed yet; false otherwise.
pub variance_computed: Cell<bool>,
/// A mapping from the def ID of an enum or struct type to the def ID
/// of the method that implements its destructor. If the type is not
/// present in this map, it does not have a destructor. This map is
/// populated during the coherence phase of typechecking.
pub destructor_for_type: RefCell<DefIdMap<ast::DefId>>,
/// A method will be in this list if and only if it is a destructor.
pub destructors: RefCell<DefIdSet>,
/// Maps a trait onto a list of impls of that trait.
pub trait_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
/// Maps a DefId of a type to a list of its inherent impls.
/// Contains implementations of methods that are inherent to a type.
/// Methods in these implementations don't need to be exported.
pub inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
/// Maps a DefId of an impl to a list of its items.
/// Note that this contains all of the impls that we know about,
/// including ones in other crates. It's not clear that this is the best
/// way to do it.
pub impl_items: RefCell<DefIdMap<Vec<ImplOrTraitItemId>>>,
/// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
/// present in this set can be warned about.
pub used_unsafe: RefCell<NodeSet>,
/// Set of nodes which mark locals as mutable which end up getting used at
/// some point. Local variable definitions not in this set can be warned
/// about.
pub used_mut_nodes: RefCell<NodeSet>,
/// vtable resolution information for impl declarations
pub impl_vtables: typeck::impl_vtable_map,
/// The set of external nominal types whose implementations have been read.
/// This is used for lazy resolution of methods.
pub populated_external_types: RefCell<DefIdSet>,
/// The set of external traits whose implementations have been read. This
/// is used for lazy resolution of traits.
pub populated_external_traits: RefCell<DefIdSet>,
/// Borrows
pub upvar_borrow_map: RefCell<UpvarBorrowMap>,
/// These two caches are used by const_eval when decoding external statics
/// and variants that are found.
pub extern_const_statics: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
pub extern_const_variants: RefCell<DefIdMap<Option<Gc<ast::Expr>>>>,
pub method_map: typeck::MethodMap,
pub vtable_map: typeck::vtable_map,
pub dependency_formats: RefCell<dependency_format::Dependencies>,
/// Records the type of each unboxed closure. The def ID is the ID of the
/// expression defining the unboxed closure.
pub unboxed_closures: RefCell<DefIdMap<UnboxedClosure>>,
pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
lint::LevelSource>>,
/// The types that must be asserted to be the same size for `transmute`
/// to be valid. We gather up these restrictions in the intrinsicck pass
/// and check them in trans.
pub transmute_restrictions: RefCell<Vec<TransmuteRestriction>>,
/// Maps any item's def-id to its stability index.
pub stability: RefCell<stability::Index>,
/// Maps closures to their capture clauses.
pub capture_modes: RefCell<CaptureModeMap>,
}
pub enum tbox_flag {
has_params = 1,
has_self = 2,
needs_infer = 4,
has_regions = 8,
has_ty_err = 16,
has_ty_bot = 32,
// a meta-pub flag: subst may be required if the type has parameters, a self
// type, or references bound regions
needs_subst = 1 | 2 | 8
}
pub type t_box = &'static t_box_;
#[deriving(Show)]
pub struct t_box_ {
pub sty: sty,
pub id: uint,
pub flags: uint,
}
// To reduce refcounting cost, we're representing types as unsafe pointers
// throughout the compiler. These are simply casted t_box values. Use ty::get
// to cast them back to a box. (Without the cast, compiler performance suffers
// ~15%.) This does mean that a t value relies on the ctxt to keep its box
// alive, and using ty::get is unsafe when the ctxt is no longer alive.
enum t_opaque {}
#[allow(raw_pointer_deriving)]
#[deriving(Clone, PartialEq, Eq, Hash)]
pub struct t { inner: *const t_opaque }
impl fmt::Show for t {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", get(*self))
}
}
pub fn get(t: t) -> t_box {
unsafe {
let t2: t_box = mem::transmute(t);
t2
}
}
pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
(tb.flags & (flag as uint)) != 0u
}
pub fn type_has_params(t: t) -> bool {
tbox_has_flag(get(t), has_params)
}
pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
pub fn type_needs_infer(t: t) -> bool {
tbox_has_flag(get(t), needs_infer)
}
pub fn type_id(t: t) -> uint { get(t).id }
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub struct BareFnTy {
pub fn_style: ast::FnStyle,
pub abi: abi::Abi,
pub sig: FnSig,
}
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub struct ClosureTy {
pub fn_style: ast::FnStyle,
pub onceness: ast::Onceness,
pub store: TraitStore,
pub bounds: BuiltinBounds,
pub sig: FnSig,
pub abi: abi::Abi,
}
/**
* Signature of a function type, which I have arbitrarily
* decided to use to refer to the input/output types.
*
* - `binder_id` is the node id where this fn type appeared;
* it is used to identify all the bound regions appearing
* in the input/output types that are bound by this fn type
* (vs some enclosing or enclosed fn type)
* - `inputs` is the list of arguments and their modes.
* - `output` is the return type.
* - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
*/
#[deriving(Clone, PartialEq, Eq, Hash)]
pub struct FnSig {
pub binder_id: ast::NodeId,
pub inputs: Vec<t>,
pub output: t,
pub variadic: bool
}
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub struct ParamTy {
pub space: subst::ParamSpace,
pub idx: uint,
pub def_id: DefId
}
/// Representation of regions:
#[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
pub enum Region {
// Region bound in a type or fn declaration which will be
// substituted 'early' -- that is, at the same time when type
// parameters are substituted.
ReEarlyBound(/* param id */ ast::NodeId,
subst::ParamSpace,
/*index*/ uint,
ast::Name),
// Region bound in a function scope, which will be substituted when the
// function is called. The first argument must be the `binder_id` of
// some enclosing function signature.
ReLateBound(/* binder_id */ ast::NodeId, BoundRegion),
/// When checking a function body, the types of all arguments and so forth
/// that refer to bound region parameters are modified to refer to free
/// region parameters.
ReFree(FreeRegion),
/// A concrete region naming some expression within the current function.
ReScope(NodeId),
/// Static data that has an "infinite" lifetime. Top in the region lattice.
ReStatic,
/// A region variable. Should not exist after typeck.
ReInfer(InferRegion),
/// Empty lifetime is for data that is never accessed.
/// Bottom in the region lattice. We treat ReEmpty somewhat
/// specially; at least right now, we do not generate instances of
/// it during the GLB computations, but rather
/// generate an error instead. This is to improve error messages.
/// The only way to get an instance of ReEmpty is to have a region
/// variable with no constraints.
ReEmpty,
}
/**
* Upvars do not get their own node-id. Instead, we use the pair of
* the original var id (that is, the root variable that is referenced
* by the upvar) and the id of the closure expression.
*/
#[deriving(Clone, PartialEq, Eq, Hash)]
pub struct UpvarId {
pub var_id: ast::NodeId,
pub closure_expr_id: ast::NodeId,
}
#[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)]
pub enum BorrowKind {
/// Data must be immutable and is aliasable.
ImmBorrow,
/// Data must be immutable but not aliasable. This kind of borrow
/// cannot currently be expressed by the user and is used only in
/// implicit closure bindings. It is needed when you the closure
/// is borrowing or mutating a mutable referent, e.g.:
///
/// let x: &mut int = ...;
/// let y = || *x += 5;
///
/// If we were to try to translate this closure into a more explicit
/// form, we'd encounter an error with the code as written:
///
/// struct Env { x: & &mut int }
/// let x: &mut int = ...;
/// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
///
/// This is then illegal because you cannot mutate a `&mut` found
/// in an aliasable location. To solve, you'd have to translate with
/// an `&mut` borrow:
///
/// struct Env { x: & &mut int }
/// let x: &mut int = ...;
/// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
///
/// Now the assignment to `**env.x` is legal, but creating a
/// mutable pointer to `x` is not because `x` is not mutable. We
/// could fix this by declaring `x` as `let mut x`. This is ok in
/// user code, if awkward, but extra weird for closures, since the
/// borrow is hidden.
///
/// So we introduce a "unique imm" borrow -- the referent is
/// immutable, but not aliasable. This solves the problem. For
/// simplicity, we don't give users the way to express this
/// borrow, it's just used when translating closures.
UniqueImmBorrow,
/// Data is mutable and not aliasable.
MutBorrow
}
/**
* Information describing the borrowing of an upvar. This is computed
* during `typeck`, specifically by `regionck`. The general idea is
* that the compiler analyses treat closures like:
*
* let closure: &'e fn() = || {
* x = 1; // upvar x is assigned to
* use(y); // upvar y is read
* foo(&z); // upvar z is borrowed immutably
* };
*
* as if they were "desugared" to something loosely like:
*
* struct Vars<'x,'y,'z> { x: &'x mut int,
* y: &'y const int,
* z: &'z int }
* let closure: &'e fn() = {
* fn f(env: &Vars) {
* *env.x = 1;
* use(*env.y);
* foo(env.z);
* }
* let env: &'e mut Vars<'x,'y,'z> = &mut Vars { x: &'x mut x,
* y: &'y const y,
* z: &'z z };
* (env, f)
* };
*
* This is basically what happens at runtime. The closure is basically
* an existentially quantified version of the `(env, f)` pair.
*
* This data structure indicates the region and mutability of a single
* one of the `x...z` borrows.
*
* It may not be obvious why each borrowed variable gets its own
* lifetime (in the desugared version of the example, these are indicated
* by the lifetime parameters `'x`, `'y`, and `'z` in the `Vars` definition).
* Each such lifetime must encompass the lifetime `'e` of the closure itself,
* but need not be identical to it. The reason that this makes sense:
*
* - Callers are only permitted to invoke the closure, and hence to
* use the pointers, within the lifetime `'e`, so clearly `'e` must
* be a sublifetime of `'x...'z`.
* - The closure creator knows which upvars were borrowed by the closure
* and thus `x...z` will be reserved for `'x...'z` respectively.
* - Through mutation, the borrowed upvars can actually escape
* the closure, so sometimes it is necessary for them to be larger
* than the closure lifetime itself.
*/
#[deriving(PartialEq, Clone, Encodable, Decodable)]
pub struct UpvarBorrow {
pub kind: BorrowKind,
pub region: ty::Region,
}
pub type UpvarBorrowMap = HashMap<UpvarId, UpvarBorrow>;
impl Region {
pub fn is_bound(&self) -> bool {
match self {
&ty::ReEarlyBound(..) => true,
&ty::ReLateBound(..) => true,
_ => false
}
}
}
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
pub struct FreeRegion {
pub scope_id: NodeId,
pub bound_region: BoundRegion
}
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Encodable, Decodable, Show)]
pub enum BoundRegion {
/// An anonymous region parameter for a given fn (&T)
BrAnon(uint),
/// Named region parameters for functions (a in &'a T)
///
/// The def-id is needed to distinguish free regions in
/// the event of shadowing.
BrNamed(ast::DefId, ast::Name),
/// Fresh bound identifiers created during GLB computations.
BrFresh(uint),
}
mod primitives {
use super::t_box_;
use syntax::ast;
macro_rules! def_prim_ty(
($name:ident, $sty:expr, $id:expr) => (
pub static $name: t_box_ = t_box_ {
sty: $sty,
id: $id,
flags: 0,
};
)
)
def_prim_ty!(TY_NIL, super::ty_nil, 0)
def_prim_ty!(TY_BOOL, super::ty_bool, 1)
def_prim_ty!(TY_CHAR, super::ty_char, 2)
def_prim_ty!(TY_INT, super::ty_int(ast::TyI), 3)
def_prim_ty!(TY_I8, super::ty_int(ast::TyI8), 4)
def_prim_ty!(TY_I16, super::ty_int(ast::TyI16), 5)
def_prim_ty!(TY_I32, super::ty_int(ast::TyI32), 6)
def_prim_ty!(TY_I64, super::ty_int(ast::TyI64), 7)
def_prim_ty!(TY_UINT, super::ty_uint(ast::TyU), 8)
def_prim_ty!(TY_U8, super::ty_uint(ast::TyU8), 9)
def_prim_ty!(TY_U16, super::ty_uint(ast::TyU16), 10)
def_prim_ty!(TY_U32, super::ty_uint(ast::TyU32), 11)
def_prim_ty!(TY_U64, super::ty_uint(ast::TyU64), 12)
def_prim_ty!(TY_F32, super::ty_float(ast::TyF32), 14)
def_prim_ty!(TY_F64, super::ty_float(ast::TyF64), 15)
pub static TY_BOT: t_box_ = t_box_ {
sty: super::ty_bot,
id: 16,
flags: super::has_ty_bot as uint,
};
pub static TY_ERR: t_box_ = t_box_ {
sty: super::ty_err,
id: 17,
flags: super::has_ty_err as uint,
};
pub static LAST_PRIMITIVE_ID: uint = 18;
}
// NB: If you change this, you'll probably want to change the corresponding
// AST structure in libsyntax/ast.rs as well.
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub enum sty {
ty_nil,
ty_bot,
ty_bool,
ty_char,
ty_int(ast::IntTy),
ty_uint(ast::UintTy),
ty_float(ast::FloatTy),
/// Substs here, possibly against intuition, *may* contain `ty_param`s.
/// That is, even after substitution it is possible that there are type
/// variables. This happens when the `ty_enum` corresponds to an enum
/// definition and not a concerete use of it. To get the correct `ty_enum`
/// from the tcx, use the `NodeId` from the `ast::Ty` and look it up in
/// the `ast_ty_to_ty_cache`. This is probably true for `ty_struct` as
/// well.`
ty_enum(DefId, Substs),
ty_box(t),
ty_uniq(t),
ty_str,
ty_vec(t, Option<uint>), // Second field is length.
ty_ptr(mt),
ty_rptr(Region, mt),
ty_bare_fn(BareFnTy),
ty_closure(Box<ClosureTy>),
ty_trait(Box<TyTrait>),
ty_struct(DefId, Substs),
ty_unboxed_closure(DefId, Region),
ty_tup(Vec<t>),
ty_param(ParamTy), // type parameter
ty_open(t), // A deref'ed fat pointer, i.e., a dynamically sized value
// and its size. Only ever used in trans. It is not necessary
// earlier since we don't need to distinguish a DST with its
// size (e.g., in a deref) vs a DST with the size elsewhere (
// e.g., in a field).
ty_infer(InferTy), // something used only during inference/typeck
ty_err, // Also only used during inference/typeck, to represent
// the type of an erroneous expression (helps cut down
// on non-useful type error messages)
}
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
pub struct TyTrait {
pub def_id: DefId,
pub substs: Substs,
pub bounds: BuiltinBounds
}
#[deriving(PartialEq, Eq, Hash, Show)]
pub struct TraitRef {
pub def_id: DefId,
pub substs: Substs,
}
#[deriving(Clone, PartialEq)]
pub enum IntVarValue {
IntType(ast::IntTy),
UintType(ast::UintTy),
}
#[deriving(Clone, Show)]
pub enum terr_vstore_kind {
terr_vec,
terr_str,
terr_fn,
terr_trait
}
#[deriving(Clone, Show)]
pub struct expected_found<T> {
pub expected: T,
pub found: T
}
// Data structures used in type unification
#[deriving(Clone, Show)]
pub enum type_err {
terr_mismatch,
terr_fn_style_mismatch(expected_found<FnStyle>),
terr_onceness_mismatch(expected_found<Onceness>),
terr_abi_mismatch(expected_found<abi::Abi>),
terr_mutability,
terr_sigil_mismatch(expected_found<TraitStore>),
terr_box_mutability,
terr_ptr_mutability,
terr_ref_mutability,
terr_vec_mutability,
terr_tuple_size(expected_found<uint>),
terr_ty_param_size(expected_found<uint>),
terr_record_size(expected_found<uint>),
terr_record_mutability,
terr_record_fields(expected_found<Ident>),
terr_arg_count,
terr_regions_does_not_outlive(Region, Region),
terr_regions_not_same(Region, Region),
terr_regions_no_overlap(Region, Region),
terr_regions_insufficiently_polymorphic(BoundRegion, Region),
terr_regions_overly_polymorphic(BoundRegion, Region),
terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
terr_sorts(expected_found<t>),
terr_integer_as_char,
terr_int_mismatch(expected_found<IntVarValue>),
terr_float_mismatch(expected_found<ast::FloatTy>),
terr_traits(expected_found<ast::DefId>),
terr_builtin_bounds(expected_found<BuiltinBounds>),
terr_variadic_mismatch(expected_found<bool>)
}
#[deriving(PartialEq, Eq, Hash, Show)]
pub struct ParamBounds {
pub builtin_bounds: BuiltinBounds,