/
ty.rs
4699 lines (4114 loc) · 147 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-2013 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.
use driver::session;
use metadata::csearch;
use metadata;
use middle::const_eval;
use middle::lang_items::{TyDescStructLangItem, TyVisitorTraitLangItem};
use middle::lang_items::OpaqueStructLangItem;
use middle::freevars;
use middle::resolve;
use middle::ty;
use middle::subst::Subst;
use middle::typeck;
use middle;
use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
use util::ppaux::{Repr, UserString};
use util::common::{indenter};
use std::cast;
use std::cmp;
use std::hashmap::{HashMap, HashSet};
use std::ops;
use std::ptr::to_unsafe_ptr;
use std::to_bytes;
use std::to_str::ToStr;
use std::vec;
use syntax::ast::*;
use syntax::ast_util::is_local;
use syntax::ast_util;
use syntax::attr;
use syntax::codemap::Span;
use syntax::codemap;
use syntax::parse::token;
use syntax::{ast, ast_map};
use syntax::opt_vec::OptVec;
use syntax::opt_vec;
use syntax::abi::AbiSet;
use syntax;
use extra::enum_set::{EnumSet, CLike};
pub type Disr = u64;
pub static INITIAL_DISCRIMINANT_VALUE: Disr = 0;
// Data types
#[deriving(Eq, IterBytes)]
pub struct field {
ident: ast::Ident,
mt: mt
}
#[deriving(Clone)]
pub enum MethodContainer {
TraitContainer(ast::DefId),
ImplContainer(ast::DefId),
}
#[deriving(Clone)]
pub struct Method {
ident: ast::Ident,
generics: ty::Generics,
transformed_self_ty: Option<ty::t>,
fty: BareFnTy,
explicit_self: ast::explicit_self_,
vis: ast::visibility,
def_id: ast::DefId,
container: MethodContainer,
// If this method is provided, we need to know where it came from
provided_source: Option<ast::DefId>
}
impl Method {
pub fn new(ident: ast::Ident,
generics: ty::Generics,
transformed_self_ty: Option<ty::t>,
fty: BareFnTy,
explicit_self: ast::explicit_self_,
vis: ast::visibility,
def_id: ast::DefId,
container: MethodContainer,
provided_source: Option<ast::DefId>)
-> Method {
// Check the invariants.
if explicit_self == ast::sty_static {
assert!(transformed_self_ty.is_none());
} else {
assert!(transformed_self_ty.is_some());
}
Method {
ident: ident,
generics: generics,
transformed_self_ty: transformed_self_ty,
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,
}
}
}
pub struct Impl {
did: DefId,
ident: Ident,
methods: ~[@Method]
}
#[deriving(Clone, Eq, IterBytes)]
pub struct mt {
ty: t,
mutbl: ast::Mutability,
}
#[deriving(Clone, Eq, Encodable, Decodable, IterBytes, ToStr)]
pub enum vstore {
vstore_fixed(uint),
vstore_uniq,
vstore_box,
vstore_slice(Region)
}
#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
pub enum TraitStore {
BoxTraitStore, // @Trait
UniqTraitStore, // ~Trait
RegionTraitStore(Region), // &Trait
}
// XXX: This should probably go away at some point. Maybe after destructors
// do?
#[deriving(Clone, Eq, Encodable, Decodable)]
pub enum SelfMode {
ByCopy,
ByRef,
}
pub struct field_ty {
name: Name,
id: DefId,
vis: ast::visibility,
}
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
#[deriving(Eq,IterBytes)]
pub struct creader_cache_key {
cnum: int,
pos: uint,
len: uint
}
type creader_cache = @mut HashMap<creader_cache_key, t>;
struct intern_key {
sty: *sty,
}
// NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
// implementation will not recurse through sty and you will get stack
// exhaustion.
impl cmp::Eq 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)
}
}
// NB: Do not replace this with #[deriving(IterBytes)], as above. (Figured
// this out the hard way.)
impl to_bytes::IterBytes for intern_key {
fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
unsafe {
(*self.sty).iter_bytes(lsb0, f)
}
}
}
pub enum ast_ty_to_ty_cache_entry {
atttce_unresolved, /* not resolved yet */
atttce_resolved(t) /* resolved to a type, irrespective of region */
}
pub type opt_region_variance = Option<region_variance>;
#[deriving(Clone, Eq, Decodable, Encodable)]
pub enum region_variance {
rv_covariant,
rv_invariant,
rv_contravariant,
}
#[deriving(Decodable, Encodable)]
pub enum AutoAdjustment {
AutoAddEnv(ty::Region, ast::Sigil),
AutoDerefRef(AutoDerefRef)
}
#[deriving(Decodable, Encodable)]
pub struct AutoDerefRef {
autoderefs: uint,
autoref: Option<AutoRef>
}
#[deriving(Decodable, Encodable)]
pub enum AutoRef {
/// Convert from T to &T
AutoPtr(Region, ast::Mutability),
/// Convert from @[]/~[]/&[] to &[] (or str)
AutoBorrowVec(Region, ast::Mutability),
/// Convert from @[]/~[]/&[] to &&[] (or str)
AutoBorrowVecRef(Region, ast::Mutability),
/// Convert from @fn()/~fn()/&fn() to &fn()
AutoBorrowFn(Region),
/// Convert from T to *T
AutoUnsafe(ast::Mutability),
/// Convert from @Trait/~Trait/&Trait to &Trait
AutoBorrowObj(Region, ast::Mutability),
}
pub type ctxt = @ctxt_;
struct ctxt_ {
diag: @mut syntax::diagnostic::span_handler,
interner: @mut HashMap<intern_key, ~t_box_>,
next_id: @mut uint,
cstore: @mut metadata::cstore::CStore,
sess: session::Session,
def_map: resolve::DefMap,
region_maps: @mut middle::region::RegionMaps,
region_paramd_items: middle::region::region_paramd_items,
// 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.
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.
node_type_substs: @mut HashMap<NodeId, ~[t]>,
// Maps from a method to the method "descriptor"
methods: @mut HashMap<DefId, @Method>,
// Maps from a trait def-id to a list of the def-ids of its methods
trait_method_def_ids: @mut HashMap<DefId, @~[DefId]>,
// A cache for the trait_methods() routine
trait_methods_cache: @mut HashMap<DefId, @~[@Method]>,
impl_trait_cache: @mut HashMap<ast::DefId, Option<@ty::TraitRef>>,
trait_refs: @mut HashMap<NodeId, @TraitRef>,
trait_defs: @mut HashMap<DefId, @TraitDef>,
items: ast_map::map,
intrinsic_defs: @mut HashMap<ast::DefId, t>,
freevars: freevars::freevar_map,
tcache: type_cache,
rcache: creader_cache,
short_names_cache: @mut HashMap<t, @str>,
needs_unwind_cleanup_cache: @mut HashMap<t, bool>,
tc_cache: @mut HashMap<uint, TypeContents>,
ast_ty_to_ty_cache: @mut HashMap<NodeId, ast_ty_to_ty_cache_entry>,
enum_var_cache: @mut HashMap<DefId, @~[@VariantInfo]>,
ty_param_defs: @mut HashMap<ast::NodeId, TypeParameterDef>,
adjustments: @mut HashMap<ast::NodeId, @AutoAdjustment>,
normalized_cache: @mut HashMap<t, t>,
lang_items: middle::lang_items::LanguageItems,
// A mapping of fake provided method def_ids to the default implementation
provided_method_sources: @mut HashMap<ast::DefId, ast::DefId>,
supertraits: @mut HashMap<ast::DefId, @~[@TraitRef]>,
// 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.
destructor_for_type: @mut HashMap<ast::DefId, ast::DefId>,
// A method will be in this list if and only if it is a destructor.
destructors: @mut HashSet<ast::DefId>,
// Maps a trait onto a list of impls of that trait.
trait_impls: @mut HashMap<ast::DefId, @mut ~[@Impl]>,
// Maps a def_id 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.
inherent_impls: @mut HashMap<ast::DefId, @mut ~[@Impl]>,
// Maps a def_id of an impl to an Impl structure.
// 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.
impls: @mut HashMap<ast::DefId, @Impl>,
// Set of used unsafe nodes (functions or blocks). Unsafe nodes not
// present in this set can be warned about.
used_unsafe: @mut HashSet<ast::NodeId>,
// 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.
used_mut_nodes: @mut HashSet<ast::NodeId>,
// vtable resolution information for impl declarations
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.
populated_external_types: @mut HashSet<ast::DefId>,
// The set of external traits whose implementations have been read. This
// is used for lazy resolution of traits.
populated_external_traits: @mut HashSet<ast::DefId>,
// These two caches are used by const_eval when decoding external statics
// and variants that are found.
extern_const_statics: @mut HashMap<ast::DefId, Option<@ast::Expr>>,
extern_const_variants: @mut HashMap<ast::DefId, Option<@ast::Expr>>,
}
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-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_;
pub struct t_box_ {
sty: sty,
id: uint,
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 {}
pub type t = *t_opaque;
impl ToStr for t {
fn to_str(&self) -> ~str {
~"*t_opaque"
}
}
pub fn get(t: t) -> t_box {
unsafe {
let t2: t_box = cast::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_has_regions(t: t) -> bool {
tbox_has_flag(get(t), has_regions)
}
pub fn type_id(t: t) -> uint { get(t).id }
#[deriving(Clone, Eq, IterBytes)]
pub struct BareFnTy {
purity: ast::purity,
abis: AbiSet,
sig: FnSig
}
#[deriving(Clone, Eq, IterBytes)]
pub struct ClosureTy {
purity: ast::purity,
sigil: ast::Sigil,
onceness: ast::Onceness,
region: Region,
bounds: BuiltinBounds,
sig: FnSig,
}
/**
* Signature of a function type, which I have arbitrarily
* decided to use to refer to the input/output types.
*
* - `lifetimes` is the list of region names bound in this fn.
* - `inputs` is the list of arguments and their modes.
* - `output` is the return type. */
#[deriving(Clone, Eq, IterBytes)]
pub struct FnSig {
bound_lifetime_names: OptVec<ast::Ident>,
inputs: ~[t],
output: t
}
#[deriving(Clone, Eq, IterBytes)]
pub struct param_ty {
idx: uint,
def_id: DefId
}
/// Representation of regions:
#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
pub enum Region {
/// Bound regions are found (primarily) in function types. They indicate
/// region parameters that have yet to be replaced with actual regions
/// (analogous to type parameters, except that due to the monomorphic
/// nature of our type system, bound type parameters are always replaced
/// with fresh type variables whenever an item is referenced, so type
/// parameters only appear "free" in types. Regions in contrast can
/// appear free or bound.). When a function is called, all bound regions
/// tied to that function's node-id are replaced with fresh region
/// variables whose value is then inferred.
re_bound(bound_region),
/// 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.
re_free(FreeRegion),
/// A concrete region naming some expression within the current function.
re_scope(NodeId),
/// Static data that has an "infinite" lifetime. Top in the region lattice.
re_static,
/// A region variable. Should not exist after typeck.
re_infer(InferRegion),
/// Empty lifetime is for data that is never accessed.
/// Bottom in the region lattice. We treat re_empty 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 re_empty is to have a region
/// variable with no constraints.
re_empty,
}
impl Region {
pub fn is_bound(&self) -> bool {
match self {
&re_bound(*) => true,
_ => false
}
}
}
#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
pub struct FreeRegion {
scope_id: NodeId,
bound_region: bound_region
}
#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
pub enum bound_region {
/// The self region for structs, impls (&T in a type defn or &'self T)
br_self,
/// An anonymous region parameter for a given fn (&T)
br_anon(uint),
/// Named region parameters for functions (a in &'a T)
br_named(ast::Ident),
/// Fresh bound identifiers created during GLB computations.
br_fresh(uint),
/**
* Handles capture-avoiding substitution in a rather subtle case. If you
* have a closure whose argument types are being inferred based on the
* expected type, and the expected type includes bound regions, then we
* will wrap those bound regions in a br_cap_avoid() with the id of the
* fn expression. This ensures that the names are not "captured" by the
* enclosing scope, which may define the same names. For an example of
* where this comes up, see src/test/compile-fail/regions-ret-borrowed.rs
* and regions-ret-borrowed-1.rs. */
br_cap_avoid(ast::NodeId, @bound_region),
}
/**
* Represents the values to use when substituting lifetime parameters.
* If the value is `ErasedRegions`, then this subst is occurring during
* trans, and all region parameters will be replaced with `ty::re_static`. */
#[deriving(Clone, Eq, IterBytes)]
pub enum RegionSubsts {
ErasedRegions,
NonerasedRegions(OptVec<ty::Region>)
}
/**
* The type substs represents the kinds of things that can be substituted to
* convert a polytype into a monotype. Note however that substituting bound
* regions other than `self` is done through a different mechanism:
*
* - `tps` represents the type parameters in scope. They are indexed
* according to the order in which they were declared.
*
* - `self_r` indicates the region parameter `self` that is present on nominal
* types (enums, structs) declared as having a region parameter. `self_r`
* should always be none for types that are not region-parameterized and
* Some(_) for types that are. The only bound region parameter that should
* appear within a region-parameterized type is `self`.
*
* - `self_ty` is the type to which `self` should be remapped, if any. The
* `self` type is rather funny in that it can only appear on traits and is
* always substituted away to the implementing type for a trait. */
#[deriving(Clone, Eq, IterBytes)]
pub struct substs {
self_ty: Option<ty::t>,
tps: ~[t],
regions: RegionSubsts,
}
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::ty_i), 3)
def_prim_ty!(TY_I8, super::ty_int(ast::ty_i8), 4)
def_prim_ty!(TY_I16, super::ty_int(ast::ty_i16), 5)
def_prim_ty!(TY_I32, super::ty_int(ast::ty_i32), 6)
def_prim_ty!(TY_I64, super::ty_int(ast::ty_i64), 7)
def_prim_ty!(TY_UINT, super::ty_uint(ast::ty_u), 8)
def_prim_ty!(TY_U8, super::ty_uint(ast::ty_u8), 9)
def_prim_ty!(TY_U16, super::ty_uint(ast::ty_u16), 10)
def_prim_ty!(TY_U32, super::ty_uint(ast::ty_u32), 11)
def_prim_ty!(TY_U64, super::ty_uint(ast::ty_u64), 12)
def_prim_ty!(TY_F32, super::ty_float(ast::ty_f32), 14)
def_prim_ty!(TY_F64, super::ty_float(ast::ty_f64), 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, Eq, IterBytes)]
pub enum sty {
ty_nil,
ty_bot,
ty_bool,
ty_char,
ty_int(ast::int_ty),
ty_uint(ast::uint_ty),
ty_float(ast::float_ty),
ty_estr(vstore),
ty_enum(DefId, substs),
ty_box(mt),
ty_uniq(mt),
ty_evec(mt, vstore),
ty_ptr(mt),
ty_rptr(Region, mt),
ty_bare_fn(BareFnTy),
ty_closure(ClosureTy),
ty_trait(DefId, substs, TraitStore, ast::Mutability, BuiltinBounds),
ty_struct(DefId, substs),
ty_tup(~[t]),
ty_param(param_ty), // type parameter
ty_self(DefId), /* special, implicit `self` type parameter;
* def_id is the id of the trait */
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)
// "Fake" types, used for trans purposes
ty_type, // type_desc*
ty_opaque_box, // used by monomorphizer to represent any @ box
ty_opaque_closure_ptr(Sigil), // ptr to env for &fn, @fn, ~fn
ty_unboxed_vec(mt),
}
#[deriving(Eq, IterBytes)]
pub struct TraitRef {
def_id: DefId,
substs: substs
}
#[deriving(Clone, Eq)]
pub enum IntVarValue {
IntType(ast::int_ty),
UintType(ast::uint_ty),
}
#[deriving(Clone, ToStr)]
pub enum terr_vstore_kind {
terr_vec,
terr_str,
terr_fn,
terr_trait
}
#[deriving(Clone, ToStr)]
pub struct expected_found<T> {
expected: T,
found: T
}
// Data structures used in type unification
#[deriving(Clone, ToStr)]
pub enum type_err {
terr_mismatch,
terr_purity_mismatch(expected_found<purity>),
terr_onceness_mismatch(expected_found<Onceness>),
terr_abi_mismatch(expected_found<AbiSet>),
terr_mutability,
terr_sigil_mismatch(expected_found<ast::Sigil>),
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(bound_region, Region),
terr_regions_overly_polymorphic(bound_region, Region),
terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
terr_in_field(@type_err, ast::Ident),
terr_sorts(expected_found<t>),
terr_integer_as_char,
terr_int_mismatch(expected_found<IntVarValue>),
terr_float_mismatch(expected_found<ast::float_ty>),
terr_traits(expected_found<ast::DefId>),
terr_builtin_bounds(expected_found<BuiltinBounds>),
}
#[deriving(Eq, IterBytes)]
pub struct ParamBounds {
builtin_bounds: BuiltinBounds,
trait_bounds: ~[@TraitRef]
}
pub type BuiltinBounds = EnumSet<BuiltinBound>;
#[deriving(Clone, Eq, IterBytes, ToStr)]
pub enum BuiltinBound {
BoundStatic,
BoundSend,
BoundFreeze,
BoundSized,
}
pub fn EmptyBuiltinBounds() -> BuiltinBounds {
EnumSet::empty()
}
pub fn AllBuiltinBounds() -> BuiltinBounds {
let mut set = EnumSet::empty();
set.add(BoundStatic);
set.add(BoundSend);
set.add(BoundFreeze);
set.add(BoundSized);
set
}
impl CLike for BuiltinBound {
fn to_uint(&self) -> uint {
*self as uint
}
fn from_uint(v: uint) -> BuiltinBound {
unsafe { cast::transmute(v) }
}
}
#[deriving(Clone, Eq, IterBytes)]
pub struct TyVid(uint);
#[deriving(Clone, Eq, IterBytes)]
pub struct IntVid(uint);
#[deriving(Clone, Eq, IterBytes)]
pub struct FloatVid(uint);
#[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
pub struct RegionVid {
id: uint
}
#[deriving(Clone, Eq, IterBytes)]
pub enum InferTy {
TyVar(TyVid),
IntVar(IntVid),
FloatVar(FloatVid)
}
#[deriving(Clone, Encodable, Decodable, IterBytes, ToStr)]
pub enum InferRegion {
ReVar(RegionVid),
ReSkolemized(uint, bound_region)
}
impl cmp::Eq for InferRegion {
fn eq(&self, other: &InferRegion) -> bool {
match ((*self), *other) {
(ReVar(rva), ReVar(rvb)) => {
rva == rvb
}
(ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
rva == rvb
}
_ => false
}
}
fn ne(&self, other: &InferRegion) -> bool {
!((*self) == (*other))
}
}
pub trait Vid {
fn to_uint(&self) -> uint;
}
impl Vid for TyVid {
fn to_uint(&self) -> uint { **self }
}
impl ToStr for TyVid {
fn to_str(&self) -> ~str { format!("<V{}>", self.to_uint()) }
}
impl Vid for IntVid {
fn to_uint(&self) -> uint { **self }
}
impl ToStr for IntVid {
fn to_str(&self) -> ~str { format!("<VI{}>", self.to_uint()) }
}
impl Vid for FloatVid {
fn to_uint(&self) -> uint { **self }
}
impl ToStr for FloatVid {
fn to_str(&self) -> ~str { format!("<VF{}>", self.to_uint()) }
}
impl Vid for RegionVid {
fn to_uint(&self) -> uint { self.id }
}
impl ToStr for RegionVid {
fn to_str(&self) -> ~str { format!("{:?}", self.id) }
}
impl ToStr for FnSig {
fn to_str(&self) -> ~str {
// grr, without tcx not much we can do.
return ~"(...)";
}
}
impl ToStr for InferTy {
fn to_str(&self) -> ~str {
match *self {
TyVar(ref v) => v.to_str(),
IntVar(ref v) => v.to_str(),
FloatVar(ref v) => v.to_str()
}
}
}
impl ToStr for IntVarValue {
fn to_str(&self) -> ~str {
match *self {
IntType(ref v) => v.to_str(),
UintType(ref v) => v.to_str(),
}
}
}
#[deriving(Clone)]
pub struct TypeParameterDef {
ident: ast::Ident,
def_id: ast::DefId,
bounds: @ParamBounds
}
/// Information about the type/lifetime parametesr associated with an item.
/// Analogous to ast::Generics.
#[deriving(Clone)]
pub struct Generics {
type_param_defs: @~[TypeParameterDef],
region_param: Option<region_variance>,
}
impl Generics {
pub fn has_type_params(&self) -> bool {
!self.type_param_defs.is_empty()
}
}
/// A polytype.
///
/// - `bounds`: The list of bounds for each type parameter. The length of the
/// list also tells you how many type parameters there are.
///
/// - `rp`: true if the type is region-parameterized. Types can have at
/// most one region parameter, always called `&self`.
///
/// - `ty`: the base type. May have reference to the (unsubstituted) bound
/// region `&self` or to (unsubstituted) ty_param types
#[deriving(Clone)]
pub struct ty_param_bounds_and_ty {
generics: Generics,
ty: t
}
/// As `ty_param_bounds_and_ty` but for a trait ref.
pub struct TraitDef {
generics: Generics,
bounds: BuiltinBounds,
trait_ref: @ty::TraitRef,
}
pub struct ty_param_substs_and_ty {
substs: ty::substs,
ty: ty::t
}
type type_cache = @mut HashMap<ast::DefId, ty_param_bounds_and_ty>;
pub type node_type_table = @mut HashMap<uint,t>;
fn mk_rcache() -> creader_cache {
return @mut HashMap::new();
}
pub fn new_ty_hash<V:'static>() -> @mut HashMap<t, V> {
@mut HashMap::new()
}
pub fn mk_ctxt(s: session::Session,
dm: resolve::DefMap,
amap: ast_map::map,
freevars: freevars::freevar_map,
region_maps: @mut middle::region::RegionMaps,
region_paramd_items: middle::region::region_paramd_items,
lang_items: middle::lang_items::LanguageItems)
-> ctxt {
@ctxt_ {
diag: s.diagnostic(),
interner: @mut HashMap::new(),
next_id: @mut primitives::LAST_PRIMITIVE_ID,
cstore: s.cstore,
sess: s,
def_map: dm,
region_maps: region_maps,
region_paramd_items: region_paramd_items,
node_types: @mut HashMap::new(),
node_type_substs: @mut HashMap::new(),
trait_refs: @mut HashMap::new(),
trait_defs: @mut HashMap::new(),
items: amap,
intrinsic_defs: @mut HashMap::new(),
freevars: freevars,
tcache: @mut HashMap::new(),
rcache: mk_rcache(),
short_names_cache: new_ty_hash(),
needs_unwind_cleanup_cache: new_ty_hash(),
tc_cache: @mut HashMap::new(),
ast_ty_to_ty_cache: @mut HashMap::new(),
enum_var_cache: @mut HashMap::new(),
methods: @mut HashMap::new(),
trait_method_def_ids: @mut HashMap::new(),
trait_methods_cache: @mut HashMap::new(),
impl_trait_cache: @mut HashMap::new(),
ty_param_defs: @mut HashMap::new(),
adjustments: @mut HashMap::new(),
normalized_cache: new_ty_hash(),
lang_items: lang_items,
provided_method_sources: @mut HashMap::new(),
supertraits: @mut HashMap::new(),
destructor_for_type: @mut HashMap::new(),
destructors: @mut HashSet::new(),
trait_impls: @mut HashMap::new(),
inherent_impls: @mut HashMap::new(),
impls: @mut HashMap::new(),
used_unsafe: @mut HashSet::new(),
used_mut_nodes: @mut HashSet::new(),
impl_vtables: @mut HashMap::new(),
populated_external_types: @mut HashSet::new(),
populated_external_traits: @mut HashSet::new(),
extern_const_statics: @mut HashMap::new(),
extern_const_variants: @mut HashMap::new(),
}
}
// Type constructors
// Interns a type/name combination, stores the resulting box in cx.interner,
// and returns the box as cast to an unsafe ptr (see comments for t above).
fn mk_t(cx: ctxt, st: sty) -> t {
// Check for primitive types.
match st {
ty_nil => return mk_nil(),
ty_err => return mk_err(),
ty_bool => return mk_bool(),
ty_int(i) => return mk_mach_int(i),
ty_uint(u) => return mk_mach_uint(u),
ty_float(f) => return mk_mach_float(f),
_ => {}
};
let key = intern_key { sty: to_unsafe_ptr(&st) };
match cx.interner.find(&key) {
Some(t) => unsafe { return cast::transmute(&t.sty); },
_ => ()
}
let mut flags = 0u;
fn rflags(r: Region) -> uint {
(has_regions as uint) | {
match r {
ty::re_infer(_) => needs_infer as uint,
_ => 0u
}
}